-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2822 lines (2387 loc) · 102 KB
/
Copy pathapp.js
File metadata and controls
2822 lines (2387 loc) · 102 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
// Firebase configuration loaded from external file
// Initialize Firebase with connection debugging
let database;
try {
firebase.initializeApp(firebaseConfig);
database = firebase.database();
// Enable offline persistence and debugging
database.goOnline();
// Test connection with authorization validation
database.ref('.info/connected').on('value', (snapshot) => {
if (snapshot.val() === true) {
console.log('✅ Firebase connected');
} else {
console.log('❌ Firebase disconnected');
}
});
} catch (error) {
console.error('Firebase initialization failed:', error);
// Clean up on initialization failure
if (database) {
try {
database.goOffline();
} catch (cleanupError) {
console.error('Cleanup failed:', cleanupError);
}
}
console.error('Connection failed. Please refresh the page.');
// Use secure notification instead of alert
if (typeof showNotification === 'function') {
showNotification('Connection failed. Please refresh the page.', 'error');
}
}
class PhoneCall {
constructor() {
try {
this.localStream = null;
this.peerConnections = new Map();
this.remoteStreams = new Map();
this.channel = null;
this.userName = null;
this.deviceHash = this.generateDeviceHash();
this.isMuted = false;
this.connectedPeers = new Set();
this.maxCallers = 2;
this.currentCallers = 0;
this.isCallActive = false;
this.isSpeakerMode = true;
this.othersInCall = false;
this.audioContext = null;
this.activeNotifications = new Set();
this.dataChannels = new Map();
this.encryptionKey = null;
this.initializeElements();
this.setupEventListeners();
this.checkUrlParams();
this.setupPageUnloadHandler();
} catch (error) {
console.error('PhoneCall initialization failed:', error);
console.log('Available elements:', Object.keys(this.elements || {}));
}
}
initializeElements() {
this.elements = {
callSetup: document.getElementById('callSetup'),
callInterface: document.getElementById('callInterface'),
channelInput: document.getElementById('channelInput'),
nameInput: document.getElementById('nameInput'),
maxCallers: document.getElementById('maxCallers'),
offlineModeToggle: document.getElementById('offlineModeToggle'),
quickCallBtn: document.getElementById('quickCallBtn'),
joinBtn: document.getElementById('joinBtn'),
settingsToggle: document.getElementById('settingsToggle'),
settingsPanel: document.getElementById('settingsPanel'),
currentChannel: document.getElementById('currentChannel'),
callStatus: document.getElementById('callStatus'),
statusDot: document.getElementById('statusDot'),
callerCount: document.getElementById('callerCount'),
maxCallerCount: document.getElementById('maxCallerCount'),
participantCountMini: document.getElementById('participantCountMini'),
shareSection: document.getElementById('shareSection'),
shareUrl: document.getElementById('shareUrl'),
copyBtn: document.getElementById('copyBtn'),
advancedTab: document.getElementById('advancedTab'),
advancedContent: document.getElementById('advancedContent'),
p2pShareUrl: document.getElementById('p2pShareUrl'),
copyP2PBtn: document.getElementById('copyP2PBtn'),
myConnectionData: document.getElementById('myConnectionData'),
copyMyDataBtn: document.getElementById('copyMyDataBtn'),
friendConnectionData: document.getElementById('friendConnectionData'),
applyFriendDataBtn: document.getElementById('applyFriendDataBtn'),
qrCodeContainer: document.getElementById('qrCodeContainer'),
startCallBtn: document.getElementById('startCallBtn'),
speakerBtn: document.getElementById('speakerBtn'),
endCallBtn: document.getElementById('endCallBtn'),
participantsList: document.getElementById('participantsList'),
participantsToggle: document.getElementById('participantsToggle'),
helpToggle: document.getElementById('helpToggle'),
helpContent: document.getElementById('helpContent'),
statusDot: document.getElementById('statusDot'),
messagesList: document.getElementById('messagesList'),
messageInput: document.getElementById('messageInput'),
sendMessageBtn: document.getElementById('sendMessageBtn'),
chatHistory: document.getElementById('chatHistory'),
historyToggle: document.getElementById('historyToggle'),
historyList: document.getElementById('historyList'),
roomTitle: document.getElementById('roomTitle'),
settingsPanel: document.getElementById('settingsPanel'),
settingsToggle: document.getElementById('settingsToggle')
};
}
setupEventListeners() {
// Core required elements
if (this.elements.quickCallBtn) this.elements.quickCallBtn.addEventListener('click', () => this.quickCall());
if (this.elements.joinBtn) this.elements.joinBtn.addEventListener('click', () => this.joinChannel());
// Optional elements
if (this.elements.settingsToggle) this.elements.settingsToggle.addEventListener('click', () => this.toggleSettings());
if (this.elements.copyBtn) this.elements.copyBtn.addEventListener('click', () => this.copyShareUrl());
if (this.elements.advancedTab) this.elements.advancedTab.addEventListener('click', () => this.toggleAdvanced());
if (this.elements.copyP2PBtn) this.elements.copyP2PBtn.addEventListener('click', () => this.copyP2PUrl());
if (this.elements.startCallBtn) this.elements.startCallBtn.addEventListener('click', () => this.startCall());
if (this.elements.speakerBtn) this.elements.speakerBtn.addEventListener('click', () => this.toggleSpeaker());
if (this.elements.endCallBtn) this.elements.endCallBtn.addEventListener('click', () => this.endCall());
if (this.elements.participantsToggle) this.elements.participantsToggle.addEventListener('click', () => this.toggleParticipants());
if (this.elements.helpToggle) this.elements.helpToggle.addEventListener('click', () => this.toggleHelp());
if (this.elements.sendMessageBtn) this.elements.sendMessageBtn.addEventListener('click', () => this.sendMessage());
if (this.elements.historyToggle) this.elements.historyToggle.addEventListener('click', () => this.toggleHistory());
if (this.elements.roomTitle) this.elements.roomTitle.addEventListener('click', () => this.renameRoom());
if (this.elements.copyMyDataBtn) this.elements.copyMyDataBtn.addEventListener('click', () => this.copyMyConnectionData());
if (this.elements.applyFriendDataBtn) this.elements.applyFriendDataBtn.addEventListener('click', () => this.applyFriendConnectionData());
if (this.elements.messageInput) {
this.elements.messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.sendMessage();
});
}
if (this.elements.channelInput) {
this.elements.channelInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.joinChannel();
});
this.elements.channelInput.addEventListener('input', (e) => {
e.target.value = e.target.value.toLowerCase().replace(/\s+/g, '-');
});
}
// Device-specific optimizations
this.setupDeviceOptimizations();
}
setupDeviceOptimizations() {
const isMobile = window.innerWidth <= 768;
const isSmartwatch = window.innerWidth <= 300;
const isDesktop = window.innerWidth >= 1024 && window.matchMedia('(pointer: fine)').matches;
if (isSmartwatch) {
// Minimal UI for smartwatch
document.body.classList.add('smartwatch-mode');
this.elements.helpSection?.remove();
this.elements.settingsToggle?.remove();
}
if (isMobile && !isSmartwatch) {
// Mobile optimizations
this.elements.channelInput.addEventListener('focus', () => {
setTimeout(() => this.elements.channelInput.scrollIntoView({ behavior: 'smooth', block: 'center' }), 300);
});
// Prevent zoom on input focus
this.elements.channelInput.addEventListener('touchstart', () => {
this.elements.channelInput.style.fontSize = '16px';
});
}
if (isDesktop) {
// Desktop enhancements
this.addKeyboardShortcuts();
this.addHoverEffects();
}
// Handle orientation changes
window.addEventListener('orientationchange', () => {
setTimeout(() => this.handleOrientationChange(), 100);
});
}
addKeyboardShortcuts() {
document.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey) {
try {
switch (e.key) {
case 'm':
e.preventDefault();
if (this.connectedPeers.size > 0) this.toggleMute();
break;
case 't':
e.preventDefault();
if (this.connectedPeers.size > 0) this.playTestTone();
break;
case 'h':
e.preventDefault();
if (this.connectedPeers.size > 0) this.hangUp();
break;
}
} catch (error) {
console.error('Keyboard shortcut error:', error);
}
}
});
}
addHoverEffects() {
// Add visual feedback for desktop users
const controls = document.querySelectorAll('.btn-control');
controls.forEach(control => {
control.addEventListener('mouseenter', () => {
control.style.transform = 'translateY(-2px) scale(1.05)';
});
control.addEventListener('mouseleave', () => {
control.style.transform = '';
});
});
}
handleOrientationChange() {
// Adjust UI for orientation changes
const isLandscape = window.innerHeight < window.innerWidth;
const isSmallScreen = window.innerHeight < 500;
if (isLandscape && isSmallScreen) {
document.body.classList.add('landscape-compact');
} else {
document.body.classList.remove('landscape-compact');
}
// Scroll to top after orientation change
setTimeout(() => {
window.scrollTo({ top: 0, behavior: 'smooth' });
}, 200);
}
showNotification(message, type = 'info') {
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.innerHTML = `
<div class="toast-content">
<span class="toast-message">${message}</span>
</div>
`;
document.body.appendChild(toast);
requestAnimationFrame(() => {
toast.classList.add('toast-show');
});
setTimeout(() => {
toast.classList.add('toast-hide');
setTimeout(() => toast.remove(), 300);
}, 3000);
}
async startCall() {
if (this.isCallActive) return;
try {
await this.getUserMedia();
this.isCallActive = true;
this.updateParticipantCallStatus();
this.updateButtonStates();
this.updateStatus('Voice call active');
this.showNotification('Call started', 'success');
} catch (error) {
console.error('Failed to start call:', error);
this.showNotification('Microphone access denied', 'error');
}
}
toggleSpeaker() {
if (!this.isCallActive) {
this.showNotification('No active call', 'error');
return;
}
this.isSpeakerMode = !this.isSpeakerMode;
if (this.isSpeakerMode) {
this.elements.speakerBtn.textContent = '🔊 Speaker';
this.elements.speakerBtn.classList.remove('active');
} else {
this.elements.speakerBtn.textContent = '📱 Earpiece';
this.elements.speakerBtn.classList.add('active');
}
this.applyAudioRouting();
const mode = this.isSpeakerMode ? 'speaker' : 'earpiece';
this.showNotification(`Audio switched to ${mode}`, 'info');
}
applyAudioRouting() {
const audioElements = document.querySelectorAll('audio');
audioElements.forEach(audio => {
if (this.isSpeakerMode) {
audio.volume = 1.0;
} else {
audio.volume = 0.8;
}
});
}
updateButtonStates() {
if (this.isCallActive) {
this.elements.startCallBtn.textContent = '📞 In Call';
this.elements.startCallBtn.classList.add('active');
this.elements.endCallBtn.textContent = '📵 End Call';
this.elements.endCallBtn.classList.add('active');
} else if (this.othersInCall) {
this.elements.startCallBtn.textContent = '📞 Join Call';
this.elements.startCallBtn.classList.remove('active');
this.elements.endCallBtn.textContent = '🚪 Leave Room';
this.elements.endCallBtn.classList.remove('active');
} else {
this.elements.startCallBtn.textContent = '📞 Start Call';
this.elements.startCallBtn.classList.remove('active');
this.elements.endCallBtn.textContent = '🚪 Leave Room';
this.elements.endCallBtn.classList.remove('active');
}
}
endCall() {
if (!this.isCallActive) {
this.leaveRoom();
return;
}
// Stop audio streams but keep room connection
if (this.localStream) {
this.localStream.getTracks().forEach(track => track.stop());
this.localStream = null;
}
// Close peer connections but don't clear room data
this.peerConnections.forEach(pc => pc.close());
this.peerConnections.clear();
// Update UI
this.isCallActive = false;
this.updateParticipantCallStatus();
this.elements.speakerBtn.textContent = '🔊 Speaker';
this.elements.speakerBtn.classList.remove('active');
this.isSpeakerMode = true;
this.updateButtonStates();
this.updateStatus('Connected to room');
this.showNotification('Left call - others continue', 'info');
}
updateParticipantCallStatus() {
if (database && this.channel && this.userName) {
database.ref(`channels/${this.channel}/participants/${this.userName}/inCall`).set(this.isCallActive);
}
}
leaveRoom() {
// End call if active
if (this.isInCall) {
this.endCall();
}
// Clean up room connection
if (this.channel && database) {
database.ref(`channels/${this.channel}`).off();
this.removeParticipant(this.userName);
}
// Update history and reset
if (this.channel) {
this.updateRoomHistory();
}
this.showCallSetup();
this.resetState();
}
updateStatus(status) {
this.elements.callStatus.textContent = status;
}
updateRoomTitle() {
if (this.elements.roomTitle) {
const displayName = this.roomName || `Room ${this.channel}`;
this.elements.roomTitle.textContent = displayName;
}
}
async requestRoomAccess(channelId, userName) {
this.showNotification('Room is full. Requesting access...', 'info');
const requestData = {
requester: userName,
timestamp: Date.now(),
status: 'pending'
};
// Send access request
const requestRef = database.ref(`channels/${channelId}/accessRequests`).push();
await requestRef.set(requestData);
// Wait for approval/denial
const waitForResponse = new Promise((resolve) => {
const timeout = setTimeout(() => {
requestRef.remove();
resolve('timeout');
}, 30000); // 30 second timeout
requestRef.on('value', (snapshot) => {
const data = snapshot.val();
if (data && data.status !== 'pending') {
clearTimeout(timeout);
requestRef.remove();
resolve(data.status);
}
});
});
const result = await waitForResponse;
if (result === 'approved') {
this.channel = channelId;
this.userName = userName;
this.isInCall = false;
this.setupSignaling();
this.showCallInterface();
this.updateStatus('Connected to room');
this.showNotification('Access granted!', 'success');
} else if (result === 'denied') {
this.showNotification('Access denied by room participants', 'error');
} else {
this.showNotification('Request timed out. Try again later.', 'error');
}
}
setupAccessRequestListener() {
if (!database || !this.channel) return;
database.ref(`channels/${this.channel}/accessRequests`).on('child_added', (snapshot) => {
const requestData = snapshot.val();
if (requestData && requestData.status === 'pending') {
this.showAccessRequest(snapshot.key, requestData);
}
});
}
showAccessRequest(requestId, requestData) {
// Remove any existing access request dialogs
const existing = document.querySelector('.access-request-dialog');
if (existing) existing.remove();
const dialog = document.createElement('div');
dialog.className = 'access-request-dialog';
dialog.innerHTML = `
<div class="dialog-content">
<h4>Room Access Request</h4>
<p><strong>${this.escapeHtml(requestData.requester)}</strong> wants to join this room.</p>
<div class="dialog-buttons">
<button class="btn-secondary" onclick="phoneCall.handleAccessRequest('${requestId}', 'denied')">Deny</button>
<button class="btn-primary" onclick="phoneCall.handleAccessRequest('${requestId}', 'approved')">Allow</button>
</div>
</div>
`;
document.body.appendChild(dialog);
// Auto-deny after 20 seconds
setTimeout(() => {
if (document.contains(dialog)) {
this.handleAccessRequest(requestId, 'denied');
}
}, 20000);
}
handleAccessRequest(requestId, decision) {
// Update request status
database.ref(`channels/${this.channel}/accessRequests/${requestId}`).update({
status: decision,
decidedBy: this.userName,
decidedAt: Date.now()
});
// Remove dialog
const dialog = document.querySelector('.access-request-dialog');
if (dialog) dialog.remove();
const action = decision === 'approved' ? 'allowed' : 'denied';
this.showNotification(`Access request ${action}`, 'info');
}
createPeerConnection(peerId) {
const configuration = {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
{ urls: 'stun:stun2.l.google.com:19302' }
],
iceCandidatePoolSize: 10
};
const pc = new RTCPeerConnection(configuration);
pc.onicecandidate = (event) => {
if (event.candidate) {
const candidate = event.candidate;
if (candidate.sdpMid || candidate.sdpMLineIndex !== null) {
this.sendSignal('ice-candidate', { candidate, targetPeer: peerId });
}
}
};
pc.ontrack = (event) => {
console.log('🎵 Received track from', encodeURIComponent(peerId));
this.remoteStreams.set(peerId, event.streams[0]);
this.setupRemoteAudio(peerId, event.streams[0]);
this.connectedPeers.add(peerId);
this.updateConnectionStatus();
};
pc.onconnectionstatechange = () => {
if (pc.connectionState === 'connected') {
this.connectedPeers.add(peerId);
// --- FIREBASE FREE TIER OPTIMIZATION ---
if (database && (!this.elements.offlineModeToggle || !this.elements.offlineModeToggle.checked)) {
console.log('P2P connection established. Disconnecting from Firebase to save limits.');
try {
database.goOffline();
} catch (e) { }
this.showNotification('Switched to secure P2P connection', 'success');
}
} else if (pc.connectionState === 'failed' || pc.connectionState === 'closed' || pc.connectionState === 'disconnected') {
this.connectedPeers.delete(peerId);
this.removeRemoteAudio(peerId);
this.dataChannels.delete(peerId);
// Re-enable Firebase if we lost connection and are not in manual offline mode
if (this.connectedPeers.size === 0 && database && (!this.elements.offlineModeToggle || !this.elements.offlineModeToggle.checked)) {
console.log('Lost all P2P peers. Reconnecting to Firebase.');
try {
database.goOnline();
this.setupSignaling(); // Re-establish presence
} catch (e) { }
}
}
this.updateConnectionStatus();
};
// Handle dynamic track additions (e.g. from startCall)
pc.onnegotiationneeded = async () => {
console.log('Negotiation needed for peer:', peerId);
try {
if (pc.signalingState !== 'stable') return;
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
this.sendSignal('offer', { offer, targetPeer: peerId });
} catch (err) {
console.error('Renegotiation error:', err);
}
};
// Create DataChannel for messaging
const dataChannel = pc.createDataChannel('messages', {
ordered: true
});
dataChannel.onopen = () => {
console.log('DataChannel opened with', peerId);
this.dataChannels.set(peerId, dataChannel);
this.exchangeReconnectInfo(peerId, dataChannel);
};
dataChannel.onmessage = (event) => {
this.handleP2PMessage(event.data, peerId);
};
pc.ondatachannel = (event) => {
const channel = event.channel;
channel.onmessage = (event) => {
this.handleP2PMessage(event.data, peerId);
};
this.dataChannels.set(peerId, channel);
};
if (this.localStream) {
this.localStream.getTracks().forEach(track => {
pc.addTrack(track, this.localStream);
});
}
return pc;
}
setupPageUnloadHandler() {
// Clean up on page unload/refresh
window.addEventListener('beforeunload', () => {
if (this.channel && this.userName) {
// Use sendBeacon for reliable cleanup on page unload
const cleanupData = JSON.stringify({
channel: this.channel,
userName: this.userName
});
// Immediate cleanup
this.removeParticipant(this.userName);
// Store for potential reconnection
sessionStorage.setItem('phoneCallSession', cleanupData);
}
});
// Handle visibility change (tab switching, minimizing)
document.addEventListener('visibilitychange', () => {
if (document.hidden && this.channel && this.userName) {
// Store session for potential reconnection (with fallback)
try {
sessionStorage.setItem('phoneCallSession', JSON.stringify({
channel: this.channel,
userName: this.userName,
maxCallers: this.maxCallers
}));
} catch (e) {
window.phoneCallSession = JSON.stringify({
channel: this.channel,
userName: this.userName,
maxCallers: this.maxCallers
});
}
}
});
}
checkUrlParams() {
const urlParams = new URLSearchParams(window.location.search);
const channel = urlParams.get('channel');
const maxCallers = urlParams.get('max');
// Check for previous session (with fallback)
let savedSession = null;
try {
savedSession = sessionStorage.getItem('phoneCallSession');
} catch (e) {
// Handle private browsing or storage errors
console.warn('SessionStorage unavailable:', e.message);
savedSession = window.phoneCallSession;
}
if (savedSession) {
try {
const session = JSON.parse(savedSession);
this.elements.channelInput.value = session.channel;
this.elements.nameInput.value = session.userName || '';
if (session.maxCallers) {
this.elements.maxCallers.value = session.maxCallers;
}
// Show reconnection option
this.showReconnectionOption(session);
sessionStorage.removeItem('phoneCallSession');
return;
} catch (e) {
sessionStorage.removeItem('phoneCallSession');
}
}
if (channel) {
this.elements.channelInput.value = channel;
if (maxCallers) {
this.elements.maxCallers.value = maxCallers;
}
}
}
showReconnectionOption(session) {
const reconnectDiv = document.createElement('div');
reconnectDiv.className = 'reconnect-banner';
const displayName = session.roomName || session.channel;
reconnectDiv.innerHTML = `
<div class="dialog-content">
<h4>Welcome Back</h4>
<p>Continue your session in <span class="room-name">${this.escapeHtml(displayName)}</span></p>
<div class="reconnect-buttons">
<button id="dismissBtn" class="btn-secondary">Start Fresh</button>
<button id="reconnectBtn" class="btn-primary">Continue Session</button>
</div>
</div>
`;
this.elements.callSetup.insertBefore(reconnectDiv, this.elements.callSetup.firstChild);
document.getElementById('reconnectBtn').addEventListener('click', () => {
this.userName = session.userName;
this.joinChannel();
reconnectDiv.remove();
});
document.getElementById('dismissBtn').addEventListener('click', () => {
reconnectDiv.remove();
});
}
generateMemorableRoomId() {
const adjectives = ['blue', 'red', 'green', 'happy', 'sunny', 'cool', 'fast', 'smart', 'bright', 'calm'];
const nouns = ['cat', 'dog', 'bird', 'fish', 'tree', 'star', 'moon', 'rock', 'wave', 'fire'];
const numbers = Math.floor(Math.random() * 99) + 1;
const adj = adjectives[Math.floor(Math.random() * adjectives.length)];
const noun = nouns[Math.floor(Math.random() * nouns.length)];
return `${adj}-${noun}-${numbers}`;
}
async quickCall() {
const userName = this.elements.nameInput.value.trim();
if (!userName) {
this.showNotification('Please enter your name first', 'error');
this.elements.nameInput.focus();
return;
}
const memorableId = this.generateMemorableRoomId();
this.elements.channelInput.value = memorableId;
this.maxCallers = parseInt(this.elements.maxCallers.value);
// Check Firebase connection
const isConnected = await this.checkFirebaseConnection();
if (!isConnected) {
this.showNotification('Connection failed. Please try again.', 'error');
return;
}
try {
this.channel = memorableId;
this.userName = userName;
this.isInCall = false;
// Create room immediately
this.setupSignaling();
this.setupAccessRequestListener();
this.showCallInterface();
this.updateStatus('Room created - Share link to invite others');
// Show share section immediately
this.generateShareUrl();
this.elements.shareSection.style.display = 'block';
this.showNotification('Room created successfully!', 'success');
} catch (error) {
console.error('Error creating room:', error);
this.showNotification('Failed to create room', 'error');
}
}
copyMyConnectionData() {
if (!this.elements.myConnectionData.value) return;
this.elements.myConnectionData.select();
document.execCommand('copy');
this.showNotification('Connection data copied!', 'success');
const btn = this.elements.copyMyDataBtn;
const origText = btn.textContent;
btn.textContent = 'Copied!';
setTimeout(() => btn.textContent = origText, 2000);
}
async applyFriendConnectionData() {
const dataStr = this.elements.friendConnectionData.value.trim();
if (!dataStr) {
this.showNotification('Please paste your friend\'s data', 'error');
return;
}
try {
const parsedData = JSON.parse(atob(dataStr));
// If they sent me an offer, I must create an answer
if (parsedData.type === 'offer') {
// Close any proactively generated offline session
if (this.peerConnections.has('offline-friend')) {
this.peerConnections.get('offline-friend').close();
this.peerConnections.delete('offline-friend');
}
const pc = this.createPeerConnection(parsedData.targetPeer || 'friend');
this.peerConnections.set(parsedData.targetPeer || 'friend', pc);
await pc.setRemoteDescription(new RTCSessionDescription(parsedData.offer));
const answer = await pc.createAnswer({ offerToReceiveAudio: true });
await pc.setLocalDescription(answer);
const myData = {
type: 'answer',
answer: answer,
targetPeer: this.userName
};
this.elements.myConnectionData.value = btoa(JSON.stringify(myData));
this.showNotification('Answer generated. Send your new data back to your friend!', 'success');
console.log('Processed offline offer and generated answer.');
}
// If they sent me an answer to my offer
else if (parsedData.type === 'answer') {
const pc = this.peerConnections.get(parsedData.targetPeer || 'friend');
if (pc && pc.signalingState === 'have-local-offer') {
await pc.setRemoteDescription(new RTCSessionDescription(parsedData.answer));
this.showNotification('Connected successfully via manual answer!', 'success');
console.log('✅ Manual offline call established!');
} else {
this.showNotification('No matching offer found for this answer.', 'error');
}
}
} catch (error) {
console.error('Invalid connection data:', error);
this.showNotification('Invalid connection data format.', 'error');
}
}
toggleSettings() {
const panel = this.elements.settingsPanel;
const isHidden = panel.classList.contains('hidden');
if (isHidden) {
panel.classList.remove('hidden');
panel.classList.add('slide-up');
} else {
panel.classList.add('hidden');
panel.classList.remove('slide-up');
}
}
toggleParticipants() {
const list = this.elements.participantsList;
const toggle = this.elements.participantsToggle;
const isHidden = list.classList.contains('hidden');
if (isHidden) {
list.classList.remove('hidden');
list.classList.add('slide-up');
toggle.classList.add('expanded');
} else {
list.classList.add('hidden');
list.classList.remove('slide-up');
toggle.classList.remove('expanded');
}
}
toggleHelp() {
const content = this.elements.helpContent;
const isHidden = content.classList.contains('hidden');
if (isHidden) {
content.classList.remove('hidden');
content.classList.add('slide-up');
} else {
content.classList.add('hidden');
content.classList.remove('slide-up');
}
}
toggleHistory() {
const list = this.elements.historyList;
const toggle = this.elements.historyToggle;
const isHidden = list.classList.contains('hidden');
if (isHidden) {
this.loadChatHistory();
list.classList.remove('hidden');
list.classList.add('slide-up');
toggle.classList.add('expanded');
} else {
list.classList.add('hidden');
list.classList.remove('slide-up');
toggle.classList.remove('expanded');
}
}
async sendMessage() {
const message = this.elements.messageInput.value.trim();
if (!message || this.dataChannels.size === 0) return;
const encryptedText = await this.encryptMessage(message);
const messageData = {
text: encryptedText,
sender: this.userName,
timestamp: Date.now(),
id: Math.random().toString(36).substring(2, 15)
};
// Display locally
this.displayMessage({
text: message,
sender: this.userName,
timestamp: messageData.timestamp,
id: messageData.id
});
// Save to local storage
this.saveMessageToHistory({
text: message,
sender: this.userName,
timestamp: messageData.timestamp,
id: messageData.id
});
// Send encrypted message via P2P DataChannels
const messageStr = JSON.stringify(messageData);
this.dataChannels.forEach((channel, peerId) => {
if (channel.readyState === 'open') {
channel.send(messageStr);
}
});
this.elements.messageInput.value = '';
}
setupMessageListener() {
// Clear current messages for fresh start
this.elements.messagesList.innerHTML = '';
// Messages now handled via P2P DataChannels
}
displayMessage(messageData) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${messageData.sender === this.userName ? 'own' : 'other'}`;
// Enhanced message with timestamp and status
const time = new Date(messageData.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
messageDiv.innerHTML = `
${messageData.sender !== this.userName ? `<div class="message-sender">${this.escapeHtml(messageData.sender)}</div>` : ''}
<div class="message-content">
<div class="message-text">${this.processMessageText(messageData.text)}</div>
<div class="message-time">${time}</div>
</div>
`;
// Animate message in
messageDiv.style.opacity = '0';
messageDiv.style.transform = 'translateY(10px)';
this.elements.messagesList.appendChild(messageDiv);
requestAnimationFrame(() => {
messageDiv.style.transition = 'all 0.3s ease';
messageDiv.style.opacity = '1';
messageDiv.style.transform = 'translateY(0)';
});
// Smart scroll
this.smartScroll();
// Save to history
this.saveMessageToHistory(messageData);
// Sound notification for received messages
if (messageData.sender !== this.userName) {
this.playMessageSound();
}
}
processMessageText(text) {
// Enhanced text processing with emoji support and links
let processed = this.escapeHtml(text);
// Auto-link URLs
processed = processed.replace(
/(https?:\/\/[^\s]+)/g,
'<a href="$1" target="_blank" rel="noopener">$1</a>'
);
return processed;
}
smartScroll() {
const messages = this.elements.messagesList;
const isNearBottom = messages.scrollTop + messages.clientHeight >= messages.scrollHeight - 50;
if (isNearBottom) {
messages.scrollTo({
top: messages.scrollHeight,