-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
467 lines (381 loc) · 14.9 KB
/
index.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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
const { Client } = require("pg");
const client = new Client({
host: "db",
user: "postgres",
password: "example",
database: "postgres"
});
client.connect();
console.log("Connect to database");
console.log('no err 1');
// =============================================
const WebSocket = require("ws");
const wss = new WebSocket.Server({
port: process.env.PORT || 8081
});
console.log("Listening on", process.env.PORT);
console.log('no err 2');
// ==============================================
// var roomlist = [];
// var roomcheckmutex = false;
var connectionlist = new Map();
// ----------------------------------------------
// client.query("SELECT * FROM room",(err,res) => {
// console.log("Inside Query",res);
// res.rows.forEach(row => {
// roomlist.push(new room(
// row.id,
// row.name,
// row.creator,
// row.code
// ));
// })
// });
// for(i = 0; i < 1 + Math.random() * 10 ;i++) {
// let roomid = generateUniqueRoomId();
// roomlist.push(new room(
// roomid,
// "Anything",
// "Origin",
// makeid()
// ));
// }
// roomlist.forEach(room => {
// let qr = "INSERT INTO room " +
// `VALUES (${room.id}, '${room.name}', '${room.creator}',`
// + ` '${room.code}');`;
// console.log(qr);
// client.query(qr);
// })
// ==============================================
// Room Pooling
// use interval to each room
// Disabled for database experiment
setInterval(() => {
// console.log("Room");
// console.log('no err 3');
// console.log('no err loop3');
// while(roomcheckmutex) {}
// console.log('no err loop4');
// roomcheckmutex = true;
// todo
// Get room idle room
// Delete idle room
// Get inactive user
let toErase = []
connectionlist.forEach((user,key) => {
user.send(messageFormat("ping","ping"));
// console.log(key);
toErase.push(key);
});
toErase.forEach(val => {
connectionlist.delete(toErase);
});
roomcheckmutex = false;
// console.log('no err 4');
}, 5000);
// ===============================================
wss.on("connection", socket => {
socket.on("message", async messageFromUser => {
// Parse message
let messageReceived = JSON.parse(messageFromUser);
let messageType = messageReceived.type;
if(messageType == "pong") {
// console.log("Active");
connectionlist.set(messageReceived.sender.name, socket);
return;
}
console.log(messageType,"Type");
// console.log('no err loop1');
// while(roomcheckmutex) {}
// console.log('no err loop2');
// roomcheckmutex = true;
console.log('no err 5');
// pull database
// todo pull message
// todo pull user
// todo update connection per user
var isChanged = true;
let roomlist = [];
let userQuery = await client.query("SELECT * FROM users");
let messageQuery = await client.query("SELECT * FROM message");
let roomQuery = await client.query("SELECT * FROM room");
roomQuery.rows.map(row => {
roomlist.push(new room(
row.id,
row.name,
row.creator,
row.code
));
roomlist[roomlist.length - 1].message = [];
roomlist[roomlist.length - 1].user = [];
// push user
userQuery.rows.forEach((users) => {
if(users.roomid == row.id) {
// corelate user and connection
let connectiondata = (connectionlist.has(users.name)) ?
connectionlist.get(users.name) : null;
roomlist[roomlist.length - 1].user.push(new user(
users.name,
users.pictureurl,
connectiondata
));
}
});
// push message
messageQuery.rows.forEach((messageq) => {
if(messageq.roomid == row.id) {
roomlist[roomlist.length - 1].message.push(new message(
messageq.sender,
messageq.text,
messageq.time
));
};
});
});
console.log("Compare this",roomlist)
console.log('no err 6');
switch (messageType) {
case "RoomList" :
console.log('no err 7');
// Interaction == roomlist
let roomlst = roomlist.map((elm) => {
return {
id : elm.id,
name : elm.name,
creator : elm.creator,
code : elm.code
}
});
let messageToDispatch = messageFormat("RoomList",roomlst);
isChanged = false;
socket.send(messageToDispatch);
break;
case "RoomMake" :
console.log('no err 8');
// Interaction == roomlist, user
let roomid = generateUniqueRoomId(roomlist);
let code = makeid();
roomlist.push(new room(roomid, messageReceived.payload.name,
messageReceived.payload.creator, code)); // new room
roomlist[roomlist.length - 1]
.user.push(new user(
messageReceived.sender.name,
messageReceived.sender.pictureurl == undefined ? messageReceived.sender.pictureurl : "",
socket
)); // join
let broadcastRoom = {
id : roomlist[roomlist.length-1].id,
name : roomlist[roomlist.length-1].name,
creator : roomlist[roomlist.length-1].creator,
code : roomlist[roomlist.length-1].code
};
let mssageToDispatch = messageFormat("MakeRoom", broadcastRoom); // new message
socket.send(mssageToDispatch);
break;
case "RoomEnter" :
console.log('no err 9');
// Interaction == roomlist, user
let roomselected = roomlist.filter((room) => {
return room.code === messageReceived.payload.code
&& room.id === messageReceived.payload.id;
});
if(roomselected.length == 0) {
let roomid = generateUniqueRoomId(roomlist);
roomlist.push(new room(roomid, messageReceived.payload.name,
messageReceived.payload.creator, messageReceived.payload.code)); // new room
roomlist[roomlist.length - 1]
.user.push(new user(
messageReceived.sender.name,
messageReceived.sender.pictureurl == undefined ? messageReceived.sender.pictureurl : "",
socket
));
} else {
roomselected[0] && roomselected[0].user.push(new user(
messageReceived.sender.name,
messageReceived.sender.pictureurl == undefined ?
"" : messageReceived.sender.pictureurl,
socket
)); // join room
}
let msgeToDispatch = messageFormat("EnterRoom",["success",messageReceived.payload.id]); // make message
socket.send(msgeToDispatch);
// User to room create mapping
connectionlist.set(messageReceived.sender.name, socket);
break;
case "RoomExit" :
console.log('no err 10');
// Interaction == roomlist, user
let roomselectedhere = roomlist.filter((room) => {
return room.code == messageReceived.payload.code
&& room.id == messageReceived.payload.id;
});
if(roomselectedhere.length == 0) break;
roomselectedhere[0].user = roomselectedhere[0].user.filter((user) => {
return user.name != messageReceived.sender.name
});
connectionlist.delete(messageReceived.sender.name);
let mseToDispatch = messageFormat("ExitRoom","Success"); // make message
socket.send(mseToDispatch);
break;
case "GetMessage" :
console.log('no err 11');
// Interaction == roomlist, user, data
let roomTemp = roomlist.filter((room) => {
return room.user.reduce((acc, curr) => {
return acc || curr.name == messageReceived.sender.name;
},false);
});
let mgeToDispatch = messageFormat("NewMessage",
roomTemp[0] == undefined ? [] : roomTemp[0].message); // make message
console.log("MESSAGE",roomTemp,roomlist);
socket.send(mgeToDispatch);
console.log("MESSAGE-----",mgeToDispatch);
isChanged = false;
break;
case "SendMessage" :
console.log('no err 12');
// Interaction == roomlist, user, data
let roomTmp = roomlist.filter((room) => {
return room.user.reduce((acc, curr) => {
return acc || (curr.name == messageReceived.sender.name)
},0);
});
if(!roomTmp[0]) break;
roomTmp[0].message.push(new message(
messageReceived.sender.name, messageReceived.payload
));
let msgToDispatch = messageFormat("NewMessage",
roomTmp[0] == undefined ? "" : roomTmp[0].message); // make message
roomTmp[0].user.forEach((user) => {
user.connection && user.connection.send(msgToDispatch);
});
break;
default:
isChanged = false;
console.log("Unhandled Data")
break;
}
// update database
console.log('no err 13');
if(isChanged) {
console.log('no err 17');
// clear database
let prlist = [];
prlist[0] = client.query("DELETE FROM room WHERE true");
prlist[1] = client.query("DELETE FROM users WHERE true");
prlist[2] = client.query("DELETE FROM message WHERE true");
await Promise.all(prlist).catch((e)=>{console.log(e)});
console.log('no err 14');
// push room
var counteruser = 0;
var countermessage = 0;
let prlistn = [];
console.log("ROOMLIST",roomlist);
roomlist.forEach((room) => {
let querystring = "INSERT INTO room (id,name,creator,code) VALUES (" + room.id.toString() + ",'" + room.name + "','" + room.creator + "','" + room.code + "');";
console.log(querystring);
prlistn.push(client.query(querystring));
console.log('no err 15');
// push user
room.user.forEach(user => {
counteruser += 1;
querystring = "INSERT INTO users (name,pictureurl,roomid) VALUES (" + "'" + user.name + "','" + user.pictureurl + "'," + room.id.toString() + ");";
console.log(querystring,counteruser);
prlistn.push(client.query(querystring));
});
console.log('no err 16');
// push message
room.message.forEach(message => {
countermessage += 1;
querystring = "INSERT INTO message (sender,text,time,roomid) VALUES (" + "'" + message.sender + "','" + message.text + "','" + message.time + "'," + room.id.toString() + ");";
console.log(querystring,countermessage);
prlistn.push(client.query(querystring));
});
console.log("no err rpt")
});
console.log('no err 18');
Promise.all(prlistn).catch((e)=>console.log(e));
console.log('no err 18a');
// roomcheckmutex = false;
}
console.log("-");
console.log("-");
// roomcheckmutex = false;
});
});
// =================================================
// Constructors
function messageFormat(type, data) {
let toReturn = {};
toReturn.type = type;
toReturn.data = data;
return JSON.stringify(toReturn);
}
function user(name, pictureurl = "", connection) {
this.name = name;
this.pictureurl = pictureurl;
this.connection = connection;
return this;
}
function room(id,name,creator,code) {
this.id = id;
this.name = name;
this.creator = creator;
this.code = code;
this.message = [];
this.user = [];
return this;
}
function message(sender, text) {
this.sender = sender;
this.text = text;
this.time = (new Date()).toString();
return this;
}
// ================================================
// ID generator
function makeid() {
let length = 9;
let result = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
function generateUniqueRoomId(roomlist) {
let roomid = Math.floor(Math.random() * 100);
while(
roomlist != 0
&&
!roomlist.reduce((acc,curr) => {
return acc || curr.id == roomid;
})
) {
roomid = Math.floor(Math.random() * 100);
}
return roomid;
}
// Reference https://www.npmjs.com/package/ws
// wss.on("close", () => { })
/* Example
setInterval(() => {
console.log("interval" + connetionlist.length);
connetionlist[0].send("periodic");
},3000);
message
ask room
enter room
send chat
receive chat
quit room
*/
/*
PGUSER=postgres \
PGPASSWORD=example \
PGHOST=localhost \
PGPORT=5432 \
PGDATABASE=postgres \
node script.js
*/