|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from collections import defaultdict |
| 5 | +from typing import Literal, Optional |
| 6 | + |
| 7 | +import websockets |
| 8 | +from django.conf import settings |
| 9 | +from django.core.signing import TimestampSigner |
| 10 | +from pydantic import BaseModel, ValidationError |
| 11 | +from websockets import WebSocketClientProtocol |
| 12 | +from websockets.server import serve |
| 13 | + |
| 14 | +from umap.models import Map, User # NOQA |
| 15 | + |
| 16 | +# Contains the list of websocket connections handled by this process. |
| 17 | +# It's a mapping of map_id to a set of the active websocket connections |
| 18 | +CONNECTIONS = defaultdict(set) |
| 19 | + |
| 20 | + |
| 21 | +class JoinMessage(BaseModel): |
| 22 | + kind: str = "join" |
| 23 | + token: str |
| 24 | + |
| 25 | + |
| 26 | +class OperationMessage(BaseModel): |
| 27 | + kind: str = "operation" |
| 28 | + verb: str = Literal["upsert", "update", "delete"] |
| 29 | + subject: str = Literal["map", "layer", "feature"] |
| 30 | + metadata: Optional[dict] = None |
| 31 | + key: Optional[str] = None |
| 32 | + |
| 33 | + |
| 34 | +async def join_and_listen( |
| 35 | + map_id: int, permissions: list, user: str | int, websocket: WebSocketClientProtocol |
| 36 | +): |
| 37 | + """Join a "room" whith other connected peers. |
| 38 | +
|
| 39 | + New messages will be broadcasted to other connected peers. |
| 40 | + """ |
| 41 | + print(f"{user} joined room #{map_id}") |
| 42 | + CONNECTIONS[map_id].add(websocket) |
| 43 | + try: |
| 44 | + async for raw_message in websocket: |
| 45 | + # recompute the peers-list at the time of message-sending. |
| 46 | + # as doing so beforehand would miss new connections |
| 47 | + peers = CONNECTIONS[map_id] - {websocket} |
| 48 | + # Only relay valid "operation" messages |
| 49 | + try: |
| 50 | + OperationMessage.model_validate_json(raw_message) |
| 51 | + websockets.broadcast(peers, raw_message) |
| 52 | + except ValidationError as e: |
| 53 | + error = f"An error occurred when receiving this message: {raw_message}" |
| 54 | + print(error, e) |
| 55 | + finally: |
| 56 | + CONNECTIONS[map_id].remove(websocket) |
| 57 | + |
| 58 | + |
| 59 | +async def handler(websocket): |
| 60 | + """Main WebSocket handler. |
| 61 | +
|
| 62 | + If permissions are granted, let the peer enter a room. |
| 63 | + """ |
| 64 | + raw_message = await websocket.recv() |
| 65 | + |
| 66 | + # The first event should always be 'join' |
| 67 | + message: JoinMessage = JoinMessage.model_validate_json(raw_message) |
| 68 | + signed = TimestampSigner().unsign_object(message.token, max_age=30) |
| 69 | + user, map_id, permissions = signed.values() |
| 70 | + |
| 71 | + # Check if permissions for this map have been granted by the server |
| 72 | + if "edit" in signed["permissions"]: |
| 73 | + await join_and_listen(map_id, permissions, user, websocket) |
| 74 | + |
| 75 | + |
| 76 | +def run(host, port): |
| 77 | + if not settings.WEBSOCKET_ENABLED: |
| 78 | + msg = ( |
| 79 | + "WEBSOCKET_ENABLED should be set to True to run the WebSocket Server. " |
| 80 | + "See the documentation at " |
| 81 | + "https://docs.umap-project.org/en/stable/config/settings/#websocket_enabled " |
| 82 | + "for more information." |
| 83 | + ) |
| 84 | + print(msg) |
| 85 | + exit(1) |
| 86 | + |
| 87 | + async def _serve(): |
| 88 | + async with serve(handler, host, port): |
| 89 | + print(f"Waiting for connections on {host}:{port}") |
| 90 | + await asyncio.Future() # run forever |
| 91 | + |
| 92 | + asyncio.run(_serve()) |
0 commit comments