This repository was archived by the owner on Apr 4, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathroom.ts
More file actions
204 lines (163 loc) · 4.43 KB
/
room.ts
File metadata and controls
204 lines (163 loc) · 4.43 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
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
import { Replica } from 'dog';
import type { Bindings } from './types';
import type { Socket, Gossip } from 'dog';
type Message = {
uid: string;
type: string;
};
type MessageData =
| { type: 'req:connected' }
| { type: 'req:user:list' }
| { type: 'msg'; text: string };
type Output = {
type: string;
from?: string;
time: number;
}
type Note = Gossip.Message & {
type: 'intra:user:list';
}
export class Room extends Replica<Bindings> {
users = new Map<string, number>();
link(env: Bindings) {
return {
parent: env.LOBBY,
self: env.ROOM,
};
}
async receive(req: Request) {
console.log('[ HELLO ][receive] req.url', req.url);
let { pathname, searchParams } = new URL(req.url);
if (pathname === '/ws') {
return this.connect(req);
}
if (pathname === '/broadcast') {
await this.broadcast({
type: 'user:msg',
from: 'HTTP',
text: 'SENT VIA "/broadcast" HTTP route',
time: Date.now(),
});
return new Response('DONE');
}
if (pathname === '/whisper') {
let target = searchParams.get('target') || 'aaa';
await this.whisper(target, {
type: 'user:msg',
from: 'HTTP',
text: 'SENT VIA "/whisper" HTTP route',
time: Date.now(),
meta: 'whisper',
to: target,
});
return new Response('DONE');
}
if (pathname === '/emit') {
this.emit({
type: 'user:msg',
from: 'HTTP',
text: 'SENT VIA "/emit" HTTP route',
time: Date.now(),
meta: 'group'
});
return new Response('DONE');
}
// NOTE: can employ whatever routing logic
return new Response(`PATH: "${pathname}"`);
}
onopen(socket: Socket) {
console.log('[ HELLO ][onopen]', socket.uid);
let output: Output = {
type: 'user:join',
from: socket.uid,
time: Date.now(),
};
socket.broadcast(output, true);
this.users.set(socket.uid, output.time);
}
onclose(socket: Socket) {
console.log('[ HELLO ][onclose]');
let output: Output = {
type: 'user:exit',
from: socket.uid,
time: Date.now(),
}
socket.broadcast(output);
this.users.delete(socket.uid);
}
async ongossip(msg: Note): Promise<Gossip.Payload> {
if (msg.type === 'intra:user:list') {
return [ ...this.users.keys() ];
}
throw new Error(`Missing: "${msg.type}" ongossip`);
}
async onmessage(socket: Socket, data: string) {
// raw broadcast channel
let input = JSON.parse(data) as Message & MessageData;
console.log('[room] onmessage', input);
input.uid = input.uid || socket.uid;
if (input.type === 'req:connected') {
let output: Output = {
type: 'user:connected',
from: input.uid,
time: Date.now(),
}
// save the `uid`::Date association
this.users.set(input.uid, output.time);
return socket.broadcast(JSON.stringify(output), true);
}
// send down a list of all connected users
if (input.type === 'req:user:list') {
let results = await this.gossip<Note>({
type: 'intra:user:list'
}) as string[][];
let list = new Set<string>(results.flat());
for (let [user] of this.users) list.add(user);
let output: Output & { list: string[] } = {
type: 'user:list',
list: [...list],
time: Date.now(),
};
return socket.send(
JSON.stringify(output)
);
}
if (input.type === 'msg') {
let text = input.text.trim();
let output: Output & { text: string, to?: string; meta?: string } = {
type: 'user:msg',
from: socket.uid,
text: text,
time: Date.now(),
}
// slash commands~!
// ---
let match: RegExpExecArray | null;
// group chat: "/group <text>" || "/g <text>"
if (match = /^([/](?:g|group)\s+)/.exec(text)) {
output.meta = 'group'; // group only
output.text = text.substring(match[0].length);
return socket.emit(output, true);
}
// whisper: "/w <target> <text>" || "/msg <target> <text>"
if (match = /^([/](?:w|msg)\s+(?<target>[^\s]+))\s+/.exec(text)) {
let target = match.groups!.target;
output.text = text.substring(match[0].length);
output.meta = 'whisper';
output.to = target;
// ensure it's sent to target first
await socket.whisper(target, output);
// then confirm w/ sender by echoing msg
return socket.send(JSON.stringify(output));
}
// all chat (default): "/all <text>" || "/a <text>"
if (match = /^([/](?:a|all)\s+)/.exec(text)) {
output.text = text.substring(match[0].length);
return socket.broadcast(output, true);
}
return socket.broadcast(output, true);
}
// catch all: broadcast
socket.broadcast(input, true);
}
}