diff --git a/lib/commands.js b/lib/commands.js index aeaea4e..05a9839 100644 --- a/lib/commands.js +++ b/lib/commands.js @@ -4,6 +4,7 @@ const accounts = require("./accounts.js"); const chatlog = require("./chatlog.js"); const customItems = require("./customitems.js"); const itemControl = require("./itemcontrol.js"); +const wearRules = require("./wearrules.js"); const modNotes = require("./modnotes.js"); const defpacks = require("./defpacks.js"); const disguises = require("./disguises.js"); @@ -73,7 +74,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB const {account} = session; const avatar = activeAvatar(account); const before = wornItems(account, avatar); - const wanted = account.items.filter(item => invs.includes(item.inv)).slice(0, MAX_WORN); + // Saved outfits are a second equip route, so they obey the same rule as + // the item editor. A saved id remains in the outfit in case staff later + // remove the rule; it simply cannot be put on while blocked. + const wanted = account.items.filter(item => invs.includes(item.inv) && wearRules.mayWear(item.def, avatar.type)).slice(0, MAX_WORN); const takenOff = before.filter(item => !wanted.includes(item)); account.outfitUndo = {avInvId: avatar.avInvId, items: before.map(item => item.inv)}; for (const item of takenOff) { @@ -596,6 +600,59 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB }; const staffCommands = { + // A short-lived room control for owners, admins and developers. It uses + // the avatar protocol rather than persisting any player appearance. + roomfx: { + permission: "room.effects", + run(session, words) { + const room = session.room; + const effect = (words[0] || "").toLowerCase(); + if (!room || !["small", "normal", "big", "rainbow", "clear"].includes(effect)) { + tell(session, "Use: !roomfx small, !roomfx normal, !roomfx big, !roomfx rainbow, or !roomfx clear"); + return; + } + const send = (type, value) => { + for (const target of room.sessions) { + for (const viewer of room.sessions) { + viewer.sendXt("uc", room.id, target.id, String(value), type); + } + } + }; + const stopRainbow = () => { + if (room.roomEffectTimer) { + clearInterval(room.roomEffectTimer); + delete room.roomEffectTimer; + } + }; + if (effect === "rainbow") { + stopRainbow(); + let hue = 0; + room.roomEffectTimer = setInterval(() => { + if (room.sessions.size === 0) { + stopRainbow(); + return; + } + const colour = [0xFF4040, 0xFFB340, 0xF8FF40, 0x50E860, 0x40CFFF, 0x7560FF, 0xDC55FF][hue++ % 7]; + send(8, colour); + }, 350); + room.roomEffectTimer.unref(); + tell(session, "Rainbow effect started for everyone in this room. !roomfx clear stops it."); + } + else { + stopRainbow(); + if (effect === "small" || effect === "big" || effect === "normal") { + send(14, effect === "small" ? 0.7 : effect === "big" ? 1.35 : 1); + tell(session, `Everyone in this room is now ${effect === "normal" ? "normal size" : effect}.`); + } + else { + send(8, 0); + send(14, 1); + tell(session, "Room effects cleared."); + } + } + modlog.record(session.account.username, "room effect (in game)", "", `${effect}: ${roomTitle(room)}`); + }, + }, // "!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. @@ -633,6 +690,38 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB tell(session, on.length ? `Staff online: ${on.join(", ")}` : "No staff online."); }, }, + // Opens the same in-game moderation window as a player's card. This is + // useful when a moderator already knows the name and does not need to + // hunt through search results first. + mod: { + permission: "player.view", + run(session, words) { + const target = words.length ? findOnline(words.join(" ")) : null; + if (!target) { + tell(session, words.length ? `${words.join(" ")} is not online.` : "Use: !mod PLAYER"); + return; + } + if (target.account !== session.account && roles.roleOf(target.account) && !roles.outranks(session.account, target.account)) { + tell(session, "Staff of your rank or above are for someone higher up to deal with."); + return; + } + session.sendXt("xui", -1, "moderate", target.account.username); + }, + }, + // Owners, admins and developers get the room-effects panel from chat. + // `host` is an intuitive alias for event hosts. + event: { + permission: "room.effects", + run(session) { + session.sendXt("xui", -1, "event"); + }, + }, + host: { + permission: "room.effects", + run(session) { + session.sendXt("xui", -1, "event"); + }, + }, // "!note PLAYER text": a note for the other staff (lib/modnotes.js), // never shown to the player. "!notes PLAYER": the latest few. note: { @@ -681,6 +770,20 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB setInvisible(session, !session.invisible); }, }, + reject: { + permission: "player.names", + run(session, words) { + withTarget(session, words, "Use: !reject PLAYER", true, target => { + if (target.account.nameRejected) { + tell(session, `${target.account.username}'s name is already rejected.`); + return; + } + staffModeration().actions.rejectName(target.account, session.account.username); + tell(session, `${target.account.username} was signed out and must choose a new name.`); + logged(session, "rejected username", target); + }); + }, + }, // "!lock clothing|den ID", "!unlock clothing|den ID", "!locked": items // kept out of the item finder for players (lib/itemcontrol.js). lock: { diff --git a/lib/customitems.js b/lib/customitems.js index 64cd4c5..c7b26fb 100644 --- a/lib/customitems.js +++ b/lib/customitems.js @@ -69,19 +69,39 @@ const apply = entry => defpacks.setCustomItem(entry.kind, rowOf(entry), entry.na // "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 xtRows = rows => JSON.stringify(rows).replace(/%/g, "\\u0025"); + 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"})); + .map(entry => ({...(kind === "clothing" ? defpacks.clientItemRow(rowOf(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")]); + out.push([kind, xtRows(rows.slice(at, at + CHUNK))]); } } return out; }; +// The patched client accepts ordinary clothing rows through xdi as well as +// newly made ones. That lets a moderation rule take effect in an already +// open editor instead of waiting for its next def-pack download. +const sendClothingDefs = ids => { + const rows = [...new Set(ids.map(Number))].map(id => { + const entry = items.get("clothing").get(id); + // A refreshed custom row must retain the extra xdi-only fields. Omitting + // them makes a live client lose its custom name or picture while its + // avatar-use flag is being updated. + return entry ? {...defpacks.clientItemRow(rowOf(entry)), name: entry.name, art: entry.artPending ? "" : entry.art || "", + artMode: entry.artMode || "sticker"} : defpacks.clientItemDef(id); + }).filter(row => row && row.type === TYPE_CLOTHING); + for (let at = 0; at < rows.length; at += CHUNK) { + broadcast("xdi", "clothing", xtRows(rows.slice(at, at + CHUNK))); + } +}; + const announce = entry => { if (entry.pending) { return; @@ -348,6 +368,7 @@ module.exports = { session.sendXt("xdi", -1, ...params); } }, + sendClothingDefs, // lib/world.js says how to reach every game playing. connect(broadcastXt) { broadcast = broadcastXt; diff --git a/lib/dens.js b/lib/dens.js index 261707a..5eeccb5 100644 --- a/lib/dens.js +++ b/lib/dens.js @@ -5,6 +5,7 @@ const accounts = require("./accounts.js"); const achievements = require("./achievements.js"); const config = require("../config.js"); const defpacks = require("./defpacks.js"); +const wearRules = require("./wearrules.js"); const epicDens = require("./epicdens.js"); const masterpieces = require("./masterpieces.js"); const {CURRENCIES, MAX_DEN_ITEMS, hasRoom, activeAvatar, resolvePurchase, isUint} = require("./player.js"); @@ -52,13 +53,21 @@ const LAYER_EYES = "3"; const isMannequin = item => (defpacks.denItemDef(item.def) || {}).specialType === SPECIAL_MANNEQUIN; +const mannequinAvatarType = item => Number((defpacks.denItemDef(item.def) || {}).mannequinAvatarDefId) || 0; + const mannequinOf = item => item.mannequin || {colors: [0, 0, 0], pattern: 0, eyes: 0, worn: [0, 0, 0, 0, 0]}; const mannequinBody = ({colors, pattern, eyes}) => [colors[0], colors[1], pattern, colors[2], eyes]; // the clothing a mannequin of `owner`'s wears, slot by slot (undefined for // an empty slot or a piece the owner no longer has). -const mannequinClothes = (owner, item) => mannequinOf(item).worn.map(inv => (inv ? owner.items.find(piece => piece.inv === inv) : undefined)); +const mannequinClothes = (owner, item) => { + const type = mannequinAvatarType(item); + return mannequinOf(item).worn.map(inv => { + const piece = inv ? owner.items.find(candidate => candidate.inv === inv) : undefined; + return piece && (!type || wearRules.mayWear(piece.def, type)) ? piece : undefined; + }); +}; // for the owner's own list (MannequinData.setupDataInvIdsOnly): the body, // then the five inventory ids. @@ -74,12 +83,13 @@ const mannequinShownFields = (owner, item) => // what the den editor sent for one mannequin, checked: [baseColor, // patternColor, patternDefId, eyeColor, eyeDefId, tail, leg, back, neck, // head]. null when any of it is not a whole number in range. -const readMannequin = (account, fields) => { +const readMannequin = (account, item, fields) => { if (fields.length !== 10 || !fields.every(isUint)) { return null; } const [base, patternColor, pattern, eyeColor, eyes, ...worn] = fields.map(Number); const bodyPart = (defId, layer) => (defId && (defpacks.itemDef(defId) || {}).layerId === layer ? defId : 0); + const type = mannequinAvatarType(item); return { colors: [base, patternColor, eyeColor], pattern: bodyPart(pattern, LAYER_PATTERN), @@ -87,7 +97,7 @@ const readMannequin = (account, fields) => { worn: worn.map((inv, slot) => { const piece = inv && account.items.find(candidate => candidate.inv === inv); const def = piece && defpacks.itemDef(piece.def); - return def && MANNEQUIN_SLOT_LAYERS[slot].includes(def.layerId) ? inv : 0; + return def && MANNEQUIN_SLOT_LAYERS[slot].includes(def.layerId) && (!type || wearRules.mayWear(piece.def, type)) ? inv : 0; }), }; }; @@ -135,7 +145,10 @@ const sendDenState = (session, room, forceReload = true) => { session.sendXt("ds", room.id, placed.length, pets.length, forceReload ? 1 : 0, ...placed.flatMap(item => { const spot = spotOf(item, owner.activeDen); - return [item.inv, item.def, 1, spot.x, spot.y, item.version, spot.flip, "", ...masterpieces.itemFields(item), + // Keep the editor's real placement category. Sending every placed + // object as category 1 made wall/floor items enter the wrong display + // layer when a den was reloaded or another player visited. + return [item.inv, item.def, spot.cat || 1, spot.x, spot.y, item.version, spot.flip, "", ...masterpieces.itemFields(item), ...mannequinShownFields(owner, item), 0]; }), ...pets.flatMap(pet => [pet.inv, pet.lBits, pet.uBits, pet.eBits, PET_CATEGORY, pet.inDen.x, pet.inDen.y, pet.inDen.flip, @@ -404,7 +417,7 @@ const handlers = ({others, findOnline}) => { else { delete item.spots[account.activeDen]; } - const mannequin = isMannequin(item) && readMannequin(account, outfit); + const mannequin = isMannequin(item) && readMannequin(account, item, outfit); if (mannequin) { // A piece of clothing is on one mannequin at a time. for (const other of mannequins) { diff --git a/lib/items.js b/lib/items.js index 86d5cd5..b997ef7 100644 --- a/lib/items.js +++ b/lib/items.js @@ -3,6 +3,7 @@ const accounts = require("./accounts.js"); const achievements = require("./achievements.js"); const defpacks = require("./defpacks.js"); +const wearRules = require("./wearrules.js"); const {CURRENCIES, MAX_ITEMS, MAX_WORN, activeAvatar, addClothing, sendClothingAdded, sendClothingRemoved, resolvePurchase} = require("./player.js"); // clothing: buying, wearing and recycling (client side: ItemXtCommManager). @@ -82,6 +83,13 @@ module.exports = ({others, sendItemList}) => { } const item = account.items.find(candidate => candidate.inv === invIdx); if (item) { + // The client flag only makes the control gray. Never trust it: a + // crafted iu packet or a stale client must not bypass a staff rule. + // Check before changing `on`, so a refused request cannot take off + // an otherwise valid item as a side effect. + if (worn && !wearRules.mayWear(item.def, avatar.type)) { + return null; + } item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId); // no more than MAX_WORN on one animal: what is over stays off. if (worn && account.items.filter(candidate => candidate.on.includes(avatar.avInvId)).length >= MAX_WORN) { diff --git a/lib/minigames.js b/lib/minigames.js index 7989597..732a9d2 100644 --- a/lib/minigames.js +++ b/lib/minigames.js @@ -63,6 +63,10 @@ const CARNIVAL_COST = 5; // gems a go const MAX_TICKETS_PER_GO = 300; const CURRENCY_TICKETS = 1; const INVASION_COST = 10; // gems a go, as the machine's own screen says +const SMOOTHIE_COLOURS = new Set(["purple", "orange", "red", "yellow"]); +// The game's attachment state is client-defined (for example, the cocoa +// recipe). It is not an item id and must never become protocol markup. +const attachmentExtra = value => String(value ?? "").replace(/[\r\n%,]/g, "").slice(0, 128); const awardsPerMinute = limits.limiter(120, 60000); const invitesPerMinute = limits.limiter(20, 60000); @@ -204,6 +208,23 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => { } }; + // Food-machine games reward a short-lived avatar attachment. Replying + // with "_a" is important: MinigameManager turns it into the same local + // attachment action used by den objects, which then sends the normal + // user-communication packet to the room. Sending that packet ourselves + // skips the local state and leaves the player with nothing visible. + const grantAttachment = (session, game, reply, emoticonDefId, extra = "") => { + if (game.attachmentGranted) { + return; + } + const state = attachmentExtra(extra); + if (!defpacks.emoticonMediaId(emoticonDefId)) { + return; + } + game.attachmentGranted = true; + reply("_a", emoticonDefId, state); + }; + // takes the player out of the game they are in, if any, and out of an // invitation. const leave = session => { @@ -450,6 +471,45 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => { // what a game asks of the server while it runs, by game class and then by // the message's first word. `reply` answers the asker as an "mm". const MESSAGES = { + // These machines do not give an inventory item. They award temporary + // Holdable Icons: popcorn (emoticon 1), smoothies (2), and hot cocoa + // (5). The final field carries the selected visual state. + MicroPopcorn: { + _a(session, game, [kind], reply) { + if (kind === "1") { + grantAttachment(session, game, reply, 1); + } + }, + }, + MicroSmoothie: { + _a(session, game, [kind, colour], reply) { + const selected = String(colour || "").toLowerCase(); + if (kind === "2" && SMOOTHIE_COLOURS.has(selected)) { + grantAttachment(session, game, reply, 2, selected); + } + }, + }, + MicroHotCocoa: { + _a(session, game, [kind, cocoaInfo], reply) { + if (kind === "5") { + grantAttachment(session, game, reply, 5, cocoaInfo); + } + }, + }, + CottonCandy: { + _a(session, game, [kind, emoticonInfo], reply) { + if (kind === "30") { + grantAttachment(session, game, reply, 30, emoticonInfo); + } + }, + }, + BradyChemistrySet: { + _a(session, game, [kind, emoticonInfo], reply) { + if (kind === "6") { + grantAttachment(session, game, reply, 6, emoticonInfo); + } + }, + }, // the claw machines: "cp" pays for a go and learns whether the claw // will hold and what on ([won, isDenItem, defId, ?, version]; anything // but 1 or 0 for `won` means "not enough gems"); "cd" keeps (1) or diff --git a/lib/parties.js b/lib/parties.js index 0535362..7efa395 100644 --- a/lib/parties.js +++ b/lib/parties.js @@ -117,7 +117,9 @@ module.exports = ({enterRoom, findOnline, blocks}) => { // PartyManager.customPartyJoinResponse: [success, reason] const joinHosted = (session, host) => { const party = host && partyOf(host); - if (!party || blocks.either(host, session.account)) { + // A one-use staff teleport may inspect a hosted party despite a block; + // ordinary party joins retain the host's privacy rule. + if (!party || (!session.staffTravel && blocks.either(host, session.account))) { session.sendXt("sjp", -1, 0, party ? "BLK" : "NPP"); return; } diff --git a/lib/pets.js b/lib/pets.js index 0bc6465..113e0a4 100644 --- a/lib/pets.js +++ b/lib/pets.js @@ -147,6 +147,14 @@ module.exports = ({others, findOnline, petFields}) => { return; } activeAvatar(account).petInvId = pet ? pet.inv : 0; + if (!pet && session.petPlayerMode) { + session.petPlayerMode = false; + if (session.pos) { + for (const other of [session, ...others(session)]) { + other.sendXt("uc", session.room.id, session.id, "off", "13"); + } + } + } accounts.save(account); const messageRoom = session.room ? session.room.id : -1; session.sendXt("ps", messageRoom, 1, session.id, pet ? pet.inv : 0); @@ -166,6 +174,14 @@ module.exports = ({others, findOnline, petFields}) => { return; } account.pets = account.pets.filter(candidate => candidate !== pet); + if (session.petPlayerMode && activeAvatar(account).petInvId === pet.inv) { + session.petPlayerMode = false; + if (session.pos) { + for (const other of [session, ...others(session)]) { + other.sendXt("uc", session.room.id, session.id, "off", "13"); + } + } + } for (const avatar of account.avatars) { if (avatar.petInvId === pet.inv) { avatar.petInvId = 0; diff --git a/lib/player.js b/lib/player.js index ff1792a..cfe15b4 100644 --- a/lib/player.js +++ b/lib/player.js @@ -1,6 +1,7 @@ "use strict"; const defpacks = require("./defpacks.js"); +const wearRules = require("./wearrules.js"); // accessors over an account's animals, pets and items (shape: accounts.js). // SbiConstants.CURRENCY_NAMES; an item's currencyType indexes into this. @@ -32,13 +33,24 @@ const avatarById = (account, perUserAvId) => const activePet = account => account.pets.find(pet => pet.inv === activeAvatar(account).petInvId) || null; -const wornItems = (account, avatar) => account.items.filter(item => item.on.includes(avatar.avInvId)); +// The persisted state is also filtered here, not only where a player tries +// to put an item on. That keeps an old/corrupt pairing from reaching player +// cards or other people in a room while a dashboard rule is being applied. +const wornItems = (account, avatar) => account.items.filter(item => item.on.includes(avatar.avInvId) + && wearRules.mayWear(item.def, avatar.type)); // item.EquippedAvatars: comma-separated 32-bit words, one bit per avInvId of // an animal wearing the item. -const equippedBits = item => { +// With an account, omit stale pairings that are no longer allowed. The full +// inventory protocol otherwise exposes those bits and a later avatar switch +// can appear to revive a prohibited item. +const equippedBits = (item, account = null) => { const words = [0]; - for (const avInvId of item.on) { + const wornBy = account ? item.on.filter(avInvId => { + const avatar = account.avatars.find(candidate => candidate.avInvId === avInvId); + return avatar && wearRules.mayWear(item.def, avatar.type); + }) : item.on; + for (const avInvId of wornBy) { const word = avInvId >>> 5; while (words.length <= word) { words.push(0); diff --git a/lib/world.js b/lib/world.js index cec88a9..9c17bd8 100644 --- a/lib/world.js +++ b/lib/world.js @@ -404,7 +404,7 @@ const sendItemList = (to, target, full, perUserAvId) => { const {account} = target; const avatar = avatarById(account, perUserAvId); const items = full - ? account.items.flatMap(item => [item.def, item.inv, item.color, equippedBits(item), 0]) + ? account.items.flatMap(item => [item.def, item.inv, item.color, equippedBits(item, account), 0]) : wornItems(account, avatar).flatMap(item => [item.def, item.inv, item.color]); const count = full ? account.items.length : wornItems(account, avatar).length; to.sendXt("il", -1, full ? "0" : "1", 0, avatar.perUserAvId, account.username, avatar.eyes, avatar.pattern, count, ...items); @@ -464,6 +464,9 @@ const sendAvatarCreate = (to, target) => { if (target.invisible) { to.sendXt("xiv", -1, target.id, 1); } + if (target.petPlayerMode) { + to.sendXt("uc", room.id, target.id, "on", "13"); + } minigames.showBubble(to, target); }; @@ -538,7 +541,7 @@ const sendUserVars = session => { }; const findOnline = username => online.get(String(username).toLowerCase()); -const STAFF_WINDOW_COMMANDS = ["warn", "unwarn", "message", "silence", "kick", "summon", "goto", "warnings"]; +const STAFF_WINDOW_COMMANDS = ["warn", "unwarn", "message", "silence", "kick", "summon", "goto", "warnings", "reject"]; 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 @@ -923,6 +926,47 @@ const handlers = { } }, + // The host/event overlay only sends one of these fixed room effects. Its + // permission check lives here as well, so a forged client packet cannot + // change a room. + xrc(session, roomId, [effect]) { + const choice = String(effect || "").toLowerCase(); + if (roles.isActiveStaff(session.account) && roles.can(session.account, "room.effects") + && ["small", "normal", "big", "rainbow", "clear"].includes(choice)) { + commands.run(session, `!roomfx ${choice}`); + } + }, + + // The browser host renders the YouTube iframe; the game receives only a + // validated video id and keeps it shared by the people in this theatre. + xtv(session, roomId, [action, value = ""]) { + const {room} = session; + // Some theatre maps report an internal room path which has no "theatre" + // in it (the visible room title does). Staff permission is the boundary; + // restricting by that unreliable path made Play for room silently fail. + if (!roles.isActiveStaff(session.account) || !roles.can(session.account, "theater.control") || !room) { + return; + } + let videoId = ""; + if (action === "play") { + const text = String(value).trim(); + const match = text.match(/^(?:[A-Za-z0-9_-]{11}|(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([A-Za-z0-9_-]{11})(?:[?&#].*)?)$/i); + videoId = match ? (match[1] || text) : ""; + if (!videoId) { + session.sendXt("xtl", -1, "Paste a YouTube watch, share, or embed link."); + return; + } + } + else if (action !== "stop") { + return; + } + room.theatreVideo = videoId; + for (const viewer of room.sessions) { + viewer.sendXt("xtv", room.id, videoId); + } + modlog.record(session.account.username, videoId ? "played theatre video" : "stopped theatre video", "", room.name); + }, + // 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 @@ -1138,10 +1182,31 @@ const itemsTaken = (account, kind, invs, worn) => { } }; +// A dashboard clothing rule can affect several animals and mannequins at +// once. Their persisted references have already been removed by +// itemcontrol.js; refresh both the owner's full inventory and anyone seeing +// their animal or den so an open game cannot keep displaying the old outfit. +const wearRulesChanged = (account, mannequinChanged = false) => { + const session = findOnline(account.username); + if (session) { + sendItemList(session, session, true); + refreshForOthers(session); + if (mannequinChanged) { + dens.sendDenItems(session); + } + } + if (mannequinChanged) { + const den = rooms.get(`den${account.username}`); + for (const visitor of den ? den.sessions : []) { + dens.sendDenState(visitor, 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. +// online, `toName` in a room. This privileged movement deliberately bypasses +// a full room, locked den, or hosted-party block; regular joins do not. // 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, @@ -1165,13 +1230,15 @@ const staffMove = (whoName, toName) => { 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); } + // staffMove is only reached through permission-checked commands. The flag + // is consumed by enterRoom/joinDen, preserving normal rules for all other + // joins. + who.staffTravel = true; joinRoom(who, room.name); + delete who.staffTravel; if (who.room !== room) { if (spot) { who.sendXt("xgt", -1); @@ -1385,11 +1452,13 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => { if (room && room === session.room) { return; } - // moderators (marked so in the admin panel) are let into a full room, and - // so is a player arriving when every spawn room is full (spawnRoom). + // Moderators, a one-use staff teleport, and a player arriving when every + // spawn room is full (spawnRoom) may enter a full room. const overflow = session.spawnOverflow; + const staffTravel = session.staffTravel === true; session.spawnOverflow = false; - if (room && room.sessions.size >= config.maxUsersPerRoom && !roles.isActiveStaff(session.account) && !overflow) { + delete session.staffTravel; + if (room && room.sessions.size >= config.maxUsersPerRoom && !roles.isActiveStaff(session.account) && !staffTravel && !overflow) { joinFailed(session, "This room is currently full"); return; } @@ -1432,6 +1501,9 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => { room.customMusicDef, worldId); dens.sendRoomProperties(session, roomAsSeenBy(session, room)); + if (room.theatreVideo !== undefined) { + session.sendXt("xtv", room.id, room.theatreVideo); + } for (const other of others(session)) { if (other.pos && sees(session, other)) { @@ -1592,7 +1664,7 @@ const joinRoom = (session, requested) => { let shard = config.shards.find(s => s.id === Number(shardText)) || config.shards.find(s => s.id === session.worldId) || config.shards[0]; // full there: with "Find Open World" on, the same room in a world that // has space (moderators get into a full room anyway). - if (roomFull(`${base}#${shard.id}`) && !session.account.moderator && findOpenWorld(session.account)) { + if (roomFull(`${base}#${shard.id}`) && !roles.isActiveStaff(session.account) && findOpenWorld(session.account)) { shard = config.shards.find(other => !roomFull(`${base}#${other.id}`)) || shard; } enterRoom(session, `${base}#${shard.id}`, base, roomInfo.name(base), shard.id); @@ -1614,7 +1686,8 @@ const joinDen = (session, requested) => { joinFailed(session, `Den "${requested}" does not exist`); return; } - if (!dens.canEnter(owner, session.account) || blocks.has(owner, session.account)) { + const staffTravel = session.staffTravel === true; + if ((!dens.canEnter(owner, session.account) || blocks.has(owner, session.account)) && !staffTravel) { joinFailed(session, "This den is locked"); return; } @@ -1661,7 +1734,11 @@ module.exports = { case "pubMsg": { // UserCommXtCommManager sends "%[%]" and reads it // back in userCommChatResponse as [sfsUserId, text, type, extra]. - if (session.room && session.room.id === msg.roomId) { + // An in-room minigame keeps the player in their world room, but its + // embedded SWF labels outgoing user messages with the minigame's + // temporary sub-room id. Accept that id as well so its attachment + // reward can make the normal round trip back to the avatar. + if (session.room && (session.room.id === msg.roomId || (session.game && session.game.roomId === Number(msg.roomId)))) { // at most text, type and one extra field, and no essays. const fields = decodeEntities(msg.cdata("txt") || "").split("%").slice(0, 3); if (fields[0].length > config.maxChatLength || (fields[2] || "").length > MAX_CHAT_EXTRA) { @@ -1680,10 +1757,42 @@ module.exports = { minigames.bubble(session, fields[0], fields[2]); return; } + // Per-player pet form. It is deliberately a user-communication + // message so every client already in the room updates the same + // avatar, while the normal pet-out state stays unchanged. + if (fields[1] === "13") { + const enabled = fields[0] === "on" && Boolean(activePet(session.account)); + session.petPlayerMode = enabled; + for (const other of [session, ...watchers(session)]) { + other.sendXt("uc", session.room.id, session.id, enabled ? "on" : "off", "13"); + } + return; + } + // Attachment messages carry an emoticon *definition* id from the + // sender, while the recipient's avatar view needs that definition's + // media id. This is the normal path used by den attachments and + // the food-machine minigames. + if (fields[1] === "4") { + const [defId, ...extra] = fields[0].split(","); + if (defId === "0") { + fields[0] = "0,"; + } + else { + const mediaId = defpacks.emoticonMediaId(defId); + if (!mediaId) { + return; + } + fields[0] = `${mediaId},${extra.join(",").replace(/[\r\n%,]/g, "").slice(0, 128)}`; + } + } // typed chat shows as "..." over the sender until the server sends // it back (UserCommXtCommManager.sendChatMessage); everything else // the sender has already shown themselves. const echo = TYPED_CHAT_TYPES.includes(fields[1]); + // An attachment is only drawn after the server sends it back. The + // local client deliberately does not draw it optimistically, unlike + // typed chat and normal emotes. + const attachmentEcho = fields[1] === "4"; // silenced, or chat switched off on the account page: the line // goes nowhere. if (echo && (moderation.isSilenced(session.account) || !accounts.featureOn(session.account, "chat"))) { @@ -1737,7 +1846,7 @@ module.exports = { // 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)) { + for (const recipient of (echo || attachmentEcho) ? session.room.sessions : others(session)) { if (session.invisible && recipient !== session && !roles.isActiveStaff(recipient.account)) { continue; } @@ -1780,6 +1889,7 @@ module.exports = { findOnline, makeColour, sendItemList, + wearRulesChanged, setTheme, // offers left on the account page (lib/trades.js); `refresh` shows a // playing account its inventories as they are now. @@ -1880,10 +1990,11 @@ module.exports = { // the panel's Masterpieces page. A painting waiting for review is an // item its maker cannot use yet; approving it tells them so, by a - // Jam-A-Gram from Animal Jam HQ and at once if they are playing. - approveMasterpiece(id) { + // Jam-A-Gram from Animal Jam HQ and at once if they are playing. `by` + // is who approved it: a moderator's username, or "admin". + approveMasterpiece(id, by) { const maker = masterpieces.creatorOf(id); - if (!masterpieces.approve(id)) { + if (!masterpieces.approve(id, by)) { return false; } if (maker) { diff --git a/test/features.js b/test/features.js index 9d87ecc..78e0e2c 100644 --- a/test/features.js +++ b/test/features.js @@ -172,6 +172,14 @@ const run = async () => { a.xt("mg", subRoom[4], 1, 2, 3); // not signed: no gems await a.nextXt("mg"); assert.ok(nextSerial > 0); + // food machine wins award a temporary avatar attachment rather than an + // inventory entry. + a.xt("mm", subRoom[4], 15, "_a", 1); + assert.deepStrictEqual((await a.nextXt("mm")).slice(2), ["_a", "1", ""]); + // Attachment packets must also return to their sender: that echoed media + // id is what makes the local avatar draw the held item. + a.send(``); + assert.deepStrictEqual((await a.nextXt("uc")).slice(2), [String(annLogin.params.userId), "35,", "4"]); a.xt("rl", subRoom[4], subRoom[4]); a.xt("mj", roomId, 4, 0, 0, -1); // gem Ball takes the room's place const gameRoom = await a.nextXt("rj"); diff --git a/test/restored.js b/test/restored.js index 26e84cb..008d876 100644 --- a/test/restored.js +++ b/test/restored.js @@ -274,6 +274,10 @@ const run = async () => { assert.strictEqual((await panel(`masterpiece?id=${posted.uuid}`)).status, 401); assert.strictEqual((await panel("masterpiece", {id: posted.uuid, action: "approve"}, admin)).status, 200); assert.match((await a.untilXt("ep"))[7], /approved/); + // on show, with who approved it and when: the last approved first + const onShow = (await panel("masterpieces", undefined, admin)).data.approved; + assert.deepStrictEqual(onShow.map(entry => [entry.id, entry.approvedBy]), [[posted.uuid, "admin"]]); + assert.ok(Math.abs(onShow[0].approvedAt - Date.now() / 1000) < 60); const approved = await a.nextXt("di"); assert.strictEqual(approved[approved.indexOf(painting, 5) + 4], "true"); // hung, once Ann is home from the easel: a visitor is told which painting and whose. @@ -316,6 +320,8 @@ const run = async () => { assert.strictEqual((await a.untilXt("db"))[2], "1"); const last = await a.nextXt("di"); assert.ok(!last.includes("2947") && last[last.indexOf(second.uuid) - 1] === "true"); + // approved by nobody, that one + assert.deepStrictEqual((await panel("masterpieces", undefined, admin)).data.approved.map(entry => [entry.id, entry.approvedBy]), [[second.uuid, null]]); a.socket.destroy(); b.socket.destroy();