parley.py 1.2 KB

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