123456789101112131415161718192021222324252627282930313233343536373839 |
- import sanic # type: ignore
- import messages
- import storage
- app = sanic.Sanic()
- cache = storage.Cache()
- db = storage.Storage()
- app.static('/static', './static')
- app.static('/', './static/index.html')
- @app.websocket("/socket")
- async def socket(request: sanic.request.Request, ws: sanic.websocket.WebSocketConnection) -> sanic.response.HTTPResponse:
- 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()
|