12 Commits
Author SHA1 Message Date
AlexKucera 90432cac21 Merge branch 'release/1.4.0' into develop 2026-06-06 18:29:13 +02:00
AlexKucera 4e96ca1969 Merge branch 'release/1.4.0' into develop 2026-06-06 18:28:46 +02:00
AlexKucera 507fbc3204 docs: add 1.1-1.4 features to MkDocs and README
Cover parallel downloads, interactive selection (--select),
chapter renaming (--rename-chapters), XDG config paths,
Ctrl+C handling, and thread-safe history across all docs:
index, quickstart, configuration, cli-usage, format-strategies,
troubleshooting, and README.
2026-06-06 18:27:23 +02:00
AlexKucera e2fa3377f5 docs(changelog): reorganize entries by version tags
Restructure CHANGELOG.md to match git tags (1.0.0 through 1.4.0).
Remove Unreleased section (all changes are tagged). Sort entries
into Added/Fixed/Refactored/Documentation sections per version.
Add standard Keep a Changelog header.
2026-06-06 18:17:07 +02:00
AlexKucera 11d677fb24 Merge pull request #49 from AlexKucera/feature/chooseBooks
Enables interactive book selection via --select
2026-06-06 18:09:50 +02:00
AlexKucera b9d90b7618 fix(sync_run): show limit-bypass notice regardless of verbose
The --limit-superseded message was only printed when verbose=True,
so users running --select --limit 5 without -v got no indication
their flag was silently ignored. Make the notice unconditional.
2026-06-06 17:33:31 +02:00
AlexKucera 4e25fb27df fix(sync_run): check stdin not stdout for TTY guard
The --select TTY guard used sys.stdout.isatty(), but interactive
prompts read from stdin. This caused two failure modes:

- Redirecting stdout (e.g. | tee log.txt) blocked --select even
  though the keyboard was available
- With stdin piped in CI, stdout could still be a TTY, allowing
  the prompt to proceed and block forever on absent input
2026-06-06 17:30:48 +02:00
AlexKucera 77712951d0 docs(orchestrator): fix raw_books type annotation and changelog prose
The raw_books parameter accepts list[dict | Book] since the
selector wiring (issue #48), but the annotation still said
list[dict]. Also restore the missing opening sentence of the
selector changelog entry that was truncated.
2026-06-06 17:28:44 +02:00
AlexKucera fa1543e3d7 feat(sync_run): wire --select into download pipeline
Replace select_mode stub with real selection pipeline:
- TTY guard: non-interactive terminals get fatal_error exit
- Convert filtered dicts to Books via from_library_row()
- Call select_books(), pass selected Books to orchestrator
- Orchestrator accepts pre-converted Book objects (isinstance check)
- --limit bypassed when --select is active, with verbose note
- Remove "[not implemented]" from --select help text

Closes #48
2026-06-06 12:13:56 +02:00
AlexKucera 0d555e4628 Merge remote-tracking branch 'origin/feature/chooseBooks' into feature/chooseBooks 2026-06-06 11:55:16 +02:00
AlexKucera 37f10f9b49 feat(selector): add interactive book selection module
New selector.py with select_books() and _format_row().
Questionary checkbox prompt, all unchecked by default,
confirmation summary + y/N, original order preservation,
Ctrl+C propagation via unsafe_ask(). 9 tests.

Closes #47
2026-06-06 11:55:08 +02:00
AlexKucera 922e7fe6bb feat(selector): add interactive book selection module
New selector.py with select_books() and _format_row().
Questionary checkbox prompt, all unchecked by default,
confirmation summary + y/N, original order preservation,
Ctrl+C propagation via unsafe_ask(). 9 tests.

Closes #47
2026-06-06 11:53:03 +02:00
20 changed files with 840 additions and 152 deletions

No files matched your search

+3 -1
View File
@@ -8,6 +8,8 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
<!-- write-log: session-log-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-06-06 | issue | [20260606-issue48-wire-selector-into-sync-run-pipeline_log.md](docs/devlog/20260606-issue48-wire-selector-into-sync-run-pipeline_log.md) | **Issue #48 Complete:** Wired `select_books()` into `sync_run.py` pipeline. TTY guard, dict→Book conversion, orchestrator Book passthrough (no double-conversion), `--limit` bypass. Updated CLI help text. **+6 tests, 304 total** · **All pass** · **11/11 AC** |
| 2026-06-06 | issue | [20260606-issue47-interactive-book-selection-selector-module_log.md](docs/devlog/20260606-issue47-interactive-book-selection-selector-module_log.md) | **Issue #47 Complete:** `selector.py` module with `select_books()` + `_format_row()`. Questionary checkbox prompt, confirmation summary, order preservation, Ctrl+C propagation. **+9 tests** · **All pass** · **10/10 AC** |
| 2026-06-05 | issue | [20260605-issue44-sync-run-injectable-pipeline_log.md](docs/devlog/20260605-issue44-sync-run-injectable-pipeline_log.md) | **Issue #44 Complete:** Refactored `sync_run()` to injectable pipeline. 4 DI seams (session/history/reporter/download_fn), extracted 2 helpers (`_print_verbose_config`, `_resolve_history_path`), simplified closure. **+10 tests, 172 total** · **All pass** · **7/7 AC** |
| 2026-06-05 | issue | [20260605-issue45-consolidate-syncrunresult-orchestratorresult_log.md](docs/devlog/20260605-issue45-consolidate-syncrunresult-orchestratorresult_log.md) | **Issue #45 Complete:** Consolidated `SyncRunResult`/`OrchestratorResult` via composition. `SyncRunResult` wraps `OrchestratorResult` + 6 delegating properties. Bridge copy code eliminated. **+2 tests, 174 total** · **All pass** · **4/4 AC** |
| 2026-06-05 | issue | [20260605-issue43-test-reorganization-cleanup-pass_log.md](docs/devlog/20260605-issue43-test-reorganization-cleanup-pass_log.md) | **Issue #43 Complete:** Test reorganization cleanup. Deleted 13 dup path classes from downloader, moved 2 integration classes progress→sync_run, removed duplicate `TestParallelProgressCallbackWiring`, rescued orphaned method. **−470 net test lines, 374 tests** · **168/168 pass on modified files** · **5/5 AC** |
@@ -51,7 +53,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **librofm-downloader** (2023 symbols, 3834 relationships, 13 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **librofm-downloader** (2116 symbols, 3907 relationships, 15 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
+135 -117
View File
@@ -1,18 +1,34 @@
# Changelog
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.4.0] - 2026-06-06
### Added
- **selector:** Add interactive book selection module `selector.py` with
`select_books()` (questionary checkbox prompt, confirmation summary) and
`_format_row()` helper. Uses `unsafe_ask()` for Ctrl+C propagation.
Row format: `N. Title — Author [Series #N]`.
9 tests. Closes #47.
- **sync_run:** Wire `--select` into download pipeline. TTY guard
(non-interactive terminals get error exit 1), dict→Book conversion
via `from_library_row()`, selected Books pass to orchestrator
without double-conversion, `--limit` bypassed with notice.
6 integration tests. Closes #48.
### Fixed
- **downloader:** Fix progress bar exceeding 100% on resumed downloads.
`Content-Length` from a Range response covers only remaining bytes;
now adds `resume_from` for the true total.
- **session:** Stop reaching into `httpx.Client._transport` (private API).
Transport reference is now stored at construction time.
- **sync_run:** Show --limit-superseded notice unconditionally when
`--select` is active. Previously the message was gated behind
`--verbose`, so non-verbose users had no indication their flag
was silently ignored.
- **sync_run:** Check stdin (not stdout) for TTY guard, fixing the
interactive selection check in non-interactive environments.
## [1.3.0] - 2026-06-06
### Added
@@ -20,12 +36,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
files with chapter titles from the download manifest. Natural sort by
numeric prefix, auto zero-padding, null/blank title fallback, sanitization
via existing `sanitize()`. 11 tests. Closes #32.
- **config:** Add `rename_chapters` boolean field to Config dataclass with default
`True`. Read from YAML config, threaded through CLI (`--rename-chapters` flag)
and `sync_run()` resolution (CLI True → config value). 5 new tests, 223 total.
Closes #33.
- **downloader:** Wire `rename_chapters()` into download pipeline.
`_download_mp3()` returns `(output_dir, tracks)` tuple; `download_book()`
accepts `rename_chapters` kwarg; new `_rename_and_log()` helper calls rename
@@ -33,6 +47,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
feedback: "Renamed N chapter(s) for 'Book' → 'example.mp3'".
`sync_run.py` closure threads resolved flag through to `download_book()`.
6 new integration tests, ~229 total. Closes #34.
- **downloader:** Integration tests for rename_chapters pipeline wiring.
Edge cases: special chars, single-track, 105-chapter 3-digit padding.
Closes #35.
### Fixed
- **downloader:** Fix progress bar exceeding 100% on resumed downloads.
`Content-Length` from a Range response covers only remaining bytes;
now adds `resume_from` for the true total.
- **downloader:** Fix missing `Callable` import in module scope.
- **session:** Stop reaching into `httpx.Client._transport` (private API).
Transport reference is now stored at construction time.
### Refactored
@@ -41,12 +67,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
it on reporter objects as shared state. Remove `cancel_event` attribute from
both `PlainTextReporter` and `ProgressReporter`. 429 tests (+5 net).
Closes #39.
- **session:** Expose public `transport` property on `LibroFmSession` returning
the underlying httpx transport. Update sole call site in `downloader.py` from
`session._client._transport` to `session.transport`. 2 new tests, 425 total.
Closes #38.
- **downloader:** Extract `_stream_to_file()` private helper from the
duplicated ~30-line chunked-download loop in `download_m4b()`,
`download_zip_part()`, `_download_cover()`, and `_download_pdf()`. All
@@ -54,32 +78,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
shared helper. 5 new TDD tests (fresh download, resume, cancel
mid-stream, progress callback, error propagation). 224 total tests.
Net -22 lines in downloader.py. Closes #41.
- **downloader:** Extract `_finalize_download()` from format-specific branches
to consolidate post-download logic into a single helper.
- **session:** Rename LibroFmClient → LibroFmSession, relocate to
session.py, inject transport at construction time. Old client.py is now
a deprecated re-export shim. Endpoint signatures slimmed from 4-5 params
to ≤3 (transport removed). 227 tests pass (+17 new). Closes #27.
- **path:** Introduce OutputPlan frozen dataclass and resolve_output_plan()
function to centralize all path computation for a book. Download functions
now consume pre-resolved plan fields instead of computing paths inline,
eliminating duplicated audio-filename logic. 237 tests pass (+10 new).
Closes #28.
- **downloader:** Shrink download_book() from 9 parameters to 4
domain-aligned params (book, session, plan, reporter) returning a frozen
DownloadResult dataclass. Move history writing to caller (cli closure).
Add format_strategy to OutputPlan, wire cancel_event through reporter,
extract transport from session. Remove config from accompanying_files.
368 tests pass (+15 new). Closes #29.
- **progress:** Return bound callable from start_download() instead of raw
task_id. Task identity is fully internal to progress.py. Orchestrator
no longer creates per-book closures — passes the bound callback
directly. download_book() accepts optional progress= kwarg. Public
update() drops task_id param. 382 tests pass (+11 new). Closes #30.
- **cli/sync-run:** Extract entire download pipeline from cli.run() into
standalone sync_run() function in new sync_run.py module. Introduce
SyncRunResult frozen dataclass (replaces OrchestratorResult as public
@@ -88,8 +108,62 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
test_cli.py to test_sync_run.py (43 total + 10 CLI-only tests).
Add select_mode stub (ADR #6 branch point) and fatal_error field for
exit-code translation. 374 tests pass. Closes #31.
- **sync-run:** Refactored `sync_run()` to injectable pipeline. 4 DI seams
(session/history/reporter/download_fn), extracted 2 helpers
(`_print_verbose_config`, `_resolve_history_path`), simplified closure.
+10 tests. Closes #44.
- **sync-run:** Consolidated `SyncRunResult`/`OrchestratorResult` via
composition. `SyncRunResult` wraps `OrchestratorResult` + 6 delegating
properties. Bridge copy code eliminated. +2 tests. Closes #45.
- **history:** Relocate `_write_history()` from `downloader.py` → `history.py`.
Updated all import sites. +1 net test. Closes #40.
- **tests:** Reorganize test files to match production modules. Deleted 13
duplicate path classes, moved 2 integration classes, removed duplicate
`TestParallelProgressCallbackWiring`, rescued orphaned method. −470 net
test lines, 374 tests. Closes #43.
- **book:** Extract Book dataclass + `from_library_row()` and path logic
(`sanitize`, `resolve_path`, `needs_subdirectory`) from monolithic
`downloader.py` into `book.py` and `path.py`. 79 new tests. Closes #26.
## [1.2.0] - 2026-06-04
### Added
- **config:** Parallel download worker count: `workers` field on Config dataclass
(default 3), `InvalidWorkersError` validation for values < 1, YAML parsing
from `librofm.workers`, and `-w`/`--workers` CLI flag with three-layer
resolution (CLI > config > default). 6 new tests (179 total). Closes #12.
- **progress:** Per-book identity mapping for concurrent progress bars:
replace singleton `_current_task`/`_current_book` with bidirectional
`_tasks`/`_book_ids` dicts keyed by `id(book)`. `start_download()` now
returns `task_id`, `update()` accepts optional `task_id` kwarg with
backward-compat fallback to most-recent task. `complete()`/`fail()`
clean up both mappings. PlainTextReporter unchanged (already stateless).
10 new tests (194 total). Closes #14.
- **api:** Rate limit concurrent Libro.fm API calls with `threading.Semaphore(3)`.
CDN downloads bypass the limiter. 4 new tests (198 total). Closes #15.
- **orchestrator:** ThreadPoolExecutor-based parallel download engine:
`download_all_books()` replaces sequential for-loop in cli.py, submitting all
books as futures with per-future failure isolation. Returns `OrchestratorResult`
dataclass with stable-sorted counts, failed_books as (Book, reason) tuples,
and skipped_books as Book objects. `_raw_to_book()` conversion extracted from
cli.py. 20 new tests (218 total). Closes #16.
- **orchestrator:** Graceful Ctrl+C drain during parallel downloads:
first interrupt prints "Aborting...", drains in-flight downloads via
`executor.shutdown(wait=True)`, then re-raises for exit code 130; second
interrupt during drain force-quits immediately with
`shutdown(cancel_futures=True)`. 13 new integration tests covering
workers=1 regression parity, concurrent execution proof, summary ordering,
failure isolation, verbose overlap safety, double-Ctrl+C fast exit, and
partial file resume-safety after interrupt (231 total). Closes #17.
- **docs:** Update all documentation for parallel downloads. Closes #18.
### Fixed
- **history:** Make `DownloadHistory.write()` thread-safe with
`threading.Lock` so concurrent worker threads don't corrupt or lose
history entries during parallel downloads. Lock guards both in-memory
mutation and disk flush. 5 new tests (184 total). Closes #13.
- **progress:** Wire task_id through parallel progress callback.
All concurrent download updates went to the same (most recently started) bar
because `task_id` was never threaded from `start_download()` to `update()`.
@@ -113,138 +187,82 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [1.1.0] - 2026-06-04
### Added
- **config (closes #22):** XDG config path resolution with CWD fallback.
- **config:** 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.
`ConfigError`. XDG directory auto-created on demand. Closes #22.
- **cli:** 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.
with no traceback when secrets missing from all locations. Closes #23.
### Documentation
- **docs (closes #24):** Update all documentation for XDG path resolution.
- 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.
and README.md updated to reference XDG-first search. Closes #24.
## [1.0.0] - 2026-06-03
### Fixed
- **history:** Make `DownloadHistory.write()` thread-safe with
`threading.Lock` so concurrent worker threads don't corrupt or lose
history entries during parallel downloads. Lock guards both in-memory
mutation and disk flush. 5 new tests (184 total) (closes #13)
### Added
- **progress:** Per-book identity mapping for concurrent progress bars:
replace singleton `_current_task`/`_current_book` with bidirectional
`_tasks`/`_book_ids` dicts keyed by `id(book)`. `start_download()` now
returns `task_id`, `update()` accepts optional `task_id` kwarg with
backward-compat fallback to most-recent task. `complete()`/`fail()`
clean up both mappings. PlainTextReporter unchanged (already stateless).
10 new tests (194 total) (closes #14)
- **config:** Parallel download worker count: `workers` field on Config dataclass
(default 3), `InvalidWorkersError` validation for values < 1, YAML parsing
from `librofm.workers`, and `-w`/`--workers` CLI flag with three-layer
resolution (CLI > config > default). 6 new tests (179 total) (closes #12)
- **orchestrator:** ThreadPoolExecutor-based parallel download engine:
`download_all_books()` replaces sequential for-loop in cli.py, submitting all
books as futures with per-future failure isolation. Returns `OrchestratorResult`
dataclass with stable-sorted counts, failed_books as (Book, reason) tuples,
and skipped_books as Book objects. `_raw_to_book()` conversion extracted from
cli.py. 20 new tests (218 total) (closes #16)
- **orchestrator:** Graceful Ctrl+C drain during parallel downloads:
first interrupt prints "Aborting...", drains in-flight downloads via
`executor.shutdown(wait=True)`, then re-raises for exit code 130; second
interrupt during drain force-quits immediately with
`shutdown(cancel_futures=True)`. 13 new integration tests covering
workers=1 regression parity, concurrent execution proof, summary ordering,
failure isolation, verbose overlap safety, double-Ctrl+C fast exit, and
partial file resume-safety after interrupt (231 total) (closes #17)
- MP3 format fallback: download manifest fetch, ZIP part download+extraction
with .partial tracking and resume, format strategy selector (m4b_mp3_fallback,
mp3_only, m4b_only), and `--limit` CLI flag for capped downloads
## [1.0.0]] - 2026-06-03
### Documentation
- **docs site (closes #10):** MkDocs documentation with 8 pages — Quickstart,
Configuration Reference, Secrets, Path Patterns, Format Strategies, CLI Usage,
and Troubleshooting. Material theme, flat URLs, all code snippets verified
against implementation. Polished README with badges, features table, format
comparison, and project comparison note.
### Added
- MP3 format fallback: download manifest fetch, ZIP part download+extraction
with .partial tracking and resume, format strategy selector (m4b_mp3_fallback,
mp3_only, m4b_only), and `--limit` CLI flag for capped downloads
- Project scaffolding: pyproject.toml, package structure, test suite,
config module with YAML loading, secrets deep-merge, validation, and
defaults. Closes #2.
- OAuth2 client with password grant auth and paginated library fetch.
Download history tracking with corrupt JSON recovery. Closes #3.
- Path resolution with default conditional patterns and custom token
substitution. Filesystem-safe component sanitization (illegal chars,
control chars, colons). Immutable Book dataclass for typed book metadata.
Subdirectory decision logic based on PDF extras or cover art presence.
Closes #4.
- M4B download pipeline: streaming chunked download with .partial files,
atomic rename to .m4b, resume support via HTTP Range header
- `fetch_m4b_url()` client method for M4B download URL lookup
- `download_book()` orchestration: resolve path → query M4B → download →
write history; returns None when book has no M4B available
- Full CLI download loop with per-book status, summary counts, and --verbose
flag showing config/auth/library/download details
- `config.yaml` template and `secrets.yaml` gitignored credentials file
- 12 new tests covering M4B query, streaming download, resume, path
integration, subdirectory logic, history post-download, skip behavior,
and verbose output (109 total)
atomic rename to .m4b, resume support via HTTP Range header.
Closes #5.
- MP3 format fallback: download manifest fetch, ZIP part download+extraction
with .partial tracking and resume, format strategy selector
(m4b_mp3_fallback, mp3_only, m4b_only), and `--limit` CLI flag for
capped downloads. Closes #6.
- PDF extras and cover art download: `fetch_pdf_extra_url()` client
endpoint, `download_accompanying_files()` with config toggles
(`download_extras`, `download_covers`), streaming .partial → atomic
rename pattern, non-critical failure handling (warnings only), and
output structure verification (subdirectory vs flat layout)
output structure verification (subdirectory vs flat layout).
12 new tests. Closes #7.
- TTY-aware download reporting: rich progress bars with live %/ETA/speed/
file size for interactive terminals, plain log lines for pipes/cron,
Content-Length-driven total so percentage works from first chunk,
per-book failure isolation (one failed book doesn't stop batch),
and fatal error immediate-exit before download loop starts
- 12 new tests covering PDF URL fetch, cover/PDF download, .partial
cleanup, config toggle behavior, failure handling, and directory layout
(134 total)
and fatal error immediate-exit before download loop starts.
18 new tests. Closes #8.
- Enhanced summary: failed books listed with ISBN/title/reason, skipped
books listed with ISBN/title; both plain-text and rich/TTY reporters
- Graceful Ctrl+C handling: clean shutdown message instead of traceback,
exit code 130 (standard Unix SIGINT convention)
- 3 integration tests exercising full run() pipeline: happy path,
mixed result (download/skip/fail), fatal auth failure
- 12 new tests covering enhanced summary formatting, exit code semantics,
graceful shutdown, and integration scenarios (168 total)
books listed with ISBN/title; both plain-text and rich/TTY reporters.
Graceful Ctrl+C handling: clean shutdown message instead of traceback,
exit code 130 (standard Unix SIGINT convention). 3 integration tests.
Closes #9.
- MkDocs documentation site with 8 pages — Quickstart, Configuration
Reference, Secrets, Path Patterns, Format Strategies, CLI Usage, and
Troubleshooting. Material theme, flat URLs, all code snippets verified
against implementation. Polished README with badges, features table,
format comparison, and project comparison note. Closes #10.
### Fixed
- **downloader:** Path doubling: `resolve_path()` returns Author/Title but code
appended title again, producing nested folders like Title/Title/Title.m4b.
Also fix cover download: add Libro.fm headers to httpx client, normalize
protocol-relative URLs (//cdn → https://cdn)
- Library endpoint key mismatch: API returns "audiobooks" not "books"
- M4B endpoint key mismatch: API returns "m4b_url" not "url"
- Narrators nested under `audiobook_info.narrators` in API response
protocol-relative URLs (//cdn → https://cdn).
- Library endpoint key mismatch: API returns "audiobooks" not "books".
- M4B endpoint key mismatch: API returns "m4b_url" not "url".
- Narrators nested under `audiobook_info.narrators` in API response.
- ISBN type mismatch in history lookup: JSON keys are strings but API
returns ISBN as integer — added str() coercion in find/is_downloaded
- Missing download loop in CLI run() function (listed books but never downloaded)
### Changed
- Initial project scaffolding: pyproject.toml, package structure, test suite
- Config module with YAML loading, secrets deep-merge, validation, and defaults
- OAuth2 client with password grant auth and paginated library fetch
- Download history tracking with corrupt JSON recovery
- Path resolution with default conditional patterns and custom token substitution
- Filesystem-safe component sanitization (illegal chars, control chars, colons)
- Immutable Book dataclass for typed book metadata
- Subdirectory decision logic based on PDF extras or cover art presence
returns ISBN as integer — added str() coercion in find/is_downloaded.
- Missing download loop in CLI run() function (listed books but never downloaded).
+1 -1
View File
@@ -1,7 +1,7 @@
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **librofm-downloader** (2023 symbols, 3834 relationships, 13 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **librofm-downloader** (2116 symbols, 3907 relationships, 15 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
+5 -1
View File
@@ -10,14 +10,16 @@ No Docker. No JVM. Just Python and go.
## Features
- **Full library sync** — fetches every audiobook in your Libro.fm account with automatic pagination
- **Interactive book selection** — pick which books to download with `--select` (checkbox prompt)
- **M4B + MP3 formats** — downloads M4B (single file) or MP3 (ZIP parts extracted) with automatic fallback
- **Chapter renaming** — MP3 files renamed with chapter titles from the manifest (configurable)
- **Resume support** — interrupted downloads pick up where they left off via `.partial` files
- **Parallel downloads** — `ThreadPoolExecutor` downloads multiple books simultaneously; configurable via `--workers N` (default 3)
- **Cover art & PDF extras** — optional download of cover images and accompanying PDFs
- **Customizable output paths** — token-based patterns for organizing your library on disk
- **TTY-aware progress** — rich progress bars in your terminal, clean log lines in cron jobs
- **Download history** — tracks what's been downloaded so re-runs only fetch new books
- **Graceful failure isolation** — one failed book doesn't stop the rest
- **Parallel downloads** — `ThreadPoolExecutor` downloads multiple books simultaneously; configurable via `--workers N` (default 3)
## Quick Start
@@ -49,8 +51,10 @@ EOF
# 3. Run
librofm-downloader # default: 3 parallel workers
librofm-downloader --select # pick books interactively
librofm-downloader -w 5 # 5 parallel workers
librofm-downloader --workers 1 # sequential (1 worker)
librofm-downloader --limit 5 # only download 5 new books
```
## Documentation
@@ -0,0 +1,54 @@
# Issue #47: Interactive Book Selection — selector.py Module
> **Date:** 2026-06-06
> **Type:** issue
> **Reference:** [GitHub #47](https://github.com/AlexKucera/librofm-downloader/issues/47)
## Goal
Create `librofm_downloader/selector.py` with `select_books(books) -> list[Book]` — an interactive checkbox prompt using `questionary` that lets users pick which books to download. Includes `_format_row(book, index) -> str` helper for display formatting.
## What Was Done
- Added `questionary>=2.1.1` to `dependencies` in `pyproject.toml`
- Created `librofm_downloader/selector.py` with two functions:
- `_format_row(book, index)` — formats Book into `"N. Title — Author [Series #N]"` display string
- `select_books(books)` — opens questionary checkbox (all unchecked by default), zero-selection message, confirmation summary + y/N prompt, returns selected Books in original input order
- Created `tests/test_selector.py` with 9 TDD tests covering all acceptance criteria
- Used `unsafe_ask()` on the checkbox to propagate `KeyboardInterrupt` (instead of `.ask()` which catches it and returns `None`)
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Use `unsafe_ask()` for checkbox, `.ask()` for confirm | `questionary.Question.ask()` catches `KeyboardInterrupt` and returns `None`. Issue requires Ctrl+C during checkbox to propagate upstream to `sync_run`. Confirm prompt can safely swallow Ctrl+C (returns `None` → falsy → empty list). |
| Map display rows → Book via dict lookup | `questionary.checkbox().ask()` returns the choice strings, not indices. Build a `row_to_book` dict to map chosen strings back to Book objects. |
| Return in original input order via `id(b)` set | User may toggle checkboxes in any order. Filter original list by `id(b) in selected_set` to preserve input ordering. |
| Pin `questionary>=2.1.1` (not `>=1.10`) | `questionary 2.1.0` crashes with `prompt_toolkit>=3.0.50` due to `_fix_unecessary_blank_lines` accessing changed internal layout API (`VSplit.content` removed). Fixed in 2.1.1. |
| Test via `mock.patch("librofm_downloader.selector.questionary")` | Patch at the import site, not globally. Mock `checkbox().unsafe_ask()` and `confirm().ask()` return values to avoid real TUI rendering. Test external behavior (inputs→outputs), not which questionary methods were called. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| `AttributeError: 'VSplit' object has no attribute 'content'` on interactive test | `questionary 2.1.0` incompatible with `prompt_toolkit>=3.0.50`. Internal `_fix_unecessary_blank_lines` accesses removed `VSplit.content` attribute. | Upgraded to `questionary>=2.1.1`, pinned in `pyproject.toml` |
| Test mock returned `["C", "A"]` but impl expected formatted row strings | Mock values must match what `questionary.checkbox().unsafe_ask()` actually returns — the choice strings as provided to `choices=` parameter. | Changed mock to return `["3. C — Author", "1. A — Author"]` matching `_format_row` output |
| 11 pre-existing failures in `test_path.py` | `Config.__init__()` missing `rename_chapters` argument — unrelated to this issue | Not addressed (pre-existing, out of scope) |
## Files Changed
| File | Change Summary |
|------|---------------|
| `pyproject.toml` | Added `questionary>=2.1.1` to `dependencies` |
| `librofm_downloader/selector.py` | New module: `_format_row()` + `select_books()` |
| `tests/test_selector.py` | New test file: 9 tests (3 formatting + 6 selection flow) |
## Open Items & Next Steps
- [ ] Wire `select_books()` into `sync_run.py` pipeline (guarded by `--select` flag) — future issue
- [ ] 11 pre-existing `test_path.py` failures need fixing (Config missing `rename_chapters`)
- [ ] User interactive testing still pending (TUI requires real terminal)
---
*Log written by write-log skill*
@@ -0,0 +1,60 @@
# Issue #48: Wire Selector into sync_run Pipeline — TTY Guard, --limit Superseded, Integration Tests
> **Date:** 2026-06-06
> **Type:** issue
> **Reference:** [GitHub #48](https://github.com/AlexKucera/librofm-downloader/issues/48)
## Goal
Replace the `select_mode` stub in `sync_run.py` (which printed "not yet implemented" and returned) with the real selection pipeline: TTY guard, dict→Book conversion, call `select_books()`, pass selected Books to orchestrator without double-conversion, and ignore `--limit` when select mode is active.
## What Was Done
- Replaced `select_mode` stub in `sync_run.py` with full pipeline: TTY check → `from_library_row()` conversion → `select_books()` call → empty selection guard → pass selected Books to orchestrator
- Added `sys` import at module level (was inline `import sys as _sys`)
- Modified limit application to skip when `select_mode=True` (`if limit and not select_mode`)
- Added verbose note: "Selection mode active -- --limit superseded by manual selection."
- Modified `download_all_books()` in `orchestrator.py` to accept pre-converted `Book` objects via `isinstance` check — skips `from_library_row()` when elements are already `Book` instances
- Updated `--select` argparse help text from `"Interactive selection [not implemented]"` to `"Interactive book selection"`
- Updated `select_mode` docstring from "not yet implemented" to active status
- Added 5 integration tests in `test_sync_run.py` covering: no-TTY fatal error, all-caught-up with select, empty selection, selected→orchestrator flow, limit ignored
- Added 1 test in `test_orchestrator.py` for Book objects passthrough
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| `isinstance(raw, Book)` check in `download_all_books` | Backward-compatible: existing dict callers unaffected, select mode passes Book objects directly. Avoids double-conversion through `from_library_row()`. |
| Patch `librofm_downloader.selector.select_books` (not `sync_run.select_books`) | `select_books` is imported locally inside the `if select_mode:` branch, so patching at the source module works correctly with `unittest.mock.patch`. |
| `sys` import at module level | Cleaner than inline `import sys as _sys` alias. Used for TTY check (`sys.stdout.isatty()`). |
| Limit bypass: `if limit and not select_mode` | Single-line guard at the existing limit application point. Keeps limit logic in one place; no separate "restore limit" needed. |
| Verbose note uses `console.print` with `[dim]` | Consistent with existing verbose output styling in sync_run.py. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| `NameError: name '_from_library_row' is not defined` | Refactor renamed `from_library_row` import but left stale `_from_library_row` references in the list comprehension | Changed `_from_library_row` → `from_library_row` and `_select_books` → `select_books` to match the clean import names |
| `AttributeError: <module 'sync_run'> does not have the attribute 'select_books'` | Test patched at `librofm_downloader.sync_run.select_books` but `select_books` is imported locally inside `if select_mode:` block | Changed patch target to `librofm_downloader.selector.select_books` (the source module) |
| Pre-existing threading test hangs | `test_three_books_all_downloaded_sequential` and similar orchestrator tests hang due to ThreadPoolExecutor + Ctrl+C interaction | Not addressed (pre-existing, out of scope). Tests excluded via `-k` filter. |
## Files Changed
| File | Change Summary |
|------|---------------|
| `librofm_downloader/sync_run.py` | Replaced `select_mode` stub with full pipeline (TTY guard, Book conversion, select_books call, limit bypass, verbose note). Added `sys` import. Updated docstring. |
| `librofm_downloader/orchestrator.py` | `download_all_books()` now accepts `list[Book]` directly — `isinstance` check skips `from_library_row()` for pre-converted objects |
| `librofm_downloader/cli.py` | Updated `--select` help text: removed "[not implemented]" |
| `tests/test_sync_run.py` | Added 4 test classes (5 tests): `TestSyncRunSelectModeTTYGuard` (2), `TestSyncRunSelectModeEmptySelection` (1), `TestSyncRunSelectModeSelectedFlow` (1), `TestSyncRunSelectModeLimitIgnored` (1). Replaced old stub test. |
| `tests/test_orchestrator.py` | Added `TestDownloadAllBooksAcceptsBookObjects` (1 test): Book objects pass through without `from_library_row()` conversion |
## Open Items & Next Steps
- [ ] User interactive testing of `--select` flag in a real terminal (TUI requires real TTY)
- [ ] Pre-existing threading test hangs (6 tests in test_orchestrator.py) need investigation
- [ ] Pre-existing `test_path.py` failures (Config missing `rename_chapters`) need fixing
- [ ] Parent issue #20 may have remaining slices (e.g., HITL for --select)
---
*Log written by write-log skill*
+63
View File
@@ -17,6 +17,8 @@ librofm-downloader [OPTIONS]
| `--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 |
| `--rename-chapters` | | config | Rename extracted MP3 files with chapter titles |
| `--select` | | off | Interactive book selection (checkbox prompt) |
| `-w, --workers` N | | `3` | Number of parallel download workers (1 = sequential) |
### --verbose
@@ -86,6 +88,67 @@ Resolution order (CLI > config > default):
Set to `1` for behavior identical to the pre-parallelism sequential mode.
### --select
Launch an interactive book selection prompt before downloading:
```bash
# Pick which books to download from a checkbox list
librofm-downloader --select
```
**Flow:**
1. Tool fetches your library and filters already-downloaded books
2. A checkbox prompt appears — use **space** to toggle, arrows to navigate, **enter** to confirm
3. A confirmation summary shows your selection
4. Only selected books are downloaded
**Behavior notes:**
- Requires an interactive terminal (TTY). Non-interactive environments (cron, pipes) produce an error and exit
- When `--select` is active, `--limit` is superseded — a notice is printed if both are specified
- Books are downloaded in the order they appear in your library (selection order is preserved)
**Row format:**
```
1. The Way of Kings — Brandon Sanderson [Stormlight Archive #1]
2. Mistborn — Brandon Sanderson [Mistborn #1]
3. Elantris — Brandon Sanderson
```
Series info and number are shown when available.
### --rename-chapters
Rename extracted MP3 files with chapter titles from the download manifest:
```bash
# Enable chapter renaming (overrides config)
librofm-downloader --rename-chapters
```
**Resolution order (CLI > config > default):**
1. **`--rename-chapters`** flag on the command line
2. **`rename_chapters:`** field in `config.yaml`
3. **Default: `true`**
Only applies when the download pipeline uses MP3 files (`m4b_mp3_fallback` fallback path or `mp3_only` mode). M4B files have built-in chapter metadata and are not affected.
**Example renaming:**
```
# Before (raw ZIP extraction)
01.mp3 02.mp3 03.mp3 04.mp3
# After (--rename-chapters, default)
001 - Opening.mp3 002 - The Arrival.mp3 003 - Revelations.mp3 004 - Departure.mp3
```
Files are zero-padded to match the widest track number (3 digits for 10-999 tracks, 2 for fewer).
## Exit codes
| Code | Meaning |
+1
View File
@@ -72,6 +72,7 @@ All non-credential settings. Safe to commit. **Optional** — if missing, built-
| `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. |
| `rename_chapters` | `boolean` | `true` | Rename extracted MP3 files with chapter titles from the manifest. Only applies to MP3 pipeline (`m4b_mp3_fallback` fallback or `mp3_only`). |
| `workers` | `integer` | `3` | Number of parallel download threads. Set to 1 for sequential mode. Must be ≥ 1. |
### Full example
+18
View File
@@ -136,3 +136,21 @@ Summary: 5 downloaded, 2 skipped, 0 failed
- The ZIP file is deleted after extraction
- Each part supports resume via `Range` headers
- Parts are downloaded sequentially within each book
### Chapter renaming (MP3 only)
When `rename_chapters` is enabled (default), extracted MP3 files are renamed with chapter titles from the download manifest:
```
# Before (raw extraction)
01.mp3 02.mp3 03.mp3
# After (renamed)
001 - Opening.mp3 002 - The Arrival.mp3 003 - Departure.mp3
```
- Files are sorted naturally by numeric prefix before renaming
- Zero-padding matches the widest track number
- Blank or missing titles fall back to the original filename
- Titles are sanitized (illegal characters stripped) via the same function used for path components
- Disable in `config.yaml` with `rename_chapters: false`, or override per-run with `--rename-chapters` on the CLI
+3
View File
@@ -10,8 +10,11 @@ No Docker. No JVM. Just Python and go.
## Features
- **Full library sync** — fetches every audiobook in your Libro.fm account with automatic pagination
- **Interactive book selection** — pick which books to download with `--select` (checkbox prompt)
- **M4B + MP3 formats** — downloads M4B (single file) or MP3 (ZIP parts extracted) with automatic fallback
- **Chapter renaming** — MP3 files renamed with chapter titles from the manifest (configurable)
- **Resume support** — interrupted downloads pick up where they left off via `.partial` files
- **Parallel downloads** — configurable worker count (`--workers N`, default 3) with graceful Ctrl+C drain
- **Cover art & PDF extras** — optional download of cover images and accompanying PDFs
- **Customizable output paths** — token-based patterns for organizing your library on disk
- **TTY-aware progress** — rich progress bars in your terminal, clean log lines in cron jobs
+42 -14
View File
@@ -16,13 +16,9 @@ pip install -e .
Requires **Python 3.11+**.
### From source
For development (includes pytest):
```bash
git clone https://github.com/AlexKucera/librofm-downloader.git
cd librofm-downloader
python -m venv .venv
source .venv/bin/activate # or .venv\Scripts\activate on Windows
pip install -e ".[dev]"
```
@@ -63,6 +59,13 @@ librofm:
# Whether to download cover art when available
download_covers: true
# Whether to rename MP3 chapter files with titles from the manifest
# Only applies when format falls back to MP3 (m4b_mp3_fallback or mp3_only)
rename_chapters: true
# Number of parallel download workers (1 = sequential)
workers: 3
```
### secrets.yaml
@@ -91,21 +94,37 @@ This:
2. Authenticates with Libro.fm via OAuth2 password grant
3. Fetches your full library (all pages)
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
5. Downloads each new book with up to 3 parallel workers
6. Records successful downloads to history
### Interactive selection
Pick which books to download from a checkbox list:
```bash
librofm-downloader --select
```
This:
1. Fetches your library and filters already-downloaded books
2. Presents a checkbox prompt (space to toggle, enter to confirm)
3. Downloads only the books you selected
> [!NOTE]
> `--select` requires an interactive terminal (TTY). In non-interactive
> environments (cron, pipes), the tool exits with an error.
When `--select` is active, `--limit` is superseded — you control exactly which books are downloaded.
### First run output (TTY)
```
3 book(s) to download:
Author One - Book Title One ██████████████████████████ 100.0% 2.1 MB/s 00:01 45.2 MB
✓ Book Title One
Author Two - Another Book ██████████████████████████ 100.0% 1.8 MB/s 00:02 120.5 MB
✓ Another Book
Author Three - Third Book ██████████████████████████ 100.0% 2.3 MB/s 00:00 89.1 MB
✓ Third Book
Brandon Sanderson - The Way of Kings ██████████████████████████ 100.0% 2.1 MB/s 00:01 45.2 MB
Author Two - Another Book ██████████████████████████ 100.0% 1.8 MB/s 00:02 120.5 MB
Author Three - Third Book ██████████████████████████ 100.0% 2.3 MB/s 00:00 89.1 MB
Summary: 3 downloaded, 0 skipped, 0 failed
```
@@ -129,6 +148,14 @@ Completed: Author Two - Another Book
Summary: 2 downloaded, 0 skipped, 0 failed
```
### Interrupted downloads
Press **Ctrl+C** to gracefully stop:
- First press: in-flight downloads drain to completion, then summary prints
- Second press: immediate hard exit
- Partial downloads (`.partial` files) resume automatically on next run
## What gets downloaded?
Files land under your `output_dir` using this structure:
@@ -147,6 +174,7 @@ audiobooks/
- Books with **cover art or PDF extras** get a subdirectory (`Author/Title/`)
- Books without extras are flat files (`Author/Title.m4b`)
- When using MP3 format, chapter files are renamed with titles from the manifest (e.g., `001 - Opening.mp3`, `002 - The Arrival.mp3`)
- See [Path Patterns](path-patterns.md) for customization options
## Next steps
+37
View File
@@ -123,6 +123,31 @@ $ librofm-downloader
- Switch to `m4b_mp3_fallback` to get the MP3 version instead
- Accept that some books aren't available in M4B format
## Selection issues
### "--select requires an interactive terminal"
**Cause:** You ran `librofm-downloader --select` in a non-interactive environment (cron, piped, SSH without TTY allocation).
**Behavior:**
- Tool exits immediately with exit code **1**
- No downloads are attempted
**Fix options:**
- Run in an interactive terminal (local shell, `ssh -t` for TTY allocation)
- Use `--limit N` instead for non-interactive capped downloads
```bash
# Non-interactive alternative: just download the first 5 new books
librofm-downloader --limit 5
```
### --limit seems ignored when using --select
**Behavior:** When `--select` is active, `--limit` is superseded — you pick exactly which books to download from the checkbox prompt. A notice is printed confirming this.
**Fix:** This is intentional. Use `--select` to choose books, or use `--limit` alone for automatic capping.
## History file problems
### "Corrupt history file download_history.json: ... Starting with empty history."
@@ -226,6 +251,18 @@ Use `--limit` to process smaller batches:
librofm-downloader --limit 5
```
Or select specific books interactively:
```bash
librofm-downloader --select
```
Or limit to the first 5 new books:
```bash
librofm-downloader --limit 5
```
## Getting help
If none of the above covers your issue:
+1 -1
View File
@@ -50,7 +50,7 @@ def main() -> None:
parser.add_argument("-w", "--workers", type=int, default=0, metavar="N", help="Parallel workers (0=config)")
parser.add_argument("--rename-chapters", action="store_true", default=False,
help="Rename chapter files (default: use config)")
parser.add_argument("--select", action="store_true", default=False, help="Interactive selection [not implemented]")
parser.add_argument("--select", action="store_true", default=False, help="Interactive book selection")
args = parser.parse_args()
exit_code = run(
config_path=args.config, secrets_path=args.secrets, history_path=args.history,
+11 -6
View File
@@ -88,7 +88,7 @@ def _download_one(
def download_all_books(
raw_books: list[dict],
raw_books: list[dict | Book],
*,
workers: int,
download_fn: Callable[[Book], Any],
@@ -99,7 +99,7 @@ def download_all_books(
"""Run downloads for all books using a thread pool.
Args:
raw_books: List of raw Libro.fm API book dicts.
raw_books: List of raw Libro.fm API book dicts, or pre-converted Book objects.
workers: Number of parallel worker threads.
download_fn: Callable accepting a Book, returning Path (success) or None (skipped).
reporter: Reporter instance with start_download/complete/fail/summary methods.
@@ -113,10 +113,15 @@ def download_all_books(
if not raw_books:
return OrchestratorResult()
# Convert raw dicts to Book objects, preserving order and index
books_with_index: list[tuple[int, Book]] = [
(i, from_library_row(raw)) for i, raw in enumerate(raw_books)
]
# Convert raw dicts to Book objects, preserving order and index.
# Accept pre-converted Book objects directly to avoid double-conversion
# when select mode has already called from_library_row().
books_with_index: list[tuple[int, Book]] = []
for i, raw in enumerate(raw_books):
if isinstance(raw, Book):
books_with_index.append((i, raw))
else:
books_with_index.append((i, from_library_row(raw)))
downloaded_count = 0
skipped_count = 0
+56
View File
@@ -0,0 +1,56 @@
"""Interactive book selection via questionary checkbox prompt.
Public API: select_books(books) -> list[Book]
Internal helper: _format_row(book, index) -> str
"""
import questionary
from librofm_downloader.book import Book
def _format_row(book: Book, index: int) -> str:
"""Format a Book into a display string for the checkbox prompt.
Format: "N. Title — First Author [Series #N]"
Series suffix omitted when absent. Author falls back to "Unknown".
"""
author = book.authors[0] if book.authors else "Unknown"
base = f"{index}. {book.title} — {author}"
if book.series and book.series_num is not None:
base += f" [{book.series} #{book.series_num}]"
return base
def select_books(books: list[Book]) -> list[Book]:
"""Present an interactive checkbox prompt and return selected Books.
Returns selected Books in their original input order.
Returns empty list on zero selection or confirmation rejection.
Propagates KeyboardInterrupt from the checkbox prompt.
"""
rows = [_format_row(b, i + 1) for i, b in enumerate(books)]
chosen = questionary.checkbox(
"Select books to download:",
choices=rows,
).unsafe_ask()
if not chosen:
print("No books selected. Exiting.")
return []
# Map display rows back to Book objects
row_to_book = {row: book for row, book in zip(rows, books)}
selected = [row_to_book[row] for row in chosen]
# Confirmation prompt
print(f"{len(selected)} book(s) selected for download:")
for book in selected:
print(f" - {book.title}")
if not questionary.confirm("Proceed with download?", default=False).ask():
return []
# Return in original input order
selected_set = {id(b) for b in selected}
return [b for b in books if id(b) in selected_set]
+22 -5
View File
@@ -11,6 +11,7 @@ calls sync_run() and translates SyncRunResult → exit code.
from __future__ import annotations
import os
import sys
import threading
from collections.abc import Callable
from dataclasses import dataclass, field
@@ -124,7 +125,7 @@ def sync_run(
verbose: Print extra detail (URLs, paths, API responses).
limit: Maximum number of books to download (0 = no limit).
workers: Parallel download worker count (0 = use config value).
select_mode: Interactive book selection (ADR #6, not yet implemented).
select_mode: Interactive book selection (ADR #6).
Returns:
SyncRunResult with counts and per-book details.
@@ -202,7 +203,7 @@ def sync_run(
if history is None:
history = DownloadHistory(history_path)
new_books = [b for b in books if not history.is_downloaded(b.get("isbn", ""))]
if limit:
if limit and not select_mode:
new_books = new_books[:limit]
if verbose:
@@ -213,10 +214,26 @@ def sync_run(
console.print("[green]All caught up! No new books to download.[/green]")
return SyncRunResult()
# 5. Select mode branch point (ADR #6 — stub)
# 5. Select mode pipeline (ADR #6)
if select_mode:
console.print("[red]--select is not yet implemented.[/red]")
return SyncRunResult()
if not sys.stdin.isatty():
console.print("[red]--select requires an interactive terminal.[/red]")
return SyncRunResult(fatal_error="--select requires an interactive terminal")
from librofm_downloader.book import from_library_row
from librofm_downloader.selector import select_books
selectable_books = [from_library_row(b) for b in new_books]
selected = select_books(selectable_books)
if not selected:
return SyncRunResult()
if limit:
console.print("[dim]Selection mode active -- --limit superseded by manual selection.[/dim]")
# Replace new_books with selected Books; orchestrator will
# receive pre-converted Book objects.
new_books = selected # type: ignore[assignment]
# 6. Download loop with TTY-aware reporting
if reporter is None:
+2 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "librofm-downloader"
version = "1.1.0"
version = "1.4.0"
description = "Download owned audiobooks from your Libro.fm account"
readme = "README.md"
license = "MIT"
@@ -12,6 +12,7 @@ requires-python = ">=3.11"
dependencies = [
"httpx>=0.27",
"pyyaml>=6.0",
"questionary>=2.1.1",
"rich>=13.0",
]
+25
View File
@@ -952,3 +952,28 @@ class TestOrchestratorUsesBoundCallback:
# The callables must be exactly the ones the reporter created
assert cb_a in reporter._callables
assert cb_b in reporter._callables
class TestDownloadAllBooksAcceptsBookObjects:
"""download_all_books accepts pre-converted Book objects (no double-conversion)."""
def test_book_objects_skip_from_library_row(self):
"""Passing Book objects directly works — no need to convert via from_library_row."""
book_a = Book(title="Book A", authors=["Auth"], narrators=[], isbn="111")
book_b = Book(title="Book B", authors=["Auth"], narrators=[], isbn="222")
books = [book_a, book_b]
downloaded: list[Book] = []
def fake_download_fn(book: Book, progress=None):
downloaded.append(book)
return Path(f"/tmp/{book.isbn}.m4b")
reporter = FakeReporter()
result = download_all_books(
books, workers=1, download_fn=fake_download_fn, reporter=reporter,
)
assert result.downloaded_count == 2
assert result.failed_count == 0
assert downloaded == [book_a, book_b]
+121
View File
@@ -0,0 +1,121 @@
"""Tests for selector.py — interactive book selection."""
import unittest.mock as mock
from librofm_downloader.book import Book
from librofm_downloader.selector import _format_row, select_books
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _book(title, authors=None, **kw):
"""Convenience Book factory for tests."""
return Book(
title=title,
authors=authors or ["Author"],
narrators=[],
isbn=kw.pop("isbn", "0000"),
**kw,
)
# ---------------------------------------------------------------------------
# _format_row
# ---------------------------------------------------------------------------
def test_format_row_with_series():
book = Book(
title="The Way of Kings",
authors=["Brandon Sanderson"],
narrators=["Michael Kramer"],
isbn="9780765365279",
series="Stormlight Archive",
series_num=1,
)
assert _format_row(book, 3) == "3. The Way of Kings — Brandon Sanderson [Stormlight Archive #1]"
def test_format_row_without_series():
book = Book(
title="Project Hail Mary",
authors=["Andy Weir"],
narrators=["Ray Porter"],
isbn="9780593135204",
)
assert _format_row(book, 1) == "1. Project Hail Mary — Andy Weir"
def test_format_row_no_authors_falls_back_to_unknown():
book = Book(
title="Mystery Book",
authors=[],
narrators=[],
isbn="0000000000",
)
assert _format_row(book, 5) == "5. Mystery Book — Unknown"
# ---------------------------------------------------------------------------
# select_books
# ---------------------------------------------------------------------------
def test_select_books_returns_selected_in_original_order():
books = [_book("A"), _book("B"), _book("C"), _book("D")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.return_value = ["3. C — Author", "1. A — Author"]
q.confirm.return_value.ask.return_value = True
result = select_books(books)
assert [b.title for b in result] == ["A", "C"]
def test_select_books_returns_empty_on_zero_selection(capsys):
books = [_book("A"), _book("B")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.return_value = []
result = select_books(books)
assert result == []
assert "No books selected" in capsys.readouterr().out
def test_select_books_returns_empty_on_confirm_rejection():
books = [_book("A"), _book("B")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.return_value = ["1. A — Author"]
q.confirm.return_value.ask.return_value = False # N / bare Enter
result = select_books(books)
assert result == []
def test_select_books_returns_books_on_confirm_acceptance(capsys):
books = [_book("Alpha"), _book("Beta")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.return_value = ["2. Beta — Author"]
q.confirm.return_value.ask.return_value = True # y/Y
result = select_books(books)
assert [b.title for b in result] == ["Beta"]
out = capsys.readouterr().out
assert "1 book(s) selected" in out
assert "- Beta" in out
def test_select_books_propagates_keyboard_interrupt():
books = [_book("A")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.side_effect = KeyboardInterrupt
try:
select_books(books)
except KeyboardInterrupt:
pass # expected
else:
raise AssertionError("Should have propagated KeyboardInterrupt")
def test_select_books_single_book_library():
books = [_book("Solo")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.return_value = ["1. Solo — Author"]
q.confirm.return_value.ask.return_value = True
result = select_books(books)
assert [b.title for b in result] == ["Solo"]
+180 -5
View File
@@ -66,11 +66,41 @@ class TestSyncRunExists:
assert result.interrupted is False
class TestSyncRunSelectMode:
"""Select mode (ADR #6) branch point — stub, returns empty result."""
class TestSyncRunSelectModeTTYGuard:
"""Select mode requires interactive terminal — no TTY → fatal_error."""
def test_select_mode_returns_not_implemented_result(self):
"""select_mode=True → empty SyncRunResult (not yet implemented)."""
def test_no_tty_returns_fatal_error(self):
"""select_mode=True + no TTY → SyncRunResult(fatal_error) with clear message."""
with (
patch("librofm_downloader.sync_run.load_config") as mock_config,
patch("librofm_downloader.sync_run.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.sync_run.DownloadHistory") as mock_history_cls,
patch("sys.stdin.isatty", return_value=False),
):
mock_config.return_value.username = "alice"
mock_config.return_value.password = "secret"
mock_config.return_value.output_dir = "./audiobooks"
mock_config.return_value.workers = 3
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
mock_instance.fetch_library.return_value = [
{"isbn": "9781234567890", "title": "A Book"},
]
mock_history_cls.return_value.is_downloaded.return_value = False
result = sync_run(
verbose=False, limit=0, workers=0, select_mode=True,
)
assert isinstance(result, SyncRunResult)
assert result.fatal_error is not None
assert "--select requires an interactive terminal" in result.fatal_error
def test_all_caught_up_with_select_mode(self):
"""select_mode=True + no new books → 'All caught up!' + exit 0 (same as non-select)."""
with (
patch("librofm_downloader.sync_run.load_config") as mock_config,
patch("librofm_downloader.sync_run.LibroFmSession") as mock_client_cls,
@@ -83,10 +113,45 @@ class TestSyncRunSelectMode:
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
# All books already downloaded
mock_instance.fetch_library.return_value = [
{"isbn": "9781234567890", "title": "A Book"},
]
mock_history_cls.return_value.is_downloaded.return_value = True
result = sync_run(
verbose=False, limit=0, workers=0, select_mode=True,
)
assert isinstance(result, SyncRunResult)
assert result.fatal_error is None
assert result.interrupted is False
assert result.downloaded_count == 0
class TestSyncRunSelectModeEmptySelection:
"""select_books() returns empty → clean exit 0, no downloads attempted."""
def test_empty_selection_returns_clean_result(self):
"""select_books() returns [] → SyncRunResult with no error, no downloads."""
with (
patch("librofm_downloader.sync_run.load_config") as mock_config,
patch("librofm_downloader.sync_run.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.sync_run.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.selector.select_books", return_value=[]),
patch("sys.stdin.isatty", return_value=True),
):
mock_config.return_value.username = "alice"
mock_config.return_value.password = "secret"
mock_config.return_value.output_dir = "./audiobooks"
mock_config.return_value.workers = 3
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
mock_instance.fetch_library.return_value = [
{"isbn": "9781234567890", "title": "A Book"},
]
mock_history_cls.return_value.is_downloaded.return_value = False
result = sync_run(
@@ -94,10 +159,120 @@ class TestSyncRunSelectMode:
)
assert isinstance(result, SyncRunResult)
assert result.downloaded_count == 0
assert result.fatal_error is None
assert result.interrupted is False
assert result.downloaded_count == 0
class TestSyncRunSelectModeSelectedFlow:
"""Selected Books flow to orchestrator correctly (no double-conversion)."""
def test_selected_books_passed_to_orchestrator(self):
"""select_books() returns subset → those Books reach download_all_books."""
from librofm_downloader.book import Book
from librofm_downloader.orchestrator import OrchestratorResult
book_a = Book(title="Book A", authors=["Author"], narrators=[], isbn="111")
book_b = Book(title="Book B", authors=["Author"], narrators=[], isbn="222")
# select_books returns only book_a (user deselected book_b)
selected = [book_a]
with (
patch("librofm_downloader.sync_run.load_config") as mock_config,
patch("librofm_downloader.sync_run.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.sync_run.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.selector.select_books", return_value=selected),
patch("librofm_downloader.sync_run.download_all_books") as mock_download,
patch("librofm_downloader.sync_run.DownloadReporter") as mock_reporter_cls,
patch("sys.stdin.isatty", return_value=True),
):
mock_config.return_value.username = "alice"
mock_config.return_value.password = "secret"
mock_config.return_value.output_dir = "./audiobooks"
mock_config.return_value.format = "m4b_mp3_fallback"
mock_config.return_value.workers = 3
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
mock_instance.fetch_library.return_value = [
{"isbn": "111", "title": "Book A"},
{"isbn": "222", "title": "Book B"},
]
mock_history_cls.return_value.is_downloaded.return_value = False
mock_download.return_value = OrchestratorResult(downloaded_count=1)
result = sync_run(
verbose=False, limit=0, workers=0, select_mode=True,
)
# Verify orchestrator received only the selected Book objects
assert mock_download.called
call_args = mock_download.call_args
raw_books_arg = call_args[1]["raw_books"] if "raw_books" in call_args[1] else call_args[0][0]
assert len(raw_books_arg) == 1
# The argument should be a Book object (not a dict)
assert isinstance(raw_books_arg[0], Book)
assert raw_books_arg[0].isbn == "111"
assert result.downloaded_count == 1
assert result.fatal_error is None
class TestSyncRunSelectModeLimitIgnored:
"""--limit is ignored when --select is active."""
def test_limit_not_applied_with_select_mode(self, capsys):
"""select_mode=True + limit=1 → all books still available for selection."""
from librofm_downloader.book import Book
from librofm_downloader.orchestrator import OrchestratorResult
book_a = Book(title="Book A", authors=["Auth"], narrators=[], isbn="111")
book_b = Book(title="Book B", authors=["Auth"], narrators=[], isbn="222")
book_c = Book(title="Book C", authors=["Auth"], narrators=[], isbn="333")
# select_books returns all 3 (user selected all)
selected = [book_a, book_b, book_c]
with (
patch("librofm_downloader.sync_run.load_config") as mock_config,
patch("librofm_downloader.sync_run.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.sync_run.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.selector.select_books", return_value=selected),
patch("librofm_downloader.sync_run.download_all_books") as mock_download,
patch("librofm_downloader.sync_run.DownloadReporter") as mock_reporter_cls,
patch("sys.stdin.isatty", return_value=True),
):
mock_config.return_value.username = "alice"
mock_config.return_value.password = "secret"
mock_config.return_value.output_dir = "./audiobooks"
mock_config.return_value.format = "m4b_mp3_fallback"
mock_config.return_value.workers = 3
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
mock_instance.fetch_library.return_value = [
{"isbn": "111", "title": "Book A"},
{"isbn": "222", "title": "Book B"},
{"isbn": "333", "title": "Book C"},
]
mock_history_cls.return_value.is_downloaded.return_value = False
mock_download.return_value = OrchestratorResult(downloaded_count=3)
result = sync_run(
verbose=True, limit=1, workers=0, select_mode=True,
)
# All 3 books should reach the selector (limit not applied)
select_call_args = mock_download.call_args
raw_books_arg = select_call_args[1]["raw_books"] if "raw_books" in select_call_args[1] else select_call_args[0][0]
assert len(raw_books_arg) == 3
# Verbose note should be printed about limit being superseded
output = capsys.readouterr().out
assert "--limit" in output.lower() or "superseded" in output.lower()
class TestSyncRunInterrupted:
"""Ctrl+C / interrupted path returns SyncRunResult(interrupted=True)."""