-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
421 lines (394 loc) · 12.1 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
const express = require('express');
const webPush = require('web-push');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const { JSDOM } = require('jsdom');
const { window } = new JSDOM("");
const $ = require('jquery')(window);
const cors = require('cors');
const fs = require('fs');
const app = express();
const publicKey = "BP9dpMh9ZzDu76icN_y9poka-vUmxC1WSFrwxHSariK-puJvRrwcsTYNs2AOrZ6SzNPcVzWnPq6vH1Q-yCXdHXc";
const privateKey = "WWE6g5zfMfrgkb27o44mfugBpnGfxTGGzykZjQLxu-c";
let confParams;
let emptyRooms = [];
let inactiveUsers = [];
//getting config params from config.json
let confData = fs.readFileSync(__dirname +"/config.json");
confParams = JSON.parse(confData);
//setting up MySQL connection pool
let pool = mysql.createPool({
connectionLimit: 100,
host: confParams.dbhost,
user: confParams.dbuser,
password: confParams.dbpass,
database: confParams.db
});
app.use(bodyParser.json());
app.use(cors());
webPush.setVapidDetails("mailto:test@mail.com",publicKey,privateKey);
app.post("/subscribe", (req,res) =>{
const params = req.body;
res.status(201).json({});
saveSubscription(params.subscription, params.username, params.chatroomId, params.lastMessage);
});
const port = 3000;
app.listen(port, ()=>{
console.log(`server started on ${port}`);
});
setInterval(sendPushNotifications,1000);
setInterval(setUserInactive,1000);
setInterval(clearRooms,15000);
/**
* saves subscription to db
* @param sub
* @param username
* @param chatroomId
* @returns {Promise<void>}
*/
async function saveSubscription(sub, username, chatroomId, lastMessage){
let subUnique = await checkSubscriptionUnique(username,chatroomId);
if (subUnique === true) {
let query = `INSERT INTO chat_subscriptions (chat_room_id,user,subscription,last_message_id) VALUES ('${chatroomId}','${username}','${cipher(JSON.stringify(sub),"encrypt")}','${lastMessage}')`;
pool.query(query,function (err){
if (err) throw err;
});
}
}
/**
* checks whether a subscription is unique
* @param username
* @param chatroomId
* @returns {Promise<unknown>}
*/
function checkSubscriptionUnique(username, chatroomId) {
return new Promise(resolve => {
let query = `SELECT * FROM chat_subscriptions WHERE user='${username}' AND chat_room_id='${chatroomId}' LIMIT 1`;
pool.query(query,(err, result) => {
if (err) throw err;
resolve(result.length === 0);
});
});
}
/**
* ciphers given data process can be "decrypt" or "encrypt"
* @param data
* @param process
* @returns {string}
*/
function cipher(data,process){
let ciphered = "";
$.ajax(confParams.url+"index.php",{
"type":"POST",
"async":false,
"data":{
"controller":"CipherAjax",
"process":process,
"data":data
},
"complete":function (response){
ciphered = response.responseText;
}
});
return ciphered;
}
/**
* sends push notifications
*/
function sendPushNotifications(){
let query = "SELECT * FROM chat_subscriptions";
pool.query(query, async function (err, result){
if (err) throw err;
for (let i = 0; i < result.length; i++){
let pushNecessary = await isPushNecessary(result[i]);
if (pushNecessary === true) {
let room = await getRoomNameById(result[i].chat_room_id);
let payload = JSON.stringify({
body:"There are new messages for you",
url:confParams.url,
chat:room,
user:result[i].user,
});
let subscription = JSON.parse(cipher(result[i].subscription,"decrypt"));
webPush.sendNotification(subscription,payload);
console.log("PN sent");
}
}
});
}
function getRoomNameById(chatroomId){
return new Promise(resolve => {
let query = `SELECT room_name FROM chat_rooms WHERE id = '${chatroomId}' LIMIT 1`;
pool.query(query,(err, result) => {
if (err) throw err;
if (result.length > 0) {
resolve(result[0].room_name);
}
});
});
}
/**
* checks whether a push notification is necessary
* @param subscriptionData
* @returns {Promise<unknown>}
*/
function isPushNecessary(subscriptionData){
return new Promise(async resolve=> {
let userInactive = await isUserDeleted(subscriptionData.user,subscriptionData.chat_room_id,"chat_active");
if (userInactive === true) {
console.log("user inactive");
let lastMessageId = await getLastMessageId(subscriptionData.chat_room_id);
if (subscriptionData.last_message_id < lastMessageId) {
console.log("PN necessary");
await updateLastMessageId(subscriptionData.id,lastMessageId);
resolve(true);
}
} else {
resolve(false);
}
});
}
/**
* gets id of last message from given room
* @param chatroomId
* @returns {Promise<unknown>}
*/
function getLastMessageId(chatroomId) {
return new Promise(resolve => {
let query = `SELECT id FROM chat_messages WHERE chat_room_id = '${chatroomId}' AND user <> '' ORDER BY id DESC LIMIT 1`;
pool.query(query,(err, result) => {
if (err) throw err;
if (result.length > 0) {
resolve(result[0].id);
}
});
});
}
/**
* checks whether user is deleted
* @param user
* @param chatroomId
* @param table
* @returns {Promise<unknown>}
*/
function isUserDeleted(user, chatroomId, table) {
return new Promise(resolve => {
let query = `SELECT * FROM ${table} WHERE user='${user}' AND chat_room_id='${chatroomId}' LIMIT 1`;
pool.query(query,(err, result) => {
if (err) throw err;
resolve(result.length === 0);
});
});
}
/**
* checks whether user is active
* @param user
* @param chatroomId
* @param table
* @returns {Promise<unknown>}
*/
function isUserInactive(user, chatroomId, table) {
return new Promise(resolve => {
let query = `SELECT * FROM ${table} WHERE user='${user}' AND chat_room_id='${chatroomId}' AND active='0' LIMIT 1`;
pool.query(query,(err, result) => {
if (err) throw err;
resolve(result.length === 1);
});
});
}
/**
* updates last message id of given subscription
* @param subscriptionId
* @param lastId
* @returns {Promise<unknown>}
*/
function updateLastMessageId(subscriptionId, lastId) {
return new Promise(resolve => {
let query = `UPDATE chat_subscriptions SET last_message_id = '${lastId}' WHERE id='${subscriptionId}'`;
pool.query(query,err=>{
if (err) throw err;
resolve(true);
});
});
}
/**
* clears empty rooms then stores empty rooms in emptyRooms array
* @returns {Promise<void>}
*/
async function clearRooms()
{
if (emptyRooms.length > 0) {
for (let i = 0; i < emptyRooms.length; i++){
let roomEmpty = await isRoomEmpty(emptyRooms[i]);
if (roomEmpty === true) {
let deleted = await deleteRoom(emptyRooms[i]);
if (deleted === true) {
console.log("deleted room "+emptyRooms[i]);
emptyRooms.splice(i,1);
}
}
}
}
emptyRooms = await getEmptyRooms();
}
/**
* checks whether room is empty
* @param roomId
* @returns {Promise<unknown>}
*/
function isRoomEmpty(roomId) {
return new Promise(resolve => {
let query = `SELECT * FROM chat_active WHERE chat_room_id='${roomId}' LIMIT 1`;
pool.query(query,(err, result) => {
if (err) throw err;
resolve(result.length === 0);
});
});
}
/**
* deletes room with given id
* @param roomId
* @returns {Promise<unknown>}
*/
function deleteRoom(roomId){
return new Promise(async resolve => {
let picsDeleted = await deletePics(roomId);
if (picsDeleted === true) {
deleteSubscription(roomId);
deleteMessages(roomId);
}
let query = `DELETE FROM chat_rooms WHERE id = '${roomId}'`;
pool.query(query, (err) => {
if (err) throw err
resolve(true);
});
});
}
/**
* deletes images of given chatroom
* @param roomId
* @returns {Promise<unknown>}
*/
function deletePics(roomId){
return new Promise(resolve => {
let query = `SELECT picture_url FROM chat_messages WHERE chat_room_id = '${roomId}' AND picture_url <> ''`;
pool.query(query,(err, result) => {
if (err) throw err;
for (let i = 0; i < result.length; i++){
let url = cipher(result[i].picture_url,"decrypt");
let file = url.slice(url.lastIndexOf("/")+1);
let path = __dirname+"\\pics\\"+file;
fs.unlink(path,(err) =>{
if (err) throw err;
console.log("deleted "+path);
});
}
resolve(true);
});
});
}
/**
* deletes messages of given chatroom
* @param roomId
*/
function deleteMessages(roomId) {
let query = `DELETE FROM chat_messages WHERE chat_room_id = '${roomId}'`;
pool.query(query,(err) =>{
if (err) throw err;
});
}
/**
* deletes subscriptions of given chatroom
* @param roomId
*/
function deleteSubscription(roomId){
let query = `DELETE FROM chat_subscriptions WHERE chat_room_id = '${roomId}'`;
pool.query(query,(err) =>{
if (err) throw err;
});
}
/**
* returns ids of empty chat rooms
* @returns {Promise<unknown>}
*/
function getEmptyRooms()
{
return new Promise(resolve => {
let query = `SELECT id FROM chat_rooms`;
let empty = [];
pool.query(query,async (err, result) => {
if (err) throw err;
for (let i = 0; i < result.length; i++) {
let roomEmpty = await isRoomEmpty(result[i].id);
if (roomEmpty === true) {
empty.push(result[i].id);
}
}
resolve(empty);
});
});
}
/**
* checks if users are still active and deletes them if not
* then stores all active users in array
* @returns {Promise<void>}
*/
async function setUserInactive() {
if (inactiveUsers.length > 0) {
for (let i = 0; i < inactiveUsers.length; i++){
let userInactive = await isUserInactive(inactiveUsers[i].user, inactiveUsers[i].chat_room_id,"chat_active");
if (userInactive === true) {
let deleted = await deleteUser(inactiveUsers[i].user, inactiveUsers[i].chat_room_id);
if (deleted === true) {
sendUserLeft(inactiveUsers[i].user,inactiveUsers[i].chat_room_id);
inactiveUsers.splice(i,1);
}
}
}
}
inactiveUsers = await getInactiveUsers();
}
/**
* deletes user by username and chat room id
* @param user
* @param chatId
* @returns {Promise<unknown>}
*/
function deleteUser(user, chatId) {
return new Promise(resolve => {
let query = `DELETE FROM chat_active WHERE user = '${user}' AND chat_room_id = '${chatId}'`;
pool.query(query,err => {
if (err) throw err;
resolve(true);
});
console.log(user + " deleted")
});
}
/**
* queries db and returns list of active users
* @returns {Promise<unknown>}
*/
function getInactiveUsers() {
return new Promise(resolve => {
let query = `SELECT * FROM chat_active WHERE active = '0'`;
let active = [];
pool.query(query,async (err, result) => {
if (err) throw err;
for (let i = 0; i < result.length; i++) {
active.push(result[i]);
}
resolve(active);
});
});
}
/**
* sends "user left chat" notification
* @param user
* @param chat
*/
function sendUserLeft(user, chat) {
let query = `INSERT INTO chat_messages (chat_room_id,msg_text) VALUES ('${chat}','${user} left the chat')`;
pool.query(query, err => {
if (err) throw err;
});
}