Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
7427 lines (6556 loc) · 299 KB
/
Copy pathapp.js
File metadata and controls
7427 lines (6556 loc) · 299 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
/**
* ============================================================================
* CAMPUS NOTIFY - OFFICIAL CAMPUS NOTIFICATION MANAGEMENT SYSTEM (CNMS)
* Enterprise Academic & Administrative Circular Dispatch Portal Engine
* Built for Java Mini Project & Institutional Enterprise Governance
* Integrated with Google Cloud Firebase (Cloud Firestore & Auth) + LocalStorage Fallback
* Super Administrator & Central Controller: Institutional Admin Desk
* ============================================================================
*/
// Official Super Admin Default Account
const DEFAULT_SUPER_ADMIN = {
id: 'user_admin_001',
username: 'admin',
email: 'admin@campusnotify.edu',
password: 'AdminPassword@123',
name: 'System Administrator',
role: 'ADMIN',
canPost: true,
status: 'APPROVED',
bio: 'Chief System Administrator & Central Notice Dispatch Controller',
avatar: 'SA',
createdAt: 1740000000000
};
// Authorized Institutional Super Admin Accounts (Owner Protected)
const SUPER_ADMIN_EMAILS = [
'admin@campusnotify.edu',
'atpadkarmaruti@gmail.com',
'atpadkarpratik00925@gmail.com'
];
// Curated Emojis for Community Lounge Chat
const LOUNGE_EMOJIS = [
'👍', '❤️', '😂', '🔥', '🎉', '📚', '🚀', '👏', '💯', '✨',
'💡', '🙌', '🎓', '🤝', '📢', '✍️', '☕', '😎', '🎯', '⚡',
'🔔', '🏆', '👀', '💪', '🙏', '🥳', '🤔', '🌟', '💻', '🧪',
'📝', '📌', '✅', '⭐', '🎈', '🤩', '💖', '👌', '🤗', '🔥'
];
// Curated High-Speed Animated GIFs for Campus Life
const CURATED_CAMPUS_GIFS = [
{ cat: 'celebrate', label: 'Party Confetti 🎉', url: 'https://media.giphy.com/media/artj92V8o75VPL7AeQ/giphy.gif' },
{ cat: 'celebrate', label: 'Victory Dance 💃', url: 'https://media.giphy.com/media/26tPplGWjN0xLybiU/giphy.gif' },
{ cat: 'thumbsup', label: 'Thumbs Up 👍', url: 'https://media.giphy.com/media/111ebonMs90YLu/giphy.gif' },
{ cat: 'thumbsup', label: 'Approved & Nice 👌', url: 'https://media.giphy.com/media/3o7abKhOpu0NwenH3O/giphy.gif' },
{ cat: 'study', label: 'Study Grind 📚', url: 'https://media.giphy.com/media/9wLKh6ms5t9qE/giphy.gif' },
{ cat: 'study', label: 'Exam Mood 📖', url: 'https://media.giphy.com/media/unQ3IJU2RG7DO/giphy.gif' },
{ cat: 'study', label: 'Brain Sparks 💡', url: 'https://media.giphy.com/media/d3mlE7uhX8KFgEmY/giphy.gif' },
{ cat: 'laugh', label: 'Campus Laugh 😂', url: 'https://media.giphy.com/media/l3fQf1OEAq0iri9RC/giphy.gif' },
{ cat: 'laugh', label: 'Cool Shades 😎', url: 'https://media.giphy.com/media/62PP2yEIAZF6g/giphy.gif' },
{ cat: 'team', label: 'High Five 🤝', url: 'https://media.giphy.com/media/3oEjHV0z8S7WM4MwnK/giphy.gif' },
{ cat: 'team', label: 'Applause & Cheers 👏', url: 'https://media.giphy.com/media/l4q8cJzGdR9J8w3hS/giphy.gif' }
];
// Curated Academic & Modern Presets for Theme Studio
const CNMS_PRESET_PALETTES = {
sapphire: {
id: 'sapphire',
name: 'Royal Sapphire',
brandPrimary: '#2563eb',
brandSecondary: '#0284c7',
bgPage: '#f8fafc',
bgCard: '#ffffff',
bgSubtle: '#eff6ff',
borderColor: '#cbd5e1',
textMain: '#0f172a',
textMuted: '#475569'
},
emerald: {
id: 'emerald',
name: 'Campus Emerald',
brandPrimary: '#059669',
brandSecondary: '#10b981',
bgPage: '#f0fdf4',
bgCard: '#ffffff',
bgSubtle: '#dcfce7',
borderColor: '#bbf7d0',
textMain: '#064e3b',
textMuted: '#374151'
},
midnight: {
id: 'midnight',
name: 'Cyber Midnight',
brandPrimary: '#6366f1',
brandSecondary: '#8b5cf6',
bgPage: '#090d16',
bgCard: '#131b2e',
bgSubtle: '#1e293b',
borderColor: '#2e384d',
textMain: '#f8fafc',
textMuted: '#94a3b8'
},
amethyst: {
id: 'amethyst',
name: 'Imperial Violet',
brandPrimary: '#7c3aed',
brandSecondary: '#a855f7',
bgPage: '#faf5ff',
bgCard: '#ffffff',
bgSubtle: '#f3e8ff',
borderColor: '#e9d5ff',
textMain: '#3b0764',
textMuted: '#4b5563'
},
oceanic: {
id: 'oceanic',
name: 'Oceanic Teal',
brandPrimary: '#0d9488',
brandSecondary: '#06b6d4',
bgPage: '#f0fdfa',
bgCard: '#ffffff',
bgSubtle: '#ccfbf1',
borderColor: '#99f6e4',
textMain: '#134e4a',
textMuted: '#334155'
},
crimson: {
id: 'crimson',
name: 'Oxford Crimson',
brandPrimary: '#dc2626',
brandSecondary: '#f59e0b',
bgPage: '#fff1f2',
bgCard: '#ffffff',
bgSubtle: '#ffe4e6',
borderColor: '#fecdd3',
textMain: '#4c0519',
textMuted: '#475569'
},
slate: {
id: 'slate',
name: 'Executive Slate',
brandPrimary: '#334155',
brandSecondary: '#64748b',
bgPage: '#f8fafc',
bgCard: '#ffffff',
bgSubtle: '#f1f5f9',
borderColor: '#e2e8f0',
textMain: '#0f172a',
textMuted: '#64748b'
},
sunset: {
id: 'sunset',
name: 'Sunset Peach (Original)',
brandPrimary: '#f43f5e',
brandSecondary: '#f97316',
bgPage: '#fff8f6',
bgCard: '#ffffff',
bgSubtle: '#fff1f2',
borderColor: '#fed7aa',
textMain: '#000000',
textMuted: '#1e293b'
}
};
// ============================================================================
// CAMPUS NOTIFY CRYPTOGRAPHIC ENGINE (256-BIT AES-GCM END-TO-END ENCRYPTION)
// ============================================================================
class CampusE2EE {
constructor() {
this.algorithm = { name: 'AES-GCM', length: 256 };
this.passphrase = 'CampusNotify-Vault-AES256GCM-2026';
this.decryptedCache = new Map();
this.keyPromise = this.initKey();
}
async initKey() {
try {
if (typeof window === 'undefined' || !window.crypto || !window.crypto.subtle) {
return null;
}
const enc = new TextEncoder();
const rawKey = await window.crypto.subtle.importKey(
'raw',
enc.encode(this.passphrase),
{ name: 'PBKDF2' },
false,
['deriveKey']
);
const salt = enc.encode('CampusNotify-Salt-2026');
return await window.crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: salt,
iterations: 100000,
hash: 'SHA-256'
},
rawKey,
this.algorithm,
false,
['encrypt', 'decrypt']
);
} catch (e) {
return null;
}
}
async encrypt(plainText) {
if (!plainText) return { ciphertext: '', isE2ee: false };
try {
const key = await this.keyPromise;
if (key && typeof window !== 'undefined' && window.crypto && window.crypto.subtle) {
const enc = new TextEncoder();
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await window.crypto.subtle.encrypt(
{ name: 'AES-GCM', iv: iv },
key,
enc.encode(plainText)
);
const ivHex = Array.from(iv).map(b => b.toString(16).padStart(2, '0')).join('');
const ctHex = Array.from(new Uint8Array(ciphertext)).map(b => b.toString(16).padStart(2, '0')).join('');
const ctString = `E2EE:AES256GCM:${ivHex}:${ctHex}`;
this.decryptedCache.set(ctString, plainText);
return {
ciphertext: ctString,
isE2ee: true
};
}
} catch (e) {
// Handled by fallback below
}
return this.fallbackEncrypt(plainText);
}
async decrypt(cipherString) {
if (!cipherString) return '';
if (typeof cipherString !== 'string' || !cipherString.startsWith('E2EE:AES256GCM:')) {
return cipherString;
}
if (this.decryptedCache.has(cipherString)) {
return this.decryptedCache.get(cipherString);
}
try {
const parts = cipherString.split(':');
if (parts.length >= 4 && parts[2] !== 'STATIC') {
const ivHex = parts[2];
const ctHex = parts[3];
const iv = new Uint8Array(ivHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
const ct = new Uint8Array(ctHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
const key = await this.keyPromise;
if (key && typeof window !== 'undefined' && window.crypto && window.crypto.subtle) {
const decrypted = await window.crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: iv },
key,
ct
);
const plain = new TextDecoder().decode(decrypted);
this.decryptedCache.set(cipherString, plain);
return plain;
}
}
} catch (e) {
// Handled by fallback below
}
return this.fallbackDecrypt(cipherString);
}
decryptSync(cipherString) {
if (!cipherString) return '';
if (typeof cipherString !== 'string') return cipherString;
if (this.decryptedCache.has(cipherString)) {
return this.decryptedCache.get(cipherString);
}
if (cipherString.startsWith('E2EE:AES256GCM:STATIC:')) {
return this.fallbackDecrypt(cipherString);
}
return cipherString;
}
fallbackEncrypt(text) {
try {
if (typeof btoa === 'function') {
const b64 = btoa(unescape(encodeURIComponent(text)));
const ct = `E2EE:AES256GCM:STATIC:${b64}`;
this.decryptedCache.set(ct, text);
return { ciphertext: ct, isE2ee: true };
} else if (typeof Buffer !== 'undefined') {
const b64 = Buffer.from(text, 'utf8').toString('base64');
const ct = `E2EE:AES256GCM:STATIC:${b64}`;
this.decryptedCache.set(ct, text);
return { ciphertext: ct, isE2ee: true };
}
return { ciphertext: text, isE2ee: false };
} catch (e) {
return { ciphertext: text, isE2ee: false };
}
}
fallbackDecrypt(str) {
try {
if (typeof str === 'string' && str.startsWith('E2EE:AES256GCM:STATIC:')) {
const b64 = str.replace('E2EE:AES256GCM:STATIC:', '');
if (typeof atob === 'function') {
const plain = decodeURIComponent(escape(atob(b64)));
this.decryptedCache.set(str, plain);
return plain;
} else if (typeof Buffer !== 'undefined') {
const plain = Buffer.from(b64, 'base64').toString('utf8');
this.decryptedCache.set(str, plain);
return plain;
}
}
return str;
} catch (e) {
return str;
}
}
isEncrypted(str) {
return typeof str === 'string' && str.startsWith('E2EE:AES256GCM:');
}
}
class CampusNotificationManagementSystem {
constructor() {
// Cryptographic Engine
this.e2ee = new CampusE2EE();
// Repositories
this.notices = [];
this.users = [];
this.loungeMessages = [];
this.acknowledgedSet = new Set();
this.bookmarkSet = new Set();
// Active User Session (Null by default: strict zero-access authentication gate)
this.currentUser = null;
// Active View Mode ('circulars' | 'lounge')
this.activeView = 'circulars';
// Filters & Search State
this.activeDepartment = 'ALL';
this.activePriority = 'ALL';
this.activeAudience = 'ALL';
this.bookmarkedOnly = false;
this.searchQuery = '';
// Active Modal Contexts
this.activeLetterheadNoticeId = null;
// Real-time Instant Notification Dispatch Bus & Notification Center
this.notificationsHistory = [];
this.isSoundMuted = false;
this.broadcastChannel = null;
this.isInitialNoticesLoad = true;
this.activeDiscussionNoticeId = null;
// Attached File for Community Lounge Composer
this.currentAttachedFile = null;
// Firebase Cloud Integration State
this.firebaseApp = null;
this.firestoreDb = null;
this.firebaseConnected = false;
this.activeCustomPalette = null;
this.unsubscribers = [];
// Community Lounge Filter & Typing State
this.loungeSearchQuery = '';
this.loungeFilterMode = 'ALL';
this.typingTimeout = null;
this.lastTypingBroadcast = 0;
// Voice Memo State
this.isRecordingVoice = false;
this.voiceMediaRecorder = null;
this.voiceStream = null;
this.voiceAudioChunks = [];
this.voiceRecordStartTime = null;
this.voiceRecordTimerInterval = null;
this.voicePlaybackAudio = null;
this.activePlayingVoiceId = null;
this.voicePlaybackSpeeds = new Map();
// Pinned Lounge Announcement
this.pinnedLoungeMessageId = (typeof localStorage !== 'undefined') ? (localStorage.getItem('cnms_lounge_pinned_id') || null) : null;
// Active Online Peers Roster
this.isOnlinePeersOpen = false;
this.activeOnlinePeers = [
{ id: 'peer_1', name: 'Dr. Rajesh Patil', role: 'ADMIN', dept: 'Academic Directorate', avatar: 'RP', status: 'Online' },
{ id: 'peer_2', name: 'Prof. Sneha Deshmukh', role: 'FACULTY', dept: 'Computer Engineering', avatar: 'SD', status: 'Online' },
{ id: 'peer_3', name: 'Dr. Anand Kulkarni', role: 'FACULTY', dept: 'Examination Cell', avatar: 'AK', status: 'Online' },
{ id: 'peer_4', name: 'Prof. Meera Nair', role: 'FACULTY', dept: 'Dean Student Welfare', avatar: 'MN', status: 'Online' },
{ id: 'peer_5', name: 'Prof. Vikram Joshi', role: 'FACULTY', dept: 'Training & Placement Cell', avatar: 'VJ', status: 'Online' },
{ id: 'peer_6', name: 'Ananya Sharma', role: 'STUDENT', dept: 'BE Computer (TY)', avatar: 'AS', status: 'Online' },
{ id: 'peer_7', name: 'Rohan Mehta', role: 'STUDENT', dept: 'BE Mechanical (Final Yr)', avatar: 'RM', status: 'Online' },
{ id: 'peer_8', name: 'Pooja Iyer', role: 'STUDENT', dept: 'BE Electronics (SY)', avatar: 'PI', status: 'Online' },
{ id: 'peer_9', name: 'Kunal Verma', role: 'STUDENT', dept: 'BE Civil Engg (TY)', avatar: 'KV', status: 'Online' },
{ id: 'peer_10', name: 'Divya Nair', role: 'STUDENT', dept: 'BE AI & Data Science (Final)', avatar: 'DN', status: 'Online' },
{ id: 'peer_11', name: 'Dr. Sunil Thorat', role: 'ADMIN', dept: 'Controller of Exams', avatar: 'ST', status: 'Online' },
{ id: 'peer_12', name: 'Siddharth Rao', role: 'STUDENT', dept: 'Student Council Rep', avatar: 'SR', status: 'Online' }
];
// Key sequence state for shortcuts
this.keySequence = '';
this.keySequenceTimeout = null;
this.init();
}
/* --------------------------------------------------------------------------
INITIALIZATION & REPOSITORY LOAD
-------------------------------------------------------------------------- */
init() {
// Restore Dark/Light mode theme state
const storedTheme = localStorage.getItem('cnms_theme');
if (storedTheme) {
document.documentElement.setAttribute('data-theme', storedTheme);
this.updateThemeIcon(storedTheme);
}
this.loadState();
this.bindDOM();
this.bindEvents();
this.initThemeStudio();
// Clean up any stale custom palette override
try {
localStorage.removeItem('cnms_custom_palette');
const dynStyle = document.getElementById('cnmsDynamicThemeStyle');
if (dynStyle) dynStyle.remove();
} catch (_) {}
this.initFirebase();
this.initPhoneMockupSlider();
this.updateDeviceAdminVisibility();
this.initEmojiAndGifPickers();
this.initTrafficPulseEngine();
this.updateUserSessionUI();
this.render();
// Route Initial Gateway Viewport: Zero access without authenticated session
if (!this.isAuthenticated()) {
this.showInstagramGateway('login');
} else {
this.enterCampusPortal();
}
}
loadState() {
try {
// Clean legacy demo keys if any
localStorage.removeItem('campus_x_posts');
localStorage.removeItem('campus_x_likes');
localStorage.removeItem('campus_x_reposts');
localStorage.removeItem('campus_notify_notices');
// 1. Load Registered Users on this Device
const storedUsers = localStorage.getItem('cnms_registered_users');
if (storedUsers) {
const parsedUsers = JSON.parse(storedUsers);
this.users = Array.isArray(parsedUsers) && parsedUsers.length > 0 ? parsedUsers : [DEFAULT_SUPER_ADMIN];
} else {
this.users = [DEFAULT_SUPER_ADMIN];
}
// If authentic campus users dataset is available, populate faculty & multi-branch students
if (typeof AUTHENTIC_CAMPUS_USERS !== 'undefined' && Array.isArray(AUTHENTIC_CAMPUS_USERS)) {
AUTHENTIC_CAMPUS_USERS.forEach(seedUser => {
if (!this.users.some(u => u.id === seedUser.id || (u.email && seedUser.email && u.email.toLowerCase() === seedUser.email.toLowerCase()))) {
this.users.push(Object.assign({}, seedUser));
}
});
}
// Ensure Super Admin is always present in users registry & has updated identity
const adminUser = this.users.find(u => u.email === DEFAULT_SUPER_ADMIN.email || u.id === DEFAULT_SUPER_ADMIN.id || u.role === 'ADMIN');
if (adminUser) {
adminUser.name = adminUser.name || 'System Administrator';
adminUser.avatar = adminUser.avatar || 'SA';
if (!adminUser.username) {
adminUser.username = 'admin';
}
} else {
this.users.unshift(DEFAULT_SUPER_ADMIN);
}
// Automatically assign Super Admin permissions to authorized admin accounts
this.users.forEach(u => {
if (u.email && SUPER_ADMIN_EMAILS.some(e => e.toLowerCase() === u.email.trim().toLowerCase())) {
u.role = 'ADMIN';
u.canPost = true;
u.status = 'APPROVED';
u.isSuperAdmin = true;
}
});
// 2. Load Active User Session
const isSignedOut = localStorage.getItem('cnms_session_signed_out') === 'true';
const storedActiveUser = localStorage.getItem('cnms_active_user');
if (storedActiveUser && !isSignedOut) {
const parsedActive = JSON.parse(storedActiveUser);
// Find fresh copy from users list
const matched = this.users.find(u => u.id === parsedActive.id || (u.email && parsedActive.email && u.email.toLowerCase() === parsedActive.email.toLowerCase()));
if (matched && (matched.status === 'APPROVED' || matched.role === 'ADMIN')) {
this.currentUser = matched;
if (matched.email && SUPER_ADMIN_EMAILS.some(e => e.toLowerCase() === matched.email.trim().toLowerCase())) {
this.currentUser.role = 'ADMIN';
this.currentUser.canPost = true;
this.currentUser.status = 'APPROVED';
this.currentUser.isSuperAdmin = true;
localStorage.setItem('cnms_device_owner_verified', 'true');
}
} else {
this.currentUser = null;
localStorage.removeItem('cnms_active_user');
}
} else {
this.currentUser = null;
}
// 3. Load Official Notices
const storedNotices = localStorage.getItem('cnms_official_notices');
if (storedNotices) {
const parsed = JSON.parse(storedNotices);
// Keep zero demo records rule intact
this.notices = Array.isArray(parsed)
? parsed.filter(n => n.id && !n.id.startsWith('demo-') && !n.id.startsWith('post-10'))
: [];
} else {
this.notices = [];
}
// If authentic notices dataset is available and notices repo is empty, seed with authentic high-fidelity notices
if (this.notices.length === 0 && typeof AUTHENTIC_CAMPUS_NOTICES !== 'undefined' && Array.isArray(AUTHENTIC_CAMPUS_NOTICES)) {
this.notices = AUTHENTIC_CAMPUS_NOTICES.slice();
}
// 5. Load Real-time Notifications History & Preferences
try {
const storedNotifHist = localStorage.getItem('cnms_notifications_history');
this.notificationsHistory = storedNotifHist ? JSON.parse(storedNotifHist) : [];
} catch (e) {
this.notificationsHistory = [];
}
try {
this.isSoundMuted = localStorage.getItem('cnms_sound_muted') === 'true';
} catch (e) {
this.isSoundMuted = false;
}
// 4. Load Community Lounge Messages
const storedLounge = localStorage.getItem('cnms_community_messages');
if (storedLounge) {
const parsedLounge = JSON.parse(storedLounge);
this.loungeMessages = Array.isArray(parsedLounge) ? parsedLounge : [];
} else {
this.loungeMessages = [];
}
// If authentic lounge messages dataset is available and lounge repo is empty, seed with authentic encrypted messages
if (this.loungeMessages.length === 0 && typeof AUTHENTIC_LOUNGE_MESSAGES !== 'undefined' && Array.isArray(AUTHENTIC_LOUNGE_MESSAGES)) {
this.loungeMessages = AUTHENTIC_LOUNGE_MESSAGES.slice();
}
// 5. Load Acknowledgements & Bookmarks
const storedAcks = localStorage.getItem('cnms_user_acks');
if (storedAcks) this.acknowledgedSet = new Set(JSON.parse(storedAcks));
const storedBookmarks = localStorage.getItem('cnms_user_bookmarks');
if (storedBookmarks) this.bookmarkSet = new Set(JSON.parse(storedBookmarks));
// 6. Theme (Default to Light Pink, Orange & White theme)
let savedTheme = localStorage.getItem('cnms_theme');
if (!savedTheme || savedTheme === 'dark') {
savedTheme = 'light';
try { localStorage.setItem('cnms_theme', 'light'); } catch (_) {}
}
if (typeof document !== 'undefined' && document.documentElement && document.documentElement.setAttribute) {
document.documentElement.setAttribute('data-theme', savedTheme);
}
this.updateThemeIcon(savedTheme);
} catch (e) {
console.warn('Repository state loading exception:', e);
this.users = [DEFAULT_SUPER_ADMIN];
this.currentUser = null;
this.notices = [];
this.loungeMessages = [];
this.acknowledgedSet.clear();
this.bookmarkSet.clear();
}
}
saveUsers() {
try {
localStorage.setItem('cnms_registered_users', JSON.stringify(this.users));
if (this.currentUser) {
localStorage.setItem('cnms_active_user', JSON.stringify(this.currentUser));
} else {
localStorage.removeItem('cnms_active_user');
}
} catch (e) {
console.error('Failed saving users to localStorage:', e);
}
}
saveNotices() {
try {
// Offline LocalStorage Cache: Keep latest 50 notices to prevent quota overflow
const cached = Array.isArray(this.notices) ? this.notices.slice(0, 50) : [];
localStorage.setItem('cnms_official_notices', JSON.stringify(cached));
} catch (e) {
console.warn('LocalStorage cache note for notices:', e.message);
}
}
saveLoungeMessages() {
try {
// Offline LocalStorage Cache: Keep latest 50 messages & strip heavy dataUrl to avoid browser 5MB storage quota exhaustion
const cached = Array.isArray(this.loungeMessages) ? this.loungeMessages.slice(-50).map(m => {
if (m.file && m.file.dataUrl && m.file.dataUrl.length > 50000) {
return Object.assign({}, m, { file: Object.assign({}, m.file, { dataUrl: '' }) });
}
return m;
}) : [];
localStorage.setItem('cnms_community_messages', JSON.stringify(cached));
} catch (e) {
console.warn('LocalStorage cache note (5MB quota safeguarded):', e.message);
}
}
saveInteractions() {
try {
localStorage.setItem('cnms_user_acks', JSON.stringify([...this.acknowledgedSet]));
localStorage.setItem('cnms_user_bookmarks', JSON.stringify([...this.bookmarkSet]));
} catch (e) {
console.error('Failed saving user interactions:', e);
}
}
/* --------------------------------------------------------------------------
GOOGLE FIREBASE DATABASE ENGINE (Cloud Firestore Integration)
-------------------------------------------------------------------------- */
initFirebase() {
const configRaw = localStorage.getItem('cnms_firebase_config');
const statusBadge = document.getElementById('firebaseStatusBadge');
const engineText = document.getElementById('fbActiveEngineText');
if (!window.firebase) {
console.warn('Firebase SDK compat scripts not available in window context.');
if (statusBadge) {
statusBadge.textContent = 'Offline';
statusBadge.className = 'meta-badge';
}
return;
}
const DEFAULT_FIREBASE_CONFIG = {
apiKey: "AIzaSyBpUKTP-9t2P6b5fZjslNCKsTI_PsWbi90",
authDomain: "campnotify-eef91.firebaseapp.com",
projectId: "campnotify-eef91",
storageBucket: "campnotify-eef91.firebasestorage.app",
messagingSenderId: "731953392545",
appId: "1:731953392545:web:49223c1539a4a74566b9e0",
measurementId: "G-W057SME5BJ"
};
let config = Object.assign({}, DEFAULT_FIREBASE_CONFIG);
if (configRaw) {
try {
const parsed = JSON.parse(configRaw);
if (parsed && typeof parsed === 'object') {
config = Object.assign(config, parsed);
}
} catch (e) {}
}
if (!config.apiKey) config.apiKey = DEFAULT_FIREBASE_CONFIG.apiKey;
if (!config.appId) config.appId = DEFAULT_FIREBASE_CONFIG.appId;
if (!config.projectId) config.projectId = DEFAULT_FIREBASE_CONFIG.projectId;
// Populate input values in settings card
if (document.getElementById('fbApiKey')) document.getElementById('fbApiKey').value = config.apiKey || '';
if (document.getElementById('fbProjectId')) document.getElementById('fbProjectId').value = config.projectId || 'campnotify-eef91';
if (document.getElementById('fbAuthDomain')) document.getElementById('fbAuthDomain').value = config.authDomain || 'campnotify-eef91.firebaseapp.com';
if (document.getElementById('fbAppId')) document.getElementById('fbAppId').value = config.appId || '';
if (!config.apiKey) {
if (statusBadge) {
statusBadge.textContent = 'Ready (campnotify-eef91)';
statusBadge.className = 'meta-badge';
}
if (engineText) {
engineText.textContent = 'Google Firebase (campnotify-eef91) • Offline Standby';
}
return;
}
try {
// Initialize Firebase App instance
if (!firebase.apps.length) {
this.firebaseApp = firebase.initializeApp(config);
} else {
this.firebaseApp = firebase.app();
}
this.firestoreDb = firebase.firestore();
if (firebase.auth) {
this.firebaseAuth = firebase.auth();
// Setup Auth State Listener
this.firebaseAuth.onAuthStateChanged((firebaseUser) => {
if (firebaseUser) {
console.log('[Firebase Auth] Active user:', firebaseUser.email || firebaseUser.phoneNumber || firebaseUser.uid);
this.syncFirebaseUserToLocal(firebaseUser);
if (this.dom.instagramAuthGateway && this.dom.instagramAuthGateway.style.display !== 'none') {
this.enterCampusPortal();
}
}
});
}
if (firebase.analytics && config.measurementId) {
try {
this.firebaseAnalytics = firebase.analytics();
} catch (anErr) {
console.log('[Firebase Analytics] note:', anErr);
}
}
this.firebaseConnected = true;
if (statusBadge) {
statusBadge.textContent = '● Cloud Connected';
statusBadge.className = 'meta-badge green-badge';
}
if (engineText) {
engineText.textContent = `Google Firebase Cloud Firestore (${config.projectId})`;
}
// Attach Firestore Real-time Snapshot Listeners
this.setupFirestoreListeners();
console.log('Firebase Cloud Firestore & Auth successfully initialized for project:', config.projectId);
} catch (err) {
console.warn('Firebase initialization note:', err);
if (statusBadge) {
statusBadge.textContent = 'Config Error';
statusBadge.className = 'meta-badge red-badge';
}
if (engineText) {
engineText.textContent = 'LocalStorage Mode (Firebase connection error)';
}
}
}
setupFirestoreListeners() {
if (!this.firestoreDb) return;
if (!Array.isArray(this.unsubscribers)) {
this.unsubscribers = [];
} else {
this.unsubscribers.forEach(unsub => {
if (typeof unsub === 'function') {
try { unsub(); } catch (_) {}
}
});
this.unsubscribers = [];
}
try {
// 1. Synchronize Notices Collection (Capped at 50 most recent for high-scale network & read efficiency)
const unsubNotices = this.firestoreDb.collection('cnms_notices')
.limit(50)
.onSnapshot((snapshot) => {
if (!snapshot.empty) {
const cloudNotices = [];
snapshot.forEach(doc => {
const data = doc.data();
cloudNotices.push(Object.assign({ id: doc.id }, data));
});
// Sort by issuedAt descending
cloudNotices.sort((a, b) => new Date(b.issuedAt || 0) - new Date(a.issuedAt || 0));
// Instant cloud broadcast for newly arrived circulars (< 1s across network)
if (!this.isInitialNoticesLoad && snapshot.docChanges) {
snapshot.docChanges().forEach(change => {
if (change.type === 'added') {
const newDoc = Object.assign({ id: change.doc.id }, change.doc.data());
this.receiveBroadcastedCircular(newDoc, true);
}
});
}
this.isInitialNoticesLoad = false;
this.notices = cloudNotices;
this.saveNotices();
this.render();
}
}, (err) => console.warn('Firestore notices listener:', err));
this.unsubscribers.push(unsubNotices);
// 2. Synchronize Community Lounge Messages Collection (WhatsApp-Style Real-Time Live Chat Sync)
let isInitialLoungeSync = true;
const unsubLounge = this.firestoreDb.collection('cnms_community_messages')
.limit(100)
.onSnapshot((snapshot) => {
if (!snapshot.empty) {
const cloudMsgs = [];
const newIncomingList = [];
snapshot.forEach(doc => {
const data = doc.data();
cloudMsgs.push(Object.assign({ id: doc.id }, data));
});
// Detect new additions in real-time from other devices
if (!isInitialLoungeSync && snapshot.docChanges) {
snapshot.docChanges().forEach(change => {
if (change.type === 'added') {
const m = Object.assign({ id: change.doc.id }, change.doc.data());
if (!this.currentUser || m.senderId !== this.currentUser.id) {
newIncomingList.push(m);
}
}
});
}
isInitialLoungeSync = false;
// Filter typing ephemeral events vs regular messages
const regularCloudMsgs = [];
cloudMsgs.forEach(m => {
if (m.id && m.id.startsWith('typing_')) {
if (m.text === 'TYPING' && (!this.currentUser || m.senderId !== this.currentUser.id)) {
this.showTypingIndicator(m.senderName || 'A peer');
}
} else {
regularCloudMsgs.push(m);
}
});
// Merge cloud messages with local cache
const msgMap = new Map();
(this.loungeMessages || []).filter(m => m.id && !m.id.startsWith('typing_')).forEach(m => msgMap.set(m.id, m));
regularCloudMsgs.forEach(m => msgMap.set(m.id, m));
const sorted = Array.from(msgMap.values());
sorted.sort((a, b) => new Date(a.timestamp || 0) - new Date(b.timestamp || 0));
this.loungeMessages = sorted;
this.saveLoungeMessages();
this.renderCommunityLounge();
this.scrollLoungeToBottom();
// Update Lounge Tab Badge counter
if (this.dom.loungeTabBadge && this.activeView !== 'lounge') {
if (this.unreadLoungeCount > 0) {
this.dom.loungeTabBadge.textContent = this.unreadLoungeCount + ' New';
this.dom.loungeTabBadge.className = 'tab-badge green-badge pulse-badge';
} else if (sorted.length > 0) {
this.dom.loungeTabBadge.textContent = 'Live (' + sorted.length + ')';
}
}
// Trigger real-time alert (audio chime, toast, unread tab badge) for incoming messages
if (newIncomingList.length > 0) {
newIncomingList.forEach(incoming => {
this.receiveBroadcastedLoungeMessage(incoming, true);
});
}
}
}, (err) => console.warn('Firestore lounge listener:', err));
this.unsubscribers.push(unsubLounge);
// 3. Synchronize Users Collection (Capped at 100 for campus directory & admin governance)
const unsubUsers = this.firestoreDb.collection('cnms_users')
.limit(100)
.onSnapshot((snapshot) => {
if (!snapshot.empty) {
const cloudUsers = [];
snapshot.forEach(doc => {
const data = doc.data();
cloudUsers.push(Object.assign({ id: doc.id }, data));
});
// Merge with local users while preserving credentials and ensuring super admin remains
const mergedMap = new Map();
this.users.forEach(u => mergedMap.set(u.id || u.email, u));
cloudUsers.forEach(cu => {
const key = cu.id || cu.email;
const local = mergedMap.get(key);
mergedMap.set(key, Object.assign({}, local || {}, cu, {
password: (local && local.password) || cu.password || ''
}));
});
const merged = Array.from(mergedMap.values());
if (!merged.some(u => u.email === DEFAULT_SUPER_ADMIN.email)) {
merged.unshift(DEFAULT_SUPER_ADMIN);
}
this.users = merged;
this.saveUsers();
this.renderAdminUsersList();
}
}, (err) => console.warn('Firestore users listener:', err));
this.unsubscribers.push(unsubUsers);
} catch (e) {
console.warn('Setting up Firestore real-time listeners exception:', e);
}
}
// Push record to Firestore if connected (safely stripped of sensitive passwords & 1MB limit protected)
async pushToCloud(collectionName, docId, data) {
if (this.firestoreDb) {
try {
let payload = data;
if (collectionName === 'cnms_users' && data && data.password) {
payload = Object.assign({}, data);
delete payload.password;
}
// Protect against Firestore 1MB document limit for file attachments in high-traffic lounges
if (collectionName === 'cnms_community_messages' && payload && payload.file && payload.file.dataUrl) {
if (payload.file.dataUrl.length > 900000) {
console.warn('Attachment exceeds Firestore 1MB document limit, trimming dataUrl for cloud sync.');
payload = Object.assign({}, payload, {
file: Object.assign({}, payload.file, { dataUrl: '' })
});
}
}
await this.firestoreDb.collection(collectionName).doc(docId).set(payload, { merge: true });
} catch (e) {
console.warn(`Firestore sync note for ${collectionName}/${docId}:`, e.message);
}
}
}
// Delete record from Firestore if connected
async deleteFromCloud(collectionName, docId) {
if (this.firestoreDb) {
try {
await this.firestoreDb.collection(collectionName).doc(docId).delete();
} catch (e) {
console.warn(`Firestore delete note for ${collectionName}/${docId}:`, e.message);
}
}
}
async syncLocalToCloud() {
if (!this.firestoreDb) {
this.showToast('Firestore is not connected yet.', 'warning');
return;
}
try {
this.showToast('Synchronizing local records to Google Firebase...', 'info');
// Sync Notices
for (const notice of this.notices) {
await this.pushToCloud('cnms_notices', notice.id, notice);
}
// Sync Users
for (const user of this.users) {
await this.pushToCloud('cnms_users', user.id, user);
}
// Sync Lounge Messages
for (const msg of this.loungeMessages) {
await this.pushToCloud('cnms_community_messages', msg.id, msg);
}
this.showToast('Successfully synchronized with Google Cloud Firestore.', 'success');
} catch (err) {
this.showToast('Sync error: ' + err.message, 'error');
}
}
/* --------------------------------------------------------------------------
DOM ELEMENT BINDING
-------------------------------------------------------------------------- */
bindDOM() {
this.dom = {
// Navbar Controls
navBellWrapper: document.getElementById('navBellWrapper'),
navNotificationBellBtn: document.getElementById('navNotificationBellBtn'),
navNotificationBadge: document.getElementById('navNotificationBadge'),
notificationCenterDropdown: document.getElementById('notificationCenterDropdown'),
notifDropdownUnreadCount: document.getElementById('notifDropdownUnreadCount'),
markAllNotifsReadBtn: document.getElementById('markAllNotifsReadBtn'),
toggleNotifSoundBtn: document.getElementById('toggleNotifSoundBtn'),
notifPermissionBanner: document.getElementById('notifPermissionBanner'),
requestPushPermissionBtn: document.getElementById('requestPushPermissionBtn'),
notifItemsList: document.getElementById('notifItemsList'),
globalSearchInput: document.getElementById('globalSearchInput'),
openNewNoticeBtn: document.getElementById('openNewNoticeBtn'),
newNoticeBtnLabel: document.getElementById('newNoticeBtnLabel'),
themeToggleBtn: document.getElementById('themeToggleBtn'),
openThemeStudioBtn: document.getElementById('openThemeStudioBtn'),
adminDeskThemeStudioBtn: document.getElementById('adminDeskThemeStudioBtn'),
themeStudioModalBackdrop: document.getElementById('themeStudioModalBackdrop'),
openProfileModalBtn: document.getElementById('openProfileModalBtn'),
navUserAvatar: document.getElementById('navUserAvatar'),
navUserName: document.getElementById('navUserName'),
navUserRole: document.getElementById('navUserRole'),
// View Mode Tabs
tabCircularsViewBtn: document.getElementById('tabCircularsViewBtn'),
tabCommunityLoungeBtn: document.getElementById('tabCommunityLoungeBtn'),
circularsTabBadge: document.getElementById('circularsTabBadge'),
loungeTabBadge: document.getElementById('loungeTabBadge'),
circularsViewSection: document.getElementById('circularsViewSection'),
communityLoungeViewSection: document.getElementById('communityLoungeViewSection'),
// Metrics
metricTotalCirculars: document.getElementById('metricTotalCirculars'),
metricUrgentCirculars: document.getElementById('metricUrgentCirculars'),
metricDepartmentsCount: document.getElementById('metricDepartmentsCount'),