storage.py 1.7 KB

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