From 33aa80b7aab7e37bb1ae4fde2fe29a12297242e5 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 3 Jun 2026 12:56:41 +0200 Subject: [PATCH] feat(downloader): add M4B download pipeline with resume (closes #5) Add streaming chunked M4B download via .partial files and atomic rename, resume support through HTTP Range headers, full CLI orchestration loop, --verbose flag, and config/secrets templates. Fix 4 API-shape bugs found during live testing: library endpoint returns audiobooks not books, M4B endpoint returns m4b_url not url, narrators nested under audiobook_info, and ISBN int/str type mismatch in history lookup causing re-downloads. 12 new tests (109 total). 6 books downloaded live (~2.9 GB). --- .pi/agent/AGENTS.md | 2 + CHANGELOG.md | 22 +- config.yaml | 19 + ...-slice-3b-live-testing-fixes-issue5_log.md | 127 ++++++ librofm_downloader/cli.py | 132 ++++++- librofm_downloader/client.py | 42 +- librofm_downloader/downloader.py | 123 ++++++ librofm_downloader/history.py | 4 +- tests/test_cli.py | 100 +++++ tests/test_client.py | 64 ++- tests/test_downloader.py | 369 +++++++++++++++++- 11 files changed, 989 insertions(+), 15 deletions(-) create mode 100644 config.yaml create mode 100644 docs/devlog/20260603-slice-3b-live-testing-fixes-issue5_log.md diff --git a/.pi/agent/AGENTS.md b/.pi/agent/AGENTS.md index ca08a0c..6044076 100644 --- a/.pi/agent/AGENTS.md +++ b/.pi/agent/AGENTS.md @@ -8,5 +8,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste | Date | Type | File | Summary | |------|------|------|---------| +| 2026-06-03 | issue | [20260603-slice-3b-live-testing-fixes-issue5_log.md](docs/devlog/20260603-slice-3b-live-testing-fixes-issue5_log.md) | **Issue #5 Live Fixes:** 4 critical API-shape bugs found & fixed (audiobooks key, m4b_url key, nested narrators, ISBN int/str). Download loop wired. `--verbose` flag. **109 tests**, 6 books downloaded (~2.9 GB) · **11/11 AC** | +| 2026-06-03 | slice | [20260603-slice-3b-m4b-download-pipeline-issue5_log.md](docs/devlog/20260603-slice-3b-m4b-download-pipeline-issue5_log.md) | **Issue #5 TDD:** M4B download pipeline — client endpoint, streaming downloader with resume, path integration, history post-download, CLI orchestration. 11 new tests, **108 total** · **11/11 AC** | | 2026-06-03 | slice | [20260603-slice-3a-path-resolution-and-sanitization-issue4_log.md](docs/devlog/20260603-slice-3a-path-resolution-and-sanitization-issue4_log.md) | **Issue #4 Complete:** Path resolution + sanitization + Book model + custom patterns. 56 new tests, **97 total** · **16/16 AC** | | 2026-06-03 | issue | [20260603-project-scaffolding-and-config-module-issue2_log.md](docs/devlog/20260603-project-scaffolding-and-config-module-issue2_log.md) | **Issue #2 Complete:** pyproject.toml + venv + config module (load/merge/validate) + 25 tests. 11/11 AC met | diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ed593e..6e3e365 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,11 +8,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- M4B download pipeline: streaming chunked download with .partial files, + atomic rename to .m4b, resume support via HTTP Range header +- `fetch_m4b_url()` client method for M4B download URL lookup +- `download_book()` orchestration: resolve path → query M4B → download → + write history; returns None when book has no M4B available +- Full CLI download loop with per-book status, summary counts, and --verbose + flag showing config/auth/library/download details +- `config.yaml` template and `secrets.yaml` gitignored credentials file +- 12 new tests covering M4B query, streaming download, resume, path + integration, subdirectory logic, history post-download, skip behavior, + and verbose output (109 total) + +### Fixed +- Library endpoint key mismatch: API returns "audiobooks" not "books" +- M4B endpoint key mismatch: API returns "m4b_url" not "url" +- Narrators nested under `audiobook_info.narrators` in API response +- ISBN type mismatch in history lookup: JSON keys are strings but API + returns ISBN as integer — added str() coercion in find/is_downloaded +- Missing download loop in CLI run() function (listed books but never downloaded) + +### Changed - Initial project scaffolding: pyproject.toml, package structure, test suite - Config module with YAML loading, secrets deep-merge, validation, and defaults - OAuth2 client with password grant auth and paginated library fetch - Download history tracking with corrupt JSON recovery -- CLI skeleton wiring config → auth → library → filter → print - Path resolution with default conditional patterns and custom token substitution - Filesystem-safe component sanitization (illegal chars, control chars, colons) - Immutable Book dataclass for typed book metadata diff --git a/config.yaml b/config.yaml new file mode 100644 index 0000000..348c048 --- /dev/null +++ b/config.yaml @@ -0,0 +1,19 @@ +# libro.fm downloader configuration +# This file is safe to commit — no credentials here. +# Credentials go in secrets.yaml (which is gitignored). + +librofm: + # Audio format preference + # m4b_mp3_fallback — try M4B first, fall back to MP3 ZIP (default) + # mp3_only — download MP3 ZIP only + # m4b_only — download M4B only, skip if unavailable + format: m4b_mp3_fallback + + # Where downloaded audiobooks are saved + output_dir: ./audiobooks + + # Whether to download PDF extras when available + download_extras: true + + # Whether to download cover art when available + download_covers: true diff --git a/docs/devlog/20260603-slice-3b-live-testing-fixes-issue5_log.md b/docs/devlog/20260603-slice-3b-live-testing-fixes-issue5_log.md new file mode 100644 index 0000000..5039ab4 --- /dev/null +++ b/docs/devlog/20260603-slice-3b-live-testing-fixes-issue5_log.md @@ -0,0 +1,127 @@ +# Slice 3b: Live Testing Fixes & CLI Polish (Issue #5) + +> **Date:** 2026-06-03 +> **Type:** issue +> **Reference:** [Issue #5](https://github.com/AlexKucera/librofm-downloader/issues/5) + +## Goal + +After completing TDD for the M4B download pipeline (109 tests passing), run against the **real Libro.fm API** to validate end-to-end behavior. Fix any discrepancies between mocked test assumptions and actual API response shapes. + +## What Was Done + +### Live API Testing — Discovered 4 Critical Bugs + +Ran `python -m librofm_downloader.cli --config config.yaml --secrets secrets.yaml -v` against the real Libro.fm API with valid credentials. Found and fixed: + +1. **`fetch_library()` returned 0 books** — Code used `data.get("books", [])` but API returns `"audiobooks"` key +2. **`fetch_m4b_url()` crashed with `KeyError: 'url'`** — Code used `data["url"]` but API returns `"m4b_url"` key +3. **Narrators always showed `?`** — Narrators are nested inside `audiobook_info.narrators`, not top-level +4. **Books re-downloaded every run** — JSON dict keys are always strings; API returns ISBNs as integers. `is_downloaded(9781250431516)` looked up int key → never matched string key `"9781250431516"` in history + +### CLI Improvements + +- **Wired the missing download loop** into `run()` — the function listed books then returned 0 without ever calling `download_book()` +- **Added `--verbose` / `-v` flag** — prints config values, auth status, library count, per-book authors/narrators, file sizes in bytes, full tracebacks on failure +- **Added `argparse` entry point** at `__main__` so script can be run directly as `python -m librofm_downloader.cli` +- **Fixed nested field extraction** in CLI loop: + - `narrators`: extracted from `raw_book["audiobook_info"]["narrators"]` with fallback to top-level + - `pdf_extras`: extracted from `raw_book["audiobook_info"]["pdf_extras"]` (API returns list, not bool) + +### Config Files Created + +- **`config.yaml`** — committed-safe config with all options documented inline (format, output_dir, download_extras, download_covers) +- **`secrets.yaml`** — gitignored credentials file template + +### Test Updates + +Updated all mock-based tests to match real API response shape: +- `test_client.py`: `books` → `audiobooks` in all library mock responses; `url` → `m4b_url` in M4B mock responses +- `test_downloader.py`: `url` → `m4b_url` in all orchestration mock responses +- Added `TestCLIVerbose::test_verbose_prints_config_and_auth_details` + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Fix history lookup with `str(isbn)` coercion | JSON keys are always strings; API returns ISBN as int. Coercion in `find()` and `is_downloaded()` makes both sides string comparison. Safer than changing HistoryEntry.isbn type which would break serialization. | +| Extract narrators/pdf_extras from `audiobook_info` in CLI only (not client) | Client returns raw API dict; transformation happens at the boundary where Book dataclass is constructed. Keeps client layer thin and honest about what the API actually returns. | +| `--verbose` flag instead of always-verbose | Default output stays clean for cron/automation use; verbose available for debugging. Follows Unix convention. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| **0 books in library** | `fetch_library()` used `.get("books", [])` but real API key is `"audiobooks"` | Changed to `.get("audiobooks", [])`. Mock tests used wrong key name — updated all mocks. | +| **KeyError 'url' on M4B fetch** | Real API returns `"m4b_url"` not `"url"` | Changed to `data["m4b_url"]`. Updated all mock responses. | +| **Narrators always empty (`?`)** | Narrators nested under `audiobook_info.narrators` in API response; code read top-level `narrators` key | Added `audiobook_info = raw_book.get("audiobook_info", {}) or {}` then `audiobook_info.get("narrators", [])` with fallback | +| **Books re-download every run despite history** | JSON dict keys are `str`; Libro.fm API returns ISBN as `int`. `history._data` has `"978..."` but lookup uses `978...` (int) → never matches | Added `str(isbn)` coercion in `find()` and `is_downloaded()` | +| **Script silently does nothing** | `run()` had no download loop wired — it fetched books, filtered them, printed count, returned 0 | Rewrote `run()` with full 6-stage pipeline: config→auth→library→filter→download→summary | +| **SyntaxError on ternary** | Wrote `(x if y else []) if y else []` which Python can't parse | Simplified to `bool(audiobook_info.get("pdf_extras")) if audiobook_info else False` | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `librofm_downloader/client.py` | `books` → `audiobooks`; `url` → `m4b_url` | +| `librofm_downloader/cli.py` | Full download loop wired; `--verbose` flag; argparse entry point; nested narrator/pdf_extras extraction | +| `librofm_downloader/history.py` | `str(isbn)` coercion in `find()` and `is_downloaded()` | +| `config.yaml` | New file — committed-safe configuration template | +| `secrets.yaml` | New file — gitignored credentials template | +| `tests/test_client.py` | Updated mock keys to match real API (`audiobooks`, `m4b_url`) | +| `tests/test_downloader.py` | Updated mock keys to match real API (`m4b_url`) | +| `tests/test_cli.py` | Added `TestCLIVerbose` class (1 test) | + +## Live Test Results + +**6 books downloaded successfully (~2.9 GB total):** + +| Book | Size | Path Pattern | +|------|------|-------------| +| This Story Might Save Your Life | 296 MB | Author/Title/Title.m4b (subdir — has PDF extras) | +| The River Has Roots | 108 MB | Author/Title/Title.m4b (subdir — has cover) | +| Harry Potter und der Feuerkelch | 654 MB | Author/Series/Book N Title/Title.m4b (series+subdir) | +| King Sorrow | 724 MB | Author/Title.m4b (flat — no extras/cover) | +| Alien Clay | 387 MB | Author/Title/Title.m4b (subdir — has PDF extras) | +| The Secret of Secrets | 634 MB | Author/Series/Book N Title/Title.m4b (series+subdir) | + +**Re-run correctly shows:** `6 already downloaded, 0 new` → `All caught up! No new books to download.` + +## Test Summary + +**109 tests passing** (up from 108 — added 1 verbose test): + +``` +tests/test_cli.py :: 5 passed (+1 verbose) +tests/test_client.py :: 7 passed (keys fixed) +tests/test_config.py :: 20 passed +tests/test_downloader.py :: 67 passed (keys fixed) +tests/test_history.py :: 10 passed (str() coercion) +─────────────────────────────────────────── +Total :: 109 passed +``` + +## Acceptance Criteria Status (re-verified against live API) + +- [x] M4B metadata query returns URL when available ✓ (live-tested, 6/6 books) +- [x] M4B query raises on 404 ✓ (mock-tested) +- [x] Download writes to `.partial` during transfer ✓ (verified file creation) +- [x] Atomic rename to `.m4b` on completion ✓ (no .partial files left behind) +- [x] Resume via Range header ✓ (mock-tested with strict Range validation) +- [x] Resume from correct byte offset ✓ (mock-tested) +- [x] Output path follows Slice 3a pattern + sanitization ✓ (all 6 paths correct) +- [x] Subdirectory when extras present; flat otherwise ✓ (mixed: 4 subdir, 2 flat) +- [x] History entry only after successful download ✓ (6 entries written) +- [x] Book without M4B skipped ✓ (mock-tested) +- [x] All tests pass ✓ (**109/109**) + +## Open Items & Next Steps + +- [ ] **MP3 fallback (Issue #5 mentions):** Books without M4B currently just skipped. Next slice should implement MP3 download manifest parsing + ZIP part extraction. +- [ ] **Progress bar:** No progress indicator during large downloads (~300-700MB each). Rich Progress bar would improve UX. +- [ ] **Concurrency:** Sequential download of 6 books took ~9 min. Parallel downloads could be faster. +- [ ] **Cover art / PDF extras downloading:** Config has flags for these but they're not implemented yet. +- [ ] **`download_history.json` cleanup:** ISBN type inconsistency in stored data (int vs str). Consider normalizing on next write. + +--- +*Log written by write-log skill* diff --git a/librofm_downloader/cli.py b/librofm_downloader/cli.py index 6f456a2..6ee51df 100644 --- a/librofm_downloader/cli.py +++ b/librofm_downloader/cli.py @@ -1,12 +1,14 @@ -"""CLI entry point — wire config → auth → fetch library → filter → print.""" +"""CLI entry point — wire config → auth → fetch library → download → history.""" import sys +from pathlib import Path 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 +from librofm_downloader.downloader import Book, download_book console = Console() @@ -15,18 +17,43 @@ def run( config_path: str = "config.yaml", secrets_path: str = "secrets.yaml", history_path: str = "download_history.json", + verbose: bool = False, ) -> int: - """Main pipeline: load config → auth → fetch library → filter → print. + """Main pipeline: load config → auth → fetch library → filter → download → summary. + + Args: + config_path: Path to config.yaml. + secrets_path: Path to secrets.yaml (gitignored). + history_path: Path to download_history.json. + verbose: Print extra detail (URLs, paths, API responses). Returns: Exit code: 0 on success, 1 on failure. """ + if verbose: + console.print("[dim]── config ──────────────────────────────────────[/dim]") + console.print(f" config: {config_path}") + console.print(f" secrets: {secrets_path}") + console.print(f" history: {history_path}") + + # 1. Load config try: config = load_config(config_path, secrets_path) except ConfigError as exc: console.print(f"[red]Config error:[/red] {exc}") return 1 + if verbose: + console.print(f" format: {config.format}") + console.print(f" output: {config.output_dir}") + console.print(f" extras: {config.download_extras}") + console.print(f" covers: {config.download_covers}") + console.print(f" user: {config.username}") + + # 2. Authenticate + if verbose: + console.print("[dim]── auth ────────────────────────────────────────[/dim]") + client = LibroFmClient( username=config.username, password=config.password, @@ -38,23 +65,116 @@ def run( console.print(f"[red]Authentication failed:[/red] {exc}") return 1 + if verbose: + console.print(" [green]✓[/green] authenticated") + + # 3. Fetch library + if verbose: + console.print("[dim]── library ─────────────────────────────────────[/dim]") + try: books = client.fetch_library() except Exception as exc: console.print(f"[red]Failed to fetch library:[/red] {exc}") return 1 + if verbose: + console.print(f" {len(books)} book(s) in library") + + # 4. Filter already-downloaded + if verbose: + console.print("[dim]── filtering ───────────────────────────────────[/dim]") + history = DownloadHistory(history_path) new_books = [b for b in books if not history.is_downloaded(b.get("isbn", ""))] + if verbose: + downloaded_count = len(books) - len(new_books) + console.print(f" {downloaded_count} already downloaded, {len(new_books)} new") + if not new_books: console.print("[green]All caught up! No new books to download.[/green]") return 0 + # 5. Download loop 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]") + + downloaded = 0 + skipped = 0 + failed = 0 + + for raw_book in new_books: + title = raw_book.get("title", "Unknown") + isbn = raw_book.get("isbn", "?") + authors = raw_book.get("authors", []) + # Narrators are nested inside audiobook_info in the API response + audiobook_info = raw_book.get("audiobook_info", {}) or {} + narrators = audiobook_info.get("narrators", []) or raw_book.get("narrators", []) + console.print(f" ⬇ {title} [dim]({isbn})[/dim]") + + if verbose: + console.print(f" authors: {', '.join(authors) or '?'}") + console.print(f" narrators: {', '.join(narrators) or '?'}") + + book = Book( + title=title, + authors=authors, + narrators=narrators, + isbn=isbn, + series=raw_book.get("series", ""), + series_num=raw_book.get("series_num"), + cover_url=raw_book.get("cover_url", ""), + # pdf_extras is a list inside audiobook_info in the API response + pdf_extras=bool(audiobook_info.get("pdf_extras")) if audiobook_info else False, + publication_year=raw_book.get("publication_year"), + publication_month=raw_book.get("publication_month"), + publication_day=raw_book.get("publication_day"), + ) + + try: + result = download_book( + book=book, + client=client, + output_base=config.output_dir, + history=history, + ) + if result is None: + console.print(f" [yellow]⏭ Skipped (no M4B available)[/yellow]") + skipped += 1 + else: + console.print(f" [green]✓ Downloaded → {result}[/green]") + if verbose: + console.print(f" [dim] {result.stat().st_size:,} bytes[/dim]") + downloaded += 1 + except Exception as exc: + console.print(f" [red]✗ Failed: {exc}[/red]") + if verbose: + import traceback + traceback.print_exc() + failed += 1 + + # 6. Summary + console.print(f"\n[bold]Summary:[/bold] {downloaded} downloaded, {skipped} skipped, {failed} failed") + + if verbose: + console.print("[dim]── done ────────────────────────────────────────[/dim]") return 0 + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Download audiobooks from Libro.fm") + parser.add_argument("--config", default="config.yaml", help="Path to config.yaml") + parser.add_argument("--secrets", default="secrets.yaml", help="Path to secrets.yaml") + parser.add_argument("--history", default="download_history.json", help="Path to download history JSON") + parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output (URLs, sizes, tracebacks)") + args = parser.parse_args() + + sys.exit(run( + config_path=args.config, + secrets_path=args.secrets, + history_path=args.history, + verbose=args.verbose, + )) diff --git a/librofm_downloader/client.py b/librofm_downloader/client.py index 18e9fca..b1889b1 100644 --- a/librofm_downloader/client.py +++ b/librofm_downloader/client.py @@ -7,6 +7,10 @@ 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 LibroFmClient: """Libro.fm API client with OAuth2 password grant and library fetching.""" @@ -93,7 +97,43 @@ class LibroFmClient: resp = client.get(next_url) resp.raise_for_status() data = resp.json() - all_books.extend(data.get("books", [])) + 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, + ) + + 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"] diff --git a/librofm_downloader/downloader.py b/librofm_downloader/downloader.py index f9ec8bc..7d5aba4 100644 --- a/librofm_downloader/downloader.py +++ b/librofm_downloader/downloader.py @@ -3,8 +3,17 @@ Pure logic module — no I/O, no network. All deterministic string manipulation. """ +import logging import re from dataclasses import dataclass +from pathlib import Path + +import httpx + +from librofm_downloader.client import M4BUnavailableError +from librofm_downloader.history import HistoryEntry + +logger = logging.getLogger(__name__) # Characters that are unsafe in filesystem path components _ILLEGAL_CHARS = str.maketrans("", "", "<>/\\|?*") @@ -147,3 +156,117 @@ def needs_subdirectory(book: Book) -> bool: Returns True when PDF extras or cover art are present. """ return bool(book.pdf_extras) or bool(book.cover_url) + + +# --------------------------------------------------------------------------- +# M4B streaming download +# --------------------------------------------------------------------------- + +# Constants for M4B download + +CHUNK_SIZE = 8 * 1024 * 1024 # 8 MB + + +def download_m4b( + url: str, + output_path: Path | str, + transport: httpx.BaseTransport | None = None, +) -> Path: + """Download an M4B file via streaming chunks. + + Writes to ``{output_path}.partial`` during transfer, then atomically + renames to the final ``{output_path}`` on completion. + + Args: + url: The CDN URL for the M4B file. + output_path: Destination path (will have .m4b extension). + transport: Optional httpx transport override for testing. + + Returns: + The Path of the completed .m4b file. + """ + output_path = Path(output_path) + partial_path = output_path.with_suffix(output_path.suffix + ".partial") + + # Ensure parent directory exists + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Resume support: detect existing partial file + resume_from = 0 + if partial_path.exists(): + resume_from = partial_path.stat().st_size + logger.info("Resuming download from byte %d", resume_from) + + headers: dict[str, str] = {} + if resume_from > 0: + headers["Range"] = f"bytes={resume_from}-" + + client = httpx.Client(transport=transport, follow_redirects=True) + + mode = "ab" if resume_from > 0 else "wb" + + with client.stream("GET", url, headers=headers) as resp: + resp.raise_for_status() + + with open(partial_path, mode) as f: + for chunk in resp.iter_bytes(chunk_size=CHUNK_SIZE): + f.write(chunk) + + # Atomic rename from .partial to final filename + partial_path.rename(output_path) + + logger.info("Downloaded %s → %s", url, output_path) + return output_path + + +def download_book( + book: Book, + client: "LibroFmClient", + output_base: Path | str, + history: "DownloadHistory", + transport: httpx.BaseTransport | None = None, +) -> Path | None: + """Orchestrate a single book download: resolve path → query M4B → download → history. + + Args: + book: The book metadata. + client: Authenticated LibroFmClient instance. + output_base: Base directory for downloads. + history: DownloadHistory instance to record successful downloads. + transport: Optional httpx transport override for testing. + + Returns: + Path to the downloaded file, or None if M4B is unavailable (book skipped). + """ + from datetime import datetime, timezone + + # 1. Resolve output path using Slice 3a logic + relative = resolve_path(book) + title_sanitized = sanitize(book.title) + + if needs_subdirectory(book): + output_path = Path(output_base) / relative / f"{title_sanitized}.m4b" + else: + output_path = Path(output_base) / f"{relative}.m4b" + + # 2. Query M4B availability + try: + m4b_url = client.fetch_m4b_url(book.isbn, transport=transport) + except M4BUnavailableError: + logger.info("Skipping %s (%s): no M4B available", book.title, book.isbn) + return None + + # 3. Download + result = download_m4b(m4b_url, output_path, transport=transport) + + # 4. Write history entry (only after successful complete download) + entry = HistoryEntry( + isbn=book.isbn, + title=book.title, + format="m4b", + path=str(result), + downloaded_at=datetime.now(timezone.utc).isoformat(), + ) + history.write(entry) + + return result diff --git a/librofm_downloader/history.py b/librofm_downloader/history.py index 1d88d83..6cf6e7b 100644 --- a/librofm_downloader/history.py +++ b/librofm_downloader/history.py @@ -41,14 +41,14 @@ class DownloadHistory: 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) + entry_dict = self._data.get(str(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 + return str(isbn) in self._data def write(self, entry: HistoryEntry) -> None: """Persist a history entry to disk.""" diff --git a/tests/test_cli.py b/tests/test_cli.py index c410d56..f52eba4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -106,3 +106,103 @@ class TestCLIHistoryFiltering: assert "Old Book" not in captured.out assert "New Book A" in captured.out assert "New Book B" in captured.out + + + +class TestCLIDownloadOrchestration: + """CLI downloads books and reports results.""" + + def test_downloads_books_and_reports_summary(self, capsys): + """Each undownloaded book: resolve → query M4B → download → history. + 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.DownloadHistory") as mock_history_cls, + patch("librofm_downloader.cli.download_book") as mock_download, + patch("librofm_downloader.cli.Book") as mock_book_cls, + ): + mock_config.return_value.username = "alice" + mock_config.return_value.password = "secret" + mock_config.return_value.output_dir = "./audiobooks" + + mock_instance = mock_client_cls.return_value + mock_instance.authenticate.return_value = None + + # 3 new books + raw_books = [ + {"isbn": "978111", "title": "M4B Book", "authors": ["A1"], + "narrators": ["N1"]}, + {"isbn": "978222", "title": "No M4B Book", "authors": ["A2"], + "narrators": ["N2"]}, + {"isbn": "978333", "title": "Another M4B", "authors": ["A3"], + "narrators": ["N3"]}, + ] + mock_instance.fetch_library.return_value = raw_books + + # All are new (not in history) + mock_history_instance = mock_history_cls.return_value + mock_history_instance.is_downloaded.return_value = False + + # download_book returns Path for success, None for skip + from pathlib import Path + mock_download.side_effect = [ + Path("/audiobooks/A1/M4B Book.m4b"), # success + None, # no M4B available (skipped) + Path("/audiobooks/A3/Another M4B.m4b"), # success + ] + + exit_code = run( + config_path="/fake/config.yaml", + secrets_path="/fake/secrets.yaml", + history_path="/fake/history.json", + ) + + assert exit_code == 0 + captured = capsys.readouterr() + # Summary should show downloads + skips + assert "downloaded" in captured.out.lower() or "978111" in captured.out or "M4B Book" in captured.out + + + +class TestCLIVerbose: + """Verbose flag prints extra detail at each pipeline stage.""" + + def test_verbose_prints_config_and_auth_details(self, capsys): + """--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.DownloadHistory") as mock_history_cls, + patch("librofm_downloader.cli.download_book") as mock_download, + patch("librofm_downloader.cli.Book") as mock_book_cls, + ): + mock_config.return_value.username = "alice" + mock_config.return_value.password = "secret" + mock_config.return_value.output_dir = "./audiobooks" + mock_config.return_value.format = "m4b_mp3_fallback" + + mock_instance = mock_client_cls.return_value + mock_instance.authenticate.return_value = None + mock_instance.fetch_library.return_value = [ + {"isbn": "978111", "title": "Verbose Book", "authors": ["A"], "narrators": ["N"]}, + ] + + mock_history_cls.return_value.is_downloaded.return_value = False + mock_download.return_value = None # skipped (no M4B) + + exit_code = run( + config_path="/fake/config.yaml", + secrets_path="/fake/secrets.yaml", + history_path="/fake/history.json", + verbose=True, + ) + + assert exit_code == 0 + captured = capsys.readouterr() + # Verbose sections should appear + assert "config" in captured.out.lower() + assert "auth" in captured.out.lower() + assert "alice" in captured.out + assert "m4b_mp3_fallback" in captured.out + assert "1 book(s) in library" in captured.out or "library" in captured.out.lower() diff --git a/tests/test_client.py b/tests/test_client.py index 4610696..cf45390 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -6,7 +6,7 @@ import logging import httpx import pytest -from librofm_downloader.client import LibroFmClient, AuthError +from librofm_downloader.client import LibroFmClient, AuthError, M4BUnavailableError class TestAuthenticate: @@ -95,7 +95,7 @@ class TestFetchLibrary: json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200}, ) if request.url.path == "/api/v10/library": - return httpx.Response(200, json={"books": books}) + return httpx.Response(200, json={"audiobooks": books}) return httpx.Response(404) transport = httpx.MockTransport(handler) @@ -125,10 +125,10 @@ class TestFetchLibrary: if request.url.path == "/api/v10/library" and "page" not in request.url.params: return httpx.Response( 200, - json={"books": page1_books, "next_page": "/api/v10/library?page=2"}, + json={"audiobooks": page1_books, "next_page": "/api/v10/library?page=2"}, ) if "page=2" in str(request.url): - return httpx.Response(200, json={"books": page2_books}) # no next_page → stop + return httpx.Response(200, json={"audiobooks": page2_books}) # no next_page → stop return httpx.Response(404) transport = httpx.MockTransport(handler) @@ -150,3 +150,59 @@ class TestFetchLibrary: with pytest.raises(AuthError, match="Not authenticated"): client.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.""" + client = LibroFmClient( + 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) + client.authenticate(transport=transport) + url = client.fetch_m4b_url("9781234567890", transport=transport) + + 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": + 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) + client.authenticate(transport=transport) + + with pytest.raises(M4BUnavailableError, match="M4B not available for ISBN 9780000000001"): + client.fetch_m4b_url("9780000000001", transport=transport) diff --git a/tests/test_downloader.py b/tests/test_downloader.py index d1bb42d..9777b78 100644 --- a/tests/test_downloader.py +++ b/tests/test_downloader.py @@ -1,8 +1,20 @@ """Tests for librofm_downloader.downloader — TDD vertical slices.""" +import httpx import pytest +from pathlib import Path +import tempfile -from librofm_downloader.downloader import Book, needs_subdirectory, resolve_path, sanitize +from librofm_downloader.downloader import ( + Book, + needs_subdirectory, + resolve_path, + sanitize, + download_m4b, + download_book, +) +from librofm_downloader.client import LibroFmClient +from librofm_downloader.history import DownloadHistory class TestSanitizeIllegalChars: @@ -412,3 +424,358 @@ class TestNeedsSubdirectory: isbn="9780000000001", ) assert needs_subdirectory(book) is False + + +# --------------------------------------------------------------------------- +# M4B streaming download +# --------------------------------------------------------------------------- + + +class TestDownloadM4B: + """Streaming chunked download with .partial → atomic rename to .m4b.""" + + def test_downloads_and_renames_to_m4b(self): + """Successful download writes .partial then renames to final .m4b file.""" + import io + + # 24 bytes of fake M4B data (3 chunks of 8 bytes each) + payload = b"fake-m4b-audio-data-!!" * 3 # 72 bytes + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, content=payload, headers={"content-length": str(len(payload))}) + + transport = httpx.MockTransport(handler) + + with tempfile.TemporaryDirectory() as tmpdir: + output_path = Path(tmpdir) / "output.m4b" + result = download_m4b( + url="https://cdn.example.com/book.m4b", + output_path=output_path, + transport=transport, + ) + + # Final .m4b file exists with correct content + assert output_path.exists() + assert output_path.read_bytes() == payload + # No .partial file left behind + assert not Path(str(output_path) + ".partial").exists() + # Result is the final path + assert result == output_path + + def test_resumes_from_partial_file(self): + """Existing .partial file → sends Range header, appends from offset.""" + # First "download" writes 30 bytes + first_chunk = b"A" * 30 + # Server has 72 bytes total; client needs last 42 + remaining = b"B" * 42 + full_payload = first_chunk + remaining + range_header_seen: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + range_header_seen.append(request.headers.get("range", "")) + # Only accept requests with correct Range header for resume + rh = request.headers.get("range") + if rh == "bytes=30-": + return httpx.Response( + 206, + content=remaining, + headers={ + "content-range": f"bytes 30-{len(full_payload)-1}/{len(full_payload)}", + "content-length": str(len(remaining)), + }, + ) + # Reject any request without proper Range header + return httpx.Response(400, text="Expected Range header") + + transport = httpx.MockTransport(handler) + + with tempfile.TemporaryDirectory() as tmpdir: + output_path = Path(tmpdir) / "resume_test.m4b" + partial_path = Path(str(output_path) + ".partial") + + # Pre-create partial file simulating interrupted download + output_path.parent.mkdir(parents=True, exist_ok=True) + partial_path.write_bytes(first_chunk) + + result = download_m4b( + url="https://cdn.example.com/book.m4b", + output_path=output_path, + transport=transport, + ) + + # Verify Range header was sent with correct offset + assert "bytes=30-" in range_header_seen + # Final file has complete content + assert output_path.exists() + assert output_path.read_bytes() == full_payload + # No .partial left behind + assert not partial_path.exists() + + def test_output_path_uses_resolved_sanitized_path(self): + """Download goes to the resolved+sanitized path for the book's metadata.""" + payload = b"m4b-data-here" + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, content=payload) + + transport = httpx.MockTransport(handler) + + book = Book( + title="Test: A Story", + authors=["O'Brien, Jane"], + narrators=["Narrator One"], + isbn="9789876543210", + series="Cool Series", + series_num=3, + ) + + with tempfile.TemporaryDirectory() as tmpdir: + base_dir = Path(tmpdir) / "audiobooks" + # Resolve path using Slice 3a logic + relative = resolve_path(book) + # Apply subdirectory decision + if needs_subdirectory(book): + output_path = base_dir / relative / f"{sanitize(book.title)}.m4b" + else: + output_path = base_dir / f"{relative}.m4b" + + result = download_m4b( + url="https://cdn.example.com/book.m4b", + output_path=output_path, + transport=transport, + ) + + assert result.exists() + assert result.read_bytes() == payload + # Path should be sanitized (colon replaced, apostrophe preserved) + assert "O'Brien" in str(result) # apostrophe preserved + assert ":" not in str(result.parent) # colon removed from parent dirs + + + def test_creates_subdirectory_when_extras_present(self): + """Book with PDF extras → file inside subdirectory, not flat.""" + payload = b"m4b-with-extras" + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, content=payload) + + transport = httpx.MockTransport(handler) + + book = Book( + title="Book With Extras", + authors=["Author Name"], + narrators=["Narrator"], + isbn="9785555555555", + pdf_extras=True, + ) + + with tempfile.TemporaryDirectory() as tmpdir: + base_dir = Path(tmpdir) / "audiobooks" + relative = resolve_path(book) + # needs_subdirectory is True → file goes inside subdirectory + output_path = base_dir / relative / f"{sanitize(book.title)}.m4b" + + result = download_m4b( + url="https://cdn.example.com/book.m4b", + output_path=output_path, + transport=transport, + ) + + # File is inside subdirectory (not at leaf) + assert result.parent.name == sanitize(book.title) + assert result.exists() + assert result.read_bytes() == payload + + +# --------------------------------------------------------------------------- +# Orchestration: resolve path → query M4B → download → update history +# --------------------------------------------------------------------------- + + +class TestDownloadBook: + """End-to-end orchestration with mocked HTTP.""" + + def test_writes_history_entry_after_successful_download(self): + """After successful M4B download, history entry is persisted.""" + m4b_payload = b"complete-m4b-audio-data" + + 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/9781111111111/packaged_m4b": + return httpx.Response( + 200, + json={"m4b_url": "https://cdn.example.com/book.m4b"}, + ) + # CDN download + if "cdn.example.com" in request.url.host: + return httpx.Response(200, content=m4b_payload) + return httpx.Response(404) + + transport = httpx.MockTransport(handler) + client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") + client.authenticate(transport=transport) + + book = Book( + title="History Test Book", + authors=["Hist Author"], + narrators=["H Narr"], + isbn="9781111111111", + ) + + with tempfile.TemporaryDirectory() as tmpdir: + base_dir = Path(tmpdir) / "audiobooks" + history_path = Path(tmpdir) / "history.json" + history = DownloadHistory(history_path) + + result = download_book( + book=book, + client=client, + output_base=base_dir, + history=history, + transport=transport, + ) + + # History was written + assert history.is_downloaded("9781111111111") + entry = history.find("9781111111111") + assert entry is not None + assert entry.format == "m4b" + assert entry.title == "History Test Book" + + def test_skips_book_without_m4b(self): + """Book with no M4B available → returns None, no history entry, no error.""" + 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/9780000000000/packaged_m4b": + return httpx.Response(404) + return httpx.Response(404) + + transport = httpx.MockTransport(handler) + client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") + client.authenticate(transport=transport) + + book = Book( + title="No M4B Book", + authors=["Author"], + narrators=["Narr"], + isbn="9780000000000", + ) + + with tempfile.TemporaryDirectory() as tmpdir: + base_dir = Path(tmpdir) / "audiobooks" + history_path = Path(tmpdir) / "history.json" + history = DownloadHistory(history_path) + + result = download_book( + book=book, + client=client, + output_base=base_dir, + history=history, + transport=transport, + ) + + # Returns None (skipped) + assert result is None + # No history entry written + assert history.is_downloaded("9780000000000") is False + + def test_no_history_entry_on_download_failure(self): + """If download fails after M4B query, no history entry is written.""" + 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/9789999999999/packaged_m4b": + return httpx.Response( + 200, + json={"m4b_url": "https://cdn.example.com/fail.m4b"}, + ) + # CDN returns 500 error + if "cdn.example.com" in request.url.host: + return httpx.Response(500, text="Server Error") + return httpx.Response(404) + + transport = httpx.MockTransport(handler) + client = LibroFmClient(base_url="https://libro.fm", username="u", password="p") + client.authenticate(transport=transport) + + book = Book( + title="Fail Book", + authors=["Author"], + narrators=["Narr"], + isbn="9789999999999", + ) + + with tempfile.TemporaryDirectory() as tmpdir: + base_dir = Path(tmpdir) / "audiobooks" + history_path = Path(tmpdir) / "history.json" + history = DownloadHistory(history_path) + + with pytest.raises(httpx.HTTPStatusError): + download_book( + book=book, + client=client, + output_base=base_dir, + history=history, + transport=transport, + ) + + # No history entry written for failed download + assert history.is_downloaded("9789999999999") is False + + def test_flat_path_when_no_accompanying_files(self): + """Book without extras/cover → flat path, no subdirectory created.""" + payload = b"flat-m4b-data" + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response( + 200, + json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200}, + ) + if request.url.path == "/api/v10/audiobooks/9782222222222/packaged_m4b": + return httpx.Response(200, json={"m4b_url": "https://cdn.example.com/flat.m4b"}) + 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) + + book = Book( + title="Standalone Book", + authors=["Solo Author"], + narrators=["Solo Narr"], + isbn="9782222222222", + # No pdf_extras, no cover_url → needs_subdirectory() returns False + ) + + with tempfile.TemporaryDirectory() as tmpdir: + base_dir = Path(tmpdir) / "audiobooks" + history_path = Path(tmpdir) / "history.json" + history = DownloadHistory(history_path) + + result = download_book( + book=book, + client=client, + output_base=base_dir, + history=history, + transport=transport, + ) + + # File is at leaf (flat), not inside a subdirectory + assert result is not None + # Path should be base/Author/Title.m4b (flat) — title is filename stem + assert result.stem == "Standalone Book" + # No extra subdirectory between author and file + assert result.parent.name == "Solo Author" + assert result.exists() \ No newline at end of file