The existing librofm-downloader reference implementation is a Kotlin/JVM application shaped as a long-running Docker container with an HTTP API server, GraphQL connectors for book tracker sync (Hardcover), healthchecks.io webhooks, SQLDelight database, and a 4 GB JVM heap. For a user who simply wants their Libro.fm audiobooks to download to a local folder on a schedule, this is excessive machinery. The user wants a lightweight Python script that authenticates against Libro.fm, checks their library, downloads new audiobooks in M4B format (falling back to MP3), and can be triggered manually or via cron job.
Solution
A Python 3.13+ command-line tool organized as a small testable module package. It runs once per invocation (no daemon, no server, no Docker). It authenticates via OAuth2 password grant against the Libro.fm REST API, fetches the user's full library (with pagination), filters out already-downloaded books using a local JSON history file, downloads each new book with streaming chunked I/O and resume support for large files (1.8+ GB), and records successful downloads. Configuration lives in a committed config.yaml file; credentials live in a gitignored secrets.yaml that deeply overrides config at runtime. The script rejects credentials found in config.yaml.
User Stories
As a Libro.fm member, I want the script to authenticate with my username and password, so that it can access my library.
As a Libro.fm member, I want my credentials stored in a separate secrets.yaml file that is gitignored, so that I don't accidentally commit them.
As a user, I want the script to error if I put credentials in config.yaml, so that I don't accidentally commit secrets.
As a Libro.fm member, I want the script to fetch my complete library across all pages, so that no owned books are missed.
As a Libro.fm member, I want new books downloaded in M4B format when available, so that I get a single high-quality audiobook file.
As a Libro.fm member, I want the script to fall back to MP3 format when M4B is unavailable for a book, so that I still get the audiobook rather than skipping it.
As a user, I want to configure which format strategy to use (m4b_mp3_fallback, mp3_only, or m4b_only), so that I control the behavior.
As a user, I want books downloaded into a configurable output directory, so that I can point it at my audiobook library location (e.g., iCloud Drive, NAS mount).
As a user, I want configurable path patterns for organizing downloaded books (e.g., <FIRST_AUTHOR>/<SERIES_NAME>/Book <SERIES_NUM> <BOOK_TITLE>), so that my library matches my preferred organizational scheme.
As a user, I want sensible default path behavior that uses series information when available and falls back to a flat structure when it isn't, so that I don't need to configure anything for common cases.
As a user, I want book metadata values sanitized for filesystem safety in path components (strip illegal chars, replace colons with dashes, cap length), so that downloads never fail due to invalid filenames.
As a user, I want books with accompanying files (PDF extras, cover art) placed in a subdirectory, and books without accompanying files as leaf files, so that my library layout stays clean without unnecessary nesting.
As a user, I want PDF extras downloaded alongside audiobooks when available, so that I get bonus content like maps and author notes.
As a user, I want cover art downloaded alongside audiobooks when available (non-critical, since M4Bs usually have embedded covers), so that I have visual assets for library management tools.
As a user, I want the script to skip books that were already successfully downloaded, so that re-runs are fast and idempotent.
As a user, I want download history tracked in a human-readable JSON file, so that I can inspect what's been downloaded and remove entries to force re-downloads.
As a user downloading large audiobooks (1.8+ GB), I want files downloaded in chunks with streaming I/O, so that the script doesn't OOM on big files.
As a user downloading large audiobooks over residential internet, I want interrupted downloads to resume from where they left off (via .partial file + HTTP Range header), so that a WiFi blip at 90% doesn't mean starting over.
As a user running the script interactively, I want a progress bar showing download speed, percentage, and ETA, so that I know how long a 1.8 GB book will take.
As a user running the script from cron, I want plain log output instead of progress bars (auto-detected via TTY check), so that cron emails are readable.
As a user, I want per-book failure isolation so that one failing book doesn't stop the rest of the batch, so that a single bad book doesn't block my entire library sync.
As a user, I want a summary at the end showing how many books were downloaded, skipped, and failed, so that I know the outcome at a glance.
As a user, I want the script to exit with code 0 on partial success (some books failed) and exit code 1 only on fatal errors (auth failure, missing config, unreachable API), so that cron's MAILTO only emails me about real problems.
As a user, I want no automatic retry per book (next cron run picks up failures), so that the script doesn't get stuck in retry loops during outages.
As a developer, I want the code split into testable modules (config, client, downloader, history, cli), so that each concern can be tested in isolation.
As a developer, I want tests written TDD-style with mocked HTTP fixtures, so that I can develop confidently against the real API surface without hitting rate limits.
Implementation Decisions
Module Architecture
Five modules under librofm_downloader/ package:
config — Loads config.yaml + secrets.yaml, deep-merges (secrets override config), validates required fields present, rejects if librofm.username or librofm.password exist in config.yaml. Returns a typed config object.
client — Wraps all Libro.fm HTTP interactions: OAuth2 token fetch, paginated library fetch, M4B metadata query, MP3 download manifest fetch, PDF extra URL fetch, book details fetch. Base URL https://libro.fm/. Required headers: X-LibroFm-AppVer and User-Agent. Uses httpx with streaming support.
downloader — File I/O layer: resolves output paths from book metadata + path pattern, sanitizes path components, manages streaming chunked downloads with .partial file tracking and HTTP Range-header resume, extracts ZIP archives for MP3 parts, downloads PDF extras and cover art. Determines whether subdirectory is needed based on presence of accompanying files.
history — Reads/writes download_history.json. Checks whether an ISBN was previously downloaded. Writes entry only after fully successful download. Handles corrupt/missing history gracefully (treat as empty).
cli — Entry point. Orchestrates the full sync run: load config → auth → fetch library → filter undownloaded → iterate books (resolve path → try M4B → fallback MP3 → download extras) → update history → print summary → exit with appropriate code. Detects TTY for rich vs plain output.
Configuration Schema
Config file (config.yaml) contains non-sensitive settings. Secrets file (secrets.yaml) contains credentials. Secrets perform a deep merge override over config. Both use YAML format.
Tests verify external behavior and contracts, not implementation details. Each module is tested through its public interface with internal details hidden behind those interfaces. HTTP interactions are tested with mock responses (fixture JSON files matching real API shapes), not against the live API.
Modules Under Test
All five modules will have dedicated test files:
test_config — Valid YAML loading, missing required fields, invalid format values, secrets merge override, rejection of credentials in config.yaml, defaults applied for optional fields
test_client — Auth success/failure, token caching, library pagination (single-page and multi-page), M4B metadata success/404, MP3 manifest parsing, PDF URL fetch, book details fetch. All via mocked httpx responses with fixture JSON data extracted from the reference implementation's model shapes
test_downloader — Path resolution from all tokens, conditional default path (with/without series), sanitization rules (colons, illegal chars, truncation), streaming download to temp dir, resume from .partial file, ZIP extraction, subdirectory-vs-flat decision logic, cover/PDF download triggering
test_history — Empty history (file doesn't exist), round-trip write/read, skip detection by ISBN, corrupt JSON recovery (treat as empty), removal of entry for re-download
test_cli — Full orchestration integration test with all dependencies mocked: happy path (new books download), mixed result (some new, some skipped, one fails), fatal error path (auth fails -> exit 1), summary output formatting, TTY vs non-TTY output difference
Test Fixtures
Sample API response JSON files in tests/fixtures/ matching the exact shapes returned by Libro.fm's API (reverse-engineered from the reference Kotlin implementation's serialization models):
token_response.json — OAuth2 token response shape
library_page1.json — Single page of library with sample books (including edge cases: book with series, book without, book with PDF extras)
library_page2.json — Second page for pagination testing
m4b_metadata_success.json — M4B URL response
m4b_metadata_404.json — Not found case
mp3_download_manifest.json — Parts list + track metadata
book_details.json — Full book details with narrators, pdf_extras, series info
Out of Scope
Daemon/server mode — No long-running process, no HTTP API, no port binding. Use cron for scheduling.
Docker — The whole point is avoiding container overhead.
Tracker syncing — No Hardcover, Goodreads, or other book tracker integration. No wishlist sync.
Webhook notifications — No healthchecks.io, no generic webhook POST on completion.
ffmpeg conversion — No MP3-to-M4B transcoding. Native M4B fallback covers the vast majority of books.
Chapter renaming and ID3 tags — Deferred to future work. Would require mutagen dependency. Low priority since most downloads are M4B.
Database — No SQLite or any database. JSON file for download history is sufficient.
GraphQL client — The reference app uses Apollo GraphQL but all needed endpoints are plain REST; we use REST directly.
Parallel downloads — Sequential download keeps it simple and avoids memory pressure with 1.8 GB files. Can be added later via --parallel flag.
GUI/Web UI — CLI-only tool.
Further Notes
The Libro.fm API requires specific headers (X-LibroFm-AppVer, User-Agent) that mimic their mobile app. These should be baked in with reasonable defaults but made configurable in case they change.
Token caching: the OAuth2 access token should be cached in-memory for the duration of a single run (not persisted across runs). A fresh token each run is simplest and avoids expiration handling.
The reference implementation uses FORMAT=MP3 as the Dockerfile default despite README saying M4B_MP3_FALLBACK is default. Our default will be m4b_mp3_fallback as documented.
The LIBRO_FM_HEADERS env var in the reference carries X-LibroFm-AppVer=7.34.8,User-Agent=okhttp/5.3.2. We'll use these as defaults but allow override in config.
This project targets Python 3.13+ (no need for legacy compatibility).
Set up a Python venv for this project.
## Problem Statement
The existing [librofm-downloader](https://github.com/burntcookie90/librofm-downloader) reference implementation is a Kotlin/JVM application shaped as a long-running Docker container with an HTTP API server, GraphQL connectors for book tracker sync (Hardcover), healthchecks.io webhooks, SQLDelight database, and a 4 GB JVM heap. For a user who simply wants their Libro.fm audiobooks to download to a local folder on a schedule, this is excessive machinery. The user wants a lightweight Python script that authenticates against Libro.fm, checks their library, downloads new audiobooks in M4B format (falling back to MP3), and can be triggered manually or via cron job.
## Solution
A Python 3.13+ command-line tool organized as a small testable module package. It runs once per invocation (no daemon, no server, no Docker). It authenticates via OAuth2 password grant against the Libro.fm REST API, fetches the user's full library (with pagination), filters out already-downloaded books using a local JSON history file, downloads each new book with streaming chunked I/O and resume support for large files (1.8+ GB), and records successful downloads. Configuration lives in a committed `config.yaml` file; credentials live in a gitignored `secrets.yaml` that deeply overrides config at runtime. The script rejects credentials found in `config.yaml`.
## User Stories
1. As a **Libro.fm member**, I want the script to authenticate with my username and password, so that it can access my library.
2. As a **Libro.fm member**, I want my credentials stored in a separate `secrets.yaml` file that is gitignored, so that I don't accidentally commit them.
3. As a **user**, I want the script to error if I put credentials in `config.yaml`, so that I don't accidentally commit secrets.
4. As a **Libro.fm member**, I want the script to fetch my complete library across all pages, so that no owned books are missed.
5. As a **Libro.fm member**, I want new books downloaded in M4B format when available, so that I get a single high-quality audiobook file.
6. As a **Libro.fm member**, I want the script to fall back to MP3 format when M4B is unavailable for a book, so that I still get the audiobook rather than skipping it.
7. As a **user**, I want to configure which format strategy to use (`m4b_mp3_fallback`, `mp3_only`, or `m4b_only`), so that I control the behavior.
8. As a **user**, I want books downloaded into a configurable output directory, so that I can point it at my audiobook library location (e.g., iCloud Drive, NAS mount).
9. As a **user**, I want configurable path patterns for organizing downloaded books (e.g., `<FIRST_AUTHOR>/<SERIES_NAME>/Book <SERIES_NUM> <BOOK_TITLE>`), so that my library matches my preferred organizational scheme.
10. As a **user**, I want sensible default path behavior that uses series information when available and falls back to a flat structure when it isn't, so that I don't need to configure anything for common cases.
11. As a **user**, I want book metadata values sanitized for filesystem safety in path components (strip illegal chars, replace colons with dashes, cap length), so that downloads never fail due to invalid filenames.
12. As a **user**, I want books with accompanying files (PDF extras, cover art) placed in a subdirectory, and books without accompanying files as leaf files, so that my library layout stays clean without unnecessary nesting.
13. As a **user**, I want PDF extras downloaded alongside audiobooks when available, so that I get bonus content like maps and author notes.
14. As a **user**, I want cover art downloaded alongside audiobooks when available (non-critical, since M4Bs usually have embedded covers), so that I have visual assets for library management tools.
15. As a **user**, I want the script to skip books that were already successfully downloaded, so that re-runs are fast and idempotent.
16. As a **user**, I want download history tracked in a human-readable JSON file, so that I can inspect what's been downloaded and remove entries to force re-downloads.
17. As a **user** downloading large audiobooks (1.8+ GB), I want files downloaded in chunks with streaming I/O, so that the script doesn't OOM on big files.
18. As a **user** downloading large audiobooks over residential internet, I want interrupted downloads to resume from where they left off (via `.partial` file + HTTP Range header), so that a WiFi blip at 90% doesn't mean starting over.
19. As a **user running the script interactively**, I want a progress bar showing download speed, percentage, and ETA, so that I know how long a 1.8 GB book will take.
20. As a **user running the script from cron**, I want plain log output instead of progress bars (auto-detected via TTY check), so that cron emails are readable.
21. As a **user**, I want per-book failure isolation so that one failing book doesn't stop the rest of the batch, so that a single bad book doesn't block my entire library sync.
22. As a **user**, I want a summary at the end showing how many books were downloaded, skipped, and failed, so that I know the outcome at a glance.
23. As a **user**, I want the script to exit with code 0 on partial success (some books failed) and exit code 1 only on fatal errors (auth failure, missing config, unreachable API), so that cron's MAILTO only emails me about real problems.
24. As a **user**, I want no automatic retry per book (next cron run picks up failures), so that the script doesn't get stuck in retry loops during outages.
25. As a **developer**, I want the code split into testable modules (config, client, downloader, history, cli), so that each concern can be tested in isolation.
26. As a **developer**, I want tests written TDD-style with mocked HTTP fixtures, so that I can develop confidently against the real API surface without hitting rate limits.
## Implementation Decisions
### Module Architecture
Five modules under `librofm_downloader/` package:
- **config** — Loads `config.yaml` + `secrets.yaml`, deep-merges (secrets override config), validates required fields present, rejects if `librofm.username` or `librofm.password` exist in config.yaml. Returns a typed config object.
- **client** — Wraps all Libro.fm HTTP interactions: OAuth2 token fetch, paginated library fetch, M4B metadata query, MP3 download manifest fetch, PDF extra URL fetch, book details fetch. Base URL `https://libro.fm/`. Required headers: `X-LibroFm-AppVer` and `User-Agent`. Uses httpx with streaming support.
- **downloader** — File I/O layer: resolves output paths from book metadata + path pattern, sanitizes path components, manages streaming chunked downloads with `.partial` file tracking and HTTP Range-header resume, extracts ZIP archives for MP3 parts, downloads PDF extras and cover art. Determines whether subdirectory is needed based on presence of accompanying files.
- **history** — Reads/writes `download_history.json`. Checks whether an ISBN was previously downloaded. Writes entry only after fully successful download. Handles corrupt/missing history gracefully (treat as empty).
- **cli** — Entry point. Orchestrates the full sync run: load config → auth → fetch library → filter undownloaded → iterate books (resolve path → try M4B → fallback MP3 → download extras) → update history → print summary → exit with appropriate code. Detects TTY for rich vs plain output.
### Configuration Schema
Config file (`config.yaml`) contains non-sensitive settings. Secrets file (`secrets.yaml`) contains credentials. Secrets perform a deep merge override over config. Both use YAML format.
Config shape:
```yaml
# Non-sensitive settings (committed)
output:
dir: "./audiobooks" # Output root directory
path_pattern: null # Optional custom pattern; null = smart default
download:
format: "m4b_mp3_fallback" # m4b_mp3_fallback | mp3_only | m4b_only
download_extras: true # Download PDF extras
download_covers: true # Download cover art
```
Secrets shape:
```yaml
# Sensitive settings (gitignored)
librofm:
username: ""
password: ""
```
### Default Path Behavior
When `path_pattern` is null/unset, the default is conditional:
- Book has `series` AND `series_num`: `<FIRST_AUTHOR>/<SERIES_NAME>/Book <SERIES_NUM> <BOOK_TITLE>`
- Book has `series` but no `series_num`: `<FIRST_AUTHOR>/<SERIES_NAME>/<BOOK_TITLE>`
- Book has no series: `<FIRST_AUTHOR>/<BOOK_TITLE>`
When `path_pattern` is set, it overrides this default entirely and is used as-is with token substitution.
### Path Sanitization Rules
Applied to every path component derived from book metadata:
1. Replace `:` characters with ` -`
2. Strip characters: `< > / \ | ? *`
3. Strip control characters: `\x00-\x1F`
4. Remove trailing dots
5. Trim whitespace
6. Cap component length at 255 characters
7. Preserve: dashes, commas, apostrophes, parentheses, periods (non-trailing)
### Output Structure Rules
- If a book has **any** accompanying file (PDF extras OR cover art): create subdirectory, place audio + all accompaniments inside
- If a book has **no** accompanying files: audio file is the leaf node (no subdirectory)
- The filename of the audio file is derived from the book title (sanitized)
### Download Resume Mechanism
- Downloads write to `{filename}.{ext}.partial` during transfer
- On completion, atomic rename to final `{filename}.{ext}`
- On restart, detect existing `.partial` file, read its size, send `Range: bytes={size}-` header
- Works for both M4B direct downloads and MP3 ZIP part downloads
- Chunk size: 8 MB per read
### Error Handling Strategy
- **Fatal errors** (exit code 1): config missing/invalid, secrets file missing, auth failure, cannot reach Libro.fm API at all
- **Book-level errors** (logged, continue): network timeout mid-download, 403/404 on specific book, disk full, corrupt ZIP
- **Summary output**: always printed at end — counts of downloaded/skipped/failed with ISBNs and titles for failures
- No automatic retry per book; next invocation picks up failures
### Dependencies
Runtime: `httpx` (HTTP client with streaming), `pyyaml` (config parsing), `rich` (progress bars, TTY auto-detection)
Test: `pytest`, `pytest-mock`, `httpx` (for transport mocking)
## Testing Decisions
### Testing Philosophy
Tests verify external behavior and contracts, not implementation details. Each module is tested through its public interface with internal details hidden behind those interfaces. HTTP interactions are tested with mock responses (fixture JSON files matching real API shapes), not against the live API.
### Modules Under Test
All five modules will have dedicated test files:
- **test_config** — Valid YAML loading, missing required fields, invalid format values, secrets merge override, rejection of credentials in config.yaml, defaults applied for optional fields
- **test_client** — Auth success/failure, token caching, library pagination (single-page and multi-page), M4B metadata success/404, MP3 manifest parsing, PDF URL fetch, book details fetch. All via mocked httpx responses with fixture JSON data extracted from the reference implementation's model shapes
- **test_downloader** — Path resolution from all tokens, conditional default path (with/without series), sanitization rules (colons, illegal chars, truncation), streaming download to temp dir, resume from `.partial` file, ZIP extraction, subdirectory-vs-flat decision logic, cover/PDF download triggering
- **test_history** — Empty history (file doesn't exist), round-trip write/read, skip detection by ISBN, corrupt JSON recovery (treat as empty), removal of entry for re-download
- **test_cli** — Full orchestration integration test with all dependencies mocked: happy path (new books download), mixed result (some new, some skipped, one fails), fatal error path (auth fails -> exit 1), summary output formatting, TTY vs non-TTY output difference
### Test Fixtures
Sample API response JSON files in `tests/fixtures/` matching the exact shapes returned by Libro.fm's API (reverse-engineered from the reference Kotlin implementation's serialization models):
- `token_response.json` — OAuth2 token response shape
- `library_page1.json` — Single page of library with sample books (including edge cases: book with series, book without, book with PDF extras)
- `library_page2.json` — Second page for pagination testing
- `m4b_metadata_success.json` — M4B URL response
- `m4b_metadata_404.json` — Not found case
- `mp3_download_manifest.json` — Parts list + track metadata
- `book_details.json` — Full book details with narrators, pdf_extras, series info
## Out of Scope
- **Daemon/server mode** — No long-running process, no HTTP API, no port binding. Use cron for scheduling.
- **Docker** — The whole point is avoiding container overhead.
- **Tracker syncing** — No Hardcover, Goodreads, or other book tracker integration. No wishlist sync.
- **Webhook notifications** — No healthchecks.io, no generic webhook POST on completion.
- **ffmpeg conversion** — No MP3-to-M4B transcoding. Native M4B fallback covers the vast majority of books.
- **Chapter renaming and ID3 tags** — Deferred to future work. Would require `mutagen` dependency. Low priority since most downloads are M4B.
- **Database** — No SQLite or any database. JSON file for download history is sufficient.
- **GraphQL client** — The reference app uses Apollo GraphQL but all needed endpoints are plain REST; we use REST directly.
- **Parallel downloads** — Sequential download keeps it simple and avoids memory pressure with 1.8 GB files. Can be added later via `--parallel` flag.
- **GUI/Web UI** — CLI-only tool.
## Further Notes
- The Libro.fm API requires specific headers (`X-LibroFm-AppVer`, `User-Agent`) that mimic their mobile app. These should be baked in with reasonable defaults but made configurable in case they change.
- Token caching: the OAuth2 access token should be cached in-memory for the duration of a single run (not persisted across runs). A fresh token each run is simplest and avoids expiration handling.
- The reference implementation uses `FORMAT=MP3` as the Dockerfile default despite README saying `M4B_MP3_FALLBACK` is default. Our default will be `m4b_mp3_fallback` as documented.
- The `LIBRO_FM_HEADERS` env var in the reference carries `X-LibroFm-AppVer=7.34.8,User-Agent=okhttp/5.3.2`. We'll use these as defaults but allow override in config.
- This project targets Python 3.13+ (no need for legacy compatibility).
- Set up a Python venv for this project.
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Problem Statement
The existing librofm-downloader reference implementation is a Kotlin/JVM application shaped as a long-running Docker container with an HTTP API server, GraphQL connectors for book tracker sync (Hardcover), healthchecks.io webhooks, SQLDelight database, and a 4 GB JVM heap. For a user who simply wants their Libro.fm audiobooks to download to a local folder on a schedule, this is excessive machinery. The user wants a lightweight Python script that authenticates against Libro.fm, checks their library, downloads new audiobooks in M4B format (falling back to MP3), and can be triggered manually or via cron job.
Solution
A Python 3.13+ command-line tool organized as a small testable module package. It runs once per invocation (no daemon, no server, no Docker). It authenticates via OAuth2 password grant against the Libro.fm REST API, fetches the user's full library (with pagination), filters out already-downloaded books using a local JSON history file, downloads each new book with streaming chunked I/O and resume support for large files (1.8+ GB), and records successful downloads. Configuration lives in a committed
config.yamlfile; credentials live in a gitignoredsecrets.yamlthat deeply overrides config at runtime. The script rejects credentials found inconfig.yaml.User Stories
secrets.yamlfile that is gitignored, so that I don't accidentally commit them.config.yaml, so that I don't accidentally commit secrets.m4b_mp3_fallback,mp3_only, orm4b_only), so that I control the behavior.<FIRST_AUTHOR>/<SERIES_NAME>/Book <SERIES_NUM> <BOOK_TITLE>), so that my library matches my preferred organizational scheme..partialfile + HTTP Range header), so that a WiFi blip at 90% doesn't mean starting over.Implementation Decisions
Module Architecture
Five modules under
librofm_downloader/package:config.yaml+secrets.yaml, deep-merges (secrets override config), validates required fields present, rejects iflibrofm.usernameorlibrofm.passwordexist in config.yaml. Returns a typed config object.https://libro.fm/. Required headers:X-LibroFm-AppVerandUser-Agent. Uses httpx with streaming support..partialfile tracking and HTTP Range-header resume, extracts ZIP archives for MP3 parts, downloads PDF extras and cover art. Determines whether subdirectory is needed based on presence of accompanying files.download_history.json. Checks whether an ISBN was previously downloaded. Writes entry only after fully successful download. Handles corrupt/missing history gracefully (treat as empty).Configuration Schema
Config file (
config.yaml) contains non-sensitive settings. Secrets file (secrets.yaml) contains credentials. Secrets perform a deep merge override over config. Both use YAML format.Config shape:
Secrets shape:
Default Path Behavior
When
path_patternis null/unset, the default is conditional:seriesANDseries_num:<FIRST_AUTHOR>/<SERIES_NAME>/Book <SERIES_NUM> <BOOK_TITLE>seriesbut noseries_num:<FIRST_AUTHOR>/<SERIES_NAME>/<BOOK_TITLE><FIRST_AUTHOR>/<BOOK_TITLE>When
path_patternis set, it overrides this default entirely and is used as-is with token substitution.Path Sanitization Rules
Applied to every path component derived from book metadata:
:characters with-< > / \ | ? *\x00-\x1FOutput Structure Rules
Download Resume Mechanism
{filename}.{ext}.partialduring transfer{filename}.{ext}.partialfile, read its size, sendRange: bytes={size}-headerError Handling Strategy
Dependencies
Runtime:
httpx(HTTP client with streaming),pyyaml(config parsing),rich(progress bars, TTY auto-detection)Test:
pytest,pytest-mock,httpx(for transport mocking)Testing Decisions
Testing Philosophy
Tests verify external behavior and contracts, not implementation details. Each module is tested through its public interface with internal details hidden behind those interfaces. HTTP interactions are tested with mock responses (fixture JSON files matching real API shapes), not against the live API.
Modules Under Test
All five modules will have dedicated test files:
.partialfile, ZIP extraction, subdirectory-vs-flat decision logic, cover/PDF download triggeringTest Fixtures
Sample API response JSON files in
tests/fixtures/matching the exact shapes returned by Libro.fm's API (reverse-engineered from the reference Kotlin implementation's serialization models):token_response.json— OAuth2 token response shapelibrary_page1.json— Single page of library with sample books (including edge cases: book with series, book without, book with PDF extras)library_page2.json— Second page for pagination testingm4b_metadata_success.json— M4B URL responsem4b_metadata_404.json— Not found casemp3_download_manifest.json— Parts list + track metadatabook_details.json— Full book details with narrators, pdf_extras, series infoOut of Scope
mutagendependency. Low priority since most downloads are M4B.--parallelflag.Further Notes
X-LibroFm-AppVer,User-Agent) that mimic their mobile app. These should be baked in with reasonable defaults but made configurable in case they change.FORMAT=MP3as the Dockerfile default despite README sayingM4B_MP3_FALLBACKis default. Our default will bem4b_mp3_fallbackas documented.LIBRO_FM_HEADERSenv var in the reference carriesX-LibroFm-AppVer=7.34.8,User-Agent=okhttp/5.3.2. We'll use these as defaults but allow override in config.