Introduce frozen OutputPlan dataclass carrying all resolved file paths
(audio, partial, cover, PDF) for a single Book. Add resolve_output_plan()
function that centralizes every path computation so download functions
receive pre-resolved Paths instead of computing them inline.
Refactor download_book() to consume plan.audio_path (eliminating
duplicated sanitize(title).m4b logic), download_accompanying_files() to
accept an OutputPlan instead of raw output_dir, and _download_cover/_download_pdf
to accept optional expected_path parameter.
Closes#28
Relocate API client from client.py to session.py with constructor
injection. Transport is now passed once at construction time
instead of per-method, eliminating 5 redundant httpx.Client
creations per session lifecycle.
- New session.py: LibroFmSession with shared _client, transport
injected at construction, auth headers set once after
authenticate()
- Old client.py: deprecated re-export shim (LibroFmClient alias)
- All endpoint signatures slimmed to ≤3 params (removed
transport= from authenticate/fetch_library/fetch_m4b_url/
fetch_download_manifest/fetch_pdf_extra_url)
- Updated all source imports (cli.py, downloader.py) and test
files (test_client, test_downloader, test_cli, test_progress)
- 17 new TDD tests in test_session.py
Closes#27
Move Book dataclass + from_library_row() into dedicated book.py.
Extract sanitize/resolve_path/needs_subdirectory into path.py.
Hard-cut import migration across 7 source+test files. 79 new tests.
Closes#26
In parallel download mode, all progress updates went to the same
(most recently started) bar because task_id was never threaded from
start_download() to the update callback. Create per-book closure in
orchestrator that binds task_id, pass through cli._download_fn as
optional kwarg. 3 new regression tests. 259 total.
Python ThreadPoolExecutor workers cannot be killed when blocked in HTTP
I/O. Previous approach of waiting for graceful cancellation via
shutdown(wait=True) caused infinite hangs, and re-raising KeyboardInterrupt
still triggered Python's _python_exit thread-join cleanup on exit.
Replace with hard-exit strategy: first Ctrl+C marks all unfinished books
(active + pending) as cancelled, prints summary, returns partial result
with interrupted=True. CLI then calls os._exit(130) to bypass thread
cleanup entirely. Second Ctrl+C hard-exits immediately.
Also fixes: books_with_index[idx][0] returning int index instead of
Book object (AttributeError on summary), empty CancelledError reason
strings, missing cancel_event wiring through download_book->download_m4b
call chain, and corrupted test body from earlier edit collision.
256 tests pass.
Extract argparse into main() and point console script at it.
The -v/--verbose flag was dead because the entry point called
run() directly, bypassing the __main__ argparse block entirely.
History path now defaults to None and resolves via XDG→CWD search,
falling back to XDG location when not found. Missing config message
lists searched paths. --verbose shows resolved paths for all three
files. Explicit --config/--secrets/--history bypass resolution.
Closes#23
Add _resolve_config_file() searching ~/.config/librofm-downloader/
then CWD. Wire into load_config() so None triggers search. Missing
config.yaml is non-fatal (prints notice, uses defaults); missing
secrets.yaml raises ConfigError listing searched paths. All OS
exceptions wrapped as domain errors. XDG dir auto-created.
Closes#22
Wrap as_completed() loop in try/except KeyboardInterrupt so first
Ctrl+C prints "Aborting...", drains in-flight downloads via
executor.shutdown(wait=True), then re-raises for exit code 130.
Second Ctrl+C during drain force-quits immediately with
shutdown(cancel_futures=True). Add 13 integration tests covering
workers=1 regression parity, concurrent execution proof, summary
ordering, failure isolation, verbose overlap safety, and partial
file resume-safety after interrupt.
Replace the sequential for-loop in cli.py with download_all_books()
which submits all books as futures to a ThreadPoolExecutor. Each future
runs the full download pipeline (API → streaming → history) independently;
failures are isolated per book and siblings continue unaffected.
OrchestratorResult dataclass returns stable-sorted counts and per-book
details (failed_books as (Book, reason) tuples, skipped_books as Book
objects). The _raw_to_book() conversion is extracted from cli.py so the
orchestrator owns the dict→Book mapping. All 20 unit tests use an injected
download_fn — no network or filesystem required.
Co-Authored-By: pi <pi@earendil.works>
Implement a rate limiter for concurrent Libro.fm API requests to prevent overwhelming the service, especially during parallel downloads. This caps concurrent lookup calls for M4B, MP3, and PDF, while allowing CDN downloads and initial authentication/library fetching to proceed unimpeded.
Replace singleton _current_task/_current_book state with bidirectional
_tasks (task_id→book) / _book_ids (id(book)→task_id) dicts, enabling N
simultaneous Rich progress bars for parallel downloads.
- start_download() now returns task_id (int)
- update() accepts optional task_id kwarg; falls back to most-recent
task when omitted for backward compat with existing callers
- complete()/fail() look up task by id(book) and clean up both mappings
- Safe on unknown books (no-op)
- PlainTextReporter unchanged — already stateless per-call design
10 new tests across TestMultiBarProgress (9) and TestMultiBookPlainText (1).
All 194 tests pass, zero regressions. Closes#14
Guard DownloadHistory.write() with a threading.Lock so concurrent
worker threads do not corrupt or lose history entries during parallel
downloads. Lock wraps both _data mutation and disk flush; read-only
methods (is_downloaded, find) stay lock-free per CPython dict atomicity.
Closes#13
Add parallel download worker-count configuration through all three
config layers: Config dataclass (workers=3 default), YAML parsing
with InvalidWorkersError validation, and -w/--workers CLI flag with
three-layer resolution (CLI > config > hardcoded 3). 6 new tests.
Closes#12
Add 8-page documentation site with Material theme covering
quickstart, configuration, secrets, path patterns, format
strategies, CLI usage, and troubleshooting. All code snippets
verified against implementation. Rewrite README with badges,
features, quickstart, and format comparison. Build HTML to
docs/html/ with flat URLs.
needs_subdirectory() treated always-present cover_url as a subdirectory
trigger, and _resolve_output_dir() double-appended the title from
resolve_path(), producing Author/Title/Title/Title.m4b paths.
Cover downloads also failed silently: _download_cover() used a naked
httpx.Client without Libro.fm headers (CDN rejection), and
protocol-relative URLs (//cdn.libro.fm/...) caused httpx errors.
Summary output now lists each failed book (ISBN + title + reason)
and each skipped book (ISBN + title) in both plain-text and rich/TTY
formats. Ctrl+C produces a clean shutdown message with exit code 130
instead of a Python traceback. Three integration tests exercise the
full run() pipeline: happy path, mixed results, and fatal auth failure.
12 new tests (168 total), 15/15 acceptance criteria met.
Rich progress bars with live %/ETA/speed/file size for interactive
terminals; plain log lines for pipes/cron. Reads Content-Length from
HTTP response so percentage works from first chunk onward. Per-book
failure isolation prevents one bad book from stopping the batch.
18 new tests, 156 total passing.
Add accompanying file download pipeline: PDF extras via new
client.fetch_pdf_extra_url() endpoint, cover art from existing
book.cover_url, both using streaming .partial -> atomic rename pattern.
Config toggles (download_extras, download_covers) control which files
are downloaded. Failures log warnings only -- never mark a book as
failed. Wired into all 3 format strategy paths in download_book().
Output structure: books with extras create subdirectories containing
audio + PDFs + cover; books without extras output audio as leaf file.
12 new tests (134 total), 11/11 acceptance criteria met.
- Add fetch_download_manifest() to client for MP3 manifest endpoint
- Add download_zip_part() for streaming ZIP download, .partial tracking,
resume via Range header, auto-extraction and cleanup
- Refactor download_book() with format_strategy param: m4b_mp3_fallback,
mp3_only, m4b_only
- Add --limit N CLI flag to cap downloads for testing
- Wire config.format through CLI to download_book()
- 12 new tests (122 total), all passing
Add streaming chunked M4B download via .partial files and atomic
rename, resume support through HTTP Range headers, full CLI
orchestration loop, --verbose flag, and config/secrets templates.
Fix 4 API-shape bugs found during live testing: library endpoint
returns audiobooks not books, M4B endpoint returns m4b_url not url,
narrators nested under audiobook_info, and ISBN int/str type mismatch
in history lookup causing re-downloads.
12 new tests (109 total). 6 books downloaded live (~2.9 GB).
Add pure-logic downloader module with Book dataclass, filesystem-safe
path component sanitization, default conditional path patterns, custom
{TOKEN} pattern substitution, and subdirectory decision logic.
- sanitize(): 5-rule pipeline — colon→dash, strip illegal/control chars,
trim whitespace, remove trailing dots, cap at 255 characters
- resolve_path(book, pattern?): default mode selects pattern by series
presence; custom mode substitutes 11 tokens with sanitization
- needs_subdirectory(book): True when PDF extras or cover art present
- @dataclass(frozen=True) Book: immutable record for all book metadata
56 new tests across 11 classes. 97 total tests passing. 16/16 AC met.
Add the data layer that feeds into downloads: OAuth2 password grant
authentication via httpx, paginated library fetching across all pages,
download history JSON read/write with corrupt-recovery safety, and a
CLI skeleton that wires config → auth → fetch → filter → print.
16 new tests (6 client + 7 history + 3 CLI), 41 total passing.
All 11 acceptance criteria met.
Set up Python package with pyproject.toml, venv, and runtime/test
dependencies. Implement config module that loads config.yaml +
secrets.yaml with deep-merge override, validates required fields,
rejects credentials in config.yaml, applies defaults, and returns a
frozen Config dataclass. 25 tests across 7 test classes.