-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.html
More file actions
1218 lines (1194 loc) · 63.9 KB
/
app.html
File metadata and controls
1218 lines (1194 loc) · 63.9 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
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="UTF-8">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<title>QueUp</title>
<link href="styles.css" rel="stylesheet">
</head>
<body>
<nav>
<div id="navside1"><p id="time">Date/time here</p></div>
<div id="navcenter">
<p style="font-size: 40px">QueUp</p>
<p style="font-size: 28px">Queuing System</p>
</div>
<div id="navside2">
<div id="slider">
<span class="switchCylinder" role="img" aria-label="theme_switch" onclick="switchTheme()">
<span class="switchCircle" id="themeSwitchCircle"></span>
</span>
</div>
<div id="collapse" class="collapsible-in-overlay">
<div style='display: flex; flex-direction: row; align-items: center'>
<a target="_blank" href="https://github.com/norandomtechie/queup/" style="text-decoration-line: none;">
<img id="help" src="ghw.png">
</a>
<p id="gear" class="">⚙️</p>
</div>
<div class="collapsible">
<button class="btn" id="leaveroom" onclick="returnToOverlay()">Leave room</button>
<button class="btn" id="closeroom" onclick="closeRoom()">Close room</button>
<button class="btn" id="addroomowners" onclick="modRoomOwners('add')">Add room owners</button>
<button class="btn" id="delroomowners" onclick="modRoomOwners('del')">Delete room owners</button>
<button class="btn" id="toggleroomlock" onclick="toggleRoomLock('del')">Lock room</button>
<button class="btn" id="adminpanel" onclick="window.open('admin?room='+window.roomname, '_blank');">View control panel</button>
<button class="btn" id="adminpanel" onclick="toggleTimerView()">Toggle exam timer</button>
<button class="btn hide-if-not-owner" id="broadcastbtn" onclick="sendBroadcast()">Broadcast Message</button>
<p id="roomstatus">Room status: --roomstatus--</p>
</div>
</div>
</div>
</nav>
<div id="utils">
<div class="container" id="rooms">
<div id="queueadddiv" class="roomtop" onclick="createQueue()">
<div id="queueadd" class="queue">
<p>Add queue</p>
</div>
</div>
</div>
<div class="container" id="timer">
<div id="innertimer">
<h3 id="timertext" contenteditable onblur="checkTime(event)" onkeydown="checkTime(event)">2:00:00</h3>
<div class="row">
<button id="stopstart" onclick="toggleTimer(event)">▶</button>
<button id="resettimer" onclick="resetTimer()">
<svg width="50%" height="50%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 489.935 489.935" xml:space="preserve">
<g>
<path d="M278.235,33.267c-116.7,0-211.6,95-211.6,211.7v0.7l-41.9-63.1c-4.1-6.2-12.5-7.9-18.7-3.8c-6.2,4.1-7.9,12.5-3.8,18.7
l60.8,91.5c2.2,3.3,5.7,5.4,9.6,5.9c0.6,0.1,1.1,0.1,1.7,0.1c3.3,0,6.5-1.2,9-3.5l84.5-76.1c5.5-5,6-13.5,1-19.1
c-5-5.5-13.5-6-19.1-1l-56.1,50.7v-1c0-101.9,82.8-184.7,184.6-184.7s184.7,82.8,184.7,184.7s-82.8,184.7-184.6,184.7
c-49.3,0-95.7-19.2-130.5-54.1c-5.3-5.3-13.8-5.3-19.1,0c-5.3,5.3-5.3,13.8,0,19.1c40,40,93.1,62,149.6,62
c116.6,0,211.6-94.9,211.6-211.7S394.935,33.267,278.235,33.267z" stroke-width="0.5" fill="var(--text-color)">
</g>
</svg>
</button>
</div>
<p id="timerstatus" style="font-size: 14px; opacity: 0.7; display: none">Synced with room</p>
<svg width="100%" height="100%" viewbox="0 0 100 100" id="innertimer-border"><circle cy="50" fill="transparent" cx="50" r="49" stroke-width="0.5" stroke="var(--softer-btn-border)"></circle></svg>
</div>
<div class="row" style="margin-top: 20px;position: relative;top: 300px;">
<button id="synctimerbtn" class="btn" style="font-size: 16px; width: auto;" onclick="toggleTimerSync()">Enable timer sync</button>
</div>
</div>
</div>
<div class="queueoverlay">
<div class="panel" id="createpanel">
<h1>Create a room</h1>
<div class="row" id="createroomrow" style="justify-content: center; margin-bottom: 50px">
<input type="text" id="createroom" name="createroom" pattern="[A-Z0-9]{5}" placeholder="🔄 creates a valid room code." value="">
<p id="genroom" style="cursor: pointer; font-size: 40px; margin: 0">🔁</p>
</div>
<input type="button" id="createroombtn" style="cursor: pointer" value="Create">
</div>
<div class="panel">
<h1>Join a room</h1>
<div class="row" style="margin-bottom: 50px">
<input type="text" id="joinroom" name="joinroom" placeholder="Enter your 5-char room ID here." pattern="[A-Z0-9]{5}" value="">
</div>
<input type="button" id="joinroombtn" style="cursor: pointer" value="Join">
</div>
</div>
<script>
window.username = "--username--";
window.section = "--section--";
window.is_owner = false; // not a risk if changed manually (maliciously) client-side.
// all authz requests are checked against room owners.
function fetchAndLimit(url) {
return new Promise(async (resolve, reject) => {
try {
var resp = await fetch(url);
if (resp.status == 429) {
alert("You appear to be sending too many requests. Please slow down. Actions are blocked for the next 30 seconds.");
reject("Too many requests");
}
else if (resp.status == 423) {
alert("This room is currently locked. Ask the owner of the room (typically a TA or course staff) to unlock it.");
reject("Room locked");
}
else if ((resp.status == 403) || (resp.status == 401)) {
alert("You are not authorized to perform this action. Unauthorized requests will be logged.");
reject("Unauthorized");
}
else if (resp.status == 500) {
alert("An error occurred on the server. Please try again.");
reject("Server error");
}
resolve(resp);
}
catch(err) {
console.log("err", err);
reject(err);
}
})
}
async function closeRoom() {
if (document.querySelectorAll(".is-self").length > 0) {
alert("You are still in the room. Please remove yourself from any queues before leaving.");
return;
}
var c = confirm("Are you sure you want to close the room? This irreversibly removes all students (if any) and deletes the room itself, and will not be accessible until you create it again.");
if (!c) return;
try {
if (!window.is_owner) {
alert("You are not authorized to close this room. Unauthorized requests will be logged.");
return;
}
var response = await fetchAndLimit('roomd.wsgi?setup=true&action=del&room=' + roomname);
if (response.status == 400) {
var t = await response.text();
if (t.includes("permanent")) {
alert("This room is marked as permanent. As a result, it cannot be deleted.");
}
else {
alert("An error occurred while deleting the room. Closing out anyway...");
}
}
else if (response.status != 200) {
alert("An error occurred while deleting the room. Closing out anyway...");
}
returnToOverlay();
}
catch(err) {
alert("An error occurred on first fetch: " + err.toString());
console.error(err);
}
}
function returnToOverlay() {
if (document.querySelectorAll(".is-self").length > 0) {
alert("You are still in the room. Please remove yourself from any queues before leaving.");
return;
}
if (window.evtSource != null)
window.evtSource.close();
// remove rooms
Array.from(document.querySelectorAll(".roomtop:not(#queueadddiv)")).forEach(e => e.remove());
document.getElementById("gear").classList.toggle("opened", false);
document.querySelector(".collapsible").classList.toggle("opened", false);
document.getElementById("collapse").classList.toggle("collapsible-in-overlay", true);
document.getElementById("navside2").classList.toggle("small-screen", false);
document.getElementsByClassName("queueoverlay")[0].style.display = "flex";
}
function generateRandomRoomName() {
var roomname = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// do not accept roomname if a character in it occurs more than two times
while (roomname == "") {
for (var i = 0; i < 5; i++) {
roomname += chars.charAt(Math.floor(Math.random() * chars.length));
}
// more than 3 identical chars? try again
if (roomname.match(/(.)\1{2,}/))
roomname = "";
// must be not all letters and not all numbers
else if (roomname.match(/^[A-Z]+$/) || roomname.match(/^[0-9]+$/))
roomname = "";
}
document.getElementById("createroom").value = roomname;
}
async function createQueue() {
var queue = null;
while (queue == null || !(/^[a-zA-Z0-9]{3,15}$/.test(queue))) {
var queue = prompt("Enter a valid name for the queue.");
if ((queue == "") || (queue == null))
return;
}
try {
var response = await fetchAndLimit('roomd.wsgi?setup=true&action=add&room=' + roomname + '&queue=' + queue);
if (response.status != 200) {
t = await response.text();
alert("An error occurred while creating the queue. Error: " + t);
return;
}
}
catch(err) {
alert("An error occurred on first fetch: " + err.toString());
console.error(err);
}
}
async function createRoom() {
var roomname = document.getElementById("createroom").value;
if (roomname.length != 5 || !roomname.match(/[A-Z0-9]{5}/)) {
alert("Room name must be 5 characters long.");
return;
}
try {
var response = await fetchAndLimit('roomd.wsgi?setup=true&action=add&room=' + roomname);
console.log(response);
if (response.status != 200) {
alert("An error occurred while creating the room. It's possible the server is just down - try again later. If this was after multiple attempts, the room name may already be taken.");
return;
}
alert("Thanks for creating a QueUp room!\n\nPlease be aware that this room will self-delete after 24 hours to save disk space. If you are a teaching assistant/instructor for a course who needs to use this room long-term, please email Niraj (niraj@purdue.edu) to ask for the room to be made permanent. Include 'QueUp' and the room number in the subject line to ensure it gets past his spam filters!");
setupRoom(response, roomname);
}
catch(err) {
alert("An error occurred on first data fetch: " + err.toString());
console.error(err);
}
}
async function joinRoom() {
document.getElementById("joinroom").value = document.getElementById("joinroom").value.toUpperCase();
var roomname = document.getElementById("joinroom").value;
if (roomname.length != 5 || !roomname.match(/[A-Z0-9]{5}/)) {
alert("Room name must be 5 characters long and contain alphanumeric characters.");
return;
}
try {
var response = await fetchAndLimit('roomd.wsgi?setup=true&action=chk&room=' + roomname);
if (response.status != 200) {
alert("An error occurred while joining the room. Please double check the room code.");
return;
}
localStorage.lastjoinedroom = document.getElementById("joinroom").value;
setupRoom(response, roomname);
}
catch(err) {
alert("An error occurred on first fetch: " + err.toString());
console.error(err);
}
}
async function setupRoom(response, roomname) {
document.getElementById("collapse").classList.toggle("collapsible-in-overlay", false);
document.getElementById("navside2").classList.toggle("small-screen", true);
j = await response.text();
try {
json = JSON.parse(j);
}
catch(err) {
alert("An error occurred while parsing the response from the server. Response was: \n" + j);
return;
}
// ### CHANGED: Set firstRun flag to true to silence initial broadcast
window.firstRun = true;
// ### END CHANGED
window.is_owner = json["is-owner"];
window.section = json["section"];
var roomsubtitle = (json["subtitle"] === null) ? "" : json["subtitle"];
window.roomlocked = json["is-locked"];
window.roompermanent = json["is-permanent"];
console.log(json);
document.getElementById("queueadddiv").classList.toggle("hide-if-not-owner", !window.is_owner);
document.getElementById("closeroom").classList.toggle("hide-if-not-owner", !window.is_owner);
document.getElementById("addroomowners").classList.toggle("hide-if-not-owner", !window.is_owner);
document.getElementById("delroomowners").classList.toggle("hide-if-not-owner", !window.is_owner);
document.getElementById("toggleroomlock").classList.toggle("hide-if-not-owner", !window.is_owner);
document.getElementById("adminpanel").classList.toggle("hide-if-not-owner", !window.is_owner);
document.getElementById("roomstatus").classList.toggle("hide-if-not-owner", !window.is_owner);
document.getElementById("broadcastbtn").classList.toggle("hide-if-not-owner", !window.is_owner);
document.getElementById("synctimerbtn").classList.toggle("hide-if-not-owner", !window.is_owner);
// very hacky way to duplicate element while getting rid of event listeners.
if (window.is_owner) {
// not a redundant statement!!! this is to ensure that the event listener is removed.
document.getElementById("roomstatus").outerHTML = document.getElementById("roomstatus").outerHTML;
document.getElementById("roomstatus").innerHTML = `Room status: ${window.roompermanent ? "Permanent" : "Temporary"} [?]`;
document.getElementById("roomstatus").addEventListener("click", (e) => {
alert(window.roompermanent ? `This room has been marked permanent. As a result, it cannot be deleted, and will not automatically be removed after 24 hours of inactivity.`
: `This room is temporary, which means it will be removed after 24 hours of inactivity, and can be deleted by any of the room owners. \n\nIf you are a TA/instructor/professor who wishes to keep this room layout permanently to avoid having to recreate the room every day, please send Niraj (niraj@purdue.edu) an email with the room code and "Queup" in the subject line to make it permanent.`)
});
}
if (window.roomlocked == true)
document.getElementById("toggleroomlock").innerHTML = "Unlock Room";
else
document.getElementById("toggleroomlock").innerHTML = "Lock Room";
addRoom(roomname, roomsubtitle);
genRoom(roomname, JSON.parse(j));
window.roomname = roomname;
createEventSource();
}
function createEventSource() {
if (typeof(EventSource) !== "undefined") {
window.evtSource = new EventSource("roomd.wsgi?sseupdate=true&room=" + window.roomname);
window.evtSource.onopen = function() {
console.log("Connection established.");
document.getElementsByClassName("queueoverlay")[0].style.display = "none";
};
window.evtSource.onmessage = function(event) {
var json = JSON.parse(event.data);
// an empty response means the room was deleted.
// close the event source and return to the overlay.
console.log(json);
if (Object.keys(json).length == 0) {
clearInterval(window.activityCheck);
returnToOverlay();
return;
}
else {
genRoom(window.roomname, json);
}
// disableOperations is a hacky way to "rate limit" students from slamming the server
// with operations.
// this is INTENDED to be coupled with server responding with HTTP 429s to students
// who submit too many requests per second (cannot possibly be more than 3 requests per second).
window.disableOperations = false;
};
window.evtSource.onerror = async () => {
function handleError(test={'status': 0}, err) {
window.evtSource = null;
delete window.evtSource;
if (test.status == 400) {
alert("An unknown error occurred while trying to reconnect to the server. The returned status was 400, which could mean the room was deleted.");
returnToOverlay();
}
else if ((test.status == 502) || (test.status == 503)) {
console.error("Server returned 502/503. Could be restarting, waiting for 10 seconds before retrying...");
setTimeout(createEventSource, 10000);
}
else {
if (test.status == 0) {
// alert("An unknown error occurred while trying to reconnect to the server. The returned error was: " + err.toString());
}
else {
// alert("An unknown error occurred while trying to reconnect to the server. The returned status was: " + test.status);
}
if (err) {
console.error(err);
}
}
// retry...
}
if (!window.disableErrors) {
if (window.evtSource)
window.evtSource.close();
console.log("Connection lost.");
window.evtSource = null;
delete window.evtSource;
// retry...
setTimeout(createEventSource, 1000);
// // first, test the connection
// // create an AbortController to stop the network request because sseupdate will not return
// // unless there's an error
// const controller = new AbortController()
// const signal = controller.signal
// try {
// // do we have Internet?
// var test = await fetch("https://engineering.purdue.edu/~menon18/", {signal, cache: "no-store"});
// if (test.status == 200) {
// // then it was just a regular drop
// // kill the connection
// controller.abort();
// }
// else {
// handleError(test, null);
// }
// }
// catch(err) {
// handleError({status: 0}, err);
// }
// controller.abort();
}
}
// create an interval to check for activity every 1 hour.
// closeRoom if no activity is detected.
if (!window.lastActivity)
window.lastActivity = Date.now();
window.activityCheck = setInterval(() => {
// if not set, create a start time
// if the last activity was more than 1 hour ago, close the room.
if ((Date.now() - window.lastActivity) >= 60*60*1000 && (timerdiv.style.display != "flex")) {
returnToOverlay();
alert("No activity detected for 1 hour, room closed. Do not keep the room open if you are not using it!");
}
}, 60*60*1000);
}
else {
alert("This browser does not support Server-Sent Events, which is required to handle room functionality. Use a more modern browser like Firefox or Chrome.");
}
}
function genRoom(r, json) {
// ### CHANGED: Updated Broadcast logic to use firstRun
if (json.meta) {
// Broadcast
var bcast = json.meta.broadcast;
if (bcast && bcast.id !== "") {
// If this is the first run (e.g., joining a room), we silently acknowledge
// the current state so we don't alert old messages.
if (window.firstRun) {
window.lastBroadcastId = bcast.id;
}
// Otherwise, if the ID has changed, it's a new message.
else if (bcast.id !== window.lastBroadcastId) {
window.lastBroadcastId = bcast.id;
alert("BROADCAST RECEIVED:\n\n" + bcast.message);
}
}
// Timer
var timerData = json.meta.timer;
if (timerData) {
handleSyncedTimer(timerData);
}
}
// Ensure firstRun is false after the initial generation
window.firstRun = false;
// ### END CHANGED
// json format - { 'room': { 'queue': [username, time] } }
// so we extract queues by just taking the first key and keying into "json" to get the queues.
// make sure to sort by longest time created!
// Filter out new metadata key "meta"
var queues = json[Object.keys(json).filter(e => !["subtitle", "is-owner", "section", "is-permanent", "owners", "meta"].includes(e))[0]];
// delete queues that don't exist in the JSON
Array.from(document.querySelectorAll(".queue"))
.filter(_q => _q.id != "queueadd") // must be a real queue - do not remove "Add Queue"!
.map(_q => _q.id.slice(5)) // get the queue names
.filter(_q => _q && !Object.keys(queues).includes(_q)).forEach(_q => { // queues that are not in the JSON...
document.querySelector(`#queue${_q}`).remove(); // ...must be removed. start with the queue
document.querySelector(`[queue=${_q}]`).parentNode.remove(); // and then the title div.
});
Object.keys(queues).forEach(_q => {
if (document.querySelector(`#queue${_q}`) == null) {
addQueue(_q);
}
var htmlarray = document.querySelector(`#queue${_q}`);
var list = Array.from(document.querySelector(`#queue${_q}`).children);
q = queues[_q];
q.sort((a, b) => a[1] - b[1]);
// look at what's already in the queue DOMs and compare it to what's in the JSON
// then generate a optimized list of actions to perform.
// increases performance and reduces DOM thrashing.
var actions = syncArr(list.filter(e => !e.classList.contains('waiter-add')).map(e => e.querySelector(".username_text").innerHTML), q.map(e => e[0]));
actions.forEach(a => {
// format of a: ['action', username, (position)]
switch(a[0]) {
case "delete":
selectElmByUsername(a[1], _q) ? selectElmByUsername(a[1], _q).remove() : null;
break;
case "add":
var user = a[1];
var data = q.filter(e => e[0] == user)[0][2];
var marked = q.filter(e => e[0] == user)[0][3] == "1" ? true : false;
var section = q.filter(e => e[0] == user)[0][4];
section = section ? section : "";
if (a[1] == window.username) {
window.userdata = data;
window.usermarked = marked;
addSelf(_q);
}
else {
addToQueue(a[1], data, marked, section, _q);
}
break;
case "shift":
console.log(selectElmByUsername(a[1], _q), list[a[2]]);
htmlarray.insertBefore(selectElmByUsername(a[1], _q), list[a[2]]);
break;
}
});
if (actions.length > 0) {
// reset activity start time for the inactivity timer
window.lastActivity = Date.now();
}
// check if marked has changed for existing users
q.forEach(e => {
var elm = selectElmByUsername(e[0], _q);
if (elm != null) {
if (e[3] == "1") {
elm.classList.add("flashing");
// first button will be marked.
if (elm.querySelector(".waiterbtn"))
elm.querySelector(".waiterbtn").innerHTML = "Unmark";
}
else {
elm.classList.remove("flashing");
// first button will be unmarked.
if (elm.querySelector(".waiterbtn"))
elm.querySelector(".waiterbtn").innerHTML = "Mark";
}
}
});
// if a TA overrides visibility and both the waiter-add/is-self buttons are removed
// and if window.username is not in the queue, then assume that student is no longer
// in room and we can add waiter-add again
var list = Array.from(document.querySelector(`#queue${_q}`).children);
if (list.filter(e => e.classList.contains('waiter-add') || e.classList.contains('is-self')).length == 0) {
var html = `<div class="waiter waiter-add" onclick="addBtnHandler(event, '${_q}')"><p class="username_text">+</p></div>`;
var added = new DOMParser().parseFromString(html, 'text/html').body.children[0];
document.querySelector(`#queue${_q}`).appendChild(added);
}
// now sync up time
applyTimeData(_q, q);
})
}
function applyTimeData(q, roomdata) {
var list = Array.from(document.querySelector(`#queue${q}`).children);
if (['GLX8Q'].includes(window.roomname)) {
roomdata.forEach(a => {
var elm = list.filter(e => e.querySelector(".username_text").innerHTML.split(" ")[0] == a[0])[0];
var now = Date.now();
var then = new Date(parseFloat(a[1])*1000);
var minute = parseInt((now - then) / (60 * 1000));
var maxopacity = 0.7;
elm.classList.toggle('waiter-bg-max', false);
if (minute <= 10) {
elm.style["background-color"] = `var(--waiter-bg-0)`;
}
else if (minute > 10 && minute <= 20) {
elm.style["background-color"] = `var(--waiter-bg-1)`;
}
else if (minute > 20 && minute <= 30) {
elm.style["background-color"] = `var(--waiter-bg-2)`;
}
else if (minute > 30 && minute <= 45) {
elm.style["background-color"] = `var(--waiter-bg-3)`;
}
else if (minute > 45 && minute <= 60) {
elm.style["background-color"] = `var(--waiter-bg-4)`;
}
else if (minute > 60 && minute <= 1000) {
elm.style["background-color"] = `var(--waiter-bg-5)`;
}
else {
elm.classList.toggle('waiter-bg-max', true);
elm.style["background-color"] = `var(--waiter-bg-max)`;
elm.style["color"] = 'var(--waiter-bg-text-max)';
}
elm.querySelector('.time_text').innerHTML = `${minute < 1 ? "<1" : minute} min`;
});
}
else {
roomdata.forEach(a => {
var elm = list.filter(e => e.querySelector(".username_text").innerHTML.split(" ")[0] == a[0])[0];
var now = Date.now();
var then = new Date(parseFloat(a[1])*1000);
var minute = parseInt((now - then) / (60 * 1000));
var max = 5;
var maxopacity = 0.7;
elm.style["background-color"] = `var(--waiter-bg-${minute <= max ? minute : max})`;
elm.querySelector('.time_text').innerHTML = `${minute < 1 ? "<1" : minute} min`;
});
}
}
window.onbeforeunload = () => {
window.disableErrors = true;
}
window.onload = async () => {
document.body.style.opacity = 1;
clock();
// initialize if not set
if (!localStorage.darkmode) {
localStorage.darkmode = "false";
}
if (localStorage.darkmode == "true") {
document.documentElement.setAttribute("theme", "dark");
}
else {
document.documentElement.setAttribute("theme", "light");
}
document.addEventListener('click', (e) => {
if (e.target.id != "gear" && document.querySelector("#gear").classList.contains("opened")) {
document.querySelector("#gear").click();
}
}, true);
setTimeout(() => {
// if room= specified in query string, join room with it
if (window.location.search.includes("room=")) {
var room = window.location.search.split("room=")[1].split("&")[0];
document.getElementById("joinroom").value = room;
joinRoom();
}
}, 250);
window.lastBroadcastId = "";
window.timerSync = false;
}
function syncArr(_old, _new) {
var actions = [];
var diff = _new.filter(x => !_old.includes(x));
var del = _old.filter(x => !_new.includes(x));
del.forEach(i => {
actions.push(['delete', i]);
_old = _old.filter(x => x != i);
});
diff.forEach(i => {
actions.push(['add', i]);
_old.push(i);
});
_new.forEach((e,i) => {
if (_old.indexOf(e) != i) {
actions.push(['shift', e, i]);
}
})
return actions;
}
function selectElmByUsername(username, queue) {
var list = Array.from(document.querySelector(`#queue${queue}`).children).filter(e => e.querySelector(".username_text").innerHTML.split(" ")[0] == username);
return list.length > 0 ? list[0] : null;
}
function clock() {
function IntTwoChars(i) {
return `0${i}`.slice(-2);
}
var time = new Date();
document.querySelector("#time").innerHTML = `${IntTwoChars(time.getHours())}:${IntTwoChars(time.getMinutes())}`;
setTimeout(clock, 1000);
}
function addSelf(queue) {
var list = Array.from(document.querySelector(`#queue${queue}`).children).filter(e => e.classList.contains('waiter-add'));
if (list.length > 0) {
list[0].remove();
}
if (window.section == "")
var sec = "";
else
var sec = `<p class="section_text">${window.section == "" ? "No section" : "Sec " + window.section}</p>`;
var html = `<div class="waiter is-self ${window.usermarked ? "flashing" : ""}" onclick="addBtnHandler(event, '${queue}')">
<p class="username_text">${window.username}</p>
<p class="data_text">${window.userdata}</p>
<p class="time_text"><1 min</p>
${sec}
</div>`;
var added = new DOMParser().parseFromString(html, 'text/html').body.children[0];
document.querySelector(`#queue${queue}`).appendChild(added);
}
function delSelf(queue) {
var list = Array.from(document.querySelector(`#queue${queue}`).children).filter(e => e.classList.contains('is-self'));
if (list.length > 0) {
list[0].remove();
}
// add back add button if it's not there
var list = Array.from(document.querySelector(`#queue${queue}`).children).filter(e => e.classList.contains('waiter-add'));
if (list.length == 0) {
var html = `<div class="waiter waiter-add" onclick="addBtnHandler(event, '${queue}')"><p class="username_text">+</p></div>`;
var added = new DOMParser().parseFromString(html, 'text/html').body.children[0];
document.querySelector(`#queue${queue}`).appendChild(added);
}
}
function delFromRoomTA(username, queue) {
fetchAndLimit(`roomd.wsgi/?action=del&room=${window.roomname}&queue=${queue}&username=${username}`);
var list = Array.from(document.querySelector(`#queue${queue}`).children).filter(e => e.classList.contains('waiter') && e.querySelector('.username_text').innerHTML == username);
if (list.length > 0) {
list[0].remove();
}
}
function performOp(action, queue, username=null) {
try {
if (window.is_owner && username != null) {
if (action == "del")
delFromRoomTA(username, queue);
}
else {
if (action == "add") {
var userdata = null;
while ((userdata == null) || !/^[a-zA-Z0-9 ,\_\'\(\)]{1,50}$/.test(userdata)) {
var userdata = prompt("Enter your name, or other text that would allow a TA to identify you in-person (eg. your name, station number) or online (Zoom name). Press Escape/Cancel to close.", window.userdata);
if (userdata == null) {
window.disableOperations = false;
return;
}
}
window.userdata = userdata;
fetchAndLimit(`roomd.wsgi/?action=add&room=${window.roomname}&queue=${queue}&waitdata=${userdata}`)
.then(r => r.text())
.then(t => {
if (t.startsWith("[cooldown]")) {
alert(t.split(" ").slice(1).join(" "));
delSelf(queue);
}
else if (t.startsWith("[singlequeue]")) {
alert(t.split(" ").slice(1).join(" "));
delSelf(queue);
window.disableOperations = false;
}
})
.catch(err => {
window.disableOperations = false;
if (err.includes("Room locked")) {
delSelf(queue);
}
else if (err.includes("[cooldown]")) {
delSelf(queue);
}
})
}
else {
fetchAndLimit(`roomd.wsgi/?action=del&room=${window.roomname}&queue=${queue}`);
}
var qlist = document.querySelector(`#queue${queue}`).children;
var added = qlist[qlist.length - 1];
if (action == "add") {
addSelf(queue);
}
else if (action == "del") {
delSelf(queue);
}
}
}
catch(err) {
console.log(`Error occurred while performing ${action} on room ${window.roomname}, queue ${queue}.`);
console.error(err);
}
}
function addToQueue(username, data, marked, section, queue) {
var list = document.querySelector(`#queue${queue}`);
// do not add duplicates!
if (Array.from(list.children).map(e => e.querySelector(".username_text").innerHTML).includes(username)) {
return;
}
var owner_buttons = window.is_owner ? `<div class="owner-buttons">
<button class="btn waiterbtn" onclick='markOrDelUser(event, "mark")'>Mark</button>
<button class="btn waiterbtn" onclick='markOrDelUser(event, "del")'>Delete</button>
</div>` : "";
var time = "<1";
var parser = new DOMParser();
var user_data = `<p class="data_text">${data}</p>`;
var newhtml = parser.parseFromString(`<div class="waiter ${marked ? "flashing" : ""}"><p class="username_text">${username}</p>${user_data}<p class="time_text">${time} min</p><p class="section_text">${(section == "") ? "No section" : ("Sec " + section)}</p>${owner_buttons}</div>`, 'text/html');
var elm = newhtml.body.children[0];
console.log("addtoqueue", elm, list.children);
// has our own entry already been added? Then add the incoming entry at the end of the list.
if (Array.from(list.children).filter(e => e.classList.contains("waiter-add")).length > 0)
list.insertBefore(elm, list.children[list.children.length - 1]);
else
list.insertBefore(elm, null);
}
function addBtnHandler(event, queue) {
if (window.disableOperations) return;
window.disableOperations = true;
if (event.currentTarget.classList.contains("waiter-add")) {
// then we're adding a new one
performOp('add', queue);
}
else if (window.is_owner && !event.currentTarget.classList.contains("is-self")) {
// we are a TA and removing someone else's username, not our own
performOp('del', queue, event.currentTarget.querySelector('.username_text').innerHTML.split(" ")[0]);
}
else if (event.currentTarget.classList.contains("is-self")) {
// then we're removing an existing one
performOp('del', queue);
}
}
async function renameQueue(event) {
if (event.type != "blur")
return;
if (!window.is_owner)
return;
event.preventDefault();
var curTarget = event.currentTarget;
curTarget.innerHTML = curTarget.innerHTML.replace(" ", "");
curTarget.innerHTML = curTarget.innerHTML.replace("<br>", "");
curTarget.blur();
// name was not changed.
if (curTarget.innerHTML == curTarget.getAttribute("queue")) {
return;
}
if (curTarget.innerHTML == "") {
var r = confirm("Setting the queue name to an empty string/only spaces will delete the queue. Are you sure you want to continue?");
if (!r) {
curTarget.innerHTML = curTarget.getAttribute("queue");
return;
}
var r = await fetchAndLimit(`roomd.wsgi/?setup=true&action=del&room=${window.roomname}&queue=${curTarget.getAttribute("queue")}`);
if (r.status != 200) {
alert("An error occurred while deleting the queue. Please try again.");
alert(await r.text());
curTarget.innerHTML = curTarget.getAttribute("queue");
return;
}
else {
curTarget.parentNode.remove();
}
return; // do not do a rename after this.
}
else if (!/^[a-zA-Z0-9\_]{3,15}$/.test(curTarget.innerHTML)) {
alert("Queue name must be alphanumeric with optional underscores, be more than 3 characters and less than 16 characters long.");
curTarget.innerHTML = curTarget.getAttribute("queue");
return;
}
var r = await fetchAndLimit(`roomd.wsgi/?setup=true&action=ren&room=${window.roomname}&queue=${curTarget.getAttribute("queue")}&newqueue=${curTarget.innerHTML}`);
if (r.status != 200) {
alert("An error occurred while renaming the queue. Please try again.");
curTarget.innerHTML = curTarget.getAttribute("queue");
return;
}
else {
// response will add back the renamed queue
curTarget.parentNode.remove();
// document.querySelector(`#queue${curTarget.getAttribute("queue")}`).remove();
}
}
async function setRoomSubtitle(event) {
// triggers when focus is shifted away (by pressing Enter or clicking somewhere else)
if (!window.is_owner)
return;
event.preventDefault();
var curTarget = event.currentTarget;
curTarget.innerHTML = curTarget.innerHTML.replace(/<br>/g, "");
curTarget.innerHTML.trim();
curTarget.blur();
// name was not changed.
if (curTarget.innerHTML == curTarget.getAttribute("subtitle")) {
return;
}
// special handling for empty subtitles
else if ((curTarget.innerHTML == "") || (curTarget.innerHTML == "<br>") || (curTarget.innerHTML == "Add room information...")) {
curTarget.innerHTML = "Add room information...";
curTarget.setAttribute("subtitle", "");
var subtitle = "";
}
else {
if (!/^[a-zA-Z0-9 ,\_\'\(\)\-]{1,130}$/.test(curTarget.innerHTML)) {
alert("Room subtitle can only contain the characters a-z, A-Z, 0-9, spaces, hyphens, and underscores, and must be less than 130 characters long.");
curTarget.innerHTML = curTarget.getAttribute("subtitle");
return;
}
var subtitle = curTarget.innerHTML;
}
var r = await fetchAndLimit(`roomd.wsgi/?setup=true&action=setsub&room=${window.roomname}&subtitle=${subtitle}`);
if (r.status != 200) {
alert("An error occurred while setting the room description. Please try again.");
curTarget.innerHTML = curTarget.getAttribute("subtitle");
}
else {
curTarget.classList.toggle("textadded", curTarget.innerHTML != "Add room information...");
curTarget.setAttribute("subtitle", subtitle);
}
}
function addRoom(room, subtitle) {
// this application will not do multiple rooms. remove all rooms first
var parser = new DOMParser();
if (subtitle == '' && !window.is_owner) {
var subtitle_p = '';
}
else if (subtitle == '') {
var subtitle_p = `<p class="roomsubtitle" spellcheck="false" contenteditable subtitle="">Add room information...</p>`;
}
else {
var style = window.is_owner ? "" : "style='cursor:default'";
var edit = window.is_owner ? "contenteditable" : "";
var subtitle_p = `<p class="roomsubtitle textadded" spellcheck="false" ${style} ${edit} subtitle=${subtitle}>${subtitle}</p>`;
}
var newhtml = parser.parseFromString(`
<div class="roomtop">
<p class="roomtitle">Room ${room}</p>
<div class="helpdiv row">${subtitle_p}</div>
</div>`, 'text/html');
var elm = newhtml.body.children[0];
document.querySelector(`#rooms`).insertBefore(elm, document.querySelector("#queueadddiv"));
if (window.is_owner) {
document.querySelector(".roomsubtitle").addEventListener('blur', setRoomSubtitle);
document.querySelector(".roomsubtitle").addEventListener('keydown', (event)=>{if(['Enter','Escape'].includes(event.key)){event.preventDefault();event.currentTarget.blur()}});
}
}
function clearQueue(queue) {
if (!window.is_owner) {
alert("You are not authorized to clear this queue. Unauthorized requests will be logged.");
return;
}
fetchAndLimit(`roomd.wsgi/?setup=true&action=clear&room=${window.roomname}&queue=${queue}`);
}
function markOrDelUser(event, action='mark') {
if (!window.is_owner) {
alert("You are not authorized to perform this action. Unauthorized requests will be logged.");
return;
}
var queue = event.currentTarget.parentNode.parentNode.parentNode.id.slice(5);
var username = event.currentTarget.parentNode.parentNode.querySelector(".username_text").innerHTML;
if (action == 'mark') {
// send a "mark" signal for this user. if already marked, will be unmarked.
fetchAndLimit(`roomd.wsgi/?setup=true&action=mark&room=${window.roomname}&queue=${queue}&username=${username}`);
}
else {
// delete user from queue.
performOp('del', queue, username);
}
}
function addQueue(queue) {
var parser = new DOMParser();
var newhtml = parser.parseFromString(`<div style="width: 100%; display: flex; flex-direction: row; justify-content: space-between; align-items: center">
<p title="Want to delete this queue? Set the name to an empty string." class="queuetitle" ${window.is_owner ? "" : "style='cursor:default'"}" onblur="renameQueue(event)" onkeydown="if(['Enter','Escape'].includes(event.key)){event.preventDefault();event.currentTarget.blur()}" queue="${queue}" ${window.is_owner ? "contenteditable" : ""}>${queue}</p>
${window.is_owner ? ('<button class="btn clearbtn" style="display: flex;" onclick=\'clearQueue("' + queue + '")\'>Clear</button>') : ""}
</div>
<div id="queue${queue}" class="queue"></div>`, 'text/html');
document.querySelector(".roomtop").appendChild(newhtml.body.children[0]);
// JS madness - appendChild REMOVES THE CHILD FROM NEWHTML!
document.querySelector(".roomtop").appendChild(newhtml.body.children[0]);
}
// for later theme changes
function switchTheme() {
if (localStorage.darkmode == "true") {
localStorage.darkmode = "false";
}
else {
localStorage.darkmode = "true";
}
document.documentElement.setAttribute("theme", localStorage.darkmode == "true" ? "dark" : "light");
}
async function toggleRoomLock() {
try {
var action = document.getElementById("toggleroomlock").innerHTML == "Lock Room" ? "lock" : "unlock";
var response = await fetchAndLimit(`roomd.wsgi?setup=true&action=${action}&room=` + window.roomname);
if (response.status != 200) {
alert("An error occurred while toggling the room lock. Error: " + await response.text());
return;
}
else {
var locked = action == "lock";
window.roomlocked = locked;
alert("Successfully toggled room lock. Room is now " + (locked ? "locked" : "unlocked") + ". " +
"Users can " + (locked ? "no longer" : "now") + " add themselves to queues.");
}
document.getElementById("toggleroomlock").innerHTML = locked ? "Unlock Room" : "Lock Room";
}
catch(err) {
alert("An error occurred while toggling the room lock: " + err.toString());
console.error(err);
}
}
async function modRoomOwners(action='add') {
var owners = null;
while (owners == null) {
var owners = prompt("Enter a comma-separated list of usernames to " + (action == "add" ? "add as" : "delete from") + " room owners. (eg. user1, user2, user3)\n" +
"You can also enter an empty string to get the current list of owners. Usernames must be in all small letters.");
if (owners == null) {
return;
}
owners = owners.replace(/ /g, "");
// mistake typing usernames
try { owners = owners.split(","); }
catch(err) { owners = null; }
if (owners != "" && !/^[a-z0-9\-, /]{3,300}$/.test(owners.join(","))) {
alert("Usernames must be alphanumeric with optional hyphens, be more than 3 characters and less than 16 characters long.\nIf you were putting in a lot of people's usernames at once, consider splitting the list and trying again.");
owners = null;
}
}
try {
var _action = action == 'add' ? '' : 'del';
var response = await fetchAndLimit(`roomd.wsgi?setup=true&action=${_action}own&room=` + window.roomname + '&newusers=' + owners.join(","));
if (response.status != 200) {
alert("An error occurred while modifying the owner list. Error: " + await response.text());
return;
}
else {
var newowners = await response.text();
newowners = newowners.replace(/"/g, "").replace(/'/g, "");
if (owners == "") {
alert("The current list of owners for this room is " + newowners + ".");
}
else {
alert("Successfully modified owner list. List of owners for this room is: " + newowners + ".");
}
}
}
catch(err) {
alert("An error occurred while modifying owners: " + err.toString());
console.error(err);
}
}
// set up gear collapsible
var gear = document.getElementById("gear");
gear.addEventListener('click', function(event) {
event.currentTarget.classList.toggle("opened");
document.querySelector(".collapsible").classList.toggle("opened");
});
// permit only allowed characters
document.getElementById("joinroom").addEventListener('keydown', (e) => {
if (e.key == 'Enter') {
document.querySelector('#joinroombtn').click();
}
});
document.getElementById("createroom").addEventListener('keydown', (e) => {
if (e.key == 'Enter') {