manga-dlp/mangadlp/cache.py

84 lines
2.5 KiB
Python
Raw Normal View History

2023-02-06 14:46:58 +01:00
import json
from pathlib import Path
from typing import Dict, List, Union
2023-02-06 14:46:58 +01:00
from loguru import logger as log
class CacheDB:
2023-02-12 16:13:41 +01:00
def __init__(
self,
db_path: Union[str, Path],
manga_uuid: str,
manga_lang: str,
manga_name: str,
) -> None:
2023-02-06 14:46:58 +01:00
self.db_path = Path(db_path)
2023-02-12 16:13:41 +01:00
self.uuid = manga_uuid
self.lang = manga_lang
self.name = manga_name
self.db_key = f"{manga_uuid}__{manga_lang}"
2023-02-06 14:46:58 +01:00
2023-02-12 16:13:41 +01:00
self._prepare_db()
2023-02-06 14:46:58 +01:00
2023-02-12 16:13:41 +01:00
self.db_data = self._read_db()
2023-02-06 15:34:40 +01:00
# create db key entry if not found
2023-02-06 14:46:58 +01:00
if not self.db_data.get(self.db_key):
self.db_data[self.db_key] = {}
2023-02-12 16:13:41 +01:00
2023-02-06 14:46:58 +01:00
self.db_uuid_data: dict = self.db_data[self.db_key]
2023-02-12 16:13:41 +01:00
if not self.db_uuid_data.get("name"):
self.db_uuid_data.update({"name": self.name})
self._write_db()
2023-02-06 14:46:58 +01:00
self.db_uuid_chapters: list = self.db_uuid_data.get("chapters") or []
def _prepare_db(self) -> None:
2023-02-06 15:34:40 +01:00
if self.db_path.exists():
2023-02-06 14:46:58 +01:00
return
2023-02-06 15:34:40 +01:00
# create empty cache
2023-02-06 14:46:58 +01:00
try:
self.db_path.touch()
self.db_path.write_text(json.dumps({}), encoding="utf8")
except Exception as exc:
log.error("Can't create db-file")
raise exc
def _read_db(self) -> Dict[str, dict]:
2023-02-06 14:46:58 +01:00
log.info(f"Reading cache-db: {self.db_path}")
try:
db_txt = self.db_path.read_text(encoding="utf8")
db_dict: dict[str, dict] = json.loads(db_txt)
2023-02-06 14:46:58 +01:00
except Exception as exc:
log.error("Can't load cache-db")
raise exc
return db_dict
2023-02-12 16:13:41 +01:00
def _write_db(self) -> None:
db_dump = json.dumps(self.db_data, indent=4, sort_keys=True)
self.db_path.write_text(db_dump, encoding="utf8")
2023-02-06 14:46:58 +01:00
def add_chapter(self, chapter: str) -> None:
log.info(f"Adding chapter to cache-db: {chapter}")
self.db_uuid_chapters.append(chapter)
2023-02-06 15:16:14 +01:00
# dedup entries
updated_chapters = list({*self.db_uuid_chapters})
2023-02-12 16:13:41 +01:00
sorted_chapters = sort_chapters(updated_chapters)
2023-02-06 14:46:58 +01:00
try:
2023-02-12 16:13:41 +01:00
self.db_data[self.db_key]["chapters"] = sorted_chapters
self._write_db()
2023-02-06 14:46:58 +01:00
except Exception as exc:
log.error("Can't write cache-db")
raise exc
2023-02-12 16:13:41 +01:00
def sort_chapters(chapters: list) -> List[str]:
2023-02-12 16:13:41 +01:00
try:
sorted_list = sorted(chapters, key=float)
except Exception:
log.debug("Can't sort cache by float, using default sorting")
sorted_list = sorted(chapters)
return sorted_list