diff --git a/AGENTS.md b/AGENTS.md index 7928bcb..197092e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,8 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste | Date | Type | File | Summary | |------|------|------|---------| +| 2026-06-04 | issue | [20260604-issue23-wire-xdg-resolution-into-cli_log.md](docs/devlog/20260604-issue23-wire-xdg-resolution-into-cli_log.md) | **Issue #23 Complete:** Wire XDG resolution into CLI — history path XDG default, verbose resolved paths, searched-paths message. **7 new tests, 188 total** · **10/10 AC** | +| 2026-06-04 | issue | [20260604-issue22-xdg-config-path-resolution-with-cwd-fallback_log.md](docs/devlog/20260604-issue22-xdg-config-path-resolution-with-cwd-fallback_log.md) | **Issue #22 Complete:** XDG→CWD path resolution, `load_config(None, None)` search, missing-config notice, OS→domain error wrapping. **9 new tests, 181 total** · **8/8 AC** | | 2026-06-03 | issue | [20260603-cli-parallel-integration-and-ctrl-c-drain-issue17_log.md](docs/devlog/20260603-cli-parallel-integration-and-ctrl-c-drain-issue17_log.md) | **Issue #17 Complete:** CLI parallel integration + graceful Ctrl+C drain. Orchestrator catches KeyboardInterrupt, drains in-flight downloads (shutdown(wait=True)), double-Ctrl+C fast exit. **13 new tests, 231 total** · **10/10 AC** | | 2026-06-03 | issue | [20260603-parallel-download-orchestrator-issue16_log.md](docs/devlog/20260603-parallel-download-orchestrator-issue16_log.md) | **Issue #16 Complete:** `orchestrator.py` — `ThreadPoolExecutor` parallel download engine. Replaces sequential for-loop in cli.py. `OrchestratorResult` dataclass, stable-sort ordering, failure isolation. **20 new tests, 218 total** · **11/11 AC** | | 2026-06-03 | issue | [20260603-api-rate-limiter-issue15_log.md](docs/devlog/20260603-api-rate-limiter-issue15_log.md) | **Issue #15 Complete:** `threading.Semaphore(3)` API rate limiter on `LibroFmClient`. Caps concurrent API calls; CDN downloads bypass. **4 new tests, 198 total** · **6/6 AC** | diff --git a/CHANGELOG.md b/CHANGELOG.md index bb542d3..986cfd0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,31 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [1.1.0] - 2026-06-04 + +### Added +- **config (closes #22):** XDG config path resolution with CWD fallback. + `_resolve_config_file()` searches `~/.config/librofm-downloader/` then CWD. + `load_config(None, None)` triggers search; missing config.yaml is non-fatal + (prints notice, uses built-in defaults); missing secrets.yaml raises + domain error listing searched paths. All OS exceptions wrapped as + `ConfigError`. XDG directory auto-created on demand. +- **cli (closes #23):** Wire XDG path resolution into CLI layer. + History path defaults to `None` (resolves XDG → CWD, falls back to XDG + location). Missing config message now lists searched paths. `--verbose` + shows resolved file paths for config, secrets, and history. Explicit + `--config`/`--secrets`/`--history` flags bypass search. Clean exit 1 + with no traceback when secrets missing from all locations. + +### Documentation +- **docs (closes #24):** Update all documentation for XDG path resolution. + configuration.md: new "Default file locations" section with search order, + auto-creation, missing-config vs missing-secrets behavior, CLI flag + overrides, validation error table with "not found" messages, and + history default location. quickstart.md, cli-usage.md, troubleshooting.md, + and README.md updated to reference XDG-first search. + +## [1.0.0] - 2026-06-03 ### Fixed diff --git a/CONTEXT.md b/CONTEXT.md index 39b8b28..451e192 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -75,7 +75,7 @@ via HTTP Range header on next run. Renamed to final filename on completion. `config.yaml` at runtime. Script errors if credentials found in config.yaml. ### **Sync Run** -One execution of the script: auth → fetch library → filter undownloaded +One execution of the script: auth → fetch library → (select mode or filter undownloaded) → download each (sequentially or in parallel) → write history → print summary → exit. ### **Workers** @@ -97,3 +97,18 @@ Endpoints: - 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 + +## Select Mode + +### **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. + +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. + +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. diff --git a/README.md b/README.md index 09e3035..c3eb229 100644 --- a/README.md +++ b/README.md @@ -25,8 +25,11 @@ No Docker. No JVM. Just `pip install` and go. # 1. Install pip install librofm-downloader -# 2. Configure -cat > config.yaml << 'EOF' +# 2. Create XDG config directory +mkdir -p ~/.config/librofm-downloader + +# 3. Configure +cat > ~/.config/librofm-downloader/config.yaml << 'EOF' librofm: format: m4b_mp3_fallback output_dir: ./audiobooks @@ -34,7 +37,7 @@ librofm: download_covers: true EOF -cat > secrets.yaml << 'EOF' +cat > ~/.config/librofm-downloader/secrets.yaml << 'EOF' librofm: username: your-email@example.com password: your-password diff --git a/docs/adr/0006-select-mode-interactive-book-selection.md b/docs/adr/0006-select-mode-interactive-book-selection.md new file mode 100644 index 0000000..53453cf --- /dev/null +++ b/docs/adr/0006-select-mode-interactive-book-selection.md @@ -0,0 +1,123 @@ +# ADR 0006: Select Mode — Interactive Book Selection + +## Status + +Accepted (2026-06-03) + +## Context + +Libro.fm-downloader downloads **all** undownloaded books from the user's library on every run. The only controls are `--limit N` (cap count) and download-history filtering (skip already-downloaded). Users with large libraries (50+ books) or limited storage want to choose specific books rather than downloading everything. + +The tool already supports two output modes: TTY (Rich progress bars) and non-TTY/cron (plain log lines). Any interactive feature must respect this duality. + +## Decision + +Add a `--select` CLI flag (off by default, CLI-only — no config.yaml option) that opens an interactive checkbox TUI before downloading. When active, select mode supersedes both the history filter and `--limit`. + +### Library: questionary + +| Library | Verdict | +|---|---| +| **questionary** | **Chosen** — mature, Rich-compatible styling, checkbox prompt with fuzzy search, most popular Python interactive CLI library | +| inquirer | Rejected — lighter but fewer features, less active maintenance | +| Custom Rich-based | Rejected — more code to write/maintain, Rich's Live is powerful but not designed for form-style interaction | + +### Non-TTY behavior + +**Hard exit with error.** Select mode requires interactivity by definition. If stdout is not a terminal (piped, cron, redirected), print `"--select requires an interactive terminal (TTY)"` and exit 1. + +Rationale: silent degradation would be surprising (user expects to pick books, gets all-or-nothing instead). A fallback to numbered-list input was considered but adds a second codepath to test and a degraded experience that most users won't encounter. + +### Row format + +`[ ] N. Title — First Author [Series #]` + +- Number for easy reference +- Title + first author (full author list available elsewhere if needed) +- Series + number when present (helps with series ordering decisions) +- Duration deliberately omitted: not available from `/api/v10/library` endpoint; fetching per-book from `/api/v10/explore/audiobook_details/{isbn}` adds N API calls and latency before the UI renders + +### Default selection state + +**All unchecked.** User must actively opt-in each book. Prevents accidental bulk downloads of large libraries. + +### Already-downloaded books + +**Hidden completely.** The selection list shows only undownloaded books. Already-downloaded books are filtered out before the TUI opens, same as today's automatic pipeline stage. If all books are downloaded, print the existing `"All caught up! No new books to download."` message and exit 0 — identical to non-select behavior. + +### Post-selection confirmation + +Always show a y/N summary after selection: + +``` +3 books selected for download: + • The Great Gatsby — F. Scott Fitzgerald + • Dune — Frank Herbert + • Project Hail Mary — Andy Weir + +Proceed? [y/N] +``` + +Prevents fat-finger mistakes on large libraries. No configurable threshold — always confirm. + +### Empty selection + +If user presses Enter without checking any boxes: print `"No books selected. Exiting."` and exit 0. Not an error — choosing nothing is valid. + +### Pipeline integration + +``` +BEFORE: auth → fetch_library → filter_downloaded → [limit] → download_all +AFTER: auth → fetch_library → [--select? → select_books() : filter_downloaded+limit] → download_all +``` + +When `--select` is on: +1. Fetch full library +2. Remove already-downloaded books (same `DownloadHistory` check) +3. Verify TTY availability → error if not +4. Convert raw dicts to `Book` objects +5. Open questionary checkbox prompt +6. On confirm: show summary, ask y/N +7. Pass selected books to existing `download_all_books()` orchestrator +8. Continue with normal progress reporting, history writing, summary + +### Code location + +New module: `librofm_downloader/selector.py` + +Single public function: +```python +def select_books(books: list[Book]) -> list[Book]: + """Open interactive TUI, return user-selected books.""" +``` + +CLI integration in `cli.py`: add `--select` argument, branch between select mode and existing auto-filter path before the download stage. + +## Consequences + +### Positive + +- Users control exactly what downloads — no more bulk downloads of unwanted books +- Works naturally with existing parallel download infrastructure (`download_all_books` accepts any book list) +- Zero changes to download pipeline, history, or progress reporting +- Clear mental model: `--select` means "I'll pick"; no flag means "auto-download everything new" + +### Negative + +- New runtime dependency: `questionary` (adds ~200KB installed, pulls in `prompt_toolkit`) +- Interactive-only feature: cannot be used in cron or piped contexts +- `--limit` becomes meaningless when `--select` is on (documented, not silently ignored) +- Test complexity: questionary's TUI requires mocking/patching for unit tests + +### Risks + +- **questionary abandonment**: mitigated by it being the most popular choice; thin wrapper around `prompt_toolkit`; could swap to custom Rich implementation if needed +- **Large libraries (100+ books)**: questionary's checkbox handles scrolling natively; row format is compact; fuzzy search helps narrow down +- **Terminal width**: rows are ~60-80 chars average; should fit 80-column terminals + +## Alternatives Considered + +1. **Numbered list + comma input**: Zero dependencies, works anywhere. Rejected — poor UX for 20+ books, no visual feedback, hard to correct mistakes. +2. **Per-book y/n prompts**: Simplest possible interactive mode. Rejected — unbearable for 30+ books ("Download this? [y/n]" × 30). +3. **Config-driven include/exclude lists**: `only_isbns: [...]` or `skip_titles: [...]` in config.yaml. Rejected — requires editing config before each run; defeats the purpose of "pick what I want right now." +4. **Web UI / separate selector tool**: Overengineered for a CLI-first tool. diff --git a/docs/devlog/20260604-issue22-xdg-config-path-resolution-with-cwd-fallback_log.md b/docs/devlog/20260604-issue22-xdg-config-path-resolution-with-cwd-fallback_log.md new file mode 100644 index 0000000..b872bf3 --- /dev/null +++ b/docs/devlog/20260604-issue22-xdg-config-path-resolution-with-cwd-fallback_log.md @@ -0,0 +1,63 @@ +# Issue #22: XDG config path resolution with CWD fallback + +> **Date:** 2026-06-04 +> **Type:** issue +> **Reference:** [GitHub #22](https://github.com/AlexKucera/librofm-downloader/issues/22) · Parent [#21](https://github.com/AlexKucera/librofm-downloader/issues/21) + +## Goal + +Build a path resolution engine for config files that searches `~/.config/librofm-downloader/` (XDG) first, then falls back to CWD. Wire it into `load_config()` so passing `None` for either path triggers search. Missing `config.yaml` is non-fatal (defaulted Config). Missing `secrets.yaml` is fatal (domain error listing searched paths). All OS exceptions caught internally → domain errors only. CLI should print a notice when running on built-in defaults. + +## What Was Done + +- Added `_resolve_config_file(filename)` to `config.py` — searches XDG (`~/.config/librofm-downloader/`) then CWD, auto-creates XDG dir, returns `Path | None` +- Modified `load_config()` signature to accept `Path | str | None` for both params; `None` triggers resolver +- Missing `config.yaml` path → `config_yaml = {}` (all fields get built-in defaults from `.get()` calls) +- Missing `secrets.yaml` path → raises `ConfigError` listing both searched locations in order +- All `FileNotFoundError`/`OSError` from file I/O caught and re-raised as `ConfigError` +- Added `_config_path: Path | None = None` field to `Config` dataclass — sentinel for "used defaults" +- CLI `run()` and argparse defaults changed from `"config.yaml"`/`"secrets.yaml"` to `None` so resolver activates +- CLI prints `[yellow]config.yaml not found. Using built-in defaults.[/yellow]` when `_config_path is None` +- 9 new tests across `TestResolveConfigFile` (5) and `TestLoadConfigWithResolution` (4) +- **181 total tests pass** (was 172) + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| `_config_path` private field on `Config` for defaults signal | Non-breaking: existing code ignores it, CLI can check it. Frozen dataclass prevents mutation. Alternatives: return tuple (breaks signature), raise warning (invisible). | +| `ConfigError` for missing secrets (not `FileNotFoundError`) | AC requires no OS exceptions leak to callers. Domain error lists searched paths so user knows where to put the file. | +| Missing config → empty dict, not exception | AC says non-fatal. All `Config` fields have sensible defaults via `.get()`. Credentials come from secrets only. | +| CLI defaults to `None` (not filename strings) | Original defaults of `"config.yaml"` bypassed the resolver entirely — `load_config` only searches when it receives `None`. | +| XDG dir auto-created on every resolution call | AC requires it. `mkdir(parents=True, exist_ok=True)` is idempotent and cheap. Ensures the dir exists for users to drop files into. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| `ConfigError` not imported in test file | New test class used `ConfigError` but only subclasses were imported | Added `ConfigError` to the import block | +| Test created `config/` instead of `.config/` | Test XDG path used `"config"` without leading dot, but implementation uses `.config` | Fixed test to use `tmp_path / ".config" / "librofm-downloader"` | +| `environ.get("HOME", "~").expanduser()` — `AttributeError` | Called `.expanduser()` on a `str`, not `Path` | Changed to `Path(environ.get("HOME", "~")).expanduser()` | +| `mkdir()` called after `chdir()` in test | Test ordered `monkeypatch.chdir()` before creating the CWD directory | Reordered: `mkdir()` first, then `chdir()` | +| CLI showed `Config error: Cannot read config file 'config.yaml': [Errno 2]` | CLI argparse defaults were `"config.yaml"` strings — `load_config` received a path, not `None`, so resolver never ran | Changed CLI and argparse defaults to `None` | +| Duplicate `InvalidFormatError` class + orphaned docstring | Edit operation merged old code into new location | Removed duplicate, kept single definition | +| Extra `"` in docstring → `SyntaxError` | Corrupted edit left 4 closing quotes instead of 3 | Fixed to `"""Invalid audio format value."""` | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `librofm_downloader/config.py` | Added `_resolve_config_file()`, modified `load_config()` to accept `None`, added `_config_path` field to `Config`, wrapped I/O in try/except for domain errors | +| `librofm_downloader/cli.py` | Changed `run()` and argparse defaults from `"config.yaml"`/`"secrets.yaml"` to `None`, added "using built-in defaults" notice | +| `tests/test_config.py` | Added `ConfigError` + `_resolve_config_file` imports, 9 new tests in `TestResolveConfigFile` and `TestLoadConfigWithResolution` | + +## Open Items & Next Steps + +- [ ] Update CLI `--help` text to mention XDG search behavior +- [ ] Consider adding `XDG_CONFIG_HOME` override (currently hardcoded to `~/.config`) +- [ ] Update README/docs to document XDG config location and CWD fallback +- [ ] GitNexus index needs rebuild (`npx gitnexus analyze`) after these changes + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/20260604-issue23-wire-xdg-resolution-into-cli_log.md b/docs/devlog/20260604-issue23-wire-xdg-resolution-into-cli_log.md new file mode 100644 index 0000000..50f2393 --- /dev/null +++ b/docs/devlog/20260604-issue23-wire-xdg-resolution-into-cli_log.md @@ -0,0 +1,52 @@ +# Issue #23: Wire XDG Path Resolution into CLI Layer + +> **Date:** 2026-06-04 +> **Type:** issue +> **Reference:** [GitHub #23](https://github.com/AlexKucera/librofm-downloader/issues/23) · Parent [#21](https://github.com/AlexKucera/librofm-downloader/issues/21) + +## Goal + +Wire the path resolver from Issue #22 into the CLI layer so that running `librofm-downloader` with no flags finds config/secrets/history via XDG→CWD search. History path defaults to XDG location. Missing config prints searched paths. Verbose mode shows resolved file locations. Explicit CLI flags bypass search entirely. + +## What Was Done + +- Changed `run()` parameter `history_path` default from `"download_history.json"` to `None` so the resolver activates +- Added history path resolution block in `run()`: calls `_resolve_config_file("download_history.json")` (XDG→CWD search); falls back to `~/.config/librofm-downloader/download_history.json` if not found anywhere +- Imported `_resolve_config_file` from `config.py` into `cli.py` +- Enhanced missing-config message to list searched paths: `"config.yaml not found in ~/.config/librofm-downloader/config.yaml → ./config.yaml. Using built-in defaults."` +- Added verbose resolved-paths display after config load showing `config`, `secrets`, `history` with actual resolved filesystem paths (not input args) +- Changed argparse `--history` default from `"download_history.json"` to `None` with updated help text +- 7 new tests across 3 test classes: `TestCLIHistoryResolution` (3), `TestCLIConfigResolutionMessages` (2), `TestCLIMissingFilesErrors` (2) +- **188 tests pass** (was 181 → +7 new) +- **All 10 acceptance criteria met** + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| History resolves before config load | History path is needed by `DownloadHistory.__init__()`, which happens before downloads; resolving early avoids expanding `load_config`'s responsibility | +| History defaults to XDG location (not CWD) when not found | Consistent with XDG-first resolution strategy; CWD is only a read fallback, not a default-write location | +| Verbose block moved to after config load | The actual resolved paths aren't known until after `load_config` runs and `_resolve_config_file` has been called; showing paths before resolution would display `None` | +| `_resolve_config_file` reused for history | Same XDG→CWD search logic; no need for a separate history resolver | +| Verbose re-calls `_resolve_config_file` for secrets display | At that point `secrets_path` is already consumed by `load_config`; re-resolving is cheap (two `is_file()` checks) and avoids threading the resolved path through | + +## Gotchas & Fixes + +*None* — all 7 vertical slices passed cleanly on first implementation attempt. No test failures requiring iteration. + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `librofm_downloader/cli.py` | `history_path` default → `None`; XDG resolution for history path; verbose resolved-paths display; argparse `--history` default → `None`; enhanced missing-config message with searched paths; imported `_resolve_config_file` | +| `tests/test_cli.py` | 7 new tests: `TestCLIHistoryResolution` (3), `TestCLIConfigResolutionMessages` (2), `TestCLIMissingFilesErrors` (2) | + +## Open Items & Next Steps + +- [ ] Update CLI `--help` text to mention XDG search behavior for `--history` +- [ ] Update README/docs to document XDG config location and history defaults +- [ ] GitNexus index needs rebuild (`npx gitnexus analyze`) after these changes + +--- + +*Log written by write-log skill* diff --git a/docs/html/cli-usage.html b/docs/html/cli-usage.html index b8c3009..e9ccedf 100644 --- a/docs/html/cli-usage.html +++ b/docs/html/cli-usage.html @@ -1223,20 +1223,20 @@
--configconfig.yamlconfig.yamlconfig.yaml (overrides default search)--secretssecrets.yamlsecrets.yamlsecrets.yaml (overrides default search)--historydownload_history.json-v, --verboseShows internal pipeline state at each stage:
── config ──────────────────────────────────────
- config: config.yaml
- secrets: secrets.yaml
- history: download_history.json
+ config: ~/.config/librofm-downloader/config.yaml
+ secrets: ~/.config/librofm-downloader/secrets.yaml
+ history: ~/.config/librofm-downloader/download_history.json
format: m4b_mp3_fallback
output: ./audiobooks
extras: True
diff --git a/docs/html/configuration.html b/docs/html/configuration.html
index d5eda01..cd21052 100644
--- a/docs/html/configuration.html
+++ b/docs/html/configuration.html
@@ -523,14 +523,42 @@
-
-
+
- File locations
+ Default file locations
+
+
-
@@ -857,14 +885,42 @@
-
-
+
- File locations
+ Default file locations
+
+
-
@@ -971,12 +1027,52 @@
Configuration Reference
-Complete reference for config.yaml and secrets.yaml.
-File locations
-The CLI looks for these files in the current working directory by default:
-librofm-downloader --config config.yaml --secrets secrets.yaml
+Complete reference for config.yaml, secrets.yaml, and download history.
+Default file locations
+When no --config, --secrets, or --history flags are provided, the tool searches for each file in this order:
+
+- XDG directory —
~/.config/librofm-downloader/
+- Current working directory (CWD)
+
+The XDG directory is created automatically on first run if it doesn't exist. This means you can drop your files into ~/.config/librofm-downloader/ and run librofm-downloader from any directory.
+~/.config/librofm-downloader/
+├── config.yaml # optional — built-in defaults used if missing
+├── secrets.yaml # required — tool exits with an error if missing
+└── download_history.json # created automatically on first download
-Both files share the same top-level key: librofm.
+Missing files: config vs secrets
+The two config files have different missing-file behavior:
+
+
+
+File
+If missing
+Behavior
+
+
+
+
+config.yaml
+Non-fatal
+Tool runs with built-in defaults (m4b_mp3_fallback, ./audiobooks, etc.). A notice is printed listing searched paths.
+
+
+secrets.yaml
+Fatal
+Tool exits with code 1 and an error listing both searched locations so you know where to create it.
+
+
+
+Overriding with CLI flags
+Use --config, --secrets, and --history to bypass the XDG→CWD search entirely and point at specific files:
+# Use files in a custom location
+librofm-downloader --config /path/to/config.yaml --secrets /path/to/secrets.yaml
+
+# Custom history file
+librofm-downloader --history /path/to/download_history.json
+
+When a flag is provided, that path is used directly — no search is performed.
+Both config files share the same top-level key: librofm.
secrets.yaml
Credentials only. This file must not be committed to version control.
@@ -1003,9 +1099,9 @@
-librofm:
- username: your-email@example.com
- password: your-password
+
[!IMPORTANT]
@@ -1013,7 +1109,7 @@ Only username and password belong in this file. All ot
If either field is missing, the tool exits with code 1 and an error message.
config.yaml
-All non-credential settings. Safe to commit.
+All non-credential settings. Safe to commit. Optional — if missing, built-in defaults are used.
@@ -1057,18 +1153,18 @@ If either field is missing, the tool exits with code 1 and an e
Full example
-librofm:
- format: m4b_mp3_fallback
- output_dir: ./audiobooks
- download_extras: true
- download_covers: true
- workers: 3
+librofm:
+ format: m4b_mp3_fallback
+ output_dir: ./audiobooks
+ download_extras: true
+ download_covers: true
+ workers: 3
Minimal example
Only format is meaningful here — everything else has a default:
-librofm:
- format: mp3_only
- workers: 5 # high-bandwidth connection
+
How merging works
config.yaml and secrets.yaml are deep-merged at startup:
@@ -1078,8 +1174,8 @@ If either field is missing, the tool exits with code 1 and an e
- The merged result is validated
This means you could theoretically put any field in either file — but credentials in config.yaml are explicitly rejected at load time with a clear error:
-Config error: Credentials (username, password) found in config.yaml.
-Move them to secrets.yaml (which is gitignored).
+Config error: Credentials (username, password) found in config.yaml.
+Move them to secrets.yaml (which is gitignored).
Validation errors
@@ -1107,6 +1203,16 @@ If either field is missing, the tool exits with code 1 and an e
Use one of: m4b_mp3_fallback, mp3_only, m4b_only
+config.yaml not found in ~/.config/.../config.yaml → ./config.yaml. Using built-in defaults.
+No config file in either location
+Non-fatal — defaults used. Create config.yaml to customize.
+
+
+Missing secrets.yaml. Searched: ~/.config/.../secrets.yaml → ./secrets.yaml.
+No secrets file in either location
+Create secrets.yaml with your credentials in one of the searched locations.
+
+
Invalid workers value: 0
Workers < 1
Set workers to an integer ≥ 1
@@ -1114,21 +1220,23 @@ If either field is missing, the tool exits with code 1 and an e
Download history
-A third file, download_history.json, is created automatically on first run:
-{
- "9780743565400": {
- "isbn": "9780743565400",
- "title": "The Way of Kings",
- "format": "m4b",
- "path": "./audiobooks/Brandon Sanderson/The Way of Kings/The Way of Kings.m4b",
- "downloaded_at": "2026-06-03T10:30:00+00:00"
- }
-}
+A third file, download_history.json, tracks what's been downloaded. It follows the same XDG→CWD search order as the config files, and defaults to the XDG directory when not found anywhere:
+
+The file is created automatically on first download. Override with --history to use a custom location.
+{
+ "9780743565400": {
+ "isbn": "9780743565400",
+ "title": "The Way of Kings",
+ "format": "m4b",
+ "path": "./audiobooks/Brandon Sanderson/The Way of Kings/The Way of Kings.m4b",
+ "downloaded_at": "2026-06-03T10:30:00+00:00"
+ }
+}
- Keyed by ISBN — each book is recorded once
- Used to skip already-downloaded books on subsequent runs
-- Location defaults to
download_history.json in CWD; override with --history
- If the file is corrupt or missing, the tool starts with an empty history (and logs a warning)
diff --git a/docs/html/quickstart.html b/docs/html/quickstart.html
index cd80eab..25d17c9 100644
--- a/docs/html/quickstart.html
+++ b/docs/html/quickstart.html
@@ -1120,12 +1120,13 @@
The [dev] extra installs pytest for testing — omit it if you only want to run the tool.
2. Configure
-librofm-downloader uses two YAML files:
+librofm-downloader uses two YAML files, searched in ~/.config/librofm-downloader/ first, then the current working directory:
File
Purpose
+Required?
Committed to git?
@@ -1133,15 +1134,22 @@
config.yaml
Preferences (format, output dir, toggles)
+No (defaults used)
✅ Yes
secrets.yaml
Credentials only
+Yes
❌ No (gitignored)
+
+[!TIP]
+The XDG directory (~/.config/librofm-downloader/) is created automatically on first run.
+Place both files there to run librofm-downloader from any directory.
+
config.yaml
# libro.fm downloader configuration
# This file is safe to commit — no credentials here.
@@ -1179,10 +1187,11 @@ If you accidentally put credentials in config.yaml, the tool will r
This:
-- Loads
config.yaml + secrets.yaml
+- Searches for
config.yaml + secrets.yaml (XDG directory first, then CWD)
- Authenticates with Libro.fm via OAuth2 password grant
- Fetches your full library (all pages)
-- Skips books already in
download_history.json
+- Skips books already in
download_history.json (XDG → CWD search)
+- Downloads each new book with a progress bar
- Downloads each new book (3 parallel workers by default) with a progress bar
- Records successful downloads to history
diff --git a/docs/html/search/search_index.json b/docs/html/search/search_index.json
index 6b8b93d..87b6ad0 100644
--- a/docs/html/search/search_index.json
+++ b/docs/html/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"index.html","title":"librofm-downloader","text":"Download owned audiobooks from your Libro.fm account \u2014 a lightweight, dependency-minimal CLI tool written in Python.
No Docker. No JVM. Just pip install and go.
"},{"location":"index.html#features","title":"Features","text":" - Full library sync \u2014 fetches every audiobook in your Libro.fm account with automatic pagination
- M4B + MP3 formats \u2014 downloads M4B (single file) or MP3 (ZIP parts extracted) with automatic fallback
- Resume support \u2014 interrupted downloads pick up where they left off via
.partial files - Cover art & PDF extras \u2014 optional download of cover images and accompanying PDFs
- Customizable output paths \u2014 token-based patterns for organizing your library on disk
- TTY-aware progress \u2014 rich progress bars in your terminal, clean log lines in cron jobs
- Download history \u2014 tracks what's been downloaded so re-runs only fetch new books
- Graceful failure isolation \u2014 one failed book doesn't stop the rest
"},{"location":"index.html#quick-start","title":"Quick Start","text":"# 1. Install\npip install librofm-downloader\n\n# 2. Configure\ncat > config.yaml << 'EOF'\nlibrofm:\n format: m4b_mp3_fallback\n output_dir: ./audiobooks\n download_extras: true\n download_covers: true\nEOF\n\ncat > secrets.yaml << 'EOF'\nlibrofm:\n username: your-email@example.com\n password: your-password\nEOF\n\n# 3. Run\nlibrofm-downloader\n
See Quickstart for the full walkthrough, or jump to Configuration Reference for every option.
"},{"location":"cli-usage.html","title":"CLI Usage","text":"Command-line interface reference for librofm-downloader.
"},{"location":"cli-usage.html#synopsis","title":"Synopsis","text":"librofm-downloader [OPTIONS]\n
"},{"location":"cli-usage.html#options","title":"Options","text":"Option Short Default Description --config config.yaml Path to config.yaml --secrets secrets.yaml Path to secrets.yaml --history download_history.json Path to download history JSON file -v, --verbose off Print extra detail (URLs, paths, API responses) --limit N 0 (no limit) Maximum number of books to download -w, --workers N 3 Number of parallel download workers (1 = sequential)"},{"location":"cli-usage.html#-verbose","title":"--verbose","text":"Shows internal pipeline state at each stage:
\u2500\u2500 config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n config: config.yaml\n secrets: secrets.yaml\n history: download_history.json\n format: m4b_mp3_fallback\n output: ./audiobooks\n extras: True\n covers: True\n user: me@example.com\n\u2500\u2500 auth \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n \u2713 authenticated\n\u2500\u2500 library \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n 47 book(s) in library\n\u2500\u2500 filtering \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n 42 already downloaded, 5 new\n \u2b07 Book Title [dim](9780743565400)[/dim]\n authors: Brandon Sanderson\n narrators: Kate Reading, Michael Kramer\n ...\n 123,456,789 bytes\n
"},{"location":"cli-usage.html#-limit","title":"--limit","text":"Cap how many books are downloaded in a single run. Useful for testing:
# Download only 1 book (the first new one)\nlibrofm-downloader --limit 1\n\n# Download up to 3 books\nlibrofm-downloader --limit 3 -v\n
Books are processed in the order returned by the Libro.fm API. Already-downloaded books are filtered out before the limit is applied.
"},{"location":"cli-usage.html#-workers","title":"--workers","text":"Controls how many books download simultaneously:
# Default: 3 parallel downloads\nlibrofm-downloader\n\n# High-bandwidth connection: 5 workers\nlibrofm-downloader -w 5\n\n# Force sequential (useful for debugging)\nlibrofm-downloader --workers 1\n
Resolution order (CLI > config > default):
--workers N / -w N on the command line workers: field in config.yaml - Default: 3
[!NOTE] The worker count controls CDN download parallelism. Libro.fm API calls are separately capped at 3 concurrent requests via an internal semaphore, regardless of worker count. This protects the API server while letting CDN transfers scale up.
Set to 1 for behavior identical to the pre-parallelism sequential mode.
"},{"location":"cli-usage.html#exit-codes","title":"Exit codes","text":"Code Meaning 0 Success \u2014 all done (including \"nothing new to download\") 1 Fatal error \u2014 config problem, auth failure, or library fetch failure 130 Interrupted \u2014 user pressed Ctrl+C during downloads"},{"location":"cli-usage.html#exit-code-0-scenarios","title":"Exit code 0 scenarios","text":" - All new books downloaded successfully
- No new books to download (
All caught up!) - Some books failed but the pipeline completed (failures are reported in the summary)
[!NOTE] Exit code 0 does not mean \"zero failures\" \u2014 it means the process ran to completion. Check the summary line for failed count.
"},{"location":"cli-usage.html#exit-code-1-scenarios","title":"Exit code 1 scenarios","text":"# Config error\n$ librofm-downloader --config missing.yaml\nConfig error: [Errno 2] No such file or directory: 'missing.yaml'\n\n# Auth failure\n$ librofm-downloader\nAuthentication failed: Auth failed (401)\n\n# Library fetch failure\n$ librofm-downloader\nFailed to fetch library: 502 Bad Gateway\n
"},{"location":"cli-usage.html#exit-code-130","title":"Exit code 130","text":"$ librofm-downloader\n^CDownload interrupted by user (Ctrl+C).\necho $?\n130\n
Partial downloads are preserved as .partial files and will be resumed on the next run.
"},{"location":"cli-usage.html#cron-setup","title":"Cron setup","text":""},{"location":"cli-usage.html#basic-daily-sync","title":"Basic daily sync","text":"# m h dom mon dow command\n0 4 * * * cd /path/to/librofm-downloader && .venv/bin/librofm-downloader >> /var/log/librofm.log 2>&1\n
Runs every day at 4:00 AM, appends output to a log file.
"},{"location":"cli-usage.html#with-email-on-failure","title":"With email on failure","text":"0 4 * * * cd /path/to/librofm-downloader && .venv/bin/librofm-downloader || echo \"librofm-downloader failed\" | mail -s \"DL failure\" you@example.com\n
"},{"location":"cli-usage.html#weekly-with-limit","title":"Weekly with limit","text":"0 3 * * 1 cd /path/to/librofm-downloader && .venv/bin/librofm-downloader --limit 10 >> /var/log/librofm-weekly.log 2>&1\n
Runs Mondays at 3:00 AM, caps at 10 books.
"},{"location":"cli-usage.html#systemd-timer-alternative-to-cron","title":"systemd timer (alternative to cron)","text":"# /etc/systemd/system/librofm-downloader.service\n[Unit]\nDescription=Libro.fm Audiobook Downloader\nAfter=network-online.target\n\n[Service]\nType=oneshot\nWorkingDirectory=/path/to/librofm-downloader\nExecStart=/path/to/librofm-downloader/.venv/bin/librofm-downloader\n\n# /etc/systemd/system/librofm-downloader.timer\n[Unit]\nDescription=Run librofm-downloader daily\n\n[Timer]\nOnCalendar=daily\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n
systemctl enable --now librofm-downloader.timer\njournalctl -u librofm-downloader -f\n
"},{"location":"cli-usage.html#tty-vs-non-tty-output","title":"TTY vs non-TTY output","text":"The tool auto-detects whether stdout is a terminal:
"},{"location":"cli-usage.html#tty-interactive-terminal","title":"TTY (interactive terminal)","text":" - Rich progress bars with percentage, transfer speed, ETA, and size
- Color-coded results (\u2713 green, \u2717 red, \u23ed yellow)
- Progress bars update in-place (no scrolling flood)
Brandon Sanderson - The Way of Kings \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 67.3% 2.1 MB/s 00:03 45.2 MB\n
"},{"location":"cli-usage.html#non-tty-cron-pipe-redirect","title":"Non-TTY (cron, pipe, redirect)","text":" - Plain text log lines \u2014 one per event
- No color, no progress bar updates
- Same information, machine-friendly format
Downloading: Brandon Sanderson - The Way of Kings (unknown size)\nCompleted: Brandon Sanderson - The Way of Kings\nSummary: 1 downloaded, 0 skipped, 0 failed\n
This means you get nice progress in your terminal and clean logs in cron \u2014 no flags needed.
"},{"location":"configuration.html","title":"Configuration Reference","text":"Complete reference for config.yaml and secrets.yaml.
"},{"location":"configuration.html#file-locations","title":"File locations","text":"The CLI looks for these files in the current working directory by default:
librofm-downloader --config config.yaml --secrets secrets.yaml\n
Both files share the same top-level key: librofm.
"},{"location":"configuration.html#secretsyaml","title":"secrets.yaml","text":"Credentials only. This file must not be committed to version control.
Field Type Required Description username string \u2705 Your Libro.fm account email password string \u2705 Your Libro.fm password librofm:\n username: your-email@example.com\n password: your-password\n
[!IMPORTANT] Only username and password belong in this file. All other settings go in config.yaml. If either field is missing, the tool exits with code 1 and an error message.
"},{"location":"configuration.html#configyaml","title":"config.yaml","text":"All non-credential settings. Safe to commit.
Field Type Default Description format string \"m4b_mp3_fallback\" Audio download strategy. See Format Strategies. output_dir string \"./audiobooks\" Base directory for downloaded files. Relative paths resolve from CWD. download_extras boolean true Download PDF extras (e.g., maps) when available. download_covers boolean true Download cover art (JPEG/PNG) when available. workers integer 3 Number of parallel download threads. Set to 1 for sequential mode. Must be \u2265 1."},{"location":"configuration.html#full-example","title":"Full example","text":"librofm:\n format: m4b_mp3_fallback\n output_dir: ./audiobooks\n download_extras: true\n download_covers: true\n workers: 3\n
"},{"location":"configuration.html#minimal-example","title":"Minimal example","text":"Only format is meaningful here \u2014 everything else has a default:
librofm:\n format: mp3_only\n workers: 5 # high-bandwidth connection\n
"},{"location":"configuration.html#how-merging-works","title":"How merging works","text":"config.yaml and secrets.yaml are deep-merged at startup:
config.yaml is loaded as the base secrets.yaml is layered on top (overrides on conflict) - The merged result is validated
This means you could theoretically put any field in either file \u2014 but credentials in config.yaml are explicitly rejected at load time with a clear error:
Config error: Credentials (username, password) found in config.yaml.\nMove them to secrets.yaml (which is gitignored).\n
"},{"location":"configuration.html#validation-errors","title":"Validation errors","text":"Error Cause Fix Config error: Credentials (...) found in config.yaml Username or password in config file Move to secrets.yaml Missing required fields in secrets.yaml: username Missing credential field Add it to secrets.yaml Invalid format 'foo' Unknown format value Use one of: m4b_mp3_fallback, mp3_only, m4b_only Invalid workers value: 0 Workers < 1 Set workers to an integer \u2265 1"},{"location":"configuration.html#download-history","title":"Download history","text":"A third file, download_history.json, is created automatically on first run:
{\n \"9780743565400\": {\n \"isbn\": \"9780743565400\",\n \"title\": \"The Way of Kings\",\n \"format\": \"m4b\",\n \"path\": \"./audiobooks/Brandon Sanderson/The Way of Kings/The Way of Kings.m4b\",\n \"downloaded_at\": \"2026-06-03T10:30:00+00:00\"\n }\n}\n
- Keyed by ISBN \u2014 each book is recorded once
- Used to skip already-downloaded books on subsequent runs
- Location defaults to
download_history.json in CWD; override with --history - If the file is corrupt or missing, the tool starts with an empty history (and logs a warning)
"},{"location":"format-strategies.html","title":"Format Strategies","text":"librofm-downloader supports three audio format strategies, controlled by the format field in config.yaml.
"},{"location":"format-strategies.html#overview","title":"Overview","text":"Strategy Behavior Best for m4b_mp3_fallback Try M4B first; fall back to MP3 if unavailable Default \u2014 maximum compatibility mp3_only Download MP3 ZIP only (skip M4B entirely) Players that don't support M4B m4b_only Download M4B only; skip book if unavailable Audiobook apps that prefer M4B"},{"location":"format-strategies.html#m4b_mp3_fallback-default","title":"m4b_mp3_fallback (default)","text":"The recommended strategy for most users.
librofm:\n format: m4b_mp3_fallback\n
Flow:
- Request the M4B download URL from Libro.fm API
- If available \u2192 download as a single
.m4b file - If the API returns 404 \u2192 fall back to fetching the MP3 manifest
- Download all MP3 ZIP parts and extract them
What you get:
- Most books: one
.m4b file (AAC/ALAC audio, bookmarkable, chapter markers) - Older or region-locked books: extracted MP3 files (one or more per book)
- No books are skipped \u2014 every downloadable title is fetched in some format
Output examples:
# M4B succeeded\naudiobooks/Brandon Sanderson/The Way of Kings.m4b # single file, ~450 MB\n\n# Fell back to MP3\naudiobooks/Some Author/Old Book/ # directory with MP3s\n\u251c\u2500\u2500 part1.mp3\n\u251c\u2500\u2500 part2.mp3\n\u2514\u2500\u2500 part3.mp3\n
"},{"location":"format-strategies.html#mp3_only","title":"mp3_only","text":"Skip M4B entirely and always use the MP3 ZIP pipeline.
librofm:\n format: mp3_only\n
Flow:
- Fetch the MP3 download manifest from Libro.fm API
- Download each ZIP part listed in the manifest
- Extract all files into the output directory
When to use this:
- Your media player doesn't support M4B/M4A containers
- You want raw MP3 files for editing or conversion
- You're feeding files into a system that only accepts MP3
Output: Always a directory with extracted MP3 files:
audiobooks/Brandon Sanderson/The Way of Kings/\n\u251c\u2500\u2500 part1.mp3\n\u251c\u2500\u2500 part2.mp3\n\u2514\u2500\u2500 ...\n
"},{"location":"format-strategies.html#m4b_only","title":"m4b_only","text":"Only attempt M4B download. Skip books where M4B is not available.
librofm:\n format: m4b_only\n
Flow:
- Request the M4B download URL from Libro.fm API
- If available \u2192 download as a single
.m4b file - If the API returns 404 \u2192 log a skip message, move to next book
When to use this:
- You only want single-file audiobooks (cleaner library management)
- Your audiobook app (Apple Books, etc.) handles M4B natively
- You'd rather miss a book than get split MP3 files
Output example:
# Success\naudiobooks/Brandon Sanderson/The Way of Kings.m4b\n\n# Skipped (shows in summary)\nSummary: 5 downloaded, 2 skipped, 0 failed\n Skipped:\n \u23ed Some Author - Old Book [9781234567890]\n
"},{"location":"format-strategies.html#how-to-choose","title":"How to choose","text":"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u2502\n\u2502 Want every book? \u2502 \u2192 m4b_mp3_fallback (default) \u2502\n\u2502 Only need MP3? \u2502 \u2192 mp3_only \u2502\n\u2502 Single-file or nothing? \u2502 \u2192 m4b_only \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n
"},{"location":"format-strategies.html#technical-details","title":"Technical details","text":""},{"location":"format-strategies.html#m4b-downloads","title":"M4B downloads","text":" - Single HTTP stream with 8 MB chunk buffering
- Written to
{title}.m4b.partial during transfer - Atomic rename to final
.m4b on completion - Supports resume: if a
.partial file exists, sends Range header to continue - Progress reporting via
Content-Length header (% complete, speed, ETA)
"},{"location":"format-strategies.html#mp3-downloads","title":"MP3 downloads","text":" - Fetches a manifest (
/api/v10/download-manifest?isbn=...) listing ZIP part URLs - Each part is downloaded as a
.zip.partial file, then renamed to .zip - ZIP contents are extracted into the output directory
- The ZIP file is deleted after extraction
- Each part supports resume via
Range headers - Parts are downloaded sequentially within each book
"},{"location":"path-patterns.html","title":"Path Patterns","text":"How librofm-downloader organizes files on disk, and how to customize the layout with tokens.
"},{"location":"path-patterns.html#default-behavior","title":"Default behavior","text":"When no custom pattern is set, the output path is determined by conditional logic based on whether a book belongs to a series:
"},{"location":"path-patterns.html#standalone-book-no-series","title":"Standalone book (no series)","text":"{FIRST_AUTHOR}/{BOOK_TITLE}\n
Example: Brandon Sanderson/The Way of Kings.m4b
"},{"location":"path-patterns.html#book-in-a-series-with-series-number","title":"Book in a series (with series number)","text":"{FIRST_AUTHOR}/{SERIES_NAME}/Book {SERIES_NUM} {BOOK_TITLE}\n
Example: Brandon Sanderson/Stormlight Archive/Book 1 The Way of Kings.m4b
"},{"location":"path-patterns.html#book-in-a-series-no-series-number","title":"Book in a series (no series number)","text":"{FIRST_AUTHOR}/{SERIES_NAME}/{BOOK_TITLE}\n
Example: J.K. Rowling/Harry Potter/Harry Potter and the Sorcerer's Stone.m4b
"},{"location":"path-patterns.html#subdirectory-logic","title":"Subdirectory logic","text":"A book gets its own subdirectory when any of these are true:
- The book has PDF extras available (
pdf_extras: true) download_covers: true and the book has a cover URL
Otherwise the audio file sits directly under the author directory as a flat file.
"},{"location":"path-patterns.html#available-tokens","title":"Available tokens","text":"Use these inside {TOKEN} placeholders in a custom pattern:
Token Source Example value Notes {FIRST_AUTHOR} First item in authors list Brandon Sanderson Empty if no authors {ALL_AUTHORS} Authors joined by , Sanderson, Brandon Empty if no authors {SERIES_NAME} Series name Stormlight Archive Empty string if not in a series {SERIES_NUM} Series position integer 1 Empty if not in a series or no number {BOOK_TITLE} Book title The Way of Kings Sanitized for filesystem safety {ISBN} ISBN identifier 9780743565400 As returned by the API {FIRST_NARRATOR} First narrator Kate Reading Empty if no narrators {ALL_NARRATORS} Narrators joined by , Kate Reading, Michael Kramer Empty if no narrators {PUBLICATION_YEAR} Year published 2024 Empty if unknown {PUBLICATION_MONTH} Month published 8 Empty if unknown {PUBLICATION_DAY} Day published 15 Empty if unknown"},{"location":"path-patterns.html#custom-patterns","title":"Custom patterns","text":"To override the default conditional logic, set a path_pattern key in your config:
librofm:\n format: m4b_mp3_fallback\n output_dir: ./audiobooks\n path_pattern: \"{PUBLICATION_YEAR}/{FIRST_AUTHOR} - {BOOK_TITLE}\"\n
This would produce paths like:
./audiobooks/2024/Brandon Sanderson - The Way of Kings.m4b\n./audiobooks/2023/Suzanne Collins - The Hunger Games.m4b\n
[!NOTE] Custom patterns are applied via regex substitution ({TOKEN_NAME} \u2192 value). Unknown tokens resolve to empty strings \u2014 no error is raised. Each path component is sanitized (colons replaced, illegal chars stripped, capped at 255 chars).
"},{"location":"path-patterns.html#pattern-examples","title":"Pattern examples","text":""},{"location":"path-patterns.html#flat-by-author","title":"Flat by author","text":"path_pattern: \"{ALL_AUTHORS}/{BOOK_TITLE}\"\n
Output:
audiobooks/Sanderson, Brandon/The Way of Kings.m4b\naudiobooks/Collins, Suzanne/The Hunger Games.m4b\n
"},{"location":"path-patterns.html#organized-by-series","title":"Organized by series","text":"path_pattern: \"{FIRST_AUTHOR}/{SERIES_NAME}/{SERIES_NUM:03d} - {BOOK_TITLE}\"\n
Output:
audiobooks/Brandon Sanderson/Stormlight Archive/001 - The Way of Kings.m4b\naudiobooks/Brandon Sanderson/Mistborn/001 - The Final Empire.m4b\n
[!WARNING] Python format specs like :03d are not supported \u2014 tokens produce plain strings only. Use {SERIES_NUM} directly; it will render as 1, 2, etc.
"},{"location":"path-patterns.html#by-narrator","title":"By narrator","text":"path_pattern: \"{FIRST_NARRATOR}/{BOOK_TITLE}\"\n
Output:
audiobooks/Kate Reading/The Way of Kings.m4b\n
"},{"location":"path-patterns.html#iso-style-date-prefix","title":"ISO-style date prefix","text":"path_pattern: \"{PUBLICATION_YEAR}-{PUBLICATION_MONTH}-{PUBLICATION_DAY}/{FIRST_AUTHOR}/{BOOK_TITLE}\"\n
Output:
audiobooks/2024-8-15/Brandon Sanderson/The Way of Kings.m4b\n
"},{"location":"path-patterns.html#path-sanitization","title":"Path sanitization","text":"Every path component goes through sanitization before being written to disk:
- Colons (
:) \u2192 replaced with - - Illegal characters
< > / \\ | ? * \u2192 stripped - Control characters (U+0000\u2013U+001F) \u2192 stripped
- Trailing dots \u2192 removed
- Whitespace \u2192 trimmed
- Length \u2192 capped at 255 characters
Preserved characters include dashes, commas, apostrophes, parentheses, and non-trailing periods.
"},{"location":"quickstart.html","title":"Quickstart","text":"Get librofm-downloader installed, configured, and running in three steps.
"},{"location":"quickstart.html#1-install","title":"1. Install","text":""},{"location":"quickstart.html#from-pypi-recommended","title":"From PyPI (recommended)","text":"pip install librofm-downloader\n
Requires Python 3.11+.
"},{"location":"quickstart.html#from-source","title":"From source","text":"git clone https://github.com/AlexKucera/librofm-downloader.git\ncd librofm-downloader\npython -m venv .venv\nsource .venv/bin/activate # or .venv\\Scripts\\activate on Windows\npip install -e \".[dev]\"\n
The [dev] extra installs pytest for testing \u2014 omit it if you only want to run the tool.
"},{"location":"quickstart.html#2-configure","title":"2. Configure","text":"librofm-downloader uses two YAML files:
File Purpose Committed to git? config.yaml Preferences (format, output dir, toggles) \u2705 Yes secrets.yaml Credentials only \u274c No (gitignored)"},{"location":"quickstart.html#configyaml","title":"config.yaml","text":"# libro.fm downloader configuration\n# This file is safe to commit \u2014 no credentials here.\n# Credentials go in secrets.yaml (which is gitignored).\n\nlibrofm:\n # Audio format preference:\n # m4b_mp3_fallback \u2014 try M4B first, fall back to MP3 ZIP (default)\n # mp3_only \u2014 download MP3 ZIP only\n # m4b_only \u2014 download M4B only, skip if unavailable\n format: m4b_mp3_fallback\n\n # Where downloaded audiobooks are saved\n output_dir: ./audiobooks\n\n # Whether to download PDF extras when available\n download_extras: true\n\n # Whether to download cover art when available\n download_covers: true\n
"},{"location":"quickstart.html#secretsyaml","title":"secrets.yaml","text":"librofm:\n username: your-email@example.com\n password: your-password\n
[!WARNING] Never commit secrets.yaml. It is listed in .gitignore by default. If you accidentally put credentials in config.yaml, the tool will refuse to start and tell you to move them.
"},{"location":"quickstart.html#3-run","title":"3. Run","text":""},{"location":"quickstart.html#basic-sync","title":"Basic sync","text":"librofm-downloader\n
This:
- Loads
config.yaml + secrets.yaml - Authenticates with Libro.fm via OAuth2 password grant
- Fetches your full library (all pages)
- Skips books already in
download_history.json - Downloads each new book (3 parallel workers by default) with a progress bar
- Records successful downloads to history
"},{"location":"quickstart.html#first-run-output-tty","title":"First run output (TTY)","text":"3 book(s) to download:\n\nAuthor One - Book Title One \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 100.0% 2.1 MB/s 00:01 45.2 MB\n \u2713 Book Title One\nAuthor Two - Another Book \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 100.0% 1.8 MB/s 00:02 120.5 MB\n \u2713 Another Book\nAuthor Three - Third Book \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 100.0% 2.3 MB/s 00:00 89.1 MB\n \u2713 Third Book\n\nSummary: 3 downloaded, 0 skipped, 0 failed\n
"},{"location":"quickstart.html#subsequent-run-nothing-new","title":"Subsequent run (nothing new)","text":"All caught up! No new books to download.\n
"},{"location":"quickstart.html#cron-non-tty-output","title":"Cron / non-TTY output","text":"When stdout is not a terminal (e.g., cron, piped), output switches to plain text log lines:
Downloading: Author One - Book Title One (unknown size)\nCompleted: Author One - Book Title One\nDownloading: Author Two - Another Book (unknown size)\nCompleted: Author Two - Another Book\n\nSummary: 2 downloaded, 0 skipped, 0 failed\n
"},{"location":"quickstart.html#what-gets-downloaded","title":"What gets downloaded?","text":"Files land under your output_dir using this structure:
audiobooks/\n\u251c\u2500\u2500 Brandon Sanderson/\n\u2502 \u251c\u2500\u2500 The Way of Kings/\n\u2502 \u2502 \u251c\u2500\u2500 The Way of Kings.m4b\n\u2502 \u2502 \u251c\u2500\u2500 cover.jpg\n\u2502 \u2502 \u2514\u2500\u2500 map.pdf\n\u2502 \u2514\u2500\u2500 Words of Radiance.m4b \u2190 no extras = flat file\n\u2514\u2500\u2500 Suzanne Collins/\n \u2514\u2500\u2500 The Hunger Games.m4b\n
- Books with cover art or PDF extras get a subdirectory (
Author/Title/) - Books without extras are flat files (
Author/Title.m4b) - See Path Patterns for customization options
"},{"location":"quickstart.html#next-steps","title":"Next steps","text":" - Configuration Reference \u2014 every field documented
- Format Strategies \u2014 choose the right mode for your setup
- CLI Usage \u2014 all flags, exit codes, cron examples
- Troubleshooting \u2014 common problems and solutions
"},{"location":"secrets.html","title":"Secrets","text":"Why secrets.yaml exists, how it works, and common mistakes to avoid.
"},{"location":"secrets.html#purpose","title":"Purpose","text":"Libro.fm authentication requires your email and password. These are stored in a separate file from your regular configuration so you can safely commit config.yaml to version control without leaking credentials.
"},{"location":"secrets.html#file-format","title":"File format","text":"librofm:\n username: your-email@example.com\n password: your-password\n
Two fields, both required, both strings. That's it.
"},{"location":"secrets.html#why-its-gitignored","title":"Why it's gitignored","text":"The .gitignore entry:
secrets.yaml\n
This is set up by default in the project template. If you clone the repo and create secrets.yaml, Git will never track it.
"},{"location":"secrets.html#common-mistakes","title":"Common mistakes","text":""},{"location":"secrets.html#1-putting-credentials-in-configyaml","title":"1. Putting credentials in config.yaml","text":"If you accidentally add username or password to config.yaml:
# \u274c Wrong \u2014 config.yaml\nlibrofm:\n username: me@example.com # <-- this will be rejected\n password: secret # <-- this will be rejected\n format: m4b_mp3_fallback\n
The tool refuses to start:
Config error: Credentials (username, password) found in config.yaml.\nMove them to secrets.yaml (which is gitignored).\n
Fix: Remove those lines from config.yaml and put them in secrets.yaml.
"},{"location":"secrets.html#2-committing-before-gitignore","title":"2. Committing before gitignore","text":"If you git add secrets.yaml before the .gitignore rule was added, Git may already be tracking it:
# Check if Git is tracking it\ngit ls-files | grep secrets.yaml\n\n# If it shows up, remove it from tracking (keeps local file)\ngit rm --cached secrets.yaml\ngit commit -m \"Stop tracking secrets.yaml\"\n
"},{"location":"secrets.html#3-missing-fields","title":"3. Missing fields","text":"If secrets.yaml exists but is missing username or password:
Missing required fields in secrets.yaml: username, password.\nAdd them to your secrets.yaml file.\n
Both fields are required \u2014 there are no defaults for credentials.
"},{"location":"secrets.html#4-wrong-indentation","title":"4. Wrong indentation","text":"YAML is whitespace-sensitive. The librofm: key must be at column 0, and username/password must be indented with exactly 2 spaces:
# \u2705 Correct\nlibrofm:\n username: me@example.com\n password: secret\n\n# \u274c Wrong \u2014 no indentation\nlibrofm:\nusername: me@example.com\npassword: secret\n\n# \u274c Wrong \u2014 wrong key name (not under librofm:)\nusername: me@example.com\npassword: secret\n
"},{"location":"secrets.html#security-notes","title":"Security notes","text":" - The password is stored in plaintext on disk \u2014 this is a CLI tool for personal use, not a multi-user service
- The password is sent to Libro.fm's OAuth2 token endpoint over HTTPS; it is never logged or transmitted elsewhere
- If your Libro.fm account has 2FA enabled, you may need an app-specific password depending on how Libro.fm handles OAuth2 password grants
- Never share your
secrets.yaml file \u2014 if you do, rotate your Libro.fm password immediately
"},{"location":"troubleshooting.html","title":"Troubleshooting","text":"Common errors, their causes, and how to fix them.
"},{"location":"troubleshooting.html#authentication-failures","title":"Authentication failures","text":""},{"location":"troubleshooting.html#authentication-failed-auth-failed-401","title":"\"Authentication failed: Auth failed (401)\"","text":"Cause: Wrong email or password in secrets.yaml.
Fix:
- Verify you can log in to libro.fm in a browser with the same credentials
- Check for typos in
secrets.yaml (YAML is case-sensitive) - If you changed your Libro.fm password recently, update
secrets.yaml
"},{"location":"troubleshooting.html#authentication-failed-auth-failed-xxx-non-401","title":"\"Authentication failed: Auth failed (xxx)\" (non-401)","text":"Cause: Network issue or Libro.fm API temporarily down.
Fix:
- Check your internet connection
- Try again in a few minutes
- Check Libro.fm status if available
"},{"location":"troubleshooting.html#configuration-errors","title":"Configuration errors","text":""},{"location":"troubleshooting.html#config-error-credentials-found-in-configyaml","title":"\"Config error: Credentials (...) found in config.yaml\"","text":"Cause: You put username or password in config.yaml instead of secrets.yaml.
Fix: Remove those lines from config.yaml. They belong only in secrets.yaml. See Secrets.
"},{"location":"troubleshooting.html#missing-required-fields-in-secretsyaml-username","title":"\"Missing required fields in secrets.yaml: username\"","text":"Cause: secrets.yaml is missing a required field.
Fix: Add both username and password under the librofm: key:
librofm:\n username: your-email@example.com\n password: your-password\n
"},{"location":"troubleshooting.html#invalid-format-xyz","title":"\"Invalid format 'xyz'\"","text":"Cause: The format value in config.yaml is not one of the three valid strategies.
Fix: Use one of:
m4b_mp3_fallback mp3_only m4b_only
"},{"location":"troubleshooting.html#errno-2-no-such-file-or-directory-configyaml","title":"\"[Errno 2] No such file or directory: 'config.yaml'\"","text":"Cause: The config file doesn't exist at the specified path (default: current directory).
Fix:
# Run from the directory that contains config.yaml\ncd /path/to/your/project\n\n# Or specify the path explicitly\nlibrofm-downloader --config /path/to/config.yaml --secrets /path/to/secrets.yaml\n
"},{"location":"troubleshooting.html#download-issues","title":"Download issues","text":""},{"location":"troubleshooting.html#download-stops-partway-through","title":"Download stops partway through","text":"Cause: Network interruption, timeout, or you pressed Ctrl+C.
Behavior: - Exit code 130 if Ctrl+C - Partial file saved as {filename}.m4b.partial or {filename}.zip.partial
Fix \u2014 resume on next run: The tool automatically detects .partial files and sends an HTTP Range header to resume from where it stopped. Just run again:
librofm-downloader\n
"},{"location":"troubleshooting.html#failed-author-title-isbn-connection-error","title":"\"Failed: Author - Title [ISBN] (connection error)\"","text":"Cause: Intermittent network failure during a single book's download.
Behavior: - That book is marked as failed in the summary - All other books continue downloading normally - Exit code is still 0 (pipeline completed)
Fix: Run again \u2014 the failed book will be retried (it wasn't recorded in history since it didn't complete):
$ librofm-downloader\nSummary: 0 downloaded, 0 skipped, 1 failed\n Failed:\n \u2717 Brandon Sanderson - The Way of Kings [9780743565400] (connection error)\n\n# Run again \u2014 it will retry the failed book\n$ librofm-downloader\n
"},{"location":"troubleshooting.html#book-shows-as-skipped-with-m4b_only-mode","title":"Book shows as skipped with m4b_only mode","text":"Cause: The book has no M4B format available from Libro.fm (API returns 404).
Behavior: - Book appears under Skipped: in summary - Not written to download history
Fix options: - Switch to m4b_mp3_fallback to get the MP3 version instead - Accept that some books aren't available in M4B format
"},{"location":"troubleshooting.html#history-file-problems","title":"History file problems","text":""},{"location":"troubleshooting.html#corrupt-history-file-download_historyjson-starting-with-empty-history","title":"\"Corrupt history file download_history.json: ... Starting with empty history.\"","text":"Cause: The download_history.json file exists but contains invalid JSON.
Behavior: - Tool starts with empty history (all books appear as \"new\") - Already-downloaded books will be re-downloaded
Fix:
# Option 1: Delete and let it rebuild\nrm download_history.json\nlibrofm-downloader\n\n# Option 2: Fix the JSON manually (if you know what's in there)\n# Check for trailing commas, missing braces, etc.\n
"},{"location":"troubleshooting.html#books-re-downloading-after-already-being-downloaded","title":"Books re-downloading after already being downloaded","text":"Cause: The ISBN in the library response doesn't match what's stored in history.
Check:
# See what's recorded\ncat download_history.json | python -m json.tool\n\n# Look for the ISBN of the book that's re-downloading\n
Possible reasons: - The book was re-published under a new ISBN - History file was deleted or moved - You're running from a different directory with a different history file
"},{"location":"troubleshooting.html#output-path-issues","title":"Output / path issues","text":""},{"location":"troubleshooting.html#files-going-to-wrong-directory","title":"Files going to wrong directory","text":"Cause: output_dir setting or CWD mismatch.
Check:
# Verify your config\ngrep output_dir config.yaml\n\n# Check where you're running from\npwd\n\n# Use absolute paths to avoid ambiguity\nlibrofm-downloader --config /absolute/path/to/config.yaml\n
"},{"location":"troubleshooting.html#permission-denied-when-writing-files","title":"\"Permission denied\" when writing files","text":"Cause: The user running the tool doesn't have write access to output_dir.
Fix:
# Check permissions\nls -la ./audiobooks/\n\n# Fix ownership or choose a writable directory\nchmod u+w ./audiobooks/\n# or set output_dir to somewhere writable in config.yaml\n
"},{"location":"troubleshooting.html#performance","title":"Performance","text":""},{"location":"troubleshooting.html#downloads-are-slow","title":"Downloads are slow","text":"Check:
- Your internet connection speed
- Whether a VPN/proxy is adding latency
- Libro.fm CDN responsiveness (varies by region)
The tool downloads in a single stream per book (no parallelism within one book), but can process multiple books in parallel via --workers N (default 3). Libro.fm API calls are rate-limited to 3 concurrent requests regardless of worker count.
"},{"location":"troubleshooting.html#large-library-takes-a-long-time","title":"Large library takes a long time","text":"Audiobooks are large (200 MB \u2013 1 GB each). A library of 50 books at 2 MB/s would take ~7 hours just for transfer time. This is expected behavior.
Use --limit to process smaller batches:
# Download 5 books at a time\nlibrofm-downloader --limit 5\n
"},{"location":"troubleshooting.html#getting-help","title":"Getting help","text":"If none of the above covers your issue:
- Run with
-v (--verbose) to get detailed output including URLs and tracebacks - Check the GitHub Issues for known problems
- Open a new issue with:
- The error message (from
-v output) - Your
format setting - Whether it happens on every book or specific ones
- Your OS and Python version (
python --version)
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"index.html","title":"librofm-downloader","text":"Download owned audiobooks from your Libro.fm account \u2014 a lightweight, dependency-minimal CLI tool written in Python.
No Docker. No JVM. Just pip install and go.
"},{"location":"index.html#features","title":"Features","text":" - Full library sync \u2014 fetches every audiobook in your Libro.fm account with automatic pagination
- M4B + MP3 formats \u2014 downloads M4B (single file) or MP3 (ZIP parts extracted) with automatic fallback
- Resume support \u2014 interrupted downloads pick up where they left off via
.partial files - Cover art & PDF extras \u2014 optional download of cover images and accompanying PDFs
- Customizable output paths \u2014 token-based patterns for organizing your library on disk
- TTY-aware progress \u2014 rich progress bars in your terminal, clean log lines in cron jobs
- Download history \u2014 tracks what's been downloaded so re-runs only fetch new books
- Graceful failure isolation \u2014 one failed book doesn't stop the rest
"},{"location":"index.html#quick-start","title":"Quick Start","text":"# 1. Install\npip install librofm-downloader\n\n# 2. Configure\ncat > config.yaml << 'EOF'\nlibrofm:\n format: m4b_mp3_fallback\n output_dir: ./audiobooks\n download_extras: true\n download_covers: true\nEOF\n\ncat > secrets.yaml << 'EOF'\nlibrofm:\n username: your-email@example.com\n password: your-password\nEOF\n\n# 3. Run\nlibrofm-downloader\n
See Quickstart for the full walkthrough, or jump to Configuration Reference for every option.
"},{"location":"cli-usage.html","title":"CLI Usage","text":"Command-line interface reference for librofm-downloader.
"},{"location":"cli-usage.html#synopsis","title":"Synopsis","text":"librofm-downloader [OPTIONS]\n
"},{"location":"cli-usage.html#options","title":"Options","text":"Option Short Default Description --config XDG \u2192 CWD search Path to config.yaml (overrides default search) --secrets XDG \u2192 CWD search Path to secrets.yaml (overrides default search) --history XDG \u2192 CWD search Path to download history JSON (overrides default search) -v, --verbose off Print extra detail (URLs, paths, API responses) --limit N 0 (no limit) Maximum number of books to download -w, --workers N 3 Number of parallel download workers (1 = sequential)"},{"location":"cli-usage.html#-verbose","title":"--verbose","text":"Shows internal pipeline state at each stage:
\u2500\u2500 config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n config: ~/.config/librofm-downloader/config.yaml\n secrets: ~/.config/librofm-downloader/secrets.yaml\n history: ~/.config/librofm-downloader/download_history.json\n format: m4b_mp3_fallback\n output: ./audiobooks\n extras: True\n covers: True\n user: me@example.com\n\u2500\u2500 auth \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n \u2713 authenticated\n\u2500\u2500 library \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n 47 book(s) in library\n\u2500\u2500 filtering \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n 42 already downloaded, 5 new\n \u2b07 Book Title [dim](9780743565400)[/dim]\n authors: Brandon Sanderson\n narrators: Kate Reading, Michael Kramer\n ...\n 123,456,789 bytes\n
"},{"location":"cli-usage.html#-limit","title":"--limit","text":"Cap how many books are downloaded in a single run. Useful for testing:
# Download only 1 book (the first new one)\nlibrofm-downloader --limit 1\n\n# Download up to 3 books\nlibrofm-downloader --limit 3 -v\n
Books are processed in the order returned by the Libro.fm API. Already-downloaded books are filtered out before the limit is applied.
"},{"location":"cli-usage.html#-workers","title":"--workers","text":"Controls how many books download simultaneously:
# Default: 3 parallel downloads\nlibrofm-downloader\n\n# High-bandwidth connection: 5 workers\nlibrofm-downloader -w 5\n\n# Force sequential (useful for debugging)\nlibrofm-downloader --workers 1\n
Resolution order (CLI > config > default):
--workers N / -w N on the command line workers: field in config.yaml - Default: 3
[!NOTE] The worker count controls CDN download parallelism. Libro.fm API calls are separately capped at 3 concurrent requests via an internal semaphore, regardless of worker count. This protects the API server while letting CDN transfers scale up.
Set to 1 for behavior identical to the pre-parallelism sequential mode.
"},{"location":"cli-usage.html#exit-codes","title":"Exit codes","text":"Code Meaning 0 Success \u2014 all done (including \"nothing new to download\") 1 Fatal error \u2014 config problem, auth failure, or library fetch failure 130 Interrupted \u2014 user pressed Ctrl+C during downloads"},{"location":"cli-usage.html#exit-code-0-scenarios","title":"Exit code 0 scenarios","text":" - All new books downloaded successfully
- No new books to download (
All caught up!) - Some books failed but the pipeline completed (failures are reported in the summary)
[!NOTE] Exit code 0 does not mean \"zero failures\" \u2014 it means the process ran to completion. Check the summary line for failed count.
"},{"location":"cli-usage.html#exit-code-1-scenarios","title":"Exit code 1 scenarios","text":"# Config error\n$ librofm-downloader --config missing.yaml\nConfig error: [Errno 2] No such file or directory: 'missing.yaml'\n\n# Auth failure\n$ librofm-downloader\nAuthentication failed: Auth failed (401)\n\n# Library fetch failure\n$ librofm-downloader\nFailed to fetch library: 502 Bad Gateway\n
"},{"location":"cli-usage.html#exit-code-130","title":"Exit code 130","text":"$ librofm-downloader\n^CDownload interrupted by user (Ctrl+C).\necho $?\n130\n
Partial downloads are preserved as .partial files and will be resumed on the next run.
"},{"location":"cli-usage.html#cron-setup","title":"Cron setup","text":""},{"location":"cli-usage.html#basic-daily-sync","title":"Basic daily sync","text":"# m h dom mon dow command\n0 4 * * * cd /path/to/librofm-downloader && .venv/bin/librofm-downloader >> /var/log/librofm.log 2>&1\n
Runs every day at 4:00 AM, appends output to a log file.
"},{"location":"cli-usage.html#with-email-on-failure","title":"With email on failure","text":"0 4 * * * cd /path/to/librofm-downloader && .venv/bin/librofm-downloader || echo \"librofm-downloader failed\" | mail -s \"DL failure\" you@example.com\n
"},{"location":"cli-usage.html#weekly-with-limit","title":"Weekly with limit","text":"0 3 * * 1 cd /path/to/librofm-downloader && .venv/bin/librofm-downloader --limit 10 >> /var/log/librofm-weekly.log 2>&1\n
Runs Mondays at 3:00 AM, caps at 10 books.
"},{"location":"cli-usage.html#systemd-timer-alternative-to-cron","title":"systemd timer (alternative to cron)","text":"# /etc/systemd/system/librofm-downloader.service\n[Unit]\nDescription=Libro.fm Audiobook Downloader\nAfter=network-online.target\n\n[Service]\nType=oneshot\nWorkingDirectory=/path/to/librofm-downloader\nExecStart=/path/to/librofm-downloader/.venv/bin/librofm-downloader\n\n# /etc/systemd/system/librofm-downloader.timer\n[Unit]\nDescription=Run librofm-downloader daily\n\n[Timer]\nOnCalendar=daily\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n
systemctl enable --now librofm-downloader.timer\njournalctl -u librofm-downloader -f\n
"},{"location":"cli-usage.html#tty-vs-non-tty-output","title":"TTY vs non-TTY output","text":"The tool auto-detects whether stdout is a terminal:
"},{"location":"cli-usage.html#tty-interactive-terminal","title":"TTY (interactive terminal)","text":" - Rich progress bars with percentage, transfer speed, ETA, and size
- Color-coded results (\u2713 green, \u2717 red, \u23ed yellow)
- Progress bars update in-place (no scrolling flood)
Brandon Sanderson - The Way of Kings \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 67.3% 2.1 MB/s 00:03 45.2 MB\n
"},{"location":"cli-usage.html#non-tty-cron-pipe-redirect","title":"Non-TTY (cron, pipe, redirect)","text":" - Plain text log lines \u2014 one per event
- No color, no progress bar updates
- Same information, machine-friendly format
Downloading: Brandon Sanderson - The Way of Kings (unknown size)\nCompleted: Brandon Sanderson - The Way of Kings\nSummary: 1 downloaded, 0 skipped, 0 failed\n
This means you get nice progress in your terminal and clean logs in cron \u2014 no flags needed.
"},{"location":"configuration.html","title":"Configuration Reference","text":"Complete reference for config.yaml, secrets.yaml, and download history.
"},{"location":"configuration.html#default-file-locations","title":"Default file locations","text":"When no --config, --secrets, or --history flags are provided, the tool searches for each file in this order:
- XDG directory \u2014
~/.config/librofm-downloader/ - Current working directory (CWD)
The XDG directory is created automatically on first run if it doesn't exist. This means you can drop your files into ~/.config/librofm-downloader/ and run librofm-downloader from any directory.
~/.config/librofm-downloader/\n\u251c\u2500\u2500 config.yaml # optional \u2014 built-in defaults used if missing\n\u251c\u2500\u2500 secrets.yaml # required \u2014 tool exits with an error if missing\n\u2514\u2500\u2500 download_history.json # created automatically on first download\n
"},{"location":"configuration.html#missing-files-config-vs-secrets","title":"Missing files: config vs secrets","text":"The two config files have different missing-file behavior:
File If missing Behavior config.yaml Non-fatal Tool runs with built-in defaults (m4b_mp3_fallback, ./audiobooks, etc.). A notice is printed listing searched paths. secrets.yaml Fatal Tool exits with code 1 and an error listing both searched locations so you know where to create it."},{"location":"configuration.html#overriding-with-cli-flags","title":"Overriding with CLI flags","text":"Use --config, --secrets, and --history to bypass the XDG\u2192CWD search entirely and point at specific files:
# Use files in a custom location\nlibrofm-downloader --config /path/to/config.yaml --secrets /path/to/secrets.yaml\n\n# Custom history file\nlibrofm-downloader --history /path/to/download_history.json\n
When a flag is provided, that path is used directly \u2014 no search is performed.
Both config files share the same top-level key: librofm.
"},{"location":"configuration.html#secretsyaml","title":"secrets.yaml","text":"Credentials only. This file must not be committed to version control.
Field Type Required Description username string \u2705 Your Libro.fm account email password string \u2705 Your Libro.fm password librofm:\n username: your-email@example.com\n password: your-password\n
[!IMPORTANT] Only username and password belong in this file. All other settings go in config.yaml. If either field is missing, the tool exits with code 1 and an error message.
"},{"location":"configuration.html#configyaml","title":"config.yaml","text":"All non-credential settings. Safe to commit. Optional \u2014 if missing, built-in defaults are used.
Field Type Default Description format string \"m4b_mp3_fallback\" Audio download strategy. See Format Strategies. output_dir string \"./audiobooks\" Base directory for downloaded files. Relative paths resolve from CWD. download_extras boolean true Download PDF extras (e.g., maps) when available. download_covers boolean true Download cover art (JPEG/PNG) when available. workers integer 3 Number of parallel download threads. Set to 1 for sequential mode. Must be \u2265 1."},{"location":"configuration.html#full-example","title":"Full example","text":"librofm:\n format: m4b_mp3_fallback\n output_dir: ./audiobooks\n download_extras: true\n download_covers: true\n workers: 3\n
"},{"location":"configuration.html#minimal-example","title":"Minimal example","text":"Only format is meaningful here \u2014 everything else has a default:
librofm:\n format: mp3_only\n workers: 5 # high-bandwidth connection\n
"},{"location":"configuration.html#how-merging-works","title":"How merging works","text":"config.yaml and secrets.yaml are deep-merged at startup:
config.yaml is loaded as the base secrets.yaml is layered on top (overrides on conflict) - The merged result is validated
This means you could theoretically put any field in either file \u2014 but credentials in config.yaml are explicitly rejected at load time with a clear error:
Config error: Credentials (username, password) found in config.yaml.\nMove them to secrets.yaml (which is gitignored).\n
"},{"location":"configuration.html#validation-errors","title":"Validation errors","text":"Error Cause Fix Config error: Credentials (...) found in config.yaml Username or password in config file Move to secrets.yaml Missing required fields in secrets.yaml: username Missing credential field Add it to secrets.yaml Invalid format 'foo' Unknown format value Use one of: m4b_mp3_fallback, mp3_only, m4b_only config.yaml not found in ~/.config/.../config.yaml \u2192 ./config.yaml. Using built-in defaults. No config file in either location Non-fatal \u2014 defaults used. Create config.yaml to customize. Missing secrets.yaml. Searched: ~/.config/.../secrets.yaml \u2192 ./secrets.yaml. No secrets file in either location Create secrets.yaml with your credentials in one of the searched locations. Invalid workers value: 0 Workers < 1 Set workers to an integer \u2265 1"},{"location":"configuration.html#download-history","title":"Download history","text":"A third file, download_history.json, tracks what's been downloaded. It follows the same XDG\u2192CWD search order as the config files, and defaults to the XDG directory when not found anywhere:
~/.config/librofm-downloader/download_history.json\n
The file is created automatically on first download. Override with --history to use a custom location.
{\n \"9780743565400\": {\n \"isbn\": \"9780743565400\",\n \"title\": \"The Way of Kings\",\n \"format\": \"m4b\",\n \"path\": \"./audiobooks/Brandon Sanderson/The Way of Kings/The Way of Kings.m4b\",\n \"downloaded_at\": \"2026-06-03T10:30:00+00:00\"\n }\n}\n
- Keyed by ISBN \u2014 each book is recorded once
- Used to skip already-downloaded books on subsequent runs
- If the file is corrupt or missing, the tool starts with an empty history (and logs a warning)
"},{"location":"format-strategies.html","title":"Format Strategies","text":"librofm-downloader supports three audio format strategies, controlled by the format field in config.yaml.
"},{"location":"format-strategies.html#overview","title":"Overview","text":"Strategy Behavior Best for m4b_mp3_fallback Try M4B first; fall back to MP3 if unavailable Default \u2014 maximum compatibility mp3_only Download MP3 ZIP only (skip M4B entirely) Players that don't support M4B m4b_only Download M4B only; skip book if unavailable Audiobook apps that prefer M4B"},{"location":"format-strategies.html#m4b_mp3_fallback-default","title":"m4b_mp3_fallback (default)","text":"The recommended strategy for most users.
librofm:\n format: m4b_mp3_fallback\n
Flow:
- Request the M4B download URL from Libro.fm API
- If available \u2192 download as a single
.m4b file - If the API returns 404 \u2192 fall back to fetching the MP3 manifest
- Download all MP3 ZIP parts and extract them
What you get:
- Most books: one
.m4b file (AAC/ALAC audio, bookmarkable, chapter markers) - Older or region-locked books: extracted MP3 files (one or more per book)
- No books are skipped \u2014 every downloadable title is fetched in some format
Output examples:
# M4B succeeded\naudiobooks/Brandon Sanderson/The Way of Kings.m4b # single file, ~450 MB\n\n# Fell back to MP3\naudiobooks/Some Author/Old Book/ # directory with MP3s\n\u251c\u2500\u2500 part1.mp3\n\u251c\u2500\u2500 part2.mp3\n\u2514\u2500\u2500 part3.mp3\n
"},{"location":"format-strategies.html#mp3_only","title":"mp3_only","text":"Skip M4B entirely and always use the MP3 ZIP pipeline.
librofm:\n format: mp3_only\n
Flow:
- Fetch the MP3 download manifest from Libro.fm API
- Download each ZIP part listed in the manifest
- Extract all files into the output directory
When to use this:
- Your media player doesn't support M4B/M4A containers
- You want raw MP3 files for editing or conversion
- You're feeding files into a system that only accepts MP3
Output: Always a directory with extracted MP3 files:
audiobooks/Brandon Sanderson/The Way of Kings/\n\u251c\u2500\u2500 part1.mp3\n\u251c\u2500\u2500 part2.mp3\n\u2514\u2500\u2500 ...\n
"},{"location":"format-strategies.html#m4b_only","title":"m4b_only","text":"Only attempt M4B download. Skip books where M4B is not available.
librofm:\n format: m4b_only\n
Flow:
- Request the M4B download URL from Libro.fm API
- If available \u2192 download as a single
.m4b file - If the API returns 404 \u2192 log a skip message, move to next book
When to use this:
- You only want single-file audiobooks (cleaner library management)
- Your audiobook app (Apple Books, etc.) handles M4B natively
- You'd rather miss a book than get split MP3 files
Output example:
# Success\naudiobooks/Brandon Sanderson/The Way of Kings.m4b\n\n# Skipped (shows in summary)\nSummary: 5 downloaded, 2 skipped, 0 failed\n Skipped:\n \u23ed Some Author - Old Book [9781234567890]\n
"},{"location":"format-strategies.html#how-to-choose","title":"How to choose","text":"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u2502\n\u2502 Want every book? \u2502 \u2192 m4b_mp3_fallback (default) \u2502\n\u2502 Only need MP3? \u2502 \u2192 mp3_only \u2502\n\u2502 Single-file or nothing? \u2502 \u2192 m4b_only \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n
"},{"location":"format-strategies.html#technical-details","title":"Technical details","text":""},{"location":"format-strategies.html#m4b-downloads","title":"M4B downloads","text":" - Single HTTP stream with 8 MB chunk buffering
- Written to
{title}.m4b.partial during transfer - Atomic rename to final
.m4b on completion - Supports resume: if a
.partial file exists, sends Range header to continue - Progress reporting via
Content-Length header (% complete, speed, ETA)
"},{"location":"format-strategies.html#mp3-downloads","title":"MP3 downloads","text":" - Fetches a manifest (
/api/v10/download-manifest?isbn=...) listing ZIP part URLs - Each part is downloaded as a
.zip.partial file, then renamed to .zip - ZIP contents are extracted into the output directory
- The ZIP file is deleted after extraction
- Each part supports resume via
Range headers - Parts are downloaded sequentially within each book
"},{"location":"path-patterns.html","title":"Path Patterns","text":"How librofm-downloader organizes files on disk, and how to customize the layout with tokens.
"},{"location":"path-patterns.html#default-behavior","title":"Default behavior","text":"When no custom pattern is set, the output path is determined by conditional logic based on whether a book belongs to a series:
"},{"location":"path-patterns.html#standalone-book-no-series","title":"Standalone book (no series)","text":"{FIRST_AUTHOR}/{BOOK_TITLE}\n
Example: Brandon Sanderson/The Way of Kings.m4b
"},{"location":"path-patterns.html#book-in-a-series-with-series-number","title":"Book in a series (with series number)","text":"{FIRST_AUTHOR}/{SERIES_NAME}/Book {SERIES_NUM} {BOOK_TITLE}\n
Example: Brandon Sanderson/Stormlight Archive/Book 1 The Way of Kings.m4b
"},{"location":"path-patterns.html#book-in-a-series-no-series-number","title":"Book in a series (no series number)","text":"{FIRST_AUTHOR}/{SERIES_NAME}/{BOOK_TITLE}\n
Example: J.K. Rowling/Harry Potter/Harry Potter and the Sorcerer's Stone.m4b
"},{"location":"path-patterns.html#subdirectory-logic","title":"Subdirectory logic","text":"A book gets its own subdirectory when any of these are true:
- The book has PDF extras available (
pdf_extras: true) download_covers: true and the book has a cover URL
Otherwise the audio file sits directly under the author directory as a flat file.
"},{"location":"path-patterns.html#available-tokens","title":"Available tokens","text":"Use these inside {TOKEN} placeholders in a custom pattern:
Token Source Example value Notes {FIRST_AUTHOR} First item in authors list Brandon Sanderson Empty if no authors {ALL_AUTHORS} Authors joined by , Sanderson, Brandon Empty if no authors {SERIES_NAME} Series name Stormlight Archive Empty string if not in a series {SERIES_NUM} Series position integer 1 Empty if not in a series or no number {BOOK_TITLE} Book title The Way of Kings Sanitized for filesystem safety {ISBN} ISBN identifier 9780743565400 As returned by the API {FIRST_NARRATOR} First narrator Kate Reading Empty if no narrators {ALL_NARRATORS} Narrators joined by , Kate Reading, Michael Kramer Empty if no narrators {PUBLICATION_YEAR} Year published 2024 Empty if unknown {PUBLICATION_MONTH} Month published 8 Empty if unknown {PUBLICATION_DAY} Day published 15 Empty if unknown"},{"location":"path-patterns.html#custom-patterns","title":"Custom patterns","text":"To override the default conditional logic, set a path_pattern key in your config:
librofm:\n format: m4b_mp3_fallback\n output_dir: ./audiobooks\n path_pattern: \"{PUBLICATION_YEAR}/{FIRST_AUTHOR} - {BOOK_TITLE}\"\n
This would produce paths like:
./audiobooks/2024/Brandon Sanderson - The Way of Kings.m4b\n./audiobooks/2023/Suzanne Collins - The Hunger Games.m4b\n
[!NOTE] Custom patterns are applied via regex substitution ({TOKEN_NAME} \u2192 value). Unknown tokens resolve to empty strings \u2014 no error is raised. Each path component is sanitized (colons replaced, illegal chars stripped, capped at 255 chars).
"},{"location":"path-patterns.html#pattern-examples","title":"Pattern examples","text":""},{"location":"path-patterns.html#flat-by-author","title":"Flat by author","text":"path_pattern: \"{ALL_AUTHORS}/{BOOK_TITLE}\"\n
Output:
audiobooks/Sanderson, Brandon/The Way of Kings.m4b\naudiobooks/Collins, Suzanne/The Hunger Games.m4b\n
"},{"location":"path-patterns.html#organized-by-series","title":"Organized by series","text":"path_pattern: \"{FIRST_AUTHOR}/{SERIES_NAME}/{SERIES_NUM:03d} - {BOOK_TITLE}\"\n
Output:
audiobooks/Brandon Sanderson/Stormlight Archive/001 - The Way of Kings.m4b\naudiobooks/Brandon Sanderson/Mistborn/001 - The Final Empire.m4b\n
[!WARNING] Python format specs like :03d are not supported \u2014 tokens produce plain strings only. Use {SERIES_NUM} directly; it will render as 1, 2, etc.
"},{"location":"path-patterns.html#by-narrator","title":"By narrator","text":"path_pattern: \"{FIRST_NARRATOR}/{BOOK_TITLE}\"\n
Output:
audiobooks/Kate Reading/The Way of Kings.m4b\n
"},{"location":"path-patterns.html#iso-style-date-prefix","title":"ISO-style date prefix","text":"path_pattern: \"{PUBLICATION_YEAR}-{PUBLICATION_MONTH}-{PUBLICATION_DAY}/{FIRST_AUTHOR}/{BOOK_TITLE}\"\n
Output:
audiobooks/2024-8-15/Brandon Sanderson/The Way of Kings.m4b\n
"},{"location":"path-patterns.html#path-sanitization","title":"Path sanitization","text":"Every path component goes through sanitization before being written to disk:
- Colons (
:) \u2192 replaced with - - Illegal characters
< > / \\ | ? * \u2192 stripped - Control characters (U+0000\u2013U+001F) \u2192 stripped
- Trailing dots \u2192 removed
- Whitespace \u2192 trimmed
- Length \u2192 capped at 255 characters
Preserved characters include dashes, commas, apostrophes, parentheses, and non-trailing periods.
"},{"location":"quickstart.html","title":"Quickstart","text":"Get librofm-downloader installed, configured, and running in three steps.
"},{"location":"quickstart.html#1-install","title":"1. Install","text":""},{"location":"quickstart.html#from-pypi-recommended","title":"From PyPI (recommended)","text":"pip install librofm-downloader\n
Requires Python 3.11+.
"},{"location":"quickstart.html#from-source","title":"From source","text":"git clone https://github.com/AlexKucera/librofm-downloader.git\ncd librofm-downloader\npython -m venv .venv\nsource .venv/bin/activate # or .venv\\Scripts\\activate on Windows\npip install -e \".[dev]\"\n
The [dev] extra installs pytest for testing \u2014 omit it if you only want to run the tool.
"},{"location":"quickstart.html#2-configure","title":"2. Configure","text":"librofm-downloader uses two YAML files, searched in ~/.config/librofm-downloader/ first, then the current working directory:
File Purpose Required? Committed to git? config.yaml Preferences (format, output dir, toggles) No (defaults used) \u2705 Yes secrets.yaml Credentials only Yes \u274c No (gitignored) [!TIP] The XDG directory (~/.config/librofm-downloader/) is created automatically on first run. Place both files there to run librofm-downloader from any directory.
"},{"location":"quickstart.html#configyaml","title":"config.yaml","text":"# libro.fm downloader configuration\n# This file is safe to commit \u2014 no credentials here.\n# Credentials go in secrets.yaml (which is gitignored).\n\nlibrofm:\n # Audio format preference:\n # m4b_mp3_fallback \u2014 try M4B first, fall back to MP3 ZIP (default)\n # mp3_only \u2014 download MP3 ZIP only\n # m4b_only \u2014 download M4B only, skip if unavailable\n format: m4b_mp3_fallback\n\n # Where downloaded audiobooks are saved\n output_dir: ./audiobooks\n\n # Whether to download PDF extras when available\n download_extras: true\n\n # Whether to download cover art when available\n download_covers: true\n
"},{"location":"quickstart.html#secretsyaml","title":"secrets.yaml","text":"librofm:\n username: your-email@example.com\n password: your-password\n
[!WARNING] Never commit secrets.yaml. It is listed in .gitignore by default. If you accidentally put credentials in config.yaml, the tool will refuse to start and tell you to move them.
"},{"location":"quickstart.html#3-run","title":"3. Run","text":""},{"location":"quickstart.html#basic-sync","title":"Basic sync","text":"librofm-downloader\n
This:
- Searches for
config.yaml + secrets.yaml (XDG directory first, then CWD) - Authenticates with Libro.fm via OAuth2 password grant
- Fetches your full library (all pages)
- Skips books already in
download_history.json (XDG \u2192 CWD search) - Downloads each new book with a progress bar
- Downloads each new book (3 parallel workers by default) with a progress bar
- Records successful downloads to history
"},{"location":"quickstart.html#first-run-output-tty","title":"First run output (TTY)","text":"3 book(s) to download:\n\nAuthor One - Book Title One \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 100.0% 2.1 MB/s 00:01 45.2 MB\n \u2713 Book Title One\nAuthor Two - Another Book \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 100.0% 1.8 MB/s 00:02 120.5 MB\n \u2713 Another Book\nAuthor Three - Third Book \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 100.0% 2.3 MB/s 00:00 89.1 MB\n \u2713 Third Book\n\nSummary: 3 downloaded, 0 skipped, 0 failed\n
"},{"location":"quickstart.html#subsequent-run-nothing-new","title":"Subsequent run (nothing new)","text":"All caught up! No new books to download.\n
"},{"location":"quickstart.html#cron-non-tty-output","title":"Cron / non-TTY output","text":"When stdout is not a terminal (e.g., cron, piped), output switches to plain text log lines:
Downloading: Author One - Book Title One (unknown size)\nCompleted: Author One - Book Title One\nDownloading: Author Two - Another Book (unknown size)\nCompleted: Author Two - Another Book\n\nSummary: 2 downloaded, 0 skipped, 0 failed\n
"},{"location":"quickstart.html#what-gets-downloaded","title":"What gets downloaded?","text":"Files land under your output_dir using this structure:
audiobooks/\n\u251c\u2500\u2500 Brandon Sanderson/\n\u2502 \u251c\u2500\u2500 The Way of Kings/\n\u2502 \u2502 \u251c\u2500\u2500 The Way of Kings.m4b\n\u2502 \u2502 \u251c\u2500\u2500 cover.jpg\n\u2502 \u2502 \u2514\u2500\u2500 map.pdf\n\u2502 \u2514\u2500\u2500 Words of Radiance.m4b \u2190 no extras = flat file\n\u2514\u2500\u2500 Suzanne Collins/\n \u2514\u2500\u2500 The Hunger Games.m4b\n
- Books with cover art or PDF extras get a subdirectory (
Author/Title/) - Books without extras are flat files (
Author/Title.m4b) - See Path Patterns for customization options
"},{"location":"quickstart.html#next-steps","title":"Next steps","text":" - Configuration Reference \u2014 every field documented
- Format Strategies \u2014 choose the right mode for your setup
- CLI Usage \u2014 all flags, exit codes, cron examples
- Troubleshooting \u2014 common problems and solutions
"},{"location":"secrets.html","title":"Secrets","text":"Why secrets.yaml exists, how it works, and common mistakes to avoid.
"},{"location":"secrets.html#purpose","title":"Purpose","text":"Libro.fm authentication requires your email and password. These are stored in a separate file from your regular configuration so you can safely commit config.yaml to version control without leaking credentials.
"},{"location":"secrets.html#file-format","title":"File format","text":"librofm:\n username: your-email@example.com\n password: your-password\n
Two fields, both required, both strings. That's it.
"},{"location":"secrets.html#why-its-gitignored","title":"Why it's gitignored","text":"The .gitignore entry:
secrets.yaml\n
This is set up by default in the project template. If you clone the repo and create secrets.yaml, Git will never track it.
"},{"location":"secrets.html#common-mistakes","title":"Common mistakes","text":""},{"location":"secrets.html#1-putting-credentials-in-configyaml","title":"1. Putting credentials in config.yaml","text":"If you accidentally add username or password to config.yaml:
# \u274c Wrong \u2014 config.yaml\nlibrofm:\n username: me@example.com # <-- this will be rejected\n password: secret # <-- this will be rejected\n format: m4b_mp3_fallback\n
The tool refuses to start:
Config error: Credentials (username, password) found in config.yaml.\nMove them to secrets.yaml (which is gitignored).\n
Fix: Remove those lines from config.yaml and put them in secrets.yaml.
"},{"location":"secrets.html#2-committing-before-gitignore","title":"2. Committing before gitignore","text":"If you git add secrets.yaml before the .gitignore rule was added, Git may already be tracking it:
# Check if Git is tracking it\ngit ls-files | grep secrets.yaml\n\n# If it shows up, remove it from tracking (keeps local file)\ngit rm --cached secrets.yaml\ngit commit -m \"Stop tracking secrets.yaml\"\n
"},{"location":"secrets.html#3-missing-fields","title":"3. Missing fields","text":"If secrets.yaml exists but is missing username or password:
Missing required fields in secrets.yaml: username, password.\nAdd them to your secrets.yaml file.\n
Both fields are required \u2014 there are no defaults for credentials.
"},{"location":"secrets.html#4-wrong-indentation","title":"4. Wrong indentation","text":"YAML is whitespace-sensitive. The librofm: key must be at column 0, and username/password must be indented with exactly 2 spaces:
# \u2705 Correct\nlibrofm:\n username: me@example.com\n password: secret\n\n# \u274c Wrong \u2014 no indentation\nlibrofm:\nusername: me@example.com\npassword: secret\n\n# \u274c Wrong \u2014 wrong key name (not under librofm:)\nusername: me@example.com\npassword: secret\n
"},{"location":"secrets.html#security-notes","title":"Security notes","text":" - The password is stored in plaintext on disk \u2014 this is a CLI tool for personal use, not a multi-user service
- The password is sent to Libro.fm's OAuth2 token endpoint over HTTPS; it is never logged or transmitted elsewhere
- If your Libro.fm account has 2FA enabled, you may need an app-specific password depending on how Libro.fm handles OAuth2 password grants
- Never share your
secrets.yaml file \u2014 if you do, rotate your Libro.fm password immediately
"},{"location":"troubleshooting.html","title":"Troubleshooting","text":"Common errors, their causes, and how to fix them.
"},{"location":"troubleshooting.html#authentication-failures","title":"Authentication failures","text":""},{"location":"troubleshooting.html#authentication-failed-auth-failed-401","title":"\"Authentication failed: Auth failed (401)\"","text":"Cause: Wrong email or password in secrets.yaml.
Fix:
- Verify you can log in to libro.fm in a browser with the same credentials
- Check for typos in
secrets.yaml (YAML is case-sensitive) - If you changed your Libro.fm password recently, update
secrets.yaml
"},{"location":"troubleshooting.html#authentication-failed-auth-failed-xxx-non-401","title":"\"Authentication failed: Auth failed (xxx)\" (non-401)","text":"Cause: Network issue or Libro.fm API temporarily down.
Fix:
- Check your internet connection
- Try again in a few minutes
- Check Libro.fm status if available
"},{"location":"troubleshooting.html#configuration-errors","title":"Configuration errors","text":""},{"location":"troubleshooting.html#config-error-credentials-found-in-configyaml","title":"\"Config error: Credentials (...) found in config.yaml\"","text":"Cause: You put username or password in config.yaml instead of secrets.yaml.
Fix: Remove those lines from config.yaml. They belong only in secrets.yaml. See Secrets.
"},{"location":"troubleshooting.html#missing-required-fields-in-secretsyaml-username","title":"\"Missing required fields in secrets.yaml: username\"","text":"Cause: secrets.yaml is missing a required field.
Fix: Add both username and password under the librofm: key:
librofm:\n username: your-email@example.com\n password: your-password\n
"},{"location":"troubleshooting.html#invalid-format-xyz","title":"\"Invalid format 'xyz'\"","text":"Cause: The format value in config.yaml is not one of the three valid strategies.
Fix: Use one of:
m4b_mp3_fallback mp3_only m4b_only
"},{"location":"troubleshooting.html#errno-2-no-such-file-or-directory-configyaml","title":"\"[Errno 2] No such file or directory: 'config.yaml'\"","text":"Cause: The config file doesn't exist at the specified path.
Fix:
# Option 1: Place files in the XDG directory (recommended)\nmkdir -p ~/.config/librofm-downloader\ncp config.yaml secrets.yaml ~/.config/librofm-downloader/\n\n# Option 2: Run from the directory that contains config.yaml\ncd /path/to/your/project\n\n# Option 3: Specify paths explicitly\nlibrofm-downloader --config /path/to/config.yaml --secrets /path/to/secrets.yaml\n
"},{"location":"troubleshooting.html#download-issues","title":"Download issues","text":""},{"location":"troubleshooting.html#download-stops-partway-through","title":"Download stops partway through","text":"Cause: Network interruption, timeout, or you pressed Ctrl+C.
Behavior: - Exit code 130 if Ctrl+C - Partial file saved as {filename}.m4b.partial or {filename}.zip.partial
Fix \u2014 resume on next run: The tool automatically detects .partial files and sends an HTTP Range header to resume from where it stopped. Just run again:
librofm-downloader\n
"},{"location":"troubleshooting.html#failed-author-title-isbn-connection-error","title":"\"Failed: Author - Title [ISBN] (connection error)\"","text":"Cause: Intermittent network failure during a single book's download.
Behavior: - That book is marked as failed in the summary - All other books continue downloading normally - Exit code is still 0 (pipeline completed)
Fix: Run again \u2014 the failed book will be retried (it wasn't recorded in history since it didn't complete):
$ librofm-downloader\nSummary: 0 downloaded, 0 skipped, 1 failed\n Failed:\n \u2717 Brandon Sanderson - The Way of Kings [9780743565400] (connection error)\n\n# Run again \u2014 it will retry the failed book\n$ librofm-downloader\n
"},{"location":"troubleshooting.html#book-shows-as-skipped-with-m4b_only-mode","title":"Book shows as skipped with m4b_only mode","text":"Cause: The book has no M4B format available from Libro.fm (API returns 404).
Behavior: - Book appears under Skipped: in summary - Not written to download history
Fix options: - Switch to m4b_mp3_fallback to get the MP3 version instead - Accept that some books aren't available in M4B format
"},{"location":"troubleshooting.html#history-file-problems","title":"History file problems","text":""},{"location":"troubleshooting.html#corrupt-history-file-download_historyjson-starting-with-empty-history","title":"\"Corrupt history file download_history.json: ... Starting with empty history.\"","text":"Cause: The download_history.json file exists but contains invalid JSON.
Behavior: - Tool starts with empty history (all books appear as \"new\") - Already-downloaded books will be re-downloaded
Fix:
# Option 1: Delete and let it rebuild\nrm ~/.config/librofm-downloader/download_history.json\nlibrofm-downloader\n\n# Option 2: If using CWD-based history\nrm download_history.json\nlibrofm-downloader\n\n# Option 3: Fix the JSON manually (if you know what's in there)\n# Check for trailing commas, missing braces, etc.\n
"},{"location":"troubleshooting.html#books-re-downloading-after-already-being-downloaded","title":"Books re-downloading after already being downloaded","text":"Cause: The ISBN in the library response doesn't match what's stored in history.
Check:
# See what's recorded (XDG location)\ncat ~/.config/librofm-downloader/download_history.json | python -m json.tool\n\n# Or if using CWD-based history\ncat download_history.json | python -m json.tool\n\n# Look for the ISBN of the book that's re-downloading\n
Possible reasons: - The book was re-published under a new ISBN - History file was deleted or moved - You're running from a different directory with a different history file
"},{"location":"troubleshooting.html#output-path-issues","title":"Output / path issues","text":""},{"location":"troubleshooting.html#files-going-to-wrong-directory","title":"Files going to wrong directory","text":"Cause: output_dir setting or CWD mismatch.
Check:
# Verify your config\ngrep output_dir config.yaml\n\n# Check where you're running from\npwd\n\n# Use absolute paths to avoid ambiguity\nlibrofm-downloader --config /absolute/path/to/config.yaml\n
"},{"location":"troubleshooting.html#permission-denied-when-writing-files","title":"\"Permission denied\" when writing files","text":"Cause: The user running the tool doesn't have write access to output_dir.
Fix:
# Check permissions\nls -la ./audiobooks/\n\n# Fix ownership or choose a writable directory\nchmod u+w ./audiobooks/\n# or set output_dir to somewhere writable in config.yaml\n
"},{"location":"troubleshooting.html#performance","title":"Performance","text":""},{"location":"troubleshooting.html#downloads-are-slow","title":"Downloads are slow","text":"Check:
- Your internet connection speed
- Whether a VPN/proxy is adding latency
- Libro.fm CDN responsiveness (varies by region)
The tool downloads in a single stream per book (no parallelism within one book), but can process multiple books in parallel via --workers N (default 3). Libro.fm API calls are rate-limited to 3 concurrent requests regardless of worker count.
"},{"location":"troubleshooting.html#large-library-takes-a-long-time","title":"Large library takes a long time","text":"Audiobooks are large (200 MB \u2013 1 GB each). A library of 50 books at 2 MB/s would take ~7 hours just for transfer time. This is expected behavior.
Use --limit to process smaller batches:
# Download 5 books at a time\nlibrofm-downloader --limit 5\n
"},{"location":"troubleshooting.html#getting-help","title":"Getting help","text":"If none of the above covers your issue:
- Run with
-v (--verbose) to get detailed output including URLs and tracebacks - Check the GitHub Issues for known problems
- Open a new issue with:
- The error message (from
-v output) - Your
format setting - Whether it happens on every book or specific ones
- Your OS and Python version (
python --version)
"}]}
\ No newline at end of file
diff --git a/docs/html/sitemap.xml.gz b/docs/html/sitemap.xml.gz
index 3c345b7..53a78b5 100644
Binary files a/docs/html/sitemap.xml.gz and b/docs/html/sitemap.xml.gz differ
diff --git a/docs/html/troubleshooting.html b/docs/html/troubleshooting.html
index 09fd31c..47087ff 100644
--- a/docs/html/troubleshooting.html
+++ b/docs/html/troubleshooting.html
@@ -1370,13 +1370,17 @@
m4b_only
"[Errno 2] No such file or directory: 'config.yaml'"
-Cause: The config file doesn't exist at the specified path (default: current directory).
+Cause: The config file doesn't exist at the specified path.
Fix:
-# Run from the directory that contains config.yaml
-cd /path/to/your/project
-
-# Or specify the path explicitly
-librofm-downloader --config /path/to/config.yaml --secrets /path/to/secrets.yaml
+# Option 1: Place files in the XDG directory (recommended)
+mkdir -p ~/.config/librofm-downloader
+cp config.yaml secrets.yaml ~/.config/librofm-downloader/
+
+# Option 2: Run from the directory that contains config.yaml
+cd /path/to/your/project
+
+# Option 3: Specify paths explicitly
+librofm-downloader --config /path/to/config.yaml --secrets /path/to/secrets.yaml
Download issues
Download stops partway through
@@ -1420,19 +1424,26 @@ Run again — the failed book will be retried (it wasn't recorded in history sin
- Already-downloaded books will be re-downloaded
Fix:
# Option 1: Delete and let it rebuild
-rm download_history.json
+rm ~/.config/librofm-downloader/download_history.json
librofm-downloader
-# Option 2: Fix the JSON manually (if you know what's in there)
-# Check for trailing commas, missing braces, etc.
+# Option 2: If using CWD-based history
+rm download_history.json
+librofm-downloader
+
+# Option 3: Fix the JSON manually (if you know what's in there)
+# Check for trailing commas, missing braces, etc.
Books re-downloading after already being downloaded
Cause: The ISBN in the library response doesn't match what's stored in history.
Check:
-# See what's recorded
-cat download_history.json | python -m json.tool
+# See what's recorded (XDG location)
+cat ~/.config/librofm-downloader/download_history.json | python -m json.tool
-# Look for the ISBN of the book that's re-downloading
+# Or if using CWD-based history
+cat download_history.json | python -m json.tool
+
+# Look for the ISBN of the book that's re-downloading
Possible reasons:
- The book was re-published under a new ISBN
diff --git a/docs/mkdocs/cli-usage.md b/docs/mkdocs/cli-usage.md
index b1e4e0f..3f4111e 100644
--- a/docs/mkdocs/cli-usage.md
+++ b/docs/mkdocs/cli-usage.md
@@ -12,9 +12,9 @@ librofm-downloader [OPTIONS]
| Option | Short | Default | Description |
|--------|-------|---------|-------------|
-| `--config` | | `config.yaml` | Path to `config.yaml` |
-| `--secrets` | | `secrets.yaml` | Path to `secrets.yaml` |
-| `--history` | | `download_history.json` | Path to download history JSON file |
+| `--config` | | XDG → CWD search | Path to `config.yaml` (overrides default search) |
+| `--secrets` | | XDG → CWD search | Path to `secrets.yaml` (overrides default search) |
+| `--history` | | XDG → CWD search | Path to download history JSON (overrides default search) |
| `-v, --verbose` | | off | Print extra detail (URLs, paths, API responses) |
| `--limit` N | | `0` (no limit) | Maximum number of books to download |
| `-w, --workers` N | | `3` | Number of parallel download workers (1 = sequential) |
@@ -25,9 +25,9 @@ Shows internal pipeline state at each stage:
```
── config ──────────────────────────────────────
- config: config.yaml
- secrets: secrets.yaml
- history: download_history.json
+ config: ~/.config/librofm-downloader/config.yaml
+ secrets: ~/.config/librofm-downloader/secrets.yaml
+ history: ~/.config/librofm-downloader/download_history.json
format: m4b_mp3_fallback
output: ./audiobooks
extras: True
diff --git a/docs/mkdocs/configuration.md b/docs/mkdocs/configuration.md
index 872e0ea..c39c4e3 100644
--- a/docs/mkdocs/configuration.md
+++ b/docs/mkdocs/configuration.md
@@ -1,16 +1,47 @@
# Configuration Reference
-Complete reference for `config.yaml` and `secrets.yaml`.
+Complete reference for `config.yaml`, `secrets.yaml`, and download history.
-## File locations
+## Default file locations
-The CLI looks for these files in the **current working directory** by default:
+When no `--config`, `--secrets`, or `--history` flags are provided, the tool searches for each file in this order:
-```bash
-librofm-downloader --config config.yaml --secrets secrets.yaml
+1. **XDG directory** — `~/.config/librofm-downloader/`
+2. **Current working directory** (CWD)
+
+The XDG directory is **created automatically** on first run if it doesn't exist. This means you can drop your files into `~/.config/librofm-downloader/` and run `librofm-downloader` from any directory.
+
+```
+~/.config/librofm-downloader/
+├── config.yaml # optional — built-in defaults used if missing
+├── secrets.yaml # required — tool exits with an error if missing
+└── download_history.json # created automatically on first download
```
-Both files share the same top-level key: `librofm`.
+### Missing files: config vs secrets
+
+The two config files have different missing-file behavior:
+
+| File | If missing | Behavior |
+|------|-----------|----------|
+| `config.yaml` | Non-fatal | Tool runs with built-in defaults (m4b_mp3_fallback, `./audiobooks`, etc.). A notice is printed listing searched paths. |
+| `secrets.yaml` | Fatal | Tool exits with code **1** and an error listing both searched locations so you know where to create it. |
+
+### Overriding with CLI flags
+
+Use `--config`, `--secrets`, and `--history` to bypass the XDG→CWD search entirely and point at specific files:
+
+```bash
+# Use files in a custom location
+librofm-downloader --config /path/to/config.yaml --secrets /path/to/secrets.yaml
+
+# Custom history file
+librofm-downloader --history /path/to/download_history.json
+```
+
+When a flag is provided, that path is used directly — no search is performed.
+
+Both config files share the same top-level key: `librofm`.
## secrets.yaml
@@ -33,7 +64,7 @@ librofm:
## config.yaml
-All non-credential settings. Safe to commit.
+All non-credential settings. Safe to commit. **Optional** — if missing, built-in defaults are used.
| Field | Type | Default | Description |
|-------|------|---------|-------------|
@@ -86,11 +117,19 @@ Move them to secrets.yaml (which is gitignored).
| `Config error: Credentials (...) found in config.yaml` | Username or password in config file | Move to `secrets.yaml` |
| `Missing required fields in secrets.yaml: username` | Missing credential field | Add it to `secrets.yaml` |
| `Invalid format 'foo'` | Unknown format value | Use one of: `m4b_mp3_fallback`, `mp3_only`, `m4b_only` |
+| `config.yaml not found in ~/.config/.../config.yaml → ./config.yaml. Using built-in defaults.` | No config file in either location | Non-fatal — defaults used. Create `config.yaml` to customize. |
+| `Missing secrets.yaml. Searched: ~/.config/.../secrets.yaml → ./secrets.yaml.` | No secrets file in either location | Create `secrets.yaml` with your credentials in one of the searched locations. |
| `Invalid workers value: 0` | Workers < 1 | Set `workers` to an integer ≥ 1 |
## Download history
-A third file, `download_history.json`, is created automatically on first run:
+A third file, `download_history.json`, tracks what's been downloaded. It follows the same XDG→CWD search order as the config files, and defaults to the XDG directory when not found anywhere:
+
+```
+~/.config/librofm-downloader/download_history.json
+```
+
+The file is created automatically on first download. Override with `--history` to use a custom location.
```json
{
@@ -106,5 +145,4 @@ A third file, `download_history.json`, is created automatically on first run:
- Keyed by **ISBN** — each book is recorded once
- Used to skip already-downloaded books on subsequent runs
-- Location defaults to `download_history.json` in CWD; override with `--history`
- If the file is corrupt or missing, the tool starts with an empty history (and logs a warning)
diff --git a/docs/mkdocs/quickstart.md b/docs/mkdocs/quickstart.md
index 186c1a9..32b47df 100644
--- a/docs/mkdocs/quickstart.md
+++ b/docs/mkdocs/quickstart.md
@@ -26,12 +26,16 @@ The `[dev]` extra installs pytest for testing — omit it if you only want to ru
## 2. Configure
-librofm-downloader uses two YAML files:
+librofm-downloader uses two YAML files, searched in `~/.config/librofm-downloader/` first, then the current working directory:
-| File | Purpose | Committed to git? |
-|------|---------|:-----------------:|
-| `config.yaml` | Preferences (format, output dir, toggles) | ✅ Yes |
-| `secrets.yaml` | Credentials only | ❌ No (gitignored) |
+| File | Purpose | Required? | Committed to git? |
+|------|---------|:---------:|:-----------------:|
+| `config.yaml` | Preferences (format, output dir, toggles) | No (defaults used) | ✅ Yes |
+| `secrets.yaml` | Credentials only | **Yes** | ❌ No (gitignored) |
+
+> [!TIP]
+> The XDG directory (`~/.config/librofm-downloader/`) is created automatically on first run.
+> Place both files there to run `librofm-downloader` from any directory.
### config.yaml
@@ -79,12 +83,13 @@ librofm-downloader
This:
-1. Loads `config.yaml` + `secrets.yaml`
+1. Searches for `config.yaml` + `secrets.yaml` (XDG directory first, then CWD)
2. Authenticates with Libro.fm via OAuth2 password grant
3. Fetches your full library (all pages)
-4. Skips books already in `download_history.json`
-5. Downloads each new book (3 parallel workers by default) with a progress bar
-6. Records successful downloads to history
+4. Skips books already in `download_history.json` (XDG → CWD search)
+5. Downloads each new book with a progress bar
+6. Downloads each new book (3 parallel workers by default) with a progress bar
+7. Records successful downloads to history
### First run output (TTY)
diff --git a/docs/mkdocs/troubleshooting.md b/docs/mkdocs/troubleshooting.md
index ef0fefb..a64320a 100644
--- a/docs/mkdocs/troubleshooting.md
+++ b/docs/mkdocs/troubleshooting.md
@@ -56,15 +56,19 @@ librofm:
### "[Errno 2] No such file or directory: 'config.yaml'"
-**Cause:** The config file doesn't exist at the specified path (default: current directory).
+**Cause:** The config file doesn't exist at the specified path.
**Fix:**
```bash
-# Run from the directory that contains config.yaml
+# Option 1: Place files in the XDG directory (recommended)
+mkdir -p ~/.config/librofm-downloader
+cp config.yaml secrets.yaml ~/.config/librofm-downloader/
+
+# Option 2: Run from the directory that contains config.yaml
cd /path/to/your/project
-# Or specify the path explicitly
+# Option 3: Specify paths explicitly
librofm-downloader --config /path/to/config.yaml --secrets /path/to/secrets.yaml
```
@@ -133,10 +137,14 @@ $ librofm-downloader
```bash
# Option 1: Delete and let it rebuild
+rm ~/.config/librofm-downloader/download_history.json
+librofm-downloader
+
+# Option 2: If using CWD-based history
rm download_history.json
librofm-downloader
-# Option 2: Fix the JSON manually (if you know what's in there)
+# Option 3: Fix the JSON manually (if you know what's in there)
# Check for trailing commas, missing braces, etc.
```
@@ -147,7 +155,10 @@ librofm-downloader
**Check:**
```bash
-# See what's recorded
+# See what's recorded (XDG location)
+cat ~/.config/librofm-downloader/download_history.json | python -m json.tool
+
+# Or if using CWD-based history
cat download_history.json | python -m json.tool
# Look for the ISBN of the book that's re-downloading
diff --git a/librofm_downloader/cli.py b/librofm_downloader/cli.py
index f4387f1..db1a709 100644
--- a/librofm_downloader/cli.py
+++ b/librofm_downloader/cli.py
@@ -5,7 +5,7 @@ from pathlib import Path
from rich.console import Console
-from librofm_downloader.config import load_config, ConfigError
+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
@@ -16,9 +16,9 @@ console = Console()
def run(
- config_path: str = "config.yaml",
- secrets_path: str = "secrets.yaml",
- history_path: str = "download_history.json",
+ config_path: str | None = None,
+ secrets_path: str | None = None,
+ history_path: str | None = None,
verbose: bool = False,
limit: int = 0,
workers: int = 0,
@@ -38,20 +38,45 @@ def run(
"""
try:
- if verbose:
- console.print("[dim]── config ──────────────────────────────────────[/dim]")
- console.print(f" config: {config_path}")
- console.print(f" secrets: {secrets_path}")
- console.print(f" history: {history_path}")
+ # 0. Resolve history path (XDG → CWD, default to XDG location)
+ if history_path is None:
+ resolved = _resolve_config_file("download_history.json")
+ if resolved is not None:
+ history_path = str(resolved)
+ else:
+ from os import environ
+ home = Path(environ.get("HOME", "~")).expanduser()
+ xdg_dir = home / ".config" / "librofm-downloader"
+ xdg_dir.mkdir(parents=True, exist_ok=True)
+ history_path = str(xdg_dir / "download_history.json")
# 1. Load config
try:
config = load_config(config_path, secrets_path)
+ if config._config_path is None:
+ searched = [
+ "~/.config/librofm-downloader/config.yaml",
+ "./config.yaml",
+ ]
+ console.print(
+ f"[yellow]config.yaml not found in {' → '.join(searched)}. "
+ f"Using built-in defaults.[/yellow]"
+ )
except ConfigError as exc:
console.print(f"[red]Config error:[/red] {exc}")
return 1
if verbose:
+ console.print("[dim]── config ──────────────────────────────────────[/dim]")
+ cfg_display = config._config_path if config._config_path else "(built-in defaults)"
+ # Determine resolved secrets path
+ secrets_display = secrets_path
+ if secrets_path is None:
+ resolved_secrets = _resolve_config_file("secrets.yaml")
+ secrets_display = resolved_secrets or "(not found)"
+ console.print(f" config: {cfg_display}")
+ console.print(f" secrets: {secrets_display}")
+ console.print(f" history: {history_path}")
console.print(f" format: {config.format}")
console.print(f" output: {config.output_dir}")
console.print(f" extras: {config.download_extras}")
@@ -171,9 +196,9 @@ if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Download audiobooks from Libro.fm")
- parser.add_argument("--config", default="config.yaml", help="Path to config.yaml")
- parser.add_argument("--secrets", default="secrets.yaml", help="Path to secrets.yaml")
- parser.add_argument("--history", default="download_history.json", help="Path to download history JSON")
+ parser.add_argument("--config", default=None, help="Path to config.yaml (default: search XDG then CWD)")
+ parser.add_argument("--secrets", default=None, help="Path to secrets.yaml (default: search XDG then CWD)")
+ parser.add_argument("--history", default=None, help="Path to download history JSON (default: search XDG then CWD)")
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output (URLs, sizes, tracebacks)")
parser.add_argument(
"--limit",
diff --git a/librofm_downloader/config.py b/librofm_downloader/config.py
index f4c3ac8..9d21b9b 100644
--- a/librofm_downloader/config.py
+++ b/librofm_downloader/config.py
@@ -16,6 +16,7 @@ class Config:
output_dir: str
download_extras: bool
download_covers: bool
+ _config_path: Path | None = None # None = defaulted (file missing)
workers: int = 3
@@ -39,19 +40,88 @@ class InvalidWorkersError(ConfigError):
"""Invalid parallel download worker count."""
+def _resolve_config_file(filename: str) -> Path | None:
+ """Resolve a config file by searching XDG then CWD.
+
+
def load_config(config_path: Path | str, secrets_path: Path | str) -> Config:
"""Load config.yaml + secrets.yaml, merge, validate, and return Config."""
config_path = Path(config_path)
secrets_path = Path(secrets_path)
- with config_path.open() as f:
- config_yaml = yaml.safe_load(f) or {}
+ Searches ``~/.config/librofm-downloader/`` first, then falls back to
+ the current working directory. Auto-creates the XDG parent directory
+ on demand.
+
+ Returns:
+ Resolved :class:`Path` if found, ``None`` if absent from both locations.
+ """
+ from os import environ # noqa: S405 – we only read HOME
+
+ home = Path(environ.get("HOME", "~")).expanduser()
+ xdg_path = home / ".config" / "librofm-downloader" / filename
+ xdg_path.parent.mkdir(parents=True, exist_ok=True)
+
+ if xdg_path.is_file():
+ return xdg_path.resolve()
+
+ cwd_path = Path(filename).resolve()
+ if cwd_path.is_file():
+ return cwd_path
+
+ return None
+
+
+
+def load_config(
+ config_path: Path | str | None,
+ secrets_path: Path | str | None,
+) -> Config:
+ """Load config.yaml + secrets.yaml, merge, validate, and return Config.
+
+ When either path is ``None``, searches XDG then CWD via
+ :func:`_resolve_config_file`. Missing config.yaml is non-fatal
+ (returns fully-defaulted :class:`Config`). Missing secrets.yaml is
+ fatal (raises :class:`ConfigError`).
+ """
+ # Resolve None paths → search XDG then CWD
+ if config_path is None:
+ config_path = _resolve_config_file("config.yaml")
+ if secrets_path is None:
+ secrets_path = _resolve_config_file("secrets.yaml")
+
+ # Load config.yaml (non-fatal if missing)
+ config_yaml: dict = {}
+ if config_path is not None:
+ try:
+ with Path(config_path).open() as f:
+ config_yaml = yaml.safe_load(f) or {}
+ except (FileNotFoundError, OSError) as exc:
+ raise ConfigError(
+ f"Cannot read config file '{config_path}': {exc}"
+ ) from exc
# Reject credentials in config.yaml
_check_no_credentials_in_config(config_yaml)
- with secrets_path.open() as f:
- secrets_yaml = yaml.safe_load(f) or {}
+ # Load secrets.yaml (fatal if missing)
+ if secrets_path is None:
+ searched = [
+ "~/.config/librofm-downloader/secrets.yaml",
+ "./secrets.yaml",
+ ]
+ raise ConfigError(
+ f"Missing secrets.yaml. Searched: {' → '.join(searched)}. "
+ f"Create one with your Libro.fm username and password."
+ )
+
+ try:
+ with Path(secrets_path).open() as f:
+ secrets_yaml = yaml.safe_load(f) or {}
+ except (FileNotFoundError, OSError) as exc:
+ raise ConfigError(
+ f"Cannot read secrets file '{secrets_path}': {exc}"
+ ) from exc
# Deep-merge secrets over config
merged = _deep_merge(config_yaml, secrets_yaml)
@@ -75,10 +145,10 @@ def load_config(config_path: Path | str, secrets_path: Path | str) -> Config:
output_dir=librofm.get("output_dir", "./audiobooks"),
download_extras=librofm.get("download_extras", True),
download_covers=librofm.get("download_covers", True),
+ _config_path=config_path,
workers=librofm.get("workers", 3),
)
-
def _deep_merge(base: dict, override: dict) -> dict:
"""Recursively merge override into base. Override wins on conflict."""
result = base.copy()
diff --git a/pyproject.toml b/pyproject.toml
index f3a7eb0..8de0144 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "librofm-downloader"
-version = "0.1.0"
+version = "1.1.0"
description = "Download owned audiobooks from your Libro.fm account"
readme = "README.md"
license = "MIT"
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 348d010..2884a7d 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -647,6 +647,229 @@ class TestAllBooksFailExitCode:
assert mock_download.call_count == 3
+# ---------------------------------------------------------------------------
+# Issue #23: XDG path resolution wired into CLI
+# ---------------------------------------------------------------------------
+
+
+class TestCLIHistoryResolution:
+ """History path resolves via XDG → CWD when not explicitly provided."""
+
+ def test_history_defaults_to_xdg_location(self, tmp_path, monkeypatch):
+ """run() with history_path=None → history resolves to XDG path."""
+ xdg_dir = tmp_path / ".config" / "librofm-downloader"
+ xdg_dir.mkdir(parents=True)
+ (xdg_dir / "download_history.json").write_text("{}")
+
+ cwd = tmp_path / "cwd"
+ cwd.mkdir()
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(cwd)
+
+ with (
+ patch("librofm_downloader.cli.load_config") as mock_config,
+ patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
+ patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
+ ):
+ mock_config.return_value.username = "alice"
+ mock_config.return_value.password = "secret"
+ mock_config.return_value._config_path = None
+ mock_config.return_value.output_dir = "./audiobooks"
+
+ mock_instance = mock_client_cls.return_value
+ mock_instance.authenticate.return_value = "tok"
+ mock_instance.fetch_library.return_value = []
+
+ exit_code = run(
+ config_path=None,
+ secrets_path=None,
+ history_path=None,
+ )
+
+ assert exit_code == 0
+
+ # Verify DownloadHistory received the XDG path
+ history_arg = mock_history_cls.call_args[0][0]
+ assert "librofm-downloader" in str(history_arg)
+ assert "download_history.json" in str(history_arg)
+
+ def test_history_defaults_to_xdg_when_not_found_anywhere(self, tmp_path, monkeypatch):
+ """No download_history.json anywhere → defaults to XDG location."""
+ cwd = tmp_path / "cwd"
+ cwd.mkdir()
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(cwd)
+
+ with (
+ patch("librofm_downloader.cli.load_config") as mock_config,
+ patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
+ patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
+ ):
+ mock_config.return_value.username = "alice"
+ mock_config.return_value.password = "secret"
+ mock_config.return_value._config_path = None
+ mock_config.return_value.output_dir = "./audiobooks"
+
+ mock_instance = mock_client_cls.return_value
+ mock_instance.authenticate.return_value = "tok"
+ mock_instance.fetch_library.return_value = []
+
+ exit_code = run(history_path=None)
+
+ assert exit_code == 0
+
+ # Should default to XDG location even though file doesn't exist
+ history_arg = mock_history_cls.call_args[0][0]
+ assert "librofm-downloader" in str(history_arg)
+ assert ".config" in str(history_arg)
+ assert "download_history.json" in str(history_arg)
+
+ def test_explicit_history_path_bypasses_resolution(self, tmp_path, monkeypatch):
+ """Explicit --history flag uses the exact path provided."""
+ with (
+ patch("librofm_downloader.cli.load_config") as mock_config,
+ patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
+ patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
+ ):
+ mock_config.return_value.username = "alice"
+ mock_config.return_value.password = "secret"
+ mock_config.return_value._config_path = None
+ mock_config.return_value.output_dir = "./audiobooks"
+
+ mock_instance = mock_client_cls.return_value
+ mock_instance.authenticate.return_value = "tok"
+ mock_instance.fetch_library.return_value = []
+
+ exit_code = run(history_path="/custom/my_history.json")
+
+ assert exit_code == 0
+
+ history_arg = mock_history_cls.call_args[0][0]
+ assert str(history_arg) == "/custom/my_history.json"
+
+
+
+class TestCLIConfigResolutionMessages:
+ """CLI messages about config resolution."""
+
+ def test_missing_config_message_includes_searched_paths(self, tmp_path, monkeypatch, capsys):
+ """config.yaml not found → message lists XDG and CWD paths."""
+ xdg_dir = tmp_path / ".config" / "librofm-downloader"
+ xdg_dir.mkdir(parents=True)
+ (xdg_dir / "secrets.yaml").write_text(
+ "librofm:\n username: alice\n password: secret\n"
+ )
+
+ cwd = tmp_path / "cwd"
+ cwd.mkdir()
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(cwd)
+
+ with (
+ patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
+ patch("librofm_downloader.cli.download_book"),
+ ):
+ mock_instance = mock_client_cls.return_value
+ mock_instance.authenticate.return_value = "tok"
+ mock_instance.fetch_library.return_value = []
+
+ exit_code = run(config_path=None, secrets_path=None, history_path=None)
+
+ assert exit_code == 0
+ output = capsys.readouterr().out
+ assert "config.yaml not found" in output
+ assert ".config" in output or "librofm-downloader" in output
+ assert "Using built-in defaults" in output
+
+ def test_verbose_shows_resolved_paths(self, tmp_path, monkeypatch, capsys):
+ """--verbose shows the actual resolved file paths after loading config."""
+ xdg_dir = tmp_path / ".config" / "librofm-downloader"
+ xdg_dir.mkdir(parents=True)
+ (xdg_dir / "secrets.yaml").write_text(
+ "librofm:\n username: alice\n password: secret\n"
+ )
+ (xdg_dir / "download_history.json").write_text("{}")
+
+ cwd = tmp_path / "cwd"
+ cwd.mkdir()
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(cwd)
+
+ with (
+ patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
+ patch("librofm_downloader.cli.download_book"),
+ ):
+ mock_instance = mock_client_cls.return_value
+ mock_instance.authenticate.return_value = "tok"
+ mock_instance.fetch_library.return_value = []
+
+ exit_code = run(
+ config_path=None,
+ secrets_path=None,
+ history_path=None,
+ verbose=True,
+ )
+
+ assert exit_code == 0
+ output = capsys.readouterr().out.lower()
+ # Verbose should show the resolved XDG paths
+ assert "secrets" in output
+ assert "history" in output
+ assert "librofm-downloader" in output
+
+
+
+class TestCLIMissingFilesErrors:
+ """Error handling when files are missing."""
+
+ def test_empty_home_clean_secrets_error(self, tmp_path, monkeypatch, capsys):
+ """No files anywhere → clean error about missing secrets, exit 1."""
+ cwd = tmp_path / "cwd"
+ cwd.mkdir()
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(cwd)
+
+ exit_code = run(config_path=None, secrets_path=None, history_path=None)
+
+ assert exit_code == 1
+ output = capsys.readouterr().out
+ assert "secrets.yaml" in output
+ assert "Traceback" not in output
+
+ def test_only_secrets_in_xdg_works(self, tmp_path, monkeypatch, capsys):
+ """Secrets in XDG only → defaults work, 'using built-in defaults' message visible."""
+ xdg_dir = tmp_path / ".config" / "librofm-downloader"
+ xdg_dir.mkdir(parents=True)
+ (xdg_dir / "secrets.yaml").write_text(
+ "librofm:\n username: alice\n password: secret\n"
+ )
+
+ cwd = tmp_path / "cwd"
+ cwd.mkdir()
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(cwd)
+
+ with (
+ patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
+ patch("librofm_downloader.cli.download_book"),
+ ):
+ mock_instance = mock_client_cls.return_value
+ mock_instance.authenticate.return_value = "tok"
+ mock_instance.fetch_library.return_value = []
+
+ exit_code = run(config_path=None, secrets_path=None, history_path=None)
+
+ assert exit_code == 0
+ output = capsys.readouterr().out
+ assert "Using built-in defaults" in output
+
+
# ---------------------------------------------------------------------------
# Issue #12: workers config field + --workers CLI flag
# ---------------------------------------------------------------------------
diff --git a/tests/test_config.py b/tests/test_config.py
index c91ace7..3cccc00 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -6,6 +6,12 @@ import pytest
from librofm_downloader.config import (
load_config,
+ _resolve_config_file,
+ Config,
+ ConfigError,
+ CredentialsInConfigError,
+ load_config,
+ _resolve_config_file,
Config,
CredentialsInConfigError,
MissingFieldError,
@@ -275,4 +281,154 @@ class TestEdgeCases:
)
# config_minimal has no format, so it gets default
# We just verify it doesn't raise for valid formats
- assert config.format in ("m4b_mp3_fallback", "mp3_only", "m4b_only")
\ No newline at end of file
+ assert config.format in ("m4b_mp3_fallback", "mp3_only", "m4b_only")
+
+
+class TestResolveConfigFile:
+ """XDG-then-CWD path resolution for config files."""
+
+ def test_returns_path_when_file_in_xdg(self, tmp_path, monkeypatch):
+ """File found in XDG dir → returns resolved Path."""
+ xdg_dir = tmp_path / ".config" / "librofm-downloader"
+ xdg_dir.mkdir(parents=True)
+ (xdg_dir / "config.yaml").write_text("librofm:\n format: m4b_only\n")
+
+ (tmp_path / "cwd").mkdir(exist_ok=True)
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(tmp_path / "cwd") # CWD has no file
+
+ result = _resolve_config_file("config.yaml")
+
+ assert result is not None
+ assert result.name == "config.yaml"
+ assert "librofm-downloader" in str(result)
+
+ def test_returns_path_when_file_only_in_cwd(self, tmp_path, monkeypatch):
+ """File only in CWD (not XDG) → returns CWD Path."""
+ (tmp_path / "config.yaml").write_text("librofm:\n format: mp3_only\n")
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(tmp_path) # CWD has the file, XDG is empty
+
+ result = _resolve_config_file("config.yaml")
+
+ assert result is not None
+ assert result.name == "config.yaml"
+ # Should be resolved from CWD, not XDG
+ assert ".config" not in str(result)
+
+ def test_xdg_wins_when_both_present(self, tmp_path, monkeypatch):
+ """File in both XDG and CWD → XDG path takes priority."""
+ xdg_dir = tmp_path / ".config" / "librofm-downloader"
+ xdg_dir.mkdir(parents=True)
+ (xdg_dir / "config.yaml").write_text("xdg_version\n")
+
+ (tmp_path / "config.yaml").write_text("cwd_version\n")
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+
+ result = _resolve_config_file("config.yaml")
+
+ assert result is not None
+ assert "librofm-downloader" in str(result) # XDG path
+ assert result.read_text() == "xdg_version\n"
+
+ def test_returns_none_when_file_absent_from_both(self, tmp_path, monkeypatch):
+ """File missing from XDG and CWD → returns None."""
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+
+ result = _resolve_config_file("config.yaml")
+
+ assert result is None
+
+ def test_xdg_directory_auto_created(self, tmp_path, monkeypatch):
+ """XDG parent dir is created even when file is absent."""
+ xdg_parent = tmp_path / ".config" / "librofm-downloader"
+ assert not xdg_parent.exists()
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+
+ _resolve_config_file("config.yaml")
+
+ assert xdg_parent.is_dir()
+
+
+class TestLoadConfigWithResolution:
+ """load_config wired to _resolve_config_file for None paths."""
+
+ def test_secrets_only_returns_defaulted_config(self, tmp_path, monkeypatch):
+ """config.yaml missing, secrets.yaml present → defaulted Config + creds."""
+ xdg_dir = tmp_path / ".config" / "librofm-downloader"
+ xdg_dir.mkdir(parents=True)
+ (xdg_dir / "secrets.yaml").write_text(
+ "librofm:\n username: alice\n password: s3cret\n"
+ )
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+
+ config = load_config(None, None)
+
+ # Credentials from secrets
+ assert config.username == "alice"
+ assert config.password == "s3cret"
+ # Built-in defaults (config.yaml was missing)
+ assert config.format == "m4b_mp3_fallback"
+ assert config.output_dir == "./audiobooks"
+ assert config.download_extras is True
+ assert config.download_covers is True
+
+ def test_neither_file_raises_error_with_searched_paths(self, tmp_path, monkeypatch):
+ """Both files missing → ConfigError listing every path searched."""
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+
+ with pytest.raises(ConfigError) as exc_info:
+ load_config(None, None)
+
+ msg = str(exc_info.value)
+ assert "secrets.yaml" in msg
+ assert "librofm-downloader" in msg or ".config" in msg
+
+ def test_explicit_config_path_bypasses_search(self, tmp_path, monkeypatch):
+ """Explicit config path → used as-is; secrets still searches if None."""
+ # Explicit config file
+ explicit_config = tmp_path / "my_config.yaml"
+ explicit_config.write_text(
+ "librofm:\n format: mp3_only\n output_dir: ./custom\n"
+ )
+
+ # Secrets only in XDG
+ xdg_dir = tmp_path / ".config" / "librofm-downloader"
+ xdg_dir.mkdir(parents=True)
+ (xdg_dir / "secrets.yaml").write_text(
+ "librofm:\n username: bob\n password: p4ss\n"
+ )
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+
+ config = load_config(explicit_config, None)
+
+ assert config.format == "mp3_only" # from explicit config
+ assert config.output_dir == "./custom" # from explicit config
+ assert config.username == "bob" # from resolved secrets
+
+ def test_missing_config_provides_detectable_signal(self, tmp_path, monkeypatch):
+ """Missing config.yaml → caller can detect defaults were used."""
+ xdg_dir = tmp_path / ".config" / "librofm-downloader"
+ xdg_dir.mkdir(parents=True)
+ (xdg_dir / "secrets.yaml").write_text(
+ "librofm:\n username: carol\n password: pw\n"
+ )
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.chdir(tmp_path)
+
+ config = load_config(None, None)
+
+ # Signal: _config_path is None when config.yaml was missing
+ assert config._config_path is None
\ No newline at end of file