File: chat.py

package info (click to toggle)
python-falcon 4.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,172 kB
  • sloc: python: 33,608; javascript: 92; sh: 50; makefile: 50
file content (49 lines) | stat: -rw-r--r-- 1,437 bytes parent folder | download
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
import re

from falcon.asgi import Request
from falcon.asgi import WebSocket

from .hub import Hub


class Chat:
    ALL = re.compile(r'^/all\s+(.+)$')
    MSG = re.compile(r'^/msg\s+(\w+)\s+(.+)$')

    def __init__(self, hub: Hub):
        self._hub = hub

    async def on_websocket(self, req: Request, ws: WebSocket, name: str) -> None:
        await ws.accept()

        try:
            await self._hub.broadcast(f'{name} CONNECTED')
            self._hub.add_user(name, ws)

            await ws.send_text(f'Hello, {name}!')

            while True:
                message = await ws.receive_text()

                if message == '/quit':
                    await ws.send_text(f'Bye, {name}!')
                    await ws.close(4001, 'quit command')
                    break

                command = self.ALL.match(message)
                if command:
                    text = command.group(1)
                    await self._hub.broadcast(f'[{name}] {text}')
                    continue

                command = self.MSG.match(message)
                if command:
                    recipient, text = command.groups()
                    await self._hub.message(recipient, f'[{name}] {text}')
                    continue

                await ws.send_text('Supported commands: /all /msg /quit')

        finally:
            self._hub.remove_user(name)
            await self._hub.broadcast(f'{name} DISCONNECTED')