diff --git a/alembic/versions/d5e6f7a8b9c0_doc_section.py b/alembic/versions/d5e6f7a8b9c0_doc_section.py index f85f2ecf..a18bbd12 100644 --- a/alembic/versions/d5e6f7a8b9c0_doc_section.py +++ b/alembic/versions/d5e6f7a8b9c0_doc_section.py @@ -49,3 +49,13 @@ def upgrade(): def downgrade(): op.execute('DROP TABLE IF EXISTS doc_section') + # If we drop the table while some file groups still have indexed=FALSE (the + # upgrade sets that to trigger re-extraction), the next refresh would try to + # write DocSection rows to a table that no longer exists. Restore indexed=TRUE + # for those rows so a downgrade leaves the system in a consistent state. + op.execute(''' + UPDATE file_group + SET indexed = TRUE + WHERE mimetype LIKE 'application/epub%' + OR mimetype = 'application/pdf' + ''') diff --git a/alembic/versions/e6f7a8b9c0d1_reindex_epubs_for_spine_order.py b/alembic/versions/e6f7a8b9c0d1_reindex_epubs_for_spine_order.py new file mode 100644 index 00000000..ade9351a --- /dev/null +++ b/alembic/versions/e6f7a8b9c0d1_reindex_epubs_for_spine_order.py @@ -0,0 +1,43 @@ +"""Force EPUB re-extraction after spine-ordering fix. + +A previous version of `extract_epub` used `book.get_items_of_type(ITEM_DOCUMENT)` +to enumerate sections, which returns manifest order (not reading-spine order) and +can include non-spine documents like EPUB 3 `nav.xhtml`. The viewer resolves +deep-links via `spine.get(n)`, so any `doc_section.ordinal` written by the old +code can land users on the wrong chapter. + +The fix iterates `book.spine` directly; this migration flips `indexed = FALSE` +on every EPUB file group so the regular refresh pipeline re-extracts them with +correct spine-indexed ordinals. PDFs are untouched — their per-page ordinals +were always correct. + +Revision ID: e6f7a8b9c0d1 +Revises: d5e6f7a8b9c0 +Create Date: 2026-04-13 + +""" +from alembic import op + +revision = 'e6f7a8b9c0d1' +down_revision = 'd5e6f7a8b9c0' +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute(''' + UPDATE file_group + SET indexed = FALSE + WHERE mimetype LIKE 'application/epub%' + ''') + + +def downgrade(): + # Symmetric with the parent migration's downgrade safeguard: if we re-apply + # downgrade, leave file groups marked indexed so a refresh doesn't try to + # repopulate doc_section rows that may have been dropped by the parent. + op.execute(''' + UPDATE file_group + SET indexed = TRUE + WHERE mimetype LIKE 'application/epub%' + ''') diff --git a/app/public/epub/epub.html b/app/public/epub/epub.html index 67945278..3a1ab60e 100644 --- a/app/public/epub/epub.html +++ b/app/public/epub/epub.html @@ -164,9 +164,73 @@ either expressed or implied, of the FreeBSD Project. --> display: block; } + #toolbar { + display: flex; + align-items: center; + gap: 8px; + margin: 8px auto; + padding: 0 12px; + flex-wrap: wrap; + font-size: 13px; + color: #444; + } + + #toolbar #toc { + margin: 0; + } + + #toolbar form { + display: flex; + gap: 4px; + align-items: center; + margin: 0; + } + + #toolbar input[type="search"] { + padding: 4px 6px; + font-size: 13px; + border: 1px solid #ccc; + border-radius: 3px; + min-width: 180px; + } + + #toolbar button { + padding: 3px 10px; + font-size: 13px; + border: 1px solid #ccc; + background: #f6f6f6; + border-radius: 3px; + cursor: pointer; + line-height: 1.4; + } + + #toolbar button:disabled { + opacity: 0.45; + cursor: default; + } + + #search-status { + color: #666; + min-width: 96px; + } + + #search-status.error { + color: #b00; + } + - +
+ +
+ + + + + +
+ +
@@ -188,41 +252,192 @@ either expressed or implied, of the FreeBSD Project. --> rendition.display(currentSectionIndex); - // If a search query was provided, try to locate it within the target spine item - // and scroll to / highlight the first match. Any failure is non-fatal — the `loc` - // jump above still lands the user at the right chapter. - if (searchQuery) { - book.ready.then(function () { + // --- In-book search --------------------------------------------------- + // State is module-level so the toolbar buttons can drive it. `hits` is the + // most recent search's results in spine order; `currentHitIndex` tracks + // which one is "selected" for prev/next navigation. + let hits = []; + let currentHitIndex = -1; + let searchInProgress = false; + const SEARCH_CONCURRENCY = 8; + + const $input = document.getElementById("search-input"); + const $submit = document.getElementById("search-submit"); + const $prev = document.getElementById("search-prev"); + const $next = document.getElementById("search-next"); + const $clear = document.getElementById("search-clear"); + const $status = document.getElementById("search-status"); + const $form = document.getElementById("search-form"); + + function setStatus(text, isError) { + $status.textContent = text || ""; + $status.classList.toggle("error", !!isError); + } + + function updateButtons() { + const hasHits = hits.length > 0; + $prev.disabled = !hasHits || searchInProgress; + $next.disabled = !hasHits || searchInProgress; + $clear.disabled = (!hasHits && !$input.value) || searchInProgress; + $submit.disabled = searchInProgress; + } + + function clearHighlights() { + for (const hit of hits) { try { - let spine = book.spine; - let item; - if (currentSectionIndex !== undefined) { - let n = parseInt(currentSectionIndex, 10); - if (!isNaN(n)) { - item = spine.get(n); - } + rendition.annotations.remove(hit.cfi, "highlight"); + } catch (e) { /* already gone — ignore */ } + } + } + + function clearSearch() { + clearHighlights(); + hits = []; + currentHitIndex = -1; + setStatus(""); + updateButtons(); + } + + function gotoHit(i) { + if (!hits.length) return; + // Wrap around both directions for easy cycling. + if (i < 0) i = hits.length - 1; + if (i >= hits.length) i = 0; + currentHitIndex = i; + try { + rendition.display(hits[i].cfi); + } catch (e) { + console.warn("failed to display hit", e); + } + setStatus(`${i + 1} of ${hits.length}`); + } + + // Run a search across every spine item, collecting CFIs and excerpts. + // Uses small-chunk concurrency so a 600-item book doesn't serialize one + // load at a time and doesn't stampede memory by loading all at once. + // `preferredSpineIndex` biases the initial hit selection. When a search is + // kicked off from a `?loc=…&q=…` deep-link, callers pass the loc so the + // viewer lands on the match in that chapter rather than jumping to the + // first match in the whole book. + async function runBookSearch(query, preferredSpineIndex) { + query = (query || "").trim(); + if (!query) { + clearSearch(); + return; + } + // Always clear prior state before starting a new search. + clearHighlights(); + hits = []; + currentHitIndex = -1; + searchInProgress = true; + updateButtons(); + setStatus("Searching…"); + + const spineItems = (book.spine && book.spine.spineItems) || []; + const total = spineItems.length; + let processed = 0; + const newHits = []; + + async function searchOne(item) { + try { + await Promise.resolve(item.load(book.load.bind(book))); + const results = item.find(query) || []; + for (const r of results) { + newHits.push({ + spineIndex: item.index, + cfi: r.cfi, + excerpt: r.excerpt, + }); } - if (!item && spine.spineItems && spine.spineItems.length) { - item = spine.spineItems[0]; - } - if (!item) return; - Promise.resolve(item.load(book.load.bind(book))).then(function () { - let results = item.find(searchQuery) || []; - if (results.length > 0) { - let hit = results[0]; - rendition.display(hit.cfi); - try { - rendition.annotations.highlight(hit.cfi); - } catch (e) { - console.warn("highlight failed", e); - } - } - }).finally(function () { - try { item.unload(); } catch (e) { /* ignore */ } - }); } catch (e) { - console.warn("epub deep-link search failed", e); + console.warn("search failed for item", item && item.href, e); + } finally { + try { item.unload(); } catch (e) { /* ignore */ } + processed += 1; + // Live progress — users with big books want to know something's happening. + if (processed % SEARCH_CONCURRENCY === 0 || processed === total) { + setStatus(`Searching… ${processed} / ${total}`); + } } + } + + // Simple fixed-concurrency pool. + let cursor = 0; + async function worker() { + while (cursor < spineItems.length) { + const i = cursor++; + await searchOne(spineItems[i]); + } + } + const workers = []; + for (let i = 0; i < Math.min(SEARCH_CONCURRENCY, spineItems.length); i++) { + workers.push(worker()); + } + await Promise.all(workers); + + // Sort hits by spine order then position within the section. `spineIndex` + // handles the first; CFI string comparison is a reasonable tiebreaker. + newHits.sort((a, b) => { + if (a.spineIndex !== b.spineIndex) return a.spineIndex - b.spineIndex; + return a.cfi < b.cfi ? -1 : a.cfi > b.cfi ? 1 : 0; + }); + + // Highlight each match. The annotation only renders visibly when its + // section is rendered, but calling this up-front means navigating to + // any hit arrives with the term already marked. + for (const hit of newHits) { + try { + rendition.annotations.highlight(hit.cfi); + } catch (e) { /* dup or invalid CFI — ignore */ } + } + + hits = newHits; + searchInProgress = false; + + if (hits.length === 0) { + setStatus("No matches"); + } else { + // If the caller pinned a preferred spine item (e.g. a deep-link with + // `?loc=`), prefer the first hit inside that exact section. Fall back + // to the first hit globally only when there's no match in the pin. + let startIdx = 0; + const pin = (preferredSpineIndex === undefined || preferredSpineIndex === null) + ? null + : parseInt(preferredSpineIndex, 10); + if (pin !== null && !isNaN(pin)) { + const pinned = hits.findIndex(h => h.spineIndex === pin); + if (pinned !== -1) startIdx = pinned; + } + gotoHit(startIdx); + } + updateButtons(); + } + + // Wire up the toolbar. + $form.addEventListener("submit", function (e) { + e.preventDefault(); + runBookSearch($input.value); + }); + $next.addEventListener("click", function () { gotoHit(currentHitIndex + 1); }); + $prev.addEventListener("click", function () { gotoHit(currentHitIndex - 1); }); + $clear.addEventListener("click", function () { + $input.value = ""; + clearSearch(); + }); + $input.addEventListener("input", function () { + // Enable/disable the clear button as the user types, even with no hits yet. + updateButtons(); + }); + updateButtons(); + + // Deep-link `q=` — pre-fill the box and run the full search once the book + // is ready. Pass `loc` (when present) as the preferred spine index so the + // viewer lands on the match inside that chapter rather than the first match + // in the book. Manual searches triggered from the toolbar don't pass a pin. + if (searchQuery) { + $input.value = searchQuery; + book.ready.then(function () { + runBookSearch(searchQuery, currentSectionIndex); }); } diff --git a/modules/docs/extractors.py b/modules/docs/extractors.py index f5074f2d..c2418bbe 100644 --- a/modules/docs/extractors.py +++ b/modules/docs/extractors.py @@ -121,6 +121,34 @@ def _build_epub_toc_label_map(toc) -> dict: return href_to_label +def _iter_epub_spine_documents(book) -> list: + """Return the EpubHtml items that make up the book's reading spine, in order. + + Using `book.get_items_of_type(ITEM_DOCUMENT)` is wrong for deep-linking because + it enumerates the full manifest — which can include EPUB 3 `nav.xhtml` files + (excluded from the spine) and can return items in manifest order that differs + from spine order. The viewer (`epub.html`) resolves deep-links via + `spine.get(n)`, which indexes the reading spine only — so section ordinals + must match that. + + Falls back to the manifest-order iteration only if the book has no spine info + (malformed EPUB), to preserve indexing behavior on edge cases. + """ + spine_docs = [] + spine = getattr(book, 'spine', None) + if spine: + for entry in spine: + # book.spine entries are (idref, linear) tuples or bare idref strings. + idref = entry[0] if isinstance(entry, (tuple, list)) else entry + item = book.get_item_with_id(idref) + if item is not None and item.get_type() == ebooklib.ITEM_DOCUMENT: + spine_docs.append(item) + if not spine_docs: + # Malformed / spine-less EPUB — fall back to manifest order. + spine_docs = list(book.get_items_of_type(ebooklib.ITEM_DOCUMENT)) + return spine_docs + + def _resolve_spine_labels(hrefs, href_to_label: dict) -> list: """Assign each spine item a label, carrying the most recently-matched TOC label forward so mid-chapter spine items inherit their chapter's label. @@ -179,7 +207,7 @@ def extract_epub(path: pathlib.Path) -> DocMetadata: # recently-matched TOC label forward so mid-chapter sections still get a useful # label (e.g. "Mullein" rather than "Section 302"). text_parts = [] - spine_items = list(book.get_items_of_type(ebooklib.ITEM_DOCUMENT)) + spine_items = _iter_epub_spine_documents(book) hrefs = [(d.file_name, d.get_name()) for d in spine_items] labels = _resolve_spine_labels(hrefs, href_to_label) for ordinal, (doc, label) in enumerate(zip(spine_items, labels)): diff --git a/modules/docs/test/test_extractors.py b/modules/docs/test/test_extractors.py index 79995cbf..908fc086 100644 --- a/modules/docs/test/test_extractors.py +++ b/modules/docs/test/test_extractors.py @@ -28,6 +28,68 @@ async def test_extract_epub_sections(test_session, test_directory, example_epub) assert all(s.label for s in metadata.sections) +@pytest.mark.asyncio +async def test_extract_epub_ordinals_match_reading_spine_order(test_session, test_directory, tmp_path): + """Section ordinals must index the EPUB *reading spine*, not the full manifest. + + The JS viewer (epub.html) resolves a deep-linked section via `spine.get(n)`, + which is only defined for items in the spine. Two ways `get_items_of_type + (ITEM_DOCUMENT)` diverges from the spine: + + 1. An EPUB 3 book lists a `nav.xhtml` (properties=nav) in the manifest but + excludes it from the spine — doc count > spine count. + 2. The spine declares items in a different order than the manifest, so + enumerating ITEM_DOCUMENT gives scrambled ordinals even when counts match. + + This test constructs a minimal EPUB exhibiting both conditions and asserts the + extracted sections are in spine order (by matching spine-only content). + """ + from ebooklib import epub as epub_lib + + book = epub_lib.EpubBook() + book.set_identifier('spine-test') + book.set_title('Spine Test') + book.set_language('en') + + # Three chapters whose spine order is INTENTIONALLY different from the + # manifest add order, so ITEM_DOCUMENT (manifest) and spine indices diverge. + c_first = epub_lib.EpubHtml(title='Opens first', file_name='c_first.xhtml', lang='en') + c_first.content = '

OPEN_MARKER

' + c_middle = epub_lib.EpubHtml(title='Opens middle', file_name='c_middle.xhtml', lang='en') + c_middle.content = '

MIDDLE_MARKER

' + c_last = epub_lib.EpubHtml(title='Opens last', file_name='c_last.xhtml', lang='en') + c_last.content = '

LAST_MARKER

' + + # Manifest insertion order: last, first, middle — deliberately scrambled. + book.add_item(c_last) + book.add_item(c_first) + book.add_item(c_middle) + + # EPUB 3 nav (in manifest but NOT in the reading spine). This makes + # ITEM_DOCUMENT iteration include a doc the viewer's spine.get() won't. + book.toc = (c_first, c_middle, c_last) + book.add_item(epub_lib.EpubNcx()) + book.add_item(epub_lib.EpubNav()) + + # Spine order: first, middle, last (different from manifest order). Nav excluded. + book.spine = [c_first, c_middle, c_last] + + epub_path = tmp_path / 'spine_order.epub' + epub_lib.write_epub(str(epub_path), book) + + from modules.docs.extractors import extract_epub + metadata = extract_epub(epub_path) + + # Sections must be in spine order: first, middle, last — and must NOT include nav. + contents = [s.content for s in metadata.sections] + assert len(contents) == 3, f'Expected 3 spine sections, got {len(contents)}: {contents!r}' + assert 'OPEN_MARKER' in contents[0], f'ordinal 0 should be the first spine item; got {contents[0]!r}' + assert 'MIDDLE_MARKER' in contents[1], f'ordinal 1 should be the middle spine item; got {contents[1]!r}' + assert 'LAST_MARKER' in contents[2], f'ordinal 2 should be the last spine item; got {contents[2]!r}' + # And none of them should be the nav file. + assert not any('epub:type' in c for c in contents), 'nav.xhtml must not be a section' + + def test_resolve_spine_labels_carries_forward_across_split_chapters(): """When a chapter spans multiple spine items (common in Calibre conversions), sections after the TOC-anchored one inherit the chapter label instead of diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index 8f573356..b187458d 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -1057,9 +1057,11 @@ def handle_file_group_search_results(statement: str, params: dict) -> Tuple[List search_str = params.get('search_str') if isinstance(params, dict) else None if search_str: from modules.docs.lib import _fetch_section_hints - doc_ids = [r['id'] for r in results if r.get('model') == 'doc'] - if doc_ids: - hints = _fetch_section_hints(session, doc_ids, search_str) + # `r['id']` is the FileGroup primary key; _fetch_section_hints filters + # on `file_group_id`, so this list is file-group ids (not doc.id). + fg_ids = [r['id'] for r in results if r.get('model') == 'doc'] + if fg_ids: + hints = _fetch_section_hints(session, fg_ids, search_str) for r in results: hint = hints.get(r['id']) if hint: diff --git a/wrolpi/files/test/test_api.py b/wrolpi/files/test/test_api.py index a0651f97..971ce748 100644 --- a/wrolpi/files/test/test_api.py +++ b/wrolpi/files/test/test_api.py @@ -249,8 +249,9 @@ async def test_files_search_attaches_doc_section_hint(async_client, test_session f'doc result has no section_hint on global search path: {result}' hint = result['section_hint'] assert hint['kind'] == 'epub_spine' - # The test EPUB's "Chapter one" body is in spine item 1. - assert hint['ordinal'] == 1 + # The test EPUB's spine order is [titlepage, start, chapter1]; the chapter1 + # document holds the "Chapter one" body, so its spine ordinal is 2. + assert hint['ordinal'] == 2 assert hint['label'] # Snippet uses our sentinel markers, not raw HTML. assert '[[WROLPI_HL]]' in hint['snippet']