/* QuickMeet Video Call App - WebRTC Client */ // ── State ──────────────────────────────────────────────────────────────── let ws = null; let localStream = null; let screenStream = null; let myPeerId = null; let myName = "Guest"; let roomId = null; let micEnabled = true; let camEnabled = true; let screenSharing = false; let chatOpen = false; let recording = false; let mediaRecorder = null; let recordedChunks = []; let recordingStartTime = null; let recordingTimerInterval = null; let myRole = "participant"; let handRaised = false; let meetingStartTime = null; let meetingTimerInterval = null; let bgBlurEnabled = false; let bgBlurCanvas = null; let bgBlurCtx = null; let bgBlurStream = null; // Map of peer_id -> { pc: RTCPeerConnection, videoEl, tile, name } const peerConnections = {}; const ICE_SERVERS = [ { urls: "stun:stun.l.google.com:19302" }, { urls: "stun:stun1.l.google.com:19302" }, { urls: "stun:stun2.l.google.com:19302" }, ]; // ── Elements ───────────────────────────────────────────────────────────── const joinScreen = document.getElementById("joinScreen"); const callScreen = document.getElementById("callScreen"); const nameInput = document.getElementById("nameInput"); const roomInput = document.getElementById("roomInput"); const newMeetingBtn = document.getElementById("newMeetingBtn"); const joinBtn = document.getElementById("joinBtn"); const previewVideo = document.getElementById("previewVideo"); const previewPlaceholder = document.getElementById("previewPlaceholder"); const previewMic = document.getElementById("previewMic"); const previewCam = document.getElementById("previewCam"); const videoGrid = document.getElementById("videoGrid"); const localVideo = document.getElementById("localVideo"); const localVideoOff = document.getElementById("localVideoOff"); const localName = document.getElementById("localName"); const localMicIndicator = document.getElementById("localMicIndicator"); const micBtn = document.getElementById("micBtn"); const camBtn = document.getElementById("camBtn"); const screenBtn = document.getElementById("screenBtn"); const chatBtn = document.getElementById("chatBtn"); const leaveBtn = document.getElementById("leaveBtn"); const copyLinkBtn = document.getElementById("copyLinkBtn"); const roomInfo = document.getElementById("roomInfo"); const peerCount = document.getElementById("peerCount"); const chatPanel = document.getElementById("chatPanel"); const chatMessages = document.getElementById("chatMessages"); const chatInput = document.getElementById("chatInput"); const sendChatBtn = document.getElementById("sendChatBtn"); const closeChatBtn = document.getElementById("closeChatBtn"); const toast = document.getElementById("toast"); const recordBtn = document.getElementById("recordBtn"); // ── Init ───────────────────────────────────────────────────────────────── document.addEventListener("DOMContentLoaded", () => { // Check if URL has a room code const pathMatch = window.location.pathname.match(/^\/room\/([a-zA-Z0-9]+)/); if (pathMatch) { roomInput.value = pathMatch[1]; } // Restore name from localStorage const savedName = localStorage.getItem("quickmeet_name"); if (savedName) nameInput.value = savedName; startPreview(); setupJoinListeners(); }); // ── Camera Preview ─────────────────────────────────────────────────────── async function startPreview() { try { localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, }, }); previewVideo.srcObject = localStream; previewVideo.muted = true; // Always mute local preview previewPlaceholder.style.display = "none"; } catch (e) { console.warn("Could not access camera/mic:", e); previewPlaceholder.querySelector("p").textContent = "Camera not available"; } } // ── Join Screen Listeners ──────────────────────────────────────────────── function setupJoinListeners() { previewMic.addEventListener("click", () => { micEnabled = !micEnabled; previewMic.classList.toggle("active", micEnabled); if (localStream) { localStream.getAudioTracks().forEach(t => t.enabled = micEnabled); } }); previewCam.addEventListener("click", () => { camEnabled = !camEnabled; previewCam.classList.toggle("active", camEnabled); if (localStream) { localStream.getVideoTracks().forEach(t => t.enabled = camEnabled); } previewPlaceholder.style.display = camEnabled ? "none" : "flex"; }); newMeetingBtn.addEventListener("click", async () => { try { const resp = await fetch("/api/create-room", { method: "POST" }); const data = await resp.json(); joinRoom(data.room_id); } catch (e) { showToast("Failed to create room"); } }); joinBtn.addEventListener("click", () => { const code = roomInput.value.trim(); if (!code) { showToast("Please enter a room code"); return; } joinRoom(code); }); roomInput.addEventListener("keydown", (e) => { if (e.key === "Enter") joinBtn.click(); }); nameInput.addEventListener("keydown", (e) => { if (e.key === "Enter") newMeetingBtn.click(); }); } // ── Join Room ──────────────────────────────────────────────────────────── function joinRoom(id) { roomId = id; myName = nameInput.value.trim() || "Guest"; localStorage.setItem("quickmeet_name", myName); // Ensure we have a stream if (!localStream) { navigator.mediaDevices.getUserMedia({ video: true, audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, }, }) .then(stream => { localStream = stream; connectWebSocket(); }) .catch(() => { // Join without media connectWebSocket(); }); } else { connectWebSocket(); } } // ── WebSocket Connection ───────────────────────────────────────────────── function connectWebSocket() { const proto = window.location.protocol === "https:" ? "wss:" : "ws:"; ws = new WebSocket(`${proto}//${window.location.host}/ws`); ws.onopen = () => { ws.send(JSON.stringify({ action: "join", room_id: roomId, name: myName, })); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); handleSignal(msg); }; ws.onclose = () => { showToast("Disconnected from server"); }; ws.onerror = (err) => { console.error("WebSocket error:", err); }; } // ── Signal Handler ─────────────────────────────────────────────────────── async function handleSignal(msg) { console.log("[signal]", msg.action, msg); switch (msg.action) { case "joined": myPeerId = msg.peer_id; myRole = msg.role || "participant"; console.log("[me] My peer ID:", myPeerId, "role:", myRole); enterCallScreen(); for (const peer of msg.peers) { console.log("[init] Creating offer to existing peer:", peer.id, peer.name); await getOrCreatePeer(peer.id, peer.name); await sendOffer(peer.id); } break; case "peer-joined": showToast(`${msg.name} joined`); console.log("[peer-joined]", msg.peer_id, msg.name); getOrCreatePeer(msg.peer_id, msg.name); updatePeerCount(); updateParticipantList(); break; case "peer-left": removePeer(msg.peer_id); updatePeerCount(); updateParticipantList(); break; case "offer": await handleOffer(msg.from, msg.data); break; case "answer": await handleAnswer(msg.from, msg.data); break; case "ice-candidate": await handleIceCandidate(msg.from, msg.data); break; case "chat": addChatMessage(msg.name, msg.text, msg.time); if (!chatOpen) showToast(`${msg.name}: ${msg.text}`); break; case "error": showToast(msg.message); break; // ── Waiting room ──────────────────────────────────── case "waiting-room": showWaitingRoom(msg.message); break; case "waiting-room-update": updateWaitingList(msg.waiting); break; case "denied": showToast(msg.message); leaveCall(); break; // ── Hand raise ────────────────────────────────────── case "hand-raise": handleHandRaise(msg.peer_id, msg.name, msg.raised); break; case "all-hands-lowered": handleAllHandsLowered(); break; // ── Reactions ─────────────────────────────────────── case "reaction": showReaction(msg.emoji, msg.name); break; // ── Host controls ─────────────────────────────────── case "host-changed": if (msg.new_host === myPeerId) { myRole = "host"; showToast("You are now the host"); showHostControls(); } else { showToast(`${msg.name} is now the host`); } updateParticipantList(); break; case "muted-by-host": micEnabled = false; micBtn.classList.remove("active"); if (localStream) localStream.getAudioTracks().forEach(t => t.enabled = false); localMicIndicator.textContent = "🔇"; localMicIndicator.classList.add("muted"); showToast(msg.message); break; case "kicked": showToast(msg.message); leaveCall(); break; case "setting-changed": showToast(`${msg.setting.replace('_', ' ')} ${msg.value ? 'enabled' : 'disabled'}`); if (msg.setting === "waiting_room") { const toggle = document.getElementById("waitingRoomToggle"); if (toggle) toggle.checked = msg.value; } break; // ── Polls ─────────────────────────────────────────── case "poll-started": renderPoll(msg.poll); showToast("New poll started!"); break; case "poll-update": updatePollResults(msg.poll_id, msg.results, msg.total_votes); break; case "poll-ended": endPollDisplay(msg.poll_id, msg.results, msg.total_votes); break; // ── Whiteboard ────────────────────────────────────── case "whiteboard-sync": replayWhiteboardStrokes(msg.strokes); break; case "whiteboard-stroke": drawRemoteStroke(msg.stroke); break; case "whiteboard-clear": clearWhiteboardLocal(); break; // ── Breakout rooms ────────────────────────────────── case "breakout-started": showToast("Breakout rooms started!"); renderBreakoutActive(msg.rooms); break; case "breakout-ended": showToast("Breakout rooms ended"); hideBreakoutActive(); break; } } // ── Enter Call Screen ──────────────────────────────────────────────────── function enterCallScreen() { joinScreen.classList.remove("active"); callScreen.classList.add("active"); if (localStream) { localVideo.srcObject = localStream; localVideo.muted = true; } localVideoOff.style.display = camEnabled ? "none" : ""; localName.textContent = `${myName} (You)`; localMicIndicator.textContent = micEnabled ? "🎤" : "🔇"; localMicIndicator.classList.toggle("muted", !micEnabled); history.replaceState(null, "", `/room/${roomId}`); document.title = `QuickMeet - ${roomId}`; roomInfo.textContent = `Room: ${roomId}`; micBtn.classList.toggle("active", micEnabled); camBtn.classList.toggle("active", camEnabled); setupCallControls(); updateGridLayout(); updatePeerCount(); updateParticipantList(); // Start meeting timer meetingStartTime = Date.now(); meetingTimerInterval = setInterval(updateMeetingTimer, 1000); updateMeetingTimer(); // Show host controls if host if (myRole === "host") { showHostControls(); } } // ── Call Control Listeners ─────────────────────────────────────────────── function setupCallControls() { micBtn.addEventListener("click", toggleMic); camBtn.addEventListener("click", toggleCam); screenBtn.addEventListener("click", toggleScreenShare); recordBtn.addEventListener("click", toggleRecording); leaveBtn.addEventListener("click", leaveCall); // Chat chatBtn.addEventListener("click", () => { chatOpen = !chatOpen; chatPanel.classList.toggle("open", chatOpen); chatBtn.classList.toggle("active", chatOpen); closeSidePanels("chatPanel"); if (chatOpen) chatInput.focus(); }); closeChatBtn.addEventListener("click", () => { chatOpen = false; chatPanel.classList.remove("open"); chatBtn.classList.remove("active"); }); copyLinkBtn.addEventListener("click", () => { const url = `${window.location.origin}/room/${roomId}`; navigator.clipboard.writeText(url).then(() => { showToast("Invite link copied!"); }).catch(() => { showToast(url); }); }); sendChatBtn.addEventListener("click", sendChat); chatInput.addEventListener("keydown", (e) => { if (e.key === "Enter") sendChat(); }); // Hand raise document.getElementById("handBtn").addEventListener("click", toggleHandRaise); // Reactions document.querySelectorAll(".reaction-btn").forEach(btn => { btn.addEventListener("click", () => { if (ws) ws.send(JSON.stringify({ action: "reaction", emoji: btn.dataset.emoji })); }); }); // Participants panel document.getElementById("participantsBtn").addEventListener("click", () => { const panel = document.getElementById("participantsPanel"); const open = !panel.classList.contains("open"); closeSidePanels("participantsPanel"); panel.classList.toggle("open", open); document.getElementById("participantsBtn").classList.toggle("active", open); if (open) updateParticipantList(); }); document.getElementById("closeParticipantsBtn").addEventListener("click", () => { document.getElementById("participantsPanel").classList.remove("open"); document.getElementById("participantsBtn").classList.remove("active"); }); // Host controls document.getElementById("muteAllBtn").addEventListener("click", () => { if (ws) ws.send(JSON.stringify({ action: "mute-all" })); }); document.getElementById("lowerAllHandsBtn").addEventListener("click", () => { if (ws) ws.send(JSON.stringify({ action: "lower-all-hands" })); }); document.getElementById("waitingRoomToggle").addEventListener("change", (e) => { if (ws) ws.send(JSON.stringify({ action: "toggle-waiting-room", enabled: e.target.checked })); }); document.getElementById("lockMeetingToggle").addEventListener("change", (e) => { if (ws) ws.send(JSON.stringify({ action: "lock-meeting", locked: e.target.checked })); }); // Waiting room leave document.getElementById("waitingLeaveBtn").addEventListener("click", leaveCall); // Whiteboard document.getElementById("whiteboardBtn").addEventListener("click", () => { const panel = document.getElementById("whiteboardPanel"); const open = !panel.classList.contains("open"); closeSidePanels("whiteboardPanel"); panel.classList.toggle("open", open); if (open) initWhiteboard(); }); document.getElementById("closeWhiteboardBtn").addEventListener("click", () => { document.getElementById("whiteboardPanel").classList.remove("open"); }); // Polls document.getElementById("pollsBtn").addEventListener("click", () => { const panel = document.getElementById("pollsPanel"); const open = !panel.classList.contains("open"); closeSidePanels("pollsPanel"); panel.classList.toggle("open", open); if (open && myRole === "host") { document.getElementById("createPollSection").style.display = "block"; } }); document.getElementById("closePollsBtn").addEventListener("click", () => { document.getElementById("pollsPanel").classList.remove("open"); }); document.getElementById("addPollOption").addEventListener("click", () => { const container = document.getElementById("pollOptionsContainer"); const count = container.children.length + 1; const input = document.createElement("input"); input.type = "text"; input.className = "poll-option-input"; input.placeholder = `Option ${count}`; input.maxLength = 100; container.appendChild(input); }); document.getElementById("launchPollBtn").addEventListener("click", () => { const question = document.getElementById("pollQuestion").value.trim(); const options = [...document.querySelectorAll(".poll-option-input")] .map(i => i.value.trim()).filter(Boolean); if (!question || options.length < 2) { showToast("Need a question and at least 2 options"); return; } if (ws) ws.send(JSON.stringify({ action: "create-poll", question, options })); document.getElementById("pollQuestion").value = ""; document.querySelectorAll(".poll-option-input").forEach((i, idx) => { i.value = ""; if (idx >= 2) i.remove(); }); }); // Breakout rooms document.getElementById("breakoutBtn").addEventListener("click", () => { const panel = document.getElementById("breakoutPanel"); const open = !panel.classList.contains("open"); closeSidePanels("breakoutPanel"); panel.classList.toggle("open", open); if (open && myRole === "host") { document.getElementById("breakoutSetup").style.display = "block"; initBreakoutSetup(); } }); document.getElementById("closeBreakoutBtn").addEventListener("click", () => { document.getElementById("breakoutPanel").classList.remove("open"); }); document.getElementById("addBreakoutRoom").addEventListener("click", addBreakoutRoomRow); document.getElementById("startBreakoutBtn").addEventListener("click", startBreakout); document.getElementById("endBreakoutBtn").addEventListener("click", () => { if (ws) ws.send(JSON.stringify({ action: "end-breakout" })); }); // Background blur document.getElementById("bgBlurBtn").addEventListener("click", toggleBgBlur); } function toggleMic() { micEnabled = !micEnabled; micBtn.classList.toggle("active", micEnabled); if (localStream) { localStream.getAudioTracks().forEach(t => t.enabled = micEnabled); } localMicIndicator.textContent = micEnabled ? "🎤" : "🔇"; localMicIndicator.classList.toggle("muted", !micEnabled); } function toggleCam() { camEnabled = !camEnabled; camBtn.classList.toggle("active", camEnabled); if (localStream) { localStream.getVideoTracks().forEach(t => t.enabled = camEnabled); } localVideoOff.style.display = camEnabled ? "none" : ""; } async function toggleScreenShare() { if (screenSharing) { stopScreenShare(); return; } try { screenStream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false, }); screenSharing = true; screenBtn.classList.add("active"); const screenTrack = screenStream.getVideoTracks()[0]; screenTrack.onended = () => stopScreenShare(); // Replace video track in all peer connections for (const pid in peerConnections) { const pc = peerConnections[pid].pc; const sender = pc.getSenders().find(s => s.track && s.track.kind === "video"); if (sender) { sender.replaceTrack(screenTrack); } } // Show screen share locally localVideo.srcObject = screenStream; localVideoOff.style.display = "none"; showToast("Screen sharing started"); } catch (e) { console.warn("Screen share cancelled:", e); } } function stopScreenShare() { if (screenStream) { screenStream.getTracks().forEach(t => t.stop()); screenStream = null; } screenSharing = false; screenBtn.classList.remove("active"); // Restore camera track const camTrack = localStream ? localStream.getVideoTracks()[0] : null; for (const pid in peerConnections) { const pc = peerConnections[pid].pc; const sender = pc.getSenders().find(s => s.track && s.track.kind === "video"); if (sender && camTrack) { sender.replaceTrack(camTrack); } } localVideo.srcObject = localStream; localVideoOff.style.display = camEnabled ? "none" : ""; showToast("Screen sharing stopped"); } function leaveCall() { if (recording) stopRecording(); for (const pid in peerConnections) { peerConnections[pid].pc.close(); peerConnections[pid].tile.remove(); delete peerConnections[pid]; } if (ws) { ws.close(); ws = null; } if (screenStream) { screenStream.getTracks().forEach(t => t.stop()); screenStream = null; } if (bgBlurStream) { bgBlurStream.getTracks().forEach(t => t.stop()); bgBlurStream = null; } bgBlurEnabled = false; screenSharing = false; chatOpen = false; handRaised = false; myRole = "participant"; chatPanel.classList.remove("open"); document.querySelectorAll(".side-panel").forEach(p => p.classList.remove("open")); clearInterval(meetingTimerInterval); meetingTimerInterval = null; // Hide waiting room overlay document.getElementById("waitingRoomOverlay").style.display = "none"; callScreen.classList.remove("active"); joinScreen.classList.add("active"); history.replaceState(null, "", "/"); document.title = "QuickMeet - Video Calls"; if (localStream) { previewVideo.srcObject = localStream; } } // ── Recording ─────────────────────────────────────────────────────────── function toggleRecording() { if (recording) { stopRecording(); } else { startRecording(); } } function startRecording() { const audioCtx = new AudioContext(); const dest = audioCtx.createMediaStreamDestination(); // Mix local audio if (localStream) { const localAudioTracks = localStream.getAudioTracks(); if (localAudioTracks.length > 0) { const localSource = audioCtx.createMediaStreamSource( new MediaStream(localAudioTracks) ); localSource.connect(dest); } } // Mix remote audio from all peers for (const pid in peerConnections) { const remoteStream = peerConnections[pid].videoEl.srcObject; if (remoteStream) { const remoteTracks = remoteStream.getAudioTracks(); if (remoteTracks.length > 0) { const remoteSource = audioCtx.createMediaStreamSource( new MediaStream(remoteTracks) ); remoteSource.connect(dest); } } } // Capture the video grid as a canvas stream const gridEl = document.getElementById("videoGrid"); const canvas = document.createElement("canvas"); canvas.width = 1280; canvas.height = 720; const ctx = canvas.getContext("2d"); // Draw all video elements onto canvas at 30fps const drawInterval = setInterval(() => { ctx.fillStyle = "#f5f7fb"; ctx.fillRect(0, 0, canvas.width, canvas.height); const videos = gridEl.querySelectorAll("video"); const count = videos.length; if (count === 0) return; const cols = count <= 1 ? 1 : count <= 4 ? 2 : 3; const rows = Math.ceil(count / cols); const tileW = canvas.width / cols; const tileH = canvas.height / rows; videos.forEach((video, i) => { if (!video.srcObject || video.videoWidth === 0) return; const col = i % cols; const row = Math.floor(i / cols); const x = col * tileW; const y = row * tileH; const vw = video.videoWidth; const vh = video.videoHeight; const vAspect = vw / vh; const tAspect = tileW / tileH; let sx, sy, sw, sh; if (vAspect > tAspect) { sh = vh; sw = vh * tAspect; sx = (vw - sw) / 2; sy = 0; } else { sw = vw; sh = vw / tAspect; sx = 0; sy = (vh - sh) / 2; } ctx.drawImage(video, sx, sy, sw, sh, x + 2, y + 2, tileW - 4, tileH - 4); }); }, 1000 / 30); const canvasStream = canvas.captureStream(30); // Combine canvas video + mixed audio const combined = new MediaStream([ ...canvasStream.getVideoTracks(), ...dest.stream.getAudioTracks(), ]); const mimeType = MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus") ? "video/webm;codecs=vp9,opus" : "video/webm"; recordedChunks = []; mediaRecorder = new MediaRecorder(combined, { mimeType }); mediaRecorder.ondataavailable = (e) => { if (e.data.size > 0) recordedChunks.push(e.data); }; mediaRecorder.onstop = () => { clearInterval(drawInterval); audioCtx.close(); const blob = new Blob(recordedChunks, { type: mimeType }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19); a.href = url; a.download = `QuickMeet-${roomId}-${timestamp}.webm`; a.click(); URL.revokeObjectURL(url); showToast("Recording saved!"); }; mediaRecorder._drawInterval = drawInterval; mediaRecorder._audioCtx = audioCtx; mediaRecorder.start(1000); recording = true; recordBtn.classList.add("active"); recordBtn.classList.add("recording"); recordingStartTime = Date.now(); updateRecordingTimer(); recordingTimerInterval = setInterval(updateRecordingTimer, 1000); showToast("Recording started"); } function stopRecording() { if (mediaRecorder && mediaRecorder.state !== "inactive") { mediaRecorder.stop(); } recording = false; recordBtn.classList.remove("active"); recordBtn.classList.remove("recording"); clearInterval(recordingTimerInterval); const timerEl = document.getElementById("recordTimer"); if (timerEl) timerEl.remove(); showToast("Recording stopped — downloading..."); } function updateRecordingTimer() { const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000); const mins = String(Math.floor(elapsed / 60)).padStart(2, "0"); const secs = String(elapsed % 60).padStart(2, "0"); let timerEl = document.getElementById("recordTimer"); if (!timerEl) { timerEl = document.createElement("span"); timerEl.id = "recordTimer"; timerEl.className = "record-timer"; recordBtn.parentElement.insertBefore(timerEl, recordBtn.nextSibling); } timerEl.textContent = `${mins}:${secs}`; } function sendChat() { const text = chatInput.value.trim(); if (!text || !ws) return; ws.send(JSON.stringify({ action: "chat", text })); chatInput.value = ""; } // ── WebRTC Peer Connection ─────────────────────────────────────────────── function getOrCreatePeer(peerId, peerName) { // If we already have a connection for this peer, just update name if (peerConnections[peerId]) { if (peerName && peerName !== "Peer") { peerConnections[peerId].name = peerName; const nameEl = peerConnections[peerId].tile.querySelector(".tile-name"); if (nameEl) nameEl.textContent = peerName; } return peerConnections[peerId]; } console.log("[peer] Creating new peer connection for:", peerId, peerName); const pc = new RTCPeerConnection({ iceServers: ICE_SERVERS }); // Create video tile for remote peer const tile = document.createElement("div"); tile.className = "video-tile"; tile.dataset.peer = peerId; tile.innerHTML = `
👤
${escapeHtml(peerName || "Peer")} 🎤
`; videoGrid.appendChild(tile); const videoEl = tile.querySelector("video"); videoEl.muted = false; videoEl.volume = 1.0; const offOverlay = tile.querySelector(".video-off-overlay"); const conn = { pc, videoEl, tile, name: peerName, offOverlay }; peerConnections[peerId] = conn; // Add local tracks to peer connection if (localStream) { localStream.getTracks().forEach(track => { pc.addTrack(track, localStream); }); console.log("[peer] Added", localStream.getTracks().length, "local tracks for", peerId); } else { console.warn("[peer] No local stream to add tracks from"); } // Handle incoming tracks from remote peer pc.ontrack = (event) => { console.log("[track] Received", event.track.kind, "track from", peerId, "streams:", event.streams.length); // Use the first stream from the event if (event.streams && event.streams[0]) { videoEl.srcObject = event.streams[0]; } else { // Fallback: create a new MediaStream if (!videoEl.srcObject) { videoEl.srcObject = new MediaStream(); } videoEl.srcObject.addTrack(event.track); } offOverlay.style.display = "none"; // Force play to handle autoplay policy videoEl.play().catch(err => { console.warn("[track] Autoplay blocked for", peerId, err); }); }; // ICE candidates pc.onicecandidate = (event) => { if (event.candidate && ws) { ws.send(JSON.stringify({ action: "ice-candidate", target: peerId, data: event.candidate.toJSON(), })); } }; pc.onconnectionstatechange = () => { console.log("[peer]", peerId, "connection state:", pc.connectionState); if (pc.connectionState === "connected") { offOverlay.style.display = "none"; } if (pc.connectionState === "failed") { console.error("[peer]", peerId, "connection failed"); removePeer(peerId); } }; pc.oniceconnectionstatechange = () => { console.log("[peer]", peerId, "ICE state:", pc.iceConnectionState); if (pc.iceConnectionState === "disconnected" || pc.iceConnectionState === "failed") { removePeer(peerId); } }; updateGridLayout(); updatePeerCount(); return conn; } async function sendOffer(peerId) { const conn = peerConnections[peerId]; if (!conn) return; try { const offer = await conn.pc.createOffer({ offerToReceiveAudio: true, offerToReceiveVideo: true, }); await conn.pc.setLocalDescription(offer); console.log("[offer] Sending offer to", peerId, "state:", conn.pc.signalingState); ws.send(JSON.stringify({ action: "offer", target: peerId, data: conn.pc.localDescription.toJSON(), })); } catch (err) { console.error("[offer] Failed to create offer for", peerId, err); } } async function handleOffer(fromId, offerData) { const conn = getOrCreatePeer(fromId, null); const pc = conn.pc; try { console.log("[offer] Handling offer from", fromId, "signalingState:", pc.signalingState); await pc.setRemoteDescription(new RTCSessionDescription(offerData)); const answer = await pc.createAnswer(); await pc.setLocalDescription(answer); console.log("[answer] Sending answer to", fromId); ws.send(JSON.stringify({ action: "answer", target: fromId, data: pc.localDescription.toJSON(), })); } catch (err) { console.error("[offer] Failed to handle offer from", fromId, err); } } async function handleAnswer(fromId, answerData) { const conn = peerConnections[fromId]; if (!conn) { console.warn("[answer] No connection for", fromId); return; } try { console.log("[answer] Setting remote description from", fromId, "signalingState:", conn.pc.signalingState); await conn.pc.setRemoteDescription(new RTCSessionDescription(answerData)); } catch (err) { console.error("[answer] Failed to set answer from", fromId, err); } } async function handleIceCandidate(fromId, candidateData) { const conn = peerConnections[fromId]; if (!conn) return; try { await conn.pc.addIceCandidate(new RTCIceCandidate(candidateData)); } catch (e) { console.warn("[ice] Failed to add ICE candidate from", fromId, e); } } function removePeer(peerId) { const conn = peerConnections[peerId]; if (!conn) return; conn.pc.close(); conn.tile.remove(); delete peerConnections[peerId]; const name = conn.name || "Someone"; showToast(`${name} left`); updateGridLayout(); updatePeerCount(); } // ── Grid Layout ────────────────────────────────────────────────────────── function updateGridLayout() { const count = videoGrid.children.length; videoGrid.dataset.count = Math.min(count, 9); } function updatePeerCount() { const count = Object.keys(peerConnections).length + 1; // +1 for self peerCount.textContent = `${count} participant${count !== 1 ? "s" : ""}`; } // ── Chat ───────────────────────────────────────────────────────────────── function addChatMessage(name, text, time) { const div = document.createElement("div"); div.className = "chat-msg"; div.innerHTML = `${escapeHtml(name)}${time || ""}
${escapeHtml(text)}`; chatMessages.appendChild(div); chatMessages.scrollTop = chatMessages.scrollHeight; } // ── Helpers ────────────────────────────────────────────────────────────── function escapeHtml(str) { const div = document.createElement("div"); div.textContent = str || ""; return div.innerHTML; } function showToast(message) { toast.textContent = message; toast.classList.add("visible"); setTimeout(() => toast.classList.remove("visible"), 3000); } // ═══════════════════════════════════════════════════════════════════════════ // NEW ZOOM-LIKE FEATURES // ═══════════════════════════════════════════════════════════════════════════ // ── Side Panel Helper ─────────────────────────────────────────────────── function closeSidePanels(except) { const panels = ["chatPanel", "participantsPanel", "whiteboardPanel", "pollsPanel", "breakoutPanel"]; panels.forEach(id => { if (id !== except) document.getElementById(id).classList.remove("open"); }); if (except !== "chatPanel") { chatOpen = false; chatBtn.classList.remove("active"); } } // ── Meeting Timer ─────────────────────────────────────────────────────── function updateMeetingTimer() { if (!meetingStartTime) return; const elapsed = Math.floor((Date.now() - meetingStartTime) / 1000); const h = Math.floor(elapsed / 3600); const m = String(Math.floor((elapsed % 3600) / 60)).padStart(2, "0"); const s = String(elapsed % 60).padStart(2, "0"); const el = document.getElementById("meetingTimer"); if (el) el.textContent = h > 0 ? `${h}:${m}:${s}` : `${m}:${s}`; } // ── Host Controls ─────────────────────────────────────────────────────── function showHostControls() { const el = document.getElementById("hostControls"); if (el) el.style.display = "flex"; const createPoll = document.getElementById("createPollSection"); if (createPoll) createPoll.style.display = "block"; const breakout = document.getElementById("breakoutSetup"); if (breakout) breakout.style.display = "block"; } // ── Hand Raise ────────────────────────────────────────────────────────── function toggleHandRaise() { handRaised = !handRaised; const btn = document.getElementById("handBtn"); btn.classList.toggle("raised", handRaised); document.getElementById("localHand").style.display = handRaised ? "" : "none"; if (ws) ws.send(JSON.stringify({ action: "hand-raise", raised: handRaised })); showToast(handRaised ? "Hand raised" : "Hand lowered"); } function handleHandRaise(peerId, name, raised) { const conn = peerConnections[peerId]; if (conn) { let indicator = conn.tile.querySelector(".hand-indicator"); if (!indicator) { indicator = document.createElement("div"); indicator.className = "hand-indicator"; indicator.textContent = "✋"; conn.tile.appendChild(indicator); } indicator.style.display = raised ? "" : "none"; conn.hand = raised; } if (raised) showToast(`${name} raised hand ✋`); updateParticipantList(); } function handleAllHandsLowered() { handRaised = false; document.getElementById("handBtn").classList.remove("raised"); document.getElementById("localHand").style.display = "none"; for (const pid in peerConnections) { peerConnections[pid].hand = false; const indicator = peerConnections[pid].tile.querySelector(".hand-indicator"); if (indicator) indicator.style.display = "none"; } showToast("All hands lowered"); updateParticipantList(); } // ── Reactions ─────────────────────────────────────────────────────────── function showReaction(emoji, name) { const overlay = document.getElementById("reactionsOverlay"); const el = document.createElement("div"); el.className = "reaction-float"; el.textContent = emoji; el.style.left = Math.random() * 250 + "px"; overlay.appendChild(el); setTimeout(() => el.remove(), 2600); } // ── Waiting Room ──────────────────────────────────────────────────────── function showWaitingRoom(message) { joinScreen.classList.remove("active"); callScreen.classList.add("active"); document.getElementById("waitingRoomOverlay").style.display = "flex"; document.getElementById("waitingRoomMsg").textContent = message; } function updateWaitingList(waiting) { const container = document.getElementById("waitingListContent"); const wrapper = document.getElementById("waitingList"); if (!waiting || !waiting.length) { wrapper.style.display = "none"; return; } wrapper.style.display = "block"; container.innerHTML = waiting.map(w => `
${escapeHtml(w.name)}
`).join(""); } function admitPeer(targetId) { if (ws) ws.send(JSON.stringify({ action: "admit-peer", target: targetId })); } function denyPeer(targetId) { if (ws) ws.send(JSON.stringify({ action: "deny-peer", target: targetId })); } // ── Participant List ──────────────────────────────────────────────────── function updateParticipantList() { const list = document.getElementById("participantList"); if (!list) return; const count = Object.keys(peerConnections).length + 1; document.getElementById("participantCountTitle").textContent = `In Meeting (${count})`; let html = `
${escapeHtml(myName)} (You) ${myRole === "host" ? 'Host' : ""} ${handRaised ? '✋' : ""}
`; for (const pid in peerConnections) { const c = peerConnections[pid]; const isHost = false; // Server tracks this, simplified here html += `
${escapeHtml(c.name || "Peer")} ${c.hand ? '✋' : ""} ${myRole === "host" ? ` ` : ""}
`; } list.innerHTML = html; } function mutePeer(targetId) { if (ws) ws.send(JSON.stringify({ action: "mute-peer", target: targetId })); } function kickPeer(targetId) { if (ws) ws.send(JSON.stringify({ action: "kick-peer", target: targetId })); } // ── Polls ─────────────────────────────────────────────────────────────── const activePolls = {}; function renderPoll(poll) { activePolls[poll.id] = poll; const container = document.getElementById("activePollsList"); let card = document.getElementById(`poll-${poll.id}`); if (!card) { card = document.createElement("div"); card.id = `poll-${poll.id}`; card.className = "poll-card"; container.prepend(card); } const total = poll.total_votes || 0; const results = poll.results || poll.options.map(() => 0); card.innerHTML = `

${escapeHtml(poll.question)}

${poll.options.map((opt, i) => { const count = results[i] || 0; const pct = total > 0 ? Math.round(count / total * 100) : 0; const voted = poll.my_vote === i; return `
${escapeHtml(opt)}
${pct}%
`; }).join("")}
${total} vote${total !== 1 ? 's' : ''}
${myRole === "host" && poll.active ? `` : ""} ${!poll.active ? '
Poll ended
' : ""} `; } function votePoll(pollId, choice) { if (ws) ws.send(JSON.stringify({ action: "vote-poll", poll_id: pollId, choice })); if (activePolls[pollId]) activePolls[pollId].my_vote = choice; } function endPoll(pollId) { if (ws) ws.send(JSON.stringify({ action: "end-poll", poll_id: pollId })); } function updatePollResults(pollId, results, totalVotes) { if (activePolls[pollId]) { activePolls[pollId].results = results; activePolls[pollId].total_votes = totalVotes; renderPoll(activePolls[pollId]); } } function endPollDisplay(pollId, results, totalVotes) { if (activePolls[pollId]) { activePolls[pollId].active = false; activePolls[pollId].results = results; activePolls[pollId].total_votes = totalVotes; renderPoll(activePolls[pollId]); } } // ── Whiteboard ────────────────────────────────────────────────────────── let wbDrawing = false; let wbCurrentStroke = null; let wbEraser = false; function initWhiteboard() { const canvas = document.getElementById("whiteboardCanvas"); if (canvas._initialized) return; canvas._initialized = true; const ctx = canvas.getContext("2d"); ctx.lineCap = "round"; ctx.lineJoin = "round"; canvas.addEventListener("pointerdown", (e) => { wbDrawing = true; const rect = canvas.getBoundingClientRect(); const x = (e.clientX - rect.left) / rect.width * canvas.width; const y = (e.clientY - rect.top) / rect.height * canvas.height; const color = wbEraser ? "#ffffff" : document.getElementById("wbColor").value; const width = wbEraser ? 20 : parseInt(document.getElementById("wbSize").value); wbCurrentStroke = { points: [[x, y]], color, width }; ctx.strokeStyle = color; ctx.lineWidth = width; ctx.beginPath(); ctx.moveTo(x, y); }); canvas.addEventListener("pointermove", (e) => { if (!wbDrawing || !wbCurrentStroke) return; const rect = canvas.getBoundingClientRect(); const x = (e.clientX - rect.left) / rect.width * canvas.width; const y = (e.clientY - rect.top) / rect.height * canvas.height; wbCurrentStroke.points.push([x, y]); const ctx2 = canvas.getContext("2d"); ctx2.strokeStyle = wbCurrentStroke.color; ctx2.lineWidth = wbCurrentStroke.width; ctx2.lineTo(x, y); ctx2.stroke(); }); const endDraw = () => { if (wbDrawing && wbCurrentStroke && wbCurrentStroke.points.length > 1) { if (ws) ws.send(JSON.stringify({ action: "whiteboard-stroke", stroke: wbCurrentStroke })); } wbDrawing = false; wbCurrentStroke = null; }; canvas.addEventListener("pointerup", endDraw); canvas.addEventListener("pointerleave", endDraw); document.getElementById("wbEraser").addEventListener("click", () => { wbEraser = !wbEraser; document.getElementById("wbEraser").classList.toggle("active", wbEraser); canvas.style.cursor = wbEraser ? "cell" : "crosshair"; }); document.getElementById("wbClear").addEventListener("click", () => { if (ws) ws.send(JSON.stringify({ action: "whiteboard-clear" })); clearWhiteboardLocal(); }); } function drawRemoteStroke(stroke) { const canvas = document.getElementById("whiteboardCanvas"); const ctx = canvas.getContext("2d"); if (!stroke.points || stroke.points.length < 2) return; ctx.strokeStyle = stroke.color || "#000"; ctx.lineWidth = stroke.width || 3; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.beginPath(); ctx.moveTo(stroke.points[0][0], stroke.points[0][1]); for (let i = 1; i < stroke.points.length; i++) { ctx.lineTo(stroke.points[i][0], stroke.points[i][1]); } ctx.stroke(); } function replayWhiteboardStrokes(strokes) { const canvas = document.getElementById("whiteboardCanvas"); const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); for (const stroke of strokes) drawRemoteStroke(stroke); } function clearWhiteboardLocal() { const canvas = document.getElementById("whiteboardCanvas"); const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); } // ── Breakout Rooms ────────────────────────────────────────────────────── function initBreakoutSetup() { const container = document.getElementById("breakoutRoomsList"); if (container.children.length === 0) { addBreakoutRoomRow(); addBreakoutRoomRow(); } } function addBreakoutRoomRow() { const container = document.getElementById("breakoutRoomsList"); const idx = container.children.length + 1; const row = document.createElement("div"); row.className = "breakout-room-row"; row.innerHTML = `
`; container.appendChild(row); updateBreakoutAssignments(); } function updateBreakoutAssignments() { const peersInCall = Object.entries(peerConnections).map(([id, c]) => ({ id, name: c.name || "Peer" })); const rows = document.querySelectorAll("#breakoutRoomsList .breakout-room-row"); rows.forEach(row => { const peersDiv = row.querySelector(".br-peers"); peersDiv.innerHTML = peersInCall.map(p => `${escapeHtml(p.name)}` ).join(""); }); } function startBreakout() { const rows = document.querySelectorAll("#breakoutRoomsList .breakout-room-row"); const breakoutRooms = []; rows.forEach(row => { const name = row.querySelector("input").value.trim() || "Room"; const assignedPeers = [...row.querySelectorAll(".br-peer-chip.assigned")].map(el => el.dataset.pid); breakoutRooms.push({ name, peers: assignedPeers }); }); if (ws) ws.send(JSON.stringify({ action: "create-breakout", rooms: breakoutRooms })); } function renderBreakoutActive(rooms) { const setup = document.getElementById("breakoutSetup"); const active = document.getElementById("breakoutActive"); const list = document.getElementById("breakoutActiveList"); setup.style.display = "none"; active.style.display = "block"; list.innerHTML = Object.entries(rooms).map(([rid, r]) => `
${escapeHtml(r.name)}
${r.peers.map(pid => { const name = peerConnections[pid]?.name || (pid === myPeerId ? myName : "Peer"); return `${escapeHtml(name)}`; }).join("")}
`).join(""); } function hideBreakoutActive() { document.getElementById("breakoutSetup").style.display = myRole === "host" ? "block" : "none"; document.getElementById("breakoutActive").style.display = "none"; } // ── Background Blur ───────────────────────────────────────────────────── function toggleBgBlur() { bgBlurEnabled = !bgBlurEnabled; const btn = document.getElementById("bgBlurBtn"); showToast(bgBlurEnabled ? "Background blur on" : "Background blur off"); if (bgBlurEnabled) { if (!localStream) return; const videoTrack = localStream.getVideoTracks()[0]; if (!videoTrack) return; bgBlurCanvas = document.createElement("canvas"); bgBlurCanvas.width = 640; bgBlurCanvas.height = 480; bgBlurCtx = bgBlurCanvas.getContext("2d"); const tempVideo = document.createElement("video"); tempVideo.srcObject = new MediaStream([videoTrack]); tempVideo.muted = true; tempVideo.play(); const draw = () => { if (!bgBlurEnabled) return; bgBlurCtx.filter = "blur(10px)"; bgBlurCtx.drawImage(tempVideo, 0, 0, bgBlurCanvas.width, bgBlurCanvas.height); bgBlurCtx.filter = "none"; // Draw center region sharp (person approximation) const cx = bgBlurCanvas.width * 0.15; const cy = bgBlurCanvas.height * 0.05; const cw = bgBlurCanvas.width * 0.7; const ch = bgBlurCanvas.height * 0.9; bgBlurCtx.drawImage(tempVideo, cx, cy, cw, ch, cx, cy, cw, ch); requestAnimationFrame(draw); }; draw(); bgBlurStream = bgBlurCanvas.captureStream(30); const blurTrack = bgBlurStream.getVideoTracks()[0]; // Replace in all peer connections for (const pid in peerConnections) { const sender = peerConnections[pid].pc.getSenders().find(s => s.track?.kind === "video"); if (sender) sender.replaceTrack(blurTrack); } localVideo.srcObject = bgBlurStream; } else { // Restore original camera const camTrack = localStream ? localStream.getVideoTracks()[0] : null; for (const pid in peerConnections) { const sender = peerConnections[pid].pc.getSenders().find(s => s.track?.kind === "video"); if (sender && camTrack) sender.replaceTrack(camTrack); } localVideo.srcObject = localStream; if (bgBlurStream) { bgBlurStream.getTracks().forEach(t => t.stop()); bgBlurStream = null; } } }