diff --git a/.github/allowed-hosts.json b/.github/allowed-hosts.json index 239b425..385df90 100644 --- a/.github/allowed-hosts.json +++ b/.github/allowed-hosts.json @@ -2,8 +2,10 @@ "server": [ "ajcontent.akamaized.net", "burrow.moe", + "cdn.jsdelivr.net", "challenges.cloudflare.com", "play.burrow.moe", + "vision.googleapis.com", "www.cloudflare.com", "www.w3.org" ], diff --git a/README.md b/README.md index 56219c0..db685fe 100644 --- a/README.md +++ b/README.md @@ -12,3 +12,6 @@ Every push to this repository is checked automatically (`.github/workflows/secur Burrow is an unofficial fan project. It is not affiliated with, endorsed by or connected to WildWorks, Inc. or Animal Jam. Animal Jam and Animal Jam Classic are trademarks of WildWorks, Inc. **Takedown procedure: WildWorks, Inc. or its authorized representatives may request the removal of content, or of Burrow as a whole, by writing to legal@burrow.moe. Upon verification of authority, the request will be carried out promptly.** + +# Credits +Emoji in chat are drawn with [Twemoji](https://github.com/jdecked/twemoji), © Twitter, Inc. and other contributors, under [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/). diff --git a/config.js b/config.js index 06355a7..1d4425b 100644 --- a/config.js +++ b/config.js @@ -3,6 +3,7 @@ const path = require("path"); const env = process.env; +const googleVisionApiKey = env.AJ_GOOGLE_VISION_API_KEY; const LOOPBACK_NAMES = ["127.0.0.1", "::1", "localhost"]; const bindAddress = env.AJ_BIND || "127.0.0.1"; const httpPort = Number(env.AJ_HTTP_PORT || 8080); @@ -84,6 +85,13 @@ module.exports = { // cookies are only sent back over an encrypted connection when players // have one, whoever does the encrypting. secureCookies: baseUrl.startsWith("https:"), + // Google Cloud Vision SafeSearch, used for player-uploaded custom item art + // and masterpieces. Off when no key is configured (useful for local work). + // When on, a Google outage rejects uploads rather than letting unscanned + // images through. + googleVision: googleVisionApiKey ? { + endpoint: `https://vision.googleapis.com/v1/images:annotate?key=${encodeURIComponent(googleVisionApiKey)}`, + } : null, // the admin panel answers this machine alone on a public server (reach it // through an SSH tunnel), plus the addresses listed in AJ_ADMIN_ALLOW, // separated by commas. on a local server it answers whoever can reach it. @@ -97,6 +105,8 @@ module.exports = { // asset mirror: anything not served locally is fetched once from here and // cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only. upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/", + // 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 @@ -263,9 +273,11 @@ module.exports = { // can switch in the settings menu (gui.ServerSelector). the game names // world N after the Nth name of its own list (551 Aldan, 552 Congo..., // generic list 16), so the names here are only for the panels and logs. - // AJ_WORLDS: how many (the tests' is one). + // AJ_WORLDS: how many. A local server starts with one shared world so two + // players in the same land can always see one another; set AJ_WORLDS=2 or + // more to opt into separate copies of every land. shards: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"] - .slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 2))).map((name, i) => ({id: i + 1, name})), + .slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 1))).map((name, i) => ({id: i + 1, name})), maxUsersPerRoom: 40, // everything in every shop for nothing (AJ_FREE_SHOPS=1). off unless // asked for: what the game's shops make of a price of 0 has not been seen. @@ -301,9 +313,22 @@ module.exports = { tlsHandshakeTimeoutMs: 10000, maxMessagesPerTenSeconds: 400, // per game socket; walking sends a few a second loginTimeoutMs: 30000, // a game socket must log in within this - idleTimeoutMs: 15 * 60000, // the client sends a keep-alive far more often + // a client sends nothing while its player is away, and signs itself out + // after 75 minutes of that (com.sbi.client.KeepAlive): the socket waits longer. + idleTimeoutMs: 80 * 60000, tokenLifetimeDays: 30, // login tokens kept by the launcher's "remember me" - maxChatLength: 300, + // a line as sent: the client's chat box takes 200 (gui.ChatHistory), and + // each emoji goes as a tag of 8 or more ("\{1f600}"). lib/chatspam.js + // cuts down what is long for no good reason. + maxChatLength: 600, + // how old an account must be before it may give its items pictures + // (lib/playeritems.js), so a picture turned away is not simply sent again + // from a new account. not for this machine's own requests (AJ_ITEM_ART_MIN_HOURS). + itemArtMinAccountHours: Number(env.AJ_ITEM_ART_MIN_HOURS || 24), + // warnings (lib/moderation.js warn): the Nth one within `days` also + // silences the player for that many minutes, [[N, minutes], ...]. a + // longer silence already on them stays. steps [] turns it off. + warningSilence: {days: 30, steps: [[3, 60], [5, 24 * 60]]}, // days typed chat and whispers are kept for the moderator panel's chat // history (lib/chatlog.js); 0 keeps none. chatLogDays: env.AJ_CHAT_LOG_DAYS === undefined ? 30 : Math.max(0, Number(env.AJ_CHAT_LOG_DAYS) || 0), diff --git a/lib/accounts.js b/lib/accounts.js index 210bfcc..c9c370d 100644 --- a/lib/accounts.js +++ b/lib/accounts.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); @@ -348,7 +349,7 @@ const importLegacyFile = () => { } db.exec("COMMIT"); fs.renameSync(file, `${file}.imported`); - console.log(`[accounts] imported ${byKey.size} accounts from accounts.json`); + console.log(`[accounts] imported ${logText(byKey.size)} accounts from accounts.json`); }; const load = () => { @@ -391,7 +392,7 @@ const load = () => { // runs the server is told which, to rename by hand if they see fit. const unusual = [...byId.values()].filter(account => names.refused(account.username)).map(account => account.username); if (unusual.length) { - console.log(`[accounts] usernames that could not be chosen today: ${unusual.slice(0, 50).join(", ")}${unusual.length > 50 ? ", ..." : ""}`); + console.log(`[accounts] usernames that could not be chosen today: ${logText(unusual.slice(0, 50).join(", "))}${logText(unusual.length > 50 ? ", ..." : "")}`); } // once: the Early Member badge for the accounts that were there before // it existed, the oldest hundred of them. @@ -414,7 +415,7 @@ const load = () => { for (const row of db.prepare("SELECT token, account_id, created_at FROM tokens").all()) { tokens.set(row.token, {id: row.account_id, createdAt: row.created_at}); } - console.log(`[accounts] ${byKey.size} accounts in ${path.join(config.dataDir, "game.sqlite")}`); + console.log(`[accounts] ${logText(byKey.size)} accounts in ${logText(path.join(config.dataDir, "game.sqlite"))}`); }; // Which accounts a save looks at. turning an account into JSON to see @@ -638,7 +639,7 @@ const backup = async () => { for (const name of old) { fs.unlinkSync(path.join(folder, name)); } - console.log(`[accounts] backup written: ${file}`); + console.log(`[accounts] backup written: ${logText(file)}`); }; const startBackups = () => { const attempt = () => { @@ -671,9 +672,26 @@ const retire = key => { // A new password: ten characters or more, with a capital letter, a small // one and a digit among them. passwords chosen before this rule still sign // in; it is asked of the next one. -const passwordProblem = password => - (typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH - || !/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password) ? "invalid_password" : null); +// the words most often under a password that meets the rules ("Password123", +// "Sunshine2024"): with its digits and signs taken off, a password that is +// one of these is refused, as is one with the username in it. +const COMMON_PASSWORD_WORDS = new Set(["password", "passw", "pass", "qwerty", "qwertyuiop", "asdfgh", "asdfghjkl", "zxcvbn", "abcdef", "abcdefg", + "abcdefgh", "abcdefghij", "welcome", "letmein", "iloveyou", "admin", "administrator", "monkey", "dragon", "football", "baseball", "soccer", + "sunshine", "princess", "starwars", "superman", "batman", "master", "shadow", "michael", "jennifer", "charlie", "freedom", "whatever", + "trustno", "hello", "secret", "login", "changeme", "animaljam", "animal", "jamaa", "jammer", "wildworks", "burrow", "summer", "winter", + "spring", "autumn", "january", "minecraft", "roblox", "fortnite", "pokemon", "computer", "internet", "cookie", "chocolate", "butterfly"]); +const passwordProblem = (password, username = "") => { + if (typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH + || !/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password)) { + return "invalid_password"; + } + const lower = password.toLowerCase(); + const name = String(username || "").toLowerCase().replace(/[^a-z0-9]/g, ""); + if (COMMON_PASSWORD_WORDS.has(lower.replace(/[^a-z]/g, "")) || (name.length >= 3 && lower.replace(/[^a-z0-9]/g, "").includes(name))) { + return "weak_password"; + } + return null; +}; // creates an account. `avatar` gives the first animal's {type, name}; the // name may be left out, and is then the player's. there is no default @@ -682,7 +700,7 @@ const passwordProblem = password => // "invalid_password" | "choose_animal"}. const register = (username, password, avatar = {}) => { username = typeof username === "string" ? username.trim() : username; - const error = usernameProblem(username) || passwordProblem(password) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal"); + const error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal"); if (error) { return {error}; } @@ -694,7 +712,7 @@ const register = (username, password, avatar = {}) => { // early Member, for an account made while there are no more than a hundred. badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [], }); - console.log(`[accounts] registered "${username}" (id ${account.id})`); + console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`); return {account}; }; @@ -740,9 +758,10 @@ const authenticateAsync = async (username, password) => { }; // gives the account a new password and signs it out everywhere. returns -// "invalid_password" when the password is not acceptable, else null. +// "invalid_password" (the rules) or "weak_password" (a common one, or the +// username in it) when the password is not acceptable, else null. const setPassword = (account, password) => { - const problem = passwordProblem(password); + const problem = passwordProblem(password, account.username); if (problem) { return problem; } @@ -791,7 +810,7 @@ const rename = (account, username, anyName = false) => { db.prepare("DELETE FROM retired_names WHERE name_key = ?").run(newKey); } db.prepare("UPDATE accounts SET username = ?, username_key = ? WHERE id = ?").run(username, newKey, account.id); - console.log(`[accounts] renamed "${account.username}" to "${username}" (id ${account.id})`); + console.log(`[accounts] renamed "${logText(account.username)}" to "${logText(username)}" (id ${logText(account.id)})`); byKey.delete(oldKey); account.username = username; byKey.set(newKey, account); @@ -850,7 +869,7 @@ const remove = account => { } } save(...named); - console.log(`[accounts] deleted "${account.username}" (id ${account.id})`); + console.log(`[accounts] deleted "${logText(account.username)}" (id ${logText(account.id)})`); }; // small server-wide values kept in the database (the admin panel's password). diff --git a/lib/admin.js b/lib/admin.js index bada434..ad4c6f6 100644 --- a/lib/admin.js +++ b/lib/admin.js @@ -6,7 +6,10 @@ const captcha = require("./captcha.js"); const defpacks = require("./defpacks.js"); const devices = require("./devices.js"); const config = require("../config.js"); +const roles = require("./roles.js"); const dens = require("./dens.js"); +const itemControl = require("./itemcontrol.js"); +const customItems = require("./customitems.js"); const limits = require("./limits.js"); const world = require("./world.js"); const {addClothing, sendClothingAdded, isUint} = require("./player.js"); @@ -22,6 +25,7 @@ const MAX_FAVOURITES = 200; // finder items remembered per account const STARTER_ANIMALS = [1, 4, 5, 6, 7, 8, 13, 18, 24]; let catalog = null; +let catalogVersion = -1; // defpacks.customVersion() it was built at: staff add items as the server runs const buildCatalog = () => [ ...defpacks.clothingIds().map(id => { @@ -36,13 +40,23 @@ const buildCatalog = () => [ // `favourites` is an account's finderGiven, or null: with nothing typed, the // items that account took most often come first, the latest first among -// equals. (The in-game finder says whose search it is.) -const search = (params, favourites = null) => { - catalog = catalog || buildCatalog(); +// equals. (The in-game finder says whose search it is.) items locked out of +// the finder (lib/itemcontrol.js) are left out, unless `seesLocked`: then +// they are marked. an item a player made (lib/playeritems.js) is found by +// its maker only (`askerId`), and by those who see locked ones. with +// "base=1", only the game's own items that can be made into a new one. +const search = (params, favourites = null, seesLocked = false, askerId = null) => { + if (!catalog || catalogVersion !== defpacks.customVersion()) { + catalog = buildCatalog(); + catalogVersion = defpacks.customVersion(); + } const kind = params.get("kind") || "all"; const words = (params.get("q") || "").toLowerCase().split(/\s+/).filter(Boolean); const matches = catalog.filter(entry => (kind === "all" || entry.kind === kind) - && words.every(word => entry.search.includes(word) || String(entry.id) === word)); + && words.every(word => entry.search.includes(word) || String(entry.id) === word) + && (seesLocked || !itemControl.isLocked(entry.kind, entry.id)) + && (seesLocked || [null, askerId].includes(customItems.ownerOf(entry.kind, entry.id))) + && (params.get("base") !== "1" || customItems.copyable(entry.kind, entry.id))); matches.sort((a, b) => words.includes(String(b.id)) - words.includes(String(a.id))); if (words.length === 0 && favourites) { const taken = entry => favourites[`${entry.kind}:${entry.id}`] || {count: 0, at: 0}; @@ -50,7 +64,10 @@ const search = (params, favourites = null) => { } return { total: matches.length, - results: matches.slice(0, MAX_RESULTS).map(({kind: entryKind, id, name, cost, colors}) => ({kind: entryKind, id, name, cost, colors})), + results: matches.slice(0, MAX_RESULTS).map(({kind: entryKind, id, name, cost, colors}) => { + const locked = seesLocked && itemControl.isLocked(entryKind, id); + return {kind: entryKind, id, name: locked ? `${name} (locked)` : name, cost, colors, ...(locked ? {locked} : {})}; + }), }; }; @@ -58,11 +75,19 @@ const search = (params, favourites = null) => { // digits alone are a colour id const HEX_COLOURS = /^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i; -const give = body => { +// `seesLocked`: who asks may take items locked out of the finder. +const give = (body, seesLocked = false) => { const account = accounts.byName(body.username); if (!account) { return {status: 404, body: {error: "No such account"}}; } + const maker = customItems.ownerOf(body.kind, body.id); + if (!seesLocked && maker !== null && maker !== account.id) { + return {status: 403, body: {error: "That item is another player's own."}}; + } + if (!seesLocked && itemControl.isLocked(body.kind, body.id)) { + return {status: 403, body: {error: "That item is locked out of the item finder."}}; + } const session = world.findOnline(account.username); if (body.kind === "clothing") { const def = defpacks.itemDef(body.id); @@ -126,6 +151,11 @@ const give = body => { const FORBIDDEN = {status: 403, body: {error: "forbidden"}}; +// may whoever asks see and take items locked out of the finder? staff who +// may lock them (admins and developers) do; so does the owner, on this +// machine, asking with no account's token (the /shop page). +const seesLocked = (account, from) => (account ? roles.can(account, "items.create") : from.local); + // the account a login token is for, while it may play. A ban leaves the // token alone (so that the client can ask about the ban with it, below), // and it is good for nothing else until the ban is over. @@ -143,7 +173,8 @@ const handle = async (route, params, body, from) => { case "GET /api/search": { const asking = accounts.byName(params.get("username") || ""); const known = asking && (from.local || holderOf(params.get("token")) === asking); - return {status: 200, body: search(params, known ? asking.finderGiven : null)}; + return {status: 200, body: search(params, known ? asking.finderGiven : null, seesLocked(params.get("token") ? holderOf(params.get("token")) : null, from), + known ? asking.id : null)}; } case "GET /api/accounts": if (!from.local) { @@ -158,7 +189,7 @@ const handle = async (route, params, body, from) => { if (!from.local && !givesPerMinute.allow(owner.id)) { return {status: 429, body: {error: "Too many at once. Try again in a minute."}}; } - return give(body || {}); + return give(body || {}, seesLocked((body || {}).token ? owner : null, from)); } case "POST /api/theme": { const account = accounts.byName((body || {}).username); @@ -256,4 +287,4 @@ const handle = async (route, params, body, from) => { } }; -module.exports = {handle}; +module.exports = {handle, search}; diff --git a/lib/adventures.js b/lib/adventures.js index deccda4..f06fe64 100644 --- a/lib/adventures.js +++ b/lib/adventures.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); // adventures. the engine is in the client (quest/QuestManager): it places // the actors named in the room file and plays them. what happens when was // decided by scripts on the official server, which no file holds, so each @@ -145,7 +146,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => { family[1](tools(session, quest), key, ...args); } else if (key !== null && kind !== "pickedUp") { - console.log(`[adventure] ${quest.script.title}: nothing written for "${kind} ${key}"`); + console.log(`[adventure] ${logText(quest.script.title)}: nothing written for "${logText(kind)} ${logText(key)}"`); } }; diff --git a/lib/bans.js b/lib/bans.js index 3f691eb..1824943 100644 --- a/lib/bans.js +++ b/lib/bans.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const accounts = require("./accounts.js"); const limits = require("./limits.js"); const net = require("net"); @@ -158,7 +159,7 @@ const appeal = (account, text, addressKey = "") => { } db().prepare("INSERT INTO appeals (account_id, created_at, username, text, address_key) VALUES (?, ?, ?, ?, ?)").run(account.id, now(), account.username, body, addressKey); record({account, address: addressKey, action: "appeal"}); - console.log(`[bans] "${account.username}" appealed`); + console.log(`[bans] "${logText(account.username)}" appealed`); return {appeal: appealOf(account)}; }; diff --git a/lib/captcha.js b/lib/captcha.js index 164a0bd..4fd6479 100644 --- a/lib/captcha.js +++ b/lib/captcha.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); @@ -79,7 +80,7 @@ const verify = async (answer, from, action) => { result = await response.json(); } catch (err) { - console.log(`[captcha] cloudflare did not answer: ${err.message}`); + console.log(`[captcha] cloudflare did not answer: ${logText(err.message)}`); return "captcha_unavailable"; } // an answer made for another form is no answer for this one. cloudflare's @@ -103,8 +104,11 @@ const check = async (body, from, action, account) => { return verify(body.captcha, from, action); }; -// a page's security policy, letting the widget in when it is on. -const policy = csp => (on ? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}` : csp); +// a page's security policy: public/captcha.js always (the page calls it even +// when off), and the widget too when it is on. +const policy = csp => (on + ? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}` + : csp.replace("script-src ", "script-src 'self' ")); // a page with public/captcha.js asked for under a name that changes with the // script and the key: cloudflare keeps .js files for hours, whatever the diff --git a/lib/cdn.js b/lib/cdn.js index 2599a12..65634c5 100644 --- a/lib/cdn.js +++ b/lib/cdn.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); @@ -69,7 +70,7 @@ const measure = async folder => { }; measure(config.cacheDir).then(() => { if (cacheBytes > config.maxCacheBytes) { - console.log(`[cdn] the cache holds ${Math.round(cacheBytes / 1048576)} MB, over its limit: new files are served but not kept (AJ_MAX_CACHE_MB)`); + console.log(`[cdn] the cache holds ${logText(Math.round(cacheBytes / 1048576))} MB, over its limit: new files are served but not kept (AJ_MAX_CACHE_MB)`); } }); @@ -84,7 +85,7 @@ const download = async (relPath, file) => { } missing.add(relPath); } - console.log(`[cdn] ${res.status} ${relPath}`); + console.log(`[cdn] ${logText(res.status)} ${logText(relPath)}`); return null; } const body = Buffer.from(await res.arrayBuffer()); @@ -99,10 +100,10 @@ const download = async (relPath, file) => { const tmp = `${file}.${process.pid}.tmp`; await fs.promises.writeFile(tmp, body); await fs.promises.rename(tmp, file); - console.log(`[cdn] cached ${relPath} (${body.length} bytes)`); + console.log(`[cdn] cached ${logText(relPath)} (${logText(body.length)} bytes)`); } catch (err) { - console.log(`[cdn] could not cache ${relPath}: ${err.message}`); + console.log(`[cdn] could not cache ${logText(relPath)}: ${logText(err.message)}`); } return body; }; @@ -134,7 +135,7 @@ const getExact = async (asked, mayFetch = () => true) => { // A download that fails (the CDN not answering in time) is "not there" // for now, and is tried again the next time the file is asked for. inFlight.set(relPath, download(relPath, file).catch(err => { - console.log(`[cdn] could not fetch ${relPath}: ${err.message}`); + console.log(`[cdn] could not fetch ${logText(relPath)}: ${logText(err.message)}`); return null; }).finally(() => inFlight.delete(relPath))); } diff --git a/lib/chatfilter.js b/lib/chatfilter.js index aa58435..d6f9f06 100644 --- a/lib/chatfilter.js +++ b/lib/chatfilter.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const fs = require("fs"); const path = require("path"); @@ -142,11 +143,11 @@ const rules = () => { parsed.push({line, clauses}); } else { - console.log(`[filter] lib/chat-filter.txt: a rule that could not be read was left out: ${line}`); + console.log(`[filter] lib/chat-filter.txt: a rule that could not be read was left out: ${logText(line)}`); } } kept = {mtime, rules: parsed}; - console.log(`[filter] ${parsed.length} rules`); + console.log(`[filter] ${logText(parsed.length)} rules`); } return kept.rules; }; diff --git a/lib/chatspam.js b/lib/chatspam.js new file mode 100644 index 0000000..04498d9 --- /dev/null +++ b/lib/chatspam.js @@ -0,0 +1,61 @@ +"use strict"; + +// typed chat made fit to read before anyone sees it (lib/world.js, pubMsg): +// not a filter of what is said (that is lib/chatfilter.js) but of how much +// of it there is. a key held down ("aaaaaaaaaa..."), a word said over and +// over, one long run of letters with no space, a line all in capitals, a +// wall of emoji: each is cut down, and the line still goes. the same line +// said again and again in a short while does not. + +const MAX_RUN = 5; // the same character this many times at most ("nooooo") +const MAX_REPEAT = 4; // the same word or emoji this many times in a row +const MAX_WORD = 32; // letters with no space between +const MAX_EMOJI = 12; // emoji in a line ("\{1f600}", as the client sends them) +const SHOUT_LENGTH = 12; // a line this long or more ... +const SHOUT_SHARE = 0.7; // ... with this share of its letters capitals is lowered +const REPEAT_LINES = 3; // the last few lines a player said ... +const REPEAT_MS = 20000; // ... within this long: one of those again is not sent + +const EMOJI = /\\\{[0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9}\}/g; + +// the line made tidy. emoji tags count as one character each here. +const tidy = text => { + // every emoji as one character for now (a private-use one), so that the + // rules below see it as one: put back at the end + const emoji = []; + let line = String(text).replace(EMOJI, tag => { + emoji.push(tag); + return String.fromCharCode(0xE000); + }); + // a character held down (not a digit: "1000000" is a number) + line = line.replace(new RegExp(`(.)\\1{${MAX_RUN},}`, "gu"), (run, char) => (/\d/.test(char) ? run : char.repeat(MAX_RUN))); + // one long run with no space + line = line.split(" ").map(word => (word.length > MAX_WORD ? word.slice(0, MAX_WORD) : word)).join(" "); + // the same word (or emoji) over and over: in a row, with or without spaces + line = line.replace(new RegExp(`((?:\\S+?)\\s*)\\1{${MAX_REPEAT},}`, "giu"), (run, once) => (/\d/.test(once) ? run : once.repeat(MAX_REPEAT))); + // shouting + const letters = line.replace(/[^A-Za-z]/g, ""); + if (letters.length >= SHOUT_LENGTH && letters.replace(/[^A-Z]/g, "").length / letters.length >= SHOUT_SHARE) { + line = line.toLowerCase(); + } + // the emoji back, no more than MAX_EMOJI of them + let kept = 0; + let at = 0; + line = line.replace(new RegExp(String.fromCharCode(0xE000), "g"), () => { + const tag = emoji[at++]; + return kept++ < MAX_EMOJI ? tag : ""; + }); + return line.replace(/\s{2,}/g, " ").trim(); +}; + +// was this line said by them just now (one of their last few, a short while +// ago)? kept on the session, as recentChat is. +const repeated = (session, line) => { + const now = Date.now(); + const said = (session.saidLately || []).filter(entry => now - entry.at < REPEAT_MS); + const again = said.some(entry => entry.line.toLowerCase() === line.toLowerCase()); + session.saidLately = [...said, {line, at: now}].slice(-REPEAT_LINES); + return again; +}; + +module.exports = {tidy, repeated}; diff --git a/lib/colours.js b/lib/colours.js index 9498f11..271121a 100644 --- a/lib/colours.js +++ b/lib/colours.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const accounts = require("./accounts.js"); // custom colours. the game stores a colour as four palette indexes packed in @@ -29,7 +30,7 @@ const load = () => { entries.set(row.id, row.rgb.split(",").map(Number)); nextId = Math.max(nextId, row.id + 1); } - console.log(`[colours] ${entries.size} custom colours`); + console.log(`[colours] ${logText(entries.size)} custom colours`); }; const valid = rgbs => rgbs.length === 4 && rgbs.every(value => Number.isInteger(value) && value >= 0 && value <= MAX_RGB); diff --git a/lib/commands.js b/lib/commands.js index 39d977d..aeaea4e 100644 --- a/lib/commands.js +++ b/lib/commands.js @@ -2,10 +2,15 @@ const accounts = require("./accounts.js"); const chatlog = require("./chatlog.js"); +const customItems = require("./customitems.js"); +const itemControl = require("./itemcontrol.js"); +const modNotes = require("./modnotes.js"); const defpacks = require("./defpacks.js"); const disguises = require("./disguises.js"); const dens = require("./dens.js"); const {isSilenced} = require("./moderation.js"); +const modlog = require("./modlog.js"); +const roles = require("./roles.js"); const {MAX_DEN_ITEMS, MAX_WORN, activeAvatar, wornItems} = require("./player.js"); // things players can do by typing "!something" in the chat box, for what @@ -47,7 +52,7 @@ const MAX_AGAIN = 100; // A hosted party's own name is three string ids, no use outside the game. const roomTitle = room => (room.partyHost ? `${room.partyHost.username}'s party` : room.displayName); -module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask}) => { +module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask, staffMove, setInvisible, staffModeration}) => { // A plain message box with an OK button. const tell = (session, text) => session.sendXt("xtl", -1, String(text).replace(/%/g, " percent")); @@ -500,6 +505,392 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB }; + // ---- staff commands (lib/roles.js). each checks the role's permission on + // every use, and what is done is written down under the staff member's + // name, as in the moderator panel. to anyone without the permission they + // are plain chat, like any other "!word" the server does not know. + const MAX_STAFF_HOURS = 24 * 365 * 10; + const MAX_WARNING = 200; + const MAX_WARNINGS_SHOWN = 5; + const MAX_ITEMS_LISTED = 8; + const MAX_NOTES_SHOWN = 5; // "!notes": the latest, in one message box + + const staffMay = (session, permission) => { + const moderation = staffModeration(); + return roles.can(session.account, permission, moderation.banRemaining(session.account) !== 0); + }; + + // the longest run of leading words naming an online player, and the words + // after it: usernames may have spaces in them. + const splitName = words => { + for (let count = words.length; count > 0; count--) { + const target = findOnline(words.slice(0, count).join(" ")); + if (target) { + return {target, rest: words.slice(count)}; + } + } + return {target: null, rest: words}; + }; + + // the same for any account, online or not. + const splitAccount = words => { + for (let count = words.length; count > 0; count--) { + const account = accounts.byName(words.slice(0, count).join(" ")); + if (account) { + return account; + } + } + return null; + }; + + // finds the player the command is about, and checks the staff member may + // act on them (`onStaff`: also on staff below their rank). + const withTarget = (session, words, usage, onStaff, run) => { + const {target, rest} = splitName(words); + if (!words.length) { + tell(session, usage); + } + else if (!target) { + tell(session, `${words.join(" ")} is not online.`); + } + else if (target === session) { + tell(session, "That is you."); + } + else if (onStaff && !roles.outranks(session.account, target.account)) { + tell(session, "Staff of your rank or above are for someone higher up to deal with."); + } + else { + run(target, rest); + } + }; + + const logged = (session, action, target, detail = "") => + modlog.record(session.account.username, `${action} (in game)`, target.account.username, detail); + + // what lib/itemcontrol.js tells about items taken. + const worldForItems = {itemsTaken: (...args) => require("./world.js").itemsTaken(...args)}; + + const lockCommand = (session, words, locked) => { + const [kind, id] = [(words[0] || "").toLowerCase(), words[1]]; + if (words.length !== 2) { + tell(session, `Use: !${locked ? "lock" : "unlock"} clothing|den ID`); + return; + } + const result = itemControl.setLocked(kind, id, locked); + tell(session, result.error || result.ok); + if (result.ok) { + modlog.record(session.account.username, locked ? "item locked (in game)" : "item unlocked (in game)", "", `${kind} ${id}`); + } + }; + + // an account named by the first words (a name may have spaces: the longest + // that is one), and the words after it. + const accountAndRest = words => { + for (let count = words.length; count > 0; count--) { + const account = accounts.byName(words.slice(0, count).join(" ")); + if (account) { + return {account, rest: words.slice(count)}; + } + } + return {account: null, rest: words}; + }; + + const staffCommands = { + // "!item clothing|den ID NAME": a new item made from the game's item ID + // (lib/customitems.js), free, every colour of the one it is made from; + // everyone has it at once. the moderator panel's Items page does more. + // "!item list": the latest made. + item: { + permission: "items.create", + run(session, words) { + const usage = "Use: !item clothing|den ID NAME, or !item list"; + if ((words[0] || "").toLowerCase() === "list") { + const latest = customItems.list().slice(0, MAX_ITEMS_LISTED) + .map(entry => `${entry.id} ${entry.name} (${entry.kind === "den" ? "den" : "clothing"}${entry.inShop ? "" : ", off sale"})`); + tell(session, latest.length ? `Latest items made: ${latest.join("; ")}` : "No items made yet."); + return; + } + const kind = (words[0] || "").toLowerCase(); + if (!customItems.KINDS.includes(kind) || !/^\d+$/.test(words[1] || "") || words.length < 3) { + tell(session, usage); + return; + } + const result = customItems.create(kind, {base: words[1], name: words.slice(2).join(" ")}, session.account.username); + if (result.error) { + tell(session, result.error); + return; + } + const {item} = result; + tell(session, `Made ${item.name}, ${kind === "den" ? "den item" : "clothing"} ${item.id}. It is in the item finder now.`); + modlog.record(session.account.username, "item made (in game)", "", `${kind} ${item.id} ${item.name}`); + }, + }, + staff: { + permission: "staff.list", + run(session) { + const on = players().filter(other => roles.isActiveStaff(other.account)) + .map(other => `${other.account.username} (${roles.ROLES[roles.roleOf(other.account)].label})`); + tell(session, on.length ? `Staff online: ${on.join(", ")}` : "No staff online."); + }, + }, + // "!note PLAYER text": a note for the other staff (lib/modnotes.js), + // never shown to the player. "!notes PLAYER": the latest few. + note: { + permission: "player.view", + run(session, words) { + const {account, rest} = accountAndRest(words); + if (!account || !rest.length) { + tell(session, account || !words.length ? "Use: !note PLAYER text" : `No player called ${words[0]}.`); + return; + } + if (account === session.account) { + tell(session, "That is you."); + return; + } + if (roles.roleOf(account) && !roles.outranks(session.account, account)) { + tell(session, "Staff of your rank or above are for someone higher up to deal with."); + return; + } + const result = modNotes.add(account, session.account.username, rest.join(" ")); + if (result.error) { + tell(session, result.error); + return; + } + tell(session, `Note on ${account.username} added.`); + modlog.record(session.account.username, "note (in game)", account.username, result.note.text); + }, + }, + notes: { + permission: "player.view", + run(session, words) { + const account = words.length ? accounts.byName(words.join(" ")) : null; + if (!account) { + tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !notes PLAYER"); + return; + } + const latest = modNotes.list(account).slice(0, MAX_NOTES_SHOWN) + .map(note => `${new Date(note.at * 1000).toISOString().slice(0, 10)} ${note.by}: ${note.text}`); + tell(session, latest.length ? `Notes on ${account.username}: ${latest.join(" | ")}` : `No notes on ${account.username}.`); + }, + }, + // "!invisible": unseen by players in every room until said again (staff + // still see them), as the game's own moderators could be. + invisible: { + permission: "staff.invisible", + run(session) { + setInvisible(session, !session.invisible); + }, + }, + // "!lock clothing|den ID", "!unlock clothing|den ID", "!locked": items + // kept out of the item finder for players (lib/itemcontrol.js). + lock: { + permission: "items.create", + run(session, words) { + lockCommand(session, words, true); + }, + }, + unlock: { + permission: "items.create", + run(session, words) { + lockCommand(session, words, false); + }, + }, + locked: { + permission: "items.create", + run(session) { + const list = itemControl.lockedList().slice(0, MAX_ITEMS_LISTED) + .map(entry => `${entry.kind} ${entry.id} ${entry.name || "(no name)"}`); + tell(session, list.length ? `Locked out of the item finder: ${list.join("; ")}` : "Nothing is locked out of the item finder."); + }, + }, + // "!take PLAYER clothing|den ID": every one of that item, out of their + // inventory, online or not. + take: { + permission: "items.create", + run(session, words) { + const usage = "Use: !take PLAYER clothing|den ID"; + // the name may have spaces: the kind and the id are the last two words. + const [kind, id] = words.slice(-2).map(word => word.toLowerCase()); + const account = words.length >= 3 ? accounts.byName(words.slice(0, -2).join(" ")) : null; + if (words.length < 3 || !/^\d+$/.test(id)) { + tell(session, usage); + return; + } + if (!account) { + tell(session, `No player called ${words.slice(0, -2).join(" ")}.`); + return; + } + if (account !== session.account && !roles.outranks(session.account, account) && roles.roleOf(account)) { + tell(session, "Staff of your rank or above are for someone higher up to deal with."); + return; + } + const result = itemControl.take(account.username, kind, id, worldForItems); + tell(session, result.error || result.ok); + if (result.ok) { + modlog.record(session.account.username, "item taken (in game)", account.username, `${kind} ${id} x${result.count}`); + } + }, + }, + summon: { + permission: "player.summon", + run(session, words) { + withTarget(session, words, "Use: !summon PLAYER", true, target => { + const result = staffMove(target.account.username, session.account.username); + if (!result.ok) { + tell(session, result.error); + return; + } + tell(session, `${target.account.username} was brought here.`); + logged(session, "summon", target, result.room); + }); + }, + }, + goto: { + permission: "player.goto", + run(session, words) { + withTarget(session, words, "Use: !goto PLAYER", false, target => { + const result = staffMove(session.account.username, target.account.username); + if (!result.ok) { + tell(session, result.error); + return; + } + logged(session, "goto", target, result.room); + }); + }, + }, + kick: { + permission: "player.kick", + run(session, words) { + withTarget(session, words, "Use: !kick PLAYER", true, target => { + const name = target.account.username; + if (staffModeration().actions.kick(target.account)) { + tell(session, `${name} was disconnected.`); + logged(session, "kick", target); + } + else { + tell(session, `${name} is not online.`); + } + }); + }, + }, + // "!silence PLAYER HOURS" (0: until lifted), "!silence PLAYER off". + silence: { + permission: "chat.silence", + run(session, words) { + withTarget(session, words, "Use: !silence PLAYER HOURS (0 until lifted), or !silence PLAYER off", true, (target, rest) => { + const {actions, PERMANENT} = staffModeration(); + const name = target.account.username; + const amount = (rest[0] || "").toLowerCase(); + if (amount === "off") { + actions.silence(target.account, 0); + tell(session, `${name} can chat again.`); + logged(session, "unsilence", target); + return; + } + const hours = /^\d{1,6}$/.test(amount) ? Number(amount) : NaN; + if (!(hours >= 0 && hours <= MAX_STAFF_HOURS)) { + tell(session, "Use: !silence PLAYER HOURS (0 until lifted), or !silence PLAYER off"); + return; + } + actions.silence(target.account, hours === 0 ? PERMANENT : hours * 3600); + tell(session, hours === 0 ? `${name} cannot chat until it is lifted.` : `${name} cannot chat for ${hours} hours.`); + logged(session, "silence", target, String(hours || "until lifted")); + }); + }, + }, + // "!warn PLAYER [REASON] [note]": a warning, kept on the account and + // shown with the game's own warning popup. REASON is behavior (the + // default), bullying, personal or scamming; the note is for staff. + // "!warn PLAYER custom TEXT": a warning in the staff member's own + // words, which is what the player is shown. + warn: { + permission: "player.warn", + run(session, words) { + const usage = `Use: !warn PLAYER [${staffModeration().WARNINGS.join("|")}] [note], or !warn PLAYER custom TEXT`; + withTarget(session, words, usage, true, (target, rest) => { + const {WARNINGS, actions} = staffModeration(); + const asked = (rest[0] || "").toLowerCase(); + const reason = WARNINGS.includes(asked) ? asked : "behavior"; + const note = (WARNINGS.includes(asked) ? rest.slice(1) : rest).join(" ").trim().slice(0, MAX_WARNING); + if (reason === "custom" && !note) { + tell(session, "Use: !warn PLAYER custom TEXT (the text is what they are shown)"); + return; + } + const result = actions.warn(target.account, reason, session.account.username, note); + tell(session, `${target.account.username} warned (${reason}): warning ${result.count}.` + + (result.silencedMinutes ? ` Silenced for ${result.silencedMinutes} minutes, for that many warnings.` : "")); + logged(session, "warn", target, note ? `${reason} · ${note}` : reason); + }); + }, + }, + // "!message PLAYER text": a message box from the moderators. + message: { + permission: "player.warn", + run(session, words) { + withTarget(session, words, "Use: !message PLAYER text", true, (target, rest) => { + const text = rest.join(" ").trim().slice(0, MAX_WARNING); + if (!text) { + tell(session, "Use: !message PLAYER text"); + return; + } + if (staffModeration().actions.message(target.account, text)) { + tell(session, `Shown to ${target.account.username}.`); + logged(session, "message", target, text); + } + else { + tell(session, `${target.account.username} is not online.`); + } + }); + }, + }, + // "!unwarn PLAYER": takes back their latest warning (one given by + // mistake), online or not. + unwarn: { + permission: "player.warn", + run(session, words) { + const account = splitAccount(words); + if (!account) { + tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !unwarn PLAYER"); + return; + } + if (account === session.account) { + tell(session, "That is you."); + return; + } + if (!roles.outranks(session.account, account)) { + tell(session, "Staff of your rank or above are for someone higher up to deal with."); + return; + } + const removed = staffModeration().actions.unwarn(account); + if (!removed) { + tell(session, `${account.username} has no warnings.`); + return; + } + tell(session, `Took back ${account.username}'s latest warning (${removed.reason}).`); + modlog.record(session.account.username, "unwarn (in game)", account.username, removed.reason); + }, + }, + // "!warnings PLAYER": their latest warnings, online or not. + warnings: { + permission: "player.warn", + run(session, words) { + const account = splitAccount(words); + if (!account) { + tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !warnings PLAYER"); + return; + } + const list = account.warnings || []; + if (!list.length) { + tell(session, `${account.username} has no warnings.`); + return; + } + const latest = list.slice(-MAX_WARNINGS_SHOWN).reverse() + .map(entry => `${new Date(entry.at * 1000).toISOString().slice(0, 10)} ${entry.reason} by ${entry.by}${entry.note ? ` (${entry.note})` : ""}`); + tell(session, `${account.username} has ${list.length} warning${list.length === 1 ? "" : "s"}. Latest: ${latest.join("; ")}`); + }, + }, + }; + return { // runs `text` if it is a command. returns what to do with the chat line: // null to swallow it, or the text everyone should see in its place. @@ -509,6 +900,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB } const typed = text.slice(PREFIX.length).trim().split(/\s+/); const [name, ...words] = typed.map(word => word.toLowerCase()); + if (Object.hasOwn(staffCommands, name) && staffMay(session, staffCommands[name].permission)) { + staffCommands[name].run(session, typed.slice(1)); + return null; + } if (Object.hasOwn(asTyped, name) && (name !== "den" || typed.length > 1)) { asTyped[name](session, typed.slice(1)); return null; diff --git a/lib/customitems.js b/lib/customitems.js new file mode 100644 index 0000000..64cd4c5 --- /dev/null +++ b/lib/customitems.js @@ -0,0 +1,355 @@ +"use strict"; + +const {logText} = require("./logtext.js"); +const accounts = require("./accounts.js"); +const defpacks = require("./defpacks.js"); + +// items the staff make while the server runs, with no restart of the server +// or of anybody's game. each is an existing item's art (the clothing piece +// or den item it is made from) under an id, name, price and colours of its +// own. the server's tables and the packs new games fetch have it at once +// (defpacks.setCustomItem); games already playing are sent its def row +// ("xdi", which the patched client adds to its tables), and so is every game +// at login, in case it was started before the item was made. +// +// an item can be taken out of the shop, renamed and repriced, or deleted: +// then it goes from every inventory too (lib/itemcontrol.js). + +// ids far above the game's own (clothing to about 4,600, den items to about +// 6,000), one range per pack; names go under localization ids above the +// server's other added strings (lib/defpacks.js ADDED_STRINGS, 9000001 on). +const FIRST_ID = 50000; +const STRING_BASE = {clothing: 9100000, den: 9200000}; +const KINDS = ["clothing", "den"]; +const MAX_NAME = 40; +const MAX_COST = 1000000; +const MAX_COLOURS = 16; +const MAX_ITEMS = 5000; // per kind +const CHUNK = 40; // def rows per "xdi" message +const TYPE_CLOTHING = "1"; +const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items that can be copied: plain, mannequin +const CURRENCY_GEMS = "0"; + +const SCHEMA = `CREATE TABLE IF NOT EXISTS custom_items ( + kind TEXT NOT NULL, id INTEGER NOT NULL, base INTEGER NOT NULL, name TEXT NOT NULL, + cost INTEGER NOT NULL, members INTEGER NOT NULL, colors TEXT NOT NULL, in_shop INTEGER NOT NULL, + created_by TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (kind, id))`; + +const items = new Map(KINDS.map(kind => [kind, new Map()])); // kind -> id -> entry +let made = 0; // entries in the order they were made (`seq`), for lists +let broadcast = () => {}; // (cmd, ...params) to every game playing; set by lib/world.js + +const db = () => accounts.database(); +const now = () => Math.floor(Date.now() / 1000); + +const baseDef = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id)); + +// the def row of an entry: its base's row with its own id, name, price and +// colours, always on sale and marked new. +const rowOf = entry => { + const base = baseDef(entry.kind, entry.base); + const own = { + id: String(entry.id), + membersOnly: entry.members ? "1" : "0", + itemStatus: "1", + availabilityStartTime: "0", + availabilityEndTime: "0", + currencyType: CURRENCY_GEMS, + recycleValue: "0", + combinedCost: "", + }; + if (entry.kind === "den") { + return {...base, ...own, nameStrId: String(STRING_BASE.den + entry.id - FIRST_ID), cost: String(entry.cost)}; + } + return {...base, ...own, titleStrId: String(STRING_BASE.clothing + entry.id - FIRST_ID), value: String(entry.cost), colors: entry.colors.join(","), isGiftable: "1"}; +}; + +const apply = entry => defpacks.setCustomItem(entry.kind, rowOf(entry), entry.name, entry.inShop); + +// "xdi" [.., .., kind, json]: def rows with their names, as JSON. a field +// may not hold "%" (lib/sfs.js drops it), so a "%" in a name is written as +// JSON's %. +const messages = entries => { + const out = []; + for (const kind of KINDS) { + // a picture waiting for a moderator is not shown yet + const rows = entries.filter(entry => entry.kind === kind && !entry.pending) + .map(entry => ({...rowOf(entry), name: entry.name, art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"})); + for (let at = 0; at < rows.length; at += CHUNK) { + out.push([kind, JSON.stringify(rows.slice(at, at + CHUNK)).replace(/%/g, "\\u0025")]); + } + } + return out; +}; + +const announce = entry => { + if (entry.pending) { + return; + } + for (const params of messages([entry])) { + broadcast("xdi", ...params); + } +}; + +const fromRow = row => ({ + kind: row.kind, id: row.id, base: row.base, name: row.name, cost: row.cost, members: row.members === 1, + colors: row.colors ? row.colors.split(",").map(Number) : [], inShop: row.in_shop === 1, createdBy: row.created_by, createdAt: row.created_at, + ownerId: row.owner_id ?? null, + art: row.art || null, + artMode: LOOKS.includes(row.art_mode) ? row.art_mode : "sticker", + pending: row.pending === 1, + artPending: row.art_pending === 1, +}); + +// a player-made item (lib/playeritems.js) has the maker's account id; +// staff-made ones none. an item with a picture of its own (lib/itemart.js) +// has its version. the columns came later than the table. +const addOwnerColumn = () => { + const columns = db().prepare("PRAGMA table_info(custom_items)").all().map(column => column.name); + if (!columns.includes("owner_id")) { + db().exec("ALTER TABLE custom_items ADD COLUMN owner_id INTEGER"); + } + if (!columns.includes("art")) { + db().exec("ALTER TABLE custom_items ADD COLUMN art TEXT"); + } + if (!columns.includes("art_mode")) { + db().exec("ALTER TABLE custom_items ADD COLUMN art_mode TEXT"); + } + // waiting for a moderator (lib/playeritems.js, when the admin asks for it): + // the item itself, or only its newest picture + if (!columns.includes("pending")) { + db().exec("ALTER TABLE custom_items ADD COLUMN pending INTEGER"); + } + if (!columns.includes("art_pending")) { + db().exec("ALTER TABLE custom_items ADD COLUMN art_pending INTEGER"); + } +}; + +const load = () => { + db().exec(SCHEMA); + addOwnerColumn(); + for (const row of db().prepare("SELECT * FROM custom_items ORDER BY rowid").all()) { + const entry = {...fromRow(row), seq: made++}; + if (!baseDef(entry.kind, entry.base)) { + console.log(`[custom items] ${logText(entry.kind)} ${logText(entry.id)} is made from ${logText(entry.base)}, which is not in the packs; left out`); + continue; + } + items.get(entry.kind).set(entry.id, entry); + if (!entry.pending) { + apply(entry); + } + } + console.log(`[custom items] ${logText(items.get("clothing").size)} clothing, ${logText(items.get("den").size)} den items`); +}; + +// checks what staff typed. returns {error} or the cleaned values. +const NAME_PATTERN = /^[\p{L}\p{N} '&!?.,:()#+\-]+$/u; +const clean = (kind, fields, current = null) => { + const out = {}; + if (fields.name !== undefined || !current) { + const name = String(fields.name || "").trim().replace(/\s+/g, " "); + if (!name || name.length > MAX_NAME || !NAME_PATTERN.test(name)) { + return {error: `A name of 1 to ${MAX_NAME} letters, numbers, spaces and simple punctuation, please.`}; + } + out.name = name; + } + if (fields.cost !== undefined || !current) { + const cost = Number(fields.cost === undefined || fields.cost === "" ? 0 : fields.cost); + if (!Number.isInteger(cost) || cost < 0 || cost > MAX_COST) { + return {error: `A price from 0 to ${MAX_COST} gems, please.`}; + } + out.cost = cost; + } + if (fields.members !== undefined || !current) { + out.members = fields.members === true || fields.members === "1" || fields.members === 1; + } + if (fields.inShop !== undefined || !current) { + out.inShop = fields.inShop === undefined ? true : fields.inShop === true || fields.inShop === "1" || fields.inShop === 1; + } + if (kind === "clothing" && (fields.colors !== undefined || !current)) { + const base = baseDef(kind, current ? current.base : fields.base); + const baseColours = String(base.colors).split(",").map(Number); + let colors = fields.colors; + if (colors === undefined || colors === null || colors === "") { + colors = baseColours; + } + else { + colors = (Array.isArray(colors) ? colors : String(colors).split(",")).map(value => Number(String(value).trim())); + } + // a colour is a packed palette number, as in the packs (or a custom colour + // id, lib/colours.js). + if (colors.length === 0 || colors.length > MAX_COLOURS || !colors.every(value => Number.isInteger(value) && value >= 0 && value <= 0xFFFFFFFF)) { + return {error: `1 to ${MAX_COLOURS} colours, each a number as the packs have them.`}; + } + out.colors = colors; + } + return out; +}; + +// makes an item from `base`, an existing clothing piece or den item. +// `ownerId`: the player who made it (lib/playeritems.js), or null for staff. +// `pending`: it waits for a moderator (approve), out of the game till then. +// returns {item} or {error}. +const create = (kind, fields, by, ownerId = null, pending = false) => { + if (!KINDS.includes(kind)) { + return {error: "The kind is clothing or den."}; + } + const baseId = Number(fields.base); + const base = Number.isInteger(baseId) ? baseDef(kind, baseId) : null; + if (!base || baseId >= FIRST_ID) { + return {error: `No ${kind === "den" ? "den item" : "clothing"} with the id ${fields.base} to make it from (it must be one of the game's own).`}; + } + if (kind === "clothing" && base.type !== TYPE_CLOTHING) { + return {error: `${baseId} is a body part, not clothing.`}; + } + if (kind === "den" && !OFFERED_SPECIAL_TYPES.includes(base.specialType)) { + return {error: `Den item ${baseId} does something of its own (a portal, a game, ...) and cannot be copied.`}; + } + if (items.get(kind).size >= MAX_ITEMS) { + return {error: "There are as many custom items of that kind as there can be."}; + } + const values = clean(kind, {...fields, base: baseId}); + if (values.error) { + return values; + } + const id = Math.max(FIRST_ID - 1, ...items.get(kind).keys()) + 1; + const entry = {kind, id, base: baseId, colors: [], ...values, createdBy: String(by), createdAt: now(), ownerId, artMode: "sticker", pending, artPending: false, + seq: made++}; + db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at, owner_id, pending) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") + .run(kind, id, baseId, entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, entry.createdBy, entry.createdAt, ownerId, pending ? 1 : 0); + items.get(kind).set(id, entry); + if (!pending) { + apply(entry); + announce(entry); + } + return {item: entry}; +}; + +// changes the name, price, members-only, colours or whether it is on sale. +const update = (kind, id, fields) => { + const entry = items.has(kind) && items.get(kind).get(Number(id)); + if (!entry) { + return {error: "No such custom item."}; + } + const values = clean(kind, fields, entry); + if (values.error) { + return values; + } + Object.assign(entry, values); + db().prepare("UPDATE custom_items SET name = ?, cost = ?, members = ?, colors = ?, in_shop = ? WHERE kind = ? AND id = ?") + .run(entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, kind, entry.id); + if (!entry.pending) { + apply(entry); + announce(entry); + } + return {item: entry}; +}; + +// how a clothing item with a picture of its own is worn: "sticker" (the +// picture where the item would be) or "texture" (the item's shape, painted +// with the picture). the patched client draws it (LayerBitmap.paintLayer). +const LOOKS = ["sticker", "texture"]; + +// returns {item} or {error}; every game is told. +const setArtMode = (kind, id, mode) => { + const entry = items.has(kind) && items.get(kind).get(Number(id)); + if (!entry) { + return {error: "No such custom item."}; + } + if (!LOOKS.includes(mode)) { + return {error: "The look is sticker or texture."}; + } + entry.artMode = mode; + db().prepare("UPDATE custom_items SET art_mode = ? WHERE kind = ? AND id = ?").run(mode, kind, entry.id); + announce(entry); + return {item: entry}; +}; + +// its picture's version (lib/itemart.js), or null for none; every game is told. +// `pending`: the picture waits for a moderator, and is not shown till then. +const setArt = (kind, id, art, pending = false) => { + const entry = items.has(kind) && items.get(kind).get(Number(id)); + if (!entry) { + return; + } + entry.art = art || null; + entry.artPending = Boolean(art && pending); + db().prepare("UPDATE custom_items SET art = ?, art_pending = ? WHERE kind = ? AND id = ?").run(entry.art, entry.artPending ? 1 : 0, kind, entry.id); + announce(entry); +}; + +// a moderator lets an item, or its picture, in (lib/playeritems.js approve). +// returns the entry, or null when there was nothing waiting. +const approve = (kind, id) => { + const entry = items.has(kind) && items.get(kind).get(Number(id)); + if (!entry || (!entry.pending && !entry.artPending)) { + return null; + } + entry.pending = false; + entry.artPending = false; + db().prepare("UPDATE custom_items SET pending = 0, art_pending = 0 WHERE kind = ? AND id = ?").run(kind, entry.id); + apply(entry); + announce(entry); + return entry; +}; + +// deletes it from the tables (games playing keep its def row, which nothing +// uses now). taking it from the players who have it is the caller's. +// returns {item} or {error}. +const remove = (kind, id) => { + const entry = items.has(kind) && items.get(kind).get(Number(id)); + if (!entry) { + return {error: "No such custom item."}; + } + db().prepare("DELETE FROM custom_items WHERE kind = ? AND id = ?").run(kind, entry.id); + items.get(kind).delete(entry.id); + defpacks.unsetCustomItem(kind, entry.id); + return {item: entry}; +}; + +const list = () => KINDS.flatMap(kind => [...items.get(kind).values()]) + .sort((one, other) => other.seq - one.seq); + +module.exports = { + KINDS, + FIRST_ID, + load, + create, + update, + remove, + setArt, + setArtMode, + approve, + // what waits for a moderator: items, and pictures, the oldest first + waiting: () => list().filter(entry => entry.pending || entry.artPending).reverse(), + LOOKS, + list, + get: (kind, id) => (items.has(kind) && items.get(kind).get(Number(id))) || null, + // the account id of the player who made an item, or null (staff's, or + // one of the game's own). + ownerOf: (kind, id) => { + const entry = items.has(kind) && items.get(kind).get(Number(id)); + return entry ? entry.ownerId : null; + }, + // can this base be made into an item? (the checks of create, for a list + // to offer only those.) + copyable: (kind, id) => { + const def = baseDef(kind, id); + return Boolean(def) && Number(id) < FIRST_ID && (kind === "clothing" ? def.type === TYPE_CLOTHING : OFFERED_SPECIAL_TYPES.includes(def.specialType)); + }, + // the base an item's art is from, for a list showing what each is. + baseName: entry => { + const def = baseDef(entry.kind, entry.base); + return def ? defpacks.string(entry.kind === "den" ? def.nameStrId : def.titleStrId) || String(def.abbrName || entry.base) : String(entry.base); + }, + // every custom item, for a game logging in. + sendAll(session) { + for (const params of messages(list().reverse().filter(entry => !entry.pending))) { + session.sendXt("xdi", -1, ...params); + } + }, + // lib/world.js says how to reach every game playing. + connect(broadcastXt) { + broadcast = broadcastXt; + }, +}; diff --git a/lib/defpacks.js b/lib/defpacks.js index ceeabbc..d251284 100644 --- a/lib/defpacks.js +++ b/lib/defpacks.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const zlib = require("zlib"); const amf3 = require("./amf3.js"); const cdn = require("./cdn.js"); @@ -175,7 +176,39 @@ const withOurName = pack => { return pack; }; -const withAddedStrings = pack => withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings())); +// the moderators' message boxes (FacilitatorXtCommManager "fp") keep +// "\n" as two characters, which the client shows just as written +// ("--Message From Moderator--\n\nhello"). real line breaks in their place. +const LITERAL_LINE_BREAKS = ["11134", "11135"]; +const withLineBreaks = pack => { + for (const id of LITERAL_LINE_BREAKS) { + if (typeof pack[id] === "string") { + pack[id] = pack[id].replace(/\\n/g, "\n"); + } + } + return pack; +}; + +// items the staff make while the server runs (lib/customitems.js): an +// existing item's art under a new id, name and price. their rows and names +// are kept here, and go into the packs like the rows above, after the +// renaming (a name staff chose is left as they wrote it). +const customRows = new Map([[DEF_ITEM, new Map()], [DEF_DEN_ITEM, new Map()]]); // pack -> id -> row +const customStrings = {}; // localization id -> name +const customInShop = {clothing: new Set(), den: new Set()}; // ids on sale +let customVersion = 0; // goes up with every change, for anything that keeps a list of items + +const withCustomRows = id => pack => { + const at = new Map(Object.entries(pack).map(([key, def]) => [String(def.id), key])); + let next = Math.max(-1, ...Object.keys(pack).map(Number).filter(Number.isInteger)) + 1; + for (const row of customRows.get(id).values()) { + // a changed row replaces the one the pack was made with. + pack[at.has(row.id) ? at.get(row.id) : next++] = {...row}; + } + return pack; +}; + +const withAddedStrings = pack => Object.assign(withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()))), customStrings); // the extra music tracks (lib/extramusic.js), as den items like the // official tracks. @@ -236,8 +269,8 @@ const SHARED_CHANGES = new Map([ [DEF_ROOM, withRestoredRooms], [DEF_PARTY, withRestoredParties], [DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)], - [DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, withExtraMusic)], - [DEF_ITEM, withoutPrices(DEF_ITEM)], + [DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, pack => withCustomRows(DEF_DEN_ITEM)(withExtraMusic(pack)))], + [DEF_ITEM, withoutPrices(DEF_ITEM, withCustomRows(DEF_ITEM))], [DEF_DIAMOND, withoutPrices(DEF_DIAMOND)], [DEF_PET, withoutPrices(DEF_PET)], [DEF_LOCALIZATION_EN, withAddedStrings], @@ -369,7 +402,7 @@ const loadOptional = async id => { return await load(id); } catch (err) { - console.log(`[defs] ${err.message}; the feature that uses it is off`); + console.log(`[defs] ${logText(err.message)}; the feature that uses it is off`); return []; } }; @@ -439,11 +472,68 @@ const init = async () => { isGame: def.isGame === "1", }]; })); - console.log(`[defs] ${avatarDefs.size} avatars, ${roomDefsByPath.size} rooms, ${clothingIds.length} clothing items, ${denItemIds.length} den items, ${petIds.length} pets`); + console.log(`[defs] ${logText(avatarDefs.size)} avatars, ${logText(roomDefsByPath.size)} rooms, ${logText(clothingIds.length)} clothing items, ${logText(denItemIds.length)} den items, ${logText(petIds.length)} pets`); +}; + +// puts a custom item (lib/customitems.js) in, or changes one already in: +// `kind` "clothing" or "den", `row` its full def row (strings, as in the +// packs), `name` its English name under the row's string id. the server's +// tables have it at once, and the packs clients fetch are made again. +// `inShop` false takes it out of the shop (the ones players have still draw). +const setCustomItem = (kind, row, name, inShop = true) => { + const pack = kind === "den" ? DEF_DEN_ITEM : DEF_ITEM; + const id = Number(row.id); + const stringId = kind === "den" ? row.nameStrId : row.titleStrId; + customRows.get(pack).set(id, row); + customStrings[stringId] = name; + strings[stringId] = name; + stringIds = null; + if (packs.has(pack)) { + packs.set(pack, [...packs.get(pack).filter(def => Number(def.id) !== id), row]); + } + if (kind === "den") { + denItemDefs.set(id, row); + denItemIds = denItemIds.includes(id) ? denItemIds : [...denItemIds, id]; + } + else { + itemDefs.set(id, row); + clothingIds = clothingIds.includes(id) ? clothingIds : [...clothingIds, id]; + } + customInShop[kind][inShop ? "add" : "delete"](id); + clientPackBodies.delete(pack); + clientPackBodies.delete(DEF_LOCALIZATION_EN); + customVersion++; +}; + +// a custom item deleted (lib/customitems.js): out of the tables and the +// packs new games fetch. its name stays under its string id, unused. +const unsetCustomItem = (kind, id) => { + const pack = kind === "den" ? DEF_DEN_ITEM : DEF_ITEM; + const number = Number(id); + customRows.get(pack).delete(number); + if (packs.has(pack)) { + packs.set(pack, packs.get(pack).filter(def => Number(def.id) !== number)); + } + if (kind === "den") { + denItemDefs.delete(number); + denItemIds = denItemIds.filter(one => one !== number); + } + else { + itemDefs.delete(number); + clothingIds = clothingIds.filter(one => one !== number); + } + customInShop[kind].delete(number); + clientPackBodies.delete(pack); + customVersion++; }; module.exports = { init, + setCustomItem, + unsetCustomItem, + // the custom items on sale, the newest first. + customShopIds: kind => [...customInShop[kind]].reverse(), + customVersion: () => customVersion, load, itemDef: id => itemDefs.get(Number(id)), clothingIds: () => clothingIds, diff --git a/lib/dens.js b/lib/dens.js index dd44161..261707a 100644 --- a/lib/dens.js +++ b/lib/dens.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const accounts = require("./accounts.js"); const achievements = require("./achievements.js"); const config = require("../config.js"); @@ -260,7 +261,7 @@ const handlers = ({others, findOnline}) => { const item = giveDenItem(account, masterpieces.DEN_ITEM, frame); item.image = String(paintingId); accounts.save(account); - console.log(`[world] ${account.username} made masterpiece ${item.image}${masterpieces.itemApproved(item) ? "" : " (waiting for review in the admin panel)"}`); + console.log(`[world] ${logText(account.username)} made masterpiece ${logText(item.image)}${logText(masterpieces.itemApproved(item) ? "" : " (waiting for review in the admin panel)")}`); session.sendXt("db", -1, 1, account.currency.diamonds || 0, 0, CURRENCY_DIAMONDS, item.inv); sendDenItems(session); }; diff --git a/lib/devices.js b/lib/devices.js index 2c51a42..20d48ca 100644 --- a/lib/devices.js +++ b/lib/devices.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); @@ -188,7 +189,7 @@ const alert = (account, kind, detail) => { return; } db().prepare("INSERT INTO device_alerts (at, account_id, username, kind, detail) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, detail); - console.log(`[devices] ${account.username}: ${kind} (${detail})`); + console.log(`[devices] ${logText(account.username)}: ${logText(kind)} (${logText(detail)})`); }; // an account signed in from this computer: its ids are kept, and what looks diff --git a/lib/ecards.js b/lib/ecards.js index 80b3212..e2d3a58 100644 --- a/lib/ecards.js +++ b/lib/ecards.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const fs = require("fs"); const path = require("path"); const accounts = require("./accounts.js"); @@ -97,7 +98,11 @@ module.exports = ({findOnline, blocks}) => { 0, // secondary type senderType, USERNAME_SHOWN, - "", // additional gift data + // additional gift data: for clothing, "item|", so that the + // patched client (ECardInbox) can show a custom item as itself (its + // own picture and name) and not as the art it was made from. (the + // "|" keeps the game from taking it for an HQ gift's own message.) + card.gift && card.gift.type === TYPE_CLOTHING ? `item|${card.gift.def}` : "", card.secret ? SECRET_VALENTINE : 0, ]; }; @@ -261,7 +266,7 @@ module.exports = ({findOnline, blocks}) => { const rule = chatFilter.broken(clean(message || "")); if (rule) { chatFilter.warn(session); - console.log(`[filter] ${account.username} in a Jam-a-Gram to ${to.username}: "${clean(message || "")}" (${rule})`); + console.log(`[filter] ${logText(account.username)} in a Jam-a-Gram to ${logText(to.username)}: "${logText(clean(message || ""))}" (${logText(rule)})`); chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, chatlog.NOT_SENT + clean(message || "")); reply(FAILED); return; diff --git a/lib/emoji.js b/lib/emoji.js new file mode 100644 index 0000000..ec369e8 --- /dev/null +++ b/lib/emoji.js @@ -0,0 +1,80 @@ +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const config = require("../config.js"); +const {logText} = require("./logtext.js"); + +// pictures of emoji, for the patched client's chat bubbles (gui.ChatBalloon): +// the game's font has none, so an emoji typed in chat (with Windows' emoji +// panel, say) is drawn as one of these. they are Twemoji's (CC-BY 4.0, +// jdecked/twemoji on GitHub), asked of config.emojiUpstream once +// each and kept in data/emoji. a name is the emoji's code points in hex, +// joined by "-", as Twemoji names its files ("1f600", "1f468-200d-1f469"). + +const NAME = /^[0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9}$/; +const MAX_BYTES = 64 * 1024; +const MAX_MISSING = 5000; +const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); +const DIR = path.join(config.dataDir, "emoji"); + +const missing = new Set(); // names the upstream does not have +const pending = new Map(); // name -> promise, so that one is asked for once + +const isName = name => typeof name === "string" && NAME.test(name); + +const fileOf = name => path.join(DIR, `${name}.png`); + +const fetchUpstream = async name => { + const res = await fetch(`${config.emojiUpstream}${name}.png`, {signal: AbortSignal.timeout(config.upstreamTimeoutMs)}); + if (!res.ok) { + if (res.status === 404 || res.status === 403) { + if (missing.size >= MAX_MISSING) { + missing.clear(); + } + missing.add(name); + } + return null; + } + const body = Buffer.from(await res.arrayBuffer()); + // a PNG, and a small one, or nothing is kept + if (body.length > MAX_BYTES || !body.subarray(0, 8).equals(PNG_SIGNATURE)) { + console.log(`[emoji] not a picture: ${logText(name)}`); + return null; + } + try { + fs.mkdirSync(DIR, {recursive: true}); + const tmp = `${fileOf(name)}.${process.pid}.tmp`; + fs.writeFileSync(tmp, body); + fs.renameSync(tmp, fileOf(name)); + } + catch (err) { + console.log(`[emoji] could not keep ${logText(name)}: ${logText(err.message)}`); + } + return body; +}; + +// the picture for `name`: a Buffer, or null. `mayFetch()`: whether one not +// kept yet may be asked of the upstream for this request (asked only then). +const get = async (name, mayFetch) => { + if (!isName(name) || missing.has(name)) { + return null; + } + try { + return await fs.promises.readFile(fileOf(name)); + } + catch (err) { + if (err.code !== "ENOENT") { + return null; + } + } + if (!mayFetch()) { + return null; + } + if (!pending.has(name)) { + pending.set(name, fetchUpstream(name).catch(() => null).finally(() => pending.delete(name))); + } + return pending.get(name); +}; + +module.exports = {get, isName}; diff --git a/lib/http.js b/lib/http.js index e51d228..b8022fc 100644 --- a/lib/http.js +++ b/lib/http.js @@ -1,11 +1,17 @@ "use strict"; +const {logText} = require("./logtext.js"); const crypto = require("crypto"); const fs = require("fs"); const http = require("http"); const https = require("https"); const path = require("path"); const accounts = require("./accounts.js"); +const customItems = require("./customitems.js"); +const itemArt = require("./itemart.js"); +const emoji = require("./emoji.js"); +const modlog = require("./modlog.js"); +const roles = require("./roles.js"); const admin = require("./admin.js"); const bans = require("./bans.js"); const captcha = require("./captcha.js"); @@ -139,6 +145,92 @@ const formParts = (contentType, body) => { return parts; }; +// a custom item's picture set or taken away (?kind=&id=[&remove=1], the +// picture as the body): by its maker, or by staff who make items. who asks +// is the holder of a game's token (/api/itemart?token=, the client's Item +// Maker), or `signedIn` (req) -> account: the account page's or the +// moderator panel's session, whose cookies only go to their own paths +// (/account/api/itemart, /mod/api/itemart), from this server's own pages. +// every answer is 200, with {ok} or {error}: the game's Flash cannot read +// the body of any other. +// `adminSignedIn` (req) -> boolean: the admin panel's session, which acts as +// staff who make items, and is written down as "admin". +const itemArtUpload = async (req, res, url, from, signedIn = null, adminSignedIn = null) => { + if ((req.method === "GET" || req.method === "HEAD") && (signedIn || adminSignedIn)) { + itemArtView(req, res, url, signedIn, adminSignedIn); + return; + } + if (req.method !== "POST" || !limits.originAllowed(req)) { + send(res, 200, {error: "forbidden"}); + return; + } + const token = url.searchParams.get("token"); + const holder = token ? accounts.byToken(token) : null; + const asAdmin = Boolean(adminSignedIn && adminSignedIn(req)); + const account = asAdmin ? null : signedIn ? signedIn(req) : holder && world.moderation.banRemaining(holder) === 0 ? holder : null; + if (!account && !asAdmin) { + send(res, 200, {error: "Sign in first."}); + return; + } + const kind = url.searchParams.get("kind"); + const entry = customItems.get(kind, url.searchParams.get("id")); + if (!entry) { + send(res, 200, {error: "No such custom item."}); + return; + } + const staffMay = asAdmin || roles.can(account, "items.create"); + if (!staffMay && entry.ownerId !== account.id) { + send(res, 200, {error: "That is not one of your items."}); + return; + } + const playerItems = require("./playeritems.js"); + const refusal = staffMay || url.searchParams.get("remove") === "1" ? null : playerItems.uploadRefusal(account, from.local); + if (refusal) { + send(res, 200, refusal); + return; + } + if (!from.local && !asAdmin && !artUploads.allow(account.id)) { + send(res, 200, {error: "Too many pictures today. Try again tomorrow."}); + return; + } + let result; + if (url.searchParams.get("remove") === "1") { + result = itemArt.remove(kind, entry.id); + } + else { + const data = await readBody(req, itemArt.MAX_UPLOAD + 1).catch(() => null); + // a player's own picture waits for a moderator unless the admin says not; + // one turned away before may not come back. + const waits = !staffMay && playerItems.pictureWaits(); + result = data ? await itemArt.set(kind, entry.id, data, waits, staffMay ? null : playerItems.pictureRefused) + : {error: `That picture is too big: ${Math.round(itemArt.MAX_UPLOAD / 1024 / 1024)} MB at most.`}; + } + if (result.ok) { + const owner = entry.ownerId === null ? null : accounts.byId(entry.ownerId); + modlog.record(asAdmin ? "admin" : account.username, url.searchParams.get("remove") === "1" ? "item picture removed" : "item picture set", + owner && owner !== account ? owner.username : "", `${kind} ${entry.id} ${entry.name}`); + } + send(res, 200, result); +}; + +// a picture still waiting for a moderator, which /itemart/ does not serve: +// to its maker (the account page) and to staff who review or make items. +const itemArtView = (req, res, url, signedIn, adminSignedIn) => { + res.setHeader("Cache-Control", "private, no-store"); + const asAdmin = Boolean(adminSignedIn && adminSignedIn(req)); + const account = asAdmin ? null : signedIn ? signedIn(req) : null; + const entry = customItems.get(url.searchParams.get("kind"), url.searchParams.get("id")); + const allowed = entry && (asAdmin || (account && (entry.ownerId === account.id || roles.can(account, "items.approve") || roles.can(account, "items.create")))); + const picture = allowed ? itemArt.file(entry.kind, entry.id, true) : null; + if (!picture) { + send(res, 404, "Not found", "text/plain"); + return; + } + res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox"); + res.setHeader("X-Content-Type-Options", "nosniff"); + send(res, 200, picture.data, `image/${picture.type}`); +}; + const send = (res, status, body, type = "application/json") => { const data = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : JSON.stringify(body)); res.writeHead(status, {"Content-Type": type, "Content-Length": data.length}); @@ -156,6 +248,8 @@ const MISSING_ASSET_SECONDS = 600; // how long a client may keep the CDN's "no s const cacheMisses = limits.limiter(config.cacheMissesPerTenMinutes, TEN_MINUTES_MS); // files fetched from the official CDN for one address const errorReports = limits.limiter(config.errorReportsPerMinute, 60000); const paintingPosts = limits.limiter(60, TEN_MINUTES_MS); // per address; each also needs a token from the game +const artUploads = limits.limiter(10, 24 * 3600000); // custom items' pictures, per account a day +const emojiFetches = limits.limiter(600, TEN_MINUTES_MS); // emoji pictures not kept yet, asked of the upstream, per address const PAINTING_PATH = /^\/masterpieces\/([0-9a-f-]{36})$/; // where clients ask for the HUD artwork; ours is a changed copy. @@ -372,7 +466,7 @@ const renameAndSignIn = (res, body, from) => { manage.forget(account); accounts.recordLogin(account, "launcher", from.address); accounts.save(account); - console.log(`[accounts] a rejected username was replaced by "${account.username}"`); + console.log(`[accounts] a rejected username was replaced by "${logText(account.username)}"`); accounts.setLoginChoices(account, body.login_choices); const token = accounts.issueToken(account); send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken}); @@ -392,36 +486,57 @@ const authenticate = async (req, res, from) => { send(res, 426, {error_code: 101, error: "client_outdated"}); return; } - const byRefresh = body.refresh_token !== undefined; const accountKey = String(body.username).trim().toLowerCase(); if (!from.local && failuresByAddress.blocked(from.key)) { send(res, 429, {error_code: 429, error: "too_many_attempts"}); return; } + // A saved sign-in ("remember me"): the account its token is good for, + // which is what the rest goes by. a token is only ever given after a + // whole sign-in (password, captcha and 2FA code), so one that is good + // stands in for them; one that is not is refused here, whatever else + // the request says. (Whether the request offers a token is not what + // decides: only the server's own answer for it.) + const saved = accounts.byToken(body.refresh_token); // null for none, or for one that is not good + if (saved) { + await signInChecked(res, body, from, saved, true, device); + return; + } + if (body.refresh_token !== undefined) { + failuresByAddress.record(from.key); + // error_code 100 = expired refresh token + send(res, 401, {error_code: 100}); + return; + } // a password is not looked at before the captcha. the custom client // knows these errors; the official launcher shows them as a wrong password. - const captchaProblem = byRefresh ? null : await captcha.check(body, from, "login", accounts.byName(accountKey)); + const captchaProblem = await captcha.check(body, from, "login", accounts.byName(accountKey)); if (captchaProblem) { send(res, captchaProblem === "captcha_unavailable" ? 503 : 401, {error_code: 101, error: captchaProblem}); return; } - const account = byRefresh - ? accounts.byToken(body.refresh_token) - : await accounts.authenticateAsync(body.username, body.password); + const account = await accounts.authenticateAsync(body.username, body.password); if (!account) { failuresByAddress.record(from.key); - if (!byRefresh) { - // A wrong password shows in the account's own login history. - const tried = accounts.byName(accountKey); - if (tried) { - accounts.recordLogin(tried, "launcher", from.address, false); - accounts.save(tried); - } + // A wrong password shows in the account's own login history. + const tried = accounts.byName(accountKey); + if (tried) { + accounts.recordLogin(tried, "launcher", from.address, false); + accounts.save(tried); } - // error_code 100 = expired refresh token, 101 = wrong credentials - send(res, 401, {error_code: byRefresh ? 100 : 101}); + // error_code 101 = wrong credentials + send(res, 401, {error_code: 101}); return; } + await signInChecked(res, body, from, account, false, device); +}; + +// the rest of a sign-in, for an account whose password was right (`saved` +// false) or whose saved sign-in's token was good (`saved` true; then it is +// not asked for a 2FA code again, and the token it has is the one it keeps). +// `device`: the computer it is on (lib/devices.js), or null for a client that does not say. +const signInChecked = async (res, body, from, account, saved, device) => { + const byRefresh = saved === true; // banned: said here, with how long is left (-1 for good), where a client // can show it. the game itself would only be refused at its socket with // the one line it has for that, which says neither. the password (or the @@ -444,7 +559,7 @@ const authenticate = async (req, res, from) => { // account was seen on. const deviceBan = device ? devices.banOf(device) : devices.banOfAccount(account); if (deviceBan) { - console.log(`[devices] "${account.username}" refused: hardware banned (ban ${deviceBan.id})`); + console.log(`[devices] "${logText(account.username)}" refused: hardware banned (ban ${logText(deviceBan.id)})`); send(res, 401, {error_code: 101, error: "device_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: deviceBan.reason}); return; } @@ -514,6 +629,10 @@ const player = (req, res) => { }; const handle = async (req, res) => { + // over https, browsers are told to keep to it (a year) + if (config.secureCookies) { + res.setHeader("Strict-Transport-Security", "max-age=31536000"); + } const url = new URL(req.url, config.baseUrl); const route = `${req.method} ${url.pathname}`; @@ -553,10 +672,20 @@ const handle = async (req, res) => { send(res, 404, "Not found", "text/plain"); return; } + if (url.pathname === "/admin/api/itemart") { + res.setHeader("Cache-Control", "no-store"); + await itemArtUpload(req, res, url, from, null, panel.signedIn); + return; + } await panel.handle(req, res, url, from, {send, readJson}); return; } + if (isAccount && url.pathname === "/account/api/itemart") { + res.setHeader("Cache-Control", "no-store"); + await itemArtUpload(req, res, url, from, manage.signedInAs); + return; + } if (isAccount) { await manage.handle(req, res, url, from, {send, readJson}); return; @@ -564,6 +693,11 @@ const handle = async (req, res) => { // and the moderator panel (lib/modpanel.js), which is there for anyone to // reach: its moderators are players, wherever they are. + if (isMod && url.pathname === "/mod/api/itemart") { + res.setHeader("Cache-Control", "no-store"); + await itemArtUpload(req, res, url, from, modpanel.signedInAs); + return; + } if (isMod) { await modpanel.handle(req, res, url, from, {send, readJson}); return; @@ -589,6 +723,39 @@ const handle = async (req, res) => { return; } + // custom items' own pictures (lib/itemart.js): served as the picture + // they are and nothing else. + const artPath = /^\/itemart\/(clothing|den)\/(\d{1,9})\.png$/.exec(url.pathname); + if (artPath && (req.method === "GET" || req.method === "HEAD")) { + const picture = itemArt.file(artPath[1], artPath[2]); + if (!picture) { + send(res, 404, "Not found", "text/plain"); + return; + } + res.setHeader("Cache-Control", "public, max-age=31536000, immutable"); + res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox"); + res.setHeader("Content-Disposition", "inline"); + send(res, 200, picture.data, `image/${picture.type}`); + return; + } + // emoji pictures for chat bubbles (lib/emoji.js) + const emojiPath = /^\/emoji\/([0-9a-f-]{2,80})\.png$/.exec(url.pathname); + if (emojiPath && (req.method === "GET" || req.method === "HEAD")) { + const picture = await emoji.get(emojiPath[1], () => from.local || emojiFetches.allow(from.key)); + if (!picture) { + send(res, 404, "Not found", "text/plain"); + return; + } + res.setHeader("Cache-Control", "public, max-age=31536000, immutable"); + res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox"); + send(res, 200, picture, "image/png"); + return; + } + if (url.pathname === "/api/itemart") { + await itemArtUpload(req, res, url, from); + return; + } + if (url.pathname.startsWith("/api/")) { // the item finder's API changes accounts, so other sites open in a // browser on this machine must not be able to call it. @@ -732,7 +899,7 @@ const handle = async (req, res) => { if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) { const again = trace ? "" : repeatedError(`${section} ${message}`); if (again !== null) { - console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}${again}`); + console.log(`[${logText(trace ? "client-trace" : "client-error")}] (${logText(section)}) ${logText(message)}${logText(again)}`); if (!trace) { keepClientError(`${new Date().toISOString()} (${section}) ${message}${again}\n`); } @@ -755,7 +922,7 @@ const handle = async (req, res) => { return; } const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024)); - const uuid = masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image")); + const uuid = await masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image")); send(res, 200, uuid ? {success: true, uuid} : {success: false}); return; } @@ -771,13 +938,13 @@ const handle = async (req, res) => { } if (req.method !== "GET" && req.method !== "HEAD") { - console.log(`[http] unhandled ${route}`); + console.log(`[http] unhandled ${logText(route)}`); send(res, 404, {error: "not_found"}); return; } if (config.logPackets) { - console.log(`[http] GET ${url.pathname}`); + console.log(`[http] GET ${logText(url.pathname)}`); } // asset SWFs import their fonts from this fixed path next to the game page; @@ -843,7 +1010,7 @@ const handle = async (req, res) => { res.setHeader("Cache-Control", `public, max-age=${MISSING_ASSET_SECONDS}`); } else { - console.log(`[http] 404 ${url.pathname}`); + console.log(`[http] 404 ${logText(url.pathname)}`); } send(res, 404, "Not found", "text/plain"); return; @@ -855,7 +1022,8 @@ const handle = async (req, res) => { const start = () => new Promise((resolve, reject) => { const onRequest = (req, res) => { handle(req, res).catch(err => { - console.log(`[http] ${req.method} ${req.url} failed: ${err.message}`); + // the path only: a query may hold a login token (the item finder's, the Item Maker's) + console.log(`[http] ${logText(req.method)} ${logText(String(req.url).split("?")[0])} failed: ${logText(err.message)}`); if (!res.headersSent) { send(res, 500, {error: "server_error"}); } @@ -904,7 +1072,7 @@ const start = () => new Promise((resolve, reject) => { }); server.once("error", reject); server.listen(config.httpPort, config.bindAddress, () => { - console.log(`[http] listening on ${config.bindAddress}:${config.httpPort}${config.webTls ? " (TLS)" : ""}`); + console.log(`[http] listening on ${logText(config.bindAddress)}:${logText(config.httpPort)}${logText(config.webTls ? " (TLS)" : "")}`); resolve(server); }); }); diff --git a/lib/image-moderation.js b/lib/image-moderation.js new file mode 100644 index 0000000..f13b58d --- /dev/null +++ b/lib/image-moderation.js @@ -0,0 +1,52 @@ +"use strict"; + +const config = require("../config.js"); + +// Google Cloud Vision SafeSearch detects adult and racy material. We keep +// this dependency-free and use its REST API so deploying the server needs no +// service-account files or Google SDK in node_modules. +const UNSAFE = new Set(["LIKELY", "VERY_LIKELY"]); +const TIMEOUT_MS = 10000; + +// {blocked, error}; `error` deliberately fails closed when the scanner is +// enabled: accepting an image while the safety service is unavailable would +// make this protection easy to bypass. +const scan = async image => { + if (!config.googleVision) { + return {blocked: false}; + } + if (!Buffer.isBuffer(image) || image.length === 0) { + return {blocked: true, error: "That picture could not be checked for safety."}; + } + const abort = new AbortController(); + const timer = setTimeout(() => abort.abort(), TIMEOUT_MS); + try { + const response = await fetch(config.googleVision.endpoint, { + method: "POST", + headers: {"Content-Type": "application/json"}, + signal: abort.signal, + body: JSON.stringify({ + requests: [{image: {content: image.toString("base64")}, features: [{type: "SAFE_SEARCH_DETECTION"}]}], + }), + }); + const result = await response.json().catch(() => null); + const safeSearch = result && result.responses && result.responses[0] && result.responses[0].safeSearchAnnotation; + if (!response.ok || !safeSearch) { + console.error(`[image-moderation] Google Vision request failed (${response.status})`); + return {blocked: true, error: "Picture safety checking is temporarily unavailable. Please try again."}; + } + if (UNSAFE.has(safeSearch.adult) || UNSAFE.has(safeSearch.racy)) { + return {blocked: true, error: "That picture was blocked because it may contain nudity or other NSFW content."}; + } + return {blocked: false}; + } + catch (err) { + console.error(`[image-moderation] Google Vision request failed: ${err.message}`); + return {blocked: true, error: "Picture safety checking is temporarily unavailable. Please try again."}; + } + finally { + clearTimeout(timer); + } +}; + +module.exports = {scan}; diff --git a/lib/itemart.js b/lib/itemart.js new file mode 100644 index 0000000..00eead6 --- /dev/null +++ b/lib/itemart.js @@ -0,0 +1,403 @@ +"use strict"; + +const crypto = require("crypto"); +const fs = require("fs"); +const path = require("path"); +const zlib = require("zlib"); +const config = require("../config.js"); +const customItems = require("./customitems.js"); +const imageModeration = require("./image-moderation.js"); + +// custom items' own pictures: uploaded by the item's maker (or staff), shown +// by the patched client in place of the item's icon, and for a den item in +// place of the item standing in a den (AJClient.customArtUrl). worn +// clothing keeps the art it was made from: that is drawn for every animal +// and pose, which one picture cannot be. +// +// a picture is checked before it is kept: a PNG, a JPEG or a GIF by its own +// bytes (whatever it is called), of a sensible size, and kept without what +// else such files carry (a photo's EXIF, with where it was taken; PNG text; +// GIF comments). a BMP is made a PNG. (the pages and the game turn other +// kinds, and pictures too big, into a PNG before they send them.) +// kept as data/itemart/-.; its version, a hash, is on +// the item (customItems.setArt), so a new picture is a new address. + +const MAX_BYTES = 300 * 1024; // a picture kept +const MAX_UPLOAD = 2 * 1024 * 1024; // one sent (a BMP is bigger than the PNG it becomes) +const MAX_SIDE = 512; +const MIN_SIDE = 8; +const DIR = path.join(config.dataDir, "itemart"); +const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); +// the PNG chunks a picture needs; text, times, EXIF and the like are dropped +const PNG_KEPT = new Set(["IHDR", "PLTE", "IDAT", "IEND", "tRNS", "gAMA", "cHRM", "sRGB", "iCCP", "sBIT", "pHYs"]); + +const TYPES = ["png", "jpeg", "gif"]; +const EXTENSION = {png: "png", jpeg: "jpg", gif: "gif"}; +const VERSION_MARK = {png: "p", jpeg: "j", gif: "g"}; + +const fileOf = (kind, id, type) => path.join(DIR, `${kind}-${Number(id)}.${EXTENSION[type]}`); + +// a GIF's blocks, without comments, plain text and any application block but +// the one that says it loops; null when it is not a whole GIF. kept animated. +const cleanGif = data => { + const head = data.toString("latin1", 0, 6); + if (data.length < 14 || (head !== "GIF87a" && head !== "GIF89a")) { + return null; + } + const width = data.readUInt16LE(6); + const height = data.readUInt16LE(8); + const packed = data[10]; + let at = 13 + (packed & 0x80 ? 3 * (2 << (packed & 7)) : 0); + if (at > data.length) { + return null; + } + const kept = [data.subarray(0, at)]; + // sub-blocks from `from`: where they end (after the 0 that ends them) + const subBlocksEnd = from => { + let i = from; + while (i < data.length && data[i] !== 0) { + i += data[i] + 1; + } + return i < data.length ? i + 1 : -1; + }; + let images = 0; + while (at < data.length) { + const block = data[at]; + if (block === 0x3B) { + kept.push(data.subarray(at, at + 1)); + return images ? {data: Buffer.concat(kept), width, height, type: "gif"} : null; + } + if (block === 0x2C) { + if (at + 10 > data.length) { + return null; + } + const local = data[at + 9]; + const start = at; + at += 10 + (local & 0x80 ? 3 * (2 << (local & 7)) : 0) + 1; // the descriptor, its colours, the LZW code size + const end = subBlocksEnd(at); + if (end === -1) { + return null; + } + kept.push(data.subarray(start, end)); + at = end; + images++; + continue; + } + if (block === 0x21 && at + 2 <= data.length) { + const label = data[at + 1]; + const end = subBlocksEnd(at + 2); + if (end === -1) { + return null; + } + const loops = label === 0xFF && data.toString("latin1", at + 3, at + 14) === "NETSCAPE2.0"; + if (label === 0xF9 || loops) { + kept.push(data.subarray(at, end)); + } + at = end; + continue; + } + return null; + } + return null; +}; + +// a PNG of RGBA pixels (`pixels`, width * height * 4 bytes, rows top down). +const CRC_TABLE = Array.from({length: 256}, (unused, n) => { + let c = n; + for (let k = 0; k < 8; k++) { + c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; + } + return c >>> 0; +}); +const crc32 = buffer => { + let c = 0xFFFFFFFF; + for (const byte of buffer) { + c = CRC_TABLE[(c ^ byte) & 0xFF] ^ (c >>> 8); + } + return (c ^ 0xFFFFFFFF) >>> 0; +}; +const pngChunk = (type, body) => { + const length = Buffer.alloc(4); + length.writeUInt32BE(body.length); + const typed = Buffer.concat([Buffer.from(type, "latin1"), body]); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(typed)); + return Buffer.concat([length, typed, crc]); +}; +const encodePng = (width, height, pixels) => { + const header = Buffer.alloc(13); + header.writeUInt32BE(width, 0); + header.writeUInt32BE(height, 4); + header[8] = 8; // bits a channel + header[9] = 6; // RGBA + const rows = Buffer.alloc((width * 4 + 1) * height); + for (let y = 0; y < height; y++) { + pixels.copy(rows, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4); + } + return Buffer.concat([PNG_SIGNATURE, pngChunk("IHDR", header), pngChunk("IDAT", zlib.deflateSync(rows)), pngChunk("IEND", Buffer.alloc(0))]); +}; + +// RGBA pixels shrunk to fit `side` (each new pixel the mean of those it covers). +const shrink = (width, height, pixels, side) => { + const scale = Math.min(1, side / width, side / height); + if (scale === 1) { + return {width, height, pixels}; + } + const w = Math.max(1, Math.round(width * scale)); + const h = Math.max(1, Math.round(height * scale)); + const out = Buffer.alloc(w * h * 4); + for (let y = 0; y < h; y++) { + const y0 = Math.floor(y / scale); + const y1 = Math.min(height, Math.max(y0 + 1, Math.floor((y + 1) / scale))); + for (let x = 0; x < w; x++) { + const x0 = Math.floor(x / scale); + const x1 = Math.min(width, Math.max(x0 + 1, Math.floor((x + 1) / scale))); + const sum = [0, 0, 0, 0]; + for (let sy = y0; sy < y1; sy++) { + for (let sx = x0; sx < x1; sx++) { + for (let c = 0; c < 4; c++) { + sum[c] += pixels[(sy * width + sx) * 4 + c]; + } + } + } + const count = (y1 - y0) * (x1 - x0); + for (let c = 0; c < 4; c++) { + out[(y * w + x) * 4 + c] = Math.round(sum[c] / count); + } + } + } + return {width: w, height: h, pixels: out}; +}; + +// a BMP (uncompressed, or bit fields: 1, 4, 8, 24 or 32 bits a pixel) as a +// PNG, shrunk to fit; null when it is not one this can read. +const MAX_BMP_SIDE = 4096; +const bmpToPng = data => { + if (data.length < 54 || data.toString("latin1", 0, 2) !== "BM") { + return null; + } + const offset = data.readUInt32LE(10); + const headerSize = data.readUInt32LE(14); + if (headerSize < 40) { + return null; + } + const width = data.readInt32LE(18); + const rawHeight = data.readInt32LE(22); + const height = Math.abs(rawHeight); + const bits = data.readUInt16LE(28); + const compression = data.readUInt32LE(30); + if (width < 1 || height < 1 || width > MAX_BMP_SIDE || height > MAX_BMP_SIDE || ![1, 4, 8, 24, 32].includes(bits) || ![0, 3].includes(compression)) { + return null; + } + const stride = Math.ceil(width * bits / 32) * 4; + if (offset + stride * height > data.length) { + return null; + } + const paletteAt = 14 + headerSize; + const pixels = Buffer.alloc(width * height * 4); + const hasAlpha = bits === 32 && (headerSize >= 56 || compression === 3); + for (let y = 0; y < height; y++) { + const row = offset + (rawHeight > 0 ? height - 1 - y : y) * stride; + for (let x = 0; x < width; x++) { + const o = (y * width + x) * 4; + let b; + let g; + let r; + let a = 255; + if (bits >= 24) { + const p = row + x * (bits / 8); + [b, g, r] = [data[p], data[p + 1], data[p + 2]]; + if (hasAlpha) { + a = data[p + 3]; + } + } + else { + const perByte = 8 / bits; + const byte = data[row + Math.floor(x / perByte)]; + const index = (byte >> ((perByte - 1 - (x % perByte)) * bits)) & ((1 << bits) - 1); + const entry = paletteAt + index * 4; + if (entry + 3 > data.length) { + return null; + } + [b, g, r] = [data[entry], data[entry + 1], data[entry + 2]]; + } + pixels[o] = r; + pixels[o + 1] = g; + pixels[o + 2] = b; + pixels[o + 3] = a; + } + } + const small = shrink(width, height, pixels, MAX_SIDE); + return {data: encodePng(small.width, small.height, small.pixels), width: small.width, height: small.height, type: "png"}; +}; + +// a PNG's chunks, without the ones not kept; null when it is not a whole PNG. +const cleanPng = data => { + if (data.length < 33 || !data.subarray(0, 8).equals(PNG_SIGNATURE)) { + return null; + } + const kept = [PNG_SIGNATURE]; + let at = 8; + let width = 0; + let height = 0; + let ended = false; + while (at + 12 <= data.length) { + const length = data.readUInt32BE(at); + const type = data.toString("latin1", at + 4, at + 8); + if (at + 12 + length > data.length) { + return null; + } + if (type === "IHDR") { + width = data.readUInt32BE(at + 8); + height = data.readUInt32BE(at + 12); + } + if (PNG_KEPT.has(type)) { + kept.push(data.subarray(at, at + 12 + length)); + } + at += 12 + length; + if (type === "IEND") { + ended = true; + break; + } + } + return ended && width && height ? {data: Buffer.concat(kept), width, height, type: "png"} : null; +}; + +// a JPEG without its APP1..APP15 (EXIF, XMP, ...) and comment segments; +// null when it is not one. its size is read from the frame header. +const cleanJpeg = data => { + if (data.length < 4 || data[0] !== 0xFF || data[1] !== 0xD8) { + return null; + } + const kept = [data.subarray(0, 2)]; + let at = 2; + let width = 0; + let height = 0; + while (at + 4 <= data.length) { + if (data[at] !== 0xFF) { + return null; + } + const marker = data[at + 1]; + if (marker === 0xD9) { + kept.push(data.subarray(at, at + 2)); + break; + } + const length = data.readUInt16BE(at + 2); + if (length < 2 || at + 2 + length > data.length) { + return null; + } + const segment = data.subarray(at, at + 2 + length); + // start of frame (not DHT, JPG or DAC): the size + if (marker >= 0xC0 && marker <= 0xCF && ![0xC4, 0xC8, 0xCC].includes(marker)) { + height = data.readUInt16BE(at + 5); + width = data.readUInt16BE(at + 7); + } + const dropped = (marker >= 0xE1 && marker <= 0xEF) || marker === 0xFE; + if (!dropped) { + kept.push(segment); + } + at += 2 + length; + // start of scan: the compressed data runs to the end + if (marker === 0xDA) { + kept.push(data.subarray(at)); + break; + } + } + return width && height ? {data: Buffer.concat(kept), width, height, type: "jpeg"} : null; +}; + +// checks and cleans an upload: {data, type} or {error}. +const check = data => { + if (!Buffer.isBuffer(data) || data.length === 0) { + return {error: "Choose a picture first."}; + } + if (data.length > MAX_UPLOAD) { + return {error: `That picture is too big: ${Math.round(MAX_UPLOAD / 1024 / 1024)} MB at most.`}; + } + const image = cleanPng(data) || cleanJpeg(data) || cleanGif(data) || bmpToPng(data); + if (!image) { + return {error: "That is not a PNG, JPEG, GIF or BMP picture."}; + } + if (image.data.length > MAX_BYTES) { + return {error: `That picture is too big: ${Math.round(MAX_BYTES / 1024)} KB at most once cleaned. A smaller one, please.`}; + } + if (image.width > MAX_SIDE || image.height > MAX_SIDE || image.width < MIN_SIDE || image.height < MIN_SIDE) { + return {error: `A picture from ${MIN_SIDE} to ${MAX_SIDE} pixels on each side, please.`}; + } + return image; +}; + +const digest = data => crypto.createHash("sha256").update(data).digest("hex"); + +// sets an item's picture. resolves to {ok, art} or {error}. +// `pending`: it waits for a moderator before anyone is shown it (lib/playeritems.js). +// `refused(hash)`: whether a picture of that SHA-256 (once cleaned) was +// turned away before, and may not be sent again. +const set = async (kind, id, data, pending = false, refused = null) => { + const entry = customItems.get(kind, id); + if (!entry) { + return {error: "No such custom item."}; + } + const image = check(data); + if (image.error) { + return image; + } + if (refused && refused(digest(image.data))) { + return {error: "A moderator turned that picture away before. Choose another one."}; + } + const safety = await imageModeration.scan(image.data); + if (safety.blocked) { + return {error: safety.error}; + } + fs.mkdirSync(DIR, {recursive: true}); + for (const type of TYPES) { + fs.rmSync(fileOf(kind, entry.id, type), {force: true}); + } + fs.writeFileSync(fileOf(kind, entry.id, image.type), image.data); + const art = `${VERSION_MARK[image.type]}${crypto.createHash("sha256").update(image.data).digest("hex").slice(0, 12)}`; + customItems.setArt(kind, entry.id, art, pending); + return {ok: pending ? `${entry.name}'s new picture is waiting for a moderator to approve it.` : `${entry.name} has a new picture.`, art}; +}; + +// takes an item's picture away (its maker's choice, or staff's). +const remove = (kind, id) => { + const entry = customItems.get(kind, id); + if (!entry || !entry.art) { + return {error: "That item has no picture of its own."}; + } + for (const type of TYPES) { + fs.rmSync(fileOf(kind, entry.id, type), {force: true}); + } + customItems.setArt(kind, entry.id, null); + return {ok: `${entry.name}'s picture was taken away.`}; +}; + +// the picture to serve: {data, type} or null. one waiting for a moderator +// only `withPending`: for the maker and the moderators (lib/http.js). +const file = (kind, id, withPending = false) => { + const entry = customItems.get(kind, id); + if (!entry || !entry.art || (entry.artPending && !withPending)) { + return null; + } + const type = TYPES.find(one => entry.art.startsWith(VERSION_MARK[one])) || "png"; + try { + return {data: fs.readFileSync(fileOf(kind, entry.id, type)), type}; + } + catch { + return null; + } +}; + +// the SHA-256 of an item's picture as kept, waiting or not: null for none. +const digestOf = (kind, id) => { + const picture = file(kind, id, true); + return picture ? digest(picture.data) : null; +}; + +// where a page shows an item's picture: the public address once anyone may +// see it; while it waits, `base` (the page's own /…/api/itemart, which asks +// who it is first). +const urlOf = (entry, base) => (!entry.art ? null : entry.artPending + ? `${base}?kind=${entry.kind}&id=${entry.id}&v=${entry.art}` : `/itemart/${entry.kind}/${entry.id}.png?v=${entry.art}`); + +module.exports = {set, remove, file, check, digestOf, urlOf, MAX_BYTES, MAX_UPLOAD}; diff --git a/lib/itemcontrol.js b/lib/itemcontrol.js new file mode 100644 index 0000000..9fe77c6 --- /dev/null +++ b/lib/itemcontrol.js @@ -0,0 +1,141 @@ +"use strict"; + +const accounts = require("./accounts.js"); +const customItems = require("./customitems.js"); +const defpacks = require("./defpacks.js"); + +// what staff who make items (items.create: admins and developers) may do +// about who has them: +// +// - lock an item out of the item finder (lib/admin.js): players no longer +// find it there or take it from it. staff who may lock still do, with the +// item marked locked. it stays wherever else it is (a shop, a trade). +// - take an item from one player: every one of it they have. +// - delete a custom item (lib/customitems.js): out of the game, and out of +// every inventory. + +const LOCKS_SETTING = "finderLocks"; +const KINDS = ["clothing", "den"]; + +let locks = null; // Set of "kind:id" + +const key = (kind, id) => `${kind}:${Number(id)}`; + +const lockSet = () => { + if (!locks) { + let saved = []; + try { + saved = JSON.parse(accounts.setting(LOCKS_SETTING) || "[]"); + } + catch { + saved = []; + } + locks = new Set(Array.isArray(saved) ? saved.map(String) : []); + } + return locks; +}; + +const saveLocks = () => accounts.setSetting(LOCKS_SETTING, JSON.stringify([...lockSet()])); + +const defOf = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id)); + +const nameOf = (kind, id) => { + const def = defOf(kind, id); + if (!def) { + return ""; + } + return kind === "den" ? defpacks.string(def.nameStrId) || def.abbrName || "" : defpacks.string(def.titleStrId); +}; + +const describe = (kind, id) => `${nameOf(kind, id) || "(no name)"} (${kind === "den" ? "den item" : "clothing"} ${Number(id)})`; + +// checks a kind and id typed by staff: {kind, id} of an item that exists, or {error}. +const item = (kind, id) => { + const number = Number(id); + if (!KINDS.includes(kind)) { + return {error: "The kind is clothing or den."}; + } + if (!Number.isInteger(number) || !defOf(kind, number) || (kind === "clothing" && !defpacks.clothingIds().includes(number))) { + return {error: `No ${kind === "den" ? "den item" : "clothing"} with the id ${id}.`}; + } + return {kind, id: number}; +}; + +const isLocked = (kind, id) => lockSet().has(key(kind, id)); + +// returns {ok} or {error}. +const setLocked = (kind, id, locked) => { + const found = item(kind, id); + if (found.error) { + return found; + } + const was = isLocked(found.kind, found.id); + if (was === locked) { + return {error: `${describe(found.kind, found.id)} is ${locked ? "already" : "not"} locked.`}; + } + lockSet()[locked ? "add" : "delete"](key(found.kind, found.id)); + saveLocks(); + return {ok: `${describe(found.kind, found.id)} is ${locked ? "locked out of" : "back in"} the item finder.`}; +}; + +const lockedList = () => [...lockSet()].map(entry => { + const [kind, id] = entry.split(":"); + return {kind, id: Number(id), name: nameOf(kind, id)}; +}); + +// every one of an item an account has, out of its inventory (and its trade +// list). `world` tells a game playing (lib/world.js itemsTaken). returns how +// many went. +const takeFromAccount = (account, kind, id, world) => { + const number = Number(id); + const collection = kind === "den" ? "denItems" : "items"; + const gone = account[collection].filter(entry => entry.def === number); + if (!gone.length) { + return 0; + } + const invs = new Set(gone.map(entry => entry.inv)); + account[collection] = account[collection].filter(entry => !invs.has(entry.inv)); + account.tradeList = account.tradeList.filter(entry => !invs.has(entry.inv)); + accounts.save(); + world.itemsTaken(account, kind, [...invs], kind === "clothing" && gone.some(entry => entry.on.length > 0)); + return gone.length; +}; + +// from one player, by username. returns {ok, count} or {error}. +const take = (username, kind, id, world) => { + const account = accounts.byName(username); + if (!account) { + return {error: `No player called ${username}.`}; + } + // a deleted custom item can be gone from the tables and still be owned: + // the id is taken as it is then. + const found = item(kind, id); + if (found.error && !(KINDS.includes(kind) && Number.isInteger(Number(id)))) { + return found; + } + const count = takeFromAccount(account, kind, id, world); + return count ? {ok: `Took ${count} of ${describe(kind, id)} from ${account.username}.`, count} + : {error: `${account.username} has no ${describe(kind, id)}.`}; +}; + +// a custom item out of the game, and out of everyone's inventory. returns {ok} or {error}. +const deleteCustom = (kind, id, world) => { + const entry = customItems.get(kind, id); + if (!entry) { + return {error: "No such custom item."}; + } + let count = 0; + for (const account of accounts.all()) { + count += takeFromAccount(account, kind, entry.id, world); + } + if (entry.art) { + require("./itemart.js").remove(kind, entry.id); + } + customItems.remove(kind, entry.id); + if (lockSet().delete(key(kind, entry.id))) { + saveLocks(); + } + return {ok: `Deleted ${entry.name} (${kind === "den" ? "den item" : "clothing"} ${entry.id})${count ? `, and took ${count} from players` : ""}.`}; +}; + +module.exports = {isLocked, setLocked, lockedList, take, deleteCustom}; diff --git a/lib/logtext.js b/lib/logtext.js new file mode 100644 index 0000000..db7053c --- /dev/null +++ b/lib/logtext.js @@ -0,0 +1,17 @@ +"use strict"; + +// a value from outside (a username, an address, what a client sent) as it +// may go into a line of the server's log: on one line, and with no control +// characters, so that it cannot pass for a line of the server's own (a name +// with a line break in it, "...\n[admin] signed in") or move the terminal's +// cursor about. (U+2028 and U+2029, which end a line too, are in the second.) +const OTHER_BREAKS_AND_CONTROLS = new RegExp("[\x00-\x1f\x7f-\x9f\u2028\u2029]", "g"); + +// (line feeds go first, and to nothing: the form code scanning knows as a +// log's sanitiser. carriage returns, and the rest, are then replaced.) +const logText = value => String(value) + .replace(/\n/g, "") + .replace(/\r/g, " ") + .replace(OTHER_BREAKS_AND_CONTROLS, "?"); + +module.exports = {logText}; diff --git a/lib/manage.js b/lib/manage.js index 1e702e5..7d1a26e 100644 --- a/lib/manage.js +++ b/lib/manage.js @@ -1,5 +1,9 @@ "use strict"; +const {logText} = require("./logtext.js"); +const customItems = require("./customitems.js"); +const itemControl = require("./itemcontrol.js"); +const playerItems = require("./playeritems.js"); const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); @@ -149,6 +153,11 @@ const profile = (account, from) => { animalType: avatar ? avatar.type : null, items: account.items.length, denItems: account.denItems.length, + // what they made in the game's Item Maker (lib/playeritems.js) + customItems: playerItems.madeBy(account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name, + art: require("./itemart.js").urlOf(entry, "/account/api/itemart"), artWaiting: Boolean(entry.artPending), look: entry.artMode || "sticker"})), + picturesStopped: Boolean(account.artBlocked), + customItemLimits: {perDay: playerItems.PER_DAY, inAll: playerItems.IN_ALL}, pets: account.pets.length, buddies: account.buddies.length, banned: null, @@ -179,7 +188,7 @@ const profile = (account, from) => { // hash, the 2FA secret, device passes), and what other tables hold of it. // what others wrote about it (reports, a moderator's notes) is not theirs // to be handed, and is not here. -const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices"]; +const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes"]; const dataOf = account => ({ exportedAt: new Date().toISOString(), server: config.baseUrl, @@ -250,7 +259,7 @@ const act = (account, body, req, from, res) => { } delete account.nameRejected; accounts.save(account); - console.log(`[account] a rejected username was replaced by "${account.username}" from ${from.address}`); + console.log(`[account] a rejected username was replaced by "${logText(account.username)}" from ${logText(from.address)}`); return {ok: "Saved."}; } // one for each account, ever: an answer that wants a follow-up says @@ -267,12 +276,14 @@ const act = (account, body, req, from, res) => { if (!passwordAgain(account, body.current)) { return {error: "Wrong password."}; } - if (accounts.setPassword(account, body.password)) { - return {error: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."}; + const passwordProblem = accounts.setPassword(account, body.password); + if (passwordProblem) { + return {error: passwordProblem === "weak_password" ? "That password is too easy to guess: it is a common one, or has your username in it." + : "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."}; } world.moderation.actions.kick(account); signOutOthers(account, req); - console.log(`[account] "${account.username}" changed their password from ${from.address}`); + console.log(`[account] "${logText(account.username)}" changed their password from ${logText(from.address)}`); return {ok: "Password changed."}; } case "requestName": { @@ -293,7 +304,7 @@ const act = (account, body, req, from, res) => { world.moderation.actions.kick(account); } accounts.save(account); - console.log(`[account] "${account.username}" ${account.locked ? "locked" : "unlocked"} from ${from.address}`); + console.log(`[account] "${logText(account.username)}" ${logText(account.locked ? "locked" : "unlocked")} from ${logText(from.address)}`); return {ok: account.locked ? "Locked." : "Unlocked."}; } case "feature": { @@ -322,11 +333,12 @@ const act = (account, body, req, from, res) => { const recovery = totp.confirm(account, body.code); if (!recovery) { accounts.save(account); - return {error: "Wrong code."}; + // confirm() drops a setup older than 15 minutes: no code can match it now. + return {error: account.totpSetup ? "Wrong code." : "Setup timed out. Turn 2FA on again and scan the new QR code."}; } accounts.revokeTokens(account); accounts.save(account); - console.log(`[account] "${account.username}" turned two-step sign-in on from ${from.address}`); + console.log(`[account] "${logText(account.username)}" turned two-step sign-in on from ${logText(from.address)}`); return {ok: "2FA is on.", recovery}; } // turning it off: the password and a code (or a recovery code). @@ -344,7 +356,7 @@ const act = (account, body, req, from, res) => { totp.turnOff(account); accounts.save(account); res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE)); - console.log(`[account] "${account.username}" turned two-step sign-in off from ${from.address}`); + console.log(`[account] "${logText(account.username)}" turned two-step sign-in off from ${logText(from.address)}`); return {ok: "2FA is off."}; } case "forgetDevices": @@ -352,6 +364,20 @@ const act = (account, body, req, from, res) => { accounts.save(account); return {ok: "Trusted devices forgotten."}; // their bio, for the Bio tab of their card in the game. empty takes it off. + // their own custom items: a new name, or gone (from everyone who has + // one). a picture is sent to /api/itemart. + case "itemLook": + return playerItems.setLook(account, String(body.kind), body.id, String(body.look)); + case "itemRename": + return playerItems.rename(account, String(body.kind), body.id, body.name); + case "itemDelete": { + const entry = customItems.get(String(body.kind), body.id); + if (!entry || entry.ownerId !== account.id) { + return {error: "That is not one of your items."}; + } + const result = itemControl.deleteCustom(entry.kind, entry.id, world); + return result.error ? result : {ok: `Deleted ${entry.name}.`}; + } case "bio": { // typed words others read: not while they cannot chat. if (world.moderation.isSilenced(account)) { @@ -365,7 +391,7 @@ const act = (account, body, req, from, res) => { // each other (lib/chat-filter.txt). const rule = chatFilter.broken(bio); if (rule) { - console.log(`[filter] "${account.username}" bio not saved (${rule}): ${JSON.stringify(bio)}`); + console.log(`[filter] "${logText(account.username)}" bio not saved (${logText(rule)}): ${logText(JSON.stringify(bio))}`); return {error: "Your bio has words that are not allowed here."}; } account.bio = bio; @@ -446,7 +472,7 @@ const act = (account, body, req, from, res) => { world.disconnect(account); signOutOthers(account, null); erase(account); - console.log(`[account] "${name}" deleted their account from ${from.address}`); + console.log(`[account] "${logText(name)}" deleted their account from ${logText(from.address)}`); return {ok: "Account deleted.", deleted: true}; } default: @@ -601,4 +627,4 @@ const handle = async (req, res, url, from, web) => { // called when an account's name changes or it is deleted: its page sessions end. const forget = account => signOutOthers(account, null); -module.exports = {handle, forget}; +module.exports = {handle, forget, signedInAs}; diff --git a/lib/masterpieces.js b/lib/masterpieces.js index 3c502ca..09cede5 100644 --- a/lib/masterpieces.js +++ b/lib/masterpieces.js @@ -6,6 +6,7 @@ const path = require("path"); const config = require("../config.js"); const accounts = require("./accounts.js"); const limits = require("./limits.js"); +const imageModeration = require("./image-moderation.js"); // masterpieces: paintings from the Art Studio, framed and hung in a den // (client side: game.artStudioPainting.ArtStudioPainting, the same in @@ -181,16 +182,21 @@ const looksLikeJpeg = image => { return false; }; -// step 2. returns the new painting's id, or null when the token is not +// step 2. resolves to the new painting's id, or null when the token is not // good, the picture is not a JPEG of a sane size, or the account has posted // too many. -const upload = (token, image) => { +const upload = async (token, image) => { const entry = typeof token === "string" ? tokens.get(token) : null; tokens.delete(token); if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image) || !uploadsPerHour.allow(entry.account)) { return null; } + const safety = await imageModeration.scan(image); + if (safety.blocked) { + console.log(`[masterpieces] rejected unsafe upload from account ${entry.account}`); + return null; + } // one painting at a time is between the easel and the frame. for (const painting of [...known.values()]) { if (painting.creator === entry.account && painting.status === UPLOADED) { diff --git a/lib/minigames.js b/lib/minigames.js index e475af2..d0818f0 100644 --- a/lib/minigames.js +++ b/lib/minigames.js @@ -75,9 +75,27 @@ const messagesPerMinute = limits.limiter(900, 60000); // the "start" message a game waits for once it has said it is ready. const START = { seed: () => [serial()], - seedAndPlayers: game => [serial(), game.players.length], + // then each player's sfs id and a field the game skips: a game knows + // which player is its own by the id (GemBreakerPlayer.init), and only + // that one aims and shoots. + seedAndPlayers: game => [serial(), game.players.length, ...game.players.flatMap(player => [player.id, 0])], }; +// the room games several players play together: "Multiplayer" on the +// game's waiting list (MinigameManager.setupWaitListPopup), for players in +// the same room. each client plays the same game from the same start, and +// the server passes each player's moves on to the others: `relay` names +// the messages passed on, true for those that go with the sender's sfs id +// first. a full list starts the game. +const MULTIPLAYER = { + // GemBreaker.message: "pos" [sfsUserId, cannon angle], "shoot" [the shot's + // nine numbers], "playerLost" [the next round's seed]. two players, a + // field each, first to win two rounds. + GemBreaker: {max: 2, relay: {pos: true, shoot: false, playerLost: false}}, +}; +const MAX_RELAYED_FIELDS = 12; +const RELAYED_FIELD = /^[-0-9a-zA-Z.]{1,32}$/; + // serial numbers the client mixes into its award messages; any number will do. function serial() { return 1 + Math.floor(Math.random() * 1000000); @@ -93,7 +111,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => { defpacks.stringId(game.title) || defpacks.stringId(FALLBACK_TITLE), game.swf, // extName game.swf, // swfName - game.buddy ? 2 : 1, game.buddy ? 2 : 1, // min and max players + // min and max players: more than one gives the game a waiting list + // with "Single Player" and "Multiplayer" (lib/minigames.js MULTIPLAYER). + game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1, + game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1, 0, // max spectators game.type, // the game card: the title picture on the "play" popup (not known), and @@ -134,6 +155,13 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => { } session.game = null; game.players = game.players.filter(player => player !== session); + if (game.lobby) { + if (game.players.length === 0) { + lobbies.delete(game.lobby); + } + tellLobby(game); + return; + } // the games' own "player left": [sfsUserId]. A buddy game takes it for // a win, so the one still looking at the result of a game that has been // decided is not told. three of them only the clients know the end of @@ -191,6 +219,59 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => { session.sendXt("mj", game.roomId, ...game.players.map(player => player.id)); }; + // the waiting lists of multiplayer room games: " " -> a + // game not started yet. one is answered "mj" from the room the players + // wait in, with who waits: the client draws them from that room, so they + // stay in it till the list is full. + const lobbies = new Map(); + const tellLobby = game => { + for (const player of game.players) { + player.sendXt("mj", game.waitRoom.id, ...game.players.map(other => other.id)); + } + }; + const joinLobby = (session, def, multi) => { + const key = `${def.id} ${session.room.name}`; + let game = lobbies.get(key); + if (game && game.players.some(player => blocks.either(player.account, session.account))) { + session.sendXt("mj", -1, "as", 0); + tell(session, "Someone already waiting for that game is not someone you play with. Try again later."); + return; + } + if (!game) { + game = {roomId: nextGameRoomId++, def, multi, players: [], started: false, ready: new Set(), lobby: key, waitRoom: session.room}; + lobbies.set(key, game); + } + game.players.push(session); + session.game = game; + tellLobby(game); + if (game.players.length >= multi.max) { + lobbies.delete(key); + game.lobby = null; + for (const player of game.players) { + const music = player.room ? player.room.customMusicDef : 0; + if (def.type !== IN_ROOM) { + leaveRoom(player); + } + seat(player, game, music); + } + start(game); + } + }; + + // a move in a multiplayer room game, passed on to the other players. + const relay = (session, game, word, params) => { + const withId = game.multi.relay[word]; + if (!game.started || params.length > MAX_RELAYED_FIELDS || !params.every(field => RELAYED_FIELD.test(String(field))) + || !messagesPerMinute.allow(session.account.id)) { + return; + } + for (const other of game.players) { + if (other !== session) { + other.sendXt("mm", game.roomId, word, ...(withId ? [session.id] : []), ...params); + } + } + }; + // starts a buddy game between two players (lib/buddygames.js says what // `match` is). it runs in a window over whatever room each is in. const startMatch = (def, sender, target) => { @@ -451,7 +532,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => { }, // MinigameManager.launchGame: [gameDefId, multiplayer, proModeId, ?]. - mj(session, roomId, [gameDefId]) { + mj(session, roomId, [gameDefId, multiplayer]) { leave(session); // a game left without a word, if any const def = games.get(Number(gameDefId)); if (!def || def.ready === false || def.buddy || !session.room) { @@ -461,6 +542,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => { tell(session, "That game is not ready on this server yet."); return; } + if (multiplayer === "1" && Object.hasOwn(MULTIPLAYER, def.swf)) { + joinLobby(session, def, MULTIPLAYER[def.swf]); + return; + } const game = {roomId: nextGameRoomId++, def, players: [session], started: false, ready: new Set()}; const music = session.room.customMusicDef; // the client takes this from every room join if (def.type !== IN_ROOM) { @@ -490,6 +575,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => { matchMessage(session, game, String(word), params); return; } + if (game.multi && Object.hasOwn(game.multi.relay, String(word))) { + relay(session, game, String(word), params); + return; + } const reply = (...fields) => session.sendXt("mm", game.roomId, ...fields); const own = game.def.tickets ? carnival : MESSAGES[game.def.swf]; if (own && Object.hasOwn(own, word)) { diff --git a/lib/moderation.js b/lib/moderation.js index 56f4321..144a7b8 100644 --- a/lib/moderation.js +++ b/lib/moderation.js @@ -4,6 +4,7 @@ const accounts = require("./accounts.js"); const achievements = require("./achievements.js"); const bans = require("./bans.js"); const dens = require("./dens.js"); +const config = require("../config.js"); const {CURRENCIES} = require("./player.js"); // moderation: kick, ban, silence, clear a den, grant gems, message a player. @@ -18,6 +19,23 @@ const CURRENCY_GEMS = 0; // client says "You earned N ..." in a popup when the amount went up. const REASON_ANNOUNCE = 3; +// a warning's reason, and the client's own warning popup for it +// (FacilitatorXtCommManager.showContextualWarningPopup, "fw"): its artwork +// and its words, which this server's strings already say in its own name. +const WARNINGS = { + behavior: 4, // "Inappropriate Behavior" + bullying: 1, // "Bullying" + personal: 3, // "Personal Information" + scamming: 9, // "Scamming" + // in the staff member's own words: its note is what the player is shown, + // in a message box (there is no popup for it), and it cannot be left out. + custom: null, +}; +const CUSTOM_WARNING = "custom"; +const MAX_WARNINGS_KEPT = 100; +const MAX_WARNING_NOTE = 200; +const SECONDS_PER_DAY = 86400; + const now = () => Math.floor(Date.now() / 1000); // seconds of ban left, PERMANENT, or 0 when not banned. @@ -35,6 +53,21 @@ const banOf = account => { return seconds === 0 ? null : {seconds, reason: account.banReason || bans.NO_REASON, by: account.bannedBy || "", since: account.bannedAt || null}; }; +// the warnings an account has had in the last config.warningSilence.days +// (all of them when that is 0). +const recentWarnings = account => { + const days = (config.warningSilence || {}).days || 0; + const since = now() - days * SECONDS_PER_DAY; + return (account.warnings || []).filter(entry => !days || entry.at >= since).length; +}; + +// the minutes of silence a warning brings when it is the Nth recent one +// (config.warningSilence.steps, [[N, minutes], ...]); 0 for none. +const silenceForWarning = count => { + const step = ((config.warningSilence || {}).steps || []).find(([warnings]) => warnings === count); + return step ? step[1] : 0; +}; + const isSilenced = account => account.silencedUntil === PERMANENT || (account.silencedUntil || 0) > now(); // seconds of silence left, PERMANENT, or 0 when the account may chat. @@ -52,6 +85,16 @@ module.exports = ({findOnline}) => { // A "message from moderator" popup; also used to answer chat commands. const notify = (session, text) => discipline(session, "fp", text, 0); + // a warning as the player sees it: the game's popup for its reason, or a + // custom one's words. + const showWarning = (session, entry) => { + if (entry.reason === CUSTOM_WARNING && entry.note) { + notify(session, `Warning: ${entry.note}`); + } + else { + discipline(session, "fw", WARNINGS[entry.reason] ?? WARNINGS.behavior); + } + }; const actions = { kick(target) { @@ -171,6 +214,51 @@ module.exports = ({findOnline}) => { notify(session, text); return true; }, + + // a warning: kept on the account (who, when, why and a note for staff), + // and shown with the game's own warning popup: now if they are in a + // room, else once they are next (greet). the Nth warning within + // config.warningSilence.days may also silence them for a while; a + // longer silence already on them is left alone. + // returns {count, online, silencedMinutes}, or null for a reason that + // is not one (or a custom warning with nothing to say). + warn(target, reason, by, note = "") { + const text = String(note).trim().slice(0, MAX_WARNING_NOTE); + if (!Object.hasOwn(WARNINGS, reason) || (reason === CUSTOM_WARNING && !text)) { + return null; + } + const session = findOnline(target.username); + const seen = Boolean(session && session.greeted); + const entry = {at: now(), by, reason, note: text, seen}; + target.warnings = [...(target.warnings || []), entry].slice(-MAX_WARNINGS_KEPT); + accounts.save(); + if (seen) { + showWarning(session, entry); + } + let silencedMinutes = silenceForWarning(recentWarnings(target)); + const left = silenceRemaining(target); + if (silencedMinutes && left !== PERMANENT && left < silencedMinutes * SECONDS_PER_MINUTE) { + actions.silence(target, silencedMinutes * SECONDS_PER_MINUTE); + } + else { + silencedMinutes = 0; + } + return {count: target.warnings.length, online: Boolean(session), silencedMinutes}; + }, + + // takes back their latest warning (one given by mistake). a silence it + // brought stays; that is lifted on its own (silence 0). returns the + // warning taken back, or null when there is none. + unwarn(target) { + const list = target.warnings || []; + if (!list.length) { + return null; + } + const removed = list[list.length - 1]; + target.warnings = list.slice(0, -1); + accounts.save(); + return removed; + }, }; // the client's moderator requests, refused whoever sends them. each @@ -178,7 +266,20 @@ module.exports = ({findOnline}) => { const refuse = reply => session => session.sendXt(reply, -1, 0); const handlers = {fk: refuse("fk"), fb: refuse("fb"), fs: refuse("fs"), fm: refuse("fm"), fg: refuse("fg"), fp: refuse("fp"), fc() {}}; - return {handlers, actions, banRemaining, banOf, isSilenced, silenceRemaining, PERMANENT}; + // the first room has loaded (lib/world.js): a warning given while they + // were away is shown now, the latest only (the game has one warning + // popup), and all of them count as seen. + const greet = session => { + const unseen = (session.account.warnings || []).filter(entry => entry.seen === false); + if (!unseen.length) { + return; + } + unseen.forEach(entry => { entry.seen = true; }); + accounts.save(); + showWarning(session, unseen[unseen.length - 1]); + }; + + return {handlers, actions, greet, banRemaining, banOf, isSilenced, silenceRemaining, PERMANENT, WARNINGS: Object.keys(WARNINGS)}; }; Object.assign(module.exports, {isSilenced, banRemaining, banOf}); diff --git a/lib/modlog.js b/lib/modlog.js index 8ab659b..258428e 100644 --- a/lib/modlog.js +++ b/lib/modlog.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const accounts = require("./accounts.js"); // what each moderator did in the moderator panel (lib/modpanel.js), for @@ -23,7 +24,7 @@ const load = () => accounts.database().exec(SCHEMA); const record = (by, action, target = "", detail = "") => { accounts.database().prepare("INSERT INTO mod_log (at, by, action, target, detail) VALUES (?, ?, ?, ?, ?)") .run(Math.floor(Date.now() / 1000), by, action, String(target), String(detail).slice(0, MAX_DETAIL)); - console.log(`[mod] ${by}: ${action}${target ? ` "${target}"` : ""}`); + console.log(`[mod] ${logText(by)}: ${logText(action)}${logText(target ? ` "${target}"` : "")}`); }; const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN); diff --git a/lib/modnotes.js b/lib/modnotes.js new file mode 100644 index 0000000..0327897 --- /dev/null +++ b/lib/modnotes.js @@ -0,0 +1,53 @@ +"use strict"; + +const crypto = require("crypto"); +const accounts = require("./accounts.js"); + +// moderators' notes on a player: what staff want one another to know about +// them ("talked to them about trading, seemed fine"), on the player's page +// of the moderator panel and with "!notes" in the game. the player is never +// shown them (lib/manage.js leaves them out of their data). +// +// on an account: modNotes [{id, at, by, text}], the oldest first. + +const MAX_NOTES = 100; +const MAX_TEXT = 500; + +const now = () => Math.floor(Date.now() / 1000); + +const list = account => [...(account.modNotes || [])].reverse(); + +// returns {note} or {error}. +const add = (account, by, text) => { + const clean = String(text || "").replace(/\s+/g, " ").trim().slice(0, MAX_TEXT); + if (!clean) { + return {error: "Write the note first."}; + } + const note = {id: crypto.randomBytes(6).toString("hex"), at: now(), by: String(by), text: clean}; + account.modNotes = [...(account.modNotes || []), note].slice(-MAX_NOTES); + accounts.save(); + return {note}; +}; + +// a note taken away by whoever wrote it, or by someone who may remove anyone's +// (`anyone`). returns {note} or {error}. +const remove = (account, id, by, anyone) => { + const note = (account.modNotes || []).find(entry => entry.id === String(id)); + if (!note) { + return {error: "No such note."}; + } + if (!anyone && note.by.toLowerCase() !== String(by).toLowerCase()) { + return {error: "Only whoever wrote a note, or an admin, can remove it."}; + } + account.modNotes = account.modNotes.filter(entry => entry !== note); + accounts.save(); + return {note}; +}; + +// the newest notes on anybody, with whom they are about. +const recent = count => accounts.all() + .flatMap(account => (account.modNotes || []).map(note => ({...note, about: account.username}))) + .sort((one, other) => other.at - one.at) + .slice(0, count); + +module.exports = {list, add, remove, recent, MAX_TEXT}; diff --git a/lib/modpanel.js b/lib/modpanel.js index c924d9e..e920fb6 100644 --- a/lib/modpanel.js +++ b/lib/modpanel.js @@ -4,16 +4,24 @@ const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); const accounts = require("./accounts.js"); +const admin = require("./admin.js"); const bans = require("./bans.js"); const captcha = require("./captcha.js"); const chatlog = require("./chatlog.js"); const config = require("../config.js"); +const customItems = require("./customitems.js"); +const itemControl = require("./itemcontrol.js"); +const itemArt = require("./itemart.js"); +const playerItems = require("./playeritems.js"); +const defpacks = require("./defpacks.js"); const devices = require("./devices.js"); const limits = require("./limits.js"); const manage = require("./manage.js"); const masterpieces = require("./masterpieces.js"); const modlog = require("./modlog.js"); +const modNotes = require("./modnotes.js"); const reports = require("./reports.js"); +const roles = require("./roles.js"); const staff = require("./staff.js"); const stats = require("./stats.js"); const support = require("./support.js"); @@ -24,8 +32,9 @@ const world = require("./world.js"); // players, and no more. it is apart from the admin panel (lib/panel.js), // which stays whoever runs the server's alone. // -// A moderator is a game account the admin marked as one (`moderator` on the -// account). they sign in here with that account's username and password and +// A moderator is a game account the admin gave a staff role (lib/roles.js: +// helper, moderator or admin; `moderator` on an older account counts as a +// moderator), and what they may do here is what their role allows. they sign in here with that account's username and password and // a code from their authenticator app, every time: an account without 2FA // cannot sign in at all, and a trusted device is not taken for a code. // being a moderator gives the account nothing in the game itself. @@ -45,6 +54,7 @@ const SESSION_HOURS = 12; const TEN_MINUTES_MS = 600000; const MAX_BAN_HOURS = 24 * 365 * 10; const MAX_MESSAGE_LENGTH = 200; +const MAX_RECENT_NOTES = 15; const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS); const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator @@ -63,8 +73,7 @@ const cookieHeader = (token, maxAgeSeconds) => `${COOKIE}=${token}; Path=/mod; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; // may this account use the panel (still)? -const mayModerate = account => Boolean(account && account.moderator && totp.isOn(account) && !account.locked - && world.moderation.banRemaining(account) === 0); +const mayModerate = account => Boolean(account && roles.isActiveStaff(account, world.moderation.banRemaining(account) !== 0)); const signedInAs = req => { const token = cookieToken(req); @@ -95,7 +104,9 @@ const playerRow = (account, playing) => { banReason: ban ? ban.reason : "", silenced: world.moderation.silenceRemaining(account), nameRejected: Boolean(account.nameRejected), - moderator: Boolean(account.moderator), + moderator: Boolean(roles.roleOf(account)), + role: roles.roleOf(account), + warnings: (account.warnings || []).length, playtime: account.playtime, bio: account.bio, discord: account.discord, @@ -118,10 +129,17 @@ const playerDetail = account => ({ ...playerRow(account, playing()), history: bans.historyOf(account).map(({at, action, seconds, reason, by}) => ({at, action, seconds, reason, by})), appeal: bans.appealOf(account), + warningList: (account.warnings || []).slice(-20).reverse(), + notes: modNotes.list(account), openReports: reports.list(false).filter(report => report.target.toLowerCase() === account.username.toLowerCase()).length, devicesKnown: devices.knownFor(account).ids, stoppedThisWeek: chatlog.notSentCount(account, 7), paintings: masterpieces.madeBy(account).length, + // what they made in the Item Maker, with its pictures, for a report about one + madeItems: playerItems.madeBy(account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name, + artUrl: itemArt.urlOf(entry, "/mod/api/itemart"), artWaiting: Boolean(entry.artPending)})), + picturesStopped: Boolean(account.artBlocked), + pictureStrikes: account.artRefusals || 0, }); // an address with its end left out, and a name to lift its ban by. @@ -135,6 +153,23 @@ const maskedAddress = ban => ({ const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null); +// the permission (lib/roles.js) each action needs. +const ACTION_PERMISSIONS = { + ban: "player.ban", banReason: "player.ban", unban: "player.ban", + 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", + note: "player.view", deleteNote: "player.view", +}; + +// minutes as a person would say them: "1 hour", "1 day", "90 minutes". +const silenceText = minutes => { + const [count, unit] = minutes % 1440 === 0 ? [minutes / 1440, "day"] : minutes % 60 === 0 ? [minutes / 60, "hour"] : [minutes, "minute"]; + return `${count} ${unit}${count === 1 ? "" : "s"}`; +}; + const act = (mod, target, body) => { const {actions, PERMANENT} = world.moderation; const name = target.username; @@ -142,8 +177,12 @@ const act = (mod, target, body) => { if (target === mod) { return {error: "That is you."}; } - if (target.moderator) { - return {error: "Another moderator is the admin's to deal with."}; + if (!roles.outranks(mod, target)) { + return {error: "Staff of your rank or above are for someone higher up to deal with."}; + } + const permission = ACTION_PERMISSIONS[body.action]; + if (permission && !roles.can(mod, permission)) { + return {error: "Your role cannot do that."}; } switch (body.action) { case "ban": { @@ -184,6 +223,22 @@ const act = (mod, target, body) => { } return actions.message(target, text) ? {ok: `Shown to ${name}.`, detail: text} : {error: `${name} is not online.`}; } + case "warn": { + const reason = String(body.reason || "behavior"); + const result = actions.warn(target, reason, by, body.note); + if (!result) { + return {error: reason === "custom" ? "A custom warning needs its words in the note: they are what the player is shown." + : `A warning's reason: ${world.moderation.WARNINGS.join(", ")}.`}; + } + return {ok: `${name} warned (${reason}): warning ${result.count}.${result.online ? "" : " They are offline: they will see it when they next play."}` + + (result.silencedMinutes ? ` That many warnings also silenced them for ${silenceText(result.silencedMinutes)}.` : ""), + detail: `${reason}${body.note ? ` · ${String(body.note).slice(0, 200)}` : ""}`}; + } + case "unwarn": { + const removed = actions.unwarn(target); + return removed ? {ok: `Took back ${name}'s latest warning (${removed.reason}).`, detail: removed.reason} + : {error: `${name} has no warnings.`}; + } case "rejectName": if (target.nameRejected) { return {error: "Already rejected."}; @@ -201,6 +256,15 @@ const act = (mod, target, body) => { target.bio = ""; accounts.save(target); return {ok: "Bio cleared."}; + // a note for the other staff (lib/modnotes.js); the player never sees it. + case "note": { + const result = modNotes.add(target, by, body.text); + return result.error ? result : {ok: "Note added.", detail: result.note.text}; + } + case "deleteNote": { + const result = modNotes.remove(target, body.id, by, roles.roleOf(mod) === "admin"); + return result.error ? result : {ok: "Note removed.", detail: `${result.note.by}: ${result.note.text}`}; + } // the address they last signed in from, for good. which address that // is, the moderator is not told. case "banAddress": { @@ -214,6 +278,16 @@ const act = (mod, target, body) => { } return {ok: "Their address is banned.", detail: result.ban.reason}; } + // the moderator's own animal and the player's, in the game: both have + // to be online, the moderator in a room. + case "summon": { + const result = world.staffMove(target.username, mod.username); + return result.ok ? {ok: `${name} was brought to ${result.room}.`, detail: result.room} : {error: result.error}; + } + case "goto": { + const result = world.staffMove(mod.username, target.username); + return result.ok ? {ok: `You went to ${name} (${result.room}).`, detail: result.room} : {error: result.error}; + } // every computer they signed in from lately (lib/devices.js). case "banDevices": return staff.banDevices(target, body.reason, by); @@ -273,7 +347,7 @@ const handle = async (req, res, url, from, web) => { const account = known && await accounts.authenticateAsync(known.username, body.password) === known ? known : null; // one answer for a wrong password and for an account that is no // moderator: who the moderators are is nobody's to find out here. - if (!account || !account.moderator) { + if (!account || !roles.roleOf(account)) { failuresByAddress.record(from.key); if (known && !account) { accounts.recordLogin(known, "mod", from.address, false); @@ -339,6 +413,43 @@ const handle = async (req, res, url, from, web) => { reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error}); }; + switch (route) { + // who is signed in here, their role and what it allows: for a client to + // show only the buttons that will work. + case "GET /mod/api/me": + reply(200, {username: mod.username, role: roles.roleOf(mod), permissions: roles.permissionsOf(mod)}); + return; + } + + // what players made that waits for approval (lib/playeritems.js) + if (url.pathname === "/mod/api/review") { + if (!roles.can(mod, "items.approve")) { + reply(403, {error: "Your role does not allow that."}); + return; + } + reviewRoutes(route.replace(" /mod/api/", " "), body, reply, done, mod.username, "/mod/api/itemart"); + return; + } + // custom items (lib/customitems.js), for whoever may make them. + if (url.pathname.startsWith("/mod/api/items")) { + if (!roles.can(mod, "items.create")) { + reply(403, {error: "Your role does not allow that."}); + return; + } + itemRoutes(route.replace(" /mod/api/", " "), url, body, reply, done, { + username: mod.username, + artBase: "/mod/api/itemart", + mayTake: target => target === mod || !roles.roleOf(target) || roles.outranks(mod, target), + }); + return; + } + // everything else shows players and what they did: not for a role that + // only makes things. + if (!roles.can(mod, "player.view")) { + reply(403, {error: "Your role does not allow that."}); + return; + } + switch (route) { case "GET /mod/api/overview": reply(200, {online: world.players().length, reports: reports.openCount(), requests: support.nameRequests(false).length + bans.openAppeals(), @@ -379,6 +490,11 @@ const handle = async (req, res, url, from, web) => { } // by address: only the address typed, which is written down (once // for each address, though the page asks again every few seconds). + // for the roles that ban addresses (lib/roles.js), not every staff member. + if (!roles.can(mod, "address.ban")) { + reply(403, {error: "Your role cannot do that."}); + return; + } const query = String(url.searchParams.get("q") || "").trim().toLowerCase(); const found = staff.byAddress(query); if (found.error) { @@ -394,6 +510,11 @@ const handle = async (req, res, url, from, web) => { return; } + // the latest mod notes on anybody (lib/modnotes.js), for the dashboard. + case "GET /mod/api/notes": + reply(200, {notes: modNotes.recent(MAX_RECENT_NOTES)}); + return; + case "GET /mod/api/stats": reply(200, stats.report(Number(url.searchParams.get("days")), Number(url.searchParams.get("offset")))); return; @@ -464,6 +585,10 @@ const handle = async (req, res, url, from, web) => { return; case "POST /mod/api/address": { + if (!roles.can(mod, "address.ban")) { + reply(403, {error: "Your role cannot do that."}); + return; + } const ban = bans.addressBans().find(entry => sha256(entry.key).slice(0, 16) === String(body.id)); done(ban && bans.unbanAddress(ban.key, mod.username) ? {ok: "No longer banned."} : {error: "Not banned."}, "address unbanned", "", ban ? ban.reason : ""); return; @@ -509,8 +634,148 @@ const handle = async (req, res, url, from, web) => { } }; -const moderators = () => accounts.all().filter(account => account.moderator) - .map(account => ({username: account.username, twoStep: totp.isOn(account), lastSeen: account.lastSeen || null})) +// the custom items' pages, for the moderator panel (/mod/api/...) and the +// admin panel (/admin/api/..., lib/panel.js): `route` is without that +// ("GET items"), and `actor` is {username, mayTake(account)}: who it is +// written down as, and whether they may take items from that player. +// GET items: the custom items, the newest first. +// GET items/find?q=WORDS&kind=all|clothing|den: any item (the game's or a +// custom one), by name or id, as the item finder finds it, each marked +// whether it is locked out of the finder: for the dashboards' lock. +// GET items/base?kind=clothing|den&id=N: an item of the game's to +// make one from (its name and colours), to check before making it. +// POST items {action: "create", kind, base, name, cost, members, colors} +// or {action: "update", kind, id, and any of name, cost, members, colors, inShop} +// or {action: "lock" | "unlock", kind, id}: kept out of the item finder +// or {action: "take", username, kind, id}: every one of it, from one player +// or {action: "delete", kind, id}: a custom item, out of the game and every inventory. +const itemRoutes = (route, url, body, reply, done, actor) => { + switch (route) { + case "GET items": + reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry), locked: itemControl.isLocked(entry.kind, entry.id), + artUrl: itemArt.urlOf(entry, actor.artBase)})), + firstId: customItems.FIRST_ID, locked: itemControl.lockedList()}); + return; + case "GET items/find": { + const found = admin.search(url.searchParams, null, true); + reply(200, {total: found.total, results: found.results.slice(0, 20).map(entry => ({ + kind: entry.kind, id: entry.id, cost: entry.cost, + name: entry.locked ? entry.name.replace(/ \(locked\)$/, "") : entry.name, + locked: Boolean(entry.locked), + custom: entry.id >= customItems.FIRST_ID, + })), lockedCount: itemControl.lockedList().length}); + return; + } + case "GET items/base": { + const kind = url.searchParams.get("kind") === "den" ? "den" : "clothing"; + const id = Number(url.searchParams.get("id")); + const def = kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id); + if (!def || id >= customItems.FIRST_ID || (kind === "clothing" && def.type !== "1")) { + reply(404, {error: `No ${kind === "den" ? "den item" : "clothing"} with that id.`}); + return; + } + reply(200, kind === "den" + ? {kind, id, name: defpacks.string(def.nameStrId) || def.abbrName, art: def.abbrName, cost: Number(def.cost)} + : {kind, id, name: defpacks.string(def.titleStrId), art: Number(def.layerDefId), cost: Number(def.value), colors: String(def.colors).split(",").map(Number)}); + return; + } + case "POST items": { + const kind = String(body.kind || ""); + if (body.action === "lock" || body.action === "unlock") { + const result = itemControl.setLocked(kind, body.id, body.action === "lock"); + done(result, result.ok ? `item ${body.action}ed` : "", "", `${kind} ${body.id}`); + return; + } + if (body.action === "take") { + const target = accounts.byName(String(body.username || "").trim()); + if (target && !actor.mayTake(target)) { + done({error: "Staff of your rank or above are for someone higher up to deal with."}); + return; + } + const result = itemControl.take(String(body.username || "").trim(), kind, body.id, world); + done(result, result.ok ? "item taken" : "", target ? target.username : "", `${kind} ${body.id}${result.count ? ` x${result.count}` : ""}`); + return; + } + if (body.action === "look") { + const result = customItems.setArtMode(kind, body.id, String(body.look)); + done(result.error ? result : {ok: `${result.item.name} is worn as ${body.look === "texture" ? "a texture" : "a sticker"}.`}, + "item look changed", "", `${kind} ${body.id} ${body.look}`); + return; + } + if (body.action === "delete") { + const result = itemControl.deleteCustom(kind, body.id, world); + done(result, result.ok ? "item deleted" : "", "", `${kind} ${body.id}`); + return; + } + const result = body.action === "update" + ? customItems.update(kind, body.id, body) + : body.action === "create" ? customItems.create(kind, body, actor.username) : {error: "Unknown action."}; + if (result.error) { + done(result); + return; + } + const {item} = result; + done({ok: `${item.name} (${item.kind === "den" ? "den item" : "clothing"} ${item.id}) ${body.action === "update" ? "changed" : "made"}.`}, + body.action === "update" ? "item changed" : "item made", "", `${item.kind} ${item.id} ${item.name}`); + return; + } + default: + reply(404, {error: "not_found"}); + } +}; + +// GET review: what waits, the oldest first; POST review {kind, id, approve: true | false}. +// for the moderator panel and the admin panel (lib/panel.js) alike. +// POST review {action: "takePicture", kind, id}: a picture off an item, +// counted against its maker; {action: "uploads", username, blocked}: +// stops, or lets again, one player's picture uploads. +// `artBase`: the panel's /…/api/itemart, where pictures that wait are shown. +const reviewRoutes = (route, body, reply, done, by, artBase) => { + if (route === "GET review") { + reply(200, { + waiting: customItems.waiting().map(entry => { + const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId); + return {kind: entry.kind, id: entry.id, name: entry.name, baseName: customItems.baseName(entry), base: entry.base, maker: maker ? maker.username : entry.createdBy, + createdAt: entry.createdAt, waiting: entry.pending ? "item" : "picture", artUrl: itemArt.urlOf(entry, artBase), + makerStrikes: maker ? maker.artRefusals || 0 : 0}; + }), + enabled: playerItems.enabled(), + approval: playerItems.approvalOn(), + artApproval: playerItems.artApprovalOn(), + strikes: playerItems.ART_STRIKES, + stopped: accounts.all().filter(account => account.artBlocked).map(account => account.username).sort(), + }); + return; + } + if (route === "POST review" && body.action === "takePicture") { + const kind = String(body.kind || ""); + const entry = customItems.get(kind, body.id); + const maker = entry && entry.ownerId !== null ? accounts.byId(entry.ownerId) : null; + const result = playerItems.takePicture(kind, body.id); + done(result, result.ok ? "item picture taken off" : "", maker ? maker.username : "", `${kind} ${body.id}`); + return; + } + if (route === "POST review" && body.action === "uploads") { + const target = accounts.byName(String(body.username || "").trim()); + if (!target) { + done({error: "No such player."}); + return; + } + const result = playerItems.setUploadsBlocked(target, body.blocked === true); + done(result, body.blocked === true ? "picture uploads stopped" : "picture uploads allowed", target.username); + return; + } + if (route === "POST review") { + const kind = String(body.kind || ""); + const result = playerItems.review(kind, body.id, body.approve === true, by, world); + done(result, result.ok ? (body.approve === true ? "item approved" : "item turned away") : "", "", `${kind} ${body.id}`); + return; + } + reply(404, {error: "not_found"}); +}; + +const moderators = () => accounts.all().filter(account => roles.roleOf(account)) + .map(account => ({username: account.username, role: roles.roleOf(account), twoStep: totp.isOn(account), lastSeen: account.lastSeen || null})) .sort((a, b) => a.username.localeCompare(b.username)); -module.exports = {handle, forget, moderators}; +module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes}; diff --git a/lib/names.js b/lib/names.js index 397d76a..21be88a 100644 --- a/lib/names.js +++ b/lib/names.js @@ -35,23 +35,31 @@ const stretched = word => /(.)\1\1/.test(word); // above. "word" is for a line marked "=": in lib/sexual-names.txt the rest // are matched anywhere in a name. const lists = new Map(); // file -> {mtime, entries} +// the file is opened once, and its time and its words are both of what was +// opened: a list changed in between cannot be read under the old one's time. const read = file => { - let mtime = 0; + let fd; try { - mtime = fs.statSync(file).mtimeMs; + fd = fs.openSync(file, "r"); } catch (err) { return []; } - const kept = lists.get(file); - if (kept && kept.mtime === mtime) { - return kept.entries; + try { + const mtime = fs.fstatSync(fd).mtimeMs; + const kept = lists.get(file); + if (kept && kept.mtime === mtime) { + return kept.entries; + } + const entries = fs.readFileSync(fd, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#")) + .map(line => ({text: line.replace(/^=/, "").replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*"), word: line.startsWith("=")})) + .filter(entry => entry.text.length >= 2); + lists.set(file, {mtime, entries}); + return entries; + } + finally { + fs.closeSync(fd); } - const entries = fs.readFileSync(file, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#")) - .map(line => ({text: line.replace(/^=/, "").replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*"), word: line.startsWith("=")})) - .filter(entry => entry.text.length >= 2); - lists.set(file, {mtime, entries}); - return entries; }; let epicDens = null; diff --git a/lib/panel.js b/lib/panel.js index a84a873..00509cc 100644 --- a/lib/panel.js +++ b/lib/panel.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); @@ -18,8 +19,10 @@ const log = require("./log.js"); const masterpieces = require("./masterpieces.js"); const modlog = require("./modlog.js"); const modpanel = require("./modpanel.js"); +const playerItems = require("./playeritems.js"); const erase = require("./erase.js"); const reports = require("./reports.js"); +const roles = require("./roles.js"); const sales = require("./sales.js"); const stats = require("./stats.js"); const staff = require("./staff.js"); @@ -88,7 +91,7 @@ const passwordAcceptable = password => const load = () => { if (!hasPassword()) { setupCode = crypto.randomBytes(5).toString("hex"); - console.log(`[admin] no admin password yet: open ${config.baseUrl}admin to choose one` + console.log(`[admin] no admin password yet: open ${logText(config.baseUrl)}admin to choose one` + ` (from another machine it will ask for this setup code: ${setupCode})`); } }; @@ -151,7 +154,12 @@ const accountRow = (account, playing) => { // seconds left, -1 for permanent, 0 for not banned banned: ban, banReason: ban === 0 ? "" : account.banReason || bans.NO_REASON, - moderator: Boolean(account.moderator), + moderator: Boolean(roles.roleOf(account)), + role: roles.roleOf(account), + // what they may do (their role's, with their own grants and denies) + permissions: roles.permissionsOf(account), + permGrants: account.permGrants || [], + permDenies: account.permDenies || [], nameRejected: Boolean(account.nameRejected), silenced: world.moderation.isSilenced(account), animals: account.avatars.length, @@ -376,8 +384,10 @@ const act = (account, body) => { const name = account.username; switch (body.action) { case "password": { - if (accounts.setPassword(account, body.password)) { - return {error: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."}; + const passwordProblem = accounts.setPassword(account, body.password); + if (passwordProblem) { + return {error: passwordProblem === "weak_password" ? "That password is too easy to guess: it is a common one, or has your username in it." + : "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."}; } actions.kick(account); manage.forget(account); // their account page too, whoever has it open @@ -500,18 +510,47 @@ const act = (account, body) => { } // A moderator may use the moderator panel (lib/modpanel.js), with this // account's password and its 2FA, which it has to have. + // (the older on/off switch; "role" below is the full one.) case "moderator": - if (body.on === true) { - account.moderator = true; - } - else { - delete account.moderator; + roles.setRole(account, body.on === true ? "moderator" : null); + if (body.on !== true) { modpanel.forget(account); } accounts.save(account); return {ok: body.on === true ? `${name} is a moderator.${totp.isOn(account) ? "" : " They have no 2FA yet and cannot sign in to the moderator panel until they turn it on."}` : `${name} is no longer a moderator.`}; + // A staff role (lib/roles.js): helper, moderator, admin, or none. What + // each allows is listed under "GET /admin/api/roles". + case "role": { + const role = body.role === null || body.role === "" || body.role === "none" ? null : String(body.role); + if (!roles.setRole(account, role)) { + return {error: `No such role. Roles: ${Object.keys(roles.ROLES).join(", ")}, or none.`}; + } + if (role === null) { + modpanel.forget(account); + } + accounts.save(); + world.refreshStaff(account); + if (role === null) { + return {ok: `${name} has no staff role.`}; + } + const label = roles.ROLES[role].label.toLowerCase(); + return {ok: `${name} is now ${/^[aeiou]/.test(label) ? "an" : "a"} ${label}.${totp.isOn(account) ? "" : " They have no 2FA yet, so their role does nothing until they turn it on."}`}; + } + // one staff member's own permissions, beyond their role's or taken from + // it ({grants: [...], denies: [...]}). + case "permissions": { + if (!roles.roleOf(account)) { + return {error: `${name} has no staff role: give them one first.`}; + } + roles.setAccountPermissions(account, body.grants, body.denies); + accounts.save(); + world.refreshStaff(account); + modlog.record("admin", "permissions changed", account.username, + `+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`); + return {ok: `${name}'s permissions are saved.`}; + } case "rejectName": actions.rejectName(account, BY); manage.forget(account); @@ -616,7 +655,7 @@ const handle = async (req, res, url, from, web) => { } storePassword(body.password); setupCode = null; - console.log(`[admin] admin password chosen from ${from.address}`); + console.log(`[admin] admin password chosen from ${logText(from.address)}`); signIn(res); reply(200, {ok: true}); return; @@ -629,11 +668,11 @@ const handle = async (req, res, url, from, web) => { } if (!hasPassword() || !passwordMatches(body.password)) { recordFailure(from.key); - console.log(`[admin] failed sign-in from ${from.address}`); + console.log(`[admin] failed sign-in from ${logText(from.address)}`); reply(401, {error: "Wrong password."}); return; } - console.log(`[admin] signed in from ${from.address}`); + console.log(`[admin] signed in from ${logText(from.address)}`); signIn(res); reply(200, {ok: true}); return; @@ -650,6 +689,39 @@ const handle = async (req, res, url, from, web) => { return; } + // what players made that waits (the moderator panel's Review), and the + // admin's switches for the Item Maker: {enabled, approval}. + if (url.pathname === "/admin/api/review" || url.pathname === "/admin/api/item-switches") { + const done = (result, action, target = "", detail = "") => { + if (result.ok) { + modlog.record("admin", action, target, result.detail || detail); + } + reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error}); + }; + if (route === "POST /admin/api/item-switches") { + const flag = value => (value === undefined ? undefined : value === true); + playerItems.setSwitches({enabled: flag(body.enabled), approval: flag(body.approval), artApproval: flag(body.artApproval)}); + const pictures = playerItems.pictureWaits() ? "pictures wait for a moderator" : "pictures are shown at once"; + done({ok: `The Item Maker is ${playerItems.enabled() ? "on" : "off"}; new items ${playerItems.approvalOn() ? "wait for a moderator first" : "are in the game at once"}; ${pictures}.`}, + "item maker settings", "", `${playerItems.enabled() ? "on" : "off"}, approval ${playerItems.approvalOn() ? "on" : "off"}, pictures ${playerItems.pictureWaits() ? "wait" : "at once"}`); + return; + } + modpanel.reviewRoutes(route.replace(" /admin/api/", " "), body, reply, done, "admin", "/admin/api/itemart"); + return; + } + // custom items (lib/customitems.js): the moderator panel's pages, the + // admin written down as "admin", and free to take from anyone. + if (url.pathname.startsWith("/admin/api/items")) { + const done = (result, action, target = "", detail = "") => { + if (result.ok) { + modlog.record("admin", action, target, result.detail || detail); + } + reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error}); + }; + modpanel.itemRoutes(route.replace(" /admin/api/", " "), url, body, reply, done, {username: "admin", artBase: "/admin/api/itemart", mayTake: () => true}); + return; + } + switch (route) { case "GET /admin/api/overview": reply(200, overview()); @@ -724,7 +796,7 @@ const handle = async (req, res, url, from, web) => { } const result = act(account, body); if (result.ok) { - console.log(`[admin] ${body.action} on "${account.username}"`); + console.log(`[admin] ${logText(body.action)} on "${logText(account.username)}"`); // in the record beside the moderators', for the player's timeline. if (!["password", "lastSeen", "level"].includes(body.action)) { modlog.record(BY, body.action, account.username, result.detail || ""); @@ -748,7 +820,7 @@ const handle = async (req, res, url, from, web) => { case "POST /admin/api/device": { const result = staff.unbanDevices(body.id, BY); if (result.ok) { - console.log(`[admin] device ban ${Number(body.id)} lifted`); + console.log(`[admin] device ban ${logText(Number(body.id))} lifted`); modlog.record(BY, "hardware ban lifted", result.username || ""); } reply(result.ok ? 200 : 400, result); @@ -777,6 +849,27 @@ const handle = async (req, res, url, from, web) => { return; // who may use the moderator panel, and what each did there. + // the staff roles and what each may do. + case "GET /admin/api/roles": + reply(200, {roles: Object.entries(roles.ROLES).map(([id, role]) => ({id, label: role.label, rank: role.rank, permissions: roles.rolePermissions(id), + defaults: role.permissions, changed: roles.roleChanged(id)})), permissions: roles.PERMISSIONS}); + return; + // a role's permissions changed ({role, permissions: [...]}), or back to + // its defaults ({role, reset: true}). its staff who are playing are told. + case "POST /admin/api/roles": { + const role = String(body.role || ""); + if (!roles.setRolePermissions(role, body.reset === true ? null : Array.isArray(body.permissions) ? body.permissions : [])) { + reply(400, {error: "No such role."}); + return; + } + for (const player of accounts.all().filter(account => roles.roleOf(account) === role)) { + world.refreshStaff(player); + } + console.log(`[admin] permissions of the ${logText(role)} role ${logText(body.reset === true ? "reset" : "changed")}`); + modlog.record("admin", body.reset === true ? "role permissions reset" : "role permissions changed", "", `${role}: ${roles.rolePermissions(role).join(", ")}`); + reply(200, {ok: `${roles.ROLES[role].label}: ${body.reset === true ? "back to its defaults" : "saved"}.`}); + return; + } case "GET /admin/api/moderators": reply(200, {moderators: modpanel.moderators(), log: modlog.recent()}); return; @@ -790,7 +883,7 @@ const handle = async (req, res, url, from, web) => { case "POST /admin/api/address": { const result = addressAct(body); if (result.ok) { - console.log(`[admin] address ${body.action}: ${limits.key(body.address)}`); + console.log(`[admin] address ${logText(body.action)}: ${logText(limits.key(body.address))}`); } reply(result.ok ? 200 : 400, result); return; @@ -807,7 +900,7 @@ const handle = async (req, res, url, from, web) => { case "POST /admin/api/debug": { const result = debugAct(body); if (result.ok) { - console.log(`[admin] debug: ${body.action} ${body.action === "teleport" ? `${body.username} -> ${body.room}` : body.on === true}`); + console.log(`[admin] debug: ${logText(body.action)} ${logText(body.action === "teleport" ? `${body.username} -> ${body.room}` : body.on === true)}`); } reply(result.ok ? 200 : 400, result); return; @@ -828,7 +921,7 @@ const handle = async (req, res, url, from, web) => { return; } const reached = world.announce(text, body.room ? String(body.room) : null); - console.log(`[admin] announcement to ${body.room ? `room ${body.room}` : "everyone"} (${reached} players)`); + console.log(`[admin] announcement to ${logText(body.room ? `room ${body.room}` : "everyone")} (${logText(reached)} players)`); reply(200, {ok: reached === 1 ? "Shown to 1 player." : `Shown to ${reached} players.`}); return; } @@ -873,7 +966,7 @@ const handle = async (req, res, url, from, web) => { result = {error: "Unknown action."}; } if (result.ok) { - console.log(`[admin] masterpiece ${body.action} ${id || body.on === true}`); + console.log(`[admin] masterpiece ${logText(body.action)} ${logText(id || body.on === true)}`); } reply(result.ok ? 200 : 400, result); return; @@ -915,7 +1008,7 @@ const handle = async (req, res, url, from, web) => { result = {error: "Unknown action."}; } if (result.ok) { - console.log(`[admin] support: ${body.action} ${Number(body.id)}`); + console.log(`[admin] support: ${logText(body.action)} ${logText(Number(body.id))}`); } reply(result.ok ? 200 : 400, result); return; @@ -943,4 +1036,4 @@ const handle = async (req, res, url, from, web) => { } }; -module.exports = {load, handle, PASSWORD_SETTING}; +module.exports = {load, handle, signedIn, PASSWORD_SETTING}; diff --git a/lib/parties.js b/lib/parties.js index bfeee9a..0535362 100644 --- a/lib/parties.js +++ b/lib/parties.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const accounts = require("./accounts.js"); const config = require("../config.js"); const defpacks = require("./defpacks.js"); @@ -190,7 +191,7 @@ module.exports = ({enterRoom, findOnline, blocks}) => { accounts.save(account); const party = {host: account, defId: def.id, name: `${name1}|${name2}|${name3}`, music: Number(music), endsAt: now() + config.partyMinutes * 60}; hosted.set(account.username.toLowerCase(), party); - console.log(`[world] ${account.username} is hosting a party (def ${def.id})`); + console.log(`[world] ${logText(account.username)} is hosting a party (def ${logText(def.id)})`); session.sendXt("cu", -1, CURRENCY_DIAMONDS, account.currency.diamonds, 0); session.sendXt("scp", -1, 1, 1, party.endsAt - now()); joinHosted(session, account); diff --git a/lib/playeritems.js b/lib/playeritems.js new file mode 100644 index 0000000..582ed8e --- /dev/null +++ b/lib/playeritems.js @@ -0,0 +1,303 @@ +"use strict"; + +const accounts = require("./accounts.js"); +const config = require("../config.js"); +const customItems = require("./customitems.js"); +const dens = require("./dens.js"); +const itemControl = require("./itemcontrol.js"); +const modlog = require("./modlog.js"); +const names = require("./names.js"); +const {addClothing, sendClothingAdded} = require("./player.js"); + +// items players make for themselves (the patched client's Item Maker, in the +// settings menu): one of the game's clothing pieces or den items under a +// name of their own, as staff make them (lib/customitems.js), but free, never +// in a shop, and in the item finder for its maker only. the maker is given +// one at once; it can be worn, placed and traded like any other. a maker +// may delete their own; staff may delete anyone's (the moderator panel). +// +// "xcm" from the client: ["info"], ["make", kind, baseId, name], +// ["rename", kind, id, name], ["look", kind, id, "sticker" | "texture"] +// (how one with a picture is worn) or ["delete", kind, id]. its picture is +// uploaded over HTTP (lib/itemart.js, POST /api/itemart). the answer is always "xcm" [ok 1 | 0, what to say, +// left today, left in all, the maker's items as JSON] + +// the admin's two switches (the admin panel's Items page): whether players +// may make items at all, and whether what they make (an item, or a new +// picture for one) waits for a moderator first (items.approve: the +// moderator panel's Review page), out of the game till then. +const ENABLED_SETTING = "playerItems"; +const APPROVAL_SETTING = "playerItemApproval"; +const enabled = () => accounts.setting(ENABLED_SETTING) !== "off"; +const approvalOn = () => accounts.setting(APPROVAL_SETTING) === "on"; +// pictures are seen by everyone who meets the item, so a player's waits for +// a moderator even when items do not: unless the admin turns this off too. +const ART_APPROVAL_SETTING = "playerArtApproval"; +const artApprovalOn = () => accounts.setting(ART_APPROVAL_SETTING) !== "off"; +const pictureWaits = () => approvalOn() || artApprovalOn(); +const setSwitches = ({enabled: on, approval, artApproval}) => { + if (on !== undefined) { + accounts.setSetting(ENABLED_SETTING, on ? "on" : "off"); + } + if (approval !== undefined) { + accounts.setSetting(APPROVAL_SETTING, approval ? "on" : "off"); + } + if (artApproval !== undefined) { + accounts.setSetting(ART_APPROVAL_SETTING, artApproval ? "on" : "off"); + } +}; + +// ---- what keeps pictures players upload decent +// +// - a picture turned away (or taken off by a moderator) is remembered by +// its SHA-256, and the same picture cannot be sent again; +// - each counts against its maker: at ART_STRIKES their uploads stop, +// till a moderator lets them again (account.artBlocked); +// - an account younger than config.itemArtMinAccountHours may not upload. +const ART_STRIKES = 3; +const REFUSED_SETTING = "refusedArt"; +const MAX_REFUSED = 5000; +let refused = null; // Set of SHA-256 hex + +const refusedSet = () => { + if (!refused) { + let saved = []; + try { + saved = JSON.parse(accounts.setting(REFUSED_SETTING) || "[]"); + } + catch { + saved = []; + } + refused = new Set(Array.isArray(saved) ? saved.map(String) : []); + } + return refused; +}; +const pictureRefused = hash => refusedSet().has(hash); + +// {error} when `account` may not upload a picture now, else null. `local`: +// the request is from this machine (no wait for a new account). +const uploadRefusal = (account, local = false) => { + if (account.artBlocked) { + return {error: "A moderator has turned off picture uploads for your account."}; + } + const hours = config.itemArtMinAccountHours; + if (!local && hours > 0 && Math.floor(Date.now() / 1000) - (account.createdAt || 0) < hours * 3600) { + return {error: `New accounts can add pictures after ${hours} hours. Try again later.`}; + } + return null; +}; + +// stops or lets again one player's uploads; letting them again clears the +// pictures counted against them. +const setUploadsBlocked = (account, blocked) => { + account.artBlocked = Boolean(blocked); + if (!blocked) { + account.artRefusals = 0; + } + accounts.save(account); + return {ok: blocked ? `${account.username} can no longer upload pictures.` : `${account.username} can upload pictures again.`}; +}; + +// a picture turned away or taken off: never again, and counted against its +// maker (not against staff, whose items have no maker). before it is removed. +// returns what to add to what the moderator is told. +const strike = entry => { + const hash = require("./itemart.js").digestOf(entry.kind, entry.id); + if (hash) { + const set = refusedSet(); + set.add(hash); + const kept = [...set].slice(-MAX_REFUSED); + refused = new Set(kept); + accounts.setSetting(REFUSED_SETTING, JSON.stringify(kept)); + } + const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId); + if (!maker) { + return ""; + } + maker.artRefusals = (maker.artRefusals || 0) + 1; + if (maker.artRefusals >= ART_STRIKES && !maker.artBlocked) { + maker.artBlocked = true; + accounts.save(maker); + modlog.record("system", "picture uploads stopped", maker.username, `${maker.artRefusals} pictures turned away`); + return ` That is ${maker.artRefusals} for ${maker.username}: their picture uploads are stopped.`; + } + accounts.save(maker); + return ` ${maker.username} has had ${maker.artRefusals} of ${ART_STRIKES} pictures turned away.`; +}; + +// a moderator takes an item's picture off, shown or waiting (after a report). +const takePicture = (kind, id) => { + const entry = customItems.get(kind, id); + if (!entry || !entry.art) { + return {error: "That item has no picture of its own."}; + } + const said = strike(entry); + const result = require("./itemart.js").remove(kind, entry.id); + return result.error ? result : {ok: `${result.ok}${said}`}; +}; + +const PER_DAY = 5; +const IN_ALL = 20; +const DAY = 86400; + +const RENAMES_PER_HOUR = 10; + +const now = () => Math.floor(Date.now() / 1000); +const renames = require("./limits.js").limiter(RENAMES_PER_HOUR, 3600000); // per account: each is sent to every game + +const madeBy = account => customItems.list().filter(entry => entry.ownerId === account.id); + +const left = account => { + const mine = madeBy(account); + const today = mine.filter(entry => entry.createdAt > now() - DAY).length; + return {today: Math.max(0, Math.min(PER_DAY - today, IN_ALL - mine.length)), inAll: Math.max(0, IN_ALL - mine.length)}; +}; + +// returns {ok} or {error}. +const make = (session, kind, baseId, name) => { + const {account} = session; + if (!enabled()) { + return {error: "The Item Maker is turned off on this server for now."}; + } + if (!customItems.KINDS.includes(kind) || !/^\d+$/.test(String(baseId))) { + return {error: "Choose an item to make yours from."}; + } + if (!customItems.copyable(kind, Number(baseId))) { + return {error: "That item cannot be made into one of your own. Choose another."}; + } + const room = left(account); + if (room.inAll === 0) { + return {error: `You have made ${IN_ALL} items, as many as there can be. Delete one to make another.`}; + } + if (room.today === 0) { + return {error: `You have made ${PER_DAY} items today. Try again tomorrow.`}; + } + const clean = String(name || "").trim().replace(/\s+/g, " "); + if (clean && names.refused(clean)) { + return {error: "That name is not allowed."}; + } + const waits = approvalOn(); + const result = customItems.create(kind, {base: Number(baseId), name: clean, cost: 0, members: false, inShop: false}, account.username, account.id, waits); + if (result.error) { + return result; + } + const {item} = result; + if (waits) { + modlog.record(account.username, "item made by a player, waiting for approval", "", `${kind} ${item.id} ${item.name}`); + return {ok: `${item.name} is waiting for a moderator to approve it. It is yours as soon as they do.`}; + } + giveTo(account, item, session); + modlog.record(account.username, "item made by a player", "", `${kind} ${item.id} ${item.name}`); + return {ok: `Made ${item.name}. It is in your ${kind === "den" ? "den items" : "clothing"} now.`}; +}; + +// one of the item, to its maker: now in their game if `session` is it +const giveTo = (account, item, session) => { + if (item.kind === "den") { + if (dens.giveDenItem(account, item.id) && session) { + dens.sendDenItems(session); + } + } + else { + const given = addClothing(account, item.id, item.colors[0]); + accounts.save(account); + if (session) { + sendClothingAdded(session, given); + } + } +}; + +// a moderator's answer about what waits (lib/modpanel.js, lib/panel.js): an +// item let in is given to its maker; one turned away is deleted, or only +// its picture taken away. `world` finds whether its maker is playing, and +// tells games about items taken. returns {ok} or {error}. +const review = (kind, id, approve, by, world) => { + const entry = customItems.get(kind, id); + if (!entry || (!entry.pending && !entry.artPending)) { + return {error: "That is not waiting for approval."}; + } + const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId); + const wasNew = entry.pending; + if (approve) { + customItems.approve(kind, entry.id); + if (wasNew && maker) { + giveTo(maker, entry, world.findOnline(maker.username)); + } + return {ok: wasNew ? `${entry.name} is in the game, and ${maker ? maker.username : "its maker"} has one.` : `${entry.name}'s picture is shown now.`}; + } + if (wasNew) { + itemControl.deleteCustom(kind, entry.id, world); + return {ok: `${entry.name} was turned away and deleted.`}; + } + const said = strike(entry); + require("./itemart.js").remove(kind, entry.id); + return {ok: `${entry.name}'s new picture was turned away.${said}`}; +}; + +// a new name for one of their own (every game is told: customItems.update). +const rename = (account, kind, id, name) => { + const entry = customItems.get(kind, id); + if (!entry || entry.ownerId !== account.id) { + return {error: "That is not one of your items."}; + } + if (!renames.allow(account.id)) { + return {error: "Too many renames. Try again in an hour."}; + } + const clean = String(name || "").trim().replace(/\s+/g, " "); + if (clean && names.refused(clean)) { + return {error: "That name is not allowed."}; + } + const result = customItems.update(kind, entry.id, {name: clean}); + return result.error ? result : {ok: `Renamed it ${result.item.name}.`}; +}; + +// how one of their own is worn ("sticker" or "texture") +const setLook = (account, kind, id, mode) => { + const entry = customItems.get(kind, id); + if (!entry || entry.ownerId !== account.id) { + return {error: "That is not one of your items."}; + } + const result = customItems.setArtMode(kind, entry.id, String(mode)); + return result.error ? result : {ok: `${entry.name} is worn as ${mode === "texture" ? "its shape, with your picture in it" : "your picture"}.`}; +}; + +const remove = (session, kind, id, world) => { + const entry = customItems.get(kind, id); + if (!entry || entry.ownerId !== session.account.id) { + return {error: "That is not one of your items."}; + } + const result = itemControl.deleteCustom(kind, entry.id, world); + return result.error ? result : {ok: `Deleted ${entry.name}.`}; +}; + +const reply = (session, result) => { + const room = left(session.account); + const mine = madeBy(session.account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name, base: entry.base, art: entry.artPending ? "" : entry.art || "", + artMode: entry.artMode || "sticker", waiting: entry.pending ? "item" : entry.artPending ? "picture" : ""})); + session.sendXt("xcm", -1, result.error ? 0 : 1, String(result.error || result.ok || "").replace(/%/g, " percent"), room.today, room.inAll, + JSON.stringify(mine).replace(/%/g, "\\u0025")); +}; + +// `world` tells games about items taken (lib/world.js itemsTaken). +const handlers = world => ({ + xcm(session, roomId, [action, kind, id, ...words]) { + if (action === "make") { + reply(session, make(session, kind, id, words.join(" "))); + } + else if (action === "look") { + reply(session, setLook(session.account, kind, id, words[0])); + } + else if (action === "rename") { + reply(session, rename(session.account, kind, id, words.join(" "))); + } + else if (action === "delete") { + reply(session, remove(session, kind, id, world)); + } + else { + reply(session, enabled() ? {ok: ""} : {error: "The Item Maker is turned off on this server for now."}); + } + }, +}); + +module.exports = {handlers, madeBy, rename, setLook, review, enabled, approvalOn, artApprovalOn, pictureWaits, setSwitches, + pictureRefused, uploadRefusal, setUploadsBlocked, takePicture, ART_STRIKES, PER_DAY, IN_ALL}; diff --git a/lib/reports.js b/lib/reports.js index 64f59aa..62c4d7f 100644 --- a/lib/reports.js +++ b/lib/reports.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const accounts = require("./accounts.js"); const limits = require("./limits.js"); @@ -69,7 +70,7 @@ const file = ({reporter, target, reason, detail = "", context = "", room = ""}) } db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)") .run(now(), reporter, target, Number.isInteger(reason) ? reason : 0, clean(detail, MAX_DETAIL), clean(context, MAX_CONTEXT), clean(room, 100)); - console.log(`[world] ${reporter} reported "${target}" (${REASONS[reason] || `reason ${reason}`})`); + console.log(`[world] ${logText(reporter)} reported "${logText(target)}" (${logText(REASONS[reason] || `reason ${reason}`)})`); return true; }; diff --git a/lib/roles.js b/lib/roles.js new file mode 100644 index 0000000..a6c54d0 --- /dev/null +++ b/lib/roles.js @@ -0,0 +1,167 @@ +"use strict"; + +const accounts = require("./accounts.js"); +const totp = require("./totp.js"); + +// staff roles, and what each may do. an account holds at most one role +// (`role` on the account), set by the admin. an account from before roles +// that is only marked `moderator` counts as a moderator, so nothing that +// worked before stops working. +// +// a role is a list of permissions, and every staff action checks the one it +// needs, in the moderator panel (lib/modpanel.js) and in the game +// (lib/commands.js) alike. a higher role holds everything a lower one does. +// staff never act on staff of their own rank or above: that is for someone +// higher up, and for the admin in the end. + +const PERMISSIONS = { + "player.view": "see players, chat, reports, requests, bans and paintings in the moderator panel, and keep notes on players (!note, !notes)", + "staff.list": "see which staff are online (!staff)", + "player.warn": "warn a player, take a warning back and send them a message (!warn, !unwarn, !warnings, !message)", + "player.goto": "go to the room a player is in (!goto)", + "chat.silence": "silence and unsilence a player (!silence)", + "player.kick": "disconnect a player (!kick)", + "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", + "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)", +}; + +const HELPER = ["player.view", "staff.list", "player.warn", "player.goto", "chat.silence"]; +const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve"]; +const ADMIN = [...MODERATOR, "items.create"]; +// a developer makes things, and moderates nobody. +const DEVELOPER = ["staff.list", "items.create"]; + +const ROLES = { + developer: {rank: 1, label: "Developer", permissions: DEVELOPER}, + helper: {rank: 1, label: "Helper", permissions: HELPER}, + moderator: {rank: 2, label: "Moderator", permissions: MODERATOR}, + admin: {rank: 3, label: "Admin", permissions: ADMIN}, +}; + +// the role an account holds, or null. +const roleOf = account => { + if (!account) { + return null; + } + if (Object.hasOwn(ROLES, account.role)) { + return account.role; + } + return account.moderator ? "moderator" : null; +}; + +const rankOf = account => { + const role = roleOf(account); + return role ? ROLES[role].rank : 0; +}; + +// may this account act as staff at all right now? as for the moderator +// panel: a role, 2FA turned on, not locked and not banned. `banned` says +// whether the account is banned (passed in, so that this file needs nothing +// of the world's). +const isActiveStaff = (account, banned = false) => + Boolean(roleOf(account) && totp.isOn(account) && !account.locked && !banned); + +// what each role may do can be changed by the admin (the admin panel's +// Moderators page): kept as a setting, {role: [permission, ...]}, a role +// not in it holding its defaults above. one staff member can be given more +// than their role, or less (`permGrants`, `permDenies` on the account, from +// their page in the admin panel). a role and 2FA are still what makes +// someone staff at all (isActiveStaff). +const ROLE_SETTING = "rolePermissions"; +let roleOverrides = null; + +const overrides = () => { + if (!roleOverrides) { + try { + const saved = JSON.parse(accounts.setting(ROLE_SETTING) || "{}"); + roleOverrides = saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {}; + } + catch { + roleOverrides = {}; + } + } + return roleOverrides; +}; + +// the permissions in a list that are ones, each once +const known = list => [...new Set(Array.isArray(list) ? list.map(String) : [])].filter(permission => Object.hasOwn(PERMISSIONS, permission)); + +const rolePermissions = role => (Object.hasOwn(overrides(), role) ? known(overrides()[role]) : [...ROLES[role].permissions]); + +const roleChanged = role => Object.hasOwn(overrides(), role); + +// a role's permissions, or its defaults again (`list` null). false for no such role. +const setRolePermissions = (role, list) => { + if (!Object.hasOwn(ROLES, role)) { + return false; + } + const changed = {...overrides()}; + if (list === null) { + delete changed[role]; + } + else { + changed[role] = known(list); + } + accounts.setSetting(ROLE_SETTING, JSON.stringify(changed)); + roleOverrides = changed; + return true; +}; + +const permissionsOf = account => { + const role = roleOf(account); + if (!role) { + return []; + } + const denied = new Set(known(account.permDenies)); + return [...new Set([...rolePermissions(role), ...known(account.permGrants)])].filter(permission => !denied.has(permission)); +}; + +// one staff member's own: given beyond their role, and taken from it. a +// permission in both is given. the caller saves the account. +const setAccountPermissions = (account, grants, denies) => { + const given = known(grants); + const taken = known(denies).filter(permission => !given.includes(permission)); + if (given.length) { + account.permGrants = given; + } + else { + delete account.permGrants; + } + if (taken.length) { + account.permDenies = taken; + } + else { + delete account.permDenies; + } +}; + +const can = (account, permission, banned = false) => + isActiveStaff(account, banned) && permissionsOf(account).includes(permission); + +// may `actor` act on `target`? never on themselves, nor on staff of their +// own rank or above. +const outranks = (actor, target) => actor !== target && rankOf(actor) > rankOf(target); + +// sets the role (one of ROLES, or null for none). `moderator` is kept in +// step for anything that still reads it. +const setRole = (account, role) => { + if (role === null || role === "" || role === "none") { + delete account.role; + delete account.moderator; + return true; + } + if (!Object.hasOwn(ROLES, role)) { + return false; + } + account.role = role; + account.moderator = true; + return true; +}; + +module.exports = {PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, rolePermissions, roleChanged, setRolePermissions, + setAccountPermissions, can, outranks, setRole}; diff --git a/lib/roominfo.js b/lib/roominfo.js index bc8a85b..0f124ed 100644 --- a/lib/roominfo.js +++ b/lib/roominfo.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const zlib = require("zlib"); const amf3 = require("./amf3.js"); const cdn = require("./cdn.js"); @@ -71,7 +72,7 @@ const preload = async () => { remember(base, body); } } - console.log(`[rooms] names of ${rooms.size} rooms read from the cache`); + console.log(`[rooms] names of ${logText(rooms.size)} rooms read from the cache`); }; // A name made from the path, for a room not read yet or left unnamed: diff --git a/lib/sfs.js b/lib/sfs.js index c6c9dcf..ab37fe9 100644 --- a/lib/sfs.js +++ b/lib/sfs.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const crypto = require("crypto"); const fs = require("fs"); const net = require("net"); @@ -49,7 +50,7 @@ class Session { write(message) { if (this.socket.writable) { if (config.logPackets) { - console.log(`[game] -> ${this.name} ${message}`); + console.log(`[game] -> ${logText(this.name)} ${logText(message)}`); } this.socket.write(message + "\0"); // A client that stopped reading must not pile up messages here forever. @@ -96,7 +97,7 @@ const parseSys = message => { const start = handlers => new Promise((resolve, reject) => { const dispatch = (session, message) => { if (config.logPackets) { - console.log(`[game] <- ${session.name} ${forLog(message)}`); + console.log(`[game] <- ${logText(session.name)} ${logText(forLog(message))}`); } if (message.startsWith(" new Promise((resolve, reject) => { let bytesInWindow = 0; let errorsInWindow = 0; socket.setNoDelay(true); - console.log(`[game] ${session.remote} connected as #${session.id}`); + console.log(`[game] ${logText(session.remote)} connected as #${logText(session.id)}`); // whoever connects has to log in (or start signing up) promptly, and // nobody may sit silent for long: the client sends keep-alives. @@ -178,7 +179,7 @@ const start = handlers => new Promise((resolve, reject) => { } bytesInWindow += chunk.length; if (bytesInWindow > config.maxBytesPerTenSeconds) { - console.log(`[game] ${session.name} disconnected for flooding`); + console.log(`[game] ${logText(session.name)} disconnected for flooding`); socket.destroy(); return; } @@ -190,7 +191,7 @@ const start = handlers => new Promise((resolve, reject) => { return; } if (++messagesInWindow > config.maxMessagesPerTenSeconds) { - console.log(`[game] ${session.name} disconnected for flooding`); + console.log(`[game] ${logText(session.name)} disconnected for flooding`); socket.destroy(); return; } @@ -203,9 +204,9 @@ const start = handlers => new Promise((resolve, reject) => { // one line a failure, and an end to them: a client that sends // nonsense in a loop is not to fill the log. const where = String(err.stack || "").split("\n")[1] || ""; - console.log(`[game] error handling message from ${session.name}: ${err.message}${where ? ` (${where.trim()})` : ""}`); + console.log(`[game] error handling message from ${logText(session.name)}: ${logText(err.message)}${logText(where ? ` (${where.trim()})` : "")}`); if (++errorsInWindow > MAX_ERRORS_PER_WINDOW) { - console.log(`[game] ${session.name} disconnected: too many messages that could not be handled`); + console.log(`[game] ${logText(session.name)} disconnected: too many messages that could not be handled`); socket.destroy(); return; } @@ -228,13 +229,13 @@ const start = handlers => new Promise((resolve, reject) => { else { connections.delete(address); } - console.log(`[game] ${session.name} disconnected`); + console.log(`[game] ${logText(session.name)} disconnected`); // nothing thrown while a player is seen off may take the server down. try { handlers.close(session); } catch (err) { - console.log(`[game] error while ${session.name} left: ${err.stack}`); + console.log(`[game] error while ${logText(session.name)} left: ${logText(err.stack)}`); } }); }; @@ -271,7 +272,7 @@ const start = handlers => new Promise((resolve, reject) => { } server.once("error", reject); server.listen(config.gamePort, config.gameBindAddress, () => { - console.log(`[game] listening on ${config.gameBindAddress}:${config.gamePort}${config.tls ? " (TLS)" : ""}`); + console.log(`[game] listening on ${logText(config.gameBindAddress)}:${logText(config.gamePort)}${logText(config.tls ? " (TLS)" : "")}`); resolve(server); }); }); diff --git a/lib/signup.js b/lib/signup.js index e5df46b..79b2432 100644 --- a/lib/signup.js +++ b/lib/signup.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const crypto = require("crypto"); const accounts = require("./accounts.js"); const bans = require("./bans.js"); @@ -24,6 +25,7 @@ const STATUS = { username_taken: USERNAME_TAKEN, invalid_username: USERNAME_INVALID, invalid_password: PASSWORD_INVALID, + weak_password: PASSWORD_INVALID, // the game's screens have one word for both name_not_allowed: USERNAME_INVALID, }; // names asked about on one guest connection: the screens ask once or twice. @@ -88,7 +90,7 @@ const handlers = { return; } if (!limits.registrationAllowed(session.address, limits.isTrustedLocal(session.address))) { - console.log(`[signup] too many sign-ups from ${session.address}`); + console.log(`[signup] too many sign-ups from ${logText(session.address)}`); session.sendXt("lc", -1, FAILED, 0); return; } diff --git a/lib/support.js b/lib/support.js index 3c26fe0..f238203 100644 --- a/lib/support.js +++ b/lib/support.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const accounts = require("./accounts.js"); // what players send from the account page (/account, lib/manage.js) for @@ -79,7 +80,7 @@ const requestName = (account, newName, reason) => { db().prepare("UPDATE name_requests SET status = ?, handled_at = ? WHERE account_id = ? AND status = ?").run(WITHDRAWN, now(), account.id, WAITING); db().prepare("INSERT INTO name_requests (created_at, account_id, old_name, new_name, reason) VALUES (?, ?, ?, ?, ?)") .run(now(), account.id, account.username, newName, clean(reason, MAX_REASON)); - console.log(`[support] "${account.username}" asked to be called "${newName}"`); + console.log(`[support] "${logText(account.username)}" asked to be called "${logText(newName)}"`); return {request: waitingNameRequest(account)}; }; @@ -127,7 +128,7 @@ const sendFeedback = (account, kind, text) => { return {error: "too_many"}; } db().prepare("INSERT INTO feedback (created_at, account_id, username, kind, text) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, body); - console.log(`[support] ${kind === "bug" ? "bug report" : "feedback"} from "${account.username}"`); + console.log(`[support] ${logText(kind === "bug" ? "bug report" : "feedback")} from "${logText(account.username)}"`); return {ok: true}; }; diff --git a/lib/walls.js b/lib/walls.js index ef282f1..4f11f14 100644 --- a/lib/walls.js +++ b/lib/walls.js @@ -1,5 +1,6 @@ "use strict"; +const {logText} = require("./logtext.js"); const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); @@ -73,6 +74,14 @@ const flat = value => scalar(value) || (typeof value === "object" && !Array.isAr && Object.keys(value).length <= 12 && Object.values(value).every(scalar)); const plainParam = value => flat(value) || (Array.isArray(value) && value.length <= MAX_PARAM_ENTRIES && value.every(flat)); const whole = value => (Number.isInteger(Number(value)) ? Number(value) : 0); +// the photo booth picture ("pb", PlayerWallGui): one level deeper than the +// rest, {avatar: {id, color1.., eyes, pattern}, bgid, pet: {ts, lbits, ..} | +// null, items: [{id, color}, ..]}. it was turned away as too deep, and the +// owner's whole change with it: the photo never stayed. +const MAX_PHOTO_ITEMS = 30; +const photoParam = value => value === null || (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length <= 6 + && Object.entries(value).every(([key, part]) => (key === "items" ? Array.isArray(part) && part.length <= MAX_PHOTO_ITEMS && part.every(flat) + : key === "avatar" || key === "pet" ? part === null || flat(part) : scalar(part)))); module.exports = ({blocks, findOnline}) => { const tokens = new Map(); // token -> {viewer: account id, owner: account id, expires} @@ -155,7 +164,7 @@ module.exports = ({blocks, findOnline}) => { // the server's filter (lib/chatfilter.js) too. const rule = message ? chatFilter.broken(message) : null; if (rule) { - console.log(`[filter] ${viewer.username} on ${owner.username}'s wall: "${message}" (${rule})`); + console.log(`[filter] ${logText(viewer.username)} on ${logText(owner.username)}'s wall: "${logText(message)}" (${logText(rule)})`); chatlog.recordTo(viewer, chatlog.WALL, owner.username, chatlog.NOT_SENT + message); const session = findOnline(viewer.username); if (session) { @@ -325,7 +334,7 @@ module.exports = ({blocks, findOnline}) => { const merged = changes && typeof changes === "object" && !Array.isArray(changes) ? {...wall.params} : null; for (const key of merged ? OWNER_PARAMS : []) { if (changes[key] !== undefined) { - if (!plainParam(changes[key])) { + if (!(key === "pb" ? photoParam(changes[key]) : plainParam(changes[key]))) { session.sendXt("wps", -1, 0); return; } diff --git a/lib/world.js b/lib/world.js index 2a8293f..bf22bb9 100644 --- a/lib/world.js +++ b/lib/world.js @@ -1,10 +1,15 @@ "use strict"; +const {logText} = require("./logtext.js"); const accounts = require("./accounts.js"); const achievements = require("./achievements.js"); const adopt = require("./adopt.js"); const config = require("../config.js"); const colours = require("./colours.js"); +const customItems = require("./customitems.js"); +const roles = require("./roles.js"); +const modlog = require("./modlog.js"); +const playerItems = require("./playeritems.js"); const commandModule = require("./commands.js"); const limits = require("./limits.js"); const masterpieces = require("./masterpieces.js"); @@ -15,6 +20,7 @@ const bans = require("./bans.js"); const devices = require("./devices.js"); const chatlog = require("./chatlog.js"); const chatFilter = require("./chatfilter.js"); +const chatSpam = require("./chatspam.js"); const buddyModule = require("./buddies.js"); const dens = require("./dens.js"); const disguises = require("./disguises.js"); @@ -35,7 +41,7 @@ const stubHandlers = require("./stubs.js"); const wallModule = require("./walls.js"); const worldItems = require("./worlditems.js"); const stats = require("./stats.js"); -const {CURRENCIES, DIAMOND_TYPES, activeAvatar, avatarById, activePet, equippedBits, wornItems, lastSeenField} = require("./player.js"); +const {CURRENCIES, DIAMOND_TYPES, activeAvatar, avatarById, activePet, equippedBits, wornItems, lastSeenField, sendClothingRemoved} = require("./player.js"); // game logic behind the socket. field orders below mirror the client's // parsers; the class that reads each message is named next to it. @@ -170,9 +176,12 @@ const blocks = { has: (blocker, target) => blocker.blocked.includes(nameKey(target)), either: (a, b) => a.blocked.includes(nameKey(b)) || b.blocked.includes(nameKey(a)), }; -const sees = (viewer, subject) => !(viewer.account.hideBlocked && blocks.has(viewer.account, subject.account)); +// staff gone invisible (setInvisible, below) are drawn for staff only. +const sees = (viewer, subject) => (!subject.invisible || roles.isActiveStaff(viewer.account)) + && !(viewer.account.hideBlocked && blocks.has(viewer.account, subject.account)); // everyone else in the room who should hear about this player's animal. 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) const decodeEntities = text => text .replace(/</g, "<") @@ -208,6 +217,11 @@ const loginParams = session => { // from bit 8 up: the name tag badges the admin gave this account // (lib/badges.js). pendingFlags: 7 | badges.loginFlags(account), + // this account's own staff role and what it allows (lib/roles.js), for a + // client to show staff tools only to staff. empty for everyone else, and + // only ever about the account logging in. + staffRole: roles.isActiveStaff(account) ? roles.roleOf(account) : "", + staffPermissions: roles.isActiveStaff(account) ? roles.permissionsOf(account).join(",") : "", dailyGiftIndex: -1, hasOnlineBuddies: buddies.hasOnlineBuddies(account), // one bit per kind of interaction (Utility.canBuddy, canTrade, canGift, @@ -267,44 +281,44 @@ const login = (session, msg) => { const username = (msg.cdata("nick") || "").split("%")[0]; const account = accounts.byToken(msg.cdata("pword")); if (!account || account.username.toLowerCase() !== username.toLowerCase()) { - console.log(`[world] login rejected for "${username}"`); + console.log(`[world] login rejected for "${logText(username)}"`); loginFailed(session, 0, "Invalid login"); return; } if (moderation.banRemaining(account) !== 0) { - console.log(`[world] login rejected for banned account "${account.username}"`); + console.log(`[world] login rejected for banned account "${logText(account.username)}"`); loginFailed(session, LOGIN_BANNED, "Banned"); return; } // A banned address (lib/bans.js). the client is told at /authenticate, // with the reason; this is for a game that got here another way. if (bans.addressBan(session.address)) { - console.log(`[world] login rejected for "${account.username}" from a banned address`); + console.log(`[world] login rejected for "${logText(account.username)}" from a banned address`); loginFailed(session, LOGIN_BANNED, "Banned"); return; } // a banned computer (lib/devices.js), and a game that never said which // computer it is on: told at /authenticate too, which is the way in. if (devices.banOfAccount(account)) { - console.log(`[world] login rejected for "${account.username}": hardware banned`); + console.log(`[world] login rejected for "${logText(account.username)}": hardware banned`); 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 "${account.username}": no device ids`); + console.log(`[world] login rejected for "${logText(account.username)}": no device ids`); loginFailed(session, 0, "Update the client"); return; } // its username was rejected (lib/moderation.js): a new one first, which // the client or the account page asks for. if (account.nameRejected) { - console.log(`[world] login rejected for "${account.username}": the name was rejected`); + console.log(`[world] login rejected for "${logText(account.username)}": the name was rejected`); loginFailed(session, 0, "Username rejected"); return; } // locked by its owner on the account page (lib/manage.js). if (account.locked) { - console.log(`[world] login rejected for locked account "${account.username}"`); + console.log(`[world] login rejected for locked account "${logText(account.username)}"`); loginFailed(session, 0, "Account locked"); return; } @@ -336,13 +350,21 @@ const login = (session, msg) => { achievements.refresh(account); accounts.save(account); online.set(key, session); - console.log(`[world] ${account.username} logged in as sfs user ${session.id}`); + console.log(`[world] ${logText(account.username)} logged in as sfs user ${logText(session.id)}`); session.sendXtJson(-1, {_cmd: "login", status: "1", params: loginParams(session)}); // every custom colour, before anything that might be drawn with one // (XtReplyDemuxer -> PaletteHelper.handleCustomColors in the patched SWF). for (const chunk of colours.chunks()) { session.sendXt("xcc", -1, chunk.length, ...chunk.flat()); } + // and the items staff have made (lib/customitems.js), for a game started + // before they were. + customItems.sendAll(session); + // staff: their role and what it allows, for the patched client's staff + // window (AJClient.onStaff). nobody else is sent anything. + if (roles.isActiveStaff(account)) { + session.sendXt("xsp", -1, roles.roleOf(account), roles.permissionsOf(account).join(",")); + } sendFilter(session); buddies.announce(account); }; @@ -411,6 +433,9 @@ const sendAvatarCreate = (to, target) => { ...(pet ? petFields(pet) : [])); sendItemList(to, target, false); disguises.show(to, target); + if (target.invisible) { + to.sendXt("xiv", -1, target.id, 1); + } }; // redraws `session`'s animal for everyone else in the room, for changes the @@ -452,6 +477,8 @@ const sortStock = () => { // has the den items, the one in the Zios archives the clothing. see // oddDenItemIds in lib/defpacks.js. const ODDITY_SHOPS = new Map([[396, () => defpacks.oddDenItemIds()], [666, () => defpacks.oddClothingIds()]]); +// the items staff have made (lib/customitems.js) are sold there too, first. +const CUSTOM_ITEM_SHOPS = new Map([[396, "den"], [666, "clothing"]]); const ticketStock = kind => sortStock()[kind]; // the den shops of the lands (Coral Canyons, Deep Blue) and the one inside // a den: lists that mix kinds, selling den rooms. @@ -482,6 +509,8 @@ const sendUserVars = session => { }; const findOnline = username => online.get(String(username).toLowerCase()); +const STAFF_WINDOW_COMMANDS = ["warn", "unwarn", "message", "silence", "kick", "summon", "goto", "warnings"]; +const MAX_STAFF_WINDOW_WORDS = 3; // username, then a reason, hours or the message (each one field) // a custom colour (lib/colours.js) for these four RGB values, made if it is // new and the account has not made its day's worth; everyone online is told @@ -504,6 +533,13 @@ const makeColour = (account, rgbs, asker = null) => { return entry; }; +// a message for every game playing (custom items, lib/customitems.js). +customItems.connect((cmd, ...params) => { + for (const session of online.values()) { + session.sendXt(cmd, -1, ...params); + } +}); + // the account's chat filter, for its game to apply: [chosen, level, mode, own words]. const sendFilter = session => { const {filter} = session.account; @@ -612,6 +648,7 @@ const handlers = { } buddies.greet(session); minigames.greet(session); + moderation.greet(session); // never asked what chat they want filtered: the window is put to // them, this once (the patched client's "xfa"). if (!session.account.filter.chosen) { @@ -619,8 +656,12 @@ const handlers = { } } if (firstUpdate) { - // the player's own animal is on their screen now: its disguise, if any. + // the player's own animal is on their screen now: its disguise, if any, + // and see-through if they are invisible. disguises.show(session, session); + if (session.invisible) { + session.sendXt("xiv", -1, session.id, 1); + } } for (const other of watchers(session)) { if (firstUpdate) { @@ -628,7 +669,6 @@ const handlers = { sendAvatarCreate(other, session); } else { - // AvatarManager.avatarUpdateResponse other.sendXt("au", session.room.id, 1, session.id, count, ...coords, teleport); } } @@ -737,7 +777,7 @@ const handlers = { else if (ODDITY_SHOPS.has(Number(listId))) { // what the shop really sold comes first. const real = shopStock.list(listId, type); - entries = [...new Set([...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])]; + entries = [...new Set([...defpacks.customShopIds(CUSTOM_ITEM_SHOPS.get(Number(listId))), ...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])]; } else if (Number(listId) === DIAMOND_DEN_LIST) { entries = defpacks.diamondIds().filter(id => { @@ -845,6 +885,39 @@ const handlers = { session.sendXt("fra", -1, fileReport(session, username, reason, "", about) ? 1 : 0); }, + // the staff's window of the patched client (AJClient.openModerate): + // [command, username, ...words], one of the staff commands about a player, + // run as if typed (lib/commands.js checks the permission and logs it). + xmd(session, roomId, [command, ...words]) { + if (roles.isActiveStaff(session.account) && STAFF_WINDOW_COMMANDS.includes(command) && words.length > 0 && words.length <= MAX_STAFF_WINDOW_WORDS) { + commands.run(session, `!${command} ${words.join(" ")}`); + } + }, + + // the patched client's chat box: whether its player is typing, for a + // "..." over their animal in everyone else's game (gui.ChatHistory): + // xty [1 | 0], passed on as "xty" [.., .., sfsId, 1 | 0]. a client says + // it again every few seconds while typing; more often is not passed on. + xty(session, roomId, [on]) { + const typing = on === "1"; + const now = Date.now(); + if (!session.room || session.invisible || (typing && session.typingAt && now - session.typingAt < TYPING_EVERY_MS) + || (!typing && !session.typingAt)) { + return; + } + session.typingAt = typing ? now : 0; + for (const other of watchers(session)) { + other.sendXt("xty", -1, session.id, typing ? 1 : 0); + } + }, + + // the patched client's staff window: going invisible, or being seen again. + xiv(session) { + if (session.invisible || roles.can(session.account, "staff.invisible")) { + setInvisible(session, !session.invisible); + } + }, + // the patched report window (gui.ReportAPlayer), just before its "fr" or // "fra": [username, reasonId, what the reporter typed]. xrd(session, roomId, [username, reason, ...text]) { @@ -951,6 +1024,118 @@ const fileReport = (session, username, reason, detail = "", about = "") => { // what the modules below may use of this one. `others` here is everyone who // should see the player's animal change; dens get everyone in the room. +// invisible staff (the "staff.invisible" permission): their animal is drawn +// for staff only, half see-through ("xiv" [.., .., sfsId, 1 | 0], for the +// patched client), on their own screen too. the game's own invisible mode +// ("fi") is not used: with it the client stops sending where it walks, and +// staff could not see them move. they say nothing while invisible (pubMsg). +const setInvisible = (session, invisible) => { + if (Boolean(session.invisible) === invisible) { + return; + } + const {room} = session; + const shown = Boolean(room && session.pos); + const before = shown ? watchers(session) : []; + session.invisible = invisible; + const after = shown ? watchers(session) : []; + for (const other of before.filter(other => !after.includes(other))) { + other.sendXt("ar", room.id, session.id); + } + for (const other of after) { + if (before.includes(other)) { + other.sendXt("xiv", -1, session.id, invisible ? 1 : 0); + } + else { + sendAvatarCreate(other, session); + } + } + if (shown) { + session.sendXt("xiv", -1, session.id, invisible ? 1 : 0); + } + // the patched client's message box, as the staff commands answer in + session.sendXt("xtl", -1, invisible ? "You are invisible: only staff see you, and you cannot chat. Say !invisible again to be seen." + : "You can be seen again."); + modlog.record(session.account.username, invisible ? "went invisible (in game)" : "became visible (in game)", "", room ? room.name : ""); +}; + +// what an account's game knows of its staff role ("xsp", AJClient.onStaff), +// sent again when the admin changed it: nothing for one no longer staff. +// one that may no longer go invisible is seen again. +const refreshStaff = account => { + const session = findOnline(account.username); + if (!session) { + return; + } + const active = roles.isActiveStaff(account); + session.sendXt("xsp", -1, active ? roles.roleOf(account) : "", active ? roles.permissionsOf(account).join(",") : ""); + if (session.invisible && !roles.can(account, "staff.invisible")) { + setInvisible(session, false); + } +}; + +// items taken from an account (lib/itemcontrol.js): its game, if playing, +// and anybody in its den are told. `worn`: clothing it had on went too. +const itemsTaken = (account, kind, invs, worn) => { + const session = findOnline(account.username); + if (session && kind === "den") { + dens.sendDenItems(session); + } + else if (session) { + sendClothingRemoved(session, invs); + if (worn) { + sendItemList(session, session, false); + refreshForOthers(session); + } + } + const den = kind === "den" ? rooms.get(`den${account.username}`) : null; + for (const other of den ? den.sessions : []) { + dens.sendDenState(other, den, false); + } +}; + +// staff moving a player: `whoName` to the room `toName` is in (summon is +// the player to the staff member, goto the staff member to the player). both +// online, `toName` in a room. the room's own rules still apply: a full room +// or a locked den keeps them out. +// they land where `toName` stands (the patched client's "xgt": [x, y, +// "1" same room, teleported now | "0" the spot to spawn on in the next +// room], or [] to forget a spot not used). with nobody's spot known yet, +// it is the room's usual spawn. +const staffMove = (whoName, toName) => { + const who = findOnline(whoName); + const to = findOnline(toName); + if (!who) { + return {error: `${whoName} is not online.`}; + } + if (!to || !to.room) { + return {error: `${toName} is not in a room.`}; + } + const room = to.room; + const shown = room.displayName || room.name; + const spot = to.pos ? [to.pos.x, to.pos.y] : null; + if (who.room === room) { + if (!spot) { + return {error: "Already in the same room."}; + } + who.sendXt("xgt", -1, ...spot, 1); + return {ok: true, room: shown}; + } + if (room.sessions.size >= config.maxUsersPerRoom) { + return {error: `${shown} is full.`}; + } + if (spot) { + who.sendXt("xgt", -1, ...spot, 0); + } + joinRoom(who, room.name); + if (who.room !== room) { + if (spot) { + who.sendXt("xgt", -1); + } + return {error: `Could not get into ${shown}.`}; + } + return {ok: true, room: shown}; +}; + const context = { others: watchers, watchers, @@ -974,6 +1159,10 @@ const context = { worldOf, worldName, joinRoom: (...args) => joinRoom(...args), + staffMove: (...args) => staffMove(...args), + setInvisible: (...args) => setInvisible(...args), + // the moderation module, made after this context (lib/commands.js uses it) + staffModeration: () => moderation, reloadRoom: session => reloadRoom(session), buyAgain: session => handlers[session.lastPurchase.cmd](session, session.lastPurchase.roomId, session.lastPurchase.params), }; @@ -990,7 +1179,8 @@ const trades = tradeHandlers(context); achievements.setFinder(findOnline); Object.assign(handlers, avatarHandlers(context), itemHandlers(context), pets.handlers, dens.handlers({...context, others}), buddies.handlers, moderation.handlers, trades.handlers, achievements.handlers, adopt.handlers, worldItems.handlers, - parties.handlers, ecards.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers); + parties.handlers, ecards.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers, + playerItems.handlers({itemsTaken: (...args) => itemsTaken(...args)})); const leaveRoom = session => { const {room} = session; @@ -1125,7 +1315,7 @@ const setTheme = (account, theme) => { // RoomXtCommManager.roomJoinResponse failure branch const joinFailed = (session, reason) => { - console.log(`[world] ${session.name} could not join: ${reason}`); + console.log(`[world] ${logText(session.name)} could not join: ${logText(reason)}`); session.sendXt("rj", -1, 0, reason); }; @@ -1153,7 +1343,7 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => { // so is a player arriving when every spawn room is full (spawnRoom). const overflow = session.spawnOverflow; session.spawnOverflow = false; - if (room && room.sessions.size >= config.maxUsersPerRoom && !session.account.moderator && !overflow) { + if (room && room.sessions.size >= config.maxUsersPerRoom && !roles.isActiveStaff(session.account) && !overflow) { joinFailed(session, "This room is currently full"); return; } @@ -1398,7 +1588,7 @@ const unhandled = (cmd, params) => { const key = cmd === "gl" ? `gl ${params[0]}` : cmd; if (!seenUnhandled.has(key) && seenUnhandled.size < 500) { seenUnhandled.add(key); - console.log(`[world] no handler for xt "${key}" (params: ${JSON.stringify(params).slice(0, 200)}) - the client gets no reply`); + console.log(`[world] no handler for xt "${logText(key)}" (params: ${logText(JSON.stringify(params).slice(0, 200))}) - the client gets no reply`); } }; @@ -1463,25 +1653,43 @@ module.exports = { session.sendXt("uc", session.room.id, session.id, ...fields); return; } - fields[0] = said; + // invisible staff give commands and say nothing: the bubble + // waiting goes, as for a silenced player. + if (session.invisible) { + session.sendXt("uc", session.room.id, session.id, -1, 5); + return; + } + // how much there is of it (lib/chatspam.js): a key held down, a + // word over and over, shouting, a wall of emoji are cut down; the + // same line again and again is not sent. + const line = chatSpam.tidy(said); + if (!line || chatSpam.repeated(session, line)) { + session.sendXt("uc", session.room.id, session.id, -1, 5); + return; + } + fields[0] = line; // the server's filter (lib/chatfilter.js): the line reaches // nobody, the sender sees the game's warning screen, and it is // kept in the chat log for the moderators, marked as not sent. - const rule = chatFilter.broken(said); + const rule = chatFilter.broken(line); if (rule) { session.sendXt("uc", session.room.id, session.id, -1, 5); chatFilter.warn(session); - chatlog.record(session.account, session.room.name, `(not sent) ${said}`); - console.log(`[filter] ${session.name} in ${session.room.name}: "${said}" (${rule})`); + chatlog.record(session.account, session.room.name, `(not sent) ${line}`); + console.log(`[filter] ${logText(session.name)} in ${logText(session.room.name)}: "${logText(line)}" (${logText(rule)})`); return; } - session.recentChat.push(`${new Date().toISOString().slice(11, 19)} ${said}`); + session.recentChat.push(`${new Date().toISOString().slice(11, 19)} ${line}`); session.recentChat = session.recentChat.slice(-RECENT_CHAT_LINES); - chatlog.record(session.account, session.room.name, said); + chatlog.record(session.account, session.room.name, line); } // nobody hears a player they have blocked, and with chat switched // off nobody's typed lines arrive at all. + // an invisible staff member's emotes and the like reach staff only. for (const recipient of echo ? session.room.sessions : others(session)) { + if (session.invisible && recipient !== session && !roles.isActiveStaff(recipient.account)) { + continue; + } if (recipient === session || (!blocks.has(recipient.account, session.account) && (!echo || accounts.featureOn(recipient.account, "chat")))) { recipient.sendXt("uc", session.room.id, session.id, ...fields); } @@ -1493,7 +1701,7 @@ module.exports = { session.close(); return; default: - console.log(`[world] unhandled sys "${msg.action}" from ${session.name}`); + console.log(`[world] unhandled sys "${logText(msg.action)}" from ${logText(session.name)}`); } }, @@ -1559,6 +1767,9 @@ module.exports = { return true; }, moderation, + staffMove, + itemsTaken, + refreshStaff, walls, ecards, // called when the admin changed an account's badges: a name tag showing diff --git a/public/account.html b/public/account.html index 5b4e4a7..3346a0e 100644 --- a/public/account.html +++ b/public/account.html @@ -136,6 +136,14 @@ input:not([type="checkbox"]), textarea { width: 100%; } textarea { min-height: 110px; resize: vertical; } .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 12px; } + /* their own custom items: a card each, its picture on the left */ + .my-items { display: grid; gap: 10px; margin-top: 10px; } + .my-item { display: grid; grid-template-columns: 72px 1fr; gap: 12px; align-items: center; padding: 10px; border: 1px solid var(--line); border-radius: 14px; } + .my-item .art { width: 72px; height: 72px; border-radius: 10px; background: var(--raised, #1a1a1a); display: grid; place-items: center; overflow: hidden; color: var(--muted); font-size: 11px; text-align: center; } + .my-item .art img { max-width: 100%; max-height: 100%; image-rendering: auto; } + .my-item .row { margin-top: 6px; } + .my-item input[type="text"] { flex: 1; min-width: 140px; } + .my-item input[type="file"] { display: none; } .captcha { margin-top: 12px; } .tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; } .tile { padding: 12px 14px 11px; border: 1px solid var(--line); border-radius: 18px; } @@ -303,6 +311,14 @@ +
+

My items

+

+
+ +

+
+ +
+

Restrict items

+

Find any item, the game's or a custom one, by name or id, and lock it out of the item finder: players can no longer find it or take it there (staff still can).

+
+ + + +
+
    + +

    +
    @@ -463,6 +610,12 @@

    Timeline

      +
      @@ -533,6 +686,97 @@ + + +
      +

      Role permissions

      +

      What each role may do. A change counts at once, for staff playing too. Each staff member can also be given more, or less, on their account.

      +
      + + +
      +

      +

      What they did

      @@ -696,6 +949,7 @@

      + @@ -499,7 +753,7 @@ const REFRESH_MS = 8000; let signedIn = false; - let tab = "players"; + let tab = "home"; let selected = null; // the username of the player whose box is open let players = []; let chatQuery = null; // what the Chat page shows: {username, room, text} @@ -646,6 +900,7 @@ ["Ban", player.banned === 0 ? "—" : `${left(player.banned)} · ${player.banReason}`], ["Chat", player.silenced === 0 ? "—" : `Silenced: ${left(player.silenced).toLowerCase()}`], ["Reports waiting", String(player.openReports)], + ["Warnings", String(player.warnings || 0)], ["Stopped by the filter", `${player.stoppedThisWeek} in the last 7 days`], ["Hardware IDs", player.devicesKnown ? String(player.devicesKnown) : "None"], ["Paintings", String(player.paintings)], @@ -664,8 +919,52 @@ if (document.activeElement !== $("ban-reason")) { $("ban-reason").value = player.banned === 0 ? "" : player.banReason; } + renderNotes(player.notes || []); + renderMade(player); }; + // what they made in the Item Maker, for a report about one of its pictures + let uploadsStopped = false; + const renderMade = player => { + $("made-block").hidden = !permissions.has("items.approve"); + const made = player.madeItems || []; + $("no-made-items").hidden = made.length > 0; + $("made-items").replaceChildren(...made.map(item => { + const row = el("div", undefined, "made-item"); + const art = el("div", item.artUrl ? undefined : "No picture", "art"); + if (item.artUrl) { + art.append(guardedPicture(item.artUrl)); + } + const about = el("div"); + about.append(el("strong", item.name), el("div", `${item.kind === "den" ? "den item" : "clothing"} ${item.id}${item.artWaiting ? " · picture waiting for approval" : ""}`, "hint")); + row.append(art, about); + if (item.artUrl) { + row.append(button("Take picture off", async () => { + if (!confirm(`Take the picture off ${item.name}? It counts against ${player.username}.`)) { + return; + } + const result = await api("review", {action: "takePicture", kind: item.kind, id: item.id}); + setStatus($("detail-status"), said(result), !result.ok); + await loadDetail(); + }, "danger")); + } + return row; + })); + uploadsStopped = player.picturesStopped; + $("uploads-state").textContent = player.picturesStopped ? "Picture uploads: stopped." + : `Picture uploads: allowed (${player.pictureStrikes || 0} of 3 turned away).`; + $("uploads-toggle").textContent = player.picturesStopped ? "Let them upload again" : "Stop their picture uploads"; + $("uploads-toggle").className = player.picturesStopped ? "" : "danger"; + }; + $("uploads-toggle").addEventListener("click", async () => { + if (!selected) { + return; + } + const result = await api("review", {action: "uploads", username: selected, blocked: !uploadsStopped}); + setStatus($("detail-status"), said(result), !result.ok); + await loadDetail(); + }); + // the player's Jam-a-Grams or wall posts, sent and received // (lib/chatlog.js): asked with the rest of the extras, and a page more // with Older. "(not sent)" in front is one the filter stopped. @@ -735,12 +1034,45 @@ $("no-timeline").hidden = events.length > 0; }; + // mod notes (lib/modnotes.js): the newest first, each removable by its + // writer (or an admin). + const renderNotes = notes => { + $("player-notes").replaceChildren(...notes.map(note => { + const row = el("li"); + const head = el("div", `${when(note.at)} · ${note.by}`, "who"); + row.append(head, note.text); + head.append(button("Remove", async () => { + if (!confirm("Remove this note?")) { + return; + } + const result = await api("act", {username: selected, action: "deleteNote", id: note.id}); + setStatus($("detail-status"), said(result), !result.ok); + refresh(); + })); + return row; + })); + }; + $("note-add").addEventListener("click", async () => { + const text = $("note-text").value.trim(); + if (!text || !selected) { + return; + } + $("note-add").disabled = true; + const result = await api("act", {username: selected, action: "note", text}); + $("note-add").disabled = false; + setStatus($("detail-status"), said(result), !result.ok); + if (result.ok) { + $("note-text").value = ""; + refresh(); + } + }); + const select = username => { selected = username; hashArg = username || ""; setHash(); setStatus($("detail-status"), ""); - for (const id of ["ban-hours", "ban-reason", "silence-hours", "message-text"]) { + for (const id of ["ban-hours", "ban-reason", "silence-hours", "message-text", "warn-note", "note-text"]) { $(id).value = ""; } renderPlayers(); @@ -775,6 +1107,7 @@ case "banReason": case "banAddress": case "banDevices": return {reason: $("ban-reason").value}; case "silence": return {hours: numberFrom("silence-hours")}; case "message": return {text: $("message-text").value}; + case "warn": return {reason: $("warn-reason").value, note: $("warn-note").value}; default: return {}; } }; @@ -783,6 +1116,7 @@ banDevices: name => `Hardware ban ${name}? Everyone on their hardware is put out.`, 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?`, }; $("detail").addEventListener("click", async event => { @@ -837,11 +1171,15 @@ const placeOf = line => (line.kind === "whisper" ? `Whisper to ${line.to}` : line.kind === "jamagram" ? `Jam-a-Gram to ${line.to}` : line.kind === "wall" ? `On ${line.to}'s wall` : line.room); + // a line as typed, its emoji ("\{1f600}", as the game sends them) as themselves + const withEmoji = text => String(text).replace(/\\\{([0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9})\}/g, + (whole, hex) => String.fromCodePoint(...hex.split("-").map(part => parseInt(part, 16)))); + const lineNode = (line, inContext = false) => { const item = el("li", undefined, inContext && line.marked ? "this" : ""); const who = button(line.username, () => openPlayer(line.username), "chat-who"); const text = el("span", undefined, "chat-text"); - text.append(line.text || "(no words)", el("span", placeOf(line), "chat-room")); + text.append(withEmoji(line.text || "(no words)"), el("span", placeOf(line), "chat-room")); item.append(el("span", when(line.at), "chat-time"), who, text); if (!inContext) { item.append(button("Around", () => showContext(line.id), "chat-more")); @@ -1206,22 +1544,381 @@ $("no-filter-hits").hidden = list.length > 0; }; + // ---- items (lib/customitems.js) + let items = []; + let editing = null; // the item the form is changing, or null to make one + let baseColours = []; // the colours of the item looked up + + const showColours = (colours, chosen) => { + $("item-colours").replaceChildren(...colours.map((colour, index) => { + const box = el("input"); + box.type = "checkbox"; + box.value = String(colour); + box.checked = !chosen || chosen.includes(colour); + const label = el("label", undefined, "check"); + label.append(box, ` Colour ${index + 1}`); + return label; + })); + }; + + const lookUp = async () => { + const result = await api(`items/base?kind=${$("item-kind").value}&id=${encodeURIComponent($("item-base").value.trim())}`); + baseColours = result.ok && result.data.colors ? result.data.colors : []; + if (!result.ok) { + $("item-base-name").textContent = said(result); + showColours([]); + return null; + } + if (!editing) { + $("item-base-name").textContent = `${result.data.name || "(no name)"}: ${result.data.cost} gems in the game.`; + if (!$("item-name").value.trim()) { + $("item-name").value = result.data.name || ""; + } + showColours(baseColours); + } + return result.data; + }; + $("item-look").addEventListener("click", lookUp); + $("item-kind").addEventListener("change", () => { + $("item-base-name").textContent = ""; + showColours([]); + }); + + const itemForm = item => { + editing = item; + $("item-form-title").textContent = item ? `Change ${item.name}` : "Make an item"; + $("item-save").textContent = item ? "Save" : "Make it"; + $("item-cancel").hidden = !item; + for (const field of ["item-kind", "item-base", "item-look"]) { + $(field).disabled = Boolean(item); + } + if (item) { + $("item-kind").value = item.kind; + } + $("item-base").value = item ? item.base : ""; + $("item-name").value = item ? item.name : ""; + $("item-cost").value = item ? item.cost : ""; + $("item-members").checked = Boolean(item && item.members); + $("item-base-name").textContent = item ? `${item.baseName} (${item.kind === "den" ? "den item" : "clothing"} ${item.base})` : ""; + showColours([]); + if (item && item.kind === "clothing") { + // the base's colours, and any of the item's own that are not among them + lookUp().then(() => showColours([...new Set([...baseColours, ...item.colors])], item.colors)); + } + }; + $("item-cancel").addEventListener("click", () => itemForm(null)); + + $("item-save").addEventListener("click", async () => { + const fields = {name: $("item-name").value, cost: $("item-cost").value, members: $("item-members").checked}; + const boxes = [...$("item-colours").querySelectorAll("input")]; + if (boxes.length) { + fields.colors = boxes.filter(box => box.checked).map(box => Number(box.value)); + if (!fields.colors.length) { + setStatus($("item-status"), "Leave at least one colour.", true); + return; + } + } + $("item-save").disabled = true; + const result = await api("items", editing + ? {action: "update", kind: editing.kind, id: editing.id, ...fields} + : {action: "create", kind: $("item-kind").value, base: $("item-base").value.trim(), ...fields}); + $("item-save").disabled = false; + setStatus($("item-status"), said(result), !result.ok); + if (result.ok) { + itemForm(null); + refresh(); + } + }); + + const renderItems = () => { + $("items").replaceChildren(...items.map(item => { + const row = el("tr"); + const buttons = el("td"); + buttons.append(button("Change", () => itemForm(item)), " ", + button(item.inShop ? "Take off sale" : "Put on sale", async () => { + const result = await api("items", {action: "update", kind: item.kind, id: item.id, inShop: !item.inShop}); + setStatus($("item-status"), said(result), !result.ok); + await refresh(); + }), " ", + button(item.locked ? "Unlock" : "Lock", async () => { + const result = await api("items", {action: item.locked ? "unlock" : "lock", kind: item.kind, id: item.id}); + setStatus($("item-status"), said(result), !result.ok); + await refresh(); + }), " ", + button("Picture", () => pickPicture(item)), " ", + ...(item.artUrl && item.kind === "clothing" ? [button(item.artMode === "texture" ? "Worn: texture" : "Worn: sticker", async () => { + const result = await api("items", {action: "look", kind: item.kind, id: item.id, look: item.artMode === "texture" ? "sticker" : "texture"}); + setStatus($("item-status"), said(result), !result.ok); + await refresh(); + }), " "] : []), + ...(item.artUrl ? [button("Remove picture", () => sendPicture(item, null)), " "] : []), + button("Delete", async () => { + if (!confirm(`Delete ${item.name}? It goes from the game and from every player who has it. This cannot be undone.`)) { + return; + } + const result = await api("items", {action: "delete", kind: item.kind, id: item.id}); + setStatus($("item-status"), said(result), !result.ok); + await refresh(); + })); + const art = el("td"); + if (item.artUrl) { + const picture = el("img", undefined, "item-art"); + picture.src = item.artUrl; + picture.alt = ""; + art.append(picture); + } + else { + art.append(el("span", "—", "hint")); + } + row.append(art, el("td", String(item.id), "num"), el("td", `${item.name}${item.members ? " (members)" : ""}${item.ownerId ? " (a player's own)" : item.inShop ? "" : " (off sale)"}${item.locked ? " (locked)" : ""}`), + el("td", `${item.baseName} (${item.kind === "den" ? "den item" : "clothing"} ${item.base})`), el("td", String(item.cost), "num"), + el("td", item.createdBy), buttons); + return row; + })); + $("no-items").hidden = items.length > 0; + }; + + // an item's own picture (lib/itemart.js): chosen here, sent as it is + // a picture made ready to send (lib/itemart.js): as it is when the + // server takes it as it is (a PNG, JPEG or GIF small enough: a GIF keeps + // moving), else drawn into a PNG that fits, smaller until it is small + // enough. any picture this browser can open will do (WebP, AVIF, BMP...). + // null when it cannot be read at all. + const PICTURE_SIDE = 512; + const PICTURE_BYTES = 300 * 1024; + const preparePicture = async file => { + const kept = ["image/png", "image/jpeg", "image/gif"].includes(file.type); + let image = null; + try { + image = await createImageBitmap(file); + } + catch (err) { + return kept ? file : null; + } + if (kept && file.size <= PICTURE_BYTES && image.width <= PICTURE_SIDE && image.height <= PICTURE_SIDE) { + image.close(); + return file; + } + for (const side of [PICTURE_SIDE, 384, 256, 128]) { + const scale = Math.min(1, side / image.width, side / image.height); + const canvas = document.createElement("canvas"); + canvas.width = Math.max(1, Math.round(image.width * scale)); + canvas.height = Math.max(1, Math.round(image.height * scale)); + canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height); + const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/png")); + if (blob && blob.size <= PICTURE_BYTES) { + image.close(); + return blob; + } + } + image.close(); + return null; + }; + + const sendPicture = async (item, chosen) => { + const file = chosen ? await preparePicture(chosen) : null; + if (chosen && !file) { + setStatus($("item-status"), "That picture could not be read. Try a PNG, JPEG or GIF.", true); + return; + } + setStatus($("item-status"), file ? "Sending the picture..." : "Taking the picture away..."); + try { + const response = await fetch(`/mod/api/itemart?kind=${encodeURIComponent(item.kind)}&id=${encodeURIComponent(item.id)}${file ? "" : "&remove=1"}`, + {method: "POST", headers: {"Content-Type": "application/octet-stream"}, body: file || new Uint8Array(0)}); + const data = await response.json().catch(() => ({})); + setStatus($("item-status"), data.ok || data.error || "That did not work.", !data.ok); + } + catch (err) { + setStatus($("item-status"), "The server did not answer.", true); + } + refresh(); + }; + const pickPicture = item => { + const file = el("input"); + file.type = "file"; + file.accept = "image/*"; + file.addEventListener("change", () => file.files[0] && sendPicture(item, file.files[0])); + file.click(); + }; + + // ---- the dashboard's item lock: any item by name or id, locked or + // unlocked where it is found (the Items page lists every locked one). + let quickLockTimer = null; + let quickLockAsked = 0; + const quickLockFind = async () => { + const query = $("quick-lock-q").value.trim(); + const asked = ++quickLockAsked; + const result = await api(`items/find?q=${encodeURIComponent(query)}&kind=${$("quick-lock-kind").value}`); + if (asked !== quickLockAsked || !result.ok) { + return; + } + const {results, total, lockedCount} = result.data; + $("lock-count").textContent = lockedCount === 1 ? "1 item is locked now." : `${lockedCount} items are locked now.`; + const shown = query ? results : []; + $("quick-lock-results").replaceChildren(...shown.map(item => { + const row = el("li"); + row.append(el("span", item.name || "(no name)"), + el("span", `${item.kind === "den" ? "den item" : "clothing"} ${item.id}${item.custom ? ", custom" : ""}`, "meta")); + if (item.locked) { + row.append(el("span", "locked", "is-locked")); + } + row.append(button(item.locked ? "Unlock" : "Lock", async () => { + const changed = await api("items", {action: item.locked ? "unlock" : "lock", kind: item.kind, id: item.id}); + setStatus($("quick-lock-status"), said(changed), !changed.ok); + await quickLockFind(); + }, item.locked ? undefined : "primary")); + return row; + })); + $("quick-lock-more").hidden = !query || (results.length > 0 && total <= results.length); + $("quick-lock-more").textContent = results.length === 0 ? "No item matches." + : `${total} items match; these are the first ${results.length}. Type more of the name.`; + }; + $("quick-lock-q").addEventListener("input", () => { + clearTimeout(quickLockTimer); + quickLockTimer = setTimeout(quickLockFind, 250); + }); + $("quick-lock-kind").addEventListener("change", quickLockFind); + $("quick-lock-all").addEventListener("click", () => showTab("items")); + + // ---- locks and taking items (lib/itemcontrol.js) + let lockedItems = []; + const renderLocked = () => { + $("locked-items").replaceChildren(...lockedItems.map(entry => { + const row = el("li", `${entry.name || "(no name)"} (${entry.kind === "den" ? "den item" : "clothing"} ${entry.id}) `); + row.append(button("Unlock", async () => { + const result = await api("items", {action: "unlock", kind: entry.kind, id: entry.id}); + setStatus($("control-status"), said(result), !result.ok); + await refresh(); + })); + return row; + })); + $("no-locked").hidden = lockedItems.length > 0; + }; + $("lock-add").addEventListener("click", async () => { + const result = await api("items", {action: "lock", kind: $("lock-kind").value, id: $("lock-id").value.trim()}); + setStatus($("control-status"), said(result), !result.ok); + if (result.ok) { + $("lock-id").value = ""; + await refresh(); + } + }); + $("take-go").addEventListener("click", async () => { + const name = $("take-name").value.trim(); + const id = $("take-id").value.trim(); + if (!name || !id || !confirm(`Take every ${$("take-kind").value === "den" ? "den item" : "clothing item"} ${id} from ${name}?`)) { + return; + } + const result = await api("items", {action: "take", username: name, kind: $("take-kind").value, id}); + setStatus($("control-status"), said(result), !result.ok); + }); + + // pictures players upload are blurred till a moderator chooses to look: + // one that is gore need not be seen whole to be turned away. + const revealed = new Set(); // pictures shown, by address (kept over refreshes) + const guardedPicture = src => { + const picture = el("img", undefined, revealed.has(src) ? "guarded shown" : "guarded"); + picture.src = src; + picture.alt = ""; + picture.title = revealed.has(src) ? "" : "Click to show"; + picture.addEventListener("click", () => { + revealed.add(src); + picture.classList.add("shown"); + picture.title = ""; + }); + return picture; + }; + + // ---- what players made that waits for approval (lib/playeritems.js) + const renderReview = data => { + const waiting = data.waiting || []; + $("no-review").hidden = waiting.length > 0; + $("review-list").replaceChildren(...waiting.map(entry => { + const card = el("div", undefined, "review-card"); + const art = el("div", entry.artUrl ? undefined : "No picture", "art"); + if (entry.artUrl) { + art.append(guardedPicture(entry.artUrl)); + } + const about = el("div"); + about.append(el("strong", entry.name), el("div", `${entry.waiting === "item" ? "A new item" : "A new picture"} · ${entry.kind === "den" ? "den item" : "clothing"} from ${entry.baseName}`, "hint"), + 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 () => { + const result = await api("review", {kind: entry.kind, id: entry.id, approve}); + setStatus($("review-status"), said(result), !result.ok); + await refresh(); + }; + buttons.append(button("Approve", decide(true), "primary"), button("Turn away", decide(false), "danger")); + card.append(art, about, buttons); + return card; + })); + const stopped = data.stopped || []; + $("no-stopped").hidden = stopped.length > 0; + $("stopped-list").replaceChildren(...stopped.map(username => { + const row = el("li", `${username} `); + row.append(button("Let them upload again", async () => { + const result = await api("review", {action: "uploads", username, blocked: false}); + setStatus($("review-status"), said(result), !result.ok); + await refresh(); + })); + return row; + })); + }; + $("stop-go").addEventListener("click", async () => { + const username = $("stop-name").value.trim(); + if (!username) { + return; + } + const result = await api("review", {action: "uploads", username, blocked: true}); + setStatus($("review-status"), said(result), !result.ok); + if (result.ok) { + $("stop-name").value = ""; + } + await refresh(); + }); + + let permissions = new Set(); // what the signed-in role may do (GET /mod/api/me) + const refresh = async () => { clearTimeout(timer); if (!signedIn) { return; } const shown = tab; - const counts = await api("overview"); + const counts = permissions.has("player.view") ? await api("overview") : {ok: false}; if (counts.ok) { - $("report-count").textContent = counts.data.reports ? ` (${counts.data.reports})` : ""; - $("request-count").textContent = counts.data.requests ? ` (${counts.data.requests})` : ""; - $("masterpiece-count").textContent = counts.data.paintings ? ` (${counts.data.paintings})` : ""; + $("report-count").textContent = counts.data.reports ? String(counts.data.reports) : ""; + $("request-count").textContent = counts.data.requests ? String(counts.data.requests) : ""; + $("masterpiece-count").textContent = counts.data.paintings ? String(counts.data.paintings) : ""; $("online-count").textContent = `${counts.data.online} playing`; + $("home-online").textContent = String(counts.data.online); + $("home-reports").textContent = String(counts.data.reports); + $("home-requests").textContent = String(counts.data.requests); + $("home-paintings").textContent = String(counts.data.paintings); + for (const [id, count] of [["home-reports", counts.data.reports], ["home-requests", counts.data.requests], ["home-paintings", counts.data.paintings]]) { + $(id).closest(".tile").classList.toggle("attention", count > 0); + } // what waits, in the page's title too, for when it is in another tab. const waiting = counts.data.reports + counts.data.requests + counts.data.paintings; document.title = waiting ? `(${waiting}) Moderators` : "Moderators"; } + if (shown === "home") { + if (permissions.has("items.create") && !$("quick-lock-q").value.trim()) { + quickLockFind(); + } + const result = await api("notes"); + const notes = result.ok ? result.data.notes : []; + $("home-notes").replaceChildren(...notes.map(note => { + const row = el("li"); + const head = el("div", undefined, "who"); + const about = el("button", note.about, "about"); + about.type = "button"; + about.addEventListener("click", () => openPlayer(note.about)); + head.append(about, `${when(note.at)} · by ${note.by}`); + row.append(head, note.text); + return row; + })); + $("no-home-notes").hidden = notes.length > 0; + } // out of sight, only the counts (for the title); the rest when it is back. if (document.hidden) { timer = setTimeout(refresh, REFRESH_MS); @@ -1288,6 +1985,21 @@ renderFilterHits(hits.data.players); } } + else if (shown === "review") { + const result = await api("review"); + if (result.ok) { + renderReview(result.data); + } + } + else if (shown === "items") { + const result = await api("items"); + if (result.ok) { + items = result.data.items; + lockedItems = result.data.locked; + renderItems(); + renderLocked(); + } + } if (signedIn) { clearTimeout(timer); timer = setTimeout(refresh, REFRESH_MS); @@ -1337,6 +2049,9 @@ const showTab = name => { tab = name; setHash(); + const named = document.querySelector(`nav button[data-tab="${name}"]`); + // the tab's own words: not its icon, nor its count + $("page-name").textContent = named ? [...named.childNodes].filter(node => node.nodeType === 3).map(node => node.textContent).join("").trim() : ""; for (const one of document.querySelectorAll("nav button")) { one.setAttribute("aria-selected", String(one.dataset.tab === name)); } @@ -1351,20 +2066,79 @@ showTab(one.dataset.tab); }); } + // the dashboard: each number opens its page; the search opens a player + for (const tile of document.querySelectorAll("[data-goto]")) { + tile.addEventListener("click", () => showTab(tile.dataset.goto)); + } + const homeFind = () => { + const name = $("home-search").value.trim(); + if (name) { + openPlayer(name); + } + }; + $("home-search-go").addEventListener("click", homeFind); + $("home-search").addEventListener("keydown", event => { + if (event.key === "Enter") { + homeFind(); + } + }); document.addEventListener("visibilitychange", () => { if (!document.hidden) { refresh(); } }); + // the permission (lib/roles.js) each button needs: one the signed-in + // role does not hold is not shown. the server checks again either way. + const ACTION_PERMISSIONS = { + ban: "player.ban", banReason: "player.ban", unban: "player.ban", + 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", + }; + const applyPermissions = async () => { + const result = await api("me"); + if (!result.ok) { + return; + } + const allowed = new Set(result.data.permissions || []); + permissions = allowed; + for (const pressed of document.querySelectorAll("button[data-action]")) { + const needed = ACTION_PERMISSIONS[pressed.dataset.action]; + pressed.hidden = Boolean(needed) && !allowed.has(needed); + } + // the pages the role may see; the first of them when the one open is not. + const pages = [...document.querySelectorAll("nav button")]; + for (const page of pages) { + page.hidden = !allowed.has(page.dataset.needs); + } + // searching by address: for the roles that ban addresses + const byAddress = document.querySelector('#player-search-by option[value="address"]'); + byAddress.hidden = byAddress.disabled = !allowed.has(byAddress.dataset.needs); + if (byAddress.disabled && $("player-search-by").value === "address") { + $("player-search-by").value = "name"; + } + $("quick-lock").hidden = !allowed.has("items.create"); + const open = pages.find(page => page.dataset.tab === tab && !page.hidden) || pages.find(page => !page.hidden); + if (open) { + tab = open.dataset.tab; + } + if (result.data.role) { + $("who").textContent = `${result.data.username} (${result.data.role})`; + } + }; + const showPanel = username => { signedIn = true; $("who").textContent = username; $("gate").hidden = true; $("panel").hidden = false; - if (!applyHash()) { - showTab(tab); - } + applyPermissions().then(() => { + if (!applyHash()) { + showTab(tab); + } + }); }; $("gate-form").addEventListener("submit", async event => { diff --git a/public/register.html b/public/register.html index 1572d5d..a104179 100644 --- a/public/register.html +++ b/public/register.html @@ -234,6 +234,7 @@ username_taken: "That username is already taken.", name_not_allowed: "That username is not allowed.", invalid_password: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit.", + weak_password: "That password is too easy to guess: it is a common one, or has your username in it.", choose_animal: "Choose an animal first.", too_many_registrations: "Too many accounts were created from your address. Try again in an hour.", address_banned: "Your address is banned.", diff --git a/server.js b/server.js index 034a2c6..62af94a 100644 --- a/server.js +++ b/server.js @@ -10,6 +10,7 @@ const chatlog = require("./lib/chatlog.js"); const modlog = require("./lib/modlog.js"); const retention = require("./lib/retention.js"); const colours = require("./lib/colours.js"); +const customItems = require("./lib/customitems.js"); const config = require("./config.js"); const defpacks = require("./lib/defpacks.js"); const http = require("./lib/http.js"); @@ -38,6 +39,7 @@ const main = async () => { fs.chmodSync(config.dataDir, 0o700); accounts.startBackups(); colours.load(); + customItems.load(); reports.load(); support.load(); bans.load(); diff --git a/swf-src/AJClient.as b/swf-src/AJClient.as index 047cf79..d4fb25d 100644 --- a/swf-src/AJClient.as +++ b/swf-src/AJClient.as @@ -7,12 +7,17 @@ package import den.DenXtCommManager; import item.ItemXtCommManager; import den.DenItem; + import den.DenXtCommManager; import item.Item; + import item.ItemXtCommManager; import com.sbi.loader.ResourceStack; import com.sbi.popup.SBOkPopup; import com.sbi.popup.SBStandardPopup; import com.sbi.popup.SBYesNoPopup; import createAccountFlow.CreateAccount; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.display.Loader; import flash.display.MovieClip; import flash.display.Shape; import flash.display.DisplayObject; @@ -20,10 +25,13 @@ package import flash.events.Event; import flash.geom.ColorTransform; import flash.geom.Matrix; + import flash.utils.ByteArray; import flash.geom.Point; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TimerEvent; + import flash.net.FileFilter; + import flash.net.FileReference; import flash.net.URLLoader; import flash.net.URLRequest; import flash.text.Font; @@ -32,6 +40,7 @@ package import flash.events.UncaughtErrorEvent; import flash.external.ExternalInterface; import flash.system.Capabilities; + import flash.system.LoaderContext; import flash.system.Security; import flash.system.System; import flash.ui.Mouse; @@ -42,6 +51,8 @@ package import gamePlayFlow.GamePlay; import gskinner.motion.GTween; import gui.DarkenManager; + import gui.ChatBalloon; + import gui.EmoticonUtility; import gui.GuiManager; import loadProgress.LoadProgress; import loader.DefPacksDefHelper; @@ -89,6 +100,28 @@ package private var _finderKind:int; private var _finderColourInput:TextField; + + // the staff's window for one player (openModerate), and what the + // signed-in role may do ("xsp" from the server; empty for players). + private var _moderate:Sprite; + + private var _moderateContent:Sprite; + + private var _moderateTitle:TextField; + + private var _moderateName:String; + + private var _moderateReason:int; + + private var _moderateInput:TextField; + + private var _moderateHint:TextField; + + private var _moderateButtons:Array; + + public static var staffRole:String = ""; + + public static var staffPermissions:Array = []; // the items drawn on the rows shown, by row number private var _finderIcons:Object = {}; @@ -285,6 +318,7 @@ package } gMainFrame.stage.addEventListener("keyDown",onFinderKey,true,1000); gMainFrame.stage.addEventListener("keyDown",onFinderKey,false,1000); + startEmojiButton(); } public static function openTool(param1:int) : void @@ -299,6 +333,10 @@ package { _toolsInstance.showChatFilter(true); } + else if(param1 == 2) + { + _toolsInstance.showItemMaker(true); + } else { _toolsInstance.showItemFinder(true); @@ -491,12 +529,408 @@ package return _loc6_; } + // "xdi": [.., .., kind, rows as JSON]. items the staff made while the + // game runs (the server's lib/customitems.js): "clothing" or "den" def + // rows, as in the item packs, each with its name. + public static function onItemDefs(param1:Object) : void + { + try + { + var _loc2_:Array = JSON.parse(String(param1[3])) as Array; + for each(var _loc3_:Object in _loc2_) + { + // a picture of its own (uploaded by its maker): its version + if(_loc3_.art) + { + _customArt[String(param1[2]) + ":" + _loc3_.id] = String(_loc3_.art); + _customArtMode[String(param1[2]) + ":" + _loc3_.id] = _loc3_.artMode == "texture" ? "texture" : "sticker"; + } + else + { + delete _customArt[String(param1[2]) + ":" + _loc3_.id]; + delete _customArtMode[String(param1[2]) + ":" + _loc3_.id]; + } + } + if(String(param1[2]) == "den") + { + DenXtCommManager.addDenItemDefs(_loc2_); + } + else + { + ItemXtCommManager.addItemDefs(_loc2_); + } + } + catch(e:Error) + { + GlobalErrorCatch.reportToServer("item defs: " + e + "\n" + e.getStackTrace()); + } + } + + // custom items' own pictures (lib/itemart.js on the server): "kind:id" + // -> version, from the def rows ("xdi"). the picture stands in for the + // item's icon, and for a den item also for the item placed in a den. + private static var _customArt:Object = {}; + + // how a custom clothing item with a picture is worn ("artMode" in its + // def row): "sticker", the picture itself where the item would be, or + // "texture", the item's own shape painted with the picture. + private static var _customArtMode:Object = {}; + + // the pictures as bitmaps, for wearing: "kind:id" -> {bmp, art, waiting} + private static var _artBitmaps:Object = {}; + + // the look a worn item has, or null for one drawn as the game draws it + public static function customArtMode(param1:String, param2:int) : String + { + return _customArt[param1 + ":" + param2] == null ? null : _customArtMode[param1 + ":" + param2]; + } + + // what makes a painted frame of it different from its base's, for a + // cache key ("" for none) + public static function customArtKey(param1:String, param2:int) : String + { + var _loc3_:String = _customArt[param1 + ":" + param2]; + return _loc3_ == null ? "" : param2 + ":" + _loc3_ + ":" + _customArtMode[param1 + ":" + param2]; + } + + // the picture as a bitmap, or null while it loads (then `param3`, an + // object with invalidate(), is told when it has: it paints again). + public static function customArtBitmap(param1:String, param2:int, param3:Object = null) : BitmapData + { + var _loc4_:String = param1 + ":" + param2; + var _loc5_:String = _customArt[_loc4_]; + var _loc6_:Object = _artBitmaps[_loc4_]; + if(_loc5_ == null) + { + return null; + } + if(_loc6_ != null && _loc6_.art == _loc5_) + { + if(_loc6_.bmp == null && param3 != null && _loc6_.waiting.indexOf(param3) == -1) + { + _loc6_.waiting.push(param3); + } + return _loc6_.bmp; + } + _loc6_ = _artBitmaps[_loc4_] = {"bmp":null,"art":_loc5_,"waiting":param3 != null ? [param3] : []}; + var _loc7_:Loader = new Loader(); + var _loc8_:Object = _loc6_; + _loc7_.contentLoaderInfo.addEventListener("complete",function(param1:Event):void + { + if(_loc7_.content is Bitmap) + { + _loc8_.bmp = Bitmap(_loc7_.content).bitmapData; + } + for each(var _loc2_:Object in _loc8_.waiting) + { + try + { + if("artArrived" in _loc2_) + { + _loc2_.artArrived(); + } + else + { + _loc2_.invalidate(); + } + } + catch(e:Error) + { + } + } + _loc8_.waiting = []; + }); + _loc7_.contentLoaderInfo.addEventListener("ioError",function(param1:Event):void + { + _loc8_.waiting = []; + }); + // its pixels are read (worn as a sticker or a texture): from another + // address that takes the server's /crossdomain.xml + _loc7_.load(new URLRequest(customArtUrl(param1,param2)),new LoaderContext(true)); + return null; + } + + // the picture's address, or null when the item has none. + public static function customArtUrl(param1:String, param2:int) : String + { + var _loc3_:String = _customArt[param1 + ":" + param2]; + return _loc3_ == null ? null : gMainFrame.clientInfo.websiteURL + "itemart/" + param1 + "/" + param2 + ".png?v=" + encodeURIComponent(_loc3_); + } + + // loads a picture into `param2`, fitted in a `param3` square: centred on + // its origin, or (`param4`) standing on it, as a den item does. then + // `param5`, if any. a picture that does not load leaves it empty. + // pictures loadArt has loaded, by address, drawn again from these + // rather than fetched and decoded again: emoji in chat bubbles, items' + // icons in long lists. those asked for while one loads wait for it. + // past ART_CACHE_MAX pictures it starts afresh (a picture shown keeps + // its own). + private static const ART_CACHE_MAX:int = 400; + + private static var _artCache:Object = {}; + + private static var _artCacheCount:int = 0; + + private static var _artLoading:Object = {}; + + public static function loadArt(param1:String, param2:Sprite, param3:int, param4:Boolean, param5:Function = null) : void + { + var url:String = param1; + var place:Function = function(param1:BitmapData):void + { + var _loc2_:Bitmap = null; + var _loc3_:Number = NaN; + if(param1 != null) + { + _loc2_ = new Bitmap(param1,"auto",true); + _loc3_ = Math.min(1,param3 / Math.max(1,param1.width),param3 / Math.max(1,param1.height)); + _loc2_.scaleX = _loc2_.scaleY = _loc3_; + _loc2_.x = -int(param1.width * _loc3_ * 0.5); + _loc2_.y = param4 ? -int(param1.height * _loc3_) : -int(param1.height * _loc3_ * 0.5); + param2.addChild(_loc2_); + } + if(param5 != null) + { + param5(); + } + }; + if(_artCache[url] != null) + { + place(_artCache[url]); + return; + } + if(_artLoading[url] != null) + { + _artLoading[url].push({"place":place,"sprite":param2,"side":param3,"standing":param4,"then":param5}); + return; + } + _artLoading[url] = []; + var shared:Loader = new Loader(); + var loaded:Function = function(param1:Event):void + { + var _loc2_:BitmapData = null; + var _loc3_:Array = _artLoading[url]; + shared.contentLoaderInfo.removeEventListener("complete",loaded); + shared.contentLoaderInfo.removeEventListener("ioError",notLoaded); + delete _artLoading[url]; + try + { + _loc2_ = shared.content is Bitmap ? Bitmap(shared.content).bitmapData : null; + } + catch(e:Error) + { + _loc2_ = null; + } + if(_loc2_ == null) + { + // not to be shared (another site's, without its leave): each + // has a loader of its own, as before + loadArtUncached(url,param2,param3,param4,param5); + for each(var _loc4_:Object in _loc3_) + { + loadArtUncached(url,_loc4_.sprite,_loc4_.side,_loc4_.standing,_loc4_.then); + } + return; + } + if(_artCacheCount >= ART_CACHE_MAX) + { + _artCache = {}; + _artCacheCount = 0; + } + _artCache[url] = _loc2_; + _artCacheCount++; + place(_loc2_); + for each(var _loc5_:Object in _loc3_) + { + _loc5_.place(_loc2_); + } + }; + var notLoaded:Function = function(param1:Event):void + { + var _loc2_:Array = _artLoading[url]; + shared.contentLoaderInfo.removeEventListener("complete",loaded); + shared.contentLoaderInfo.removeEventListener("ioError",notLoaded); + delete _artLoading[url]; + place(null); + for each(var _loc3_:Object in _loc2_) + { + _loc3_.place(null); + } + }; + shared.contentLoaderInfo.addEventListener("complete",loaded); + shared.contentLoaderInfo.addEventListener("ioError",notLoaded); + shared.load(new URLRequest(url),new LoaderContext(true)); + } + + private static function loadArtUncached(param1:String, param2:Sprite, param3:int, param4:Boolean, param5:Function = null) : void + { + var _loc6_:Loader = new Loader(); + var done:Function = function(param1:Event):void + { + var _loc2_:Number = NaN; + _loc6_.contentLoaderInfo.removeEventListener("complete",done); + _loc6_.contentLoaderInfo.removeEventListener("ioError",failed); + if(_loc6_.content is Bitmap) + { + Bitmap(_loc6_.content).smoothing = true; + } + _loc2_ = Math.min(1,param3 / Math.max(1,_loc6_.contentLoaderInfo.width),param3 / Math.max(1,_loc6_.contentLoaderInfo.height)); + _loc6_.scaleX = _loc6_.scaleY = _loc2_; + _loc6_.x = -int(_loc6_.contentLoaderInfo.width * _loc2_ * 0.5); + _loc6_.y = param4 ? -int(_loc6_.contentLoaderInfo.height * _loc2_) : -int(_loc6_.contentLoaderInfo.height * _loc2_ * 0.5); + param2.addChild(_loc6_); + if(param5 != null) + { + param5(); + } + }; + var failed:Function = function(param1:Event):void + { + _loc6_.contentLoaderInfo.removeEventListener("complete",done); + _loc6_.contentLoaderInfo.removeEventListener("ioError",failed); + if(param5 != null) + { + param5(); + } + }; + _loc6_.contentLoaderInfo.addEventListener("complete",done); + _loc6_.contentLoaderInfo.addEventListener("ioError",failed); + _loc6_.load(new URLRequest(param1)); + } + + // "xsp": [.., .., role, permissions]. sent at login to staff only: their + // role and what it allows, comma separated (the server's lib/roles.js). + public static function onStaff(param1:Object) : void + { + staffRole = String(param1[2]); + staffPermissions = String(param1[3]).length > 0 ? String(param1[3]).split(",") : []; + } + + public static function staffMay(param1:String) : Boolean + { + return staffPermissions.indexOf(param1) != -1; + } + + // whether a player's card offers the staff's window instead of a report. + public static function canModerate() : Boolean + { + return _toolsInstance != null && (staffMay("player.warn") || staffMay("player.kick") || staffMay("chat.silence") || staffMay("player.summon") || staffMay("player.goto")); + } + + public static function openModerate(param1:String) : void + { + if(_toolsInstance == null) + { + return; + } + try + { + _toolsInstance.showModerate(param1); + } + catch(e:Error) + { + GlobalErrorCatch.reportToServer("moderate: " + e + "\n" + e.getStackTrace()); + } + } + // "xtl": [.., .., text]. A plain message box; what a chat command says. public static function showMessage(param1:Object) : void { new SBOkPopup(GuiManager.guiLayer,String(param1[2])); } + // "xgt": [.., .., x, y, same room]: staff moving a player (summon, + // goto) puts them on that spot: now when in the room already ("1"), + // else on spawning in the room they are sent to next ("0"). with no + // spot, the one kept is forgotten (the move failed). + public static function onStaffGoto(param1:Object) : void + { + var _loc2_:RoomManagerWorld = RoomManagerWorld.instance; + if(_loc2_ == null) + { + return; + } + if(param1.length < 5) + { + _loc2_.setGotoSpawnPoint("default"); + return; + } + if(String(param1[4]) == "1") + { + _loc2_.teleportPlayer(int(param1[2]),int(param1[3]),true); + } + else + { + _loc2_.setGotoSpawnLocation(int(param1[2]),int(param1[3])); + } + } + + // whether this player is invisible staff (lib/world.js setInvisible), + // for the staff window's button. + public static var staffInvisible:Boolean = false; + + // "xiv": [.., .., sfsId, 1 | 0]: an animal of invisible staff, which + // only staff are shown, drawn half see-through (this player's own too). + public static function onInvisible(param1:Object) : void + { + var _loc2_:int = int(param1[2]); + var _loc3_:Boolean = String(param1[3]) == "1"; + var _loc4_:AvatarWorldView = AvatarManager.avatarViewList != null ? AvatarManager.avatarViewList[_loc2_] as AvatarWorldView : null; + if(_loc2_ == AvatarManager.playerSfsUserId) + { + staffInvisible = _loc3_; + } + if(_loc4_ != null) + { + _loc4_.alpha = _loc3_ ? 0.5 : 1; + } + } + + // typing (lib/world.js xty): this player's chat box says so as it + // changes (gui.ChatHistory), again every TYPING_RESEND ms while it goes + // on, and once when it is emptied; a line sent counts as stopping. + private static const TYPING_RESEND:int = 4000; + + private static var _typingSent:Boolean = false; + + private static var _typingSentAt:int = 0; + + public static function noteTyping(param1:String) : void + { + var _loc2_:Boolean = param1 != null && param1.replace(/\s+/g,"").length > 0; + if(gMainFrame.clientInfo.invisMode || staffInvisible) + { + return; + } + if(_loc2_ && (!_typingSent || getTimer() - _typingSentAt > TYPING_RESEND)) + { + gMainFrame.server.setXtObject_Str("xty",[1]); + _typingSent = true; + _typingSentAt = getTimer(); + } + else if(!_loc2_ && _typingSent) + { + gMainFrame.server.setXtObject_Str("xty",[0]); + _typingSent = false; + } + } + + // a line was sent: every other game drops the "..." when it arrives. + public static function typingSent() : void + { + _typingSent = false; + } + + // "xty": [.., .., sfsId, 1 | 0]: another player typing, or not. + public static function onTyping(param1:Object) : void + { + var _loc2_:AvatarWorldView = AvatarManager.avatarViewList != null ? AvatarManager.avatarViewList[int(param1[2])] as AvatarWorldView : null; + if(_loc2_ != null && int(param1[2]) != AvatarManager.playerSfsUserId) + { + _loc2_.setTyping(String(param1[3]) == "1"); + } + } + // "xyn": [.., .., id, text]. A yes-or-no box; the answer goes back as // "xyn" [id, 1 | 0]. public static function askYesNo(param1:Object) : void @@ -1953,7 +2387,1298 @@ package param1.stopPropagation(); showItemFinder(false); } - + + // ---- the staff's window for one player, from the report button of + // their card. each button is a staff command for that player ("xmd", + // which the server runs as if typed: lib/commands.js, its permission + // checks and log included); only the ones the role allows are shown. + // the window closes and the server's answer comes as a message box. + // a warning's reason, as the server knows it, and its chip. with text + // in the box, Warn sends that text as the warning ("custom": what the + // player is shown) and the reason is not used. + private static const MODERATE_REASONS:Array = ["behavior","bullying","personal","scamming"]; + + private static const MODERATE_REASON_NAMES:Array = ["Behavior","Bullying","Personal info","Scamming"]; + + // the window's look: flat, dark, rounded, in the game's font. + private static const MOD_W:int = 560; + + private static const MOD_H:int = 432; + + private static const MOD_PAD:int = 24; + + private static const MOD_BG:uint = 0x1C1D24; + + private static const MOD_EDGE:uint = 0x34364A; + + private static const MOD_FIELD:uint = 0x272934; + + private static const MOD_MUTED:uint = 0x9A9DB0; + + private static const MOD_GREY:uint = 0x3A3D4E; + + private static const MOD_AMBER:uint = 0xE0A030; + + private static const MOD_BLUE:uint = 0x3D7BF0; + + private static const MOD_PURPLE:uint = 0x8B5CF6; + + private static const MOD_TEAL:uint = 0x14A38B; + + private static const MOD_RED:uint = 0xE0475B; + + // text in the game's font (embedded when the game has it). + public static function modText(param1:String, param2:int, param3:uint, param4:Boolean = true) : TextField + { + var _loc5_:TextField = new TextField(); + _loc5_.embedFonts = hasGameFont(); + _loc5_.selectable = false; + _loc5_.mouseEnabled = false; + _loc5_.autoSize = "left"; + _loc5_.defaultTextFormat = new TextFormat("CCDigitalDelivery",param2,param3,param4); + _loc5_.text = param1; + return _loc5_; + } + + // a flat button: a rounded box of colour `param6`, its label centred. + private function modButton(param1:String, param2:String, param3:Number, param4:Number, param5:Number, param6:uint, param7:String) : Sprite + { + var _loc8_:Sprite = new Sprite(); + _loc8_.name = param1; + _loc8_.x = param3; + _loc8_.y = param4; + _loc8_.buttonMode = true; + _loc8_.useHandCursor = true; + _loc8_.mouseChildren = false; + var _loc9_:TextField = modText(param2,14,0xFFFFFF); + _loc9_.name = "label"; + _loc8_.addChild(_loc9_); + paintFlatButton(_loc8_,param5,param6); + _loc8_.addEventListener("mouseDown",onModerateButton); + _loc8_.addEventListener("mouseOver",onFlatHover); + _loc8_.addEventListener("mouseOut",onFlatHover); + _moderateContent.addChild(_loc8_); + _moderateButtons.push({ + "clip":_loc8_, + "permission":param7 + }); + return _loc8_; + } + + // draws a flat button `param2` wide in colour `param3`, its label + // ("label") centred in it. also for the settings menu's own windows. + public static function paintFlatButton(param1:Sprite, param2:Number, param3:uint) : void + { + var _loc4_:TextField = param1.getChildByName("label") as TextField; + param1.graphics.clear(); + param1.graphics.beginFill(param3); + param1.graphics.drawRoundRect(0,0,param2,34,14,14); + param1.graphics.endFill(); + if(_loc4_ != null) + { + _loc4_.x = int((param2 - _loc4_.width) * 0.5); + _loc4_.y = int((34 - _loc4_.height) * 0.5); + } + } + + private static function modSetLabel(param1:Sprite, param2:String) : void + { + var _loc3_:TextField = param1.getChildByName("label") as TextField; + var _loc4_:Number = param1.width; + _loc3_.text = param2; + _loc3_.x = int((_loc4_ - _loc3_.width) * 0.5); + } + + public static function onFlatHover(param1:MouseEvent) : void + { + Sprite(param1.currentTarget).alpha = param1.type == "mouseOver" ? 0.82 : 1; + } + + private function modSection(param1:String, param2:Number) : void + { + var _loc3_:TextField = modText(param1.toUpperCase(),11,MOD_MUTED); + _loc3_.x = MOD_PAD; + _loc3_.y = param2; + _moderateContent.addChild(_loc3_); + } + + private function buildModerate() : void + { + var _loc1_:Number = (MOD_W - MOD_PAD * 2 - 20) / 3; // a column's width + var _loc2_:Array = [MOD_PAD,MOD_PAD + _loc1_ + 10,MOD_PAD + (_loc1_ + 10) * 2]; + var _loc3_:Sprite = null; + var _loc4_:Number = MOD_PAD; + var _loc5_:int = 0; + _moderate = new Sprite(); + _moderate.graphics.beginFill(0,0.55); + _moderate.graphics.drawRect(0,0,900,550); + _moderate.graphics.endFill(); + _moderateContent = new Sprite(); + _moderateContent.x = int((900 - MOD_W) * 0.5); + _moderateContent.y = int((550 - MOD_H) * 0.5); + // a soft shadow, then the panel + _moderateContent.graphics.beginFill(0,0.35); + _moderateContent.graphics.drawRoundRect(0,6,MOD_W,MOD_H,26,26); + _moderateContent.graphics.endFill(); + _moderateContent.graphics.lineStyle(1,MOD_EDGE); + _moderateContent.graphics.beginFill(MOD_BG); + _moderateContent.graphics.drawRoundRect(0,0,MOD_W,MOD_H,26,26); + _moderateContent.graphics.endFill(); + _moderate.addChild(_moderateContent); + _moderateButtons = []; + _moderateTitle = modText("",22,0xFFFFFF); + _moderateTitle.x = MOD_PAD; + _moderateTitle.y = 18; + _moderateContent.addChild(_moderateTitle); + var _loc6_:TextField = modText("Everything here is logged under your name.",12,MOD_MUTED,false); + _loc6_.x = MOD_PAD; + _loc6_.y = 50; + _moderateContent.addChild(_loc6_); + // the close button: a round grey X + _loc3_ = new Sprite(); + _loc3_.name = "close"; + _loc3_.buttonMode = true; + _loc3_.useHandCursor = true; + _loc3_.graphics.beginFill(MOD_GREY); + _loc3_.graphics.drawCircle(0,0,15); + _loc3_.graphics.endFill(); + _loc3_.graphics.lineStyle(2.5,0xFFFFFF); + _loc3_.graphics.moveTo(-5,-5); + _loc3_.graphics.lineTo(5,5); + _loc3_.graphics.moveTo(5,-5); + _loc3_.graphics.lineTo(-5,5); + _loc3_.x = MOD_W - MOD_PAD - 6; + _loc3_.y = 32; + _loc3_.addEventListener("mouseDown",onModerateCloseClick); + _loc3_.addEventListener("mouseOver",onFlatHover); + _loc3_.addEventListener("mouseOut",onFlatHover); + _moderateContent.addChild(_loc3_); + // warn: a chip for each reason, and Warn + modSection("Warn",84); + _loc5_ = 0; + while(_loc5_ < MODERATE_REASONS.length) + { + _loc3_ = modButton("reason" + _loc5_,MODERATE_REASON_NAMES[_loc5_],_loc4_,102,_loc5_ == 2 ? 104 : 82,MOD_GREY,"player.warn"); + _loc4_ += _loc3_.width + 8; + _loc5_++; + } + modButton("warn","Warn",_loc2_[2] + _loc1_ - 120,102,120,MOD_AMBER,"player.warn"); + // the text: a message, or the warning in the staff member's words + modSection("Message, or your own warning",150); + var _loc7_:Sprite = new Sprite(); + _loc7_.x = MOD_PAD; + _loc7_.y = 168; + _loc7_.graphics.lineStyle(1,MOD_EDGE); + _loc7_.graphics.beginFill(MOD_FIELD); + _loc7_.graphics.drawRoundRect(0,0,_loc2_[2] - MOD_PAD - 10,34,14,14); + _loc7_.graphics.endFill(); + _moderateContent.addChild(_loc7_); + _moderateHint = modText("Type here, then Send it or press Warn",13,0x6E7187,false); + _moderateHint.x = 12; + _moderateHint.y = int((34 - _moderateHint.height) * 0.5); + _loc7_.addChild(_moderateHint); + _moderateInput = new TextField(); + _moderateInput.embedFonts = hasGameFont(); + _moderateInput.type = "input"; + _moderateInput.defaultTextFormat = new TextFormat("CCDigitalDelivery",14,0xFFFFFF,false); + _moderateInput.maxChars = 200; + _moderateInput.x = 10; + _moderateInput.y = 7; + _moderateInput.width = _loc2_[2] - MOD_PAD - 30; + _moderateInput.height = 22; + _moderateInput.addEventListener("change",onModerateTyped); + _loc7_.addChild(_moderateInput); + modButton("message","Send",_loc2_[2],168,_loc1_,MOD_BLUE,"player.warn"); + modSection("Chat",218); + modButton("silence 1","Silence 1 hour",_loc2_[0],236,_loc1_,MOD_PURPLE,"chat.silence"); + modButton("silence 24","Silence 1 day",_loc2_[1],236,_loc1_,MOD_PURPLE,"chat.silence"); + modButton("silence off","Lift silence",_loc2_[2],236,_loc1_,MOD_GREY,"chat.silence"); + modSection("Move",286); + modButton("summon","Bring here",_loc2_[0],304,_loc1_,MOD_TEAL,"player.summon"); + modButton("goto","Go to them",_loc2_[1],304,_loc1_,MOD_TEAL,"player.goto"); + modButton("kick","Disconnect",_loc2_[2],304,_loc1_,MOD_RED,"player.kick"); + modSection("Record, and you",354); + modButton("warnings","Warnings",_loc2_[0],372,_loc1_,MOD_GREY,"player.warn"); + modButton("unwarn","Undo warning",_loc2_[1],372,_loc1_,MOD_GREY,"player.warn"); + modButton("invisible","Go invisible",_loc2_[2],372,_loc1_,MOD_GREY,"staff.invisible"); + _moderate.addEventListener("mouseDown",onFinderMouse); + _moderate.addEventListener("mouseUp",onFinderMouse); + _moderate.addEventListener("click",onFinderMouse); + _moderate.addEventListener("mouseWheel",onFinderMouse); + _moderate.visible = false; + addChild(_moderate); + } + + private function onModerateTyped(param1:Event) : void + { + _moderateHint.visible = _moderateInput.text.length == 0; + showModerateReason(); + } + + private function showModerate(param1:String) : void + { + if(_moderate == null) + { + buildModerate(); + } + _moderateName = param1; + _moderateReason = 0; + _moderateTitle.text = "Moderate " + param1; + _moderateInput.text = ""; + _moderateHint.visible = true; + for each(var _loc2_:Object in _moderateButtons) + { + _loc2_.clip.visible = staffMay(_loc2_.permission); + } + _moderateInput.parent.visible = staffMay("player.warn"); + modSetLabel(_moderateContent.getChildByName("invisible") as Sprite,staffInvisible ? "Be seen" : "Go invisible"); + showModerateReason(); + _moderate.visible = true; + setChildIndex(_moderate,numChildren - 1); + } + + // the chosen reason's chip is lit; with text typed none is (the text is + // the warning), and Warn says so. + private function showModerateReason() : void + { + var _loc1_:Boolean = _moderateInput.text.replace(/^\s+|\s+$/g,"").length > 0; + var _loc2_:int = 0; + var _loc3_:Sprite = null; + while(_loc2_ < MODERATE_REASONS.length) + { + _loc3_ = _moderateContent.getChildByName("reason" + _loc2_) as Sprite; + paintFlatButton(_loc3_,_loc3_.width,!_loc1_ && _loc2_ == _moderateReason ? MOD_AMBER : MOD_GREY); + _loc3_.alpha = _loc1_ ? 0.45 : 1; + _loc2_++; + } + modSetLabel(_moderateContent.getChildByName("warn") as Sprite,_loc1_ ? "Warn with text" : "Warn"); + } + + private function hideModerate() : void + { + if(_moderate != null) + { + _moderate.visible = false; + } + gMainFrame.stage.focus = null; + } + + private function onModerateCloseClick(param1:MouseEvent) : void + { + param1.stopPropagation(); + hideModerate(); + } + + private function onModerateButton(param1:MouseEvent) : void + { + param1.stopPropagation(); + var _loc2_:String = Sprite(param1.currentTarget).name; + var _loc3_:String = null; + if(_loc2_.indexOf("reason") == 0) + { + _moderateReason = int(_loc2_.substr(6)); + showModerateReason(); + return; + } + if(_loc2_ == "invisible") + { + gMainFrame.server.setXtObject_Str("xiv",[]); + hideModerate(); + return; + } + // "%" ends a field of the message: left out. + _loc3_ = _moderateInput.text.split("%").join("").replace(/^\s+|\s+$/g,""); + if(_loc2_ == "warn" && _loc3_.length > 0) + { + gMainFrame.server.setXtObject_Str("xmd",["warn",_moderateName,"custom",_loc3_]); + } + else if(_loc2_ == "warn") + { + gMainFrame.server.setXtObject_Str("xmd",["warn",_moderateName,MODERATE_REASONS[_moderateReason]]); + } + else if(_loc2_ == "message") + { + if(_loc3_.length == 0) + { + gMainFrame.stage.focus = _moderateInput; + return; + } + gMainFrame.server.setXtObject_Str("xmd",["message",_moderateName,_loc3_]); + } + else if(_loc2_.indexOf("silence ") == 0) + { + gMainFrame.server.setXtObject_Str("xmd",["silence",_moderateName,_loc2_.substr(8)]); + } + else + { + gMainFrame.server.setXtObject_Str("xmd",[_loc2_,_moderateName]); + } + hideModerate(); + } + + // ---- emoji in chat. the game's text box takes nothing from Windows' + // emoji panel, so they are put in from here: a button at the end of the + // chat box opens a grid of them (Twemoji's pictures, from the server's + // /emoji/), and ":name:" in a line becomes the emoji when it is sent + // (unless it is one of the game's own emote codes, which win). the + // bubble draws them (gui.ChatBalloon). each is its name and its code + // points in hex, as Twemoji names its pictures. + private static const EMOJI_LIST:String = "smile:1f604,grin:1f601,joy:1f602,rofl:1f923,smiley:1f603,wink:1f609,blush:1f60a,innocent:1f607," + + "heart_eyes:1f60d,kissing_heart:1f618,star_struck:1f929,partying:1f973,sunglasses:1f60e,nerd:1f913,thinking:1f914," + + "neutral:1f610,expressionless:1f611,rolling_eyes:1f644,smirk:1f60f,relieved:1f60c,sleeping:1f634,yum:1f60b," + + "tongue:1f61b,zany:1f92a,shush:1f92b,cry:1f622,sob:1f62d,pleading:1f97a,angry:1f620,rage:1f621,scream:1f631," + + "flushed:1f633,cold:1f976,hot:1f975,skull:1f480,ghost:1f47b,alien:1f47d,robot:1f916,clown:1f921,poop:1f4a9," + + "thumbsup:1f44d,thumbsdown:1f44e,clap:1f44f,wave:1f44b,ok_hand:1f44c,pray:1f64f,muscle:1f4aa,raised_hands:1f64c," + + "v:270c,point_up:261d,eyes:1f440,heart:2764,orange_heart:1f9e1,yellow_heart:1f49b,green_heart:1f49a," + + "blue_heart:1f499,purple_heart:1f49c,black_heart:1f5a4,white_heart:1f90d,broken_heart:1f494,sparkling_heart:1f496," + + "two_hearts:1f495,fire:1f525,sparkles:2728,star:2b50,zap:26a1,boom:1f4a5,rainbow:1f308,sunny:2600,cloud:2601," + + "snowflake:2744,moon:1f319,tada:1f389,confetti:1f38a,balloon:1f388,gift:1f381,crown:1f451,gem:1f48e,trophy:1f3c6," + + "100:1f4af,check:2705,x:274c,warning:26a0,question:2753,exclamation:2757,music:1f3b5,video_game:1f3ae,dog:1f436," + + "cat:1f431,wolf:1f43a,fox:1f98a,bunny:1f430,bear:1f43b,panda:1f43c,tiger:1f42f,lion:1f981,monkey:1f435," + + "penguin:1f427,koala:1f428,horse:1f434,unicorn:1f984,owl:1f989,frog:1f438,turtle:1f422,snake:1f40d,dolphin:1f42c," + + "whale:1f433,shark:1f988,octopus:1f419,butterfly:1f98b,bee:1f41d,cherry_blossom:1f338,rose:1f339,sunflower:1f33b," + + "tree:1f333,cactus:1f335,mushroom:1f344,apple:1f34e,pizza:1f355,hamburger:1f354,fries:1f35f,cake:1f382,cookie:1f36a," + + "ice_cream:1f366,candy:1f36c,coffee:2615,house:1f3e0,rocket:1f680,ocean:1f30a,earth:1f30d,pumpkin:1f383," + + "christmas_tree:1f384,snowman:2603,crystal_ball:1f52e,magic:1fa84,paw:1f43e,feather:1fab6,leaf:1f343,four_leaf:1f340"; + + private static const EMOJI_COLUMNS:int = 14; + + private static const EMOJI_CELL:int = 26; + + private static var _emojiTable:Array; // [{name, hex, chars}] + + private static var _emojiByName:Object; + + private var _emojiButton:Sprite; + + private var _emojiPanel:Sprite; + + private var _emojiHint:TextField; + + private var _emojiField:TextField; + + private var _emojiCaret:int = -1; + + private var _emojiTimer:Timer; + + // the characters of code points in hex ("1f468-200d-1f469") + public static function charsOfHex(param1:String) : String + { + var _loc2_:String = ""; + var _loc3_:int = 0; + for each(var _loc4_:String in param1.split("-")) + { + _loc3_ = parseInt(_loc4_,16); + if(_loc3_ > 0xFFFF) + { + _loc3_ -= 0x10000; + _loc2_ += String.fromCharCode(0xD800 + (_loc3_ >> 10),0xDC00 + (_loc3_ & 0x3FF)); + } + else + { + _loc2_ += String.fromCharCode(_loc3_); + } + } + return _loc2_; + } + + private static function emojiTable() : Array + { + if(_emojiTable == null) + { + _emojiTable = []; + _emojiByName = {}; + for each(var _loc1_:String in EMOJI_LIST.split(",")) + { + var _loc2_:Array = _loc1_.split(":"); + var _loc3_:Object = {"name":_loc2_[0],"hex":_loc2_[1],"chars":charsOfHex(_loc2_[1])}; + _emojiTable.push(_loc3_); + _emojiByName[_loc3_.name] = _loc3_.chars; + } + } + return _emojiTable; + } + + // a line about to be sent: each ":name:" of an emoji above becomes it, + // but not the game's own emote codes (":happy:", ":joy:"), which the + // bubble shows as the game's. + public static function emojiShortcodes(param1:String) : String + { + if(param1.indexOf(":") == -1) + { + return param1; + } + emojiTable(); + return param1.replace(/:([a-z0-9_]{1,30}):/g,function(param1:String, param2:String, ... rest):String + { + if(EmoticonUtility.doesStringMatchAnEmote(param1) || _emojiByName[param2] == null) + { + return param1; + } + return _emojiByName[param2]; + }); + } + + // a line about to be sent, its emoji as "\{1f600}" (their pictures' + // names): the game's socket carries characters past U+FFFF badly, and + // these are plain letters. the bubble draws them (gui.ChatBalloon). + public static function emojiToTokens(param1:String) : String + { + var _loc2_:String = ""; + var _loc3_:int = 0; + var _loc4_:int = 0; + while(_loc3_ < param1.length) + { + _loc4_ = ChatBalloon.emojiLength(param1,_loc3_); + if(_loc4_ > 0) + { + _loc2_ += "\\{" + ChatBalloon.emojiName(param1.substr(_loc3_,_loc4_)) + "}"; + _loc3_ += _loc4_; + } + else + { + _loc2_ += param1.charAt(_loc3_); + _loc3_++; + } + } + return _loc2_; + } + + // a line for the chat history's list, which has no pictures: each emoji + // as its name (":fire:"), or ":emoji:" for one not in the grid. + public static function emojiAsNames(param1:String) : String + { + if(param1.indexOf("\\{") == -1) + { + return param1; + } + emojiTable(); + return param1.replace(/\\\{([0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9})\}/g,function(param1:String, param2:String, ... rest):String + { + for each(var _loc4_:Object in _emojiTable) + { + if(_loc4_.hex == param2 || ChatBalloon.emojiName(_loc4_.chars) == param2) + { + return ":" + _loc4_.name + ":"; + } + } + return ":emoji:"; + }); + } + + private function startEmojiButton() : void + { + _emojiTimer = new Timer(500); + _emojiTimer.addEventListener("timer",placeEmojiButton); + _emojiTimer.start(); + gMainFrame.stage.addEventListener("mouseDown",onEmojiStageDown,false,0,true); + } + + private static function shownOnStage(param1:DisplayObject) : Boolean + { + if(param1 == null || param1.stage == null) + { + return false; + } + while(param1 != null) + { + if(!param1.visible) + { + return false; + } + param1 = param1.parent; + } + return true; + } + + // the button, kept at the right end of the chat box while it is shown + private function placeEmojiButton(param1:Event = null) : void + { + var _loc2_:TextField = null; + var _loc3_:Point = null; + try + { + _loc2_ = GuiManager.chatHist != null ? GuiManager.chatHist.chatMsgText : null; + } + catch(e:Error) + { + _loc2_ = null; + } + if(_emojiButton == null) + { + _emojiButton = new Sprite(); + _emojiButton.buttonMode = true; + _emojiButton.useHandCursor = true; + _emojiButton.graphics.lineStyle(2,8349508); + _emojiButton.graphics.beginFill(16774084); + _emojiButton.graphics.drawCircle(0,0,12); + _emojiButton.graphics.endFill(); + var _loc4_:Sprite = new Sprite(); + _loc4_.mouseEnabled = false; + _loc4_.mouseChildren = false; + loadArt(gMainFrame.clientInfo.websiteURL + "emoji/1f600.png",_loc4_,17,false); + _emojiButton.addChild(_loc4_); + _emojiButton.addEventListener("mouseDown",onEmojiButton); + addChild(_emojiButton); + } + var _loc5_:Boolean = shownOnStage(_loc2_) && _loc2_.type == "input"; + _emojiButton.visible = _loc5_; + if(!_loc5_) + { + if(_emojiPanel != null) + { + _emojiPanel.visible = false; + } + return; + } + // the box gives up room for it once + if(_emojiField != _loc2_) + { + _emojiField = _loc2_; + _loc2_.width = Math.max(60,_loc2_.width - 28); + } + _loc3_ = globalToLocal(_loc2_.localToGlobal(new Point(_loc2_.width,_loc2_.height * 0.5))); + _emojiButton.x = int(_loc3_.x + 15); + _emojiButton.y = int(_loc3_.y); + if(getChildIndex(_emojiButton) < numChildren - 1 && (_emojiPanel == null || !_emojiPanel.visible)) + { + setChildIndex(_emojiButton,numChildren - 1); + } + } + + private function onEmojiButton(param1:MouseEvent) : void + { + param1.stopPropagation(); + if(_emojiPanel == null) + { + buildEmojiPanel(); + } + _emojiCaret = _emojiField != null && gMainFrame.stage.focus == _emojiField ? _emojiField.caretIndex : -1; + _emojiPanel.visible = !_emojiPanel.visible; + if(_emojiPanel.visible) + { + _emojiPanel.x = int(Math.max(4,_emojiButton.x + 14 - _emojiPanel.width)); + _emojiPanel.y = int(Math.max(4,_emojiButton.y - 18 - _emojiPanel.height)); + setChildIndex(_emojiPanel,numChildren - 1); + setChildIndex(_emojiButton,numChildren - 1); + } + } + + private function buildEmojiPanel() : void + { + var _loc1_:Array = emojiTable(); + var _loc2_:int = Math.ceil(_loc1_.length / EMOJI_COLUMNS); + var _loc3_:int = EMOJI_COLUMNS * EMOJI_CELL + 12; + var _loc4_:int = _loc2_ * EMOJI_CELL + 36; + var _loc5_:int = 0; + _emojiPanel = new Sprite(); + _emojiPanel.graphics.lineStyle(2,8349508); + _emojiPanel.graphics.beginFill(16774084); + _emojiPanel.graphics.drawRoundRect(0,0,_loc3_,_loc4_,14,14); + _emojiPanel.graphics.endFill(); + while(_loc5_ < _loc1_.length) + { + var _loc6_:Sprite = new Sprite(); + _loc6_.name = "emoji" + _loc5_; + _loc6_.x = 6 + (_loc5_ % EMOJI_COLUMNS) * EMOJI_CELL + EMOJI_CELL * 0.5; + _loc6_.y = 6 + Math.floor(_loc5_ / EMOJI_COLUMNS) * EMOJI_CELL + EMOJI_CELL * 0.5; + _loc6_.graphics.beginFill(3184463,0); + _loc6_.graphics.drawRoundRect(-EMOJI_CELL * 0.5,-EMOJI_CELL * 0.5,EMOJI_CELL,EMOJI_CELL,8,8); + _loc6_.graphics.endFill(); + _loc6_.buttonMode = true; + _loc6_.useHandCursor = true; + _loc6_.mouseChildren = false; + loadArt(gMainFrame.clientInfo.websiteURL + "emoji/" + _loc1_[_loc5_].hex + ".png",_loc6_,20,false); + _loc6_.addEventListener("mouseDown",onEmojiPick); + _loc6_.addEventListener("mouseOver",onEmojiHover); + _loc6_.addEventListener("mouseOut",onEmojiHover); + _emojiPanel.addChild(_loc6_); + _loc5_++; + } + _emojiHint = new TextField(); + _emojiHint.embedFonts = hasGameFont(); + _emojiHint.selectable = false; + _emojiHint.mouseEnabled = false; + _emojiHint.defaultTextFormat = new TextFormat("CCDigitalDelivery",12,6045213,true); + _emojiHint.width = _loc3_ - 16; + _emojiHint.height = 20; + _emojiHint.x = 8; + _emojiHint.y = _loc4_ - 26; + _emojiHint.text = "Or type its name, as :fire: or :heart:"; + _emojiPanel.addChild(_emojiHint); + _emojiPanel.visible = false; + addChild(_emojiPanel); + } + + private function onEmojiHover(param1:MouseEvent) : void + { + var _loc2_:Sprite = Sprite(param1.currentTarget); + var _loc3_:Object = emojiTable()[int(_loc2_.name.substr(5))]; + _loc2_.alpha = param1.type == "mouseOver" ? 0.7 : 1; + _emojiHint.text = param1.type == "mouseOver" ? ":" + _loc3_.name + ":" : "Or type its name, as :fire: or :heart:"; + } + + // an emoji into the chat box, where its cursor was + private function onEmojiPick(param1:MouseEvent) : void + { + param1.stopPropagation(); + var _loc2_:Object = emojiTable()[int(Sprite(param1.currentTarget).name.substr(5))]; + var _loc3_:TextField = _emojiField; + if(_loc3_ == null || _loc3_.text.length + _loc2_.chars.length > _loc3_.maxChars && _loc3_.maxChars > 0) + { + return; + } + var _loc4_:int = _emojiCaret >= 0 && _emojiCaret <= _loc3_.text.length ? _emojiCaret : _loc3_.text.length; + _loc3_.replaceText(_loc4_,_loc4_,_loc2_.chars); + _emojiCaret = _loc4_ + _loc2_.chars.length; + gMainFrame.stage.focus = _loc3_; + _loc3_.setSelection(_emojiCaret,_emojiCaret); + _loc3_.dispatchEvent(new Event("change")); + } + + // a click anywhere else closes the grid + private function onEmojiStageDown(param1:MouseEvent) : void + { + if(_emojiPanel != null && _emojiPanel.visible && !_emojiPanel.contains(param1.target as DisplayObject) && !_emojiButton.contains(param1.target as DisplayObject)) + { + _emojiPanel.visible = false; + } + } + + // ---- the Item Maker (the settings menu): a player's own item made from + // one of the game's (the server's lib/playeritems.js), in the look of the + // game's own windows, as the Item Giver is. two pages: making one (the + // game's items, looked up as the Item Giver does, "base=1": only those + // that can be copied) and the player's own (rename, a picture of its own, + // delete). the server answers "xcm" [ok, what to say, left today, left + // in all, the player's items as JSON]; a picture goes over HTTP + // (POST /api/itemart, lib/itemart.js). + private static const MAKER_ROWS:int = 5; + + private var _maker:Sprite; + + private var _makerContent:MovieClip; + + private var _makerMode:String = "make"; + + private var _makerKind:String = "clothing"; + + private var _makerStatus:TextField; + + private var _makerSearchBar:MovieClip; + + private var _makerNameBar:MovieClip; + + private var _makerKindButton:MovieClip; + + private var _makerRowsSprite:Sprite; + + private var _makerResults:Array = []; + + private var _makerMine:Array = []; + + private var _makerPage:int = 0; + + private var _makerChosen:Object; + + private var _makerLeft:String = ""; + + private var _makerButtons:Object = {}; + + private var _makerFile:FileReference; + + private var _makerUploading:Object; + + private var _makerIcons:Array = []; + + // "xcm": the server's answer, for the Item Maker if it is open. + public static function onItemMaker(param1:Object) : void + { + if(_toolsInstance != null) + { + try + { + _toolsInstance.makerAnswer(param1); + } + catch(e:Error) + { + GlobalErrorCatch.reportToServer("item maker: " + e + "\n" + e.getStackTrace()); + } + } + } + + // a button of the game's, at param3, param4; `param5` says which pages + // show it. + private function makerButton(param1:String, param2:String, param3:Number, param4:Number, param5:String, param6:Number = 1) : MovieClip + { + var _loc7_:MovieClip = GETDEFINITIONBYNAME("introBtnCont"); + _loc7_.name = param1; + _loc7_.x = param3; + _loc7_.y = param4; + _loc7_.scaleX = _loc7_.scaleY = param6; + finderButtonText(_loc7_,param2); + // the file picker opens only for a click + _loc7_.addEventListener(param1 == "picture" ? "click" : "mouseDown",onMakerButton); + _makerContent.addChild(_loc7_); + _makerButtons[param1] = {"clip":_loc7_,"pages":param5}; + return _loc7_; + } + + private function buildItemMaker() : void + { + var _loc1_:MovieClip = GETDEFINITIONBYNAME("ReportRulesPopupSkin"); + var _loc2_:int = 1; + var _loc3_:MovieClip = null; + _maker = new Sprite(); + _maker.graphics.beginFill(0,0.45); + _maker.graphics.drawRect(0,0,900,550); + _maker.graphics.endFill(); + var _loc4_:Sprite = new Sprite(); + _loc4_.x = 450; + _loc4_.y = 275; + _maker.addChild(_loc4_); + _loc4_.addChild(_loc1_); + _makerContent = GETDEFINITIONBYNAME("ReportRulesPopupContent"); + _makerContent.x = _loc1_.c.x; + _makerContent.y = _loc1_.c.y; + _loc4_.addChild(_makerContent); + _loc1_.bx.addEventListener("mouseDown",function(param1:MouseEvent):void + { + param1.stopPropagation(); + showItemMaker(false); + }); + while(_loc2_ <= 5) + { + _makerContent["ruleTxt" + _loc2_].visible = false; + _makerContent["ruleBodyTxt" + _loc2_].visible = false; + _loc2_++; + } + _makerContent.titleTxt.text = "Item Maker"; + _makerStatus = _makerContent.ruleBodyTxt1; + _makerStatus.visible = true; + _makerStatus.wordWrap = true; + _makerStatus.x = -245; + _makerStatus.y = -116; + _makerStatus.width = 490; + _makerStatus.height = 44; + // the bars and the kind, over the list + _makerSearchBar = finderSearchBar(-247,-160,212,"Search the game's items",null,40,true); + _makerContent.addChild(_makerSearchBar); + _makerKindButton = makerButton("kind","Clothing",-30,-156,"make"); + _makerNameBar = finderSearchBar(93,-160,156,"Your item's name","A-Za-z0-9 '&!?.,:()#+\\-",40,false); + _makerContent.addChild(_makerNameBar); + _makerRowsSprite = new Sprite(); + _makerRowsSprite.y = -54; + _makerContent.addChild(_makerRowsSprite); + _loc3_ = GETDEFINITIONBYNAME("arrow_l_btnContOld"); + _loc3_.x = -228; + _loc3_.y = 166; + _loc3_.name = "prev"; + _loc3_.addEventListener("mouseDown",onMakerButton); + _makerContent.addChild(_loc3_); + _loc3_ = GETDEFINITIONBYNAME("arrow_r_btnContOld"); + _loc3_.x = 228; + _loc3_.y = 166; + _loc3_.name = "next"; + _loc3_.addEventListener("mouseDown",onMakerButton); + _makerContent.addChild(_loc3_); + // making one + makerButton("make","Make it",-175,148,"make"); + makerButton("mine","My items",-58,148,"make"); + makerButton("search","Search",59,148,"make"); + // their own: what the bar's name, a picture or a delete does to the one chosen + makerButton("rename","Rename",-215,148,"mine",0.72); + makerButton("picture","Picture",-128,148,"mine",0.72); + makerButton("look","Look",-41,148,"mine",0.72); + makerButton("delete","Delete",46,148,"mine",0.72); + makerButton("back","Make more",133,148,"mine",0.72); + _maker.addEventListener("mouseDown",onFinderMouse); + _maker.addEventListener("mouseUp",onFinderMouse); + _maker.addEventListener("click",onFinderMouse); + _maker.addEventListener("mouseWheel",onFinderMouse); + _maker.visible = false; + addChild(_maker); + } + + private function showItemMaker(param1:Boolean) : void + { + if(!param1) + { + if(_maker != null) + { + _maker.visible = false; + } + gMainFrame.stage.focus = null; + return; + } + if(_maker == null) + { + buildItemMaker(); + } + _makerChosen = null; + _makerNameBar.searchTxt.text = ""; + _makerNameBar.txt.visible = true; + makerMode("make"); + _maker.visible = true; + setChildIndex(_maker,numChildren - 1); + gMainFrame.stage.focus = _makerSearchBar.searchTxt; + gMainFrame.server.setXtObject_Str("xcm",["info"]); + makerSearch(); + } + + private function makerMode(param1:String) : void + { + _makerMode = param1; + _makerPage = 0; + _makerChosen = null; + for each(var _loc2_:Object in _makerButtons) + { + _loc2_.clip.visible = String(_loc2_.pages).indexOf(param1) != -1; + } + _makerSearchBar.visible = param1 == "make"; + _makerNameBar.txt.text = param1 == "make" ? "Your item's name" : "New name"; + makerSay(param1 == "make" ? "Choose one of the game's items, name it, then Make it. " + _makerLeft : "Choose one of your items: rename it (type the name first), give it a picture, change its Look (worn as the picture, or its shape painted with it), or delete it."); + makerRows(); + } + + private function makerSay(param1:String) : void + { + _makerStatus.text = param1; + } + + private function makerSearch() : void + { + var _loc1_:URLLoader = new URLLoader(); + _loc1_.addEventListener("complete",onMakerResults,false,0,false); + _loc1_.addEventListener("ioError",onMakerFailed,false,0,false); + _loc1_.addEventListener("securityError",onMakerFailed,false,0,false); + _loc1_.load(new URLRequest(gMainFrame.clientInfo.websiteURL + "api/search?base=1&kind=" + _makerKind + "&q=" + encodeURIComponent(_makerSearchBar.searchTxt.text) + + "&username=" + encodeURIComponent(gMainFrame.server.userName) + "&token=" + encodeURIComponent(gMainFrame.clientInfo.authToken))); + } + + private function onMakerFailed(param1:Event) : void + { + makerSay("That did not work. Try again."); + } + + private function onMakerResults(param1:Event) : void + { + try + { + _makerResults = JSON.parse(param1.target.data).results as Array; + } + catch(e:Error) + { + _makerResults = null; + } + if(_makerResults == null) + { + _makerResults = []; + } + _makerPage = 0; + if(_makerMode == "make") + { + makerRows(); + if(_makerResults.length == 0) + { + makerSay("Nothing found. Try another word."); + } + } + } + + private function makerList() : Array + { + return _makerMode == "make" ? _makerResults : _makerMine; + } + + // the page of the list shown: a row of the game's for each, its icon + // (a custom item's own picture, when it has one) beside it. + private function makerRows() : void + { + var _loc1_:Array = makerList(); + var _loc2_:int = _makerPage * MAKER_ROWS; + var _loc3_:MovieClip = null; + var _loc4_:Object = null; + while(_makerRowsSprite.numChildren > 0) + { + _makerRowsSprite.removeChildAt(0); + } + _makerIcons = []; + while(_loc2_ < _loc1_.length && _loc2_ < _makerPage * MAKER_ROWS + MAKER_ROWS) + { + _loc4_ = _loc1_[_loc2_]; + _loc3_ = GETDEFINITIONBYNAME("textBtnCont"); + _loc3_.x = -40; + _loc3_.y = (_loc2_ - _makerPage * MAKER_ROWS) * 40; + _loc3_.name = "row" + _loc2_; + _loc3_.currTxt.mouseEnabled = false; + var _loc5_:Boolean = _makerChosen != null && _makerChosen.id == _loc4_.id && _makerChosen.kind == _loc4_.kind; + _loc3_.currTxt.text = (_loc5_ ? "> " : "") + makerShort(String(_loc4_.name || "(no name)"),24) + (_makerMode == "mine" ? (_loc4_.waiting == "item" ? " (waiting)" : _loc4_.waiting == "picture" ? " (picture waiting)" : _loc4_.art ? (_loc4_.kind == "clothing" ? (_loc4_.artMode == "texture" ? " (texture)" : " (sticker)") : " (picture)") : "") : " #" + _loc4_.id); + _loc3_.addEventListener("mouseDown",onMakerButton); + _makerRowsSprite.addChild(_loc3_); + _makerRowsSprite.addChild(finderPreview(_loc4_,_loc2_,186,_loc3_.y)); + _loc2_++; + } + if(_makerMode == "mine" && _loc1_.length == 0) + { + makerSay("You have not made any items yet. " + _makerLeft); + } + } + + private static function makerShort(param1:String, param2:int) : String + { + return param1.length > param2 ? param1.substr(0,param2 - 3) + "..." : param1; + } + + public function makerAnswer(param1:Object) : void + { + if(_maker == null) + { + return; + } + var _loc2_:String = String(param1[3]); + try + { + _makerMine = JSON.parse(String(param1[6])) as Array; + } + catch(e:Error) + { + _makerMine = null; + } + if(_makerMine == null) + { + _makerMine = []; + } + _makerMine.reverse(); // the newest first + // the one chosen on this page, as it is now (its look, its picture) + if(_makerMode == "mine" && _makerChosen != null) + { + var _loc6_:Object = _makerChosen; + _makerChosen = null; + for each(var _loc7_:Object in _makerMine) + { + if(_loc7_.kind == _loc6_.kind && _loc7_.id == _loc6_.id) + { + _makerChosen = _loc7_; + } + } + } + _makerLeft = "You can make " + int(param1[4]) + " more today (" + int(param1[5]) + " in all)."; + if(_loc2_.length > 0) + { + makerSay(_loc2_); + } + else if(_makerMode == "make") + { + makerSay("Choose one of the game's items, name it, then Make it. " + _makerLeft); + } + if(String(param1[2]) == "1" && _loc2_.length > 0) + { + _makerNameBar.searchTxt.text = ""; + _makerNameBar.txt.visible = true; + _makerChosen = null; + } + if(_makerMode == "mine") + { + makerRows(); + } + } + + private function makerName() : String + { + return _makerNameBar.searchTxt.text.split("%").join("").replace(/^\s+|\s+$/g,""); + } + + private function onMakerButton(param1:MouseEvent) : void + { + param1.stopPropagation(); + var _loc2_:String = DisplayObject(param1.currentTarget).name; + var _loc3_:Object = null; + if(_loc2_.indexOf("row") == 0) + { + _makerChosen = makerList()[int(_loc2_.substr(3))]; + if(_makerChosen != null && _makerMode == "make" && _makerNameBar.searchTxt.text.length == 0) + { + _makerNameBar.searchTxt.text = String(_makerChosen.name || "").replace(/[^A-Za-z0-9 '&!?.,:()#+\-]/g,"").substr(0,40); + _makerNameBar.txt.visible = _makerNameBar.searchTxt.text.length == 0; + } + if(_makerChosen != null) + { + makerSay((_makerMode == "make" ? "Making it from " : "Chosen: ") + _makerChosen.name + "."); + } + makerRows(); + } + else if(_loc2_ == "kind") + { + _makerKind = _makerKind == "clothing" ? "den" : "clothing"; + finderButtonText(_makerKindButton,_makerKind == "clothing" ? "Clothing" : "Den items"); + _makerChosen = null; + makerSearch(); + } + else if(_loc2_ == "search") + { + makerSearch(); + } + else if(_loc2_ == "prev" || _loc2_ == "next") + { + _makerPage = Math.max(0,Math.min(_makerPage + (_loc2_ == "next" ? 1 : -1),Math.ceil(makerList().length / MAKER_ROWS) - 1)); + makerRows(); + } + else if(_loc2_ == "mine") + { + makerMode("mine"); + } + else if(_loc2_ == "back") + { + makerMode("make"); + makerSearch(); + } + else if(_makerChosen == null) + { + makerSay(_makerMode == "make" ? "Choose one of the game's items first." : "Choose one of your items first."); + } + else if(_loc2_ == "make") + { + if(makerName().length == 0) + { + gMainFrame.stage.focus = _makerNameBar.searchTxt; + makerSay("Type a name for it first."); + return; + } + makerSay("Making it..."); + gMainFrame.server.setXtObject_Str("xcm",["make",_makerChosen.kind,_makerChosen.id,makerName()]); + } + else if(_loc2_ == "rename") + { + if(makerName().length == 0) + { + gMainFrame.stage.focus = _makerNameBar.searchTxt; + makerSay("Type the new name in the box first."); + return; + } + gMainFrame.server.setXtObject_Str("xcm",["rename",_makerChosen.kind,_makerChosen.id,makerName()]); + } + else if(_loc2_ == "delete") + { + _loc3_ = _makerChosen; + new SBYesNoPopup(GuiManager.guiLayer,"Delete " + _loc3_.name + "? It goes from everyone who has it.",true,function(param1:Object):void + { + if(param1.status) + { + gMainFrame.server.setXtObject_Str("xcm",["delete",_loc3_.kind,_loc3_.id]); + } + },0); + } + else if(_loc2_ == "picture") + { + makerPickPicture(_makerChosen); + } + // how a clothing item with a picture is worn: the picture itself + // (a sticker) or the item's shape painted with it (a texture) + else if(_loc2_ == "look") + { + if(_makerChosen.kind != "clothing" || !_makerChosen.art) + { + makerSay(_makerChosen.kind != "clothing" ? "A den item stands as its picture." : "Give it a picture first."); + return; + } + gMainFrame.server.setXtObject_Str("xcm",["look",_makerChosen.kind,_makerChosen.id,_makerChosen.artMode == "texture" ? "sticker" : "texture"]); + } + } + + // the picture: chosen from this computer, read, and sent as it is (the + // server checks it and takes out what does not belong in it). + private function makerPickPicture(param1:Object) : void + { + _makerUploading = param1; + _makerFile = new FileReference(); + _makerFile.addEventListener("select",function(param1:Event):void + { + makerSay("Reading the picture..."); + _makerFile.load(); + }); + _makerFile.addEventListener("complete",onMakerPictureRead); + _makerFile.addEventListener("ioError",onMakerFailed); + try + { + _makerFile.browse([new FileFilter("Pictures (PNG, JPEG, GIF, BMP)","*.png;*.jpg;*.jpeg;*.gif;*.bmp")]); + } + catch(e:Error) + { + makerSay("The picture could not be chosen here. Use your account page on the website instead."); + } + } + + // the picture read: sent as it is when the server takes it so (a PNG, + // JPEG or GIF small enough, or a BMP, which the server makes a PNG); one + // too big is drawn smaller here and sent as a PNG. + private static const MAKER_PICTURE_SIDE:int = 512; + + private static const MAKER_PICTURE_BYTES:int = 300 * 1024; + + private function onMakerPictureRead(param1:Event) : void + { + var _loc2_:ByteArray = _makerFile.data; + if(/\.bmp$/i.test(String(_makerFile.name))) + { + makerSendPicture(_loc2_); + return; + } + var _loc3_:Loader = new Loader(); + _loc3_.contentLoaderInfo.addEventListener("complete",function(param1:Event):void + { + var _loc2_:BitmapData = _loc3_.content is Bitmap ? Bitmap(_loc3_.content).bitmapData : null; + if(_loc2_ == null) + { + makerSay("That picture could not be read. Try a PNG, JPEG or GIF."); + } + else if(_loc2_.width <= MAKER_PICTURE_SIDE && _loc2_.height <= MAKER_PICTURE_SIDE && _makerFile.data.length <= MAKER_PICTURE_BYTES) + { + makerSendPicture(_makerFile.data); + } + else + { + makerSay("Making the picture smaller..."); + makerSendPicture(shrunkPng(_loc2_)); + } + }); + _loc3_.contentLoaderInfo.addEventListener("ioError",function(param1:Event):void + { + makerSay("That picture could not be read. Try a PNG, JPEG or GIF."); + }); + _loc3_.loadBytes(_loc2_); + } + + // a PNG of the picture fitted in MAKER_PICTURE_SIDE, smaller until it is + // no more than MAKER_PICTURE_BYTES + private static function shrunkPng(param1:BitmapData) : ByteArray + { + var _loc2_:ByteArray = null; + for each(var _loc3_:int in [MAKER_PICTURE_SIDE,384,256,128]) + { + var _loc4_:Number = Math.min(1,_loc3_ / param1.width,_loc3_ / param1.height); + var _loc5_:BitmapData = new BitmapData(Math.max(1,Math.round(param1.width * _loc4_)),Math.max(1,Math.round(param1.height * _loc4_)),true,0); + _loc5_.draw(param1,new Matrix(_loc4_,0,0,_loc4_),null,null,null,true); + _loc2_ = encodePng(_loc5_); + _loc5_.dispose(); + if(_loc2_.length <= MAKER_PICTURE_BYTES) + { + break; + } + } + return _loc2_; + } + + private static var _crcTable:Array; + + private static function crc32(param1:ByteArray, param2:int, param3:int) : uint + { + var _loc4_:uint = 0; + var _loc5_:int = 0; + var _loc6_:int = 0; + if(_crcTable == null) + { + _crcTable = []; + while(_loc5_ < 256) + { + _loc4_ = _loc5_; + _loc6_ = 0; + while(_loc6_ < 8) + { + _loc4_ = (_loc4_ & 1) != 0 ? uint(0xEDB88320 ^ (_loc4_ >>> 1)) : uint(_loc4_ >>> 1); + _loc6_++; + } + _crcTable[_loc5_] = _loc4_; + _loc5_++; + } + } + _loc4_ = 0xFFFFFFFF; + _loc5_ = param2; + while(_loc5_ < param3) + { + _loc4_ = uint(_crcTable[(_loc4_ ^ param1[_loc5_]) & 0xFF] ^ (_loc4_ >>> 8)); + _loc5_++; + } + return uint(_loc4_ ^ 0xFFFFFFFF); + } + + private static function pngChunk(param1:ByteArray, param2:uint, param3:ByteArray) : void + { + param1.writeUnsignedInt(param3 == null ? 0 : param3.length); + var _loc4_:int = int(param1.position); + param1.writeUnsignedInt(param2); + if(param3 != null) + { + param1.writeBytes(param3); + } + param1.writeUnsignedInt(crc32(param1,_loc4_,int(param1.position))); + } + + // a PNG (RGBA, 8 bits a channel) of `param1` + public static function encodePng(param1:BitmapData) : ByteArray + { + var _loc2_:ByteArray = new ByteArray(); + var _loc3_:ByteArray = new ByteArray(); + var _loc4_:ByteArray = new ByteArray(); + var _loc5_:int = 0; + var _loc6_:int = 0; + var _loc7_:uint = 0; + _loc2_.writeUnsignedInt(0x89504E47); + _loc2_.writeUnsignedInt(0x0D0A1A0A); + _loc3_.writeInt(param1.width); + _loc3_.writeInt(param1.height); + _loc3_.writeByte(8); + _loc3_.writeByte(6); + _loc3_.writeByte(0); + _loc3_.writeByte(0); + _loc3_.writeByte(0); + pngChunk(_loc2_,0x49484452,_loc3_); + while(_loc5_ < param1.height) + { + _loc4_.writeByte(0); + _loc6_ = 0; + while(_loc6_ < param1.width) + { + _loc7_ = param1.getPixel32(_loc6_,_loc5_); + _loc4_.writeUnsignedInt(uint((_loc7_ & 0xFFFFFF) << 8 | _loc7_ >>> 24)); + _loc6_++; + } + _loc5_++; + } + _loc4_.compress(); + pngChunk(_loc2_,0x49444154,_loc4_); + pngChunk(_loc2_,0x49454E44,null); + return _loc2_; + } + + private function makerSendPicture(param1:ByteArray) : void + { + var _loc2_:URLRequest = new URLRequest(gMainFrame.clientInfo.websiteURL + "api/itemart?kind=" + _makerUploading.kind + "&id=" + _makerUploading.id + + "&token=" + encodeURIComponent(gMainFrame.clientInfo.authToken)); + _loc2_.method = "POST"; + _loc2_.contentType = "application/octet-stream"; + _loc2_.data = param1; + var _loc3_:URLLoader = new URLLoader(); + _loc3_.addEventListener("complete",function(param1:Event):void + { + var _loc2_:Object = null; + try + { + _loc2_ = JSON.parse(param1.target.data); + } + catch(e:Error) + { + _loc2_ = {"error":"That did not work. Try again."}; + } + makerSay(_loc2_.ok ? String(_loc2_.ok) : String(_loc2_.error)); + gMainFrame.server.setXtObject_Str("xcm",["info"]); + }); + _loc3_.addEventListener("ioError",onMakerFailed); + _loc3_.addEventListener("securityError",onMakerFailed); + makerSay("Sending the picture..."); + _loc3_.load(_loc2_); + } + private function onFinderKey(param1:KeyboardEvent) : void { if(param1.eventPhase == 3) @@ -1961,6 +3686,31 @@ package return; } var _loc2_:Boolean = _finder != null && _finder.visible; + // the Item Maker and the staff's window: Esc closes them, Enter + // searches (in the Item Maker's search box), and no key gets past + // them to the game (which would take typing for its chat bar). + if(_maker != null && _maker.visible) + { + if(param1.keyCode == 27) + { + showItemMaker(false); + } + else if(param1.keyCode == 13 && gMainFrame.stage.focus == _makerSearchBar.searchTxt) + { + makerSearch(); + } + param1.stopImmediatePropagation(); + return; + } + if(_moderate != null && _moderate.visible) + { + if(param1.keyCode == 27) + { + hideModerate(); + } + param1.stopImmediatePropagation(); + return; + } // the rules: Esc closes them as their X does if(_rulesWin != null && _rulesWin.visible) { diff --git a/swf-src/ActionManager.as b/swf-src/ActionManager.as index eb5b719..1487fab 100644 --- a/swf-src/ActionManager.as +++ b/swf-src/ActionManager.as @@ -47,6 +47,17 @@ package gui private var _names:Dictionary = new Dictionary(true); private var _swapBtn:MovieClip; + + // Whether the next (and currently selected) action is horizontally + // mirrored. The state is sent with the action to other players. + public var mirrorActions:Boolean = false; + + private var _lastAction:Sprite; + + // sitting facing forward (":sitS:", AvatarWorldView's animation 1): the + // "Forward" in the middle of the four arrows. its action sprite is a + // class of the client's own (SitForwardAction), not of the HUD's art. + private static const SIT_FORWARD:String = "SitForwardAction"; private const ACTIONWINDOW_DIM_ALPHA:Number = 0.5; @@ -309,6 +320,7 @@ package gui _loc12_.addEventListener("mouseDown",actionClickHandler,false,0,true); _loc8_++; } + addSitDirectionButtons(_loc3_); } else if(_loc6_ >= 4) { @@ -393,6 +405,7 @@ package gui actionStrings["sleepAnim_btnCont"] = actionStrings["diveAnim_btnCont"] = [":sleep:",":dive:"]; actionStrings["hopAnim_btnCont"] = actionStrings["swirlAnim_btnCont"] = [":hop:",":swirl:"]; actionStrings["playAnim_btnCont"] = [":play:"]; + actionStrings[SIT_FORWARD] = [":sitS:"]; } private function setupTitleBanner() : void @@ -445,6 +458,110 @@ package gui return _loc2_.length > 1 ? _loc2_[_oceanShown ? 1 : 0] : _loc2_[0]; } + // Front and Back sit facing straight forward and straight away. Mirror + // replays whichever action was picked most recently in the other + // horizontal direction (including dance, sleep, hop and play). + private function addSitDirectionButtons(param1:MovieClip) : void + { + var _loc2_:Rectangle = param1.getBounds(param1); + var _loc3_:Number = _loc2_.x + _loc2_.width * 0.5; + var _loc4_:Number = _loc2_.y + _loc2_.height * 0.5; + var _loc5_:Sprite = addDirectionButton(param1,"Front",0,0,false); + var _loc6_:Sprite = addDirectionButton(param1,"Back",0,0,true); + var _loc7_:Number = _loc3_ - (_loc5_.width + 3 + _loc6_.width) * 0.5; + _loc5_.x = _loc7_; + _loc6_.x = _loc7_ + _loc5_.width + 3; + _loc5_.y = _loc6_.y = _loc4_ - 13; + var _loc8_:Sprite = actionPill("Mirror"); + var _loc9_:Sprite = actionHitTarget(_loc8_); + _loc9_.x = _loc3_ - _loc9_.width * 0.5; + _loc9_.y = _loc4_ + 3; + _loc9_.addEventListener("mouseDown",mirrorClickHandler,false,0,true); + _loc9_.addEventListener("mouseOver",function(param1:MouseEvent):void + { + _loc9_.alpha = 0.8; + },false,0,true); + _loc9_.addEventListener("mouseOut",function(param1:MouseEvent):void + { + _loc9_.alpha = 1; + },false,0,true); + param1.addChild(_loc9_); + } + + private function addDirectionButton(param1:MovieClip, param2:String, param3:Number, param4:Number, param5:Boolean) : Sprite + { + var _loc6_:Sprite = actionPill(param2); + var _loc7_:Sprite = actionHitTarget(_loc6_); + _loc7_.x = param3; + _loc7_.y = param4; + _loc7_.name = param5 ? "sitBackHit" : "sitFrontHit"; + _loc7_.addEventListener("mouseDown",sitDirectionClickHandler,false,0,true); + param1.addChild(_loc7_); + return _loc7_; + } + + // Keep the generated controls visually uniform. Invisible trailing + // spaces reserve the same room without changing the labels players see. + private function actionPill(param1:String) : Sprite + { + var _loc2_:String = param1 == "Front" ? "Front " : (param1 == "Back" ? "Back " : param1); + return AJClient.makePill(_loc2_,0x5CB82E,0x2C6E16,false,10); + } + + private function sitDirectionClickHandler(param1:MouseEvent) : void + { + param1.stopPropagation(); + // one sprite class for both; each sprite is named for the way it faces + var _loc2_:Sprite = new SitForwardAction(); + _names[_loc2_] = param1.currentTarget.name == "sitBackHit" ? ":sitN:" : ":sitS:"; + selectAction(_loc2_); + } + + // The sit artwork is itself a MovieClip with mouse children. A separate + // transparent hit target above it keeps our generated labels clickable. + private function actionHitTarget(param1:Sprite) : Sprite + { + var _loc2_:Sprite = new Sprite(); + _loc2_.graphics.beginFill(0,0); + _loc2_.graphics.drawRect(0,0,param1.width,param1.height); + _loc2_.graphics.endFill(); + _loc2_.addChild(param1); + _loc2_.buttonMode = true; + _loc2_.useHandCursor = true; + _loc2_.mouseEnabled = true; + _loc2_.mouseChildren = false; + return _loc2_; + } + + private function selectAction(param1:Sprite, param2:Boolean = false) : void + { + if(!actionBtn.isGray) + { + mirrorActions = param2; + _lastAction = param1; + setActionCallback(param1); + actionBtn.dispatchEvent(new MouseEvent("mouseDown")); + } + } + + private function mirrorClickHandler(param1:MouseEvent) : void + { + param1.stopPropagation(); + if(!actionBtn.isGray) + { + mirrorActions = !mirrorActions; + if(_lastAction) + { + setActionCallback(_lastAction); + } + } + } + + public function rememberAction(param1:Sprite) : void + { + _lastAction = param1; + } + public function getActionString(param1:Sprite) : String { if(_names[param1] != undefined) @@ -462,6 +579,12 @@ package gui public function matchActionString(param1:String, param2:Boolean = false) : Sprite { var _loc3_:int = 0; + if(param1 == ":sitS:" || param1 == ":sitN:") + { + var _loc9_:Sprite = new SitForwardAction(); + _names[_loc9_] = param1; + return _loc9_; + } var _loc4_:String = OTHER_SET_BUTTONS[param1]; var _loc5_:Sprite = null; if(_loc4_ && param2 && !playerHasSet(param1.indexOf("Swim") != -1)) @@ -565,7 +688,8 @@ package gui param1.stopPropagation(); if(!actionBtn.isGray && !param1.currentTarget.isGray) { - setActionCallback(new param1.currentTarget.constructor()); + _lastAction = new param1.currentTarget.constructor(); + setActionCallback(_lastAction); actionBtn.dispatchEvent(new MouseEvent("mouseDown")); param1.currentTarget.downToUpState(); } diff --git a/swf-src/AvatarUtility.as b/swf-src/AvatarUtility.as new file mode 100644 index 0000000..7678c4e --- /dev/null +++ b/swf-src/AvatarUtility.as @@ -0,0 +1,2161 @@ +package avatar +{ + import collection.AccItemCollection; + import com.sbi.bit.BitUtility; + import diamond.DiamondItem; + import diamond.DiamondXtCommManager; + import flash.events.MouseEvent; + import flash.geom.Point; + import gui.GuiManager; + import item.EquippedAvatars; + import item.Item; + import item.ItemXtCommManager; + + public class AvatarUtility + { + + public static const AVT_AVAIL_HIDDEN:int = 0; + + public static const AVT_AVAIL_ACTIVE:int = 1; + + public static const AVT_AVAIL_ENDANGERED:int = 2; + + public static const AVT_AVAIL_EXTINCT:int = 3; + + private static var _creationAvatars:Array; + + private static var _avatarDefInfo:Array; + + private static var _skippedIndexes:Array; + + private static var _avtMgrGetAvtByPerUserAvId:Function; + + private static var _numViewsLoaded:int; + + private static var _numNonMemberAvatars:Function; + + private static var _currDiamondAvatarStoreDefs:Array; + + private static var _diamondAvatarListData:Array; + + private static var _onAvatarListLoaded:Function; + + public function AvatarUtility() + { + super(); + } + + public static function init(param1:Function, param2:Function = null, param3:Boolean = true, param4:Function = null) : void + { + _avtMgrGetAvtByPerUserAvId = param1; + _numNonMemberAvatars = param2; + _onAvatarListLoaded = param4; + GenericListXtCommManager.requestGenericList(64,buildCreationAvatarViews,null,param3); + } + + public static function buildCreationAvatarViews(param1:Array, param2:Boolean = false, param3:Function = null) : void + { + var _loc13_:int = 0; + var _loc4_:int = 0; + var _loc21_:Avatar = null; + var _loc9_:int = 0; + var _loc17_:int = 0; + var _loc18_:Item = null; + var _loc15_:int = 0; + var _loc14_:int = 0; + var _loc16_:Object = null; + var _loc7_:Object = null; + var _loc12_:int = 0; + var _loc6_:Object = null; + var _loc19_:* = undefined; + var _loc8_:int = 0; + var _loc20_:CustomAvatarDef = null; + var _loc10_:int = 0; + if(param3 != null) + { + _onAvatarListLoaded = param3; + } + _skippedIndexes = []; + var _loc11_:int = int(param1.length); + var _loc5_:int = 0; + if(_creationAvatars) + { + if(_creationAvatars.length > 0) + { + _loc12_ = 0; + while(_loc12_ < _creationAvatars.length) + { + _creationAvatars[_loc12_].destroy(); + _loc12_++; + } + } + } + _avatarDefInfo = new Array(_loc11_); + _creationAvatars = []; + _loc14_ = 0; + _loc13_ = 0; + _loc4_ = 0; + while(_loc14_ < _loc11_) + { + _loc6_ = gMainFrame.userInfo.getAvatarDefByAvType(param1[_loc14_],false); + if(_loc6_) + { + if(isAvatarActive(_loc6_.availability) && (!param2 || param2 && !_loc6_.isMemOnly && !isExtinct(_loc6_.availability) && Utility.isLand(_loc6_.enviroTypeFlag))) + { + _loc17_ = int(param1[_loc14_]); + _avatarDefInfo[_loc4_ - _loc5_] = { + "isMemberOnly":_loc6_.isMemOnly, + "enviroFlag":_loc6_.enviroTypeFlag, + "recycleValue":Math.ceil(_loc6_.cost * 0.5), + "cost":(_loc6_.status == 2 ? Math.ceil(_loc6_.cost * 0.5) : _loc6_.cost), + "availability":_loc6_.availability, + "status":_loc6_.status, + "isDiamond":false, + "diamondItem":null, + "diamondCost":0 + }; + _loc21_ = new Avatar(); + _loc21_.init(0,0,"",_loc17_,[_loc6_.colorLayer1,_loc6_.colorLayer2,_loc6_.colorLayer3]); + if(!param2) + { + _loc16_ = ItemXtCommManager.getItemDef(_loc6_.defEyes); + _loc7_ = ItemXtCommManager.getItemDef(_loc6_.defPattern); + if(_loc16_ == null) + { + _skippedIndexes[_loc14_] = true; + _loc5_++; + _loc4_++; + _loc14_++; + continue; + } + _loc18_ = new Item(); + _loc18_.init(1,_loc13_++,0,EquippedAvatars.forced()); + _loc21_.inventoryBodyMod.addItem(_loc18_); + _loc21_.accStateShowAccessory(_loc18_); + _loc18_ = new Item(); + _loc18_.init(_loc16_.defId,_loc13_++,_loc16_.colors,EquippedAvatars.forced()); + _loc21_.inventoryBodyMod.addItem(_loc18_); + _loc21_.accStateShowAccessory(_loc18_); + if(_loc7_) + { + _loc18_ = new Item(); + _loc18_.init(_loc7_.defId,_loc13_++,_loc7_.colors,EquippedAvatars.forced()); + _loc21_.inventoryBodyMod.addItem(_loc18_); + _loc21_.accStateShowAccessory(_loc18_); + } + } + _creationAvatars.push(_loc21_); + _skippedIndexes[_loc14_] = false; + if(!param2) + { + _loc19_ = gMainFrame.userInfo.getCustomAvatarDefsByAvRefId(_loc17_); + if(_loc19_) + { + _loc8_ = 0; + while(_loc8_ < _loc19_.length) + { + _loc20_ = _loc19_[_loc8_]; + if(_loc20_) + { + _loc21_ = new Avatar(); + _loc21_.init(0,0,"",_loc20_.avatarRefId,[_loc20_.colorLayer1,_loc20_.colorLayer2,_loc20_.colorLayer3],_loc20_.defId); + _loc16_ = ItemXtCommManager.getItemDef(_loc20_.defEyes); + if(_loc16_ == null) + { + _skippedIndexes[_loc14_] = true; + } + else + { + _loc18_ = new Item(); + _loc18_.init(1,_loc13_++,0,EquippedAvatars.forced()); + _loc21_.inventoryBodyMod.addItem(_loc18_); + _loc21_.accStateShowAccessory(_loc18_); + _loc18_ = new Item(); + _loc18_.init(_loc16_.defId,_loc13_++,_loc16_.colors,EquippedAvatars.forced()); + _loc21_.inventoryBodyMod.addItem(_loc18_); + _loc21_.accStateShowAccessory(_loc18_); + _loc10_ = 0; + while(_loc10_ < _loc20_.patternRefIds.length) + { + _loc7_ = ItemXtCommManager.getItemDef(_loc20_.patternRefIds[_loc10_]); + if(_loc7_) + { + _loc18_ = new Item(); + _loc18_.init(_loc7_.defId,_loc13_++,_loc7_.colors,EquippedAvatars.forced()); + _loc21_.inventoryBodyMod.addItem(_loc18_); + _loc21_.accStateShowAccessory(_loc18_); + } + _loc10_++; + } + _creationAvatars.push(_loc21_); + _loc4_++; + _avatarDefInfo[_loc4_ - _loc5_] = { + "isMemberOnly":_loc20_.isMemOnly, + "enviroFlag":_loc20_.enviroTypeFlag, + "recycleValue":Math.ceil(_loc20_.cost * 0.5), + "cost":(_loc20_.status == 2 ? Math.ceil(_loc20_.cost * 0.5) : _loc20_.cost), + "availability":_loc20_.availability, + "status":_loc20_.status, + "isDiamond":false, + "diamondItem":null, + "diamondCost":0 + }; + } + } + _loc8_++; + } + if(_skippedIndexes[_loc14_]) + { + _loc5_++; + _loc4_++; + _loc14_++; + continue; + } + } + } + } + else + { + _skippedIndexes[_loc14_] = true; + _loc5_++; + } + } + else + { + _skippedIndexes[_loc14_] = true; + _loc5_++; + } + _loc4_++; + _loc14_++; + } + GenericListXtCommManager.requestGenericList(166,onCurrDiamondAvatarStoreList,null,true); + GenericListXtCommManager.requestGenericList(293,onDiamondAvatarListLoaded,null,true); + } + + private static function onCurrDiamondAvatarStoreList(param1:int, param2:Array) : void + { + _currDiamondAvatarStoreDefs = param2.slice(8); + if(_diamondAvatarListData != null) + { + onDiamondAvatarListLoaded(293,_diamondAvatarListData); + } + } + + private static function onDiamondAvatarListLoaded(param1:int, param2:Array) : void + { + var j:int; + var numItems:int; + var diamondItem:DiamondItem; + var avt:Avatar; + var avatarDef:Object; + var avatarRefId:int; + var i:int; + var glId:int = param1; + var cad:Array = param2; + if(_currDiamondAvatarStoreDefs != null) + { + j = 8; + numItems = int(cad[j++]); + i = 0; + while(i < numItems) + { + diamondItem = DiamondXtCommManager.getDiamondItem(int(cad[j++])); + if(diamondItem && (diamondItem.isAvatar || diamondItem.isAvatarCustom)) + { + if(diamondItem.isAvatarCustom) + { + avatarRefId = int(gMainFrame.userInfo.getCustomAvatarDefByAvType(diamondItem.refDefId).avatarRefId); + } + else + { + avatarRefId = diamondItem.refDefId; + } + avt = AvatarUtility._creationAvatars[AvatarUtility.findAvatarIndexByType(avatarRefId,diamondItem.isAvatarCustom ? diamondItem.refDefId : -1)]; + if(avt && (getAvatarDefIsViewable(avt,avt.customAvId != -1) || _currDiamondAvatarStoreDefs.some((function():* + { + var isSame:Function; + return isSame = function(param1:*, param2:int, param3:Array):Boolean + { + return int(param1) == diamondItem.defId; + }; + })()))) + { + avatarDef = findAvDefByType(avt.avTypeId,diamondItem.isAvatarCustom ? diamondItem.refDefId : -1); + avatarDef.diamondItem = diamondItem; + avatarDef.isDiamond = true; + } + } + i = i + 1; + } + if(_onAvatarListLoaded != null) + { + _onAvatarListLoaded(); + _onAvatarListLoaded = null; + } + } + else + { + _diamondAvatarListData = cad; + } + } + + public static function getAvatarDefIsViewable(param1:Avatar, param2:Boolean = false) : Boolean + { + var _loc3_:Number = Number(gMainFrame.userInfo.userVarCache.getUserVarValueById(param2 ? 410 : 287)); + _loc3_ |= 0; + param2 ? _loc3_ : 0; + var _loc4_:int = param2 ? param1.customAvId : param1.avTypeId; + return BitUtility.bitwiseAnd(_loc3_,BitUtility.leftShiftNumbers(_loc4_ - 1)) > 0; + } + + public static function getAvatarDefIsViewableWithAvId(param1:int, param2:int = -1) : Boolean + { + var _loc3_:Number = Number(gMainFrame.userInfo.userVarCache.getUserVarValueById(param2 != -1 ? 410 : 287)); + _loc3_ |= 0; + param2 != -1 ? _loc3_ : 0; + return BitUtility.bitwiseAnd(_loc3_,BitUtility.leftShiftNumbers(param2 != -1 ? param2 - 1 : param1 - 1)) > 0; + } + + public static function generateNew(param1:int, param2:Avatar = null, param3:String = null, param4:int = -1, param5:int = 0, param6:Function = null, param7:Boolean = false, param8:Boolean = false) : Avatar + { + var _loc9_:AvatarInfo = null; + var _loc10_:Avatar = null; + if(param2 == null && _avtMgrGetAvtByPerUserAvId != null) + { + _loc10_ = _avtMgrGetAvtByPerUserAvId(param3,param1); + } + if(!_loc10_) + { + if(param2) + { + _loc10_ = param2; + } + else + { + _loc10_ = new Avatar(); + } + if(_loc10_.userName == null) + { + if(param3 == null) + { + throw new Error("avt and paramUserName are both null!!!"); + } + _loc10_.userName = param3; + } + _loc9_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(param3,param1); + if(_loc9_ && _loc9_.uuid != "") + { + _loc10_.init(param1,_loc9_.avInvId,_loc9_.avName,_loc9_.type,_loc9_.colors,_loc9_.customAvId,null,_loc9_.userName,param4,param5); + getAvatarItemData(_loc10_,param6,_loc9_,param8); + } + else + { + _loc10_.init(param1,_loc9_ ? _loc9_.avInvId : -1,"",_loc9_ ? _loc9_.type : -1,[0,0,0],_loc9_ ? _loc9_.customAvId : -1,null,_loc10_.userName,param4); + if(param7 == false) + { + AvatarXtCommManager.requestADForAvatar(param1,true,param6,_loc10_); + } + } + } + return _loc10_; + } + + public static function getAvatarItemData(param1:Avatar, param2:Function = null, param3:AvatarInfo = null, param4:Boolean = false) : void + { + if(param1 == null || param1.perUserAvId < 0) + { + throw new Error("Invalid avatar!"); + } + if(param3 == null) + { + param3 = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(param1.userName,param1.perUserAvId); + if(param3 == null) + { + throw new Error("Invalid avatar or avInfo!"); + } + } + var _loc5_:AccItemCollection = null; + if(param4) + { + _loc5_ = param3.getFullItems(true); + } + else + { + _loc5_ = param3.getItems(true); + } + if(_loc5_ && _loc5_.length > 0 && param1.uuid != "") + { + param1.itemResponseIntegrate(_loc5_,param4); + } + else if(param1.uuid != "") + { + ItemXtCommManager.requestItemListForAvatar(null,param1,param1.userName.toLowerCase() == gMainFrame.userInfo.myUserName.toLowerCase() ? !ItemXtCommManager.hasRequestedFullItemList : false); + } + else + { + AvatarXtCommManager.requestADForAvatar(param1.perUserAvId,true,param2,param1,param4); + } + } + + public static function layerArrayForItemsAndColors(param1:AccItemCollection, param2:Array, param3:int, param4:int, param5:Boolean = false) : Array + { + var _loc7_:Object = null; + var _loc6_:* = 0; + var _loc8_:Array = []; + if(param1) + { + for each(var _loc9_:Item in param1.getCoreArray()) + { + if((_loc9_.layerId <= 3 || (param5 || _loc9_.enviroType == param4 || _loc9_.isLandAndOcean)) && _loc9_.getInUse(param3)) + { + if(_loc9_.layerId == 1) + { + _loc6_ = uint(param2[0]); + } + else if(_loc9_.layerId == 2) + { + _loc6_ = uint(param2[1]); + } + else if(_loc9_.layerId == 3) + { + _loc6_ = uint(param2[2]); + } + else + { + _loc6_ = _loc9_.color; + } + // "d": the item, for a custom one's own picture (LayerAnim, LayerBitmap) + _loc7_ = { + "l":_loc9_.accId, + "c":_loc6_, + "d":_loc9_.defId + }; + _loc8_.push(_loc7_); + } + } + } + return _loc8_; + } + + public static function getAvatarByIndex(param1:int) : Avatar + { + return _creationAvatars[param1]; + } + + public static function getAvatarDefByIndex(param1:int) : Object + { + if(_avatarDefInfo) + { + return _avatarDefInfo[param1]; + } + return null; + } + + public static function get numAvatarDefs() : int + { + if(_avatarDefInfo) + { + return _avatarDefInfo.length; + } + return 0; + } + + public static function get creationAvatarsList() : Array + { + return _creationAvatars; + } + + public static function findCreationAvatarByType(param1:int, param2:int) : Avatar + { + var _loc3_:int = 0; + _loc3_ = 0; + while(_loc3_ < _creationAvatars.length) + { + if(_creationAvatars[_loc3_] && _creationAvatars[_loc3_].avTypeId == param1 && _creationAvatars[_loc3_].customAvId == param2) + { + return _creationAvatars[_loc3_]; + } + _loc3_++; + } + return null; + } + + public static function findAvatarIndexByType(param1:int, param2:int) : int + { + var _loc3_:int = 0; + _loc3_ = 0; + while(_loc3_ < _creationAvatars.length) + { + if(_creationAvatars[_loc3_] && _creationAvatars[_loc3_].avTypeId == param1 && _creationAvatars[_loc3_].customAvId == param2) + { + return _loc3_; + } + _loc3_++; + } + return -1; + } + + public static function findAvDefByType(param1:int, param2:int) : Object + { + var _loc3_:int = findAvatarIndexByType(param1,param2); + if(_loc3_ != -1) + { + return _avatarDefInfo[_loc3_]; + } + return null; + } + + public static function numNonMemberAvatars() : int + { + if(_numNonMemberAvatars != null) + { + return _numNonMemberAvatars(); + } + return 0; + } + + private static function nameTypeScreenMouseDownHandler(param1:MouseEvent) : void + { + param1.stopPropagation(); + } + + public static function getAvatarHudPosition(param1:int) : Point + { + var _loc2_:Number = NaN; + var _loc3_:Number = NaN; + switch(param1) + { + case 1: + _loc3_ = 228; + _loc2_ = 220; + break; + case 2: + _loc3_ = 213; + _loc2_ = 318; + break; + case 35: + _loc3_ = 213; + _loc2_ = 308; + break; + case 4: + _loc3_ = 226; + _loc2_ = 217; + break; + case 5: + _loc3_ = 228; + _loc2_ = 220; + break; + case 6: + _loc3_ = 225; + _loc2_ = 215; + break; + case 7: + _loc3_ = 228; + _loc2_ = 216; + break; + case 8: + _loc3_ = 231; + _loc2_ = 216; + break; + case 13: + _loc3_ = 230; + _loc2_ = 216; + break; + case 15: + _loc3_ = 222; + _loc2_ = 216; + break; + case 16: + _loc3_ = 230; + _loc2_ = 216; + break; + case 18: + _loc3_ = 222; + _loc2_ = 213; + break; + case 19: + _loc3_ = 216; + _loc2_ = 250; + break; + case 20: + _loc3_ = 222; + _loc2_ = 245; + break; + case 17: + _loc3_ = 232; + _loc2_ = 216; + break; + case 23: + _loc3_ = 232; + _loc2_ = 220; + break; + case 22: + _loc3_ = 225; + _loc2_ = 237; + break; + case 24: + _loc3_ = 223; + _loc2_ = 217; + break; + case 21: + _loc3_ = 221; + _loc2_ = 249; + break; + case 26: + _loc3_ = 220; + _loc2_ = 215; + break; + case 25: + _loc3_ = 216; + _loc2_ = 218; + break; + case 28: + _loc3_ = 222; + _loc2_ = 222; + break; + case 29: + _loc3_ = 220; + _loc2_ = 223; + break; + case 30: + _loc3_ = 220; + _loc2_ = 212; + break; + case 31: + _loc3_ = 220; + _loc2_ = 215; + break; + case 27: + _loc3_ = 220; + _loc2_ = 212; + break; + case 3: + _loc3_ = 225; + _loc2_ = 220; + break; + case 9: + _loc3_ = 225; + _loc2_ = 220; + break; + case 10: + _loc3_ = 227; + _loc2_ = 220; + break; + case 11: + _loc3_ = 221; + _loc2_ = 218; + break; + case 12: + _loc3_ = 221; + _loc2_ = 218; + break; + case 14: + _loc3_ = 221; + _loc2_ = 215; + break; + case 32: + case 33: + _loc3_ = 224; + _loc2_ = 218; + break; + case 34: + _loc3_ = 224; + _loc2_ = 215; + break; + case 36: + _loc3_ = 224; + _loc2_ = 220; + break; + case 37: + _loc3_ = 219; + _loc2_ = 209; + break; + case 38: + _loc3_ = 219; + _loc2_ = 238; + break; + case 39: + _loc3_ = 240; + _loc2_ = 340; + break; + case 40: + _loc3_ = 235; + _loc2_ = 215; + break; + case 41: + case 42: + _loc3_ = 219; + _loc2_ = 219; + break; + case 43: + _loc3_ = 235; + _loc2_ = 216; + break; + case 44: + _loc3_ = 220; + _loc2_ = 214; + break; + case 45: + _loc3_ = 230; + _loc2_ = 310; + break; + case 46: + _loc3_ = 225; + _loc2_ = 305; + break; + case 47: + _loc3_ = 229; + _loc2_ = 305; + break; + case 49: + _loc3_ = 225; + _loc2_ = 350; + break; + case 48: + _loc3_ = 232; + _loc2_ = 215; + break; + case 50: + _loc3_ = 227; + _loc2_ = 215; + break; + case 51: + _loc3_ = 227; + _loc2_ = 217; + break; + case 52: + _loc3_ = 230; + _loc2_ = 219; + break; + case 53: + _loc3_ = 235; + _loc2_ = 215; + break; + default: + _loc3_ = 225; + _loc2_ = 200; + } + return new Point(_loc3_,_loc2_); + } + + public static function getAvatarViewPosition(param1:int) : Point + { + var _loc2_:Point = new Point(); + switch(param1) + { + case 1: + _loc2_.x = 137; + _loc2_.y = 85; + break; + case 2: + _loc2_.x = 120; + _loc2_.y = 150; + break; + case 35: + _loc2_.x = 120; + _loc2_.y = 140; + break; + case 4: + _loc2_.x = 136; + _loc2_.y = 85; + break; + case 5: + _loc2_.x = 133; + _loc2_.y = 85; + break; + case 6: + _loc2_.x = 131; + _loc2_.y = 90; + break; + case 7: + _loc2_.x = 136; + _loc2_.y = 95; + break; + case 8: + _loc2_.x = 140; + _loc2_.y = 85; + break; + case 13: + _loc2_.x = 125; + _loc2_.y = 95; + break; + case 15: + _loc2_.x = 127; + _loc2_.y = 130; + break; + case 16: + _loc2_.x = 134; + _loc2_.y = 80; + break; + case 18: + _loc2_.x = 131; + _loc2_.y = 75; + break; + case 19: + _loc2_.x = 125; + _loc2_.y = 90; + break; + case 20: + _loc2_.x = 127; + _loc2_.y = 120; + break; + case 17: + _loc2_.x = 140; + _loc2_.y = 100; + break; + case 23: + _loc2_.x = 130; + _loc2_.y = 100; + break; + case 22: + _loc2_.x = 125; + _loc2_.y = 117; + break; + case 24: + _loc2_.x = 129; + _loc2_.y = 95; + break; + case 21: + _loc2_.x = 128; + _loc2_.y = 95; + break; + case 26: + _loc2_.x = 124; + _loc2_.y = 110; + break; + case 25: + _loc2_.x = 123; + _loc2_.y = 115; + break; + case 28: + _loc2_.x = 129; + _loc2_.y = 99; + break; + case 29: + _loc2_.x = 127; + _loc2_.y = 115; + break; + case 30: + _loc2_.x = 127; + _loc2_.y = 115; + break; + case 31: + _loc2_.x = 127; + _loc2_.y = 115; + break; + case 27: + _loc2_.x = 127; + _loc2_.y = 110; + break; + case 3: + _loc2_.x = 130; + _loc2_.y = 100; + break; + case 9: + _loc2_.x = 140; + _loc2_.y = 100; + break; + case 10: + _loc2_.x = 134; + _loc2_.y = 97; + break; + case 11: + _loc2_.x = 130; + _loc2_.y = 97; + break; + case 12: + _loc2_.x = 127; + _loc2_.y = 90; + break; + case 14: + case 34: + _loc2_.x = 127; + _loc2_.y = 90; + break; + case 32: + case 33: + _loc2_.x = 130; + _loc2_.y = 115; + break; + case 36: + _loc2_.x = 125; + _loc2_.y = 95; + break; + case 37: + _loc2_.x = 125; + _loc2_.y = 90; + break; + case 38: + _loc2_.x = 128; + _loc2_.y = 110; + break; + case 39: + _loc2_.x = 135; + _loc2_.y = 225; + break; + case 40: + _loc2_.x = 145; + _loc2_.y = 80; + break; + case 41: + case 42: + _loc2_.x = 115; + _loc2_.y = 95; + break; + case 43: + _loc2_.x = 140; + _loc2_.y = 115; + break; + case 44: + _loc2_.x = 135; + _loc2_.y = 105; + break; + case 45: + _loc2_.x = 135; + _loc2_.y = 165; + break; + case 46: + _loc2_.x = 130; + _loc2_.y = 175; + break; + case 47: + _loc2_.x = 135; + _loc2_.y = 185; + break; + case 49: + _loc2_.x = 125; + _loc2_.y = 220; + break; + case 48: + _loc2_.x = 135; + _loc2_.y = 120; + break; + case 50: + _loc2_.x = 125; + _loc2_.y = 100; + break; + case 51: + _loc2_.x = 127; + _loc2_.y = 110; + break; + case 52: + _loc2_.x = 135; + _loc2_.y = 105; + break; + case 53: + _loc2_.x = 155; + _loc2_.y = 100; + break; + default: + _loc2_.x = 112; + _loc2_.y = 140; + } + return _loc2_; + } + + public static function getAvatarChatOffset(param1:int) : Point + { + var _loc2_:Point = new Point(); + if(GuiManager.isBeYourPetRoom()) + { + if(AvatarManager.playerAvatarWorldView) + { + _loc2_.x = 10; + _loc2_.y = -80; + } + else + { + _loc2_.x = 10; + _loc2_.y = -90; + } + } + else + { + switch(param1) + { + case 1: + _loc2_.x = 10; + _loc2_.y = -70; + break; + case 2: + _loc2_.x = 10; + _loc2_.y = -130; + break; + case 35: + _loc2_.x = 0; + _loc2_.y = -110; + break; + case 4: + _loc2_.x = 5; + _loc2_.y = -80; + break; + case 5: + _loc2_.x = -25; + _loc2_.y = -75; + break; + case 6: + _loc2_.x = -15; + _loc2_.y = -85; + break; + case 7: + _loc2_.x = -25; + _loc2_.y = -75; + break; + case 8: + _loc2_.x = -25; + _loc2_.y = -75; + break; + case 13: + _loc2_.x = -10; + _loc2_.y = -95; + break; + case 15: + _loc2_.x = -10; + _loc2_.y = -90; + break; + case 16: + _loc2_.x = -10; + _loc2_.y = -105; + break; + case 18: + _loc2_.x = -15; + _loc2_.y = -60; + break; + case 19: + _loc2_.x = -10; + _loc2_.y = -95; + break; + case 20: + _loc2_.x = -15; + _loc2_.y = -88; + break; + case 17: + _loc2_.x = -15; + _loc2_.y = -90; + break; + case 23: + _loc2_.x = -20; + _loc2_.y = -104; + break; + case 22: + _loc2_.x = -10; + _loc2_.y = -75; + break; + case 24: + _loc2_.x = -16; + _loc2_.y = -95; + break; + case 21: + _loc2_.x = -25; + _loc2_.y = -95; + break; + case 26: + _loc2_.x = -17; + _loc2_.y = -130; + break; + case 25: + _loc2_.x = -17; + _loc2_.y = -88; + break; + case 28: + _loc2_.x = -7; + _loc2_.y = -113; + break; + case 29: + _loc2_.x = -7; + _loc2_.y = -99; + break; + case 30: + _loc2_.x = -2; + _loc2_.y = -58; + break; + case 31: + _loc2_.x = 0; + _loc2_.y = -80; + break; + case 27: + _loc2_.x = -2; + _loc2_.y = -95; + break; + case 3: + _loc2_.x = -2; + _loc2_.y = -135; + break; + case 9: + _loc2_.x = -5; + _loc2_.y = -85; + break; + case 10: + _loc2_.x = -10; + _loc2_.y = -83; + break; + case 11: + _loc2_.x = -5; + _loc2_.y = -100; + break; + case 12: + _loc2_.x = -10; + _loc2_.y = -120; + break; + case 14: + _loc2_.x = -2; + _loc2_.y = -115; + break; + case 32: + case 33: + case 34: + _loc2_.x = -8; + _loc2_.y = -83; + break; + case 36: + _loc2_.x = -8; + _loc2_.y = -70; + break; + case 37: + case 38: + _loc2_.x = -8; + _loc2_.y = -73; + break; + case 39: + _loc2_.x = -20; + _loc2_.y = -110; + break; + case 40: + _loc2_.x = -28; + _loc2_.y = -85; + break; + case 41: + _loc2_.x = -5; + _loc2_.y = -110; + break; + case 42: + _loc2_.x = -20; + _loc2_.y = -110; + break; + case 43: + _loc2_.x = -20; + _loc2_.y = -110; + break; + case 44: + _loc2_.x = -10; + _loc2_.y = -90; + break; + case 45: + _loc2_.x = -10; + _loc2_.y = -115; + break; + case 46: + _loc2_.x = -5; + _loc2_.y = -85; + break; + case 47: + _loc2_.x = -5; + _loc2_.y = -95; + break; + case 49: + _loc2_.x = -5; + _loc2_.y = -155; + break; + case 48: + _loc2_.x = -10; + _loc2_.y = -65; + break; + case 51: + case 52: + case 53: + _loc2_.x = -10; + _loc2_.y = -110; + break; + case 50: + default: + _loc2_.x = -25; + _loc2_.y = -75; + } + } + return _loc2_; + } + + public static function getAvatarEmoteBgOffset(param1:int) : Point + { + var _loc2_:Point = new Point(); + if(GuiManager.isBeYourPetRoom()) + { + if(AvatarManager.playerAvatarWorldView) + { + _loc2_.x = -5; + _loc2_.y = -25; + } + else + { + _loc2_.x = -5; + _loc2_.y = -35; + } + } + else + { + switch(param1) + { + case 1: + _loc2_.x = -5; + _loc2_.y = -30; + break; + case 2: + _loc2_.x = -5; + _loc2_.y = -35; + break; + case 35: + _loc2_.x = -15; + _loc2_.y = -23; + break; + case 4: + _loc2_.x = -5; + _loc2_.y = -45; + break; + case 5: + _loc2_.x = 8; + _loc2_.y = -40; + break; + case 6: + _loc2_.x = 5; + _loc2_.y = -35; + break; + case 7: + _loc2_.x = -5; + _loc2_.y = -35; + break; + case 8: + _loc2_.x = -5; + _loc2_.y = -35; + break; + case 13: + _loc2_.x = -10; + _loc2_.y = -25; + break; + case 15: + _loc2_.x = 5; + _loc2_.y = -15; + break; + case 16: + _loc2_.x = 5; + _loc2_.y = -35; + break; + case 18: + _loc2_.x = 0; + _loc2_.y = -30; + break; + case 19: + _loc2_.x = 0; + _loc2_.y = -20; + break; + case 20: + _loc2_.x = 0; + _loc2_.y = -30; + break; + case 17: + _loc2_.x = 0; + _loc2_.y = -45; + break; + case 23: + _loc2_.x = 5; + _loc2_.y = -37; + break; + case 22: + case 24: + _loc2_.x = 0; + _loc2_.y = -30; + break; + case 21: + _loc2_.x = -5; + _loc2_.y = -55; + break; + case 26: + _loc2_.x = 5; + _loc2_.y = -42; + break; + case 25: + _loc2_.x = 10; + _loc2_.y = -33; + break; + case 28: + _loc2_.x = -1; + _loc2_.y = -35; + break; + case 29: + _loc2_.x = -1; + _loc2_.y = -15; + break; + case 30: + _loc2_.x = -8; + _loc2_.y = -24; + break; + case 31: + _loc2_.x = -6; + _loc2_.y = -30; + break; + case 27: + _loc2_.x = -8; + _loc2_.y = -28; + break; + case 3: + _loc2_.x = -8; + _loc2_.y = -30; + break; + case 9: + _loc2_.x = -5; + _loc2_.y = -33; + break; + case 10: + _loc2_.x = -10; + _loc2_.y = -33; + break; + case 11: + _loc2_.x = -10; + _loc2_.y = -33; + break; + case 12: + _loc2_.x = -10; + _loc2_.y = -40; + break; + case 14: + _loc2_.x = -2; + _loc2_.y = -33; + break; + case 32: + case 33: + case 34: + _loc2_.x = -10; + _loc2_.y = -28; + break; + case 36: + _loc2_.x = -10; + _loc2_.y = -35; + break; + case 37: + case 38: + _loc2_.x = -5; + _loc2_.y = -39; + break; + case 39: + _loc2_.x = -10; + _loc2_.y = -40; + break; + case 40: + _loc2_.x = -15; + _loc2_.y = -35; + break; + case 41: + case 42: + case 43: + case 44: + case 45: + case 46: + case 47: + case 49: + case 48: + case 50: + case 51: + case 52: + case 53: + _loc2_.x = -5; + _loc2_.y = -35; + break; + case 49: + _loc2_.x = -5; + _loc2_.y = -80; + break; + default: + _loc2_.x = -5; + _loc2_.y = -45; + } + } + return _loc2_; + } + + public static function getAnimalItemWindowOffset(param1:int) : Point + { + var _loc2_:Point = new Point(); + switch(param1) + { + case 1: + _loc2_.x = 123; + _loc2_.y = 34; + break; + case 2: + _loc2_.x = 90; + _loc2_.y = 135; + break; + case 35: + _loc2_.x = 104; + _loc2_.y = 125; + break; + case 4: + _loc2_.x = 134; + _loc2_.y = 45; + break; + case 5: + _loc2_.x = 127; + _loc2_.y = 58; + break; + case 6: + _loc2_.x = 124; + _loc2_.y = 50; + break; + case 7: + _loc2_.x = 133; + _loc2_.y = 54; + break; + case 8: + _loc2_.x = 138; + _loc2_.y = 65; + break; + case 13: + _loc2_.x = 120; + _loc2_.y = 85; + break; + case 15: + _loc2_.x = 133; + _loc2_.y = 85; + break; + case 16: + _loc2_.x = 125; + _loc2_.y = 52; + break; + case 18: + _loc2_.x = 127; + _loc2_.y = 38; + break; + case 19: + _loc2_.x = 125; + _loc2_.y = 75; + break; + case 20: + _loc2_.x = 128; + _loc2_.y = 80; + break; + case 17: + _loc2_.x = 135; + _loc2_.y = 60; + break; + case 23: + _loc2_.x = 135; + _loc2_.y = 75; + break; + case 22: + _loc2_.x = 120; + _loc2_.y = 67; + break; + case 24: + _loc2_.x = 127; + _loc2_.y = 62; + break; + case 21: + case 36: + _loc2_.x = 122; + _loc2_.y = 62; + break; + case 26: + _loc2_.x = 122; + _loc2_.y = 78; + break; + case 25: + case 10: + _loc2_.x = 127; + _loc2_.y = 72; + break; + case 28: + _loc2_.x = 127; + _loc2_.y = 90; + break; + case 29: + _loc2_.x = 127; + _loc2_.y = 90; + break; + case 30: + _loc2_.x = 114; + _loc2_.y = 98; + break; + case 31: + _loc2_.x = 122; + _loc2_.y = 70; + break; + case 27: + _loc2_.x = 128; + _loc2_.y = 65; + break; + case 3: + _loc2_.x = 132; + _loc2_.y = 70; + break; + case 9: + _loc2_.x = 145; + _loc2_.y = 70; + break; + case 11: + _loc2_.x = 125; + _loc2_.y = 68; + break; + case 12: + _loc2_.x = 130; + _loc2_.y = 77; + break; + case 14: + case 34: + _loc2_.x = 122; + _loc2_.y = 68; + break; + case 32: + case 33: + _loc2_.x = 120; + _loc2_.y = 90; + break; + case 37: + _loc2_.x = 125; + _loc2_.y = 60; + break; + case 38: + _loc2_.x = 130; + _loc2_.y = 90; + break; + case 39: + _loc2_.x = 132; + _loc2_.y = 180; + break; + case 40: + _loc2_.x = 142; + _loc2_.y = 65; + break; + case 41: + _loc2_.x = 115; + _loc2_.y = 65; + break; + case 42: + _loc2_.x = 130; + _loc2_.y = 65; + break; + case 43: + _loc2_.x = 145; + _loc2_.y = 90; + break; + case 44: + _loc2_.x = 135; + _loc2_.y = 80; + break; + case 45: + _loc2_.x = 138; + _loc2_.y = 150; + break; + case 46: + _loc2_.x = 130; + _loc2_.y = 145; + break; + case 47: + _loc2_.x = 140; + _loc2_.y = 160; + break; + case 49: + _loc2_.x = 130; + _loc2_.y = 195; + break; + case 48: + _loc2_.x = 140; + _loc2_.y = 100; + break; + case 50: + _loc2_.x = 120; + _loc2_.y = 80; + break; + case 51: + _loc2_.x = 140; + _loc2_.y = 95; + break; + case 52: + _loc2_.x = 145; + _loc2_.y = 75; + break; + case 53: + _loc2_.x = 165; + _loc2_.y = 85; + break; + default: + _loc2_.x = 120; + _loc2_.y = 50; + } + return _loc2_; + } + + public static function getTalkingHeadOffset(param1:int) : Point + { + var _loc2_:Point = new Point(); + var _loc3_:int = param1; + _loc2_.x = 112; + _loc2_.y = 140; + return _loc2_; + } + + public static function getAvatarPhotoOffset(param1:int) : Point + { + var _loc2_:Point = new Point(); + switch(param1) + { + case 1: + _loc2_.x = -150; + _loc2_.y = -160; + break; + case 2: + _loc2_.x = -195; + _loc2_.y = -60; + break; + case 35: + _loc2_.x = -155; + _loc2_.y = -95; + break; + case 4: + _loc2_.x = -155; + _loc2_.y = -190; + break; + case 5: + _loc2_.x = -152; + _loc2_.y = -140; + break; + case 6: + _loc2_.x = -130; + _loc2_.y = -158; + break; + case 7: + _loc2_.x = -140; + _loc2_.y = -175; + break; + case 8: + _loc2_.x = -145; + _loc2_.y = -192; + break; + case 13: + _loc2_.x = -160; + _loc2_.y = -155; + break; + case 15: + _loc2_.x = -165; + _loc2_.y = -125; + break; + case 16: + _loc2_.x = -162; + _loc2_.y = -148; + break; + case 18: + _loc2_.x = -107; + _loc2_.y = -140; + break; + case 19: + _loc2_.x = -160; + _loc2_.y = -190; + break; + case 20: + _loc2_.x = -160; + _loc2_.y = -190; + break; + case 17: + _loc2_.x = -155; + _loc2_.y = -150; + break; + case 23: + _loc2_.x = -130; + _loc2_.y = -185; + break; + case 22: + _loc2_.x = -160; + _loc2_.y = -190; + break; + case 24: + _loc2_.x = -162; + _loc2_.y = -180; + break; + case 21: + _loc2_.x = -160; + _loc2_.y = -190; + break; + case 26: + _loc2_.x = -140; + _loc2_.y = -160; + break; + case 25: + _loc2_.x = -165; + _loc2_.y = -175; + break; + case 28: + _loc2_.x = -150; + _loc2_.y = -165; + break; + case 29: + _loc2_.x = -145; + _loc2_.y = -180; + break; + case 30: + _loc2_.x = -140; + _loc2_.y = -165; + break; + case 31: + _loc2_.x = -135; + _loc2_.y = -145; + break; + case 27: + _loc2_.x = -145; + _loc2_.y = -160; + break; + case 3: + _loc2_.x = -145; + _loc2_.y = -160; + break; + case 9: + _loc2_.x = -130; + _loc2_.y = -130; + break; + case 10: + _loc2_.x = -125; + _loc2_.y = -175; + break; + case 11: + _loc2_.x = -125; + _loc2_.y = -155; + break; + case 12: + _loc2_.x = -135; + _loc2_.y = -100; + break; + case 14: + _loc2_.x = -165; + _loc2_.y = -175; + break; + case 32: + _loc2_.x = -150; + _loc2_.y = -135; + break; + case 33: + _loc2_.x = -120; + _loc2_.y = -115; + break; + case 34: + _loc2_.x = -145; + _loc2_.y = -190; + break; + case 36: + _loc2_.x = -160; + _loc2_.y = -178; + break; + case 37: + _loc2_.x = -152; + _loc2_.y = -130; + break; + case 38: + _loc2_.x = -145; + _loc2_.y = -150; + break; + case 39: + _loc2_.x = -150; + _loc2_.y = -75; + break; + case 40: + _loc2_.x = -125; + _loc2_.y = -150; + break; + case 41: + _loc2_.x = -147; + _loc2_.y = -115; + break; + case 42: + _loc2_.x = -135; + _loc2_.y = -135; + break; + case 43: + _loc2_.x = -135; + _loc2_.y = -170; + break; + case 44: + _loc2_.x = -105; + _loc2_.y = -115; + break; + case 45: + _loc2_.x = -135; + _loc2_.y = -80; + break; + case 46: + _loc2_.x = -140; + _loc2_.y = -60; + break; + case 47: + _loc2_.x = -140; + _loc2_.y = -75; + break; + case 49: + _loc2_.x = -105; + _loc2_.y = -65; + break; + case 48: + _loc2_.x = -175; + _loc2_.y = -95; + break; + case 50: + _loc2_.x = -135; + _loc2_.y = -145; + break; + case 51: + _loc2_.x = -120; + _loc2_.y = -143; + break; + case 52: + _loc2_.x = -145; + _loc2_.y = -159; + break; + case 53: + _loc2_.x = -90; + _loc2_.y = -183; + break; + default: + _loc2_.x = -160; + _loc2_.y = -190; + } + return _loc2_; + } + + public static function getAvatarMinigameLobbyOffset(param1:int) : Point + { + var _loc2_:Point = new Point(0,0); + switch(param1) + { + case 1: + case 4: + _loc2_.x = 160; + _loc2_.y = 152; + break; + case 2: + _loc2_.x = 150; + _loc2_.y = 220; + break; + case 35: + _loc2_.x = 150; + _loc2_.y = 215; + break; + case 5: + case 6: + _loc2_.x = 158; + _loc2_.y = 152; + break; + case 7: + _loc2_.x = 157; + _loc2_.y = 148; + break; + case 8: + _loc2_.x = 162; + _loc2_.y = 149; + break; + case 13: + case 16: + case 15: + _loc2_.x = 160; + _loc2_.y = 152; + break; + case 22: + _loc2_.x = 155; + _loc2_.y = 165; + break; + case 18: + _loc2_.x = 153; + _loc2_.y = 150; + break; + case 19: + _loc2_.x = 148; + _loc2_.y = 173; + break; + case 20: + _loc2_.x = 153; + _loc2_.y = 170; + break; + case 17: + case 23: + _loc2_.x = 162; + _loc2_.y = 152; + break; + case 24: + _loc2_.x = 155; + _loc2_.y = 152; + break; + case 26: + _loc2_.x = 155; + _loc2_.y = 150; + break; + case 25: + _loc2_.x = 153; + _loc2_.y = 152; + break; + case 28: + _loc2_.x = 155; + _loc2_.y = 152; + break; + case 29: + _loc2_.x = 155; + _loc2_.y = 155; + break; + case 30: + _loc2_.x = 152; + _loc2_.y = 155; + break; + case 31: + _loc2_.x = 154; + _loc2_.y = 148; + break; + case 27: + _loc2_.x = 152; + _loc2_.y = 155; + break; + case 3: + case 9: + _loc2_.x = 158; + _loc2_.y = 155; + break; + case 21: + _loc2_.x = 153; + _loc2_.y = 172; + break; + case 10: + _loc2_.x = 159; + _loc2_.y = 150; + break; + case 11: + _loc2_.x = 152; + _loc2_.y = 152; + break; + case 12: + _loc2_.x = 156; + _loc2_.y = 156; + break; + case 14: + _loc2_.x = 153; + _loc2_.y = 153; + break; + case 32: + case 33: + _loc2_.x = 158; + _loc2_.y = 152; + break; + case 34: + _loc2_.x = 158; + _loc2_.y = 147; + break; + case 36: + _loc2_.x = 156; + _loc2_.y = 155; + break; + case 37: + _loc2_.x = 153; + _loc2_.y = 148; + break; + case 38: + _loc2_.x = 154; + _loc2_.y = 165; + break; + case 39: + _loc2_.x = 170; + _loc2_.y = 235; + break; + case 40: + _loc2_.x = 165; + _loc2_.y = 147; + break; + case 41: + case 42: + _loc2_.x = 154; + _loc2_.y = 151; + break; + case 43: + _loc2_.x = 167; + _loc2_.y = 149; + break; + case 44: + _loc2_.x = 152; + _loc2_.y = 147; + break; + case 45: + _loc2_.x = 157; + _loc2_.y = 215; + break; + case 46: + _loc2_.x = 157; + _loc2_.y = 210; + break; + case 47: + _loc2_.x = 159; + _loc2_.y = 210; + break; + case 49: + _loc2_.x = 157; + _loc2_.y = 245; + break; + case 48: + _loc2_.x = 162; + _loc2_.y = 148; + break; + case 50: + _loc2_.x = 158; + _loc2_.y = 148; + break; + case 51: + _loc2_.x = 158; + _loc2_.y = 150; + break; + case 52: + _loc2_.x = 159; + _loc2_.y = 151; + break; + case 53: + _loc2_.x = 163; + _loc2_.y = 148; + break; + default: + _loc2_.x = 160; + _loc2_.y = 152; + } + return _loc2_; + } + + public static function getAvOffsetByDefId(param1:int) : Point + { + switch(param1) + { + case 1: + return new Point(120,35); + case 2: + return new Point(92,140); + case 35: + return new Point(105,130); + case 4: + return new Point(134,54); + case 5: + return new Point(125,58); + case 6: + return new Point(125,55); + case 7: + return new Point(138,50); + case 8: + return new Point(130,72); + case 13: + return new Point(120,88); + case 15: + return new Point(134,90); + case 16: + return new Point(125,53); + case 18: + return new Point(128,41); + case 19: + return new Point(125,80); + case 20: + return new Point(128,85); + case 17: + return new Point(138,60); + case 23: + return new Point(132,80); + case 22: + return new Point(122,70); + case 24: + return new Point(125,60); + case 26: + return new Point(125,79); + case 21: + return new Point(122,65); + case 25: + return new Point(126,75); + case 28: + return new Point(126,92); + case 29: + return new Point(130,110); + case 30: + return new Point(110,105); + case 31: + return new Point(121,70); + case 27: + case 34: + break; + case 3: + return new Point(135,75); + case 9: + return new Point(145,75); + case 10: + return new Point(130,72); + case 11: + return new Point(125,72); + case 12: + return new Point(132,75); + case 14: + return new Point(125,72); + case 32: + case 33: + return new Point(125,87); + case 36: + return new Point(122,55); + case 37: + return new Point(122,55); + case 38: + return new Point(130,95); + case 39: + return new Point(130,175); + case 40: + return new Point(140,60); + case 41: + return new Point(115,60); + case 42: + return new Point(130,60); + case 43: + return new Point(145,85); + case 44: + return new Point(140,75); + case 45: + return new Point(135,150); + case 46: + return new Point(130,145); + case 47: + return new Point(140,165); + case 49: + return new Point(125,195); + case 48: + return new Point(145,100); + case 50: + return new Point(115,80); + case 51: + return new Point(140,80); + case 52: + return new Point(145,80); + case 53: + return new Point(155,85); + default: + return new Point(115,110); + } + return new Point(125,65); + } + + public static function isAvatarActive(param1:int) : Boolean + { + if(param1 > 0) + { + return true; + } + return false; + } + + public static function isEndangered(param1:int) : Boolean + { + if(param1 == 2) + { + return true; + } + return false; + } + + public static function isExtinct(param1:int) : Boolean + { + if(param1 == 3) + { + return true; + } + return false; + } + } +} + diff --git a/swf-src/AvatarView.as b/swf-src/AvatarView.as new file mode 100644 index 0000000..1ad0599 --- /dev/null +++ b/swf-src/AvatarView.as @@ -0,0 +1,380 @@ +package avatar +{ + import collection.AccItemCollection; + import com.sbi.graphics.LayerAnim; + import flash.display.Sprite; + import flash.filters.ColorMatrixFilter; + import item.Item; + + public class AvatarView extends Sprite + { + + protected var _layerAnim:LayerAnim; + + protected var _avatar:Avatar; + + protected var _skipAnimEnviroCheck:Boolean; + + public var avTypeChangedCallback:Function; + + public var onAvatarChangedCallback:Function; + + private var _isOffScreen:Boolean; + + private var _holdAnimId:int; + + private var _lastAnimToHappen:int; + + public function AvatarView() + { + super(); + } + + public function set lastAnimToHappen(param1:int) : void + { + _lastAnimToHappen = param1; + } + + public function get lastAnimToHappen() : int + { + return _lastAnimToHappen; + } + + public function set holdAnimId(param1:int) : void + { + _holdAnimId = param1; + } + + public function init(param1:Avatar, param2:Function = null, param3:Function = null, param4:Boolean = false, param5:Boolean = false) : void + { + _holdAnimId = 0; + _avatar = param1; + _avatar.addEventListener("OnAvatarChanged",avatarChanged,false,0,true); + avTypeChangedCallback = param2; + onAvatarChangedCallback = param3; + _skipAnimEnviroCheck = param5; + _layerAnim = LayerAnim.getNew(param4); + _layerAnim.avDefId = _avatar.avTypeId; + if(_avatar.colors) + { + _layerAnim.layers = setLayerHelper(); + } + this.addChild(_layerAnim.bitmap); + } + + public function destroy(param1:Boolean = false) : void + { + if(param1 && _avatar) + { + _avatar.removeEventListener("OnAvatarChanged",avatarChanged); + _avatar.destroy(); + _avatar = null; + } + avTypeChangedCallback = null; + onAvatarChangedCallback = null; + LayerAnim.destroy(_layerAnim); + _layerAnim = null; + } + + public function resetAvatar(param1:Avatar) : void + { + if(_avatar && _avatar.hasEventListener("OnAvatarChanged")) + { + _avatar.removeEventListener("OnAvatarChanged",avatarChanged); + } + _avatar = param1; + _avatar.addEventListener("OnAvatarChanged",avatarChanged,false,0,true); + if(_layerAnim) + { + _layerAnim.avDefId = _avatar.avTypeId; + if(_avatar.colors) + { + _layerAnim.layers = setLayerHelper(); + } + } + } + + public function isValid() : Boolean + { + return _layerAnim != null; + } + + public function hideAvatar() : void + { + if(_layerAnim != null) + { + _layerAnim.visible = false; + } + } + + public function showAvatar() : void + { + if(_layerAnim != null) + { + _layerAnim.visible = true; + } + } + + public function set isOffScreen(param1:Boolean) : void + { + _isOffScreen = param1; + } + + public function get isOffScreen() : Boolean + { + return _isOffScreen; + } + + public function pauseAnim(param1:Boolean) : void + { + _layerAnim.pause = param1; + } + + public function advanceFrame() : void + { + _layerAnim.frame++; + } + + public function get frame() : int + { + return _layerAnim.frame; + } + + public function set frame(param1:int) : void + { + _layerAnim.frame = param1; + } + + public function get flip() : Boolean + { + return _layerAnim.hFlip; + } + + public function get animId() : int + { + return _layerAnim.animId; + } + + protected function avatarChanged(param1:AvatarEvent) : void + { + if(_layerAnim) + { + if(_layerAnim.avDefId != _avatar.avTypeId) + { + _layerAnim.avDefId = _avatar.avTypeId; + if(avTypeChangedCallback != null) + { + avTypeChangedCallback(this); + } + } + _layerAnim.layers = setLayerHelper(); + if(onAvatarChangedCallback != null) + { + onAvatarChangedCallback(this); + } + } + } + + protected function setLayerHelper() : Array + { + var _loc1_:AvatarInfo = null; + var _loc2_:AccItemCollection = null; + var _loc3_:* = null; + if(_avatar.inventoryBodyMod && _avatar.inventoryBodyMod.itemCollection && _avatar.inventoryBodyMod.itemCollection.length >= 1) + { + _loc3_ = new AccItemCollection(_avatar.inventoryBodyMod.itemCollection.concatCollection(_avatar.inventoryClothing.itemCollection)); + } + else + { + _loc1_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(_avatar.userName,_avatar.perUserAvId); + if(_loc1_) + { + _loc2_ = _skipAnimEnviroCheck ? _loc1_.getFullItems(true) : _loc1_.getItems(true); + if(_loc2_) + { + _loc3_ = _loc2_; + } + } + } + return AvatarUtility.layerArrayForItemsAndColors(_loc3_,_avatar.colors,_avatar.avInvId,_avatar.roomType,_skipAnimEnviroCheck); + } + + public function playAnim(param1:int, param2:Boolean = false, param3:int = 0, param4:Function = null, param5:Boolean = false) : void + { + var _loc14_:Boolean = false; + var _loc13_:AccItemCollection = null; + var _loc6_:int = 0; + var _loc15_:int = 0; + var _loc11_:Array = null; + var _loc8_:* = null; + var _loc10_:Object = null; + var _loc9_:Array = null; + var _loc7_:* = 0; + if(_layerAnim && _layerAnim.visible && (_holdAnimId == 0 || param1 == _holdAnimId)) + { + if(!_isOffScreen) + { + _loc14_ = false; + _loc13_ = _avatar.accShownItems; + if(!_layerAnim.layers) + { + _loc14_ = true; + } + else if(_layerAnim.layers.length != _loc13_.length) + { + _loc14_ = true; + } + else + { + _loc6_ = int(_loc13_.length); + _loc15_ = 0; + while(_loc15_ < _loc6_) + { + if(_layerAnim.layers.indexOf(_loc13_.getAccItem(_loc15_).accId) == -1) + { + _loc14_ = true; + break; + } + _loc15_++; + } + } + if(_loc14_) + { + _loc11_ = []; + _loc8_ = _loc13_; + _loc9_ = _avatar.colors; + for each(var _loc12_ in _loc8_.getCoreArray()) + { + if((_loc12_.layerId <= 3 || (_skipAnimEnviroCheck || _loc12_.enviroType == _avatar.roomType || _loc12_.isLandAndOcean)) && _loc12_.getInUse(_avatar.avInvId)) + { + if(_loc12_.layerId == 1) + { + _loc7_ = uint(_loc9_[0]); + } + else if(_loc12_.layerId == 2) + { + _loc7_ = uint(_loc9_[1]); + } + else if(_loc12_.layerId == 3) + { + _loc7_ = uint(_loc9_[2]); + } + else + { + if(param5) + { + continue; + } + _loc7_ = _loc12_.color; + } + // "d": the item, as AvatarUtility.layerArrayForItemsAndColors + // gives it: a custom one's own picture goes by it + // (LayerAnim, LayerBitmap). without it every new + // animation (walking) was painted as the item's base. + _loc10_ = { + "l":_loc12_.accId, + "c":_loc7_, + "d":_loc12_.defId + }; + _loc11_.push(_loc10_); + } + } + _layerAnim.layers = _loc11_; + } + _layerAnim.hFlip = param2; + _layerAnim.playAnim(param1,param3,param4); + } + else + { + _lastAnimToHappen = param1; + } + } + } + + public function reloadItemsFromCache() : void + { + var _loc1_:AccItemCollection = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(_avatar.userName,_avatar.perUserAvId).getItems(true); + _avatar.itemResponseIntegrate(_loc1_,_skipAnimEnviroCheck); + } + + public function preloadAnims(param1:Array, param2:Function = null) : void + { + _layerAnim.preload(param1,param2); + } + + public function blackOut() : void + { + var _loc1_:Array = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]; + _layerAnim.bitmap.filters = [new ColorMatrixFilter(_loc1_)]; + } + + public function get avatarData() : Avatar + { + return _avatar; + } + + public function get userName() : String + { + if(_avatar != null) + { + return _avatar.userName; + } + return null; + } + + public function get userId() : int + { + if(_avatar == null) + { + return -1; + } + return _avatar.sfsUserId; + } + + public function get avTypeId() : int + { + return _avatar.avTypeId; + } + + public function get customAvId() : int + { + return _avatar.customAvId; + } + + public function get perUserAvId() : int + { + return _avatar.perUserAvId; + } + + public function get avInvId() : int + { + return _avatar.avInvId; + } + + public function get inventoryBodyModItems() : AccItemCollection + { + return _avatar.inventoryBodyMod.itemCollection; + } + + public function get inventoryClothingItems() : AccItemCollection + { + return _avatar.inventoryClothing.itemCollection; + } + + public function setAvtColors(param1:Array) : void + { + _avatar.colors = param1; + } + + public function get avName() : String + { + return _avatar.avName; + } + + public function get accShownItems() : AccItemCollection + { + return _avatar.accShownItems; + } + } +} + diff --git a/swf-src/AvatarWorldView.as b/swf-src/AvatarWorldView.as index 279f2d6..70b47e3 100644 --- a/swf-src/AvatarWorldView.as +++ b/swf-src/AvatarWorldView.as @@ -191,6 +191,20 @@ package avatar "water":40, "set":"land", "flip":false + },{ + // sitting facing straight forward, and straight away (the "Front" + // and "Back" between the arrows): animations 5 and 1, the ends of + // the sitting turn 1-5 (2 the back corners, 4 the front ones; the + // slide's spin plays them in turn). the game's own buttons never did. + "name":":sitS:", + "land":5, + "water":40, + "flip":false + },{ + "name":":sitN:", + "land":1, + "water":40, + "flip":false }]; // the landing puff, artwork compiled into the client. its class has a @@ -209,6 +223,21 @@ package avatar private var _platformingCurVel:Number = 0; private var _chatBalloon:ChatBalloon; + + // "..." where the chat bubble goes, while the player is typing + // (AJClient.onTyping). gone when a line arrives, when they stop, or + // TYPING_SHOWN ms after they last said they were, if a "stopped" is lost. + private static const TYPING_SHOWN:int = 8000; + + private var _typing:Sprite; + + private var _typingDots:Array; + + private var _typingTimer:Timer; + + private var _typingStep:int; + + private var _typingUntil:int; private var _namebar:NameBar; @@ -628,6 +657,14 @@ package avatar { _chatLayer.removeChild(_chatBalloon); } + hideTyping(); + if(_typingTimer) + { + _typingTimer.removeEventListener("timer",onTypingTimer); + _typingTimer = null; + } + _typing = null; + _typingDots = null; removeChild(_namebar); if(_secondaryEmot && _chatLayer.contains(_secondaryEmot)) { @@ -1023,9 +1060,108 @@ package avatar return false; } + public function setTyping(param1:Boolean) : void + { + var _loc2_:Sprite = null; + var _loc3_:int = 0; + if(!param1 || _chatLayer == null) + { + hideTyping(); + return; + } + if(_typing == null) + { + _typing = new Sprite(); + _typing.mouseEnabled = false; + _typing.mouseChildren = false; + _typing.graphics.lineStyle(2,0x8C6A3C); + _typing.graphics.beginFill(0xFFFFFF); + _typing.graphics.drawRoundRect(-22,-26,44,22,20,20); + _typing.graphics.endFill(); + _typing.graphics.lineStyle(); + _typing.graphics.beginFill(0xFFFFFF); + _typing.graphics.moveTo(-5,-5); + _typing.graphics.lineTo(0,2); + _typing.graphics.lineTo(5,-5); + _typing.graphics.endFill(); + _typingDots = []; + _loc3_ = 0; + while(_loc3_ < 3) + { + _loc2_ = new Sprite(); + _loc2_.graphics.beginFill(0x6B5034); + _loc2_.graphics.drawCircle(0,0,3); + _loc2_.graphics.endFill(); + _loc2_.x = -10 + _loc3_ * 10; + _loc2_.y = -15; + _typing.addChild(_loc2_); + _typingDots.push(_loc2_); + _loc3_++; + } + _typingTimer = new Timer(300); + _typingTimer.addEventListener("timer",onTypingTimer,false,0,true); + } + _typingUntil = getTimer() + TYPING_SHOWN; + if(_typing.parent != _chatLayer) + { + _chatLayer.addChild(_typing); + } + placeTyping(); + _typing.visible = !(_chatBalloon && _chatBalloon.visible); + if(!_typingTimer.running) + { + _typingTimer.start(); + } + } + + private function hideTyping() : void + { + if(_typingTimer) + { + _typingTimer.stop(); + } + if(_typing && _typing.parent) + { + _typing.parent.removeChild(_typing); + } + } + + private function placeTyping() : void + { + if(_typing && _chatBalloon) + { + _typing.x = _chatBalloon.x; + _typing.y = _chatBalloon.y; + } + } + + private function onTypingTimer(param1:TimerEvent) : void + { + var _loc2_:int = 0; + if(_typing == null || getTimer() > _typingUntil) + { + hideTyping(); + return; + } + placeTyping(); + _typing.visible = !(_chatBalloon && _chatBalloon.visible); + _typingStep = (_typingStep + 1) % 3; + _loc2_ = 0; + while(_loc2_ < _typingDots.length) + { + _typingDots[_loc2_].alpha = _loc2_ == _typingStep ? 1 : 0.35; + _typingDots[_loc2_].y = _loc2_ == _typingStep ? -17 : -15; + _loc2_++; + } + } + public function setMessage(param1:String, param2:int) : void { var _loc3_:Boolean = false; + if(param1 != "...") + { + hideTyping(); + } if(param2 > 1) { if(param2 == 2) @@ -1220,6 +1356,18 @@ package avatar _pet.setActionByName(_loc2_.replace(/(Land|Swim):$/,":")); } } + + // The base action definitions supply their normal orientation. A local + // Mirror selection is applied after that, so it works for every action + // without changing the original sit/dance/etc. mappings. + public function setActionMirrored(param1:Boolean) : void + { + if(_lastIdleAnim > 0 && param1) + { + _lastIdleFlip = !_lastIdleFlip; + playAnim(_lastIdleAnim,_lastIdleFlip); + } + } public function circleTest(param1:int, param2:int, param3:int) : Boolean { diff --git a/swf-src/BuddyCard.as b/swf-src/BuddyCard.as index 84605ba..c1944cb 100644 --- a/swf-src/BuddyCard.as +++ b/swf-src/BuddyCard.as @@ -3325,6 +3325,12 @@ package buddy private function reportDownHandler(param1:MouseEvent) : void { param1.stopPropagation(); + // staff get their window for this player instead (AJClient.openModerate). + if(!param1.currentTarget.isGray && AJClient.canModerate()) + { + AJClient.openModerate(_currUserName); + return; + } if(!param1.currentTarget.isGray) { if(_reportAPlayer) @@ -3344,7 +3350,7 @@ package buddy param1.stopPropagation(); if(!param1.currentTarget.isGray) { - GuiManager.toolTip.init(_popupLayer,LocalizationManager.translateIdOnly(14633),845,210); + GuiManager.toolTip.init(_popupLayer,AJClient.canModerate() ? "Moderate" : LocalizationManager.translateIdOnly(14633),845,210); GuiManager.toolTip.startTimer(param1); } } diff --git a/swf-src/ChatBalloon.as b/swf-src/ChatBalloon.as index 0cef6b4..831ed2f 100644 --- a/swf-src/ChatBalloon.as +++ b/swf-src/ChatBalloon.as @@ -63,9 +63,12 @@ package gui private var _emoteBGOffsetFunc:Function; - // emotes drawn inside a line of chat: "\" and an emote's code - // ("\:)", "\:fever:") is shown as that emote, small, where it was - // typed. each is {at, clip}: where its gap starts in the text shown. + // emotes drawn inside a line of chat, small, where they were typed: an + // emote's code standing as a word of its own ("hi :) there", ":fever:"), + // or anywhere after a "\" ("yay\:)"). and emoji (typed with Windows' + // emoji panel, say), which the game's font has none of: each is drawn + // as a picture of it, from the server (/emoji/.png, + // Twemoji's). each is {at, clip}: where its gap starts in the text shown. private static const INLINE_GAP:String = " "; private static const LONGEST_EMOTE_CODE:int = 16; @@ -130,7 +133,7 @@ package gui this.visible = true; } clearInline(); - _msgTxt.text = param1.indexOf("\\") == -1 ? param1 : inlineEmotes(param1); + _msgTxt.text = inlineEmotes(param1); _msgTxt.height; // AJClient.whisperNext is set by the server's "xw" just ahead of a // whispered line. @@ -178,50 +181,63 @@ package gui } } - // the text with each "\" replaced by a gap, the emote for - // it kept in _inline. A code that is no emote stays as typed. + // the text with each emote code and emoji (above) replaced by a gap, the + // picture for it kept in _inline. what is neither stays as typed. private function inlineEmotes(param1:String) : String { var _loc2_:String = ""; var _loc3_:int = 0; - var _loc4_:int = 0; var _loc5_:String = null; - var _loc6_:String = null; - var _loc7_:MovieClip = null; + var _loc7_:Sprite = null; + var _loc8_:int = 0; while(_loc3_ < param1.length) { - _loc5_ = null; - if(param1.charAt(_loc3_) == "\\") + _loc8_ = emojiLength(param1,_loc3_); + if(_loc8_ > 0) { - _loc4_ = Math.min(LONGEST_EMOTE_CODE,param1.length - _loc3_ - 1); - while(_loc4_ >= 2 && _loc5_ == null) - { - _loc6_ = param1.substr(_loc3_ + 1,_loc4_); - if(EmoticonUtility.doesStringMatchAnEmote(_loc6_)) - { - _loc5_ = _loc6_; - } - _loc4_--; - } + _inline.push({ + "at":_loc2_.length, + "clip":emojiClip(param1.substr(_loc3_,_loc8_)) + }); + _loc2_ += INLINE_GAP; + _loc3_ += _loc8_; + continue; } - if(_loc5_ != null) + _loc5_ = null; + // an emoji as it is sent: "\{1f600}" (AJClient.emojiToTokens) + if(param1.substr(_loc3_,2) == "\\{") { - _loc7_ = EmoticonUtility.getSmallSmileyMCForEmoteString(_loc5_); - if(_loc7_ != null) + var _loc9_:Array = /^\\\{([0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9})\}/.exec(param1.substr(_loc3_,90)); + if(_loc9_ != null) { - _loc7_.mouseEnabled = false; - _loc7_.mouseChildren = false; _inline.push({ "at":_loc2_.length, - "clip":_loc7_ + "clip":emojiClipNamed(_loc9_[1]) }); _loc2_ += INLINE_GAP; + _loc3_ += String(_loc9_[0]).length; + continue; } - else - { - _loc2_ += _loc5_; - } - _loc3_ += 1 + _loc5_.length; + } + if(param1.charAt(_loc3_) == "\\") + { + _loc5_ = emoteCodeAt(param1,_loc3_ + 1,false); + } + else if(_loc3_ == 0 || param1.charAt(_loc3_ - 1) == " ") + { + _loc5_ = emoteCodeAt(param1,_loc3_,true); + } + _loc7_ = _loc5_ == null ? null : EmoticonUtility.getSmallSmileyMCForEmoteString(_loc5_); + if(_loc7_ != null) + { + _loc7_.mouseEnabled = false; + _loc7_.mouseChildren = false; + _inline.push({ + "at":_loc2_.length, + "clip":_loc7_ + }); + _loc2_ += INLINE_GAP; + _loc3_ += (param1.charAt(_loc3_) == "\\" ? 1 : 0) + _loc5_.length; } else { @@ -231,7 +247,149 @@ package gui } return _loc2_; } - + + // the longest emote code at `param2`, or null. `param3`: as a word of its + // own, so it must end the text or come before a space or a stop. + private static function emoteCodeAt(param1:String, param2:int, param3:Boolean) : String + { + var _loc4_:int = Math.min(LONGEST_EMOTE_CODE,param1.length - param2); + var _loc5_:String = null; + var _loc6_:String = null; + while(_loc4_ >= 2) + { + _loc5_ = param1.substr(param2,_loc4_); + _loc6_ = param1.charAt(param2 + _loc4_); + if((!param3 || _loc6_ == "" || " .,!?".indexOf(_loc6_) != -1) && EmoticonUtility.doesStringMatchAnEmote(_loc5_)) + { + return _loc5_; + } + _loc4_--; + } + return null; + } + + // how many UTF-16 units the emoji at `param2` takes (with its skin tone, + // its variation selector, a keycap, a second flag letter, and whatever + // it is joined to with a zero-width joiner), or 0 when there is none. + public static function emojiLength(param1:String, param2:int) : int + { + var _loc3_:int = param1.charCodeAt(param2); + var _loc4_:int = 0; + var _loc5_:int = 0; + var _loc6_:int = 0; + var _loc7_:Boolean = false; + if(_loc3_ >= 0xD800 && _loc3_ <= 0xDBFF) + { + _loc5_ = codePointAt(param1,param2); + if(_loc5_ < 0x1F000 || _loc5_ > 0x1FAFF) + { + return 0; + } + _loc4_ = 2; + _loc7_ = _loc5_ >= 0x1F1E6 && _loc5_ <= 0x1F1FF; + // a flag is two letters + if(_loc7_) + { + _loc6_ = codePointAt(param1,param2 + 2); + if(_loc6_ >= 0x1F1E6 && _loc6_ <= 0x1F1FF) + { + _loc4_ = 4; + } + } + } + else if(_loc3_ >= 0x2600 && _loc3_ <= 0x27BF || _loc3_ >= 0x2300 && _loc3_ <= 0x23FF || _loc3_ >= 0x2B00 && _loc3_ <= 0x2BFF + || _loc3_ >= 0x2194 && _loc3_ <= 0x21AA || _loc3_ >= 0x25AA && _loc3_ <= 0x25FE + || [0x203C,0x2049,0x2122,0x2139,0x24C2,0x2934,0x2935,0x3030,0x303D,0x3297,0x3299,0xA9,0xAE].indexOf(_loc3_) != -1 && param1.charCodeAt(param2 + 1) == 0xFE0F) + { + _loc4_ = 1; + } + else if("0123456789#*".indexOf(param1.charAt(param2)) != -1 && param1.charCodeAt(param2 + 1) == 0xFE0F && param1.charCodeAt(param2 + 2) == 0x20E3) + { + return 3; + } + else + { + return 0; + } + while(param2 + _loc4_ < param1.length) + { + _loc3_ = param1.charCodeAt(param2 + _loc4_); + if(_loc3_ == 0xFE0F || _loc3_ == 0x20E3) + { + _loc4_++; + } + else if(_loc3_ == 0xD83C && param1.charCodeAt(param2 + _loc4_ + 1) >= 0xDFFB && param1.charCodeAt(param2 + _loc4_ + 1) <= 0xDFFF) + { + _loc4_ += 2; + } + else if(_loc3_ == 0x200D && param2 + _loc4_ + 1 < param1.length) + { + _loc5_ = emojiLength(param1,param2 + _loc4_ + 1); + if(_loc5_ == 0) + { + break; + } + _loc4_ += 1 + _loc5_; + break; + } + else + { + break; + } + } + return _loc4_; + } + + private static function codePointAt(param1:String, param2:int) : int + { + var _loc3_:int = param1.charCodeAt(param2); + var _loc4_:int = param1.charCodeAt(param2 + 1); + if(_loc3_ >= 0xD800 && _loc3_ <= 0xDBFF && _loc4_ >= 0xDC00 && _loc4_ <= 0xDFFF) + { + return (_loc3_ - 0xD800) * 0x400 + (_loc4_ - 0xDC00) + 0x10000; + } + return _loc3_; + } + + // its picture's name, as Twemoji names its files: the code points in + // hex, "-" between, without U+FE0F unless it is joined (U+200D). + public static function emojiName(param1:String) : String + { + var _loc2_:Array = []; + var _loc3_:int = 0; + var _loc4_:int = 0; + var _loc5_:Boolean = param1.indexOf(String.fromCharCode(0x200D)) != -1; + while(_loc3_ < param1.length) + { + _loc4_ = codePointAt(param1,_loc3_); + _loc3_ += _loc4_ > 0xFFFF ? 2 : 1; + if(_loc4_ != 0xFE0F || _loc5_) + { + _loc2_.push(_loc4_.toString(16)); + } + } + return _loc2_.join("-"); + } + + // the picture of an emoji: a 72-square, its middle on the origin (as + // the game's small emotes are), filled when the picture has loaded. + private static function emojiClip(param1:String) : Sprite + { + return emojiClipNamed(emojiName(param1)); + } + + private static function emojiClipNamed(param1:String) : Sprite + { + var _loc2_:Sprite = new Sprite(); + _loc2_.graphics.beginFill(0,0); + _loc2_.graphics.drawRect(-36,-36,72,72); + _loc2_.graphics.endFill(); + _loc2_.mouseEnabled = false; + _loc2_.mouseChildren = false; + AJClient.loadArt(gMainFrame.clientInfo.websiteURL + "emoji/" + param1 + ".png",_loc2_,72,false); + return _loc2_; + } + // puts each inline emote over its gap, as tall as the line. private function placeInline() : void { diff --git a/swf-src/ChatHistory.as b/swf-src/ChatHistory.as index 228c80a..e63793d 100644 --- a/swf-src/ChatHistory.as +++ b/swf-src/ChatHistory.as @@ -14,6 +14,7 @@ package gui import flash.events.TextEvent; import flash.text.StyleSheet; import flash.text.TextField; + import flash.text.TextFormat; import flash.ui.Mouse; import gui.itemWindows.ItemWindowTextNode; import localization.LocalizationManager; @@ -211,6 +212,8 @@ package gui public function addMessage(param1:String, param2:String, param3:String, param4:String) : void { + // emoji as their names here: this list has no pictures (AJClient.emojiAsNames) + param4 = AJClient.emojiAsNames(param4); var _loc5_:Boolean = false; var _loc6_:* = 0; var _loc7_:int = 0; @@ -479,9 +482,10 @@ package gui } else { - // 150 here, where the original stopped at 70. the server takes - // up to config.maxChatLength. - chatMsgText.maxChars = 150; + // 200 here, where the original stopped at 70. the server takes + // up to config.maxChatLength (more: an emoji goes as a tag of 8 + // or more), and makes long lines shorter (lib/chatspam.js). + chatMsgText.maxChars = 200; } } @@ -753,6 +757,51 @@ package gui { _predictiveTextManager.onTextFieldChanged(param1); } + showEmojiInInput(); + AJClient.noteTyping(chatMsgText.text); + } + + // the chat box while it holds an emoji (Windows' emoji panel, say): the + // game's font has none, so the box is drawn in the computer's own emoji + // font until there are none again. the bubble shows them as pictures + // (gui.ChatBalloon). + private var _inputShowsEmoji:Boolean = false; + + private var _inputFormat:TextFormat; + + private var _inputEmbedded:Boolean = true; + + public function showEmojiInInput() : void + { + var _loc1_:Boolean = false; + var _loc2_:int = 0; + var _loc3_:String = chatMsgText == null ? "" : chatMsgText.text; + var _loc4_:TextFormat = null; + while(_loc2_ < _loc3_.length && !_loc1_) + { + _loc1_ = ChatBalloon.emojiLength(_loc3_,_loc2_) > 0; + _loc2_++; + } + if(chatMsgText == null || _loc1_ == _inputShowsEmoji) + { + return; + } + if(_loc1_) + { + _inputFormat = chatMsgText.defaultTextFormat; + _inputEmbedded = chatMsgText.embedFonts; + _loc4_ = new TextFormat("Segoe UI Emoji",_inputFormat.size,_inputFormat.color,_inputFormat.bold); + chatMsgText.embedFonts = false; + chatMsgText.defaultTextFormat = _loc4_; + chatMsgText.setTextFormat(_loc4_); + } + else + { + chatMsgText.embedFonts = _inputEmbedded; + chatMsgText.defaultTextFormat = _inputFormat; + chatMsgText.setTextFormat(_inputFormat); + } + _inputShowsEmoji = _loc1_; } private function keyDownListener(param1:KeyboardEvent) : void diff --git a/swf-src/DenItemHelper.as b/swf-src/DenItemHelper.as new file mode 100644 index 0000000..3bcd605 --- /dev/null +++ b/swf-src/DenItemHelper.as @@ -0,0 +1,665 @@ +package loader +{ + import Enums.DenItemDef; + import avatar.AvatarManager; + import avatar.MannequinData; + import com.sbi.loader.FileServerEvent; + import den.DenItem; + import den.DenStateItem; + import den.DenXtCommManager; + import flash.display.DisplayObject; + import flash.display.Loader; + import flash.display.MovieClip; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.MouseEvent; + import pet.PetItem; + import pet.PetManager; + + public class DenItemHelper + { + + private var _denItem:DenItem; + + private var _denStateItem:DenStateItem; + + private var _defId:int; + + private var _id:uint; + + private var _callback:Function; + + private var _loader:Loader; + + private var _sprite:Sprite; + + private var _portalSprite:Sprite; + + private var _sortOffset:int; + + private var _minigameDefId:int; + + private var _nameStrId:int; + + private var _listLauncherId:int; + + private var _version:int; + + private var _version2:int; + + private var _version3:int; + + private var _petItem:PetItem; + + private var _bFlipLabel:Boolean; + + private var _isUniqueImageItem:Boolean; + + private var _uniqueImageId:String; + + private var _uniqueImageCreator:String; + + private var _uniqueImageCreatorDbId:int; + + private var _uniqueImageCreatorUUID:String; + + private var _isMannequin:Boolean; + + private var _isDenStore:Boolean; + + private var _masterpieceDefHelper:MasterpieceDefHelper; + + private var _mannequinData:MannequinData; + + private var _onMouseDownCallback:Function; + + private var _onMouseOverCallback:Function; + + private var _onMouseOutCallback:Function; + + private var _uniqueImage:Sprite; + + public function DenItemHelper() + { + super(); + } + + public function get displayObject() : Sprite + { + return _sprite; + } + + public function get content() : DisplayObject + { + return _loader.content; + } + + public function get sortOffset() : int + { + return _sortOffset; + } + + public function get id() : int + { + return _id; + } + + public function get minigameDefId() : int + { + return _minigameDefId; + } + + public function get bFlipLabel() : Boolean + { + return _bFlipLabel; + } + + public function get isUniqueImageItem() : Boolean + { + return _isUniqueImageItem; + } + + public function get listLauncherId() : int + { + return _listLauncherId; + } + + public function get nameStrId() : int + { + return _nameStrId; + } + + public function get uniqueImage() : Sprite + { + return _uniqueImage; + } + + public function get uniqueImageId() : String + { + return _uniqueImageId; + } + + public function set uniqueImageId(param1:String) : void + { + _uniqueImageId = param1; + } + + public function get uniqueImageCreator() : String + { + return _uniqueImageCreator; + } + + public function set uniqueImageCreator(param1:String) : void + { + _uniqueImageCreator = param1; + } + + public function get uniqueImageCreatorDbId() : int + { + return _uniqueImageCreatorDbId; + } + + public function get uniqueImageCreatorUUID() : String + { + return _uniqueImageCreatorUUID; + } + + public function get denStateItem() : DenStateItem + { + return _denStateItem; + } + + public function get defId() : int + { + return _defId; + } + + public function get version() : int + { + return _version; + } + + public function get mannequin() : MannequinData + { + return _mannequinData; + } + + public function get isMannequin() : Boolean + { + return _isMannequin; + } + + public function get isDenStore() : Boolean + { + return _isDenStore; + } + + public function get contentWidth() : int + { + if(_loader != null && _loader.content != null) + { + if(_loader.content.hasOwnProperty("sizeCont")) + { + return _loader.content["sizeCont"].width; + } + return _loader.content.width; + } + return 0; + } + + public function get contentHeight() : int + { + if(_loader != null && _loader.content != null) + { + if(_loader.content.hasOwnProperty("sizeCont")) + { + return _loader.content["sizeCont"].height; + } + return _loader.content.height; + } + return 0; + } + + public function get currDenItem() : DenItem + { + return _denItem; + } + + public function init(param1:DenItem, param2:Function, param3:PetItem = null, param4:int = 0, param5:int = 0, param6:MannequinData = null) : void + { + _denItem = param1; + _defId = param1.defId; + _id = uint(_defId << 16 | DenItem.getIconId(param1.sortId)); + _callback = param2; + _minigameDefId = param1.minigameDefId; + _nameStrId = param5; + _listLauncherId = param4; + _bFlipLabel = false; + _isUniqueImageItem = false; + _petItem = param3; + _version = param1.sortId == 99 ? _petItem.petBits[0] : param1.version; + _version2 = param1.sortId == 99 ? _petItem.petBits[1] : 0; + _version3 = param1.sortId == 99 ? _petItem.petBits[2] : 0; + _loader = new Loader(); + _sprite = new Sprite(); + _portalSprite = new Sprite(); + _uniqueImage = new Sprite(); + _uniqueImageId = param1.uniqueImageId; + _uniqueImageCreator = param1.uniqueImageCreator; + _uniqueImageCreatorDbId = param1.uniqueImageCreatorDbId; + _uniqueImageCreatorUUID = param1.uniqueImageCreatorUUID; + _mannequinData = param6; + if(loadCustomArt()) + { + return; + } + DenItemServer.instance.addEventListener("OnNewData",handleData,false,0,true); + DenItemServer.instance.requestFile(_id); + } + + public function initDS(param1:DenStateItem, param2:Function) : void + { + _denStateItem = param1; + _defId = param1.defId; + _id = uint(_defId << 16 | param1.catId); + _callback = param2; + _minigameDefId = param1.minigameDefId; + _nameStrId = param1.nameStrId; + _listLauncherId = param1.listLauncherId; + _bFlipLabel = false; + _isUniqueImageItem = false; + _petItem = param1.petItem; + _version = param1.sortCatId == 99 ? _petItem.petBits[0] : param1.version; + _version2 = param1.sortCatId == 99 ? _petItem.petBits[1] : 0; + _version3 = param1.sortCatId == 99 ? _petItem.petBits[2] : 0; + _loader = new Loader(); + _sprite = new Sprite(); + _portalSprite = new Sprite(); + _uniqueImage = new Sprite(); + _uniqueImageId = param1.uniqueImageId; + _uniqueImageCreator = param1.uniqueImageCreator; + _uniqueImageCreatorDbId = param1.uniqueImageCreatorDbId; + _uniqueImageCreatorUUID = param1.uniqueImageCreatorUUID; + _mannequinData = param1.mannequinData; + if(loadCustomArt()) + { + return; + } + DenItemServer.instance.addEventListener("OnNewData",handleData,false,0,true); + DenItemServer.instance.requestFile(_id); + } + + public function initGeneric(param1:DenItemDef, param2:Function, param3:int = 0, param4:int = 0, param5:int = 0, param6:String = "", param7:int = -1, param8:String = "", param9:PetItem = null, param10:MannequinData = null) : void + { + _defId = param1.id; + _id = uint(_defId << 16 | DenItem.getIconId(param1.sortCat)); + _callback = param2; + _minigameDefId = param1.gameDefId; + _nameStrId = param5; + _listLauncherId = param4; + _bFlipLabel = false; + _isUniqueImageItem = false; + _petItem = param9; + _version = param1.sortCat == 99 ? _petItem.petBits[0] : param3; + _version2 = param1.sortCat == 99 ? _petItem.petBits[1] : 0; + _version3 = param1.sortCat == 99 ? _petItem.petBits[2] : 0; + _loader = new Loader(); + _sprite = new Sprite(); + _portalSprite = new Sprite(); + _uniqueImage = new Sprite(); + _uniqueImageId = param6; + _uniqueImageCreator = ""; + _uniqueImageCreatorDbId = param7; + _uniqueImageCreatorUUID = param8; + _mannequinData = param10; + if(loadCustomArt()) + { + return; + } + DenItemServer.instance.addEventListener("OnNewData",handleData,false,0,true); + DenItemServer.instance.requestFile(_id); + } + + public function destroy() : void + { + DenItemServer.instance.removeEventListener("OnNewData",handleData); + if(_loader) + { + if(_loader.parent) + { + _loader.parent.removeChild(_loader); + } + _loader.unloadAndStop(true); + } + _callback = null; + _sprite = null; + } + + public function loadUniqueImage() : void + { + if(_loader && _loader.content.hasOwnProperty("setUniqueImage")) + { + _isUniqueImageItem = true; + if(_uniqueImageId != "") + { + _masterpieceDefHelper = new MasterpieceDefHelper(); + _masterpieceDefHelper.init(_uniqueImageId,onUniqueImageIdLoaded); + } + } + } + + public function setupItemWithEmotes(param1:DenStateItem) : void + { + _denStateItem = param1; + } + + public function addPortalListeners(param1:DenStateItem, param2:Function, param3:Function = null, param4:Function = null) : void + { + _denStateItem = param1; + _onMouseDownCallback = param2; + _portalSprite.addEventListener("mouseDown",onMouseDown,false,0,true); + if(param3 != null) + { + _onMouseOverCallback = param3; + _portalSprite.addEventListener("mouseOver",onMouseOver,false,0,true); + } + if(param4 != null) + { + _onMouseOutCallback = param4; + _portalSprite.addEventListener("mouseOut",onMouseOut,false,0,true); + } + } + + public function addMouseListeners(param1:DenStateItem, param2:Function, param3:Function = null, param4:Function = null) : void + { + _denStateItem = param1; + _onMouseDownCallback = param2; + _sprite.addEventListener("mouseDown",onMouseDown,false,0,true); + if(param3 != null) + { + _onMouseOverCallback = param3; + _sprite.addEventListener("mouseOver",onMouseOver,false,0,true); + } + if(param4 != null) + { + _onMouseOutCallback = param4; + _sprite.addEventListener("mouseOut",onMouseOut,false,0,true); + } + } + + public function removeMouseListeners() : void + { + _denStateItem = null; + _onMouseDownCallback = null; + _sprite.removeEventListener("mouseDown",onMouseDown); + if(_onMouseOverCallback != null) + { + _onMouseOverCallback = null; + _sprite.removeEventListener("mouseOver",onMouseOver); + } + if(_onMouseOutCallback != null) + { + _onMouseOutCallback = null; + _sprite.removeEventListener("mouseOut",onMouseOut); + } + } + + public function removePortalListeners() : void + { + _denStateItem = null; + _onMouseDownCallback = null; + _portalSprite.removeEventListener("mouseDown",onMouseDown); + if(_onMouseOverCallback != null) + { + _onMouseOverCallback = null; + _portalSprite.removeEventListener("mouseOver",onMouseOver); + } + if(_onMouseOutCallback != null) + { + _onMouseOutCallback = null; + _portalSprite.removeEventListener("mouseOut",onMouseOut); + } + } + + public function getVersions() : Array + { + if(_loader && _loader.content && _loader.content.hasOwnProperty("getVersions")) + { + return _loader.content["getVersions"](); + } + return null; + } + + public function setVersion(param1:int, param2:int = 0, param3:int = 0) : void + { + var _loc5_:MovieClip = null; + var _loc4_:int = 0; + _version = param1; + if(param2 > 0) + { + _version2 = param2; + } + if(param3 > 0) + { + _version3 = param3; + } + if(_loader && _loader.content) + { + if(_loader.content.hasOwnProperty("setVersion")) + { + if(_version == -1) + { + _version = getVersions()[0]; + } + _loader.content["setVersion"](param1); + } + else if(_loader.content.hasOwnProperty("pet")) + { + _loc5_ = MovieClip(_loader.content); + PetManager.setPetState(_loc5_,_version,_version2,_version3); + if(_petItem && _petItem.isEgg) + { + if(_loc5_.pet.hasOwnProperty("setEggDayInt")) + { + _loc4_ = _petItem.createdTs > 0 ? Math.floor((Utility.getInitialEpochTime() - _petItem.createdTs) / 86400) : 0; + _loc5_.pet.setEggDayInt(_loc4_); + } + } + } + } + } + + public function rebuildMannequinView() : void + { + var _loc1_:DenItemDef = DenXtCommManager.getDenItemDef(_defId); + if(_loc1_ != null && _loc1_.mannequinAvatarDefId > 0) + { + _isMannequin = true; + _mannequinData.setupMannequinAvatarView(_loc1_,MovieClip(_loader.content)); + } + } + + // a custom den item's own picture (AJClient.customArtUrl): in place of + // the game's art, as its icon and in a den, standing on its spot. + private function loadCustomArt() : Boolean + { + var _loc1_:String = AJClient.customArtUrl("den",_defId); + if(_loc1_ == null) + { + return false; + } + var _loc2_:DenItemHelper = this; + _sortOffset = 0; + AJClient.loadArt(_loc1_,_sprite,160,true,function():void + { + _sprite.addChild(_portalSprite); + if(_callback != null) + { + _callback(_loc2_); + _callback = null; + } + }); + return true; + } + + private function handleData(param1:FileServerEvent) : void + { + var _loc2_:Object = null; + if(param1.id == _id && param1.success) + { + DenItemServer.instance.removeEventListener("OnNewData",handleData); + _loader.contentLoaderInfo.addEventListener("complete",onBytesLoaded); + param1.data.position = 0; + _loc2_ = param1.data.readObject(); + _sortOffset = _loc2_.so; + _loader.loadBytes(_loc2_.ba); + } + } + + private function onBytesLoaded(param1:Event) : void + { + var _loc3_:MovieClip = null; + var _loc2_:int = 0; + var _loc4_:DenItemDef = null; + _loader.contentLoaderInfo.removeEventListener("complete",onBytesLoaded); + var _loc5_:Array = _loader.content["currentLabels"]; + if(_loc5_.length >= 0) + { + for each(var _loc6_:Object in _loc5_) + { + if(_loc6_.name == "flip") + { + _bFlipLabel = true; + break; + } + } + if(!Utility.doesItAnimate(_loader.content)) + { + _loader.cacheAsBitmap = true; + } + } + if(_version == -1) + { + if(_loader.content.hasOwnProperty("getVersions")) + { + _version = getVersions()[0]; + } + else + { + _version = 0; + } + } + if(_loader.content.hasOwnProperty("setVersion") && _version >= 0) + { + MovieClip(_loader.content).setVersion(_version); + } + else if(_loader.content.hasOwnProperty("pet")) + { + _loc3_ = MovieClip(_loader.content); + PetManager.setPetState(_loc3_,_version,_version2,_version3); + if(_petItem && _petItem.isEgg) + { + if(_loc3_.pet.hasOwnProperty("setEggDayInt")) + { + _loc2_ = _petItem.createdTs > 0 ? Math.floor((Utility.getInitialEpochTime() - _petItem.createdTs) / 86400) : 0; + _loc3_.pet.setEggDayInt(_loc2_); + } + } + } + if(MovieClip(_loader.content).isMoveToDisabled) + { + _loader.name = "moveToDisabled"; + } + if(_mannequinData != null) + { + _loc4_ = DenXtCommManager.getDenItemDef(_defId); + if(_loc4_ != null && _loc4_.mannequinAvatarDefId > 0) + { + _isMannequin = true; + _mannequinData.setupMannequinAvatarView(_loc4_,MovieClip(_loader.content)); + } + } + if(_denStateItem != null) + { + if(_denStateItem.specialType == 1) + { + _portalSprite.addChild(MovieClip(_loader.content).clickObject); + } + else if(_denStateItem.specialType == 2 && _loader.content.hasOwnProperty("setEmoteCallback")) + { + MovieClip(_loader.content).setEmoteCallback(onEmoteItemClicked); + } + else if(_denStateItem.specialType == 5) + { + _isDenStore = true; + } + } + if(_loader.content.hasOwnProperty("setUniqueImage")) + { + _isUniqueImageItem = true; + if(_uniqueImageId != "") + { + _masterpieceDefHelper = new MasterpieceDefHelper(); + _masterpieceDefHelper.init(_uniqueImageId,onUniqueImageIdLoaded); + } + } + _sprite.addChild(_loader); + _sprite.addChild(_portalSprite); + if(_callback != null) + { + _callback(this); + _callback = null; + } + } + + private function onUniqueImageIdLoaded(param1:Sprite) : void + { + if(_masterpieceDefHelper) + { + _masterpieceDefHelper.destroy(); + _masterpieceDefHelper = null; + } + if(_uniqueImage) + { + _uniqueImage.addChild(param1); + if(_loader && _loader.content && "setUniqueImage" in _loader.content) + { + MovieClip(_loader.content).setUniqueImage(_uniqueImage); + } + } + } + + private function onEmoteItemClicked(param1:int) : void + { + if(AvatarManager.playerAvatarWorldView && !AvatarManager.playerAvatarWorldView.isThisAttachmentOn(param1)) + { + AvatarManager.setPlayerAttachmentEmot(param1); + } + } + + private function onMouseDown(param1:MouseEvent) : void + { + if(_onMouseDownCallback != null) + { + _onMouseDownCallback(param1,this); + } + } + + private function onMouseOver(param1:MouseEvent) : void + { + if(_onMouseOverCallback != null) + { + _onMouseOverCallback(param1,this); + } + } + + private function onMouseOut(param1:MouseEvent) : void + { + if(_onMouseOutCallback != null) + { + _onMouseOutCallback(param1); + } + } + } +} + diff --git a/swf-src/DenXtCommManager.as b/swf-src/DenXtCommManager.as new file mode 100644 index 0000000..a24e8d5 --- /dev/null +++ b/swf-src/DenXtCommManager.as @@ -0,0 +1,1551 @@ +package den +{ + import Enums.DenItemDef; + import avatar.AvatarManager; + import avatar.AvatarWorldView; + import avatar.MannequinData; + import buddy.BuddyManager; + import collection.DenItemCollection; + import collection.DenItemDefCollection; + import collection.DenRoomItemCollection; + import collection.DenStateItemCollection; + import collection.IitemCollection; + import collection.IntItemCollection; + import collection.PetItemCollection; + import com.sbi.analytics.SBTracker; + import com.sbi.client.SFEvent; + import com.sbi.debug.DebugUtility; + import currency.UserCurrency; + import flash.utils.Dictionary; + import game.MinigameManager; + import game.MinigameXtCommManager; + import gui.DarkenManager; + import gui.DenSwitch; + import gui.GuiManager; + import loader.DefPacksDefHelper; + import localization.LocalizationManager; + import pet.PetDef; + import pet.PetItem; + import pet.PetManager; + import room.RoomManagerWorld; + import room.RoomXtCommManager; + import shop.ShopToSellXtCommManager; + + public class DenXtCommManager + { + + private static var _roomMgr:RoomManagerWorld; + + private static var _denChangePending:Boolean; + + private static var _pendingDenChangeItems:DenStateItemCollection; + + private static var _itemBuyCallback:Function; + + private static var _denEditorDIResponseCallback:Function; + + private static var _denItemsCallback:Function; + + private static var _denMasterpieceItemsCallback:Function; + + private static var _denListCallback:Function; + + private static var _denRecycleCallback:Function; + + private static var _recycleDiCallback:Function; + + private static var _denRoomBuyCallback:Function; + + private static var _denHighestCallback:Function; + + private static var _denPrivateCallback:Function; + + private static var _denChangeCallback:Function; + + private static var _dmcCallback:Function; + + private static var _onDenSaveSetCallback:Function; + + private static var _ecoRefreshCallback:Function; + + private static var _ecoCreditRedeemCallback:Function; + + private static var _ecoConsumerCallback:Function; + + private static var _isBuyingDenRoom:Boolean; + + private static var _cachedDlResponse:Object; + + private static var _denItemDefs:DenItemDefCollection; + + public function DenXtCommManager() + { + super(); + } + + public static function init(param1:Function) : void + { + _roomMgr = RoomManagerWorld.instance; + _denListCallback = param1; + _denChangePending = false; + _pendingDenChangeItems = null; + new DenMannequinInventory(); + var _loc2_:DefPacksDefHelper = new DefPacksDefHelper(); + _loc2_.init(1030,denItemDefsResponse,null,2); + DefPacksDefHelper.mediaArray[1030] = _loc2_; + XtReplyDemuxer.addModule(handleXtReply,"d"); + } + + public static function destroy() : void + { + _denEditorDIResponseCallback = null; + _denItemsCallback = null; + _denRecycleCallback = null; + _recycleDiCallback = null; + } + + public static function requestDenStateChange(param1:Array, param2:Function) : void + { + var _loc3_:MannequinData = null; + var _loc5_:int = 0; + var _loc4_:Array = []; + var _loc6_:int = 0; + _loc4_[_loc6_++] = param1.length; + _loc5_ = 0; + while(_loc5_ < param1.length) + { + _loc3_ = param1[_loc5_].mannequinData; + _loc4_[_loc6_++] = param1[_loc5_].r; + _loc4_[_loc6_++] = param1[_loc5_].i; + _loc4_[_loc6_++] = param1[_loc5_].d; + _loc4_[_loc6_++] = param1[_loc5_].x; + _loc4_[_loc6_++] = param1[_loc5_].y; + _loc4_[_loc6_++] = param1[_loc5_].f ? param1[_loc5_].f : 0; + _loc4_[_loc6_++] = param1[_loc5_].userNameLink == "" ? "off" : param1[_loc5_].userNameLink; + _loc4_[_loc6_++] = _loc3_ == null ? 0 : _loc3_.baseColor; + _loc4_[_loc6_++] = _loc3_ == null ? 0 : _loc3_.patternColor; + _loc4_[_loc6_++] = _loc3_ == null ? 0 : _loc3_.patternDefId; + _loc4_[_loc6_++] = _loc3_ == null ? 0 : _loc3_.eyeColor; + _loc4_[_loc6_++] = _loc3_ == null ? 0 : _loc3_.eyeDefId; + _loc4_[_loc6_++] = _loc3_ == null ? 0 : _loc3_.tailInvId; + _loc4_[_loc6_++] = _loc3_ == null ? 0 : _loc3_.legInvId; + _loc4_[_loc6_++] = _loc3_ == null ? 0 : _loc3_.backInvId; + _loc4_[_loc6_++] = _loc3_ == null ? 0 : _loc3_.neckInvId; + _loc4_[_loc6_++] = _loc3_ == null ? 0 : _loc3_.headInvId; + _loc5_++; + } + _onDenSaveSetCallback = param2; + gMainFrame.server.setXtObject_Str("ds",_loc4_); + } + + public static function requestDenItems(param1:Function = null) : void + { + _denItemsCallback = param1; + gMainFrame.server.setXtObject_Str("di",[]); + } + + public static function requestDenMasterpieceItems(param1:String, param2:Function) : void + { + _denMasterpieceItemsCallback = param2; + gMainFrame.server.setXtObject_Str("dmi",[param1]); + } + + public static function requestDenRoomList() : void + { + gMainFrame.server.setXtObject_Str("dl",[]); + } + + public static function requestBuy(param1:Boolean, param2:int, param3:int, param4:Function, param5:Function, param6:int = 0, param7:Function = null, param8:int = 0, param9:int = 0, param10:Boolean = false, param11:Boolean = false, param12:String = "") : void + { + _itemBuyCallback = param4; + _denEditorDIResponseCallback = param5; + if(param1) + { + gMainFrame.server.setXtObject_Str("db",["0",param2,param3,param8,param9,param10 ? "1" : "0",param11 ? "1" : "0",param12]); + } + else + { + _isBuyingDenRoom = true; + gMainFrame.server.setXtObject_Str("db",["-1",param2,param3,param6,param9]); + _denRoomBuyCallback = param7; + } + } + + public static function requestRecycle(param1:Boolean, param2:IntItemCollection, param3:Function, param4:Function = null) : void + { + _denRecycleCallback = param3; + _recycleDiCallback = param4; + gMainFrame.server.setXtObject_Str("dr",[param1 ? "0" : "-1",param2.getCoreArray()]); + } + + public static function requestDenChange(param1:int, param2:Function) : void + { + _denChangeCallback = param2; + gMainFrame.server.setXtObject_Str("dc",[DenSwitch.denList.getDenRoomItem(param1).invIdx]); + } + + public static function requestDenJoinFull(param1:String, param2:int = -1, param3:Boolean = true, param4:Boolean = true) : void + { + var _loc5_:String = null; + if(!RoomXtCommManager.isSwitching) + { + if(RoomXtCommManager.loadingNewRoom) + { + DebugUtility.debugTrace("INGORING requestDenJoinFull request because user is already joining a new room!"); + return; + } + if(gMainFrame.server.getCurrentRoom()) + { + if(param1 == gMainFrame.server.getCurrentRoomName()) + { + trace("WARNING: User is already in this den!"); + DarkenManager.showLoadingSpiral(false); + return; + } + } + DarkenManager.showLoadingSpiral(true); + AvatarManager.joiningNewRoom = true; + if(RoomManagerWorld.instance.haveHadLastGoodRoomName()) + { + SBTracker.trackPageview("/game/play/loading/changeRooms"); + } + RoomXtCommManager.denJoinRequested(param1); + _denChangePending = true; + _loc5_ = param4 ? "1" : "0"; + gMainFrame.server.setXtObject_Str("dj",[param1,_loc5_,param2]); + if(param3 || _roomMgr.forceInvisMode) + { + _roomMgr.forceInvisMode = true; + } + } + else + { + DarkenManager.showLoadingSpiral(false); + } + } + + public static function requestDenHighest() : void + { + gMainFrame.server.setXtObject_Str("dh",[]); + } + + public static function requestSetDenPrivacy(param1:int) : void + { + gMainFrame.server.setXtObject_Str("dp",["0",param1]); + } + + public static function requestUserDenPrivacy(param1:String) : void + { + gMainFrame.server.setXtObject_Str("dp",["1",param1]); + } + + public static function requestEmptyDen() : void + { + gMainFrame.server.setXtObject_Str("de",[]); + } + + public static function requestDenPhantom(param1:int) : void + { + gMainFrame.server.setXtObject_Str("dph",[param1]); + } + + public static function requestDenMasterpieceCreatorName(param1:String, param2:String, param3:Function) : void + { + _dmcCallback = param3; + gMainFrame.server.setXtObject_Str("dmc",[param1,param2]); + } + + public static function requestDenEcoCreditRefresh(param1:Function) : void + { + _ecoRefreshCallback = param1; + gMainFrame.server.setXtObject_Str("dEf",[]); + } + + public static function requestDenEcoCreditRedeem(param1:Function) : void + { + _ecoCreditRedeemCallback = param1; + gMainFrame.server.setXtObject_Str("dEr",[]); + } + + public static function requestDenEcoConsumer(param1:int, param2:Boolean, param3:Function) : void + { + _ecoConsumerCallback = param3; + gMainFrame.server.setXtObject_Str("dEc",[param1,param2 ? "1" : "0"]); + } + + public static function handleXtReply(param1:SFEvent) : void + { + var _loc2_:Object = param1.obj; + switch(_loc2_[0]) + { + case "ds": + denStateResponse(_loc2_); + break; + case "dss": + denStateSetResponse(_loc2_); + break; + case "dp": + denPrivacyResponse(_loc2_); + break; + case "dpk": + denPrivacyKickResponse(); + break; + case "di": + denItemsResponse(_loc2_); + break; + case "dc": + denChangeResponse(_loc2_); + break; + case "db": + denBuyResponse(_loc2_); + break; + case "dr": + denRecycleResponse(_loc2_); + break; + case "dh": + denHighestResponse(_loc2_); + break; + case "dl": + denListResponse(_loc2_); + break; + case "drc": + denRoomCount(_loc2_); + break; + case "de": + denEmptyResponse(_loc2_); + break; + case "dmi": + denMasterpieceInventoryResponse(_loc2_); + break; + case "dph": + denPhantomResponse(_loc2_); + break; + case "dmc": + denMasterpieceCreatorResponse(_loc2_); + break; + case "dEf": + denEcoRefreshResponse(_loc2_); + break; + case "dEr": + denEcoCreditRefreshResponse(_loc2_); + break; + case "dEc": + denEcoConsumerResponse(_loc2_); + break; + default: + ShopToSellXtCommManager.handleXtReply(param1); + } + } + + public static function denItemsResponse(param1:Object) : void + { + var _loc31_:int = 0; + var _loc28_:int = 0; + var _loc32_:int = 0; + var _loc24_:int = 0; + var _loc14_:* = false; + var _loc33_:String = null; + var _loc17_:int = 0; + var _loc30_:String = null; + var _loc4_:MannequinData = null; + var _loc26_:int = 0; + var _loc21_:int = 0; + var _loc18_:DenItem = null; + var _loc22_:DenItemDef = null; + var _loc7_:PetItem = null; + if(gMainFrame.userInfo.playerUserInfo == null) + { + return; + } + var _loc23_:int = 2; + DenSwitch.activeDenIdx = int(param1[_loc23_++]); + var _loc13_:int = int(param1[_loc23_++]); + var _loc15_:int = int(param1[_loc23_++]); + var _loc6_:DenItemCollection = new DenItemCollection(); + new DenMannequinInventory(); + var _loc20_:Array = []; + var _loc8_:Boolean = true; + _loc21_ = 0; + while(_loc21_ < _loc13_) + { + _loc18_ = new DenItem(); + _loc31_ = int(param1[_loc23_++]); + _loc28_ = int(param1[_loc23_++]); + _loc32_ = int(param1[_loc23_++]); + _loc24_ = int(param1[_loc23_++]); + _loc14_ = param1[_loc23_++] == "true"; + _loc33_ = param1[_loc23_++]; + _loc17_ = int(param1[_loc23_++]); + _loc30_ = param1[_loc23_++]; + _loc22_ = getDenItemDef(_loc28_); + if(_loc22_) + { + if(_loc22_.sortCat == 4 && _loc32_ > 0) + { + _loc8_ = false; + } + if(_loc22_.specialType == 4) + { + _loc4_ = new MannequinData(); + _loc23_ = _loc4_.init(_loc22_,param1,_loc23_,true,_loc31_,true); + } + _loc26_ = int(param1[_loc23_++]); + _loc18_.init(_loc28_,_loc31_,_loc32_,_loc24_,0,null,_loc14_,_loc33_,"",_loc17_,_loc30_,_loc4_,_loc26_); + _loc6_.setDenItem(_loc21_,_loc18_); + if(_loc18_.minigameDefId > 0 && !MinigameManager.minigameInfoCache.getMinigameInfo(_loc18_.minigameDefId)) + { + _loc20_.push(_loc18_.minigameDefId); + } + } + _loc21_++; + } + _loc6_.getCoreArray().sortOn("invIdx",0x10 | 2); + _loc18_ = new DenItem(); + _loc18_.init(617,-1,_loc8_ ? 7 : 0); + _loc6_.getCoreArray().unshift(_loc18_); + var _loc3_:PetItemCollection = PetManager.myPetListAsIitem; + var _loc27_:DenItemCollection = new DenItemCollection(); + var _loc19_:DenItemCollection = new DenItemCollection(); + _loc21_ = 0; + while(_loc21_ < _loc3_.length) + { + _loc7_ = _loc3_.getPetItem(_loc21_); + _loc18_ = new DenItem(); + _loc18_.init(_loc7_.defId,_loc7_.invIdx,0,0,1,_loc7_); + if(PetManager.canPetGoInBothEnviroTypes(_loc7_.currPetDef,_loc7_.createdTs)) + { + _loc27_.pushDenItem(_loc18_); + _loc19_.pushDenItem(_loc18_); + } + else if(_loc18_.enviroType == 2 || _loc18_.enviroType == 0) + { + _loc27_.pushDenItem(_loc18_); + } + else + { + _loc19_.pushDenItem(_loc18_); + } + _loc21_++; + } + _loc27_.getCoreArray().sortOn("invIdx",0x10 | 2); + _loc19_.getCoreArray().sortOn("invIdx",0x10 | 2); + var _loc25_:int = 0; + while(_loc25_ < _loc15_) + { + _loc31_ = int(param1[_loc23_ + _loc25_]); + _loc21_ = 0; + while(_loc21_ < _loc27_.length) + { + if(_loc27_.getDenItem(_loc21_).invIdx == _loc31_) + { + _loc27_.getDenItem(_loc21_).categoryId = 1; + break; + } + _loc21_++; + } + _loc21_ = 0; + while(_loc21_ < _loc19_.length) + { + if(_loc19_.getDenItem(_loc21_).invIdx == _loc31_) + { + _loc19_.getDenItem(_loc21_).categoryId = 1; + break; + } + _loc21_++; + } + _loc25_++; + } + if(_loc20_.length > 0) + { + MinigameXtCommManager.sendMinigameInfoRequest(_loc20_); + } + gMainFrame.userInfo.playerUserInfo.denItemsPartial = enviroItems(_loc6_); + if(AvatarManager.playerAvatar != null) + { + AvatarManager.playerAvatar.inventoryDenPartial.denItemCollection = gMainFrame.userInfo.playerUserInfo.denItemsPartial; + AvatarManager.playerAvatar.inventoryDenFull.denItemCollection = _loc6_; + } + gMainFrame.userInfo.playerUserInfo.denItemsFull = _loc6_; + gMainFrame.userInfo.setMyPetsInDenByEnviroType(_loc27_,0); + gMainFrame.userInfo.setMyPetsInDenByEnviroType(_loc19_,1); + if(_denItemsCallback != null) + { + _denItemsCallback(); + } + if(_denEditorDIResponseCallback != null) + { + _denEditorDIResponseCallback(); + } + if(_recycleDiCallback != null) + { + _recycleDiCallback(); + } + } + + public static function addPetToDen(param1:PetItem) : void + { + var _loc2_:DenItem = new DenItem(); + _loc2_.init(param1.defId,param1.invIdx,0,0,1,param1); + if(PetManager.canPetGoInBothEnviroTypes(param1.currPetDef,param1.createdTs)) + { + if(gMainFrame.userInfo.getMyPetsInDenByEnviroType(0)) + { + gMainFrame.userInfo.getMyPetsInDenByEnviroType(0).getCoreArray().unshift(_loc2_); + } + else + { + gMainFrame.userInfo.setMyPetsInDenByEnviroType(new DenItemCollection(),0); + gMainFrame.userInfo.getMyPetsInDenByEnviroType(0).pushDenItem(_loc2_); + } + if(gMainFrame.userInfo.getMyPetsInDenByEnviroType(1)) + { + gMainFrame.userInfo.getMyPetsInDenByEnviroType(1).getCoreArray().unshift(_loc2_); + } + else + { + gMainFrame.userInfo.setMyPetsInDenByEnviroType(new DenItemCollection(),1); + gMainFrame.userInfo.getMyPetsInDenByEnviroType(1).pushDenItem(_loc2_); + } + } + else if(gMainFrame.userInfo.getMyPetsInDenByEnviroType(_loc2_.enviroType)) + { + gMainFrame.userInfo.getMyPetsInDenByEnviroType(_loc2_.enviroType).getCoreArray().unshift(_loc2_); + } + else + { + gMainFrame.userInfo.setMyPetsInDenByEnviroType(new DenItemCollection(),_loc2_.enviroType); + gMainFrame.userInfo.getMyPetsInDenByEnviroType(_loc2_.enviroType).pushDenItem(_loc2_); + } + GuiManager.resetPetWindowListAndUpdateBtns(); + } + + public static function removePetFromDen(param1:int, param2:PetItem) : void + { + if(PetManager.canPetGoInBothEnviroTypes(param2.currPetDef,param2.createdTs)) + { + removePetFromDenByEnviroType(param1,0); + removePetFromDenByEnviroType(param1,1); + } + else + { + removePetFromDenByEnviroType(param1,PetManager.getEnviroTypeByPetType(param2.currPetDef,param2.createdTs)); + } + GuiManager.resetPetWindowListAndUpdateBtns(); + } + + private static function removePetFromDenByEnviroType(param1:int, param2:int) : void + { + var _loc3_:int = 0; + var _loc4_:DenItemCollection = gMainFrame.userInfo.getMyPetsInDenByEnviroType(param2); + if(!_loc4_) + { + return; + } + _loc3_ = 0; + while(_loc3_ < _loc4_.length) + { + if(_loc4_.getDenItem(_loc3_).invIdx == param1) + { + _loc4_.getCoreArray().splice(_loc3_,1); + break; + } + _loc3_++; + } + } + + public static function reloadPetInDen(param1:int, param2:Number, param3:int, param4:String, param5:int, param6:int, param7:int, param8:int, param9:int, param10:int) : void + { + if(PetManager.canPetGoInBothEnviroTypes(PetManager.getPetDef(param5 & 0xFF),param2)) + { + updatePetInDenByEnviroType(param1,param2,0,param4,param5,param6,param7,param8,param9,param10); + updatePetInDenByEnviroType(param1,param2,1,param4,param5,param6,param7,param8,param9,param10); + } + else + { + updatePetInDenByEnviroType(param1,param2,PetManager.getEnviroTypeByPetType(PetManager.getPetDef(param5 & 0xFF),param2),param4,param5,param6,param7,param8,param9,param10); + } + GuiManager.resetPetWindowListAndUpdateBtns(); + } + + private static function updatePetInDenByEnviroType(param1:int, param2:Number, param3:int, param4:String, param5:int, param6:int, param7:int, param8:int, param9:int, param10:int) : void + { + var _loc11_:int = 0; + var _loc12_:DenItem = null; + var _loc13_:DenItemCollection = gMainFrame.userInfo.getMyPetsInDenByEnviroType(param3); + if(!_loc13_) + { + return; + } + _loc11_ = 0; + while(_loc11_ < _loc13_.length) + { + _loc12_ = _loc13_.getDenItem(_loc11_); + if(_loc12_.invIdx == param1) + { + _loc12_.version = param5; + _loc12_.version2 = param6; + _loc12_.version3 = param7; + _loc12_.petTraitDefId = param8; + _loc12_.petFoodDefId = param9; + _loc12_.petToyDefId = param10; + _loc12_.createdTs = param2; + _loc12_.name = LocalizationManager.translatePetName(param4); + if(_loc12_.petItem) + { + _loc12_.petItem.setPetBits(param5,param6,param7); + _loc12_.petItem.traitDefId = param8; + _loc12_.petItem.foodDefId = param9; + _loc12_.petItem.toyDefId = param10; + _loc12_.petItem.createdTs = param2; + } + break; + } + _loc11_++; + } + } + + public static function set denEditorDIResponseCallback(param1:Function) : void + { + _denEditorDIResponseCallback = param1; + } + + private static function denBuyResponse(param1:Object) : void + { + var _loc5_:Object = null; + var _loc6_:int = int(param1[2]); + var _loc2_:int = int(param1[5]); + var _loc4_:int = int(param1[4]); + var _loc3_:int = int(param1[6]); + if(param1[3] == "") + { + _loc5_ = UserCurrency.getCurrency(_loc2_); + if(_loc5_ == null) + { + throw new Error("DenXtCommManager: Received unknown currencyType: " + _loc2_); + } + } + else + { + _loc5_ = param1[3]; + } + if(_loc6_ == 1) + { + if(!UserCurrency.setCurrency(_loc5_,_loc2_)) + { + throw new Error("ItemManager: Received unknown currencyType: " + _loc2_); + } + } + if(_itemBuyCallback != null) + { + _itemBuyCallback(_loc6_,_loc5_,_loc3_); + _itemBuyCallback = null; + } + } + + private static function denRecycleResponse(param1:Object) : void + { + var _loc5_:int = 0; + var _loc6_:int = 2; + var _loc2_:int = int(param1[_loc6_++]); + var _loc4_:int = UserCurrency.getCurrency(0) as int; + var _loc3_:int = int(param1[_loc6_] == "-1" ? _loc4_ : param1[_loc6_]); + _loc6_++; + var _loc7_:Vector. = new Vector.(); + if(_loc2_ > 0) + { + _loc5_ = 0; + while(_loc5_ < _loc2_) + { + _loc7_.push(param1[_loc6_++]); + _loc5_++; + } + UserCurrency.setCurrency(_loc3_,0); + } + if(_denRecycleCallback != null) + { + _denRecycleCallback(_loc7_); + } + } + + private static function denHighestResponse(param1:Object) : void + { + var _loc4_:int = 0; + var _loc5_:int = 2; + var _loc2_:int = int(param1[_loc5_++]); + var _loc3_:Array = new Array(_loc2_); + _loc4_ = 0; + while(_loc4_ < _loc2_) + { + _loc3_[_loc4_] = param1[_loc5_++]; + _loc4_++; + } + if(_denHighestCallback != null) + { + _denHighestCallback(_loc3_); + } + } + + private static function denPrivateResponse(param1:Object) : void + { + if(_denPrivateCallback != null) + { + _denPrivateCallback(param1[3],param1[4] == "1"); + } + } + + private static function denRoomCount(param1:Object) : void + { + var _loc5_:int = 2; + var _loc3_:int = int(param1[_loc5_++]); + var _loc2_:* = param1[_loc5_++] == "1"; + var _loc4_:String = param1[_loc5_++]; + GuiManager.updateDenRoomCount(_loc3_,_loc2_,_loc4_); + } + + private static function denListResponse(param1:Object) : void + { + var _loc6_:int = 0; + var _loc2_:int = 0; + var _loc9_:DenRoomItemCollection = null; + var _loc5_:int = 0; + var _loc7_:DenRoomItem = null; + var _loc8_:int = 0; + var _loc3_:int = 0; + var _loc4_:Object = null; + if(gMainFrame.userInfo.denRoomDefs) + { + _loc6_ = 2; + _loc2_ = int(param1[_loc6_++]); + _loc9_ = new DenRoomItemCollection(); + _loc5_ = 0; + while(_loc5_ < _loc2_) + { + _loc7_ = new DenRoomItem(); + _loc8_ = int(param1[_loc6_++]); + _loc3_ = int(param1[_loc6_++]); + _loc4_ = gMainFrame.userInfo.getDenRoomDefByDefId(_loc3_); + if(_loc4_) + { + _loc7_.init(_loc8_,_loc3_,_loc4_); + _loc9_.setDenRoomItem(_loc8_,_loc7_); + } + _loc5_++; + } + if(_denListCallback != null) + { + _denListCallback(_loc9_); + } + if(_isBuyingDenRoom) + { + if(_denRoomBuyCallback != null) + { + _denRoomBuyCallback(); + } + _isBuyingDenRoom = false; + _denRoomBuyCallback = null; + } + if(GuiManager.denEditor) + { + GuiManager.denEditor.reloadDenItems(); + } + } + else + { + _cachedDlResponse = param1; + } + } + + public static function denRoomResponse(param1:DefPacksDefHelper) : void + { + var _loc4_:Object = null; + var _loc5_:Object = param1.def; + DefPacksDefHelper.mediaArray[1040] = null; + var _loc2_:Object = {}; + for each(var _loc3_ in param1.def) + { + _loc4_ = { + "value":int(_loc3_.cost), + "enviroType":int(_loc3_.enviroType), + "mediaIdLarge":int(_loc3_.iconMediaRef), + "defId":Number(_loc3_.id), + "mediaId":int(_loc3_.mediaRef), + "name":LocalizationManager.translateIdOnly(_loc3_.titleStrRef), + "titleStrRef":int(_loc3_.titleStrRef), + "status":int(_loc3_.storeStatus), + "membersOnly":_loc3_.membersOnly == "1", + "roomDefId":int(_loc3_.roomDefId), + "availabilityStartTime":uint(_loc3_.availabilityStartTime), + "availabilityEndTime":uint(_loc3_.availabilityEndTime) + }; + _loc2_[_loc4_.defId] = _loc4_; + } + gMainFrame.userInfo.denRoomDefs = _loc2_; + if(_cachedDlResponse) + { + denListResponse(_cachedDlResponse); + _cachedDlResponse = null; + } + } + + public static function relocalizeDenRooms() : void + { + var _loc1_:Object = gMainFrame.userInfo.denRoomDefs; + for each(var _loc2_ in _loc1_) + { + _loc2_.name = LocalizationManager.translateIdOnly(_loc2_.titleStrRef); + } + gMainFrame.userInfo.denRoomDefs = _loc1_; + } + + private static function denStateResponse(param1:Object) : void + { + var _loc38_:int = 0; + var _loc27_:int = 0; + var _loc12_:* = false; + var _loc33_:int = 0; + var _loc34_:int = 0; + var _loc24_:int = 0; + var _loc2_:int = 0; + var _loc22_:String = null; + var _loc39_:String = null; + var _loc15_:int = 0; + var _loc36_:String = null; + var _loc29_:int = 0; + var _loc28_:* = 0; + var _loc6_:int = 0; + var _loc3_:MannequinData = null; + var _loc4_:int = 0; + var _loc21_:int = 0; + var _loc19_:DenItemDef = null; + var _loc5_:int = 0; + var _loc7_:int = 0; + var _loc17_:int = 0; + var _loc25_:Number = NaN; + var _loc30_:int = 0; + var _loc16_:int = 0; + var _loc11_:int = 0; + var _loc8_:String = null; + var _loc35_:PetItem = null; + var _loc31_:PetDef = null; + var _loc10_:Boolean = false; + var _loc32_:int = 0; + var _loc13_:DenStateItem = null; + var _loc37_:DenStateItem = null; + var _loc20_:int = 2; + var _loc26_:int = int(param1[_loc20_++]); + var _loc14_:int = int(param1[_loc20_++]); + var _loc23_:* = param1[_loc20_++] == "1"; + var _loc9_:DenStateItemCollection = new DenStateItemCollection(); + DebugUtility.debugTrace("gettind den state with numItems=" + _loc26_ + "forceReload=" + _loc23_); + var _loc18_:Array = []; + _loc21_ = 0; + while(_loc21_ < _loc26_) + { + _loc38_ = int(param1[_loc20_++]); + _loc27_ = int(param1[_loc20_++]); + _loc19_ = getDenItemDef(_loc27_); + if(!_loc19_) + { + _loc9_.setDenStateItem(_loc21_,new DenStateItem(0,_loc38_,0,0,0,0,0,0,0,0,0,0,0,0,0,"",0,"",0,0,"","",-1,"",false,null,0,0,null,null,2)); + } + else + { + _loc12_ = param1[_loc20_++] == "1"; + _loc33_ = int(param1[_loc20_++]); + _loc34_ = int(param1[_loc20_++]); + _loc24_ = int(param1[_loc20_++]); + _loc2_ = int(param1[_loc20_++]); + _loc22_ = param1[_loc20_] == "null" ? "" : param1[_loc20_]; + _loc20_++; + _loc39_ = param1[_loc20_++]; + _loc15_ = int(param1[_loc20_++]); + _loc36_ = param1[_loc20_++]; + if(_loc19_.specialType == 4) + { + _loc3_ = new MannequinData(); + _loc20_ = _loc3_.init(_loc19_,param1,_loc20_,false,_loc38_,RoomManagerWorld.instance.isMyDen); + } + _loc4_ = int(param1[_loc20_++]); + _loc29_ = _loc19_.sortCat; + if(_loc12_) + { + if(_loc29_ == 0 || _loc29_ == 99 || _loc29_ == 6 || _loc29_ == 5) + { + _loc29_ = 1; + } + else if(_loc29_ == 1) + { + _loc29_ = 2; + } + else if(_loc29_ == 4) + { + _loc29_ = 3; + } + else if(_loc29_ == 2 || _loc29_ == 3) + { + _loc29_ = _roomMgr.denCatId; + } + else + { + _loc29_ = -1; + } + } + else + { + _loc29_ = -1; + } + _loc28_ = uint(_loc27_ << 16 | _loc29_); + _loc6_ = _loc19_.gameDefId; + if(_loc6_ > 0 && !MinigameManager.minigameInfoCache.getMinigameInfo(_loc6_)) + { + _loc18_.push(_loc6_); + } + _loc9_.setDenStateItem(_loc21_,new DenStateItem(_loc27_,_loc38_,_loc28_,_loc33_,_loc34_,_loc24_,_loc19_.flag,0,_loc2_,_loc29_,0,_loc19_.sortCat,_loc19_.gameDefId,_loc19_.layer,_loc19_.enviroType,_loc19_.abbrName,_loc19_.nameStrId,_loc22_,_loc19_.specialType,_loc19_.listId,_loc39_,"",_loc15_,_loc36_,false,null,0,0,null,_loc3_,_loc4_)); + } + _loc21_++; + } + _loc21_ = 0; + while(_loc21_ < _loc14_) + { + _loc38_ = int(param1[_loc20_++]); + _loc5_ = int(param1[_loc20_++]); + _loc27_ = PetManager.getDefIdFromLBits(_loc5_); + _loc31_ = PetManager.getPetDef(_loc27_); + if(_loc31_ == null) + { + _loc9_.setDenStateItem(_loc21_,new DenStateItem(0,_loc38_,0,0,0,0,0,0,0,0,1,99,0,0,0,"",0,"",0,0,"","",-1,"",false,null,0,0,null,null,2)); + } + else + { + _loc7_ = int(param1[_loc20_++]); + _loc17_ = int(param1[_loc20_++]); + _loc29_ = int(param1[_loc20_++]); + _loc33_ = int(param1[_loc20_++]); + _loc34_ = int(param1[_loc20_++]); + _loc2_ = int(param1[_loc20_++]); + _loc25_ = Number(param1[_loc20_++]); + _loc30_ = int(param1[_loc20_++]); + _loc16_ = int(param1[_loc20_++]); + _loc11_ = int(param1[_loc20_++]); + _loc8_ = param1[_loc20_++]; + _loc27_ = denItemDefIdForPetDefId(_loc27_); + _loc28_ = uint(_loc27_ << 16 | _loc29_); + _loc35_ = new PetItem(); + _loc35_.init(_loc25_,_loc31_.defId,[_loc5_,_loc7_,_loc17_],_loc30_,_loc16_,_loc11_,_loc38_,_loc8_); + _loc9_.setDenStateItem(_loc26_ + _loc21_,new DenStateItem(_loc27_,_loc38_,_loc28_,_loc33_,_loc34_,_loc5_,_loc7_,_loc17_,_loc2_,_loc29_,1,99,0,0,PetManager.getEnviroTypeByPetType(_loc31_,_loc25_),"",_loc31_.titleStrId,"",0,0,"","",-1,"",false,null,0,0,_loc35_,null,2)); + } + _loc21_++; + } + if(_loc18_.length > 0) + { + MinigameXtCommManager.sendMinigameInfoRequest(_loc18_); + } + if(_pendingDenChangeItems && _pendingDenChangeItems.length > 0) + { + _loc32_ = int(_pendingDenChangeItems.length); + _loc20_ = 0; + while(_loc20_ < _loc9_.getCoreArray().length) + { + _loc10_ = false; + _loc21_ = 0; + while(_loc21_ < _loc32_) + { + if(_loc9_.getDenStateItem(_loc20_).refId == _pendingDenChangeItems.getDenStateItem(_loc21_).refId && _loc9_.getDenStateItem(_loc20_).invIdx == _pendingDenChangeItems.getDenStateItem(_loc21_).invIdx) + { + _loc10_ = true; + _loc37_ = _pendingDenChangeItems.getDenStateItem(_loc21_); + _loc13_ = _loc9_.getDenStateItem(_loc20_); + _loc37_.x = _loc13_.x; + _loc37_.y = _loc13_.y; + _loc37_.version = _loc13_.version; + _loc37_.version2 = _loc13_.version2; + _loc37_.flipped = _loc13_.flipped; + _loc37_.catId = _loc13_.catId; + _loc37_.userNameLink = _loc13_.userNameLink; + _loc37_.uniqueImageId = _loc13_.uniqueImageId; + _loc37_.uniqueImageCreator = _loc13_.uniqueImageCreator; + _loc37_.mannequinData = _loc13_.mannequinData; + break; + } + _loc21_++; + } + if(!_loc10_) + { + _pendingDenChangeItems.pushDenStateItem(_loc9_.getDenStateItem(_loc20_)); + } + _loc20_++; + } + } + else + { + _pendingDenChangeItems = _loc9_; + } + if(!_denChangePending || _loc23_) + { + setDenItems(); + } + if(_loc23_) + { + DarkenManager.showLoadingSpiral(false); + RoomXtCommManager.loadingNewRoom = false; + AvatarManager.joiningNewRoom = false; + } + } + + private static function denStateSetResponse(param1:Object) : void + { + if(_onDenSaveSetCallback != null) + { + _onDenSaveSetCallback(param1 as Array); + _onDenSaveSetCallback = null; + } + } + + private static function denEmptyResponse(param1:Object) : void + { + _roomMgr.denItemHolder.clearDen(); + if(GuiManager.denEditor) + { + GuiManager.denEditor.clearDenInUseItems(); + } + } + + private static function denPrivacyResponse(param1:Object) : void + { + BuddyManager.onDenPrivacyResponse(param1[2],param1[3]); + } + + private static function denPrivacyKickResponse() : void + { + _roomMgr.needsToSeeKickFromDenMessage = true; + } + + private static function denChangeResponse(param1:Object) : void + { + _denChangePending = true; + var _loc2_:int = int(param1[2]); + if(param1.length >= 4) + { + gMainFrame.userInfo.myPerUserAvId = int(param1[3]); + PetManager.myActivePetInvId = int(param1[4]); + } + var _loc3_:Object = gMainFrame.userInfo.getDenRoomDefByDefId(_loc2_); + var _loc4_:Object = _loc3_ != null ? RoomXtCommManager.getRoomDef(_loc3_.roomDefId) : null; + if(_denChangeCallback != null) + { + _denChangeCallback(_loc4_ != null && _loc3_ != null); + _denChangeCallback = null; + } + if(_loc4_ && _loc3_) + { + _roomMgr.loadRoom(_loc4_.pathName,_loc3_.enviroType,2,_loc3_.defId,100,_loc3_.roomDefId,null); + } + } + + private static function denMasterpieceInventoryResponse(param1:Object) : void + { + var _loc2_:DenItem = null; + var _loc4_:int = 0; + var _loc6_:int = int(param1[2]); + var _loc3_:DenItemCollection = new DenItemCollection(); + var _loc5_:int = 3; + _loc4_ = 0; + while(_loc4_ < _loc6_) + { + _loc2_ = new DenItem(); + _loc2_.init(param1[_loc5_++],param1[_loc5_++],0,param1[_loc5_++],0,null,param1[_loc5_++],param1[_loc5_++],"",param1[_loc5_++],param1[_loc5_++]); + _loc3_.pushDenItem(_loc2_); + _loc4_++; + } + if(_denMasterpieceItemsCallback != null) + { + _denMasterpieceItemsCallback(_loc3_); + _denMasterpieceItemsCallback = null; + } + } + + private static function denMasterpieceCreatorResponse(param1:Object) : void + { + if(_dmcCallback != null) + { + _dmcCallback(param1[2]); + _dmcCallback = null; + } + } + + private static function denPhantomResponse(param1:Object) : void + { + var _loc3_:AvatarWorldView = null; + var _loc2_:* = param1[2] == "1"; + if(_loc2_) + { + _loc3_ = AvatarManager.getAvatarWorldViewBySfsUserId(param1[3]); + if(_loc3_ != null) + { + _loc3_.setAvatarAsPhantom(param1[4] == "1"); + } + } + } + + public static function handleDenShopList(param1:Array, param2:int, param3:Function) : IitemCollection + { + var _loc8_:IitemCollection = null; + var _loc6_:int = 0; + var _loc7_:DenRoomItem = null; + var _loc10_:Object = null; + var _loc4_:int = 8; + var _loc5_:String = param1[4]; + var _loc9_:int = int(param1[_loc4_++]); + if(param2 == 1030) + { + _loc8_ = generateDenShopList(_loc9_,param1.splice(_loc4_++,param1.length)); + } + else + { + _loc8_ = new IitemCollection(); + _loc6_ = 0; + while(_loc6_ < _loc9_) + { + _loc7_ = new DenRoomItem(); + _loc10_ = gMainFrame.userInfo.getDenRoomDefByDefId(param1[_loc4_++]); + _loc7_.initShopItem(_loc6_,_loc10_.defId,_loc10_); + _loc8_.setIitem(_loc6_,_loc7_); + _loc6_++; + } + } + if(param3 != null) + { + param3(_loc8_,_loc5_); + } + return _loc8_; + } + + public static function denEcoRefreshResponse(param1:Object) : void + { + if(_ecoRefreshCallback != null) + { + _ecoRefreshCallback(new EcoStateResponse(param1)); + _ecoRefreshCallback = null; + } + } + + public static function denEcoCreditRefreshResponse(param1:Object) : void + { + if(_ecoCreditRedeemCallback != null) + { + _ecoCreditRedeemCallback(param1[2] == "1",param1[3]); + _ecoCreditRedeemCallback = null; + } + } + + public static function denEcoConsumerResponse(param1:Object) : void + { + var _loc6_:int = 0; + var _loc5_:int = 2; + var _loc3_:int = int(param1[_loc5_++]); + var _loc4_:int = int(param1[_loc5_++]); + var _loc7_:int = int(param1[_loc5_++]); + var _loc2_:Dictionary = new Dictionary(); + if(_loc7_ > 0) + { + _loc6_ = 0; + while(_loc6_ < _loc7_) + { + _loc2_[int(param1[_loc5_++])] = param1[_loc5_++]; + _loc6_++; + } + _roomMgr.denItemHolder.updateConsumers(_loc2_); + } + if(_ecoConsumerCallback != null) + { + _ecoConsumerCallback(_loc3_,_loc4_,_loc2_); + _ecoConsumerCallback = null; + } + } + + public static function generateDenShopList(param1:int, param2:Object) : IitemCollection + { + var _loc4_:int = 0; + var _loc3_:DenItem = null; + var _loc5_:IitemCollection = new IitemCollection(); + _loc4_ = 0; + while(_loc4_ < param1) + { + _loc3_ = new DenItem(); + _loc3_.initShopItem(int(param2[_loc4_]),-1); + _loc5_.pushIitem(_loc3_); + _loc4_++; + } + return _loc5_; + } + + public static function setDenItems() : void + { + if(_roomMgr) + { + if(_pendingDenChangeItems) + { + if(AvatarManager.playerAvatar != null) + { + _roomMgr.denItemHolder.setItems(_pendingDenChangeItems); + _pendingDenChangeItems = null; + } + else + { + AvatarManager.setDenItemsCallback = setDenItems; + } + } + } + } + + public static function denChangeDone() : void + { + _denChangePending = false; + updateCatIdsForPendingFlooringAndWallpaper(); + setDenItems(); + } + + private static function updateCatIdsForPendingFlooringAndWallpaper() : void + { + var _loc2_:DenStateItem = null; + var _loc1_:int = 0; + if(!_pendingDenChangeItems || _pendingDenChangeItems.length <= 0) + { + return; + } + _loc1_ = 0; + while(_loc1_ < _pendingDenChangeItems.length) + { + _loc2_ = _pendingDenChangeItems.getDenStateItem(_loc1_); + if(_loc2_.sortCatId == 2 || _loc2_.sortCatId == 3) + { + _loc2_.catId = _roomMgr.denCatId; + _loc2_.packedId = uint(_loc2_.defId << 16 | _loc2_.catId); + } + _loc1_++; + } + } + + public static function saveDenItemsState() : void + { + _roomMgr.denItemHolder.saveState(); + } + + public static function set denChangePending(param1:Boolean) : void + { + _denChangePending = param1; + } + + public static function set recycleDiCallback(param1:Function) : void + { + _recycleDiCallback = param1; + } + + public static function set denHighestCallback(param1:Function) : void + { + _denHighestCallback = param1; + } + + public static function set denPrivateCallback(param1:Function) : void + { + _denPrivateCallback = param1; + } + + private static function denItemDefsResponse(param1:DefPacksDefHelper) : void + { + _denItemDefs = new DenItemDefCollection(); + for each(var _loc2_ in param1.def) + { + addDenItemDef(_loc2_); + } + delete DefPacksDefHelper.mediaArray[1030]; + DefPacksDefHelper.mediaArray[1030] = null; + } + + // Burrow: as ItemXtCommManager.addItemDefs, for den items ("xdi"). + public static function addDenItemDefs(param1:Array) : void + { + if(_denItemDefs == null) + { + return; + } + for each(var _loc2_:Object in param1) + { + addDenItemDef(_loc2_); + if(_loc2_.name) + { + _denItemDefs.getDenItemDefItem(int(_loc2_.id)).name = String(_loc2_.name); + } + } + } + + private static function addDenItemDef(_loc2_:Object) : void + { + { + _denItemDefs.setDenItemDefItem(int(_loc2_.id),new DenItemDef(_loc2_.abbrName,_loc2_.combinedCost,int(_loc2_.cost),int(_loc2_.currencyType),int(_loc2_.enviroType),int(_loc2_.flag),int(_loc2_.gameDefId),int(_loc2_.id),int(_loc2_.itemStatus),int(_loc2_.layer),int(_loc2_.mannequinAvatarDefId),int(_loc2_.mannequinCatId),int(_loc2_.mannequinCatId),int(_loc2_.membersOnly),int(_loc2_.nameStrId),int(_loc2_.parentArrayId),int(_loc2_.promoType),int(_loc2_.recycleValue),int(_loc2_.scalePercent),int(_loc2_.sortCat),int(_loc2_.specialType),int(_loc2_.typeCat),uint(_loc2_.availabilityStartTime),uint(_loc2_.availabilityEndTime),int(_loc2_.ecoPower))); + } + } + + public static function relocalizeDenItems() : void + { + for each(var _loc1_ in _denItemDefs.getCoreArray()) + { + _loc1_.name = LocalizationManager.translateIdOnly(_loc1_.nameStrId); + } + } + + public static function enviroItems(param1:DenItemCollection) : DenItemCollection + { + var _loc3_:DenItemCollection = new DenItemCollection(); + for each(var _loc2_ in param1.getCoreArray()) + { + if(_loc2_.enviroType == AvatarManager.roomEnviroType || _loc2_.isLandAndOcean) + { + _loc3_.pushDenItem(_loc2_); + } + } + return _loc3_; + } + + public static function denItemDefIdForPetDefId(param1:int) : int + { + switch(param1) + { + case 9: + return 863; + case 7: + return 859; + case 5: + return 857; + case 1: + return 853; + case 4: + return 854; + case 3: + return 856; + case 2: + return 855; + case 6: + return 858; + case 12: + return 864; + case 10: + return 860; + case 8: + return 862; + case 11: + return 861; + case 13: + return 915; + case 14: + return 957; + case 15: + return 1089; + case 16: + return 1110; + case 17: + return 1138; + case 18: + return 1149; + case 19: + return 1171; + case 20: + return 1180; + case 21: + return 1206; + case 22: + return 1275; + case 23: + return 1331; + case 24: + return 1521; + case 25: + return 1567; + case 26: + return 1676; + case 27: + return 1662; + case 28: + return 1698; + case 29: + return 1780; + case 30: + return 1868; + case 31: + return 1867; + case 32: + return 1946; + case 34: + return 1995; + case 35: + return 2032; + case 36: + return 2292; + case 37: + return 2300; + case 38: + return 2301; + case 39: + return 2307; + case 40: + return 2350; + case 42: + return 2432; + case 43: + return 2463; + case 44: + return 2506; + case 45: + return 2513; + case 46: + return 2589; + case 47: + return 2588; + case 48: + return 2587; + case 49: + return 2591; + case 50: + return 2590; + case 51: + return 2592; + case 52: + return 2622; + case 53: + return 2656; + case 54: + return 2715; + case 55: + return 2775; + case 56: + return 2844; + case 57: + return 2861; + case 58: + return 2876; + case 59: + return 2877; + case 60: + return 2878; + case 61: + return 2884; + case 62: + return 2894; + case 63: + return 2977; + case 41: + return 2989; + case 64: + return 3039; + case 67: + return 3113; + case 68: + return 3117; + case 69: + return 3136; + case 70: + return 3137; + case 71: + return 3182; + case 74: + return 3205; + case 75: + return 3222; + case 76: + return 3241; + case 65: + return 3307; + case 66: + return 3306; + case 77: + return 3292; + case 73: + return 3321; + case 72: + return 2861; + case 80: + return 3362; + case 81: + return 3369; + case 82: + return 3367; + case 83: + return 3368; + case 84: + return 3377; + case 85: + return 3432; + case 86: + return 3448; + case 87: + return 3534; + case 88: + return 3546; + case 89: + return 3677; + case 90: + return 3738; + case 91: + return 3775; + case 92: + return 3815; + case 93: + return 3898; + case 94: + return 3899; + case 95: + return 3900; + case 96: + return 3928; + case 97: + return 3966; + case 98: + return 3994; + case 99: + return 4016; + case 100: + return 4096; + case 101: + return 4139; + case 102: + return 4147; + case 103: + return 4161; + case 104: + return 4173; + case 105: + return 4196; + case 106: + return 4227; + case 107: + return 4230; + case 108: + return 4272; + case 109: + return 4273; + case 110: + return 4374; + case 111: + return 4595; + case 112: + return 4758; + case 113: + return 5454; + case 114: + return 5586; + case 115: + return 5636; + case 116: + return 5653; + default: + return 853; + } + } + + public static function getDenItemDef(param1:int) : DenItemDef + { + return _denItemDefs.getDenItemDefItem(param1); + } + } +} + diff --git a/swf-src/ECardInbox.as b/swf-src/ECardInbox.as index 9625322..b09d4eb 100644 --- a/swf-src/ECardInbox.as +++ b/swf-src/ECardInbox.as @@ -33,6 +33,7 @@ package gui import flash.net.navigateToURL; import giftPopup.GiftPopup; import gui.itemWindows.ItemWindowECard; + import item.ItemXtCommManager; import item.SimpleIcon; import loader.DenItemHelper; import loader.MediaHelper; @@ -698,6 +699,16 @@ package gui switch(_loc6_.type) { case 1: + // a custom item's own picture, when it has one (AJClient.customArtUrl) + if(AJClient.customArtUrl("clothing",giftItemDefId(_loc6_)) != null) + { + var _loc8_:Sprite = new Sprite(); + AJClient.loadArt(AJClient.customArtUrl("clothing",giftItemDefId(_loc6_)),_loc8_,100,false,function():void + { + setupGiftPopup(_loc8_); + }); + break; + } _clothingIconHelper = new SimpleIcon(); _clothingIconHelper.init(_loc6_.giftColor,_loc6_.giftId,1,true,false,clothingIconReceived); break; @@ -802,10 +813,45 @@ package gui setupGiftPopup(_guiPet); } + // a clothing gift's item id, which the server sends as "item|" in + // the card's additional gift data (its gift id is the art's), or 0 + private static function giftItemDefId(param1:ECard) : int + { + var _loc2_:String = param1.additionalGiftData == null ? "" : param1.additionalGiftData; + return _loc2_.indexOf("item|") == 0 ? int(_loc2_.substr(5)) : 0; + } + + // a custom item's name as it is now (the server sends it with the + // item, "xdi"): the game's strings have none for one made since this + // game started, nor a name it was given since. + private static function giftItemName(param1:ECard) : String + { + var _loc2_:Object = null; + var _loc3_:int = param1.type == 1 ? giftItemDefId(param1) : param1.giftId; + if(_loc3_ < 50000) + { + return null; + } + if(param1.type == 1) + { + _loc2_ = ItemXtCommManager.getItemDef(_loc3_); + } + else if(param1.type == 3 || param1.type == 99) + { + _loc2_ = DenXtCommManager.getDenItemDef(_loc3_); + } + return _loc2_ != null && _loc2_.name ? String(_loc2_.name) : null; + } + private function setupGiftPopup(param1:Sprite) : void { DarkenManager.showLoadingSpiral(false); var _loc2_:ECard = _inbox[_currCardIdx]; + var _loc4_:String = giftItemName(_loc2_); + if(_loc4_ != null) + { + _loc2_.giftName = _loc4_; + } var _loc3_:Boolean = _loc2_.isFromVoice && _loc2_.additionalGiftData.length > 0 && _loc2_.additionalGiftData.indexOf("|") == -1; _giftPopup = new GiftPopup(); _giftPopup.init(_guiLayer,param1,_loc2_.giftName,_loc2_.giftId,_loc2_.isFromVoice ? 6 : 0,GiftPopup.giftTypeForECardType(_loc2_.type),keepGiftCallback,rejectGiftCallback,destroyGiftPopup,!_loc2_.isFromVoice,GiftPopup.buttonsTypeForECardType(_loc2_.type),_loc2_.secondaryType,null,_loc3_ ? _loc2_.modifiedMsg : null,_petBits); diff --git a/swf-src/EmoticonUtility.cinit.pcode b/swf-src/EmoticonUtility.cinit.pcode index ffd632e..65414fe 100644 --- a/swf-src/EmoticonUtility.cinit.pcode +++ b/swf-src/EmoticonUtility.cinit.pcode @@ -3,7 +3,7 @@ returns null body - maxstack 43 + maxstack 45 localcount 1 initscopedepth 0 maxscopedepth 1 @@ -54,7 +54,9 @@ pushstring "emo_star2_sml" pushstring "emo_star3_sml" pushstring "emo_temp_sml" - newarray 43 + pushstring "emo_skull_sml" + pushstring "emo_sob_sml" + newarray 45 findproperty QName(PrivateNamespace("gui:EmoticonUtility"),"displaySprites") swap setproperty QName(PrivateNamespace("gui:EmoticonUtility"),"displaySprites") @@ -126,7 +128,9 @@ pushstring "emo_star2" pushstring "emo_star3" pushstring "emo_temp" - newarray 43 + pushstring "emo_skull" + pushstring "emo_sob" + newarray 45 findproperty QName(PrivateNamespace("gui:EmoticonUtility"),"emoteSprites") swap setproperty QName(PrivateNamespace("gui:EmoticonUtility"),"emoteSprites") @@ -565,6 +569,26 @@ pushstring ":fever:" newarray 1 setproperty MultinameL([PrivateNamespace("gui:EmoticonUtility"),StaticProtectedNs("gui:EmoticonUtility"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:EmoticonUtility"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")]) + getlex QName(PrivateNamespace("gui:EmoticonUtility"),"_emoteStrings") + pushstring "emo_skull" + pushstring ":skull:" + newarray 1 + setproperty MultinameL([PrivateNamespace("gui:EmoticonUtility"),StaticProtectedNs("gui:EmoticonUtility"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:EmoticonUtility"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")]) + getlex QName(PrivateNamespace("gui:EmoticonUtility"),"_emoteChatStrings") + pushstring "emo_skull" + pushstring ":skull:" + newarray 1 + setproperty MultinameL([PrivateNamespace("gui:EmoticonUtility"),StaticProtectedNs("gui:EmoticonUtility"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:EmoticonUtility"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")]) + getlex QName(PrivateNamespace("gui:EmoticonUtility"),"_emoteStrings") + pushstring "emo_sob" + pushstring ":sob:" + newarray 1 + setproperty MultinameL([PrivateNamespace("gui:EmoticonUtility"),StaticProtectedNs("gui:EmoticonUtility"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:EmoticonUtility"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")]) + getlex QName(PrivateNamespace("gui:EmoticonUtility"),"_emoteChatStrings") + pushstring "emo_sob" + pushstring ":sob:" + newarray 1 + setproperty MultinameL([PrivateNamespace("gui:EmoticonUtility"),StaticProtectedNs("gui:EmoticonUtility"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:EmoticonUtility"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")]) returnvoid end ; code end ; body diff --git a/swf-src/GuiManager.as b/swf-src/GuiManager.as index a8b6126..50f2001 100644 --- a/swf-src/GuiManager.as +++ b/swf-src/GuiManager.as @@ -2769,8 +2769,20 @@ package gui gMainFrame.stage.removeEventListener("mouseUp",clickedOutsideChatCui); } + // an emote from the emote window: sent on its own, as the game has it; + // but with words already typed in the chat box, its code goes there, + // after them, and the line shows it among the words (gui.ChatBalloon). public static function onEmoteClick(param1:Sprite) : void { + var _loc2_:String = EmoticonUtility.getEmoteString(param1); + var _loc3_:Object = chatHist != null ? chatHist.chatMsgText : null; + if(_loc2_ != null && _loc3_ != null && chatHist.enableFreeChatValue && String(_loc3_.text).replace(/\s+/g,"").length > 0) + { + _loc3_.text = String(_loc3_.text).replace(/\s+$/,"") + " " + _loc2_ + " "; + gMainFrame.stage.focus = _loc3_ as InteractiveObject; + _loc3_.setSelection(_loc3_.text.length,_loc3_.text.length); + return; + } UserCommXtCommManager.sendAvatarEmote(param1); } diff --git a/swf-src/Item.as b/swf-src/Item.as new file mode 100644 index 0000000..cb02465 --- /dev/null +++ b/swf-src/Item.as @@ -0,0 +1,803 @@ +package item +{ + import com.sbi.debug.DebugUtility; + import currency.CombinedCurrencyItem; + import diamond.DiamondItem; + import diamond.DiamondXtCommManager; + import flash.display.Sprite; + import inventory.Iitem; + import localization.LocalizationManager; + + public class Item implements Iitem + { + + public static const BODY_MOD_TYPE:int = 0; + + public static const CLOTHING_TYPE:int = 1; + + public static const BASE_LAYER:int = 1; + + public static const PATTERN_LAYER:int = 2; + + public static const EYE_LAYER:int = 3; + + public static const TAIL_LAYER:int = 4; + + public static const LEG_LAYER:int = 5; + + public static const BACK_LAYER:int = 6; + + public static const NECK_LAYER:int = 7; + + public static const HEAD_LAYER_1:int = 8; + + public static const HEAD_LAYER_2:int = 9; + + public static const HEAD_LAYER_3:int = 10; + + public static const OCEAN_LEG_LAYER:int = 8; + + public static const OCEAN_BACK_LAYER:int = 6; + + public static const OCEAN_HEAD_LAYER:int = 7; + + public static const OCEAN_NECK_LAYER:int = 5; + + public static const NUM_DETAILS_PER_ITEM:int = 11; + + public static const COMBAT_TYPE_MELEE:int = 0; + + public static const COMBAT_TYPE_RANGED:int = 1; + + public static const MODIFIER_TYPE_NONE:int = 0; + + public static const MODIFIER_TYPE_RANGED:int = 1; + + public static const MODIFIER_TYPE_MELEE:int = 2; + + public static const MODIFIER_TYPE_DEFENSE:int = 3; + + public static const MODIFIER_TYPE_RESTORE:int = 4; + + private var _currDef:Object; + + private var _layerId:int; + + private var _invIdx:int; + + private var _accId:int; + + private var _color:uint; + + private var _name:String; + + private var _isGiftable:Boolean; + + private var _isMemberOnly:Boolean; + + private var _itemStatus:int; + + private var _type:int; + + private var _enviroType:int; + + private var _recycleValue:int; + + private var _currencyType:int; + + private var _avatarUseFlag:Object; + + private var _endTime:uint; + + private var _colors:Array; + + private var _equippedAvatars:EquippedAvatars; + + private var _value:int; + + private var _defId:int; + + private var _icon:Sprite; + + private var _iconHelper:SimpleIcon; + + private var _denStoreInvId:int; + + private var _largeIcon:Sprite; + + private var _largeIconHelper:SimpleIcon; + + private var _isShopItem:Boolean; + + private var _isIconLoaded:Boolean; + + private var _imageLoadedCallback:Function; + + private var _iconLayerID:int = -1; + + private var _iconColorID:int = 0; + + private var _attackMediaRefId:int = 0; + + private var _defense:int = 0; + + private var _attack:int = 0; + + private var _combatType:int = 0; + + private var _fierce:int = 0; + + private var _modifierType:int = 0; + + private var _modifierValue:int = 0; + + private var _combinedCurrencyItem:CombinedCurrencyItem; + + private var _specialScale:Number; + + private var _diamondItem:DiamondItem; + + private var _asShopItemSized:Boolean; + + public function Item() + { + super(); + } + + public function init(param1:int, param2:int = 0, param3:uint = 0, param4:EquippedAvatars = null, param5:Boolean = false, param6:Number = -1, param7:int = 0) : void + { + _defId = param1; + _invIdx = param2; + _color = param3; + _equippedAvatars = param4 != null ? param4 : new EquippedAvatars(); + _isShopItem = param5; + _specialScale = param6; + _denStoreInvId = param7; + _currDef = ItemXtCommManager.getItemDef(param1); + if(_currDef == null) + { + DebugUtility.debugTrace("Item.init got invalid defId? defId:" + param1); + return; + } + _layerId = _currDef.layerId; + _accId = _currDef.accId; + _name = _currDef.name; + _isGiftable = _currDef.isGiftable; + _diamondItem = DiamondXtCommManager.getDiamondItem(DiamondXtCommManager.getDiamondDefIdByRefId(_currDef.defId,0)); + if(_diamondItem) + { + _itemStatus = _diamondItem.status; + _value = _diamondItem.value; + _currencyType = 3; + _endTime = _diamondItem.availabilityEndTime; + } + else + { + _itemStatus = _currDef.itemStatus; + _value = isOnSale ? Math.ceil(_currDef.cost * 0.5) : _currDef.cost; + _currencyType = _currDef.currencyType; + _endTime = _currDef.availabilityEndTime; + } + _type = _currDef.type; + _isMemberOnly = _currDef.isMembersOnly; + _enviroType = _currDef.enviroType; + _recycleValue = _currDef.recycleValue == 0 ? _currDef.cost * gMainFrame.clientInfo.recyclePercentage : _currDef.recycleValue; + _avatarUseFlag = _currDef.avatarUseFlag; + _colors = _currDef.colors; + _attackMediaRefId = _currDef.attackMediaRefId; + _defense = _currDef.defense; + _attack = _currDef.attack; + _combatType = _currDef.combatType; + _fierce = _currDef.criticalHit; + _modifierType = _currDef.modifierType; + _modifierValue = _currDef.modifierValue; + _largeIcon = null; + _icon = null; + if(_currencyType == 100) + { + _combinedCurrencyItem = new CombinedCurrencyItem(_currDef.combinedCurrencyString); + } + _isIconLoaded = false; + } + + public function destroy() : void + { + if(_iconHelper) + { + _iconHelper.destroy(); + _iconHelper = null; + } + if(_largeIconHelper) + { + _largeIconHelper.destroy(); + _largeIconHelper = null; + } + if(_icon) + { + _icon = null; + } + } + + public function ifItemDiffers(param1:Iitem) : Boolean + { + var _loc2_:Item = param1 as Item; + if(_loc2_) + { + if(_defId == param1.defId) + { + if(!_equippedAvatars.equals(_loc2_._equippedAvatars) || value != _loc2_.value || _color != _loc2_._color || _name != _loc2_._name || _isGiftable != _loc2_._isGiftable || _type != _loc2_._type || _layerId != _loc2_._layerId || _accId != _loc2_._accId || _isMemberOnly != _loc2_._isMemberOnly || isNew != _loc2_.isNew || isOnSale != _loc2_.isOnSale || _recycleValue != _loc2_._recycleValue || _currencyType != _loc2_._currencyType || _endTime != _loc2_._endTime || _specialScale != _loc2_.specialScale || isInDenShop != _loc2_.isInDenShop) + { + return true; + } + } + } + return false; + } + + public function clone() : Iitem + { + var _loc1_:Item = new Item(); + _loc1_.init(_defId,_invIdx,_color,_equippedAvatars.clone(),_isShopItem,_specialScale,_denStoreInvId); + _loc1_.updateValueWithNewStatus(_itemStatus); + _loc1_.imageLoadedCallback = imageLoadedCallback; + return _loc1_; + } + + public function makeSmallIcon() : void + { + if(_accId == 3) + { + return; + } + _isIconLoaded = false; + _icon = new Sprite(); + // a custom item's own picture (AJClient.customArtUrl), in a box the + // size of the game's icons + var _loc1_:String = AJClient.customArtUrl("clothing",_defId); + if(_loc1_ != null) + { + var _loc2_:Sprite = new Sprite(); + AJClient.loadArt(_loc1_,_loc2_,100,false,function():void + { + _loc2_.x = 50; + _loc2_.y = 50; + _icon.addChild(_loc2_); + resizeAndPositionIcon(false); + _isIconLoaded = true; + }); + return; + } + _iconHelper = new SimpleIcon(); + _iconHelper.init(_color,_accId,1,_isShopItem,false,smallIconReceived); + } + + public function makeLargeIcon() : void + { + if(_accId == 3) + { + return; + } + _isIconLoaded = false; + _largeIcon = new Sprite(); + var _loc1_:String = AJClient.customArtUrl("clothing",_defId); + if(_loc1_ != null) + { + var _loc2_:Sprite = new Sprite(); + AJClient.loadArt(_loc1_,_loc2_,100,false,function():void + { + _loc2_.x = 50; + _loc2_.y = 50; + _largeIcon.addChild(_loc2_); + resizeAndPositionIcon(true); + _isIconLoaded = true; + }); + return; + } + _largeIconHelper = new SimpleIcon(); + _largeIconHelper.init(_color,_accId,1,_isShopItem,false,largeIconReceived); + } + + private function smallIconReceived() : void + { + _icon.addChild(_iconHelper.iconBitmap); + resizeAndPositionIcon(false); + _isIconLoaded = true; + if(_iconLayerID >= 0) + { + if(_icon && _iconHelper) + { + _iconHelper.updateLayerColor(_iconLayerID,_iconColorID); + } + _iconLayerID = -1; + } + } + + private function largeIconReceived() : void + { + _largeIcon.addChild(_largeIconHelper.iconBitmap); + resizeAndPositionIcon(true); + _isIconLoaded = true; + } + + public function setIconColor(param1:int, param2:uint) : void + { + _iconLayerID = param1; + _iconColorID = param2; + if(_icon && _iconHelper) + { + _iconHelper.updateLayerColor(_iconLayerID,_iconColorID); + } + } + + private function updateLargeIconColor() : void + { + if(_largeIcon && _largeIconHelper) + { + _largeIconHelper.updateLayerColor(_layerId,_color); + } + } + + private function updateIconColor() : void + { + if(_icon && _iconHelper) + { + _iconHelper.updateLayerColor(_layerId,_color); + } + } + + public function resizeAndPositionIcon(param1:Boolean) : void + { + var _loc2_:Number = NaN; + if(_isShopItem || param1 || _asShopItemSized) + { + if(param1) + { + _loc2_ = 1; + _largeIcon.width *= _loc2_; + _largeIcon.height *= _loc2_; + _largeIcon.x = -(_largeIcon.width * 0.5); + _largeIcon.y = -(_largeIcon.height * 0.5); + } + else + { + if(_specialScale > 0) + { + _loc2_ = _specialScale; + } + else + { + _loc2_ = 0.6; + } + _icon.width *= _loc2_; + _icon.height *= _loc2_; + _icon.x = -(_icon.width * 0.5); + _icon.y = -(_icon.height * 0.5); + } + } + else + { + _loc2_ = 0.75; + _icon.width *= _loc2_; + _icon.height *= _loc2_; + _icon.x = -(_icon.width * 0.5); + _icon.y = -(_icon.height * 0.5); + } + if(_imageLoadedCallback != null) + { + _imageLoadedCallback(); + } + } + + public function set asShopItemSized(param1:Boolean) : void + { + _asShopItemSized = param1; + } + + public function set diamondItem(param1:DiamondItem) : void + { + _diamondItem = param1; + } + + public function get diamondItem() : DiamondItem + { + return _diamondItem; + } + + public function get defId() : int + { + return _defId; + } + + public function set defId(param1:int) : void + { + _defId = param1; + } + + public function get icon() : Sprite + { + if(!_icon) + { + makeSmallIcon(); + } + else + { + updateIconColor(); + } + return _icon; + } + + public function get largeIcon() : Sprite + { + if(!_largeIcon) + { + makeLargeIcon(); + } + else + { + updateLargeIconColor(); + } + return _largeIcon; + } + + public function get isOnSale() : Boolean + { + return _itemStatus == 2; + } + + public function get isOnClearance() : Boolean + { + return _itemStatus == 3; + } + + public function get isRare() : Boolean + { + return _itemStatus == 4; + } + + public function get isNew() : Boolean + { + return _itemStatus == 1; + } + + public function get startTime() : uint + { + if(_diamondItem) + { + return _diamondItem.startTime; + } + if(_currDef) + { + return _currDef.availabilityStartTime; + } + return 0; + } + + public function get isOcean() : Boolean + { + return _enviroType == 1; + } + + public function get isLand() : Boolean + { + return _enviroType == 0; + } + + public function get isLandAndOcean() : Boolean + { + return _enviroType == 3; + } + + public function get isDiamond() : Boolean + { + return _diamondItem != null; + } + + public function get isRareDiamond() : Boolean + { + return isRare && isDiamond; + } + + public function get attackMediaRefId() : int + { + return _attackMediaRefId; + } + + public function get defense() : int + { + return _defense; + } + + public function get attack() : int + { + return _attack; + } + + public function get combatType() : int + { + return _combatType; + } + + public function get modifierType() : int + { + return _modifierType; + } + + public function get modifierValue() : int + { + return _modifierValue; + } + + public function get fierceAttack() : int + { + return _fierce; + } + + public function get extraTooltipInfo() : String + { + return ""; + } + + public function cloneEquippedAvatars(param1:Boolean = false) : EquippedAvatars + { + if(param1 && _equippedAvatars.isEquippedOnAnyAvatars()) + { + return EquippedAvatars.forced(); + } + return _equippedAvatars.clone(); + } + + public function getInUse(param1:int = -1) : Boolean + { + return _equippedAvatars.isEquipped(param1); + } + + public function setInUse(param1:int, param2:Boolean) : void + { + _equippedAvatars.setEquipped(param1,param2); + } + + public function forceInUse(param1:Boolean) : void + { + _equippedAvatars.setForceInUse(param1); + } + + public function updateValueWithNewStatus(param1:int) : void + { + if(_currencyType != 100 && !isRare && _currDef != null) + { + _itemStatus = param1; + if(isOnSale) + { + if(_diamondItem) + { + if(_diamondItem.isOnSale) + { + _value = _diamondItem.value; + } + else + { + _value = Math.ceil(_diamondItem.value * 0.5); + } + } + else + { + _value = Math.ceil(_currDef.cost * 0.5); + } + } + else + { + _value = _diamondItem ? _diamondItem.value : _currDef.cost; + } + _recycleValue = _currDef.recycleValue == 0 ? _currDef.cost * gMainFrame.clientInfo.recyclePercentage : _currDef.recycleValue; + } + } + + public function get combinedCurrencyItem() : CombinedCurrencyItem + { + return _combinedCurrencyItem; + } + + public function get sincleCurrencyCost() : int + { + return _value; + } + + public function get value() : * + { + if(_currencyType == 100) + { + return _combinedCurrencyItem; + } + return _value; + } + + public function get sortIdString() : String + { + switch(_layerId - 4) + { + case 0: + return LocalizationManager.translateIdOnly(11209).toLowerCase(); + case 1: + return LocalizationManager.translateIdOnly(11208).toLowerCase(); + case 2: + return LocalizationManager.translateIdOnly(11207).toLowerCase(); + case 3: + return LocalizationManager.translateIdOnly(11206).toLowerCase(); + case 4: + case 5: + case 6: + return LocalizationManager.translateIdOnly(11205).toLowerCase(); + default: + return ""; + } + } + + public function get isMemberOnly() : Boolean + { + return _isMemberOnly; + } + + public function set isMemberOnly(param1:Boolean) : void + { + _isMemberOnly = param1; + } + + public function get layerId() : int + { + return _layerId; + } + + public function get invIdx() : int + { + return _invIdx; + } + + public function get accId() : int + { + return _accId; + } + + public function get color() : uint + { + return _color; + } + + public function set color(param1:uint) : void + { + _color = param1; + } + + public function get colors() : Array + { + return _colors; + } + + public function get name() : String + { + return _name; + } + + public function get isGiftable() : Boolean + { + return _isGiftable; + } + + public function get itemStatus() : int + { + return _itemStatus; + } + + public function get type() : int + { + return _type; + } + + public function get enviroType() : int + { + return _enviroType; + } + + public function get recycleValue() : int + { + return _recycleValue; + } + + public function get currencyType() : int + { + return _currencyType; + } + + public function get avatarUseFlag() : Object + { + return _avatarUseFlag; + } + + public function get endTime() : uint + { + return _endTime; + } + + public function set endTime(param1:uint) : void + { + _endTime = param1; + } + + public function get isIconLoaded() : Boolean + { + return _isIconLoaded; + } + + public function get imageLoadedCallback() : Function + { + return _imageLoadedCallback; + } + + public function set imageLoadedCallback(param1:Function) : void + { + _imageLoadedCallback = param1; + } + + public function get isShopItem() : Boolean + { + return _isShopItem; + } + + public function get specialScale() : Number + { + return _specialScale; + } + + public function set specialScale(param1:Number) : void + { + _specialScale = param1; + } + + public function get isApproved() : Boolean + { + return true; + } + + public function set isApproved(param1:Boolean) : void + { + } + + public function get isCustom() : Boolean + { + return false; + } + + public function get isAvailable() : Boolean + { + if(_diamondItem) + { + return _diamondItem.isAvailable; + } + if(_currDef) + { + return Utility.isAvailable(_currDef.availabilityStartTime,_currDef.availabilityEndTime); + } + return false; + } + + public function get isInDenShop() : Boolean + { + return _denStoreInvId > 0; + } + + public function get denStoreInvId() : int + { + return _denStoreInvId; + } + + public function get itemType() : int + { + return 2; + } + + public function set denStoreInvId(param1:int) : void + { + _denStoreInvId = param1; + } + } +} + diff --git a/swf-src/ItemWindowToggle.as b/swf-src/ItemWindowToggle.as index 8f46668..1257931 100644 --- a/swf-src/ItemWindowToggle.as +++ b/swf-src/ItemWindowToggle.as @@ -165,6 +165,7 @@ package gui.itemWindows _window.goNowBtn.mouse.up.txt.text = ServerSelector.getShardName(RoomManagerWorld.instance.shardId); break; case "itemFinder": + case "itemMaker": case "chatFilter": case "themeMenu": case "themePick": @@ -636,6 +637,13 @@ package gui.itemWindows } AJClient.openTool(0); break; + case "itemMaker": + if(_mySettingsCloseFunction != null) + { + _mySettingsCloseFunction(null); + } + AJClient.openTool(2); + break; case "chatFilter": if(_mySettingsCloseFunction != null) { diff --git a/swf-src/ItemXtCommManager.as b/swf-src/ItemXtCommManager.as new file mode 100644 index 0000000..594728e --- /dev/null +++ b/swf-src/ItemXtCommManager.as @@ -0,0 +1,1407 @@ +package item +{ + import avatar.Avatar; + import avatar.AvatarInfo; + import avatar.UserInfo; + import collection.AccItemCollection; + import collection.IitemCollection; + import collection.IntItemCollection; + import com.sbi.bit.BitUtility; + import com.sbi.client.SFEvent; + import com.sbi.debug.DebugUtility; + import com.sbi.graphics.LayerAnim; + import com.sbi.popup.SBOkPopup; + import currency.CurrencyItem; + import currency.UserCurrency; + import den.DenMannequinInventory; + import diamond.DiamondXtCommManager; + import game.MinigameManager; + import gui.GuiManager; + import loader.DefPacksDefHelper; + import localization.LocalizationManager; + import quest.QuestManager; + import room.RoomManagerWorld; + + public class ItemXtCommManager + { + + public static var guiManager:Object; + + public static var hasRequestedFullItemList:Boolean; + + public static var itemDefsHaveLoaded:Boolean; + + public static var functionToCallWhenDefsLoaded:Function; + + private static var _ilAvatarQueue:Vector.; + + private static var _acIlAvatarQueue:Vector.; + + private static var _ibQueue:Vector.; + + private static var _iuQueue:Vector.; + + private static var _slQueue:Vector.; + + private static var _denShopListHandler:Function; + + private static var _donateCallback:Function; + + private static var _currencyExchangeCallback:Function; + + private static var _diamondBundleBuyCallback:Function; + + private static var _irCallback:Function; + + private static var _recycleIlCallback:Function; + + private static var _hudAvtLayerAnim:LayerAnim; + + private static var _buyItemsIlCallback:Function; + + private static var _getAvatarFromAvatarManager:Function; + + private static var _processAcIlComboFromAvatarManager:Function; + + private static var _playerAvatar:Avatar; + + private static var _itemDefs:Object; + + private static var _currencyExchangeDefs:Object; + + private static var _ignoreAndCacheIlResponses:Boolean; + + private static var _ignoreIlCache:Object; + + private static var _bodyItemDefIds:Array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,314,315,316,317,318,319,320,407,457,480,926,1022,1186,1458,1766,1787,1788,1789,1790,1963,1964,1965,1966,1976,1981,2073,2121]; + + public function ItemXtCommManager() + { + super(); + } + + public static function init(param1:Function = null, param2:Function = null, param3:Object = null, param4:Function = null) : void + { + _getAvatarFromAvatarManager = param1; + _processAcIlComboFromAvatarManager = param2; + guiManager = param3; + _denShopListHandler = param4; + _ilAvatarQueue = new Vector.(); + _acIlAvatarQueue = new Vector.(); + _ibQueue = new Vector.(); + _iuQueue = new Vector.(); + _slQueue = new Vector.(); + _ignoreIlCache = {}; + itemDefsHaveLoaded = false; + var _loc5_:DefPacksDefHelper = new DefPacksDefHelper(); + _loc5_.init(1000,itemDefResponse,null,2); + DefPacksDefHelper.mediaArray[1000] = _loc5_; + var _loc6_:DefPacksDefHelper = new DefPacksDefHelper(); + _loc6_.init(1051,currencyExchangeDefResponse,null,2); + DefPacksDefHelper.mediaArray[1051] = _loc6_; + } + + public static function destroy() : void + { + _ilAvatarQueue = null; + _acIlAvatarQueue = null; + _ibQueue = null; + _iuQueue = null; + _slQueue = null; + _irCallback = null; + } + + public static function set playerAvatar(param1:Avatar) : void + { + _playerAvatar = param1; + } + + public static function set recycleIlCallback(param1:Function) : void + { + _recycleIlCallback = param1; + } + + public static function requestItemBuy(param1:Function, param2:int, param3:int, param4:int, param5:int, param6:int, param7:String) : void + { + gMainFrame.server.setXtObject_Str("ib",[param2,1,param3,param4,param5,param6,param7]); + var _loc8_:Object = {}; + _loc8_[param2] = { + "c":param1, + "i":param3, + "o":param4 + }; + _ibQueue.push(_loc8_); + } + + public static function requestItemRecycle(param1:IntItemCollection, param2:Function, param3:Function) : void + { + _irCallback = param2; + _recycleIlCallback = param3; + gMainFrame.server.setXtObject_Str("ir",param1.getCoreArray()); + } + + public static function requestItemUse(param1:Function, param2:IntItemCollection, param3:IntItemCollection) : void + { + var _loc4_:Object = null; + var _loc5_:Array = [param2.length,param3.length]; + _loc5_ = _loc5_.concat(param2.concatCollection(param3)); + if(!(_loc5_[0] == 0 && _loc5_[1] == 0)) + { + gMainFrame.server.setXtObject_Str("iu",_loc5_,gMainFrame.server.isWorldZone); + _loc4_ = {}; + _loc4_[0] = { + "c":param1, + "o":param2, + "f":param3 + }; + _iuQueue.push(_loc4_); + } + } + + public static function requestItemListForAvatar(param1:Function, param2:Avatar, param3:Boolean, param4:Boolean = true) : void + { + var _loc5_:int = param2.perUserAvId; + insertIntoILAvatarQueue(_loc5_,param1,param2); + gMainFrame.server.setXtObject_Str("il",[param2.userName,_loc5_,param3 ? "1" : "0"],gMainFrame.server.isWorldZone,false,param4); + } + + public static function insertIntoILAvatarQueue(param1:int, param2:Function, param3:Avatar) : void + { + if(param3.userName.toLowerCase() == gMainFrame.userInfo.myUserName.toLowerCase()) + { + hasRequestedFullItemList = true; + } + var _loc4_:Object = {}; + _loc4_[param3.userName] = {}; + _loc4_[param3.userName][param1] = { + "c":param2, + "a":param3 + }; + _ilAvatarQueue.push(_loc4_); + } + + public static function removeFromILAvatarQueue(param1:String, param2:int) : void + { + var _loc3_:int = 0; + _loc3_ = 0; + while(_loc3_ < _ilAvatarQueue.length) + { + if(_ilAvatarQueue[_loc3_].hasOwnProperty(param1)) + { + if(_ilAvatarQueue[_loc3_][param1].hasOwnProperty(param2)) + { + _ilAvatarQueue.splice(_loc3_,1); + break; + } + } + _loc3_++; + } + } + + public static function insertAvIntoAcIlQueue(param1:int, param2:Avatar, param3:Function) : void + { + var _loc5_:int = 0; + var _loc6_:int = 0; + var _loc4_:Object = null; + if(_ilAvatarQueue) + { + _loc5_ = int(_ilAvatarQueue.length); + _loc6_ = 0; + while(_loc6_ < _loc5_) + { + if(_ilAvatarQueue[_loc6_] && _ilAvatarQueue[_loc6_].hasOwnProperty(param2.userName)) + { + if(_ilAvatarQueue[_loc6_][param2.userName].hasOwnProperty(param1)) + { + trace("WARNING: avatar is in ilAvatarQueue but shouldn\'t be yet."); + param3(param1,false); + } + } + _loc6_++; + } + } + else + { + insertIntoILAvatarQueue(param1,null,param2); + _loc4_ = {}; + _loc4_[param2.userName] = { + "i":param1, + "c":param3 + }; + _acIlAvatarQueue.push(_loc4_); + } + } + + public static function requestShopList(param1:Function, param2:int) : void + { + var _loc3_:Object = {}; + _loc3_[param2] = {"c":param1}; + _slQueue.push(_loc3_); + GenericListXtCommManager.requestGenericList(param2); + } + + public static function requestDonateGems(param1:int, param2:Function) : void + { + _donateCallback = param2; + gMainFrame.server.setXtObject_Str("cd",[param1]); + } + + public static function requestCurrencyExchange(param1:int, param2:int, param3:Function) : void + { + gMainFrame.server.setXtObject_Str("ce",[param1,param2]); + _currencyExchangeCallback = param3; + } + + public static function requestBuyDiamondBundle(param1:int, param2:Function) : void + { + gMainFrame.server.setXtObject_Str("id",[param1]); + _diamondBundleBuyCallback = param2; + } + + public static function handleXtReply(param1:SFEvent) : void + { + var _loc2_:Object = param1.obj; + switch(_loc2_[0]) + { + case "il": + itemListResponse(_loc2_); + break; + case "iu": + itemUseResponse(_loc2_); + break; + case "ib": + itemBuyResponse(_loc2_); + break; + case "ir": + itemRecycleResponse(_loc2_); + break; + case "cu": + currencyUpdateResponse(_loc2_); + break; + case "cd": + currencyDonationResponse(_loc2_); + break; + case "ce": + currencyExchangeResponse(_loc2_); + break; + case "ip": + itemPrizeResponse(_loc2_); + break; + case "id": + itemDiamondBundleResponse(_loc2_); + break; + default: + throw new Error("ItemManager: Received illegal cmd: " + _loc2_[0]); + } + } + + private static function getResponseItems(param1:Object, param2:int, param3:String) : Object + { + var _loc7_:Avatar = null; + var _loc8_:int = 0; + var _loc5_:Object = null; + var _loc11_:Object = null; + var _loc10_:int = 0; + var _loc6_:AvatarInfo = null; + var _loc4_:Object = { + "ilCallback":null, + "ilAvatar":null + }; + var _loc9_:int = int(_ilAvatarQueue.length); + if(_loc9_ > 0) + { + _loc10_ = 0; + while(_loc10_ < _loc9_) + { + _loc8_ = _ilAvatarQueue[_loc10_].hasOwnProperty(param3) ? 1 : 0; + if(_loc8_ == 1) + { + _loc8_ = _ilAvatarQueue[_loc10_][param3].hasOwnProperty(param2) ? 1 : 0; + if(_loc8_ == 0) + { + _loc5_ = _ilAvatarQueue[_loc10_][param3][param2]; + if(_loc5_ && _loc5_.hasOwnProperty("a")) + { + _loc8_ = (_loc5_["a"] as Avatar).perUserAvId == param2 ? 2 : 0; + } + } + if(_loc8_ > 0) + { + _loc11_ = _ilAvatarQueue[_loc10_][param3][int(_loc8_ == 1 ? param2 : 0)]; + if(_loc11_ != null) + { + _loc4_.ilCallback = _loc11_.hasOwnProperty("c") ? _loc11_["c"] : null; + _loc7_ = _loc11_.hasOwnProperty("a") ? _loc11_["a"] : null; + } + _ilAvatarQueue.splice(_loc10_,1); + break; + } + } + _loc10_++; + } + } + if(!_loc7_ && _getAvatarFromAvatarManager != null) + { + _loc4_.ilCallback = null; + _loc7_ = _getAvatarFromAvatarManager(param3,param2); + if(!_loc7_) + { + if(param3.toLowerCase() == gMainFrame.userInfo.myUserName.toLowerCase() && param2 == gMainFrame.userInfo.myPerUserAvId && MinigameManager.inFullRoomGame) + { + _loc6_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(gMainFrame.userInfo.myUserName,param2); + if(_loc6_) + { + _loc7_ = new Avatar(); + _loc7_.init(param2,_loc6_.avInvId,_loc6_.avName,_loc6_.type,_loc6_.colors,_loc6_.customAvId,null,gMainFrame.userInfo.myUserName); + } + } + else if(_processAcIlComboFromAvatarManager != null) + { + _processAcIlComboFromAvatarManager(param3,param2,false,param1); + } + } + } + _loc4_.ilAvatar = _loc7_; + return _loc4_; + } + + private static function checkIlCallbacks(param1:String) : void + { + if(_buyItemsIlCallback != null) + { + _buyItemsIlCallback(); + } + if(_recycleIlCallback != null) + { + _recycleIlCallback(); + } + guiManager.openAvEditorRecycle(); + } + + private static function itemsChangedListResponse(param1:Object) : void + { + var _loc16_:Function = null; + var _loc5_:Avatar = null; + var _loc22_:int = 0; + var _loc25_:AccItemCollection = null; + var _loc8_:int = 0; + var _loc17_:Item = null; + var _loc7_:Boolean = false; + var _loc14_:Object = null; + var _loc20_:int = 0; + var _loc23_:int = 0; + var _loc21_:Object = param1.concat(); + var _loc6_:* = param1[2] == "3"; + var _loc4_:* = param1[3] == "1"; + var _loc26_:int = int(param1[4]); + var _loc15_:String = param1[5]; + var _loc2_:uint = uint(param1[6]); + var _loc9_:int = int(param1[7]); + var _loc3_:int = int(param1[8]); + var _loc11_:int = 9; + var _loc24_:Array = []; + var _loc18_:Array = []; + var _loc13_:Array = []; + _loc22_ = 0; + while(_loc22_ < _loc9_) + { + _loc18_.push(int(param1[_loc11_++])); + _loc24_.push(int(param1[_loc11_++])); + _loc22_++; + } + _loc22_ = 0; + while(_loc22_ < _loc3_) + { + _loc13_.push(int(param1[_loc11_++])); + _loc22_++; + } + var _loc12_:Object = getResponseItems(_loc21_,_loc26_,_loc15_); + _loc5_ = _loc12_.ilAvatar; + _loc16_ = _loc12_.ilCallback; + if(!_loc5_) + { + return; + } + var _loc10_:* = _loc5_.userName.toLowerCase() == gMainFrame.userInfo.myUserName.toLowerCase(); + var _loc19_:AvatarInfo = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(_loc15_,_loc26_); + if(_loc19_ && _loc10_) + { + _loc25_ = _loc19_.getFullItems(true); + _loc8_ = int(_loc25_.length); + if(_loc25_) + { + _loc22_ = 0; + while(_loc22_ < _loc18_.length) + { + _loc20_ = 0; + while(_loc20_ < _loc8_) + { + if(_loc25_.getAccItem(_loc20_).invIdx == _loc18_[_loc22_]) + { + _loc25_.getAccItem(_loc20_).setInUse(_loc19_.avInvId,true); + _loc7_ = true; + break; + } + _loc20_++; + } + if(!_loc6_ && !_loc7_) + { + _loc14_ = getItemDef(_loc24_[_loc22_]); + _loc17_ = new Item(); + _loc17_.init(_loc14_.defId,_loc18_[_loc22_],_loc2_); + _loc17_.setInUse(_loc19_.avInvId,_loc4_); + _loc25_.getCoreArray().unshift(_loc17_); + } + _loc7_ = false; + _loc22_++; + } + _loc8_ = int(_loc25_.length); + _loc22_ = 0; + while(_loc22_ < _loc13_.length) + { + _loc20_ = 0; + while(_loc20_ < _loc8_) + { + if(_loc25_.getAccItem(_loc20_).invIdx == _loc13_[_loc22_]) + { + _loc25_.getAccItem(_loc20_).setInUse(_loc19_.avInvId,false); + if(!_loc6_) + { + _loc25_.getCoreArray().splice(_loc20_,1); + } + DenMannequinInventory.removeItemFromUse(_loc13_[_loc22_]); + break; + } + _loc20_++; + } + _loc22_++; + } + _loc19_.fullItemList = _loc25_; + gMainFrame.userInfo.setAvatarInfoByUsernamePerUserAvId(_loc19_.perUserAvId,_loc19_); + } + } + _loc5_.itemResponseIntegrate(_loc19_.getItems(true),false); + if(_loc16_ != null) + { + _loc16_(true); + } + if(_loc10_) + { + checkIlCallbacks(_loc19_.userName); + if(RoomManagerWorld.instance.isMyDen) + { + RoomManagerWorld.instance.denItemHolder.rebuildMannequins(); + } + } + var _loc27_:int = int(_acIlAvatarQueue.length); + if(_acIlAvatarQueue && _loc27_ > 0) + { + _loc23_ = 0; + while(_loc23_ < _loc27_) + { + if(_acIlAvatarQueue.hasOwnProperty(_loc5_.userName)) + { + if(_acIlAvatarQueue[_loc23_][_loc5_.userName].i == _loc5_.perUserAvId) + { + _acIlAvatarQueue[_loc23_][_loc5_.userName].c(_loc5_.userName,_loc5_.perUserAvId,false,_loc21_); + } + _acIlAvatarQueue.splice(_loc23_,1); + break; + } + _loc23_++; + } + } + } + + private static function itemsInUseResponse(param1:Object) : void + { + var _loc20_:Function = null; + var _loc4_:Avatar = null; + var _loc9_:int = 0; + var _loc14_:AccItemCollection = null; + var _loc6_:int = 0; + var _loc7_:int = 0; + var _loc18_:Item = null; + var _loc5_:AvatarInfo = null; + var _loc10_:int = 0; + var _loc8_:Object = param1.concat(); + var _loc3_:int = int(param1[3]); + var _loc21_:int = int(param1[4]); + var _loc19_:String = param1[5]; + var _loc12_:int = int(param1[6]); + var _loc16_:int = int(param1[7]); + var _loc13_:int = int(param1[8]); + var _loc2_:Array = param1.slice(9,param1.length); + var _loc15_:Object = getResponseItems(_loc8_,_loc21_,_loc19_); + _loc4_ = _loc15_.ilAvatar; + _loc20_ = _loc15_.ilCallback; + if(!_loc4_) + { + return; + } + var _loc11_:* = _loc4_.userName.toLowerCase() == gMainFrame.userInfo.myUserName.toLowerCase(); + var _loc17_:UserInfo = gMainFrame.userInfo.getUserInfoByUserName(_loc4_.userName); + if(_loc11_) + { + _loc14_ = _loc17_.fullItemList; + _loc7_ = int(_loc14_.length); + _loc6_ = 0; + while(_loc6_ < _loc7_) + { + _loc18_ = _loc14_.getAccItem(_loc6_); + if(_loc18_.defId == 1 || _loc18_.defId == _loc12_ || _loc18_.defId == _loc16_) + { + _loc18_.setInUse(_loc4_.avInvId,true); + } + else + { + _loc9_ = 1; + while(_loc9_ < _loc13_) + { + if(_loc18_.invIdx == int(_loc2_[_loc9_])) + { + _loc18_.setInUse(_loc4_.avInvId,true); + } + _loc9_ += 2; + _loc9_++; + } + } + _loc6_++; + } + _loc17_.fullItemList = _loc14_; + gMainFrame.userInfo.setUserInfoByUserName(_loc4_.userName,_loc17_); + } + else + { + _loc17_.fullItemList = generateClothingList(_loc13_,_loc2_,_loc4_.avInvId,_loc12_,_loc16_,false); + gMainFrame.userInfo.setUserInfoByUserName(_loc4_.userName,_loc17_); + } + _loc5_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(_loc19_,_loc21_); + if(_loc5_ == null) + { + _loc5_ = new AvatarInfo(); + if(_loc21_ == _loc4_.perUserAvId) + { + _loc5_.init(_loc21_,_loc4_.avInvId,_loc4_.avName,_loc4_.userName,_loc4_.uuid,_loc4_.avTypeId,_loc4_.colors); + } + else + { + _loc5_.init(_loc21_); + } + } + gMainFrame.userInfo.setAvatarInfoByUsernamePerUserAvId(_loc21_,_loc5_); + _loc4_.itemResponseIntegrate(_loc17_.getPartialItemList(_loc5_.type,true),false); + if(_loc20_ != null) + { + _loc20_(true); + } + if(_loc11_) + { + checkIlCallbacks(_loc5_.userName); + } + var _loc22_:int = int(_acIlAvatarQueue.length); + if(_acIlAvatarQueue && _loc22_ > 0) + { + _loc10_ = 0; + while(_loc10_ < _loc22_) + { + if(_acIlAvatarQueue[_loc10_].hasOwnProperty(_loc4_.userName)) + { + if(_acIlAvatarQueue[_loc10_][_loc4_.userName].i == _loc4_.perUserAvId) + { + _acIlAvatarQueue[_loc10_][_loc4_.userName].c(_loc4_.userName,_loc4_.perUserAvId,false,_loc8_); + } + _acIlAvatarQueue.splice(_loc10_,1); + break; + } + _loc10_++; + } + } + } + + public static function handleIlWhenBeforeACAfterReceivingAC(param1:Object) : void + { + itemListResponse(param1); + } + + private static function itemListResponse(param1:Object) : void + { + var _loc19_:Function = null; + var _loc4_:Avatar = null; + var _loc7_:int = 0; + var _loc5_:AvatarInfo = null; + var _loc9_:int = 0; + var _loc8_:Object = param1.concat(); + var _loc20_:* = param1[2] == "0"; + if(!_loc20_) + { + if(param1[2] == "1") + { + itemsInUseResponse(param1); + } + else + { + if(param1[2] == "-1") + { + throw new Error("server returned IL failure: " + param1); + } + itemsChangedListResponse(param1); + } + return; + } + var _loc3_:int = int(param1[3]); + var _loc21_:int = int(param1[4]); + var _loc18_:String = param1[5]; + var _loc10_:int = int(param1[6]); + var _loc14_:int = int(param1[7]); + var _loc11_:int = int(param1[8]); + var _loc2_:Array = param1.slice(9,param1.length); + var _loc17_:int = int(_ilAvatarQueue.length); + var _loc13_:Object = getResponseItems(_loc8_,_loc21_,_loc18_); + _loc4_ = _loc13_.ilAvatar; + _loc19_ = _loc13_.ilCallback; + if(!_loc4_) + { + return; + } + var _loc12_:AccItemCollection = generateClothingList(_loc11_,_loc2_,_loc4_.avInvId,_loc10_,_loc14_,_loc4_.userName.toLowerCase() == gMainFrame.userInfo.myUserName.toLowerCase()); + var _loc15_:AccItemCollection = new AccItemCollection(); + var _loc6_:int = int(_loc12_.length); + _loc7_ = 0; + while(_loc7_ < _loc6_) + { + _loc15_.pushAccItem(_loc12_.getAccItem(_loc7_).clone() as Item); + _loc7_++; + } + _loc12_ = null; + if(_loc4_.userName != gMainFrame.userInfo.myUserName) + { + return; + } + var _loc16_:UserInfo = gMainFrame.userInfo.getUserInfoByUserName(_loc4_.userName); + _loc5_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(_loc18_,_loc21_); + _loc16_.fullItemList = _loc15_; + gMainFrame.userInfo.setUserInfoByUserName(_loc4_.userName,_loc16_); + _loc4_.itemResponseIntegrate(_loc16_.getPartialItemList(_loc5_.type,true),false); + if(_loc19_ != null) + { + _loc19_(true); + } + checkIlCallbacks(_loc5_.userName); + var _loc22_:int = int(_acIlAvatarQueue.length); + if(_acIlAvatarQueue && _loc22_ > 0) + { + _loc9_ = 0; + while(_loc9_ < _loc22_) + { + if(_acIlAvatarQueue[_loc9_].hasOwnProperty(_loc4_.userName)) + { + if(_acIlAvatarQueue[_loc9_][_loc4_.userName].i == _loc4_.perUserAvId) + { + _acIlAvatarQueue[_loc9_][_loc4_.userName].c(_loc4_.userName,_loc4_.perUserAvId,false,_loc8_); + } + _acIlAvatarQueue.splice(_loc9_,1); + break; + } + _loc9_++; + } + } + _loc15_ = null; + } + + private static function itemUseResponse(param1:Object) : void + { + var _loc3_:Boolean = false; + var _loc4_:Function = null; + var _loc2_:Object = null; + if(_iuQueue.length > 0) + { + _loc2_ = _iuQueue.shift()[0]; + _loc4_ = _loc2_["c"]; + } + else + { + _loc4_ = null; + } + _loc3_ = false; + if(param1[2] == "1") + { + _loc3_ = true; + } + if(_loc4_ != null) + { + _loc4_(_loc2_["o"],_loc2_["f"],_loc3_); + } + } + + private static function itemBuyResponse(param1:Object) : void + { + var _loc3_:Function = null; + var _loc6_:Object = null; + var _loc4_:Object = null; + var _loc5_:int = int(param1[3]); + var _loc7_:int = int(param1[2]); + var _loc2_:int = int(param1[5]); + if(param1[4] == "") + { + _loc6_ = UserCurrency.getCurrency(_loc2_); + if(_loc6_ == null) + { + throw new Error("ItemManager: Received unknown currencyType: " + _loc2_); + } + } + else + { + _loc6_ = param1[4]; + } + if(_loc7_ == 1) + { + if(!UserCurrency.setCurrency(_loc6_,_loc2_)) + { + throw new Error("ItemManager: Received unknown currencyType: " + _loc2_); + } + } + if(_ibQueue.length > 0 && Boolean(_ibQueue[0].hasOwnProperty(_loc5_))) + { + _loc4_ = _ibQueue.shift()[_loc5_]; + _loc3_ = _loc4_["c"]; + } + else + { + _loc3_ = null; + } + if(_loc3_ != null) + { + _loc3_(_loc7_,_loc6_,0); + } + } + + private static function itemRecycleResponse(param1:Object) : void + { + var _loc5_:int = 0; + var _loc6_:int = 2; + var _loc2_:int = int(param1[_loc6_++]); + var _loc4_:int = UserCurrency.getCurrency(0) as int; + var _loc3_:int = int(param1[_loc6_] == "-1" ? _loc4_ : param1[_loc6_]); + _loc6_++; + var _loc7_:Vector. = new Vector.(); + if(_loc2_ > 0) + { + _loc5_ = 0; + while(_loc5_ < _loc2_) + { + _loc7_.push(param1[_loc6_++]); + _loc5_++; + } + UserCurrency.setCurrency(_loc3_,0); + } + if(_irCallback != null) + { + _irCallback(_loc7_); + } + } + + private static function itemPrizeResponse(param1:Object) : void + { + guiManager.onItemPrize(param1); + } + + private static function itemDiamondBundleResponse(param1:Object) : void + { + if(_diamondBundleBuyCallback != null) + { + _diamondBundleBuyCallback(param1); + _diamondBundleBuyCallback = null; + } + } + + private static function itemDefResponse(param1:DefPacksDefHelper) : void + { + var _loc2_:* = null; + _itemDefs = {}; + for each(_loc2_ in param1.def) + { + addItemDef(_loc2_); + } + itemDefsHaveLoaded = true; + if(functionToCallWhenDefsLoaded != null) + { + functionToCallWhenDefsLoaded(); + functionToCallWhenDefsLoaded = null; + } + } + + private static function addItemDef(_loc2_:Object) : void + { + var _loc4_:Array = null; + var _loc3_:int = 0; + _loc4_ = _loc2_.colors.split(","); + _loc3_ = 0; + while(_loc3_ < _loc4_.length) + { + _loc4_[_loc3_] = uint(_loc4_[_loc3_]); + _loc3_++; + } + _itemDefs[int(_loc2_.id)] = { + "defId":int(_loc2_.id), + "accId":int(_loc2_.layerDefId), + "layerId":int(_loc2_.layerId), + "type":int(_loc2_.type), + "cost":int(_loc2_.value), + "name":"", + "titleStrId":int(_loc2_.titleStrId), + "isGiftable":_loc2_.isGiftable == "1", + "isMembersOnly":_loc2_.membersOnly == "1", + "isNew":_loc2_.itemStatus == "1", + "isOnSale":_loc2_.itemStatus == "2", + "enviroType":int(_loc2_.enviroType), + "avatarUseFlag":Number(_loc2_.avatarUseFlags), + "itemStatus":int(_loc2_.itemStatus), + "recycleValue":int(_loc2_.recycleValue), + "currencyType":int(_loc2_.currencyType), + "defense":int(_loc2_.defense), + "attack":int(_loc2_.attack), + "attackMediaRefId":int(_loc2_.attackMediaRefId), + "combatType":int(_loc2_.combatType), + "modifierType":int(_loc2_.modifierType), + "modifierValue":int(_loc2_.modifierValue), + "criticalHit":int(_loc2_.criticalHit), + "combinedCurrencyString":_loc2_.combinedCost, + "colors":_loc4_, + "availabilityStartTime":uint(_loc2_.availabilityStartTime), + "availabilityEndTime":uint(_loc2_.availabilityEndTime) + }; + _itemDefs[int(_loc2_.id)].name = LocalizationManager.translateIdOnly(int(_loc2_.titleStrId)); + } + + // Burrow: def rows sent while the game runs ("xdi", XtReplyDemuxer), for + // items the staff make (the server's lib/customitems.js); each with its + // name, which the localization the game loaded does not have. before + // the item pack is in, there is nothing to do: the pack has them. + public static function addItemDefs(param1:Array) : void + { + if(_itemDefs == null) + { + return; + } + for each(var _loc2_:Object in param1) + { + addItemDef(_loc2_); + if(_loc2_.name) + { + _itemDefs[int(_loc2_.id)].name = String(_loc2_.name); + } + } + } + + public static function relocalizeItems() : void + { + for each(var _loc1_ in _itemDefs) + { + _loc1_.name = LocalizationManager.translateIdOnly(_loc1_.titleStrId); + } + } + + private static function currencyExchangeDefResponse(param1:DefPacksDefHelper) : void + { + var _loc2_:Object = null; + _currencyExchangeDefs = {}; + for each(var _loc3_ in param1.def) + { + _loc2_ = { + "defId":_loc3_.id, + "mediaId":_loc3_.mediaRefId, + "result":_loc3_.result, + "resultType":_loc3_.resultType, + "value":_loc3_.cost, + "currencyType":_loc3_.costType, + "name":"", + "titleStrId":int(_loc3_.titleStrId), + "availabilityStartTime":uint(_loc3_.availabilityStartTime), + "availabilityEndTime":uint(_loc3_.availabilityEndTime) + }; + _currencyExchangeDefs[_loc2_.defId] = _loc2_; + _currencyExchangeDefs[int(_loc3_.id)].name = LocalizationManager.translateIdOnly(_loc3_.titleStrId); + } + } + + public static function relocalizeCurrencyExchanges() : void + { + for each(var _loc1_ in _currencyExchangeDefs) + { + _loc1_.name = LocalizationManager.translateIdOnly(_loc1_.titleStrId); + } + } + + private static function currencyUpdateResponse(param1:Object) : void + { + var _loc6_:int = 0; + var _loc7_:int = 0; + var _loc3_:SBOkPopup = null; + var _loc2_:int = int(param1[2]); + var _loc4_:Object = param1[3]; + var _loc5_:Boolean = param1[4] == 3 || param1[4] == 4; + var _loc8_:int = -1; + if(_loc2_ == 0) + { + _loc8_ = UserCurrency.getCurrency(0); + UserCurrency.setCurrency(_loc4_,0); + _loc7_ = int(_loc4_) - _loc8_; + if(_loc7_ != 1) + { + _loc6_ = 14900; + } + else + { + _loc6_ = 14901; + } + QuestManager.currencyUpdate(int(_loc4_) - _loc8_); + } + else if(_loc2_ == 1) + { + _loc8_ = UserCurrency.getCurrency(1); + UserCurrency.setCurrency(_loc4_,1); + _loc7_ = int(_loc4_) - _loc8_; + if(_loc7_ != 1) + { + _loc6_ = 14902; + } + else + { + _loc6_ = 14903; + } + } + else if(_loc2_ == 2) + { + _loc8_ = UserCurrency.getCurrency(2); + UserCurrency.setCurrency(_loc4_,2); + _loc7_ = int(_loc4_) - _loc8_; + if(_loc7_ != 1) + { + _loc6_ = 14904; + } + else + { + _loc6_ = 14905; + } + } + else if(_loc2_ == 3) + { + _loc8_ = UserCurrency.getCurrency(3); + UserCurrency.setCurrency(_loc4_,3); + _loc7_ = int(_loc4_) - _loc8_; + if(_loc7_ != 1) + { + _loc6_ = 14906; + } + else + { + _loc6_ = 14907; + } + } + else if(_loc2_ == 4) + { + UserCurrency.setCurrency(_loc4_,4); + } + else if(_loc2_ == 5) + { + UserCurrency.setCurrency(_loc4_,5); + } + else if(_loc2_ == 6) + { + UserCurrency.setCurrency(_loc4_,6); + } + else if(_loc2_ == 7) + { + UserCurrency.setCurrency(_loc4_,7); + } + else if(_loc2_ == 8) + { + UserCurrency.setCurrency(_loc4_,7); + } + else if(_loc2_ == 9) + { + UserCurrency.setCurrency(_loc4_,9); + } + else if(_loc2_ == 10) + { + UserCurrency.setCurrency(_loc4_,10); + } + else if(_loc2_ == 100) + { + UserCurrency.setCurrency(_loc4_,100); + } + else + { + if(_loc2_ != 11) + { + throw new Error("ItemManager: Received unknown currencyType: " + _loc2_); + } + UserCurrency.setCurrency(_loc4_,11); + } + if(_loc8_ < _loc4_) + { + if(guiManager != null) + { + if(guiManager.guiLayer != null) + { + if(_loc5_) + { + _loc3_ = new SBOkPopup(guiManager.guiLayer,LocalizationManager.translateIdAndInsertOnly(_loc6_,Utility.convertNumberToString(_loc7_))); + } + else if(param1[4] == 15) + { + GuiManager.openJumpPopup(false,null,null,_loc7_); + } + else if(param1[4] == 16) + { + guiManager.setupGemGiftPopup(_loc7_); + } + } + } + } + if(gMainFrame.clientInfo.roomType == 7) + { + QuestManager.updateCombinedCurrency(); + } + } + + private static function currencyDonationResponse(param1:Object) : void + { + if(_donateCallback != null) + { + _donateCallback(param1[2] == "1"); + _donateCallback = null; + } + } + + private static function currencyExchangeResponse(param1:Object) : void + { + if(_currencyExchangeCallback != null) + { + _currencyExchangeCallback(param1[2] == "1",param1[3],0); + _currencyExchangeCallback = null; + } + } + + public static function shopListResponse(param1:Array, param2:int) : void + { + var _loc4_:int = 0; + var _loc13_:Function = null; + var _loc6_:Object = null; + var _loc11_:int = int(param1[2]); + var _loc5_:String = param1[4]; + var _loc12_:Boolean = Boolean(param1[6]); + var _loc7_:int = int(param1[7]); + _loc4_ = 0; + while(_loc4_ < _slQueue.length) + { + if(_slQueue[_loc4_].hasOwnProperty(_loc11_)) + { + _loc6_ = _slQueue.shift()[_loc11_]; + _loc13_ = _loc6_["c"]; + break; + } + _loc4_++; + } + var _loc3_:Object = setupShopItemObject(param1,param2); + var _loc8_:IitemCollection = _loc3_.shopItemArray; + var _loc9_:Array = _loc3_.shopItemColorsArray; + if(_loc8_ != null && _loc13_ != null) + { + if(_loc9_ != null) + { + if(_loc13_.length == 3) + { + _loc13_(_loc8_,_loc5_,_loc9_); + } + else + { + _loc13_(_loc8_,_loc5_,_loc12_,_loc7_,_loc9_); + } + } + else if(_loc13_.length <= 3) + { + _loc13_(_loc8_,_loc5_); + } + else + { + _loc13_(_loc8_,_loc5_,_loc12_,_loc7_); + } + } + } + + private static function setupShopItemObject(param1:Array, param2:int) : Object + { + var _loc9_:int = 0; + var _loc4_:Array = null; + var _loc10_:Array = null; + var _loc11_:Array = null; + var _loc13_:Array = null; + var _loc3_:Object = null; + var _loc12_:int = 0; + var _loc5_:int = 0; + var _loc7_:Array = null; + var _loc8_:IitemCollection = null; + var _loc6_:int = 8; + if(param2 == 1000) + { + _loc9_ = int(param1[_loc6_++]); + _loc7_ = []; + _loc8_ = generateClothingShopList(_loc9_,param1.slice(_loc6_++,param1.length),_loc7_); + } + else if(param2 == 1030 || param2 == 1040) + { + if(_denShopListHandler != null) + { + _loc8_ = _denShopListHandler(param1,param2,null); + } + } + else if(param2 == 1051) + { + _loc9_ = int(param1[_loc6_++]); + _loc8_ = generateCurrencyExchangeShopList(_loc9_,param1.slice(_loc6_++,param1.length)); + } + else if(param2 == 1054) + { + _loc9_ = int(param1[_loc6_++]); + _loc7_ = []; + _loc8_ = DiamondXtCommManager.generateDiamondShopList(_loc9_,param1.slice(_loc6_++,param1.length),_loc7_); + } + else + { + if(param2 != 1060) + { + throw new Error("Unimplemented shopList response type: " + param2); + } + _loc9_ = int(param1[_loc6_++]); + if(_loc9_ > 0) + { + _loc4_ = (param1[_loc6_++] as String).split(","); + _loc10_ = (param1[_loc6_++] as String).split(","); + _loc11_ = (param1 as Array).slice(_loc6_); + _loc12_ = 0; + _loc5_ = 0; + while(_loc5_ < _loc4_.length) + { + _loc13_ = (param1 as Array).slice(0,_loc6_ - 2); + _loc13_[8] = _loc10_[_loc5_]; + _loc13_ = _loc13_.concat(_loc11_.slice(_loc12_,_loc12_ + int(_loc10_[_loc5_]))); + _loc12_ += int(_loc10_[_loc5_]); + _loc3_ = setupShopItemObject(_loc13_,_loc4_[_loc5_]); + if(_loc8_ == null) + { + _loc8_ = _loc3_.shopItemArray; + } + else + { + _loc8_.setCoreArray(_loc8_.concatCollection(_loc3_.shopItemArray)); + } + if(_loc7_ == null) + { + _loc7_ = _loc3_.shopItemColorsArray; + } + else + { + _loc7_ = _loc7_.concat(_loc3_.shopItemColorsArray); + } + _loc5_++; + } + } + } + return { + "shopItemArray":_loc8_, + "shopItemColorsArray":_loc7_ + }; + } + + public static function setItemBuyIlCallback(param1:Function) : void + { + _buyItemsIlCallback = param1; + } + + public static function setHudAvtItemListLayerAnim(param1:LayerAnim) : void + { + _hudAvtLayerAnim = param1; + } + + public static function generateBodyModList(param1:int, param2:int = -1, param3:int = -1, param4:Boolean = true) : AccItemCollection + { + var _loc5_:int = 0; + var _loc6_:Object = null; + var _loc9_:Item = null; + var _loc8_:int = 0; + var _loc7_:AccItemCollection = new AccItemCollection(); + _loc8_ = 0; + while(_loc8_ < _bodyItemDefIds.length) + { + _loc5_ = int(_bodyItemDefIds[_loc8_]); + _loc6_ = _itemDefs[_loc5_]; + if(_loc6_ == null) + { + DebugUtility.debugTrace("ItemManager: unknown body itemDef=" + _loc5_); + } + else + { + _loc9_ = getBodyModFromDefId(_loc5_,param1,_loc5_ == 1 || _loc5_ == param2 || _loc5_ == param3,param4); + _loc7_.pushAccItem(_loc9_); + } + _loc8_++; + } + return _loc7_; + } + + public static function getBodyModFromDefId(param1:int, param2:int, param3:Boolean = false, param4:Boolean = true) : Item + { + var _loc5_:Item = new Item(); + _loc5_.init(param1,param1 * -1); + if(param3) + { + if(param4) + { + _loc5_.setInUse(param2,param3); + } + else + { + _loc5_.forceInUse(true); + } + } + return _loc5_; + } + + public static function generateClothingList(param1:int, param2:Array, param3:int, param4:int, param5:int, param6:Boolean) : AccItemCollection + { + var _loc8_:int = 0; + var _loc10_:int = 0; + var _loc11_:Object = null; + var _loc9_:Item = null; + var _loc7_:int = 0; + var _loc12_:AccItemCollection = new AccItemCollection(); + var _loc13_:AccItemCollection = generateBodyModList(param3,param4,param5,param6); + _loc8_ = 0; + while(_loc8_ < param1) + { + _loc10_ = int(param2[_loc7_++]); + _loc11_ = _itemDefs[_loc10_]; + if(_loc11_ == null) + { + DebugUtility.debugTrace("ItemXtCommManager: unknown clothing itemDef=" + _loc10_); + } + else + { + _loc9_ = new Item(); + if(param6) + { + _loc9_.init(_loc10_,int(param2[_loc7_++]),uint(param2[_loc7_++]),new EquippedAvatars(param2[_loc7_++]),false,-1,param2[_loc7_++]); + } + else + { + _loc9_.init(_loc10_,int(param2[_loc7_++]),uint(param2[_loc7_++]),EquippedAvatars.forced()); + } + _loc12_.setAccItem(_loc8_,_loc9_); + } + _loc8_++; + } + _loc12_ = new AccItemCollection(_loc12_.concatCollection(_loc13_)); + if(param6) + { + _loc12_.getCoreArray().sortOn("invIdx",0x10 | 2); + } + return _loc12_; + } + + private static function generateClothingShopList(param1:int, param2:Array, param3:Array) : IitemCollection + { + var _loc6_:Object = null; + var _loc7_:int = 0; + var _loc5_:Item = null; + var _loc4_:int = _playerAvatar.avTypeId; + var _loc8_:IitemCollection = new IitemCollection(); + _loc7_ = 0; + while(_loc7_ < param1) + { + _loc5_ = new Item(); + _loc6_ = ItemXtCommManager.getItemDef(int(param2[_loc7_])); + param3[_loc6_.defId] = _loc6_.colors.concat(); + _loc5_.init(_loc6_.defId,_loc7_,_loc6_.colors[0],null,true); + _loc8_.pushIitem(_loc5_); + _loc7_++; + } + return _loc8_; + } + + private static function generateCurrencyExchangeShopList(param1:int, param2:Array) : IitemCollection + { + var _loc3_:int = 0; + var _loc5_:Object = null; + var _loc4_:CurrencyItem = null; + var _loc6_:int = 0; + var _loc8_:IitemCollection = new IitemCollection(); + var _loc7_:int = 0; + _loc6_ = 0; + while(_loc6_ < param1) + { + _loc3_ = int(param2[_loc7_++]); + _loc5_ = getCurrencyExchangeDef(_loc3_); + if(!_loc5_) + { + _loc6_--; + } + else + { + _loc4_ = new CurrencyItem(); + _loc4_.init(_loc3_); + _loc8_.setIitem(_loc6_,_loc4_); + } + _loc6_++; + } + return _loc8_; + } + + public static function getItemDef(param1:int) : Object + { + return _itemDefs[param1]; + } + + public static function getCurrencyExchangeDef(param1:int) : Object + { + return _currencyExchangeDefs[param1]; + } + + public static function canUseItem(param1:int, param2:Avatar, param3:Boolean) : Boolean + { + if(param3 && gMainFrame.userInfo.getAvatarDefByAvatar(param2) && gMainFrame.userInfo.getAvatarDefByAvatar(param2).patternRefIds.indexOf(param1) != -1) + { + return true; + } + if(_itemDefs[param1] != null) + { + return BitUtility.bitwiseAnd(_itemDefs[param1].avatarUseFlag,BitUtility.leftShiftNumbers(param2.avTypeId - 1)) != 0; + } + return false; + } + + public static function avTypeThatCanUseItem(param1:int) : Array + { + var _loc3_:int = 0; + var _loc4_:int = 0; + var _loc2_:Number = Number(_itemDefs[param1].avatarUseFlag); + var _loc5_:Array = []; + while(_loc2_ > 0) + { + if(BitUtility.bitwiseAnd(_loc2_,1) == 1) + { + _loc3_ += 1; + _loc5_.push(_loc3_ + _loc4_); + } + else + { + _loc4_++; + } + _loc2_ = BitUtility.rightShiftNumber(_loc2_); + } + return _loc5_; + } + } +} + diff --git a/swf-src/KeepAlive.as b/swf-src/KeepAlive.as new file mode 100644 index 0000000..a30b3d4 --- /dev/null +++ b/swf-src/KeepAlive.as @@ -0,0 +1,177 @@ +package com.sbi.client +{ + import com.sbi.popup.SBOkPopup; + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.events.TimerEvent; + import flash.utils.Timer; + import localization.LocalizationManager; + + public class KeepAlive + { + + // how long a player may be away before the game signs them out: an + // hour and a quarter (the game's own was 7 minutes). the server's + // socket waits longer still (config.idleTimeoutMs). + private static var KICK_INTERVAL:int = 4500000; + + private static var SEND_MSG_INTERVAL:int = 180000; + + private static var NOTIFY_USER_INTERVAL:int = 10000; + + private static var NOTIFY_USER_TIME:int = 60000; + + public static var popupLayer:DisplayObjectContainer; + + private static var _keepAliveTimer:Timer; + + private static var _timeLeftTimer:Timer; + + private static var _bInputReceived:Boolean; + + private static var _mcsToKeepAlive:Array; + + private static var _lastMsgSentToServer:Number; + + private static var _inputTimer:Timer; + + private static var _kickWarningPopupShowing:Boolean; + + private static var _isConnected:Function; + + private static var _disconnectClient:Function; + + private static var _playIdleWarningSound:Function; + + public function KeepAlive() + { + super(); + } + + public static function init(param1:DisplayObjectContainer, param2:Function, param3:Function = null, param4:Function = null) : void + { + popupLayer = param1; + _keepAliveTimer = new Timer(SEND_MSG_INTERVAL); + _keepAliveTimer.addEventListener("timer",sendKeepAliveMsg); + _timeLeftTimer = new Timer(NOTIFY_USER_INTERVAL); + _timeLeftTimer.addEventListener("timer",timeLeftTimer); + _timeLeftTimer.start(); + _lastMsgSentToServer = new Date().getTime(); + _mcsToKeepAlive = []; + _isConnected = param2; + _disconnectClient = param3; + _playIdleWarningSound = param4; + } + + public static function startKATimer(param1:DisplayObjectContainer) : void + { + param1.addEventListener("mouseDown",inputReceivedHandler,false,0,true); + param1.addEventListener("keyDown",inputReceivedHandler,false,0,true); + _mcsToKeepAlive.push(param1); + _bInputReceived = true; + sendKeepAliveMsg(null); + _keepAliveTimer.start(); + } + + public static function stopKATimer(param1:DisplayObjectContainer) : void + { + var _loc2_:int = 0; + gMainFrame.server.setXtObject_Str("ka",[],gMainFrame.server.isWorldZone); + _keepAliveTimer.stop(); + _loc2_ = 0; + while(_loc2_ < _mcsToKeepAlive.length) + { + if(_mcsToKeepAlive[_loc2_] == param1) + { + _mcsToKeepAlive[_loc2_].removeEventListener("mouseDown",inputReceivedHandler); + _mcsToKeepAlive[_loc2_].removeEventListener("keyDown",inputReceivedHandler); + _mcsToKeepAlive.splice(_loc2_,1); + break; + } + _loc2_++; + } + } + + public static function restartTimeLeftTimer() : void + { + if(_timeLeftTimer) + { + _lastMsgSentToServer = new Date().getTime(); + _timeLeftTimer.stop(); + _timeLeftTimer.start(); + } + } + + public static function sendKeepAliveReset() : void + { + _bInputReceived = true; + sendKeepAliveMsg(null); + } + + private static function sendKeepAliveMsg(param1:TimerEvent) : void + { + if(_bInputReceived) + { + gMainFrame.server.setXtObject_Str("ka",[],gMainFrame.server.isWorldZone); + _lastMsgSentToServer = new Date().getTime(); + _bInputReceived = false; + } + } + + private static function timeLeftTimer(param1:TimerEvent) : void + { + var _loc2_:DisplayObject = null; + var _loc3_:Number = new Date().getTime() - _lastMsgSentToServer; + if(!_kickWarningPopupShowing && _loc3_ > KICK_INTERVAL - NOTIFY_USER_TIME) + { + _loc2_ = new SBOkPopup(popupLayer,LocalizationManager.translateIdOnly(14681),true,onKickWarningPopup); + _kickWarningPopupShowing = true; + if(_playIdleWarningSound != null) + { + _playIdleWarningSound(); + } + if((gMainFrame.userInfo.isModerator || gMainFrame.clientInfo.accountType == 4) && !gMainFrame.server.isBlueboxMode()) + { + _bInputReceived = true; + sendKeepAliveMsg(null); + _kickWarningPopupShowing = false; + SBOkPopup.destroyInParentChain(_loc2_); + } + } + if(_loc3_ > KICK_INTERVAL) + { + if(_isConnected()) + { + if(_disconnectClient != null) + { + _disconnectClient(); + } + } + } + } + + private static function onKickWarningPopup(param1:MouseEvent) : void + { + _bInputReceived = true; + sendKeepAliveMsg(null); + param1.stopPropagation(); + SBOkPopup.destroyInParentChain(param1.target.parent); + _kickWarningPopupShowing = false; + } + + public static function inputReceivedHandler(param1:Event) : void + { + if(!_bInputReceived) + { + _bInputReceived = true; + } + if(new Date().getTime() - _lastMsgSentToServer > SEND_MSG_INTERVAL) + { + sendKeepAliveMsg(null); + } + } + } +} + diff --git a/swf-src/LayerAnim.as b/swf-src/LayerAnim.as index ec3819b..f6a120d 100644 --- a/swf-src/LayerAnim.as +++ b/swf-src/LayerAnim.as @@ -440,7 +440,8 @@ package com.sbi.graphics _loc2_ = false; for(var _loc4_ in param1) { - if(!_layers[_loc4_] || _layers[_loc4_].l != param1[_loc4_].l) + // (a custom item has its base's art: its own picture makes it another, AJClient.customArtKey) + if(!_layers[_loc4_] || _layers[_loc4_].l != param1[_loc4_].l || AJClient.customArtKey("clothing",int(_layers[_loc4_].d)) != AJClient.customArtKey("clothing",int(param1[_loc4_].d))) { _loc2_ = true; break; @@ -702,6 +703,19 @@ package com.sbi.graphics buildRequestArray(param1,_loc2_,_loc4_); _loc2_.sort(); var _loc3_:String = _loc2_.join(); + // custom items with pictures of their own are painted otherwise than + // their bases: their frames are kept apart + for each(var _loc5_:Object in _layers) + { + if(_loc5_.d) + { + var _loc6_:String = AJClient.customArtKey("clothing",int(_loc5_.d)); + if(_loc6_ != "") + { + _loc3_ += "|" + _loc6_; + } + } + } _colors = _loc4_; _requestedCacheKey = _loc3_; _receivedData = []; @@ -792,7 +806,8 @@ package com.sbi.graphics { var _loc7_:int = int(_loc6_[_loc4_.l]); _loc6_[_loc4_.l] = _loc7_ + 1; - _bitmap.setLayer(LayerBitmap.slotFor(_loc4_.l,_loc7_),_loc4_.d,_loc4_.c,_requestedCacheKey); + _bitmap.setLayer(LayerBitmap.slotFor(_loc4_.l,_loc7_),_loc4_.d,_loc4_.c,_requestedCacheKey, + _loc4_.p >= 0 && _layers != null && _layers[_loc4_.p] != null ? int(_layers[_loc4_.p].d) : 0); } finishAnimRequest(); _receivedData = null; diff --git a/swf-src/LayerBitmap.as b/swf-src/LayerBitmap.as index 4dc0a4c..39d0584 100644 --- a/swf-src/LayerBitmap.as +++ b/swf-src/LayerBitmap.as @@ -4,7 +4,9 @@ package com.sbi.graphics import com.sbi.loader.ImageServerURL; import flash.display.Bitmap; import flash.display.BitmapData; + import flash.geom.Matrix; import flash.geom.Point; + import flash.geom.Rectangle; import flash.utils.ByteArray; import flash.utils.Dictionary; @@ -88,6 +90,42 @@ package com.sbi.graphics { _lastFrame = -1; } + + // a custom item's picture has loaded (AJClient.customArtBitmap). the + // frames painted while it loaded show the item it was made from, and + // are kept: each is painted again, or the picture shows only on the + // frames not painted yet (and comes and goes as the animation plays). + public function artArrived() : void + { + var _loc1_:Array = [_activeLayerGroup]; + for each(var _loc2_:LayerGroup in _cachedLayerGroups) + { + _loc1_.push(_loc2_); + } + for each(var _loc3_:LayerGroup in _loc1_) + { + if(_loc3_ == null || _loc3_.paintedFrames == null) + { + continue; + } + for each(var _loc4_:Array in _loc3_.paintedFrames) + { + if(_loc4_ == null) + { + continue; + } + if(_loc4_[false] != null) + { + _loc4_[false].isValid = false; + } + if(_loc4_[true] != null) + { + _loc4_[true].isValid = false; + } + } + } + invalidate(); + } public function trimLayerGroups() : Set { @@ -126,7 +164,9 @@ package com.sbi.graphics return 100 + param1 * 16 + Math.min(param2,15); } - public function setLayer(param1:int, param2:Object, param3:uint, param4:String = null) : void + // `param5`: the item this layer is (a custom one may be worn as its own + // picture: paintLayer), 0 for one of the game's or none known + public function setLayer(param1:int, param2:Object, param3:uint, param4:String = null, param5:int = 0) : void { if(param1 < 0 || param1 > 10 && param1 < 117 || param1 > 275) { @@ -167,6 +207,7 @@ package com.sbi.graphics setLayerColor(param1,param3); } _activeLayerGroup.layers[param1].o = param2; + _activeLayerGroup.layers[param1].item = param5; } else { @@ -432,7 +473,7 @@ package com.sbi.graphics _loc6_ = _activeLayerGroup.layers[_loc5_]; if(_loc6_ != null && _loc6_.o != null && _loc6_.pal != null) { - if(paintFrame(_loc6_.o,param1,_loc6_.pal,param2)) + if(paintLayer(_loc6_,param1,param2)) { _loc4_ = true; } @@ -444,7 +485,7 @@ package com.sbi.graphics _loc6_ = _activeLayerGroup.layers[100 + _loc5_ * 16 + _loc8_]; if(_loc6_ != null && _loc6_.o != null && _loc6_.pal != null) { - if(paintFrame(_loc6_.o,param1,_loc6_.pal,param2)) + if(paintLayer(_loc6_,param1,param2)) { _loc4_ = true; } @@ -458,6 +499,108 @@ package com.sbi.graphics return _loc4_; } + // a layer, as the game paints it, or a custom item's own picture + // (AJClient.customArtMode): "sticker", the picture fitted in the + // item's place in this frame; "texture", the item's shape with the + // picture in it, its outlines kept. while the picture loads it is + // painted as the item it was made from. + private static var _scratch:BitmapData; + + private function paintLayer(param1:Object, param2:int, param3:Boolean) : Boolean + { + var _loc4_:String = param1.item > 0 ? AJClient.customArtMode("clothing",param1.item) : null; + var _loc5_:BitmapData = _loc4_ != null ? AJClient.customArtBitmap("clothing",param1.item,this) : null; + if(_loc5_ == null || param1.o == null || !param1.o.hasOwnProperty("f") || param2 >= param1.o.f.length || param1.o.f[param2] == null) + { + return paintFrame(param1.o,param2,param1.pal,param3); + } + var _loc6_:Object = param1.o.f[param2]; + var _loc7_:BitmapData = this.bitmapData; + if(_loc7_ == null) + { + return false; + } + var _loc8_:Number = _bmax.x - _bmin.x; + var _loc9_:Number = int(_loc6_.x) - _bmin.x; + var _loc10_:Number = int(_loc6_.y) - _bmin.y; + var _loc11_:Number = int(_loc6_.w); + var _loc12_:Number = int(_loc6_.h); + if(param3) + { + _loc9_ = _loc8_ - _loc9_ - _loc11_; + } + if(_loc4_ == "sticker") + { + var _loc13_:Number = Math.min(_loc11_ / _loc5_.width,_loc12_ / _loc5_.height); + var _loc14_:Matrix = new Matrix(); + if(param3) + { + _loc14_.scale(-_loc13_,_loc13_); + _loc14_.translate(_loc9_ + (_loc11_ + _loc5_.width * _loc13_) * 0.5,_loc10_ + (_loc12_ - _loc5_.height * _loc13_) * 0.5); + } + else + { + _loc14_.scale(_loc13_,_loc13_); + _loc14_.translate(_loc9_ + (_loc11_ - _loc5_.width * _loc13_) * 0.5,_loc10_ + (_loc12_ - _loc5_.height * _loc13_) * 0.5); + } + _loc7_.draw(_loc5_,_loc14_,null,null,null,true); + return true; + } + // the texture: the layer alone first, then its pixels from the picture + if(_scratch == null || _scratch.width < _loc7_.width || _scratch.height < _loc7_.height) + { + if(_scratch != null) + { + _scratch.dispose(); + } + _scratch = new BitmapData(Math.max(_loc7_.width,256),Math.max(_loc7_.height,256),true,0); + } + _scratch.fillRect(_scratch.rect,0); + this.bitmapData = _scratch; + var _loc15_:Boolean = paintFrame(param1.o,param2,param1.pal,param3); + this.bitmapData = _loc7_; + if(!_loc15_) + { + return false; + } + var _loc16_:int = Math.max(0,int(_loc9_)); + var _loc17_:int = Math.max(0,int(_loc10_)); + var _loc18_:int = Math.min(_loc7_.width,int(_loc9_ + _loc11_)); + var _loc19_:int = Math.min(_loc7_.height,int(_loc10_ + _loc12_)); + var _loc20_:int = _loc17_; + while(_loc20_ < _loc19_) + { + var _loc21_:int = _loc16_; + while(_loc21_ < _loc18_) + { + var _loc22_:uint = _scratch.getPixel32(_loc21_,_loc20_); + var _loc23_:uint = _loc22_ >>> 24; + if(_loc23_ > 0) + { + var _loc24_:Number = (((_loc22_ >> 16) & 0xFF) * 3 + ((_loc22_ >> 8) & 0xFF) * 6 + (_loc22_ & 0xFF)) / 10; + // dark: an outline, kept + if(_loc24_ >= 60) + { + var _loc25_:int = int(((param3 ? _loc18_ - 1 - _loc21_ : _loc21_ - _loc16_) / Math.max(1,_loc18_ - _loc16_)) * _loc5_.width); + var _loc26_:int = int(((_loc20_ - _loc17_) / Math.max(1,_loc19_ - _loc17_)) * _loc5_.height); + var _loc27_:uint = _loc5_.getPixel32(Math.min(_loc5_.width - 1,_loc25_),Math.min(_loc5_.height - 1,_loc26_)); + // its shading kept: lighter or darker as the item was there + var _loc28_:Number = Math.max(0.55,Math.min(1.15,_loc24_ / 170)); + var _loc29_:uint = Math.min(255,((_loc27_ >> 16) & 0xFF) * _loc28_); + var _loc30_:uint = Math.min(255,((_loc27_ >> 8) & 0xFF) * _loc28_); + var _loc31_:uint = Math.min(255,(_loc27_ & 0xFF) * _loc28_); + var _loc32_:uint = Math.min(_loc23_,_loc27_ >>> 24); + _scratch.setPixel32(_loc21_,_loc20_,_loc32_ << 24 | _loc29_ << 16 | _loc30_ << 8 | _loc31_); + } + } + _loc21_++; + } + _loc20_++; + } + _loc7_.copyPixels(_scratch,new Rectangle(0,0,_loc7_.width,_loc7_.height),new Point(0,0),null,null,true); + return true; + } + private function paintFrame(param1:Object, param2:int, param3:Array, param4:Boolean) : Boolean { var _loc25_:int = 0; diff --git a/swf-src/MySettings.as b/swf-src/MySettings.as index d71457e..ceaac49 100644 --- a/swf-src/MySettings.as +++ b/swf-src/MySettings.as @@ -161,6 +161,13 @@ package gui "iconFrame":"redeemCode", "labelLabel":"Item Giver", "btnLabel":"Open" + },{ + // a player's own items (AJClient's Item Maker) + "type":TOGGLE_TYPE_JOIN, + "frame":"itemMaker", + "iconFrame":"redeemCode", + "labelLabel":"Item Maker", + "btnLabel":"Open" },{ "type":TOGGLE_TYPE_JOIN, "frame":"chatFilter", diff --git a/swf-src/SitForwardAction.as b/swf-src/SitForwardAction.as new file mode 100644 index 0000000..775f866 --- /dev/null +++ b/swf-src/SitForwardAction.as @@ -0,0 +1,16 @@ +// not in the game: the action sprite of sitting facing forward (":sitS:", +// gui.ActionManager). the game's other actions are sprites of the HUD's art, +// found by their class name; this one has no art of its own, and only its +// class name is ever read. +package gui +{ + import flash.display.Sprite; + + public class SitForwardAction extends Sprite + { + public function SitForwardAction() + { + super(); + } + } +} diff --git a/swf-src/UserCommXtCommManager.as b/swf-src/UserCommXtCommManager.as index 41b2391..308dbfa 100644 --- a/swf-src/UserCommXtCommManager.as +++ b/swf-src/UserCommXtCommManager.as @@ -215,6 +215,7 @@ package avatar { return; } + _actionMgr.rememberAction(param1); AvatarManager.setAvatarAction(param1); if(!_actionMgr.getActionString(param1)) { @@ -222,8 +223,15 @@ package avatar } addChatMessage(_actionMgr.getActionString(param1)); var _loc2_:AvatarWorldView = AvatarManager.avatarViewList[AvatarManager.playerSfsUserId]; + if(_loc2_ && _actionMgr.mirrorActions) + { + _loc2_.setActionMirrored(true); + } var _loc3_:int = _loc2_.lastIdleAnim; - gMainFrame.server.sendMessage(_actionMgr.getActionString(param1) + RAW_STR + 3 + RAW_STR + _loc3_); + // m0/m1 is deliberately a new marker: old clients sent the + // animation number here. New clients use it to mirror every action + // consistently on every screen. + gMainFrame.server.sendMessage(_actionMgr.getActionString(param1) + RAW_STR + 3 + RAW_STR + "m" + (_actionMgr.mirrorActions ? "1" : "0")); if(_chatHist.enableFreeChatValue) { _chatHist.resetTreeSearch(); @@ -263,14 +271,21 @@ package avatar } param2 = fixMispellings(param2); param2 = adjustCamelCase(param2); + AJClient.typingSent(); AvatarManager.addAvatarMessage("...",param1,0); param2 = adjustSpecialWords(param2); + // ":fire:" and the like as the emoji (AJClient's emoji) + param2 = AJClient.emojiShortcodes(param2); + // and every emoji as "\{code points}" (AJClient.emojiToTokens) + param2 = AJClient.emojiToTokens(param2); var _loc3_:int = gMainFrame.userInfo.sgChatType == 1 ? 0 : 9; gMainFrame.server.sendMessage(param2 + RAW_STR + _loc3_); if(_chatHist.enableFreeChatValue) { _chatHist.resetTreeSearch(); _chatHist.chatMsgText.text = ""; + // emptied: back to the game's font (ChatHistory.showEmojiInInput) + _chatHist.showEmojiInInput(); gMainFrame.stage.focus = _chatHist.chatMsgText; } } @@ -750,6 +765,10 @@ package avatar if(_loc5_) { AvatarManager.setAvatarAction(_loc5_,_loc19_); + if(String(param1[5]) == "m1") + { + AvatarManager.avatarViewList[_loc19_].setActionMirrored(true); + } } else { diff --git a/swf-src/XtReplyDemuxer.as b/swf-src/XtReplyDemuxer.as index c3c9763..1f0529f 100644 --- a/swf-src/XtReplyDemuxer.as +++ b/swf-src/XtReplyDemuxer.as @@ -84,6 +84,16 @@ package PaletteHelper.handleCustomColors(param1.obj); return; } + if(param1.obj[0] == "xsp") + { + AJClient.onStaff(param1.obj); + return; + } + if(param1.obj[0] == "xdi") + { + AJClient.onItemDefs(param1.obj); + return; + } if(param1.obj[0] == "xtl") { AJClient.showMessage(param1.obj); @@ -94,6 +104,26 @@ package AJClient.askYesNo(param1.obj); return; } + if(param1.obj[0] == "xgt") + { + AJClient.onStaffGoto(param1.obj); + return; + } + if(param1.obj[0] == "xcm") + { + AJClient.onItemMaker(param1.obj); + return; + } + if(param1.obj[0] == "xiv") + { + AJClient.onInvisible(param1.obj); + return; + } + if(param1.obj[0] == "xty") + { + AJClient.onTyping(param1.obj); + return; + } if(param1.obj[0] == "xw") { AJClient.onWhisper(param1.obj); diff --git a/swf/HUDAssets.swf b/swf/HUDAssets.swf index 3c0193e..f497d60 100644 Binary files a/swf/HUDAssets.swf and b/swf/HUDAssets.swf differ diff --git a/swf/ajclient.swf b/swf/ajclient.swf index c0ef464..0fabb0e 100644 Binary files a/swf/ajclient.swf and b/swf/ajclient.swf differ diff --git a/test/account.js b/test/account.js index 77a28d7..5b3a926 100644 --- a/test/account.js +++ b/test/account.js @@ -44,7 +44,7 @@ const panel = page("admin"); const run = async () => { const register = (username, avatarType) => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, - body: JSON.stringify({username, password: "Password01", avatarType, agreed: true})}); + body: JSON.stringify({username, password: "KettlePass01", avatarType, agreed: true})}); assert.strictEqual((await register("Ann", 4)).status, 200); assert.strictEqual((await register("Ben", 24)).status, 200); // what a client shows beside its login form. @@ -55,8 +55,8 @@ const run = async () => { assert.match(await (await fetch(`${BASE}/account`)).text(), /Your account/); assert.strictEqual((await mine("me")).status, 401); assert.strictEqual((await mine("login", {username: "Ann", password: "wrong"})).status, 401); - assert.strictEqual((await mine("login", {username: "Nobody", password: "Password01"})).status, 401); - const signedIn = await mine("login", {username: "ann", password: "Password01"}); + assert.strictEqual((await mine("login", {username: "Nobody", password: "KettlePass01"})).status, 401); + const signedIn = await mine("login", {username: "ann", password: "KettlePass01"}); assert.strictEqual(signedIn.status, 200); assert.match(signedIn.cookie, /^ajc_account=[0-9a-f]{48}$/); const ann = signedIn.cookie; @@ -67,8 +67,8 @@ const run = async () => { assert.deepStrictEqual(me.history.map(login => [login.via, login.ok]), [["web", true], ["web", false]]); // --- parts of the game switched off - const {client: a, roomId} = await arrive("Ann", "Password01"); - const {client: b} = await arrive("Ben", "Password01"); + const {client: a, roomId} = await arrive("Ann", "KettlePass01"); + const {client: b} = await arrive("Ben", "KettlePass01"); await a.untilXt("ac"); const set = async (feature, on) => assert.strictEqual((await mine("act", {action: "feature", feature, on}, ann)).status, 200); assert.strictEqual((await mine("act", {action: "feature", feature: "flying", on: false}, ann)).status, 400); @@ -144,7 +144,7 @@ const run = async () => { } b.xt("ts", roomId, 0, 1, 0, benHas[9]); // ben puts his scarf up for trade, in the game await b.untilXt("tl"); - const benPageCookie = (await mine("login", {username: "Ben", password: "Password01"})).cookie; + const benPageCookie = (await mine("login", {username: "Ben", password: "KettlePass01"})).cookie; const tradable = (await mine("tradable?of=ben", undefined, ann)).data; assert.deepStrictEqual([tradable.found, tradable.theirs.map(item => item.name), tradable.mine.map(item => item.name)], [true, [scarfName], [hatName]]); assert.strictEqual((await mine("act", {action: "offer", to: "Ben", wanted: tradable.theirs[0], offered: []}, ann)).status, 400); @@ -182,27 +182,27 @@ const run = async () => { assert.strictEqual((await panel("support", {action: "approve", id: waiting.names[0].id}, admin)).status, 200); assert.strictEqual((await panel("support", {action: "approve", id: waiting.names[0].id}, admin)).status, 400); // only once assert.strictEqual((await mine("me", undefined, ann)).status, 401); // renamed: sign in again, with the new name - assert.strictEqual((await authenticate("Ann", "Password01")).status, 401); - const annabel = (await mine("login", {username: "Annabel", password: "Password01"})).cookie; + assert.strictEqual((await authenticate("Ann", "KettlePass01")).status, 401); + const annabel = (await mine("login", {username: "Annabel", password: "KettlePass01"})).cookie; me = (await mine("me", undefined, annabel)).data; assert.deepStrictEqual([me.username, me.nameRequests[0].status, me.feedback[0].handledAt > 0], ["Annabel", "approved", true]); // --- the lock: out of the game, and no way back in until it is undone - const {token} = await arrive("Annabel", "Password01"); + const {token} = await arrive("Annabel", "KettlePass01"); assert.strictEqual((await mine("act", {action: "lock", locked: true}, annabel)).status, 200); - assert.strictEqual((await authenticate("Annabel", "Password01")).status, 401); + assert.strictEqual((await authenticate("Annabel", "KettlePass01")).status, 401); assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: token})).status, 401); // the saved sign-in is gone assert.strictEqual((await panel("accounts", undefined, admin)).data.accounts.find(account => account.username === "Annabel").locked, true); - assert.strictEqual((await mine("login", {username: "Annabel", password: "Password01"})).status, 200); // the page still lets her in + assert.strictEqual((await mine("login", {username: "Annabel", password: "KettlePass01"})).status, 200); // the page still lets her in assert.strictEqual((await mine("act", {action: "lock", locked: false}, annabel)).status, 200); - assert.strictEqual((await authenticate("Annabel", "Password01")).status, 200); + assert.strictEqual((await authenticate("Annabel", "KettlePass01")).status, 200); // --- the password: the old one is asked for, and stops working - assert.strictEqual((await mine("act", {action: "password", current: "wrong", password: "Password02"}, annabel)).status, 400); - assert.strictEqual((await mine("act", {action: "password", current: "Password01", password: "short"}, annabel)).status, 400); - assert.strictEqual((await mine("act", {action: "password", current: "Password01", password: "Password02"}, annabel)).status, 200); - assert.strictEqual((await authenticate("Annabel", "Password01")).status, 401); - assert.strictEqual((await authenticate("Annabel", "Password02")).status, 200); + assert.strictEqual((await mine("act", {action: "password", current: "wrong", password: "KettlePass02"}, annabel)).status, 400); + assert.strictEqual((await mine("act", {action: "password", current: "KettlePass01", password: "short"}, annabel)).status, 400); + assert.strictEqual((await mine("act", {action: "password", current: "KettlePass01", password: "KettlePass02"}, annabel)).status, 200); + assert.strictEqual((await authenticate("Annabel", "KettlePass01")).status, 401); + assert.strictEqual((await authenticate("Annabel", "KettlePass02")).status, 200); me = (await mine("me", undefined, annabel)).data; assert.ok(me.history.some(login => login.via === "launcher" && !login.ok) && me.history.some(login => login.via === "game" && login.ok)); @@ -210,16 +210,18 @@ const run = async () => { assert.strictEqual((await mine("me", undefined, annabel)).status, 401); // --- deleting one's own account: the password and the name, then it is gone - const {client: b2} = await arrive("Ben", "Password01"); - const ben = (await mine("login", {username: "Ben", password: "Password01"})).cookie; + const {client: b2} = await arrive("Ben", "KettlePass01"); + const ben = (await mine("login", {username: "Ben", password: "KettlePass01"})).cookie; assert.strictEqual((await mine("act", {action: "delete", current: "wrong", confirm: "Ben"}, ben)).status, 400); - assert.strictEqual((await mine("act", {action: "delete", current: "Password01", confirm: "Annabel"}, ben)).status, 400); - const gone = await mine("act", {action: "delete", current: "Password01", confirm: "ben"}, ben); + assert.strictEqual((await mine("act", {action: "delete", current: "KettlePass01", confirm: "Annabel"}, ben)).status, 400); + const gone = await mine("act", {action: "delete", current: "KettlePass01", confirm: "ben"}, ben); assert.deepStrictEqual([gone.status, gone.data.deleted, gone.data.account], [200, true, undefined]); assert.strictEqual((await mine("me", undefined, ben)).status, 401); - assert.strictEqual((await authenticate("Ben", "Password01")).status, 401); + assert.strictEqual((await authenticate("Ben", "KettlePass01")).status, 401); assert.ok(!(await panel("accounts", undefined, admin)).data.accounts.some(account => account.username === "Ben")); - assert.strictEqual((await register("Ben", 5)).status, 200); // the name is free again + // the name is held for a while (lib/accounts.js, NAME_HELD_DAYS): the + // players Ben met still know him by it. + assert.deepStrictEqual(await (await register("Ben", 5)).json(), {error: "username_taken"}); b2.socket.destroy(); a.socket.destroy(); b.socket.destroy(); diff --git a/test/buddygames.js b/test/buddygames.js index 8f2d679..ce5db67 100644 --- a/test/buddygames.js +++ b/test/buddygames.js @@ -14,7 +14,7 @@ const {postJson} = harness; const GAMES = {ticTacToe: 89, fourGems: 90, rockPaperScissors: 91, shellGame: 92, pairs: 93, scooped: 95, bowling: 98, marbles: 101}; const arrive = async username => { - const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "Password01"})).json(); + const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "KettlePass01"})).json(); const client = new harness.GameClient(GAME_PORT); await client.connect(); const login = await client.logIn(username, auth.auth_token); @@ -28,7 +28,7 @@ const arrive = async username => { const run = async () => { for (const username of ["Ann", "Ben", "Cat"]) { - const response = await fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({username, password: "Password01", avatarType: 1, agreed: true})}); + const response = await fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({username, password: "KettlePass01", avatarType: 1, agreed: true})}); assert.strictEqual(response.status, 200); } const ann = await arrive("Ann"); @@ -301,6 +301,56 @@ const run = async () => { a.socket.destroy(); assert.deepStrictEqual((await b.untilXt("mp")).slice(2), ["101", "1"]); + // --- a room game played together (lib/minigames.js MULTIPLAYER): Gem + // Breaker offers its waiting list, Ben waits in the room, Cat joins, both + // are taken in, and each one's moves reach the other + // (and first, typing: Cat's "..." reaches Ben, said again too soon is not + // passed on, and stopping is) + c.xt("xty", cat.roomId, 1); + assert.deepStrictEqual((await b.untilXt("xty")).slice(2), [cat.id, "1"]); + c.xt("xty", cat.roomId, 1); + c.xt("xty", cat.roomId, 0); + assert.deepStrictEqual((await b.nextXt("xty")).slice(2), [cat.id, "0"]); + + const GEM_BREAKER = 30; + b.xt("mi", ben.roomId, GEM_BREAKER); + const gemInfo = (await b.untilXt("mi")).slice(3); + assert.deepStrictEqual([gemInfo[0], gemInfo[4], gemInfo[5]], ["30", "2", "2"]); + b.xt("mj", ben.roomId, GEM_BREAKER, 1, 0, -1); + assert.deepStrictEqual((await b.untilXt("mj")).slice(1), [ben.roomId, ben.id]); + c.xt("mj", cat.roomId, GEM_BREAKER, 1, 0, -1); + for (const client of [b, c]) { + assert.deepStrictEqual((await client.untilXt("mj")).slice(1), [ben.roomId, ben.id, cat.id]); + } + const gemRoom = (await b.untilXt("rj"))[4]; + for (const client of [b, c]) { + assert.deepStrictEqual((await client.untilXt("mj")).slice(1), [gemRoom, ben.id, cat.id]); + assert.deepStrictEqual((await client.untilXt("ms")).slice(2, 5), ["2", ben.id, cat.id]); + } + b.xt("mm", gemRoom, GEM_BREAKER, "ready"); + c.xt("mm", gemRoom, GEM_BREAKER, "ready"); + for (const client of [b, c]) { + const go = await client.untilXt("mm"); + assert.deepStrictEqual([go[2], ...go.slice(4)], ["start", "2", ben.id, "0", cat.id, "0"]); + } + b.xt("mm", gemRoom, GEM_BREAKER, "pos", "-45"); + assert.deepStrictEqual((await c.nextXt("mm")).slice(2), ["pos", ben.id, "-45"]); + c.xt("mm", gemRoom, GEM_BREAKER, "shoot", "0.5", "-0.8", "210", "40", "3", "1", "300", "0", "5"); + assert.deepStrictEqual((await b.nextXt("mm")).slice(2), ["shoot", "0.5", "-0.8", "210", "40", "3", "1", "300", "0", "5"]); + c.xt("mm", gemRoom, GEM_BREAKER, "pos", ""); + c.xt("mm", gemRoom, GEM_BREAKER, "playerLost", "12345"); + assert.deepStrictEqual((await b.nextXt("mm")).slice(2), ["playerLost", "12345"]); // and not the one with markup + // one leaving: the other is told, as the game expects + c.xt("ml", gemRoom); + assert.deepStrictEqual((await b.untilXt("ml")).slice(1), [gemRoom, cat.id]); + // alone, the start names its one player, whose cannon it is + b.xt("rj", gemRoom, TOWNSHIP, 1, 0, 0); + const back = (await b.untilXt("rj"))[4]; + b.xt("mj", back, GEM_BREAKER, 0, 0, -1); + const soloRoom = (await b.untilXt("mj"))[1]; + b.xt("mm", soloRoom, GEM_BREAKER, "ready"); + assert.deepStrictEqual((await b.untilXt("mm")).slice(4), ["1", ben.id, "0"]); + b.socket.destroy(); c.socket.destroy(); }; diff --git a/test/features.js b/test/features.js index 65a5b84..9d87ecc 100644 --- a/test/features.js +++ b/test/features.js @@ -45,8 +45,8 @@ const wall = async body => (await postJson(`${BASE}/wall`, body)).json(); const run = async () => { const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})}); - for (const username of ["Ann", "Ben", "Cat"]) { - assert.strictEqual((await registerJson({username, password: "Password01"})).status, 200); + for (const username of ["Ann", "Ben", "Cat", "Scout"]) { + assert.strictEqual((await registerJson({username, password: "KettlePass01"})).status, 200); } // --- the admin panel's message of the day reaches a player once their first room has loaded @@ -62,7 +62,7 @@ const run = async () => { assert.strictEqual((await panel("motd", {text: "Welcome to the test server"}, admin)).status, 200); assert.strictEqual((await panel("messages", undefined, admin)).data.motd, "Welcome to the test server"); - const {client: a, login: annLogin, roomId} = await arrive("Ann", "Password01"); + const {client: a, login: annLogin, roomId} = await arrive("Ann", "KettlePass01"); // "ua": the text sits where a room id usually does, then 1 = system message. assert.deepStrictEqual((await a.untilXt("ua")).slice(1), ["Welcome to the test server", "1"]); assert.strictEqual((await panel("motd", {text: ""}, admin)).status, 200); @@ -81,10 +81,34 @@ const run = async () => { a.xt("pad", roomId, "Ann"); assert.deepStrictEqual((await a.nextXt("pad")).slice(2), ["1", "1", String(annLogin.params.usableAdoptAPetDefs[0].defId), String(annLogin.params.usableAdoptAPetDefs[0].invId)]); - const {client: b, login: benLogin} = await arrive("Ben", "Password01"); + const {client: b, login: benLogin} = await arrive("Ben", "KettlePass01"); await a.untilXt("ac"); await a.nextXt("il"); + // the shop's name and stalls come from its room file (lib/roominfo.js), + // read the first time anyone goes in; until then the name is made from its + // path. a scout goes in first and comes back until the file has been read, + // so that what follows does not depend on what an earlier run left in the + // cache. (the scout never enters the township, so a and b see nothing.) + const scoutAuth = await (await postJson(`${BASE}/authenticate`, {username: "Scout", password: "KettlePass01"})).json(); + const scout = new harness.GameClient(GAME_PORT); + await scout.connect(); + assert.strictEqual((await scout.logIn("Scout", scoutAuth.auth_token)).status, "1"); + let scoutRoom = 1; + for (let tries = 0; ; tries++) { + scout.xt("rj", scoutRoom, "jamaa_township.clothes_shop#1", 1, 0, 0); + const there = await scout.untilXt("rj"); + if (there[14] === "Jam Mart Clothing") { + break; + } + assert.ok(tries < 40, `the shop's room file was never read (still "${there[14]}")`); + await new Promise(resolve => setTimeout(resolve, 500)); + scout.xt("rj", there[4], "sarepia.room_main#1", 1, 0, 0); + scoutRoom = (await scout.untilXt("rj"))[4]; + } + scout.socket.destroy(); + await new Promise(resolve => setTimeout(resolve, 300)); // gone before Ben walks in + // --- a shop's title is its room's name, as the id of the string that says so b.xt("rj", roomId, "jamaa_township.clothes_shop#1", 1, 0, 0); const shopRoom = await b.untilXt("rj"); @@ -176,7 +200,7 @@ const run = async () => { // --- name tags: the colour and badge go with a colour change, reach the room, and stay a.xt("gl", roomId, 110); const badges = await a.nextXt("gl"); - assert.deepStrictEqual([badges[3], badges[8], badges[9], badges[70]], ["1049", "75", "1", "62"]); // every badge, in id order: the game's 62 and the thirteen the admin gives + assert.deepStrictEqual([badges[3], badges[8], badges[9], badges[70]], ["1049", "76", "1", "62"]); // every badge, in id order: the game's 62 and the fourteen the admin gives (verified among them) const tag = 6 | 11 << 8; // colour 6, the twelfth badge a.xt("ap", roomId, 1, 2, 3, tag); assert.deepStrictEqual((await a.nextXt("ap")).slice(2), ["1"]); @@ -389,7 +413,10 @@ const run = async () => { assert.deepStrictEqual([sent[2], sent[7], sent[8], sent[9]], ["2", "0", "1", hat]); assert.deepStrictEqual((await a.nextXt("es")).slice(2), ["1"]); const pushed = await b.untilXt("ep"); - assert.deepStrictEqual(pushed.slice(3, 10), ["Ann", cards[9], stamps[9], "0", "A hat for you!", "1", shop[9]]); + // a clothing gift goes by the id of its picture (the def's layerDefId, + // lib/ecards.js giftId), not the item's + assert.deepStrictEqual(pushed.slice(3, 9), ["Ann", cards[9], stamps[9], "0", "A hat for you!", "1"]); + assert.ok(Number(pushed[9]) > 0); b.xt("el", own[4], 0); const inbox = await b.nextXt("el"); assert.deepStrictEqual([inbox[2], inbox.length], ["1", 3 + 17]); @@ -408,18 +435,9 @@ const run = async () => { b.xt("ei", own[4], 0); await b.nextXt("ei"); - // A secret valentine: the receiver is not told who sent it, the server knows. + // secret valentines are off (lib/ecards.js): one asked for is refused a.xt("es", own[4], "Ben", cards[9], stamps[9], 2, "GUESS WHO", 0, 0, 1); - assert.deepStrictEqual((await a.nextXt("es")).slice(2), ["1"]); - const valentine = await b.nextXt("ep"); - assert.deepStrictEqual([valentine[3], valentine[7], valentine[18]], ["", "GUESS WHO", "1"]); // no name; special type 1 - b.xt("fr", own[4], "Secret Valentine", 14); // reported under the name the game shows - assert.deepStrictEqual((await b.nextXt("fr")).slice(2), ["1"]); - const aboutValentine = (await panel("reports", undefined, admin)).data.reports; - assert.deepStrictEqual([aboutValentine[0].reporter, aboutValentine[0].target, aboutValentine[0].reason], ["Ben", "Ann", "Inappropriate Jam-A-Gram"]); - await panel("report", {id: aboutValentine[0].id}, admin); - b.xt("ed", own[4], valentine[2]); - await b.nextXt("ed"); + assert.deepStrictEqual((await a.nextXt("es")).slice(2), ["0"]); // --- Jammer Walls: the wallpapers a wall cannot be drawn without, and their buttons a.xt("gl", own[4], 314); @@ -461,6 +479,14 @@ const run = async () => { assert.deepStrictEqual((await b.nextXt("wps")).slice(2), ["1"]); const mine = await wall({cmd: "GET", t: ownToken}); assert.deepStrictEqual([mine.p.bg, mine.p.tag, mine.p.visits, mine.r.length], ["7", "hello there", 1, 1]); // visits are not the owner's to set + // the photo booth picture: its animal, its pet and what it wears, kept + const photo = {avatar: {id: 4, color1: 1463028479, color2: 603979776, color3: 83885823, eyes: 4, pattern: 25}, bgid: 3, + pet: {ts: 1792133948, lbits: 25, uBits: 0, eBits: 0}, items: [{id: 101, color: 1463028479}, {id: 202, color: 0}]}; + b.xt("wps", own[4], JSON.stringify({pb: photo})); + assert.deepStrictEqual((await b.nextXt("wps")).slice(2), ["1"]); + assert.deepStrictEqual((await wall({cmd: "GET", t: ownToken})).p.pb, photo); + b.xt("wps", own[4], JSON.stringify({pb: {avatar: {deep: {deeper: 1}}}})); // but no deeper than that + assert.deepStrictEqual((await b.nextXt("wps")).slice(2), ["0"]); assert.deepStrictEqual(await wall({cmd: "CLW", t: token[3]}), {s: false}); // only the owner clears a wall assert.deepStrictEqual(await wall({cmd: "DEL", t: ownToken, x: put.x}), {s: true}); assert.strictEqual((await wall({cmd: "GET", t: ownToken})).r.length, 0); @@ -488,7 +514,7 @@ const run = async () => { assert.strictEqual((await panel("overview", undefined, admin)).data.stats.reports, 1); assert.strictEqual((await panel("report", {id: waiting.reports[0].id}, admin)).status, 200); assert.strictEqual((await panel("reports", undefined, admin)).data.open, 0); - assert.strictEqual((await panel("reports?handled=1", undefined, admin)).data.reports.length, 2); // this one and the valentine + assert.strictEqual((await panel("reports?handled=1", undefined, admin)).data.reports.length, 1); // this one (secret valentines, reported before, are off) // --- blocking: no chat from them, out of my party and my den, and out of sight if I say so a.xt("bb", own[4], "Ben"); diff --git a/test/harness.js b/test/harness.js index efa3128..e802849 100644 --- a/test/harness.js +++ b/test/harness.js @@ -101,6 +101,12 @@ class GameClient { this.varUpdates.push(fields); continue; } + // the chat filter settings ("xfl", after every login), the one-time + // question which filter to use ("xfa", on the first room) and the + // buddy list with when each was last seen ("bl", "xls": at login) come unasked. + if ((fields[0] === "xfl" || fields[0] === "xfa" || fields[0] === "bl" || fields[0] === "xls") && cmd !== fields[0]) { + continue; + } if (this.unasked(fields)) { continue; } @@ -148,8 +154,10 @@ const postJson = (url, body) => fetch(url, { // starts a server on the given ports with an empty database, runs `run` // against it, and prints `name` passed or the server's output on failure. -const withServer = async (name, httpPort, gamePort, run) => { - const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-")); +// with `dataDir` it uses that database instead, and leaves it there (for a +// test of what is still there after a restart). +const withServer = async (name, httpPort, gamePort, run, {dataDir: keptDir = null} = {}) => { + const dataDir = keptDir || fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-")); const server = spawn(process.execPath, [path.join(__dirname, "..", "server.js")], { env: {...process.env, AJ_HTTP_PORT: httpPort, AJ_GAME_PORT: gamePort, AJ_DATA_DIR: dataDir, AJ_QUIET: "1", // everyone arrives in the township, as the tests expect @@ -177,8 +185,14 @@ const withServer = async (name, httpPort, gamePort, run) => { throw err; } finally { + // on Windows the database stays locked until the process has gone, so + // wait for it before throwing its files away. + const exited = server.exitCode !== null ? Promise.resolve() : new Promise(resolve => server.once("exit", resolve)); server.kill(); - fs.rmSync(dataDir, {recursive: true, force: true}); + await exited; + if (!keptDir) { + fs.rmSync(dataDir, {recursive: true, force: true, maxRetries: 10, retryDelay: 200}); + } } }; diff --git a/test/items.js b/test/items.js new file mode 100644 index 0000000..5e5b659 --- /dev/null +++ b/test/items.js @@ -0,0 +1,509 @@ +"use strict"; + +// end to end: items the staff make while the server runs +// (lib/customitems.js), from the moderator panel and in the game: games +// already playing are sent them, the packs have them, the shop sells them, +// and they are still there after a restart. + +const assert = require("assert"); +const crypto = require("crypto"); +const fs = require("fs"); +const os = require("os"); +const path = require("path"); +const zlib = require("zlib"); +const harness = require("./harness.js"); +const {decode} = require("../lib/amf3.js"); +const cdn = require("../lib/cdn.js"); + +const HTTP_PORT = 18093; +const GAME_PORT = 19352; +const BASE = `http://127.0.0.1:${HTTP_PORT}`; +const TOWNSHIP = "jamaa_township.room_main#1"; +const ODD_CLOTHING_SHOP = 666; +const ODD_DEN_SHOP = 396; +const {postJson} = harness; + +// the authenticator app's side of 2FA (lib/totp.js), as in test/staff.js. +const STEP = 30; +const base32Decode = text => { + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + const bits = text.replace(/=+$/, "").toUpperCase().split("").map(c => alphabet.indexOf(c).toString(2).padStart(5, "0")).join(""); + const bytes = []; + for (let i = 0; i + 8 <= bits.length; i += 8) { + bytes.push(parseInt(bits.slice(i, i + 8), 2)); + } + return Buffer.from(bytes); +}; +const codeAt = (secret, step) => { + const counter = Buffer.alloc(8); + counter.writeBigUInt64BE(BigInt(step)); + const mac = crypto.createHmac("sha1", base32Decode(secret)).update(counter).digest(); + const offset = mac[mac.length - 1] & 0x0F; + return String((mac.readUInt32BE(offset) & 0x7FFFFFFF) % 1000000).padStart(6, "0"); +}; +const stepNow = () => Math.floor(Date.now() / 1000 / STEP); +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +const waitForStep = async step => { + while (stepNow() < step) { + await sleep(250); + } +}; + +const webSession = () => { + let cookie = ""; + return async (urlPath, body) => { + const headers = {cookie}; + const options = body === undefined ? {headers} : {method: "POST", headers: {...headers, "Content-Type": "application/json"}, body: JSON.stringify(body)}; + const res = await fetch(`${BASE}${urlPath}`, options); + const set = res.headers.get("set-cookie"); + if (set) { + cookie = set.split(";")[0]; + } + return {status: res.status, data: await res.json().catch(() => ({}))}; + }; +}; + +const say = (client, roomId, text) => + client.send(``); + +// `onLogin(client)` runs before the room is joined, for what the server +// sends with the login (joining skips everything else on the way). +const arrive = async (username, password, totp, onLogin = async () => {}) => { + const res = await postJson(`${BASE}/authenticate`, {username, password, ...(totp ? {totp} : {})}); + const auth = await res.json(); + assert.strictEqual(res.status, 200, `${username} could not sign in: ${JSON.stringify(auth)}`); + const client = new harness.GameClient(GAME_PORT); + await client.connect(); + const login = await client.logIn(username, auth.auth_token); + assert.strictEqual(login.status, "1"); + await onLogin(client); + client.xt("rj", 1, TOWNSHIP, 1, 0, 0); + const rj = await client.untilXt("rj"); + await client.untilXt("rp"); + return {client, roomId: rj[4], token: auth.auth_token}; +}; + +// a pack as the clients get it. +const pack = async id => Object.values(decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${cdn.hashedPath(`defPacks/${id}`)}`)).arrayBuffer())))); +const strings = async () => decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${cdn.hashedPath("defPacks/10230")}`)).arrayBuffer()))); +const byId = (rows, id) => rows.find(row => String(row.id) === String(id)); + +// "xdi" [.., .., kind, rows as JSON], the next one of `kind`. +const untilDefs = async (client, kind) => { + for (;;) { + const fields = await client.untilXt("xdi"); + if (fields[2] === kind) { + return JSON.parse(fields[3]); + } + } +}; +const nextBox = async client => (await client.untilXt("xtl"))[2]; +const shopList = async (client, roomId, shop) => { + client.xt("gl", roomId, shop); + return (await client.untilXt("gl")).slice(9); +}; + +const people = {Dev: "KettlePass21", Hal: "KettlePass22", Pat: "KettlePass23", Lou: "KettlePass24"}; +const secret = {}; +let usedStep = 0; +let made = {}; + +const first = async () => { + const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})}); + for (const [username, password] of Object.entries(people)) { + assert.strictEqual((await registerJson({username, password})).status, 200); + } + const admin = webSession(); + assert.strictEqual((await admin("/admin/api/setup", {password: "AdminPass99!"})).status, 200); + assert.strictEqual((await admin("/admin/api/login", {password: "AdminPass99!"})).status, 200); + for (const username of ["Dev", "Hal"]) { + const page = webSession(); + assert.strictEqual((await page("/account/api/login", {username, password: people[username]})).status, 200); + secret[username] = (await page("/account/api/act", {action: "twoStepStart", current: people[username]})).data.setup.secret; + usedStep = Math.max(usedStep, stepNow()); + assert.ok((await page("/account/api/act", {action: "twoStepConfirm", code: codeAt(secret[username], stepNow())})).data.ok); + } + assert.match((await admin("/admin/api/account", {username: "Dev", action: "role", role: "developer"})).data.ok, /developer/); + assert.match((await admin("/admin/api/account", {username: "Hal", action: "role", role: "helper"})).data.ok, /helper/); + + // a game started before anything is made + const pat = await arrive("Pat", people.Pat); + + // --- the panel: a developer makes items, and sees no players + usedStep++; + await waitForStep(usedStep); + const dev = webSession(); + assert.strictEqual((await dev("/mod/api/login", {username: "Dev", password: people.Dev, code: codeAt(secret.Dev, usedStep)})).status, 200); + const me = (await dev("/mod/api/me")).data; + assert.strictEqual(me.role, "developer"); + assert.ok(me.permissions.includes("items.create") && !me.permissions.includes("player.view")); + for (const page of ["/mod/api/players", "/mod/api/chat", "/mod/api/reports", "/mod/api/overview"]) { + assert.strictEqual((await dev(page)).status, 403, page); + } + assert.deepStrictEqual((await dev("/mod/api/items")).data.items, []); + + // something to make them from: a clothing piece with several colours, and the bean bag chair + const clothing = await pack(1000); + const base = clothing.find(row => row.type === "1" && String(row.colors).split(",").length >= 3); + const looked = (await dev(`/mod/api/items/base?kind=clothing&id=${base.id}`)).data; + assert.strictEqual(looked.art, Number(base.layerDefId)); + assert.strictEqual(looked.colors.length, String(base.colors).split(",").length); + const bodyPart = clothing.find(row => row.type === "0"); + assert.strictEqual((await dev(`/mod/api/items/base?kind=clothing&id=${bodyPart.id}`)).status, 404); + + // bad requests + const make = fields => dev("/mod/api/items", {action: "create", kind: "clothing", base: base.id, name: "Test Crown", cost: 25, ...fields}); + assert.match((await make({name: ""})).data.error, /name/); + assert.match((await make({name: "hi"})).data.error, /name/); + assert.match((await make({cost: -1})).data.error, /price/); + assert.match((await make({base: bodyPart.id})).data.error, /body part/); + assert.match((await make({base: 999999})).data.error, /No clothing/); + assert.match((await make({colors: []})).data.error, /colours/); + + // made: Pat's game is told at once + const colours = looked.colors.slice(0, 2); + const crown = await make({colors: colours}); + assert.match(crown.data.ok, /^Test Crown \(clothing 50000\) made\.$/); + const [row] = await untilDefs(pat.client, "clothing"); + assert.deepStrictEqual([row.id, row.name, row.layerDefId, row.layerId, row.colors, row.titleStrId], + ["50000", "Test Crown", base.layerDefId, base.layerId, colours.join(","), "9100000"]); + + // the packs a new game fetches have it, and its name + const crownRow = byId(await pack(1000), 50000); + assert.strictEqual(crownRow.layerDefId, base.layerDefId); + assert.strictEqual(crownRow.avatarUseFlags, "9007199254740991"); // any animal, like all clothing here + assert.strictEqual((await strings())[9100000], "Test Crown"); + + // first in the shop of oddities, and Pat can buy it in a colour it has + assert.strictEqual((await shopList(pat.client, pat.roomId, ODD_CLOTHING_SHOP))[0], "50000"); + pat.client.xt("ib", pat.roomId, ODD_CLOTHING_SHOP, 1, 50000, 2, 0); + assert.strictEqual((await pat.client.untilXt("ib"))[2], "0"); // a third colour it was not given + pat.client.xt("ib", pat.roomId, ODD_CLOTHING_SHOP, 1, 50000, 1, 0); + const bought = await pat.client.untilXt("il"); + assert.ok(bought.includes("50000")); + assert.strictEqual((await pat.client.untilXt("ib"))[2], "1"); + + // a den item, from the bean bag chair + const chair = await dev("/mod/api/items", {action: "create", kind: "den", base: 1, name: "Test Chair", cost: 10}); + assert.match(chair.data.ok, /^Test Chair \(den item 50000\) made\.$/); + const [chairRow] = await untilDefs(pat.client, "den"); + assert.deepStrictEqual([chairRow.id, chairRow.abbrName, chairRow.name, chairRow.nameStrId], ["50000", "BeanBagChair", "Test Chair", "9200000"]); + assert.strictEqual((await shopList(pat.client, pat.roomId, ODD_DEN_SHOP))[0], "50000"); + assert.strictEqual(byId(await pack(1030), 50000).abbrName, "BeanBagChair"); + + // the item finder has them + const found = await (await fetch(`${BASE}/api/search?kind=all&q=50000`)).json(); + assert.deepStrictEqual(found.results.filter(entry => entry.id === 50000).map(entry => `${entry.kind} ${entry.name}`).sort(), ["clothing Test Crown", "den Test Chair"]); + + // changed: renamed and taken off sale, and Pat is told the new name + assert.match((await dev("/mod/api/items", {action: "update", kind: "clothing", id: 50000, name: "Gold Crown", inShop: false})).data.ok, /Gold Crown .* changed/); + assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].name, "Gold Crown"); + assert.ok(!(await shopList(pat.client, pat.roomId, ODD_CLOTHING_SHOP)).includes("50000")); + assert.strictEqual((await strings())[9100000], "Gold Crown"); + + // --- in the game: !item, for whoever may make items + usedStep++; + await waitForStep(usedStep); + // a game logging in is sent every item made so far + let atLogin = null; + const devGame = await arrive("Dev", people.Dev, codeAt(secret.Dev, usedStep), async client => { + atLogin = await untilDefs(client, "clothing"); + }); + assert.deepStrictEqual(atLogin.map(entry => entry.name), ["Gold Crown"]); + say(devGame.client, devGame.roomId, `!item clothing ${base.id} Quick Hat`); + assert.strictEqual(await nextBox(devGame.client), "Made Quick Hat, clothing 50001. It is in the item finder now."); + assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].name, "Quick Hat"); + say(devGame.client, devGame.roomId, "!item list"); + assert.match(await nextBox(devGame.client), /^Latest items made: 50001 Quick Hat \(clothing\); 50000 Test Chair \(den\); 50000 Gold Crown \(clothing, off sale\)$/); + say(devGame.client, devGame.roomId, "!item hat 12 x"); + assert.match(await nextBox(devGame.client), /^Use: !item/); + + // a helper may not: it is chat (another account: the same step will do) + const hal = await arrive("Hal", people.Hal, codeAt(secret.Hal, usedStep)); + say(hal.client, hal.roomId, `!item clothing ${base.id} Nope`); + for (;;) { + const line = await pat.client.untilXt("uc"); + if (line[3] === `!item clothing ${base.id} Nope`) { + break; + } + } + assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3); + + // --- locked out of the item finder (lib/itemcontrol.js): players do not + // find it or take it; the owner here, and staff who may lock, still do + const searchAs = async (q, who) => (await (await fetch(`${BASE}/api/search?kind=clothing&q=${q}${who ? `&username=${who.name}&token=${who.token}` : ""}`)).json()).results; + // (as the item finder page and the client send it: no Origin of another site) + const giveAs = (body, token) => fetch(`${BASE}/api/give`, {method: "POST", headers: {"Content-Type": "application/json"}, + body: JSON.stringify({...body, ...(token ? {token} : {})})}); + const patAs = {name: "Pat", token: pat.token}; + assert.ok((await searchAs(50001, patAs)).some(entry => entry.id === 50001)); + assert.match((await dev("/mod/api/items", {action: "lock", kind: "clothing", id: 50001})).data.ok, /^Quick Hat \(clothing 50001\) is locked out of the item finder\.$/); + assert.match((await dev("/mod/api/items", {action: "lock", kind: "clothing", id: 50001})).data.error, /already locked/); + assert.ok(!(await searchAs(50001, patAs)).some(entry => entry.id === 50001)); + const refused = await giveAs({username: "Pat", kind: "clothing", id: 50001}, pat.token); + assert.deepStrictEqual([refused.status, (await refused.json()).error], [403, "That item is locked out of the item finder."]); + assert.deepStrictEqual((await searchAs(50001)).filter(entry => entry.id === 50001).map(entry => [entry.name, entry.locked]), [["Quick Hat (locked)", true]]); + assert.strictEqual((await searchAs(50001, {name: "Dev", token: devGame.token})).find(entry => entry.id === 50001).name, "Quick Hat (locked)"); + assert.deepStrictEqual((await dev("/mod/api/items")).data.locked, [{kind: "clothing", id: 50001, name: "Quick Hat"}]); + // the dashboards' lock finds it by name, marked locked, with the count + const findLock = (await dev("/mod/api/items/find?q=quick%20hat&kind=clothing")).data; + assert.deepStrictEqual([findLock.lockedCount, findLock.results.find(entry => entry.id === 50001)], + [1, {kind: "clothing", id: 50001, cost: findLock.results.find(entry => entry.id === 50001).cost, name: "Quick Hat", locked: true, custom: true}]); + say(devGame.client, devGame.roomId, "!locked"); + assert.strictEqual(await nextBox(devGame.client), "Locked out of the item finder: clothing 50001 Quick Hat"); + + // --- taken from a player: every one of it, their game told + assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50001, colorIndex: 0})).status, 200); // the owner, here + assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50001, colorIndex: 0})).status, 200); + say(devGame.client, devGame.roomId, "!take Pat clothing 50001"); + assert.strictEqual(await nextBox(devGame.client), "Took 2 of Quick Hat (clothing 50001) from Pat."); + for (;;) { + const changed = await pat.client.untilXt("il"); + if (changed[2] === "2" && changed[8] === "2") { // two removed + break; + } + } + say(devGame.client, devGame.roomId, "!take Pat clothing 50001"); + assert.strictEqual(await nextBox(devGame.client), "Pat has no Quick Hat (clothing 50001)."); + assert.strictEqual((await giveAs({username: "Pat", kind: "den", id: 50000})).status, 200); + assert.match((await dev("/mod/api/items", {action: "take", username: "Pat", kind: "den", id: 50000})).data.ok, /^Took 1 of Test Chair \(den item 50000\) from Pat\.$/); + assert.match((await dev("/mod/api/items", {action: "unlock", kind: "clothing", id: 50001})).data.ok, /back in the item finder/); + assert.ok((await searchAs(50001, patAs)).some(entry => entry.id === 50001)); + + // --- a custom item deleted: out of the game and every inventory + say(devGame.client, devGame.roomId, `!item clothing ${base.id} Doomed Hat`); + assert.strictEqual(await nextBox(devGame.client), "Made Doomed Hat, clothing 50002. It is in the item finder now."); + assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50002, colorIndex: 0})).status, 200); + assert.match((await dev("/mod/api/items", {action: "delete", kind: "clothing", id: 50002})).data.ok, /^Deleted Doomed Hat \(clothing 50002\), and took 1 from players\.$/); + assert.ok(!(await searchAs(50002)).some(entry => entry.id === 50002)); + assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50002, colorIndex: 0})).status, 400); + assert.ok(!byId(await pack(1000), 50002)); + assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3); + + // --- a player's own items (lib/playeritems.js, the client's Item Maker): + // free, given to them, found by them only, at most five a day + const maker = async (...params) => { + pat.client.xt("xcm", pat.roomId, ...params); + const answer = await pat.client.untilXt("xcm"); + return {ok: answer[2] === "1", said: answer[3], today: Number(answer[4]), inAll: Number(answer[5]), mine: JSON.parse(answer[6])}; + }; + assert.deepStrictEqual(await maker("info"), {ok: true, said: "", today: 5, inAll: 20, mine: []}); + const own = await maker("make", "clothing", base.id, "Pat Hat"); + assert.deepStrictEqual([own.ok, own.said, own.today, own.inAll], [true, "Made Pat Hat. It is in your clothing now.", 4, 19]); + const patHat = own.mine[0]; + assert.deepStrictEqual([patHat.kind, patHat.name, patHat.base], ["clothing", "Pat Hat", Number(base.id)]); + assert.ok((await searchAs(patHat.id, patAs)).some(entry => entry.id === patHat.id)); + const halAs = {name: "Hal", token: hal.token}; + assert.ok(!(await searchAs(patHat.id, halAs)).some(entry => entry.id === patHat.id)); + assert.strictEqual((await giveAs({username: "Hal", kind: "clothing", id: patHat.id, colorIndex: 0}, hal.token)).status, 403); + assert.ok((await searchAs(patHat.id, {name: "Dev", token: devGame.token})).some(entry => entry.id === patHat.id)); // staff who make items + assert.match((await maker("make", "clothing", base.id, "Admin Hat")).said, /not allowed/); + assert.match((await maker("make", "clothing", bodyPart.id, "Body")).said, /cannot be made into one of your own/); + // the base list offers only what can be copied + assert.ok(!(await (await fetch(`${BASE}/api/search?base=1&kind=clothing&q=${bodyPart.id}`)).json()).results.some(entry => entry.id === bodyPart.id)); + for (let count = 2; count <= 5; count++) { + assert.ok((await maker("make", "den", 1, `Pat Chair ${count}`)).ok); + } + const full = await maker("make", "den", 1, "One Too Many"); + assert.deepStrictEqual([full.ok, full.today], [false, 0]); + assert.match(full.said, /made 5 items today/); + // --- its own picture (lib/itemart.js): checked and cleaned, served, and + // every game told; only by its maker or staff who make items + const crc32 = buf => { + let c = ~0; + for (const byte of buf) { + c ^= byte; + for (let k = 0; k < 8; k++) { + c = (c >>> 1) ^ (0xEDB88320 & -(c & 1)); + } + } + return (~c) >>> 0; + }; + const chunk = (type, data) => { + const head = Buffer.alloc(8); + head.writeUInt32BE(data.length); + head.write(type, 4, "latin1"); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data]))); + return Buffer.concat([head, data, crc]); + }; + const png = (side, extra = []) => { + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(side, 0); + ihdr.writeUInt32BE(side, 4); + ihdr[8] = 8; + ihdr[9] = 2; + const raw = Buffer.alloc((side * 3 + 1) * side, 0x7F); + return Buffer.concat([Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]), chunk("IHDR", ihdr), ...extra, + chunk("IDAT", zlib.deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]); + }; + const upload = (who, entry, body, extra = "") => fetch(`${BASE}/api/itemart?kind=${entry.kind}&id=${entry.id}&token=${who.token}${extra}`, + {method: "POST", headers: {"Content-Type": "application/octet-stream"}, body}).then(response => response.json()); + const hatEntry = (await maker("info")).mine.find(entry => entry.name === "Pat Hat"); + // by default a player's picture waits for a moderator, even with items + // let in at once: nobody else is shown it, not even by its address + assert.match((await upload(pat, hatEntry, png(30))).ok, /waiting for a moderator/); + assert.strictEqual((await maker("info")).mine.find(entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id).art, ""); + assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404); + const pendingUrl = (await admin("/admin/api/review")).data.waiting.find(entry => entry.id === hatEntry.id).artUrl; + assert.match(pendingUrl, /^\/admin\/api\/itemart\?kind=clothing&id=\d+&v=p[0-9a-f]{12}$/); + assert.strictEqual((await admin(pendingUrl)).status, 200); + assert.strictEqual((await fetch(`${BASE}${pendingUrl}`)).status, 404); // signed in to nothing + assert.match((await admin("/admin/api/review", {kind: "clothing", id: hatEntry.id, approve: true})).data.ok, /picture is shown now/); + assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 200); + while (!(await untilDefs(pat.client, "clothing")).some(row => row.art)) { + // every game is told of it waiting (no picture), then of it shown + } + // the rest of these, shown at once (the admin's switch) + assert.strictEqual((await admin("/admin/api/item-switches", {artApproval: false})).status, 200); + assert.strictEqual((await admin("/admin/api/review")).data.artApproval, false); + assert.match((await upload(pat, hatEntry, png(32, [chunk("tEXt", Buffer.from("Author\x00Pat at home"))]))).ok, /new picture/); + const told = (await untilDefs(pat.client, "clothing")).map(row => [row.id, row.art]); + const sameItem = entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id; + const withArt = (await maker("info")).mine.find(sameItem); + assert.match(withArt.art, /^p[0-9a-f]{12}$/); + assert.deepStrictEqual(told, [[String(hatEntry.id), withArt.art]]); + const served = await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${withArt.art}`); + assert.deepStrictEqual([served.status, served.headers.get("content-type"), served.headers.get("x-content-type-options")], [200, "image/png", "nosniff"]); + const bytes = Buffer.from(await served.arrayBuffer()); + assert.ok(!bytes.includes(Buffer.from("tEXt")) && !bytes.includes(Buffer.from("Pat at home")), "the text chunk was left in"); + assert.match((await upload(pat, hatEntry, Buffer.from(""))).error, /not a PNG, JPEG, GIF or BMP/); + // a GIF is kept a GIF (without its comment); a BMP is made a PNG + const gif = Buffer.concat([Buffer.from("GIF89a"), Buffer.from([16, 0, 16, 0, 0x80, 0, 0]), Buffer.alloc(6, 0x55), + Buffer.from([0x21, 0xFE, 4]), Buffer.from("Bob!"), Buffer.from([0]), Buffer.from([0x2C, 0, 0, 0, 0, 16, 0, 16, 0, 0, 2, 3, 1, 2, 3, 0, 0x3B])]); + assert.match((await upload(pat, hatEntry, gif)).ok, /new picture/); + const gifArt = (await maker("info")).mine.find(entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id).art; + const gifServed = await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${gifArt}`); + assert.strictEqual(gifServed.headers.get("content-type"), "image/gif"); + assert.ok(!Buffer.from(await gifServed.arrayBuffer()).includes(Buffer.from("Bob!")), "the GIF comment was left in"); + const bmp = Buffer.alloc(54 + 32 * 3 * 32); + bmp.write("BM"); + bmp.writeUInt32LE(bmp.length, 2); + bmp.writeUInt32LE(54, 10); + bmp.writeUInt32LE(40, 14); + bmp.writeInt32LE(32, 18); + bmp.writeInt32LE(32, 22); + bmp.writeUInt16LE(1, 26); + bmp.writeUInt16LE(24, 28); + assert.match((await upload(pat, hatEntry, bmp)).ok, /new picture/); + const bmpArt = (await maker("info")).mine.find(entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id).art; + assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${bmpArt}`)).headers.get("content-type"), "image/png"); + assert.match((await upload(pat, hatEntry, png(600))).error, /512 pixels/); + assert.match((await upload(hal, hatEntry, png(16))).error, /not one of your items/); + assert.match((await fetch(`${BASE}/api/itemart?kind=clothing&id=${hatEntry.id}`, {method: "POST", body: png(16)}).then(r => r.json())).error, /Sign in/); + // a JPEG keeps its picture and loses its EXIF (where a photo was taken) + const segment = (marker, data) => Buffer.concat([Buffer.from([0xFF, marker, (data.length + 2) >> 8, (data.length + 2) & 0xFF]), data]); + const jpeg = Buffer.concat([Buffer.from([0xFF, 0xD8]), segment(0xE0, Buffer.from("JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00", "latin1")), + segment(0xE1, Buffer.from("Exif\x00\x00GPS 51.5N 0.12W", "latin1")), segment(0xC0, Buffer.from([8, 0, 20, 0, 30, 1, 1, 0x11, 0])), + segment(0xDA, Buffer.from([1, 1, 0, 0, 0x3F, 0])), Buffer.from([0x12, 0x34, 0xFF, 0xD9])]); + assert.match((await upload(pat, hatEntry, jpeg)).ok, /new picture/); + const jpegArt = (await maker("info")).mine.find(sameItem).art; + const jpegBytes = Buffer.from(await (await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${jpegArt}`)).arrayBuffer()); + assert.ok(jpegBytes.includes(Buffer.from("JFIF")) && !jpegBytes.includes(Buffer.from("GPS")), "the EXIF was left in"); + assert.match((await upload(pat, hatEntry, Buffer.alloc(0), "&remove=1")).ok, /taken away/); + assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404); + assert.match((await upload(pat, hatEntry, png(24))).ok, /new picture/); // deleted with the item, below + assert.match((await maker("rename", "clothing", hatEntry.id, "Party Hat")).said, /^Renamed it Party Hat\.$/); + // how it is worn: a sticker by default, a texture when its maker says so, every game told + pat.client.xt("xcm", pat.roomId, "look", "clothing", hatEntry.id, "texture"); + assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].artMode, "texture"); + assert.strictEqual((await pat.client.untilXt("xcm"))[2], "1"); // its own answer, after every game was told + const wornAs = await maker("info"); + assert.strictEqual(wornAs.mine.find(entry => entry.kind === "clothing" && entry.id === hatEntry.id).artMode, "texture"); + assert.match((await maker("look", "clothing", hatEntry.id, "melted")).said, /sticker or texture/); + + // deleting: their own only, and gone from everyone + assert.match((await maker("delete", "clothing", 50001)).said, /not one of your items/); + for (const entry of full.mine) { + assert.match((await maker("delete", entry.kind, entry.id)).said, /^Deleted /); + } + assert.deepStrictEqual((await maker("info")).mine, []); + assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404); + assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3); + + // --- the admin's switches: what players make waits for a moderator first, + // out of the game till then; or the Item Maker is off + assert.strictEqual((await admin("/admin/api/item-switches", {enabled: true, approval: true})).status, 200); + const asked = await maker("make", "clothing", base.id, "Waiting Hat"); + assert.match(asked.said, /waiting for a moderator/); + const waitingHat = asked.mine.find(entry => entry.name === "Waiting Hat"); + assert.strictEqual(waitingHat.waiting, "item"); + assert.ok(!(await searchAs(waitingHat.id)).some(entry => entry.id === waitingHat.id)); // not in the game yet + const queue = (await admin("/admin/api/review")).data; + assert.deepStrictEqual([queue.enabled, queue.approval, queue.waiting.map(entry => `${entry.name} ${entry.waiting} ${entry.maker}`)], + [true, true, ["Waiting Hat item Pat"]]); + assert.strictEqual((await dev("/mod/api/review")).status, 403); // a developer approves nothing + assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: true})).data.ok, /in the game, and Pat has one/); + for (;;) { + const changed = await pat.client.untilXt("il"); + if (changed[2] === "2" && changed[10] === String(waitingHat.id)) { // given to Pat + break; + } + } + assert.ok((await searchAs(waitingHat.id, patAs)).some(entry => entry.id === waitingHat.id)); + // a new picture waits too, and is not shown till then + assert.match((await upload(pat, waitingHat, png(20))).ok, /waiting for a moderator/); + assert.strictEqual((await maker("info")).mine.find(entry => entry.id === waitingHat.id && entry.kind === "clothing").waiting, "picture"); + assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: false})).data.ok, + /picture was turned away\. Pat has had 1 of 3 pictures turned away\.$/); + assert.strictEqual((await admin("/admin/api/review")).data.waiting.length, 0); + // the same picture cannot come back; after three turned away, uploads stop + assert.match((await upload(pat, waitingHat, png(20))).error, /turned that picture away before/); + assert.match((await upload(pat, waitingHat, png(21))).ok, /waiting/); + assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: false})).data.ok, /2 of 3/); + assert.match((await upload(pat, waitingHat, png(22))).ok, /waiting/); + assert.match((await admin("/admin/api/review", {action: "takePicture", kind: "clothing", id: waitingHat.id})).data.ok, + /taken away\. That is 3 for Pat: their picture uploads are stopped\.$/); + assert.match((await upload(pat, waitingHat, png(23))).error, /turned off picture uploads/); + assert.deepStrictEqual((await admin("/admin/api/review")).data.stopped, ["Pat"]); + assert.match((await admin("/admin/api/review", {action: "uploads", username: "Pat", blocked: false})).data.ok, /Pat can upload pictures again/); + assert.match((await upload(pat, waitingHat, png(23))).ok, /waiting/); + assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: true})).data.ok, /shown now/); + // off: nothing is made + assert.strictEqual((await admin("/admin/api/item-switches", {enabled: false, approval: false})).status, 200); + assert.match((await maker("make", "clothing", base.id, "No Hat")).said, /turned off/); + assert.strictEqual((await admin("/admin/api/item-switches", {enabled: true})).status, 200); + assert.match((await maker("delete", "clothing", waitingHat.id)).said, /^Deleted /); + + // written down under the maker's name + const log = (await admin("/admin/api/moderators")).data.log.map(entry => `${entry.by} ${entry.action} ${entry.detail}`); + for (const line of ["Dev item made clothing 50000 Test Crown", "Dev item made den 50000 Test Chair", "Dev item changed clothing 50000 Gold Crown", + "Dev item made (in game) clothing 50001 Quick Hat", "Dev item locked clothing 50001", "Dev item taken (in game) clothing 50001 x2", + "Dev item taken den 50000 x1", "Dev item deleted clothing 50002"]) { + assert.ok(log.includes(line), `missing from the log: ${line}\n${log.join("\n")}`); + } + made = {base}; + for (const {client} of [pat, devGame, hal]) { + client.socket.destroy(); + } +}; + +// the same database, a new server: everything is still there. +const second = async () => { + const atLogin = {}; + const lou = await arrive("Lou", people.Lou, null, async client => { + atLogin.clothing = await untilDefs(client, "clothing"); + atLogin.den = await untilDefs(client, "den"); + }); + assert.deepStrictEqual(atLogin.clothing.map(entry => `${entry.id} ${entry.name}`), ["50000 Gold Crown", "50001 Quick Hat"]); + assert.deepStrictEqual(atLogin.den.map(entry => entry.name), ["Test Chair"]); + assert.strictEqual(byId(await pack(1000), 50001).layerDefId, made.base.layerDefId); + assert.strictEqual((await strings())[9100001], "Quick Hat"); + const shop = await shopList(lou.client, lou.roomId, ODD_CLOTHING_SHOP); + assert.ok(shop.includes("50001") && !shop.includes("50000")); + lou.client.socket.destroy(); +}; + +(async () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-")); + try { + await harness.withServer("items test", HTTP_PORT, GAME_PORT, first, {dataDir}); + await harness.withServer("items test (after a restart)", HTTP_PORT, GAME_PORT, second, {dataDir}); + } + finally { + fs.rmSync(dataDir, {recursive: true, force: true, maxRetries: 10, retryDelay: 200}); + } +})().catch(err => { + console.error(err); + process.exit(1); +}); diff --git a/test/qol.js b/test/qol.js index 51545d2..2be6b32 100644 --- a/test/qol.js +++ b/test/qol.js @@ -21,7 +21,7 @@ const told = async client => (await client.untilXt("xtl"))[2]; // logs in and asks for the township, as the game always does first. // returns where the server put them. const arrive = async username => { - const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "Password01"})).json(); + const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "KettlePass01"})).json(); const client = new harness.GameClient(GAME_PORT); await client.connect(); const login = await client.logIn(username, auth.auth_token); @@ -36,7 +36,7 @@ const arrive = async username => { const run = async () => { for (const username of ["Ann", "Ben"]) { const response = await fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, - body: JSON.stringify({username, password: "Password01", avatarType: 1, agreed: true})}); + body: JSON.stringify({username, password: "KettlePass01", avatarType: 1, agreed: true})}); assert.strictEqual(response.status, 200); } let {client: a, login, roomId, room} = await arrive("Ann"); @@ -149,7 +149,7 @@ const run = async () => { assert.strictEqual(await owned(), before + 3); say(a, roomId, "!help"); // gone: the list is at /commands assert.strictEqual((await a.untilXt("uc"))[3], "!help"); - assert.match(await (await fetch(`${BASE}/commands`)).text(), /!outfit save NAME/); + assert.match(await (await fetch(`${BASE}/commands`)).text(), /!outfit save NAME<\/i>/); // the page sets what to type in italics // --- den undo, mail, music say(a, roomId, "!den undo"); @@ -190,7 +190,7 @@ const run = async () => { await new Promise(resolve => setTimeout(resolve, 200)); // --- "start in your own den" (asked for at sign-in): the game asks for the township and is put in the den - const denAuth = await (await postJson(`${BASE}/authenticate`, {username: "Ann", password: "Password01", login_choices: {startInDen: true}})).json(); + const denAuth = await (await postJson(`${BASE}/authenticate`, {username: "Ann", password: "KettlePass01", login_choices: {startInDen: true}})).json(); const home = new harness.GameClient(GAME_PORT); await home.connect(); await home.logIn("Ann", denAuth.auth_token); diff --git a/test/restored.js b/test/restored.js index 8292727..26e84cb 100644 --- a/test/restored.js +++ b/test/restored.js @@ -38,9 +38,9 @@ const byId = (rows, id) => rows.find(row => String(row.id) === String(id)); const run = async () => { const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})}); for (const username of ["Ann", "Ben"]) { - assert.strictEqual((await registerJson({username, password: "Password01"})).status, 200); + assert.strictEqual((await registerJson({username, password: "KettlePass01"})).status, 200); } - const {client: a, roomId} = await arrive("Ann", "Password01"); + const {client: a, roomId} = await arrive("Ann", "KettlePass01"); // --- Epic Dens: twenty names; asking for the den of one leads into its room a.xt("dh", roomId); @@ -147,7 +147,7 @@ const run = async () => { a.xt("di", den); assert.deepStrictEqual((await a.nextXt("di")).slice(13, 24), ["111", "222", "0", "333", "0", "0", "0", "0", "0", hat, "0"]); // A visitor is told what the hat is: its def and colour, then its id. - const {client: b, roomId: benRoom} = await arrive("Ben", "Password01"); + const {client: b, roomId: benRoom} = await arrive("Ben", "KettlePass01"); b.xt("dj", benRoom, "denAnn", 1, -1); const seen = await b.untilXt("ds"); assert.deepStrictEqual(seen.slice(5), [mannequin, "3433", "1", "300", "400", "0", "0", "", "", "-1", "", @@ -177,8 +177,8 @@ const run = async () => { assert.strictEqual((await a.nextXt("di"))[22], "0"); // --- a player who is not in the game: their card still shows who they are - assert.strictEqual((await registerJson({username: "Cat", password: "Password01"})).status, 200); - const {client: c, roomId: catRoom} = await arrive("Cat", "Password01"); + assert.strictEqual((await registerJson({username: "Cat", password: "KettlePass01"})).status, 200); + const {client: c, roomId: catRoom} = await arrive("Cat", "KettlePass01"); c.xt("pc", catRoom, 312, 1, 0, 0, 15386, 15428, 0); // a pet, so there is one to list await c.untilXt("pc"); c.socket.destroy(); @@ -204,7 +204,7 @@ const run = async () => { const stamps = (await b.nextXt("gl")).slice(9); b.xt("es", benRoom, "Cat", cards[0], stamps[0], 0, "see you soon", 0, 0, 0); assert.strictEqual((await b.untilXt("es"))[2], "1"); - const {client: c2, login: catLogin, roomId: catRoom2} = await arrive("Cat", "Password01"); + const {client: c2, login: catLogin, roomId: catRoom2} = await arrive("Cat", "KettlePass01"); assert.strictEqual(catLogin.params.numUnreadECards, 1); assert.deepStrictEqual((await c2.untilXt("ba")).slice(2), ["0", "Ben", "1"]); // asked, now that Cat is here c2.xt("bc", catRoom2, "Ben", 1); diff --git a/test/smoke.js b/test/smoke.js index aee19c0..0c07c20 100644 --- a/test/smoke.js +++ b/test/smoke.js @@ -28,29 +28,29 @@ const run = async () => { // --- registration: the web form's API, and no accounts made by logging in assert.match(await (await fetch(`${BASE}/register`)).text(), /Create an account/); const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})}); - assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Alice", password: "Password01"})).status, 401); - assert.strictEqual((await registerJson({username: "Alice", password: "Password01"})).status, 200); - assert.deepStrictEqual(await (await registerJson({username: "alice", password: "Password01"})).json(), {error: "username_taken"}); - assert.deepStrictEqual(await (await registerJson({username: "a!", password: "Password01"})).json(), {error: "invalid_username"}); + assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Alice", password: "KettlePass01"})).status, 401); + assert.strictEqual((await registerJson({username: "Alice", password: "KettlePass01"})).status, 200); + assert.deepStrictEqual(await (await registerJson({username: "alice", password: "KettlePass01"})).json(), {error: "username_taken"}); + assert.deepStrictEqual(await (await registerJson({username: "a!", password: "KettlePass01"})).json(), {error: "invalid_username"}); assert.deepStrictEqual(await (await registerJson({username: "Shorty", password: "pw"})).json(), {error: "invalid_password"}); // no default animal: whoever signs up picks one of the nine on the page. - assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "Password01", avatarType: undefined})).json(), {error: "choose_animal"}); - assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "Password01", avatarType: 2})).json(), {error: "choose_animal"}); + assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "KettlePass01", avatarType: undefined})).json(), {error: "choose_animal"}); + assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "KettlePass01", avatarType: 2})).json(), {error: "choose_animal"}); assert.match(await (await fetch(`${BASE}/register`)).text(), /Choose an animal/); assert.strictEqual((await fetch(`${BASE}/signup/thumb_wolf.svg`)).headers.get("content-type"), "image/svg+xml"); assert.strictEqual((await fetch(`${BASE}/signup/..%2Faccount.html`)).status, 404); - for (const [username, password] of [["Bob", "Password02"], ["Carol", "Password03"], ["foo", "Password04"]]) { + for (const [username, password] of [["Bob", "KettlePass02"], ["Carol", "KettlePass03"], ["foo", "KettlePass04"]]) { assert.strictEqual((await registerJson({username, password})).status, 200); } - let res = await postJson(`${BASE}/authenticate`, {username: "Alice", password: "Password01", domain: "flash", df: "x"}); + let res = await postJson(`${BASE}/authenticate`, {username: "Alice", password: "KettlePass01", domain: "flash", df: "x"}); assert.strictEqual(res.status, 200); assert.strictEqual(res.headers.get("access-control-allow-origin"), "null"); const alice = await res.json(); assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "alice", password: "wrong"})).status, 401); - assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "constructor", password: "Password01"})).status, 401); + assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "constructor", password: "KettlePass01"})).status, 401); assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: alice.refresh_token})).status, 200); - const bob = await (await postJson(`${BASE}/authenticate`, {username: "Bob", password: "Password02"})).json(); + const bob = await (await postJson(`${BASE}/authenticate`, {username: "Bob", password: "KettlePass02"})).json(); res = await fetch(`${BASE}/player?domain=flash&client_version=1830`, {headers: {Authorization: `Bearer ${alice.auth_token}`}}); assert.strictEqual((await res.json()).screen_name, "Alice"); @@ -83,11 +83,11 @@ const run = async () => { assert.deepStrictEqual((await guest.nextXt("la")).slice(2), ["1"]); const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv("aes-256-cbc", crypto.createHash("sha256").update(guestKey).digest(), iv); - const encrypted = Buffer.concat([iv, cipher.update("DavePass01"), cipher.final()]).toString("base64"); + const encrypted = Buffer.concat([iv, cipher.update("TulipKettle01"), cipher.final()]).toString("base64"); guest.xt("lc", 1, "Dave", encrypted, "2000-01-01", 0, "", 15136, 15224, 15299, 4, 0, "US", 1830); assert.deepStrictEqual((await guest.nextXt("lc")).slice(2, 3), ["1"]); guest.socket.destroy(); - assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Dave", password: "DavePass01"})).status, 200); + assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Dave", password: "TulipKettle01"})).status, 200); // --- first player: login and world entry const a = new GameClient(); @@ -158,6 +158,10 @@ const run = async () => { assert.deepStrictEqual((await b.nextXt("uc")).slice(1), [roomId, String(bobId), "hi & bye", "0"]); b.send(``); // emote: not echoed assert.deepStrictEqual((await a.nextXt("uc")).slice(3), ["7", "2"]); + // Actions are sent to every other player in the room. The sender has + // already applied the action locally, so it is not echoed back to them. + b.send(``); + assert.deepStrictEqual((await a.nextXt("uc")).slice(3), [":sitS:", "3", "m1"]); // --- player cards a.xt("ag", roomId, "bob", 1); @@ -234,7 +238,7 @@ const run = async () => { assert.deepStrictEqual((await a.nextXt("ds")).slice(2), ["0", "0", "1"]); // --- shops, clothing, animals and pets (Carol watches from the same den) - const carol = await (await postJson(`${BASE}/authenticate`, {username: "Carol", password: "Password03"})).json(); + const carol = await (await postJson(`${BASE}/authenticate`, {username: "Carol", password: "KettlePass03"})).json(); const c = new GameClient(); await c.connect(); await c.logIn("Carol", carol.auth_token); @@ -383,17 +387,18 @@ const run = async () => { const moved = await c.nextXt("rp"); assert.deepStrictEqual([moved[4], moved[5]], ["2", newDenDef]); // room type 2 = den, then the den type assert.deepStrictEqual((await c.nextXt("ds")).slice(2, 3), ["0"]); // the furniture stayed in the first den - assert.deepStrictEqual((await a.nextXt("ds")).slice(2, 3), ["0"]); + // the owner is also sent the den's items ("di") on a switch + assert.deepStrictEqual((await a.untilXt("ds")).slice(2, 3), ["0"]); a.xt("dc", denId, 0); await a.nextXt("dc"); await c.nextXt("rp"); assert.deepStrictEqual((await c.nextXt("ds")).slice(2, 3), ["1"]); - await a.nextXt("ds"); + await a.untilXt("ds"); a.xt("dp", denId, 0, 0); { const stranger = new GameClient(); await stranger.connect(); - await stranger.logIn("Dave", (await (await postJson(`${BASE}/authenticate`, {username: "Dave", password: "DavePass01"})).json()).auth_token); + await stranger.logIn("Dave", (await (await postJson(`${BASE}/authenticate`, {username: "Dave", password: "TulipKettle01"})).json()).auth_token); stranger.xt("dj", 1, "denAlice", 1, -1); assert.strictEqual((await stranger.nextXt("rj"))[2], "0"); stranger.socket.destroy(); @@ -411,7 +416,7 @@ const run = async () => { assert.deepStrictEqual([gone[2], gone[5], ...gone.slice(7)], ["2", "Alice", "0", "1", tradedInv]); // --- item finder: search by name and id, give to a connected player - assert.match(await (await fetch(`${BASE}/shop`)).text(), /Item finder/); + assert.match(await (await fetch(`${BASE}/shop`)).text(), /Item giver/); const found = await (await fetch(`${BASE}/api/search?q=top+hat&kind=clothing`)).json(); assert.ok(found.total > 0 && found.results.every(item => /top/i.test(item.name) && /hat/i.test(item.name))); const hat = found.results[0]; @@ -428,7 +433,7 @@ const run = async () => { assert.deepStrictEqual((await a.nextXt("di")).slice(3, 4), ["1"]); // --- no game account has admin powers: "foo" is an ordinary player now - const foo = await (await postJson(`${BASE}/authenticate`, {username: "foo", password: "Password04"})).json(); + const foo = await (await postJson(`${BASE}/authenticate`, {username: "foo", password: "KettlePass04"})).json(); const f = new GameClient(); await f.connect(); const fooLogin = await f.logIn("foo", foo.auth_token); @@ -520,14 +525,14 @@ const run = async () => { // names sign-up would refuse are fine from the panel, and can log in. for (const odd of ["x", "~*Bob*~ <3", "Ünïcødé 名前", "a name well past twenty characters"]) { assert.strictEqual((await panel("account", {username: "Bob", action: "rename", newName: odd}, admin)).status, 200); - assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: odd, password: "Password02"})).status, 200); + assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: odd, password: "KettlePass02"})).status, 200); assert.strictEqual((await panel("account", {username: odd, action: "rename", newName: "Bob"}, admin)).status, 200); } - assert.strictEqual((await registerJson({username: "x", password: "Password09"})).status, 400); // sign-up rules unchanged + assert.strictEqual((await registerJson({username: "x", password: "KettlePass09"})).status, 400); // sign-up rules unchanged const renamed = await panel("account", {username: "Bob", action: "rename", newName: "Robert"}, admin); assert.deepStrictEqual([renamed.status, renamed.data.username], [200, "Robert"]); - assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Bob", password: "Password02"})).status, 401); - assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "robert", password: "Password02"})).status, 200); + assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Bob", password: "KettlePass02"})).status, 401); + assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "robert", password: "KettlePass02"})).status, 200); assert.ok(!(await panel("accounts", undefined, admin)).data.accounts.some(account => account.username === "Bob")); assert.strictEqual((await panel("account", {username: "Robert", action: "rename", newName: "ROBERT"}, admin)).status, 200); assert.strictEqual((await panel("account", {username: "robert", action: "rename", newName: "Bob"}, admin)).status, 200); @@ -535,7 +540,7 @@ const run = async () => { // A new password for a player: the old one and old tokens stop working. assert.strictEqual((await panel("account", {username: "foo", action: "password", password: "short"}, admin)).status, 400); assert.strictEqual((await panel("account", {username: "foo", action: "password", password: "New-password-4"}, admin)).status, 200); - assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "Password04"})).status, 401); + assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "KettlePass04"})).status, 401); assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: foo.refresh_token})).status, 401); assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "New-password-4"})).status, 200); assert.strictEqual((await panel("account", {username: "foo", action: "delete"}, admin)).status, 200); @@ -621,14 +626,16 @@ const run = async () => { // --- the custom client's login choices: honoured for that session only assert.strictEqual((await (await fetch(`${BASE}/flashvars`)).json()).loginChoices, true); - const chosen = await (await postJson(`${BASE}/authenticate`, {username: "Carol", password: "Password03", + // (a fresh account: Carol is banned by now, and a banned account's + // sign-in is refused with "account_banned", so it gets no token.) + assert.strictEqual((await registerJson({username: "Erin", password: "KettlePass05"})).status, 200); + const chosen = await (await postJson(`${BASE}/authenticate`, {username: "Erin", password: "KettlePass05", login_choices: {accountType: 0, isGuide: true, membershipDays: 12, isModerator: "yes"}})).json(); - // (Carol is banned from the game by now, so only the web side is checked.) assert.strictEqual((await (await fetch(`${BASE}/player`, {headers: {Authorization: `Bearer ${chosen.auth_token}`}})).json()).game_account_type, 0); - a.xt("ag", denId, "Carol", 0); + a.xt("ag", denId, "Erin", 0); assert.deepStrictEqual((await a.untilXt("ag")).slice(5, 7), ["0", "1"]); // account type, guide - await postJson(`${BASE}/authenticate`, {username: "Carol", password: "Password03"}); // and back to normal - a.xt("ag", denId, "Carol", 0); + await postJson(`${BASE}/authenticate`, {username: "Erin", password: "KettlePass05"}); // and back to normal + a.xt("ag", denId, "Erin", 0); assert.deepStrictEqual((await a.untilXt("ag")).slice(5, 7), ["2", "0"]); // --- custom colours: an id for four RGB values, announced to everyone @@ -642,7 +649,7 @@ const run = async () => { assert.strictEqual((await a.untilXt("ap"))[2], "1"); const late = new GameClient(); await late.connect(); - const dev = await (await postJson(`${BASE}/authenticate`, {username: "Alice", password: "Password01", login_choices: {accountType: 4, membershipDays: 7}})).json(); + const dev = await (await postJson(`${BASE}/authenticate`, {username: "Alice", password: "KettlePass01", login_choices: {accountType: 4, membershipDays: 7}})).json(); const devLogin = await late.logIn("Alice", dev.auth_token); assert.deepStrictEqual([devLogin.params.accountType, devLogin.params.numDaysLeftOnSubscription, devLogin.params.isGuide, devLogin.params.isModerator], [4, 7, false, false]); assert.deepStrictEqual((await late.untilXt("xcc")).slice(2, 4), ["1", String(0xFD000000)]); // the table at login diff --git a/test/staff.js b/test/staff.js new file mode 100644 index 0000000..4cdfbe8 --- /dev/null +++ b/test/staff.js @@ -0,0 +1,376 @@ +"use strict"; + +// end to end: staff roles (lib/roles.js), the staff chat commands +// (lib/commands.js) and the moderator panel's role checks +// (lib/modpanel.js), against a real server with a database of its own. + +const assert = require("assert"); +const crypto = require("crypto"); +const harness = require("./harness.js"); + +const HTTP_PORT = 18091; +const GAME_PORT = 19350; +const BASE = `http://127.0.0.1:${HTTP_PORT}`; +const TOWNSHIP = "jamaa_township.room_main#1"; +const SAREPIA = "sarepia.room_main#1"; +const {postJson} = harness; + +// the authenticator app's side of 2FA (lib/totp.js): a base32 secret, +// HMAC-SHA1, 30-second steps, six digits. +const STEP = 30; +const base32Decode = text => { + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + const bits = text.replace(/=+$/, "").toUpperCase().split("").map(c => alphabet.indexOf(c).toString(2).padStart(5, "0")).join(""); + const bytes = []; + for (let i = 0; i + 8 <= bits.length; i += 8) { + bytes.push(parseInt(bits.slice(i, i + 8), 2)); + } + return Buffer.from(bytes); +}; +const codeAt = (secret, step) => { + const counter = Buffer.alloc(8); + counter.writeBigUInt64BE(BigInt(step)); + const mac = crypto.createHmac("sha1", base32Decode(secret)).update(counter).digest(); + const offset = mac[mac.length - 1] & 0x0F; + return String((mac.readUInt32BE(offset) & 0x7FFFFFFF) % 1000000).padStart(6, "0"); +}; +const stepNow = () => Math.floor(Date.now() / 1000 / STEP); +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +// a code is taken once: each use needs a later step than the last. +const waitForStep = async step => { + while (stepNow() < step) { + await sleep(250); + } +}; + +// a web panel's session: keeps the cookie it is given. +const webSession = () => { + let cookie = ""; + return async (path, body) => { + const headers = {cookie}; + const options = body === undefined ? {headers} : {method: "POST", headers: {...headers, "Content-Type": "application/json"}, body: JSON.stringify(body)}; + const res = await fetch(`${BASE}${path}`, options); + const set = res.headers.get("set-cookie"); + if (set) { + cookie = set.split(";")[0]; + } + return {status: res.status, data: await res.json().catch(() => ({}))}; + }; +}; + +const say = (client, roomId, text) => + client.send(``); + +// logs in (with a 2FA code when given) and walks into `room`. `onLogin` +// sees what comes with the login, before joining skips past it. +const arrive = async (username, password, room, totp, onLogin = async () => {}) => { + const res = await postJson(`${BASE}/authenticate`, {username, password, ...(totp ? {totp} : {})}); + const auth = await res.json(); + assert.strictEqual(res.status, 200, `${username} could not sign in: ${JSON.stringify(auth)}`); + const client = new harness.GameClient(GAME_PORT); + await client.connect(); + const login = await client.logIn(username, auth.auth_token); + assert.strictEqual(login.status, "1"); + await onLogin(client); + client.xt("rj", 1, room, 1, 0, 0); + let rj = await client.untilXt("rj"); + await client.untilXt("rp"); + // a session's first room is always a spawn room (lib/world.js joinRoom) + if (rj[3] !== room) { + client.xt("rj", rj[4], room, 1, 0, 0); + rj = await client.untilXt("rj"); + await client.untilXt("rp"); + } + client.xt("au", rj[4], 1, 400, 400, 14, 1); + return {client, login, roomId: rj[4], room: rj[3]}; +}; + +// the next moderator popup ("fd") of this kind, skipping earlier ones (a +// silence notice, say) still waiting. +const untilPopup = async (client, kind) => { + for (;;) { + const fields = await client.untilXt("fd"); + if (fields[2] === kind) { + return fields; + } + } +}; + +// the next message box ("xtl") the server shows this client. +const nextBox = async client => (await client.untilXt("xtl"))[2]; + +// the chat line `text` coming back (every typed line, a command too, is +// shown to its sender, so skip those before it). +const untilChat = async (client, text) => { + for (;;) { + const line = await client.untilXt("uc"); + if (line[3] === text) { + return line; + } + } +}; + +const run = async () => { + const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})}); + const people = {Mira: "KettlePass11", Hal: "KettlePass12", Pip: "KettlePass13", Ann: "KettlePass14"}; + for (const [username, password] of Object.entries(people)) { + assert.strictEqual((await registerJson({username, password})).status, 200); + } + + // --- the admin gives roles + const admin = webSession(); + assert.strictEqual((await admin("/admin/api/setup", {password: "AdminPass99!"})).status, 200); + assert.strictEqual((await admin("/admin/api/login", {password: "AdminPass99!"})).status, 200); + const roleList = await admin("/admin/api/roles"); + assert.deepStrictEqual(roleList.data.roles.map(role => role.id), ["developer", "helper", "moderator", "admin"]); + assert.match((await admin("/admin/api/account", {username: "Mira", action: "role", role: "boss"})).data.error, /No such role/); + + // staff need 2FA: turned on from the account page. + const secrets = {}; + const usedStep = {}; + for (const username of ["Mira", "Hal"]) { + const page = webSession(); + assert.strictEqual((await page("/account/api/login", {username, password: people[username]})).status, 200); + const begun = await page("/account/api/act", {action: "twoStepStart", current: people[username]}); + secrets[username] = begun.data.setup.secret; + usedStep[username] = stepNow(); + const confirmed = await page("/account/api/act", {action: "twoStepConfirm", code: codeAt(secrets[username], usedStep[username])}); + assert.ok(confirmed.data.ok, JSON.stringify(confirmed.data)); + } + assert.match((await admin("/admin/api/account", {username: "Mira", action: "role", role: "moderator"})).data.ok, /moderator/); + assert.match((await admin("/admin/api/account", {username: "Hal", action: "role", role: "helper"})).data.ok, /helper/); + + // --- the game: the login reply carries your own role, and nobody else's + usedStep.Mira++; + // and the patched client's staff window is told the same ("xsp") + let staffSaid = null; + const mira = await arrive("Mira", people.Mira, TOWNSHIP, codeAt(secrets.Mira, usedStep.Mira), async client => { + staffSaid = await client.untilXt("xsp"); + }); + assert.strictEqual(staffSaid[2], "moderator"); + assert.ok(staffSaid[3].split(",").includes("player.summon")); + assert.strictEqual(mira.login.params.staffRole, "moderator"); + assert.ok(mira.login.params.staffPermissions.split(",").includes("player.summon")); + usedStep.Hal++; + const hal = await arrive("Hal", people.Hal, TOWNSHIP, codeAt(secrets.Hal, usedStep.Hal)); + assert.strictEqual(hal.login.params.staffRole, "helper"); + const pip = await arrive("Pip", people.Pip, SAREPIA); + assert.strictEqual(pip.login.params.staffRole, ""); + const ann = await arrive("Ann", people.Ann, SAREPIA); + + // a staff command from a player is plain chat + say(pip.client, pip.roomId, "!kick Mira"); + await untilChat(pip.client, "!kick Mira"); + + say(mira.client, mira.roomId, "!staff"); + const staffBox = await nextBox(mira.client); + assert.match(staffBox, /Mira \(Moderator\)/); + assert.match(staffBox, /Hal \(Helper\)/); + + // summon: Pip is brought from Sarepia to Mira in the township + say(mira.client, mira.roomId, "!summon Pip"); + // ... onto the spot where Mira stands, when the room has loaded ("xgt") + assert.deepStrictEqual((await pip.client.untilXt("xgt")).slice(2), ["400", "400", "0"]); + assert.strictEqual((await pip.client.untilXt("rj"))[3], TOWNSHIP); + assert.strictEqual(await nextBox(mira.client), "Pip was brought here."); + + // a helper may silence a player, but not kick, nor act on a moderator + say(hal.client, hal.roomId, "!silence Pip 1"); + assert.strictEqual(await nextBox(hal.client), "Pip cannot chat for 1 hours."); + say(hal.client, hal.roomId, "!silence Pip off"); + assert.strictEqual(await nextBox(hal.client), "Pip can chat again."); + say(hal.client, hal.roomId, "!silence Mira 1"); + assert.match(await nextBox(hal.client), /your rank or above/); + say(hal.client, hal.roomId, "!kick Pip"); + // no permission: just chat, seen by the room (Mira, in the township) + await untilChat(mira.client, "!kick Pip"); + + // goto: Mira goes to Ann in Sarepia + say(mira.client, mira.roomId, "!goto Ann"); + assert.deepStrictEqual((await mira.client.untilXt("xgt")).slice(2), ["400", "400", "0"]); + assert.strictEqual((await mira.client.untilXt("rj"))[3], SAREPIA); + // in the same room already: straight onto her + say(mira.client, ann.roomId, "!goto Ann"); + assert.deepStrictEqual((await mira.client.untilXt("xgt")).slice(2), ["400", "400", "1"]); + + // a warning: the game's own popup for the reason ("fw", 1 = bullying), + // kept on the account; a message box; the count; then kick disconnects + say(mira.client, ann.roomId, "!warn Ann bullying called names"); + assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fw", "1"]); + assert.strictEqual(await nextBox(mira.client), "Ann warned (bullying): warning 1."); + say(mira.client, ann.roomId, "!warn Ann"); + assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fw", "4"]); // behavior, the default + assert.strictEqual(await nextBox(mira.client), "Ann warned (behavior): warning 2."); + say(mira.client, ann.roomId, "!message Ann please be kind"); + assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fp", "please be kind"]); + assert.strictEqual(await nextBox(mira.client), "Shown to Ann."); + say(mira.client, ann.roomId, "!warnings Ann"); + assert.match(await nextBox(mira.client), /^Ann has 2 warnings\. Latest: \S+ behavior by Mira; \S+ bullying by Mira \(called names\)$/); + // the client's staff window ("xmd"): the same commands, one field each + // the third warning in 30 days also silences for an hour (config.warningSilence) + mira.client.xt("xmd", ann.roomId, "warn", "Ann", "personal"); + assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fw", "3"]); + assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fs", "60"]); + assert.strictEqual(await nextBox(mira.client), "Ann warned (personal): warning 3. Silenced for 60 minutes, for that many warnings."); + mira.client.xt("xmd", ann.roomId, "message", "Ann", "hello there"); + assert.deepStrictEqual((await untilPopup(ann.client, "fp")).slice(2, 4), ["fp", "hello there"]); + assert.strictEqual(await nextBox(mira.client), "Shown to Ann."); + mira.client.xt("xmd", ann.roomId, "ban", "Ann"); // not one the window has: nothing + // and from a player, nothing at all: Ann warns Mira + ann.client.xt("xmd", ann.roomId, "warn", "Mira", "bullying"); + mira.client.xt("xmd", ann.roomId, "warnings", "Ann"); + assert.match(await nextBox(mira.client), /^Ann has 3 warnings\. /); + say(mira.client, ann.roomId, "!warnings Mira"); + assert.strictEqual(await nextBox(mira.client), "Mira has no warnings."); + say(mira.client, ann.roomId, "!kick Ann"); + assert.strictEqual((await ann.client.untilXt("fd"))[2], "fk"); + assert.strictEqual(await nextBox(mira.client), "Ann was disconnected."); + + // --- the moderator panel: what the role allows, checked by the server + for (const username of ["Mira", "Hal"]) { + usedStep[username]++; + } + await waitForStep(Math.max(usedStep.Mira, usedStep.Hal) - 1); + const modPage = webSession(); + assert.strictEqual((await modPage("/mod/api/login", {username: "Mira", password: people.Mira, code: codeAt(secrets.Mira, usedStep.Mira)})).status, 200); + const miraMe = (await modPage("/mod/api/me")).data; + assert.strictEqual(miraMe.role, "moderator"); + assert.ok(miraMe.permissions.includes("player.ban")); + const halPage = webSession(); + assert.strictEqual((await halPage("/mod/api/login", {username: "Hal", password: people.Hal, code: codeAt(secrets.Hal, usedStep.Hal)})).status, 200); + const halMe = (await halPage("/mod/api/me")).data; + assert.strictEqual(halMe.role, "helper"); + assert.ok(!halMe.permissions.includes("player.ban")); + assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "ban", hours: 1, reason: "x"})).data.error, "Your role cannot do that."); + assert.match((await halPage("/mod/api/act", {username: "Mira", action: "silence", hours: 1})).data.error, /your rank or above/); + // searching by address (against ban evasion) is for the roles that ban addresses + assert.strictEqual((await halPage("/mod/api/players?by=address&q=127.0.0.")).status, 403); + assert.ok(Array.isArray((await modPage("/mod/api/players?by=address&q=127.0.0.")).data.players)); + // a warning from the panel, and on the player's page + assert.match((await modPage("/mod/api/act", {username: "Pip", action: "warn", reason: "scamming", note: "fake trade"})).data.ok, /^Pip warned \(scamming\): warning 1\./); + assert.match((await modPage("/mod/api/act", {username: "Pip", action: "warn", reason: "nonsense"})).data.error, /reason/); + assert.deepStrictEqual((await untilPopup(pip.client, "fw")).slice(2, 4), ["fw", "9"]); + const pipPage = (await modPage("/mod/api/player?username=Pip")).data; + assert.strictEqual(pipPage.warnings, 1); + assert.deepStrictEqual([pipPage.warningList[0].reason, pipPage.warningList[0].note, pipPage.warningList[0].by], ["scamming", "fake trade", "Mira"]); + assert.strictEqual(pipPage.warningList[0].seen, true); + + // mod notes: for staff, never the player; removed by their writer or an admin + assert.strictEqual((await modPage("/mod/api/act", {username: "Pip", action: "note", text: " talked about trading, seemed fine "})).data.ok, "Note added."); + assert.match((await modPage("/mod/api/act", {username: "Pip", action: "note", text: " "})).data.error, /Write the note first/); + assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "note", text: "keeps asking for free items"})).data.ok, "Note added."); + const notes = (await modPage("/mod/api/player?username=Pip")).data.notes; + assert.deepStrictEqual(notes.map(note => `${note.by}: ${note.text}`), ["Hal: keeps asking for free items", "Mira: talked about trading, seemed fine"]); + assert.match((await modPage("/mod/api/act", {username: "Pip", action: "deleteNote", id: notes[0].id})).data.error, /Only whoever wrote a note/); + assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "deleteNote", id: notes[0].id})).data.ok, "Note removed."); + assert.match((await halPage("/mod/api/act", {username: "Mira", action: "note", text: "x"})).data.error, /your rank or above/); + say(mira.client, ann.roomId, "!note Pip asked about the rules"); + assert.strictEqual(await nextBox(mira.client), "Note on Pip added."); + say(mira.client, ann.roomId, "!notes Pip"); + assert.match(await nextBox(mira.client), /^Notes on Pip: \S+ Mira: asked about the rules \| \S+ Mira: talked about trading, seemed fine$/); + say(mira.client, ann.roomId, "!notes Nobody"); + assert.strictEqual(await nextBox(mira.client), "No player called Nobody."); + + // warnings while away (Ann was disconnected): kept for her next visit; + // the fifth in 30 days silences for a day; one is taken back + assert.match((await modPage("/mod/api/act", {username: "Ann", action: "warn", reason: "bullying"})).data.ok, + /^Ann warned \(bullying\): warning 4\. They are offline: they will see it when they next play\.$/); + assert.match((await modPage("/mod/api/act", {username: "Ann", action: "warn", reason: "behavior"})).data.ok, + /warning 5\. .*silenced them for 1 day\.$/); + assert.strictEqual((await modPage("/mod/api/act", {username: "Ann", action: "unwarn"})).data.ok, "Took back Ann's latest warning (behavior)."); + const annAway = (await modPage("/mod/api/player?username=Ann")).data; + assert.strictEqual(annAway.warnings, 4); + assert.strictEqual(annAway.warningList[0].seen, false); + const annBack = await arrive("Ann", people.Ann, SAREPIA); + assert.deepStrictEqual((await untilPopup(annBack.client, "fw")).slice(2, 4), ["fw", "1"]); // the bullying one + assert.strictEqual((await modPage("/mod/api/player?username=Ann")).data.warningList[0].seen, true); + say(mira.client, ann.roomId, "!unwarn Ann"); + assert.strictEqual(await nextBox(mira.client), "Took back Ann's latest warning (bullying)."); + say(mira.client, ann.roomId, "!unwarn Mira"); + assert.strictEqual(await nextBox(mira.client), "That is you."); + + // the panel's summon brings Pip to Mira (now in Sarepia) + assert.match((await modPage("/mod/api/act", {username: "Pip", action: "summon"})).data.ok || "", /^Pip was brought to /); + assert.strictEqual((await pip.client.untilXt("rj"))[3], SAREPIA); + + // a custom warning: the staff member's words are what the player sees + mira.client.xt("xmd", ann.roomId, "warn", "Pip", "custom", "no spamming please"); + assert.deepStrictEqual((await untilPopup(pip.client, "fp")).slice(2, 4), ["fp", "Warning: no spamming please"]); + assert.strictEqual(await nextBox(mira.client), "Pip warned (custom): warning 2."); + say(mira.client, ann.roomId, "!warn Pip custom"); + assert.match(await nextBox(mira.client), /^Use: !warn PLAYER custom TEXT/); + assert.match((await modPage("/mod/api/act", {username: "Pip", action: "warn", reason: "custom", note: " "})).data.error, /custom warning needs its words/); + + // invisible: gone from players' screens, still seen by staff (half + // see-through: "xiv"), and seen moving by them; not for a helper + // ("ac": [.., room, id, x, y, anim, username, ...]; others' may be waiting) + const untilDrawn = async (client, username, x) => { + for (;;) { + const fields = await client.untilXt("ac"); + if (fields[6] === username && fields[3] === x) { + return fields; + } + } + }; + const untilRemoved = async (client, id) => { + for (;;) { + if ((await client.untilXt("ar"))[2] === id) { + return; + } + } + }; + mira.client.xt("au", ann.roomId, 1, 300, 300, 14, 1); + const miraId = (await untilDrawn(pip.client, "Mira", "300"))[2]; + hal.client.xt("rj", 1, SAREPIA, 1, 0, 0); + const halRj = await hal.client.untilXt("rj"); + await hal.client.untilXt("rp"); + hal.client.xt("au", halRj[4], 1, 410, 410, 14, 1); + await untilDrawn(hal.client, "Mira", "300"); + say(mira.client, ann.roomId, "!invisible"); + await untilRemoved(pip.client, miraId); + assert.deepStrictEqual((await hal.client.untilXt("xiv")).slice(2), [miraId, "1"]); + assert.deepStrictEqual((await mira.client.untilXt("xiv")).slice(2), [miraId, "1"]); + assert.match(await nextBox(mira.client), /^You are invisible: only staff see you/); + mira.client.xt("au", ann.roomId, 1, 350, 350, 14, 0); + for (;;) { + const moved = await hal.client.untilXt("au"); + if (moved[3] === miraId) { + break; + } + } + // a helper may not: the window's request does nothing, the command is chat + hal.client.xt("xiv", halRj[4]); + say(hal.client, halRj[4], "!invisible"); + await untilChat(pip.client, "!invisible"); + // back again, where she walked to + mira.client.xt("xiv", ann.roomId); + assert.deepStrictEqual((await untilDrawn(pip.client, "Mira", "350")).slice(2, 5), [miraId, "350", "350"]); + assert.deepStrictEqual((await hal.client.untilXt("xiv")).slice(2), [miraId, "0"]); + assert.strictEqual(await nextBox(mira.client), "You can be seen again."); + + // everything above is in the moderators' log, the in-game ones marked so + const log = (await admin("/admin/api/moderators")).data.log.map(entry => `${entry.by} ${entry.action} ${entry.target}`); + for (const line of ["Mira summon (in game) Pip", "Hal silence (in game) Pip", "Mira goto (in game) Ann", "Mira warn (in game) Ann", + "Mira message (in game) Ann", "Mira kick (in game) Ann", "Mira warn Pip", "Mira summon Pip", "Mira warn Ann", "Mira unwarn Ann", + "Mira unwarn (in game) Ann", "Mira went invisible (in game) ", "Mira became visible (in game) ", "Mira note Pip", "Hal deleteNote Pip", + "Mira note (in game) Pip"]) { + assert.ok(log.includes(line), `missing from the log: ${line}\n${log.join("\n")}`); + } + + // the moderators' message box header has real line breaks, not "\\n" + const zlib = require("zlib"); + const {decode} = require("../lib/amf3.js"); + const stringsPath = require("../lib/cdn.js").hashedPath("defPacks/10230"); + const strings = decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${stringsPath}`)).arrayBuffer()))); + assert.strictEqual(strings[11134], "--Message From Moderator--\n\n"); + assert.ok(!strings[11135].includes("\\n")); + + for (const {client} of [mira, hal, pip, annBack]) { + client.socket.destroy(); + } +}; + +harness.withServer("staff test", HTTP_PORT, GAME_PORT, run).catch(err => { + console.error(err); + process.exit(1); +}); diff --git a/tools/build-client.sh b/tools/build-client.sh index 123d793..9ae40a2 100755 --- a/tools/build-client.sh +++ b/tools/build-client.sh @@ -23,6 +23,7 @@ cd "$(dirname "$(readlink -f "$0")")/.." out=${1:-swf/ajclient.swf} set -- \ AJClient AJClient.as \ + com.sbi.client.KeepAlive KeepAlive.as \ GlobalErrorCatch GlobalErrorCatch.as \ XtReplyDemuxer XtReplyDemuxer.as \ loader.MediaHelper MediaHelper.as \ @@ -56,6 +57,7 @@ set -- \ gui.PetInventory PetInventory.as \ gui.DenEditor DenEditor.as \ gui.TradeManager TradeManager.as \ + avatar.AvatarView AvatarView.as \ avatar.AvatarWorldView AvatarWorldView.as \ room.RoomManagerWorld RoomManagerWorld.as \ gskinner.motion.GTween GTween.as \ @@ -75,10 +77,18 @@ set -- \ ecard.ECard ECard.as \ game.ArtStudioKit ArtStudioKit.as \ game.artStudioPainting.ArtStudioPainting ArtStudioPainting.as \ - game.artStudioGridDrawing.ArtStudioGridDrawing ArtStudioGridDrawing.as + game.artStudioGridDrawing.ArtStudioGridDrawing ArtStudioGridDrawing.as \ + item.ItemXtCommManager ItemXtCommManager.as \ + den.DenXtCommManager DenXtCommManager.as \ + gui.ActionManager ActionManager.as \ + gui.SitForwardAction SitForwardAction.as \ + avatar.AvatarUtility AvatarUtility.as \ + item.Item Item.as \ + loader.DenItemHelper DenItemHelper.as # not in the game: added before the replace (game.ArtStudioKit is Strawberry -# Jam's, shared by its two art studio painters) -NEW_CLASSES="game.ArtStudioKit" +# Jam's, shared by its two art studio painters; gui.SitForwardAction is the +# action of sitting facing forward) +NEW_CLASSES="game.ArtStudioKit gui.SitForwardAction" args="" while [ $# -gt 0 ]; do args="$args $1 swf-src/$2" diff --git a/tools/emotes/skull.png b/tools/emotes/skull.png new file mode 100644 index 0000000..0ef2693 Binary files /dev/null and b/tools/emotes/skull.png differ diff --git a/tools/emotes/sob.png b/tools/emotes/sob.png new file mode 100644 index 0000000..fde68ee Binary files /dev/null and b/tools/emotes/sob.png differ diff --git a/tools/make-emote.py b/tools/make-emote.py index cbada02..8b0f456 100644 --- a/tools/make-emote.py +++ b/tools/make-emote.py @@ -1,4 +1,4 @@ -"""make-emote.py [name] [--black-background] +"""make-emote.py [name] [--slot=N] [--black-background] Adds an emote of our own to swf/HUDAssets.swf, from a picture: the classes "" (the emote over an animal's head and in a chat bubble) and @@ -10,7 +10,9 @@ The game makes an emote by its class name (gui.EmoticonUtility), so the name also has to be in that class's lists: swf-src/EmoticonUtility.cinit.pcode, which tools/build-client.sh puts into the client. -Running it again replaces what an earlier run added. The picture must be an +Each emote of ours has a slot (--slot=N, 0 by default: emo_temp's), its +own character ids and its own code: running it again for a slot replaces +what an earlier run put there, and leaves the other slots as they are. The picture must be an 8-bit RGBA PNG, not interlaced; --black-background is for one that came on black where it should be see-through. Needs nothing but Python. """ @@ -267,18 +269,23 @@ def main(): sys.exit(__doc__) words = [word for word in sys.argv[1:] if not word.startswith("--")] name = words[1] if len(words) > 1 else "emo_temp" + slots = [word for word in sys.argv[1:] if word.startswith("--slot=")] + slot = int(slots[0].split("=", 1)[1]) if slots else 0 + first_id = FIRST_ID + slot * 5 + # slot 0 keeps the name it always had, so that a run for it replaces it + abc_name = ABC_NAME if slot == 0 else ABC_NAME + b"_" + str(slot).encode() picture = read_png(Path(words[0])) if "--black-background" in sys.argv: picture = without_background(*picture) width, height, pixels = shrunk(*picture, SHRINK) - bitmap, large_shape, small_shape, large, small = range(FIRST_ID, FIRST_ID + 5) + bitmap, large_shape, small_shape, large, small = range(first_id, first_id + 5) ours = [ tag(36, struct.pack(" new Date(time).toISOString().slice(0, 10); fs.mkdirSync(filesDir, {recursive: true}); // {builds: {build: newest sale start}, rooms: {room: {build: hash of its file}}} - let index = fs.existsSync(indexFile) ? JSON.parse(fs.readFileSync(indexFile)) : null; + // read if it is there: no separate look first, which the file could change after + let index = null; + try { + index = JSON.parse(fs.readFileSync(indexFile)); + } + catch (err) { + if (err.code !== "ENOENT") { + throw err; + } + } if (!index) { index = {builds: {}, rooms: {}}; const jobs = []; @@ -83,14 +92,25 @@ const day = time => new Date(time).toISOString().slice(0, 10); const [build, room] = jobs.pop(); const body = await download(build, `roomDefs/${room}.xroom`); const hash = body ? crypto.createHash("sha1").update(body).digest("hex").slice(0, 12) : null; - if (body && !fs.existsSync(path.join(filesDir, hash))) { - fs.writeFileSync(path.join(filesDir, hash), body); + // named by its own hash, so one already there is this same file: "wx" + // writes only a new one, in the one step. + if (body) { + try { + fs.writeFileSync(path.join(filesDir, hash), body, {flag: "wx"}); + } + catch (err) { + if (err.code !== "EEXIST") { + throw err; + } + } } (index.rooms[room] = index.rooms[room] || {})[build] = hash; } }; await Promise.all(Array.from({length: WORKERS}, worker)); - fs.writeFileSync(indexFile, JSON.stringify(index)); + // written whole under another name, then put in its place + fs.writeFileSync(`${indexFile}.tmp`, JSON.stringify(index)); + fs.renameSync(`${indexFile}.tmp`, indexFile); } console.log("Builds, by the newest sale start in each:");