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