Restored CONTEXT.md

Subagents overwrote this with wrong artefacts.
This commit is contained in:
AlexKucera committed 2026-06-04 15:31:24 +02:00
1 parent cbb8992acc
commit fe7642be7c
1 file changed
+89 -198
+89 -198
View File
@@ -1,223 +1,114 @@
# Code Context — Issue #26: Book Intake Module Extraction
# Libro.fm Downloader — Domain Glossary
## Files Retrieved
## 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.
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"`.
## Terms
---
### **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.
## Key Code
### **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.
### 1. `Book` dataclass (`downloader.py:36–51`)
### **M4B**
Packaged audiobook file (Apple Audiobook container). Single file, typically
contains embedded cover art. Served directly from Libro.fm's CDN.
```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
```
### **MP3**
Fallback format. Delivered as a download manifest containing N ZIP parts,
each containing one or more `.mp3` track files. Must be extracted.
**11 fields, frozen/immutable.** This is the central domain object.
### **Download Manifest**
API response (`/api/v10/download-manifest?isbn=`) listing ZIP part URLs and
track metadata (number, chapter_title) for MP3-format books.
### 2. `_raw_to_book()` — API-shape intake (`orchestrator.py:57–77`)
### **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.
```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", [])
### **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>
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"),
)
```
Custom PATH_PATTERN in config overrides this default.
**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`.
### **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`
### 3. Path helper functions (all in `downloader.py`)
### **Accompanying Files**
PDF extras and cover art. Their presence triggers subdirectory creation
for the audiobook file.
| 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 |
### **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
### 4. Everything else in `downloader.py` (download machinery — stays)
### **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.
| 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 |
### **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.
---
### **Secrets File**
`secrets.yaml` — gitignored, contains credentials. Deep-merged over
`config.yaml` at runtime. Script errors if credentials found in config.yaml.
## Architecture
### **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.
### Current module layout
### **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.
```
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
```
## API Surface (Libro.fm)
### Import graph for symbols being extracted
Base URL: https://libro.fm/
Required headers: X-LibroFm-AppVer, User-Agent
```
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
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
_raw_to_book (orchestrator.py:57)
└── called by: orchestrator.py:143 inside download_all_books()
## Select Mode
Path functions (sanitize, resolve_path, needs_subdirectory, _resolve_output_dir)
└── imported by: test_downloader.py:9-18
```
### **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.
### Data flow
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.
```
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`
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.