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.

141 line
4.1KB

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