forked from josephdadams/TimeKeeper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
687 lines (560 loc) · 14.7 KB
/
main.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
/* TimeKeeper */
//express variables
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json({ type: 'application/json' }));
//socket.io variables
const http = require('http').Server(app);
const io = require('socket.io')(http);
const listenPort = 4000;
//filesystem variables
const fs = require('fs');
const JSONdatafile = 'timekeeper-data.json'; //local storage JSON file
//TimeKeeper Arrays
var Rooms = []; // array of Room Objects to display
var Timers = []; // array of Timer Objects to display
var Messages = []; // array of Message Objects to display
//app route setups
app.get('/', function (req, res) {
res.sendFile(__dirname + '/views/index.html');
});
//about the author, this program, etc.
app.get('/about', function (req, res) {
res.sendFile(__dirname + '/views/about.html');
});
//serve up any files in the static folder like images, CSS, client-side JS, etc.
app.use(express.static('views/static'));
//Room APIs
app.get('/api/rooms', function (req, res) {
//gets all Room objects
res.send(TimeKeeper_GetRooms(true));
});
app.get('/api/room/:roomid', function (req, res) {
//gets a specific timer object
let roomID = req.params.roomid;
let roomObj = TimeKeeper_GetTimer(roomID);
if (roomObj === null)
{
//return as invalid
res.send({returnStatus: 'invalid-room-id'});
}
else
{
res.send({returnStatus: 'success', room: roomObj});
}
});
app.post('/api/room/add', function (req, res) {
//add the new timer object into the array
let roomObj = TimeKeeper_AddRoom(req.body);
if (roomObj !== null)
{
res.send({returnStatus: 'success', room: roomObj});
}
});
app.post('/api/room/update/:roomid', function (req, res) {
//updates the room object that already exists in the array
let roomID = req.params.roomid;
let roomObj = TimeKeeper_UpdateRoom(roomID, req.body);
if (roomObj !== null)
{
res.send({returnStatus: 'success', room: roomObj});
}
});
app.post('/api/room/delete/:roomid', function (req, res) {
//updates the room object that already exists in the array
let roomID = req.params.roomid;
TimeKeeper_DeleteRoom(roomID);
res.send({returnStatus: 'success'});
});
//Timer APIs
app.get('/api/timers', function (req, res) {
//gets all Timer objects
res.send(Timers);
});
app.get('/api/timer/:timerid', function (req, res) {
//gets a specific timer object
let timerID = req.params.timerid;
let timerObj = TimeKeeper_GetTimer(timerID);
if (timerObj === null)
{
//return as invalid
res.send({returnStatus: 'invalid-timer-id'});
}
else
{
res.send({returnStatus: 'success', timer: timerObj});
}
});
app.post('/api/timer/add', function (req, res) {
//add the new timer object into the array
let timerObj = TimeKeeper_AddTimer(req.body);
if (timerObj !== null)
{
res.send({returnStatus: 'success', timer: timerObj});
}
});
app.post('/api/timer/update/:timerid', function (req, res) {
//updates the timer object that already exists in the array
let timerID = req.params.timerid;
let timerObj = TimeKeeper_UpdateTimer(timerID, req.body);
if (timerObj !== null)
{
res.send({returnStatus: 'success', timer: timerObj});
}
});
app.post('/api/timer/delete/:timerid', function (req, res) {
//updates the timer object that already exists in the array
let timerID = req.params.timerid;
TimeKeeper_DeleteTimer(timerID);
res.send({returnStatus: 'success'});
});
app.get('/api/countdown/:roomid/:length', function (req, res) {
let roomID = req.params.roomid;
let length = parseInt(req.params.length);
let obj = {};
let d = new Date();
let dt = new Date(d.getTime() + (length * 1000));
obj.label = '';
obj.datetime = dt.getTime();
obj.publishMillis = 120000;
obj.expireMillis = 120000;
obj.roomID = roomID;
//add the new timer object into the array
let timerObj = TimeKeeper_AddTimer(obj);
if (timerObj !== null)
{
res.send({returnStatus: 'success', timer: timerObj});
}
});
//Message APIs
app.get('/api/messages', function (req, res) {
//gets all Message objects
res.send(Messages);
});
app.post('/api/message/add', function (req, res) {
console.log('add msg received:');
console.log(req.body);
//add the new timer object into the array
TimeKeeper_AddMessage(req.body);
res.send({returnStatus: 'success'});
});
app.post('/api/message/update/:messageid', function (req, res) {
//updates the timer object that already exists in the array
let messageID = req.params.messageid;
let messageObj = TimeKeeper_UpdateMessage(messageID, req.body);
if (messageObj !== null)
{
res.send({returnStatus: 'success', message: messageObj});
}
});
app.post('/api/message/delete/:messageid', function (req, res) {
//updates the timer object that already exists in the array
let messageID = req.params.messageid;
TimeKeeper_DeleteMessage(messageID);
res.send({returnStatus: 'success'});
});
function loadFile() //loads settings on first load of app
{
let rawdata = fs.readFileSync(JSONdatafile);
let myJson = JSON.parse(rawdata);
if (myJson.Rooms)
{
Rooms = myJson.Rooms;
}
if (myJson.Timers)
{
Timers = myJson.Timers;
}
if (myJson.Messages)
{
Messages = myJson.Messages;
}
}
function saveFile() //saves settings to a local storage file for later recalling on restarts, etc.
{
var myJson = {
Rooms: Rooms,
Timers: Timers,
Messages: Messages
};
fs.writeFileSync(JSONdatafile, JSON.stringify(myJson, null, 1), 'utf8', function(error) {
if (error)
{
console.log('error: ' + error);
}
else
{
console.log('file saved');
}
});
}
//SOCKET.IO config
io.sockets.on('connection', function(socket) {
// VIEWER SOCKETS //
socket.on('TimeKeeper_JoinRoom', function(roomID) {
switch(roomID)
{
case 'TimeKeeper_Clients':
socket.join('TimeKeeper_Clients');
break;
default:
socket.join(roomID);
console.log(roomID + ' joined.');
socket.emit('TimeKeeper_Timers', TimeKeeper_GetTimers(roomID));
socket.emit('TimeKeeper_Messages', TimeKeeper_GetMessages(roomID));
break;
}
});
socket.on('TimeKeeper_GetAllRooms', function(onlyShowEnabled) {
socket.emit('TimeKeeper_Rooms', TimeKeeper_GetRooms(onlyShowEnabled));
});
socket.on('TimeKeeper_GetTimers', function(roomID) {
socket.emit('TimeKeeper_Timers', TimeKeeper_GetTimers(roomID));
});
socket.on('TimeKeeper_GetMessages', function(roomID) {
socket.emit('TimeKeeper_Messages', TimeKeeper_GetMessages(roomID));
});
socket.on('disconnect', function(){
switch(socket.room)
{
case 'Viewer':
console.log('Viewer Client Disconnected.');
break;
default:
break;
}
});
});
function uuidv4() //unique UUID generator for IDs
{
return 'xxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
//TimeKeeper Data Functions
function TimeKeeper_GetRooms(onlyShowEnabled)
{
let roomsArray = [];
if (onlyShowEnabled)
{
for (let i = 0; i < Rooms.length; i++)
{
if (Rooms[i].enabled)
{
roomsArray.push(Rooms[i]);
}
}
}
else
{
roomsArray = Rooms;
}
return roomsArray;
}
function TimeKeeper_GetRoom(roomID)
{
let roomObj = Rooms.find(o => o.id === roomID);
if (roomObj === undefined)
{
roomObj = null;
}
return roomObj;
}
function TimeKeeper_AddRoom(roomObj)
{
let newRoomObj = {};
newRoomObj.id = 'room-' + uuidv4();
newRoomObj.name = roomObj.name;
newRoomObj.enabled = roomObj.enabled;
Rooms.push(newRoomObj);
saveFile();
}
function TimeKeeper_UpdateRoom(roomID, roomObj)
{
let updatedRoomObj = Rooms.find((o, i) => {
if (o.id === roomID)
{
Rooms[i] = roomObj; // need to update this to go property by property, and data check each one
return true; // stop searching
}
});
saveFile();
return updatedRoomObj;
}
function TimeKeeper_DeleteRoom(roomID)
{
Rooms.find((o, i) => {
if (o.id === roomID)
{
Rooms.splice(i, 1);
}
});
saveFile();
}
function TimeKeeper_GetAllTimers()
{
return Timers;
}
function TimeKeeper_GetTimers(roomID)
{
let timersArray = [];
for (let i = 0; i < Timers.length; i++)
{
if ((Timers[i].roomID === roomID) || (roomID === 'room-0'))
{
timersArray.push(Timers[i]);
}
}
return timersArray;
}
function TimeKeeper_GetTimer(timerID)
{
let timerObj = Timers.find(o => o.id === timerID);
if (timerObj === undefined)
{
timerObj = null;
}
return timerObj;
}
function TimeKeeper_AddTimer(timerObj)
{
let newTimerObj = {};
newTimerObj.id = 'timer-' + uuidv4();
newTimerObj.datetime = timerObj.datetime;
newTimerObj.label = timerObj.label;
newTimerObj.expireMillis = timerObj.expireMillis;
newTimerObj.publishMillis = timerObj.publishMillis;
newTimerObj.roomID = timerObj.roomID;
Timers.push(newTimerObj);
if (timerObj.roomID === 'room-0')
{
io.emit('TimeKeeper_Timers', TimeKeeper_GetTimers(timerObj.roomID));
}
else
{
io.to(timerObj.roomID).emit('TimeKeeper_Timers', TimeKeeper_GetTimers(timerObj.roomID)); //send it to the unique room
}
console.log('sending new timer to room: ' + timerObj.roomID);
io.to('room-0').emit('TimeKeeper_Timers', TimeKeeper_GetAllTimers()); //send update timers to room-0
saveFile();
return newTimerObj;
}
function TimeKeeper_UpdateTimer(timerID, timerObj)
{
let updatedTimerObj = {};
let found = false;
for (let i = 0; i < Timers.length; i++)
{
if (Timers[i].id === timerID)
{
Timers[i].datetime = timerObj.datetime;
Timers[i].label = timerObj.label;
Timers[i].publishMillis = timerObj.publishMillis;
Timers[i].expireMillis = timerObj.expireMillis;
Timers[i].roomID = timerObj.roomID;
found = true;
break;
}
}
if (found) //send the updated timer to the room
{
saveFile();
if (timerObj.roomID === 'room-0')
{
io.emit('TimeKeeper_Timers', TimeKeeper_GetTimers(timerObj.roomID));
}
else
{
io.to(timerObj.roomID).emit('TimeKeeper_Timers', TimeKeeper_GetTimers(timerObj.roomID));
}
}
else // just re-add it if it got deleted
{
timerObj.id = timerID;
TimeKeeper_AddTimer(timerObj);
}
updatedTimerObj = timerObj;
return updatedTimerObj;
}
function TimeKeeper_DeleteTimer(timerID)
{
let index = null;
for (let i = 0; i < Timers.length; i++)
{
if (Timers[i].id === timerID)
{
index = i;
break;
}
}
if (index !== null)
{
let roomID = Timers[index].roomID;
Timers.splice(index, 1);
if (roomID === 'room-0')
{
io.emit('TimeKeeper_Timers', TimeKeeper_GetTimers(roomID));
}
else
{
io.to(roomID).emit('TimeKeeper_Timers', TimeKeeper_GetTimers(roomID));
}
}
saveFile();
}
function TimeKeeper_GetMessages(roomID)
{
let messagesArray = [];
for (let i = 0; i < Messages.length; i++)
{
if ((Messages[i].roomID === roomID) || (Messages[i].roomID === 'room-0'))
{
messagesArray.push(Messages[i]);
}
}
return messagesArray;
}
function TimeKeeper_GetMessage(messageID)
{
let messageObj = Messages.find(o => o.id === messageID);
if (messageObj === undefined)
{
messageObj = null;
}
return messageObj;
}
function TimeKeeper_AddMessage(messageObj)
{
let newMessageObj = {};
newMessageObj.id = 'message-' + uuidv4();
newMessageObj.datetime = new Date().getTime();
newMessageObj.message = messageObj.message;
newMessageObj.expireMillis = messageObj.expireMillis;
newMessageObj.publishMillis = messageObj.publishMillis;
newMessageObj.roomID = messageObj.roomID;
Messages.push(newMessageObj);
if (messageObj.roomID === 'room-0')
{
io.emit('TimeKeeper_Messages', TimeKeeper_GetTimers(messageObj.roomID));
}
else
{
io.to(messageObj.roomID).emit('TimeKeeper_Messages', TimeKeeper_GetTimers(messageObj.roomID));
}
console.log('sending new message to room: ' + newMessageObj.roomID);
console.log(TimeKeeper_GetMessages(messageObj.roomID));
saveFile();
}
function TimeKeeper_UpdateMessage(messageID, messageObj)
{
let updatedMessageObj = {};
let found = false;
for (let i = 0; i < Messages.length; i++)
{
if (Messages[i].id === messageID)
{
Messages[i].datetime = messageObj.datetime;
Messages[i].message = messageObj.message;
Messages[i].publishMillis = messageObj.publishMillis;
Messages[i].expireMillis = messageObj.expireMillis;
Messages[i].roomID = messageObj.roomID;
found = true;
break;
}
}
if (found) //send the updated message to the room
{
saveFile();
if (messageObj.roomID === 'room-0')
{
io.emit('TimeKeeper_Messages', TimeKeeper_GetMessages(messageObj.roomID));
}
else
{
io.to(messageObj.roomID).emit('TimeKeeper_Messages', TimeKeeper_GetMessages(messageObj.roomID));
}
}
else // just re-add it if it got deleted
{
messageObj.id = messageID;
TimeKeeper_AddTimer(messageObj);
}
updatedMessageObj = messageObj;
return updatedMessageObj;
}
function TimeKeeper_DeleteMessage(messageID)
{
let index = null;
for (let i = 0; i < Messages.length; i++)
{
if (Messages[i].id === messageID)
{
index = i;
break;
}
}
if (index !== null)
{
let roomID = Messages[index].roomID;
Messages.splice(index, 1);
if (roomID === 'room-0')
{
io.emit('TimeKeeper_Messages', TimeKeeper_GetMessages(roomID));
}
else
{
io.to(roomID).emit('TimeKeeper_Messages', TimeKeeper_GetMessages(roomID));
}
}
saveFile();
}
function TimeKeeper_ReviewTimers()
{
// looks at all the timers and deletes any that are older than 5 minutes (that ran out 5 minutes ago or more)
console.log('Reviewing old timers and messages.');
let d = new Date();
let Timers_ToDelete = [];
let Messages_ToDelete = [];
//Review Timers for expired ones
for (let i = 0; i < Timers.length; i++)
{
let dt = Timers[i].datetime;
let distance = dt - d + 1000;
if (distance < - (5 * 60 * 1000)) // 5 mimutes
{
// delete this from the array, but add it to an array of items to delete, rather than deleting it from the same array while looping
console.log(Timers[i].id + ' has expired.');
Timers_ToDelete.push(Timers[i].id);
}
}
for (let i = 0; i < Timers_ToDelete.length; i++)
{
TimeKeeper_DeleteTimer(Timers_ToDelete[i]);
}
//Review Messages for expired ones
for (let i = 0; i < Messages.length; i++)
{
let dt = Messages[i].datetime;
let distance = dt - d + 1000;
if (distance < - (5 * 60 * 1000)) // 5 mimutes
{
// delete this from the array, but add it to an array of items to delete, rather than deleting it from the same array while looping
console.log(Messages[i].id + ' has expired.');
Messages_ToDelete.push(Messages[i].id);
}
}
for (let i = 0; i < Messages_ToDelete.length; i++)
{
TimeKeeper_DeleteMessage(Messages_ToDelete[i]);
}
saveFile();
setTimeout(TimeKeeper_ReviewTimers, 60 * 1000); // runs every minute
}
http.listen(listenPort, function () {
console.log('listening on *:' + listenPort);
console.log('latest version.');
});
loadFile(); //loads the last saved set of data
TimeKeeper_ReviewTimers(); //starts the review process to delete expired timers and messages from the arrays