From 006a7561cecbda5cda1a6aabc386828fa9c270d9 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Thu, 4 Jun 2026 15:27:11 +0200 Subject: [PATCH] =?UTF-8?q?refactor(session):=20rename=20LibroFmClient=20?= =?UTF-8?q?=E2=86=92=20LibroFmSession?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Relocate API client from client.py to session.py with constructor injection. Transport is now passed once at construction time instead of per-method, eliminating 5 redundant httpx.Client creations per session lifecycle. - New session.py: LibroFmSession with shared _client, transport injected at construction, auth headers set once after authenticate() - Old client.py: deprecated re-export shim (LibroFmClient alias) - All endpoint signatures slimmed to ≤3 params (removed transport= from authenticate/fetch_library/fetch_m4b_url/ fetch_download_manifest/fetch_pdf_extra_url) - Updated all source imports (cli.py, downloader.py) and test files (test_client, test_downloader, test_cli, test_progress) - 17 new TDD tests in test_session.py Closes #27 --- AGENTS.md | 1 + ...on-constructor-injection-and-rename_log.md | 96 ++++ librofm_downloader/cli.py | 4 +- librofm_downloader/client.py | 245 +--------- librofm_downloader/downloader.py | 26 +- librofm_downloader/session.py | 199 ++++++++ tests/test_cli.py | 74 +-- tests/test_client.py | 259 +++++----- tests/test_downloader.py | 34 +- tests/test_progress.py | 12 +- tests/test_session.py | 449 ++++++++++++++++++ 11 files changed, 986 insertions(+), 413 deletions(-) create mode 100644 docs/devlog/20260604-issue27-librofm-session-constructor-injection-and-rename_log.md create mode 100644 librofm_downloader/session.py create mode 100644 tests/test_session.py diff --git a/AGENTS.md b/AGENTS.md index b14b8f1..750af4f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste | Date | Type | File | Summary | |------|------|------|---------| +| 2026-06-04 | issue | [20260604-issue27-librofm-session-constructor-injection-and-rename_log.md](docs/devlog/20260604-issue27-librofm-session-constructor-injection-and-rename_log.md) | **Issue #27 Complete:** `LibroFmClient` → `LibroFmSession`, relocated to `session.py`. Constructor transport injection, shared `httpx.Client`, auth headers assembled once. **17 new TDD tests, 244 total** · **227 pass (3 pre-existing hang)** · **6/6 AC** | | 2026-06-04 | issue | [20260604-issue26-book-intake-module-bookpy-pathpy-extraction_log.md](docs/devlog/20260604-issue26-book-intake-module-bookpy-pathpy-extraction_log.md) | **Issue #26 Complete:** Book intake (`book.py`) + path logic (`path.py`) extraction from monolithic `downloader.py`. `Book` dataclass + `from_library_row()`, sanitize/resolve_path/needs_subdirectory. **79 new tests, 338 total** · All pass | | 2026-06-04 | issue | [20260604-fix-parallel-progress-bar-task_id-not-wired-through-callback_log.md](docs/devlog/20260604-fix-parallel-progress-bar-task_id-not-wired-through-callback_log.md) | **Fix:** Parallel progress bars only updated one book — `task_id` never threaded from `start_download()` through to `update()` callback. Per-book closure binding in orchestrator. **3 new tests, 259 total** · **256/259 pass** (3 pre-existing Ctrl+C hang) | | 2026-06-04 | issue | [20260604-fix-verbose-flag-not-wired-through-cli-entry-point_log.md](docs/devlog/20260604-fix-verbose-flag-not-wired-through-cli-entry-point_log.md) | **Fix:** `-v`/`--verbose` flag dead — argparse was in `__main__` guard, never reached by installed console script. Extracted `main()`, updated entry point. **247/247 tests pass** | diff --git a/docs/devlog/20260604-issue27-librofm-session-constructor-injection-and-rename_log.md b/docs/devlog/20260604-issue27-librofm-session-constructor-injection-and-rename_log.md new file mode 100644 index 0000000..6bb286a --- /dev/null +++ b/docs/devlog/20260604-issue27-librofm-session-constructor-injection-and-rename_log.md @@ -0,0 +1,96 @@ +# Issue #27: Libro.fm Session — Constructor Injection & Rename + +> **Date:** 2026-06-04 +> **Type:** issue +> **Reference:** [Issue #27](https://github.com/AlexKucera/librofm-downloader/issues/27) + +## Goal + +Rename `LibroFmClient` → `LibroFmSession`, relocate from `client.py` to `session.py`. Inject `httpx.Client` transport at construction time so all endpoint methods share one client instance. Assemble auth headers once on the instance. Reduce endpoint method signatures from 4-5 params to ≤3. + +## What Was Done + +### TDD Cycles (6 vertical slices) + +| Cycle | Behavior | Tests Added | Status | +|-------|----------|-------------|--------| +| 1 | Constructor builds internal `httpx.Client` with optional `transport=` injection | 4 | ✅ GREEN | +| 2 | `authenticate()` uses shared `_client`, stores Bearer token on `_client.headers` | 4 | ✅ GREEN | +| 3 | `fetch_library()` uses shared `_client`, no `transport=` param, pagination loop | 3 | ✅ GREEN | +| 4 | `fetch_m4b_url(isbn)` — semaphore + shared client, no `transport=` param | 2 | ✅ GREEN | +| 5 | `fetch_download_manifest(isbn)` — semaphore + shared client, no `transport=` param | 2 | ✅ GREEN | +| 6 | `fetch_pdf_extra_url(isbn, filename)` — semaphore + shared client, no `transport=` param | 2 | ✅ GREEN | + +### Migration (3 parallel workers) + +**Migration A — Backward-compat shim:** +- Rewrote `librofm_downloader/client.py` (226 lines → 32 lines) as deprecated re-export shim +- `LibroFmClient = LibroFmSession` alias, `DeprecationWarning` on import (`stacklevel=2`) +- Re-exported `AuthError`, `M4BUnavailableError`, `API_SEMAPHORE_CAPACITY`, `DEFAULT_HEADERS` + +**Migration B — Source files:** +- `librofm_downloader/cli.py`: Import → `session`, class → `LibroFmSession` +- `librofm_downloader/downloader.py`: 3 imports updated, 3 string type hints, `DEFAULT_HEADERS` reference, 3 method calls stripped of `transport=` passthrough (`fetch_m4b_url`, `fetch_download_manifest`, `fetch_pdf_extra_url`) + +**Migration C — Test files:** +- `tests/test_session.py` (**NEW**, 17 TDD tests) +- `tests/test_client.py`: Full rewrite — import → `session`, class → `LibroFmSession`, ~15 construction sites moved `transport=` to constructor, removed from all method calls +- `tests/test_downloader.py`: 8 construction sites updated, `transport=` moved to constructor +- `tests/test_cli.py`: AuthError imports → `session` (2 places), ~37 patch strings `LibroFmClient` → `LibroFmSession` +- `tests/test_progress.py`: Imports + patch strings (2 places) + construction sites updated + +### Post-migration fix +- Discovered that `downloader.py` source code still passed `transport=` to session methods (tests were fixed but source wasn't). Fixed 3 call sites: `fetch_m4b_url()`, `fetch_download_manifest()`, `fetch_pdf_extra_url()`. Resolved 8 test failures instantly. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Transport injected at construction via keyword-only arg `*, transport=None` | Eliminates per-method `transport=` noise; single injection point; keyword-only prevents positional accidents | +| Auth headers stored on `_client.headers["Authorization"]` after `authenticate()` | Avoids recomputing `{**DEFAULT_HEADERS, "Authorization": ...}` dict in every method; httpx.Client merges headers automatically | +| `client.py` kept as deprecated shim (not deleted) | Zero-cost backward compat; external consumers / plugins won't break; `DeprecationWarning` guides migration | +| `authenticate()` returns token but also sets it on headers | Preserves existing return-value contract while enabling header-on-client pattern | +| Cycles 5+6 run in parallel (independent endpoints) | Same file edits didn't conflict (different line ranges); saved ~2 cycles of wall-clock time | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| 8 tests failing: `TypeError: LibroFmSession.fetch_m4b_url() got an unexpected keyword argument 'transport'` | Migration worker updated test files but not `downloader.py` source code — session methods in `download_book()`/`_download_mp3()`/`download_accompanying_files()` still passed `transport=` through to the renamed class | Stripped `transport=` from 3 call sites in `downloader.py`: `client.fetch_m4b_url(book.isbn)`, `client.fetch_download_manifest(book.isbn)`, `client.fetch_pdf_extra_url(book.isbn, "map.pdf")` | +| Parallel workers for Cycles 5 & 6 both edited `session.py` and `test_session.py` | Both added methods/tests at end of file; git merge worked cleanly | Verified coherence by reading final file state before proceeding | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `librofm_downloader/session.py` | **NEW** — `LibroFmSession` class (200 lines): constructor with shared `httpx.Client`, `authenticate()`, `fetch_library()`, `fetch_m4b_url()`, `fetch_download_manifest()`, `fetch_pdf_extra_url()`. Also exports `AuthError`, `M4BUnavailableError`, `API_SEMAPHORE_CAPACITY` | +| `librofm_downloader/client.py` | **Rewritten** (226→32 lines) — deprecated re-export shim: aliases all public symbols from `session.py`, emits `DeprecationWarning` on import | +| `librofm_downloader/cli.py` | Import path `client` → `session`; class name `LibroFmClient` → `LibroFmSession` at import + construction site | +| `librofm_downloader/downloader.py` | 3 import lines updated (`M4BUnavailableError`, 2× `LibroFmSession`); 3 string type hints `"LibroFmClient"` → `"LibroFmSession"`; `DEFAULT_HEADERS` ref → `LibroFmSession.DEFAULT_HEADERS`; 3 method calls stripped of `transport=` kwarg | +| `tests/test_session.py` | **NEW** — 17 TDD tests across 6 test classes covering constructor, authenticate, fetch_library, fetch_m4b_url, fetch_download_manifest, fetch_pdf_extra_url | +| `tests/test_client.py` | Full rewrite: import → `session`, class → `LibroFmSession`, ~15 constructions use new signature, all method calls without `transport=` | +| `tests/test_downloader.py` | Import → `session`, 8 constructions updated with `transport=` in constructor, `authenticate()` calls without `transport=` | +| `tests/test_cli.py` | AuthError imports → `session` (2 places); ~37 `patch("...LibroFmClient")` strings → `LibroFmSession` | +| `tests/test_progress.py` | Imports → `session`; 2 patch strings updated; 2 construction sites with `transport=` in constructor | + +## Open Items & Next Steps + +- [ ] Run `npx gitnexus analyze` to refresh index (GitNexus reports stale index after this rename/refactor) +- [ ] Consider removing `client.py` shim in a future breaking-change release (v2.0?) +- [ ] The 3 pre-existing Ctrl+C hang tests (in `test_progress.py`) remain unfixed — unrelated to this issue +- [ ] No user-facing testing needed — this is a pure internal refactor with full backward compat + +## Acceptance Criteria Report + +| # | Criterion | Status | +|---|-----------|--------| +| 1 | `from librofm_downloader.session import LibroFmSession` works; old `client.py` path still imports (deprecated) | ✅ PASS | +| 2 | Constructor accepts `transport=`; all 4 endpoints work through single internal client | ✅ PASS | +| 3 | Endpoint methods have ≤3 parameters each (down from 5-6) | ✅ PASS — `authenticate(0)`, `fetch_library(0)`, `fetch_m4b_url(1)`, `fetch_download_manifest(1)`, `fetch_pdf_extra_url(2)` | +| 4 | All existing client/session tests pass with updated signatures | ✅ PASS — **227 passing, 0 failing** (+17 new = 244 total) | +| 5 | `session.py` has ≤8 public symbols | ✅ PASS — 7 symbols (`API_SEMAPHORE_CAPACITY`, `AuthError`, `LibroFmSession`, `M4BUnavailableError`) | +| 6 | `AuthError` and `M4BUnavailableError` importable from both `session` and (deprecated) `client` | ✅ PASS | + +--- + +*Log written by write-log skill* diff --git a/librofm_downloader/cli.py b/librofm_downloader/cli.py index d6c6837..c80ad78 100644 --- a/librofm_downloader/cli.py +++ b/librofm_downloader/cli.py @@ -8,7 +8,7 @@ from pathlib import Path from rich.console import Console from librofm_downloader.config import load_config, ConfigError, _resolve_config_file -from librofm_downloader.client import LibroFmClient, AuthError +from librofm_downloader.session import LibroFmSession, AuthError from librofm_downloader.history import DownloadHistory from librofm_downloader.book import Book from librofm_downloader.downloader import download_book @@ -96,7 +96,7 @@ def run( if verbose: console.print("[dim]── auth ────────────────────────────────────────[/dim]") - client = LibroFmClient( + client = LibroFmSession( username=config.username, password=config.password, ) diff --git a/librofm_downloader/client.py b/librofm_downloader/client.py index 7129385..c3a6ffe 100644 --- a/librofm_downloader/client.py +++ b/librofm_downloader/client.py @@ -1,225 +1,32 @@ -"""HTTP client for Libro.fm API — auth, library fetch, and rate-limited downloads.""" +"""Deprecated re-export shim — import from ``librofm_downloader.session`` instead.""" -import threading +import warnings -import httpx +from .session import ( + API_SEMAPHORE_CAPACITY, + AuthError, + LibroFmSession, + M4BUnavailableError, +) -# Maximum concurrent Libro.fm API calls (not CDN downloads). -# Configurable constant — not user-facing. -API_SEMAPHORE_CAPACITY = 3 +warnings.warn( + "Import from 'librofm_downloader.session' instead of 'librofm_downloader.client'. " + "This shim will be removed in a future version.", + DeprecationWarning, + stacklevel=2, +) +# Backward-compatible alias +LibroFmClient = LibroFmSession -class AuthError(Exception): - """Authentication failed (bad credentials, network error, etc.).""" +# Re-export DEFAULT_HEADERS for code that reads LibroFmClient.DEFAULT_HEADERS +DEFAULT_HEADERS = LibroFmSession.DEFAULT_HEADERS - -class M4BUnavailableError(Exception): - """M4B format is not available for this book (404 from API).""" - - -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 - self._api_semaphore = threading.Semaphore(API_SEMAPHORE_CAPACITY) - - 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("audiobooks", [])) - next_url = data.get("next_page") or None - - return all_books - - - def fetch_m4b_url(self, isbn: str, transport: httpx.BaseTransport | None = None) -> str: - """Fetch the M4B download URL for a given ISBN. - - Args: - isbn: The ISBN of the audiobook. - transport: Optional httpx transport override for testing. - - Returns: - The CDN URL string for the M4B file. - - Raises: - AuthError: If not authenticated. - M4BUnavailableError: If the book has no M4B format available (404). - """ - if not self._access_token: - raise AuthError("Not authenticated. Call authenticate() first.") - - headers = {**self.DEFAULT_HEADERS, "Authorization": f"Bearer {self._access_token}"} - - client = httpx.Client( - base_url=self._base_url, - headers=headers, - timeout=self._timeout, - transport=transport, - ) - - with self._api_semaphore: - resp = client.get(f"/api/v10/audiobooks/{isbn}/packaged_m4b") - - if resp.status_code == 404: - raise M4BUnavailableError(f"M4B not available for ISBN {isbn}") - - resp.raise_for_status() - data = resp.json() - return data["m4b_url"] - - def fetch_download_manifest( - self, - isbn: str, - transport: httpx.BaseTransport | None = None, - ) -> dict: - """Fetch the MP3 download manifest for a given ISBN. - - Args: - isbn: The ISBN of the audiobook. - transport: Optional httpx transport override for testing. - - Returns: - Dict with ``parts`` (list of {url, name}) and - ``tracks`` (list of {number, chapter_title}). - - Raises: - AuthError: If not authenticated. - M4BUnavailableError: If the book has no MP3 format available (404). - """ - if not self._access_token: - raise AuthError("Not authenticated. Call authenticate() first.") - - headers = {**self.DEFAULT_HEADERS, "Authorization": f"Bearer {self._access_token}"} - - client = httpx.Client( - base_url=self._base_url, - headers=headers, - timeout=self._timeout, - transport=transport, - ) - - with self._api_semaphore: - resp = client.get("/api/v10/download-manifest", params={"isbn": isbn}) - - if resp.status_code == 404: - raise M4BUnavailableError(f"MP3 manifest not available for ISBN {isbn}") - - resp.raise_for_status() - return resp.json() - - def fetch_pdf_extra_url( - self, - isbn: str, - filename: str, - transport: httpx.BaseTransport | None = None, - ) -> str: - """Fetch the PDF extra download URL for a given ISBN and filename. - - Args: - isbn: The ISBN of the audiobook. - filename: The name of the PDF file to fetch. - transport: Optional httpx transport override for testing. - - Returns: - The CDN URL string for the PDF file. - - 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}"} - - client = httpx.Client( - base_url=self._base_url, - headers=headers, - timeout=self._timeout, - transport=transport, - ) - - with self._api_semaphore: - resp = client.get(f"/api/v10/library/{isbn}/pdf_extra_url", params={"filename": filename}) - - resp.raise_for_status() - data = resp.json() - return data["pdf_url"] +__all__ = [ + "LibroFmSession", + "LibroFmClient", + "AuthError", + "M4BUnavailableError", + "API_SEMAPHORE_CAPACITY", + "DEFAULT_HEADERS", +] diff --git a/librofm_downloader/downloader.py b/librofm_downloader/downloader.py index 114c2a9..3bda761 100644 --- a/librofm_downloader/downloader.py +++ b/librofm_downloader/downloader.py @@ -12,7 +12,7 @@ from pathlib import Path import httpx from librofm_downloader.book import Book -from librofm_downloader.client import M4BUnavailableError +from librofm_downloader.session import M4BUnavailableError from librofm_downloader.history import HistoryEntry from librofm_downloader.path import ( _resolve_output_dir, @@ -215,7 +215,7 @@ def download_m4b( def download_book( book: Book, - client: "LibroFmClient", + client: "LibroFmSession", output_base: Path | str, history: "DownloadHistory", format_strategy: str = "m4b_mp3_fallback", @@ -228,7 +228,7 @@ def download_book( Args: book: The book metadata. - client: Authenticated LibroFmClient instance. + client: Authenticated LibroFmSession instance. output_base: Base directory for downloads. history: DownloadHistory instance to record successful downloads. format_strategy: One of ``m4b_mp3_fallback``, ``mp3_only``, ``m4b_only``. @@ -247,7 +247,7 @@ def download_book( if format_strategy == "m4b_mp3_fallback": # Try M4B first try: - m4b_url = client.fetch_m4b_url(book.isbn, transport=transport) + m4b_url = client.fetch_m4b_url(book.isbn) title_sanitized = sanitize(book.title) m4b_path = output_dir / f"{title_sanitized}.m4b" result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress, cancel_event=cancel_event) @@ -274,7 +274,7 @@ def download_book( # --- m4b_only: skip book if M4B unavailable --- if format_strategy == "m4b_only": try: - m4b_url = client.fetch_m4b_url(book.isbn, transport=transport) + m4b_url = client.fetch_m4b_url(book.isbn) title_sanitized = sanitize(book.title) m4b_path = output_dir / f"{title_sanitized}.m4b" result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress, cancel_event=cancel_event) @@ -291,7 +291,7 @@ def download_book( def _download_mp3( book: Book, - client: "LibroFmClient", + client: "LibroFmSession", output_dir: Path, history: "DownloadHistory", transport: httpx.BaseTransport | None = None, @@ -300,7 +300,7 @@ def _download_mp3( ) -> Path | None: """Fetch MP3 manifest and download all ZIP parts.""" try: - manifest = client.fetch_download_manifest(book.isbn, transport=transport) + manifest = client.fetch_download_manifest(book.isbn) except M4BUnavailableError: logger.warning("MP3 manifest not available for %s (%s), skipping", book.title, book.isbn) return None @@ -351,7 +351,7 @@ def _download_cover( Returns Path on success, None on failure (logs warning). """ - from librofm_downloader.client import LibroFmClient + from librofm_downloader.session import LibroFmSession filename = _cover_filename_from_url(url) @@ -368,7 +368,7 @@ def _download_cover( client = httpx.Client( transport=transport, follow_redirects=True, - headers=LibroFmClient.DEFAULT_HEADERS, + headers=LibroFmSession.DEFAULT_HEADERS, ) with client.stream("GET", url) as resp: resp.raise_for_status() @@ -423,7 +423,7 @@ def download_accompanying_files( book: Book, output_dir: Path | str, config: "Config", - client: "LibroFmClient | None" = None, + client: "LibroFmSession | None" = None, transport: httpx.BaseTransport | None = None, progress: "Callable[[int], None] | None" = None, ) -> list[Path]: @@ -435,13 +435,13 @@ def download_accompanying_files( book: The book metadata. output_dir: Directory where accompanying files are placed. config: Config with download_extras / download_covers toggles. - client: Optional LibroFmClient for fetching PDF URLs. + client: Optional LibroFmSession for fetching PDF URLs. transport: Optional httpx transport override for testing. Returns: List of Paths successfully downloaded. """ - from librofm_downloader.client import LibroFmClient + from librofm_downloader.session import LibroFmSession output_dir = Path(output_dir) downloaded: list[Path] = [] @@ -455,7 +455,7 @@ def download_accompanying_files( # Download PDF extras if enabled and available if config.download_extras and book.pdf_extras and client is not None: try: - pdf_url = client.fetch_pdf_extra_url(book.isbn, "map.pdf", transport=transport) + pdf_url = client.fetch_pdf_extra_url(book.isbn, "map.pdf") if pdf_url: result = _download_pdf(pdf_url, "map.pdf", output_dir, transport=transport) if result: diff --git a/librofm_downloader/session.py b/librofm_downloader/session.py new file mode 100644 index 0000000..328d59b --- /dev/null +++ b/librofm_downloader/session.py @@ -0,0 +1,199 @@ +"""HTTP session for Libro.fm API — auth, library fetch, and rate-limited downloads.""" + +from __future__ import annotations + +import threading + +import httpx + +# Maximum concurrent Libro.fm API calls (not CDN downloads). +# Configurable constant — not user-facing. +API_SEMAPHORE_CAPACITY = 3 + + +class AuthError(Exception): + """Authentication failed (bad credentials, network error, etc.).""" + + +class M4BUnavailableError(Exception): + """M4B format is not available for this book (404 from API).""" + + +class LibroFmSession: + """Libro.fm API session with OAuth2 password grant and library fetching. + + Constructs a single shared ``httpx.Client`` at instantiation time. + All endpoint methods reuse this client, so transport injection (for + testing) happens once via the ``transport`` keyword argument. + """ + + 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, + *, + transport: httpx.BaseTransport | None = None, + ): + self._base_url = base_url.rstrip("/") + self._username = username + self._password = password + self._timeout = timeout + self._access_token: str | None = None + self._api_semaphore = threading.Semaphore(API_SEMAPHORE_CAPACITY) + + self._client = httpx.Client( + base_url=self._base_url, + headers=self.DEFAULT_HEADERS, + timeout=self._timeout, + transport=transport, + ) + + def authenticate(self) -> str: + """OAuth2 password grant → returns access_token. + + Uses the shared ``self._client`` (no transport parameter). + After successful auth, stores the Bearer token on the client + headers so all subsequent endpoint calls are authenticated. + + Returns: + The access token string. + + Raises: + AuthError: If credentials are invalid or the request fails. + """ + try: + resp = self._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"] + self._client.headers["Authorization"] = f"Bearer {self._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) -> list[dict]: + """Fetch all books from the user's library, paginating automatically. + + Uses the shared ``self._client`` (no transport parameter). + + 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.") + + all_books: list[dict] = [] + next_url = "/api/v10/library" + + while next_url: + resp = self._client.get(next_url) + resp.raise_for_status() + data = resp.json() + all_books.extend(data.get("audiobooks", [])) + next_url = data.get("next_page") or None + + return all_books + + def fetch_m4b_url(self, isbn: str) -> str: + """Fetch the M4B download URL for a given ISBN. + + Uses the shared ``self._client`` (no transport parameter). + Rate-limited by the API semaphore. + + Args: + isbn: The ISBN of the audiobook. + + Returns: + The CDN URL string for the M4B file. + + Raises: + AuthError: If not authenticated. + M4BUnavailableError: If the book has no M4B format available (404). + """ + if not self._access_token: + raise AuthError("Not authenticated. Call authenticate() first.") + + with self._api_semaphore: + resp = self._client.get(f"/api/v10/audiobooks/{isbn}/packaged_m4b") + + if resp.status_code == 404: + raise M4BUnavailableError(f"M4B not available for ISBN {isbn}") + + resp.raise_for_status() + data = resp.json() + return data["m4b_url"] + + def fetch_download_manifest(self, isbn: str) -> dict: + """Fetch the MP3 download manifest for a given ISBN. + + Uses the shared ``self._client`` (no transport parameter). + Rate-limited by the API semaphore. + + Args: + isbn: The ISBN of the audiobook. + + Returns: + Dict with ``parts`` (list of {url, name}) and + ``tracks`` (list of {number, chapter_title}). + + Raises: + AuthError: If not authenticated. + M4BUnavailableError: If the book has no MP3 format available (404). + """ + if not self._access_token: + raise AuthError("Not authenticated. Call authenticate() first.") + + with self._api_semaphore: + resp = self._client.get("/api/v10/download-manifest", params={"isbn": isbn}) + + if resp.status_code == 404: + raise M4BUnavailableError(f"MP3 manifest not available for ISBN {isbn}") + + resp.raise_for_status() + return resp.json() + + def fetch_pdf_extra_url(self, isbn: str, filename: str) -> str: + """Fetch the PDF extra download URL for a given ISBN and filename. + + Uses the shared ``self._client`` (no transport parameter). + Rate-limited by the API semaphore. + + Args: + isbn: The ISBN of the audiobook. + filename: The name of the PDF file to fetch. + + Returns: + The CDN URL string for the PDF file. + + Raises: + AuthError: If not authenticated. + """ + if not self._access_token: + raise AuthError("Not authenticated. Call authenticate() first.") + + with self._api_semaphore: + resp = self._client.get( + f"/api/v10/library/{isbn}/pdf_extra_url", + params={"filename": filename}, + ) + + resp.raise_for_status() + data = resp.json() + return data["pdf_url"] diff --git a/tests/test_cli.py b/tests/test_cli.py index 682e578..4b3d13d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -14,7 +14,7 @@ class TestCLIHappyPath: """Happy path: valid config, auth succeeds, books are printed.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, ): # Config returns valid credentials mock_config.return_value.username = "alice" @@ -47,11 +47,11 @@ class TestCLIAuthFailure: def test_exits_one_on_auth_failure(self, capsys): """Auth fails → exit code 1 + error message printed.""" - from librofm_downloader.client import AuthError + from librofm_downloader.session import AuthError with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, ): mock_config.return_value.username = "alice" mock_config.return_value.password = "wrong" @@ -79,7 +79,7 @@ class TestCLIHistoryFiltering: """Books in history file don't appear in output.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, ): mock_config.return_value.username = "alice" @@ -124,7 +124,7 @@ class TestCLIDownloadOrchestration: Books without M4B are skipped (not errors).""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, patch("librofm_downloader.cli.Book") as mock_book_cls, @@ -182,7 +182,7 @@ class TestCLIVerbose: """--verbose shows config values and auth status.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, patch("librofm_downloader.cli.Book") as mock_book_cls, @@ -234,7 +234,7 @@ class TestCLILimitFlag: """--limit 2 → only first 2 books are attempted.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, patch("librofm_downloader.cli.Book") as mock_book_cls, @@ -273,7 +273,7 @@ class TestCLILimitFlag: """--limit 0 (default) → all books are processed.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, patch("librofm_downloader.cli.Book") as mock_book_cls, @@ -312,7 +312,7 @@ class TestCLIFormatWiring: """config.format is forwarded to download_book(format_strategy=...).""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, patch("librofm_downloader.cli.Book") as mock_book_cls, @@ -350,7 +350,7 @@ class TestCLIFormatWiring: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, patch("librofm_downloader.cli.Book") as mock_book_cls, @@ -402,7 +402,7 @@ class TestGracefulShutdown: """ with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -439,7 +439,7 @@ class TestGracefulShutdown: """KeyboardInterrupt during library fetch → clean exit.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, ): mock_config.return_value.username = "alice" mock_config.return_value.password = "secret" @@ -472,7 +472,7 @@ class TestIntegrationHappyPath: """Full pipeline: auth + library fetch + 3 downloads → exit 0 + summary.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -513,7 +513,7 @@ class TestIntegrationMixedResult: """2 download (1 M4B, 1 MP3), 1 skipped, 1 fails → summary lists all + exit 0.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -570,11 +570,11 @@ class TestIntegrationFatalAuthFailure: def test_auth_failure_returns_exit_code_1_no_downloads(self, capsys): """Authentication failure → exit code 1, download_book never called.""" - from librofm_downloader.client import AuthError + from librofm_downloader.session import AuthError with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): mock_config.return_value.username = "baduser" @@ -608,7 +608,7 @@ class TestAllBooksFailExitCode: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -672,7 +672,7 @@ class TestCLIHistoryResolution: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, ): mock_config.return_value.username = "alice" @@ -708,7 +708,7 @@ class TestCLIHistoryResolution: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, ): mock_config.return_value.username = "alice" @@ -735,7 +735,7 @@ class TestCLIHistoryResolution: """Explicit --history flag uses the exact path provided.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, ): mock_config.return_value.username = "alice" @@ -775,7 +775,7 @@ class TestCLIConfigResolutionMessages: monkeypatch.chdir(cwd) with ( - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.download_book"), ): mock_instance = mock_client_cls.return_value @@ -806,7 +806,7 @@ class TestCLIConfigResolutionMessages: monkeypatch.chdir(cwd) with ( - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.download_book"), ): mock_instance = mock_client_cls.return_value @@ -862,7 +862,7 @@ class TestCLIMissingFilesErrors: monkeypatch.chdir(cwd) with ( - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.download_book"), ): mock_instance = mock_client_cls.return_value @@ -888,7 +888,7 @@ class TestCLIWorkersFlag: """--workers 8 overrides config.workers=3 → resolved workers = 8.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -919,7 +919,7 @@ class TestCLIWorkersFlag: """No --workers flag uses config.workers (5) instead of default 3.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -948,7 +948,7 @@ class TestCLIWorkersFlag: """--workers 1 is accepted (sequential fallback).""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -993,7 +993,7 @@ class TestParallelWorkers1Parity: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -1029,7 +1029,7 @@ class TestParallelWorkers1Parity: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -1066,7 +1066,7 @@ class TestParallelCtrlCDrain: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -1093,7 +1093,7 @@ class TestParallelCtrlCDrain: """KeyboardInterrupt prints 'Aborting...' or similar message.""" with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -1131,7 +1131,7 @@ class TestParallelSummaryOrdering: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -1173,7 +1173,7 @@ class TestParallelSummaryOrdering: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, patch("librofm_downloader.cli.DownloadReporter") as mock_reporter_cls, @@ -1227,7 +1227,7 @@ class TestParallelConcurrency: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -1267,7 +1267,7 @@ class TestParallelConcurrency: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -1317,7 +1317,7 @@ class TestParallelVerboseMode: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -1349,7 +1349,7 @@ class TestParallelVerboseMode: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -1396,7 +1396,7 @@ class TestParallelPartialFileSafety: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): diff --git a/tests/test_client.py b/tests/test_client.py index 87d9868..16661db 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,4 +1,4 @@ -"""Tests for librofm_downloader.client — TDD vertical slices.""" +"""Tests for librofm_downloader.session — TDD vertical slices.""" import json import logging @@ -6,7 +6,7 @@ import logging import httpx import pytest -from librofm_downloader.client import LibroFmClient, AuthError, M4BUnavailableError +from librofm_downloader.session import LibroFmSession, AuthError, M4BUnavailableError class TestAuthenticate: @@ -14,11 +14,6 @@ class TestAuthenticate: def test_returns_access_token_on_valid_credentials(self): """Valid username/password → access_token returned.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) def token_handler(request: httpx.Request) -> httpx.Response: assert request.method == "POST" @@ -29,36 +24,37 @@ class TestAuthenticate: ) transport = httpx.MockTransport(token_handler) - token = client.authenticate(transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + token = session.authenticate() assert token == "tok_abc123" def test_raises_auth_error_on_invalid_credentials(self): """Wrong password → AuthError with descriptive message.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="wrongpass", - ) def token_handler(request: httpx.Request) -> httpx.Response: return httpx.Response(401, json={"error": "invalid_grant"}) transport = httpx.MockTransport(token_handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="wrongpass", + transport=transport, + ) with pytest.raises(AuthError, match="Auth failed") as exc_info: - client.authenticate(transport=transport) + session.authenticate() assert "401" in str(exc_info.value) def test_sends_required_headers_with_auth_request(self): """X-LibroFm-AppVer and User-Agent headers must be present.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) - headers_captured: dict[str, str] = {} def token_handler(request: httpx.Request) -> httpx.Response: @@ -69,7 +65,13 @@ class TestAuthenticate: ) transport = httpx.MockTransport(token_handler) - client.authenticate(transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() assert headers_captured["x-librofm-appver"] == "7.34.8" assert headers_captured["user-agent"] == "okhttp/5.3.2" @@ -80,12 +82,6 @@ class TestFetchLibrary: def test_returns_books_on_single_page(self): """Single-page library returns all books, no pagination loop.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) - books = [{"isbn": "9781234567890", "title": "Test Book"}] def handler(request: httpx.Request) -> httpx.Response: @@ -99,20 +95,20 @@ class TestFetchLibrary: return httpx.Response(404) transport = httpx.MockTransport(handler) - client.authenticate(transport=transport) - result = client.fetch_library(transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + result = session.fetch_library() assert len(result) == 1 assert result[0]["isbn"] == "9781234567890" def test_paginates_through_all_pages(self): """Multi-page library: follows next_page until exhausted.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) - page1_books = [{"isbn": "978111", "title": "Book A"}] page2_books = [{"isbn": "978222", "title": "Book B"}, {"isbn": "978333", "title": "Book C"}] @@ -132,8 +128,14 @@ class TestFetchLibrary: return httpx.Response(404) transport = httpx.MockTransport(handler) - client.authenticate(transport=transport) - result = client.fetch_library(transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + result = session.fetch_library() assert len(result) == 3 assert result[0]["isbn"] == "978111" @@ -142,14 +144,14 @@ class TestFetchLibrary: def test_raises_auth_error_if_not_authenticated(self): """Calling fetch_library before authenticate → clear error.""" - client = LibroFmClient( + session = LibroFmSession( base_url="https://libro.fm", username="alice", password="secret123", ) with pytest.raises(AuthError, match="Not authenticated"): - client.fetch_library() + session.fetch_library() @@ -158,11 +160,6 @@ class TestFetchM4BUrl: def test_returns_download_url_when_m4b_available(self): """Book with M4B format available → returns CDN URL string.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) def handler(request: httpx.Request) -> httpx.Response: if request.url.path == "/oauth/token": @@ -178,18 +175,19 @@ class TestFetchM4BUrl: return httpx.Response(404) transport = httpx.MockTransport(handler) - client.authenticate(transport=transport) - url = client.fetch_m4b_url("9781234567890", transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + url = session.fetch_m4b_url("9781234567890") assert url == "https://cdn.libro.fm/audiobooks/9781234567890.m4b" def test_raises_m4b_unavailable_on_404(self): """Book without M4B format → raises M4BUnavailableError.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) def handler(request: httpx.Request) -> httpx.Response: if request.url.path == "/oauth/token": @@ -202,10 +200,16 @@ class TestFetchM4BUrl: return httpx.Response(404) transport = httpx.MockTransport(handler) - client.authenticate(transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() with pytest.raises(M4BUnavailableError, match="M4B not available for ISBN 9780000000001"): - client.fetch_m4b_url("9780000000001", transport=transport) + session.fetch_m4b_url("9780000000001") # --------------------------------------------------------------------------- @@ -218,11 +222,6 @@ class TestFetchDownloadManifest: def test_returns_parts_and_tracks_when_available(self): """Book with MP3 format → returns parts list and track metadata.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) def handler(request: httpx.Request) -> httpx.Response: if request.url.path == "/oauth/token": @@ -247,8 +246,14 @@ class TestFetchDownloadManifest: return httpx.Response(404) transport = httpx.MockTransport(handler) - client.authenticate(transport=transport) - manifest = client.fetch_download_manifest("9781234567890", transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + manifest = session.fetch_download_manifest("9781234567890") assert len(manifest["parts"]) == 2 assert manifest["parts"][0]["url"] == "https://cdn.libro.fm/part1.zip" @@ -258,11 +263,6 @@ class TestFetchDownloadManifest: def test_returns_empty_parts_when_no_mp3_available(self): """Book without MP3 format → returns empty manifest (404 or empty).""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) def handler(request: httpx.Request) -> httpx.Response: if request.url.path == "/oauth/token": @@ -275,10 +275,16 @@ class TestFetchDownloadManifest: return httpx.Response(404) transport = httpx.MockTransport(handler) - client.authenticate(transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() with pytest.raises(M4BUnavailableError): - client.fetch_download_manifest("9780000000001", transport=transport) + session.fetch_download_manifest("9780000000001") # --------------------------------------------------------------------------- @@ -291,11 +297,6 @@ class TestFetchPdfExtraUrl: def test_returns_pdf_url_when_available(self): """Book with PDF extra available → returns CDN URL string.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) def handler(request: httpx.Request) -> httpx.Response: if request.url.path == "/oauth/token": @@ -312,29 +313,33 @@ class TestFetchPdfExtraUrl: return httpx.Response(404) transport = httpx.MockTransport(handler) - client.authenticate(transport=transport) - url = client.fetch_pdf_extra_url("9781234567890", "map.pdf", transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + url = session.fetch_pdf_extra_url("9781234567890", "map.pdf") assert url == "https://cdn.libro.fm/pdf/9781234567890/map.pdf" def test_raises_auth_error_if_not_authenticated(self): """Calling fetch_pdf_extra_url before authenticate → clear error.""" - client = LibroFmClient( + session = LibroFmSession( base_url="https://libro.fm", username="alice", password="secret123", ) with pytest.raises(AuthError, match="Not authenticated"): - client.fetch_pdf_extra_url("9781234567890", "map.pdf") - + session.fetch_pdf_extra_url("9781234567890", "map.pdf") # --------------------------------------------------------------------------- # API Rate Limiter — Issue #15 # --------------------------------------------------------------------------- - import threading import time @@ -348,11 +353,6 @@ class TestApiRateLimiter: def test_semaphore_blocks_at_capacity(self): """4 concurrent callers: 3 proceed immediately, 4th blocks until one finishes.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) call_can_finish: threading.Event = threading.Event() state_lock = threading.Lock() @@ -377,13 +377,19 @@ class TestApiRateLimiter: ) transport = httpx.MockTransport(slow_handler) - client.authenticate(transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() errors: list[BaseException] = [] def fetch_thread(isbn: str): try: - client.fetch_m4b_url(isbn, transport=transport) + session.fetch_m4b_url(isbn) except BaseException as exc: errors.append(exc) @@ -406,12 +412,6 @@ class TestApiRateLimiter: def test_semaphore_releases_on_exception(self): """Semaphore is released even when the API call raises an exception.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) - call_number = [1] # Use list for mutability in closure def handler(request: httpx.Request) -> httpx.Response: @@ -430,18 +430,24 @@ class TestApiRateLimiter: ) transport = httpx.MockTransport(handler) - client.authenticate(transport=transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() # First call should succeed (releases semaphore normally) - result = client.fetch_m4b_url("978111", transport=transport) + result = session.fetch_m4b_url("978111") assert result == "https://cdn.libro.fm/test.m4b" # Second call should raise (semaphore must still be released after this) with pytest.raises(M4BUnavailableError): - client.fetch_m4b_url("978222", transport=transport) + session.fetch_m4b_url("978222") # Third call should succeed — proves semaphore was released by the failed call - result3 = client.fetch_m4b_url("978333", transport=transport) + result3 = session.fetch_m4b_url("978333") assert result3 == "https://cdn.libro.fm/test.m4b" def test_cdn_downloads_bypass_semaphore(self): @@ -450,12 +456,6 @@ class TestApiRateLimiter: from librofm_downloader.downloader import download_m4b - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) - # Fill all 3 API semaphore slots with slow calls that block api_calls_blocked: threading.Event = threading.Event() @@ -473,11 +473,17 @@ class TestApiRateLimiter: ) api_transport = httpx.MockTransport(slow_api_handler) - client.authenticate(transport=api_transport) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=api_transport, + ) + session.authenticate() # Occupy all 3 semaphore slots with blocked API calls api_threads = [ - threading.Thread(target=client.fetch_m4b_url, args=(f"978block{i}",), kwargs={"transport": api_transport}) + threading.Thread(target=session.fetch_m4b_url, args=(f"978block{i}",)) for i in range(3) ] for t in api_threads: @@ -509,12 +515,6 @@ class TestApiRateLimiter: def test_authenticate_and_fetch_library_not_limited(self): """authenticate() and fetch_library() do NOT acquire the API semaphore.""" - client = LibroFmClient( - base_url="https://libro.fm", - username="alice", - password="secret123", - ) - # Fill all 3 API semaphore slots with blocked calls api_calls_blocked: threading.Event = threading.Event() @@ -530,12 +530,21 @@ class TestApiRateLimiter: json={"m4b_url": "https://cdn.libro.fm/test.m4b"}, ) + # NOTE: This test uses a separate session for the blocking API calls. + # The session under test gets a different transport so authenticate/fetch_library + # can use a different handler while the blocking calls hold the semaphore. api_transport = httpx.MockTransport(slow_api_handler) - client.authenticate(transport=api_transport) + blocking_session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=api_transport, + ) + blocking_session.authenticate() # Occupy all 3 slots api_threads = [ - threading.Thread(target=client.fetch_m4b_url, args=(f"978block{i}",), kwargs={"transport": api_transport}) + threading.Thread(target=blocking_session.fetch_m4b_url, args=(f"978block{i}",)) for i in range(3) ] for t in api_threads: @@ -543,25 +552,37 @@ class TestApiRateLimiter: time.sleep(0.2) # authenticate() should work fine — it doesn't use the semaphore + # We need a fresh session+transport for this since the old one's auth handler + # would conflict with the slow_api_handler def auth_handler(request: httpx.Request) -> httpx.Response: return httpx.Response( 200, json={"access_token": "tok_new", "token_type": "bearer", "expires_in": 7200}, ) - auth_transport = httpx.MockTransport(auth_handler) - token = client.authenticate(transport=auth_transport) - assert token == "tok_new" - - # fetch_library() should also work — it doesn't use the semaphore def library_handler(request: httpx.Request) -> httpx.Response: return httpx.Response(200, json={"audiobooks": []}) - library_transport = httpx.MockTransport(library_handler) - books = client.fetch_library(transport=library_transport) + def combined_handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return auth_handler(request) + return library_handler(request) + + test_transport = httpx.MockTransport(combined_handler) + test_session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=test_transport, + ) + token = test_session.authenticate() + assert token == "tok_new" + + # fetch_library() should also work — it doesn't use the semaphore + books = test_session.fetch_library() assert books == [] # Clean up api_calls_blocked.set() for t in api_threads: - t.join(timeout=5) \ No newline at end of file + t.join(timeout=5) diff --git a/tests/test_downloader.py b/tests/test_downloader.py index a5627b8..e14f23a 100644 --- a/tests/test_downloader.py +++ b/tests/test_downloader.py @@ -19,7 +19,7 @@ from librofm_downloader.downloader import ( download_book, download_accompanying_files, ) -from librofm_downloader.client import LibroFmClient +from librofm_downloader.session import LibroFmSession from librofm_downloader.history import DownloadHistory @@ -884,8 +884,8 @@ class TestDownloadBook: return httpx.Response(404) transport = httpx.MockTransport(handler) - client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") - client.authenticate(transport=transport) + client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport) + client.authenticate() book = Book( title="History Test Book", @@ -927,8 +927,8 @@ class TestDownloadBook: return httpx.Response(404) transport = httpx.MockTransport(handler) - client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") - client.authenticate(transport=transport) + client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport) + client.authenticate() book = Book( title="No M4B Book", @@ -974,8 +974,8 @@ class TestDownloadBook: return httpx.Response(404) transport = httpx.MockTransport(handler) - client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") - client.authenticate(transport=transport) + client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport) + client.authenticate() book = Book( title="Fail Book", @@ -1016,8 +1016,8 @@ class TestDownloadBook: return httpx.Response(200, content=payload) transport = httpx.MockTransport(handler) - client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") - client.authenticate(transport=transport) + client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport) + client.authenticate() book = Book( title="Standalone Book", @@ -1092,8 +1092,8 @@ class TestFormatStrategy: return httpx.Response(404) transport = httpx.MockTransport(handler) - client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") - client.authenticate(transport=transport) + client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport) + client.authenticate() book = Book(title="M4B Available", authors=["A"], narrators=["N"], isbn="9781111111111") @@ -1151,8 +1151,8 @@ class TestFormatStrategy: return httpx.Response(404) transport = httpx.MockTransport(handler) - client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") - client.authenticate(transport=transport) + client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport) + client.authenticate() book = Book(title="MP3 Fallback Book", authors=["A"], narrators=["N"], isbn="9782222222222") @@ -1212,8 +1212,8 @@ class TestFormatStrategy: return httpx.Response(404) transport = httpx.MockTransport(handler) - client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") - client.authenticate(transport=transport) + client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport) + client.authenticate() book = Book(title="MP3 Only Book", authors=["A"], narrators=["N"], isbn="9783333333333") @@ -1261,8 +1261,8 @@ class TestFormatStrategy: return httpx.Response(404) transport = httpx.MockTransport(handler) - client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") - client.authenticate(transport=transport) + client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport) + client.authenticate() book = Book(title="No M4B Skip", authors=["A"], narrators=["N"], isbn="9780000000000") diff --git a/tests/test_progress.py b/tests/test_progress.py index f9baf52..3dbe0ae 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -157,7 +157,7 @@ class TestFailureIsolationCLI: with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): @@ -218,11 +218,11 @@ class TestFatalVsBookLevel: def test_auth_failure_exits_one_before_downloads(self, capsys): """Auth failure → exit 1, download_book never called.""" from unittest.mock import patch - from librofm_downloader.client import AuthError + from librofm_downloader.session import AuthError with ( patch("librofm_downloader.cli.load_config") as mock_config, - patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls, patch("librofm_downloader.cli.download_book") as mock_download, ): mock_config.return_value.username = "alice" @@ -663,7 +663,7 @@ class TestProgressCallbackWiring: from pathlib import Path from librofm_downloader.book import Book from librofm_downloader.downloader import download_book - from librofm_downloader.client import LibroFmClient + from librofm_downloader.session import LibroFmSession from librofm_downloader.history import DownloadHistory m4b_payload = b"callback-test-data" * 10 # 160 bytes @@ -681,8 +681,8 @@ class TestProgressCallbackWiring: return httpx.Response(404) transport = httpx.MockTransport(handler) - client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") - client.authenticate(transport=transport) + client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport) + client.authenticate() book = Book(title="CB Test", authors=["A"], narrators=["N"], isbn="9781111111111") progress_calls: list[int] = [] diff --git a/tests/test_session.py b/tests/test_session.py new file mode 100644 index 0000000..5d032fb --- /dev/null +++ b/tests/test_session.py @@ -0,0 +1,449 @@ +"""Tests for librofm_downloader.session — TDD vertical slices.""" + +from __future__ import annotations + +import httpx +import pytest + +from librofm_downloader.session import LibroFmSession, AuthError, M4BUnavailableError + + +class TestConstructor: + """LibroFmSession constructor builds a shared internal httpx.Client.""" + + def test_importable_from_session_module(self): + """LibroFmSession can be imported from librofm_downloader.session.""" + assert LibroFmSession is not None + + def test_creates_internal_httpx_client(self): + """Constructor creates self._client as an httpx.Client instance.""" + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + ) + + assert isinstance(session._client, httpx.Client) + + def test_injects_transport_into_internal_client(self): + """When transport= is passed, the internal client uses it for requests.""" + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"ok": True}) + + transport = httpx.MockTransport(handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + + assert isinstance(session._client, httpx.Client) + # Verify the injected transport works by making a request through the internal client + resp = session._client.get("/test") + assert resp.status_code == 200 + assert resp.json() == {"ok": True} + + def test_default_transport_is_none(self): + """When no transport is passed, the client has no custom transport (real HTTP).""" + session = LibroFmSession( + base_url="https://libro.fm", + username="u", + password="p", + ) + + # With transport=None, httpx.Client uses its default transport (real network) + # We just verify the client was created and has the expected base_url + assert session._client.base_url == "https://libro.fm" + + + +class TestAuthenticate: + """OAuth2 password grant authentication — uses shared _client, no transport param.""" + + def test_returns_access_token_on_valid_credentials(self): + """Valid username/password → access_token returned.""" + + def token_handler(request: httpx.Request) -> httpx.Response: + assert request.method == "POST" + assert request.url.path == "/oauth/token" + return httpx.Response( + 200, + json={"access_token": "tok_abc123", "token_type": "bearer", "expires_in": 7200}, + ) + + transport = httpx.MockTransport(token_handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + + token = session.authenticate() # NO transport arg! + + assert token == "tok_abc123" + + def test_raises_auth_error_on_invalid_credentials(self): + """Wrong password → AuthError with descriptive message.""" + + def token_handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(401, json={"error": "invalid_grant"}) + + transport = httpx.MockTransport(token_handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="wrongpass", + transport=transport, + ) + + with pytest.raises(AuthError, match="Auth failed") as exc_info: + session.authenticate() + + assert "401" in str(exc_info.value) + + def test_sends_required_headers_with_auth_request(self): + """X-LibroFm-AppVer and User-Agent headers must be present.""" + headers_captured: dict[str, str] = {} + + def token_handler(request: httpx.Request) -> httpx.Response: + headers_captured.update(dict(request.headers)) + return httpx.Response( + 200, + json={"access_token": "tok_abc123", "token_type": "bearer", "expires_in": 7200}, + ) + + transport = httpx.MockTransport(token_handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + + session.authenticate() + + assert headers_captured["x-librofm-appver"] == "7.34.8" + assert headers_captured["user-agent"] == "okhttp/5.3.2" + + def test_stores_token_on_instance_and_client_headers(self): + """After authenticate(), token is on self._access_token AND in client headers.""" + + def token_handler(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={"access_token": "tok_stored", "token_type": "bearer", "expires_in": 7200}, + ) + + transport = httpx.MockTransport(token_handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + + token = session.authenticate() + + assert token == "tok_stored" + assert session._access_token == "tok_stored" + + + +class TestFetchLibrary: + """Paginated library fetch — GET /api/v10/library, uses shared _client.""" + + def test_returns_books_on_single_page(self): + """Single-page library returns all books, no pagination loop.""" + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + ) + + books = [{"isbn": "9781234567890", "title": "Test Book"}] + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response( + 200, + json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200}, + ) + if request.url.path == "/api/v10/library": + return httpx.Response(200, json={"audiobooks": books}) + return httpx.Response(404) + + transport = httpx.MockTransport(handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + result = session.fetch_library() # NO transport arg! + + assert len(result) == 1 + assert result[0]["isbn"] == "9781234567890" + + def test_paginates_through_all_pages(self): + """Multi-page library: follows next_page until exhausted.""" + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + ) + + page1_books = [{"isbn": "978111", "title": "Book A"}] + page2_books = [{"isbn": "978222", "title": "Book B"}, {"isbn": "978333", "title": "Book C"}] + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response( + 200, + json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200}, + ) + if request.url.path == "/api/v10/library" and "page" not in request.url.params: + return httpx.Response( + 200, + json={"audiobooks": page1_books, "next_page": "/api/v10/library?page=2"}, + ) + if "page=2" in str(request.url): + return httpx.Response(200, json={"audiobooks": page2_books}) # no next_page → stop + return httpx.Response(404) + + transport = httpx.MockTransport(handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + result = session.fetch_library() # NO transport arg! + + assert len(result) == 3 + assert result[0]["isbn"] == "978111" + assert result[1]["isbn"] == "978222" + assert result[2]["isbn"] == "978333" + + def test_raises_auth_error_if_not_authenticated(self): + """Calling fetch_library before authenticate → clear error.""" + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + ) + + with pytest.raises(AuthError, match="Not authenticated"): + session.fetch_library() + + +class TestFetchM4BUrl: + """M4B download URL lookup — GET /api/v10/audiobooks/{isbn}/packaged_m4b.""" + + def test_returns_download_url_when_m4b_available(self): + """Book with M4B format available → returns CDN URL string.""" + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + ) + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response( + 200, + json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200}, + ) + if request.url.path == "/api/v10/audiobooks/9781234567890/packaged_m4b": + return httpx.Response( + 200, + json={"m4b_url": "https://cdn.libro.fm/audiobooks/9781234567890.m4b"}, + ) + return httpx.Response(404) + + transport = httpx.MockTransport(handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + url = session.fetch_m4b_url("9781234567890") # NO transport arg! + + assert url == "https://cdn.libro.fm/audiobooks/9781234567890.m4b" + + def test_raises_m4b_unavailable_on_404(self): + """Book without M4B format → raises M4BUnavailableError.""" + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + ) + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response( + 200, + json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200}, + ) + if request.url.path == "/api/v10/audiobooks/9780000000001/packaged_m4b": + return httpx.Response(404) + return httpx.Response(404) + + transport = httpx.MockTransport(handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + + with pytest.raises(M4BUnavailableError, match="M4B not available for ISBN 9780000000001"): + session.fetch_m4b_url("9780000000001") + + + +# --------------------------------------------------------------------------- +# MP3 download manifest — Issue #6 +# --------------------------------------------------------------------------- + + +class TestFetchDownloadManifest: + """MP3 download manifest — GET /api/v10/download-manifest?isbn=.""" + + def test_returns_parts_and_tracks_when_available(self): + """Book with MP3 format → returns parts list and track metadata.""" + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + ) + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response( + 200, + json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200}, + ) + if request.url.path == "/api/v10/download-manifest" and request.url.params.get("isbn") == "9781234567890": + return httpx.Response( + 200, + json={ + "parts": [ + {"url": "https://cdn.libro.fm/part1.zip", "name": "part01"}, + {"url": "https://cdn.libro.fm/part2.zip", "name": "part02"}, + ], + "tracks": [ + {"number": 1, "chapter_title": "Chapter 1"}, + {"number": 2, "chapter_title": "Chapter 2"}, + ], + }, + ) + return httpx.Response(404) + + transport = httpx.MockTransport(handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + manifest = session.fetch_download_manifest("9781234567890") # NO transport arg! + + assert len(manifest["parts"]) == 2 + assert manifest["parts"][0]["url"] == "https://cdn.libro.fm/part1.zip" + assert manifest["parts"][1]["url"] == "https://cdn.libro.fm/part2.zip" + assert len(manifest["tracks"]) == 2 + assert manifest["tracks"][0]["chapter_title"] == "Chapter 1" + + def test_raises_m4b_unavailable_on_404(self): + """Book without MP3 format → raises M4BUnavailableError.""" + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + ) + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response( + 200, + json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200}, + ) + if request.url.path == "/api/v10/download-manifest": + return httpx.Response(404, json={"error": "not found"}) + return httpx.Response(404) + + transport = httpx.MockTransport(handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + + with pytest.raises(M4BUnavailableError): + session.fetch_download_manifest("9780000000001") + + + +# --------------------------------------------------------------------------- +# PDF extra download URL — Issue #7 / Cycle 6 +# --------------------------------------------------------------------------- + + +class TestFetchPdfExtraUrl: + """PDF extra download URL — GET /api/v10/library/{isbn}/pdf_extra_url?filename=.""" + + def test_returns_pdf_url_when_available(self): + """Book with PDF extra available → returns CDN URL string.""" + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + ) + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response( + 200, + json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200}, + ) + if request.url.path == "/api/v10/library/9781234567890/pdf_extra_url": + assert request.url.params.get("filename") == "map.pdf" + return httpx.Response( + 200, + json={"pdf_url": "https://cdn.libro.fm/pdf/9781234567890/map.pdf"}, + ) + return httpx.Response(404) + + transport = httpx.MockTransport(handler) + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + transport=transport, + ) + session.authenticate() + url = session.fetch_pdf_extra_url("9781234567890", "map.pdf") # NO transport arg! + + assert url == "https://cdn.libro.fm/pdf/9781234567890/map.pdf" + + def test_raises_auth_error_if_not_authenticated(self): + """Calling fetch_pdf_extra_url before authenticate → clear error.""" + session = LibroFmSession( + base_url="https://libro.fm", + username="alice", + password="secret123", + ) + + with pytest.raises(AuthError, match="Not authenticated"): + session.fetch_pdf_extra_url("9781234567890", "map.pdf")