feat: redemption codes, world count, den visitor count and more fixes

- codes made in the admin panel (Messages) give an item, gems or
  diamonds through the game's Redeem Code window, which was never
  answered; its "need help?" says what codes are here
- the number of worlds is set in the admin panel (Debug), live
- a den's owner is told how many are in it: the HUD's count and doorbell
- the map counts the player's buddies in each land of their world
- gifts whose item no longer exists, or with a nonsense amount, are no
  gift at all, rather than a window that will not close
- custom item pictures are 256 pixels and 100 KB at most
- the account page's buddies and den visitors fold away
- shops no longer count down "X days left"
This commit is contained in:
Burrowdev committed 2026-10-23 22:25:35 +03:00
1 parent 15f321fb00
commit 7de41ceed5
14 files changed
+707 -27

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
"use strict";
const accounts = require("./accounts.js");
const defpacks = require("./defpacks.js");
// codes players type into the game's "Redeem Code" window
// (gameRedemption.CodeRedemptionPopup, "grc" in lib/world.js), made in the
// admin panel. a code gives one thing: a clothing item (in a colour), a den
// item, gems or diamonds, as a gift from Burrow HQ (lib/ecards.js
// sendFromHq). each account may use a code once; a code may also have an
// end to how many times it is used in all, and is then spent.
const SCHEMA = `
CREATE TABLE IF NOT EXISTS redeem_codes (
code TEXT PRIMARY KEY,
kind TEXT NOT NULL,
item INTEGER NOT NULL DEFAULT 0,
amount INTEGER NOT NULL DEFAULT 0,
color INTEGER,
uses INTEGER NOT NULL DEFAULT 0,
used INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS redeem_uses (
code TEXT NOT NULL,
account_id INTEGER NOT NULL,
at INTEGER NOT NULL,
PRIMARY KEY (code, account_id)
);
`;
const KINDS = ["clothing", "den", "gems", "diamonds"];
const CODE = /^[A-Z0-9-]{3,32}$/; // what the game's box lets be typed (and in capitals)
const MAX_AMOUNT = 10000000;
const MAX_USES = 1000000;
let made = false;
const db = () => {
const database = accounts.database();
if (!made) {
database.exec(SCHEMA);
made = true;
}
return database;
};
const now = () => Math.floor(Date.now() / 1000);
const normal = code => String(code || "").trim().toUpperCase();
const row = entry => ({code: entry.code, kind: entry.kind, item: entry.item, amount: entry.amount, color: entry.color,
uses: entry.uses, used: entry.used, createdAt: entry.created_at});
const list = () => db().prepare("SELECT * FROM redeem_codes ORDER BY created_at DESC").all().map(row);
// {code, kind, item, amount, color, uses}: returns {ok} or {error}.
const create = fields => {
const code = normal(fields.code);
const kind = String(fields.kind || "");
const uses = Number(fields.uses) || 0;
if (!CODE.test(code)) {
return {error: "A code is 3 to 32 letters, digits and dashes."};
}
if (!KINDS.includes(kind)) {
return {error: "A code gives clothing, a den item, gems or diamonds."};
}
if (!Number.isInteger(uses) || uses < 0 || uses > MAX_USES) {
return {error: "Uses: 0 for any number, or how many in all."};
}
let item = 0;
let amount = 0;
let color = null;
if (kind === "clothing") {
item = Number(fields.item);
const def = defpacks.itemDef(item);
if (!def || !defpacks.clothingIds().includes(item)) {
return {error: "No clothing item with that id."};
}
const own = String(def.colors).split(",").map(Number);
const chosen = fields.color === undefined || String(fields.color).trim() === "" ? own[0] : Number(fields.color);
if (!Number.isInteger(chosen) || chosen < -0x80000000 || chosen > 0xFFFFFFFF) {
return {error: "A colour as the game writes it (a whole number), or none for the item's own."};
}
color = chosen >>> 0;
}
else if (kind === "den") {
item = Number(fields.item);
if (!defpacks.denItemIds().includes(item)) {
return {error: "No den item with that id."};
}
}
else {
amount = Number(fields.amount);
if (!Number.isInteger(amount) || amount < 1 || amount > MAX_AMOUNT) {
return {error: "An amount from 1 to 10,000,000."};
}
}
if (db().prepare("SELECT 1 FROM redeem_codes WHERE code = ?").get(code)) {
return {error: "That code is taken."};
}
db().prepare("INSERT INTO redeem_codes (code, kind, item, amount, color, uses, used, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?)")
.run(code, kind, item, amount, color, uses, now());
return {ok: `${code} made.`};
};
const remove = code => db().prepare("DELETE FROM redeem_codes WHERE code = ?").run(normal(code)).changes > 0;
// a code typed in the game, for `account`: {gift} for lib/ecards.js
// sendFromHq, or {error: "unknown" | "used" | "spent"}. the use is noted.
const redeem = (account, typed) => {
const code = normal(typed);
const entry = CODE.test(code) ? db().prepare("SELECT * FROM redeem_codes WHERE code = ?").get(code) : null;
if (!entry) {
return {error: "unknown"};
}
if (db().prepare("SELECT 1 FROM redeem_uses WHERE code = ? AND account_id = ?").get(code, account.id)) {
return {error: "used"};
}
if (entry.uses > 0 && entry.used >= entry.uses) {
return {error: "spent"};
}
db().prepare("INSERT INTO redeem_uses (code, account_id, at) VALUES (?, ?, ?)").run(code, account.id, now());
db().prepare("UPDATE redeem_codes SET used = used + 1 WHERE code = ?").run(code);
const gift = entry.kind === "clothing" ? {kind: "clothing", id: entry.item, color: entry.color}
: entry.kind === "den" ? {kind: "den", id: entry.item} : {kind: entry.kind, amount: entry.amount};
return {gift, code};
};
// a use taken back, when the gift could not be sent after all
const unredeem = (account, code) => {
if (db().prepare("DELETE FROM redeem_uses WHERE code = ? AND account_id = ?").run(code, account.id).changes > 0) {
db().prepare("UPDATE redeem_codes SET used = MAX(used - 1, 0) WHERE code = ?").run(code);
}
};
module.exports = {list, create, remove, redeem, unredeem, KINDS};
+34 -7
View File
@@ -77,8 +77,23 @@ const now = () => Math.floor(Date.now() / 1000);
const clean = text => String(text).replace(/[\u0000-\u001f\u007f%]/g, " ").trim().slice(0, MAX_MESSAGE);
module.exports = ({findOnline, blocks}) => {
// a gift the game can show and take: its item still exists (a custom item
// may have been deleted since), or an amount that makes sense. any other
// left the gift windows stuck; it is treated as no gift at all.
const MAX_GIFT_AMOUNT = 10000000;
const giftUsable = gift => {
if (gift.type === TYPE_CLOTHING) {
return Boolean(defpacks.itemDef(gift.def)) && Number.isFinite(Number(gift.color));
}
if (gift.type === TYPE_DEN_ITEM) {
return Boolean(defpacks.denItemDef(gift.def));
}
const amount = Number(gift.def);
return Object.hasOwn(CURRENCY_OF, gift.type) && Number.isInteger(amount) && amount > 0 && amount <= MAX_GIFT_AMOUNT;
};
// A card from the server carrying gems or diamonds: one of the popups.
const isRedemption = card => Boolean(card.hq && card.gift && Object.hasOwn(CURRENCY_OF, card.gift.type));
const isRedemption = card => Boolean(card.hq && card.gift && giftUsable(card.gift) && Object.hasOwn(CURRENCY_OF, card.gift.type));
// who sent a card: by account id, and for cards from before ids were
// kept by the name on them.
@@ -98,9 +113,10 @@ module.exports = ({findOnline, blocks}) => {
const sender = card.hq ? null : senderOf(card);
const senderType = isRedemption(card) ? FROM_REDEMPTION : card.hq ? FROM_HQ : FROM_PLAYER;
const name = card.secret ? "" : senderType === FROM_HQ ? HQ_NAME_STRING : card.hq ? HQ_NAME : card.from;
const gift = card.gift && giftUsable(card.gift) ? card.gift : null;
return [
card.id, name, card.card, card.stamp, card.read ? 1 : 0, card.msg, card.gift ? card.gift.type : TYPE_PLAIN,
card.gift ? giftId(card.gift) : 0, card.gift ? card.gift.color : 0, card.gift ? card.gift.name : 0,
card.id, name, card.card, card.stamp, card.read ? 1 : 0, card.msg, gift ? gift.type : TYPE_PLAIN,
gift ? giftId(gift) : 0, gift ? gift.color : 0, gift ? gift.name : 0,
card.hq || card.secret ? MEMBER : sender ? sender.accountType : 0,
0, // name bar data
0, // secondary type
@@ -110,7 +126,7 @@ module.exports = ({findOnline, blocks}) => {
// patched client (ECardInbox) can show a custom item as itself (its
// own picture and name) and not as the art it was made from. (the
// "|" keeps the game from taking it for an HQ gift's own message.)
card.gift && card.gift.type === TYPE_CLOTHING ? `item|${card.gift.def}` : "",
gift && gift.type === TYPE_CLOTHING ? `item|${gift.def}` : "",
card.secret ? SECRET_VALENTINE : 0,
];
};
@@ -163,7 +179,11 @@ module.exports = ({findOnline, blocks}) => {
}
else {
// for these the card's "gift id" and "gift name" are both the amount.
attached = {type: gift.kind === "gems" ? TYPE_GEMS : TYPE_DIAMONDS, def: gift.amount, color: 0, name: gift.amount};
const amount = Number(gift.amount);
if (!Number.isInteger(amount) || amount < 1 || amount > MAX_GIFT_AMOUNT) {
return "An amount from 1 to 10,000,000";
}
attached = {type: gift.kind === "gems" ? TYPE_GEMS : TYPE_DIAMONDS, def: amount, color: 0, name: amount};
}
// the gift popup takes a message that starts with a number for the id of
// a localization string (StartupPopups.setupGiftPopup).
@@ -226,8 +246,8 @@ module.exports = ({findOnline, blocks}) => {
}
else if (Object.hasOwn(CURRENCY_OF, gift.type)) {
const currency = CURRENCIES[CURRENCY_OF[gift.type]];
account.currency[currency] = (account.currency[currency] || 0) + gift.def;
achievements.currencyChanged(account, currency, gift.def);
account.currency[currency] = (account.currency[currency] || 0) + Number(gift.def);
achievements.currencyChanged(account, currency, Number(gift.def));
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
session.sendXt("cu", -1, CURRENCY_OF[gift.type], account.currency[currency], 0);
}
@@ -333,6 +353,13 @@ module.exports = ({findOnline, blocks}) => {
return;
}
const {gift} = card;
// a gift that cannot be had (above): gone, and the window let go
if (!giftUsable(gift)) {
card.gift = null;
accounts.save(session.account);
session.sendXt("eg", -1, msgId, 1);
return;
}
// no room for it: it stays in the card until there is.
if (accept === "1" && ((gift.type === TYPE_CLOTHING && !hasRoom(session.account, "items"))
|| (gift.type === TYPE_DEN_ITEM && !hasRoom(session.account, "denItems")))) {
+2 -2
View File
@@ -22,9 +22,9 @@ const imageModeration = require("./image-moderation.js");
// kept as data/itemart/<kind>-<id>.<png|jpg|gif>; its version, a hash, is on
// the item (customItems.setArt), so a new picture is a new address.
const MAX_BYTES = 300 * 1024; // a picture kept
const MAX_BYTES = 100 * 1024; // a picture kept: every player who sees the item downloads it
const MAX_UPLOAD = 2 * 1024 * 1024; // one sent (a BMP is bigger than the PNG it becomes)
const MAX_SIDE = 512;
const MAX_SIDE = 256; // drawn fitted to the item anyway (a den item's place is 160)
const MIN_SIDE = 8;
const DIR = path.join(config.dataDir, "itemart");
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
+30
View File
@@ -32,6 +32,7 @@ const support = require("./support.js");
const totp = require("./totp.js");
const manage = require("./manage.js");
const world = require("./world.js");
const codes = require("./codes.js");
const {activeAvatar} = require("./player.js");
// the admin panel at /admin: the only place the server is administered from.
@@ -92,6 +93,11 @@ const passwordAcceptable = password =>
typeof password === "string" && password.length >= MIN_PASSWORD_LENGTH && password.length <= MAX_PASSWORD_LENGTH;
const load = () => {
// the number of worlds the admin chose last (world.setWorldCount)
const worlds = accounts.setting(world.WORLD_COUNT_SETTING);
if (worlds !== null) {
world.setWorldCount(worlds, false);
}
if (!hasPassword()) {
setupCode = crypto.randomBytes(5).toString("hex");
console.log(`[admin] no admin password yet: open ${logText(config.baseUrl)}admin to choose one`
@@ -314,6 +320,8 @@ const debugState = () => ({
}).sort((a, b) => a.path.localeCompare(b.path)),
everythingOnSale: sales.everythingOnSale(),
theatreBrowser: theatreBrowserOn(),
worlds: config.shards.length,
maxWorlds: config.worldNames.length,
});
const debugAct = body => {
@@ -331,6 +339,11 @@ const debugAct = body => {
? "Sale dates are off: every item shows, for players who start the game from now on."
: "Sale dates are back on, for players who start the game from now on."};
}
if (body.action === "worlds") {
const count = world.setWorldCount(body.count);
return count ? {ok: `${count} ${count === 1 ? "world" : "worlds"}: ${config.shards.map(shard => shard.name).join(", ")}.`}
: {error: "A number of worlds, please."};
}
if (body.action === "theatreBrowser") {
accounts.setSetting(THEATRE_BROWSER_SETTING, body.on === true ? "on" : "off");
return {ok: body.on === true
@@ -1112,6 +1125,23 @@ const handle = async (req, res, url, from, web) => {
return;
}
// codes for the game's Redeem Code window (lib/codes.js), each giving
// an item, gems or diamonds
case "GET /admin/api/codes":
reply(200, {codes: codes.list(), kinds: codes.KINDS});
return;
case "POST /admin/api/codes": {
const result = body.action === "remove"
? (codes.remove(body.code) ? {ok: "Code deleted."} : {error: "No such code."})
: codes.create(body);
if (result.ok) {
console.log(`[admin] redemption code ${logText(body.action === "remove" ? "deleted" : "made")}: ${logText(String(body.code || "").toUpperCase())}`);
}
reply(result.ok ? 200 : 400, result);
return;
}
// the message everyone is shown when they arrive; empty for none.
case "POST /admin/api/motd":
world.setMotd(String(body.text || ""));
+100 -4
View File
@@ -20,6 +20,7 @@ const bans = require("./bans.js");
const devices = require("./devices.js");
const chatlog = require("./chatlog.js");
const support = require("./support.js");
const codes = require("./codes.js");
const chatFilter = require("./chatfilter.js");
const chatSpam = require("./chatspam.js");
const chatStyles = require("./chatstyles.js");
@@ -181,6 +182,7 @@ const LOGIN_OUTDATED = -12;
const THEME_PATH_PREFIX = "theme_"; // lib/http.js looks for this
const chatLines = limits.limiter(config.chatLinesPerWindow, config.chatWindowMs);
const codeTries = limits.limiter(10, 60000); // codes typed, per account a minute
// emotes, actions, attachments: each goes to everyone in the room, so a
// player pressing one over and over slowed a busy room for all of them.
const roomActions = limits.limiter(config.roomActionsPerWindow, config.roomActionWindowMs);
@@ -242,6 +244,7 @@ const watchers = session => others(session).filter(other => sees(other, session)
const FEEDBACK_KINDS = new Map([[1, "Theatre feedback"], [3, "Feedback"], [4, "Jamaa Journal feedback"], [5, "Feedback"],
[11, "Theatre feedback"], [18, "Jammer Wall feedback"], [19, "Chat feedback"], [21, "Theatre feedback"], [22, "Theatre feedback"]]);
const TYPING_EVERY_MS = 2000; // "typing" passed on at most this often per player (xty)
const WORLD_COUNT_SETTING = "worldCount"; // how many worlds the admin chose (setWorldCount)
// tags ("@name") in chat and on Jammer Walls (xmn): the longest player's
// name that the text after an "@" starts with, ending where a word does
@@ -1121,6 +1124,42 @@ const handlers = {
}
},
// the game's Redeem Code window (GameRedemptionXtCommManager.requestRedeemCode):
// [code, captcha question, answer], a code made in the admin panel
// (lib/codes.js). the reply (CodeRedemptionPopup.onCodeRedeemResponse) is
// "1" redeemed: the gift comes as a card from HQ, or for gems and diamonds
// as a gift popup, whose card says so itself (lib/ecards.js deliver);
// "-4" not now (used already, and an HQ popup says so); else "that code
// didn't work". it was not answered at all, and the window spun.
grc(session, roomId, [code]) {
const {account} = session;
if (!codeTries.allow(account.id)) {
session.sendXt("grc", -1, "-4", "", 0);
return;
}
const result = codes.redeem(account, code);
if (result.error === "used" || result.error === "spent") {
tell(session, result.error === "used" ? "You have used that code already." : "That code has been used up.");
session.sendXt("grc", -1, "-4", "", 0);
return;
}
if (result.error) {
session.sendXt("grc", -1, "0", "", 0);
return;
}
const problem = ecards.sendFromHq(account, `Code ${result.code} redeemed!`, result.gift);
if (problem) {
codes.unredeem(account, result.code);
tell(session, `${problem}. The code can be used once there is room.`);
session.sendXt("grc", -1, "-4", "", 0);
return;
}
if (result.gift.kind === "clothing" || result.gift.kind === "den") {
session.sendXt("grc", -1, "1", "", 0);
tell(session, "Code redeemed! Your gift is in your Jam-A-Grams.");
}
},
// the patched client's tags (AJClient.resolveMentions): xmn [id, the text
// after each "@", ...] -> "xmn" [.., .., id, then for each text: how many
// of its characters are a player's name (0 for none), the name as it is
@@ -1206,11 +1245,28 @@ const handlers = {
// VolumeSelector.handleRoomCountResponse: the head-count shown on each land
// of the world map, as [count, (roomName, players)...].
// the map's buddy counts (VolumeSelector.handleRoomCountResponse): how
// many of the player's buddies are in each land of the player's world.
// the map takes a land from the room's name (an ocean's from its room)
// and keeps the last number it gets for it, so each land comes once,
// its rooms added up. it counted everyone in every room of every world.
// dens, parties and adventures are left out, whose names are nobody
// else's business.
rc(session) {
// the lands and their shops, as the map shows them: not dens, parties,
// or anybody's adventure, whose names are nobody else's business.
const counts = [...rooms.values()].filter(room => !room.denOwner && room.roomType === 0).flatMap(room => [room.name, room.sessions.size]);
session.sendXt("rc", -1, counts.length / 2, ...counts);
const counts = new Map(); // a name the map reads its land from -> buddies there
const world = session.worldId || config.shards[0].id;
for (const other of online.values()) {
const {room} = other;
if (other === session || !room || room.denOwner || room.roomType !== 0 || worldOf(room.name) !== world
|| !session.account.buddies.includes(other.account.username.toLowerCase()) || !sees(session, other)
|| blocks.either(session.account, other.account)) {
continue;
}
const [land, place = ""] = room.base.split(".");
const key = land === "oceans" ? `oceans.${place}#${world}` : `${land}.room_main#${world}`;
counts.set(key, (counts.get(key) || 0) + 1);
}
session.sendXt("rc", -1, counts.size, ...[...counts].flat());
},
// RoomXtCommManager.sendRoomJoinRequestFull: [nameOrId, confirmLanguage, invisible, joinType]
@@ -1453,6 +1509,19 @@ Object.assign(handlers, avatarHandlers(context), itemHandlers(context), pets.han
parties.handlers, ecards.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers,
playerItems.handlers({itemsTaken: (...args) => itemsTaken(...args)}));
// a den's owner, wherever they are, is told how many are in it: the HUD's
// den count, with the doorbell when it goes up (DenXtCommManager.denRoomCount,
// GuiManager.updateDenRoomCount: [count, 1 if they are among them, owner]).
// someone they cannot see is not counted.
const tellDenCount = room => {
const owner = room && room.denOwner ? findOnline(room.denOwner.username) : null;
if (!owner) {
return;
}
const inside = [...room.sessions].filter(other => other === owner || sees(owner, other));
owner.sendXt("drc", -1, inside.length, inside.includes(owner) ? 1 : 0, room.denOwner.username);
};
const leaveRoom = session => {
const {room} = session;
if (!room) {
@@ -1475,6 +1544,7 @@ const leaveRoom = session => {
if (room.sessions.size === 0) {
rooms.delete(room.name);
}
tellDenCount(room);
};
// the Bio tab's words: the bio, under the time played when the player
@@ -1647,6 +1717,7 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
if (props.denOwner && props.denOwner !== session.account) {
noteDenVisit(props.denOwner, session.account);
}
tellDenCount(room);
roomInfo.ensure(base);
const avatar = activeAvatar(session.account);
pets.walked(session.account);
@@ -2246,6 +2317,31 @@ module.exports = {
return true;
},
// how many worlds there are (the admin panel), from 1 to 10, kept as a
// setting. the list is changed where it is (config.shards: everything
// reads it from there), so the world picker shows the new ones at once;
// whoever is in a world that is gone is moved to the first.
WORLD_COUNT_SETTING,
setWorldCount(count, keep = true) {
const wanted = Math.min(config.worldNames.length, Math.max(1, Math.floor(Number(count))));
if (!Number.isFinite(wanted)) {
return null;
}
config.shards.splice(0, config.shards.length, ...config.worldNames.slice(0, wanted).map((name, i) => ({id: i + 1, name})));
if (keep) {
accounts.setSetting(WORLD_COUNT_SETTING, String(wanted));
}
for (const session of online.values()) {
if (session.worldId > wanted) {
session.worldId = config.shards[0].id;
if (session.room && worldOf(session.room.name) === 0 && /#\d+$/.test(session.room.name)) {
sendHome(session);
}
}
}
return wanted;
},
// the panel's Debug page: puts a playing account into any room of the room
// list, as that room and nothing more (a den's file without its owner, a
// party's without the party). returns what is wrong, or null.