-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
797 lines (718 loc) · 33.5 KB
/
Copy pathscript.js
File metadata and controls
797 lines (718 loc) · 33.5 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
// PeerChat - Standalone JS (P2P with PeerJS + AES via CryptoJS)
(function(){
const params = new URLSearchParams(window.location.search);
let room = params.get('room');
if(!room){
room = Math.random().toString(36).substring(2,8);
window.history.replaceState({},'',window.location.pathname+'?room='+room);
}
const $ = (id) => document.getElementById(id);
// Mobile Keyboard Viewport Height Fix
if (window.visualViewport) {
const adjustViewport = () => {
const vh = window.visualViewport.height;
document.documentElement.style.setProperty('--pc-vh', `${vh}px`);
};
window.visualViewport.addEventListener('resize', adjustViewport);
window.visualViewport.addEventListener('scroll', adjustViewport);
adjustViewport();
}
$('roomId').textContent = room;
$('roomAvatar').firstChild.textContent = room.substring(0,2).toUpperCase();
let peer=null, conn=null, currentCall=null, localStream=null, role=null;
let isSharing=false, isCalling=false, hasRealStream=false;
const SVG_MIC = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="22"/></svg>`;
const SVG_MIC_OFF = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="2" x2="22" y2="22"/><path d="M18.89 13.23A7.12 7.12 0 0 0 19 12v-2"/><path d="M5 10v2a7 7 0 0 0 12 5.79"/><path d="M15 9.34V5a3 3 0 0 0-5.68-1.33"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12"/><line x1="12" y1="19" x2="12" y2="22"/></svg>`;
const SVG_VIDEO = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 8-6 4 6 4V8Z"/><rect width="14" height="12" x="2" y="6" rx="2" ry="2"/></svg>`;
const SVG_VIDEO_OFF = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.66 6H14a2 2 0 0 1 2 2v2.5l5.25-3.25A1 1 0 0 1 23 8v8a1 1 0 0 1-1.75.75L16 13.5V14a2 2 0 0 1-2 2h-3.34"/><line x1="2" y1="2" x2="22" y2="22"/><path d="M16 16a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h2"/></svg>`;
const SVG_IMAGE_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pc-reply-type-icon"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`;
const setStatus = (label, online) => {
$('headerStatus').textContent = label;
$('statusDot').classList.toggle('online', !!online);
$('statusDot').classList.toggle('idle', !online);
$('roomDot').classList.toggle('online', !!online);
$('disconnectBtn').style.display = online ? 'inline-flex' : 'none';
if ($('hdrDisconnectBtn')) {
$('hdrDisconnectBtn').style.display = online ? 'inline-flex' : 'none';
}
const canCall = !!online && !isCalling && !isSharing;
$('startVideoBtn').disabled = !canCall;
$('shareScreenBtn').disabled = !canCall;
$('hdrVideoBtn').disabled = !canCall;
$('hdrShareBtn').disabled = !canCall;
};
const fmtTime = () => new Date().toLocaleTimeString([], {hour:'2-digit',minute:'2-digit'});
const fmtBytes = (b) => b<1024?b+' B':b<1048576?(b/1024).toFixed(1)+' KB':(b/1048576).toFixed(2)+' MB';
const chatStack = $('chatStack');
function clearEmpty(){ const e=chatStack.querySelector('.pc-empty'); if(e) e.remove(); }
function logSystem(text){
clearEmpty();
const d=document.createElement('div'); d.className='pc-msg-system';
const s=document.createElement('span'); s.textContent=text; d.appendChild(s);
chatStack.appendChild(d); chatStack.parentElement.scrollTop=chatStack.parentElement.scrollHeight;
}
const reactionsState = {}; // { msgId: { you: emoji, peer: emoji } }
let replyingTo = null; // { id, text, sender }
function setReply(id, text, sender) {
replyingTo = { id, text, sender };
$('replyPreviewSender').textContent = `Replying to ${sender}`;
if (text === 'Image') {
$('replyPreviewText').innerHTML = `${SVG_IMAGE_ICON} Image`;
} else {
$('replyPreviewText').textContent = text;
}
$('replyPreview').style.display = 'flex';
$('messageInput').focus();
}
function cancelReply() {
replyingTo = null;
$('replyPreview').style.display = 'none';
}
function handleReact(msgId, emoji, sender) {
if (!reactionsState[msgId]) {
reactionsState[msgId] = {};
}
if (reactionsState[msgId][sender] === emoji) {
delete reactionsState[msgId][sender];
} else {
reactionsState[msgId][sender] = emoji;
}
const row = chatStack.querySelector(`[data-msg-id="${msgId}"]`);
if (!row) return;
const bubble = row.querySelector('.pc-bubble');
if (!bubble) return;
let capsule = bubble.querySelector('.pc-reaction-capsule');
const activeReactions = Object.values(reactionsState[msgId]).filter(Boolean);
if (activeReactions.length === 0) {
if (capsule) capsule.remove();
row.classList.remove('has-reaction');
return;
}
if (!capsule) {
capsule = document.createElement('div');
capsule.className = 'pc-reaction-capsule';
capsule.addEventListener('click', (e) => {
e.stopPropagation();
if (reactionsState[msgId]['you']) {
const currentEmoji = reactionsState[msgId]['you'];
handleReact(msgId, currentEmoji, 'you');
sendReaction(msgId, currentEmoji);
}
});
bubble.appendChild(capsule);
}
const unique = [...new Set(activeReactions)];
capsule.innerHTML = unique.map(e => `<span class="pc-reaction-emoji">${e}</span>`).join('');
row.classList.add('has-reaction');
}
function sendReaction(targetId, emoji) {
if (!conn || !conn.open) return;
conn.send({
type: 'reaction',
targetId: targetId,
emoji: emoji
});
}
function closeEmojiSelector() {
const active = document.querySelector('.pc-emoji-selector');
if (active) {
active.remove();
}
document.querySelectorAll('.pc-msg-row.emoji-open').forEach(r => r.classList.remove('emoji-open'));
}
const emojiKeywords = {
'👍': 'like thumbsup yes ok agree good positive check',
'❤️': 'love heart red like favorite',
'😂': 'laugh cry haha lol tear happy fun funny smile',
'😮': 'wow surprise shock gasp amazed open mouth',
'😢': 'sad cry tear upset unhappy hurt pain sob',
'🙏': 'please pray thank you gratitude hands hope highfive',
'🔥': 'fire hot burn lit cool awesome trend spark',
'👏': 'clap applaud congrats good job well done',
'🎉': 'party celebrate congrats birthday holiday balloon',
'✨': 'sparkles shine magic glow star brand new',
'😎': 'cool sunglasses chill smart slick sun glass',
'💡': 'lightbulb idea bulb brain creative smart info',
'🥳': 'party celebrate happy birthday face horn hat',
'🥰': 'love hearts blushing happy sweet soft warm smile',
'😍': 'love heart eyes adoration infatuated beauty like',
'🤩': 'star eyes starstruck amazed awesome wow',
'🤔': 'think ponder question hmm doubt confused',
'🤨': 'raised eyebrow suspicious skeptical doubt huh',
'🙄': 'roll eyes bored annoy whatever sigh',
'😅': 'laugh sweat nervous relief happy smile haha',
'😭': 'cry sob sad loud tears unhappy pain',
'😡': 'angry mad rage furious red face annoyed',
'😱': 'scream fear shock horror face gasp ghost',
'🥱': 'yawn tired sleepy bore wake up',
'😴': 'sleep dream zzz tired rest night',
'🤐': 'zipper mouth quiet secret shh silence',
'🤫': 'shh quiet silence secret whisper',
'💩': 'poop turd brown smelly funny smile',
'🤡': 'clown circus face funny makeup joker',
'👻': 'ghost scary spooky halloween white phantom',
'👽': 'alien space UFO monster green extraterrestrial',
'👾': 'monster alien space invader game pixel retro',
'👑': 'king queen crown royal gold prince princess',
'💯': 'hundred 100 percent perfect score grade success',
'✔️': 'check mark tick yes correct confirm done',
'❌': 'cross mark x no wrong incorrect fail cancel',
'⚠️': 'warning caution alert hazard exclamation sign',
'💔': 'heartbroken break sad love hurt end divorce',
'💖': 'sparkle heart love pink glowing shine',
'💗': 'grow heart love pink pulsing expand',
'🌟': 'star shine glow gold bright spark favorite',
'🌈': 'rainbow color sky weather hope LGBT pride',
'☀️': 'sun warm hot summer bright clear day weather',
'🌙': 'moon crescent night sleep space dark',
'❄️': 'snow flake cold winter weather ice freeze',
'🍀': 'clover leaf luck green Irish shamrock',
'🍕': 'pizza slice cheese food fast food dinner eat',
'🍻': 'beer cheers drink mug bar alcohol celebrate',
'☕': 'coffee tea mug hot caffeine morning drink',
'✈️': 'plane airplane flight travel vacation sky airport',
'🎈': 'balloon party celebrate birthday red toy float',
'🎁': 'gift present box wrap birthday christmas holiday',
'🎮': 'game controller video game play arcade console joystick',
'🎵': 'music note song sound melody audio tune'
};
function expandEmojiSelector(selector, msgId) {
selector.innerHTML = '';
selector.classList.add('expanded');
const grid = document.createElement('div');
grid.className = 'pc-emoji-grid';
const allEmojis = Object.keys(emojiKeywords);
const renderGrid = (filterQuery = '') => {
grid.innerHTML = '';
const query = filterQuery.toLowerCase().trim();
const filtered = allEmojis.filter(emoji => {
const keywords = emojiKeywords[emoji] || '';
return emoji.includes(query) || keywords.toLowerCase().includes(query);
});
filtered.forEach(emoji => {
const opt = document.createElement('span');
opt.className = 'pc-emoji-option';
opt.textContent = emoji;
opt.addEventListener('click', (e) => {
e.stopPropagation();
handleReact(msgId, emoji, 'you');
sendReaction(msgId, emoji);
closeEmojiSelector();
});
grid.appendChild(opt);
});
};
renderGrid();
selector.appendChild(grid);
const customRow = document.createElement('div');
customRow.className = 'pc-emoji-custom-row';
const input = document.createElement('input');
input.type = 'text';
input.className = 'pc-emoji-custom-input';
input.placeholder = 'Search or paste emoji (Enter)...';
input.maxLength = 10;
input.addEventListener('click', (e) => e.stopPropagation());
const doSubmit = () => {
const val = input.value.trim();
if (val) {
handleReact(msgId, val, 'you');
sendReaction(msgId, val);
closeEmojiSelector();
}
};
input.addEventListener('input', () => {
const val = input.value.trim();
if (val && Array.from(val).length === 1 && !/[a-zA-Z0-9]/.test(val)) {
handleReact(msgId, val, 'you');
sendReaction(msgId, val);
closeEmojiSelector();
return;
}
renderGrid(val);
});
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.stopPropagation();
doSubmit();
}
});
customRow.appendChild(input);
selector.appendChild(customRow);
setTimeout(() => input.focus(), 50);
}
function appendMessage(type, contentNode, msgId, replyTo){
clearEmpty();
if(!msgId) msgId = 'msg-' + Math.random().toString(36).substring(2, 9);
const row=document.createElement('div'); row.className='pc-msg-row '+(type==='sent'?'right':'left');
row.setAttribute('data-msg-id', msgId);
const b=document.createElement('div'); b.className='pc-bubble '+(type==='sent'?'pc-bubble-sent':'pc-bubble-received');
b.appendChild(contentNode);
const t=document.createElement('div'); t.className='pc-bubble-time'; t.textContent=fmtTime();
b.appendChild(t);
if (replyTo) {
const quote = document.createElement('div');
quote.className = 'pc-bubble-reply-quote';
const sender = document.createElement('div');
sender.className = 'pc-bubble-reply-sender';
sender.textContent = replyTo.sender || 'Reply';
const qText = document.createElement('div');
qText.className = 'pc-bubble-reply-text';
if (replyTo.text === 'Image') {
qText.innerHTML = `${SVG_IMAGE_ICON} Image`;
} else {
qText.textContent = replyTo.text;
}
quote.appendChild(sender);
quote.appendChild(qText);
quote.addEventListener('click', (e) => {
e.stopPropagation();
const target = chatStack.querySelector(`[data-msg-id="${replyTo.id}"]`);
if (target) {
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
target.classList.add('pc-msg-flash');
setTimeout(() => target.classList.remove('pc-msg-flash'), 1200);
}
});
b.insertBefore(quote, b.firstChild);
}
const actions = document.createElement('div');
actions.className = 'pc-msg-actions';
const reactBtn = document.createElement('button');
reactBtn.className = 'pc-msg-action-btn pc-msg-action-react';
reactBtn.title = 'React';
reactBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>`;
const replyBtn = document.createElement('button');
replyBtn.className = 'pc-msg-action-btn pc-msg-action-reply';
replyBtn.title = 'Reply';
replyBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg>`;
actions.appendChild(reactBtn);
actions.appendChild(replyBtn);
replyBtn.addEventListener('click', (e) => {
e.stopPropagation();
let textSnippet = '';
const textEl = contentNode.querySelector('.pc-bubble-text');
if (textEl) {
textSnippet = textEl.textContent;
} else if (contentNode.classList.contains('pc-file-card')) {
textSnippet = contentNode.querySelector('.pc-file-name').textContent;
} else if (contentNode.classList.contains('pc-image-wrapper')) {
textSnippet = 'Image';
} else {
textSnippet = contentNode.textContent || 'File';
}
setReply(msgId, textSnippet, type === 'sent' ? 'You' : 'Peer');
});
reactBtn.addEventListener('click', (e) => {
e.stopPropagation();
const existing = document.querySelector('.pc-emoji-selector');
const isSameMsg = existing && existing.dataset.targetId === msgId;
closeEmojiSelector();
if (isSameMsg) return;
const selector = document.createElement('div');
selector.className = 'pc-emoji-selector';
selector.dataset.targetId = msgId;
row.classList.add('emoji-open');
if (type === 'sent') {
selector.style.right = '0';
} else {
selector.style.left = '0';
}
// Check space above the button to prevent clipping
const rect = reactBtn.getBoundingClientRect();
const canvasRect = $('chatCanvas').getBoundingClientRect();
const spaceAbove = rect.top - canvasRect.top;
if (spaceAbove < 240) {
selector.style.bottom = 'auto';
selector.style.top = '34px';
} else {
selector.style.bottom = '34px';
selector.style.top = 'auto';
}
const emojis = ['👍', '❤️', '😂', '😮', '😢', '🙏'];
emojis.forEach(emoji => {
const opt = document.createElement('span');
opt.className = 'pc-emoji-option';
opt.textContent = emoji;
opt.addEventListener('click', (e) => {
e.stopPropagation();
handleReact(msgId, emoji, 'you');
sendReaction(msgId, emoji);
closeEmojiSelector();
});
selector.appendChild(opt);
});
const plusBtn = document.createElement('span');
plusBtn.className = 'pc-emoji-option pc-emoji-plus';
plusBtn.title = 'More emojis';
plusBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>`;
plusBtn.addEventListener('click', (e) => {
e.stopPropagation();
expandEmojiSelector(selector, msgId);
});
selector.appendChild(plusBtn);
reactBtn.appendChild(selector);
});
if (type === 'sent') {
row.appendChild(actions);
row.appendChild(b);
} else {
row.appendChild(b);
row.appendChild(actions);
}
chatStack.appendChild(row);
chatStack.parentElement.scrollTop=chatStack.parentElement.scrollHeight;
}
function textNode(text){ const d=document.createElement('div'); d.className='pc-bubble-text'; d.textContent=text; return d; }
function fileNode(data){
if(data.fileType && data.fileType.startsWith('image/')){
const a=document.createElement('a'); a.href=data.file; a.download=data.fileName; a.className='pc-image-wrapper';
const img=document.createElement('img'); img.src=data.file; img.className='pc-file-image';
const btn=document.createElement('div'); btn.className='pc-image-download-btn';
btn.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
a.appendChild(img); a.appendChild(btn); return a;
}
const a=document.createElement('a'); a.href=data.file; a.download=data.fileName; a.className='pc-file-card';
const ic=document.createElement('div'); ic.className='pc-file-icon';
ic.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
const meta=document.createElement('div'); meta.className='pc-file-meta';
const nm=document.createElement('div'); nm.className='pc-file-name'; nm.textContent=data.fileName;
const sz=document.createElement('div'); sz.className='pc-file-size'; sz.textContent=fmtBytes(data.fileSize||0);
meta.appendChild(nm); meta.appendChild(sz); a.appendChild(ic); a.appendChild(meta); return a;
}
const encrypt = (m) => CryptoJS.AES.encrypt(m, room).toString();
const decrypt = (d) => { try { return CryptoJS.AES.decrypt(d, room).toString(CryptoJS.enc.Utf8); } catch(e){ return '[decrypt failed]'; } };
function setupConn(c){
conn=c;
c.on('open',()=>{ setStatus('Online', true); logSystem('Chat connection established'); });
c.on('data', (data)=>{
if(data && data.type==='call-ended'){ endMedia(true); logSystem('Peer ended the stream'); return; }
if(typeof data==='object' && data.file){
const mId = data.id || 'msg-' + Math.random().toString(36).substring(2, 9);
appendMessage('received', fileNode(data), mId);
return;
}
if(typeof data==='object' && data.type === 'reaction'){
handleReact(data.targetId, data.emoji, 'peer');
return;
}
if(typeof data==='object' && data.type === 'chat'){
const text = decrypt(data.content);
let rxSender = 'Reply';
if (data.replyToSender) {
rxSender = data.replyToSender === 'You' ? 'Peer' : 'You';
}
const replyInfo = data.replyToId ? { id: data.replyToId, text: data.replyToText, sender: rxSender } : null;
appendMessage('received', textNode(text), data.id, replyInfo);
return;
}
if(typeof data === 'string') {
const mId = 'msg-' + Math.random().toString(36).substring(2, 9);
appendMessage('received', textNode(decrypt(data)), mId);
}
});
c.on('close',()=>{ setStatus('Disconnected', false); logSystem('Peer disconnected'); });
c.on('error',(e)=>logSystem('Connection error: '+e));
}
function createDummyStream() {
try {
const tracks = [];
try {
const canvas = document.createElement('canvas');
canvas.width = 16;
canvas.height = 16;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, 16, 16);
const canvasStream = (canvas.captureStream || canvas.webkitCaptureStream).call(canvas, 1);
const vt = canvasStream.getVideoTracks()[0];
if (vt) tracks.push(vt);
} catch (e) {}
try {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const dst = audioCtx.createMediaStreamDestination();
const at = dst.stream.getAudioTracks()[0];
if (at) tracks.push(at);
} catch (e) {}
return new MediaStream(tracks);
} catch (e) {
return null;
}
}
async function handleIncomingCall(call){
const isScreen = call.metadata && call.metadata.isScreenShare;
if (isScreen) {
call.answer();
setupCall(call);
showOverlay('Incoming screen share', true);
setStatus('Online', true);
} else {
localStream = createDummyStream();
hasRealStream = false;
call.answer(localStream);
setupCall(call);
isCalling = true;
showOverlay('On video call', false);
setStatus('Online', true);
// Start B's camera/mic as MUTED by default
$('toggleAudioBtn').classList.add('muted');
$('toggleAudioBtn').innerHTML = SVG_MIC_OFF;
$('toggleVideoBtn').classList.add('muted');
$('toggleVideoBtn').innerHTML = SVG_VIDEO_OFF;
}
}
function setupCall(call){
currentCall=call;
call.on('stream', (rs)=>{ $('remoteVideo').srcObject=rs; });
call.on('close', ()=>{
if (currentCall) {
currentCall = null;
endMedia(true);
logSystem('Call ended');
}
});
call.on('error', (e)=>logSystem('Call error: '+e));
}
function initHost(){
peer = new Peer(room+'-host', { debug:1, config:{ iceServers:[{urls:'stun:stun.l.google.com:19302'}] } });
peer.on('open',()=>{ role='host'; setStatus('Waiting for peer...', false); logSystem('Waiting for peer to join...'); peer.on('connection', setupConn); peer.on('call', handleIncomingCall); });
peer.on('error',(err)=>{ if(err.type==='unavailable-id'){ try{ peer.destroy(); }catch(e){} initGuest(); } else logSystem('Peer error: '+err.type); });
}
function initGuest(){
const gid = room+'-guest-'+Math.random().toString(36).substring(2,6);
peer = new Peer(gid, { debug:1, config:{ iceServers:[{urls:'stun:stun.l.google.com:19302'}] } });
peer.on('open',()=>{ role='guest'; setStatus('Connecting to host...', false); logSystem('Connecting to host...'); const c=peer.connect(room+'-host',{reliable:true}); setupConn(c); peer.on('call', handleIncomingCall); });
peer.on('error',(err)=>logSystem('Peer error: '+(err.type||err)));
}
function sendMessage(){
const v = $('messageInput').value.trim(); if(!v) return;
if(!conn || !conn.open){ logSystem('Waiting for peer...'); return; }
const msgId = 'msg-' + Math.random().toString(36).substring(2, 9);
const payload = {
type: 'chat',
id: msgId,
content: encrypt(v)
};
if (replyingTo) {
payload.replyToId = replyingTo.id;
payload.replyToText = replyingTo.text;
payload.replyToSender = replyingTo.sender;
}
conn.send(payload);
appendMessage('sent', textNode(v), msgId, replyingTo);
if (replyingTo) {
cancelReply();
}
$('messageInput').value='';
}
function onFile(e){
const f=e.target.files[0]; if(!f) return;
if(!conn||!conn.open){ logSystem('Waiting for peer...'); e.target.value=''; return; }
const msgId = 'msg-' + Math.random().toString(36).substring(2, 9);
const r=new FileReader();
r.onload=(ev)=>{
const payload={
id: msgId,
file:ev.target.result,
fileName:f.name,
fileType:f.type,
fileSize:f.size
};
conn.send(payload);
appendMessage('sent', fileNode(payload), msgId);
};
r.readAsDataURL(f);
e.target.value='';
}
function showOverlay(label, isScreenShare){
$('mediaLabel').textContent = label || 'On call';
$('mediaOverlay').style.display='flex';
$('mediaOverlay').classList.toggle('is-screen-share', !!isScreenShare);
if (isScreenShare) {
$('toggleAudioBtn').style.display = 'none';
$('toggleVideoBtn').style.display = 'none';
} else {
$('toggleAudioBtn').style.display = '';
$('toggleVideoBtn').style.display = '';
}
}
function hideOverlay(){ $('mediaOverlay').style.display='none'; }
function getSenderKind(sender) {
if (sender.track) return sender.track.kind;
return sender.dtmf ? 'audio' : 'video';
}
async function acquireRealStream() {
if (hasRealStream) return true;
try {
if (!navigator.mediaDevices) {
throw new Error("WebRTC requires secure context");
}
const stream = await navigator.mediaDevices.getUserMedia({video:true,audio:true});
const realVideoTrack = stream.getVideoTracks()[0];
const realAudioTrack = stream.getAudioTracks()[0];
if (localStream) {
localStream.getTracks().forEach(t => t.stop());
}
localStream = stream;
hasRealStream = true;
$('localVideo').srcObject = localStream;
if (currentCall && currentCall.peerConnection) {
const senders = currentCall.peerConnection.getSenders();
senders.forEach(sender => {
const kind = getSenderKind(sender);
if (kind === 'video' && realVideoTrack) {
sender.replaceTrack(realVideoTrack);
} else if (kind === 'audio' && realAudioTrack) {
sender.replaceTrack(realAudioTrack);
}
});
}
return true;
} catch(e) {
logSystem('Camera/Mic permission denied: ' + e.message);
$('toggleVideoBtn').classList.add('muted');
$('toggleVideoBtn').innerHTML = SVG_VIDEO_OFF;
$('toggleAudioBtn').classList.add('muted');
$('toggleAudioBtn').innerHTML = SVG_MIC_OFF;
return false;
}
}
async function toggleAudio() {
if (!hasRealStream) {
const ok = await acquireRealStream();
if (!ok) return;
const audioTrack = localStream.getAudioTracks()[0];
const videoTrack = localStream.getVideoTracks()[0];
if (audioTrack) audioTrack.enabled = true;
if (videoTrack) videoTrack.enabled = false;
$('toggleAudioBtn').classList.remove('muted');
$('toggleAudioBtn').innerHTML = SVG_MIC;
$('toggleVideoBtn').classList.add('muted');
$('toggleVideoBtn').innerHTML = SVG_VIDEO_OFF;
$('localVideo').classList.add('hidden');
} else {
const audioTrack = localStream.getAudioTracks()[0];
if (audioTrack) {
audioTrack.enabled = !audioTrack.enabled;
$('toggleAudioBtn').classList.toggle('muted', !audioTrack.enabled);
$('toggleAudioBtn').innerHTML = audioTrack.enabled ? SVG_MIC : SVG_MIC_OFF;
}
}
}
async function toggleVideo() {
if (!hasRealStream) {
const ok = await acquireRealStream();
if (!ok) return;
const audioTrack = localStream.getAudioTracks()[0];
const videoTrack = localStream.getVideoTracks()[0];
if (audioTrack) audioTrack.enabled = false;
if (videoTrack) videoTrack.enabled = true;
$('toggleAudioBtn').classList.add('muted');
$('toggleAudioBtn').innerHTML = SVG_MIC_OFF;
$('toggleVideoBtn').classList.remove('muted');
$('toggleVideoBtn').innerHTML = SVG_VIDEO;
$('localVideo').classList.remove('hidden');
} else {
const videoTrack = localStream.getVideoTracks()[0];
if (videoTrack) {
videoTrack.enabled = !videoTrack.enabled;
$('toggleVideoBtn').classList.toggle('muted', !videoTrack.enabled);
$('toggleVideoBtn').innerHTML = videoTrack.enabled ? SVG_VIDEO : SVG_VIDEO_OFF;
$('localVideo').classList.toggle('hidden', !videoTrack.enabled);
}
}
}
async function startVideo(){
try{
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
throw new Error("Media devices are not available. WebRTC requires a secure context (HTTPS or localhost). If serving locally, use 'localhost' in your URL.");
}
localStream = await navigator.mediaDevices.getUserMedia({video:true,audio:true});
hasRealStream = true;
$('localVideo').srcObject = localStream; $('localVideo').classList.remove('hidden');
if(!conn||!conn.open){ logSystem('Peer not connected'); localStream.getTracks().forEach(t=>t.stop()); return; }
const call=peer.call(conn.peer, localStream); setupCall(call);
isCalling=true; showOverlay('On video call', false); setStatus('Online', true);
$('toggleAudioBtn').classList.remove('muted');
$('toggleAudioBtn').innerHTML = SVG_MIC;
$('toggleVideoBtn').classList.remove('muted');
$('toggleVideoBtn').innerHTML = SVG_VIDEO;
} catch(e){ logSystem('Cannot start video: '+e.message); }
}
async function startShare(){
try{
if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
throw new Error("Screen sharing is not supported on this device/browser.");
}
localStream = await navigator.mediaDevices.getDisplayMedia({video:true});
hasRealStream = true;
$('localVideo').srcObject = localStream; $('localVideo').classList.remove('hidden');
if(!conn||!conn.open){ logSystem('Peer not connected'); localStream.getTracks().forEach(t=>t.stop()); return; }
const call=peer.call(conn.peer, localStream, {metadata:{isScreenShare:true}}); setupCall(call);
const vt = localStream.getVideoTracks()[0];
if (vt) vt.addEventListener('ended', endMedia);
isSharing=true; showOverlay('Sharing screen', true); setStatus('Online', true);
$('mediaOverlay').classList.add('local-is-main');
$('toggleAudioBtn').classList.remove('muted');
$('toggleAudioBtn').innerHTML = SVG_MIC;
$('toggleVideoBtn').classList.remove('muted');
$('toggleVideoBtn').innerHTML = SVG_VIDEO;
} catch(e){ logSystem('Cannot share screen: '+e.message); }
}
function endMedia(silent){
try{ if(!silent && conn && conn.open) conn.send({type:'call-ended'}); }catch(e){}
if(currentCall){
const tempCall = currentCall;
currentCall = null;
try{tempCall.close();}catch(e){}
}
if(localStream){ localStream.getTracks().forEach(t=>t.stop()); localStream=null; }
hasRealStream = false;
$('localVideo').srcObject=null; $('localVideo').classList.add('hidden');
$('remoteVideo').srcObject=null;
$('mediaOverlay').classList.remove('local-is-main');
$('mediaOverlay').classList.remove('is-screen-share');
isCalling=false; isSharing=false; hideOverlay(); setStatus(conn&&conn.open?'Online':'Disconnected', !!(conn&&conn.open));
}
function disconnect(){
endMedia(false);
try{ if(conn) conn.close(); if(peer && !peer.destroyed) peer.destroy(); }catch(e){}
setStatus('Disconnected', false); logSystem('You disconnected from the room');
}
async function copyRoom(){
const link=window.location.origin+window.location.pathname+'?room='+room;
try{ await navigator.clipboard.writeText(link); }catch(e){}
$('copyBtn').textContent='Copied'; setTimeout(()=>$('copyBtn').textContent='Copy',1500);
}
$('sendBtn').addEventListener('click', sendMessage);
$('messageInput').addEventListener('keydown',(e)=>{ if(e.key==='Enter') sendMessage(); });
$('attachBtn').addEventListener('click',()=>$('fileInput').click());
$('fileInput').addEventListener('change', onFile);
$('cancelReplyBtn').addEventListener('click', cancelReply);
$('startVideoBtn').addEventListener('click', startVideo);
$('shareScreenBtn').addEventListener('click', startShare);
$('hdrVideoBtn').addEventListener('click', startVideo);
$('hdrShareBtn').addEventListener('click', startShare);
$('toggleAudioBtn').addEventListener('click', toggleAudio);
$('toggleVideoBtn').addEventListener('click', toggleVideo);
$('endMediaBtn').addEventListener('click', endMedia);
$('disconnectBtn').addEventListener('click', disconnect);
if ($('hdrDisconnectBtn')) {
$('hdrDisconnectBtn').addEventListener('click', disconnect);
}
$('copyBtn').addEventListener('click', copyRoom);
document.addEventListener('click', (e) => {
if (!e.target.closest('.pc-msg-action-react') && !e.target.closest('.pc-emoji-selector')) {
closeEmojiSelector();
}
});
// Mobile Safari Autoplay Workaround
const resumeRemoteVideo = () => {
const rv = $('remoteVideo');
if (rv && rv.srcObject && rv.paused) {
rv.play().catch(() => {});
}
};
document.addEventListener('click', resumeRemoteVideo);
document.addEventListener('touchstart', resumeRemoteVideo);
initHost();
})();