Commit Graph
41 Commits
Author SHA1 Message Date
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 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 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 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 8acea390e6 fix(downloader): correct resume progress and avoid httpx private API
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.
2026-06-06 09:28:33 +02:00
AlexKucera fcdba333d1 refactor(downloader): extract _stream_to_file() helper
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
2026-06-05 19:05:23 +02:00
AlexKuceraandClaude Opus 4.6 2930d163b2 refactor(reporters): remove cancel_event from progress reporters
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>
2026-06-05 18:45:27 +02:00
AlexKucera caca930c7c refactor(session): expose public transport property on LibroFmSession
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
2026-06-05 18:36:03 +02:00
AlexKucera a415fc37f5 feat(downloader): wire rename_chapters into download pipeline
_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.
2026-06-05 17:47:10 +02:00
AlexKucera af5ad4953c feat(config): add rename_chapters field, CLI flag, and 3-layer resolution
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
2026-06-05 17:15:16 +02:00
AlexKuceraandClaude Opus 4.6 b6df4e3a9b feat(downloader): add rename_chapters for MP3 chapter title renaming
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>
2026-06-05 15:26:04 +02:00
AlexKucera f371152166 refactor(cli): extract sync_run pipeline and slim CLI to adapter (#31)
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.
2026-06-05 14:52:00 +02:00
AlexKucera 1f46467f2c refactor(progress): return bound callable from start_download (#30)
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.
2026-06-05 11:58:04 +02:00
AlexKuceraandClaude Opus 4.6 9ac581e5b7 refactor(downloader): shrink download_book to 4 domain params
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>
2026-06-05 07:34:01 +02:00
AlexKucera 0ee8186361 feat(path): add OutputPlan dataclass for centralized path resolution
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
2026-06-04 15:47:33 +02:00
AlexKucera cbb8992acc docs(changelog): add #27 session rename to Unreleased 2026-06-04 15:27:33 +02:00
AlexKucera 75a6eb61ea fix(progress): wire task_id through parallel progress callback
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.
2026-06-04 13:26:38 +02:00
AlexKucera 3dcae24d34 fix(orchestrator): Ctrl+C hangs and threading shutdown traceback
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.
2026-06-04 13:10:10 +02:00
AlexKuceraandClaude Opus 4.6 2a1a404350 fix(cli): remove redundant per-book verbose print in parallel downloads
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>
2026-06-04 11:32:16 +02:00
AlexKucera 722413a45b fix(cli): wire verbose flag through entry point
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.
2026-06-04 11:20:02 +02:00
AlexKucera 44fc544a3e Merge branch 'develop' into feature/parallel-downloads 2026-06-04 11:04:19 +02:00
AlexKucera a9a169d4c2 docs: update docs for XDG path resolution, bump v1.1.0
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
2026-06-04 10:54:43 +02:00
AlexKucera 01b14f1926 feat(cli): wire XDG path resolution into CLI layer
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
2026-06-04 10:32:31 +02:00
AlexKucera 3ba9f25903 feat(config): add XDG path resolution with CWD fallback
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
2026-06-04 10:00:52 +02:00
AlexKucera f1ee0dbc8e feat(orchestrator): add graceful Ctrl+C drain and parallel CLI tests (#17)
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.
2026-06-03 18:16:27 +02:00
AlexKuceraandpi c874eb31df docs(changelog): add orchestrator entry for Issue #16
Co-Authored-By: pi <pi@earendil.works>
2026-06-03 18:01:30 +02:00
AlexKucera 31cd52469a doc: moved changelog features
some post-1.0.0 featured had sneaked into old paragraphs
2026-06-03 17:35:31 +02:00
AlexKucera 35cd34b604 feat(progress): support concurrent multi-bar progress via per-book identity mapping
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
2026-06-03 17:30:16 +02:00
AlexKucera a18232c063 fix(history): make write() thread-safe
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
2026-06-03 17:15:57 +02:00
AlexKucera 7a0d8c1d18 feat(config): add workers field and --workers CLI flag
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
2026-06-03 17:07:50 +02:00
AlexKucera 61543204a8 docs: add MkDocs site and polished README (closes #10)
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.
2026-06-03 16:20:51 +02:00
AlexKucera e2da04ad92 fix(downloader): resolve path doubling and cover download failures
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.
2026-06-03 15:58:49 +02:00
AlexKucera 4aaae68a2e feat(cli): enhanced summary, graceful Ctrl+C, integration tests (closes #9)
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.
2026-06-03 15:00:27 +02:00
AlexKucera 6cefc79006 feat(progress): add TTY-aware download reporting (closes #8)
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.
2026-06-03 14:44:37 +02:00
AlexKucera aceaece504 feat(downloader): add PDF extras and cover art download (closes #7)
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.
2026-06-03 14:00:55 +02:00
AlexKucera 455d3dd172 feat(downloader): add MP3 fallback pipeline with ZIP download and format strategies (closes #6)
- 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
2026-06-03 13:22:45 +02:00
AlexKucera 33aa80b7aa feat(downloader): add M4B download pipeline with resume (closes #5)
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).
2026-06-03 12:56:41 +02:00
AlexKucera 25ee66b95d feat(downloader): add path resolution and sanitization (closes #4)
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.
2026-06-03 12:03:00 +02:00
AlexKucera 515f5c01f6 feat(client,history,cli): add auth, library fetch, and download history (closes #3)
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.
2026-06-03 11:44:16 +02:00
AlexKucera 6c049d1301 feat(config): add project scaffolding and config module (closes #2)
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.
2026-06-03 11:04:44 +02:00