diff --git a/.gitignore b/.gitignore index 6c60a2fe..892e797c 100644 --- a/.gitignore +++ b/.gitignore @@ -236,6 +236,7 @@ pyrightconfig.json *.local.* AGENTS.md .claude/ +CLAUDE.md .nvmrc .playwright-mcp/ frontend-dist/ diff --git a/docs/dev/release-sources-plugin-guide.md b/docs/dev/release-sources-plugin-guide.md index 10039aa3..37709201 100644 --- a/docs/dev/release-sources-plugin-guide.md +++ b/docs/dev/release-sources-plugin-guide.md @@ -276,6 +276,27 @@ class DownloadHandler(ABC): pass ``` +### Optional: Listing Files Before Download + +Some releases bundle several books (a whole-series torrent). Shelfmark inspects a +release before queueing it so the user can review how it will be split into books. +Override `list_files` when your source can enumerate a release's files without +downloading it; the default returns `None`, which the UI reports as "can't inspect": + +```python +from shelfmark.download.postprocess.packs import PackFile + +def list_files(self, release_data: dict[str, Any]) -> list[PackFile] | None: + """Return the release's files (release-relative paths + sizes), or None.""" + torrent_bytes = ... # e.g. fetch the .torrent, or scrape the indexer's detail page + return extract_file_list_from_torrent(torrent_bytes) # from download.clients.torrent_utils +``` + +`release_data` is the same payload the frontend sends to `/api/releases/download` +(`source_id`, `download_url`, `content_type`, `series_name`, ...). Built-in examples: +Prowlarr parses the `.torrent` it already fetches (magnet-only releases return +`None`), and AudiobookBay reads the file table off its detail page. + ### Download Method Parameters | Parameter | Type | Description | diff --git a/shelfmark/core/models.py b/shelfmark/core/models.py index d27ebd64..20fd3374 100644 --- a/shelfmark/core/models.py +++ b/shelfmark/core/models.py @@ -136,6 +136,12 @@ class DownloadTask: default_factory=dict ) # Per-output parameters (e.g. email recipient) + # Multi-book packs: one release holding several books. `book_plan` is the split the + # user approved before download (list of {title, series_position, year, files}); + # `multi_book` asks post-processing to split heuristically when no plan exists. + multi_book: bool = False + book_plan: list[dict[str, Any]] | None = None + # User association (multi-user support) user_id: int | None = None # DB user ID who queued this download username: str | None = None # Username for {User} template variable diff --git a/shelfmark/core/release_inspect_routes.py b/shelfmark/core/release_inspect_routes.py new file mode 100644 index 00000000..f9381628 --- /dev/null +++ b/shelfmark/core/release_inspect_routes.py @@ -0,0 +1,102 @@ +"""Pre-download release inspection: list a release's files and plan a multi-book split.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from flask import jsonify, request + +from shelfmark.core.logger import setup_logger +from shelfmark.core.utils import is_audiobook +from shelfmark.download.postprocess.packs import PackFile, PackPlan, plan_pack +from shelfmark.download.postprocess.policy import ( + get_supported_audiobook_formats, + get_supported_formats, +) +from shelfmark.release_sources import get_handler + +if TYPE_CHECKING: + from collections.abc import Callable + + from flask import Flask, Response + +logger = setup_logger(__name__) + +_INSPECT_ERRORS = (OSError, RuntimeError, ValueError, TypeError, KeyError, AttributeError) +NOT_INSPECTABLE_REASON = "This source cannot list the release's files before downloading" + + +def _serialize_plan(plan: PackPlan) -> dict[str, Any]: + return { + "is_pack": plan.is_pack, + "ignored": plan.ignored, + "books": [ + { + "title": book.title, + "series_position": book.series_position, + "year": book.year, + "files": book.files, + } + for book in plan.books + ], + } + + +def inspect_release(data: dict[str, Any]) -> dict[str, Any]: + """Build the inspect response for a release payload (same shape as a download).""" + source = str(data["source"]) + handler = get_handler(source) + try: + files: list[PackFile] | None = handler.list_files(data) + except _INSPECT_ERRORS as exc: + logger.warning( + "Could not list files for %s release %s: %s", source, data.get("source_id"), exc + ) + return {"inspected": False, "reason": str(exc), "files": [], "plan": None} + + if files is None: + return {"inspected": False, "reason": NOT_INSPECTABLE_REASON, "files": [], "plan": None} + + content_type = data.get("content_type") + supported = ( + get_supported_audiobook_formats() + if is_audiobook(content_type if isinstance(content_type, str) else None) + else get_supported_formats() + ) + series_name = data.get("series_name") + author_name = data.get("author") + plan = plan_pack( + files, + supported_extensions=set(supported), + series_name=series_name if isinstance(series_name, str) else None, + author_name=author_name if isinstance(author_name, str) else None, + ) + return { + "inspected": True, + "reason": None, + "files": [{"path": f.path, "size": f.size} for f in files], + "plan": _serialize_plan(plan), + } + + +def register_release_inspect_routes( + app: Flask, + login_required: Callable[..., Any], +) -> None: + """Register POST /api/releases/inspect.""" + + @app.route("/api/releases/inspect", methods=["POST"]) + @login_required + def api_inspect_release() -> Response | tuple[Response, int]: + data = request.get_json(silent=True) + if not isinstance(data, dict): + return jsonify({"error": "No data provided"}), 400 + if not data.get("source_id"): + return jsonify({"error": "source_id is required"}), 400 + if not data.get("source"): + return jsonify({"error": "source is required"}), 400 + try: + get_handler(str(data["source"])) + except ValueError as exc: + return jsonify({"error": str(exc)}), 400 + return jsonify(inspect_release(data)) diff --git a/shelfmark/download/clients/torrent_utils.py b/shelfmark/download/clients/torrent_utils.py index fd810540..526d1130 100644 --- a/shelfmark/download/clients/torrent_utils.py +++ b/shelfmark/download/clients/torrent_utils.py @@ -17,6 +17,7 @@ from shelfmark.core.config import config from shelfmark.core.logger import setup_logger from shelfmark.core.utils import normalize_http_url from shelfmark.download.network import get_ssl_verify +from shelfmark.download.postprocess.packs import PackFile logger = setup_logger(__name__) @@ -433,6 +434,56 @@ def extract_info_hash_from_torrent(torrent_data: bytes) -> str | None: return None +def _decode_torrent_text(value: object) -> str | None: + if isinstance(value, bytes): + return value.decode("utf-8", errors="replace") + if isinstance(value, str): + return value + return None + + +def extract_file_list_from_torrent(torrent_data: bytes) -> list[PackFile] | None: + """List the files a .torrent describes, release-relative, without downloading it. + + Multi-file torrents nest every path under the torrent name (which becomes the + client's save folder); single-file torrents are just the named file. + """ + try: + decoded, _ = bencode_decode(torrent_data) + except _TORRENT_PARSE_ERRORS as e: + logger.debug("Failed to parse torrent file list: %s", e) + return None + if not isinstance(decoded, dict): + return None + info = decoded.get(b"info") + if not isinstance(info, dict): + return None + + name = _decode_torrent_text(info.get(b"name")) or "" + raw_files = info.get(b"files") + if not isinstance(raw_files, list): + length = info.get(b"length") + if not name: + return None + return [PackFile(name, length if isinstance(length, int) else None)] + + files: list[PackFile] = [] + for entry in raw_files: + if not isinstance(entry, dict): + continue + raw_path = entry.get(b"path") + if not isinstance(raw_path, list): + continue + segments = [seg for seg in (_decode_torrent_text(part) for part in raw_path) if seg] + if not segments: + continue + if name: + segments.insert(0, name) + length = entry.get(b"length") + files.append(PackFile("/".join(segments), length if isinstance(length, int) else None)) + return files + + def extract_hash_from_magnet(magnet_url: str) -> str | None: """Extract info_hash from a magnet URL.""" if not magnet_url.startswith("magnet:"): diff --git a/shelfmark/download/orchestrator.py b/shelfmark/download/orchestrator.py index bd4b38f2..cfc03b94 100644 --- a/shelfmark/download/orchestrator.py +++ b/shelfmark/download/orchestrator.py @@ -265,6 +265,8 @@ def queue_release( series_position = release_data.get("series_position") or extra.get("series_position") subtitle = release_data.get("subtitle") or extra.get("subtitle") language = release_data.get("language") or extra.get("language") + multi_book = bool(release_data.get("multi_book") or extra.get("multi_book")) + book_plan = _normalize_book_plan(release_data.get("book_plan") or extra.get("book_plan")) books_output_mode = ( str(config.get("BOOKS_OUTPUT_MODE", "folder", user_id=user_id) or "folder") @@ -300,6 +302,8 @@ def queue_release( series_position=series_position, subtitle=subtitle, language=language, + multi_book=multi_book or book_plan is not None, + book_plan=book_plan, search_mode=search_mode, output_mode=output_mode, output_args=output_args, @@ -408,6 +412,33 @@ def can_retry_download_task( return _has_staged_retry_source(task) +def _normalize_book_plan(value: object) -> list[dict[str, Any]] | None: + """Keep only well-formed pack books: a title plus a non-empty list of file paths.""" + if not isinstance(value, list): + return None + books: list[dict[str, Any]] = [] + for entry in value: + if not isinstance(entry, dict): + continue + title = normalize_optional_text(entry.get("title")) + raw_files = entry.get("files") + if title is None or not isinstance(raw_files, list): + continue + files = [f for f in raw_files if isinstance(f, str) and f.strip()] + if not files: + continue + year = entry.get("year") + books.append( + { + "title": title, + "series_position": _optional_number(entry.get("series_position")), + "year": year if isinstance(year, int) and not isinstance(year, bool) else None, + "files": files, + } + ) + return books or None + + def serialize_task_for_retry(task: DownloadTask) -> dict[str, Any]: """Serialize the task state needed for restart-safe retries.""" raw_search_mode = getattr(task, "search_mode", None) @@ -437,6 +468,8 @@ def serialize_task_for_retry(task: DownloadTask) -> dict[str, Any]: "subtitle": getattr(task, "subtitle", None), "language": getattr(task, "language", None), "search_mode": search_mode, + "multi_book": bool(getattr(task, "multi_book", False)), + "book_plan": _normalize_book_plan(getattr(task, "book_plan", None)), "output_mode": getattr(task, "output_mode", None), "output_args": dict(raw_output_args) if isinstance(raw_output_args, dict) else {}, "user_id": getattr(task, "user_id", None), @@ -495,6 +528,8 @@ def _restore_task_from_retry_payload(payload: object) -> DownloadTask | None: subtitle=normalize_optional_text(payload.get("subtitle")), language=normalize_optional_text(payload.get("language")), search_mode=search_mode, + multi_book=bool(payload.get("multi_book", False)), + book_plan=_normalize_book_plan(payload.get("book_plan")), output_mode=normalize_optional_text(payload.get("output_mode")), output_args=dict(output_args) if isinstance(output_args, dict) else {}, user_id=normalize_positive_int(payload.get("user_id")), diff --git a/shelfmark/download/outputs/folder.py b/shelfmark/download/outputs/folder.py index 7e3278f2..3f549d35 100644 --- a/shelfmark/download/outputs/folder.py +++ b/shelfmark/download/outputs/folder.py @@ -105,6 +105,7 @@ def process_folder_output( maybe_run_custom_script, prepare_output_files, record_step, + resolve_book_groups, transfer_book_files, ) @@ -260,7 +261,15 @@ def process_folder_output( prepared.cleanup_paths, ) - message = "Complete" if len(final_paths) == 1 else f"Complete ({len(final_paths)} files)" + pack_groups = resolve_book_groups( + task, prepared.files, organization_mode=plan.organization_mode + ) + if pack_groups is not None: + message = f"Complete ({len(pack_groups)} books, {len(final_paths)} files)" + elif len(final_paths) == 1: + message = "Complete" + else: + message = f"Complete ({len(final_paths)} files)" status_callback("complete", message) return str(final_paths[0]) diff --git a/shelfmark/download/postprocess/packs.py b/shelfmark/download/postprocess/packs.py new file mode 100644 index 00000000..ee13dc25 --- /dev/null +++ b/shelfmark/download/postprocess/packs.py @@ -0,0 +1,406 @@ +"""Multi-book ("pack") release planning. + +A pack is one release that contains several books: a whole-series torrent with one +subfolder per book, or a flat folder of `Series 1.0 - Title.m4b` files. The same +planning rules serve pre-download inspection (the file list comes from the release +source) and post-processing (the file list comes from disk), so what the user +approved in the modal is what gets filed. +""" + +from __future__ import annotations + +import os +import re +from dataclasses import dataclass +from pathlib import Path, PurePosixPath + +_YEAR_SUFFIX_RE = re.compile(r"\s*\(\s*(?P\d{4})\s*\)\s*$") +_SERIES_MARKER_RE = re.compile( + r""" + ^\s* + (?: + \[\s*\#?(?P\d+(?:\.\d+)?)\s*\] # [03] / [#3] + | \#(?P\d+(?:\.\d+)?) # #3 + | book\.?\s*(?P\d+(?:\.\d+)?) # Book 3 / Book. 03 + | (?P\d+(?:\.\d+)?)(?=[\s\-:.]) # 03 - / 1.0 - / 3. + ) + \s*(?:[-:.]\s*)? + """, + re.IGNORECASE | re.VERBOSE, +) +_SEPARATOR_CHARS = " \t-_:." +# "Gods of Risk 2.5 - Gods of Risk": the title repeated on both sides of the position. +_REPEATED_TITLE_RE = re.compile( + r"^(?P.+?)\s+(?P\d+(?:\.\d+)?)\s*[-:\u2013]\s*(?P.+)$" +) +_SERIES_LABEL_WORDS = r"(?:novella|novellas|short\s+story|short|story|novel)" +# "Uncrowned Cradle, Book 7" / "Reaper Cradle, Volume 10" / "Wintersteel (Cradle, Book 8)": +# an explicit word marks the position at the END of the name. A bare trailing number +# is deliberately not matched — "Title - 02" is a chapter, not a series position. +_TRAILING_MARKER_RE = re.compile( + r""" + [\s,\-:\u2013(]* + (?:book|volume|vol\.?)\s*\#?(?P\d+(?:\.\d+)?) + \s*\)?\s*$ + """, + re.IGNORECASE | re.VERBOSE, +) +# AudiobookBay renders a file inside a folder as " " with no separator, +# so a pack row reads "Author - Title Series, Book 1 Title Series, Book 1". +_GLUED_FOLDER_RE = re.compile( + r"^(?P.+?\s[-\u2013]\s)?(?P.+?)\s+(?P=core)$", re.IGNORECASE +) + + +@dataclass(frozen=True) +class PackFile: + """One file inside a release, path relative to the release root.""" + + path: str + size: int | None = None + + +@dataclass(frozen=True) +class PackBook: + """One book split out of a pack, files as release-relative paths.""" + + title: str + series_position: float | None + year: int | None + files: list[str] + + +@dataclass(frozen=True) +class PackPlan: + books: list[PackBook] + ignored: list[str] + + @property + def is_pack(self) -> bool: + return len(self.books) > 1 + + +@dataclass(frozen=True) +class BookGroup: + """One book's on-disk files, ready for transfer.""" + + title: str + series_position: float | None + year: int | None + files: list[Path] + + +def _strip_series_name(name: str, series_name: str | None) -> str: + if not series_name: + return name + prefix = series_name.strip() + if not prefix or not name.lower().startswith(prefix.lower()): + return name + remainder = name[len(prefix) :] + if remainder and remainder[0].isalnum(): + return name + return remainder.lstrip(_SEPARATOR_CHARS) + + +def _strip_series_label(work: str, series_name: str | None) -> str: + """Drop a leading "An Novella - " style label that some packs prepend.""" + if not series_name: + return work + # "The Expanse" is labelled "An Expanse Novella", so match without the article. + core = re.sub(r"^(?:the|an?)\s+", "", series_name.strip(), flags=re.IGNORECASE) + if not core: + return work + pattern = re.compile( + rf"^(?:an?\s+|the\s+)?{re.escape(core)}\s+{_SERIES_LABEL_WORDS}\s*[-:\u2013]\s*", + re.IGNORECASE, + ) + return pattern.sub("", work, count=1) + + +def _collapse_glued_folder(name: str) -> str: + match = _GLUED_FOLDER_RE.match(name) + if not match: + return name + prefix = match.group("prefix") or "" + core = match.group("core") + # "Author - X X" → "Author - X" (the folder carried the author, the file did not). + return (prefix + core).strip() + + +def _strip_author_name(name: str, author_name: str | None) -> str: + """Drop a leading "Author - " (packs are often filed as `Author - Title`).""" + if not author_name: + return name + prefix = author_name.strip() + if not prefix or not name.lower().startswith(prefix.lower()): + return name + remainder = name[len(prefix) :] + stripped = remainder.lstrip(_SEPARATOR_CHARS + "\u2013") + if stripped == remainder: # no separator after the author: part of the title + return name + return stripped + + +def _strip_trailing_series_name(work: str, series_name: str | None) -> str: + """Drop a trailing series name left behind by a trailing position marker.""" + if not series_name: + return work + suffix = series_name.strip() + if not suffix or not work.lower().endswith(suffix.lower()): + return work + remainder = work[: -len(suffix)] + stripped = remainder.rstrip(_SEPARATOR_CHARS + ",(\u2013") + if not stripped or stripped == remainder: + return work + return stripped + + +def parse_pack_book_name( + name: str, *, series_name: str | None, author_name: str | None = None +) -> tuple[str, float | None, int | None]: + """Split a book folder/file-stem name into (title, series position, year). + + Strips a leading series name, a leading position marker (`Book 3 - `, `03 - `, + `1.0 - `, `3. `, `[03] `, `#3 `) and a trailing `(YYYY)`. Also understands a + trailing marker (`Title Series, Book 3`, `Title (Series, Volume 3)`), a leading + `Author - `, and AudiobookBay's glued ` ` names. Returns the name + unchanged with no position/year when nothing would be left of the title. + """ + work = _collapse_glued_folder(name.strip()) + work = _strip_author_name(work, author_name) + work = _strip_series_name(work, series_name) + + year: int | None = None + year_match = _YEAR_SUFFIX_RE.search(work) + if year_match: + year = int(year_match.group("year")) + work = work[: year_match.start()] + + position: float | None = None + repeated = _REPEATED_TITLE_RE.match(work.strip()) + if ( + repeated + and repeated.group("left").strip().lower() == repeated.group("right").strip().lower() + ): + return repeated.group("right").strip(), float(repeated.group("position")), year + + marker = _SERIES_MARKER_RE.match(work) + if marker: + raw = ( + marker.group("bracket") + or marker.group("hash") + or marker.group("book") + or marker.group("plain") + ) + position = float(raw) + work = work[marker.end() :] + else: + trailing = _TRAILING_MARKER_RE.search(work) + if trailing and trailing.start() > 0: + position = float(trailing.group("position")) + work = _strip_trailing_series_name(work[: trailing.start()], series_name) + + work = _strip_series_label(work, series_name) + title = work.strip().strip(_SEPARATOR_CHARS).strip() + if not title: + return name, None, None + return title, position, year + + +def _book_from_name( + name: str, files: list[str], series_name: str | None, author_name: str | None = None +) -> PackBook: + title, position, year = parse_pack_book_name( + name, series_name=series_name, author_name=author_name + ) + return PackBook(title=title, series_position=position, year=year, files=files) + + +def _common_root_parts(paths: list[PurePosixPath]) -> tuple[str, ...]: + parents = [p.parent.parts for p in paths] + common: list[str] = [] + for parts in zip(*parents, strict=False): + if len(set(parts)) != 1: + break + common.append(parts[0]) + return tuple(common) + + +def plan_pack( + files: list[PackFile], + *, + supported_extensions: set[str], + series_name: str | None, + author_name: str | None = None, + root_depth: int | None = None, +) -> PackPlan: + """Group a release's file list into books. + + Files in a subfolder (relative to the common root) group by that subfolder. Files + directly in the root split one-book-per-file only when at least two of them carry + a series position in their names; otherwise they are one book (a chaptered + audiobook, e.g. `01.mp3`, `02.mp3`). `root_depth` fixes how many leading path + components form the root instead of deriving it from the files' common parent. + """ + supported = {ext.lower().lstrip(".") for ext in supported_extensions} + book_files: list[PurePosixPath] = [] + ignored: list[str] = [] + for pack_file in files: + rel = PurePosixPath(pack_file.path.replace("\\", "/").lstrip("./")) + if rel.suffix.lower().lstrip(".") in supported: + book_files.append(rel) + else: + ignored.append(pack_file.path) + + if not book_files: + return PackPlan(books=[], ignored=ignored) + + root_parts = ( + _common_root_parts(book_files) if root_depth is None else book_files[0].parts[:root_depth] + ) + depth = len(root_parts) + + root_files: list[PurePosixPath] = [] + folders: dict[str, list[str]] = {} + for rel in book_files: + remainder = rel.parts[depth:] + if len(remainder) > 1: + folders.setdefault(remainder[0], []).append(str(rel)) + else: + root_files.append(rel) + + books: list[PackBook] = [] + if root_files: + parsed = [ + parse_pack_book_name(f.stem, series_name=series_name, author_name=author_name) + for f in root_files + ] + positions = {p[1] for p in parsed if p[1] is not None} + if len(positions) >= 2: + books.extend( + PackBook(title=title, series_position=position, year=year, files=[str(f)]) + for f, (title, position, year) in zip(root_files, parsed, strict=True) + ) + elif len(root_files) == 1: + books.append( + _book_from_name(root_files[0].stem, [str(root_files[0])], series_name, author_name) + ) + else: + group_name = root_parts[-1] if root_parts else "" + books.append( + _book_from_name(group_name, [str(f) for f in root_files], series_name, author_name) + ) + + books.extend( + _book_from_name(folder, paths, series_name, author_name) + for folder, paths in folders.items() + ) + return PackPlan(books=books, ignored=ignored) + + +def _relative_paths( + book_files: list[Path], root: Path | None = None +) -> tuple[Path, dict[Path, str]]: + if root is None: + root = Path(os.path.commonpath([str(f.parent) for f in book_files])) + return root, {f: f.relative_to(root).as_posix() for f in book_files} + + +def group_files_into_books( + book_files: list[Path], + *, + series_name: str | None, + author_name: str | None = None, + root: Path | None = None, +) -> list[BookGroup]: + """Heuristically split on-disk files into books (see `plan_pack`). + + `root` pins the release root when grouping a subset of a larger file set. + """ + if not book_files: + return [] + _root, rel_by_path = _relative_paths(book_files, root) + path_by_rel = {rel: path for path, rel in rel_by_path.items()} + extensions = {f.suffix.lower().lstrip(".") for f in book_files} + plan = plan_pack( + [PackFile(rel) for rel in rel_by_path.values()], + supported_extensions=extensions, + series_name=series_name, + author_name=author_name, + root_depth=None if root is None else 0, + ) + return [ + BookGroup( + title=book.title, + series_position=book.series_position, + year=book.year, + files=[path_by_rel[rel] for rel in book.files], + ) + for book in plan.books + ] + + +def match_plan_to_files( + plan: list[PackBook], + book_files: list[Path], + *, + series_name: str | None = None, + author_name: str | None = None, +) -> list[BookGroup]: + """Apply an approved plan to on-disk files. + + Files match by release-relative path first, then by basename (archive extraction + and client save paths can shift the root), then by the on-disk basename being a + suffix of the planned name (sources that glue folder and file names together). + Book files the plan does not mention fall back to heuristic grouping so nothing + is silently dropped. + """ + if not book_files: + return [] + root, rel_by_path = _relative_paths(book_files) + by_rel = {rel: path for path, rel in rel_by_path.items()} + by_name: dict[str, list[Path]] = {} + for path in book_files: + by_name.setdefault(path.name, []).append(path) + + claimed: set[Path] = set() + groups: list[BookGroup] = [] + for book in plan: + matched: list[Path] = [] + for wanted in book.files: + wanted_rel = wanted.replace("\\", "/").lstrip("./") + candidate = by_rel.get(wanted_rel) + if candidate is None: + candidates = [ + p for p in by_name.get(PurePosixPath(wanted_rel).name, []) if p not in claimed + ] + candidate = candidates[0] if candidates else None + if candidate is None: + wanted_name = PurePosixPath(wanted_rel).name.lower() + candidates = [ + p + for p in book_files + if p not in claimed and wanted_name.endswith(p.name.lower()) + ] + candidate = candidates[0] if len(candidates) == 1 else None + if candidate is not None and candidate not in claimed: + claimed.add(candidate) + matched.append(candidate) + if matched: + groups.append( + BookGroup( + title=book.title, + series_position=book.series_position, + year=book.year, + files=matched, + ) + ) + + unmatched = [p for p in book_files if p not in claimed] + if unmatched: + groups.extend( + group_files_into_books( + unmatched, series_name=series_name, author_name=author_name, root=root + ) + ) + return groups diff --git a/shelfmark/download/postprocess/pipeline.py b/shelfmark/download/postprocess/pipeline.py index f015350f..c9034c56 100644 --- a/shelfmark/download/postprocess/pipeline.py +++ b/shelfmark/download/postprocess/pipeline.py @@ -40,6 +40,7 @@ from .transfer import ( build_metadata_dict, is_torrent_source, process_directory, + resolve_book_groups, resolve_hardlink_source, should_hardlink, transfer_book_files, @@ -80,6 +81,7 @@ __all__ = [ "process_directory", "record_step", "resolve_custom_script_target", + "resolve_book_groups", "resolve_hardlink_source", "run_custom_script", "safe_cleanup_path", diff --git a/shelfmark/download/postprocess/transfer.py b/shelfmark/download/postprocess/transfer.py index 94118ca7..efdc0540 100644 --- a/shelfmark/download/postprocess/transfer.py +++ b/shelfmark/download/postprocess/transfer.py @@ -2,6 +2,7 @@ from __future__ import annotations +import dataclasses import os from pathlib import Path from typing import TYPE_CHECKING @@ -26,6 +27,7 @@ from shelfmark.download.fs import ( ) from shelfmark.download.postprocess.policy import get_file_organization, get_template +from .packs import BookGroup, PackBook, group_files_into_books, match_plan_to_files from .scan import collect_directory_files, scan_directory_tree from .types import TransferPlan from .workspace import safe_cleanup_path @@ -196,6 +198,19 @@ def transfer_book_files( is_audiobook = check_audiobook(task.content_type) organization_mode = organization_mode or get_file_organization(is_audiobook=is_audiobook) + + groups = resolve_book_groups(task, book_files, organization_mode=organization_mode) + if groups is not None: + return _transfer_book_groups( + groups, + destination, + task, + use_hardlink=use_hardlink, + is_torrent=is_torrent, + preserve_source=preserve_source, + organization_mode=organization_mode, + ) + max_attempts = _max_attempts_for_batch(len(book_files)) final_paths: list[Path] = [] @@ -299,6 +314,101 @@ def transfer_book_files( return final_paths, None, op_counts +def resolve_book_groups( + task: DownloadTask, + book_files: list[Path], + *, + organization_mode: str, +) -> list[BookGroup] | None: + """Split a multi-book pack into per-book groups, or None to file as one book. + + An approved `book_plan` wins; a bare `multi_book` flag falls back to heuristic + grouping. Organization `none` keeps files as-is, and a split that yields a single + group is not a pack at all. + """ + if organization_mode == "none" or not (task.book_plan or task.multi_book): + return None + if task.book_plan: + plan = [ + PackBook( + title=str(entry.get("title") or ""), + series_position=entry.get("series_position"), + year=entry.get("year"), + files=list(entry.get("files") or []), + ) + for entry in task.book_plan + if isinstance(entry, dict) + ] + groups = match_plan_to_files( + plan, book_files, series_name=task.series_name, author_name=task.author + ) + else: + groups = group_files_into_books( + book_files, series_name=task.series_name, author_name=task.author + ) + return groups if len(groups) > 1 else None + + +def _transfer_book_groups( + groups: list[BookGroup], + destination: Path, + task: DownloadTask, + *, + use_hardlink: bool, + is_torrent: bool, + preserve_source: bool, + organization_mode: str, +) -> tuple[list[Path], str | None, dict[str, int]]: + """Transfer each book of a pack through the normal single-book path. + + Each book gets an isolated task copy (the single-file path mutates `task.format`) + carrying its own title, position and year; the searched book's position must not + leak onto its siblings, while author and series name apply to all of them. + """ + all_paths: list[Path] = [] + totals: dict[str, int] = {"hardlink": 0, "copy": 0, "move": 0} + errors: list[str] = [] + + for group in groups: + book_task = dataclasses.replace( + task, + title=group.title or task.title, + year=str(group.year) if group.year is not None else None, + subtitle=None, + series_position=group.series_position, + multi_book=False, + book_plan=None, + ) + paths, error, op_counts = transfer_book_files( + group.files, + destination, + book_task, + use_hardlink=use_hardlink, + is_torrent=is_torrent, + preserve_source=preserve_source, + organization_mode=organization_mode, + source_root=group.files[0].parent, + ) + for op, count in op_counts.items(): + totals[op] = totals.get(op, 0) + count + if error: + errors.append(f"{group.title}: {error}") + logger.warning("Task %s: pack book %r failed: %s", task.task_id, group.title, error) + continue + all_paths.extend(paths) + + if not all_paths: + return [], "; ".join(errors) or "No book files found", totals + if errors: + logger.warning( + "Task %s: pack filed with %d failed book(s): %s", + task.task_id, + len(errors), + "; ".join(errors), + ) + return all_paths, None, totals + + def process_directory( directory: Path, ingest_dir: Path, diff --git a/shelfmark/main.py b/shelfmark/main.py index 68903b34..5f60008b 100644 --- a/shelfmark/main.py +++ b/shelfmark/main.py @@ -62,6 +62,7 @@ from shelfmark.core.notifications import ( notify_user, ) from shelfmark.core.prefix_middleware import PrefixMiddleware +from shelfmark.core.release_inspect_routes import register_release_inspect_routes from shelfmark.core.request_helpers import ( coerce_bool, emit_ws_event, @@ -1024,6 +1025,9 @@ def _serialize_release(release: Release) -> dict: return result +register_release_inspect_routes(app, login_required) + + @app.route("/api/releases/download", methods=["POST"]) @login_required def api_download_release() -> Response | tuple[Response, int]: diff --git a/shelfmark/release_sources/__init__.py b/shelfmark/release_sources/__init__.py index b0c751d4..deb69e40 100644 --- a/shelfmark/release_sources/__init__.py +++ b/shelfmark/release_sources/__init__.py @@ -13,6 +13,7 @@ if TYPE_CHECKING: from shelfmark.core.models import DownloadTask from shelfmark.core.search_plan import ReleaseSearchPlan + from shelfmark.download.postprocess.packs import PackFile from shelfmark.metadata_providers import BookMetadata @@ -400,6 +401,14 @@ class DownloadHandler(ABC): """Return private queue-time fields needed for restart-safe retry.""" return {} + def list_files(self, release_data: dict[str, Any]) -> list[PackFile] | None: + """Return the release's file list without downloading it. + + Lets the UI review a multi-book pack before queueing. Return None when the + source cannot know the files ahead of time (magnet links, usenet, ...). + """ + return None + @abstractmethod def cancel(self, task_id: str) -> bool: """Cancel an in-progress download.""" diff --git a/shelfmark/release_sources/audiobookbay/handler.py b/shelfmark/release_sources/audiobookbay/handler.py index 723fbfcc..f080ec9f 100644 --- a/shelfmark/release_sources/audiobookbay/handler.py +++ b/shelfmark/release_sources/audiobookbay/handler.py @@ -1,6 +1,6 @@ """AudiobookBay download handler - resolves magnet links and uses shared client lifecycle.""" -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from urllib.parse import urlparse from shelfmark.core.config import config @@ -22,6 +22,7 @@ if TYPE_CHECKING: from collections.abc import Callable from shelfmark.core.models import DownloadTask + from shelfmark.download.postprocess.packs import PackFile logger = setup_logger(__name__) DEFAULT_ABB_HOSTNAME = "audiobookbay.lu" @@ -68,6 +69,19 @@ class AudiobookBayHandler(ExternalClientHandler): return task_id return None + def list_files(self, release_data: dict[str, Any]) -> list[PackFile] | None: + """Read the torrent's file list off the detail page, without downloading.""" + raw_url = release_data.get("download_url") or release_data.get("source_url") + detail_url = raw_url.strip() if isinstance(raw_url, str) else "" + hostname = _resolve_allowed_detail_hostname() + if not detail_url or not _detail_url_matches_host(detail_url, hostname): + logger.debug("Cannot list files for AudiobookBay release without a valid detail URL") + return None + detail_html = scraper.fetch_detail_html(detail_url, hostname) + if not detail_html: + return None + return scraper.extract_file_list(detail_html) + def _get_client(self, protocol: str) -> DownloadClient | None: """Compatibility shim so module-level patching still works in tests.""" return get_client(protocol) diff --git a/shelfmark/release_sources/audiobookbay/scraper.py b/shelfmark/release_sources/audiobookbay/scraper.py index 217fe7d3..7fd65b14 100644 --- a/shelfmark/release_sources/audiobookbay/scraper.py +++ b/shelfmark/release_sources/audiobookbay/scraper.py @@ -2,6 +2,7 @@ import re import time +from threading import Lock from urllib.parse import quote, quote_plus import requests @@ -10,6 +11,7 @@ from bs4 import BeautifulSoup from shelfmark.core.config import config from shelfmark.core.logger import setup_logger from shelfmark.download import http as downloader +from shelfmark.download.postprocess.packs import PackFile from shelfmark.release_sources.audiobookbay.utils import normalize_search_punctuation logger = setup_logger(__name__) @@ -32,6 +34,13 @@ FIRST_PAGE_SESSION_REFRESH_ATTEMPTS = 2 # Legacy search parameter used by older ABB flows LEGACY_CATEGORY_QUERY = "undefined%2Cundefined" +# Detail pages are fetched once and shared by inspection (file list) and download +# (magnet link) so a "review then download" round trip costs ABB a single request. +DETAIL_PAGE_CACHE_TTL_SECONDS = 120.0 +DETAIL_PAGE_CACHE_MAX_ENTRIES = 8 +_detail_page_cache: dict[str, tuple[float, str]] = {} +_detail_page_cache_lock = Lock() + # Precompiled patterns used while parsing result cards LANGUAGE_PATTERN = re.compile(r"Language:\s*([A-Za-z]+)") POSTED_PATTERN = re.compile(r"Posted:\s*(\d+\s+[A-Za-z]+\s+\d{4})") @@ -39,6 +48,11 @@ FORMAT_PATTERN = re.compile(r"Format:\s*([A-Za-z0-9]+)") BITRATE_PATTERN = re.compile(r"Bitrate:\s*([\d]+\s*[A-Za-z/]+)") SIZE_PATTERN = re.compile(r"File Size:\s*([\d.]+)\s*([A-Za-z]+)") INFO_HASH_LABEL_PATTERN = re.compile(r"Info Hash", re.IGNORECASE) +FILE_ROW_SIZE_PATTERN = re.compile( + r"^(?P.+?)\s+(?P\d+(?:\.\d+)?)\s*(?PBytes?|KBs?|MBs?|GBs?|TBs?)$", + re.IGNORECASE, +) +_FILE_SIZE_MULTIPLIERS = {"b": 1, "k": 1024, "m": 1024**2, "g": 1024**3, "t": 1024**4} def _coerce_non_negative_float(value: object, default: float) -> float: @@ -348,6 +362,98 @@ def search_audiobookbay( return results +def _get_cached_detail_page(details_url: str) -> str | None: + with _detail_page_cache_lock: + entry = _detail_page_cache.get(details_url) + if entry is None: + return None + fetched_at, html = entry + if time.monotonic() - fetched_at > DETAIL_PAGE_CACHE_TTL_SECONDS: + del _detail_page_cache[details_url] + return None + return html + + +def _store_cached_detail_page(details_url: str, html: str) -> None: + with _detail_page_cache_lock: + _detail_page_cache[details_url] = (time.monotonic(), html) + while len(_detail_page_cache) > DETAIL_PAGE_CACHE_MAX_ENTRIES: + oldest = min(_detail_page_cache, key=lambda key: _detail_page_cache[key][0]) + del _detail_page_cache[oldest] + + +def clear_detail_page_cache() -> None: + """Drop cached detail pages (used by tests).""" + with _detail_page_cache_lock: + _detail_page_cache.clear() + + +def _fetch_detail_page_once(details_url: str, hostname: str) -> str: + session = requests.Session() + _bootstrap_abb_session(hostname, session, DETAIL_PAGE_RETRY_ATTEMPTS) + return _coerce_markup_to_html( + downloader.html_get_page( + details_url, + retry=DETAIL_PAGE_RETRY_ATTEMPTS, + use_bypasser=False, + allow_bypasser_fallback=False, + success_delay=0, + session=session, + ) + ) + + +def fetch_detail_html(details_url: str, hostname: str = "audiobookbay.lu") -> str: + """Fetch a detail page (one retry with a fresh session), cached briefly per URL.""" + cached = _get_cached_detail_page(details_url) + if cached is not None: + logger.debug("Reusing recently fetched detail page: %s", details_url) + return cached + detail_html = _fetch_detail_page_once(details_url, hostname) + if not detail_html: + detail_html = _fetch_detail_page_once(details_url, hostname) + if detail_html: + _store_cached_detail_page(details_url, detail_html) + return detail_html + + +def _parse_file_row(text: str) -> PackFile | None: + match = FILE_ROW_SIZE_PATTERN.match(text.strip()) + if not match: + return None + multiplier = _FILE_SIZE_MULTIPLIERS[match.group("unit")[0].lower()] + return PackFile(match.group("name"), int(float(match.group("size")) * multiplier)) + + +def extract_file_list(detail_html: str) -> list[PackFile] | None: + """Read the torrent file rows off a detail page. + + ABB renders the torrent's file table as single-cell rows between the + "This is a Multifile Torrent" marker (absent for single-file torrents) and the + "Combined File Size" row. Returns None when the page has no such table. + """ + soup = BeautifulSoup(detail_html, "html.parser") + rows: list[PackFile] = [] + for row in soup.find_all("tr"): + cells = row.find_all("td") + if not cells: + continue + label = cells[0].get_text(" ", strip=True) + if label.lower().startswith("combined file size"): + return rows or None + if len(cells) != 1: + rows = [] # a two-column metadata row means we're not in the file table yet + continue + text = cells[0].get_text(" ", strip=True) + if "multifile torrent" in text.lower(): + rows = [] + continue + parsed = _parse_file_row(text) + if parsed is not None: + rows.append(parsed) + return None + + def extract_magnet_link(details_url: str, hostname: str = "audiobookbay.lu") -> str | None: """Extract info hash and trackers from book detail page, then construct magnet link. @@ -360,35 +466,7 @@ def extract_magnet_link(details_url: str, hostname: str = "audiobookbay.lu") -> """ try: - session = requests.Session() - _bootstrap_abb_session(hostname, session, DETAIL_PAGE_RETRY_ATTEMPTS) - - # Fetch detail page - detail_html = _coerce_markup_to_html( - downloader.html_get_page( - details_url, - retry=DETAIL_PAGE_RETRY_ATTEMPTS, - use_bypasser=False, - allow_bypasser_fallback=False, - success_delay=0, - session=session, - ) - ) - - if not detail_html: - session = requests.Session() - _bootstrap_abb_session(hostname, session, DETAIL_PAGE_RETRY_ATTEMPTS) - detail_html = _coerce_markup_to_html( - downloader.html_get_page( - details_url, - retry=DETAIL_PAGE_RETRY_ATTEMPTS, - use_bypasser=False, - allow_bypasser_fallback=False, - success_delay=0, - session=session, - ) - ) - + detail_html = fetch_detail_html(details_url, hostname) if not detail_html: logger.warning("Failed to fetch details page") return None diff --git a/shelfmark/release_sources/prowlarr/handler.py b/shelfmark/release_sources/prowlarr/handler.py index cf432ad7..78ca74c5 100644 --- a/shelfmark/release_sources/prowlarr/handler.py +++ b/shelfmark/release_sources/prowlarr/handler.py @@ -28,6 +28,10 @@ from shelfmark.download.clients.base_handler import ( DownloadRequest, ExternalClientHandler, ) +from shelfmark.download.clients.torrent_utils import ( + extract_file_list_from_torrent, + extract_torrent_info, +) from shelfmark.metadata_providers import BookMetadata from shelfmark.release_sources import register_handler from shelfmark.release_sources.prowlarr.api import IndexerSeedSettings, ProwlarrClient @@ -38,12 +42,14 @@ from shelfmark.release_sources.prowlarr.utils import ( coerce_int_like, get_preferred_download_url, get_protocol, + sanitize_download_url, ) if TYPE_CHECKING: from collections.abc import Callable from shelfmark.core.models import DownloadTask + from shelfmark.download.postprocess.packs import PackFile logger = setup_logger(__name__) @@ -127,6 +133,24 @@ class ProwlarrHandler(ExternalClientHandler): return settings.get(indexer_id) + def list_files(self, release_data: dict[str, Any]) -> list[PackFile] | None: + """List a cached torrent release's files from its .torrent, without downloading. + + Magnet-only and usenet releases cannot be listed ahead of time. + """ + source_id = str(release_data.get("source_id") or "") + prowlarr_result = get_release(source_id) if source_id else None + if not prowlarr_result or get_protocol(prowlarr_result) != "torrent": + return None + download_url = sanitize_download_url(str(prowlarr_result.get("downloadUrl") or "").strip()) + if not download_url or download_url.startswith("magnet:"): + return None + expected_hash = str(prowlarr_result.get("infoHash") or "").strip() or None + info = extract_torrent_info(download_url, expected_hash=expected_hash) + if not info.torrent_data: + return None + return extract_file_list_from_torrent(info.torrent_data) + def _get_client(self, protocol: str) -> DownloadClient | None: """Compatibility shim so module-level patching still works in tests.""" return get_client(protocol) diff --git a/src/frontend/src/App.tsx b/src/frontend/src/App.tsx index 65a572b7..bad19116 100644 --- a/src/frontend/src/App.tsx +++ b/src/frontend/src/App.tsx @@ -58,7 +58,6 @@ import { isApiResponseError, updateSelfUser, setBookTargetState, - type DownloadReleasePayload, } from './services/api'; import type { Book, @@ -93,6 +92,7 @@ import { getEffectiveMetadataSort } from './utils/metadataSort'; import { isRecord } from './utils/objectHelpers'; import { policyTrace } from './utils/policyTrace'; import { buildQueryTargets, getDefaultQueryTargetKey } from './utils/queryTargets'; +import { buildReleaseDownloadPayload, type ReleaseDownloadOptions } from './utils/releasePayload'; import { applyRequestNoteToPayload } from './utils/requestConfirmation'; import { bookFromRequestData } from './utils/requestFulfil'; import { @@ -219,6 +219,7 @@ type PendingOnBehalfDownload = release: Release; releaseContentType: ContentType; actingAsUser: ActingAsUserSelection; + options?: ReleaseDownloadOptions; } | { type: 'combined'; @@ -1072,41 +1073,6 @@ function App() { [], ); - const buildReleaseDownloadPayload = useCallback( - (book: Book, release: Release, releaseContentType: ContentType): DownloadReleasePayload => { - const isManual = book.provider === 'manual'; - const releasePreview = - typeof release.extra?.preview === 'string' ? release.extra.preview : undefined; - const releaseAuthor = - typeof release.extra?.author === 'string' ? release.extra.author : undefined; - - return { - source: release.source, - source_id: release.source_id, - title: isManual ? release.title : book.title, - author: isManual ? releaseAuthor || '' : book.author, - year: book.year, - format: release.format, - size: release.size, - size_bytes: release.size_bytes, - download_url: release.download_url, - protocol: release.protocol, - indexer: release.indexer, - seeders: release.seeders, - extra: release.extra, - preview: isManual ? releasePreview || undefined : book.preview, - content_type: releaseContentType, - series_name: book.series_name, - series_position: book.series_position, - subtitle: book.subtitle, - // From the release, never the book: book.language is the provider's - // canonical edition, which would mislabel a translated release. - language: release.language ?? undefined, - }; - }, - [], - ); - // When downloading a book while browsing a Hardcover list the user owns, // automatically remove it from that list (fire-and-forget). const searchFieldLabelsRef = useRef(searchFieldLabels); @@ -1214,12 +1180,13 @@ function App() { release: Release, releaseContentType: ContentType, onBehalfOfUserId?: number, + options?: ReleaseDownloadOptions, ): Promise => { const requestStartedAtSeconds = Date.now() / 1000; try { trackRelease(book.id, release.source_id); await downloadRelease( - buildReleaseDownloadPayload(book, release, releaseContentType), + buildReleaseDownloadPayload(book, release, releaseContentType, options), onBehalfOfUserId, ); await fetchStatus(); @@ -1301,7 +1268,6 @@ function App() { } }, [ - buildReleaseDownloadPayload, fetchStatus, openRequestConfirmation, refreshRequestPolicy, @@ -1416,6 +1382,7 @@ function App() { effectivePendingOnBehalfDownload.release, effectivePendingOnBehalfDownload.releaseContentType, onBehalfOfUserId, + effectivePendingOnBehalfDownload.options, ); } setPendingOnBehalfDownload(null); @@ -1640,6 +1607,7 @@ function App() { book: Book, release: Release, releaseContentType: ContentType, + options?: ReleaseDownloadOptions, ) => { policyTrace('release.action:start', { bookId: book.id, @@ -1655,11 +1623,12 @@ function App() { release, releaseContentType, actingAsUser: effectiveActingAsUser, + options, }); return; } - await executeReleaseDownload(book, release, releaseContentType); + await executeReleaseDownload(book, release, releaseContentType, undefined, options); }; const handleReleaseRequest = useCallback( diff --git a/src/frontend/src/components/PackReviewPanel.tsx b/src/frontend/src/components/PackReviewPanel.tsx new file mode 100644 index 00000000..007ccf1a --- /dev/null +++ b/src/frontend/src/components/PackReviewPanel.tsx @@ -0,0 +1,193 @@ +import { useState } from 'react'; + +import type { PackBook, PackPlan, Release } from '../types'; +import { + describePackPlan, + parseSeriesPositionInput, + toBookPlanPayload, + updateReviewBook, +} from '../utils/packReview'; +import { ToggleSwitch } from './shared/ToggleSwitch'; + +interface PackReviewPanelProps { + release: Release; + plan: PackPlan; + books: PackBook[]; + onChange: (books: PackBook[]) => void; + onBack: () => void; + /** `null` means "treat the whole release as one book". */ + onConfirm: (books: PackBook[] | null) => Promise; + isSubmitting: boolean; +} + +const inputClassName = + 'w-full rounded-md border border-(--border-muted) bg-(--bg) px-2 py-1 text-sm text-(--text) focus:border-emerald-500 focus:outline-none'; + +export const PackReviewPanel = ({ + release, + plan, + books, + onChange, + onBack, + onConfirm, + isSubmitting, +}: PackReviewPanelProps) => { + const [singleBook, setSingleBook] = useState(false); + const [expandedFiles, setExpandedFiles] = useState(null); + const [showIgnored, setShowIgnored] = useState(false); + + const payloadBooks = toBookPlanPayload(books); + const canConfirm = !isSubmitting && (singleBook || payloadBooks.length > 0); + const confirmLabel = singleBook + ? 'Download as one book' + : `Download ${payloadBooks.length} ${payloadBooks.length === 1 ? 'book' : 'books'}`; + + return ( +
+
+

+ This release contains several books +

+

+ {release.title} ·{' '} + {describePackPlan(books, plan.ignored)} +

+

+ Each book below is filed separately with its own title. Fix any titles before downloading + — the author and series come from the book you searched. +

+
+ +
+
+

Treat as a single book

+

+ Use this if the split is wrong and the files are really one audiobook. +

+
+ +
+ +
+
+ Title + Series # + Year + Files +
+ {books.map((book, index) => ( +
+
+ + onChange(updateReviewBook(books, index, { title: e.target.value })) + } + aria-label={`Title for book ${index + 1}`} + className={inputClassName} + disabled={isSubmitting} + /> + + onChange( + updateReviewBook(books, index, { + series_position: parseSeriesPositionInput(e.target.value), + }), + ) + } + aria-label={`Series position for book ${index + 1}`} + className={inputClassName} + disabled={isSubmitting} + /> + { + const parsed = parseSeriesPositionInput(e.target.value); + onChange( + updateReviewBook(books, index, { + year: parsed === null ? null : Math.trunc(parsed), + }), + ); + }} + aria-label={`Year for book ${index + 1}`} + className={inputClassName} + disabled={isSubmitting} + /> + +
+ {expandedFiles === index && ( +
    + {book.files.map((file) => ( +
  • {file}
  • + ))} +
+ )} +
+ ))} +
+ + {plan.ignored.length > 0 && ( +
+ + {showIgnored && ( +
    + {plan.ignored.map((file) => ( +
  • {file}
  • + ))} +
+ )} +
+ )} + +
+ + +
+
+ ); +}; diff --git a/src/frontend/src/components/ReleaseModal.tsx b/src/frontend/src/components/ReleaseModal.tsx index 0359316f..adca13fc 100644 --- a/src/frontend/src/components/ReleaseModal.tsx +++ b/src/frontend/src/components/ReleaseModal.tsx @@ -7,6 +7,7 @@ import { useReleaseSearchSession } from '../hooks/releaseModal/useReleaseSearchS import { useTabIndicator } from '../hooks/ui/useTabIndicator'; import { useBodyScrollLock } from '../hooks/useBodyScrollLock'; import { useEscapeKey } from '../hooks/useEscapeKey'; +import { inspectRelease } from '../services/api'; import type { Book, Release, @@ -18,6 +19,8 @@ import type { LeadingCellConfig, ContentType, RequestPolicyMode, + PackBook, + PackPlan, } from '../types'; import { isMetadataBook } from '../types'; import { bookSupportsTargets } from '../utils/bookTargetLoader'; @@ -29,7 +32,9 @@ import { buildLanguageNormalizer, } from '../utils/languageFilters'; import { getNestedValue, toComparableText, toStringValue } from '../utils/objectHelpers'; +import { toBookPlanPayload } from '../utils/packReview'; import { getReleaseFormats } from '../utils/releaseFormats'; +import { buildReleaseDownloadPayload, type ReleaseDownloadOptions } from '../utils/releasePayload'; import { getBookTitleCandidates, getBookAuthorCandidates, @@ -50,6 +55,7 @@ import { BookTargetDropdown } from './BookTargetDropdown'; import { Dropdown } from './Dropdown'; import { DropdownList } from './DropdownList'; import { LanguageMultiSelect } from './LanguageMultiSelect'; +import { PackReviewPanel } from './PackReviewPanel'; import { ReleaseCell } from './ReleaseCell'; // Combined mode configuration for the ReleaseModal @@ -140,7 +146,12 @@ const DEFAULT_COLUMN_CONFIG: ReleaseColumnConfig = { interface ReleaseModalProps { book: Book | null; onClose: () => void; - onDownload: (book: Book, release: Release, contentType: ContentType) => Promise; + onDownload: ( + book: Book, + release: Release, + contentType: ContentType, + options?: ReleaseDownloadOptions, + ) => Promise; onRequestRelease?: (book: Book, release: Release, contentType: ContentType) => Promise; onRequestBook?: (book: Book, contentType: ContentType) => Promise; getPolicyModeForSource?: (source: string, contentType: ContentType) => RequestPolicyMode; @@ -762,6 +773,15 @@ const ReleaseModalSession = ({ : supportedFormats; const [isRequestingBook, setIsRequestingBook] = useState(false); const [selectedRelease, setSelectedRelease] = useState(null); + // Multi-book packs: `multiBook` is the manual header toggle (heuristic split for + // releases we can't inspect); `packReview` holds an inspected pack awaiting approval. + const [multiBook, setMultiBook] = useState(false); + const [packReview, setPackReview] = useState<{ + release: Release; + plan: PackPlan; + books: PackBook[]; + } | null>(null); + const [packSubmitting, setPackSubmitting] = useState(false); const isCombinedMode = combinedMode != null; const combinedPhase = combinedMode?.phase ?? null; const combinedStepLabel = combinedMode?.stepLabel ?? ''; @@ -1196,7 +1216,30 @@ const ReleaseModalSession = ({ const mode = getReleaseActionMode(release); if (mode === 'download') { - await onDownload(book, release, contentType); + // Look at the release's files before queueing so a whole-series pack can be + // reviewed and filed as separate books instead of one mangled item. + let inspected = false; + let plan: PackPlan | null = null; + try { + const inspection = await inspectRelease( + buildReleaseDownloadPayload(book, release, contentType), + ); + inspected = inspection.inspected; + plan = inspection.plan; + } catch (error) { + console.error('Release inspection failed:', error); + } + if (inspected && plan?.is_pack) { + setPackReview({ release, plan, books: plan.books }); + return; + } + if (!inspected && !multiBook) { + onShowToast?.( + "Couldn't check this release's files before download. If it contains several books, turn on the multi-book pack toggle first.", + 'info', + ); + } + await onDownload(book, release, contentType, multiBook ? { multiBook: true } : {}); handleClose(); return; } @@ -1215,9 +1258,32 @@ const ReleaseModalSession = ({ onRequestRelease, contentType, handleClose, + multiBook, + onShowToast, ], ); + const handlePackConfirm = useCallback( + async (books: PackBook[] | null): Promise => { + if (!book || !packReview) { + return; + } + setPackSubmitting(true); + try { + await onDownload( + book, + packReview.release, + contentType, + books ? { multiBook: true, bookPlan: toBookPlanPayload(books) } : {}, + ); + handleClose(); + } finally { + setPackSubmitting(false); + } + }, + [book, packReview, onDownload, contentType, handleClose], + ); + const titleId = `release-modal-title-${book.id}`; const providerDisplay = book.provider_display_name || @@ -1720,6 +1786,37 @@ const ReleaseModalSession = ({
+ {/* Multi-book pack toggle (fallback for releases that can't be inspected) */} + {!isCombinedMode && ( + + )} + {/* Manual query button */}