parley.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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(f'connected websocket for {config.user} in game {config.game}')
  18. cache.add_connection(config.game, ws)
  19. try:
  20. for (author, content) in db.get_backlog(config.game):
  21. await ws.send(messages.Post(author, content).json())
  22. async for payload in ws:
  23. msg = messages.Message.decode(payload)
  24. db.add_msg(config.user, msg.content, config.game)
  25. for w in cache.get_connections(config.game):
  26. await w.send(messages.Post(config.user, msg.content).json())
  27. finally:
  28. sanic.log.logger.info(f'removing websocket for {config.game}')
  29. cache.remove_connection(config.game, ws)
  30. if __name__ == '__main__':
  31. try:
  32. app.run()
  33. finally:
  34. db.close()