database.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # -*- coding: utf-8 -*-
  2. from pathlib import Path
  3. from typing import Optional
  4. __all__ = ['Database']
  5. class AbstractDatabase:
  6. def __init__(self, root: Path):
  7. self._root = Path(root).expanduser().absolute()
  8. def check(self, mode: int = 0o700) -> None:
  9. return self._root.mkdir(mode, parents=True, exist_ok=True)
  10. async def insert(self, key: str, value: bytes) -> int:
  11. with (self._root / key).open(mode='wb') as item:
  12. return item.write(value)
  13. async def exist(self, key: str) -> bool:
  14. return (self._root / key).exists()
  15. async def get(self, key: str) -> bytes:
  16. with (self._root / key).open(mode='rb') as item:
  17. return item.read()
  18. class Database(AbstractDatabase):
  19. def __init__(self, root: Path):
  20. super().__init__(root)
  21. self.check()
  22. async def get_last_live(self, channel: str) -> Optional[str]:
  23. if await self.exist(channel):
  24. if last := await self.get(channel):
  25. return last.decode()
  26. return None
  27. async def update_last_live(self, channel: str, item: str) -> int:
  28. return await self.insert(channel, item.encode())