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
 
 
 
 
 
 
 
 
 
 
 
5a0b7f3
 
 
17c6267
 
 
 
 
5a0b7f3
 
 
 
 
 
 
17c6267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a0b7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

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"),
                        })

                # ── Captions ──────────────────────────────────────────
                elif action == "caption":
                    text = data.get("text", "").strip()[:500]
                    if text and room_id:
                        name = peers.get(peer_id, {}).get("name", "?")
                        await broadcast(room_id, {
                            "action": "caption",
                            "from": peer_id,
                            "name": name,
                            "text": text,
                        }, exclude=peer_id)

                # ── 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)