Add inline comment in _finalize_download() explaining that the
rename_chapters bool param shadows the module-level rename_chapters()
function. This is safe because the actual call is delegated to
_rename_and_log(), which has its own clean scope.
Two bugs found by code review:
1. Progress bar exceeds 100% on resumed downloads because
Content-Length from a Range response covers only remaining
bytes. Now adds resume_from for the true total.
2. session.transport reached into httpx.Client._transport, a
private attribute that may break on httpx upgrades. Transport
is now stored at construction time instead.
SyncRunResult now wraps OrchestratorResult instead of duplicating
its 6 fields. Delegating properties preserve the public interface,
eliminating field-by-field copy code in the bridge between
orchestrator and sync_run.
Closes#45
Add 4 injectable parameters (session, history, reporter,
download_all_fn) to sync_run() with backward-compatible defaults.
Extract _print_verbose_config() and _resolve_history_path() helpers.
Refactor _make_download_fn() to take explicit params instead of
closing over enclosing scope.
Tests can now pass fakes via parameters instead of mock.patch.
Closes#44
Delete 13 duplicate path test classes from test_downloader.py
(already exist in test_path.py). Move 2 sync_run integration
classes from test_progress.py to test_sync_run.py. Remove
duplicate TestParallelProgressCallbackWiring class. Rescue orphaned
3-book interleaved plain text test with proper class wrapper.
Net -469 test lines. Each test file now tests exactly one module.
The three format-strategy blocks in download_book() each duplicated
the same post-download success logic: rename chapters (MP3 only),
download accompanying files, and return a DownloadResult. Extract
a single _finalize_download() helper so each branch reduces to:
attempt download → return _finalize_download(...).
Adding a new format strategy now requires only the download attempt
plus one call to the existing success helper.
Closes#42
Eliminate the ~30-line duplicated chunked-download loop across
download_m4b(), download_zip_part(), _download_cover(), and
_download_pdf() by extracting a shared _stream_to_file() private
helper. Each caller is now a thin wrapper that delegates streaming
to the helper then performs its own post-processing step.
5 new TDD tests covering fresh download, resume, cancel mid-stream,
progress callback with content-length, and HTTP error propagation.
224 total tests pass. Net -22 lines in downloader.py.
Closes#41
Move the `_write_history()` function from `downloader.py` to `history.py`. This refactoring separates persistence logic from download orchestration, ensuring `downloader.py` focuses solely on its core responsibility.
Thread cancel_event explicitly through the parameter chain
(sync_run closure → download_book() → streaming calls) instead of
stashing it on reporter objects as shared state. Remove the
cancel_event attribute from both PlainTextReporter and
ProgressReporter — cancellation is not a reporting concern.
Closes#39
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add @property transport getter that returns the underlying httpx
transport, replacing the single call site in downloader.py that
reached through session._client._transport. Encapsulates private
attribute access behind a public interface. 2 new tests.
Closes#38
Remove the 32-line re-export shim (Issue #27 leftover) and its 588-line
duplicate test file. Migrate 4 unique rate-limiter tests into
test_session.py. Zero production imports of client.py confirmed.
Net: -337 lines dead code, 425→413 tests collected.
Closes#37
Add 4 end-to-end integration tests proving rename_chapters() fires
correctly through the full download pipeline for each format strategy,
and is properly suppressed when disabled.
Closes#35
_download_mp3() returns (output_dir, tracks) tuple so manifest
track data flows to callers. download_book() accepts rename_chapters
kwarg; after MP3 extraction succeeds, calls rename_chapters() via
_rename_and_log() helper which also reports to user via reporter.
Both PlainTextReporter and RichProgressReporter show visible feedback:
'Renamed N chapter(s) for Book → example.mp3'. sync_run.py closure
threads resolved_rename_chapters flag through to download_book().
6 new integration tests covering all format strategies and edge cases.
~229 total tests. Closes#34.
Add rename_chapters boolean config field following the established
pattern from download_extras/download_covers. Config defaults to
True; YAML supports explicit false; --rename-chapters CLI flag forces
True overriding config. Threaded through sync_run() with resolved value
ready for pipeline wiring in slice 3.
Closes#33
Add standalone rename_chapters(output_dir, tracks, book_title) -> int
function that renames extracted MP3 files to include chapter titles
from the Libro.fm download manifest. Features: natural sort by numeric
prefix, auto zero-padding from track count, null/blank title fallback
to "Chapter N", sanitization via existing sanitize(). 11 tests, all
passing. Closes#32.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Move entire download pipeline from cli.run() into standalone
sync_run() in new sync_run.py module. Introduce SyncRunResult
frozen dataclass as public return type with fatal_error field
for exit-code translation. Slim cli.py from 252→65 lines to a
thin argparse→exit adapter that only calls sync_run().
Migrate 35 pipeline tests from test_cli.py to test_sync_run.py
(43 total). CLI tests now only patch sync_run (no internal
collaborators). Add select_mode stub for ADR #6 branch point.
Update test_progress.py patch targets to sync_run module.
374 tests pass.
start_download(book) now returns a per-book bound callable
instead of raw task_id. Task identity is fully internal to
progress.py — no caller ever sees or passes task_id.
- Orchestrator: removed closure pattern, now threads
progress_cb = start_download(book) directly
- downloader: download_book() accepts optional progress= kwarg,
uses it when provided (falls back to reporter.update)
- cli.py: forwards progress kwarg through _download_fn
- Public update() drops task_id param; bound callable calls
_progress.update(task_id_internal) directly
382 tests pass (+11 new), 6/6 AC met.
Replace 9-parameter signature (book, client, output_base, history,
format_strategy, config, transport, progress, cancel_event) with
4 domain-aligned parameters (book, session, plan, reporter) that
return a frozen DownloadResult dataclass.
Key changes:
- Add DownloadResult(status, path, format, error) frozen dataclass
- Add format_strategy field to OutputPlan
- Move history writing from download_book() to caller (cli closure)
- Remove config param from download_accompanying_files()
- Wire cancel_event through reporter.cancel_event attribute
- Extract transport from session._client._transport
Closes#29
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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
This document outlines a plan to refactor the codebase to address shallow modules and leaky interfaces. It defines new deep module boundaries to improve testability, maintainability, and extensibility for future development.
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.
Refreshes the project's GitNexus code intelligence index statistics
in documentation to accurately reflect the current codebase.
This update incorporates recent development, likely from the parallel
downloads feature, which increased symbols, relationships, and
execution flows. Also adds a missing newline to CLAUDE.md.
Update quick start guides (README, MkDocs) to recommend installing from source via `git clone` and `venv`. This ensures users access the latest development features and promotes a consistent setup. The "Just pip install" phrase was also broadened to "Just Python".
The _download_fn closure printed ⬇ title, authors, and narrators for
every book inside the parallel download loop. This was fine for
sequential mode but became redundant when rich ProgressReporter bars
were added — causing a triple-display: progress bars at 0%, then full
book details with expanded narrators, then live progress updates.
Progress bars already convey author+title, so the extra block was pure
noise. Verbose mode still shows config, paths, auth status, summary,
and the done separator.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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.
Remove duplicate load_config stub that was injected into
_resolve_config_file's docstring in config.py (SyntaxError
on import). Add workers attribute to 3 TestCLIHistoryResolution
mocks — develop added workers resolution in cli.py but the
existing tests didn't mock it, causing TypeError.
Update all documentation to reflect XDG-first config search
introduced in #22/#23. configuration.md gains a new Default File
Locations section with search order, auto-creation, missing-config
vs missing-secrets behavior, CLI flag overrides, and new error
messages. quickstart.md, cli-usage.md, troubleshooting.md, and
README.md updated accordingly. Bump version 0.1.0 → 0.2.0.
Closes#24
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
Allows users to pick specific books for download via a new `--select` CLI flag. This provides granular control over downloads, addressing limitations for users with large libraries or limited storage by superseding automatic filtering.
Update README, MkDocs site (cli-usage, configuration,
quickstart, troubleshooting), and built HTML to cover the
--workers flag, parallel download capability, workers config
field, and API semaphore behavior. Fix stale sequential-only
language across all user-facing documentation.
Closes#18
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