/* 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 = `