refactor: extract book.py and path.py from downloader monolith
Move Book dataclass + from_library_row() into dedicated book.py. Extract sanitize/resolve_path/needs_subdirectory into path.py. Hard-cut import migration across 7 source+test files. 79 new tests. Closes #26
This commit is contained in:
1 parent
323fbf76fd
commit
fb219be248
13 files changed
+1268
-309
No files matched your search
@@ -8,9 +8,8 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
|
||||
<!-- write-log: session-log-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 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) |
|
||||
| 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-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** |
|
||||
|
||||
+198
-89
@@ -1,114 +1,223 @@
|
||||
# Libro.fm Downloader — Domain Glossary
|
||||
# Code Context — Issue #26: Book Intake Module Extraction
|
||||
|
||||
## Purpose
|
||||
A Python script that logs into a Libro.fm account and downloads owned audiobooks.
|
||||
Runs once per invocation (manual or cron). No daemon, no server, no Docker.
|
||||
## Files Retrieved
|
||||
|
||||
## Terms
|
||||
1. `librofm_downloader/downloader.py` (652 lines) — **The monolith to split.** Contains Book dataclass, all path logic (sanitize, resolve_path, needs_subdirectory, token registry), download functions (M4B, ZIP, accompanying files), and orchestration helpers.
|
||||
2. `librofm_downloader/__init__.py` (2 lines) — Package init; currently exports **nothing** (no `__all__`, no re-exports).
|
||||
3. `librofm_downloader/orchestrator.py` (277 lines) — Contains `_raw_to_book()` (lines 57–77), the API-shape→Book intake function that **should** move to a new `book.py`.
|
||||
4. `librofm_downloader/cli.py` (247 lines) — Imports `Book, download_book` from downloader.
|
||||
5. `tests/test_downloader.py` (1686 lines) — **Primary test file.** Imports Book, sanitize, resolve_path, needs_subdirectory, _resolve_output_dir, download_m4b, download_zip_part, download_book, download_accompanying_files from downloader.
|
||||
6. `tests/test_orchestrator.py` (877 lines) — Imports `Book` from downloader. Has `_make_raw_book()` helper (line 19) that builds raw API dicts. Tests `_raw_to_book` indirectly via `download_all_books()`.
|
||||
7. `tests/test_progress.py` (1286 lines) — Imports `Book` from downloader for progress bar book-identity tests.
|
||||
8. `tests/test_client.py` (566 lines) — Uses raw API dict keys (`isbn`, `title`, `audiobooks`) in mock responses; imports `download_m4b` from downloader for one integration test.
|
||||
9. `tests/test_cli.py` (1423 lines) — Does NOT import from downloader directly (imports from cli which re-exports nothing).
|
||||
10. `librofm_downloader/client.py` (226 lines) — `fetch_library()` returns `list[dict]` raw API dicts under key `"audiobooks"`.
|
||||
|
||||
### **Book**
|
||||
An audiobook owned by the user's Libro.fm account. Has: title, authors, ISBN,
|
||||
cover_url, publisher, publication_date, description, genres, series (optional),
|
||||
series_num (optional), narrators, duration, track_count, pdf_extras.
|
||||
---
|
||||
|
||||
### **Format**
|
||||
The audio format to download. Three modes:
|
||||
- **m4b_mp3_fallback** (default) — Try packaged M4B first; if unavailable, download MP3 ZIP.
|
||||
- **mp3_only** — Download MP3 ZIP only.
|
||||
- **m4b_only** — Download M4B only; skip book if unavailable.
|
||||
## Key Code
|
||||
|
||||
### **M4B**
|
||||
Packaged audiobook file (Apple Audiobook container). Single file, typically
|
||||
contains embedded cover art. Served directly from Libro.fm's CDN.
|
||||
### 1. `Book` dataclass (`downloader.py:36–51`)
|
||||
|
||||
### **MP3**
|
||||
Fallback format. Delivered as a download manifest containing N ZIP parts,
|
||||
each containing one or more `.mp3` track files. Must be extracted.
|
||||
```python
|
||||
@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
|
||||
```
|
||||
|
||||
### **Download Manifest**
|
||||
API response (`/api/v10/download-manifest?isbn=`) listing ZIP part URLs and
|
||||
track metadata (number, chapter_title) for MP3-format books.
|
||||
**11 fields, frozen/immutable.** This is the central domain object.
|
||||
|
||||
### **Path Pattern**
|
||||
Template string resolving output file paths from book metadata. Tokens:
|
||||
FIRST_AUTHOR, ALL_AUTHORS, SERIES_NAME, SERIES_NUM, BOOK_TITLE, ISBN,
|
||||
FIRST_NARRATOR, ALL_NARRATORS, PUBLICATION_YEAR, PUBLICATION_MONTH,
|
||||
PUBLICATION_DAY.
|
||||
### 2. `_raw_to_book()` — API-shape intake (`orchestrator.py:57–77`)
|
||||
|
||||
### **Default Path Behavior**
|
||||
Not a static pattern — conditional on series data:
|
||||
- **With series:** <FIRST_AUTHOR>/<SERIES_NAME>/Book <SERIES_NUM> <BOOK_TITLE>
|
||||
- **Without series:** <FIRST_AUTHOR>/<BOOK_TITLE>
|
||||
```python
|
||||
def _raw_to_book(raw: dict) -> Book:
|
||||
"""Convert a Libro.fm API dict to a Book object."""
|
||||
audiobook_info = raw.get("audiobook_info", {}) or {}
|
||||
narrators = audiobook_info.get("narrators", []) or raw.get("narrators", [])
|
||||
|
||||
Custom PATH_PATTERN in config overrides this default.
|
||||
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"),
|
||||
)
|
||||
```
|
||||
|
||||
### **Output Structure**
|
||||
- Book with accompanying files (PDF extras, cover art) → subdirectory:
|
||||
`Author/Series/Book 1 Book Title/Book Title.m4b` (+ pdf, cover inside)
|
||||
- Book without accompanying files → file is leaf node:
|
||||
`Author/Series/Book 2 Another Book.m4b` or `Author/Standalone Book.m4b`
|
||||
**Raw API dict keys consumed:** `title`, `authors`, `narrators`, `isbn`, `series`, `series_num`, `cover_url`, `publication_year`, `publication_month`, `publication_day`, and nested `audiobook_info.narrators`, `audiobook_info.pdf_extras`.
|
||||
|
||||
### **Accompanying Files**
|
||||
PDF extras and cover art. Their presence triggers subdirectory creation
|
||||
for the audiobook file.
|
||||
### 3. Path helper functions (all in `downloader.py`)
|
||||
|
||||
### **Sanitization**
|
||||
Applied to every path component derived from book metadata:
|
||||
- Replace `:` with ` -`
|
||||
- Strip `< > / \ | ? *` and control characters (\x00-\x1F)
|
||||
- Remove trailing dots
|
||||
- Trim whitespace
|
||||
- Cap at 255 characters
|
||||
- Preserve dashes, commas, apostrophes, parentheses
|
||||
| Function | Lines | Purpose |
|
||||
|----------|-------|---------|
|
||||
| `sanitize(component)` | 53–75 | Filesystem-safe path component sanitization |
|
||||
| `_ILLEGAL_CHARS` | 30 | Translation table: `<>/\\|?*` |
|
||||
| `_CONTROL_CHARS` | 33 | Set of U+0000–U+001F |
|
||||
| `_TOKEN_REGISTRY` | 81–93 | 12 token → (attr, formatter) mappings |
|
||||
| `_token_value(book, token)` | 96–113 | Resolve single token to string |
|
||||
| `resolve_path(book, pattern)` | 116–132 | Main entry: custom pattern or default |
|
||||
| `_resolve_default_path(book)` | 135–148 | Author/Series/Book N Title logic |
|
||||
| `_resolve_custom_pattern(book, pattern)` | 151–161 | `{TOKEN}` regex substitution |
|
||||
| `needs_subdirectory(book)` | 164–172 | PDF extras → True |
|
||||
| `_resolve_output_dir(book, output_base, config)` | 353–379 | Full Path resolution with config |
|
||||
|
||||
### **Download History**
|
||||
JSON file mapping ISBN → {title, format, path, downloaded_at}.
|
||||
Source of truth for "has this been downloaded." Written only after
|
||||
successful complete download. Delete entry or file to re-download.
|
||||
### 4. Everything else in `downloader.py` (download machinery — stays)
|
||||
|
||||
### **Partial File**
|
||||
`.m4b.partial` or `.zip.partial` — in-progress download. Supports resume
|
||||
via HTTP Range header on next run. Renamed to final filename on completion.
|
||||
| Symbol | Lines | Purpose |
|
||||
|--------|-------|---------|
|
||||
| `InterruptedDownload` | 10–17 | Exception class |
|
||||
| `CHUNK_SIZE` | 183 | 8 MB constant |
|
||||
| `_part_filename_from_url(url)` | 186–191 | URL → safe filename |
|
||||
| `download_zip_part(...)` | 194–272 | ZIP download + extract + resume |
|
||||
| `download_m4b(...)` | 283–350 | M4B streaming download + resume |
|
||||
| `download_book(...)` | 382–455 | Format strategy orchestrator |
|
||||
| `_download_mp3(...)` | 458–490 | MP3 manifest → ZIP parts |
|
||||
| `_cover_filename_from_url(url)` | 501–505 | Cover URL → filename |
|
||||
| `_download_cover(...)` | 508–552 | Cover art streaming download |
|
||||
| `_download_pdf(...)` | 555–585 | PDF extra streaming download |
|
||||
| `download_accompanying_files(...)` | 588–632 | Cover + PDF dispatch |
|
||||
| `_write_history(...)` | 635–651 | HistoryEntry writer |
|
||||
|
||||
### **Secrets File**
|
||||
`secrets.yaml` — gitignored, contains credentials. Deep-merged over
|
||||
`config.yaml` at runtime. Script errors if credentials found in config.yaml.
|
||||
---
|
||||
|
||||
### **Sync Run**
|
||||
One execution of the script: auth → fetch library → (select mode or filter undownloaded)
|
||||
→ download each (sequentially or in parallel) → write history → print summary → exit.
|
||||
## Architecture
|
||||
|
||||
### **Workers**
|
||||
Number of simultaneous book downloads during a Sync Run. Configured via `workers` in
|
||||
config.yaml, `--workers N` CLI flag (CLI overrides config), or defaults to 3.
|
||||
Set to 1 for sequential behavior (identical to pre-parallelism). Libro.fm API calls
|
||||
are capped at 3 concurrent via semaphore regardless of worker count; CDN downloads
|
||||
are unbounded.
|
||||
### Current module layout
|
||||
|
||||
## API Surface (Libro.fm)
|
||||
```
|
||||
librofm_downloader/
|
||||
├── __init__.py # (empty — no exports)
|
||||
├── cli.py # → imports Book, download_book from downloader
|
||||
├── client.py # → fetch_library() returns list[dict] (raw API)
|
||||
├── config.py # standalone
|
||||
├── downloader.py # ★ MONOLITH: Book + path logic + downloads
|
||||
├── history.py # standalone
|
||||
├── orchestrator.py # → imports Book from downloader; has _raw_to_book()
|
||||
└── progress.py # standalone
|
||||
```
|
||||
|
||||
Base URL: https://libro.fm/
|
||||
Required headers: X-LibroFm-AppVer, User-Agent
|
||||
### Import graph for symbols being extracted
|
||||
|
||||
Endpoints:
|
||||
- POST /oauth/token — OAuth2 password grant → access_token
|
||||
- GET /api/v10/library — Paginated library list (Books[])
|
||||
- GET /api/v10/audiobooks/{isbn}/packaged_m4b — M4B download URL (404 if unavailable)
|
||||
- GET /api/v10/download-manifest?isbn= — MP3 download manifest (parts[], tracks[])
|
||||
- GET /api/v10/explore/audiobook_details/{isbn} — Full book details
|
||||
- GET /api/v10/library/{isbn}/pdf_extra_url?filename= — PDF extra download URL
|
||||
```
|
||||
Book (downloader.py:36)
|
||||
├── imported by: orchestrator.py:21
|
||||
├── imported by: cli.py:13
|
||||
├── imported by: test_downloader.py:10
|
||||
├── imported by: test_orchestrator.py:11
|
||||
└── imported by: test_progress.py:9
|
||||
|
||||
## Select Mode
|
||||
_raw_to_book (orchestrator.py:57)
|
||||
└── called by: orchestrator.py:143 inside download_all_books()
|
||||
|
||||
### **Select Mode**
|
||||
Optional interactive book selection, activated by `--select` CLI flag (off by default).
|
||||
Replaces the automatic history-filter + `--limit` pipeline stage with a user-driven TUI.
|
||||
Requires a TTY; exits with error if stdout is not a terminal.
|
||||
Powered by `questionary` library.
|
||||
Path functions (sanitize, resolve_path, needs_subdirectory, _resolve_output_dir)
|
||||
└── imported by: test_downloader.py:9-18
|
||||
```
|
||||
|
||||
When active, the pipeline becomes:
|
||||
auth → fetch library → hide already-downloaded → open checkbox TUI
|
||||
→ user picks books → confirm summary (y/N) → download(selected) → write history.
|
||||
### Data flow
|
||||
|
||||
Selection rows show: `Title — First Author [Series #]`. All books unchecked by default.
|
||||
Empty selection → exit 0. All books already downloaded → same "caught up" message as non-select mode.
|
||||
```
|
||||
client.fetch_library() → list[dict] (raw API response)
|
||||
↓
|
||||
orchestrator._raw_to_book(raw) → Book (intake/conversion)
|
||||
↓
|
||||
downloader.resolve_path(Book) → str (path logic)
|
||||
downloader.sanitize(str) → str (component safety)
|
||||
downloader.needs_subdirectory(Book) → bool (layout decision)
|
||||
↓
|
||||
downloader.download_book(Book, ...) → Path (I/O)
|
||||
```
|
||||
|
||||
### Raw API dict shape (from test patterns)
|
||||
|
||||
The Libro.fm API returns books as dicts inside an `"audiobooks"` list:
|
||||
|
||||
```python
|
||||
{
|
||||
"isbn": "9781234567890",
|
||||
"title": "Book Title",
|
||||
"authors": ["Author Name"],
|
||||
"narrators": ["Narrator Name"], # sometimes at top level
|
||||
"cover_url": "https://...",
|
||||
"series": "Series Name",
|
||||
"series_num": 1,
|
||||
"publication_year": 2024,
|
||||
"publication_month": 6,
|
||||
"publication_day": 1,
|
||||
"audiobook_info": { # nested block
|
||||
"narrators": ["Narrator Name"], # alternate narrator location
|
||||
"pdf_extras": True,
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `_make_raw_book()` helper in `test_orchestrator.py:19–36` is the canonical test fixture builder.
|
||||
|
||||
---
|
||||
|
||||
## Test Inventory
|
||||
|
||||
| File | Lines | Tests | Imports from downloader |
|
||||
|------|-------|-------|------------------------|
|
||||
| `test_downloader.py` | 1686 | ~97 tests | Book, sanitize, resolve_path, needs_subdirectory, _resolve_output_dir, download_m4b, download_zip_part, download_book, download_accompanying_files, CHUNK_SIZE, InterruptedDownload |
|
||||
| `test_orchestrator.py` | 877 | ~20 tests | Book (+ uses _raw_to_book indirectly) |
|
||||
| `test_progress.py` | 1286 | ~80+ tests | Book, download_m4b, download_zip_part, download_book |
|
||||
| `test_client.py` | 566 | ~20 tests | download_m4b (1 import) |
|
||||
| `test_cli.py` | 1423 | ~60 tests | *(none — goes through cli.run)* |
|
||||
| **Total** | **6837** | **~277** | |
|
||||
|
||||
**Total test count: 6,513 lines across 7 files.**
|
||||
|
||||
### Test classes in `test_downloader.py` relevant to extraction target:
|
||||
|
||||
| Class | Lines | What it tests |
|
||||
|-------|-------|---------------|
|
||||
| `TestSanitizeIllegalChars` | 24–45 | `sanitize()` strips chars |
|
||||
| `TestSanitizeColonReplacement` | 46–58 | `sanitize()` colon → ` -` |
|
||||
| `TestSanitizeControlChars` | 60–77 | `sanitize()` strips control chars |
|
||||
| `TestSanitizeTrailingDots` | 79–93 | `sanitize()` trailing dots |
|
||||
| `TestSanitizeTrimWhitespace` | 95–109 | `sanitize()` whitespace trim |
|
||||
| `TestSanitizeLengthCap` | 111–125 | `sanitize()` 255 cap |
|
||||
| `TestSanitizePreservedChars` | 127–147 | `sanitize()` preserves safe chars |
|
||||
| `TestSanitizeEdgeCases` | 149–166 | `sanitize()` edge cases |
|
||||
| `TestDefaultPathSeriesWithNumber` | 172–211 | `resolve_path()` series+num |
|
||||
| `TestDefaultPathSeriesWithoutNumber` | 213–227 | `resolve_path()` series only |
|
||||
| `TestDefaultPathNoSeries` | 229–243 | `resolve_path()` flat |
|
||||
| `TestCustomPathPattern` | 245–373 | `resolve_path()` tokens |
|
||||
| `TestNeedsSubdirectory` | 375–431 | `needs_subdirectory()` |
|
||||
| `TestOutputStructure` | 1509–1685 | `_resolve_output_dir()` |
|
||||
|
||||
**These ~42 test classes (~170+ test methods) are candidates for ownership by `test_book.py` / `test_path.py`.**
|
||||
|
||||
---
|
||||
|
||||
## Start Here
|
||||
|
||||
**Start with `librofm_downloader/downloader.py`** — it's the 652-line monolith containing everything to be extracted. The extraction boundary is clear:
|
||||
|
||||
1. **`book.py`** should own: `Book` dataclass + `_raw_to_book()` (moved from orchestrator.py)
|
||||
2. **`path.py`** should own: `sanitize()`, `resolve_path()`, `_resolve_default_path()`, `_resolve_custom_pattern()`, `_token_value()`, `_TOKEN_REGISTRY`, `_ILLEGAL_CHARS`, `_CONTROL_CHARS`, `needs_subdirectory()`, `_resolve_output_dir()`
|
||||
3. **`downloader.py`** keeps: All download I/O functions (`download_m4b`, `download_zip_part`, `download_book`, `_download_mp3`, `download_accompanying_files`, helpers, `InterruptedDownload`, `CHUNK_SIZE`)
|
||||
|
||||
**Key risk areas:**
|
||||
- `__init__.py` currently exports nothing — decide whether to add re-exports for backward compat
|
||||
- 6 files import from `downloader.py`; all will need updated import paths
|
||||
- `test_downloader.py` is 1686 lines and will need to be split (book/path tests vs. download I/O tests)
|
||||
- `_resolve_output_dir()` calls both `needs_subdirectory()` and `resolve_path()` — these become intra-module calls in `path.py`
|
||||
- `download_book()` and friends call `sanitize()`, `resolve_path()`, `needs_subdirectory()` — these become cross-module imports from `path.py`
|
||||
@@ -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,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"),
|
||||
)
|
||||
@@ -10,7 +10,8 @@ from rich.console import Console
|
||||
from librofm_downloader.config import load_config, ConfigError, _resolve_config_file
|
||||
from librofm_downloader.client import LibroFmClient, AuthError
|
||||
from librofm_downloader.history import DownloadHistory
|
||||
from librofm_downloader.downloader import Book, download_book
|
||||
from librofm_downloader.book import Book
|
||||
from librofm_downloader.downloader import download_book
|
||||
from librofm_downloader.orchestrator import download_all_books
|
||||
from librofm_downloader.progress import DownloadReporter
|
||||
|
||||
|
||||
@@ -1,10 +1,27 @@
|
||||
"""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 threading
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from librofm_downloader.book import Book
|
||||
from librofm_downloader.client import M4BUnavailableError
|
||||
from librofm_downloader.history import HistoryEntry
|
||||
from librofm_downloader.path import (
|
||||
_resolve_output_dir,
|
||||
needs_subdirectory,
|
||||
resolve_path,
|
||||
sanitize,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class InterruptedDownload(Exception):
|
||||
@@ -15,161 +32,6 @@ class InterruptedDownload(Exception):
|
||||
callers can distinguish "user hit Ctrl+C" from "download was cancelled
|
||||
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 +48,7 @@ CHUNK_SIZE = 8 * 1024 * 1024 # 8 MB
|
||||
def _part_filename_from_url(url: str) -> str:
|
||||
"""Derive a safe filename from a URL's last path component."""
|
||||
from urllib.parse import urlparse
|
||||
|
||||
parsed = urlparse(url)
|
||||
name = Path(parsed.path).stem or "download"
|
||||
return sanitize(name)
|
||||
@@ -290,7 +153,7 @@ def download_m4b(
|
||||
"""Download an M4B file via streaming chunks.
|
||||
|
||||
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:
|
||||
url: The CDN URL for the M4B file.
|
||||
@@ -350,35 +213,6 @@ def download_m4b(
|
||||
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(
|
||||
book: Book,
|
||||
client: "LibroFmClient",
|
||||
|
||||
@@ -18,7 +18,7 @@ from typing import Any, Callable
|
||||
|
||||
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:
|
||||
@@ -54,27 +54,6 @@ class OrchestratorResult:
|
||||
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(
|
||||
@@ -140,7 +119,7 @@ def download_all_books(
|
||||
|
||||
# Convert raw dicts to Book objects, preserving order and index
|
||||
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
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Path resolution and sanitization for librofm-downloader.
|
||||
|
||||
Pure logic module — no I/O, no network. All deterministic string manipulation.
|
||||
"""
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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
|
||||
@@ -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
|
||||
@@ -6,12 +6,14 @@ import unittest
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
|
||||
from librofm_downloader.downloader import (
|
||||
Book,
|
||||
from librofm_downloader.book import Book
|
||||
from librofm_downloader.path import (
|
||||
sanitize,
|
||||
resolve_path,
|
||||
needs_subdirectory,
|
||||
_resolve_output_dir,
|
||||
resolve_path,
|
||||
sanitize,
|
||||
)
|
||||
from librofm_downloader.downloader import (
|
||||
download_m4b,
|
||||
download_zip_part,
|
||||
download_book,
|
||||
|
||||
@@ -8,7 +8,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from librofm_downloader.downloader import Book
|
||||
from librofm_downloader.book import Book
|
||||
from librofm_downloader.orchestrator import OrchestratorResult, download_all_books
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,571 @@
|
||||
"""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 (
|
||||
needs_subdirectory,
|
||||
_resolve_output_dir,
|
||||
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"
|
||||
@@ -6,7 +6,12 @@ import tempfile
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -656,7 +661,8 @@ class TestProgressCallbackWiring:
|
||||
"""progress callable passed to download_book reaches download_m4b."""
|
||||
import httpx
|
||||
from pathlib import Path
|
||||
from librofm_downloader.downloader import Book, download_book
|
||||
from librofm_downloader.book import Book
|
||||
from librofm_downloader.downloader import download_book
|
||||
from librofm_downloader.client import LibroFmClient
|
||||
from librofm_downloader.history import DownloadHistory
|
||||
|
||||
|
||||
Reference in new issue
Block a user