-
Notifications
You must be signed in to change notification settings - Fork 0
/
roomlogs.js
285 lines (268 loc) · 7.4 KB
/
roomlogs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
* Roomlogs
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This handles data storage for rooms.
*
* @license MIT license
*/
'use strict';
const FS = require('./lib/fs');
/**
* Most rooms have three logs:
* - scrollback
* - roomlog
* - modlog
* This class keeps track of all three.
*
* The scrollback is stored in memory, and is the log you get when you
* join the room. It does not get moderator messages.
*
* The modlog is stored in
* `logs/modlog/modlog_<ROOMID>.txt`
* It contains moderator messages, formatted for ease of search.
*
* The roomlog is stored in
* `logs/chat/<ROOMID>/<YEAR>-<MONTH>/<YEAR>-<MONTH>-<DAY>.txt`
* It contains (nearly) everything.
*/
class Roomlog {
/**
* @param {Room} room
*/
constructor(room, options = {}) {
this.id = room.id;
/**
* Scrollback log
* @type {string[]}
*/
this.log = [];
this.broadcastBuffer = '';
/**
* Battle rooms are multichannel, which means their logs are split
* into four channels, public, p1, p2, full.
*/
this.isMultichannel = !!options.isMultichannel;
/**
* Chat rooms auto-truncate, which means it only stores the recent
* messages, if there are more.
*/
this.autoTruncate = !!options.autoTruncate;
/**
* Chat rooms include timestamps.
*/
this.logTimes = !!options.logTimes;
/**
* undefined = uninitialized,
* null = disabled
* @type {WriteStream? | undefined}
*/
this.modlogStream = undefined;
/**
* undefined = uninitialized,
* null = disabled
* @type {WriteStream? | undefined}
*/
this.roomlogStream = undefined;
// modlog/roomlog state
this.sharedModlog = false;
// TypeScript bug: can't infer
/** @type {string} */
this.roomlogFilename = '';
this.setupModlogStream();
this.setupRoomlogStream(true);
}
getScrollback(channel = 0) {
let log = this.log;
if (this.logTimes) log = [`|:|${~~(Date.now() / 1000)}`].concat(log);
if (!this.isMultichannel) {
return log.join('\n') + '\n';
}
log = [];
for (let i = 0; i < this.log.length; ++i) {
let line = this.log[i];
if (line === '|split') {
log.push(this.log[i + channel + 1]);
i += 4;
} else {
log.push(line);
}
}
let textLog = log.join('\n') + '\n';
if (channel === 0) {
return textLog.replace(/\n\|choice\|\|\n/g, '\n').replace(/\n\|seed\|\n/g, '\n');
}
return textLog;
}
setupModlogStream() {
if (this.modlogStream !== undefined) return;
if (!this.id.includes('-')) {
this.modlogStream = FS(`logs/modlog/modlog_${this.id}.txt`).createAppendStream();
return;
}
const sharedStreamId = this.id.split('-')[0];
let stream = Roomlogs.sharedModlogs.get(sharedStreamId);
if (!stream) {
stream = FS(`logs/modlog/modlog_${sharedStreamId}.txt`).createAppendStream();
Roomlogs.sharedModlogs.set(sharedStreamId, stream);
}
this.modlogStream = stream;
this.sharedModlog = true;
}
async setupRoomlogStream(sync = false) {
if (this.roomlogStream === null) return;
if (!Config.logchat) {
this.roomlogStream = null;
return;
}
if (this.id.startsWith('battle-')) {
this.roomlogStream = null;
return;
}
const date = new Date();
const dateString = Chat.toTimestamp(date).split(' ')[0];
const monthString = dateString.split('-', 2).join('-');
const basepath = `logs/chat/${this.id}/`;
const relpath = `${monthString}/${dateString}.txt`;
if (relpath === this.roomlogFilename) return;
if (sync) {
FS(basepath + monthString).mkdirpSync();
} else {
await FS(basepath + monthString).mkdirp();
if (this.roomlogStream === null) return;
}
this.roomlogFilename = relpath;
if (this.roomlogStream) this.roomlogStream.end();
this.roomlogStream = FS(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.
let link0 = basepath + 'today.txt.0';
FS(link0).unlinkIfExistsSync();
try {
FS(link0).symlinkToSync(relpath); // intentionally a relative link
FS(link0).renameSync(basepath + 'today.txt');
} catch (e) {} // OS might not support symlinks or atomic rename
if (!Roomlogs.rollLogTimer) Roomlogs.rollLogs();
}
/**
* @param {string} message
*/
add(message) {
if (message.startsWith('|uhtmlchange|')) return this.uhtmlchange(message);
this.roomlog(message);
if (this.logTimes && message.startsWith('|c|')) {
message = '|c:|' + (~~(Date.now() / 1000)) + '|' + message.substr(3);
}
this.log.push(message);
this.broadcastBuffer += message + '\n';
return this;
}
/**
* @param {string} username
*/
hasUsername(username) {
const userid = toId(username);
for (const line of this.log) {
if (line.startsWith('|c:|')) {
const curUserid = toId(line.split('|', 4)[3]);
if (curUserid === userid) return true;
} else if (line.startsWith('|c|')) {
const curUserid = toId(line.split('|', 3)[2]);
if (curUserid === userid) return true;
}
}
return false;
}
/**
* @param {string} message
*/
uhtmlchange(message) {
let thirdPipe = message.indexOf('|', 13);
let originalStart = '|uhtml|' + message.slice(13, thirdPipe + 1);
for (let i = 0; i < this.log.length; i++) {
if (this.log[i].startsWith(originalStart)) {
this.log[i] = originalStart + message.slice(thirdPipe + 1);
break;
}
}
this.broadcastBuffer += message + '\n';
return this;
}
/**
* @param {string} message
*/
roomlog(message, date = new Date()) {
if (!this.roomlogStream) return;
const timestamp = Chat.toTimestamp(date).split(' ')[1] + ' ';
message = message.replace(/<img[^>]* src="data:image\/png;base64,[^">]+"[^>]*>/g, '');
this.roomlogStream.write(timestamp + message + '\n');
}
/**
* @param {string} message
*/
modlog(message) {
if (!this.modlogStream) return;
this.modlogStream.write('[' + (new Date().toJSON()) + '] ' + message + '\n');
}
static async rollLogs() {
if (Roomlogs.rollLogTimer === true) return;
if (Roomlogs.rollLogTimer) {
clearTimeout(Roomlogs.rollLogTimer);
}
Roomlogs.rollLogTimer = true;
for (const log of Roomlogs.roomlogs.values()) {
await log.setupRoomlogStream();
}
const time = Date.now();
const nextMidnight = new Date(time + 24 * 60 * 60 * 1000);
nextMidnight.setHours(0, 0, 1);
Roomlogs.rollLogTimer = setTimeout(() => Roomlog.rollLogs(), nextMidnight.getTime() - time);
}
truncate() {
if (!this.autoTruncate) return;
if (this.log.length > 100) {
this.log.splice(0, this.log.length - 100);
}
}
destroy() {
let promises = [];
if (this.sharedModlog) {
this.modlogStream = null;
}
if (this.modlogStream) {
promises.push(this.modlogStream.end());
this.modlogStream = null;
}
if (this.roomlogStream) {
promises.push(this.roomlogStream.end());
this.roomlogStream = null;
}
Roomlogs.roomlogs.delete(this.id);
return Promise.all(promises);
}
}
/** @type {Map<string, WriteStream>} */
const sharedModlogs = new Map();
/** @type {Map<string, Roomlog>} */
const roomlogs = new Map();
/**
* @param {Room} room
*/
function createRoomlog(room, options = {}) {
let roomlog = Roomlogs.roomlogs.get(room.id);
if (roomlog) throw new Error(`Roomlog ${room.id} already exists`);
roomlog = new Roomlog(room, options);
Roomlogs.roomlogs.set(room.id, roomlog);
return roomlog;
}
const Roomlogs = {
create: createRoomlog,
Roomlog,
roomlogs,
sharedModlogs,
rollLogs: Roomlog.rollLogs,
/** @type {NodeJS.Timer? | true} */
rollLogTimer: null,
};
module.exports = Roomlogs;