-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.js
More file actions
644 lines (598 loc) · 20.9 KB
/
common.js
File metadata and controls
644 lines (598 loc) · 20.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
const protocol = window.location.protocol;
const hostname = window.location.hostname;
// For development
const serverport = 8081;
// For production
// const serverport = window.location.port || (protocol === "https:" ? 443 : 80);
// Auth Server
const APIENDPOINT_LOGIN = `${protocol}//${hostname}:${serverport}/userauth/login`;
const APIENDPOINT_USERCREATE = `${protocol}//${hostname}:${serverport}/userauth/signup`;
const APIENDPOINT_REFRESH = `${protocol}//${hostname}:${serverport}/userauth/refresh`;
const APIENDPOINT_LOGOUT = `${protocol}//${hostname}:${serverport}/userauth/logout`;
const APIENDPOINT_GUESTLOGIN = `${protocol}//${hostname}:${serverport}/userauth/guestLogin`;
const APIENDPOINT_TOKENINFO = `${protocol}//${hostname}:${serverport}/userauth/jwtInfo`;
const APIENDPOINT_RESETPASSWORDREQUEST = `${protocol}//${hostname}:${serverport}/userauth/resetPassword?email=`;
const APIENDPOINT_RESETPASSWORD = `${protocol}//${hostname}:${serverport}/userauth/resetPassword`;
const APIENDPOINT_PRIVILAGELEVEL = `${protocol}//${hostname}:${serverport}/info/users/me/privilage_level`;
const APIENDPOINT_SELFUSER = `${protocol}//${hostname}:${serverport}/info/users/me`;
const APIENDPOINT_USERINFOBYID = `${protocol}//${hostname}:${serverport}/info/users/getById/`;
const APIENDPOINT_USERINFOUPDATE = `${protocol}//${hostname}:${serverport}/update/user/update`;
const APIENDPOINT_UNAPPROVEDUSERS = `${protocol}//${hostname}:${serverport}/admin/users/getUnapprovedUsers`;
const APIENDPOINT_ADMINAPPROVEUSER = `${protocol}//${hostname}:${serverport}/admin/users/approveUser/`;
const APIENDPOINT_ADMINREJECTUSER = `${protocol}//${hostname}:${serverport}/admin/users/rejectUser/`;
const APIENDPOINT_ADMINEDITUSER = `${protocol}//${hostname}:${serverport}/admin/users/update`;
const APIENDPOINT_USERSLIST = `${protocol}//${hostname}:${serverport}/admin/users/list`;
const APIENDPOINT_DELETEUSER = `${protocol}//${hostname}:${serverport}/admin/users/delete/`;
const APIENDPOINT_LISTFILES = `${protocol}//${hostname}:${serverport}/files/listFiles`;
const APIENDPOINT_VIDEOPLAYBACK = `${protocol}//${hostname}:${serverport}/files/video/`;
const APIENDPOINT_GETFILE = `${protocol}//${hostname}:${serverport}/files/getFile/`;
const APIENDPOINT_DELETEFILE = `${protocol}//${hostname}:${serverport}/admin/files/delete/`;
const APIENDPOINT_UPLOADFILE = `${protocol}//${hostname}:${serverport}/admin/files/upload`;
const APIENDPOINT_DEVICELIST = `${protocol}//${hostname}:${serverport}/admin/devices/listDevices`;
const privilage_level_dict = {
NONE: 0,
GUEST: 1,
ADMIN: 2,
CMSADMIN: 3
};
const rev_privilage_level_dict = {
0: "NONE",
1: "GUEST",
2: "ADMIN",
3: "CMSADMIN"
};
const file_type_dict = {
NONE: 0,
IMAGE: 1,
PDF: 2,
VIDEO: 3
};
const rev_file_type_dict = {
0: "NONE",
1: "IMAGE",
2: "PDF",
3: "VIDEO"
};
let loadedPages = [];
function loadPagetoElementInstant(page, element, loadcss, loadjs, forceload, afterload) {
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
tooltipTriggerList.forEach((tooltipTriggerEl) => {
const tooltipInstance = bootstrap.Tooltip.getInstance(tooltipTriggerEl);
if (tooltipInstance) {
tooltipInstance.dispose();
}
});
if(!loadedPages.includes(page) || forceload) {
fetch(`pages/html/${page}.html`) // Fetch HTML file from server
.then(response => response.text())
.then(html => {
document.getElementById(element).innerHTML = html;
if(!loadjs) {
let script = document.createElement("script");
script.src = `pages/js/${page}_script.js`;
script.async = true;
document.body.appendChild(script);
}
if(!loadcss) {
let link = document.createElement("link");
link.rel = "stylesheet";
link.href = `pages/css/${page}_style.css`;
link.onload = () => console.log("Stylesheet loaded successfully");
link.onerror = () => console.error("Failed to load stylesheet");
document.head.appendChild(link);
}
if(afterload) afterload();
});
loadedPages.push(page);
} else {
fetch(`pages/html/${page}.html`) // Fetch HTML file from server
.then(response => response.text())
.then(html => {
document.getElementById(element).innerHTML = html;
});
}
}
function loadComponent(component, loadcss, loadjs) {
fetch(`components/html/component_${component}.html`) // Fetch HTML file from server
.then(response => response.text())
.then(html => {
// document.getElementById("contentArea").insertAdjacentHTML("afterbegin", html);
document.getElementById("contentArea").innerHTML += html;
if(!loadjs) {
let script = document.createElement("script");
script.src = `components/js/component_${component}_script.js`;
script.async = true;
document.body.appendChild(script);
}
if(!loadcss) {
let link = document.createElement("link");
link.rel = "stylesheet";
link.href = `components/css/component_${component}_style.css`;
link.onload = () => console.log("Stylesheet loaded successfully");
link.onerror = () => console.error("Failed to load stylesheet");
document.head.appendChild(link);
}
});
}
function loadPagetoElement(page, element, loadcss, loadjs) {
setTimeout(function () {
loadPagetoElementInstant(page, element, loadcss, loadjs);
}, 450);
}
async function loadPageIntoElementAfterComponents(page, components, element, loadcss, loadjs) {
for (const component of components) {
await new Promise((resolve) => {
fetch(`components/html/component_${component.name}.html`)
.then(response => response.text())
.then(html => {
document.getElementById("contentArea").innerHTML += html;
if (!component.loadJS) {
const script = document.createElement("script");
script.src = `components/js/component_${component.name}_script.js`;
script.async = true;
document.body.appendChild(script);
}
if (!component.loadCSS) {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = `components/css/component_${component.name}_style.css`;
link.onload = () => console.log("Stylesheet loaded successfully");
link.onerror = () => console.error("Failed to load stylesheet");
document.head.appendChild(link);
}
setTimeout(resolve, 10);
});
});
}
loadPagetoElementInstant(page, element, loadcss, loadjs);
}
async function doGuestLogin() {
var login_response = await guestLogin();
if("error" in login_response) {
loadPagetoElementInstant("login", "contentArea", false, false);
return;
}
const token = login_response["token"];
const refreshtoken = login_response["refreshToken"];
localStorage.setItem("usertoken", token);
localStorage.setItem("userrefreshtoken", refreshtoken);
localStorage.setItem("loggedin", true);
const userinfo = await getUserInfo(token);
localStorage.setItem("user", JSON.stringify(userinfo));
location.reload();
}
async function onPageLoad() {
if(!localStorage.getItem("loggedin")) {
// loadPagetoElementInstant("login", "contentArea", false, false);
await doGuestLogin();
} else {
loadPageIntoElementAfterComponents("dashboard", [
{ name: "navbar", loadCSS: true, loadJS: false },
{ name: "sidebar", loadCSS: false, loadJS: false }
], "layoutSidenav_content", true, false);
}
}
async function sendPOSTRequest(url, body, authtoken) {
if(authtoken) {
let response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${authtoken}`
},
body: JSON.stringify(body)
});
let result = await response.json();
return result;
}
let response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body)
});
let result = await response.json();
return result;
}
async function sendPOSTRequestForm(url, body, authtoken) {
let response = await fetch(url, {
method: "POST",
headers: {
"Authorization": `Bearer ${authtoken}`
},
body: body
});
let result = await response.json();
return result;
}
async function sendPOSTRequestString(url, body, authtoken) {
let response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "text/plain",
"Authorization": `Bearer ${authtoken}`
},
body: body
});
let result = await response.json();
return result;
}
async function sendGETRequest(url, authtoken) {
if(authtoken) {
let response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${authtoken}`
}
});
let result = await response.json();
return result;
}
let response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
}
});
let result = await response.json();
return result;
}
async function sendGETRequestBlob(url, authtoken) {
let response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${authtoken}`
}
});
let result = await response.blob();
return result;
}
async function sendDELETERequest(url, reason, authtoken) {
let response = await fetch(url, {
method: "DELETE",
headers: {
"Content-Type": "plain/text",
"Authorization": `Bearer ${authtoken}`
},
body: reason
});
let result = await response.json();
return result;
}
function isEmptyOrWhitespace(str) {
return str.trim().length === 0;
}
var newModal;
function createAndShowModal(header, body, footer) {
// Create the modal HTML dynamically
const modalHtml = `
<div class="modal fade" id="newModal" tabindex="-1" aria-labelledby="newModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
${header ? `
<!-- Modal Header -->
<div class="modal-header">
${header}
</div>
` : ""}
${body ? `
<!-- Modal Body -->
<div class="modal-body">
${body}
</div>
` : ""}
${footer ? `
<!-- Modal Footer -->
<div class="modal-footer">
${footer}
</div>
` : ""}
</div>
</div>
</div>
`;
document.getElementById("modalContainer").innerHTML = modalHtml;
newModal = new bootstrap.Modal(document.getElementById('newModal'));
newModal.show();
document.getElementById('newModal').addEventListener('hidden.bs.modal', function () {
document.getElementById('newModal').remove();
});
}
function closeModal() {
newModal.hide();
}
function showTimedAlert(message, timeout = 5000, color="info") {
const alertId = `alert-${Date.now()}`;
const alertHTML = `
<div id="${alertId}" class="alert alert-${color} alert-dismissible fade show mb-2 position-relative" role="alert" style="min-width: 300px;">
${message}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
<div class="progress position-absolute bottom-0 start-0 w-100" style="height: 4px;">
<div class="progress-bar bg-${color}" role="progressbar" style="width: 100%; transition: width ${timeout}ms linear;"></div>
</div>
</div>
`;
document.getElementById("alert-container").insertAdjacentHTML("beforeend", alertHTML);
setTimeout(() => {
const alertElement = document.getElementById(alertId);
if (alertElement) {
alertElement.classList.remove("show");
alertElement.addEventListener("transitionend", () => {
alertElement.remove();
});
}
}, timeout);
}
function isotimeToHumanTime(inputstring) {
// Remove the IANA zone part (e.g., [Asia/Kolkata])
const cleaned = inputstring.replace(/\[.*?\]$/, "");
const date = new Date(cleaned);
return date.toLocaleString("en-US", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hourCycle: "h23",
timeZoneName: 'short'
});
}
function timeSort(a, b) {
const [h1, m1] = a.split(':').map(Number);
const [h2, m2] = b.split(':').map(Number);
return h1 !== h2 ? h1 - h2 : m1 - m2;
}
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(String(email).toLowerCase());
}
async function getUserInfoById(id, authtoken) {
const url = APIENDPOINT_USERINFOBYID + id;
try {
const response = await sendGETRequest(url, authtoken);
return response;
} catch (error) {
console.error("Error fetching user info by ID:", error);
throw error;
}
}
async function getUserList(authtoken) {
const url = APIENDPOINT_USERSLIST;
try {
const response = await sendGETRequest(url, authtoken);
return response;
} catch (error) {
console.error("Error fetching user list:", error);
throw error;
}
}
async function getPrivilageLevel(authtoken) {
const url = APIENDPOINT_PRIVILAGELEVEL;
try {
const response = await sendGETRequest(url, authtoken);
return response;
} catch (error) {
console.error("Error fetching privilage level:", error);
throw error;
}
}
async function loginUser(email, password) {
const url = APIENDPOINT_LOGIN;
const body = {
email: email,
password: password
};
try {
const response = await sendPOSTRequest(url, body);
return response;
} catch (error) {
console.error("Error logging in user:", error);
throw error;
}
}
async function getUserInfo(authtoken) {
const url = APIENDPOINT_SELFUSER;
try {
const response = await sendGETRequest(url, authtoken);
return response;
} catch (error) {
console.error("Error fetching user info:", error);
throw error;
}
}
async function refreshToken(refreshtoken) {
try {
const response = await sendPOSTRequest(APIENDPOINT_REFRESH, {
refreshToken: refreshtoken
});
return response;
} catch (error) {
console.error("Error refreshing token:", error);
throw error;
}
}
async function getTokenInfo(authtoken) {
const url = APIENDPOINT_TOKENINFO;
try {
const response = await sendPOSTRequest(url, {
token: authtoken
});
return response;
} catch (error) {
console.error("Error fetching token info:", error);
throw error;
}
}
async function createUser(email, password, name, username, location, authtoken) {
const url = APIENDPOINT_USERCREATE;
const body = {
email: email,
password: password,
fullname: name,
username: username,
location: location
};
try {
const response = await sendPOSTRequest(url, body, authtoken);
return response;
} catch (error) {
console.error("Error creating user:", error);
throw error;
}
}
async function getUnapprovedUsers(authtoken) {
const url = APIENDPOINT_UNAPPROVEDUSERS;
try {
const response = await sendGETRequest(url, authtoken);
return response;
} catch (error) {
console.error("Error fetching users:", error);
throw error;
}
}
async function approveUser(id, authtoken) {
const url = APIENDPOINT_ADMINAPPROVEUSER + id;
try {
const response = await sendGETRequest(url, authtoken);
return response;
} catch (error) {
console.error("Error approving user:", error);
throw error;
}
}
async function rejectUser(id, reason, authtoken) {
const url = APIENDPOINT_ADMINREJECTUSER + id;
try {
const response = await sendPOSTRequestString(url, reason, authtoken);
return response;
} catch (error) {
console.error("Error rejecting user:", error);
throw error;
}
}
async function deleteUserAdmin(id, reason) {
const url = APIENDPOINT_DELETEUSER + id;
try {
const response = await sendDELETERequest(url, reason, localStorage.getItem("usertoken"));
return response;
} catch (error) {
console.error("Error deleting user:", error);
throw error;
}
}
async function logoutUser() {
const url = APIENDPOINT_LOGOUT;
try {
const response = await sendPOSTRequest(url, {
refreshToken: localStorage.getItem("userrefreshtoken"),
jwtToken: localStorage.getItem("usertoken")
}, localStorage.getItem("usertoken"));
return response;
} catch (error) {
console.error("Error logging out user:", error);
throw error;
}
}
async function updateUser(userData, authtoken) {
const url = APIENDPOINT_ADMINEDITUSER;
try {
const response = await sendPOSTRequest(url, userData, authtoken);
return response;
} catch (error) {
console.error("Error updating user:", error);
throw error;
}
}
async function resetPasswordRequest(email) {
const url = APIENDPOINT_RESETPASSWORDREQUEST + email;
try {
const response = await sendGETRequest(url);
return response;
} catch (error) {
console.error("Error requesting password reset:", error);
throw error;
}
}
async function resetPassword(otp, email, newPassword) {
const url = APIENDPOINT_RESETPASSWORD;
const body = {
otp: otp,
email: email,
newpassword: newPassword
};
try {
const response = await sendPOSTRequest(url, body);
return response;
} catch (error) {
console.error("Error resetting password:", error);
throw error;
}
}
async function listFilesRequest(authtoken) {
const url = APIENDPOINT_LISTFILES;
try {
const response = await sendGETRequest(url, authtoken);
return response;
} catch (error) {
console.error("Error requesting file list:", error);
throw error;
}
}
async function getFileRequest(fileId, authtoken) {
const url = APIENDPOINT_GETFILE + fileId;
try {
const response = await sendGETRequestBlob(url, authtoken);
return response;
} catch (error) {
console.error("Error fetching file:", error);
throw error;
}
}
async function deleteFileRequest(fileId, authtoken) {
const url = APIENDPOINT_DELETEFILE + fileId;
const body = { };
try {
const response = await sendPOSTRequest(url, body, authtoken);
return response;
} catch (error) {
console.error("Error resetting password:", error);
throw error;
}
}
async function uploadFileRequest(body, authtoken) {
const url = APIENDPOINT_UPLOADFILE;
try {
const response = await sendPOSTRequestForm(url, body, authtoken);
return response;
} catch (error) {
console.error("Error uploading file:", error);
throw error;
}
}
async function guestLogin() {
const url = APIENDPOINT_GUESTLOGIN;
try {
const response = await sendPOSTRequest(url, {});
return response;
} catch (error) {
console.error("Error guest logging in:", error);
throw error;
}
}
async function getDevicesRequest(authtoken) {
const url = APIENDPOINT_DEVICELIST;
try {
const response = await sendGETRequest(url, authtoken);
return response;
} catch (error) {
console.error("Error requesting device list:", error);
throw error;
}
}
(async function () {
await onPageLoad();
})();