vomebook commited on
Commit ·
19146fe
1
Parent(s): 9ccdee8
Allow Reader downloads while preparing
Browse filesFiles changed (2)
- static/reader.js+15-18
- tests/test_reader_refactor.py+51-10
112 unmodified lines113114115116117118119120121122123124125126127128129130131132133134135136137138139157 unmodified lines2972982993003013023033043053063073083093103548 unmodified lines38593860386138623863386438653 unmodified lines386938703871387238733874387528 unmodified lines3904390539063907390839093910391113 unmodified lines39253926392739283929393039313932112 unmodified linesasync function startReaderDownload(event) {event.preventDefault();const button = event.currentTarget;if (!readerDownloadReady && !(readerDownloadSourceResolved && readerLifecycle.phase === "failed")) {showDownloadFeedback("正在准备原文件,请稍候");return;}if (button.hasAttribute("aria-busy")) return;showDownloadFeedback("");const filename = documentState.title || "file";const checkUrl = readerDownloadApiUrl(`/api/download/check?link=${encodeURIComponent(downloadUrl || "")}`);const controller = new AbortController();const timer = setTimeout(() => controller.abort(), 8000);button.setAttribute("aria-busy", "true");try {const response = await fetch(checkUrl, { signal: controller.signal, cache: "no-store" });const result = await response.json().catch(() => null);if (!response.ok || result?.ok !== true) throw new Error(result?.error || "下载检查失败,请重试");const frame = document.createElement("iframe");frame.hidden = true;frame.setAttribute("aria-hidden", "true");frame.src = readerDownloadUrl(filename, downloadUrl);document.body.appendChild(frame);setTimeout(() => frame.remove(), 60000);} catch (error) {if (!readerLifecycle.disposed) {showDownloadFeedback(error?.name === "AbortError" ? "下载检查超时,请重试" : (error.message || "下载失败,请重试"));157 unmodified linesconst loadingStatus = document.querySelector("#loading-status");const downloadButton = document.querySelector("#download");const downloadFeedback = document.querySelector("#download-feedback");let readerDownloadReady = false;let readerDownloadSourceResolved = false;let downloadFeedbackTimer = 0;function showDownloadFeedback(message) {clearTimeout(downloadFeedbackTimer);downloadFeedback.textContent = message;downloadFeedback.hidden = !message;if (message) downloadFeedbackTimer = setTimeout(() => showDownloadFeedback(""), 4000);}downloadButton.addEventListener("click", startReaderDownload);loadingStatus.textContent = "";3548 unmodified lines// an ID-only Reader link is resolving its source URL. The promise is reused// by loadPdfDocument, so this does not create a second module request.if (extension === "pdf" || /\.pdf(?:$|[?#])/i.test(sourceUrl)) preloadPdfEngine().catch(() => {});await resolveReaderSource();assertReaderActive();if (readerId && /\/calibre-chm-epub-[^/]+\/document\.epub(?:$|\?)/i.test(sourceUrl)) {extension = "epub";3 unmodified linesdocument.querySelector(".page-controls").hidden = true;}syncCapabilityControls();readerDownloadSourceResolved = true;downloadButton.href = readerDownloadUrl(documentState.title, downloadUrl);if ((!validSource(sourceUrl) && !validSource(chapterManifestUrl) && !readerId) ||28 unmodified lines}assertReaderActive();if (!setReaderPhase("ready")) return;readerDownloadReady = true;showDownloadFeedback("");updateDocumentState({ restorationReady: !restorationFailed });scheduleSave();return;13 unmodified linesawait restoreInitialPosition(documentState.restoredEntry, generation);assertReaderActive();if (!setReaderPhase("ready")) return;readerDownloadReady = true;showDownloadFeedback("");updateDocumentState({ restorationReady: !restorationFailed });updateProgressTools();if (fullSearchInput.value.trim()) runFullSearch();112 unmodified lines113114115116117118119120121122123124125126127128129130131132133134135136137138139140141157 unmodified lines2993003013023033043053063073083093103113548 unmodified lines386038613862386338643865386638673 unmodified lines38713872387338743875387628 unmodified lines39053906390739083909391013 unmodified lines392439253926392739283929112 unmodified linesasync function startReaderDownload(event) {event.preventDefault();const button = event.currentTarget;if (button.hasAttribute("aria-busy")) return;showDownloadFeedback("正在准备下载…", 0);const controller = new AbortController();let timer;button.setAttribute("aria-busy", "true");try {// ID-only links share the Reader's in-flight resolution, not its render phase.if (!downloadUrl) await readerSourcePromise;if (!downloadUrl) throw new Error("无法获取原文件地址");const filename = documentState.title || "file";const checkUrl = readerDownloadApiUrl(`/api/download/check?link=${encodeURIComponent(downloadUrl)}`);timer = setTimeout(() => controller.abort(), 8000);const response = await fetch(checkUrl, { signal: controller.signal, cache: "no-store" });const result = await response.json().catch(() => null);if (!response.ok || result?.ok !== true) throw new Error(result?.error || "下载检查失败,请重试");if (readerLifecycle.disposed) return;const frame = document.createElement("iframe");frame.hidden = true;frame.setAttribute("aria-hidden", "true");frame.src = readerDownloadUrl(filename, downloadUrl);document.body.appendChild(frame);setTimeout(() => frame.remove(), 60000);showDownloadFeedback("已发起下载");} catch (error) {if (!readerLifecycle.disposed) {showDownloadFeedback(error?.name === "AbortError" ? "下载检查超时,请重试" : (error.message || "下载失败,请重试"));157 unmodified linesconst loadingStatus = document.querySelector("#loading-status");const downloadButton = document.querySelector("#download");const downloadFeedback = document.querySelector("#download-feedback");let readerSourcePromise = null;let downloadFeedbackTimer = 0;function showDownloadFeedback(message, duration = 4000) {clearTimeout(downloadFeedbackTimer);downloadFeedback.textContent = message;downloadFeedback.hidden = !message;if (message && duration) downloadFeedbackTimer = setTimeout(() => showDownloadFeedback(""), duration);}downloadButton.addEventListener("click", startReaderDownload);loadingStatus.textContent = "";3548 unmodified lines// an ID-only Reader link is resolving its source URL. The promise is reused// by loadPdfDocument, so this does not create a second module request.if (extension === "pdf" || /\.pdf(?:$|[?#])/i.test(sourceUrl)) preloadPdfEngine().catch(() => {});readerSourcePromise = resolveReaderSource();await readerSourcePromise;assertReaderActive();if (readerId && /\/calibre-chm-epub-[^/]+\/document\.epub(?:$|\?)/i.test(sourceUrl)) {extension = "epub";3 unmodified linesdocument.querySelector(".page-controls").hidden = true;}syncCapabilityControls();downloadButton.href = readerDownloadUrl(documentState.title, downloadUrl);if ((!validSource(sourceUrl) && !validSource(chapterManifestUrl) && !readerId) ||28 unmodified lines}assertReaderActive();if (!setReaderPhase("ready")) return;updateDocumentState({ restorationReady: !restorationFailed });scheduleSave();return;13 unmodified linesawait restoreInitialPosition(documentState.restoredEntry, generation);assertReaderActive();if (!setReaderPhase("ready")) return;updateDocumentState({ restorationReady: !restorationFailed });updateProgressTools();if (fullSearchInput.value.trim()) runFullSearch();
78 unmodified lines7980818283848516 unmodified lines1021031041051061071081091101111 unmodified line11311411511611711811912012112212312412512612712812978 unmodified linesself.assertEqual(image.get_attribute("src"), source + "/pages/page-000003.webp")self.assertTrue(image.evaluate("image => image.complete && image.naturalWidth > 0"))def test_download_waits_for_reader_ready_then_uses_attachment(self):pending_content = []checks = []downloads = []16 unmodified linesself.page.wait_for_function("() => document.querySelector('#download').hasAttribute('href')")self.assertNotEqual(self.page.locator("html").get_attribute("data-reader-phase"), "ready")self.page.locator("#download").click()self.page.wait_for_timeout(200)self.assertEqual(checks, [])self.assertEqual(downloads, [])self.assertEqual(self.page.locator("#download-feedback").text_content(), "正在准备原文件,请稍候")self.assertNotIn("原文件", self.page.locator("#status").text_content())self.page.set_viewport_size({"width": 390, "height": 844})self.assertTrue(self.page.locator("#download-feedback").evaluate("""node => {1 unmodified lineconst button = document.querySelector('#download').getBoundingClientRect();return message.left >= 0 && message.right <= innerWidth && message.top >= button.bottom;}"""))pending_content[0].fulfill(status=200, content_type="text/plain", body="Reader download")self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")self.assertTrue(self.page.locator("#download-feedback").is_hidden())self.page.locator("#download").click()self.page.wait_for_function("() => document.querySelector('#download-feedback').textContent === '下载检查失败,请重试'")self.assertEqual(downloads, [])with self.page.expect_download() as event:self.page.locator("#download").click()self.assertEqual(event.value.suggested_filename, "refactor.txt")self.assertEqual(len(checks), 2)self.assertEqual(len(downloads), 1)def test_failed_reader_still_allows_original_download(self):checks = []78 unmodified lines7980818283848516 unmodified lines1021031041051061071081091101 unmodified line11211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917078 unmodified linesself.assertEqual(image.get_attribute("src"), source + "/pages/page-000003.webp")self.assertTrue(image.evaluate("image => image.complete && image.naturalWidth > 0"))def test_download_during_prepare_does_not_interrupt_reader(self):pending_content = []checks = []downloads = []16 unmodified linesself.page.wait_for_function("() => document.querySelector('#download').hasAttribute('href')")self.assertNotEqual(self.page.locator("html").get_attribute("data-reader-phase"), "ready")self.page.locator("#download").click()self.page.wait_for_function("() => document.querySelector('#download-feedback').textContent === '下载检查失败,请重试'")self.assertEqual(len(checks), 1)self.assertEqual(downloads, [])self.assertNotIn("原文件", self.page.locator("#status").text_content())self.page.set_viewport_size({"width": 390, "height": 844})self.assertTrue(self.page.locator("#download-feedback").evaluate("""node => {1 unmodified lineconst button = document.querySelector('#download').getBoundingClientRect();return message.left >= 0 && message.right <= innerWidth && message.top >= button.bottom;}"""))with self.page.expect_download() as event:self.page.locator("#download").click()self.assertEqual(event.value.suggested_filename, "refactor.txt")self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "prepare")self.assertEqual(len(checks), 2)self.assertEqual(len(downloads), 1)pending_content[0].fulfill(status=200, content_type="text/plain", body="Reader download")self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")self.assertIn("Reader download", self.page.locator("#content").text_content())def test_id_only_download_joins_reader_resolution(self):resolved = []content = []checks = []source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/shared.txt"self.page.route("**/api/reader-resolve?**", lambda route: resolved.append(route))self.page.route("**/api/reader-content?**", lambda route: content.append(route))self.page.route("**/api/download/check?**", lambda route: (checks.append(route.request.url), route.fulfill(json={"ok": True})))self.page.route("**/api/download?**", lambda route: route.fulfill(body=b"original", headers={"Content-Disposition": "attachment; filename=shared.txt"}))self.page.goto(self.origin + "/static/reader.html?id=" + "a" * 13 + "&ext=txt", wait_until="domcontentloaded")self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'resolve'")self.page.locator("#download").click()self.page.locator("#download").click()self.assertEqual(len(resolved), 1)self.assertEqual(checks, [])with self.page.expect_download() as event:resolved[0].fulfill(json={"url": source, "download": source, "title": "shared", "extension": "txt"})self.assertEqual(event.value.suggested_filename, "shared.txt")self.assertEqual(len(checks), 1)self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "prepare")content[0].fulfill(body="Resolved text")self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")def test_pdf_can_finish_preparing_after_download_starts(self):pending_content = []self.page.route("**/api/reader-content**", lambda route: pending_content.append(route))self.page.route("**/api/download/check**", lambda route: route.fulfill(json={"ok": True}))self.page.route("**/api/download?**", lambda route: route.fulfill(content_type="application/octet-stream", body=b"original",headers={"Content-Disposition": "attachment; filename=book.pdf"}))self.page.goto(self.reader_url("pdf"), wait_until="domcontentloaded")self.page.wait_for_function("() => document.querySelector('#download').hasAttribute('href')")with self.page.expect_download() as event:self.page.locator("#download").click()self.assertEqual(event.value.suggested_filename, "book.pdf")self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "prepare")self.page.wait_for_timeout(200)self.assertTrue(pending_content)pending_content[0].fulfill(content_type="application/pdf", body=support.minimal_pdf())self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for(state="attached")def test_failed_reader_still_allows_original_download(self):checks = []
static/reader.js+15-18
tests/test_reader_refactor.py+51-10