parley.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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.route("/static/<f>")
  8. async def static(request: sanic.request.Request, f: str) -> sanic.response.Response:
  9. return await sanic.response.file('static/{}'.format(f))
  10. @app.route("/")
  11. async def index(request: sanic.request.Request) -> sanic.response.Response:
  12. return await sanic.response.file('static/index.html')
  13. @app.websocket("/socket")
  14. async def socket(request: sanic.request.Request, ws: sanic.websocket.WebSocketConnection) -> sanic.response.Response:
  15. initial = await ws.recv()
  16. config: messages.InitialConfig = messages.Message.decode(initial)
  17. sanic.log.logger.info(
  18. f'connected websocket for {config.user} in game {config.game}')
  19. cache.add_connection(config.game, ws)
  20. try:
  21. for (author, content) in db.get_backlog(config.game):
  22. await ws.send(messages.Post(author, content).json())
  23. async for payload in ws:
  24. msg = messages.Message.decode(payload)
  25. db.add_msg(config.user, msg.content, config.game)
  26. for w in cache.get_connections(config.game):
  27. await w.send(messages.Post(config.user, msg.content).json())
  28. finally:
  29. sanic.log.logger.info(f'removing websocket for {config.game}')
  30. cache.remove_connection(config.game, ws)
  31. if __name__ == '__main__':
  32. try:
  33. app.run()
  34. finally:
  35. db.close()