quickmeet / server.py
SemantIQ's picture
Upload folder using huggingface_hub
5fcd816 verified
Raw History Blame
24.6 kB
"""
Video Call Server - WebRTC Signaling via WebSockets
Uses aiohttp for HTTP serving and WebSocket signaling.
Zoom-like features: waiting room, host controls, hand raise, reactions,
breakout rooms, polls, whiteboard, participant management.
"""
import os
import json
import uuid
import asyncio
from datetime import datetime
from pathlib import Path
from aiohttp import web
# ── Room State ────────────────────────────────────────────────────────────
# rooms = { room_id: { peer_id: websocket, ... } }
rooms: dict[str, dict[str, web.WebSocketResponse]] = {}
# peer metadata: { peer_id: { "name": ..., "room": ..., "role": ..., "hand": False } }
peers: dict[str, dict] = {}
# room metadata: { room_id: { "host": peer_id, "waiting_room_enabled": bool, "locked": bool, ... } }
room_meta: dict[str, dict] = {}
# waiting room: { room_id: { peer_id: { "ws": ws, "name": name } } }
waiting_rooms: dict[str, dict] = {}
# polls: { room_id: [{ "id": str, "question": str, "options": [...], "votes": {peer_id: idx}, "active": bool }] }
room_polls: dict[str, list] = {}
# whiteboard: { room_id: [ {type, points, color, width} ] }
room_whiteboards: dict[str, list] = {}
# breakout rooms: { room_id: { "rooms": { sub_id: { "name": str, "peers": [peer_id] } }, "active": bool } }
room_breakouts: dict[str, dict] = {}
STATIC_DIR = Path(__file__).parent / "static"
# ── HTTP Routes ───────────────────────────────────────────────────────────
async def index(request):
return web.FileResponse(STATIC_DIR / "index.html")
async def room_page(request):
return web.FileResponse(STATIC_DIR / "index.html")
async def create_room(request):
room_id = uuid.uuid4().hex[:8]
rooms[room_id] = {}
room_meta[room_id] = {
"host": None,
"waiting_room_enabled": False,
"locked": False,
"created": datetime.utcnow().isoformat(),
}
waiting_rooms[room_id] = {}
room_polls[room_id] = []
room_whiteboards[room_id] = []
room_breakouts[room_id] = {"rooms": {}, "active": False}
return web.json_response({"room_id": room_id})
async def room_info(request):
room_id = request.match_info["room_id"]
if room_id not in rooms:
rooms[room_id] = {}
peer_list = [
{"id": pid, "name": peers.get(pid, {}).get("name", "Unknown")}
for pid in rooms[room_id]
]
return web.json_response({"room_id": room_id, "peers": peer_list})
# ── WebSocket Signaling ──────────────────────────────────────────────────
async def websocket_handler(request):
ws = web.WebSocketResponse(heartbeat=30.0)
await ws.prepare(request)
peer_id = uuid.uuid4().hex[:12]
room_id = None
try:
async for msg in ws:
if msg.type == web.WSMsgType.TEXT:
data = json.loads(msg.data)
action = data.get("action")
if action == "join":
room_id = data.get("room_id", "").strip()
name = data.get("name", "Guest").strip()[:50] or "Guest"
if not room_id:
await ws.send_json({"action": "error", "message": "Room ID required"})
continue
if room_id not in rooms:
rooms[room_id] = {}
room_meta[room_id] = {
"host": None,
"waiting_room_enabled": False,
"locked": False,
"created": datetime.utcnow().isoformat(),
}
waiting_rooms[room_id] = {}
room_polls[room_id] = []
room_whiteboards[room_id] = []
room_breakouts[room_id] = {"rooms": {}, "active": False}
meta = room_meta[room_id]
# Check if room is locked
if meta.get("locked") and meta.get("host"):
await ws.send_json({"action": "error", "message": "This meeting is locked"})
continue
# Check waiting room
if meta.get("waiting_room_enabled") and meta.get("host") and meta["host"] != peer_id:
waiting_rooms[room_id][peer_id] = {"ws": ws, "name": name}
await ws.send_json({"action": "waiting-room", "message": "Please wait for the host to admit you"})
# Notify host
host_id = meta["host"]
if host_id in rooms[room_id]:
await rooms[room_id][host_id].send_json({
"action": "waiting-room-update",
"waiting": [
{"id": pid, "name": winfo["name"]}
for pid, winfo in waiting_rooms[room_id].items()
]
})
continue
# Assign host if first participant
is_host = not meta.get("host") or meta["host"] not in rooms.get(room_id, {})
if is_host:
meta["host"] = peer_id
# Register peer
rooms[room_id][peer_id] = ws
peers[peer_id] = {"name": name, "room": room_id, "role": "host" if is_host else "participant", "hand": False}
# Tell this peer about existing peers
existing = [
{"id": pid, "name": peers.get(pid, {}).get("name", "?"),
"role": peers.get(pid, {}).get("role", "participant"),
"hand": peers.get(pid, {}).get("hand", False)}
for pid in rooms[room_id] if pid != peer_id
]
await ws.send_json({
"action": "joined",
"peer_id": peer_id,
"peers": existing,
"room_id": room_id,
"role": "host" if is_host else "participant",
"waiting_room_enabled": meta.get("waiting_room_enabled", False),
})
# Notify others about the new peer
await broadcast(room_id, {
"action": "peer-joined",
"peer_id": peer_id,
"name": name,
"role": peers[peer_id]["role"],
}, exclude=peer_id)
# Send existing whiteboard state
if room_whiteboards.get(room_id):
await ws.send_json({
"action": "whiteboard-sync",
"strokes": room_whiteboards[room_id],
})
# Send active polls
active_polls = [p for p in room_polls.get(room_id, []) if p.get("active")]
if active_polls:
for poll in active_polls:
await ws.send_json({
"action": "poll-started",
"poll": _sanitize_poll(poll, peer_id),
})
print(f"[{room_id}] {name} ({peer_id}) joined as {'host' if is_host else 'participant'}. "
f"Room has {len(rooms[room_id])} peers.")
elif action in ("offer", "answer", "ice-candidate"):
target = data.get("target")
if target and room_id and target in rooms.get(room_id, {}):
target_ws = rooms[room_id][target]
await target_ws.send_json({
"action": action,
"from": peer_id,
"data": data.get("data"),
})
elif action == "chat":
text = data.get("text", "").strip()[:500]
if text and room_id:
name = peers.get(peer_id, {}).get("name", "?")
await broadcast(room_id, {
"action": "chat",
"from": peer_id,
"name": name,
"text": text,
"time": datetime.utcnow().strftime("%H:%M"),
})
# ── Hand Raise ────────────────────────────────────────
elif action == "hand-raise":
raised = data.get("raised", True)
if peer_id in peers:
peers[peer_id]["hand"] = raised
name = peers.get(peer_id, {}).get("name", "?")
await broadcast(room_id, {
"action": "hand-raise",
"peer_id": peer_id,
"name": name,
"raised": raised,
})
# ── Reactions ─────────────────────────────────────────
elif action == "reaction":
emoji = data.get("emoji", "")[:4]
if emoji and room_id:
name = peers.get(peer_id, {}).get("name", "?")
await broadcast(room_id, {
"action": "reaction",
"peer_id": peer_id,
"name": name,
"emoji": emoji,
})
# ── Waiting Room: Admit / Deny ────────────────────────
elif action == "admit-peer":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
target_id = data.get("target")
if target_id in waiting_rooms.get(room_id, {}):
winfo = waiting_rooms[room_id].pop(target_id)
target_ws = winfo["ws"]
target_name = winfo["name"]
rooms[room_id][target_id] = target_ws
peers[target_id] = {"name": target_name, "room": room_id, "role": "participant", "hand": False}
existing = [
{"id": pid, "name": peers.get(pid, {}).get("name", "?"),
"role": peers.get(pid, {}).get("role", "participant"),
"hand": peers.get(pid, {}).get("hand", False)}
for pid in rooms[room_id] if pid != target_id
]
await target_ws.send_json({
"action": "joined",
"peer_id": target_id,
"peers": existing,
"room_id": room_id,
"role": "participant",
"waiting_room_enabled": room_meta[room_id].get("waiting_room_enabled", False),
})
await broadcast(room_id, {
"action": "peer-joined",
"peer_id": target_id,
"name": target_name,
"role": "participant",
}, exclude=target_id)
elif action == "deny-peer":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
target_id = data.get("target")
if target_id in waiting_rooms.get(room_id, {}):
winfo = waiting_rooms[room_id].pop(target_id)
await winfo["ws"].send_json({"action": "denied", "message": "The host denied your request to join"})
# ── Host Controls ─────────────────────────────────────
elif action == "toggle-waiting-room":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
enabled = data.get("enabled", True)
room_meta[room_id]["waiting_room_enabled"] = enabled
await broadcast(room_id, {
"action": "setting-changed",
"setting": "waiting_room",
"value": enabled,
})
elif action == "lock-meeting":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
locked = data.get("locked", True)
room_meta[room_id]["locked"] = locked
await broadcast(room_id, {
"action": "setting-changed",
"setting": "locked",
"value": locked,
})
elif action == "mute-peer":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
target = data.get("target")
if target in rooms.get(room_id, {}):
await rooms[room_id][target].send_json({
"action": "muted-by-host",
"message": "The host muted you",
})
elif action == "kick-peer":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
target = data.get("target")
if target in rooms.get(room_id, {}):
await rooms[room_id][target].send_json({
"action": "kicked",
"message": "You have been removed from the meeting",
})
elif action == "mute-all":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
await broadcast(room_id, {
"action": "muted-by-host",
"message": "The host muted everyone",
}, exclude=peer_id)
elif action == "lower-all-hands":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
for pid in rooms.get(room_id, {}):
if pid in peers:
peers[pid]["hand"] = False
await broadcast(room_id, {"action": "all-hands-lowered"})
# ── Polls ─────────────────────────────────────────────
elif action == "create-poll":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
question = data.get("question", "").strip()[:200]
options = [o.strip()[:100] for o in data.get("options", []) if o.strip()][:10]
if question and len(options) >= 2:
poll = {
"id": uuid.uuid4().hex[:8],
"question": question,
"options": options,
"votes": {},
"active": True,
}
room_polls.setdefault(room_id, []).append(poll)
await broadcast(room_id, {
"action": "poll-started",
"poll": _sanitize_poll(poll, None),
})
elif action == "vote-poll":
poll_id = data.get("poll_id")
choice = data.get("choice")
polls = room_polls.get(room_id, [])
for poll in polls:
if poll["id"] == poll_id and poll["active"]:
if isinstance(choice, int) and 0 <= choice < len(poll["options"]):
poll["votes"][peer_id] = choice
await broadcast(room_id, {
"action": "poll-update",
"poll_id": poll_id,
"results": _poll_results(poll),
"total_votes": len(poll["votes"]),
})
break
elif action == "end-poll":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
poll_id = data.get("poll_id")
for poll in room_polls.get(room_id, []):
if poll["id"] == poll_id:
poll["active"] = False
await broadcast(room_id, {
"action": "poll-ended",
"poll_id": poll_id,
"results": _poll_results(poll),
"total_votes": len(poll["votes"]),
})
break
# ── Whiteboard ────────────────────────────────────────
elif action == "whiteboard-stroke":
stroke = data.get("stroke")
if stroke and room_id:
room_whiteboards.setdefault(room_id, []).append(stroke)
# Limit stored strokes
if len(room_whiteboards[room_id]) > 5000:
room_whiteboards[room_id] = room_whiteboards[room_id][-3000:]
await broadcast(room_id, {
"action": "whiteboard-stroke",
"stroke": stroke,
"from": peer_id,
}, exclude=peer_id)
elif action == "whiteboard-clear":
if room_id:
room_whiteboards[room_id] = []
await broadcast(room_id, {"action": "whiteboard-clear"})
# ── Breakout Rooms ────────────────────────────────────
elif action == "create-breakout":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
br_rooms = data.get("rooms", [])
breakout = {"rooms": {}, "active": True}
for br in br_rooms[:10]:
br_id = uuid.uuid4().hex[:6]
breakout["rooms"][br_id] = {
"name": br.get("name", f"Room {br_id}")[:30],
"peers": [p for p in br.get("peers", []) if p in rooms.get(room_id, {})],
}
room_breakouts[room_id] = breakout
await broadcast(room_id, {
"action": "breakout-started",
"rooms": {rid: {"name": r["name"], "peers": r["peers"]} for rid, r in breakout["rooms"].items()},
})
elif action == "end-breakout":
if room_id and room_meta.get(room_id, {}).get("host") == peer_id:
room_breakouts[room_id] = {"rooms": {}, "active": False}
await broadcast(room_id, {"action": "breakout-ended"})
elif msg.type == web.WSMsgType.ERROR:
print(f"WebSocket error: {ws.exception()}")
finally:
# Clean up on disconnect
# Remove from waiting room if applicable
if room_id and room_id in waiting_rooms:
waiting_rooms[room_id].pop(peer_id, None)
if room_id and room_id in rooms:
rooms[room_id].pop(peer_id, None)
name = peers.get(peer_id, {}).get("name", "?")
print(f"[{room_id}] {name} ({peer_id}) left. "
f"Room has {len(rooms[room_id])} peers.")
await broadcast(room_id, {
"action": "peer-left",
"peer_id": peer_id,
})
# Transfer host if host left
if room_meta.get(room_id, {}).get("host") == peer_id and rooms[room_id]:
new_host = next(iter(rooms[room_id]))
room_meta[room_id]["host"] = new_host
if new_host in peers:
peers[new_host]["role"] = "host"
await broadcast(room_id, {
"action": "host-changed",
"new_host": new_host,
"name": peers.get(new_host, {}).get("name", "?"),
})
# Clean up empty rooms
if not rooms[room_id]:
del rooms[room_id]
room_meta.pop(room_id, None)
waiting_rooms.pop(room_id, None)
room_polls.pop(room_id, None)
room_whiteboards.pop(room_id, None)
room_breakouts.pop(room_id, None)
print(f"[{room_id}] Room empty, removed.")
peers.pop(peer_id, None)
return ws
def _sanitize_poll(poll, peer_id):
"""Return poll data safe for sending to clients."""
return {
"id": poll["id"],
"question": poll["question"],
"options": poll["options"],
"results": _poll_results(poll),
"total_votes": len(poll["votes"]),
"active": poll["active"],
"my_vote": poll["votes"].get(peer_id) if peer_id else None,
}
def _poll_results(poll):
"""Count votes per option."""
counts = [0] * len(poll["options"])
for choice in poll["votes"].values():
if 0 <= choice < len(counts):
counts[choice] += 1
return counts
async def broadcast(room_id, message, exclude=None):
"""Send a message to all peers in a room, optionally excluding one."""
if room_id not in rooms:
return
dead = []
for pid, ws in rooms[room_id].items():
if pid == exclude:
continue
try:
await ws.send_json(message)
except Exception:
dead.append(pid)
for pid in dead:
rooms[room_id].pop(pid, None)
peers.pop(pid, None)
# ── App Setup ─────────────────────────────────────────────────────────────
app = web.Application()
app.router.add_get("/", index)
app.router.add_get("/room/{room_id}", room_page)
app.router.add_post("/api/create-room", create_room)
app.router.add_get("/api/room/{room_id}", room_info)
app.router.add_get("/ws", websocket_handler)
app.router.add_static("/static/", STATIC_DIR, show_index=False)
if __name__ == "__main__":
port = int(os.environ.get("PORT", 8080))
print(f"Video Call server starting on http://localhost:{port}")
web.run_app(app, host="0.0.0.0", port=port)