-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwebsockets.ts
More file actions
415 lines (322 loc) · 13.3 KB
/
websockets.ts
File metadata and controls
415 lines (322 loc) · 13.3 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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//external modules
import { Server, createRedisAdapter, createRedisClient, type Socket } from "https://deno.land/x/socket_io@0.2.1/mod.ts";
import "https://deno.land/x/dotenv@v3.2.2/load.ts";
//internal modules
import { getRandomKey } from './keyGen.ts';
import { redis, Key, User, _R_getAllUsersData, _R_exitUserFromSocket, _R_deleteChatKey, _R_joinChat } from '../db/database.ts';
import { validatename, validateKey } from './utils.ts';
//get client url from .env file which will be set to CORS
const { clienturl, host, port, password, devMode } = Deno.env.toObject();
const allowAllOrigins = devMode === 'true';
const [pubClient, subClient] = await Promise.all([
createRedisClient({
hostname: host,
port: parseInt(port),
password,
}),
createRedisClient({
hostname: host,
port: parseInt(port),
password,
}),
]);
pubClient.hset('server', 'status', 'online');
//initialize socket.io server
export const io = new Server({
cors: {
origin: allowAllOrigins ? '*' : [clienturl],
methods: ["GET", "POST"],
credentials: !allowAllOrigins,
},
adapter: createRedisAdapter(pubClient, subClient),
});
console.log('Socket.io server initialized');
try {
//listen for connection
io.on('connection', (socket) => {
socket.on('fetchKeyData', async (key: string, ssr: boolean, callback: (data: object | null) => void) => {
try {
if (!redis.isConnected) {
console.log('Redis not connected');
redis.connect();
callback({ success: false, message: 'Database disconnected', statusCode: 502, icon: 'fa-solid fa-triangle-exclamation', users: {}, maxUsers: null })
return;
}
if (!validateKey(key)) {
callback({ success: false, message: 'Invalid Key', statusCode: 400, icon: 'fa-solid fa-triangle-exclamation', users: {}, maxUsers: null });
return;
}
const exists = await redis.exists(`chat:${key}`);
if (!exists) {
callback({ success: false, message: 'Key Does Not Exist', statusCode: 404, icon: 'fa-solid fa-ghost', users: {}, maxUsers: null });
return;
}
const keyData = await redis.hmget(`chat:${key}`, 'activeUsers', 'maxUsers');
if (!keyData) {
callback({ success: false, message: 'Key Data Not Found', statusCode: 404, icon: 'fa-solid fa-ghost', users: {}, maxUsers: null });
return;
}
const activeUsers = parseInt(keyData[0] as string);
const maxUsers = parseInt(keyData[1] as string);
if (activeUsers >= maxUsers) {
callback({ success: false, message: 'Key Full', statusCode: 401, icon: 'fa-solid fa-door-closed', users: {}, maxUsers: null });
return;
}
const users = await _R_getAllUsersData(key);
if (!ssr) {
socket.join(`waitingRoom:${key}`);
console.log(socket.id, 'joined waiting room for key: ', key);
}
callback({ success: true, message: 'Available', statusCode: 200, icon: '', users: { ...users }, maxUsers: maxUsers });
} catch (error) {
console.error(error);
callback({ success: false, message: 'Server Error', statusCode: 500, icon: 'fa-solid fa-triangle-exclamation', users: {}, maxUsers: null });
}
});
socket.on('createChat', async (avatar: string, maxUsers: number, publicKey: string, callback: (data: object | null) => void) => {
try {
if (!redis.isConnected) {
callback({ success: false, message: 'Database disconnected', statusCode: 502, icon: 'fa-solid fa-triangle-exclamation', users: {}, maxUsers: null })
//try to reconnect
redis.connect();
return;
}
if (!validatename(avatar)) {
callback({ success: false, message: 'Invalid avatar', icon: 'fa-solid fa-triangle-exclamation' });
return;
}
if (maxUsers < 2 || maxUsers > 10) {
callback({ success: false, message: 'Invalid Max Users', icon: 'fa-solid fa-triangle-exclamation' });
return;
}
const uid = socket.id;
const key = await getRandomKey();
socket.join(`chat:${key}`);
socket.leave(`waitingRoom:${key}`);
const chatKey: Key = {
keyId: key,
activeUsers: 1,
maxUsers,
admin: uid,
createdAt: Date.now(),
}
const user: User = {
avatar,
uid,
publicKey,
joinedAt: Date.now(),
}
await _R_joinChat(true, chatKey, user);
callback({ success: true, message: 'Chat Created', key, userId: uid, maxUsers: maxUsers, user: user });
//get avatar, and id of all users in the room
//omit the joinedAt and public key
const dataForWaitingRoom = { [uid]: { avatar } };
io.in(`waitingRoom:${key}`).emit('updateUserListWR', dataForWaitingRoom);
socket.on('disconnect', async () => {
console.log(`Chat Socket ${socket.id} Disconnected`);
await exitSocket(socket, key);
});
socket.on('leaveChat', (destroy: boolean) => exitHandler(destroy, key, socket));
} catch (error) {
console.error(error);
callback({ success: false, message: 'Chat Creation Failed', icon: 'fa-solid fa-triangle-exclamation' });
}
});
socket.on('joinChat', async (key: string, avatar: string, publicKey: string, callback: (data: object | null) => void) => {
try {
console.log('joinChat requested');
if (!redis.isConnected) {
callback({ success: false, message: 'Database disconnected', statusCode: 502, icon: 'fa-solid fa-triangle-exclamation' })
//try to reconnect
redis.connect();
return;
}
if (!validateKey(key)) {
callback({ success: false, message: 'Invalid Key', icon: 'fa-solid fa-triangle-exclamation' });
return;
}
if (!validatename(avatar)) {
callback({ success: false, message: 'Invalid avatar', icon: 'fa-solid fa-triangle-exclamation' });
return;
}
if (await redis.exists(`chat:${key}`)) {
const keyData = await redis.hmget(`chat:${key}`, 'activeUsers', 'maxUsers', 'admin');
if (keyData) {
const activeUsers = parseInt(keyData[0] as string);
const maxUsers = parseInt(keyData[1] as string);
const admin = keyData[2] as string;
if (activeUsers >= maxUsers) {
callback({ success: false, message: 'Chat Full', icon: 'fa-solid fa-door-closed' });
return;
}
const uid = socket.id;
const me: User = {
avatar,
uid,
publicKey,
joinedAt: Date.now(),
};
socket.join(`chat:${key}`);
socket.leave(`waitingRoom:${key}`);
await _R_joinChat(false, { keyId: key }, me);
// 'avatar', 'key', 'publicKey' are stored in redis
let users: { [key: string]: Omit<User, 'joined'> } = {}; //omit the joined property
users = await _R_getAllUsersData(key) as { [key: string]: Omit<User, 'joined'> };
callback({ success: true, message: 'Chat Joined', userId: uid, admin: admin, maxUsers: maxUsers, users });
//sent the users detail to the waiting room but exclude public key and joinedAt
const dataForWaitingRoom = Object.keys(users).reduce((acc, curr) => {
const { avatar } = users[curr];
acc[curr] = { avatar };
return acc;
}, {} as { [key: string]: { avatar: string } });
dataForWaitingRoom[uid] = { avatar };
io.in(`waitingRoom:${key}`).emit('updateUserListWR', dataForWaitingRoom);
socket.in(`chat:${key}`).emit('newUser', { avatar, uid, publicKey });
socket.on('disconnect', async () => {
console.log(`Chat Socket ${socket.id} Disconnected`);
await exitSocket(socket, key);
});
socket.on('leaveChat', (destroy: boolean) => exitHandler(destroy, key, socket));
} else {
// Handle the case where the data doesn't exist or is null.
callback({ success: false, message: 'Key Data Not Found', icon: 'fa-solid fa-ghost' });
}
} else {
callback({ success: false, message: 'Key Does Not Exist', icon: 'fa-solid fa-ghost' });
return;
}
} catch (error) {
console.error(error);
callback({ success: false, message: 'Chat Join Failed' });
}
});
socket.on('newMessage', (message, key: string, smKeys: {[key: string]: ArrayBuffer}, callback: (data: string | null) => void) => {
const messageId = crypto.randomUUID();
//get all users in the room by the socket and room name (key)
io.in(`chat:${key}`).fetchSockets().then((sockets) => {
try {
sockets.forEach((soc) => {
if (soc.id !== socket.id) {
const smKey = smKeys[soc.id];
soc.emit('newMessage', message, smKey, messageId);
}
});
} catch (error) {
console.error('Error broadcasting message', error);
}
});
callback(messageId);
});
//socket.emit('editMessage', encryptedMessage, chatRoomStore.value.Key, smKeys
socket.on('editMessage', (message: string, key: string, smKeys: {[key: string]: ArrayBuffer}, callback: () => void) => {
//everyone in room including sender
io.in(`chat:${key}`).fetchSockets().then((sockets) => {
try {
sockets.forEach((soc) => {
if (soc.id !== socket.id) {
const smKey = smKeys[soc.id];
soc.emit('editMessage', message, smKey);
}
});
} catch (error) {
console.error('Error broadcasting edited message', error);
}
});
callback();
});
socket.on('deleteMessage', (messageId: string, key: string, userId: string) => {
//send back to all users in the room including the sender
io.in(`chat:${key}`).emit('deleteMessage', messageId, userId);
});
socket.on('react', (messageId: string, key: string, userId: string, react: string) => {
//everyone in room including sender
io.in(`chat:${key}`).emit('react', messageId, userId, react);
});
socket.on('seen', (uid: string, key: string, msgId: string) => {
//broadcast
socket.in(`chat:${key}`).emit('seen', uid, msgId);
});
socket.on('typing', (uid: string, key: string, event: string) => {
//broadcast
socket.in(`chat:${key}`).emit('typing', uid, event);
});
socket.on('location', (position, key, uid) => {
const messageId = crypto.randomUUID();
//everyone in room including sender
io.in(`chat:${key}`).emit('location', position, messageId, uid);
});
});
} catch (error) {
console.error(error);
}
async function exitHandler(destroy: boolean, key: string, socket: Socket) {
try {
if (destroy) {
//delete the chat and empty the room only if the user is the admin
if (await redis.hget(`chat:${key}`, 'admin') !== socket.id) {
console.log('Not an admin');
return;
}
await _R_deleteChatKey(key, socket.id);
io.in(`chat:${key}`).emit('selfDestruct', 'Chat destroyed🥺');
io.in(`waitingRoom:${key}`).emit('updateUserListWR', {});
//empty the chat room
socket.rooms.delete(`chat:${key}`);
socket.rooms.delete(`waitingRoom:${key}`);
} else {
await exitSocket(socket, key);
socket.emit('selfDestruct', 'You left the chat🥺');
}
} catch (error) {
console.error(error);
}
}
async function exitSocket(socket: Socket, key: string) {
try {
socket.leave(`waitingRoom:${key}`);
socket.leave(`chat:${key}`);
//if socket not exists in redis, return
if (!await redis.exists(`uid:${socket.id}`)) {
return;
}
//get uid from redis
let data = await redis.hmget(`uid:${socket.id}`, 'avatar', 'uid');
if (!data) {
return;
}
const [avatar] = data as [string, string];
await _R_exitUserFromSocket(key, socket.id);
console.log(`${avatar} left ${key}`);
socket.in(`chat:${key}`).emit('userLeft', socket.id);
data = await redis.hmget(`chat:${key}`, 'activeUsers');
const [activeUsers] = data as unknown as [number];
if (activeUsers < 1) {
//if folder exists,
Deno.stat('./uploads/' + key)
.then((info) => {
if (info.isDirectory) {
Deno.remove('./uploads/' + key, { recursive: true }).then(() => {
console.log('Deleted folder', key);
}).catch((err) => {
console.log(`Unable to delete folder ${key}. Reason: ${err}`);
});
}
})
.catch(() => {
console.log('No folder found to clean for key: ', key);
});
await _R_deleteChatKey(key, socket.id);
io.in(`waitingRoom:${key}`).emit('updateUserListWR', {});
console.log('Chat deleted on', key);
return;
} else {
const users = await _R_getAllUsersData(key) as { [key: string]: Omit<User, 'joined'> };
if (!users) {
return;
}
io.in(`waitingRoom:${key}`).emit('updateUserListWR', users);
}
} catch (error) {
console.error(error);
}
}