-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroom.ts
More file actions
63 lines (55 loc) · 1.54 KB
/
room.ts
File metadata and controls
63 lines (55 loc) · 1.54 KB
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
import { Client } from './client';
import * as fsProm from 'fs/promises';
import * as fs from 'fs';
export class Room {
private chatLog: string;
private logBuffer: string[] = [];
private maxBufferedLines = 2;
constructor(
public clients: Map<string, Client>,
public name: string,
public owner: null | Client,
public topic?: string,
) {
this.chatLog = `./${name}.log`;
}
broadcast(sender: Client, msg: string, isSystemMessage = false) {
const chatMsg = `[${new Date().toISOString()}::<${this.name}>] ${msg.trim()}\n`;
for (const [_, client] of this.clients) {
if (
sender.socket === client.socket ||
(isSystemMessage && client.currentRoom.name !== this.name)
) {
continue;
}
client.socket.write(chatMsg);
}
this.addToLogBuffer(chatMsg.trim());
}
private addToLogBuffer(msg: string) {
this.logBuffer.push(msg);
if (this.logBuffer.length > this.maxBufferedLines) {
this.writeLog(this.logBuffer.join('\n')).then(() => {
this.logBuffer = [];
});
}
}
flushLogsSync() {
if (this.logBuffer.length) {
fs.writeFileSync(this.chatLog, `\n${this.logBuffer.join('\n')}`, {
flag: 'a+',
});
return true;
}
return false;
}
async writeLog(content: string) {
try {
await fsProm.writeFile(this.chatLog, `\n${content}`, { flag: 'a+' });
} catch (e: any) {
console.error("Couldn't write to", this.chatLog);
console.error(e);
}
}
}
export const ALL_ROOMS = new Map<string, Room>();