/**
* Wrapper to facilitate posting / interacting with Smogon.
* By Mia.
* @author mia-pi-git
*/
import { Net, FS, Utils } from '../../lib';
export interface Nomination {
by: ID;
ips: string[];
info: string;
date: number;
standing: string;
alts: string[];
primaryID: ID;
claimed?: ID;
post?: string;
}
interface IPData {
country: string;
isp: string;
city: string;
regionName: string;
lat: number;
lon: number;
}
export function getIPData(ip: string) {
try {
return Net("https://miapi.dev/api/ip/" + ip).get().then(JSON.parse) as Promise;
} catch {
return null;
}
}
export const Smogon = new class {
async post(threadNum: string, postText: string) {
if (!Config.smogon) return null;
try {
const raw = await Net(`https://www.smogon.com/forums/api/posts`).get({
method: 'POST',
body: new URLSearchParams({
thread_id: threadNum,
message: postText,
}).toString(),
headers: {
'XF-Api-Key': Config.smogon,
'Content-Type': 'application/x-www-form-urlencoded',
},
});
// todo return URL of post
const data = JSON.parse(raw);
if (data.errors?.length) {
const errData = data.errors.pop();
throw new Error(errData.message);
}
return data;
} catch (e: any) {
if (e.message.includes('Not Found')) {
// special case to be loud
throw new Error("WHO DELETED THE PERMA THREAD");
}
return { error: e.message };
}
}
};
export const Nominations = new class {
noms: Nomination[] = [];
icons: Record = {};
constructor() {
this.load();
}
load() {
try {
let data = JSON.parse(FS('config/chat-plugins/permas.json').readSync());
if (Array.isArray(data)) {
data = { noms: data, icons: {} };
FS('config/chat-plugins/permas.json').writeSync(JSON.stringify(data));
}
this.noms = data.noms;
this.icons = data.icons;
} catch {}
}
fetchModlog(id: string) {
return Rooms.Modlog.search('global', {
user: [{ search: id, isExact: true }],
note: [],
ip: [],
action: [],
actionTaker: [],
}, undefined, true);
}
save() {
FS('config/chat-plugins/permas.json').writeUpdate(() => JSON.stringify({ noms: this.noms, icons: this.icons }));
}
notifyStaff() {
const usRoom = Rooms.get('upperstaff');
if (!usRoom) return;
usRoom.send(`|uhtml|permanoms|${this.getDisplayButton()}`);
Chat.refreshPageFor('permalocks', usRoom);
}
async add(target: string, connection: Connection) {
const user = connection.user;
const [primary, rawAlts, rawIps, type, details] = Utils.splitFirst(target, '|', 4).map(f => f.trim());
const primaryID = toID(primary);
const alts = rawAlts.split(',').map(toID).filter(Boolean);
const ips = rawIps.split(',').map(f => f.trim()).filter(Boolean);
for (const ip of ips) {
if (!IPTools.ipRegex.test(ip)) this.error(`Invalid IP: ${ip}`, connection);
}
const standings = this.getStandings();
if (!standings[type]) {
this.error(`Invalid standing: ${type}.`, connection);
}
if (!details) {
this.error("Details must be provided. Explain why this user should be permalocked.", connection);
}
if (!primaryID) {
this.error("A primary username must be provided. Use one of their alts if necessary.", connection);
}
for (const nom of this.noms) {
if (nom.primaryID === primaryID) {
this.error(`'${primaryID}' was already nominated for permalock by ${nom.by}.`, connection);
}
}
const ipTable = new Set(ips);
const altTable = new Set([...alts]);
for (const alt of [primaryID, ...alts]) {
const modlog = await this.fetchModlog(alt);
if (!modlog?.results.length) continue;
for (const entry of modlog.results) {
if (entry.ip) ipTable.add(entry.ip);
if (entry.autoconfirmedID) altTable.add(entry.autoconfirmedID);
if (entry.alts) {
for (const id of entry.alts) altTable.add(id);
}
}
}
altTable.delete(primaryID);
this.noms.push({
by: user.id,
alts: [...altTable],
ips: Utils.sortBy([...ipTable], z => -(IPTools.ipToNumber(z) || Infinity)),
info: details,
primaryID,
standing: type,
date: Date.now(),
});
Utils.sortBy(this.noms, nom => -nom.date);
this.save();
this.notifyStaff();
Rooms.get('staff')?.addByUser(user, `${user.name} submitted a perma nomination for ${primaryID}`);
}
find(id: string) {
return this.noms.find(f => f.primaryID === id);
}
error(message: string, conn: Connection): never {
conn.popup(message);
throw new Chat.Interruption();
}
close(target: string, context: Chat.CommandContext) {
const entry = this.find(target);
if (!entry) {
this.error(`There is no nomination pending for '${toID(target)}'.`, context.connection);
}
this.noms.splice(this.noms.findIndex(f => f.primaryID === entry.primaryID), 1);
this.save();
this.notifyStaff();
// todo fix when on good comp
return context.closePage(`permalocks-view-${entry.primaryID}`);
}
display(nom: Nomination, canEdit?: boolean) {
let buf = `
`;
let title = nom.primaryID as string;
if (canEdit) {
title = `${nom.primaryID}`;
}
buf += `${title} (submitted by ${nom.by}) `;
buf += `Submitted ${Chat.toTimestamp(new Date(nom.date), { human: true })} `;
buf += `${Chat.count(nom.alts, 'alts')}, ${Chat.count(nom.ips, 'IPs')}`;
buf += `
`;
return buf;
}
displayModlog(results: import('../modlog').ModlogEntry[] | null) {
if (!results) return '';
let curDate = '';
return results.map(result => {
const date = new Date(result.time || Date.now());
const entryRoom = result.visualRoomID || result.roomID || 'global';
let [dateString, timestamp] = Chat.toTimestamp(date, { human: true }).split(' ');
let line = `[${timestamp}] (${entryRoom}) ${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 (result.ip) line += ` [${result.ip}]`;
}
if (result.loggedBy) line += `: by ${result.loggedBy}`;
if (result.note) line += Utils.html`: ${result.note}`;
if (dateString !== curDate) {
curDate = dateString;
dateString = `