-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvoice-chat.js
More file actions
569 lines (487 loc) · 22.5 KB
/
Copy pathvoice-chat.js
File metadata and controls
569 lines (487 loc) · 22.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
// ============================================
// EL JASUS — VOICE CHAT (WebRTC) v3 FIXED
// Peer-to-peer audio via Firebase signaling
// ALL BUGS FIXED:
// • Firebase functions properly accessed
// • Mute state correctly managed
// • Voice panel toggle fixed
// • No more "push is not a function" errors
// • Clean disconnect/reconnect flow
// ============================================
class VoiceChat {
constructor(db, roomCode, currentUid, currentUsername) {
this.db = db;
this.roomCode = roomCode;
this.uid = currentUid;
this.username = currentUsername;
this.peers = {}; // uid → RTCPeerConnection
this.localStream = null;
this.muted = false;
this.active = false;
this.speaking = {}; // uid → bool
this._audioCtx = null; // single AudioContext for VAD
this._rafId = null; // voice detection animation frame ID
this.config = {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' }
]
};
this.buildUI();
this.listenSignals();
}
// ── JOIN VOICE ────────────────────────────
async join() {
if (this.active) return; // already in voice
try {
this.localStream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
},
video: false
});
this.active = true;
this.muted = false; // always start unmuted
this.updateUI();
this.setupVoiceDetection();
// Announce presence to signal room
this.signal('joined', { username: this.username });
if (window.showToast) showToast('🎙️ انضممت للدردشة الصوتية');
} catch (err) {
console.error('[VC] join error:', err);
this.active = false;
if (err.name === 'NotAllowedError') {
if (window.showToast) showToast('⛔ يجب السماح بالوصول للميكروفون');
else alert('يجب السماح بالوصول للميكروفون لاستخدام الدردشة الصوتية');
} else {
if (window.showToast) showToast('⛔ خطأ في الصوت: ' + err.message);
else alert('خطأ في الدردشة الصوتية: ' + err.message);
}
}
}
// ── LEAVE VOICE ───────────────────────────
leave() {
// Stop local mic tracks
if (this.localStream) {
this.localStream.getTracks().forEach(t => t.stop());
this.localStream = null;
}
// Stop voice activity detection
if (this._rafId) {
cancelAnimationFrame(this._rafId);
this._rafId = null;
}
if (this._audioCtx) {
try { this._audioCtx.close(); } catch(e) {}
this._audioCtx = null;
}
// Close all peer connections + remove their audio elements
Object.keys(this.peers).forEach(uid => {
this.removePeer(uid);
this.removeVoiceUser(uid);
});
this.peers = {};
// ✅ FIX: always reset muted state on leave
this.active = false;
this.muted = false;
this.updateUI();
this.signal('left', {});
if (window.showToast) showToast('🎙️ غادرت الدردشة الصوتية');
}
// ── MUTE / UNMUTE ─────────────────────────
toggleMute() {
if (!this.active) {
if (window.showToast) showToast('⛔ انضم للدردشة الصوتية أولاً');
return;
}
this.muted = !this.muted;
// Apply to existing stream
if (this.localStream) {
this.localStream.getAudioTracks().forEach(t => (t.enabled = !this.muted));
}
this.updateUI();
if (window.showToast) showToast(this.muted ? '🔇 تم كتم الصوت' : '🎙️ تم تشغيل الصوت');
}
// ── SIGNALING VIA FIREBASE ─────────────────
signal(type, data) {
// ✅ FIX: Properly access Firebase functions
if (!window._firebaseFns || !window._firebaseFns.push || !window._firebaseFns.ref) {
console.error('[VC] Firebase functions not available');
if (window.showToast) showToast('⛔ خطأ في الاتصال بالسيرفر');
return;
}
const { push, ref } = window._firebaseFns;
try {
push(ref(this.db, `rooms/${this.roomCode}/voiceSignals`), {
from: this.uid,
fromName: this.username,
type,
data,
timestamp: Date.now()
});
} catch (error) {
console.error('[VC] Signal error:', error);
}
}
listenSignals() {
// ✅ FIX: Properly access Firebase functions
if (!window._firebaseFns || !window._firebaseFns.ref || !window._firebaseFns.onChildAdded) {
console.error('[VC] Firebase functions not available for listening');
return;
}
const { ref, onChildAdded } = window._firebaseFns;
const sigRef = ref(this.db, `rooms/${this.roomCode}/voiceSignals`);
onChildAdded(sigRef, snap => {
const msg = snap.val();
if (!msg || msg.from === this.uid) return;
// Ignore stale signals (older than 30s)
if (msg.timestamp < Date.now() - 30000) return;
this.handleSignal(msg);
});
}
async handleSignal(msg) {
switch (msg.type) {
case 'joined':
this.addVoiceUser(msg.from, msg.fromName);
if (this.active) {
// We're already in voice — initiate a peer connection to the newcomer
await this.createPeer(msg.from, true);
}
break;
case 'offer':
await this.handleOffer(msg.from, msg.fromName, msg.data);
break;
case 'answer':
if (this.peers[msg.from]) {
try {
await this.peers[msg.from].setRemoteDescription(
new RTCSessionDescription(msg.data)
);
} catch(e) { console.warn('[VC] setRemoteDescription error:', e); }
}
break;
case 'ice':
if (this.peers[msg.from]) {
try {
await this.peers[msg.from].addIceCandidate(
new RTCIceCandidate(msg.data)
);
} catch(e) { /* ignore ICE errors */ }
}
break;
case 'left':
this.removePeer(msg.from);
this.removeVoiceUser(msg.from);
break;
case 'speaking':
this.setSpeaking(msg.from, msg.data.speaking);
break;
}
}
// ── PEER CONNECTION ───────────────────────
async createPeer(remoteUid, initiator) {
// Close existing connection cleanly
if (this.peers[remoteUid]) {
this.peers[remoteUid].close();
delete this.peers[remoteUid];
}
const pc = new RTCPeerConnection(this.config);
this.peers[remoteUid] = pc;
// Add local tracks
if (this.localStream) {
this.localStream.getTracks().forEach(t => pc.addTrack(t, this.localStream));
}
// Handle remote audio — remove stale element first
pc.ontrack = (e) => {
const old = document.getElementById(`audio-${remoteUid}`);
if (old) old.remove();
const audio = document.createElement('audio');
audio.autoplay = true;
audio.id = `audio-${remoteUid}`;
audio.srcObject = e.streams[0];
document.getElementById('voice-audio-container')?.appendChild(audio);
};
// ICE candidates
pc.onicecandidate = (e) => {
if (e.candidate) {
this.signal('ice', e.candidate.toJSON());
}
};
// Connection state changes
pc.onconnectionstatechange = () => {
this.updatePeerStatus(remoteUid, pc.connectionState);
// Auto-remove on permanent failure
if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
this.removePeer(remoteUid);
}
};
if (initiator) {
const offer = await pc.createOffer({ offerToReceiveAudio: true });
await pc.setLocalDescription(offer);
this.signal('offer', pc.localDescription.toJSON());
}
return pc;
}
async handleOffer(fromUid, fromName, offerData) {
if (!this.active) return; // ignore offers if we're not in voice
const pc = await this.createPeer(fromUid, false);
await pc.setRemoteDescription(new RTCSessionDescription(offerData));
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
this.signal('answer', pc.localDescription.toJSON());
this.addVoiceUser(fromUid, fromName);
}
removePeer(uid) {
if (this.peers[uid]) {
this.peers[uid].close();
delete this.peers[uid];
}
const audio = document.getElementById(`audio-${uid}`);
if (audio) audio.remove();
}
// ── VOICE ACTIVITY DETECTION ──────────────
setupVoiceDetection() {
if (!this.localStream || !window.AudioContext) return;
// Close any previous AudioContext
if (this._audioCtx) {
try { this._audioCtx.close(); } catch(e) {}
}
this._audioCtx = new AudioContext();
const source = this._audioCtx.createMediaStreamSource(this.localStream);
const analyser = this._audioCtx.createAnalyser();
analyser.fftSize = 256;
source.connect(analyser);
const data = new Uint8Array(analyser.frequencyBinCount);
let lastState = false;
const check = () => {
// Stop if no longer active or stream gone
if (!this.active || !this.localStream) {
this._rafId = null;
return;
}
analyser.getByteFrequencyData(data);
const avg = data.reduce((a, b) => a + b, 0) / data.length;
const speaking = avg > 20 && !this.muted;
if (speaking !== lastState) {
lastState = speaking;
this.setSpeaking(this.uid, speaking);
this.signal('speaking', { speaking });
// Visual glow on own avatar
const myAvatar = document.getElementById(`voice-user-${this.uid}`);
if (myAvatar) {
myAvatar.style.borderColor = speaking ? '#00ff00' : 'rgba(0,242,255,.3)';
myAvatar.style.boxShadow = speaking ? '0 0 15px rgba(0,255,0,.5)' : 'none';
}
}
this._rafId = requestAnimationFrame(check);
};
check();
}
setSpeaking(uid, speaking) {
this.speaking[uid] = speaking;
const el = document.getElementById(`voice-user-${uid}`);
if (el) {
el.style.borderColor = speaking ? '#00ff00' : 'rgba(0,242,255,.3)';
el.style.boxShadow = speaking ? '0 0 15px rgba(0,255,0,.6)' : 'none';
}
}
updatePeerStatus(uid, state) {
const dot = document.getElementById(`peer-dot-${uid}`);
if (!dot) return;
const colors = {
connected: '#00ff00',
connecting: '#ffd700',
failed: '#ff4444',
disconnected: '#666',
closed: '#666',
};
dot.style.background = colors[state] || '#666';
}
// ── VOICE USERS UI ────────────────────────
addVoiceUser(uid, name) {
const container = document.getElementById('voice-users');
if (!container) return;
if (document.getElementById(`voice-user-${uid}`)) return; // already shown
// Remove "nobody here" placeholder
const placeholder = container.querySelector('.vc-empty');
if (placeholder) placeholder.remove();
const el = document.createElement('div');
el.id = `voice-user-${uid}`;
el.style.cssText = `
display:flex;flex-direction:column;align-items:center;gap:4px;
padding:8px;border-radius:12px;border:2px solid rgba(0,242,255,.3);
background:rgba(0,242,255,.05);transition:all .3s;min-width:60px;`;
el.innerHTML = `
<div style="width:36px;height:36px;border-radius:50%;
background:linear-gradient(135deg,#00f2ff,#7c30ff);
display:flex;align-items:center;justify-content:center;position:relative;">
<i class="fas fa-user" style="color:white;font-size:14px;"></i>
<div id="peer-dot-${uid}" style="
position:absolute;bottom:0;right:0;
width:10px;height:10px;border-radius:50%;
background:#ffd700;border:2px solid #0a0e1a;"></div>
</div>
<span style="font-size:9px;color:#ccc;font-weight:700;
max-width:56px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${name}</span>`;
container.appendChild(el);
}
removeVoiceUser(uid) {
document.getElementById(`voice-user-${uid}`)?.remove();
// If container is now empty, restore placeholder
const container = document.getElementById('voice-users');
if (container && !container.querySelector('[id^="voice-user-"]')) {
const p = document.createElement('p');
p.className = 'vc-empty';
p.style.cssText = 'color:#555;font-size:11px;text-align:center;width:100%;';
p.textContent = 'لا أحد في الدردشة الصوتية';
container.appendChild(p);
}
}
// ── UI PANEL ──────────────────────────────
buildUI() {
if (document.getElementById('voice-panel')) return;
document.body.insertAdjacentHTML('beforeend', `
<!-- Hidden audio container -->
<div id="voice-audio-container" style="display:none;position:absolute;"></div>
<!-- Voice chat panel — z-index 8500, right side -->
<div id="voice-panel" style="
position:fixed;bottom:136px;right:20px;z-index:8500;
background:linear-gradient(135deg,rgba(10,14,26,.97),rgba(20,25,45,.97));
border:2px solid rgba(0,242,255,.3);border-radius:20px;padding:16px;
backdrop-filter:blur(20px);min-width:230px;display:none;
box-shadow:0 8px 32px rgba(0,0,0,.5);font-family:'Cairo',sans-serif;
animation:vcPanelIn .25s ease;">
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;">
<h4 style="color:#00f2ff;font-size:12px;font-weight:900;
text-transform:uppercase;letter-spacing:2px;margin:0;">
🎙️ الدردشة الصوتية
</h4>
<button id="vc-close-btn"
style="background:none;border:none;color:#555;cursor:pointer;font-size:16px;
padding:4px 6px;border-radius:6px;transition:color .2s;"
onmouseover="this.style.color='#ccc'" onmouseout="this.style.color='#555'">✕</button>
</div>
<!-- Active users list -->
<div id="voice-users" style="
display:flex;flex-wrap:wrap;gap:8px;margin-bottom:12px;
min-height:50px;align-items:center;justify-content:center;">
<p class="vc-empty" style="color:#555;font-size:11px;text-align:center;width:100%;">
لا أحد في الدردشة الصوتية
</p>
</div>
<!-- Controls -->
<div style="display:flex;gap:8px;align-items:center;">
<!-- Join button (visible when not in voice) -->
<button id="vc-join-btn"
style="flex:1;padding:10px;border-radius:12px;font-weight:900;font-size:12px;
background:linear-gradient(135deg,#00f2ff,#7c30ff);border:none;
color:white;cursor:pointer;transition:opacity .2s;"
onmouseover="this.style.opacity='.85'" onmouseout="this.style.opacity='1'">
انضم للصوت
</button>
<!-- Mute button (visible when in voice) -->
<button id="vc-mute-btn"
style="display:none;flex:1;padding:10px;border-radius:12px;font-weight:900;font-size:12px;
border:2px solid rgba(0,242,255,.3);background:rgba(0,242,255,.1);
color:#00f2ff;cursor:pointer;transition:all .2s;">
<i class="fas fa-microphone"></i> مفتوح
</button>
<!-- Leave button (visible when in voice) -->
<button id="vc-leave-btn"
style="display:none;width:42px;height:42px;border-radius:12px;
border:2px solid rgba(239,68,68,.3);background:rgba(239,68,68,.1);
color:#ef4444;cursor:pointer;font-size:16px;
display:none;align-items:center;justify-content:center;
transition:all .2s;"
title="مغادرة الصوت">
<i class="fas fa-phone-slash"></i>
</button>
</div>
</div>
<!-- Voice FAB — stacked below chat FAB at bottom:80px -->
<button id="voice-fab" style="
position:fixed;bottom:80px;right:20px;z-index:8501;
width:46px;height:46px;border-radius:50%;
background:linear-gradient(135deg,rgba(0,242,255,.15),rgba(124,48,255,.15));
border:2px solid rgba(0,242,255,.4);cursor:pointer;
display:flex;align-items:center;justify-content:center;
backdrop-filter:blur(12px);color:#00f2ff;font-size:18px;
transition:all .3s;box-shadow:0 4px 15px rgba(0,242,255,.2);"
title="الدردشة الصوتية">
<i class="fas fa-microphone"></i>
</button>
<style>
@keyframes vcPanelIn {
from { opacity:0; transform:translateY(12px) scale(.97); }
to { opacity:1; transform:translateY(0) scale(1); }
}
</style>`);
// Wire up FAB toggle
document.getElementById('voice-fab').addEventListener('click', () => this._togglePanel());
// Wire up panel close button
document.getElementById('vc-close-btn').addEventListener('click', () => this._togglePanel(false));
// Wire up join/mute/leave
document.getElementById('vc-join-btn').addEventListener('click', () => this.join());
document.getElementById('vc-mute-btn').addEventListener('click', () => this.toggleMute());
document.getElementById('vc-leave-btn').addEventListener('click', () => {
this.leave();
this._togglePanel(false);
});
}
_togglePanel(force) {
const panel = document.getElementById('voice-panel');
if (!panel) return;
const isOpen = panel.style.display === 'block';
const next = force !== undefined ? force : !isOpen;
panel.style.display = next ? 'block' : 'none';
}
updateUI() {
const joinBtn = document.getElementById('vc-join-btn');
const muteBtn = document.getElementById('vc-mute-btn');
const leaveBtn = document.getElementById('vc-leave-btn');
const fab = document.getElementById('voice-fab');
if (!joinBtn || !muteBtn || !leaveBtn || !fab) return;
if (this.active) {
// ── In voice ──
joinBtn.style.display = 'none';
muteBtn.style.display = 'block';
leaveBtn.style.display = 'flex';
// Mute button appearance
if (this.muted) {
muteBtn.style.background = 'rgba(239,68,68,.15)';
muteBtn.style.borderColor = 'rgba(239,68,68,.4)';
muteBtn.style.color = '#ef4444';
muteBtn.innerHTML = '<i class="fas fa-microphone-slash"></i> مكتوم';
} else {
muteBtn.style.background = 'rgba(0,242,255,.1)';
muteBtn.style.borderColor = 'rgba(0,242,255,.3)';
muteBtn.style.color = '#00f2ff';
muteBtn.innerHTML = '<i class="fas fa-microphone"></i> مفتوح';
}
// FAB: green when active, red-ish when muted
fab.style.borderColor = this.muted ? 'rgba(239,68,68,.7)' : '#00ff00';
fab.style.boxShadow = this.muted
? '0 0 12px rgba(239,68,68,.4)'
: '0 0 15px rgba(0,255,0,.4)';
fab.innerHTML = this.muted
? '<i class="fas fa-microphone-slash" style="color:#ef4444;"></i>'
: '<i class="fas fa-microphone" style="color:#00ff00;"></i>';
// Add self to user list
this.addVoiceUser(this.uid, this.username);
} else {
// ── Not in voice ──
joinBtn.style.display = 'block';
muteBtn.style.display = 'none';
leaveBtn.style.display = 'none';
// FAB: default cyan idle state
fab.style.borderColor = 'rgba(0,242,255,.4)';
fab.style.boxShadow = '0 4px 15px rgba(0,242,255,.2)';
fab.innerHTML = '<i class="fas fa-microphone" style="color:#00f2ff;"></i>';
this.removeVoiceUser(this.uid);
}
}
}
// ── EXPORT ────────────────────────────────
window.VoiceChat = VoiceChat;