parley.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import sanic # type: ignore
  2. import messages
  3. import storage
  4. app = sanic.Sanic()
  5. cache = storage.Cache()
  6. db = storage.Storage()
  7. app.static('/static', './static')
  8. app.static('/', './static/index.html')
  9. @app.websocket("/socket")
  10. async def socket(request: sanic.request.Request, ws: sanic.websocket.WebSocketConnection) -> sanic.response.HTTPResponse:
  11. initial = await ws.recv()
  12. config: messages.InitialConfig = messages.Message.decode(initial)
  13. sanic.log.logger.info(
  14. f'connected websocket for {config.user} in game {config.game}')
  15. cache.add_connection(config.game, ws)
  16. try:
  17. for (author, content) in db.get_backlog(config.game):
  18. await ws.send(messages.Post(author, content).json())
  19. async for payload in ws:
  20. msg = messages.Message.decode(payload)
  21. db.add_msg(config.user, msg.content, config.game)
  22. for w in cache.get_connections(config.game):
  23. await w.send(messages.Post(config.user, msg.content).json())
  24. finally:
  25. sanic.log.logger.info(f'removing websocket for {config.game}')
  26. cache.remove_connection(config.game, ws)
  27. if __name__ == '__main__':
  28. try:
  29. app.run()
  30. finally:
  31. db.close()