diff --git a/lib/crashlogger.ts b/lib/crashlogger.ts index 0dc1a53ca2..ba01b148a9 100644 --- a/lib/crashlogger.ts +++ b/lib/crashlogger.ts @@ -15,7 +15,8 @@ const CRASH_EMAIL_THROTTLE = 5 * 60 * 1000; // 5 minutes const logPath = path.resolve( // not sure why this is necessary, but in Windows testing it was - __dirname, '../', __dirname.includes(`${path.sep}dist${path.sep}`) ? '..' : '', 'logs/errors.txt' + __dirname, '../', __dirname.includes(`${path.sep}dist${path.sep}`) ? '..' : '', + path.join(global.Config?.logsdir || 'logs', 'errors.txt') ); let lastCrashLog = 0; let transport: any; diff --git a/server/chat-plugins/abuse-monitor.ts b/server/chat-plugins/abuse-monitor.ts index a67541832d..2b43e0b978 100644 --- a/server/chat-plugins/abuse-monitor.ts +++ b/server/chat-plugins/abuse-monitor.ts @@ -670,11 +670,11 @@ function getFlaggedRooms() { } export function writeStats(type: string, entry: AnyObject) { - const path = `logs/artemis/${type}/${Chat.toTimestamp(new Date()).split(' ')[0].slice(0, -3)}.jsonl`; + const path = `artemis/${type}/${Chat.toTimestamp(new Date()).split(' ')[0].slice(0, -3)}.jsonl`; try { - FS(path).parentDir().mkdirpSync(); + Monitor.logPath(path).parentDir().mkdirpSync(); } catch {} - void FS(path).append(JSON.stringify(entry) + "\n"); + void Monitor.logPath(path).append(JSON.stringify(entry) + "\n"); } function saveSettings(path?: string) { @@ -2092,7 +2092,7 @@ export const pages: Chat.PageTable = { types: {} as Record, }; const inaccurate = new Set(); - const logPath = FS(`logs/artemis/punishments/${dateString}.jsonl`); + const logPath = Monitor.logPath(`artemis/punishments/${dateString}.jsonl`); if (await logPath.exists()) { const stream = logPath.createReadStream(); for await (const line of stream.byLine()) { @@ -2107,7 +2107,7 @@ export const pages: Chat.PageTable = { } } - const reviewLogPath = FS(`logs/artemis/reviews/${dateString}.jsonl`); + const reviewLogPath = Monitor.logPath(`artemis/reviews/${dateString}.jsonl`); if (await reviewLogPath.exists()) { const stream = reviewLogPath.createReadStream(); for await (const line of stream.byLine()) { diff --git a/server/chat-plugins/battlesearch.ts b/server/chat-plugins/battlesearch.ts index a22216fbd0..9f58720576 100644 --- a/server/chat-plugins/battlesearch.ts +++ b/server/chat-plugins/battlesearch.ts @@ -29,11 +29,11 @@ interface BattleSearchResults { const MAX_BATTLESEARCH_PROCESSES = 1; export async function runBattleSearch(userids: ID[], month: string, tierid: ID, turnLimit?: number) { const useRipgrep = await checkRipgrepAvailability(); - const pathString = `logs/${month}/${tierid}/`; + const pathString = `${month}/${tierid}/`; const results: {[k: string]: BattleSearchResults} = {}; let files = []; try { - files = await FS(pathString).readdir(); + files = await Monitor.logPath(pathString).readdir(); } catch (err: any) { if (err.code === 'ENOENT') { return results; @@ -41,7 +41,7 @@ export async function runBattleSearch(userids: ID[], month: string, tierid: ID, throw err; } const [userid] = userids; - files = files.filter(item => item.startsWith(month)).map(item => `logs/${month}/${tierid}/${item}`); + files = files.filter(item => item.startsWith(month)).map(item => Monitor.logPath(`${month}/${tierid}/${item}`).path); if (useRipgrep) { // Matches non-word (including _ which counts as a word) characters between letters/numbers @@ -276,7 +276,7 @@ async function rustBattleSearch( const day = date.getDate().toString().padStart(2, '0'); directories.push( - FS(path.join('logs', `${year}-${month}`, format, `${year}-${month}-${day}`)).path + Monitor.logPath(path.join(`${year}-${month}`, format, `${year}-${month}-${day}`)).path ); } @@ -340,7 +340,7 @@ export const pages: Chat.PageTable = { buf += `

`; const months = Utils.sortBy( - (await FS('logs/').readdir()).filter(f => f.length === 7 && f.includes('-')), + (await Monitor.logPath('/').readdir()).filter(f => f.length === 7 && f.includes('-')), name => ({reverse: name}) ); if (!month) { @@ -357,7 +357,7 @@ export const pages: Chat.PageTable = { } const tierid = toID(formatid); - const tiers = Utils.sortBy(await FS(`logs/${month}/`).readdir(), tier => [ + const tiers = Utils.sortBy(await Monitor.logPath(`${month}/`).readdir(), tier => [ // First sort by gen with the latest being first tier.startsWith('gen') ? -parseInt(tier.charAt(3)) : -6, // Then sort alphabetically diff --git a/server/chat-plugins/chatlog.ts b/server/chat-plugins/chatlog.ts index 9120a1503e..413925f7c2 100644 --- a/server/chat-plugins/chatlog.ts +++ b/server/chat-plugins/chatlog.ts @@ -69,7 +69,7 @@ export class LogReaderRoom { return dates.map(x => x.month); } try { - const listing = await FS(`logs/chat/${this.roomid}`).readdir(); + const listing = await Monitor.logPath(`chat/${this.roomid}`).readdir(); return listing.filter(file => /^[0-9][0-9][0-9][0-9]-[0-9][0-9]$/.test(file)); } catch { return []; @@ -84,7 +84,7 @@ export class LogReaderRoom { return dates.map(x => x.date); } try { - const listing = await FS(`logs/chat/${this.roomid}/${month}`).readdir(); + const listing = await Monitor.logPath(`chat/${this.roomid}/${month}`).readdir(); return listing.filter(file => file.endsWith(".txt")).map(file => file.slice(0, -4)); } catch { return []; @@ -106,7 +106,7 @@ export class LogReaderRoom { }); } const month = LogReader.getMonth(day); - const log = FS(`logs/chat/${this.roomid}/${month}/${day}.txt`); + const log = Monitor.logPath(`chat/${this.roomid}/${month}/${day}.txt`); if (!await log.exists()) return null; return log.createReadStream().byLine(); } @@ -117,7 +117,7 @@ export const LogReader = new class { if (roomlogTable) { if (!(await roomlogTable.selectOne()`WHERE roomid = ${roomid}`)) return null; } else { - if (!await FS(`logs/chat/${roomid}`).exists()) return null; + if (!await Monitor.logPath(`chat/${roomid}`).exists()) return null; } return new LogReaderRoom(roomid); } @@ -127,7 +127,7 @@ export const LogReader = new class { const roomids = await roomlogTable.query()`SELECT DISTINCT roomid FROM roomlogs`; return roomids.map(x => x.roomid) as RoomID[]; } - const listing = await FS(`logs/chat`).readdir(); + const listing = await Monitor.logPath(`chat`).readdir(); return listing.filter(file => /^[a-z0-9-]+$/.test(file)) as RoomID[]; } @@ -474,10 +474,10 @@ export abstract class Searcher { buf += `Month: ${month}:
`; const nextMonth = LogReader.nextMonth(month); const prevMonth = LogReader.prevMonth(month); - if (FS(`logs/chat/${roomid}/${prevMonth}`).existsSync()) { + if (Monitor.logPath(`chat/${roomid}/${prevMonth}`).existsSync()) { buf += `Previous month`; } - if (FS(`logs/chat/${roomid}/${nextMonth}`).existsSync()) { + if (Monitor.logPath(`chat/${roomid}/${nextMonth}`).existsSync()) { buf += ` Next month`; } if (!results) { @@ -533,10 +533,10 @@ export abstract class Searcher { // this would normally be abstract, but it's very difficult with ripgrep // so it's easier to just do it the same way for both. async roomStats(room: RoomID, month: string) { - if (!FS(`logs/chat/${room}`).existsSync()) { + if (!Monitor.logPath(`chat/${room}`).existsSync()) { return LogViewer.error(Utils.html`Room ${room} not found.`); } - if (!FS(`logs/chat/${room}/${month}`).existsSync()) { + if (!Monitor.logPath(`chat/${room}/${month}`).existsSync()) { return LogViewer.error(Utils.html`Room ${room} does not have logs for the month ${month}.`); } const stats = await PM.query({ @@ -546,8 +546,8 @@ export abstract class Searcher { buf += `Total days with logs: ${stats.average.days}
`; const next = LogReader.nextMonth(month); const prev = LogReader.prevMonth(month); - const prevExists = FS(`logs/chat/${room}/${prev}`).existsSync(); - const nextExists = FS(`logs/chat/${room}/${next}`).existsSync(); + const prevExists = Monitor.logPath(`chat/${room}/${prev}`).existsSync(); + const nextExists = Monitor.logPath(`chat/${room}/${next}`).existsSync(); if (prevExists) { buf += `
Previous month`; buf += nextExists ? ` | ` : `
`; @@ -594,7 +594,7 @@ export abstract class Searcher { return buf; } async activityStats(room: RoomID, month: string) { - const days = (await FS(`logs/chat/${room}/${month}`).readdir()).map(f => f.slice(0, -4)); + const days = (await Monitor.logPath(`chat/${room}/${month}`).readdir()).map(f => f.slice(0, -4)); const stats: RoomStats[] = []; const today = Chat.toTimestamp(new Date()).split(' ')[0]; for (const day of days) { @@ -651,7 +651,7 @@ export abstract class Searcher { averagePresent: 0, day, }; - const path = FS(`logs/chat/${room}/${LogReader.getMonth(day)}/${day}.txt`); + const path = Monitor.logPath(`chat/${room}/${LogReader.getMonth(day)}/${day}.txt`); if (!path.existsSync()) return false; const stream = path.createReadStream(); let lastTime = new Date(day).getTime(); // start at beginning of day to be sure @@ -719,7 +719,7 @@ export class FSLogSearcher extends Searcher { this.results = 0; } async searchLinecounts(roomid: RoomID, month: string, user?: ID) { - const directory = FS(`logs/chat/${roomid}/${month}`); + const directory = Monitor.logPath(`chat/${roomid}/${month}`); if (!directory.existsSync()) { return this.renderLinecountResults(null, roomid, month, user); } @@ -727,7 +727,7 @@ export class FSLogSearcher extends Searcher { const results: {[date: string]: {[userid: string]: number}} = {}; for (const file of files) { const day = file.slice(0, -4); - const stream = FS(`logs/chat/${roomid}/${month}/${file}`).createReadStream(); + const stream = Monitor.logPath(`chat/${roomid}/${month}/${file}`).createReadStream(); for await (const line of stream.byLine()) { const parts = line.split('|').map(toID); const id = parts[2]; @@ -756,7 +756,7 @@ export class RipgrepLogSearcher extends Searcher { try { const options = [ '-e', search, - `logs/chat/${roomid}/${month}`, + Monitor.logPath(`chat/${roomid}/${month}`).path, '-i', ]; if (args) { @@ -899,7 +899,7 @@ if (!PM.isParentProcess) { PM.spawn(MAX_PROCESSES); } -const accessLog = FS(`logs/chatlog-access.txt`).createAppendStream(); +const accessLog = Monitor.logPath(`chatlog-access.txt`).createAppendStream(); export const pages: Chat.PageTable = { async chatlog(args, user, connection) { @@ -1018,7 +1018,7 @@ export const pages: Chat.PageTable = { let buf = `

${title}`; if (userid) buf += ` for ${userid}`; buf += `


    `; - const accessStream = FS(`logs/chatlog-access.txt`).createReadStream(); + const accessStream = Monitor.logPath(`chatlog-access.txt`).createReadStream(); for await (const line of accessStream.byLine()) { const [id, rest] = Utils.splitFirst(line, ': '); if (userid && id !== userid) continue; @@ -1294,7 +1294,7 @@ export const commands: Chat.ChatCommands = { if (target.length < 3) { return this.errorReply(`Too short of a search term.`); } - const files = await FS(`logs/chat`).readdir(); + const files = await Monitor.logPath(`chat`).readdir(); const buffer = []; for (const roomid of files) { if (roomid.startsWith('groupchat-') && roomid.includes(target)) { diff --git a/server/chat-plugins/helptickets.ts b/server/chat-plugins/helptickets.ts index bb3ca2dcaf..af036a72a3 100644 --- a/server/chat-plugins/helptickets.ts +++ b/server/chat-plugins/helptickets.ts @@ -169,7 +169,7 @@ export function writeStats(line: string) { const date = new Date(); const month = Chat.toTimestamp(date).split(' ')[0].split('-', 2).join('-'); try { - FS(`logs/tickets/${month}.tsv`).appendSync(line + '\n'); + Monitor.logPath(`tickets/${month}.tsv`).appendSync(line + '\n'); } catch (e: any) { if (e.code !== 'ENOENT') throw e; } @@ -506,7 +506,7 @@ export class HelpTicket extends Rooms.SimpleRoomGame { recommended: ticket.recommended, }; const date = Chat.toTimestamp(new Date()).split(' ')[0]; - void FS(`logs/tickets/${date.slice(0, -3)}.jsonl`).append(JSON.stringify(entry) + '\n'); + void Monitor.logPath(`tickets/${date.slice(0, -3)}.jsonl`).append(JSON.stringify(entry) + '\n'); } /** @@ -532,7 +532,7 @@ export class HelpTicket extends Rooms.SimpleRoomGame { let lines; try { lines = await ProcessManager.exec([ - `rg`, FS(`logs/tickets/${date ? `${date}.jsonl` : ''}`).path, ...args, + `rg`, Monitor.logPath(`tickets/${date ? `${date}.jsonl` : ''}`).path, ...args, ]); } catch (e: any) { if (e.message.includes('No such file or directory')) { @@ -552,7 +552,7 @@ export class HelpTicket extends Rooms.SimpleRoomGame { } } else { if (!date) throw new Chat.ErrorMessage(`Specify a month.`); - const path = FS(`logs/tickets/${date}.jsonl`); + const path = Monitor.logPath(`tickets/${date}.jsonl`); if (!path.existsSync()) { throw new Chat.ErrorMessage(`There are no logs for the month "${date}".`); } @@ -2084,7 +2084,7 @@ export const pages: Chat.PageTable = { } const dateUrl = Chat.toTimestamp(date).split(' ')[0].split('-', 2).join('-'); - const rawTicketStats = FS(`logs/tickets/${dateUrl}.tsv`).readIfExistsSync(); + const rawTicketStats = Monitor.logPath(`tickets/${dateUrl}.tsv`).readIfExistsSync(); if (!rawTicketStats) return `

    ${this.tr`No ticket stats found.`}
    `; // Calculate next/previous month for stats and validate stats exist for the month @@ -2110,13 +2110,13 @@ export const pages: Chat.PageTable = { const nextString = Chat.toTimestamp(nextDate).split(' ')[0].split('-', 2).join('-'); let buttonBar = ''; - if (FS(`logs/tickets/${prevString}.tsv`).readIfExistsSync()) { + if (Monitor.logPath(`tickets/${prevString}.tsv`).readIfExistsSync()) { buttonBar += `< ${this.tr`Previous Month`}`; } else { buttonBar += `< ${this.tr`Previous Month`}`; } buttonBar += `${this.tr`Ticket Stats`} ${this.tr`Staff Stats`}`; - if (FS(`logs/tickets/${nextString}.tsv`).readIfExistsSync()) { + if (Monitor.logPath(`tickets/${nextString}.tsv`).readIfExistsSync()) { buttonBar += `${this.tr`Next Month`} >`; } else { buttonBar += `${this.tr`Next Month`} >`; @@ -2945,14 +2945,14 @@ export const commands: Chat.ChatCommands = { if (!/[0-9]{4}-[0-9]{2}-[0-9]{2}/.test(date)) { return this.errorReply(`Invalid date (must be YYYY-MM-DD format).`); } - const logPath = FS(`logs/chat/help-${userid}/${date.slice(0, -3)}/${date}.txt`); + const logPath = Monitor.logPath(`chat/help-${userid}/${date.slice(0, -3)}/${date}.txt`); if (!(await logPath.exists())) { return this.errorReply(`There are no logs for tickets from '${userid}' on the date '${date}'.`); } - if (!(await FS(`logs/private/${userid}`).exists())) { - await FS(`logs/private/${userid}`).mkdirp(); + if (!(await Monitor.logPath(`private/${userid}`).exists())) { + await Monitor.logPath(`private/${userid}`).mkdirp(); } - await logPath.copyFile(`logs/private/${userid}/${date}.txt`); + await logPath.copyFile(Monitor.logPath(`private/${userid}/${date}.txt`).path); await logPath.write(''); // empty out the logfile this.globalModlog(`HELPTICKET PRIVATELOGS`, null, `${userid} (${date})`); this.privateGlobalModAction(`${user.name} set the ticket logs for '${userid}' on '${date}' to be private.`); @@ -2969,15 +2969,15 @@ export const commands: Chat.ChatCommands = { if (!/[0-9]{4}-[0-9]{2}-[0-9]{2}/.test(date)) { return this.errorReply(`Invalid date (must be YYYY-MM-DD format).`); } - const logPath = FS(`logs/private/${userid}/${date}.txt`); + const logPath = Monitor.logPath(`private/${userid}/${date}.txt`); if (!(await logPath.exists())) { return this.errorReply(`There are no logs for tickets from '${userid}' on the date '${date}'.`); } - const monthPath = FS(`logs/chat/help-${userid}/${date.slice(0, -3)}`); + const monthPath = Monitor.logPath(`chat/help-${userid}/${date.slice(0, -3)}`); if (!(await monthPath.exists())) { await monthPath.mkdirp(); } - await logPath.copyFile(`logs/chat/help-${userid}/${date.slice(0, -3)}/${date}.txt`); + await logPath.copyFile(Monitor.logPath(`chat/help-${userid}/${date.slice(0, -3)}/${date}.txt`).path); await logPath.unlinkIfExists(); this.globalModlog(`HELPTICKET PUBLICLOGS`, null, `${userid} (${date})`); this.privateGlobalModAction(`${user.name} set the ticket logs for '${userid}' on '${date}' to be public.`); diff --git a/server/chat-plugins/randombattles/winrates.ts b/server/chat-plugins/randombattles/winrates.ts index f6337d1367..4e3ba6cf14 100644 --- a/server/chat-plugins/randombattles/winrates.ts +++ b/server/chat-plugins/randombattles/winrates.ts @@ -21,13 +21,13 @@ interface FormatData { period?: number; // how often it resets - defaults to 1mo } -const STATS_PATH = 'logs/randbats/{{MONTH}}-winrates.json'; +const STATS_PATH = Monitor.logPath('randbats/{{MONTH}}-winrates.json').path; export const stats: Stats = getDefaultStats(); try { const path = STATS_PATH.replace('{{MONTH}}', getMonth()); - if (!FS('logs/randbats/').existsSync()) { - FS('logs/randbats/').mkdirSync(); + if (!Monitor.logPath('randbats/').existsSync()) { + Monitor.logPath('randbats/').mkdirSync(); } const savedStats = JSON.parse(FS(path).readSync()); stats.elo = savedStats.elo; diff --git a/server/chat-plugins/responder.ts b/server/chat-plugins/responder.ts index 062b67e0f4..2e92740bc0 100644 --- a/server/chat-plugins/responder.ts +++ b/server/chat-plugins/responder.ts @@ -12,7 +12,7 @@ import {LogViewer} from './chatlog'; import {roomFaqs, visualizeFaq} from './room-faqs'; const DATA_PATH = 'config/chat-plugins/responder.json'; -const LOG_PATH = 'logs/responder.jsonl'; +const LOG_PATH = Monitor.logPath('responder.jsonl').path; export let answererData: {[roomid: string]: PluginData} = {}; diff --git a/server/monitor.ts b/server/monitor.ts index 242dff5aff..0da9431d44 100644 --- a/server/monitor.ts +++ b/server/monitor.ts @@ -9,6 +9,7 @@ import {exec, ExecException, ExecOptions} from 'child_process'; import {crashlogger, FS} from "../lib"; +import * as pathModule from 'path'; const MONITOR_CLEAN_TIMEOUT = 2 * 60 * 60 * 1000; @@ -93,6 +94,13 @@ export const Monitor = new class { } } + logPath(path: string) { + if (Config.logsdir) { + return FS(pathModule.join(Config.logsdir, path)); + } + return FS(pathModule.join('logs', path)); + } + log(text: string) { this.notice(text); const staffRoom = Rooms.get('staff'); @@ -278,7 +286,7 @@ export const Monitor = new class { for (const i in this.networkUse) { buf += `${this.networkUse[i]}\t${this.networkCount[i]}\t${i}\n`; } - void FS('logs/networkuse.tsv').write(buf); + void Monitor.logPath('networkuse.tsv').write(buf); } clearNetworkUse() { @@ -333,8 +341,8 @@ export const Monitor = new class { async version() { let hash; try { - await FS('.git/index').copyFile('logs/.gitindex'); - const index = FS('logs/.gitindex'); + await FS('.git/index').copyFile(Monitor.logPath('.gitindex').path); + const index = Monitor.logPath('.gitindex'); const options = { cwd: __dirname, env: {GIT_INDEX_FILE: index.path}, diff --git a/server/room-battle.ts b/server/room-battle.ts index c358202899..d151b5c3c3 100644 --- a/server/room-battle.ts +++ b/server/room-battle.ts @@ -12,7 +12,7 @@ */ import {execSync} from "child_process"; -import {FS, Repl, ProcessManager, type Streams} from '../lib'; +import {Repl, ProcessManager, type Streams} from '../lib'; import {BattleStream} from "../sim/battle-stream"; import {RoomGamePlayer, RoomGame} from "./room-game"; import type {Tournament} from './tournaments/index'; @@ -909,10 +909,10 @@ export class RoomBattle extends RoomGame { const logsubfolder = Chat.toTimestamp(date).split(' ')[0]; const logfolder = logsubfolder.split('-', 2).join('-'); const tier = Dex.formats.get(this.room.format).id; - const logpath = `logs/${logfolder}/${tier}/${logsubfolder}/`; + const logpath = `${logfolder}/${tier}/${logsubfolder}/`; - await FS(logpath).mkdirp(); - await FS(`${logpath}${this.room.getReplayData().id}.log.json`).write(JSON.stringify(logData)); + await Monitor.logPath(logpath).mkdirp(); + await Monitor.logPath(`${logpath}${this.room.getReplayData().id}.log.json`).write(JSON.stringify(logData)); // console.log(JSON.stringify(logData)); } override onConnect(user: User, connection: Connection | null = null) { diff --git a/server/roomlogs.ts b/server/roomlogs.ts index 6b0d9b8d05..8aea6334e1 100644 --- a/server/roomlogs.ts +++ b/server/roomlogs.ts @@ -134,28 +134,28 @@ export class Roomlog { const date = new Date(); const dateString = Chat.toTimestamp(date).split(' ')[0]; const monthString = dateString.split('-', 2).join('-'); - const basepath = `logs/chat/${this.roomid}/`; + const basepath = `chat/${this.roomid}/`; const relpath = `${monthString}/${dateString}.txt`; if (relpath === this.roomlogFilename) return; if (sync) { - FS(basepath + monthString).mkdirpSync(); + Monitor.logPath(basepath + monthString).mkdirpSync(); } else { - await FS(basepath + monthString).mkdirp(); + await Monitor.logPath(basepath + monthString).mkdirp(); if (this.roomlogStream === null) return; } this.roomlogFilename = relpath; if (this.roomlogStream) void this.roomlogStream.writeEnd(); - this.roomlogStream = FS(basepath + relpath).createAppendStream(); + this.roomlogStream = Monitor.logPath(basepath + relpath).createAppendStream(); // Create a symlink to today's lobby log. // These operations need to be synchronous, but it's okay // because this code is only executed once every 24 hours. const link0 = basepath + 'today.txt.0'; - FS(link0).unlinkIfExistsSync(); + Monitor.logPath(link0).unlinkIfExistsSync(); try { - FS(link0).symlinkToSync(relpath); // intentionally a relative link - FS(link0).renameSync(basepath + 'today.txt'); + Monitor.logPath(link0).symlinkToSync(relpath); // intentionally a relative link + Monitor.logPath(link0).renameSync(basepath + 'today.txt'); } catch {} // OS might not support symlinks or atomic rename if (!Roomlogs.rollLogTimer) void Roomlogs.rollLogs(); } @@ -296,15 +296,15 @@ export class Roomlog { await roomlogTable.updateAll({roomid: this.roomid})`WHERE roomid = ${this.roomid}`; return true; } else { - const roomlogPath = `logs/chat`; + const roomlogPath = `chat`; const roomlogStreamExisted = this.roomlogStream !== null; await this.destroy(); const [roomlogExists, newRoomlogExists] = await Promise.all([ - FS(roomlogPath + `/${this.roomid}`).exists(), - FS(roomlogPath + `/${newID}`).exists(), + Monitor.logPath(roomlogPath + `/${this.roomid}`).exists(), + Monitor.logPath(roomlogPath + `/${newID}`).exists(), ]); if (roomlogExists && !newRoomlogExists) { - await FS(roomlogPath + `/${this.roomid}`).rename(roomlogPath + `/${newID}`); + await Monitor.logPath(roomlogPath + `/${this.roomid}`).rename(Monitor.logPath(roomlogPath + `/${newID}`).path); } await Rooms.Modlog.rename(this.roomid, newID); this.roomid = newID; diff --git a/server/rooms.ts b/server/rooms.ts index 39f8429a33..273b983ed0 100644 --- a/server/rooms.ts +++ b/server/rooms.ts @@ -1265,7 +1265,7 @@ export class GlobalRoomState { // init battle room logging if (Config.logladderip) { - this.ladderIpLog = FS('logs/ladderip/ladderip.txt').createAppendStream(); + this.ladderIpLog = Monitor.logPath('ladderip/ladderip.txt').createAppendStream(); } else { // Prevent there from being two possible hidden classes an instance // of GlobalRoom can have. @@ -1289,7 +1289,7 @@ export class GlobalRoomState { let lastBattle; try { - lastBattle = FS('logs/lastbattle.txt').readSync('utf8'); + lastBattle = Monitor.logPath('lastbattle.txt').readSync('utf8'); } catch {} this.lastBattle = Number(lastBattle) || 0; this.lastWrittenBattle = this.lastBattle; @@ -1346,7 +1346,7 @@ export class GlobalRoomState { async saveBattles() { let count = 0; - const out = FS('logs/battles.jsonl.progress').createAppendStream(); + const out = Monitor.logPath('battles.jsonl.progress').createAppendStream(); for (const room of Rooms.rooms.values()) { if (!room.battle || room.battle.ended) continue; room.battle.frozen = true; @@ -1357,7 +1357,7 @@ export class GlobalRoomState { count++; } await out.writeEnd(); - await FS('logs/battles.jsonl.progress').rename('logs/battles.jsonl'); + await Monitor.logPath('battles.jsonl.progress').rename(Monitor.logPath('battles.jsonl').path); return count; } @@ -1374,7 +1374,7 @@ export class GlobalRoomState { let count = 0; let input; try { - const stream = FS('logs/battles.jsonl').createReadStream(); + const stream = Monitor.logPath('battles.jsonl').createReadStream(); await stream.fd; input = stream.byLine(); } catch (e) { @@ -1387,7 +1387,7 @@ export class GlobalRoomState { for (const u of Users.users.values()) { u.send(`|pm|&|${u.getIdentity()}|/uhtmlchange restartmsg,`); } - await FS('logs/battles.jsonl').unlinkIfExists(); + await Monitor.logPath('battles.jsonl').unlinkIfExists(); Monitor.notice(`Loaded ${count} battles in ${Date.now() - startTime}ms`); this.battlesLoading = false; } @@ -1426,7 +1426,7 @@ export class GlobalRoomState { if (this.lastBattle < this.lastWrittenBattle) return; this.lastWrittenBattle = this.lastBattle + LAST_BATTLE_WRITE_THROTTLE; } - FS('logs/lastbattle.txt').writeUpdate( + Monitor.logPath('lastbattle.txt').writeUpdate( () => `${this.lastWrittenBattle}` ); } diff --git a/server/users.ts b/server/users.ts index abc54fa164..5f1447e982 100644 --- a/server/users.ts +++ b/server/users.ts @@ -45,7 +45,7 @@ const PERMALOCK_CACHE_TIME = 30 * 24 * 60 * 60 * 1000; // 30 days const DEFAULT_TRAINER_SPRITES = [1, 2, 101, 102, 169, 170, 265, 266]; -import {FS, Utils, ProcessManager} from '../lib'; +import {Utils, ProcessManager} from '../lib'; import { Auth, GlobalAuth, SECTIONLEADER_SYMBOL, PLAYER_SYMBOL, HOST_SYMBOL, RoomPermission, GlobalPermission, } from './user-groups'; @@ -1617,7 +1617,7 @@ function logGhostConnections(threshold: number): Promise { } } return buffer.length ? - FS(`logs/ghosts-${process.pid}.log`).append(buffer.join('\r\n') + '\r\n') : + Monitor.logPath(`ghosts-${process.pid}.log`).append(buffer.join('\r\n') + '\r\n') : Promise.resolve(); } @@ -1642,7 +1642,7 @@ function socketConnect( } // Emergency mode connections logging if (Config.emergency) { - void FS('logs/cons.emergency.log').append('[' + ip + ']\n'); + void Monitor.logPath('cons.emergency.log').append('[' + ip + ']\n'); } const user = new User(connection); @@ -1732,7 +1732,7 @@ function socketReceive(worker: ProcessManager.StreamWorker, workerid: number, so } // Emergency logging if (Config.emergency) { - void FS('logs/emergency.log').append(`[${user} (${connection.ip})] ${roomId}|${message}\n`); + void Monitor.logPath('emergency.log').append(`[${user} (${connection.ip})] ${roomId}|${message}\n`); } for (const line of lines) {