123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- import sanic
- import messages
- import storage
- app = sanic.Sanic()
- cache = storage.Cache()
- db = storage.Storage()
- @app.route("/static/<f>")
- async def static(request, f):
- return await sanic.response.file('static/{}'.format(f))
- @app.route("/")
- async def index(request):
- return await sanic.response.file('static/index.html')
- @app.websocket("/socket")
- async def socket(request, ws):
- initial = await ws.recv()
- config = messages.Message.decode(initial)
- user = config.user
- game = config.game
- sanic.log.logger.info(f'connected websocket for {user} in game {game}')
- cache.add_connection(game, ws)
- try:
- for (author, content) in db.get_backlog(game):
- await ws.send(messages.Post(author, content).json())
- async for payload in ws:
- msg = messages.Message.decode(payload)
- db.add_msg(user, msg.content, game)
- for w in cache.get_connections(game):
- await w.send(messages.Post(user, msg.content).json())
- finally:
- sanic.log.logger.info('removing websocket for {}'.format(game))
- cache.remove_connection(game, ws)
- if __name__ == '__main__':
- try:
- app.run()
- finally:
- db.close()
|