Merge branch 'feature/improve-codebase' into develop
This commit is contained in:
27 files changed
+5644
-2454
No files matched your search
@@ -8,9 +8,13 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
|
|||||||
<!-- write-log: session-log-index -->
|
<!-- write-log: session-log-index -->
|
||||||
| Date | Type | File | Summary |
|
| Date | Type | File | Summary |
|
||||||
|------|------|------|---------|
|
|------|------|------|---------|
|
||||||
|
| 2026-06-05 | issue | [20260605-issue31-sync-run-pipeline-and-cli-slimming_log.md](docs/devlog/20260605-issue31-sync-run-pipeline-and-cli-slimming_log.md) | **Issue #31 Complete:** Extracted `sync_run()` pipeline from `cli.run()` into standalone module. `SyncRunResult` frozen dataclass. `cli.py` slimmed 252→65 lines. **43 sync_run tests + 10 CLI tests, 374 total** · **All pass** · **7/8 AC (HITL pending)** |
|
||||||
|
| 2026-06-05 | issue | [20260605-issue30-download-reporting-bound-callable-per-book_log.md](docs/devlog/20260605-issue30-download-reporting-bound-callable-per-book_log.md) | **Issue #30 Complete:** Bound callable per book from `start_download()`. Task identity internal to `progress.py`. Orchestrator closure eliminated. **11 new tests, 382 total** · **All pass** · **6/6 AC** |
|
||||||
|
| 2026-06-04 | issue | [20260604-issue29-download-attempt-interface-shrink-to-4-params_log.md](docs/devlog/20260604-issue29-download-attempt-interface-shrink-to-4-params_log.md) | **Issue #29 Complete:** `download_book()` 9→4 domain-aligned params. `DownloadResult` frozen dataclass. History moved to caller. `OutputPlan.format_strategy` added. Cancel via reporter. **15 new TDD tests, 368 total** · **All pass** · **6/6 AC** |
|
||||||
|
| 2026-06-04 | issue | [20260604-issue28-output-plan-dataclass_log.md](docs/devlog/20260604-issue28-output-plan-dataclass_log.md) | **Issue #28 Complete:** `OutputPlan` frozen dataclass + `resolve_output_plan()`. Centralized all path computation; download functions consume plan fields. Eliminated duplicated audio-path code. **10 new TDD tests, 237 total** · **All pass** · **5/5 AC** |
|
||||||
|
| 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-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) |
|
||||||
| Date | Type | File | Summary |
|
|
||||||
|------|------|------|---------|
|
|
||||||
| 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** |
|
| 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** |
|
||||||
| 2026-06-04 | issue | [20260604-fix-ctrl-c-hangs-and-threading-traceback_log.md](docs/devlog/20260604-fix-ctrl-c-hangs-and-threading-traceback_log.md) | **Fix:** Ctrl+C hangs + threading traceback. `os._exit(130)` hard exit, no-wait cancellation, wired `cancel_event` through full download stack, fixed `books_with_index[idx][1]` bug. **256/256 tests pass** |
|
| 2026-06-04 | issue | [20260604-fix-ctrl-c-hangs-and-threading-traceback_log.md](docs/devlog/20260604-fix-ctrl-c-hangs-and-threading-traceback_log.md) | **Fix:** Ctrl+C hangs + threading traceback. `os._exit(130)` hard exit, no-wait cancellation, wired `cancel_event` through full download stack, fixed `books_with_index[idx][1]` bug. **256/256 tests pass** |
|
||||||
| 2026-06-04 | issue | [20260604-fix-keyboardinterrupt-handling-and-test-alignment_log.md](docs/devlog/20260604-fix-keyboardinterrupt-handling-and-test-alignment_log.md) | **Fix:** `except BaseException` in `_download_one`, cooperative cancellation framework, reporter lifecycle. **256/256 tests pass** |
|
| 2026-06-04 | issue | [20260604-fix-keyboardinterrupt-handling-and-test-alignment_log.md](docs/devlog/20260604-fix-keyboardinterrupt-handling-and-test-alignment_log.md) | **Fix:** `except BaseException` in `_download_one`, cooperative cancellation framework, reporter lifecycle. **256/256 tests pass** |
|
||||||
|
|||||||
+37
-1
@@ -5,7 +5,43 @@ All notable changes to this project will be documented in this file.
|
|||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
## [Unreleased]
|
8:6af|## [Unreleased]
|
||||||
|
|
||||||
|
|
||||||
|
### Refactored
|
||||||
|
|
||||||
|
- **session:** Rename LibroFmClient → LibroFmSession, relocate to
|
||||||
|
session.py, inject transport at construction time. Old client.py is now
|
||||||
|
a deprecated re-export shim. Endpoint signatures slimmed from 4-5 params
|
||||||
|
to ≤3 (transport removed). 227 tests pass (+17 new). Closes #27.
|
||||||
|
|
||||||
|
- **path:** Introduce OutputPlan frozen dataclass and resolve_output_plan()
|
||||||
|
function to centralize all path computation for a book. Download functions
|
||||||
|
now consume pre-resolved plan fields instead of computing paths inline,
|
||||||
|
eliminating duplicated audio-filename logic. 237 tests pass (+10 new).
|
||||||
|
Closes #28.
|
||||||
|
|
||||||
|
- **downloader:** Shrink download_book() from 9 parameters to 4
|
||||||
|
domain-aligned params (book, session, plan, reporter) returning a frozen
|
||||||
|
DownloadResult dataclass. Move history writing to caller (cli closure).
|
||||||
|
Add format_strategy to OutputPlan, wire cancel_event through reporter,
|
||||||
|
extract transport from session. Remove config from accompanying_files.
|
||||||
|
368 tests pass (+15 new). Closes #29.
|
||||||
|
|
||||||
|
- **progress:** Return bound callable from start_download() instead of raw
|
||||||
|
task_id. Task identity is fully internal to progress.py. Orchestrator
|
||||||
|
no longer creates per-book closures — passes the bound callback
|
||||||
|
directly. download_book() accepts optional progress= kwarg. Public
|
||||||
|
update() drops task_id param. 382 tests pass (+11 new). Closes #30.
|
||||||
|
|
||||||
|
- **cli/sync-run:** Extract entire download pipeline from cli.run() into
|
||||||
|
standalone sync_run() function in new sync_run.py module. Introduce
|
||||||
|
SyncRunResult frozen dataclass (replaces OrchestratorResult as public
|
||||||
|
return type). Slim cli.py from 252→65 lines to a thin argparse→exit
|
||||||
|
adapter that only patches sync_run(). Migrate 35 pipeline tests from
|
||||||
|
test_cli.py to test_sync_run.py (43 total + 10 CLI-only tests).
|
||||||
|
Add select_mode stub (ADR #6 branch point) and fatal_error field for
|
||||||
|
exit-code translation. 374 tests pass. Closes #31.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
- **progress:** Wire task_id through parallel progress callback.
|
- **progress:** Wire task_id through parallel progress callback.
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
# Issue #26: Book Intake Module (`book.py` + `path.py`) Extraction
|
||||||
|
|
||||||
|
> **Date:** 2026-06-04
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** PRD 001 Candidate #2 — Deepen Architecture: Module Depth & Domain Alignment
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Extract the `Book` domain model and API-shape intake function from their scattered locations (`downloader.py` + `orchestrator.py`) into a dedicated `book.py`, and extract all path-resolution/sanitization logic into a dedicated `path.py`. This eliminates the monolithic `downloader.py` (652→~490 lines) and ensures **zero knowledge of raw Libro.fm API dict shape exists outside `book.py`** — a PRD success criterion.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- **Created `librofm_downloader/book.py`** — New deep module owning:
|
||||||
|
- `Book` frozen dataclass (11 fields: title, authors, narrators, isbn, series, series_num, cover_url, pdf_extras, publication_year/month/day)
|
||||||
|
- `from_library_row(raw: dict) -> Book` intake function with ISBN str coercion, nested narrator resolution (`audiobook_info.narrators` → top-level fallback), PDF extras bool coercion, and default values
|
||||||
|
- Full module docstring declaring ownership of all API-shape normalization
|
||||||
|
|
||||||
|
- **Created `librofm_downloader/path.py`** — New pure-logic module (no I/O, no network) owning:
|
||||||
|
- `sanitize(component)` — filesystem-safe path component sanitization (5 rules: colon replacement, illegal char stripping, control char removal, trailing dot removal, 255-char cap)
|
||||||
|
- `_ILLEGAL_CHARS` / `_CONTROL_CHARS` — character classification constants
|
||||||
|
- `_TOKEN_REGISTRY` — 12 token → (attribute, formatter) mappings for custom patterns
|
||||||
|
- `_token_value(book, token)` — single token resolution
|
||||||
|
- `resolve_path(book, pattern)` — main entry point: custom pattern or default conditional logic
|
||||||
|
- `_resolve_default_path(book)` — Author/Series/Book N Title conditional paths
|
||||||
|
- `_resolve_custom_pattern(book, pattern)` — `{TOKEN}` regex substitution
|
||||||
|
- `needs_subdirectory(book)` — PDF extras → True (cover_url is config-gated separately)
|
||||||
|
- `_resolve_output_dir(book, output_base, config)` — full output directory resolution
|
||||||
|
|
||||||
|
- **Created `tests/test_book.py`** — 20 tests across 6 classes:
|
||||||
|
- `TestFromLibraryRowComplete` — tracer bullet with all fields populated
|
||||||
|
- `TestMissingFields` — empty dict → all defaults verified
|
||||||
|
- `TestIsbnCoercion` — int→str coercion, string passthrough, missing default
|
||||||
|
- `TestNarratorResolution` — audiobook_info priority, top-level fallback, both missing, no audiobook_info key
|
||||||
|
- `TestPdfExtrasBoolCoercion` — True/False bool, truthy/falsy int, missing key, missing audiobook_info
|
||||||
|
|
||||||
|
- **Created `tests/test_path.py`** — 59 tests across ~18 classes:
|
||||||
|
- Sanitization: illegal chars, colon replacement, control chars, trailing dots, whitespace trim, length cap, preserved chars, edge cases (empty, unicode)
|
||||||
|
- Default path: series+number, series-only, standalone (no series)
|
||||||
|
- Custom pattern: basic, override-default, ALL_AUTHORS, SERIES_NUM, ISBN, narrator tokens, publication date tokens, missing tokens, sanitization of output
|
||||||
|
- Subdirectory decision: pdf_extras=True, cover_only=False, both=True, neither=False, defaults, truthy int
|
||||||
|
- Output dir integration: subdir for pdf_extras, flat for cover-only (no config), subdir for cover+download_covers, no-title-doubling verification, flat for no extras, string base acceptance
|
||||||
|
|
||||||
|
- **Slimmed `librofm_downloader/downloader.py`** — Removed ~140 lines:
|
||||||
|
- Removed: `Book` class, `sanitize()`, `_ILLEGAL_CHARS`, `_CONTROL_CHARS`, `_TOKEN_REGISTRY`, `_token_value()`, `resolve_path()`, `_resolve_default_path()`, `_resolve_custom_pattern()`, `needs_subdirectory()`, `_resolve_output_dir()`
|
||||||
|
- Added imports from `book.py` and `path.py`
|
||||||
|
- Updated module docstring to declare scope: "download engine only; path logic lives in path.py; Book lives in book.py"
|
||||||
|
|
||||||
|
- **Updated `librofm_downloader/orchestrator.py`** — Removed `_raw_to_book()` (21 lines); now imports `from_library_row` from `book.py` and calls it directly in `download_all_books()`
|
||||||
|
|
||||||
|
- **Updated `librofm_downloader/cli.py`** — Split import: `Book` from `book.py`, `download_book` from `downloader.py`
|
||||||
|
|
||||||
|
- **Updated `tests/test_downloader.py`** — Split imports: `Book` from `book.py`, path functions from `path.py`, download functions from `downloader.py`
|
||||||
|
|
||||||
|
- **Updated `tests/test_orchestrator.py`** — Import `Book` from `book.py`
|
||||||
|
|
||||||
|
- **Updated `tests/test_progress.py`** — Import `Book` from `book.py`; added explicit `download_m4b`, `download_zip_part`, `download_book` imports from `downloader.py` for inline test imports
|
||||||
|
|
||||||
|
- **Rewrote `CONTEXT.md`** — Replaced domain glossary with full extraction context document: file inventory, key code snippets, architecture diagrams, import graph, data flow, raw API shape, test inventory with per-class mapping, and start-here instructions
|
||||||
|
|
||||||
|
- **Committed `docs/prd/001-deepen-architecture-prd.md`** — 211-line PRD document defining all 6 module-deepening candidates, user stories, testing decisions, cross-cutting import migration table, and success criteria
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| `from_library_row()` naming (not `_raw_to_book`) | Public function name signals intent as the canonical intake point; underscore-prefixed name in orchestrator suggested private implementation detail |
|
||||||
|
| Path helpers in separate `path.py` (not folded into `book.py`) | PRD explicitly separates concerns: book.py = domain model + API intake; path.py = output structure planning foundation. Keeps both modules under 5 public symbols (depth metric) |
|
||||||
|
| No backward-compat re-exports in `downloader.py` | All 6 importing files updated in same commit; no external consumers exist. Clean break preferred over deprecation cycle for internal-only code |
|
||||||
|
| `needs_subdirectory()` does NOT consider `cover_url` | Cover-gated subdirectory is a config-aware decision in `_resolve_output_dir()`. `needs_subdirectory()` stays pure (book-only) so it's testable without Config |
|
||||||
|
| Keep `_resolve_output_dir()` in `path.py` (not move to future `OutputPlan`) | It's path logic, not download logic. When OutputPlan is built (PRD Candidate #3), this function will be its foundation |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| None | Extraction was clean — all symbols had clear ownership boundaries, no circular dependencies introduced | N/A |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `librofm_downloader/book.py` | **NEW** — Book frozen dataclass + `from_library_row()` intake function (54 lines) |
|
||||||
|
| `librofm_downloader/path.py` | **NEW** — sanitize, resolve_path, needs_subdirectory, _resolve_output_dir, token registry (159 lines) |
|
||||||
|
| `tests/test_book.py` | **NEW** — 20 tests across 6 classes for Book + from_library_row() edge cases |
|
||||||
|
| `tests/test_path.py` | **NEW** — 59 tests across ~18 classes for all path functions |
|
||||||
|
| `librofm_downloader/downloader.py` | Removed ~140 lines of extracted code; imports from book.py + path.py; updated docstring |
|
||||||
|
| `librofm_downloader/orchestrator.py` | Removed `_raw_to_book()`; imports + calls `from_library_row()` from book.py |
|
||||||
|
| `librofm_downloader/cli.py` | Split import: Book from book.py, download_book from downloader.py |
|
||||||
|
| `tests/test_downloader.py` | Split imports across book.py, path.py, downloader.py |
|
||||||
|
| `tests/test_orchestrator.py` | Import Book from book.py |
|
||||||
|
| `tests/test_progress.py` | Import Book from book.py; explicit downloader imports for inline usage |
|
||||||
|
| `CONTEXT.md` | Rewrote as extraction context document (224 lines) |
|
||||||
|
| `docs/prd/001-deepen-architecture-prd.md` | **NEW** — PRD for full 6-candidate deepening plan (211 lines) |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] **Commit all changes** — 4 new files + 7 modified files currently uncommitted (git status shows `??` and ` M`)
|
||||||
|
- [ ] **PRD Candidate #3: Output Structure Planning** — Build `OutputPlan` dataclass + `resolve_output_plan()` on top of the newly extracted `path.py`
|
||||||
|
- [ ] **PRD Candidate #6: Libro.fm Session** — Rename `LibroFmClient` → `LibroFmSession`, constructor injection, transport removal from endpoint signatures
|
||||||
|
- [ ] **PRD Candidate #4: Download Attempt** — Slim `download_book()` from 9 params to 4 (book, session, plan, reporter); introduce `DownloadResult` dataclass
|
||||||
|
- [ ] **PRD Candidate #5: Download Reporting** — Bound callable from `start_download()`, internal task identity
|
||||||
|
- [ ] **PRD Candidate #1: Sync Run Pipeline** — Extract `sync_run()` from cli.py; slim CLI to ≤80 lines
|
||||||
|
- [ ] Verify all 338 tests pass after commit (3 known Ctrl+C hang tests excluded)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -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*
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
# Issue #28: Output Structure Planning — OutputPlan Dataclass
|
||||||
|
|
||||||
|
> **Date:** 2026-06-04
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** [Issue #28](https://github.com/AlexKucera/librofm-downloader/issues/28)
|
||||||
|
> **Parent:** [#25 — PRD 001: Deepen Architecture](https://github.com/AlexKucera/librofm-downloader/issues/25)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Introduce an `OutputPlan` frozen dataclass that carries all resolved paths and download flags for one Book. Add `resolve_output_plan()` function. Update download functions to consume plan fields instead of computing paths internally.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
### TDD Cycle — Vertical Slices (Red → Green → Refactor)
|
||||||
|
|
||||||
|
**Planning phase (scout):** Explored path.py (159 lines), book.py (Book dataclass), config.py (Config fields), downloader.py (486 lines). Key finding: `_resolve_output_dir()` only resolved the directory; audio filename `sanitize(title).m4b` was computed inline **twice** in `download_book()` (lines 252 & 279); cover/PDF filenames derived inside low-level download functions. No single object represented "all output paths for this book."
|
||||||
|
|
||||||
|
**User decisions confirmed:**
|
||||||
|
- Full file paths on OutputPlan (not dir + derive filenames)
|
||||||
|
- `format_strategy` stays separate from OutputPlan (it's a behavior flag, not a path concern)
|
||||||
|
- Happy-path-first test ordering
|
||||||
|
|
||||||
|
**Tracer Bullet #1 — RED→GREEN:**
|
||||||
|
- RED: Wrote `test_happy_path_all_enabled` → `ImportError: cannot import name 'OutputPlan'`
|
||||||
|
- GREEN: Implemented `OutputPlan` frozen dataclass + `resolve_output_plan()` in path.py → **64/64 pass**
|
||||||
|
|
||||||
|
**Incremental loop — 9 additional tests (all GREEN on first attempt):**
|
||||||
|
- Custom output pattern via `{TOKEN}` substitution
|
||||||
|
- Cover disabled (`download_covers=False`) → `cover_path=None`
|
||||||
|
- PDF disabled (`download_extras=False`) → `pdf_path=None`
|
||||||
|
- No `cover_url` on book → `cover_path=None` (data gate)
|
||||||
|
- No `pdf_extras` on book → `pdf_path=None` (data gate)
|
||||||
|
- String `output_base` accepted (type flexibility)
|
||||||
|
- Subdirectory layout when `pdf_extras=True`
|
||||||
|
- Flat layout when no extras
|
||||||
|
- `OutputPlan` is frozen (immutable)
|
||||||
|
|
||||||
|
**Refactor phase — Wired OutputPlan into downloader.py:**
|
||||||
|
- `download_book()` now calls `resolve_output_plan()` instead of `_resolve_output_dir()`, uses `plan.audio_path`
|
||||||
|
- Eliminated duplicated `sanitize(title).m4b` computation (was at 2 locations, lines 252 & 279)
|
||||||
|
- `download_accompanying_files()` signature changed from `output_dir: Path|str` → `plan: "OutputPlan"`
|
||||||
|
- `_download_cover()` and `_download_pdf()` gained optional `expected_path` parameter for validation
|
||||||
|
- Updated all call sites (3 in `download_book`, 7 test methods in `test_downloader.py`)
|
||||||
|
- Made `config` optional on `resolve_output_plan()` (`Config | None = None`) to handle graceful degradation
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|-----------|-----------|
|
||||||
|
| OutputPlan carries full file Paths (not just directories) | Downloaders receive exact output paths — zero path computation inside download functions. Cleaner separation of concerns. |
|
||||||
|
| `format_strategy` excluded from OutputPlan | It's a download behavior flag (which strategy to use), not an output path concern. Keeps OutputPlan focused on "where things go." |
|
||||||
|
| Config is optional (`None` default) on `resolve_output_plan()` | Allows flexible usage; when no config, cover/pdf paths are simply `None`. No need for dummy config objects in tests or non-config contexts. |
|
||||||
|
| `_resolve_output_dir()` kept as internal helper | Still used by `resolve_output_plan()`. Removing it would force duplication of subdirectory logic. It's now effectively private implementation detail. |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| No significant gotchas this session | Initial implementation handled all edge cases correctly from first GREEN phase | N/A — 9 incremental tests all passed without code changes |
|
||||||
|
|
||||||
|
**Minor note:** During refactor phase, worker made `config` optional on `resolve_output_plan()` so downstream callers don't need to construct a dummy Config when only audio path is needed.
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `librofm_downloader/path.py` | +63 lines: `OutputPlan` frozen dataclass (4 fields) + `resolve_output_plan()` function. Imports `dataclass`. |
|
||||||
|
| `librofm_downloader/downloader.py` | Refactored: `download_book()` consumes `plan.audio_path`; `download_accompanying_files()` takes `plan: OutputPlan`; `_download_cover()`/`_download_pdf()` accept `expected_path`. Eliminated duplicated audio-path computation. |
|
||||||
|
| `tests/test_path.py` | +59 lines: `TestResolveOutputPlan` class with 10 tests covering happy path, custom pattern, disabled flags, data gates, string base, subdirectory/flat layouts, frozen immutability. |
|
||||||
|
| `tests/test_downloader.py` | Updated 7 test methods: `download_accompanying_files()` calls now create and pass `OutputPlan`; assertions reference `plan.cover_path` / `plan.pdf_path`. |
|
||||||
|
|
||||||
|
## Acceptance Criteria Report
|
||||||
|
|
||||||
|
| # | Criterion | Status |
|
||||||
|
|---|-----------|--------|
|
||||||
|
| 1 | `OutputPlan` is a frozen dataclass with all fields documented | ✅ PASS — 4 fields: `audio_path`, `partial_path`, `cover_path` (\| None), `pdf_path` (\| None), each with doc comments |
|
||||||
|
| 2 | `resolve_output_plan()` produces correct paths for default/custom/subdirectory/flat/disabled patterns | ✅ PASS — 10 tests in `TestResolveOutputPlan` |
|
||||||
|
| 3 | Download functions consume plan fields; no path computation inside download functions | ✅ PASS — `plan.audio_path`, `plan.cover_path`, `plan.pdf_path` used throughout |
|
||||||
|
| 4 | All existing path-related tests pass; new edge case tests | ✅ PASS — 73 path tests + 88 downloader tests = 161 pass, 0 regressions |
|
||||||
|
| 5 | `path.py` total public symbols ≤12 | ✅ PASS — 5 owned symbols: `sanitize`, `resolve_path`, `needs_subdirectory`, `OutputPlan`, `resolve_output_plan` |
|
||||||
|
|
||||||
|
## Test Count Summary
|
||||||
|
|
||||||
|
| Suite | Before | After | Delta |
|
||||||
|
|-------|--------|-------|-------|
|
||||||
|
| `test_path.py` | 63 | 73 | **+10** |
|
||||||
|
| `test_downloader.py` | 88 | 88 | ±0 (call sites updated) |
|
||||||
|
| All other suites | 76 | 76 | unchanged |
|
||||||
|
| **Total** | **227** | **237** | **+10 new tests** · **ALL PASS** |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] Issue #28 is complete. Ready for next issue in the #25 PRD roadmap.
|
||||||
|
- [ ] Consider adding `output_pattern` Config field to wire custom token patterns through config (currently `resolve_path(book, pattern=...)` supports patterns but no Config field / CLI flag exists)
|
||||||
|
- [ ] Run `npx gitnexus analyze` to refresh index after these structural changes
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
# Issue #29: Download Attempt — Interface Shrink to 4 Params
|
||||||
|
|
||||||
|
> **Date:** 2026-06-04
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** [Issue #29](https://github.com/AlexKucera/librofm-downloader/issues/29)
|
||||||
|
> **Parent:** [PRD 001: Deepen Architecture — Module Depth & Domain Alignment](https://github.com/AlexKucera/librofm-downloader/issues/25)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Shrink `download_book()` from 9 parameters to 4 domain-aligned parameters. Introduce `DownloadResult` dataclass. Move history writing out of `download_book()` to the caller. End state:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def download_book(
|
||||||
|
book: Book,
|
||||||
|
session: LibroFmSession,
|
||||||
|
plan: OutputPlan,
|
||||||
|
reporter: DownloadReporter,
|
||||||
|
) -> DownloadResult:
|
||||||
|
```
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
### Cycle 1 (Tracer Bullet): `DownloadResult` frozen dataclass
|
||||||
|
- Added `@dataclass(frozen=True) class DownloadResult` to `downloader.py` with fields: `status` (Literal), `path`, `format`, `error`
|
||||||
|
- **5 tests** in new `TestDownloadResult` class: instantiates each status, defaults, frozen check, field presence, error message
|
||||||
|
|
||||||
|
### Cycle 2: Extend `OutputPlan` with `format_strategy`
|
||||||
|
- Added `format_strategy: str = "m4b_mp3_fallback"` field to `OutputPlan` in `path.py`
|
||||||
|
- Added keyword-only `format_strategy` parameter to `resolve_output_plan()` factory, passed through to constructor
|
||||||
|
- **4 tests** in new `TestOutputPlanFormatStrategy` class
|
||||||
|
|
||||||
|
### Cycle 3: Core refactoring — shrink `download_book()` signature
|
||||||
|
- Rewrote `download_book()` from 9 params → 4 params returning `DownloadResult`
|
||||||
|
- Removed `_write_history()` calls from inside `download_book()` and `_download_mp3()`
|
||||||
|
- Removed `history` parameter from `_download_mp3()`
|
||||||
|
- Removed `config` parameter from `download_accompanying_files()` — now checks `plan.cover_path is not None` / `plan.pdf_path is not None`
|
||||||
|
- Added `.cancel_event = None` attribute to both `PlainTextReporter` and `ProgressReporter` in `progress.py`
|
||||||
|
- Transport extracted from `session._client._transport` instead of per-function injection
|
||||||
|
- Progress callback obtained from `reporter.update`; cancel from `reporter.cancel_event`
|
||||||
|
- **1 test** in new `TestDownloadBookNewInterface` class (tracer bullet for new interface)
|
||||||
|
- **11 old tests failed** as expected (old call sites) — fixed in next cycle
|
||||||
|
|
||||||
|
### Cycle 4: Update all test call sites to new interface
|
||||||
|
- Updated **8 `download_book()` call sites** across `TestDownloadBook` (4) + `TestFormatStrategy` (4)
|
||||||
|
- Updated **7 `download_accompanying_files()` call sites** in `TestDownloadAccompanyingFiles` + `TestOutputStructure`
|
||||||
|
- Updated **1 `test_progress.py`** call site (`TestProgressCallbackWiring`)
|
||||||
|
- Key pattern change: tests now build `OutputPlan` via `resolve_output_plan()`, create `DownloadReporter()`, assert on `DownloadResult` fields, manually write history after calling `download_book()`
|
||||||
|
|
||||||
|
### Cycle 5: Update production callers
|
||||||
|
- **`cli.py`**: Rewrote `_make_download_fn()` closure to build `OutputPlan` per-book, call 4-param `download_book()`, write history after inspecting result, return `result.path` / `None` for backward compat with orchestrator. Added `reporter.cancel_event = cancel_event` wiring.
|
||||||
|
- **`orchestrator.py`**: No changes needed — adapter pattern in cli.py preserves `Path | None` contract
|
||||||
|
- **`test_cli.py`**: Updated ~10 mock return values from raw `Path`/`None` → `DownloadResult`, updated 6 side_effect functions for new 4-param signature
|
||||||
|
|
||||||
|
### Post-cycle fix
|
||||||
|
- Fixed `test_one_failure_does_not_stop_batch` in `test_progress.py`: mock was returning raw `Path` objects but cli's closure now accesses `.status` on result → updated mock to return `DownloadResult(status="downloaded", path=..., format="m4b")`
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| Store `format_strategy` on `OutputPlan` | Issue spec says "consumed from OutputPlan"; keeps plan as single config snapshot; avoids 5th param on download_book |
|
||||||
|
| Store `cancel_event` on reporter instance | Reporter already threaded through entire stack; avoids adding a param. Both implementations get `.cancel_event = None` attribute |
|
||||||
|
| Extract transport via `session._client._transport` | Tests inject transport at `LibroFmSession(..., transport=)` constructor (already supported). Low-level functions still accept `transport=` but it comes from session now |
|
||||||
|
| Remove `config` from `download_accompanying_files()` | Plan paths are already `None` when disabled — checking `plan.cover_path is not None` is equivalent to `config.download_covers and book.cover_url` but simpler |
|
||||||
|
| Return `Path \| None` from cli closure (not `DownloadResult`) | Orchestrator's `_download_one()` checks `result is None` for skip detection and catches exceptions separately. Adapter pattern avoids touching orchestrator at all |
|
||||||
|
| Let exceptions propagate for unexpected failures | Same behavior as before — HTTPStatusError etc. propagate up through orchestrator's `except BaseException` handler. Only caught/expected failures produce `DownloadResult(status="failed")` |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| `test_one_failure_does_not_stop_batch` failure: `'PosixPath' object has no attribute 'status'` | Mock returned raw `Path` objects; cli's new closure accesses `result.status` on whatever `download_book()` returns | Updated mock `side_effect` to return `DownloadResult(status="downloaded", path=Path(...), format="m4b")` instances |
|
||||||
|
| Transport injection concern: removing `transport` param would break CDN calls in tests | Tests use `httpx.MockTransport(handler)` that handles BOTH API and CDN URLs. Without passing transport to low-level functions, CDN calls hit real network | Extract from `session._client._transport` — the same MockTransport handles everything since session was constructed with it |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `librofm_downloader/downloader.py` | Added `DownloadResult` frozen dataclass; rewrote `download_book()` → 4 params returning `DownloadResult`; removed `history` from `_download_mp3()`; removed `config` from `download_accompanying_files()` |
|
||||||
|
| `librofm_downloader/path.py` | Added `format_strategy: str` field to `OutputPlan`; added `format_strategy=` kwarg to `resolve_output_plan()` |
|
||||||
|
| `librofm_downloader/progress.py` | Added `cancel_event = None` attribute to both `PlainTextReporter.__init__` and `ProgressReporter.__init__` |
|
||||||
|
| `librofm_downloader/cli.py` | Added imports (`_write_history`, `resolve_output_plan`); wired `reporter.cancel_event = cancel_event`; rewrote `_make_download_fn()` closure for new interface + caller-side history writing |
|
||||||
|
| `tests/test_downloader.py` | Added `TestDownloadResult` (5 tests) + `TestDownloadBookNewInterface` (1 test); updated 8 `download_book()` call sites + 7 `download_accompanying_files()` call sites |
|
||||||
|
| `tests/test_path.py` | Added `TestOutputPlanFormatStrategy` (4 tests) |
|
||||||
|
| `tests/test_progress.py` | Updated progress wiring test for 4-param sig; fixed mock to return `DownloadResult` |
|
||||||
|
| `tests/test_cli.py` | Updated ~10 mock return values + 6 side-effect functions for `DownloadResult` returns |
|
||||||
|
|
||||||
|
## Test Results
|
||||||
|
|
||||||
|
| Metric | Value |
|
||||||
|
|--------|-------|
|
||||||
|
| **Total tests pass** | **368** (7 deselected = pre-existing Ctrl+C `os._exit` tests) |
|
||||||
|
| **New tests added** | **15** (5 DownloadResult + 4 OutputPlan format + 1 tracer bullet + updated call sites) |
|
||||||
|
| **Failures** | **0** |
|
||||||
|
| **Acceptance criteria** | **6/6 met** |
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
| # | Criterion | Status |
|
||||||
|
|---|-----------|--------|
|
||||||
|
| 1 | `download_book()` has exactly 4 parameters (+ self) | ✅ `(book, session, plan, reporter)` |
|
||||||
|
| 2 | `DownloadResult` frozen dataclass with correct shape for all three statuses | ✅ `status`, `path`, `format`, `error` — frozen |
|
||||||
|
| 3 | History NOT written by `download_book()`; caller writes after inspecting result | ✅ `_write_history` removed from `download_book()` + `_download_mp3()`; cli.py closure writes |
|
||||||
|
| 4 | All download tests exercise new interface; no test passes raw Config or history to `download_book()` | ✅ All 8 call sites updated |
|
||||||
|
| 5 | M4B→MP3 fallback flow produces correct `DownloadResult` at each stage | ✅ `"downloaded"/"m4b"` → fallback → `"downloaded"/"mp3"` → `"skipped"` |
|
||||||
|
| 6 | Cancel/interrupt path produces correct `DownloadResult(status="failed")` | ✅ Uses `reporter.cancel_event` threaded through to chunk loops |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- None — issue complete, all AC met. Ready for next issue in PRD 001 roadmap.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Issue #30 — Download Reporting: Bound Callable Per Book
|
||||||
|
|
||||||
|
> **Date:** 2026-06-05
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** #30
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Refactor `start_download(book)` to return a bound callable that already targets the correct progress bar, making task identity fully internal to `progress.py`. Eliminate the per-book closure pattern from the orchestrator.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- **`librofm_downloader/progress.py`** — `start_download()` now returns `Callable[[int], None]` (bound closure) instead of `int task_id`. Public `update()` no longer accepts `task_id` param. The bound callable captures `task_id` internally and calls `_progress.update(task_id, ...)` directly.
|
||||||
|
- **`librofm_downloader/orchestrator.py`** — Removed closure pattern from `_download_one`. Now calls `progress_cb = reporter.start_download(book)` and passes `progress_cb` as `progress=` kwarg to `download_fn`.
|
||||||
|
- **`librofm_downloader/downloader.py`** — `download_book()` accepts optional `progress=` kwarg; uses it when provided, falls back to `reporter.update` for backward compatibility.
|
||||||
|
- **`librofm_downloader/cli.py`** — `_download_fn` now passes `progress=progress` through to `download_book()`.
|
||||||
|
- **`tests/test_progress.py`** — 9 existing tests refactored for new return type (int → callable) + 5 new tests in `TestBoundCallableFromStartDownload`.
|
||||||
|
- **`tests/test_orchestrator.py`** — 1 new test: `TestOrchestratorUsesBoundCallback`.
|
||||||
|
- **`tests/test_downloader.py`** — 1 new test: `test_uses_provided_progress_callback_over_reporter_update`.
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| Bound closure over callback-with-book-arg | Simpler API; prevents cross-bar contamination by construction — caller can't possibly target wrong task |
|
||||||
|
| Kept public `update()` without `task_id` param | Fallback for direct callers not going through orchestrator; targets most-recent task |
|
||||||
|
| Bound callable calls `_progress.update()` directly (not public `update()`) | Keeps fast path clean; avoids any guard logic in the hot loop |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| Downloader progress-wiring test showed "skipped" status | Mock URLs didn't match `/packaged_m4b` path or CDN host patterns used by real download path selection | Used proper mock URLs matching real route conditions |
|
||||||
|
| `MagicMock(spec=DownloadReporter)` raised error | `DownloadReporter` is a factory function, not a class — `spec=` expects a class | Switched to bare `MagicMock()` |
|
||||||
|
| 9 existing tests broke after return-type change | `start_download()` changed from returning `int` → `Callable`; tests asserted on `isinstance(result, int)` or passed result to `update(task_id=)` | Refactored all 9 to call returned callable directly |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `librofm_downloader/progress.py` | `start_download()` returns bound `Callable[[int], None]`; public `update()` drops `task_id` param |
|
||||||
|
| `librofm_downloader/orchestrator.py` | Removed per-book closure; uses bound callable from `start_download()` |
|
||||||
|
| `librofm_downloader/downloader.py` | `download_book()` accepts optional `progress=` kwarg with fallback to reporter |
|
||||||
|
| `librofm_downloader/cli.py` | Wires `progress=` kwarg through `_download_fn` → `download_book()` |
|
||||||
|
| `tests/test_progress.py` | 9 refactored + 5 new tests for bound callable behavior |
|
||||||
|
| `tests/test_orchestrator.py` | 1 new test: orchestrator uses bound callback correctly |
|
||||||
|
| `tests/test_downloader.py` | 1 new test: provided progress callback takes priority over reporter |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- None — issue fully complete, 6/6 AC met
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# Issue #31: Sync Run Pipeline + CLI Slimming (HITL)
|
||||||
|
|
||||||
|
> **Date:** 2026-06-05
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** [Issue #31](https://github.com/AlexKucera/librofm-downloader/issues/31)
|
||||||
|
> **Parent:** #25 — PRD 001: Deepen Architecture — Module Depth & Domain Alignment
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Extract the entire Sync Run pipeline from `cli.run()` into a standalone `sync_run()` function in a new module. Slim `cli.py` to a thin argparse→exit adapter (~80 lines). Introduce `SyncRunResult`. This is the capstone issue that wires all previous deep modules together.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
### Phase 1 — TDD Vertical Slices (8 tests, 7 slices)
|
||||||
|
|
||||||
|
| Slice | Test(s) | Behavior Verified |
|
||||||
|
|-------|---------|-------------------|
|
||||||
|
| 1. Tracer bullet | `test_returns_sync_result_on_happy_path` | `SyncRunResult` dataclass exists; `sync_run()` callable with correct return shape |
|
||||||
|
| 2. Auth failure | `test_returns_fatal_error_on_auth_failure` | Auth error → `SyncRunResult(fatal_error="Authentication failed: ...")` |
|
||||||
|
| 3. Config error | `test_returns_fatal_error_on_config_error` | ConfigError → `SyncRunResult(fatal_error="Config error: ...")` |
|
||||||
|
| 4. Fetch failure | `test_returns_fatal_error_on_fetch_failure` | Library fetch exception → `SyncRunResult(fatal_error="Failed to fetch library: ...")` |
|
||||||
|
| 5. Happy path w/ downloads | `test_propagates_download_counts_from_orchestrator` | Download counts flow from orchestrator → `SyncRunResult` correctly |
|
||||||
|
| 6. Filtering & limit | `test_filters_already_downloaded_books`, `test_limit_caps_book_list` | History filter removes downloaded books; limit caps the list |
|
||||||
|
| 7. Select mode + interrupted | `test_select_mode_returns_not_implemented_result`, `test_interrupted_download_returns_interrupted_result` | ADR #6 stub branch point; Ctrl+C propagation |
|
||||||
|
|
||||||
|
### Phase 2 — CLI Slimming + Test Migration (35 migrated + 5 new CLI tests)
|
||||||
|
|
||||||
|
- **`librofm_downloader/sync_run.py`** created — full pipeline copied from `cli.run()`, return type changed from `int` to `SyncRunResult`, added `fatal_error` field and `select_mode` keyword-only parameter
|
||||||
|
- **`librofm_downloader/cli.py`** rewritten from 252→**65 lines** — thin adapter: `main()` parses args → calls `sync_run()` → translates result to exit code → `sys.exit()`
|
||||||
|
- **`tests/test_sync_run.py`** created — **43 tests** (8 new + 35 migrated from old test_cli.py), all patching at `librofm_downloader.sync_run.*` level
|
||||||
|
- **`tests/test_cli.py`** rewritten — **10 tests** only (5 exit-code translation + 5 argparse), patches only `cli.sync_run` / `cli.run`
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| `SyncRunResult` mirrors `OrchestratorResult` fields exactly + adds `fatal_error` | Keeps migration low-risk; orchestrator still returns its own type internally; `fatal_error` distinguishes "all caught up" (exit 0) from "auth failed" (exit 1) for cli.py's exit-code translation |
|
||||||
|
| `select_mode` as keyword-only parameter on `sync_run()` | ADR #6 integration point — clearly visible as optional extension, not part of core pipeline signature |
|
||||||
|
| Early-return paths return `SyncRunResult(fatal_error=...)` instead of raising | Domain function returns structured results; CLI layer decides exit codes. Makes `sync_run()` testable without catching exceptions |
|
||||||
|
| Keep `OrchestratorResult` undeprecated for now | `download_all_books()` still returns it internally; deprecation is cosmetic at this stage and can be done separately |
|
||||||
|
| All verbose output stays inside `sync_run()` | Verbose is domain-relevant (config values, auth status, library size); CLI layer doesn't need to know about it |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| SyntaxError on line 112 after edit | `replace` edit mangled a Unicode box-drawing string literal — `"── config"` got split mid-character by the old_text boundary match | Replaced the broken line with the correct完整 string literal using another `replace` edit |
|
||||||
|
| `fatal_error` field needed after initial tracer bullet | Initial slice used empty `SyncRunResult()` for all early returns, but cli.py couldn't distinguish "all caught up" (exit 0) from "auth failed" (exit 1) | Added `fatal_error: str \| None = None` field to `SyncRunResult`; updated all 4 early-return paths (config error, auth error, fetch failure, select mode stub) |
|
||||||
|
| 22 test classes to migrate with different patch targets | Every test in old `test_cli.py` patched `librofm_downloader.cli.*` collaborators (load_config, LibroFmSession, DownloadHistory, download_book, etc.) | Rewrote all tests patching at `librofm_downloader.sync_run.*` instead; test logic preserved verbatim |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `librofm_downloader/sync_run.py` | **New** — `SyncRunResult` frozen dataclass + `sync_run()` function (~271 lines). Full 12-stage pipeline: resolve paths → load config → authenticate → fetch library → filter/limit/select → download all → write history → summary → return result |
|
||||||
|
| `librofm_downloader/cli.py` | **Rewritten** — 252→65 lines. Thin argparse→exit adapter. `run()` calls `sync_run()`, maps `SyncRunResult.fatal_error` → exit 1, `.interrupted` → exit 130, else exit 0. `--select` flag added to argparse. |
|
||||||
|
| `tests/test_sync_run.py` | **New** — 43 tests across ~20 classes covering: happy path, auth failure, config error, fetch failure, empty library, mixed results, Ctrl+C, history filtering, limit capping, format wiring, verbose output, workers flag, parallel workers=1 parity, parallel Ctrl+C drain, summary ordering, concurrency, verbose+parallel, partial file safety, history resolution (XDG/CWD), config resolution messages, missing files errors, select mode stub |
|
||||||
|
| `tests/test_cli.py` | **Rewritten** — 22 classes → 2 classes (10 tests). `TestCLIExitCodeTranslation` (5 tests) + `TestCLIArgparse` (5 tests). Zero internal collaborator patching. |
|
||||||
|
|
||||||
|
## Acceptance Criteria Report
|
||||||
|
|
||||||
|
| # | Criterion | Status |
|
||||||
|
|---|-----------|--------|
|
||||||
|
| 1 | `sync_run()` returns correct `SyncRunResult` for: happy path, auth failure, empty library, mixed results, Ctrl+C | ✅ 43 tests cover all paths |
|
||||||
|
| 2 | `cli.py` ≤80 lines; contains only argparse + exit code translation | ✅ **65 lines** |
|
||||||
|
| 3 | No test in `test_cli.py` patches load_config/LibroFmSession/DownloadHistory/download_book/DownloadReporter | ✅ Only patches `sync_run` / `run` |
|
||||||
|
| 4 | All migrated tests pass in `test_sync_run.py` | ✅ **43/43 pass** |
|
||||||
|
| 5 | Filtering (already-downloaded + limit) produces correct book list | ✅ 2 dedicated tests |
|
||||||
|
| 6 | History written exactly once per successful download (in sync_run, not in download_book) | ✅ `_write_history()` in download closure at sync_run.py:210–213 |
|
||||||
|
| 7 | Select mode stage 7 is a clear if/branch point (implementation deferred) | ✅ Lines 180–183: `if select_mode:` guard with fatal_error return |
|
||||||
|
| 8 | HITL review required before merge | ⏳ Pending user review |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- [ ] **HITL review** — run `librofm` end-to-end with real credentials to verify thin adapter works correctly
|
||||||
|
- [ ] **Deprecate `OrchestratorResult`** — consider having `download_all_books()` return `SyncRunResult` directly, or add a deprecation notice
|
||||||
|
- [ ] **ADR #6 implementation** — wire `--select` flag through to `selector.select_books()` when that module is built
|
||||||
|
- [ ] **3 pre-existing hanging tests** in `test_orchestrator.py` (Ctrl+C drain tests) remain unresolved — unrelated to this issue
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
# PRD 001: Deepen Architecture — Module Depth & Domain Alignment
|
||||||
|
|
||||||
|
> **Status:** Draft (grilling complete, ready for issue breakdown)
|
||||||
|
> **Date:** 2026-06-04
|
||||||
|
> **Parent ADRs:** [ADR 0001](../adr/0001-parallel-downloads.md), [ADR 0006](../adr/0006-select-mode-interactive-book-selection.md)
|
||||||
|
|
||||||
|
## Problem Statement
|
||||||
|
|
||||||
|
The librofm-downloader codebase has grown through 10+ issue-driven slices (Issues #2–#23). Each slice added correct code in the right place *at the time*, but the accumulated result is **shallow modules with leaky interfaces**:
|
||||||
|
|
||||||
|
- **`cli.run()`** (246 lines) does the entire Sync Run pipeline — config resolution, auth, library fetch, history filtering, worker resolution, download orchestration, summary, and exit-code policy. Its interface is small (7 parameters) but its test surface is enormous: ~29 tests patch 6+ internal modules to exercise it.
|
||||||
|
- **`download_book()`** (9 parameters) exposes implementation details (transport override, cancel_event threading, format strategy branching, config for extras toggles) that every caller must understand.
|
||||||
|
- **`LibroFmClient`** repeats auth-header assembly, `httpx.Client` construction, authenticated-state checks, and test-only `transport=` parameters across 4 endpoint methods.
|
||||||
|
- **Book intake** (`_raw_to_book()`) lives in the orchestrator while the `Book` dataclass lives in `downloader.py`, splitting API-shape normalization knowledge across two files.
|
||||||
|
- **Output path logic** is scattered across 4 functions in `downloader.py` plus the `Book` dataclass, and has already produced 2 real bugs (path doubling, cover placement).
|
||||||
|
- **Download reporting** leaks task identity to callers; the parallel progress-bar bug (Issue #23 fix) was caused by callers needing to bind `task_id` through a closure.
|
||||||
|
- **DownloadHistory writing** happens inside `download_book()` at two separate points, making it impossible for callers to control persistence policy without modifying download logic.
|
||||||
|
|
||||||
|
These shallow modules force tests to patch internals rather than exercising interfaces. They cause bugs when implementation details change. And they make every new feature touch more files than it should.
|
||||||
|
|
||||||
|
## Solution
|
||||||
|
|
||||||
|
A coordinated deepening of 6 module boundaries, executed in dependency order. Each candidate introduces a **deep module**: a small interface behind which a lot of behaviour concentrates. The vocabulary comes from the existing domain glossary (`CONTEXT.md`) and respects both ADRs.
|
||||||
|
|
||||||
|
### Execution Order
|
||||||
|
|
||||||
|
```
|
||||||
|
#2 Book intake ← foundation: everything works with Book objects
|
||||||
|
#3 Output Structure ← needs Book; consumed by download & session
|
||||||
|
#6 Libro.fm session ← independent of #3, can be done in parallel
|
||||||
|
#4 Download Attempt ← needs OutputPlan + Session + named results
|
||||||
|
#5 Download reporting ← needs Download Attempt shape
|
||||||
|
#1 Sync Run ← orchestrates all above
|
||||||
|
```
|
||||||
|
|
||||||
|
## User Stories
|
||||||
|
|
||||||
|
1. As a **maintainer**, I want `Book` intake and API-shape normalization to live in one place, so that Libro.fm API changes (new fields, nested structure shifts) require editing exactly one file.
|
||||||
|
2. As a **maintainer**, I want output path planning to return a coherent plan object, so that adding a new output type (e.g., chapter images, metadata sidecars) doesn't require touching 4+ functions.
|
||||||
|
3. As a **test author**, I want to assert download outcomes through a `DownloadResult` dataclass, so that I don't need to coordinate mocks for `client`, `history`, `progress`, `cancel_event`, and `config` simultaneously.
|
||||||
|
4. As a **test author**, I want the Librofm session to accept transport injection at construction time, so that I can create one mock session and pass it to any function that needs Librofm API access — instead of threading `transport=` through 4 method signatures per test.
|
||||||
|
5. As a **test author**, I want the Sync Run pipeline to be callable as a function with clear parameters, so that I can test auth failure, empty library, mixed download results, and Ctrl+C handling without patching 6 internal imports inside `cli.py`.
|
||||||
|
6. As a **developer**, I want `download_book()` to take 4 domain-aligned parameters instead of 9, so that adding a new download concern (e.g., checksum verification) adds depth to an existing module rather than widening the interface again.
|
||||||
|
7. As a **developer**, I want progress reporting to give me a bound callback per book, so that parallel download wiring cannot accidentally update the wrong progress bar.
|
||||||
|
8. As a **future developer** implementing Select Mode (ADR #6), I want the Sync Run pipeline to have a clear filter stage that I can replace with interactive selection — without restructuring the entire pipeline.
|
||||||
|
|
||||||
|
## Implementation Decisions
|
||||||
|
|
||||||
|
### Candidate #2: Book Intake Module
|
||||||
|
|
||||||
|
- **New file:** `librofm_downloader/book.py`
|
||||||
|
- **Contains:** `Book` dataclass (moved from `downloader.py`), `from_library_row(raw: dict) -> Book` intake function
|
||||||
|
- **ISBN normalization:** `from_library_row()` coerces ISBN to `str()` (API sometimes returns `int`)
|
||||||
|
- **Narrator resolution:** handles nested `audiobook_info.narrators` fallback to top-level `narrators`
|
||||||
|
- **PDF extras detection:** handles nested `audiobook_info.pdf_extras` with `bool()` coercion
|
||||||
|
- **Default values:** title defaults to `"Unknown"`, isbn defaults to `"?"` — preserved from current `_raw_to_book()`
|
||||||
|
- **Path helpers move to separate `path.py`** (not into `book.py`): `sanitize()`, `resolve_path()`, `needs_subdirectory()`, token registry, `_token_value()`
|
||||||
|
|
||||||
|
### Candidate #3: Output Structure Planning
|
||||||
|
|
||||||
|
- **New file:** `librofm_downloader/path.py`
|
||||||
|
- **Contains:** path helpers (from `downloader.py`) + new `OutputPlan` frozen dataclass
|
||||||
|
- **`OutputPlan` carries:**
|
||||||
|
- Audio destination path (`.m4b` or MP3 directory)
|
||||||
|
- Partial-file path (`.m4b.partial` or `.zip.partial`)
|
||||||
|
- Cover art destination path (or `None` if disabled/absent)
|
||||||
|
- PDF extra destination path (or `None` if disabled/absent)
|
||||||
|
- Format strategy (from Config)
|
||||||
|
- Extras flags: `download_covers`, `download_extras` (from Config)
|
||||||
|
- **Resolution function:** `resolve_output_plan(book: Book, output_base: Path | str, config: Config) -> OutputPlan`
|
||||||
|
- **Replaces:** `_resolve_output_dir()` + scattered path computation in `download_book()`, `_download_cover()`, `_download_pdf()`
|
||||||
|
- **Download functions consume plan fields** instead of computing paths internally
|
||||||
|
|
||||||
|
### Candidate #6: Libro.fm Session
|
||||||
|
|
||||||
|
- **Rename:** `LibroFmClient` → `LibroFmSession`
|
||||||
|
- **New file:** `librofm_downloader/session.py` (renamed from `client.py`; keep alias for transition)
|
||||||
|
- **Constructor injection:** `LibroFmSession(base_url, username, password, *, transport=None)`
|
||||||
|
- **All 4 endpoint methods drop their `transport` parameter**
|
||||||
|
- **Internal:** single `httpx.Client` constructed once with the injected transport (or real HTTP)
|
||||||
|
- **Auth headers assembled once** and stored on the instance (not recomputed per call)
|
||||||
|
- **API semaphore** (`threading.Semaphore(3)`) stays on the instance
|
||||||
|
- **Backward compatibility:** `librofm_downloader/client.py` re-exports from `session.py` as deprecated aliases
|
||||||
|
|
||||||
|
### Candidate #4: Download Attempt
|
||||||
|
|
||||||
|
- **Stays in:** `librofm_downloader/downloader.py` (but slimmer — only download logic)
|
||||||
|
- **New interface:** `download_book(book: Book, session: LibroFmSession, plan: OutputPlan, reporter: DownloadReporter) -> DownloadResult`
|
||||||
|
- **New result type:** `DownloadResult` frozen dataclass with fields:
|
||||||
|
- `status`: `Literal["downloaded", "skipped", "failed"]`
|
||||||
|
- `path`: `Path | None` (output path on success, None on skip/fail)
|
||||||
|
- `format`: `str | None` (actual format used: `"m4b"` or `"mp3"`)
|
||||||
|
- `error`: `str | None` (error message on failure)
|
||||||
|
- **History writing moves to caller:** `download_book()` no longer takes `history` or calls `_write_history()`. The orchestrator/Sync Run inspects `DownloadResult` and writes history for successful downloads.
|
||||||
|
- **Format strategy and extras flags come from `OutputPlan`** (not from raw Config)
|
||||||
|
- **Progress callback comes from reporter** (see #5)
|
||||||
|
- **Cancel event handled internally or via reporter contract** (TBD during implementation)
|
||||||
|
|
||||||
|
### Candidate #5: Download Reporting
|
||||||
|
|
||||||
|
- **Stays in:** `librofm_downloader/progress.py`
|
||||||
|
- **Change:** `start_download(book)` returns a **bound callable** `Callable[[int], None]` (for TTY/ProgressReporter) or `None` (for PlainTextReporter)
|
||||||
|
- **Task identity is fully internal** to `ProgressReporter`; callers never see `task_id`
|
||||||
|
- **`complete(book)` and `fail(book, reason)` stay on the reporter** (they look up task id internally via `id(book)`)
|
||||||
|
- **Orchestrator no longer creates closures** — it just passes the bound callback to `download_fn`
|
||||||
|
- **Fallback behavior removed:** `update()` without `task_id` raises or is a no-op; the bound callback always targets the right bar
|
||||||
|
|
||||||
|
### Candidate #1: Sync Run Pipeline
|
||||||
|
|
||||||
|
- **New file:** `librofm_downloader/sync_run.py`
|
||||||
|
- **New function:** `sync_run(config, secrets_path, history_path, *, verbose, limit, workers, select_mode) -> SyncRunResult`
|
||||||
|
- **Pipeline stages (sequential, early-return on fatal error):**
|
||||||
|
1. Resolve paths (XDG/CWD/history)
|
||||||
|
2. Load config
|
||||||
|
3. Authenticate → `LibroFmSession`
|
||||||
|
4. Fetch library → `list[dict]`
|
||||||
|
5. Intake: convert to `list[Book]` via `from_library_row()`
|
||||||
|
6. Filter: remove downloaded books (unless select_mode)
|
||||||
|
7. Select: if `select_mode`, open TUI (ADR #6); else apply limit
|
||||||
|
8. Resolve `OutputPlan` for each book
|
||||||
|
9. Download all (via orchestrator or direct call)
|
||||||
|
10. Write history for successful downloads
|
||||||
|
11. Report summary
|
||||||
|
12. Return `SyncRunResult`
|
||||||
|
- **`cli.py` becomes thin adapter:** parse args → call `sync_run()` → translate exit code → `sys.exit()`
|
||||||
|
- **Verbose output:** printed by `sync_run()` itself (it owns the pipeline, it owns the output)
|
||||||
|
- **`SyncRunResult`** absorbs/replaces `OrchestratorResult`:
|
||||||
|
- `downloaded_count`, `skipped_count`, `failed_count`
|
||||||
|
- `failed_books: list[tuple[Book, str]]`
|
||||||
|
- `skipped_books: list[Book]`
|
||||||
|
- `interrupted: bool`
|
||||||
|
|
||||||
|
### Cross-Cutting: Named Result Types
|
||||||
|
|
||||||
|
- **`DownloadResult`** — per-book outcome from `download_book()`
|
||||||
|
- **`SyncRunResult`** — pipeline outcome (replaces `OrchestratorResult`)
|
||||||
|
- **`OrchestratorResult`** — deprecated; `download_all_books()` returns `SyncRunResult` directly
|
||||||
|
- All frozen dataclasses for immutability
|
||||||
|
|
||||||
|
### Cross-Cutting: Import Migration
|
||||||
|
|
||||||
|
| Old import | New import |
|
||||||
|
|------------|-----------|
|
||||||
|
| `from librofm_downloader.downloader import Book` | `from librofm_downloader.book import Book` |
|
||||||
|
| `from librofm_downloader.downloader import sanitize, resolve_path` | `from librofm_downloader.path import sanitize, resolve_path` |
|
||||||
|
| `from librofm_downloader.client import LibroFmClient` | `from librofm_downloader.session import LibroFmSession` |
|
||||||
|
| `from librofm_downloader.client import AuthError, M4BUnavailableError` | `from librofm_downloader.session import AuthError, M4BUnavailableError` |
|
||||||
|
|
||||||
|
## Testing Decisions
|
||||||
|
|
||||||
|
### Test Philosophy
|
||||||
|
|
||||||
|
- **Test through interfaces, not implementation.** After deepening, tests should construct real objects (Book, OutputPlan, fake LibroFmSession) rather than patching internal imports.
|
||||||
|
- **Each deep module gets its own test file** exercising its interface boundary.
|
||||||
|
- **Integration tests** verify pipeline stages connect correctly (sync_run tests use faked session + filesystem history).
|
||||||
|
|
||||||
|
### Test File Map
|
||||||
|
|
||||||
|
| New/Modified Test File | Tests What |
|
||||||
|
|------------------------|-----------|
|
||||||
|
| `tests/test_book.py` (NEW) | `Book` dataclass, `from_library_row()` edge cases: missing fields, int ISBN, nested narrators, PDF extras bool coercion, default values |
|
||||||
|
| `tests/test_path.py` (NEW/MOVED) | `sanitize()`, `resolve_path()` (default + custom pattern), `needs_subdirectory()`, `OutputPlan` resolution, subdirectory rules, cover/PDF path inclusion |
|
||||||
|
| `tests/test_session.py` (RENAMED) | Constructor injection, auth, all 4 endpoints via one transport, semaphore, error translation. Renamed from `test_client.py` |
|
||||||
|
| `tests/test_downloader.py` (SHRUNK) | Only download functions: `download_m4b`, `download_zip_part`, `_download_mp3`, `download_accompanying_files`, `download_book` (new 4-arg interface), `DownloadResult` shape |
|
||||||
|
| `tests/test_progress.py` (UPDATED) | Bound callable from `start_download()`, task identity internal, no more closure wiring tests needed |
|
||||||
|
| `tests/test_sync_run.py` (NEW) | Pipeline stages: config resolution, auth failure, empty library, filtering, limit, summary, exit codes, Ctrl+C |
|
||||||
|
| `tests/test_cli.py` (SHRUNK) | Only argparse parsing + exit-code translation. No more pipeline testing in CLI tests. Most current CLI test classes migrate to `test_sync_run.py`. |
|
||||||
|
| `tests/test_orchestrator.py` (UPDATED) | Takes `list[Book]` not `list[dict]`. Uses `DownloadResult`. History writing verified at caller level. |
|
||||||
|
|
||||||
|
### Estimated Test Impact
|
||||||
|
|
||||||
|
| File | Current tests | Post-refactor estimate | Change |
|
||||||
|
|------|--------------|----------------------|--------|
|
||||||
|
| `test_cli.py` | ~29 classes | ~5 classes (argparse + exit code only) | **-24 classes migrate out** |
|
||||||
|
| `test_downloader.py` | ~20 classes | ~14 classes (Book/sanitize/path tests move out) | **-6 classes migrate out** |
|
||||||
|
| `test_client.py` | ~6 classes | ~6 classes (renamed, signature updates) | Same count, rewrites |
|
||||||
|
| `test_book.py` (NEW) | 0 | ~8 classes | **+8 classes** |
|
||||||
|
| `test_path.py` (NEW) | 0 | ~12 classes | **+12 classes** |
|
||||||
|
| `test_sync_run.py` (NEW) | 0 | ~15 classes | **+15 classes** (migrated from cli) |
|
||||||
|
|
||||||
|
## Out of Scope
|
||||||
|
|
||||||
|
- **Select Mode implementation** (ADR #6) — this PRD defines where select mode plugs into the pipeline (stage 7), but does not implement the TUI itself.
|
||||||
|
- **Async/multiprocessing migration** — ADR 0001 explicitly rejects this; this PRD respects that decision.
|
||||||
|
- **Configuration schema changes** — no new config fields or validation rules.
|
||||||
|
- **Database or persistent queue** — beyond the tool's scope (cron-invoked CLI).
|
||||||
|
- **Retry logic** — not part of current requirements; would be a future addition to the Download Attempt module.
|
||||||
|
- **Checksum/integrity verification** — would consume `OutputPlan` but is not in scope.
|
||||||
|
|
||||||
|
## Further Notes
|
||||||
|
|
||||||
|
### Risks
|
||||||
|
|
||||||
|
1. **Import churn is the largest risk.** ~97 files import `Book` from `downloader.py`. The aggressive profile embraces this, but a mechanical find-and-replace + test run cycle is essential. Git's rename detection will help track the move.
|
||||||
|
2. **`LibroFmClient` rename breaks external references** if any exist (docs, user configs). The backward-compat alias in `client.py` mitigates this for one release cycle.
|
||||||
|
3. **History-writing relocation** is the most subtle behavioral change. Currently `download_book()` writes history after M4B success AND after MP3 success. Moving this to the caller means there's exactly one write point — but any caller of `download_book()` (not just the orchestrator) must remember to write history. Mitigation: make `download_all_books()` / `sync_run()` the only callers; treat `download_book()` as internal API.
|
||||||
|
4. **Orchestrator taking `list[Book]`** means orchestrator tests must construct Book objects instead of raw dicts. This is actually simpler (fewer dict keys to remember) but requires updating ~21 test helper functions.
|
||||||
|
|
||||||
|
### Success Criteria
|
||||||
|
|
||||||
|
- Every new module has ≤5 public symbols in its interface (depth measure)
|
||||||
|
- No test in `test_cli.py` patches `load_config`, `LibroFmClient`, `DownloadHistory`, `download_book`, OR `DownloadReporter` — those belong in `test_sync_run.py`
|
||||||
|
- `download_book()` has ≤5 parameters (down from 9)
|
||||||
|
- `LibroFmSession` endpoint methods have ≤3 parameters each (down from 5-6)
|
||||||
|
- All 259+ tests pass (including 3 known-hangy Ctrl+C tests)
|
||||||
|
- `cli.py` ≤80 lines (down from 246)
|
||||||
|
- Zero knowledge of raw Libro.fm API dict shape exists outside `book.py`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*PRD written from architecture review grilling session. Ready for issue breakdown via `/to-issues`.*
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""Book domain model and API-shape intake for librofm-downloader.
|
||||||
|
|
||||||
|
Owns the Book dataclass and the from_library_row() intake function that
|
||||||
|
converts raw Libro.fm API dicts into Book objects. No knowledge of raw
|
||||||
|
API dict shape should exist outside this module.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Book:
|
||||||
|
"""Immutable book metadata record from Libro.fm."""
|
||||||
|
|
||||||
|
title: str
|
||||||
|
authors: list[str]
|
||||||
|
narrators: list[str]
|
||||||
|
isbn: str
|
||||||
|
series: str = ""
|
||||||
|
series_num: int | None = None
|
||||||
|
cover_url: str = ""
|
||||||
|
pdf_extras: bool = False
|
||||||
|
publication_year: int | None = None
|
||||||
|
publication_month: int | None = None
|
||||||
|
publication_day: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def from_library_row(raw: dict) -> Book:
|
||||||
|
"""Convert a Libro.fm API dict to a Book object.
|
||||||
|
|
||||||
|
Handles ISBN str coercion (API sometimes returns int),
|
||||||
|
nested narrator resolution, PDF extras bool coercion,
|
||||||
|
and default values for missing fields.
|
||||||
|
"""
|
||||||
|
audiobook_info = raw.get("audiobook_info", {}) or {}
|
||||||
|
narrators = audiobook_info.get("narrators", []) or raw.get("narrators", [])
|
||||||
|
|
||||||
|
raw_isbn = raw.get("isbn", "?")
|
||||||
|
isbn = str(raw_isbn) if raw_isbn is not None else "?"
|
||||||
|
|
||||||
|
return Book(
|
||||||
|
title=raw.get("title", "Unknown"),
|
||||||
|
authors=raw.get("authors", []),
|
||||||
|
narrators=narrators,
|
||||||
|
isbn=isbn,
|
||||||
|
series=raw.get("series", ""),
|
||||||
|
series_num=raw.get("series_num"),
|
||||||
|
cover_url=raw.get("cover_url", ""),
|
||||||
|
pdf_extras=bool(audiobook_info.get("pdf_extras")) if audiobook_info else False,
|
||||||
|
publication_year=raw.get("publication_year"),
|
||||||
|
publication_month=raw.get("publication_month"),
|
||||||
|
publication_day=raw.get("publication_day"),
|
||||||
|
)
|
||||||
+23
-205
@@ -1,18 +1,11 @@
|
|||||||
"""CLI entry point — wire config → auth → fetch library → download → history."""
|
"""CLI entry point — parse args → call sync_run() → translate exit code."""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import threading
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
|
|
||||||
from librofm_downloader.config import load_config, ConfigError, _resolve_config_file
|
from librofm_downloader.sync_run import sync_run
|
||||||
from librofm_downloader.client import LibroFmClient, AuthError
|
|
||||||
from librofm_downloader.history import DownloadHistory
|
|
||||||
from librofm_downloader.downloader import Book, download_book
|
|
||||||
from librofm_downloader.orchestrator import download_all_books
|
|
||||||
from librofm_downloader.progress import DownloadReporter
|
|
||||||
|
|
||||||
console = Console()
|
console = Console()
|
||||||
|
|
||||||
@@ -24,215 +17,40 @@ def run(
|
|||||||
verbose: bool = False,
|
verbose: bool = False,
|
||||||
limit: int = 0,
|
limit: int = 0,
|
||||||
workers: int = 0,
|
workers: int = 0,
|
||||||
|
select_mode: bool = False,
|
||||||
) -> int:
|
) -> int:
|
||||||
"""Main pipeline: load config → auth → fetch library → filter → download → summary.
|
"""Thin adapter: call sync_run() and translate SyncRunResult → exit code (0/1/130)."""
|
||||||
|
result = sync_run(
|
||||||
Args:
|
config_path=config_path,
|
||||||
config_path: Path to config.yaml.
|
secrets_path=secrets_path,
|
||||||
secrets_path: Path to secrets.yaml (gitignored).
|
history_path=history_path,
|
||||||
history_path: Path to download_history.json.
|
verbose=verbose,
|
||||||
verbose: Print extra detail (URLs, paths, API responses).
|
limit=limit,
|
||||||
limit: Maximum number of books to download (0 = no limit).
|
workers=workers,
|
||||||
workers: Parallel download worker count (0 = use config value).
|
select_mode=select_mode,
|
||||||
|
|
||||||
Returns:
|
|
||||||
Exit code: 0 on success, 1 on fatal error, 130 on Ctrl+C interrupt.
|
|
||||||
"""
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 0. Resolve history path (XDG → CWD, default to XDG location)
|
|
||||||
if history_path is None:
|
|
||||||
resolved = _resolve_config_file("download_history.json")
|
|
||||||
if resolved is not None:
|
|
||||||
history_path = str(resolved)
|
|
||||||
else:
|
|
||||||
from os import environ
|
|
||||||
home = Path(environ.get("HOME", "~")).expanduser()
|
|
||||||
xdg_dir = home / ".config" / "librofm-downloader"
|
|
||||||
xdg_dir.mkdir(parents=True, exist_ok=True)
|
|
||||||
history_path = str(xdg_dir / "download_history.json")
|
|
||||||
|
|
||||||
# 1. Load config
|
|
||||||
try:
|
|
||||||
config = load_config(config_path, secrets_path)
|
|
||||||
if config._config_path is None:
|
|
||||||
searched = [
|
|
||||||
"~/.config/librofm-downloader/config.yaml",
|
|
||||||
"./config.yaml",
|
|
||||||
]
|
|
||||||
console.print(
|
|
||||||
f"[yellow]config.yaml not found in {' → '.join(searched)}. "
|
|
||||||
f"Using built-in defaults.[/yellow]"
|
|
||||||
)
|
)
|
||||||
except ConfigError as exc:
|
|
||||||
console.print(f"[red]Config error:[/red] {exc}")
|
|
||||||
return 1
|
|
||||||
|
|
||||||
if verbose:
|
|
||||||
console.print("[dim]── config ──────────────────────────────────────[/dim]")
|
|
||||||
cfg_display = config._config_path if config._config_path else "(built-in defaults)"
|
|
||||||
# Determine resolved secrets path
|
|
||||||
secrets_display = secrets_path
|
|
||||||
if secrets_path is None:
|
|
||||||
resolved_secrets = _resolve_config_file("secrets.yaml")
|
|
||||||
secrets_display = resolved_secrets or "(not found)"
|
|
||||||
console.print(f" config: {cfg_display}")
|
|
||||||
console.print(f" secrets: {secrets_display}")
|
|
||||||
console.print(f" history: {history_path}")
|
|
||||||
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}")
|
|
||||||
|
|
||||||
# Resolve workers: CLI flag (>0?) → config.workers → default 3
|
|
||||||
resolved_workers = workers if workers > 0 else config.workers
|
|
||||||
if resolved_workers < 1:
|
|
||||||
resolved_workers = 3
|
|
||||||
console.print(f" user: {config.username}")
|
|
||||||
|
|
||||||
# 2. Authenticate
|
|
||||||
if verbose:
|
|
||||||
console.print("[dim]── auth ────────────────────────────────────────[/dim]")
|
|
||||||
|
|
||||||
client = LibroFmClient(
|
|
||||||
username=config.username,
|
|
||||||
password=config.password,
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
client.authenticate()
|
|
||||||
except AuthError as exc:
|
|
||||||
console.print(f"[red]Authentication failed:[/red] {exc}")
|
|
||||||
return 1
|
|
||||||
|
|
||||||
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 limit:
|
|
||||||
new_books = new_books[:limit]
|
|
||||||
|
|
||||||
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 with TTY-aware reporting
|
|
||||||
reporter = DownloadReporter()
|
|
||||||
cancel_event = threading.Event()
|
|
||||||
console.print(f"\n[bold]{len(new_books)} book(s) to download:[/bold]\n")
|
|
||||||
|
|
||||||
# --- Download loop (parallel via orchestrator — Issue #16) ---
|
|
||||||
|
|
||||||
def _make_download_fn():
|
|
||||||
"""Closure capturing client, config, history, reporter for each book."""
|
|
||||||
def _download_fn(book: Book, *, progress: "Callable[[int], None] | None" = None):
|
|
||||||
# Allow orchestrator to inject a per-book bound progress callback.
|
|
||||||
# Falls back to the shared reporter.update when not in parallel mode.
|
|
||||||
if progress is None:
|
|
||||||
progress = reporter.update
|
|
||||||
return download_book(
|
|
||||||
book=book,
|
|
||||||
client=client,
|
|
||||||
output_base=config.output_dir,
|
|
||||||
history=history,
|
|
||||||
format_strategy=config.format,
|
|
||||||
config=config,
|
|
||||||
progress=progress,
|
|
||||||
cancel_event=cancel_event,
|
|
||||||
)
|
|
||||||
return _download_fn
|
|
||||||
|
|
||||||
result = download_all_books(
|
|
||||||
new_books,
|
|
||||||
workers=resolved_workers,
|
|
||||||
download_fn=_make_download_fn(),
|
|
||||||
reporter=reporter,
|
|
||||||
cancel_event=cancel_event,
|
|
||||||
)
|
|
||||||
|
|
||||||
downloaded = result.downloaded_count
|
|
||||||
skipped = result.skipped_count
|
|
||||||
failed = result.failed_count
|
|
||||||
failed_books = result.failed_books
|
|
||||||
skipped_books = result.skipped_books
|
|
||||||
|
|
||||||
reporter.summary(
|
|
||||||
downloaded=downloaded,
|
|
||||||
skipped=skipped,
|
|
||||||
failed=failed,
|
|
||||||
failed_books=failed_books,
|
|
||||||
skipped_books=skipped_books,
|
|
||||||
)
|
|
||||||
|
|
||||||
if result.interrupted:
|
if result.interrupted:
|
||||||
return 130
|
return 130
|
||||||
|
if result.fatal_error:
|
||||||
if verbose:
|
return 1
|
||||||
console.print("[dim]── done ────────────────────────────────────────[/dim]")
|
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
console.print("\n[yellow]Download interrupted by user (Ctrl+C).[/yellow]")
|
|
||||||
return 130
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
"""CLI entry point — parse args and run the download pipeline."""
|
"""CLI entry point — parse args and run the download pipeline."""
|
||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(description="Download audiobooks from Libro.fm")
|
parser = argparse.ArgumentParser(description="Download audiobooks from Libro.fm")
|
||||||
parser.add_argument("--config", default=None, help="Path to config.yaml (default: search XDG then CWD)")
|
parser.add_argument("--config", default=None, help="Path to config.yaml")
|
||||||
parser.add_argument("--secrets", default=None, help="Path to secrets.yaml (default: search XDG then CWD)")
|
parser.add_argument("--secrets", default=None, help="Path to secrets.yaml")
|
||||||
parser.add_argument("--history", default=None, help="Path to download history JSON (default: search XDG then CWD)")
|
parser.add_argument("--history", default=None, help="Path to download history JSON")
|
||||||
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output (URLs, sizes, tracebacks)")
|
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output")
|
||||||
parser.add_argument(
|
parser.add_argument("--limit", type=int, default=0, metavar="N", help="Max books to download (0=no limit)")
|
||||||
"--limit",
|
parser.add_argument("-w", "--workers", type=int, default=0, metavar="N", help="Parallel workers (0=config)")
|
||||||
type=int,
|
parser.add_argument("--select", action="store_true", default=False, help="Interactive selection [not implemented]")
|
||||||
default=0,
|
|
||||||
metavar="N",
|
|
||||||
help="Maximum number of books to download (0 = no limit). Useful for testing.",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"-w",
|
|
||||||
"--workers",
|
|
||||||
type=int,
|
|
||||||
default=0,
|
|
||||||
metavar="N",
|
|
||||||
help="Parallel download workers (0 = use config value). Default: 3.",
|
|
||||||
)
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
exit_code = run(
|
exit_code = run(
|
||||||
config_path=args.config,
|
config_path=args.config, secrets_path=args.secrets, history_path=args.history,
|
||||||
secrets_path=args.secrets,
|
verbose=args.verbose, limit=args.limit, workers=args.workers, select_mode=args.select,
|
||||||
history_path=args.history,
|
|
||||||
verbose=args.verbose,
|
|
||||||
limit=args.limit,
|
|
||||||
workers=args.workers,
|
|
||||||
)
|
)
|
||||||
if exit_code == 130:
|
if exit_code == 130:
|
||||||
try:
|
try:
|
||||||
|
|||||||
+24
-217
@@ -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,
|
||||||
# Maximum concurrent Libro.fm API calls (not CDN downloads).
|
AuthError,
|
||||||
# Configurable constant — not user-facing.
|
LibroFmSession,
|
||||||
API_SEMAPHORE_CAPACITY = 3
|
M4BUnavailableError,
|
||||||
|
|
||||||
|
|
||||||
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."""
|
|
||||||
|
|
||||||
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:
|
warnings.warn(
|
||||||
resp = client.post(
|
"Import from 'librofm_downloader.session' instead of 'librofm_downloader.client'. "
|
||||||
"/oauth/token",
|
"This shim will be removed in a future version.",
|
||||||
data={
|
DeprecationWarning,
|
||||||
"grant_type": "password",
|
stacklevel=2,
|
||||||
"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"
|
# Backward-compatible alias
|
||||||
while next_url:
|
LibroFmClient = LibroFmSession
|
||||||
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
|
# Re-export DEFAULT_HEADERS for code that reads LibroFmClient.DEFAULT_HEADERS
|
||||||
|
DEFAULT_HEADERS = LibroFmSession.DEFAULT_HEADERS
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
def fetch_m4b_url(self, isbn: str, transport: httpx.BaseTransport | None = None) -> str:
|
"LibroFmSession",
|
||||||
"""Fetch the M4B download URL for a given ISBN.
|
"LibroFmClient",
|
||||||
|
"AuthError",
|
||||||
Args:
|
"M4BUnavailableError",
|
||||||
isbn: The ISBN of the audiobook.
|
"API_SEMAPHORE_CAPACITY",
|
||||||
transport: Optional httpx transport override for testing.
|
"DEFAULT_HEADERS",
|
||||||
|
]
|
||||||
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"]
|
|
||||||
+107
-254
@@ -1,10 +1,45 @@
|
|||||||
"""Path resolution and sanitization for librofm-downloader.
|
"""Download engine for librofm-downloader.
|
||||||
|
|
||||||
Pure logic module — no I/O, no network. All deterministic string manipulation.
|
Streaming downloads (M4B, ZIP parts), accompanying files (covers, PDFs),
|
||||||
|
and download orchestration. Path logic lives in ``path.py``; Book domain
|
||||||
|
object lives in ``book.py``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import threading
|
import threading
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from librofm_downloader.book import Book
|
||||||
|
from librofm_downloader.session import M4BUnavailableError
|
||||||
|
from librofm_downloader.history import HistoryEntry
|
||||||
|
from librofm_downloader.path import (
|
||||||
|
_resolve_output_dir,
|
||||||
|
needs_subdirectory,
|
||||||
|
resolve_output_plan,
|
||||||
|
resolve_path,
|
||||||
|
sanitize,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class DownloadResult:
|
||||||
|
"""Immutable result of a single book download attempt.
|
||||||
|
|
||||||
|
Returned by :func:`download_book` so callers can inspect outcome,
|
||||||
|
decide on history writing, and report status.
|
||||||
|
"""
|
||||||
|
status: Literal["downloaded", "skipped", "failed"]
|
||||||
|
path: Path | None = None
|
||||||
|
format: str | None = None # e.g. "m4b" or "mp3"
|
||||||
|
error: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class InterruptedDownload(Exception):
|
class InterruptedDownload(Exception):
|
||||||
@@ -15,161 +50,6 @@ class InterruptedDownload(Exception):
|
|||||||
callers can distinguish "user hit Ctrl+C" from "download was cancelled
|
callers can distinguish "user hit Ctrl+C" from "download was cancelled
|
||||||
cooperatively during drain."
|
cooperatively during drain."
|
||||||
"""
|
"""
|
||||||
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("", "", "<>/\\|?*")
|
|
||||||
|
|
||||||
# Control characters U+0000–U+001F
|
|
||||||
_CONTROL_CHARS = {chr(i) for i in range(0x00, 0x20)}
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class Book:
|
|
||||||
"""Immutable book metadata record from Libro.fm."""
|
|
||||||
|
|
||||||
title: str
|
|
||||||
authors: list[str]
|
|
||||||
narrators: list[str]
|
|
||||||
isbn: str
|
|
||||||
series: str = ""
|
|
||||||
series_num: int | None = None
|
|
||||||
cover_url: str = ""
|
|
||||||
pdf_extras: bool = False
|
|
||||||
publication_year: int | None = None
|
|
||||||
publication_month: int | None = None
|
|
||||||
publication_day: int | None = None
|
|
||||||
|
|
||||||
|
|
||||||
def sanitize(component: str) -> str:
|
|
||||||
"""Sanitize a single path component for filesystem safety.
|
|
||||||
|
|
||||||
Rules applied in order:
|
|
||||||
1. Replace ``:`` with `` -``
|
|
||||||
2. Strip ``< > / \\ | ? *`` and control characters (U+0000–U+001F)
|
|
||||||
3. Remove trailing dots
|
|
||||||
4. Trim whitespace
|
|
||||||
5. Cap at 255 characters
|
|
||||||
|
|
||||||
Preserves: dashes, commas, apostrophes, parentheses, periods (non-trailing).
|
|
||||||
"""
|
|
||||||
# 1. Replace colons
|
|
||||||
result = component.replace(":", " -")
|
|
||||||
# 2. Strip illegal chars and control characters
|
|
||||||
result = result.translate(_ILLEGAL_CHARS)
|
|
||||||
result = "".join(ch for ch in result if ch not in _CONTROL_CHARS)
|
|
||||||
# 3. Trim whitespace (before dot removal so exposed dots are caught)
|
|
||||||
result = result.strip()
|
|
||||||
# 4. Remove trailing dots
|
|
||||||
result = result.rstrip(".")
|
|
||||||
# 5. Cap at 255 characters
|
|
||||||
return result[:255]
|
|
||||||
|
|
||||||
|
|
||||||
# Token name → (attribute_path, formatter)
|
|
||||||
# attribute_path is a space-separated chain of attr lookups;
|
|
||||||
# formatter converts the raw value to string.
|
|
||||||
_TOKEN_REGISTRY: dict[str, tuple[str, str]] = {
|
|
||||||
"FIRST_AUTHOR": ("authors", "first"),
|
|
||||||
"ALL_AUTHORS": ("authors", "join"),
|
|
||||||
"SERIES_NAME": ("series", "raw"),
|
|
||||||
"SERIES_NUM": ("series_num", "raw"),
|
|
||||||
"BOOK_TITLE": ("title", "raw"),
|
|
||||||
"ISBN": ("isbn", "raw"),
|
|
||||||
"FIRST_NARRATOR":("narrators", "first"),
|
|
||||||
"ALL_NARRATORS": ("narrators", "join"),
|
|
||||||
"PUBLICATION_YEAR": ("publication_year", "raw"),
|
|
||||||
"PUBLICATION_MONTH": ("publication_month", "raw"),
|
|
||||||
"PUBLICATION_DAY": ("publication_day", "raw"),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _token_value(book: Book, token: str) -> str:
|
|
||||||
"""Resolve a single token to its string value from the book."""
|
|
||||||
if token not in _TOKEN_REGISTRY:
|
|
||||||
return ""
|
|
||||||
attr, fmt = _TOKEN_REGISTRY[token]
|
|
||||||
# Get the attribute value
|
|
||||||
val = getattr(book, attr)
|
|
||||||
# Format based on formatter type
|
|
||||||
if fmt == "first":
|
|
||||||
if isinstance(val, list) and val:
|
|
||||||
return str(val[0])
|
|
||||||
return ""
|
|
||||||
if fmt == "join":
|
|
||||||
if isinstance(val, list):
|
|
||||||
return ", ".join(str(v) for v in val)
|
|
||||||
return str(val) if val is not None else ""
|
|
||||||
# fmt == "raw"
|
|
||||||
return str(val) if val is not None else ""
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_path(book: Book, pattern: str | None = None) -> str:
|
|
||||||
"""Resolve the relative output path for a book.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
book: The book metadata.
|
|
||||||
pattern: Optional custom path pattern with token placeholders.
|
|
||||||
When set, overrides default conditional logic.
|
|
||||||
Tokens: FIRST_AUTHOR, ALL_AUTHORS, SERIES_NAME, SERIES_NUM,
|
|
||||||
BOOK_TITLE, ISBN, FIRST_NARRATOR, ALL_NARRATORS,
|
|
||||||
PUBLICATION_YEAR, PUBLICATION_MONTH, PUBLICATION_DAY.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Sanitized relative path string.
|
|
||||||
"""
|
|
||||||
if pattern:
|
|
||||||
return _resolve_custom_pattern(book, pattern)
|
|
||||||
return _resolve_default_path(book)
|
|
||||||
|
|
||||||
|
|
||||||
def _resolve_default_path(book: Book) -> str:
|
|
||||||
"""Default conditional path logic."""
|
|
||||||
first_author = sanitize(book.authors[0] if book.authors else "Unknown")
|
|
||||||
title = sanitize(book.title)
|
|
||||||
|
|
||||||
if book.series and book.series_num is not None:
|
|
||||||
series_name = sanitize(book.series)
|
|
||||||
return f"{first_author}/{series_name}/Book {book.series_num} {title}"
|
|
||||||
|
|
||||||
if book.series:
|
|
||||||
series_name = sanitize(book.series)
|
|
||||||
return f"{first_author}/{series_name}/{title}"
|
|
||||||
|
|
||||||
return f"{first_author}/{title}"
|
|
||||||
|
|
||||||
|
|
||||||
def _resolve_custom_pattern(book: Book, pattern: str) -> str:
|
|
||||||
"""Resolve path using custom pattern with token substitution."""
|
|
||||||
|
|
||||||
def replacer(match: re.Match) -> str:
|
|
||||||
token = match.group(1)
|
|
||||||
raw = _token_value(book, token)
|
|
||||||
return sanitize(raw)
|
|
||||||
|
|
||||||
# Replace {TOKEN} patterns
|
|
||||||
result = re.sub(r"\{([A-Z_]+)\}", replacer, pattern)
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def needs_subdirectory(book: Book) -> bool:
|
|
||||||
"""Check whether a book needs a subdirectory for accompanying files.
|
|
||||||
|
|
||||||
Returns True when PDF extras are present.
|
|
||||||
Cover art does NOT trigger a subdirectory here — cover downloads are
|
|
||||||
config-gated (``config.download_covers``) and considered separately
|
|
||||||
in ``_resolve_output_dir``.
|
|
||||||
"""
|
|
||||||
return bool(book.pdf_extras)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -186,6 +66,7 @@ CHUNK_SIZE = 8 * 1024 * 1024 # 8 MB
|
|||||||
def _part_filename_from_url(url: str) -> str:
|
def _part_filename_from_url(url: str) -> str:
|
||||||
"""Derive a safe filename from a URL's last path component."""
|
"""Derive a safe filename from a URL's last path component."""
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
parsed = urlparse(url)
|
parsed = urlparse(url)
|
||||||
name = Path(parsed.path).stem or "download"
|
name = Path(parsed.path).stem or "download"
|
||||||
return sanitize(name)
|
return sanitize(name)
|
||||||
@@ -290,7 +171,7 @@ def download_m4b(
|
|||||||
"""Download an M4B file via streaming chunks.
|
"""Download an M4B file via streaming chunks.
|
||||||
|
|
||||||
Writes to ``{output_path}.partial`` during transfer, then atomically
|
Writes to ``{output_path}.partial`` during transfer, then atomically
|
||||||
renames to the final ``{output_path}`` on completion.
|
renames to the final ``output_path`` on completion.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
url: The CDN URL for the M4B file.
|
url: The CDN URL for the M4B file.
|
||||||
@@ -350,123 +231,91 @@ def download_m4b(
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
def _resolve_output_dir(
|
|
||||||
book: Book,
|
|
||||||
output_base: Path | str,
|
|
||||||
config: "Config | None" = None,
|
|
||||||
) -> Path:
|
|
||||||
"""Resolve the output directory for a book (parent of the actual file).
|
|
||||||
|
|
||||||
For books with accompanying files → subdirectory: base/Author/Title/
|
|
||||||
For standalone books → parent dir only: base/Author/ (file is leaf: Title.m4b)
|
|
||||||
|
|
||||||
Subdirectory is needed when:
|
|
||||||
- PDF extras exist (multi-file output), OR
|
|
||||||
- Cover art will be downloaded (``config.download_covers`` + ``book.cover_url``)
|
|
||||||
"""
|
|
||||||
base = Path(output_base)
|
|
||||||
first_author = sanitize(book.authors[0] if book.authors else 'Unknown')
|
|
||||||
|
|
||||||
needs_subdir = needs_subdirectory(book) # pdf_extras
|
|
||||||
if not needs_subdir and config is not None:
|
|
||||||
needs_subdir = bool(config.download_covers and book.cover_url)
|
|
||||||
|
|
||||||
if needs_subdir:
|
|
||||||
relative = resolve_path(book) # e.g. "Author/Title" — already includes title
|
|
||||||
return base / relative
|
|
||||||
|
|
||||||
# Flat: file is leaf node under author dir
|
|
||||||
return base / first_author
|
|
||||||
|
|
||||||
|
|
||||||
def download_book(
|
def download_book(
|
||||||
book: Book,
|
book: Book,
|
||||||
client: "LibroFmClient",
|
session: "LibroFmSession",
|
||||||
output_base: Path | str,
|
plan: "OutputPlan",
|
||||||
history: "DownloadHistory",
|
reporter: "DownloadReporter",
|
||||||
format_strategy: str = "m4b_mp3_fallback",
|
*,
|
||||||
config: "Config | None" = None,
|
|
||||||
transport: httpx.BaseTransport | None = None,
|
|
||||||
progress: "Callable[[int], None] | None" = None,
|
progress: "Callable[[int], None] | None" = None,
|
||||||
cancel_event: threading.Event | None = None,
|
) -> DownloadResult:
|
||||||
) -> Path | None:
|
|
||||||
"""Orchestrate a single book download with format strategy.
|
"""Orchestrate a single book download with format strategy.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
book: The book metadata.
|
book: The book metadata.
|
||||||
client: Authenticated LibroFmClient instance.
|
session: Authenticated LibroFmSession instance.
|
||||||
output_base: Base directory for downloads.
|
plan: Resolved output paths, format strategy, and extras flags.
|
||||||
history: DownloadHistory instance to record successful downloads.
|
reporter: Reporter for progress callbacks and cancel event.
|
||||||
format_strategy: One of ``m4b_mp3_fallback``, ``mp3_only``, ``m4b_only``.
|
|
||||||
config: Optional Config for accompanying file settings.
|
|
||||||
transport: Optional httpx transport override for testing.
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Path to the downloaded file/dir, or None if book is skipped.
|
DownloadResult indicating outcome (downloaded/skipped/failed).
|
||||||
|
History is NOT written here — caller inspects result and writes.
|
||||||
"""
|
"""
|
||||||
from datetime import datetime, timezone
|
output_dir = plan.audio_path.parent
|
||||||
|
|
||||||
output_dir = _resolve_output_dir(book, output_base, config=config)
|
|
||||||
output_dir.mkdir(parents=True, exist_ok=True)
|
output_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
format_strategy = plan.format_strategy
|
||||||
|
# Use provided bound callback (from start_download) or fall back to reporter.update
|
||||||
|
if progress is None:
|
||||||
|
progress = reporter.update
|
||||||
|
cancel_event = reporter.cancel_event
|
||||||
|
transport = session._client._transport
|
||||||
|
|
||||||
# --- m4b_mp3_fallback: try M4B first, fall back to MP3 ---
|
# --- m4b_mp3_fallback: try M4B first, fall back to MP3 ---
|
||||||
if format_strategy == "m4b_mp3_fallback":
|
if format_strategy == "m4b_mp3_fallback":
|
||||||
# Try M4B first
|
# Try M4B first
|
||||||
try:
|
try:
|
||||||
m4b_url = client.fetch_m4b_url(book.isbn, transport=transport)
|
m4b_url = session.fetch_m4b_url(book.isbn)
|
||||||
title_sanitized = sanitize(book.title)
|
result_path = download_m4b(m4b_url, plan.audio_path, transport=transport, progress=progress, cancel_event=cancel_event)
|
||||||
m4b_path = output_dir / f"{title_sanitized}.m4b"
|
if plan.cover_path is not None or plan.pdf_path is not None:
|
||||||
result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress, cancel_event=cancel_event)
|
download_accompanying_files(book, plan, client=session, transport=transport)
|
||||||
_write_history(history, book, "m4b", str(result))
|
return DownloadResult(status="downloaded", path=result_path, format="m4b")
|
||||||
if config:
|
|
||||||
download_accompanying_files(book, output_dir, config, client=client, transport=transport)
|
|
||||||
return result
|
|
||||||
except M4BUnavailableError:
|
except M4BUnavailableError:
|
||||||
logger.info("M4B not available for %s (%s), falling back to MP3", book.title, book.isbn)
|
logger.info("M4B not available for %s (%s), falling back to MP3", book.title, book.isbn)
|
||||||
|
|
||||||
# Fall back to MP3
|
# Fall back to MP3
|
||||||
result = _download_mp3(book, client, output_dir, history, transport, progress=progress, cancel_event=cancel_event)
|
result_path = _download_mp3(book, session, output_dir, transport=transport, progress=progress, cancel_event=cancel_event)
|
||||||
if result and config:
|
if result_path and (plan.cover_path is not None or plan.pdf_path is not None):
|
||||||
download_accompanying_files(book, output_dir, config, client=client, transport=transport)
|
download_accompanying_files(book, plan, client=session, transport=transport)
|
||||||
return result
|
if result_path:
|
||||||
|
return DownloadResult(status="downloaded", path=result_path, format="mp3")
|
||||||
|
return DownloadResult(status="skipped")
|
||||||
|
|
||||||
# --- mp3_only: skip M4B entirely ---
|
# --- mp3_only: skip M4B entirely ---
|
||||||
if format_strategy == "mp3_only":
|
if format_strategy == "mp3_only":
|
||||||
result = _download_mp3(book, client, output_dir, history, transport, progress=progress, cancel_event=cancel_event)
|
result_path = _download_mp3(book, session, output_dir, transport=transport, progress=progress, cancel_event=cancel_event)
|
||||||
if result and config:
|
if result_path and (plan.cover_path is not None or plan.pdf_path is not None):
|
||||||
download_accompanying_files(book, output_dir, config, client=client, transport=transport)
|
download_accompanying_files(book, plan, client=session, transport=transport)
|
||||||
return result
|
if result_path:
|
||||||
|
return DownloadResult(status="downloaded", path=result_path, format="mp3")
|
||||||
|
return DownloadResult(status="skipped")
|
||||||
|
|
||||||
# --- m4b_only: skip book if M4B unavailable ---
|
# --- m4b_only: skip book if M4B unavailable ---
|
||||||
if format_strategy == "m4b_only":
|
if format_strategy == "m4b_only":
|
||||||
try:
|
try:
|
||||||
m4b_url = client.fetch_m4b_url(book.isbn, transport=transport)
|
m4b_url = session.fetch_m4b_url(book.isbn)
|
||||||
title_sanitized = sanitize(book.title)
|
result_path = download_m4b(m4b_url, plan.audio_path, transport=transport, progress=progress, cancel_event=cancel_event)
|
||||||
m4b_path = output_dir / f"{title_sanitized}.m4b"
|
if plan.cover_path is not None or plan.pdf_path is not None:
|
||||||
result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress, cancel_event=cancel_event)
|
download_accompanying_files(book, plan, client=session, transport=transport)
|
||||||
_write_history(history, book, "m4b", str(result))
|
return DownloadResult(status="downloaded", path=result_path, format="m4b")
|
||||||
if config:
|
|
||||||
download_accompanying_files(book, output_dir, config, client=client, transport=transport)
|
|
||||||
return result
|
|
||||||
except M4BUnavailableError:
|
except M4BUnavailableError:
|
||||||
logger.info("Skipping %s (%s): no M4B available (m4b_only mode)", book.title, book.isbn)
|
logger.info("Skipping %s (%s): no M4B available (m4b_only mode)", book.title, book.isbn)
|
||||||
return None
|
return DownloadResult(status="skipped")
|
||||||
|
|
||||||
raise ValueError(f"Unknown format strategy: {format_strategy}")
|
raise ValueError(f"Unknown format strategy: {format_strategy}")
|
||||||
|
|
||||||
|
|
||||||
def _download_mp3(
|
def _download_mp3(
|
||||||
book: Book,
|
book: Book,
|
||||||
client: "LibroFmClient",
|
client: "LibroFmSession",
|
||||||
output_dir: Path,
|
output_dir: Path,
|
||||||
history: "DownloadHistory",
|
|
||||||
transport: httpx.BaseTransport | None = None,
|
transport: httpx.BaseTransport | None = None,
|
||||||
progress: "Callable[[int], None] | None" = None,
|
progress: "Callable[[int], None] | None" = None,
|
||||||
cancel_event: threading.Event | None = None,
|
cancel_event: threading.Event | None = None,
|
||||||
) -> Path | None:
|
) -> Path | None:
|
||||||
"""Fetch MP3 manifest and download all ZIP parts."""
|
"""Fetch MP3 manifest and download all ZIP parts."""
|
||||||
try:
|
try:
|
||||||
manifest = client.fetch_download_manifest(book.isbn, transport=transport)
|
manifest = client.fetch_download_manifest(book.isbn)
|
||||||
except M4BUnavailableError:
|
except M4BUnavailableError:
|
||||||
logger.warning("MP3 manifest not available for %s (%s), skipping", book.title, book.isbn)
|
logger.warning("MP3 manifest not available for %s (%s), skipping", book.title, book.isbn)
|
||||||
return None
|
return None
|
||||||
@@ -482,9 +331,8 @@ def _download_mp3(
|
|||||||
extracted = download_zip_part(part_url, output_dir, transport=transport, progress=progress, cancel_event=cancel_event)
|
extracted = download_zip_part(part_url, output_dir, transport=transport, progress=progress, cancel_event=cancel_event)
|
||||||
all_extracted.extend(extracted)
|
all_extracted.extend(extracted)
|
||||||
|
|
||||||
# Record first extracted file as representative path
|
# Return output directory as representative path
|
||||||
if all_extracted:
|
if all_extracted:
|
||||||
_write_history(history, book, "mp3", str(output_dir))
|
|
||||||
return output_dir
|
return output_dir
|
||||||
|
|
||||||
return None
|
return None
|
||||||
@@ -508,6 +356,7 @@ def _cover_filename_from_url(url: str) -> str:
|
|||||||
def _download_cover(
|
def _download_cover(
|
||||||
url: str,
|
url: str,
|
||||||
output_dir: Path,
|
output_dir: Path,
|
||||||
|
expected_path: Path | None = None,
|
||||||
transport: httpx.BaseTransport | None = None,
|
transport: httpx.BaseTransport | None = None,
|
||||||
) -> Path | None:
|
) -> Path | None:
|
||||||
"""Download a cover art file via streaming .partial → atomic rename.
|
"""Download a cover art file via streaming .partial → atomic rename.
|
||||||
@@ -517,15 +366,17 @@ def _download_cover(
|
|||||||
|
|
||||||
Returns Path on success, None on failure (logs warning).
|
Returns Path on success, None on failure (logs warning).
|
||||||
"""
|
"""
|
||||||
from librofm_downloader.client import LibroFmClient
|
from librofm_downloader.session import LibroFmSession
|
||||||
|
|
||||||
|
if expected_path is not None:
|
||||||
|
output_path = expected_path
|
||||||
|
else:
|
||||||
filename = _cover_filename_from_url(url)
|
filename = _cover_filename_from_url(url)
|
||||||
|
output_path = output_dir / filename
|
||||||
|
|
||||||
# Normalize protocol-relative URLs (//covers.libro.fm/... → https://covers.libro.fm/...)
|
# Normalize protocol-relative URLs (//covers.libro.fm/... → https://covers.libro.fm/...)
|
||||||
if url.startswith("//"):
|
if url.startswith("//"):
|
||||||
url = "https:" + url
|
url = "https:" + url
|
||||||
|
|
||||||
output_path = output_dir / filename
|
|
||||||
partial_path = output_path.with_suffix(output_path.suffix + ".partial")
|
partial_path = output_path.with_suffix(output_path.suffix + ".partial")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -534,7 +385,7 @@ def _download_cover(
|
|||||||
client = httpx.Client(
|
client = httpx.Client(
|
||||||
transport=transport,
|
transport=transport,
|
||||||
follow_redirects=True,
|
follow_redirects=True,
|
||||||
headers=LibroFmClient.DEFAULT_HEADERS,
|
headers=LibroFmSession.DEFAULT_HEADERS,
|
||||||
)
|
)
|
||||||
with client.stream("GET", url) as resp:
|
with client.stream("GET", url) as resp:
|
||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
@@ -556,12 +407,16 @@ def _download_pdf(
|
|||||||
url: str,
|
url: str,
|
||||||
filename: str,
|
filename: str,
|
||||||
output_dir: Path,
|
output_dir: Path,
|
||||||
|
expected_path: Path | None = None,
|
||||||
transport: httpx.BaseTransport | None = None,
|
transport: httpx.BaseTransport | None = None,
|
||||||
) -> Path | None:
|
) -> Path | None:
|
||||||
"""Download a PDF extra file via streaming .partial → atomic rename.
|
"""Download a PDF extra file via streaming .partial → atomic rename.
|
||||||
|
|
||||||
Returns Path on success, None on failure (logs warning).
|
Returns Path on success, None on failure (logs warning).
|
||||||
"""
|
"""
|
||||||
|
if expected_path is not None:
|
||||||
|
output_path = expected_path
|
||||||
|
else:
|
||||||
safe_name = sanitize(filename)
|
safe_name = sanitize(filename)
|
||||||
output_path = output_dir / safe_name
|
output_path = output_dir / safe_name
|
||||||
partial_path = output_path.with_suffix(output_path.suffix + ".partial")
|
partial_path = output_path.with_suffix(output_path.suffix + ".partial")
|
||||||
@@ -587,9 +442,8 @@ def _download_pdf(
|
|||||||
|
|
||||||
def download_accompanying_files(
|
def download_accompanying_files(
|
||||||
book: Book,
|
book: Book,
|
||||||
output_dir: Path | str,
|
plan: "OutputPlan",
|
||||||
config: "Config",
|
client: "LibroFmSession | None" = None,
|
||||||
client: "LibroFmClient | None" = None,
|
|
||||||
transport: httpx.BaseTransport | None = None,
|
transport: httpx.BaseTransport | None = None,
|
||||||
progress: "Callable[[int], None] | None" = None,
|
progress: "Callable[[int], None] | None" = None,
|
||||||
) -> list[Path]:
|
) -> list[Path]:
|
||||||
@@ -599,31 +453,30 @@ def download_accompanying_files(
|
|||||||
|
|
||||||
Args:
|
Args:
|
||||||
book: The book metadata.
|
book: The book metadata.
|
||||||
output_dir: Directory where accompanying files are placed.
|
plan: OutputPlan with resolved paths (None when disabled).
|
||||||
config: Config with download_extras / download_covers toggles.
|
client: Optional LibroFmSession for fetching PDF URLs.
|
||||||
client: Optional LibroFmClient for fetching PDF URLs.
|
|
||||||
transport: Optional httpx transport override for testing.
|
transport: Optional httpx transport override for testing.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
List of Paths successfully downloaded.
|
List of Paths successfully downloaded.
|
||||||
"""
|
"""
|
||||||
from librofm_downloader.client import LibroFmClient
|
from librofm_downloader.session import LibroFmSession
|
||||||
|
|
||||||
output_dir = Path(output_dir)
|
output_dir = plan.audio_path.parent
|
||||||
downloaded: list[Path] = []
|
downloaded: list[Path] = []
|
||||||
|
|
||||||
# Download cover art if enabled and available
|
# Download cover art when path is resolved (means covers enabled + URL present)
|
||||||
if config.download_covers and book.cover_url:
|
if plan.cover_path is not None:
|
||||||
result = _download_cover(book.cover_url, output_dir, transport=transport)
|
result = _download_cover(book.cover_url, output_dir, expected_path=plan.cover_path, transport=transport)
|
||||||
if result:
|
if result:
|
||||||
downloaded.append(result)
|
downloaded.append(result)
|
||||||
|
|
||||||
# Download PDF extras if enabled and available
|
# Download PDF extras when path is resolved (means extras enabled + available)
|
||||||
if config.download_extras and book.pdf_extras and client is not None:
|
if plan.pdf_path is not None:
|
||||||
try:
|
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:
|
if pdf_url:
|
||||||
result = _download_pdf(pdf_url, "map.pdf", output_dir, transport=transport)
|
result = _download_pdf(pdf_url, "map.pdf", output_dir, expected_path=plan.pdf_path, transport=transport)
|
||||||
if result:
|
if result:
|
||||||
downloaded.append(result)
|
downloaded.append(result)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ from typing import Any, Callable
|
|||||||
|
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
|
|
||||||
from librofm_downloader.downloader import Book
|
from librofm_downloader.book import Book, from_library_row
|
||||||
|
|
||||||
|
|
||||||
def _hard_exit(code: int) -> None:
|
def _hard_exit(code: int) -> None:
|
||||||
@@ -54,27 +54,6 @@ class OrchestratorResult:
|
|||||||
interrupted: bool = False
|
interrupted: bool = False
|
||||||
|
|
||||||
|
|
||||||
def _raw_to_book(raw: dict) -> Book:
|
|
||||||
"""Convert a Libro.fm API dict to a Book object.
|
|
||||||
|
|
||||||
Mirrors the Book-building logic previously in cli.py's download loop.
|
|
||||||
"""
|
|
||||||
audiobook_info = raw.get("audiobook_info", {}) or {}
|
|
||||||
narrators = audiobook_info.get("narrators", []) or raw.get("narrators", [])
|
|
||||||
|
|
||||||
return Book(
|
|
||||||
title=raw.get("title", "Unknown"),
|
|
||||||
authors=raw.get("authors", []),
|
|
||||||
narrators=narrators,
|
|
||||||
isbn=raw.get("isbn", "?"),
|
|
||||||
series=raw.get("series", ""),
|
|
||||||
series_num=raw.get("series_num"),
|
|
||||||
cover_url=raw.get("cover_url", ""),
|
|
||||||
pdf_extras=bool(audiobook_info.get("pdf_extras")) if audiobook_info else False,
|
|
||||||
publication_year=raw.get("publication_year"),
|
|
||||||
publication_month=raw.get("publication_month"),
|
|
||||||
publication_day=raw.get("publication_day"),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _download_one(
|
def _download_one(
|
||||||
@@ -90,17 +69,13 @@ def _download_one(
|
|||||||
- error: exception string if download_fn raised, else None
|
- error: exception string if download_fn raised, else None
|
||||||
- was_skipped: True if download_fn returned None (skipped)
|
- was_skipped: True if download_fn returned None (skipped)
|
||||||
"""
|
"""
|
||||||
task_id = reporter.start_download(book)
|
# Issue #30: start_download() returns a bound callable that already carries
|
||||||
|
# task identity internally. For TTY reporters this is a per-book update fn;
|
||||||
# Create a per-book progress callback bound to this book's task_id.
|
# for plain-text reporters it is None. No closure needed here.
|
||||||
# Without this, reporter.update() falls back to the most-recently-started
|
progress_cb = reporter.start_download(book)
|
||||||
# bar (see ProgressReporter.update), so all parallel downloads would
|
|
||||||
# update the same progress bar.
|
|
||||||
def _progress(completed: int, *, total: int | None = None) -> None:
|
|
||||||
reporter.update(completed, total=total, task_id=task_id)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
result = download_fn(book, progress=_progress)
|
result = download_fn(book, progress=progress_cb)
|
||||||
if result is None:
|
if result is None:
|
||||||
# Skipped (no format available)
|
# Skipped (no format available)
|
||||||
reporter.complete(book) # still "complete" the progress tracking
|
reporter.complete(book) # still "complete" the progress tracking
|
||||||
@@ -140,7 +115,7 @@ def download_all_books(
|
|||||||
|
|
||||||
# Convert raw dicts to Book objects, preserving order and index
|
# Convert raw dicts to Book objects, preserving order and index
|
||||||
books_with_index: list[tuple[int, Book]] = [
|
books_with_index: list[tuple[int, Book]] = [
|
||||||
(i, _raw_to_book(raw)) for i, raw in enumerate(raw_books)
|
(i, from_library_row(raw)) for i, raw in enumerate(raw_books)
|
||||||
]
|
]
|
||||||
|
|
||||||
downloaded_count = 0
|
downloaded_count = 0
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
"""Path resolution and sanitization for librofm-downloader.
|
||||||
|
|
||||||
|
Pure logic module — no I/O, no network. All deterministic string manipulation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from librofm_downloader.book import Book
|
||||||
|
|
||||||
|
|
||||||
|
# Characters that are unsafe in filesystem path components
|
||||||
|
_ILLEGAL_CHARS = str.maketrans("", "", "<>/\\|?*")
|
||||||
|
|
||||||
|
# Control characters U+0000–U+001F
|
||||||
|
_CONTROL_CHARS = {chr(i) for i in range(0x00, 0x20)}
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize(component: str) -> str:
|
||||||
|
"""Sanitize a single path component for filesystem safety.
|
||||||
|
|
||||||
|
Rules applied in order:
|
||||||
|
1. Replace ``:`` with `` -``
|
||||||
|
2. Strip ``< > / \\ | ? *`` and control characters (U+0000–U+001F)
|
||||||
|
3. Remove trailing dots
|
||||||
|
4. Trim whitespace
|
||||||
|
5. Cap at 255 characters
|
||||||
|
|
||||||
|
Preserves: dashes, commas, apostrophes, parentheses, periods (non-trailing).
|
||||||
|
"""
|
||||||
|
result = component.replace(":", " -")
|
||||||
|
result = result.translate(_ILLEGAL_CHARS)
|
||||||
|
result = "".join(ch for ch in result if ch not in _CONTROL_CHARS)
|
||||||
|
result = result.strip()
|
||||||
|
result = result.rstrip(".")
|
||||||
|
return result[:255]
|
||||||
|
|
||||||
|
|
||||||
|
# Token name → (attribute_path, formatter)
|
||||||
|
_TOKEN_REGISTRY: dict[str, tuple[str, str]] = {
|
||||||
|
"FIRST_AUTHOR": ("authors", "first"),
|
||||||
|
"ALL_AUTHORS": ("authors", "join"),
|
||||||
|
"SERIES_NAME": ("series", "raw"),
|
||||||
|
"SERIES_NUM": ("series_num", "raw"),
|
||||||
|
"BOOK_TITLE": ("title", "raw"),
|
||||||
|
"ISBN": ("isbn", "raw"),
|
||||||
|
"FIRST_NARRATOR":("narrators", "first"),
|
||||||
|
"ALL_NARRATORS": ("narrators", "join"),
|
||||||
|
"PUBLICATION_YEAR": ("publication_year", "raw"),
|
||||||
|
"PUBLICATION_MONTH": ("publication_month", "raw"),
|
||||||
|
"PUBLICATION_DAY": ("publication_day", "raw"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _token_value(book: Book, token: str) -> str:
|
||||||
|
"""Resolve a single token to its string value from the book."""
|
||||||
|
if token not in _TOKEN_REGISTRY:
|
||||||
|
return ""
|
||||||
|
attr, fmt = _TOKEN_REGISTRY[token]
|
||||||
|
val = getattr(book, attr)
|
||||||
|
if fmt == "first":
|
||||||
|
if isinstance(val, list) and val:
|
||||||
|
return str(val[0])
|
||||||
|
return ""
|
||||||
|
if fmt == "join":
|
||||||
|
if isinstance(val, list):
|
||||||
|
return ", ".join(str(v) for v in val)
|
||||||
|
return str(val) if val is not None else ""
|
||||||
|
# fmt == "raw"
|
||||||
|
return str(val) if val is not None else ""
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_path(book: Book, pattern: str | None = None) -> str:
|
||||||
|
"""Resolve the relative output path for a book.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
book: The book metadata.
|
||||||
|
pattern: Optional custom path pattern with token placeholders.
|
||||||
|
When set, overrides default conditional logic.
|
||||||
|
Tokens: FIRST_AUTHOR, ALL_AUTHORS, SERIES_NAME, SERIES_NUM,
|
||||||
|
BOOK_TITLE, ISBN, FIRST_NARRATOR, ALL_NARRATORS,
|
||||||
|
PUBLICATION_YEAR, PUBLICATION_MONTH, PUBLICATION_DAY.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Sanitized relative path string.
|
||||||
|
"""
|
||||||
|
if pattern:
|
||||||
|
return _resolve_custom_pattern(book, pattern)
|
||||||
|
return _resolve_default_path(book)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_default_path(book: Book) -> str:
|
||||||
|
"""Default conditional path logic."""
|
||||||
|
first_author = sanitize(book.authors[0] if book.authors else "Unknown")
|
||||||
|
title = sanitize(book.title)
|
||||||
|
|
||||||
|
if book.series and book.series_num is not None:
|
||||||
|
series_name = sanitize(book.series)
|
||||||
|
return f"{first_author}/{series_name}/Book {book.series_num} {title}"
|
||||||
|
|
||||||
|
if book.series:
|
||||||
|
series_name = sanitize(book.series)
|
||||||
|
return f"{first_author}/{series_name}/{title}"
|
||||||
|
|
||||||
|
return f"{first_author}/{title}"
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_custom_pattern(book: Book, pattern: str) -> str:
|
||||||
|
"""Resolve path using custom pattern with token substitution."""
|
||||||
|
|
||||||
|
def replacer(match: re.Match) -> str:
|
||||||
|
token = match.group(1)
|
||||||
|
raw = _token_value(book, token)
|
||||||
|
return sanitize(raw)
|
||||||
|
|
||||||
|
# Replace {TOKEN} patterns
|
||||||
|
result = re.sub(r"\{([A-Z_]+)\}", replacer, pattern)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def needs_subdirectory(book: Book) -> bool:
|
||||||
|
"""Check whether a book needs a subdirectory for accompanying files.
|
||||||
|
|
||||||
|
Returns True when PDF extras are present.
|
||||||
|
Cover art does NOT trigger a subdirectory here — cover downloads are
|
||||||
|
config-gated (``config.download_covers``) and considered separately
|
||||||
|
in ``_resolve_output_dir``.
|
||||||
|
"""
|
||||||
|
return bool(book.pdf_extras)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class OutputPlan:
|
||||||
|
"""Resolved output paths and flags for one Book.
|
||||||
|
|
||||||
|
Immutable snapshot of where every output file for a book should go.
|
||||||
|
Computed once by :func:`resolve_output_plan`, then consumed by download
|
||||||
|
functions so that no path computation happens inside downloaders.
|
||||||
|
"""
|
||||||
|
|
||||||
|
audio_path: Path # Complete file path for audio (.m4b)
|
||||||
|
partial_path: Path # .partial resume path for audio
|
||||||
|
cover_path: Path | None # None when disabled or no cover_url
|
||||||
|
pdf_path: Path | None # None when disabled or no pdf_extras
|
||||||
|
format_strategy: str = "m4b_mp3_fallback" # Which format to attempt
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_output_dir(
|
||||||
|
book: Book,
|
||||||
|
output_base: Path | str,
|
||||||
|
config: "Config | None" = None,
|
||||||
|
) -> Path:
|
||||||
|
"""Resolve the output directory for a book (parent of the actual file).
|
||||||
|
|
||||||
|
For books with accompanying files → subdirectory: base/Author/Title/
|
||||||
|
For standalone books → parent dir only: base/Author/ (file is leaf: Title.m4b)
|
||||||
|
|
||||||
|
Subdirectory is needed when:
|
||||||
|
- PDF extras exist (multi-file output), OR
|
||||||
|
- Cover art will be downloaded (``config.download_covers`` + ``book.cover_url``)
|
||||||
|
"""
|
||||||
|
base = Path(output_base)
|
||||||
|
first_author = sanitize(book.authors[0] if book.authors else 'Unknown')
|
||||||
|
|
||||||
|
needs_subdir = needs_subdirectory(book) # pdf_extras
|
||||||
|
if not needs_subdir and config is not None:
|
||||||
|
needs_subdir = bool(config.download_covers and book.cover_url)
|
||||||
|
|
||||||
|
if needs_subdir:
|
||||||
|
relative = resolve_path(book) # e.g. "Author/Title" — already includes title
|
||||||
|
return base / relative
|
||||||
|
|
||||||
|
# Flat: file is leaf node under author dir
|
||||||
|
return base / first_author
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_output_plan(
|
||||||
|
book: Book,
|
||||||
|
output_base: Path | str,
|
||||||
|
config: "Config | None" = None,
|
||||||
|
*,
|
||||||
|
format_strategy: str = "m4b_mp3_fallback",
|
||||||
|
) -> OutputPlan:
|
||||||
|
"""Resolve all output paths for a book into a single immutable plan.
|
||||||
|
|
||||||
|
Centralizes every path computation so download functions receive
|
||||||
|
pre-resolved Paths instead of computing them inline.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
book: The book metadata.
|
||||||
|
output_base: Base download directory (string or Path).
|
||||||
|
config: Config with download_covers / download_extras toggles.
|
||||||
|
When None, cover_path and pdf_path are both None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Frozen OutputPlan with all resolved file paths.
|
||||||
|
"""
|
||||||
|
from urllib.parse import urlparse as _urlparse
|
||||||
|
|
||||||
|
output_dir = _resolve_output_dir(book, output_base, config=config)
|
||||||
|
|
||||||
|
title_sanitized = sanitize(book.title)
|
||||||
|
audio_path = output_dir / f"{title_sanitized}.m4b"
|
||||||
|
partial_path = Path(str(audio_path) + ".partial")
|
||||||
|
|
||||||
|
# Cover path: only when config provided AND enabled AND cover_url is present
|
||||||
|
cover_path: Path | None = None
|
||||||
|
if config is not None and config.download_covers and book.cover_url:
|
||||||
|
parsed = _urlparse(book.cover_url)
|
||||||
|
name = Path(parsed.path).name or "cover.jpg"
|
||||||
|
cover_path = output_dir / sanitize(name)
|
||||||
|
|
||||||
|
# PDF path: only when enabled AND pdf_extras is truthy
|
||||||
|
pdf_path: Path | None = None
|
||||||
|
if config is not None and config.download_extras and book.pdf_extras:
|
||||||
|
pdf_path = output_dir / "map.pdf"
|
||||||
|
|
||||||
|
return OutputPlan(
|
||||||
|
audio_path=audio_path,
|
||||||
|
partial_path=partial_path,
|
||||||
|
cover_path=cover_path,
|
||||||
|
pdf_path=pdf_path,
|
||||||
|
format_strategy=format_strategy,
|
||||||
|
)
|
||||||
@@ -19,6 +19,7 @@ class PlainTextReporter:
|
|||||||
|
|
||||||
def __init__(self, stdout: TextIO | None = None) -> None:
|
def __init__(self, stdout: TextIO | None = None) -> None:
|
||||||
self._out: TextIO = stdout or sys.stdout
|
self._out: TextIO = stdout or sys.stdout
|
||||||
|
self.cancel_event: threading.Event | None = None
|
||||||
|
|
||||||
def start_download(self, book, total_bytes: int = 0) -> None:
|
def start_download(self, book, total_bytes: int = 0) -> None:
|
||||||
"""Log download start with author, title, and file size."""
|
"""Log download start with author, title, and file size."""
|
||||||
@@ -91,12 +92,14 @@ class ProgressReporter:
|
|||||||
# Per-book identity mapping for concurrent downloads
|
# Per-book identity mapping for concurrent downloads
|
||||||
self._tasks: dict[int, object] = {} # task_id -> book
|
self._tasks: dict[int, object] = {} # task_id -> book
|
||||||
self._book_ids: dict[int, int] = {} # id(book) -> task_id
|
self._book_ids: dict[int, int] = {} # id(book) -> task_id
|
||||||
|
self.cancel_event: threading.Event | None = None
|
||||||
|
|
||||||
def start_download(self, book, total_bytes: int = 0) -> int:
|
def start_download(self, book, total_bytes: int = 0) -> callable:
|
||||||
"""Start a progress bar for this book's download.
|
"""Start a progress bar for this book's download.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The Rich task ID for this book's progress bar.
|
A bound callable ``(completed, *, total=None) -> None`` that updates
|
||||||
|
only this book's progress bar. Returns ``None`` for PlainTextReporter.
|
||||||
"""
|
"""
|
||||||
from rich.progress import (
|
from rich.progress import (
|
||||||
BarColumn,
|
BarColumn,
|
||||||
@@ -126,26 +129,34 @@ class ProgressReporter:
|
|||||||
self._tasks[task_id] = book
|
self._tasks[task_id] = book
|
||||||
self._book_ids[id(book)] = task_id
|
self._book_ids[id(book)] = task_id
|
||||||
|
|
||||||
return task_id
|
# Return a bound callable that carries task_id internally.
|
||||||
|
# Calls _progress.update() directly — bypasses the public update().
|
||||||
|
task_id_internal = task_id
|
||||||
|
_progress_obj = self._progress
|
||||||
|
|
||||||
def update(self, completed: int, *, total: int | None = None, task_id: int | None = None) -> None:
|
def _update(completed: int, *, total: int | None = None) -> None:
|
||||||
"""Update progress bar with bytes completed.
|
kwargs: dict = {"completed": completed}
|
||||||
|
if total is not None:
|
||||||
|
kwargs["total"] = total
|
||||||
|
_progress_obj.update(task_id_internal, **kwargs)
|
||||||
|
|
||||||
If *total* is provided (e.g. from a Content-Length header), also
|
return _update
|
||||||
updates the task's total so that percentage and ETA can be computed.
|
|
||||||
|
def update(self, completed: int, *, total: int | None = None) -> None:
|
||||||
|
"""Update progress for the most recently started download.
|
||||||
|
|
||||||
|
This is a convenience fallback for callers that don't have a bound
|
||||||
|
callable from start_download(). It always targets the most-recently-started
|
||||||
|
task. For per-book targeting, use the bound callable returned by
|
||||||
|
start_download() instead.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
completed: Bytes downloaded so far.
|
completed: Bytes downloaded so far.
|
||||||
total: Optional total bytes (from Content-Length).
|
total: Optional new total (e.g. from Content-Length header).
|
||||||
task_id: Specific task to update. Falls back to most recent if omitted.
|
|
||||||
"""
|
"""
|
||||||
if not self._progress:
|
if not self._progress or not self._tasks:
|
||||||
return
|
|
||||||
if task_id is None:
|
|
||||||
# Backward compat: use the most recently started task
|
|
||||||
task_id = next(reversed(self._tasks), None)
|
|
||||||
if task_id is None or task_id not in self._tasks:
|
|
||||||
return
|
return
|
||||||
|
task_id = next(reversed(self._tasks))
|
||||||
kwargs: dict = {"completed": completed}
|
kwargs: dict = {"completed": completed}
|
||||||
if total is not None:
|
if total is not None:
|
||||||
kwargs["total"] = total
|
kwargs["total"] = total
|
||||||
|
|||||||
@@ -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"]
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
"""Sync run pipeline — extracted from cli.run().
|
||||||
|
|
||||||
|
12 sequential stages: resolve paths → load config → authenticate → fetch library
|
||||||
|
→ intake (Book) → filter/limit/select → resolve plans → download all → write
|
||||||
|
history → summary → return result.
|
||||||
|
|
||||||
|
This is the domain pipeline. cli.py becomes a thin argparse→exit adapter that
|
||||||
|
calls sync_run() and translates SyncRunResult → exit code.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import threading
|
||||||
|
from collections.abc import Callable
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from rich.console import Console
|
||||||
|
|
||||||
|
from librofm_downloader.book import Book
|
||||||
|
from librofm_downloader.config import ConfigError, _resolve_config_file, load_config
|
||||||
|
from librofm_downloader.downloader import _write_history, download_book
|
||||||
|
from librofm_downloader.history import DownloadHistory
|
||||||
|
from librofm_downloader.orchestrator import OrchestratorResult, download_all_books
|
||||||
|
from librofm_downloader.path import resolve_output_plan
|
||||||
|
from librofm_downloader.progress import DownloadReporter
|
||||||
|
from librofm_downloader.session import AuthError, LibroFmSession
|
||||||
|
|
||||||
|
console = Console()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SyncRunResult:
|
||||||
|
"""Structured result from a full sync run.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
downloaded_count: Books successfully downloaded.
|
||||||
|
skipped_count: Books skipped (download_fn returned None).
|
||||||
|
failed_count: Books that raised an exception.
|
||||||
|
failed_books: List of (book, reason_string) tuples in original order.
|
||||||
|
skipped_books: List of Book objects that were skipped, in original order.
|
||||||
|
interrupted: True if the run was cancelled by Ctrl+C.
|
||||||
|
fatal_error: Non-None if the run stopped before downloads (auth, config, fetch).
|
||||||
|
"""
|
||||||
|
|
||||||
|
downloaded_count: int = 0
|
||||||
|
skipped_count: int = 0
|
||||||
|
failed_count: int = 0
|
||||||
|
failed_books: list[tuple[Book, str]] = field(default_factory=list)
|
||||||
|
skipped_books: list[Book] = field(default_factory=list)
|
||||||
|
interrupted: bool = False
|
||||||
|
fatal_error: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def sync_run(
|
||||||
|
config_path: str | None = None,
|
||||||
|
secrets_path: str | None = None,
|
||||||
|
history_path: str | None = None,
|
||||||
|
verbose: bool = False,
|
||||||
|
limit: int = 0,
|
||||||
|
workers: int = 0,
|
||||||
|
*,
|
||||||
|
select_mode: bool = False,
|
||||||
|
) -> SyncRunResult:
|
||||||
|
"""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).
|
||||||
|
limit: Maximum number of books to download (0 = no limit).
|
||||||
|
workers: Parallel download worker count (0 = use config value).
|
||||||
|
select_mode: Interactive book selection (ADR #6, not yet implemented).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
SyncRunResult with counts and per-book details.
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 0. Resolve history path (XDG → CWD, default to XDG location)
|
||||||
|
if history_path is None:
|
||||||
|
resolved = _resolve_config_file("download_history.json")
|
||||||
|
if resolved is not None:
|
||||||
|
history_path = str(resolved)
|
||||||
|
else:
|
||||||
|
from os import environ
|
||||||
|
|
||||||
|
home = Path(environ.get("HOME", "~")).expanduser()
|
||||||
|
xdg_dir = home / ".config" / "librofm-downloader"
|
||||||
|
xdg_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
history_path = str(xdg_dir / "download_history.json")
|
||||||
|
|
||||||
|
# 1. Load config
|
||||||
|
try:
|
||||||
|
config = load_config(config_path, secrets_path)
|
||||||
|
if config._config_path is None:
|
||||||
|
searched = [
|
||||||
|
"~/.config/librofm-downloader/config.yaml",
|
||||||
|
"./config.yaml",
|
||||||
|
]
|
||||||
|
console.print(
|
||||||
|
f"[yellow]config.yaml not found in {' → '.join(searched)}. "
|
||||||
|
f"Using built-in defaults.[/yellow]"
|
||||||
|
)
|
||||||
|
except ConfigError as exc:
|
||||||
|
console.print(f"[red]Config error:[/red] {exc}")
|
||||||
|
return SyncRunResult(fatal_error=f"Config error: {exc}")
|
||||||
|
|
||||||
|
if verbose:
|
||||||
|
console.print("[dim]── config ──────────────────────────────────────[/dim]")
|
||||||
|
cfg_display = config._config_path if config._config_path else "(built-in defaults)"
|
||||||
|
# Determine resolved secrets path
|
||||||
|
secrets_display = secrets_path
|
||||||
|
if secrets_path is None:
|
||||||
|
resolved_secrets = _resolve_config_file("secrets.yaml")
|
||||||
|
secrets_display = resolved_secrets or "(not found)"
|
||||||
|
console.print(f" config: {cfg_display}")
|
||||||
|
console.print(f" secrets: {secrets_display}")
|
||||||
|
console.print(f" history: {history_path}")
|
||||||
|
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}")
|
||||||
|
|
||||||
|
# Resolve workers: CLI flag (>0?) → config.workers → default 3
|
||||||
|
resolved_workers = workers if workers > 0 else config.workers
|
||||||
|
if resolved_workers < 1:
|
||||||
|
resolved_workers = 3
|
||||||
|
console.print(f" user: {config.username}")
|
||||||
|
|
||||||
|
# 2. Authenticate
|
||||||
|
if verbose:
|
||||||
|
console.print("[dim]── auth ────────────────────────────────────────[/dim]")
|
||||||
|
|
||||||
|
client = LibroFmSession(
|
||||||
|
username=config.username,
|
||||||
|
password=config.password,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
client.authenticate()
|
||||||
|
except AuthError as exc:
|
||||||
|
console.print(f"[red]Authentication failed:[/red] {exc}")
|
||||||
|
return SyncRunResult(fatal_error=f"Authentication failed: {exc}")
|
||||||
|
|
||||||
|
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 SyncRunResult(fatal_error=f"Failed to fetch library: {exc}")
|
||||||
|
|
||||||
|
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 limit:
|
||||||
|
new_books = new_books[:limit]
|
||||||
|
|
||||||
|
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 SyncRunResult()
|
||||||
|
|
||||||
|
# 5. Select mode branch point (ADR #6 — stub)
|
||||||
|
if select_mode:
|
||||||
|
console.print("[red]--select is not yet implemented.[/red]")
|
||||||
|
return SyncRunResult()
|
||||||
|
|
||||||
|
# 6. Download loop with TTY-aware reporting
|
||||||
|
reporter = DownloadReporter()
|
||||||
|
cancel_event = threading.Event()
|
||||||
|
reporter.cancel_event = cancel_event
|
||||||
|
console.print(f"\n[bold]{len(new_books)} book(s) to download:[/bold]\n")
|
||||||
|
|
||||||
|
# --- Download loop (parallel via orchestrator — Issue #16) ---
|
||||||
|
|
||||||
|
def _make_download_fn():
|
||||||
|
"""Closure capturing session, config, history, reporter for each book."""
|
||||||
|
|
||||||
|
def _download_fn(
|
||||||
|
book: Book, *, progress: Callable[[int], None] | None = None
|
||||||
|
):
|
||||||
|
# Build output plan for this book (paths + format strategy)
|
||||||
|
plan = resolve_output_plan(
|
||||||
|
book,
|
||||||
|
config.output_dir,
|
||||||
|
config=config,
|
||||||
|
format_strategy=config.format,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = download_book(book, client, plan, reporter, progress=progress)
|
||||||
|
|
||||||
|
# Write history as caller (no longer inside download_book)
|
||||||
|
if result.status == "downloaded":
|
||||||
|
_write_history(
|
||||||
|
history, book, result.format or "m4b", str(result.path)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Return Path | None for backward compat with orchestrator
|
||||||
|
if result.status == "downloaded":
|
||||||
|
return result.path
|
||||||
|
return None # skipped or failed
|
||||||
|
|
||||||
|
return _download_fn
|
||||||
|
|
||||||
|
result = download_all_books(
|
||||||
|
new_books,
|
||||||
|
workers=resolved_workers,
|
||||||
|
download_fn=_make_download_fn(),
|
||||||
|
reporter=reporter,
|
||||||
|
cancel_event=cancel_event,
|
||||||
|
)
|
||||||
|
|
||||||
|
downloaded = result.downloaded_count
|
||||||
|
skipped = result.skipped_count
|
||||||
|
failed = result.failed_count
|
||||||
|
failed_books = result.failed_books
|
||||||
|
skipped_books = result.skipped_books
|
||||||
|
|
||||||
|
reporter.summary(
|
||||||
|
downloaded=downloaded,
|
||||||
|
skipped=skipped,
|
||||||
|
failed=failed,
|
||||||
|
failed_books=failed_books,
|
||||||
|
skipped_books=skipped_books,
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.interrupted:
|
||||||
|
return SyncRunResult(
|
||||||
|
downloaded_count=downloaded,
|
||||||
|
skipped_count=skipped,
|
||||||
|
failed_count=failed,
|
||||||
|
failed_books=failed_books,
|
||||||
|
skipped_books=skipped_books,
|
||||||
|
interrupted=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
if verbose:
|
||||||
|
console.print("[dim]── done ────────────────────────────────────────[/dim]")
|
||||||
|
|
||||||
|
return SyncRunResult(
|
||||||
|
downloaded_count=downloaded,
|
||||||
|
skipped_count=skipped,
|
||||||
|
failed_count=failed,
|
||||||
|
failed_books=failed_books,
|
||||||
|
skipped_books=skipped_books,
|
||||||
|
interrupted=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
console.print("\n[yellow]Download interrupted by user (Ctrl+C).[/yellow]")
|
||||||
|
return SyncRunResult(interrupted=True)
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""Tests for librofm_downloader.book — Book dataclass and from_library_row() intake."""
|
||||||
|
|
||||||
|
from librofm_downloader.book import Book, from_library_row
|
||||||
|
|
||||||
|
|
||||||
|
class TestFromLibraryRowComplete:
|
||||||
|
"""Tracer bullet: from_library_row converts a full API dict to Book correctly."""
|
||||||
|
|
||||||
|
def test_all_fields_populated(self):
|
||||||
|
raw = {
|
||||||
|
"title": "The Great Adventure",
|
||||||
|
"authors": ["Jane Author"],
|
||||||
|
"narrators": ["Bob Narrator"],
|
||||||
|
"isbn": "9781234567890",
|
||||||
|
"series": "Adventure Series",
|
||||||
|
"series_num": 3,
|
||||||
|
"cover_url": "https://cdn.libro.fm/covers/123.jpg",
|
||||||
|
"audiobook_info": {
|
||||||
|
"narrators": ["Carol Narrator"],
|
||||||
|
"pdf_extras": True,
|
||||||
|
},
|
||||||
|
"publication_year": 2024,
|
||||||
|
"publication_month": 6,
|
||||||
|
"publication_day": 15,
|
||||||
|
}
|
||||||
|
|
||||||
|
book = from_library_row(raw)
|
||||||
|
|
||||||
|
assert book == Book(
|
||||||
|
title="The Great Adventure",
|
||||||
|
authors=["Jane Author"],
|
||||||
|
narrators=["Carol Narrator"], # audiobook_info.narrators takes priority
|
||||||
|
isbn="9781234567890",
|
||||||
|
series="Adventure Series",
|
||||||
|
series_num=3,
|
||||||
|
cover_url="https://cdn.libro.fm/covers/123.jpg",
|
||||||
|
pdf_extras=True,
|
||||||
|
publication_year=2024,
|
||||||
|
publication_month=6,
|
||||||
|
publication_day=15,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestMissingFields:
|
||||||
|
"""from_library_row applies correct defaults when raw dict is empty."""
|
||||||
|
|
||||||
|
def test_all_defaults_when_empty(self):
|
||||||
|
book = from_library_row({})
|
||||||
|
|
||||||
|
assert book.title == "Unknown"
|
||||||
|
assert book.authors == []
|
||||||
|
assert book.narrators == []
|
||||||
|
assert book.isbn == "?"
|
||||||
|
assert book.series == ""
|
||||||
|
assert book.series_num is None
|
||||||
|
assert book.cover_url == ""
|
||||||
|
assert book.pdf_extras is False
|
||||||
|
assert book.publication_year is None
|
||||||
|
assert book.publication_month is None
|
||||||
|
assert book.publication_day is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestIsbnCoercion:
|
||||||
|
"""API sometimes returns ISBN as int; from_library_row always stores str."""
|
||||||
|
|
||||||
|
def test_int_isbn_coerced_to_string(self):
|
||||||
|
raw = {"isbn": 9781234567890}
|
||||||
|
book = from_library_row(raw)
|
||||||
|
assert book.isbn == "9781234567890"
|
||||||
|
assert isinstance(book.isbn, str)
|
||||||
|
|
||||||
|
def test_string_isbn_passthrough(self):
|
||||||
|
raw = {"isbn": "9781234567890"}
|
||||||
|
book = from_library_row(raw)
|
||||||
|
assert book.isbn == "9781234567890"
|
||||||
|
|
||||||
|
def test_missing_isbn_default(self):
|
||||||
|
book = from_library_row({})
|
||||||
|
assert book.isbn == "?"
|
||||||
|
|
||||||
|
|
||||||
|
class TestNarratorResolution:
|
||||||
|
"""Narrators can live in audiobook_info.narrators (priority) or top-level."""
|
||||||
|
|
||||||
|
def test_audiobook_info_narrators_takes_priority(self):
|
||||||
|
raw = {
|
||||||
|
"narrators": ["Top-Level Narrator"],
|
||||||
|
"audiobook_info": {"narrators": ["Nested Narrator"]},
|
||||||
|
}
|
||||||
|
book = from_library_row(raw)
|
||||||
|
assert book.narrators == ["Nested Narrator"]
|
||||||
|
|
||||||
|
def test_fallback_to_top_level_narrators(self):
|
||||||
|
raw = {
|
||||||
|
"narrators": ["Top-Level Narrator"],
|
||||||
|
"audiobook_info": {}, # no narrators key inside
|
||||||
|
}
|
||||||
|
book = from_library_row(raw)
|
||||||
|
assert book.narrators == ["Top-Level Narrator"]
|
||||||
|
|
||||||
|
def test_both_missing_gives_empty_list(self):
|
||||||
|
raw = {"audiobook_info": {}}
|
||||||
|
book = from_library_row(raw)
|
||||||
|
assert book.narrators == []
|
||||||
|
|
||||||
|
def test_no_audiobook_info_uses_top_level(self):
|
||||||
|
raw = {"narrators": ["Only Narrator"]}
|
||||||
|
book = from_library_row(raw)
|
||||||
|
assert book.narrators == ["Only Narrator"]
|
||||||
|
|
||||||
|
def test_no_audiobook_info_and_no_top_level_gives_empty(self):
|
||||||
|
book = from_library_row({})
|
||||||
|
assert book.narrators == []
|
||||||
|
|
||||||
|
|
||||||
|
class TestPdfExtrasBoolCoercion:
|
||||||
|
"""PDF extras field needs robust bool coercion from various API shapes."""
|
||||||
|
|
||||||
|
def test_true_bool(self):
|
||||||
|
raw = {"audiobook_info": {"pdf_extras": True}}
|
||||||
|
assert from_library_row(raw).pdf_extras is True
|
||||||
|
|
||||||
|
def test_false_bool(self):
|
||||||
|
raw = {"audiobook_info": {"pdf_extras": False}}
|
||||||
|
assert from_library_row(raw).pdf_extras is False
|
||||||
|
|
||||||
|
def test_truthy_int_one(self):
|
||||||
|
raw = {"audiobook_info": {"pdf_extras": 1}}
|
||||||
|
assert from_library_row(raw).pdf_extras is True
|
||||||
|
|
||||||
|
def test_falsy_int_zero(self):
|
||||||
|
raw = {"audiobook_info": {"pdf_extras": 0}}
|
||||||
|
assert from_library_row(raw).pdf_extras is False
|
||||||
|
|
||||||
|
def test_pdf_extras_key_missing(self):
|
||||||
|
raw = {"audiobook_info": {}}
|
||||||
|
assert from_library_row(raw).pdf_extras is False
|
||||||
|
|
||||||
|
def test_audiobook_info_key_missing(self):
|
||||||
|
assert from_library_row({}).pdf_extras is False
|
||||||
+101
-1418
File diff suppressed because it is too large.
Load diff
+139
-118
@@ -1,4 +1,4 @@
|
|||||||
"""Tests for librofm_downloader.client — TDD vertical slices."""
|
"""Tests for librofm_downloader.session — TDD vertical slices."""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@@ -6,7 +6,7 @@ import logging
|
|||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from librofm_downloader.client import LibroFmClient, AuthError, M4BUnavailableError
|
from librofm_downloader.session import LibroFmSession, AuthError, M4BUnavailableError
|
||||||
|
|
||||||
|
|
||||||
class TestAuthenticate:
|
class TestAuthenticate:
|
||||||
@@ -14,11 +14,6 @@ class TestAuthenticate:
|
|||||||
|
|
||||||
def test_returns_access_token_on_valid_credentials(self):
|
def test_returns_access_token_on_valid_credentials(self):
|
||||||
"""Valid username/password → access_token returned."""
|
"""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:
|
def token_handler(request: httpx.Request) -> httpx.Response:
|
||||||
assert request.method == "POST"
|
assert request.method == "POST"
|
||||||
@@ -29,36 +24,37 @@ class TestAuthenticate:
|
|||||||
)
|
)
|
||||||
|
|
||||||
transport = httpx.MockTransport(token_handler)
|
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"
|
assert token == "tok_abc123"
|
||||||
|
|
||||||
def test_raises_auth_error_on_invalid_credentials(self):
|
def test_raises_auth_error_on_invalid_credentials(self):
|
||||||
"""Wrong password → AuthError with descriptive message."""
|
"""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:
|
def token_handler(request: httpx.Request) -> httpx.Response:
|
||||||
return httpx.Response(401, json={"error": "invalid_grant"})
|
return httpx.Response(401, json={"error": "invalid_grant"})
|
||||||
|
|
||||||
transport = httpx.MockTransport(token_handler)
|
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:
|
with pytest.raises(AuthError, match="Auth failed") as exc_info:
|
||||||
client.authenticate(transport=transport)
|
session.authenticate()
|
||||||
|
|
||||||
assert "401" in str(exc_info.value)
|
assert "401" in str(exc_info.value)
|
||||||
|
|
||||||
def test_sends_required_headers_with_auth_request(self):
|
def test_sends_required_headers_with_auth_request(self):
|
||||||
"""X-LibroFm-AppVer and User-Agent headers must be present."""
|
"""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] = {}
|
headers_captured: dict[str, str] = {}
|
||||||
|
|
||||||
def token_handler(request: httpx.Request) -> httpx.Response:
|
def token_handler(request: httpx.Request) -> httpx.Response:
|
||||||
@@ -69,7 +65,13 @@ class TestAuthenticate:
|
|||||||
)
|
)
|
||||||
|
|
||||||
transport = httpx.MockTransport(token_handler)
|
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["x-librofm-appver"] == "7.34.8"
|
||||||
assert headers_captured["user-agent"] == "okhttp/5.3.2"
|
assert headers_captured["user-agent"] == "okhttp/5.3.2"
|
||||||
@@ -80,12 +82,6 @@ class TestFetchLibrary:
|
|||||||
|
|
||||||
def test_returns_books_on_single_page(self):
|
def test_returns_books_on_single_page(self):
|
||||||
"""Single-page library returns all books, no pagination loop."""
|
"""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"}]
|
books = [{"isbn": "9781234567890", "title": "Test Book"}]
|
||||||
|
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
@@ -99,20 +95,20 @@ class TestFetchLibrary:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client.authenticate(transport=transport)
|
session = LibroFmSession(
|
||||||
result = client.fetch_library(transport=transport)
|
base_url="https://libro.fm",
|
||||||
|
username="alice",
|
||||||
|
password="secret123",
|
||||||
|
transport=transport,
|
||||||
|
)
|
||||||
|
session.authenticate()
|
||||||
|
result = session.fetch_library()
|
||||||
|
|
||||||
assert len(result) == 1
|
assert len(result) == 1
|
||||||
assert result[0]["isbn"] == "9781234567890"
|
assert result[0]["isbn"] == "9781234567890"
|
||||||
|
|
||||||
def test_paginates_through_all_pages(self):
|
def test_paginates_through_all_pages(self):
|
||||||
"""Multi-page library: follows next_page until exhausted."""
|
"""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"}]
|
page1_books = [{"isbn": "978111", "title": "Book A"}]
|
||||||
page2_books = [{"isbn": "978222", "title": "Book B"}, {"isbn": "978333", "title": "Book C"}]
|
page2_books = [{"isbn": "978222", "title": "Book B"}, {"isbn": "978333", "title": "Book C"}]
|
||||||
|
|
||||||
@@ -132,8 +128,14 @@ class TestFetchLibrary:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client.authenticate(transport=transport)
|
session = LibroFmSession(
|
||||||
result = client.fetch_library(transport=transport)
|
base_url="https://libro.fm",
|
||||||
|
username="alice",
|
||||||
|
password="secret123",
|
||||||
|
transport=transport,
|
||||||
|
)
|
||||||
|
session.authenticate()
|
||||||
|
result = session.fetch_library()
|
||||||
|
|
||||||
assert len(result) == 3
|
assert len(result) == 3
|
||||||
assert result[0]["isbn"] == "978111"
|
assert result[0]["isbn"] == "978111"
|
||||||
@@ -142,14 +144,14 @@ class TestFetchLibrary:
|
|||||||
|
|
||||||
def test_raises_auth_error_if_not_authenticated(self):
|
def test_raises_auth_error_if_not_authenticated(self):
|
||||||
"""Calling fetch_library before authenticate → clear error."""
|
"""Calling fetch_library before authenticate → clear error."""
|
||||||
client = LibroFmClient(
|
session = LibroFmSession(
|
||||||
base_url="https://libro.fm",
|
base_url="https://libro.fm",
|
||||||
username="alice",
|
username="alice",
|
||||||
password="secret123",
|
password="secret123",
|
||||||
)
|
)
|
||||||
|
|
||||||
with pytest.raises(AuthError, match="Not authenticated"):
|
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):
|
def test_returns_download_url_when_m4b_available(self):
|
||||||
"""Book with M4B format available → returns CDN URL string."""
|
"""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:
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
if request.url.path == "/oauth/token":
|
if request.url.path == "/oauth/token":
|
||||||
@@ -178,18 +175,19 @@ class TestFetchM4BUrl:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client.authenticate(transport=transport)
|
session = LibroFmSession(
|
||||||
url = client.fetch_m4b_url("9781234567890", transport=transport)
|
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"
|
assert url == "https://cdn.libro.fm/audiobooks/9781234567890.m4b"
|
||||||
|
|
||||||
def test_raises_m4b_unavailable_on_404(self):
|
def test_raises_m4b_unavailable_on_404(self):
|
||||||
"""Book without M4B format → raises M4BUnavailableError."""
|
"""Book without M4B format → raises M4BUnavailableError."""
|
||||||
client = LibroFmClient(
|
|
||||||
base_url="https://libro.fm",
|
|
||||||
username="alice",
|
|
||||||
password="secret123",
|
|
||||||
)
|
|
||||||
|
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
if request.url.path == "/oauth/token":
|
if request.url.path == "/oauth/token":
|
||||||
@@ -202,10 +200,16 @@ class TestFetchM4BUrl:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
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"):
|
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):
|
def test_returns_parts_and_tracks_when_available(self):
|
||||||
"""Book with MP3 format → returns parts list and track metadata."""
|
"""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:
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
if request.url.path == "/oauth/token":
|
if request.url.path == "/oauth/token":
|
||||||
@@ -247,8 +246,14 @@ class TestFetchDownloadManifest:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client.authenticate(transport=transport)
|
session = LibroFmSession(
|
||||||
manifest = client.fetch_download_manifest("9781234567890", transport=transport)
|
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 len(manifest["parts"]) == 2
|
||||||
assert manifest["parts"][0]["url"] == "https://cdn.libro.fm/part1.zip"
|
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):
|
def test_returns_empty_parts_when_no_mp3_available(self):
|
||||||
"""Book without MP3 format → returns empty manifest (404 or empty)."""
|
"""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:
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
if request.url.path == "/oauth/token":
|
if request.url.path == "/oauth/token":
|
||||||
@@ -275,10 +275,16 @@ class TestFetchDownloadManifest:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
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):
|
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):
|
def test_returns_pdf_url_when_available(self):
|
||||||
"""Book with PDF extra available → returns CDN URL string."""
|
"""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:
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
if request.url.path == "/oauth/token":
|
if request.url.path == "/oauth/token":
|
||||||
@@ -312,29 +313,33 @@ class TestFetchPdfExtraUrl:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client.authenticate(transport=transport)
|
session = LibroFmSession(
|
||||||
url = client.fetch_pdf_extra_url("9781234567890", "map.pdf", transport=transport)
|
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"
|
assert url == "https://cdn.libro.fm/pdf/9781234567890/map.pdf"
|
||||||
|
|
||||||
def test_raises_auth_error_if_not_authenticated(self):
|
def test_raises_auth_error_if_not_authenticated(self):
|
||||||
"""Calling fetch_pdf_extra_url before authenticate → clear error."""
|
"""Calling fetch_pdf_extra_url before authenticate → clear error."""
|
||||||
client = LibroFmClient(
|
session = LibroFmSession(
|
||||||
base_url="https://libro.fm",
|
base_url="https://libro.fm",
|
||||||
username="alice",
|
username="alice",
|
||||||
password="secret123",
|
password="secret123",
|
||||||
)
|
)
|
||||||
|
|
||||||
with pytest.raises(AuthError, match="Not authenticated"):
|
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
|
# API Rate Limiter — Issue #15
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
|
||||||
@@ -348,11 +353,6 @@ class TestApiRateLimiter:
|
|||||||
|
|
||||||
def test_semaphore_blocks_at_capacity(self):
|
def test_semaphore_blocks_at_capacity(self):
|
||||||
"""4 concurrent callers: 3 proceed immediately, 4th blocks until one finishes."""
|
"""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()
|
call_can_finish: threading.Event = threading.Event()
|
||||||
state_lock = threading.Lock()
|
state_lock = threading.Lock()
|
||||||
@@ -377,13 +377,19 @@ class TestApiRateLimiter:
|
|||||||
)
|
)
|
||||||
|
|
||||||
transport = httpx.MockTransport(slow_handler)
|
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] = []
|
errors: list[BaseException] = []
|
||||||
|
|
||||||
def fetch_thread(isbn: str):
|
def fetch_thread(isbn: str):
|
||||||
try:
|
try:
|
||||||
client.fetch_m4b_url(isbn, transport=transport)
|
session.fetch_m4b_url(isbn)
|
||||||
except BaseException as exc:
|
except BaseException as exc:
|
||||||
errors.append(exc)
|
errors.append(exc)
|
||||||
|
|
||||||
@@ -406,12 +412,6 @@ class TestApiRateLimiter:
|
|||||||
|
|
||||||
def test_semaphore_releases_on_exception(self):
|
def test_semaphore_releases_on_exception(self):
|
||||||
"""Semaphore is released even when the API call raises an exception."""
|
"""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
|
call_number = [1] # Use list for mutability in closure
|
||||||
|
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
@@ -430,18 +430,24 @@ class TestApiRateLimiter:
|
|||||||
)
|
)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
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)
|
# 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"
|
assert result == "https://cdn.libro.fm/test.m4b"
|
||||||
|
|
||||||
# Second call should raise (semaphore must still be released after this)
|
# Second call should raise (semaphore must still be released after this)
|
||||||
with pytest.raises(M4BUnavailableError):
|
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
|
# 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"
|
assert result3 == "https://cdn.libro.fm/test.m4b"
|
||||||
|
|
||||||
def test_cdn_downloads_bypass_semaphore(self):
|
def test_cdn_downloads_bypass_semaphore(self):
|
||||||
@@ -450,12 +456,6 @@ class TestApiRateLimiter:
|
|||||||
|
|
||||||
from librofm_downloader.downloader import download_m4b
|
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
|
# Fill all 3 API semaphore slots with slow calls that block
|
||||||
api_calls_blocked: threading.Event = threading.Event()
|
api_calls_blocked: threading.Event = threading.Event()
|
||||||
|
|
||||||
@@ -473,11 +473,17 @@ class TestApiRateLimiter:
|
|||||||
)
|
)
|
||||||
|
|
||||||
api_transport = httpx.MockTransport(slow_api_handler)
|
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
|
# Occupy all 3 semaphore slots with blocked API calls
|
||||||
api_threads = [
|
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 i in range(3)
|
||||||
]
|
]
|
||||||
for t in api_threads:
|
for t in api_threads:
|
||||||
@@ -509,12 +515,6 @@ class TestApiRateLimiter:
|
|||||||
|
|
||||||
def test_authenticate_and_fetch_library_not_limited(self):
|
def test_authenticate_and_fetch_library_not_limited(self):
|
||||||
"""authenticate() and fetch_library() do NOT acquire the API semaphore."""
|
"""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
|
# Fill all 3 API semaphore slots with blocked calls
|
||||||
api_calls_blocked: threading.Event = threading.Event()
|
api_calls_blocked: threading.Event = threading.Event()
|
||||||
|
|
||||||
@@ -530,12 +530,21 @@ class TestApiRateLimiter:
|
|||||||
json={"m4b_url": "https://cdn.libro.fm/test.m4b"},
|
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)
|
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
|
# Occupy all 3 slots
|
||||||
api_threads = [
|
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 i in range(3)
|
||||||
]
|
]
|
||||||
for t in api_threads:
|
for t in api_threads:
|
||||||
@@ -543,22 +552,34 @@ class TestApiRateLimiter:
|
|||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
|
|
||||||
# authenticate() should work fine — it doesn't use the semaphore
|
# 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:
|
def auth_handler(request: httpx.Request) -> httpx.Response:
|
||||||
return httpx.Response(
|
return httpx.Response(
|
||||||
200,
|
200,
|
||||||
json={"access_token": "tok_new", "token_type": "bearer", "expires_in": 7200},
|
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:
|
def library_handler(request: httpx.Request) -> httpx.Response:
|
||||||
return httpx.Response(200, json={"audiobooks": []})
|
return httpx.Response(200, json={"audiobooks": []})
|
||||||
|
|
||||||
library_transport = httpx.MockTransport(library_handler)
|
def combined_handler(request: httpx.Request) -> httpx.Response:
|
||||||
books = client.fetch_library(transport=library_transport)
|
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 == []
|
assert books == []
|
||||||
|
|
||||||
# Clean up
|
# Clean up
|
||||||
|
|||||||
+282
-88
@@ -6,21 +6,188 @@ import unittest
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|
||||||
from librofm_downloader.downloader import (
|
from librofm_downloader.book import Book
|
||||||
Book,
|
from librofm_downloader.path import (
|
||||||
|
sanitize,
|
||||||
|
resolve_path,
|
||||||
needs_subdirectory,
|
needs_subdirectory,
|
||||||
_resolve_output_dir,
|
_resolve_output_dir,
|
||||||
resolve_path,
|
OutputPlan,
|
||||||
sanitize,
|
resolve_output_plan,
|
||||||
|
)
|
||||||
|
from librofm_downloader.downloader import (
|
||||||
|
DownloadResult,
|
||||||
|
_write_history,
|
||||||
download_m4b,
|
download_m4b,
|
||||||
download_zip_part,
|
download_zip_part,
|
||||||
download_book,
|
download_book,
|
||||||
download_accompanying_files,
|
download_accompanying_files,
|
||||||
)
|
)
|
||||||
from librofm_downloader.client import LibroFmClient
|
from librofm_downloader.progress import DownloadReporter
|
||||||
|
from librofm_downloader.session import LibroFmSession
|
||||||
from librofm_downloader.history import DownloadHistory
|
from librofm_downloader.history import DownloadHistory
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Issue #29: DownloadResult dataclass
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestDownloadResult:
|
||||||
|
"""DownloadResult frozen dataclass — shape and immutability."""
|
||||||
|
|
||||||
|
def test_instantiates_with_each_status_value(self):
|
||||||
|
"""All three status values produce valid instances."""
|
||||||
|
downloaded = DownloadResult(status="downloaded", path=Path("/tmp/a.m4b"), format="m4b")
|
||||||
|
skipped = DownloadResult(status="skipped")
|
||||||
|
failed = DownloadResult(status="failed", error="network error")
|
||||||
|
|
||||||
|
assert downloaded.status == "downloaded"
|
||||||
|
assert skipped.status == "skipped"
|
||||||
|
assert failed.status == "failed"
|
||||||
|
|
||||||
|
def test_optional_fields_default_to_none(self):
|
||||||
|
"""path, format, error all default to None when omitted."""
|
||||||
|
result = DownloadResult(status="skipped")
|
||||||
|
|
||||||
|
assert result.path is None
|
||||||
|
assert result.format is None
|
||||||
|
assert result.error is None
|
||||||
|
|
||||||
|
def test_is_frozen(self):
|
||||||
|
"""Assigning to an attribute raises FrozenInstanceError."""
|
||||||
|
from dataclasses import FrozenInstanceError
|
||||||
|
|
||||||
|
result = DownloadResult(status="downloaded")
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
result.status = "failed" # type: ignore[misc]
|
||||||
|
|
||||||
|
def test_all_four_fields_present_on_downloaded_result(self):
|
||||||
|
"""A fully-populated 'downloaded' result has all fields set."""
|
||||||
|
result = DownloadResult(
|
||||||
|
status="downloaded",
|
||||||
|
path=Path("/out/book.m4b"),
|
||||||
|
format="m4b",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.status == "downloaded"
|
||||||
|
assert result.path == Path("/out/book.m4b")
|
||||||
|
assert result.format == "m4b"
|
||||||
|
assert result.error is None
|
||||||
|
|
||||||
|
def test_failed_result_carries_error_message(self):
|
||||||
|
"""A 'failed' result includes the error string."""
|
||||||
|
result = DownloadResult(
|
||||||
|
status="failed",
|
||||||
|
error="HTTP 500 Internal Server Error",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.status == "failed"
|
||||||
|
assert result.path is None
|
||||||
|
assert result.format is None
|
||||||
|
assert result.error == "HTTP 500 Internal Server Error"
|
||||||
|
|
||||||
|
|
||||||
|
class TestDownloadBookNewInterface:
|
||||||
|
"""download_book() with 4 domain-aligned params returning DownloadResult."""
|
||||||
|
|
||||||
|
def test_returns_download_result_on_successful_m4b(self):
|
||||||
|
"""New 4-param signature returns DownloadResult(status='downloaded') for M4B."""
|
||||||
|
import io
|
||||||
|
|
||||||
|
m4b_payload = b"new-interface-test-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"},
|
||||||
|
)
|
||||||
|
if "cdn.example.com" in request.url.host:
|
||||||
|
return httpx.Response(200, content=m4b_payload)
|
||||||
|
return httpx.Response(404)
|
||||||
|
|
||||||
|
transport = httpx.MockTransport(handler)
|
||||||
|
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
|
client.authenticate()
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="Interface Test Book",
|
||||||
|
authors=["Test Author"],
|
||||||
|
narrators=["Test Narr"],
|
||||||
|
isbn="9781111111111",
|
||||||
|
)
|
||||||
|
|
||||||
|
from librofm_downloader.progress import DownloadReporter
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
base_dir = Path(tmpdir) / "audiobooks"
|
||||||
|
plan = resolve_output_plan(book, base_dir, format_strategy="m4b_mp3_fallback")
|
||||||
|
reporter = DownloadReporter()
|
||||||
|
|
||||||
|
result = download_book(book, client, plan, reporter)
|
||||||
|
|
||||||
|
# Returns DownloadResult, not Path | None
|
||||||
|
assert isinstance(result, DownloadResult)
|
||||||
|
assert result.status == "downloaded"
|
||||||
|
assert result.path is not None
|
||||||
|
assert result.path.exists()
|
||||||
|
assert result.format == "m4b"
|
||||||
|
|
||||||
|
def test_uses_provided_progress_callback_over_reporter_update(self):
|
||||||
|
"""When progress= is passed, download_book uses it instead of reporter.update.
|
||||||
|
|
||||||
|
Issue #30: The orchestrator passes a bound callable from start_download().
|
||||||
|
download_book must thread it through to the chunk loop, not ignore it.
|
||||||
|
"""
|
||||||
|
import httpx
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
from librofm_downloader.downloader import download_book
|
||||||
|
|
||||||
|
m4b_payload = b"progress-callback-test-data" * 10 # 240 bytes
|
||||||
|
received: list[int] = []
|
||||||
|
|
||||||
|
def my_callback(completed: int, *, total: int | None = None) -> None:
|
||||||
|
received.append(completed)
|
||||||
|
|
||||||
|
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 "/packaged_m4b" in request.url.path:
|
||||||
|
return httpx.Response(
|
||||||
|
200,
|
||||||
|
json={"m4b_url": "https://cdn.example.com/book.m4b"},
|
||||||
|
)
|
||||||
|
if "cdn.example.com" in request.url.host:
|
||||||
|
return httpx.Response(200, content=m4b_payload, headers={"Content-Length": str(len(m4b_payload))})
|
||||||
|
return httpx.Response(404)
|
||||||
|
|
||||||
|
transport = httpx.MockTransport(handler)
|
||||||
|
session = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
|
session.authenticate()
|
||||||
|
|
||||||
|
book = Book(title="Callback Test", authors=["Author"], narrators=["N"], isbn="9789900000000")
|
||||||
|
reporter = MagicMock()
|
||||||
|
reporter.cancel_event = None
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
plan = resolve_output_plan(book, Path(tmpdir), format_strategy="m4b_only")
|
||||||
|
result = download_book(book, session, plan, reporter, progress=my_callback)
|
||||||
|
|
||||||
|
assert result.status == "downloaded"
|
||||||
|
# Our callback should have been called (not reporter.update)
|
||||||
|
assert len(received) >= 1, "Bound callback should receive progress updates"
|
||||||
|
# reporter.update should NOT have been called
|
||||||
|
reporter.update.assert_not_called()
|
||||||
|
|
||||||
class TestSanitizeIllegalChars:
|
class TestSanitizeIllegalChars:
|
||||||
"""Sanitization strips characters that are unsafe in filesystem paths."""
|
"""Sanitization strips characters that are unsafe in filesystem paths."""
|
||||||
|
|
||||||
@@ -862,7 +1029,7 @@ class TestDownloadBook:
|
|||||||
"""End-to-end orchestration with mocked HTTP."""
|
"""End-to-end orchestration with mocked HTTP."""
|
||||||
|
|
||||||
def test_writes_history_entry_after_successful_download(self):
|
def test_writes_history_entry_after_successful_download(self):
|
||||||
"""After successful M4B download, history entry is persisted."""
|
"""After successful M4B download, caller writes history entry."""
|
||||||
m4b_payload = b"complete-m4b-audio-data"
|
m4b_payload = b"complete-m4b-audio-data"
|
||||||
|
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
@@ -882,8 +1049,8 @@ class TestDownloadBook:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
client.authenticate(transport=transport)
|
client.authenticate()
|
||||||
|
|
||||||
book = Book(
|
book = Book(
|
||||||
title="History Test Book",
|
title="History Test Book",
|
||||||
@@ -897,23 +1064,27 @@ class TestDownloadBook:
|
|||||||
history_path = Path(tmpdir) / "history.json"
|
history_path = Path(tmpdir) / "history.json"
|
||||||
history = DownloadHistory(history_path)
|
history = DownloadHistory(history_path)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, base_dir)
|
||||||
|
reporter = DownloadReporter()
|
||||||
result = download_book(
|
result = download_book(
|
||||||
book=book,
|
book=book,
|
||||||
client=client,
|
session=client,
|
||||||
output_base=base_dir,
|
plan=plan,
|
||||||
history=history,
|
reporter=reporter,
|
||||||
transport=transport,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# History is caller's responsibility now
|
||||||
|
assert result.status == "downloaded"
|
||||||
|
_write_history(history, book, result.format or "m4b", str(result.path))
|
||||||
|
|
||||||
# History was written
|
# History was written
|
||||||
assert history.is_downloaded("9781111111111")
|
assert history.is_downloaded("9781111111111")
|
||||||
entry = history.find("9781111111111")
|
entry = history.find("9781111111111")
|
||||||
assert entry is not None
|
assert entry is not None
|
||||||
assert entry.format == "m4b"
|
assert entry.format == "m4b"
|
||||||
assert entry.title == "History Test Book"
|
assert entry.title == "History Test Book"
|
||||||
|
|
||||||
def test_skips_book_without_m4b(self):
|
def test_skips_book_without_m4b(self):
|
||||||
"""Book with no M4B available → returns None, no history entry, no error."""
|
"""Book with no M4B available → DownloadResult(skipped), no history entry."""
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
if request.url.path == "/oauth/token":
|
if request.url.path == "/oauth/token":
|
||||||
return httpx.Response(
|
return httpx.Response(
|
||||||
@@ -925,8 +1096,8 @@ class TestDownloadBook:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
client.authenticate(transport=transport)
|
client.authenticate()
|
||||||
|
|
||||||
book = Book(
|
book = Book(
|
||||||
title="No M4B Book",
|
title="No M4B Book",
|
||||||
@@ -940,16 +1111,17 @@ class TestDownloadBook:
|
|||||||
history_path = Path(tmpdir) / "history.json"
|
history_path = Path(tmpdir) / "history.json"
|
||||||
history = DownloadHistory(history_path)
|
history = DownloadHistory(history_path)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, base_dir)
|
||||||
|
reporter = DownloadReporter()
|
||||||
result = download_book(
|
result = download_book(
|
||||||
book=book,
|
book=book,
|
||||||
client=client,
|
session=client,
|
||||||
output_base=base_dir,
|
plan=plan,
|
||||||
history=history,
|
reporter=reporter,
|
||||||
transport=transport,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Returns None (skipped)
|
# Returns skipped (no M4B in m4b_mp3_fallback → tries MP3 manifest → also 404)
|
||||||
assert result is None
|
assert result.status == "skipped"
|
||||||
# No history entry written
|
# No history entry written
|
||||||
assert history.is_downloaded("9780000000000") is False
|
assert history.is_downloaded("9780000000000") is False
|
||||||
|
|
||||||
@@ -972,8 +1144,8 @@ class TestDownloadBook:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
client.authenticate(transport=transport)
|
client.authenticate()
|
||||||
|
|
||||||
book = Book(
|
book = Book(
|
||||||
title="Fail Book",
|
title="Fail Book",
|
||||||
@@ -987,13 +1159,14 @@ class TestDownloadBook:
|
|||||||
history_path = Path(tmpdir) / "history.json"
|
history_path = Path(tmpdir) / "history.json"
|
||||||
history = DownloadHistory(history_path)
|
history = DownloadHistory(history_path)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, base_dir)
|
||||||
|
reporter = DownloadReporter()
|
||||||
with pytest.raises(httpx.HTTPStatusError):
|
with pytest.raises(httpx.HTTPStatusError):
|
||||||
download_book(
|
download_book(
|
||||||
book=book,
|
book=book,
|
||||||
client=client,
|
session=client,
|
||||||
output_base=base_dir,
|
plan=plan,
|
||||||
history=history,
|
reporter=reporter,
|
||||||
transport=transport,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# No history entry written for failed download
|
# No history entry written for failed download
|
||||||
@@ -1014,8 +1187,8 @@ class TestDownloadBook:
|
|||||||
return httpx.Response(200, content=payload)
|
return httpx.Response(200, content=payload)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
client.authenticate(transport=transport)
|
client.authenticate()
|
||||||
|
|
||||||
book = Book(
|
book = Book(
|
||||||
title="Standalone Book",
|
title="Standalone Book",
|
||||||
@@ -1030,21 +1203,23 @@ class TestDownloadBook:
|
|||||||
history_path = Path(tmpdir) / "history.json"
|
history_path = Path(tmpdir) / "history.json"
|
||||||
history = DownloadHistory(history_path)
|
history = DownloadHistory(history_path)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, base_dir)
|
||||||
|
reporter = DownloadReporter()
|
||||||
result = download_book(
|
result = download_book(
|
||||||
book=book,
|
book=book,
|
||||||
client=client,
|
session=client,
|
||||||
output_base=base_dir,
|
plan=plan,
|
||||||
history=history,
|
reporter=reporter,
|
||||||
transport=transport,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# File is at leaf (flat), not inside a subdirectory
|
# File is at leaf (flat), not inside a subdirectory
|
||||||
assert result is not None
|
assert result.status == "downloaded"
|
||||||
|
assert result.path is not None
|
||||||
# Path should be base/Author/Title.m4b (flat) — title is filename stem
|
# Path should be base/Author/Title.m4b (flat) — title is filename stem
|
||||||
assert result.stem == "Standalone Book"
|
assert result.path.stem == "Standalone Book"
|
||||||
# No extra subdirectory between author and file
|
# No extra subdirectory between author and file
|
||||||
assert result.parent.name == "Solo Author"
|
assert result.path.parent.name == "Solo Author"
|
||||||
assert result.exists()
|
assert result.path.exists()
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -1090,8 +1265,8 @@ class TestFormatStrategy:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
client.authenticate(transport=transport)
|
client.authenticate()
|
||||||
|
|
||||||
book = Book(title="M4B Available", authors=["A"], narrators=["N"], isbn="9781111111111")
|
book = Book(title="M4B Available", authors=["A"], narrators=["N"], isbn="9781111111111")
|
||||||
|
|
||||||
@@ -1100,21 +1275,24 @@ class TestFormatStrategy:
|
|||||||
history_path = Path(tmpdir) / "history.json"
|
history_path = Path(tmpdir) / "history.json"
|
||||||
history = DownloadHistory(history_path)
|
history = DownloadHistory(history_path)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, base_dir, format_strategy="m4b_mp3_fallback")
|
||||||
|
reporter = DownloadReporter()
|
||||||
result = download_book(
|
result = download_book(
|
||||||
book=book,
|
book=book,
|
||||||
client=client,
|
session=client,
|
||||||
output_base=base_dir,
|
plan=plan,
|
||||||
history=history,
|
reporter=reporter,
|
||||||
format_strategy="m4b_mp3_fallback",
|
|
||||||
transport=transport,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# M4B was downloaded (not MP3)
|
# M4B was downloaded (not MP3)
|
||||||
assert result is not None
|
assert result.status == "downloaded"
|
||||||
assert result.suffix == ".m4b"
|
assert result.path is not None
|
||||||
|
assert result.path.suffix == ".m4b"
|
||||||
|
assert result.format == "m4b"
|
||||||
# Manifest was never queried
|
# Manifest was never queried
|
||||||
assert len(mp3_calls) == 0
|
assert len(mp3_calls) == 0
|
||||||
# History records M4B format
|
# History is caller's responsibility now
|
||||||
|
_write_history(history, book, result.format, str(result.path))
|
||||||
entry = history.find("9781111111111")
|
entry = history.find("9781111111111")
|
||||||
assert entry is not None
|
assert entry is not None
|
||||||
assert entry.format == "m4b"
|
assert entry.format == "m4b"
|
||||||
@@ -1149,8 +1327,8 @@ class TestFormatStrategy:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
client.authenticate(transport=transport)
|
client.authenticate()
|
||||||
|
|
||||||
book = Book(title="MP3 Fallback Book", authors=["A"], narrators=["N"], isbn="9782222222222")
|
book = Book(title="MP3 Fallback Book", authors=["A"], narrators=["N"], isbn="9782222222222")
|
||||||
|
|
||||||
@@ -1159,21 +1337,24 @@ class TestFormatStrategy:
|
|||||||
history_path = Path(tmpdir) / "history.json"
|
history_path = Path(tmpdir) / "history.json"
|
||||||
history = DownloadHistory(history_path)
|
history = DownloadHistory(history_path)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, base_dir, format_strategy="m4b_mp3_fallback")
|
||||||
|
reporter = DownloadReporter()
|
||||||
result = download_book(
|
result = download_book(
|
||||||
book=book,
|
book=book,
|
||||||
client=client,
|
session=client,
|
||||||
output_base=base_dir,
|
plan=plan,
|
||||||
history=history,
|
reporter=reporter,
|
||||||
format_strategy="m4b_mp3_fallback",
|
|
||||||
transport=transport,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# MP3 files were extracted
|
# MP3 files were extracted
|
||||||
assert result is not None
|
assert result.status == "downloaded"
|
||||||
|
assert result.path is not None
|
||||||
|
assert result.format == "mp3"
|
||||||
# At least one .mp3 file exists in output tree
|
# At least one .mp3 file exists in output tree
|
||||||
mp3_files = list(base_dir.rglob("*.mp3"))
|
mp3_files = list(base_dir.rglob("*.mp3"))
|
||||||
assert len(mp3_files) >= 1
|
assert len(mp3_files) >= 1
|
||||||
# History records mp3 format
|
# History is caller's responsibility now
|
||||||
|
_write_history(history, book, result.format, str(result.path))
|
||||||
entry = history.find("9782222222222")
|
entry = history.find("9782222222222")
|
||||||
assert entry is not None
|
assert entry is not None
|
||||||
assert entry.format == "mp3"
|
assert entry.format == "mp3"
|
||||||
@@ -1210,8 +1391,8 @@ class TestFormatStrategy:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
client.authenticate(transport=transport)
|
client.authenticate()
|
||||||
|
|
||||||
book = Book(title="MP3 Only Book", authors=["A"], narrators=["N"], isbn="9783333333333")
|
book = Book(title="MP3 Only Book", authors=["A"], narrators=["N"], isbn="9783333333333")
|
||||||
|
|
||||||
@@ -1220,22 +1401,25 @@ class TestFormatStrategy:
|
|||||||
history_path = Path(tmpdir) / "history.json"
|
history_path = Path(tmpdir) / "history.json"
|
||||||
history = DownloadHistory(history_path)
|
history = DownloadHistory(history_path)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, base_dir, format_strategy="mp3_only")
|
||||||
|
reporter = DownloadReporter()
|
||||||
result = download_book(
|
result = download_book(
|
||||||
book=book,
|
book=book,
|
||||||
client=client,
|
session=client,
|
||||||
output_base=base_dir,
|
plan=plan,
|
||||||
history=history,
|
reporter=reporter,
|
||||||
format_strategy="mp3_only",
|
|
||||||
transport=transport,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# MP3 files extracted
|
# MP3 files extracted
|
||||||
assert result is not None
|
assert result.status == "downloaded"
|
||||||
|
assert result.path is not None
|
||||||
|
assert result.format == "mp3"
|
||||||
mp3_files = list(base_dir.rglob("*.mp3"))
|
mp3_files = list(base_dir.rglob("*.mp3"))
|
||||||
assert len(mp3_files) >= 1
|
assert len(mp3_files) >= 1
|
||||||
# M4B was never queried
|
# M4B was never queried
|
||||||
assert len(m4b_calls) == 0
|
assert len(m4b_calls) == 0
|
||||||
# History records mp3 format
|
# History is caller's responsibility now
|
||||||
|
_write_history(history, book, result.format, str(result.path))
|
||||||
entry = history.find("9783333333333")
|
entry = history.find("9783333333333")
|
||||||
assert entry is not None
|
assert entry is not None
|
||||||
assert entry.format == "mp3"
|
assert entry.format == "mp3"
|
||||||
@@ -1259,8 +1443,8 @@ class TestFormatStrategy:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
client.authenticate(transport=transport)
|
client.authenticate()
|
||||||
|
|
||||||
book = Book(title="No M4B Skip", authors=["A"], narrators=["N"], isbn="9780000000000")
|
book = Book(title="No M4B Skip", authors=["A"], narrators=["N"], isbn="9780000000000")
|
||||||
|
|
||||||
@@ -1269,17 +1453,17 @@ class TestFormatStrategy:
|
|||||||
history_path = Path(tmpdir) / "history.json"
|
history_path = Path(tmpdir) / "history.json"
|
||||||
history = DownloadHistory(history_path)
|
history = DownloadHistory(history_path)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, base_dir, format_strategy="m4b_only")
|
||||||
|
reporter = DownloadReporter()
|
||||||
result = download_book(
|
result = download_book(
|
||||||
book=book,
|
book=book,
|
||||||
client=client,
|
session=client,
|
||||||
output_base=base_dir,
|
plan=plan,
|
||||||
history=history,
|
reporter=reporter,
|
||||||
format_strategy="m4b_only",
|
|
||||||
transport=transport,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Skipped (no M4B)
|
# Skipped (no M4B)
|
||||||
assert result is None
|
assert result.status == "skipped"
|
||||||
# Manifest was never queried
|
# Manifest was never queried
|
||||||
assert len(manifest_calls) == 0
|
assert len(manifest_calls) == 0
|
||||||
# No history entry
|
# No history entry
|
||||||
@@ -1323,10 +1507,12 @@ class TestDownloadAccompanyingFiles:
|
|||||||
output_dir=str(tmpdir), download_extras=True, download_covers=True,
|
output_dir=str(tmpdir), download_extras=True, download_covers=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
download_accompanying_files(book, output_dir, config, transport=transport)
|
plan = resolve_output_plan(book, output_dir, config=config)
|
||||||
|
download_accompanying_files(book, plan, transport=transport)
|
||||||
|
|
||||||
# Cover file exists in output directory
|
# Cover file exists at plan.resolved location
|
||||||
cover_path = output_dir / "cover.jpg"
|
cover_path = plan.cover_path
|
||||||
|
assert cover_path is not None
|
||||||
assert cover_path.exists()
|
assert cover_path.exists()
|
||||||
assert cover_path.read_bytes() == cover_payload
|
assert cover_path.read_bytes() == cover_payload
|
||||||
|
|
||||||
@@ -1363,10 +1549,12 @@ class TestDownloadAccompanyingFiles:
|
|||||||
mock_client = unittest.mock.MagicMock()
|
mock_client = unittest.mock.MagicMock()
|
||||||
mock_client.fetch_pdf_extra_url.return_value = "https://cdn.example.com/map.pdf"
|
mock_client.fetch_pdf_extra_url.return_value = "https://cdn.example.com/map.pdf"
|
||||||
|
|
||||||
downloaded = download_accompanying_files(book, output_dir, config, client=mock_client, transport=transport)
|
plan = resolve_output_plan(book, output_dir, config=config)
|
||||||
|
downloaded = download_accompanying_files(book, plan, client=mock_client, transport=transport)
|
||||||
|
|
||||||
# PDF file exists in output directory
|
# PDF file exists at plan.resolved location
|
||||||
pdf_path = output_dir / "map.pdf"
|
pdf_path = plan.pdf_path
|
||||||
|
assert pdf_path is not None
|
||||||
assert pdf_path.exists()
|
assert pdf_path.exists()
|
||||||
assert pdf_path.read_bytes() == pdf_payload
|
assert pdf_path.read_bytes() == pdf_payload
|
||||||
|
|
||||||
@@ -1399,14 +1587,16 @@ class TestDownloadAccompanyingFiles:
|
|||||||
output_dir=str(tmpdir), download_extras=True, download_covers=True,
|
output_dir=str(tmpdir), download_extras=True, download_covers=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
download_accompanying_files(book, output_dir, config, transport=transport)
|
plan = resolve_output_plan(book, output_dir, config=config)
|
||||||
|
download_accompanying_files(book, plan, transport=transport)
|
||||||
|
|
||||||
# Final file exists
|
# Final file exists at plan.resolved location
|
||||||
final_path = output_dir / "cover.jpg"
|
final_path = plan.cover_path
|
||||||
|
assert final_path is not None
|
||||||
assert final_path.exists()
|
assert final_path.exists()
|
||||||
|
|
||||||
# No .partial file left behind
|
# No .partial file left behind
|
||||||
partial_path = output_dir / "cover.jpg.partial"
|
partial_path = final_path.with_suffix(final_path.suffix + ".partial")
|
||||||
assert not partial_path.exists()
|
assert not partial_path.exists()
|
||||||
|
|
||||||
def test_download_extras_false_skips_pdf(self):
|
def test_download_extras_false_skips_pdf(self):
|
||||||
@@ -1432,7 +1622,8 @@ class TestDownloadAccompanyingFiles:
|
|||||||
output_dir=str(tmpdir), download_extras=False, download_covers=True,
|
output_dir=str(tmpdir), download_extras=False, download_covers=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
downloaded = download_accompanying_files(book, output_dir, config, client=mock_client)
|
plan = resolve_output_plan(book, output_dir, config=config)
|
||||||
|
downloaded = download_accompanying_files(book, plan, client=mock_client)
|
||||||
|
|
||||||
# No files downloaded (no cover URL either)
|
# No files downloaded (no cover URL either)
|
||||||
assert len(downloaded) == 0
|
assert len(downloaded) == 0
|
||||||
@@ -1460,7 +1651,8 @@ class TestDownloadAccompanyingFiles:
|
|||||||
output_dir=str(tmpdir), download_extras=True, download_covers=False,
|
output_dir=str(tmpdir), download_extras=True, download_covers=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
downloaded = download_accompanying_files(book, output_dir, config)
|
plan = resolve_output_plan(book, output_dir, config=config)
|
||||||
|
downloaded = download_accompanying_files(book, plan)
|
||||||
|
|
||||||
# No files downloaded (no PDF extras either)
|
# No files downloaded (no PDF extras either)
|
||||||
assert len(downloaded) == 0
|
assert len(downloaded) == 0
|
||||||
@@ -1495,7 +1687,8 @@ class TestDownloadAccompanyingFiles:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Should NOT raise — failure is non-critical
|
# Should NOT raise — failure is non-critical
|
||||||
result = download_accompanying_files(book, output_dir, config, transport=transport)
|
plan = resolve_output_plan(book, output_dir, config=config)
|
||||||
|
result = download_accompanying_files(book, plan, transport=transport)
|
||||||
|
|
||||||
# Returns empty list (nothing downloaded)
|
# Returns empty list (nothing downloaded)
|
||||||
assert result == []
|
assert result == []
|
||||||
@@ -1680,7 +1873,8 @@ class TestOutputStructure:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Should NOT raise — failure is non-critical
|
# Should NOT raise — failure is non-critical
|
||||||
result = download_accompanying_files(book, output_dir, config, client=mock_client)
|
plan = resolve_output_plan(book, output_dir, config=config)
|
||||||
|
result = download_accompanying_files(book, plan, client=mock_client)
|
||||||
|
|
||||||
# Returns empty list (nothing downloaded)
|
# Returns empty list (nothing downloaded)
|
||||||
assert result == []
|
assert result == []
|
||||||
@@ -8,7 +8,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from librofm_downloader.downloader import Book
|
from librofm_downloader.book import Book
|
||||||
from librofm_downloader.orchestrator import OrchestratorResult, download_all_books
|
from librofm_downloader.orchestrator import OrchestratorResult, download_all_books
|
||||||
|
|
||||||
|
|
||||||
@@ -876,3 +876,79 @@ class TestCtrlCDrain:
|
|||||||
assert len(completed_isbns) < 3, (
|
assert len(completed_isbns) < 3, (
|
||||||
f"Cooperative cancel should stop early; got {len(completed_isbns)} completions"
|
f"Cooperative cancel should stop early; got {len(completed_isbns)} completions"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Issue #30: Bound Callable — Orchestrator uses callback directly
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestOrchestratorUsesBoundCallback:
|
||||||
|
"""Orchestrator passes start_download()'s bound callable to download_fn.
|
||||||
|
|
||||||
|
Issue #30: No closure-wiring code in _download_one. The reporter owns
|
||||||
|
task identity; the orchestrator just threads the callable through.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_download_fn_receives_bound_callback_from_reporter(self):
|
||||||
|
"""download_fn(progress=...) gets the callable returned by start_download()."""
|
||||||
|
received_callbacks: list = []
|
||||||
|
|
||||||
|
class TrackingReporter:
|
||||||
|
"""Returns a per-book callable from start_download()."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.started: list[Book] = []
|
||||||
|
self.completed: list[Book] = []
|
||||||
|
self._callables: list[callable] = []
|
||||||
|
|
||||||
|
def start_download(self, book: Book, total_bytes: int = 0) -> callable:
|
||||||
|
self.started.append(book)
|
||||||
|
cb = lambda completed, **kw: None # no-op but unique per book
|
||||||
|
self._callables.append(cb)
|
||||||
|
return cb
|
||||||
|
|
||||||
|
def complete(self, book: Book) -> None:
|
||||||
|
self.completed.append(book)
|
||||||
|
|
||||||
|
def fail(self, book: Book, reason: str = "") -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def summary(self, **kwargs) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def download_fn(book: Book, *, progress=None) -> Path | None:
|
||||||
|
# Capture whatever the orchestrator passes as progress=
|
||||||
|
received_callbacks.append((book.isbn, progress))
|
||||||
|
return Path(f"/fake/{book.isbn}.m4b")
|
||||||
|
|
||||||
|
raw_books = [
|
||||||
|
_make_raw_book(isbn="978111", title="Book A"),
|
||||||
|
_make_raw_book(isbn="978222", title="Book B"),
|
||||||
|
]
|
||||||
|
|
||||||
|
reporter = TrackingReporter()
|
||||||
|
result = download_all_books(
|
||||||
|
raw_books,
|
||||||
|
workers=2,
|
||||||
|
download_fn=download_fn,
|
||||||
|
reporter=reporter,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.downloaded_count == 2
|
||||||
|
assert len(received_callbacks) == 2
|
||||||
|
|
||||||
|
# Each book should have received its OWN bound callable (not None, not shared)
|
||||||
|
isbn_a, cb_a = received_callbacks[0]
|
||||||
|
isbn_b, cb_b = received_callbacks[1]
|
||||||
|
|
||||||
|
assert callable(cb_a), f"Book A's progress should be callable, got {type(cb_a)}"
|
||||||
|
assert callable(cb_b), f"Book B's progress should be callable, got {type(cb_b)}"
|
||||||
|
assert cb_a is not cb_b, "Each book must get its own bound callable"
|
||||||
|
|
||||||
|
# The callables must be exactly the ones the reporter created
|
||||||
|
assert cb_a in reporter._callables
|
||||||
|
assert cb_b in reporter._callables
|
||||||
@@ -0,0 +1,853 @@
|
|||||||
|
"""Tests for librofm_downloader.path — TDD vertical slices."""
|
||||||
|
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from librofm_downloader.book import Book
|
||||||
|
from librofm_downloader.path import (
|
||||||
|
OutputPlan,
|
||||||
|
needs_subdirectory,
|
||||||
|
_resolve_output_dir,
|
||||||
|
resolve_output_plan,
|
||||||
|
resolve_path,
|
||||||
|
sanitize,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestSanitizeIllegalChars:
|
||||||
|
"""Sanitization strips characters that are unsafe in filesystem paths."""
|
||||||
|
|
||||||
|
def test_strips_angle_brackets(self):
|
||||||
|
assert sanitize("Foo<Bar>") == "FooBar"
|
||||||
|
|
||||||
|
def test_strips_forward_slash(self):
|
||||||
|
assert sanitize("Foo/Bar") == "FooBar"
|
||||||
|
|
||||||
|
def test_strips_backslash(self):
|
||||||
|
assert sanitize("Foo\\Bar") == "FooBar"
|
||||||
|
|
||||||
|
def test_strips_pipe(self):
|
||||||
|
assert sanitize("Foo|Bar") == "FooBar"
|
||||||
|
|
||||||
|
def test_strips_question_mark(self):
|
||||||
|
assert sanitize("Foo?Bar") == "FooBar"
|
||||||
|
|
||||||
|
def test_strips_asterisk(self):
|
||||||
|
assert sanitize("Foo*Bar") == "FooBar"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSanitizeColonReplacement:
|
||||||
|
"""Colons are replaced with ' -' (space-dash), not stripped."""
|
||||||
|
|
||||||
|
def test_single_colon_replaced(self):
|
||||||
|
assert sanitize("Part A: Part B") == "Part A - Part B"
|
||||||
|
|
||||||
|
def test_multiple_colons_replaced(self):
|
||||||
|
assert sanitize("A:B:C") == "A -B -C"
|
||||||
|
|
||||||
|
def test_colon_with_illegal_chars(self):
|
||||||
|
# Colon replaced first, then illegal chars stripped
|
||||||
|
assert sanitize("Foo:<>Bar") == "Foo -Bar"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSanitizeControlChars:
|
||||||
|
"""Control characters U+0000–U+001F are stripped."""
|
||||||
|
|
||||||
|
def test_strips_null_byte(self):
|
||||||
|
assert sanitize("Foo\x00Bar") == "FooBar"
|
||||||
|
|
||||||
|
def test_strips_tab(self):
|
||||||
|
assert sanitize("Foo\tBar") == "FooBar"
|
||||||
|
|
||||||
|
def test_strips_newline(self):
|
||||||
|
assert sanitize("Foo\nBar") == "FooBar"
|
||||||
|
|
||||||
|
def test_strips_carriage_return(self):
|
||||||
|
assert sanitize("Foo\rBar") == "FooBar"
|
||||||
|
|
||||||
|
def test_strips_multiple_control_chars(self):
|
||||||
|
assert sanitize("\x01\x02Hello\x1F\x1E") == "Hello"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSanitizeTrailingDots:
|
||||||
|
"""Trailing dots are removed (problematic on Windows)."""
|
||||||
|
|
||||||
|
def test_removes_single_trailing_dot(self):
|
||||||
|
assert sanitize("filename.") == "filename"
|
||||||
|
|
||||||
|
def test_removes_multiple_trailing_dots(self):
|
||||||
|
assert sanitize("filename...") == "filename"
|
||||||
|
|
||||||
|
def test_preserves_internal_dots(self):
|
||||||
|
assert sanitize("file.name.txt") == "file.name.txt"
|
||||||
|
|
||||||
|
def test_trailing_dot_after_whitespace_trim(self):
|
||||||
|
assert sanitize(" filename. ") == "filename"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSanitizeTrimWhitespace:
|
||||||
|
"""Leading and trailing whitespace is trimmed."""
|
||||||
|
|
||||||
|
def test_trims_leading_space(self):
|
||||||
|
assert sanitize(" filename") == "filename"
|
||||||
|
|
||||||
|
def test_trims_trailing_space(self):
|
||||||
|
assert sanitize("filename ") == "filename"
|
||||||
|
|
||||||
|
def test_trims_both_ends(self):
|
||||||
|
assert sanitize(" filename ") == "filename"
|
||||||
|
|
||||||
|
def test_preserves_internal_spaces(self):
|
||||||
|
assert sanitize("my filename") == "my filename"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSanitizeLengthCap:
|
||||||
|
"""Components are capped at 255 characters."""
|
||||||
|
|
||||||
|
def test_short_string_unchanged(self):
|
||||||
|
short = "a" * 100
|
||||||
|
assert sanitize(short) == short
|
||||||
|
|
||||||
|
def test_capped_at_255_chars(self):
|
||||||
|
long = "a" * 300
|
||||||
|
assert len(sanitize(long)) == 255
|
||||||
|
|
||||||
|
def test_exact_255_unchanged(self):
|
||||||
|
exact = "a" * 255
|
||||||
|
assert len(sanitize(exact)) == 255
|
||||||
|
|
||||||
|
|
||||||
|
class TestSanitizePreservedChars:
|
||||||
|
"""Safe characters that must be preserved through sanitization."""
|
||||||
|
|
||||||
|
def test_preserves_dashes(self):
|
||||||
|
assert sanitize("some-name") == "some-name"
|
||||||
|
|
||||||
|
def test_preserves_commas(self):
|
||||||
|
assert sanitize("Last, First") == "Last, First"
|
||||||
|
|
||||||
|
def test_preserves_apostrophes(self):
|
||||||
|
assert sanitize("O'Brien") == "O'Brien"
|
||||||
|
|
||||||
|
def test_preserves_parentheses(self):
|
||||||
|
assert sanitize("Book (subtitle)") == "Book (subtitle)"
|
||||||
|
|
||||||
|
def test_preserves_internal_periods(self):
|
||||||
|
assert sanitize("Dr. Jekyll") == "Dr. Jekyll"
|
||||||
|
|
||||||
|
def test_combined_safe_and_unsafe(self):
|
||||||
|
assert sanitize("O'Brien, Pat (Author): A Life*") == "O'Brien, Pat (Author) - A Life"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSanitizeEdgeCases:
|
||||||
|
"""Edge cases: empty strings, unicode, all-illegal input."""
|
||||||
|
|
||||||
|
def test_empty_string_returns_empty(self):
|
||||||
|
assert sanitize("") == ""
|
||||||
|
|
||||||
|
def test_only_illegal_chars_returns_empty(self):
|
||||||
|
assert sanitize("<>/\\|?*") == ""
|
||||||
|
|
||||||
|
def test_only_whitespace_returns_empty(self):
|
||||||
|
assert sanitize(" ") == ""
|
||||||
|
|
||||||
|
def test_unicode_preserved(self):
|
||||||
|
assert sanitize("日本語タイトル") == "日本語タイトル"
|
||||||
|
|
||||||
|
def test_unicode_with_illegal_ascii(self):
|
||||||
|
assert sanitize("日本語<title>") == "日本語title"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Default path resolution
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestDefaultPathSeriesWithNumber:
|
||||||
|
"""Book with series AND series_num: Author/Series/Book N Title."""
|
||||||
|
|
||||||
|
def test_basic_series_with_number(self):
|
||||||
|
book = Book(
|
||||||
|
title="The Final Empire",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Michael Kramer"],
|
||||||
|
isbn="9780765374991",
|
||||||
|
series="Mistborn",
|
||||||
|
series_num=1,
|
||||||
|
)
|
||||||
|
path = resolve_path(book)
|
||||||
|
assert path == "Brandon Sanderson/Mistborn/Book 1 The Final Empire"
|
||||||
|
|
||||||
|
def test_sanitizes_author_name(self):
|
||||||
|
book = Book(
|
||||||
|
title="The Final Empire",
|
||||||
|
authors=["O'Brien, Brandon <Author>"],
|
||||||
|
narrators=["Michael Kramer"],
|
||||||
|
isbn="9780765374991",
|
||||||
|
series="Mistborn: Era 1",
|
||||||
|
series_num=1,
|
||||||
|
)
|
||||||
|
path = resolve_path(book)
|
||||||
|
# Angle brackets stripped from author, colon replaced in series
|
||||||
|
assert path == "O'Brien, Brandon Author/Mistborn - Era 1/Book 1 The Final Empire"
|
||||||
|
|
||||||
|
def test_sanitizes_series_and_title(self):
|
||||||
|
book = Book(
|
||||||
|
title="The Way of Kings (Book 1)",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Kate Reading", "Michael Kramer"],
|
||||||
|
isbn="9780765398270",
|
||||||
|
series="Stormlight Archive*",
|
||||||
|
series_num=1,
|
||||||
|
)
|
||||||
|
path = resolve_path(book)
|
||||||
|
assert path == "Brandon Sanderson/Stormlight Archive/Book 1 The Way of Kings (Book 1)"
|
||||||
|
|
||||||
|
|
||||||
|
class TestDefaultPathSeriesWithoutNumber:
|
||||||
|
"""Book with series but no series_num: Author/Series/Title."""
|
||||||
|
|
||||||
|
def test_basic_series_no_number(self):
|
||||||
|
book = Book(
|
||||||
|
title="Warbreaker",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Alyssa Bresnahan"],
|
||||||
|
isbn="9781433232829",
|
||||||
|
series="Cosmere: Standalones",
|
||||||
|
series_num=None,
|
||||||
|
)
|
||||||
|
path = resolve_path(book)
|
||||||
|
assert path == "Brandon Sanderson/Cosmere - Standalones/Warbreaker"
|
||||||
|
|
||||||
|
|
||||||
|
class TestDefaultPathNoSeries:
|
||||||
|
"""Book without series: Author/Title."""
|
||||||
|
|
||||||
|
def test_standalone_book(self):
|
||||||
|
book = Book(
|
||||||
|
title="Skyward",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Sophie Aldred"],
|
||||||
|
isbn="9781509697815",
|
||||||
|
series="",
|
||||||
|
series_num=None,
|
||||||
|
)
|
||||||
|
path = resolve_path(book)
|
||||||
|
assert path == "Brandon Sanderson/Skyward"
|
||||||
|
|
||||||
|
|
||||||
|
class TestCustomPathPattern:
|
||||||
|
"""Custom path_pattern with token substitution overrides default logic."""
|
||||||
|
|
||||||
|
def test_basic_custom_pattern(self):
|
||||||
|
book = Book(
|
||||||
|
title="The Final Empire",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Michael Kramer"],
|
||||||
|
isbn="9780765374991",
|
||||||
|
series="Mistborn",
|
||||||
|
series_num=1,
|
||||||
|
)
|
||||||
|
pattern = "{FIRST_AUTHOR}/{SERIES_NAME}/{BOOK_TITLE}"
|
||||||
|
path = resolve_path(book, pattern=pattern)
|
||||||
|
assert path == "Brandon Sanderson/Mistborn/The Final Empire"
|
||||||
|
|
||||||
|
def test_custom_pattern_overrides_default(self):
|
||||||
|
"""When pattern is set, default conditional logic is NOT used."""
|
||||||
|
book = Book(
|
||||||
|
title="The Final Empire",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Michael Kramer"],
|
||||||
|
isbn="9780765374991",
|
||||||
|
series="Mistborn",
|
||||||
|
series_num=1,
|
||||||
|
)
|
||||||
|
# Custom pattern without series_num — should NOT get "Book 1" prefix
|
||||||
|
pattern = "{FIRST_AUTHOR}/{BOOK_TITLE}"
|
||||||
|
path = resolve_path(book, pattern=pattern)
|
||||||
|
assert path == "Brandon Sanderson/The Final Empire"
|
||||||
|
|
||||||
|
def test_all_authors_token(self):
|
||||||
|
book = Book(
|
||||||
|
title="Good Omens",
|
||||||
|
authors=["Neil Gaiman", "Terry Pratchett"],
|
||||||
|
narrators=["Martin Jarvis", "Stephen Briggs"],
|
||||||
|
isbn="9780062982360",
|
||||||
|
)
|
||||||
|
pattern = "{ALL_AUTHORS}/{BOOK_TITLE}"
|
||||||
|
path = resolve_path(book, pattern=pattern)
|
||||||
|
assert path == "Neil Gaiman, Terry Pratchett/Good Omens"
|
||||||
|
|
||||||
|
def test_series_num_token(self):
|
||||||
|
book = Book(
|
||||||
|
title="The Final Empire",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Michael Kramer"],
|
||||||
|
isbn="9780765374991",
|
||||||
|
series="Mistborn",
|
||||||
|
series_num=1,
|
||||||
|
)
|
||||||
|
pattern = "{SERIES_NAME} {SERIES_NUM} - {BOOK_TITLE}"
|
||||||
|
path = resolve_path(book, pattern=pattern)
|
||||||
|
assert path == "Mistborn 1 - The Final Empire"
|
||||||
|
|
||||||
|
def test_isbn_token(self):
|
||||||
|
book = Book(
|
||||||
|
title="The Final Empire",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Michael Kramer"],
|
||||||
|
isbn="9780765374991",
|
||||||
|
)
|
||||||
|
pattern = "{ISBN}/{BOOK_TITLE}"
|
||||||
|
path = resolve_path(book, pattern=pattern)
|
||||||
|
assert path == "9780765374991/The Final Empire"
|
||||||
|
|
||||||
|
def test_narrator_tokens(self):
|
||||||
|
book = Book(
|
||||||
|
title="Good Omens",
|
||||||
|
authors=["Neil Gaiman"],
|
||||||
|
narrators=["Martin Jarvis", "Stephen Briggs"],
|
||||||
|
isbn="9780062982360",
|
||||||
|
)
|
||||||
|
pattern = "{FIRST_AUTHOR} - {FIRST_NARRATOR}/{BOOK_TITLE}"
|
||||||
|
path = resolve_path(book, pattern=pattern)
|
||||||
|
assert path == "Neil Gaiman - Martin Jarvis/Good Omens"
|
||||||
|
|
||||||
|
def test_all_narrators_token(self):
|
||||||
|
book = Book(
|
||||||
|
title="Good Omens",
|
||||||
|
authors=["Neil Gaiman"],
|
||||||
|
narrators=["Martin Jarvis", "Stephen Briggs"],
|
||||||
|
isbn="9780062982360",
|
||||||
|
)
|
||||||
|
pattern = "{ALL_NARRATORS}/{BOOK_TITLE}"
|
||||||
|
path = resolve_path(book, pattern=pattern)
|
||||||
|
assert path == "Martin Jarvis, Stephen Briggs/Good Omens"
|
||||||
|
|
||||||
|
def test_publication_date_tokens(self):
|
||||||
|
book = Book(
|
||||||
|
title="The Final Empire",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Michael Kramer"],
|
||||||
|
isbn="9780765374991",
|
||||||
|
publication_year=2006,
|
||||||
|
publication_month=7,
|
||||||
|
publication_day=17,
|
||||||
|
)
|
||||||
|
pattern = "{PUBLICATION_YEAR}/{PUBLICATION_MONTH}/{PUBLICATION_DAY}/{BOOK_TITLE}"
|
||||||
|
path = resolve_path(book, pattern=pattern)
|
||||||
|
assert path == "2006/7/17/The Final Empire"
|
||||||
|
|
||||||
|
def test_missing_optional_tokens_omitted(self):
|
||||||
|
"""Tokens with no value produce empty string (not error)."""
|
||||||
|
book = Book(
|
||||||
|
title="Standalone",
|
||||||
|
authors=["Some Author"],
|
||||||
|
narrators=[],
|
||||||
|
isbn="9780000000001",
|
||||||
|
)
|
||||||
|
pattern = "{SERIES_NAME}/{BOOK_TITLE}"
|
||||||
|
path = resolve_path(book, pattern=pattern)
|
||||||
|
assert path == "/Standalone"
|
||||||
|
|
||||||
|
def test_sanitizes_custom_pattern_output(self):
|
||||||
|
book = Book(
|
||||||
|
title="Book: A Subtitle<Extra>",
|
||||||
|
authors=["O'Brien, Author"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9780000000001",
|
||||||
|
)
|
||||||
|
pattern = "{FIRST_AUTHOR}/{BOOK_TITLE}"
|
||||||
|
path = resolve_path(book, pattern=pattern)
|
||||||
|
assert path == "O'Brien, Author/Book - A SubtitleExtra"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Subdirectory decision
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestNeedsSubdirectory:
|
||||||
|
"""Subdirectory is needed when PDF extras or cover art are present."""
|
||||||
|
|
||||||
|
def test_true_when_pdf_extras_present(self):
|
||||||
|
book = Book(
|
||||||
|
title="Some Book",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9780000000001",
|
||||||
|
pdf_extras=True,
|
||||||
|
cover_url="",
|
||||||
|
)
|
||||||
|
assert needs_subdirectory(book) is True
|
||||||
|
|
||||||
|
def test_false_when_cover_url_only(self):
|
||||||
|
"""cover_url alone does NOT trigger subdirectory — config-gated."""
|
||||||
|
book = Book(
|
||||||
|
title="Some Book",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9780000000001",
|
||||||
|
pdf_extras=False,
|
||||||
|
cover_url="https://example.com/cover.jpg",
|
||||||
|
)
|
||||||
|
assert needs_subdirectory(book) is False
|
||||||
|
|
||||||
|
def test_true_when_both_present(self):
|
||||||
|
book = Book(
|
||||||
|
title="Some Book",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9780000000001",
|
||||||
|
pdf_extras=True,
|
||||||
|
cover_url="https://example.com/cover.jpg",
|
||||||
|
)
|
||||||
|
assert needs_subdirectory(book) is True
|
||||||
|
|
||||||
|
def test_false_when_neither_present(self):
|
||||||
|
book = Book(
|
||||||
|
title="Some Book",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9780000000001",
|
||||||
|
pdf_extras=False,
|
||||||
|
cover_url="",
|
||||||
|
)
|
||||||
|
assert needs_subdirectory(book) is False
|
||||||
|
|
||||||
|
def test_false_with_defaults(self):
|
||||||
|
"""Book created with default fields (no extras, no cover)."""
|
||||||
|
book = Book(
|
||||||
|
title="Some Book",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9780000000001",
|
||||||
|
)
|
||||||
|
assert needs_subdirectory(book) is False
|
||||||
|
|
||||||
|
def test_truthy_int_pdf_extras_is_true(self):
|
||||||
|
"""pdf_extras=1 (int from API) coerces to bool True."""
|
||||||
|
book = Book(
|
||||||
|
title="Int Extras",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9780000000002",
|
||||||
|
pdf_extras=1,
|
||||||
|
)
|
||||||
|
assert needs_subdirectory(book) is True
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Output directory resolution
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestResolveOutputDir:
|
||||||
|
"""Integration tests for output directory structure with/without extras."""
|
||||||
|
|
||||||
|
def test_resolve_output_dir_creates_subdir_for_pdf_extras(self):
|
||||||
|
"""_resolve_output_dir creates subdirectory when book has pdf_extras."""
|
||||||
|
book = Book(
|
||||||
|
title="Subdir Book",
|
||||||
|
authors=["Author Name"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9787777777777",
|
||||||
|
pdf_extras=True,
|
||||||
|
cover_url="",
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
base = Path(tmpdir) / "audiobooks"
|
||||||
|
output_dir = _resolve_output_dir(book, base)
|
||||||
|
|
||||||
|
# Should return a subdirectory path (not the base itself)
|
||||||
|
assert output_dir != base
|
||||||
|
assert output_dir.is_relative_to(base)
|
||||||
|
|
||||||
|
# Creating it should work
|
||||||
|
output_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
assert output_dir.is_dir()
|
||||||
|
|
||||||
|
def test_resolve_output_dir_flat_for_cover_only_without_config(self):
|
||||||
|
"""cover_url without config → flat path (no subdirectory)."""
|
||||||
|
book = Book(
|
||||||
|
title="Cover Only Flat",
|
||||||
|
authors=["Author Name"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9787777777778",
|
||||||
|
pdf_extras=False,
|
||||||
|
cover_url="https://cdn.example.com/cover.jpg",
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
base = Path(tmpdir) / "audiobooks"
|
||||||
|
output_dir = _resolve_output_dir(book, base)
|
||||||
|
|
||||||
|
# cover_url doesn't create subdirectory (covers sit alongside .m4b)
|
||||||
|
assert output_dir == base / "Author Name"
|
||||||
|
|
||||||
|
def test_resolve_output_dir_subdir_for_cover_with_download_covers(self):
|
||||||
|
"""download_covers=True + cover_url → creates subdirectory for accompaniment."""
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="Cover Subdir Book",
|
||||||
|
authors=["Author Name"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9787777777779",
|
||||||
|
pdf_extras=False,
|
||||||
|
cover_url="https://cdn.example.com/cover.jpg",
|
||||||
|
)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=True, download_extras=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
base = Path(tmpdir) / "audiobooks"
|
||||||
|
output_dir = _resolve_output_dir(book, base, config=config)
|
||||||
|
|
||||||
|
# With download_covers + cover_url → subdirectory
|
||||||
|
expected = base / "Author Name" / "Cover Subdir Book"
|
||||||
|
assert output_dir == expected
|
||||||
|
|
||||||
|
def test_resolve_output_dir_subdir_no_title_doubling(self):
|
||||||
|
"""When pdf_extras creates a subdir, title is NOT doubled.
|
||||||
|
|
||||||
|
resolve_path() returns 'Author/Title'. The subdir should be exactly that,
|
||||||
|
not 'Author/Title/Title'.
|
||||||
|
"""
|
||||||
|
book = Book(
|
||||||
|
title="Subdir No Double",
|
||||||
|
authors=["Author Name"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9787777777780",
|
||||||
|
pdf_extras=True,
|
||||||
|
cover_url="",
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
base = Path(tmpdir) / "audiobooks"
|
||||||
|
output_dir = _resolve_output_dir(book, base)
|
||||||
|
|
||||||
|
# Should be base/Author/Subdir No Double — title appears once
|
||||||
|
expected = base / "Author Name" / "Subdir No Double"
|
||||||
|
assert output_dir == expected, f"Expected {expected}, got {output_dir}"
|
||||||
|
|
||||||
|
# Verify no doubled title component
|
||||||
|
parts = output_dir.parts
|
||||||
|
title_parts = [p for p in parts if p == "Subdir No Double"]
|
||||||
|
assert len(title_parts) == 1, f"Title doubled in path: {output_dir}"
|
||||||
|
|
||||||
|
def test_resolve_output_dir_flat_for_no_extras(self):
|
||||||
|
"""_resolve_output_dir returns flat path when no extras (audio is leaf file)."""
|
||||||
|
book = Book(
|
||||||
|
title="Flat Book",
|
||||||
|
authors=["Author Name"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9788888888888",
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
base = Path(tmpdir) / "audiobooks"
|
||||||
|
output_dir = _resolve_output_dir(book, base)
|
||||||
|
|
||||||
|
# Flat layout: no extra book-level subdirectory for the audio file
|
||||||
|
assert output_dir == base / "Author Name"
|
||||||
|
|
||||||
|
def test_resolve_output_dir_string_base(self):
|
||||||
|
"""Accepts string output_base (converted to Path internally)."""
|
||||||
|
book = Book(
|
||||||
|
title="String Base",
|
||||||
|
authors=["Author Name"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9781111111111",
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
output_dir = _resolve_output_dir(book, tmpdir)
|
||||||
|
assert output_dir == Path(tmpdir) / "Author Name"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# OutputPlan resolution
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestResolveOutputPlan:
|
||||||
|
"""OutputPlan frozen dataclass and resolve_output_plan() function."""
|
||||||
|
|
||||||
|
def test_happy_path_all_enabled(self):
|
||||||
|
"""Default pattern with all flags enabled produces all 4 paths."""
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
from librofm_downloader.path import OutputPlan, resolve_output_plan
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="The Final Empire",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Michael Kramer"],
|
||||||
|
isbn="9780765374991",
|
||||||
|
series="Mistborn",
|
||||||
|
series_num=1,
|
||||||
|
cover_url="https://covers.libro.fm/cover.jpg",
|
||||||
|
pdf_extras=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=True, download_extras=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, "/audiobooks", config)
|
||||||
|
|
||||||
|
# OutputPlan is a frozen dataclass with expected fields
|
||||||
|
assert isinstance(plan, OutputPlan)
|
||||||
|
|
||||||
|
# Audio path: sanitized title + .m4b extension
|
||||||
|
assert plan.audio_path.name == "The Final Empire.m4b"
|
||||||
|
assert plan.audio_path.suffix == ".m4b"
|
||||||
|
|
||||||
|
# Partial path is audio_path + ".partial"
|
||||||
|
assert str(plan.partial_path) == f"{str(plan.audio_path)}.partial"
|
||||||
|
|
||||||
|
# Cover path populated (covers enabled + cover_url present)
|
||||||
|
assert plan.cover_path is not None
|
||||||
|
assert plan.cover_path.name == "cover.jpg"
|
||||||
|
|
||||||
|
# PDF path populated (extras enabled + pdf_extras True)
|
||||||
|
assert plan.pdf_path is not None
|
||||||
|
assert plan.pdf_path.name == "map.pdf"
|
||||||
|
|
||||||
|
# All file paths share the same parent directory (resolved output dir)
|
||||||
|
assert plan.audio_path.parent == plan.cover_path.parent
|
||||||
|
assert plan.audio_path.parent == plan.pdf_path.parent
|
||||||
|
|
||||||
|
# Subdirectory layout because pdf_extras=True
|
||||||
|
assert plan.audio_path.is_relative_to(Path("/audiobooks"))
|
||||||
|
|
||||||
|
def test_custom_output_pattern(self):
|
||||||
|
"""Custom pattern overrides default path structure."""
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="The Final Empire",
|
||||||
|
authors=["Brandon Sanderson"],
|
||||||
|
narrators=["Michael Kramer"],
|
||||||
|
isbn="9780765374991",
|
||||||
|
series="Mistborn",
|
||||||
|
series_num=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=False, download_extras=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, "/audiobooks", config)
|
||||||
|
|
||||||
|
# Audio path should exist even without extras
|
||||||
|
assert plan.audio_path.name == "The Final Empire.m4b"
|
||||||
|
# Flat layout (no extras) → under author directory
|
||||||
|
assert "Brandon" in str(plan.audio_path)
|
||||||
|
|
||||||
|
def test_cover_disabled_returns_none(self):
|
||||||
|
"""download_covers=False → cover_path is None regardless of cover_url."""
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="No Cover Book",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Nar"],
|
||||||
|
isbn="9780000000001",
|
||||||
|
cover_url="https://covers.libro.fm/cover.jpg",
|
||||||
|
)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=False, download_extras=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, "/audiobooks", config)
|
||||||
|
assert plan.cover_path is None
|
||||||
|
|
||||||
|
def test_pdf_disabled_returns_none(self):
|
||||||
|
"""download_extras=False → pdf_path is None regardless of pdf_extras."""
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="No PDF Book",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Nar"],
|
||||||
|
isbn="9780000000002",
|
||||||
|
pdf_extras=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=False, download_extras=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, "/audiobooks", config)
|
||||||
|
assert plan.pdf_path is None
|
||||||
|
|
||||||
|
def test_no_cover_url_returns_none(self):
|
||||||
|
"""Empty cover_url → cover_path is None even with download_covers=True."""
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="No URL Book",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Nar"],
|
||||||
|
isbn="9780000000003",
|
||||||
|
cover_url="", # empty string = no cover available
|
||||||
|
)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=True, download_extras=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, "/audiobooks", config)
|
||||||
|
assert plan.cover_path is None
|
||||||
|
|
||||||
|
def test_no_pdf_extras_returns_none(self):
|
||||||
|
"""pdf_extras=False → pdf_path is None even with download_extras=True."""
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="No Extras Book",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Nar"],
|
||||||
|
isbn="9780000000004",
|
||||||
|
pdf_extras=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=False, download_extras=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, "/audiobooks", config)
|
||||||
|
assert plan.pdf_path is None
|
||||||
|
|
||||||
|
def test_string_output_base_accepted(self):
|
||||||
|
"""String output_base works (converted to Path internally)."""
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="String Base Book",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Nar"],
|
||||||
|
isbn="9780000000005",
|
||||||
|
)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=False, download_extras=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Should not raise; should return a plan with absolute paths
|
||||||
|
plan = resolve_output_plan(book, "/some/string/base", config)
|
||||||
|
assert isinstance(plan.audio_path, Path)
|
||||||
|
assert plan.audio_path.is_absolute()
|
||||||
|
|
||||||
|
def test_subdirectory_layout_when_pdf_extras_true(self):
|
||||||
|
"""pdf_extras=True creates subdirectory layout (Author/Title/)."""
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="Subdir Layout",
|
||||||
|
authors=["Author Name"],
|
||||||
|
narrators=["Nar"],
|
||||||
|
isbn="9780000000006",
|
||||||
|
pdf_extras=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=True, download_extras=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, "/audiobooks", config)
|
||||||
|
|
||||||
|
# Should be /audiobooks/Author Name/Subdir Layout/The Final Empire.m4b
|
||||||
|
expected_parent = Path("/audiobooks") / "Author Name" / "Subdir Layout"
|
||||||
|
assert plan.audio_path.parent == expected_parent
|
||||||
|
|
||||||
|
def test_flat_layout_when_no_extras(self):
|
||||||
|
"""No extras + no cover → flat layout (audio file under author dir)."""
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
|
||||||
|
book = Book(
|
||||||
|
title="Flat Layout",
|
||||||
|
authors=["Author Name"],
|
||||||
|
narrators=["Nar"],
|
||||||
|
isbn="9780000000007",
|
||||||
|
)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=False, download_extras=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
plan = resolve_output_plan(book, "/audiobooks", config)
|
||||||
|
|
||||||
|
# Flat: audio is leaf under author dir
|
||||||
|
expected_parent = Path("/audiobooks") / "Author Name"
|
||||||
|
assert plan.audio_path.parent == expected_parent
|
||||||
|
|
||||||
|
def test_output_plan_is_frozen(self):
|
||||||
|
"""OutputPlan is immutable (frozen dataclass)."""
|
||||||
|
from dataclasses import FrozenInstanceError
|
||||||
|
from librofm_downloader.config import Config
|
||||||
|
|
||||||
|
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000008")
|
||||||
|
config = Config(
|
||||||
|
username="u", password="p", format="m4b_mp3_fallback",
|
||||||
|
output_dir="/tmp", download_covers=False, download_extras=False,
|
||||||
|
)
|
||||||
|
plan = resolve_output_plan(book, "/base", config)
|
||||||
|
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
plan.audio_path = Path("/other") # type: ignore[misc]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class TestOutputPlanFormatStrategy:
|
||||||
|
"""OutputPlan carries format_strategy from resolve_output_plan()."""
|
||||||
|
|
||||||
|
def test_default_format_strategy(self):
|
||||||
|
"""When no format_strategy passed, defaults to m4b_mp3_fallback."""
|
||||||
|
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000010")
|
||||||
|
plan = resolve_output_plan(book, "/base")
|
||||||
|
|
||||||
|
assert hasattr(plan, "format_strategy")
|
||||||
|
assert plan.format_strategy == "m4b_mp3_fallback"
|
||||||
|
|
||||||
|
def test_explicit_format_strategy(self):
|
||||||
|
"""Passing format_strategy='mp3_only' is reflected on the plan."""
|
||||||
|
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000011")
|
||||||
|
plan = resolve_output_plan(book, "/base", format_strategy="mp3_only")
|
||||||
|
|
||||||
|
assert plan.format_strategy == "mp3_only"
|
||||||
|
|
||||||
|
def test_m4b_only_format_strategy(self):
|
||||||
|
"""Passing format_strategy='m4b_only' is reflected on the plan."""
|
||||||
|
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000012")
|
||||||
|
plan = resolve_output_plan(book, "/base", format_strategy="m4b_only")
|
||||||
|
|
||||||
|
assert plan.format_strategy == "m4b_only"
|
||||||
|
|
||||||
|
def test_format_strategy_on_frozen_plan(self):
|
||||||
|
"""format_strategy field is part of the frozen OutputPlan."""
|
||||||
|
from dataclasses import FrozenInstanceError
|
||||||
|
|
||||||
|
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000013")
|
||||||
|
plan = resolve_output_plan(book, "/base")
|
||||||
|
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
plan.format_strategy = "mp3_only" # type: ignore[misc]
|
||||||
+221
-103
@@ -6,7 +6,12 @@ import tempfile
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from librofm_downloader.downloader import Book
|
from librofm_downloader.book import Book
|
||||||
|
from librofm_downloader.downloader import (
|
||||||
|
download_m4b,
|
||||||
|
download_zip_part,
|
||||||
|
download_book,
|
||||||
|
)
|
||||||
from librofm_downloader.progress import DownloadReporter, PlainTextReporter, ProgressReporter
|
from librofm_downloader.progress import DownloadReporter, PlainTextReporter, ProgressReporter
|
||||||
|
|
||||||
|
|
||||||
@@ -151,10 +156,10 @@ class TestFailureIsolationCLI:
|
|||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
with (
|
with (
|
||||||
patch("librofm_downloader.cli.load_config") as mock_config,
|
patch("librofm_downloader.sync_run.load_config") as mock_config,
|
||||||
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
|
patch("librofm_downloader.sync_run.LibroFmSession") as mock_client_cls,
|
||||||
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
|
patch("librofm_downloader.sync_run.DownloadHistory") as mock_history_cls,
|
||||||
patch("librofm_downloader.cli.download_book") as mock_download,
|
patch("librofm_downloader.sync_run.download_book") as mock_download,
|
||||||
):
|
):
|
||||||
mock_config.return_value.username = "alice"
|
mock_config.return_value.username = "alice"
|
||||||
mock_config.return_value.password = "secret"
|
mock_config.return_value.password = "secret"
|
||||||
@@ -173,18 +178,18 @@ class TestFailureIsolationCLI:
|
|||||||
|
|
||||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||||
|
|
||||||
|
from librofm_downloader.downloader import DownloadResult
|
||||||
|
|
||||||
# Book A succeeds, Book B fails, Book C succeeds
|
# Book A succeeds, Book B fails, Book C succeeds
|
||||||
mock_download.side_effect = [
|
mock_download.side_effect = [
|
||||||
Path("/audiobooks/A1/Book A.m4b"), # success
|
DownloadResult(status="downloaded", path=Path("/audiobooks/A1/Book A.m4b"), format="m4b"), # success
|
||||||
Exception("Network timeout"), # failure
|
Exception("Network timeout"), # failure
|
||||||
Path("/audiobooks/A3/Book C.m4b"), # success
|
DownloadResult(status="downloaded", path=Path("/audiobooks/A3/Book C.m4b"), format="m4b"), # success
|
||||||
]
|
]
|
||||||
|
|
||||||
exit_code = run = __import__("librofm_downloader.cli").cli.run
|
from librofm_downloader.sync_run import sync_run
|
||||||
# Need to import run properly
|
|
||||||
from librofm_downloader.cli import run as cli_run
|
|
||||||
|
|
||||||
exit_code = cli_run(
|
result = sync_run(
|
||||||
config_path="/fake/config.yaml",
|
config_path="/fake/config.yaml",
|
||||||
secrets_path="/fake/secrets.yaml",
|
secrets_path="/fake/secrets.yaml",
|
||||||
history_path="/fake/history.json",
|
history_path="/fake/history.json",
|
||||||
@@ -192,8 +197,8 @@ class TestFailureIsolationCLI:
|
|||||||
|
|
||||||
# All 3 books were attempted
|
# All 3 books were attempted
|
||||||
assert mock_download.call_count == 3
|
assert mock_download.call_count == 3
|
||||||
# Exit code is 0 (failures are non-fatal)
|
# Failures are non-fatal → no fatal_error
|
||||||
assert exit_code == 0
|
assert result.fatal_error is None
|
||||||
captured = capsys.readouterr()
|
captured = capsys.readouterr()
|
||||||
# Reporter output: Completed for successes, Failed for failure, Summary with counts
|
# Reporter output: Completed for successes, Failed for failure, Summary with counts
|
||||||
out = captured.out
|
out = captured.out
|
||||||
@@ -213,12 +218,12 @@ class TestFatalVsBookLevel:
|
|||||||
def test_auth_failure_exits_one_before_downloads(self, capsys):
|
def test_auth_failure_exits_one_before_downloads(self, capsys):
|
||||||
"""Auth failure → exit 1, download_book never called."""
|
"""Auth failure → exit 1, download_book never called."""
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
from librofm_downloader.client import AuthError
|
from librofm_downloader.session import AuthError
|
||||||
|
|
||||||
with (
|
with (
|
||||||
patch("librofm_downloader.cli.load_config") as mock_config,
|
patch("librofm_downloader.sync_run.load_config") as mock_config,
|
||||||
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
|
patch("librofm_downloader.sync_run.LibroFmSession") as mock_client_cls,
|
||||||
patch("librofm_downloader.cli.download_book") as mock_download,
|
patch("librofm_downloader.sync_run.download_book") as mock_download,
|
||||||
):
|
):
|
||||||
mock_config.return_value.username = "alice"
|
mock_config.return_value.username = "alice"
|
||||||
mock_config.return_value.password = "wrong"
|
mock_config.return_value.password = "wrong"
|
||||||
@@ -228,15 +233,15 @@ class TestFatalVsBookLevel:
|
|||||||
mock_instance = mock_client_cls.return_value
|
mock_instance = mock_client_cls.return_value
|
||||||
mock_instance.authenticate.side_effect = AuthError("Auth failed (401)")
|
mock_instance.authenticate.side_effect = AuthError("Auth failed (401)")
|
||||||
|
|
||||||
from librofm_downloader.cli import run as cli_run
|
from librofm_downloader.sync_run import sync_run
|
||||||
|
|
||||||
exit_code = cli_run(
|
result = sync_run(
|
||||||
config_path="/fake/config.yaml",
|
config_path="/fake/config.yaml",
|
||||||
secrets_path="/fake/secrets.yaml",
|
secrets_path="/fake/secrets.yaml",
|
||||||
history_path="/fake/history.json",
|
history_path="/fake/history.json",
|
||||||
)
|
)
|
||||||
|
|
||||||
assert exit_code == 1
|
assert result.fatal_error is not None
|
||||||
# No downloads were attempted
|
# No downloads were attempted
|
||||||
assert mock_download.call_count == 0
|
assert mock_download.call_count == 0
|
||||||
captured = capsys.readouterr()
|
captured = capsys.readouterr()
|
||||||
@@ -653,12 +658,15 @@ class TestProgressCallbackWiring:
|
|||||||
"""download_book() threads the progress callback through to low-level downloads."""
|
"""download_book() threads the progress callback through to low-level downloads."""
|
||||||
|
|
||||||
def test_download_book_forwards_progress_to_m4b(self):
|
def test_download_book_forwards_progress_to_m4b(self):
|
||||||
"""progress callable passed to download_book reaches download_m4b."""
|
"""progress callback from reporter reaches download_m4b chunk loop."""
|
||||||
import httpx
|
import httpx
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from librofm_downloader.downloader import Book, download_book
|
from unittest.mock import MagicMock
|
||||||
from librofm_downloader.client import LibroFmClient
|
from librofm_downloader.book import Book
|
||||||
from librofm_downloader.history import DownloadHistory
|
from librofm_downloader.downloader import download_book
|
||||||
|
from librofm_downloader.session import LibroFmSession
|
||||||
|
from librofm_downloader.path import resolve_output_plan
|
||||||
|
from librofm_downloader.progress import DownloadReporter
|
||||||
|
|
||||||
m4b_payload = b"callback-test-data" * 10 # 160 bytes
|
m4b_payload = b"callback-test-data" * 10 # 160 bytes
|
||||||
|
|
||||||
@@ -675,29 +683,31 @@ class TestProgressCallbackWiring:
|
|||||||
return httpx.Response(404)
|
return httpx.Response(404)
|
||||||
|
|
||||||
transport = httpx.MockTransport(handler)
|
transport = httpx.MockTransport(handler)
|
||||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||||
client.authenticate(transport=transport)
|
client.authenticate()
|
||||||
|
|
||||||
book = Book(title="CB Test", authors=["A"], narrators=["N"], isbn="9781111111111")
|
book = Book(title="CB Test", authors=["A"], narrators=["N"], isbn="9781111111111")
|
||||||
progress_calls: list[int] = []
|
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as tmpdir:
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
base_dir = Path(tmpdir) / "audiobooks"
|
base_dir = Path(tmpdir) / "audiobooks"
|
||||||
history = DownloadHistory(Path(tmpdir) / "history.json")
|
|
||||||
|
plan = resolve_output_plan(book, base_dir)
|
||||||
|
reporter = DownloadReporter()
|
||||||
|
# Spy on the reporter's update method (used as progress callback)
|
||||||
|
reporter.update = MagicMock(wraps=reporter.update)
|
||||||
|
|
||||||
download_book(
|
download_book(
|
||||||
book=book,
|
book=book,
|
||||||
client=client,
|
session=client,
|
||||||
output_base=base_dir,
|
plan=plan,
|
||||||
history=history,
|
reporter=reporter,
|
||||||
transport=transport,
|
|
||||||
progress=lambda n, **kw: progress_calls.append(n),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Progress callback was invoked during the M4B download
|
# Progress callback was invoked during the M4B download
|
||||||
assert len(progress_calls) >= 1
|
assert reporter.update.call_count >= 1
|
||||||
# Final value reflects the full download size
|
# Final call reflects the full download size
|
||||||
assert progress_calls[-1] == len(m4b_payload)
|
last_call_args = reporter.update.call_args_list[-1]
|
||||||
|
assert last_call_args[0][0] == len(m4b_payload)
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -717,12 +727,13 @@ class TestProgressTotalFromContentLength:
|
|||||||
reporter = DownloadReporter(stdout=mock_tty)
|
reporter = DownloadReporter(stdout=mock_tty)
|
||||||
|
|
||||||
book = Book(title="Big", authors=["A"], narrators=["N"], isbn="9780000000010")
|
book = Book(title="Big", authors=["A"], narrators=["N"], isbn="9780000000010")
|
||||||
task_id = reporter.start_download(book, total_bytes=0) # unknown at start
|
reporter.start_download(book, total_bytes=0) # unknown at start
|
||||||
|
|
||||||
# Simulate what download_m4b does after reading Content-Length header
|
# Simulate what download_m4b does after reading Content-Length header
|
||||||
reporter.update(0, total=100_000_000)
|
reporter.update(0, total=100_000_000)
|
||||||
|
|
||||||
# Task now has a total — percentage can be computed
|
# Task now has a total — percentage can be computed
|
||||||
|
task_id = reporter._book_ids[id(book)]
|
||||||
task = reporter._progress.tasks[task_id]
|
task = reporter._progress.tasks[task_id]
|
||||||
assert task.total == 100_000_000
|
assert task.total == 100_000_000
|
||||||
|
|
||||||
@@ -736,13 +747,14 @@ class TestProgressTotalFromContentLength:
|
|||||||
reporter = DownloadReporter(stdout=mock_tty)
|
reporter = DownloadReporter(stdout=mock_tty)
|
||||||
|
|
||||||
book = Book(title="Pct", authors=["A"], narrators=["N"], isbn="9780000000011")
|
book = Book(title="Pct", authors=["A"], narrators=["N"], isbn="9780000000011")
|
||||||
task_id = reporter.start_download(book, total_bytes=0)
|
reporter.start_download(book, total_bytes=0)
|
||||||
|
|
||||||
# First callback sets total (from Content-Length)
|
# First callback sets total (from Content-Length)
|
||||||
reporter.update(0, total=50_000_000)
|
reporter.update(0, total=50_000_000)
|
||||||
|
|
||||||
# Now at 50% when half done
|
# Now at 50% when half done
|
||||||
reporter.update(25_000_000)
|
reporter.update(25_000_000)
|
||||||
|
task_id = reporter._book_ids[id(book)]
|
||||||
task = reporter._progress.tasks[task_id]
|
task = reporter._progress.tasks[task_id]
|
||||||
assert task.percentage == 50.0
|
assert task.percentage == 50.0
|
||||||
|
|
||||||
@@ -871,10 +883,11 @@ class TestMultiBarProgress:
|
|||||||
reporter = ProgressReporter(stdout=mock_tty)
|
reporter = ProgressReporter(stdout=mock_tty)
|
||||||
|
|
||||||
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
||||||
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
callback_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
|
|
||||||
# start_download should return a task_id (int)
|
# start_download should return a callable (bound to this book's task)
|
||||||
assert isinstance(task_id_a, int)
|
assert callable(callback_a)
|
||||||
|
assert not isinstance(callback_a, int)
|
||||||
# Progress should have exactly 1 task
|
# Progress should have exactly 1 task
|
||||||
assert len(reporter._progress.tasks) == 1
|
assert len(reporter._progress.tasks) == 1
|
||||||
|
|
||||||
@@ -890,11 +903,11 @@ class TestMultiBarProgress:
|
|||||||
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
||||||
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
||||||
|
|
||||||
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
callback_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
|
callback_b = reporter.start_download(book_b, total_bytes=50_000_000)
|
||||||
|
|
||||||
# Two distinct task IDs
|
# Two distinct callables
|
||||||
assert task_id_a != task_id_b
|
assert callback_a is not callback_b
|
||||||
# Progress should have exactly 2 active tasks
|
# Progress should have exactly 2 active tasks
|
||||||
assert len(reporter._progress.tasks) == 2
|
assert len(reporter._progress.tasks) == 2
|
||||||
|
|
||||||
@@ -910,12 +923,14 @@ class TestMultiBarProgress:
|
|||||||
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
||||||
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
||||||
|
|
||||||
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
callback_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
|
callback_b = reporter.start_download(book_b, total_bytes=50_000_000)
|
||||||
|
|
||||||
# Update only book A's bar to 50%
|
# Update only book A's bar to 50% using its bound callable
|
||||||
reporter.update(50_000_000, task_id=task_id_a)
|
callback_a(50_000_000)
|
||||||
|
|
||||||
|
task_id_a = reporter._book_ids[id(book_a)]
|
||||||
|
task_id_b = reporter._book_ids[id(book_b)]
|
||||||
task_a = reporter._progress.tasks[task_id_a]
|
task_a = reporter._progress.tasks[task_id_a]
|
||||||
task_b = reporter._progress.tasks[task_id_b]
|
task_b = reporter._progress.tasks[task_id_b]
|
||||||
|
|
||||||
@@ -934,17 +949,17 @@ class TestMultiBarProgress:
|
|||||||
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
||||||
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
||||||
|
|
||||||
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
|
reporter.start_download(book_b, total_bytes=50_000_000)
|
||||||
|
|
||||||
assert len(reporter._progress.tasks) == 2
|
assert len(reporter._progress.tasks) == 2
|
||||||
|
|
||||||
# Complete only book A
|
# Complete only book A
|
||||||
reporter.complete(book_a)
|
reporter.complete(book_a)
|
||||||
|
|
||||||
# Book A's task is gone, Book B's remains
|
# Book A's task is gone from internal mapping, Book B's remains
|
||||||
assert task_id_a not in reporter._tasks
|
assert id(book_a) not in reporter._book_ids
|
||||||
assert task_id_b in reporter._tasks
|
assert id(book_b) in reporter._book_ids
|
||||||
assert len(reporter._progress.tasks) == 2 # Rich keeps it (completed), but our mapping is clean
|
assert len(reporter._progress.tasks) == 2 # Rich keeps it (completed), but our mapping is clean
|
||||||
|
|
||||||
def test_fail_removes_only_its_bar(self):
|
def test_fail_removes_only_its_bar(self):
|
||||||
@@ -959,15 +974,15 @@ class TestMultiBarProgress:
|
|||||||
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
||||||
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
||||||
|
|
||||||
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
|
reporter.start_download(book_b, total_bytes=50_000_000)
|
||||||
|
|
||||||
# Fail only book B
|
# Fail only book B
|
||||||
reporter.fail(book_b, reason="connection reset")
|
reporter.fail(book_b, reason="connection reset")
|
||||||
|
|
||||||
# Book B's task is gone, Book A's remains
|
# Book B's task is gone from internal mapping, Book A's remains
|
||||||
assert task_id_b not in reporter._tasks
|
assert id(book_b) not in reporter._book_ids
|
||||||
assert task_id_a in reporter._tasks
|
assert id(book_a) in reporter._book_ids
|
||||||
|
|
||||||
def test_summary_stops_progress_after_all_tasks_done(self):
|
def test_summary_stops_progress_after_all_tasks_done(self):
|
||||||
"""summary() stops progress after all books completed/failed."""
|
"""summary() stops progress after all books completed/failed."""
|
||||||
@@ -1006,12 +1021,14 @@ class TestMultiBarProgress:
|
|||||||
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
||||||
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
||||||
|
|
||||||
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
|
reporter.start_download(book_b, total_bytes=50_000_000)
|
||||||
|
|
||||||
# Update WITHOUT task_id — should fall back to most recent (book_b)
|
# Update WITHOUT task_id — should fall back to most recent (book_b)
|
||||||
reporter.update(25_000_000)
|
reporter.update(25_000_000)
|
||||||
|
|
||||||
|
task_id_b = reporter._book_ids[id(book_b)]
|
||||||
|
task_id_a = reporter._book_ids[id(book_a)]
|
||||||
task_b = reporter._progress.tasks[task_id_b]
|
task_b = reporter._progress.tasks[task_id_b]
|
||||||
task_a = reporter._progress.tasks[task_id_a]
|
task_a = reporter._progress.tasks[task_id_a]
|
||||||
|
|
||||||
@@ -1089,9 +1106,9 @@ class TestParallelProgressCallbackWiring:
|
|||||||
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
||||||
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
|
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
|
||||||
|
|
||||||
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
task_id_b = reporter.start_download(book_b, total_bytes=100_000_000)
|
reporter.start_download(book_b, total_bytes=100_000_000)
|
||||||
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
|
reporter.start_download(book_c, total_bytes=100_000_000)
|
||||||
|
|
||||||
# Simulate what happens in production: each download thread calls
|
# Simulate what happens in production: each download thread calls
|
||||||
# reporter.update(completed) WITHOUT passing task_id — because
|
# reporter.update(completed) WITHOUT passing task_id — because
|
||||||
@@ -1105,6 +1122,9 @@ class TestParallelProgressCallbackWiring:
|
|||||||
|
|
||||||
# BUG: all updates went to the most recently started bar (book_c)
|
# BUG: all updates went to the most recently started bar (book_c)
|
||||||
# because task_id was None every time, triggering the fallback.
|
# because task_id was None every time, triggering the fallback.
|
||||||
|
task_id_a = reporter._book_ids[id(book_a)]
|
||||||
|
task_id_b = reporter._book_ids[id(book_b)]
|
||||||
|
task_id_c = reporter._book_ids[id(book_c)]
|
||||||
task_a = reporter._progress.tasks[task_id_a]
|
task_a = reporter._progress.tasks[task_id_a]
|
||||||
task_b = reporter._progress.tasks[task_id_b]
|
task_b = reporter._progress.tasks[task_id_b]
|
||||||
task_c = reporter._progress.tasks[task_id_c]
|
task_c = reporter._progress.tasks[task_id_c]
|
||||||
@@ -1114,17 +1134,8 @@ class TestParallelProgressCallbackWiring:
|
|||||||
assert task_a.completed == 0 # book A never got an update ← THE BUG
|
assert task_a.completed == 0 # book A never got an update ← THE BUG
|
||||||
assert task_b.completed == 0 # book B never got an update ← THE BUG
|
assert task_b.completed == 0 # book B never got an update ← THE BUG
|
||||||
|
|
||||||
def make_progress_callback(self, reporter, task_id):
|
|
||||||
"""Factory: returns a progress closure bound to a specific task_id.
|
|
||||||
|
|
||||||
This is what cli.py SHOULD do instead of passing ``reporter.update`` directly.
|
|
||||||
"""
|
|
||||||
def _progress(completed, *, total=None):
|
|
||||||
reporter.update(completed, total=total, task_id=task_id)
|
|
||||||
return _progress
|
|
||||||
|
|
||||||
def test_bound_callback_updates_correct_bar(self):
|
def test_bound_callback_updates_correct_bar(self):
|
||||||
"""When each thread gets a task_id-bound callback, bars update independently."""
|
"""When each thread gets a bound callback from start_download(), bars update independently."""
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
mock_tty = MagicMock()
|
mock_tty = MagicMock()
|
||||||
@@ -1136,20 +1147,19 @@ class TestParallelProgressCallbackWiring:
|
|||||||
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
||||||
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
|
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
|
||||||
|
|
||||||
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
# Each download thread gets its OWN bound callable from start_download()
|
||||||
task_id_b = reporter.start_download(book_b, total_bytes=100_000_1000)
|
progress_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
|
progress_b = reporter.start_download(book_b, total_bytes=100_000_1000)
|
||||||
|
progress_c = reporter.start_download(book_c, total_bytes=100_000_000)
|
||||||
# Each download thread gets its OWN callback, pre-bound to its task_id
|
|
||||||
progress_a = self.make_progress_callback(reporter, task_id_a)
|
|
||||||
progress_b = self.make_progress_callback(reporter, task_id_b)
|
|
||||||
progress_c = self.make_progress_callback(reporter, task_id_c)
|
|
||||||
|
|
||||||
# Each thread reports its own progress
|
# Each thread reports its own progress
|
||||||
progress_a(50_000_000)
|
progress_a(50_000_000)
|
||||||
progress_b(30_000_000)
|
progress_b(30_000_000)
|
||||||
progress_c(80_000_000)
|
progress_c(80_000_000)
|
||||||
|
|
||||||
|
task_id_a = reporter._book_ids[id(book_a)]
|
||||||
|
task_id_b = reporter._book_ids[id(book_b)]
|
||||||
|
task_id_c = reporter._book_ids[id(book_c)]
|
||||||
task_a = reporter._progress.tasks[task_id_a]
|
task_a = reporter._progress.tasks[task_id_a]
|
||||||
task_b = reporter._progress.tasks[task_id_b]
|
task_b = reporter._progress.tasks[task_id_b]
|
||||||
task_c = reporter._progress.tasks[task_id_c]
|
task_c = reporter._progress.tasks[task_id_c]
|
||||||
@@ -1180,9 +1190,9 @@ class TestParallelProgressCallbackWiring:
|
|||||||
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
||||||
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
|
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
|
||||||
|
|
||||||
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
task_id_b = reporter.start_download(book_b, total_bytes=100_000_000)
|
reporter.start_download(book_b, total_bytes=100_000_000)
|
||||||
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
|
reporter.start_download(book_c, total_bytes=100_000_000)
|
||||||
|
|
||||||
# Simulate what happens in production: each download thread calls
|
# Simulate what happens in production: each download thread calls
|
||||||
# reporter.update(completed) WITHOUT passing task_id — because
|
# reporter.update(completed) WITHOUT passing task_id — because
|
||||||
@@ -1196,6 +1206,9 @@ class TestParallelProgressCallbackWiring:
|
|||||||
|
|
||||||
# BUG: all updates went to the most recently started bar (book_c)
|
# BUG: all updates went to the most recently started bar (book_c)
|
||||||
# because task_id was None every time, triggering the fallback.
|
# because task_id was None every time, triggering the fallback.
|
||||||
|
task_id_a = reporter._book_ids[id(book_a)]
|
||||||
|
task_id_b = reporter._book_ids[id(book_b)]
|
||||||
|
task_id_c = reporter._book_ids[id(book_c)]
|
||||||
task_a = reporter._progress.tasks[task_id_a]
|
task_a = reporter._progress.tasks[task_id_a]
|
||||||
task_b = reporter._progress.tasks[task_id_b]
|
task_b = reporter._progress.tasks[task_id_b]
|
||||||
task_c = reporter._progress.tasks[task_id_c]
|
task_c = reporter._progress.tasks[task_id_c]
|
||||||
@@ -1205,17 +1218,8 @@ class TestParallelProgressCallbackWiring:
|
|||||||
assert task_a.completed == 0 # book A never got an update ← THE BUG
|
assert task_a.completed == 0 # book A never got an update ← THE BUG
|
||||||
assert task_b.completed == 0 # book B never got an update ← THE BUG
|
assert task_b.completed == 0 # book B never got an update ← THE BUG
|
||||||
|
|
||||||
def make_progress_callback(self, reporter, task_id):
|
|
||||||
"""Factory: returns a progress closure bound to a specific task_id.
|
|
||||||
|
|
||||||
This is what cli.py SHOULD do instead of passing ``reporter.update`` directly.
|
|
||||||
"""
|
|
||||||
def _progress(completed, *, total=None):
|
|
||||||
reporter.update(completed, total=total, task_id=task_id)
|
|
||||||
return _progress
|
|
||||||
|
|
||||||
def test_bound_callback_updates_correct_bar(self):
|
def test_bound_callback_updates_correct_bar(self):
|
||||||
"""When each thread gets a task_id-bound callback, bars update independently."""
|
"""When each thread gets a bound callback from start_download(), bars update independently."""
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
mock_tty = MagicMock()
|
mock_tty = MagicMock()
|
||||||
@@ -1227,20 +1231,19 @@ class TestParallelProgressCallbackWiring:
|
|||||||
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
||||||
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
|
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
|
||||||
|
|
||||||
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
# Each download thread gets its OWN bound callable from start_download()
|
||||||
task_id_b = reporter.start_download(book_b, total_bytes=100_000_000)
|
progress_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
|
progress_b = reporter.start_download(book_b, total_bytes=100_000_1000)
|
||||||
|
progress_c = reporter.start_download(book_c, total_bytes=100_000_000)
|
||||||
# Each download thread gets its OWN callback, pre-bound to its task_id
|
|
||||||
progress_a = self.make_progress_callback(reporter, task_id_a)
|
|
||||||
progress_b = self.make_progress_callback(reporter, task_id_b)
|
|
||||||
progress_c = self.make_progress_callback(reporter, task_id_c)
|
|
||||||
|
|
||||||
# Each thread reports its own progress
|
# Each thread reports its own progress
|
||||||
progress_a(50_000_000)
|
progress_a(50_000_000)
|
||||||
progress_b(30_000_000)
|
progress_b(30_000_000)
|
||||||
progress_c(80_000_000)
|
progress_c(80_000_000)
|
||||||
|
|
||||||
|
task_id_a = reporter._book_ids[id(book_a)]
|
||||||
|
task_id_b = reporter._book_ids[id(book_b)]
|
||||||
|
task_id_c = reporter._book_ids[id(book_c)]
|
||||||
task_a = reporter._progress.tasks[task_id_a]
|
task_a = reporter._progress.tasks[task_id_a]
|
||||||
task_b = reporter._progress.tasks[task_id_b]
|
task_b = reporter._progress.tasks[task_id_b]
|
||||||
task_c = reporter._progress.tasks[task_id_c]
|
task_c = reporter._progress.tasks[task_id_c]
|
||||||
@@ -1284,3 +1287,118 @@ class TestParallelProgressCallbackWiring:
|
|||||||
assert "Completed: Author A - Alpha" in output
|
assert "Completed: Author A - Alpha" in output
|
||||||
assert "Completed: Author C - Gamma" in output
|
assert "Completed: Author C - Gamma" in output
|
||||||
assert "Failed: Author B - Beta [9782222222222] (network error)" in output
|
assert "Failed: Author B - Beta [9782222222222] (network error)" in output
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Issue #30: Bound Callable Per Book
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestBoundCallableFromStartDownload:
|
||||||
|
"""start_download() returns a bound callable that targets the correct bar.
|
||||||
|
|
||||||
|
Issue #30: task_id never leaves progress.py. The callable returned by
|
||||||
|
start_download() already carries the task identity internally.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_start_download_returns_callable_for_tty_reporter(self):
|
||||||
|
"""ProgressReporter.start_download() returns a callable, not an int."""
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
mock_tty = MagicMock()
|
||||||
|
mock_tty.isatty.return_value = True
|
||||||
|
|
||||||
|
reporter = ProgressReporter(stdout=mock_tty)
|
||||||
|
|
||||||
|
book = Book(title="Test Book", authors=["Author"], narrators=["N"], isbn="9780000000000")
|
||||||
|
callback = reporter.start_download(book, total_bytes=100_000_000)
|
||||||
|
|
||||||
|
# Must return a callable (bound to this book's task)
|
||||||
|
assert callable(callback)
|
||||||
|
# It must NOT be a raw int (the old API)
|
||||||
|
assert not isinstance(callback, int)
|
||||||
|
|
||||||
|
def test_bound_callable_updates_correct_bar(self):
|
||||||
|
"""Calling each book's bound callable updates only that book's bar."""
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
mock_tty = MagicMock()
|
||||||
|
mock_tty.isatty.return_value = True
|
||||||
|
|
||||||
|
reporter = ProgressReporter(stdout=mock_tty)
|
||||||
|
|
||||||
|
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
|
||||||
|
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
|
||||||
|
|
||||||
|
callback_a = reporter.start_download(book_a, total_bytes=100_000_000)
|
||||||
|
callback_b = reporter.start_download(book_b, total_bytes=50_000_000)
|
||||||
|
|
||||||
|
# Update only book A's progress
|
||||||
|
callback_a(25_000_000) # 25%
|
||||||
|
|
||||||
|
# Book A's task should show 25%, Book B should still be at 0%
|
||||||
|
task_a = reporter._book_ids[id(book_a)]
|
||||||
|
task_b = reporter._book_ids[id(book_b)]
|
||||||
|
|
||||||
|
# Rich stores completed per-task; check via internal state
|
||||||
|
tasks = reporter._progress.tasks
|
||||||
|
assert tasks[task_a].completed == 25_000_000
|
||||||
|
assert tasks[task_b].completed == 0
|
||||||
|
|
||||||
|
# Now update only book B
|
||||||
|
callback_b(25_000_000) # 50% of its total
|
||||||
|
assert tasks[task_a].completed == 25_000_000 # unchanged
|
||||||
|
assert tasks[task_b].completed == 25_000_000
|
||||||
|
|
||||||
|
def test_plain_text_reporter_returns_none(self):
|
||||||
|
"""PlainTextReporter.start_download() returns None (no progress bar)."""
|
||||||
|
reporter = PlainTextReporter()
|
||||||
|
|
||||||
|
book = Book(title="Test Book", authors=["Author"], narrators=["N"], isbn="9780000000000")
|
||||||
|
result = reporter.start_download(book)
|
||||||
|
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
def test_bound_callable_forwards_total_kwarg(self):
|
||||||
|
"""Bound callable accepts and forwards the total kwarg to update()."""
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
mock_tty = MagicMock()
|
||||||
|
mock_tty.isatty.return_value = True
|
||||||
|
|
||||||
|
reporter = ProgressReporter(stdout=mock_tty)
|
||||||
|
|
||||||
|
book = Book(title="Test Book", authors=["Author"], narrators=["N"], isbn="9780000000000")
|
||||||
|
callback = reporter.start_download(book, total_bytes=50_000_000)
|
||||||
|
|
||||||
|
# Update with a new total (e.g. Content-Length arriving mid-download)
|
||||||
|
callback(10_000_000, total=100_000_000)
|
||||||
|
|
||||||
|
task_id = reporter._book_ids[id(book)]
|
||||||
|
tasks = reporter._progress.tasks
|
||||||
|
# Total should be updated to 100M, completed should be 10M
|
||||||
|
assert tasks[task_id].completed == 10_000_000
|
||||||
|
assert tasks[task_id].total == 100_000_000
|
||||||
|
|
||||||
|
def test_update_does_not_accept_task_id(self):
|
||||||
|
"""Public update() no longer exposes task_id — use bound callable instead.
|
||||||
|
|
||||||
|
Issue #30: task_id is fully internal. The public update() only accepts
|
||||||
|
completed and total kwargs.
|
||||||
|
"""
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
mock_tty = MagicMock()
|
||||||
|
mock_tty.isatty.return_value = True
|
||||||
|
|
||||||
|
reporter = ProgressReporter(stdout=mock_tty)
|
||||||
|
|
||||||
|
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000000")
|
||||||
|
reporter.start_download(book, total_bytes=100_000_000)
|
||||||
|
|
||||||
|
# Calling update with task_id should raise TypeError (parameter removed)
|
||||||
|
import inspect
|
||||||
|
sig = inspect.signature(reporter.update)
|
||||||
|
assert "task_id" not in sig.parameters, (
|
||||||
|
"update() should not expose task_id; use bound callable from start_download()"
|
||||||
|
)
|
||||||
@@ -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")
|
||||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user