storage.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from sanic.websocket import WebSocketConnection # type: ignore
  2. import sqlite3 as sql
  3. from typing import Dict, List, Optional, Tuple
  4. class Cache:
  5. connections: Dict[str, WebSocketConnection]
  6. def __init__(self):
  7. self.connections = {}
  8. def add_connection(self, game: str, ws: WebSocketConnection):
  9. if game not in self.connections:
  10. self.connections[game] = set()
  11. self.connections[game].add(ws)
  12. def remove_connection(self, game: str, ws: WebSocketConnection):
  13. if game in self.connections:
  14. self.connections[game].remove(ws)
  15. def get_connections(self, game: str) -> List[WebSocketConnection]:
  16. return self.connections.get(game, [])
  17. class Storage:
  18. db: sql.Connection
  19. def __init__(self):
  20. self.db = sql.connect('samp.db')
  21. def get_backlog(self, game: str, c: Optional[sql.Cursor]=None) -> List[Tuple[str, str]]:
  22. if c is None:
  23. c = self.db.cursor()
  24. c.execute('SELECT c.user, c.content '
  25. 'FROM chat c, games g '
  26. 'WHERE c.game = g.id AND g.name = ?', [game])
  27. return list(c)
  28. def get_game_id(self, game: str, c: Optional[sql.Cursor]=None) -> int:
  29. if c is None:
  30. c = self.db.cursor()
  31. c.execute('SELECT id FROM games WHERE name = ?', [game])
  32. res = c.fetchone()
  33. if res is not None:
  34. return res[0]
  35. else:
  36. c.execute('INSERT INTO games (name) VALUES (?)', [game])
  37. self.db.commit()
  38. c.execute('SELECT id FROM games WHERE name = ?', [game])
  39. return c.fetchone()[0]
  40. def add_msg(self, user: str, content: str, game: str, c: Optional[sql.Cursor]=None):
  41. if c is None:
  42. c = self.db.cursor()
  43. game_id: int = self.get_game_id(game, c)
  44. c.execute('INSERT INTO chat (game, user, content) '
  45. 'VALUES (?, ?, ?)', [game_id, user, content])
  46. self.db.commit()
  47. def close(self):
  48. self.db.close()