Initial Modpack Upload

This commit is contained in:
Rbanh committed 2023-08-14 21:45:09 -04:00
1 parent 268b0650aa
commit 3d8b956ee4
1429 files changed
+820128

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/abuse-monitor.ts"],
"sourcesContent": ["/**\r\n * Neural net chat'filters'.\r\n * These are in a separate file so that they don't crash the other filters.\r\n\t * (issues with globals, etc)\r\n * We use Google's Perspective API to classify messages.\r\n * @see https://perspectiveapi.com/\r\n * by Mia.\r\n * @author mia-pi-git\r\n */\r\nimport * as Artemis from '../artemis';\r\nimport {FS, Utils} from '../../lib';\r\nimport {Config} from '../config-loader';\r\nimport {toID} from '../../sim/dex-data';\r\nimport {getBattleLog, getBattleLinks, HelpTicket} from './helptickets';\r\nimport type {GlobalPermission} from '../user-groups';\r\n\r\nconst WHITELIST = [\"mia\"];\r\nconst MUTE_DURATION = 7 * 60 * 1000;\r\nconst DAY = 24 * 60 * 60 * 1000;\r\nconst STAFF_NOTIF_INTERVAL = 10 * 60 * 1000;\r\nconst MAX_MODLOG_TIME = 2 * 365 * DAY;\r\nconst NON_PUNISHMENTS = ['MUTE', 'REPORT'];\r\nconst NOJOIN_COMMAND_WHITELIST: {[k: string]: string} = {\r\n\t'lock': '/lock',\r\n\t'weeklock': '/weeklock',\r\n\t'warn': '/warn',\r\n\t'forcerename': '/fr',\r\n\t'namelock': '/nl',\r\n\t'weeknamelock': '/wnl',\r\n};\r\n\r\nexport let migrated = global.Chat?.oldPlugins['abuse-monitor']?.migrated || false;\r\n\r\nexport const cache: {\r\n\t[roomid: string]: {\r\n\t\tusers: Record<string, number>,\r\n\t\t// can be a string and not string[] if it was added to the object before this patch was done.\r\n\t\t// todo: move this to just ID[]\r\n\t\tstaffNotified?: ID | ID[],\r\n\t\tclaimed?: ID,\r\n\t\trecommended?: Record<string, {type: string, reason: string}>,\r\n\t},\r\n} = (() => {\r\n\tconst plugin = global.Chat?.oldPlugins['abuse-monitor'];\r\n\tif (!plugin?.cache) return {};\r\n\tif (plugin.migrated) return plugin.cache;\r\n\tfor (const k in plugin.cache) {\r\n\t\tconst cur = plugin.cache[k];\r\n\t\tif (typeof cur.recommended?.type === 'string') { // would be object if it was the new entry\r\n\t\t\t// we cannot feasibly determine who it was (but it __is__ logged in <<abuselog>>, so staff can)\r\n\t\t\tdelete cur.recommended;\r\n\t\t}\r\n\t}\r\n\tmigrated = true;\r\n\treturn plugin.cache;\r\n})();\r\n\r\nexport const muted = Chat.oldPlugins['abuse-monitor']?.muted || new WeakMap<Room, WeakMap<User, number>>();\r\n\r\nconst defaults: FilterSettings = {\r\n\tthreshold: 4,\r\n\tthresholdIncrement: null,\r\n\tminScore: 0.65,\r\n\tspecials: {\r\n\t\tTHREAT: {0.96: 'MAXIMUM'},\r\n\t\tIDENTITY_ATTACK: {0.8: 2},\r\n\t\tSEVERE_TOXICITY: {0.8: 2},\r\n\t},\r\n\treplacements: {},\r\n\trecommendOnly: true,\r\n\tpunishments: [\r\n\t\t{certainty: 0.93, type: 'IDENTITY_ATTACK', punishment: 'WARN', count: 2},\r\n\t],\r\n};\r\n\r\nexport const settings: FilterSettings = (() => {\r\n\ttry {\r\n\t\t// accounting for data changes -\r\n\t\t// make sure we do have the default data in case it's not in the stored data\r\n\t\treturn {...defaults, ...JSON.parse(FS('config/chat-plugins/nf.json').readSync())};\r\n\t} catch (e: any) {\r\n\t\tif (e.code !== \"ENOENT\") throw e;\r\n\t\treturn defaults;\r\n\t}\r\n})();\r\n\r\nexport const reviews: Record<string, ReviewRequest[]> = (() => {\r\n\ttry {\r\n\t\treturn JSON.parse(FS(`config/chat-plugins/artemis-reviews.json`).readSync());\r\n\t} catch {\r\n\t\treturn {};\r\n\t}\r\n})();\r\n\r\n/**\r\n * Non-core settings - ones that shouldn't be included in /am backups/backup rollbacks/etc.\r\n * They should stay unless changed via specific command.\r\n */\r\nexport const metadata: MetaSettings = (() => {\r\n\ttry {\r\n\t\treturn JSON.parse(FS('config/chat-plugins/artemis-metadata.json').readSync());\r\n\t} catch {\r\n\t\treturn {};\r\n\t}\r\n})();\r\n\r\ninterface PunishmentSettings {\r\n\tcount?: number;\r\n\tcertainty?: number;\r\n\ttype?: string;\r\n\tpunishment: typeof PUNISHMENTS[number];\r\n\tmodlogCount?: number;\r\n\tmodlogActions?: string[];\r\n\t/** Other types of a given certainty needed beyond the primary */\r\n\tsecondaryTypes?: Record<string, number>;\r\n\t/** Requires another punishment given to activate. */\r\n\trequiresPunishment?: boolean;\r\n}\r\n\r\ninterface FilterSettings {\r\n\tdisabled?: boolean;\r\n\tthresholdIncrement: {turns: number, amount: number, minTurns?: number} | null;\r\n\tthreshold: number;\r\n\tminScore: number;\r\n\tspecials: {[k: string]: {[k: number]: number | \"MAXIMUM\"}};\r\n\t/** Replaces [key] with [value] before processing the string. */\r\n\treplacements: Record<string, string>;\r\n\tpunishments: PunishmentSettings[];\r\n\t/** Should it make recommendations, or punish? */\r\n\trecommendOnly?: boolean;\r\n}\r\n\r\ninterface MetaSettings {\r\n\t/** {[userid]: entries to ignore[] OR ignore entries after date [string]} */\r\n\tmodlogIgnores?: Record<string, string | number[]>;\r\n}\r\n\r\ninterface ReviewRequest {\r\n\tstaff: string;\r\n\troom: string;\r\n\tdetails: string;\r\n\ttime: number;\r\n\tresolved?: {by: string, time: number, details: string, result: number};\r\n}\r\n\r\n// stolen from chatlog. necessary here, but importing chatlog sucks.\r\nfunction nextMonth(month: string) {\r\n\tconst Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,cAAyB;AACzB,iBAAwB;AACxB,2BAAqB;AACrB,sBAAmB;AACnB,yBAAuD;AAGvD,MAAM,YAAY,CAAC,KAAK;AACxB,MAAM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AAC,MAAM,QAAQ,SAAS,MAAM,MAAM,GAAG;AAC1C,eAAO,QAAQ,OAAO,GAAG,CAAC;AAAA,MAC3B;AAAA,IACD;AAAA,EACD;AACA,SAAO,OAAO,QAAQ;AACvB;AAEO,MAAM,aAAa,IAAI,QAAQ,iBAAiB;AAEvD,eAAsB,WAAW,MAAY,MAAgB,SAAiB,UAAkC;AAC/G,QAAM,OAAO,iBAAM,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAK,CAAC,SAAS,CAAC,CAAC;AAClE,QAAM,cAA2C,CAAC;AAClD,QAAM,gBAAgB,MAAM,KAAK,MAAM,GAAG,cAAc,KAAK,EAAE;AAC/D,aAAW,cAAc,SAAS,aAAa;AAC9C,QAAI,eAAe,MAAM;AACxB,UAAI,YAAY,QAAQ,WAAW,UAAU,KAAK,YAAY,QAAQ,eAAe,IAAI;AAAG;AAAA,IAC7F;AACA,eAAW,QAAQ,MAAM;AACxB,YAAM,MAAM,SAAS,IAAI;AACzB,UAAI,WAAW,QAAQ,WAAW,SAAS;AAAM;AACjD,ULine truncated
"names": ["punishment"]
}
@@ -0,0 +1,176 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var announcements_exports = {};
__export(announcements_exports, {
Announcement: () => Announcement,
commands: () => commands
});
module.exports = __toCommonJS(announcements_exports);
class Announcement extends Rooms.MinorActivity {
constructor(room, options) {
super(room);
this.activityid = "announcement";
this.name = "Announcement";
this.activityNumber = options.activityNumber || room.nextGameNumber();
this.source = options.source;
this.setTimer(options);
}
generateAnnouncement() {
return `<div class="broadcast-blue"><p style="margin: 2px 0 5px 0"><strong style="font-size:11pt">${this.source}</strong></p></div>`;
}
displayTo(user, connection = null) {
const recipient = connection || user;
recipient.sendTo(this.room, `|uhtml|announcement${this.activityNumber}|${this.generateAnnouncement()}`);
}
display() {
const announcement = this.generateAnnouncement();
for (const id in this.room.users) {
const thisUser = this.room.users[id];
thisUser.sendTo(this.room, `|uhtml|announcement${this.activityNumber}|${announcement}`);
}
}
onConnect(user, connection = null) {
this.displayTo(user, connection);
}
destroy() {
this.room.send(`|uhtmlchange|announcement${this.activityNumber}|<div class="infobox">(${this.room.tr`The announcement has ended.`})</div>`);
this.room.setMinorActivity(null);
}
toJSON() {
return {
source: this.source,
activityNumber: this.activityNumber,
timeoutMins: this.timeoutMins,
timerEnd: this.timerEnd,
activityid: "announcement"
};
}
save() {
this.room.settings.minorActivity = this.toJSON();
this.room.saveSettings();
}
}
const commands = {
announcement: {
htmlcreate: "new",
create: "new",
new(target, room, user, connection, cmd, message) {
room = this.requireRoom();
if (!target)
return this.parse("/help announcement new");
target = target.trim();
if (room.battle)
return this.errorReply(this.tr`Battles do not support announcements.`);
const text = this.filter(target);
if (target !== text)
return this.errorReply(this.tr`You are not allowed to use filtered words in announcements.`);
const supportHTML = cmd === "htmlcreate";
this.checkCan("minigame", null, room);
if (supportHTML)
this.checkCan("declare", null, room);
this.checkChat();
if (room.minorActivity) {
return this.errorReply(this.tr`There is already a poll or announcement in progress in this room.`);
}
const source = supportHTML ? this.checkHTML(Chat.collapseLineBreaksHTML(target)) : Chat.formatText(target, true);
room.setMinorActivity(new Announcement(room, { source }));
this.roomlog(`${user.name} used ${message}`);
this.modlog("ANNOUNCEMENT");
return this.privateModAction(room.tr`An announcement was started by ${user.name}.`);
},
newhelp: [`/announcement create [announcement] - Creates an announcement. Requires: % @ # &`],
timer(target, room, user) {
room = this.requireRoom();
const announcement = this.requireMinorActivity(Announcement);
if (target) {
this.checkCan("minigame", null, room);
if (target === "clear") {
if (!announcement.endTimer())
return this.errorReply(this.tr`There is no timer to clear.`);
return this.add(this.tr`The announcement timer was turned off.`);
}
const timeoutMins = parseFloat(target);
if (isNaN(timeoutMins) || timeoutMins <= 0 || timeoutMins > 7 * 24 * 60) {
return this.errorReply(this.tr`Time should be a number of minutes less than one week.`);
}
announcement.setTimer({ timeoutMins });
room.add(`The announcement timer was turned on: the announcement will end in ${timeoutMins} minute${Chat.plural(timeoutMins)}.`);
this.modlog("ANNOUNCEMENT TIMER", null, `${timeoutMins} minutes`);
return this.privateModAction(`The announcement timer was set to ${timeoutMins} minute${Chat.plural(timeoutMins)} by ${user.name}.`);
} else {
if (!this.runBroadcast())
return;
if (announcement.timeout) {
return this.sendReply(`The announcement timer is on and will end in ${announcement.timeoutMins} minute${Chat.plural(announcement.timeoutMins)}.`);
} else {
return this.sendReply(this.tr`The announcement timer is off.`);
}
}
},
timerhelp: [
`/announcement timer [minutes] - Sets the announcement to automatically end after [minutes] minutes. Requires: % @ # &`,
`/announcement timer clear - Clears the announcement's timer. Requires: % @ # &`
],
close: "end",
stop: "end",
end(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
this.checkChat();
const announcement = this.requireMinorActivity(Announcement);
announcement.end(room);
this.modlog("ANNOUNCEMENT END");
this.privateModAction(room.tr`The announcement was ended by ${user.name}.`);
},
endhelp: [`/announcement end - Ends a announcement and displays the results. Requires: % @ # &`],
show: "",
display: "",
""(target, room, user, connection) {
room = this.requireRoom();
const announcement = this.requireMinorActivity(Announcement);
if (!this.runBroadcast())
return;
room.update();
if (this.broadcasting) {
announcement.display();
} else {
announcement.displayTo(user, connection);
}
},
displayhelp: [`/announcement display - Displays the announcement`]
},
announcementhelp: [
`/announcement allows rooms to run their own announcements. These announcements are limited to one announcement at a time per room.`,
`Accepts the following commands:`,
`/announcement create [announcement] - Creates a announcement. Requires: % @ # &`,
`/announcement htmlcreate [announcement] - Creates a announcement, with HTML allowed. Requires: # &`,
`/announcement timer [minutes] - Sets the announcement to automatically end after [minutes]. Requires: % @ # &`,
`/announcement display - Displays the announcement`,
`/announcement end - Ends a announcement. Requires: % @ # &`
]
};
process.nextTick(() => {
Chat.multiLinePattern.register("/announcement (new|create|htmlcreate) ");
});
for (const room of Rooms.rooms.values()) {
if (room.settings.minorActivity?.activityid === "announcement") {
room.setMinorActivity(new Announcement(room, room.settings.minorActivity), true);
}
}
//# sourceMappingURL=announcements.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/announcements.ts"],
"sourcesContent": ["/*\r\n * Announcements chat plugin\r\n * By Spandamn\r\n */\r\n\r\nexport interface AnnouncementOptions {\r\n\tactivityNumber?: number;\r\n\tsource: string;\r\n\ttimeoutMins?: number;\r\n\ttimerEnd?: number;\r\n}\r\n\r\nexport interface AnnouncementData extends AnnouncementOptions {\r\n\treadonly activityid: 'announcement';\r\n}\r\n\r\nexport class Announcement extends Rooms.MinorActivity {\r\n\treadonly activityid = 'announcement' as ID;\r\n\tname = 'Announcement';\r\n\tactivityNumber: number;\r\n\tsource: string;\r\n\tconstructor(room: Room, options: AnnouncementOptions) {\r\n\t\tsuper(room);\r\n\t\tthis.activityNumber = options.activityNumber || room.nextGameNumber();\r\n\t\tthis.source = options.source;\r\n\t\tthis.setTimer(options);\r\n\t}\r\n\r\n\tgenerateAnnouncement() {\r\n\t\treturn `<div class=\"broadcast-blue\"><p style=\"margin: 2px 0 5px 0\"><strong style=\"font-size:11pt\">${this.source}</strong></p></div>`;\r\n\t}\r\n\r\n\tdisplayTo(user: User, connection: Connection | null = null) {\r\n\t\tconst recipient = connection || user;\r\n\t\trecipient.sendTo(this.room, `|uhtml|announcement${this.activityNumber}|${this.generateAnnouncement()}`);\r\n\t}\r\n\r\n\tdisplay() {\r\n\t\tconst announcement = this.generateAnnouncement();\r\n\t\tfor (const id in this.room.users) {\r\n\t\t\tconst thisUser = this.room.users[id];\r\n\t\t\tthisUser.sendTo(this.room, `|uhtml|announcement${this.activityNumber}|${announcement}`);\r\n\t\t}\r\n\t}\r\n\r\n\tonConnect(user: User, connection: Connection | null = null) {\r\n\t\tthis.displayTo(user, connection);\r\n\t}\r\n\r\n\tdestroy() {\r\n\t\tthis.room.send(`|uhtmlchange|announcement${this.activityNumber}|<div class=\"infobox\">(${this.room.tr`The announcement has ended.`})</div>`);\r\n\t\tthis.room.setMinorActivity(null);\r\n\t}\r\n\r\n\ttoJSON(): AnnouncementData {\r\n\t\treturn {\r\n\t\t\tsource: this.source,\r\n\t\t\tactivityNumber: this.activityNumber,\r\n\t\t\ttimeoutMins: this.timeoutMins,\r\n\t\t\ttimerEnd: this.timerEnd,\r\n\t\t\tactivityid: 'announcement',\r\n\t\t};\r\n\t}\r\n\r\n\tsave() {\r\n\t\tthis.room.settings.minorActivity = this.toJSON();\r\n\t\tthis.room.saveSettings();\r\n\t}\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tannouncement: {\r\n\t\thtmlcreate: 'new',\r\n\t\tcreate: 'new',\r\n\t\tnew(target, room, user, connection, cmd, message) {\r\n\t\t\troom = this.requireRoom();\r\n\t\t\tif (!target) return this.parse('/help announcement new');\r\n\t\t\ttarget = target.trim();\r\n\t\t\tif (room.battle) return this.errorReply(this.tr`Battles do not support announcements.`);\r\n\r\n\t\t\tconst text = this.filter(target);\r\n\t\t\tif (target !== text) return this.errorReply(this.tr`You are not allowed to use filtered words in announcements.`);\r\n\r\n\t\t\tconst supportHTML = cmd === 'htmlcreate';\r\n\r\n\t\t\tthis.checkCan('minigame', null, room);\r\n\t\t\tif (supportHTML) this.checkCan('declare', null, room);\r\n\t\t\tthis.checkChat();\r\n\t\t\tif (room.minorActivity) {\r\n\t\t\t\treturn this.errorReply(this.tr`There is already a poll or announcement in progress in this room.`);\r\n\t\t\t}\r\n\r\n\t\t\tconst source = supportHTML ? this.checkHTML(Chat.collapseLineBreaksHTML(target)) : Chat.formatText(target, true);\r\n\r\n\t\t\troom.setMinorActivity(new Announcement(room, {source}));\r\n\r\n\t\t\tthis.roomlog(`${user.name} used ${message}`);\r\n\t\t\tthis.modlog('ANNOUNCEMENT');\r\n\t\t\treturn this.privateModAction(room.tr`An announcement was started by ${user.name}.`);\r\n\t\t},\r\n\t\tnewhelp: [`/announcement create [announcement] - Creates an announcement. Requires: % @ # &`],\r\n\r\n\t\ttimer(target, room, user) {\r\n\t\t\troom = this.requireRoom();\r\n\t\t\tconst announcement = this.requireMinorActivity(Announcement);\r\n\r\n\t\t\tif (target) {\r\n\t\t\t\tthis.checkCan('minigame', null, room);\r\n\t\t\t\tif (target === 'clear') {\r\n\t\t\t\t\tif (!announcement.endTimer()) return this.errorReply(this.tr`There is no timer to clear.`);\r\n\t\t\t\t\treturn this.add(this.tr`The announcement timer was turned off.`);\r\n\t\t\t\t}\r\n\t\t\t\tconst timeoutMins = parseFloat(target);\r\n\t\t\t\tif (isNaN(timeoutMins) || timeoutMins <= 0 || timeoutMins > 7 * 24 * 60) {\r\n\t\t\t\t\treturn this.errorReply(this.tr`Time should be a number of minutes less than one week.`);\r\n\t\t\t\t}\r\n\t\t\t\tannouncement.setTimer({timeoutMins});\r\n\t\t\t\troom.add(`The announcement timer was turned on: the announcement will end in ${timeoutMins} minute${Chat.plural(timeoutMins)}.`);\r\n\t\t\t\tthis.modlog('ANNOUNCEMENT TIMER', null, `${timeoutMins} minutes`);\r\n\t\t\t\treturn this.privateModAction(`The announcement timer was set to ${timeoutMins} minute${Chat.plural(timeoutMins)} by ${user.name}.`);\r\n\t\t\t} else {\r\n\t\t\t\tif (!this.runBroadcast()) return;\r\n\t\t\t\tif (announcement.timeout) {\r\n\t\t\t\t\treturn this.sendReply(`The announcement timer is on and will end in ${announcement.timeoutMins} minute${Chat.plural(announcemLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBO,M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,kBAAkB;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AACD;AAEA,QAAQ,SAAS,MAAM;AACtB,OAAK,iBAAiB,SAAS,wCAAwC;AACxE,CAAC;AAGD,WAAW,QAAQ,MAAM,MAAM,OAAO,GAAG;AACxC,MAAI,KAAK,SAAS,eAAe,eAAe,gBAAgB;AAC/D,SAAK,iBAAiB,IAAI,aAAa,MAAM,KAAK,SAAS,aAAa,GAAG,IAAI;AAAA,EAChF;AACD;",
"names": []
}
@@ -0,0 +1,491 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var battlesearch_exports = {};
__export(battlesearch_exports, {
PM: () => PM,
commands: () => commands,
pages: () => pages,
runBattleSearch: () => runBattleSearch
});
module.exports = __toCommonJS(battlesearch_exports);
var import_lib = require("../../lib");
var import_config_loader = require("../config-loader");
var path = __toESM(require("path"));
var child_process = __toESM(require("child_process"));
const BATTLESEARCH_PROCESS_TIMEOUT = 3 * 60 * 60 * 1e3;
const MAX_BATTLESEARCH_PROCESSES = 1;
async function runBattleSearch(userids, month, tierid, turnLimit) {
const useRipgrep = await (0, import_config_loader.checkRipgrepAvailability)();
const pathString = `logs/${month}/${tierid}/`;
const results = {};
let files = [];
try {
files = await (0, import_lib.FS)(pathString).readdir();
} catch (err) {
if (err.code === "ENOENT") {
return results;
}
throw err;
}
const [userid] = userids;
files = files.filter((item) => item.startsWith(month)).map((item) => `logs/${month}/${tierid}/${item}`);
if (useRipgrep) {
const regexString = userids.map((id) => `(?=.*?("p(1|2)":"${[...id].join("[^a-zA-Z0-9]*")}[^a-zA-Z0-9]*"))`).join("");
let output;
try {
output = await import_lib.ProcessManager.exec(["rg", "-i", regexString, "--no-line-number", "-P", "-tjson", ...files]);
} catch {
return results;
}
for (const line of output.stdout.split("\n").reverse()) {
const [file, raw] = import_lib.Utils.splitFirst(line, ":");
if (!raw || !line)
continue;
const data = JSON.parse(raw);
const day = file.split("/")[3];
if (!results[day]) {
results[day] = {
totalBattles: 0,
totalWins: {},
totalOutcomes: userids.length > 1 ? [] : null,
totalLosses: {},
totalTies: 0,
timesBattled: {}
};
}
const p1id = toID(data.p1);
const p2id = toID(data.p2);
if (userids.length > 1) {
if (userids.filter((item) => [p1id, p2id].includes(item)).length < userids.length)
continue;
} else {
if (!(p1id === userid || p2id === userid))
continue;
}
if (turnLimit && data.turns > turnLimit)
continue;
if (!results[day]) {
results[day] = {
totalBattles: 0,
totalWins: {},
totalOutcomes: userids.length > 1 ? [] : null,
totalLosses: {},
totalTies: 0,
timesBattled: {}
};
}
results[day].totalBattles++;
const winnerid = toID(data.winner);
const loser = winnerid === p1id ? p2id : p1id;
if (userids.includes(winnerid)) {
if (!results[day].totalWins[winnerid])
results[day].totalWins[winnerid] = 0;
results[day].totalWins[winnerid]++;
} else if (data.winner) {
if (!results[day].totalLosses[loser])
results[day].totalLosses[loser] = 0;
results[day].totalLosses[loser]++;
} else {
results[day].totalTies++;
}
for (const id of userids) {
if (!results[day].totalLosses[id])
results[day].totalLosses[id] = 0;
if (!results[day].totalWins[id])
results[day].totalWins[id] = 0;
}
const outcomes = results[day].totalOutcomes;
if (outcomes) {
outcomes.push({ won: winnerid, lost: loser, turns: data.turns });
}
const foe = userids.length > 1 ? null : userid === toID(data.p1) ? toID(data.p2) : toID(data.p1);
if (foe) {
if (!results[day].timesBattled[foe])
results[day].timesBattled[foe] = 0;
results[day].timesBattled[foe]++;
}
}
return results;
}
for (const file of files) {
const subFiles = (0, import_lib.FS)(`${file}`).readdirSync();
const day = file.split("/")[3];
for (const dayFile of subFiles) {
const json = (0, import_lib.FS)(`${file}/${dayFile}`).readIfExistsSync();
const data = JSON.parse(json);
const p1id = toID(data.p1);
const p2id = toID(data.p2);
if (userids.length > 1) {
if (userids.filter((item) => item === p1id || item === p2id).length < userids.length)
continue;
} else {
if (!(p1id === userid || p2id === userid))
continue;
}
if (turnLimit && data.turns > turnLimit)
continue;
if (!results[day]) {
results[day] = {
totalBattles: 0,
totalWins: {},
totalOutcomes: [],
totalLosses: {},
totalTies: 0,
timesBattled: {}
};
}
results[day].totalBattles++;
const winnerid = toID(data.winner);
const loser = winnerid === p1id ? p2id : p1id;
if (userids.includes(winnerid)) {
if (!results[day].totalWins[winnerid])
results[day].totalWins[winnerid] = 0;
results[day].totalWins[winnerid]++;
} else if (data.winner) {
if (!results[day].totalLosses[loser])
results[day].totalLosses[loser] = 0;
results[day].totalLosses[loser]++;
} else {
results[day].totalTies++;
}
for (const id of userids) {
if (!results[day].totalLosses[id])
results[day].totalLosses[id] = 0;
if (!results[day].totalWins[id])
results[day].totalWins[id] = 0;
}
const outcomes = results[day].totalOutcomes;
if (outcomes) {
outcomes.push({ won: winnerid, lost: loser, turns: data.turns });
}
const foe = userids.length > 1 ? null : userid === p1id ? p2id : p1id;
if (foe) {
if (!results[day].timesBattled[foe])
results[day].timesBattled[foe] = 0;
results[day].timesBattled[foe]++;
}
}
}
return results;
}
function buildResults(data, userids, month, tierid, turnLimit) {
let buf = `>view-battlesearch-${userids.join("-")}--${turnLimit}--${month}--${tierid}--confirm
|init|html
|title|[Battle Search][${userids.join("-")}][${tierid}][${month}]
`;
buf += `|pagehtml|<div class="pad ladder"><p>`;
buf += `${tierid} battles on ${month} where `;
buf += userids.length > 1 ? `the users ${userids.join(", ")} were players` : `the user ${userids[0]} was a player`;
buf += turnLimit ? ` and the battle lasted less than ${turnLimit} turn${Chat.plural(turnLimit)}` : "";
buf += `:</p><li style="display: inline; list-style: none"><a href="/view-battlesearch-${userids.join("-")}--${turnLimit}--${month}--${tierid}" target="replace">`;
buf += `<button class="button">Back</button></a></li><br />`;
if (userids.length > 1) {
const outcomes = [];
for (const day in data) {
const curOutcomes = data[day].totalOutcomes;
if (curOutcomes)
outcomes.push(...curOutcomes);
}
buf += `<table><tbody><tr><h3 style="margin: 5px auto">Full summary</h3></tr>`;
buf += `<tr><th>Won</th><th>Lost</th><th>Turns</th></tr>`;
for (const battle of outcomes) {
const { won, lost, turns } = battle;
buf += `<tr><td>${won}</td><td>${lost}</td><td>${turns}</td></tr>`;
}
}
buf += `</tbody></table><br />`;
for (const day in data) {
const dayStats = data[day];
buf += `<p style="text-align:left">`;
const { totalWins, totalLosses } = dayStats;
buf += `<table style=""><tbody><tr><th colspan="2"><h3 style="margin: 5px auto">${day}</h3>`;
buf += `</th></tr><tr><th>Category</th><th>Number</th></tr>`;
buf += `<tr><td>Total Battles</td><td>${dayStats.totalBattles}</td></tr>`;
for (const id in totalWins) {
buf += `<tr><td>Total Wins${userids.length > 1 ? ` (${id}) ` : ""}</td><td>${totalWins[id]}</td></tr>`;
}
for (const id in totalLosses) {
buf += `<tr><td>Total Losses${userids.length > 1 ? ` (${id}) ` : ""}</td><td>${totalLosses[id]}</td></tr>`;
}
if (userids.length < 2) {
buf += `<tr><th>Opponent</th><th>Times Battled</th></tr>`;
const [userid] = userids;
for (const foe in dayStats.timesBattled) {
buf += `<tr><td>`;
buf += `<a href="/view-battlesearch-${userid}-${foe}--${turnLimit}--${month}--${tierid}" target="replace">${foe}</a>`;
buf += `</td><td>${dayStats.timesBattled[foe]}</td></tr>`;
}
}
buf += `</p><br />`;
}
buf += `</tbody></table></div>`;
return buf;
}
async function rustBattleSearch(context, targetUser, daysString, format) {
const days = parseInt(daysString);
if (days < 1 || days > 15) {
throw new Chat.ErrorMessage(`Days must be between 1 and 15. To search longer ranges, use psbattletools manually on sim3.`);
}
if (!targetUser) {
throw new Chat.ErrorMessage(`No user specified.`);
}
const { connection, user } = context;
const currentDayOfMonth = new Date().getDate();
if (days < 1 || days > 15) {
return context.errorReply(`Days must be between 1 and 15. To search longer ranges, use psbattletools manually on sim3.`);
}
try {
await import_lib.ProcessManager.exec(`psbattletools --version`, {
env: { PATH: `${process.env.PATH}:${process.env.HOME}/.cargo/bin` }
});
} catch (e) {
return context.errorReply(
`You must install <a href="https://crates.io/crates/psbattletools">psbattletools</a> to use the alternate battlesearch.`
);
}
if (user.lastCommand !== "/battlesearch" && [30, 31, 1].includes(currentDayOfMonth)) {
const buf2 = [`Warning: Usage stats may be running currently.`];
buf2.push(`Battlesearch can interfere with usage stats processing due to high computational load.`);
buf2.push(`Please exercise caution.`);
buf2.push(`Type the command again to confirm.`);
user.lastCommand = "/battlesearch";
throw new Chat.ErrorMessage(buf2.join("<br />"));
}
user.lastCommand = "";
const directories = [];
for (let daysAgo = 0; daysAgo < days; daysAgo++) {
const date = new Date(Date.now() - 24 * 60 * 60 * 1e3 * daysAgo);
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
directories.push(
(0, import_lib.FS)(path.join("logs", `${year}-${month}`, format, `${year}-${month}-${day}`)).path
);
}
let buf = `>view-battlesearch-${toID(targetUser)}
|init|html
|title|[Battlesearch] ${targetUser} in ${format}
`;
buf += `|pagehtml|<div class="pad"><h2>Battlesearch for ${targetUser} in ${format} in the last ${days} days</h2>`;
buf += `<div style="white-space:pre-wrap;display:block;"></div>`;
buf += `<p>Searching...</p>`;
buf += `</div>`;
connection.send(buf);
const search = child_process.spawn(
"psbattletools",
["--threads", "3", "search", targetUser, ...directories],
{ env: { PATH: `${process.env.PATH}:${process.env.HOME}/.cargo/bin` } }
);
search.stdout.on("data", (data) => {
buf = buf.replace("</div>", `${Chat.formatText(data.toString()).replace(/\n/g, "<br />")}</div>`);
connection.send(buf);
});
search.on("close", () => {
buf = buf.replace("Searching...", "Done!");
connection.send(buf);
});
}
async function fsBattleSearch(connection, userids, month, tierid, turnLimit) {
userids = userids.map(toID);
const user = connection.user;
if (!user.can("forcewin"))
return connection.popup(`/battlesearch - Access Denied`);
const response = await PM.query({ userids, turnLimit, month, tierid });
connection.send(buildResults(response, userids, month, tierid, turnLimit));
}
const pages = {
async battlesearch(args, user, connection) {
if (!user.named)
return Rooms.RETRY_AFTER_LOGIN;
this.checkCan("forcewin");
if (import_config_loader.Config.nobattlesearch === true) {
return this.errorReply(`Battlesearch has been temporarily disabled due to load issues.`);
}
if (import_config_loader.Config.nobattlesearch === "psbattletools") {
return rustBattleSearch(this, args[0], args[1], toID(args[2]));
}
const [ids, rawLimit, month, formatid, confirmation] = import_lib.Utils.splitFirst(this.pageid.slice(18), "--", 5);
let turnLimit = parseInt(rawLimit);
if (isNaN(turnLimit))
turnLimit = void 0;
const userids = ids.split("-");
if (!ids || turnLimit && turnLimit < 1) {
return user.popup(`Some arguments are missing or invalid for battlesearch. Use /battlesearch to start over.`);
}
this.title = `[Battle Search][${userids.join(", ")}]`;
let buf = `<div class="pad ladder"><h2>Battle Search</h2><p>Userid${Chat.plural(userids)}: ${userids.join(", ")}</p><p>`;
if (turnLimit) {
buf += `Maximum Turns: ${turnLimit}`;
}
buf += `</p>`;
const months = import_lib.Utils.sortBy(
(await (0, import_lib.FS)("logs/").readdir()).filter((f) => f.length === 7 && f.includes("-")),
(name) => ({ reverse: name })
);
if (!month) {
buf += `<p>Please select a month:</p><ul style="list-style: none; display: block; padding: 0">`;
for (const i of months) {
buf += `<li style="display: inline; list-style: none"><a href="/view-battlesearch-${userids.join("-")}--${turnLimit}--${i}" target="replace"><button class="button">${i}</button></li>`;
}
return `${buf}</ul></div>`;
} else {
if (!months.includes(month)) {
return `${buf}Invalid month selected. <a href="/view-battlesearch-${userids.join("-")}--${turnLimit}" target="replace"><button class="button">Back to month selection</button></a></div>`;
}
buf += `<p><a href="/view-battlesearch-${userids.join("-")}--${turnLimit}" target="replace"><button class="button">Back</button></a> <button class="button disabled">${month}</button></p>`;
}
const tierid = toID(formatid);
const tiers = import_lib.Utils.sortBy(await (0, import_lib.FS)(`logs/${month}/`).readdir(), (tier) => [
// First sort by gen with the latest being first
tier.startsWith("gen") ? -parseInt(tier.charAt(3)) : -6,
// Then sort alphabetically
tier
]).map((tier) => {
const format = Dex.formats.get(tier);
if (format?.exists)
tier = format.name;
if (tier.startsWith("gen")) {
return `[Gen ${tier.substring(3, 4)}] ${tier.substring(4)}`;
}
return tier;
});
if (!tierid) {
buf += `<p>Please select the tier to search:</p><ul style="list-style: none; display: block; padding: 0">`;
for (const tier of tiers) {
buf += `<li style="display: inline; list-style: none">`;
buf += `<a href="/view-battlesearch-${userids.join("-")}--${turnLimit}--${month}--${toID(tier)}" target="replace">`;
buf += `<button class="button">${tier}</button></a></li><br />`;
}
return `${buf}</ul></div>`;
} else {
if (!tiers.map(toID).includes(tierid)) {
return `${buf}Invalid tier selected. <a href="/view-battlesearch-${userids.join("-")}--${turnLimit}--${month}" target="replace"><button class="button">Back to tier selection</button></a></div>`;
}
this.title += `[${tierid}]`;
buf += `<p><a href="/view-battlesearch-${userids.join("-")}--${turnLimit}--${month}" target="replace"><button class="button">Back</button></a> <button class="button disabled">${tierid}</button></p>`;
}
const [userid] = userids;
if (toID(confirmation) !== "confirm") {
buf += `<p>Are you sure you want to run a battle search for for ${tierid} battles on ${month} `;
buf += `where the ${userids.length > 1 ? `user(s) ${userids.join(", ")} were players` : `the user ${userid} was a player`}`;
if (turnLimit)
buf += ` and the battle lasted less than ${turnLimit} turn${Chat.plural(turnLimit)}`;
buf += `?</p><p><a href="/view-battlesearch-${userids.join("-")}--${turnLimit}--${month}--${tierid}--confirm" target="replace"><button class="button notifying">Yes, run the battle search</button></a> <a href="/view-battlesearch-${userids.join("-")}--${turnLimit}--${month}--${tierid}" target="replace"><button class="button">No, go back</button></a></p>`;
return `${buf}</div>`;
}
void fsBattleSearch(connection, userids, month, tierid, turnLimit);
return `<div class="pad ladder"><h2>Battle Search</h2><p>Searching for ${tierid} battles on ${month} where the ${userids.length > 1 ? `user(s) ${userids.join(", ")} were players` : `the user ${userid} was a player`} ` + (turnLimit ? `and the battle lasted less than ${turnLimit} turn${Chat.plural(turnLimit)}.` : "") + `</p><p>Loading... (this will take a while)</p></div>`;
}
};
const commands = {
battlesearch(target, room, user, connection) {
if (!target.trim())
return this.parse("/help battlesearch");
this.checkCan("forcewin");
const parts = target.split(",");
let turnLimit;
const ids = [];
for (const part of parts) {
if (part.startsWith("limit=")) {
const n = parseInt(part.slice("limit=".length).trim());
if (isNaN(n)) {
return this.errorReply(`Invalid limit: ${part.slice("limit=".length)}`);
}
turnLimit = n;
continue;
}
ids.push(part);
}
return this.parse(`/join view-battlesearch-${ids.map(toID).join("-")}--${turnLimit || ""}`);
},
battlesearchhelp() {
if (import_config_loader.Config.nobattlesearch === "psbattletools") {
return this.parse("/help rustbattlesearch");
}
this.runBroadcast();
return this.sendReply(
`/battlesearch [args] - Searches rated battle history for the provided [args] and returns information on battles between the userids given.
If a number is provided in the [args], it is assumed to be a turn limit, else they're assumed to be userids. Requires &`
);
},
rustbattlesearchhelp: [
`/battlesearch <user>, <format>, <days> - Searches for battles played by <user> in the past <days> days. Requires: &`
]
};
const PM = new import_lib.ProcessManager.QueryProcessManager(module, async (data) => {
const { userids, turnLimit, month, tierid } = data;
const start = Date.now();
try {
const result = await runBattleSearch(userids, month, tierid, turnLimit);
const elapsedTime = Date.now() - start;
if (elapsedTime > 10 * 60 * 1e3) {
Monitor.slow(`[Slow battlesearch query] ${elapsedTime}ms: ${JSON.stringify(data)}`);
}
return result;
} catch (err) {
Monitor.crashlog(err, "A battle search query", {
userids,
turnLimit,
month,
tierid
});
}
return null;
}, BATTLESEARCH_PROCESS_TIMEOUT, (message) => {
if (message.startsWith("SLOW\n")) {
Monitor.slow(message.slice(5));
}
});
if (!PM.isParentProcess) {
global.Config = require("../config-loader").Config;
global.Monitor = {
crashlog(error, source = "A battle search process", details = null) {
const repr = JSON.stringify([error.name, error.message, source, details]);
process.send(`THROW
@!!@${repr}
${error.stack}`);
},
slow(text) {
process.send(`CALLBACK
SLOW
${text}`);
}
};
process.on("uncaughtException", (err) => {
if (import_config_loader.Config.crashguard) {
Monitor.crashlog(err, "A battle search child process");
}
});
global.Dex = require("../../sim/dex").Dex;
global.toID = Dex.toID;
import_lib.Repl.start("battlesearch", (cmd) => eval(cmd));
} else {
PM.spawn(MAX_BATTLESEARCH_PROCESSES);
}
//# sourceMappingURL=battlesearch.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/battlesearch.ts"],
"sourcesContent": ["/**\r\n * Battle search - handles searching battle logs.\r\n */\r\nimport {FS, Utils, ProcessManager, Repl} from '../../lib';\r\n\r\nimport {checkRipgrepAvailability, Config} from '../config-loader';\r\n\r\nimport * as path from 'path';\r\nimport * as child_process from 'child_process';\r\n\r\nconst BATTLESEARCH_PROCESS_TIMEOUT = 3 * 60 * 60 * 1000; // 3 hours\r\n\r\ninterface BattleOutcome {\r\n\tlost: string;\r\n\twon: string;\r\n\tturns: string;\r\n}\r\n\r\ninterface BattleSearchResults {\r\n\ttotalBattles: number;\r\n\t/** Total battle outcomes. Null when only searching for one userid.*/\r\n\ttotalOutcomes: BattleOutcome[] | null;\r\n\ttotalWins: {[k: string]: number};\r\n\ttotalLosses: {[k: string]: number};\r\n\ttotalTies: number;\r\n\ttimesBattled: {[k: string]: number};\r\n}\r\n\r\nconst MAX_BATTLESEARCH_PROCESSES = 1;\r\nexport async function runBattleSearch(userids: ID[], month: string, tierid: ID, turnLimit?: number) {\r\n\tconst useRipgrep = await checkRipgrepAvailability();\r\n\tconst pathString = `logs/${month}/${tierid}/`;\r\n\tconst results: {[k: string]: BattleSearchResults} = {};\r\n\tlet files = [];\r\n\ttry {\r\n\t\tfiles = await FS(pathString).readdir();\r\n\t} catch (err: any) {\r\n\t\tif (err.code === 'ENOENT') {\r\n\t\t\treturn results;\r\n\t\t}\r\n\t\tthrow err;\r\n\t}\r\n\tconst [userid] = userids;\r\n\tfiles = files.filter(item => item.startsWith(month)).map(item => `logs/${month}/${tierid}/${item}`);\r\n\r\n\tif (useRipgrep) {\r\n\t\t// Matches non-word (including _ which counts as a word) characters between letters/numbers\r\n\t\t// in a user's name so the userid can case-insensitively be matched to the name.\r\n\t\tconst regexString = userids.map(id => `(?=.*?(\"p(1|2)\":\"${[...id].join('[^a-zA-Z0-9]*')}[^a-zA-Z0-9]*\"))`).join('');\r\n\t\tlet output;\r\n\t\ttry {\r\n\t\t\toutput = await ProcessManager.exec(['rg', '-i', regexString, '--no-line-number', '-P', '-tjson', ...files]);\r\n\t\t} catch {\r\n\t\t\treturn results;\r\n\t\t}\r\n\t\tfor (const line of output.stdout.split('\\n').reverse()) {\r\n\t\t\tconst [file, raw] = Utils.splitFirst(line, ':');\r\n\t\t\tif (!raw || !line) continue;\r\n\t\t\tconst data = JSON.parse(raw);\r\n\t\t\tconst day = file.split('/')[3];\r\n\t\t\tif (!results[day]) {\r\n\t\t\t\tresults[day] = {\r\n\t\t\t\t\ttotalBattles: 0,\r\n\t\t\t\t\ttotalWins: {},\r\n\t\t\t\t\ttotalOutcomes: userids.length > 1 ? [] : null,\r\n\t\t\t\t\ttotalLosses: {},\r\n\t\t\t\t\ttotalTies: 0,\r\n\t\t\t\t\ttimesBattled: {},\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t\tconst p1id = toID(data.p1);\r\n\t\t\tconst p2id = toID(data.p2);\r\n\r\n\t\t\tif (userids.length > 1) {\r\n\t\t\t\t// looking for specific userids, only register ones where those users are players\r\n\t\t\t\tif (userids.filter(item => [p1id, p2id].includes(item)).length < userids.length) continue;\r\n\t\t\t} else {\r\n\t\t\t\tif (!(p1id === userid || p2id === userid)) continue;\r\n\t\t\t}\r\n\r\n\t\t\tif (turnLimit && data.turns > turnLimit) continue;\r\n\t\t\tif (!results[day]) {\r\n\t\t\t\tresults[day] = {\r\n\t\t\t\t\ttotalBattles: 0,\r\n\t\t\t\t\ttotalWins: {},\r\n\t\t\t\t\ttotalOutcomes: userids.length > 1 ? [] : null,\r\n\t\t\t\t\ttotalLosses: {},\r\n\t\t\t\t\ttotalTies: 0,\r\n\t\t\t\t\ttimesBattled: {},\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t\tresults[day].totalBattles++;\r\n\t\t\tconst winnerid = toID(data.winner);\r\n\t\t\tconst loser = winnerid === p1id ? p2id : p1id;\r\n\t\t\tif (userids.includes(winnerid)) {\r\n\t\t\t\tif (!results[day].totalWins[winnerid]) results[day].totalWins[winnerid] = 0;\r\n\t\t\t\tresults[day].totalWins[winnerid]++;\r\n\t\t\t} else if (data.winner) {\r\n\t\t\t\tif (!results[day].totalLosses[loser]) results[day].totalLosses[loser] = 0;\r\n\t\t\t\tresults[day].totalLosses[loser]++;\r\n\t\t\t} else {\r\n\t\t\t\tresults[day].totalTies++;\r\n\t\t\t}\r\n\t\t\t// explicitly state 0 of stats if none\r\n\t\t\tfor (const id of userids) {\r\n\t\t\t\tif (!results[day].totalLosses[id]) results[day].totalLosses[id] = 0;\r\n\t\t\t\tif (!results[day].totalWins[id]) results[day].totalWins[id] = 0;\r\n\t\t\t}\r\n\r\n\t\t\tconst outcomes = results[day].totalOutcomes;\r\n\t\t\tif (outcomes) {\r\n\t\t\t\toutcomes.push({won: winnerid, lost: loser, turns: data.turns});\r\n\t\t\t}\r\n\t\t\t// we only want foe data for single-userid searches\r\n\t\t\tconst foe = userids.length > 1 ? null : userid === toID(data.p1) ? toID(data.p2) : toID(data.p1);\r\n\t\t\tif (foe) {\r\n\t\t\t\tif (!results[day].timesBattled[foe]) results[day].timesBattled[foe] = 0;\r\n\t\t\t\tresults[day].timesBattled[foe]++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn results;\r\n\t}\r\n\tfor (const file of files) {\r\n\t\tconst subFiles = FS(`${file}`).readdirSync();\r\n\t\tconst day = file.split('/')[3];\r\n\t\tfor (const dayFile of subFiles) {\r\n\t\t\tconst json = FS(`${file}/${dayFile}`).readIfExistsSync();\r\n\t\t\tconst data = JSON.parse(json);\r\n\t\t\tconst p1id = toID(data.p1);\r\n\t\t\tconst p2id = toID(data.p2);\r\n\t\t\tif Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAA8C;AAE9C,2BAA+C;AAE/C,WAAsB;AACtB,oBAA+B;AAE/B,MAAM,+BAA+B,IAAI,KAAK,KAAK;AAkBnD,MAAM,6BAA6B;AACnC,eAAsB,gBAAgB,SAAe,OAAe,QAAY,WAAoB;AACnG,QAAM,aAAa,UAAM,+CAAyB;AAClD,QAAM,aAAa,QAAQ,SAAS;AACpC,QAAM,UAA8C,CAAC;AACrD,MAAI,QAAQ,CAAC;AACb,MAAI;AACH,YAAQ,UAAM,eAAG,UAAU,EAAE,QAAQ;AAAA,EACtC,SAAS,KAAP;AACD,QAAI,IAAI,SAAS,UAAU;AAC1B,aAAO;AAAA,IACR;AACA,UAAM;AAAA,EACP;AACA,QAAM,CAAC,MAAM,IAAI;AACjB,UAAQ,MAAM,OAAO,UAAQ,KAAK,WAAW,KAAK,CAAC,EAAE,IAAI,UAAQ,QAAQ,SAAS,UAAU,MAAM;AAElG,MAAI,YAAY;AAGf,UAAM,cAAc,QAAQ,IAAI,QAAM,oBAAoB,CAAC,GAAG,EAAE,EAAE,KAAK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AAM,EAAC,KAAK,MAAM,MAAK,IAAI;AAC3B,aAAO,WAAW,eAAe,gBAAgB;AAAA,IAClD;AAAA,EACD;AACA,SAAO;AACP,aAAW,OAAO,MAAM;AACvB,UAAM,WAAW,KAAK,GAAG;AACzB,WAAO;AACP,UAAM,EAAC,WAAW,YAAW,IAAI;AACjC,WAAO,2EAA2E;AAClF,WAAO;AACP,WAAO,iCAAiC,SAAS;AACjD,eAAW,MAAM,WAAW;AAE3Line truncated
"names": ["buf"]
}
+755
View File
@@ -0,0 +1,755 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var blackjack_exports = {};
__export(blackjack_exports, {
Blackjack: () => Blackjack,
commands: () => commands,
roomSettings: () => roomSettings
});
module.exports = __toCommonJS(blackjack_exports);
var import_lib = require("../../lib");
/**
* Blackjack Game
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This allows users to play the classic blackjack card game.
* Credits: jd, panpawn
*
* @license MIT license
*/
class Blackjack extends Rooms.RoomGame {
constructor(room, user, autostartMinutes = 0) {
super(room);
this.gameNumber = room.nextGameNumber();
this.room = room;
this.turnTimeoutMinutes = 1;
this.timerTickSeconds = 5;
this.createdBy = user.name;
this.startedBy = "";
this.allowRenames = true;
this.playerCap = 16;
this.minimumPlayers = 2;
this.playerScrollWheel = 4;
this.cardWidth = 50;
this.cardHeight = 85;
this.spectators = /* @__PURE__ */ Object.create(null);
this.dealer = new BlackjackDealer();
this.symbols = {
"\u2665": "Hearts",
"\u2666": "Diamonds",
"\u2663": "Clubs",
"\u2660": "Spades"
};
this.deck = new BlackjackDeck().shuffle();
this.roomID = this.room.roomid;
this.title = `Blackjack (${room.title})`;
this.state = "signups";
this.lastMessage = "";
this.turnLog = "";
this.uhtmlChange = "";
this.curUsername = "";
this.endedBy = "";
this.infoboxLimited = "";
this.button = '<button class="button" name="send" value="/joingame" title="Join Blackjack">Join</button> | <button class="button" name="send" value="/leavegame" title="Leave Blackjack">Leave</button>';
this.spectateButton = '<button class="button" name="send" value="/blackjack spectate" title="Spectate Blackjack">Spectate</button>';
this.slideButton = '<button class="button" name="send" value="/blackjack slide" title="Slide the game log down in the chat">(<i class="fa fa-arrow-down" aria-hidden="true"></i> slide)</button>';
this.autostart = null;
this.dqTimer = null;
this.timerTick = null;
this.makeGame(autostartMinutes);
}
/**
* Game Setup
* makeGame - configures required settings for creating a game
* makePlayer - adds blackjack-specific properties to player object
* sendInvite - called when a game is created, or when a player joins/leaves
*/
makeGame(autostartMinutes = 0) {
if (autostartMinutes > 0) {
this.autostart = setTimeout(() => this.start(), autostartMinutes * 6e4);
}
this.sendInvite();
}
makePlayer(user) {
return new BlackjackPlayer(user, this);
}
sendInvite() {
const change = this.uhtmlChange;
const players = Object.keys(this.playerTable);
const playerList = [];
for (const player of players)
playerList.push(import_lib.Utils.escapeHTML(this.playerTable[player].name));
this.room.send(`|uhtml${change}|blackjack-${this.gameNumber}|<div class="infobox${this.infoboxLimited}">${this.createdBy} has created a game of Blackjack. ${this.button}<br /><strong>Players (${players.length}):</strong> ${!players.length ? "(None)" : playerList.join(", ")}</div>`);
this.uhtmlChange = "change";
}
/**
* Joining/Leaving/Viewing
* joinGame - joins the game
* leaveGame - leaves the game
* spectate - spectates the game
* unspectate - stops spectating the game
*/
joinGame(user) {
if (!user.named)
return this.errorMessage(user, `You must first choose a name to play Blackjack.`);
if (this.state === "started")
return this.errorMessage(user, `Blackjack has already started.`);
const joined = this.addPlayer(user);
if (!joined) {
this.errorMessage(user, `You are already in this game.`);
return false;
}
this.sendInvite();
if (Object.keys(this.playerTable).length === this.playerCap) {
this.start();
}
if (this.spectators[user.id])
delete this.spectators[user.id];
return true;
}
leaveGame(user) {
if (this.state === "started")
return this.errorMessage(user, `You cannot leave this game; it has already started.`);
if (!this.playerTable[user.id])
return this.errorMessage(user, "You are not in this game to leave.");
this.removePlayer(user);
this.sendInvite();
}
spectate(user) {
if (this.spectators[user.id])
return this.errorMessage(user, `You are already spectating this game.`);
if (this.playerTable[user.id]) {
return this.errorMessage(user, `You don't need to spectate the game; you're playing the game.`);
}
this.spectators[user.id] = user.id;
user.sendTo(this.roomid, `You are now spectating this game.`);
}
unspectate(user) {
if (!this.spectators[user.id])
return this.errorMessage(user, `You are already not spectating this game.`);
delete this.spectators[user.id];
user.sendTo(this.roomid, `You are no longer spectating this game.`);
}
/**
* Utility
* errorMessage - sends a user an error message
* add - adds/sends text to room
* display - displays gameplay to players and spectators
* clear - clears a user's gameplay screen
* clearAllTimers - clears all possible existing timers pertaining to blackjack
* slide - slides the game log down in the chat
* onConnect - handles replies to send when a user joins the room, if any
* onUpdateConnection - overrides default onUpdateConnection
* createTimer - creates a timer with a countdown for a player
* generateCard - generates the card for the UI
* getWinners - returns an array of the winners and their cards
*/
errorMessage(user, message) {
user.sendTo(this.room, import_lib.Utils.html`|html|<div class="message-error">${message}</div>`);
}
send(message, clean = false) {
const change = this.uhtmlChange;
this.room.send(`|uhtml${change}|blackjack-${this.gameNumber}|<div class="infobox${this.infoboxLimited}">${clean ? message : this.lastMessage + message}</div>`);
this.lastMessage += message;
this.uhtmlChange = "change";
}
display(text, clean = false, playerName, noChange = false, end = false) {
const force = end && this.endedBy;
let change = this.uhtmlChange;
if (noChange)
change = "";
if (clean)
this.lastMessage = "";
const message = `|uhtml${change}|blackjack-${this.gameNumber}|<div class="infobox${this.infoboxLimited}">`;
this.lastMessage += text;
if (end) {
text = `The game of blackjack has ${force ? `been forcibly ended by ${this.endedBy}` : "ended"}. <details><summary>View turn log</summary>${this.turnLog}</details>${text}`;
this.lastMessage = "";
}
for (const player of Object.keys(this.playerTable)) {
if (playerName && this.playerTable[player].name === playerName) {
this.playerTable[player].gameLog += `<span class="highlighted">${text}</span>`;
this.playerTable[player].sendRoom(`${message}${end ? text : this.playerTable[player].gameLog}</div>`);
} else {
this.playerTable[player].gameLog += text;
this.playerTable[player].sendRoom(`${message}${end ? text : this.playerTable[player].gameLog}</div>`);
}
}
for (const spectatorID of Object.keys(this.spectators)) {
const spectator = Users.get(this.spectators[spectatorID]);
if (spectator)
spectator.sendTo(this.roomid, `${message}${this.lastMessage + text}</div>`);
}
}
clear() {
const player = this.playerTable[this.curUsername];
if (!player)
throw new Error(`Player not in player table`);
player.sendRoom(`|uhtmlchange|user-blackjack-${this.gameNumber}|`);
}
clearAllTimers() {
if (this.dqTimer) {
clearTimeout(this.dqTimer);
this.dqTimer = null;
}
if (this.timerTick) {
clearInterval(this.timerTick);
this.timerTick = null;
}
if (this.autostart) {
clearTimeout(this.autostart);
this.autostart = null;
}
}
slide(user) {
user.sendTo(this.roomid, `|uhtml|blackjack-${this.gameNumber}|`);
this.display("", false, user.name);
}
onConnect(user) {
const message = `|uhtml|blackjack-${this.gameNumber}|<div class="infobox${this.infoboxLimited}">`;
if (this.state === "signups") {
this.sendInvite();
} else if (this.state === "started") {
const player = this.playerTable[user.id];
const spectator = this.spectators[user.id];
if (player && user.id === toID(this.curUsername)) {
player.sendRoom(`${message}${player.gameLog}`);
player.sendRoom(player.playScreen.replace("|uhtmlchange|", "|uhtml|"));
return;
} else if (player) {
player.sendRoom(`${message}${player.gameLog}`);
return;
} else if (spectator) {
user.sendTo(this.roomid, `${message}${this.lastMessage}`);
return;
}
}
}
onUpdateConnection() {
}
createTimer(user) {
const player = this.playerTable[user.id];
this.dqTimer = setTimeout(() => {
let cards = "";
for (const card of player.cards)
cards += `[${card}] `;
player.status = "stand";
this.display(
import_lib.Utils.html`<br /><strong>${player.name}</strong> stands with ${cards}` + ` (${player.points}) (Auto-stand: took too long to move)`,
false,
this.playerTable[this.curUsername].name
);
this.clear();
this.next();
}, this.turnTimeoutMinutes * 60 * 1e3);
this.timerTick = setInterval(() => {
const display = player.playScreen.replace("|uhtml|", "|uhtmlchange|");
if (display !== "") {
const timeLeft = player.timerTicksLeft - 5;
const buffer = String(timeLeft).length === 1 ? "0" : "";
const half = timeLeft <= this.turnTimeoutMinutes * 60 / 2;
player.sendRoom(`${display} | <span${half ? ` class="message-error"` : ``}>[<i class="fa fa-hourglass-${half ? 2 : 1}" aria-hidden="true"></i> 0:${buffer}${timeLeft}]</span>`);
player.timerTicksLeft -= this.timerTickSeconds;
}
}, this.timerTickSeconds * 1e3);
}
generateCard(card) {
const value = toID(card).toUpperCase();
const symbolName = this.symbols[card.substr(-1)];
const red = ["D", "H"].includes(symbolName.charAt(0));
let cardUI = value;
if (value === "K")
cardUI = "King";
if (value === "Q")
cardUI = "Queen";
if (value === "A")
cardUI = "Ace";
if (value === "J")
cardUI = "Joker";
return `<div title="${cardUI} of ${symbolName}" style="color: ${red ? "#992222" : "#000000"}; border-radius: 6px; background-color: #ffffff; position: relative; font-size: 14px; display: inline-block; width: ${this.cardWidth}px; height: ${this.cardHeight}px; border: 1px solid #000000; padding: 2px 4px;">${value}<br /> ${card.substr(-1)}<br /><span style="padding: 2px 4px; position: absolute; bottom: 0; right: 0; transform: rotate(-180deg);">${value}<br />${card.substr(-1)}</span></div> `;
}
getWinners(forceend = false) {
const winners = [];
if (forceend)
this.giveCard("dealer");
if (this.dealer.points > 21) {
for (const player of Object.keys(this.playerTable)) {
if (this.playerTable[player].status === "bust")
continue;
winners.push(
import_lib.Utils.html`<strong>${this.playerTable[player].name}</strong> ` + `[${this.playerTable[player].cards.join(", ")}]`
);
}
} else if (this.dealer.points !== 21) {
for (const player of Object.keys(this.playerTable)) {
if (this.playerTable[player].status === "bust" || this.playerTable[player].points <= this.dealer.points)
continue;
winners.push(
import_lib.Utils.html`<strong>${this.playerTable[player].name}</strong> ` + `[${this.playerTable[player].cards.join(", ")}]`
);
}
} else if (this.dealer.points === 21) {
winners.push(`<strong>${this.dealer.name}</strong> [${this.dealer.cards.join(", ")}]`);
}
return winners;
}
/**
* Game State Changes
* start - starts the game
* end - ends the game
* destroy - destroys the game
*/
start(user) {
const numberOfPlayers = Object.keys(this.playerTable).length;
if (numberOfPlayers < this.minimumPlayers) {
if (this.autostart) {
clearTimeout(this.autostart);
this.autostart = null;
}
this.send("<br />Not enough players to start; game canceled.");
this.destroy();
return;
}
if (user)
this.startedBy = import_lib.Utils.escapeHTML(user.name);
this.infoboxLimited = numberOfPlayers >= this.playerScrollWheel ? " infobox-limited" : "";
this.send(`[Blackjack has started. ${this.spectateButton}]`, true);
this.curUsername = Object.keys(this.playerTable)[0];
const header = `The game of blackjack has started${this.startedBy !== "" ? ` (started by ${this.startedBy})` : ``}. ${this.slideButton}<br />`;
this.state = "started";
this.giveCard("dealer");
this.giveCard("dealer");
this.turnLog += `<strong>${this.dealer.name}</strong>: [${this.dealer.cards[0]}]`;
for (const player of Object.keys(this.playerTable)) {
this.giveCard(this.playerTable[player].user.id);
this.giveCard(this.playerTable[player].user.id);
this.turnLog += import_lib.Utils.html`<br /><strong>${this.playerTable[player].name}</strong>: ` + `[${this.playerTable[player].cards[0]}] [${this.playerTable[player].cards[1]}] (${this.playerTable[player].points})`;
}
this.display(`${header}${this.turnLog}`, true, "");
this.next();
}
end(user, cmd) {
const force = cmd && toID(cmd) === "forceend";
if (user === true) {
this.state = "ended";
this.destroy();
return true;
}
if (this.state === "started" && cmd && !force) {
return this.errorMessage(
user,
`Because this game has started, you can only end this game by using /blackjack forceend.`
);
}
let winners = this.getWinners();
if (force) {
winners = this.getWinners(true);
this.endedBy = import_lib.Utils.escapeHTML(user.name);
if (this.curUsername) {
this.playerTable[this.curUsername].send(`|uhtmlchange|user-blackjack-${this.gameNumber}|`);
}
if (winners.length < 1) {
this.display(`There are no winners this time.`, false, void 0, false, true);
} else {
this.display(`<strong>Winner${Chat.plural(winners.length)}</strong>: ${winners.join(", ")}`, false, void 0, false, true);
}
}
if (!force && this.state !== "signups") {
if (winners.length < 1) {
this.display(`There are no winners this time.`, false, void 0, false, true);
} else {
this.display(`<strong>Winner${Chat.plural(winners.length)}</strong>: ${winners.join(", ")}`, false, void 0, false, true);
}
} else if (this.state === "signups") {
this.send(
import_lib.Utils.html`The game of blackjack has been ended by ${user.name}, ` + `and there are no winners because the game never started.`,
true
);
}
this.state = "ended";
this.destroy();
return true;
}
destroy() {
if (Object.keys(this.playerTable).length) {
for (const player of Object.keys(this.playerTable)) {
this.playerTable[player].destroy();
}
}
this.clearAllTimers();
this.room.game = null;
}
/**
* Gameplay
* hit - player decides to get a new card
* stand - player decides to keep current cards
* giveCard - gives a player a card from the deck
* getCardPoints - returns the point value of a user's cards
* next - game goes on to the next turn
*/
hit(user) {
if (this.state !== "started")
return this.errorMessage(user, `Blackjack hasn't started yet.`);
if (!this.playerTable[user.id])
return this.errorMessage(user, `You aren't a player in this game.`);
if (this.curUsername !== user.id)
return this.errorMessage(user, `It's not your turn.`);
this.playerTable[user.id].selfUhtml = "change";
this.playerTable[user.id].resetTimerTicks();
this.giveCard(user.id);
}
stand(user) {
const player = this.playerTable[user.id];
if (this.state !== "started")
return this.errorMessage(user, `Blackjack hasn't started yet.`);
if (!player)
return this.errorMessage(user, `You aren't a player in this game.`);
if (this.curUsername !== user.id)
return this.errorMessage(user, `It's not your turn.`);
player.status = "stand";
let cards = "";
for (const card of player.cards)
cards += `[${card}] `;
const turnLine = import_lib.Utils.html`<br /><strong>${player.name}</strong> stands with ${cards} ` + `(${player.points}${player.points === 21 ? " - blackjack!" : ""})`;
this.turnLog += turnLine;
this.display(turnLine, false, player.name);
this.clear();
this.next();
}
giveCard(userid) {
if (this.deck.length < 1)
this.deck = new BlackjackDeck().shuffle();
const player = userid === "dealer" ? this.dealer : this.playerTable[userid];
if (!player)
return;
player.cards.push(this.deck[0]);
this.deck.shift();
if (this.deck.length === 0) {
this.display(`<br />${this.dealer.name} has ran out of cards in the deck; shuffling a new deck...`);
this.deck = new BlackjackDeck().shuffle();
}
player.points = this.getCardPoints(userid);
if (player.cards.length < 3)
return;
let turnLine = import_lib.Utils.html`<br /><strong>${player.name}</strong> hit and received ` + `[${player.cards[player.cards.length - 1]}] (${player.points})`;
this.turnLog += turnLine;
if (player.cards.length > 2)
this.display(turnLine, false, player.name);
if (player instanceof BlackjackDealer) {
if (player.points > 21) {
let cards = "";
for (const card of player.cards) {
cards += `[${card}] `;
}
turnLine = import_lib.Utils.html`<br /><strong>${this.dealer.name}</strong> has busted with ${cards} (${player.points})`;
this.turnLog += turnLine;
this.display(turnLine);
this.end(true);
return;
} else if (player.points === 21) {
turnLine = import_lib.Utils.html`<br /><strong>${this.dealer.name}</strong> has blackjack!`;
this.turnLog += turnLine;
this.display(turnLine);
this.end(true);
return;
}
} else if (player.points > 21) {
player.status = "bust";
let cards = "";
for (const card of player.cards) {
cards += `[${card}] `;
}
turnLine = import_lib.Utils.html`<br /><strong>${player.name}</strong> has busted with ${cards} (${player.points})`;
this.turnLog += turnLine;
this.display(turnLine, false, player.name);
this.clear();
} else if (player.points === 21) {
player.status = "stand";
turnLine = import_lib.Utils.html`<br /><strong>${player.name}</strong> has blackjack!`;
this.turnLog += turnLine;
this.display(turnLine, false, player.name);
this.clear();
}
if (player !== this.dealer)
this.playerTable[userid].cards = player.cards;
this.next();
}
getCardPoints(playerid) {
const player = playerid === "dealer" ? this.dealer : this.playerTable[playerid];
let points = 0;
let aceCount = 0;
for (const card of player.cards.map((x) => toID(x).toUpperCase())) {
if (!isNaN(Number(card))) {
points += Number(card);
} else if (["K", "Q", "J"].includes(card)) {
points += 10;
} else if (card === "A") {
points += 11;
aceCount++;
}
}
while (points > 21 && aceCount > 0) {
points -= 10;
aceCount--;
}
return points;
}
next() {
this.clearAllTimers();
if (Object.keys(this.playerTable)[Object.keys(this.playerTable).length - 1] === this.curUsername && this.playerTable[this.curUsername].status !== "playing") {
if (this.dealer.points < 17) {
this.giveCard("dealer");
} else if (this.dealer.points >= 17) {
let cards = "";
for (const card of this.dealer.cards) {
cards += `[${card}] `;
}
const turnLine = `<br /><strong>${this.dealer.name}</strong> stands with ${cards} (${this.dealer.points})`;
this.turnLog += turnLine;
this.display(turnLine);
this.end(true);
}
return;
}
if (this.playerTable[this.curUsername].status !== "playing") {
let num = 0;
while (this.playerTable[Object.keys(this.playerTable)[num]].status !== "playing") {
num++;
}
this.curUsername = Object.keys(this.playerTable)[num];
}
let output = `|uhtml${this.playerTable[this.curUsername].selfUhtml}|user-blackjack-${this.gameNumber}|<div class="infobox" style="line-height: 20px;">`;
output += `It's your turn to move, ${this.playerTable[this.curUsername].name}<br />`;
for (const card of this.playerTable[this.curUsername].cards) {
output += this.generateCard(card);
}
output += `<br />Score: ${this.playerTable[this.curUsername].points}${this.playerTable[this.curUsername].points === 21 ? ` (you have blackjack!)` : ``}`;
output += `<br /><button class="button" name="send" value="/blackjack hit" title="Hit (get another card)">Hit</button> | <button class="button" name="send" value="/blackjack stand" title="Stand (just keep these cards)">Stand</button>`;
this.playerTable[this.curUsername].sendRoom(`|notify|Blackjack (${this.room.title})|It's your turn to play!`);
this.playerTable[this.curUsername].sendRoom(output);
this.playerTable[this.curUsername].playScreen = output;
this.createTimer(this.playerTable[this.curUsername].user);
}
}
class BlackjackPlayer extends Rooms.RoomGamePlayer {
constructor(user, game) {
super(user, game);
this.user = user;
this.cards = [];
this.points = 0;
this.slide = 0;
this.status = "playing";
this.selfUhtml = "";
this.gameLog = "";
this.playScreen = "";
this.timerTicksLeft = this.game.turnTimeoutMinutes * 60;
}
resetTimerTicks() {
this.timerTicksLeft = this.game.turnTimeoutMinutes * 60;
}
}
class BlackjackDealer {
constructor() {
this.cards = [];
this.points = 0;
this.name = "The Dealer";
}
}
class BlackjackDeck {
constructor() {
this.deck = [
"A\u2665",
"A\u2666",
"A\u2663",
"A\u2660",
"2\u2665",
"2\u2666",
"2\u2663",
"2\u2660",
"3\u2665",
"3\u2666",
"3\u2663",
"3\u2660",
"4\u2665",
"4\u2666",
"4\u2663",
"4\u2660",
"5\u2665",
"5\u2666",
"5\u2663",
"5\u2660",
"6\u2665",
"6\u2666",
"6\u2663",
"6\u2660",
"7\u2665",
"7\u2666",
"7\u2663",
"7\u2660",
"8\u2665",
"8\u2666",
"8\u2663",
"8\u2660",
"9\u2665",
"9\u2666",
"9\u2663",
"9\u2660",
"10\u2665",
"10\u2666",
"10\u2663",
"10\u2660",
"J\u2665",
"J\u2666",
"J\u2663",
"J\u2660",
"Q\u2665",
"Q\u2666",
"Q\u2663",
"Q\u2660",
"K\u2665",
"K\u2666",
"K\u2663",
"K\u2660"
];
}
shuffle() {
return import_lib.Utils.shuffle(this.deck);
}
}
const commands = {
blj: "blackjack",
blackjack: {
new: "create",
create(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
if (room.game)
return this.errorReply("There is already a game running in this room.");
if (room.settings.blackjackDisabled)
return this.errorReply("Blackjack is currently disabled in this room.");
const autostartMinutes = target ? parseFloat(target) : 0;
if (isNaN(autostartMinutes) || autostartMinutes <= 0 || autostartMinutes * 60 * 1e3 > Chat.MAX_TIMEOUT_DURATION) {
return this.errorReply("Usage: /blackjack create [autostart] - where autostart is an integer");
}
this.privateModAction(`A game of blackjack was created by ${user.name}.`);
this.modlog(`BLACKJACK CREATE`);
room.game = new Blackjack(room, user, autostartMinutes);
},
start(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
const game = this.requireGame(Blackjack);
if (game.state !== "signups")
return this.errorReply("This game of blackjack has already started.");
this.privateModAction(`The game of blackjack was started by ${user.name}.`);
this.modlog(`BLACKJACK START`);
game.start(user);
},
forceend: "end",
end(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
const game = this.requireGame(Blackjack);
const force = cmd === "forceend" ? "forcibly " : "";
const end = game.end(user, cmd);
if (end) {
this.privateModAction(`The game of blackjack was ${force}ended by ${user.name}.`);
this.modlog(`BLACKJACK END`);
}
},
hit(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Blackjack);
game.hit(user);
},
stand(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Blackjack);
game.stand(user);
},
slide(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Blackjack);
game.slide(user);
},
j: "join",
join(target, room, user) {
return this.parse("/joingame");
},
l: "leave",
leave(target, room, user) {
return this.parse("/leavegame");
},
unspectate: "spectate",
spectate(target, room, user, connection, cmd) {
room = this.requireRoom();
const game = this.requireGame(Blackjack);
if (cmd === "spectate") {
game.spectate(user);
} else if (cmd === "unspectate") {
game.unspectate(user);
}
},
disable(target, room, user) {
room = this.requireRoom();
this.checkCan("gamemanagement", null, room);
if (room.settings.blackjackDisabled) {
return this.errorReply("Blackjack is already disabled in this room.");
}
room.settings.blackjackDisabled = true;
room.saveSettings();
this.sendReply(`Blackjack has been disabled for this room.`);
},
enable(target, room, user) {
room = this.requireRoom();
this.checkCan("gamemanagement", null, room);
if (!room.settings.blackjackDisabled) {
return this.errorReply("Blackjack is already enabled in this room.");
}
delete room.settings.blackjackDisabled;
room.saveSettings();
this.sendReply(`Blackjack has been enabled for this room.`);
},
"": "help",
help(target, room, user) {
return this.parse("/help blackjack");
}
},
blackjackhelp: [
"/blackjack create - Creates a game of blackjack. Requires: % @ # &",
"/blackjack create [autostart] - Automatically creates a game of blackjack in [autostart] minutes. Requires: % @ # &",
"/blackjack start - Starts a game of blackjack. Requires: % @ # &",
"/blackjack end - Ends a game of blackjack. Requires: % @ # &",
"/blackjack join - Joins a game of blackjack.",
"/blackjack leave - Leaves a game of blackjack.",
"/blackjack spectate - Spectates a game of blackjack.",
"/blackjack unspectate - Stops spectating a game of blackjack.",
"/blackjack disable - Prevents games of blackjack from being made in the room. Requires: # &",
"/blackjack enable - Allows games of blackjack to be made in the room. Requires: # &"
]
};
const roomSettings = (room) => ({
label: "Blackjack",
permission: "editroom",
options: [
[`disabled`, room.settings.blackjackDisabled || "blackjack disable"],
[`enabled`, !room.settings.blackjackDisabled || "blackjack enable"]
]
});
//# sourceMappingURL=blackjack.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/blackjack.ts"],
"sourcesContent": ["/**\r\n * Blackjack Game\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * This allows users to play the classic blackjack card game.\r\n * Credits: jd, panpawn\r\n *\r\n * @license MIT license\r\n */\r\nimport {Utils} from '../../lib';\r\n\r\ntype Deck =\r\n\t'A\u2665' | 'A\u2666' | 'A\u2663' | 'A\u2660' | '2\u2665' | '2\u2666' | '2\u2663' | '2\u2660' | '3\u2665' | '3\u2666' | '3\u2663' | '3\u2660' | '4\u2665' | '4\u2666' | '4\u2663' |\r\n\t'4\u2660' | '5\u2665' | '5\u2666' | '5\u2663' | '5\u2660' | '6\u2665' | '6\u2666' | '6\u2663' | '6\u2660' | '7\u2665' | '7\u2666' | '7\u2663' | '7\u2660' | '8\u2665' | '8\u2666' |\r\n\t'8\u2663' | '8\u2660' | '9\u2665' | '9\u2666' | '9\u2663' | '9\u2660' | '10\u2665' | '10\u2666' | '10\u2663' | '10\u2660' | 'J\u2665' | 'J\u2666' | 'J\u2663' | 'J\u2660' |\r\n\t'Q\u2665' | 'Q\u2666' | 'Q\u2663' | 'Q\u2660' | 'K\u2665' | 'K\u2666' | 'K\u2663' | 'K\u2660';\r\ntype Symbols = '\u2665' | '\u2666' | '\u2663' | '\u2660';\r\ntype SymbolName = 'Hearts' | 'Diamonds' | 'Clubs' | 'Spades';\r\n\r\nexport class Blackjack extends Rooms.RoomGame<BlackjackPlayer> {\r\n\troom: Room;\r\n\r\n\troomID: RoomID;\r\n\r\n\tautostart: NodeJS.Timer | null;\r\n\tdqTimer: NodeJS.Timer | null;\r\n\ttimerTick: NodeJS.Timer | null;\r\n\r\n\tcardHeight: number;\r\n\tcardWidth: number;\r\n\tminimumPlayers: number;\r\n\tplayerScrollWheel: number;\r\n\tturnTimeoutMinutes: number;\r\n\ttimerTickSeconds: number;\r\n\r\n\tbutton: string;\r\n\tcreatedBy: string;\r\n\tcurUsername: string;\r\n\tendedBy: string;\r\n\tinfoboxLimited: string;\r\n\tlastMessage: string;\r\n\tslideButton: string;\r\n\tspectateButton: string;\r\n\tstartedBy: string;\r\n\tstate: string;\r\n\tturnLog: string;\r\n\tuhtmlChange: string;\r\n\r\n\tspectators: {[k: string]: ID};\r\n\tsymbols: {[k in Symbols]: SymbolName};\r\n\r\n\tdealer: BlackjackDealer;\r\n\tdeck: Deck[];\r\n\tgameNumber: number;\r\n\r\n\tconstructor(room: Room, user: User, autostartMinutes = 0) {\r\n\t\tsuper(room);\r\n\t\tthis.gameNumber = room.nextGameNumber();\r\n\t\tthis.room = room;\r\n\r\n\t\tthis.turnTimeoutMinutes = 1;\r\n\t\tthis.timerTickSeconds = 5;\r\n\r\n\t\tthis.createdBy = user.name;\r\n\t\tthis.startedBy = '';\r\n\t\tthis.allowRenames = true;\r\n\r\n\t\tthis.playerCap = 16;\r\n\t\tthis.minimumPlayers = 2;\r\n\t\tthis.playerScrollWheel = 4;\r\n\t\tthis.cardWidth = 50;\r\n\t\tthis.cardHeight = 85;\r\n\r\n\t\tthis.spectators = Object.create(null);\r\n\t\tthis.dealer = new BlackjackDealer();\r\n\r\n\t\tthis.symbols = {\r\n\t\t\t'\u2665': 'Hearts',\r\n\t\t\t'\u2666': 'Diamonds',\r\n\t\t\t'\u2663': 'Clubs',\r\n\t\t\t'\u2660': 'Spades',\r\n\t\t};\r\n\t\tthis.deck = new BlackjackDeck().shuffle();\r\n\r\n\t\tthis.roomID = this.room.roomid;\r\n\t\tthis.title = `Blackjack (${room.title})`;\r\n\t\tthis.state = 'signups';\r\n\r\n\t\tthis.lastMessage = '';\r\n\t\tthis.turnLog = '';\r\n\t\tthis.uhtmlChange = '';\r\n\t\tthis.curUsername = '';\r\n\t\tthis.endedBy = '';\r\n\t\tthis.infoboxLimited = '';\r\n\r\n\t\tthis.button = '<button class=\"button\" name=\"send\" value=\"/joingame\" title=\"Join Blackjack\">Join</button> | <button class=\"button\" name=\"send\" value=\"/leavegame\" title=\"Leave Blackjack\">Leave</button>';\r\n\t\tthis.spectateButton = '<button class=\"button\" name=\"send\" value=\"/blackjack spectate\" title=\"Spectate Blackjack\">Spectate</button>';\r\n\t\tthis.slideButton = '<button class=\"button\" name=\"send\" value=\"/blackjack slide\" title=\"Slide the game log down in the chat\">(<i class=\"fa fa-arrow-down\" aria-hidden=\"true\"></i> slide)</button>';\r\n\r\n\t\tthis.autostart = null;\r\n\t\tthis.dqTimer = null;\r\n\t\tthis.timerTick = null;\r\n\r\n\t\tthis.makeGame(autostartMinutes);\r\n\t}\r\n\r\n\t/**\r\n\t * Game Setup\r\n\t * makeGame - configures required settings for creating a game\r\n\t * makePlayer - adds blackjack-specific properties to player object\r\n\t * sendInvite - called when a game is created, or when a player joins/leaves\r\n\t */\r\n\tmakeGame(autostartMinutes = 0) {\r\n\t\tif (autostartMinutes > 0) {\r\n\t\t\tthis.autostart = setTimeout(() => this.start(), autostartMinutes * 60000);\r\n\t\t}\r\n\r\n\t\tthis.sendInvite();\r\n\t}\r\n\tmakePlayer(user: User) {\r\n\t\treturn new BlackjackPlayer(user, this);\r\n\t}\r\n\tsendInvite() {\r\n\t\tconst change = this.uhtmlChange;\r\n\t\tconst players = Object.keys(this.playerTable);\r\n\t\tconst playerList = [];\r\n\t\tfor (const player of players) playerList.push(Utils.escapeHTML(this.playerTable[player].name));\r\n\t\tthis.room.send(`|uhtml${change}|blackjack-${this.gameNumber}|<div class=\"infobox${this.infoboxLimited}\">${this.createdBy} has created a game of Blackjack. ${this.button}<br /><strong>Players (${players.length}):</strong> ${!players.length ? '(None)' : playerList.join(', ')}</div>`);\r\n\t\tthis.uhtmlChange = 'change';\r\n\t}\r\n\r\n\t/**\r\n\t * Joining/Leaving/Viewing\r\n\t * joinGame - joins the game\r\n\t * lea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KAAK,UAAU,WAAW;AAC7B,WAAK,WAAW;AAAA,IACjB,WAAW,KAAK,UAAU,WAAW;AACpC,YAAM,SAAS,KAAK,YAAY,KAAK,EAAE;AACvC,YAAM,YAAY,KAAK,WAAW,KAAK,EAAE;AACzC,UAAI,UAAU,KAAK,OAAO,KAAK,KAAK,WAAW,GAAG;AACjD,eAAO,SAAS,GAAG,UAAU,OAAO,SAAS;AAC7C,eAAO,SAAS,OAAO,WAAW,QAAQ,iBAAiB,SAAS,CAAC;AACrE;AAAA,MACD,WAAW,QAAQ;AAClB,eAAO,SAAS,GAAG,UAAU,OAAO,SAAS;AAC7C;AAAA,MACD,WAAW,WAAW;AACrB,aAAK,OAAO,KAAK,QAAQ,GAAG,UAAU,KAAK,aAAa;AACxD;AAAA,MACD;AAAA,IACD;AAAA,EACD;AAAA,EACA,qBAAqB;AAAA,EAIrB;AAAA,EACA,YAAY,MAAY;AACvB,UAAM,SAAS,KAAK,YAAY,KAAK,EAAE;AACvC,SAAK,UAAU,WAAW,MAAM;AAC/B,UAAI,QAAQ;AACZ,iBAAW,QAAQ,OAAO;AAAO,iBAAS,IAAI;AAC9C,aAAO,SAAS;AAChB,WAAK;AAAA,QACJ,iBAAM,qBAAqB,OAAO,6BAA6B,UAC/D,KAAK,OAAO;AAAA,QACZ;AAAA,QACA,KAAK,YAAY,KAAK,WAAW,EAAE;AAAA,MACpC;AACA,WAAK,MAAM;AACX,WAAK,KAAK;AAAA,IACX,GAAG,KAAK,qBAAqB,KAAK,GAAI;AACtC,SAAKLine truncated
"names": []
}
+239
View File
@@ -0,0 +1,239 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var calculator_exports = {};
__export(calculator_exports, {
commands: () => commands
});
module.exports = __toCommonJS(calculator_exports);
var import_lib = require("../../lib");
const OPERATORS = {
"^": {
precedence: 5,
associativity: "Right"
},
"negative": {
precedence: 4,
associativity: "Right"
},
"%": {
precedence: 3,
associativity: "Left"
},
"/": {
precedence: 3,
associativity: "Left"
},
"*": {
precedence: 3,
associativity: "Left"
},
"+": {
precedence: 2,
associativity: "Left"
},
"-": {
precedence: 2,
associativity: "Left"
},
"(": {
precedence: 1,
associativity: "Right"
}
};
const BASE_PREFIXES = {
2: "0b",
8: "0o",
10: "",
16: "0x"
};
function parseMathematicalExpression(infix) {
const outputQueue = [];
const operatorStack = [];
infix = infix.replace(/\s+/g, "");
const infixArray = infix.split(/([+\-*/%^()])/).filter((token) => token);
let isExprExpected = true;
for (const token of infixArray) {
if (isExprExpected && "+-".includes(token)) {
if (token === "-")
operatorStack.push("negative");
} else if ("^%*/+-".includes(token)) {
if (isExprExpected)
throw new SyntaxError(`Got "${token}" where an expression should be`);
const op = OPERATORS[token];
let prevToken = operatorStack[operatorStack.length - 1] || "(";
let prevOp = OPERATORS[prevToken];
while (op.associativity === "Left" ? op.precedence <= prevOp.precedence : op.precedence < prevOp.precedence) {
outputQueue.push(operatorStack.pop());
prevToken = operatorStack[operatorStack.length - 1] || "(";
prevOp = OPERATORS[prevToken];
}
operatorStack.push(token);
isExprExpected = true;
} else if (token === "(") {
if (!isExprExpected)
throw new SyntaxError(`Got "(" where an operator should be`);
operatorStack.push(token);
isExprExpected = true;
} else if (token === ")") {
if (isExprExpected)
throw new SyntaxError(`Got ")" where an expression should be`);
while (operatorStack.length && operatorStack[operatorStack.length - 1] !== "(") {
outputQueue.push(operatorStack.pop());
}
operatorStack.pop();
isExprExpected = false;
} else {
if (!isExprExpected)
throw new SyntaxError(`Got "${token}" where an operator should be`);
outputQueue.push(token);
isExprExpected = false;
}
}
if (isExprExpected)
throw new SyntaxError(`Input ended where an expression should be`);
while (operatorStack.length > 0) {
const token = operatorStack.pop();
if (token === "(")
continue;
outputQueue.push(token);
}
return outputQueue;
}
function solveRPN(rpn) {
let base = 10;
const resultStack = [];
for (let token of rpn) {
if (token === "negative") {
if (!resultStack.length)
throw new SyntaxError(`Unknown syntax error`);
resultStack.push(-resultStack.pop());
} else if (!"^%*/+-".includes(token)) {
if (token.endsWith("h")) {
token = `0x${token.slice(0, -1)}`;
} else if (token.endsWith("o")) {
token = `0o${token.slice(0, -1)}`;
} else if (token.endsWith("b")) {
token = `0b${token.slice(0, -1)}`;
}
if (token.startsWith("0x"))
base = 16;
if (token.startsWith("0b"))
base = 2;
if (token.startsWith("0o"))
base = 8;
let num = Number(token);
if (isNaN(num) && token.toUpperCase() in Math) {
num = Math[token.toUpperCase()];
}
if (isNaN(num) && token !== "NaN") {
throw new SyntaxError(`Unrecognized token ${token}`);
}
resultStack.push(num);
} else {
if (resultStack.length < 2)
throw new SyntaxError(`Unknown syntax error`);
const a = resultStack.pop();
const b = resultStack.pop();
switch (token) {
case "+":
resultStack.push(a + b);
break;
case "-":
resultStack.push(b - a);
break;
case "*":
resultStack.push(a * b);
break;
case "/":
resultStack.push(b / a);
break;
case "%":
resultStack.push(b % a);
break;
case "^":
resultStack.push(b ** a);
break;
}
}
}
if (resultStack.length !== 1)
throw new SyntaxError(`Unknown syntax error`);
return [resultStack.pop(), base];
}
const commands = {
math: "calculate",
calculate(target, room, user) {
if (!target)
return this.parse("/help calculate");
let base = 0;
const baseMatchResult = /\b(?:in|to)\s+([a-zA-Z]+)\b/.exec(target);
if (baseMatchResult) {
switch (toID(baseMatchResult[1])) {
case "decimal":
case "dec":
base = 10;
break;
case "hexadecimal":
case "hex":
base = 16;
break;
case "octal":
case "oct":
base = 8;
break;
case "binary":
case "bin":
base = 2;
break;
default:
return this.errorReply(`Unrecognized base "${baseMatchResult[1]}". Valid options are binary or bin, octal or oct, decimal or dec, and hexadecimal or hex.`);
}
}
const expression = target.replace(/\b(in|to)\s+([a-zA-Z]+)\b/g, "").trim();
if (!this.runBroadcast())
return;
try {
const [result, inferredBase] = solveRPN(parseMathematicalExpression(expression));
if (!base)
base = inferredBase;
let baseResult = "";
if (result && base !== 10) {
baseResult = `${BASE_PREFIXES[base]}${result.toString(base).toUpperCase()}`;
if (baseResult === expression)
baseResult = "";
}
let resultStr = "";
if (baseResult) {
resultStr = `<strong>${baseResult}</strong> = ${result}`;
} else {
resultStr = `<strong>${result}</strong>`;
}
this.sendReplyBox(`${expression}<br />= ${resultStr}`);
} catch (e) {
this.sendReplyBox(
import_lib.Utils.html`${expression}<br />= <span class="message-error"><strong>Invalid input:</strong> ${e.message}</span>`
);
}
},
calculatehelp: [
`/calculate [arithmetic question] - Calculates an arithmetical question. Supports PEMDAS (Parenthesis, Exponents, Multiplication, Division, Addition and Subtraction), pi and e.`,
`/calculate [arithmetic question] in [base] - Returns the result in a specific base. [base] can be bin, oct, dec or hex.`
]
};
//# sourceMappingURL=calculator.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/calculator.ts"],
"sourcesContent": ["import {Utils} from '../../lib';\r\n\r\ntype Operator = '^' | 'negative' | '%' | '/' | '*' | '+' | '-' | '(';\r\ninterface Operators {\r\n\tprecedence: number;\r\n\tassociativity: \"Left\" | \"Right\";\r\n}\r\n\r\nconst OPERATORS: {[k in Operator]: Operators} = {\r\n\t\"^\": {\r\n\t\tprecedence: 5,\r\n\t\tassociativity: \"Right\",\r\n\t},\r\n\t\"negative\": {\r\n\t\tprecedence: 4,\r\n\t\tassociativity: \"Right\",\r\n\t},\r\n\t\"%\": {\r\n\t\tprecedence: 3,\r\n\t\tassociativity: \"Left\",\r\n\t},\r\n\t\"/\": {\r\n\t\tprecedence: 3,\r\n\t\tassociativity: \"Left\",\r\n\t},\r\n\t\"*\": {\r\n\t\tprecedence: 3,\r\n\t\tassociativity: \"Left\",\r\n\t},\r\n\t\"+\": {\r\n\t\tprecedence: 2,\r\n\t\tassociativity: \"Left\",\r\n\t},\r\n\t\"-\": {\r\n\t\tprecedence: 2,\r\n\t\tassociativity: \"Left\",\r\n\t},\r\n\t\"(\": {\r\n\t\tprecedence: 1,\r\n\t\tassociativity: \"Right\",\r\n\t},\r\n};\r\n\r\nconst BASE_PREFIXES: {[base: number]: string} = {\r\n\t2: \"0b\",\r\n\t8: \"0o\",\r\n\t10: \"\",\r\n\t16: \"0x\",\r\n};\r\n\r\nfunction parseMathematicalExpression(infix: string) {\r\n\t// Shunting-yard Algorithm -- https://en.wikipedia.org/wiki/Shunting-yard_algorithm\r\n\tconst outputQueue: string[] = [];\r\n\tconst operatorStack: Operator[] = [];\r\n\tinfix = infix.replace(/\\s+/g, \"\");\r\n\tconst infixArray = infix.split(/([+\\-*/%^()])/).filter(token => token);\r\n\tlet isExprExpected = true;\r\n\tfor (const token of infixArray) {\r\n\t\tif (isExprExpected && \"+-\".includes(token)) {\r\n\t\t\tif (token === '-') operatorStack.push('negative');\r\n\t\t} else if (\"^%*/+-\".includes(token)) {\r\n\t\t\tif (isExprExpected) throw new SyntaxError(`Got \"${token}\" where an expression should be`);\r\n\t\t\tconst op = OPERATORS[token as Operator];\r\n\t\t\tlet prevToken = operatorStack[operatorStack.length - 1] || '(';\r\n\t\t\tlet prevOp = OPERATORS[prevToken];\r\n\t\t\twhile (op.associativity === \"Left\" ? op.precedence <= prevOp.precedence : op.precedence < prevOp.precedence) {\r\n\t\t\t\toutputQueue.push(operatorStack.pop()!);\r\n\t\t\t\tprevToken = operatorStack[operatorStack.length - 1] || '(';\r\n\t\t\t\tprevOp = OPERATORS[prevToken];\r\n\t\t\t}\r\n\t\t\toperatorStack.push(token as Operator);\r\n\t\t\tisExprExpected = true;\r\n\t\t} else if (token === \"(\") {\r\n\t\t\tif (!isExprExpected) throw new SyntaxError(`Got \"(\" where an operator should be`);\r\n\t\t\toperatorStack.push(token as Operator);\r\n\t\t\tisExprExpected = true;\r\n\t\t} else if (token === \")\") {\r\n\t\t\tif (isExprExpected) throw new SyntaxError(`Got \")\" where an expression should be`);\r\n\t\t\twhile (operatorStack.length && operatorStack[operatorStack.length - 1] !== \"(\") {\r\n\t\t\t\toutputQueue.push(operatorStack.pop()!);\r\n\t\t\t}\r\n\t\t\toperatorStack.pop();\r\n\t\t\tisExprExpected = false;\r\n\t\t} else {\r\n\t\t\tif (!isExprExpected) throw new SyntaxError(`Got \"${token}\" where an operator should be`);\r\n\t\t\toutputQueue.push(token);\r\n\t\t\tisExprExpected = false;\r\n\t\t}\r\n\t}\r\n\tif (isExprExpected) throw new SyntaxError(`Input ended where an expression should be`);\r\n\twhile (operatorStack.length > 0) {\r\n\t\tconst token = operatorStack.pop()!;\r\n\t\tif (token === '(') continue;\r\n\t\toutputQueue.push(token);\r\n\t}\r\n\treturn outputQueue;\r\n}\r\n\r\nfunction solveRPN(rpn: string[]): [number, number] {\r\n\tlet base = 10;\r\n\tconst resultStack: number[] = [];\r\n\tfor (let token of rpn) {\r\n\t\tif (token === 'negative') {\r\n\t\t\tif (!resultStack.length) throw new SyntaxError(`Unknown syntax error`);\r\n\t\t\tresultStack.push(-resultStack.pop()!);\r\n\t\t} else if (!\"^%*/+-\".includes(token)) {\r\n\t\t\tif (token.endsWith('h')) {\r\n\t\t\t\t// Convert h suffix for hexadecimal to 0x prefix\r\n\t\t\t\ttoken = `0x${token.slice(0, -1)}`;\r\n\t\t\t} else if (token.endsWith('o')) {\r\n\t\t\t\t// Convert o suffix for octal to 0o prefix\r\n\t\t\t\ttoken = `0o${token.slice(0, -1)}`;\r\n\t\t\t} else if (token.endsWith('b')) {\r\n\t\t\t\t// Convert b suffix for binary to 0b prefix\r\n\t\t\t\ttoken = `0b${token.slice(0, -1)}`;\r\n\t\t\t}\r\n\t\t\tif (token.startsWith('0x')) base = 16;\r\n\t\t\tif (token.startsWith('0b')) base = 2;\r\n\t\t\tif (token.startsWith('0o')) base = 8;\r\n\t\t\tlet num = Number(token);\r\n\t\t\tif (isNaN(num) && token.toUpperCase() in Math) {\r\n\t\t\t\t// @ts-ignore\r\n\t\t\t\tnum = Math[token.toUpperCase()];\r\n\t\t\t}\r\n\t\t\tif (isNaN(num) && token !== 'NaN') {\r\n\t\t\t\tthrow new SyntaxError(`Unrecognized token ${token}`);\r\n\t\t\t}\r\n\t\t\tresultStack.push(num);\r\n\t\t} else {\r\n\t\t\tif (resultStack.length < 2) throw new SyntaxError(`Unknown syntax error`);\r\n\t\t\tconst a = resultStack.pop()!;\r\n\t\t\tconst b = resultStack.pop()!;\r\n\t\t\tswitch (token) {\r\n\t\t\tcase \"+\":\r\n\t\t\t\tresultStack.push(a + b);\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"-\":\r\n\t\t\t\tresultStack.push(b - a);\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"*\":\r\n\t\t\t\tresultStack.push(a * b);\r\n\t\Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAoB;AAQpB,MAAM,YAA0C;AAAA,EAC/C,KAAK;AAAA,IACJ,YAAY;AAAA,IACZ,eAAe;AAAA,EAChB;AAAA,EACA,YAAY;AAAA,IACX,YAAY;AAAA,IACZ,eAAe;AAAA,EAChB;AAAA,EACA,KAAK;AAAA,IACJ,YAAY;AAAA,IACZ,eAAe;AAAA,EAChB;AAAA,EACA,KAAK;AAAA,IACJ,YAAY;AAAA,IACZ,eAAe;AAAA,EAChB;AAAA,EACA,KAAK;AAAA,IACJ,YAAY;AAAA,IACZ,eAAe;AAAA,EAChB;AAAA,EACA,KAAK;AAAA,IACJ,YAAY;AAAA,IACZ,eAAe;AAAA,EAChB;AAAA,EACA,KAAK;AAAA,IACJ,YAAY;AAAA,IACZ,eAAe;AAAA,EAChB;AAAA,EACA,KAA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QAAQ,8BAA8B,EAAE,EAAE,KAAK;AAEzE,QAAI,CAAC,KAAK,aAAa;AAAG;AAC1B,QAAI;AACH,YAAM,CAAC,QAAQ,YAAY,IAAI,SAAS,4BAA4B,UAAU,CAAC;AAC/E,UAAI,CAAC;AAAM,eAAO;AAClB,UAAI,aAAa;AACjB,UAAI,UAAU,SAAS,IAAI;AAC1B,qBAAa,GAAG,cAAc,IAAI,IAAI,OAAO,SAAS,IAAI,EAAE,YAAY;AACxE,YAAI,eAAe;AAAY,uBAAa;AAAA,MAC7C;AACA,UAAI,YAAY;AAChB,UAAI,YAAY;AACf,oBAAY,WAAW,yBAAyB;AAAA,MACjD,OAAO;AACN,oBAAY,WAAW;AAAA,MACxB;AACA,WAAK,aAAa,GAAG,qBAAqB,WAAW;AAAA,IACtD,SAAS,GAAP;AACD,WAAK;AAAA,QACJ,iBAAM,OAAO,iFAAiF,EAAE;AAAA,MACjG;AAAA,IACD;AAAA,EACD;AAAA,EACA,eAAe;AAAA,IACd;AAAA,IACA;AAAA,EACD;AACD;",
"names": []
}
@@ -0,0 +1,88 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var cg_teams_leveling_exports = {};
__export(cg_teams_leveling_exports, {
addPokemon: () => addPokemon,
dbSetupPromise: () => dbSetupPromise,
handlers: () => handlers,
incrementLosses: () => incrementLosses,
incrementWins: () => incrementWins
});
module.exports = __toCommonJS(cg_teams_leveling_exports);
var import_lib = require("../../lib");
let addPokemon = null;
let incrementWins = null;
let incrementLosses = null;
let dbSetupPromise = null;
async function setupDatabase(database) {
await database.runFile("./databases/schemas/battlestats.sql");
addPokemon = await database.prepare(
"INSERT OR IGNORE INTO gen9computergeneratedteams (species_id, wins, losses, level) VALUES (?, 0, 0, ?)"
);
incrementWins = await database.prepare(
"UPDATE gen9computergeneratedteams SET wins = wins + 1 WHERE species_id = ?"
);
incrementLosses = await database.prepare(
"UPDATE gen9computergeneratedteams SET losses = losses + 1 WHERE species_id = ?"
);
}
if (Config.usesqlite && Config.usesqliteleveling) {
const database = (0, import_lib.SQL)(module, {
file: "./databases/battlestats.db"
});
dbSetupPromise = setupDatabase(database);
}
async function updateStats(battle, winner) {
if (!incrementWins || !incrementLosses)
await dbSetupPromise;
if (battle.rated < 1e3 || toID(battle.format) !== "gen9computergeneratedteams")
return;
const p1 = Users.get(battle.p1.name);
const p2 = Users.get(battle.p2.name);
if (!p1 || !p2)
return;
const p1team = await battle.getTeam(p1);
const p2team = await battle.getTeam(p2);
if (!p1team || !p2team)
return;
let loserTeam, winnerTeam;
if (winner === p1.id) {
loserTeam = p2team;
winnerTeam = p1team;
} else {
loserTeam = p1team;
winnerTeam = p2team;
}
for (const species of winnerTeam) {
await addPokemon?.run([toID(species.species), species.level]);
await incrementWins?.run([toID(species.species)]);
}
for (const species of loserTeam) {
await addPokemon?.run([toID(species.species), species.level]);
await incrementLosses?.run([toID(species.species)]);
}
}
const handlers = {
onBattleEnd(battle, winner) {
if (!Config.usesqlite || !Config.usesqliteleveling)
return;
void updateStats(battle, winner);
}
};
//# sourceMappingURL=cg-teams-leveling.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/cg-teams-leveling.ts"],
"sourcesContent": ["/**\r\n * Not a chat plugin.\r\n *\r\n * Handles updating the level database for [Gen 9] Computer-Generated Teams.\r\n */\r\n\r\nimport {SQL} from \"../../lib\";\r\n\r\nexport let addPokemon: SQL.Statement | null = null;\r\nexport let incrementWins: SQL.Statement | null = null;\r\nexport let incrementLosses: SQL.Statement | null = null;\r\nexport let dbSetupPromise: Promise<void> | null = null;\r\n\r\nasync function setupDatabase(database: SQL.DatabaseManager) {\r\n\tawait database.runFile('./databases/schemas/battlestats.sql');\r\n\taddPokemon = await database.prepare(\r\n\t\t'INSERT OR IGNORE INTO gen9computergeneratedteams (species_id, wins, losses, level) VALUES (?, 0, 0, ?)'\r\n\t);\r\n\tincrementWins = await database.prepare(\r\n\t\t'UPDATE gen9computergeneratedteams SET wins = wins + 1 WHERE species_id = ?'\r\n\t);\r\n\tincrementLosses = await database.prepare(\r\n\t\t'UPDATE gen9computergeneratedteams SET losses = losses + 1 WHERE species_id = ?'\r\n\t);\r\n}\r\n\r\nif (Config.usesqlite && Config.usesqliteleveling) {\r\n\tconst database = SQL(module, {\r\n\t\tfile: './databases/battlestats.db',\r\n\t});\r\n\tdbSetupPromise = setupDatabase(database);\r\n}\r\n\r\nasync function updateStats(battle: RoomBattle, winner: ID) {\r\n\tif (!incrementWins || !incrementLosses) await dbSetupPromise;\r\n\tif (battle.rated < 1000 || toID(battle.format) !== 'gen9computergeneratedteams') return;\r\n\r\n\tconst p1 = Users.get(battle.p1.name);\r\n\tconst p2 = Users.get(battle.p2.name);\r\n\tif (!p1 || !p2) return;\r\n\r\n\tconst p1team = await battle.getTeam(p1);\r\n\tconst p2team = await battle.getTeam(p2);\r\n\tif (!p1team || !p2team) return;\r\n\r\n\tlet loserTeam, winnerTeam;\r\n\tif (winner === p1.id) {\r\n\t\tloserTeam = p2team;\r\n\t\twinnerTeam = p1team;\r\n\t} else {\r\n\t\tloserTeam = p1team;\r\n\t\twinnerTeam = p2team;\r\n\t}\r\n\r\n\tfor (const species of winnerTeam) {\r\n\t\tawait addPokemon?.run([toID(species.species), species.level]);\r\n\t\tawait incrementWins?.run([toID(species.species)]);\r\n\t}\r\n\tfor (const species of loserTeam) {\r\n\t\tawait addPokemon?.run([toID(species.species), species.level]);\r\n\t\tawait incrementLosses?.run([toID(species.species)]);\r\n\t}\r\n}\r\n\r\nexport const handlers: Chat.Handlers = {\r\n\tonBattleEnd(battle, winner) {\r\n\t\tif (!Config.usesqlite || !Config.usesqliteleveling) return;\r\n\t\tvoid updateStats(battle, winner);\r\n\t},\r\n};\r\n"],
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,iBAAkB;AAEX,IAAI,aAAmC;AACvC,IAAI,gBAAsC;AAC1C,IAAI,kBAAwC;AAC5C,IAAI,iBAAuC;AAElD,eAAe,cAAc,UAA+B;AAC3D,QAAM,SAAS,QAAQ,qCAAqC;AAC5D,eAAa,MAAM,SAAS;AAAA,IAC3B;AAAA,EACD;AACA,kBAAgB,MAAM,SAAS;AAAA,IAC9B;AAAA,EACD;AACA,oBAAkB,MAAM,SAAS;AAAA,IAChC;AAAA,EACD;AACD;AAEA,IAAI,OAAO,aAAa,OAAO,mBAAmB;AACjD,QAAM,eAAW,gBAAI,QAAQ;AAAA,IAC5B,MAAM;AAAA,EACP,CAAC;AACD,mBAAiB,cAAc,QAAQ;AACxC;AAEA,eAAe,YAAY,QAAoB,QAAY;AAC1D,MAAI,CAAC,iBAAiB,CAAC;AAAiB,UAAM;AAC9C,MAAI,OAAO,QAAQ,OAAQ,KAAK,OAAO,MAAM,MAAM;AAA8B;AAEjF,QAAM,KAAK,MAAM,IAAI,OAAO,GAAG,IAAI;AACnC,QAAM,KAAK,MAAM,IAAI,OAAO,GAAG,IAAI;AACnC,MAAI,CAAC,MAAM,CAAC;AAAI;AAEhB,QAAM,SAAS,MAAM,OAAO,QAAQ,EAAE;AACtC,QAAM,SAAS,MAAM,OAAO,QAAQ,EAAE;AACtC,MAAI,CAAC,UAAU,CAAC;AAAQ;AAExB,MAAI,WAAW;AACf,MAAI,WAAW,GAAG,IAAI;AACrB,gBAAY;AACZ,iBAAa;AAAA,EACd,OAAO;AACN,gBAAY;AACZ,iBAAa;AAAA,EACd;AAEA,aAAW,WAAW,YAAY;AACjC,UAAM,YAAY,IAAI,CAAC,KAAK,QAAQ,OAAO,GAAG,QAAQ,KAAK,CAAC;AAC5D,UAAM,eAAe,IAAI,CAAC,KAAK,QAAQ,OAAO,CAAC,CAAC;AAAA,EACjD;AACA,aAAW,WAAW,WAAW;AAChC,UAAM,YAAY,IAAI,CAAC,KAAK,QAAQ,OAAO,GAAG,QAAQ,KAAK,CAAC;AAC5D,UAAM,iBAAiB,IAAI,CAAC,KAAK,QAAQ,OAAO,CAAC,CAAC;AAAA,EACnD;AACD;AAEO,MAAM,WAA0B;AAAA,EACtC,YAAY,QAAQ,QAAQ;AAC3B,QAAI,CAAC,OAAO,aAAa,CAAC,OAAO;AAAmB;AACpD,SAAK,YAAY,QAAQ,MAAM;AAAA,EAChC;AACD;",
"names": []
}
@@ -0,0 +1,892 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var chat_monitor_exports = {};
__export(chat_monitor_exports, {
Filters: () => Filters,
chatfilter: () => chatfilter,
commands: () => commands,
loginfilter: () => loginfilter,
namefilter: () => namefilter,
nicknamefilter: () => nicknamefilter,
pages: () => pages,
statusfilter: () => statusfilter
});
module.exports = __toCommonJS(chat_monitor_exports);
var import_lib = require("../../lib");
const LEGACY_MONITOR_FILE = "config/chat-plugins/chat-monitor.tsv";
const MONITOR_FILE = "config/chat-plugins/chat-filter.json";
const WRITE_THROTTLE_TIME = 5 * 60 * 1e3;
const EVASION_DETECTION_SUBSTITUTIONS = {
a: ["a", "4", "@", "\xE1", "\xE2", "\xE3", "\xE0", "\u15E9", "A", "\u24D0", "\u24B6", "\u03B1", "\u034F", "\u20B3", "\xE4", "\xC4", "\u13D7", "\u03BB", "\u0394", "\u1E00", "\u13AA", "\u01DF", "\u033E", "\uFF41", "\uFF21", "\u1D00", "\u0250", "\u{1F150}", "\u{1D41A}", "\u{1D400}", "\u{1D622}", "\u{1D608}", "\u{1D656}", "\u{1D63C}", "\u{1D4B6}", "\u{1D4EA}", "\u{1D4D0}", "\u{1D552}", "\u{1D538}", "\u{1D51E}", "\u{1D504}", "\u{1D586}", "\u{1D56C}", "\u{1F130}", "\u{1F170}", "\u{1D49C}", "\u{1D68A}", "\u{1D670}", "\uA34F", "\u0430", "\u{1D4EA}"],
b: ["b", "8", "\u15F7", "B", "\u24D1", "\u24B7", "\u0432", "\u0E3F", "\u1E05", "\u1E04", "\u13F0", "\u03D0", "\u0181", "\u1E03", "\u1E02", "\u026E", "\uFF42", "\uFF22", "\u0299", "\u{1F151}", "\u{1D41B}", "\u{1D401}", "\u{1D623}", "\u{1D609}", "\u{1D657}", "\u{1D63D}", "\u{1D4B7}", "\u{1D4EB}", "\u{1D4D1}", "\u{1D553}", "\u{1D539}", "\u{1D51F}", "\u{1D505}", "\u{1D587}", "\u{1D56D}", "\u{1F131}", "\u{1F171}", "\u{1D435}", "\u10A6", "\u{1D68B}", "\u{1D671}", "\u266D", "b"],
c: ["c", "\xE7", "\u1455", "C", "\u24D2", "\u24B8", "\xA2", "\u034F", "\u20B5", "\u010B", "\u010A", "\u1348", "\u03C2", "\u1E09", "\u1E08", "\u13DF", "\u0188", "\u033E", "\uFF43", "\uFF23", "\u1D04", "\u0254", "\u{1F152}", "\u{1D41C}", "\u{1D402}", "\u{1D624}", "\u{1D60A}", "\u{1D658}", "\u{1D63E}", "\u{1D4B8}", "\u{1D4EC}", "\u{1D4D2}", "\u{1D554}", "\u2102", "\u{1D520}", "\u212D", "\u{1D588}", "\u{1D56E}", "\u{1F132}", "\u{1F172}", "\u{1D49E}", "\u{1D68C}", "\u{1D672}", "\u263E", "\u0441"],
d: ["d", "\u15EA", "D", "\u24D3", "\u24B9", "\u2202", "\u0110", "\u010F", "\u010E", "\u13B4", "\u1E0A", "\u13A0", "\u0256", "\uFF44", "\uFF24", "\u1D05", "\u{1F153}", "\u{1D41D}", "\u{1D403}", "\u{1D625}", "\u{1D60B}", "\u{1D659}", "\u{1D63F}", "\u{1D4B9}", "\u{1D4ED}", "\u{1D4D3}", "\u{1D555}", "\u200B", "\u{1D521}", "\u{1D589}", "\u{1D56F}", "\u{1F133}", "\u{1F173}", "\u{1D49F}", "\u0503", "\u{1D68D}", "\u{1D673}", "\u25D7", "\u217E"],
e: ["e", "3", "\xE9", "\xEA", "E", "\u24D4", "\u24BA", "\u0454", "\u034F", "\u0246", "\u1EC7", "\u1EC6", "\u13CB", "\u03B5", "\u03A3", "\u1E15", "\u1E14", "\u13AC", "\u025B", "\u033E", "\uFF45", "\uFF25", "\u1D07", "\u01DD", "\u{1F154}", "\u{1D41E}", "\u{1D404}", "\u{1D626}", "\u{1D60C}", "\u{1D65A}", "\u{1D640}", "\u212F", "\u{1D4EE}", "\u{1D4D4}", "\u{1D556}", "\u{1D53B}", "\u{1D522}", "\u{1D507}", "\u{1D58A}", "\u{1D570}", "\u{1F134}", "\u{1F174}", "\u{1D452}", "\u{1D438}", "\u04BD", "\u{1D68E}", "\u{1D674}", "\u20AC", "\u0435", "\u0451", "\u{1D4EE}"],
f: ["f", "\u15B4", "F", "\u24D5", "\u24BB", "\u20A3", "\u1E1F", "\u1E1E", "\u13A6", "\u0493", "\u0284", "\uFF46", "\uFF26", "\u025F", "\u{1F155}", "\u{1D41F}", "\u{1D405}", "\u{1D627}", "\u{1D60D}", "\u{1D65B}", "\u{1D641}", "\u{1D4BB}", "\u{1D4EF}", "\u{1D4D5}", "\u{1D557}", "\u{1D53C}", "\u{1D523}", "\u{1D508}", "\u{1D58B}", "\u{1D571}", "\u{1F135}", "\u{1F175}", "\u{1D439}", "\u03DD", "\u{1D68F}", "\u{1D675}", "\u03DC", "f"],
g: ["g", "q", "6", "9", "G", "\u24D6", "\u24BC", "\u034F", "\u20B2", "\u0121", "\u0120", "\u13B6", "\u03D1", "\u1E20", "\u0262", "\u033E", "\uFF47", "\uFF27", "\u0183", "\u{1F156}", "\u{1D420}", "\u{1D406}", "\u{1D628}", "\u{1D60E}", "\u{1D65C}", "\u{1D642}", "\u210A", "\u{1D4F0}", "\u{1D4D6}", "\u{1D558}", "\u{1D53D}", "\u{1D524}", "\u{1D509}", "\u{1D58C}", "\u{1D572}", "\u{1F136}", "\u{1F176}", "\u{1D454}", "\u{1D4A2}", "\u0260", "\u{1D690}", "\u{1D676}", "\u2761", "\u0581", "\u{1D676}", "\u{1D4F0}"],
h: [
"h",
"\u157C",
"H",
"\u24D7",
"\u24BD",
"\u043D",
"\u2C67",
"\u1E27",
"\u1E26",
"\u13C2",
"\u0266",
"\uFF48",
"\uFF28",
"\u029C",
"\u0265",
"\u{1F157}",
"\u{1D421}",
"\u{1D407}",
"\u{1D629}",
"\u{1D60F}",
"\u{1D65D}",
"\u{1D643}",
"\u{1D4BD}",
"\u{1D4F1}",
"\u{1D4D7}",
"\u{1D559}",
"\u{1D53E}",
"\u{1D525}",
"\u{1D50A}",
"\u{1D58D}",
"\u{1D573}",
"\u{1F137}",
"\u{1F177}",
"\u{1D43B}",
"\u050B",
"\u{1D691}",
"\u{1D677}",
"\u2644",
"h"
],
i: ["i", "!", "l", "1", "\xED", "I", "\u24D8", "\u24BE", "\u03B9", "\u034F", "\u0142", "\xEF", "\xCF", "\u13A5", "\u1E2D", "\u1E2C", "\u0268", "\u033E", "\uFF49", "\uFF29", "\u026A", "\u0131", "\u{1F158}", "\u{1D422}", "\u{1D408}", "\u{1D62A}", "\u{1D610}", "\u{1D65E}", "\u{1D644}", "\u{1D4BE}", "\u{1D4F2}", "\u{1D4D8}", "\u{1D55A}", "\u210D", "\u{1D526}", "\u210C", "\u{1D58E}", "\u{1D574}", "\u{1F138}", "\u{1F178}", "\u{1D43C}", "\u{1D692}", "\u{1D678}", "\u2657", "\u0456", "\xA1", "|", "\u{1D4F2}"],
j: ["j", "\u148D", "J", "\u24D9", "\u24BF", "\u05E0", "\u13E0", "\u03F3", "\u029D", "\uFF4A", "\uFF2A", "\u1D0A", "\u027E", "\u{1F159}", "\u{1D423}", "\u{1D409}", "\u{1D62B}", "\u{1D611}", "\u{1D65F}", "\u{1D645}", "\u{1D4BF}", "\u{1D4F3}", "\u{1D4D9}", "\u{1D55B}", "\u200B", "\u{1D527}", "\u{1D58F}", "\u{1D575}", "\u{1F139}", "\u{1F179}", "\u{1D4A5}", "\u{1D693}", "\u{1D679}", "\u266A", "\u0458"],
k: ["k", "K", "\u24DA", "\u24C0", "\u043A", "\u034F", "\u20AD", "\u1E33", "\u1E32", "\u13E6", "\u03BA", "\u0198", "\u04C4", "\u033E", "\uFF4B", "\uFF2B", "\u1D0B", "\u029E", "\u{1F15A}", "\u{1D424}", "\u{1D40A}", "\u{1D62C}", "\u{1D612}", "\u{1D660}", "\u{1D646}", "\u{1D4C0}", "\u{1D4F4}", "\u{1D4DA}", "\u{1D55C}", "\u{1D540}", "\u{1D528}", "\u2111", "\u{1D590}", "\u{1D576}", "\u{1F13A}", "\u{1F17A}", "\u{1D4A6}", "\u0199", "\u{1D694}", "\u{1D67A}", "\u03F0", "k", "\u{1D4F4}"],
l: ["l", "i", "1", "/", "|", "\u14AA", "L", "\u24DB", "\u24C1", "\u2113", "\u2C60", "\u0140", "\u013F", "\u13DD", "\u1E36", "\u13DE", "\u029F", "\uFF4C", "\uFF2C", "\u{1F15B}", "\u{1D425}", "\u{1D40B}", "\u{1D62D}", "\u{1D613}", "\u{1D661}", "\u{1D647}", "\u{1D4C1}", "\u{1D4F5}", "\u{1D4DB}", "\u{1D55D}", "\u{1D541}", "\u{1D529}", "\u200B", "\u{1D591}", "\u{1D577}", "\u{1F13B}", "\u{1F17B}", "\u{1D43F}", "\u0285", "\u{1D695}", "\u{1D67B}", "\u21B3", "\u217C"],
m: [
"m",
"\u15F0",
"M",
"\u24DC",
"\u24C2",
"\u043C",
"\u034F",
"\u20A5",
"\u1E43",
"\u1E42",
"\u13B7",
"\u03FB",
"\u039C",
"\u1E41",
"\u1E40",
"\u028D",
"\u033E",
"\uFF4D",
"\uFF2D",
"\u1D0D",
"\u026F",
"\u{1F15C}",
"\u{1D426}",
"\u{1D40C}",
"\u{1D62E}",
"\u{1D614}",
"\u{1D662}",
"\u{1D648}",
"\u{1D4C2}",
"\u{1D4F6}",
"\u{1D4DC}",
"\u{1D55E}",
"\u{1D542}",
"\u{1D52A}",
"\u{1D50D}",
"\u{1D592}",
"\u{1D578}",
"\u{1F13C}",
"\u{1F17C}",
"\u{1D440}",
"\u0271",
"\u{1D696}",
"\u{1D67C}",
"\u2654",
"\u217F"
],
n: ["n", "\xF1", "\u144E", "N", "\u24DD", "\u24C3", "\u0438", "\u20A6", "\u0144", "\u0143", "\u13C1", "\u03C0", "\u220F", "\u1E46", "\u057C", "\uFF4E", "\uFF2E", "\u0274", "\u{1F15D}", "\u{1D427}", "\u{1D40D}", "\u{1D62F}", "\u{1D615}", "\u{1D663}", "\u{1D649}", "\u{1D4C3}", "\u{1D4F7}", "\u{1D4DD}", "\u{1D55F}", "\u{1D543}", "\u{1D52B}", "\u{1D50E}", "\u{1D593}", "\u{1D579}", "\u{1F13D}", "\u{1F17D}", "\u{1D4A9}", "\u0273", "\u{1D697}", "\u{1D67D}", "\u266B", "\u0578", "\u03B7", "\u{1D67D}", "\u019E", "\u{1D4F7}"],
o: ["o", "0", "\xF3", "\xF4", "\xF5", "\xFA", "O", "\u24DE", "\u24C4", "\u03C3", "\u034F", "\xD8", "\xF6", "\xD6", "\u13A7", "\u0398", "\u1E4F", "\u1E4E", "\u13BE", "\u0585", "\u033E", "\uFF4F", "\uFF2F", "\u1D0F", "\u{1F15E}", "\u{1D428}", "\u{1D40E}", "\u{1D630}", "\u{1D616}", "\u{1D664}", "\u{1D64A}", "\u2134", "\u{1D4F8}", "\u{1D4DE}", "\u{1D560}", "\u{1D544}", "\u{1D52C}", "\u{1D50F}", "\u{1D594}", "\u{1D57A}", "\u{1F13E}", "\u{1F17E}", "\u{1D45C}", "\u{1D4AA}", "\u{1D698}", "\u{1D67E}", "\u2299", "\u03BF"],
p: ["p", "\u146D", "P", "\u24DF", "\u24C5", "\u03C1", "\u20B1", "\u1E57", "\u1E56", "\u13AE", "\u01A4", "\u13E2", "\u0584", "\uFF50", "\uFF30", "\u1D18", "\u{1F15F}", "\u{1D429}", "\u{1D40F}", "\u{1D631}", "\u{1D617}", "\u{1D665}", "\u{1D64B}", "\u{1D4C5}", "\u{1D4F9}", "\u{1D4DF}", "\u{1D561}", "\u2115", "\u{1D52D}", "\u{1D510}", "\u{1D595}", "\u{1D57B}", "\u{1F13F}", "\u{1F17F}", "\u{1D4AB}", "\u{1D699}", "\u{1D67F}", "\u0440"],
q: [
"q",
"\u146B",
"Q",
"\u24E0",
"\u24C6",
"\u034F",
"\u13A4",
"\u03C6",
"\u10B3",
"\u0566",
"\u033E",
"\uFF51",
"\uFF31",
"\u03D9",
"\u01EB",
"\u{1F160}",
"\u{1D42A}",
"\u{1D410}",
"\u{1D632}",
"\u{1D618}",
"\u{1D666}",
"\u{1D64C}",
"\u{1D4C6}",
"\u{1D4FA}",
"\u{1D4E0}",
"\u{1D562}",
"\u200B",
"\u{1D52E}",
"\u{1D511}",
"\u{1D596}",
"\u{1D57C}",
"\u{1F140}",
"\u{1F180}",
"\u{1D4AC}",
"\u{1D69A}",
"\u{1D680}",
"\u262D",
"\u051B"
],
r: ["r", "\u1587", "R", "\u24E1", "\u24C7", "\u044F", "\u2C64", "\u0155", "\u0154", "\u13D2", "\u0433", "\u0393", "\u1E59", "\u1E58", "\u0280", "\uFF52", "\uFF32", "\u0279", "\u{1F161}", "\u{1D42B}", "\u{1D411}", "\u{1D633}", "\u{1D619}", "\u{1D667}", "\u{1D64D}", "\u{1D4C7}", "\u{1D4FB}", "\u{1D4E1}", "\u{1D563}", "\u{1D546}", "\u{1D52F}", "\u{1D512}", "\u{1D597}", "\u{1D57D}", "\u{1F141}", "\u{1F181}", "\u{1D445}", "\u027E", "\u{1D69B}", "\u{1D681}", "\u2608", "r", "\u{1D681}", "\u{1D4FB}"],
s: ["s", "5", "\u1515", "S", "\u24E2", "\u24C8", "\u0455", "\u034F", "\u20B4", "\u1E69", "\u1E68", "\u13D5", "\u0405", "\u1E60", "\u0586", "\u033E", "\uFF53", "\uFF33", "\uA731", "\u{1F162}", "\u{1D42C}", "\u{1D412}", "\u{1D634}", "\u{1D61A}", "\u{1D668}", "\u{1D64E}", "\u{1D4C8}", "\u{1D4FC}", "\u{1D4E2}", "\u{1D564}", "\u2119", "\u{1D530}", "\u{1D513}", "\u{1D598}", "\u{1D57E}", "\u{1F142}", "\u{1F182}", "\u{1D4AE}", "\u0282", "\u{1D69C}", "\u{1D682}", "\u0455", "\u{1D4FC}"],
t: ["t", "+", "T", "\u24E3", "\u24C9", "\u0442", "\u20AE", "\u1E97", "\u1E6E", "\u13D6", "\u03C4", "\u01AC", "\u13C6", "\u0236", "\uFF54", "\uFF34", "\u1D1B", "\u0287", "\u{1F163}", "\u{1D42D}", "\u{1D413}", "\u{1D635}", "\u{1D61B}", "\u{1D669}", "\u{1D64F}", "\u{1D4C9}", "\u{1D4FD}", "\u{1D4E3}", "\u{1D565}", "\u200B", "\u{1D531}", "\u{1D514}", "\u{1D599}", "\u{1D57F}", "\u{1F143}", "\u{1F183}", "\u{1D4AF}", "\u019A", "\u{1D69D}", "\u{1D683}", "\u2602", "t", "\u{1D4FD}"],
u: ["u", "\xFA", "\xFC", "\u144C", "U", "\u24E4", "\u24CA", "\u03C5", "\u034F", "\u0244", "\xDC", "\u13EC", "\u01B1", "\u1E73", "\u1E72", "\u028A", "\u033E", "\uFF55", "\uFF35", "\u1D1C", "\u{1F164}", "\u{1D42E}", "\u{1D414}", "\u{1D636}", "\u{1D61C}", "\u{1D66A}", "\u{1D650}", "\u{1D4CA}", "\u{1D4FE}", "\u{1D4E4}", "\u{1D566}", "\u211A", "\u{1D532}", "\u211C", "\u{1D59A}", "\u{1D580}", "\u{1F144}", "\u{1F184}", "\u{1D4B0}", "\u{1D69E}", "\u{1D684}", "\u260B", "\u057D"],
v: ["v", "\u142F", "V", "\u24E5", "\u24CB", "\u03BD", "\u1E7F", "\u1E7E", "\u13C9", "\u01B2", "\u1E7C", "\u028B", "\uFF56", "\uFF36", "\u1D20", "\u028C", "\u{1F165}", "\u{1D42F}", "\u{1D415}", "\u{1D637}", "\u{1D61D}", "\u{1D66B}", "\u{1D651}", "\u{1D4CB}", "\u{1D4FF}", "\u{1D4E5}", "\u{1D567}", "\u200B", "\u{1D533}", "\u{1D59B}", "\u{1D581}", "\u{1F145}", "\u{1F185}", "\u{1D4B1}", "\u{1D69F}", "\u{1D685}", "\u2713", "\u2174"],
w: ["w", "\u15EF", "W", "\u24E6", "\u24CC", "\u03C9", "\u034F", "\u20A9", "\u1E85", "\u1E84", "\u13C7", "\u0448", "\u0428", "\u1E87", "\u1E86", "\u13B3", "\u0561", "\u033E", "\uFF57", "\uFF37", "\u1D21", "\u028D", "\u{1F166}", "\u{1D430}", "\u{1D416}", "\u{1D638}", "\u{1D61E}", "\u{1D66C}", "\u{1D652}", "\u{1D4CC}", "\u{1D500}", "\u{1D4E6}", "\u{1D568}", "\u211D", "\u{1D534}", "\u{1D516}", "\u{1D59C}", "\u{1D582}", "\u{1F146}", "\u{1F186}", "\u{1D4B2}", "\u026F", "\u{1D6A0}", "\u{1D686}", "\u051D"],
x: ["x", "\u166D", "X", "\u24E7", "\u24CD", "\u03C7", "\u04FE", "\u1E8D", "\u1E8C", "\u1300", "\u03F0", "\u0416", "\u0445", "\u04FC", "\uFF58", "\uFF38", "\u{1F167}", "\u{1D431}", "\u{1D417}", "\u{1D639}", "\u{1D61F}", "\u{1D66D}", "\u{1D653}", "\u{1D4CD}", "\u{1D501}", "\u{1D4E7}", "\u{1D569}", "\u200B", "\u{1D535}", "\u{1D517}", "\u{1D59D}", "\u{1D583}", "\u{1F147}", "\u{1F187}", "\u{1D4B3}", "\u{1D6A1}", "\u{1D687}", "\u2318", "\u0445"],
y: [
"y",
"Y",
"\u24E8",
"\u24CE",
"\u0443",
"\u034F",
"\u024E",
"\xFF",
"\u0178",
"\u13A9",
"\u03C8",
"\u03A8",
"\u1E8F",
"\u1E8E",
"\u13BD",
"\u0447",
"\u028F",
"\u033E",
"\uFF59",
"\uFF39",
"\u028E",
"\u{1F168}",
"\u{1D432}",
"\u{1D418}",
"\u{1D63A}",
"\u{1D620}",
"\u{1D66E}",
"\u{1D654}",
"\u{1D4CE}",
"\u{1D502}",
"\u{1D4E8}",
"\u{1D56A}",
"\u{1D54A}",
"\u{1D536}",
"\u{1D518}",
"\u{1D59E}",
"\u{1D584}",
"\u{1F148}",
"\u{1F188}",
"\u{1D4B4}",
"\u10E7",
"\u{1D6A2}",
"\u{1D688}",
"\u263F",
"\u0443"
],
z: ["z", "\u1614", "Z", "\u24E9", "\u24CF", "\u2C6B", "\u1E93", "\u1E92", "\u135A", "\u13C3", "\u0290", "\uFF5A", "\uFF3A", "\u1D22", "\u{1F169}", "\u{1D433}", "\u{1D419}", "\u{1D63B}", "\u{1D621}", "\u{1D66F}", "\u{1D655}", "\u{1D4CF}", "\u{1D503}", "\u{1D4E9}", "\u{1D56B}", "\u{1D54B}", "\u{1D537}", "\u{1D519}", "\u{1D59F}", "\u{1D585}", "\u{1F149}", "\u{1F189}", "\u{1D4B5}", "\u0225", "\u{1D6A3}", "\u{1D689}", "\u2621", "z", "\u{1D503}"]
};
const filterWords = Chat.filterWords;
const Filters = new class {
constructor() {
this.EVASION_DETECTION_SUB_STRINGS = {};
for (const letter in EVASION_DETECTION_SUBSTITUTIONS) {
this.EVASION_DETECTION_SUB_STRINGS[letter] = `[${EVASION_DETECTION_SUBSTITUTIONS[letter].join("")}]`;
}
this.load();
}
constructEvasionRegex(str) {
const buf = "\\b" + [...str].map((letter) => (this.EVASION_DETECTION_SUB_STRINGS[letter] || letter) + "+").join("\\.?") + "\\b";
return new RegExp(buf, "iu");
}
generateRegex(word, isEvasion = false, isShortener = false, isReplacement = false) {
try {
if (isEvasion) {
return this.constructEvasionRegex(word);
} else {
return new RegExp(isShortener ? `\\b${word}` : word, isReplacement ? "igu" : "iu");
}
} catch (e) {
throw new Chat.ErrorMessage(
e.message.startsWith("Invalid regular expression: ") ? e.message : `Invalid regular expression: /${word}/: ${e.message}`
);
}
}
stripWordBoundaries(regex) {
return new RegExp(regex.toString().replace("/\\b", "").replace("\\b/iu", ""), "iu");
}
save(force = false) {
(0, import_lib.FS)(MONITOR_FILE).writeUpdate(() => {
const buf = {};
for (const key in Chat.monitors) {
buf[key] = [];
for (const filterWord of filterWords[key]) {
const word = { ...filterWord };
delete word.regex;
buf[key].push(word);
}
}
return JSON.stringify(buf);
}, { throttle: force ? 0 : WRITE_THROTTLE_TIME });
}
add(filterWord) {
if (!filterWord.hits)
filterWord.hits = 0;
const punishment = Chat.monitors[filterWord.list].punishment;
if (!filterWord.regex) {
filterWord.regex = this.generateRegex(
filterWord.word,
punishment === "EVASION",
punishment === "SHORTENER",
!!filterWord.replacement
);
}
if (filterWords[filterWord.list].some((val) => String(val.regex) === String(filterWord.regex))) {
throw new Chat.ErrorMessage(`${filterWord.word} is already added to the ${filterWord.list} list.`);
}
filterWords[filterWord.list].push(filterWord);
this.save(true);
}
load() {
const legacy = (0, import_lib.FS)(LEGACY_MONITOR_FILE);
if (legacy.existsSync()) {
return process.nextTick(() => {
this.loadLegacy();
legacy.renameSync(LEGACY_MONITOR_FILE + ".backup");
Monitor.notice(`Legacy chatfilter data loaded and renamed to a .backup file.`);
});
}
const data = JSON.parse((0, import_lib.FS)(MONITOR_FILE).readIfExistsSync() || "{}");
for (const k in data) {
filterWords[k] = [];
for (const entry of data[k]) {
if (k === "evasion") {
entry.regex = this.constructEvasionRegex(entry.word);
} else {
entry.regex = new RegExp(
k === "shorteners" ? `\\b${entry.word}` : entry.word,
entry.replacement ? "igu" : "iu"
);
}
filterWords[k].push(entry);
}
}
}
loadLegacy() {
let data;
try {
data = (0, import_lib.FS)(LEGACY_MONITOR_FILE).readSync();
} catch (e) {
if (e.code !== "ENOENT")
throw e;
}
if (!data)
return;
const lines = data.split("\n");
loop:
for (const line of lines) {
if (!line || line === "\r")
continue;
const [location, word, punishment, reason, times, ...rest] = line.split(" ").map((param) => param.trim());
if (location === "Location")
continue;
if (!(location && word && punishment))
continue;
for (const key in Chat.monitors) {
if (Chat.monitors[key].location === location && Chat.monitors[key].punishment === punishment) {
const replacement = rest[0];
const publicReason = rest[1];
let regex;
if (punishment === "EVASION") {
regex = Filters.constructEvasionRegex(word);
} else {
regex = new RegExp(punishment === "SHORTENER" ? `\\b${word}` : word, replacement ? "igu" : "iu");
}
const filterWord = { regex, word, hits: parseInt(times) || 0 };
if (reason && reason !== "undefined")
filterWord.reason = reason;
if (publicReason)
filterWord.publicReason = publicReason;
if (replacement)
filterWord.replacement = replacement;
filterWords[key].push(filterWord);
continue loop;
}
}
Monitor.crashlog(new Error("Couldn't find [location, punishment] pair for a filter word"), "The main process", {
location,
word,
punishment,
reason,
times,
rest
});
}
}
}();
Chat.registerMonitor("autolock", {
location: "EVERYWHERE",
punishment: "AUTOLOCK",
label: "Autolock",
monitor(line, room, user, message, lcMessage, isStaff) {
const { regex, word, reason, publicReason } = line;
const match = regex.exec(lcMessage);
if (match) {
if (isStaff)
return `${message} __[would be locked: ${word}${reason ? ` (${reason})` : ""}]__`;
message = message.replace(/(https?):\/\//g, "$1__:__//");
message = message.replace(/\./g, "__.__");
if (room) {
void Punishments.autolock(
user,
room,
"ChatMonitor",
`Filtered phrase: ${word}`,
`<<${room.roomid}>> ${user.name}: ||\`\`${message}\`\`${reason ? ` __(${reason})__` : ""}||`,
true
);
} else {
this.errorReply(`Please do not say '${match[0]}'${publicReason ? ` ${publicReason}` : ``}.`);
}
return false;
}
}
});
Chat.registerMonitor("publicwarn", {
location: "PUBLIC",
punishment: "WARN",
label: "Filtered in public",
monitor(line, room, user, message, lcMessage, isStaff) {
const { regex, word, reason, publicReason } = line;
const match = regex.exec(lcMessage);
if (match) {
if (isStaff)
return `${message} __[would be filtered in public: ${word}${reason ? ` (${reason})` : ""}]__`;
this.errorReply(`Please do not say '${match[0]}'${publicReason ? ` ${publicReason}` : ``}.`);
return false;
}
}
});
Chat.registerMonitor("warn", {
location: "EVERYWHERE",
punishment: "WARN",
label: "Filtered",
monitor(line, room, user, message, lcMessage, isStaff) {
const { regex, word, reason, publicReason } = line;
const match = regex.exec(lcMessage);
if (match) {
if (isStaff)
return `${message} __[would be filtered: ${word}${reason ? ` (${reason})` : ""}]__`;
this.errorReply(`Please do not say '${match[0]}'${publicReason ? ` ${publicReason}` : ``}.`);
return false;
}
}
});
Chat.registerMonitor("evasion", {
location: "EVERYWHERE",
punishment: "EVASION",
label: "Filter Evasion Detection",
monitor(line, room, user, message, lcMessage, isStaff) {
const { regex, word, reason, publicReason } = line;
let normalizedMessage = lcMessage.normalize("NFKC");
normalizedMessage = normalizedMessage.replace(/[\s-_,.]+/g, ".");
const match = regex.exec(normalizedMessage);
if (match) {
if (match[0] === word && regex.test(message)) {
if (isStaff)
return `${message} __[would be filtered: ${word}${reason ? ` (${reason})` : ""}]__`;
this.errorReply(`Do not say '${word}'.`);
return false;
}
if (isStaff)
return `${message} __[would be locked for filter evading: ${match[0]} (${word})]__`;
message = message.replace(/(https?):\/\//g, "$1__:__//");
if (room) {
void Punishments.autolock(
user,
room,
"FilterEvasionMonitor",
`Evading filter: ${message} (${match[0]} => ${word})`,
`<<${room.roomid}>> ${user.name}: ||\`\`${message}\`\` __(${match[0]} => ${word})__||`,
true
);
} else {
this.errorReply(`Please do not say '${word}'${publicReason ? ` ${publicReason}` : ``}.`);
}
return false;
}
}
});
Chat.registerMonitor("wordfilter", {
location: "EVERYWHERE",
punishment: "FILTERTO",
label: "Filtered to a different phrase",
condition: "notStaff",
monitor(line, room, user, message, lcMessage, isStaff) {
const { regex, replacement } = line;
let match = regex.exec(message);
while (match) {
let filtered = replacement || "";
if (match[0] === match[0].toUpperCase())
filtered = filtered.toUpperCase();
if (match[0].startsWith(match[0].charAt(0).toUpperCase())) {
filtered = `${filtered ? filtered.charAt(0).toUpperCase() : ""}${filtered.slice(1)}`;
}
message = message.replace(match[0], filtered);
match = regex.exec(message);
}
return message;
}
});
Chat.registerMonitor("namefilter", {
location: "NAMES",
punishment: "WARN",
label: "Filtered in names"
});
Chat.registerMonitor("battlefilter", {
location: "BATTLES",
punishment: "MUTE",
label: "Filtered in battles",
monitor(line, room, user, message, lcMessage, isStaff) {
const { regex, word, reason, publicReason } = line;
const match = regex.exec(lcMessage);
if (match) {
if (isStaff)
return `${message} __[would be filtered: ${word}${reason ? ` (${reason})` : ""}]__`;
message = message.replace(/(https?):\/\//g, "$1__:__//");
message = message.replace(/\./g, "__.__");
if (room) {
room.mute(user);
this.errorReply(
`You have been muted for using a banned phrase. Please do not say '${match[0]}'${publicReason ? ` ${publicReason}` : ``}.`
);
const text = `[BattleMonitor] <<${room.roomid}>> MUTED: ${user.name}: ${message}${reason ? ` __(${reason})__` : ""}`;
const adminlog = Rooms.get("adminlog");
if (adminlog) {
adminlog.add(`|c|~|${text}`).update();
} else {
Monitor.log(text);
}
void room.uploadReplay(user, this.connection, "forpunishment");
}
return false;
}
}
});
Chat.registerMonitor("shorteners", {
location: "EVERYWHERE",
punishment: "SHORTENER",
label: "URL Shorteners",
condition: "notTrusted",
monitor(line, room, user, message, lcMessage, isStaff) {
const { regex, word, publicReason } = line;
if (regex.test(lcMessage)) {
if (isStaff)
return `${message} __[shortener: ${word}]__`;
this.errorReply(`Please do not use URL shorteners such as '${word}'${publicReason ? ` ${publicReason}` : ``}.`);
return false;
}
}
});
const chatfilter = function(message, user, room) {
let lcMessage = message.replace(/\u039d/g, "N").toLowerCase().replace(/[\u200b\u007F\u00AD\uDB40\uDC00\uDC21]/g, "").replace(/\u03bf/g, "o").replace(/\u043e/g, "o").replace(/\u0430/g, "a").replace(/\u0435/g, "e").replace(/\u039d/g, "e");
lcMessage = lcMessage.replace(/__|\*\*|``|\[\[|\]\]/g, "");
const isStaffRoom = room && (room.persist && room.roomid.endsWith("staff") || room.roomid.startsWith("help-"));
const isStaff = isStaffRoom || user.isStaff || !!(this.pmTarget && this.pmTarget.isStaff);
for (const list in Chat.monitors) {
const { location, condition, monitor } = Chat.monitors[list];
if (!monitor)
continue;
if (location === "BATTLES" && !(room && room.battle && room.battle.challengeType !== "challenge"))
continue;
if (location === "PUBLIC" && room && room.settings.isPrivate === true)
continue;
switch (condition) {
case "notTrusted":
if (user.trusted && !isStaffRoom)
continue;
break;
case "notStaff":
if (isStaffRoom)
continue;
break;
}
for (const line of Chat.filterWords[list]) {
const ret = monitor.call(this, line, room, user, message, lcMessage, isStaff);
if (ret !== void 0 && ret !== message) {
line.hits++;
Filters.save();
}
if (typeof ret === "string") {
message = ret;
} else if (ret === false) {
return false;
}
}
}
return message;
};
const namefilter = (name, user) => {
const id = toID(name);
if (Punishments.namefilterwhitelist.has(id))
return name;
if (Monitor.forceRenames.has(id)) {
if (typeof Monitor.forceRenames.get(id) === "number") {
Monitor.forceRenames.set(id, false);
}
if (!Monitor.forceRenames.get(id)) {
user.trackRename = id;
Monitor.forceRenames.set(id, true);
}
return "";
}
if (id === toID(user.trackRename))
return "";
let lcName = name.replace(/\u039d/g, "N").toLowerCase().replace(/[\u200b\u007F\u00AD]/g, "").replace(/\u03bf/g, "o").replace(/\u043e/g, "o").replace(/\u0430/g, "a").replace(/\u0435/g, "e").replace(/\u039d/g, "e");
lcName = lcName.replace("herapist", "").replace("grape", "").replace("scrape", "");
for (const list in filterWords) {
if (!Chat.monitors[list] || Chat.monitors[list].location === "BATTLES")
continue;
const punishment = Chat.monitors[list].punishment;
for (const line of filterWords[list]) {
const regex = punishment === "EVASION" ? Filters.stripWordBoundaries(line.regex) : line.regex;
if (regex.test(lcName)) {
if (Chat.monitors[list].punishment === "AUTOLOCK") {
void Punishments.autolock(
user,
"staff",
`NameMonitor`,
`inappropriate name: ${name}`,
`using an inappropriate name: ||${name} (from ${user.name})||`,
false,
name
);
}
line.hits++;
Filters.save();
return "";
}
}
}
return name;
};
const loginfilter = (user) => {
if (user.namelocked)
return;
if (user.trackRename) {
const manualForceRename = Monitor.forceRenames.has(toID(user.trackRename));
Rooms.global.notifyRooms(
["staff"],
import_lib.Utils.html`|html|[NameMonitor] Username used: <span class="username">${user.name}</span> ${user.getAccountStatusString()} (${!manualForceRename ? "automatically " : ""}forcerenamed from <span class="username">${user.trackRename}</span>)`
);
user.trackRename = "";
}
const offlineWarn = Punishments.offlineWarns.get(user.id);
if (typeof offlineWarn !== "undefined") {
user.send(`|c|~|/warn You were warned while offline${offlineWarn.length ? `: ${offlineWarn}` : "."}`);
Punishments.offlineWarns.delete(user.id);
}
};
const nicknamefilter = (name, user) => {
let lcName = name.replace(/\u039d/g, "N").toLowerCase().replace(/[\u200b\u007F\u00AD]/g, "").replace(/\u03bf/g, "o").replace(/\u043e/g, "o").replace(/\u0430/g, "a").replace(/\u0435/g, "e").replace(/\u039d/g, "e");
lcName = lcName.replace("herapist", "").replace("grape", "").replace("scrape", "");
for (const list in filterWords) {
if (!Chat.monitors[list])
continue;
if (Chat.monitors[list].location === "BATTLES")
continue;
for (const line of filterWords[list]) {
let { regex, word } = line;
if (Chat.monitors[list].punishment === "EVASION") {
regex = Filters.stripWordBoundaries(regex);
}
const match = regex.exec(lcName);
if (match) {
if (Chat.monitors[list].punishment === "AUTOLOCK") {
void Punishments.autolock(
user,
"staff",
`NameMonitor`,
`inappropriate Pok\xE9mon nickname: ${name}`,
`${user.name} - using an inappropriate Pok\xE9mon nickname: ||${name}||`,
true
);
} else if (Chat.monitors[list].punishment === "EVASION" && match[0] !== lcName) {
void Punishments.autolock(
user,
"staff",
"FilterEvasionMonitor",
`Evading filter in Pok\xE9mon nickname (${name} => ${word})`,
`${user.name}: Pok\xE9mon nicknamed ||\`\`${name} => ${word}\`\`||`,
true
);
}
line.hits++;
Filters.save();
return "";
}
}
}
return name;
};
const statusfilter = (status, user) => {
let lcStatus = status.replace(/\u039d/g, "N").toLowerCase().replace(/[\u200b\u007F\u00AD]/g, "").replace(/\u03bf/g, "o").replace(/\u043e/g, "o").replace(/\u0430/g, "a").replace(/\u0435/g, "e").replace(/\u039d/g, "e");
lcStatus = lcStatus.replace("herapist", "").replace("grape", "").replace("scrape", "");
const impersonationRegex = /\b(?:global|room|upper|senior)?\s*(?:staff|admin|administrator|leader|owner|founder|mod|moderator|driver|voice|operator|sysop|creator)\b/gi;
if (!user.can("lock") && impersonationRegex.test(lcStatus))
return "";
for (const list in filterWords) {
if (!Chat.monitors[list])
continue;
const punishment = Chat.monitors[list].punishment;
for (const line of filterWords[list]) {
const regex = punishment === "EVASION" ? Filters.stripWordBoundaries(line.regex) : line.regex;
if (regex.test(lcStatus)) {
if (punishment === "AUTOLOCK") {
void Punishments.autolock(
user,
"staff",
`NameMonitor`,
`inappropriate status message: ${status}`,
`${user.name} - using an inappropriate status: ||${status}||`,
true
);
}
line.hits++;
Filters.save();
return "";
}
}
}
return status;
};
const pages = {
filters(query, user, connection) {
if (!user.named)
return Rooms.RETRY_AFTER_LOGIN;
this.title = "Filters";
let buf = `<div class="pad ladder"><h2>Filters</h2>`;
if (!user.can("addhtml"))
this.checkCan("lock");
let content = ``;
for (const key in Chat.monitors) {
content += `<tr><th colspan="2"><h3>${Chat.monitors[key].label} <span style="font-size:8pt;">[${key}]</span></h3></tr></th>`;
if (filterWords[key].length) {
content += filterWords[key].map(({ regex, word, reason, publicReason, replacement, hits }) => {
let entry = import_lib.Utils.html`<abbr title="${reason}"><code>${word}</code></abbr>`;
if (publicReason)
entry += import_lib.Utils.html` <small>(public reason: ${publicReason})</small>`;
if (replacement)
entry += import_lib.Utils.html` &rArr; ${replacement}`;
return `<tr><td>${entry}</td><td>${hits}</td></tr>`;
}).join("");
}
}
if (Punishments.namefilterwhitelist.size) {
content += `<tr><th colspan="2"><h3>Whitelisted names</h3></tr></th>`;
for (const [val] of Punishments.namefilterwhitelist) {
content += `<tr><td>${val}</td></tr>`;
}
}
if (!content) {
buf += `<p>There are no filtered words.</p>`;
} else {
buf += `<table>${content}</table>`;
}
buf += `</div>`;
return buf;
}
};
const commands = {
filters: "filter",
filter: {
add(target, room, user) {
this.checkCan("rangeban");
let separator = ",";
if (target.includes("\n")) {
separator = "\n";
} else if (target.includes("/")) {
separator = "/";
}
let [list, ...rest] = target.split(separator);
list = toID(list);
if (!list || !rest.length) {
return this.errorReply(`Syntax: /filter add list ${separator} word ${separator} reason [${separator} optional public reason]`);
}
if (!(list in filterWords)) {
return this.errorReply(`Invalid list: ${list}. Possible options: ${Object.keys(filterWords).join(", ")}`);
}
const filterWord = { list, word: "" };
rest = rest.map((part) => part.trim());
if (Chat.monitors[list].punishment === "FILTERTO") {
[filterWord.word, filterWord.replacement, filterWord.reason, filterWord.publicReason] = rest;
if (!filterWord.replacement) {
return this.errorReply(
`Syntax for word filters: /filter add ${list} ${separator} regex ${separator} reason [${separator} optional public reason]`
);
}
} else {
[filterWord.word, filterWord.reason, filterWord.publicReason] = rest;
}
filterWord.word = filterWord.word.trim();
if (!filterWord.word) {
return this.errorReply(`Invalid word: '${filterWord.word}'.`);
}
Filters.add(filterWord);
const reason = filterWord.reason ? ` (${filterWord.reason})` : "";
if (Chat.monitors[list].punishment === "FILTERTO") {
this.globalModlog(`ADDFILTER`, null, `'${String(filterWord.regex)} => ${filterWord.replacement}' to ${list} list${reason}`);
} else {
this.globalModlog(`ADDFILTER`, null, `'${filterWord.word}' to ${list} list${reason}`);
}
const output = `'${filterWord.word}' was added to the ${list} list.`;
Rooms.get("upperstaff")?.add(output).update();
if (room?.roomid !== "upperstaff")
this.sendReply(output);
},
remove(target, room, user) {
this.checkCan("rangeban");
let [list, ...words] = target.split(target.includes("\n") ? "\n" : ",").map((param) => param.trim());
list = toID(list);
if (!list || !words.length)
return this.errorReply("Syntax: /filter remove list, words");
if (!(list in filterWords)) {
return this.errorReply(`Invalid list: ${list}. Possible options: ${Object.keys(filterWords).join(", ")}`);
}
const notFound = words.filter((val) => !filterWords[list].filter((entry) => entry.word === val).length);
if (notFound.length) {
return this.errorReply(`${notFound.join(", ")} ${Chat.plural(notFound, "are", "is")} not on the ${list} list.`);
}
filterWords[list] = filterWords[list].filter((entry) => !words.includes(entry.word));
this.globalModlog(`REMOVEFILTER`, null, `'${words.join(", ")}' from ${list} list`);
Filters.save(true);
const output = `'${words.join(", ")}' ${Chat.plural(words, "were", "was")} removed from the ${list} list.`;
Rooms.get("upperstaff")?.add(output).update();
if (room?.roomid !== "upperstaff")
this.sendReply(output);
},
"": "view",
list: "view",
view(target, room, user) {
this.parse(`/join view-filters`);
},
help(target, room, user) {
this.parse(`/help filter`);
},
test(target, room, user) {
this.checkCan("lock");
if (room && ["staff", "upperstaff"].includes(room.roomid)) {
this.runBroadcast(true, `!filter test ${target}`);
}
const lcMessage = Chat.stripFormatting(target.replace(/\u039d/g, "N").toLowerCase().replace(/[\u200b\u007F\u00AD\uDB40\uDC00\uDC21]/g, "").replace(/\u03bf/g, "o").replace(/\u043e/g, "o").replace(/\u0430/g, "a").replace(/\u0435/g, "e").replace(/\u039d/g, "e"));
const buf = [];
for (const monitorName in Chat.monitors) {
const monitor = Chat.monitors[monitorName];
if (!monitor.monitor)
continue;
for (const line of Chat.filterWords[monitorName]) {
const ret = monitor.monitor.call(this, line, room, user, target, lcMessage, true);
if (typeof ret === "string") {
buf.push(`${monitorName}: ${ret}`);
break;
} else if (ret === false) {
buf.push(`${monitorName}: "${target}" would be blocked from being sent.`);
break;
}
}
}
if (buf.length) {
return this.sendReplyBox(Chat.formatText(buf.join("\n"), false, true));
} else {
throw new Chat.ErrorMessage(
`"${target}" doesn't trigger any filters. Check spelling?`
);
}
},
testhelp(target, room, user) {
this.checkCan("lock");
if (room && ["staff", "upperstaff"].includes(room.roomid))
this.runBroadcast(true);
const monitorNames = [...Object.keys(Chat.monitors).filter((x) => Chat.monitors[x].monitor)];
monitorNames.push(
...Object.keys(Chat.monitors).filter((x) => Chat.monitors[x].monitor && x.includes("filter")).map((x) => x.replace("filter", ""))
);
this.sendReplyBox(
`<code>/filter test [monitor name] [test string]</code>:<br />Tests whether or not the provided test string would trigger the respective monitor.<br />All usable commands: <code>${monitorNames.sort().map((x) => `/filter test ${x}`).join("</code>, <code>")}</code><br />Can only be broadcast in Staff and Upper Staff. Requires: % @ &`
);
}
},
filterhelp: [
`/filter add list, word, reason[, optional public reason] - Adds a word to the given filter list. Requires: &`,
`/filter remove list, words - Removes words from the given filter list. Requires: &`,
`/filter view - Opens the list of filtered words. Requires: % @ &`,
`/filter test - Do "/help filter test" for more information. Requires: % @ &`,
`You may use / instead of , in /filter add if you want to specify a reason that includes commas.`
],
allowname(target, room, user) {
this.checkCan("forcerename");
target = toID(target);
if (!target)
return this.errorReply(`Syntax: /allowname username`);
if (Punishments.namefilterwhitelist.has(target)) {
return this.errorReply(`${target} is already allowed as a username.`);
}
const msg = `${target} was allowed as a username by ${user.name}.`;
const toNotify = ["staff", "upperstaff"];
Rooms.global.notifyRooms(toNotify, `|c|${user.getIdentity()}|/log ${msg}`);
if (!room || !toNotify.includes(room.roomid)) {
this.sendReply(msg);
}
this.globalModlog(`ALLOWNAME`, target);
Monitor.forceRenames.delete(target);
}
};
process.nextTick(() => {
Chat.multiLinePattern.register("/filter (add|remove) ");
});
//# sourceMappingURL=chat-monitor.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/chat-monitor.ts"],
"sourcesContent": ["import {FS, Utils} from '../../lib';\r\nimport type {FilterWord} from '../chat';\r\n\r\nconst LEGACY_MONITOR_FILE = 'config/chat-plugins/chat-monitor.tsv';\r\nconst MONITOR_FILE = 'config/chat-plugins/chat-filter.json';\r\nconst WRITE_THROTTLE_TIME = 5 * 60 * 1000;\r\n\r\n// Substitution dictionary adapted from https://github.com/ThreeLetters/NoSwearingPlease/blob/master/index.js\r\n// Licensed under MIT.\r\nconst EVASION_DETECTION_SUBSTITUTIONS: {[k: string]: string[]} = {\r\n\ta: [\"a\", \"4\", \"@\", \"\u00E1\", \"\u00E2\", \"\u00E3\", \"\u00E0\", \"\u15E9\", \"A\", \"\u24D0\", \"\u24B6\", \"\u03B1\", \"\u034F\", \"\u20B3\", \"\u00E4\", \"\u00C4\", \"\u13D7\", \"\u03BB\", \"\u0394\", \"\u1E00\", \"\u13AA\", \"\u01DF\", \"\u033E\", \"\uFF41\", \"\uFF21\", \"\u1D00\", \"\u0250\", \"\uD83C\uDD50\", \"\uD835\uDC1A\", \"\uD835\uDC00\", \"\uD835\uDE22\", \"\uD835\uDE08\", \"\uD835\uDE56\", \"\uD835\uDE3C\", \"\uD835\uDCB6\", \"\uD835\uDCEA\", \"\uD835\uDCD0\", \"\uD835\uDD52\", \"\uD835\uDD38\", \"\uD835\uDD1E\", \"\uD835\uDD04\", \"\uD835\uDD86\", \"\uD835\uDD6C\", \"\uD83C\uDD30\", \"\uD83C\uDD70\", \"\uD835\uDC9C\", \"\uD835\uDE8A\", \"\uD835\uDE70\", \"\uA34F\", \"\u0430\", \"\uD835\uDCEA\"],\r\n\tb: [\"b\", \"8\", \"\u15F7\", \"B\", \"\u24D1\", \"\u24B7\", \"\u0432\", \"\u0E3F\", \"\u1E05\", \"\u1E04\", \"\u13F0\", \"\u03D0\", \"\u0181\", \"\u1E03\", \"\u1E02\", \"\u026E\", \"\uFF42\", \"\uFF22\", \"\u0299\", \"\uD83C\uDD51\", \"\uD835\uDC1B\", \"\uD835\uDC01\", \"\uD835\uDE23\", \"\uD835\uDE09\", \"\uD835\uDE57\", \"\uD835\uDE3D\", \"\uD835\uDCB7\", \"\uD835\uDCEB\", \"\uD835\uDCD1\", \"\uD835\uDD53\", \"\uD835\uDD39\", \"\uD835\uDD1F\", \"\uD835\uDD05\", \"\uD835\uDD87\", \"\uD835\uDD6D\", \"\uD83C\uDD31\", \"\uD83C\uDD71\", \"\uD835\uDC35\", \"\u10A6\", \"\uD835\uDE8B\", \"\uD835\uDE71\", \"\u266D\", \"b\"],\r\n\tc: [\"c\", \"\u00E7\", \"\u1455\", \"C\", \"\u24D2\", \"\u24B8\", \"\u00A2\", \"\u034F\", \"\u20B5\", \"\u010B\", \"\u010A\", \"\u1348\", \"\u03C2\", \"\u1E09\", \"\u1E08\", \"\u13DF\", \"\u0188\", \"\u033E\", \"\uFF43\", \"\uFF23\", \"\u1D04\", \"\u0254\", \"\uD83C\uDD52\", \"\uD835\uDC1C\", \"\uD835\uDC02\", \"\uD835\uDE24\", \"\uD835\uDE0A\", \"\uD835\uDE58\", \"\uD835\uDE3E\", \"\uD835\uDCB8\", \"\uD835\uDCEC\", \"\uD835\uDCD2\", \"\uD835\uDD54\", \"\u2102\", \"\uD835\uDD20\", \"\u212D\", \"\uD835\uDD88\", \"\uD835\uDD6E\", \"\uD83C\uDD32\", \"\uD83C\uDD72\", \"\uD835\uDC9E\", \"\uD835\uDE8C\", \"\uD835\uDE72\", \"\u263E\", \"\u0441\"],\r\n\td: [\"d\", \"\u15EA\", \"D\", \"\u24D3\", \"\u24B9\", \"\u2202\", \"\u0110\", \"\u010F\", \"\u010E\", \"\u13B4\", \"\u1E0A\", \"\u13A0\", \"\u0256\", \"\uFF44\", \"\uFF24\", \"\u1D05\", \"\uD83C\uDD53\", \"\uD835\uDC1D\", \"\uD835\uDC03\", \"\uD835\uDE25\", \"\uD835\uDE0B\", \"\uD835\uDE59\", \"\uD835\uDE3F\", \"\uD835\uDCB9\", \"\uD835\uDCED\", \"\uD835\uDCD3\", \"\uD835\uDD55\", \"\u200B\", \"\uD835\uDD21\", \"\uD835\uDD89\", \"\uD835\uDD6F\", \"\uD83C\uDD33\", \"\uD83C\uDD73\", \"\uD835\uDC9F\", \"\u0503\", \"\uD835\uDE8D\", \"\uD835\uDE73\", \"\u25D7\", \"\u217E\"],\r\n\te: [\"e\", \"3\", \"\u00E9\", \"\u00EA\", \"E\", \"\u24D4\", \"\u24BA\", \"\u0454\", \"\u034F\", \"\u0246\", \"\u1EC7\", \"\u1EC6\", \"\u13CB\", \"\u03B5\", \"\u03A3\", \"\u1E15\", \"\u1E14\", \"\u13AC\", \"\u025B\", \"\u033E\", \"\uFF45\", \"\uFF25\", \"\u1D07\", \"\u01DD\", \"\uD83C\uDD54\", \"\uD835\uDC1E\", \"\uD835\uDC04\", \"\uD835\uDE26\", \"\uD835\uDE0C\", \"\uD835\uDE5A\", \"\uD835\uDE40\", \"\u212F\", \"\uD835\uDCEE\", \"\uD835\uDCD4\", \"\uD835\uDD56\", \"\uD835\uDD3B\", \"\uD835\uDD22\", \"\uD835\uDD07\", \"\uD835\uDD8A\", \"\uD835\uDD70\", \"\uD83C\uDD34\", \"\uD83C\uDD74\", \"\uD835\uDC52\", \"\uD835\uDC38\", \"\u04BD\", \"\uD835\uDE8E\", \"\uD835\uDE74\", \"\u20AC\", \"\u0435\", \"\u0451\", \"\uD835\uDCEE\"],\r\n\tf: [\"f\", \"\u15B4\", \"F\", \"\u24D5\", \"\u24BB\", \"\u20A3\", \"\u1E1F\", \"\u1E1E\", \"\u13A6\", \"\u0493\", \"\u0284\", \"\uFF46\", \"\uFF26\", \"\u025F\", \"\uD83C\uDD55\", \"\uD835\uDC1F\", \"\uD835\uDC05\", \"\uD835\uDE27\", \"\uD835\uDE0D\", \"\uD835\uDE5B\", \"\uD835\uDE41\", \"\uD835\uDCBB\", \"\uD835\uDCEF\", \"\uD835\uDCD5\", \"\uD835\uDD57\", \"\uD835\uDD3C\", \"\uD835\uDD23\", \"\uD835\uDD08\", \"\uD835\uDD8B\", \"\uD835\uDD71\", \"\uD83C\uDD35\", \"\uD83C\uDD75\", \"\uD835\uDC39\", \"\u03DD\", \"\uD835\uDE8F\", \"\uD835\uDE75\", \"\u03DC\", \"f\"],\r\n\tg: [\"g\", \"q\", \"6\", \"9\", \"G\", \"\u24D6\", \"\u24BC\", \"\u034F\", \"\u20B2\", \"\u0121\", \"\u0120\", \"\u13B6\", \"\u03D1\", \"\u1E20\", \"\u0262\", \"\u033E\", \"\uFF47\", \"\uFF27\", \"\u0183\", \"\uD83C\uDD56\", \"\uD835\uDC20\", \"\uD835\uDC06\", \"\uD835\uDE28\", \"\uD835\uDE0E\", \"\uD835\uDE5C\", \"\uD835\uDE42\", \"\u210A\", \"\uD835\uDCF0\", \"\uD835\uDCD6\", \"\uD835\uDD58\", \"\uD835\uDD3D\", \"\uD835\uDD24\", \"\uD835\uDD09\", \"\uD835\uDD8C\", \"\uD835\uDD72\", \"\uD83C\uDD36\", \"\uD83C\uDD76\", \"\uD835\uDC54\", \"\uD835\uDCA2\", \"\u0260\", \"Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAwB;AAGxB,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,sBAAsB,IAAI,KAAK;AAIrC,MAAM,kCAA2D;AAAA,EAChE,GAAG,CAAC,KAAK,KAAK,KAAK,QAAK,QAAK,QAAK,QAAK,UAAK,KAAK,UAAK,UAAK,UAAK,UAAK,UAAK,QAAK,QAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,UAAK,UAAK,WAAI;AAAA,EACvR,GAAG,CAAC,KAAK,KAAK,UAAK,KAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,U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AAAA,IAAM;AAAA,IAAM;AAAA,IAAM;AAAA,IAAM;AAAA,IAAM;AAAA,IAAK;AAAA,IAAM;AAAA,IAAM;AAAA,IAAM;AAAA,IAAM;AAAA,IAAM;AAAA,IAAM;AAAA,IAAM;AAAA,IAAM;AAAA,IAAM;AAAA,IAAK;AAAA,EAC9M;AAAA,EACA,GAAG,CAAC,KAAK,UAAK,KAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aAAM,aLine truncated
"names": []
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/chatlog.ts"],
"sourcesContent": ["/**\r\n * Pokemon Showdown log viewer\r\n *\r\n * by Zarel\r\n * @license MIT\r\n */\r\n\r\nimport {Utils, FS, Dashycode, ProcessManager, Repl, Net} from '../../lib';\r\nimport {Config} from '../config-loader';\r\nimport {Dex} from '../../sim/dex';\r\nimport {Chat} from '../chat';\r\n\r\nconst DAY = 24 * 60 * 60 * 1000;\r\nconst MAX_RESULTS = 3000;\r\nconst MAX_MEMORY = 67108864; // 64MB\r\nconst MAX_PROCESSES = 1;\r\nconst MAX_TOPUSERS = 100;\r\n\r\nconst CHATLOG_PM_TIMEOUT = 1 * 60 * 60 * 1000; // 1 hour\r\n\r\nconst UPPER_STAFF_ROOMS = ['upperstaff', 'adminlog', 'slowlog'];\r\n\r\ninterface ChatlogSearch {\r\n\traw?: boolean;\r\n\tsearch: string;\r\n\troom: RoomID;\r\n\tdate: string;\r\n\tlimit?: number | null;\r\n\targs?: string[];\r\n}\r\n\r\ninterface RoomStats {\r\n\t/**\r\n\t * Lines per user.\r\n\t */\r\n\tlines: {[k: string]: number};\r\n\t// guessed from |J| (number of joins)\r\n\tusers: {[k: string]: number};\r\n\tdays: number;\r\n\t/**\r\n\t * Average wait time between each line (\"dead\")\r\n\t */\r\n\tdeadTime: number;\r\n\t/**\r\n\t * Average percent of the day that it's inactive\r\n\t */\r\n\tdeadPercent: number;\r\n\t/**\r\n\t * Average lines per user.\r\n\t */\r\n\tlinesPerUser: number;\r\n\ttotalLines: number;\r\n\t/**\r\n\t * Average user count present at any given time (from |userstats|)\r\n\t */\r\n\taveragePresent: number;\r\n}\r\n\r\nexport class LogReaderRoom {\r\n\troomid: RoomID;\r\n\tconstructor(roomid: RoomID) {\r\n\t\tthis.roomid = roomid;\r\n\t}\r\n\r\n\tasync listMonths() {\r\n\t\ttry {\r\n\t\t\tconst listing = await FS(`logs/chat/${this.roomid}`).readdir();\r\n\t\t\treturn listing.filter(file => /^[0-9][0-9][0-9][0-9]-[0-9][0-9]$/.test(file));\r\n\t\t} catch {\r\n\t\t\treturn [];\r\n\t\t}\r\n\t}\r\n\r\n\tasync listDays(month: string) {\r\n\t\ttry {\r\n\t\t\tconst listing = await FS(`logs/chat/${this.roomid}/${month}`).readdir();\r\n\t\t\treturn listing.filter(file => file.endsWith(\".txt\")).map(file => file.slice(0, -4));\r\n\t\t} catch {\r\n\t\t\treturn [];\r\n\t\t}\r\n\t}\r\n\r\n\tasync getLog(day: string) {\r\n\t\tconst month = LogReader.getMonth(day);\r\n\t\tconst log = FS(`logs/chat/${this.roomid}/${month}/${day}.txt`);\r\n\t\tif (!await log.exists()) return null;\r\n\t\treturn log.createReadStream();\r\n\t}\r\n}\r\n\r\nexport const LogReader = new class {\r\n\tasync get(roomid: RoomID) {\r\n\t\tif (!await FS(`logs/chat/${roomid}`).exists()) return null;\r\n\t\treturn new LogReaderRoom(roomid);\r\n\t}\r\n\r\n\tasync list() {\r\n\t\tconst listing = await FS(`logs/chat`).readdir();\r\n\t\treturn listing.filter(file => /^[a-z0-9-]+$/.test(file)) as RoomID[];\r\n\t}\r\n\r\n\tasync listCategorized(user: User, opts?: string) {\r\n\t\tconst list = await this.list();\r\n\t\tconst isUpperStaff = user.can('rangeban');\r\n\t\tconst isStaff = user.can('lock');\r\n\r\n\t\tconst official = [];\r\n\t\tconst normal = [];\r\n\t\tconst hidden = [];\r\n\t\tconst secret = [];\r\n\t\tconst deleted = [];\r\n\t\tconst personal: RoomID[] = [];\r\n\t\tconst deletedPersonal: RoomID[] = [];\r\n\t\tlet atLeastOne = false;\r\n\r\n\t\tfor (const roomid of list) {\r\n\t\t\tconst room = Rooms.get(roomid);\r\n\t\t\tconst forceShow = room && (\r\n\t\t\t\t// you are authed in the room\r\n\t\t\t\t(room.auth.has(user.id) && user.can('mute', null, room)) ||\r\n\t\t\t\t// you are staff and currently in the room\r\n\t\t\t\t(isStaff && user.inRooms.has(room.roomid))\r\n\t\t\t);\r\n\t\t\tif (!isUpperStaff && !forceShow) {\r\n\t\t\t\tif (!isStaff) continue;\r\n\t\t\t\tif (!room) continue;\r\n\t\t\t\tif (!room.checkModjoin(user)) continue;\r\n\t\t\t\tif (room.settings.isPrivate === true) continue;\r\n\t\t\t}\r\n\r\n\t\t\tatLeastOne = true;\r\n\t\t\tif (roomid.includes('-')) {\r\n\t\t\t\tconst matchesOpts = opts && roomid.startsWith(`${opts}-`);\r\n\t\t\t\tif (matchesOpts || opts === 'all' || forceShow) {\r\n\t\t\t\t\t(room ? personal : deletedPersonal).push(roomid);\r\n\t\t\t\t}\r\n\t\t\t} else if (!room) {\r\n\t\t\t\tif (opts === 'all' || opts === 'deleted') deleted.push(roomid);\r\n\t\t\t} else if (room.settings.section === 'official') {\r\n\t\t\t\tofficial.push(roomid);\r\n\t\t\t} else if (!room.settings.isPrivate) {\r\n\t\t\t\tnormal.push(roomid);\r\n\t\t\t} else if (room.settings.isPrivate === 'hidden') {\r\n\t\t\t\thidden.push(roomid);\r\n\t\t\t} else {\r\n\t\t\t\tsecret.push(roomid);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (!atLeastOne) return null;\r\n\t\treturn {official, normal, hidden, secret, deleted, personal, deletedPersonal};\r\n\t}\r\n\r\n\tasync read(roomid: RoomID, day: string, limit: number) {\r\n\t\tconst roomLog = await LogReader.get(roomid);\r\n\t\tconst stream = await roomLog!.getLog(day);\r\n\t\tlet buf = '';\r\n\t\tlet i = (LogSearcher as FSLogSearcher).results || 0;\r\n\t\tif (!stream) {\r\n\t\t\tbuf += `<p class=\"message-error\">Room \"${roomid}\" doesn't have logs for ${day}</p>`;\r\n\t\t} else {\r\n\t\t\tfor await (const line of stream.byLine()) {\r\n\t\t\t\tconst Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAA8D;AAC9D,2BAAqB;AACrB,iBAAkB;AAClB,kBAAmB;AAVnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,MAAM,MAAM,KAAK,KAAK,KAAK;AAC3B,MAAM,cAAc;AACpB,MAAM,aAAa;AACnB,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAErB,MAAM,qBAAqB,IAAI,KAAK,KAAK;AAEzC,MAAM,oBAAoB,CAAC,cAAc,YAAY,SAAS;AAsCvD,MAAM,cAAc;AAAA,EAE1B,YAAY,QAAgB;AAC3B,SAAK,SAAS;AAAA,EACf;AAAA,EAEA,MAAM,aAAa;AAClB,QAAI;AACH,YAAM,UAAU,UAAM,eAAG,aAAa,KAAK,QAAQ,EAAE,QAAQ;AAC7D,aAAO,QAAQ,OAAO,UAAQ,oCAAoC,KAAK,IAAI,CAAC;AAAA,IAC7E,QAAE;AACD,aAAO,CAAC;AAAA,IACT;AAAA,EACD;AAAA,EAEA,MAAM,SAAS,OAAe;AAC7B,QAAI;AACH,YAAM,UAAU,UAAM,eAAG,aAAa,KAAK,UAAU,OAAO,EAAE,QAAQ;AACtE,aAAO,QAAQ,OAAO,UAAQ,KAAK,SAAS,MAAM,CAAC,EAAE,IAAI,UAAQ,KAAK,MAAM,GAAG,EAAE,CAAC;AAAA,IACnF,QAAE;AACD,aAAO,CAA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G;AACtB,YAAI,MAAM,UAAU,GAAG;AAAG,iBAAO;AALine truncated
"names": ["cmd"]
}
@@ -0,0 +1,337 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var daily_spotlight_exports = {};
__export(daily_spotlight_exports, {
commands: () => commands,
destroy: () => destroy,
handlers: () => handlers,
pages: () => pages,
renderSpotlight: () => renderSpotlight,
spotlights: () => spotlights
});
module.exports = __toCommonJS(daily_spotlight_exports);
var import_lib = require("../../lib");
const DAY = 24 * 60 * 60 * 1e3;
const SPOTLIGHT_FILE = "config/chat-plugins/spotlights.json";
const NUMBER_REGEX = /^\s*[0-9]+\s*$/;
let spotlights = {};
try {
spotlights = JSON.parse((0, import_lib.FS)(SPOTLIGHT_FILE).readIfExistsSync() || "{}");
for (const roomid in spotlights) {
for (const k in spotlights[roomid]) {
for (const spotlight of spotlights[roomid][k]) {
if (!spotlight.time) {
spotlight.time = Date.now();
}
}
}
}
} catch (e) {
if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ENOENT")
throw e;
}
if (!spotlights || typeof spotlights !== "object")
spotlights = {};
function saveSpotlights() {
(0, import_lib.FS)(SPOTLIGHT_FILE).writeUpdate(() => JSON.stringify(spotlights));
}
function nextDaily() {
for (const roomid in spotlights) {
for (const key in spotlights[roomid]) {
if (spotlights[roomid][key].length > 1) {
spotlights[roomid][key].shift();
}
}
}
saveSpotlights();
timeout = setTimeout(nextDaily, DAY);
}
const midnight = new Date();
midnight.setHours(24, 0, 0, 0);
let timeout = setTimeout(nextDaily, midnight.valueOf() - Date.now());
async function renderSpotlight(roomid, key, index) {
let imgHTML = "";
const { image, description } = spotlights[roomid][key][index];
if (image) {
if (Array.isArray(image)) {
imgHTML = `<td><img src="${image[0]}" width="${image[1]}" height="${image[2]}" style="vertical-align:middle;"></td>`;
} else {
try {
const [width, height] = await Chat.fitImage(image, 150, 300);
imgHTML = `<td><img src="${image}" width="${width}" height="${height}" style="vertical-align:middle;"></td>`;
spotlights[roomid][key][index].image = [image, width, height];
} catch {
}
}
}
return `<table style="text-align:center;margin:auto"><tr><td style="padding-right:10px;">${Chat.formatText(description, true)}</td>${imgHTML}</tr></table>`;
}
const destroy = () => clearTimeout(timeout);
const pages = {
async spotlights(query, user, connection) {
this.title = "Daily Spotlights";
const room = this.requireRoom();
query.shift();
const sortType = toID(query.shift());
if (sortType && !["time", "alphabet"].includes(sortType)) {
return this.errorReply(`Invalid sorting type '${sortType}' - must be either 'time', 'alphabet', or not provided.`);
}
let buf = `<div class="pad ladder">`;
buf += `<div class="pad">`;
buf += `<button style="float:right;" class="button" name="send" value="/join view-spotlights-${room.roomid}${sortType ? "-" + sortType : ""}">`;
buf += `<i class="fa fa-refresh"></i> Refresh</button>`;
buf += `<h2>Daily Spotlights</h2>`;
if (sortType) {
let title = "";
switch (sortType) {
case "time":
title = "latest time updated";
break;
default:
title = "alphabetical";
break;
}
buf += `(sorted by ${title})<br />`;
}
if (!spotlights[room.roomid]) {
buf += `<p>This room has no daily spotlights.</p></div>`;
} else {
const sortedKeys = import_lib.Utils.sortBy(Object.keys(spotlights[room.roomid]), (key) => {
switch (sortType) {
case "time": {
const sortedSpotlights = import_lib.Utils.sortBy(spotlights[room.roomid][key].slice(), (k) => -k.time);
return -sortedSpotlights[0].time;
}
default:
return key;
}
});
for (const key of sortedKeys) {
buf += `<table style="margin-bottom:30px;"><th colspan="2"><h3>${key}:</h3></th>`;
const keys = import_lib.Utils.sortBy(spotlights[room.roomid][key].slice(), (spotlight) => {
switch (sortType) {
case "time":
return -spotlight.time;
default:
return spotlight.description;
}
});
for (const [i] of keys.entries()) {
const html = await renderSpotlight(room.roomid, key, i);
buf += `<tr><td>${i ? i : "Current"}</td><td>${html}</td></tr>`;
if (!user.can("announce", null, room))
break;
}
buf += "</table>";
}
}
return buf;
}
};
const commands = {
removedaily(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
let [key, rest] = target.split(",");
key = toID(key);
if (!key)
return this.parse("/help daily");
if (!spotlights[room.roomid][key])
return this.errorReply(`Cannot find a daily spotlight with name '${key}'`);
this.checkCan("announce", null, room);
if (rest) {
const queueNumber = parseInt(rest);
if (isNaN(queueNumber) || queueNumber < 1)
return this.errorReply("Invalid queue number");
if (queueNumber >= spotlights[room.roomid][key].length) {
return this.errorReply(`Queue number needs to be between 1 and ${spotlights[room.roomid][key].length - 1}`);
}
spotlights[room.roomid][key].splice(queueNumber, 1);
saveSpotlights();
this.modlog(`DAILY REMOVE`, `${key}[${queueNumber}]`);
this.privateModAction(
`${user.name} removed the ${queueNumber}th entry from the queue of the daily spotlight named '${key}'.`
);
} else {
spotlights[room.roomid][key].shift();
if (!spotlights[room.roomid][key].length) {
delete spotlights[room.roomid][key];
}
saveSpotlights();
this.modlog(`DAILY REMOVE`, key);
this.privateModAction(`${user.name} successfully removed the daily spotlight named '${key}'.`);
}
Chat.refreshPageFor(`spotlights-${room.roomid}`, room);
},
swapdailies: "swapdaily",
swapdaily(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
if (!spotlights[room.roomid])
return this.errorReply("There are no dailies for this room.");
this.checkCan("announce", null, room);
const [key, indexStringA, indexStringB] = target.split(",").map((index) => toID(index));
if (!indexStringB)
return this.parse("/help daily");
if (!spotlights[room.roomid][key])
return this.errorReply(`Cannot find a daily spotlight with name '${key}'`);
if (!(NUMBER_REGEX.test(indexStringA) && NUMBER_REGEX.test(indexStringB))) {
return this.errorReply("Queue numbers must be numbers.");
}
const indexA = parseInt(indexStringA);
const indexB = parseInt(indexStringB);
const queueLength = spotlights[room.roomid][key].length;
if (indexA < 1 || indexB < 1 || indexA >= queueLength || indexB >= queueLength) {
return this.errorReply(`Queue numbers must between 1 and the length of the queue (${queueLength}).`);
}
const dailyA = spotlights[room.roomid][key][indexA];
const dailyB = spotlights[room.roomid][key][indexB];
spotlights[room.roomid][key][indexA] = dailyB;
spotlights[room.roomid][key][indexB] = dailyA;
saveSpotlights();
this.modlog(`DAILY QUEUE SWAP`, key, `${indexA} with ${indexB}`);
this.privateModAction(`${user.name} swapped the queued dailies for '${key}' at queue numbers ${indexA} and ${indexB}.`);
Chat.refreshPageFor(`spotlights-${room.roomid}`, room);
},
queuedaily: "setdaily",
queuedailyat: "setdaily",
replacedaily: "setdaily",
async setdaily(target, room, user, connection, cmd) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
let key, indexString, rest;
if (cmd.endsWith("at") || cmd === "replacedaily") {
[key, indexString, ...rest] = target.split(",");
} else {
[key, ...rest] = target.split(",");
}
key = toID(key);
if (!key)
return this.parse("/help daily");
if (key.length > 20)
return this.errorReply("Spotlight names can be a maximum of 20 characters long.");
if (key === "constructor")
return false;
if (!spotlights[room.roomid])
spotlights[room.roomid] = {};
const queueLength = spotlights[room.roomid][key]?.length || 0;
if (indexString && !NUMBER_REGEX.test(indexString))
return this.errorReply("The queue number must be a number.");
const index = indexString ? parseInt(indexString) : queueLength;
if (indexString && (index < 1 || index > queueLength)) {
return this.errorReply(`Queue numbers must be between 1 and the length of the queue (${queueLength}).`);
}
this.checkCan("announce", null, room);
if (!rest.length)
return this.parse("/help daily");
let img, height, width;
if (rest[0].trim().startsWith("http://") || rest[0].trim().startsWith("https://")) {
[img, ...rest] = rest;
img = img.trim();
try {
[width, height] = await Chat.fitImage(img);
} catch {
return this.errorReply(`Invalid image url: ${img}`);
}
}
const desc = rest.join(",");
if (Chat.stripFormatting(desc).length > 500) {
return this.errorReply("Descriptions can be at most 500 characters long.");
}
if (img)
img = [img, width, height];
const obj = { image: img, description: desc, time: Date.now() };
if (!spotlights[room.roomid][key])
spotlights[room.roomid][key] = [];
if (cmd === "setdaily") {
spotlights[room.roomid][key].shift();
spotlights[room.roomid][key].unshift(obj);
this.modlog("SETDAILY", key, `${img ? `${img}, ` : ""}${desc}`);
this.privateModAction(`${user.name} set the daily ${key}.`);
} else if (cmd === "queuedailyat") {
spotlights[room.roomid][key].splice(index, 0, obj);
this.modlog("QUEUEDAILY", key, `queue number ${index}: ${img ? `${img}, ` : ""}${desc}`);
this.privateModAction(`${user.name} queued a daily ${key} at queue number ${index}.`);
} else {
spotlights[room.roomid][key][index] = obj;
if (indexString) {
this.modlog("REPLACEDAILY", key, `queue number ${index}: ${img ? `${img}, ` : ""}${desc}`);
this.privateModAction(`${user.name} replaced the daily ${key} at queue number ${index}.`);
} else {
this.modlog("QUEUEDAILY", key, `${img ? `${img}, ` : ""}${desc}`);
this.privateModAction(`${user.name} queued a daily ${key}.`);
}
}
saveSpotlights();
Chat.refreshPageFor(`spotlights-${room.roomid}`, room);
},
async daily(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
const key = toID(target);
if (!key)
return this.parse("/help daily");
if (!spotlights[room.roomid]?.[key]) {
return this.errorReply(`Cannot find a daily spotlight with name '${key}'`);
}
if (!this.runBroadcast())
return;
const { image, description } = spotlights[room.roomid][key][0];
const html = await renderSpotlight(room.roomid, key, 0);
this.sendReplyBox(html);
if (!this.broadcasting && user.can("ban", null, room, "setdaily")) {
const code = import_lib.Utils.escapeHTML(description).replace(/\n/g, "<br />");
this.sendReplyBox(`<details><summary>Source</summary><code style="white-space: pre-wrap; display: table; tab-size: 3">/setdaily ${key},${image ? `${image},` : ""}${code}</code></details>`);
}
room.update();
},
vsl: "viewspotlights",
dailies: "viewspotlights",
viewspotlights(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
target = toID(target);
return this.parse(`/join view-spotlights-${room.roomid}${target ? `-${target}` : ""}`);
},
dailyhelp() {
this.sendReply(
`|html|<details class="readmore"><summary><code>/daily [name]</code>: shows the daily spotlight.<br /><code>!daily [name]</code>: shows the daily spotlight to everyone. Requires: + % @ # &<br /><code>/setdaily [name], [image], [description]</code>: sets the daily spotlight. Image can be left out. Requires: % @ # &</summary><code>/queuedaily [name], [image], [description]</code>: queues a daily spotlight. At midnight, the spotlight with this name will automatically switch to the next queued spotlight. Image can be left out. Requires: % @ # &<br /><code>/queuedailyat [name], [queue number], [image], [description]</code>: inserts a daily spotlight into the queue at the specified number (starting from 1). Requires: % @ # &<br /><code>/replacedaily [name], [queue number], [image], [description]</code>: replaces the daily spotlight queued at the specified number. Requires: % @ # &<br /><code>/removedaily [name][, queue number]</code>: if no queue number is provided, deletes all queued and current spotlights with the given name. If a number is provided, removes a specific future spotlight from the queue. Requires: % @ # &<br /><code>/swapdaily [name], [queue number], [queue number]</code>: swaps the two queued spotlights at the given queue numbers. Requires: % @ # &<br /><code>/viewspotlights [sorter]</code>: shows all current spotlights in the room. For staff, also shows queued spotlights.[sorter] can either be unset, 'time', or 'alphabet'. These sort by either the time added, or alphabetical order.</details>`
);
}
};
const handlers = {
onRenameRoom(oldID, newID) {
if (spotlights[oldID]) {
if (!spotlights[newID])
spotlights[newID] = {};
Object.assign(spotlights[newID], spotlights[oldID]);
delete spotlights[oldID];
saveSpotlights();
}
}
};
process.nextTick(() => {
Chat.multiLinePattern.register("/(queue|set|replace)daily(at | )");
});
//# sourceMappingURL=daily-spotlight.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/daily-spotlight.ts"],
"sourcesContent": ["import {FS, Utils} from '../../lib';\r\n\r\nconst DAY = 24 * 60 * 60 * 1000;\r\nconst SPOTLIGHT_FILE = 'config/chat-plugins/spotlights.json';\r\nconst NUMBER_REGEX = /^\\s*[0-9]+\\s*$/;\r\n\r\n/** legacy - string = just url, arr is [url, width, height] */\r\ntype StoredImage = string | [string, number, number];\r\n\r\ninterface Spotlight {\r\n\timage?: StoredImage;\r\n\tdescription: string;\r\n\ttime: number;\r\n}\r\n\r\nexport let spotlights: {\r\n\t[roomid: string]: {[k: string]: Spotlight[]},\r\n} = {};\r\n\r\ntry {\r\n\tspotlights = JSON.parse(FS(SPOTLIGHT_FILE).readIfExistsSync() || \"{}\");\r\n\tfor (const roomid in spotlights) {\r\n\t\tfor (const k in spotlights[roomid]) {\r\n\t\t\tfor (const spotlight of spotlights[roomid][k]) {\r\n\t\t\t\tif (!spotlight.time) {\r\n\t\t\t\t\tspotlight.time = Date.now();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n} catch (e: any) {\r\n\tif (e.code !== 'MODULE_NOT_FOUND' && e.code !== 'ENOENT') throw e;\r\n}\r\nif (!spotlights || typeof spotlights !== 'object') spotlights = {};\r\n\r\nfunction saveSpotlights() {\r\n\tFS(SPOTLIGHT_FILE).writeUpdate(() => JSON.stringify(spotlights));\r\n}\r\n\r\nfunction nextDaily() {\r\n\tfor (const roomid in spotlights) {\r\n\t\tfor (const key in spotlights[roomid]) {\r\n\t\t\tif (spotlights[roomid][key].length > 1) {\r\n\t\t\t\tspotlights[roomid][key].shift();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tsaveSpotlights();\r\n\ttimeout = setTimeout(nextDaily, DAY);\r\n}\r\n\r\nconst midnight = new Date();\r\nmidnight.setHours(24, 0, 0, 0);\r\nlet timeout = setTimeout(nextDaily, midnight.valueOf() - Date.now());\r\n\r\nexport async function renderSpotlight(roomid: RoomID, key: string, index: number) {\r\n\tlet imgHTML = '';\r\n\tconst {image, description} = spotlights[roomid][key][index];\r\n\r\n\tif (image) {\r\n\t\tif (Array.isArray(image)) {\r\n\t\t\timgHTML = `<td><img src=\"${image[0]}\" width=\"${image[1]}\" height=\"${image[2]}\" style=\"vertical-align:middle;\"></td>`;\r\n\t\t} else {\r\n\t\t\t// legacy format\r\n\t\t\ttry {\r\n\t\t\t\tconst [width, height] = await Chat.fitImage(image, 150, 300);\r\n\t\t\t\timgHTML = `<td><img src=\"${image}\" width=\"${width}\" height=\"${height}\" style=\"vertical-align:middle;\"></td>`;\r\n\t\t\t\tspotlights[roomid][key][index].image = [image, width, height];\r\n\t\t\t} catch {}\r\n\t\t}\r\n\t}\r\n\r\n\treturn `<table style=\"text-align:center;margin:auto\"><tr><td style=\"padding-right:10px;\">${Chat.formatText(description, true)}</td>${imgHTML}</tr></table>`;\r\n}\r\n\r\nexport const destroy = () => clearTimeout(timeout);\r\n\r\nexport const pages: Chat.PageTable = {\r\n\tasync spotlights(query, user, connection) {\r\n\t\tthis.title = 'Daily Spotlights';\r\n\t\tconst room = this.requireRoom();\r\n\t\tquery.shift(); // roomid\r\n\t\tconst sortType = toID(query.shift());\r\n\t\tif (sortType && !['time', 'alphabet'].includes(sortType)) {\r\n\t\t\treturn this.errorReply(`Invalid sorting type '${sortType}' - must be either 'time', 'alphabet', or not provided.`);\r\n\t\t}\r\n\r\n\t\tlet buf = `<div class=\"pad ladder\">`;\r\n\t\tbuf += `<div class=\"pad\">`;\r\n\t\tbuf += `<button style=\"float:right;\" class=\"button\" name=\"send\" value=\"/join view-spotlights-${room.roomid}${sortType ? '-' + sortType : ''}\">`;\r\n\t\tbuf += `<i class=\"fa fa-refresh\"></i> Refresh</button>`;\r\n\t\tbuf += `<h2>Daily Spotlights</h2>`;\r\n\t\t// for posterity, all these switches are futureproofing for more sort types\r\n\t\tif (sortType) {\r\n\t\t\tlet title = '';\r\n\t\t\tswitch (sortType) {\r\n\t\t\tcase 'time':\r\n\t\t\t\ttitle = 'latest time updated';\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\ttitle = 'alphabetical';\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tbuf += `(sorted by ${title})<br />`;\r\n\t\t}\r\n\t\tif (!spotlights[room.roomid]) {\r\n\t\t\tbuf += `<p>This room has no daily spotlights.</p></div>`;\r\n\t\t} else {\r\n\t\t\tconst sortedKeys = Utils.sortBy(Object.keys(spotlights[room.roomid]), key => {\r\n\t\t\t\tswitch (sortType) {\r\n\t\t\t\tcase 'time': {\r\n\t\t\t\t\t// find most recently added/updated spotlight in that key, sort all by that\r\n\t\t\t\t\tconst sortedSpotlights = Utils.sortBy(spotlights[room.roomid][key].slice(), k => -k.time);\r\n\t\t\t\t\treturn -sortedSpotlights[0].time;\r\n\t\t\t\t}\r\n\t\t\t\t// sort alphabetically by key otherwise\r\n\t\t\t\tdefault:\r\n\t\t\t\t\treturn key;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\tfor (const key of sortedKeys) {\r\n\t\t\t\tbuf += `<table style=\"margin-bottom:30px;\"><th colspan=\"2\"><h3>${key}:</h3></th>`;\r\n\t\t\t\tconst keys = Utils.sortBy(spotlights[room.roomid][key].slice(), spotlight => {\r\n\t\t\t\t\tswitch (sortType) {\r\n\t\t\t\t\tcase 'time':\r\n\t\t\t\t\t\treturn -spotlight.time;\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\treturn spotlight.description;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\tfor (const [i] of keys.entries()) {\r\n\t\t\t\t\tconst html = await renderSpotlight(room.roomid, key, i);\r\n\t\t\t\t\tbuf += `<tr><tdLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAwB;AAExB,MAAM,MAAM,KAAK,KAAK,KAAK;AAC3B,MAAM,iBAAiB;AACvB,MAAM,eAAe;AAWd,IAAI,aAEP,CAAC;AAEL,IAAI;AACH,eAAa,KAAK,UAAM,eAAG,cAAc,EAAE,iBAAiB,KAAK,IAAI;AACr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D,eAAe;AAAA,IACpG;AAEA,UAAM,SAAS,WAAW,KAAK,MAAM,EAAE,GAAG,EAAE,MAAM;AAClD,UAAM,SAAS,WAAW,KAAK,MAAM,EAAE,GAAG,EAAE,MAAM;AAClD,eAAW,KAAK,MAAM,EAAE,GAAG,EAAE,MAAM,IAAI;AACvC,eAAW,KAAK,MAAM,EAAE,GAAG,EAAE,MAAM,IAAI;AAEvC,mBAAe;AAEf,SAAK,OAAO,oBAAoB,KAAK,GAAG,eAAe,QAAQ;AAC/D,SAAK,iBAAiB,GAAG,KAAK,wCAAwC,yBAAyB,cAAc,SAAS;AACtH,SAAK,eAAe,cAAc,KAAK,UAAU,IAAI;AAAA,EACtD;AAAA,EACA,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,cAAc;AAAA,EACd,MAAM,SAAS,QAAQ,MAAM,MAAM,YAAY,KAAK;AACnD,WAAO,KAAK,YAAY;AACxB,QAAI,CAAC,KAAK;AAAS,aAAO,KAAK,WAAW,iDAAiD;AAC3F,QAAI,KAAK,aAAa;AACtB,QAAI,IAAI,SAAS,IAAI,KAALine truncated
"names": []
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/datasearch.ts"],
"sourcesContent": ["/**\r\n * Data searching commands.\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * Commands for advanced searching for pokemon, moves, items and learnsets.\r\n * These commands run on a child process by default.\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {ProcessManager, Utils} from '../../lib';\r\nimport {TeamValidator} from '../../sim/team-validator';\r\nimport {Chat} from '../chat';\r\n\r\ninterface DexOrGroup {\r\n\tabilities: {[k: string]: boolean};\r\n\ttiers: {[k: string]: boolean};\r\n\tdoublesTiers: {[k: string]: boolean};\r\n\tcolors: {[k: string]: boolean};\r\n\t'egg groups': {[k: string]: boolean};\r\n\tformes: {[k: string]: boolean};\r\n\tgens: {[k: string]: boolean};\r\n\tmoves: {[k: string]: boolean};\r\n\ttypes: {[k: string]: boolean};\r\n\tresists: {[k: string]: boolean};\r\n\tweak: {[k: string]: boolean};\r\n\tstats: {[k: string]: {[k in Direction]: number}};\r\n\tskip: boolean;\r\n}\r\n\r\ninterface MoveOrGroup {\r\n\ttypes: {[k: string]: boolean};\r\n\tcategories: {[k: string]: boolean};\r\n\tcontestTypes: {[k: string]: boolean};\r\n\tflags: {[k: string]: boolean};\r\n\tgens: {[k: string]: boolean};\r\n\tother: {[k: string]: boolean};\r\n\tmon: {[k: string]: boolean};\r\n\tproperty: {[k: string]: {[k in Direction]: number}};\r\n\tboost: {[k: string]: boolean};\r\n\tlower: {[k: string]: boolean};\r\n\tzboost: {[k: string]: boolean};\r\n\tstatus: {[k: string]: boolean};\r\n\tvolatileStatus: {[k: string]: boolean};\r\n\ttargets: {[k: string]: boolean};\r\n\tskip: boolean;\r\n\tmultihit: boolean;\r\n}\r\n\r\ntype Direction = 'less' | 'greater' | 'equal';\r\n\r\nconst MAX_PROCESSES = 1;\r\nconst RESULTS_MAX_LENGTH = 10;\r\nconst MAX_RANDOM_RESULTS = 30;\r\nconst dexesHelp = Object.keys((global.Dex?.dexes || {})).filter(x => x !== 'sourceMaps').join('</code>, <code>');\r\n\r\nfunction escapeHTML(str?: string) {\r\n\tif (!str) return '';\r\n\treturn ('' + str)\r\n\t\t.replace(/&/g, '&amp;')\r\n\t\t.replace(/</g, '&lt;')\r\n\t\t.replace(/>/g, '&gt;')\r\n\t\t.replace(/\"/g, '&quot;')\r\n\t\t.replace(/'/g, '&apos;')\r\n\t\t.replace(/\\//g, '&#x2f;');\r\n}\r\n\r\nfunction toListString(arr: string[]) {\r\n\tif (!arr.length) return '';\r\n\tif (arr.length === 1) return arr[0];\r\n\tif (arr.length === 2) return `${arr[0]} and ${arr[1]}`;\r\n\treturn `${arr.slice(0, -1).join(\", \")}, and ${arr.slice(-1)[0]}`;\r\n}\r\n\r\nfunction checkCanAll(room: Room | null) {\r\n\tif (!room) return false; // no, no good reason for using `all` in pms\r\n\tconst {isPersonal, isHelp} = room.settings;\r\n\t// allowed if it's a groupchat\r\n\treturn !room.battle && !!isPersonal && !isHelp;\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tds: 'dexsearch',\r\n\tds1: 'dexsearch',\r\n\tds2: 'dexsearch',\r\n\tds3: 'dexsearch',\r\n\tds4: 'dexsearch',\r\n\tds5: 'dexsearch',\r\n\tds6: 'dexsearch',\r\n\tds7: 'dexsearch',\r\n\tds8: 'dexsearch',\r\n\tdsearch: 'dexsearch',\r\n\tnds: 'dexsearch',\r\n\tasync dexsearch(target, room, user, connection, cmd, message) {\r\n\t\tthis.checkBroadcast();\r\n\t\tif (!target) return this.parse('/help dexsearch');\r\n\t\tif (target.length > 300) return this.errorReply('Dexsearch queries may not be longer than 300 characters.');\r\n\t\tconst targetGen = parseInt(cmd[cmd.length - 1]);\r\n\t\tif (targetGen) target += `, mod=gen${targetGen}`;\r\n\t\tconst split = target.split(',').map(term => term.trim());\r\n\t\tconst index = split.findIndex(x => /^max\\s*gen/i.test(x));\r\n\t\tif (index >= 0) {\r\n\t\t\tconst genNum = parseInt(/\\d*$/.exec(split[index])?.[0] || '');\r\n\t\t\tif (!isNaN(genNum) && !(genNum < 1 || genNum > Dex.gen)) {\r\n\t\t\t\tsplit[index] = `mod=gen${genNum}`;\r\n\t\t\t\ttarget = split.join(',');\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!target.includes('mod=')) {\r\n\t\t\tconst dex = this.extractFormat(room?.settings.defaultFormat || room?.battle?.format).dex;\r\n\t\t\tif (dex) target += `, mod=${dex.currentMod}`;\r\n\t\t}\r\n\t\tif (cmd === 'nds') target += ', natdex';\r\n\t\tconst response = await runSearch({\r\n\t\t\ttarget,\r\n\t\t\tcmd: 'dexsearch',\r\n\t\t\tcanAll: !this.broadcastMessage || checkCanAll(room),\r\n\t\t\tmessage: (this.broadcastMessage ? \"\" : message),\r\n\t\t});\r\n\t\tif (!response.error && !this.runBroadcast()) return;\r\n\t\tif (response.error) {\r\n\t\t\tthrow new Chat.ErrorMessage(response.error);\r\n\t\t} else if (response.reply) {\r\n\t\t\tthis.sendReplyBox(response.reply);\r\n\t\t} else if (response.dt) {\r\n\t\t\t(Chat.commands.data as Chat.ChatHandler).call(\r\n\t\t\t\tthis, response.dt, room, user, connection, 'dt', this.broadcastMessage ? \"\" : message\r\n\t\t\t);\r\n\t\t}\r\n\t},\r\n\tdexsearchhelp() {\r\n\t\tthis.sendReply(\r\n\t\t\t`|html| <details class=\"readmore\"><summary><code>/dexsearch [parameter], [parameter], [parameter], ...</code>: searches for Pok\\u00e9mon that fulfill the selected criteria<br/>` +\r\n\t\t\t`Search categories are: type, tier, color, moves, ability, gen, resists, weakLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,iBAAoC;AACpC,4BAA4B;AAC5B,kBAAmB;AAZnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmDA,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,YAAY,OAAO,KAAM,OAAO,KAAK,SAAS,CAAC,CAAE,EAAE,OAAO,OAAK,MAAM,YAAY,EAAE,KAAK,iBAAiB;AAE/G,SAAS,WAAW,KAAc;AACjC,MAAI,CAAC;AAAK,WAAO;AACjB,UAAQ,KAAK,KACX,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,OAAO,QAAQ;AAC1B;AAEA,SAAS,aAAa,KAAe;AACpC,MAAI,CAAC,IAAI;AAAQ,WAAO;AACxB,MAAI,IAAI,WAAW;AAAG,WAAO,IAAI,CAAC;AAClC,MAAI,IAAI,WAAW;AAAG,WAAO,GAAG,IAAI,CAAC,SAAS,IAAI,C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O,MAAM,GAAG,GAAG;AAC5B,UAAM,YAAY,SAASA,KAAIA,KAAI,SAAS,CAAC,CAAC;AAC9C,QAAI;AAAW,gBAAU,YAAY;AACrC,UAAM,QAAQ,OAAO,MAAM,GAAG,EAAE,IAAI,UAAQ,KAAK,KAAK,CAAC;Line truncated
"names": ["cmd", "stat", "format"]
}
+692
View File
@@ -0,0 +1,692 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var friends_exports = {};
__export(friends_exports, {
Friends: () => Friends,
commands: () => commands,
handlers: () => handlers,
loginfilter: () => loginfilter,
pages: () => pages
});
module.exports = __toCommonJS(friends_exports);
var import_utils = require("../../lib/utils");
var import_friends = require("../friends");
const STATUS_COLORS = {
idle: "#ff7000",
online: "#009900",
busy: "#cc3838"
};
const STATUS_TITLES = {
online: "Online",
idle: "Idle",
busy: "Busy",
offline: "Offline"
};
const LOGIN_NOTIFY_THROTTLE = 15 * 60 * 1e3;
const Friends = new class {
async notifyPending(user) {
if (user.settings.blockFriendRequests)
return;
const friendRequests = await Chat.Friends.getRequests(user);
const pendingCount = friendRequests.received.size;
if (pendingCount < 1)
return;
if (pendingCount === 1) {
const sender = [...friendRequests.received][0];
const senderName = Users.getExact(sender)?.name || sender;
let buf = import_utils.Utils.html`/uhtml sent,<button class="button" name="send" value="/friends accept ${sender}">Accept</button> | `;
buf += import_utils.Utils.html`<button class="button" name="send" value="/friends reject ${sender}">Deny</button><br /> `;
buf += `<small>(You can also stop this user from sending you friend requests with <code>/ignore</code>)</small>`;
(0, import_friends.sendPM)(import_utils.Utils.html`/raw <span class="username">${senderName}</span> sent you a friend request!`, user.id);
(0, import_friends.sendPM)(buf, user.id);
(0, import_friends.sendPM)(
`/raw <small>Note: If this request is accepted, your friend will be notified when you come online, and you will be notified when they do, unless you opt out of receiving them.</small>`,
user.id
);
} else {
(0, import_friends.sendPM)(`/nonotify You have ${pendingCount} friend requests pending!`, user.id);
(0, import_friends.sendPM)(`/raw <button class="button" name="send" value="/j view-friends-received">View</button></div>`, user.id);
}
}
async notifyConnection(user) {
const connected = await Chat.Friends.getLastLogin(user.id);
if (connected && Date.now() - connected < LOGIN_NOTIFY_THROTTLE) {
return;
}
const friends = await Chat.Friends.getFriends(user.id);
const message = `/nonotify Your friend <username class="username">${import_utils.Utils.escapeHTML(user.name)}</username> has just connected!`;
for (const f of friends) {
const curUser = Users.getExact(f.friend);
if (curUser?.settings.allowFriendNotifications) {
curUser.send(`|pm|&|${curUser.getIdentity()}|${message}`);
}
}
}
async visualizeList(userid) {
const friends = await Chat.Friends.getFriends(userid);
const categorized = {
online: [],
idle: [],
busy: [],
offline: []
};
const loginTimes = {};
for (const { friend: friendID, last_login, allowing_login: hideLogin } of [...friends].sort()) {
const friend = Users.getExact(friendID);
if (friend?.connected) {
categorized[friend.statusType].push(friend.id);
} else {
categorized.offline.push(friendID);
if (!hideLogin) {
loginTimes[toID(friendID)] = last_login;
}
}
}
const sorted = Object.keys(categorized).filter((item) => categorized[item].length > 0).map((item) => `${STATUS_TITLES[item]} (${categorized[item].length})`);
let buf = `<h3>Your friends: <small> `;
if (sorted.length > 0) {
buf += `Total (${friends.length}) | ${sorted.join(" | ")}`;
} else {
buf += `</h3><em>you have no friends added on Showdown lol</em><br /><br /><br />`;
buf += `<strong>To add a friend, use </strong><code>/friend add [username]</code>.<br /><br />`;
return buf;
}
buf += `</h3> `;
for (const key in categorized) {
const friendArray = categorized[key].sort();
if (friendArray.length === 0)
continue;
buf += `<h4>${STATUS_TITLES[key]} (${friendArray.length})</h4>`;
for (const friend of friendArray) {
const friendID = toID(friend);
buf += `<div class="pad"><div>`;
buf += this.displayFriend(friendID, loginTimes[friendID]);
buf += `</div></div>`;
}
}
return buf;
}
// much more info redacted
async visualizePublicList(userid) {
const friends = (await Chat.Friends.getFriends(userid)).map((f) => f.friend);
let buf = `<h3>${userid}'s friends:</h3><hr />`;
if (!friends.length) {
buf += `None.`;
return buf;
}
for (const friend of friends) {
buf += `- <username>${friend}</username><br />`;
}
return buf;
}
displayFriend(userid, login) {
const user = Users.getExact(userid);
const name = import_utils.Utils.escapeHTML(user ? user.name : userid);
const statusType = user?.connected ? `<strong style="color:${STATUS_COLORS[user.statusType]}">\u25C9 ${STATUS_TITLES[user.statusType]}</strong>` : "\u25CC Offline";
let buf = user ? `<span class="username"> <username>${name}</username></span><span><small> (${statusType})</small></span>` : import_utils.Utils.html`<i>${name}</i> <small>(${statusType})</small>`;
buf += `<br />`;
const curUser = Users.get(userid);
if (user) {
if (user.userMessage)
buf += import_utils.Utils.html`Status: <i>${user.userMessage}</i><br />`;
} else if (curUser && curUser.id !== userid) {
buf += `<small>On an alternate account</small><br />`;
}
if (login && typeof login === "number" && !user?.connected) {
const time = Chat.toTimestamp(new Date(Number(login)), { human: true });
buf += `Last seen: ${time.split(" ").reverse().join(", on ")}`;
buf += ` (${Chat.toDurationString(Date.now() - login, { precision: 1 })} ago)`;
} else if (typeof login === "string") {
buf += `${login}`;
}
buf = `<div class="infobox">${buf}</div>`;
return toLink(buf);
}
checkCanUse(context) {
const user = context.user;
if (!user.autoconfirmed) {
throw new Chat.ErrorMessage(context.tr`You must be autoconfirmed to use the friends feature.`);
}
if (user.locked || user.namelocked || user.semilocked || user.permalocked) {
throw new Chat.ErrorMessage(`You are locked, and so cannot use the friends feature.`);
}
if (!Config.usesqlitefriends || !Config.usesqlite) {
throw new Chat.ErrorMessage(`The friends list feature is currently disabled.`);
}
if (!Users.globalAuth.atLeast(user, Config.usesqlitefriends)) {
throw new Chat.ErrorMessage(`You are currently unable to use the friends feature.`);
}
}
request(user, receiver) {
return Chat.Friends.request(user, receiver);
}
removeFriend(userid, friendID) {
return Chat.Friends.removeFriend(userid, friendID);
}
approveRequest(receiverID, senderID) {
return Chat.Friends.approveRequest(receiverID, senderID);
}
removeRequest(receiverID, senderID) {
return Chat.Friends.removeRequest(receiverID, senderID);
}
updateSpectatorLists(user) {
if (!user.friends)
return;
for (const id of user.friends) {
const curUser = Users.getExact(id);
if (curUser) {
for (const conn of curUser.connections) {
if (conn.openPages?.has("friends-spectate")) {
void Chat.parse("/friends view spectate", null, curUser, conn);
}
}
}
}
}
}();
function toLink(buf) {
return buf.replace(/<a roomid="/g, `<a target="replace" href="/`);
}
function headerButtons(type, user) {
const buf = [];
const icons = {
sent: '<i class="fa fa-paper-plane"></i>',
received: '<i class="fa fa-get-pocket"></i>',
all: '<i class="fa fa-users"></i>',
help: '<i class="fa fa-question-circle"></i>',
settings: '<i class="fa fa-cog"></i>',
spectate: '<i class="fa fa-binoculars"></i>'
};
const titles = {
all: "All Friends",
spectate: "Spectate",
sent: "Sent",
received: "Received",
help: "Help",
settings: "Settings"
};
for (const page in titles) {
const title = titles[page];
const icon = icons[page];
if (page === type) {
buf.push(`${icon} <strong>${user.tr(title)}</strong>`);
} else {
buf.push(`${icon} <a roomid="view-friends-${page}">${user.tr(title)}</a>`);
}
}
const refresh = `<button class="button" name="send" value="/j view-friends${type?.trim() ? `-${type}` : ""}" style="float: right"> <i class="fa fa-refresh"></i> ${user.tr("Refresh")}</button>`;
return `<div style="line-height:25px">${buf.join(" / ")}${refresh}</div><hr />`;
}
const commands = {
unfriend(target) {
return this.parse(`/friend remove ${target}`);
},
friend: "friends",
friendslist: "friends",
friends: {
""(target) {
if (toID(target)) {
return this.parse(`/friend add ${target}`);
}
return this.parse(`/friends list`);
},
viewlist(target, room, user) {
Friends.checkCanUse(this);
target = toID(target);
if (!target)
return this.errorReply(`Specify a user.`);
if (target === user.id)
return this.parse(`/friends list`);
return this.parse(`/j view-friends-viewuser-${target}`);
},
request: "add",
async add(target, room, user, connection) {
Friends.checkCanUse(this);
target = toID(target);
if (target.length > 18) {
return this.errorReply(this.tr`That name is too long - choose a valid name.`);
}
if (!target)
return this.parse("/help friends");
await Friends.request(user, target);
this.refreshPage("friends-sent");
return this.sendReply(`You sent a friend request to '${target}'.`);
},
unfriend: "remove",
async remove(target, room, user) {
Friends.checkCanUse(this);
target = toID(target);
if (!target)
return this.parse("/help friends");
await Friends.removeFriend(user.id, target);
this.sendReply(`Removed friend '${target}'.`);
await Chat.Friends.updateUserCache(user);
this.refreshPage("friends-all");
const targetUser = Users.get(target);
if (targetUser)
await Chat.Friends.updateUserCache(targetUser);
},
view(target) {
return this.parse(`/join view-friends-${target}`);
},
list() {
return this.parse(`/join view-friends-all`);
},
async accept(target, room, user, connection) {
Friends.checkCanUse(this);
target = toID(target);
if (user.settings.blockFriendRequests) {
return this.errorReply(this.tr`You are currently blocking friend requests, and so cannot accept your own.`);
}
if (!target)
return this.parse("/help friends");
await Friends.approveRequest(user.id, target);
const targetUser = Users.get(target);
(0, import_friends.sendPM)(`You accepted a friend request from "${target}".`, user.id);
this.refreshPage("friends-received");
if (targetUser) {
(0, import_friends.sendPM)(`/text ${user.name} accepted your friend request!`, targetUser.id);
(0, import_friends.sendPM)(`/uhtmlchange sent-${targetUser.id},`, targetUser.id);
(0, import_friends.sendPM)(`/uhtmlchange undo-${targetUser.id},`, targetUser.id);
}
await Chat.Friends.updateUserCache(user);
if (targetUser)
await Chat.Friends.updateUserCache(targetUser);
},
deny: "reject",
async reject(target, room, user, connection) {
Friends.checkCanUse(this);
target = toID(target);
if (!target)
return this.parse("/help friends");
const res = await Friends.removeRequest(user.id, target);
if (!res.changes) {
return this.errorReply(`You do not have a friend request pending from '${target}'.`);
}
this.refreshPage("friends-received");
return (0, import_friends.sendPM)(`You denied a friend request from '${target}'.`, user.id);
},
toggle(target, room, user, connection) {
Friends.checkCanUse(this);
const setting = user.settings.blockFriendRequests;
target = target.trim();
if (this.meansYes(target)) {
if (!setting)
return this.errorReply(this.tr`You already are allowing friend requests.`);
user.settings.blockFriendRequests = false;
this.sendReply(this.tr`You are now allowing friend requests.`);
} else if (this.meansNo(target)) {
if (setting)
return this.errorReply(this.tr`You already are blocking incoming friend requests.`);
user.settings.blockFriendRequests = true;
this.sendReply(this.tr`You are now blocking incoming friend requests.`);
} else {
if (target)
this.errorReply(this.tr`Unrecognized setting.`);
this.sendReply(
this.tr(setting ? `You are currently blocking friend requests.` : `You are not blocking friend requests.`)
);
}
this.refreshPage("friends-settings");
user.update();
},
async undorequest(target, room, user, connection) {
Friends.checkCanUse(this);
target = toID(target);
await Friends.removeRequest(target, user.id);
this.refreshPage("friends-sent");
return (0, import_friends.sendPM)(`You removed your friend request to '${target}'.`, user.id);
},
hidenotifs: "viewnotifications",
hidenotifications: "viewnotifications",
viewnotifs: "viewnotifications",
viewnotifications(target, room, user, connection, cmd) {
const setting = user.settings.allowFriendNotifications;
target = target.trim();
if (!cmd.includes("hide") || target && this.meansYes(target)) {
if (setting)
return this.errorReply(this.tr(`You are already allowing friend notifications.`));
user.settings.allowFriendNotifications = true;
this.sendReply(this.tr(`You will now receive friend notifications.`));
} else if (cmd.includes("hide") || target && this.meansNo(target)) {
if (!setting)
return this.errorReply(this.tr`You are already not receiving friend notifications.`);
user.settings.allowFriendNotifications = false;
this.sendReply(this.tr`You will not receive friend notifications.`);
} else {
if (target)
this.errorReply(this.tr`Unrecognized setting.`);
this.sendReply(
this.tr(setting ? `You are currently allowing friend notifications.` : `Your friend notifications are disabled.`)
);
}
this.refreshPage("friends-settings");
user.update();
},
hidelogins: "togglelogins",
showlogins: "togglelogins",
async togglelogins(target, room, user, connection, cmd) {
Friends.checkCanUse(this);
const setting = user.settings.hideLogins;
if (cmd.includes("hide")) {
if (setting)
return this.errorReply(this.tr`You are already hiding your logins from friends.`);
user.settings.hideLogins = true;
await Chat.Friends.hideLoginData(user.id);
this.sendReply(`You are now hiding your login times from your friends.`);
} else if (cmd.includes("show")) {
if (!setting)
return this.errorReply(this.tr`You are already allowing friends to see your login times.`);
user.settings.hideLogins = false;
await Chat.Friends.allowLoginData(user.id);
this.sendReply(`You are now allowing your friends to see your login times.`);
} else {
return this.errorReply(`Invalid setting.`);
}
this.refreshPage("friends-settings");
user.update();
},
async listdisplay(target, room, user, connection) {
Friends.checkCanUse(this);
target = toID(target);
const { public_list: setting } = await Chat.Friends.getSettings(user.id);
if (this.meansYes(target)) {
if (setting) {
return this.errorReply(this.tr`You are already allowing other people to view your friends list.`);
}
await Chat.Friends.setHideList(user.id, true);
this.refreshPage("friends-settings");
return this.sendReply(this.tr`You are now allowing other people to view your friends list.`);
} else if (this.meansNo(target)) {
if (!setting) {
return this.errorReply(this.tr`You are already hiding your friends list.`);
}
await Chat.Friends.setHideList(user.id, false);
this.refreshPage("friends-settings");
return this.sendReply(this.tr`You are now hiding your friends list.`);
}
this.sendReply(`You are currently ${setting ? "displaying" : "hiding"} your friends list.`);
},
invalidatecache(target, room, user) {
this.canUseConsole();
for (const curUser of Users.users.values()) {
void Chat.Friends.updateUserCache(curUser);
}
Rooms.global.notifyRooms(
["staff", "development"],
`|c|${user.getIdentity()}|/log ${user.name} used /friends invalidatecache`
);
this.sendReply(`You invalidated each entry in the friends database cache.`);
},
sharebattles(target, room, user) {
Friends.checkCanUse(this);
target = toID(target);
if (this.meansYes(target)) {
if (user.settings.displayBattlesToFriends) {
return this.errorReply(this.tr`You are already sharing your battles with friends.`);
}
user.settings.displayBattlesToFriends = true;
this.sendReply(`You are now allowing your friends to see your ongoing battles.`);
} else if (this.meansNo(target)) {
if (!user.settings.displayBattlesToFriends) {
return this.errorReply(this.tr`You are already not sharing your battles with friends.`);
}
user.settings.displayBattlesToFriends = false;
this.sendReply(`You are now hiding your ongoing battles from your friends.`);
} else {
if (!target)
return this.parse("/help friends sharebattles");
return this.errorReply(`Invalid setting '${target}'. Provide 'on' or 'off'.`);
}
user.update();
this.refreshPage("friends-settings");
},
sharebattleshelp: [
`/friends sharebattles [on|off] - Allow or disallow your friends from seeing your ongoing battles.`
]
},
friendshelp() {
this.runBroadcast();
if (this.broadcasting) {
return this.sendReplyBox([
`<code>/friend list</code> - View current friends.`,
`<code>/friend add [name]</code> OR <code>/friend [name]</code> - Send a friend request to [name], if you don't have them added.`,
`<code>/friend remove [username]</code> OR <code>/unfriend [username]</code> - Unfriend the user.`,
`<details class="readmore"><summary>More commands...</summary>`,
`<code>/friend accept [username]</code> - Accepts the friend request from [username], if it exists.`,
`<code>/friend reject [username]</code> - Rejects the friend request from [username], if it exists.`,
`<code>/friend toggle [off/on]</code> - Enable or disable receiving of friend requests.`,
`<code>/friend hidenotifications</code> OR <code>hidenotifs</code> - Opts out of receiving friend notifications.`,
`<code>/friend viewnotifications</code> OR <code>viewnotifs</code> - Opts into view friend notifications.`,
`<code>/friend listdisplay [on/off]</code> - Opts [in/out] of letting others view your friends list.`,
`<code>/friend viewlist [user]</code> - View the given [user]'s friend list, if they're allowing others to see.`,
`<code>/friends sharebattles [on|off]</code> - Allow or disallow your friends from seeing your ongoing battles.</details>`
].join("<br />"));
}
return this.parse("/join view-friends-help");
}
};
const pages = {
async friends(args, user) {
if (!user.named)
return Rooms.RETRY_AFTER_LOGIN;
Friends.checkCanUse(this);
const type = args.shift();
let buf = '<div class="pad">';
switch (toID(type)) {
case "outgoing":
case "sent":
this.title = `[Friends] Sent`;
buf += headerButtons("sent", user);
if (user.settings.blockFriendRequests) {
buf += `<h3>${this.tr(`You are currently blocking friend requests`)}.</h3>`;
}
const { sent } = await Chat.Friends.getRequests(user);
if (sent.size < 1) {
buf += `<strong>You have no outgoing friend requests pending.</strong><br />`;
buf += `<br />To add a friend, use <code>/friend add [username]</code>.`;
buf += `</div>`;
return toLink(buf);
}
buf += `<h3>You have ${Chat.count(sent.size, "friend requests")} pending${sent.size === import_friends.MAX_REQUESTS ? ` (maximum reached)` : ""}.</h3>`;
for (const request of sent) {
buf += `<br /><div class="infobox">`;
buf += `<strong>${request}</strong>`;
buf += ` <button class="button" name="send" value="/friends undorequest ${request}">`;
buf += `<i class="fa fa-undo"></i> ${this.tr("Undo")}</button>`;
buf += `</div>`;
}
break;
case "received":
case "incoming":
this.title = `[Friends] Received`;
buf += headerButtons("received", user);
const { received } = await Chat.Friends.getRequests(user);
if (received.size < 1) {
buf += `<strong>You have no pending friend requests.</strong>`;
buf += `</div>`;
return toLink(buf);
}
buf += `<h3>You have ${received.size} pending friend requests.</h3>`;
for (const request of received) {
buf += `<br /><div class="infobox">`;
buf += `<strong>${request}</strong>`;
buf += ` <button class="button" name="send" value="/friends accept ${request}">${this.tr("Accept")}</button> |`;
buf += ` <button class="button" name="send" value="/friends reject ${request}">${this.tr("Deny")}</button>`;
buf += `</div>`;
}
break;
case "viewuser":
const target = toID(args.shift());
if (!target)
return this.errorReply(`Specify a user.`);
if (target === user.id) {
return this.errorReply(`Use /friends list to view your own list.`);
}
const { public_list: isAllowing } = await Chat.Friends.getSettings(target);
if (!isAllowing)
return this.errorReply(`${target}'s friends list is not public or they do not have one.`);
this.title = `[Friends List] ${target}`;
buf += await Friends.visualizePublicList(target);
break;
case "help":
this.title = `[Friends] Help`;
buf += headerButtons("help", user);
buf += `<h3>Help</h3>`;
buf += `<strong>/friend OR /friends OR /friendslist:</strong><br /><ul><li>`;
buf += [
`<code>/friend list</code> - View current friends.`,
`<code>/friend add [name]</code> OR <code>/friend [name]</code> - Send a friend request to [name], if you don't have them added.`,
`<code>/friend remove [username]</code> OR <code>/unfriend [username]</code> - Unfriend the user.`,
`<code>/friend accept [username]</code> - Accepts the friend request from [username], if it exists.`,
`<code>/friend reject [username]</code> - Rejects the friend request from [username], if it exists.`,
`<code>/friend toggle [off/on]</code> - Enable or disable receiving of friend requests.`,
`<code>/friend hidenotifications</code> OR <code>hidenotifs</code> - Opts out of receiving friend notifications.`,
`<code>/friend viewnotifications</code> OR <code>viewnotifs</code> - Opts into view friend notifications.`,
`<code>/friend listdisplay [on/off]</code> - Opts [in/out] of letting others view your friends list.`,
`<code>/friend viewlist [user]</code> - View the given [user]'s friend list, if they're allowing others to see.`,
`<code>/friends sharebattles [on|off]</code> - Allow or disallow your friends from seeing your ongoing battles.`
].join("</li><li>");
buf += `</li></ul>`;
break;
case "settings":
this.title = `[Friends] Settings`;
buf += headerButtons("settings", user);
buf += `<h3>Friends Settings:</h3>`;
const settings = user.settings;
const { public_list, send_login_data } = await Chat.Friends.getSettings(user.id);
buf += `<strong>Notify me when my friends come online:</strong><br />`;
buf += `<button class="button${settings.allowFriendNotifications ? `` : ` disabled`}" name="send" `;
buf += `value="/friends hidenotifs">Disable</button> `;
buf += `<button class="button${settings.allowFriendNotifications ? ` disabled` : ``}" name="send" `;
buf += `value="/friends viewnotifs">Enable</button> <br /><br />`;
buf += `<strong>Receive friend requests:</strong><br />`;
buf += `<button class="button${settings.blockFriendRequests ? ` disabled` : ""}" name="send" `;
buf += `value="/friends toggle off">Disable</button> `;
buf += `<button class="button${settings.blockFriendRequests ? `` : ` disabled`}" name="send" `;
buf += `value="/friends toggle on">Enable</button> <br /><br />`;
buf += `<strong>Allow others to see your list:</strong><br />`;
buf += `<button class="button${public_list ? ` disabled` : ""}" name="send" `;
buf += `value="/friends listdisplay yes">Allow</button> `;
buf += `<button class="button${public_list ? `` : ` disabled`}" name="send" `;
buf += `value="/friends listdisplay no">Hide</button> <br /><br />`;
buf += `<strong>Allow others to see my login times</strong><br />`;
buf += `<button class="button${send_login_data ? ` disabled` : ""}" name="send" `;
buf += `value="/friends hidelogins">Disable</button> `;
buf += `<button class="button${send_login_data ? `` : " disabled"}" name="send" `;
buf += `value="/friends showlogins">Enable</button><br /><br />`;
buf += `<strong>Allow friends to see my hidden battles on the spectator list:</strong><br />`;
buf += `<button class="button${settings.displayBattlesToFriends ? `` : " disabled"}" name="send" `;
buf += `value="/friends sharebattles off">Disable</button> `;
buf += `<button class="button${settings.displayBattlesToFriends ? ` disabled` : ``}" name="send" `;
buf += `value="/friends sharebattles on">Enable</button> <br /><br />`;
buf += `<strong>Block PMs except from friends (and staff):</strong><br />`;
buf += `<button class="button${settings.blockPMs ? `` : " disabled"}" name="send" `;
buf += `value="/unblockpms&#10;/j view-friends-settings">Disable</button> `;
buf += `<button class="button${settings.blockPMs ? ` disabled` : ``}" name="send" `;
buf += `value="/blockpms friends&#10;/j view-friends-settings">Enable</button> <br /><br />`;
buf += `<strong>Block challenges except from friends (and staff):</strong><br />`;
buf += `<button class="button${settings.blockChallenges ? `` : " disabled"}" name="send" `;
buf += `value="/unblockchallenges&#10;/j view-friends-settings">Disable</button> `;
buf += `<button class="button${settings.blockChallenges ? ` disabled` : ``}" name="send" `;
buf += `value="/blockchallenges friends&#10;/j view-friends-settings">Enable</button> <br /><br />`;
break;
case "spectate":
this.title = `[Friends] Spectating`;
buf += headerButtons("spectate", user);
buf += `<h3>Spectate your friends:</h3>`;
const toggleMessage = user.settings.displayBattlesToFriends ? " disallow your friends from seeing your hidden battles" : " allow your friends to see your hidden battles";
buf += `<i><small>Use the <a roomid="view-friends-settings">settings page</a> to ${toggleMessage} on this page.</small></i><br />`;
buf += `<br />`;
if (!user.friends?.size) {
buf += `<h3>You have no friends to spectate.</h3>`;
break;
}
const friends = [];
for (const friendID of user.friends) {
const friend = Users.getExact(friendID);
if (!friend)
continue;
friends.push(friend);
}
if (!friends.length) {
buf += `<em>None of your friends are currently around to spectate.</em>`;
break;
}
const battles = [];
for (const friend of friends) {
const curBattles = [...friend.inRooms].filter((id) => {
const battle = Rooms.get(id)?.battle;
return battle && battle.playerTable[friend.id] && (!battle.roomid.endsWith("pw") || friend.settings.displayBattlesToFriends);
}).map((id) => [friend, id]);
if (!curBattles.length)
continue;
battles.push(...curBattles);
}
import_utils.Utils.sortBy(battles, ([, id]) => -Number(id.split("-")[2]));
if (!battles.length) {
buf += `<em>None of your friends are currently in a battle.</em>`;
} else {
buf += battles.map(([friend, battle]) => {
const room = Rooms.get(battle);
const format = Dex.formats.get(room.battle.format).name;
const rated = room.battle.rated ? `<small style="float:right">(Rated: ${room.battle.rated})</small>` : "";
const title = room.title.includes(friend.name) ? room.title.replace(friend.name, `<strong>${friend.name}</strong>`) : room.title + ` (with ${friend.name})`;
return `<a class="blocklink" href="/${room.roomid}"><small>[${format}]</small>${rated}<br /> ${title}</a>`;
}).join("<br />");
}
break;
default:
this.title = `[Friends] All Friends`;
buf += headerButtons("all", user);
buf += await Friends.visualizeList(user.id);
}
buf += `</div>`;
return toLink(buf);
}
};
const handlers = {
onBattleStart(user) {
return Friends.updateSpectatorLists(user);
},
onBattleLeave(user, room) {
return Friends.updateSpectatorLists(user);
},
onBattleEnd(battle, winner, players) {
for (const id of players) {
const user = Users.get(id);
if (!user)
continue;
Friends.updateSpectatorLists(user);
}
},
onDisconnect(user) {
void Chat.Friends.writeLogin(user.id);
}
};
const loginfilter = (user) => {
if (!Config.usesqlitefriends || !Users.globalAuth.atLeast(user, Config.usesqlitefriends)) {
return;
}
void Friends.notifyPending(user);
void Friends.notifyConnection(user);
void Chat.Friends.writeLogin(user.id);
void Chat.Friends.updateUserCache(user);
};
//# sourceMappingURL=friends.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/friends.ts"],
"sourcesContent": ["/**\r\n * Friends list plugin.\r\n * Allows for adding and removing friends, as well as seeing their activity.\r\n * Written by Mia.\r\n * @author mia-pi-git\r\n */\r\n\r\nimport {Utils} from '../../lib/utils';\r\nimport {MAX_REQUESTS, sendPM} from '../friends';\r\n\r\nconst STATUS_COLORS: {[k: string]: string} = {\r\n\tidle: '#ff7000',\r\n\tonline: '#009900',\r\n\tbusy: '#cc3838',\r\n};\r\n\r\nconst STATUS_TITLES: {[k: string]: string} = {\r\n\tonline: 'Online',\r\n\tidle: 'Idle',\r\n\tbusy: 'Busy',\r\n\toffline: 'Offline',\r\n};\r\n\r\n// once every 15 minutes\r\nconst LOGIN_NOTIFY_THROTTLE = 15 * 60 * 1000;\r\n\r\nexport const Friends = new class {\r\n\tasync notifyPending(user: User) {\r\n\t\tif (user.settings.blockFriendRequests) return;\r\n\t\tconst friendRequests = await Chat.Friends.getRequests(user);\r\n\t\tconst pendingCount = friendRequests.received.size;\r\n\t\tif (pendingCount < 1) return;\r\n\t\tif (pendingCount === 1) {\r\n\t\t\tconst sender = [...friendRequests.received][0];\r\n\t\t\tconst senderName = Users.getExact(sender)?.name || sender;\r\n\t\t\tlet buf = Utils.html`/uhtml sent,<button class=\"button\" name=\"send\" value=\"/friends accept ${sender}\">Accept</button> | `;\r\n\t\t\tbuf += Utils.html`<button class=\"button\" name=\"send\" value=\"/friends reject ${sender}\">Deny</button><br /> `;\r\n\t\t\tbuf += `<small>(You can also stop this user from sending you friend requests with <code>/ignore</code>)</small>`;\r\n\t\t\tsendPM(Utils.html`/raw <span class=\"username\">${senderName}</span> sent you a friend request!`, user.id);\r\n\t\t\tsendPM(buf, user.id);\r\n\t\t\tsendPM(\r\n\t\t\t\t`/raw <small>Note: If this request is accepted, your friend will be notified when you come online, ` +\r\n\t\t\t\t`and you will be notified when they do, unless you opt out of receiving them.</small>`,\r\n\t\t\t\tuser.id\r\n\t\t\t);\r\n\t\t} else {\r\n\t\t\tsendPM(`/nonotify You have ${pendingCount} friend requests pending!`, user.id);\r\n\t\t\tsendPM(`/raw <button class=\"button\" name=\"send\" value=\"/j view-friends-received\">View</button></div>`, user.id);\r\n\t\t}\r\n\t}\r\n\tasync notifyConnection(user: User) {\r\n\t\tconst connected = await Chat.Friends.getLastLogin(user.id);\r\n\t\tif (connected && (Date.now() - connected) < LOGIN_NOTIFY_THROTTLE) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tconst friends = await Chat.Friends.getFriends(user.id);\r\n\t\tconst message = `/nonotify Your friend <username class=\"username\">${Utils.escapeHTML(user.name)}</username> has just connected!`;\r\n\t\tfor (const f of friends) {\r\n\t\t\tconst curUser = Users.getExact(f.friend);\r\n\t\t\tif (curUser?.settings.allowFriendNotifications) {\r\n\t\t\t\tcurUser.send(`|pm|&|${curUser.getIdentity()}|${message}`);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tasync visualizeList(userid: ID) {\r\n\t\tconst friends = await Chat.Friends.getFriends(userid);\r\n\t\tconst categorized: {[k: string]: string[]} = {\r\n\t\t\tonline: [],\r\n\t\t\tidle: [],\r\n\t\t\tbusy: [],\r\n\t\t\toffline: [],\r\n\t\t};\r\n\t\tconst loginTimes: {[k: string]: number} = {};\r\n\t\tfor (const {friend: friendID, last_login, allowing_login: hideLogin} of [...friends].sort()) {\r\n\t\t\tconst friend = Users.getExact(friendID);\r\n\t\t\tif (friend?.connected) {\r\n\t\t\t\tcategorized[friend.statusType].push(friend.id);\r\n\t\t\t} else {\r\n\t\t\t\tcategorized.offline.push(friendID);\r\n\t\t\t\t// hidelogin - 1 to disable it being visible\r\n\t\t\t\tif (!hideLogin) {\r\n\t\t\t\t\tloginTimes[toID(friendID)] = last_login;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst sorted = Object.keys(categorized)\r\n\t\t\t.filter(item => categorized[item].length > 0)\r\n\t\t\t.map(item => `${STATUS_TITLES[item]} (${categorized[item].length})`);\r\n\r\n\t\tlet buf = `<h3>Your friends: <small> `;\r\n\t\tif (sorted.length > 0) {\r\n\t\t\tbuf += `Total (${friends.length}) | ${sorted.join(' | ')}`;\r\n\t\t} else {\r\n\t\t\tbuf += `</h3><em>you have no friends added on Showdown lol</em><br /><br /><br />`;\r\n\t\t\tbuf += `<strong>To add a friend, use </strong><code>/friend add [username]</code>.<br /><br />`;\r\n\t\t\treturn buf;\r\n\t\t}\r\n\t\tbuf += `</h3> `;\r\n\r\n\t\tfor (const key in categorized) {\r\n\t\t\tconst friendArray = categorized[key].sort();\r\n\t\t\tif (friendArray.length === 0) continue;\r\n\t\t\tbuf += `<h4>${STATUS_TITLES[key]} (${friendArray.length})</h4>`;\r\n\t\t\tfor (const friend of friendArray) {\r\n\t\t\t\tconst friendID = toID(friend);\r\n\t\t\t\tbuf += `<div class=\"pad\"><div>`;\r\n\t\t\t\tbuf += this.displayFriend(friendID, loginTimes[friendID]);\r\n\t\t\t\tbuf += `</div></div>`;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn buf;\r\n\t}\r\n\t// much more info redacted\r\n\tasync visualizePublicList(userid: ID) {\r\n\t\tconst friends: string[] = (await Chat.Friends.getFriends(userid) as any[]).map(f => f.friend);\r\n\t\tlet buf = `<h3>${userid}'s friends:</h3><hr />`;\r\n\t\tif (!friends.length) {\r\n\t\t\tbuf += `None.`;\r\n\t\t\treturn buf;Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,mBAAoB;AACpB,qBAAmC;AAEnC,MAAM,gBAAuC;AAAA,EAC5C,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,MAAM;AACP;AAEA,MAAM,gBAAuC;AAAA,EAC5C,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS;AACV;AAGA,MAAM,wBAAwB,KAAK,KAAK;AAEjC,MAAM,UAAU,IAAI,MAAM;AAAA,EAChC,MAAM,cAAc,MAAY;AAC/B,QAAI,KAAK,SAAS;AAAqB;AACvC,UAAM,iBAAiB,MAAM,KAAK,QAAQ,YAAY,IAAI;AAC1D,UAAM,eAAe,eAAe,SAAS;AAC7C,QAAI,eAAe;AAAG;AACtB,QAAI,iBAAiB,GAAG;AACvB,YAAM,SAAS,CAAC,GAAG,eAAe,QAAQ,EAAE,CAAC;AAC7C,YAAM,aAAa,MAAM,SAAS,MAAM,GAAG,QAAQ;AACnD,UAAI,MAAM,mBAAM,6EAA6E;AAC7F,aAAO,mBAAM,iEAAiE;AAC9E,aAAO;AACP,iCAAO,mBAAM,mCAAmC,gDAAgD,KAAK,EAAE;AACvG,iCAAO,KAAK,K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AAiC,IAAI,KAAK,KAAK,IAAI;AAC3D;AAEO,MAAM,WAA8B;AAAA,EAC1C,SAAS,QAAQ;AAChB,WAAO,KAAK,MAAM,kBAAkB,QAAQ;AAAA,EAC7C;AAAA,EACA,QAAQ;AAALine truncated
"names": []
}
+278
View File
@@ -0,0 +1,278 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var github_exports = {};
__export(github_exports, {
GitHub: () => GitHub,
commands: () => commands,
destroy: () => destroy,
gitData: () => gitData,
pages: () => pages
});
module.exports = __toCommonJS(github_exports);
var import_lib = require("../../lib");
const STAFF_REPOS = Config.staffrepos || [
"pokemon-showdown",
"pokemon-showdown-client",
"Pokemon-Showdown-Dex",
"pokemon-showdown-loginserver"
];
const COOLDOWN = 10 * 60 * 1e3;
const gitData = JSON.parse((0, import_lib.FS)("config/chat-plugins/github.json").readIfExistsSync() || "{}");
const GitHub = new class {
constructor() {
this.hook = null;
this.updates = /* @__PURE__ */ Object.create(null);
if (!Config.github)
return;
try {
this.hook = require("githubhook")({
logger: {
log: (line) => Monitor.debug(line),
error: (line) => Monitor.notice(line)
},
...Config.github
});
} catch (err) {
Monitor.crashlog(err, "GitHub hook");
}
this.listen();
}
listen() {
if (!this.hook)
return;
this.hook.listen();
this.hook.on("push", (repo, ref, result) => this.handlePush(repo, ref, result));
this.hook.on("pull_request", (repo, ref, result) => this.handlePull(repo, ref, result));
}
getRepoName(repo) {
switch (repo) {
case "pokemon-showdown":
return "server";
case "pokemon-showdown-client":
return "client";
case "Pokemon-Showdown-Dex":
return "dex";
default:
return repo.toLowerCase();
}
}
handlePush(repo, ref, result) {
const branch = /[^/]+$/.exec(ref)?.[0] || "";
if (branch !== "master")
return;
const messages = {
staff: [],
development: []
};
for (const commit of result.commits) {
const { message, url } = commit;
const [shortMessage] = message.split("\n\n");
const username = this.getUsername(commit.author.name);
const repoName = this.getRepoName(repo);
const id = commit.id.substring(0, 6);
messages.development.push(
import_lib.Utils.html`[<span style="color:#FF00FF">${repoName}</span>] <a href="${url}" style="color:#606060">${id}</a> ${shortMessage} <span style="color:#909090">(${username})</span>`
);
messages.staff.push(import_lib.Utils.html`[<span style="color:#FF00FF">${repoName}</span>] <a href="${url}">${shortMessage}</a> <span style="color:#909090">(${username})</span>`);
}
for (const k in messages) {
this.report(k, repo, messages[k]);
}
}
handlePull(repo, ref, result) {
if (this.isRateLimited(result.number))
return;
if (this.isGitbanned(result))
return;
const url = result.pull_request.html_url;
const action = this.isValidAction(result.action);
if (!action)
return;
const repoName = this.getRepoName(repo);
const userName = this.getUsername(result.sender.login);
const title = result.pull_request.title;
let buf = import_lib.Utils.html`[<span style="color:#FF00FF">${repoName}</span>] <span style="color:#909090">${userName}</span> `;
buf += import_lib.Utils.html`${action} <a href="${url}">PR#${result.number}</a>: ${title}`;
this.report("development", repo, buf);
}
report(roomid, repo, messages) {
if (!STAFF_REPOS.includes(repo) && roomid === "staff")
return;
if (Array.isArray(messages))
messages = messages.join("<br />");
Rooms.get(roomid)?.add(`|html|<div class="infobox">${messages}</div>`).update();
}
isGitbanned(result) {
if (!gitData.bans)
return false;
return gitData.bans[result.sender.login] || gitData.bans[result.pull_request.user.login];
}
isRateLimited(prNumber) {
if (this.updates[prNumber]) {
if (this.updates[prNumber] + COOLDOWN > Date.now())
return true;
this.updates[prNumber] = Date.now();
return false;
}
this.updates[prNumber] = Date.now();
return false;
}
isValidAction(action) {
if (action === "synchronize")
return "updated";
if (action === "review_requested") {
return "requested a review for";
} else if (action === "review_request_removed") {
return "removed a review request for";
}
if (["ready_for_review", "labeled", "unlabeled", "converted_to_draft"].includes(action)) {
return null;
}
return action;
}
getUsername(name) {
return gitData.usernames?.[toID(name)] || name;
}
save() {
(0, import_lib.FS)("config/chat-plugins/github.json").writeUpdate(() => JSON.stringify(gitData));
}
}();
const commands = {
gh: "github",
github: {
""() {
return this.parse("/help github");
},
ban(target, room, user) {
room = this.requireRoom("development");
this.checkCan("mute", null, room);
const [username, reason] = import_lib.Utils.splitFirst(target, ",").map((u) => u.trim());
if (!toID(target))
return this.parse(`/help github`);
if (!toID(username))
return this.errorReply("Provide a username.");
if (room.auth.has(toID(GitHub.getUsername(username)))) {
return this.errorReply("That user is Dev roomauth. If you need to do this, demote them and try again.");
}
if (!gitData.bans)
gitData.bans = {};
if (gitData.bans[toID(username)]) {
return this.errorReply(`${username} is already gitbanned.`);
}
gitData.bans[toID(username)] = reason || " ";
GitHub.save();
this.privateModAction(`${user.name} banned the GitHub user ${username} from having their GitHub actions reported to this server.`);
this.modlog("GITHUB BAN", username, reason);
},
unban(target, room, user) {
room = this.requireRoom("development");
this.checkCan("mute", null, room);
target = toID(target);
if (!target)
return this.parse("/help github");
if (!gitData.bans?.[target])
return this.errorReply("That user is not gitbanned.");
delete gitData.bans[target];
if (!Object.keys(gitData.bans).length)
delete gitData.bans;
GitHub.save();
this.privateModAction(`${user.name} allowed the GitHub user ${target} to have their GitHub actions reported to this server.`);
this.modlog("GITHUB UNBAN", target);
},
bans() {
const room = this.requireRoom("development");
this.checkCan("mute", null, room);
return this.parse("/j view-github-bans");
},
setname: "addusername",
addusername(target, room, user) {
room = this.requireRoom("development");
this.checkCan("mute", null, room);
const [gitName, username] = import_lib.Utils.splitFirst(target, ",").map((u) => u.trim());
if (!toID(gitName) || !toID(username))
return this.parse(`/help github`);
if (!gitData.usernames)
gitData.usernames = {};
gitData.usernames[toID(gitName)] = username;
GitHub.save();
this.privateModAction(`${user.name} set ${gitName}'s name on reported GitHub actions to be ${username}.`);
this.modlog("GITHUB SETNAME", null, `'${gitName}' to '${username}'`);
},
clearname: "removeusername",
removeusername(target, room, user) {
room = this.requireRoom("development");
this.checkCan("mute", null, room);
target = toID(target);
if (!target)
return this.parse(`/help github`);
const name = gitData.usernames?.[target];
if (!name)
return this.errorReply(`${target} is not a GitHub username on our list.`);
delete gitData.usernames?.[target];
if (!Object.keys(gitData.usernames || {}).length)
delete gitData.usernames;
GitHub.save();
this.privateModAction(`${user.name} removed ${target}'s name from the GitHub username list.`);
this.modlog("GITHUB CLEARNAME", target, `from the name ${name}`);
},
names() {
return this.parse("/j view-github-names");
}
},
githubhelp: [
`/github ban [username], [reason] - Bans a GitHub user from having their GitHub actions reported to Dev room. Requires: % @ # &`,
`/github unban [username] - Unbans a GitHub user from having their GitHub actions reported to Dev room. Requires: % @ # &`,
`/github bans - Lists all GitHub users that are currently gitbanned. Requires: % @ # &`,
`/github setname [username], [name] - Sets a GitHub user's name on reported GitHub actions to be [name]. Requires: % @ # &`,
`/github clearname [username] - Removes a GitHub user's name from the GitHub username list. Requires: % @ # &`,
`/github names - Lists all GitHub usernames that are currently on our list.`
]
};
const pages = {
github: {
bans(query, user) {
const room = Rooms.get("development");
if (!room)
return this.errorReply("No Development room found.");
this.checkCan("mute", null, room);
if (!gitData.bans)
return this.errorReply("There are no gitbans at this time.");
let buf = `<div class="pad"><h2>Current Gitbans:</h2><hr /><ol>`;
for (const [username, reason] of Object.entries(gitData.bans)) {
buf += `<li><strong>${username}</strong> - ${reason.trim() || "(No reason found)"}</li>`;
}
buf += `</ol>`;
return buf;
},
names() {
if (!gitData.usernames)
return this.errorReply("There are no GitHub usernames in the list.");
let buf = `<div class="pad"><h2>Current GitHub username mappings:</h2><hr /><ol>`;
for (const [username, name] of Object.entries(gitData.usernames)) {
buf += `<li><strong>${username}</strong> - ${name}</li>`;
}
buf += `</ol>`;
return buf;
}
}
};
function destroy() {
GitHub.hook?.server.close();
}
//# sourceMappingURL=github.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/github.ts"],
"sourcesContent": ["/**\r\n * Chat plugin to view GitHub events in a chatroom.\r\n * By Mia, with design / html from xfix's original bot, https://github.com/xfix/GitHub-Bot-Legacy/\r\n * @author mia-pi-git\r\n */\r\n\r\nimport {FS, Utils} from '../../lib';\r\n\r\nconst STAFF_REPOS = Config.staffrepos || [\r\n\t'pokemon-showdown', 'pokemon-showdown-client', 'Pokemon-Showdown-Dex', 'pokemon-showdown-loginserver',\r\n];\r\nconst COOLDOWN = 10 * 60 * 1000;\r\n\r\nexport const gitData: GitData = JSON.parse(FS(\"config/chat-plugins/github.json\").readIfExistsSync() || \"{}\");\r\n\r\ninterface GitHookHandler {\r\n\ton(event: 'pull_request', callback: (repo: string, ref: string | undefined, result: PullRequest) => void): void;\r\n\ton(event: 'push', callback: (repo: string, ref: string, result: Push) => void): void;\r\n\ton(event: string, callback: (repo: string, ref: string | undefined, result: any) => void): void;\r\n\tlisten(): void;\r\n\tserver: import('http').Server;\r\n}\r\n\r\ninterface Push {\r\n\tcommits: Commit[];\r\n\tsender: {login: string};\r\n\tcompare: string;\r\n}\r\n\r\ninterface PullRequest {\r\n\taction: string;\r\n\tnumber: number;\r\n\tpull_request: {\r\n\t\turl: string,\r\n\t\thtml_url: string,\r\n\t\ttitle: string,\r\n\t\tuser: {\r\n\t\t\tlogin: string,\r\n\t\t\thtml_url: string,\r\n\t\t},\r\n\t\tmerge_commit_sha: string,\r\n\t};\r\n\tsender: {login: string};\r\n}\r\n\r\ninterface Commit {\r\n\tid: string;\r\n\tmessage: string;\r\n\tauthor: {name: string, avatar_url: string};\r\n\turl: string;\r\n}\r\n\r\ninterface GitData {\r\n\tusernames?: {[username: string]: string};\r\n\tbans?: {[username: string]: string};\r\n}\r\n\r\nexport const GitHub = new class {\r\n\treadonly hook: GitHookHandler | null = null;\r\n\tupdates: {[k: string]: number} = Object.create(null);\r\n\tconstructor() {\r\n\t\t// config.github: https://github.com/nlf/node-github-hook#readme\r\n\t\tif (!Config.github) return;\r\n\r\n\t\ttry {\r\n\t\t\tthis.hook = require('githubhook')({\r\n\t\t\t\tlogger: {\r\n\t\t\t\t\tlog: (line: string) => Monitor.debug(line),\r\n\t\t\t\t\terror: (line: string) => Monitor.notice(line),\r\n\t\t\t\t},\r\n\t\t\t\t...Config.github,\r\n\t\t\t});\r\n\t\t} catch (err) {\r\n\t\t\tMonitor.crashlog(err, \"GitHub hook\");\r\n\t\t}\r\n\t\tthis.listen();\r\n\t}\r\n\tlisten() {\r\n\t\tif (!this.hook) return;\r\n\t\tthis.hook.listen();\r\n\t\tthis.hook.on('push', (repo, ref, result) => this.handlePush(repo, ref, result));\r\n\t\tthis.hook.on('pull_request', (repo, ref, result) => this.handlePull(repo, ref, result));\r\n\t}\r\n\tprivate getRepoName(repo: string) {\r\n\t\tswitch (repo) {\r\n\t\tcase 'pokemon-showdown':\r\n\t\t\treturn 'server';\r\n\t\tcase 'pokemon-showdown-client':\r\n\t\t\treturn 'client';\r\n\t\tcase 'Pokemon-Showdown-Dex':\r\n\t\t\treturn 'dex';\r\n\t\tdefault:\r\n\t\t\treturn repo.toLowerCase();\r\n\t\t}\r\n\t}\r\n\thandlePush(repo: string, ref: string, result: Push) {\r\n\t\tconst branch = /[^/]+$/.exec(ref)?.[0] || \"\";\r\n\t\tif (branch !== 'master') return;\r\n\t\tconst messages: {[k: string]: string[]} = {\r\n\t\t\tstaff: [],\r\n\t\t\tdevelopment: [],\r\n\t\t};\r\n\t\tfor (const commit of result.commits) {\r\n\t\t\tconst {message, url} = commit;\r\n\t\t\tconst [shortMessage] = message.split('\\n\\n');\r\n\t\t\tconst username = this.getUsername(commit.author.name);\r\n\t\t\tconst repoName = this.getRepoName(repo);\r\n\t\t\tconst id = commit.id.substring(0, 6);\r\n\t\t\tmessages.development.push(\r\n\t\t\t\tUtils.html`[<span style=\"color:#FF00FF\">${repoName}</span>] <a href=\"${url}\" style=\"color:#606060\">${id}</a> ${shortMessage} <span style=\"color:#909090\">(${username})</span>`\r\n\t\t\t);\r\n\t\t\tmessages.staff.push(Utils.html`[<span style=\"color:#FF00FF\">${repoName}</span>] <a href=\"${url}\">${shortMessage}</a> <span style=\"color:#909090\">(${username})</span>`);\r\n\t\t}\r\n\t\tfor (const k in messages) {\r\n\t\t\tthis.report(k as RoomID, repo, messages[k as RoomID]);\r\n\t\t}\r\n\t}\r\n\thandlePull(repo: string, ref: string | undefined, result: PullRequest) {\r\n\t\tif (this.isRateLimited(result.number)) return;\r\n\t\tif (this.isGitbanned(result)) return;\r\n\t\tconst url = result.pull_request.html_url;\r\n\t\tconst action = this.isValidAction(result.action);\r\n\t\tif (!action) return;\r\n\t\tconst repoName = this.getRepoName(repo);\r\n\t\tconst userName = this.getUsername(result.sender.login);\r\n\t\tconst title = result.pull_request.title;\r\n\t\tlet buf = Utils.html`[<span style=\"color:#FF00FF\">${repoName}</span>] <span style=\"color:#909090\">${userName}</span> `;\r\n\t\tbuf += Utils.html`${action} <a href=\"${url}\">PR#${result.number}</a>: ${title}`;\r\n\t\tthis.report('development', repo, buf);\r\n\t}\r\n\treport(roomid: RoomID, repo: string, messages: string[] | string) {\r\n\t\tif (!STAFF_REPOS.includes(repo) && roomid === 'staff') return;\r\n\t\tif (Array.isArray(messages)) messages = messages.join('<br />');\r\n\t\tRooms.get(roomid)?.add(`|html|<dLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,iBAAwB;AAExB,MAAM,cAAc,OAAO,cAAc;AAAA,EACxC;AAAA,EAAoB;AAAA,EAA2B;AAAA,EAAwB;AACxE;AACA,MAAM,WAAW,KAAK,KAAK;AAEpB,MAAM,UAAmB,KAAK,UAAM,eAAG,iCAAiC,EAAE,iBAAiB,KAAK,IAAI;AA4CpG,MAAM,SAAS,IAAI,MAAM;AAAA,EA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AAM,cAAc;AACvE,UAAI,CAAC,QAAQ;AAAW,gBAAQ,YAAY,CAAC;AAC7C,cAAQ,UAAU,KAAK,OAAO,CAAC,IAAI;AACnC,aAAO,KAAK;AACZ,WAAK,iBAAiB,GAAG,KAAK,YAAY,mDAAmD,WAAW;AACxG,WAAK,OAAO,kBAAkB,MAAM,IAAI,gBAAgB,WAAW;AAAA,IACpE;AAAA,IACA,WAAW;AAAA,IACX,eAAe,QAAQ,MAAM,MAAM;AAClC,aAAO,KAAK,YAAY,aAAa;AACrC,WAAK,SAAS,QAAQ,MAAM,IAAI;AAChC,eAAS,KAAK,MAAM;AACpB,UAAI,CAAC;AAAQ,eAAO,KAAK,MAAM,cAAc;AAC7C,YAAM,OAAO,QAAQ,YAAY,MAAM;AACvC,UAAI,CAAC;AAAM,eAAO,KAAK,WAAW,GAAG,8CAA8C;AACnF,aAAO,QAAQ,YAAY,MAAM;AACjC,UAAI,CAAC,OAAO,KAAK,QAAQ,aAAa,CAAC,CAAC,EAAE;AAAQ,eAAO,QAAQ;AACjE,aAAO,KAAK;ALine truncated
"names": []
}
+565
View File
@@ -0,0 +1,565 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var hangman_exports = {};
__export(hangman_exports, {
Hangman: () => Hangman,
commands: () => commands,
hangmanData: () => hangmanData,
pages: () => pages,
roomSettings: () => roomSettings
});
module.exports = __toCommonJS(hangman_exports);
var import_lib = require("../../lib");
const HANGMAN_FILE = "config/chat-plugins/hangman.json";
const DIACRITICS_AFTER_UNDERSCORE = /_[\u0300-\u036f\u0483-\u0489\u0610-\u0615\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06ED\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]+/g;
const MAX_HANGMAN_LENGTH = 30;
const MAX_INDIVIDUAL_WORD_LENGTH = 20;
const MAX_HINT_LENGTH = 150;
let hangmanData = {};
try {
hangmanData = JSON.parse((0, import_lib.FS)(HANGMAN_FILE).readSync());
let save = false;
for (const roomid in hangmanData) {
const roomData = hangmanData[roomid] || {};
const roomKeys = Object.keys(roomData);
if (roomKeys.length && !roomData[roomKeys[0]].hints) {
save = true;
for (const key of roomKeys) {
roomData[key] = { hints: roomData[key] };
}
}
}
if (save) {
(0, import_lib.FS)(HANGMAN_FILE).writeUpdate(() => JSON.stringify(hangmanData));
}
} catch {
}
const maxMistakes = 6;
class Hangman extends Rooms.SimpleRoomGame {
constructor(room, user, word, hint = "", gameOptions = {}) {
super(room);
this.checkChat = true;
this.gameNumber = room.nextGameNumber();
this.gameid = "hangman";
this.title = "Hangman";
this.creator = user.id;
this.word = word;
this.hint = hint;
this.incorrectGuesses = 0;
this.options = gameOptions;
this.guesses = [];
this.letterGuesses = [];
this.lastGuesser = "";
this.wordSoFar = [];
for (const letter of word) {
if (/[a-zA-Z]/.test(letter)) {
this.wordSoFar.push("_");
} else {
this.wordSoFar.push(letter);
}
}
}
choose(user, word) {
if (user.id === this.creator && !this.options.allowCreator) {
throw new Chat.ErrorMessage("You can't guess in your own hangman game.");
}
const sanitized = word.replace(/[^A-Za-z ]/g, "");
const normalized = toID(sanitized);
if (normalized.length < 1) {
throw new Chat.ErrorMessage(`Use "/guess [letter]" to guess a letter, or "/guess [phrase]" to guess the entire Hangman phrase.`);
}
if (sanitized.length > MAX_HANGMAN_LENGTH) {
throw new Chat.ErrorMessage(`Guesses must be ${MAX_HANGMAN_LENGTH} or fewer letters \u2013 "${word}" is too long.`);
}
for (const guessid of this.guesses) {
if (normalized === toID(guessid))
throw new Chat.ErrorMessage(`Your guess "${word}" has already been guessed.`);
}
if (sanitized.length > 1) {
if (!this.guessWord(sanitized, user.name)) {
throw new Chat.ErrorMessage(`Your guess "${sanitized}" is invalid.`);
} else {
this.room.addByUser(user, `${user.name} guessed "${sanitized}"!`);
}
} else {
if (!this.guessLetter(sanitized, user.name)) {
throw new Chat.ErrorMessage(`Your guess "${sanitized}" is not a valid letter.`);
}
}
}
guessLetter(letter, guesser) {
letter = letter.toUpperCase();
if (this.guesses.includes(letter))
return false;
if (this.word.toUpperCase().includes(letter)) {
for (let i = 0; i < this.word.length; i++) {
if (this.word[i].toUpperCase() === letter) {
this.wordSoFar[i] = this.word[i];
}
}
if (!this.wordSoFar.includes("_")) {
this.incorrectGuesses = -1;
this.guesses.push(letter);
this.letterGuesses.push(`${letter}1`);
this.lastGuesser = guesser;
this.finish();
return true;
}
this.letterGuesses.push(`${letter}1`);
} else {
this.incorrectGuesses++;
this.letterGuesses.push(`${letter}0`);
}
this.guesses.push(letter);
this.lastGuesser = guesser;
this.update();
return true;
}
guessWord(word, guesser) {
const ourWord = toID(this.word.replace(/[0-9]+/g, ""));
const guessedWord = toID(word.replace(/[0-9]+/g, ""));
const wordSoFar = this.wordSoFar.filter((letter) => /[a-zA-Z_]/.test(letter)).join("").toLowerCase();
if (ourWord.length !== guessedWord.length)
return false;
for (let i = 0; i < ourWord.length; i++) {
if (wordSoFar.charAt(i) === "_") {
if (this.letterGuesses.some((guess) => guess.toLowerCase().startsWith(guessedWord.charAt(i))))
return false;
} else if (wordSoFar.charAt(i) !== guessedWord.charAt(i)) {
return false;
}
}
if (ourWord === guessedWord) {
for (const [i, letter] of this.wordSoFar.entries()) {
if (letter === "_") {
this.wordSoFar[i] = this.word[i];
}
}
this.incorrectGuesses = -1;
this.guesses.push(word);
this.lastGuesser = guesser;
this.finish();
} else {
this.incorrectGuesses++;
this.guesses.push(word);
this.lastGuesser = guesser;
this.update();
}
return true;
}
hangingMan() {
return `<img width="120" height="120" src="//${Config.routes.client}/fx/hangman${this.incorrectGuesses === -1 ? 7 : this.incorrectGuesses}.png" />`;
}
generateWindow() {
let result = 0;
if (this.incorrectGuesses === maxMistakes) {
result = 1;
} else if (!this.wordSoFar.includes("_")) {
result = 2;
}
const color = result === 1 ? "red" : result === 2 ? "green" : "blue";
const message = `${result === 1 ? "Too bad! The mon has been hanged." : result === 2 ? "The word has been guessed. Congratulations!" : "Hangman"}`;
let output = `<div class="broadcast-${color}">`;
output += `<p style="text-align:left;font-weight:bold;font-size:10pt;margin:5px 0 0 15px">${message}</p>`;
output += `<table><tr><td style="text-align:center;">${this.hangingMan()}</td><td style="text-align:center;width:100%;word-wrap:break-word">`;
let escapedWord = this.wordSoFar.map(import_lib.Utils.escapeHTML);
if (result === 1) {
const word = this.word;
escapedWord = escapedWord.map((letter, index) => letter === "_" ? `<font color="#7af87a">${word.charAt(index)}</font>` : letter);
}
const wordString = escapedWord.join("").replace(DIACRITICS_AFTER_UNDERSCORE, "_");
if (this.hint)
output += import_lib.Utils.html`<div>(Hint: ${this.hint})</div>`;
output += `<p style="font-weight:bold;font-size:12pt;letter-spacing:3pt">${wordString}</p>`;
if (this.guesses.length) {
if (this.letterGuesses.length) {
output += "Letters: " + this.letterGuesses.map(
(g) => `<strong${g[1] === "1" ? "" : ' style="color: #DBA"'}>${g[0]}</strong>`
).join(", ");
}
if (result === 2) {
output += import_lib.Utils.html`<br />Winner: ${this.lastGuesser}`;
} else if (this.guesses[this.guesses.length - 1].length === 1) {
output += import_lib.Utils.html` <small>&ndash; ${this.lastGuesser}</small>`;
} else {
output += import_lib.Utils.html`<br />Guessed: ${this.guesses[this.guesses.length - 1]} ` + `<small>&ndash; ${this.lastGuesser}</small>`;
}
}
output += "</td></tr></table></div>";
return output;
}
display(user, broadcast = false) {
if (broadcast) {
this.room.add(`|uhtml|hangman${this.gameNumber}|${this.generateWindow()}`);
} else {
user.sendTo(this.room, `|uhtml|hangman${this.gameNumber}|${this.generateWindow()}`);
}
}
update() {
this.room.uhtmlchange(`hangman${this.gameNumber}`, this.generateWindow());
if (this.incorrectGuesses === maxMistakes) {
this.finish();
}
}
end() {
this.room.uhtmlchange(`hangman${this.gameNumber}`, '<div class="infobox">(The game of hangman was ended.)</div>');
this.room.add("The game of hangman was ended.");
this.room.game = null;
}
finish() {
this.room.uhtmlchange(`hangman${this.gameNumber}`, '<div class="infobox">(The game of hangman has ended &ndash; scroll down to see the results)</div>');
this.room.add(`|html|${this.generateWindow()}`);
this.room.game = null;
}
static save() {
(0, import_lib.FS)(HANGMAN_FILE).writeUpdate(() => JSON.stringify(hangmanData));
}
static getRandom(room, tag) {
if (!hangmanData[room]) {
hangmanData[room] = {};
this.save();
}
let phrases = Object.keys(hangmanData[room]);
if (!phrases.length)
throw new Chat.ErrorMessage(`The room ${room} has no saved hangman words.`);
if (tag) {
tag = toID(tag);
phrases = phrases.filter((key) => hangmanData[room][key].tags?.map(toID).includes(tag));
if (!phrases.length) {
throw new Chat.ErrorMessage(`No terms found with tag ${tag}`);
}
}
const shuffled = import_lib.Utils.randomElement(phrases);
const entry = hangmanData[room][shuffled];
return {
question: shuffled,
hint: import_lib.Utils.randomElement(entry.hints)
};
}
static validateParams(params) {
const phrase = params[0].normalize("NFD").trim().replace(/_/g, "\uFF3F");
if (!phrase.length)
throw new Chat.ErrorMessage("Enter a valid word");
if (phrase.length > MAX_HANGMAN_LENGTH) {
throw new Chat.ErrorMessage(`Phrase must be less than ${MAX_HANGMAN_LENGTH} characters long.`);
}
if (phrase.split(" ").some((w) => w.length > MAX_INDIVIDUAL_WORD_LENGTH)) {
throw new Chat.ErrorMessage(`Each word in the phrase must be less than ${MAX_INDIVIDUAL_WORD_LENGTH} characters long.`);
}
if (!/[a-zA-Z]/.test(phrase))
throw new Chat.ErrorMessage("Word must contain at least one letter.");
let hint;
if (params.length > 1) {
hint = params.slice(1).join(",").trim();
if (hint.length > MAX_HINT_LENGTH) {
throw new Chat.ErrorMessage(`Hint must be less than ${MAX_HINT_LENGTH} characters long.`);
}
}
return { phrase, hint };
}
}
const commands = {
hangman: {
create: "new",
new(target, room, user, connection) {
room = this.requireRoom();
target = target.trim();
const text = this.filter(target);
if (target !== text)
return this.errorReply("You are not allowed to use filtered words in hangmans.");
const params = text.split(",");
this.checkCan("minigame", null, room);
if (room.settings.hangmanDisabled)
return this.errorReply("Hangman is disabled for this room.");
this.checkChat();
if (room.game)
return this.errorReply(`There is already a game of ${room.game.title} in progress in this room.`);
if (!params)
return this.errorReply("No word entered.");
const { phrase, hint } = Hangman.validateParams(params);
const game = new Hangman(room, user, phrase, hint);
room.game = game;
game.display(user, true);
this.modlog("HANGMAN");
return this.addModAction(`A game of hangman was started by ${user.name} \u2013 use /guess to play!`);
},
createhelp: ["/hangman create [word], [hint] - Makes a new hangman game. Requires: % @ # &"],
guess(target, room, user) {
const word = this.filter(target);
if (word !== target)
return this.errorReply(`You may not use filtered words in guesses.`);
this.parse(`/choose ${target}`);
},
guesshelp: [
`/guess [letter] - Makes a guess for the letter entered.`,
`/guess [word] - Same as a letter, but guesses an entire word.`
],
stop: "end",
end(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
this.checkChat();
const game = this.requireGame(Hangman);
game.end();
this.modlog("ENDHANGMAN");
return this.privateModAction(`The game of hangman was ended by ${user.name}.`);
},
endhelp: ["/hangman end - Ends the game of hangman before the man is hanged or word is guessed. Requires: % @ # &"],
disable(target, room, user) {
room = this.requireRoom();
this.checkCan("gamemanagement", null, room);
if (room.settings.hangmanDisabled) {
return this.errorReply("Hangman is already disabled.");
}
room.settings.hangmanDisabled = true;
room.saveSettings();
return this.sendReply("Hangman has been disabled for this room.");
},
enable(target, room, user) {
room = this.requireRoom();
this.checkCan("gamemanagement", null, room);
if (!room.settings.hangmanDisabled) {
return this.errorReply("Hangman is already enabled.");
}
delete room.settings.hangmanDisabled;
room.saveSettings();
return this.sendReply("Hangman has been enabled for this room.");
},
display(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Hangman);
if (!this.runBroadcast())
return;
room.update();
game.display(user, this.broadcasting);
},
""(target, room, user) {
return this.parse("/help hangman");
},
random(target, room, user) {
room = this.requireRoom();
this.checkCan("mute", null, room);
if (room.game) {
throw new Chat.ErrorMessage(`There is already a game of ${room.game.title} running.`);
}
target = toID(target);
const { question, hint } = Hangman.getRandom(room.roomid, target);
const game = new Hangman(room, user, question, hint, { allowCreator: true });
room.game = game;
this.addModAction(`${user.name} started a random game of hangman - use /guess to play!`);
game.display(user, true);
this.modlog(`HANGMAN RANDOM`, null, target ? `tag: ${target}` : "");
},
addrandom(target, room, user) {
room = this.requireRoom();
this.checkCan("mute", null, room);
if (!hangmanData[room.roomid])
hangmanData[room.roomid] = {};
if (!target)
return this.parse("/help hangman");
const args = target.split(target.includes("|") ? "|" : ",");
const { phrase } = Hangman.validateParams(args);
if (!hangmanData[room.roomid][phrase])
hangmanData[room.roomid][phrase] = { hints: [] };
args.shift();
hangmanData[room.roomid][phrase].hints.push(...args);
Hangman.save();
this.privateModAction(`${user.name} added a random hangman with ${Chat.count(args.length, "hints")}.`);
this.modlog(`HANGMAN ADDRANDOM`, null, `${phrase}: ${args.join(", ")}`);
},
rr: "removerandom",
removerandom(target, room, user) {
room = this.requireRoom();
this.checkCan("mute", null, room);
let [word, ...hints] = target.split(",");
if (!toID(target) || !word)
return this.parse("/help hangman");
for (const [i, hint] of hints.entries()) {
if (hint.startsWith("room:")) {
const newID = hint.slice(5);
const targetRoom = Rooms.search(newID);
if (!targetRoom) {
return this.errorReply(`Invalid room: ${newID}`);
}
this.room = targetRoom;
room = targetRoom;
hints.splice(i, 1);
}
}
if (!hangmanData[room.roomid]) {
return this.errorReply("There are no hangman words for this room.");
}
const roomKeys = Object.keys(hangmanData[room.roomid]);
const roomKeyIDs = roomKeys.map(toID);
const index = roomKeyIDs.indexOf(toID(word));
if (index < 0) {
return this.errorReply(`That word is not a saved hangman.`);
}
word = roomKeys[index];
hints = hints.map(toID);
if (!hints.length) {
delete hangmanData[room.roomid][word];
this.privateModAction(`${user.name} deleted the hangman entry for '${word}'`);
this.modlog(`HANGMAN REMOVERANDOM`, null, word);
} else {
hangmanData[room.roomid][word].hints = hangmanData[room.roomid][word].hints.filter((item) => !hints.includes(toID(item)));
if (!hangmanData[room.roomid][word].hints.length) {
delete hangmanData[room.roomid][word];
}
this.privateModAction(`${user.name} deleted ${Chat.count(hints, "hints")} for the hangman term '${word}'`);
this.modlog(`HANGMAN REMOVERANDOM`, null, `${word}: ${hints.join(", ")}`);
}
this.refreshPage(`hangman-${room.roomid}`);
Hangman.save();
},
addtag(target, room, user) {
room = this.requireRoom();
this.checkCan("mute", null, room);
let [term, ...tags] = target.split(",");
term = term.trim();
tags = tags.map((i) => toID(i)).filter(Boolean);
if (!term || !tags || !tags.length) {
return this.parse("/help hangman");
}
if (!hangmanData[room.roomid]) {
hangmanData[room.roomid] = {};
}
if (!hangmanData[room.roomid][term]) {
return this.errorReply(`Term ${term} not found.`);
}
if (!hangmanData[room.roomid][term].tags)
hangmanData[room.roomid][term].tags = [];
for (const [i, tag] of tags.entries()) {
if (hangmanData[room.roomid][term].tags.includes(tag)) {
this.errorReply(`The tag ${tag} is already on the term ${term} and has been skipped.`);
tags.splice(i, 1);
}
}
if (!tags.length) {
this.errorReply(`Specify at least one valid tag.`);
return this.parse(`/help hangman`);
}
hangmanData[room.roomid][term].tags.push(...tags);
Hangman.save();
this.privateModAction(`${user.name} added ${Chat.count(tags, "tags")} to the hangman term ${term}`);
this.modlog(`HANGMAN ADDTAG`, null, `${term}: ${tags.map(import_lib.Utils.escapeHTML).join(", ")}`);
this.refreshPage(`hangman-${room.roomid}`);
},
untag(target, room, user) {
room = this.requireRoom();
this.checkCan("mute", null, room);
if (!toID(target)) {
return this.parse(`/help hangman`);
}
let [term, ...tags] = target.split(",");
tags = tags.map((i) => toID(i)).filter(Boolean);
if (!term || !tags) {
return this.parse("/help hangman");
}
if (!hangmanData[room.roomid]) {
return this.errorReply(`This room has no hangman terms.`);
}
if (!hangmanData[room.roomid][term]) {
return this.errorReply(`That term was not found.`);
}
if (!hangmanData[room.roomid][term].tags) {
return this.errorReply(`That term has no tags.`);
}
if (tags.length) {
this.privateModAction(`${user.name} removed ${Chat.count(tags, "tags")} from the hangman term ${term}`);
this.modlog(`HANGMAN UNTAG`, null, `${term}: ${tags.map(import_lib.Utils.escapeHTML).join(", ")}`);
hangmanData[room.roomid][term].tags = hangmanData[room.roomid][term].tags?.filter((t) => !tags.includes(t));
} else {
this.privateModAction(`${user.name} removed all tags from the hangman term ${term}`);
this.modlog(`HANGMAN UNTAG`, null, `${term}`);
hangmanData[room.roomid][term].tags = [];
}
if (!hangmanData[room.roomid][term].tags.length) {
delete hangmanData[room.roomid][term].tags;
}
Hangman.save();
this.refreshPage(`hangman-${room.roomid}`);
},
view: "terms",
terms(target, room, user) {
room = this.requireRoom();
return this.parse(`/j view-hangman-${target || room.roomid}`);
}
},
hangmanhelp: [
`/hangman allows users to play the popular game hangman in PS rooms.`,
`Accepts the following commands:`,
`/hangman create [word], [hint] - Makes a new hangman game. Requires: % @ # &`,
`/hangman guess [letter] - Makes a guess for the letter entered.`,
`/hangman guess [word] - Same as a letter, but guesses an entire word.`,
`/hangman display - Displays the game.`,
`/hangman end - Ends the game of hangman before the man is hanged or word is guessed. Requires: % @ # &`,
`/hangman [enable/disable] - Enables or disables hangman from being started in a room. Requires: # &`,
`/hangman random [tag]- Runs a random hangman, if the room has any added. `,
`If a tag is given, randomizes from only terms with those tags. Requires: % @ # &`,
`/hangman addrandom [word], [...hints] - Adds an entry for [word] with the [hints] provided to the room's hangman pool. Requires: % @ # &`,
`/hangman removerandom [word][, hints] - Removes data from the hangman entry for [word]. If hints are given, removes only those hints. Otherwise it removes the entire entry. Requires: % @ & #`,
`/hangman addtag [word], [...tags] - Adds tags to the hangman term matching [word]. Requires: % @ & #`,
`/hangman untag [term][, ...tags] - Removes tags from the hangman [term]. If tags are given, removes only those tags. Requires: % @ # * `,
`/hangman terms - Displays all random hangman in a room. Requires: % @ # &`
]
};
const pages = {
hangman(args, user) {
const room = this.requireRoom();
this.title = `[Hangman]`;
this.checkCan("mute", null, room);
let buf = `<div class="pad"><button style="float:right;" class="button" name="send" value="/join view-hangman-${room.roomid}"><i class="fa fa-refresh"></i> Refresh</button>`;
buf += `<div class="pad"><h2>Hangman entries on ${room.title}</h2>`;
const roomTerms = hangmanData[room.roomid];
if (!roomTerms) {
return this.errorReply(`No hangman terms found for ${room.title}.`);
}
for (const t in roomTerms) {
buf += `<div class="infobox">`;
buf += `<h3>${t}</h3><hr />`;
if (user.can("mute", null, room, "hangman addrandom")) {
buf += `<strong>Hints:</strong> `;
buf += roomTerms[t].hints.map(
(hint) => `${hint} <button class="button" name="send" value="/msgroom ${room.roomid}, /hangman rr ${t},${hint}" aria-label="Delete"><i class="fa fa-trash"></i></button>`
).join(", ");
buf += `<button style="float:right;" class="button" name="send" value="/msgroom ${room.roomid}, /hangman rr ${t}"><i class="fa fa-trash"></i> Delete all terms</button>`;
if (roomTerms[t].tags) {
buf += `<br /><strong>Tags: </strong> `;
buf += roomTerms[t].tags?.map(
(tag) => `${tag} <button class="button" name="send" value="/msgroom ${room.roomid}, /hangman untag ${t},${tag}" aria-label="Delete"><i class="fa fa-trash"></i></button>`
).join(", ");
buf += `<button style="float:right;" class="button" name="send" value="/msgroom ${room.roomid}, /hangman untag ${t}"><i class="fa fa-trash"></i> Delete all tags</button>`;
}
}
buf += `</div><br />`;
}
buf += `</div>`;
return buf;
}
};
const roomSettings = (room) => ({
label: "Hangman",
permission: "editroom",
options: [
[`disabled`, room.settings.hangmanDisabled || "hangman disable"],
[`enabled`, !room.settings.hangmanDisabled || "hangman enable"]
]
});
//# sourceMappingURL=hangman.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/hangman.ts"],
"sourcesContent": ["/*\r\n* Hangman chat plugin\r\n* By bumbadadabum and Zarel. Art by crobat.\r\n*/\r\nimport {FS, Utils} from '../../lib';\r\n\r\nconst HANGMAN_FILE = 'config/chat-plugins/hangman.json';\r\n\r\nconst DIACRITICS_AFTER_UNDERSCORE = /_[\\u0300-\\u036f\\u0483-\\u0489\\u0610-\\u0615\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06ED\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E]+/g;\r\nconst MAX_HANGMAN_LENGTH = 30;\r\nconst MAX_INDIVIDUAL_WORD_LENGTH = 20;\r\nconst MAX_HINT_LENGTH = 150;\r\n\r\ninterface HangmanEntry {\r\n\thints: string[];\r\n\ttags?: string[];\r\n}\r\n\r\n// futureproofing this into one single object so that new params can be added\r\n// more easily\r\ninterface HangmanOptions {\r\n\tallowCreator?: boolean;\r\n}\r\n\r\nexport let hangmanData: {[roomid: string]: {[phrase: string]: HangmanEntry}} = {};\r\n\r\ntry {\r\n\thangmanData = JSON.parse(FS(HANGMAN_FILE).readSync());\r\n\tlet save = false;\r\n\tfor (const roomid in hangmanData) {\r\n\t\tconst roomData = hangmanData[roomid] || {};\r\n\t\tconst roomKeys = Object.keys(roomData);\r\n\t\tif (roomKeys.length && !roomData[roomKeys[0]].hints) {\r\n\t\t\tsave = true;\r\n\t\t\tfor (const key of roomKeys) {\r\n\t\t\t\troomData[key] = {hints: roomData[key] as any};\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (save) {\r\n\t\tFS(HANGMAN_FILE).writeUpdate(() => JSON.stringify(hangmanData));\r\n\t}\r\n} catch {}\r\n\r\nconst maxMistakes = 6;\r\n\r\nexport class Hangman extends Rooms.SimpleRoomGame {\r\n\tgameNumber: number;\r\n\tcreator: ID;\r\n\tword: string;\r\n\thint: string;\r\n\tincorrectGuesses: number;\r\n\toptions: HangmanOptions;\r\n\r\n\tguesses: string[];\r\n\tletterGuesses: string[];\r\n\tlastGuesser: string;\r\n\twordSoFar: string[];\r\n\treadonly checkChat = true;\r\n\r\n\tconstructor(\r\n\t\troom: Room,\r\n\t\tuser: User,\r\n\t\tword: string,\r\n\t\thint = '',\r\n\t\tgameOptions: HangmanOptions = {}\r\n\t) {\r\n\t\tsuper(room);\r\n\r\n\t\tthis.gameNumber = room.nextGameNumber();\r\n\r\n\t\tthis.gameid = 'hangman' as ID;\r\n\t\tthis.title = 'Hangman';\r\n\t\tthis.creator = user.id;\r\n\t\tthis.word = word;\r\n\t\tthis.hint = hint;\r\n\t\tthis.incorrectGuesses = 0;\r\n\t\tthis.options = gameOptions;\r\n\r\n\t\tthis.guesses = [];\r\n\t\tthis.letterGuesses = [];\r\n\t\tthis.lastGuesser = '';\r\n\t\tthis.wordSoFar = [];\r\n\r\n\t\tfor (const letter of word) {\r\n\t\t\tif (/[a-zA-Z]/.test(letter)) {\r\n\t\t\t\tthis.wordSoFar.push('_');\r\n\t\t\t} else {\r\n\t\t\t\tthis.wordSoFar.push(letter);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tchoose(user: User, word: string) {\r\n\t\tif (user.id === this.creator && !this.options.allowCreator) {\r\n\t\t\tthrow new Chat.ErrorMessage(\"You can't guess in your own hangman game.\");\r\n\t\t}\r\n\r\n\t\tconst sanitized = word.replace(/[^A-Za-z ]/g, '');\r\n\t\tconst normalized = toID(sanitized);\r\n\t\tif (normalized.length < 1) {\r\n\t\t\tthrow new Chat.ErrorMessage(`Use \"/guess [letter]\" to guess a letter, or \"/guess [phrase]\" to guess the entire Hangman phrase.`);\r\n\t\t}\r\n\t\tif (sanitized.length > MAX_HANGMAN_LENGTH) {\r\n\t\t\tthrow new Chat.ErrorMessage(`Guesses must be ${MAX_HANGMAN_LENGTH} or fewer letters \u2013 \"${word}\" is too long.`);\r\n\t\t}\r\n\r\n\t\tfor (const guessid of this.guesses) {\r\n\t\t\tif (normalized === toID(guessid)) throw new Chat.ErrorMessage(`Your guess \"${word}\" has already been guessed.`);\r\n\t\t}\r\n\r\n\t\tif (sanitized.length > 1) {\r\n\t\t\tif (!this.guessWord(sanitized, user.name)) {\r\n\t\t\t\tthrow new Chat.ErrorMessage(`Your guess \"${sanitized}\" is invalid.`);\r\n\t\t\t} else {\r\n\t\t\t\tthis.room.addByUser(user, `${user.name} guessed \"${sanitized}\"!`);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif (!this.guessLetter(sanitized, user.name)) {\r\n\t\t\t\tthrow new Chat.ErrorMessage(`Your guess \"${sanitized}\" is not a valid letter.`);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tguessLetter(letter: string, guesser: string) {\r\n\t\tletter = letter.toUpperCase();\r\n\t\tif (this.guesses.includes(letter)) return false;\r\n\t\tif (this.word.toUpperCase().includes(letter)) {\r\n\t\t\tfor (let i = 0; i < this.word.length; i++) {\r\n\t\t\t\tif (this.word[i].toUpperCase() === letter) {\r\n\t\t\t\t\tthis.wordSoFar[i] = this.word[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (!this.wordSoFar.includes('_')) {\r\n\t\t\t\tthis.incorrectGuesses = -1;\r\n\t\t\t\tthis.guesses.push(letter);\r\n\t\t\t\tthis.letterGuesses.push(`${letter}1`);\r\n\t\t\t\tthis.lastGuesser = guesser;\r\n\t\t\t\tthis.finish();\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\tthis.letterGuesses.push(`${letter}1`);\r\n\t\t} else {\r\n\t\t\tthis.incorrectGuesses++;\r\n\t\t\tthis.letterGuesses.push(`${letter}0`);\r\n\t\t}\r\n\r\n\t\tthis.guesses.push(letter);\r\n\t\tthis.lastGuesser = guesser;\r\n\t\tthis.update();\r\n\t\treturn true;\r\n\t}\r\n\r\n\tguessWord(word: string, guesser: string) {\r\n\t\tconst ourWord = toID(this.word.replace(/[0-9]+/g, ''));\r\n\t\tconst guessedWord = toID(word.replace(/[0-9]+/g, ''));\r\nLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;A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AAqB,KAAK;AAAA,MAC3C,WAAW,KAAK,QAAQ,KAAK,QAAQ,SAAS,CAAC,EAAE,WAAW,GAAG;AAE9D,kBAAU,iBAAM,uBAAuB,KAAK;AAAA,MAC7C,OAAO;AACN,kBAAU,iBAAM,sBAAsB,KAAK,QAAQ,KAAK,QAAQ,SAAS,CAAC,OACzE,kBAAkB,KAAK;AAAA,MACzB;AAAA,IACD;AAEA,cAAU;AAEV,WAAO;AAAA,EACR;AAAA,EAEA,QAAQ,MAAY,YAAY,OAAO;AACtC,QAAI,WAAW;AACd,WAAK,KAAK,IAAI,iBAAiB,KAAK,cAAc,KAAK,eAAe,GAAG;AAAA,IAC1E,OAAO;AACN,WAAK,OAAO,KAAK,MAAM,iBAAiB,KAAK,cAAc,KAAK,eAAe,GAAG;AAAA,IACnF;AAAA,EACD;AAAA,EAEA,SAAS;AACR,SAAK,KAAK,YAAY,UAAU,KAAK,cAAc,KAAK,eAAe,CAAC;AAExE,QAAI,KAAK,qBAAqB,aAAa;AAC1C,WAAK,OAAO;AAAA,IACb;AAAA,EACD;AAAA,EAEA,MAAM;AACL,SAAK,KAAK,YAAY,UAAU,KAAK,cAAc,6DAA6D;AAChH,SAAK,KAAK,IAAI,gCAAgC;AAC9C,SAAK,KAAK,OAAO;AAAA,EAClB;AAAA,EAEA,SAAS;AACR,SAAK,KAAK,YAAY,UAAU,KAAK,cAAc,mGAAmG;AACtJ,SAAK,KAAK,IAAI,SAAS,KAAK,eAALine truncated
"names": []
}
@@ -0,0 +1,843 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var helptickets_auto_exports = {};
__export(helptickets_auto_exports, {
actionHandlers: () => actionHandlers,
addModAction: () => addModAction,
checkers: () => checkers,
classifier: () => classifier,
commands: () => commands,
determinePunishment: () => determinePunishment,
getMessageAverages: () => getMessageAverages,
getModlog: () => getModlog,
globalModlog: () => globalModlog,
pages: () => pages,
punishmentsFor: () => punishmentsFor,
runPunishments: () => runPunishments,
settings: () => settings
});
module.exports = __toCommonJS(helptickets_auto_exports);
var import_lib = require("../../lib");
var import_helptickets = require("./helptickets");
var Artemis = __toESM(require("../artemis"));
const ORDERED_PUNISHMENTS = ["WARN", "FORCERENAME", "LOCK", "NAMELOCK", "WEEKLOCK", "WEEKNAMELOCK"];
const PMLOG_IGNORE_TIME = 24 * 60 * 60 * 1e3;
const WHITELIST = ["mia"];
const defaults = {
punishments: [{
ticketType: "inapname",
punishment: "forcerename",
severity: { type: ["sexual_explicit", "severe_toxicity", "identity_attack"], certainty: 0.4 }
}, {
ticketType: "pmharassment",
punishment: "warn",
severity: { type: ["sexual_explicit", "severe_toxicity", "identity_attack"], certainty: 0.15 }
}],
applyPunishments: false
};
const settings = (() => {
try {
return { ...defaults, ...JSON.parse((0, import_lib.FS)("config/chat-plugins/ht-auto.json").readSync()) };
} catch {
return defaults;
}
})();
function saveSettings() {
return (0, import_lib.FS)("config/chat-plugins/ht-auto.json").writeUpdate(() => JSON.stringify(settings));
}
function visualizePunishment(punishment) {
const buf = [`punishment: ${punishment.punishment?.toUpperCase()}`];
buf.push(`ticket type: ${punishment.ticketType}`);
if (punishment.severity) {
buf.push(`severity: ${punishment.severity.certainty} (for ${punishment.severity.type.join(", ")})`);
}
if (punishment.modlogCount) {
buf.push(`required modlog: ${punishment.modlogCount}`);
}
if (punishment.isSingleMessage) {
buf.push(`for single messages only`);
}
return buf.join(", ");
}
function checkAccess(context) {
if (!WHITELIST.includes(context.user.id))
context.checkCan("bypassall");
}
function punishmentsFor(type) {
return settings.punishments.filter((t) => t.ticketType === type);
}
function supersedes(p1, p2) {
return ORDERED_PUNISHMENTS.indexOf(p1) > ORDERED_PUNISHMENTS.indexOf(p2);
}
function determinePunishment(ticketType, results, modlog, isSingleMessage = false) {
const punishments = punishmentsFor(ticketType);
let action = null;
const types = [];
import_lib.Utils.sortBy(punishments, (p) => -ORDERED_PUNISHMENTS.indexOf(p.punishment));
for (const punishment of punishments) {
if (isSingleMessage && !punishment.isSingleMessage)
continue;
if (punishment.modlogCount && modlog.length < punishment.modlogCount)
continue;
if (punishment.severity) {
let hit = false;
for (const type of punishment.severity.type) {
if (results[type] < punishment.severity.certainty)
continue;
hit = true;
types.push(type);
break;
}
if (!hit)
continue;
}
if (!action || supersedes(punishment.punishment, action)) {
action = punishment.punishment;
}
}
return { action, types };
}
function globalModlog(action, user, note, roomid) {
user = Users.get(user) || user;
void Rooms.Modlog.write(roomid || "global", {
action,
ip: user && typeof user === "object" ? user.latestIp : void 0,
userid: toID(user) || void 0,
loggedBy: "artemis",
note
});
}
function addModAction(message) {
Rooms.get("staff")?.add(`|c|&|/log ${message}`).update();
}
async function getModlog(params) {
const search = {
note: [],
user: [],
ip: [],
action: [],
actionTaker: []
};
if (params.user)
search.user = [{ search: params.user, isExact: true }];
if (params.ip)
search.ip = [{ search: params.ip }];
if (params.actions)
search.action = params.actions.map((s) => ({ search: s }));
const res = await Rooms.Modlog.search("global", search);
return res?.results || [];
}
function closeTicket(ticket, msg) {
if (!ticket.open)
return;
ticket.open = false;
ticket.active = false;
ticket.resolved = {
time: Date.now(),
by: "the Artemis AI",
// we want it to be clear to end users that it was not a human
seen: false,
staffReason: "",
result: msg || "",
note: `Want to learn more about the AI? <a href="https://www.smogon.com/forums/threads/3570628/#post-9056769">Visit the information thread</a>.`
};
(0, import_helptickets.writeTickets)();
(0, import_helptickets.notifyStaff)();
const tarUser = Users.get(ticket.userid);
if (tarUser) {
import_helptickets.HelpTicket.notifyResolved(tarUser, ticket, ticket.userid);
}
(0, import_helptickets.writeStats)(`${ticket.type} ${Date.now() - ticket.created} 0 0 resolved valid artemis`);
}
async function lock(user, result, ticket, isWeek, isName) {
const id = toID(user);
let desc, type;
const expireTime = isWeek ? Date.now() + 7 * 24 * 60 * 60 * 1e3 : null;
if (isName) {
if (typeof user === "object")
user.resetName();
desc = "locked your username and prevented you from changing names";
type = `locked from talking${isWeek ? ` for a week` : ""}`;
await Punishments.namelock(id, expireTime, null, false, result.reason || "Automatically locked due to a user report");
} else {
type = isWeek ? "weeknamelocked" : "namelocked";
desc = "locked you from talking in chats, battles, and PMing regular users";
await Punishments.lock(id, expireTime, null, false, result.reason || "Automatically locked due to a user report");
}
if (typeof user !== "string") {
let message = `|popup||html|${user.name} has ${desc} for ${isWeek ? "7" : "2"} days.`;
if (result.reason)
message += `
Reason: ${result.reason}`;
let appeal = "";
if (Chat.pages.help) {
appeal += `<a href="view-help-request--appeal"><button class="button"><strong>Appeal your punishment</strong></button></a>`;
} else if (Config.appealurl) {
appeal += `appeal: <a href="${Config.appealurl}">${Config.appealurl}</a>`;
}
if (appeal)
message += `
If you feel that your lock was unjustified, you can ${appeal}.`;
message += `
Your lock will expire in a few days.`;
user.send(message);
}
addModAction(`${id} was ${type} by Artemis. (${result.reason || `report from ${ticket.creator}`})`);
globalModlog(
`${isWeek ? "WEEK" : ""}${isName ? "NAME" : ""}LOCK`,
id,
(result.reason || `report from ${ticket.creator}`) + (result.proof ? ` PROOF: ${result.proof}` : "")
);
}
const actionHandlers = {
forcerename(user, result, ticket) {
if (typeof user === "string")
return;
const id = toID(user);
user.resetName();
user.trackRename = id;
Monitor.forceRenames.set(id, true);
user.send(
`|nametaken|Your name was detected to be breaking our name rules. ${result.reason ? `Reason: ${result.reason}. ` : ""}Please change it, or submit a help ticket by typing /ht in chat to appeal this action.`
);
Rooms.get("staff")?.add(
`|html|<span class="username">${id}</span> was automatically forced to choose a new name by Artemis (report from ${ticket.userid}).`
).update();
globalModlog(
"FORCERENAME",
id,
`username determined to be inappropriate due to a report by ${ticket.creator}`,
result.roomid
);
return `${id} was automatically forcerenamed. Thank you for reporting.`;
},
async namelock(user, result, ticket) {
await lock(user, result, ticket, false, true);
return `${toID(user)} was automatically namelocked. Thank you for reporting.`;
},
async weeknamelock(user, result, ticket) {
await lock(user, result, ticket, true, true);
return `${toID(user)} was automatically weeknamelocked. Thank you for reporting.`;
},
async lock(user, result, ticket) {
await lock(user, result, ticket);
return `${toID(user)} was automatically locked. Thank you for reporting.`;
},
async weeklock(user, result, ticket) {
await lock(user, result, ticket, true);
return `${toID(user)} was automatically weeklocked. Thank you for reporting.`;
},
warn(user, result, ticket) {
user = toID(user);
user = Users.get(user) || user;
if (typeof user === "object") {
user.send(`|c|~|/warn ${result.reason || ""}`);
} else {
Punishments.offlineWarns.set(user, result.reason);
}
addModAction(
`${user} was warned by Artemis. ${typeof user === "string" ? "while offline " : ""}(${result.reason || `report from ${ticket.creator}`})`
);
globalModlog(
"WARN",
user,
result.reason || `report from ${ticket.creator}`
);
return `${user} was automatically warned. Thank you for reporting.`;
}
};
function shouldNotProcess(message) {
return message.startsWith("/") && !message.startsWith("//") || // broadcasted chat command
message.startsWith("!");
}
async function getMessageAverages(messages) {
const counts = {};
const classified = [];
for (const message of messages) {
if (shouldNotProcess(message))
continue;
const res = await classifier.classify(message);
if (!res)
continue;
classified.push(res);
for (const k in res) {
if (!counts[k])
counts[k] = { count: 0, raw: 0 };
counts[k].count++;
counts[k].raw += res[k];
}
}
const averages = {};
for (const k in counts) {
averages[k] = counts[k].raw / counts[k].count;
}
return { averages, classified };
}
const checkers = {
async inapname(ticket) {
const id = toID(ticket.text[0]);
const user = Users.getExact(id);
if (user && !user.trusted) {
const result = await classifier.classify(user.name);
if (!result)
return;
const keys = ["identity_attack", "sexual_explicit", "severe_toxicity"];
const matched = keys.some((k) => result[k] >= 0.4);
if (matched) {
const modlog = await getModlog({
ip: user.latestIp,
actions: ["FORCERENAME", "NAMELOCK", "WEEKNAMELOCK"]
});
let { action } = determinePunishment("inapname", result, modlog);
if (!action)
action = "forcerename";
return /* @__PURE__ */ new Map([[user.id, {
action,
user,
result,
reason: "Username detected to be breaking username rules"
}]]);
}
}
},
async inappokemon(ticket) {
const actions = /* @__PURE__ */ new Map();
const links = [...(0, import_helptickets.getBattleLinks)(ticket.text[0]), ...(0, import_helptickets.getBattleLinks)(ticket.text[1])];
for (const link of links) {
const log = await (0, import_helptickets.getBattleLog)(link);
if (!log)
continue;
for (const [user, pokemon] of Object.entries(log.pokemon)) {
const userid = toID(user);
let result = null;
for (const set of pokemon) {
if (!set.name)
continue;
const results = await classifier.classify(set.name);
if (!results)
continue;
const curAction = determinePunishment("inappokemon", results, []).action;
if (curAction && (!result || supersedes(curAction, result.action))) {
result = { action: curAction, name: set.name, result: results, replay: link };
}
}
if (result) {
actions.set(user, {
action: result.action,
user: userid,
result: result.result,
reason: `Pokemon name detected to be breaking rules - '${result.name}'`,
roomid: link
});
}
}
}
if (actions.size)
return actions;
},
async battleharassment(ticket) {
const urls = (0, import_helptickets.getBattleLinks)(ticket.text[0]);
const actions = /* @__PURE__ */ new Map();
for (const url of urls) {
const log = await (0, import_helptickets.getBattleLog)(url);
if (!log)
continue;
const messages = {};
for (const message of log.log) {
const [username, text] = import_lib.Utils.splitFirst(message.slice(3), "|").map((f) => f.trim());
const id = toID(username);
if (!id)
continue;
if (!messages[id])
messages[id] = [];
messages[id].push(text);
}
for (const [id, messageList] of Object.entries(messages)) {
const { averages, classified } = await getMessageAverages(messageList);
const { action } = determinePunishment("battleharassment", averages, []);
if (action) {
const existingPunishment = actions.get(id);
if (!existingPunishment || supersedes(action, existingPunishment.action)) {
actions.set(id, {
action,
user: toID(id),
result: averages,
reason: `Not following rules in battles (https://${Config.routes.client}/${url})`,
proof: urls.join(", ")
});
}
}
for (const result of classified) {
const curPunishment = determinePunishment("battleharassment", result, [], true).action;
if (!curPunishment)
continue;
const exists = actions.get(id);
if (!exists || supersedes(curPunishment, exists.action)) {
actions.set(id, {
action: curPunishment,
user: toID(id),
result: averages,
reason: `Not following rules in battles (https://${Config.routes.client}/${url})`,
proof: urls.join(", ")
});
}
}
}
}
const creatorWasPunished = actions.get(ticket.userid);
if (creatorWasPunished) {
let displayReason = "You were punished for your behavior.";
if (actions.size !== 1) {
displayReason += ` ${actions.size - 1} other(s) were also punished.`;
}
creatorWasPunished.displayReason = displayReason;
}
if (actions.size)
return actions;
},
async pmharassment(ticket) {
const actions = /* @__PURE__ */ new Map();
const targetId = toID(ticket.text[0]);
const creator = ticket.userid;
if (!Config.getpmlog)
return;
const pmLog = await Config.getpmlog(targetId, creator);
const messages = {};
const ids = /* @__PURE__ */ new Set();
for (const { from, message, timestamp } of pmLog) {
if (Date.now() - new Date(timestamp).getTime() > PMLOG_IGNORE_TIME)
continue;
const id = toID(from);
ids.add(id);
if (!messages[id])
messages[id] = [];
messages[id].push(message);
}
for (const id of ids) {
let punishment;
const { averages, classified } = await getMessageAverages(messages[id]);
const curPunishment = determinePunishment("pmharassment", averages, []).action;
if (curPunishment) {
if (!punishment || supersedes(curPunishment, punishment)) {
punishment = curPunishment;
}
if (punishment) {
actions.set(id, {
action: punishment,
user: id,
result: {},
reason: `PM harassment (against ${ticket.userid === id ? targetId : ticket.userid})`
});
}
}
for (const result of classified) {
const { action } = determinePunishment("pmharassment", result, [], true);
if (!action)
continue;
const exists = actions.get(id);
if (!exists || supersedes(action, exists.action)) {
actions.set(id, {
action,
user: id,
result: {},
reason: `PM harassment (against ${ticket.userid === id ? targetId : ticket.userid})`
});
}
}
}
const creatorWasPunished = actions.get(ticket.userid);
if (creatorWasPunished) {
let displayReason = `You were punished for your behavior. `;
if (actions.has(targetId) && targetId !== ticket.userid) {
displayReason += ` The person you reported was also punished.`;
}
creatorWasPunished.displayReason = displayReason;
}
if (actions.size)
return actions;
}
};
const classifier = new Artemis.LocalClassifier();
async function runPunishments(ticket, typeId) {
let result = null;
if (checkers[typeId]) {
result = await checkers[typeId](ticket) || null;
}
if (result) {
if (settings.applyPunishments) {
const responses = [];
for (const res of result.values()) {
const curResult = await actionHandlers[res.action.toLowerCase()](res.user, res, ticket);
if (curResult)
responses.push([res.action, res.displayReason || curResult]);
if (toID(res.user) === ticket.creator) {
closeTicket(ticket, res.displayReason);
}
}
if (responses.length) {
import_lib.Utils.sortBy(responses, (r) => -ORDERED_PUNISHMENTS.indexOf(r[0]));
closeTicket(ticket, responses[0][1]);
} else {
closeTicket(ticket);
}
} else {
ticket.recommended = [];
for (const res of result.values()) {
Rooms.get("abuselog")?.add(
`|c|&|/log [${ticket.type} Monitor] Recommended: ${res.action}: for ${res.user} (${res.reason})`
).update();
ticket.recommended.push(`${res.action}: for ${res.user} (${res.reason})`);
}
}
}
}
const commands = {
aht: "autohelpticket",
autohelpticket: {
""() {
return this.parse(`/help autohelpticket`);
},
async test(target) {
checkAccess(this);
target = target.trim();
const response = await classifier.classify(target) || {};
let buf = import_lib.Utils.html`<strong>Results for "${target}":</strong><br />`;
buf += `<strong>Score breakdown:</strong><br />`;
for (const k in response) {
buf += `&bull; ${k}: ${response[k]}<br />`;
}
this.runBroadcast();
this.sendReplyBox(buf);
},
ap: "addpunishment",
add: "addpunishment",
addpunishment(target, room, user) {
checkAccess(this);
if (!toID(target))
return this.parse(`/help autohelpticket`);
const args = Chat.parseArguments(target);
const punishment = {};
for (const [k, list] of Object.entries(args)) {
if (k !== "type" && list.length > 1)
throw new Chat.ErrorMessage(`More than one ${k} param provided.`);
const val = list[0];
switch (k) {
case "type":
case "t":
const types = list.map((f) => f.toLowerCase().replace(/\s/g, "_"));
for (const type2 of types) {
if (!Artemis.LocalClassifier.ATTRIBUTES[type2]) {
return this.errorReply(
`Invalid classifier type '${type2}'. Valid types are ` + Object.keys(Artemis.LocalClassifier.ATTRIBUTES).join(", ")
);
}
}
if (!punishment.severity) {
punishment.severity = { certainty: 0, type: [] };
}
punishment.severity.type.push(...types);
break;
case "certainty":
case "c":
const num = parseFloat(val);
if (isNaN(num) || num < 0 || num > 1) {
return this.errorReply(`Certainty must be a number below 1 and above 0.`);
}
if (!punishment.severity) {
punishment.severity = { certainty: 0, type: [] };
}
punishment.severity.certainty = num;
break;
case "modlog":
case "m":
const count = parseInt(val);
if (isNaN(count) || count < 0) {
return this.errorReply(`Modlog count must be a number above 0.`);
}
punishment.modlogCount = count;
break;
case "ticket":
case "tt":
case "tickettype":
const type = toID(val);
if (!(type in checkers)) {
return this.errorReply(
`The ticket type '${type}' does not exist or is not supported. Supported types are ${Object.keys(checkers).join(", ")}.`
);
}
punishment.ticketType = type;
break;
case "p":
case "punishment":
const name = toID(val).toUpperCase();
if (!ORDERED_PUNISHMENTS.includes(name)) {
return this.errorReply(
`Punishment '${name}' not supported. Supported punishments: ${ORDERED_PUNISHMENTS.join(", ")}`
);
}
punishment.punishment = name;
break;
case "single":
case "s":
if (!this.meansYes(toID(val))) {
return this.errorReply(
`The 'single' value must always be 'on'. If you don't want it enabled, just do not use this argument type.`
);
}
punishment.isSingleMessage = true;
break;
}
}
if (!punishment.ticketType) {
return this.errorReply(`Must specify a ticket type to handle.`);
}
if (!punishment.punishment) {
return this.errorReply(`Must specify a punishment to apply.`);
}
if (!(punishment.severity?.certainty && punishment.severity?.type.length)) {
return this.errorReply(`A severity to monitor for must be specified (certainty).`);
}
for (const curP of settings.punishments) {
let matches = 0;
for (const k in curP) {
if (punishment[k] === curP[k]) {
matches++;
}
}
if (matches === Object.keys(punishment).length) {
return this.errorReply(`That punishment is already added.`);
}
}
settings.punishments.push(punishment);
saveSettings();
this.privateGlobalModAction(
`${user.name} added a ${punishment.punishment} punishment to the Artemis helpticket handler.`
);
this.globalModlog(`AUTOHELPTICKET ADDPUNISHMENT`, null, visualizePunishment(punishment));
},
dp: "deletepunishment",
delete: "deletepunishment",
deletepunishment(target, room, user) {
checkAccess(this);
const num = parseInt(target) - 1;
if (isNaN(num))
return this.parse(`/h autohelpticket`);
const punishment = settings.punishments[num];
if (!punishment)
return this.errorReply(`There is no punishment at index ${num + 1}.`);
settings.punishments.splice(num, 1);
this.privateGlobalModAction(
`${user.name} removed the Artemis helpticket ${punishment.punishment} punishment indexed at ${num + 1}`
);
this.globalModlog(`AUTOHELPTICKET REMOVE`, null, visualizePunishment(punishment));
},
vp: "viewpunishments",
view: "viewpunishments",
viewpunishments() {
checkAccess(this);
let buf = `<strong>Artemis helpticket punishments</strong><hr />`;
if (!settings.punishments.length) {
buf += `None.`;
return this.sendReplyBox(buf);
}
buf += settings.punishments.map(
(curP, i) => `<strong>${i + 1}:</strong> ${visualizePunishment(curP)}`
).join("<br />");
return this.sendReplyBox(buf);
},
togglepunishments(target, room, user) {
checkAccess(this);
let message;
if (this.meansYes(target)) {
if (settings.applyPunishments) {
return this.errorReply(`Automatic punishments are already enabled.`);
}
settings.applyPunishments = true;
message = `${user.name} enabled automatic punishments for the Artemis ticket handler`;
} else if (this.meansNo(target)) {
if (!settings.applyPunishments) {
return this.errorReply(`Automatic punishments are already disabled.`);
}
settings.applyPunishments = false;
message = `${user.name} disabled automatic punishments for the Artemis ticket handler`;
} else {
return this.errorReply(`Invalid setting. Must be 'on' or 'off'.`);
}
this.privateGlobalModAction(message);
this.globalModlog(`AUTOHELPTICKET TOGGLE`, null, settings.applyPunishments ? "on" : "off");
saveSettings();
},
stats(target) {
if (!target)
target = Chat.toTimestamp(new Date()).split(" ")[0];
return this.parse(`/j view-autohelpticket-stats-${target}`);
},
logs(target) {
if (!target)
target = Chat.toTimestamp(new Date()).split(" ")[0];
return this.parse(`/j view-autohelpticket-logs-${target}`);
},
resolve(target, room, user) {
this.checkCan("lock");
const [ticketId, result] = import_lib.Utils.splitFirst(target, ",").map(toID);
const ticket = import_helptickets.tickets[ticketId];
if (!ticket?.open) {
return this.popupReply(`The user '${ticketId}' does not have a ticket open at present.`);
}
if (!["success", "failure"].includes(result)) {
return this.popupReply(`The result must be 'success' or 'failure'.`);
}
(ticket.state || (ticket.state = {})).recommendResult = result;
(0, import_helptickets.writeTickets)();
Chat.refreshPageFor(`help-text-${ticketId}`, "staff");
}
},
autohelptickethelp: [
`/aht addpunishment [args] - Adds a punishment with the given [args]. Requires: whitelist &`,
`/aht deletepunishment [index] - Deletes the automatic helpticket punishment at [index]. Requires: whitelist &`,
`/aht viewpunishments - View automatic helpticket punishments. Requires: whitelist &`,
`/aht togglepunishments [on | off] - Turn [on | off] automatic helpticket punishments. Requires: whitelist &`,
`/aht stats - View success rates of the Artemis ticket handler. Requires: whitelist &`
]
};
const pages = {
autohelpticket: {
async stats(query, user) {
checkAccess(this);
let month;
if (query.length) {
month = /[0-9]{4}-[0-9]{2}/.exec(query.join("-"))?.[0];
} else {
month = Chat.toTimestamp(new Date()).split(" ")[0].slice(0, -3);
}
if (!month) {
return this.errorReply(`Invalid month. Must be in YYYY-MM format.`);
}
this.title = `[Artemis Ticket Stats] ${month}`;
this.setHTML(`<div class="pad"><h3>Artemis ticket stats</h3><hr />Searching...`);
const found = await import_helptickets.HelpTicket.getTextLogs(["recommendResult"], month);
const percent = (numerator, denom) => Math.floor(numerator / denom * 100);
let buf = `<div class="pad">`;
buf += `<button style="float:right;" class="button" name="send" value="/join ${this.pageid}">`;
buf += `<i class="fa fa-refresh"></i> Refresh</button>`;
buf += `<h3>Artemis ticket stats</h3><hr />`;
const dayStats = {};
const total = { successes: 0, failures: 0, total: 0 };
const failed = [];
for (const ticket of found) {
const day = Chat.toTimestamp(new Date(ticket.created)).split(" ")[0];
if (!dayStats[day])
dayStats[day] = { successes: 0, failures: 0, total: 0 };
dayStats[day].total++;
total.total++;
switch (ticket.state.recommendResult) {
case "success":
dayStats[day].successes++;
total.successes++;
break;
case "failure":
dayStats[day].failures++;
total.failures++;
failed.push([ticket.userid, ticket.type]);
break;
}
}
buf += `<strong>Total:</strong> ${total.total}<br />`;
buf += `<strong>Success rate:</strong> ${percent(total.successes, total.total)}% (${total.successes})<br />`;
buf += `<strong>Failure rate:</strong> ${percent(total.failures, total.total)}% (${total.failures})<br />`;
buf += `<strong>Day stats:</strong><br />`;
buf += `<div class="ladder pad"><table>`;
let header = "";
let data = "";
const sortedDays = import_lib.Utils.sortBy(Object.keys(dayStats), (d) => new Date(d).getTime());
for (const [i, day] of sortedDays.entries()) {
const cur = dayStats[day];
if (!cur.total)
continue;
header += `<th>${day.split("-")[2]} (${cur.total})</th>`;
data += `<td><small>${cur.successes} (${percent(cur.successes, cur.total)}%)`;
if (cur.failures) {
data += ` | ${cur.failures} (${percent(cur.failures, cur.total)}%)`;
} else {
data += " | 0 (0%)";
}
data += "</small></td>";
if ((i + 1) % 5 === 0 && sortedDays[i + 1]) {
buf += `<tr>${header}</tr><tr>${data}</tr>`;
buf += `</div></table>`;
buf += `<div class="ladder pad"><table>`;
header = "";
data = "";
}
}
buf += `<tr>${header}</tr><tr>${data}</tr>`;
buf += `</div></table>`;
buf += `<br />`;
if (failed.length) {
buf += `<details class="readmore"><summary>Marked as inaccurate</summary>`;
buf += failed.map(([userid, type]) => `<a href="/view-help-text-${userid}">${userid}</a> (${type})`).join("<br />");
buf += `</details>`;
}
return buf;
},
async logs(query, user) {
checkAccess(this);
let month;
if (query.length) {
month = /[0-9]{4}-[0-9]{2}/.exec(query.join("-"))?.[0];
} else {
month = Chat.toTimestamp(new Date()).split(" ")[0].slice(0, -3);
}
if (!month) {
return this.errorReply(`Invalid month. Must be in YYYY-MM format.`);
}
this.title = `[Artemis Ticket Logs]`;
let buf = `<div class="pad"><h3>Artemis ticket logs</h3><hr />`;
const allHits = await import_helptickets.HelpTicket.getTextLogs(["recommended"], month);
import_lib.Utils.sortBy(allHits, (h) => -h.created);
if (allHits.length) {
buf += `<strong>All hits:</strong><hr />`;
for (const hit of allHits) {
if (!hit.recommended)
continue;
buf += `<a href="/view-help-text-${hit.userid}">${hit.userid}</a> (${hit.type}) `;
buf += `[${Chat.toTimestamp(new Date(hit.created))}]<br />`;
buf += import_lib.Utils.html`&bull; <code><small>${hit.recommended.join(", ")}</small></code><hr />`;
}
} else {
buf += `<div class="message-error">No hits found.</div>`;
}
return buf;
}
}
};
//# sourceMappingURL=helptickets-auto.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/helptickets-auto.ts"],
"sourcesContent": ["import {FS, Utils} from '../../lib';\r\nimport type {ModlogSearch, ModlogEntry} from '../modlog';\r\nimport {\r\n\tTicketState, getBattleLog, getBattleLinks,\r\n\twriteTickets, notifyStaff, writeStats, HelpTicket,\r\n\ttickets,\r\n} from './helptickets';\r\nimport * as Artemis from '../artemis';\r\n\r\nconst ORDERED_PUNISHMENTS = ['WARN', 'FORCERENAME', 'LOCK', 'NAMELOCK', 'WEEKLOCK', 'WEEKNAMELOCK'];\r\nconst PMLOG_IGNORE_TIME = 24 * 60 * 60 * 1000;\r\nconst WHITELIST = ['mia'];\r\n\r\nexport interface AutoPunishment {\r\n\tmodlogCount?: number;\r\n\tseverity?: {type: string[], certainty: number};\r\n\t/**\r\n\t * Should it be run on just one message?\r\n\t * or is it safe to run on averages (for the types that use averages)\r\n\t */\r\n\tisSingleMessage?: boolean;\r\n\tpunishment: string;\r\n\tticketType: string;\r\n}\r\n\r\nexport interface AutoSettings {\r\n\tpunishments: AutoPunishment[];\r\n\tapplyPunishments: boolean;\r\n}\r\n\r\nconst defaults: AutoSettings = {\r\n\tpunishments: [{\r\n\t\tticketType: 'inapname',\r\n\t\tpunishment: 'forcerename',\r\n\t\tseverity: {type: ['sexual_explicit', 'severe_toxicity', 'identity_attack'], certainty: 0.4},\r\n\t}, {\r\n\t\tticketType: 'pmharassment',\r\n\t\tpunishment: 'warn',\r\n\t\tseverity: {type: ['sexual_explicit', 'severe_toxicity', 'identity_attack'], certainty: 0.15},\r\n\t}],\r\n\tapplyPunishments: false,\r\n};\r\n\r\nexport const settings: AutoSettings = (() => {\r\n\ttry {\r\n\t\t// spreading w/ default means that\r\n\t\t// adding new things won't crash by not existing\r\n\t\treturn {...defaults, ...JSON.parse(FS('config/chat-plugins/ht-auto.json').readSync())};\r\n\t} catch {\r\n\t\treturn defaults;\r\n\t}\r\n})();\r\n\r\nfunction saveSettings() {\r\n\treturn FS('config/chat-plugins/ht-auto.json').writeUpdate(() => JSON.stringify(settings));\r\n}\r\n\r\nfunction visualizePunishment(punishment: AutoPunishment) {\r\n\tconst buf = [`punishment: ${punishment.punishment?.toUpperCase()}`];\r\n\tbuf.push(`ticket type: ${punishment.ticketType}`);\r\n\tif (punishment.severity) {\r\n\t\tbuf.push(`severity: ${punishment.severity.certainty} (for ${punishment.severity.type.join(', ')})`);\r\n\t}\r\n\tif (punishment.modlogCount) {\r\n\t\tbuf.push(`required modlog: ${punishment.modlogCount}`);\r\n\t}\r\n\tif (punishment.isSingleMessage) {\r\n\t\tbuf.push(`for single messages only`);\r\n\t}\r\n\treturn buf.join(', ');\r\n}\r\n\r\nfunction checkAccess(context: Chat.CommandContext | Chat.PageContext) {\r\n\tif (!WHITELIST.includes(context.user.id)) context.checkCan('bypassall');\r\n}\r\n\r\nexport function punishmentsFor(type: string) {\r\n\treturn settings.punishments.filter(t => t.ticketType === type);\r\n}\r\n\r\n/** Is punishment1 higher than punishment2 on the list? */\r\nfunction supersedes(p1: string, p2: string) {\r\n\treturn ORDERED_PUNISHMENTS.indexOf(p1) > ORDERED_PUNISHMENTS.indexOf(p2);\r\n}\r\n\r\nexport function determinePunishment(\r\n\tticketType: string, results: Record<string, number>, modlog: ModlogEntry[], isSingleMessage = false\r\n) {\r\n\tconst punishments = punishmentsFor(ticketType);\r\n\tlet action: string | null = null;\r\n\tconst types = [];\r\n\tUtils.sortBy(punishments, p => -ORDERED_PUNISHMENTS.indexOf(p.punishment));\r\n\tfor (const punishment of punishments) {\r\n\t\tif (isSingleMessage && !punishment.isSingleMessage) continue;\r\n\t\tif (punishment.modlogCount && modlog.length < punishment.modlogCount) continue;\r\n\t\tif (punishment.severity) {\r\n\t\t\tlet hit = false;\r\n\t\t\tfor (const type of punishment.severity.type) {\r\n\t\t\t\tif (results[type] < punishment.severity.certainty) continue;\r\n\t\t\t\thit = true;\r\n\t\t\t\ttypes.push(type);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (!hit) continue;\r\n\t\t}\r\n\t\tif (!action || supersedes(punishment.punishment, action)) {\r\n\t\t\taction = punishment.punishment;\r\n\t\t}\r\n\t}\r\n\treturn {action, types};\r\n}\r\n\r\nexport function globalModlog(action: string, user: User | ID | null, note: string, roomid?: string) {\r\n\tuser = Users.get(user) || user;\r\n\tvoid Rooms.Modlog.write(roomid || 'global', {\r\n\t\taction,\r\n\t\tip: user && typeof user === 'object' ? user.latestIp : undefined,\r\n\t\tuserid: toID(user) || undefined,\r\n\t\tloggedBy: 'artemis' as ID,\r\n\t\tnote,\r\n\t});\r\n}\r\n\r\nexport function addModAction(message: string) {\r\n\tRooms.get('staff')?.add(`|c|&|/log ${message}`).update();\r\n}\r\n\r\nexport async function getModlog(params: {user?: ID, ip?: string, actions?: string[]}) {\r\n\tconst search: ModlogSearch = {\r\n\t\tnote: [],\r\n\t\tuser: [],\r\n\t\tip: [],\r\n\t\taction: [],\r\n\t\tactionTaker: [],\r\n\t};\r\n\tif (params.user) search.user = [{search: params.user, isExact: true}];\r\n\tif (params.ip) search.ip = [{search: params.ip}];\r\n\tif (params.actions) search.action = params.actions.map(s => ({search: s}));\r\n\tconst res = await Rooms.Modlog.search('global', search);\r\n\treturn res?.results || [];\r\n}\r\n\r\nfunctLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA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IAAI,OAAO,GAAG;AAAA,MACnB,gCAAgC,mFACyC,OAAO;AAAA,IACjF,EAAE,OAAO;AACT;AAAA,MACC;AAAA,MAAe;AAAA,MAAI,8DAA8D,OAAO;AAAA,MAAW,OAAO;AAAA,IAC3G;AACA,WAAO,GAAG;AAAA,EACX;AAAA,EACA,MAAM,SAAS,MAAM,QAAQ,QAAQ;AACpC,UAAM,KAAK,MAAM,QAAQ,QAAQ,OAAO,IAAI;AAC5C,WAAO,GAAG,KAAK,IAAI;AAAA,EACpB;AAAA,EACA,MAAM,aAAa,MAAM,QAAQ,QAAQ;AACxC,UAAM,KAAK,MAAM,QAAQ,QAAQ,MAAM,IAAI;AAC3C,WAAO,GAAG,KAAK,IAAI;AAAA,EACpB;AAAA,EACA,MAAM,KAAK,MAAM,QAAQ,QAAQ;AAChC,UAAM,KAAK,MAAM,QAAQ,MAAM;AAC/B,WAAO,GAAG,KAAK,IAAI;AAAA,EACpB;AAAA,EACA,MAAM,SAAS,MAAM,QAAQ,QAAQ;AACpC,UAAM,KAAK,MAAM,QAAQ,QAAQ,IAAI;AACrC,WAAO,GAAG,KAAK,IAAI;AAAA,EACpB;AAAA,EACA,KAAK,MAAM,QAAQ,QAAQ;AAC1B,WAAO,KAAK,IAAI;AAChB,WAAO,MAAM,IAAI,IAAI,KAAK;AAC1B,QAAI,OAAO,SAAS,UAAU;AAC7B,WAAK,KAAK,cAAc,OAAO,UAAU,IAAI;AAAA,Line truncated
"names": ["type"]
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/helptickets.ts"],
"sourcesContent": ["import {FS, Utils, Net, ProcessManager} from '../../lib';\r\nimport {getCommonBattles} from '../chat-commands/info';\r\nimport {checkRipgrepAvailability} from '../config-loader';\r\nimport type {Punishment} from '../punishments';\r\nimport type {PartialModlogEntry, ModlogID} from '../modlog';\r\nimport {runPunishments} from './helptickets-auto';\r\n\r\nconst TICKET_FILE = 'config/tickets.json';\r\nconst SETTINGS_FILE = 'config/chat-plugins/ticket-settings.json';\r\nconst TICKET_CACHE_TIME = 24 * 60 * 60 * 1000; // 24 hours\r\nconst TICKET_BAN_DURATION = 48 * 60 * 60 * 1000; // 48 hours\r\nexport const BATTLES_REGEX = /\\bbattle-(?:[a-z0-9]+)-(?:[0-9]+)(?:-[a-z0-9]{31}pw)?/g;\r\nexport const REPLAY_REGEX = new RegExp(\r\n\t`${Utils.escapeRegex(Config.routes.replays)}/(?:[a-z0-9]-)?(?:[a-z0-9]+)-(?:[0-9]+)(?:-[a-z0-9]{31}pw)?`, \"g\"\r\n);\r\nconst REPORT_NAMECOLORS: {[k: string]: string} = {\r\n\tp1: 'DodgerBlue',\r\n\tp2: 'Crimson',\r\n\tp3: '#FBa92C',\r\n\tp4: '#228B22',\r\n\tother: '#00000',\r\n};\r\n\r\nPunishments.addPunishmentType({\r\n\ttype: 'TICKETBAN',\r\n\tdesc: 'banned from creating help tickets',\r\n});\r\n\r\ninterface TicketSettings {\r\n\t// {[ticketType]: {[button title]: response}}\r\n\tresponses: {[ticketType: string]: {[title: string]: string}};\r\n}\r\n\r\nexport interface TicketState {\r\n\tcreator: string;\r\n\tuserid: ID;\r\n\topen: boolean;\r\n\tactive: boolean;\r\n\ttype: string;\r\n\tcreated: number;\r\n\tclaimed: string | null;\r\n\tip: string;\r\n\tneedsDelayWarning?: boolean;\r\n\toffline?: boolean;\r\n\t// text ticket properties\r\n\t/** [main text, context] */\r\n\ttext?: [string, string];\r\n\tresolved?: ResolvedTicketInfo;\r\n\tmeta?: string;\r\n\tnotes?: {[userid: string]: string};\r\n\t/** Extra info that they might need for displays or whatnot.\r\n\t * Use `TextTicketInfo#getState` to set it at creation (store properties of the user object, etc)\r\n\t */\r\n\tstate?: AnyObject & {claimTime?: number};\r\n\t/** Recommendations from the Artemis monitor, if it is set to only recommend. */\r\n\trecommended?: string[];\r\n}\r\n\r\ninterface ResolvedTicketInfo {\r\n\ttime: number;\r\n\tresult: string;\r\n\tby: string;\r\n\tseen: boolean;\r\n\tstaffReason: string;\r\n\t/** <small> note under the resolved */\r\n\tnote?: string;\r\n}\r\n\r\nexport interface TextTicketInfo {\r\n\tchecker?: (\r\n\t\tinput: string, context: string, pageId: string, user: User, reportTarget?: string\r\n\t) => boolean | string[] | Promise<boolean | string[]>;\r\n\ttitle: string;\r\n\tdisclaimer?: string;\r\n\t/**\r\n\t * Set this to prompt for more specific context beyond\r\n\t * \"Do you have any other information you want to provide? (this is optional)\"\r\n\t */\r\n\tcontextMessage?: string;\r\n\t/** Should this be displayed with all the other tickets of the type on a singular page? */\r\n\tlistOnly?: boolean;\r\n\tgetReviewDisplay: (\r\n\t\tticket: TicketState & {text: [string, string]}, staff: User, conn: Connection, state?: AnyObject\r\n\t) => Promise<string | void> | string | void;\r\n\tonSubmit?: (ticket: TicketState, text: [string, string], submitter: User, conn: Connection) => void | Promise<void>;\r\n\tgetState?: (ticket: TicketState, user: User) => AnyObject;\r\n}\r\n\r\ninterface BattleInfo {\r\n\tlog: string[];\r\n\turl: string;\r\n\ttitle: string;\r\n\tplayers: {p1: ID, p2: ID, p3?: ID, p4?: ID};\r\n\tpokemon: Record<string, {species: string, name?: string}[]>;\r\n}\r\n\r\ntype TicketResult = 'approved' | 'valid' | 'assisted' | 'denied' | 'invalid' | 'unassisted' | 'ticketban' | 'deleted';\r\n\r\nconst defaults: TicketSettings = {responses: {}};\r\n\r\nexport const tickets: {[k: string]: TicketState} = {};\r\nexport const settings: TicketSettings = (() => {\r\n\ttry {\r\n\t\t// this ensures that if new settings are added to the defaults, they are added\r\n\t\t// to the JSON as well\r\n\t\treturn {...defaults, ...JSON.parse(FS(SETTINGS_FILE).readSync())};\r\n\t} catch {\r\n\t\treturn {...defaults};\r\n\t}\r\n})();\r\n\r\ntry {\r\n\tconst ticketData = JSON.parse(FS(TICKET_FILE).readSync());\r\n\tfor (const t in ticketData) {\r\n\t\tconst ticket = ticketData[t];\r\n\t\tif (ticket.banned) {\r\n\t\t\tif (ticket.expires && ticket.expires <= Date.now()) continue;\r\n\t\t\tvoid Punishments.punish(ticket.userid, {\r\n\t\t\t\ttype: 'TICKETBAN',\r\n\t\t\t\tid: ticket.userid,\r\n\t\t\t\texpireTime: ticket.expires,\r\n\t\t\t\treason: ticket.reason,\r\n\t\t\t}, false);\r\n\t\t\tdelete ticketData[t]; // delete the old format\r\n\t\t} else {\r\n\t\t\tif (ticket.created + TICKET_CACHE_TIME <= Date.now()) {\r\n\t\t\t\t// Tickets that have been open for 24+ hours will be automatically closed.\r\n\t\t\t\tconst ticketRoom = Rooms.get(`help-${ticket.userid}`) as ChatRoom | null;\r\n\t\t\t\tif (ticketRoom) {\r\n\t\t\t\t\tconst ticketGame = ticketRoom.game as HelpTicket;\r\n\t\t\t\t\tticketGame.writeStats(false);\r\n\t\t\t\t\tticketRoom.expire();\r\n\t\t\t\t} else if (ticket.text && ticket.Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAA6C;AAC7C,kBAA+B;AAC/B,2BAAuC;AAGvC,8BAA6B;AAE7B,MAAM,cAAc;AACpB,MAAM,gBAAgB;AACtB,MAAM,oBAAoB,KAAK,KAAK,KAAK;AACzC,MAAM,sBAAsB,KAAK,KAAK,KAAK;AACpC,MAAM,gBAAgB;AACtB,MAAM,eAAe,IAAI;AAAA,EAC/B,GAAG,iBAAM,YAAY,OAAO,OAAO,OAAO;AAAA,EAAgE;AAC3G;AACA,MAAM,oBAA2C;AAAA,EAChD,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,OAAO;AACR;AAEA,YAAY,kBAAkB;AAAA,EAC7B,MAAM;AAAA,EACN,MAAM;AACP,CAAC;AAwED,MAAM,WAA2B,EAAC,W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KAAK,gBAAgB,SAAS,KAAK,OAAO,CAAC,IACjH;AACD,WAAK,KAAK,IAAI,aAAa,KAAK,KAAK,6GAA6G;AAClJ,WAAK,KAAK,IAAI,aAAa,KAAK,KAAK,8FAA8F;AACnI,WAAK,KAAK,OAAO;AACjB,aAAO;AAAA,IACR;AACA,SAAK,CAAC,KAAK,WAAW,KAAK,OAAO,WAAW,KAAK,OAAO,CAAC,KAAK,OAAO,QAAQ;AAC7E,WAALine truncated
"names": ["buf", "type", "helpRoom"]
}
+570
View File
@@ -0,0 +1,570 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var hosts_exports = {};
__export(hosts_exports, {
commands: () => commands,
pages: () => pages,
visualizeRangeList: () => visualizeRangeList
});
module.exports = __toCommonJS(hosts_exports);
var import_lib = require("../../lib");
const HOST_SUFFIXES = ["res", "proxy", "mobile"];
const SUFFIX_ALIASES = {
residential: "res"
};
const WHITELISTED_USERIDS = [];
function checkCanPerform(context, user, permission = "lockdown") {
if (!WHITELISTED_USERIDS.includes(user.id))
context.checkCan(permission);
}
function getHostType(type) {
type = toID(type);
if (HOST_SUFFIXES.includes(type))
return type;
if (SUFFIX_ALIASES[type])
return SUFFIX_ALIASES[type];
throw new Chat.ErrorMessage(`'${type}' is not a valid host type. Please specify one of ${HOST_SUFFIXES.join(", ")}.`);
}
function visualizeRangeList(ranges) {
let html = `<tr><th>Lowest IP address</th><th>Highest IP address</th><th>Host</th></tr>`;
for (const range of ranges) {
html += `<tr>`;
html += `<td>${IPTools.numberToIP(range.minIP)}</td>`;
html += `<td>${IPTools.numberToIP(range.maxIP)}</td>`;
html += import_lib.Utils.html`<td>${range.host}</td>`;
html += `</tr>`;
}
return html;
}
function formatRange(range, includeModlogBrackets) {
const startBracket = includeModlogBrackets ? "[" : "";
const endBracket = includeModlogBrackets ? "]" : "";
let result = `${startBracket}${IPTools.numberToIP(range.minIP)}${endBracket}`;
result += `-${startBracket}${IPTools.numberToIP(range.maxIP)}${endBracket}`;
if (range.host)
result += ` (${range.host})`;
return result;
}
const pages = {
proxies(query, user) {
this.title = "[Proxies]";
checkCanPerform(this, user, "globalban");
const openProxies = [...IPTools.singleIPOpenProxies];
const proxyHosts = [...IPTools.proxyHosts];
import_lib.Utils.sortBy(openProxies, (ip) => {
const number = IPTools.ipToNumber(ip);
if (number === null) {
Rooms.get("upperstaff")?.add(`|error|Invalid IP address in IPTools.singleIPOpenProxies: '${ip}'`);
return -1;
}
return number;
});
proxyHosts.sort();
IPTools.sortRanges();
let html = `<div class="ladder pad"><h2>Single IP proxies:</h2><table><tr><th>IP</th><th>Type</th></tr>`;
for (const proxyIP of openProxies) {
html += `<tr><td>${proxyIP}</td><td>Single IP open proxy</td></tr>`;
}
html += `</table></div>`;
html += `<div class="ladder pad"><h2>Proxy hosts:</h2><table><tr><th>Host</th><th>Type</th></tr>`;
for (const proxyHost of proxyHosts) {
html += `<tr><td>${proxyHost}</td><td>Proxy host</td></tr>`;
}
html += `</table></div>`;
html += `<div class="ladder pad"><h2>Proxy IP Ranges:</h2><table>`;
html += visualizeRangeList(IPTools.ranges.filter((r) => r.host?.endsWith("/proxy")));
html += `</table></div>`;
return html;
},
hosts(query, user) {
this.title = "[Hosts]";
checkCanPerform(this, user, "globalban");
const type = toID(query[0]) || "all";
IPTools.sortRanges();
const mobileHosts = ["all", "mobile"].includes(type) ? [...IPTools.mobileHosts] : [];
const residentialHosts = ["all", "residential", "res"].includes(type) ? [...IPTools.residentialHosts] : [];
const hostRanges = ["all", "ranges", "isps"].includes(type) ? IPTools.ranges.filter((r) => r.host && !r.host.endsWith("/proxy")) : [];
mobileHosts.sort();
residentialHosts.sort();
let html = `<div class="ladder pad"><h2>Mobile hosts:</h2><table><tr><th>Host</th><th>Type</th></tr>`;
for (const mobileHost of mobileHosts) {
html += `<tr><td>${mobileHost}</td><td>Mobile host</td></tr>`;
}
html += `</table></div>`;
html += `<div class="ladder pad"><h2>Residential hosts:</h2><table><tr><th>Host</th><th>Type</th></tr>`;
for (const resHost of residentialHosts) {
html += `<tr><td>${resHost}</td><td>Residential host</td></tr>`;
}
html += `</table></div>`;
html += `<div class="ladder pad"><h2>ISP IP Ranges:</h2><table>`;
html += visualizeRangeList(hostRanges);
html += `</table></div>`;
return html;
},
ranges(query, user) {
this.title = "[IP Ranges]";
checkCanPerform(this, user, "globalban");
const type = toID(query[0]) || "all";
IPTools.sortRanges();
let html = ``;
if (["all", "mobile"].includes(type)) {
html += `<div class="ladder pad"><h2>Mobile IP Ranges:</h2><table>`;
html += visualizeRangeList(IPTools.ranges.filter((range) => range.host?.endsWith("/mobile")));
html += `</table></div>`;
}
if (["all", "res", "residential"].includes(type)) {
html += `<div class="ladder pad"><h2>Residential IP Ranges:</h2><table>`;
html += visualizeRangeList(IPTools.ranges.filter((range) => range.host?.endsWith("/res")));
html += `</table></div>`;
}
if (["all", "proxy", "proxies"].includes(type)) {
html += `<div class="ladder pad"><h2>Proxy IP Ranges:</h2><table>`;
html += visualizeRangeList(IPTools.ranges.filter((range) => range.host?.endsWith("/proxy")));
html += `</table></div>`;
}
if (["all", "openproxy"].includes(type)) {
html += `<div class="ladder pad"><h2>Single-IP Open Proxies:</h2><table>`;
for (const ip of IPTools.singleIPOpenProxies) {
html += `<tr><td>${ip}</td></tr>`;
}
html += `</table></div>`;
}
return html;
},
sharedipblacklist(args, user, connection) {
this.title = `[Shared IP Blacklist]`;
checkCanPerform(this, user, "lock");
let buf = `<div class="pad"><h2>IPs blocked from being marked as shared</h2>`;
if (!Punishments.sharedIpBlacklist.size) {
buf += `<p>None currently.</p>`;
} else {
buf += `<div class="ladder"><table><tr><th>IP</th><th>Reason</th></tr>`;
const sortedSharedIPBlacklist = [...Punishments.sharedIpBlacklist];
import_lib.Utils.sortBy(sortedSharedIPBlacklist, ([ipOrRange]) => {
if (IPTools.ipRegex.test(ipOrRange)) {
const number = IPTools.ipToNumber(ipOrRange);
if (number === null) {
Monitor.error(`Invalid blacklisted-from-markshared IP: '${ipOrRange}`);
return -1;
}
return number;
}
return IPTools.stringToRange(ipOrRange).minIP;
});
for (const [ip, reason] of sortedSharedIPBlacklist) {
buf += `<tr><td>${ip}</td><td>${reason}</td></tr>`;
}
buf += `</table></div>`;
}
buf += `</div>`;
return buf;
},
sharedips(args, user, connection) {
this.title = `[Shared IPs]`;
checkCanPerform(this, user, "globalban");
let buf = `<div class="pad"><h2>IPs marked as shared</h2>`;
if (!Punishments.sharedIps.size) {
buf += `<p>None currently.</p>`;
} else {
buf += `<div class="ladder"><table><tr><th>IP</th><th>Location</th></tr>`;
const sortedSharedIPs = [...Punishments.sharedIps];
import_lib.Utils.sortBy(sortedSharedIPs, ([ip]) => {
const number = IPTools.ipToNumber(ip);
if (number === null) {
Monitor.error(`Invalid shared IP address: '${ip}'`);
return -1;
}
return number;
});
for (const [ip, location] of sortedSharedIPs) {
buf += `<tr><td>${ip}</td><td>${location}</td></tr>`;
}
buf += `</table></div>`;
}
buf += `</div>`;
return buf;
}
};
const commands = {
dc: "ipranges",
datacenter: "ipranges",
datacenters: "ipranges",
iprange: "ipranges",
ipranges: {
"": "help",
help() {
return this.parse("/help ipranges");
},
show: "view",
view(target, room, user) {
checkCanPerform(this, user, "globalban");
const types = ["all", "residential", "res", "mobile", "proxy", "openproxy"];
const type = target ? toID(target) : "all";
if (!types.includes(type)) {
return this.errorReply(`'${type}' isn't a valid host type. Specify one of ${types.join(", ")}.`);
}
return this.parse(`/join view-ranges-${type}`);
},
viewhelp: [
`/ipranges view - View the list of all IP ranges. Requires: hosts manager @ &`,
`/ipranges view [type] - View the list of a particular type of IP range ('residential', 'mobile', or 'proxy'). Requires: hosts manager @ &`
],
// Originally by Zarel
widen: "add",
add(target, room, user, connection, cmd) {
checkCanPerform(this, user, "globalban");
if (!target)
return this.parse("/help ipranges add");
const widen = cmd.includes("widen");
const [typeString, stringRange, host] = target.split(",").map((part) => part.trim());
if (!host || !IPTools.hostRegex.test(host)) {
return this.errorReply(`Invalid data: ${target}`);
}
const type = getHostType(typeString);
const range = IPTools.stringToRange(stringRange);
if (!range)
return this.errorReply(`Couldn't parse IP range '${stringRange}'.`);
range.host = `${IPTools.urlToHost(host)}?/${type}`;
IPTools.sortRanges();
let result;
try {
result = IPTools.checkRangeConflicts(range, IPTools.ranges, widen);
} catch (e) {
return this.errorReply(e.message);
}
if (typeof result === "number") {
IPTools.removeRange(IPTools.ranges[result].minIP, IPTools.ranges[result].maxIP);
}
IPTools.addRange(range);
this.privateGlobalModAction(`${user.name} added the IP range ${formatRange(range)} to the list of ${type} ranges.`);
this.globalModlog("IPRANGE ADD", null, formatRange(range, true));
},
addhelp: [
`/ipranges add [type], [low]-[high], [host] - Adds an IP range. Requires: hosts manager &`,
`/ipranges widen [type], [low]-[high], [host] - Adds an IP range, allowing a new range to completely cover an old range. Requires: hosts manager &`,
`For example: /ipranges add proxy, 5.152.192.0 - 5.152.223.255, redstation.com`,
`Get datacenter info from whois; [low], [high] are the range in the last inetnum; [type] is one of res, proxy, or mobile.`
],
remove(target, room, user) {
checkCanPerform(this, user);
if (!target)
return this.parse("/help ipranges remove");
const range = IPTools.stringToRange(target);
if (!range)
return this.errorReply(`Couldn't parse the IP range '${target}'.`);
if (!IPTools.getRange(range.minIP, range.maxIP))
return this.errorReply(`No IP range found at '${target}'.`);
void IPTools.removeRange(range.minIP, range.maxIP);
this.privateGlobalModAction(`${user.name} removed the IP range ${formatRange(range)}.`);
this.globalModlog("IPRANGE REMOVE", null, formatRange(range, true));
},
removehelp: [
`/ipranges remove [low IP]-[high IP] - Removes an IP range. Requires: hosts manager &`,
`Example: /ipranges remove 5.152.192.0-5.152.223.255`
],
rename(target, room, user) {
checkCanPerform(this, user);
if (!target)
return this.parse("/help ipranges rename");
const [type, rangeString, url] = target.split(",").map((part) => part.trim());
if (!url) {
return this.parse("/help ipranges rename");
}
const toRename = IPTools.stringToRange(rangeString);
if (!toRename)
return this.errorReply(`Couldn't parse IP range '${rangeString}'.`);
const exists = IPTools.getRange(toRename.minIP, toRename.maxIP);
if (!exists)
return this.errorReply(`No IP range found at '${rangeString}'.`);
const range = {
minIP: toRename.minIP,
maxIP: toRename.maxIP,
host: `${IPTools.urlToHost(url)}?/${type}`
};
void IPTools.addRange(range);
this.privateGlobalModAction(`${user.name} renamed the IP range ${formatRange(toRename)} to ${range.host}.`);
this.globalModlog("IPRANGE RENAME", null, `IP range ${formatRange(toRename, true)} to ${range.host}`);
},
renamehelp: [
`/ipranges rename [type], [low IP]-[high IP], [host] - Changes the host an IP range resolves to. Requires: hosts manager &`
]
},
iprangeshelp() {
const help = [
`<code>/ipranges view [type]</code>: view the list of a particular type of IP range (<code>residential</code>, <code>mobile</code>, or <code>proxy</code>). Requires: hosts manager @ &`,
`<code>/ipranges add [type], [low IP]-[high IP], [host]</code>: add IP ranges (can be multiline). Requires: hosts manager &</summary><code>/ipranges view</code>: view the list of all IP ranges. Requires: hosts manager @ &`,
`<code>/ipranges widen [type], [low IP]-[high IP], [host]</code>: add IP ranges, allowing a new range to completely cover an old range. Requires: hosts manager &`,
`For example: <code>/ipranges add proxy, 5.152.192.0-5.152.223.255, redstation.com</code>.`,
`Get datacenter info from <code>/whois</code>; <code>[low IP]</code>, <code>[high IP]</code> are the range in the last inetnum.`,
`<code>/ipranges remove [low IP]-[high IP]</code>: remove IP range(s). Can be multiline. Requires: hosts manager &`,
`For example: <code>/ipranges remove 5.152.192.0, 5.152.223.255</code>.`,
`<code>/ipranges rename [type], [low IP]-[high IP], [host]</code>: changes the host an IP range resolves to. Requires: hosts manager &`
];
return this.sendReply(`|html|<details class="readmore"><summary>${help.join("<br />")}`);
},
viewhosts(target, room, user) {
checkCanPerform(this, user, "globalban");
const types = ["all", "residential", "mobile", "ranges"];
const type = target ? toID(target) : "all";
if (!types.includes(type)) {
return this.errorReply(`'${type}' isn't a valid host type. Specify one of ${types.join(", ")}.`);
}
return this.parse(`/join view-hosts-${type}`);
},
viewhostshelp: [
`/viewhosts - View the list of hosts. Requires: hosts manager @ &`,
`/viewhosts [type] - View the list of a particular type of host. Requires: hosts manager @ &`,
`Host types are: 'all', 'residential', 'mobile', and 'ranges'.`
],
removehost: "addhosts",
removehosts: "addhosts",
addhost: "addhosts",
addhosts(target, room, user, connection, cmd) {
checkCanPerform(this, user);
const removing = cmd.includes("remove");
let [type, ...hosts] = target.split(",");
type = toID(type);
hosts = hosts.map((host) => host.trim());
if (!hosts.length)
return this.parse("/help addhosts");
switch (type) {
case "openproxy":
for (const host of hosts) {
if (!IPTools.ipRegex.test(host))
return this.errorReply(`'${host}' is not a valid IP address.`);
if (removing !== IPTools.singleIPOpenProxies.has(host)) {
return this.errorReply(`'${host}' is ${removing ? "not" : "already"} in the list of proxy IPs.`);
}
}
if (removing) {
void IPTools.removeOpenProxies(hosts);
} else {
void IPTools.addOpenProxies(hosts);
}
break;
case "proxy":
for (const host of hosts) {
if (!IPTools.hostRegex.test(host))
return this.errorReply(`'${host}' is not a valid host.`);
if (removing !== IPTools.proxyHosts.has(host)) {
return this.errorReply(`'${host}' is ${removing ? "not" : "already"} in the list of proxy hosts.`);
}
}
if (removing) {
void IPTools.removeProxyHosts(hosts);
} else {
void IPTools.addProxyHosts(hosts);
}
break;
case "residential":
for (const host of hosts) {
if (!IPTools.hostRegex.test(host))
return this.errorReply(`'${host}' is not a valid host.`);
if (removing !== IPTools.residentialHosts.has(host)) {
return this.errorReply(`'${host}' is ${removing ? "not" : "already"} in the list of residential hosts.`);
}
}
if (removing) {
void IPTools.removeResidentialHosts(hosts);
} else {
void IPTools.addResidentialHosts(hosts);
}
break;
case "mobile":
for (const host of hosts) {
if (!IPTools.hostRegex.test(host))
return this.errorReply(`'${host}' is not a valid host.`);
if (removing !== IPTools.mobileHosts.has(host)) {
return this.errorReply(`'${host}' is ${removing ? "not" : "already"} in the list of mobile hosts.`);
}
}
if (removing) {
void IPTools.removeMobileHosts(hosts);
} else {
void IPTools.addMobileHosts(hosts);
}
break;
default:
return this.errorReply(`'${type}' isn't one of 'openproxy', 'proxy', 'residential', or 'mobile'.`);
}
this.privateGlobalModAction(
`${user.name} ${removing ? "removed" : "added"} ${hosts.length} hosts (${hosts.join(", ")}) ${removing ? "from" : "to"} the ${type} category`
);
this.globalModlog(removing ? "REMOVEHOSTS" : "ADDHOSTS", null, `${type}: ${hosts.join(", ")}`);
},
addhostshelp: [
`/addhosts [category], host1, host2, ... - Adds hosts to the given category. Requires: hosts manager &`,
`/removehosts [category], host1, host2, ... - Removes hosts from the given category. Requires: hosts manager &`,
`Categories are: 'openproxy' (which takes IP addresses, not hosts), 'proxy', 'residential', and 'mobile'.`
],
viewproxies(target, room, user) {
checkCanPerform(this, user, "globalban");
return this.parse("/join view-proxies");
},
viewproxieshelp: [
`/viewproxies - View the list of proxies. Requires: hosts manager @ &`
],
markshared(target, room, user) {
if (!target)
return this.parse("/help markshared");
checkCanPerform(this, user, "globalban");
const [ip, note] = this.splitOne(target);
if (!IPTools.ipRegex.test(ip)) {
const pattern = IPTools.stringToRange(ip);
if (!pattern) {
return this.errorReply("Please enter a valid IP address.");
}
if (!user.can("rangeban")) {
return this.errorReply("Only upper staff can markshare ranges.");
}
for (const range of Punishments.sharedRanges.keys()) {
if (IPTools.rangeIntersects(range, pattern)) {
return this.errorReply(
`Range ${IPTools.rangeToString(pattern)} intersects with shared range ${IPTools.rangeToString(range)}`
);
}
}
}
if (Punishments.isSharedIp(ip))
return this.errorReply("This IP is already marked as shared.");
if (Punishments.isBlacklistedSharedIp(ip)) {
return this.errorReply(`This IP is blacklisted from being marked as shared.`);
}
if (!note) {
this.errorReply(`You must specify who owns this shared IP.`);
this.parse(`/help markshared`);
return;
}
Punishments.addSharedIp(ip, note);
this.privateGlobalModAction(`The IP '${ip}' was marked as shared by ${user.name}. (${note})`);
this.globalModlog("SHAREDIP", null, note, ip);
},
marksharedhelp: [
`/markshared [IP], [owner/organization of IP] - Marks an IP address as shared.`,
`Note: the owner/organization (i.e., University of Minnesota) of the shared IP is required. Requires @ &`
],
unmarkshared(target, room, user) {
if (!target)
return this.parse("/help unmarkshared");
checkCanPerform(this, user, "globalban");
target = target.trim();
const pattern = IPTools.stringToRange(target);
if (!pattern)
return this.errorReply("Please enter a valid IP address.");
if (pattern.minIP !== pattern.maxIP && !user.can("rangeban")) {
return this.errorReply(`Only administrators can unmarkshare ranges.`);
}
let shared = false;
if (pattern.minIP !== pattern.maxIP) {
for (const range of Punishments.sharedRanges.keys()) {
shared = range.minIP === pattern.minIP && range.maxIP === pattern.maxIP;
if (shared)
break;
}
} else {
shared = Punishments.sharedIps.has(target);
}
if (!shared)
return this.errorReply(`That IP/range isn't marked as shared.`);
Punishments.removeSharedIp(target);
this.privateGlobalModAction(`The IP '${target}' was unmarked as shared by ${user.name}.`);
this.globalModlog("UNSHAREDIP", null, null, target);
},
unmarksharedhelp: [`/unmarkshared [IP] - Unmarks a shared IP address. Requires @ &`],
marksharedblacklist: "nomarkshared",
marksharedbl: "nomarkshared",
nomarkshared: {
add(target, room, user) {
if (!target)
return this.parse(`/help nomarkshared`);
checkCanPerform(this, user, "globalban");
const [ip, ...reasonArr] = target.split(",");
if (!IPTools.ipRangeRegex.test(ip))
return this.errorReply(`Please enter a valid IP address or range.`);
if (!reasonArr?.length) {
this.errorReply(`A reason is required.`);
this.parse(`/help nomarkshared`);
return;
}
if (Punishments.isBlacklistedSharedIp(ip)) {
return this.errorReply(`This IP is already blacklisted from being marked as shared.`);
}
if (!IPTools.ipRegex.test(ip)) {
if (!ip.endsWith("*")) {
this.errorReply(`That looks like a range, but it is invalid.`);
this.errorReply(`Append * to the end of the range and try again.`);
return;
}
if (!user.can("bypassall")) {
return this.errorReply(`Only Administrators can add ranges.`);
}
const range = IPTools.stringToRange(ip);
if (!range)
return this.errorReply(`Invalid IP range.`);
for (const sharedIp of Punishments.sharedIps.keys()) {
const ipNum = IPTools.ipToNumber(sharedIp);
if (IPTools.checkPattern([range], ipNum)) {
this.parse(`/unmarkshared ${sharedIp}`);
}
}
} else {
if (Punishments.isSharedIp(ip))
this.parse(`/unmarkshared ${ip}`);
}
const reason = reasonArr.join(",");
Punishments.addBlacklistedSharedIp(ip, reason);
this.privateGlobalModAction(`The IP '${ip}' was blacklisted from being marked as shared by ${user.name}.`);
this.globalModlog("SHAREDIP BLACKLIST", null, reason.trim(), ip);
},
remove(target, room, user) {
if (!target)
return this.parse(`/help nomarkshared`);
checkCanPerform(this, user);
if (!IPTools.ipRangeRegex.test(target))
return this.errorReply(`Please enter a valid IP address or range.`);
if (!Punishments.sharedIpBlacklist.has(target)) {
return this.errorReply(`This IP is not blacklisted from being marked as shared.`);
}
Punishments.removeBlacklistedSharedIp(target);
this.privateGlobalModAction(`The IP '${target}' was unblacklisted from being marked as shared by ${user.name}.`);
this.globalModlog("SHAREDIP UNBLACKLIST", null, null, target);
},
view() {
return this.parse(`/join view-sharedipblacklist`);
},
help: "",
""() {
return this.parse(`/help nomarkshared`);
}
},
nomarksharedhelp: [
`/nomarkshared add [IP], [reason] - Prevents an IP from being marked as shared until it's removed from this list. Requires &`,
`Note: Reasons are required.`,
`/nomarkshared remove [IP] - Removes an IP from the nomarkshared list. Requires &`,
`/nomarkshared view - Lists all IPs prevented from being marked as shared. Requires @ &`
],
sharedips: "viewsharedips",
viewsharedips() {
return this.parse("/join view-sharedips");
},
viewsharedipshelp: [
`/viewsharedips \u2014 Lists IP addresses marked as shared. Requires: hosts manager @ &`
]
};
//# sourceMappingURL=hosts.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/hosts.ts"],
"sourcesContent": ["/**\r\n * Chat plugin to help manage hosts, proxies, and datacenters\r\n * Written by Annika\r\n * Original /adddatacenters command written by Zarel\r\n */\r\n\r\nimport {Utils} from \"../../lib\";\r\nimport {AddressRange} from \"../ip-tools\";\r\nimport {GlobalPermission} from \"../user-groups\";\r\n\r\nconst HOST_SUFFIXES = ['res', 'proxy', 'mobile'];\r\nconst SUFFIX_ALIASES: {[k: string]: string} = {\r\n\tresidential: 'res',\r\n};\r\nconst WHITELISTED_USERIDS: ID[] = [];\r\n\r\nfunction checkCanPerform(\r\n\tcontext: Chat.PageContext | Chat.CommandContext, user: User, permission: GlobalPermission = 'lockdown'\r\n) {\r\n\tif (!WHITELISTED_USERIDS.includes(user.id)) context.checkCan(permission);\r\n}\r\n\r\nfunction getHostType(type: string) {\r\n\ttype = toID(type);\r\n\tif (HOST_SUFFIXES.includes(type)) return type;\r\n\tif (SUFFIX_ALIASES[type]) return SUFFIX_ALIASES[type];\r\n\tthrow new Chat.ErrorMessage(`'${type}' is not a valid host type. Please specify one of ${HOST_SUFFIXES.join(', ')}.`);\r\n}\r\n\r\nexport function visualizeRangeList(ranges: AddressRange[]) {\r\n\tlet html = `<tr><th>Lowest IP address</th><th>Highest IP address</th><th>Host</th></tr>`;\r\n\tfor (const range of ranges) {\r\n\t\thtml += `<tr>`;\r\n\t\thtml += `<td>${IPTools.numberToIP(range.minIP)}</td>`;\r\n\t\thtml += `<td>${IPTools.numberToIP(range.maxIP)}</td>`;\r\n\t\thtml += Utils.html`<td>${range.host}</td>`;\r\n\t\thtml += `</tr>`;\r\n\t}\r\n\treturn html;\r\n}\r\n\r\nfunction formatRange(range: AddressRange, includeModlogBrackets?: boolean) {\r\n\tconst startBracket = includeModlogBrackets ? '[' : '';\r\n\tconst endBracket = includeModlogBrackets ? ']' : '';\r\n\r\n\tlet result = `${startBracket}${IPTools.numberToIP(range.minIP)}${endBracket}`;\r\n\tresult += `-${startBracket}${IPTools.numberToIP(range.maxIP)}${endBracket}`;\r\n\tif (range.host) result += ` (${range.host})`;\r\n\r\n\treturn result;\r\n}\r\n\r\nexport const pages: Chat.PageTable = {\r\n\tproxies(query, user) {\r\n\t\tthis.title = \"[Proxies]\";\r\n\t\tcheckCanPerform(this, user, 'globalban');\r\n\r\n\t\tconst openProxies = [...IPTools.singleIPOpenProxies];\r\n\t\tconst proxyHosts = [...IPTools.proxyHosts];\r\n\t\tUtils.sortBy(openProxies, ip => {\r\n\t\t\tconst number = IPTools.ipToNumber(ip);\r\n\t\t\tif (number === null) {\r\n\t\t\t\tRooms.get('upperstaff')?.add(`|error|Invalid IP address in IPTools.singleIPOpenProxies: '${ip}'`);\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t\treturn number;\r\n\t\t});\r\n\t\tproxyHosts.sort();\r\n\t\tIPTools.sortRanges();\r\n\r\n\t\tlet html = `<div class=\"ladder pad\"><h2>Single IP proxies:</h2><table><tr><th>IP</th><th>Type</th></tr>`;\r\n\t\tfor (const proxyIP of openProxies) {\r\n\t\t\thtml += `<tr><td>${proxyIP}</td><td>Single IP open proxy</td></tr>`;\r\n\t\t}\r\n\t\thtml += `</table></div>`;\r\n\r\n\t\thtml += `<div class=\"ladder pad\"><h2>Proxy hosts:</h2><table><tr><th>Host</th><th>Type</th></tr>`;\r\n\t\tfor (const proxyHost of proxyHosts) {\r\n\t\t\thtml += `<tr><td>${proxyHost}</td><td>Proxy host</td></tr>`;\r\n\t\t}\r\n\t\thtml += `</table></div>`;\r\n\r\n\t\thtml += `<div class=\"ladder pad\"><h2>Proxy IP Ranges:</h2><table>`;\r\n\t\thtml += visualizeRangeList(IPTools.ranges.filter(r => r.host?.endsWith('/proxy')));\r\n\t\thtml += `</table></div>`;\r\n\t\treturn html;\r\n\t},\r\n\r\n\thosts(query, user) {\r\n\t\tthis.title = \"[Hosts]\";\r\n\t\tcheckCanPerform(this, user, 'globalban');\r\n\t\tconst type = toID(query[0]) || 'all';\r\n\r\n\t\tIPTools.sortRanges();\r\n\t\tconst mobileHosts = ['all', 'mobile'].includes(type) ? [...IPTools.mobileHosts] : [];\r\n\t\tconst residentialHosts = ['all', 'residential', 'res'].includes(type) ? [...IPTools.residentialHosts] : [];\r\n\t\tconst hostRanges = ['all', 'ranges', 'isps'].includes(type) ?\r\n\t\t\tIPTools.ranges.filter(r => r.host && !r.host.endsWith('/proxy')) :\r\n\t\t\t[];\r\n\t\tmobileHosts.sort();\r\n\t\tresidentialHosts.sort();\r\n\r\n\t\tlet html = `<div class=\"ladder pad\"><h2>Mobile hosts:</h2><table><tr><th>Host</th><th>Type</th></tr>`;\r\n\t\tfor (const mobileHost of mobileHosts) {\r\n\t\t\thtml += `<tr><td>${mobileHost}</td><td>Mobile host</td></tr>`;\r\n\t\t}\r\n\t\thtml += `</table></div>`;\r\n\r\n\t\thtml += `<div class=\"ladder pad\"><h2>Residential hosts:</h2><table><tr><th>Host</th><th>Type</th></tr>`;\r\n\t\tfor (const resHost of residentialHosts) {\r\n\t\t\thtml += `<tr><td>${resHost}</td><td>Residential host</td></tr>`;\r\n\t\t}\r\n\t\thtml += `</table></div>`;\r\n\r\n\t\thtml += `<div class=\"ladder pad\"><h2>ISP IP Ranges:</h2><table>`;\r\n\t\thtml += visualizeRangeList(hostRanges);\r\n\t\thtml += `</table></div>`;\r\n\t\treturn html;\r\n\t},\r\n\r\n\tranges(query, user) {\r\n\t\tthis.title = \"[IP Ranges]\";\r\n\t\tcheckCanPerform(this, user, 'globalban');\r\n\t\tconst type = toID(query[0]) || 'all';\r\n\t\tIPTools.sortRanges();\r\n\r\n\t\tlet html = ``;\r\n\t\tif (['all', 'mobile'].includes(type)) {\r\n\t\t\thtml +=Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,iBAAoB;AAIpB,MAAM,gBAAgB,CAAC,OAAO,SAAS,QAAQ;AAC/C,MAAM,iBAAwC;AAAA,EAC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AAG;AAC1B,eAAO,KAAK,WAAW,IAAI,iDAAiD,MAAM,KAAK,IAAI,IAAI;AAAA,MAChG;AACA,aAAO,KAAK,MAAM,qBAAqB,MAAM;AAAA,IAC9C;AAAA,IACA,UAAU;AAAA,MACT;AAAA,MACA;AAAA,IACD;AAAA;AAAA,IAGA,OAAO;AAAA,IACP,IAAI,QAAQ,MAAM,MAAM,YAAY,KAAK;AACxC,sBAAgB,MAAM,MAAM,WAAW;AACvC,UAAI,CAAC;AAAQ,eAAO,KAAK,MAAM,oBAAoB;AAEnD,YAAM,QAAQ,IAAI,SAAS,OAAO;AAElC,YAAM,CAAC,YAAY,aAAa,IAAI,IAAI,OAAO,MAAM,GAAG,EAAE,IAAI,UAAQ,KAAK,KAAK,CAAC;AACjF,UAAI,CAAC,QAAQ,CAAC,QAAQ,UAAU,KAAK,IAAI,GAAG;AAC3C,eAAO,KAAK,WAAW,iBAAiB,QAAQ;AAAA,MACjD;AACA,YAAM,OAAO,YAAY,UAAU;AACnC,YAAM,QAAQ,QAAQ,cAAc,WAAW;AAC/C,UAAI,CAAC;AAAO,eAAO,KAAK,WAAW,4BAA4B,eAAe;AAC9E,YAAM,OAAO,GAAG,QAAQ,UAAU,IAAI,MAAM;AAE5C,cAAQ,WAAW;AACnB,UAAI;AACJ,UAAI;AACH,iBALine truncated
"names": []
}
+916
View File
@@ -0,0 +1,916 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var jeopardy_exports = {};
__export(jeopardy_exports, {
Jeopardy: () => Jeopardy,
commands: () => commands,
roomSettings: () => roomSettings
});
module.exports = __toCommonJS(jeopardy_exports);
var import_lib = require("../../lib");
const BACKGROUND_COLOR = "#0000FF";
const HEIGHT = 40;
const MAX_CATEGORY_COUNT = 5;
const MAX_QUESTION_COUNT = 5;
const BUZZ_COOLDOWN = 500;
class Jeopardy extends Rooms.RoomGame {
constructor(room, user, categoryCount, questionCount, playerCap) {
super(room);
this.gameNumber = room.nextGameNumber();
this.host = user;
this.allowRenames = true;
this.state = "signups";
this.gameid = "jeopardy";
this.title = "Jeopardy";
this.categories = [];
this.question = /* @__PURE__ */ Object.create(null);
this.questions = [];
this.finalQuestion = /* @__PURE__ */ Object.create(null);
this.started = false;
this.categoryCount = categoryCount;
this.questionCount = questionCount;
this.round = 1;
this.points = /* @__PURE__ */ new Map();
this.playerCap = playerCap;
this.canBuzz = false;
this.numUpdates = 0;
this.finalCategory = "";
this.answeringTime = 10;
this.finalAnsweringTime = 30;
this.timeout = null;
this.roundStarted = false;
this.curPlayer = new JeopardyGamePlayer(user, this);
this.prevPlayer = new JeopardyGamePlayer(user, this);
this.order = [];
this.finals = false;
this.setupGrid();
}
destroy() {
if (this.timeout)
clearTimeout(this.timeout);
super.destroy();
}
makePlayer(user) {
return new JeopardyGamePlayer(user, this);
}
setupGrid() {
this.categories = [];
for (let j = 0; j < this.categoryCount; j++) {
this.categories.push("");
}
this.questions = [];
for (let i = 0; i < this.questionCount; i++) {
this.questions.push([]);
for (let j = 0; j < this.categoryCount; j++) {
this.questions[i].push({ question: "", answer: "", points: 200 * this.round * (i + 1), answered: false, dd: false });
}
}
this.finalQuestion = /* @__PURE__ */ Object.create(null);
this.roundStarted = false;
this.question = /* @__PURE__ */ Object.create(null);
if (this.round === 1) {
this.display();
} else {
this.update();
}
}
start() {
if (this.roundStarted)
throw new Chat.ErrorMessage("The game has already been started.");
if (this.playerCount < 2)
throw new Chat.ErrorMessage("The game needs at least two players to start.");
const noquestions = [];
for (let i = 0; i < this.categoryCount; i++) {
for (let j = 0; j < this.questionCount; j++) {
if (!this.questions[j][i].question) {
noquestions.push(`(${i + 1}, ${j + 1})`);
}
}
}
let badstr = noquestions.join(", ");
if (!this.finalQuestion.question && this.round === 2) {
badstr += `${badstr ? ", " : ""} final`;
}
if (badstr) {
throw new Chat.ErrorMessage(`The following questions still need questions and answers: ${badstr}.`);
}
this.roundStarted = true;
if (this.round === 1) {
for (const userID in this.playerTable) {
const player = this.playerTable[userID];
this.points.set(player, 0);
}
}
this.state = "selecting";
let lowest = [];
let minpoints;
for (const userID in this.playerTable) {
const points = this.playerTable[userID].points;
if (!minpoints) {
lowest.push(userID);
minpoints = points;
} else if (points < minpoints) {
lowest = [userID];
minpoints = points;
} else if (points === minpoints) {
lowest.push(userID);
}
}
this.curPlayer = this.playerTable[lowest[Math.floor(lowest.length * Math.random())]];
this.prevPlayer = this.curPlayer;
this.update();
this.nextPlayer();
}
nextPlayer() {
this.room.addRaw(`${this.curPlayer.name}, you're up!`);
}
getGrid() {
let buffer = `<div class="infobox"><html><body><table align="center" border="2" style="table-layout: fixed; width: 100%"><tr>`;
for (let i = 0; i < this.categoryCount; i++) {
buffer += `<td style="word-wrap: break-word" bgcolor="${BACKGROUND_COLOR}"; height="${HEIGHT}px"; width="30px" align="center"><font color="white">${import_lib.Utils.escapeHTML(this.categories[i])}</font></td>`;
}
buffer += `</tr>`;
for (let i = 0; i < this.questionCount; i++) {
buffer += `<tr>`;
for (let j = 0; j < this.categoryCount; j++) {
buffer += `<td bgcolor="${BACKGROUND_COLOR}"; height="${HEIGHT}px"; align="center"><font color="black" size="6">${this.questions[i][j].answered ? "" : this.questions[i][j].points}</font></td>`;
}
buffer += `</tr>`;
}
buffer += `</table><br />`;
for (const userID in this.playerTable) {
const player = this.playerTable[userID];
const bold = this.curPlayer?.name === player.name;
buffer += `${bold ? "<b>" : ""}<font size=2>${import_lib.Utils.escapeHTML(player.name)} (${player.points || 0})${bold ? "</b>" : ""}<br />`;
}
buffer += `</body></html></div>`;
return buffer;
}
display() {
this.room.add(`|uhtml|jeopardy${this.gameNumber}-${this.numUpdates}|${this.getGrid()}`);
}
update(dontMove = false) {
if (dontMove) {
this.room.add(`|uhtmlchange|jeopardy${this.gameNumber}-${this.numUpdates}|${this.getGrid()}`);
} else {
this.room.add(`|uhtmlchange|jeopardy${this.gameNumber}-${this.numUpdates}|`);
this.numUpdates++;
this.room.add(`|uhtml|jeopardy${this.gameNumber}-${this.numUpdates}|${this.getGrid()}`);
}
}
dailyDouble() {
if (this.timeout)
clearTimeout(this.timeout);
this.state = "answering";
if (!this.curPlayer.wager)
this.curPlayer.wager = 0;
this.askQuestion();
}
select(target) {
if (this.state !== "selecting")
throw new Chat.ErrorMessage("The game of Jeopardy is not in the selection phase.");
const params = target.split(",");
if (params.length < 2)
throw new Chat.ErrorMessage("You must specify a row and a column number.");
const categoryNumber = parseInt(params[0]);
if (!categoryNumber || categoryNumber < 1 || categoryNumber > this.categoryCount) {
throw new Chat.ErrorMessage(`The category must be a number between 1 and ${this.categoryCount}.`);
}
const questionNumber = parseInt(params[1]);
if (!questionNumber || questionNumber < 1 || questionNumber > this.questionCount) {
throw new Chat.ErrorMessage(`The question must be a number between 1 and ${this.questionCount}.`);
}
const question = this.questions[questionNumber - 1][categoryNumber - 1];
if (question.answered)
throw new Chat.ErrorMessage("That question has already been answered.");
this.question = question;
if (question.dd) {
this.room.add(`That was a daily double! ${this.curPlayer.name}, how much would you like to wager?`);
this.clearWagers();
this.state = "wagering";
this.timeout = setTimeout(() => this.dailyDouble(), 30 * 1e3);
} else {
this.state = "buzzing";
this.askQuestion();
}
}
clearWagers() {
for (const userID in this.playerTable) {
this.playerTable[userID].wager = 0;
}
}
clearBuzzes() {
for (const userID in this.playerTable) {
this.playerTable[userID].buzzed = false;
}
}
askQuestion() {
if (!this.question.dd) {
this.curPlayer = null;
}
this.clearBuzzes();
this.room.addRaw(import_lib.Utils.html`<div class="broadcast-blue">Your question is: ${this.question.question}</div>`);
if (!this.finals) {
this.canBuzz = false;
this.update(true);
this.timeout = setTimeout(() => this.allowBuzzes(), this.question.question.length / 15 * 1e3);
}
}
allowBuzzes() {
this.canBuzz = true;
this.room.add(`You may now buzz in for the Jeopardy game!`);
this.update(true);
this.timeout = setTimeout(() => this.allowAllBuzzes(), BUZZ_COOLDOWN);
}
allowAllBuzzes() {
for (const userID in this.playerTable) {
this.playerTable[userID].buzzedEarly = false;
}
}
revealAnswer() {
this.room.addRaw(`<div class="broadcast-blue">The answer was: ${import_lib.Utils.escapeHTML(this.question.answer)}</div>`);
this.question.answered = true;
}
buzz(user) {
if (this.state !== "buzzing")
throw new Chat.ErrorMessage("You cannot buzz in at this time.");
const player = this.playerTable[user.id];
if (!player)
throw new Chat.ErrorMessage("You are not in the game of Jeopardy.");
if (player.buzzed)
throw new Chat.ErrorMessage("You have already buzzed in to the current question.");
if (!this.canBuzz) {
player.buzzedEarly = true;
player.send("You buzzed early! You now have a delay before you will be able to buzz.");
return;
} else if (player.buzzedEarly) {
throw new Chat.ErrorMessage("Your buzzing cooldown has not yet ended.");
}
this.curPlayer = player;
this.curPlayer.buzzed = true;
this.room.add(`${user.name} has buzzed in!`);
this.state = "answering";
this.timeout = setTimeout(() => this.check({ correct: false, isBuzzTimeout: true }), this.answeringTime * 1e3);
}
hasRemainingQuestion() {
for (let i = 0; i < this.questionCount; i++) {
for (let j = 0; j < this.categoryCount; j++) {
if (!this.questions[i][j].answered)
return true;
}
}
return false;
}
startFinals() {
this.update();
this.room.add("Time to begin finals! The category is: " + this.finalCategory + "! Please wager your amounts now.");
this.finals = true;
this.state = "wagering";
this.clearWagers();
this.timeout = setTimeout(() => this.finalWagers(), this.finalAnsweringTime * 1e3);
}
wager(amount, user) {
if (this.state !== "wagering" && (!this.finals || this.curPlayer?.id !== user.id)) {
throw new Chat.ErrorMessage("You cannot wager at this time.");
}
const player = this.playerTable[user.id];
if (!player)
throw new Chat.ErrorMessage("You are not in the game of Jeopardy.");
amount = toID(amount);
const wager = amount === "all" ? player.points : parseInt(amount);
if (!wager || isNaN(wager))
throw new Chat.ErrorMessage("Your wager must be a number, or 'all'.");
if (wager < 0)
throw new Chat.ErrorMessage("You cannot wager a negative amount.");
if (wager > player.points && (wager > this.round * 1e3 || this.finals)) {
throw new Chat.ErrorMessage("You cannot wager more than your current number of points.");
}
if (player.wager)
throw new Chat.ErrorMessage("You have already wagered.");
player.wager = wager;
player.send(`You have wagered ${wager} points!`);
if (!this.finals) {
this.dailyDouble();
} else {
for (const userID in this.playerTable) {
if (!this.playerTable[userID].wager)
return;
}
if (this.timeout)
clearTimeout(this.timeout);
this.finalWagers();
}
}
finalWagers() {
for (const userID in this.playerTable) {
const player = this.playerTable[userID];
if (!player.wager)
player.wager = 0;
}
this.question = this.finalQuestion;
this.state = "answering";
this.askQuestion();
this.timeout = setTimeout(() => this.doFinals(), this.finalAnsweringTime * 1e3);
}
doFinals() {
if (!this.playerTable)
return this.room?.add(`Could not play finals because the player table does not exist.`);
this.order = Object.keys(this.playerTable);
this.doFinalPlayer();
}
doFinalPlayer() {
if (this.order.length === 0) {
this.revealAnswer();
let highest = [];
let maxpoints;
for (const userID in this.playerTable) {
const player = this.playerTable[userID];
const points = player.points;
if (!maxpoints) {
highest.push(player.name);
maxpoints = points;
} else if (points > maxpoints) {
highest = [player.name];
maxpoints = points;
} else if (points === maxpoints) {
highest.push(player.name);
}
}
this.room.add(`|raw|<div class=broadcast-green>Congratulations to ${highest.map((n) => import_lib.Utils.escapeHTML(n)).join(", ")} for winning the game of Jeopardy with ${maxpoints} points!`);
this.destroy();
return;
} else {
const index = this.order.shift() || 0;
this.curPlayer = this.playerTable[index];
const answer = this.curPlayer.finalAnswer;
if (answer) {
this.room.add(`${this.curPlayer.name} has answered ${import_lib.Utils.escapeHTML(answer)}!`);
this.state = "checking";
} else {
const wager = this.curPlayer.wager;
this.room.add(`${this.curPlayer.name} did not answer the final Jeopardy and loses ${wager} points`);
let points = this.curPlayer.points;
points -= wager;
this.curPlayer.points = points;
this.timeout = setTimeout(() => this.doFinalPlayer(), 5 * 1e3);
}
}
}
answer(target, user) {
if (this.state !== "answering")
throw new Chat.ErrorMessage("You cannot answer the question at this time.");
const player = this.playerTable[user.id];
if (!player)
throw new Chat.ErrorMessage("You are not in the game of Jeopardy.");
if (this.finals) {
if (player.finalAnswer)
throw new Chat.ErrorMessage("You have already answered the Final Jeopardy");
player.answer = import_lib.Utils.escapeHTML(target);
player.send(`You have selected your answer as ${import_lib.Utils.escapeHTML(target)}.`);
} else {
if (this.timeout)
clearTimeout(this.timeout);
if (!this.curPlayer || this.curPlayer.id !== user.id)
throw new Chat.ErrorMessage("It is not your turn to answer.");
this.state = "checking";
this.room.add(`${user.name} has answered ${import_lib.Utils.escapeHTML(target)}!`);
}
}
mark(correct) {
if (this.state !== "checking")
throw new Chat.ErrorMessage("There is no answer to currently check.");
this.check({ correct });
}
check(info) {
if (info.correct) {
const gainpoints = this.question.dd || this.finals ? this.curPlayer.wager : this.question.points;
let points = this.curPlayer.points;
points += gainpoints;
this.curPlayer.points = points;
this.room.add(`${this.curPlayer.name} has answered the question correctly and gained ${gainpoints} points!`);
if (!this.finals) {
this.revealAnswer();
}
if (this.finals) {
this.doFinalPlayer();
} else if (!this.hasRemainingQuestion()) {
if (this.round === 1) {
this.round++;
this.setupGrid();
this.state = "round2";
} else {
this.startFinals();
}
} else {
this.prevPlayer = this.curPlayer;
this.state = "selecting";
this.question = /* @__PURE__ */ Object.create(null);
this.update();
}
} else {
const losspoints = this.question.dd || this.finals ? this.curPlayer.wager : this.question.points;
const action = info.isBuzzTimeout ? "failed to answer in time" : "answered incorrectly";
this.room.add(`${this.curPlayer.name} ${action} and loses ${losspoints} points!`);
let points = this.curPlayer.points;
points -= losspoints;
this.curPlayer.points = points;
if (this.finals) {
this.doFinalPlayer();
} else if (this.everyBuzzed() || this.question.dd) {
this.nextQuestion();
} else {
this.state = "buzzing";
}
}
}
everyBuzzed() {
for (const userID in this.playerTable) {
if (!this.playerTable[userID].buzzed)
return false;
}
return true;
}
setCategory(categoryNumber, category) {
if (typeof categoryNumber === "string") {
this.finalCategory = category.trim();
} else {
this.categories[categoryNumber] = category.trim();
this.update();
}
}
nextQuestion() {
this.revealAnswer();
if (!this.hasRemainingQuestion()) {
if (this.round === 1) {
this.round++;
this.setupGrid();
this.state = "round2";
} else {
this.startFinals();
}
} else {
this.curPlayer = this.prevPlayer;
this.state = "selecting";
this.question = /* @__PURE__ */ Object.create(null);
this.update();
}
}
setCategories(categories) {
if (this.state !== "signups" && this.state !== "round2")
return false;
for (const [i, category] of categories.entries()) {
this.categories[i] = category;
}
this.update();
}
getQuestion(categoryNumber, questionNumber) {
const question = this.questions[questionNumber][categoryNumber];
if (question.question) {
return `<strong>Question: </strong>${import_lib.Utils.escapeHTML(question.question)}<br><strong>Answer: </strong>${import_lib.Utils.escapeHTML(question.answer)}`;
} else {
return "That question has not yet been imported.";
}
}
setDailyDouble(categoryNumber, questionNumber) {
const question = this.questions[questionNumber][categoryNumber];
if (question.dd)
throw new Chat.ErrorMessage("That question is already a daily double.");
question.dd = true;
}
importQuestions(questions, questionStart, categoryStart) {
if (typeof categoryStart === "string") {
const split = questions[0].split("|");
if (split.length !== 2)
throw new Chat.ErrorMessage("Final question was unable to be imported.");
this.finalQuestion.question = split[0].trim();
this.finalQuestion.answer = split[1].trim();
} else {
for (let i = categoryStart; i < this.categoryCount; i++) {
for (let j = i === categoryStart ? questionStart : 0; j < this.questionCount; j++) {
if (questions.length === 0) {
return;
}
const split = questions[0].split("|");
if (split.length !== 2) {
throw new Chat.ErrorMessage(`Questions before ${questions[0]} imported successfully, but ${questions[0]} did not have a question and one answer.`);
}
this.questions[j][i].question = split[0].trim();
this.questions[j][i].answer = split[1].trim();
questions.shift();
}
}
if (questions.length > 0) {
const split = questions[0].split("|");
if (split.length !== 2) {
throw new Chat.ErrorMessage(`Questions before ${questions[0]} imported successfully, but ${questions[0]} did not have a question and one answer.`);
}
this.finalQuestion.question = split[0].trim();
this.finalQuestion.answer = split[1].trim();
}
}
}
givePoints(user, n) {
const id = toID(user);
if (!(id in this.playerTable))
throw new Chat.ErrorMessage(`'${id}' is not a player in the game of Jeopardy.`);
this.playerTable[id].points += n;
}
substitute(original, substitute) {
const originalPlayer = this.playerTable[original.id];
if (!originalPlayer)
throw new Chat.ErrorMessage(`${original.name} is not a player in the game of Jeopardy.`);
delete this.playerTable[original.id];
this.addPlayer(substitute);
this.playerTable[substitute.id].answer = originalPlayer.answer;
this.playerTable[substitute.id].points = originalPlayer.points;
this.playerTable[substitute.id].wager = originalPlayer.wager;
this.playerTable[substitute.id].buzzedEarly = originalPlayer.buzzedEarly;
this.playerTable[substitute.id].finalAnswer = originalPlayer.finalAnswer;
this.playerTable[substitute.id].buzzed = originalPlayer.buzzed;
this.room.add(`${substitute.name} subbed in for ${original.name}!`);
}
}
class JeopardyGamePlayer extends Rooms.RoomGamePlayer {
constructor(user, game) {
super(user, game);
this.answer = "";
this.points = 0;
this.wager = 0;
this.buzzedEarly = false;
this.finalAnswer = "";
this.buzzed = false;
}
}
const commands = {
jp: "jeopardy",
jeopardy: {
"": "help",
help() {
return this.parse("/help jeopardy");
},
off: "disable",
disable(target, room, user) {
room = this.requireRoom();
this.checkCan("gamemanagement", null, room);
if (room.settings.jeopardyDisabled) {
return this.errorReply("Jeopardy is already disabled in this room.");
}
room.settings.jeopardyDisabled = true;
room.saveSettings();
return this.sendReply("Jeopardy has been disabled for this room.");
},
on: "enable",
enable(target, room, user) {
room = this.requireRoom();
this.checkCan("gamemanagement", null, room);
if (!room.settings.jeopardyDisabled) {
return this.errorReply("Jeopardy is already enabled in this room.");
}
delete room.settings.jeopardyDisabled;
room.saveSettings();
return this.sendReply("Jeopardy has been enabled for this room.");
},
create: "new",
new(target, room, user) {
room = this.requireRoom();
if (room.game) {
return this.errorReply(`There is already a game of ${room.game.title} in progress in this room.`);
}
this.checkCan("minigame", null, room);
const params = target.split(",");
const playerCap = parseInt(params[0]);
const categoryCount = parseInt(params[1]);
const questionCount = parseInt(params[2]);
if (isNaN(playerCap) || playerCap <= 1) {
return this.errorReply(`The player cap must be a number above 1.`);
}
if (isNaN(categoryCount) || categoryCount <= 0) {
return this.errorReply(`The category count must be a number above 0.`);
}
if (categoryCount > MAX_CATEGORY_COUNT) {
return this.sendReply(`A match with more than ${MAX_CATEGORY_COUNT} categories cannot be created.`);
}
if (isNaN(questionCount) || questionCount <= 0) {
return this.errorReply(`The question count must be a number above 0.`);
}
if (questionCount > MAX_QUESTION_COUNT) {
return this.sendReply(
`A match with more than ${MAX_QUESTION_COUNT} questions per category cannot be created.`
);
}
room.game = new Jeopardy(room, user, categoryCount, questionCount, playerCap);
this.privateModAction(`${user.name} started a new game of Jeopardy.`);
this.modlog("JEOPARDY", null, `maximum of ${playerCap} players, ${categoryCount} categories, and ${questionCount} questions`);
},
categories(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
const params = target.split(",");
if (params.length !== game.categoryCount) {
return this.errorReply(`You must set exactly ${game.categoryCount} categories.`);
}
const reply = game.setCategories(params);
if (reply)
this.errorReply(reply);
},
category(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
const params = target.split(",");
if (params.length !== 2)
return this.errorReply("You must specify the category number and the category.");
let categoryNumber;
if (params[0] === "final") {
categoryNumber = "final";
} else {
categoryNumber = parseInt(params[0]);
if (!categoryNumber || categoryNumber < 1 || categoryNumber > game.categoryCount) {
return this.errorReply(`The category number must be between 1 and ${game.categoryCount}.`);
}
}
game.setCategory(typeof categoryNumber === "string" ? categoryNumber : categoryNumber - 1, params[1]);
},
select(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
game.select(target);
},
buzz(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
game.buzz(user);
},
wager(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.lastCommand !== `/jeopardy wager ${target}`) {
user.lastCommand = `/jeopardy wager ${target}`;
return this.sendReply(`To confirm your wager of ${target}, type '${user.lastCommand}' again.`);
}
game.wager(target, user);
},
answer(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
game.answer(target, user);
},
import(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (!target)
return this.errorReply("You must specify at least one question");
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
const params = target.split(",");
let dataStart = 0;
let catStart;
let questionStart = 1;
if (toID(params[0]) === "final") {
catStart = "finals";
params.splice(0, 1);
} else {
if (isNaN(import_lib.Utils.parseExactInt(params[0])) || isNaN(import_lib.Utils.parseExactInt(params[1]))) {
return this.errorReply(`You must specify numeric values for Category Number Start and Question Number Start.`);
}
catStart = parseInt(params[0]);
if (catStart) {
if (catStart < 1 || catStart > game.categoryCount) {
return this.errorReply(`The category must be a number between 1 and ${game.categoryCount}.`);
}
dataStart = 1;
questionStart = parseInt(params[1]);
if (questionStart) {
if (questionStart < 1 || questionStart > game.questionCount) {
return this.errorReply(`The question must be a number between 1 and ${game.questionCount}.`);
}
dataStart = 2;
} else {
questionStart = 1;
}
} else {
catStart = 1;
questionStart = 1;
}
params.splice(0, dataStart);
}
const numberOfQuestions = params.length;
game.importQuestions(
params,
questionStart - 1,
typeof catStart === "string" ? catStart : catStart - 1
);
this.sendReply(`Imported ${numberOfQuestions} questions.`);
},
dd: "dailydouble",
dailydouble(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
const params = target.split(",");
if (params.length !== 2)
return this.errorReply("You must specify the category number and question number");
const categoryNumber = parseInt(params[0]);
if (!categoryNumber || categoryNumber < 1 || categoryNumber > game.categoryCount) {
return this.errorReply(`The category must be a number between 1 and ${game.categoryCount}.`);
}
const questionNumber = parseInt(params[0]);
if (!questionNumber || questionNumber < 1 || questionNumber > game.questionCount) {
return this.errorReply(`The question must be a number between 1 and ${game.questionCount}.`);
}
game.setDailyDouble(categoryNumber - 1, questionNumber - 1);
this.sendReply("Daily double has been added.");
},
dailydoublehelp: [
`/jeopardy dailydouble [category number], [question number] - Set a question to be a daily double.`
],
view(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
const params = target.split(",");
if (params.length !== 2)
return this.errorReply("You must specify the category number and question number");
const categoryNumber = parseInt(params[0]);
if (!categoryNumber || categoryNumber < 1 || categoryNumber > game.categoryCount) {
return this.errorReply(`The category must be a number between 1 and ${game.categoryCount}.`);
}
const questionNumber = parseInt(params[1]);
if (!questionNumber || questionNumber < 1 || questionNumber > game.questionCount) {
return this.errorReply(`The question must be a number between 1 and ${game.questionCount}.`);
}
this.sendReplyBox(game.getQuestion(categoryNumber - 1, questionNumber - 1));
},
join(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (game.host.id === user.id)
return this.errorReply("You are the host and therefore cannot join the game.");
if (game.state !== "signups")
return this.errorReply("This Jeopardy game is not in its signups phase.");
if (game.addPlayer(user)) {
game.update();
} else {
this.errorReply("Unable to join the game.");
}
},
incorrect: "correct",
correct(target, room, user, connection, cmd) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
game.mark(cmd === "correct");
},
start(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
game.start();
},
kick: "leave",
leave(target, room, user, connection, cmd) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
const kicking = cmd.includes("kick");
if (kicking && user.id !== game.host.id)
return this.errorReply("Only the host can kick players.");
const targetUser = kicking ? Users.get(target) : user;
if (!targetUser)
return this.errorReply(`User '${target}' not found.`);
if (game.removePlayer(targetUser)) {
game.update();
} else {
return this.errorReply(`Unable to remove '${targetUser.name}' from the game.`);
}
},
subhost(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
const targetUser = Users.get(target);
if (!targetUser)
return this.errorReply(`User '${target}' not found.`);
game.host = targetUser;
this.sendReply(`${targetUser.name} has subbed in as the host.`);
},
subplayer(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
const split = target.split(",");
if (split.length !== 2)
return this.parse(`/help jeopardy`);
const [toSubOut, toSubIn] = split.map((u) => Users.get(u));
if (!toSubOut)
return this.errorReply(`User '${target[0]}' not found.`);
if (!toSubIn)
return this.errorReply(`User '${target[1]}' not found.`);
game.substitute(toSubOut, toSubIn);
},
state(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
this.sendReply(`The game is currently in the ${game.state} state.`);
},
end(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
this.checkCan("minigame", null, room);
game.destroy();
this.privateModAction(`${user.name} ended the game of Jeopardy.`);
this.modlog("JEOPARDY END");
},
pass(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
game.nextQuestion();
},
timer(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
const amount = parseInt(target);
if (!amount || amount < 2 || amount > 120)
return this.errorReply("The amount must be a number between 2 and 120.");
game.answeringTime = amount;
this.addModAction(`${user.name} has set the answering window for questions to ${amount} seconds`);
this.modlog("JEOPARDY TIMER", null, `${amount} seconds`);
},
finaltimer(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
const amount = parseInt(target);
if (!amount || amount < 2 || amount > 300)
return this.errorReply("The amount must be a number between 2 and 300.");
game.finalAnsweringTime = amount;
this.addModAction(`${user.name} has set the answering window for the final question to ${amount} seconds`);
this.modlog("JEOPARDY FINALTIMER", null, `${amount} seconds`);
},
removepoints: "addpoints",
addpoints(target, room, user, connection, cmd) {
room = this.requireRoom();
if (!target)
return this.parse(`/help jeopardy`);
const game = this.requireGame(Jeopardy);
if (user.id !== game.host.id)
return this.errorReply("This command can only be used by the host.");
const [recipient, pointsString] = target.split(",");
let points = parseInt(pointsString);
if (points <= 0 || isNaN(points)) {
return this.errorReply(`You must provide a positive number of points to add/remove.`);
}
if (cmd.includes("remove"))
points *= -1;
game.givePoints(toID(recipient), points);
}
},
jeopardyhelp() {
this.runBroadcast();
return this.sendReply(
`|html|<details class="readmore"><summary><code>/jp new [player cap], [number of categories], [number of questions]</code>: Host a new game of Jeopardy. Requires: % @ # &<br /><code>/jp join</code>: Join the game of Jeopardy.<br /><code>/jp leave</code>: Leave the game of Jeopardy.<br /><code>/jp buzz</code>: Buzz into the current question.<br /><code>/jp answer [answer]</code>: Attempt to answer the current question.</summary><code>/jp start</code>: Start the game of Jeopardy. Must be the host.<br /><code>/jp correct/incorrect</code>: Mark an answer as correct or incorrect. Must be the host.<br /><code>/jp categories [First Category], [Second Category], etc.</code>: Set the categories of the jeopardy game. Must be the host.<br /><code>/jp category [Category Number], [Category Name]</code>: Set a specific category of the jeopardy game. Must be the host.<br /><code>/jp select [Category Number], [Question Number]</code>: Select a question of the Jeopardy game.<br /><code>/jp end</code>: End the current game of Jeopardy. Requires: % @ # &<br /><code>/jp dailydouble [Category Number], [Question Number]</code>: Set a question to be a daily double. Must be the host.<br /><code>/jp wager [amount]</code>: Wager some money for a daily double or finals. Must be a number or 'all'<br /><code>/jp kick [User]</code>: Remove a user from the game of Jeopardy. Must be the host.<br /><code>/jp view [Category Number], [Question Number]</code>: View a specific question and answer. Must be the host.<br /><code>/jp subhost [User]</code>: Sub a new host into the game. Must be the host.<br /><code>/jp subplayer [original], [substitute]</code>: Sub a new player into the game. Must be the host.<br /><code>/jp import [Category Number Start], [Question Number Start], [Question 1 | Answer 1], [Question 2 | Answer 2], etc.</code>: Import questions into the current game of Jeopardy. Must be the host.<br /><code>/jp pass</code>: Skip the current question of Jeopardy. Must be the host.<br /><code>/jp state</code>: Check the state of the current Jeopardy game. Must be the host.<br /><code>/jp timer [seconds]</code>: Set the answering window after buzzing for questions<br /><code>/jp finaltimer [seconds]</code>: Set the answering window for answering the final question<br /><code>/jp addpoints [user], [number of points]</code>: Give a player an arbitrary number of points. Must be the host.<br /><code>/jp remove [user], [number of points]</code>: Subtract an arbitrary number of points from a player. Must be the host.</details>`
);
}
};
const roomSettings = (room) => ({
label: "Jeopardy",
permission: "editroom",
options: [
[`disabled`, room.settings.jeopardyDisabled || "jeopardy disable"],
[`enabled`, !room.settings.jeopardyDisabled || "jeopardy enable"]
]
});
//# sourceMappingURL=jeopardy.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/jeopardy.ts"],
"sourcesContent": ["import {Utils} from '../../lib';\r\n\r\nconst BACKGROUND_COLOR = \"#0000FF\";\r\nconst HEIGHT = 40;\r\nconst MAX_CATEGORY_COUNT = 5;\r\nconst MAX_QUESTION_COUNT = 5;\r\nconst BUZZ_COOLDOWN = 500; // 0.5 seconds\r\n\r\ninterface Question {\r\n\tquestion: string;\r\n\tanswer: string;\r\n\tpoints: number;\r\n\tanswered: boolean;\r\n\tdd: boolean;\r\n}\r\n\r\ntype JeopardyState = 'signups' | 'selecting' | 'answering' | 'wagering' | 'buzzing' | 'checking' | 'round2';\r\n\r\nexport class Jeopardy extends Rooms.RoomGame<JeopardyGamePlayer> {\r\n\thost: User;\r\n\tstate: JeopardyState;\r\n\tgameid: ID;\r\n\tcategories: string[];\r\n\tquestion: Question;\r\n\tquestions: Question[][];\r\n\tfinalQuestion: Question;\r\n\tstarted: boolean;\r\n\tcategoryCount: number;\r\n\tquestionCount: number;\r\n\tround: number;\r\n\tcanBuzz: boolean;\r\n\tnumUpdates: number;\r\n\tfinalCategory: string;\r\n\tansweringTime: number;\r\n\tfinalAnsweringTime: number;\r\n\ttimeout: NodeJS.Timer | null;\r\n\troundStarted: boolean;\r\n\t// FIXME: this type should be `JeopardyGamePlayer | null`\r\n\tcurPlayer: JeopardyGamePlayer;\r\n\tprevPlayer: JeopardyGamePlayer;\r\n\torder: string[];\r\n\tpoints: Map<JeopardyGamePlayer, number>;\r\n\tfinals: boolean;\r\n\tgameNumber: number;\r\n\r\n\tconstructor(room: Room, user: User, categoryCount: number, questionCount: number, playerCap: number) {\r\n\t\tsuper(room);\r\n\t\tthis.gameNumber = room.nextGameNumber();\r\n\t\tthis.host = user;\r\n\t\tthis.allowRenames = true;\r\n\t\tthis.state = \"signups\";\r\n\t\tthis.gameid = 'jeopardy' as ID;\r\n\t\tthis.title = 'Jeopardy';\r\n\t\tthis.categories = [];\r\n\t\tthis.question = Object.create(null);\r\n\t\tthis.questions = [];\r\n\t\tthis.finalQuestion = Object.create(null);\r\n\t\tthis.started = false;\r\n\t\tthis.categoryCount = categoryCount;\r\n\t\tthis.questionCount = questionCount;\r\n\t\tthis.round = 1;\r\n\t\tthis.points = new Map();\r\n\t\tthis.playerCap = playerCap;\r\n\t\tthis.canBuzz = false;\r\n\t\tthis.numUpdates = 0;\r\n\t\tthis.finalCategory = \"\";\r\n\t\tthis.answeringTime = 10;\r\n\t\tthis.finalAnsweringTime = 30;\r\n\t\tthis.timeout = null;\r\n\t\tthis.roundStarted = false;\r\n\t\tthis.curPlayer = new JeopardyGamePlayer(user, this);\r\n\t\tthis.prevPlayer = new JeopardyGamePlayer(user, this);\r\n\t\tthis.order = [];\r\n\t\tthis.finals = false;\r\n\t\tthis.setupGrid();\r\n\t}\r\n\r\n\tdestroy() {\r\n\t\tif (this.timeout) clearTimeout(this.timeout);\r\n\t\tsuper.destroy();\r\n\t}\r\n\r\n\tmakePlayer(user: User) {\r\n\t\treturn new JeopardyGamePlayer(user, this);\r\n\t}\r\n\r\n\tsetupGrid() {\r\n\t\tthis.categories = [];\r\n\t\tfor (let j = 0; j < this.categoryCount; j++) {\r\n\t\t\tthis.categories.push(\"\");\r\n\t\t}\r\n\t\tthis.questions = [];\r\n\t\tfor (let i = 0; i < this.questionCount; i++) {\r\n\t\t\tthis.questions.push([]);\r\n\t\t\tfor (let j = 0; j < this.categoryCount; j++) {\r\n\t\t\t\tthis.questions[i].push({question: '', answer: '', points: 200 * this.round * (i + 1), answered: false, dd: false});\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.finalQuestion = Object.create(null);\r\n\t\tthis.roundStarted = false;\r\n\t\tthis.question = Object.create(null);\r\n\t\tif (this.round === 1) {\r\n\t\t\tthis.display();\r\n\t\t} else {\r\n\t\t\tthis.update();\r\n\t\t}\r\n\t}\r\n\r\n\tstart() {\r\n\t\tif (this.roundStarted) throw new Chat.ErrorMessage(\"The game has already been started.\");\r\n\t\tif (this.playerCount < 2) throw new Chat.ErrorMessage(\"The game needs at least two players to start.\");\r\n\t\tconst noquestions = [];\r\n\t\tfor (let i = 0; i < this.categoryCount; i++) {\r\n\t\t\tfor (let j = 0; j < this.questionCount; j++) {\r\n\t\t\t\tif (!this.questions[j][i].question) {\r\n\t\t\t\t\tnoquestions.push(`(${(i + 1)}, ${(j + 1)})`);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tlet badstr = noquestions.join(\", \");\r\n\t\tif (!this.finalQuestion.question && this.round === 2) {\r\n\t\t\tbadstr += `${(badstr ? \", \" : \"\")} final`;\r\n\t\t}\r\n\t\tif (badstr) {\r\n\t\t\tthrow new Chat.ErrorMessage(`The following questions still need questions and answers: ${badstr}.`);\r\n\t\t}\r\n\t\tthis.roundStarted = true;\r\n\t\tif (this.round === 1) {\r\n\t\t\tfor (const userID in this.playerTable) {\r\n\t\t\t\tconst player = this.playerTable[userID];\r\n\t\t\t\tthis.points.set(player, 0);\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.state = 'selecting';\r\n\t\tlet lowest: string[] = [];\r\n\t\tlet minpoints;\r\n\t\tfor (const userID in this.playerTable) {\r\n\t\t\tconst points = this.playerTable[userID].points;\r\n\t\t\tif (!minpoints) {\r\n\t\t\t\tlowest.push(userID);\r\n\t\t\t\tminpoints = points;\r\n\t\t\t} else if (points < minpoints) {\r\n\t\t\t\tlowest = [userID];\r\n\t\t\t\tminpoints = points;\r\n\t\t\t} else if (points === minpoints) {\r\n\t\t\t\tlowest.push(userID);\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.curPlayer = this.playerTable[lowest[Math.floor(lowest.length * Math.random())]];\r\n\t\tthis.prevPlayer = this.curPlayer;\r\n\t\tthis.upLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAoB;AAEpB,MAAM,mBAAmB;AACzB,MAAM,SAAS;AACf,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;AAYf,MAAM,iBAAiB,MAAM,SAA6B;AAAA,EA2BhE,YAAY,MAAY,MAAY,eAAuB,eAAuB,WAAmB;AACpG,UAAM,IAAI;AACV,SAAK,aAAa,KAAK,eAAe;AACtC,SAAK,OAAO;AACZ,SAAK,eAAe;AACpB,SAAK,QAAQ;AACb,SAAK,SAAS;AACd,SAAK,QAAQ;AACb,SAAK,aAAa,CAAC;AACnB,SAAK,WAAW,uBAAO,OAAO,IAAI;AAClC,SAAK,YAAY,CAAC;AAClB,SAAK,gBAAgB,uBAAO,OAAO,IAAI;AACvC,SAAK,UAAU;AACf,SAAK,gBAAgB;AACrB,SAAK,gBAAgB;AACrB,SAAK,QAAQ;AACb,SAAK,SAAS,oBAAI,IAAI;AACtB,SAAK,YAAY;AACjB,SAAK,UAAU;A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B,WAAK,YAAY;AAAA,IAClB;AACA,SAAK,YAAY;AACjB,SAAK,KAAK,OAAO,iBAAM,qDAAqD,KAAK,SAAS,gBAAgB;AAC1G,QAAI,CAAC,KAAK,QAAQ;AACjB,WAAK,UAAU;AACf,WAAK,OAAO,IAAI;AAChB,WAAK,UAAU,WAAW,MAAM,KAAK,YAAY,GAAG,KAAK,SAAS,SALine truncated
"names": []
}
+314
View File
@@ -0,0 +1,314 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var lottery_exports = {};
__export(lottery_exports, {
commands: () => commands,
pages: () => pages
});
module.exports = __toCommonJS(lottery_exports);
var import_lib = require("../../lib");
const LOTTERY_FILE = "config/chat-plugins/lottery.json";
const lotteriesContents = (0, import_lib.FS)(LOTTERY_FILE).readIfExistsSync();
const lotteries = lotteriesContents ? Object.assign(/* @__PURE__ */ Object.create(null), JSON.parse(lotteriesContents)) : /* @__PURE__ */ Object.create(null);
function createLottery(roomid, maxWinners, name, markup) {
if (lotteries[roomid] && !lotteries[roomid].running) {
delete lotteries[roomid];
}
const lottery = lotteries[roomid];
lotteries[roomid] = {
maxWinners,
name,
markup,
participants: lottery?.participants || /* @__PURE__ */ Object.create(null),
winners: lottery?.winners || [],
running: true
};
writeLotteries();
}
function writeLotteries() {
for (const roomid of Object.keys(lotteries)) {
if (!Rooms.get(roomid)) {
delete lotteries[roomid];
}
}
(0, import_lib.FS)(LOTTERY_FILE).writeUpdate(() => JSON.stringify(lotteries));
}
function destroyLottery(roomid) {
delete lotteries[roomid];
writeLotteries();
}
function endLottery(roomid, winners) {
const lottery = lotteries[roomid];
if (!lottery)
return;
lottery.winners = winners;
lottery.running = false;
Object.freeze(lottery);
writeLotteries();
}
function isSignedUp(roomid, user) {
const lottery = lotteries[roomid];
if (!lottery)
return;
const participants = lottery.participants;
const participantNames = Object.values(participants).map(toID);
if (participantNames.includes(user.id))
return true;
if (Config.noipchecks)
return false;
return !!participants[user.latestIp];
}
function addUserToLottery(roomid, user) {
const lottery = lotteries[roomid];
if (!lottery)
return;
const participants = lottery.participants;
if (!isSignedUp(roomid, user)) {
participants[user.latestIp] = user.name;
writeLotteries();
return true;
}
return false;
}
function removeUserFromLottery(roomid, user) {
const lottery = lotteries[roomid];
if (!lottery)
return;
const participants = lottery.participants;
for (const [ip, participant] of Object.entries(participants)) {
if (toID(participant) === user.id || ip === user.latestIp) {
delete participants[ip];
writeLotteries();
return true;
}
}
return false;
}
function getWinnersInLottery(roomid) {
const lottery = lotteries[roomid];
if (!lottery)
return;
const winners = [];
const participants = Object.values(lottery.participants);
for (let i = 0; i < lottery.maxWinners; i++) {
const randomIdx = participants.length * Math.random() << 0;
const winner = participants[randomIdx];
winners.push(winner);
participants.splice(randomIdx, 1);
}
return winners;
}
const commands = {
lottery: {
""(target, room) {
room = this.requireRoom();
const lottery = lotteries[room.roomid];
if (!lottery) {
return this.errorReply("This room doesn't have a lottery running.");
}
return this.parse(`/join view-lottery-${room.roomid}`);
},
edit: "create",
create(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan("declare", null, room);
if (room.battle || !room.persist) {
return this.errorReply("This room does not support the creation of lotteries.");
}
const lottery = lotteries[room.roomid];
const edited = lottery?.running;
if (cmd === "edit" && !target && lottery) {
this.sendReply("Source:");
const markup2 = import_lib.Utils.html`${lottery.markup}`.replace(/\n/g, "<br />");
return this.sendReplyBox(`<code style="white-space: pre-wrap">/lottery edit ${lottery.maxWinners}, ${lottery.name}, ${markup2}</code>`);
}
const [maxWinners, name, markup] = import_lib.Utils.splitFirst(target, ",", 2).map((val) => val.trim());
if (!(maxWinners && name && markup.length)) {
return this.errorReply("You're missing a command parameter - see /help lottery for this command's syntax.");
}
const maxWinnersNum = parseInt(maxWinners);
this.checkHTML(markup);
if (isNaN(maxWinnersNum)) {
return this.errorReply(`${maxWinners} is not a valid number.`);
}
if (maxWinnersNum < 1) {
return this.errorReply("The maximum winners should be at least 1.");
}
if (maxWinnersNum > Number.MAX_SAFE_INTEGER) {
return this.errorReply("The maximum winners number is too large, please pick a smaller number.");
}
if (name.length > 50) {
return this.errorReply("Name needs to be under 50 characters.");
}
createLottery(room.roomid, maxWinnersNum, name, markup);
this.sendReply(`The lottery was successfully ${edited ? "edited" : "created"}.`);
if (!edited) {
this.add(
import_lib.Utils.html`|raw|<div class="broadcast-blue"><b>${user.name} created the` + ` "<a href="/view-lottery-${room.roomid}">${name}</a>" lottery!</b></div>`
);
}
this.modlog(`LOTTERY ${edited ? "EDIT" : "CREATE"} ${name}`, null, `${maxWinnersNum} max winners`);
},
delete(target, room, user) {
room = this.requireRoom();
this.checkCan("declare", null, room);
const lottery = lotteries[room.roomid];
if (!lottery) {
return this.errorReply("This room does not have a lottery running.");
}
destroyLottery(room.roomid);
this.addModAction(`${user.name} deleted the "${lottery.name}" lottery.`);
this.modlog("LOTTERY DELETE");
this.sendReply("The lottery was successfully deleted.");
},
end(target, room) {
room = this.requireRoom();
this.checkCan("declare", null, room);
const lottery = lotteries[room.roomid];
if (!lottery) {
return this.errorReply("This room does not have a lottery running.");
}
if (!lottery.running) {
return this.errorReply(`The "${lottery.name}" lottery already ended.`);
}
for (const [ip, participant] of Object.entries(lottery.participants)) {
const userid = toID(participant);
const pUser = Users.get(userid);
if (Punishments.userids.get(userid) || Punishments.getRoomPunishments(pUser || userid, { publicOnly: true, checkIps: true }).length) {
delete lottery.participants[ip];
}
}
if (lottery.maxWinners >= Object.keys(lottery.participants).length) {
return this.errorReply("There have been not enough participants for you to be able to end this. If you wish to end it anyway use /lottery delete.");
}
const winners = getWinnersInLottery(room.roomid);
if (!winners)
return this.errorReply(`An error occured while getting the winners.`);
this.add(
import_lib.Utils.html`|raw|<div class="broadcast-blue"><b>${Chat.toListString(winners)} won the "<a href="/view-lottery-${room.roomid}">${lottery.name}</a>" lottery!</b></div>`
);
this.modlog(`LOTTERY END ${lottery.name}`);
endLottery(room.roomid, winners);
},
join(target, room, user) {
const roomid = target || room?.roomid;
if (!roomid) {
return this.errorReply(`This is not a valid room.`);
}
const lottery = lotteries[roomid];
if (!lottery) {
return this.errorReply(`${roomid} does not have a lottery running.`);
}
if (!lottery.running) {
return this.errorReply(`The "${lottery.name}" lottery already ended.`);
}
if (!user.named) {
return this.popupReply("You must be logged into an account to participate.");
}
if (!user.autoconfirmed) {
return this.popupReply("You must be autoconfirmed to join lotteries.");
}
if (user.locked || Punishments.getRoomPunishments(user, { publicOnly: true, checkIps: true }).length) {
return this.popupReply("Punished users cannot join lotteries.");
}
const success = addUserToLottery(roomid, user);
if (success) {
this.popupReply("You have successfully joined the lottery.");
} else {
this.popupReply("You are already in the lottery.");
}
},
leave(target, room, user) {
const roomid = target || room?.roomid;
if (!roomid) {
return this.errorReply("This can only be used in rooms.");
}
const lottery = lotteries[roomid];
if (!lottery) {
return this.errorReply(`${roomid} does not have a lottery running.`);
}
if (!lottery.running) {
return this.errorReply(`The "${lottery.name}" lottery already ended.`);
}
const success = removeUserFromLottery(roomid, user);
if (success) {
this.popupReply("You have successfully left the lottery.");
} else {
this.popupReply("You have not joined the lottery.");
}
},
participants(target, room, user) {
room = this.requireRoom();
const lottery = lotteries[room.roomid];
if (!lottery) {
return this.errorReply("This room does not have a lottery running.");
}
const canSeeIps = user.can("ip");
const participants = Object.entries(lottery.participants).map(
([ip, participant]) => `- ${participant}${canSeeIps ? " (IP: " + ip + ")" : ""}`
);
let buf = "";
if (user.can("declare", null, room)) {
buf += `<details class="readmore"><summary><strong>List of participants (${participants.length}):</strong></summary>${participants.join("<br>")}</details>`;
} else {
buf += `${participants.length} participant(s) joined this lottery.`;
}
this.sendReplyBox(buf);
},
help() {
return this.parse("/help lottery");
}
},
lotteryhelp: [
`/lottery - opens the current lottery, if it exists.`,
`/lottery create max winners, name, html - creates a new lottery with [name] as the header and [html] as body. Max winners is the amount of people that will win the lottery. Requires # &`,
`/lottery delete - deletes the current lottery without declaring a winner. Requires # &`,
`/lottery end - ends the current lottery, declaring a random participant as the winner. Requires # &`,
`/lottery edit max winners, name, html - edits the lottery with the provided parameters. Requires # &`,
`/lottery join - joins the current lottery, if it exists, you need to be not currently punished in any public room, not locked and be autoconfirmed.`,
`/lottery leave - leaves the current lottery, if it exists.`,
`/lottery participants - shows the current participants in the lottery.`
]
};
const pages = {
lottery(query, user) {
this.title = "Lottery";
const room = this.requireRoom();
let buf = '<div class="pad">';
const lottery = lotteries[room.roomid];
if (!lottery) {
buf += `<h2>There is no lottery running in ${room.title}</h2></div>`;
return buf;
}
buf += `<h2 style="text-align: center">${lottery.name}</h2>${lottery.markup}<br />`;
if (lottery.running) {
const userSignedUp = lottery.participants[user.latestIp] || Object.values(lottery.participants).map(toID).includes(user.id);
buf += `<button class="button" name="send" style=" display: block; margin: 0 auto" value="/lottery ${userSignedUp ? "leave" : "join"} ${room.roomid}">${userSignedUp ? "Leave the " : "Sign up for the"} lottery</button>`;
} else {
buf += '<p style="text-align: center"><b>This lottery has already ended. The winners are:</b></p>';
buf += '<ul style="display: table; margin: 0px auto">';
for (const winner of lottery.winners) {
buf += `<li>${winner}</li>`;
}
buf += "</ul>";
}
return buf;
}
};
//# sourceMappingURL=lottery.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/lottery.ts"],
"sourcesContent": ["const LOTTERY_FILE = 'config/chat-plugins/lottery.json';\r\n\r\nimport {FS, Utils} from '../../lib';\r\n\r\nconst lotteriesContents = FS(LOTTERY_FILE).readIfExistsSync();\r\nconst lotteries: {\r\n\t[roomid: string]: {\r\n\t\tmaxWinners: number,\r\n\t\tname: string,\r\n\t\tmarkup: string,\r\n\t\tparticipants: {[ip: string]: string},\r\n\t\twinners: string[],\r\n\t\trunning: boolean,\r\n\t},\r\n} = lotteriesContents ? Object.assign(Object.create(null), JSON.parse(lotteriesContents)) : Object.create(null);\r\n\r\nfunction createLottery(roomid: RoomID, maxWinners: number, name: string, markup: string) {\r\n\tif (lotteries[roomid] && !lotteries[roomid].running) {\r\n\t\tdelete lotteries[roomid];\r\n\t}\r\n\tconst lottery = lotteries[roomid];\r\n\tlotteries[roomid] = {\r\n\t\tmaxWinners, name, markup, participants: lottery?.participants || Object.create(null),\r\n\t\twinners: lottery?.winners || [], running: true,\r\n\t};\r\n\twriteLotteries();\r\n}\r\nfunction writeLotteries() {\r\n\tfor (const roomid of Object.keys(lotteries)) {\r\n\t\tif (!Rooms.get(roomid)) {\r\n\t\t\tdelete lotteries[roomid];\r\n\t\t}\r\n\t}\r\n\tFS(LOTTERY_FILE).writeUpdate(() => JSON.stringify(lotteries));\r\n}\r\nfunction destroyLottery(roomid: RoomID) {\r\n\tdelete lotteries[roomid];\r\n\twriteLotteries();\r\n}\r\nfunction endLottery(roomid: RoomID, winners: string[]) {\r\n\tconst lottery = lotteries[roomid];\r\n\tif (!lottery) return;\r\n\tlottery.winners = winners;\r\n\tlottery.running = false;\r\n\tObject.freeze(lottery);\r\n\twriteLotteries();\r\n}\r\n\r\nfunction isSignedUp(roomid: RoomID, user: User) {\r\n\tconst lottery = lotteries[roomid];\r\n\tif (!lottery) return;\r\n\tconst participants = lottery.participants;\r\n\tconst participantNames = Object.values(participants).map(toID);\r\n\tif (participantNames.includes(user.id)) return true;\r\n\tif (Config.noipchecks) return false;\r\n\treturn !!participants[user.latestIp];\r\n}\r\n\r\nfunction addUserToLottery(roomid: RoomID, user: User) {\r\n\tconst lottery = lotteries[roomid];\r\n\tif (!lottery) return;\r\n\tconst participants = lottery.participants;\r\n\tif (!isSignedUp(roomid, user)) {\r\n\t\tparticipants[user.latestIp] = user.name;\r\n\t\twriteLotteries();\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\nfunction removeUserFromLottery(roomid: RoomID, user: User) {\r\n\tconst lottery = lotteries[roomid];\r\n\tif (!lottery) return;\r\n\tconst participants = lottery.participants;\r\n\tfor (const [ip, participant] of Object.entries(participants)) {\r\n\t\tif (toID(participant) === user.id || ip === user.latestIp) {\r\n\t\t\tdelete participants[ip];\r\n\t\t\twriteLotteries();\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\nfunction getWinnersInLottery(roomid: RoomID) {\r\n\tconst lottery = lotteries[roomid];\r\n\tif (!lottery) return;\r\n\tconst winners = [];\r\n\tconst participants = Object.values(lottery.participants);\r\n\tfor (let i = 0; i < lottery.maxWinners; i++) {\r\n\t\tconst randomIdx = participants.length * Math.random() << 0;\r\n\t\tconst winner = participants[randomIdx];\r\n\t\twinners.push(winner);\r\n\t\tparticipants.splice(randomIdx, 1);\r\n\t}\r\n\treturn winners;\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tlottery: {\r\n\t\t''(target, room) {\r\n\t\t\troom = this.requireRoom();\r\n\t\t\tconst lottery = lotteries[room.roomid];\r\n\t\t\tif (!lottery) {\r\n\t\t\t\treturn this.errorReply(\"This room doesn't have a lottery running.\");\r\n\t\t\t}\r\n\t\t\treturn this.parse(`/join view-lottery-${room.roomid}`);\r\n\t\t},\r\n\t\tedit: 'create',\r\n\t\tcreate(target, room, user, connection, cmd) {\r\n\t\t\troom = this.requireRoom();\r\n\t\t\tthis.checkCan('declare', null, room);\r\n\t\t\tif (room.battle || !room.persist) {\r\n\t\t\t\treturn this.errorReply('This room does not support the creation of lotteries.');\r\n\t\t\t}\r\n\t\t\tconst lottery = lotteries[room.roomid];\r\n\t\t\tconst edited = lottery?.running;\r\n\t\t\tif (cmd === 'edit' && !target && lottery) {\r\n\t\t\t\tthis.sendReply('Source:');\r\n\t\t\t\tconst markup = Utils.html`${lottery.markup}`.replace(/\\n/g, '<br />');\r\n\t\t\t\treturn this.sendReplyBox(`<code style=\"white-space: pre-wrap\">/lottery edit ${lottery.maxWinners}, ${lottery.name}, ${markup}</code>`);\r\n\t\t\t}\r\n\t\t\tconst [maxWinners, name, markup] = Utils.splitFirst(target, ',', 2).map(val => val.trim());\r\n\t\t\tif (!(maxWinners && name && markup.length)) {\r\n\t\t\t\treturn this.errorReply(\"You're missing a command parameter - see /help lottery for this command's syntax.\");\r\n\t\t\t}\r\n\t\t\tconst maxWinnersNum = parseInt(maxWinners);\r\n\t\t\tthis.checkHTML(markup);\r\n\t\t\tif (isNaN(maxWinnersNum)) {\r\n\t\t\t\treturn this.errorReply(`${maxWinners} is not a valid number.`);\r\n\t\t\t}\r\n\t\t\tif (maxWinnersNum < 1) {\r\n\t\t\t\treturn this.errorReply('The maximum winners should be at least 1.');\r\n\t\t\t}\r\n\t\t\tif (maxWinnersNum > Number.MAX_SAFE_INTEGER) {\r\nLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,iBAAwB;AAFxB,MAAM,eAAe;AAIrB,MAAM,wBAAoB,eAAG,YAAY,EAAE,iBAAiB;AAC5D,MAAM,YASF,oBAAoB,OAAO,OAAO,uBAAO,OAAO,IAAI,GAAG,KAAK,MAAM,iBAAiB,CAAC,IAAI,uBAAO,OAAO,IAAI;AAE9G,SAAS,cAAc,QAAgB,YAAoB,MAAc,QAAgB;AACxF,MAAI,UAAU,MAAM,KAAK,CAAC,UAAU,MAAM,EAAE,SAAS;AACpD,WAAO,UAAU,MAAM;AAAA,EACxB;AACA,QAAM,UAAU,UAAU,MAAM;AAChC,YAAU,MAAM,IAAI;AAAA,IACnB;AAAA,IAAY;AAAA,IAAM;AAAA,IAAQ,cAAc,SAAS,gBAAgB,uBAAO,OAAO,IAAI;AAAA,IACnF,SAAS,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S;AACrB,eAAO,KAAK,WAAW,QAAQ,QAAQ,8BAA8B;AAAA,MACtE;AACA,UAAI,CAAC,KAAK,OAAO;AAChB,eAAO,KAAK,WAAW,oDAAoD;AAAA,MAC5E;AACA,UAAI,CAAC,KAAK,eAAe;AACxB,eAAO,KAAK,WAAW,8CAA8C;AAAA,MACtE;AACA,UAAI,KAAK,UAAU,YAAY,mBAAmB,MAAM,EAAC,YAAY,MAAM,UAAU,KAAI,CAAC,EAAE,QAAQ;AACnG,eAAO,KAAK,WAAW,uCAAuC;AAAA,MAC/D;AACA,YAAM,UAAU,iBAAiB,QAAkB,IAAI;AACvDLine truncated
"names": ["markup"]
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/mafia.ts"],
"sourcesContent": ["import {Utils, FS} from '../../lib';\r\n\r\ninterface MafiaData {\r\n\t// keys for all of these are IDs\r\n\talignments: {[k: string]: MafiaDataAlignment};\r\n\troles: {[k: string]: MafiaDataRole};\r\n\tthemes: {[k: string]: MafiaDataTheme};\r\n\tIDEAs: {[k: string]: MafiaDataIDEA};\r\n\tterms: {[k: string]: MafiaDataTerm};\r\n\taliases: {[k: string]: ID};\r\n}\r\ninterface MafiaDataAlignment {\r\n\tname: string;\r\n\tplural: string;\r\n\tcolor?: string;\r\n\tbuttonColor?: string;\r\n\tmemo: string[];\r\n\timage?: string;\r\n}\r\ninterface MafiaDataRole {\r\n\tname: string;\r\n\tmemo: string[];\r\n\talignment?: string;\r\n\timage?: string;\r\n}\r\ninterface MafiaDataTheme {\r\n\tname: string;\r\n\tdesc: string;\r\n\t// roles\r\n\t[players: number]: string;\r\n}\r\ninterface MafiaDataIDEA {\r\n\tname: string;\r\n\troles: string[];\r\n\tpicks: string[];\r\n\tchoices: number;\r\n}\r\ninterface MafiaDataTerm {\r\n\tname: string;\r\n\tmemo: string[];\r\n}\r\n\r\ninterface MafiaLogTable {\r\n\t[date: string]: {[userid: string]: number};\r\n}\r\ntype MafiaLogSection = 'leaderboard' | 'mvps' | 'hosts' | 'plays' | 'leavers';\r\ntype MafiaLog = {[section in MafiaLogSection]: MafiaLogTable};\r\n\r\ninterface MafiaRole {\r\n\tname: string;\r\n\tsafeName: string;\r\n\tid: string;\r\n\tmemo: string[];\r\n\talignment: string;\r\n\timage: string;\r\n}\r\n\r\ninterface MafiaVote {\r\n\t// number of people on this vote\r\n\tcount: number;\r\n\t// number of votes, accounting for doublevoter etc\r\n\ttrueCount: number;\r\n\tlastVote: number;\r\n\tdir: 'up' | 'down';\r\n\tvoters: ID[];\r\n}\r\n\r\ninterface MafiaIDEAData {\r\n\tname: string;\r\n\t// do we trust the roles to parse properly\r\n\tuntrusted?: true;\r\n\troles: string[];\r\n\t// eg, GestI has 3 choices\r\n\tchoices: number;\r\n\t// eg, GestI has 2 things to pick, role and alignment\r\n\tpicks: string[];\r\n}\r\ninterface MafiaIDEAModule {\r\n\tdata: MafiaIDEAData | null;\r\n\ttimer: NodeJS.Timer | null;\r\n\tdiscardsHidden: boolean;\r\n\tdiscardsHTML: string;\r\n\t// users that haven't picked a role yet\r\n\twaitingPick: string[];\r\n}\r\ninterface MafiaIDEAPlayerData {\r\n\tchoices: string[];\r\n\toriginalChoices: string[];\r\n\tpicks: {[choice: string]: string | null};\r\n}\r\n\r\nconst DATA_FILE = 'config/chat-plugins/mafia-data.json';\r\nconst LOGS_FILE = 'config/chat-plugins/mafia-logs.json';\r\n\r\n// see: https://play.pokemonshowdown.com/fx/\r\nconst VALID_IMAGES = [\r\n\t'cop', 'dead', 'doctor', 'fool', 'godfather', 'goon', 'hooker', 'mafia', 'mayor', 'villager', 'werewolf',\r\n];\r\n\r\nlet MafiaData: MafiaData = Object.create(null);\r\nlet logs: MafiaLog = {leaderboard: {}, mvps: {}, hosts: {}, plays: {}, leavers: {}};\r\n\r\nPunishments.addRoomPunishmentType({\r\n\ttype: 'MAFIAGAMEBAN',\r\n\tdesc: 'banned from playing mafia games',\r\n});\r\nPunishments.addRoomPunishmentType({\r\n\ttype: 'MAFIAHOSTBAN',\r\n\tdesc: 'banned from hosting mafia games',\r\n});\r\n\r\nconst hostQueue: ID[] = [];\r\n\r\nconst IDEA_TIMER = 60 * 1000;\r\n\r\nfunction readFile(path: string) {\r\n\ttry {\r\n\t\tconst json = FS(path).readIfExistsSync();\r\n\t\tif (!json) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn Object.assign(Object.create(null), JSON.parse(json));\r\n\t} catch (e: any) {\r\n\t\tif (e.code !== 'ENOENT') throw e;\r\n\t}\r\n}\r\nfunction writeFile(path: string, data: AnyObject) {\r\n\tFS(path).writeUpdate(() => (\r\n\t\tJSON.stringify(data)\r\n\t));\r\n}\r\n\r\n// data assumptions -\r\n// the alignments \"town\" and \"solo\" always exist (defaults)\r\n// <role>.alignment is always a valid key in data.alignments\r\n// roles and alignments have no common keys (looked up together in the role parser)\r\n// themes and IDEAs have no common keys (looked up together when setting themes)\r\n\r\n// Load data\r\nMafiaData = readFile(DATA_FILE) || {alignments: {}, roles: {}, themes: {}, IDEAs: {}, terms: {}, aliases: {}};\r\nif (!MafiaData.alignments.town) {\r\n\tMafiaData.alignments.town = {\r\n\t\tname: 'town', plural: 'town', memo: [`This alignment is required for the script to function properly.`],\r\n\t};\r\n}\r\nif (!MafiaData.alignments.solo) {\r\n\tMafiaData.alignments.solo = {\r\n\t\tname: 'solo', plural: 'solo', memo: [`This alignment is required for the script to function properly.`],\r\n\t};\r\n}\r\n\r\nlogs = readFile(LOGS_FILE) || {leaderboard: {}, mvps: {}, hosts: {}, plays: {}, leavers: {}};\r\n\r\nconst tables: MafiaLogSection[] = ['leaderboard', 'mvps', 'hosts', 'plays', 'leavers'];\r\nfor (const section of tables) {\r\n\t// Check to see if we need to eliminate an old month's data.\r\n\tconst month = new Date().toLocaleString(\"en-us\", {month: \"numeric\", year: \"numeric\"});\r\n\tif (!logs[section]) logs[section] = {};\r\n\tif (!logs[section][month]) logs[section][month] = {};\r\n\tif (Object.keys(logs[section]).length >= 3) {\r\n\t\t// eliminate the oldest month(s)\r\n\t\tconst keys = Utils.sortBy(Object.keys(logs[section]), key =Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAwB;AA2FxB,MAAM,YAAY;AAClB,MAAM,YAAY;AAGlB,MAAM,eAAe;AAAA,EACpB;AAAA,EAAO;AAAA,EAAQ;AAAA,EAAU;AAAA,EAAQ;AAAA,EAAa;AAAA,EAAQ;AAAA,EAAU;AAAA,EAAS;AAAA,EAAS;AAAA,EAAY;AAC/F;AAEA,IAAI,YAAuB,uBAAO,OAAO,IAAI;AAC7C,IAAI,OAAiB,EAAC,aAAa,CAAC,GAAG,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,OAAO,CAAC,GAAG,SAAS,CAAC,EAAC;AAElF,YAAY,sBAAsB;AAAA,EACjC,MAAM;AAAA,EACN,MAAM;AACP,CAAC;AACD,YAAY,sBAAsB;AAAA,EACjC,MAAM;AAAA,EACN,MAAM;AACP,CAAC;AAED,MAAM,YAAkB,CAAC;AAEzB,MAAM,aAAa,KAAK;AAExB,SAAS,SAAS,MAAc;AAC/B,MAAI;AACH,UAAM,WAAO,eAAG,IAAI,EAAE,iBAAiB;AACvC,QAAI,CAAC,MAAM;AACV,aAAO;AAAA,IACR;AACA,WAAO,OAAO,OAAO,uBAAO,OAAO,IAAI,GAAG,KAAK,MAAM,IAAI,CAAC;AAAA,EAC3D,SAAS,GAAP;AACD,QAAI,EAAE,SAAS;AAAU,YAAM;AAAA,EAChC;AACD;AACA,SAAS,UAAU,MAAc,MAAiB;AACjD,qBAAG,IAAI,EAAE,YAAY,MACpB,KAAK,UAAU,IAAI,CACnB;AACF;AASA,YAAY,SAAS,SAAS,KAAK,EAAC,YAAY,CAAC,GAAG,OAAO,CAAC,GAAG,QAAQ,CAAC,GAAG,OAAO,CAAC,GAAG,OAAO,CAAC,GAAG,SAAS,CAAC,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AK,gBAAgB;AACjH,QAAI,CAAC,KAAK,UAAU,IAAI;AAAG,aAAO,KAAK,OAAO,KAAK,MAAM,8CAA8C,KAAK,QAAQ;AACpH,QAAI,KAAK,KAAK,SAAS,KAAK,EAAE;AAAG,WAAK,KAAK,OAAO,KAAK,KAAK,QAAQ,KAAK,EAAE,GAAG,CAAC;AAC/E,SAAK,YAAY,KAAK,EAAE,EAAE,eAAe;AACzC,SAAK,SAAS,GAAG,KAAK,YAAY,KAAK,EAAE,EAAE,2BAA2B;AAAA,EACvE;AAAA,EAEA,MAAM,MAAY;AACjB,QAAI,EAAE,KAAK,MAAM,KAAK,cAAc;AACnC,aAAO,KAAK,OAAO,KAAK,MAAM,0CAA0C,KAAK,QAAQ;AAAA,IACtF;AACA,QAAI,KAAK,UAAU;AAAW,aAAO,KAAK,OAAO,KAAK,MAAM,sBAAsB,KAAK,4BAA4B;AACnH,SAAK,YAAY,KAAK,EAAE,EAAE,QAAQ;AAClC,WAAO,KAAK,YAAY,KAAK,EAAE;AAC/B,SAAK;AACL,QAAI,WAAW,KAAK,aAAa,QAAQ,KAAK,EAAE;AAChD,QAAI,aAAa;AAAI,WAAK,aAAa,OAAO,UAAU,CAAC;AACzD,eAAW,KAAK,iBAAiB,QAAQ,KAAK,EAAE;AAChD,QAAI,aAAa;AAAI,WAAK,iBAAiB,OAAO,UAAU,CAAC;AAC7D,SAAK,SAAS,GAAG,KAAK,yBAAyB;AAC/C,eAAW,QAAQ,KAAK,aAAa;AACpC,WAAK,KAAK,YAAY,cAAc,KAAK,KAAK,UAAU,MAAM,IAAI;AAAA,IACnE;AAAA,EACD;AAAA,EAEA,OAAO,aAAa,MAAY,MAAY;AAC3C,WAAO,YAAY,kBAAkLine truncated
"names": ["player", "game"]
}
@@ -0,0 +1,453 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var modlog_viewer_exports = {};
__export(modlog_viewer_exports, {
commands: () => commands,
pages: () => pages
});
module.exports = __toCommonJS(modlog_viewer_exports);
var import_lib = require("../../lib");
/**
* Modlog viewer
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Actually reading, writing, and searching modlog is handled in server/modlog/.
*
* @license MIT
*/
const MAX_QUERY_LENGTH = 2500;
const DEFAULT_RESULTS_LENGTH = 100;
const MORE_BUTTON_INCREMENTS = [200, 400, 800, 1600, 3200];
const LINES_SEPARATOR = "lines=";
const MAX_RESULTS_LENGTH = MORE_BUTTON_INCREMENTS[MORE_BUTTON_INCREMENTS.length - 1];
const IPS_REGEX = /[([]?([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})[)\]]?/g;
const ALIASES = {
"helpticket": "help-rooms",
"groupchat": "groupchat-rooms",
"battle": "battle-rooms"
};
function getMoreButton(roomid, searchCmd, lines, maxLines, onlyPunishments, onlyNotes) {
let newLines = 0;
for (const increase of MORE_BUTTON_INCREMENTS) {
if (increase > lines) {
newLines = increase;
break;
}
}
if (!newLines || lines < maxLines) {
return "";
} else {
let cmd = `/modlog`;
if (onlyNotes)
cmd = `/modnotes`;
if (onlyPunishments)
cmd = `/punishlog`;
return import_lib.Utils.html`<br /><div style="text-align:center"><button class="button" name="send" value="${cmd} room=${roomid}, ${searchCmd}, ${LINES_SEPARATOR}${newLines}" title="View more results">Older results<br />&#x25bc;</button></div>`;
}
}
function getRoomID(id) {
if (id in ALIASES)
return ALIASES[id];
return id;
}
function prettifyResults(resultArray, roomid, search, searchCmd, addModlogLinks, hideIps, maxLines, onlyPunishments, onlyNotes) {
if (resultArray === null) {
return "|popup|The modlog query crashed.";
}
let roomName;
switch (roomid) {
case "all":
roomName = "all rooms";
break;
case "public":
roomName = "all public rooms";
break;
default:
roomName = `room ${roomid}`;
}
const scope = onlyPunishments ? "punishment-related " : "";
let searchString = ``;
const excludes = search.note.filter((s) => s.isExclusion).map((s) => s.search) || [];
const includes = search.note.filter((s) => !s.isExclusion).map((s) => s.search) || [];
if (includes.length)
searchString += `with a note including any of: ${includes.join(", ")} `;
if (excludes.length)
searchString += `with a note that does not include any of: ${excludes.join(", ")} `;
for (const u of search.user)
searchString += `${u.isExclusion ? "not " : ""}taken against ${u.search} `;
for (const ip of search.ip) {
searchString += `${ip.isExclusion ? "not " : ""}taken against a user on the IP ${ip.search} `;
}
for (const action of search.action)
searchString += `${action.isExclusion ? "not " : ""}of the type ${action.search} `;
for (const actionTaker of search.actionTaker) {
searchString += `${actionTaker.isExclusion ? "not " : ""}taken by ${actionTaker.search} `;
}
if (!resultArray.length) {
return `|popup|No ${scope}moderator actions ${searchString}found on ${roomName}.`;
}
const title = `[${roomid}] ${searchCmd}`;
const lines = resultArray.length;
let curDate = "";
const resultString = resultArray.map((result) => {
const date = new Date(result.time || Date.now());
const entryRoom = result.visualRoomID || result.roomID || "global";
let [dateString2, timestamp2] = Chat.toTimestamp(date, { human: true }).split(" ");
let line = `<small>[${timestamp2}] (${entryRoom})</small> ${result.action}`;
if (result.userid) {
line += `: [${result.userid}]`;
if (result.autoconfirmedID)
line += ` ac: [${result.autoconfirmedID}]`;
if (result.alts.length)
line += ` alts: [${result.alts.join("], [")}]`;
if (!hideIps && result.ip)
line += ` [${result.ip}]`;
}
if (result.loggedBy)
line += `: by ${result.loggedBy}`;
if (result.note)
line += `: ${result.note}`;
if (dateString2 !== curDate) {
curDate = dateString2;
dateString2 = `</p><p>[${dateString2}]<br />`;
} else {
dateString2 = ``;
}
const thisRoomID = entryRoom?.split(" ")[0];
if (addModlogLinks) {
if (thisRoomID.startsWith("battle-")) {
timestamp2 = `<a href="/${thisRoomID}">${timestamp2}</a>`;
} else {
const [day, time] = Chat.toTimestamp(date).split(" ");
timestamp2 = `<a href="/view-chatlog-${thisRoomID}--${day}--time-${toID(time)}">${timestamp2}</a>`;
}
}
line = import_lib.Utils.escapeHTML(line.slice(line.indexOf(")") + ` </small>`.length));
line = line.replace(
IPS_REGEX,
hideIps ? "" : `[<a href="https://whatismyipaddress.com/ip/$1" target="_blank">$1</a>]`
);
return `${dateString2}<small>[${timestamp2}] (${thisRoomID})</small>${line}`;
}).join(`<br />`);
const [dateString, timestamp] = Chat.toTimestamp(new Date(), { human: true }).split(" ");
let preamble;
const modlogid = roomid + (searchString ? "-" + import_lib.Dashycode.encode(searchString) : "");
if (searchString) {
preamble = `>view-modlog-${modlogid}
|init|html
|title|[Modlog]${title}
|pagehtml|<div class="pad"><p>The last ${scope}${Chat.count(lines, "logged actions")} ${import_lib.Utils.escapeHTML(searchString)} on ${roomName}.`;
} else {
preamble = `>view-modlog-${modlogid}
|init|html
|title|[Modlog]${title}
|pagehtml|<div class="pad"><p>The last ${Chat.count(lines, `${scope}lines`)} of the Moderator Log of ${roomName}.`;
}
preamble += `</p><p>[${dateString}]<br /><small>[${timestamp}] \u2190 current server time</small>`;
const moreButton = getMoreButton(roomid, searchCmd, lines, maxLines, onlyPunishments, onlyNotes);
return `${preamble}${resultString}${moreButton}</div>`;
}
async function getModlog(connection, roomid = "global", search, searchCmd, maxLines = 20, onlyPunishments = false, timed = false, onlyNotes = false) {
const targetRoom = Rooms.search(roomid);
const user = connection.user;
roomid = getRoomID(roomid);
if (roomid === "all" || roomid === "public") {
if (!user.can("modlog")) {
return connection.popup("Access denied");
}
} else {
if (!user.can("modlog", null, targetRoom) && !user.can("modlog")) {
return connection.popup("Access denied");
}
}
const hideIps = !user.can("lock");
const addModlogLinks = !!(user.tempGroup !== " " || targetRoom && targetRoom.settings.isPrivate !== true);
if (hideIps && search.ip.length) {
connection.popup(`You cannot search for IPs.`);
return;
}
if (Object.values(search).join("").length > MAX_QUERY_LENGTH) {
connection.popup(`Your search query is too long.`);
return;
}
if (search.note?.length) {
for (const [i, noteSearch] of search.note.entries()) {
if (/^["'].+["']$/.test(noteSearch.search)) {
search.note[i] = { ...noteSearch, search: noteSearch.search.substring(1, noteSearch.search.length - 1) };
search.note[i].isExact = true;
}
}
}
for (const [i, userSearch] of search.user.entries()) {
if (/^["'].+["']$/.test(userSearch.search)) {
userSearch.search = userSearch.search.substring(1, userSearch.search.length - 1);
userSearch.isExact = true;
}
userSearch.search = toID(userSearch.search);
search.user[i] = userSearch;
}
if (onlyNotes)
search.action.push({ search: "NOTE" });
const response = await Rooms.Modlog.search(roomid, search, maxLines, onlyPunishments);
if (!response)
return connection.popup(`The moderator log is currently disabled.`);
connection.send(
prettifyResults(
response.results,
roomid,
search,
searchCmd,
addModlogLinks,
hideIps,
maxLines,
onlyPunishments,
onlyNotes
)
);
if (timed)
connection.popup(`The modlog query took ${response.duration} ms to complete.`);
}
const shouldSearchGlobal = ["staff", "adminlog"];
const commands = {
ml: "modlog",
punishlog: "modlog",
pl: "modlog",
timedmodlog: "modlog",
mlid: "modlog",
mlip: "modlog",
plid: "modlog",
plip: "modlog",
modnotes: "modlog",
modlog(target, room, user, connection, cmd) {
let roomid = !room || shouldSearchGlobal.includes(room.roomid) ? "global" : room.roomid;
const onlyPunishments = cmd.startsWith("pl") || cmd.startsWith("punishlog");
let lines;
const possibleParam = cmd.slice(2);
const targets = target.split(",").map((f) => f.trim()).filter(Boolean);
const search = { note: [], user: [], ip: [], action: [], actionTaker: [] };
switch (possibleParam) {
case "id":
targets.unshift(`user='${targets.shift()}'`);
break;
case "ip":
targets.unshift(`ip=${targets.shift()}`);
break;
}
for (const [i, option] of targets.entries()) {
let [param, value] = option.split("=").map((part) => part.trim());
if (!value) {
value = param.trim();
if (i === 0 && value) {
param = "room";
if (!Rooms.search(toID(value)) && !user.can("lock")) {
return this.parse(`/help modlog`);
}
} else {
this.errorReply(`You must specify a search type and search value.`);
return this.parse(`/help modlog`);
}
}
const isExclusion = param.endsWith("!");
param = toID(param);
switch (param) {
case "note":
case "text":
if (!search.note)
search.note = [];
search.note.push({ search: value, isExclusion });
break;
case "user":
case "name":
case "username":
case "userid":
search.user.push({ search: value });
break;
case "ip":
case "ipaddress":
case "ipaddr":
search.ip.push({ search: value, isExclusion });
break;
case "action":
case "punishment":
search.action.push({ search: value.toUpperCase(), isExclusion });
break;
case "actiontaker":
case "moderator":
case "staff":
case "mod":
search.actionTaker.push({ search: toID(value), isExclusion });
break;
case "room":
case "roomid":
roomid = value.toLowerCase().replace(/[^a-z0-9-]+/g, "");
break;
case "lines":
case "maxlines":
lines = parseInt(value);
if (isNaN(lines) || lines < 1)
return this.errorReply(`Invalid linecount: '${value}'.`);
break;
default:
this.errorReply(`Invalid modlog parameter: '${param}'.`);
return this.errorReply(`Please specify 'room', 'note', 'user', 'ip', 'action', 'staff', or 'lines'.`);
}
}
const targetRoom = Rooms.search(roomid);
if (targetRoom)
roomid = targetRoom.roomid;
if (roomid.includes("-")) {
if (user.can("modlog")) {
roomid = "global";
} else {
return this.errorReply(`Only global staff may view battle and groupchat modlogs.`);
}
}
if (!target && !lines) {
lines = 20;
}
if (!lines)
lines = DEFAULT_RESULTS_LENGTH;
if (lines > MAX_RESULTS_LENGTH)
lines = MAX_RESULTS_LENGTH;
void getModlog(
connection,
roomid,
search,
target.replace(/^\s?([^,=]*),\s?/, "").replace(/,?\s*(room|lines)\s*=[^,]*,?/g, ""),
lines,
onlyPunishments,
cmd === "timedmodlog",
cmd === "modnotes"
);
},
modloghelp() {
this.sendReplyBox(
`<code>/modlog [comma-separated list of parameters]</code>: searches the moderator log, defaulting to the current room unless specified otherwise.<br />You can replace the <code>=</code> in a parameter with a <code>!=</code> to exclude entries that match that parameter.<br /><details><summary><strong>Parameters</strong></summary><ul><li><code>room=[room]</code> - searches a room's modlog</li><li><code>userid=[user]</code> - searches for a username (or fragment of one)</li><li><code>note=[text]</code> - searches the contents of notes/reasons</li><li><code>ip=[IP address]</code> - searches for an IP address (or fragment of one)</li><li><code>staff=[user]</code> - searches for actions taken by a particular staff member</li><li><code>action=[type]</code> - searches for a particular type of action</li><li><code>lines=[number]</code> - displays the given number of lines</li></ul></details><details><summary><strong>Additional commands</strong></summary><ul><li><code>/mlid [user]</code> - searches for actions taken against a specific user</li><li><code>/mlip [IP address]</code> - searches for actions taken against a specific IP address</li><li><code>/punishlog</code>, <code>/pl</code>, <code>/plid</code>, <code>/plip</code> - like <code>/modlog</code>, but only displays punishments</li><li><code>/modnotes</code> - searches only modnotes</li></ul></details>`
);
},
mls: "modlogstats",
modlogstats(target, room, user) {
this.checkCan("lock");
target = toID(target);
if (!target)
return this.parse(`/help modlogstats`);
return this.parse(`/join view-modlogstats-${target}`);
},
modlogstatshelp: [`/modlogstats [userid] - Fetch all information on that [userid] from the modlog (IPs, alts, etc). Requires: @ &`]
};
const pages = {
async modlogstats(query, user) {
this.checkCan("lock");
const target = toID(query.shift());
if (!target || target.length > 18) {
return this.errorReply(`Invalid userid - must be between 1 and 18 characters long.`);
}
this.title = `[Modlog Stats] ${target}`;
this.setHTML(`<div class="pad"><strong>Running modlog search...</strong></div>`);
const entries = await Rooms.Modlog.search("global", {
user: [{
search: target,
isExact: true
}],
note: [],
ip: [],
action: [],
actionTaker: []
}, 1e3);
if (!entries?.results.length) {
return this.errorReply(`No data found.`);
}
const punishmentTable = new import_lib.Utils.Multiset();
const punishmentsByIp = /* @__PURE__ */ new Map();
const actionsWithIp = /* @__PURE__ */ new Set();
const alts = /* @__PURE__ */ new Set();
const autoconfirmed = /* @__PURE__ */ new Set();
const ips = /* @__PURE__ */ new Set();
for (const entry of entries.results) {
if (entry.action !== "NOTE") {
punishmentTable.add(entry.action);
if (entry.ip) {
let ipTable = punishmentsByIp.get(entry.ip);
if (!ipTable) {
ipTable = new import_lib.Utils.Multiset();
punishmentsByIp.set(entry.ip, ipTable);
}
ipTable.add(entry.action);
actionsWithIp.add(entry.action);
}
}
if (entry.alts) {
for (const alt of entry.alts)
alts.add(alt);
}
if (entry.autoconfirmedID)
autoconfirmed.add(entry.autoconfirmedID);
if (entry.ip)
ips.add(entry.ip);
}
let buf = `<div class="pad"><h2>Modlog information for ${target}</h2><hr />`;
if (alts.size) {
buf += `<strong>Listed alts:</strong> `;
buf += `<small>(These are userids sharing the same IP at the time of the punishment, they may not be direct alts)</small><br />`;
buf += [...alts].map((id) => `<a href="https://${Config.routes.root}/users/${toID(id)}">${toID(id)}</a>`).join(", ");
buf += `<br /><br />`;
}
if (autoconfirmed.size) {
buf += `<strong>Autoconfirmed alts:</strong>`;
buf += ` (these are autoconfirmed accounts linked to their name, and are very likely them)<br />`;
buf += [...autoconfirmed].map((id) => `<a href="https://${Config.routes.root}/users/${toID(id)}">${toID(id)}</a>`).join(", ");
buf += `<br /><br />`;
}
if (ips.size) {
buf += `<strong>Known IPs:</strong><br />`;
const mapped = await Promise.all([...ips].map(async (ip) => {
const info = await IPTools.lookup(ip);
return `<a href="https://whatismyipaddress.com/ip/${ip}">${ip}</a> [${info.hostType}]`;
}));
buf += mapped.join(", ");
buf += `<br /><br />`;
}
if (punishmentTable.size) {
buf += `<strong>Punishments:</strong><br />`;
buf += `<div class="ladder pad"><table>`;
buf += `<tr><th>Punishment type</th><th>Count</th></tr>`;
for (const [punishment, number] of punishmentTable) {
buf += `<tr><td>${punishment}</td><td>${number}</td></tr>`;
}
buf += `</table></div><br />`;
}
if (punishmentsByIp.size) {
buf += `<strong>Punishments by IP:</strong><br />`;
const keys = [...actionsWithIp];
buf += `<div class="ladder pad"><table>`;
buf += `<tr><th></th>${keys.map((k) => `<th>${k}</th>`).join("")}</tr>`;
for (const [ip, table] of punishmentsByIp) {
buf += `<tr><td><a href="https://whatismyipaddress.com/ip/${ip}">${ip}</a></td>`;
for (const key of keys) {
buf += `<td>${table.get(key) || 0}</td>`;
}
buf += `</tr>`;
}
buf += `</table></div>`;
}
buf += `<br /><br />`;
return buf;
}
};
//# sourceMappingURL=modlog-viewer.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/modlog-viewer.ts"],
"sourcesContent": ["/**\r\n * Modlog viewer\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * Actually reading, writing, and searching modlog is handled in server/modlog/.\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {Dashycode, Utils} from '../../lib';\r\nimport {ModlogID, ModlogSearch, ModlogEntry} from '../modlog';\r\n\r\nconst MAX_QUERY_LENGTH = 2500;\r\nconst DEFAULT_RESULTS_LENGTH = 100;\r\nconst MORE_BUTTON_INCREMENTS = [200, 400, 800, 1600, 3200];\r\nconst LINES_SEPARATOR = 'lines=';\r\nconst MAX_RESULTS_LENGTH = MORE_BUTTON_INCREMENTS[MORE_BUTTON_INCREMENTS.length - 1];\r\nconst IPS_REGEX = /[([]?([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})[)\\]]?/g;\r\n\r\nconst ALIASES: {[k: string]: string} = {\r\n\t'helpticket': 'help-rooms',\r\n\t'groupchat': 'groupchat-rooms',\r\n\t'battle': 'battle-rooms',\r\n};\r\n\r\n/*********************************************************\r\n * Modlog Functions\r\n *********************************************************/\r\n\r\nfunction getMoreButton(\r\n\troomid: ModlogID, searchCmd: string,\r\n\tlines: number, maxLines: number, onlyPunishments: boolean, onlyNotes: boolean,\r\n) {\r\n\tlet newLines = 0;\r\n\tfor (const increase of MORE_BUTTON_INCREMENTS) {\r\n\t\tif (increase > lines) {\r\n\t\t\tnewLines = increase;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (!newLines || lines < maxLines) {\r\n\t\treturn ''; // don't show a button if no more pre-set increments are valid or if the amount of results is already below the max\r\n\t} else {\r\n\t\tlet cmd = `/modlog`;\r\n\t\tif (onlyNotes) cmd = `/modnotes`;\r\n\t\tif (onlyPunishments) cmd = `/punishlog`;\r\n\r\n\t\treturn Utils.html`<br /><div style=\"text-align:center\"><button class=\"button\" name=\"send\" value=\"${cmd} room=${roomid}, ${searchCmd}, ${LINES_SEPARATOR}${newLines}\" title=\"View more results\">Older results<br />&#x25bc;</button></div>`;\r\n\t}\r\n}\r\n\r\nfunction getRoomID(id: string) {\r\n\tif (id in ALIASES) return ALIASES[id] as ModlogID;\r\n\treturn id as ModlogID;\r\n}\r\n\r\nfunction prettifyResults(\r\n\tresultArray: ModlogEntry[], roomid: ModlogID, search: ModlogSearch, searchCmd: string,\r\n\taddModlogLinks: boolean, hideIps: boolean, maxLines: number, onlyPunishments: boolean, onlyNotes: boolean\r\n) {\r\n\tif (resultArray === null) {\r\n\t\treturn \"|popup|The modlog query crashed.\";\r\n\t}\r\n\tlet roomName;\r\n\tswitch (roomid) {\r\n\tcase 'all':\r\n\t\troomName = \"all rooms\";\r\n\t\tbreak;\r\n\tcase 'public':\r\n\t\troomName = \"all public rooms\";\r\n\t\tbreak;\r\n\tdefault:\r\n\t\troomName = `room ${roomid}`;\r\n\t}\r\n\tconst scope = onlyPunishments ? 'punishment-related ' : '';\r\n\tlet searchString = ``;\r\n\tconst excludes = search.note.filter(s => s.isExclusion).map(s => s.search) || [];\r\n\tconst includes = search.note.filter(s => !s.isExclusion).map(s => s.search) || [];\r\n\tif (includes.length) searchString += `with a note including any of: ${includes.join(', ')} `;\r\n\tif (excludes.length) searchString += `with a note that does not include any of: ${excludes.join(', ')} `;\r\n\tfor (const u of search.user) searchString += `${u.isExclusion ? 'not ' : ''}taken against ${u.search} `;\r\n\tfor (const ip of search.ip) {\r\n\t\tsearchString += `${ip.isExclusion ? 'not ' : ''}taken against a user on the IP ${ip.search} `;\r\n\t}\r\n\tfor (const action of search.action) searchString += `${action.isExclusion ? 'not ' : ''}of the type ${action.search} `;\r\n\tfor (const actionTaker of search.actionTaker) {\r\n\t\tsearchString += `${actionTaker.isExclusion ? 'not ' : ''}taken by ${actionTaker.search} `;\r\n\t}\r\n\tif (!resultArray.length) {\r\n\t\treturn `|popup|No ${scope}moderator actions ${searchString}found on ${roomName}.`;\r\n\t}\r\n\tconst title = `[${roomid}] ${searchCmd}`;\r\n\tconst lines = resultArray.length;\r\n\tlet curDate = '';\r\n\tconst resultString = resultArray.map(result => {\r\n\t\tconst date = new Date(result.time || Date.now());\r\n\t\tconst entryRoom = result.visualRoomID || result.roomID || 'global';\r\n\t\tlet [dateString, timestamp] = Chat.toTimestamp(date, {human: true}).split(' ');\r\n\t\tlet line = `<small>[${timestamp}] (${entryRoom})</small> ${result.action}`;\r\n\t\tif (result.userid) {\r\n\t\t\tline += `: [${result.userid}]`;\r\n\t\t\tif (result.autoconfirmedID) line += ` ac: [${result.autoconfirmedID}]`;\r\n\t\t\tif (result.alts.length) line += ` alts: [${result.alts.join('], [')}]`;\r\n\t\t\tif (!hideIps && result.ip) line += ` [${result.ip}]`;\r\n\t\t}\r\n\r\n\t\tif (result.loggedBy) line += `: by ${result.loggedBy}`;\r\n\t\tif (result.note) line += `: ${result.note}`;\r\n\r\n\t\tif (dateString !== curDate) {\r\n\t\t\tcurDate = dateString;\r\n\t\t\tdateString = `</p><p>[${dateString}]<br />`;\r\n\t\t} else {\r\n\t\t\tdateString = ``;\r\n\t\t}\r\n\t\tconst thisRoomID = entryRoom?.split(' ')[0];\r\n\t\tif (addModlogLinks) {\r\n\t\t\tif (thisRoomID.startsWith('battle-')) {\r\n\t\t\t\ttimestamp = `<a href=\"/${thisRoomID}\"Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,iBAA+B;AAT/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAC/B,MAAM,yBAAyB,CAAC,KAAK,KAAK,KAAK,MAAM,IAAI;AACzD,MAAM,kBAAkB;AACxB,MAAM,qBAAqB,uBAAuB,uBAAuB,S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WAAO,OAAO,KAAK,EAAC,QAAQ,OAAM,CAAC;AAElD,QAAM,WAAW,MAAM,MAAM,OAAO,OAAO,QAAQ,QAAQ,UAAU,eAAe;AACpF,MAAI,CAAC;AAAU,WAAO,WAAW,MAAM,0CAA0C;AAEjF,aAAW;AAAA,IACV;AAAA,MACC,SAAS;AAAA,MACT;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAAA,EACD;AACA,MAAI;AAAO,eAAW,MAAM,yBAAyB,SAAS,0BAA0B;AACzF;AAEA,MAAM,qBAAqB,CAAC,SAAS,UAAU;AAExC,MAAM,WAA8B;AAAA,EAC1C,IAAI;AAAA,EACJ,WAAW;AAAA,EACX,IAAI;AAAA,EACJ,aAAa;AAAA,EACb,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,UAAU;AAAA,EACV,OAAO,QAAQ,MAAM,MAAM,YAAY,KAAK;AAC3C,QAAI,SAAoB,CAAC,QAALine truncated
"names": ["dateString", "timestamp"]
}
+787
View File
@@ -0,0 +1,787 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var othermetas_exports = {};
__export(othermetas_exports, {
commands: () => commands
});
module.exports = __toCommonJS(othermetas_exports);
var import_lib = require("../../lib");
function getMegaStone(stone, mod = "gen9") {
let dex = Dex;
if (mod && toID(mod) in Dex.dexes)
dex = Dex.mod(toID(mod));
const item = dex.items.get(stone);
if (!item.exists) {
if (toID(stone) === "dragonascent") {
const move = dex.moves.get(stone);
return {
id: move.id,
name: move.name,
fullname: move.name,
megaEvolves: "Rayquaza",
megaStone: "Rayquaza-Mega",
exists: true,
// Adding extra values to appease typescript
gen: 6,
num: -1,
effectType: "Item",
sourceEffect: ""
};
} else {
return null;
}
}
if (!item.megaStone && !item.onPrimal && !item.forcedForme?.endsWith("Epilogue") && !item.forcedForme?.endsWith("Origin") && !item.name.startsWith("Rusted"))
return null;
return item;
}
const commands = {
om: "othermetas",
othermetas(target, room, user) {
target = toID(target);
const omLink = `- <a href="https://www.smogon.com/forums/forums/733/">Other Metagames Forum</a><br />`;
if (!target) {
this.runBroadcast();
return this.sendReplyBox(omLink);
}
if (target === "all") {
this.runBroadcast();
if (this.broadcasting) {
throw new Chat.ErrorMessage(`"!om all" is too spammy to broadcast.`);
}
this.parse(`/formathelp omofthemonth`);
this.parse(`/formathelp othermetagames`);
return this.sendReply(`|raw|<center>${omLink}</center>`);
}
if (target === "month")
this.target = "omofthemonth";
this.run("formathelp");
},
othermetashelp: [
`/om - Provides links to information on the Other Metagames.`,
`!om - Show everyone that information. Requires: + % @ # &`
],
mnm: "mixandmega",
mixandmega(target, room, user) {
if (!toID(target) || !target.includes("@"))
return this.parse("/help mixandmega");
this.runBroadcast();
let dex = Dex;
const sep = target.split("@");
const stoneName = sep.slice(1).join("@").trim().split(",");
const mod = stoneName[1];
if (mod) {
if (toID(mod) in Dex.dexes) {
dex = Dex.mod(toID(mod));
} else {
throw new Chat.ErrorMessage(`A mod by the name of '${mod.trim()}' does not exist.`);
}
if (dex === Dex.dexes["ssb"]) {
throw new Chat.ErrorMessage(`The SSB mod supports custom elements for Mega Stones that have the capability of crashing the server.`);
}
}
const stone = getMegaStone(stoneName[0], mod);
const species = dex.species.get(sep[0]);
if (!stone) {
throw new Chat.ErrorMessage(`Error: Mega Stone/Primal Orb/Rusted Item/Origin Item not found.`);
}
if (!species.exists)
throw new Chat.ErrorMessage(`Error: Pok\xE9mon not found.`);
let baseSpecies;
let megaSpecies;
switch (stone.id) {
case "blueorb":
megaSpecies = dex.species.get("Kyogre-Primal");
baseSpecies = dex.species.get("Kyogre");
break;
case "redorb":
megaSpecies = dex.species.get("Groudon-Primal");
baseSpecies = dex.species.get("Groudon");
break;
case "rustedshield":
megaSpecies = dex.species.get("Zamazenta-Crowned");
baseSpecies = dex.species.get("Zamazenta");
break;
case "rustedsword":
megaSpecies = dex.species.get("Zacian-Crowned");
baseSpecies = dex.species.get("Zacian");
break;
default:
const forcedForme = stone.forcedForme;
if (forcedForme && (forcedForme.endsWith("Origin") || forcedForme.endsWith("Epilogue"))) {
megaSpecies = dex.species.get(forcedForme);
baseSpecies = dex.species.get(forcedForme.split("-")[0]);
} else {
megaSpecies = dex.species.get(stone.megaStone);
baseSpecies = dex.species.get(stone.megaEvolves);
}
break;
}
const deltas = {
baseStats: /* @__PURE__ */ Object.create(null),
weighthg: megaSpecies.weighthg - baseSpecies.weighthg,
bst: megaSpecies.bst - baseSpecies.bst
};
let statId;
for (statId in megaSpecies.baseStats) {
deltas.baseStats[statId] = megaSpecies.baseStats[statId] - baseSpecies.baseStats[statId];
}
if (megaSpecies.types.length > baseSpecies.types.length) {
deltas.type = megaSpecies.types[1];
} else if (megaSpecies.types.length < baseSpecies.types.length) {
deltas.type = "mono";
} else if (megaSpecies.types[1] !== baseSpecies.types[1]) {
deltas.type = megaSpecies.types[1];
}
const mixedSpecies = import_lib.Utils.deepClone(species);
mixedSpecies.abilities = import_lib.Utils.deepClone(megaSpecies.abilities);
if (mixedSpecies.types[0] === deltas.type) {
mixedSpecies.types = [deltas.type];
} else if (deltas.type === "mono") {
mixedSpecies.types = [mixedSpecies.types[0]];
} else if (deltas.type) {
mixedSpecies.types = [mixedSpecies.types[0], deltas.type];
}
let statName;
mixedSpecies.bst = 0;
for (statName in species.baseStats) {
mixedSpecies.baseStats[statName] = import_lib.Utils.clampIntRange(
mixedSpecies.baseStats[statName] + deltas.baseStats[statName],
1,
255
);
mixedSpecies.bst += mixedSpecies.baseStats[statName];
}
mixedSpecies.weighthg = Math.max(1, species.weighthg + deltas.weighthg);
mixedSpecies.tier = "MnM";
let weighthit = 20;
if (mixedSpecies.weighthg >= 2e3) {
weighthit = 120;
} else if (mixedSpecies.weighthg >= 1e3) {
weighthit = 100;
} else if (mixedSpecies.weighthg >= 500) {
weighthit = 80;
} else if (mixedSpecies.weighthg >= 250) {
weighthit = 60;
} else if (mixedSpecies.weighthg >= 100) {
weighthit = 40;
}
const details = {
"Dex#": "" + mixedSpecies.num,
Gen: "" + mixedSpecies.gen,
Height: mixedSpecies.heightm + " m",
Weight: mixedSpecies.weighthg / 10 + " kg <em>(" + weighthit + " BP)</em>",
"Dex Colour": mixedSpecies.color
};
if (mixedSpecies.eggGroups)
details["Egg Group(s)"] = mixedSpecies.eggGroups.join(", ");
details['<font color="#686868">Does Not Evolve</font>'] = "";
this.sendReply(`|raw|${Chat.getDataPokemonHTML(mixedSpecies)}`);
this.sendReply(`|raw|<font size="1">` + Object.entries(details).map(([detail, value]) => value === "" ? detail : `<font color="#686868">${detail}:</font> ${value}`).join("&nbsp;|&ThickSpace;") + `</font>`);
},
mixandmegahelp: [
`/mnm <pokemon> @ <mega stone or other>[, generation] - Shows the Mix and Mega evolved Pok\xE9mon's type and stats.`
],
orb: "stone",
megastone: "stone",
stone(target) {
const sep = target.split(",");
let dex = Dex;
if (sep[1]) {
if (toID(sep[1]) in Dex.dexes) {
dex = Dex.mod(toID(sep[1]));
} else {
throw new Chat.ErrorMessage(`A mod by the name of '${sep[1].trim()}' does not exist.`);
}
if (dex === Dex.dexes["ssb"]) {
throw new Chat.ErrorMessage(`The SSB mod supports custom elements for Mega Stones that have the capability of crashing the server.`);
}
}
const targetid = toID(sep[0]);
if (!targetid)
return this.parse("/help stone");
this.runBroadcast();
const stone = getMegaStone(targetid, sep[1]);
const stones = [];
if (!stone) {
const species = dex.species.get(targetid.replace(/(?:mega[xy]?|primal|origin|crowned|epilogue)$/, ""));
if (!species.exists)
throw new Chat.ErrorMessage(`Error: Mega Stone not found.`);
if (!species.otherFormes)
throw new Chat.ErrorMessage(`Error: Mega Evolution not found.`);
for (const poke of species.otherFormes) {
if (!/(?:-Crowned|-Epilogue|-Origin|-Primal|-Mega(?:-[XY])?)$/.test(poke))
continue;
const megaPoke = dex.species.get(poke);
const flag = megaPoke.requiredMove === "Dragon Ascent" ? megaPoke.requiredMove : megaPoke.requiredItem;
if (/mega[xy]$/.test(targetid) && toID(megaPoke.name) !== toID(dex.species.get(targetid)))
continue;
if (!flag)
continue;
stones.push(getMegaStone(flag, sep[1]));
}
if (!stones.length)
throw new Chat.ErrorMessage(`Error: Mega Evolution not found.`);
}
const toDisplay = stones.length ? stones : [stone];
for (const aStone of toDisplay) {
if (!aStone)
return;
let baseSpecies;
let megaSpecies;
switch (aStone.id) {
case "blueorb":
megaSpecies = dex.species.get("Kyogre-Primal");
baseSpecies = dex.species.get("Kyogre");
break;
case "redorb":
megaSpecies = dex.species.get("Groudon-Primal");
baseSpecies = dex.species.get("Groudon");
break;
case "rustedshield":
megaSpecies = dex.species.get("Zamazenta-Crowned");
baseSpecies = dex.species.get("Zamazenta");
break;
case "rustedsword":
megaSpecies = dex.species.get("Zacian-Crowned");
baseSpecies = dex.species.get("Zacian");
break;
default:
const forcedForme = aStone.forcedForme;
if (forcedForme && (forcedForme.endsWith("Origin") || forcedForme.endsWith("Epilogue"))) {
megaSpecies = dex.species.get(forcedForme);
baseSpecies = dex.species.get(forcedForme.split("-")[0]);
} else {
megaSpecies = dex.species.get(aStone.megaStone);
baseSpecies = dex.species.get(aStone.megaEvolves);
}
break;
}
const deltas = {
baseStats: /* @__PURE__ */ Object.create(null),
weighthg: megaSpecies.weighthg - baseSpecies.weighthg,
bst: megaSpecies.bst - baseSpecies.bst
};
let statId;
for (statId in megaSpecies.baseStats) {
deltas.baseStats[statId] = megaSpecies.baseStats[statId] - baseSpecies.baseStats[statId];
}
if (megaSpecies.types.length > baseSpecies.types.length) {
deltas.type = megaSpecies.types[1];
} else if (megaSpecies.types.length < baseSpecies.types.length) {
deltas.type = dex.gen >= 8 ? "mono" : megaSpecies.types[0];
} else if (megaSpecies.types[1] !== baseSpecies.types[1]) {
deltas.type = megaSpecies.types[1];
}
const details = {
Gen: aStone.gen,
Weight: (deltas.weighthg < 0 ? "" : "+") + deltas.weighthg / 10 + " kg"
};
let tier;
if (["redorb", "blueorb"].includes(aStone.id) || aStone.forcedForme?.endsWith("Origin")) {
tier = "Orb";
} else if (aStone.name === "Dragon Ascent") {
tier = "Move";
} else if (aStone.megaStone) {
tier = "Stone";
} else {
tier = "Item";
}
let buf = `<li class="result">`;
buf += `<span class="col numcol">${tier}</span> `;
if (aStone.name === "Dragon Ascent") {
buf += `<span class="col itemiconcol"></span>`;
} else {
const itemName = aStone.forcedForme?.endsWith("Origin") ? aStone.name.split(" ")[0] + " Orb" : aStone.name;
buf += `<span class="col itemiconcol"><psicon item="${toID(itemName)}"/></span> `;
}
if (aStone.name === "Dragon Ascent") {
buf += `<span class="col movenamecol" style="white-space:nowrap"><a href="https://${Config.routes.dex}/moves/${targetid}" target="_blank">Dragon Ascent</a></span> `;
} else {
buf += `<span class="col pokemonnamecol" style="white-space:nowrap"><a href="https://${Config.routes.dex}/items/${aStone.id}" target="_blank">${aStone.name}</a></span> `;
}
if (deltas.type && deltas.type !== "mono") {
buf += `<span class="col typecol"><img src="https://${Config.routes.client}/sprites/types/${deltas.type}.png" alt="${deltas.type}" height="14" width="32"></span> `;
} else {
buf += `<span class="col typecol"></span>`;
}
buf += `<span style="float:left;min-height:26px">`;
buf += `<span class="col abilitycol">${megaSpecies.abilities["0"]}</span>`;
buf += `<span class="col abilitycol">${megaSpecies.abilities["H"] ? `<em>${megaSpecies.abilities["H"]}</em>` : ""}</span>`;
buf += `</span>`;
buf += `<span style="float:left;min-height:26px">`;
buf += `<span class="col statcol"><em>HP</em><br />0</span> `;
buf += `<span class="col statcol"><em>Atk</em><br />${deltas.baseStats.atk}</span> `;
buf += `<span class="col statcol"><em>Def</em><br />${deltas.baseStats.def}</span> `;
buf += `<span class="col statcol"><em>SpA</em><br />${deltas.baseStats.spa}</span> `;
buf += `<span class="col statcol"><em>SpD</em><br />${deltas.baseStats.spd}</span> `;
buf += `<span class="col statcol"><em>Spe</em><br />${deltas.baseStats.spe}</span> `;
buf += `<span class="col bstcol"><em>BST<br />${deltas.bst}</em></span> `;
buf += `</span>`;
buf += `</li>`;
this.sendReply(`|raw|<div class="message"><ul class="utilichart">${buf}<li style="clear:both"></li></ul></div>`);
this.sendReply(`|raw|<font size="1"><font color="#686868">Gen:</font> ${details["Gen"]}&nbsp;|&ThickSpace;<font color="#686868">Weight:</font> ${details["Weight"]}</font>`);
}
},
stonehelp: [`/stone <mega stone or other>[, generation] - Shows the changes that a mega stone/orb applies to a Pok\xE9mon.`],
350: "350cup",
"350cup"(target, room, user) {
const args = target.split(",");
if (!toID(args[0]))
return this.parse("/help 350cup");
this.runBroadcast();
let dex = Dex;
if (args[1] && toID(args[1]) in Dex.dexes) {
dex = Dex.dexes[toID(args[1])];
} else if (room?.battle) {
const format = Dex.formats.get(room.battle.format);
dex = Dex.mod(format.mod);
}
const species = import_lib.Utils.deepClone(dex.species.get(args[0]));
if (!species.exists || species.gen > dex.gen) {
const monName = species.gen > dex.gen ? species.name : args[0].trim();
const additionalReason = species.gen > dex.gen ? ` in Generation ${dex.gen}` : ``;
throw new Chat.ErrorMessage(`Error: Pok\xE9mon '${monName}' not found${additionalReason}.`);
}
const bst = species.bst;
species.bst = 0;
for (const i in species.baseStats) {
if (dex.gen === 1 && i === "spd")
continue;
species.baseStats[i] = species.baseStats[i] * (bst <= 350 ? 2 : 1);
species.bst += species.baseStats[i];
}
this.sendReply(`|html|${Chat.getDataPokemonHTML(species, dex.gen)}`);
},
"350cuphelp": [
`/350 OR /350cup <pokemon>[, gen] - Shows the base stats that a Pok\xE9mon would have in 350 Cup.`
],
ts: "tiershift",
ts1: "tiershift",
ts2: "tiershift",
ts3: "tiershift",
ts4: "tiershift",
ts5: "tiershift",
ts6: "tiershift",
ts7: "tiershift",
ts8: "tiershift",
tiershift(target, room, user, connection, cmd) {
const args = target.split(",");
if (!toID(args[0]))
return this.parse("/help tiershift");
this.runBroadcast();
const targetGen = parseInt(cmd[cmd.length - 1]);
if (targetGen && !args[1])
args[1] = `gen${targetGen}`;
let dex = Dex;
if (args[1] && toID(args[1]) in Dex.dexes) {
dex = Dex.dexes[toID(args[1])];
} else if (room?.battle) {
const format = Dex.formats.get(room.battle.format);
dex = Dex.mod(format.mod);
}
const species = import_lib.Utils.deepClone(dex.species.get(args[0]));
if (!species.exists || species.gen > dex.gen) {
const monName = species.gen > dex.gen ? species.name : args[0].trim();
const additionalReason = species.gen > dex.gen ? ` in Generation ${dex.gen}` : ``;
throw new Chat.ErrorMessage(`Error: Pok\xE9mon '${monName}' not found${additionalReason}.`);
}
const boosts = {
UU: 10,
RUBL: 10,
RU: 20,
NUBL: 20,
NU: 30,
PUBL: 30,
PU: 40,
NFE: 40,
LC: 40
};
let tier = species.tier;
if (tier[0] === "(")
tier = tier.slice(1, -1);
if (!(tier in boosts))
return this.sendReply(`|html|${Chat.getDataPokemonHTML(species, dex.gen)}`);
const boost = boosts[tier];
species.bst = species.baseStats.hp;
for (const statName in species.baseStats) {
if (statName === "hp")
continue;
if (dex.gen === 1 && statName === "spd")
continue;
species.baseStats[statName] = import_lib.Utils.clampIntRange(species.baseStats[statName] + boost, 1, 255);
species.bst += species.baseStats[statName];
}
this.sendReply(`|raw|${Chat.getDataPokemonHTML(species, dex.gen)}`);
},
tiershifthelp: [
`/ts OR /tiershift <pokemon>[, generation] - Shows the base stats that a Pok\xE9mon would have in Tier Shift.`,
`Alternatively, you can use /ts[gen number] to see a Pok\xE9mon's stats in that generation.`
],
scale: "scalemons",
scale1: "scalemons",
scale2: "scalemons",
scale3: "scalemons",
scale4: "scalemons",
scale5: "scalemons",
scale6: "scalemons",
scale7: "scalemons",
scale8: "scalemons",
scalemons(target, room, user, connection, cmd) {
const args = target.split(",");
if (!args.length || !toID(args[0]))
return this.parse(`/help scalemons`);
this.runBroadcast();
const targetGen = parseInt(cmd[cmd.length - 1]);
if (targetGen && !args[1])
args[1] = `gen${targetGen}`;
let dex = Dex;
if (args[1] && toID(args[1]) in Dex.dexes) {
dex = Dex.dexes[toID(args[1])];
} else if (room?.battle) {
const format = Dex.formats.get(room.battle.format);
dex = Dex.mod(format.mod);
}
const species = import_lib.Utils.deepClone(dex.species.get(args[0]));
if (!species.exists || species.gen > dex.gen) {
const monName = species.gen > dex.gen ? species.name : args[0].trim();
const additionalReason = species.gen > dex.gen ? ` in Generation ${dex.gen}` : ``;
throw new Chat.ErrorMessage(`Error: Pok\xE9mon '${monName}' not found${additionalReason}.`);
}
const bstNoHP = species.bst - species.baseStats.hp;
const scale = (dex.gen !== 1 ? 600 : 500) - species.baseStats["hp"];
species.bst = 0;
for (const stat in species.baseStats) {
if (stat === "hp")
continue;
if (dex.gen === 1 && stat === "spd")
continue;
species.baseStats[stat] = import_lib.Utils.clampIntRange(species.baseStats[stat] * scale / bstNoHP, 1, 255);
species.bst += species.baseStats[stat];
}
species.bst += species.baseStats.hp;
this.sendReply(`|raw|${Chat.getDataPokemonHTML(species, dex.gen)}`);
},
scalemonshelp: [
`/scale OR /scalemons <pokemon>[, gen] - Shows the base stats that a Pok\xE9mon would have in Scalemons.`,
`Alternatively, you can use /scale[gen number] to see a Pok\xE9mon's scaled stats in that generation.`
],
flip: "flipped",
flip1: "flipped",
flip2: "flipped",
flip3: "flipped",
flip4: "flipped",
flip5: "flipped",
flip6: "flipped",
flip7: "flipped",
flip8: "flipped",
flipped(target, room, user, connection, cmd) {
const args = target.split(",");
if (!args[0])
return this.parse(`/help flipped`);
this.runBroadcast();
const mon = args[0];
let mod = args[1];
const targetGen = parseInt(cmd[cmd.length - 1]);
if (targetGen && !mod)
mod = `gen${targetGen}`;
let dex = Dex;
if (mod && toID(mod) in Dex.dexes) {
dex = Dex.dexes[toID(mod)];
} else if (room?.battle) {
dex = Dex.forFormat(room.battle.format);
}
const species = import_lib.Utils.deepClone(dex.species.get(mon));
if (!species.exists || species.gen > dex.gen) {
const monName = species.gen > dex.gen ? species.name : mon.trim();
const additionalReason = species.gen > dex.gen ? ` in Generation ${dex.gen}` : ``;
throw new Chat.ErrorMessage(`Error: Pok\xE9mon '${monName}' not found${additionalReason}.`);
}
if (dex.gen === 1) {
const flippedStats = {
hp: species.baseStats.spe,
atk: species.baseStats.spa,
def: species.baseStats.def,
spa: species.baseStats.atk,
spd: species.baseStats.atk,
spe: species.baseStats.hp
};
for (const stat in species.baseStats) {
species.baseStats[stat] = flippedStats[stat];
}
this.sendReply(`|raw|${Chat.getDataPokemonHTML(species, dex.gen)}`);
return;
}
const stats = Object.values(species.baseStats).reverse();
for (const [i, statName] of Object.keys(species.baseStats).entries()) {
species.baseStats[statName] = stats[i];
}
this.sendReply(`|raw|${Chat.getDataPokemonHTML(species, dex.gen)}`);
},
flippedhelp: [
`/flip OR /flipped <pokemon>[, gen] - Shows the base stats that a Pok\xE9mon would have in Flipped.`,
`Alternatively, you can use /flip[gen number] to see a Pok\xE9mon's stats in that generation.`
],
ns: "natureswap",
ns3: "natureswap",
ns4: "natureswap",
ns5: "natureswap",
ns6: "natureswap",
ns7: "natureswap",
ns8: "natureswap",
natureswap(target, room, user, connection, cmd) {
const args = target.split(",");
const nature = args[0];
const pokemon = args[1];
const targetGen = parseInt(cmd[cmd.length - 1]);
if (targetGen && !args[2])
args[2] = `gen${targetGen}`;
let dex = Dex;
if (args[2] && toID(args[2]) in Dex.dexes) {
dex = Dex.dexes[toID(args[2])];
} else if (room?.battle) {
const format = Dex.formats.get(room.battle.format);
dex = Dex.mod(format.mod);
}
if (!toID(nature) || !toID(pokemon))
return this.parse(`/help natureswap`);
this.runBroadcast();
const natureObj = dex.natures.get(nature);
if (dex.gen < 3)
throw new Chat.ErrorMessage(`Error: Natures don't exist prior to Generation 3.`);
if (!natureObj.exists)
throw new Chat.ErrorMessage(`Error: Nature ${nature} not found.`);
const species = import_lib.Utils.deepClone(dex.species.get(pokemon));
if (!species.exists || species.gen > dex.gen) {
const monName = species.gen > dex.gen ? species.name : args[0].trim();
const additionalReason = species.gen > dex.gen ? ` in Generation ${dex.gen}` : ``;
throw new Chat.ErrorMessage(`Error: Pok\xE9mon '${monName}' not found${additionalReason}.`);
}
if (natureObj.minus && natureObj.plus) {
const swap = species.baseStats[natureObj.minus];
species.baseStats[natureObj.minus] = species.baseStats[natureObj.plus];
species.baseStats[natureObj.plus] = swap;
species.tier = "NS";
}
this.sendReply(`|raw|${Chat.getDataPokemonHTML(species, dex.gen)}`);
},
natureswaphelp: [
`/ns OR /natureswap <nature>, <pokemon>[, gen] - Shows the base stats that a Pok\xE9mon would have in Nature Swap.`,
`Alternatively, you can use /ns[gen number] to see a Pok\xE9mon's stats in that generation.`
],
ce: "crossevolve",
crossevo: "crossevolve",
crossevolve(target, user, room) {
if (!this.runBroadcast())
return;
if (!target?.includes(","))
return this.parse(`/help crossevo`);
const pokes = target.split(",");
const species = Dex.species.get(pokes[0]);
const crossSpecies = Dex.species.get(pokes[1]);
if (!species.exists)
throw new Chat.ErrorMessage(`Error: Pok\xE9mon '${pokes[0]}' not found.`);
if (!crossSpecies.exists)
throw new Chat.ErrorMessage(`Error: Pok\xE9mon '${pokes[1]}' not found.`);
if (!species.evos.length)
throw new Chat.ErrorMessage(`Error: ${species.name} does not evolve.`);
if (!crossSpecies.prevo)
throw new Chat.ErrorMessage(`Error: ${crossSpecies.name} does not have a prevolution.`);
let setStage = 1;
let crossStage = 1;
if (species.prevo) {
setStage++;
if (Dex.species.get(species.prevo).prevo) {
setStage++;
}
}
const prevo = Dex.species.get(crossSpecies.prevo);
if (crossSpecies.prevo) {
crossStage++;
if (prevo.prevo) {
crossStage++;
}
}
if (setStage + 1 !== crossStage) {
throw new Chat.ErrorMessage(`Error: Cross evolution must follow evolutionary stages. (${species.name} is Stage ${setStage} and can only cross evolve to Stage ${setStage + 1})`);
}
const mixedSpecies = import_lib.Utils.deepClone(species);
mixedSpecies.abilities = import_lib.Utils.deepClone(crossSpecies.abilities);
mixedSpecies.baseStats = import_lib.Utils.deepClone(mixedSpecies.baseStats);
mixedSpecies.bst = 0;
let statName;
for (statName in species.baseStats) {
const statChange = crossSpecies.baseStats[statName] - prevo.baseStats[statName];
mixedSpecies.baseStats[statName] = import_lib.Utils.clampIntRange(mixedSpecies.baseStats[statName] + statChange, 1, 255);
mixedSpecies.bst += mixedSpecies.baseStats[statName];
}
mixedSpecies.types = [species.types[0]];
if (species.types[1])
mixedSpecies.types.push(species.types[1]);
if (crossSpecies.types[0] !== prevo.types[0])
mixedSpecies.types[0] = crossSpecies.types[0];
if (crossSpecies.types[1] !== prevo.types[1]) {
mixedSpecies.types[1] = crossSpecies.types[1] || crossSpecies.types[0];
}
if (mixedSpecies.types[0] === mixedSpecies.types[1])
mixedSpecies.types = [mixedSpecies.types[0]];
mixedSpecies.weighthg += crossSpecies.weighthg - prevo.weighthg;
if (mixedSpecies.weighthg < 1) {
mixedSpecies.weighthg = 1;
}
mixedSpecies.tier = "CE";
let weighthit = 20;
if (mixedSpecies.weighthg >= 2e3) {
weighthit = 120;
} else if (mixedSpecies.weighthg >= 1e3) {
weighthit = 100;
} else if (mixedSpecies.weighthg >= 500) {
weighthit = 80;
} else if (mixedSpecies.weighthg >= 250) {
weighthit = 60;
} else if (mixedSpecies.weighthg >= 100) {
weighthit = 40;
}
const details = {
"Dex#": mixedSpecies.num,
Gen: mixedSpecies.gen,
Height: mixedSpecies.heightm + " m",
Weight: mixedSpecies.weighthg / 10 + " kg <em>(" + weighthit + " BP)</em>",
"Dex Colour": mixedSpecies.color
};
if (mixedSpecies.eggGroups)
details["Egg Group(s)"] = mixedSpecies.eggGroups.join(", ");
details['<font color="#686868">Does Not Evolve</font>'] = "";
this.sendReply(`|raw|${Chat.getDataPokemonHTML(mixedSpecies)}`);
this.sendReply(`|raw|<font size="1">` + Object.entries(details).map(([detail, value]) => value === "" ? detail : `<font color="#686868">${detail}:</font> ${value}`).join("&nbsp;|&ThickSpace;") + `</font>`);
},
crossevolvehelp: [
"/crossevo <base pokemon>, <evolved pokemon> - Shows the type and stats for the Cross Evolved Pok\xE9mon."
],
reevo: "showevo",
showevo(target, user, room, connection, cmd) {
if (!this.runBroadcast())
return;
const targetid = toID(target);
const isReEvo = cmd === "reevo";
if (!targetid)
return this.parse(`/help ${isReEvo ? "re" : "show"}evo`);
const evo = Dex.species.get(target);
if (!evo.exists) {
throw new Chat.ErrorMessage(`Error: Pok\xE9mon ${target} not found.`);
}
if (!evo.prevo) {
const evoBaseSpecies = Dex.species.get(evo.baseSpecies);
if (!evoBaseSpecies.prevo)
throw new Chat.ErrorMessage(`Error: ${evoBaseSpecies.name} is not an evolution.`);
const prevoSpecies = Dex.species.get(evoBaseSpecies.prevo);
const deltas = import_lib.Utils.deepClone(evo);
if (!isReEvo) {
deltas.tier = "CE";
deltas.weightkg = evo.weightkg - prevoSpecies.weightkg;
deltas.types = [];
if (evo.types[0] !== prevoSpecies.types[0])
deltas.types[0] = evo.types[0];
if (evo.types[1] !== prevoSpecies.types[1]) {
deltas.types[1] = evo.types[1] || evo.types[0];
}
if (deltas.types.length) {
deltas.types = deltas.types.filter((type) => type !== void 0);
if (deltas.types[0] === deltas.types[1])
deltas.types = [deltas.types[0]];
} else {
deltas.types = null;
}
}
deltas.bst = 0;
let i;
for (i in evo.baseStats) {
const statChange = evoBaseSpecies.baseStats[i] - prevoSpecies.baseStats[i];
const formeChange = evo.baseStats[i] - evoBaseSpecies.baseStats[i];
if (!isReEvo) {
if (!evo.prevo) {
deltas.baseStats[i] = formeChange;
} else {
deltas.baseStats[i] = statChange;
}
} else {
deltas.baseStats[i] = import_lib.Utils.clampIntRange(evoBaseSpecies.baseStats[i] + statChange, 1, 255);
deltas.baseStats[i] = import_lib.Utils.clampIntRange(deltas.baseStats[i] + formeChange, 1, 255);
}
deltas.bst += deltas.baseStats[i];
}
const details = {
Gen: evo.gen,
Weight: (deltas.weighthg < 0 ? "" : "+") + deltas.weighthg / 10 + " kg",
Stage: Dex.species.get(prevoSpecies.prevo).exists ? 3 : 2
};
this.sendReply(`|raw|${Chat.getDataPokemonHTML(deltas)}`);
if (!isReEvo) {
this.sendReply(`|raw|<font size="1"><font color="#686868">Gen:</font> ${details["Gen"]}&nbsp;|&ThickSpace;<font color="#686868">Weight:</font> ${details["Weight"]}&nbsp;|&ThickSpace;<font color="#686868">Stage:</font> ${details["Stage"]}</font>`);
}
} else {
const prevoSpecies = Dex.species.get(evo.prevo);
const deltas = import_lib.Utils.deepClone(evo);
if (!isReEvo) {
deltas.tier = "CE";
deltas.weightkg = evo.weightkg - prevoSpecies.weightkg;
deltas.types = [];
if (evo.types[0] !== prevoSpecies.types[0])
deltas.types[0] = evo.types[0];
if (evo.types[1] !== prevoSpecies.types[1]) {
deltas.types[1] = evo.types[1] || evo.types[0];
}
if (deltas.types.length) {
deltas.types = deltas.types.filter((type) => type !== void 0);
if (deltas.types[0] === deltas.types[1])
deltas.types = [deltas.types[0]];
} else {
deltas.types = null;
}
}
deltas.bst = 0;
let i;
for (i in evo.baseStats) {
const statChange = evo.baseStats[i] - prevoSpecies.baseStats[i];
if (!isReEvo) {
deltas.baseStats[i] = statChange;
} else {
deltas.baseStats[i] = import_lib.Utils.clampIntRange(deltas.baseStats[i] + statChange, 1, 255);
}
deltas.bst += deltas.baseStats[i];
}
const details = {
Gen: evo.gen,
Weight: (deltas.weighthg < 0 ? "" : "+") + deltas.weighthg / 10 + " kg",
Stage: Dex.species.get(prevoSpecies.prevo).exists ? 3 : 2
};
this.sendReply(`|raw|${Chat.getDataPokemonHTML(deltas)}`);
if (!isReEvo) {
this.sendReply(`|raw|<font size="1"><font color="#686868">Gen:</font> ${details["Gen"]}&nbsp;|&ThickSpace;<font color="#686868">Weight:</font> ${details["Weight"]}&nbsp;|&ThickSpace;<font color="#686868">Stage:</font> ${details["Stage"]}</font>`);
}
}
},
reevohelp: [
`/reevo <Pok\xE9mon> - Shows the stats that a Pok\xE9mon would have in Re-Evolution`
],
showevohelp: [
`/showevo <Pok\xE9mon> - Shows the changes that a Pok\xE9mon applies in Cross Evolution`
]
};
//# sourceMappingURL=othermetas.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/othermetas.ts"],
"sourcesContent": ["/**\r\n * Other Metagames chat plugin\r\n * Lets users see elements of Pokemon in various Other Metagames.\r\n * Originally by Spandan.\r\n * @author Kris\r\n*/\r\n\r\nimport {Utils} from '../../lib';\r\n\r\ninterface StoneDeltas {\r\n\tbaseStats: {[stat in StatID]: number};\r\n\tbst: number;\r\n\tweighthg: number;\r\n\ttype?: string;\r\n}\r\n\r\ntype TierShiftTiers = 'UU' | 'RUBL' | 'RU' | 'NUBL' | 'NU' | 'PUBL' | 'PU' | 'NFE' | 'LC';\r\n\r\nfunction getMegaStone(stone: string, mod = 'gen9'): Item | null {\r\n\tlet dex = Dex;\r\n\tif (mod && toID(mod) in Dex.dexes) dex = Dex.mod(toID(mod));\r\n\tconst item = dex.items.get(stone);\r\n\tif (!item.exists) {\r\n\t\tif (toID(stone) === 'dragonascent') {\r\n\t\t\tconst move = dex.moves.get(stone);\r\n\t\t\treturn {\r\n\t\t\t\tid: move.id,\r\n\t\t\t\tname: move.name,\r\n\t\t\t\tfullname: move.name,\r\n\t\t\t\tmegaEvolves: 'Rayquaza',\r\n\t\t\t\tmegaStone: 'Rayquaza-Mega',\r\n\t\t\t\texists: true,\r\n\t\t\t\t// Adding extra values to appease typescript\r\n\t\t\t\tgen: 6,\r\n\t\t\t\tnum: -1,\r\n\t\t\t\teffectType: 'Item',\r\n\t\t\t\tsourceEffect: '',\r\n\t\t\t} as Item;\r\n\t\t} else {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\tif (!item.megaStone && !item.onPrimal && !item.forcedForme?.endsWith('Epilogue') &&\r\n\t\t!item.forcedForme?.endsWith('Origin') && !item.name.startsWith('Rusted')) return null;\r\n\treturn item;\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tom: 'othermetas',\r\n\tothermetas(target, room, user) {\r\n\t\ttarget = toID(target);\r\n\t\tconst omLink = `- <a href=\"https://www.smogon.com/forums/forums/733/\">Other Metagames Forum</a><br />`;\r\n\r\n\t\tif (!target) {\r\n\t\t\tthis.runBroadcast();\r\n\t\t\treturn this.sendReplyBox(omLink);\r\n\t\t}\r\n\r\n\t\tif (target === 'all') {\r\n\t\t\tthis.runBroadcast();\r\n\t\t\tif (this.broadcasting) {\r\n\t\t\t\tthrow new Chat.ErrorMessage(`\"!om all\" is too spammy to broadcast.`);\r\n\t\t\t}\r\n\t\t\t// Display OMotM formats, with forum thread links as caption\r\n\t\t\tthis.parse(`/formathelp omofthemonth`);\r\n\r\n\t\t\t// Display the rest of OM formats, with OM hub/index forum links as caption\r\n\t\t\tthis.parse(`/formathelp othermetagames`);\r\n\t\t\treturn this.sendReply(`|raw|<center>${omLink}</center>`);\r\n\t\t}\r\n\r\n\t\tif (target === 'month') this.target = 'omofthemonth';\r\n\t\tthis.run('formathelp');\r\n\t},\r\n\tothermetashelp: [\r\n\t\t`/om - Provides links to information on the Other Metagames.`,\r\n\t\t`!om - Show everyone that information. Requires: + % @ # &`,\r\n\t],\r\n\r\n\tmnm: 'mixandmega',\r\n\tmixandmega(target, room, user) {\r\n\t\tif (!toID(target) || !target.includes('@')) return this.parse('/help mixandmega');\r\n\t\tthis.runBroadcast();\r\n\t\tlet dex = Dex;\r\n\t\tconst sep = target.split('@');\r\n\t\tconst stoneName = sep.slice(1).join('@').trim().split(',');\r\n\t\tconst mod = stoneName[1];\r\n\t\tif (mod) {\r\n\t\t\tif (toID(mod) in Dex.dexes) {\r\n\t\t\t\tdex = Dex.mod(toID(mod));\r\n\t\t\t} else {\r\n\t\t\t\tthrow new Chat.ErrorMessage(`A mod by the name of '${mod.trim()}' does not exist.`);\r\n\t\t\t}\r\n\t\t\tif (dex === Dex.dexes['ssb']) {\r\n\t\t\t\tthrow new Chat.ErrorMessage(`The SSB mod supports custom elements for Mega Stones that have the capability of crashing the server.`);\r\n\t\t\t}\r\n\t\t}\r\n\t\tconst stone = getMegaStone(stoneName[0], mod);\r\n\t\tconst species = dex.species.get(sep[0]);\r\n\t\tif (!stone) {\r\n\t\t\tthrow new Chat.ErrorMessage(`Error: Mega Stone/Primal Orb/Rusted Item/Origin Item not found.`);\r\n\t\t}\r\n\t\tif (!species.exists) throw new Chat.ErrorMessage(`Error: Pok\\u00e9mon not found.`);\r\n\t\tlet baseSpecies: Species;\r\n\t\tlet megaSpecies: Species;\r\n\t\tswitch (stone.id) {\r\n\t\tcase 'blueorb':\r\n\t\t\tmegaSpecies = dex.species.get(\"Kyogre-Primal\");\r\n\t\t\tbaseSpecies = dex.species.get(\"Kyogre\");\r\n\t\t\tbreak;\r\n\t\tcase 'redorb':\r\n\t\t\tmegaSpecies = dex.species.get(\"Groudon-Primal\");\r\n\t\t\tbaseSpecies = dex.species.get(\"Groudon\");\r\n\t\t\tbreak;\r\n\t\tcase 'rustedshield':\r\n\t\t\tmegaSpecies = dex.species.get(\"Zamazenta-Crowned\");\r\n\t\t\tbaseSpecies = dex.species.get(\"Zamazenta\");\r\n\t\t\tbreak;\r\n\t\tcase 'rustedsword':\r\n\t\t\tmegaSpecies = dex.species.get(\"Zacian-Crowned\");\r\n\t\t\tbaseSpecies = dex.species.get(\"Zacian\");\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tconst forcedForme = stone.forcedForme;\r\n\t\t\tif (forcedForme && (forcedForme.endsWith('Origin') || forcedForme.endsWith('Epilogue'))) {\r\n\t\t\t\tmegaSpecies = dex.species.get(forcedForme);\r\n\t\t\t\tbaseSpecies = dex.species.get(forcedForme.split('-')[0]);\r\n\t\t\t} else {\r\n\t\t\t\tmegaSpecies = dex.species.get(stone.megaStone);\r\n\t\t\t\tbaseSpecies = dex.species.get(stone.megaEvolves);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tconst deltas: StoneDeltas = {\r\n\t\t\tbaseStats: Object.create(null),\r\n\t\t\tweighthg: megaSpecies.weighthg - baseSpecies.weighthg,\r\n\t\t\tLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAoB;AAWpB,SAAS,aAAa,OAAe,MAAM,QAAqB;AAC/D,MAAI,MAAM;AACV,MAAI,OAAO,KAAK,GAAG,KAAK,IAAI;AAAO,UAAM,IAAI,IAAI,KAAK,GAAG,CAAC;AAC1D,QAAM,OAAO,IAAI,MAAM,IAAI,KAAK;AAChC,MAAI,CAAC,KAAK,QAAQ;AACjB,QAAI,KAAK,KAAK,MAAM,gBAAgB;AACnC,YAAM,OAAO,IAAI,MAAM,IAAI,KAAK;AAChC,aAAO;AAAA,QACN,IAAI,KAAK;AAAA,QACT,MAAM,KAAK;AAAA,QACX,UAAU,KAAK;AAAA,QACf,aAAa;AAAA,QACb,WAAW;AAAA,QACX,QAAQ;AAAA;AAAA,QAER,KAAK;AAAA,QACL,KAAK;AAAA,QACL,YAAY;AAAA,QACZ,cAAc;AAAA,MACf;AAAA,IACD,OAAO;AACN,aAAO;AAAA,IACR;AAAA,EACD;AACA,MAAI,CAAC,KAAK,aAAa,CAAC,KAAK,YAAY,CAAC,KAAK,aAAa,SAAS,UAAU,KAC9E,CAAC,KAAK,aAAa,SAAS,QAAQ,KAAK,CAAC,KAAK,KAAK,WAAW,QAAQ;AAAG,WAAO;AAClF,SAAO;AACR;AAEO,MAAM,WAA8B;AAAA,EAC1C,IAAI;AAAA,EACJ,WAAW,QAAQ,MAAM,MAAM;AAC9B,aAAS,KAAK,MAAM;AACpB,UAAM,SAAS;AAEf,QAAI,CAAC,QAAQ;AACZ,WAAK,aAAa;AAClB,aAAO,KAAK,aAAa,MAAM;A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 +1,639 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var poll_exports = {};
__export(poll_exports, {
Poll: () => Poll,
commands: () => commands,
pages: () => pages
});
module.exports = __toCommonJS(poll_exports);
var import_lib = require("../../lib");
const MINUTES = 6e4;
const MAX_QUESTIONS = 10;
class Poll extends Rooms.MinorActivity {
constructor(room, options) {
super(room);
this.activityid = "poll";
this.name = "Poll";
this.activityNumber = options.activityNumber || room.nextGameNumber();
this.question = options.question;
this.supportHTML = options.supportHTML;
this.multiPoll = options.multiPoll;
this.pendingVotes = options.pendingVotes || {};
this.voters = options.voters || {};
this.voterIps = options.voterIps || {};
this.totalVotes = options.totalVotes || 0;
this.maxVotes = options.maxVotes || 0;
if (!options.answers)
options.answers = options.questions;
this.answers = Poll.getAnswers(options.answers);
this.isQuiz = options.isQuiz ?? [...this.answers.values()].some((answer) => answer.correct);
this.setTimer(options);
}
select(user, option) {
const userid = user.id;
if (!this.multiPoll) {
this.pendingVotes[userid] = [option];
this.submit(user);
return;
}
if (!this.pendingVotes[userid]) {
this.pendingVotes[userid] = [];
}
if (this.pendingVotes[userid].includes(option)) {
throw new Chat.ErrorMessage(this.room.tr`That option is already selected.`);
}
this.pendingVotes[userid].push(option);
this.updateFor(user);
this.save();
}
deselect(user, option) {
const userid = user.id;
const pendingVote = this.pendingVotes[userid];
if (!pendingVote?.includes(option)) {
throw new Chat.ErrorMessage(this.room.tr`That option is not selected.`);
}
pendingVote.splice(pendingVote.indexOf(option), 1);
this.updateFor(user);
this.save();
}
submit(user) {
const ip = user.latestIp;
const userid = user.id;
if (userid in this.voters || !Config.noipchecks && ip in this.voterIps) {
delete this.pendingVotes[userid];
throw new Chat.ErrorMessage(this.room.tr`You have already voted for this poll.`);
}
const selected = this.pendingVotes[userid];
if (!selected)
throw new Chat.ErrorMessage(this.room.tr`No options selected.`);
this.voters[userid] = selected;
this.voterIps[ip] = selected;
for (const option of selected) {
this.answers.get(option).votes++;
}
delete this.pendingVotes[userid];
this.totalVotes++;
if (this.maxVotes && this.totalVotes >= this.maxVotes) {
this.end(this.room);
return this.room.add(`|c|&|/log The poll hit the max vote cap of ${this.maxVotes}, and has ended.`).update();
}
this.update();
this.save();
}
blankvote(user) {
const ip = user.latestIp;
const userid = user.id;
if (!(userid in this.voters) || !(ip in this.voterIps)) {
this.voters[userid] = [];
this.voterIps[ip] = [];
}
this.updateTo(user);
this.save();
}
generateVotes(user) {
const iconText = this.isQuiz ? `<i class="fa fa-question"></i> ${this.room.tr`Quiz`}` : `<i class="fa fa-bar-chart"></i> ${this.room.tr`Poll`}`;
let output = `<div class="infobox"><p style="margin: 2px 0 5px 0"><span style="border:1px solid #6A6;color:#484;border-radius:4px;padding:0 3px">${iconText}</span>`;
output += ` <strong style="font-size:11pt">${Poll.getQuestionMarkup(this.question, this.supportHTML)}</strong></p>`;
if (this.multiPoll) {
const empty = `<i class="fa fa-square-o" aria-hidden="true"></i>`;
const chosen = `<i class="fa fa-check-square-o" aria-hidden="true"></i>`;
const pendingVotes = user && this.pendingVotes[user.id] || [];
for (const [num, answer] of this.answers) {
const selected = pendingVotes.includes(num);
output += `<div style="margin-top: 5px"><button style="text-align: left; border: none; background: none; color: inherit;" value="/poll ${selected ? "de" : ""}select ${num}" name="send" title="${selected ? "Deselect" : "Select"} ${num}. ${import_lib.Utils.escapeHTML(answer.name)}">${selected ? "<strong>" : ""}${selected ? chosen : empty} ${num}. `;
output += `${Poll.getAnswerMarkup(answer, this.supportHTML)}${selected ? "</strong>" : ""}</button></div>`;
}
const submitButton = pendingVotes.length ? `<button class="button" value="/poll submit" name="send" title="${this.room.tr`Submit your vote`}"><strong>${this.room.tr`Submit`}</strong></button>` : `<button class="button" value="/poll results" name="send" title="${this.room.tr`View results`} - ${this.room.tr`you will not be able to vote after viewing results`}">(${this.room.tr`View results`})</button>`;
output += `<div style="margin-top: 7px; padding-left: 12px">${submitButton}</div>`;
output += `</div>`;
} else {
for (const [num, answer] of this.answers) {
output += `<div style="margin-top: 5px"><button class="button" style="text-align: left" value="/poll vote ${num}" name="send" title="${this.room.tr`Vote for ${num}`}. ${import_lib.Utils.escapeHTML(answer.name)}">${num}.`;
output += ` <strong>${Poll.getAnswerMarkup(answer, this.supportHTML)}</strong></button></div>`;
}
output += `<div style="margin-top: 7px; padding-left: 12px"><button value="/poll results" name="send" title="${this.room.tr`View results`} - ${this.room.tr`you will not be able to vote after viewing results`}"><small>(${this.room.tr`View results`})</small></button></div>`;
output += `</div>`;
}
return output;
}
static generateResults(options, room, ended = false, choice = null) {
const iconText = options.isQuiz ? `<i class="fa fa-question"></i> ${room.tr`Quiz`}` : `<i class="fa fa-bar-chart"></i> ${room.tr`Poll`}`;
const icon = `<span style="border:1px solid #${ended ? "777;color:#555" : "6A6;color:#484"};border-radius:4px;padding:0 3px">${iconText}${ended ? " " + room.tr`ended` : ""}</span> <small>${options.totalVotes || 0} ${room.tr`votes`}</small>`;
let output = `<div class="infobox"><p style="margin: 2px 0 5px 0">${icon} <strong style="font-size:11pt">${this.getQuestionMarkup(options.question, options.supportHTML)}</strong></p>`;
const answers = Poll.getAnswers(options.answers);
const colors = ["#88B", "#79A", "#8A8"];
for (const [num, answer] of answers) {
const chosen = choice?.includes(num);
const percentage = Math.round(answer.votes * 100 / (options.totalVotes || 1));
const answerMarkup = options.isQuiz ? `<span style="color:${answer.correct ? "green" : "red"};">${answer.correct ? "" : "<s>"}${this.getAnswerMarkup(answer, options.supportHTML)}${answer.correct ? "" : "</s>"}</span>` : this.getAnswerMarkup(answer, options.supportHTML);
output += `<div style="margin-top: 3px">${num}. <strong>${chosen ? "<em>" : ""}${answerMarkup}${chosen ? "</em>" : ""}</strong> <small>(${answer.votes} vote${answer.votes === 1 ? "" : "s"})</small><br /><span style="font-size:7pt;background:${colors[num % 3]};padding-right:${percentage * 3}px"></span><small>&nbsp;${percentage}%</small></div>`;
}
if (!choice && !ended) {
output += `<div><small>(${room.tr`You can't vote after viewing results`})</small></div>`;
}
output += "</div>";
return output;
}
static getQuestionMarkup(question, supportHTML = false) {
if (supportHTML)
return question;
return Chat.formatText(question);
}
static getAnswerMarkup(answer, supportHTML = false) {
if (supportHTML)
return answer.name;
return Chat.formatText(answer.name);
}
update() {
const state = this.toJSON();
const blankvote = Poll.generateResults(state, this.room, false);
for (const id in this.room.users) {
const user = this.room.users[id];
const selection = this.voters[user.id] || this.voterIps[user.latestIp];
if (selection) {
if (selection.length) {
user.sendTo(
this.room,
`|uhtmlchange|poll${this.activityNumber}|${Poll.generateResults(state, this.room, false, selection)}`
);
} else {
user.sendTo(this.room, `|uhtmlchange|poll${this.activityNumber}|${blankvote}`);
}
}
}
}
updateTo(user, connection = null) {
const state = this.toJSON();
const recipient = connection || user;
const selection = this.voters[user.id] || this.voterIps[user.latestIp];
if (selection) {
recipient.sendTo(
this.room,
`|uhtmlchange|poll${this.activityNumber}|${Poll.generateResults(state, this.room, false, selection)}`
);
} else {
recipient.sendTo(this.room, `|uhtmlchange|poll${this.activityNumber}|${this.generateVotes(user)}`);
}
}
updateFor(user) {
const state = this.toJSON();
if (user.id in this.voters) {
user.sendTo(
this.room,
`|uhtmlchange|poll${this.activityNumber}|${Poll.generateResults(state, this.room, false, this.voters[user.id])}`
);
} else {
user.sendTo(this.room, `|uhtmlchange|poll${this.activityNumber}|${this.generateVotes(user)}`);
}
}
display() {
const state = this.toJSON();
const blankvote = Poll.generateResults(state, this.room, false);
const blankquestions = this.generateVotes(null);
for (const id in this.room.users) {
const thisUser = this.room.users[id];
const selection = this.voters[thisUser.id] || this.voterIps[thisUser.latestIp];
if (selection) {
if (selection.length) {
thisUser.sendTo(
this.room,
`|uhtml|poll${this.activityNumber}|${Poll.generateResults(state, this.room, false, selection)}`
);
} else {
thisUser.sendTo(this.room, `|uhtml|poll${this.activityNumber}|${blankvote}`);
}
} else {
if (this.multiPoll && thisUser.id in this.pendingVotes) {
thisUser.sendTo(this.room, `|uhtml|poll${this.activityNumber}|${this.generateVotes(thisUser)}`);
} else {
thisUser.sendTo(this.room, `|uhtml|poll${this.activityNumber}|${blankquestions}`);
}
}
}
}
displayTo(user, connection = null) {
const state = this.toJSON();
const recipient = connection || user;
if (user.id in this.voters) {
recipient.sendTo(
this.room,
`|uhtml|poll${this.activityNumber}|${Poll.generateResults(state, this.room, false, this.voters[user.id])}`
);
} else if (user.latestIp in this.voterIps && !Config.noipchecks) {
recipient.sendTo(this.room, `|uhtml|poll${this.activityNumber}|${Poll.generateResults(
state,
this.room,
false,
this.voterIps[user.latestIp]
)}`);
} else {
recipient.sendTo(this.room, `|uhtml|poll${this.activityNumber}|${this.generateVotes(user)}`);
}
}
onConnect(user, connection = null) {
this.displayTo(user, connection);
}
onRename(user, oldid, joining) {
if (user.id in this.voters) {
this.updateFor(user);
}
}
destroy() {
const results = Poll.generateResults(this.toJSON(), this.room, true);
this.room.send(`|uhtmlchange|poll${this.activityNumber}|<div class="infobox">(${this.room.tr`The poll has ended &ndash; scroll down to see the results`})</div>`);
this.room.add(`|html|${results}`).update();
this.room.setMinorActivity(null);
}
toJSON() {
return {
activityid: "poll",
activityNumber: this.activityNumber,
question: this.question,
supportHTML: this.supportHTML,
multiPoll: this.multiPoll,
pendingVotes: this.pendingVotes,
voters: this.voters,
voterIps: this.voterIps,
totalVotes: this.totalVotes,
timeoutMins: this.timeoutMins,
timerEnd: this.timerEnd,
isQuiz: this.isQuiz,
answers: [...this.answers.values()]
};
}
save() {
this.room.settings.minorActivity = this.toJSON();
this.room.saveSettings();
}
static getAnswers(answers) {
const out = /* @__PURE__ */ new Map();
if (answers.length && typeof answers[0] === "string") {
for (const [i, answer] of answers.entries()) {
out.set(i + 1, {
name: answer.startsWith("+") ? answer.slice(1) : answer,
votes: 0,
correct: answer.startsWith("+")
});
}
} else {
for (const [i, answer] of answers.entries()) {
out.set(i + 1, answer);
}
}
return out;
}
}
const commands = {
poll: {
htmlcreate: "new",
create: "new",
createmulti: "new",
htmlcreatemulti: "new",
queue: "new",
queuehtml: "new",
htmlqueue: "new",
queuemulti: "new",
htmlqueuemulti: "new",
new(target, room, user, connection, cmd, message) {
room = this.requireRoom();
if (!target)
return this.parse("/help poll new");
target = target.trim();
if (target.length > 1024)
return this.errorReply(this.tr`Poll too long.`);
if (room.battle)
return this.errorReply(this.tr`Battles do not support polls.`);
const text = this.filter(target);
if (target !== text)
return this.errorReply(this.tr`You are not allowed to use filtered words in polls.`);
const supportHTML = cmd.includes("html");
const multiPoll = cmd.includes("multi");
const queue = cmd.includes("queue");
let params = [];
let separator = "";
if (text.includes("\n")) {
separator = "\n";
} else if (text.includes("|")) {
separator = "|";
} else if (text.includes(",")) {
separator = ",";
} else {
return this.errorReply(this.tr`Not enough arguments for /poll new.`);
}
let currentParam = "";
for (let i = 0; i < text.length; ++i) {
const currentCharacter = text[i];
const nextCharacter = text[i + 1];
const isEscapeCharacter = currentCharacter === "\\";
if (isEscapeCharacter) {
if (nextCharacter) {
currentParam += nextCharacter;
i += 1;
} else {
return this.errorReply(this.tr`Extra escape character. To end a poll with '\\', enter it as '\\\\'`);
}
continue;
}
const isSeparator = currentCharacter === separator;
if (isSeparator) {
params.push(currentParam);
currentParam = "";
continue;
}
currentParam += currentCharacter;
}
params.push(currentParam);
params = params.map((param) => param.trim());
this.checkCan("minigame", null, room);
if (supportHTML)
this.checkCan("declare", null, room);
this.checkChat();
if (room.minorActivity && !queue) {
return this.errorReply(this.tr`There is already a poll or announcement in progress in this room.`);
}
if (params.length < 3)
return this.errorReply(this.tr`Not enough arguments for /poll new.`);
if (supportHTML)
params = params.map((parameter) => this.checkHTML(parameter));
const questions = params.splice(1);
if (questions.length > MAX_QUESTIONS) {
return this.errorReply(this.tr`Too many options for poll (maximum is ${MAX_QUESTIONS}).`);
}
if (new Set(questions).size !== questions.length) {
return this.errorReply(this.tr`There are duplicate options in the poll.`);
}
if (room.minorActivity) {
room.queueMinorActivity({
question: params[0],
answers: questions,
multiPoll,
supportHTML,
activityid: "poll"
});
this.modlog("QUEUEPOLL");
return this.privateModAction(room.tr`${user.name} queued a poll.`);
}
room.setMinorActivity(new Poll(room, {
question: params[0],
supportHTML,
answers: questions,
multiPoll
}));
this.roomlog(`${user.name} used ${message}`);
this.modlog("POLL");
this.addModAction(room.tr`A poll was started by ${user.name}.`);
},
newhelp: [
`/poll create [question], [option1], [option2], [...] - Creates a poll. Requires: % @ # &`,
`/poll createmulti [question], [option1], [option2], [...] - Creates a poll, allowing for multiple answers to be selected. Requires: % @ # &`,
`To queue a poll, use [queue], [queuemulti], [queuehtml], or [htmlqueuemulti].`,
`Polls can be used as quiz questions. To do this, prepend all correct answers with a +.`
],
viewqueue(target, room, user) {
room = this.requireRoom();
this.checkCan("mute", null, room);
this.parse(`/join view-pollqueue-${room.roomid}`);
},
viewqueuehelp: [`/viewqueue - view the queue of polls in the room. Requires: % @ # &`],
deletequeue(target, room, user) {
room = this.requireRoom();
if (!target)
return this.parse("/help deletequeue");
this.checkCan("mute", null, room);
const queue = room.getMinorActivityQueue();
if (!queue) {
return this.errorReply(this.tr`The queue is already empty.`);
}
const slot = parseInt(target);
if (isNaN(slot)) {
return this.errorReply(this.tr`Can't delete poll at slot ${target} - "${target}" is not a number.`);
}
if (!queue[slot - 1])
return this.errorReply(this.tr`There is no poll in queue at slot ${slot}.`);
room.clearMinorActivityQueue(slot - 1);
room.modlog({
action: "DELETEQUEUE",
loggedBy: user.id,
note: slot.toString()
});
room.sendMods(this.tr`(${user.name} deleted the queued poll in slot ${slot}.)`);
room.update();
this.refreshPage(`pollqueue-${room.roomid}`);
},
deletequeuehelp: [
`/poll deletequeue [number] - deletes poll at the corresponding queue slot (1 = next, 2 = the one after that, etc). Requires: % @ # &`
],
clearqueue(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan("mute", null, room);
const queue = room.getMinorActivityQueue();
if (!queue) {
return this.errorReply(this.tr`The queue is already empty.`);
}
room.clearMinorActivityQueue();
this.modlog("CLEARQUEUE");
this.sendReply(this.tr`Cleared poll queue.`);
},
clearqueuehelp: [
`/poll clearqueue - deletes the queue of polls. Requires: % @ # &`
],
deselect: "select",
vote: "select",
select(target, room, user, connection, cmd) {
room = this.requireRoom();
const poll = this.requireMinorActivity(Poll);
if (!target)
return this.parse("/help poll vote");
const parsed = parseInt(target);
if (isNaN(parsed))
return this.errorReply(this.tr`To vote, specify the number of the option.`);
if (!poll.answers.has(parsed))
return this.sendReply(this.tr`Option not in poll.`);
if (cmd === "deselect") {
poll.deselect(user, parsed);
} else {
poll.select(user, parsed);
}
},
selecthelp: [
`/poll select [number] - Select option [number].`,
`/poll deselect [number] - Deselects option [number].`
],
submit(target, room, user) {
room = this.requireRoom();
const poll = this.requireMinorActivity(Poll);
poll.submit(user);
},
submithelp: [`/poll submit - Submits your vote.`],
timer(target, room, user) {
room = this.requireRoom();
const poll = this.requireMinorActivity(Poll);
if (target) {
this.checkCan("minigame", null, room);
if (target === "clear") {
if (!poll.endTimer())
return this.errorReply(this.tr("There is no timer to clear."));
return this.add(this.tr`The poll timer was turned off.`);
}
const timeoutMins = parseFloat(target);
if (isNaN(timeoutMins) || timeoutMins <= 0 || timeoutMins > 7 * 24 * 60) {
return this.errorReply(this.tr`Time should be a number of minutes less than one week.`);
}
poll.setTimer({ timeoutMins });
room.add(this.tr`The poll timer was turned on: the poll will end in ${Chat.toDurationString(timeoutMins * MINUTES)}.`);
this.modlog("POLL TIMER", null, `${timeoutMins} minutes`);
return this.privateModAction(room.tr`The poll timer was set to ${timeoutMins} minute(s) by ${user.name}.`);
} else {
if (!this.runBroadcast())
return;
if (poll.timeout) {
return this.sendReply(this.tr`The poll timer is on and will end in ${Chat.toDurationString(poll.timeoutMins * MINUTES)}.`);
} else {
return this.sendReply(this.tr`The poll timer is off.`);
}
}
},
timerhelp: [
`/poll timer [minutes] - Sets the poll to automatically end after [minutes] minutes. Requires: % @ # &`,
`/poll timer clear - Clears the poll's timer. Requires: % @ # &`
],
results(target, room, user) {
room = this.requireRoom();
const poll = this.requireMinorActivity(Poll);
poll.blankvote(user);
},
resultshelp: [
`/poll results - Shows the results of the poll without voting. NOTE: you can't go back and vote after using this.`
],
close: "end",
stop: "end",
end(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
this.checkChat();
const poll = this.requireMinorActivity(Poll);
this.modlog("POLL END");
this.privateModAction(room.tr`The poll was ended by ${user.name}.`);
poll.end(room, Poll);
},
endhelp: [`/poll end - Ends a poll and displays the results. Requires: % @ # &`],
show: "",
display: "",
""(target, room, user, connection) {
room = this.requireRoom();
const poll = this.requireMinorActivity(Poll);
if (!this.runBroadcast())
return;
room.update();
if (this.broadcasting) {
poll.display();
} else {
poll.displayTo(user, connection);
}
},
displayhelp: [`/poll display - Displays the poll`],
mv: "maxvotes",
maxvotes(target, room, user) {
room = this.requireRoom();
this.checkCan("mute", null, room);
const poll = this.requireMinorActivity(Poll);
let num = parseInt(target);
if (this.meansNo(target)) {
num = 0;
}
if (isNaN(num)) {
return this.errorReply(`Invalid max vote cap: '${target}'`);
}
if (poll.maxVotes === num) {
return this.errorReply(`The poll's vote cap is already set to ${num}.`);
}
poll.maxVotes = num;
this.addModAction(`${user.name} set the poll's vote cap to ${num}.`);
let ended = false;
if (poll.totalVotes > poll.maxVotes) {
poll.end(room);
this.addModAction(`The poll has more votes than the maximum vote cap, and has ended.`);
ended = true;
}
if (!ended)
poll.save();
this.modlog("POLL MAXVOTES", null, `${poll.maxVotes}${ended ? ` (ended poll)` : ""}`);
}
},
pollhelp() {
this.sendReply(
`|html|<details class="readmore"><summary>/poll allows rooms to run their own polls (limit 1 at a time).<br />Polls can be used as quiz questions, by putting <code>+</code> before correct answers.<br /><code>/poll create [question], [option1], [option2], [...]</code> - Creates a poll. Requires: % @ # &</summary><code>/poll createmulti [question], [option1], [option2], [...]</code> - Creates a poll, allowing for multiple answers to be selected. Requires: % @ # &<br /><code>/poll htmlcreate(multi) [question], [option1], [option2], [...]</code> - Creates a poll, with HTML allowed in the question and options. Requires: # &<br /><code>/poll vote [number]</code> - Votes for option [number].<br /><code>/poll timer [minutes]</code> - Sets the poll to automatically end after [minutes]. Requires: % @ # &.<br /><code>/poll results</code> - Shows the results of the poll without voting. NOTE: you can't go back and vote after using this.<br /><code>/poll display</code> - Displays the poll.<br /><code>/poll end</code> - Ends a poll and displays the results. Requires: % @ # &.<br /><code>/poll queue [question], [option1], [option2], [...]</code> - Add a poll in queue. Requires: % @ # &<br /><code>/poll deletequeue [number]</code> - Deletes poll at the corresponding queue slot (1 = next, 2 = the one after that, etc).<br /><code>/poll clearqueue</code> - Deletes the queue of polls. Requires: % @ # &.<br /><code>/poll viewqueue</code> - View the queue of polls in the room. Requires: % @ # &<br /><code>/poll maxvotes [number]</code> - Set the max poll votes to the given [number]. Requires: % @ # &<br /></details>`
);
}
};
const pages = {
pollqueue(args, user) {
const room = this.requireRoom();
let buf = `<div class="pad"><strong>${this.tr`Queued polls:`}</strong>`;
buf += `<button class="button" name="send" value="/join view-pollqueue-${room.roomid}" style="float: right">`;
buf += `<i class="fa fa-refresh"></i> ${this.tr`Refresh`}</button><br />`;
const queue = room.getMinorActivityQueue()?.filter((activity) => activity.activityid === "poll");
if (!queue) {
buf += `<hr /><strong>${this.tr`No polls queued.`}</strong></div>`;
return buf;
}
for (const [i, poll] of queue.entries()) {
const number = i + 1;
const button = `<strong>${this.tr`#${number} in queue`} </strong><button class="button" name="send" value="/msgroom ${room.roomid},/poll deletequeue ${i + 1}">(${this.tr`delete`})</button>`;
buf += `<hr />`;
buf += `${button}<br />${Poll.generateResults(poll, room, false)}`;
}
buf += `<hr />`;
return buf;
}
};
process.nextTick(() => {
Chat.multiLinePattern.register("/poll (new|create|createmulti|htmlcreate|htmlcreatemulti|queue|queuemulti|htmlqueuemulti) ");
});
for (const room of Rooms.rooms.values()) {
if (room.getMinorActivityQueue(true)) {
for (const poll of room.getMinorActivityQueue(true)) {
if (!poll.activityid) {
poll.activityid = poll.activityId;
delete poll.activityId;
}
if (!poll.activityNumber) {
poll.activityNumber = poll.pollNumber;
delete poll.pollNumber;
}
room.saveSettings();
}
}
if (room.settings.minorActivity) {
if (!room.settings.minorActivity.activityid) {
room.settings.minorActivity.activityid = room.settings.minorActivity.activityId;
delete room.settings.minorActivity.activityId;
}
if (typeof room.settings.minorActivity.activityNumber !== "number") {
room.settings.minorActivity.activityNumber = room.settings.minorActivity.pollNumber || // @ts-ignore
room.settings.minorActivity.announcementNumber;
}
room.saveSettings();
}
if (room.settings.minorActivity?.activityid === "poll") {
room.setMinorActivity(new Poll(room, room.settings.minorActivity), true);
}
}
//# sourceMappingURL=poll.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/poll.ts"],
"sourcesContent": ["/*\r\n * Poll chat plugin\r\n * By bumbadadabum and Zarel.\r\n */\r\nimport {Utils} from '../../lib';\r\n\r\nconst MINUTES = 60000;\r\nconst MAX_QUESTIONS = 10;\r\n\r\ninterface PollAnswer {\r\n\tname: string; votes: number; correct?: boolean;\r\n}\r\n\r\nexport interface PollOptions {\r\n\tactivityNumber?: number;\r\n\tquestion: string;\r\n\tsupportHTML: boolean;\r\n\tmultiPoll: boolean;\r\n\tpendingVotes?: {[userid: string]: number[]};\r\n\tvoters?: {[k: string]: number[]};\r\n\tvoterIps?: {[k: string]: number[]};\r\n\tmaxVotes?: number;\r\n\ttotalVotes?: number;\r\n\ttimeoutMins?: number;\r\n\ttimerEnd?: number;\r\n\tisQuiz?: boolean;\r\n\tanswers: string[] | PollAnswer[];\r\n}\r\n\r\nexport interface PollData extends PollOptions {\r\n\treadonly activityid: 'poll';\r\n}\r\n\r\nexport class Poll extends Rooms.MinorActivity {\r\n\treadonly activityid = 'poll' as ID;\r\n\tname = \"Poll\";\r\n\tactivityNumber: number;\r\n\tquestion: string;\r\n\tmultiPoll: boolean;\r\n\tpendingVotes: {[userid: string]: number[]};\r\n\tvoters: {[k: string]: number[]};\r\n\tvoterIps: {[k: string]: number[]};\r\n\ttotalVotes: number;\r\n\tisQuiz: boolean;\r\n\t/** Max votes of 0 means no vote cap */\r\n\tmaxVotes: number;\r\n\tanswers: Map<number, PollAnswer>;\r\n\tconstructor(room: Room, options: PollOptions) {\r\n\t\tsuper(room);\r\n\t\tthis.activityNumber = options.activityNumber || room.nextGameNumber();\r\n\t\tthis.question = options.question;\r\n\t\tthis.supportHTML = options.supportHTML;\r\n\t\tthis.multiPoll = options.multiPoll;\r\n\t\tthis.pendingVotes = options.pendingVotes || {};\r\n\t\tthis.voters = options.voters || {};\r\n\t\tthis.voterIps = options.voterIps || {};\r\n\t\tthis.totalVotes = options.totalVotes || 0;\r\n\t\tthis.maxVotes = options.maxVotes || 0;\r\n\r\n\t\t// backwards compatibility\r\n\t\tif (!options.answers) options.answers = (options as any).questions;\r\n\r\n\t\tthis.answers = Poll.getAnswers(options.answers);\r\n\t\tthis.isQuiz = options.isQuiz ?? [...this.answers.values()].some(answer => answer.correct);\r\n\t\tthis.setTimer(options);\r\n\t}\r\n\r\n\tselect(user: User, option: number) {\r\n\t\tconst userid = user.id;\r\n\t\tif (!this.multiPoll) {\r\n\t\t\t// vote immediately\r\n\t\t\tthis.pendingVotes[userid] = [option];\r\n\t\t\tthis.submit(user);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (!this.pendingVotes[userid]) {\r\n\t\t\tthis.pendingVotes[userid] = [];\r\n\t\t}\r\n\t\tif (this.pendingVotes[userid].includes(option)) {\r\n\t\t\tthrow new Chat.ErrorMessage(this.room.tr`That option is already selected.`);\r\n\t\t}\r\n\t\tthis.pendingVotes[userid].push(option);\r\n\t\tthis.updateFor(user);\r\n\t\tthis.save();\r\n\t}\r\n\r\n\tdeselect(user: User, option: number) {\r\n\t\tconst userid = user.id;\r\n\t\tconst pendingVote = this.pendingVotes[userid];\r\n\t\tif (!pendingVote?.includes(option)) {\r\n\t\t\tthrow new Chat.ErrorMessage(this.room.tr`That option is not selected.`);\r\n\t\t}\r\n\t\tpendingVote.splice(pendingVote.indexOf(option), 1);\r\n\t\tthis.updateFor(user);\r\n\t\tthis.save();\r\n\t}\r\n\r\n\tsubmit(user: User) {\r\n\t\tconst ip = user.latestIp;\r\n\t\tconst userid = user.id;\r\n\r\n\t\tif (userid in this.voters || (!Config.noipchecks && ip in this.voterIps)) {\r\n\t\t\tdelete this.pendingVotes[userid];\r\n\t\t\tthrow new Chat.ErrorMessage(this.room.tr`You have already voted for this poll.`);\r\n\t\t}\r\n\t\tconst selected = this.pendingVotes[userid];\r\n\t\tif (!selected) throw new Chat.ErrorMessage(this.room.tr`No options selected.`);\r\n\r\n\t\tthis.voters[userid] = selected;\r\n\t\tthis.voterIps[ip] = selected;\r\n\t\tfor (const option of selected) {\r\n\t\t\tthis.answers.get(option)!.votes++;\r\n\t\t}\r\n\t\tdelete this.pendingVotes[userid];\r\n\t\tthis.totalVotes++;\r\n\t\tif (this.maxVotes && this.totalVotes >= this.maxVotes) {\r\n\t\t\tthis.end(this.room);\r\n\t\t\treturn this.room\r\n\t\t\t\t.add(`|c|&|/log The poll hit the max vote cap of ${this.maxVotes}, and has ended.`)\r\n\t\t\t\t.update();\r\n\t\t}\r\n\r\n\t\tthis.update();\r\n\t\tthis.save();\r\n\t}\r\n\r\n\tblankvote(user: User) {\r\n\t\tconst ip = user.latestIp;\r\n\t\tconst userid = user.id;\r\n\r\n\t\tif (!(userid in this.voters) || !(ip in this.voterIps)) {\r\n\t\t\tthis.voters[userid] = [];\r\n\t\t\tthis.voterIps[ip] = [];\r\n\t\t}\r\n\r\n\t\tthis.updateTo(user);\r\n\t\tthis.save();\r\n\t}\r\n\r\n\tgenerateVotes(user: User | null) {\r\n\t\tconst iconText = this.isQuiz ?\r\n\t\t\t`<i class=\"fa fa-question\"></i> ${this.room.tr`Quiz`}` :\r\n\t\t\t`<i class=\"fa fa-bar-chart\"></i> ${this.room.tr`Poll`}`;\r\n\t\tlet output = `<div class=\"infobox\"><p style=\"margin: 2px 0 5px 0\"><span style=\"border:1px solid #6A6;color:#484;border-radius:4px;padding:0 3px\">${iconText}</span>`;\r\n\t\toutput += ` <strong style=\"font-size:11pt\">${Poll.getQuestionMarkup(this.question, this.supportHTML)}</strong></p>`;\r\n\r\n\t\tif (this.multiPoll) {\r\n\t\t\tconst empty = `<i class=\"fa fa-square-o\" ariLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,iBAAoB;AAEpB,MAAM,UAAU;AAChB,MAAM,gBAAgB;AA0Bf,MAAM,aAAa,MAAM,cAAc;AAAA,EAc7C,YAAY,MAAY,SAAsB;AAC7C,UAAM,IAAI;AAdX,SAAS,aAAa;AACtB,gBAAO;AAcN,SAAK,iBAAiB,QAAQ,kBAAkB,KAAK,eAAe;AACpE,SAAK,WAAW,QAAQ;AACxB,SAAK,cAAc,QAAQ;AAC3B,SAAK,YAAY,QAAQ;AACzB,SAAK,eAAe,QAAQ,gBAAgB,CAAC;AAC7C,SAAK,SAAS,QAAQ,UAAU,CAAC;AACjC,SAAK,WAAW,QAAQ,YAAY,CAAC;AACrC,SAAK,aAAa,QAAQ,cAAc;AACxC,SAAK,WAAW,QAAQ,YAAY;AAGpC,QAAI,CAAC,QAAQ;AAAS,cAAQ,UAAW,QAAgB;AAEzD,SAAK,UAAU,KAAK,WAAW,QAAQ,OAAO;AAC9C,SAAK,SAAS,QAAQ,UAAU,CAAC,GAAG,KAAK,QAAQ,OAAO,CAAC,EAAE,KAAK,YAAU,OAAO,OAAO;AACxF,SAAK,S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ACd,gBAAU;AAAA,QACT,KAAK;AAAA,QACL,oBAAoB,KAAK,kBAAkB,KAAK,gBAAgB,OAAO,KAAK,MAAM,OAAO,SAAS;AAAA,MACnG;AAAA,IACD,OAAO;AACN,gBAAU,OAAO,KAAK,MAAM,oBAAoB,KAAK,kBAAkB,KAAK,cAAc,IAAI,GAAG;AAAA,IAClG;AAAA,EACD;AAAA,EAEA,Line truncated
"names": []
}
+184
View File
@@ -0,0 +1,184 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var quotes_exports = {};
__export(quotes_exports, {
commands: () => commands,
handlers: () => handlers,
pages: () => pages
});
module.exports = __toCommonJS(quotes_exports);
var import_lib = require("../../lib");
const STORAGE_PATH = "config/chat-plugins/quotes.json";
const MAX_QUOTES = 300;
const quotes = JSON.parse((0, import_lib.FS)(STORAGE_PATH).readIfExistsSync() || "{}");
function convertOldQuotes() {
for (const room of Rooms.rooms.values()) {
if (room.settings.quotes) {
quotes[room.roomid] = room.settings.quotes;
delete room.settings.quotes;
room.saveSettings();
saveQuotes();
}
}
}
function saveQuotes() {
(0, import_lib.FS)(STORAGE_PATH).writeUpdate(() => JSON.stringify(quotes));
}
convertOldQuotes();
const commands = {
randquote(target, room, user) {
room = this.requireRoom();
const roomQuotes = quotes[room.roomid];
if (!roomQuotes?.length)
return this.errorReply(`This room has no quotes.`);
this.runBroadcast(true);
const { quote, date, userid } = roomQuotes[Math.floor(Math.random() * roomQuotes.length)];
const time = Chat.toTimestamp(new Date(date), { human: true });
const attribution = toID(target) === "showauthor" ? `<hr /><small>Added by ${userid} on ${time}</small>` : "";
return this.sendReplyBox(`${Chat.getReadmoreBlock(quote)}${attribution}`);
},
randquotehelp: [`/randquote [showauthor] - Show a random quote from the room. Add 'showauthor' to see who added it and when.`],
addquote: "quote",
quote(target, room, user) {
room = this.requireRoom();
if (!room.persist) {
return this.errorReply("This command is unavailable in temporary rooms.");
}
target = target.trim();
this.checkCan("mute", null, room);
if (!target) {
return this.parse(`/help quote`);
}
if (!quotes[room.roomid])
quotes[room.roomid] = [];
const roomQuotes = quotes[room.roomid];
if (this.filter(target) !== target) {
return this.errorReply(`Invalid quote.`);
}
if (roomQuotes.filter((item) => item.quote === target).length) {
return this.errorReply(`"${target}" is already quoted in this room.`);
}
if (target.length > 8192) {
return this.errorReply(`Your quote cannot exceed 8192 characters.`);
}
if (room.settings.isPrivate && roomQuotes.length >= MAX_QUOTES) {
return this.errorReply(`This room already has ${MAX_QUOTES} quotes, which is the maximum for private rooms.`);
}
roomQuotes.push({ userid: user.id, quote: target, date: Date.now() });
saveQuotes();
this.refreshPage(`quotes-${room.roomid}`);
const collapsedQuote = target.replace(/\n/g, " ");
this.privateModAction(`${user.name} added a new quote: "${collapsedQuote}".`);
return this.modlog(`ADDQUOTE`, null, collapsedQuote);
},
quotehelp: [`/quote [quote] - Adds [quote] to the room's quotes. Requires: % @ # &`],
removequote(target, room, user) {
room = this.requireRoom();
this.checkCan("mute", null, room);
if (!quotes[room.roomid]?.length)
return this.errorReply(`This room has no quotes.`);
const index = parseInt(target.trim());
if (isNaN(index)) {
return this.errorReply(`Invalid index.`);
}
const roomQuotes = quotes[room.roomid];
if (!roomQuotes[index - 1]) {
return this.errorReply(`Quote not found.`);
}
const [removed] = roomQuotes.splice(index - 1, 1);
const collapsedQuote = removed.quote.replace(/\n/g, " ");
this.privateModAction(`${user.name} removed quote indexed at ${index}: "${collapsedQuote}" (originally added by ${removed.userid}).`);
this.modlog(`REMOVEQUOTE`, null, collapsedQuote);
saveQuotes();
this.refreshPage(`quotes-${room.roomid}`);
},
removequotehelp: [`/removequote [index] - Removes the quote from the room's quotes. Requires: % @ # &`],
viewquote(target, room, user) {
room = this.requireRoom();
const roomQuotes = quotes[room.roomid];
if (!roomQuotes?.length)
return this.errorReply(`This room has no quotes.`);
const [num, showAuthor] = import_lib.Utils.splitFirst(target, ",");
const index = parseInt(num) - 1;
if (isNaN(index)) {
return this.errorReply(`Invalid index.`);
}
if (!roomQuotes[index]) {
return this.errorReply(`Quote not found.`);
}
this.runBroadcast(true);
const { quote, date, userid } = roomQuotes[index];
const time = Chat.toTimestamp(new Date(date), { human: true });
const attribution = toID(showAuthor) === "showauthor" ? `<hr /><small>Added by ${userid} on ${time}</small>` : "";
return this.sendReplyBox(`${Chat.formatText(quote, false, true)}${attribution}`);
},
viewquotehelp: [
`/viewquote [index][, params] - View the quote from the room's quotes.`,
`If 'showauthor' is used for the [params] argument, it shows who added the quote and when.`,
`Requires: % @ # &`
],
viewquotes: "quotes",
quotes(target, room) {
const targetRoom = target ? Rooms.search(target) : room;
if (!targetRoom)
return this.errorReply(`Invalid room.`);
this.parse(`/join view-quotes-${targetRoom.roomid}`);
},
quoteshelp: [`/quotes [room] - Shows all quotes for [room]. Defaults the room the command is used in.`]
};
const pages = {
quotes(args, user) {
const room = this.requireRoom();
this.title = `[Quotes]`;
if (!room.checkModjoin(user)) {
return this.errorReply(`Access denied.`);
}
let buffer = `<div class="pad">`;
buffer += `<button style="float:right;" class="button" name="send" value="/join view-quotes-${room.roomid}"><i class="fa fa-refresh"></i> Refresh</button>`;
const roomQuotes = quotes[room.roomid];
if (!roomQuotes?.length) {
return `${buffer}<h2>This room has no quotes.</h2></div>`;
}
buffer += import_lib.Utils.html`<h2>Quotes for ${room.title} (${roomQuotes.length}):</h2>`;
for (const [i, quoteObj] of roomQuotes.entries()) {
const index = i + 1;
const { quote, userid, date } = quoteObj;
buffer += `<div class="infobox">#${index}: ${Chat.formatText(quote, false, true)}`;
buffer += `<br /><hr /><small>Added by ${userid} on ${Chat.toTimestamp(new Date(date), { human: true })}</small>`;
if (user.can("mute", null, room)) {
buffer += ` <button class="button" name="send" value="/msgroom ${room.roomid},/removequote ${index}">Remove</button>`;
}
buffer += `</div>`;
}
buffer += `</div>`;
return buffer;
}
};
const handlers = {
onRenameRoom(oldID, newID) {
if (quotes[oldID]) {
if (!quotes[newID])
quotes[newID] = [];
quotes[newID].push(...quotes[oldID]);
delete quotes[oldID];
saveQuotes();
}
}
};
//# sourceMappingURL=quotes.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/quotes.ts"],
"sourcesContent": ["import {FS, Utils} from '../../lib';\r\n\r\nconst STORAGE_PATH = 'config/chat-plugins/quotes.json';\r\nconst MAX_QUOTES = 300;\r\n\r\ninterface Quote {\r\n\tuserid: string;\r\n\tquote: string;\r\n\tdate: number;\r\n}\r\n\r\nconst quotes: {[room: string]: Quote[]} = JSON.parse(FS(STORAGE_PATH).readIfExistsSync() || \"{}\");\r\n\r\n// migrate quotes out of roomsettings\r\nfunction convertOldQuotes() {\r\n\tfor (const room of Rooms.rooms.values()) {\r\n\t\t// @ts-ignore\r\n\t\tif (room.settings.quotes) {\r\n\t\t\t// @ts-ignore\r\n\t\t\tquotes[room.roomid] = room.settings.quotes;\r\n\t\t\t// @ts-ignore\r\n\t\t\tdelete room.settings.quotes;\r\n\t\t\troom.saveSettings();\r\n\t\t\tsaveQuotes();\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunction saveQuotes() {\r\n\tFS(STORAGE_PATH).writeUpdate(() => JSON.stringify(quotes));\r\n}\r\n\r\nconvertOldQuotes();\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\trandquote(target, room, user) {\r\n\t\troom = this.requireRoom();\r\n\t\tconst roomQuotes = quotes[room.roomid];\r\n\t\tif (!roomQuotes?.length) return this.errorReply(`This room has no quotes.`);\r\n\t\tthis.runBroadcast(true);\r\n\t\tconst {quote, date, userid} = roomQuotes[Math.floor(Math.random() * roomQuotes.length)];\r\n\t\tconst time = Chat.toTimestamp(new Date(date), {human: true});\r\n\t\tconst attribution = toID(target) === 'showauthor' ? `<hr /><small>Added by ${userid} on ${time}</small>` : '';\r\n\t\treturn this.sendReplyBox(`${Chat.getReadmoreBlock(quote)}${attribution}`);\r\n\t},\r\n\trandquotehelp: [`/randquote [showauthor] - Show a random quote from the room. Add 'showauthor' to see who added it and when.`],\r\n\r\n\taddquote: 'quote',\r\n\tquote(target, room, user) {\r\n\t\troom = this.requireRoom();\r\n\t\tif (!room.persist) {\r\n\t\t\treturn this.errorReply(\"This command is unavailable in temporary rooms.\");\r\n\t\t}\r\n\t\ttarget = target.trim();\r\n\t\tthis.checkCan('mute', null, room);\r\n\t\tif (!target) {\r\n\t\t\treturn this.parse(`/help quote`);\r\n\t\t}\r\n\t\tif (!quotes[room.roomid]) quotes[room.roomid] = [];\r\n\r\n\t\tconst roomQuotes = quotes[room.roomid];\r\n\t\tif (this.filter(target) !== target) {\r\n\t\t\treturn this.errorReply(`Invalid quote.`);\r\n\t\t}\r\n\t\tif (roomQuotes.filter(item => item.quote === target).length) {\r\n\t\t\treturn this.errorReply(`\"${target}\" is already quoted in this room.`);\r\n\t\t}\r\n\t\tif (target.length > 8192) {\r\n\t\t\treturn this.errorReply(`Your quote cannot exceed 8192 characters.`);\r\n\t\t}\r\n\t\tif (room.settings.isPrivate && roomQuotes.length >= MAX_QUOTES) {\r\n\t\t\treturn this.errorReply(`This room already has ${MAX_QUOTES} quotes, which is the maximum for private rooms.`);\r\n\t\t}\r\n\t\troomQuotes.push({userid: user.id, quote: target, date: Date.now()});\r\n\t\tsaveQuotes();\r\n\t\tthis.refreshPage(`quotes-${room.roomid}`);\r\n\t\tconst collapsedQuote = target.replace(/\\n/g, ' ');\r\n\t\tthis.privateModAction(`${user.name} added a new quote: \"${collapsedQuote}\".`);\r\n\t\treturn this.modlog(`ADDQUOTE`, null, collapsedQuote);\r\n\t},\r\n\tquotehelp: [`/quote [quote] - Adds [quote] to the room's quotes. Requires: % @ # &`],\r\n\r\n\tremovequote(target, room, user) {\r\n\t\troom = this.requireRoom();\r\n\t\tthis.checkCan('mute', null, room);\r\n\t\tif (!quotes[room.roomid]?.length) return this.errorReply(`This room has no quotes.`);\r\n\t\tconst index = parseInt(target.trim());\r\n\t\tif (isNaN(index)) {\r\n\t\t\treturn this.errorReply(`Invalid index.`);\r\n\t\t}\r\n\t\tconst roomQuotes = quotes[room.roomid];\r\n\t\tif (!roomQuotes[index - 1]) {\r\n\t\t\treturn this.errorReply(`Quote not found.`);\r\n\t\t}\r\n\t\tconst [removed] = roomQuotes.splice(index - 1, 1);\r\n\t\tconst collapsedQuote = removed.quote.replace(/\\n/g, ' ');\r\n\t\tthis.privateModAction(`${user.name} removed quote indexed at ${index}: \"${collapsedQuote}\" (originally added by ${removed.userid}).`);\r\n\t\tthis.modlog(`REMOVEQUOTE`, null, collapsedQuote);\r\n\t\tsaveQuotes();\r\n\t\tthis.refreshPage(`quotes-${room.roomid}`);\r\n\t},\r\n\tremovequotehelp: [`/removequote [index] - Removes the quote from the room's quotes. Requires: % @ # &`],\r\n\r\n\tviewquote(target, room, user) {\r\n\t\troom = this.requireRoom();\r\n\t\tconst roomQuotes = quotes[room.roomid];\r\n\t\tif (!roomQuotes?.length) return this.errorReply(`This room has no quotes.`);\r\n\t\tconst [num, showAuthor] = Utils.splitFirst(target, ',');\r\n\t\tconst index = parseInt(num) - 1;\r\n\t\tif (isNaN(index)) {\r\n\t\t\treturn this.errorReply(`Invalid index.`);\r\n\t\t}\r\n\t\tif (!roomQuotes[index]) {\r\n\t\t\treturn this.errorReply(`Quote not found.`);\r\n\t\t}\r\n\t\tthis.runBroadcast(true);\r\n\t\tconst {quote, date, userid} = roomQuotes[index];\r\n\t\tconst time = Chat.toTimestamp(new Date(date), {human: true});\r\n\t\tconst att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KAAK,IAAI,CAAC;AACrC,aAAO,KAAK,EAAE,KAAK,GAAG,OAAO,KAAK,CAAC;AACnC,aAAO,OAAO,KAAK;AACnB,iBAAW;AAAA,IACZ;AAAA,EACD;AACD;",
"names": []
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../../server/chat-plugins/randombattles/index.ts"],
"sourcesContent": ["/**\r\n * Random Battles chat-plugin\r\n * Written by Kris with inspiration from sirDonovan and The Immortal\r\n *\r\n * Set probability code written by Annika\r\n */\r\n\r\nimport {FS, Utils} from '../../../lib';\r\nimport {SSBSet, ssbSets} from '../../../data/mods/ssb/random-teams';\r\n\r\n\r\ninterface SetCriteria {\r\n\tmoves: {mustHave: Move[], mustNotHave: Move[]};\r\n\tability: {mustHave?: Ability, mustNotHave: Ability[]};\r\n\titem: {mustHave?: Item, mustNotHave: Item[]};\r\n\tnature: {mustHave?: Nature, mustNotHave: Nature[]};\r\n\tteraType: {mustHave?: TypeInfo, mustNotHave: TypeInfo[]};\r\n}\r\n\r\n\r\nfunction getHTMLCriteriaDescription(criteria: SetCriteria) {\r\n\tconst format = (list: {name: string}[]) => list.map(m => Utils.html`<strong>${m.name}</strong>`);\r\n\tconst parts = [];\r\n\r\n\tconst {moves, ability, item, nature, teraType} = criteria;\r\n\r\n\tif (moves.mustHave.length) {\r\n\t\tparts.push(`had the move${Chat.plural(moves.mustHave)} ${Chat.toListString(format(moves.mustHave))}`);\r\n\t}\r\n\tif (moves.mustNotHave.length) {\r\n\t\tparts.push(`did not have the move${Chat.plural(moves.mustNotHave)} ${Chat.toListString(format(moves.mustNotHave), 'or')}`);\r\n\t}\r\n\r\n\tif (ability.mustHave) {\r\n\t\tparts.push(Utils.html`had the ability <strong>${ability.mustHave.name}</strong>`);\r\n\t}\r\n\tif (ability.mustNotHave.length) {\r\n\t\tparts.push(`did not have the ${Chat.plural(ability.mustNotHave, 'abilities', 'ability')} ${Chat.toListString(format(ability.mustNotHave), 'or')}`);\r\n\t}\r\n\r\n\tif (item.mustHave) {\r\n\t\tparts.push(Utils.html`had the item <strong>${item.mustHave.name}</strong>`);\r\n\t}\r\n\tif (item.mustNotHave.length) {\r\n\t\tparts.push(`did not have the item${Chat.plural(item.mustNotHave)} ${Chat.toListString(format(item.mustNotHave), 'or')}`);\r\n\t}\r\n\r\n\tif (nature.mustHave) {\r\n\t\tparts.push(Utils.html`had the nature <strong>${nature.mustHave.name}</strong>`);\r\n\t}\r\n\tif (nature.mustNotHave.length) {\r\n\t\tparts.push(`did not have the nature${Chat.plural(nature.mustNotHave)} ${Chat.toListString(format(nature.mustNotHave), 'or')}`);\r\n\t}\r\n\r\n\tif (teraType.mustHave) {\r\n\t\tparts.push(Utils.html`had the Tera Type <strong>${teraType.mustHave.name}</strong>`);\r\n\t}\r\n\tif (teraType.mustNotHave.length) {\r\n\t\tparts.push(`did not have the Tera Type${Chat.plural(teraType.mustNotHave)} ${Chat.toListString(format(teraType.mustNotHave), 'or')}`);\r\n\t}\r\n\r\n\treturn Chat.toListString(parts, 'and');\r\n}\r\n\r\nfunction setProbability(\r\n\tspecies: Species,\r\n\tformat: Format,\r\n\tcriteria: SetCriteria,\r\n\trounds = 700\r\n): {rounds: number, matches: number} {\r\n\tconst results = {rounds, matches: 0};\r\n\tconst generator = Teams.getGenerator(format);\r\n\r\n\tfor (let i = 0; i < rounds; i++) {\r\n\t\tconst set = generator.randomSet(\r\n\t\t\tspecies,\r\n\t\t\t{},\r\n\t\t\tfalse,\r\n\t\t\tformat.gameType !== 'singles',\r\n\t\t\tformat.ruleTable?.has('dynamaxclause')\r\n\t\t);\r\n\r\n\t\tif (criteria.item.mustHave && set.item !== criteria.item.mustHave.name) continue;\r\n\t\tif (criteria.item.mustNotHave.some(item => item.name === set.item)) continue;\r\n\r\n\t\tif (criteria.ability.mustHave && set.ability !== criteria.ability.mustHave.name) continue;\r\n\t\tif (criteria.ability.mustNotHave.some(ability => ability.name === set.ability)) continue;\r\n\r\n\t\tif (criteria.nature.mustHave && set.nature !== criteria.nature.mustHave.name) continue;\r\n\t\tif (criteria.nature.mustNotHave.some(nature => nature.name === set.nature)) continue;\r\n\r\n\t\tif (criteria.teraType.mustHave && set.teraType !== criteria.teraType.mustHave.name) continue;\r\n\t\tif (criteria.teraType.mustNotHave.some(type => type.name === set.teraType)) continue;\r\n\r\n\t\tconst setHasMove = (move: Move) => {\r\n\t\t\tconst id = move.id === 'hiddenpower' ? `${move.id}${toID(move.type)}` : move.id;\r\n\t\t\treturn set.moves.includes(id);\r\n\t\t};\r\n\t\tif (!criteria.moves.mustHave.every(setHasMove)) continue;\r\n\t\tif (criteria.moves.mustNotHave.some(setHasMove)) continue;\r\n\r\n\t\tresults.matches++;\r\n\t}\r\n\r\n\treturn results;\r\n}\r\n\r\nconst GEN_NAMES: {[k: string]: string} = {\r\n\tgen1: '[Gen 1]', gen2: '[Gen 2]', gen3: '[Gen 3]', gen4: '[Gen 4]', gen5: '[Gen 5]', gen6: '[Gen 6]', gen7: '[Gen 7]',\r\n};\r\n\r\nconst STAT_NAMES: {[k: string]: string} = {\r\n\thp: \"HP\", atk: \"Atk\", def: \"Def\", spa: \"SpA\", spd: \"SpD\", spe: \"Spe\",\r\n};\r\n\r\nconst TIERS: {[k: string]: string} = {\r\n\tuber: \"Uber\", ubers: \"Uber\",\r\n\tou: \"OU\", uu: \"UU\", ru: \"RU\", nu: \"NU\", pu: \"PU\",\r\n\tmono: \"Mono\", monotype: \"Mono\", lc: \"LC\", littlecup: \"LC\",\r\n};\r\n\r\nfunction formatAbility(ability: Ability | string) {\r\n\tability = Dex.abilities.get(ability);\r\n\treturn `<a href=\"https://${Config.routes.dex}/abilities/${ability.id}\" target=\"_blank\" class=\"subtle\" style=\"white-space:nowrap\">${ability.name}</a>`;\r\n}\rLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAwB;AACxB,0BAA8B;AAY9B,SAAS,2BAA2B,UAAuB;A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,KAAK,SAAS,CAAC,KAAK,cACrB,CAAC,KAAK,kBAAkB,CAAC,KAAK,eAC7B;AACD,WAAO;AAAA,EACR;AACA,SAAO;AACR;AAEA,SAAS,eAAe,SAA2B;AAClD,YAAU,IAAI,QAAQ,IAAI,OAAO;AACjC,QAAM,OAAO,QAAQ,SAAS,wBAAwB;AACtD,MAAI,CAAC;AAAM,WAAO;AAClB,QAAM,iBACJ,QAAQ,OAAO,OAAO,CAAC,UAAU,UAAU,EAAE,SAAS,QAAQ,IAAI,OAClE,CAAC,QAAQ,SAAS,CAAC,SAAS,QAAQ,UAAU,UAAU,SAAS,EAAE,SAAS,QAAQ,KAAK;AAE3F,MAAI,CAAC;AAAe,WAAO;AAC3B,MAAI,CAAC,KAAK,OAAO;AAAQ,WAAO;AAChC,SAAO,KAAK,MAAM,IAAI,UAAU,EAAE,KAAK,EAAE,KAAK,IAAI;AACnD;AAEA,SAAS,kBAAkB,SAA2B,MAAqB,MAAM,QAAQ,QAAQ,OAAO;AACvG,YAAU,IAAI,QAAQ,IAAI,OAAO;AACjC,MAAI,OAAO,QAAQ,eAAe,UAAU;AAC3C,cAAU,IAAI,QAAQ,IAAI,QAAQ,UAAU;AAAA,EAC7C;AACA,QAAM,KAAK,GAAG;AACd,QAAM,SAAS,SAAS,IAAI,CAAC,CAAC;AAC9B,MAAI,MAAM,MAAM,KAAK,SAAS,KAAM,SAAS,SAAS;AAAI,WAAO;AACjE,QLine truncated
"names": ["buf"]
}
@@ -0,0 +1,256 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var winrates_exports = {};
__export(winrates_exports, {
commands: () => commands,
handlers: () => handlers,
pages: () => pages,
saveStats: () => saveStats,
stats: () => stats
});
module.exports = __toCommonJS(winrates_exports);
var import_lib = require("../../../lib");
const STATS_PATH = "logs/randbats/{{MONTH}}-winrates.json";
let stats;
try {
const path = STATS_PATH.replace("{{MONTH}}", getMonth());
if (!(0, import_lib.FS)("logs/randbats/").existsSync()) {
(0, import_lib.FS)("logs/randbats/").mkdirSync();
}
stats = JSON.parse((0, import_lib.FS)(path).readSync());
} catch {
stats = getDefaultStats();
}
function getDefaultStats() {
return {
elo: 1500,
month: getMonth(),
formats: {
// all of these requested by rands staff. they don't anticipate it being changed much
// so i'm not spending the time to add commands to toggle this
gen9randombattle: { mons: {} },
gen7randombattle: { mons: {} },
gen6randombattle: { mons: {} },
gen5randombattle: { mons: {} },
gen4randombattle: { mons: {} },
gen3randombattle: { mons: {} },
gen2randombattle: { mons: {} }
}
};
}
function saveStats(month = getMonth()) {
const curStats = { ...stats };
(0, import_lib.FS)(STATS_PATH.replace("{{MONTH}}", month)).writeUpdate(() => JSON.stringify(curStats));
}
function getMonth() {
return Chat.toTimestamp(new Date()).split(" ")[0].slice(0, -3);
}
function getSpeciesName(set, format) {
const species = set.species;
const item = Dex.items.get(set.item);
const moves = set.moves;
const megaRayquazaPossible = ["gen6", "gen7"].includes(format.mod) && !format.ruleset.includes("Mega Rayquaza Clause");
if (species.startsWith("Pikachu-")) {
return "Pikachu";
} else if (species.startsWith("Unown-")) {
return "Unown";
} else if (species === "Gastrodon-East") {
return "Gastrodon";
} else if (species === "Magearna-Original") {
return "Magearna";
} else if (species === "Genesect-Douse") {
return "Genesect";
} else if (species === "Dudunsparce-Three-Segment") {
return "Dudunsparce";
} else if (species === "Maushold-Four") {
return "Maushold";
} else if (species === "Squawkabilly-Blue") {
return "Squawkabilly";
} else if (species === "Squawkabilly-White") {
return "Squawkabilly-Yellow";
} else if (species.startsWith("Basculin-")) {
return "Basculin";
} else if (species.startsWith("Sawsbuck-")) {
return "Sawsbuck";
} else if (species.startsWith("Vivillon-")) {
return "Vivillon";
} else if (species.startsWith("Florges-")) {
return "Florges";
} else if (species.startsWith("Furfrou-")) {
return "Furfrou";
} else if (species.startsWith("Minior-")) {
return "Minior";
} else if (species.startsWith("Toxtricity-")) {
return "Toxtricity";
} else if (species.startsWith("Tatsugiri-")) {
return "Tatsugiri";
} else if (species === "Zacian" && item.name === "Rusted Sword") {
return "Zacian-Crowned";
} else if (species === "Zamazenta" && item.name === "Rusted Shield") {
return "Zamazenta-Crowned";
} else if (species === "Kyogre" && item.name === "Blue Orb") {
return "Kyogre-Primal";
} else if (species === "Groudon" && item.name === "Red Orb") {
return "Groudon-Primal";
} else if (item.megaStone) {
return item.megaStone;
} else if (species === "Rayquaza" && moves.includes("Dragon Ascent") && megaRayquazaPossible) {
return "Rayquaza-Mega";
} else {
return species;
}
}
function checkRollover() {
if (stats.month !== getMonth()) {
saveStats(stats.month);
Object.assign(stats, getDefaultStats());
saveStats();
}
}
const getZScore = (data) => 2 * Math.sqrt(data.timesGenerated) * (data.numWins / data.timesGenerated - 0.5);
const handlers = {
onBattleEnd(battle, winner, players) {
void collectStats(battle, winner, players);
}
};
async function collectStats(battle, winner, players) {
const formatData = stats.formats[battle.format];
let eloFloor = stats.elo;
const format = Dex.formats.get(battle.format);
if (format.mod !== `gen${Dex.gen}`) {
eloFloor = 1300;
}
if (!formatData || battle.rated < eloFloor)
return;
checkRollover();
for (const p of players) {
const team = await battle.getTeam(p);
if (!team)
return;
const mons = team.map((f) => getSpeciesName(f, format));
for (const mon of mons) {
if (!formatData.mons[mon])
formatData.mons[mon] = { timesGenerated: 0, numWins: 0 };
formatData.mons[mon].timesGenerated++;
if (toID(winner) === toID(p)) {
formatData.mons[mon].numWins++;
}
}
}
saveStats();
}
const commands = {
rwr: "randswinrates",
randswinrates(target, room, user) {
return this.parse(`/j view-winrates-${toID(target) || `gen${Dex.gen}randombattle`}`);
},
randswinrateshelp: [
"/randswinrates OR /rwr [format] - Get a list of the win rates for all Pokemon in the given Random Battles format."
],
async removewinrates(target, room, user) {
this.checkCan("rangeban");
if (!/^[0-9]{4}-[0-9]{2}$/.test(target) || target === getMonth()) {
return this.errorReply(`Invalid month: ${target}`);
}
const path = STATS_PATH.replace("{{MON}}", target);
if (!await (0, import_lib.FS)(path).exists()) {
return this.errorReply(`No stats for the month ${target}.`);
}
await (0, import_lib.FS)(path).unlinkIfExists();
this.globalModlog("REMOVEWINRATES", null, target);
this.privateGlobalModAction(`${user.name} removed Random Battle winrates for the month of ${target}`);
}
};
const pages = {
async winrates(query, user) {
if (!user.named)
return Rooms.RETRY_AFTER_LOGIN;
query = query.join("-").split("--");
const format = toID(query.shift());
if (!format)
return this.errorReply(`Specify a format to view winrates for.`);
if (!stats.formats[format]) {
return this.errorReply(`That format does not have winrates tracked.`);
}
checkRollover();
const sorter = toID(query.shift() || "zscore");
if (!["zscore", "raw"].includes(sorter)) {
return this.errorReply(`Invalid sorting method. Must be either 'zscore' or 'raw'.`);
}
const month = query.shift() || getMonth();
if (!/^[0-9]{4}-[0-9]{2}$/.test(month)) {
return this.errorReply(`Invalid month: ${month}`);
}
const isOldMonth = month !== getMonth();
if (isOldMonth && !await (0, import_lib.FS)(STATS_PATH.replace("{{MONTH}}", month)).exists()) {
return this.errorReply(`There are no winrates for that month.`);
}
const formatTitle = Dex.formats.get(format).name;
let buf = `<div class="pad"><h2>Winrates for ${formatTitle} (${month})</h2>`;
const prevMonth = new Date(new Date(`${month}-15`).getTime() - 30 * 24 * 60 * 60 * 1e3).toISOString().slice(0, 7);
let hasButton = false;
if (await (0, import_lib.FS)(STATS_PATH.replace("{{MONTH}}", prevMonth)).exists()) {
buf += `<a class="button" href="/view-winrates-${format}--${sorter}--${prevMonth}">Previous month</a>`;
hasButton = true;
}
const nextMonth = new Date(new Date(`${month}-15`).getTime() + 30 * 24 * 60 * 60 * 1e3).toISOString().slice(0, 7);
if (await (0, import_lib.FS)(STATS_PATH.replace("{{MONTH}}", nextMonth)).exists()) {
if (hasButton)
buf += ` | `;
buf += `<a class="button" href="/view-winrates-${format}--${sorter}--${nextMonth}">Next month</a>`;
hasButton = true;
}
buf += hasButton ? ` | ` : "";
const otherSort = sorter === "zscore" ? "Raw" : "Z-Score";
buf += `<a class="button" target="replace" href="/view-winrates-${format}--${toID(otherSort)}--${month}">`;
buf += `Sort by ${otherSort} descending</a>`;
buf += `<hr />`;
const statData = month === stats.month ? stats : JSON.parse(await (0, import_lib.FS)(STATS_PATH.replace("{{MONTH}}", month)).read());
const formatData = statData.formats[format];
if (!formatData) {
buf += `<div class="message-error">No stats for that format found on that month.</div>`;
return buf;
}
this.title = `[Winrates] [${format}] ${month}`;
let sortFn;
if (sorter === "zscore") {
sortFn = ([_, data]) => [-getZScore(data), -data.timesGenerated];
} else {
sortFn = ([_, data]) => [
-(data.numWins / data.timesGenerated),
-data.numWins,
-data.timesGenerated
];
}
const mons = import_lib.Utils.sortBy(Object.entries(formatData.mons), sortFn);
buf += `<div class="ladder pad"><table><tr><th>Pokemon</th><th>Win %</th><th>Z-Score</th>`;
buf += `<th>Raw wins</th><th>Times generated</th></tr>`;
for (const [mon, data] of mons) {
buf += `<tr><td>${Dex.species.get(mon).name}</td>`;
const { timesGenerated, numWins } = data;
buf += `<td>${(numWins / timesGenerated * 100).toFixed(2)}%</td>`;
buf += `<td>${getZScore(data).toFixed(3)}</td>`;
buf += `<td>${numWins}</td><td>${timesGenerated}</td>`;
buf += `</tr>`;
}
buf += `</table></div></div>`;
return buf;
}
};
//# sourceMappingURL=winrates.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../../server/chat-plugins/randombattles/winrates.ts"],
"sourcesContent": ["/**\r\n * A chat plugin to store, calculate, and view winrates in random battle formats.\r\n * @author mia-pi-git\r\n */\r\n\r\nimport {FS, Utils} from '../../../lib';\r\n\r\ninterface Stats {\r\n\telo: number;\r\n\tmonth: string;\r\n\tformats: Record<string, FormatData>;\r\n}\r\n\r\ninterface MonEntry {\r\n\ttimesGenerated: number;\r\n\tnumWins: number;\r\n}\r\n\r\ninterface FormatData {\r\n\tmons: Record<string, MonEntry>;\r\n\tperiod?: number; // how often it resets - defaults to 1mo\r\n}\r\n\r\nconst STATS_PATH = 'logs/randbats/{{MONTH}}-winrates.json';\r\nexport let stats: Stats;\r\n\r\ntry {\r\n\tconst path = STATS_PATH.replace('{{MONTH}}', getMonth());\r\n\tif (!FS('logs/randbats/').existsSync()) {\r\n\t\tFS('logs/randbats/').mkdirSync();\r\n\t}\r\n\tstats = JSON.parse(FS(path).readSync());\r\n} catch {\r\n\tstats = getDefaultStats();\r\n}\r\n\r\nfunction getDefaultStats() {\r\n\treturn {\r\n\t\telo: 1500,\r\n\t\tmonth: getMonth(),\r\n\t\tformats: {\r\n\t\t\t// all of these requested by rands staff. they don't anticipate it being changed much\r\n\t\t\t// so i'm not spending the time to add commands to toggle this\r\n\t\t\tgen9randombattle: {mons: {}},\r\n\t\t\tgen7randombattle: {mons: {}},\r\n\t\t\tgen6randombattle: {mons: {}},\r\n\t\t\tgen5randombattle: {mons: {}},\r\n\t\t\tgen4randombattle: {mons: {}},\r\n\t\t\tgen3randombattle: {mons: {}},\r\n\t\t\tgen2randombattle: {mons: {}},\r\n\t\t},\r\n\t} as Stats;\r\n}\r\n\r\nexport function saveStats(month = getMonth()) {\r\n\t// clone to avoid race conditions with the data getting deleted later (on month rollover)\r\n\tconst curStats = {...stats};\r\n\tFS(STATS_PATH.replace('{{MONTH}}', month)).writeUpdate(() => JSON.stringify(curStats));\r\n}\r\n\r\nfunction getMonth() {\r\n\treturn Chat.toTimestamp(new Date()).split(' ')[0].slice(0, -3);\r\n}\r\n\r\n// no, this cannot be baseSpecies - some formes matter, ex arceus formes\r\n// no, there is no better way to do this.\r\n// yes, i tried.\r\nfunction getSpeciesName(set: PokemonSet, format: Format) {\r\n\tconst species = set.species;\r\n\tconst item = Dex.items.get(set.item);\r\n\tconst moves = set.moves;\r\n\tconst megaRayquazaPossible = ['gen6', 'gen7'].includes(format.mod) && !format.ruleset.includes('Mega Rayquaza Clause');\r\n\tif (species.startsWith(\"Pikachu-\")) {\r\n\t\treturn 'Pikachu';\r\n\t} else if (species.startsWith(\"Unown-\")) {\r\n\t return 'Unown';\r\n\t} else if (species === \"Gastrodon-East\") {\r\n\t\treturn 'Gastrodon';\r\n\t} else if (species === \"Magearna-Original\") {\r\n\t return \"Magearna\";\r\n\t} else if (species === \"Genesect-Douse\") {\r\n\t\treturn \"Genesect\";\r\n\t} else if (species === \"Dudunsparce-Three-Segment\") {\r\n\t\treturn 'Dudunsparce';\r\n\t} else if (species === \"Maushold-Four\") {\r\n\t\treturn 'Maushold';\r\n\t} else if (species === \"Squawkabilly-Blue\") {\r\n\t\treturn \"Squawkabilly\";\r\n\t} else if (species === \"Squawkabilly-White\") {\r\n\t\treturn \"Squawkabilly-Yellow\";\r\n\t} else if (species.startsWith(\"Basculin-\")) {\r\n\t\treturn \"Basculin\";\r\n\t} else if (species.startsWith(\"Sawsbuck-\")) {\r\n\t\treturn \"Sawsbuck\";\r\n\t} else if (species.startsWith(\"Vivillon-\")) {\r\n\t\treturn \"Vivillon\";\r\n\t} else if (species.startsWith(\"Florges-\")) {\r\n\t\treturn \"Florges\";\r\n\t} else if (species.startsWith(\"Furfrou-\")) {\r\n\t\treturn \"Furfrou\";\r\n\t} else if (species.startsWith(\"Minior-\")) {\r\n\t\treturn \"Minior\";\r\n\t} else if (species.startsWith(\"Toxtricity-\")) {\r\n\t\treturn 'Toxtricity';\r\n\t} else if (species.startsWith(\"Tatsugiri-\")) {\r\n\t\treturn 'Tatsugiri';\r\n\t} else if (species === \"Zacian\" && item.name === \"Rusted Sword\") {\r\n\t\treturn 'Zacian-Crowned';\r\n\t} else if (species === \"Zamazenta\" && item.name === \"Rusted Shield\") {\r\n\t\treturn \"Zamazenta-Crowned\";\r\n\t} else if (species === \"Kyogre\" && item.name === \"Blue Orb\") {\r\n\t\treturn \"Kyogre-Primal\";\r\n\t} else if (species === \"Groudon\" && item.name === \"Red Orb\") {\r\n\t\treturn \"Groudon-Primal\";\r\n\t} else if (item.megaStone) {\r\n\t\treturn item.megaStone;\r\n\t} else if (species === \"Rayquaza\" && moves.includes('Dragon Ascent') && megaRayquazaPossible) {\r\n\t\treturn \"Rayquaza-Mega\";\r\n\t} else {\r\n\t\treturn species;\r\n\t}\r\n}\r\n\r\nfunction checkRollover() {\r\n\tif (stats.month !== getMonth()) {\r\n\t\tsaveStats(stats.month);\r\n\t\tObject.assign(stats, getDefaultStats());\r\n\t\tsaveStats();\r\n\t}\r\n}\r\n\r\nconst getZScore = (data: MonEntry) => (\r\n\t2 * Math.sqrt(data.timesGenerated) * (data.numWins / data.timesGenerated - 0.5)\r\n);\r\n\r\n\r\nexport const handlers: Chat.Handlers = {\r\n\tonBattleEnd(battle, winner, players) {\r\n\t\tvoid collectStats(battle, winner, players);\r\n\t},\r\n};\r\n\r\nasync function collectStats(battle: RoomBattle, winner: ID, players: ID[]) {\r\n\tconst formatData = stats.formats[battle.format];\r\n\tlet eloFloor = stats.elo;\r\n\tconsLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,iBAAwB;AAkBxB,MAAM,aAAa;AACZ,IAAI;AAEX,IAAI;AACH,QAAM,OAAO,WAAW,QAAQ,aAAa,SAAS,CAAC;AACvD,MAAI,KAAC,eAAG,gBAAgB,EAAE,WAAW,GAAG;AACvC,uBAAG,gBAAgB,EAAE,UAAU;AAAA,EAChC;AACA,UAAQ,KAAK,UAAM,eAAG,IAAI,EAAE,SAAS,CAAC;AACvC,QAAE;AACD,UAAQ,gBAAgB;AACzB;AAEA,SAAS,kBAAkB;AAC1B,SAAO;AAAA,IACN,KAAK;AAAA,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MAAM,GAAG,CAAC;AACnH,QAAI,YAAY;AAChB,QAAI,UAAM,eAAG,WAAW,QAAQ,aAAa,SAAS,CAAC,EAAE,OAAO,GAAG;AAClE,aAAO,0CAA0C,WAAW,WAAW;AACvE,kBAAY;AAAA,IACb;AACA,UAAM,YAAY,IAAI,KAAK,IAAI,KAAK,GAAG,UAAU,EAAE,QAAQ,IAAK,KAAK,KAAK,KAAK,KAAK,GAAK,EAAE,YAAY,EAAE,MAAM,GAAG,CAAC;AACnH,QAAI,UAAM,eAAG,WAAW,QAAQ,aAAa,SAAS,CAAC,EAAE,OAAO,GAAG;AAClE,UAAI;AAAW,eAAO;AACtB,aAAO,0CAA0C,WAAW,WAAW;AACvE,kBAAY;AAAA,IACb;AACA,WAAO,YAAY,QAAQ;AAC3B,UAAM,YAAY,WAAW,WAAW,QAAQ;AAChD,WAAO,2DAA2D,WAAW,Line truncated
"names": []
}
+268
View File
@@ -0,0 +1,268 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var repeats_exports = {};
__export(repeats_exports, {
Repeats: () => Repeats,
commands: () => commands,
destroy: () => destroy,
pages: () => pages
});
module.exports = __toCommonJS(repeats_exports);
var import_room_faqs = require("./room-faqs");
const Repeats = new class {
constructor() {
// keying to Room rather than RoomID will help us correctly handle room renames
/** room:identifier:phrase:timeout map */
this.repeats = /* @__PURE__ */ new Map();
for (const room of Rooms.rooms.values()) {
if (!room.settings?.repeats?.length)
continue;
for (const repeat of room.settings.repeats) {
this.runRepeat(room, repeat);
}
}
}
removeRepeatHandler(room, handler) {
if (typeof handler === "function") {
room.nthMessageHandlers.delete(handler);
} else if (typeof handler === "object") {
clearInterval(handler);
}
}
hasRepeat(room, id) {
return !!this.repeats.get(room)?.get(id);
}
addRepeat(room, repeat) {
this.runRepeat(room, repeat);
if (!room.settings.repeats)
room.settings.repeats = [];
room.settings.repeats.push(repeat);
room.saveSettings();
}
removeRepeat(room, id) {
if (!room.settings.repeats)
return;
const phrase = room.settings.repeats.find((x) => x.id === id)?.phrase;
room.settings.repeats = room.settings.repeats.filter((repeat) => repeat.id !== id);
if (!room.settings.repeats.length)
delete room.settings.repeats;
room.saveSettings();
const roomRepeats = this.repeats.get(room);
if (!roomRepeats)
return;
const oldInterval = roomRepeats.get(id)?.get(phrase);
this.removeRepeatHandler(room, oldInterval);
roomRepeats.delete(id);
}
clearRepeats(room) {
const roomRepeats = this.repeats.get(room);
if (!roomRepeats)
return;
for (const ids of roomRepeats.values()) {
for (const interval of ids.values()) {
this.removeRepeatHandler(room, interval);
}
}
this.repeats.delete(room);
}
runRepeat(room, repeat) {
let roomRepeats = this.repeats.get(room);
if (!roomRepeats) {
roomRepeats = /* @__PURE__ */ new Map();
this.repeats.set(room, roomRepeats);
}
const { id, phrase, interval } = repeat;
if (roomRepeats.has(id)) {
throw new Error(`Repeat already exists`);
}
const repeater = (targetRoom) => {
if (targetRoom !== Rooms.get(targetRoom.roomid)) {
this.clearRepeats(targetRoom);
return;
}
const repeatedPhrase = repeat.faq ? (0, import_room_faqs.visualizeFaq)(import_room_faqs.roomFaqs[targetRoom.roomid][repeat.id]) : Chat.formatText(phrase, true);
const formattedText = repeat.isHTML ? phrase : repeatedPhrase;
targetRoom.add(`|uhtml|repeat-${repeat.id}|<div class="infobox">${formattedText}</div>`);
targetRoom.update();
};
if (repeat.isByMessages) {
room.nthMessageHandlers.set(repeater, interval);
roomRepeats.set(id, (/* @__PURE__ */ new Map()).set(phrase, repeater));
} else {
roomRepeats.set(id, (/* @__PURE__ */ new Map()).set(phrase, setInterval(repeater, interval, room)));
}
}
destroy() {
for (const [room, roomRepeats] of this.repeats) {
for (const ids of roomRepeats.values()) {
for (const interval of ids.values()) {
this.removeRepeatHandler(room, interval);
}
}
}
}
}();
function destroy() {
Repeats.destroy();
}
const pages = {
repeats(args, user) {
const room = this.requireRoom();
this.title = `[Repeats]`;
this.checkCan("mute", null, room);
let html = `<div class="ladder pad">`;
html += `<button class="button" name="send" value="/join view-repeats-${room.roomid}" style="float: right"><i class="fa fa-refresh"></i> ${this.tr`Refresh`}</button>`;
if (!room.settings.repeats?.length) {
return `${html}<h1>${this.tr`There are no repeated phrases in ${room.title}.`}</h1></div>`;
}
html += `<h2>${this.tr`Repeated phrases in ${room.title}`}</h2>`;
html += `<table><tr><th>${this.tr`Identifier`}</th><th>${this.tr`Phrase`}</th><th>${this.tr`Raw text`}</th><th>${this.tr`Interval`}</th><th>${this.tr`Action`}</th>`;
for (const repeat of room.settings.repeats) {
const minutes = repeat.interval / (repeat.isByMessages ? 1 : 60 * 1e3);
const repeatText = repeat.faq ? import_room_faqs.roomFaqs[room.roomid][repeat.id].source : repeat.phrase;
const phrase = repeat.faq ? (0, import_room_faqs.visualizeFaq)(import_room_faqs.roomFaqs[room.roomid][repeat.id]) : repeat.isHTML ? repeat.phrase : Chat.formatText(repeatText, true);
html += `<tr><td>${repeat.id}</td><td>${phrase}</td><td>${Chat.getReadmoreCodeBlock(repeatText)}</td><td>${repeat.isByMessages ? this.tr`every ${minutes} chat message(s)` : this.tr`every ${minutes} minute(s)`}</td>`;
html += `<td><button class="button" name="send" value="/msgroom ${room.roomid},/removerepeat ${repeat.id}">${this.tr`Remove`}</button></td>`;
}
html += `</table>`;
if (user.can("editroom", null, room)) {
html += `<br /><button class="button" name="send" value="/msgroom ${room.roomid},/removeallrepeats">${this.tr`Remove all repeats`}</button>`;
}
html += `</div>`;
return html;
}
};
const commands = {
repeatbymessages: "repeat",
repeathtmlbymessages: "repeat",
repeathtml: "repeat",
repeat(target, room, user, connection, cmd) {
const isHTML = cmd.includes("html");
const isByMessages = cmd.includes("bymessages");
room = this.requireRoom();
this.checkCan(isHTML ? "addhtml" : "mute", null, room);
const [intervalString, name, ...messageArray] = target.split(",");
const id = toID(name);
if (!id)
throw new Chat.ErrorMessage(this.tr`Repeat names must include at least one alphanumeric character.`);
const phrase = messageArray.join(",").trim();
const interval = parseInt(intervalString);
if (isNaN(interval) || !/[0-9]{1,}/.test(intervalString) || interval < 1 || interval > 24 * 60) {
throw new Chat.ErrorMessage(this.tr`You must specify an interval as a number of minutes or chat messages between 1 and 1440.`);
}
if (Repeats.hasRepeat(room, id)) {
throw new Chat.ErrorMessage(this.tr`The phrase labeled with "${id}" is already being repeated in this room.`);
}
if (isHTML)
this.checkHTML(phrase);
Repeats.addRepeat(room, {
id,
phrase,
// convert to milliseconds for time-based repeats
interval: interval * (isByMessages ? 1 : 60 * 1e3),
isHTML,
isByMessages
});
this.modlog("REPEATPHRASE", null, `every ${interval} ${isByMessages ? `chat messages` : `minute`}${Chat.plural(interval)}: "${phrase.replace(/\n/g, " ")}"`);
this.privateModAction(
isByMessages ? room.tr`${user.name} set the phrase labeled with "${id}" to be repeated every ${interval} chat message(s).` : room.tr`${user.name} set the phrase labeled with "${id}" to be repeated every ${interval} minute(s).`
);
},
repeathelp() {
this.runBroadcast();
this.sendReplyBox(
`<code>/repeat [minutes], [id], [phrase]</code>: repeats a given phrase every [minutes] minutes. Requires: % @ # &<br /><code>/repeathtml [minutes], [id], [phrase]</code>: repeats a given phrase containing HTML every [minutes] minutes. Requires: # &<br /><code>/repeatfaq [minutes], [FAQ name/alias]</code>: repeats a given Room FAQ every [minutes] minutes. Requires: % @ # &<br /><code>/removerepeat [id]</code>: removes a repeated phrase. Requires: % @ # &<br /><code>/viewrepeats [optional room]</code>: Displays all repeated phrases in a room. Requires: % @ # &<br />You can append <code>bymessages</code> to a <code>/repeat</code> command to repeat a phrase based on how many messages have been sent in chat. For example, <code>/repeatfaqbymessages ...</code><br />Phrases for <code>/repeat</code> can include normal chat formatting, but not commands.`
);
},
repeatfaqbymessages: "repeatfaq",
repeatfaq(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan("mute", null, room);
const isByMessages = cmd.includes("bymessages");
let [intervalString, topic] = target.split(",");
const interval = parseInt(intervalString);
if (isNaN(interval) || !/[0-9]{1,}/.test(intervalString) || interval < 1 || interval > 24 * 60) {
throw new Chat.ErrorMessage(this.tr`You must specify an interval as a number of minutes or chat messages between 1 and 1440.`);
}
if (!import_room_faqs.roomFaqs[room.roomid]) {
throw new Chat.ErrorMessage(`This room has no FAQs.`);
}
topic = toID((0, import_room_faqs.getAlias)(room.roomid, topic) || topic);
const faq = import_room_faqs.roomFaqs[room.roomid][topic];
if (!faq) {
throw new Chat.ErrorMessage(`Invalid topic.`);
}
if (Repeats.hasRepeat(room, topic)) {
throw new Chat.ErrorMessage(this.tr`The text for the Room FAQ "${topic}" is already being repeated.`);
}
Repeats.addRepeat(room, {
id: topic,
phrase: faq.source,
interval: interval * (isByMessages ? 1 : 60 * 1e3),
faq: true,
isByMessages
});
this.modlog("REPEATPHRASE", null, `every ${interval} ${isByMessages ? "chat message" : "minute"}${Chat.plural(interval)}: the Room FAQ for "${topic}"`);
this.privateModAction(
isByMessages ? room.tr`${user.name} set the Room FAQ "${topic}" to be repeated every ${interval} chat message(s).` : room.tr`${user.name} set the Room FAQ "${topic}" to be repeated every ${interval} minute(s).`
);
},
deleterepeat: "removerepeat",
removerepeat(target, room, user) {
room = this.requireRoom();
const id = toID(target);
if (!id) {
return this.parse(`/help repeat`);
}
this.checkCan("mute", null, room);
if (!room.settings.repeats?.length) {
return this.errorReply(this.tr`There are no repeated phrases in this room.`);
}
if (!Repeats.hasRepeat(room, id)) {
return this.errorReply(this.tr`The phrase labeled with "${id}" is not being repeated in this room.`);
}
Repeats.removeRepeat(room, id);
this.modlog("REMOVE REPEATPHRASE", null, `"${id}"`);
this.privateModAction(room.tr`${user.name} removed the repeated phrase labeled with "${id}".`);
this.refreshPage(`repeats-${room.roomid}`);
},
removeallrepeats(target, room, user) {
room = this.requireRoom();
this.checkCan("declare", null, room);
if (!room.settings.repeats?.length) {
return this.errorReply(this.tr`There are no repeated phrases in this room.`);
}
for (const { id } of room.settings.repeats) {
Repeats.removeRepeat(room, id);
}
this.modlog("REMOVE REPEATPHRASE", null, "all repeated phrases");
this.privateModAction(room.tr`${user.name} removed all repeated phrases.`);
},
repeats: "viewrepeats",
viewrepeats(target, room, user) {
const roomid = toID(target) || room?.roomid;
if (!roomid)
return this.errorReply(this.tr`You must specify a room when using this command in PMs.`);
this.parse(`/j view-repeats-${roomid}`);
}
};
process.nextTick(() => {
Chat.multiLinePattern.register("/repeat(html|faq)?(bymessages)? ");
});
//# sourceMappingURL=repeats.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/repeats.ts"],
"sourcesContent": ["/**\r\n * Chat plugin for repeating messages in chat\r\n * Based on bot functionality from Kid A and Expecto Botronum\r\n * @author Annika, Zarel\r\n */\r\n\r\nimport {roomFaqs, getAlias, visualizeFaq} from './room-faqs';\r\nimport type {MessageHandler} from '../rooms';\r\n\r\nexport interface RepeatedPhrase {\r\n\t/** Identifier for deleting */\r\n\tid: ID;\r\n\tphrase: string;\r\n\t/** interval in milliseconds */\r\n\tinterval: number;\r\n\tfaq?: boolean;\r\n\tisByMessages?: boolean;\r\n\tisHTML?: boolean;\r\n}\r\n\r\nexport const Repeats = new class {\r\n\t// keying to Room rather than RoomID will help us correctly handle room renames\r\n\t/** room:identifier:phrase:timeout map */\r\n\trepeats = new Map<BasicRoom, Map<ID, Map<string, NodeJS.Timeout | MessageHandler>>>();\r\n\r\n\tconstructor() {\r\n\t\tfor (const room of Rooms.rooms.values()) {\r\n\t\t\tif (!room.settings?.repeats?.length) continue;\r\n\t\t\tfor (const repeat of room.settings.repeats) {\r\n\t\t\t\tthis.runRepeat(room, repeat);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tremoveRepeatHandler(room: BasicRoom, handler?: NodeJS.Timeout | MessageHandler) {\r\n\t\tif (typeof handler === 'function') {\r\n\t\t\troom.nthMessageHandlers.delete(handler);\r\n\t\t} else if (typeof handler === 'object') {\r\n\t\t\tclearInterval(handler);\r\n\t\t}\r\n\t}\r\n\r\n\thasRepeat(room: BasicRoom, id: ID) {\r\n\t\treturn !!this.repeats.get(room)?.get(id);\r\n\t}\r\n\r\n\taddRepeat(room: BasicRoom, repeat: RepeatedPhrase) {\r\n\t\tthis.runRepeat(room, repeat);\r\n\t\tif (!room.settings.repeats) room.settings.repeats = [];\r\n\t\troom.settings.repeats.push(repeat);\r\n\t\troom.saveSettings();\r\n\t}\r\n\r\n\tremoveRepeat(room: BasicRoom, id: ID) {\r\n\t\tif (!room.settings.repeats) return;\r\n\t\tconst phrase = room.settings.repeats.find(x => x.id === id)?.phrase;\r\n\t\troom.settings.repeats = room.settings.repeats.filter(repeat => repeat.id !== id);\r\n\t\tif (!room.settings.repeats.length) delete room.settings.repeats;\r\n\t\troom.saveSettings();\r\n\r\n\t\tconst roomRepeats = this.repeats.get(room);\r\n\t\tif (!roomRepeats) return;\r\n\t\tconst oldInterval = roomRepeats.get(id)?.get(phrase!);\r\n\t\tthis.removeRepeatHandler(room, oldInterval);\r\n\t\troomRepeats.delete(id);\r\n\t}\r\n\r\n\tclearRepeats(room: BasicRoom) {\r\n\t\tconst roomRepeats = this.repeats.get(room);\r\n\t\tif (!roomRepeats) return;\r\n\t\tfor (const ids of roomRepeats.values()) {\r\n\t\t\tfor (const interval of ids.values()) {\r\n\t\t\t\tthis.removeRepeatHandler(room, interval);\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.repeats.delete(room);\r\n\t}\r\n\r\n\trunRepeat(room: BasicRoom, repeat: RepeatedPhrase) {\r\n\t\tlet roomRepeats = this.repeats.get(room);\r\n\t\tif (!roomRepeats) {\r\n\t\t\troomRepeats = new Map();\r\n\t\t\tthis.repeats.set(room, roomRepeats);\r\n\t\t}\r\n\t\tconst {id, phrase, interval} = repeat;\r\n\r\n\t\tif (roomRepeats.has(id)) {\r\n\t\t\tthrow new Error(`Repeat already exists`);\r\n\t\t}\r\n\t\tconst repeater = (targetRoom: BasicRoom) => {\r\n\t\t\tif (targetRoom !== Rooms.get(targetRoom.roomid)) {\r\n\t\t\t\t// room was deleted\r\n\t\t\t\tthis.clearRepeats(targetRoom);\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tconst repeatedPhrase = repeat.faq ?\r\n\t\t\t\tvisualizeFaq(roomFaqs[targetRoom.roomid][repeat.id]) : Chat.formatText(phrase, true);\r\n\t\t\tconst formattedText = repeat.isHTML ? phrase : repeatedPhrase;\r\n\t\t\ttargetRoom.add(`|uhtml|repeat-${repeat.id}|<div class=\"infobox\">${formattedText}</div>`);\r\n\t\t\ttargetRoom.update();\r\n\t\t};\r\n\r\n\t\tif (repeat.isByMessages) {\r\n\t\t\troom.nthMessageHandlers.set(repeater, interval);\r\n\t\t\troomRepeats.set(id, new Map().set(phrase, repeater));\r\n\t\t} else {\r\n\t\t\troomRepeats.set(id, new Map().set(phrase, setInterval(repeater, interval, room)));\r\n\t\t}\r\n\t}\r\n\r\n\tdestroy() {\r\n\t\tfor (const [room, roomRepeats] of this.repeats) {\r\n\t\t\tfor (const ids of roomRepeats.values()) {\r\n\t\t\t\tfor (const interval of ids.values()) {\r\n\t\t\t\t\tthis.removeRepeatHandler(room, interval);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\nexport function destroy() {\r\n\tRepeats.destroy();\r\n}\r\n\r\nexport const pages: Chat.PageTable = {\r\n\trepeats(args, user) {\r\n\t\tconst room = this.requireRoom();\r\n\t\tthis.title = `[Repeats]`;\r\n\t\tthis.checkCan(\"mute\", null, room);\r\n\t\tlet html = `<div class=\"ladder pad\">`;\r\n\t\thtml += `<button class=\"button\" name=\"send\" value=\"/join view-repeats-${room.roomid}\" style=\"float: right\"><i class=\"fa fa-refresh\"></i> ${this.tr`Refresh`}</button>`;\r\n\t\tif (!room.settings.repeats?.length) {\r\n\t\t\treturn `${html}<h1>${this.tr`There are no repeated phrases in ${room.title}.`}</h1></div>`;\r\n\t\t}\r\n\t\thtml += `<h2>${this.tr`Repeated phrases in ${room.title}`}</h2>`;\r\n\t\thtml += `<table><tr><th>${this.tr`Identifier`}</th><th>${this.tr`Phrase`}</th><th>${this.tr`Raw text`}</th><th>${this.tr`Interval`}</th><th>${this.tr`ActLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,uBAA+C;AAcxC,MAAM,UAAU,IAAI,MAAM;AAAA,EAKhC,cAAc;AAFd;AAAA;AAAA,mBAAU,oBAAI,IAAsE;AAGnF,eAAW,QAAQ,MAAM,MAAM,OAAO,GAAG;AACxC,UAAI,CAAC,KAAK,UAAU,SAAS;AAAQ;AACrC,iBAAW,UAAU,KAAK,SAAS,SAAS;AAC3C,aAAK,UAAU,MAAM,MAAM;AAAA,MAC5B;AAAA,IACD;AAAA,EACD;AAAA,EAEA,oBAAoB,MAAiB,SAA2C;AAC/E,QAAI,OAAO,YAAY,YAAY;AAClC,WAAK,mBAAmB,OAAO,OAAO;AAAA,IACvC,WAAW,OAAO,YAAY,UAAU;AACvC,oBAAc,OAAO;AAAA,IACtB;AAAA,EACD;AAAA,EAEA,UAAU,MAAiB,IAAQ;AAClC,WAAO,CAAC,CAAC,KAAK,QAAQ,IAAI,IAAI,GAAG,IAAI,EAAE;AAAA,EACxC;AAAA,EAEA,UAAU,MAAiB,QAAwB;AAClD,SAAK,UAAU,MAAM,MAAM;AAC3B,QAAI,CAAC,KAAK,SAAS;AAAS,WAAK,SAAS,UAAU,CAAC;AACrD,SAAK,SAAS,QAAQ,KAAK,MAAM;AACjC,SAAK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AAK;AACvC,QAAI,CAAC,KAAK;AACT,YAAM,IAAI,KAAK,aAAa,gBAAgB;AAAA,IAC7C;AAEA,QAAI,QAAQ,UAAU,MAAM,KAAW,GAAG;AACzC,YAAM,IAAI,KAAK,aAAa,KAAK,gCAAgC,mCLine truncated
"names": []
}
+557
View File
@@ -0,0 +1,557 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var responder_exports = {};
__export(responder_exports, {
AutoResponder: () => AutoResponder,
answererData: () => answererData,
chatfilter: () => chatfilter,
commands: () => commands,
handlers: () => handlers,
pages: () => pages
});
module.exports = __toCommonJS(responder_exports);
var import_lib = require("../../lib");
var import_chatlog = require("./chatlog");
var import_room_faqs = require("./room-faqs");
const DATA_PATH = "config/chat-plugins/responder.json";
const LOG_PATH = "logs/responder.jsonl";
let answererData = {};
try {
answererData = JSON.parse((0, import_lib.FS)(DATA_PATH).readSync());
} catch {
}
const _AutoResponder = class {
constructor(room, data) {
this.room = room;
this.data = data || { pairs: {}, ignore: [] };
_AutoResponder.migrateStats(this.data, this);
}
static migrateStats(data, responder) {
if (!data.stats)
return data;
for (const date in data.stats) {
for (const entry of data.stats[date].matches) {
void this.logMessage(responder.room.roomid, { ...entry, date });
}
}
delete data.stats;
responder.data = data;
responder.writeState();
return data;
}
static logMessage(roomid, entry) {
return this.logStream.writeLine(JSON.stringify({
...entry,
room: roomid,
regex: entry.regex.toString()
}));
}
find(question, user) {
question = question.slice(0, 300);
const room = this.room;
const helpFaqs = import_room_faqs.roomFaqs[room.roomid];
if (!helpFaqs)
return null;
const normalized = Chat.normalize(question);
if (this.data.ignore) {
if (this.data.ignore.some((t) => new RegExp(t, "i").test(normalized))) {
return null;
}
}
const faqs = Object.keys(helpFaqs).filter((item) => !helpFaqs[item].alias);
for (const faq of faqs) {
const match = this.test(normalized, faq);
if (match) {
if (user) {
const timestamp = Chat.toTimestamp(new Date()).split(" ")[1];
const log = `${timestamp} |c| ${user.name}|${question}`;
this.log(log, faq, match.regex);
}
return helpFaqs[match.faq];
}
}
return null;
}
visualize(question, hideButton, user) {
const response = this.find(question, user);
if (response) {
let buf = "";
buf += import_lib.Utils.html`<strong>You said:</strong> ${question}<br />`;
buf += `<strong>Our automated reply:</strong> ${Chat.collapseLineBreaksHTML((0, import_room_faqs.visualizeFaq)(response))}`;
if (!hideButton) {
buf += import_lib.Utils.html`<hr /><button class="button" name="send" value="A: ${question}">`;
buf += `Send to ${this.room.title} if you weren't answered correctly. </button>`;
}
return buf;
}
return null;
}
getFaqID(faq) {
if (!faq)
throw new Chat.ErrorMessage(`Your input must be in the format [input] => [faq].`);
faq = faq.trim();
if (!faq)
throw new Chat.ErrorMessage(`Your FAQ ID can't be empty.`);
const room = this.room;
const entry = import_room_faqs.roomFaqs[room.roomid][faq];
if (!entry)
throw new Chat.ErrorMessage(`FAQ ID "${faq}" not found.`);
if (!entry.alias)
return faq;
return entry.source;
}
async getStatsFor(date) {
const stream = (0, import_lib.FS)(LOG_PATH).createReadStream();
const buf = [];
for await (const raw of stream.byLine()) {
try {
const data = JSON.parse(raw);
if (data.date !== date || data.room !== this.room.roomid)
continue;
buf.push(data);
} catch {
}
}
return buf;
}
async listDays() {
const stream = (0, import_lib.FS)(LOG_PATH).createReadStream();
const buf = new import_lib.Utils.Multiset();
for await (const raw of stream.byLine()) {
try {
const data = JSON.parse(raw);
if (!data.date || data.room !== this.room.roomid)
continue;
buf.add(data.date);
} catch {
}
}
return buf;
}
/**
* Checks if the FAQ exists. If not, deletes all references to it.
*/
updateFaqData(faq) {
if (Config.nofswriting)
return true;
const room = this.room;
if (!room)
return;
if (import_room_faqs.roomFaqs[room.roomid][faq])
return true;
if (this.data.pairs[faq])
delete this.data.pairs[faq];
return false;
}
stringRegex(str, raw) {
[str] = import_lib.Utils.splitFirst(str, "=>");
const args = str.split(",").map((item) => item.trim());
if (!raw && args.length > 10) {
throw new Chat.ErrorMessage(`Too many arguments.`);
}
if (str.length > 300 && !raw)
throw new Chat.ErrorMessage("Your given string is too long.");
return args.map((item) => {
const split = item.split("&").map((string) => {
if (raw)
return string;
return string.replace(/[\\^$.*+?()[\]{}]/g, "\\$&").trim();
});
return split.map((term) => {
if (term.length > 100 && !raw) {
throw new Chat.ErrorMessage(`One or more of your arguments is too long. Use less than 100 characters.`);
}
if (item.startsWith("|") || item.endsWith("|")) {
throw new Chat.ErrorMessage(`Invalid use of |. Make sure you have an option on either side.`);
}
if (term.startsWith("!")) {
return `^(?!.*${term.slice(1)})`;
}
if (!term.trim())
return null;
return `(?=.*?(${term.trim()}))`;
}).filter(Boolean).join("");
}).filter(Boolean).join("");
}
test(question, faq) {
if (!this.data.pairs[faq])
this.data.pairs[faq] = [];
const regexes = this.data.pairs[faq].map((item) => new RegExp(item, "i"));
if (!regexes.length)
return;
for (const regex of regexes) {
if (regex.test(question))
return { faq, regex: regex.toString() };
}
return null;
}
log(entry, faq, expression) {
const [day] = import_lib.Utils.splitFirst(Chat.toTimestamp(new Date()), " ");
void _AutoResponder.logMessage(this.room.roomid, {
message: entry,
faqName: faq,
regex: expression,
date: day
});
}
writeState() {
for (const faq in this.data.pairs) {
this.updateFaqData(faq);
}
answererData[this.room.roomid] = this.data;
return (0, import_lib.FS)(DATA_PATH).writeUpdate(() => JSON.stringify(answererData));
}
tryAddRegex(inputString, raw) {
let [args, faq] = inputString.split("=>").map((item) => item.trim());
faq = this.getFaqID(toID(faq));
if (!this.data.pairs)
this.data.pairs = {};
if (!this.data.pairs[faq])
this.data.pairs[faq] = [];
const regex = raw ? args.trim() : this.stringRegex(args, raw);
if (this.data.pairs[faq].includes(regex)) {
throw new Chat.ErrorMessage(`That regex is already stored.`);
}
Chat.validateRegex(regex);
this.data.pairs[faq].push(regex);
return this.writeState();
}
tryRemoveRegex(faq, index) {
faq = this.getFaqID(faq);
if (!this.data.pairs)
this.data.pairs = {};
if (!this.data.pairs[faq])
throw new Chat.ErrorMessage(`There are no regexes for ${faq}.`);
if (!this.data.pairs[faq][index])
throw new Chat.ErrorMessage("Your provided index is invalid.");
this.data.pairs[faq].splice(index, 1);
this.writeState();
return true;
}
static canOverride(user, room) {
const devAuth = Rooms.get("development")?.auth;
return devAuth?.atLeast(user, "%") && devAuth?.has(user.id) && room.auth.atLeast(user, "@") || user.can("rangeban");
}
destroy() {
this.writeState();
this.room.responder = null;
this.room = null;
}
ignore(terms, context) {
const filtered = terms.map((t) => context.filter(t)).filter(Boolean);
if (filtered.length !== terms.length) {
throw new Chat.ErrorMessage(`Invalid terms.`);
}
if (terms.some((t) => t.length > 300)) {
throw new Chat.ErrorMessage(`One of your terms is too long.`);
}
if (!this.data.ignore)
this.data.ignore = [];
this.data.ignore.push(...terms);
this.writeState();
return terms;
}
unignore(terms) {
if (!this.data.ignore) {
throw new Chat.ErrorMessage(`The autoresponse filter in this room has no ignored terms.`);
}
this.data.ignore = this.data.ignore.filter((item) => !terms.includes(item));
this.writeState();
return true;
}
};
let AutoResponder = _AutoResponder;
AutoResponder.logStream = (0, import_lib.FS)(LOG_PATH).createAppendStream();
for (const room of Rooms.rooms.values()) {
room.responder?.destroy();
if (answererData[room.roomid]) {
room.responder = new AutoResponder(room, answererData[room.roomid]);
}
}
const BYPASS_TERMS = ["a:", "A:", "!", "/"];
const chatfilter = function(message, user, room) {
if (BYPASS_TERMS.some((t) => message.startsWith(t))) {
return;
}
if (room?.responder && room.auth.get(user.id) === " ") {
const responder = room.responder;
const reply = responder.visualize(message, false, user);
if (!reply) {
return message;
} else {
this.sendReply(`|uhtml|askhelp-${user}-${toID(message)}|<div class="infobox">${reply}</div>`);
const trimmedMessage = `<div class="infobox">${responder.visualize(message, true)}</div>`;
setTimeout(() => {
this.sendReply(`|uhtmlchange|askhelp-${user}-${toID(message)}|${trimmedMessage}`);
}, 10 * 1e3);
return false;
}
}
};
const commands = {
question(target, room, user) {
room = this.requireRoom();
const responder = room.responder;
if (!responder)
return this.errorReply(`This room does not have an autoresponder configured.`);
if (!target)
return this.parse("/help question");
const reply = responder.visualize(target, true);
if (!reply)
return this.sendReplyBox(`No answer found.`);
this.runBroadcast();
this.sendReplyBox(reply);
},
questionhelp: ["/question [question] - Asks the current room's auto-response filter a question."],
ar: "autoresponder",
autoresponder: {
""(target, room) {
room = this.requireRoom();
const responder = room.responder;
if (!responder) {
return this.errorReply(`This room has not configured an autoresponder.`);
}
if (!target) {
return this.parse("/help autoresponder");
}
return this.parse(`/j view-autoresponder-${room.roomid}-${target}`);
},
view(target, room, user) {
room = this.requireRoom();
return this.parse(`/join view-autoresponder-${room.roomid}-${target}`);
},
toggle(target, room, user) {
room = this.requireRoom();
if (!target) {
return this.sendReply(
`The Help auto-response filter is currently set to: ${room.responder ? "ON" : "OFF"}`
);
}
this.checkCan("ban", null, room);
if (room.settings.isPrivate === true) {
return this.errorReply(`Secret rooms cannot enable an autoresponder.`);
}
if (this.meansYes(target)) {
if (room.responder)
return this.errorReply(`The Autoresponder for this room is already enabled.`);
room.responder = new AutoResponder(room, answererData[room.roomid]);
room.responder.writeState();
}
if (this.meansNo(target)) {
if (!room.responder)
return this.errorReply(`The Autoresponder for this room is already disabled.`);
room.responder.destroy();
}
this.privateModAction(`${user.name} ${!room.responder ? "disabled" : "enabled"} the auto-response filter.`);
this.modlog(`AUTOFILTER`, null, !room.responder ? "OFF" : "ON");
},
forceadd: "add",
add(target, room, user, connection, cmd) {
room = this.requireRoom();
if (!room.responder) {
return this.errorReply(`This room has not configured an auto-response filter.`);
}
const force = cmd === "forceadd";
if (force && !AutoResponder.canOverride(user, room)) {
return this.errorReply(`You cannot use raw regex - use /autoresponder add instead.`);
}
this.checkCan("ban", null, room);
room.responder.tryAddRegex(target, force);
this.privateModAction(`${user.name} added regex for "${target.split("=>")[0]}" to the autoresponder.`);
this.modlog(`AUTOFILTER ADD`, null, target);
},
remove(target, room, user) {
const [faq, index] = target.split(",");
room = this.requireRoom();
if (!room.responder) {
return this.errorReply(`${room.title} has not configured an auto-response filter.`);
}
this.checkCan("ban", null, room);
const num = parseInt(index);
if (isNaN(num))
return this.errorReply("Invalid index.");
room.responder.tryRemoveRegex(faq, num - 1);
this.privateModAction(`${user.name} removed regex ${num} from the usable regexes for ${faq}.`);
this.modlog("AUTOFILTER REMOVE", null, index);
const pages2 = [`keys`, `pairs`];
for (const p of pages2) {
this.refreshPage(`autofilter-${room.roomid}-${p}`);
}
},
ignore(target, room, user) {
room = this.requireRoom();
if (!room.responder) {
return this.errorReply(`This room has not configured an auto-response filter.`);
}
this.checkCan("ban", null, room);
if (!toID(target)) {
return this.parse(`/help autoresponder`);
}
const targets = target.split(",");
room.responder.ignore(targets, this);
this.privateModAction(
`${user.name} added ${Chat.count(targets.length, "terms")} to the autoresponder ignore list.`
);
this.modlog(`AUTOFILTER IGNORE`, null, target);
},
unignore(target, room, user) {
room = this.requireRoom();
if (!room.responder) {
return this.errorReply(`${room.title} has not configured an auto-response filter.`);
}
this.checkCan("ban", null, room);
if (!toID(target)) {
return this.parse(`/help autoresponder`);
}
const targets = target.split(",");
room.responder.unignore(targets);
this.privateModAction(`${user.name} removed ${Chat.count(targets.length, "terms")} from the autoresponder ignore list.`);
this.modlog(`AUTOFILTER UNIGNORE`, null, target);
if (this.connection.openPages?.has(`autoresponder-${room.roomid}-ignore`)) {
return this.parse(`/join view-autoresponder-${room.roomid}-ignore`);
}
}
},
autoresponderhelp() {
const help = [
`<code>/autoresponder view [page]</code> - Views the Autoresponder page [page]. (options: keys, stats)`,
`<code>/autoresponder toggle [on | off]</code> - Enables or disables the Autoresponder for the current room. Requires: @ # &`,
`<code>/autoresponder add [input] => [faq]</code> - Adds regex made from the input string to the current room's Autoresponder, to respond with [faq] to matches.`,
`<code>/autoresponder remove [faq], [regex index]</code> - removes the regex matching the [index] from the current room's responses for [faq].`,
`Indexes can be found in /autoresponder keys.`,
`Requires: @ # &`
];
return this.sendReplyBox(help.join("<br/ >"));
}
};
const pages = {
async autoresponder(args, user) {
const room = this.requireRoom();
if (!room.responder) {
return this.errorReply(`${room.title} does not have a configured autoresponder.`);
}
args.shift();
const roomData = answererData[room.roomid];
const canChange = user.can("ban", null, room);
let buf = "";
const refresh = (type, extra) => {
if (extra)
extra = extra.filter(Boolean);
let button = `<button class="button" name="send" value="/join view-autoresponder-${room.roomid}-${type}`;
button += `${extra?.length ? `-${extra.join("-")}` : ""}" style="float: right">`;
button += `<i class="fa fa-refresh"></i> Refresh</button><br />`;
return button;
};
const back = `<br /><a roomid="view-autoresponder-${room.roomid}">Back to all</a>`;
switch (args[0]) {
case "stats":
args.shift();
this.checkCan("mute", null, room);
const date = args.join("-") || "";
if (!!date && isNaN(new Date(date).getTime())) {
return `<h2>Invalid date.</h2>`;
}
buf = `<div class="pad"><strong>Stats for the ${room.title} auto-response filter${date ? ` on ${date}` : ""}.</strong>`;
buf += `${back}${refresh("stats", [date])}<hr />`;
if (date) {
const stats = await room.responder.getStatsFor(date);
if (!stats)
return `<h2>No stats.</h2>`;
this.title = `[Autoresponder Stats] ${date ? date : ""}`;
if (!stats.length)
return `<h2>No stats for ${date}.</h2>`;
buf += `<strong>Total messages answered: ${stats.length}</strong><hr />`;
buf += `<details><summary>All messages and the corresponding answers (FAQs):</summary>`;
for (const entry of stats) {
buf += `<small>Message:</small>${import_chatlog.LogViewer.renderLine(entry.message)}`;
buf += `<small>FAQ: ${entry.faqName}</small><br />`;
buf += `<small>Regex: <code>${entry.regex}</code></small> <hr />`;
}
return import_chatlog.LogViewer.linkify(buf);
}
buf += `<strong> No date specified.<br />`;
const days = [];
let totalCount = 0;
const dayKeys = await room.responder.listDays();
for (const [dateKey, total] of dayKeys) {
totalCount += total;
days.push(`- <a roomid="view-autoresponder-${room.roomid}-stats-${dateKey}">${dateKey}</a> (${total})`);
}
buf += `Dates with stats:</strong><small>(total matches: ${totalCount})</small><br /><br />`;
buf += days.join("<br />");
break;
case "pairs":
case "keys":
this.title = "[Autoresponder Regexes]";
this.checkCan("show", null, room);
buf = `<div class="pad"><h2>${room.title} responder regexes and responses:</h2>${back}${refresh("keys")}<hr />`;
buf += Object.entries(roomData.pairs).map(([item, regexes]) => {
if (regexes.length < 1)
return null;
let buffer = `<details><summary>${item}</summary>`;
buffer += `<div class="ladder pad"><table><tr><th>Index</th><th>Regex</th>`;
if (canChange)
buffer += `<th>Options</th>`;
buffer += `</tr>`;
for (const regex of regexes) {
const index = regexes.indexOf(regex) + 1;
const button = `<button class="button" name="send"value="/msgroom ${room.roomid},/ar remove ${item}, ${index}">Remove</button>`;
buffer += `<tr><td>${index}</td><td><code>${regex}</code></td>`;
if (canChange)
buffer += `<td>${button}</td></tr>`;
}
buffer += `</details>`;
return buffer;
}).filter(Boolean).join("<hr />");
break;
case "ignore":
this.title = `[${room.title} Autoresponder ignore list]`;
buf = `<div class="pad"><h2>${room.title} responder terms to ignore:</h2>${back}${refresh("ignore")}<hr />`;
if (!roomData.ignore) {
return this.errorReply(`No terms on ignore list.`);
}
for (const term of roomData.ignore) {
buf += `- ${term} <button class="button" name="send"value="/msgroom ${room.roomid},/ar unignore ${term}">Remove</button><br />`;
}
buf += `</div>`;
break;
default:
this.title = `[${room.title} Autoresponder]`;
buf = `<div class="pad"><h2>Specify a filter page to view.</h2>`;
buf += `<hr /><strong>Options:</strong><hr />`;
buf += `<a roomid="view-autoresponder-${room.roomid}-stats">Stats</a><hr />`;
buf += `<a roomid="view-autoresponder-${room.roomid}-keys">Regex keys</a><hr/>`;
buf += `<a roomid="view-autoresponder-${room.roomid}-ignore">Ignore list</a><hr/>`;
buf += `</div>`;
}
return import_chatlog.LogViewer.linkify(buf);
}
};
const handlers = {
onRenameRoom(oldID, newID) {
if (answererData[oldID]) {
if (!answererData[newID])
answererData[newID] = { pairs: {} };
Object.assign(answererData[newID], answererData[oldID]);
delete answererData[oldID];
(0, import_lib.FS)(DATA_PATH).writeUpdate(() => JSON.stringify(answererData));
}
}
};
//# sourceMappingURL=responder.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/responder.ts"],
"sourcesContent": ["/**\r\n * PS Help room auto-response plugin.\r\n * Uses Regex to match room frequently asked question (RFAQ) entries,\r\n * and replies if a match is found.\r\n * Supports configuration, and works in all rooms, though intended mainly for Help.\r\n * Written by Mia.\r\n * @author mia-pi-git\r\n */\r\n\r\nimport {FS, Utils} from '../../lib';\r\nimport {LogViewer} from './chatlog';\r\nimport {roomFaqs, visualizeFaq} from './room-faqs';\r\n\r\nconst DATA_PATH = 'config/chat-plugins/responder.json';\r\nconst LOG_PATH = 'logs/responder.jsonl';\r\n\r\nexport let answererData: {[roomid: string]: PluginData} = {};\r\n\r\ntry {\r\n\tanswererData = JSON.parse(FS(DATA_PATH).readSync());\r\n} catch {}\r\n\r\n/**\r\n * A message caught by the filter.\r\n */\r\ninterface LoggedMessage {\r\n\t/** Message that's matched by the filter. */\r\n\tmessage: string;\r\n\t/** The FAQ that it's matched to. */\r\n\tfaqName: string;\r\n\t/** The regex that it's matched to. */\r\n\tregex: string;\r\n\tdate: string;\r\n}\r\ninterface PluginData {\r\n\t/** Word pairs that have been marked as a match for a specific FAQ. */\r\n\tpairs: {[k: string]: string[]};\r\n\t/** Common terms to be ignored in question parsing. */\r\n\tignore?: string[];\r\n}\r\n\r\nexport class AutoResponder {\r\n\tdata: PluginData;\r\n\troom: Room;\r\n\tconstructor(room: Room, data?: PluginData) {\r\n\t\tthis.room = room;\r\n\t\tthis.data = data || {pairs: {}, ignore: []};\r\n\t\tAutoResponder.migrateStats(this.data, this);\r\n\t}\r\n\tstatic migrateStats(data: any, responder: AutoResponder) {\r\n\t\tif (!data.stats) return data;\r\n\t\tfor (const date in data.stats) {\r\n\t\t\tfor (const entry of data.stats[date].matches) {\r\n\t\t\t\tvoid this.logMessage(responder.room.roomid, {...entry, date});\r\n\t\t\t}\r\n\t\t}\r\n\t\tdelete data.stats;\r\n\t\tresponder.data = data;\r\n\t\tresponder.writeState();\r\n\t\treturn data;\r\n\t}\r\n\tstatic logStream = FS(LOG_PATH).createAppendStream();\r\n\tstatic logMessage(roomid: RoomID, entry: LoggedMessage) {\r\n\t\treturn this.logStream.writeLine(JSON.stringify({\r\n\t\t\t...entry,\r\n\t\t\troom: roomid,\r\n\t\t\tregex: entry.regex.toString(),\r\n\t\t}));\r\n\t}\r\n\tfind(question: string, user?: User) {\r\n\t\t// sanity slice, APPARENTLY people are dumb.\r\n\t\tquestion = question.slice(0, 300);\r\n\t\tconst room = this.room;\r\n\t\tconst helpFaqs = roomFaqs[room.roomid];\r\n\t\tif (!helpFaqs) return null;\r\n\t\tconst normalized = Chat.normalize(question);\r\n\t\tif (this.data.ignore) {\r\n\t\t\tif (this.data.ignore.some(t => new RegExp(t, \"i\").test(normalized))) {\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}\r\n\t\tconst faqs = Object.keys(helpFaqs).filter(item => !helpFaqs[item].alias);\r\n\t\tfor (const faq of faqs) {\r\n\t\t\tconst match = this.test(normalized, faq);\r\n\t\t\tif (match) {\r\n\t\t\t\tif (user) {\r\n\t\t\t\t\tconst timestamp = Chat.toTimestamp(new Date()).split(' ')[1];\r\n\t\t\t\t\tconst log = `${timestamp} |c| ${user.name}|${question}`;\r\n\t\t\t\t\tthis.log(log, faq, match.regex);\r\n\t\t\t\t}\r\n\t\t\t\treturn helpFaqs[match.faq];\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\tvisualize(question: string, hideButton?: boolean, user?: User) {\r\n\t\tconst response = this.find(question, user);\r\n\t\tif (response) {\r\n\t\t\tlet buf = '';\r\n\t\t\tbuf += Utils.html`<strong>You said:</strong> ${question}<br />`;\r\n\t\t\tbuf += `<strong>Our automated reply:</strong> ${Chat.collapseLineBreaksHTML(visualizeFaq(response))}`;\r\n\t\t\tif (!hideButton) {\r\n\t\t\t\tbuf += Utils.html`<hr /><button class=\"button\" name=\"send\" value=\"A: ${question}\">`;\r\n\t\t\t\tbuf += `Send to ${this.room.title} if you weren't answered correctly. </button>`;\r\n\t\t\t}\r\n\t\t\treturn buf;\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\tgetFaqID(faq?: string) {\r\n\t\tif (!faq) throw new Chat.ErrorMessage(`Your input must be in the format [input] => [faq].`);\r\n\t\tfaq = faq.trim();\r\n\t\tif (!faq) throw new Chat.ErrorMessage(`Your FAQ ID can't be empty.`);\r\n\t\tconst room = this.room;\r\n\t\tconst entry = roomFaqs[room.roomid][faq];\r\n\t\tif (!entry) throw new Chat.ErrorMessage(`FAQ ID \"${faq}\" not found.`);\r\n\r\n\t\tif (!entry.alias) return faq; // not an alias\r\n\t\treturn entry.source;\r\n\t}\r\n\tasync getStatsFor(date: string) {\r\n\t\tconst stream = FS(LOG_PATH).createReadStream();\r\n\t\tconst buf: LoggedMessage[] = [];\r\n\t\tfor await (const raw of stream.byLine()) {\r\n\t\t\ttry {\r\n\t\t\t\tconst data = JSON.parse(raw);\r\n\t\t\t\tif (data.date !== date || data.room !== this.room.roomid) continue;\r\n\t\t\t\tbuf.push(data);\r\n\t\t\t} catch {}\r\n\t\t}\r\n\t\treturn buf;\r\n\t}\r\n\r\n\tasync listDays() {\r\n\t\tconst stream = FS(LOG_PATH).createReadStream();\r\n\t\tconst buf = new Utils.Multiset<string>();\r\n\t\tfor await (const raw of stream.byLine()) {\r\n\t\t\ttry {\r\n\t\t\t\tconst data = JSON.parse(raw);\r\n\t\t\t\tif (!data.date || data.room !== this.room.roomid) continueLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;A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G;AAC9D,SAAK,eAAc,WAAW,KAAK,KAAK,QAAQ;AAAA,MAC/C,SAAS;AAAA,MACT,SAAS;AAAA,MACT,OAAO;AAAA,MACP,MAAM;AAAA,IACP,CAAC;AAAA,EACF;AAAA,EACA,aAAa;AACZ,eAAW,OAAO,KAAK,KAAK,OAAO;AAGlC,WAAK,cAAc,GAAG;AAAA,IACvB;AACA,iBAAa,KAAK,KAAK,MAAM,IAAI,KAAK;AACtC,eAAO,eAAG,SAAS,EAAE,YAAY,MAAM,KAAK,UAAU,YAAY,CAAC;AAAA,EACpE;AAAA,EACA,YAAY,aAAqB,KAAe;AAC/C,QAAI,CAAC,MAAM,GAAG,IAAI,YAAY,MAAM,IAAI,EAAE,IAAI,UAAQ,KAAK,KAAK,CAAC;AACjE,UAAM,KAAK,SAAS,KAAK,GAAG,CAAC;AAC7B,QAAI,CAAC,KAAK,KAAK;AAAO,WAAK,KAAK,QAAQ,CAAC;AACzC,QAAI,CAAC,KAAK,KAAK,MAAM,GAAG;AAAG,WAAK,KAAK,MAAM,GAAG,IAAI,CAAC;AACnD,UAAM,QAAQ,MAAM,KAAK,KAAK,IAAI,KAAK,YAAY,MAAM,GAAG;AAC5D,QAAI,KAAK,KAAK,MAAM,GAAG,EAAE,SAAS,KAAK,GAAG;AACzC,YAAM,IAAI,KAAK,aAAa,+BAA+B;AAAA,IAC5D;AACA,SAAK,cAAc,KAAK;AACxB,SAAK,KAAK,MAAM,GAAG,EAAE,KAAK,KAAK;AACLine truncated
"names": ["pages"]
}
@@ -0,0 +1,378 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var rock_paper_scissors_exports = {};
__export(rock_paper_scissors_exports, {
RPSGame: () => RPSGame,
RPSPlayer: () => RPSPlayer,
commands: () => commands
});
module.exports = __toCommonJS(rock_paper_scissors_exports);
const MAX_ROUNDS = 200;
const TIMEOUT = 10 * 1e3;
const ICONS = {
Rock: /* @__PURE__ */ Chat.h("i", { class: "fa fa-hand-rock-o" }),
Paper: /* @__PURE__ */ Chat.h("i", { class: "fa fa-hand-paper-o" }),
Scissors: /* @__PURE__ */ Chat.h("i", { class: "fa fa-hand-scissors-o" })
};
const MATCHUPS = /* @__PURE__ */ new Map([
["Scissors", "Paper"],
["Rock", "Scissors"],
["Paper", "Rock"]
]);
function toChoice(str) {
const id = toID(str);
return id.charAt(0).toUpperCase() + id.slice(1);
}
class RPSPlayer extends Rooms.RoomGamePlayer {
constructor() {
super(...arguments);
this.choice = "";
this.prevChoice = "";
this.prevWinner = false;
this.score = 0;
}
sendControls(jsx) {
this.sendRoom(Chat.html`|controlshtml|${jsx}`);
}
}
class RPSGame extends Rooms.RoomGame {
constructor(room) {
super(room);
this.checkChat = true;
this.roundTimer = null;
this.currentRound = 0;
this.title = "Rock Paper Scissors";
this.gameid = "rockpaperscissors";
this.room.update();
this.controls(/* @__PURE__ */ Chat.h("div", { style: { textAlign: "center" } }, "Waiting for another player to join...."));
this.sendField();
}
controls(node) {
this.room.send(Chat.html`|controlshtml|${node}`);
}
onConnect(user, connection) {
this.room.sendUser(connection, Chat.html`|fieldhtml|${this.getField()}`);
}
static getWinner(p1, p2) {
const p1Choice = p1.choice;
const p2Choice = p2.choice;
if (!p1Choice && p2Choice)
return p2;
if (!p2Choice && p1Choice)
return p1;
if (MATCHUPS.get(p1Choice) === p2Choice)
return p1;
if (MATCHUPS.get(p2Choice) === p1Choice)
return p2;
return null;
}
sendControls(player) {
if (!this.roundTimer) {
return player.sendControls(/* @__PURE__ */ Chat.h("div", { style: { textAlign: "center" } }, "The game is paused.", /* @__PURE__ */ Chat.h("br", null), /* @__PURE__ */ Chat.h("br", null), /* @__PURE__ */ Chat.h("button", { class: "button", name: "send", value: "/rps resume" }, "Resume game")));
}
if (player.choice) {
player.sendControls(
/* @__PURE__ */ Chat.h("div", { style: { textAlign: "center" } }, "You have selected ", /* @__PURE__ */ Chat.h("strong", null, player.choice), ". Now to wait for your foe.")
);
return;
}
player.sendControls(/* @__PURE__ */ Chat.h("div", { style: { textAlign: "center" } }, /* @__PURE__ */ Chat.h("strong", null, "Make your choice, quick! You have ", Chat.toDurationString(TIMEOUT), "!"), /* @__PURE__ */ Chat.h("br", null), ["Rock", "Paper", "Scissors"].map((choice) => /* @__PURE__ */ Chat.h("button", { class: "button", name: "send", value: `/choose ${choice}`, style: { width: "6em" } }, /* @__PURE__ */ Chat.h("span", { style: { fontSize: "24px" } }, ICONS[choice]), /* @__PURE__ */ Chat.h("br", null), choice || "\xA0")), /* @__PURE__ */ Chat.h("br", null), /* @__PURE__ */ Chat.h("br", null), /* @__PURE__ */ Chat.h("button", { class: "button", name: "send", value: "/rps end" }, "End game"), /* @__PURE__ */ Chat.h("br", null), /* @__PURE__ */ Chat.h("button", { class: "button", name: "send", value: "/rps pause" }, "Pause game")));
}
getField() {
if (this.players.length < 2) {
return /* @__PURE__ */ Chat.h("div", { style: { textAlign: "center" } }, /* @__PURE__ */ Chat.h("h2", null, "Waiting to start the game..."));
}
const [p1, p2] = this.players;
function renderBigChoice(choice, isWinner) {
return /* @__PURE__ */ Chat.h("div", { style: {
width: "180px",
fontSize: "120px",
background: isWinner ? "#595" : "#888",
color: "white",
borderRadius: "20px",
paddingBottom: "5px",
margin: "0 auto"
} }, ICONS[choice] || "\xA0", /* @__PURE__ */ Chat.h("br", null), /* @__PURE__ */ Chat.h("small", { style: { fontSize: "40px" } }, /* @__PURE__ */ Chat.h("small", { style: { fontSize: "32px", display: "block" } }, choice || "\xA0")));
}
function renderCurrentChoice(exists) {
return /* @__PURE__ */ Chat.h("div", { style: {
width: "100px",
fontSize: "60px",
background: "#888",
color: "white",
borderRadius: "15px",
paddingBottom: "5px",
margin: "20px auto 0"
} }, exists ? /* @__PURE__ */ Chat.h("i", { class: "fa fa-check" }) : "\xA0");
}
return /* @__PURE__ */ Chat.h("table", { style: { width: "100%", textAlign: "center", fontSize: "18px" } }, /* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("td", null, /* @__PURE__ */ Chat.h("div", { style: { padding: "8px 0" } }, /* @__PURE__ */ Chat.h("strong", null, p1.name), " (", p1.score, ")"), renderBigChoice(p1.prevChoice, p1.prevWinner), renderCurrentChoice(!!p1.choice)), /* @__PURE__ */ Chat.h("td", null, /* @__PURE__ */ Chat.h("em", { style: { fontSize: "24px" } }, "vs")), /* @__PURE__ */ Chat.h("td", null, /* @__PURE__ */ Chat.h("div", { style: { padding: "8px 0" } }, /* @__PURE__ */ Chat.h("strong", null, p2.name), " (", p2.score, ")"), renderBigChoice(p2.prevChoice, p2.prevWinner), renderCurrentChoice(!!p2.choice))));
}
sendField() {
this.room.send(Chat.html`|fieldhtml|${this.getField()}`);
}
end() {
const [p1, p2] = this.players;
if (p1.score === p2.score) {
this.message(`**Tie** at score ${p1.score}!`);
} else {
const [winner, loser] = p1.score > p2.score ? [p1, p2] : [p2, p1];
this.message(`**${winner.name}** wins with score ${winner.score} to ${loser.score}!`);
}
if (this.roundTimer) {
clearTimeout(this.roundTimer);
this.roundTimer = null;
}
this.room.pokeExpireTimer();
this.ended = true;
this.room.add(`|-message|The game has ended.`);
for (const player of this.players) {
player.sendControls(/* @__PURE__ */ Chat.h("div", { class: "pad" }, "The game has ended."));
player.unlinkUser();
}
}
runMatch() {
const [p1, p2] = this.players;
const winner = RPSGame.getWinner(p1, p2);
if (!winner) {
if (!p1.choice) {
this.message(`${p1.name} and ${p2.name} both **timed out**.`);
} else {
this.message(`${p1.name} and ${p2.name} **tie** with ${p1.choice}.`);
}
} else {
const loser = p1 === winner ? p2 : p1;
if (!loser.choice) {
this.message(`**${winner.name}**'s ${winner.choice} wins; ${loser.name} timed out.`);
} else {
this.message(`**${winner.name}**'s ${winner.choice} beats ${loser.name}'s ${loser.choice}.`);
}
winner.score++;
}
if (!winner && !p1.choice) {
this.pause();
return;
}
if (this.currentRound >= MAX_ROUNDS) {
this.message(`The game is ending automatically at ${this.currentRound} rounds.`);
return this.end();
}
for (const player of this.players) {
player.prevChoice = player.choice;
player.prevWinner = false;
player.choice = "";
}
if (winner)
winner.prevWinner = true;
this.sendField();
this.nextRound();
}
smallMessage(message) {
this.room.add(`|-message|${message}`).update();
}
message(message) {
this.room.add(`|message|${message}`).update();
}
start() {
if (this.players.length < 2) {
throw new Chat.ErrorMessage(`There are not enough players to start. Use /rps start to start when all players are ready.`);
}
if (this.room.log.log.length > 1e3) {
this.room.log.log = [];
}
const [p1, p2] = this.players;
this.room.add(
`|raw|<h2><span style="font-weight: normal">Rock Paper Scissors:</span> ${p1.name} vs ${p2.name}!</h2>
|message|Game started!
|notify|Game started!`
).update();
this.nextRound();
}
getPlayer(user) {
const player = this.playerTable[user.id];
if (!player)
throw new Chat.ErrorMessage(`You are not a player in this game.`);
return player;
}
pause(user) {
if (!this.roundTimer)
throw new Chat.ErrorMessage(`The game is not running, and cannot be paused.`);
const player = user ? this.getPlayer(user) : null;
clearTimeout(this.roundTimer);
this.roundTimer = null;
for (const curPlayer of this.players)
this.sendControls(curPlayer);
if (player)
this.message(`The game was paused by ${player.name}.`);
}
unpause(user) {
if (this.roundTimer)
throw new Chat.ErrorMessage(`The game is not paused.`);
const player = this.getPlayer(user);
this.message(`The game was resumed by ${player.name}.`);
this.nextRound();
}
nextRound() {
this.currentRound++;
this.sendField();
this.room.add(`|html|<h2>Round ${this.currentRound}</h2>`).update();
this.roundTimer = setTimeout(() => {
this.runMatch();
}, TIMEOUT);
for (const player of this.players)
this.sendControls(player);
}
choose(user, option) {
option = toChoice(option);
const player = this.getPlayer(user);
if (!MATCHUPS.get(option)) {
throw new Chat.ErrorMessage(`Invalid choice: ${option}.`);
}
if (player.choice)
throw new Chat.ErrorMessage("You have already made your choice!");
player.choice = option;
this.smallMessage(`${user.name} made a choice.`);
this.sendControls(player);
if (this.players.filter((item) => item.choice).length > 1) {
clearTimeout(this.roundTimer);
this.roundTimer = null;
return this.runMatch();
}
this.sendField();
return true;
}
leaveGame(user) {
const player = this.getPlayer(user);
player.sendRoom(`You left the game.`);
delete this.playerTable[user.id];
this.end();
}
addPlayer(user) {
if (this.playerTable[user.id])
throw new Chat.ErrorMessage(`You are already a player in this game.`);
this.playerTable[user.id] = this.makePlayer(user);
this.players.push(this.playerTable[user.id]);
this.room.auth.set(user.id, Users.PLAYER_SYMBOL);
return this.playerTable[user.id];
}
makePlayer(user) {
return new RPSPlayer(user, this);
}
}
function findExisting(user1, user2) {
return Rooms.get(`game-rps-${user1}-${user2}`) || Rooms.get(`game-rps-${user2}-${user1}`);
}
const commands = {
rps: "rockpaperscissors",
rockpaperscissors: {
challenge: "create",
chall: "create",
chal: "create",
create(target, room, user) {
target = target.trim();
if (!target && this.pmTarget) {
target = this.pmTarget.id;
}
const { targetUser, targetUsername } = this.splitUser(target);
if (!targetUser) {
return this.errorReply(`User ${targetUsername} not found. Either specify a username or use this command in PMs.`);
}
if (targetUser === user)
return this.errorReply(`You cannot challenge yourself.`);
if (targetUser.settings.blockChallenges && !user.can("bypassblocks", targetUser)) {
Chat.maybeNotifyBlocked("challenge", targetUser, user);
return this.errorReply(this.tr`The user '${targetUser.name}' is not accepting challenges right now.`);
}
const existingRoom = findExisting(user.id, targetUser.id);
if (existingRoom?.game && !existingRoom.game.ended) {
return this.errorReply(`You're already playing a Rock Paper Scissors game against ${targetUser.name}!`);
}
Ladders.challenges.add(
new Ladders.GameChallenge(user.id, targetUser.id, "Rock Paper Scissors", {
acceptCommand: `/rps accept ${user.id}`
})
);
if (!this.pmTarget)
this.pmTarget = targetUser;
this.sendChatMessage(
`/raw ${user.name} wants to play Rock Paper Scissors!`
);
},
accept(target, room, user) {
const fromUser = Ladders.challenges.accept(this);
const existingRoom = findExisting(user.id, fromUser.id);
const roomid = `game-rps-${fromUser.id}-${user.id}`;
const gameRoom = existingRoom || Rooms.createGameRoom(
roomid,
`[RPS] ${user.name} vs ${fromUser.name}`,
{}
);
const game = new RPSGame(gameRoom);
gameRoom.game = game;
game.addPlayer(fromUser);
game.addPlayer(user);
user.joinRoom(gameRoom.roomid);
fromUser.joinRoom(gameRoom.roomid);
gameRoom.game.start();
this.pmTarget = fromUser;
this.sendChatMessage(`/text ${user.name} accepted <<${gameRoom.roomid}>>`);
},
deny: "reject",
reject(target, room, user) {
return this.parse(`/reject ${target}`);
},
end(target, room, user) {
const game = this.requireGame(RPSGame);
if (!game.playerTable[user.id]) {
return this.errorReply(`You are not a player, and so cannot end the game.`);
}
game.end();
},
choose(target, room, user) {
this.parse(`/choose ${target}`);
},
leave(target, room, user) {
this.parse(`/leavegame`);
},
pause(target, room, user) {
const game = this.requireGame(RPSGame);
game.pause(user);
},
unpause: "resume",
resume(target, room, user) {
const game = this.requireGame(RPSGame);
game.unpause(user);
},
"": "help",
help() {
this.runBroadcast();
const strings = [
`/rockpaperscissors OR /rps<br />`,
`/rps challenge [user] - Challenges a user to a game of Rock Paper Scissors`,
`(in PM) /rps challenge - Challenges a user to a game of Rock Paper Scissors`,
`/rps leave - Leave the game.`,
`/rps start - Start the Rock Paper Scissors game.`,
`/rps end - End the Rock Paper Scissors game`,
`/rps pause - Pauses the game, if it's in progress.`,
`/rps resume - Resumes the game, if it's paused.`
];
return this.sendReplyBox(strings.join("<br />"));
}
}
};
//# sourceMappingURL=rock-paper-scissors.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/rock-paper-scissors.tsx"],
"sourcesContent": ["/**\r\n * Rock Paper Scissors plugin by Mia\r\n * @author mia-pi-git\r\n */\r\nconst MAX_ROUNDS = 200;\r\nconst TIMEOUT = 10 * 1000;\r\nconst ICONS: {[k: string]: Chat.VNode} = {\r\n\tRock: <i class=\"fa fa-hand-rock-o\"></i>,\r\n\tPaper: <i class=\"fa fa-hand-paper-o\"></i>,\r\n\tScissors: <i class=\"fa fa-hand-scissors-o\"></i>,\r\n};\r\n\r\nconst MATCHUPS = new Map<string, string>([\r\n\t['Scissors', 'Paper'],\r\n\t['Rock', 'Scissors'],\r\n\t['Paper', 'Rock'],\r\n]);\r\n\r\nfunction toChoice(str: string) {\r\n\tconst id = toID(str);\r\n\treturn id.charAt(0).toUpperCase() + id.slice(1);\r\n}\r\n\r\nexport class RPSPlayer extends Rooms.RoomGamePlayer {\r\n\tchoice = '';\r\n\tprevChoice = '';\r\n\tprevWinner = false;\r\n\tscore = 0;\r\n\tsendControls(jsx: Chat.VNode) {\r\n\t\tthis.sendRoom(Chat.html`|controlshtml|${jsx}`);\r\n\t}\r\n}\r\n\r\nexport class RPSGame extends Rooms.RoomGame<RPSPlayer> {\r\n\tcurrentRound: number;\r\n\treadonly checkChat = true;\r\n\troundTimer: NodeJS.Timeout | null = null;\r\n\tconstructor(room: Room) {\r\n\t\tsuper(room);\r\n\t\tthis.currentRound = 0;\r\n\t\tthis.title = 'Rock Paper Scissors';\r\n\t\tthis.gameid = 'rockpaperscissors' as ID;\r\n\r\n\t\tthis.room.update();\r\n\t\tthis.controls(<div style={{textAlign: 'center'}}>Waiting for another player to join....</div>);\r\n\t\tthis.sendField();\r\n\t}\r\n\tcontrols(node: Chat.VNode) {\r\n\t\tthis.room.send(Chat.html`|controlshtml|${node}`);\r\n\t}\r\n\tonConnect(user: User, connection: Connection) {\r\n\t\tthis.room.sendUser(connection, Chat.html`|fieldhtml|${this.getField()}`);\r\n\t}\r\n\tstatic getWinner(p1: RPSPlayer, p2: RPSPlayer) {\r\n\t\tconst p1Choice = p1.choice;\r\n\t\tconst p2Choice = p2.choice;\r\n\t\tif (!p1Choice && p2Choice) return p2;\r\n\t\tif (!p2Choice && p1Choice) return p1;\r\n\t\tif (MATCHUPS.get(p1Choice) === p2Choice) return p1;\r\n\t\tif (MATCHUPS.get(p2Choice) === p1Choice) return p2;\r\n\t\treturn null;\r\n\t}\r\n\tsendControls(player: RPSPlayer) {\r\n\t\tif (!this.roundTimer) {\r\n\t\t\treturn player.sendControls(<div style={{textAlign: 'center'}}>\r\n\t\t\t\tThe game is paused.<br /><br />\r\n\t\t\t\t<button class=\"button\" name=\"send\" value=\"/rps resume\">Resume game</button>\r\n\t\t\t</div>);\r\n\t\t}\r\n\t\tif (player.choice) {\r\n\t\t\tplayer.sendControls(\r\n\t\t\t\t<div style={{textAlign: 'center'}}>You have selected <strong>{player.choice}</strong>. Now to wait for your foe.</div>\r\n\t\t\t);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tplayer.sendControls(<div style={{textAlign: 'center'}}>\r\n\t\t\t<strong>Make your choice, quick! You have {Chat.toDurationString(TIMEOUT)}!</strong><br />\r\n\t\t\t{['Rock', 'Paper', 'Scissors'].map(choice => (\r\n\t\t\t\t<button class=\"button\" name=\"send\" value={`/choose ${choice}`} style={{width: '6em'}}>\r\n\t\t\t\t\t<span style={{fontSize: '24px'}}>{ICONS[choice]}</span><br />\r\n\t\t\t\t\t{choice || '\\u00A0'}\r\n\t\t\t\t</button>\r\n\t\t\t))}<br /><br />\r\n\t\t\t<button class=\"button\" name=\"send\" value=\"/rps end\">End game</button><br />\r\n\t\t\t<button class=\"button\" name=\"send\" value=\"/rps pause\">Pause game</button>\r\n\t\t</div>);\r\n\t}\r\n\tgetField() {\r\n\t\tif (this.players.length < 2) {\r\n\t\t\treturn <div style={{textAlign: 'center'}}><h2>Waiting to start the game...</h2></div>;\r\n\t\t}\r\n\r\n\t\tconst [p1, p2] = this.players;\r\n\r\n\t\tfunction renderBigChoice(choice: string, isWinner?: boolean) {\r\n\t\t\treturn <div style={{\r\n\t\t\t\twidth: '180px', fontSize: '120px', background: isWinner ? '#595' : '#888', color: 'white', borderRadius: '20px', paddingBottom: '5px', margin: '0 auto',\r\n\t\t\t}}>\r\n\t\t\t\t{ICONS[choice] || '\\u00A0'}<br />\r\n\t\t\t\t<small style={{fontSize: '40px'}}>\r\n\t\t\t\t\t<small style={{fontSize: '32px', display: 'block'}}>\r\n\t\t\t\t\t\t{choice || '\\u00A0'}\r\n\t\t\t\t\t</small>\r\n\t\t\t\t</small>\r\n\t\t\t</div>;\r\n\t\t}\r\n\r\n\t\tfunction renderCurrentChoice(exists?: boolean) {\r\n\t\t\treturn <div style={{\r\n\t\t\t\twidth: '100px', fontSize: '60px', background: '#888', color: 'white', borderRadius: '15px', paddingBottom: '5px', margin: '20px auto 0',\r\n\t\t\t}}>{exists ? <i class=\"fa fa-check\"></i> : '\\u00A0'}</div>;\r\n\t\t}\r\n\r\n\t\treturn <table style={{width: '100%', textAlign: 'center', fontSize: '18px'}}><tr>\r\n\t\t\t<td>\r\n\t\t\t\t<div style={{padding: '8px 0'}}><strong>{p1.name}</strong> ({p1.score})</div>\r\n\t\t\t\t{renderBigChoice(p1.prevChoice, p1.prevWinner)}\r\n\t\t\t\t{renderCurrentChoice(!!p1.choice)}\r\n\t\t\t</td>\r\n\t\t\t<td>\r\n\t\t\t\t<em style={{fontSize: '24px'}}>vs</em>\r\n\t\t\t</td>\r\n\t\t\t<td>\r\n\t\t\t\t<div style={{padding: '8px 0'}}><strong>{p2.name}</strong> ({p2.score})</div>\r\n\t\t\t\t{renderBigChoice(p2.prevChoice, p2.prevWinner)}\r\n\t\t\t\t{renderCurrentChoice(!!p2.choice)}\r\n\t\t\t</td>\r\n\t\t</tr></table>;\r\n\t}\r\n\tsendField() {\r\n\t\tthis.room.send(Chat.html`|fieldhtml|${this.getField()}`);\r\n\t}\r\n\tend(Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,MAAM,aAAa;AACnB,MAAM,UAAU,KAAK;AACrB,MA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aAAK,QAAQ,KAAK,OAAO,YAAY,OAAO,gBAAgB,MAAM,iBAAiB;AAAA,MACpF,OAAO;AACN,aAAK,QAAQ,KAAK,OAAO,YAAY,OAAO,gBAAgB,MAAM,UAAU,MAAM,SAAS;AAAA,MAC5F;AACA,aAAO;AAAA,IACR;AAEA,QAAI,CAAC,UAAU,CAAC,GAAG,QAAQ;AAC1B,WAAK,MAAM;AACX;AAAA,IACD;AAEA,QAAI,KAAK,gBAAgB,YAAY;AACpC,WAAK,QAAQ,uCAAuC,KAAK,sBAAsB;AAC/E,aAAO,KAAK,IAAI;AAAA,IACjB;AAEA,eAAW,UAAU,KAAK,SAAS;AAClC,aAAO,aAAa,OAAO;AAC3B,aAAO,aAAa;AACpB,aAAO,SAAS;AAAA,IACjB;AACA,QAAI;AAAQ,aAAO,aAAa;AAEhC,SAAK,UAAU;AACf,SAAK,UAAU;AAAA,EAChB;AAAA,EACA,aAAa,SAAiB;AAC7B,SAAK,KAAK,IAAI,aAAa,SAAS,EAAE,OAAO;AAAA,EAC9C;AAAA,EACA,QAAQ,SAAiB;AACxB,SAAK,KAAK,IAAI,YAAY,SAAS,EAAE,OAAO;AAAA,EAC7C;AAAA,EACA,QAAQ;AACP,QAAI,KAAK,QAAQ,SAAS,GAAG;AAC5B,YAAM,IAAI,KAAK,aAAa,4FAA4F;AAAA,IACzH;AACA,QAAI,KAAK,KAAK,ILine truncated
"names": []
}
+557
View File
@@ -0,0 +1,557 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var room_events_exports = {};
__export(room_events_exports, {
commands: () => commands
});
module.exports = __toCommonJS(room_events_exports);
var import_lib = require("../../lib");
/**
* Room Events Plugin
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This is a room-management system to keep track of upcoming room events.
*
* @license MIT license
*/
function convertAliasFormat(room) {
if (!room.settings.events)
return;
for (const event of Object.values(room.settings.events)) {
if (!event.aliases)
continue;
for (const alias of event.aliases) {
room.settings.events[alias] = { eventID: toID(event.eventName) };
}
delete event.aliases;
}
}
function formatEvent(room, event, showAliases, showCategories) {
const timeRemaining = new Date(event.date).getTime() - new Date().getTime();
let explanation = timeRemaining.toString();
if (!timeRemaining)
explanation = "The time remaining for this event is not available";
if (timeRemaining < 0)
explanation = "This event will start soon";
if (event.started)
explanation = "This event has started";
if (!isNaN(timeRemaining)) {
explanation = `This event will start in: ${Chat.toDurationString(timeRemaining, { precision: 2 })}`;
}
const eventID = toID(event.eventName);
const aliases = getAliases(room, eventID);
const categories = getAllCategories(room).filter(
(category) => room.settings.events[category].events.includes(eventID)
);
let ret = `<tr title="${explanation}">`;
ret += import_lib.Utils.html`<td>${event.eventName}</td>`;
if (showAliases)
ret += import_lib.Utils.html`<td>${aliases.join(", ")}</td>`;
if (showCategories)
ret += import_lib.Utils.html`<td>${categories.join(", ")}</td>`;
ret += `<td>${Chat.formatText(event.desc, true)}</td>`;
ret += import_lib.Utils.html`<td><time>${event.date}</time></td></tr>`;
return ret;
}
function getAliases(room, eventID) {
if (!room.settings.events)
return [];
const aliases = [];
for (const aliasID in room.settings.events) {
if ("eventID" in room.settings.events[aliasID] && (!eventID || room.settings.events[aliasID].eventID === eventID))
aliases.push(aliasID);
}
return aliases;
}
function getAllCategories(room) {
if (!room.settings.events)
return [];
const categories = [];
for (const categoryID in room.settings.events) {
if ("events" in room.settings.events[categoryID])
categories.push(categoryID);
}
return categories;
}
function getAllEvents(room) {
if (!room.settings.events)
return [];
const events = [];
for (const event of Object.values(room.settings.events)) {
if ("eventName" in event)
events.push(event);
}
return events;
}
function getEventID(nameOrAlias, room) {
let id = toID(nameOrAlias);
const event = room.settings.events?.[id];
if (event && "eventID" in event) {
id = event.eventID;
}
return id;
}
const commands = {
events: "roomevents",
roomevent: "roomevents",
roomevents: {
""(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
if (!room.settings.events || !Object.keys(room.settings.events).length) {
return this.errorReply("There are currently no planned upcoming events for this room.");
}
if (!this.runBroadcast())
return;
convertAliasFormat(room);
const hasAliases = getAliases(room).length > 0;
const hasCategories = getAllCategories(room).length > 0;
let buff = '<table border="1" cellspacing="0" cellpadding="3">';
buff += "<th>Event Name:</th>";
if (hasAliases)
buff += "<th>Event Aliases:</th>";
if (hasCategories)
buff += "<th>Event Categories:</th>";
buff += "<th>Event Description:</th><th>Event Date:</th>";
for (const event of getAllEvents(room)) {
buff += formatEvent(room, event, hasAliases, hasCategories);
}
buff += "</table>";
return this.sendReply(`|raw|<div class="infobox-limited">${buff}</div>`);
},
new: "add",
create: "add",
edit: "add",
add(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.checkCan("ban", null, room);
if (!room.settings.events)
room.settings.events = /* @__PURE__ */ Object.create(null);
convertAliasFormat(room);
const events = room.settings.events;
const [eventName, date, ...desc] = target.split(target.includes("|") ? "|" : ",");
if (!(eventName && date && desc)) {
return this.errorReply("You're missing a command parameter - to see this command's syntax, use /help roomevents.");
}
const dateActual = date.trim();
const descString = desc.join(target.includes("|") ? "|" : ",").trim();
if (eventName.trim().length > 50)
return this.errorReply("Event names should not exceed 50 characters.");
if (dateActual.length > 150)
return this.errorReply("Event dates should not exceed 150 characters.");
if (descString.length > 1e3)
return this.errorReply("Event descriptions should not exceed 1000 characters.");
const eventId = getEventID(eventName, room);
if (!eventId)
return this.errorReply("Event names must contain at least one alphanumerical character.");
const oldEvent = room.settings.events?.[eventId];
if (oldEvent && "events" in oldEvent)
return this.errorReply(`"${eventId}" is already the name of a category.`);
const eventNameActual = oldEvent ? oldEvent.eventName : eventName.trim();
this.privateModAction(`${user.name} ${oldEvent ? "edited the" : "added a"} roomevent titled "${eventNameActual}".`);
this.modlog("ROOMEVENT", null, `${oldEvent ? "edited" : "added"} "${eventNameActual}"`);
events[eventId] = {
eventName: eventNameActual,
date: dateActual,
desc: descString,
started: false
};
room.saveSettings();
},
rename(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.checkCan("ban", null, room);
let [oldName, newName] = target.split(target.includes("|") ? "|" : ",");
if (!(oldName && newName))
return this.errorReply("Usage: /roomevents rename [old name], [new name]");
convertAliasFormat(room);
newName = newName.trim();
const newID = toID(newName);
const oldID = getAliases(room).includes(toID(oldName)) ? getEventID(oldName, room) : toID(oldName);
if (newID === oldID)
return this.errorReply("The new name must be different from the old one.");
if (!newID)
return this.errorReply("Event names must contain at least one alphanumeric character.");
if (newName.length > 50)
return this.errorReply("Event names should not exceed 50 characters.");
const events = room.settings.events;
const eventData = events?.[oldID];
if (!(eventData && "eventName" in eventData))
return this.errorReply(`There is no event titled "${oldName}".`);
if (events?.[newID]) {
return this.errorReply(`"${newName}" is already an event, alias, or category.`);
}
const originalName = eventData.eventName;
eventData.eventName = newName;
events[newID] = eventData;
delete events[oldID];
this.privateModAction(`${user.name} renamed the roomevent titled "${originalName}" to "${newName}".`);
this.modlog("ROOMEVENT", null, `renamed "${originalName}" to "${newName}"`);
room.saveSettings();
},
begin: "start",
start(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.checkCan("ban", null, room);
if (!room.settings.events || !Object.keys(room.settings.events).length) {
return this.errorReply("There are currently no planned upcoming events for this room to start.");
}
if (!target)
return this.errorReply("Usage: /roomevents start [event name]");
convertAliasFormat(room);
target = toID(target);
const event = room.settings.events[getEventID(target, room)];
if (!(event && "eventName" in event))
return this.errorReply(`There is no event titled '${target}'. Check spelling?`);
if (event.started) {
return this.errorReply(`The event ${event.eventName} has already started.`);
}
for (const u in room.users) {
const activeUser = Users.get(u);
if (activeUser?.connected) {
activeUser.sendTo(
room,
import_lib.Utils.html`|notify|A new roomevent in ${room.title} has started!|` + `The "${event.eventName}" roomevent has started!`
);
}
}
this.add(
import_lib.Utils.html`|raw|<div class="broadcast-blue"><b>The "${event.eventName}" roomevent has started!</b></div>`
);
this.modlog("ROOMEVENT", null, `started "${toID(event.eventName)}"`);
event.started = true;
room.saveSettings();
},
delete: "remove",
remove(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.checkCan("ban", null, room);
if (!room.settings.events || Object.keys(room.settings.events).length === 0) {
return this.errorReply("There are currently no planned upcoming events for this room to remove.");
}
if (!target)
return this.errorReply("Usage: /roomevents remove [event name]");
const eventID = toID(target);
convertAliasFormat(room);
if (getAliases(room).includes(eventID))
return this.errorReply("To delete aliases, use /roomevents removealias.");
if (!(room.settings.events[eventID] && "eventName" in room.settings.events[eventID])) {
return this.errorReply(`There is no event titled '${target}'. Check spelling?`);
}
delete room.settings.events[eventID];
for (const alias of getAliases(room, eventID)) {
delete room.settings.events[alias];
}
for (const category of getAllCategories(room).map((cat) => room.settings.events?.[cat])) {
category.events = category.events.filter((event) => event !== eventID);
}
this.privateModAction(`${user.name} removed a roomevent titled "${target}".`);
this.modlog("ROOMEVENT", null, `removed "${target}"`);
room.saveSettings();
},
view(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
if (!room.settings.events || !Object.keys(room.settings.events).length) {
return this.errorReply("There are currently no planned upcoming events for this room.");
}
if (!target)
return this.errorReply("Usage: /roomevents view [event name, alias, or category]");
convertAliasFormat(room);
target = getEventID(target, room);
let events = [];
if (getAllCategories(room).includes(target)) {
for (const categoryID of Object.keys(room.settings.events)) {
const category = room.settings.events[categoryID];
if ("events" in category && categoryID === target) {
events = category.events.map((e) => room.settings.events?.[e]).filter((e) => e);
break;
}
}
} else if (room.settings.events[target] && "eventName" in room.settings.events[target]) {
events.push(room.settings.events[target]);
} else {
return this.errorReply(`There is no event or category titled '${target}'. Check spelling?`);
}
if (!this.runBroadcast())
return;
let hasAliases = false;
let hasCategories = false;
for (const event of events) {
if (getAliases(room, toID(event.eventName)).length)
hasAliases = true;
}
for (const potentialCategory of getAllCategories(room)) {
if (events.map((event) => toID(event.eventName)).filter((id) => (room.settings.events?.[potentialCategory]).events.includes(id)).length)
hasCategories = true;
break;
}
let buff = '<table border="1" cellspacing="0" cellpadding="3">';
buff += "<th>Event Name:</th>";
if (hasAliases)
buff += "<th>Event Aliases:</th>";
if (hasCategories)
buff += "<th>Event Categories:</th>";
buff += "<th>Event Description:</th><th>Event Date:</th>";
for (const event of events) {
buff += formatEvent(room, event, hasAliases, hasCategories);
}
buff += "</table>";
this.sendReply(`|raw|<div class="infobox-limited">${buff}</div>`);
if (!this.broadcasting && user.can("ban", null, room, "roomevents add") && events.length === 1) {
const event = events[0];
this.sendReplyBox(import_lib.Utils.html`<details><summary>Source</summary><code style="white-space: pre-wrap; display: table; tab-size: 3">/roomevents add ${event.eventName} | ${event.date} | ${event.desc}</code></details>`.replace(/\n/g, "<br />"));
}
},
alias: "addalias",
addalias(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.checkCan("ban", null, room);
const [alias, eventId] = target.split(target.includes("|") ? "|" : ",").map((argument) => toID(argument));
if (!(alias && eventId)) {
return this.errorReply("Usage: /roomevents addalias [alias], [event name]. Aliases must contain at least one alphanumeric character.");
}
if (!room.settings.events || Object.keys(room.settings.events).length === 0) {
return this.errorReply(`There are currently no scheduled events.`);
}
convertAliasFormat(room);
const event = room.settings.events[eventId];
if (!(event && "eventName" in event))
return this.errorReply(`There is no event titled "${eventId}".`);
if (room.settings.events[alias])
return this.errorReply(`"${alias}" is already an event, alias, or category.`);
room.settings.events[alias] = { eventID: eventId };
this.privateModAction(`${user.name} added an alias "${alias}" for the roomevent "${eventId}".`);
this.modlog("ROOMEVENT", null, `alias for "${eventId}": "${alias}"`);
room.saveSettings();
},
deletealias: "removealias",
removealias(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.checkCan("ban", null, room);
target = toID(target);
if (!target)
return this.errorReply("Usage: /roomevents removealias <alias>");
if (!room.settings.events || Object.keys(room.settings.events).length === 0) {
return this.errorReply(`There are currently no scheduled events.`);
}
convertAliasFormat(room);
if (!(room.settings.events[target] && "eventID" in room.settings.events[target])) {
return this.errorReply(`${target} isn't an alias.`);
}
delete room.settings.events[target];
this.privateModAction(`${user.name} removed the alias "${target}"`);
this.modlog("ROOMEVENT", null, `removed the alias "${target}"`);
room.saveSettings();
},
addtocategory(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.checkCan("ban", null, room);
const [eventId, categoryId] = target.split(target.includes("|") ? "|" : ",").map((argument) => toID(argument));
if (!(eventId && categoryId))
return this.errorReply("Usage: /roomevents addtocategory [event name], [category].");
if (!room.settings.events || Object.keys(room.settings.events).length === 0) {
return this.errorReply(`There are currently no scheduled events.`);
}
convertAliasFormat(room);
const event = room.settings.events[getEventID(eventId, room)];
if (!(event && "eventName" in event))
return this.errorReply(`There is no event or alias titled "${eventId}".`);
const category = room.settings.events[categoryId];
if (category && !("events" in category)) {
return this.errorReply(`There is already an event or alias titled "${categoryId}".`);
}
if (!category) {
return this.errorReply(`There is no category titled "${categoryId}". To create it, use /roomevents addcategory ${categoryId}.`);
}
if (category.events.includes(toID(event.eventName))) {
return this.errorReply(`The event "${eventId}" is already in the "${categoryId}" category.`);
}
category.events.push(toID(event.eventName));
room.settings.events[categoryId] = category;
this.privateModAction(`${user.name} added the roomevent "${eventId}" to the category "${categoryId}".`);
this.modlog("ROOMEVENT", null, `category for "${eventId}": "${categoryId}"`);
room.saveSettings();
},
removefromcategory(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.checkCan("ban", null, room);
const [eventId, categoryId] = target.split(target.includes("|") ? "|" : ",").map((argument) => toID(argument));
if (!(eventId && categoryId)) {
return this.errorReply("Usage: /roomevents removefromcategory [event name], [category].");
}
if (!room.settings.events || Object.keys(room.settings.events).length === 0) {
return this.errorReply(`There are currently no scheduled events.`);
}
convertAliasFormat(room);
const event = room.settings.events[getEventID(eventId, room)];
if (!(event && "eventName" in event))
return this.errorReply(`There is no event or alias titled "${eventId}".`);
const category = room.settings.events[categoryId];
if (category && !("events" in category)) {
return this.errorReply(`There is already an event or alias titled "${categoryId}".`);
}
if (!category)
return this.errorReply(`There is no category titled "${categoryId}".`);
if (!category.events.includes(toID(event.eventName))) {
return this.errorReply(`The event "${eventId}" isn't in the "${categoryId}" category.`);
}
category.events = category.events.filter((e) => e !== eventId);
room.settings.events[categoryId] = category;
this.privateModAction(`${user.name} removed the roomevent "${eventId}" from the category "${categoryId}".`);
this.modlog("ROOMEVENT", null, `category for "${eventId}": removed "${categoryId}"`);
room.saveSettings();
},
addcat: "addcategory",
addcategory(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.checkCan("ban", null, room);
const categoryId = toID(target);
if (!target) {
return this.errorReply("Usage: /roomevents addcategory [category name]. Categories must contain at least one alphanumeric character.");
}
convertAliasFormat(room);
if (!room.settings.events)
room.settings.events = /* @__PURE__ */ Object.create(null);
if (room.settings.events?.[categoryId])
return this.errorReply(`The category "${target}" already exists.`);
room.settings.events[categoryId] = { events: [] };
this.privateModAction(`${user.name} added the category "${categoryId}".`);
this.modlog("ROOMEVENT", null, `category: added "${categoryId}"`);
room.saveSettings();
},
deletecategory: "removecategory",
deletecat: "removecategory",
removecat: "removecategory",
rmcat: "removecategory",
removecategory(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.checkCan("ban", null, room);
const categoryId = toID(target);
if (!target)
return this.errorReply("Usage: /roomevents removecategory [category name].");
convertAliasFormat(room);
if (!room.settings.events)
room.settings.events = /* @__PURE__ */ Object.create(null);
if (!room.settings.events?.[categoryId])
return this.errorReply(`The category "${target}" doesn't exist.`);
delete room.settings.events?.[categoryId];
this.privateModAction(`${user.name} removed the category "${categoryId}".`);
this.modlog("ROOMEVENT", null, `category: removed "${categoryId}"`);
room.saveSettings();
},
viewcategories: "categories",
categories(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
this.runBroadcast();
const categoryButtons = getAllCategories(room).map(
(category) => `<button class="button" name="send" value="/roomevents view ${category}">${category}</button>`
);
if (!categoryButtons.length)
return this.errorReply(`There are no roomevent categories in ${room.title}.`);
this.sendReplyBox(`Roomevent categories in ${room.title}: ${categoryButtons.join(" ")}`);
},
help(target, room, user) {
return this.parse("/help roomevents");
},
sortby(target, room, user) {
room = this.requireRoom();
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
if (!room.settings.events || !Object.keys(room.settings.events).length) {
return this.errorReply("There are currently no planned upcoming events for this room.");
}
this.checkCan("ban", null, room);
let multiplier = 1;
let columnName = "";
const delimited = target.split(target.includes("|") ? "|" : ",");
const sortable = Object.values(room.settings.events).filter((event) => "eventName" in event).map((event) => event);
if (delimited.length === 1) {
columnName = target;
} else {
let order = "";
[columnName, order] = delimited;
order = toID(order);
multiplier = order === "desc" ? -1 : 1;
}
columnName = toID(columnName);
switch (columnName) {
case "date":
case "eventdate":
sortable.sort(
(a, b) => toID(a.date) < toID(b.date) ? -1 * multiplier : toID(b.date) < toID(a.date) ? 1 * multiplier : 0
);
break;
case "desc":
case "description":
case "eventdescription":
sortable.sort(
(a, b) => toID(a.desc) < toID(b.desc) ? -1 * multiplier : toID(b.desc) < toID(a.desc) ? 1 * multiplier : 0
);
break;
case "eventname":
case "name":
sortable.sort(
(a, b) => toID(a.eventName) < toID(b.eventName) ? -1 * multiplier : toID(b.eventName) < toID(a.eventName) ? 1 * multiplier : 0
);
break;
default:
return this.errorReply(`Invalid column name "${columnName}". Please use one of: date, desc, name.`);
}
for (const sortedObj of sortable) {
const eventId = toID(sortedObj.eventName);
delete room.settings.events[eventId];
room.settings.events[eventId] = sortedObj;
}
const resultString = `sorted by column: ${columnName} in ${multiplier === 1 ? "ascending" : "descending"} order${delimited.length === 1 ? " (by default)" : ""}`;
this.modlog("ROOMEVENT", null, resultString);
return this.sendReply(resultString);
}
},
roomeventshelp() {
this.sendReply(
`|html|<details class="readmore"><summary><code>/roomevents</code>: displays a list of upcoming room-specific events.<br /><code>/roomevents add [event name] | [event date/time] | [event description]</code>: adds a room event. A timestamp in event date/time field like YYYY-MM-DD HH:MM\xB1hh:mm will be displayed in user's timezone. Requires: @ # &<br /><code>/roomevents start [event name]</code>: declares to the room that the event has started. Requires: @ # &<br /><code>/roomevents remove [event name]</code>: deletes an event. Requires: @ # &</summary><code>/roomevents rename [old event name] | [new name]</code>: renames an event. Requires: @ # &<br /><code>/roomevents addalias [alias] | [event name]</code>: adds an alias for the event. Requires: @ # &<br /><code>/roomevents removealias [alias]</code>: removes an event alias. Requires: @ # &<br /><code>/roomevents addcategory [category]</code>: adds an event category. Requires: @ # &<br /><code>/roomevents removecategory [category]</code>: removes an event category. Requires: @ # &<br /><code>/roomevents addtocategory [event name] | [category]</code>: adds the event to a category. Requires: @ # &<br /><code>/roomevents removefromcategory [event name] | [category]</code>: removes the event from a category. Requires: @ # &<br /><code>/roomevents sortby [column name] | [asc/desc (optional)]</code> sorts events table by column name and an optional argument to ascending or descending order. Ascending order is default. Requires: @ # &<br /><code>/roomevents view [event name or category]</code>: displays information about a specific event or category of events.<br /><code>/roomevents viewcategories</code>: displays a list of event categories for that room.</details>`
);
}
};
//# sourceMappingURL=room-events.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/room-events.ts"],
"sourcesContent": ["/**\r\n * Room Events Plugin\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * This is a room-management system to keep track of upcoming room events.\r\n *\r\n * @license MIT license\r\n */\r\nimport {Utils} from '../../lib';\r\n\r\nexport interface RoomEvent {\r\n\teventName: string;\r\n\tdate: string;\r\n\tdesc: string;\r\n\tstarted: boolean;\r\n}\r\n\r\nexport interface RoomEventAlias {\r\n\teventID: ID;\r\n}\r\n\r\nexport interface RoomEventCategory {\r\n\tevents: ID[];\r\n}\r\n\r\nfunction convertAliasFormat(room: Room) {\r\n\tif (!room.settings.events) return;\r\n\tfor (const event of Object.values(room.settings.events) as AnyObject[]) {\r\n\t\tif (!event.aliases) continue;\r\n\t\tfor (const alias of event.aliases) {\r\n\t\t\troom.settings.events[alias] = {eventID: toID(event.eventName)};\r\n\t\t}\r\n\t\tdelete event.aliases;\r\n\t}\r\n}\r\n\r\nfunction formatEvent(room: Room, event: RoomEvent, showAliases?: boolean, showCategories?: boolean) {\r\n\tconst timeRemaining = new Date(event.date).getTime() - new Date().getTime();\r\n\tlet explanation = timeRemaining.toString();\r\n\tif (!timeRemaining) explanation = \"The time remaining for this event is not available\";\r\n\tif (timeRemaining < 0) explanation = \"This event will start soon\";\r\n\tif (event.started) explanation = \"This event has started\";\r\n\tif (!isNaN(timeRemaining)) {\r\n\t\texplanation = `This event will start in: ${Chat.toDurationString(timeRemaining, {precision: 2})}`;\r\n\t}\r\n\r\n\tconst eventID = toID(event.eventName);\r\n\tconst aliases = getAliases(room, eventID);\r\n\tconst categories = getAllCategories(room).filter(\r\n\t\tcategory => (room.settings.events![category] as RoomEventCategory).events.includes(eventID)\r\n\t);\r\n\r\n\tlet ret = `<tr title=\"${explanation}\">`;\r\n\tret += Utils.html`<td>${event.eventName}</td>`;\r\n\tif (showAliases) ret += Utils.html`<td>${aliases.join(\", \")}</td>`;\r\n\tif (showCategories) ret += Utils.html`<td>${categories.join(\", \")}</td>`;\r\n\tret += `<td>${Chat.formatText(event.desc, true)}</td>`;\r\n\tret += Utils.html`<td><time>${event.date}</time></td></tr>`;\r\n\treturn ret;\r\n}\r\n\r\nfunction getAliases(room: Room, eventID?: ID) {\r\n\tif (!room.settings.events) return [];\r\n\tconst aliases: string[] = [];\r\n\tfor (const aliasID in room.settings.events) {\r\n\t\tif (\r\n\t\t\t'eventID' in room.settings.events[aliasID] &&\r\n\t\t\t(!eventID || (room.settings.events[aliasID] as RoomEventAlias).eventID === eventID)\r\n\t\t) aliases.push(aliasID);\r\n\t}\r\n\treturn aliases;\r\n}\r\n\r\nfunction getAllCategories(room: Room) {\r\n\tif (!room.settings.events) return [];\r\n\tconst categories: string[] = [];\r\n\tfor (const categoryID in room.settings.events) {\r\n\t\tif ('events' in room.settings.events[categoryID]) categories.push(categoryID);\r\n\t}\r\n\treturn categories;\r\n}\r\n\r\nfunction getAllEvents(room: Room) {\r\n\tif (!room.settings.events) return [];\r\n\tconst events: RoomEvent[] = [];\r\n\tfor (const event of Object.values(room.settings.events)) {\r\n\t\tif ('eventName' in event) events.push(event);\r\n\t}\r\n\treturn events;\r\n}\r\n\r\nfunction getEventID(nameOrAlias: string, room: Room): ID {\r\n\tlet id = toID(nameOrAlias);\r\n\tconst event = room.settings.events?.[id];\r\n\tif (event && 'eventID' in event) {\r\n\t\tid = event.eventID;\r\n\t}\r\n\treturn id;\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tevents: 'roomevents',\r\n\troomevent: 'roomevents',\r\n\troomevents: {\r\n\t\t''(target, room, user) {\r\n\t\t\troom = this.requireRoom();\r\n\t\t\tif (!room.persist) return this.errorReply(\"This command is unavailable in temporary rooms.\");\r\n\t\t\tif (!room.settings.events || !Object.keys(room.settings.events).length) {\r\n\t\t\t\treturn this.errorReply(\"There are currently no planned upcoming events for this room.\");\r\n\t\t\t}\r\n\t\t\tif (!this.runBroadcast()) return;\r\n\t\t\tconvertAliasFormat(room);\r\n\t\t\tconst hasAliases = getAliases(room).length > 0;\r\n\t\t\tconst hasCategories = getAllCategories(room).length > 0;\r\n\r\n\t\t\tlet buff = '<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">';\r\n\t\t\tbuff += '<th>Event Name:</th>';\r\n\t\t\tif (hasAliases) buff += '<th>Event Aliases:</th>';\r\n\t\t\tif (hasCategories) buff += '<th>Event Categories:</th>';\r\n\t\t\tbuff += '<th>Event Description:</th><th>Event Date:</th>';\r\n\r\n\t\t\tfor (const event of getAllEvents(room)) {\r\n\t\t\t\tbuff += formatEvent(room, event, hasAliases, hasCategories);\r\n\t\t\t}\r\n\t\t\tbuff += '</table>';\r\n\t\t\treturn this.sendReply(`|raw|<div class=\"infobox-limited\">${buff}</div>`);\r\n\t\t},\r\n\r\n\t\tnew: 'add',\r\n\t\tcreate: 'add',\r\n\t\tedit: 'add',\r\n\t\tadd(target, room, user) {\r\n\t\t\troom = this.requireRoom();\r\n\t\t\tif (!room.persist) return this.errorReply(\"This command is unavailable in temporary rooms.\");\r\n\t\t\tthis.checkCan('ban', null, room);\r\n\t\t\tif (!room.settings.Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,iBAAoB;AARpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyBA,SAAS,mBAAmB,MAAY;AACvC,MAAI,CAAC,KAAK,SAAS;AAAQ;AAC3B,aAAW,SAAS,OAAO,OAAO,KAAK,SAAS,MAAM,GAAkB;AACvE,QAAI,CAAC,MAAM;AAAS;AACpB,eAAW,SAAS,MAAM,SAAS;AAClC,WAAK,SAAS,OAAO,KAAK,IAAI,EAAC,SAAS,KAAK,MAAM,SAAS,EAAC;AAAA,IAC9D;AACA,WAAO,MAAM;AAAA,EACd;AACD;AAEA,SAAS,YAAY,MAAY,OAAkB,aAAuB,gBAA0B;AACnG,QAAM,gBAAgB,IAAI,KAAK,MAAM,IAAI,EAAE,QAAQ,IAAI,IAAI,KAAK,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WAAK,SAAS,OAAO,MAAM,IAAI;AAC/B,UAAI,CAAC,KAAK,SAAS,UAAU,CAAC,OAAO,KAAK,KAAK,SAAS,MAAM,EAAE,QAAQ;AACvE,eAAO,KAAK,WAAW,wEAAwE;AAAA,MAChG;AACA,UAAI,CAAC;AAAQ,eAAO,KAAK,WAAW,uCAAuC;AAC3E,yBAAmB,IAAI;AAEvB,eAAS,KAAK,MAAM;AACpB,YAAM,QAAQ,KAAK,SAAS,OAAO,WAAW,QAAQ,IAAI,CAAC;AAC3D,UAAI,EAAE,SAAS,eAAe;AAAQ,eAAO,KAAK,WAAW,6BAA6B,0BAA0B;AACpH,UAAI,MAAM,SAAS;AAClB,eAAO,KAAK,WAAW,aAAa,MAAM,gLine truncated
"names": []
}
+259
View File
@@ -0,0 +1,259 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var room_faqs_exports = {};
__export(room_faqs_exports, {
ROOMFAQ_FILE: () => ROOMFAQ_FILE,
commands: () => commands,
getAlias: () => getAlias,
handlers: () => handlers,
pages: () => pages,
roomFaqs: () => roomFaqs,
visualizeFaq: () => visualizeFaq
});
module.exports = __toCommonJS(room_faqs_exports);
var import_lib = require("../../lib");
const ROOMFAQ_FILE = "config/chat-plugins/faqs.json";
const MAX_ROOMFAQ_LENGTH = 8192;
const roomFaqs = (() => {
const data = JSON.parse((0, import_lib.FS)(ROOMFAQ_FILE).readIfExistsSync() || "{}");
let save = false;
for (const k in data) {
for (const name in data[k]) {
if (typeof data[k][name] === "string") {
data[k][name] = convertFaq(data[k][name]);
save = true;
}
}
}
if (save)
saveRoomFaqs(data);
return data;
})();
function saveRoomFaqs(table) {
(0, import_lib.FS)(ROOMFAQ_FILE).writeUpdate(() => JSON.stringify(table || roomFaqs));
}
function convertFaq(faq) {
if (faq.startsWith(">")) {
return {
alias: true,
source: faq.slice(1)
};
}
return {
source: faq
};
}
function visualizeFaq(faq) {
if (faq.html) {
return faq.source;
}
return Chat.formatText(faq.source, true);
}
function getAlias(roomid, key) {
if (!roomFaqs[roomid])
return false;
const value = roomFaqs[roomid][key];
if (value?.alias)
return value.source;
return false;
}
const commands = {
addhtmlfaq: "addfaq",
addfaq(target, room, user, connection) {
room = this.requireRoom();
const useHTML = this.cmd.includes("html");
this.checkCan("ban", null, room);
if (useHTML && !user.can("addhtml", null, room, this.fullCmd)) {
return this.errorReply(`You are not allowed to use raw HTML in roomfaqs.`);
}
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
if (!target)
return this.parse("/help roomfaq");
target = target.trim();
const input = this.filter(target);
if (target !== input)
return this.errorReply("You are not allowed to use fitered words in roomfaq entries.");
let [topic, ...rest] = input.split(",");
topic = toID(topic);
if (!(topic && rest.length))
return this.parse("/help roomfaq");
let text = rest.join(",").trim();
if (topic.length > 25)
return this.errorReply("FAQ topics should not exceed 25 characters.");
const lengthWithoutFormatting = Chat.stripFormatting(text).length;
if (lengthWithoutFormatting > MAX_ROOMFAQ_LENGTH) {
return this.errorReply(`FAQ entries must not exceed ${MAX_ROOMFAQ_LENGTH} characters.`);
} else if (lengthWithoutFormatting < 1) {
return this.errorReply(`FAQ entries must include at least one character.`);
}
if (!useHTML) {
text = text.replace(/^>/, "&gt;");
} else {
text = text.replace(/\n/ig, "<br />");
text = this.checkHTML(text);
}
if (!roomFaqs[room.roomid])
roomFaqs[room.roomid] = {};
const exists = topic in roomFaqs[room.roomid];
roomFaqs[room.roomid][topic] = {
source: text,
html: useHTML
};
saveRoomFaqs();
this.sendReplyBox(visualizeFaq(roomFaqs[room.roomid][topic]));
this.privateModAction(`${user.name} ${exists ? "edited" : "added"} an FAQ for '${topic}'`);
this.modlog("RFAQ", null, `${exists ? "edited" : "added"} '${topic}'`);
},
removefaq(target, room, user) {
room = this.requireRoom();
this.checkChat();
this.checkCan("ban", null, room);
const topic = toID(target);
if (!topic)
return this.parse("/help roomfaq");
if (!(roomFaqs[room.roomid] && roomFaqs[room.roomid][topic]))
return this.errorReply("Invalid topic.");
if (room.settings.repeats?.length && room.settings.repeats.filter((x) => x.faq && x.id === (getAlias(room.roomid, topic) || topic)).length) {
this.parse(`/msgroom ${room.roomid},/removerepeat ${getAlias(room.roomid, topic) || topic}`);
}
delete roomFaqs[room.roomid][topic];
Object.keys(roomFaqs[room.roomid]).filter(
(val) => getAlias(room.roomid, val) === topic
).map(
(val) => delete roomFaqs[room.roomid][val]
);
if (!Object.keys(roomFaqs[room.roomid]).length)
delete roomFaqs[room.roomid];
saveRoomFaqs();
this.privateModAction(`${user.name} removed the FAQ for '${topic}'`);
this.modlog("ROOMFAQ", null, `removed ${topic}`);
this.refreshPage(`roomfaqs-${room.roomid}`);
},
addalias(target, room, user) {
room = this.requireRoom();
this.checkChat();
this.checkCan("ban", null, room);
if (!room.persist)
return this.errorReply("This command is unavailable in temporary rooms.");
const [alias, topic] = target.split(",").map((val) => toID(val));
if (!(alias && topic))
return this.parse("/help roomfaq");
if (alias.length > 25)
return this.errorReply("FAQ topics should not exceed 25 characters.");
if (!(roomFaqs[room.roomid] && topic in roomFaqs[room.roomid])) {
return this.errorReply(`The topic ${topic} was not found in this room's faq list.`);
}
if (getAlias(room.roomid, topic)) {
return this.errorReply(`You cannot make an alias of an alias. Use /addalias ${alias}, ${getAlias(room.roomid, topic)} instead.`);
}
roomFaqs[room.roomid][alias] = {
alias: true,
source: topic
};
saveRoomFaqs();
this.privateModAction(`${user.name} added an alias for '${topic}': ${alias}`);
this.modlog("ROOMFAQ", null, `alias for '${topic}' - ${alias}`);
},
viewfaq: "roomfaq",
rfaq: "roomfaq",
roomfaq(target, room, user, connection, cmd) {
room = this.requireRoom();
if (!roomFaqs[room.roomid])
return this.errorReply("This room has no FAQ topics.");
let topic = toID(target);
if (topic === "constructor")
return false;
if (!topic) {
return this.parse(`/join view-roomfaqs-${room.roomid}`);
}
if (!roomFaqs[room.roomid][topic])
return this.errorReply("Invalid topic.");
topic = getAlias(room.roomid, topic) || topic;
if (!this.runBroadcast())
return;
const rfaq = roomFaqs[room.roomid][topic];
this.sendReplyBox(visualizeFaq(rfaq));
if (!this.broadcasting && user.can("ban", null, room, "addfaq")) {
const code = import_lib.Utils.escapeHTML(rfaq.source).replace(/\n/g, "<br />");
const command = rfaq.html ? "addhtmlfaq" : "addfaq";
this.sendReplyBox(`<details><summary>Source</summary><code style="white-space: pre-wrap; display: table; tab-size: 3">/${command} ${topic}, ${code}</code></details>`);
}
},
roomfaqhelp: [
`/roomfaq - Shows the list of all available FAQ topics`,
`/roomfaq <topic> - Shows the FAQ for <topic>.`,
`/addfaq <topic>, <text> - Adds an entry for <topic> in this room or updates it. Requires: @ # &`,
`/addhtmlfaq <topic>, <text> - Adds or updates an entry for <topic> with HTML support. Requires: # &`,
`/addalias <alias>, <topic> - Adds <alias> as an alias for <topic>, displaying it when users use /roomfaq <alias>. Requires: @ # &`,
`/removefaq <topic> - Removes the entry for <topic> in this room. If used on an alias, removes the alias. Requires: @ # &`
]
};
const pages = {
roomfaqs(args, user) {
const room = this.requireRoom();
this.title = `[Room FAQs]`;
if (!room.checkModjoin(user)) {
throw new Chat.ErrorMessage(`<h2>Access denied.</h2>`);
}
let buf = `<div class="pad"><button style="float:right;" class="button" name="send" value="/join view-roomfaqs-${room.roomid}"><i class="fa fa-refresh"></i> Refresh</button>`;
if (!roomFaqs[room.roomid]) {
return `${buf}<h2>This room has no FAQs.</h2></div>`;
}
buf += `<h2>FAQs for ${room.title}:</h2>`;
const keys = Object.keys(roomFaqs[room.roomid]);
const sortedKeys = import_lib.Utils.sortBy(keys.filter((val) => !getAlias(room.roomid, val)));
for (const key of sortedKeys) {
const topic = roomFaqs[room.roomid][key];
buf += `<div class="infobox">`;
buf += `<h3>${key}</h3>`;
buf += `<hr />`;
buf += visualizeFaq(topic);
const aliases = keys.filter((val) => getAlias(room.roomid, val) === key);
if (aliases.length) {
buf += `<hr /><strong>Aliases:</strong> ${aliases.join(", ")}`;
}
if (user.can("ban", null, room, "addfaq")) {
const src = import_lib.Utils.escapeHTML(topic.source).replace(/\n/g, `<br />`);
const command = topic.html ? "addhtmlfaq" : "addfaq";
buf += `<hr /><details><summary>Raw text</summary>`;
buf += `<code style="white-space: pre-wrap; display: table; tab-size: 3;">/${command} ${key}, ${src}</code></details>`;
buf += `<hr /><button class="button" name="send" value="/msgroom ${room.roomid},/removefaq ${key}">Delete FAQ</button>`;
}
buf += `</div>`;
}
buf += `</div>`;
return buf;
}
};
const handlers = {
onRenameRoom(oldID, newID) {
if (roomFaqs[oldID]) {
if (!roomFaqs[newID])
roomFaqs[newID] = {};
Object.assign(roomFaqs[newID], roomFaqs[oldID]);
delete roomFaqs[oldID];
saveRoomFaqs();
}
}
};
process.nextTick(() => {
Chat.multiLinePattern.register("/add(htmlfaq|faq) ");
});
//# sourceMappingURL=room-faqs.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/room-faqs.ts"],
"sourcesContent": ["import {FS, Utils} from '../../lib';\r\n\r\nexport const ROOMFAQ_FILE = 'config/chat-plugins/faqs.json';\r\nconst MAX_ROOMFAQ_LENGTH = 8192;\r\n\r\nexport const roomFaqs: {[k: string]: {[k: string]: RoomFAQ}} = (() => {\r\n\tconst data = JSON.parse(FS(ROOMFAQ_FILE).readIfExistsSync() || \"{}\");\r\n\tlet save = false;\r\n\tfor (const k in data) {\r\n\t\tfor (const name in data[k]) {\r\n\t\t\tif (typeof data[k][name] === 'string') {\r\n\t\t\t\tdata[k][name] = convertFaq(data[k][name]);\r\n\t\t\t\tsave = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (save) saveRoomFaqs(data);\r\n\treturn data;\r\n})();\r\n\r\ninterface RoomFAQ {\r\n\tsource: string;\r\n\talias?: boolean;\r\n\thtml?: boolean;\r\n}\r\n\r\nfunction saveRoomFaqs(table?: {[k: string]: {[k: string]: RoomFAQ}}) {\r\n\tFS(ROOMFAQ_FILE).writeUpdate(() => JSON.stringify(table || roomFaqs));\r\n}\r\n\r\nfunction convertFaq(faq: string): RoomFAQ {\r\n\tif (faq.startsWith('>')) {\r\n\t\treturn {\r\n\t\t\talias: true,\r\n\t\t\tsource: faq.slice(1),\r\n\t\t};\r\n\t}\r\n\treturn {\r\n\t\tsource: faq,\r\n\t};\r\n}\r\n\r\nexport function visualizeFaq(faq: RoomFAQ) {\r\n\tif (faq.html) {\r\n\t\treturn faq.source;\r\n\t}\r\n\treturn Chat.formatText(faq.source, true);\r\n}\r\n\r\nexport function getAlias(roomid: RoomID, key: string) {\r\n\tif (!roomFaqs[roomid]) return false;\r\n\tconst value = roomFaqs[roomid][key];\r\n\tif (value?.alias) return value.source;\r\n\treturn false;\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\taddhtmlfaq: 'addfaq',\r\n\taddfaq(target, room, user, connection) {\r\n\t\troom = this.requireRoom();\r\n\t\tconst useHTML = this.cmd.includes('html');\r\n\t\tthis.checkCan('ban', null, room);\r\n\t\tif (useHTML && !user.can('addhtml', null, room, this.fullCmd)) {\r\n\t\t\treturn this.errorReply(`You are not allowed to use raw HTML in roomfaqs.`);\r\n\t\t}\r\n\t\tif (!room.persist) return this.errorReply(\"This command is unavailable in temporary rooms.\");\r\n\t\tif (!target) return this.parse('/help roomfaq');\r\n\r\n\t\ttarget = target.trim();\r\n\t\tconst input = this.filter(target);\r\n\t\tif (target !== input) return this.errorReply(\"You are not allowed to use fitered words in roomfaq entries.\");\r\n\t\tlet [topic, ...rest] = input.split(',');\r\n\r\n\t\ttopic = toID(topic);\r\n\t\tif (!(topic && rest.length)) return this.parse('/help roomfaq');\r\n\t\tlet text = rest.join(',').trim();\r\n\t\tif (topic.length > 25) return this.errorReply(\"FAQ topics should not exceed 25 characters.\");\r\n\r\n\t\tconst lengthWithoutFormatting = Chat.stripFormatting(text).length;\r\n\t\tif (lengthWithoutFormatting > MAX_ROOMFAQ_LENGTH) {\r\n\t\t\treturn this.errorReply(`FAQ entries must not exceed ${MAX_ROOMFAQ_LENGTH} characters.`);\r\n\t\t} else if (lengthWithoutFormatting < 1) {\r\n\t\t\treturn this.errorReply(`FAQ entries must include at least one character.`);\r\n\t\t}\r\n\r\n\t\tif (!useHTML) {\r\n\t\t\ttext = text.replace(/^>/, '&gt;');\r\n\t\t} else {\r\n\t\t\ttext = text.replace(/\\n/ig, '<br />');\r\n\t\t\ttext = this.checkHTML(text);\r\n\t\t}\r\n\r\n\t\tif (!roomFaqs[room.roomid]) roomFaqs[room.roomid] = {};\r\n\t\tconst exists = topic in roomFaqs[room.roomid];\r\n\t\troomFaqs[room.roomid][topic] = {\r\n\t\t\tsource: text,\r\n\t\t\thtml: useHTML,\r\n\t\t};\r\n\t\tsaveRoomFaqs();\r\n\t\tthis.sendReplyBox(visualizeFaq(roomFaqs[room.roomid][topic]));\r\n\t\tthis.privateModAction(`${user.name} ${exists ? 'edited' : 'added'} an FAQ for '${topic}'`);\r\n\t\tthis.modlog('RFAQ', null, `${exists ? 'edited' : 'added'} '${topic}'`);\r\n\t},\r\n\tremovefaq(target, room, user) {\r\n\t\troom = this.requireRoom();\r\n\t\tthis.checkChat();\r\n\t\tthis.checkCan('ban', null, room);\r\n\t\tconst topic = toID(target);\r\n\t\tif (!topic) return this.parse('/help roomfaq');\r\n\r\n\t\tif (!(roomFaqs[room.roomid] && roomFaqs[room.roomid][topic])) return this.errorReply(\"Invalid topic.\");\r\n\t\tif (\r\n\t\t\troom.settings.repeats?.length &&\r\n\t\t\troom.settings.repeats.filter(x => x.faq && x.id === (getAlias(room!.roomid, topic) || topic)).length\r\n\t\t) {\r\n\t\t\tthis.parse(`/msgroom ${room.roomid},/removerepeat ${getAlias(room.roomid, topic) || topic}`);\r\n\t\t}\r\n\t\tdelete roomFaqs[room.roomid][topic];\r\n\t\tObject.keys(roomFaqs[room.roomid]).filter(\r\n\t\t\tval => getAlias(room!.roomid, val) === topic\r\n\t\t).map(\r\n\t\t\tval => delete roomFaqs[room!.roomid][val]\r\n\t\t);\r\n\t\tif (!Object.keys(roomFaqs[room.roomid]).length) delete roomFaqs[room.roomid];\r\n\t\tsaveRoomFaqs();\r\n\t\tthis.privateModAction(`${user.name} removed the FAQ for '${topic}'`);\r\n\t\tthis.modlog('ROOMFAQ', null, `removed ${topic}`);\r\n\t\tthis.refreshPage(`roomfaqs-${room.roomid}`);\r\n\t},\r\n\taddalias(target, room, user) {\r\n\t\troom = this.requireRoom();\r\n\t\tthis.checkChat();\r\n\t\tthis.checkCan('ban', null, room);\r\n\t\tif (!room.persist) return this.errorReply(\"This command is unavailable in temporary rooms.\");\r\n\t\tconLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAwB;AAEjB,MAAM,eAAe;AAC5B,MAAM,qBAAqB;AAEpB,MAAM,YAAmD,MAAM;AACrE,QAAM,OAAO,KAAK,UAAM,eAAG,YAAY,EAAE,iBAAiB,KAAK,IAAI;AACnE,MAAI,OAAO;AACX,aAAW,KAAK,MAAM;AACrB,eAAW,QAAQ,KAAK,CAAC,GAAG;AAC3B,UAAI,OAAO,KAAK,CAAC,EAAE,IAAI,MAAM,UAAU;AACtC,aAAK,CAAC,EAAE,IAAI,IAAI,WAAW,KAAK,CAAC,EAAE,IAAI,CAAC;AACxC,eAAO;AAAA,MACR;AAAA,IACD;AAAA,EACD;AACA,MAAI;AAAM,iBAAa,IAAI;AAC3B,SAAO;AACR,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QAAwB;AAAA,EACpC,SAAS,MAAM,MAAM;AACpB,UAAM,OAAO,KAAK,YAAY;AAC9B,SAAK,QAAQ;AAEb,QAAI,CAAC,KAAK,aAAa,IAAI,GAAG;AAC7B,YAAM,IAAI,KAAK,aAAa,yBAAyB;AAAA,IACtD;AACA,QAAI,MAAM,uGAAuG,KAAK;AACtH,QAAI,CAAC,SAAS,KAAK,MAAM,GAAG;AAC3B,aAAO,GAAG;AAAA,IACX;AAEA,WAAO,gBAAgB,KAAK;AAC5B,UAAM,OAAO,OAAO,KAAK,SAAS,KAAK,MAAM,CAAC;AAC9C,UAAM,aAAa,iBAAM,OAAO,KAAK,OAAO,SAAO,CAAC,SAAS,KAAK,QAAQ,GAAG,CAALine truncated
"names": []
}
@@ -0,0 +1,615 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var sample_teams_exports = {};
__export(sample_teams_exports, {
SampleTeams: () => SampleTeams,
commands: () => commands,
destroy: () => destroy,
handlers: () => handlers,
pages: () => pages,
teamData: () => teamData
});
module.exports = __toCommonJS(sample_teams_exports);
var import_lib = require("../../lib");
const SAMPLE_TEAMS = "config/chat-plugins/sample-teams.json";
const teamData = (() => {
try {
return JSON.parse((0, import_lib.FS)(SAMPLE_TEAMS).readIfExistsSync());
} catch {
return {
whitelist: {},
teams: {}
};
}
})();
function save() {
(0, import_lib.FS)(SAMPLE_TEAMS).writeUpdate(() => JSON.stringify(teamData));
}
for (const formatid in teamData.teams) {
if (!teamData.teams[formatid].uncategorized)
teamData.teams[formatid].uncategorized = {};
}
save();
const SampleTeams = new class SampleTeams2 {
isRoomStaff(user, roomids) {
let matched = false;
if (!roomids?.length)
return false;
for (const roomid of roomids) {
const room = Rooms.search(roomid);
if (!room)
continue;
matched = room.auth.isStaff(user.id);
if (matched)
break;
}
return matched;
}
isDevMod(user) {
return !!Rooms.get("development")?.auth.atLeast(user, "@");
}
checkPermissions(user, roomids) {
return this.isRoomStaff(user, roomids) || user.can("bypassall") || this.isDevMod(user);
}
whitelistedRooms(formatid, names = false) {
formatid = this.sanitizeFormat(formatid);
if (!teamData.whitelist[formatid]?.length)
return null;
return import_lib.Utils.sortBy(teamData.whitelist[formatid], (x) => {
if (!names)
return x;
const room = Rooms.search(x);
if (!room)
return x;
return room.title;
});
}
whitelistRooms(formatids, roomids) {
for (const unsanitizedFormatid of formatids) {
const formatid = this.sanitizeFormat(unsanitizedFormatid);
if (!teamData.whitelist[formatid])
teamData.whitelist[formatid] = [];
for (const roomid of roomids) {
const targetRoom = Rooms.search(roomid);
if (!targetRoom?.persist) {
throw new Chat.ErrorMessage(`Room ${roomid} not found. Check spelling?`);
}
if (teamData.whitelist[formatid].includes(targetRoom.roomid)) {
throw new Chat.ErrorMessage(`Room ${targetRoom.title} is already added.`);
}
teamData.whitelist[formatid].push(targetRoom.roomid);
save();
}
}
}
unwhitelistRoom(formatid, roomid) {
formatid = this.sanitizeFormat(formatid, false);
const targetRoom = Rooms.search(roomid);
if (!targetRoom?.persist)
throw new Chat.ErrorMessage(`Room ${roomid} not found. Check spelling?`);
if (!teamData.whitelist[formatid]?.length)
throw new Chat.ErrorMessage(`No rooms are whitelisted for ${formatid}.`);
if (!teamData.whitelist[formatid].includes(targetRoom.roomid)) {
throw new Chat.ErrorMessage(`Room ${targetRoom.title} isn't whitelisted.`);
}
const index = teamData.whitelist[formatid].indexOf(targetRoom.roomid);
teamData.whitelist[formatid].splice(index, 1);
if (!teamData.whitelist[formatid].length)
delete teamData.whitelist[formatid];
save();
}
sanitizeFormat(formatid, checkExists = false) {
const format = Dex.formats.get(formatid);
if (checkExists && !format.exists) {
throw new Chat.ErrorMessage(`Format "${formatid.trim()}" not found. Check spelling?`);
}
if (format.team) {
throw new Chat.ErrorMessage(`Formats with computer-generated teams can't have team storage.`);
}
return format.id;
}
initializeFormat(formatid) {
if (!teamData.teams[formatid]) {
teamData.teams[formatid] = { uncategorized: {} };
save();
}
}
addCategory(user, formatid, category) {
formatid = this.sanitizeFormat(formatid);
if (!this.checkPermissions(user, teamData.whitelist[formatid])) {
let rankNeeded = `a global administrator`;
if (teamData.whitelist[formatid]) {
rankNeeded = `staff in ${Chat.toListString(teamData.whitelist[formatid], "or")}`;
}
throw new Chat.ErrorMessage(`Access denied. You need to be ${rankNeeded} to add teams for ${formatid}`);
}
category = category.trim();
this.initializeFormat(formatid);
if (this.findCategory(formatid, category)) {
throw new Chat.ErrorMessage(`The category named ${category} already exists.`);
}
teamData.teams[formatid][category] = {};
save();
}
removeCategory(user, formatid, category) {
formatid = this.sanitizeFormat(formatid, false);
if (!this.checkPermissions(user, teamData.whitelist[formatid])) {
let rankNeeded = `a global administrator`;
if (teamData.whitelist[formatid]) {
rankNeeded = `staff in ${Chat.toListString(teamData.whitelist[formatid], "or")}`;
}
throw new Chat.ErrorMessage(`Access denied. You need to be ${rankNeeded} to add teams for ${formatid}`);
}
const categoryName = this.findCategory(formatid, category);
if (!categoryName) {
throw new Chat.ErrorMessage(`There's no category named "${category.trim()}" for the format ${formatid}.`);
}
delete teamData.teams[formatid][categoryName];
save();
}
/**
* @param user
* @param formatid
* @param teamName
* @param team - Can be a team in the packed, JSON, or exported format
* @param category - Category the team will go in, defaults to uncategorized
*/
addTeam(user, formatid, teamName, team, category = "uncategorized") {
formatid = this.sanitizeFormat(formatid);
if (!this.checkPermissions(user, teamData.whitelist[formatid])) {
let rankNeeded = `a global administrator`;
if (teamData.whitelist[formatid]?.length) {
rankNeeded = `staff in ${Chat.toListString(teamData.whitelist[formatid], "or")}`;
}
throw new Chat.ErrorMessage(`Access denied. You need to be ${rankNeeded} to add teams for ${formatid}`);
}
teamName = teamName.trim();
category = category.trim();
this.initializeFormat(formatid);
if (this.findTeamName(formatid, category, teamName)) {
throw new Chat.ErrorMessage(`There is already a team for ${formatid} with the name ${teamName} in the ${category} category.`);
}
if (!teamData.teams[formatid][category])
this.addCategory(user, formatid, category);
teamData.teams[formatid][category][teamName] = Teams.pack(Teams.import(team.trim()));
save();
return teamData.teams[formatid][category][teamName];
}
removeTeam(user, formatid, teamid, category) {
formatid = this.sanitizeFormat(formatid, false);
category = category.trim();
if (!this.checkPermissions(user, teamData.whitelist[formatid])) {
let required = `an administrator`;
if (teamData.whitelist[formatid]) {
required = `staff in ${Chat.toListString(teamData.whitelist[formatid], "or")}`;
}
throw new Chat.ErrorMessage(`Access denied. You need to be ${required} to add teams for ${formatid}`);
}
const categoryName = this.findCategory(formatid, category);
if (!categoryName) {
throw new Chat.ErrorMessage(`There are no teams for ${formatid} under the category ${category.trim()}. Check spelling?`);
}
const teamName = this.findTeamName(formatid, category, teamid);
if (!teamName) {
throw new Chat.ErrorMessage(`There is no team for ${formatid} with the name of "${teamid}". Check spelling?`);
}
const oldTeam = teamData.teams[formatid][categoryName][teamName];
delete teamData.teams[formatid][categoryName][teamName];
if (!Object.keys(teamData.teams[formatid][categoryName]).length)
delete teamData.teams[formatid][categoryName];
if (!Object.keys(teamData.teams[formatid]).filter((x) => x !== "uncategorized").length)
delete teamData.teams[formatid];
save();
return oldTeam;
}
formatTeam(teamName, teamStr, broadcasting = false) {
const team = Teams.unpack(teamStr);
if (!team)
return `Team is not correctly formatted. PM room staff to fix the formatting.`;
let buf = ``;
if (!broadcasting) {
buf += `<center><strong style="letter-spacing:1.2pt">${team.map((x) => `<psicon pokemon="${x.species}" />`).join("")}`;
buf += `<br />${import_lib.Utils.escapeHTML(teamName.toUpperCase())}</strong></center>`;
buf += Chat.getReadmoreCodeBlock(Teams.export(team).trim());
} else {
buf += `<details><summary>${team.map((x) => `<psicon pokemon="${x.species}" />`).join("")} &ndash; ${import_lib.Utils.escapeHTML(teamName)}</summary>`;
buf += `<code style="white-space: pre-wrap; display: table; tab-size: 3">${Teams.export(team).trim().replace(/\n/g, "<br />")}</code></details>`;
}
return buf;
}
modlog(context, formatid, action, note, log) {
formatid = this.sanitizeFormat(formatid);
const whitelistedRooms = this.whitelistedRooms(formatid);
if (whitelistedRooms?.length) {
for (const roomid of whitelistedRooms) {
const room = Rooms.get(roomid);
if (!room)
continue;
context.room = room;
context.modlog(action, null, `${formatid}: ${note}`);
context.privateModAction(log);
}
} else {
context.room = Rooms.get("staff") || null;
context.globalModlog(action, null, `${formatid}: ${note}`);
context.privateGlobalModAction(log);
}
}
/**
* Returns the category name of the provided category ID if there is one.
*/
findCategory(formatid, categoryid) {
formatid = toID(formatid);
categoryid = toID(categoryid);
let match = null;
for (const categoryName in teamData.teams[formatid] || {}) {
if (toID(categoryName) === categoryid) {
match = categoryName;
break;
}
}
return match;
}
findTeamName(formatid, categoryid, teamid) {
const categoryName = this.findCategory(formatid, categoryid);
if (!categoryName)
return null;
let match = null;
for (const teamName in teamData.teams[formatid][categoryName] || {}) {
if (toID(teamName) === teamid) {
match = teamName;
break;
}
}
return match;
}
getFormatName(formatid) {
return Dex.formats.get(formatid).exists ? Dex.formats.get(formatid).name : formatid;
}
destroy() {
for (const formatid in teamData.whitelist) {
for (const [i, roomid] of teamData.whitelist[formatid].entries()) {
const room = Rooms.search(roomid);
if (room)
continue;
teamData.whitelist[formatid].splice(i, 1);
if (!teamData.whitelist[formatid].length)
delete teamData.whitelist[formatid];
save();
}
}
}
}();
const destroy = SampleTeams.destroy;
const handlers = {
onRenameRoom(oldID, newID) {
for (const formatid in teamData.whitelist) {
if (!SampleTeams.whitelistedRooms(formatid)?.includes(oldID))
continue;
SampleTeams.unwhitelistRoom(formatid, oldID);
SampleTeams.whitelistRooms([formatid], [newID]);
}
}
};
const commands = {
sampleteams: {
""(target, room, user) {
this.runBroadcast();
let [formatid, category] = target.split(",");
if (!this.broadcasting) {
if (!formatid)
return this.parse(`/j view-sampleteams-view`);
formatid = SampleTeams.sanitizeFormat(formatid);
if (!category)
return this.parse(`/j view-sampleteams-view-${formatid}`);
const categoryName = SampleTeams.findCategory(formatid, category);
return this.parse(`/j view-sampleteams-view-${formatid}${categoryName ? "-" + toID(categoryName) : ""}`);
}
if (!formatid)
return this.parse(`/help sampleteams`);
formatid = SampleTeams.sanitizeFormat(formatid);
if (!teamData.teams[formatid]) {
throw new Chat.ErrorMessage(`No teams for ${SampleTeams.getFormatName(formatid)} found. Check spelling?`);
}
let buf = ``;
if (!category) {
for (const categoryName in teamData.teams[formatid]) {
if (!Object.keys(teamData.teams[formatid][categoryName]).length)
continue;
if (buf)
buf += `<hr />`;
buf += `<details${Object.keys(teamData.teams[formatid]).length < 2 ? ` open` : ``}><summary><strong style="letter-spacing:1.2pt">${categoryName.toUpperCase()}</strong></summary>`;
for (const [i, teamName] of Object.keys(teamData.teams[formatid][categoryName]).entries()) {
if (i)
buf += `<hr />`;
buf += SampleTeams.formatTeam(teamName, teamData.teams[formatid][categoryName][teamName], true);
}
buf += `</details>`;
}
if (!buf) {
throw new Chat.ErrorMessage(`No teams for ${SampleTeams.getFormatName(formatid)} found. Check spelling?`);
} else {
buf = `<center><h3>Sample Teams for ${SampleTeams.getFormatName(formatid)}</h3></center><hr />${buf}`;
}
} else {
const categoryName = SampleTeams.findCategory(formatid, category);
if (!categoryName) {
throw new Chat.ErrorMessage(`No teams for ${SampleTeams.getFormatName(formatid)} in the ${category} category found. Check spelling?`);
}
for (const teamName in teamData.teams[formatid][categoryName]) {
buf += SampleTeams.formatTeam(teamName, teamData.teams[formatid][categoryName][teamName], true);
}
}
this.sendReplyBox(buf);
},
addcategory(target, room, user) {
let [formatid, categoryName] = target.split(",");
if (!(formatid && categoryName))
return this.parse(`/help sampleteams`);
if (!categoryName.trim())
categoryName = "uncategorized";
SampleTeams.addCategory(user, formatid, categoryName.trim());
SampleTeams.modlog(
this,
formatid,
"ADDTEAMCATEGORY",
categoryName.trim(),
`${user.name} added ${categoryName.trim()} as a category for ${formatid}.`
);
this.sendReply(`Added ${categoryName.trim()} as a category for ${formatid}.`);
},
removecategory(target, room, user) {
const [formatid, categoryName] = target.split(",");
if (!(formatid && categoryName))
return this.parse(`/help sampleteams`);
if (toID(categoryName) === "uncategorized") {
throw new Chat.ErrorMessage(`The uncategorized category cannot be removed.`);
}
SampleTeams.removeCategory(user, formatid, categoryName);
SampleTeams.modlog(
this,
formatid,
"REMOVETEAMCATEGORY",
categoryName.trim(),
`${user.name} removed ${categoryName.trim()} as a category for ${formatid}.`
);
this.sendReply(`Removed ${categoryName.trim()} as a category for ${formatid}.`);
},
add(target, room, user) {
const [formatid, category, teamName, team] = target.split(",");
if (!(formatid && category?.trim() && teamName && team))
return this.parse("/j view-sampleteams-add");
const packedTeam = SampleTeams.addTeam(user, formatid, teamName, team, category);
SampleTeams.modlog(
this,
formatid,
"ADDTEAM",
`${category}: ${teamName}: ${packedTeam}`,
`${user.name} added a team for ${formatid} in the ${category} category.`
);
this.sendReply(`Added a team for ${formatid} in the ${category} category.`);
},
remove(target, room, user) {
const [formatid, category, teamName] = target.split(",").map((x) => x.trim());
if (!(formatid && category && teamName))
return this.parse(`/help sampleteams`);
const team = SampleTeams.removeTeam(user, formatid, toID(teamName), category);
SampleTeams.modlog(
this,
formatid,
"REMOVETEAM",
`${category}: ${teamName}: ${team}`,
`${user.name} removed a team from ${formatid} in the ${category} category.`
);
this.sendReply(`Removed a team from ${formatid} in the ${category} category.`);
},
whitelist: {
add(target, room, user) {
if (!SampleTeams.isDevMod(user)) {
this.checkCan("bypassall");
}
const [formatids, roomids] = target.split("|").map((x) => x.split(","));
if (!(formatids?.length && roomids?.length))
return this.parse(`/help sampleteams`);
SampleTeams.whitelistRooms(formatids, roomids);
this.privateGlobalModAction(`${user.name} whitelisted ${Chat.toListString(roomids.map((x) => Rooms.search(x).title))} to handle sample teams for ${Chat.toListString(formatids)}.`);
this.globalModlog(`SAMPLETEAMS WHITELIST`, null, roomids.join(", "));
this.sendReply(`Whitelisted ${Chat.toListString(roomids)} to handle sample teams for ${Chat.toListString(formatids)}.`);
},
remove(target, room, user) {
if (!SampleTeams.isDevMod(user)) {
this.checkCan("bypassall");
}
const [formatid, roomid] = target.split(",");
if (!(formatid && roomid))
return this.parse(`/help sampleteams`);
SampleTeams.unwhitelistRoom(formatid, roomid);
this.refreshPage("sampleteams-whitelist");
},
"": "view",
view(target, room, user) {
if (!SampleTeams.isDevMod(user)) {
this.checkCan("bypassall");
}
this.parse(`/j view-sampleteams-whitelist`);
}
}
},
sampleteamshelp: [
`/sampleteams [format] - Lists the sample teams for [format], if there are any.`,
`/sampleteams addcategory/removecategory [format], [category] - Adds/removes categories for [format].`,
`/sampleteams add - Pulls up the interface to add sample teams. Requires: Room staff in dedicated tier room, &`,
`/sampleteams remove [format], [category], [team name] - Removes a sample team for [format] in [category].`,
`/sampleteams whitelist add [formatid], [formatid] | [roomid], [roomid], ... - Whitelists room staff for the provided roomids to add sample teams. Requires: &`,
`/sampleteams whitelist remove [formatid], [roomid] - Unwhitelists room staff for the provided room to add sample teams. Requires: &`
]
};
function formatFakeButton(url, text) {
return `<a class="button" style="text-decoration:inherit" target="replace" href="${url}">${text}</a>`;
}
const pages = {
sampleteams: {
whitelist(query, user, connection) {
this.title = `Sample Teams Whitelist`;
if (!(SampleTeams.isDevMod(user) || user.can("bypassall"))) {
return `<div class="pad"><h2>Access denied.</h2></div>`;
}
const staffRoomAccess = Rooms.get("staff")?.checkModjoin(user);
let buf = `<div class="pad"><button style="float:right" class="button" name="send" value="/j view-sampleteams-whitelist${query.length ? `-${query.join("-")}` : ""}"><i class="fa fa-refresh"></i> Refresh</button><h2>Sample Teams Rooms Whitelist</h2>`;
if ((!teamData.whitelist || !Object.keys(teamData.whitelist).length) && !query.length) {
buf += `<p>No rooms are whitelisted for any formats.</p>`;
}
if (query[0] === "add") {
buf += `<form data-submitsend="${staffRoomAccess ? `/msgroom staff,` : SampleTeams.isDevMod(user) ? `/msgroom development,` : ``}/sampleteams whitelist add {formats}|{roomids}">`;
buf += `<label>Enter a list formats, separated by comma: <input name="formats" /></label><br /><br />`;
buf += `<label>Enter a list of rooms, separated by comma: <input name="roomids" /></label><br />`;
buf += `<br /><button class="button" type="submit">Whitelist rooms</button></form>`;
buf += `<br />${formatFakeButton("view-sampleteams-whitelist", "Return to list")}`;
} else {
buf += `<dl>`;
for (const formatid of Object.keys(teamData.whitelist).sort().reverse()) {
if (!teamData.whitelist[formatid]?.length)
continue;
buf += `<dt>${SampleTeams.getFormatName(formatid)}</dt>`;
for (const roomid of teamData.whitelist[formatid]) {
buf += `<dd>${Rooms.get(roomid)?.title || roomid}`;
buf += ` <button class="button" name="send" value="/sampleteams whitelist remove ${formatid},${roomid}">Remove</button></dd>`;
}
}
buf += `</dl>`;
}
buf += `${query.length ? "" : formatFakeButton("view-sampleteams-whitelist-add", "Whitelist room")}</div>`;
return buf;
},
view(query, user, connection) {
this.title = `Sample Teams`;
let buf = `<div class="pad">`;
if (query.slice(0, query.length - 1).join("-")) {
buf += `${formatFakeButton(`view-sampleteams-view-${query.slice(0, query.length - 1).join("-")}`, "&laquo; Back")}`;
} else {
buf += `<button class="button disabled" disabled>&laquo; Back</button>`;
}
buf += `<button style="float:right" class="button" name="send" value="/j view-sampleteams-view${query.join("-") ? `-${query.join("-")}` : ``}"><i class="fa fa-refresh"></i> Refresh</button>`;
buf += `<center><h2>Sample Teams</h2></center><hr />`;
const q0Teams = teamData.teams[query[0]];
const q0TeamKeys = q0Teams ? Object.keys(q0Teams) : [];
if (!query[0]) {
const formats = Object.keys(teamData.teams);
if (!formats.length)
return `${buf}<p>No teams found.</p></div>`;
buf += `<h3>Pick a format</h3><ul>`;
for (const formatid of formats) {
if (!formatid)
continue;
buf += `<li>${formatFakeButton(`view-sampleteams-view-${formatid}`, `${SampleTeams.getFormatName(formatid)}`)}</button></li>`;
}
buf += `</ul>`;
} else if (!q0Teams || !q0TeamKeys.length || !Object.keys(q0Teams.uncategorized).length && !q0TeamKeys.filter((x) => x !== "uncategorized").length) {
const name = Dex.formats.get(query[0]).exists ? Dex.formats.get(query[0]).name : query[0];
return `${buf}<p>No teams for ${name} were found.</p></div>`;
} else if (!query[1] || !SampleTeams.findCategory(query[0], query[1]) && query[1] !== "allteams") {
buf += `<h3>Pick a category</h3><ul>`;
for (const category of Object.keys(teamData.teams[query[0]])) {
buf += `<li><a class="button" style="text-decoration:inherit;color:inherit" target="replace" href="view-sampleteams-view-${query[0]}-${toID(category)}">${category}</button></li>`;
}
buf += `<li><a class="button" style="text-decoration:inherit;color:inherit" target="replace" href="view-sampleteams-view-${query[0]}-allteams">ALL</button></li></ul>`;
} else if (query[1] === "allteams") {
buf += `<h3>All teams for ${SampleTeams.getFormatName(query[0])}</h3>`;
for (const categoryName in teamData.teams[query[0]]) {
const category = teamData.teams[query[0]][categoryName];
if (!Object.keys(category).length)
continue;
buf += `<details><summary><h4 style="display:inline">${categoryName}</h4></summary>`;
for (const teamName in category) {
const team = category[teamName];
if (SampleTeams.checkPermissions(user, teamData.whitelist[query[0]] || [])) {
buf += `<button class="button" style="float:right" name="send" value="/sampleteams remove ${query[0]},${categoryName},${teamName}">Delete team</button>`;
}
buf += SampleTeams.formatTeam(teamName, team);
}
buf += `</details>`;
const index = Object.keys(teamData.teams[query[0]]).indexOf(categoryName);
if (index !== Object.keys(teamData.teams[query[0]]).length - 1)
buf += `<hr />`;
}
} else if (SampleTeams.findCategory(query[0], query[1])) {
const categoryName = SampleTeams.findCategory(query[0], query[1]);
buf += `<h3>Sample teams for ${SampleTeams.getFormatName(query[0])} in the ${categoryName} category</h3>`;
for (const teamName in teamData.teams[query[0]][categoryName]) {
const team = teamData.teams[query[0]][categoryName][teamName];
buf += SampleTeams.formatTeam(teamName, team);
}
}
buf += `</div>`;
return buf;
},
add(query, user, connection) {
this.title = `Sample Teams`;
const trimFormatName = (name) => (name.includes("(") ? name.slice(0, name.indexOf("(")) : name).trim();
const formatsSet = new Set(Dex.formats.all().map((format) => trimFormatName(format.name)));
const formatsArr = Array.from(formatsSet);
const formats = formatsArr.map((formatName) => Dex.formats.get(formatName)).filter((format) => !format.name.includes("Custom") && format.effectType === "Format" && !format.team && SampleTeams.checkPermissions(user, SampleTeams.whitelistedRooms(format.id) || []));
if (!formats.length)
return `<div class="pad"><h2>Access denied.</h2></div>`;
let buf = `<div class="pad">`;
if (query.slice(0, query.length - 1).join("-")) {
buf += `${formatFakeButton(`view-sampleteams-add-${query.slice(0, query.length - 1).join("-")}`, "&laquo; Back")}`;
} else {
buf += `<button class="button disabled" disabled>&laquo; Back</button>`;
}
let buttonTitle = "Refresh";
if (query[2] === "submit")
buttonTitle = "Add another team";
buf += `<button style="float:right" class="button" name="send" value="/j view-sampleteams-add${query.join("-") ? `-${query.join("-")}` : ``}"><i class="fa fa-refresh"></i> ${buttonTitle}</button>`;
buf += `<div class="pad"><h2>Add a sample team</h2>`;
if (!query[0] || !Dex.formats.get(query[0]).exists) {
buf += `<h3>Pick a format</h3><ul>`;
for (const format of formats) {
buf += `<li>${formatFakeButton(`view-sampleteams-add-${format.id}`, format.name)}</button></li>`;
}
buf += `</ul>`;
} else if (!query[1] || !SampleTeams.findCategory(query[0], query[1]) || query[1] === "addnewcategory") {
const name = SampleTeams.getFormatName(query[0]);
if (query[1] === "addnewcategory") {
buf += `<h3>Add a category for ${name}</h3>`;
buf += `<form data-submitsend="/sampleteams addcategory ${query[0]},{categoryname}">`;
buf += `<input name="categoryname" />`;
buf += `<button class="button" type="submit">Add category</button></form>`;
} else {
buf += `<h3>Pick a category for ${name}</h3><ul>`;
for (const category of Object.keys(teamData.teams[query[0]] || {}) || []) {
buf += `<li style="padding-top:5px">${formatFakeButton(`view-sampleteams-add-${query[0]}-${toID(category)}-submit`, category)}</li>`;
}
buf += `<li style="padding-top:5px">${formatFakeButton(`view-sampleteams-add-${query[0]}-addnewcategory`, `<strong>Add new category</strong>`)}</li></ul>`;
}
}
const categoryName = SampleTeams.findCategory(query[0], query[1]);
if (categoryName) {
buf += `<form data-submitsend="/sampleteams add ${query[0]}, ${categoryName}, {teamName}, {team}">`;
buf += `<h3>Enter a team name</h3><input name="teamName" />`;
buf += `<h3>Enter team importable</h3><textarea style="width:100%;height:400px" name="team"></textarea><br />`;
buf += `<button class="button" type="submit">Add sample team</button></form>`;
}
buf += `</div>`;
return buf;
}
}
};
Chat.multiLinePattern.register(`/sampleteams add `);
//# sourceMappingURL=sample-teams.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/sample-teams.ts"],
"sourcesContent": ["/**\r\n * A sample teams plugin\r\n *\r\n * @author Kris\r\n */\r\n\r\nimport {FS, Utils} from \"../../lib\";\r\n\r\nconst SAMPLE_TEAMS = 'config/chat-plugins/sample-teams.json';\r\n\r\ninterface SampleTeamsData {\r\n\twhitelist: {[formatid: string]: RoomID[]};\r\n\t/** Teams are stored in the packed format */\r\n\tteams: {\r\n\t\t[formatid: string]: {\r\n\t\t\tuncategorized: {[k: string]: string},\r\n\t\t\t[category: string]: {[teamName: string]: string},\r\n\t\t},\r\n\t};\r\n}\r\n\r\nexport const teamData: SampleTeamsData = (() => {\r\n\ttry {\r\n\t\treturn JSON.parse(FS(SAMPLE_TEAMS).readIfExistsSync());\r\n\t} catch {\r\n\t\treturn {\r\n\t\t\twhitelist: {},\r\n\t\t\tteams: {},\r\n\t\t};\r\n\t}\r\n})();\r\n\r\nfunction save() {\r\n\tFS(SAMPLE_TEAMS).writeUpdate(() => JSON.stringify(teamData));\r\n}\r\n\r\nfor (const formatid in teamData.teams) {\r\n\tif (!teamData.teams[formatid].uncategorized) teamData.teams[formatid].uncategorized = {};\r\n}\r\nsave();\r\n\r\nexport const SampleTeams = new class SampleTeams {\r\n\tprivate isRoomStaff(user: User, roomids: RoomID[]) {\r\n\t\tlet matched = false;\r\n\t\tif (!roomids?.length) return false;\r\n\t\tfor (const roomid of roomids) {\r\n\t\t\tconst room = Rooms.search(roomid);\r\n\t\t\t// Malformed entry from botched room rename\r\n\t\t\tif (!room) continue;\r\n\t\t\tmatched = room.auth.isStaff(user.id);\r\n\t\t\tif (matched) break;\r\n\t\t}\r\n\t\treturn matched;\r\n\t}\r\n\r\n\tisDevMod(user: User) {\r\n\t\treturn !!Rooms.get('development')?.auth.atLeast(user, '@');\r\n\t}\r\n\r\n\tcheckPermissions(user: User, roomids: RoomID[]) {\r\n\t\t// Give Development room mods access to help fix crashes\r\n\t\treturn this.isRoomStaff(user, roomids) || user.can('bypassall') || this.isDevMod(user);\r\n\t}\r\n\r\n\twhitelistedRooms(formatid: string, names = false) {\r\n\t\tformatid = this.sanitizeFormat(formatid);\r\n\t\tif (!teamData.whitelist[formatid]?.length) return null;\r\n\t\treturn Utils.sortBy(teamData.whitelist[formatid], (x) => {\r\n\t\t\tif (!names) return x;\r\n\t\t\tconst room = Rooms.search(x);\r\n\t\t\tif (!room) return x;\r\n\t\t\treturn room.title;\r\n\t\t});\r\n\t}\r\n\r\n\twhitelistRooms(formatids: string[], roomids: string[]) {\r\n\t\tfor (const unsanitizedFormatid of formatids) {\r\n\t\t\tconst formatid = this.sanitizeFormat(unsanitizedFormatid);\r\n\t\t\tif (!teamData.whitelist[formatid]) teamData.whitelist[formatid] = [];\r\n\t\t\tfor (const roomid of roomids) {\r\n\t\t\t\tconst targetRoom = Rooms.search(roomid);\r\n\t\t\t\tif (!targetRoom?.persist) {\r\n\t\t\t\t\tthrow new Chat.ErrorMessage(`Room ${roomid} not found. Check spelling?`);\r\n\t\t\t\t}\r\n\t\t\t\tif (teamData.whitelist[formatid].includes(targetRoom.roomid)) {\r\n\t\t\t\t\tthrow new Chat.ErrorMessage(`Room ${targetRoom.title} is already added.`);\r\n\t\t\t\t}\r\n\t\t\t\tteamData.whitelist[formatid].push(targetRoom.roomid);\r\n\t\t\t\tsave();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tunwhitelistRoom(formatid: string, roomid: string) {\r\n\t\tformatid = this.sanitizeFormat(formatid, false);\r\n\t\tconst targetRoom = Rooms.search(roomid);\r\n\t\tif (!targetRoom?.persist) throw new Chat.ErrorMessage(`Room ${roomid} not found. Check spelling?`);\r\n\t\tif (!teamData.whitelist[formatid]?.length) throw new Chat.ErrorMessage(`No rooms are whitelisted for ${formatid}.`);\r\n\t\tif (!teamData.whitelist[formatid].includes(targetRoom.roomid)) {\r\n\t\t\tthrow new Chat.ErrorMessage(`Room ${targetRoom.title} isn't whitelisted.`);\r\n\t\t}\r\n\t\tconst index = teamData.whitelist[formatid].indexOf(targetRoom.roomid);\r\n\t\tteamData.whitelist[formatid].splice(index, 1);\r\n\t\tif (!teamData.whitelist[formatid].length) delete teamData.whitelist[formatid];\r\n\t\tsave();\r\n\t}\r\n\r\n\tsanitizeFormat(formatid: string, checkExists = false) {\r\n\t\tconst format = Dex.formats.get(formatid);\r\n\t\tif (checkExists && !format.exists) {\r\n\t\t\tthrow new Chat.ErrorMessage(`Format \"${formatid.trim()}\" not found. Check spelling?`);\r\n\t\t}\r\n\t\tif (format.team) {\r\n\t\t\tthrow new Chat.ErrorMessage(`Formats with computer-generated teams can't have team storage.`);\r\n\t\t}\r\n\t\treturn format.id;\r\n\t}\r\n\r\n\tinitializeFormat(formatid: string) {\r\n\t\tif (!teamData.teams[formatid]) {\r\n\t\t\tteamData.teams[formatid] = {uncategorized: {}};\r\n\t\t\tsave();\r\n\t\t}\r\n\t}\r\n\r\n\taddCategory(user: User, formatid: string, category: string) {\r\n\t\tformatid = this.sanitizeFormat(formatid);\r\n\t\tif (!this.checkPermissions(user, teamData.whitelist[formatid])) {\r\n\t\t\tlet rankNeeded = `a global administrator`;\r\n\t\t\tif (teamData.whitelist[formatid]) {\r\n\t\t\t\trankNeeded = `staff in ${Chat.toListString(teamData.whitelist[formatid], \"or\")}`;\r\n\t\t\t}\r\n\t\t\tthrow new Chat.ErrorMessage(`Access denied. You need to be ${rankNeeded} to add teams for ${formatid}`);\r\n\t\t}\r\n\t\tcategory = category.trim();\r\n\t\tthis.initializeFormat(formatid);\r\n\t\tif (this.findCategorLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,iBAAwB;AAExB,MAAM,eAAe;AAad,MAAM,YAA6B,MAAM;AAC/C,MAAI;AACH,WAAO,KAAK,UAAM,eAAG,YAAY,EAAE,iBAAiB,CAAC;AAAA,EACtD,QAAE;AACD,WAAO;AAAA,MACN,WAAW,CAAC;AAAA,MACZ,OAAO,CAAC;AAAA,IACT;AAAA,EACD;AACD,GAAG;AAEH,SAAS,OAAO;AACf,qBAAG,YAAY,EAAE,YAAY,MAAM,KAAK,UAAU,QAAQ,CAAC;AAC5D;AAEA,WAAW,YAAY,SAAS,OAAO;AACtC,MAAI,CAAC,SAAS,MAAM,QAAQ,EAAE;AAAe,aAAS,MAAM,QAAQ,EAAE,gBAAgB,CAAC;AACxF;AACA,KAAK;AAEE,MAAM,cAAc,IAAI,MAAMA,aAAY;AAAA,EACxC,YAAY,MAAY,SAAmB;AAClD,QAAI,UAAU;AACd,QAAI,CAAC,SAAS;AAAQ,aAAO;AAC7B,eAAW,UAAU,SAAS;AAC7B,YAAM,OAAO,MAAM,OAAO,MAAM;AAEhC,UAAI,CAAC;AAAM;AACX,gBAAU,KAAK,KAAK,QAAQ,KAAK,EAAE;AACnC,UAAI;AAAS;AAAA,IACd;AACA,WAAO;AAAA,EACR;AAAA,EAEA,SAAS,MAAY;AACpB,WAAO,CAAC,CAAC,MAAM,IAAI,aAAa,GAAG,KAAK,QAAQ,MAAM,GAAG;AAAA,EAC1D;AAAA,EAEA,iBAAiB,MAAY,SAAmB;AAE/C,WAAO,KAAK,YAAY,MAAM,OAAO,KAAK,KAAK,IAAI,WAAW,KAAK,KAAK,SAAS,IAAI;AAAA,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__defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var scavenger_games_exports = {};
__export(scavenger_games_exports, {
ScavMods: () => ScavMods,
ScavengerGameTemplate: () => ScavengerGameTemplate
});
module.exports = __toCommonJS(scavenger_games_exports);
var import_scavengers = require("./scavengers");
var import_lib = require("../../lib");
/**
* Scavengers Games Plugin
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This plugin stores the different possible game modes and twists that take place in scavengers room
*
* @license MIT license
*/
function toSeconds(time) {
const parts = time.split(":").reverse();
return parts.map((value, index) => parseInt(value) * Math.pow(60, index)).reduce((a, b) => a + b);
}
class Leaderboard {
constructor() {
this.data = {};
}
addPoints(name, aspect, points, noUpdate) {
const userid = toID(name);
if (!userid || userid === "constructor" || !points)
return this;
if (!this.data[userid])
this.data[userid] = { name };
if (!this.data[userid][aspect])
this.data[userid][aspect] = 0;
this.data[userid][aspect] += points;
if (!noUpdate)
this.data[userid].name = name;
return this;
}
visualize(sortBy, userid) {
return new Promise((resolve, reject) => {
let lowestScore = Infinity;
let lastPlacement = 1;
const ladder = import_lib.Utils.sortBy(
Object.entries(this.data).filter(([u, bit]) => sortBy in bit),
([u, bit]) => -bit[sortBy]
).map(([u, bit], i) => {
if (bit[sortBy] !== lowestScore) {
lowestScore = bit[sortBy];
lastPlacement = i + 1;
}
return {
rank: lastPlacement,
...bit
};
});
if (userid) {
const rank = ladder.find((entry) => toID(entry.name) === userid);
resolve(rank);
} else {
resolve(ladder);
}
});
}
async htmlLadder() {
const data = await this.visualize("points");
const display = `<div class="ladder" style="overflow-y: scroll; max-height: 170px;"><table style="width: 100%"><tr><th>Rank</th><th>Name</th><th>Points</th></tr>${data.map((line) => `<tr><td>${line.rank}</td><td>${line.name}</td><td>${line.points}</td></tr>`).join("")}</table></div>`;
return display;
}
}
const TWISTS = {
perfectscore: {
name: "Perfect Score",
id: "perfectscore",
desc: "Players who finish the hunt without submitting a single wrong answer get a shoutout!",
onLeave(player) {
if (!this.leftGame)
this.leftGame = [];
this.leftGame.push(player.id);
},
onSubmitPriority: 1,
onSubmit(player, value) {
const currentQuestion = player.currentQuestion;
if (!player.answers)
player.answers = {};
if (!player.answers[currentQuestion])
player.answers[currentQuestion] = [];
if (player.answers[currentQuestion].includes(value))
return;
player.answers[currentQuestion].push(value);
},
onComplete(player, time, blitz) {
const isPerfect = !this.leftGame?.includes(player.id) && Object.values(player.answers).every((attempts) => attempts.length <= 1);
return { name: player.name, time, blitz, isPerfect };
},
onAfterEndPriority: 1,
onAfterEnd(isReset) {
if (isReset)
return;
const perfect = this.completed.filter((entry) => entry.isPerfect).map((entry) => entry.name);
if (perfect.length) {
this.announce(import_lib.Utils.html`${Chat.toListString(perfect)} ${perfect.length > 1 ? "have" : "has"} completed the hunt without a single wrong answer!`);
}
}
},
bonusround: {
name: "Bonus Round",
id: "bonusround",
desc: "Players can choose whether or not they choose to complete the 4th question.",
onAfterLoad() {
if (this.questions.length === 3) {
this.announce("This twist requires at least four questions. Please reset the hunt and make it again.");
this.huntLocked = true;
} else {
this.questions[this.questions.length - 1].hint += " (You may choose to skip this question using ``/scavenge skip``.)";
}
},
onAnySubmit(player) {
if (this.huntLocked) {
player.sendRoom("The hunt was not set up correctly. Please wait for the host to reset the hunt and create a new one.");
return true;
}
},
onSubmitPriority: 1,
onSubmit(player, value) {
const currentQuestion = player.currentQuestion;
if (value === "skip" && currentQuestion + 1 === this.questions.length) {
player.sendRoom("You have opted to skip the current question.");
player.skippedQuestion = true;
this.onComplete(player);
return true;
}
},
onComplete(player, time, blitz) {
const noSkip = !player.skippedQuestion;
return { name: player.name, time, blitz, noSkip };
},
onAfterEndPriority: 1,
onAfterEnd(isReset) {
if (isReset)
return;
const noSkip = this.completed.filter((entry) => entry.noSkip).map((entry) => entry.name);
if (noSkip.length) {
this.announce(import_lib.Utils.html`${Chat.toListString(noSkip)} ${noSkip.length > 1 ? "have" : "has"} completed the hunt without skipping the last question!`);
}
}
},
incognito: {
name: "Incognito",
id: "incognito",
desc: "Upon answering the last question correctly, the player's finishing time will not be announced in the room! Results will only be known at the end of the hunt.",
onCorrectAnswer(player, value) {
if (player.currentQuestion + 1 >= this.questions.length) {
this.runEvent("PreComplete", player);
player.sendRoom(`Congratulations! You have gotten the correct answer.`);
player.sendRoom(`This is a special style where finishes aren't announced! To see your placement, wait for the hunt to end. Until then, it's your secret that you finished!`);
return false;
}
},
onPreComplete(player) {
const now = Date.now();
const time = Chat.toDurationString(now - this.startTime, { hhmmss: true });
const canBlitz = this.completed.length < 3;
const blitz = now - this.startTime <= 6e4 && canBlitz && (this.room.settings.scavSettings?.blitzPoints?.[this.gameType] || this.gameType === "official");
const result = this.runEvent("Complete", player, time, blitz) || { name: player.name, time, blitz };
this.preCompleted = this.preCompleted ? [...this.preCompleted, result] : [result];
player.completed = true;
player.destroy();
},
onEnd() {
this.completed = this.preCompleted || [];
}
},
spamfilter: {
name: "Spam Filter",
id: "spamfilter",
desc: "Every wrong answer adds 30 seconds to your final time!",
onIncorrectAnswer(player, value) {
if (!player.incorrect)
player.incorrect = [];
const id = `${player.currentQuestion}-${value}`;
if (player.incorrect.includes(id))
return;
player.incorrect.push(id);
},
onComplete(player, time, blitz) {
const seconds = toSeconds(time);
if (!player.incorrect)
return { name: player.name, total: seconds, blitz, time, original_time: time };
const total = seconds + 30 * player.incorrect.length;
const finalTime = Chat.toDurationString(total * 1e3, { hhmmss: true });
if (total > 60)
blitz = false;
return { name: player.name, total, blitz, time: finalTime, original_time: time };
},
onConfirmCompletion(player, time, blitz, place, result) {
blitz = result.blitz;
time = result.time;
const deductionMessage = player.incorrect?.length ? Chat.count(player.incorrect, "incorrect guesses", "incorrect guess") : "Perfect!";
return `<em>${import_lib.Utils.escapeHTML(player.name)}</em> has finished the hunt! (Final Time: ${time} - ${deductionMessage}${blitz ? " - BLITZ" : ""})`;
},
onEnd() {
import_lib.Utils.sortBy(this.completed, (entry) => entry.total);
}
},
blindincognito: {
name: "Blind Incognito",
id: "blindincognito",
desc: "Upon completing the last question, neither you nor other players will know if the last question is correct! You may be in for a nasty surprise when the hunt ends!",
onAnySubmit(player, value) {
if (player.precompleted) {
player.sendRoom(`That may or may not be the right answer - if you aren't confident, you can try again!`);
return true;
}
},
onCorrectAnswer(player, value) {
if (player.currentQuestion + 1 >= this.questions.length) {
this.runEvent("PreComplete", player);
player.sendRoom(`That may or may not be the right answer - if you aren't confident, you can try again!`);
return true;
}
},
onIncorrectAnswer(player, value) {
if (player.currentQuestion + 1 >= this.questions.length) {
player.sendRoom(`That may or may not be the right answer - if you aren't confident, you can try again!`);
return false;
}
},
onPreComplete(player) {
const now = Date.now();
const time = Chat.toDurationString(now - this.startTime, { hhmmss: true });
const canBlitz = this.completed.length < 3;
const blitz = now - this.startTime <= 6e4 && canBlitz && (this.room.settings.scavSettings?.blitzPoints?.[this.gameType] || this.gameType === "official");
const result = this.runEvent("Complete", player, time, blitz) || { name: player.name, time, blitz };
this.preCompleted = this.preCompleted ? [...this.preCompleted, result] : [result];
player.precompleted = true;
},
onEnd() {
this.completed = this.preCompleted || [];
}
},
timetrial: {
name: "Time Trial",
id: "timetrial",
desc: "Time starts when the player starts the hunt!",
onAfterLoad() {
if (this.questions.length === 3) {
this.announce("This twist requires at least four questions. Please reset the hunt and make it again.");
this.huntLocked = true;
}
this.altIps = {};
this.startTimes = {};
},
onJoin(user) {
if (!Config.noipchecks) {
const altIp = user.ips.find((ip) => this.altIps[ip] && this.altsIps[ip].id !== user.id);
if (altIp) {
user.sendTo(this.room, `You already have started the hunt as ${this.altIps[altIp].name}.`);
return true;
}
}
if (!this.startTimes[user.id])
this.startTimes[user.id] = Date.now();
if (this.addPlayer(user)) {
this.cacheUserIps(user);
delete this.leftHunt[user.id];
user.sendTo(this.room, "You joined the scavenger hunt! Use the command /scavenge to answer.");
this.onSendQuestion(user);
} else {
user.sendTo(this.room, "You have already joined the hunt.");
}
return true;
},
onLeave(user) {
for (const ip of user.ips) {
this.altIps[ip] = { id: user.id, name: user.name };
}
},
onAnySubmit(player) {
if (this.huntLocked) {
player.sendRoom("The hunt was not set up correctly. Please wait for the host to reset the hunt and create a new one.");
return true;
}
},
onComplete(player, time, blitz) {
const now = Date.now();
const takenTime = Chat.toDurationString(now - this.startTimes[player.id], { hhmmss: true });
const result = { name: player.name, id: player.id, time: takenTime, blitz };
this.completed.push(result);
const place = import_lib.Utils.formatOrder(this.completed.length);
this.announce(
import_lib.Utils.html`<em>${result.name}</em> is the ${place} player to finish the hunt! (${takenTime}${blitz ? " - BLITZ" : ""})`
);
import_lib.Utils.sortBy(this.completed, (entry) => entry.time);
player.destroy();
return true;
}
},
scavengersfeud: {
id: "scavengersfeud",
name: "Scavengers Feud",
desc: "After completing the hunt, players will guess what the most common incorrect answer for each question is.",
onAfterLoad() {
this.guesses = {};
this.incorrect = this.questions.map(() => ({}));
this.questions.push({
hint: "Please enter what you think are the most common incorrect answers to each question. (Enter your guesses in the order of the previous questions, and separate them with a comma)",
answer: ["Any"],
spoilers: []
});
},
onIncorrectAnswer(player, value) {
const curr = player.currentQuestion;
if (!this.incorrect[curr][value])
this.incorrect[curr][value] = [];
if (this.incorrect[curr][value].includes(player.id))
return;
this.incorrect[curr][value].push(player.id);
},
onSubmitPriority: 1,
onSubmit(player, jumble, value) {
const currentQuestion = player.currentQuestion;
if (currentQuestion + 1 === this.questions.length) {
this.guesses[player.id] = value.split(",").map((part) => toID(part));
this.onComplete(player);
return true;
}
},
onEnd() {
this.questions = this.questions.slice(0, -1);
},
onAfterEnd(isReset) {
if (isReset)
return;
const buffer = [];
for (const [idx, data] of this.incorrect.entries()) {
let collection = [];
for (const str in data) {
collection.push({ count: data[str].length, value: str });
}
collection = collection.sort((a, b) => b.count - a.count);
const maxValue = collection[0]?.count || 0;
const matches = collection.filter((pair) => pair.count === maxValue).map((pair) => pair.value);
const matchedPlayers = [];
for (const playerid in this.guesses) {
const guesses = this.guesses[playerid];
if (matches.includes(guesses[idx]))
matchedPlayers.push(playerid);
}
const matchDisplay = matches.length ? matches.join(", ") : "No wrong answers!";
const playerDisplay = matches.length ? matchedPlayers.length ? `- ${matchedPlayers.join(", ")}` : "- No one guessed correctly!" : "";
buffer.push(`Q${idx + 1}: ${matchDisplay} ${playerDisplay}`);
}
this.announce(`<h3>Most common incorrect answers:</h3>${buffer.join("<br />")}`);
}
},
minesweeper: {
id: "minesweeper",
name: "Minesweeper",
desc: "The huntmaker can add incorrect 'mines' to the hunt - they get points every time a player scavenges it, and players that dodge all the mines in the hunt get points.",
onAfterLoad() {
this.guesses = this.questions.map(() => []);
this.mines = [];
for (const question of this.questions) {
this.mines.push(question.answer.filter((ans) => ans.startsWith("!")));
question.answer = question.answer.filter((ans) => !ans.startsWith("!"));
}
if (this.mines.some((mineSet) => mineSet.length === 0)) {
this.announce("This twist requires at least one mine for each question. Please reset the hunt and make it again.");
this.huntLocked = true;
}
},
onEditQuestion(questionNumber, questionAnswer, value) {
if (questionAnswer === "question")
questionAnswer = "hint";
if (!["hint", "answer"].includes(questionAnswer))
return false;
let answer = [];
if (questionAnswer === "answer") {
answer = value.split(";").map((p) => p.trim());
}
if (!questionNumber || questionNumber < 1 || questionNumber > this.questions.length || !answer && !value) {
return false;
}
questionNumber--;
if (questionAnswer === "answer") {
this.mines[questionNumber] = answer.filter((ans) => ans.startsWith("!"));
this.questions[questionNumber].answer = answer.filter((ans) => !ans.startsWith("!"));
} else {
this.questions[questionNumber].hint = value;
}
this.announce(`The ${questionAnswer} for question ${questionNumber + 1} has been edited.`);
if (questionAnswer === "hint") {
for (const p in this.playerTable) {
this.playerTable[p].onNotifyChange(questionNumber);
}
}
return true;
},
onAnySubmit(player) {
if (this.huntLocked) {
player.sendRoom("The hunt was not set up correctly. Please wait for the host to reset the hunt and create a new one.");
return true;
}
},
onIncorrectAnswer(player, value) {
const curr = player.currentQuestion;
if (!this.guesses[curr][player.id])
this.guesses[curr][player.id] = /* @__PURE__ */ new Set();
this.guesses[curr][player.id].add(toID(value));
throw new Chat.ErrorMessage("That is not the answer - try again!");
},
onShowEndBoard(endedBy) {
const sliceIndex = this.gameType === "official" ? 5 : 3;
const hosts = Chat.toListString(this.hosts.map((h) => `<em>${import_lib.Utils.escapeHTML(h.name)}</em>`));
const mines = [];
for (let index = 0; index < this.mines.length; index++) {
mines[index] = [];
for (const mine of this.mines[index]) {
mines[index].push({ mine: mine.substr(1), users: [] });
}
}
for (const player of Object.values(this.playerTable)) {
if (player.mines) {
for (const { index, mine } of player.mines) {
mines[index].find((obj) => obj.mine === mine)?.users.push(player.name);
}
}
}
for (const mineSet of mines)
mineSet.sort();
this.announce(
`The ${this.gameType ? `${this.gameType} ` : ""}scavenger hunt by ${hosts} was ended ${endedBy ? "by " + import_lib.Utils.escapeHTML(endedBy.name) : "automatically"}.<br />${this.completed.slice(0, sliceIndex).map((p, i) => `${import_lib.Utils.formatOrder(i + 1)} place: <em>${import_lib.Utils.escapeHTML(p.name)}</em> <span style="color: lightgreen;">[${p.time}]</span>.<br />`).join("")}${this.completed.length > sliceIndex ? `Consolation Prize: ${this.completed.slice(sliceIndex).map((e) => `<em>${import_lib.Utils.escapeHTML(e.name)}</em> <span style="color: lightgreen;">[${e.time}]</span>`).join(", ")}<br />` : ""}<br /><details style="cursor: pointer;"><summary>Solution: </summary><br />${this.questions.map((q, i) => `${i + 1}) ${Chat.formatText(q.hint)} <span style="color: lightgreen">[<em>${import_lib.Utils.escapeHTML(q.answer.join(" / "))}</em>]</span><br/><details style="cursor: pointer;"><summary>Mines: </summary>${mines[i].map(({ mine, users }) => import_lib.Utils.escapeHTML(`${mine}: ${users.join(" / ") || "-"}`)).join("<br />")}</details>`).join("<br />")}</details>`
);
return true;
},
onEnd(isReset) {
if (isReset)
return;
for (const [q, guessObj] of this.guesses.entries()) {
const mines = this.mines[q];
for (const [playerId, guesses] of Object.entries(guessObj)) {
const player = this.playerTable[playerId];
if (!player.mines)
player.mines = [];
player.mines.push(...mines.filter((mine) => guesses.has(toID(mine))).map((mine) => ({ index: q, mine: mine.substr(1) })));
}
}
},
onAfterEndPriority: 1,
onAfterEnd(isReset) {
if (isReset)
return;
const noMines = [];
for (const { name } of this.completed) {
const player = this.playerTable[toID(name)];
if (!player)
continue;
if (!player.mines?.length)
noMines.push(name);
}
if (noMines.length) {
this.announce(import_lib.Utils.html`${Chat.toListString(noMines)} ${noMines.length > 1 ? "have" : "has"} completed the hunt without hitting a single mine!`);
}
}
}
};
const MODES = {
ko: "kogames",
kogames: {
name: "KO Games",
id: "kogames",
mod: {
name: "KO Games",
id: "KO Games",
isGameMode: true,
onLoad() {
this.allowRenames = false;
},
onJoin(user) {
const game = this.room.scavgame;
if (game.playerlist && !game.playerlist.includes(user.id)) {
user.sendTo(this.room, "You are not allowed to join this scavenger hunt.");
return true;
}
},
onAfterEnd() {
const game = this.room.scavgame;
if (!this.completed.length) {
this.announce("No one has completed the hunt - the round has been void.");
return;
}
game.round++;
if (!game.playerlist) {
game.playerlist = this.completed.map((entry) => toID(entry.name));
this.announce(`Round ${game.round} - ${Chat.toListString(this.completed.map((p) => `<em>${p.name}</em>`))} have successfully completed the last hunt and have moved on to the next round!`);
} else {
let eliminated = [];
const completed = this.completed.map((entry) => toID(entry.name));
if (completed.length === game.playerlist.length) {
eliminated.push(completed.pop());
game.playerlist = game.playerlist.filter((userid) => completed.includes(userid));
} else {
eliminated = game.playerlist.filter((userid) => !completed.includes(userid));
for (const username of eliminated) {
const userid = toID(username);
game.playerlist = game.playerlist.filter((pid) => pid !== userid);
}
}
this.announce(`Round ${game.round} - ${Chat.toListString(eliminated.map((n) => `<em>${n}</em>`))} ${Chat.plural(eliminated, "have", "has")} been eliminated! ${Chat.toListString(game.playerlist.map((p) => `<em>${this.playerTable[p].name}</em>`))} have successfully completed the last hunt and have moved on to the next round!`);
}
if (game.playerlist.length === 1) {
const winningUser = Users.get(game.playerlist[0]);
const winner = winningUser ? winningUser.name : game.playerlist[0];
this.announce(`Congratulations to the winner - ${winner}!`);
game.destroy();
} else if (!game.playerlist.length) {
this.announce("Everyone has been eliminated! Better luck next time!");
game.destroy();
}
}
},
round: 0,
playerlist: null
},
scav: "scavengergames",
scavgames: "scavengergames",
scavengergames: {
name: "Scavenger Games",
id: "scavengergames",
mod: {
name: "Scavenger Games",
id: "scavengergames",
isGameMode: true,
onLoad() {
this.allowRenames = false;
this.setTimer(1);
},
onJoin(user) {
const game = this.room.scavgame;
if (game.playerlist && !game.playerlist.includes(user.id)) {
user.sendTo(this.room, "You are not allowed to join this scavenger hunt.");
return true;
}
},
onAfterEnd() {
const game = this.room.scavgame;
if (!this.completed.length) {
this.announce("No one has completed the hunt - the round has been void.");
return;
}
game.round++;
let eliminated = [];
if (!game.playerlist) {
game.playerlist = this.completed.map((entry) => toID(entry.name));
} else {
const completed = this.completed.map((entry) => toID(entry.name));
eliminated = game.playerlist.filter((userid) => !completed.includes(userid));
for (const username of eliminated) {
const userid = toID(username);
game.playerlist = game.playerlist.filter((pid) => pid !== userid);
}
}
this.announce(`Round ${game.round} - ${Chat.toListString(eliminated.map((n) => `<em>${n}</em>`))} ${eliminated.length ? `${Chat.plural(eliminated, "have", "has")} been eliminated!` : ""} ${Chat.toListString(game.playerlist.map((p) => `<em>${this.playerTable[p].name}</em>`))} have successfully completed the last hunt and have moved on to the next round!`);
if (game.playerlist.length === 1) {
const winningUser = Users.get(game.playerlist[0]);
const winner = winningUser ? winningUser.name : game.playerlist[0];
this.announce(`Congratulations to the winner - ${winner}!`);
game.destroy();
} else if (!game.playerlist.length) {
this.announce("Everyone has been eliminated! Better luck next time!");
game.destroy();
}
}
},
round: 0,
playerlist: null
},
pr: "pointrally",
pointrally: {
name: "Point Rally",
id: "pointrally",
pointDistribution: [50, 40, 32, 25, 20, 15, 10],
mod: {
name: "Point Rally",
id: "pointrally",
isGameMode: true,
onLoad() {
const game = this.room.scavgame;
this.announce(`Round ${++game.round}`);
},
async onAfterEnd() {
const game = this.room.scavgame;
for (const [i, completed] of this.completed.map((e) => e.name).entries()) {
const points = game.pointDistribution[i] || game.pointDistribution[game.pointDistribution.length - 1];
game.leaderboard.addPoints(completed, "points", points);
}
const room = this.room;
const html = await game.leaderboard.htmlLadder();
room.add(`|raw|${html}`).update();
}
},
round: 0,
leaderboard: true
},
js: "jumpstart",
jump: "jumpstart",
jumpstart: {
name: "Jump Start",
id: "jumpstart",
jumpstart: [60, 40, 30, 20, 10],
round: 0,
mod: {
name: "Jump Start",
id: "jumpstart",
isGameMode: true,
onLoad() {
const game = this.room.scavgame;
if (game.round === 0)
return;
const maxTime = Math.max(...game.jumpstart);
this.jumpstartTimers = [];
this.answerLock = true;
for (const [i, time] of game.jumpstart.entries()) {
if (!game.completed[i])
break;
this.jumpstartTimers[i] = setTimeout(() => {
const target = game.completed.shift();
if (!target)
return;
const staffHost = Users.get(this.staffHostId);
const targetUser = Users.get(target);
if (targetUser) {
if (staffHost)
staffHost.sendTo(this.room, `${targetUser.name} has received their first hint early.`);
targetUser.sendTo(
this.room,
`|raw|<strong>The first hint to the next hunt is:</strong> ${Chat.formatText(this.questions[0].hint)}`
);
targetUser.sendTo(
this.room,
`|notify|Early Hint|The first hint to the next hunt is: ${Chat.formatText(this.questions[0].hint)}`
);
}
}, (maxTime - time) * 1e3 + 5e3);
}
this.jumpstartTimers[this.jumpstartTimers.length] = setTimeout(() => {
this.answerLock = false;
const message = this.getCreationMessage(true);
this.room.add(message).update();
this.announce("You may start guessing!");
this.startTime = Date.now();
}, 1e3 * (maxTime + 5));
},
onJoin(user) {
if (this.answerLock) {
user.sendTo(this.room, `The hunt is not open for guesses yet!`);
return true;
}
},
onViewHunt(user) {
if (this.answerLock && !(this.hosts.some((h) => h.id === user.id) || user.id === this.staffHostId)) {
return true;
}
},
onCreateCallback() {
if (this.answerLock) {
return `|raw|<div class="broadcast-blue"><strong>${["official", "unrated"].includes(this.gameType) ? "An" : "A"} ${this.gameType} Scavenger Hunt by <em>${import_lib.Utils.escapeHTML(Chat.toListString(this.hosts.map((h) => h.name)))}</em> has been started${this.hosts.some((h) => h.id === this.staffHostId) ? "" : ` by <em>${import_lib.Utils.escapeHTML(this.staffHostName)}</em>`}.<br />The first hint is currently being handed out to early finishers.`;
}
},
onEnd(reset) {
if (this.jumpstartTimers) {
for (const timer of this.jumpstartTimers) {
clearTimeout(timer);
}
}
const game = this.room.scavgame;
if (!reset) {
if (game.round === 0) {
game.completed = this.completed.map((entry) => toID(entry.name));
game.round++;
} else {
game.destroy();
}
}
}
}
},
ts: "teamscavs",
tscav: "teamscavs",
teamscavengers: "teamscavs",
teamscavs: {
name: "Team Scavs",
id: "teamscavs",
/* {
[team
name: string]: {
name: string[],
players: UserID[],
answers: string[],
question: number,
completed: boolean
}
} */
teams: {},
teamAnnounce(player, message) {
const team = this.getPlayerTeam(player);
for (const userid of team.players) {
const user = Users.getExact(userid);
if (!user?.connected)
continue;
user.sendTo(this.room, `|raw|<div class="infobox">${message}</div>`);
}
},
getPlayerTeam(player) {
const game = this.room.scavgame;
for (const teamID in game.teams) {
const team = game.teams[teamID];
if (team.players.includes(player.id)) {
return team;
}
}
return null;
},
advanceTeam(answerer, isFinished) {
const hunt = this.room.getGame(import_scavengers.ScavengerHunt);
const team = this.getPlayerTeam(answerer);
team.question++;
const question = hunt.getQuestion(team.question);
for (const userid of team.players) {
const user = Users.getExact(userid);
if (!user)
continue;
user.sendTo(this.room, question);
}
team.answers = [];
},
mod: {
name: "Team Scavs",
id: "teamscavs",
isGameMode: true,
onLoad() {
this.allowRenames = false;
},
onViewHunt(user) {
const game = this.room.scavgame;
const team = game.getPlayerTeam(user);
const player = this.playerTable[user.id];
if (!player || !team)
return;
if (player.currentQuestion !== team.question - 1)
player.currentQuestion = team.question - 1;
if (team.completed)
player.completed = true;
},
onSendQuestion(player) {
const game = this.room.scavgame;
const team = game.getPlayerTeam(player);
if (!team)
return;
if (player.currentQuestion !== team.question - 1)
player.currentQuestion = team.question - 1;
if (team.completed) {
player.completed = true;
player.sendRoom("Your team has already completed the hunt!");
return true;
}
},
onConnect(user) {
const player = this.playerTable[user.id];
if (!player)
return;
const game = this.room.scavgame;
const team = game.getPlayerTeam(player);
if (team) {
if (player.currentQuestion !== team.question - 1)
player.currentQuestion = team.question - 1;
if (team.completed)
player.completed = true;
}
},
onJoin(user) {
const game = this.room.scavgame;
const team = game.getPlayerTeam(user);
if (!team) {
user.sendTo(this.room, "You are not allowed to join this scavenger hunt as you are not on any of the teams.");
return true;
}
},
onAfterLoadPriority: -9999,
onAfterLoad() {
const game = this.room.scavgame;
if (Object.keys(game.teams).length === 0) {
this.announce("Teams have not been set up yet. Please reset the hunt.");
}
},
// -1 so that blind incog takes precedence of this
onCorrectAnswerPriority: -1,
onCorrectAnswer(player, value) {
const game = this.room.scavgame;
if (player.currentQuestion + 1 < this.questions.length) {
game.teamAnnounce(
player,
import_lib.Utils.html`<strong>${player.name}</strong> has gotten the correct answer (${value}) for question #${player.currentQuestion + 1}.`
);
game.advanceTeam(player);
return false;
}
},
onAnySubmit(player, value) {
const game = this.room.scavgame;
const team = game.getPlayerTeam(player);
if (!team)
return true;
if (player.currentQuestion !== team.question - 1)
player.currentQuestion = team.question - 1;
if (team.completed)
player.completed = true;
if (player.completed)
return;
if (team.answers.includes(value))
return;
game.teamAnnounce(player, import_lib.Utils.html`${player.name} has guessed "${value}".`);
team.answers.push(value);
},
onCompletePriority: 2,
onComplete(player, time, blitz) {
const game = this.room.scavgame;
const team = game.getPlayerTeam(player);
return { name: team.name, time, blitz };
},
// workaround that gives the answer after verifying that completion should not be hidden
onConfirmCompletion(player, time, blitz) {
const game = this.room.scavgame;
const team = game.getPlayerTeam(player);
team.completed = true;
team.question++;
game.teamAnnounce(
player,
import_lib.Utils.html`<strong>${player.name}</strong> has gotten the correct answer for question #${player.currentQuestion}. Your team has completed the hunt!`
);
},
onEnd() {
const game = this.room.scavgame;
for (const teamID in game.teams) {
const team = game.teams[teamID];
team.answers = [];
team.question = 1;
team.completed = false;
}
}
}
}
};
class ScavengerGameTemplate {
constructor(room) {
this.room = room;
this.playerlist = null;
this.timer = null;
}
destroy(force) {
if (this.timer)
clearTimeout(this.timer);
const game = this.room.getGame(import_scavengers.ScavengerHunt);
if (force && game)
game.onEnd(false);
this.room.scavgame = null;
}
eliminate(userid) {
if (!this.playerlist?.includes(userid))
return false;
this.playerlist = this.playerlist.filter((pid) => pid !== userid);
if (this.leaderboard)
delete this.leaderboard.data[userid];
return true;
}
announce(msg) {
this.room.add(`|raw|<div class="broadcast-blue"><strong>${msg}</strong></div>`).update();
}
}
const LoadGame = function(room, gameid) {
let game = MODES[gameid];
if (!game)
return false;
if (typeof game === "string")
game = MODES[game];
const base = new ScavengerGameTemplate(room);
const scavgame = Object.assign(base, import_lib.Utils.deepClone(game));
if (scavgame.leaderboard) {
scavgame.leaderboard = new Leaderboard();
}
return scavgame;
};
const ScavMods = {
LoadGame,
twists: TWISTS,
modes: MODES
};
//# sourceMappingURL=scavenger-games.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/scavenger-games.ts"],
"sourcesContent": ["/**\r\n * Scavengers Games Plugin\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * This plugin stores the different possible game modes and twists that take place in scavengers room\r\n *\r\n * @license MIT license\r\n */\r\n\r\nimport {ScavengerHunt, ScavengerHuntPlayer} from './scavengers';\r\nimport {Utils} from '../../lib';\r\n\r\nexport type TwistEvent = (this: ScavengerHunt, ...args: any[]) => void;\r\ninterface Twist {\r\n\tname: string;\r\n\tid: string;\r\n\tisGameMode?: true;\r\n\tdesc?: string;\r\n\t[eventid: string]: string | number | TwistEvent | boolean | undefined;\r\n}\r\n\r\ntype GameModeFunction = (this: ScavengerGameTemplate, ...args: any[]) => void;\r\ninterface GameMode {\r\n\tname: string;\r\n\tid: string;\r\n\tmod: Twist;\r\n\tround?: number;\r\n\tleaderboard?: true;\r\n\tteamAnnounce?: GameModeFunction;\r\n\tgetPlayerTeam?: GameModeFunction;\r\n\tadvanceTeam?: GameModeFunction;\r\n\t[k: string]: any;\r\n}\r\n\r\nfunction toSeconds(time: string) {\r\n\t// hhmmss => ss\r\n\tconst parts = time.split(':').reverse();\r\n\treturn parts.map((value, index) => parseInt(value) * Math.pow(60, index)).reduce((a, b) => a + b);\r\n}\r\n\r\nclass Leaderboard {\r\n\tdata: {[userid: string]: AnyObject};\r\n\r\n\tconstructor() {\r\n\t\tthis.data = {};\r\n\t}\r\n\r\n\taddPoints(name: string, aspect: string, points: number, noUpdate?: boolean) {\r\n\t\tconst userid: string = toID(name);\r\n\r\n\t\tif (!userid || userid === 'constructor' || !points) return this;\r\n\t\tif (!this.data[userid]) this.data[userid] = {name: name};\r\n\r\n\t\tif (!this.data[userid][aspect]) this.data[userid][aspect] = 0;\r\n\t\tthis.data[userid][aspect] += points;\r\n\r\n\t\tif (!noUpdate) this.data[userid].name = name; // always keep the last used name\r\n\r\n\t\treturn this; // allow chaining\r\n\t}\r\n\r\n\tvisualize(sortBy: string): Promise<({rank: number} & AnyObject)[]>;\r\n\tvisualize(sortBy: string, userid: string): Promise<({rank: number} & AnyObject) | undefined>;\r\n\tvisualize(sortBy: string, userid?: string) {\r\n\t\t// FIXME: this is not how promises work\r\n\t\t// return a promise for async sorting - make this less exploitable\r\n\t\treturn new Promise((resolve, reject) => {\r\n\t\t\tlet lowestScore = Infinity;\r\n\t\t\tlet lastPlacement = 1;\r\n\r\n\t\t\tconst ladder = Utils.sortBy(\r\n\t\t\t\tObject.entries(this.data).filter(([u, bit]) => sortBy in bit),\r\n\t\t\t\t([u, bit]) => -bit[sortBy]\r\n\t\t\t).map(([u, bit], i) => {\r\n\t\t\t\tif (bit[sortBy] !== lowestScore) {\r\n\t\t\t\t\tlowestScore = bit[sortBy];\r\n\t\t\t\t\tlastPlacement = i + 1;\r\n\t\t\t\t}\r\n\t\t\t\treturn {\r\n\t\t\t\t\trank: lastPlacement,\r\n\t\t\t\t\t...bit,\r\n\t\t\t\t} as {rank: number} & AnyObject;\r\n\t\t\t}); // identify ties\r\n\t\t\tif (userid) {\r\n\t\t\t\tconst rank = ladder.find(entry => toID(entry.name) === userid);\r\n\t\t\t\tresolve(rank);\r\n\t\t\t} else {\r\n\t\t\t\tresolve(ladder);\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\tasync htmlLadder(): Promise<string> {\r\n\t\tconst data = await this.visualize('points');\r\n\t\tconst display = `<div class=\"ladder\" style=\"overflow-y: scroll; max-height: 170px;\"><table style=\"width: 100%\"><tr><th>Rank</th><th>Name</th><th>Points</th></tr>${data.map(line =>\r\n\t\t\t`<tr><td>${line.rank}</td><td>${line.name}</td><td>${line.points}</td></tr>`).join('')\r\n\t\t}</table></div>`;\r\n\t\treturn display;\r\n\t}\r\n}\r\n\r\nconst TWISTS: {[k: string]: Twist} = {\r\n\tperfectscore: {\r\n\t\tname: 'Perfect Score',\r\n\t\tid: 'perfectscore',\r\n\t\tdesc: \"Players who finish the hunt without submitting a single wrong answer get a shoutout!\",\r\n\r\n\t\tonLeave(player) {\r\n\t\t\tif (!this.leftGame) this.leftGame = [];\r\n\t\t\tthis.leftGame.push(player.id);\r\n\t\t},\r\n\r\n\t\tonSubmitPriority: 1,\r\n\t\tonSubmit(player, value) {\r\n\t\t\tconst currentQuestion = player.currentQuestion;\r\n\r\n\t\t\tif (!player.answers) player.answers = {};\r\n\t\t\tif (!player.answers[currentQuestion]) player.answers[currentQuestion] = [];\r\n\r\n\t\t\tif (player.answers[currentQuestion].includes(value)) return;\r\n\r\n\t\t\tplayer.answers[currentQuestion].push(value);\r\n\t\t},\r\n\r\n\t\tonComplete(player, time, blitz) {\r\n\t\t\tconst isPerfect = !this.leftGame?.includes(player.id) &&\r\n\t\t\t\tObject.values(player.answers).every((attempts: any) => attempts.length <= 1);\r\n\t\t\treturn {name: player.name, time, blitz, isPerfect};\r\n\t\t},\r\n\r\n\t\tonAfterEndPriority: 1,\r\n\t\tonAfterEnd(isReset) {\r\n\t\t\tif (isReset) return;\r\n\t\t\tconst perfect = this.completed.filter(entry => entry.isPerfect).map(entry => entry.name);\r\n\t\t\tif (perfect.length) {\r\n\t\t\t\tthis.announce(Utils.html`${Chat.toListString(perfect)} ${perfect.length > 1 ? 'have' : 'has'} completed the hunt without a single wrong answer!`);\r\n\t\t\t}\r\n\t\t},\r\n\t},\r\n\r\n\tbonusround: {\r\n\t\tname: 'Bonus Round',\r\n\t\tid: 'bonusround',\r\n\t\tdesc: \"Players can choose whether or not Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,wBAAiD;AACjD,iBAAoB;AAVpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkCA,SAAS,UAAU,MAAc;AAEhC,QAAM,QAAQ,KAAK,MAAM,GAAG,EAAE,QAAQ;AACtC,SAAO,MAAM,IAAI,CAAC,OAAO,UAAU,SAAS,KAAK,IAAI,KAAK,IAAI,IAAI,KAAK,CAAC,EAAE,OAAO,CAAC,GAAG,MAAM,IAAI,CAAC;AACjG;AAEA,MAAM,YAAY;AAAA,EAGjB,cAAc;AACb,SAAK,OAAO,CAAC;AAAA,EACd;AAAA,EAEA,UAAU,MAAc,QAAgB,QAAgB,UAAoB;AAC3E,UAAM,SAAiB,KAAK,IAAI;AAEhC,QAAI,CAAC,UAAU,WAAW,iBAAiB,CAAC;AAAQ,aAAO;AAC3D,QAAI,CAAC,KAAK,KAAK,MAAM;AAAG,WAAK,KAAK,MAAM,IAAI,EAAC,KAAU;AAEvD,QAAI,CAAC,KAAK,KAAK,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O,iBAAM,WAAW,OAAO,IAAI,8CAA8C,UAAU,mBAAoB,QAAQ,aAAa;AAAA,IAC5I;AAAA,IAEA,QAAQ;AACP,uBAAM,OAAO,KAAK,WAAW,WAAS,MAAM,KAAK;AAAA,IAClD;AAAA,EACD;AAAA,EAEA,gBAAgB;AAAA,IACf,MAAM;AAAA,IACN,IAAI;AAAA,IACJ,MAAM;AAAA,IAEN,YAAY,QAAQ,OAAO;AAC1B,UAAI,OAAO,cAAc;AACxB,eAAO,SAAS,uFAAuF;AACLine truncated
"names": []
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/scavengers.ts"],
"sourcesContent": ["/**\r\n * Scavengers Plugin\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * This is a game plugin to host scavenger games specifically in the Scavengers room,\r\n * where the players will race answer several hints.\r\n *\r\n * @license MIT license\r\n */\r\n\r\nimport {FS, Utils} from '../../lib';\r\nimport {ScavMods, TwistEvent} from './scavenger-games';\r\nimport {ChatHandler} from '../chat';\r\n\r\ntype GameTypes = 'official' | 'regular' | 'mini' | 'unrated' | 'practice' | 'recycled';\r\n\r\nexport interface QueuedHunt {\r\n\thosts: {id: string, name: string, noUpdate?: boolean}[];\r\n\tquestions: (string | string[])[];\r\n\tstaffHostId: string;\r\n\tstaffHostName: string;\r\n\tgameType: GameTypes;\r\n}\r\nexport interface FakeUser {\r\n\tname: string;\r\n\tid: string;\r\n\tnoUpdate?: boolean;\r\n}\r\ninterface ModEvent {\r\n\tpriority: number;\r\n\texec: TwistEvent;\r\n}\r\n\r\nconst RATED_TYPES = ['official', 'regular', 'mini'];\r\nconst DEFAULT_POINTS: {[k: string]: number[]} = {\r\n\tofficial: [20, 15, 10, 5, 1],\r\n};\r\nconst DEFAULT_BLITZ_POINTS: {[k: string]: number} = {\r\n\tofficial: 10,\r\n};\r\nconst DEFAULT_HOST_POINTS = 4;\r\nconst DEFAULT_TIMER_DURATION = 120;\r\n\r\nconst DATA_FILE = 'config/chat-plugins/ScavMods.json';\r\nconst HOST_DATA_FILE = 'config/chat-plugins/scavhostdata.json';\r\nconst PLAYER_DATA_FILE = 'config/chat-plugins/scavplayerdata.json';\r\nconst DATABASE_FILE = 'config/chat-plugins/scavhunts.json';\r\n\r\nconst ACCIDENTAL_LEAKS = /^((?:\\s)?(?:\\/{2,}|[^\\w/]+)|\\s\\/)?(?:\\s)?(?:s\\W?cavenge|s\\W?cav(?:engers)? guess|d\\W?t|d\\W?ata|d\\W?etails|g\\W?(?:uess)?|v)\\b/i;\r\n\r\nconst FILTER_LENIENCY = 7;\r\n\r\nconst HISTORY_PERIOD = 6; // months\r\n\r\nconst databaseContentsJSON = FS(DATABASE_FILE).readIfExistsSync();\r\nconst scavengersData = databaseContentsJSON ? JSON.parse(databaseContentsJSON) : {recycledHunts: []};\r\n\r\nconst SCAVENGER_ROOMID = 'scavengers';\r\nfunction getScavsRoom(room?: Room) {\r\n\tif (!room) return Rooms.get(SCAVENGER_ROOMID);\r\n\tif (room.roomid === SCAVENGER_ROOMID) return room;\r\n\tif (room.parent?.roomid === SCAVENGER_ROOMID) return room.parent;\r\n\treturn null;\r\n}\r\n\r\nclass Ladder {\r\n\tfile: string;\r\n\tdata: {[userid: string]: AnyObject};\r\n\tconstructor(file: string) {\r\n\t\tthis.file = file;\r\n\t\tthis.data = {};\r\n\r\n\t\tthis.load();\r\n\t}\r\n\r\n\tload() {\r\n\t\tconst json = FS(this.file).readIfExistsSync();\r\n\t\tif (json) this.data = JSON.parse(json);\r\n\t}\r\n\r\n\taddPoints(name: string, aspect: string, points: number, noUpdate?: boolean) {\r\n\t\tconst userid = toID(name);\r\n\r\n\t\tif (!userid || userid === 'constructor' || !points) return this;\r\n\t\tif (!this.data[userid]) this.data[userid] = {name: name};\r\n\r\n\t\tif (!this.data[userid][aspect]) this.data[userid][aspect] = 0;\r\n\t\tthis.data[userid][aspect] += points;\r\n\r\n\t\tif (!noUpdate) this.data[userid].name = name; // always keep the last used name\r\n\r\n\t\treturn this; // allow chaining\r\n\t}\r\n\r\n\treset() {\r\n\t\tthis.data = {};\r\n\t\treturn this; // allow chaining\r\n\t}\r\n\r\n\twrite() {\r\n\t\tFS(this.file).writeUpdate(() => JSON.stringify(this.data));\r\n\t}\r\n\r\n\tvisualize(sortBy: string): Promise<({rank: number} & AnyObject)[]>;\r\n\tvisualize(sortBy: string, userid: ID): Promise<({rank: number} & AnyObject) | undefined>;\r\n\tvisualize(sortBy: string, userid?: ID) {\r\n\t\t// return a promise for async sorting - make this less exploitable\r\n\t\treturn new Promise((resolve, reject) => {\r\n\t\t\tlet lowestScore = Infinity;\r\n\t\t\tlet lastPlacement = 1;\r\n\r\n\t\t\tconst ladder = Utils.sortBy(\r\n\t\t\t\tObject.entries(this.data).filter(([u, bit]) => sortBy in bit),\r\n\t\t\t\t([u, bit]) => -bit[sortBy]\r\n\t\t\t).map(([u, chunk], i) => {\r\n\t\t\t\tif (chunk[sortBy] !== lowestScore) {\r\n\t\t\t\t\tlowestScore = chunk[sortBy];\r\n\t\t\t\t\tlastPlacement = i + 1;\r\n\t\t\t\t}\r\n\t\t\t\treturn {\r\n\t\t\t\t\trank: lastPlacement,\r\n\t\t\t\t\t...chunk,\r\n\t\t\t\t} as {rank: number} & AnyObject;\r\n\t\t\t}); // identify ties\r\n\t\t\tif (userid) {\r\n\t\t\t\tconst rank = ladder.find(entry => toID(entry.name) === userid);\r\n\t\t\t\tresolve(rank);\r\n\t\t\t} else {\r\n\t\t\t\tresolve(ladder);\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n}\r\n\r\nclass PlayerLadder extends Ladder {\r\n\tconstructor(file: string) {\r\n\t\tsuper(file);\r\n\t}\r\n\r\n\taddPoints(name: string, aspect: string, points: number, noUpdate?: boolean) {\r\n\t\tif (!aspect.startsWith('cumulative-')) {\r\n\t\t\tthis.addPoints(name, `cumulative-${aspect}`, points, noUpdate);\r\n\t\t}\r\n\t\tconst userid = toID(name);\r\n\r\n\t\tif (!userid || userid === 'constructor' || !points) return this;\r\n\t\tif (!this.data[userid]) this.data[userid] = {name: name};\r\n\r\n\t\tif (!this.data[userid][aspect]) this.data[userid][aspect] = 0;\r\n\t\tthis.data[userid][aspect] += points;\r\n\r\n\t\tif (!noUpdate) this.data[userid].name = namLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,iBAAwB;AACxB,6BAAmC;AAXnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiCA,MAAM,cAAc,CAAC,YAAY,WAAW,MAAM;AAClD,MAAM,iBAA0C;AAAA,EAC/C,UAAU,CAAC,IAAI,IAAI,IAAI,GAAG,CAAC;AAC5B;AACA,MAAM,uBAA8C;AAAA,EACnD,UAAU;AACX;AACA,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAE/B,MAAM,YAAY;AAClB,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AAEtB,MAAM,mBAAmB;AAEzB,MAAM,kBAAkB;AAExB,MAAM,iBAAiB;AAEvB,MAAM,2BAAuB,eAAG,aAAa,EAAE,iBAAiB;AAChE,MAAM,iBAAiB,uBAAuB,KAAK,MAAM,oBAAoB,IAAI,EAAC,eAAe,CAAC,EAAC;AAEnG,MAAM,mBAAmB;AACzB,SAAS,aAAa,MAAa;AAClC,MAAI,CAAC;AAAM,WAAO,MAAM,IAAI,gBAAgB;AAC5C,MAAI,KAAK,WAAW;AAAkB,WAAO;AAC7C,MAAI,KAAK,QAAQ,WAAW;AAAkB,WAAO,KAAK;AAC1D,SAAO;AACR;AAEA,MAAM,OAAO;AAAA,EAGZ,YAAY,MAAc;AACzB,SAAK,OAAO;AACZ,SAAK,OAAO,CAAC;AAEb,SAAK,KAAK;AAAA,EACX;AAAA,EAEA,OAAO;AACN,UAAM,WAAO,eAAG,KAAK,IAAI,EAAE,iBAAiB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perty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var smogtours_exports = {};
__export(smogtours_exports, {
commands: () => commands,
pages: () => pages,
renderPageChooser: () => renderPageChooser,
tours: () => tours
});
module.exports = __toCommonJS(smogtours_exports);
var import_lib = require("../../lib");
const tours = {
official: {
title: "Smogon Officials",
// cap this one's dimensions
icon: ["https://www.smogon.com/media/zracknel-beta.svg", 178, 200],
tours: [],
desc: "Tournaments run by Smogon staff."
},
smogon: {
title: "Open Sign-Ups",
tours: [],
desc: "Tournaments run by Smogon staff and regular users alike."
},
ps: {
title: "Pok\xE9mon Showdown!",
icon: ["https://play.pokemonshowdown.com/pokemonshowdownbeta.png", 146, 44],
tours: [],
desc: "Tournaments run by the rooms of Pokemon Showdown."
}
};
try {
const data = JSON.parse((0, import_lib.FS)("config/chat-plugins/smogtours.json").readSync());
const PRIO = ["title", "icon"];
for (const key in data) {
const section = tours[key] || (tours[key] = data[key]);
for (const k in data[key]) {
if (PRIO.includes(k)) {
if (!section[k])
section[k] = data[key][k];
} else {
section[k] = data[key][k];
}
}
}
} catch {
}
function saveTours() {
(0, import_lib.FS)("config/chat-plugins/smogtours.json").writeUpdate(() => JSON.stringify(tours));
}
function getTour(categoryID, id) {
id = toID(id);
return tours?.[categoryID].tours.find((f) => f.id === id) || null;
}
function checkWhitelisted(category, user) {
return category ? tours[category].whitelist?.includes(user.id) : Object.values(tours).some((f) => f.whitelist?.includes(user.id));
}
function checkCanEdit(user, context, category) {
category = toID(category);
if (!checkWhitelisted(category, user)) {
context.checkCan("rangeban");
}
}
const commands = {
smogtours: {
""() {
return this.parse("/j view-tournaments-all");
},
edit: "add",
async add(target, room, user, connection, cmd) {
if (!toID(target).length) {
return this.parse(`/help smogtours`);
}
const targets = target.split("|");
const isEdit = cmd === "edit";
const tourID = isEdit ? toID(targets.shift()) : null;
const [
title,
rawSection,
url,
rawImg,
rawShort,
rawDesc
] = import_lib.Utils.splitFirst(targets.join("|"), "|", 5).map((f) => f.trim());
const sectionID = toID(rawSection);
if (!toID(title)) {
return this.popupReply(`Invalid title. Must have at least one alphanumeric character.`);
}
const section = tours[sectionID];
if (!section) {
return this.errorReply(`Invalid section ID: "${sectionID}"`);
}
if (!isEdit && section.tours.find((f) => toID(title) === f.id)) {
return this.popupReply(`A tour with that ID already exists. Please choose another.`);
}
checkCanEdit(user, this, sectionID);
if (!Chat.isLink(url)) {
return this.popupReply(`Invalid info URL: "${url}"`);
}
let image;
if (rawImg) {
if (!Chat.isLink(rawImg)) {
return this.popupReply(`Invalid image URL: ${rawImg}`);
}
try {
const dimensions = await Chat.fitImage(rawImg, 300, 300);
image = [rawImg, ...dimensions.slice(0, -1)];
} catch (e) {
return this.popupReply(`Invalid image URL: ${rawImg}`);
}
}
if (!rawShort?.length || !rawDesc?.length) {
return this.popupReply(`Must provide both a short description and a full description.`);
}
const tour = {
title: import_lib.Utils.escapeHTML(title),
url,
image,
shortDesc: rawShort.replace(/&#13;&#10;/g, "\n"),
desc: rawDesc.replace(/&#13;&#10;/g, "\n"),
id: tourID || toID(title),
date: Date.now()
};
if (isEdit) {
const index = section.tours.findIndex((t) => t.id === tour.id);
if (index < 0) {
return this.popupReply(`Tour not found. Create one first.`);
}
section.tours.splice(index, 1);
}
section.tours.push(tour);
saveTours();
this.refreshPage(`tournaments-add`);
},
end(target, room, user, connection) {
const [sectionID, tourID] = target.split(",").map(toID).filter(Boolean);
if (!sectionID || !tourID) {
return this.parse(`/help smogtours`);
}
const section = tours[sectionID];
if (!section)
return this.popupReply(`Invalid section: "${sectionID}"`);
const idx = section.tours.findIndex((t) => t.id === tourID);
const title = section.tours[idx].title;
if (idx < 0) {
return this.popupReply(`Tour with ID "${tourID}" not found.`);
}
section.tours.splice(idx, 1);
this.refreshPage(`tournaments-view-${sectionID}-${tourID}`);
this.popupReply(`Tour "${title}" ended.`);
},
whitelist(target, room, user) {
this.checkCan("rangeban");
const [sectionID, targetID] = target.split(",").map(toID).filter(Boolean);
if (!sectionID || !targetID) {
return this.parse(`/help smogtours`);
}
const section = tours[sectionID];
if (!section) {
return this.errorReply(`Invalid section ID: "${sectionID}". Valid IDs: ${Object.keys(tours).join(", ")}`);
}
if (section.whitelist?.includes(targetID)) {
return this.errorReply(`That user is already whitelisted on that section.`);
}
if (!section.whitelist)
section.whitelist = [];
section.whitelist.push(targetID);
this.privateGlobalModAction(
`${user.name} whitelisted ${targetID} to manage tours for the ${section.title} section`
);
this.globalModlog("TOUR WHITELIST", targetID);
saveTours();
},
unwhitelist(target, room, user) {
this.checkCan("rangeban");
const [sectionID, targetID] = target.split(",").map(toID).filter(Boolean);
if (!sectionID || !targetID) {
return this.parse(`/help smogtours`);
}
const section = tours[sectionID];
if (!section) {
return this.errorReply(`Invalid section ID: "${sectionID}". Valid IDs: ${Object.keys(tours).join(", ")}`);
}
const idx = section.whitelist?.indexOf(targetID) ?? -1;
if (!section.whitelist || idx < 0) {
return this.errorReply(`${targetID} is not whitelisted in that section.`);
}
section.whitelist.splice(idx, 1);
if (!section.whitelist.length) {
delete section.whitelist;
}
this.privateGlobalModAction(
`${user.name} removed ${targetID} from the tour management whitelist for the ${section.title} section`
);
this.globalModlog("TOUR UNWHITELIST", targetID);
saveTours();
},
view() {
return this.parse(`/join view-tournaments-all`);
}
},
smogtourshelp: [
`/smogtours view - View a list of ongoing forum tournaments.`,
`/smogtours whitelist [section], [user] - Whitelists the given [user] to manage tournaments for the given [section].`,
`Requires: &`,
`/smogtours unwhitelist [section], [user] - Removes the given [user] from the [section]'s management whitelist.`,
`Requires: &`
]
};
function renderTab(inner, isTitle, isCur) {
isTitle = false;
let buf = "";
if (isCur) {
buf += `<div class="folder cur"><div class="folderhack3"><div class="folderhack1">`;
buf += `</div><div class="folderhack2"></div>`;
buf += `<div class="selectFolder">${inner}</div></div></div>`;
} else {
if (!isTitle) {
inner = `<div class="selectFolder">${inner}</div>`;
}
buf += `<div class="folder">${inner}</div>`;
}
return buf;
}
const refresh = (pageid) => `<button class="button" name="send" value="/join ${pageid}" style="float: right"><i class="fa fa-refresh"></i> Refresh</button>`;
const back = (section) => `<a class="button" target="replace" href="/view-tournaments-${section ? `section-${section}` : "all"}" style="float: left"><i class="fa fa-arrow-left"></i> Back</a>`;
function renderPageChooser(curPage, buffer, user) {
let buf = `<div class="folderpane">`;
buf += `<div class="folderlist">`;
buf += `<div class="folderlistbefore"></div>`;
const keys = Object.keys(tours);
buf += keys.map((cat) => {
let innerBuf = "";
const tourData = tours[cat];
innerBuf += renderTab(
`<strong><a target="replace" href="/view-tournaments-section-${cat}">${tourData.title}</a></strong>`,
true,
curPage === cat
);
if (tourData.tours.length) {
import_lib.Utils.sortBy(tourData.tours, (t) => -t.date);
innerBuf += tourData.tours.map((t) => renderTab(
`<i class="fa fa-trophy"></i><a target="replace" href="/view-tournaments-view-${cat}-${t.id}">${t.title}</a>`,
false,
curPage === `${cat}-${t.id}`
)).join("");
} else {
innerBuf += renderTab(`None`, false);
}
return innerBuf;
}).join('<div class="foldersep"></div>');
if (user && (checkWhitelisted("", user) || user?.can("rangeban"))) {
buf += `<div class="foldersep"></div>`;
buf += renderTab(
`<strong>Manage</strong>`,
true,
curPage === "manage"
);
buf += renderTab(
`<i class="fa fa-pencil"></i><a target="replace" href="/view-tournaments-start">Start new</a>`,
false,
curPage === "start"
);
buf += renderTab(
`<i class="fa fa-pencil"></i><a target="replace" href="/view-tournaments-edit">Edit existing</a>`,
false,
curPage === "edit"
);
if (user.can("rangeban")) {
buf += renderTab(
`<i class="fa fa-pencil"></i><a target="replace" href="/view-tournaments-whitelists">Whitelist</a>`,
false,
curPage === "whitelist"
);
}
}
buf += `<div class="folderlistafter"></div></div></div><div class="teampane">`;
buf += `${buffer}</div>`;
return buf;
}
function error(page, message, user) {
return renderPageChooser(page, `<div class="message-error">${message}</div>`, user);
}
const pages = {
tournaments: {
all(query, user) {
let buf = `${refresh(this.pageid)}<br /><center>`;
buf += `<h2><psicon pokemon="Meloetta-Pirouette" />Welcome!<psicon pokemon="Meloetta-Pirouette" /></h2>`;
const icon = tours.official.icon;
if (icon)
buf += `<img src="${icon[0]}" width="${icon[1]}" height="${icon[2]}"></center>`;
buf += `<hr />`;
this.title = "[Tournaments] All";
buf += `<p>Smogon runs official tournaments across their metagames where the strongest and most `;
buf += `experienced competitors duke it out for prizes and recognition!</p><p>`;
buf += `You can see a listing of current official tournaments here; `;
buf += `by clicking any hyperlink, you will be directed to the forum for any given tournament!</p><p>`;
buf += `Be sure to sign up if you are eager to participate or `;
buf += `check it out if you want to spectate the most hyped games out there.</p><p>`;
buf += `For information on tournament rules and etiquette, check out <a href="https://www.smogon.com/forums/threads/3642760/">this information thread</a>.`;
buf += `</p><center>`;
buf += Object.keys(tours).map((catID) => `<a class="button" target="replace" href="/view-tournaments-section-${catID}"><i class="fa fa-play"></i> ${tours[catID].title}</a>`).join(" ");
buf += `</center>`;
return renderPageChooser("", buf, user);
},
view(query, user) {
const [categoryID, tourID] = query.map(toID);
if (!categoryID || !tourID) {
return error("", "You must specify a tour category and a tour ID.", user);
}
this.title = `[Tournaments] [${categoryID}] `;
if (!tours[categoryID]) {
return error("", `Invalid tour section: '${categoryID}'.`, user);
}
const tour = getTour(categoryID, tourID);
if (!tour) {
return error(categoryID, `Tour '${tourID}' not found.`, user);
}
this.title += `${tour.title}`.replace(/&quot;/g, '"').replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&amp;/g, "&");
let buf = `${back(categoryID)}${refresh(this.pageid)}<br />`;
buf += `<center><h2><a href="${tour.url}">${tour.title}</a></h2>`;
if (tour.image) {
buf += `<img src="${tour.image[0]}" width="${tour.image[1]}" height="${tour.image[2]}" />`;
}
buf += `</center><hr />`;
buf += import_lib.Utils.escapeHTML(tour.desc).replace(/\n/ig, "<br />");
buf += `<br /><br /><a class="button notifying" href="${tour.url}">View information and signups</a>`;
try {
checkCanEdit(user, this, categoryID);
buf += `<br /><br /><details class="readmore"><summary>Manage</summary>`;
buf += `<button class="button" name="send" value="/smogtours end ${categoryID},${tourID}">End tour</button>`;
buf += `</details>`;
} catch {
}
return renderPageChooser(query.join("-"), buf, user);
},
section(query, user) {
const categoryID = toID(query.shift());
if (!categoryID) {
return error("", `No section specified.`, user);
}
this.title = "[Tournaments] " + categoryID;
const category = tours[categoryID];
if (!category) {
return error("", import_lib.Utils.html`Invalid section specified: '${categoryID}'`, user);
}
let buf = `${back()}${refresh(this.pageid)}<br /><center><h2>${category.title}</h2>`;
if (category.icon) {
buf += `<img src="${category.icon[0]}" width="${category.icon[1]}" height="${category.icon[2]}" /><br />`;
}
buf += `</center>${category.desc}<hr />`;
if (!category.tours.length) {
buf += `<p>There are currently no tournaments in this section with open signups.</p>`;
buf += `<p>Check back later for new tours.</p>`;
} else {
buf += category.tours.map((tour) => {
let innerBuf = `<div class="infobox">`;
innerBuf += `<a href="/view-tournaments-view-${categoryID}-${tour.id}">${tour.title}</a><br />`;
innerBuf += import_lib.Utils.escapeHTML(tour.shortDesc);
innerBuf += `</div>`;
return innerBuf;
}).join("<br />");
}
return renderPageChooser(categoryID, buf, user);
},
start(query, user) {
checkCanEdit(user, this);
let buf = `${refresh(this.pageid)}<br />`;
this.title = "[Tournaments] Add";
buf += `<center><h2>Add new tournament</h2></center><hr />`;
buf += `<form data-submitsend="/smogtours add {title}|{category}|{url}|{img}|{shortDesc}|{desc}">`;
let possibleCategory = Object.keys(tours)[0];
for (const k in tours) {
if (tours[k].whitelist?.includes(user.id)) {
possibleCategory = k;
break;
}
}
buf += `Title: <input name="title" /><br />`;
buf += `Category: <select name="category">`;
const keys = import_lib.Utils.sortBy(Object.keys(tours), (k) => [k === possibleCategory, k]).filter((cat) => checkWhitelisted(toID(cat), user) || user.can("rangeban"));
buf += keys.map((k) => `<option>${k}</option>`).join("");
buf += `</select><br />`;
buf += `Info link: <input name="url" /><br />`;
buf += `<abbr title="Max length and width: 300px">Image link</abbr> (optional): <input name="img" /><br />`;
buf += `Short description: <br /><textarea name="shortDesc" rows="6" cols="50"></textarea><br />`;
buf += `Full description: <br /><textarea name="desc" rows="20" cols="50"></textarea><br />`;
buf += `<button type="submit" class="button notifying">Create!</button></form>`;
return renderPageChooser("start", buf, user);
},
// edit single
edit(query, user) {
this.title = "[Tournaments] Edit ";
const [sectionID, tourID] = query.map(toID);
if (!sectionID || !tourID) {
return Chat.resolvePage(`view-tournaments-manage`, user, this.connection);
}
const section = tours[sectionID];
if (!section)
return error("edit", `Invalid section: "${sectionID}"`, user);
const tour = section.tours.find((t) => t.id === tourID);
if (!tour)
return error("edit", `Tour with ID "${tourID}" not found.`, user);
let buf = `${refresh(this.pageid)}<br /><center><h2>Edit tournament "${tour.title}"</h2></center><hr />`;
buf += `<form data-submitsend="/smogtours edit ${tour.id}|{title}|${sectionID}|{url}|{img}|{shortDesc}|{desc}">`;
buf += `Title: <input name="title" value="${tour.title}"/><br />`;
buf += `Info link: <input name="url" value="${tour.url}" /><br />`;
buf += `Image link (optional): <input name="img" value="${tour.image?.[0] || ""}" /><br />`;
buf += `Short description: <br />`;
buf += `<textarea name="shortDesc" rows="6" cols="50">${tour.shortDesc}</textarea><br />`;
const desc = import_lib.Utils.escapeHTML(tour.desc).replace(/<br \/>/g, "&#10;");
buf += `Full description: <br /><textarea name="desc" rows="20" cols="50">${desc}</textarea><br />`;
buf += `<button type="submit" class="button notifying">Update!</button>`;
return renderPageChooser("edit", buf, user);
},
// panel for all you have perms to edit
manage(query, user) {
checkCanEdit(user, this);
this.title = "[Tournaments] Manage";
let buf = `${refresh(this.pageid)}<br /><center><h2>Manage ongoing tournaments</h2></center><hr />`;
buf += Object.keys(tours).map((cat) => {
let innerBuf = "";
try {
checkCanEdit(user, this, toID(cat));
} catch {
return "";
}
const section = tours[cat];
innerBuf += `<strong>${section.title}</strong>:<br />`;
innerBuf += section.tours.map(
(t) => `&bull; <a href="/view-tournaments-edit-${cat}-${t.id}">${t.title}</a>`
).join("<br />") || "None active.";
return innerBuf;
}).filter(Boolean).join("<hr />");
return renderPageChooser("manage", buf, user);
},
whitelists(query, user) {
this.checkCan("rangeban");
let buf = `${refresh(this.pageid)}<br /><center><h2>Section whitelists</center</h2><hr />`;
for (const k in tours) {
buf += `<strong>${tours[k].title}</strong><br />`;
const whitelist = tours[k].whitelist || [];
if (!whitelist.length) {
buf += `None.<br />`;
continue;
}
buf += import_lib.Utils.sortBy(whitelist).map((f) => `<li>${f}</li>`).join("");
buf += `<br />`;
}
return renderPageChooser("whitelist", buf, user);
}
}
};
process.nextTick(() => {
Chat.multiLinePattern.register("/smogtours (add|edit)");
});
//# sourceMappingURL=smogtours.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/smogtours.ts"],
"sourcesContent": ["/**\r\n * Integration for Smogon tournaments.\r\n * @author mia-pi-git\r\n */\r\nimport {FS, Utils} from '../../lib';\r\n\r\ntype Image = [string, number, number];\r\ninterface TourEvent {\r\n\ttitle: string;\r\n\turl: string;\r\n\tdesc: string;\r\n\timage?: Image;\r\n\tid: string;\r\n\tshortDesc: string;\r\n\tdate: number;\r\n}\r\n\r\ninterface TourTable {\r\n\ttitle: string;\r\n\ttours: TourEvent[];\r\n\twhitelist?: string[];\r\n\ticon?: Image;\r\n\tdesc: string;\r\n}\r\n\r\nexport const tours: Record<string, TourTable> = {\r\n\tofficial: {\r\n\t\ttitle: \"Smogon Officials\",\r\n\t\t// cap this one's dimensions\r\n\t\ticon: ['https://www.smogon.com/media/zracknel-beta.svg', 178, 200],\r\n\t\ttours: [],\r\n\t\tdesc: \"Tournaments run by Smogon staff.\",\r\n\t},\r\n\tsmogon: {\r\n\t\ttitle: \"Open Sign-Ups\",\r\n\t\ttours: [],\r\n\t\tdesc: \"Tournaments run by Smogon staff and regular users alike.\",\r\n\t},\r\n\tps: {\r\n\t\ttitle: \"Pok\u00E9mon Showdown!\",\r\n\t\ticon: ['https://play.pokemonshowdown.com/pokemonshowdownbeta.png', 146, 44],\r\n\t\ttours: [],\r\n\t\tdesc: \"Tournaments run by the rooms of Pokemon Showdown.\",\r\n\t},\r\n};\r\ntry {\r\n\tconst data = JSON.parse(FS('config/chat-plugins/smogtours.json').readSync());\r\n\t// settings should prioritize hardcoded values for these keys\r\n\tconst PRIO = ['title', 'icon'];\r\n\tfor (const key in data) {\r\n\t\tconst section = (tours[key] ||= data[key]) as any;\r\n\t\tfor (const k in data[key]) {\r\n\t\t\tif (PRIO.includes(k)) {\r\n\t\t\t\tif (!section[k]) section[k] = data[key][k];\r\n\t\t\t} else {\r\n\t\t\t\tsection[k] = data[key][k];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n} catch {}\r\n\r\nfunction saveTours() {\r\n\tFS('config/chat-plugins/smogtours.json').writeUpdate(() => JSON.stringify(tours));\r\n}\r\n\r\nfunction getTour(categoryID: ID, id: string) {\r\n\tid = toID(id);\r\n\treturn tours?.[categoryID].tours.find(f => f.id === id) || null;\r\n}\r\n\r\nfunction checkWhitelisted(category: ID, user: User) {\r\n\treturn category ?\r\n\t\ttours[category].whitelist?.includes(user.id) :\r\n\t\tObject.values(tours).some(f => f.whitelist?.includes(user.id));\r\n}\r\n\r\nfunction checkCanEdit(user: User, context: Chat.PageContext | Chat.CommandContext, category?: ID) {\r\n\tcategory = toID(category);\r\n\tif (!checkWhitelisted(category, user)) {\r\n\t\tcontext.checkCan('rangeban');\r\n\t}\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tsmogtours: {\r\n\t\t''() {\r\n\t\t\treturn this.parse('/j view-tournaments-all');\r\n\t\t},\r\n\t\tedit: 'add',\r\n\t\tasync add(target, room, user, connection, cmd) {\r\n\t\t\tif (!toID(target).length) {\r\n\t\t\t\treturn this.parse(`/help smogtours`);\r\n\t\t\t}\r\n\t\t\tconst targets = target.split('|');\r\n\t\t\tconst isEdit = cmd === 'edit';\r\n\t\t\tconst tourID = isEdit ? toID(targets.shift()) : null;\r\n\t\t\t// {title}|{category}|{url}|{img}|{shortDesc}|{desc}\r\n\t\t\tconst [\r\n\t\t\t\ttitle, rawSection, url, rawImg, rawShort, rawDesc,\r\n\t\t\t] = Utils.splitFirst(targets.join('|'), '|', 5).map(f => f.trim());\r\n\t\t\tconst sectionID = toID(rawSection);\r\n\t\t\tif (!toID(title)) {\r\n\t\t\t\treturn this.popupReply(`Invalid title. Must have at least one alphanumeric character.`);\r\n\t\t\t}\r\n\t\t\tconst section = tours[sectionID];\r\n\t\t\tif (!section) {\r\n\t\t\t\treturn this.errorReply(`Invalid section ID: \"${sectionID}\"`);\r\n\t\t\t}\r\n\t\t\tif (!isEdit && section.tours.find(f => toID(title) === f.id)) {\r\n\t\t\t\treturn this.popupReply(`A tour with that ID already exists. Please choose another.`);\r\n\t\t\t}\r\n\t\t\tcheckCanEdit(user, this, sectionID);\r\n\t\t\tif (!Chat.isLink(url)) {\r\n\t\t\t\treturn this.popupReply(`Invalid info URL: \"${url}\"`);\r\n\t\t\t}\r\n\t\t\tlet image;\r\n\t\t\tif (rawImg) {\r\n\t\t\t\tif (!Chat.isLink(rawImg)) {\r\n\t\t\t\t\treturn this.popupReply(`Invalid image URL: ${rawImg}`);\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\tconst dimensions = await Chat.fitImage(rawImg, 300, 300);\r\n\t\t\t\t\timage = [rawImg, ...dimensions.slice(0, -1)] as Image;\r\n\t\t\t\t} catch (e) {\r\n\t\t\t\t\treturn this.popupReply(`Invalid image URL: ${rawImg}`);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (!rawShort?.length || !rawDesc?.length) {\r\n\t\t\t\treturn this.popupReply(`Must provide both a short description and a full description.`);\r\n\t\t\t}\r\n\t\t\tconst tour: TourEvent = {\r\n\t\t\t\ttitle: Utils.escapeHTML(title),\r\n\t\t\t\turl,\r\n\t\t\t\timage,\r\n\t\t\t\tshortDesc: rawShort.replace(/&#13;&#10;/g, '\\n'),\r\n\t\t\t\tdesc: rawDesc.replace(/&#13;&#10;/g, '\\n'),\r\n\t\t\t\tid: tourID || toID(title),\r\n\t\t\t\tdate: Date.now(),\r\n\t\t\t};\r\n\t\t\tif (isEdit) {\r\n\t\t\t\tconst index = section.tours.findIndex(t => t.id === tour.id);\r\n\t\t\t\tif (index < 0) {\r\n\t\t\t\t\treturn this.popupReply(`Tour not found. Create one first.`);\r\n\t\t\t\t}\r\n\t\t\t\tsection.tours.splice(index, 1);\r\n\t\t\t}\r\n\t\t\tsection.tours.push(tour);\r\n\t\t\tsaveToLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,iBAAwB;AAqBjB,MAAM,QAAmC;AAAA,EAC/C,UAAU;AAAA,IACT,OAAO;AAAA;AAAA,IAEP,MAAM,CAAC,kDAAkD,KAAK,GAAG;AAAA,IACjE,OAAO,CAAC;AAAA,IACR,MAAM;AAAA,EACP;AAAA,EACA,QAAQ;AAAA,IACP,OAAO;AAAA,IACP,OAAO,CAAC;AAAA,IACR,MAAM;AAAA,EACP;AAAA,EACA,IAAI;AAAA,IACH,OAAO;AAAA,IACP,MAAM,CAAC,4DAA4D,KAAK,EAAE;AAAA,IAC1E,OAAO,CAAC;AAAA,IACR,MAAM;AAAA,EACP;AACD;AACA,IAAI;AACH,QAAM,OAAO,KAAK,UAAM,eAAG,oCAAoC,EAAE,SAAS,CAAC;AAE3E,QAAM,OAAO,CAAC,SAAS,MAAM;AAC7B,aAAW,OAAO,MAAM;AACvB,UAAM,UAAW,4BAAe,KAAK,GAAG;AAC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M,4BAA4B;AAAA,IAC/C;AAAA,EACD;AAAA,EACA,eAAe;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AACD;AAGA,SAAS,UAAU,OAAe,SAAmB,OAAiB;AACrE,YAAU;AACV,MAAI,MAAM;AACV,MAAI,OAAO;AAEV,WAAO;AACP,WAAO;AACP,WAAO,6BAA6B;AAAA,EACrC,OAAO;AACN,QAAI,CAAC,SAAS;AACb,cAAQ,6BAA6B;AAAA,IACtC;AACA,WAAO,uLine truncated
"names": []
}
@@ -0,0 +1,108 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var suspect_tests_exports = {};
__export(suspect_tests_exports, {
commands: () => commands,
suspectTests: () => suspectTests
});
module.exports = __toCommonJS(suspect_tests_exports);
var import_fs = require("../../lib/fs");
const SUSPECTS_FILE = "config/suspects.json";
const WHITELIST = ["kris"];
const suspectTests = JSON.parse((0, import_fs.FS)(SUSPECTS_FILE).readIfExistsSync() || "{}");
function saveSuspectTests() {
(0, import_fs.FS)(SUSPECTS_FILE).writeUpdate(() => JSON.stringify(suspectTests));
}
function checkPermissions(context) {
const user = context.user;
if (WHITELIST.includes(user.id))
return true;
context.checkCan("gdeclare");
}
const commands = {
suspect: "suspects",
suspects: {
""(target, room, user) {
if (!Object.keys(suspectTests).length) {
return this.errorReply("There are no suspect tests running.");
}
if (!this.runBroadcast())
return;
let buffer = "<strong>Suspect tests currently running:</strong>";
for (const i of Object.keys(suspectTests)) {
const test = suspectTests[i];
buffer += "<br />";
buffer += `${test.tier}: <a href="${test.url}">${test.suspect}</a> (${test.date})`;
}
return this.sendReplyBox(buffer);
},
edit: "add",
add(target, room, user) {
checkPermissions(this);
const [tier, suspect, date, url] = target.split(",");
if (!(tier && suspect && date && url)) {
return this.parse("/help suspects");
}
const format = Dex.formats.get(tier);
if (!format.exists)
return this.errorReply(`"${tier}" is not a valid tier.`);
const suspectString = suspect.trim();
const [month, day] = date.trim().split(date.includes("-") ? "-" : "/");
const isValidDate = /[0-1]?[0-9]/.test(month) && /[0-3]?[0-9]/.test(day);
if (!isValidDate)
return this.errorReply("Dates must be in the format MM/DD.");
const dateActual = `${month}/${day}`;
const urlActual = url.trim();
if (!/^https:\/\/www\.smogon\.com\/forums\/(threads|posts)\//.test(urlActual)) {
throw new Chat.ErrorMessage("Suspect test URLs must be Smogon threads or posts.");
}
this.privateGlobalModAction(`${user.name} ${suspectTests[format.id] ? "edited the" : "added a"} ${format.name} suspect test.`);
this.globalModlog("SUSPECTTEST", null, `${suspectTests[format.id] ? "edited" : "added"} ${format.name}`);
suspectTests[format.id] = {
tier: format.name,
suspect: suspectString,
date: dateActual,
url: urlActual
};
saveSuspectTests();
},
end: "remove",
delete: "remove",
remove(target, room, user) {
checkPermissions(this);
const format = toID(target);
const test = suspectTests[format];
if (!test)
return this.errorReply(`There is no suspect test for '${target}'. Check spelling?`);
this.privateGlobalModAction(`${user.name} removed the ${test.tier} suspect test.`);
this.globalModlog("SUSPECTTEST", null, `removed ${test.tier}`);
delete suspectTests[format];
saveSuspectTests();
},
help() {
return this.parse("/help suspects");
}
},
suspectshelp() {
this.sendReplyBox(
`Commands to manage suspect tests:<br /><code>/suspects</code>: displays currently running suspect tests.<br /><code>/suspects add [tier], [suspect], [date], [link]</code>: adds a suspect test. Date in the format MM/DD. Requires: &<br /><code>/suspects remove [tier]</code>: deletes a suspect test. Requires: &`
);
}
};
//# sourceMappingURL=suspect-tests.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/suspect-tests.ts"],
"sourcesContent": ["import {FS} from '../../lib/fs';\r\n\r\nconst SUSPECTS_FILE = 'config/suspects.json';\r\nconst WHITELIST = [\"kris\"];\r\n\r\ninterface SuspectTest {\r\n\ttier: string;\r\n\tsuspect: string;\r\n\tdate: string;\r\n\turl: string;\r\n}\r\n\r\nexport const suspectTests: {[format: string]: SuspectTest} = JSON.parse(FS(SUSPECTS_FILE).readIfExistsSync() || \"{}\");\r\n\r\nfunction saveSuspectTests() {\r\n\tFS(SUSPECTS_FILE).writeUpdate(() => JSON.stringify(suspectTests));\r\n}\r\n\r\nfunction checkPermissions(context: Chat.CommandContext) {\r\n\tconst user = context.user;\r\n\tif (WHITELIST.includes(user.id)) return true;\r\n\tcontext.checkCan('gdeclare');\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tsuspect: 'suspects',\r\n\tsuspects: {\r\n\t\t''(target, room, user) {\r\n\t\t\tif (!Object.keys(suspectTests).length) {\r\n\t\t\t\treturn this.errorReply(\"There are no suspect tests running.\");\r\n\t\t\t}\r\n\t\t\tif (!this.runBroadcast()) return;\r\n\r\n\t\t\tlet buffer = '<strong>Suspect tests currently running:</strong>';\r\n\t\t\tfor (const i of Object.keys(suspectTests)) {\r\n\t\t\t\tconst test = suspectTests[i];\r\n\t\t\t\tbuffer += '<br />';\r\n\t\t\t\tbuffer += `${test.tier}: <a href=\"${test.url}\">${test.suspect}</a> (${test.date})`;\r\n\t\t\t}\r\n\t\t\treturn this.sendReplyBox(buffer);\r\n\t\t},\r\n\r\n\t\tedit: 'add',\r\n\t\tadd(target, room, user) {\r\n\t\t\tcheckPermissions(this);\r\n\r\n\t\t\tconst [tier, suspect, date, url] = target.split(',');\r\n\t\t\tif (!(tier && suspect && date && url)) {\r\n\t\t\t\treturn this.parse('/help suspects');\r\n\t\t\t}\r\n\r\n\t\t\tconst format = Dex.formats.get(tier);\r\n\t\t\tif (!format.exists) return this.errorReply(`\"${tier}\" is not a valid tier.`);\r\n\r\n\t\t\tconst suspectString = suspect.trim();\r\n\r\n\t\t\tconst [month, day] = date.trim().split(date.includes('-') ? '-' : '/');\r\n\t\t\tconst isValidDate = /[0-1]?[0-9]/.test(month) && /[0-3]?[0-9]/.test(day);\r\n\t\t\tif (!isValidDate) return this.errorReply(\"Dates must be in the format MM/DD.\");\r\n\t\t\tconst dateActual = `${month}/${day}`;\r\n\r\n\t\t\tconst urlActual = url.trim();\r\n\t\t\tif (!/^https:\\/\\/www\\.smogon\\.com\\/forums\\/(threads|posts)\\//.test(urlActual)) {\r\n\t\t\t\tthrow new Chat.ErrorMessage(\"Suspect test URLs must be Smogon threads or posts.\");\r\n\t\t\t}\r\n\r\n\t\t\tthis.privateGlobalModAction(`${user.name} ${suspectTests[format.id] ? \"edited the\" : \"added a\"} ${format.name} suspect test.`);\r\n\t\t\tthis.globalModlog('SUSPECTTEST', null, `${suspectTests[format.id] ? \"edited\" : \"added\"} ${format.name}`);\r\n\r\n\t\t\tsuspectTests[format.id] = {\r\n\t\t\t\ttier: format.name,\r\n\t\t\t\tsuspect: suspectString,\r\n\t\t\t\tdate: dateActual,\r\n\t\t\t\turl: urlActual,\r\n\t\t\t};\r\n\t\t\tsaveSuspectTests();\r\n\t\t},\r\n\r\n\t\tend: 'remove',\r\n\t\tdelete: 'remove',\r\n\t\tremove(target, room, user) {\r\n\t\t\tcheckPermissions(this);\r\n\r\n\t\t\tconst format = toID(target);\r\n\t\t\tconst test = suspectTests[format];\r\n\t\t\tif (!test) return this.errorReply(`There is no suspect test for '${target}'. Check spelling?`);\r\n\r\n\t\t\tthis.privateGlobalModAction(`${user.name} removed the ${test.tier} suspect test.`);\r\n\t\t\tthis.globalModlog('SUSPECTTEST', null, `removed ${test.tier}`);\r\n\r\n\t\t\tdelete suspectTests[format];\r\n\t\t\tsaveSuspectTests();\r\n\t\t},\r\n\r\n\t\thelp() {\r\n\t\t\treturn this.parse('/help suspects');\r\n\t\t},\r\n\t},\r\n\r\n\tsuspectshelp() {\r\n\t\tthis.sendReplyBox(\r\n\t\t\t`Commands to manage suspect tests:<br />` +\r\n\t\t\t`<code>/suspects</code>: displays currently running suspect tests.<br />` +\r\n\t\t\t`<code>/suspects add [tier], [suspect], [date], [link]</code>: adds a suspect test. Date in the format MM/DD. Requires: &<br />` +\r\n\t\t\t`<code>/suspects remove [tier]</code>: deletes a suspect test. Requires: &`\r\n\t\t);\r\n\t},\r\n};\r\n"],
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAiB;AAEjB,MAAM,gBAAgB;AACtB,MAAM,YAAY,CAAC,MAAM;AASlB,MAAM,eAAgD,KAAK,UAAM,cAAG,aAAa,EAAE,iBAAiB,KAAK,IAAI;AAEpH,SAAS,mBAAmB;AAC3B,oBAAG,aAAa,EAAE,YAAY,MAAM,KAAK,UAAU,YAAY,CAAC;AACjE;AAEA,SAAS,iBAAiB,SAA8B;AACvD,QAAM,OAAO,QAAQ;AACrB,MAAI,UAAU,SAAS,KAAK,EAAE;AAAG,WAAO;AACxC,UAAQ,SAAS,UAAU;AAC5B;AAEO,MAAM,WAA8B;AAAA,EAC1C,SAAS;AAAA,EACT,UAAU;AAAA,IACT,GAAG,QAAQ,MAAM,MAAM;AACtB,UAAI,CAAC,OAAO,KAAK,YAAY,EAAE,QAAQ;AACtC,eAAO,KAAK,WAAW,qCAAqC;AAAA,MAC7D;AACA,UAAI,CAAC,KAAK,aAAa;AAAG;AAE1B,UAAI,SAAS;AACb,iBAAW,KAAK,OAAO,KAAK,YAAY,GAAG;AAC1C,cAAM,OAAO,aAAa,CAAC;AAC3B,kBAAU;AACV,kBAAU,GAAG,KAAK,kBAAkB,KAAK,QAAQ,KAAK,gBAAgB,KAAK;AAAA,MAC5E;AACA,aAAO,KAAK,aAAa,MAAM;AAAA,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CAAC;AAAM,eAAO,KAAK,WAAW,iCAAiC,0BAA0B;AAE7F,WAAK,uBAAuB,GAAG,KAAK,oBAAoB,KAAK,oBAAoB;AACjF,WAAK,aAAa,eAAe,MAAM,WAAW,KAAK,MAAM;AAE7D,aAAO,aAAa,MAAM;AAC1B,uBAAiB;AAAA,IAClB;AAAA,IAEA,OAAO;AACN,aAAO,KAAK,MAAM,gBAAgB;AAAA,IACnC;AAAA,EACD;AAAA,EAEA,eAAe;AACd,SAAK;AAAA,MACJ;AAAA,IAID;AAAA,EACD;AACD;",
"names": []
}
+123
View File
@@ -0,0 +1,123 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var tcgtabletop_exports = {};
__export(tcgtabletop_exports, {
commands: () => commands
});
module.exports = __toCommonJS(tcgtabletop_exports);
var import_lib = require("../../lib");
const SEARCH_PATH = "/api/v1/Search/List/";
const DETAILS_PATH = "/api/v1/Articles/Details/";
async function getFandom(site, pathName, search) {
const body = await (0, import_lib.Net)(`https://${site}.fandom.com/${pathName}`).get({ query: search });
const json = JSON.parse(body);
if (!json)
throw new Error(`Malformed data`);
if (json.exception)
throw new Error(import_lib.Utils.getString(json.exception.message) || `Not found`);
return json;
}
async function searchFandom(site, query) {
const result = await getFandom(site, SEARCH_PATH, { query, limit: 1 });
if (!Array.isArray(result.items) || !result.items.length)
throw new Error(`Malformed data`);
if (!result.items[0] || typeof result.items[0] !== "object")
throw new Error(`Malformed data`);
return result.items[0];
}
async function getCardDetails(site, id) {
const specifications = {
ids: id,
abstract: 0,
width: 80,
height: 115
};
const result = await getFandom(site, DETAILS_PATH, specifications);
if (typeof result.items !== "object" || !result.items[id] || typeof result.items[id] !== "object") {
throw new Error(`Malformed data`);
}
return result.items[id];
}
const commands = {
ygo: "yugioh",
yugioh(target, room, user) {
this.checkBroadcast();
room = this.requireRoom("tcgtabletop");
const subdomain = "yugioh";
const query = target.trim();
if (!query)
return this.parse("/help yugioh");
return searchFandom(subdomain, query).then((data) => {
if (!this.runBroadcast())
return;
const entryUrl = import_lib.Utils.getString(data.url);
const entryTitle = import_lib.Utils.getString(data.title);
const id = import_lib.Utils.getString(data.id);
let htmlReply = import_lib.Utils.html`<strong>Best result for ${query}:</strong><br /><a href="${entryUrl}">${entryTitle}</a>`;
if (id) {
getCardDetails(subdomain, id).then((card) => {
if (!room)
return;
const thumb = import_lib.Utils.getString(card.thumbnail);
if (thumb) {
htmlReply = `<table><tr><td style="padding-right:5px;"><img src="${import_lib.Utils.escapeHTML(thumb)}" width=80 height=115></td><td>${htmlReply}</td></tr></table>`;
}
if (!this.broadcasting)
return this.sendReply(`|raw|<div class="infobox">${htmlReply}</div>`);
room.addRaw(`<div class="infobox">${htmlReply}</div>`).update();
}, () => {
if (!room)
return;
if (!this.broadcasting)
return this.sendReply(`|raw|<div class="infobox">${htmlReply}</div>`);
room.addRaw(`<div class="infobox">${htmlReply}</div>`).update();
});
} else {
if (!room)
return;
if (!this.broadcasting)
return this.sendReply(`|raw|<div class="infobox">${htmlReply}</div>`);
room.addRaw(`<div class="infobox">${htmlReply}</div>`).update();
}
}, (err) => {
if (!this.runBroadcast())
return;
if (!room)
return;
if (err instanceof SyntaxError || err.message === "Malformed data") {
if (!this.broadcasting)
return this.sendReply(`Error: Something went wrong in the request: ${err.message}`);
return room.add(`Error: Something went wrong in the request: ${err.message}`).update();
} else if (err.message === "Not found") {
if (!this.broadcasting)
return this.sendReply('|raw|<div class="infobox">No results found.</div>');
return room.addRaw('<div class="infobox">No results found.</div>').update();
} else if (err.code === "ENOTFOUND") {
if (!this.broadcasting)
return this.sendReply("Error connecting to the yugioh wiki.");
return room.add("Error connecting to the yugioh wiki.").update();
}
if (!this.broadcasting)
return this.sendReply(`Error: ${err.message}`);
return room.add(`Error: ${err.message}`).update();
});
},
yugiohhelp: [`/yugioh [query] - Search the Yugioh wiki.`]
};
//# sourceMappingURL=tcgtabletop.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/tcgtabletop.ts"],
"sourcesContent": ["/**\r\n* TCG & Tabletop: Yugioh wiki plugin\r\n* This is a command that allows users to search the yugioh wiki for cards.\r\n* It will display the closest match with a given query, or a separate message if there isn't anything found.\r\n* By bumbadadabum with help from ascriptmaster, codelegend and the PS development team.\r\n*/\r\n\r\n\r\nimport {Net, Utils} from '../../lib';\r\nconst SEARCH_PATH = '/api/v1/Search/List/';\r\nconst DETAILS_PATH = '/api/v1/Articles/Details/';\r\n\r\nasync function getFandom(site: string, pathName: string, search: AnyObject) {\r\n\tconst body = await Net(`https://${site}.fandom.com/${pathName}`).get({query: search});\r\n\tconst json = JSON.parse(body);\r\n\tif (!json) throw new Error(`Malformed data`);\r\n\tif (json.exception) throw new Error(Utils.getString(json.exception.message) || `Not found`);\r\n\treturn json;\r\n}\r\n\r\nasync function searchFandom(site: string, query: string) {\r\n\tconst result = await getFandom(site, SEARCH_PATH, {query, limit: 1});\r\n\tif (!Array.isArray(result.items) || !result.items.length) throw new Error(`Malformed data`);\r\n\tif (!result.items[0] || typeof result.items[0] !== 'object') throw new Error(`Malformed data`);\r\n\treturn result.items[0];\r\n}\r\n\r\nasync function getCardDetails(site: string, id: string) {\r\n\tconst specifications = {\r\n\t\tids: id,\r\n\t\tabstract: 0,\r\n\t\twidth: 80,\r\n\t\theight: 115,\r\n\t};\r\n\r\n\tconst result = await getFandom(site, DETAILS_PATH, specifications);\r\n\tif (typeof result.items !== 'object' || !result.items[id] || typeof result.items[id] !== 'object') {\r\n\t\tthrow new Error(`Malformed data`);\r\n\t}\r\n\treturn result.items[id];\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tygo: 'yugioh',\r\n\tyugioh(target, room, user) {\r\n\t\tthis.checkBroadcast();\r\n\t\troom = this.requireRoom('tcgtabletop' as RoomID);\r\n\t\tconst subdomain = 'yugioh';\r\n\t\tconst query = target.trim();\r\n\t\tif (!query) return this.parse('/help yugioh');\r\n\r\n\t\treturn searchFandom(subdomain, query).then((data: {url: unknown, title: unknown, id: unknown}) => {\r\n\t\t\tif (!this.runBroadcast()) return;\r\n\t\t\tconst entryUrl = Utils.getString(data.url);\r\n\t\t\tconst entryTitle = Utils.getString(data.title);\r\n\t\t\tconst id = Utils.getString(data.id);\r\n\t\t\tlet htmlReply = Utils.html`<strong>Best result for ${query}:</strong><br /><a href=\"${entryUrl}\">${entryTitle}</a>`;\r\n\t\t\tif (id) {\r\n\t\t\t\tgetCardDetails(subdomain, id).then((card: {thumbnail: unknown}) => {\r\n\t\t\t\t\tif (!room) return; // do nothing if the room doesn't exist anymore\r\n\t\t\t\t\tconst thumb = Utils.getString(card.thumbnail);\r\n\t\t\t\t\tif (thumb) {\r\n\t\t\t\t\t\thtmlReply = `<table><tr><td style=\"padding-right:5px;\"><img src=\"${Utils.escapeHTML(thumb)}\" width=80 height=115></td><td>${htmlReply}</td></tr></table>`;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!this.broadcasting) return this.sendReply(`|raw|<div class=\"infobox\">${htmlReply}</div>`);\r\n\t\t\t\t\troom.addRaw(`<div class=\"infobox\">${htmlReply}</div>`).update();\r\n\t\t\t\t}, () => {\r\n\t\t\t\t\tif (!room) return; // do nothing if the room doesn't exist anymore\r\n\t\t\t\t\tif (!this.broadcasting) return this.sendReply(`|raw|<div class=\"infobox\">${htmlReply}</div>`);\r\n\t\t\t\t\troom.addRaw(`<div class=\"infobox\">${htmlReply}</div>`).update();\r\n\t\t\t\t});\r\n\t\t\t} else {\r\n\t\t\t\tif (!room) return; // do nothing if the room doesn't exist anymore\r\n\t\t\t\tif (!this.broadcasting) return this.sendReply(`|raw|<div class=\"infobox\">${htmlReply}</div>`);\r\n\t\t\t\troom.addRaw(`<div class=\"infobox\">${htmlReply}</div>`).update();\r\n\t\t\t}\r\n\t\t}, (err: Error & {code: string}) => {\r\n\t\t\tif (!this.runBroadcast()) return;\r\n\t\t\tif (!room) return; // do nothing if the room doesn't exist anymore\r\n\r\n\t\t\tif (err instanceof SyntaxError || err.message === 'Malformed data') {\r\n\t\t\t\tif (!this.broadcasting) return this.sendReply(`Error: Something went wrong in the request: ${err.message}`);\r\n\t\t\t\treturn room.add(`Error: Something went wrong in the request: ${err.message}`).update();\r\n\t\t\t} else if (err.message === 'Not found') {\r\n\t\t\t\tif (!this.broadcasting) return this.sendReply('|raw|<div class=\"infobox\">No results found.</div>');\r\n\t\t\t\treturn room.addRaw('<div class=\"infobox\">No results found.</div>').update();\r\n\t\t\t} else if (err.code === \"ENOTFOUND\") {\r\n\t\t\t\tif (!this.broadcasting) return this.sendReply(\"Error connecting to the yugioh wiki.\");\r\n\t\t\t\treturn room.add(\"Error connecting to the yugioh wiki.\").update();\r\n\t\t\t}\r\n\t\t\tif (!this.broadcasting) return this.sendReply(`Error: ${err.message}`);\r\n\t\t\treturn room.add(`Error: ${err.message}`).update();\r\n\t\t});\r\n\t},\r\n\tyugiohhelp: [`/yugioh [query] - Search the Yugioh wiki.`],\r\n};\r\n"],
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,iBAAyB;AACzB,MAAM,cAAc;AACpB,MAAM,eAAe;AAErB,eAAe,UAAU,MAAc,UAAkB,QAAmB;AAC3E,QAAM,OAAO,UAAM,gBAAI,WAAW,mBAAmB,UAAU,EAAE,IAAI,EAAC,OAAO,OAAM,CAAC;AACpF,QAAM,OAAO,KAAK,MAAM,IA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AAI,SAAS,aAAa;AACpC,YAAI,CAAC,KAAK;AAAc,iBAAO,KAAK,UAAU,sCAAsC;AACpF,eAAO,KAAK,IAAI,sCAAsC,EAAE,OAAO;AAAA,MAChE;AACA,UAAI,CAAC,KAAK;AAAc,eAAO,KAAK,UAAU,UAAU,IAAI,SAAS;AACrE,aAAO,KAAK,IAAI,UAAU,IAAI,SAAS,EAAE,OAAO;AAAA,IACjD,CAAC;AAAA,EACF;AAAA,EACA,YAAY,CAAC,2CAA2C;AACzD;",
"names": []
}
+647
View File
@@ -0,0 +1,647 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var the_studio_exports = {};
__export(the_studio_exports, {
LastFM: () => LastFM,
LastFMInterface: () => LastFMInterface,
Recs: () => Recs,
commands: () => commands,
pages: () => pages
});
module.exports = __toCommonJS(the_studio_exports);
var import_lib = require("../../lib");
var import_youtube = require("./youtube");
const LASTFM_DB = "config/chat-plugins/lastfm.json";
const RECOMMENDATIONS = "config/chat-plugins/the-studio.json";
const API_ROOT = "http://ws.audioscrobbler.com/2.0/";
const DEFAULT_IMAGES = [
"https://lastfm.freetls.fastly.net/i/u/34s/2a96cbd8b46e442fc41c2b86b821562f.png",
"https://lastfm.freetls.fastly.net/i/u/64s/2a96cbd8b46e442fc41c2b86b821562f.png",
"https://lastfm.freetls.fastly.net/i/u/174s/2a96cbd8b46e442fc41c2b86b821562f.png",
"https://lastfm.freetls.fastly.net/i/u/300x300/2a96cbd8b46e442fc41c2b86b821562f.png"
];
const lastfm = JSON.parse((0, import_lib.FS)(LASTFM_DB).readIfExistsSync() || "{}");
const recommendations = JSON.parse((0, import_lib.FS)(RECOMMENDATIONS).readIfExistsSync() || "{}");
if (!recommendations.saved)
recommendations.saved = [];
if (!recommendations.suggested)
recommendations.suggested = [];
saveRecommendations();
function updateRecTags() {
for (const rec of recommendations.saved) {
if (!rec.tags.map(toID).includes(toID(rec.artist)))
rec.tags.push(rec.artist);
if (!rec.tags.map(toID).includes(toID(rec.userData.name)))
rec.tags.push(rec.userData.name);
}
for (const rec of recommendations.suggested) {
if (!rec.tags.map(toID).includes(toID(rec.artist)))
rec.tags.push(rec.artist);
if (!rec.tags.map(toID).includes(toID(rec.userData.name)))
rec.tags.push(rec.userData.name);
}
saveRecommendations();
}
updateRecTags();
function saveLastFM() {
(0, import_lib.FS)(LASTFM_DB).writeUpdate(() => JSON.stringify(lastfm));
}
function saveRecommendations() {
(0, import_lib.FS)(RECOMMENDATIONS).writeUpdate(() => JSON.stringify(recommendations));
}
class LastFMInterface {
async getScrobbleData(username, displayName) {
this.checkHasKey();
const accountName = this.getAccountName(username);
let raw;
try {
raw = await (0, import_lib.Net)(API_ROOT).get({
query: {
method: "user.getRecentTracks",
user: accountName,
limit: 1,
api_key: Config.lastfmkey,
format: "json"
}
});
} catch {
throw new Chat.ErrorMessage(`No scrobble data found.`);
}
const res = JSON.parse(raw);
if (res.error) {
throw new Chat.ErrorMessage(`${res.message}.`);
}
if (!res?.recenttracks?.track?.length)
throw new Chat.ErrorMessage(`last.fm account not found.`);
const track = res.recenttracks.track[0];
let buf = `<table><tr>`;
if (track.image?.length) {
const imageIndex = track.image.length >= 3 ? 2 : track.image.length - 1;
if (track.image[imageIndex]["#text"]) {
buf += `<td style="padding-right:5px"><img src="${track.image[imageIndex]["#text"]}" width="75" height="75" /></td>`;
}
buf += `<td><strong><a href="https://www.last.fm/user/${accountName}">${import_lib.Utils.escapeHTML(displayName || accountName)}</a></strong>`;
if (track["@attr"]?.nowplaying) {
buf += ` is currently listening to:`;
} else {
buf += ` was last seen listening to:`;
}
buf += `<br />`;
const trackName = `${track.artist?.["#text"] ? `${track.artist["#text"]} - ` : ""}${track.name}`;
let videoIDs;
try {
videoIDs = await import_youtube.YouTube.searchVideo(trackName, 1);
} catch (e) {
throw new Chat.ErrorMessage(`Error while fetching video data: ${e.message}`);
}
if (!videoIDs?.length) {
throw new Chat.ErrorMessage(`Something went wrong with the YouTube API.`);
}
buf += `<a href="https://youtu.be/${videoIDs[0]}">${import_lib.Utils.escapeHTML(trackName)}</a>`;
buf += `</td></tr></table>${this.getScrobbleBadge()}`;
}
return buf;
}
addAccountName(userid, accountName) {
this.checkHasKey();
accountName = accountName.trim();
if (lastfm[userid]) {
const oldName = lastfm[userid];
lastfm[userid] = accountName;
saveLastFM();
return `last.fm account name changed from '${oldName}' to '${accountName}'.`;
}
lastfm[userid] = accountName;
saveLastFM();
return `Registered last.fm account '${accountName}'.`;
}
validateAccountName(accountName) {
accountName = accountName.trim();
const sanitizedName = accountName.replace(/[^-_a-zA-Z0-9]+/g, "");
if (!(!accountName.includes(" ") && accountName === sanitizedName && /^[a-zA-Z]/.test(sanitizedName) && sanitizedName.length > 1 && sanitizedName.length < 16)) {
throw new Chat.ErrorMessage(`The provided account name (${sanitizedName}) is invalid. Valid last.fm usernames are between 2-15 characters, start with a letter, and only contain letters, numbers, hyphens, and underscores.`);
}
return true;
}
getAccountName(username) {
if (lastfm[toID(username)])
return lastfm[toID(username)];
return username.trim().replace(/ /g, "_").replace(/[^-_a-zA-Z0-9]/g, "");
}
async tryGetTrackData(track, artist) {
this.checkHasKey();
const query = {
method: "track.search",
limit: 1,
api_key: Config.lastfmkey,
track,
format: "json"
};
if (artist)
query.artist = artist;
let raw;
try {
raw = await (0, import_lib.Net)(API_ROOT).get({ query });
} catch {
throw new Chat.ErrorMessage(`No track data found.`);
}
const req = JSON.parse(raw);
let buf = ``;
if (req.results?.trackmatches?.track?.length) {
buf += `<table><tr><td style="padding-right:5px">`;
const obj = req.results.trackmatches.track[0];
const trackName = obj.name || "Untitled";
const artistName = obj.artist || "Unknown Artist";
const searchName = `${artistName} - ${trackName}`;
if (obj.image?.length) {
const img = obj.image;
const imageIndex = img.length >= 3 ? 2 : img.length - 1;
if (img[imageIndex]["#text"] && !DEFAULT_IMAGES.includes(img[imageIndex]["#text"])) {
buf += `<img src="${img[imageIndex]["#text"]}" width="75" height="75" />`;
}
}
buf += `</td><td>`;
const artistUrl = obj.url.split("_/")[0];
buf += `<strong><a href="${artistUrl}">${artistName}</a> - <a href="${obj.url}">${trackName}</a></strong><br />`;
let videoIDs;
try {
videoIDs = await import_youtube.YouTube.searchVideo(searchName, 1);
} catch (e) {
throw new Chat.ErrorMessage(`Error while fetching video data: ${e.message}`);
}
if (!videoIDs?.length) {
buf += searchName;
} else {
buf += `<a href="https://youtu.be/${videoIDs[0]}">YouTube link</a>`;
}
buf += `</td></tr></table>${this.getScrobbleBadge()}`;
}
if (req.error) {
throw new Chat.ErrorMessage(`${req.message}.`);
}
if (!buf) {
throw new Chat.ErrorMessage(`No results for '${artist ? `${artist} - ` : ``}${track}' found. Check spelling?`);
}
return buf;
}
checkHasKey() {
if (!Config.lastfmkey) {
throw new Chat.ErrorMessage(`This server does not support last.fm commands. If you're the owner, you can enable them by setting up Config.lastfmkey.`);
}
}
getScrobbleBadge() {
return `<div style="float:right;color:#888;font-size:8pt">[powered by AudioScrobbler]</div><div style="clear:both"></div>`;
}
}
class RecommendationsInterface {
getRandomRecommendation() {
const recs = recommendations.saved;
return recs[Math.floor(Math.random() * recs.length)];
}
async add(artist, title, url, description, username, tags, avatar) {
artist = artist.trim();
title = title.trim();
if (this.get(artist, title)) {
throw new Chat.ErrorMessage(`The song titled '${title}' by ${artist} is already recommended.`);
}
if (!/^https?:\/\//.test(url))
url = `https://${url}`;
if (!import_youtube.YouTube.linkRegex.test(url)) {
throw new Chat.ErrorMessage(`Please provide a valid YouTube link.`);
}
url = url.split("&")[0];
const videoInfo = await import_youtube.YouTube.getVideoData(url);
this.checkTags(tags);
if (!recommendations.saved)
recommendations.saved = [];
const rec = { artist, title, videoInfo, url, description, tags, userData: { name: username }, likes: 0 };
if (!rec.tags.map(toID).includes(toID(username)))
rec.tags.push(username);
if (!rec.tags.map(toID).includes(toID(artist)))
rec.tags.push(artist);
if (avatar)
rec.userData.avatar = avatar;
recommendations.saved.push(rec);
saveRecommendations();
}
delete(artist, title) {
artist = artist.trim();
title = title.trim();
if (!recommendations.saved?.length) {
throw new Chat.ErrorMessage(`The song titled '${title}' by ${artist} isn't recommended.`);
}
const recIndex = this.getIndex(artist, title);
if (recIndex < 0) {
throw new Chat.ErrorMessage(`The song titled '${title}' by ${artist} isn't recommended.`);
}
recommendations.saved.splice(recIndex, 1);
saveRecommendations();
}
async suggest(artist, title, url, description, username, tags, avatar) {
artist = artist.trim();
title = title.trim();
if (this.get(artist, title)) {
throw new Chat.ErrorMessage(`The song titled '${title}' by ${artist} is already recommended.`);
}
if (this.get(artist, title, null, true)) {
throw new Chat.ErrorMessage(`The song titled '${title}' by ${artist} is already suggested.`);
}
if (!/^https?:\/\//.test(url))
url = `https://${url}`;
if (!import_youtube.YouTube.linkRegex.test(url)) {
throw new Chat.ErrorMessage(`Please provide a valid YouTube link.`);
}
url = url.split("&")[0];
const videoInfo = await import_youtube.YouTube.getVideoData(url);
this.checkTags(tags);
const rec = { artist, title, videoInfo, url, description, tags, userData: { name: username }, likes: 0 };
if (!rec.tags.map(toID).includes(toID(username)))
rec.tags.push(username);
if (!rec.tags.map(toID).includes(toID(artist)))
rec.tags.push(artist);
if (avatar)
rec.userData.avatar = avatar;
recommendations.suggested.push(rec);
saveRecommendations();
}
approveSuggestion(submitter, artist, title) {
artist = artist.trim();
title = title.trim();
const rec = this.get(artist, title, submitter, true);
if (!rec) {
throw new Chat.ErrorMessage(`There is no song titled '${title}' by ${artist} suggested from ${submitter.trim()}.`);
}
if (!recommendations.saved)
recommendations.saved = [];
recommendations.saved.push(rec);
recommendations.suggested.splice(recommendations.suggested.indexOf(rec), 1);
saveRecommendations();
}
denySuggestion(submitter, artist, title) {
artist = artist.trim();
title = title.trim();
const index = this.getIndex(artist, title, submitter, true);
if (index < 0) {
throw new Chat.ErrorMessage(`There is no song titled '${title}' by ${artist} suggested from ${submitter.trim()}.`);
}
recommendations.suggested.splice(index, 1);
saveRecommendations();
}
async render(rec, suggested = false) {
let buf = ``;
buf += `<div style="color:#000;background:linear-gradient(rgba(210,210,210),rgba(225,225,225))">`;
buf += `<table style="margin:auto;background:rgba(255,255,255,0.25);padding:3px;"><tbody><tr>`;
if (rec.videoInfo === void 0) {
rec.videoInfo = await import_youtube.YouTube.getVideoData(rec.videoInfo);
saveRecommendations();
}
if (rec.videoInfo) {
buf += `<td style="text-align:center;"><img src="${rec.videoInfo.thumbnail}" width="120" height="67" /><br />`;
buf += `<small><em>${!suggested ? `${Chat.count(rec.likes, "points")} | ` : ``}${rec.videoInfo.views} views</em></small></td>`;
}
buf += import_lib.Utils.html`<td style="max-width:300px"><a href="${rec.url}" style="color:#000;font-weight:bold;">${rec.artist} - ${rec.title}</a>`;
const tags = rec.tags.map((x) => import_lib.Utils.escapeHTML(x)).filter((x) => toID(x) !== toID(rec.userData.name) && toID(x) !== toID(rec.artist));
if (tags.length) {
buf += `<br /><strong>Tags:</strong> <em>${tags.join(", ")}</em>`;
}
if (rec.description) {
buf += `<br /><span style="display:inline-block;line-height:1.15em;"><strong>Description:</strong> ${import_lib.Utils.escapeHTML(rec.description)}</span>`;
}
if (!rec.videoInfo && !suggested) {
buf += `<br /><strong>Score:</strong> ${Chat.count(rec.likes, "points")}`;
}
if (!rec.userData.avatar) {
buf += `<br /><strong>Recommended by:</strong> ${rec.userData.name}`;
}
buf += `<hr />`;
if (suggested) {
buf += import_lib.Utils.html`<button class="button" name="send" value="/msgroom thestudio,/approvesuggestion ${rec.userData.name}|${rec.artist}|${rec.title}">Approve</button> | `;
buf += import_lib.Utils.html`<button class="button" name="send" value="/msgroom thestudio,/denysuggestion ${rec.userData.name}|${rec.artist}|${rec.title}">Deny</button>`;
} else {
buf += import_lib.Utils.html`<button class="button" name="send" value="/msgroom thestudio,/likerec ${rec.artist}|${rec.title}" style="float:right;display:inline;padding:3px 5px;font-size:8pt;">`;
buf += `<img src="https://${Config.routes.client}/sprites/bwicons/441.png" style="margin:-9px 0 -6px -7px;" width="32" height="32" />`;
buf += `<span style="position:relative;bottom:2.6px;">Upvote</span></button>`;
}
buf += `</td>`;
if (rec.userData.avatar) {
buf += `<td style="text-align:center;width:110px;background:rgba(255,255,255,0.4);border-radius:15px;">`;
const isCustom = rec.userData.avatar.startsWith("#");
buf += `<img style="margin-bottom:-38px;" src="https://${Config.routes.client}/sprites/trainers${isCustom ? "-custom" : ""}/${isCustom ? rec.userData.avatar.slice(1) : rec.userData.avatar}.png" width="80" height="80" />`;
buf += `<br /><span style="background:rgba(0,0,0,0.5);padding:1.5px 4px;color:white;font-size:7pt;">Recommended by:`;
buf += `<br /><strong>${rec.userData.name}</strong></span></td>`;
} else {
buf += `<td><span style="background:rgba(0,0,0,0.5);padding:1.5px 4px;color:white;font-size:7pt;">Recommended by: <strong>${rec.userData.name}</strong></span></td>`;
}
buf += `</tbody></table>`;
buf += `</div>`;
return buf;
}
likeRecommendation(artist, title, liker) {
const rec = this.get(artist, title);
if (!rec) {
throw new Chat.ErrorMessage(`The song titled '${title}' by ${artist} isn't recommended.`);
}
if (!rec.liked) {
rec.liked = { ips: [], userids: [] };
}
if (!Config.noipchecks && rec.liked.ips.includes(liker.latestIp) || rec.liked.userids.includes(liker.id)) {
throw new Chat.ErrorMessage(`You've already liked this recommendation.`);
}
rec.likes++;
rec.liked.ips.push(liker.latestIp);
rec.liked.userids.push(liker.id);
saveRecommendations();
}
get(artist, title, submitter = null, fromSuggestions = false) {
let recs = recommendations.saved;
if (fromSuggestions)
recs = recommendations.suggested;
return recs.find((x) => toID(x.artist) === toID(artist) && toID(x.title) === toID(title) && (!submitter || toID(x.userData.name) === toID(submitter)));
}
getIndex(artist, title, submitter = null, fromSuggestions = false) {
let recs = recommendations.saved;
if (fromSuggestions)
recs = recommendations.suggested;
return recs.findIndex((x) => toID(x.artist) === toID(artist) && toID(x.title) === toID(title) && (!submitter || toID(x.userData.name) === toID(submitter)));
}
checkTags(tags) {
const cleansedTags = /* @__PURE__ */ new Set();
for (const tag of tags) {
if (!toID(tag))
throw new Chat.ErrorMessage(`Empty tag detected.`);
if (cleansedTags.has(toID(tag))) {
throw new Chat.ErrorMessage(`Duplicate tag: ${tag.trim()}`);
}
cleansedTags.add(toID(tag));
}
}
}
const LastFM = new LastFMInterface();
const Recs = new RecommendationsInterface();
const commands = {
registerlastfm(target, room, user) {
if (!target)
return this.parse(`/help registerlastfm`);
this.checkChat(target);
target = this.filter(target) || "";
if (!target) {
throw new Chat.ErrorMessage(`The provided account name has phrases that PS doesn't allow.`);
}
LastFM.validateAccountName(target);
this.sendReply(LastFM.addAccountName(user.id, target.trim()));
},
registerlastfmhelp: [
`/registerlastfm [username] - Adds the provided [username] to the last.fm database for scrobbling.`,
`Usernames can only be 2-15 characters long, must start with a letter, and can only contain letters, numbers, hyphens, and underscores.`
],
async lastfm(target, room, user) {
this.checkChat();
if (!user.autoconfirmed)
return this.errorReply(`You cannot use this command while not autoconfirmed.`);
this.runBroadcast(true);
const targetUsername = this.splitUser(target).targetUsername || (user.named ? user.name : "");
const username = LastFM.getAccountName(targetUsername);
this.sendReplyBox(await LastFM.getScrobbleData(username, targetUsername));
},
lastfmhelp: [
`/lastfm [username] - Displays the last scrobbled song for the person using the command or for [username] if provided.`,
`To link up your last.fm account, check out "/help registerlastfm".`
],
async track(target, room, user) {
if (!target)
return this.parse("/help track");
this.checkChat();
if (!user.autoconfirmed)
return this.errorReply(`You cannot use this command while not autoconfirmed.`);
const [track, artist] = this.splitOne(target);
if (!track)
return this.parse("/help track");
this.runBroadcast(true);
this.sendReplyBox(await LastFM.tryGetTrackData(track, artist || void 0));
},
trackhelp: [
`/track [song name], [artist] - Displays the most relevant search result to the song name (and artist if specified) provided.`
],
addrec: "addrecommendation",
async addrecommendation(target, room, user) {
room = this.requireRoom("thestudio");
this.checkCan("show", null, room);
const [artist, title, url, description, ...tags] = target.split("|").map((x) => x.trim());
if (!(artist && title && url && description && tags?.length)) {
return this.parse(`/help addrecommendation`);
}
const cleansedTags = tags.map((x) => x.trim());
await Recs.add(artist, title, url, description, user.name, cleansedTags, String(user.avatar));
this.privateModAction(`${user.name} added a recommendation for '${title}' by ${artist}.`);
this.modlog(`RECOMMENDATION`, null, `add: '${toID(title)}' by ${toID(artist)}`);
},
addrecommendationhelp: [
`/addrecommendation artist | song title | url | description | tag1 | tag2 | ... - Adds a song recommendation. Requires: + % @ * # &`
],
delrec: "removerecommendation",
removerecommendation(target, room, user) {
room = this.requireRoom("thestudio");
const [artist, title] = target.split(`|`).map((x) => x.trim());
if (!(artist && title))
return this.parse(`/help removerecommendation`);
const rec = Recs.get(artist, title);
if (!rec)
throw new Chat.ErrorMessage(`Recommendation not found.`);
if (toID(rec.userData.name) !== user.id) {
this.checkCan("mute", null, room);
}
Recs.delete(artist, title);
this.privateModAction(`${user.name} removed a recommendation for '${title}' by ${artist}.`);
this.modlog(`RECOMMENDATION`, null, `remove: '${toID(title)}' by ${toID(artist)}`);
},
removerecommendationhelp: [
`/removerecommendation artist | song title - Removes a song recommendation. Requires: % @ * # &`,
`If you added a recommendation, you can remove it on your own without being one of the required ranks.`
],
suggestrec: "suggestrecommendation",
async suggestrecommendation(target, room, user) {
room = this.requireRoom("thestudio");
if (!target) {
return this.parse("/help suggestrecommendation");
}
this.checkChat(target);
if (!user.autoconfirmed)
return this.errorReply(`You cannot use this command while not autoconfirmed.`);
const [artist, title, url, description, ...tags] = target.split("|").map((x) => x.trim());
if (!(artist && title && url && description && tags?.length)) {
return this.parse(`/help suggestrecommendation`);
}
const cleansedTags = tags.map((x) => x.trim());
await Recs.suggest(artist, title, url, description, user.name, cleansedTags, String(user.avatar));
this.sendReply(`Your suggestion for '${title}' by ${artist} has been submitted.`);
const html = await Recs.render({
artist,
title,
url,
description,
userData: { name: user.name, avatar: String(user.avatar) },
tags: cleansedTags,
likes: 0,
videoInfo: null
}, true);
room.sendRankedUsers(`|html|${html}`, "%");
},
suggestrecommendationhelp: [
`/suggestrecommendation artist | song title | url | description | tag1 | tag2 | ... - Suggest a song recommendation.`
],
approvesuggestion(target, room, user) {
room = this.requireRoom("thestudio");
this.checkCan("mute", null, room);
const [submitter, artist, title] = target.split("|").map((x) => x.trim());
if (!(submitter && artist && title))
return this.parse(`/help approvesuggestion`);
Recs.approveSuggestion(submitter, artist, title);
this.privateModAction(`${user.name} approved a suggested recommendation from ${submitter} for '${title}' by ${artist}.`);
this.modlog(`RECOMMENDATION`, null, `approve: '${toID(title)}' by ${toID(artist)} from ${submitter}`);
},
approvesuggestionhelp: [
`/approvesuggestion submitter | artist | strong title - Approve a submitted song recommendation. Requires: % @ * # &`
],
denysuggestion(target, room, user) {
room = this.requireRoom("thestudio");
this.checkCan("mute", null, room);
const [submitter, artist, title] = target.split("|").map((x) => x.trim());
if (!(submitter && artist && title))
return this.parse(`/help approvesuggestion`);
Recs.denySuggestion(submitter, artist, title);
this.privateModAction(`${user.name} denied a suggested recommendation from ${submitter} for '${title}' by ${artist}.`);
this.modlog(`RECOMMENDATION`, null, `deny: '${toID(title)}' by ${toID(artist)} from ${submitter}`);
},
denysuggestionhelp: [
`/denysuggestion submitter | artist | strong title - Deny a submitted song recommendation. Requires: % @ * # &`
],
rec: "recommendation",
searchrec: "recommendation",
viewrec: "recommendation",
searchrecommendation: "recommendation",
viewrecommendation: "recommendation",
randrec: "recommendation",
randomrecommendation: "recommendation",
async recommendation(target, room, user) {
if (!recommendations.saved.length) {
throw new Chat.ErrorMessage(`There are no recommendations saved.`);
}
room = this.requireRoom("thestudio");
this.runBroadcast();
if (!target) {
return this.sendReply(`|html|${await Recs.render(Recs.getRandomRecommendation())}`);
}
const matches = [];
target = target.slice(0, 300);
const args = target.split(",");
for (const rec of recommendations.saved) {
if (!args.every((x) => rec.tags.map(toID).includes(toID(x))))
continue;
matches.push(rec);
}
if (!matches.length) {
throw new Chat.ErrorMessage(`No matches found.`);
}
const sample = import_lib.Utils.shuffle(matches)[0];
this.sendReply(`|html|${await Recs.render(sample)}`);
},
recommendationhelp: [
`/recommendation [key1, key2, key3, ...] - Displays a random recommendation that matches all keys, if one exists.`,
`If no arguments are provided, a random recommendation is shown.`,
`/addrecommendation artist | song title | url | description | tag1 | tag2 | ... - Adds a song recommendation. Requires: + % @ * # &`,
`/removerecommendation artist | song title - Removes a song recommendation. Requires: % @ * # &`,
`If you added a recommendation, you can remove it on your own without being one of the required ranks.`,
`/suggestrecommendation artist | song title | url | description | tag1 | tag2 | ... - Suggest a song recommendation.`
],
likerec: "likerecommendation",
likerecommendation(target, room, user, connection) {
room = this.requireRoom("thestudio");
const [artist, title] = target.split("|").map((x) => x.trim());
if (!(artist && title))
return this.parse(`/help likerecommendation`);
Recs.likeRecommendation(artist, title, user);
this.sendReply(`You liked '${title}' by ${artist}.`);
},
likerecommendationhelp: [
`/likerecommendation artist | title - Upvotes a recommendation for the provided artist and title.`
],
viewrecs: "viewrecommendations",
viewrecommendations(target, room, user) {
room = this.requireRoom("thestudio");
this.parse(`/j view-recommendations-${room.roomid}`);
},
viewrecommendationshelp: [
`/viewrecommendations OR /viewrecs - View all recommended songs.`
],
viewsuggestions: "viewsuggestedrecommendations",
viewsuggestedrecs: "viewsuggestedrecommendations",
viewsuggestedrecommendations(target, room, user) {
room = this.requireRoom("thestudio");
this.parse(`/j view-suggestedrecommendations-${room.roomid}`);
},
viewsuggestedrecommendationshelp: [
`/viewsuggestedrecommendations OR /viewsuggestions - View all suggested recommended songs. Requires: % @ * # &`
]
};
const pages = {
async recommendations(query, user, connection) {
const room = this.requireRoom();
this.checkCan("mute", null, room);
if (!user.inRooms.has(room.roomid))
throw new Chat.ErrorMessage(`You must be in ${room.title} to view this page.`);
this.title = "Recommendations";
let buf = `<div class="pad">`;
buf += `<button style="float:right" class="button" name="send" value="/j view-recommendations-${room.roomid}"><i class="fa fa-refresh"></i> Refresh</button>`;
const recs = recommendations.saved;
if (!recs?.length) {
return `${buf}<h2>There are currently no recommendations.</h2></div>`;
}
buf += `<h2>Recommendations (${recs.length}):</h2>`;
for (const rec of recs) {
buf += `<div class="infobox">`;
buf += await Recs.render(rec);
if (user.can("mute", null, room) || toID(rec.userData.name) === user.id) {
buf += `<hr /><button class="button" name="send" value="/msgroom thestudio,/removerecommendation ${rec.artist}|${rec.title}">Delete</button>`;
}
buf += `</div>`;
}
return buf;
},
async suggestedrecommendations(query, user, connection) {
const room = this.requireRoom();
this.checkCan("mute", null, room);
if (!user.inRooms.has(room.roomid))
throw new Chat.ErrorMessage(`You must be in ${room.title} to view this page.`);
this.title = "Suggested Recommendations";
let buf = `<div class="pad">`;
buf += `<button style="float:right" class="button" name="send" value="/j view-suggestedrecommendations-${room.roomid}"><i class="fa fa-refresh"></i> Refresh</button>`;
const recs = recommendations.suggested;
if (!recs?.length) {
return `${buf}<h2>There are currently no suggested recommendations.</h2></div>`;
}
buf += `<h2>Suggested Recommendations (${recs.length}):</h2>`;
for (const rec of recs) {
buf += `<div class="infobox">`;
buf += await Recs.render(rec, true);
buf += `</div>`;
}
return buf;
}
};
//# sourceMappingURL=the-studio.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/the-studio.ts"],
"sourcesContent": ["/**\r\n * The Studio room chat-plugin.\r\n * Supports scrobbling and searching for music from last.fm.\r\n * Also supports storing and suggesting recommendations.\r\n * Written by Kris, loosely based on the concept from bumbadadabum.\r\n * @author Kris\r\n */\r\n\r\nimport {FS, Net, Utils} from '../../lib';\r\nimport {YouTube, VideoData} from './youtube';\r\n\r\nconst LASTFM_DB = 'config/chat-plugins/lastfm.json';\r\nconst RECOMMENDATIONS = 'config/chat-plugins/the-studio.json';\r\nconst API_ROOT = 'http://ws.audioscrobbler.com/2.0/';\r\nconst DEFAULT_IMAGES = [\r\n\t'https://lastfm.freetls.fastly.net/i/u/34s/2a96cbd8b46e442fc41c2b86b821562f.png',\r\n\t'https://lastfm.freetls.fastly.net/i/u/64s/2a96cbd8b46e442fc41c2b86b821562f.png',\r\n\t'https://lastfm.freetls.fastly.net/i/u/174s/2a96cbd8b46e442fc41c2b86b821562f.png',\r\n\t'https://lastfm.freetls.fastly.net/i/u/300x300/2a96cbd8b46e442fc41c2b86b821562f.png',\r\n];\r\n\r\ninterface Recommendation {\r\n\tartist: string;\r\n\ttitle: string;\r\n\turl: string;\r\n\tvideoInfo: VideoData | null;\r\n\tdescription: string;\r\n\ttags: string[];\r\n\tuserData: {\r\n\t\tname: string,\r\n\t\tavatar?: string,\r\n\t};\r\n\tlikes: number;\r\n\tliked?: {\r\n\t\tips: string[],\r\n\t\tuserids: string[],\r\n\t};\r\n}\r\n\r\ninterface Recommendations {\r\n\tsuggested: Recommendation[];\r\n\tsaved: Recommendation[];\r\n}\r\n\r\nconst lastfm: {[userid: string]: string} = JSON.parse(FS(LASTFM_DB).readIfExistsSync() || \"{}\");\r\nconst recommendations: Recommendations = JSON.parse(FS(RECOMMENDATIONS).readIfExistsSync() || \"{}\");\r\n\r\nif (!recommendations.saved) recommendations.saved = [];\r\nif (!recommendations.suggested) recommendations.suggested = [];\r\nsaveRecommendations();\r\n\r\nfunction updateRecTags() {\r\n\tfor (const rec of recommendations.saved) {\r\n\t\tif (!rec.tags.map(toID).includes(toID(rec.artist))) rec.tags.push(rec.artist);\r\n\t\tif (!rec.tags.map(toID).includes(toID(rec.userData.name))) rec.tags.push(rec.userData.name);\r\n\t}\r\n\tfor (const rec of recommendations.suggested) {\r\n\t\tif (!rec.tags.map(toID).includes(toID(rec.artist))) rec.tags.push(rec.artist);\r\n\t\tif (!rec.tags.map(toID).includes(toID(rec.userData.name))) rec.tags.push(rec.userData.name);\r\n\t}\r\n\tsaveRecommendations();\r\n}\r\n\r\nupdateRecTags();\r\n\r\nfunction saveLastFM() {\r\n\tFS(LASTFM_DB).writeUpdate(() => JSON.stringify(lastfm));\r\n}\r\nfunction saveRecommendations() {\r\n\tFS(RECOMMENDATIONS).writeUpdate(() => JSON.stringify(recommendations));\r\n}\r\n\r\nexport class LastFMInterface {\r\n\tasync getScrobbleData(username: string, displayName?: string) {\r\n\t\tthis.checkHasKey();\r\n\t\tconst accountName = this.getAccountName(username);\r\n\t\tlet raw;\r\n\t\ttry {\r\n\t\t\traw = await Net(API_ROOT).get({\r\n\t\t\t\tquery: {\r\n\t\t\t\t\tmethod: 'user.getRecentTracks', user: accountName,\r\n\t\t\t\t\tlimit: 1, api_key: Config.lastfmkey, format: 'json',\r\n\t\t\t\t},\r\n\t\t\t});\r\n\t\t} catch {\r\n\t\t\tthrow new Chat.ErrorMessage(`No scrobble data found.`);\r\n\t\t}\r\n\t\tconst res = JSON.parse(raw);\r\n\t\tif (res.error) {\r\n\t\t\tthrow new Chat.ErrorMessage(`${res.message}.`);\r\n\t\t}\r\n\t\tif (!res?.recenttracks?.track?.length) throw new Chat.ErrorMessage(`last.fm account not found.`);\r\n\t\tconst track = res.recenttracks.track[0];\r\n\t\tlet buf = `<table><tr>`;\r\n\t\tif (track.image?.length) {\r\n\t\t\tconst imageIndex = track.image.length >= 3 ? 2 : track.image.length - 1;\r\n\t\t\tif (track.image[imageIndex]['#text']) {\r\n\t\t\t\tbuf += `<td style=\"padding-right:5px\"><img src=\"${track.image[imageIndex]['#text']}\" width=\"75\" height=\"75\" /></td>`;\r\n\t\t\t}\r\n\t\t\tbuf += `<td><strong><a href=\"https://www.last.fm/user/${accountName}\">${Utils.escapeHTML(displayName || accountName)}</a></strong>`;\r\n\t\t\tif (track['@attr']?.nowplaying) {\r\n\t\t\t\tbuf += ` is currently listening to:`;\r\n\t\t\t} else {\r\n\t\t\t\tbuf += ` was last seen listening to:`;\r\n\t\t\t}\r\n\t\t\tbuf += `<br />`;\r\n\t\t\tconst trackName = `${track.artist?.['#text'] ? `${track.artist['#text']} - ` : ''}${track.name}`;\r\n\t\t\tlet videoIDs: string[] | undefined;\r\n\t\t\ttry {\r\n\t\t\t\tvideoIDs = await YouTube.searchVideo(trackName, 1);\r\n\t\t\t} catch (e: any) {\r\n\t\t\t\tthrow new Chat.ErrorMessage(`Error while fetching video data: ${e.message}`);\r\n\t\t\t}\r\n\t\t\tif (!videoIDs?.length) {\r\n\t\t\t\tthrow new Chat.ErrorMessage(`Something went wrong with the YouTube API.`);\r\n\t\t\t}\r\n\t\t\tbuf += `<a href=\"https://youtu.be/${videoIDs[0]}\">${Utils.escapeHTML(trackName)}</a>`;\r\n\t\t\tbuf += `</td></tr></table>${this.getScrobbleBadge()}`;\r\n\t\t}\r\n\t\treturn buf;\r\n\t}\r\n\r\n\taddAccountName(userid: ID, accountName: string) {\r\n\t\tthis.checkHasKey();\r\n\t\taccountName = accountName.trim();\r\n\t\tif (lastfm[userid]) {\r\n\t\t\tconst oldName = lastfm[userid];\r\n\t\t\tlastfm[userid] = accountName;\r\n\t\t\tsaveLastFM();\r\n\Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,iBAA6B;AAC7B,qBAAiC;AAEjC,MAAM,YAAY;AAClB,MAAM,kBAAkB;AACxB,MAAM,WAAW;AACjB,MAAM,iBAAiB;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AAyBA,MAAM,SAAqC,KAAK,UAAM,eAAG,SAAS,EAAE,iBAAiB,KAAK,IAAI;AAC9F,MAAM,kBAAmC,KAAK,UAAM,eAAG,eAAe,EAAE,iBAAiB,KAAK,IAAI;AAElG,IAAI,CAAC,gBAAgB;AAAO,kBAAgB,QAAQ,CAAC;AACrD,IAAI,CAAC,gBAAgB;AAAW,kBAAgB,YAAY,CAAC;AAC7D,oBAAoB;AAEpB,SAAS,gBAAgB;AACxB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S,OAAO,KAAK;AACrB,YAAQ,MAAM,KAAK;AACnB,QAAI,KAAK,IAAI,QAAQ,KAAK,GAAG;AAC5B,YAAM,IAAI,KAAK,aAAa,oBAAoB,aAAa,gCAAgC;AAAA,IAC9F;AACA,QAAI,CAAC,eAAe,KAAK,GAAG;AAAG,YAAM,WAAW;AAChD,QAAI,CAAC,uBAAQ,UAAU,KAAK,GAAG,GAAG;AACjC,YAAM,IAAI,KAAK,aAAa,sCAAsC;AAAA,IACnE;AACA,UAAM,IAAI,MAAM,GAAG,EAAE,CAAC;AACtB,UAAM,YAAY,MAAM,uBAAQ,aAAa,GAAG;AAChD,SAAK,UAAU,IAAI;AAEnB,QLine truncated
"names": []
}
+203
View File
@@ -0,0 +1,203 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var thecafe_exports = {};
__export(thecafe_exports, {
commands: () => commands,
pages: () => pages
});
module.exports = __toCommonJS(thecafe_exports);
var import_fs = require("../../lib/fs");
var import_utils = require("../../lib/utils");
const DISHES_FILE = "config/chat-plugins/thecafe-foodfight.json";
const FOODFIGHT_COOLDOWN = 5 * 60 * 1e3;
const dishes = JSON.parse((0, import_fs.FS)(DISHES_FILE).readIfExistsSync() || "{}");
function saveDishes() {
void (0, import_fs.FS)(DISHES_FILE).write(JSON.stringify(dishes));
}
function generateTeam(generator = "") {
let potentialPokemon = Object.keys(Dex.data.Pokedex).filter((mon) => {
const species = Dex.species.get(mon);
return species.baseSpecies === species.name;
});
let speciesClause = true;
switch (generator) {
case "ou":
potentialPokemon = potentialPokemon.filter((mon) => {
const species = Dex.species.get(mon);
return species.tier === "OU";
}).concat(potentialPokemon.filter((mon) => {
const species = Dex.species.get(mon);
return species.tier === "OU" || species.tier === "UU";
}));
break;
case "ag":
potentialPokemon = potentialPokemon.filter((mon) => {
const species = Dex.species.get(mon);
const unviable = species.tier === "NFE" || species.tier === "PU" || species.tier === "(PU)" || species.tier.startsWith("LC");
const illegal = species.tier === "Unreleased" || species.tier === "Illegal" || species.tier.startsWith("CAP");
return !(unviable || illegal);
});
speciesClause = false;
break;
default:
potentialPokemon = potentialPokemon.filter((mon) => {
const species = Dex.species.get(mon);
const op = species.tier === "AG" || species.tier === "Uber" || species.tier.slice(1, -1) === "Uber";
const unviable = species.tier === "Illegal" || species.tier.includes("LC");
return !(op || unviable);
});
potentialPokemon.push("miltank", "miltank", "miltank", "miltank");
}
const team = [];
while (team.length < 6) {
const randIndex = Math.floor(Math.random() * potentialPokemon.length);
const potentialMon = potentialPokemon[randIndex];
if (team.includes(potentialMon))
continue;
team.push(potentialMon);
if (speciesClause)
potentialPokemon.splice(randIndex, 1);
}
return team.map((mon) => Dex.species.get(mon).name);
}
function generateDish() {
const keys = Object.keys(dishes);
const entry = dishes[keys[Math.floor(Math.random() * keys.length)]].slice();
const dish = entry.splice(0, 1)[0];
const ingredients = [];
while (ingredients.length < 6) {
ingredients.push(entry.splice(Math.floor(Math.random() * entry.length), 1)[0]);
}
return [dish, ingredients];
}
const commands = {
foodfight(target, room, user) {
room = this.requireRoom("thecafe");
if (!Object.keys(dishes).length)
return this.errorReply("No dishes found. Add some dishes first.");
if (user.foodfight && user.foodfight.timestamp + FOODFIGHT_COOLDOWN > Date.now()) {
return this.errorReply("Please wait a few minutes before using this command again.");
}
target = toID(target);
let team = [];
let importable;
const [newDish, newIngredients] = generateDish();
if (!target) {
const bfTeam = Teams.generate("gen7bssfactory");
for (const [i, name] of newIngredients.entries())
bfTeam[i].name = name;
importable = Teams.export(bfTeam);
team = bfTeam.map((val) => val.species);
} else {
team = generateTeam(target);
}
user.foodfight = { generatedTeam: team, dish: newDish, ingredients: newIngredients, timestamp: Date.now() };
const importStr = importable ? import_utils.Utils.html`<tr><td colspan=7><details><summary style="font-size:13pt;">Importable team:</summary><div style="width:100%;height:400px;overflow:auto;color:black;font-family:monospace;background:white;text-align:left;">${importable}</textarea></details></td></tr>` : "";
return this.sendReplyBox(`<div class="ladder"><table style="text-align:center;"><tr><th colspan="7" style="font-size:10pt;">Your dish is: <u>${newDish}</u></th></tr><tr><th>Team</th>${team.map((mon) => `<td><psicon pokemon="${mon}"/> ${mon}</td>`).join("")}</tr><tr><th>Ingredients</th>${newIngredients.map((ingredient) => `<td>${ingredient}</td>`).join("")}</tr>${importStr}</table></div>`);
},
checkfoodfight(target, room, user) {
room = this.requireRoom("thecafe");
const targetUser = this.getUserOrSelf(target);
if (!targetUser)
return this.errorReply(`User ${target} not found.`);
const self = targetUser === user;
if (!self)
this.checkCan("mute", targetUser, room);
const foodfight = targetUser.foodfight;
if (!foodfight) {
return this.errorReply(`${self ? `You don't` : `This user doesn't`} have an active Foodfight team.`);
}
return this.sendReplyBox(/* @__PURE__ */ Chat.h("div", { class: "ladder" }, /* @__PURE__ */ Chat.h("table", { style: { textAlign: "center" } }, /* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("th", { colSpan: 7, style: { fontSize: "10pt" } }, self ? `Your` : `${targetUser.name}'s`, " dish is: ", /* @__PURE__ */ Chat.h("u", null, foodfight.dish))), /* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("th", null, "Team"), foodfight.generatedTeam.map((mon) => /* @__PURE__ */ Chat.h("td", null, /* @__PURE__ */ Chat.h("psicon", { pokemon: mon }), " ", mon))), /* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("th", null, "Ingredients"), foodfight.ingredients.map((ingredient) => /* @__PURE__ */ Chat.h("td", null, ingredient))))));
},
addingredients: "adddish",
adddish(target, room, user, connection, cmd) {
room = this.requireRoom("thecafe");
this.checkCan("mute", null, room);
let [dish, ...ingredients] = target.split(",");
dish = dish.trim();
if (!dish || !ingredients.length)
return this.parse("/help foodfight");
const id = toID(dish);
if (id === "constructor")
return this.errorReply("Invalid dish name.");
ingredients = ingredients.map((ingredient) => ingredient.trim());
if ([...ingredients.entries()].some(([index, ingredient]) => ingredients.indexOf(ingredient) !== index)) {
return this.errorReply("Please don't enter duplicate ingredients.");
}
if (ingredients.some((ingredient) => ingredient.length > 19)) {
return this.errorReply("Ingredients can only be 19 characters long.");
}
if (cmd === "adddish") {
if (dishes[id])
return this.errorReply("This dish already exists.");
if (ingredients.length < 6)
return this.errorReply("Dishes need at least 6 ingredients.");
dishes[id] = [dish];
} else {
if (!dishes[id])
return this.errorReply(`Dish not found: ${dish}`);
if (ingredients.some((ingredient) => dishes[id].includes(ingredient))) {
return this.errorReply("Please don't enter duplicate ingredients.");
}
}
dishes[id] = dishes[id].concat(ingredients);
saveDishes();
this.sendReply(`${cmd.slice(3)} '${dish}: ${ingredients.join(", ")}' added successfully.`);
},
removedish(target, room, user) {
room = this.requireRoom("thecafe");
this.checkCan("mute", null, room);
const id = toID(target);
if (id === "constructor")
return this.errorReply("Invalid dish.");
if (!dishes[id])
return this.errorReply(`Dish '${target}' not found.`);
delete dishes[id];
saveDishes();
this.sendReply(`Dish '${target}' deleted successfully.`);
},
viewdishes(target, room, user, connection) {
room = this.requireRoom("thecafe");
return this.parse(`/join view-foodfight`);
},
foodfighthelp: [
`/foodfight <generator> - Gives you a randomly generated Foodfight dish, ingredient list and team. Generator can be either 'random', 'ou', 'ag', or left blank. If left blank, uses Battle Factory to generate an importable team.`,
`/checkfoodfight <username> - Gives you the last team and dish generated for the entered user, or your own if left blank. Anyone can check their own info, checking other people requires: % @ # &`,
`/adddish <dish>, <ingredient>, <ingredient>, ... - Adds a dish to the database. Requires: % @ # &`,
`/addingredients <dish>, <ingredient>, <ingredient>, ... - Adds extra ingredients to a dish in the database. Requires: % @ # &`,
`/removedish <dish> - Removes a dish from the database. Requires: % @ # &`,
`/viewdishes - Shows the entire database of dishes. Requires: % @ # &`
]
};
const pages = {
foodfight(query, user, connection) {
if (!user.named)
return Rooms.RETRY_AFTER_LOGIN;
this.title = "Foodfight";
const room = Rooms.get("thecafe");
if (!room)
return this.errorReply(`Room not found.`);
this.checkCan("mute", null, room);
const content = Object.values(dishes).map(
([dish, ...ingredients]) => /* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("td", null, dish), /* @__PURE__ */ Chat.h("td", null, ingredients.join(", ")))
).join("");
return /* @__PURE__ */ Chat.h("div", { class: "pad ladder" }, /* @__PURE__ */ Chat.h("h2", null, "Foodfight Dish list"), content ? /* @__PURE__ */ Chat.h("table", null, /* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("th", null, /* @__PURE__ */ Chat.h("h3", null, "Dishes")), /* @__PURE__ */ Chat.h("th", null, /* @__PURE__ */ Chat.h("h3", null, "Ingredients"))), content) : /* @__PURE__ */ Chat.h("p", null, "There are no dishes in the database."));
}
};
//# sourceMappingURL=thecafe.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/thecafe.tsx"],
"sourcesContent": ["import {FS} from '../../lib/fs';\r\nimport {Utils} from '../../lib/utils';\r\n\r\nconst DISHES_FILE = 'config/chat-plugins/thecafe-foodfight.json';\r\nconst FOODFIGHT_COOLDOWN = 5 * 60 * 1000;\r\n\r\nconst dishes: {[k: string]: string[]} = JSON.parse(FS(DISHES_FILE).readIfExistsSync() || \"{}\");\r\n\r\nfunction saveDishes() {\r\n\tvoid FS(DISHES_FILE).write(JSON.stringify(dishes));\r\n}\r\n\r\nfunction generateTeam(generator = '') {\r\n\tlet potentialPokemon = Object.keys(Dex.data.Pokedex).filter(mon => {\r\n\t\tconst species = Dex.species.get(mon);\r\n\t\treturn species.baseSpecies === species.name;\r\n\t});\r\n\tlet speciesClause = true;\r\n\tswitch (generator) {\r\n\tcase 'ou':\r\n\t\tpotentialPokemon = potentialPokemon.filter(mon => {\r\n\t\t\tconst species = Dex.species.get(mon);\r\n\t\t\treturn species.tier === 'OU';\r\n\t\t}).concat(potentialPokemon.filter(mon => {\r\n\t\t\t// There is probably a better way to get the ratios right, oh well.\r\n\t\t\tconst species = Dex.species.get(mon);\r\n\t\t\treturn species.tier === 'OU' || species.tier === 'UU';\r\n\t\t}));\r\n\t\tbreak;\r\n\tcase 'ag':\r\n\t\tpotentialPokemon = potentialPokemon.filter(mon => {\r\n\t\t\tconst species = Dex.species.get(mon);\r\n\t\t\tconst unviable = species.tier === 'NFE' || species.tier === 'PU' ||\r\n\t\t\t\tspecies.tier === '(PU)' || species.tier.startsWith(\"LC\");\r\n\t\t\tconst illegal = species.tier === 'Unreleased' || species.tier === 'Illegal' || species.tier.startsWith(\"CAP\");\r\n\t\t\treturn !(unviable || illegal);\r\n\t\t});\r\n\t\tspeciesClause = false;\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tpotentialPokemon = potentialPokemon.filter(mon => {\r\n\t\t\tconst species = Dex.species.get(mon);\r\n\t\t\tconst op = species.tier === 'AG' || species.tier === 'Uber' || species.tier.slice(1, -1) === 'Uber';\r\n\t\t\tconst unviable = species.tier === 'Illegal' || species.tier.includes(\"LC\");\r\n\t\t\treturn !(op || unviable);\r\n\t\t});\r\n\t\tpotentialPokemon.push('miltank', 'miltank', 'miltank', 'miltank'); // 5x chance for miltank for flavor purposes.\r\n\t}\r\n\r\n\tconst team: string[] = [];\r\n\r\n\twhile (team.length < 6) {\r\n\t\tconst randIndex = Math.floor(Math.random() * potentialPokemon.length);\r\n\t\tconst potentialMon = potentialPokemon[randIndex];\r\n\t\tif (team.includes(potentialMon)) continue;\r\n\t\tteam.push(potentialMon);\r\n\t\tif (speciesClause) potentialPokemon.splice(randIndex, 1);\r\n\t}\r\n\r\n\treturn team.map(mon => Dex.species.get(mon).name);\r\n}\r\n\r\nfunction generateDish(): [string, string[]] {\r\n\tconst keys = Object.keys(dishes);\r\n\tconst entry = dishes[keys[Math.floor(Math.random() * keys.length)]].slice();\r\n\tconst dish = entry.splice(0, 1)[0];\r\n\tconst ingredients = [];\r\n\twhile (ingredients.length < 6) {\r\n\t\tingredients.push(entry.splice(Math.floor(Math.random() * entry.length), 1)[0]);\r\n\t}\r\n\treturn [dish, ingredients];\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tfoodfight(target, room, user) {\r\n\t\troom = this.requireRoom('thecafe' as RoomID);\r\n\t\tif (!Object.keys(dishes).length) return this.errorReply(\"No dishes found. Add some dishes first.\");\r\n\r\n\t\tif (user.foodfight && user.foodfight.timestamp + FOODFIGHT_COOLDOWN > Date.now()) {\r\n\t\t\treturn this.errorReply(\"Please wait a few minutes before using this command again.\");\r\n\t\t}\r\n\r\n\t\ttarget = toID(target);\r\n\r\n\t\tlet team: string[] = [];\r\n\t\tlet importable;\r\n\t\tconst [newDish, newIngredients] = generateDish();\r\n\t\tif (!target) {\r\n\t\t\tconst bfTeam = Teams.generate('gen7bssfactory');\r\n\t\t\tfor (const [i, name] of newIngredients.entries()) bfTeam[i].name = name;\r\n\t\t\timportable = Teams.export(bfTeam);\r\n\t\t\tteam = bfTeam.map(val => val.species);\r\n\t\t} else {\r\n\t\t\tteam = generateTeam(target);\r\n\t\t}\r\n\t\tuser.foodfight = {generatedTeam: team, dish: newDish, ingredients: newIngredients, timestamp: Date.now()};\r\n\t\tconst importStr = importable ?\r\n\t\t\tUtils.html`<tr><td colspan=7><details><summary style=\"font-size:13pt;\">Importable team:</summary><div style=\"width:100%;height:400px;overflow:auto;color:black;font-family:monospace;background:white;text-align:left;\">${importable}</textarea></details></td></tr>` :\r\n\t\t\t'';\r\n\t\treturn this.sendReplyBox(`<div class=\"ladder\"><table style=\"text-align:center;\"><tr><th colspan=\"7\" style=\"font-size:10pt;\">Your dish is: <u>${newDish}</u></th></tr><tr><th>Team</th>${team.map(mon => `<td><psicon pokemon=\"${mon}\"/> ${mon}</td>`).join('')}</tr><tr><th>Ingredients</th>${newIngredients.map(ingredient => `<td>${ingredient}</td>`).join('')}</tr>${importStr}</table></div>`);\r\n\t},\r\n\tcheckfoodfight(target, room, user) {\r\n\t\troom = this.requireRoom('thecafe' as RoomID);\r\n\r\n\t\tconst targetUser = this.getUserOrSelf(target);\r\n\t\tif (!targetUser) return this.errorReply(`User ${target} not found.`);\r\n\t\tconst self = targetUser === user;\r\n\t\tif (!selLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAiB;AACjB,mBAAoB;AAEpB,MAAM,cAAc;AACpB,MAAM,qBAAqB,IAAI,KAAK;AAEpC,MAAM,SAAkC,KAAK,UAAM,cAAG,WAAW,EAAE,iBAAiB,KAAK,IAAI;AAE7F,SAAS,aAAa;AACrB,WAAK,cAAG,WAAW,EAAE,MAAM,KAAK,UAAU,MAAM,CAAC;AAClD;AAEA,SAAS,aAAa,YAAY,IAAI;AACrC,MAAI,mBAAmB,OAAO,KAAK,IAAI,KAAK,OAAO,EAAE,OAAO,SAAO;AAClE,UAAM,UAAU,IAAI,QAAQ,IAAI,GAAG;AACnC,WAAO,QAAQ,gBAAgB,QAAQ;AAAA,EACxC,CAAC;AACD,MAAI,gBAAgB;AACpB,UAAQ,WAAW;AAAA,IACnB,KAAK;AACJ,yBAAmB,iBAAiB,OAAO,SAAO;AACjD,cAAM,UAAU,IAAI,QAAQ,IAAI,GAAG;AACnC,eAAO,QAAQ,SAAS;AAAA,MACzB,CAAC,EAAE,OAAO,iBAAiB,OAAO,SAAO;AAExC,cAAM,UAAU,IAAI,QAAQ,IAAI,GAAG;AACnC,eAAO,QAAQ,SAAS,QAAQ,QAAQ,SAAS;AAAA,MAClD,CAAC,CAAC;AACF;AAAA,IACD,KAAK;AACJ,yBAAmB,iBAAiB,OA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A,EACzC;AAAA,EACA,eAAe;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AACD;AAEO,MAAM,QAAwB;AAAALine truncated
"names": []
}
@@ -0,0 +1,870 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var thing_of_the_day_exports = {};
__export(thing_of_the_day_exports, {
commands: () => commands,
handlers: () => handlers,
otdCommands: () => otdCommands,
otdData: () => otdData,
otds: () => otds,
pages: () => pages,
prenoms: () => prenoms,
punishmentfilter: () => punishmentfilter
});
module.exports = __toCommonJS(thing_of_the_day_exports);
var import_lib = require("../../lib");
var import_youtube = require("./youtube");
const MINUTE = 60 * 1e3;
const PRENOM_BUMP_TIME = 2 * 60 * MINUTE;
const PRENOMS_FILE = "config/chat-plugins/otd-prenoms.json";
const DATA_FILE = "config/chat-plugins/otds.json";
const prenoms = JSON.parse((0, import_lib.FS)(PRENOMS_FILE).readIfExistsSync() || "{}");
const otdData = JSON.parse((0, import_lib.FS)(DATA_FILE).readIfExistsSync() || "{}");
const otds = /* @__PURE__ */ new Map();
const FINISH_HANDLERS = {
cotw: async (winner) => {
const { channel, nominator } = winner;
const searchResults = await import_youtube.YouTube.searchChannel(channel, 1);
const result = searchResults?.[0];
if (result) {
if (import_youtube.YouTube.data.channels[result])
return;
void import_youtube.YouTube.getChannelData(`https://www.youtube.com/channel/${result}`);
const yt = Rooms.get("youtube");
if (!yt)
return;
yt.sendMods(
`|c|&|/log The channel with ID ${result} was added to the YouTube channel database.`
);
yt.modlog({
action: `ADDCHANNEL`,
note: `${result} (${toID(nominator)})`,
loggedBy: toID(`COTW`)
});
}
}
};
function savePrenoms() {
return (0, import_lib.FS)(PRENOMS_FILE).writeUpdate(() => JSON.stringify(prenoms));
}
function toNominationId(nomination) {
return nomination.toLowerCase().replace(/\s/g, "").replace(/\b&\b/g, "");
}
class OtdHandler {
constructor(id, room, settings) {
this.id = id;
this.name = settings.title;
this.room = room;
this.nominations = new Map(prenoms[id]);
this.removedNominations = /* @__PURE__ */ new Map();
this.voting = false;
this.timer = null;
this.keys = settings.keys;
this.keyLabels = settings.keyLabels;
this.timeLabel = settings.timeLabel;
this.settings = settings;
this.lastPrenom = 0;
this.winners = otdData[this.id]?.winners || [];
}
static create(room, settings) {
const { title, timeLabel } = settings;
const id = settings.id || toID(title).charAt(0) + "ot" + timeLabel.charAt(0);
const handler = new OtdHandler(id, room, settings);
otds.set(id, handler);
let needsSave = false;
for (const winner of handler.winners) {
if (winner.timestamp) {
winner.time = winner.timestamp;
delete winner.timestamp;
needsSave = true;
}
}
if (needsSave)
handler.save();
return handler;
}
static parseOldWinners(content, keyLabels, keys) {
const data = ("" + content).split("\n");
const winners = [];
for (const arg of data) {
if (!arg || arg === "\r")
continue;
if (arg.startsWith(`${keyLabels[0]} `)) {
continue;
}
const entry = {};
const vals = arg.trim().split(" ");
for (let i = 0; i < vals.length; i++) {
entry[keys[i]] = vals[i];
}
entry.time = Number(entry.time) || 0;
winners.push(entry);
}
return winners;
}
/**
* Handles old-format data from the IP and userid refactor
*/
convertNominations() {
for (const value of this.nominations.values()) {
if (!Array.isArray(value.userids))
value.userids = Object.keys(value.userids);
if (!Array.isArray(value.ips))
value.ips = Object.keys(value.ips);
}
for (const value of this.removedNominations.values()) {
if (!Array.isArray(value.userids))
value.userids = Object.keys(value.userids);
if (!Array.isArray(value.ips))
value.ips = Object.keys(value.ips);
}
}
startVote() {
this.voting = true;
this.timer = setTimeout(() => this.rollWinner(), 20 * MINUTE);
this.display();
}
finish() {
this.voting = false;
this.nominations = /* @__PURE__ */ new Map();
this.removedNominations = /* @__PURE__ */ new Map();
delete prenoms[this.id];
void savePrenoms();
if (this.timer)
clearTimeout(this.timer);
}
addNomination(user, nomination) {
const id = toNominationId(nomination);
if (this.winners.slice(-30).some((entry) => toNominationId(entry[this.keys[0]]) === id)) {
return user.sendTo(this.room, `This ${this.name.toLowerCase()} has already been ${this.id} in the past month.`);
}
for (const value of this.removedNominations.values()) {
if (value.userids.includes(toID(user)) || !Config.noipchecks && value.ips.includes(user.latestIp)) {
return user.sendTo(
this.room,
`Since your nomination has been removed by staff, you cannot submit another ${this.name.toLowerCase()} until the next round.`
);
}
}
const prevNom = this.nominations.get(id);
if (prevNom) {
if (!(prevNom.userids.includes(toID(user)) || !Config.noipchecks && prevNom.ips.includes(user.latestIp))) {
return user.sendTo(this.room, `This ${this.name.toLowerCase()} has already been nominated.`);
}
}
for (const [key, value] of this.nominations) {
if (value.userids.includes(toID(user)) || !Config.noipchecks && value.ips.includes(user.latestIp)) {
user.sendTo(this.room, `Your previous vote for ${value.nomination} will be removed.`);
this.nominations.delete(key);
if (prenoms[this.id]) {
const idx = prenoms[this.id].findIndex((val) => val[0] === key);
if (idx > -1) {
prenoms[this.id].splice(idx, 1);
void savePrenoms();
}
}
}
}
const obj = {};
obj[user.id] = user.name;
const nomObj = {
nomination,
name: user.name,
userids: user.previousIDs.concat(user.id),
ips: user.ips.slice()
};
this.nominations.set(id, nomObj);
if (!prenoms[this.id])
prenoms[this.id] = [];
prenoms[this.id].push([id, nomObj]);
void savePrenoms();
user.sendTo(this.room, `Your nomination for ${nomination} was successfully submitted.`);
let updateOnly = !this.voting;
if (updateOnly) {
const now = Date.now();
if (now - this.lastPrenom > PRENOM_BUMP_TIME) {
updateOnly = false;
this.lastPrenom = now;
}
}
if (this.settings.updateOnNom) {
this.display(updateOnly);
}
}
generateNomWindow() {
let buffer = "";
if (this.voting) {
buffer += `<div class="broadcast-blue"><p style="font-weight:bold;text-align:center;font-size:12pt;">Nominations for ${this.name} of the ${this.timeLabel} are in progress! Use <code>/${this.id} nom</code> to nominate a${["A", "E", "I", "O", "U"].includes(this.name[0]) ? "n" : ""} ${this.name.toLowerCase()}!</p>`;
if (this.nominations.size)
buffer += `<span style="font-weight:bold;">Nominations:</span>`;
} else {
buffer += `<div class="broadcast-blue"><p style="font-weight:bold;text-align:center;font-size:10pt;">Pre-noms for ${this.name} of the ${this.timeLabel}. Use <code>/${this.id} nom</code> to nominate a${["A", "E", "I", "O", "U"].includes(this.name[0]) ? "n" : ""} ${this.name.toLowerCase()}:</p>`;
}
if (this.winners.length) {
const winner = this.winners[this.winners.length - 1];
buffer += `<p>Current winner: <b>${winner[this.keys[0]]}</b> (nominated by ${winner.nominator})</p>`;
}
const entries = [];
for (const value of this.nominations.values()) {
entries.push(import_lib.Utils.html`<li><b>${value.nomination}</b> <i>(Submitted by ${value.name})</i></li>`);
}
if (entries.length > 20) {
buffer += `<table><tr><td><ul>${entries.slice(0, Math.ceil(entries.length / 2)).join("")}</ul></td><td><ul>${entries.slice(Math.ceil(entries.length / 2)).join("")}</ul></td></tr></table>`;
} else {
buffer += `<ul>${entries.join("")}</ul>`;
}
buffer += `</div>`;
return buffer;
}
display(update = false) {
if (update) {
this.room.uhtmlchange("otd", this.generateNomWindow());
} else {
this.room.add(`|uhtml|otd|${this.generateNomWindow()}`);
}
}
displayTo(connection) {
connection.sendTo(this.room, `|uhtml|otd|${this.generateNomWindow()}`);
}
rollWinner() {
const keys = [...this.nominations.keys()];
if (!keys.length)
return false;
const winner = this.nominations.get(keys[Math.floor(Math.random() * keys.length)]);
if (!winner)
return false;
const winnerEntry = this.appendWinner(winner.nomination, winner.name);
const names = [...this.nominations.values()].map((obj) => obj.name);
const columns = names.length > 27 ? 4 : names.length > 18 ? 3 : names.length > 9 ? 2 : 1;
let content = "";
for (let i = 0; i < columns; i++) {
content += `<td>${names.slice(Math.ceil(i / columns * names.length), Math.ceil((i + 1) / columns * names.length)).join("<br />")}</td>`;
}
const namesHTML = `<table><tr>${content}</tr></table></p></div>`;
const finishHandler = FINISH_HANDLERS[this.id];
if (finishHandler) {
void finishHandler(winnerEntry);
}
this.room.add(
import_lib.Utils.html`|uhtml|otd|<div class="broadcast-blue"><p style="font-weight:bold;text-align:center;font-size:12pt;">` + `Nominations for ${this.name} of the ${this.timeLabel} are over!</p><p style="tex-align:center;font-size:10pt;">Out of ${keys.length} nominations, we randomly selected <strong>${winner.nomination}</strong> as the winner!(Nomination by ${winner.name})</p><p style="font-weight:bold;">Thanks to today's participants:` + namesHTML
);
this.room.update();
this.finish();
return true;
}
removeNomination(name) {
name = toID(name);
let success = false;
for (const [key, value] of this.nominations) {
if (value.userids.includes(name)) {
this.removedNominations.set(key, value);
this.nominations.delete(key);
if (prenoms[this.id]) {
const idx = prenoms[this.id].findIndex((val) => val[0] === key);
if (idx > -1) {
prenoms[this.id].splice(idx, 1);
void savePrenoms();
}
}
success = true;
}
}
if (this.voting)
this.display();
return success;
}
forceWinner(winner, user) {
this.appendWinner(winner, user);
this.finish();
}
appendWinner(nomination, user) {
const entry = { time: Date.now(), nominator: user };
entry[this.keys[0]] = nomination;
this.winners.push(entry);
this.save();
return entry;
}
removeWinner(nominationName) {
for (const [i, entry] of this.winners.entries()) {
if (toID(entry[this.keys[0]]) === toID(nominationName)) {
const removed = this.winners.splice(i, 1);
this.save();
return removed[0];
}
}
throw new Chat.ErrorMessage(`The winner with nomination ${nominationName} could not be found.`);
}
setWinnerProperty(properties) {
if (!this.winners.length)
return;
for (const i in properties) {
this.winners[this.winners.length - 1][i] = properties[i];
}
return this.save();
}
save(destroy = false) {
if (!destroy) {
otdData[this.id] = {
settings: this.settings,
winners: this.winners
};
}
(0, import_lib.FS)(DATA_FILE).writeUpdate(() => JSON.stringify(otdData));
}
destroy() {
this.room = null;
delete otdData[this.id];
otds.delete(this.id);
delete Chat.commands[this.id];
delete Chat.pages[this.id];
this.save(true);
}
async generateWinnerDisplay() {
if (!this.winners.length)
return false;
const winner = this.winners[this.winners.length - 1];
let output = import_lib.Utils.html`<div class="broadcast-blue" style="text-align:center;">` + `<p><span style="font-weight:bold;font-size:11pt">The ${this.name} of the ${this.timeLabel} is ${winner[this.keys[0]]}${winner.author ? ` by ${winner.author}` : ""}.</span>`;
if (winner.quote)
output += import_lib.Utils.html`<br /><span style="font-style:italic;">"${winner.quote}"</span>`;
if (winner.tagline)
output += import_lib.Utils.html`<br />${winner.tagline}`;
output += `</p><table style="margin:auto;"><tr>`;
if (winner.image) {
try {
const [width, height] = await Chat.fitImage(winner.image, 100, 100);
output += import_lib.Utils.html`<td><img src="${winner.image}" width=${width} height=${height}></td>`;
} catch {
}
}
output += `<td style="text-align:right;margin:5px;">`;
if (winner.event)
output += import_lib.Utils.html`<b>Event:</b> ${winner.event}<br />`;
if (winner.song) {
output += `<b>Song:</b> `;
if (winner.link) {
output += import_lib.Utils.html`<a href="${winner.link}">${winner.song}</a>`;
} else {
output += import_lib.Utils.escapeHTML(winner.song);
}
output += `<br />`;
} else if (winner.link) {
output += import_lib.Utils.html`<b>Link:</b> <a href="${winner.link}">${winner.link}</a><br />`;
}
const athleteDetails = [];
if (winner.sport)
athleteDetails.push(import_lib.Utils.html`<b>Sport:</b> ${winner.sport}`);
if (winner.team)
athleteDetails.push(import_lib.Utils.html`<b>Team:</b> ${winner.team}`);
if (winner.age)
athleteDetails.push(import_lib.Utils.html`<b>Age:</b> ${winner.age}`);
if (winner.country)
athleteDetails.push(import_lib.Utils.html`<b>Nationality:</b> ${winner.country}`);
if (athleteDetails.length) {
output += athleteDetails.slice(0, 2).join(" | ") + "<br />";
if (athleteDetails.length > 2)
output += athleteDetails.slice(2).join(" | ") + "<br />";
}
output += import_lib.Utils.html`Nominated by ${winner.nominator}.`;
output += `</td></tr></table></div>`;
return output;
}
generateWinnerList(context) {
context.title = `${this.id.toUpperCase()} Winners`;
let buf = `<div class="pad ladder"><h2>${this.name} of the ${this.timeLabel} Winners</h2>`;
const columns = [];
const labels = [];
for (let i = 0; i < this.keys.length; i++) {
if (i === 0 || ["song", "event", "link", "tagline", "sport", "country"].includes(this.keys[i]) && !(this.keys[i] === "link" && this.keys.includes("song"))) {
columns.push(this.keys[i]);
labels.push(this.keyLabels[i]);
}
}
if (!columns.includes("time")) {
columns.push("time");
labels.push("Timestamp");
}
let content = ``;
content += `<tr>${labels.map((label) => `<th><h3>${label}</h3></th>`).join("")}</tr>`;
for (let i = this.winners.length - 1; i >= 0; i--) {
const entry = columns.map((col) => {
let val = this.winners[i][col];
if (!val)
return "";
switch (col) {
case "time":
const date = new Date(parseInt(this.winners[i].time));
const pad = (num) => num < 10 ? "0" + num : num;
return import_lib.Utils.html`${pad(date.getMonth() + 1)}-${pad(date.getDate())}-${date.getFullYear()}`;
case "song":
if (!this.winners[i].link)
return val;
case "link":
return `<a href="${this.winners[i].link}">${val}</a>`;
case "book":
val = `${val}${this.winners[i].author ? ` by ${this.winners[i].author}` : ""}`;
case columns[0]:
return `${import_lib.Utils.escapeHTML(val)}${this.winners[i].nominator ? import_lib.Utils.html`<br /><span style="font-style:italic;font-size:8pt;">nominated by ${this.winners[i].nominator}</span>` : ""}`;
default:
return import_lib.Utils.escapeHTML(val);
}
});
content += `<tr>${entry.map((val) => `<td style="max-width:${600 / columns.length}px;word-wrap:break-word;">${val}</td>`).join("")}</tr>`;
}
if (!content) {
buf += `<p>There have been no ${this.id} winners.</p>`;
} else {
buf += `<table>${content}</table>`;
}
buf += `</div>`;
return buf;
}
}
function selectHandler(message) {
const id = toID(message.substring(1).split(" ")[0]);
const handler = otds.get(id);
if (!handler)
throw new Error("Invalid type for otd handler.");
return handler;
}
const otdCommands = {
start(target, room, user, connection, cmd) {
this.checkChat();
const handler = selectHandler(this.message);
if (!handler.room)
return this.errorReply(`The room for this -otd doesn't exist.`);
if (room !== handler.room)
return this.errorReply(`This command can only be used in ${handler.room.title}.`);
this.checkCan("mute", null, room);
if (handler.voting) {
return this.errorReply(
`The nomination for the ${handler.name} of the ${handler.timeLabel} nomination is already in progress.`
);
}
handler.startVote();
this.privateModAction(`${user.name} has started nominations for the ${handler.name} of the ${handler.timeLabel}.`);
this.modlog(`${handler.id.toUpperCase()} START`, null);
},
starthelp: [`/-otd start - Starts nominations for the Thing of the Day. Requires: % @ # &`],
end(target, room, user) {
this.checkChat();
const handler = selectHandler(this.message);
if (!handler.room)
return this.errorReply(`The room for this -otd doesn't exist.`);
if (room !== handler.room)
return this.errorReply(`This command can only be used in ${handler.room.title}.`);
this.checkCan("mute", null, room);
if (!handler.voting) {
return this.errorReply(`There is no ${handler.name} of the ${handler.timeLabel} nomination in progress.`);
}
if (!handler.nominations.size) {
return this.errorReply(`Can't select the ${handler.name} of the ${handler.timeLabel} without nominations.`);
}
handler.rollWinner();
this.privateModAction(`${user.name} has ended nominations for the ${handler.name} of the ${handler.timeLabel}.`);
this.modlog(`${handler.id.toUpperCase()} END`, null);
},
endhelp: [
`/-otd end - End nominations for the Thing of the Day and set it to a randomly selected nomination. Requires: % @ # &`
],
nom(target, room, user) {
this.checkChat(target);
if (!target)
return this.parse("/help otd");
const handler = selectHandler(this.message);
if (!handler.room)
return this.errorReply(`The room for this -otd doesn't exist.`);
if (room !== handler.room)
return this.errorReply(`This command can only be used in ${handler.room.title}.`);
if (!toNominationId(target).length || target.length > 75) {
return this.sendReply(`'${target}' is not a valid ${handler.name.toLowerCase()} name.`);
}
handler.addNomination(user, target);
},
nomhelp: [`/-otd nom [nomination] - Nominate something for Thing of the Day.`],
view(target, room, user, connection) {
this.checkChat();
if (!this.runBroadcast())
return false;
const handler = selectHandler(this.message);
if (!handler.room)
return this.errorReply(`The room for this -otd doesn't exist.`);
if (room !== handler.room)
return this.errorReply(`This command can only be used in ${handler.room.title}.`);
if (this.broadcasting) {
selectHandler(this.message).display();
} else {
selectHandler(this.message).displayTo(connection);
}
},
viewhelp: [`/-otd view - View the current nominations for the Thing of the Day.`],
remove(target, room, user) {
this.checkChat();
const handler = selectHandler(this.message);
if (!handler.room)
return this.errorReply(`The room for this -otd doesn't exist.`);
if (room !== handler.room)
return this.errorReply(`This command can only be used in ${handler.room.title}.`);
this.checkCan("mute", null, room);
const userid = toID(target);
if (!userid)
return this.errorReply(`'${target}' is not a valid username.`);
if (handler.removeNomination(userid)) {
this.privateModAction(`${user.name} removed ${target}'s nomination for the ${handler.name} of the ${handler.timeLabel}.`);
this.modlog(`${handler.id.toUpperCase()} REMOVENOM`, userid);
} else {
this.sendReply(`User '${target}' has no nomination for the ${handler.name} of the ${handler.timeLabel}.`);
}
},
removehelp: [
`/-otd remove [username] - Remove a user's nomination for the Thing of the Day.`,
`Prevents them from voting again until the next round. Requires: % @ # &`
],
removewinner(target, room, user) {
const handler = selectHandler(this.message);
room = this.requireRoom(handler.room.roomid);
this.checkCan("mute", null, room);
if (!toID(target)) {
return this.parse(`/help aotd removewinner`);
}
const removed = handler.removeWinner(target);
this.privateModAction(`${user.name} removed the nomination for ${removed[handler.keys[0]]} from ${removed.nominator}`);
this.modlog(`${handler.id.toUpperCase()} REMOVEWINNER`, removed.nominator, removed[handler.keys[0]]);
},
removewinnerhelp: [
`/-otd removewinner [nomination] - Remove winners matching the given [nomination] from Thing of the Day.`,
`Requires: % @ # &`
],
force(target, room, user) {
this.checkChat();
if (!target)
return this.parse("/help aotd force");
const handler = selectHandler(this.message);
if (!handler.room)
return this.errorReply(`The room for this -otd doesn't exist.`);
if (room !== handler.room)
return this.errorReply(`This command can only be used in ${handler.room.title}.`);
this.checkCan("declare", null, room);
if (!toNominationId(target).length || target.length > 50) {
return this.sendReply(`'${target}' is not a valid ${handler.name.toLowerCase()} name.`);
}
handler.forceWinner(target, user.name);
this.privateModAction(`${user.name} forcibly set the ${handler.name} of the ${handler.timeLabel} to ${target}.`);
this.modlog(`${handler.id.toUpperCase()} FORCE`, user.name, target);
room.add(`The ${handler.name} of the ${handler.timeLabel} was forcibly set to '${target}'`);
},
forcehelp: [
`/-otd force [nomination] - Forcibly sets the Thing of the Day without a nomination round. Requires: # &`
],
delay(target, room, user) {
this.checkChat();
const handler = selectHandler(this.message);
if (!handler.room)
return this.errorReply(`The room for this -otd doesn't exist.`);
if (room !== handler.room)
return this.errorReply(`This command can only be used in ${handler.room.title}.`);
this.checkCan("mute", null, room);
if (!(handler.voting && handler.timer)) {
return this.errorReply(`There is no ${handler.name} of the ${handler.timeLabel} nomination to disable the timer for.`);
}
clearTimeout(handler.timer);
this.privateModAction(`${user.name} disabled the ${handler.name} of the ${handler.timeLabel} timer.`);
},
delayhelp: [
`/-otd delay - Turns off the automatic 20 minute timer for Thing of the Day voting rounds. Requires: % @ # &`
],
set(target, room, user) {
this.checkChat();
const handler = selectHandler(this.message);
if (!handler.room)
return this.errorReply(`The room for this -otd doesn't exist.`);
if (room !== handler.room)
return this.errorReply(`This command can only be used in ${handler.room.title}.`);
this.checkCan("mute", null, room);
const params = target.split(target.includes("|") ? "|" : ",").map((param) => param.trim());
const changelist = {};
for (const param of params) {
let [key, ...values] = param.split(":");
if (!key || !values.length)
return this.errorReply(`Syntax error in '${param}'`);
key = key.trim();
const value = values.join(":").trim();
if (!handler.keys.includes(key)) {
return this.errorReply(`Invalid key: '${key}'. Valid keys: ${handler.keys.join(", ")}`);
}
switch (key) {
case "artist":
case "film":
case "show":
case "channel":
case "book":
case "author":
case "athlete":
if (!toNominationId(value) || value.length > 50)
return this.errorReply(`Please enter a valid ${key} name.`);
break;
case "quote":
case "tagline":
case "match":
case "event":
case "videogame":
if (!value.length || value.length > 150)
return this.errorReply(`Please enter a valid ${key}.`);
break;
case "sport":
case "team":
case "song":
case "country":
if (!value.length || value.length > 50)
return this.errorReply(`Please enter a valid ${key} name.`);
break;
case "link":
case "image":
if (!/https?:\/\//.test(value)) {
return this.errorReply(`Please enter a valid URL for the ${key} (starting with http:// or https://)`);
}
if (value.length > 200)
return this.errorReply("URL too long.");
break;
case "age":
const num = parseInt(value);
if (isNaN(num) || num < 1 || num > 100)
return this.errorReply("Please enter a valid number as an age");
break;
default:
if (!toNominationId(value)) {
return this.errorReply(`No value provided for key ${key}.`);
}
break;
}
changelist[key] = value;
}
const keys = Object.keys(changelist);
if (keys.length) {
void handler.setWinnerProperty(changelist);
this.modlog(handler.id.toUpperCase(), null, `changed ${keys.join(", ")}`);
return this.privateModAction(`${user.name} changed the following propert${Chat.plural(keys, "ies", "y")} of the ${handler.name} of the ${handler.timeLabel}: ${keys.join(", ")}`);
}
},
sethelp: [
`/-otd set property: value[, property: value] - Set the winner, quote, song, link or image for the current Thing of the Day.`,
`Requires: % @ # &`
],
toggleupdate(target, room, user) {
const otd = selectHandler(this.message);
room = this.requireRoom(otd.room.roomid);
this.checkCan("declare", null, room);
let logMessage = "";
if (this.meansYes(target)) {
if (otd.settings.updateOnNom) {
throw new Chat.ErrorMessage(`This -OTD is already set to update automatically on nomination.`);
}
otd.settings.updateOnNom = true;
logMessage = "update automatically on nomination";
} else {
if (!otd.settings.updateOnNom) {
throw new Chat.ErrorMessage(`This -OTD is not set to update automatically on nomination.`);
}
delete otd.settings.updateOnNom;
logMessage = "not update on nomination";
}
this.privateModAction(`${user.name} set the ${otd.name} of the ${otd.timeLabel} to ${logMessage}`);
this.modlog(`OTD TOGGLEUPDATE`, null, logMessage);
otd.save();
},
winners(target, room, user, connection) {
this.checkChat();
const handler = selectHandler(this.message);
if (!handler.room)
return this.errorReply(`The room for this -otd doesn't exist.`);
if (room !== handler.room)
return this.errorReply(`This command can only be used in ${handler.room.title}.`);
return this.parse(`/join view-${handler.id}`);
},
winnershelp: [`/-otd winners - Displays a list of previous things of the day.`],
async ""(target, room) {
this.checkChat();
if (!this.runBroadcast())
return false;
const handler = selectHandler(this.message);
if (!handler.room)
return this.errorReply(`The room for this -otd doesn't exist.`);
if (room !== handler.room)
return this.errorReply(`This command can only be used in ${handler.room.title}.`);
const text = await handler.generateWinnerDisplay();
if (!text)
return this.errorReply("There is no winner yet.");
this.sendReplyBox(text);
}
};
const pages = {};
const commands = {
otd: {
create(target, room, user) {
room = this.requireRoom();
if (room.settings.isPrivate) {
return this.errorReply(`This command is only available in public rooms`);
}
const count = [...otds.values()].filter((otd2) => otd2.room.roomid === room.roomid).length;
if (count > 3) {
return this.errorReply(`This room already has 3+ -otd's.`);
}
this.checkCan("rangeban");
if (!toID(target)) {
return this.parse(`/help otd`);
}
const [title, time, ...keyLabels] = target.split(",").map((i) => i.trim());
if (!toID(title)) {
return this.errorReply(`Invalid title.`);
}
const timeLabel = toID(time);
if (!["week", "day"].includes(timeLabel)) {
return this.errorReply("Invalid time label - use 'week' or 'month'");
}
const id = `${title.charAt(0)}ot${timeLabel.charAt(0)}`;
const existing = otds.get(id);
if (existing) {
this.errorReply(`That -OTD already exists (${existing.name} of the ${existing.timeLabel}, in ${existing.room.title})`);
return this.errorReply(`Try picking a new title.`);
}
const titleIdx = keyLabels.map(toID).indexOf(toID(title));
if (titleIdx > -1) {
keyLabels.splice(titleIdx, 1);
}
keyLabels.unshift(title);
const filteredKeys = keyLabels.map(toNominationId).filter(Boolean);
if (!filteredKeys.length) {
return this.errorReply(`No valid key labels given.`);
}
if (new Set(filteredKeys).size !== keyLabels.length) {
return this.errorReply(`Invalid keys in set - do not use duplicate key labels.`);
}
if (filteredKeys.length < 3) {
return this.errorReply(`Specify at least 3 key labels.`);
}
if (filteredKeys.some((k) => k.length < 3 || k.length > 50)) {
return this.errorReply(`All labels must be more than 3 characters and less than 50 characters long.`);
}
const otd = OtdHandler.create(room, {
keyLabels,
keys: filteredKeys,
title,
timeLabel,
roomid: room.roomid
});
const name = `${otd.name} of the ${otd.timeLabel}`;
this.globalModlog(`OTD CREATE`, null, `${name} - ${filteredKeys.join(", ")}`);
this.privateGlobalModAction(`${user.name} created the ${name} for ${room.title}`);
otd.save();
},
updateroom(target, room, user) {
this.checkCan("rangeban");
const [otdId, roomid] = target.split(",").map((i) => toID(i));
if (!otdId || !roomid) {
return this.parse("/help otd");
}
const otd = otds.get(otdId);
if (!otd) {
return this.errorReply(`OTD ${otd} not found.`);
}
const targetRoom = Rooms.get(roomid);
if (!targetRoom) {
return this.errorReply(`Room ${roomid} not found.`);
}
const oldRoom = otd.settings.roomid.slice();
otd.settings.roomid = targetRoom.roomid;
otd.room = targetRoom;
otd.save();
this.privateGlobalModAction(
`${user.name} updated the room for the ${otd.name} of the ${otd.timeLabel} from ${oldRoom} to ${targetRoom}`
);
this.globalModlog(`OTD UPDATEROOM`, null, `${otd.id} to ${targetRoom} from ${oldRoom}`);
},
delete(target, room, user) {
this.checkCan("rangeban");
target = toID(target);
if (!target) {
return this.parse(`/help otd`);
}
const otd = otds.get(target);
if (!otd)
return this.errorReply(`OTD ${target} not found.`);
otd.destroy();
this.globalModlog(`OTD DELETE`, null, target);
this.privateGlobalModAction(`${user.name} deleted the OTD ${otd.name} of the ${otd.timeLabel}`);
}
},
otdhelp: [
`/otd create [title], [time], [...labels] - Creates a Thing of the Day with the given [name], [time], and [labels]. Requires: &`,
`/otd updateroom [otd], [room] - Updates the room for the given [otd] to the new [room]. Requires: &`,
`/otd delete [otd] - Removes the given Thing of the Day. Requires: &`
]
};
const otdHelp = [
`Thing of the Day plugin commands (aotd, fotd, sotd, cotd, botw, motw, anotd):`,
`- /-otd - View the current Thing of the Day.`,
`- /-otd start - Starts nominations for the Thing of the Day. Requires: % @ # &`,
`- /-otd nom [nomination] - Nominate something for Thing of the Day.`,
`- /-otd remove [username] - Remove a user's nomination for the Thing of the Day and prevent them from voting again until the next round. Requires: % @ # &`,
`- /-otd end - End nominations for the Thing of the Day and set it to a randomly selected nomination. Requires: % @ # &`,
`- /-otd removewinner [nomination] - Remove a winner with the given [nomination] from the winners list. Requires: % @ # &`,
`- /-otd force [nomination] - Forcibly sets the Thing of the Day without a nomination round. Requires: # &`,
`- /-otd delay - Turns off the automatic 20 minute timer for Thing of the Day voting rounds. Requires: % @ # &`,
`- /-otd set property: value[, property: value] - Set the winner, quote, song, link or image for the current Thing of the Day. Requires: % @ # &`,
`- /-otd winners - Displays a list of previous things of the day.`,
`- /-otd toggleupdate [on|off] - Changes the Thing of the Day to display on nomination ([on] to update, [off] to turn off updates). Requires: % @ # &`
];
for (const otd in otdData) {
const data = otdData[otd];
const settings = data.settings;
const room = Rooms.get(settings.roomid);
if (!room) {
Monitor.warn(`Room for -otd ${settings.title} of the ${settings.timeLabel} (${settings.roomid}) not found.`);
continue;
}
OtdHandler.create(room, settings);
}
for (const [k, v] of otds) {
pages[k] = function() {
return v.generateWinnerList(this);
};
commands[k] = otdCommands;
commands[`${k}help`] = otdHelp;
}
const handlers = {
onRenameRoom(oldID, newID, room) {
for (const otd in otdData) {
const data = otdData[otd];
if (data.settings.roomid === oldID) {
data.settings.roomid = newID;
const handler = otds.get(otd);
handler.room = room;
handler.save();
}
}
}
};
const punishmentfilter = (user, punishment) => {
user = toID(user);
if (!["NAMELOCK", "BAN"].includes(punishment.type))
return;
for (const handler of otds.values()) {
handler.removeNomination(user);
}
};
//# sourceMappingURL=thing-of-the-day.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/thing-of-the-day.ts"],
"sourcesContent": ["import {FS, Utils} from '../../lib';\r\nimport {YouTube} from './youtube';\r\n\r\nconst MINUTE = 60 * 1000;\r\nconst PRENOM_BUMP_TIME = 2 * 60 * MINUTE;\r\n\r\nconst PRENOMS_FILE = 'config/chat-plugins/otd-prenoms.json';\r\nconst DATA_FILE = 'config/chat-plugins/otds.json';\r\n\r\nexport const prenoms: {[k: string]: [string, AnyObject][]} = JSON.parse(FS(PRENOMS_FILE).readIfExistsSync() || \"{}\");\r\nexport const otdData: OtdData = JSON.parse(FS(DATA_FILE).readIfExistsSync() || \"{}\");\r\nexport const otds = new Map<string, OtdHandler>();\r\n\r\nconst FINISH_HANDLERS: {[k: string]: (winner: AnyObject) => Promise<void>} = {\r\n\tcotw: async winner => {\r\n\t\tconst {channel, nominator} = winner;\r\n\t\tconst searchResults = await YouTube.searchChannel(channel, 1);\r\n\t\tconst result = searchResults?.[0];\r\n\t\tif (result) {\r\n\t\t\tif (YouTube.data.channels[result]) return;\r\n\t\t\tvoid YouTube.getChannelData(`https://www.youtube.com/channel/${result}`);\r\n\t\t\tconst yt = Rooms.get('youtube');\r\n\t\t\tif (!yt) return;\r\n\t\t\tyt.sendMods(\r\n\t\t\t\t`|c|&|/log The channel with ID ${result} was added to the YouTube channel database.`\r\n\t\t\t);\r\n\t\t\tyt.modlog({\r\n\t\t\t\taction: `ADDCHANNEL`,\r\n\t\t\t\tnote: `${result} (${toID(nominator)})`,\r\n\t\t\t\tloggedBy: toID(`COTW`),\r\n\t\t\t});\r\n\t\t}\r\n\t},\r\n};\r\n\r\ninterface OtdSettings {\r\n\tid?: string;\r\n\tupdateOnNom?: boolean;\r\n\tkeys: string[];\r\n\ttitle: string;\r\n\tkeyLabels: string[];\r\n\ttimeLabel: string;\r\n\troomid: RoomID;\r\n}\r\n\r\ninterface OtdData {\r\n\t[k: string]: {settings: OtdSettings, winners: AnyObject[]};\r\n}\r\n\r\nfunction savePrenoms() {\r\n\treturn FS(PRENOMS_FILE).writeUpdate(() => JSON.stringify(prenoms));\r\n}\r\n\r\nfunction toNominationId(nomination: string) {\r\n\treturn nomination.toLowerCase().replace(/\\s/g, '').replace(/\\b&\\b/g, '');\r\n}\r\n\r\nclass OtdHandler {\r\n\tid: string;\r\n\tname: string;\r\n\troom: Room;\r\n\tnominations: Map<string, AnyObject>;\r\n\tremovedNominations: Map<string, AnyObject>;\r\n\tvoting: boolean;\r\n\ttimer: NodeJS.Timeout | null;\r\n\tkeys: string[];\r\n\tkeyLabels: string[];\r\n\ttimeLabel: string;\r\n\tsettings: OtdSettings;\r\n\tlastPrenom: number;\r\n\twinners: AnyObject[];\r\n\tconstructor(\r\n\t\tid: string, room: Room, settings: OtdSettings\r\n\t) {\r\n\t\tthis.id = id;\r\n\t\tthis.name = settings.title;\r\n\t\tthis.room = room;\r\n\r\n\t\tthis.nominations = new Map(prenoms[id]);\r\n\t\tthis.removedNominations = new Map();\r\n\r\n\t\tthis.voting = false;\r\n\t\tthis.timer = null;\r\n\r\n\t\tthis.keys = settings.keys;\r\n\t\tthis.keyLabels = settings.keyLabels;\r\n\t\tthis.timeLabel = settings.timeLabel;\r\n\t\tthis.settings = settings;\r\n\r\n\t\tthis.lastPrenom = 0;\r\n\r\n\t\tthis.winners = otdData[this.id]?.winners || [];\r\n\t}\r\n\r\n\tstatic create(room: Room, settings: OtdSettings) {\r\n\t\tconst {title, timeLabel} = settings;\r\n\t\tconst id = settings.id || toID(title).charAt(0) + 'ot' + timeLabel.charAt(0);\r\n\t\tconst handler = new OtdHandler(id, room, settings);\r\n\t\totds.set(id, handler);\r\n\t\tlet needsSave = false;\r\n\t\tfor (const winner of handler.winners) {\r\n\t\t\tif (winner.timestamp) {\r\n\t\t\t\twinner.time = winner.timestamp;\r\n\t\t\t\tdelete winner.timestamp;\r\n\t\t\t\tneedsSave = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (needsSave) handler.save();\r\n\t\treturn handler;\r\n\t}\r\n\r\n\tstatic parseOldWinners(content: string, keyLabels: string[], keys: string[]) {\r\n\t\tconst data = ('' + content).split(\"\\n\");\r\n\t\tconst winners = [];\r\n\t\tfor (const arg of data) {\r\n\t\t\tif (!arg || arg === '\\r') continue;\r\n\t\t\tif (arg.startsWith(`${keyLabels[0]}\\t`)) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tconst entry: AnyObject = {};\r\n\t\t\tconst vals = arg.trim().split(\"\\t\");\r\n\t\t\tfor (let i = 0; i < vals.length; i++) {\r\n\t\t\t\tentry[keys[i]] = vals[i];\r\n\t\t\t}\r\n\t\t\tentry.time = Number(entry.time) || 0;\r\n\t\t\twinners.push(entry);\r\n\t\t}\r\n\t\treturn winners;\r\n\t}\r\n\r\n\t/**\r\n\t * Handles old-format data from the IP and userid refactor\r\n\t */\r\n\tconvertNominations() {\r\n\t\tfor (const value of this.nominations.values()) {\r\n\t\t\tif (!Array.isArray(value.userids)) value.userids = Object.keys(value.userids);\r\n\t\t\tif (!Array.isArray(value.ips)) value.ips = Object.keys(value.ips);\r\n\t\t}\r\n\t\tfor (const value of this.removedNominations.values()) {\r\n\t\t\tif (!Array.isArray(value.userids)) value.userids = Object.keys(value.userids);\r\n\t\t\tif (!Array.isArray(value.ips)) value.ips = Object.keys(value.ips);\r\n\t\t}\r\n\t}\r\n\r\n\tstartVote() {\r\n\t\tthis.voting = true;\r\n\t\tthis.timer = setTimeout(() => this.rollWinner(), 20 * MINUTE);\r\n\t\tthis.display();\r\n\t}\r\n\r\n\tfinish() {\r\n\t\tthis.voting = false;\r\n\t\tthis.nominations = new Map();\r\n\t\tthis.removedNominations = new Map();\r\n\t\tdelete prenoms[this.id];\r\n\t\tvoid savePrenoms();\Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAwB;AACxB,qBAAsB;AAEtB,MAAM,SAAS,KAAK;AACpB,MAAM,mBAAmB,IAAI,KAAK;AAElC,MAAM,eAAe;AACrB,MAAM,YAAY;AAEX,MAAM,UAAgD,KAAK,UAAM,eAAG,YAAY,EAAE,iBAAiB,KAAK,IAAI;AAC5G,MAAM,UAAmB,KAAK,UAAM,eAAG,SAAS,EAAE,iBAAiB,KAAK,IAAI;AAC5E,MAAM,OAAO,oBAAI,IAAwB;AAEhD,MAAM,kBAAuE;AAAA,EAC5E,MAAM,OAAM,WAAU;AACrB,UAAM,EAAC,SAAS,UAAS,IAAI;AAC7B,UAAM,gBAAgB,MAAM,uBAAQ,cAAc,SAAS,CAAC;AAC5D,UAAM,SAAS,gBAAgB,CAAC;AAChC,QAAI,QAAQ;AACX,UAAI,uBAAQ,KAAK,SAAS,MAAM;AAAG;AACnC,WAAK,uBAAQ,eAAe,mCAAmC,QAAQ;AACvE,YAAM,KAAK,MAAM,IAA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,kBAAU;AAAA,IACtC,OAAO;AACN,gBAAU,0GAA0G,KAAK,eAAe,KAAK,yBAAyB,KAAK,8BAA8B,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG,EAAE,SAAS,KAAK,KAAK,CAAC,CAAC,IAAI,MAAM,MAAM,KAAK,KAAK,YAAY;AAAA,IAC/R;AAEA,QAAI,KAAK,QAAQ,QAAQ;AACxB,YAAM,SAAS,KAAK,QAAQ,KAAK,QAAQ,Line truncated
"names": ["otd"]
}
@@ -0,0 +1,635 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var database_exports = {};
__export(database_exports, {
LEADERBOARD_ENUM: () => LEADERBOARD_ENUM,
TriviaSQLiteDatabase: () => TriviaSQLiteDatabase
});
module.exports = __toCommonJS(database_exports);
var import_lib = require("../../../lib");
var import_utils = require("../../../lib/utils");
const LEADERBOARD_ENUM = {
alltime: 1,
nonAlltime: 0,
cycle: 2
};
class TriviaSQLiteDatabase {
constructor(legacyJSONPath) {
this.legacyJSONPath = legacyJSONPath;
this.leaderboardInsertion = null;
this.questionInsertion = null;
this.answerInsertion = null;
this.gameHistoryInsertion = null;
this.scoreHistoryInsertion = null;
this.updateMoveEventQuestions = null;
this.categoryChangeQuery = null;
this.leaderboardChangeQuery = null;
this.migrateCategoryQuery = null;
this.historyQuery = null;
this.historyScoresQuery = null;
this.allQuestionsRandomOrderQuery = null;
this.allQuestionsNewestFirstQuery = null;
this.allQuestionsOldestFirstQuery = null;
this.answersQuery = null;
this.submissionsQuery = null;
this.leaderboardQuery = null;
this.leaderboardByUserQuery = null;
this.scoreAndPointsByUser = null;
this.eventQuestionQuery = null;
this.categoriesQuery = null;
this.questionCountQuery = null;
this.categoryQuestionCountQuery = null;
this.questionSearchQuery = null;
this.questionExistsQuery = null;
this.clearAllSubmissionsQuery = null;
this.clearCategoryQuery = null;
this.clearCycleLeaderboardQuery = null;
this.deleteQuestionQuery = null;
this.leaderboardDeletionQuery = null;
this.readyPromise = this.prepareStatements().then(() => {
void this.convertLegacyJSON();
this.readyPromise = null;
});
}
/***************************
* Methods for adding data *
***************************/
async updateLeaderboardForUser(userid, additions) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't update the leaderboard for ${userid} because SQLite is not enabled.`);
}
for (const [lb, discrim] of Object.entries(LEADERBOARD_ENUM)) {
if (!additions[lb])
continue;
await this.leaderboardChangeQuery.run({
score: additions[lb].score,
totalPoints: additions[lb].totalPoints,
totalCorrectAnswers: additions[lb].totalCorrectAnswers,
userid,
leaderboard: discrim
});
}
}
async addHistory(history) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't add a Trivia game to the history because SQLite is not enabled.`);
}
const res = await Chat.database.transaction("addHistory", {
history,
gameHistoryInsertion: this.gameHistoryInsertion.toString(),
scoreHistoryInsertion: this.scoreHistoryInsertion.toString()
});
if (!res)
throw new Error(`Error updating Trivia history.`);
}
async addQuestions(questions) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't add a Trivia question because SQLite is not enabled.`);
}
const res = await Chat.database.transaction("addQuestions", {
questions,
questionInsertion: this.questionInsertion.toString(),
answerInsertion: this.answerInsertion.toString(),
isSubmission: false
});
if (!res)
throw new Chat.ErrorMessage(`Error adding Trivia questions.`);
}
async addQuestionSubmissions(questions) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't submit a Trivia question for review because SQLite is not enabled.`);
}
const res = await Chat.database.transaction("addQuestions", {
questions,
questionInsertion: this.questionInsertion.toString(),
answerInsertion: this.answerInsertion.toString(),
isSubmission: true
});
if (!res)
throw new Chat.ErrorMessage(`Error adding Trivia questions for review.`);
}
async setShouldMoveEventQuestions(shouldMove) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't enable/disable moving event questions because SQLite is not enabled.`);
}
await this.updateMoveEventQuestions.run([Number(shouldMove)]);
}
/******************************
* Methods for modifying data *
******************************/
async mergeLeaderboardEntries(from, to) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't merge ${from} and ${to}'s Trivia leaderboard entries because SQLite is not enabled.`);
}
for (const lbDiscrim of Object.values(LEADERBOARD_ENUM)) {
const fromScores = await this.scoreAndPointsByUser.get([from, lbDiscrim]) || {
score: 0,
totalCorrectAnswers: 0,
totalPoints: 0
};
const toScores = await this.scoreAndPointsByUser.get([to, lbDiscrim]) || {
score: 0,
totalCorrectAnswers: 0,
totalPoints: 0
};
toScores.score += fromScores.score;
toScores.totalCorrectAnswers += fromScores.totalCorrectAnswers;
toScores.totalPoints += fromScores.totalPoints;
await Chat.database.run(
this.leaderboardInsertion,
[to, toScores.score, toScores.totalPoints, toScores.totalCorrectAnswers, lbDiscrim]
);
await this.leaderboardDeletionQuery.run([from, lbDiscrim]);
}
}
async shouldMoveEventQuestions() {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't find out if we are moving event questions because SQLite is not enabled.`);
}
return (await this.eventQuestionQuery.get([]) || { value: false }).value;
}
async moveQuestionToCategory(question, newCategory) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't move question category because SQLite is not enabled.`);
}
await this.categoryChangeQuery.run([newCategory, question]);
}
async migrateCategory(sourceCategory, targetCategory) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't migrate categories because SQLite is not enabled.`);
}
const { changes } = await this.migrateCategoryQuery.run([targetCategory, sourceCategory]);
return changes;
}
async acceptSubmissions(submissions) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't accept Trivia question submissions because SQLite is not enabled.`);
}
await Chat.database.run(
`UPDATE trivia_questions SET is_submission = 0 WHERE question IN (${(0, import_utils.formatSQLArray)(submissions)})`,
submissions
);
}
async editQuestion(oldQuestionText, newQuestionText, newAnswers) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't edit Trivia question because SQLite is not enabled.`);
}
await Chat.database.transaction("editQuestion", {
oldQuestionText,
newQuestionText,
newAnswers
});
}
/*****************************
* Methods for fetching data *
*****************************/
async getHistory(numberOfLines = 10) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't get Trivia game history because SQLite is not enabled.`);
}
const rows = await this.historyQuery.all([numberOfLines]);
return rows.map((row) => ({
mode: row.mode,
length: /^d+$/.test(row.length) ? parseInt(row.length) || row.length : row.length,
category: row.category,
creator: row.creator || void 0,
givesPoints: row.givesPoints !== 0,
startTime: row.time
}));
}
async getScoresForLastGame() {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't get Trivia game scores because SQLite is not enabled.`);
}
const { game_id } = await this.historyQuery.get([1]);
const results = {};
for (const row of await this.historyScoresQuery.all([game_id])) {
results[row.userid] = row.score;
}
return results;
}
async getQuestions(categories, limit, options) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite)
throw new Chat.ErrorMessage(`Can't get Trivia questions because SQLite is not enabled.`);
let query;
let args;
if (categories === "all") {
if (options.order === "newestfirst") {
query = this.allQuestionsNewestFirstQuery;
} else if (options.order === "oldestfirst") {
query = this.allQuestionsOldestFirstQuery;
} else {
query = this.allQuestionsRandomOrderQuery;
}
args = [limit];
} else {
query = `SELECT * FROM trivia_questions WHERE category IN (${(0, import_utils.formatSQLArray)(categories)}) AND is_submission = 0 ORDER BY ${options.order === "random" ? "RANDOM()" : `added_at ${options.order === "oldestfirst" ? "ASC" : "DESC"}`} LIMIT ?`;
args = [...categories, limit];
}
if (!query)
throw new Error(`Couldn't prepare query`);
const rows = await Chat.database.all(query, args);
return Promise.all(rows.map((row) => this.rowToQuestion(row)));
}
async getLeaderboardEntry(id, leaderboard) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't find out if user ${id} has a Trivia leaderboard entry because SQLite is not enabled.`);
}
const row = await this.leaderboardByUserQuery.get([id, LEADERBOARD_ENUM[leaderboard]]);
if (!row)
return null;
return {
score: row.score,
totalPoints: row.total_points,
totalCorrectAnswers: row.total_correct_answers
};
}
async getLeaderboards() {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't get the Trivia leaderboard scores because SQLite is not enabled.`);
}
const result = {
alltime: {},
nonAlltime: {},
cycle: {}
};
const rows = await this.leaderboardQuery.all([]);
for (const row of rows) {
const entry = {
score: row.score,
totalPoints: row.total_points,
totalCorrectAnswers: row.total_correct_answers
};
let leaderboard = null;
for (const [lb, discrim] of Object.entries(LEADERBOARD_ENUM)) {
if (discrim === row.leaderboard)
leaderboard = lb;
}
if (leaderboard === null)
throw new Error(`Invalid leaderboard value ${row.leaderboard}`);
result[leaderboard][row.userid] = entry;
}
return result;
}
async getQuestion(questionText) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't check if a Trivia question already exists because SQLite is not enabled.`);
}
const row = await this.questionExistsQuery.get([questionText]);
if (!row)
return null;
return this.rowToQuestion(row);
}
async ensureQuestionExists(questionText) {
const question = await this.getQuestion(questionText);
if (!question) {
throw new Chat.ErrorMessage(`Question "${questionText}" is not in the question database.`);
}
return question;
}
async ensureQuestionDoesNotExist(questionText) {
if (await this.getQuestion(questionText)) {
throw new Chat.ErrorMessage(`Question "${questionText}" is already in the question database.`);
}
}
async getSubmissions() {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't retrieve the Trivia question submissions because SQLite is not enabled.`);
}
const rows = await this.submissionsQuery.all([]);
return Promise.all(rows.map((row) => this.rowToQuestion(row)));
}
async getQuestionCounts() {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't retrieve the Trivia question counts because SQLite is not enabled.`);
}
const allCategories = (await this.categoriesQuery.all([])).map((row) => row.category);
const total = (await this.questionCountQuery.get([])).count;
const result = { total };
for (const category of allCategories) {
result[category] = (await this.categoryQuestionCountQuery.get([category])).count;
}
return result;
}
async searchQuestions(search, options) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't search Trivia questions because SQLite is not enabled.`);
}
if (options.caseSensitive)
await Chat.database.exec(`PRAGMA case_sensitive_like = true;`);
const rows = await this.questionSearchQuery.all([`%${search}%`, Number(options.searchSubmissions)]);
if (options.caseSensitive)
await Chat.database.exec(`PRAGMA case_sensitive_like = false;`);
return Promise.all(rows.map((row) => this.rowToQuestion(row)));
}
/*****************************
* Methods for deleting data *
* ***************************/
async clearSubmissions() {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't clear the Trivia question submissions because SQLite is not enabled.`);
}
await Chat.database.run(this.clearAllSubmissionsQuery, []);
}
async clearCategory(category) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't clear the Trivia questions in category "${category}" because SQLite is not enabled.`);
}
await Chat.database.run(this.clearCategoryQuery, [category]);
}
async clearCycleLeaderboard() {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't clear the cycle leaderboard because SQLite is not enabled.`);
}
await Chat.database.run(this.clearCycleLeaderboardQuery);
}
async deleteQuestion(questionText) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't delete the Trivia question because SQLite is not enabled.`);
}
await Chat.database.run(this.deleteQuestionQuery, [questionText]);
}
async deleteLeaderboardEntry(userid, leaderboard) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't delete leaderboard entries because SQLite is not enabled.`);
}
await this.leaderboardDeletionQuery.run([userid, LEADERBOARD_ENUM[leaderboard]]);
}
async deleteSubmissions(submissions) {
if (this.readyPromise)
await this.readyPromise;
if (!Config.usesqlite) {
throw new Chat.ErrorMessage(`Can't delete Trivia question submissions because SQLite is not enabled.`);
}
const query = await Chat.database.prepare(
`DELETE FROM trivia_questions WHERE is_submission = 1 AND question IN (${(0, import_utils.formatSQLArray)(submissions)})`
);
await query?.run(submissions);
}
/****************************************
* Private helper methods *
* These are not part of the public API *
****************************************/
async prepareStatements() {
if (!Config.usesqlite)
return;
if (Chat.databaseReadyPromise)
await Chat.databaseReadyPromise;
this.leaderboardInsertion = await Chat.database.prepare(
`INSERT OR REPLACE INTO trivia_leaderboard (userid, score, total_points, total_correct_answers, leaderboard) VALUES (?, ?, ?, ?, ?) `
);
this.questionInsertion = await Chat.database.prepare(
`INSERT OR IGNORE INTO trivia_questions (question, category, added_at, userid, is_submission) VALUES (?, ?, ?, ?, ?)`
);
this.answerInsertion = await Chat.database.prepare(
`INSERT INTO trivia_answers (question_id, answer) VALUES (?, ?)`
);
this.gameHistoryInsertion = await Chat.database.prepare(
`INSERT INTO trivia_game_history (mode, length, category, time, creator, gives_points) VALUES (?, ?, ?, ?, ?, ?)`
);
this.scoreHistoryInsertion = await Chat.database.prepare(
`INSERT INTO trivia_game_scores (game_id, userid, score) VALUES (?, ?, ?)`
);
this.updateMoveEventQuestions = await Chat.database.prepare(
`INSERT OR REPLACE INTO trivia_settings (key, value) VALUES ('moveEventQuestions', ?)`
);
this.categoryChangeQuery = await Chat.database.prepare(
`UPDATE trivia_questions SET category = ? WHERE question = ?`
);
this.leaderboardChangeQuery = await Chat.database.prepare(
`INSERT INTO trivia_leaderboard (userid, score, total_points, total_correct_answers, leaderboard) VALUES ($userid, $score, $totalPoints, $totalCorrectAnswers, $leaderboard) ON CONFLICT DO UPDATE SET score = score + $score, total_points = total_points + $totalPoints, total_correct_answers = total_correct_answers + $totalCorrectAnswers WHERE userid = $userid AND leaderboard = $leaderboard`
);
this.migrateCategoryQuery = await Chat.database.prepare(
`UPDATE OR REPLACE trivia_questions SET category = ? WHERE category = ?`
);
this.historyQuery = await Chat.database.prepare(
`SELECT * FROM trivia_game_history ORDER BY time DESC LIMIT ?`
);
this.historyScoresQuery = await Chat.database.prepare(`SELECT userid, score FROM trivia_game_scores WHERE game_id = ?`);
this.allQuestionsRandomOrderQuery = await Chat.database.prepare(
`SELECT * FROM trivia_questions WHERE category IN ('ae', 'pokemon', 'sg', 'sh') AND is_submission = 0 ORDER BY RANDOM() LIMIT ?`
);
this.allQuestionsNewestFirstQuery = await Chat.database.prepare(
`SELECT * FROM trivia_questions WHERE category IN ('ae', 'pokemon', 'sg', 'sh') AND is_submission = 0 ORDER BY added_at DESC LIMIT ?`
);
this.allQuestionsOldestFirstQuery = await Chat.database.prepare(
`SELECT * FROM trivia_questions WHERE category IN ('ae', 'pokemon', 'sg', 'sh') AND is_submission = 0 ORDER BY added_at ASC LIMIT ?`
);
this.answersQuery = await Chat.database.prepare(
`SELECT * FROM trivia_answers WHERE question_id = ?`
);
this.submissionsQuery = await Chat.database.prepare(
`SELECT * FROM trivia_questions WHERE is_submission = 1 ORDER BY category ASC`
);
this.leaderboardQuery = await Chat.database.prepare(
`SELECT * FROM trivia_leaderboard`
);
this.leaderboardByUserQuery = await Chat.database.prepare(
`SELECT * FROM trivia_leaderboard WHERE userid = ? AND leaderboard = ?`
);
this.scoreAndPointsByUser = await Chat.database.prepare(
`SELECT score, total_points as totalPoints, total_correct_answers as totalCorrectAnswers FROM trivia_leaderboard WHERE userid = ? AND leaderboard = ?`
);
this.eventQuestionQuery = await Chat.database.prepare(
`SELECT * FROM trivia_settings WHERE key = 'moveEventQuestions'`
);
this.categoriesQuery = await Chat.database.prepare(
`SELECT DISTINCT category FROM trivia_questions`
);
this.questionCountQuery = await Chat.database.prepare(
`SELECT count(*) AS count FROM trivia_questions WHERE is_submission = 0`
);
this.categoryQuestionCountQuery = await Chat.database.prepare(
`SELECT count(*) AS count FROM trivia_questions WHERE category = ? AND is_submission = 0`
);
this.questionSearchQuery = await Chat.database.prepare(
`SELECT * FROM trivia_questions WHERE question LIKE ? AND is_submission = ? ORDER BY added_at DESC`
);
this.questionExistsQuery = await Chat.database.prepare(
`SELECT * FROM trivia_questions WHERE question = ?`
);
this.leaderboardDeletionQuery = await Chat.database.prepare(
`DELETE FROM trivia_leaderboard WHERE userid = ? AND leaderboard = ?`
);
this.clearAllSubmissionsQuery = await Chat.database.prepare(
`DELETE FROM trivia_questions WHERE is_submission = 1`
);
this.clearCategoryQuery = await Chat.database.prepare(
`DELETE FROM trivia_questions WHERE category = ? AND is_submission = 0`
);
this.clearCycleLeaderboardQuery = await Chat.database.prepare(
`DELETE FROM trivia_leaderboard WHERE leaderboard = ${LEADERBOARD_ENUM.cycle}`
);
this.deleteQuestionQuery = await Chat.database.prepare(
`DELETE FROM trivia_questions WHERE question = ?`
);
await Chat.database.exec("PRAGMA foreign_keys = ON;");
await Chat.database.loadExtension("server/chat-plugins/trivia/transactions.js");
}
async convertLegacyJSON() {
if (!Config.usesqlite || !this.legacyJSONPath)
return;
if (this.readyPromise)
await this.readyPromise;
let triviaData;
try {
triviaData = JSON.parse((0, import_lib.FS)(this.legacyJSONPath).readIfExistsSync() || "{}");
if (!triviaData)
throw new Error(`no JSON`);
} catch {
return;
}
if (Array.isArray(triviaData.submissions)) {
const oldSubmissions = triviaData.submissions;
triviaData.submissions = {};
for (const question of oldSubmissions) {
if (!(question.category in triviaData.submissions))
triviaData.submissions[question.category] = [];
triviaData.submissions[question.category].push(question);
}
}
if (Array.isArray(triviaData.questions)) {
const oldSubmissions = triviaData.questions;
triviaData.questions = {};
for (const question of oldSubmissions) {
if (!(question.category in triviaData.questions))
triviaData.questions[question.category] = [];
triviaData.questions[question.category].push(question);
}
}
if (typeof triviaData.leaderboard === "object") {
for (const userid in triviaData.leaderboard) {
const [score, totalGamePoints, totalCorrectAnswers] = triviaData.leaderboard[userid];
await Chat.database.run(
this.leaderboardInsertion,
[userid, score, totalGamePoints, totalCorrectAnswers, Number(true)]
);
}
}
if (typeof triviaData.altLeaderboard === "object") {
for (const userid in triviaData.altLeaderboard) {
const [score, totalGamePoints, totalCorrectAnswers] = triviaData.altLeaderboard[userid];
await Chat.database.run(
this.leaderboardInsertion,
[userid, score, totalGamePoints, totalCorrectAnswers, Number(false)]
);
}
}
const addedAt = Date.now();
if (typeof triviaData.questions === "object") {
for (const category in triviaData.questions) {
for (const question of triviaData.questions[category]) {
if (!question.addedAt)
question.addedAt = addedAt;
if (!question.user)
question.user = "unknown user";
question.question = question.question.trim();
await this.addQuestions([question]);
}
}
}
if (typeof triviaData.submissions === "object") {
for (const category in triviaData.submissions) {
for (const question of triviaData.submissions[category]) {
if (!question.addedAt)
question.addedAt = addedAt;
if (!question.user)
question.user = "unknown user";
question.question = question.question.trim();
await this.addQuestionSubmissions([question]);
}
}
}
if (Array.isArray(triviaData.history)) {
const now = Date.now();
for (const game of triviaData.history) {
if (!game.startTime)
game.startTime = now;
await this.addHistory([game]);
}
}
if (triviaData.moveEventQuestions) {
await this.setShouldMoveEventQuestions(true);
}
try {
await (0, import_lib.FS)(this.legacyJSONPath).rename(this.legacyJSONPath + ".converted");
} catch {
}
}
rowToQuestion(row) {
return Chat.database.all(this.answersQuery, [row.question_id]).then((answerRows) => ({
question: row.question,
category: row.category,
answers: answerRows.map((answerRow) => answerRow.answer),
user: row.userid,
addedAt: row.added_at
}));
}
}
//# sourceMappingURL=database.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../../server/chat-plugins/trivia/database.ts"],
"sourcesContent": ["/**\r\n * Manages the Trivia database.\r\n *\r\n * @author Annika\r\n */\r\n\r\nimport type {TriviaGame, TriviaHistory, TriviaLeaderboardData, TriviaLeaderboardScore, TriviaQuestion} from \"./trivia\";\r\nimport {FS} from \"../../../lib\";\r\nimport {formatSQLArray} from \"../../../lib/utils\";\r\nimport type {Statement} from \"../../../lib/sql\";\r\n\r\nexport type Leaderboard = 'alltime' | 'nonAlltime' | 'cycle';\r\n/**\r\n * Keys are different Trivia leaderboards.\r\n * Values are the corresponding integer values of the SQLite `leaderboard` column.\r\n */\r\nexport const LEADERBOARD_ENUM: Record<Leaderboard, number> = {\r\n\talltime: 1,\r\n\tnonAlltime: 0,\r\n\tcycle: 2,\r\n};\r\n\r\ntype TriviaLeaderboards = Record<Leaderboard, TriviaLeaderboardData>;\r\n\r\nexport interface TriviaDatabase {\r\n\tupdateLeaderboardForUser(\r\n\t\tuserid: ID,\r\n\t\tadditions: Record<Leaderboard, TriviaLeaderboardScore>\r\n\t): Promise<void> | void;\r\n\taddHistory(history: Iterable<TriviaHistory>): Promise<void> | void;\r\n\taddQuestions(questions: Iterable<TriviaQuestion>): Promise<void> | void;\r\n\taddQuestionSubmissions(questions: Iterable<TriviaQuestion>): Promise<void> | void;\r\n\tsetShouldMoveEventQuestions(shouldMove: boolean): Promise<void> | void;\r\n\tmergeLeaderboardEntries(from: ID, to: ID): Promise<void> | void;\r\n\r\n\tshouldMoveEventQuestions(): Promise<boolean> | boolean;\r\n\tmoveQuestionToCategory(question: string, newCategory: string): Promise<void> | void;\r\n\tmigrateCategory(sourceCategory: string, targetCategory: string): Promise<number> | number;\r\n\tacceptSubmissions(submissions: string[]): Promise<void> | void;\r\n\teditQuestion(oldQuestionText: string, newQuestionText?: string, newAnswers?: string[]): Promise<void>;\r\n\r\n\tgetHistory(numberOfLines: number): Promise<TriviaGame[]> | TriviaGame[];\r\n\tgetScoresForLastGame(): Promise<{[k: string]: number}> | {[k: string]: number};\r\n\tgetQuestions(\r\n\t\tcategories: string[] | 'all',\r\n\t\tlimit: number,\r\n\t\toptions: {order: 'newestfirst' | 'oldestfirst' | 'random'}\r\n\t): Promise<TriviaQuestion[]> | TriviaQuestion[];\r\n\tgetLeaderboardEntry(\r\n\t\tid: ID,\r\n\t\tleaderboard: Leaderboard\r\n\t): Promise<TriviaLeaderboardScore | null> | TriviaLeaderboardScore | null;\r\n\tgetLeaderboards(): Promise<TriviaLeaderboards> | TriviaLeaderboards;\r\n\r\n\tgetQuestion(questionText: string): Promise<TriviaQuestion | null> | TriviaQuestion | null;\r\n\tensureQuestionExists(questionText: string): Promise<TriviaQuestion> | TriviaQuestion;\r\n\tensureQuestionDoesNotExist(questionText: string): Promise<void> | void;\r\n\tgetSubmissions(): Promise<TriviaQuestion[]> | TriviaQuestion[];\r\n\tgetQuestionCounts(): Promise<{[k: string]: number, total: number}> | {[k: string]: number, total: number};\r\n\tsearchQuestions(\r\n\t\tsearch: string,\r\n\t\toptions: {searchSubmissions: boolean, caseSensitive?: boolean}\r\n\t): Promise<TriviaQuestion[]> | TriviaQuestion[];\r\n\r\n\tclearSubmissions(): Promise<void> | void;\r\n\tclearCategory(category: string): Promise<void> | void;\r\n\tclearCycleLeaderboard(): Promise<void> | void;\r\n\tdeleteQuestion(questionText: string): Promise<void> | void;\r\n\tdeleteLeaderboardEntry(userid: ID, leaderboard: Leaderboard): Promise<void> | void;\r\n\tdeleteSubmissions(submissions: string[]): Promise<void> | void;\r\n}\r\n\r\nexport class TriviaSQLiteDatabase implements TriviaDatabase {\r\n\treadyPromise: Promise<void> | null;\r\n\r\n\tprivate legacyJSONPath?: string;\r\n\r\n\t// adding data\r\n\tprivate leaderboardInsertion: Statement | null;\r\n\tprivate questionInsertion: Statement | null;\r\n\tprivate answerInsertion: Statement | null;\r\n\tprivate gameHistoryInsertion: Statement | null;\r\n\tprivate scoreHistoryInsertion: Statement | null;\r\n\tprivate updateMoveEventQuestions: Statement | null;\r\n\r\n\t// modifying data\r\n\tprivate categoryChangeQuery: Statement | null;\r\n\tprivate leaderboardChangeQuery: Statement | null;\r\n\tprivate migrateCategoryQuery: Statement | null;\r\n\r\n\t// fetching data\r\n\tprivate historyQuery: Statement | null;\r\n\tprivate historyScoresQuery: Statement | null;\r\n\tprivate allQuestionsRandomOrderQuery: Statement | null;\r\n\tprivate allQuestionsNewestFirstQuery: Statement | null;\r\n\tprivate allQuestionsOldestFirstQuery: Statement | null;\r\n\tprivate answersQuery: Statement | null;\r\n\tprivate submissionsQuery: Statement | null;\r\n\tprivate leaderboardQuery: Statement | null;\r\n\tprivate leaderboardByUserQuery: Statement | null;\r\n\tprivate scoreAndPointsByUser: Statement | null;\r\n\tprivate eventQuestionQuery: Statement | null;\r\n\tprivate categoriesQuery: Statement | null;\r\n\tprivate questionCountQuery: Statement | null;\r\n\tprivate categoryQuestionCountQuery: Statement | null;\r\n\tprivate questionSearchQuery: Statement | null;\r\n\tprivate questionExistsQuery: Statement | null;\r\n\r\n\t// deleting data\r\n\tprivate clearAllSubmissionsQuery: SLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAiB;AACjB,mBAA6B;AAQtB,MAAM,mBAAgD;AAAA,EAC5D,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,OAAO;AACR;AAoDO,MAAM,qBAA+C;AAAA,EA2C3D,YAAY,gBAAyB;AACpC,SAAK,iBAAiB;AAEtB,SAAK,uBAAuB;AAC5B,SAAK,oBAAoB;AACzB,SAAK,kBAAkB;AACvB,SAAK,uBAAuB;AAC5B,SAAK,wBAAwB;AAC7B,SAAK,2BAA2B;AAE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I;AAAA,MAC3E,UAAU,IAAI;AAAA,MACd,SAAS,IAAI,WAAW;AAAA,MACxB,aAAa,IAAI,gBAAgB;AAAA,MACjC,WAAW,IAAI;AAAA,IAChB,EAAE;AAAA,EACH;AAAA,EAEA,MAAM,uBAAuD;AAC5D,QAAI,KAAK;AAAc,YAAM,KAAK;AAClC,QAAI,CAAC,OAAO,WAAW;AACtB,YAAM,IAAI,KAAK,aAAa,6DAA6D;AAAA,IAC1F;AACA,UAAM,EAAC,QAAO,IAAI,MAAM,KAAK,aAAc,IAAI,CAAC,CAAC,CAAC;AAElD,UAAM,UAAiC,CAAC;AACxC,eAAW,OAAO,MAAM,KAAK,mBAAoB,IAAI,CAAC,OAAO,CAAC,GAAG;AAChE,cAAQ,IAAI,MAAM,IAAI,IAAI;AAAA,IAC3B;AACA,WAAO;AAAA,EACR;AAAA,EAEA,MAAM,aACL,YALine truncated
"names": []
}
@@ -0,0 +1,82 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var transactions_exports = {};
__export(transactions_exports, {
transactions: () => transactions
});
module.exports = __toCommonJS(transactions_exports);
const transactions = {
addHistory: (args, env) => {
const gameHistoryInsertion = env.statements.get(args.gameHistoryInsertion);
const scoreHistoryInsertion = env.statements.get(args.scoreHistoryInsertion);
if (!gameHistoryInsertion || !scoreHistoryInsertion)
throw new Error("Statements not found");
for (const game of args.history) {
const { lastInsertRowid } = gameHistoryInsertion.run(
game.mode,
game.length,
game.category,
game.startTime,
game.creator,
Number(game.givesPoints)
);
for (const userid in game.scores) {
scoreHistoryInsertion.run(lastInsertRowid, userid, game.scores[userid]);
}
}
return true;
},
editQuestion(args, env) {
const { oldQuestionText, newQuestionText, newAnswers } = args;
if (newAnswers) {
const questionID = env.db.prepare("SELECT question_id FROM trivia_questions WHERE question = ?").get(oldQuestionText)?.question_id;
if (!questionID)
throw new Error("Question not found");
env.db.prepare("DELETE FROM trivia_answers WHERE question_id = ?").run(questionID);
const insert = env.db.prepare("INSERT INTO trivia_answers (question_id, answer) VALUES (?, ?)");
for (const answer of newAnswers) {
insert.run([questionID, answer]);
}
}
if (newQuestionText) {
env.db.prepare(`UPDATE trivia_questions SET question = ? WHERE question = ?`).run([newQuestionText, oldQuestionText]);
}
},
addQuestions: (args, env) => {
const questionInsertion = env.statements.get(args.questionInsertion);
const answerInsertion = env.statements.get(args.answerInsertion);
if (!questionInsertion || !answerInsertion)
throw new Error("Statements not found");
const isSubmissionForSQLite = Number(args.isSubmission);
for (const question of args.questions) {
const { lastInsertRowid } = questionInsertion.run(
question.question,
question.category,
question.addedAt,
question.user,
isSubmissionForSQLite
);
for (const answer of question.answers) {
answerInsertion.run(lastInsertRowid, answer);
}
}
return true;
}
};
//# sourceMappingURL=transactions.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../../server/chat-plugins/trivia/transactions.ts"],
"sourcesContent": ["/**\r\n * SQL transactions for the Trivia plugin.\r\n */\r\n\r\nimport type {TransactionEnvironment} from '../../../lib/sql';\r\nimport type {TriviaHistory, TriviaQuestion} from './trivia';\r\n\r\nexport const transactions = {\r\n\taddHistory: (\r\n\t\targs: {history: Iterable<TriviaHistory>, gameHistoryInsertion: string, scoreHistoryInsertion: string},\r\n\t\tenv: TransactionEnvironment\r\n\t) => {\r\n\t\tconst gameHistoryInsertion = env.statements.get(args.gameHistoryInsertion);\r\n\t\tconst scoreHistoryInsertion = env.statements.get(args.scoreHistoryInsertion);\r\n\t\tif (!gameHistoryInsertion || !scoreHistoryInsertion) throw new Error('Statements not found');\r\n\r\n\t\tfor (const game of args.history) {\r\n\t\t\tconst {lastInsertRowid} = gameHistoryInsertion.run(\r\n\t\t\t\tgame.mode, game.length, game.category, game.startTime, game.creator, Number(game.givesPoints)\r\n\t\t\t);\r\n\t\t\tfor (const userid in game.scores) {\r\n\t\t\t\tscoreHistoryInsertion.run(lastInsertRowid, userid, game.scores[userid]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\teditQuestion(\r\n\t\targs: {oldQuestionText: string, newQuestionText?: string, newAnswers?: string[]},\r\n\t\tenv: TransactionEnvironment,\r\n\t) {\r\n\t\t// Question editing is likely to be infrequent, so I've optimized for readability and proper argument checking\r\n\t\t// rather than performance (i.e. not passing in prepared statements).\r\n\t\tconst {oldQuestionText, newQuestionText, newAnswers} = args;\r\n\r\n\t\tif (newAnswers) {\r\n\t\t\tconst questionID = env.db\r\n\t\t\t\t.prepare('SELECT question_id FROM trivia_questions WHERE question = ?')\r\n\t\t\t\t.get(oldQuestionText)?.question_id;\r\n\t\t\tif (!questionID) throw new Error('Question not found');\r\n\t\t\tenv.db.prepare('DELETE FROM trivia_answers WHERE question_id = ?').run(questionID);\r\n\t\t\tconst insert = env.db.prepare('INSERT INTO trivia_answers (question_id, answer) VALUES (?, ?)');\r\n\t\t\tfor (const answer of newAnswers) {\r\n\t\t\t\tinsert.run([questionID, answer]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (newQuestionText) {\r\n\t\t\tenv.db\r\n\t\t\t\t.prepare(`UPDATE trivia_questions SET question = ? WHERE question = ?`)\r\n\t\t\t\t.run([newQuestionText, oldQuestionText]);\r\n\t\t}\r\n\t},\r\n\r\n\taddQuestions: (\r\n\t\targs: {\r\n\t\t\tquestions: Iterable<TriviaQuestion>,\r\n\t\t\tquestionInsertion: string,\r\n\t\t\tanswerInsertion: string,\r\n\t\t\tisSubmission: boolean,\r\n\t\t},\r\n\t\tenv: TransactionEnvironment\r\n\t) => {\r\n\t\tconst questionInsertion = env.statements.get(args.questionInsertion);\r\n\t\tconst answerInsertion = env.statements.get(args.answerInsertion);\r\n\t\tif (!questionInsertion || !answerInsertion) throw new Error('Statements not found');\r\n\r\n\t\tconst isSubmissionForSQLite = Number(args.isSubmission);\r\n\t\tfor (const question of args.questions) {\r\n\t\t\tconst {lastInsertRowid} = questionInsertion.run(\r\n\t\t\t\tquestion.question, question.category, question.addedAt, question.user, isSubmissionForSQLite\r\n\t\t\t);\r\n\t\t\tfor (const answer of question.answers) {\r\n\t\t\t\tanswerInsertion.run(lastInsertRowid, answer);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t},\r\n};\r\n"],
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOO,MAAM,eAAe;AAAA,EAC3B,YAAY,CACX,MACA,QACI;AACJ,UAAM,uBAAuB,IAAI,WAAW,IAAI,KAAK,oBAAoB;AACzE,UAAM,wBAAwB,IAAI,WAAW,IAAI,KAAK,qBAAqB;AAC3E,QAAI,CAAC,wBAAwB,CAAC;AAAuB,YAAM,IAAI,MAAM,sBAAsB;AAE3F,eAAW,QAAQ,KAAK,SAAS;AAChC,YAAM,EAAC,gBAAe,IAAI,qBAAqB;AAAA,QAC9C,KAAK;AAAA,QAAM,KAAK;AAAA,QAAQ,KAAK;AAAA,QAAU,KAAK;AAAA,QAAW,KAAK;AAAA,QAAS,OAAO,KAAK,WAAW;AAAA,MAC7F;AACA,iBAAW,UAAU,KAAK,QAAQ;AACjC,8BAAsB,IAAI,iBAAiB,QAAQ,KAAK,OAAO,MAAM,CAAC;AAAA,MACvE;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AAAA,EAEA,aACC,MACA,KACC;AAGD,UAAM,EAAC,iBAAiB,iBAAiB,WAAU,IAAI;AAEvD,QAAI,YAAY;AACf,YAAM,aAAa,IAAI,GACrB,QAAQ,6DAA6D,EACrE,IAAI,eAAe,GAAG;AACxB,UAAI,CAAC;AAAY,cAAM,IAAI,MAAM,oBAAoB;AACrD,UAAI,GAAG,QAAQ,kDAAkD,EAAE,IAAI,UAAU;AACjF,YAAM,SAAS,IAAI,GAAG,QAAQ,gEAAgE;AAC9F,iBAAW,UAAU,YAAY;AAChC,eAAO,IAAI,CAAC,YAAY,MAAM,CAAC;AAAA,MAChC;AAAA,IACD;AAEA,QAAI,iBAAiB;AACpB,UAAI,GACF,QAAQ,6DAA6D,EACrE,IAAI,CAAC,iBAAiB,eAAe,CAAC;AAAA,IACzC;AAAA,EACD;AAAA,EAEA,cAAc,CACb,MAMA,QACI;AACJ,UAAM,oBAAoB,IAAI,WAAW,IAAI,KAAK,iBAAiB;AACnE,UAAM,kBAAkB,IAAI,WAAW,IAAI,KAAK,eAAe;AAC/D,QAAI,CAAC,qBAAqB,CAAC;AAAiB,YAAM,IAAI,MAAM,sBAAsB;AAElF,UAAM,wBAAwB,OAAO,KAAK,YAAY;AACtD,eAAW,YAAY,KAAK,WAAW;AACtC,YAAM,EAAC,gBAAe,IAAI,kBAAkB;AAAA,QAC3C,SAAS;AAAA,QAAU,SAAS;AAAA,QAAU,SAAS;AAAA,QAAS,SAAS;AAAA,QAAM;AAAA,MACxE;AACA,iBAAW,UAAU,SAAS,SAAS;AACtC,wBAAgB,IAAI,iBAAiB,MAAM;AAAA,MAC5C;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;",
"names": []
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../../server/chat-plugins/trivia/trivia.ts"],
"sourcesContent": ["/*\r\n * Trivia plugin\r\n * Written by Morfent\r\n */\r\n\r\nimport {Utils} from '../../../lib';\r\nimport {Leaderboard, LEADERBOARD_ENUM, TriviaDatabase, TriviaSQLiteDatabase} from './database';\r\n\r\nconst MAIN_CATEGORIES: {[k: string]: string} = {\r\n\tae: 'Arts and Entertainment',\r\n\tpokemon: 'Pok\\u00E9mon',\r\n\tsg: 'Science and Geography',\r\n\tsh: 'Society and Humanities',\r\n};\r\n\r\nconst SPECIAL_CATEGORIES: {[k: string]: string} = {\r\n\tmisc: 'Miscellaneous',\r\n\tevent: 'Event',\r\n\teventused: 'Event (used)',\r\n\tsubcat: 'Sub-Category 1',\r\n\tsubcat2: 'Sub-Category 2',\r\n\tsubcat3: 'Sub-Category 3',\r\n\tsubcat4: 'Sub-Category 4',\r\n\tsubcat5: 'Sub-Category 5',\r\n\toldae: 'Old Arts and Entertainment',\r\n\toldsg: 'Old Science and Geography',\r\n\toldsh: 'Old Society and Humanities',\r\n\toldpoke: 'Old Pok\\u00E9mon',\r\n};\r\n\r\nconst ALL_CATEGORIES: {[k: string]: string} = {...SPECIAL_CATEGORIES, ...MAIN_CATEGORIES};\r\n\r\n/**\r\n * Aliases for keys in the ALL_CATEGORIES object.\r\n */\r\nconst CATEGORY_ALIASES: {[k: string]: ID} = {\r\n\tpoke: 'pokemon' as ID,\r\n\tsubcat1: 'subcat' as ID,\r\n};\r\n\r\nconst MODES: {[k: string]: string} = {\r\n\tfirst: 'First',\r\n\tnumber: 'Number',\r\n\ttimer: 'Timer',\r\n\ttriumvirate: 'Triumvirate',\r\n};\r\n\r\nconst LENGTHS: {[k: string]: {cap: number | false, prizes: number[]}} = {\r\n\tshort: {\r\n\t\tcap: 20,\r\n\t\tprizes: [3, 2, 1],\r\n\t},\r\n\tmedium: {\r\n\t\tcap: 35,\r\n\t\tprizes: [4, 2, 1],\r\n\t},\r\n\tlong: {\r\n\t\tcap: 50,\r\n\t\tprizes: [5, 3, 1],\r\n\t},\r\n\tinfinite: {\r\n\t\tcap: false,\r\n\t\tprizes: [5, 3, 1],\r\n\t},\r\n};\r\n\r\nObject.setPrototypeOf(MAIN_CATEGORIES, null);\r\nObject.setPrototypeOf(SPECIAL_CATEGORIES, null);\r\nObject.setPrototypeOf(ALL_CATEGORIES, null);\r\nObject.setPrototypeOf(MODES, null);\r\nObject.setPrototypeOf(LENGTHS, null);\r\n\r\nconst SIGNUP_PHASE = 'signups';\r\nconst QUESTION_PHASE = 'question';\r\nconst INTERMISSION_PHASE = 'intermission';\r\n\r\nconst MASTERMIND_ROUNDS_PHASE = 'rounds';\r\nconst MASTERMIND_FINALS_PHASE = 'finals';\r\n\r\nconst MOVE_QUESTIONS_AFTER_USE_FROM_CATEGORY = 'event';\r\nconst MOVE_QUESTIONS_AFTER_USE_TO_CATEGORY = 'eventused';\r\n\r\nconst START_TIMEOUT = 30 * 1000;\r\nconst MASTERMIND_FINALS_START_TIMEOUT = 30 * 1000;\r\nconst INTERMISSION_INTERVAL = 20 * 1000;\r\nconst MASTERMIND_INTERMISSION_INTERVAL = 500; // 0.5 seconds\r\nconst PAUSE_INTERMISSION = 5 * 1000;\r\n\r\nconst MAX_QUESTION_LENGTH = 252;\r\nconst MAX_ANSWER_LENGTH = 32;\r\n\r\nexport interface TriviaQuestion {\r\n\tquestion: string;\r\n\tcategory: string;\r\n\tanswers: string[];\r\n\tuser?: string;\r\n\t/** UNIX timestamp in milliseconds */\r\n\taddedAt?: number;\r\n}\r\n\r\nexport interface TriviaLeaderboardData {\r\n\t[userid: string]: TriviaLeaderboardScore;\r\n}\r\nexport interface TriviaLeaderboardScore {\r\n\tscore: number;\r\n\ttotalPoints: number;\r\n\ttotalCorrectAnswers: number;\r\n}\r\nexport interface TriviaGame {\r\n\tmode: string;\r\n\t/** if number, question cap, else score cap */\r\n\tlength: keyof typeof LENGTHS | number;\r\n\tcategory: string;\r\n\tstartTime: number;\r\n\tcreator?: string;\r\n\tgivesPoints?: boolean;\r\n}\r\n\r\ntype TriviaLadder = ID[][];\r\nexport type TriviaHistory = TriviaGame & {scores: {[k: string]: number}};\r\n\r\nexport interface TriviaData {\r\n\t/** category:questions */\r\n\tquestions?: {[k: string]: TriviaQuestion[]};\r\n\tsubmissions?: {[k: string]: TriviaQuestion[]};\r\n\tleaderboard?: TriviaLeaderboardData;\r\n\taltLeaderboard?: TriviaLeaderboardData;\r\n\t/* `scores` key is a user ID */\r\n\thistory?: TriviaHistory[];\r\n\tmoveEventQuestions?: boolean;\r\n}\r\n\r\ninterface TopPlayer {\r\n\tid: string;\r\n\tplayer: TriviaPlayer;\r\n\tname: string;\r\n}\r\n\r\nexport const database: TriviaDatabase = new TriviaSQLiteDatabase('config/chat-plugins/triviadata.json');\r\n\r\n/** from:to Map */\r\nexport const pendingAltMerges = new Map<ID, ID>();\r\n\r\nfunction getTriviaGame(room: Room | null) {\r\n\tif (!room) {\r\n\t\tthrow new Chat.ErrorMessage(`This command can only be used in the Trivia room.`);\r\n\t}\r\n\tconst game = room.game;\r\n\tif (!game) {\r\n\t\tthrow new Chat.ErrorMessage(room.tr`There is no game in progress.`);\r\n\t}\r\n\tif (game.gameid !== 'trivia') {\r\n\t\tthrow new Chat.ErrorMessage(room.tr`The currently running game is not Trivia, it's ${game.title}.`);\r\n\t}\r\n\treturn game as Trivia;\r\n}\r\n\r\nfunction getMastermindGame(room: Room | null) {\r\n\tif (!room) {\r\n\t\tthrow new Chat.ErrorMessage(`This command can only be used in the Trivia room.`);\r\n\t}\r\n\tconst game = room.game;\r\n\tif (!game) {\r\n\t\tthrow new Chat.ErrorMessage(room.tr`There is no game in progress.`);\r\n\t}\r\n\tif (game.gameid !== 'mastermind') {\r\n\t\tthrow new Chat.ErrorMessage(room.tr`The currently running game is not Mastermind, it's ${game.title}.`);\r\n\t}\r\n\treturn game as Mastermind;\r\n}\r\n\r\nfunction getTriLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,iBAAoB;AACpB,sBAAkF;AAElF,MAAM,kBAAyC;AAAA,EAC9C,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,IAAI;AAAA,EACJ,IAAI;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W,OAAO,KAAK;AAClC,gBAAI,CAAC,OAAO,IAAI;AAAG,qBAAO,IAAI,IAAI,CAAC;AACnC,mBAAO,IAAI,EAAE,KAAK,MAAY;AAAA,UAC/B;AACA,gBAAM,MAAM,EAAE,GAAG,IAAI,OAAO;AAAA,QAC7B;AAAA,MACD;AACA,WAAK,MAAM,EAAE,IAAI,EAAC,QAAQ,MAAK;AAAA,IAChC;AAAA,EACD;AACD;AAEO,MAAM,eAAe,IAAI,OAAO;AAEvC,MAAM,qBAAqB,MAAM,eAAuB;AAAA,EAUvD,YAAY,MAAY,MAAc;AACrC,UAAM,MAAM,IAAI;AAChB,SAAK,SAAS;AACd,SAAK,iBAAiB;AACtB,SAAK,SAAS;AACd,SAAK,oBAAoB,CAAC;AAC1B,SAAK,eAAe;AACpB,SAAK,aAAa,CAAC;AACnB,SAAK,YAAY;AACjB,SAAK,WAAW;AAAA,EACjB;AAAA,EAEA,UAAU,QAAgB,WAAqB;AAC9C,SAAK,SAAS;AACd,SAAK,oBAAoB,QAAQ,OAAO;AACxC,SAAK,YAAY,Line truncated
"names": ["scores", "category"]
}
+833
View File
@@ -0,0 +1,833 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var uno_exports = {};
__export(uno_exports, {
UNO: () => UNO,
commands: () => commands,
roomSettings: () => roomSettings
});
module.exports = __toCommonJS(uno_exports);
var import_lib = require("../../lib");
/**
* UNO
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This plugin allows rooms to run games of scripted UNO
*
* @license MIT license
*/
const maxTime = 60;
const rgbGradients = {
Green: "rgba(0, 122, 0, 1), rgba(0, 185, 0, 0.9)",
Yellow: "rgba(255, 225, 0, 1), rgba(255, 255, 85, 0.9)",
Blue: "rgba(40, 40, 255, 1), rgba(125, 125, 255, 0.9)",
Red: "rgba(255, 0, 0, 1), rgba(255, 125, 125, 0.9)",
Black: "rgba(0, 0, 0, 1), rgba(0, 0, 0, 0.55)"
};
const textColors = {
Green: "rgb(0, 128, 0)",
Yellow: "rgb(175, 165, 40)",
Blue: "rgb(75, 75, 255)",
Red: "rgb(255, 0, 0)",
Black: "inherit"
};
const textShadow = "text-shadow: 1px 0px black, -1px 0px black, 0px -1px black, 0px 1px black, 2px -2px black;";
function cardHTML(card, fullsize) {
let surface = card.value.replace(/[^A-Z0-9+]/g, "");
const background = rgbGradients[card.color];
if (surface === "R")
surface = '<i class="fa fa-refresh" aria-hidden="true"></i>';
return `<button class="button" style="font-size: 14px; font-weight: bold; color: white; ${textShadow} padding-bottom: 117px; text-align: left; height: 135px; width: ${fullsize ? "72" : "37"}px; border-radius: 10px 2px 2px 3px; color: white; background: ${card.color}; background: -webkit-linear-gradient(${background}); background: -o-linear-gradient(${background}); background: -moz-linear-gradient(${background}); background: linear-gradient(${background})" name=send value="/uno play ${card.name}" aria-label="${card.name}">${surface}</button>`;
}
function createDeck() {
const colors = ["Red", "Blue", "Green", "Yellow"];
const values = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "Reverse", "Skip", "+2"];
const basic = [];
for (const color of colors) {
basic.push(...values.map((v) => {
const c = { value: v, color, name: `${color} ${v}` };
return c;
}));
}
return [
// two copies of the basic stuff (total 96)
...basic,
...basic,
// The four 0s
...[0, 1, 2, 3].map((v) => {
const c = { color: colors[v], value: "0", name: `${colors[v]} 0` };
return c;
}),
// Wild cards
...[0, 1, 2, 3].map((v) => {
const c = { color: "Black", value: "Wild", name: "Wild" };
return c;
}),
// Wild +4 cards
...[0, 1, 2, 3].map((v) => {
const c = { color: "Black", value: "+4", name: "Wild +4" };
return c;
})
];
}
class UNO extends Rooms.RoomGame {
constructor(room, cap, suppressMessages) {
super(room);
this.gameNumber = room.nextGameNumber();
this.playerCap = cap;
this.allowRenames = true;
this.maxTime = maxTime;
this.timer = null;
this.autostartTimer = null;
this.gameid = "uno";
this.title = "UNO";
this.state = "signups";
this.currentPlayerid = "";
this.deck = import_lib.Utils.shuffle(createDeck());
this.discards = [];
this.topCard = null;
this.awaitUno = null;
this.unoId = null;
this.isPlusFour = false;
this.direction = 1;
this.suppressMessages = suppressMessages || false;
this.spectators = /* @__PURE__ */ Object.create(null);
this.sendToRoom(`|uhtml|uno-${this.gameNumber}|<div class="broadcast-blue"><p style="font-size: 14pt; text-align: center">A new game of <strong>UNO</strong> is starting!</p><p style="font-size: 9pt; text-align: center"><button class="button" name="send" value="/uno join"><strong>Join and play</strong></button> <button class="button" name="send" value="/uno spectate">Watch</button></p>${this.suppressMessages ? `<p style="font-size: 6pt; text-align: center">Game messages won't show up unless you're playing or watching.</p>` : ""}</div>`, true);
}
onUpdateConnection() {
}
onConnect(user, connection) {
if (this.state === "signups") {
connection.sendTo(
this.room,
`|uhtml|uno-${this.gameNumber}|<div class="broadcast-blue"><p style="font-size: 14pt; text-align: center">A new game of <strong>UNO</strong> is starting!</p><p style="font-size: 9pt; text-align: center"><button class="button" name="send" value="/uno join"><strong>Join and play</strong></button> <button class="button" name="send" value="/uno spectate">Watch</button></p>${this.suppressMessages ? `<p style="font-size: 6pt; text-align: center">Game messages won't show up unless you're playing or watching.` : ""}</div>`
);
} else if (this.onSendHand(user) === false) {
connection.sendTo(
this.room,
`|uhtml|uno-${this.gameNumber}|<div class="infobox"><p>A game of UNO is currently in progress.<button class="button" name="send" value="/uno spectate">Spectate Game</button></p>${this.suppressMessages ? `<p style="font-size: 6pt">Game messages won't show up unless you're playing or watching.` : ""}</div>`
);
}
}
onStart(isAutostart) {
if (this.playerCount < 2) {
if (isAutostart) {
this.room.add("The game of UNO was forcibly ended because there aren't enough users.");
this.destroy();
return false;
} else {
throw new Chat.ErrorMessage("There must be at least 2 players to start a game of UNO.");
}
}
if (this.autostartTimer)
clearTimeout(this.autostartTimer);
this.sendToRoom(`|uhtmlchange|uno-${this.gameNumber}|<div class="infobox"><p>The game of UNO has started. <button class="button" name="send" value="/uno spectate">Spectate Game</button></p>${this.suppressMessages ? `<p style="font-size: 6pt">Game messages won't show up unless you're playing or watching.` : ""}</div>`, true);
this.state = "play";
this.onNextPlayer();
for (const i in this.playerTable) {
this.playerTable[i].hand.push(...this.drawCard(7));
}
do {
this.topCard = this.drawCard(1)[0];
this.discards.unshift(this.topCard);
} while (this.topCard.color === "Black");
this.sendToRoom(`|raw|The top card is <span style="font-weight:bold;color: ${textColors[this.topCard.color]}">${this.topCard.name}</span>.`);
this.onRunEffect(this.topCard.value, true);
this.nextTurn(true);
}
joinGame(user) {
if (user.id in this.playerTable) {
throw new Chat.ErrorMessage("You have already joined the game of UNO.");
}
if (this.state === "signups" && this.addPlayer(user)) {
this.sendToRoom(`${user.name} has joined the game of UNO.`);
return true;
}
return false;
}
leaveGame(user) {
if (!(user.id in this.playerTable))
return false;
if (this.state === "signups" && this.removePlayer(user) || this.eliminate(user.id)) {
this.sendToRoom(`${user.name} has left the game of UNO.`);
return true;
}
return false;
}
/**
* Overwrite the default makePlayer so it makes an UNOPlayer instead.
*/
makePlayer(user) {
return new UNOPlayer(user, this);
}
onRename(user, oldUserid, isJoining, isForceRenamed) {
if (!(oldUserid in this.playerTable) || user.id === oldUserid)
return false;
if (!user.named && !isForceRenamed) {
user.games.delete(this.roomid);
user.updateSearch();
return;
}
this.playerTable[user.id] = this.playerTable[oldUserid];
if (user.id !== oldUserid)
delete this.playerTable[oldUserid];
this.playerTable[user.id].name = user.name;
this.playerTable[user.id].id = user.id;
if (this.awaitUno && this.awaitUno === oldUserid)
this.awaitUno = user.id;
if (this.currentPlayerid === oldUserid)
this.currentPlayerid = user.id;
}
eliminate(userid) {
if (!(userid in this.playerTable))
return false;
const name = this.playerTable[userid].name;
if (this.playerCount === 2) {
this.removePlayer(this.playerTable[userid]);
this.onWin(this.playerTable[Object.keys(this.playerTable)[0]]);
return name;
}
const removingCurrentPlayer = userid === this.currentPlayerid;
if (removingCurrentPlayer) {
if (this.state === "color") {
if (!this.topCard) {
throw new Error(`No top card in the discard pile.`);
}
this.topCard.changedColor = this.discards[1].changedColor || this.discards[1].color;
this.sendToRoom(`|raw|${import_lib.Utils.escapeHTML(name)} has not picked a color, the color will stay as <span style="color: ${textColors[this.topCard.changedColor]}">${this.topCard.changedColor}</span>.`);
}
}
if (this.awaitUno === userid)
this.awaitUno = null;
if (!this.topCard) {
throw new Chat.ErrorMessage(`Unable to disqualify ${name}.`);
}
this.discards.push(...this.playerTable[userid].hand);
if (removingCurrentPlayer) {
this.onNextPlayer();
}
this.removePlayer(this.playerTable[userid]);
if (removingCurrentPlayer) {
this.nextTurn(true);
}
return name;
}
sendToRoom(msg, overrideSuppress = false) {
if (!this.suppressMessages || overrideSuppress) {
this.room.add(msg).update();
} else {
for (const i in this.playerTable) {
this.playerTable[i].sendRoom(msg);
}
for (const i in this.spectators) {
if (i in this.playerTable)
continue;
const user = Users.getExact(i);
if (user)
user.sendTo(this.roomid, msg);
}
}
}
getPlayers(showCards) {
let playerList = Object.keys(this.playerTable);
if (!showCards) {
return playerList.sort().map((id) => import_lib.Utils.escapeHTML(this.playerTable[id].name)).join(", ");
}
if (this.direction === -1)
playerList = playerList.reverse();
let buf = `<ol style="padding-left:0;">`;
for (const playerid of playerList) {
buf += `<li${this.currentPlayerid === playerid ? ` style="font-weight:bold;"` : ""}>`;
buf += `${import_lib.Utils.escapeHTML(this.playerTable[playerid].name)} (${this.playerTable[playerid].hand.length})`;
buf += `</li>`;
}
buf += `</ol>`;
return buf;
}
onAwaitUno() {
return new Promise((resolve) => {
if (!this.awaitUno)
return resolve();
this.state = "uno";
setTimeout(() => resolve(), 750);
});
}
nextTurn(starting) {
void this.onAwaitUno().then(() => {
if (!starting)
this.onNextPlayer();
if (this.timer)
clearTimeout(this.timer);
const player = this.playerTable[this.currentPlayerid];
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|${player.name}'s turn.`);
this.state = "play";
if (player.cardLock)
player.cardLock = null;
player.sendDisplay();
this.timer = setTimeout(() => {
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|${player.name} has been automatically disqualified.`);
this.eliminate(this.currentPlayerid);
}, this.maxTime * 1e3);
});
}
onNextPlayer() {
if (!this.currentPlayerid) {
const userList = Object.keys(this.playerTable);
this.currentPlayerid = userList[Math.floor(this.playerCount * Math.random())];
}
this.currentPlayerid = this.getNextPlayer();
}
getNextPlayer() {
const userList = Object.keys(this.playerTable);
let player = userList[userList.indexOf(this.currentPlayerid) + this.direction];
if (!player) {
player = toID(this.direction === 1 ? userList[0] : userList[this.playerCount - 1]);
}
return player;
}
onDraw(player) {
if (this.currentPlayerid !== player.id || this.state !== "play")
return false;
if (player.cardLock)
return true;
this.onCheckUno();
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|${player.name} has drawn a card.`);
const card = this.onDrawCard(player, 1);
player.sendDisplay();
player.cardLock = card[0].name;
}
onPlay(player, cardName) {
if (this.currentPlayerid !== player.id || this.state !== "play")
return false;
const card = player.hasCard(cardName);
if (!card)
return "You do not have that card.";
if (!this.topCard) {
throw new Error(`No top card in the discard pile.`);
}
if (player.cardLock && player.cardLock !== cardName)
return `You can only play ${player.cardLock} after drawing.`;
if (card.color !== "Black" && card.color !== (this.topCard.changedColor || this.topCard.color) && card.value !== this.topCard.value) {
return `You cannot play this card; you can only play: Wild cards, ${this.topCard.changedColor ? "and" : ""} ${this.topCard.changedColor || this.topCard.color} cards${this.topCard.changedColor ? "" : ` and cards with the digit ${this.topCard.value}`}.`;
}
if (card.value === "+4" && !player.canPlayWildFour()) {
return "You cannot play Wild +4 when you still have a card with the same color as the top card.";
}
if (this.timer)
clearTimeout(this.timer);
this.onCheckUno();
this.topCard = card;
player.removeCard(cardName);
this.discards.unshift(card);
if (player.hand.length === 1) {
this.awaitUno = player.id;
this.unoId = Math.floor(Math.random() * 100).toString();
}
player.sendDisplay();
this.sendToRoom(`|raw|${import_lib.Utils.escapeHTML(player.name)} has played a <span style="font-weight:bold;color: ${textColors[card.color]}">${card.name}</span>.`);
if (!player.hand.length) {
this.onWin(player);
return;
}
this.onRunEffect(card.value);
if (this.state === "play")
this.nextTurn();
}
onRunEffect(value, initialize) {
const colorDisplay = `|uhtml|uno-color|<table style="width: 100%; border: 1px solid black"><tr><td style="width: 50%"><button style="width: 100%; background-color: red; border: 2px solid rgba(0 , 0 , 0 , 0.59); border-radius: 5px; padding: 5px" name=send value="/uno color Red">Red</button></td><td style="width: 50%"><button style="width: 100%; background-color: blue; border: 2px solid rgba(0 , 0 , 0 , 0.59); border-radius: 5px; color: white; padding: 5px" name=send value="/uno color Blue">Blue</button></td></tr><tr><td style="width: 50%"><button style="width: 100%; background-color: green; border: 2px solid rgba(0 , 0 , 0 , 0.59); border-radius: 5px; padding: 5px" name=send value="/uno color Green">Green</button></td><td style="width: 50%"><button style="width: 100%; background-color: yellow; border: 2px solid rgba(0 , 0 , 0 , 0.59); border-radius: 5px; padding: 5px" name=send value="/uno color Yellow">Yellow</button></td></tr></table>`;
switch (value) {
case "Reverse":
this.direction *= -1;
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|The direction of the game has changed.`);
if (!initialize && this.playerCount === 2)
this.onNextPlayer();
break;
case "Skip":
this.onNextPlayer();
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|${this.playerTable[this.currentPlayerid].name}'s turn has been skipped.`);
break;
case "+2":
this.onNextPlayer();
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|${this.playerTable[this.currentPlayerid].name} has been forced to draw 2 cards.`);
this.onDrawCard(this.playerTable[this.currentPlayerid], 2);
break;
case "+4":
this.playerTable[this.currentPlayerid].sendRoom(colorDisplay);
this.state = "color";
const next = this.getNextPlayer();
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|${this.playerTable[next].name} has been forced to draw 4 cards.`);
this.onDrawCard(this.playerTable[next], 4);
this.isPlusFour = true;
this.timer = setTimeout(() => {
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|${this.playerTable[this.currentPlayerid].name} has been automatically disqualified.`);
this.eliminate(this.currentPlayerid);
}, this.maxTime * 1e3);
break;
case "Wild":
this.playerTable[this.currentPlayerid].sendRoom(colorDisplay);
this.state = "color";
this.timer = setTimeout(() => {
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|${this.playerTable[this.currentPlayerid].name} has been automatically disqualified.`);
this.eliminate(this.currentPlayerid);
}, this.maxTime * 1e3);
break;
}
if (initialize)
this.onNextPlayer();
}
onSelectColor(player, color) {
if (!["Red", "Blue", "Green", "Yellow"].includes(color) || player.id !== this.currentPlayerid || this.state !== "color") {
return false;
}
if (!this.topCard) {
throw new Error(`No top card in the discard pile.`);
}
this.topCard.changedColor = color;
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|The color has been changed to ${color}.`);
if (this.timer)
clearTimeout(this.timer);
player.sendRoom("|uhtmlchange|uno-color|");
player.sendDisplay();
if (this.isPlusFour) {
this.isPlusFour = false;
this.onNextPlayer();
}
this.nextTurn();
}
onDrawCard(player, count) {
if (typeof count === "string")
count = parseInt(count);
if (!count || isNaN(count) || count < 1)
count = 1;
const drawnCards = this.drawCard(count);
player.hand.push(...drawnCards);
player.sendRoom(
`|raw|You have drawn the following card${Chat.plural(drawnCards)}: ${drawnCards.map((card) => `<span style="color: ${textColors[card.color]}">${card.name}</span>`).join(", ")}.`
);
return drawnCards;
}
drawCard(count) {
if (typeof count === "string")
count = parseInt(count);
if (!count || isNaN(count) || count < 1)
count = 1;
const drawnCards = [];
for (let i = 0; i < count; i++) {
if (!this.deck.length) {
this.deck = this.discards.length ? import_lib.Utils.shuffle(this.discards) : import_lib.Utils.shuffle(createDeck());
this.discards = [];
}
drawnCards.push(this.deck[this.deck.length - 1]);
this.deck.pop();
}
return drawnCards;
}
onUno(player, unoId) {
if (this.unoId !== unoId || player.id !== this.awaitUno)
return false;
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|**UNO!** ${player.name} is down to their last card!`);
this.awaitUno = null;
this.unoId = null;
}
onCheckUno() {
if (this.awaitUno) {
if (this.awaitUno !== this.currentPlayerid) {
this.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|${this.playerTable[this.awaitUno].name} forgot to say UNO! and is forced to draw 2 cards.`);
this.onDrawCard(this.playerTable[this.awaitUno], 2);
}
this.awaitUno = null;
this.unoId = null;
}
}
onSendHand(user) {
if (!(user.id in this.playerTable) || this.state === "signups")
return false;
this.playerTable[user.id].sendDisplay();
}
onWin(player) {
this.sendToRoom(
import_lib.Utils.html`|raw|<div class="broadcast-blue">Congratulations to ${player.name} for winning the game of UNO!</div>`,
true
);
this.destroy();
}
destroy() {
if (this.timer)
clearTimeout(this.timer);
if (this.autostartTimer)
clearTimeout(this.autostartTimer);
this.sendToRoom(`|uhtmlchange|uno-${this.gameNumber}|<div class="infobox">The game of UNO has ended.</div>`, true);
for (const i in this.playerTable) {
this.playerTable[i].destroy();
}
this.room.game = null;
}
}
class UNOPlayer extends Rooms.RoomGamePlayer {
constructor(user, game) {
super(user, game);
this.hand = [];
this.cardLock = null;
}
canPlayWildFour() {
if (!this.game.topCard) {
throw new Error(`No top card in the discard pile.`);
}
const color = this.game.topCard.changedColor || this.game.topCard.color;
if (this.hand.some((c) => c.color === color))
return false;
return true;
}
hasCard(cardName) {
return this.hand.find((card) => card.name === cardName);
}
removeCard(cardName) {
for (const [i, card] of this.hand.entries()) {
if (card.name === cardName) {
this.hand.splice(i, 1);
break;
}
}
}
buildHand() {
return import_lib.Utils.sortBy(this.hand, (card) => [card.color, card.value]).map((card, i) => cardHTML(card, i === this.hand.length - 1));
}
sendDisplay() {
const hand = this.buildHand().join("");
const players = `<p><strong>Players (${this.game.playerCount}):</strong></p> ${this.game.getPlayers(true)}`;
const draw = '<button class="button" style="width: 45%; background: rgba(0, 0, 255, 0.05)" name=send value="/uno draw">Draw a card!</button>';
const pass = '<button class="button" style=" width: 45%; background: rgba(255, 0, 0, 0.05)" name=send value="/uno pass">Pass!</button>';
const uno = `<button class="button" style=" width: 90%; background: rgba(0, 255, 0, 0.05); height: 60px; margin-top: 2px;" name=send value="/uno uno ${this.game.unoId || "0"}">UNO!</button>`;
if (!this.game.topCard) {
throw new Error(`No top card in the discard pile.`);
}
const top = `<strong>Top Card: <span style="color: ${textColors[this.game.topCard.changedColor || this.game.topCard.color]}">${this.game.topCard.name}</span></strong>`;
this.sendRoom("|uhtmlchange|uno-hand|");
this.sendRoom(
`|uhtml|uno-hand|<div style="border: 1px solid skyblue; padding: 0 0 5px 0"><table style="width: 100%; table-layout: fixed; border-radius: 3px"><tr><td colspan="4" rowspan="2" style="padding: 5px"><div style="overflow-x: auto; white-space: nowrap; width: 100%">${hand}</div></td>${this.game.currentPlayerid === this.id ? `<td colspan="2" style="padding: 5px 5px 0 5px">${top}</td></tr>` : ""}<tr><td colspan="2" style="vertical-align: top; padding: 0px 5px 5px 5px"><div style="overflow-y: scroll">${players}</div></td></tr></table>${this.game.currentPlayerid === this.id ? `<div style="text-align: center">${draw}${pass}<br />${uno}</div>` : ""}</div>`
);
}
}
const commands = {
uno: {
// roomowner commands
off: "disable",
disable(target, room, user) {
room = this.requireRoom();
this.checkCan("gamemanagement", null, room);
if (room.settings.unoDisabled) {
throw new Chat.ErrorMessage("UNO is already disabled in this room.");
}
room.settings.unoDisabled = true;
room.saveSettings();
return this.sendReply("UNO has been disabled for this room.");
},
on: "enable",
enable(target, room, user) {
room = this.requireRoom();
this.checkCan("gamemanagement", null, room);
if (!room.settings.unoDisabled) {
throw new Chat.ErrorMessage("UNO is already enabled in this room.");
}
delete room.settings.unoDisabled;
room.saveSettings();
return this.sendReply("UNO has been enabled for this room.");
},
// moderation commands
new: "create",
make: "create",
createpublic: "create",
makepublic: "create",
createprivate: "create",
makeprivate: "create",
create(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
if (room.settings.unoDisabled)
throw new Chat.ErrorMessage("UNO is currently disabled for this room.");
if (room.game)
throw new Chat.ErrorMessage("There is already a game in progress in this room.");
const suppressMessages = cmd.includes("private") || !(cmd.includes("public") || room.roomid === "gamecorner");
let cap = parseInt(target);
if (isNaN(cap))
cap = 12;
if (cap < 2)
cap = 2;
room.game = new UNO(room, cap, suppressMessages);
this.privateModAction(`A game of UNO was created by ${user.name}.`);
this.modlog("UNO CREATE");
},
cap: "setcap",
setcap(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
const game = this.requireGame(UNO);
if (game.state !== "signups") {
throw new Chat.ErrorMessage(`There is no UNO game in the signups phase in this room, so adjusting the player cap would do nothing.`);
}
let cap = parseInt(target);
if (isNaN(cap) || cap < 2) {
cap = 2;
}
game.playerCap = cap;
this.privateModAction(`The playercap was set to ${game.playerCap} by ${user.name}.`);
this.modlog("UNO PLAYERCAP");
},
start(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
const game = this.requireGame(UNO);
if (game.state !== "signups") {
throw new Chat.ErrorMessage("There is no UNO game in signups phase in this room.");
}
game.onStart();
this.privateModAction(`The game of UNO was started by ${user.name}.`);
this.modlog("UNO START");
},
stop: "end",
end(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
if (!room.game || room.game.gameid !== "uno") {
throw new Chat.ErrorMessage("There is no UNO game going on in this room.");
}
room.game.destroy();
room.add("The game of UNO was forcibly ended.").update();
this.privateModAction(`The game of UNO was ended by ${user.name}.`);
this.modlog("UNO END");
},
autodq: "timer",
timer(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
const game = this.requireGame(UNO);
const amount = parseInt(target);
if (!amount || amount < 5 || amount > 300) {
throw new Chat.ErrorMessage("The amount must be a number between 5 and 300.");
}
game.maxTime = amount;
if (game.timer)
clearTimeout(game.timer);
game.timer = setTimeout(() => {
game.eliminate(game.currentPlayerid);
}, amount * 1e3);
this.addModAction(`${user.name} has set the UNO automatic disqualification timer to ${amount} seconds.`);
this.modlog("UNO TIMER", null, `${amount} seconds`);
},
autostart(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
const game = this.requireGame(UNO);
if (toID(target) === "off") {
if (!game.autostartTimer)
throw new Chat.ErrorMessage("There is no autostart timer running on.");
this.addModAction(`${user.name} has turned off the UNO autostart timer.`);
clearTimeout(game.autostartTimer);
return;
}
const amount = parseInt(target);
if (!amount || amount < 30 || amount > 600) {
throw new Chat.ErrorMessage("The amount must be a number between 30 and 600 seconds.");
}
if (game.state !== "signups")
throw new Chat.ErrorMessage("The game of UNO has already started.");
if (game.autostartTimer)
clearTimeout(game.autostartTimer);
game.autostartTimer = setTimeout(() => {
game.onStart(true);
}, amount * 1e3);
this.addModAction(`${user.name} has set the UNO autostart timer to ${amount} seconds.`);
},
dq: "disqualify",
disqualify(target, room, user) {
room = this.requireRoom();
this.checkCan("minigame", null, room);
const game = this.requireGame(UNO);
const disqualified = game.eliminate(toID(target));
if (disqualified === false)
throw new Chat.ErrorMessage(`Unable to disqualify ${target}.`);
this.privateModAction(`${user.name} has disqualified ${disqualified} from the UNO game.`);
this.modlog("UNO DQ", toID(target));
room.add(`${disqualified} has been disqualified from the UNO game.`).update();
},
// player/user commands
j: "join",
join(target, room, user) {
const game = this.requireGame(UNO);
this.checkChat();
if (!game.joinGame(user))
throw new Chat.ErrorMessage("Unable to join the game.");
return this.sendReply("You have joined the game of UNO.");
},
l: "leave",
leave(target, room, user) {
const game = this.requireGame(UNO);
if (!game.leaveGame(user))
throw new Chat.ErrorMessage("Unable to leave the game.");
return this.sendReply("You have left the game of UNO.");
},
play(target, room, user) {
const game = this.requireGame(UNO);
if (!game)
throw new Chat.ErrorMessage("There is no UNO game going on in this room right now.");
const player = game.playerTable[user.id];
if (!player)
throw new Chat.ErrorMessage(`You are not in the game of UNO.`);
const error = game.onPlay(player, target);
if (typeof error === "string")
throw new Chat.ErrorMessage(error);
},
draw(target, room, user) {
room = this.requireRoom();
const game = room.getGame(UNO);
if (!game)
throw new Chat.ErrorMessage("There is no UNO game going on in this room right now.");
const player = game.playerTable[user.id];
if (!player)
throw new Chat.ErrorMessage(`You are not in the game of UNO.`);
const error = game.onDraw(player);
if (error)
throw new Chat.ErrorMessage("You have already drawn a card this turn.");
},
pass(target, room, user) {
const game = this.requireGame(UNO);
if (!game)
throw new Chat.ErrorMessage("There is no UNO game going on in this room right now.");
if (game.currentPlayerid !== user.id)
throw new Chat.ErrorMessage("It is currently not your turn.");
const player = game.playerTable[user.id];
if (!player)
throw new Chat.ErrorMessage(`You are not in the game of UNO.`);
if (!player.cardLock)
throw new Chat.ErrorMessage("You cannot pass until you draw a card.");
if (game.state === "color")
throw new Chat.ErrorMessage("You cannot pass until you choose a color.");
game.sendToRoom(`|c:|${Math.floor(Date.now() / 1e3)}|&|${user.name} has passed.`);
game.nextTurn();
},
color(target, room, user) {
const game = this.requireGame(UNO);
const player = game.playerTable[user.id];
if (!player)
throw new Chat.ErrorMessage(`You are not in the game of UNO.`);
let color;
if (target === "Red" || target === "Green" || target === "Blue" || target === "Yellow" || target === "Black") {
color = target;
} else {
throw new Chat.ErrorMessage(`"${target}" is not a valid color.`);
}
game.onSelectColor(player, color);
},
uno(target, room, user) {
const game = this.requireGame(UNO);
const player = game.playerTable[user.id];
if (!player)
throw new Chat.ErrorMessage(`You are not in the game of UNO.`);
game.onUno(player, toID(target));
},
// information commands
"": "hand",
hand(target, room, user) {
const game = this.requireGame(UNO);
game.onSendHand(user);
},
"c": "cards",
cards(target, room, user) {
const game = this.requireGame(UNO);
if (!this.runBroadcast())
return false;
const players = `<strong>Players (${game.playerCount}):</strong></p>${game.getPlayers(true)}`;
this.sendReplyBox(`<tr><td colspan="2" style="vertical-align: top; padding: 0px 5px 5px 5px"><div style="overflow-y: scroll">${players}</div></td></tr></table>`);
},
players: "getusers",
users: "getusers",
getplayers: "getusers",
getusers(target, room, user) {
const game = this.requireGame(UNO);
if (!this.runBroadcast())
return false;
this.sendReplyBox(`<strong>Players (${game.playerCount})</strong>:${game.getPlayers()}`);
},
help(target, room, user) {
this.parse("/help uno");
},
// suppression commands
suppress(target, room, user) {
room = this.requireRoom();
const game = this.requireGame(UNO);
this.checkCan("minigame", null, room);
target = toID(target);
const state = target === "on" ? true : target === "off" ? false : void 0;
if (state === void 0) {
return this.sendReply(`Suppression of UNO game messages is currently ${game.suppressMessages ? "on" : "off"}.`);
}
if (state === game.suppressMessages) {
throw new Chat.ErrorMessage(`Suppression of UNO game messages is already ${game.suppressMessages ? "on" : "off"}.`);
}
game.suppressMessages = state;
this.addModAction(`${user.name} has turned ${state ? "on" : "off"} suppression of UNO game messages.`);
this.modlog("UNO SUPRESS", null, state ? "ON" : "OFF");
},
spectate(target, room, user) {
const game = this.requireGame(UNO);
if (!game)
throw new Chat.ErrorMessage("There is no UNO game going on in this room right now.");
if (!game.suppressMessages)
throw new Chat.ErrorMessage("The current UNO game is not suppressing messages.");
if (user.id in game.spectators)
throw new Chat.ErrorMessage("You are already spectating this game.");
game.spectators[user.id] = 1;
this.sendReply("You are now spectating this private UNO game.");
},
unspectate(target, room, user) {
const game = this.requireGame(UNO);
if (!game)
throw new Chat.ErrorMessage("There is no UNO game going on in this room right now.");
if (!game.suppressMessages)
throw new Chat.ErrorMessage("The current UNO game is not suppressing messages.");
if (!(user.id in game.spectators))
throw new Chat.ErrorMessage("You are currently not spectating this game.");
delete game.spectators[user.id];
this.sendReply("You are no longer spectating this private UNO game.");
}
},
unohelp: [
`/uno create [player cap] - creates a new UNO game with an optional player cap (default player cap at 12). Use the command [createpublic] to force a public game or [createprivate] to force a private game. Requires: % @ # &`,
`/uno setcap [player cap] - adjusts the player cap of the current UNO game. Requires: % @ # &`,
`/uno timer [amount] - sets an auto disqualification timer for [amount] seconds. Requires: % @ # &`,
`/uno autostart [amount] - sets an auto starting timer for [amount] seconds. Requires: % @ # &`,
`/uno end - ends the current game of UNO. Requires: % @ # &`,
`/uno start - starts the current game of UNO. Requires: % @ # &`,
`/uno disqualify [player] - disqualifies the player from the game. Requires: % @ # &`,
`/uno hand - displays your own hand.`,
`/uno cards - displays the number of cards for each player.`,
`/uno getusers - displays the players still in the game.`,
`/uno [spectate|unspectate] - spectate / unspectate the current private UNO game.`,
`/uno suppress [on|off] - Toggles suppression of game messages.`
]
};
const roomSettings = (room) => ({
label: "UNO",
permission: "editroom",
options: [
[`disabled`, room.settings.unoDisabled || "uno disable"],
[`enabled`, !room.settings.unoDisabled || "uno enable"]
]
});
//# sourceMappingURL=uno.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/uno.ts"],
"sourcesContent": ["/**\r\n * UNO\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * This plugin allows rooms to run games of scripted UNO\r\n *\r\n * @license MIT license\r\n */\r\nimport {Utils} from '../../lib';\r\n\r\ntype Color = 'Green' | 'Yellow' | 'Red' | 'Blue' | 'Black';\r\ninterface Card {\r\n\tvalue: string;\r\n\tcolor: Color;\r\n\tchangedColor?: Color;\r\n\tname: string;\r\n}\r\n\r\nconst maxTime = 60; // seconds\r\n\r\nconst rgbGradients: {[k in Color]: string} = {\r\n\tGreen: \"rgba(0, 122, 0, 1), rgba(0, 185, 0, 0.9)\",\r\n\tYellow: \"rgba(255, 225, 0, 1), rgba(255, 255, 85, 0.9)\",\r\n\tBlue: \"rgba(40, 40, 255, 1), rgba(125, 125, 255, 0.9)\",\r\n\tRed: \"rgba(255, 0, 0, 1), rgba(255, 125, 125, 0.9)\",\r\n\tBlack: \"rgba(0, 0, 0, 1), rgba(0, 0, 0, 0.55)\",\r\n};\r\n\r\nconst textColors: {[k in Color]: string} = {\r\n\tGreen: \"rgb(0, 128, 0)\",\r\n\tYellow: \"rgb(175, 165, 40)\",\r\n\tBlue: \"rgb(75, 75, 255)\",\r\n\tRed: \"rgb(255, 0, 0)\",\r\n\tBlack: 'inherit',\r\n};\r\n\r\nconst textShadow = 'text-shadow: 1px 0px black, -1px 0px black, 0px -1px black, 0px 1px black, 2px -2px black;';\r\n\r\nfunction cardHTML(card: Card, fullsize: boolean) {\r\n\tlet surface = card.value.replace(/[^A-Z0-9+]/g, \"\");\r\n\tconst background = rgbGradients[card.color];\r\n\tif (surface === 'R') surface = '<i class=\"fa fa-refresh\" aria-hidden=\"true\"></i>';\r\n\r\n\treturn `<button class=\"button\" style=\"font-size: 14px; font-weight: bold; color: white; ${textShadow} padding-bottom: 117px; text-align: left; height: 135px; width: ${fullsize ? '72' : '37'}px; border-radius: 10px 2px 2px 3px; color: white; background: ${card.color}; background: -webkit-linear-gradient(${background}); background: -o-linear-gradient(${background}); background: -moz-linear-gradient(${background}); background: linear-gradient(${background})\" name=send value=\"/uno play ${card.name}\" aria-label=\"${card.name}\">${surface}</button>`;\r\n}\r\n\r\nfunction createDeck() {\r\n\tconst colors: Color[] = ['Red', 'Blue', 'Green', 'Yellow'];\r\n\tconst values = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'Reverse', 'Skip', '+2'];\r\n\r\n\tconst basic: Card[] = [];\r\n\r\n\tfor (const color of colors) {\r\n\t\tbasic.push(...values.map(v => {\r\n\t\t\tconst c: Card = {value: v, color: color, name: `${color} ${v}`};\r\n\t\t\treturn c;\r\n\t\t}));\r\n\t}\r\n\r\n\treturn [\r\n\t\t// two copies of the basic stuff (total 96)\r\n\t\t...basic,\r\n\t\t...basic,\r\n\t\t// The four 0s\r\n\t\t...[0, 1, 2, 3].map(v => {\r\n\t\t\tconst c: Card = {color: colors[v], value: '0', name: `${colors[v]} 0`};\r\n\t\t\treturn c;\r\n\t\t}),\r\n\t\t // Wild cards\r\n\t\t...[0, 1, 2, 3].map(v => {\r\n\t\t\tconst c: Card = {color: 'Black', value: 'Wild', name: 'Wild'};\r\n\t\t\treturn c;\r\n\t\t}),\r\n\t\t// Wild +4 cards\r\n\t\t...[0, 1, 2, 3].map(v => {\r\n\t\t\tconst c: Card = {color: 'Black', value: '+4', name: 'Wild +4'};\r\n\t\t\treturn c;\r\n\t\t}),\r\n\t]; // 108 cards\r\n}\r\n\r\nexport class UNO extends Rooms.RoomGame<UNOPlayer> {\r\n\tplayerCap: number;\r\n\tallowRenames: boolean;\r\n\tmaxTime: number;\r\n\ttimer: NodeJS.Timer | null;\r\n\tautostartTimer: NodeJS.Timer | null;\r\n\tstate: string;\r\n\tcurrentPlayerid: ID;\r\n\tdeck: Card[];\r\n\tdiscards: Card[];\r\n\ttopCard: Card | null;\r\n\tawaitUno: string | null;\r\n\tunoId: ID | null;\r\n\tdirection: number;\r\n\tsuppressMessages: boolean;\r\n\tspectators: {[k: string]: number};\r\n\tisPlusFour: boolean;\r\n\tgameNumber: number;\r\n\r\n\tconstructor(room: Room, cap: number, suppressMessages: boolean) {\r\n\t\tsuper(room);\r\n\r\n\t\tthis.gameNumber = room.nextGameNumber();\r\n\r\n\t\tthis.playerCap = cap;\r\n\t\tthis.allowRenames = true;\r\n\t\tthis.maxTime = maxTime;\r\n\t\tthis.timer = null;\r\n\t\tthis.autostartTimer = null;\r\n\r\n\t\tthis.gameid = 'uno' as ID;\r\n\t\tthis.title = 'UNO';\r\n\r\n\t\tthis.state = 'signups';\r\n\t\tthis.currentPlayerid = '';\r\n\t\tthis.deck = Utils.shuffle(createDeck());\r\n\t\tthis.discards = [];\r\n\t\tthis.topCard = null;\r\n\t\tthis.awaitUno = null;\r\n\t\tthis.unoId = null;\r\n\t\tthis.isPlusFour = false;\r\n\r\n\t\tthis.direction = 1;\r\n\r\n\t\tthis.suppressMessages = suppressMessages || false;\r\n\t\tthis.spectators = Object.create(null);\r\n\r\n\t\tthis.sendToRoom(`|uhtml|uno-${this.gameNumber}|<div class=\"broadcast-blue\"><p style=\"font-size: 14pt; text-align: center\">A new game of <strong>UNO</strong> is starting!</p><p style=\"font-size: 9pt; text-align: center\"><button class=\"button\" name=\"send\" value=\"/uno join\"><strong>Join and play</strong></button> <button class=\"button\" name=\"send\" value=\"/uno spectate\">Watch</button></p>${this.suppressMessages ? `<p style=\"font-size: 6pt; text-align: center\">Game messages won't show up unless you're playing or watching.</p>` : ''}</div>`, true);\r\n\t}\r\n\r\n\tonUpdateConnection() {}\r\n\r\n\tonConnect(user: User, connection: Connection) {\r\n\t\tif (this.state === 'signupLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,iBAAoB;AARpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,MAAM,UAAU;AAEhB,MAAM,eAAuC;AAAA,EAC5C,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,KAAK;AAAA,EACL,OAAO;AACR;AAEA,MAAM,aAAqC;AAAA,EAC1C,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,KAAK;AAAA,EACL,OAAO;AACR;AAEA,MAAM,aAAa;AAEnB,SAAS,SAAS,MAAY,UAAmB;AAChD,MAAI,UAAU,KAAK,MAAM,QAAQ,eAAe,EAAE;AAClD,QAAM,aAAa,aAAa,KAAK,KAAK;AAC1C,MAAI,YAAY;AAAK,cAAU;AAE/B,SAAO,mFAAmF,6EAA6E,WAAW,OAAO,sEAAsE,KAAK,8CAA8C,+CAA+C,iDAAiD,4CAA4C,2CAA2C,KAAK,qBAAqB,KAAK,SAAS;AAClhB;AAEA,SAAS,aAAa;AACrB,QAAM,SAAkB,CAAC,OAAO,QAAQ,SAAS,QAAQ;AACzD,QAAM,SAAS,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,WAAW,QAAQ,IAAI;AAEpF,QAAM,QAAgB,CAAC;AAEvB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ChC,YAAI,KAAK,KAAK;AAAa;AAC3B,cAAM,OAAO,MAAM,SAAS,CAAC;AAC7B,YAAI;AAAM,eAAK,OLine truncated
"names": []
}
@@ -0,0 +1,142 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var username_prefixes_exports = {};
__export(username_prefixes_exports, {
PrefixManager: () => PrefixManager,
commands: () => commands,
prefixManager: () => prefixManager
});
module.exports = __toCommonJS(username_prefixes_exports);
var import_lib = require("../../lib");
const PREFIXES_FILE = "config/chat-plugins/username-prefixes.json";
const PREFIX_DURATION = 10 * 24 * 60 * 60 * 1e3;
class PrefixManager {
constructor() {
if (!Chat.oldPlugins["username-prefixes"])
this.refreshConfig(true);
}
save() {
(0, import_lib.FS)(PREFIXES_FILE).writeUpdate(() => JSON.stringify(Config.forcedprefixes || []));
}
refreshConfig(configJustLoaded = false) {
if (!Config.forcedprefixes)
Config.forcedprefixes = [];
if (!Array.isArray(Config.forcedprefixes)) {
const convertedPrefixes = [];
for (const type in Config.forcedprefixes) {
for (const prefix of Config.forcedprefixes[type].map(toID)) {
convertedPrefixes.push({ type, prefix, expireAt: Date.now() + PREFIX_DURATION });
}
}
Config.forcedprefixes = convertedPrefixes;
}
if (configJustLoaded) {
for (const entry of Config.forcedprefixes) {
entry.prefix = toID(entry.prefix);
}
}
let data;
try {
data = JSON.parse((0, import_lib.FS)(PREFIXES_FILE).readSync());
} catch (e) {
if (e.code !== "ENOENT")
throw e;
return;
}
if (data.length) {
for (const entry of data) {
if (Config.forcedprefixes.includes(entry))
continue;
Config.forcedprefixes.push(entry);
}
}
}
addPrefix(prefix, type) {
if (!Config.forcedprefixes)
Config.forcedprefixes = [];
const entry = Config.forcedprefixes.find((x) => x.prefix === prefix && x.type === type);
if (entry) {
throw new Chat.ErrorMessage(`Username prefix '${prefix}' is already configured to force ${type}.`);
}
Config.forcedprefixes.push({ type, prefix, expireAt: Date.now() + PREFIX_DURATION });
this.save();
}
removePrefix(prefix, type) {
const entry = Config.forcedprefixes.findIndex((x) => x.prefix === prefix && x.type === type);
if (entry < 0) {
throw new Chat.ErrorMessage(`Username prefix '${prefix}' is not configured to force ${type}!`);
}
Config.forcedprefixes.splice(entry, 1);
this.save();
}
validateType(type) {
if (type !== "privacy" && type !== "modchat") {
throw new Chat.ErrorMessage(`'${type}' is not a valid type of forced prefix. Valid types are 'privacy' and 'modchat'.`);
}
return type;
}
}
const prefixManager = new PrefixManager();
const commands = {
forceprefix: "usernameprefix",
forcedprefix: "usernameprefix",
forcedprefixes: "usernameprefix",
usernameprefixes: "usernameprefix",
usernameprefix: {
help: "",
""() {
this.parse(`/help forcedprefix`);
},
delete: "add",
remove: "add",
add(target, room, user, connection, cmd) {
this.checkCan("addhtml");
const isAdding = cmd.includes("add");
const [prefix, type] = target.split(",").map(toID);
if (!prefix || !type)
return this.parse(`/help usernameprefix`);
if (prefix.length > 18) {
throw new Chat.ErrorMessage(`Specified prefix '${prefix}' is longer than the maximum user ID length.`);
}
if (isAdding) {
prefixManager.addPrefix(prefix, prefixManager.validateType(type));
} else {
prefixManager.removePrefix(prefix, prefixManager.validateType(type));
}
this.globalModlog(`FORCEDPREFIX ${isAdding ? "ADD" : "REMOVE"}`, null, `'${prefix}' ${isAdding ? "to" : "from"} ${type}`);
this.addGlobalModAction(`${user.name} set the username prefix ${prefix} to${isAdding ? "" : " no longer"} disable ${type}.`);
},
view(target) {
this.checkCan("addhtml");
const types = target ? [prefixManager.validateType(toID(target))] : ["privacy", "modchat"];
const entries = Config.forcedprefixes.filter((x) => types.includes(x.type));
return this.sendReplyBox(types.map((type) => {
const prefixes = entries.filter((x) => x.type === type).map((x) => x.prefix);
const info = prefixes.length ? `<code>${prefixes.join("</code>, <code>")}</code>` : `none`;
return `Username prefixes that disable <strong>${type}</strong>: ${info}.`;
}).join(`<br />`));
}
},
usernameprefixhelp() {
return this.sendReplyBox(
`<code>/usernameprefix add [prefix], [type]</code>: Sets the username prefix [prefix] to disable privacy or modchat on battles where at least one player has the prefix.<br /><code>/usernameprefix remove [prefix], [type]</code>: Removes a prefix configuration.<br /><code>/usernameprefix view [optional type]</code>: Displays the currently configured username prefixes.<br />Valid types are <code>privacy</code> (which forces battles to take place in public rooms) and <code>modchat</code> (which prevents players from setting moderated chat).<br />Requires: * &`
);
}
};
//# sourceMappingURL=username-prefixes.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/username-prefixes.ts"],
"sourcesContent": ["/**\r\n * Code to manage username prefixes that force battles to be public or disable modchat.\r\n * @author Annika\r\n */\r\n\r\nimport {FS} from '../../lib';\r\n\r\nconst PREFIXES_FILE = 'config/chat-plugins/username-prefixes.json';\r\nconst PREFIX_DURATION = 10 * 24 * 60 * 60 * 1000;\r\n\r\nexport class PrefixManager {\r\n\tconstructor() {\r\n\t\t// after a restart/newly using the plugin, load prefixes from config.js\r\n\t\tif (!Chat.oldPlugins['username-prefixes']) this.refreshConfig(true);\r\n\t}\r\n\r\n\tsave() {\r\n\t\tFS(PREFIXES_FILE).writeUpdate(() => JSON.stringify(Config.forcedprefixes || []));\r\n\t}\r\n\r\n\trefreshConfig(configJustLoaded = false) {\r\n\t\tif (!Config.forcedprefixes) Config.forcedprefixes = [];\r\n\t\t// ensure everything is in the right format\r\n\t\tif (!Array.isArray(Config.forcedprefixes)) {\r\n\t\t\tconst convertedPrefixes = [];\r\n\t\t\tfor (const type in Config.forcedprefixes) {\r\n\t\t\t\tfor (const prefix of Config.forcedprefixes[type].map(toID)) {\r\n\t\t\t\t\tconvertedPrefixes.push({type, prefix, expireAt: Date.now() + PREFIX_DURATION});\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tConfig.forcedprefixes = convertedPrefixes;\r\n\t\t}\r\n\t\tif (configJustLoaded) {\r\n\t\t\tfor (const entry of Config.forcedprefixes) {\r\n\t\t\t\tentry.prefix = toID(entry.prefix);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tlet data: AnyObject[];\r\n\t\ttry {\r\n\t\t\tdata = JSON.parse(FS(PREFIXES_FILE).readSync());\r\n\t\t} catch (e: any) {\r\n\t\t\tif (e.code !== 'ENOENT') throw e;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (data.length) {\r\n\t\t\tfor (const entry of data) {\r\n\t\t\t\tif (Config.forcedprefixes.includes(entry)) continue;\r\n\t\t\t\tConfig.forcedprefixes.push(entry);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\taddPrefix(prefix: ID, type: 'privacy' | 'modchat') {\r\n\t\tif (!Config.forcedprefixes) Config.forcedprefixes = [];\r\n\t\tconst entry = Config.forcedprefixes.find((x: AnyObject) => x.prefix === prefix && x.type === type);\r\n\t\tif (entry) {\r\n\t\t\tthrow new Chat.ErrorMessage(`Username prefix '${prefix}' is already configured to force ${type}.`);\r\n\t\t}\r\n\r\n\t\tConfig.forcedprefixes.push({type, prefix, expireAt: Date.now() + PREFIX_DURATION});\r\n\t\tthis.save();\r\n\t}\r\n\r\n\tremovePrefix(prefix: ID, type: 'privacy' | 'modchat') {\r\n\t\tconst entry = Config.forcedprefixes.findIndex((x: AnyObject) => x.prefix === prefix && x.type === type);\r\n\t\tif (entry < 0) {\r\n\t\t\tthrow new Chat.ErrorMessage(`Username prefix '${prefix}' is not configured to force ${type}!`);\r\n\t\t}\r\n\r\n\t\tConfig.forcedprefixes.splice(entry, 1);\r\n\t\tthis.save();\r\n\t}\r\n\r\n\tvalidateType(type: string) {\r\n\t\tif (type !== 'privacy' && type !== 'modchat') {\r\n\t\t\tthrow new Chat.ErrorMessage(`'${type}' is not a valid type of forced prefix. Valid types are 'privacy' and 'modchat'.`);\r\n\t\t}\r\n\t\treturn type;\r\n\t}\r\n}\r\n\r\nexport const prefixManager = new PrefixManager();\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tforceprefix: 'usernameprefix',\r\n\tforcedprefix: 'usernameprefix',\r\n\tforcedprefixes: 'usernameprefix',\r\n\tusernameprefixes: 'usernameprefix',\r\n\tusernameprefix: {\r\n\t\thelp: '',\r\n\t\t''() {\r\n\t\t\tthis.parse(`/help forcedprefix`);\r\n\t\t},\r\n\r\n\t\tdelete: 'add',\r\n\t\tremove: 'add',\r\n\t\tadd(target, room, user, connection, cmd) {\r\n\t\t\tthis.checkCan('addhtml');\r\n\r\n\t\t\tconst isAdding = cmd.includes('add');\r\n\r\n\t\t\tconst [prefix, type] = target.split(',').map(toID);\r\n\t\t\tif (!prefix || !type) return this.parse(`/help usernameprefix`);\r\n\t\t\tif (prefix.length > 18) {\r\n\t\t\t\tthrow new Chat.ErrorMessage(`Specified prefix '${prefix}' is longer than the maximum user ID length.`);\r\n\t\t\t}\r\n\r\n\t\t\tif (isAdding) {\r\n\t\t\t\tprefixManager.addPrefix(prefix, prefixManager.validateType(type));\r\n\t\t\t} else {\r\n\t\t\t\tprefixManager.removePrefix(prefix, prefixManager.validateType(type));\r\n\t\t\t}\r\n\r\n\t\t\tthis.globalModlog(`FORCEDPREFIX ${isAdding ? 'ADD' : 'REMOVE'}`, null, `'${prefix}' ${isAdding ? 'to' : 'from'} ${type}`);\r\n\t\t\tthis.addGlobalModAction(`${user.name} set the username prefix ${prefix} to${isAdding ? '' : ' no longer'} disable ${type}.`);\r\n\t\t},\r\n\r\n\t\tview(target) {\r\n\t\t\tthis.checkCan('addhtml');\r\n\r\n\t\t\tconst types = target ? [prefixManager.validateType(toID(target))] : ['privacy', 'modchat'];\r\n\r\n\t\t\tconst entries = Config.forcedprefixes.filter((x: any) => types.includes(x.type));\r\n\r\n\t\t\treturn this.sendReplyBox(types.map(type => {\r\n\t\t\t\tconst prefixes = entries.filter((x: any) => x.type === type).map((x: any) => x.prefix);\r\n\t\t\t\tconst info = prefixes.length ?\r\n\t\t\t\t\t`<code>${prefixes.join('</code>, <code>')}</code>` : `none`;\r\n\t\t\t\treturn `Username prefixes that disable <strong>${type}</strong>: ${info}.`;\r\n\t\t\t}).join(`<br />`));\r\n\t\t},\r\n\t},\r\n\tusernameprefixhelp() {\r\n\t\treturn this.sendReplyBox(\r\n\t\t\t`<code>Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,iBAAiB;AAEjB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB,KAAK,KAAK,KAAK,KAAK;AAErC,MAAM,cAAc;AAAA,EAC1B,cAAc;AAEb,QAAI,CAAC,KAAK,WAAW,mBAAmB;AAAG,WAAK,cAAc,IAAI;AAAA,EACnE;AAAA,EAEA,OAAO;AACN,uBAAG,aAAa,EAAE,YAAY,MAAM,KAAK,UAAU,OAAO,kBAAkB,CAAC,CAAC,CAAC;AAAA,EAChF;AAAA,EAEA,cAAc,mBAAmB,OAAO;AACvC,QAAI,CAAC,OAAO;AAAgB,aAAO,iBAAiB,CAAC;AAErD,QAAI,CAAC,MAAM,QAAQ,OAAO,cAAc,GAAG;AAC1C,YAAM,oBAAoB,CAAC;AAC3B,iBAAW,QAAQ,OAAO,gBAAgB;AACzC,mBAAW,UAAU,OAAO,eAAe,IAAI,EAAE,IAAI,IAAI,GAAG;AAC3D,4BAAkB,KAAK,EAAC,MAAM,QAAQ,UAAU,KAAK,IAAI,IAAI,gBAAe,CAAC;AAAA,QAC9E;AAAA,MACD;AACA,aAAO,iBAAiB;AAAA,IACzB;AACA,QAAI,kBAAkB;AACrB,iBAAW,SAAS,OAAO,gBAAgB;AA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,SAAS,KAAK,iBAAiB,aAAa;AACtD,eAAO,0CAA0C,kBAAkB;AAAA,MACpE,CAAC,EAAE,KAAK,QAAQ,CAAC;AAAA,IAClB;AAAA,EACD;AAAA,EACA,qBAAqB;AACpB,WAAO,KAAK;AAAA,MACX;AAAA,IAKD;AAAA,EACD;AACD;",
"names": []
}
+217
View File
@@ -0,0 +1,217 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var usersearch_exports = {};
__export(usersearch_exports, {
commands: () => commands,
nameList: () => nameList,
pages: () => pages
});
module.exports = __toCommonJS(usersearch_exports);
var import_lib = require("../../lib");
const nameList = new Set(JSON.parse(
(0, import_lib.FS)("config/chat-plugins/usersearch.json").readIfExistsSync() || "[]"
));
const ONLINE_SYMBOL = ` \u25C9 `;
const OFFLINE_SYMBOL = ` \u25CC `;
class PunishmentHTML extends Chat.JSX.Component {
render() {
const { userid, target } = { ...this.props };
const buf = [];
for (const cmdName of ["Forcerename", "Namelock", "Weeknamelock"]) {
buf.push(/* @__PURE__ */ Chat.h("span", { dangerouslySetInnerHTML: {
__html: `<button class="button" name="send" value="/msgroom staff,/${toID(cmdName)} ${userid}&#10;/uspage ${target}">${cmdName}</button>`
} }));
}
return buf;
}
}
class SearchUsernames extends Chat.JSX.Component {
render() {
const { target, page } = { ...this.props };
const results = {
offline: [],
online: []
};
for (const curUser of Users.users.values()) {
if (!curUser.id.includes(target) || curUser.id.startsWith("guest"))
continue;
if (Punishments.isGlobalBanned(curUser))
continue;
if (curUser.connected) {
results.online.push(`${!page ? ONLINE_SYMBOL : ""} ${curUser.name}`);
} else {
results.offline.push(`${!page ? OFFLINE_SYMBOL : ""} ${curUser.name}`);
}
}
for (const k in results) {
import_lib.Utils.sortBy(results[k], (result) => toID(result));
}
if (!page) {
return /* @__PURE__ */ Chat.h(Chat.Fragment, null, "Users with a name matching '", target, "':", /* @__PURE__ */ Chat.h("br", null), !results.offline.length && !results.online.length ? /* @__PURE__ */ Chat.h(Chat.Fragment, null, "No users found.") : /* @__PURE__ */ Chat.h(Chat.Fragment, null, results.online.join("; "), !!results.offline.length && /* @__PURE__ */ Chat.h(Chat.Fragment, null, !!results.online.length && /* @__PURE__ */ Chat.h(Chat.Fragment, null, /* @__PURE__ */ Chat.h("br", null), /* @__PURE__ */ Chat.h("br", null)), results.offline.join("; "))));
}
return /* @__PURE__ */ Chat.h("div", { class: "pad" }, /* @__PURE__ */ Chat.h("h2", null, 'Usernames containing "', target, '"'), !results.online.length && !results.offline.length ? /* @__PURE__ */ Chat.h("p", null, "No results found.") : /* @__PURE__ */ Chat.h(Chat.Fragment, null, !!results.online.length && /* @__PURE__ */ Chat.h("div", { class: "ladder pad" }, /* @__PURE__ */ Chat.h("h3", null, "Online users"), /* @__PURE__ */ Chat.h("table", null, /* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("th", null, "Username"), /* @__PURE__ */ Chat.h("th", null, "Punish")), (() => {
const online = [];
for (const username of results.online) {
online.push(/* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("td", null, /* @__PURE__ */ Chat.h("username", null, username)), /* @__PURE__ */ Chat.h("td", null, /* @__PURE__ */ Chat.h(PunishmentHTML, { userid: toID(username), target }))));
}
return online;
})())), !!(results.online.length && results.offline.length) && /* @__PURE__ */ Chat.h("hr", null), !!results.offline.length && /* @__PURE__ */ Chat.h("div", { class: "ladder pad" }, /* @__PURE__ */ Chat.h("h3", null, "Offline users"), /* @__PURE__ */ Chat.h("table", null, /* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("th", null, "Username"), /* @__PURE__ */ Chat.h("th", null, "Punish")), (() => {
const offline = [];
for (const username of results.offline) {
offline.push(/* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("td", null, /* @__PURE__ */ Chat.h("username", null, username)), /* @__PURE__ */ Chat.h("td", null, /* @__PURE__ */ Chat.h(PunishmentHTML, { userid: toID(username), target }))));
}
return offline;
})()))));
}
}
function saveNames() {
(0, import_lib.FS)("config/chat-plugins/usersearch.json").writeUpdate(() => JSON.stringify([...nameList]));
}
const commands = {
us: "usersearch",
uspage: "usersearch",
usersearchpage: "usersearch",
usersearch(target, room, user, connection, cmd) {
this.checkCan("lock");
target = toID(target);
if (!target) {
if (cmd.includes("page"))
return this.parse(`/j view-usersearch`);
return this.parse(`/help usersearch`);
}
if (target.length < 3) {
throw new Chat.ErrorMessage(`That's too short of a term to search for.`);
}
const showPage = cmd.includes("page");
if (showPage) {
this.parse(`/j view-usersearch-${target}`);
return;
}
return this.sendReplyBox(/* @__PURE__ */ Chat.h(SearchUsernames, { target }));
},
usersearchhelp: [
`/usersearch [pattern]: Looks for all names matching the [pattern]. Requires: % @ &`,
`Adding "page" to the end of the command, i.e. /usersearchpage OR /uspage will bring up a page.`,
`See also /usnames for a staff-curated list of the most commonly searched terms.`
],
usnames: "usersearchnames",
usersearchnames: {
"": "list",
list() {
this.parse(`/join view-usersearch`);
},
add(target, room, user) {
this.checkCan("lock");
const targets = target.split(",").map(toID).filter(Boolean);
if (!targets.length) {
return this.errorReply(`Specify at least one term.`);
}
for (const [i, arg] of targets.entries()) {
if (nameList.has(arg)) {
targets.splice(i, 1);
this.errorReply(`Term ${arg} is already on the usersearch term list.`);
continue;
}
if (arg.length < 3) {
targets.splice(i, 1);
this.errorReply(`Term ${arg} is too short for the usersearch term list. Must be more than 3 characters.`);
continue;
}
nameList.add(arg);
}
if (!targets.length) {
return this.errorReply(`No terms could be added.`);
}
const count = Chat.count(targets, "terms");
Rooms.get("staff")?.addByUser(
user,
`${user.name} added the ${count} "${targets.join(", ")}" to the usersearch name list.`
);
this.globalModlog(`USERSEARCH ADD`, null, targets.join(", "));
if (!room || room.roomid !== "staff") {
this.sendReply(`You added the ${count} "${targets.join(", ")}" to the usersearch name list.`);
}
saveNames();
},
remove(target, room, user) {
this.checkCan("lock");
const targets = target.split(",").map(toID).filter(Boolean);
if (!targets.length) {
return this.errorReply(`Specify at least one term.`);
}
for (const [i, arg] of targets.entries()) {
if (!nameList.has(arg)) {
targets.splice(i, 1);
this.errorReply(`${arg} is not in the usersearch name list, and has been skipped.`);
continue;
}
nameList.delete(arg);
}
if (!targets.length) {
return this.errorReply(`No terms could be removed.`);
}
const count = Chat.count(targets, "terms");
Rooms.get("staff")?.addByUser(
user,
`${user.name} removed the ${count} "${targets.join(", ")}" from the usersearch name list.`
);
this.globalModlog(`USERSEARCH REMOVE`, null, targets.join(", "));
if (!room || room.roomid !== "staff") {
this.sendReply(`You removed the ${count} "${targets.join(", ")}"" from the usersearch name list.`);
}
saveNames();
}
},
usnameshelp: [
`/usnames add [...terms]: Adds the given [terms] to the usersearch name list. Requires: % @ &`,
`/usnames remove [...terms]: Removes the given [terms] from the usersearch name list. Requires: % @ &`,
`/usnames OR /usnames list: Shows the usersearch name list.`
]
};
const pages = {
usersearch(query, user) {
this.checkCan("lock");
const target = toID(query.shift());
if (!target) {
this.title = `[Usersearch Terms]`;
const sorted = {};
for (const curUser of Users.users.values()) {
for (const term of nameList) {
if (curUser.id.includes(term)) {
if (!(term in sorted))
sorted[term] = 0;
sorted[term]++;
}
}
}
return /* @__PURE__ */ Chat.h("div", { class: "pad" }, /* @__PURE__ */ Chat.h("strong", null, "Usersearch term list"), /* @__PURE__ */ Chat.h("button", { style: { float: "right" }, class: "button", name: "send", value: "/uspage" }, /* @__PURE__ */ Chat.h("i", { class: "fa fa-refresh" }), " Refresh"), /* @__PURE__ */ Chat.h("hr", null), !nameList.size ? /* @__PURE__ */ Chat.h("p", null, "None found.") : /* @__PURE__ */ Chat.h("div", { class: "ladder pad" }, /* @__PURE__ */ Chat.h("table", null, /* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("th", null, "Term"), /* @__PURE__ */ Chat.h("th", null, "Current Matches"), /* @__PURE__ */ Chat.h("th", null)), (() => {
const buf = [];
for (const k of import_lib.Utils.sortBy(Object.keys(sorted), (v) => -sorted[v])) {
buf.push(/* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("td", null, k), /* @__PURE__ */ Chat.h("td", null, sorted[k]), /* @__PURE__ */ Chat.h("td", null, /* @__PURE__ */ Chat.h("button", { class: "button", name: "send", value: `/uspage ${k}` }, "Search"))));
}
if (!buf.length)
return /* @__PURE__ */ Chat.h("tr", null, /* @__PURE__ */ Chat.h("td", { colSpan: 3, style: { textAlign: "center" } }, "No names found."));
return buf;
})())));
}
this.title = `[Usersearch] ${target}`;
return /* @__PURE__ */ Chat.h(SearchUsernames, { target, page: true });
}
};
//# sourceMappingURL=usersearch.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/usersearch.tsx"],
"sourcesContent": ["import {Utils, FS} from '../../lib';\r\n\r\nexport const nameList = new Set<string>(JSON.parse(\r\n\tFS('config/chat-plugins/usersearch.json').readIfExistsSync() || \"[]\"\r\n));\r\n\r\nconst ONLINE_SYMBOL = ` \\u25C9 `;\r\nconst OFFLINE_SYMBOL = ` \\u25CC `;\r\n\r\nclass PunishmentHTML extends Chat.JSX.Component<{userid: ID, target: string}> {\r\n\trender() {\r\n\t\tconst {userid, target} = {...this.props};\r\n\t\tconst buf = [];\r\n\t\tfor (const cmdName of ['Forcerename', 'Namelock', 'Weeknamelock']) {\r\n\t\t\t// We have to use dangerouslySetInnerHTML here because otherwise the `value`\r\n\t\t\t// property of the button tag is auto escaped, making &#10; into &amp;#10;\r\n\t\t\tbuf.push(<span dangerouslySetInnerHTML={\r\n\t\t\t\t{\r\n\t\t\t\t\t__html: `<button class=\"button\" name=\"send\" value=\"/msgroom staff,/${toID(cmdName)} ${userid}` +\r\n\t\t\t\t\t`&#10;/uspage ${target}\">${cmdName}</button>`,\r\n\t\t\t\t}\r\n\t\t\t} />);\r\n\t\t}\r\n\t\treturn buf;\r\n\t}\r\n}\r\n\r\nclass SearchUsernames extends Chat.JSX.Component<{target: string, page?: boolean}> {\r\n\trender() {\r\n\t\tconst {target, page} = {...this.props};\r\n\t\tconst results: {offline: string[], online: string[]} = {\r\n\t\t\toffline: [],\r\n\t\t\tonline: [],\r\n\t\t};\r\n\t\tfor (const curUser of Users.users.values()) {\r\n\t\t\tif (!curUser.id.includes(target) || curUser.id.startsWith('guest')) continue;\r\n\t\t\tif (Punishments.isGlobalBanned(curUser)) continue;\r\n\t\t\tif (curUser.connected) {\r\n\t\t\t\tresults.online.push(`${!page ? ONLINE_SYMBOL : ''} ${curUser.name}`);\r\n\t\t\t} else {\r\n\t\t\t\tresults.offline.push(`${!page ? OFFLINE_SYMBOL : ''} ${curUser.name}`);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (const k in results) {\r\n\t\t\tUtils.sortBy(results[k as keyof typeof results], result => toID(result));\r\n\t\t}\r\n\t\tif (!page) {\r\n\t\t\treturn <>\r\n\t\t\t\tUsers with a name matching '{target}':<br />\r\n\t\t\t\t{!results.offline.length && !results.online.length ?\r\n\t\t\t\t\t<>No users found.</> : <>\r\n\t\t\t\t\t\t{results.online.join('; ')}\r\n\t\t\t\t\t\t{!!results.offline.length &&\r\n\t\t\t\t\t\t\t<>{!!results.online.length && <><br /><br /></>}{results.offline.join('; ')}</>}\r\n\t\t\t\t\t</>\r\n\t\t\t\t}\r\n\t\t\t</>;\r\n\t\t}\r\n\t\treturn <div class=\"pad\">\r\n\t\t\t<h2>Usernames containing \"{target}\"</h2>\r\n\t\t\t{!results.online.length && !results.offline.length ?\r\n\t\t\t\t<p>No results found.</p> :\r\n\t\t\t\t<>{!!results.online.length && <div class=\"ladder pad\">\r\n\t\t\t\t\t<h3>Online users</h3>\r\n\t\t\t\t\t<table>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th>Username</th>\r\n\t\t\t\t\t\t\t<th>Punish</th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t{(() => {\r\n\t\t\t\t\t\t\tconst online = [];\r\n\t\t\t\t\t\t\tfor (const username of results.online) {\r\n\t\t\t\t\t\t\t\tonline.push(<tr>\r\n\t\t\t\t\t\t\t\t\t<td><username>{username}</username></td>\r\n\t\t\t\t\t\t\t\t\t<td><PunishmentHTML userid={toID(username)} target={target} /></td>\r\n\t\t\t\t\t\t\t\t</tr>);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\treturn online;\r\n\t\t\t\t\t\t})()}\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</div>}\r\n\t\t\t\t{!!(results.online.length && results.offline.length) && <hr />}\r\n\t\t\t\t{!!results.offline.length && <div class=\"ladder pad\">\r\n\t\t\t\t\t<h3>Offline users</h3>\r\n\t\t\t\t\t<table>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th>Username</th>\r\n\t\t\t\t\t\t\t<th>Punish</th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t{(() => {\r\n\t\t\t\t\t\t\tconst offline = [];\r\n\t\t\t\t\t\t\tfor (const username of results.offline) {\r\n\t\t\t\t\t\t\t\toffline.push(<tr>\r\n\t\t\t\t\t\t\t\t\t<td><username>{username}</username></td>\r\n\t\t\t\t\t\t\t\t\t<td><PunishmentHTML userid={toID(username)} target={target} /></td>\r\n\t\t\t\t\t\t\t\t</tr>);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\treturn offline;\r\n\t\t\t\t\t\t})()}\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</div>}</>\r\n\t\t\t}\r\n\t\t</div>;\r\n\t}\r\n}\r\n\r\nfunction saveNames() {\r\n\tFS('config/chat-plugins/usersearch.json').writeUpdate(() => JSON.stringify([...nameList]));\r\n}\r\n\r\nexport const commands: Chat.ChatCommands = {\r\n\tus: 'usersearch',\r\n\tuspage: 'usersearch',\r\n\tusersearchpage: 'usersearch',\r\n\tusersearch(target, room, user, connection, cmd) {\r\n\t\tthis.checkCan('lock');\r\n\t\ttarget = toID(target);\r\n\t\tif (!target) { // just join directly if it's the page cmd, they're likely looking for the full list\r\n\t\t\tif (cmd.includes('page')) return this.parse(`/j view-usersearch`);\r\n\t\t\treturn this.parse(`/help usersearch`);\r\n\t\t}\r\n\t\tif (target.length < 3) {\r\n\t\t\tthrow new Chat.ErrorMessage(`That's too short of a term to search for.`);\r\n\t\t}\r\n\t\tconst showPage = cmd.includes('page');\r\n\t\tif (showPage) {\r\n\t\t\tthis.parse(`/j view-usersearch-${target}`);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\treturn this.sendReplyBox(<SearchUsernames target={target} />);\r\n\t},\r\n\tusersearchhelp: [\r\n\t\t`/usersearch [pattern]: Looks for all names matchiLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAwB;AAEjB,MAAM,WAAW,IAAI,IAAY,KAAK;AAAA,MAC5C,eAAG,qCAAqC,EAAE,iBAAiB,KAAK;AACjE,CAAC;AAED,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AAEvB,MAAM,uBAAuB,KAAK,IAAI,UAAwC;AAAA,EAC7E,SAAS;AACR,UAAM,EAAC,QAAQ,OAAM,IAAI,EAAC,GAAG,KAAK,MAAK;AACvC,UAAM,MAAM,CAAC;AACb,eAAW,WAAW,CAAC,eAAe,YAAY,cAAc,GAAG;AAGlE,UAAI,KAAK,uBAAC,UAAK,yBACd;AAAA,QACC,QAAQ,6DAA6D,KAAK,OAAO,KAAK,sBACtE,WA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AA,IACA;AAAA,IACA;AAAA,EACD;AACD;AAEO,MAAM,QAAwB;AAAA,EACpC,WAAW,OAAO,MAAM;AACvB,SAAK,SAAS,MAAM;AACpB,UAAM,SAAS,KAAK,MAAM,MAAM,CAAC;AACjC,QAAI,CAAC,QAAQ;AACZ,WAAK,QAAQ;AACb,YAAM,SAAgC,CAAC;AACvC,iBAAW,WAAW,MAAM,MAAM,OAAO,GAAG;AAC3C,mBAAW,QAAQ,UAAU;AAC5B,cAAI,QAAQ,GAAG,SAAS,IAAI,GAAG;AAC9B,gBAAI,EAAE,QAAQ;AAAS,qBAAO,IAAI,IAAI;AACtC,mBAAO,IAAI;AAAA,UACZ;AAAA,QACD;AAAA,MACD;AACA,aAAO,uBAAC,SAAILine truncated
"names": []
}
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/wifi.tsx"],
"sourcesContent": ["/**\r\n * Wi-Fi chat-plugin. Only works in a room with id 'wifi'\r\n * Handles giveaways in the formats: question, lottery, gts\r\n * Written by Kris and bumbadadabum, based on the original plugin as written by Codelegend, SilverTactic, DanielCranham\r\n */\r\n\r\nimport {FS, Utils} from '../../lib';\r\n\r\nPunishments.addRoomPunishmentType({\r\n\ttype: 'GIVEAWAYBAN',\r\n\tdesc: 'banned from giveaways',\r\n});\r\n\r\nconst BAN_DURATION = 7 * 24 * 60 * 60 * 1000;\r\nconst RECENT_THRESHOLD = 30 * 24 * 60 * 60 * 1000;\r\n\r\nconst DATA_FILE = 'config/chat-plugins/wifi.json';\r\n\r\ntype Game = 'SwSh' | 'BDSP' | 'SV';\r\n\r\ninterface GiveawayData {\r\n\ttargetUserID: string;\r\n\tot: string;\r\n\ttid: string;\r\n\tgame: Game;\r\n\tprize: PokemonSet;\r\n\tivs: string[];\r\n\tball: string;\r\n\textraInfo: string;\r\n\t/** Staff handling it. */\r\n\tclaimed?: ID;\r\n}\r\n\r\ninterface QuestionGiveawayData extends GiveawayData {\r\n\tquestion: string;\r\n\tanswers: string[];\r\n}\r\n\r\ninterface LotteryGiveawayData extends GiveawayData {\r\n\twinners: number;\r\n}\r\n\r\ninterface WifiData {\r\n\twhitelist: string[];\r\n\tstats: {[k: string]: number[]};\r\n\tstoredGiveaways: {question: QuestionGiveawayData[], lottery: LotteryGiveawayData[]};\r\n\tsubmittedGiveaways: {question: QuestionGiveawayData[], lottery: LotteryGiveawayData[]};\r\n}\r\n\r\nconst defaults: WifiData = {\r\n\twhitelist: [],\r\n\tstats: {},\r\n\tstoredGiveaways: {\r\n\t\tquestion: [],\r\n\t\tlottery: [],\r\n\t},\r\n\tsubmittedGiveaways: {\r\n\t\tquestion: [],\r\n\t\tlottery: [],\r\n\t},\r\n};\r\n\r\nexport let wifiData: WifiData = (() => {\r\n\ttry {\r\n\t\treturn JSON.parse(FS(DATA_FILE).readSync());\r\n\t} catch (e: any) {\r\n\t\tif (e.code !== 'ENOENT') throw e;\r\n\t\treturn defaults;\r\n\t}\r\n})();\r\n\r\nfunction saveData() {\r\n\tFS(DATA_FILE).writeUpdate(() => JSON.stringify(wifiData));\r\n}\r\n\r\n// Convert old file type\r\nif (!wifiData.stats && !wifiData.storedGiveaways && !wifiData.submittedGiveaways) {\r\n\t// we cast under the assumption that it's the old file format\r\n\tconst stats = {...wifiData} as unknown as {[k: string]: number[]};\r\n\twifiData = {...defaults, stats};\r\n\tsaveData();\r\n}\r\n// ensure the whitelist exists for those who might have the conversion above but not the stats\r\nif (!wifiData.whitelist) wifiData.whitelist = [];\r\n\r\nconst statNames = [\"HP\", \"Atk\", \"Def\", \"SpA\", \"SpD\", \"Spe\"];\r\n\r\nconst gameName: {[k in Game]: string} = {\r\n\tSwSh: 'Sword/Shield',\r\n\tBDSP: 'Brilliant Diamond/Shining Pearl',\r\n\tSV: 'Scarlet/Violet',\r\n};\r\nconst gameidToGame: {[k: string]: Game} = {\r\n\tswsh: 'SwSh',\r\n\tbdsp: 'BDSP',\r\n\tsv: 'SV',\r\n};\r\n\r\nclass Giveaway extends Rooms.SimpleRoomGame {\r\n\tgaNumber: number;\r\n\thost: User;\r\n\tgiver: User;\r\n\troom: Room;\r\n\tot: string;\r\n\ttid: string;\r\n\tgame: Game;\r\n\tivs: string[];\r\n\tprize: PokemonSet;\r\n\tphase: string;\r\n\tball: string;\r\n\textraInfo: string;\r\n\t/**\r\n\t * IP:userid\r\n\t */\r\n\tjoined: Map<string, ID>;\r\n\ttimer: NodeJS.Timer | null;\r\n\tpokemonID: ID;\r\n\tsprite: Chat.VNode;\r\n\r\n\tconstructor(\r\n\t\thost: User, giver: User, room: Room, ot: string, tid: string, ivs: string[],\r\n\t\tprize: PokemonSet, game: Game = 'SV', ball: string, extraInfo: string\r\n\t) {\r\n\t\t// Make into a sub-game if the gts ever opens up again\r\n\t\tsuper(room);\r\n\t\tthis.gaNumber = room.nextGameNumber();\r\n\t\tthis.host = host;\r\n\t\tthis.giver = giver;\r\n\t\tthis.room = room;\r\n\t\tthis.ot = ot;\r\n\t\tthis.tid = tid;\r\n\t\tthis.ball = ball;\r\n\t\tthis.extraInfo = extraInfo;\r\n\t\tthis.game = game;\r\n\t\tthis.ivs = ivs;\r\n\t\tthis.prize = prize;\r\n\t\tthis.phase = 'pending';\r\n\r\n\t\tthis.joined = new Map();\r\n\r\n\t\tthis.timer = null;\r\n\r\n\t\t[this.pokemonID, this.sprite] = Giveaway.getSprite(prize);\r\n\t}\r\n\r\n\tdestroy() {\r\n\t\tthis.clearTimer();\r\n\t\tsuper.destroy();\r\n\t}\r\n\r\n\tgenerateReminder(joined?: boolean): string | Chat.VNode;\r\n\tgenerateReminder() {\r\n\t\treturn '';\r\n\t}\r\n\r\n\tgetStyle() {\r\n\t\tconst css: {[k: string]: string | {[k: string]: string}} = {class: \"broadcast-blue\"};\r\n\t\tif (this.game === 'BDSP') css.style = {background: '#aa66a9', color: '#fff'};\r\n\t\tif (this.game === 'SV') css.style = {background: '#CD5C5C', color: '#fff'};\r\n\t\treturn css;\r\n\t}\r\n\r\n\tsendToUser(user: User, content: string | Chat.VNode) {\r\n\t\tuser.sendTo(\r\n\t\t\tthis.room,\r\n\t\t\tChat.html`|uhtmlchange|giveaway${this.gaNumber}${this.phase}|${<div {...this.getStyle()}>{content}</div>}`\r\n\t\t);\r\n\t}\r\n\r\n\tsend(content: string | Chat.VNode, isStart = false) {\r\n\t\tthis.room.add(Chat.html`|uhtml|giveaway${this.gaNumber}${this.phase}|${<div {...this.getStyle()}>{content}</div>}`);\r\n\t\tif (isStart) this.room.add(`|c:|${Math.floor(Date.now() / 1000)}|&|It's ${this.game} giveaway time!`);\r\n\t\tthis.room.update();\r\n\t}\r\n\r\n\tchangeUhLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,iBAAwB;AAExB,YAAY,sBAAsB;AAAA,EACjC,MAAM;AAAA,EACN,MAAM;AACP,CAAC;AAED,MAAM,eAAe,IAAI,KAAK,KAAK,KAAK;AACxC,MAAM,mBAAmB,KAAK,KAAK,KAAK,KAAK;AAE7C,MAAM,YAAY;AAiClB,MAAM,WAAqB;AAAA,EAC1B,WAAW,CAAC;AAAA,EACZ,OAAO,CAAC;AAAA,EACR,iBAAiB;AAAA,IAChB,UAAU,CAAC;AAAA,IACX,SAAS,CAAC;AAAA,EACX;AAAA,EACA,oBAAoB;AAAA,IACnB,UAAU,CAAC;AAAA,IACX,SAAS,CAAC;AAAA,EACX;AACD;AAEO,IAAI,YAAsB,MAAM;AACtC,MAAI;AACH,WAAO,KAAK,UAAM,eAAG,SAAS,EAAE,SAAS,CAAC;AAAA,EAC3C,SAAS,GAAP;AACD,QAAI,EAAE,SAAS;AAAU,YAAM;AAC/B,WAAO;AAAA,EACR;AACD,GAAG;AAEH,SAAS,WAAW;AACnB,qBAAG,SAAS,EAAE,YAAY,MAAM,KAAK,UAAU,QAAQ,CAAC;AACzD;AAGA,IAAI,CAAC,SAAS,S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AA,MAAa;AAAA,MACxH;AAAA,MAAU;AAAA,MAAW;AAAA,MAAa;AAAA,MAAU;AAAA,MAAa;AAAA,MAAW;AAAA,MAAa;AAAA,MAAY;AAAA,MAAS;AAAA,MAAY;AAAA,MAClH;AAAA,MAAW;ALine truncated
"names": []
}
+832
View File
@@ -0,0 +1,832 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var youtube_exports = {};
__export(youtube_exports, {
GroupWatch: () => GroupWatch,
Twitch: () => Twitch,
TwitchStream: () => TwitchStream,
YouTube: () => YouTube,
YoutubeInterface: () => YoutubeInterface,
commands: () => commands,
destroy: () => destroy,
pages: () => pages,
searchDataCache: () => searchDataCache,
videoDataCache: () => videoDataCache
});
module.exports = __toCommonJS(youtube_exports);
var import_lib = require("../../lib");
const ROOT = "https://www.googleapis.com/youtube/v3/";
const STORAGE_PATH = "config/chat-plugins/youtube.json";
const GROUPWATCH_ROOMS = ["youtube", "pokemongames", "videogames", "smashbros", "pokemongo", "hindi"];
const videoDataCache = Chat.oldPlugins.youtube?.videoDataCache || /* @__PURE__ */ new Map();
const searchDataCache = Chat.oldPlugins.youtube?.searchDataCache || /* @__PURE__ */ new Map();
function loadData() {
const raw = JSON.parse((0, import_lib.FS)(STORAGE_PATH).readIfExistsSync() || "{}");
if (!(raw.channels && raw.categories)) {
const data = {};
data.channels = raw;
data.categories = [];
(0, import_lib.FS)(STORAGE_PATH).writeUpdate(() => JSON.stringify(data));
return data;
}
return raw;
}
const channelData = loadData();
class YoutubeInterface {
constructor(data) {
this.linkRegex = /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)(\/|$)/i;
this.data = data ? data : { categories: [], channels: {} };
this.interval = null;
this.intervalTime = 0;
if (data?.intervalTime) {
this.runInterval(`${data.intervalTime}`);
}
}
async getChannelData(link, username) {
if (!Config.youtubeKey) {
throw new Chat.ErrorMessage(`This server does not support YouTube commands. If you're the owner, you can enable them by setting up Config.youtubekey.`);
}
const id = this.getId(link);
const raw = await (0, import_lib.Net)(`${ROOT}channels`).get({
query: { part: "snippet,statistics", id, key: Config.youtubeKey }
});
const res = JSON.parse(raw);
if (!res?.items || res.items.length < 1) {
throw new Chat.ErrorMessage(`Channel not found.`);
}
const data = res.items[0];
const cache = {
name: data.snippet.title,
description: data.snippet.description,
url: data.snippet.customUrl,
icon: data.snippet.thumbnails.medium.url,
videos: Number(data.statistics.videoCount),
subs: Number(data.statistics.subscriberCount),
views: Number(data.statistics.viewCount),
username
};
this.data.channels[id] = { ...cache };
this.save();
return cache;
}
async generateChannelDisplay(link) {
const id = this.getId(link);
const { name, description, icon, videos, subs, views, username } = await this.get(id);
let buf = `<div class="infobox"><table style="margin:0px;"><tr>`;
buf += `<td style="margin:5px;padding:5px;min-width:175px;max-width:160px;text-align:center;border-bottom:0px;">`;
buf += `<div style="padding:5px;background:white;border:1px solid black;margin:auto;max-width:100px;max-height:100px;">`;
buf += `<a href="${ROOT}channel/${id}"><img src="${icon}" width=100px height=100px/></a>`;
buf += `</div><p style="margin:5px 0px 4px 0px;word-wrap:break-word;">`;
buf += `<a style="font-weight:bold;color:#c70000;font-size:12pt;" href="https://www.youtube.com/channel/${id}">${name}</a>`;
buf += `</p></td><td style="padding: 0px 25px;font-size:10pt;background:rgb(220,20,60);width:100%;border-bottom:0px;vertical-align:top;">`;
buf += `<p style="padding: 5px;border-radius:8px;color:white;font-weight:bold;text-align:center;">`;
buf += `${videos} videos | ${subs} subscribers | ${views} video views</p>`;
buf += `<p style="margin-left: 5px; font-size:9pt;color:white;">`;
buf += `${description.slice(0, 400).replace(/\n/g, " ")}${description.length > 400 ? "(...)" : ""}</p>`;
if (username) {
buf += `<p style="text-align:left;font-style:italic;color:white;">PS username: ${username}</p></td></tr></table></div>`;
} else {
buf += "</td></tr></table></div>";
}
return buf;
}
randChannel(cat) {
let channels = Object.keys(this.data.channels);
if (channels.length < 1) {
throw new Chat.ErrorMessage(`There are no channels in the database.`);
}
if (cat) {
cat = toID(cat);
const categoryIDs = this.data.categories.map(toID);
if (!categoryIDs.includes(cat)) {
throw new Chat.ErrorMessage(`Invalid category.`);
}
channels = channels.filter((id2) => {
const channel = this.data.channels[id2];
return channel.category && toID(channel.category) === cat;
});
}
const id = import_lib.Utils.shuffle(channels)[0];
return this.generateChannelDisplay(id);
}
get(id, username) {
if (!(id in this.data.channels))
return this.getChannelData(id, username);
return Promise.resolve({ ...this.data.channels[id] });
}
async getVideoData(id) {
const cached = videoDataCache.get(id);
if (cached)
return cached;
let raw;
try {
raw = await (0, import_lib.Net)(`${ROOT}videos`).get({
query: { part: "snippet,statistics", id, key: Config.youtubeKey }
});
} catch (e) {
throw new Chat.ErrorMessage(`Failed to retrieve video data: ${e.message}.`);
}
const res = JSON.parse(raw);
if (!res?.items || res.items.length < 1)
return null;
const video = res.items[0];
const data = {
title: video.snippet.title,
id,
date: new Date(video.snippet.publishedAt).toString(),
description: video.snippet.description,
channelTitle: video.snippet.channelTitle,
channelUrl: video.snippet.channelId,
views: video.statistics.viewCount,
thumbnail: video.snippet.thumbnails.default.url,
likes: video.statistics.likeCount,
dislikes: video.statistics.dislikeCount
};
videoDataCache.set(id, data);
return data;
}
channelSearch(search) {
let channel;
if (this.data.channels[search]) {
channel = search;
} else {
for (const id of Object.keys(this.data.channels)) {
const name = toID(this.data.channels[id].name);
const username = this.data.channels[id].username;
if (name === toID(search) || username && toID(username) === toID(search)) {
channel = id;
break;
}
}
}
return channel;
}
getId(link) {
let id = "";
if (!link)
throw new Chat.ErrorMessage("You must provide a YouTube link.");
if (this.data.channels[link])
return link;
if (!link.includes("channel/")) {
if (link.includes("youtube")) {
id = link.split("v=")[1] || "";
} else if (link.includes("youtu.be")) {
id = link.split("/")[3] || "";
} else {
throw new Chat.ErrorMessage("Invalid YouTube channel link.");
}
} else {
id = link.split("channel/")[1] || "";
}
if (id.includes("&"))
id = id.split("&")[0];
if (id.includes("?"))
id = id.split("?")[0];
return id;
}
async generateVideoDisplay(link, fullInfo = false) {
if (!Config.youtubeKey) {
throw new Chat.ErrorMessage(`This server does not support YouTube commands. If you're the owner, you can enable them by setting up Config.youtubekey.`);
}
const id = this.getId(link);
const info = await this.getVideoData(id);
if (!info)
throw new Chat.ErrorMessage(`Video not found.`);
if (!fullInfo) {
let buf2 = `<b>${info.title}</b> `;
buf2 += `(<a class="subtle" href="https://youtube.com/channel/${info.channelUrl}">${info.channelTitle}</a>)<br />`;
buf2 += `<youtube src="https://www.youtube.com/embed/${id}" />`;
return buf2;
}
let buf = `<table style="margin:0px;"><tr>`;
buf += `<td style="margin:5px;padding:5px;min-width:175px;max-width:160px;text-align:center;border-bottom:0px;">`;
buf += `<div style="padding:5px;background:#b0b0b0;border:1px solid black;margin:auto;max-width:100px;max-height:100px;">`;
buf += `<a href="${ROOT}channel/${id}"><img src="${info.thumbnail}" width=100px height=100px/></a>`;
buf += `</div><p style="margin:5px 0px 4px 0px;word-wrap:break-word;">`;
buf += `<a style="font-weight:bold;color:#c70000;font-size:12pt;" href="https://www.youtube.com/watch?v=${id}">${info.title}</a>`;
buf += `</p></td><td style="padding: 0px 25px;font-size:10pt;max-width:100px;background:`;
buf += `#white;width:100%;border-bottom:0px;vertical-align:top;">`;
buf += `<p style="background: #e22828; padding: 5px;border-radius:8px;color:white;font-weight:bold;text-align:center;">`;
buf += `${info.likes} likes | ${info.dislikes} dislikes | ${info.views} video views<br><br>`;
buf += `<small>Published on ${info.date} | ID: ${id}</small><br>Uploaded by: ${info.channelTitle}</p>`;
buf += `<br><details><summary>Video Description</p></summary>`;
buf += `<p style="background: #e22828;max-width:500px;padding: 5px;border-radius:8px;color:white;font-weight:bold;text-align:center;">`;
buf += `<i>${info.description.slice(0, 400).replace(/\n/g, " ")}${info.description.length > 400 ? "(...)" : ""}</p><i></details></td>`;
return buf;
}
save() {
return (0, import_lib.FS)(STORAGE_PATH).writeUpdate(() => JSON.stringify(this.data));
}
async searchVideo(name, limit) {
const cached = searchDataCache.get(toID(name));
if (cached) {
return cached.slice(0, limit);
}
const raw = await (0, import_lib.Net)(`${ROOT}search`).get({
query: {
part: "snippet",
q: name,
key: Config.youtubeKey,
order: "relevance"
}
});
const result = JSON.parse(raw);
const resultArray = result.items?.map((item) => item?.id?.videoId).filter(Boolean);
searchDataCache.set(toID(name), resultArray);
return resultArray.slice(0, limit);
}
async searchChannel(name, limit = 10) {
const raw = await (0, import_lib.Net)(`${ROOT}search`).get({
query: {
part: "snippet",
q: name,
type: "channel",
key: Config.youtubeKey,
order: "relevance",
maxResults: limit
}
});
const result = JSON.parse(raw);
return result?.items.map((item) => item?.snippet?.channelId);
}
runInterval(time) {
let interval = Number(time);
if (interval < 10)
throw new Chat.ErrorMessage(`${interval} is too low - set it above 10 minutes.`);
this.intervalTime = interval;
this.data.intervalTime = interval;
interval = interval * 60 * 1e3;
if (this.interval)
clearInterval(this.interval);
this.interval = setInterval(() => {
void (async () => {
const room = Rooms.get("youtube");
if (!room)
return;
const res = await YouTube.randChannel();
room.add(`|html|${res}`).update();
})();
}, interval);
return this.interval;
}
async createGroupWatch(url, baseRoom, title) {
const id = this.getId(url);
const videoInfo = await this.getVideoData(id);
if (!videoInfo)
throw new Chat.ErrorMessage(`Video not found.`);
const num = baseRoom.nextGameNumber();
baseRoom.saveSettings();
const gameRoom = Rooms.createGameRoom(`video-watch-${num}`, import_lib.Utils.html`[Group Watch] ${title}`, {
isPrivate: "hidden"
});
const game = new GroupWatch(gameRoom, url, videoInfo);
gameRoom.game = game;
gameRoom.setParent(baseRoom);
return gameRoom;
}
}
const Twitch = new class {
constructor() {
this.linkRegex = /(https?:\/\/)?twitch.tv\/([A-Za-z0-9]+)/i;
}
async getChannel(channel) {
channel = toID(channel);
let res;
try {
res = await (0, import_lib.Net)(`https://api.twitch.tv/kraken/search/channels`).get({
headers: {
"Client-Id": Config.twitchKey,
"Content-Type": "application/json",
"Accept": "application/vnd.twitchtv.v5+json"
},
query: { query: channel }
});
} catch (e) {
throw new Chat.ErrorMessage(`Error retrieving twitch channel: ${e.message}`);
}
const data = JSON.parse(res);
import_lib.Utils.sortBy(data.channels, (c) => -c.followers);
return data?.channels?.[0];
}
visualizeChannel(info) {
let buf = `<div class="infobox"><table style="margin:0px;"><tr>`;
buf += `<td style="margin:5px;padding:5px;min-width:175px;max-width:160px;text-align:center;border-bottom:0px;">`;
buf += `<div style="padding:5px;background:white;border:1px solid black;margin:auto;max-width:100px;max-height:100px;">`;
buf += `<a href="${info.url}"><img src="${info.logo}" width=100px height=100px/></a>`;
buf += `</div><p style="margin:5px 0px 4px 0px;word-wrap:break-word;">`;
buf += `<a style="font-weight:bold;color:#6441a5;font-size:12pt;" href="${info.logo}">${info.display_name}</a>`;
buf += `</p></td><td style="padding: 0px 25px;font-size:10pt;background:rgb(100, 65, 164);width:100%;border-bottom:0px;vertical-align:top;">`;
buf += `<p style="padding: 5px;border-radius:8px;color:white;font-size:15px;font-weight:bold;text-align:center;">`;
const created = new Date(info.created_at);
buf += `${info.followers} subscribers | ${info.views} stream views | created ${Chat.toTimestamp(created).split(" ")[0]}</p>`;
buf += `<p style="color:white;font-size:10px">Last seen playing ${info.game} (Status: ${info.status})</p>`;
buf += `<hr /><p style="margin-left: 5px; font-size:9pt;color:white;">`;
buf += `${info.description.slice(0, 400).replace(/\n/g, " ")}${info.description.length > 400 ? "..." : ""}</p>`;
buf += "</td></tr></table></div>";
return buf;
}
}();
class GroupWatch extends Rooms.SimpleRoomGame {
constructor(room, url, videoInfo) {
super(room);
this.started = null;
this.url = url;
this.info = videoInfo;
this.controls(`<h2><i>Waiting to start the video...</i></h2>`);
}
onJoin(user) {
const hints = this.hints();
for (const hint of hints) {
user.sendTo(this.room.roomid, `|html|${hint}`);
}
}
start() {
if (this.started)
throw new Chat.ErrorMessage(`We've already started.`);
this.controls(this.getStatsDisplay());
this.field(this.getVideoDisplay());
this.started = Date.now();
this.add(`|html|<h2>Group Watch!</h2>`);
}
hints() {
const hints = [
`To watch, all you need to do is click play on the video once staff have started it!`,
`We are currently watching: <a href="${this.url}">${this.info.title}</a>`
];
if (this.started) {
const diff = Date.now() - this.started;
hints.push(`Video is currently at ${Chat.toDurationString(diff)} (${diff / 1e3} seconds)`);
}
return hints;
}
getStatsDisplay() {
let controlsHTML = `<h3>${this.info.title}</h3>`;
controlsHTML += `<div class="infobox"><b>Channel:</b> `;
controlsHTML += `<a href="https://www.youtube.com/channel/${this.info.channelUrl}">${this.info.channelTitle}</a><br />`;
controlsHTML += `<b>Likes:</b> ${this.info.likes} | <b>Dislikes:</b> ${this.info.dislikes}<br />`;
controlsHTML += `<b>Uploaded:</b> ${Chat.toTimestamp(new Date(this.info.date))}<br />`;
controlsHTML += `<details><summary>Description</summary>${this.info.description.replace(/\n/ig, "<br />")}</details>`;
controlsHTML += `</div>`;
return controlsHTML;
}
getVideoDisplay() {
let buf = `<p style="background: #e22828; padding: 5px;border-radius:8px;color:white;font-weight:bold;text-align:center;">`;
buf += `<br /><br /><b>${this.info.title}</b><br />`;
const id = YouTube.getId(this.url);
const url = `https://youtube.com/watch?v=${id}`;
buf += `<youtube src="${url}" />`;
buf += `<br />`.repeat(4);
buf += `</p>`;
return buf;
}
controls(html) {
this.add(`|controlshtml|<center>${html}</center>`);
}
field(html) {
this.add(`|fieldhtml|${html}`);
}
add(buf) {
this.room.add(buf).update();
}
destroy() {
this.controls(`<b>The group watch has ended.</b>`);
let endBuf = `<center>`;
endBuf += this.getStatsDisplay();
endBuf += `<br /> Thanks for watching!</center>`;
this.field(endBuf);
this.room = null;
}
}
class TwitchStream extends Rooms.SimpleRoomGame {
constructor(room, data) {
super(room);
this.started = false;
this.data = data;
}
static async createStreamWatch(room, channel) {
if ([...Rooms.rooms.values()].some(
(r) => r.roomid.startsWith(`twitch-`) && r.parent?.roomid === room?.roomid
)) {
throw new Chat.ErrorMessage(`Twitch watch already in progress for this room.`);
}
const data = await Twitch.getChannel(channel);
if (!data)
throw new Chat.ErrorMessage(`Channel not found`);
const watchRoom = Rooms.createGameRoom(
`twitch-stream-watch-${room.nextGameNumber()}`,
import_lib.Utils.html`[Twitch Watch] ${data.display_name}`,
{ isPrivate: "hidden" }
);
room.saveSettings();
watchRoom.setParent(room);
const stream = new TwitchStream(watchRoom, data);
watchRoom.game = stream;
return watchRoom;
}
field(buf) {
this.add(`|fieldhtml|${buf}`);
}
controls(buf) {
this.add(`|controlshtml|${buf}`);
}
add(data) {
return this.room.add(data).update();
}
onJoin(user) {
if (!user.named)
return;
this.controls(this.getControlsDisplay());
}
onLeave(user) {
if (!user.named)
return;
this.controls(this.getControlsDisplay());
}
start() {
if (this.started) {
throw new Chat.ErrorMessage(`Stream already started`);
}
this.controls(this.getControlsDisplay());
this.field(this.getStreamDisplay());
this.add(`|html|<h2>The stream watch has started!</h2>`);
this.started = true;
}
end() {
this.field("");
this.controls(`<center><h2>Stream watch ended</h2></center>`);
this.room.parent?.add(`|uhtmlchange|ts-${this.room.roomid}|`);
this.add(`|expire|Stream ended`);
this.room.destroy();
}
getControlsDisplay() {
let buf = `<p style="background: #6441a5; padding: 5px;border-radius:8px;color:white;font-weight:bold;text-align:center;">`;
buf += `<strong>Watching <a href="${this.data.url}" class="subtle">${this.data.display_name}</strong><br />`;
buf += `${Chat.count(Object.keys(this.room.users).length, "users")} watching<br />`;
buf += `<strong>Playing: ${this.data.game}`;
return buf;
}
getStreamDisplay() {
let buf = `<p style="background: #6441a5; padding: 5px;border-radius:8px;color:white;font-weight:bold;text-align:center;">`;
buf += `<twitch src="${this.data.url}" width="600" height="330" />`;
return buf;
}
}
const YouTube = new YoutubeInterface(channelData);
function destroy() {
if (YouTube.interval)
clearInterval(YouTube.interval);
}
const commands = {
async randchannel(target, room, user) {
room = this.requireRoom("youtube");
if (Object.keys(YouTube.data.channels).length < 1)
return this.errorReply(`No channels in the database.`);
target = toID(target);
this.runBroadcast();
const data = await YouTube.randChannel(target);
return this.sendReply(`|html|${data}`);
},
randchannelhelp: [`/randchannel - View data of a random channel from the YouTube database.`],
yt: "youtube",
youtube: {
async addchannel(target, room, user) {
room = this.requireRoom("youtube");
this.checkCan("mute", null, room);
const [id, name] = target.split(",").map((t) => t.trim());
if (!id)
return this.errorReply("Specify a channel ID.");
await YouTube.getChannelData(id, name);
this.modlog("ADDCHANNEL", null, `${id} ${name ? `username: ${name}` : ""}`);
return this.privateModAction(
`${user.name} added channel with id ${id} ${name ? `and username (${name}) ` : ""} to the random channel pool.`
);
},
addchannelhelp: [`/addchannel - Add channel data to the YouTube database. Requires: % @ #`],
removechannel(target, room, user) {
room = this.requireRoom("youtube");
this.checkCan("mute", null, room);
const id = YouTube.channelSearch(target);
if (!id)
return this.errorReply(`Channel with ID or name ${target} not found.`);
delete YouTube.data.channels[id];
YouTube.save();
this.privateModAction(`${user.name} deleted channel with ID or name ${target}.`);
return this.modlog(`REMOVECHANNEL`, null, id);
},
removechannelhelp: [`/youtube removechannel - Delete channel data from the YouTube database. Requires: % @ #`],
async channel(target, room, user) {
room = this.requireRoom("youtube");
const channel = YouTube.channelSearch(target);
if (!channel)
return this.errorReply(`No channels with ID or name ${target} found.`);
const data = await YouTube.generateChannelDisplay(channel);
this.runBroadcast();
return this.sendReply(`|html|${data}`);
},
channelhelp: [
"/youtube channel - View the data of a specified channel. Can be either channel ID or channel name."
],
async video(target, room, user) {
room = this.requireRoom("youtube");
this.checkCan("mute", null, room);
const buffer = await YouTube.generateVideoDisplay(target, true);
this.runBroadcast();
this.sendReplyBox(buffer);
},
channels(target, room, user) {
target = toID(target);
return this.parse(`/j view-channels${target ? `-${target}` : ""}`);
},
help(target, room, user) {
return this.parse("/help youtube");
},
categories() {
return this.parse(`/j view-channels-categories`);
},
update(target, room, user) {
room = this.requireRoom("youtube");
this.checkCan("mute", null, room);
const [channel, name] = target.split(",");
const id = YouTube.channelSearch(channel);
if (!id)
return this.errorReply(`Channel ${channel} is not in the database.`);
YouTube.data.channels[id].username = name;
this.modlog(`UPDATECHANNEL`, null, name);
this.privateModAction(`${user.name} updated channel ${id}'s username to ${name}.`);
YouTube.save();
},
interval: "repeat",
repeat(target, room, user) {
room = this.requireRoom("youtube");
this.checkCan("declare", null, room);
if (!target) {
if (!YouTube.interval)
return this.errorReply(`The YouTube plugin is not currently running an interval.`);
return this.sendReply(`Interval is currently set to ${Chat.toDurationString(YouTube.intervalTime * 60 * 1e3)}.`);
}
if (this.meansNo(target)) {
if (!YouTube.interval)
return this.errorReply(`The interval is not currently running`);
clearInterval(YouTube.interval);
delete YouTube.data.intervalTime;
YouTube.save();
this.privateModAction(`${user.name} turned off the YouTube interval`);
return this.modlog(`YOUTUBE INTERVAL`, null, "OFF");
}
if (Object.keys(channelData).length < 1)
return this.errorReply(`No channels in the database.`);
if (isNaN(parseInt(target)))
return this.errorReply(`Specify a number (in minutes) for the interval.`);
YouTube.runInterval(target);
YouTube.save();
this.privateModAction(`${user.name} set a randchannel interval to ${target} minutes`);
return this.modlog(`CHANNELINTERVAL`, null, `${target} minutes`);
},
addcategory(target, room, user) {
room = this.requireRoom("youtube");
this.checkCan("mute", null, room);
const categoryID = toID(target);
if (!categoryID)
return this.parse(`/help youtube`);
if (YouTube.data.categories.map(toID).includes(categoryID)) {
return this.errorReply(`This category is already added. To change it, remove it and re-add it.`);
}
YouTube.data.categories.push(target);
this.modlog(`YOUTUBE ADDCATEGORY`, null, target);
this.privateModAction(`${user.name} added category '${target}' to the categories list.`);
YouTube.save();
},
removecategory(target, room, user) {
room = this.requireRoom("youtube");
this.checkCan("mute", null, room);
const categoryID = toID(target);
if (!categoryID)
return this.parse(`/help youtube`);
const index = YouTube.data.categories.indexOf(target);
if (index < 0) {
return this.errorReply(`${target} is not a valid category.`);
}
for (const id in YouTube.data.channels) {
const channel = YouTube.data.channels[id];
if (channel.category === target)
delete YouTube.data.channels[id].category;
}
YouTube.save();
this.privateModAction(`${user.name} removed the category '${target}' from the category list.`);
this.modlog(`YOUTUBE REMOVECATEGORY`, null, target);
},
setcategory(target, room, user) {
room = this.requireRoom("youtube");
this.checkCan("mute", null, room);
target = target.trim();
const [category, id] = import_lib.Utils.splitFirst(target, ",").map((item) => item.trim());
if (!target || !category || !id) {
return this.parse("/help youtube");
}
if (!YouTube.data.categories.includes(category)) {
return this.errorReply(`Invalid category.`);
}
const name = YouTube.channelSearch(id);
if (!name)
return this.errorReply(`Invalid channel.`);
const channel = YouTube.data.channels[name];
YouTube.data.channels[name].category = category;
YouTube.save();
this.modlog(`YOUTUBE SETCATEGORY`, null, `${id}: to category ${category}`);
this.privateModAction(`${user.name} set the channel ${channel.name}'s category to '${category}'.`);
},
decategorize(target, room, user) {
room = this.requireRoom("youtube");
this.checkCan("mute", null, room);
target = target.trim();
if (!target) {
return this.parse("/help youtube");
}
const name = YouTube.channelSearch(target);
if (!name)
return this.errorReply(`Invalid channel.`);
const channel = YouTube.data.channels[name];
const category = channel.category;
if (!category)
return this.errorReply(`That channel does not have a category.`);
delete channel.category;
YouTube.save();
this.modlog(`YOUTUBE DECATEGORIZE`, null, target);
this.privateModAction(`${user.name} removed the channel ${channel.name} from the category ${category}.`);
},
async groupwatch(target, room, user) {
room = this.requireRoom();
if (!GROUPWATCH_ROOMS.includes(room.roomid)) {
return this.errorReply(`This room is not allowed to use the groupwatch function.`);
}
this.checkCan("mute", null, room);
const [url, title] = import_lib.Utils.splitFirst(target, ",").map((p) => p.trim());
if (!url || !title)
return this.errorReply(`You must specify a video to watch and a title for the group watch.`);
const gameRoom = await YouTube.createGroupWatch(url, room, title);
this.modlog(`YOUTUBE GROUPWATCH`, null, `${url} (${title})`);
room.add(
`|uhtml|${gameRoom.roomid}|<button class="button" name="send" value="/j ${gameRoom.roomid}">Join the ongoing group watch!</button>`
);
room.send(`|tempnotify|youtube|New groupwatch - ${title}!`);
this.update();
user.joinRoom(gameRoom);
},
endwatch(target, room, user) {
room = this.requireRoom();
this.checkCan("mute", null, room);
this.requireGame(GroupWatch);
room.parent.modlog({ action: `GROUPWATCH END`, loggedBy: user.id });
room.parent.add(`|uhtmlchange|${room.roomid}|`).update();
room.destroy();
},
startwatch: "beginwatch",
beginwatch(target, room, user) {
room = this.requireRoom();
this.checkCan("mute", null, room);
const game = this.requireGame(GroupWatch);
game.start();
},
groupwatches() {
let buf = `<strong>Ongoing groupwatches:</strong><br />`;
for (const curRoom of Rooms.rooms.values()) {
if (!curRoom.getGame(GroupWatch))
continue;
buf += `<button class="button" name="send" value="/j ${curRoom.roomid}">${curRoom.title}</button>`;
}
this.runBroadcast();
this.sendReplyBox(buf);
}
},
youtubehelp: [
`YouTube commands:`,
`/randchannel [optional category]- View data of a random channel from the YouTube database. If a category is given, the random channel will be in the given category.`,
`/youtube addchannel [channel] - Add channel data to the YouTube database. Requires: % @ #`,
`/youtube removechannel [channel]- Delete channel data from the YouTube database. Requires: % @ #`,
`/youtube channel [channel] - View the data of a specified channel. Can be either channel ID or channel name.`,
`/youtube video [video] - View data of a specified video. Can be either channel ID or channel name.`,
`/youtube update [channel], [name] - sets a channel's PS username to [name]. Requires: % @ #`,
`/youtube repeat [time] - Sets an interval for [time] minutes, showing a random channel each time. Requires: # &`,
`/youtube addcategory [name] - Adds the [category] to the channel category list. Requires: @ # &`,
`/youtube removecategory [name] - Removes the [category] from the channel category list. Requires: @ # &`,
`/youtube setcategory [category], [channel name] - Sets the category for [channel] to [category]. Requires: @ # &`,
`/youtube decategorize [channel name] - Removes the category for the [channel], if there is one. Requires: @ # &`,
`/youtube categores - View all channels sorted by category.`,
`/youtube groupwatch [link], [title] - Creates a group watch of the [url] with the given [title]. Requires % @ & #`,
`/youtube startwatch - Starts the group watch in the current room, if there is one. Requires % @ & #`,
`/youtube stopwatch - Ends the current group watch, if there is one in the current room. Requires % @ & #`
],
twitch: {
async channel(target, room, user) {
room = this.requireRoom("youtube");
if (!Config.twitchKey)
return this.errorReply(`Twitch is not configured`);
const data = await Twitch.getChannel(target);
if (!data)
return this.errorReply(`Channel not found`);
const html = Twitch.visualizeChannel(data);
this.runBroadcast();
return this.sendReplyBox(html);
},
async watch(target, room, user) {
room = this.requireRoom();
if (!GROUPWATCH_ROOMS.includes(room.roomid)) {
throw new Chat.ErrorMessage(`You cannot use this command in this room.`);
}
this.checkCan("mute", null, room);
if (!toID(target)) {
return this.errorReply(`Invalid channel`);
}
const gameRoom = await TwitchStream.createStreamWatch(room, target);
user.joinRoom(gameRoom);
room.add(
`|uhtml|ts-${gameRoom.roomid}|<button class="button" name="send" value="/j ${gameRoom.roomid}">Join the ongoing stream watch!</button>`
).update();
},
start(target, room) {
room = this.requireRoom();
const stream = this.requireGame(TwitchStream);
stream.start();
},
stop(target, room, user) {
room = this.requireRoom();
const stream = this.requireGame(TwitchStream);
this.checkCan("mute", null, room);
stream.end();
}
}
};
const pages = {
async channels(args, user) {
const [type] = args;
if (!Config.youtubeKey)
return `<h2>Youtube is not configured.</h2>`;
const titles = {
all: "All channels",
categories: "by category"
};
const title = titles[type] || "Usernames only";
this.title = `[Channels] ${title}`;
let buffer = `<div class="pad"><h4>Channels in the YouTube database: (${title})`;
buffer += ` <button class="button" name="send" value="/join view-channels-${type}" style="float: right">Refresh</button>`;
buffer += `</h4><hr />`;
switch (toID(type)) {
case "categories":
if (!YouTube.data.categories.length) {
return this.errorReply(`There are currently no categories in the Youtube channel database.`);
}
const sorted = {};
const channels = YouTube.data.channels;
for (const [id, channel] of Object.entries(channels)) {
const category = channel.category || "No category";
if (!sorted[category]) {
sorted[category] = [];
}
sorted[category].push(id);
}
for (const cat in sorted) {
buffer += `<h3>${cat}:</h3>`;
for (const id of sorted[cat]) {
const channel = channels[id];
buffer += `<details><summary>${channel.name}</summary>`;
buffer += await YouTube.generateChannelDisplay(id);
buffer += `</details><br />`;
}
}
break;
default:
for (const id of import_lib.Utils.shuffle(Object.keys(YouTube.data.channels))) {
const { name, username } = await YouTube.get(id);
if (toID(type) !== "all" && !username)
continue;
buffer += `<details><summary>${name}`;
buffer += `<small><i> (Channel ID: ${id})</i></small>`;
if (username)
buffer += ` <small>(PS name: ${username})</small>`;
buffer += `</summary>`;
buffer += await YouTube.generateChannelDisplay(id);
buffer += `</details><hr/ >`;
}
break;
}
buffer += `</div>`;
return buffer;
}
};
//# sourceMappingURL=youtube.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../server/chat-plugins/youtube.ts"],
"sourcesContent": ["/**\r\n * Youtube room chat-plugin.\r\n * Supports adding channels and selecting a random channel.\r\n * Also supports showing video data on request.\r\n * Written by Mia, with some design concepts from bumbadadabum.\r\n * @author mia-pi-git\r\n */\r\n\r\nimport {Utils, FS, Net} from '../../lib';\r\n\r\nconst ROOT = 'https://www.googleapis.com/youtube/v3/';\r\nconst STORAGE_PATH = 'config/chat-plugins/youtube.json';\r\nconst GROUPWATCH_ROOMS = ['youtube', 'pokemongames', 'videogames', 'smashbros', 'pokemongo', 'hindi'];\r\n\r\nexport const videoDataCache: Map<string, VideoData> = Chat.oldPlugins.youtube?.videoDataCache || new Map();\r\nexport const searchDataCache: Map<string, string[]> = Chat.oldPlugins.youtube?.searchDataCache || new Map();\r\n\r\ninterface ChannelEntry {\r\n\tname: string;\r\n\tdescription: string;\r\n\turl: string;\r\n\ticon: string;\r\n\tvideos: number;\r\n\tsubs: number;\r\n\tviews: number;\r\n\tusername?: string;\r\n\tcategory?: string;\r\n}\r\n\r\nexport interface VideoData {\r\n\tid: string;\r\n\ttitle: string;\r\n\tdate: string;\r\n\tdescription: string;\r\n\tchannelTitle: string;\r\n\tchannelUrl: string;\r\n\tviews: number;\r\n\tthumbnail: string;\r\n\tlikes: number;\r\n\tdislikes: number;\r\n}\r\n\r\ninterface TwitchChannel {\r\n\tstatus: string;\r\n\tdisplay_name: string;\r\n\tname: string;\r\n\tlanguage: string;\r\n\tcreated_at: string;\r\n\tlogo: string;\r\n\tviews: number;\r\n\tfollowers: number;\r\n\tvideo_banner: string;\r\n\turl: string;\r\n\tgame: string;\r\n\tdescription: string;\r\n\tupdated_at: string;\r\n}\r\n\r\ninterface ChannelData {\r\n\tchannels: {[k: string]: ChannelEntry};\r\n\tcategories: string[];\r\n\tintervalTime?: number;\r\n}\r\n\r\nfunction loadData() {\r\n\tconst raw: AnyObject = JSON.parse(FS(STORAGE_PATH).readIfExistsSync() || \"{}\");\r\n\tif (!(raw.channels && raw.categories)) { // hasn't been converted to new format\r\n\t\tconst data: Partial<ChannelData> = {};\r\n\t\tdata.channels = raw;\r\n\t\tdata.categories = [];\r\n\t\t// re-save into new format\r\n\t\tFS(STORAGE_PATH).writeUpdate(() => JSON.stringify(data));\r\n\t\treturn data as ChannelData;\r\n\t}\r\n\treturn raw as ChannelData;\r\n}\r\n\r\nconst channelData: ChannelData = loadData();\r\n\r\nexport class YoutubeInterface {\r\n\tinterval: NodeJS.Timer | null;\r\n\tintervalTime: number;\r\n\tdata: ChannelData;\r\n\tlinkRegex = /^(https?:\\/\\/)?(www\\.)?(youtube\\.com|youtu\\.be)(\\/|$)/i;\r\n\tconstructor(data?: ChannelData) {\r\n\t\tthis.data = data ? data : {categories: [], channels: {}};\r\n\t\tthis.interval = null;\r\n\t\tthis.intervalTime = 0;\r\n\t\tif (data?.intervalTime) {\r\n\t\t\tthis.runInterval(`${data.intervalTime}`);\r\n\t\t}\r\n\t}\r\n\tasync getChannelData(link: string, username?: string) {\r\n\t\tif (!Config.youtubeKey) {\r\n\t\t\tthrow new Chat.ErrorMessage(`This server does not support YouTube commands. If you're the owner, you can enable them by setting up Config.youtubekey.`);\r\n\t\t}\r\n\t\tconst id = this.getId(link);\r\n\t\tconst raw = await Net(`${ROOT}channels`).get({\r\n\t\t\tquery: {part: 'snippet,statistics', id, key: Config.youtubeKey},\r\n\t\t});\r\n\t\tconst res = JSON.parse(raw);\r\n\t\tif (!res?.items || res.items.length < 1) {\r\n\t\t\tthrow new Chat.ErrorMessage(`Channel not found.`);\r\n\t\t}\r\n\t\tconst data = res.items[0];\r\n\t\tconst cache: ChannelEntry = {\r\n\t\t\tname: data.snippet.title,\r\n\t\t\tdescription: data.snippet.description,\r\n\t\t\turl: data.snippet.customUrl,\r\n\t\t\ticon: data.snippet.thumbnails.medium.url,\r\n\t\t\tvideos: Number(data.statistics.videoCount),\r\n\t\t\tsubs: Number(data.statistics.subscriberCount),\r\n\t\t\tviews: Number(data.statistics.viewCount),\r\n\t\t\tusername: username,\r\n\t\t};\r\n\t\tthis.data.channels[id] = {...cache};\r\n\t\tthis.save();\r\n\t\treturn cache;\r\n\t}\r\n\tasync generateChannelDisplay(link: string) {\r\n\t\tconst id = this.getId(link);\r\n\t\tconst {name, description, icon, videos, subs, views, username} = await this.get(id);\r\n\t\t// credits bumbadadabum for most of the html\r\n\t\tlet buf = `<div class=\"infobox\"><table style=\"margin:0px;\"><tr>`;\r\n\t\tbuf += `<td style=\"margin:5px;padding:5px;min-width:175px;max-width:160px;text-align:center;border-bottom:0px;\">`;\r\n\t\tbuf += `<div style=\"padding:5px;background:white;border:1px solid black;margin:auto;max-width:100px;max-height:100px;\">`;\r\n\t\tbuf += `<a href=\"${ROOT}channel/${id}\"><img src=\"${icon}\" width=100px height=100px/></a>`;\r\n\t\tbuf += `</div><p style=\"margin:5px 0px 4px 0px;word-wrap:break-word;\">`;\r\n\t\tbuf += `<a style=\"font-weight:bold;color:#c70000;font-size:12pt;\" href=\"https://www.youtube.com/channel/${id}\">${name}</a>`;\r\n\t\tbuf += `</p></td><td style=\"padding: 0px 25px;font-size:10pt;background:rgb(220,20,60);width:100%;border-bottom:0px;vertical-align:top;\">`;\r\n\t\tbuf += `<p style=\"padding: 5px;border-radius:8px;color:white;font-weight:bold;text-align:center;\Line truncated
"mappings": ";;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