-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.js
449 lines (323 loc) · 13.1 KB
/
Server.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
require('dotenv').config({ path: 'variables.env' });
const push = require('web-push');
const Joi = require('joi'); // Validation of user input
const express = require('express');
const StringBuilder = require("string-builder");
const date = require('date-and-time');
const bodyParser = require('body-parser')
const app = express();
app.set('port', process.env.PORT || 2828);
app.use( express.static(__dirname + '/public') );
app.use(express.json() )
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({extended: true}));
let users = [];
let chat_rooms = [];
// ------------------ Functions --------------------- //
function formater_my_rooms(arr){
let out = new StringBuilder()
arr.forEach(room => {
let div = `<div class="chat_list">
<div class="chat_people">
<div class="chat_img"><span class="material-icons md-dark">forum</span></div>
<div class="chat_ib">${room.name}<span class="chat_date">
<button class="btn btn-lg btn-primary btn-block" onclick="enter_room(${room.room_id})">Enter</button></span>
</div>
</div>
</div>
</div>`
out.append(div);
});
return out;
}
function formater_room_users(arr, room){
let out = new StringBuilder()
let div = `<div class="chat_list">
<div class="chat_people">
<div class="recent_heading"><h4>${room.name}</h4><br><h5>Participants:</h5></div>
</div>
</div>
</div>`
out.append(div)
arr.forEach(user => {
div = `<div class="chat_list">
<div class="chat_people">
<div class="chat_img"><span class="material-icons" style="color: lime;">adjust</span></div>
<div class="chat_ib">${user.username}</div>
</div>
</div>
</div>`
out.append(div);
});
div = `<div class="chat_list">
<div class="chat_people">
<button class="btn btn-lg btn-danger btn-block" onclick="get_user_rooms()">Exit</button>
</div>
</div>
</div>`
out.append(div)
return out.toString();
}
function formater_users(arr){
let out = new StringBuilder()
arr.forEach(user => {
div = `<div class="chat_list">
<div class="chat_people">
<div class="chat_img"><span class="material-icons" style="color: lime;">adjust</span></div>
<div class="chat_ib">${user.username}</div>
</div>
</div>
</div>`
out.append(div);
});
return out.toString();
}
function formater_rooms(arr) {
let link;
let out = new StringBuilder()
arr.forEach(room => {
let div = `
<div class="chat_list">
<div class="chat_people">
<div class="chat_img"><span class="material-icons md-dark">forum</span></div>
<div class="chat_ib">
<h5>${room.name}<span class="chat_date"><button class="btn btn-lg btn-primary btn-block"
onclick="join_room(${room.room_id})">Join</button></span></h5>
</div>
</div>
</div>
</div>`
out.append(div);
});
return out;
}
function foramterMsgs(arr){
let out = new StringBuilder();
arr.forEach(msg =>{
let div = `<div class="incoming_msg">
<div class="incoming_msg_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>
<div class="received_msg">
<span>From ${msg.sender}</span>
<div class="received_withd_msg">
<p>${msg.message}</p>
<span class="time_date">${msg.time}</span></div>
</div>
</div>`
out.append(div);
});
return out.toString();
}
function getTimeAndDate(){
const now = new Date();
date.format(now, 'YYYY/MM/DD HH:mm:ss');
date.format(now, 'ddd, MMM DD YYYY');
date.format(now, 'hh:mm A [GMT+2]Z');
date.format(now, 'hh:mm A [GMT+2]Z', true);
const pattern = date.compile('ddd, MMM DD YYYY, HH:mm:ss');
return date.format(now, pattern);
}
// ------------ Push Notifications ------------- //
const publicVapidKey = process.env.PUBLIC_VAPID_KEY;
const privateVapidKey = process.env.PRIVATE_VAPID_KEY;
push.setVapidDetails('mailto:test@code.no', publicVapidKey, privateVapidKey)
let subscribers = [];
app.post('/api/sub', (req, res) => {
if(req.body){
subscribers.push(req.body)
return res.status(200).send("Sub registered!");
} else {
res.status(404).send("Couldn't add sub!");
console.error("Couldn't add sub!")
}
})
// ------------------ Users --------------------- //
app.post('/api/login', (req,res) => {
const user_login = {
username: req.body.username
};
const user = users.find(c => c.username === user_login.username);
if (!user) return res.status(404).send(req.body.username + " does not exist.");
res.status(200).send("Welcome back, " + req.body.username);
});
app.get('/api/get_rooms/:username', function (req,res){
const user = users.find(c => c.username === req.params.username);
let user_in_rooms = [];
chat_rooms.forEach(room => {
room.roomUsers.forEach(room_users => {
if (room_users.username === user.username){
user_in_rooms.push(room);
}
})
});
let out = formater_my_rooms(user_in_rooms);
if (!out.toString()){
return res.status(200).send(`<h4 class="title">Welcome, ${user.username}!</h4>`)
}
else res.status(200).send(out.toString());
});
app.route('/api/users')
//get all
.get((req, res) => {
res.status(200).send(formater_users(users));
})
//add user
.post((req,res) => {
const schema = {
username: Joi.string().min(2).max(50).required()
};
const result = Joi.validate(req.body, schema);
if (result.error){
return res.status(400).send(result.error.details[0].message); // If the name is "Null" or less than 2
// characters, the user will get an error with the details.
}
const user = {
username: req.body.username
};
const user_check = users.find(c => c.username === user.username);
if (user_check)
return res.status(409).send("The username is taken.");
else {
users.push(user);
}
res.status(200).send(`Welcome , ${user.username}!`);
});
app.route('/api/user/:username')
// get one user by given id
.get((req,res) => {
const user = users.find(c => c.username === req.params.username);
if (!user) return res.status(404).send('The user with the given id was not found.');
res.status(200).send(user);
})
// Delete user by given id
.delete((req, res) =>{
const user = users.find(c => c.username === req.params.username);
if (!user) return res.status(404).send('The user with the given id was not found.');
for (let i = 0;i<chat_rooms.length;i++){
let roomuser = chat_rooms[i].roomUsers;
for (let j = 0;j<roomuser.length;j++){
if (roomuser[j].username === user.username){
roomuser.splice(j,1);
}
}
}
const index = users.indexOf(user);
users.splice(index,1);
res.status(200).send(`User ${user.username} is deleted!`);
});
// -------------- Chat-Rooms -------------------- //
app.route('/api/rooms')
// Get all
.get((req, res) => {
let out = formater_rooms(chat_rooms);
if (!out.toString()){
return res.status(200).send(`No rooms created!`);
}
else res.status(200).send(out.toString());
})
//add room
.post((req,res) => {
const schema = {
name: Joi.string().min(2).max(50).required()
};
const result = Joi.validate(req.body, schema);
if (result.error){
// If the name is "Null" or less than 2 characters,
// the user will get an error with the details.
return res.status(404).send(result.error.details[0].message);
}
const check_room = chat_rooms.find(c => c.name === req.body.name);
if (check_room) return res.status(404).send(req.body.name + " already exist.");
const room = {
room_id: chat_rooms.length + 1,
name: req.body.name,
roomUsers: [],
messages: []
// [[user1,melding1,melding2,melding3],[user2,melding1,melding2,melding3]]
};
chat_rooms.push(room);
res.status(200).send(req.body.name +" was created!");
});
//Get room with room id
app.get('/api/room/:room_id', (req,res) => {
const room = chat_rooms.find(c => c.room_id === parseInt(req.params.room_id));
if (!room) res.status(404).send('The room with the given id was not found.');
res.status(200).send(room);
});
app.route('/api/room/:room_id/bots')
//Get all users in the room
.get((req, res) =>{
const room = chat_rooms.find(c => c.room_id === parseInt(req.params.room_id));
if (!room) return res.status(404).send('The room with the given id was not found.');
res.status(200).send(room.roomUsers);
});
app.route('/api/room/:room_id/users')
//Get all users in the room
.get((req, res) =>{
const room = chat_rooms.find(c => c.room_id === parseInt(req.params.room_id));
if (!room) return res.status(404).send('The room with the given id was not found.');
res.status(200).send(formater_room_users(room.roomUsers, room));
})
//Add/join user
//Restrictions:Only registered users can join
.post((req,res) => {
const room = chat_rooms.find(c => c.room_id === parseInt(req.params.room_id));
if (!room) return res.status(404).send('The room with the given id was not found.');
const joinUser = {
username: req.body.username
};
const check_users_in_room = room.roomUsers.find(c => c.username === joinUser.username);
if(check_users_in_room) return res.status(400).send("You have already joined " + room.name);
const user = users.indexOf(joinUser);
if (!user) res.status(404).send("No user with username " + joinUser.username + " is found");
room.roomUsers.push(joinUser);
res.status(200).send(room.roomUsers);
});
// ------- Messages ------- //
// Restrictions:Only users in the room can get messages.
app.get('/api/room/:room_id/messages', (req, res) => {
const room = chat_rooms.find(c => c.room_id === parseInt(req.params.room_id));
if (!room) res.status(404).send('The room with the given id was not found.');
const joinUser = {
username: req.body.username
};
const user = room.roomUsers.indexOf(joinUser);
if (!user) res.status(404).send("No user with user ID " + joinUser.username + " is found.");
res.status(200).send(foramterMsgs(room.messages));
});
app.route('/api/room/:room_id/:username/messages')
//Get all messages
.get((req, res) => {
const room = chat_rooms.find(c => c.room_id === parseInt(req.params.room_id));
if (!room) return res.status(404).send('The room with the given id was not found.');
const user = users.find(c => c.username === req.params.username);
if (!user) return res.status(404).send('The user with the given username was not found.');
const user_messages = [];
for (let i = 0; i < room.messages.length; i++){
if(room.messages[i].sender === user.username){
user_messages.push(room.messages[i].message)
}
}
res.status(200).send(user_messages);
})
//Add message
.post((req, res) => {
const room = chat_rooms.find(c => c.room_id === parseInt(req.params.room_id));
if (!room) return res.status(404).send('The room with the given id was not found.');
const user = users.find(c => c.username === req.body.user);
if (!user) return res.status(404).send('The user with the given username was not found.');
const message = {
sender: req.body.user,
message: req.body.msg,
time: getTimeAndDate()
}
for (let i = 0; i < subscribers.length; i++){
if(subscribers[i] !== req.body) {
push.sendNotification(subscribers[i], 'Message from ')
}
}
room.messages.push(message);
res.status(200).send(foramterMsgs(room.messages));
});
const server = app.listen(app.get('port'), () => {
console.log(`Listening for connections on port ${server.address().port}`);
});