This commit is contained in:
Snipzil committed 2026-10-20 19:16:08 -04:00
commit 059f059a9e
31 files changed
+2771 -192

No files matched your search

+9 -1
View File
@@ -155,7 +155,7 @@ module.exports = {
// 49 and 50: its link to a colour picker.
// 61: the Owner, Moderator and Verified name tag badges seen by everyone.
// 62: "Custom pictures" in the settings menu, to hide players' item pictures.
buildVersion: env.AJ_BUILD_VERSION || "71",
buildVersion: env.AJ_BUILD_VERSION || "78",
// what the official CDN is asked for; not ours to change.
upstreamBuildVersion: "3",
@@ -327,6 +327,14 @@ module.exports = {
cacheMissesPerTenMinutes: 1500, // a first visit with an empty cache fetches several hundred files
upstreamTimeoutMs: 20000,
maxCacheBytes: Number(env.AJ_MAX_CACHE_MB || 8192) * 1024 * 1024,
// how often at most the packs with custom items in are made again after
// one changes (lib/defpacks.js clientPack); the tests use 0, made at once.
packRemakeMs: env.AJ_PACK_REMAKE_MS === undefined ? 15000 : Number(env.AJ_PACK_REMAKE_MS),
// masterpieces (lib/masterpieces.js): seconds an account must have had
// before it paints one (AJ_MASTERPIECE_MIN_AGE; the tests use 0), and new
// pictures an account may post in any 24 hours.
masterpieceMinAccountAge: env.AJ_MASTERPIECE_MIN_AGE === undefined ? 86400 : Number(env.AJ_MASTERPIECE_MIN_AGE),
masterpiecesPerDay: 10,
maxConnections: 2000,
maxHttpConnections: 2000, // open at once, in all
maxHttpConnectionsPerAddress: 40, // the game opens a good many at once while it loads
+17 -10
View File
@@ -46,7 +46,7 @@ const SCHEMA = `
// fields stored in their own columns rather than in `state`.
const COLUMN_FIELDS = ["id", "username", "salt", "hash", "createdAt"];
// how the game treats the account this session; set again at every login.
const SESSION_FIELDS = ["accountType", "isGuide", "isModerator", "membershipDays", "startInDen", "startRoom"];
const SESSION_FIELDS = ["accountType", "isGuide", "guideRefused", "isModerator", "membershipDays", "startInDen", "startRoom"];
const DEFAULT_MEMBERSHIP_DAYS = 9999;
const MAX_ACCOUNT_TYPE = 5;
const MEMBERSHIP_TYPES = [0, 2]; // non-member, member
@@ -78,7 +78,10 @@ const LOGIN_DAYS_KEPT = 90; // and none older than this: they hold addresses
let db = null;
const byKey = new Map(); // lowercased username -> account
const byId = new Map();
const savedState = new Map(); // account id -> state JSON as last written
// account id -> digest of the state JSON as last written: enough to tell a
// change, without a second copy of every account's state (~13 KB each).
const savedState = new Map();
const stateDigest = json => crypto.createHash("sha256").update(json).digest("base64");
// A name somebody gave up (a rename, a deleted account) is nobody's to take
// for a while: whoever had it is still known by it to the players they met.
const NAME_HELD_DAYS = 30;
@@ -299,13 +302,17 @@ const MAX_START_ROOM = 80;
function setLoginChoices(account, choices) {
const asked = config.loginChoices && choices && typeof choices === "object" ? choices : {};
const whole = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
// member or not, and guide or not, are the player's own choice on any
// server; the rest only with config.loginChoices: another account type
// shows to everyone.
// member or not is the player's own choice on any server; the rest only
// with config.loginChoices: another account type shows to everyone.
const own = choices && typeof choices === "object" ? choices : {};
const type = MEMBERSHIP_TYPES.includes(own.accountType) ? own.accountType : asked.accountType;
account.accountType = whole(type, MAX_ACCOUNT_TYPE) ? type : config.defaultAccountType;
account.isGuide = own.isGuide === true;
// guide (the name tag, the chat bubble, what others see) only for an
// account the admin made one (lib/panel.js); asked for without that, it is
// refused. a guide's own client may leave it off; the official launcher
// asks nothing, and a guide is one.
account.isGuide = account.guideGiven === true && (choices && typeof choices === "object" ? own.isGuide === true : true);
account.guideRefused = own.isGuide === true && account.guideGiven !== true;
account.isModerator = asked.isModerator === true;
account.membershipDays = whole(asked.membershipDays, MAX_MEMBERSHIP_DAYS) ? asked.membershipDays : DEFAULT_MEMBERSHIP_DAYS;
// where to start is the player's to say on any server: their own den in
@@ -331,7 +338,7 @@ const insert = (username, salt, hash, createdAt, state) => {
const result = db.prepare("INSERT INTO accounts (username, username_key, password_salt, password_hash, created_at, state) VALUES (?, ?, ?, ?, ?, ?)")
.run(username, username.toLowerCase(), salt, hash, createdAt, json);
account.id = Number(result.lastInsertRowid);
savedState.set(account.id, json);
savedState.set(account.id, stateDigest(json));
remember(account);
touch(account);
return account;
@@ -381,7 +388,7 @@ const load = () => {
createdAt: row.created_at,
...JSON.parse(row.state),
});
savedState.set(account.id, row.state);
savedState.set(account.id, stateDigest(row.state));
remember(account);
}
importLegacyFile();
@@ -475,7 +482,7 @@ const release = account => {
const changedState = (account, changed) => {
const json = stateJson(account);
if (savedState.get(account.id) !== json) {
if (savedState.get(account.id) !== stateDigest(json)) {
changed.push([account.id, json]);
return true;
}
@@ -583,7 +590,7 @@ const flush = ({some = false} = {}) => {
throw err;
}
for (const [id, json] of changed) {
savedState.set(id, json);
savedState.set(id, stateDigest(json));
}
};
+90 -31
View File
@@ -177,40 +177,89 @@ class Amf3Reader {
// writer for what the reader above produces from a defPack: plain objects,
// arrays (with or without string keys), strings, numbers, booleans and null.
// nothing is written as a reference except repeated strings.
// written into one buffer that grows: a pack is megabytes of small values,
// and a Buffer for each of them took seconds for the item pack.
class Amf3Writer {
constructor() {
this.parts = [];
this.buf = Buffer.allocUnsafe(1 << 16);
this.pos = 0;
this.strings = new Map();
}
room(bytes) {
if (this.pos + bytes > this.buf.length) {
let size = this.buf.length * 2;
while (size < this.pos + bytes) {
size *= 2;
}
const bigger = Buffer.allocUnsafe(size);
this.buf.copy(bigger, 0, 0, this.pos);
this.buf = bigger;
}
}
byte(value) {
this.room(1);
this.buf[this.pos++] = value;
}
u29(value) {
this.room(4);
const {buf} = this;
if (value < 0x80) {
this.parts.push(Buffer.from([value]));
buf[this.pos++] = value;
}
else if (value < 0x4000) {
this.parts.push(Buffer.from([(value >> 7) | 0x80, value & 0x7f]));
buf[this.pos++] = (value >> 7) | 0x80;
buf[this.pos++] = value & 0x7f;
}
else if (value < 0x200000) {
this.parts.push(Buffer.from([(value >> 14) | 0x80, ((value >> 7) & 0x7f) | 0x80, value & 0x7f]));
buf[this.pos++] = (value >> 14) | 0x80;
buf[this.pos++] = ((value >> 7) & 0x7f) | 0x80;
buf[this.pos++] = value & 0x7f;
}
else {
this.parts.push(Buffer.from([(value >> 22) | 0x80, ((value >> 15) & 0x7f) | 0x80, ((value >> 8) & 0x7f) | 0x80, value & 0xff]));
buf[this.pos++] = (value >> 22) | 0x80;
buf[this.pos++] = ((value >> 15) & 0x7f) | 0x80;
buf[this.pos++] = ((value >> 8) & 0x7f) | 0x80;
buf[this.pos++] = value & 0xff;
}
}
string(text) {
if (text === "") {
this.u29(1);
return;
}
else if (this.strings.has(text)) {
this.u29(this.strings.get(text) << 1);
const known = this.strings.get(text);
if (known !== undefined) {
this.u29(known << 1);
return;
}
else {
this.strings.set(text, this.strings.size);
const bytes = Buffer.from(text, "utf8");
this.u29((bytes.length << 1) | 1);
this.parts.push(bytes);
this.strings.set(text, this.strings.size);
// nearly every string of a pack is short and ASCII: its bytes are its
// characters, copied here rather than through Buffer's utf8 writer.
if (text.length < 64) {
let ascii = true;
for (let i = 0; i < text.length; i++) {
if (text.charCodeAt(i) > 0x7f) {
ascii = false;
break;
}
}
if (ascii) {
this.u29((text.length << 1) | 1);
this.room(text.length);
for (let i = 0; i < text.length; i++) {
this.buf[this.pos++] = text.charCodeAt(i);
}
return;
}
}
const length = Buffer.byteLength(text, "utf8");
this.u29((length << 1) | 1);
this.room(length);
this.pos += this.buf.write(text, this.pos, "utf8");
}
pairs(entries) {
@@ -222,45 +271,55 @@ class Amf3Writer {
}
value(value) {
if (value === undefined) {
this.parts.push(Buffer.from([0x00]));
// most values of a pack are strings: asked first
if (typeof value === "string") {
this.byte(0x06);
this.string(value);
}
else if (value === undefined) {
this.byte(0x00);
}
else if (value === null) {
this.parts.push(Buffer.from([0x01]));
this.byte(0x01);
}
else if (typeof value === "boolean") {
this.parts.push(Buffer.from([value ? 0x03 : 0x02]));
this.byte(value ? 0x03 : 0x02);
}
else if (typeof value === "number") {
if (Number.isInteger(value) && value >= -0x10000000 && value < 0x10000000) {
this.parts.push(Buffer.from([0x04]));
this.byte(0x04);
this.u29(value & 0x1fffffff);
}
else {
const bytes = Buffer.alloc(9);
bytes[0] = 0x05;
bytes.writeDoubleBE(value, 1);
this.parts.push(bytes);
this.byte(0x05);
this.room(8);
this.pos = this.buf.writeDoubleBE(value, this.pos);
}
}
else if (typeof value === "string") {
this.parts.push(Buffer.from([0x06]));
this.string(value);
}
else if (Array.isArray(value)) {
this.parts.push(Buffer.from([0x09]));
this.byte(0x09);
this.u29((value.length << 1) | 1);
// string keys set on the array beside its numbered elements.
this.pairs(Object.entries(value).filter(([key]) => !/^\d+$/.test(key)));
// string keys set on the array beside its numbered elements (an array
// with as many keys as elements has none).
const keys = Object.keys(value);
this.pairs(keys.length === value.length ? [] : keys.filter(key => !/^\d+$/.test(key)).map(key => [key, value[key]]));
for (const element of value) {
this.value(element);
}
}
else if (typeof value === "object" && !Buffer.isBuffer(value)) {
// A dynamic object of no class, with its traits written in place.
this.parts.push(Buffer.from([0x0a, 0x0b]));
this.byte(0x0a);
this.byte(0x0b);
this.string("");
// its own keys in Object.keys order, without an array of entries for each object
for (const key in value) {
if (Object.hasOwn(value, key)) {
this.string(key);
this.value(value[key]);
}
}
this.string("");
this.pairs(Object.entries(value));
}
else {
throw new Error("Cannot write this value as AMF3");
@@ -273,6 +332,6 @@ module.exports = {
encode: value => {
const writer = new Amf3Writer();
writer.value(value);
return Buffer.concat(writer.parts);
return writer.buf.subarray(0, writer.pos);
},
};
+100 -11
View File
@@ -3,14 +3,15 @@
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
const defpacks = require("./defpacks.js");
const limits = require("./limits.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.
// ("xdi", which the patched client adds to its tables), and so is a game at
// login if its packs may be older than the item (sendAll).
//
// an item can be taken out of the shop, renamed and repriced, or deleted:
// then it goes from every inventory too (lib/itemcontrol.js).
@@ -29,6 +30,21 @@ 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";
// the fields of a def row the patched client reads from "xdi"
// (ItemXtCommManager.addItemDef, DenXtCommManager.addDenItemDef): the rest of
// the base's row is only weight, ~600 bytes a row and 5000 rows at login.
const CLIENT_FIELDS = {
clothing: ["id", "layerDefId", "layerId", "type", "value", "titleStrId", "isGiftable", "membersOnly", "itemStatus", "enviroType",
"avatarUseFlags", "recycleValue", "currencyType", "defense", "attack", "attackMediaRefId", "combatType", "modifierType",
"modifierValue", "criticalHit", "combinedCost", "colors", "availabilityStartTime", "availabilityEndTime"],
den: ["id", "abbrName", "combinedCost", "cost", "currencyType", "enviroType", "flag", "gameDefId", "itemStatus", "layer",
"mannequinAvatarDefId", "mannequinCatId", "membersOnly", "nameStrId", "parentArrayId", "promoType", "recycleValue",
"scalePercent", "sortCat", "specialType", "typeCat", "availabilityStartTime", "availabilityEndTime", "ecoPower"],
};
// how long a fetch of the packs is taken to describe a game of that address
// that logs in (sendAll). a game logs in minutes after it fetched them.
const PACKS_SEEN_MS = 2 * 3600000;
const MAX_PACKS_SEEN = 100000; // addresses
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,
@@ -38,12 +54,22 @@ const SCHEMA = `CREATE TABLE IF NOT EXISTS custom_items (
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
// address key -> {at, clothing, den, names}: the version (defpacks
// customVersion) of the packs with custom items in that address last
// fetched, the oldest within PACKS_SEEN_MS (players behind one address
// fetch at different times). an entry's `changed` is the version of its last change.
const packsSeen = new Map();
const db = () => accounts.database();
const now = () => Math.floor(Date.now() / 1000);
const baseDef = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id));
// the file name an uploaded music track is asked for by (lib/custommusic.js):
// a new upload is a new name, so no game plays an old copy from its cache.
const audioName = entry => `CustomMusic${entry.id}_${entry.audio}`;
let audioGone = () => {}; // (entry): an uploaded track's item was deleted; set by lib/custommusic.js
// 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 => {
@@ -59,12 +85,34 @@ const rowOf = entry => {
combinedCost: "",
};
if (entry.kind === "den") {
// a music track uploaded by staff (lib/custommusic.js): the game plays
// "audio/<abbrName>.mp3", which the server answers with its file
if (entry.audio) {
own.abbrName = audioName(entry);
}
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);
const apply = entry => {
defpacks.setCustomItem(entry.kind, rowOf(entry), entry.name, entry.inShop);
entry.changed = defpacks.customVersion();
};
// what "xdi" carries of an entry: the fields the client reads, its name and
// picture. clothing goes through the clients' pack transform, so the wear
// rules reach custom items too.
const clientRow = entry => {
const row = entry.kind === "clothing" ? defpacks.clientItemRow(rowOf(entry)) : rowOf(entry);
const out = {};
for (const field of CLIENT_FIELDS[entry.kind]) {
if (row[field] !== undefined) {
out[field] = row[field];
}
}
return {...out, name: entry.name, art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"};
};
// "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
@@ -75,9 +123,7 @@ 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 => ({...(kind === "clothing" ? defpacks.clientItemRow(rowOf(entry)) : rowOf(entry)), name: entry.name,
art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"}));
const rows = entries.filter(entry => entry.kind === kind && !entry.pending).map(clientRow);
for (let at = 0; at < rows.length; at += CHUNK) {
out.push([kind, xtRows(rows.slice(at, at + CHUNK))]);
}
@@ -119,6 +165,7 @@ const fromRow = row => ({
artMode: LOOKS.includes(row.art_mode) ? row.art_mode : "sticker",
pending: row.pending === 1,
artPending: row.art_pending === 1,
audio: /^[0-9a-f]{8,64}$/.test(row.audio || "") ? row.audio : null,
});
// a player-made item (lib/playeritems.js) has the maker's account id;
@@ -143,6 +190,10 @@ const addOwnerColumn = () => {
if (!columns.includes("art_pending")) {
db().exec("ALTER TABLE custom_items ADD COLUMN art_pending INTEGER");
}
// a music track uploaded by staff (lib/custommusic.js): its file's version
if (!columns.includes("audio")) {
db().exec("ALTER TABLE custom_items ADD COLUMN audio TEXT");
}
};
const load = () => {
@@ -233,10 +284,12 @@ const create = (kind, fields, by, ownerId = null, pending = false) => {
return values;
}
const id = Math.max(FIRST_ID - 1, ...items.get(kind).keys()) + 1;
// `fields.audio`: an uploaded music track's version (lib/custommusic.js)
const audio = kind === "den" && /^[0-9a-f]{8,64}$/.test(String(fields.audio || "")) ? String(fields.audio) : null;
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);
audio, seq: made++};
db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at, owner_id, pending, audio) 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, audio);
items.get(kind).set(id, entry);
if (!pending) {
apply(entry);
@@ -281,6 +334,7 @@ const setArtMode = (kind, id, mode) => {
}
entry.artMode = mode;
db().prepare("UPDATE custom_items SET art_mode = ? WHERE kind = ? AND id = ?").run(mode, kind, entry.id);
entry.changed = defpacks.customChanged();
announce(entry);
return {item: entry};
};
@@ -295,6 +349,7 @@ const setArt = (kind, id, art, pending = false) => {
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);
entry.changed = defpacks.customChanged();
announce(entry);
};
@@ -324,6 +379,9 @@ const remove = (kind, id) => {
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);
if (entry.audio) {
audioGone(entry);
}
return {item: entry};
};
@@ -333,6 +391,10 @@ const list = () => KINDS.flatMap(kind => [...items.get(kind).values()])
module.exports = {
KINDS,
FIRST_ID,
audioName,
onAudioGone: callback => {
audioGone = callback;
},
load,
create,
update,
@@ -362,9 +424,36 @@ module.exports = {
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.
// an address was sent a pack with custom items in: "clothing", "den" or
// "names" (lib/defpacks.js customPackKind), made at `version`.
sawPack(key, packKind, version) {
const time = Date.now();
const seen = packsSeen.get(key);
if (seen && time - seen.at < PACKS_SEEN_MS) {
if (seen[packKind] === undefined) {
seen[packKind] = version;
}
return;
}
packsSeen.delete(key);
packsSeen.set(key, {at: time, [packKind]: version});
// the oldest are first
for (const [oldKey, old] of packsSeen) {
if (packsSeen.size <= MAX_PACKS_SEEN && time - old.at < PACKS_SEEN_MS) {
break;
}
packsSeen.delete(oldKey);
}
},
// the custom items a game logging in may not have: those changed since its
// address fetched the packs, and those with a picture (which the packs do
// not carry); every one when the address fetched none lately.
sendAll(session) {
for (const params of messages(list().reverse().filter(entry => !entry.pending))) {
const seen = packsSeen.get(limits.key(session.address));
const fresh = seen && Date.now() - seen.at < PACKS_SEEN_MS && seen.names !== undefined ? seen : null;
const since = kind => (fresh && fresh[kind] !== undefined ? Math.min(fresh[kind], fresh.names) : -1);
const needed = entry => !entry.pending && (entry.changed > since(entry.kind) || (entry.art && !entry.artPending));
for (const params of messages(list().reverse().filter(needed))) {
session.sendXt("xdi", -1, ...params);
}
},
+174
View File
@@ -0,0 +1,174 @@
"use strict";
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const {logText} = require("./logtext.js");
const cdn = require("./cdn.js");
const config = require("../config.js");
const customItems = require("./customitems.js");
const extraMusic = require("./extramusic.js");
// music tracks staff upload in the panels (permission "music.upload",
// lib/roles.js): an MP3 made a den music item while the server runs, as the
// extra tracks of lib/extramusic.js are. each is a custom den item
// (lib/customitems.js) made from the game's "Jam On", with an `audio`
// version of its own: games are sent its def row at once, players get it
// from the item finder (or the shop, if staff put it on sale), and deleting
// it takes it from everyone, as with any custom item.
//
// a den music item plays "audio/<abbrName>.mp3" from the content server
// (DenItemHolder); for these the server answers with the file uploaded, kept
// in data/custom-music/<item id>-<version>.mp3 (the data folder is the one
// place the server writes to).
const MAX_BYTES = 15 * 1024 * 1024;
const MIN_BYTES = 4 * 1024;
const VERSION_LENGTH = 12;
const FOLDER = () => path.join(config.dataDir, "custom-music");
const fileOf = entry => path.join(FOLDER(), `${entry.id}-${entry.audio}.mp3`);
// MPEG audio layer III, as the game's Flash plays it: an ID3v2 tag may come
// first; then a frame header whose next frame is where its length says.
const BITRATES = {
1: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
2: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
};
const SAMPLE_RATES = {3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000]};
// the frame at `at`: {length, sampleRate} or null.
const frameAt = (data, at) => {
if (at + 4 > data.length || data[at] !== 0xFF || (data[at + 1] & 0xE0) !== 0xE0) {
return null;
}
const version = (data[at + 1] >> 3) & 3; // 3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5
const layer = (data[at + 1] >> 1) & 3; // 1 is layer III
const bitrateIndex = data[at + 2] >> 4;
const rateIndex = (data[at + 2] >> 2) & 3;
const padding = (data[at + 2] >> 1) & 1;
if (version === 1 || layer !== 1 || bitrateIndex === 0 || bitrateIndex === 15 || rateIndex === 3) {
return null;
}
const bitrate = BITRATES[version === 3 ? 1 : 2][bitrateIndex] * 1000;
const sampleRate = SAMPLE_RATES[version][rateIndex];
return {length: Math.floor(((version === 3 ? 144 : 72) * bitrate) / sampleRate) + padding, sampleRate};
};
// null for an MP3 the game can play, or what is wrong with it.
const problem = data => {
if (!Buffer.isBuffer(data) || data.length < MIN_BYTES) {
return "That file is too small to be a song.";
}
if (data.length > MAX_BYTES) {
return `That file is too big: ${MAX_BYTES / 1024 / 1024} MB at most.`;
}
let at = 0;
if (data.toString("latin1", 0, 3) === "ID3" && data.length > 10) {
at = 10 + (((data[6] & 0x7F) << 21) | ((data[7] & 0x7F) << 14) | ((data[8] & 0x7F) << 7) | (data[9] & 0x7F)) + (data[5] & 0x10 ? 10 : 0);
}
// the first frame: the header, then two more where their lengths say
for (const end = Math.min(data.length, at + 64 * 1024); at < end; at++) {
const first = frameAt(data, at);
const second = first && frameAt(data, at + first.length);
const third = second && frameAt(data, at + first.length + second.length);
if (third) {
return null;
}
}
return "That is not an MP3 file (MPEG audio layer III).";
};
const tracks = () => customItems.list().filter(entry => entry.kind === "den" && entry.audio);
// content path ("1830/audio/<hash>") -> entry, made again when the tracks change.
let paths = null;
const pathMap = () => {
if (!paths) {
paths = new Map(tracks().map(entry => [cdn.hashedPath(`audio/${customItems.audioName(entry)}.mp3`), entry]));
}
return paths;
};
// what to answer a content request with when it is for one of these
// tracks: {body, type}; undefined when it is not.
const asset = async relPath => {
const entry = pathMap().get(relPath);
if (!entry) {
return undefined;
}
const body = await fs.promises.readFile(fileOf(entry)).catch(() => null);
return {body, type: "audio/mpeg"};
};
// an upload made a track: {item} or {error}. `fields`: {name, cost, inShop, members}.
const add = (data, fields, by) => {
const wrong = problem(data);
if (wrong) {
return {error: wrong};
}
const audio = crypto.createHash("sha256").update(data).digest("hex").slice(0, VERSION_LENGTH);
fs.mkdirSync(FOLDER(), {recursive: true, mode: 0o700});
// written before the item exists, so no game asks for a file not there yet
const waiting = path.join(FOLDER(), `new-${audio}-${process.pid}.mp3`);
fs.writeFileSync(waiting, data, {mode: 0o600});
const result = customItems.create("den", {name: fields.name, cost: fields.cost, members: fields.members,
inShop: fields.inShop === true, base: extraMusic.TEMPLATE, audio}, by);
if (result.error) {
fs.rmSync(waiting, {force: true});
return result;
}
fs.renameSync(waiting, fileOf(result.item));
paths = null;
console.log(`[custom music] ${logText(by)} uploaded "${logText(result.item.name)}" (den item ${logText(result.item.id)}, ${logText(data.length)} bytes)`);
return result;
};
// the file of a track, for staff to listen to before or after: {data} or null.
const file = id => {
const entry = tracks().find(track => track.id === Number(id));
if (!entry) {
return null;
}
const data = (() => {
try {
return fs.readFileSync(fileOf(entry));
}
catch (err) {
return null;
}
})();
return data ? {data, entry} : null;
};
// for the panels: newest first
const list = () => tracks().map(entry => ({id: entry.id, name: entry.name, cost: entry.cost, inShop: entry.inShop,
createdBy: entry.createdBy, createdAt: entry.createdAt,
bytes: (() => {
try {
return fs.statSync(fileOf(entry)).size;
}
catch (err) {
return 0;
}
})()}));
// a track's item was deleted (lib/itemcontrol.js deleteCustom): its file goes too.
customItems.onAudioGone(entry => {
fs.rmSync(fileOf(entry), {force: true});
paths = null;
});
// at start: files of tracks no longer there (and of uploads cut short) go.
const load = () => {
const kept = new Set(tracks().map(entry => path.basename(fileOf(entry))));
let gone = 0;
for (const name of fs.existsSync(FOLDER()) ? fs.readdirSync(FOLDER()) : []) {
if (!kept.has(name)) {
fs.rmSync(path.join(FOLDER(), name), {force: true});
gone++;
}
}
console.log(`[custom music] ${logText(kept.size)} uploaded tracks${gone ? `, ${logText(gone)} stray files removed` : ""}`);
};
module.exports = {MAX_BYTES, problem, asset, add, file, list, load};
+47 -13
View File
@@ -370,24 +370,51 @@ const CLIENT_PACKS = new Map([
[DEF_NAMEBAR_BADGE, () => {}],
]);
const clientPackPaths = new Map([...CLIENT_PACKS.keys()].map(id => [cdn.hashedPath(`defPacks/${id}`), id]));
const clientPackBodies = new Map(); // id -> {day, allOnSale, body}
const clientPackBodies = new Map(); // id -> {day, allOnSale, body, version, madeAt}
const clientPacksChanged = new Set(); // ids whose body is older than a custom item change
const clientPacksMaking = new Map(); // id -> the promise of the body being made
// a pack is made again after a custom item change at most every
// config.packRemakeMs: the item pack takes ~70 ms of the one thread at 5000
// items (~300 ms at 50000), and players make items many times a minute.
// until then the body made before goes out, with the version it has; a
// game logging in is sent what changed after it (lib/customitems.js sendAll).
const deflateRaw = require("util").promisify(zlib.deflateRaw);
// the packs custom items are in: their rows, and their names
const CUSTOM_PACK_KINDS = new Map([[DEF_ITEM, "clothing"], [DEF_DEN_ITEM, "den"], [DEF_LOCALIZATION_EN, "names"]]);
// the pack at `relPath` as clients should get it, or null when it is not
// one of the above (and comes straight from the CDN).
const makeClientPack = async id => {
// the version before the rows are read: a change while it is made counts
// as after, and is sent at login (more than needed, never less)
const version = customVersion;
const pack = await loadChanged(id);
CLIENT_PACKS.get(id)(pack);
// deflated on libuv's threads, not this one
const body = await deflateRaw(amf3.encode(pack));
const made = {day: sales.today(), allOnSale: sales.everythingOnSale(), body, version, madeAt: Date.now()};
clientPackBodies.set(id, made);
if (customVersion === version) {
clientPacksChanged.delete(id);
}
return made;
};
// the pack at `relPath` as clients should get it, {body, version}, or null
// when it is not one of the above (and comes straight from the CDN).
// `version`: customVersion() of the custom items in it.
const clientPack = async relPath => {
const id = clientPackPaths.get(relPath);
if (id === undefined) {
return null;
}
const made = clientPackBodies.get(id);
if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()) {
return made.body;
if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()
&& (!clientPacksChanged.has(id) || Date.now() - made.madeAt < config.packRemakeMs)) {
return made;
}
const pack = await loadChanged(id);
CLIENT_PACKS.get(id)(pack);
const body = zlib.deflateRawSync(amf3.encode(pack));
clientPackBodies.set(id, {day: sales.today(), allOnSale: sales.everythingOnSale(), body});
return body;
if (!clientPacksMaking.has(id)) {
clientPacksMaking.set(id, makeClientPack(id).finally(() => clientPacksMaking.delete(id)));
}
return clientPacksMaking.get(id);
};
// most packs are tables: an object of rows keyed by row index.
@@ -535,8 +562,8 @@ const setCustomItem = (kind, row, name, inShop = true) => {
clothingIds = clothingIds.includes(id) ? clothingIds : [...clothingIds, id];
}
customInShop[kind][inShop ? "add" : "delete"](id);
clientPackBodies.delete(pack);
clientPackBodies.delete(DEF_LOCALIZATION_EN);
clientPacksChanged.add(pack);
clientPacksChanged.add(DEF_LOCALIZATION_EN);
customVersion++;
};
@@ -558,7 +585,7 @@ const unsetCustomItem = (kind, id) => {
clothingIds = clothingIds.filter(one => one !== number);
}
customInShop[kind].delete(number);
clientPackBodies.delete(pack);
clientPacksChanged.add(pack);
customVersion++;
};
@@ -569,6 +596,13 @@ module.exports = {
// the custom items on sale, the newest first.
customShopIds: kind => [...customInShop[kind]].reverse(),
customVersion: () => customVersion,
// a change of a custom item that is not in the packs (its picture): one
// more version, for a game logging in to be told of it
customChanged: () => ++customVersion,
// the avatarUseFlags every clothing row has in the clients' pack (any animal)
EVERY_AVATAR,
// "clothing", "den" or "names" for a pack path with custom items in (lib/customitems.js sawPack), else null.
customPackKind: relPath => CUSTOM_PACK_KINDS.get(clientPackPaths.get(relPath)) || null,
load,
itemDef: id => itemDefs.get(Number(id)),
clothingIds: () => clothingIds,
+115 -4
View File
@@ -24,6 +24,8 @@ const manage = require("./manage.js");
const modpanel = require("./modpanel.js");
const badges = require("./badges.js");
const extraMusic = require("./extramusic.js");
const customMusic = require("./custommusic.js");
const itemControl = require("./itemcontrol.js");
const masterpieces = require("./masterpieces.js");
const panel = require("./panel.js");
const totp = require("./totp.js");
@@ -230,6 +232,75 @@ const itemArtUpload = async (req, res, url, from, signedIn = null, adminSignedIn
send(res, 200, result);
};
// music tracks uploaded in the panels (lib/custommusic.js), at
// /mod/api/music (staff with "music.upload") and /admin/api/music:
// GET: the tracks; GET ?play=<id>: one's file, to listen to;
// POST ?name=&cost=&inShop=1, the MP3 as the body: a new track;
// POST ?delete=<id>: the track deleted, and taken from every player.
// `signedIn` (req) -> account: the moderator panel's session;
// `adminSignedIn` (req) -> boolean: the admin panel's, written down as "admin".
const musicUploads = limits.limiter(30, 3600000); // tracks an hour, per staff member
const musicRoute = async (req, res, url, from, signedIn = null, adminSignedIn = null) => {
res.setHeader("Cache-Control", "no-store");
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
const account = asAdmin ? null : signedIn ? signedIn(req) : null;
if (!asAdmin && !(account && roles.can(account, "music.upload"))) {
send(res, 403, {error: "Your role cannot upload music."});
return;
}
const by = asAdmin ? "admin" : account.username;
if (req.method === "GET" || req.method === "HEAD") {
if (url.searchParams.has("play")) {
const track = customMusic.file(url.searchParams.get("play"));
if (!track) {
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, track.data, "audio/mpeg");
return;
}
send(res, 200, {tracks: customMusic.list(), maxBytes: customMusic.MAX_BYTES});
return;
}
if (req.method !== "POST" || !limits.originAllowed(req)) {
send(res, 403, {error: "forbidden"});
return;
}
if (url.searchParams.has("delete")) {
const entry = customItems.get("den", url.searchParams.get("delete"));
if (!entry || !entry.audio) {
send(res, 404, {error: "No such uploaded track."});
return;
}
const result = itemControl.deleteCustom("den", entry.id, world);
if (result.ok) {
modlog.record(by, "music deleted", "", `den ${entry.id} ${entry.name}`);
}
send(res, result.ok ? 200 : 400, result);
return;
}
if (!asAdmin && !musicUploads.allow(account.id)) {
send(res, 429, {error: "Too many uploads. Try again later."});
return;
}
const data = await readBody(req, customMusic.MAX_BYTES + 1).catch(() => null);
if (!data) {
send(res, 413, {error: `That file is too big: ${customMusic.MAX_BYTES / 1024 / 1024} MB at most.`});
return;
}
const result = customMusic.add(data, {name: url.searchParams.get("name"), cost: url.searchParams.get("cost") || 0,
inShop: url.searchParams.get("inShop") === "1"}, by);
if (result.error) {
send(res, 400, result);
return;
}
modlog.record(by, "music uploaded", "", `den ${result.item.id} ${result.item.name}`);
send(res, 200, {ok: `"${result.item.name}" is den item ${result.item.id}. Players can get it from the item finder now${result.item.inShop ? ", and the shop" : ""}.`,
item: {id: result.item.id, name: result.item.name}});
};
// 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) => {
@@ -361,6 +432,7 @@ const CAPTCHA_PAGE_HEADERS = {...PAGE_HEADERS, "Content-Security-Policy": captch
// write, from config.js.
const LEGAL_VALUES = {legalEmail: config.legalEmail, adminEmail: config.adminEmail, operator: config.operator, hostedIn: config.hostedIn,
version: config.termsVersion, site: new URL(config.siteUrl).host};
const MAX_RULES_LENGTH = 65536; // characters of data/rules.txt the game is sent
const escapeHtml = text => String(text).replace(/[&<>"]/g, sign => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;"})[sign]);
const sendLegalPage = async (res, file) => {
for (const [name, value] of Object.entries(PAGE_HEADERS)) {
@@ -731,6 +803,10 @@ const handle = async (req, res) => {
await itemArtUpload(req, res, url, from, null, panel.signedIn);
return;
}
if (url.pathname === "/admin/api/music") {
await musicRoute(req, res, url, from, null, panel.signedIn);
return;
}
await panel.handle(req, res, url, from, {send, readJson});
return;
}
@@ -757,6 +833,10 @@ const handle = async (req, res) => {
await itemArtUpload(req, res, url, from, modpanel.signedInAs);
return;
}
if (isMod && url.pathname === "/mod/api/music") {
await musicRoute(req, res, url, from, modpanel.signedInAs);
return;
}
if (isMod) {
await modpanel.handle(req, res, url, from, {send, readJson});
return;
@@ -981,13 +1061,38 @@ const handle = async (req, res) => {
return;
}
const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024));
const uuid = await masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
const {uuid, refusal, maker} = await masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
// the game only says it could not be sent: HQ says why
if (refusal && maker) {
world.tellAccount(maker, refusal);
}
send(res, 200, uuid ? {success: true, uuid} : {success: false});
return;
}
case "GET /crossdomain.xml":
send(res, 200, CROSS_DOMAIN, "text/xml");
return;
// the game's rules window (AJClient.showRules) shows this file, read
// again on every ask so it can be changed on a running server; made
// with a placeholder when there is none.
case "GET /rules.txt": {
const file = path.join(config.dataDir, "rules.txt");
let text;
try {
text = await fs.promises.readFile(file, "utf8");
}
catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
text = "Example\n";
await fs.promises.writeFile(file, text, {flag: "wx"}).catch(() => {});
}
res.setHeader("Cache-Control", "no-cache");
res.setHeader("X-Content-Type-Options", "nosniff");
send(res, 200, text.slice(0, MAX_RULES_LENGTH), "text/plain; charset=utf-8");
return;
}
case "GET /gameClient/game/index.html":
// not to be put in a frame of anyone's; the client shows it in a view of its own.
res.setHeader("X-Frame-Options", "DENY");
@@ -1043,15 +1148,21 @@ const handle = async (req, res) => {
send(res, body ? 200 : 404, body || "Not found", body ? MIME[".swf"] : "text/plain");
return;
}
// the extra den music tracks, which the CDN does not have as files.
const extra = await extraMusic.asset(relPath);
// the extra den music tracks, which the CDN does not have as files, and
// those uploaded by staff.
const extra = await extraMusic.asset(relPath) || await customMusic.asset(relPath);
if (extra) {
send(res, extra.body ? 200 : 404, extra.body || "Not found", extra.body ? extra.type : "text/plain");
return;
}
const clientPack = await defpacks.clientPack(relPath);
if (clientPack) {
send(res, 200, clientPack, "application/octet-stream");
// what custom items this game has from its packs (customItems.sendAll)
const packKind = defpacks.customPackKind(relPath);
if (packKind) {
customItems.sawPack(from.key, packKind, clientPack.version);
}
send(res, 200, clientPack.body, "application/octet-stream");
return;
}
// A room file in a seasonal theme ("<build>/roomDefs/theme_<other
+212
View File
@@ -0,0 +1,212 @@
"use strict";
// a picture's fingerprint, to know a masterpiece again when it comes back
// re-encoded (lib/masterpieces.js): the Art Studio paints a saved .ajart
// again a little differently, so the JPEG's bytes differ while every 8 by 8
// block's average stays within a fraction of a step.
//
// the fingerprint is the average of each block, per component, read from
// the JPEG's DC coefficients alone (no inverse DCT): a baseline JPEG (what
// the Art Studio writes) with no subsampling and no restart markers. any
// other JPEG has none, and only its exact bytes are known again.
//
// layout: [width (uint16), height (uint16), components (uint8)], then a byte
// per block and component, block by block in rows.
const HEADER = 5;
const SAME_WITHIN = 2; // of 255, per block: a mark of a few pixels moves its block by more
const THUMB = 16; // the thumbnail's side, for finding candidates quickly
// a Huffman table as JPEG decoders keep it: per code length the smallest
// and largest code and where its values start.
const huffmanTable = (counts, values) => {
const minCode = new Int32Array(17);
const maxCode = new Int32Array(18).fill(-1);
const valPtr = new Int32Array(17);
let code = 0;
let k = 0;
for (let length = 1; length <= 16; length++) {
valPtr[length] = k;
minCode[length] = code;
code += counts[length - 1];
k += counts[length - 1];
maxCode[length] = counts[length - 1] ? code - 1 : -1;
code <<= 1;
}
maxCode[17] = 0x7FFFFFFF;
return {minCode, maxCode, valPtr, values};
};
// the fingerprint of a JPEG, or null.
const fingerprint = buf => {
try {
return read(buf);
}
catch (err) {
return null;
}
};
const read = buf => {
const tables = {};
const quant = {};
let frame = null;
let scan = null;
let at = 2;
while (!scan) {
if (at + 4 > buf.length || buf[at] !== 0xFF) {
return null;
}
const marker = buf[at + 1];
const length = buf.readUInt16BE(at + 2);
const body = buf.subarray(at + 4, at + 2 + length);
if (marker === 0xDB) {
for (let p = 0; p + 65 <= body.length; p += 65) {
if (body[p] >> 4) {
return null; // 16-bit tables: not the Art Studio's
}
quant[body[p] & 15] = body[p + 1];
}
}
else if (marker === 0xC4) {
for (let p = 0; p + 17 <= body.length;) {
const counts = body.subarray(p + 1, p + 17);
const total = counts.reduce((sum, count) => sum + count, 0);
tables[(body[p] >> 4 ? "ac" : "dc") + (body[p] & 15)] = huffmanTable(counts, body.subarray(p + 17, p + 17 + total));
p += 17 + total;
}
}
else if (marker === 0xC0 || marker === 0xC1) {
const comps = body[5];
frame = {height: body.readUInt16BE(1), width: body.readUInt16BE(3), comps: []};
for (let c = 0; c < comps; c++) {
if (body[7 + c * 3] !== 0x11) {
return null; // subsampled
}
frame.comps.push(body[8 + c * 3]);
}
}
else if (marker === 0xDD || (marker >= 0xC2 && marker <= 0xCF && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC)) {
return null; // restart markers, progressive, lossless or arithmetic
}
else if (marker === 0xDA) {
scan = [];
for (let c = 0; c < body[0]; c++) {
scan.push({dc: tables[`dc${body[2 + c * 2] >> 4}`], ac: tables[`ac${body[2 + c * 2] & 15}`]});
}
}
at += 2 + length;
}
if (!frame || frame.width < 1 || frame.height < 1 || scan.length !== frame.comps.length || scan.length < 1 || scan.length > 3
|| scan.some(table => !table.dc || !table.ac) || frame.comps.some(id => quant[id] === undefined)) {
return null;
}
// the entropy-coded data, its 0xFF bytes followed by a stuffed 0x00
let pos = at;
let bits = 0;
let left = 0;
const bit = () => {
if (left === 0) {
if (pos >= buf.length) {
throw new Error("ran out");
}
bits = buf[pos++];
if (bits === 0xFF) {
if (buf[pos] !== 0) {
throw new Error("marker in the data");
}
pos++;
}
left = 8;
}
left--;
return (bits >> left) & 1;
};
const decode = table => {
let code = bit();
let length = 1;
while (code > table.maxCode[length]) {
code = (code << 1) | bit();
if (++length > 16) {
throw new Error("bad code");
}
}
return table.values[table.valPtr[length] + code - table.minCode[length]];
};
const receive = size => {
let value = 0;
for (let i = 0; i < size; i++) {
value = (value << 1) | bit();
}
return value < 1 << (size - 1) ? value - (1 << size) + 1 : value;
};
const across = Math.ceil(frame.width / 8);
const down = Math.ceil(frame.height / 8);
const comps = scan.length;
const out = Buffer.alloc(HEADER + across * down * comps);
out.writeUInt16BE(frame.width, 0);
out.writeUInt16BE(frame.height, 2);
out[4] = comps;
const predicted = new Int32Array(comps);
for (let block = 0; block < across * down; block++) {
for (let c = 0; c < comps; c++) {
const size = decode(scan[c].dc);
predicted[c] += size ? receive(size) : 0;
// the DC coefficient is eight times the block's average, less 128
const average = Math.round(predicted[c] * quant[frame.comps[c]] / 8 + 128);
out[HEADER + block * comps + c] = Math.max(0, Math.min(255, average));
for (let k = 1; k < 64;) {
const runSize = decode(scan[c].ac);
if ((runSize & 15) === 0) {
if (runSize >> 4 !== 15) {
break; // end of block
}
k += 16;
continue;
}
k += runSize >> 4;
receive(runSize & 15);
k++;
}
}
}
return out;
};
// the first component (brightness) in THUMB by THUMB, to find candidates
// among many fingerprints before comparing whole ones.
const thumbnail = print => {
const across = Math.ceil(print.readUInt16BE(0) / 8);
const down = Math.ceil(print.readUInt16BE(2) / 8);
const comps = print[4];
const sums = new Float64Array(THUMB * THUMB);
const counts = new Float64Array(THUMB * THUMB);
for (let y = 0; y < down; y++) {
for (let x = 0; x < across; x++) {
const cell = Math.floor(y * THUMB / down) * THUMB + Math.floor(x * THUMB / across);
sums[cell] += print[HEADER + (y * across + x) * comps];
counts[cell]++;
}
}
return Buffer.from(sums.map((sum, cell) => (counts[cell] ? Math.round(sum / counts[cell]) : 0)));
};
// could these two be the same picture? (thumbnails: a cheap first look)
const thumbnailsClose = (one, other) => one.length === other.length && one.every((value, i) => Math.abs(value - other[i]) <= SAME_WITHIN);
// the same picture: the same size, and no block further apart than a step or two.
const samePicture = (one, other) => {
if (!one || !other || one.length !== other.length || one.compare(other, 0, HEADER, 0, HEADER) !== 0) {
return false;
}
for (let i = HEADER; i < one.length; i++) {
if (Math.abs(one[i] - other[i]) > SAME_WITHIN) {
return false;
}
}
return true;
};
module.exports = {fingerprint, thumbnail, thumbnailsClose, samePicture};
+215 -21
View File
@@ -7,6 +7,7 @@ const config = require("../config.js");
const accounts = require("./accounts.js");
const limits = require("./limits.js");
const imageModeration = require("./image-moderation.js");
const jpegPrint = require("./jpegprint.js");
// masterpieces: paintings from the Art Studio, framed and hung in a den
// (client side: game.artStudioPainting.ArtStudioPainting, the same in
@@ -45,6 +46,23 @@ const SCHEMA = `
likes TEXT NOT NULL,
image BLOB NOT NULL
);
-- every picture taken in, for the daily limit (pictures thrown away
-- unframed count too)
CREATE TABLE IF NOT EXISTS masterpiece_uploads (
creator_id INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS masterpiece_uploads_by ON masterpiece_uploads (creator_id, created_at);
-- pictures a moderator or the admin approved once: the same picture
-- again, the same file (SHA-256) or the same painting saved and painted
-- again (its fingerprint, lib/jpegprint.js), is approved as it is framed
CREATE TABLE IF NOT EXISTS masterpiece_approved_pictures (
hash TEXT PRIMARY KEY,
approved_at INTEGER NOT NULL,
approved_by TEXT NOT NULL,
fingerprint BLOB,
thumb BLOB
);
`;
const UPLOADED = 0; // posted, not made into an item yet
@@ -79,19 +97,35 @@ const fileOf = id => path.join(folder(), `${id}.jpg`);
const GALLERY_SPOTS = 12; // PartyManager.setupMasterpiecesInRoom
const uploadsPerHour = limits.limiter(30, 3600000);
const DAY = 86400;
const AUTO_APPROVER = "auto"; // reviewedBy of a painting approved for a picture approved before
const now = () => Math.floor(Date.now() / 1000);
const db = () => accounts.database();
const known = new Map(); // id -> {id, creator, createdAt, status, frame, reviewedAt, reviewedBy, likes: [account ids]}
const known = new Map(); // id -> {id, creator, createdAt, status, frame, reviewedAt, reviewedBy, likes: [account ids], hash}
const approvedPictures = new Map(); // hash -> thumbnail of its fingerprint, or null: masterpiece_approved_pictures
const tokens = new Map(); // upload token -> {account id, expires (ms)}
const load = () => {
db().exec(SCHEMA);
// who approved it: a moderator's username, "admin", or null when nobody
// looked (review was off, or it was approved before this was kept).
if (!db().prepare("PRAGMA table_info(masterpieces)").all().some(column => column.name === "reviewed_by")) {
const columns = db().prepare("PRAGMA table_info(masterpieces)").all().map(column => column.name);
if (!columns.includes("reviewed_by")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN reviewed_by TEXT");
}
// the picture's SHA-256 (hashOf) and fingerprint (lib/jpegprint.js), to know it again
if (!columns.includes("hash")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN hash TEXT");
}
if (!columns.includes("fingerprint")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN fingerprint BLOB");
}
const pictureColumns = db().prepare("PRAGMA table_info(masterpiece_approved_pictures)").all().map(column => column.name);
if (!pictureColumns.includes("fingerprint")) {
db().exec("ALTER TABLE masterpiece_approved_pictures ADD COLUMN fingerprint BLOB");
db().exec("ALTER TABLE masterpiece_approved_pictures ADD COLUMN thumb BLOB");
}
fs.mkdirSync(folder(), {recursive: true});
// pictures still in the table move out into files, once.
for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) {
@@ -99,16 +133,138 @@ const load = () => {
fs.writeFileSync(fileOf(row.id), Buffer.from(picture));
db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id);
}
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, reviewed_at, reviewed_by, likes FROM masterpieces").all()) {
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, reviewed_at, reviewed_by, likes, hash FROM masterpieces").all()) {
known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame,
reviewedAt: row.reviewed_at, reviewedBy: row.reviewed_by, likes: JSON.parse(row.likes)});
reviewedAt: row.reviewed_at, reviewedBy: row.reviewed_by, likes: JSON.parse(row.likes), hash: row.hash || null});
}
for (const row of db().prepare("SELECT hash, thumb FROM masterpiece_approved_pictures").all()) {
approvedPictures.set(row.hash, row.thumb ? Buffer.from(row.thumb) : null);
}
backfill();
};
const hashOf = image => crypto.createHash("sha256").update(image).digest("hex");
const printOf = painting => {
const row = db().prepare("SELECT fingerprint FROM masterpieces WHERE id = ?").get(painting.id);
return row && row.fingerprint ? Buffer.from(row.fingerprint) : null;
};
// the approved pictures (their hashes) that this picture is: the same file,
// or the same painting by its fingerprint.
const approvedMatches = (hash, print) => {
const found = approvedPictures.has(hash) ? [hash] : [];
if (print) {
const thumb = jpegPrint.thumbnail(print);
for (const [other, otherThumb] of approvedPictures) {
if (other !== hash && otherThumb && jpegPrint.thumbnailsClose(thumb, otherThumb)) {
const row = db().prepare("SELECT fingerprint FROM masterpiece_approved_pictures WHERE hash = ?").get(other);
if (row && row.fingerprint && jpegPrint.samePicture(print, Buffer.from(row.fingerprint))) {
found.push(other);
}
}
}
}
return found;
};
const pictureApproved = (hash, print) => Boolean(hash) && approvedMatches(hash, print).length > 0;
const notePictureApproved = (painting, print) => {
const thumb = print ? jpegPrint.thumbnail(print) : null;
db().prepare("INSERT OR IGNORE INTO masterpiece_approved_pictures (hash, approved_at, approved_by, fingerprint, thumb) VALUES (?, ?, ?, ?, ?)")
.run(painting.hash, painting.reviewedAt || now(), painting.reviewedBy, print, thumb);
if (!approvedPictures.has(painting.hash)) {
approvedPictures.set(painting.hash, thumb);
}
};
// paintings from before pictures were known again get their hash and
// fingerprint, a few at a time after start (each is a file read and some
// milliseconds of decoding, on the thread the game shares); those a person
// approved make their pictures approved ones.
const BACKFILL_BATCH = 20;
const backfill = () => {
const missing = db().prepare("SELECT id FROM masterpieces WHERE fingerprint IS NULL OR hash IS NULL").all().map(row => row.id);
const notedAgain = db().prepare("SELECT hash FROM masterpiece_approved_pictures WHERE fingerprint IS NULL").all().map(row => row.hash);
const step = () => {
for (const id of missing.splice(0, BACKFILL_BATCH)) {
const painting = known.get(id);
let image = null;
try {
image = painting ? fs.readFileSync(fileOf(id)) : null;
}
catch (err) {
image = null;
}
if (!image) {
continue;
}
painting.hash = hashOf(image);
const print = jpegPrint.fingerprint(image);
db().prepare("UPDATE masterpieces SET hash = ?, fingerprint = ? WHERE id = ?").run(painting.hash, print, id);
if (painting.status === APPROVED && painting.reviewedBy && painting.reviewedBy !== AUTO_APPROVER) {
notePictureApproved(painting, print);
}
}
// pictures approved before fingerprints were kept: from a painting of
// theirs, once every painting has its own
for (const hash of missing.length ? [] : notedAgain.splice(0, BACKFILL_BATCH)) {
const row = db().prepare("SELECT fingerprint FROM masterpieces WHERE hash = ? AND fingerprint IS NOT NULL").get(hash);
if (row) {
const print = Buffer.from(row.fingerprint);
const thumb = jpegPrint.thumbnail(print);
db().prepare("UPDATE masterpiece_approved_pictures SET fingerprint = ?, thumb = ? WHERE hash = ?").run(print, thumb, hash);
approvedPictures.set(hash, thumb);
}
}
if (missing.length || notedAgain.length) {
setTimeout(step, 200).unref();
}
};
if (missing.length || notedAgain.length) {
setTimeout(step, 1000).unref();
}
};
// why this account may not paint for a frame now, as words for the player,
// or null when it may: too new an account (asked at the easel, step 1), or
// as many new pictures in the last 24 hours as a day allows (asked of a
// picture not approved before, step 2). `whenFree` speaks of the wait.
const whenFree = seconds => {
const hours = Math.ceil(seconds / 3600);
return hours > 1 ? `in ${hours} hours` : `in ${Math.max(1, Math.ceil(seconds / 60))} minutes`;
};
const tooNew = account => {
const age = now() - (Number(account.createdAt) || 0);
if (age < config.masterpieceMinAccountAge) {
return `Accounts can make Masterpieces once they are a day old. Try again ${whenFree(config.masterpieceMinAccountAge - age)}.`;
}
return null;
};
const tooMany = account => {
const recent = db().prepare("SELECT created_at FROM masterpiece_uploads WHERE creator_id = ? AND created_at > ? ORDER BY created_at")
.all(account.id, now() - DAY);
const perDay = config.masterpiecesPerDay;
if (recent.length >= perDay) {
return `You can make ${perDay} new Masterpieces a day. Try again ${whenFree(recent[recent.length - perDay].created_at + DAY - now())}.`;
}
return null;
};
const needsReview = () => accounts.setting(REVIEW_SETTING) !== "0";
const setNeedsReview = on => accounts.setSetting(REVIEW_SETTING, on ? "1" : "0");
const forget = id => {
// `unapprove`: it was taken back by staff, so its picture is no longer one
// approved before (a painting thrown away unframed leaves it alone).
const forget = (id, unapprove = false) => {
const painting = known.get(id);
if (unapprove && painting && painting.hash) {
for (const hash of approvedMatches(painting.hash, printOf(painting))) {
db().prepare("DELETE FROM masterpiece_approved_pictures WHERE hash = ?").run(hash);
approvedPictures.delete(hash);
}
}
known.delete(id);
db().prepare("DELETE FROM masterpieces WHERE id = ?").run(id);
fs.rmSync(fileOf(id), {force: true});
@@ -126,6 +282,7 @@ const sweep = () => {
forget(painting.id);
}
}
db().prepare("DELETE FROM masterpiece_uploads WHERE created_at <= ?").run(now() - DAY);
};
setInterval(() => {
try {
@@ -136,8 +293,12 @@ setInterval(() => {
}
}, 600000).unref();
// A token for one upload by this account (step 1).
// A token for one upload by this account (step 1), or null when it is
// `tooNew`, which says why.
const issueToken = account => {
if (tooNew(account)) {
return null;
}
for (const [token, entry] of tokens) {
if (entry.account === account.id) {
tokens.delete(token);
@@ -189,20 +350,33 @@ const looksLikeJpeg = image => {
return false;
};
// 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.
// step 2. resolves to {uuid}, the new painting's id, or {uuid: null} when
// the token is not good, the picture is not a JPEG of a sane size, or the
// account has posted too many; with `refusal` and `maker` when the player
// should be told why.
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;
return {uuid: null};
}
// a picture approved before is not a new one and does not count
const hash = hashOf(image);
const print = jpegPrint.fingerprint(image);
const approvedBefore = pictureApproved(hash, print);
const maker = accounts.byId(entry.account);
const refusal = maker && !approvedBefore ? tooNew(maker) || tooMany(maker) : null;
if (!maker || refusal) {
return {uuid: null, refusal, maker};
}
const safety = await imageModeration.scan(image);
if (safety.blocked) {
console.log(`[masterpieces] rejected unsafe upload from account ${entry.account}`);
return null;
return {uuid: null};
}
if (!approvedBefore) {
db().prepare("INSERT INTO masterpiece_uploads (creator_id, created_at) VALUES (?, ?)").run(entry.account, now());
}
// one painting at a time is between the easel and the frame.
for (const painting of [...known.values()]) {
@@ -210,12 +384,12 @@ const upload = async (token, image) => {
forget(painting.id);
}
}
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, reviewedAt: null, reviewedBy: null, likes: []};
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, reviewedAt: null, reviewedBy: null, likes: [], hash};
fs.writeFileSync(fileOf(painting.id), image);
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image) VALUES (?, ?, ?, ?, ?, '[]', ?)")
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE);
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image, hash, fingerprint) VALUES (?, ?, ?, ?, ?, '[]', ?, ?, ?)")
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE, hash, print);
known.set(painting.id, painting);
return painting.id;
return {uuid: painting.id};
};
// `by`: who approved it, when someone did.
@@ -239,11 +413,19 @@ const claimable = (account, id, frame) => {
};
// step 3, paid for: the painting is an item now. true when it is approved
// on the spot.
// on the spot: review is off, or its picture was approved before.
const claim = (id, frame) => {
const painting = known.get(String(id));
painting.frame = frame;
setStatus(painting, needsReview() ? PENDING : APPROVED);
if (!needsReview()) {
setStatus(painting, APPROVED);
}
else if (pictureApproved(painting.hash, printOf(painting))) {
setStatus(painting, APPROVED, AUTO_APPROVER);
}
else {
setStatus(painting, PENDING);
}
return painting.status === APPROVED;
};
@@ -278,14 +460,26 @@ const mayView = (id, address, addressOf) => {
return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address);
};
// `by`: the moderator's username, or "admin".
// `by`: the moderator's username, or "admin". its picture is approved from
// now on, and the same picture waiting in other paintings is approved with
// it. the paintings approved, none when `id` was not waiting.
const approve = (id, by) => {
const painting = get(id);
if (!painting || painting.status !== PENDING) {
return false;
return [];
}
setStatus(painting, APPROVED, by);
return true;
if (!painting.hash) {
return [painting];
}
const print = printOf(painting);
notePictureApproved(painting, print);
const twins = [...known.values()].filter(other => other.status === PENDING
&& (other.hash === painting.hash || (print && jpegPrint.samePicture(print, printOf(other)))));
for (const twin of twins) {
setStatus(twin, APPROVED, AUTO_APPROVER);
}
return [painting, ...twins];
};
// is a den item fit to be shown, traded and recycled? anything that is not
@@ -362,7 +556,7 @@ const frameList = listId =>
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
module.exports = {
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
load, issueToken, tooNew, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
needsReview, setNeedsReview, madeBy,
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
};
+8 -1
View File
@@ -464,8 +464,15 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
},
};
// refused to an account under a day old: the game shows its "could not
// send" popup, and a plain message box ("xtl") says why.
const uploadToken = (session, game, [, purpose], reply) => {
reply("tkn", 1, 0, masterpieces.issueToken(session.account), 0, purpose === undefined ? 1 : Number(purpose) || 1);
const token = masterpieces.issueToken(session.account);
if (!token) {
const why = masterpieces.tooNew(session.account) || "Your Masterpiece could not be sent. Try again later.";
session.sendXt("xtl", -1, why.replace(/%/g, " percent"));
}
reply("tkn", token ? 1 : 0, 0, token || "", 0, purpose === undefined ? 1 : Number(purpose) || 1);
};
// what a game asks of the server while it runs, by game class and then by
+12 -1
View File
@@ -395,7 +395,7 @@ const PAGE_HEADERS = {
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Content-Security-Policy": captcha.policy("default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
"Content-Security-Policy": captcha.policy("default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; media-src 'self'; font-src 'self'; "
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'"),
};
@@ -670,6 +670,17 @@ const handle = async (req, res, url, from, web) => {
return;
}
// the mod log (lib/modlog.js): what staff did, as the admin panel's
// Moderators page shows it.
if (route === "GET /mod/api/modlog") {
if (!roles.can(mod, "staff.log")) {
reply(403, {error: "Your role does not allow that."});
return;
}
reply(200, {log: modlog.recent()});
return;
}
// everything else shows players and what they did: not for a role that
// only makes things.
if (!roles.can(mod, "player.view")) {
+39 -1
View File
@@ -149,6 +149,7 @@ const accountRow = (account, playing) => {
twoStep: totp.isOn(account),
discord: account.discord,
adminDashboardAccess: Boolean(account.adminDashboardAccess),
guide: account.guideGiven === true,
bio: account.bio,
badges: account.badges,
featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)),
@@ -382,6 +383,13 @@ const gift = (account, body) => {
const MAX_QUEST_LEVEL = 100;
// a password for a player who lost theirs: read out or pasted to them, so
// nothing that looks like something else (0 O, 1 l I).
const TEMP_PASSWORD_LETTERS = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
const TEMP_PASSWORD_LENGTH = 12;
const randomPassword = () => Array.from({length: TEMP_PASSWORD_LENGTH},
() => TEMP_PASSWORD_LETTERS[crypto.randomInt(TEMP_PASSWORD_LETTERS.length)]).join("");
const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null);
// returns {ok: text} or {error: text}.
@@ -534,6 +542,36 @@ const act = (account, body) => {
`+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`);
return {ok: `${name}'s permissions are saved.`};
}
// guide: lets the player log in as one (lib/accounts.js setLoginChoices).
// it shows from their next login.
// lost access: a new random password, shown here once. it signs them out
// everywhere (lib/accounts.js setPassword); with `twoStepOff` their 2FA
// goes as well, for a lost authenticator.
case "tempPassword": {
let password = randomPassword();
// the account rules want a capital, a small letter and a digit, and no
// common word or the username in it: draw again until it has them.
while (accounts.setPassword(account, password)) {
password = randomPassword();
}
const twoStepOff = body.twoStepOff === true && totp.isOn(account);
if (twoStepOff) {
totp.turnOff(account);
}
accounts.save(account);
world.disconnect(account);
manage.forget(account);
modpanel.forget(account);
modlog.record("admin", "temporary password set", account.username, twoStepOff ? "2FA turned off" : "");
return {ok: `${name}'s password is now ${password}${twoStepOff ? " and their 2FA is off" : ""}. Ask them to change it on their account page.`, password};
}
case "guide": {
const on = body.on === true;
account.guideGiven = on;
accounts.save(account);
modlog.record("admin", on ? "made a guide" : "no longer a guide", account.username, "");
return {ok: on ? `${name} is a guide from their next login.` : `${name} is no longer a guide from their next login.`};
}
case "adminDashboardAccess": {
const on = body.on === true;
if (on && !account.discordId) {
@@ -600,7 +638,7 @@ const PAGE_HEADERS = {
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; media-src 'self'; font-src 'self'; "
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'",
};
+38 -18
View File
@@ -3,7 +3,7 @@
const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const defpacks = require("./defpacks.js");
const {activeAvatar, isUint} = require("./player.js");
const {activeAvatar, activePet, isUint} = require("./player.js");
// pets (client side: PetManager, PetXtCommManager). A pet's species and look
// are packed into three integers by PetManager.packPetBits; the species is
@@ -30,6 +30,13 @@ const MASTERY_FULL = 100;
const MASTERY_PER_ROOM = 5;
const MASTERY_BITS = 0xF00; // the part of uBits PetInventory writes
const SECONDS_TO_HATCH = 259200; // PetManager.hasHatched
// not one of the game's: the pet chooser's "play as your pet" switch
// (gui.PetInventory), kept with the user vars so it reaches the client at
// login. on, whichever pet is out stands in for the avatar, in any room, as
// at a Play-As-Your-Pet party.
const USER_VAR_PET_FORM = 9008;
const inPetForm = account => Number(account.userVars[USER_VAR_PET_FORM]) === 1 && Boolean(activePet(account));
const random = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
@@ -106,6 +113,24 @@ module.exports = ({others, findOnline, petFields}) => {
const ownPet = (account, invIdx) => account.pets.find(candidate => candidate.inv === Number(invIdx));
// tells the player and everyone who sees them whether the pet stands in
// for the avatar (UserCommXtCommManager, user communication type 13).
const sendPetForm = session => {
if (session.pos) {
const state = inPetForm(session.account) ? "on" : "off";
for (const other of [session, ...others(session)]) {
other.sendXt("uc", session.room.id, session.id, state, "13");
}
}
};
// the pet chooser's switch. on with no pet out is kept for the next pet.
const setPetForm = (session, on) => {
achievements.set(session.account, USER_VAR_PET_FORM, on ? 1 : 0);
accounts.save(session.account);
sendPetForm(session);
};
const handlers = {
// PetManager.onPetListResponse: [found, username, count, (invIdx,
// createdTs, name, lBits, uBits, eBits, mastery, personality, toy, food,
@@ -146,15 +171,8 @@ module.exports = ({others, findOnline, petFields}) => {
session.sendXt("ps", -1, 0);
return;
}
const wasPetForm = inPetForm(account);
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);
@@ -163,6 +181,11 @@ module.exports = ({others, findOnline, petFields}) => {
other.sendXt("ps", messageRoom, 1, session.id, ...petFields(pet));
}
}
// with no pet out the avatar comes back; the next pet out takes its
// place again while the switch is on.
if (wasPetForm !== inPetForm(account)) {
sendPetForm(session);
}
},
// PetManager.onPetDismissResponse: [success, invIdx]
@@ -173,14 +196,10 @@ module.exports = ({others, findOnline, petFields}) => {
session.sendXt("pd", -1, 0, invIdx);
return;
}
const wasPetForm = inPetForm(account);
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");
}
}
if (wasPetForm && !inPetForm(account)) {
sendPetForm(session);
}
for (const avatar of account.avatars) {
if (avatar.petInvId === pet.inv) {
@@ -215,7 +234,8 @@ module.exports = ({others, findOnline, petFields}) => {
// EggPetHatchedPopup: [petInvIdx, nameId1, nameId2] names a pet hatched
// from an egg. PetManager.onPetEggNameResponse: [success, invIdx, name].
pn(session, roomId, [invIdx, name1, name2]) {
const pet = ownPet(session.account, invIdx);
const {account} = session;
const pet = ownPet(account, invIdx);
const def = pet && defpacks.petDef(pet.lBits & 0xFF);
if (!pet || ![name1, name2].every(isUint) || pet.name || !def || def.isEgg !== "1"
|| pet.createdAt + SECONDS_TO_HATCH > Math.floor(Date.now() / 1000)) {
@@ -250,5 +270,5 @@ module.exports = ({others, findOnline, petFields}) => {
},
};
return {handlers, walked, giveCharacter, favouritesList, personalityList, PERSONALITY_LIST};
return {handlers, walked, giveCharacter, favouritesList, personalityList, PERSONALITY_LIST, inPetForm, setPetForm};
};
+4 -2
View File
@@ -32,11 +32,13 @@ const PERMISSIONS = {
"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)",
"room.effects": "run temporary room-wide size and colour effects (!roomfx)",
"theater.control": "play or stop a YouTube video for everyone in the theatre",
"music.upload": "upload MP3s as den music tracks, and delete those uploaded (the Music page)",
"staff.log": "read the mod log: what staff did, in the panels and the game (the Mod log page)",
};
const HELPER = ["server.view", "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", "items.restrict", "theater.control"];
const ADMIN = [...MODERATOR, "items.create", "room.effects"];
const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve", "items.restrict", "theater.control", "staff.log"];
const ADMIN = [...MODERATOR, "items.create", "room.effects", "music.upload"];
// a developer makes things, and moderates nobody.
const DEVELOPER = ["server.view", "staff.list", "items.create", "room.effects", "theater.control"];
+28 -24
View File
@@ -459,17 +459,20 @@ const sendAvatarCreate = (to, target) => {
avatar.questLevel || 0,
1, // userNameModeratedFlag
lastSeenField(account, Boolean(findOnline(account.username))), // daysSinceLastLogin: see lib/player.js
// optional-field flags: bit 0 accountType, bit 1 nameBarData, bit 2 pet
pet ? 7 : 3,
// optional-field flags: bit 0 accountType, bit 1 nameBarData, bit 2 pet,
// bit 3 a blend colour (none: 0), bit 4 guide (the name tag and bubble
// every client draws for a guide)
3 | (pet ? 4 : 0) | (account.isGuide ? 24 : 0),
account.accountType,
account.nameBarData,
...(pet ? petFields(pet) : []));
...(pet ? petFields(pet) : []),
...(account.isGuide ? [0, 1] : []));
sendItemList(to, target, false);
disguises.show(to, target);
if (target.invisible) {
to.sendXt("xiv", -1, target.id, 1);
}
if (target.petPlayerMode) {
if (pets.inPetForm(account)) {
to.sendXt("uc", room.id, target.id, "on", "13");
}
// `ac` only creates the avatar. Actions normally travel as live `uc`
@@ -692,6 +695,9 @@ const handlers = {
if (motd) {
tell(session, motd);
}
if (session.account.guideRefused) {
session.sendXt("xtl", -1, "Guide is only for players the Burrow team has made guides.");
}
buddies.greet(session);
minigames.greet(session);
moderation.greet(session);
@@ -1772,15 +1778,12 @@ 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.
// Per-player pet form (the pet chooser's switch, lib/pets.js). 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");
}
pets.setPetForm(session, fields[0] === "on");
return;
}
// Type 3 is the action packet. It used to be sent only to people
@@ -2016,20 +2019,21 @@ 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. `by`
// is who approved it: a moderator's username, or "admin".
// is who approved it: a moderator's username, or "admin". the same
// picture waiting elsewhere is approved with it, and its makers told too.
approveMasterpiece(id, by) {
const maker = masterpieces.creatorOf(id);
if (!masterpieces.approve(id, by)) {
return false;
}
if (maker) {
ecards.noteFromHq(maker, "Your Masterpiece has been approved! It is with your den items.");
const session = findOnline(maker.username);
if (session) {
dens.sendDenItems(session);
const approved = masterpieces.approve(id, by);
for (const painting of approved) {
const maker = masterpieces.creatorOf(painting.id);
if (maker) {
ecards.noteFromHq(maker, "Your Masterpiece has been approved! It is with your den items.");
const session = findOnline(maker.username);
if (session) {
dens.sendDenItems(session);
}
}
}
return true;
return approved.length > 0;
},
// takes a painting away for good, from whoever has it by now: one that
// was not approved, or one that should not have been. its maker gets a
@@ -2054,7 +2058,7 @@ module.exports = {
account.denItems = account.denItems.filter(item => item.image !== painting.id);
account.tradeList = account.tradeList.filter(listed => !(listed.type === 1 && held.some(item => item.inv === listed.inv)));
}
masterpieces.forget(painting.id);
masterpieces.forget(painting.id, true);
if (maker) {
dens.giveDenItem(maker, masterpieces.TOKEN_DEN_ITEM);
ecards.noteFromHq(maker, "Your Masterpiece was not approved. Here is a Masterpiece Token to frame another one with.");
+143 -1
View File
@@ -413,6 +413,7 @@
<button role="tab" data-tab="masterpieces" aria-selected="false"><span class="icon" aria-hidden="true">&#9635;</span>Masterpieces<span id="masterpiece-count"></span></button>
<button role="tab" data-tab="items" aria-selected="false"><span class="icon" aria-hidden="true">&#10070;</span>Items</button>
<button role="tab" data-tab="wear-rules" aria-selected="false"><span class="icon" aria-hidden="true">&#9873;</span>Wear rules</button>
<button role="tab" data-tab="music" aria-selected="false"><span class="icon" aria-hidden="true">&#9835;</span>Music</button>
<button role="tab" data-tab="bans" aria-selected="false"><span class="icon" aria-hidden="true">&#8856;</span>Bans</button>
<button role="tab" data-tab="moderators" aria-selected="false"><span class="icon" aria-hidden="true">&#9733;</span>Moderators</button>
<button role="tab" data-tab="messages" aria-selected="false"><span class="icon" aria-hidden="true">&#9993;</span>Messages</button>
@@ -501,6 +502,15 @@
<div class="row"><input id="new-name" maxlength="100" placeholder="New username" autocomplete="off" spellcheck="false" aria-label="New username">
<button type="button" data-action="rename">Rename</button></div>
</div>
<div class="action">
<h3>Lost access</h3>
<p class="hint">A new random password, shown once. They are signed out everywhere and should change it on their account page.</p>
<div class="row"><label class="check"><input type="checkbox" id="temp-two-step-off"> Turn off their 2FA too</label></div>
<div class="row" style="margin-top:8px"><button type="button" data-action="tempPassword">Make temporary password</button></div>
<div class="row" style="margin-top:8px" id="temp-password-row" hidden>
<input id="temp-password" readonly aria-label="Temporary password" spellcheck="false" style="font-family:monospace">
<button type="button" id="temp-password-copy">Copy</button></div>
</div>
<div class="action">
<h3>Adventure level</h3>
<div class="row"><input id="quest-level" type="number" min="0" max="100" step="1" aria-label="Adventure level of the animal in use">
@@ -525,6 +535,8 @@
<h3>Badges</h3>
<div class="buttons" id="badge-boxes"></div>
<div class="row" style="margin-top:8px"><button type="button" data-action="badges">Set</button></div>
<div class="row" style="margin-top:8px" title="A guide's name tag and chat bubble, seen by everyone; from their next login">
<button type="button" data-action="guide" id="guide-toggle"></button></div>
<div class="row" style="margin-top:8px" title="Players link their Discord themselves, on the account page">
<span class="hint" id="discord-name"></span>
<button type="button" data-action="discord">Unlink Discord</button></div>
@@ -735,6 +747,31 @@
</section>
</div>
<div data-view="music" hidden>
<section>
<h2>Upload music</h2>
<p class="hint">An MP3 becomes a den music track at once, with no restart: players get it from the item finder (and the shop, if it is on sale) and play it in their dens like the game's own tracks. 44.1 kHz MP3s play best; 15 MB at most.</p>
<div class="actions">
<div class="action">
<h3>The track</h3>
<div class="row"><input id="music-file" type="file" accept=".mp3,audio/mpeg" aria-label="MP3 file"></div>
<div class="row" style="margin-top:8px"><input id="music-name" maxlength="40" placeholder="Name" aria-label="Name"></div>
<div class="row" style="margin-top:8px"><input id="music-cost" type="number" min="0" placeholder="Price in gems (0)" aria-label="Price in gems">
<label class="check"><input type="checkbox" id="music-shop"> On sale in the shop</label></div>
<div class="row" style="margin-top:8px"><button type="button" class="primary" id="music-upload">Upload</button></div>
</div>
</div>
<p class="status" id="music-status" role="status"></p>
</section>
<section>
<h2>Uploaded tracks</h2>
<div class="table-wrap"><table>
<thead><tr><th>Track</th><th class="num">Den item</th><th>Uploaded</th><th class="num">Size</th><th></th></tr></thead>
<tbody id="music-list"></tbody>
</table></div>
<div class="empty" id="no-music" hidden>None yet.</div>
</section>
</div>
<div data-view="items" hidden>
<section>
<h2 id="item-form-title">Make an item</h2>
@@ -1501,6 +1538,8 @@
label.append(box, ` ${badge.label}`);
return label;
}));
$("temp-two-step-off").disabled = !current || !current.twoStep;
$("guide-toggle").textContent = current && current.guide ? "Remove guide" : "Make guide";
$("discord-name").textContent = current && current.discord ? `Discord: ${current.discord}` : "No Discord linked";
$("admin-dashboard-access").textContent = current && current.adminDashboardAccess ? "Remove Discord dashboard access" : "Allow Discord dashboard access";
$("admin-dashboard-access").disabled = !current || (!current.discord && !current.adminDashboardAccess);
@@ -1537,7 +1576,8 @@
selected = username;
current = null;
setStatus($("detail-status"), "");
for (const id of ["new-name", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
$("temp-password-row").hidden = true;
for (const id of ["temp-password", "new-name", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
$(id).value = "";
}
hashArg = username;
@@ -1690,6 +1730,8 @@
case "role": return {role: $("role-select").value};
case "permissions": return permissionChoices();
case "adminDashboardAccess": return {on: !(current || {}).adminDashboardAccess};
case "guide": return {on: !(current || {}).guide};
case "tempPassword": return {twoStepOff: $("temp-two-step-off").checked};
case "message": return {text: $("message-text").value};
case "gems": return {amount: numberFrom("gems-amount")};
case "gift": return giftBody();
@@ -1701,6 +1743,10 @@
}
};
$("temp-password-copy").addEventListener("click", () => {
navigator.clipboard.writeText($("temp-password").value).catch(() => $("temp-password").select());
});
// the "N ago" buttons fill the last-seen box and press Set.
$("detail").addEventListener("click", event => {
const quick = event.target.closest("button[data-ago]");
@@ -1730,6 +1776,9 @@
if (action === "banDevices" && !window.confirm(`Hardware ban ${selected}? Everyone on their hardware is put out.`)) {
return;
}
if (action === "tempPassword" && !window.confirm(`Give ${selected} a new random password? Their old one stops working and they are signed out everywhere.`)) {
return;
}
button.disabled = true;
const result = await api("account", {username: selected, action, ...actionBody(action)});
button.disabled = false;
@@ -1737,6 +1786,11 @@
if (result.ok && action === "delete") {
selected = null;
}
if (result.ok && action === "tempPassword") {
$("temp-password").value = result.data.password;
$("temp-password-row").hidden = false;
$("temp-two-step-off").checked = false;
}
if (result.ok && action === "rename") {
selected = result.data.username;
$("new-name").value = "";
@@ -2853,6 +2907,91 @@
setStatus($("control-status"), said(result), !result.ok);
});
// ---- music uploaded by staff (lib/custommusic.js): an MP3 made a den
// music track, which players get from the item finder at once
const MUSIC = "/admin/api/music";
let musicShown = "";
const musicCall = async (query, body) => {
try {
const response = await fetch(`${MUSIC}${query}`, {method: "POST", headers: {"Content-Type": "audio/mpeg"}, body});
return await response.json().catch(() => ({error: "That did not work."}));
}
catch (err) {
return {error: "The server did not answer."};
}
};
const renderMusic = data => {
const tracks = data.tracks || [];
// drawn again only when something changed: a track being listened to keeps playing
const shown = JSON.stringify(tracks);
if (shown === musicShown) {
return;
}
musicShown = shown;
$("no-music").hidden = tracks.length > 0;
$("music-list").replaceChildren(...tracks.map(track => {
const row = el("tr");
const name = el("td");
const player = el("audio");
player.controls = true;
player.preload = "none";
player.src = `${MUSIC}?play=${track.id}`;
player.style.cssText = "display:block;margin-top:6px;height:32px;max-width:260px";
name.append(el("strong", track.name), player);
const actions = el("td");
actions.append(button("Delete", async () => {
if (!confirm(`Delete "${track.name}"? It is taken from every player who has it. This cannot be undone.`)) {
return;
}
const result = await musicCall(`?delete=${track.id}`, new Uint8Array(0));
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
await loadMusic();
}, "danger"));
row.append(name, el("td", String(track.id), "num"), el("td", `${when(track.createdAt)} · ${track.createdBy}${track.inShop ? ` · on sale, ${track.cost} gems` : ""}`),
el("td", `${(track.bytes / 1048576).toFixed(1)} MB`, "num"), actions);
return row;
}));
};
const loadMusic = async () => {
try {
const response = await fetch(MUSIC);
const data = await response.json().catch(() => ({}));
if (response.ok) {
renderMusic(data);
}
}
catch (err) {
// shown again with the next refresh
}
};
// the name from the file's, until one is typed
$("music-file").addEventListener("change", () => {
const file = $("music-file").files[0];
if (file && !$("music-name").value.trim()) {
$("music-name").value = file.name.replace(/\.mp3$/i, "").replace(/[_]+/g, " ").slice(0, 40);
}
});
$("music-upload").addEventListener("click", async () => {
const file = $("music-file").files[0];
if (!file || !$("music-name").value.trim()) {
setStatus($("music-status"), file ? "Give the track a name." : "Choose an MP3 first.", true);
return;
}
$("music-upload").disabled = true;
setStatus($("music-status"), "Uploading...");
const query = `?name=${encodeURIComponent($("music-name").value.trim())}&cost=${encodeURIComponent($("music-cost").value || 0)}&inShop=${$("music-shop").checked ? 1 : 0}`;
const result = await musicCall(query, new Uint8Array(await file.arrayBuffer()));
$("music-upload").disabled = false;
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
if (result.ok) {
for (const id of ["music-file", "music-name", "music-cost"]) {
$(id).value = "";
}
$("music-shop").checked = false;
}
await loadMusic();
});
const refresh = async () => {
clearTimeout(timer);
if (!state || !state.signedIn) {
@@ -2921,6 +3060,9 @@
else if (tab === "wear-rules") {
await loadWearRules();
}
else if (tab === "music") {
await loadMusic();
}
else if (tab === "items") {
result = await api("items");
if (result.ok) {
+486 -7
View File
@@ -14,24 +14,183 @@
position: relative;
z-index: 1;
}
#theatre-video {
/* the theatre's screen, as the game says where it is (ajTheatreScreen):
laid over the stage as Flash's "showAll" draws it, every size in
stage pixels times --s. the room's video (staff) and the player's
own both sit on it. */
@font-face { font-family: "DigitalDelivery"; font-weight: 400; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
@font-face { font-family: "DigitalDelivery"; font-weight: 700; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
#theatre {
--s: 1;
--px: calc(var(--s) * 1px);
position: fixed;
z-index: 2;
display: none;
left: 8.4vw;
top: 6.2vh;
width: 56.8vw;
height: 52.8vh;
overflow: hidden;
pointer-events: none;
font-family: "DigitalDelivery", Arial, Helvetica, sans-serif;
}
#theatre[hidden], #theatre [hidden] {
display: none !important;
}
/* the game draws over it just now (ajTheatreScreen) */
#theatre .covered {
visibility: hidden;
}
.theatre-screen {
position: absolute;
border: 0;
background: #000;
pointer-events: auto;
}
#theatre-video {
display: none;
}
#theatre-video.visible {
display: block;
}
#own-video > * {
width: 100%;
height: 100%;
border: 0;
display: block;
}
/* in the game's own colours: cream panels, brown edges, a green "go" */
#own-video-open {
position: absolute;
pointer-events: auto;
font: 700 calc(13 * var(--px)) / 1 "DigitalDelivery", Arial, sans-serif;
color: #6d4330;
background: linear-gradient(#fffbe6, #ffe9a6);
border: calc(2 * var(--px)) solid #7f6744;
border-radius: 999px;
padding: calc(6 * var(--px)) calc(14 * var(--px));
box-shadow: 0 calc(2 * var(--px)) 0 #7f6744;
cursor: pointer;
white-space: nowrap;
}
#own-video-open:hover {
background: linear-gradient(#fffef5, #fff0be);
}
#own-video-open:active {
transform: translateY(calc(2 * var(--px)));
box-shadow: none;
}
#own-video-box {
position: absolute;
pointer-events: auto;
box-sizing: border-box;
width: calc(360 * var(--px));
padding: calc(14 * var(--px)) calc(16 * var(--px)) calc(12 * var(--px));
color: #6d4330;
font-size: calc(13 * var(--px));
background: #fff2c4;
border: calc(4 * var(--px)) solid #7f6744;
border-radius: calc(18 * var(--px));
box-shadow: inset 0 0 0 calc(2 * var(--px)) #ffe39a, 0 calc(4 * var(--px)) 0 rgba(0, 0, 0, 0.35);
}
#own-video-box h2 {
margin: 0 calc(24 * var(--px)) calc(10 * var(--px)) 0;
font-size: calc(20 * var(--px));
font-weight: 700;
color: #fff;
letter-spacing: 0.02em;
text-shadow: 0 0 calc(2 * var(--px)) #6d4330, calc(1.5 * var(--px)) calc(1.5 * var(--px)) 0 #6d4330, calc(-1.5 * var(--px)) calc(1.5 * var(--px)) 0 #6d4330, calc(1.5 * var(--px)) calc(-1.5 * var(--px)) 0 #6d4330, calc(-1.5 * var(--px)) calc(-1.5 * var(--px)) 0 #6d4330;
}
#own-video-url {
box-sizing: border-box;
width: 100%;
font: 400 calc(13 * var(--px)) / 1.2 Arial, Helvetica, sans-serif;
color: #3d2716;
background: #fff;
border: calc(2 * var(--px)) solid #c9a86a;
border-radius: calc(9 * var(--px));
padding: calc(7 * var(--px)) calc(9 * var(--px));
box-shadow: inset 0 calc(2 * var(--px)) calc(3 * var(--px)) rgba(109, 67, 48, 0.25);
outline: none;
}
#own-video-url:focus {
border-color: #7f6744;
}
#own-video-url::placeholder {
color: #a88f6a;
}
.own-video-buttons {
display: flex;
justify-content: center;
gap: calc(10 * var(--px));
margin-top: calc(10 * var(--px));
}
.aj-button {
min-width: calc(88 * var(--px));
font: 700 calc(15 * var(--px)) / 1 "DigitalDelivery", Arial, sans-serif;
color: #fff;
border-radius: 999px;
padding: calc(7 * var(--px)) calc(16 * var(--px));
cursor: pointer;
text-shadow: 0 calc(1.5 * var(--px)) 0 rgba(0, 0, 0, 0.45);
}
.aj-button:active {
transform: translateY(calc(2 * var(--px)));
box-shadow: none !important;
}
.aj-button.go {
background: linear-gradient(#a6e05a, #4fa52f);
border: calc(2 * var(--px)) solid #2f7420;
box-shadow: inset 0 calc(2 * var(--px)) 0 rgba(255, 255, 255, 0.45), 0 calc(2 * var(--px)) 0 #2f7420;
}
.aj-button.go:hover {
background: linear-gradient(#b5ea6c, #5cb43a);
}
.aj-button.stop {
background: linear-gradient(#f59a6a, #d4482a);
border: calc(2 * var(--px)) solid #8e2b16;
box-shadow: inset 0 calc(2 * var(--px)) 0 rgba(255, 255, 255, 0.4), 0 calc(2 * var(--px)) 0 #8e2b16;
}
.aj-button.stop:hover {
background: linear-gradient(#ffab7c, #e05634);
}
#own-video-close {
position: absolute;
top: calc(-10 * var(--px));
right: calc(-10 * var(--px));
width: calc(30 * var(--px));
height: calc(30 * var(--px));
padding: 0;
font: 700 calc(18 * var(--px)) / 1 Arial, sans-serif;
color: #fff;
background: radial-gradient(circle at 50% 35%, #ff7a5c, #c8321a 70%);
border: calc(3 * var(--px)) solid #fff;
border-radius: 50%;
box-shadow: 0 0 0 calc(2 * var(--px)) #7f6744, 0 calc(2 * var(--px)) 0 calc(2 * var(--px)) rgba(0, 0, 0, 0.3);
cursor: pointer;
}
#own-video-close:hover {
background: radial-gradient(circle at 50% 35%, #ff8f74, #d93d22 70%);
}
#own-video-said {
min-height: calc(15 * var(--px));
margin: calc(8 * var(--px)) 0 0;
font: 400 calc(12 * var(--px)) / 1.25 Arial, Helvetica, sans-serif;
color: #a3341c;
text-align: center;
}
</style>
<embed id="flash-content"></embed>
<iframe id="theatre-video" title="Theatre video" allow="autoplay; encrypted-media" referrerpolicy="strict-origin-when-cross-origin"></iframe>
<div id="theatre" hidden>
<iframe id="theatre-video" class="theatre-screen" title="Theatre video" allow="autoplay; encrypted-media" referrerpolicy="strict-origin-when-cross-origin"></iframe>
<div id="own-video" class="theatre-screen" hidden></div>
<button type="button" id="own-video-open">&#9654; Your Video</button>
<form id="own-video-box" hidden>
<h2>Your Video</h2>
<button type="button" id="own-video-close" aria-label="Close">&times;</button>
<input id="own-video-url" type="url" placeholder="Paste a link: YouTube, Vimeo, .mp4, .webm, .mp3" autocomplete="off" spellcheck="false" aria-label="Video link">
<div class="own-video-buttons">
<button type="submit" class="aj-button go">Play</button>
<button type="button" id="own-video-stop" class="aj-button stop">Stop</button>
</div>
<p id="own-video-said" role="status"></p>
</form>
</div>
<script>
"use strict";
@@ -114,6 +273,130 @@
window.ipc.sendToHost("presence", String(text).slice(0, 100));
}
// the theatre's screen, from the game (AJClient.reportTheatreScreen):
// "x,y,width,height" in its 900 by 550 stage, or "" with none shown.
// the stage fills the page as Flash's "showAll" draws it: as big as
// fits, in the middle.
//
// after it, "|columns|row,row,..." when the game draws something over
// the screen (or just under it): a hex row of bits per COVER_CELL
// stage pixels. a web page is always drawn over the game, so those
// cells are cut out of the videos, and the button and box step aside.
const STAGE_W = 900;
const STAGE_H = 550;
const COVER_CELL = 4;
const theatre = document.getElementById("theatre");
let theatreScreen = null;
let theatreCover = []; // {x, y, w, h} in stage pixels from the screen's corner
function ajTheatreScreen(text) {
const parts = String(text || "").split("|");
const numbers = parts[0].split(",").map(Number);
theatreScreen = numbers.length === 4 && numbers.every(Number.isFinite) && numbers[2] > 0 && numbers[3] > 0
? {x: numbers[0], y: numbers[1], w: numbers[2], h: numbers[3]} : null;
theatreCover = theatreScreen && parts.length === 3 ? coverRects(Number(parts[1]), parts[2].split(",")) : [];
placeTheatre();
ownVideo.inTheatre(theatreScreen !== null);
}
// the covered cells as rectangles: runs along each row, and a run
// that the row above has too made taller.
function coverRects(columns, rows) {
const rects = [];
let above = new Map(); // "from,to" of the row above -> its rectangle
rows.forEach((hex, row) => {
const here = new Map();
let from = -1;
for (let column = 0; column <= columns; column++) {
const digit = column < columns ? parseInt(hex[column >> 2] || "0", 16) : 0;
const covered = column < columns && Boolean(digit & (8 >> (column & 3)));
if (covered && from < 0) {
from = column;
}
else if (!covered && from >= 0) {
const key = `${from},${column}`;
let rect = above.get(key);
if (rect) {
rect.h += COVER_CELL;
}
else {
rect = {x: from * COVER_CELL, y: row * COVER_CELL, w: (column - from) * COVER_CELL, h: COVER_CELL};
rects.push(rect);
}
here.set(key, rect);
from = -1;
}
}
above = here;
});
return rects;
}
// the screen with the covered rectangles cut out ("evenodd": each one
// is a hole, reached from the corner and back).
function coverClip(scale) {
if (!theatreCover.length) {
return "none";
}
const px = value => `${Math.round(value * scale * 10) / 10}px`;
const points = ["0 0", "100% 0", "100% 100%", "0 100%", "0 0"];
for (const {x, y, w, h} of theatreCover) {
points.push(`${px(x)} ${px(y)}`, `${px(x + w)} ${px(y)}`, `${px(x + w)} ${px(y + h)}`, `${px(x)} ${px(y + h)}`, `${px(x)} ${px(y)}`, "0 0");
}
return `polygon(evenodd, ${points.join(", ")})`;
}
// is any of this element (placed in #theatre) under the game's drawing?
function underCover(element, scale) {
if (element.hidden) {
return false;
}
const left = element.offsetLeft / scale - theatreScreen.x;
const top = element.offsetTop / scale - theatreScreen.y;
const right = left + element.offsetWidth / scale;
const bottom = top + element.offsetHeight / scale;
return theatreCover.some(rect => rect.x < right && rect.x + rect.w > left && rect.y < bottom && rect.y + rect.h > top);
}
const BUTTON_ROOM = 34; // stage pixels the button wants under the screen
const BOX_W = 360; // #own-video-box's width in stage pixels
const BOX_H = 170; // and about its height
function placeTheatre() {
theatre.hidden = theatreScreen === null;
if (!theatreScreen) {
return;
}
const scale = Math.min(window.innerWidth / STAGE_W, window.innerHeight / STAGE_H);
const place = (element, x, y, w, h) => {
element.style.left = `${x * scale}px`;
element.style.top = `${y * scale}px`;
if (w !== undefined) {
element.style.width = `${w * scale}px`;
element.style.height = `${h * scale}px`;
}
};
theatre.style.left = `${(window.innerWidth - STAGE_W * scale) / 2}px`;
theatre.style.top = `${(window.innerHeight - STAGE_H * scale) / 2}px`;
theatre.style.width = `${STAGE_W * scale}px`;
theatre.style.height = `${STAGE_H * scale}px`;
theatre.style.setProperty("--s", String(scale));
const {x, y, w, h} = theatreScreen;
place(theatreVideo, x, y, w, h);
place(document.getElementById("own-video"), x, y, w, h);
// the button under the screen's left corner, or inside it when the
// stage ends first; the box over the middle of the screen.
const below = y + h + 8 + BUTTON_ROOM <= STAGE_H;
place(document.getElementById("own-video-open"), x + 4, below ? y + h + 8 : y + h - BUTTON_ROOM);
place(document.getElementById("own-video-box"), x + (w - BOX_W) / 2, Math.max(4, y + (h - BOX_H) / 2));
const clip = coverClip(scale);
theatreVideo.style.clipPath = clip;
document.getElementById("own-video").style.clipPath = clip;
for (const id of ["own-video-open", "own-video-box"]) {
const element = document.getElementById(id);
element.classList.toggle("covered", underCover(element, scale));
}
}
window.addEventListener("resize", placeTheatre);
function ajPrint(imageData) {
window.ipc.sendToHost("printImage", imageData);
}
@@ -125,12 +408,208 @@
if (!/^[A-Za-z0-9_-]{11}$/.test(id)) {
theatreVideo.removeAttribute("src");
theatreVideo.classList.remove("visible");
ownVideo.roomVideo(false);
return;
}
theatreVideo.src = `https://www.youtube-nocookie.com/embed/${id}?autoplay=1&rel=0&modestbranding=1`;
theatreVideo.classList.add("visible");
// what staff play for the room comes first; the player's own waits.
ownVideo.roomVideo(true);
}
// a video of the player's own choosing on the theatre screen, seen by
// them alone: nothing of it goes to the server. YouTube and Vimeo
// links play in those sites' own players; any other http(s) address
// in a <video>, which plays a media file or nothing (a web page in it
// runs no script and asks nobody for anything).
const ownVideo = (() => {
const $ = id => document.getElementById(id);
const screen = $("own-video");
const opener = $("own-video-open");
const box = $("own-video-box");
const input = $("own-video-url");
const said = $("own-video-said");
const SAVED = "ownVideoUrl";
let here = false; // in a theatre
let roomPlaying = false;
let playing = null; // the element showing it
const embedFor = text => {
let url;
try {
url = new URL(text);
}
catch (err) {
return null;
}
if (url.protocol !== "https:" && url.protocol !== "http:") {
return null;
}
const host = url.hostname.replace(/^(?:www\.|m\.)/, "").toLowerCase();
let match = null;
if (host === "youtu.be") {
match = /^\/([A-Za-z0-9_-]{11})/.exec(url.pathname);
}
else if (host === "youtube.com" || host === "youtube-nocookie.com") {
match = url.pathname === "/watch" ? /^([A-Za-z0-9_-]{11})$/.exec(url.searchParams.get("v") || "")
: /^\/(?:embed|shorts|live)\/([A-Za-z0-9_-]{11})/.exec(url.pathname);
}
if (match) {
return {frame: `https://www.youtube-nocookie.com/embed/${match[1]}?autoplay=1&rel=0&modestbranding=1`};
}
if (host === "vimeo.com" || host === "player.vimeo.com") {
match = /^\/(?:video\/)?(\d{1,12})(?:\/|$)/.exec(url.pathname);
return match ? {frame: `https://player.vimeo.com/video/${match[1]}?autoplay=1`} : {error: "That Vimeo link has no video in it."};
}
if (host.endsWith("youtube.com")) {
return {error: "That YouTube link has no video in it."};
}
return {file: url.href};
};
const show = () => {
screen.hidden = !playing || !here || roomPlaying;
if (playing instanceof HTMLMediaElement) {
if (screen.hidden) {
playing.pause();
}
else {
playing.play().catch(() => {});
}
}
};
const stop = () => {
if (playing instanceof HTMLMediaElement) {
playing.pause();
playing.removeAttribute("src");
playing.load();
window.ipc.sendToHost("ownVideo", "");
}
screen.replaceChildren();
playing = null;
show();
};
// the desktop client loads nothing for this page from elsewhere but
// what it is told the player chose (client 1.3.2, app/main.js): it
// says when that address may load. an older client never answers.
const CLIENT_WAIT_MS = 1500;
let cleared = null; // {link, go}
window.ipc.on("ownVideoReady", (event, link) => {
if (cleared && cleared.link === link) {
cleared.go();
}
});
const whenCleared = link => new Promise(resolve => {
const timer = setTimeout(resolve, CLIENT_WAIT_MS);
cleared = {link, go: () => {
clearTimeout(timer);
resolve();
}};
window.ipc.sendToHost("ownVideo", link);
});
const play = text => {
const found = embedFor(String(text || "").trim());
if (!found || found.error) {
said.textContent = found ? found.error : "Paste a link starting with https://";
return;
}
stop();
if (found.frame) {
playing = document.createElement("iframe");
playing.title = "Your video";
playing.allow = "autoplay; encrypted-media; fullscreen";
playing.referrerPolicy = "strict-origin-when-cross-origin";
playing.src = found.frame;
}
else {
const video = document.createElement("video");
playing = video;
video.controls = true;
video.autoplay = true;
video.playsInline = true;
video.addEventListener("error", () => {
said.textContent = "That link did not play. It has to be a video or sound file (.mp4, .webm, .mp3), and the site has to allow it.";
});
whenCleared(found.file).then(() => {
if (playing === video) {
video.src = found.file;
show();
}
});
}
screen.append(playing);
said.textContent = roomPlaying ? "It plays when the theatre's own video stops." : "";
try {
localStorage.setItem(SAVED, input.value.trim());
}
catch (err) {
}
show();
};
opener.addEventListener("click", () => {
box.hidden = !box.hidden;
opener.hidden = !box.hidden;
placeTheatre();
if (!box.hidden) {
if (!input.value) {
try {
input.value = localStorage.getItem(SAVED) || "";
}
catch (err) {
}
}
input.focus();
input.select();
}
});
const close = () => {
box.hidden = true;
opener.hidden = false;
placeTheatre();
said.textContent = "";
};
$("own-video-close").addEventListener("click", close);
$("own-video-stop").addEventListener("click", () => {
stop();
said.textContent = "";
});
box.addEventListener("submit", event => {
event.preventDefault();
play(input.value);
});
input.addEventListener("keydown", event => {
if (event.key === "Escape") {
close();
}
});
return {
// in a theatre or not; out of one, the video is gone.
inTheatre(yes) {
if (yes === here) {
return;
}
here = yes;
if (!here) {
stop();
close();
}
show();
},
roomVideo(on) {
roomPlaying = on;
if (!on) {
said.textContent = "";
}
show();
},
};
})();
// The native theatre sign calls this through ExternalInterface. The
// SWF performs its own permission check before showing the controls.
function ajOpenTheatreControl() {
+139
View File
@@ -475,9 +475,11 @@
<button role="tab" data-tab="masterpieces" data-needs="player.view" aria-selected="false"><span class="icon" aria-hidden="true">&#9635;</span>Masterpieces<span id="masterpiece-count"></span></button>
<button role="tab" data-tab="bans" data-needs="player.view" aria-selected="false"><span class="icon" aria-hidden="true">&#8856;</span>Bans</button>
<button role="tab" data-tab="stats" data-needs="player.view" aria-selected="false"><span class="icon" aria-hidden="true">&#9636;</span>Stats</button>
<button role="tab" data-tab="mod-log" data-needs="staff.log" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#9776;</span>Mod log</button>
<button role="tab" data-tab="review" data-needs="items.approve" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#10004;</span>Review</button>
<button role="tab" data-tab="wear-rules" data-needs="items.restrict" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#9873;</span>Wear rules</button>
<button role="tab" data-tab="items" data-needs="items.create" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#10070;</span>Items</button>
<button role="tab" data-tab="music" data-needs="music.upload" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#9835;</span>Music</button>
</nav>
<button id="sign-out" type="button">Sign out</button>
</aside>
@@ -897,6 +899,31 @@
</section>
</div>
<div data-view="music" hidden>
<section>
<h2>Upload music</h2>
<p class="hint">An MP3 becomes a den music track at once, with no restart: players get it from the item finder (and the shop, if it is on sale) and play it in their dens like the game's own tracks. 44.1 kHz MP3s play best; 15 MB at most.</p>
<div class="actions">
<div class="action">
<h3>The track</h3>
<div class="row"><input id="music-file" type="file" accept=".mp3,audio/mpeg" aria-label="MP3 file"></div>
<div class="row" style="margin-top:8px"><input id="music-name" maxlength="40" placeholder="Name" aria-label="Name"></div>
<div class="row" style="margin-top:8px"><input id="music-cost" type="number" min="0" placeholder="Price in gems (0)" aria-label="Price in gems">
<label class="check"><input type="checkbox" id="music-shop"> On sale in the shop</label></div>
<div class="row" style="margin-top:8px"><button type="button" class="primary" id="music-upload">Upload</button></div>
</div>
</div>
<p class="status" id="music-status" role="status"></p>
</section>
<section>
<h2>Uploaded tracks</h2>
<div class="table-wrap"><table>
<thead><tr><th>Track</th><th class="num">Den item</th><th>Uploaded</th><th class="num">Size</th><th></th></tr></thead>
<tbody id="music-list"></tbody>
</table></div>
<div class="empty" id="no-music" hidden>None yet.</div>
</section>
</div>
<div data-view="items" hidden>
<section>
<h2 id="item-form-title">Make an item</h2>
@@ -966,6 +993,17 @@
</section>
</div>
<div data-view="mod-log" hidden>
<section>
<h2>What staff did</h2>
<div class="table-wrap"><table>
<thead><tr><th>When</th><th>Who</th><th>What</th><th>Player</th><th>Detail</th></tr></thead>
<tbody id="mod-log"></tbody>
</table></div>
<div class="empty" id="no-mod-log" hidden>Nothing yet.</div>
</section>
</div>
<div data-view="bans" hidden>
<section>
<h2>Banned and silenced</h2>
@@ -2733,6 +2771,91 @@
$("server-updated").textContent = `Updated ${new Date(Number(data.now || Date.now())).toLocaleTimeString()}.`;
};
// ---- music uploaded by staff (lib/custommusic.js): an MP3 made a den
// music track, which players get from the item finder at once
const MUSIC = "/mod/api/music";
let musicShown = "";
const musicCall = async (query, body) => {
try {
const response = await fetch(`${MUSIC}${query}`, {method: "POST", headers: {"Content-Type": "audio/mpeg"}, body});
return await response.json().catch(() => ({error: "That did not work."}));
}
catch (err) {
return {error: "The server did not answer."};
}
};
const renderMusic = data => {
const tracks = data.tracks || [];
// drawn again only when something changed: a track being listened to keeps playing
const shown = JSON.stringify(tracks);
if (shown === musicShown) {
return;
}
musicShown = shown;
$("no-music").hidden = tracks.length > 0;
$("music-list").replaceChildren(...tracks.map(track => {
const row = el("tr");
const name = el("td");
const player = el("audio");
player.controls = true;
player.preload = "none";
player.src = `${MUSIC}?play=${track.id}`;
player.style.cssText = "display:block;margin-top:6px;height:32px;max-width:260px";
name.append(el("strong", track.name), player);
const actions = el("td");
actions.append(button("Delete", async () => {
if (!confirm(`Delete "${track.name}"? It is taken from every player who has it. This cannot be undone.`)) {
return;
}
const result = await musicCall(`?delete=${track.id}`, new Uint8Array(0));
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
await loadMusic();
}, "danger"));
row.append(name, el("td", String(track.id), "num"), el("td", `${when(track.createdAt)} · ${track.createdBy}${track.inShop ? ` · on sale, ${track.cost} gems` : ""}`),
el("td", `${(track.bytes / 1048576).toFixed(1)} MB`, "num"), actions);
return row;
}));
};
const loadMusic = async () => {
try {
const response = await fetch(MUSIC);
const data = await response.json().catch(() => ({}));
if (response.ok) {
renderMusic(data);
}
}
catch (err) {
// shown again with the next refresh
}
};
// the name from the file's, until one is typed
$("music-file").addEventListener("change", () => {
const file = $("music-file").files[0];
if (file && !$("music-name").value.trim()) {
$("music-name").value = file.name.replace(/\.mp3$/i, "").replace(/[_]+/g, " ").slice(0, 40);
}
});
$("music-upload").addEventListener("click", async () => {
const file = $("music-file").files[0];
if (!file || !$("music-name").value.trim()) {
setStatus($("music-status"), file ? "Give the track a name." : "Choose an MP3 first.", true);
return;
}
$("music-upload").disabled = true;
setStatus($("music-status"), "Uploading...");
const query = `?name=${encodeURIComponent($("music-name").value.trim())}&cost=${encodeURIComponent($("music-cost").value || 0)}&inShop=${$("music-shop").checked ? 1 : 0}`;
const result = await musicCall(query, new Uint8Array(await file.arrayBuffer()));
$("music-upload").disabled = false;
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
if (result.ok) {
for (const id of ["music-file", "music-name", "music-cost"]) {
$(id).value = "";
}
$("music-shop").checked = false;
}
await loadMusic();
});
const refresh = async () => {
clearTimeout(timer);
if (!signedIn) {
@@ -2850,6 +2973,19 @@
else if (shown === "stats") {
await window.statsView.load(api);
}
else if (shown === "mod-log") {
const result = await api("modlog");
if (result.ok) {
$("mod-log").replaceChildren(...result.data.log.map(entry => {
const row = el("tr");
const detail = el("td", entry.detail);
detail.style.whiteSpace = "normal";
row.append(el("td", when(entry.at)), el("td", entry.by), el("td", entry.action), el("td", entry.target || "—"), detail);
return row;
}));
$("no-mod-log").hidden = result.data.log.length > 0;
}
}
else if (shown === "bans") {
const [result, hits] = await Promise.all([api("bans"), api("filterhits")]);
if (result.ok) {
@@ -2868,6 +3004,9 @@
else if (shown === "wear-rules") {
await loadWearRules();
}
else if (shown === "music") {
await loadMusic();
}
else if (shown === "items") {
const result = await api("items");
if (result.ok) {
+2
View File
@@ -12,6 +12,7 @@ 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 customMusic = require("./lib/custommusic.js");
const config = require("./config.js");
const defpacks = require("./lib/defpacks.js");
const http = require("./lib/http.js");
@@ -41,6 +42,7 @@ const main = async () => {
accounts.startBackups();
colours.load();
customItems.load();
customMusic.load();
reports.load();
support.load();
bans.load();
+235 -3
View File
@@ -22,6 +22,7 @@ package
import createAccountFlow.CreateAccount;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Shape;
@@ -340,6 +341,181 @@ package
gMainFrame.stage.addEventListener("keyDown",onFinderKey,false,1000);
startEmojiButton();
placeTheatreButton();
gMainFrame.stage.addEventListener("enterFrame",reportTheatreScreen,false,0,true);
}
// where the theatre's screen is, for game.html to lay a web video over
// it exactly: the original player's 512 by 288 at the top left of the
// theatre layer's videoLayer (movie.VideoPlayerOSMF), in stage
// coordinates (900 by 550; the page scales them as "showAll" does).
// "x,y,width,height", or "" with no theatre screen shown; told only
// when it changes, as the room zooms and scrolls under it.
//
// a web video is always drawn over the whole game, so it also gets
// where the game draws something over the screen (the HUD, the buddy
// list, a Jammer Wall, chat balloons): "x,y,width,height|columns|rows",
// a hex row of bits per SCREEN_CELL stage pixels, top to bottom, over
// the screen and SCREEN_BELOW pixels under it (the page's own button
// sits there). the page cuts those cells out of the video.
private static const THEATRE_SCREEN_W:Number = 512;
private static const THEATRE_SCREEN_H:Number = 288;
private static const SCREEN_CELL:Number = 4;
private static const SCREEN_BELOW:Number = 44;
private static const SCREEN_COVER_EVERY:int = 4; // frames between looks
private static const SCREEN_COVER_ALPHA:uint = 64; // of 255: drawn on, as far as the video goes
private static var _theatreScreenTold:String = null;
private static var _theatreCover:String = "";
private static var _theatreCoverFrame:int = 0;
private static function reportTheatreScreen(param1:Event = null) : void
{
var _loc2_:String = "";
var _loc3_:Object = null;
var _loc4_:DisplayObject = null;
var _loc5_:Point = null;
var _loc6_:Point = null;
try
{
_loc3_ = RoomManagerWorld.instance != null ? RoomManagerWorld.instance.theaterWindow : null;
_loc4_ = _loc3_ != null && _loc3_.hasOwnProperty("videoLayer") ? _loc3_.videoLayer as DisplayObject : null;
if(_loc4_ != null && shownOnStage(_loc4_))
{
_loc5_ = _loc4_.localToGlobal(new Point(0,0));
_loc6_ = _loc4_.localToGlobal(new Point(THEATRE_SCREEN_W,THEATRE_SCREEN_H));
_loc2_ = [_loc5_.x,_loc5_.y,_loc6_.x - _loc5_.x,_loc6_.y - _loc5_.y].map(function(param1:Number, ... rest):String
{
return String(Math.round(param1 * 10) / 10);
}).join(",");
if(++_theatreCoverFrame >= SCREEN_COVER_EVERY || _theatreScreenTold == null || _theatreScreenTold.indexOf(_loc2_) != 0)
{
_theatreCoverFrame = 0;
_theatreCover = theatreCover(_loc3_ as DisplayObject,_loc5_.x,_loc5_.y,_loc6_.x - _loc5_.x,_loc6_.y - _loc5_.y);
}
if(_theatreCover != "")
{
_loc2_ += "|" + _theatreCover;
}
}
}
catch(e:Error)
{
_loc2_ = "";
}
if(_loc2_ == _theatreScreenTold || !ExternalInterface.available)
{
return;
}
_theatreScreenTold = _loc2_;
try
{
ExternalInterface.call("ajTheatreScreen",_loc2_);
}
catch(e:Error)
{
}
}
// what is drawn over the theatre screen, as above: the game's windows
// and buttons, and the room's chat balloons, drawn small, cell by cell.
// the rest is hidden for the moment of drawing, in between two frames:
// the screen, what lies under it, and the room itself (its seats and
// floor are drawn above the screen, and are no reason for the video or
// its button to step aside). "" for nothing, or when the game will not
// be drawn.
private static function theatreCover(param1:DisplayObject, param2:Number, param3:Number, param4:Number, param5:Number) : String
{
var _loc6_:Array = [];
var _loc7_:DisplayObject = param1;
var _loc8_:DisplayObjectContainer = null;
var _loc9_:int = 0;
var _loc10_:DisplayObject = null;
var _loc11_:int = Math.max(1,Math.ceil(param4 / SCREEN_CELL));
var _loc12_:int = Math.max(1,Math.ceil((param5 + SCREEN_BELOW) / SCREEN_CELL));
var _loc13_:BitmapData = null;
var _loc14_:Array = [];
var _loc15_:Boolean = false;
var _loc16_:int = 0;
var _loc17_:int = 0;
var _loc18_:int = 0;
var _loc19_:String = null;
try
{
if(_loc7_.visible)
{
_loc7_.visible = false;
_loc6_.push(_loc7_);
}
while(_loc7_.parent != null)
{
_loc8_ = _loc7_.parent;
_loc9_ = _loc8_.getChildIndex(_loc7_);
while(--_loc9_ >= 0)
{
_loc10_ = _loc8_.getChildAt(_loc9_);
if(_loc10_.visible)
{
_loc10_.visible = false;
_loc6_.push(_loc10_);
}
}
_loc7_ = _loc8_;
}
_loc8_ = RoomManagerWorld.instance.layerManager.bkg;
_loc9_ = _loc8_.numChildren;
while(--_loc9_ >= 0)
{
_loc10_ = _loc8_.getChildAt(_loc9_);
if(_loc10_ != RoomManagerWorld.instance.layerManager.room_chat && _loc10_.visible)
{
_loc10_.visible = false;
_loc6_.push(_loc10_);
}
}
_loc13_ = new BitmapData(_loc11_,_loc12_,true,0);
_loc13_.draw(gMainFrame.stage,new Matrix(1 / SCREEN_CELL,0,0,1 / SCREEN_CELL,-param2 / SCREEN_CELL,-param3 / SCREEN_CELL));
}
catch(e:Error)
{
if(_loc13_ != null)
{
_loc13_.dispose();
_loc13_ = null;
}
}
for each(_loc10_ in _loc6_)
{
_loc10_.visible = true;
}
if(_loc13_ == null)
{
return "";
}
_loc16_ = 0;
while(_loc16_ < _loc12_)
{
_loc19_ = "";
_loc17_ = 0;
while(_loc17_ < _loc11_)
{
_loc18_ = 0;
_loc9_ = 0;
while(_loc9_ < 4)
{
if(_loc17_ + _loc9_ < _loc11_ && _loc13_.getPixel32(_loc17_ + _loc9_,_loc16_) >>> 24 >= SCREEN_COVER_ALPHA)
{
_loc18_ |= 8 >> _loc9_;
_loc15_ = true;
}
_loc9_++;
}
_loc19_ += _loc18_.toString(16);
_loc17_ += 4;
}
_loc14_.push(_loc19_);
_loc16_++;
}
_loc13_.dispose();
return _loc15_ ? _loc11_ + "|" + _loc14_.join(",") : "";
}
public static function openTool(param1:int) : void
@@ -608,6 +784,14 @@ package
return settingOf(9006) != 1;
}
// the pet chooser's "play as your pet" switch (gui.PetInventory): the
// pet that is out stands in for the avatar in any room. user var 9008,
// which the server also reads to show the pet form to everyone.
public static function petFormOn() : Boolean
{
return settingOf(9008) == 1;
}
// an item's picture version, or null for none or with them hidden
private static function artOf(param1:String, param2:int) : String
{
@@ -1542,6 +1726,7 @@ package
// 9007 Performance profile: 1 Low-end, 2 High, unset Balanced. A
// profile changes only optional rendering work, never the
// game's native 24 FPS (which would slow its animations).
// 9008 Play as your pet (gui.PetInventory, lib/pets.js): 1 on.
private static var _smoothTimer:Timer;
@@ -2289,8 +2474,55 @@ package
drawChatFilter();
}
// the server's rules, word for word as the owner gave them
private static const RULES_HTML:String = "<font size=\"16\" color=\"#563421\"><b>[1] Be Respectful / Have Common Sense</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>This is quite self explanatory. Be kind, treat people how you would want to be treated. If someone is uncomfortable with something you are saying and or doing, please respect that of them and do not argue against it, even if it may seem ridiculous in your eyes.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[2] No Direct Harassment / Bullying</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>If you are being disrespectful towards another person, Moderators have every right to punish you. Please don't be an asshole. Thank you.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[3] Keep Personal Information for Yourself.</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>As friendly that people may seem on this platform, never share personal identifying details with ANYONE. This leads to a lot of unsafe situations. Please be safe and responsible with the information you give to other people.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[4] Keep Drama OUT</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>If you have personal issues with another person, it is not our responsibility unless said person is confirmed to be problematic towards something against the rules of our server. Please do not bring arguments into our public chat, you will be muted until things clear up. Keep it in DMS.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[5] No NSFW!</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>NSFW and Suggestive Content are entirely banned from the server, period. We do not want to be a place that allows predatory behavior to fester. If you are unsure of what specific details this goes under, feel free to ask in a ticket.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[8] Report Any Issues</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>Issues can be anything from harassment, a person you are uncomfortable with, bugs, etc. Moderators are always happy to help!</b></font><br><br><font size=\"13\" color=\"#6E4A2E\"><b>Burrow gives players more freedom than the original game, including free chat. If you do not want to see certain content you may utilise the client side chat filter and block players, which has an option to completely hide them on your side.</b></font><br><br><font size=\"13\" color=\"#6E4A2E\"><b>These options are found in the in-game settings or player cards.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>burrow.moe/terms</b></font>";
// the rules come from the server's data/rules.txt (GET /rules.txt), read
// each time the window opens, so they change without a new client: a
// line starting "# " is a heading, the rest is shown as it is written.
private static const RULES_HEADING:String = "<font size=\"16\" color=\"#563421\"><b>";
private static const RULES_BODY:String = "<font size=\"13\" color=\"#6E4A2E\"><b>";
private static function rulesHtml(param1:String) : String
{
var _loc2_:Array = param1.replace(/\r/g,"").split("\n");
var _loc3_:Array = [];
var _loc4_:String = null;
var _loc5_:int = 0;
while(_loc5_ < _loc2_.length)
{
_loc4_ = String(_loc2_[_loc5_]).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
if(_loc4_.indexOf("# ") == 0)
{
_loc3_.push(RULES_HEADING + _loc4_.substr(2) + "</b></font>");
}
else
{
_loc3_.push(RULES_BODY + _loc4_ + "</b></font>");
}
_loc5_++;
}
return _loc3_.join("<br>");
}
private function loadRules() : void
{
var _loc1_:URLLoader = new URLLoader();
_rulesText.htmlText = rulesHtml("Loading...");
_loc1_.addEventListener("complete",onRulesLoaded);
_loc1_.addEventListener("ioError",onRulesFailed);
_loc1_.addEventListener("securityError",onRulesFailed);
_loc1_.load(new URLRequest(gMainFrame.clientInfo.websiteURL + "rules.txt?t=" + new Date().getTime()));
}
private function onRulesLoaded(param1:Event) : void
{
_rulesText.htmlText = rulesHtml(String(URLLoader(param1.currentTarget).data));
_rulesText.scrollV = 1;
}
private function onRulesFailed(param1:Event) : void
{
_rulesText.htmlText = rulesHtml("The rules could not be loaded. Try again in a moment.");
}
private var _rulesWin:Sprite;
@@ -2338,7 +2570,6 @@ package
_rulesText.y = -158;
_rulesText.width = 462;
_rulesText.height = 338;
_rulesText.htmlText = RULES_HTML;
_loc5_ = GETDEFINITIONBYNAME("arrow_r_btnContOld");
_loc5_.rotation = -90;
_loc5_.x = 236;
@@ -2370,6 +2601,7 @@ package
_rulesWin.visible = param1;
if(param1)
{
loadRules();
_rulesText.scrollV = 1;
setChildIndex(_rulesWin,numChildren - 1);
}
-13
View File
@@ -700,19 +700,6 @@ package gui
{
var _loc2_:WorldPet = null;
param1.stopPropagation();
// Outside a play-as-your-pet event this button is the personal
// pet-form switch. The server echoes the change to everybody in
// the room, so this is not merely a local visual effect.
if(!GuiManager.isBeYourPetRoom())
{
if(AvatarManager.playerAvatarWorldView && AvatarManager.playerAvatarWorldView.getActivePet())
{
UserCommXtCommManager.sendPetPlayerMode(!GuiManager.isPlayingAsPet());
}
actionBtn.dispatchEvent(new MouseEvent("mouseDown"));
param1.currentTarget.downToUpState();
return;
}
if(AvatarManager.playerAvatarWorldView)
{
_loc2_ = AvatarManager.playerAvatarWorldView.getActivePet();
+73 -15
View File
@@ -335,6 +335,12 @@ package avatar
private var _currPetName:String;
private var _shouldShowPetOnly:Boolean;
// the pet chooser's switch as last heard for this avatar (type-13 user
// communication), and the pet last set, to make it again in either form
private var _petPlayerMode:Boolean;
private var _petArgs:Array;
private var _emitParticles:Boolean;
@@ -552,7 +558,7 @@ package avatar
_loc12_ = 1;
}
_chatBalloon = GETDEFINITIONBYNAME("ChatBalloonAsset",false);
_chatBalloon.init(_avatar.avTypeId,AvatarUtility.getAvatarEmoteBgOffset,false,_loc12_,RoomManagerWorld.instance.layerManager.bkg.scaleX,SBTextField,onChatBallonAdventureDown,onChatBalloonPVPDown);
_chatBalloon.init(_avatar.avTypeId,emoteBgOffset,false,_loc12_,RoomManagerWorld.instance.layerManager.bkg.scaleX,SBTextField,onChatBallonAdventureDown,onChatBalloonPVPDown);
_chatLayer.addChild(_chatBalloon);
_moving = 0;
_lastMoveAngle = 2;
@@ -605,7 +611,7 @@ package avatar
_hudViewHolder.mouse.gotoAndStop(offScreenDefaultMouseFrameLabel());
}
}
_shouldShowPetOnly = GuiManager.isBeYourPetRoom() || userId == AvatarManager.playerSfsUserId && GuiManager.isPlayingAsPet();
_shouldShowPetOnly = GuiManager.isBeYourPetRoom() || (userId == AvatarManager.playerSfsUserId ? GuiManager.isPlayingAsPet() : _petPlayerMode);
if(_shouldShowPetOnly)
{
_layerAnim.alpha = 0;
@@ -2066,6 +2072,7 @@ package avatar
public function setActivePet(param1:Number, param2:uint, param3:uint, param4:uint, param5:String, param6:int, param7:int, param8:int, param9:int = 0) : void
{
_petArgs = [param1,param2,param3,param4,param5,param6,param7,param8,param9];
if(_pet)
{
if(_pet.parent == this)
@@ -2094,6 +2101,17 @@ package avatar
{
_splash.showShadow(true);
}
// another pet out in the pet form: the HUD shows the new one
if(_shouldShowPetOnly && userId == AvatarManager.playerSfsUserId)
{
GuiManager.setPersonalPetMode(true);
}
}
// a pet that cannot come into this room leaves the avatar shown
if(_shouldShowPetOnly && !_pet && !GuiManager.isBeYourPetRoom())
{
_shouldShowPetOnly = false;
showPetForm();
}
}
@@ -2102,8 +2120,30 @@ package avatar
// own state instead of asking the room-wide GuiManager predicate.
public function setPetPlayerMode(param1:Boolean) : void
{
var _loc2_:Boolean = param1 && _pet != null;
_shouldShowPetOnly = _loc2_ || GuiManager.isBeYourPetRoom();
var _loc2_:Boolean = false;
_petPlayerMode = param1;
_loc2_ = GuiManager.isBeYourPetRoom() || param1 && _petArgs != null && _petArgs[1] != 0;
if(_loc2_ != _shouldShowPetOnly)
{
_shouldShowPetOnly = _loc2_;
// WorldPet takes its size and place from the form when it is
// made, so the pet is made again
if(_petArgs != null)
{
setActivePet.apply(this,_petArgs);
}
}
showPetForm();
if(userId == AvatarManager.playerSfsUserId)
{
GuiManager.setPersonalPetMode(_shouldShowPetOnly);
}
}
// the avatar or its pet, as _shouldShowPetOnly says
private function showPetForm() : void
{
var _loc1_:UserInfo = null;
_layerAnim.alpha = _shouldShowPetOnly ? 0 : 1;
_layerAnim.avatarEnabled = !_shouldShowPetOnly;
if(_shouldShowPetOnly && _pet)
@@ -2117,12 +2157,32 @@ package avatar
else
{
_splash.showShadow(true);
_namebar.setAvName(_avatar.avName);
}
if(userId == AvatarManager.playerSfsUserId)
{
GuiManager.setPersonalPetMode(_loc2_);
_loc1_ = gMainFrame.userInfo.getUserInfoByUserName(_avatar.userName);
_namebar.setAvName(_avatar,Utility.isSettingOn(MySettings.SETTINGS_USERNAME_BADGE),_loc1_);
}
placeChatBalloon();
updateChatBallonBgOffsets();
}
// the pet stands in for this avatar: the party's or quest's form, or
// the pet chooser's switch (WorldPet asks)
public function isPetForm() : Boolean
{
return _shouldShowPetOnly;
}
// chat balloons and emotes sit over the pet in its form, as the
// party's do (AvatarUtility's pet offsets)
private function placeChatBalloon() : void
{
var _loc1_:Point = _shouldShowPetOnly ? new Point(10,-80) : AvatarUtility.getAvatarChatOffset(_avatar.avTypeId);
_chatBalloon.x = this.x + _loc1_.x;
_chatBalloon.y = this.y + _loc1_.y;
}
private function emoteBgOffset(param1:int) : Point
{
return _shouldShowPetOnly ? new Point(-5,-25) : AvatarUtility.getAvatarEmoteBgOffset(param1);
}
public function getActivePet() : WorldPet
@@ -2281,9 +2341,7 @@ package avatar
param2 *= _scale.y;
this.x = param1;
this.y = param2;
var _loc3_:Point = AvatarUtility.getAvatarChatOffset(_avatar.avTypeId);
_chatBalloon.x = this.x + _loc3_.x;
_chatBalloon.y = this.y + _loc3_.y;
placeChatBalloon();
if(_avSwitchedNPC)
{
_avSwitchedNPC.x = param1;
@@ -2359,9 +2417,9 @@ package avatar
{
_hudViewHolder.mouse.gotoAndStop(offScreenDefaultMouseFrameLabel());
}
if(GuiManager.isBeYourPetRoom())
_loc7_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(userName,perUserAvId);
if(_shouldShowPetOnly && _loc7_ && _loc7_.currPet)
{
_loc7_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(userName,perUserAvId);
_hudAvtOrPetView = new GuiPet(_loc7_.currPet.createdTs,0,_loc7_.currPet.lBits,_loc7_.currPet.uBits,_loc7_.currPet.eBits,_loc7_.currPet.type,_loc7_.currPet.name,_loc7_.currPet.personalityDefId,_loc7_.currPet.favoriteToyDefId,_loc7_.currPet.favoriteFoodDefId,onHudAvtOrPetView);
}
else
@@ -2479,7 +2537,7 @@ package avatar
var _loc3_:Number = NaN;
if(_hudAvtOrPetView)
{
if(GuiManager.isBeYourPetRoom())
if(_hudAvtOrPetView is GuiPet)
{
_hudAvtOrPetView.y = 15;
}
+5 -11
View File
@@ -181,10 +181,6 @@ package gui
private static var _petInventory:PetInventory;
// A player's voluntary pet form. Party and quest pet forms remain
// room-wide and are still reported by isBeYourPetRoom().
private static var _personalPetMode:Boolean = false;
private static var _joeyPopup:MovieClip;
private static var _secondaryJoeyPopup:MovieClip;
@@ -2616,7 +2612,7 @@ package gui
{
mainHud.charWindow.charLayer.removeChildAt(0);
}
if(isBeYourPetRoom())
if(isPlayingAsPet())
{
_loc1_ = PetManager.myActivePet;
if(_loc1_)
@@ -2911,18 +2907,16 @@ package gui
return QuestManager.isBeYourPetQuest() || PartyManager.isBeYourPetParty();
}
// A player's own pet form: the party's and the quest's for everyone in
// the room, or the pet chooser's switch with a pet out.
public static function isPlayingAsPet() : Boolean
{
return _personalPetMode || isBeYourPetRoom();
return isBeYourPetRoom() || AJClient.petFormOn() && PetManager.myActivePet != null;
}
// the player's own avatar came into or out of its pet form
public static function setPersonalPetMode(param1:Boolean) : void
{
if(_personalPetMode == param1)
{
return;
}
_personalPetMode = param1;
if(mainHud)
{
showHudAvt();
+74
View File
@@ -3,6 +3,7 @@ package gui
import Party.PartyManager;
import adoptAPet.AdoptAPetManager;
import avatar.AvatarManager;
import avatar.UserCommXtCommManager;
import com.sbi.analytics.SBTracker;
import com.sbi.popup.SBOkPopup;
import com.sbi.popup.SBYesNoPopup;
@@ -43,6 +44,12 @@ package gui
private var _inventoryMC:MovieClip;
private var _loadingMediaHelper:MediaHelper;
// "play as your pet": the settings menu's on/off switch, in any room
// but a Play-As-Your-Pet party's (AJClient.petFormOn)
private var _petFormSwitch:MovieClip;
private var _petFormOn:Boolean;
private var _loadingSpiralBig:LoadingSpiral;
@@ -222,6 +229,7 @@ package gui
_guiLayer.addChild(_inventoryMC);
DarkenManager.darken(_inventoryMC);
createItemWindows();
addPetFormSwitch();
addEventListeners();
if(_openCheckListImmediately)
{
@@ -246,6 +254,58 @@ package gui
}
// A double click on the big pet's name lets the player type another.
// the switch sits at the top left of the pet's picture, across from
// the certificate. on, whichever pet is out stands in for the avatar,
// for everyone (the server keeps it with the user vars and tells the
// room: UserCommXtCommManager type 13).
private function addPetFormSwitch() : void
{
var _loc1_:MovieClip = null;
if(GuiManager.isBeYourPetRoom())
{
return;
}
_loc1_ = GETDEFINITIONBYNAME("mySettingsToggle",false);
_petFormSwitch = _loc1_.toggleBtn;
_loc1_.removeChild(_petFormSwitch);
_petFormSwitch.x = 78;
_petFormSwitch.y = -143;
_petFormSwitch.buttonMode = true;
_petFormSwitch.useHandCursor = true;
_petFormSwitch.toggleBtn.toggleKnob.gotoAndStop("up");
_petFormSwitch.toggleBtn.toggleBG.gotoAndStop("up");
_petFormOn = AJClient.petFormOn();
_petFormSwitch.toggleBtn.gotoAndStop(_petFormOn ? "startingOn" : "startingOff");
LocalizationManager.translateId(_petFormSwitch.toggleBtn.valueTxt.onTxt,6324);
LocalizationManager.translateId(_petFormSwitch.toggleBtn.valueTxt.offTxt,6322);
_inventoryMC.addChild(_petFormSwitch);
}
private function onPetFormSwitch(param1:MouseEvent) : void
{
param1.stopPropagation();
_petFormOn = !_petFormOn;
_petFormSwitch.toggleBtn.gotoAndPlay(_petFormOn ? "on" : "off");
UserCommXtCommManager.sendPetPlayerMode(_petFormOn);
}
private function onPetFormSwitchOver(param1:MouseEvent) : void
{
param1.stopPropagation();
_petFormSwitch.toggleBtn.toggleBG.gotoAndStop("over");
_petFormSwitch.toggleBtn.toggleKnob.gotoAndStop("over");
GuiManager.toolTip.init(_petFormSwitch,"Play as your pet",58,-10);
GuiManager.toolTip.startTimer(param1);
}
private function onPetFormSwitchOut(param1:MouseEvent) : void
{
param1.stopPropagation();
_petFormSwitch.toggleBtn.toggleBG.gotoAndStop("up");
_petFormSwitch.toggleBtn.toggleKnob.gotoAndStop("up");
GuiManager.toolTip.resetTimerAndSetVisibility();
}
private function onPetRenamed(param1:String) : void
{
var _loc2_:int = 0;
@@ -852,6 +912,12 @@ package gui
_inventoryMC.salonBtn.addEventListener("mouseDown",onSalonBtn,false,0,true);
_inventoryMC.checklistBtn.addEventListener("mouseDown",onChecklistBtn,false,0,true);
_inventoryMC.certBtn.addEventListener("mouseDown",onCertBtn,false,0,true);
if(_petFormSwitch)
{
_petFormSwitch.addEventListener("mouseDown",onPetFormSwitch,false,0,true);
_petFormSwitch.addEventListener("rollOver",onPetFormSwitchOver,false,0,true);
_petFormSwitch.addEventListener("rollOut",onPetFormSwitchOut,false,0,true);
}
}
private function removeEventListeners() : void
@@ -866,6 +932,14 @@ package gui
_inventoryMC.salonBtn.removeEventListener("mouseDown",onSalonBtn);
_inventoryMC.checklistBtn.removeEventListener("mouseDown",onChecklistBtn);
_inventoryMC.certBtn.removeEventListener("mouseDown",onCertBtn);
if(_petFormSwitch)
{
_petFormSwitch.removeEventListener("mouseDown",onPetFormSwitch);
_petFormSwitch.removeEventListener("rollOver",onPetFormSwitchOver);
_petFormSwitch.removeEventListener("rollOut",onPetFormSwitchOut);
GuiManager.toolTip.resetTimerAndSetVisibility();
_petFormSwitch = null;
}
}
}
}
+1 -1
View File
@@ -725,7 +725,7 @@ package avatar
{
if(AvatarManager.avatarViewList[_loc19_])
{
AvatarManager.avatarViewList[_loc19_].setPetPlayerMode(_loc2_ == "on");
AvatarManager.avatarViewList[_loc19_].setPetPlayerMode(param1[3] == "on");
}
}
else
+421
View File
@@ -0,0 +1,421 @@
package pet
{
import avatar.AvatarWorldView;
import avatar.UserCommXtCommManager;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.geom.Matrix;
import gui.GuiManager;
public class WorldPet extends PetBase
{
public static const ANIM_IDLE:int = 0;
public static const ANIM_MOVE:int = 1;
public static const ANIM_IDLE_UP:int = 2;
public static const ANIM_MOVE_UP:int = 3;
public static const ANIM_CLICK:int = 4;
public static const ANIM_IDLE_WATER:int = 10;
public static const ANIM_IDLE_MUD:int = 20;
public static const ANIM_DANCE:int = 31;
public static const ANIM_SLEEP_OR_DIVE:int = 32;
public static const ANIM_HOP_OR_SWIRL:int = 33;
public static const ANIM_PLAY:int = 34;
public static const ANIM_SIT_OR_POSE:int = 35;
public static const ACTION_CLICK:int = 0;
public static const ACTION_SPARKLE:int = 1;
public static const PET_SPARKLE_TIME:int = 7200;
public static var _actionLookup:Array = [{
"name":":dance:",
"animId":31
},{
"name":":sleep:",
"animId":32
},{
"name":":dive:",
"animId":32
},{
"name":":hop:",
"animId":33
},{
"name":":swirl:",
"animId":33
},{
"name":":play:",
"animId":34
},{
"name":":sit:",
"animId":35
},{
"name":":sitNW:",
"animId":35
},{
"name":":sitSW:",
"animId":35
},{
"name":":sitSE:",
"animId":35
},{
"name":":sitNE:",
"animId":35
},{
"name":":pose:",
"animId":35
},{
"name":":poseLeft:",
"animId":35
},{
"name":":poseRight:",
"animId":35
}];
private var _parent:AvatarWorldView;
private var _mode:int;
private var _x:int;
private var _y:int;
private var _targetX:int;
private var _targetY:int;
private var _bNewTarget:Boolean;
private var _dirX:Number;
private var _dirY:Number;
private var _speed:Number;
private var _lastAnim:int;
private var _bFlip:Boolean;
private var _bBack:Boolean;
private var _bUpdateState:Boolean;
private var _parentLastX:Number;
private var _parentLastY:Number;
private var _bSpecialMove:Boolean;
private var _petLoaded:Boolean;
private var _sparkle:int;
private var _offsetX:int = 100;
private var _offsetY:int = -50;
private var _maxSpeed:Number = 1;
private var _accel:Number = 0.03;
private var _scale:Number = 1;
private var _minX:Number = -70;
private var _maxX:Number = 55;
private var _airPetYOffest:Number = -80;
private var _oceanPetXOffset:Number = 55;
private var _petLandLowXOffset:Number = 30;
public function WorldPet(param1:AvatarWorldView, param2:Number, param3:uint, param4:uint, param5:uint, param6:uint, param7:uint, param8:uint, param9:int = 0)
{
super(param2,param3,param4,param5,param6,param7,param8,onPetLoaded);
_sparkle = param9;
_parent = param1;
_targetX = 0;
_bNewTarget = true;
_mode = 1;
_lastAnim = -1;
_bUpdateState = true;
_bFlip = false;
_bBack = false;
_bSpecialMove = false;
_parent.addChild(this);
if(param1.userName.toLowerCase() == gMainFrame.server.userName.toLowerCase() && !_parent.isPetForm())
{
this.addEventListener("mouseDown",onClick,false,0,true);
}
else
{
this.mouseChildren = false;
this.mouseEnabled = false;
}
if(isEggAndHasNotHatched || (getType() == 0 || getType() == 2 || getType() == 4))
{
if(_parent.isPetForm())
{
_y = -5;
GuiManager.actionMgr.grayOutPetDanceBtn(false);
}
else
{
_y = 0;
}
}
else
{
GuiManager.actionMgr.grayOutPetDanceBtn(true);
if(_parent.isPetForm())
{
_y = -5;
}
else
{
_y = _airPetYOffest;
}
}
_parentLastX = _parent.x;
_parentLastY = _parent.y;
if(_parent.isPetForm())
{
_minX = 25;
_maxX = -30;
_x = _maxX;
_parentLastX = 0;
}
else
{
if(getType() == 2)
{
_minX -= _oceanPetXOffset;
_maxX += _oceanPetXOffset;
}
else if(getType() == 0)
{
if(param1.avTypeId != 5)
{
_minX -= _petLandLowXOffset;
}
}
_x = 0;
}
_targetX = 0;
}
override public function destroy() : void
{
super.destroy();
this.removeEventListener("mouseDown",onClick);
}
public function heartbeat(param1:int, param2:Boolean) : void
{
var _loc5_:int = 0;
var _loc3_:Matrix = null;
var _loc4_:int = 0;
if(_content && _parent && !_parent.isOffScreen)
{
if(_parent.isPetForm())
{
if(_parentLastX != _parent.x)
{
if(_parent.x > _parentLastX)
{
if(!_bFlip)
{
_parent.flipSplash(true);
_bFlip = true;
_x = _minX;
}
}
else if(_bFlip)
{
_parent.flipSplash(false);
_bFlip = false;
_x = _maxX;
}
_parentLastX = _parent.x;
}
}
else
{
if(_targetX == 0)
{
_targetX = _parent.hFlip ? _minX : _maxX;
}
if(_parentLastX != _parent.x)
{
_bFlip = _parent.x > _parentLastX ? true : false;
if(Math.abs(_parentLastX - _parent.x) > 13)
{
_targetX = _bFlip ? _minX : _maxX;
}
_parentLastX = _parent.x;
}
if(_parentLastY != _parent.y)
{
_bBack = _parent.y < _parentLastY - 10 ? true : false;
_parentLastY = _parent.y;
}
if(_x > _targetX)
{
_x -= 10;
if(_x <= _targetX)
{
_x = _targetX;
}
_bFlip = _x == _targetX ? true : false;
}
if(_x < _targetX)
{
_x += 10;
if(_x > _targetX)
{
_x = _targetX;
}
_bFlip = _x == _targetX ? false : true;
}
}
if(_bUpdateState)
{
PetManager.setPetState(_content,_lBits,_uBits,_eBits);
_bUpdateState = false;
}
_loc5_ = _parent.inSplashVolume() ? 10 : 0;
if(_loc5_ && _parent.splashLiquid == "mud")
{
_loc5_ = 20;
}
if(_parent.splashLiquid != "mud" && _parent.splashLiquid != "water")
{
_loc5_ = 0;
}
_loc3_ = _content.transform.matrix;
_loc3_.identity();
_loc3_.scale(_bFlip ? -_scale : _scale,_scale);
_loc3_.translate(_x,_y - param1);
_content.transform.matrix = _loc3_;
_loc4_ = _loc5_ + param2;
if(_bBack)
{
_loc4_ += 2;
}
if((param2 || _lastAnim <= 4) && _lastAnim != _loc4_)
{
_lastAnim = _loc4_;
_content.pet.setAnim(_loc4_);
}
if(_bSpecialMove)
{
_bSpecialMove = false;
if(!param2)
{
_content.pet.setAnim(4 + _loc5_);
}
}
}
}
public function setState(param1:Array) : void
{
_lBits = param1[0];
_uBits = param1[1];
_eBits = param1[2];
_bUpdateState = true;
}
public function setAction(param1:int, param2:int = 0) : void
{
switch(param1)
{
case 0:
onClick();
break;
case 1:
setSparkle(param2);
}
}
public function setActionByName(param1:String) : void
{
var _loc2_:int = 0;
for each(var _loc3_:Object in _actionLookup)
{
if(_loc3_.name == param1)
{
_loc2_ = int(_loc3_.animId);
if(_loc2_ > 0)
{
_lastAnim = _loc2_;
if(_content)
{
_content.pet.setAnim(_loc2_);
}
}
break;
}
}
}
public function onClick(param1:MouseEvent = null) : void
{
if(param1)
{
param1.stopPropagation();
UserCommXtCommManager.sendPetAction(0);
}
_bSpecialMove = true;
}
private function onPetLoaded(param1:MovieClip) : void
{
if(_parent.isPetForm())
{
_content.pet.scaleX = _content.pet.scaleY = 2;
}
_content.pet.setSparkle(_sparkle);
}
private function convertAvtAnimToPetAnim() : int
{
switch(_parent.animId)
{
case 23:
case 38:
return 31;
case 22:
case 41:
return 32;
case 17:
case 33:
return 33;
case 6:
case 39:
return 34;
case 2:
case 4:
case 40:
break;
default:
return _parent.isPetMovingTest() ? 0 : 1;
}
return 35;
}
}
}
BIN
View File
Binary file not shown.
+9 -3
View File
@@ -13,8 +13,11 @@ const os = require("os");
const path = require("path");
class GameClient {
constructor(gamePort) {
// `localAddress`: another loopback address to come from (127.0.0.2), for
// what the server tells apart by address.
constructor(gamePort, localAddress = undefined) {
this.gamePort = gamePort;
this.localAddress = localAddress;
this.queue = [];
this.varUpdates = [];
this.askedForGames = 0;
@@ -25,7 +28,7 @@ class GameClient {
connect() {
return new Promise((resolve, reject) => {
this.socket = net.connect(this.gamePort, "127.0.0.1", resolve);
this.socket = net.connect({port: this.gamePort, host: "127.0.0.1", localAddress: this.localAddress}, resolve);
this.socket.once("error", reject);
this.socket.on("data", chunk => {
this.buffer = Buffer.concat([this.buffer, chunk]);
@@ -163,7 +166,10 @@ const withServer = async (name, httpPort, gamePort, run, {dataDir: keptDir = nul
// everyone arrives in the township, as the tests expect
AJ_SPAWN_ROOMS: process.env.AJ_SPAWN_ROOMS || "jamaa_township.room_main",
// and in the one world
AJ_WORLDS: process.env.AJ_WORLDS || "1"},
AJ_WORLDS: process.env.AJ_WORLDS || "1",
// the packs made again at once after a custom item changes
AJ_PACK_REMAKE_MS: process.env.AJ_PACK_REMAKE_MS || "0",
AJ_MASTERPIECE_MIN_AGE: process.env.AJ_MASTERPIECE_MIN_AGE || "0"},
stdio: ["ignore", "pipe", "inherit"],
});
let output = "";
+71
View File
@@ -8,6 +8,7 @@
const assert = require("assert");
const crypto = require("crypto");
const fs = require("fs");
const http = require("http");
const os = require("os");
const path = require("path");
const zlib = require("zlib");
@@ -119,6 +120,34 @@ const untilDefs = async (client, kind) => {
}
}
};
// a game on another address: it fetches the packs with custom items in, and
// at login is sent of them only what they may lack (customItems.sendAll),
// all of it before the chat filter settings ("xfl").
const ELSEWHERE = "127.0.0.2";
const packsFrom = address => Promise.all([1000, 1030, 10230].map(id => new Promise((resolve, reject) => {
http.get(`${BASE}/${cdn.hashedPath(`defPacks/${id}`)}`, {localAddress: address}, res => {
assert.strictEqual(res.statusCode, 200);
res.resume();
res.on("end", resolve);
}).on("error", reject);
})));
const defsAtLogin = async (username, password, address) => {
const auth = await (await postJson(`${BASE}/authenticate`, {username, password})).json();
const client = new harness.GameClient(GAME_PORT, address);
await client.connect();
assert.strictEqual((await client.logIn(username, auth.auth_token)).status, "1");
const defs = {clothing: [], den: []};
for (;;) {
const fields = (await client.next()).split("%").slice(2, -1);
if (fields[0] === "xfl") {
client.socket.destroy();
return defs;
}
if (fields[0] === "xdi") {
defs[fields[2]].push(...JSON.parse(fields[3]));
}
}
};
const nextBox = async client => (await client.untilXt("xtl"))[2];
const shopList = async (client, roomId, shop) => {
client.xt("gl", roomId, shop);
@@ -194,6 +223,7 @@ const first = async () => {
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(row.avatarUseFlags, crownRow.avatarUseFlags); // and so in what games playing are sent
assert.strictEqual((await strings())[9100000], "Test Crown");
// first in the shop of oddities, and Pat can buy it in a colour it has
@@ -235,6 +265,20 @@ const first = async () => {
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");
// a game whose address fetched the packs since has every item from them,
// and is sent none again; then only the one changed after
await packsFrom(ELSEWHERE);
assert.deepStrictEqual(await defsAtLogin("Lou", people.Lou, ELSEWHERE), {clothing: [], den: []});
assert.match((await dev("/mod/api/items", {action: "update", kind: "clothing", id: 50000, cost: 7})).data.ok, /changed/);
assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].value, "7");
const changedSince = await defsAtLogin("Lou", people.Lou, ELSEWHERE);
assert.deepStrictEqual(changedSince.clothing.map(row => `${row.id} ${row.name} ${row.value}`), ["50000 Gold Crown 7"]);
assert.deepStrictEqual(changedSince.den, []);
// a row carries what the client reads of it, not the whole base row
const wire = ["id", "layerDefId", "layerId", "type", "value", "titleStrId", "isGiftable", "membersOnly", "itemStatus", "enviroType",
"avatarUseFlags", "recycleValue", "currencyType", "defense", "attack", "attackMediaRefId", "combatType", "modifierType",
"modifierValue", "criticalHit", "combinedCost", "colors", "availabilityStartTime", "availabilityEndTime", "name", "art", "artMode"];
assert.deepStrictEqual(Object.keys(changedSince.clothing[0]).filter(field => !wire.includes(field)), []);
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");
@@ -385,6 +429,10 @@ const first = async () => {
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]]);
// the packs have no pictures: a game logging in is sent each one, however new its packs
await packsFrom(ELSEWHERE);
const pictured = (await defsAtLogin("Lou", people.Lou, ELSEWHERE)).clothing;
assert.deepStrictEqual(pictured.filter(row => row.art).map(row => [row.id, row.art]), [[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());
@@ -584,11 +632,34 @@ const second = async () => {
lou.client.socket.destroy();
};
// the packs made again at most every AJ_PACK_REMAKE_MS after a change: one
// fetched before then is the one made before, and a game whose address
// fetched it is sent at login the item it lacks.
const REMAKE_MS = 5000;
const third = async () => {
const fetchedEarlier = "127.0.0.3";
await packsFrom(fetchedEarlier);
const lou = await arrive("Lou", people.Lou);
lou.client.xt("xcm", lou.roomId, "make", "clothing", made.base.id, "Lou Hat");
const answer = await lou.client.untilXt("xcm");
assert.strictEqual(answer[2], "1", answer[3]);
const louHat = JSON.parse(answer[6]).find(entry => entry.name === "Lou Hat");
assert.ok(!byId(await pack(1000), louHat.id)); // the pack of before, for a moment
const atLogin = await defsAtLogin("Pat", people.Pat, fetchedEarlier);
assert.deepStrictEqual(atLogin.clothing.filter(row => row.id === String(louHat.id)).map(row => row.name), ["Lou Hat"]);
await new Promise(resolve => setTimeout(resolve, REMAKE_MS + 200));
assert.strictEqual(byId(await pack(1000), louHat.id).titleStrId, String(9100000 + louHat.id - 50000));
assert.strictEqual((await strings())[9100000 + louHat.id - 50000], "Lou Hat");
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});
process.env.AJ_PACK_REMAKE_MS = String(REMAKE_MS);
await harness.withServer("items test (packs made again at most so often)", HTTP_PORT, GAME_PORT, third, {dataDir});
}
finally {
fs.rmSync(dataDir, {recursive: true, force: true, maxRetries: 10, retryDelay: 200});
+3
View File
@@ -180,6 +180,9 @@ const run = async () => {
const made = await a.untilXt("pc");
assert.strictEqual(made[2], "1");
assert.ok(Number(made[10]) <= Date.now() / 1000 - 259200);
// ... and named from the hatched popup (EggPetHatchedPopup waits for this answer)
a.xt("pn", roomId, made[5], 15386, 15428);
assert.deepStrictEqual((await a.untilXt("pn")).slice(2), ["1", made[5], "15386|15428"]);
// --- she starts in the township as ever, in a look picked at random if she asked for one
say(a, roomId, "!theme random on");
+1
View File
@@ -60,6 +60,7 @@ set -- \
gui.RecycleItems RecycleItems.as \
gui.AvatarEditor AvatarEditor.as \
gui.PetInventory PetInventory.as \
pet.WorldPet WorldPet.as \
gui.DenEditor DenEditor.as \
gui.TradeManager TradeManager.as \
avatar.AvatarView AvatarView.as \