"""Library scanning and the stable per-book key shared across progress.py, blocks.py and remote.py.""" from __future__ import annotations import hashlib import re from pathlib import Path # Books downloaded from the server are named " - .epub". _SERVER_FILE_RE = re.compile(r"^(\d{4,7}) - ") def server_id_of(path: Path) -> int | None: m = _SERVER_FILE_RE.match(path.name) return int(m.group(1)) if m else None def server_key(server_id: int) -> str: return f"s{server_id}" def _book_id(path: Path) -> str: """A book's key for reading state: the server's id for a downloaded book (the same whether or not, and under whatever name, the file is there), else a hash of its path.""" sid = server_id_of(path) if sid is not None: return server_key(sid) return hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:16] def scan_library(library_dir: Path) -> list[Path]: if not library_dir.exists(): return [] return sorted(library_dir.rglob("*.epub"))