Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

144 lines
4.3KB

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