You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

142 line
4.2KB

  1. import asyncio
  2. import collections
  3. import datetime
  4. import http
  5. import json
  6. import uuid
  7. from functools import partial
  8. from pathlib import Path
  9. import websockets
  10. rooms = collections.defaultdict(dict)
  11. class PicoProtocol(websockets.WebSocketServerProtocol):
  12. def serve_file(self, path):
  13. home = Path(__file__).parent
  14. document = home.joinpath(path.lstrip('/'))
  15. if not document.is_file():
  16. document = home.joinpath('pico.html').resolve()
  17. if document.suffix == '.html':
  18. content_type = 'text/html; charset=utf-8'
  19. elif document.suffix == '.js':
  20. content_type = 'application/javascript; charset=utf-8'
  21. elif document.suffix == '.css':
  22. content_type = 'text/css; charset=utf-8'
  23. elif document.suffix == '.svg':
  24. content_type = 'image/svg+xml; charset=utf-8'
  25. else:
  26. content_type = 'text/plain; charset=utf-8'
  27. return (
  28. http.HTTPStatus.OK,
  29. [('Content-Type', content_type)],
  30. document.read_bytes(),
  31. )
  32. def random_redirect(self):
  33. new_path = str(uuid.uuid4()).split('-')[1]
  34. return (
  35. http.HTTPStatus.FOUND,
  36. [('Location', new_path)],
  37. b'',
  38. )
  39. async def process_request(self, path, request_headers):
  40. if path == '/':
  41. return self.random_redirect()
  42. if request_headers.get('Upgrade') != 'websocket':
  43. return self.serve_file(path)
  44. return await super().process_request(path, request_headers)
  45. async def send_json_many(targets, **data):
  46. for websocket in list(targets):
  47. await send_json(websocket, **data)
  48. async def send_json(websocket, **data):
  49. try:
  50. await websocket.send(json.dumps(data))
  51. except websockets.exceptions.ConnectionClosed:
  52. pass
  53. async def recv_json(websocket):
  54. try:
  55. return json.loads(await websocket.recv())
  56. except websockets.exceptions.ConnectionClosed:
  57. return {'kind': 'logout'}
  58. except json.decoder.JSONDecodeError:
  59. return {}
  60. async def handle(ws, path, server_name):
  61. room = rooms[path]
  62. usernames = room.keys()
  63. sockets = room.values()
  64. username = None
  65. while True:
  66. data = await recv_json(ws)
  67. ts = datetime.datetime.now().isoformat() + 'Z'
  68. emit = partial(send_json_many, kind=data['kind'], ts=ts)
  69. broadcast = partial(emit, targets=sockets)
  70. reply = partial(emit, targets=[ws])
  71. error = partial(reply, kind='error')
  72. if 'kind' not in data:
  73. await error(value='Message without kind is invalid')
  74. elif data['kind'] == 'login':
  75. username = data['value']
  76. if not username:
  77. await error(value='Username not allowed')
  78. break
  79. if username in usernames:
  80. await error(value='Username taken')
  81. break
  82. room[username] = ws
  83. online = list(usernames)
  84. await reply(kind='state', username=username)
  85. await broadcast(kind='state', online=online)
  86. elif username not in room:
  87. await error(value='Login required')
  88. break
  89. elif data['kind'] == 'logout':
  90. del room[username]
  91. online = list(usernames)
  92. await broadcast(kind='state', online=online)
  93. break
  94. else:
  95. value = data.get('value')
  96. if 'target' in data:
  97. recipients = {username, data['target']}
  98. targets = {v for k, v in room.items() if k in recipients}
  99. await broadcast(source=username, value=value, targets=targets)
  100. else:
  101. await broadcast(source=username, value=value)
  102. async def start_server(host, port, server_name):
  103. bound_handle = partial(handle, server_name=server_name)
  104. bound_serve = partial(websockets.serve, create_protocol=PicoProtocol)
  105. return await bound_serve(bound_handle, host, port)
  106. if __name__ == '__main__':
  107. host, port = 'localhost', 9753
  108. loop = asyncio.get_event_loop()
  109. loop.run_until_complete(start_server(host, port, 'PicoChat'))
  110. print(f'Running on {host}:{port}')
  111. loop.run_forever()