feat(client,history,cli): add auth, library fetch, and download history (closes #3)

Add the data layer that feeds into downloads: OAuth2 password grant
authentication via httpx, paginated library fetching across all pages,
download history JSON read/write with corrupt-recovery safety, and a
CLI skeleton that wires config → auth → fetch → filter → print.

16 new tests (6 client + 7 history + 3 CLI), 41 total passing.
All 11 acceptance criteria met.
This commit is contained in:
AlexKucera committed 2026-06-03 11:44:16 +02:00
1 parent 6c049d1301
commit 515f5c01f6
8 files changed
+699

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
"""CLI entry point — wire config → auth → fetch library → filter → print."""
import sys
from rich.console import Console
from librofm_downloader.config import load_config, ConfigError
from librofm_downloader.client import LibroFmClient, AuthError
from librofm_downloader.history import DownloadHistory
console = Console()
def run(
config_path: str = "config.yaml",
secrets_path: str = "secrets.yaml",
history_path: str = "download_history.json",
) -> int:
"""Main pipeline: load config → auth → fetch library → filter → print.
Returns:
Exit code: 0 on success, 1 on failure.
"""
try:
config = load_config(config_path, secrets_path)
except ConfigError as exc:
console.print(f"[red]Config error:[/red] {exc}")
return 1
client = LibroFmClient(
username=config.username,
password=config.password,
)
try:
client.authenticate()
except AuthError as exc:
console.print(f"[red]Authentication failed:[/red] {exc}")
return 1
try:
books = client.fetch_library()
except Exception as exc:
console.print(f"[red]Failed to fetch library:[/red] {exc}")
return 1
history = DownloadHistory(history_path)
new_books = [b for b in books if not history.is_downloaded(b.get("isbn", ""))]
if not new_books:
console.print("[green]All caught up! No new books to download.[/green]")
return 0
console.print(f"\n[bold]{len(new_books)} book(s) to download:[/bold]\n")
for book in new_books:
title = book.get("title", "Unknown")
isbn = book.get("isbn", "?")
console.print(f" • {title} [dim]({isbn})[/dim]")
return 0
+99
View File
@@ -0,0 +1,99 @@
"""HTTP client for Libro.fm API — auth and library fetch."""
import httpx
class AuthError(Exception):
"""Authentication failed (bad credentials, network error, etc.)."""
class LibroFmClient:
"""Libro.fm API client with OAuth2 password grant and library fetching."""
DEFAULT_HEADERS = {
"X-LibroFm-AppVer": "7.34.8",
"User-Agent": "okhttp/5.3.2",
}
def __init__(
self,
base_url: str = "https://libro.fm",
username: str = "",
password: str = "",
timeout: float = 30.0,
):
self._base_url = base_url.rstrip("/")
self._username = username
self._password = password
self._timeout = timeout
self._access_token: str | None = None
def authenticate(self, transport: httpx.BaseTransport | None = None) -> str:
"""OAuth2 password grant → returns access_token.
Args:
transport: Optional httpx transport override for testing.
Returns:
The access token string.
Raises:
AuthError: If credentials are invalid or the request fails.
"""
client = httpx.Client(
base_url=self._base_url,
headers=self.DEFAULT_HEADERS,
timeout=self._timeout,
transport=transport,
)
try:
resp = client.post(
"/oauth/token",
data={
"grant_type": "password",
"username": self._username,
"password": self._password,
},
)
resp.raise_for_status()
token_data = resp.json()
self._access_token = token_data["access_token"]
return self._access_token
except httpx.HTTPStatusError as exc:
raise AuthError(f"Auth failed ({exc.response.status_code})") from exc
def fetch_library(self, transport: httpx.BaseTransport | None = None) -> list[dict]:
"""Fetch all books from the user's library, paginating automatically.
Args:
transport: Optional httpx transport override for testing.
Returns:
List of book dicts across all pages.
Raises:
AuthError: If not authenticated.
"""
if not self._access_token:
raise AuthError("Not authenticated. Call authenticate() first.")
headers = {**self.DEFAULT_HEADERS, "Authorization": f"Bearer {self._access_token}"}
all_books: list[dict] = []
client = httpx.Client(
base_url=self._base_url,
headers=headers,
timeout=self._timeout,
transport=transport,
)
next_url = "/api/v10/library"
while next_url:
resp = client.get(next_url)
resp.raise_for_status()
data = resp.json()
all_books.extend(data.get("books", []))
next_url = data.get("next_page") or None
return all_books
+64
View File
@@ -0,0 +1,64 @@
"""Download history — track which ISBNs have been downloaded."""
import json
import logging
from dataclasses import dataclass, asdict
from pathlib import Path
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class HistoryEntry:
"""A single download history record."""
isbn: str
title: str
format: str
path: str
downloaded_at: str
class DownloadHistory:
"""Read/write download_history.json — ISBN → entry mapping."""
def __init__(self, path: Path | str):
self._path = Path(path)
self._data: dict[str, dict] = {}
self._load()
def _load(self) -> None:
"""Load existing history from disk. Missing/corrupt → empty with warning."""
if not self._path.exists():
return
try:
text = self._path.read_text(encoding="utf-8")
self._data = json.loads(text) if text.strip() else {}
except (json.JSONDecodeError, OSError) as exc:
logger.warning("Corrupt history file %s: %s. Starting with empty history.", self._path, exc)
self._data = {}
def find(self, isbn: str) -> HistoryEntry | None:
"""Look up a history entry by ISBN. Returns None if not found."""
entry_dict = self._data.get(isbn)
if entry_dict is None:
return None
return HistoryEntry(**entry_dict)
def is_downloaded(self, isbn: str) -> bool:
"""Check whether an ISBN was previously downloaded."""
return isbn in self._data
def write(self, entry: HistoryEntry) -> None:
"""Persist a history entry to disk."""
self._data[entry.isbn] = asdict(entry)
self._flush()
def _flush(self) -> None:
"""Write current in-memory state to disk."""
self._path.parent.mkdir(parents=True, exist_ok=True)
self._path.write_text(
json.dumps(self._data, indent=2, ensure_ascii=False),
encoding="utf-8",
)