diff --git a/.github/allowed-hosts.json b/.github/allowed-hosts.json index 385df90..2258e83 100644 --- a/.github/allowed-hosts.json +++ b/.github/allowed-hosts.json @@ -3,6 +3,7 @@ "ajcontent.akamaized.net", "burrow.moe", "cdn.jsdelivr.net", + "discord.com", "challenges.cloudflare.com", "play.burrow.moe", "vision.googleapis.com", diff --git a/config.js b/config.js index 9768f79..2ee6633 100644 --- a/config.js +++ b/config.js @@ -108,12 +108,23 @@ module.exports = { // emoji pictures for chat (lib/emoji.js): Twemoji's, at one version emojiUpstream: env.AJ_EMOJI_UPSTREAM || "https://cdn.jsdelivr.net/gh/jdecked/twemoji@15.1.0/assets/72x72/", offline: env.AJ_OFFLINE === "1", - // the client's device ids (lib/devices.js): with AJ_REQUIRE_DEVICE=1, a - // sign-in without them (a client from before 1.3.0, the official - // launcher, or one that left them out) is refused. off for now, while - // players update to 1.3.0: they are let in, and an account seen on banned - // hardware before is still kept out. - requireDevice: env.AJ_REQUIRE_DEVICE === "1", + // the client's device ids (lib/devices.js): a game whose launcher sent none + // (a client from before 1.3.0, the official launcher, or one that left + // them out) is turned away at its login, its popup saying to update. + // AJ_REQUIRE_DEVICE=0 lets them in (an account seen on banned hardware + // before is still kept out). + requireDevice: env.AJ_REQUIRE_DEVICE !== "0", + // Discord (lib/discord.js): an application's id and secret for linking a + // player's Discord account on the account page (its OAuth2 redirect must + // be account/discord/callback), and a bot in Burrow's Discord + // server for the booster badge. linking is off without the first two, the + // booster badge left alone without the last two. + discord: { + clientId: env.AJ_DISCORD_CLIENT_ID || "", + clientSecret: env.AJ_DISCORD_CLIENT_SECRET || "", + botToken: env.AJ_DISCORD_BOT_TOKEN || "", + guildId: env.AJ_DISCORD_GUILD_ID || "", + }, deployVersion: env.AJ_DEPLOY_VERSION || "1830", // older builds the CDN still serves, asked in turn for a room file the // current build has dropped. 1828 is the last with the Summer Carnival. @@ -134,7 +145,7 @@ module.exports = { // 49 and 50: its link to a colour picker. // 61: the Owner, Moderator and Verified name tag badges seen by everyone. // 62: "Custom pictures" in the settings menu, to hide players' item pictures. - buildVersion: env.AJ_BUILD_VERSION || "62", + buildVersion: env.AJ_BUILD_VERSION || "71", // what the official CDN is asked for; not ours to change. upstreamBuildVersion: "3", diff --git a/lib/accounts.js b/lib/accounts.js index c9c370d..9a08ea6 100644 --- a/lib/accounts.js +++ b/lib/accounts.js @@ -245,7 +245,10 @@ const normalize = account => { account.nameBarData = Number.isInteger(account.nameBarData) ? account.nameBarData : 0; account.disguise = Number.isInteger(account.disguise) ? account.disguise : 0; // NPC id, see lib/disguises.js // shown on the player's card: lib/badges.js. - account.discord = typeof account.discord === "string" ? account.discord : ""; // their Discord username, as they gave it + account.discord = typeof account.discord === "string" ? account.discord : ""; // their Discord username, as Discord gave it (lib/discord.js) + if (account.discordId !== undefined && !/^\d{5,25}$/.test(String(account.discordId))) { + delete account.discordId; // the linked Discord account's id + } account.badges = Array.isArray(account.badges) ? account.badges : []; // badge ids, given in the admin panel account.bio = typeof account.bio === "string" ? account.bio : ""; // their own words, for the card's Bio tab // seconds spent in the game in all (lib/world.js counts it), and whether @@ -905,10 +908,17 @@ const byToken = token => { const byName = username => touch(byKey.get(String(username).toLowerCase())) || null; +// a username as its account spells it, or null. only asks whether there is +// one: unlike byName it does not count as the account being in use. +const nameOf = username => { + const account = byKey.get(String(username).toLowerCase()); + return account ? account.username : null; +}; + const accountById = id => touch(byId.get(Number(id))) || null; const all = () => [...byId.values()]; const database = () => db; -module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, hold, release, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, byId: accountById, newAvatar, freeAvatarSlot, all}; +module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, hold, release, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, nameOf, byId: accountById, newAvatar, freeAvatarSlot, all}; diff --git a/lib/admin.js b/lib/admin.js index ad4c6f6..0a4d479 100644 --- a/lib/admin.js +++ b/lib/admin.js @@ -110,6 +110,12 @@ const give = (body, seesLocked = false) => { } custom = String(entry.id); } + // a colour id written signed, as lists of the game's colours often do + // them: the same 32 bits, kept as the game keeps colours (unsigned), so + // -16777216 is 4278190080. + if (/^-\d{1,10}$/.test(custom) && Number(custom) >= -0x80000000) { + custom = String(Number(custom) >>> 0); + } if (custom && !isUint(custom)) { return {status: 400, body: {error: "Colour: an id, or #RRGGBB"}}; } diff --git a/lib/badges.js b/lib/badges.js index 438fbe6..9c85608 100644 --- a/lib/badges.js +++ b/lib/badges.js @@ -65,7 +65,7 @@ const set = (account, ids) => { }; // A Discord username as Discord has them now: 2 to 32 of a-z, 0-9, "_" and -// ".", with no two dots in a row. nobody checks that it is theirs. +// ".", with no two dots in a row. players link theirs (lib/discord.js). const DISCORD_NAME = /^(?!.*\.\.)[a-z0-9_.]{2,32}$/; // returns the username as it will be kept ("" for none), or null when it diff --git a/lib/defpacks.js b/lib/defpacks.js index d251284..2376fc3 100644 --- a/lib/defpacks.js +++ b/lib/defpacks.js @@ -144,6 +144,9 @@ const withRestoredParties = pack => { // text of our own, for things the game has no string for. added to the // English localization pack under ids far above the game's (about 41,000). const ADDED_STRINGS = { + // the login popup for a launcher too old to send device ids (lib/world.js + // LOGIN_OUTDATED), in place of "Your account is currently under maintenance." + 11198: "Your client is outdated. Update at https://burrow.moe/download", 9000001: "Castle (2010 draft)", 9000002: "Water Park (three slides)", 9000003: "Water Park (five slides)", diff --git a/lib/devices.js b/lib/devices.js index 20d48ca..d6eebea 100644 --- a/lib/devices.js +++ b/lib/devices.js @@ -397,4 +397,25 @@ const forget = account => { db().prepare("DELETE FROM device_alerts WHERE account_id = ?").run(account.id); }; -module.exports = {load, read, banOf, banOfAccount, seen, alts, knownFor, banAccount, accountsUnder, unban, list, idsFor, bansOfAccount, search, bannedId, alerts, alertsOf, forget, clientHash}; +// sign-in tokens last given to (or brought back by) a launcher that sent no +// device ids: one from before 1.3.0, or not ours. with config.requireDevice +// its sign-in still goes through, so that the game loads and its own login +// popup can say to update (lib/world.js), which a refused sign-in cannot. +// kept by hash, in memory: such a launcher signs in again each time it starts. +const MAX_OUTDATED = 20000; +const outdatedTokens = new Set(); +const tokenKey = token => crypto.createHash("sha256").update(String(token)).digest("hex"); +const noteLauncher = (token, hasIds) => { + const key = tokenKey(token); + if (hasIds) { + outdatedTokens.delete(key); + return; + } + if (outdatedTokens.size >= MAX_OUTDATED) { + outdatedTokens.delete(outdatedTokens.values().next().value); + } + outdatedTokens.add(key); +}; +const launcherOutdated = token => outdatedTokens.has(tokenKey(token)); + +module.exports = {noteLauncher, launcherOutdated, load, read, banOf, banOfAccount, seen, alts, knownFor, banAccount, accountsUnder, unban, list, idsFor, bansOfAccount, search, bannedId, alerts, alertsOf, forget, clientHash}; diff --git a/lib/discord.js b/lib/discord.js new file mode 100644 index 0000000..579a0b3 --- /dev/null +++ b/lib/discord.js @@ -0,0 +1,205 @@ +"use strict"; + +const crypto = require("crypto"); +const {logText} = require("./logtext.js"); +const accounts = require("./accounts.js"); +const badges = require("./badges.js"); +const config = require("../config.js"); + +// a player's Discord account, linked on the account page by signing in to +// Discord (OAuth2, scope "identify"): the only way a Discord username gets +// onto a player's card, so the name shown is theirs. one Discord account +// for one Burrow account, or a single boost would badge a player's every +// account. +// +// the Discord Server Booster badge follows the linked account: given while +// it boosts Burrow's Discord server, taken off when it stops, checked when +// the account is linked and again every RECHECK_HOURS. Burrow's bot asks +// Discord (GET /guilds//members/, which needs no privileged +// intent: the bot only has to be in the server). an account that is not +// linked keeps whatever badges the admin gave it. +// +// with AJ_DISCORD_CLIENT_ID and AJ_DISCORD_CLIENT_SECRET unset, linking is +// off; without AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, the booster +// badge is left alone. + +const API = "https://discord.com/api/v10"; +const AUTHORIZE = "https://discord.com/oauth2/authorize"; +const STATE_MINUTES = 10; +const MAX_STATES = 10000; +const RECHECK_HOURS = 6; +const RECHECK_GAP_MS = 300; // between two members asked about, under Discord's rate limit +const TIMEOUT_MS = 15000; +const BOOSTER = "booster"; + +const linking = () => Boolean(config.discord.clientId && config.discord.clientSecret); +const boostChecks = () => Boolean(config.discord.botToken && config.discord.guildId); +const redirectUri = () => `${config.siteUrl}account/discord/callback`; + +// a link under way: state (in Discord's address) -> {accountId, nonce (in a +// cookie of the browser that asked), expires}. both must come back. +const states = new Map(); + +const start = account => { + for (const [state, entry] of states) { + if (entry.expires < Date.now()) { + states.delete(state); + } + } + if (states.size >= MAX_STATES) { + states.delete(states.keys().next().value); + } + const state = crypto.randomBytes(24).toString("hex"); + const nonce = crypto.randomBytes(24).toString("hex"); + states.set(state, {accountId: account.id, nonce, expires: Date.now() + STATE_MINUTES * 60000}); + const url = new URL(AUTHORIZE); + url.search = new URLSearchParams({client_id: config.discord.clientId, response_type: "code", scope: "identify", + redirect_uri: redirectUri(), state, prompt: "consent"}).toString(); + return {url: url.href, nonce}; +}; + +const call = async (path, options = {}) => { + const res = await fetch(`${API}${path}`, {...options, signal: AbortSignal.timeout(TIMEOUT_MS)}); + const body = await res.json().catch(() => ({})); + return {status: res.status, body}; +}; + +// how a Discord username is kept and shown: as Discord spells them now, or, +// for an old "name#1234" one, without the characters a card cannot carry. +const shownName = user => badges.discordName(user.username) + || `${String(user.username).replace(/[,|%\s]/g, "")}${user.discriminator && user.discriminator !== "0" ? `#${user.discriminator}` : ""}`.slice(0, 40); + +const setBooster = (account, on) => { + if (account.badges.includes(BOOSTER) === on) { + return false; + } + badges.set(account, on ? [...account.badges, BOOSTER] : account.badges.filter(id => id !== BOOSTER)); + return true; +}; + +// whether the linked account boosts the server now: true, false, or null +// when Discord could not be asked. +const boosting = async account => { + if (!boostChecks() || !account.discordId) { + return null; + } + for (let attempt = 0; attempt < 3; attempt++) { + const {status, body} = await call(`/guilds/${config.discord.guildId}/members/${account.discordId}`, + {headers: {Authorization: `Bot ${config.discord.botToken}`}}).catch(() => ({status: 0, body: {}})); + if (status === 200) { + return Boolean(body.premium_since); + } + if (status === 404) { + return false; // not in the server (any more) + } + if (status === 429) { + await new Promise(resolve => setTimeout(resolve, Math.min(60, Number(body.retry_after) || 5) * 1000)); + continue; + } + console.log(`[discord] could not check ${logText(account.username)}'s boost: ${logText(status)}`); + return null; + } + return null; +}; + +const checkBoost = async account => { + const on = await boosting(account); + if (on !== null && setBooster(account, on)) { + accounts.save(account); + console.log(`[discord] ${logText(account.username)} ${on ? "boosts: booster badge given" : "no longer boosts: booster badge taken off"}`); + } +}; + +// the end of a link: the code Discord gave, for the state and the nonce the +// browser brought back. {ok, account} or {error}. +const finish = async (state, nonce, code) => { + const entry = typeof state === "string" ? states.get(state) : null; + states.delete(state); + const digest = text => crypto.createHash("sha256").update(String(text)).digest(); + if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce))) { + return {error: "expired"}; + } + const account = accounts.byId(entry.accountId); + if (!account || typeof code !== "string" || !code) { + return {error: "expired"}; + } + try { + const token = await call("/oauth2/token", { + method: "POST", + headers: {"Content-Type": "application/x-www-form-urlencoded"}, + body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret, + grant_type: "authorization_code", code, redirect_uri: redirectUri()}).toString(), + }); + if (token.status !== 200 || !token.body.access_token) { + return {error: "discord"}; + } + const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}}); + if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) { + return {error: "discord"}; + } + const id = String(me.body.id); + if (accounts.all().some(other => other !== account && other.discordId === id)) { + return {error: "taken"}; + } + account.discordId = id; + account.discord = shownName(me.body); + accounts.save(account); + console.log(`[discord] ${logText(account.username)} linked Discord ${logText(account.discord)} (${logText(id)})`); + await checkBoost(account); + return {ok: true, account}; + } + catch (err) { + console.log(`[discord] link failed: ${logText(err.message)}`); + return {error: "discord"}; + } +}; + +// the link undone, by the player or an admin; the booster badge goes with it. +const unlink = account => { + const had = Boolean(account.discordId || account.discord); + delete account.discordId; + account.discord = ""; + if (had) { + setBooster(account, false); + } + accounts.save(account); + return had; +}; + +// every linked account in turn, a little apart, again and again. +let rechecking = false; +const recheckAll = async () => { + if (rechecking || !boostChecks()) { + return; + } + rechecking = true; + try { + for (const account of accounts.all().filter(one => one.discordId)) { + await checkBoost(account); + await new Promise(resolve => setTimeout(resolve, RECHECK_GAP_MS)); + } + } + finally { + rechecking = false; + } +}; + +// at start: Discord usernames typed in by hand before linking existed are +// cleared (only a linked one is shown now), then the boosts are looked at +// and looked at again every RECHECK_HOURS. +const startup = () => { + const typed = accounts.all().filter(account => account.discord && !account.discordId); + for (const account of typed) { + account.discord = ""; + } + if (typed.length) { + accounts.save(...typed); + console.log(`[discord] ${typed.length} Discord usernames typed in by hand were cleared`); + } + if (boostChecks()) { + setTimeout(recheckAll, 30000).unref(); + setInterval(recheckAll, RECHECK_HOURS * 3600000).unref(); + } +}; + +module.exports = {linking, boostChecks, start, finish, unlink, startup}; diff --git a/lib/http.js b/lib/http.js index b8022fc..a23218e 100644 --- a/lib/http.js +++ b/lib/http.js @@ -73,6 +73,10 @@ const flashVars = () => ({ startupRoom: config.startupRoom, // "-1" turns the client's stats socket off. sbStatTrackerIp: "-1", + // the client's Discord rich presence (its app/discord.js): the Discord + // application it shows as, "" for none, and where its button goes. + discordAppId: config.discord.clientId, + presenceUrl: `${config.siteUrl}download`, sbStatModulator: "0", currentTimestamp: Math.floor(Date.now() / 1000), country: "US", @@ -469,6 +473,7 @@ const renameAndSignIn = (res, body, from) => { console.log(`[accounts] a rejected username was replaced by "${logText(account.username)}"`); accounts.setLoginChoices(account, body.login_choices); const token = accounts.issueToken(account); + devices.noteLauncher(token, Boolean(devices.read(body.device))); send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken}); }; @@ -479,13 +484,11 @@ const authenticate = async (req, res, from) => { return; } // the computer it is on (lib/devices.js): a client that does not say is - // out of date (before 1.3.0) or not ours. 1.2 shows "The server refused - // the login (426)", and still offers its update. + // out of date (before 1.3.0) or not ours. it is signed in all the same, + // and its token noted (signInChecked): with config.requireDevice the game + // then loads and its login popup says to update (lib/world.js), where a + // refusal here only ever showed "The server refused the login (426)". const device = devices.read(body.device); - if (!device && config.requireDevice) { - send(res, 426, {error_code: 101, error: "client_outdated"}); - return; - } const accountKey = String(body.username).trim().toLowerCase(); if (!from.local && failuresByAddress.blocked(from.key)) { send(res, 429, {error_code: 429, error: "too_many_attempts"}); @@ -609,6 +612,7 @@ const signInChecked = async (res, body, from, account, saved, device) => { // the custom client's advanced settings; the official launcher sends none. accounts.setLoginChoices(account, body.login_choices); const token = byRefresh ? body.refresh_token : accounts.issueToken(account); + devices.noteLauncher(token, Boolean(device)); send(res, 200, {auth_token: token, refresh_token: token, device_token: deviceToken}); }; diff --git a/lib/manage.js b/lib/manage.js index 7d1a26e..a69b55c 100644 --- a/lib/manage.js +++ b/lib/manage.js @@ -12,6 +12,7 @@ const config = require("../config.js"); const limits = require("./limits.js"); const achievements = require("./achievements.js"); const badges = require("./badges.js"); +const discord = require("./discord.js"); const bans = require("./bans.js"); const captcha = require("./captcha.js"); const chatlog = require("./chatlog.js"); @@ -40,6 +41,12 @@ const world = require("./world.js"); const COOKIE = "ajc_account"; // A device that gave its two-step code keeps this for 30 days (lib/totp.js). const DEVICE_COOKIE = "ajc_device"; +// a Discord link under way (lib/discord.js): the browser that started it +// must be the one that comes back. Lax, as Discord's redirect back is from +// another site, which the page's own (Strict) cookie is not sent from. +const DISCORD_COOKIE = "ajc_dlink"; +const discordCookie = (value, maxAgeSeconds) => + `${DISCORD_COOKIE}=${value}; Path=/account/discord; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; const SESSION_HOURS = 12; const TEN_MINUTES_MS = 600000; const MAX_NOTE = 120; @@ -164,6 +171,8 @@ const profile = (account, from) => { locked: account.locked, twoStep: twoStepOf(account), discord: account.discord, + discordLinked: Boolean(account.discordId), + discordLinking: discord.linking(), bio: account.bio, bioLimit: badges.MAX_BIO, badges: badges.of(account).map(badge => badge.label), @@ -403,16 +412,15 @@ const act = (account, body, req, from, res) => { account.playtimePublic = body.on === true; accounts.save(account); return {ok: account.playtimePublic ? "Others can see your playtime on your card." : "Your playtime is private."}; - // their Discord username, for their card in the game. empty takes it off. - case "discord": { - const name = badges.discordName(body.name); - if (name === null) { - return {error: "Not a Discord username."}; + // their Discord account, for their card in the game: it is linked by + // signing in to Discord (GET /account/discord/link), and only taken off + // here, with the booster badge it brought. + case "discord": + if (String(body.name || "") !== "") { + return {error: "Link your Discord account instead."}; } - account.discord = name; - accounts.save(account); - return {ok: name ? "Saved." : "Removed."}; - } + discord.unlink(account); + return {ok: "Removed."}; // the player's own words about a buddy; only they see them. case "buddyNote": { const key = String(body.name || "").toLowerCase(); @@ -570,12 +578,38 @@ const handle = async (req, res, url, from, web) => { } } + // back from Discord (lib/discord.js): the state and the nonce must be the + // ones the link began with. the page then says how it went. + if (route === "GET /account/discord/callback") { + const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1]; + const result = url.searchParams.get("error") ? {error: "cancelled"} + : await discord.finish(url.searchParams.get("state"), nonce, url.searchParams.get("code")); + res.setHeader("Set-Cookie", discordCookie("", 0)); + res.writeHead(302, {Location: `/account?discord=${result.ok ? "linked" : result.error}`}); + res.end(); + return; + } + const account = signedInAs(req); if (!account) { reply(401, {error: "Sign in first."}); return; } switch (route) { + // the page's "Link Discord": off to Discord's sign-in, which comes back + // to /account/discord/callback. + case "GET /account/discord/link": { + if (!discord.linking() || banFor(account, from)) { + res.writeHead(302, {Location: "/account?discord=off"}); + res.end(); + return; + } + const {url: to, nonce} = discord.start(account); + res.setHeader("Set-Cookie", discordCookie(nonce, 600)); + res.writeHead(302, {Location: to}); + res.end(); + return; + } // A copy of their data, as a file. also from the page of a ban. case "GET /account/api/export": if (!writesPerTenMinutes.allow(account.id)) { diff --git a/lib/moderation.js b/lib/moderation.js index 144a7b8..e0e4661 100644 --- a/lib/moderation.js +++ b/lib/moderation.js @@ -183,6 +183,34 @@ module.exports = ({findOnline}) => { return true; }, + // every post they wrote on anyone's Jammer Wall (lib/walls.js), their + // own included, and the replies to those, as deleting a post in the game + // takes its replies. returns {posts, replies, walls}. + clearWallPosts(author) { + const changed = []; + let posts = 0; + let replies = 0; + for (const owner of accounts.all()) { + const {wall} = owner; + const gone = new Set(wall.posts.filter(post => post.uid === author.id).map(post => post.x)); + if (!gone.size) { + continue; + } + const kept = wall.posts.filter(post => !gone.has(post.x) && !gone.has(post.pp)); + posts += gone.size; + replies += wall.posts.length - kept.length - gone.size; + const left = new Set(kept.map(post => post.x)); + wall.posts = kept; + wall.hidden = wall.hidden.filter(id => left.has(id)); + wall.modified = Date.now(); + changed.push(owner); + } + if (changed.length) { + accounts.save(...changed); + } + return {posts, replies, walls: changed.length}; + }, + grantGems(target, amount) { return actions.grantCurrency(target, CURRENCY_GEMS, amount, false); }, diff --git a/lib/modpanel.js b/lib/modpanel.js index e920fb6..5a52258 100644 --- a/lib/modpanel.js +++ b/lib/modpanel.js @@ -159,7 +159,7 @@ const ACTION_PERMISSIONS = { silence: "chat.silence", unsilence: "chat.silence", kick: "player.kick", message: "player.warn", warn: "player.warn", unwarn: "player.warn", rejectName: "player.names", acceptName: "player.names", clearBio: "player.names", - banAddress: "address.ban", + clearWallPosts: "player.names", banAddress: "address.ban", summon: "player.summon", goto: "player.goto", note: "player.view", deleteNote: "player.view", }; @@ -256,6 +256,15 @@ const act = (mod, target, body) => { target.bio = ""; accounts.save(target); return {ok: "Bio cleared."}; + case "clearWallPosts": { + const {posts, replies, walls} = actions.clearWallPosts(target); + if (!posts) { + return {error: `${name} has no posts on any Jammer Wall.`}; + } + const text = `${posts} wall ${posts === 1 ? "post" : "posts"} by ${name} removed from ${walls} ${walls === 1 ? "wall" : "walls"}` + + `${replies ? ` (with ${replies} ${replies === 1 ? "reply" : "replies"} to them)` : ""}.`; + return {ok: text, detail: `${posts} posts, ${replies} replies, ${walls} walls`}; + } // a note for the other staff (lib/modnotes.js); the player never sees it. case "note": { const result = modNotes.add(target, by, body.text); diff --git a/lib/panel.js b/lib/panel.js index 00509cc..ec9dbf8 100644 --- a/lib/panel.js +++ b/lib/panel.js @@ -8,6 +8,7 @@ const accounts = require("./accounts.js"); const achievements = require("./achievements.js"); const adopt = require("./adopt.js"); const badges = require("./badges.js"); +const discordLinks = require("./discord.js"); const bans = require("./bans.js"); const colours = require("./colours.js"); const chatlog = require("./chatlog.js"); @@ -452,16 +453,13 @@ const act = (account, body) => { world.checkNameTag(account); return {ok: account.badges.length ? `${name} has: ${badges.of(account).map(badge => badge.label).join(", ")}.` : `${name} has no badges.`}; } - // their Discord username, which they otherwise set on the account - // page; empty takes it off. + // their linked Discord account (lib/discord.js), taken off. case "discord": { - const discord = badges.discordName(body.name); - if (discord === null) { - return {error: "Not a Discord username."}; + // only taken off: a player links their own (lib/discord.js) + if (String(body.name || "") !== "") { + return {error: "Players link their Discord themselves, on the account page."}; } - account.discord = discord; - accounts.save(account); - return {ok: discord ? `Discord set to "${discord}".` : "Discord cleared."}; + return discordLinks.unlink(account) ? {ok: "Discord unlinked."} : {error: `${name} has no Discord linked.`}; } // their bio, which they otherwise write on the account page; empty // takes it off. @@ -572,6 +570,15 @@ const act = (account, body) => { case "clearDen": actions.clearDen(account); return {ok: `Everything in ${name}'s den went back to their inventory.`}; + case "clearWallPosts": { + const {posts, replies, walls} = actions.clearWallPosts(account); + if (!posts) { + return {error: `${name} has no posts on any Jammer Wall.`}; + } + const text = `${posts} wall ${posts === 1 ? "post" : "posts"} by ${name} removed from ${walls} ${walls === 1 ? "wall" : "walls"}` + + `${replies ? ` (with ${replies} ${replies === 1 ? "reply" : "replies"} to them)` : ""}.`; + return {ok: text, detail: `${posts} posts, ${replies} replies, ${walls} walls`}; + } case "gems": { const amount = wholeNumber(body.amount, -MAX_GEMS, MAX_GEMS); if (amount === null) { diff --git a/lib/roles.js b/lib/roles.js index a6c54d0..20b308a 100644 --- a/lib/roles.js +++ b/lib/roles.js @@ -24,7 +24,7 @@ const PERMISSIONS = { "player.summon": "bring a player to the room you are in (!summon)", "staff.invisible": "go unseen in rooms, as the game's moderators could (!invisible)", "player.ban": "ban, unban and change a ban's reason", - "player.names": "reject or accept a name, clear a bio", + "player.names": "reject or accept a name, clear a bio, remove a player's Jammer Wall posts", "address.ban": "ban the address a player last signed in from", "items.approve": "approve or turn away the items and pictures players make, when the admin has asked for that", "items.create": "make new items from the game's art, change and delete them, lock items out of the item finder and take items from players (!item, !lock, !unlock, !locked, !take)", diff --git a/lib/world.js b/lib/world.js index b54dd58..cec88a9 100644 --- a/lib/world.js +++ b/lib/world.js @@ -146,6 +146,11 @@ const MAX_USER_VARS = 2000; const MAX_FILTER_WORDS = 100; // a player's own words for their chat filter const MAX_FILTER_WORD = 30; const LOGIN_BANNED = -15; // MainFrame.MSG_ID_LOGIN_BANNED +// MainFrame.MSG_ID_LOGIN_ACCT_MAINT: its popup (GamePlay.onWorldLogIn) shows +// localization string 11198, which lib/defpacks.js makes the "update your +// client" message. the official servers' account maintenance never happens +// here. +const LOGIN_OUTDATED = -12; const THEME_PATH_PREFIX = "theme_"; // lib/http.js looks for this const chatLines = limits.limiter(config.chatLinesPerWindow, config.chatWindowMs); @@ -183,6 +188,26 @@ const sees = (viewer, subject) => (!subject.invisible || roles.isActiveStaff(vie const watchers = session => others(session).filter(other => sees(other, session)); const TYPING_EVERY_MS = 2000; // "typing" passed on at most this often per player (xty) +// tags ("@name") in chat and on Jammer Walls (xmn): the longest player's +// name that the text after an "@" starts with, ending where a word does +// ("@John Smith hi" is John Smith if there is one, else John; "@Bobby" is +// never Bob). {length, name} or null. +const MAX_MENTION_TEXT = 40; +const MAX_MENTIONS = 10; // per question +const mentionLookups = limits.limiter(120, 60000); // questions a minute, per player +const mentionOf = text => { + for (let length = Math.min(text.length, MAX_MENTION_TEXT); length > 0; length--) { + if (length < text.length && /[A-Za-z0-9]/.test(text[length])) { + continue; + } + const name = accounts.nameOf(text.slice(0, length)); + if (name) { + return {length, name}; + } + } + return null; +}; + const decodeEntities = text => text .replace(/</g, "<") .replace(/>/g, ">") @@ -304,9 +329,12 @@ const login = (session, msg) => { loginFailed(session, LOGIN_BANNED, "Banned"); return; } - if (config.requireDevice && devices.knownFor(account).lastAt < Math.floor(Date.now() / 1000) - 90 * 86400) { - console.log(`[world] login rejected for "${logText(account.username)}": no device ids`); - loginFailed(session, 0, "Update the client"); + // a launcher that sent no device ids (before 1.3.0): signed in at + // /authenticate, refused here, where the game's popup can say why. + if (config.requireDevice && (devices.launcherOutdated(msg.cdata("pword")) + || devices.knownFor(account).lastAt < Math.floor(Date.now() / 1000) - 90 * 86400)) { + console.log(`[world] login rejected for "${logText(account.username)}": client outdated (no device ids)`); + loginFailed(session, LOGIN_OUTDATED, "Client outdated"); return; } // its username was rejected (lib/moderation.js): a new one first, which @@ -912,6 +940,22 @@ const handlers = { } }, + // the patched client's tags (AJClient.resolveMentions): xmn [id, the text + // after each "@", ...] -> "xmn" [.., .., id, then for each text: how many + // of its characters are a player's name (0 for none), the name as it is + // spelled, 1 if they are online]. what a text is not a name of stays text. + xmn(session, roomId, [id, ...texts]) { + if (!mentionLookups.allow(session.account.id)) { + return; + } + const reply = []; + for (const text of texts.slice(0, MAX_MENTIONS)) { + const found = mentionOf(String(text)); + reply.push(found ? found.length : 0, found ? found.name : "", found && findOnline(found.name) ? 1 : 0); + } + session.sendXt("xmn", -1, Number.isInteger(Number(id)) ? Number(id) : 0, ...reply); + }, + // the patched client's staff window: going invisible, or being seen again. xiv(session) { if (session.invisible || roles.can(session.account, "staff.invisible")) { diff --git a/public/account.html b/public/account.html index 3346a0e..57c9e10 100644 --- a/public/account.html +++ b/public/account.html @@ -367,12 +367,10 @@

Discord

-
- - -
-
-
+

+

Shown on your card in the game. Sign in to Discord to link your account; boosting Burrow's Discord server gives you the Server Booster badge while you boost.

+
+

@@ -805,11 +803,11 @@ $("bio-text").maxLength = account.bioLimit + 20; // room for the line ends a browser counts double $("bio-remove").hidden = !account.bio; bioCount(); - // not while it is being typed in: every answer from the server draws the page again. - if (document.activeElement !== $("discord-name")) { - $("discord-name").value = account.discord; - } - $("discord-remove").hidden = !account.discord; + // linked by signing in to Discord (lib/discord.js), not typed in + $("discord-shown").textContent = account.discordLinked ? `Linked: ${account.discord}` : "Not linked."; + $("discord-link").textContent = account.discordLinked ? "Link another" : "Link Discord"; + $("discord-link").hidden = !account.discordLinking; + $("discord-remove").hidden = !account.discordLinked; $("badges").hidden = account.badges.length === 0; $("badges").textContent = `Badges: ${account.badges.join(", ")}`; @@ -938,6 +936,11 @@ if (result.ok) { account = result.data; render(); + // back from linking Discord: how it went, once + if (discordResult && Object.hasOwn(DISCORD_RESULTS, discordResult)) { + setStatus("discord-status", DISCORD_RESULTS[discordResult], discordResult !== "linked"); + history.replaceState(null, "", location.pathname + location.hash); + } } else { showGate(result.status === 0 ? result.data.error : ""); @@ -1340,12 +1343,24 @@ }); $("bio-remove").addEventListener("click", () => act({action: "bio", text: ""}, "bio-status")); - $("discord-form").addEventListener("submit", async event => { - event.preventDefault(); - $("discord-name").blur(); - await act({action: "discord", name: $("discord-name").value}, "discord-status"); + // off to Discord's sign-in; it comes back to /account?discord= + $("discord-link").addEventListener("click", () => { + location.href = "/account/discord/link"; }); - $("discord-remove").addEventListener("click", () => act({action: "discord", name: ""}, "discord-status")); + $("discord-remove").addEventListener("click", () => { + if (confirm("Unlink your Discord account? It comes off your card, and so does the Server Booster badge.")) { + act({action: "discord", name: ""}, "discord-status"); + } + }); + const DISCORD_RESULTS = { + linked: "Discord linked.", + cancelled: "Linking was cancelled.", + expired: "That took too long, or was started in another browser. Try again.", + taken: "That Discord account is linked to another Burrow account.", + discord: "Discord did not answer. Try again later.", + off: "Linking Discord is not available right now.", + }; + const discordResult = new URLSearchParams(location.search).get("discord"); $("lock").addEventListener("click", () => { if (!account.locked && !window.confirm("Lock the account? Nobody gets in until you unlock it here.")) { diff --git a/public/admin.html b/public/admin.html index e9b04a0..ae37957 100644 --- a/public/admin.html +++ b/public/admin.html @@ -503,8 +503,9 @@

Badges

-
-
+
+ +

Ban

@@ -576,6 +577,7 @@ +
@@ -1440,7 +1442,7 @@ label.append(box, ` ${badge.label}`); return label; })); - $("discord-name").value = current ? current.discord : ""; + $("discord-name").textContent = current && current.discord ? `Discord: ${current.discord}` : "No Discord linked"; $("bio-text").value = current ? current.bio : ""; $("quest-level").value = current ? current.level : ""; $("ban-reason").value = current ? current.banReason : ""; @@ -1628,7 +1630,7 @@ case "gems": return {amount: numberFrom("gems-amount")}; case "gift": return giftBody(); case "badges": return {badges: [...$("badge-boxes").querySelectorAll("input:checked")].map(box => box.value)}; - case "discord": return {name: $("discord-name").value}; + case "discord": return {name: ""}; case "bio": return {text: $("bio-text").value}; case "level": return {level: numberFrom("quest-level")}; default: return {}; @@ -1658,6 +1660,9 @@ if (action === "unbanDevices" && !window.confirm(`Lift the hardware bans on ${selected}?`)) { return; } + if (action === "clearWallPosts" && !window.confirm(`Remove every post ${selected} wrote on any Jammer Wall, and the replies to them? This cannot be undone.`)) { + return; + } if (action === "banDevices" && !window.confirm(`Hardware ban ${selected}? Everyone on their hardware is put out.`)) { return; } @@ -1999,10 +2004,16 @@ el("div", `${when(painting.createdAt)}${painting.status === "approved" ? `, ${painting.likes} like${painting.likes === 1 ? "" : "s"}` : ""}` + `${which === "all" ? (painting.status === "waiting" ? " · waiting" : " · approved") : ""}`, "hint")); const buttons = el("div", undefined, "buttons"); + // rejecting or removing asks first; approving does not + const sure = action => action === "approve" || confirm(action === "reject" + ? `Reject this painting by ${painting.creator}?` : `Remove this painting by ${painting.creator} from show?`); const button = (label, action, className) => { const node = el("button", label, className); node.type = "button"; node.addEventListener("click", async () => { + if (!sure(action)) { + return; + } node.disabled = true; const result = await api("masterpiece", {id: painting.id, action}); setStatus($("masterpiece-status"), result.data.ok || result.data.error || "That did not work.", !result.ok); @@ -2335,6 +2346,10 @@ el("div", `by ${entry.maker} · ${when(entry.createdAt)}${entry.makerStrikes ? ` · ${entry.makerStrikes} of ${data.strikes} pictures turned away before` : ""}`, "hint")); const buttons = el("div", undefined, "buttons"); const decide = approve => async () => { + // turning away asks first; approving does not + if (!approve && !confirm(`Turn away ${entry.waiting === "item" ? "the item" : "the picture of"} "${entry.name}" by ${entry.maker}?`)) { + return; + } const result = await api("review", {kind: entry.kind, id: entry.id, approve}); setStatus($("review-status"), said(result), !result.ok); await refresh(); diff --git a/public/game.html b/public/game.html index 837e663..9aff8d0 100644 --- a/public/game.html +++ b/public/game.html @@ -84,6 +84,12 @@ } } + // where the player is, for the client's Discord rich presence + // (AJClient.presenceRoom): a short line such as "In Jamaa Township". + function ajPresence(text) { + window.ipc.sendToHost("presence", String(text).slice(0, 100)); + } + function ajPrint(imageData) { window.ipc.sendToHost("printImage", imageData); } diff --git a/public/mod.html b/public/mod.html index 96c5423..7e721ee 100644 --- a/public/mod.html +++ b/public/mod.html @@ -477,11 +477,13 @@
-

Username and bio

+

Username, bio and wall posts

+
+

Other accounts

@@ -1117,6 +1119,7 @@ unbanDevices: name => `Lift the hardware bans on ${name}?`, rejectName: name => `Reject the username ${name}? They are signed out and must pick another.`, unwarn: name => `Take back ${name}'s latest warning?`, + clearWallPosts: name => `Remove every post ${name} wrote on any Jammer Wall, and the replies to them? This cannot be undone.`, }; $("detail").addEventListener("click", async event => { @@ -1404,7 +1407,13 @@ box.append(picture, el("h3", painting.creator), el("div", `${when(painting.createdAt)}${which === "all" ? (painting.status === "waiting" ? " · waiting" : " · on show") : ""}`, "hint")); const buttons = el("div", undefined, "buttons"); + // rejecting or removing asks first; approving does not + const sure = action => action === "approve" || confirm(action === "reject" + ? `Reject this painting by ${painting.creator}?` : `Remove this painting by ${painting.creator} from show?`); const does = (label, action, className) => button(label, async () => { + if (!sure(action)) { + return; + } const result = await api("masterpiece", {id: painting.id, action}); setStatus($("masterpiece-status"), said(result), !result.ok); refresh(); @@ -1843,6 +1852,10 @@ el("div", `by ${entry.maker} · ${when(entry.createdAt)}${entry.makerStrikes ? ` · ${entry.makerStrikes} of ${data.strikes} pictures turned away before` : ""}`, "hint")); const buttons = el("div", undefined, "buttons"); const decide = approve => async () => { + // turning away asks first; approving does not + if (!approve && !confirm(`Turn away ${entry.waiting === "item" ? "the item" : "the picture of"} "${entry.name}" by ${entry.maker}?`)) { + return; + } const result = await api("review", {kind: entry.kind, id: entry.id, approve}); setStatus($("review-status"), said(result), !result.ok); await refresh(); @@ -2095,7 +2108,7 @@ silence: "chat.silence", unsilence: "chat.silence", kick: "player.kick", message: "player.warn", warn: "player.warn", unwarn: "player.warn", rejectName: "player.names", acceptName: "player.names", clearBio: "player.names", - banAddress: "address.ban", summon: "player.summon", goto: "player.goto", + clearWallPosts: "player.names", banAddress: "address.ban", summon: "player.summon", goto: "player.goto", }; const applyPermissions = async () => { const result = await api("me"); diff --git a/server.js b/server.js index 62af94a..7c0cf53 100644 --- a/server.js +++ b/server.js @@ -6,6 +6,7 @@ const fs = require("fs"); const accounts = require("./lib/accounts.js"); const bans = require("./lib/bans.js"); const devices = require("./lib/devices.js"); +const discord = require("./lib/discord.js"); const chatlog = require("./lib/chatlog.js"); const modlog = require("./lib/modlog.js"); const retention = require("./lib/retention.js"); @@ -44,6 +45,7 @@ const main = async () => { support.load(); bans.load(); devices.load(); + discord.startup(); chatlog.load(); modlog.load(); masterpieces.load(); diff --git a/swf-src/AJClient.as b/swf-src/AJClient.as index 6a18dd6..7ab99b5 100644 --- a/swf-src/AJClient.as +++ b/swf-src/AJClient.as @@ -2,6 +2,11 @@ package { import avatar.AvatarManager; import avatar.AvatarWorldView; + import buddy.Buddy; + import buddy.BuddyManager; + import com.sbi.corelib.audio.SBAudio; + import com.sbi.corelib.audio.SBMusic; + import com.sbi.corelib.audio.SBSound; import com.sbi.debug.DebugUtility; import com.sbi.graphics.PaletteHelper; import den.DenXtCommManager; @@ -27,9 +32,11 @@ package import flash.geom.Matrix; import flash.utils.ByteArray; import flash.geom.Point; + import flash.geom.Rectangle; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TimerEvent; + import flash.media.SoundTransform; import flash.net.FileFilter; import flash.net.FileReference; import flash.net.URLLoader; @@ -47,6 +54,7 @@ package import flash.utils.Dictionary; import flash.utils.Timer; import flash.utils.getTimer; + import flash.utils.setTimeout; import game.MinigameManager; import gamePlayFlow.GamePlay; import gskinner.motion.GTween; @@ -2291,7 +2299,8 @@ package finderButtonText(_finderKindButton,"All items"); _finderKindButton.addEventListener("mouseDown",onFinderKindClick); _loc2_.addChild(_finderKindButton); - _finderColourBar = finderSearchBar(93,-160,156,"Colour ID or #hex","0-9a-fA-F# ,",31,false); + // a colour id may be negative: the signed way of writing it (lib/admin.js) + _finderColourBar = finderSearchBar(93,-160,156,"Colour ID or #hex","0-9a-fA-F# ,\\-",31,false); _finderColourInput = _finderColourBar.searchTxt; _finderColourInput.addEventListener("change",onFinderColourTyped); _loc2_.addChild(_finderColourBar); @@ -2880,6 +2889,499 @@ package }); } + // tags: "@name" in chat and on Jammer Walls, when the name is a + // player's, is drawn light blue and underlined, and opens that player's + // card when clicked. which names are players' the server says (xmn, + // lib/world.js): the longest name the text after the "@" starts with, + // spaces and all ("@John Smith hi"), ending where a word does. a "@" + // counts at the start or after a character no name has ("me@home" is + // no tag). what is no player's name stays plain text. + public static const MENTION_COLOR:uint = 4895732; // #4ab3f4 + + private static const MENTION_TEXT:int = 40; // characters after an "@" asked about + + private static const MENTION_ASK_MOST:int = 10; // texts in one question, as the server takes + + private static const MENTION_WAIT_MS:int = 3000; // no answer by then: no tags in that text + + private static const MENTION_KEEP:int = 2000; // answers kept before starting over + + private static var _mentionKnown:Object = {}; // lowercased text after an "@" -> {length, name} or null + + private static var _mentionKnownCount:int = 0; + + private static var _mentionOnline:Object = {}; // lowercased name -> 1 | 0, as last heard + + private static var _mentionAsks:Object = {}; // question id -> {texts, finish} + + private static var _mentionNextId:int = 1; + + // the "@"s that could start a tag: [{at, text}], `text` what follows, + // up to a "%" or a line's end (neither is in a name). + private static function mentionStarts(param1:String) : Array + { + var _loc2_:Array = []; + var _loc3_:int = param1 == null ? -1 : param1.indexOf("@"); + var _loc4_:String = null; + var _loc5_:String = null; + while(_loc3_ != -1) + { + _loc4_ = _loc3_ > 0 ? param1.charAt(_loc3_ - 1) : " "; + if(!/[A-Za-z0-9.\-@]/.test(_loc4_) && /[A-Za-z0-9]/.test(param1.charAt(_loc3_ + 1))) + { + _loc5_ = param1.substr(_loc3_ + 1,MENTION_TEXT).split("%")[0].split("\r")[0].split("\n")[0]; + _loc2_.push({ + "at":_loc3_, + "text":_loc5_ + }); + } + _loc3_ = param1.indexOf("@",_loc3_ + 1); + } + return _loc2_; + } + + // [{at, length, name}] for the starts the server has said are tags: + // `at` at the "@", `length` with it, `name` as the account spells it. + private static function mentionsFound(param1:Array) : Array + { + var _loc2_:Array = []; + var _loc3_:Object = null; + var _loc4_:Object = null; + for each(_loc3_ in param1) + { + _loc4_ = _mentionKnown[String(_loc3_.text).toLowerCase()]; + if(_loc4_ != null) + { + _loc2_.push({ + "at":_loc3_.at, + "length":_loc4_.length + 1, + "name":_loc4_.name + }); + } + } + return _loc2_; + } + + // the tags in a text, given to `param2` as [{at, length, name}]: at + // once when every name in it is known, else when the server answers + // (or does not, in MENTION_WAIT_MS: then only the known ones). + public static function resolveMentions(param1:String, param2:Function) : void + { + var _loc3_:Array = mentionStarts(param1); + var _loc4_:Array = []; + var _loc5_:Array = []; + var _loc6_:Object = null; + var _loc7_:String = null; + var _loc8_:int = 0; + var _loc9_:Function = null; + for each(_loc6_ in _loc3_) + { + _loc7_ = String(_loc6_.text).toLowerCase(); + if(!(_loc7_ in _mentionKnown) && _loc5_.indexOf(_loc7_) == -1 && _loc4_.length < MENTION_ASK_MOST) + { + _loc5_.push(_loc7_); + _loc4_.push(_loc6_.text); + } + } + if(_loc4_.length == 0) + { + param2(mentionsFound(_loc3_)); + return; + } + _loc8_ = _mentionNextId++; + _loc9_ = function():void + { + if(_loc8_ in _mentionAsks) + { + delete _mentionAsks[_loc8_]; + param2(mentionsFound(_loc3_)); + } + }; + _mentionAsks[_loc8_] = { + "texts":_loc4_, + "finish":_loc9_ + }; + gMainFrame.server.setXtObject_Str("xmn",[_loc8_].concat(_loc4_)); + setTimeout(_loc9_,MENTION_WAIT_MS); + } + + // "xmn": [.., .., id, then for each text asked about: length of the + // name it starts with (0: none), the name, 1 if they are online]. + public static function onMentions(param1:Object) : void + { + var _loc2_:Object = _mentionAsks[int(param1[2])]; + var _loc3_:int = 0; + var _loc4_:int = 0; + var _loc5_:String = null; + if(_loc2_ == null) + { + return; + } + if(_mentionKnownCount > MENTION_KEEP) + { + _mentionKnown = {}; + _mentionKnownCount = 0; + } + _loc3_ = 0; + while(_loc3_ < _loc2_.texts.length && 5 + _loc3_ * 3 < param1.length) + { + _loc4_ = int(param1[3 + _loc3_ * 3]); + _loc5_ = String(param1[4 + _loc3_ * 3]); + _mentionKnown[String(_loc2_.texts[_loc3_]).toLowerCase()] = _loc4_ > 0 ? { + "length":_loc4_, + "name":_loc5_ + } : null; + _mentionKnownCount++; + if(_loc4_ > 0) + { + _mentionOnline[_loc5_.toLowerCase()] = int(param1[5 + _loc3_ * 3]); + } + _loc3_++; + } + _loc2_.finish(); + } + + // colours tags (resolveMentions) in a text field that reads as it did + // then: MENTION_COLOR, or `param4` when given. with `param3`, each is + // also a link ("event:@name", heard as a "link" event). + public static function styleMentions(param1:TextField, param2:Array, param3:Boolean, param4:int = -1) : void + { + var _loc4_:Object = null; + var _loc5_:TextFormat = null; + if(param1 == null || param2 == null) + { + return; + } + for each(_loc4_ in param2) + { + if(_loc4_.at + _loc4_.length <= param1.length) + { + _loc5_ = new TextFormat(); + _loc5_.color = param4 >= 0 ? param4 : MENTION_COLOR; + _loc5_.underline = true; + if(param3) + { + _loc5_.url = "event:@" + _loc4_.name; + } + param1.setTextFormat(_loc5_,_loc4_.at,_loc4_.at + _loc4_.length); + } + } + } + + // the name of the tag under the mouse in a text field, or null. + public static function mentionAt(param1:TextField, param2:Array) : String + { + var _loc3_:int = param1 == null || param2 == null ? -1 : param1.getCharIndexAtPoint(param1.mouseX,param1.mouseY); + var _loc4_:Object = null; + if(_loc3_ < 0) + { + return null; + } + for each(_loc4_ in param2) + { + if(_loc3_ >= _loc4_.at && _loc3_ < _loc4_.at + _loc4_.length) + { + return _loc4_.name; + } + } + return null; + } + + // a tagged player's card (the server has said the name is theirs). + public static function openProfile(param1:String) : void + { + var _loc2_:Buddy = null; + if(param1 == null || param1 == "") + { + return; + } + _loc2_ = BuddyManager.getBuddyByUserName(param1); + BuddyManager.showBuddyCard({ + "userName":(_loc2_ != null ? _loc2_.userName : param1), + "onlineStatus":(_loc2_ != null ? _loc2_.onlineStatus : int(_mentionOnline[param1.toLowerCase()])) + }); + } + + // a tag's background, as Discord draws a mention: a rounded box of + // the tag's colour, see-through, behind its words (one a line, should a + // tag wrap). a text field has no background for part of its text, so + // it is drawn on a Shape just under the field (over it, faintly, if + // the field paints its own background), kept a field. + // how strong the box is: the chat log's dark panel shows a fainter one + // well, the white balloons and the wall posts need it stronger (a + // balloon is see-through itself). + public static const MENTION_BACK_DARK:Number = 0.4; + + public static const MENTION_BACK_LIGHT:Number = 0.6; + + private static var _mentionBacks:Dictionary = new Dictionary(true); // text field -> Shape + + // the tags in a text field whose tags are links ("event:@name", the + // chat log's): [{at, length}]. + public static function mentionLinks(param1:TextField) : Array + { + var _loc2_:Array = []; + var _loc3_:String = param1 == null ? "" : param1.text; + var _loc4_:int = _loc3_.indexOf("@"); + var _loc5_:String = null; + var _loc6_:int = 0; + while(_loc4_ != -1) + { + _loc5_ = param1.getTextFormat(_loc4_,_loc4_ + 1).url; + if(_loc5_ != null && _loc5_.indexOf("event:@") == 0) + { + _loc6_ = _loc4_ + 1; + while(_loc6_ < _loc3_.length && param1.getTextFormat(_loc6_,_loc6_ + 1).url == _loc5_) + { + _loc6_++; + } + _loc2_.push({ + "at":_loc4_, + "length":_loc6_ - _loc4_ + }); + _loc4_ = _loc3_.indexOf("@",_loc6_); + } + else + { + _loc4_ = _loc3_.indexOf("@",_loc4_ + 1); + } + } + return _loc2_; + } + + // draws the backgrounds of `param2` ([{at, length}]) for a text field + // as it is laid out and scrolled now, `param3` strong; none, with no tags. + public static function drawMentionBacks(param1:TextField, param2:Array, param3:Number = 0.6) : void + { + var _loc3_:Shape = _mentionBacks[param1]; + var _loc4_:Object = null; + var _loc5_:Object = null; + var _loc6_:Object = null; + var _loc7_:Rectangle = null; + var _loc8_:int = 0; + var _loc9_:int = 0; + var _loc10_:int = 0; + var _loc11_:int = 0; + var _loc12_:Number = 0; + var _loc13_:int = 0; + if(param1 == null) + { + return; + } + if(_loc3_ == null) + { + if(param2 == null || param2.length == 0) + { + return; + } + _loc3_ = new Shape(); + _mentionBacks[param1] = _loc3_; + } + _loc3_.graphics.clear(); + if(param1.parent == null || param2 == null || param2.length == 0) + { + return; + } + if(_loc3_.parent != null) + { + _loc3_.parent.removeChild(_loc3_); + } + _loc13_ = param1.parent.getChildIndex(param1); + param1.parent.addChildAt(_loc3_,param1.background ? _loc13_ + 1 : _loc13_); + _loc3_.transform.matrix = param1.transform.matrix; + // only the lines in view; their place as the field is scrolled now + _loc9_ = param1.scrollV - 1; + _loc10_ = param1.bottomScrollV - 1; + if(_loc9_ > 0) + { + _loc7_ = param1.getCharBoundaries(param1.getLineOffset(_loc9_)); + _loc12_ = _loc7_ != null ? _loc7_.y - 2 : 0; + } + for each(_loc4_ in param2) + { + _loc5_ = {}; + _loc8_ = _loc4_.at; + while(_loc8_ < _loc4_.at + _loc4_.length && _loc8_ < param1.length) + { + _loc11_ = param1.getLineIndexOfChar(_loc8_); + _loc7_ = _loc11_ >= _loc9_ && _loc11_ <= _loc10_ ? param1.getCharBoundaries(_loc8_) : null; + if(_loc7_ != null && _loc7_.width > 0) + { + _loc6_ = _loc5_[_loc11_]; + if(_loc6_ == null) + { + _loc5_[_loc11_] = { + "left":_loc7_.x, + "right":_loc7_.x + _loc7_.width, + "top":_loc7_.y, + "height":_loc7_.height + }; + } + else + { + _loc6_.left = Math.min(_loc6_.left,_loc7_.x); + _loc6_.right = Math.max(_loc6_.right,_loc7_.x + _loc7_.width); + _loc6_.height = Math.max(_loc6_.height,_loc7_.height); + } + } + _loc8_++; + } + for each(_loc6_ in _loc5_) + { + _loc3_.graphics.beginFill(MENTION_COLOR,param3); + _loc3_.graphics.drawRoundRect(_loc6_.left - 3,_loc6_.top - _loc12_,_loc6_.right - _loc6_.left + 6,_loc6_.height,8,8); + _loc3_.graphics.endFill(); + } + } + } + + // sound settings (MySettings' Music and SFX sliders): music and sound + // effects apart, each a volume from 0 to 1, kept on this computer in + // the game's shared object (musicVolume, sfxVolume). both start at the + // game's one old volume ("volume"), which is then left at full under + // them. + // music: every SBMusic (the rooms', the minigames' streams). sound + // effects: every SBSound (the interface's too), the minigames' + // SoundManager sounds, and what artwork plays by itself (gMainFrame's + // soundTransform; music plays apart from the display, so not under it). + // the HUD's speaker button still turns everything off and on. + private static var _musicVolume:Number = 1; + + private static var _sfxVolume:Number = 1; + + public static function musicLevel() : Number + { + return _musicVolume; + } + + public static function sfxLevel() : Number + { + return _sfxVolume; + } + + // "music" or "sfx" + public static function soundVolume(param1:String) : Number + { + return param1 == "music" ? _musicVolume : _sfxVolume; + } + + private static function volumeFrom(param1:*, param2:Number) : Number + { + var _loc3_:Number = param1 == null ? param2 : Number(param1); + return isNaN(_loc3_) ? param2 : Math.max(0,Math.min(1,_loc3_)); + } + + // once the game has read its shared object (GuiManager.setupSharedObject) + public static function loadSoundSettings() : void + { + var _loc1_:Object = GuiManager.sharedObj != null ? GuiManager.sharedObj.data : null; + var _loc2_:Number = volumeFrom(_loc1_ != null ? _loc1_.volume : null,1); + _musicVolume = volumeFrom(_loc1_ != null ? _loc1_.musicVolume : null,_loc2_); + _sfxVolume = volumeFrom(_loc1_ != null ? _loc1_.sfxVolume : null,_loc2_); + if(SBAudio.currentVolume != 1) + { + SBAudio.setVolumeAll(1); + } + applySoundSettings(); + } + + // a volume (0 to 1); `param3` keeps it (a slider being dragged does + // not, until it is let go) + public static function setSoundVolume(param1:String, param2:Number, param3:Boolean = true) : void + { + param2 = volumeFrom(param2,1); + if(param1 == "music") + { + _musicVolume = param2; + } + else + { + _sfxVolume = param2; + } + applySoundSettings(); + if(param3) + { + saveSoundSettings(); + } + } + + public static function saveSoundSettings() : void + { + if(GuiManager.sharedObj == null) + { + return; + } + GuiManager.sharedObj.data.musicVolume = _musicVolume; + GuiManager.sharedObj.data.sfxVolume = _sfxVolume; + try + { + GuiManager.sharedObj.flush(); + } + catch(e:Error) + { + } + } + + private static function applySoundSettings() : void + { + SBMusic.refreshAll(); + SBSound.refreshAll(); + if(gMainFrame != null) + { + gMainFrame.soundTransform = new SoundTransform(sfxLevel()); + } + } + + // where the player is, for the client's Discord rich presence (game.html + // ajPresence, the client's app/discord.js): the room's name as the game + // shows it, but never another player's name: a den or a player's party + // is named after its owner, so it is only "In their den", "Visiting a + // den" and the like. which room it is goes by its name on the server + // (lib/world.js): "den", "pparty", "party_". + private static var _presenceShown:String = null; + + public static function presenceRoom(param1:String) : void + { + var _loc2_:String = ""; + var _loc3_:String = gMainFrame.userInfo.myUserName != null ? String(gMainFrame.userInfo.myUserName).toLowerCase() : ""; + var _loc4_:String = null; + try + { + _loc2_ = String(gMainFrame.server.getCurrentRoomName() || ""); + } + catch(e:Error) + { + } + if(_loc2_.indexOf("den") == 0) + { + _loc4_ = _loc2_.substr(3).toLowerCase() == _loc3_ ? "In their den" : "Visiting a den"; + } + else if(_loc2_.indexOf("pparty") == 0) + { + _loc4_ = _loc2_.substr(6).toLowerCase() == _loc3_ ? "Hosting a party" : "At a party"; + } + else if(_loc2_.indexOf("party") == 0 && _loc2_.indexOf("_") != -1) + { + _loc4_ = "At a party"; + } + else + { + _loc4_ = param1 != null && param1 != "" ? "In " + param1 : "Playing"; + } + if(_loc4_ == _presenceShown || !ExternalInterface.available) + { + return; + } + _presenceShown = _loc4_; + try + { + ExternalInterface.call("ajPresence",_loc4_); + } + catch(e:Error) + { + } + } + private function startEmojiButton() : void { _emojiTimer = new Timer(500); @@ -3940,7 +4442,7 @@ package }; if(_finderColourInput.text.length > 0 && _loc2_.kind != "den") { - if(_finderColourInput.text.indexOf("#") >= 0 ? finderHexColours(_finderColourInput.text) == null : !/^\s*[0-9]+\s*$/.test(_finderColourInput.text)) + if(_finderColourInput.text.indexOf("#") >= 0 ? finderHexColours(_finderColourInput.text) == null : !/^\s*-?[0-9]+\s*$/.test(_finderColourInput.text)) { _finderStatus.text = "Colour: an id, or #RRGGBB"; return; @@ -4001,8 +4503,9 @@ package return _finderHexId; } } - else if(/^[0-9]+$/.test(_loc2_)) + else if(/^-?[0-9]+$/.test(_loc2_)) { + // a negative id is the same colour written signed return uint(Number(_loc2_)); } _loc4_ = ItemXtCommManager.getItemDef(int(param1.id)); @@ -4104,7 +4607,7 @@ package private function onFinderColourTyped(param1:Event) : void { var _loc2_:String = _finderColourInput.text.replace(/^\s+|\s+$/g,""); - if(_loc2_.length == 0 || /^[0-9]+$/.test(_loc2_) || finderHexColours(_loc2_) != null) + if(_loc2_.length == 0 || /^-?[0-9]+$/.test(_loc2_) || finderHexColours(_loc2_) != null) { for(var _loc3_:String in _finderIcons) { diff --git a/swf-src/ChatBalloon.as b/swf-src/ChatBalloon.as index 831ed2f..9b67096 100644 --- a/swf-src/ChatBalloon.as +++ b/swf-src/ChatBalloon.as @@ -3,9 +3,11 @@ package gui import flash.display.MovieClip; import flash.display.Sprite; import flash.events.MouseEvent; + import flash.events.TextEvent; import flash.geom.ColorTransform; import flash.geom.Point; import flash.geom.Rectangle; + import flash.text.TextField; import flash.utils.setTimeout; import loader.MediaHelper; import localization.LocalizationManager; @@ -133,6 +135,7 @@ package gui this.visible = true; } clearInline(); + clearMentionBacks(); _msgTxt.text = inlineEmotes(param1); _msgTxt.height; // AJClient.whisperNext is set by the server's "xw" just ahead of a @@ -167,6 +170,33 @@ package gui { _msgTxt.textColor = 4477529; } + // tags (AJClient.resolveMentions): once the server says which "@"s + // are players', light blue and underlined, each a link to that + // player's card, if the balloon still says the same. (the field is + // another on some frames.) + if(!param2 && _msgTxt is TextField && _msgTxt.text.indexOf("@") != -1) + { + var field:TextField = TextField(_msgTxt); + var shown:String = field.text; + field.addEventListener("link",onMentionLink,false,0,true); + AJClient.resolveMentions(shown,function(param1:Array):void + { + if(field.text == shown) + { + // in the message's own colour here: the blue box marks it + AJClient.styleMentions(field,param1,true,4477529); + // and their backgrounds, now and once laid out for sure + AJClient.drawMentionBacks(field,param1,AJClient.MENTION_BACK_LIGHT); + setTimeout(function():void + { + if(field.text == shown) + { + AJClient.drawMentionBacks(field,param1,AJClient.MENTION_BACK_LIGHT); + } + },42); + } + }); + } _timeout = 8000; if(param3 && this.parent) { @@ -438,6 +468,7 @@ package gui public function setCustomAdventureMessage(param1:String, param2:String, param3:int, param4:Boolean = false, param5:Boolean = false) : void { + clearMentionBacks(); var _loc6_:int = 0; var _loc7_:int = 0; var _loc8_:Array = param2.split("|"); @@ -582,6 +613,25 @@ package gui } } + // the backgrounds of the tags of the text before (setText) + private function clearMentionBacks() : void + { + if(_msgTxt is TextField) + { + AJClient.drawMentionBacks(TextField(_msgTxt),null); + } + } + + // a tag clicked: "@name" (setText) + private function onMentionLink(param1:TextEvent) : void + { + param1.stopPropagation(); + if(param1.text && param1.text.charAt(0) == "@") + { + AJClient.openProfile(param1.text.substr(1)); + } + } + private function onBtnBG(param1:MouseEvent) : void { param1.stopPropagation(); @@ -610,6 +660,7 @@ package gui public function setEmote(param1:Sprite, param2:int = -1) : void { + clearMentionBacks(); if(this.currentFrameLabel != "advBtn") { _permEmoteMediaId = param2; diff --git a/swf-src/ChatHistory.as b/swf-src/ChatHistory.as index e63793d..5b42477 100644 --- a/swf-src/ChatHistory.as +++ b/swf-src/ChatHistory.as @@ -209,6 +209,82 @@ package gui } return param1.split("&").join("&").split("<").join("<").split(">").join(">").split("\"").join("""); } + + // a line's words as plain() makes them, with each tag (`param2`, + // AJClient.resolveMentions) as typed, made a link to that player's card. + private static function withMentions(param1:String, param2:Array) : String + { + var _loc3_:String = ""; + var _loc4_:int = 0; + var _loc5_:Object = null; + if(param1 == null) + { + return ""; + } + for each(_loc5_ in param2) + { + _loc3_ += plain(param1.substring(_loc4_,_loc5_.at)) + "" + plain(param1.substr(_loc5_.at,_loc5_.length)) + ""; + _loc4_ = _loc5_.at + _loc5_.length; + } + return _loc3_ + plain(param1.substr(_loc4_)); + } + + // lines wait here, in the order they came, while the server is asked + // which "@"s in them are players' (AJClient.resolveMentions; a line + // without one goes on at once, unless one ahead of it is waiting). + // each is {before, words, after: HTML around the words, found}. + private var _lines:Array = []; + + private function addLine(param1:String, param2:String, param3:String) : void + { + var line:Object = { + "before":param1, + "words":param2, + "after":param3, + "found":null + }; + _lines.push(line); + AJClient.resolveMentions(param2,function(param1:Array):void + { + line.found = param1; + showLines(); + }); + } + + private function showLines() : void + { + var _loc1_:Object = null; + var _loc2_:String = null; + while(_lines.length > 0 && _lines[0].found != null) + { + _loc1_ = _lines.shift(); + if(_chatText == null) + { + continue; + } + _chatText.htmlText += _loc1_.before + withMentions(_loc1_.words,_loc1_.found) + _loc1_.after; + if(_chatText.numLines >= 100) + { + _loc2_ = _chatText.htmlText; + _chatText.htmlText = _loc2_.substr(_loc2_.indexOf("\n") + 1); + } + if(!_isOverChatText) + { + _chatText.scrollV = _chatText.maxScrollV; + } + } + drawMentionBacks(); + } + + // the tags' backgrounds (AJClient.drawMentionBacks), for the lines in + // view: again after each new line and each scroll. + private function drawMentionBacks(param1:Event = null) : void + { + if(_chatText != null) + { + AJClient.drawMentionBacks(_chatText,AJClient.mentionLinks(_chatText),AJClient.MENTION_BACK_DARK); + } + } public function addMessage(param1:String, param2:String, param3:String, param4:String) : void { @@ -217,10 +293,9 @@ package gui var _loc5_:Boolean = false; var _loc6_:* = 0; var _loc7_:int = 0; - var _loc8_:String = null; if(_chatText && param1 != null && param1.length > 0 && param2 && param4) { - _chatText.htmlText += "" + plain(Utility.isSettingOn(MySettings.SETTINGS_USERNAME_BADGE) ? param3 : param1) + ": " + "" + plain(param4) + "\n"; + addLine("" + plain(Utility.isSettingOn(MySettings.SETTINGS_USERNAME_BADGE) ? param3 : param1) + ": " + "",param4,"\n"); if(_chatRepeatWindow && AvatarManager.playerAvatar && param2.toLowerCase() == AvatarManager.playerAvatar.userName.toLowerCase()) { _loc7_ = 0; @@ -254,16 +329,7 @@ package gui } else { - _chatText.htmlText += "\"" + plain(param4) + "\"" + "\n"; - } - if(_chatText.numLines >= 100) - { - _loc8_ = _chatText.htmlText; - _chatText.htmlText = _loc8_.substr(_loc8_.indexOf("\n") + 1); - } - if(!_isOverChatText) - { - _chatText.scrollV = _chatText.maxScrollV; + addLine("\"",param4,"\"" + "\n"); } } @@ -293,11 +359,11 @@ package gui { if(param2 == null) { - _chatText.htmlText += plain(param1) + ": " + plain(param3) + "\n"; + addLine(plain(param1) + ": ",param3,"\n"); } else { - _chatText.htmlText += plain(param1) + " to " + plain(param2) + ": " + plain(param3) + "\n"; + addLine(plain(param1) + " to " + plain(param2) + ": ",param3,"\n"); } } } @@ -322,9 +388,11 @@ package gui public function clearChat() : void { + _lines = []; if(_chatText) { _chatText.htmlText = ""; + AJClient.drawMentionBacks(_chatText,null); } _chatRepeatArray = []; setupRepeatChat(); @@ -582,12 +650,18 @@ package gui { _chatText.addEventListener("mouseDown",chatClickHandler,false,0,true); _chatText.addEventListener("link",onChatLink,false,0,true); + _chatText.addEventListener("scroll",drawMentionBacks,false,0,true); _chatText.addEventListener("mouseOver",overChatText,false,0,true); _chatText.addEventListener("mouseOut",outChatText,false,0,true); _loc13_ = new StyleSheet(); _loc12_ = {}; _loc12_.color = "#ff9900"; _loc13_.setStyle("a:hover",_loc12_); + // tags (withMentions) + _loc13_.setStyle(".mention",{ + "color":"#4ab3f4", + "textDecoration":"underline" + }); _chatText.styleSheet = _loc13_; } chatMsgText.addEventListener("change",onTextFieldChanged,false,0,true); @@ -732,6 +806,12 @@ package gui private function onChatLink(param1:TextEvent) : void { + // a tag: "@name" (withMentions) + if(param1.text && param1.text.charAt(0) == "@") + { + AJClient.openProfile(param1.text.substr(1)); + return; + } if(param1.text && param1.text != "" && param1.text != gMainFrame.userInfo.myUserName) { BuddyManager.showBuddyCard({ diff --git a/swf-src/GuiManager.as b/swf-src/GuiManager.as index 50f2001..c3bfd6e 100644 --- a/swf-src/GuiManager.as +++ b/swf-src/GuiManager.as @@ -382,6 +382,8 @@ package gui } } AJAudio.setupSharedObject(_sharedObj); + // music and sound effects apart (AJClient's sound settings) + AJClient.loadSoundSettings(); PlayerWallManager.init(mainHud.playerWall); } @@ -2829,6 +2831,8 @@ package gui var _loc5_:UserInfo = null; _currRoomDisplayName = param1; _currRoomDisplayNameId = param2; + // for the client's Discord rich presence + AJClient.presenceRoom(param1); if(mainHud.zoneNameTxt) { if(param1.indexOf(gMainFrame.userInfo.myUserName) == 0) diff --git a/swf-src/ItemWindowPost.as b/swf-src/ItemWindowPost.as new file mode 100644 index 0000000..646b5fd --- /dev/null +++ b/swf-src/ItemWindowPost.as @@ -0,0 +1,426 @@ +package gui.itemWindows +{ + import avatar.Avatar; + import avatar.AvatarDef; + import avatar.AvatarUtility; + import avatar.AvatarView; + import avatar.AvatarXtCommManager; + import buddy.Buddy; + import buddy.BuddyList; + import buddy.BuddyManager; + import collection.AccItemCollection; + import com.sbi.corelib.input.SBTextField; + import flash.display.MovieClip; + import flash.events.MouseEvent; + import flash.geom.Point; + import flash.text.TextField; + import flash.utils.setTimeout; + import gui.LoadingSpiral; + import item.EquippedAvatars; + import item.Item; + import loader.MediaHelper; + import localization.LocalizationManager; + import playerWall.PostMessage; + + public class ItemWindowPost extends ItemWindowBase + { + + private var _iconMediaHelper:MediaHelper; + + private var _onReportDown:Function; + + private var _onDeleteDown:Function; + + private var _onReplyDown:Function; + + private var _smileyText:SBTextField; + + // the field the message is drawn in, and its tags once the server has + // said which "@"s are players' (AJClient.resolveMentions) + private var _messageField:TextField; + + private var _mentions:Array = []; + + private var _isMyPost:Boolean; + + private var _patternWindow:ItemWindowPattern; + + private var _hasSetInitialConditions:Boolean; + + public function ItemWindowPost(param1:Function, param2:Object, param3:String, param4:int, param5:Function = null, param6:Function = null, param7:Function = null, param8:Function = null, param9:Object = null) + { + _onReportDown = param9.reportMsgBtnMouseDown; + _onDeleteDown = param9.deleteMsgBtnMouseDown; + _onReplyDown = param9.replyMsgBtnMouseDown; + _isMyPost = param9.isMyPost; + tabEnabled = false; + super(1501,param1,param2,param3,param4,param5,param6,param7,param8); + } + + public function get msgId() : String + { + return _currItem.msgId; + } + + public function get senderUserName() : String + { + return _currItem.senderUserName; + } + + public function get senderModeratedUserName() : String + { + return _currItem.senderModeratedUserName; + } + + public function get parentOrMyPostMessageId() : String + { + if((_currItem as PostMessage).parentMessageId != null) + { + return (_currItem as PostMessage).parentMessageId; + } + return msgId; + } + + public function get sizeCont() : MovieClip + { + return MovieClip(_window.parent).sizeCont; + } + + public function darken(param1:Boolean) : void + { + if(_window) + { + _window.darkCont.visible = param1; + } + } + + public function update() : void + { + var _loc1_:Number = new Date().valueOf(); + _loc1_ += Utility.getTimeOffset(); + var _loc2_:Object = Utility.calculateTime((_loc1_ - _currItem.postTime) / 1000); + if(_loc2_.mins < 0) + { + _loc2_.mins = 0; + } + if(_loc2_.mins == 0 && _loc2_.hours < 1 && _loc2_.days < 1) + { + _window.dark.timeTxt.text = Utility.calculatePrintTimeToNearest(_loc2_.mins,_loc2_.hours,true,_loc2_.days); + } + else + { + LocalizationManager.translateIdAndInsert(_window.dark.timeTxt,11360,Utility.calculatePrintTimeToNearest(_loc2_.mins,_loc2_.hours,true,_loc2_.days)); + } + } + + public function updateWithInput(param1:PostMessage) : void + { + if(_smileyText && param1) + { + _smileyText.text = param1.message; + showMentions(); + } + } + + override public function destroy() : void + { + removeEventListeners(); + if(_iconMediaHelper) + { + _iconMediaHelper.destroy(); + _iconMediaHelper = null; + } + _onReportDown = null; + _onDeleteDown = null; + if(_smileyText) + { + _smileyText.destroy(); + _smileyText = null; + } + _messageField = null; + _window = null; + _windowLoadedCallback = null; + _currItem = null; + _mouseDown = null; + _mouseOver = null; + _mouseOut = null; + } + + override public function loadCurrItem(param1:int = 0, param2:int = 0) : void + { + _itemYLocation = param1; + _itemXLocation = param2; + if(_currItem && !_isCurrItemLoaded) + { + if(!_spiral) + { + _spiral = new LoadingSpiral(_window.iconLayer); + } + else + { + _spiral.setNewParent(_window.iconLayer); + } + _messageField = _window.dark.messageTxt; + _smileyText = new SBTextField(null,_messageField,_window.textItemHolder,true); + _smileyText.text = _currItem.message; + showMentions(); + _smileyText.mouseEnabled = false; + _smileyText.selectable = false; + if(!_isMyPost) + { + _window.reportMessageBtn.x += _window.reportMessageBtn.width; + } + _isCurrItemLoaded = true; + setupCurrAvtImage(); + } + } + + override public function setStatesForVisibility(param1:Boolean, param2:Object = null) : void + { + } + + override protected function onWindowLoadCallback() : void + { + setChildrenAndInitialConditions(); + super.onWindowLoadCallback(); + } + + override protected function setChildrenAndInitialConditions() : void + { + if(!_hasSetInitialConditions) + { + _hasSetInitialConditions = true; + if(_currItem) + { + if(_currItem.senderUserName.toLowerCase() == gMainFrame.userInfo.myUserName.toLowerCase()) + { + if(hasParent()) + { + _window.gotoAndStop("playerReply"); + _window = _window.playerReply; + } + else + { + _window.gotoAndStop("player"); + _window = _window.player; + } + } + else if(hasParent()) + { + _window.gotoAndStop("buddiesReply"); + _window = _window.buddiesReply; + } + else + { + _window.gotoAndStop("buddies"); + _window = _window.buddies; + } + darken(false); + loadPostPattern(); + _window.reportMessageBtn.visible = false; + _window.deleteMessageBtn.visible = false; + _window.replyMessageBtn.visible = false; + _window.updateColor(_currItem.colorId); + _window.dark.messageTxt.text = ""; + _window.dark.messageTxt.selectable = false; + LocalizationManager.updateToFit(_window.dark.nameTxt,_currItem.senderModeratedUserName); + _window.dark.timeTxt.autoSize = "right"; + if(_window.newIcon != null) + { + _window.newIcon.visible = false; + } + if(_currItem.isBuddy && _currItem.senderUserName.toLowerCase() != gMainFrame.userInfo.myUserName.toLowerCase()) + { + _window.buddyIcon.visible = true; + } + else + { + _window.buddyIcon.visible = false; + } + update(); + } + addEventListeners(); + } + } + + override protected function addEventListeners() : void + { + if(_isMyPost) + { + _window.deleteMessageBtn.addEventListener("mouseDown",_onDeleteDown,false,0,true); + } + _window.reportMessageBtn.addEventListener("mouseDown",_onReportDown,false,0,true); + _window.replyMessageBtn.addEventListener("mouseDown",_onReplyDown,false,0,true); + _window.darkCont.addEventListener("mouseDown",onDarkCont,false,0,true); + addEventListener("rollOver",onPostRollOverOut,false,0,true); + addEventListener("rollOut",onPostRollOverOut,false,0,true); + addEventListener("mouseDown",onPostDown,false,0,true); + } + + override protected function removeEventListeners() : void + { + if(_isMyPost) + { + _window.deleteMessageBtn.removeEventListener("mouseDown",_onDeleteDown); + } + _window.reportMessageBtn.removeEventListener("mouseDown",_onReportDown); + _window.replyMessageBtn.removeEventListener("mouseDown",_onReplyDown); + _window.darkCont.removeEventListener("mouseDown",onDarkCont); + removeEventListener("rollOver",onPostRollOverOut); + removeEventListener("rollOut",onPostRollOverOut); + removeEventListener("mouseDown",onPostDown); + } + + // tags: light blue and underlined; a click on one opens that player's + // card (onPostDown), anywhere else the writer's. + private function showMentions() : void + { + var field:TextField = _messageField; + var shown:String = field != null ? field.text : ""; + _mentions = []; + AJClient.drawMentionBacks(field,null); + if(shown.indexOf("@") == -1) + { + return; + } + AJClient.resolveMentions(shown,function(param1:Array):void + { + if(_messageField == field && field.text == shown) + { + _mentions = param1; + AJClient.styleMentions(field,param1,false); + // and their backgrounds, now and once laid out for sure + AJClient.drawMentionBacks(field,param1,AJClient.MENTION_BACK_LIGHT); + setTimeout(function():void + { + if(_messageField == field && field.text == shown) + { + AJClient.drawMentionBacks(field,param1,AJClient.MENTION_BACK_LIGHT); + } + },42); + } + }); + } + + private function hasParent() : Boolean + { + return (_currItem as PostMessage).parentMessageId != null && (_currItem as PostMessage).parentMessageId.length > 0; + } + + private function onDarkCont(param1:MouseEvent) : void + { + param1.stopPropagation(); + } + + private function onPostDown(param1:MouseEvent) : void + { + param1.stopPropagation(); + var _loc2_:String = AJClient.mentionAt(_messageField,_mentions); + if(_loc2_ != null) + { + AJClient.openProfile(_loc2_); + return; + } + if(_window && _currItem.senderUserName.toLowerCase() != gMainFrame.userInfo.myUserName.toLowerCase()) + { + BuddyList.requestBuddyListIfNeeded(onBuddyListRequested); + } + } + + private function onBuddyListRequested() : void + { + var _loc1_:Buddy = BuddyManager.getBuddyByUserName(_currItem.senderUserName); + if(_loc1_) + { + BuddyManager.showBuddyCard({ + "userName":_loc1_.userName, + "onlineStatus":_loc1_.onlineStatus + }); + return; + } + AvatarXtCommManager.requestAvatarGet(_currItem.senderUserName,onUserLookUpReceived,true); + } + + private function onUserLookUpReceived(param1:String, param2:Boolean, param3:int) : void + { + if(param2) + { + BuddyManager.showBuddyCard({ + "userName":param1, + "onlineStatus":param3 + }); + } + } + + private function onPostRollOverOut(param1:MouseEvent) : void + { + param1.stopPropagation(); + if(_window) + { + if(_window.messageHighlight.currentFrameLabel != "on") + { + _window.messageHighlight.gotoAndStop("on"); + _window.reportMessageBtn.visible = _currItem.senderUserName != gMainFrame.userInfo.myUserName; + _window.replyMessageBtn.visible = true; + if(_isMyPost) + { + _window.deleteMessageBtn.visible = true; + } + } + else + { + _window.messageHighlight.gotoAndStop("off"); + _window.reportMessageBtn.visible = false; + _window.replyMessageBtn.visible = false; + if(_isMyPost) + { + _window.deleteMessageBtn.visible = false; + } + } + } + } + + private function loadPostPattern() : void + { + _patternWindow = new ItemWindowPattern(null,3983,"",0,null,null,null,null,{ + "type":(hasParent() ? "reply" : "message"), + "colorIndex":_currItem.colorId, + "patternIndex":_currItem.patternId + }); + _window.messageBodyHolder.addChild(_patternWindow); + } + + private function setupCurrAvtImage() : void + { + var _loc5_:Avatar = new Avatar(); + _loc5_.init(-1,-1,"",_currItem.avtDefId,_currItem.avtColors,_currItem.avtCustomId,null,_currItem.senderUserName); + var _loc3_:AccItemCollection = new AccItemCollection(); + var _loc2_:Item = new Item(); + _loc3_.setAccItem(0,_loc2_); + _loc2_.init(1,1,0,EquippedAvatars.forced()); + _loc2_ = new Item(); + _loc3_.setAccItem(1,_loc2_); + _loc2_.init(_currItem.avtEyeDefId > 0 ? _currItem.avtEyeDefId : 2,2,0,EquippedAvatars.forced()); + var _loc6_:AvatarDef = gMainFrame.userInfo.getAvatarDefByAvatar(_loc5_); + if(_currItem.avtCustomId != -1 && _loc6_ && _currItem.avtPatternDefId < 1) + { + _currItem.avtPatternDefId = _loc6_.patternRefIds[0]; + } + if(_currItem.avtPatternDefId > 0) + { + _loc2_ = new Item(); + _loc3_.setAccItem(2,_loc2_); + _loc2_.init(_currItem.avtPatternDefId,3,0,EquippedAvatars.forced()); + } + _loc5_.itemResponseIntegrate(_loc3_); + var _loc1_:AvatarView = new AvatarView(); + _loc1_.init(_loc5_,null); + _loc1_.playAnim(15,false,1,null,true); + var _loc4_:Point = AvatarUtility.getAvatarHudPosition(_loc1_.avTypeId); + _loc1_.x = _loc4_.x + _window.charCont.width * 0.5; + _loc1_.y = _loc4_.y + _window.charCont.height * 0.5; + _window.charCont.charLayer.addChild(_loc1_); + } + } +} + diff --git a/swf-src/ItemWindowToggle.as b/swf-src/ItemWindowToggle.as index 7006907..fe5e38f 100644 --- a/swf-src/ItemWindowToggle.as +++ b/swf-src/ItemWindowToggle.as @@ -138,7 +138,13 @@ package gui.itemWindows _window.scrubBtn.scrubBG.gotoAndStop("up"); _window.scrubBtn.addEventListener("rollOver",handleMouseOver,false,0,true); _window.scrubBtn.addEventListener("rollOut",handleMouseOut,false,0,true); - if(GuiManager.sharedObj && GuiManager.sharedObj.data.volume != null) + if(_currItem.sound) + { + // music or sound effects (AJClient's sound settings) + _window.scrubBtn.scrubKnob.x = AJClient.soundVolume(_currItem.sound) * 82 + 15; + _window.labelTxtCont.labelTxt.text = _currItem.labelLabel; + } + else if(GuiManager.sharedObj && GuiManager.sharedObj.data.volume != null) { _window.scrubBtn.scrubKnob.x = GuiManager.sharedObj.data.volume * 82 + 15; } @@ -767,7 +773,15 @@ package gui.itemWindows param1.stopPropagation(); if(_currItem.type == MySettings.TOGGLE_TYPE_SCRUB && _window.scrubBtn.scrubKnob.dragging) { - SBAudio.setVolumeAll((int(_window.scrubBtn.scrubKnob.x - 15)) / 82); + if(_currItem.sound) + { + // heard as it moves, kept when let go (handleStopScrubbing) + AJClient.setSoundVolume(_currItem.sound,(int(_window.scrubBtn.scrubKnob.x - 15)) / 82,false); + } + else + { + SBAudio.setVolumeAll((int(_window.scrubBtn.scrubKnob.x - 15)) / 82); + } } } @@ -843,7 +857,13 @@ package gui.itemWindows private function handleStopScrubbing() : void { - if(_window.scrubBtn.scrubKnob.dragging) + if(_window.scrubBtn.scrubKnob.dragging && _currItem.sound) + { + _window.scrubBtn.scrubKnob.dragging = false; + _window.scrubBtn.scrubKnob.stopDrag(); + AJClient.setSoundVolume(_currItem.sound,(int(_window.scrubBtn.scrubKnob.x - 15)) / 82); + } + else if(_window.scrubBtn.scrubKnob.dragging) { _window.scrubBtn.scrubKnob.dragging = false; _window.scrubBtn.scrubKnob.stopDrag(); diff --git a/swf-src/MySettings.as b/swf-src/MySettings.as index 6e4d8cd..966ea01 100644 --- a/swf-src/MySettings.as +++ b/swf-src/MySettings.as @@ -268,15 +268,17 @@ package gui "onTxt":6324, "offTxt":6322 },{ - "type":TOGGLE_TYPE_TOGGLE_BTN, - "frame":"music", - "labelTxt":6373, - "onTxt":6324, - "offTxt":6322 + // music and sound effects apart, a volume each (AJClient's + // sound settings), for the game's one sound switch and volume + "type":TOGGLE_TYPE_SCRUB, + "frame":"", + "sound":"music", + "labelLabel":"Music" },{ "type":TOGGLE_TYPE_SCRUB, "frame":"", - "labelTxt":14666 + "sound":"sfx", + "labelLabel":"SFX" },{ "type":TOGGLE_TYPE_CURSOR, "frame":"", diff --git a/swf-src/SBMusic.as b/swf-src/SBMusic.as new file mode 100644 index 0000000..ac011f9 --- /dev/null +++ b/swf-src/SBMusic.as @@ -0,0 +1,251 @@ +package com.sbi.corelib.audio +{ + import com.sbi.loader.LoaderCache; + import flash.events.IOErrorEvent; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.media.SoundLoaderContext; + import flash.media.SoundTransform; + import flash.net.URLRequest; + import flash.utils.Dictionary; + + public class SBMusic + { + + private var _hashKey:String; + + private var _previouslyPlayedFilename:String; + + private var _currFilename:String; + + private var _previousVolume:Number; + + private var _currVolume:Number; + + public var paused:Boolean = false; + + public var muted:Boolean = false; + + public var mutedVolume:Number = 1; + + public var playVolume:Number = 1; + + public var s:Sound; + + public var sc:SoundChannel; + + public var position:Number; + + // every piece of music, for the music setting (AJClient.musicLevel): + // each plays at the volume the game gives it times that setting, and + // again so when the setting changes (refreshAll). + private static var _all:Dictionary = new Dictionary(true); + + private var _setVolume:Number = 1; + + public static function refreshAll() : void + { + var _loc1_:Object = null; + var _loc2_:SBMusic = null; + for(_loc1_ in _all) + { + _loc2_ = _loc1_ as SBMusic; + if(_loc2_ != null && _loc2_.sc != null) + { + _loc2_.setTransformVolume(_loc2_._setVolume); + } + } + } + + public function SBMusic(param1:String, param2:Boolean = true, param3:Number = 1, param4:Number = 1000, param5:Boolean = true) + { + super(); + _all[this] = true; + playNewMusic(param1,param2,param3,param4,param5); + SBAudio.addMusic(this); + } + + public function playNewMusic(param1:String, param2:Boolean = true, param3:Number = 1, param4:Number = 1000, param5:Boolean = true) : void + { + _previouslyPlayedFilename = _currFilename; + _currFilename = param1; + _previousVolume = _currVolume; + _currVolume = param3 * SBAudio.currentVolume; + var _loc6_:URLRequest = LoaderCache.fetchCDNURLRequest("audio/" + param1); + if(s) + { + s.removeEventListener("ioError",handleIOError); + s = null; + } + if(sc) + { + sc.stop(); + sc = null; + } + s = new Sound(_loc6_,new SoundLoaderContext(param4,param5)); + volume = _currVolume; + if(param2) + { + play(); + } + else + { + stop(); + } + s.addEventListener("ioError",handleIOError,false,0,true); + } + + public function play(param1:Number = 0, param2:int = 2147483647, param3:SoundTransform = null) : void + { + if(s == null) + { + return; + } + sc = s.play(param1,param2,param3); + if(sc == null) + { + return; + } + setTransformVolume(playVolume); + } + + // the game's own volume for it, before the music setting + public function get volume() : Number + { + return sc ? _setVolume : -1; + } + + public function set volume(param1:Number) : void + { + if(muted) + { + mutedVolume = param1; + } + else + { + playVolume = param1; + } + if(sc) + { + setTransformVolume(param1); + } + } + + public function toggleMute() : void + { + if(muted) + { + unmute(); + } + else + { + mute(); + } + } + + public function mute() : void + { + if(!muted) + { + mutedVolume = volume; + volume = 0; + muted = true; + } + } + + public function unmute() : void + { + if(muted) + { + volume = mutedVolume; + muted = false; + } + } + + public function togglePause() : void + { + if(paused) + { + unpause(); + } + else + { + pause(); + } + } + + public function pause() : void + { + if(s && sc && !paused) + { + position = sc.position; + sc.stop(); + paused = true; + } + } + + public function unpause() : void + { + if(s && sc && paused) + { + sc = s.play(position); + setTransformVolume(playVolume); + paused = false; + } + } + + public function stop() : void + { + if(sc) + { + sc.stop(); + } + paused = false; + muted = false; + } + + public function get previouslyPlayedFilename() : String + { + return _previouslyPlayedFilename; + } + + public function get previousVolume() : Number + { + return _previousVolume; + } + + public function get currFilename() : String + { + return _currFilename; + } + + public function get currVolume() : Number + { + return _currVolume; + } + + private function setTransformVolume(param1:Number) : void + { + _setVolume = param1; + var _loc2_:SoundTransform = sc.soundTransform; + _loc2_.volume = param1 * AJClient.musicLevel(); + sc.soundTransform = _loc2_; + } + + private function handleIOError(param1:IOErrorEvent) : void + { + if(s) + { + trace("WARNING - IOError while attempting to load music:" + s.url); + s = null; + } + if(sc) + { + sc.stop(); + sc = null; + } + SBAudio.removeMusic(this); + } + } +} + diff --git a/swf-src/SBSound.as b/swf-src/SBSound.as new file mode 100644 index 0000000..57913d2 --- /dev/null +++ b/swf-src/SBSound.as @@ -0,0 +1,184 @@ +package com.sbi.corelib.audio +{ + import flash.events.Event; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.media.SoundTransform; + import flash.utils.Dictionary; + + public class SBSound + { + + public var paused:Boolean = false; + + public var playVolume:Number = 1; + + public var s:Sound; + + public var sc:SoundChannel; + + private var _soundPlaying:Boolean; + + private var _onSoundComplete:Function; + + // every sound effect, for the sound effects setting (AJClient.sfxLevel): + // each plays at the volume the game gives it times that setting, and + // again so when the setting changes (refreshAll). + private static var _all:Dictionary = new Dictionary(true); + + private var _setVolume:Number = 1; + + public static function refreshAll() : void + { + var _loc1_:Object = null; + var _loc2_:SBSound = null; + for(_loc1_ in _all) + { + _loc2_ = _loc1_ as SBSound; + if(_loc2_ != null && _loc2_.sc != null) + { + _loc2_.setTransformVolume(_loc2_._setVolume); + } + } + } + + public function SBSound(param1:Class, param2:Boolean = true, param3:Number = 1) + { + super(); + _all[this] = true; + s = new param1(); + volume = param3; + if(param2) + { + play(); + } + else + { + stop(); + } + SBAudio.addSound(this); + } + + public function play(param1:Number = 0, param2:int = 0, param3:SoundTransform = null, param4:Function = null) : void + { + if(param2 == -1) + { + param2 = 2147483647; + } + if(s == null) + { + return; + } + sc = s.play(param1,param2,param3); + if(sc == null) + { + return; + } + _soundPlaying = true; + _onSoundComplete = param4; + sc.addEventListener("soundComplete",soundStoppedHandler,false,0,true); + setTransformVolume(playVolume); + } + + public function destroy() : void + { + stop(); + sc = null; + s = null; + SBAudio.removeSound(this); + } + + // the game's own volume for it, before the sound effects setting + public function get volume() : Number + { + return sc ? _setVolume : -1; + } + + public function set volume(param1:Number) : void + { + playVolume = param1; + if(sc) + { + setTransformVolume(param1); + } + } + + public function get isPlaying() : Boolean + { + return _soundPlaying; + } + + public function togglePause() : void + { + if(paused) + { + unpause(); + } + else + { + pause(); + } + } + + public function pause() : void + { + if(sc && !paused) + { + sc.stop(); + paused = true; + _soundPlaying = false; + } + } + + public function unpause() : void + { + if(s && sc && paused) + { + sc = s.play(sc.position); + if(sc == null) + { + return; + } + _soundPlaying = true; + sc.addEventListener("soundComplete",soundStoppedHandler,false,0,true); + setTransformVolume(playVolume); + paused = false; + } + } + + public function stop() : void + { + if(sc) + { + sc.stop(); + } + paused = false; + _soundPlaying = false; + } + + private function setTransformVolume(param1:Number) : void + { + _setVolume = param1; + var _loc2_:SoundTransform = sc.soundTransform; + if(SBAudio.isMusicMuted) + { + _loc2_.volume = 0; + } + else + { + _loc2_.volume = param1 * AJClient.sfxLevel(); + } + sc.soundTransform = _loc2_; + } + + private function soundStoppedHandler(param1:Event) : void + { + _soundPlaying = false; + if(_onSoundComplete != null) + { + _onSoundComplete(); + } + } + } +} + diff --git a/swf-src/SoundManager.as b/swf-src/SoundManager.as index eda1ab4..2d11880 100644 --- a/swf-src/SoundManager.as +++ b/swf-src/SoundManager.as @@ -194,7 +194,8 @@ package game } else { - _loc5_ = Number(_soundVolume[_loc8_]); + // times the sound effects setting (AJClient.sfxLevel) + _loc5_ = Number(_soundVolume[_loc8_]) * AJClient.sfxLevel(); } _loc7_ = new SoundTransform(_loc5_,0); if(_soundLimit > 0) @@ -234,7 +235,7 @@ package game } else { - _loc4_ = Number(_soundVolume[_loc7_]); + _loc4_ = Number(_soundVolume[_loc7_]) * AJClient.sfxLevel(); } _loc6_ = new SoundTransform(_loc4_,0); if(_soundLimit > 0) @@ -276,9 +277,8 @@ package game gMainFrame.stage.removeEventListener("enterFrame",doFadeIn); } var _loc2_:Number = _musicVolume[_fadeInStream] * _loc4_; - var _loc5_:SoundChannel = _fadeInStream.sc; - var _loc3_:SoundTransform = new SoundTransform(_loc2_,0); - _fadeInStream.sc.soundTransform = _loc3_; + // through SBMusic's volume, which takes the music setting + _fadeInStream.volume = _loc2_; if(_loc4_ == 1) { _fadeInStream = null; @@ -301,8 +301,7 @@ package game gMainFrame.stage.removeEventListener("enterFrame",doFadeOut); } var _loc2_:Number = _musicVolume[_fadeOutStream] * (1 - _loc4_); - var _loc3_:SoundTransform = new SoundTransform(_loc2_,0); - _fadeOutStream.sc.soundTransform = _loc3_; + _fadeOutStream.volume = _loc2_; if(_loc4_ == 1) { _fadeOutStream.sc.stop(); @@ -374,7 +373,7 @@ package game _loc6_ = new SoundTransform(_loc5_,0); if(_fadeOutStream.sc != null) { - _fadeOutStream.sc.soundTransform = _loc6_; + _fadeOutStream.volume = _loc5_; return _fadeOutStream.sc; } return null; @@ -397,7 +396,8 @@ package game return null; } _musicChannel[param1] = param1.sc; - param1.sc.soundTransform = _loc6_; + // the stream's volume through SBMusic, which takes the music setting + param1.volume = _loc6_.volume; if(SBAudio.isMusicMuted) { param1.mute(); diff --git a/swf-src/XtReplyDemuxer.as b/swf-src/XtReplyDemuxer.as index 1f0529f..44264b0 100644 --- a/swf-src/XtReplyDemuxer.as +++ b/swf-src/XtReplyDemuxer.as @@ -119,6 +119,11 @@ package AJClient.onInvisible(param1.obj); return; } + if(param1.obj[0] == "xmn") + { + AJClient.onMentions(param1.obj); + return; + } if(param1.obj[0] == "xty") { AJClient.onTyping(param1.obj); diff --git a/swf/ajclient.swf b/swf/ajclient.swf index 9a1400f..ceba6a7 100644 Binary files a/swf/ajclient.swf and b/swf/ajclient.swf differ diff --git a/test/qol.js b/test/qol.js index 2be6b32..1eba684 100644 --- a/test/qol.js +++ b/test/qol.js @@ -164,8 +164,10 @@ const run = async () => { assert.match(await told(a), /0 read Jam-A-Grams deleted/); say(a, roomId, "!music all"); const tracks = await a.untilXt("di"); - assert.match(await told(a), /66 music tracks added/); - assert.ok(Number(tracks[3]) >= 66); + // the game's 55 tracks and this server's own (lib/extramusic.js) + const allTracks = 55 + require("../lib/extramusic.js").TRACKS.length; + assert.match(await told(a), new RegExp(`${allTracks} music tracks added`)); + assert.ok(Number(tracks[3]) >= allTracks); say(a, roomId, "!music all"); await a.untilXt("di"); assert.match(await told(a), /every music track already/); diff --git a/test/smoke.js b/test/smoke.js index 0c07c20..a5e854f 100644 --- a/test/smoke.js +++ b/test/smoke.js @@ -339,7 +339,10 @@ const run = async () => { a.xt("al", denId, "Alice"); assert.deepStrictEqual((await a.nextXt("al")).slice(5, 7), ["2", aa[3]]); a.xt("ak", denId, aa[3]); // cannot remove the animal in use - assert.strictEqual((await a.nextXt("ak"))[2], "0"); + const notRemoved = await a.nextXt("ak"); + assert.strictEqual(notRemoved[2], "0"); + // the second field is the gems the animal switcher then shows: the total + assert.ok(Number(notRemoved[3]) > 0, `gems after "ak": ${notRemoved[3]}`); a.xt("gl", denId, 312); const petShop = await a.nextXt("gl"); @@ -427,6 +430,10 @@ const run = async () => { assert.strictEqual((await giveJson({username: "Alice", kind: "clothing", id: hat.id, colorIndex: 0})).status, 200); const pushed = await a.nextXt("il"); assert.deepStrictEqual([pushed[2], pushed[10]], ["2", String(hat.id)]); + // a colour id written signed is the same colour, kept unsigned (lib/admin.js) + assert.strictEqual((await giveJson({username: "Alice", kind: "clothing", id: hat.id, color: "-16777216"})).status, 200); + assert.strictEqual((await a.nextXt("il"))[6], "4278190080"); + assert.strictEqual((await giveJson({username: "Alice", kind: "clothing", id: hat.id, color: "-99999999999"})).status, 400); assert.strictEqual((await giveJson({username: "Alice", kind: "clothing", id: 1})).status, 400); assert.strictEqual((await giveJson({username: "Nobody", kind: "den", id: 6})).status, 404); assert.strictEqual((await giveJson({username: "Alice", kind: "den", id: 6})).status, 200); @@ -608,7 +615,10 @@ const run = async () => { await a.untilXt("il"); a.xt("il", denId, "Alice", 1, 1); assert.ok((await a.untilXt("il")).includes("123456789")); - assert.strictEqual((await giveJson({username: "Alice", kind: "clothing", id: hat.id, color: "-5"})).status, 400); + // negative: the same colour written signed (-5 is 4294967291); not a number at all is refused + assert.strictEqual((await giveJson({username: "Alice", kind: "clothing", id: hat.id, color: "-5"})).status, 200); + assert.ok((await a.untilXt("il")).includes("4294967291")); + assert.strictEqual((await giveJson({username: "Alice", kind: "clothing", id: hat.id, color: "5x"})).status, 400); // --- the item defs clients get: ocean eyes (314) allowed on every animal const {decode} = require("../lib/amf3.js"); diff --git a/tools/build-client.sh b/tools/build-client.sh index 1476a0d..c7f304d 100755 --- a/tools/build-client.sh +++ b/tools/build-client.sh @@ -67,6 +67,7 @@ set -- \ room.RoomManagerWorld RoomManagerWorld.as \ gskinner.motion.GTween GTween.as \ playerWall.PostMessage PostMessage.as \ + gui.itemWindows.ItemWindowPost ItemWindowPost.as \ shop.BundleShop BundleShop.as \ gui.GenericListGuiManager GenericListGuiManager.as \ gui.DenSwitcher DenSwitcher.as \ @@ -77,6 +78,8 @@ set -- \ Party.PartyPopup PartyPopup.as \ gui.ECardInbox ECardInbox.as \ game.SoundManager SoundManager.as \ + com.sbi.corelib.audio.SBMusic SBMusic.as \ + com.sbi.corelib.audio.SBSound SBSound.as \ com.sbi.graphics.LayerAnim LayerAnim.as \ com.sbi.graphics.LayerBitmap LayerBitmap.as \ ecard.ECard ECard.as \