vomebook commited on
Commit ·
19146fe
1
Parent(s): 9ccdee8
Allow Reader downloads while preparing
Browse files- static/reader.js +15 -18
- tests/test_reader_refactor.py +51 -10
static/reader.js
CHANGED
|
@@ -113,27 +113,29 @@ function readerDownloadUrl(filename, link) {
|
|
| 113 |
async function startReaderDownload(event) {
|
| 114 |
event.preventDefault();
|
| 115 |
const button = event.currentTarget;
|
| 116 |
-
if (!readerDownloadReady && !(readerDownloadSourceResolved && readerLifecycle.phase === "failed")) {
|
| 117 |
-
showDownloadFeedback("正在准备原文件,请稍候");
|
| 118 |
-
return;
|
| 119 |
-
}
|
| 120 |
if (button.hasAttribute("aria-busy")) return;
|
| 121 |
-
showDownloadFeedback("");
|
| 122 |
-
const filename = documentState.title || "file";
|
| 123 |
-
const checkUrl = readerDownloadApiUrl(`/api/download/check?link=${encodeURIComponent(downloadUrl || "")}`);
|
| 124 |
const controller = new AbortController();
|
| 125 |
-
|
| 126 |
button.setAttribute("aria-busy", "true");
|
| 127 |
try {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
const response = await fetch(checkUrl, { signal: controller.signal, cache: "no-store" });
|
| 129 |
const result = await response.json().catch(() => null);
|
| 130 |
if (!response.ok || result?.ok !== true) throw new Error(result?.error || "下载检查失败,请重试");
|
|
|
|
| 131 |
const frame = document.createElement("iframe");
|
| 132 |
frame.hidden = true;
|
| 133 |
frame.setAttribute("aria-hidden", "true");
|
| 134 |
frame.src = readerDownloadUrl(filename, downloadUrl);
|
| 135 |
document.body.appendChild(frame);
|
| 136 |
setTimeout(() => frame.remove(), 60000);
|
|
|
|
| 137 |
} catch (error) {
|
| 138 |
if (!readerLifecycle.disposed) {
|
| 139 |
showDownloadFeedback(error?.name === "AbortError" ? "下载检查超时,请重试" : (error.message || "下载失败,请重试"));
|
|
@@ -297,14 +299,13 @@ const status = document.querySelector("#status");
|
|
| 297 |
const loadingStatus = document.querySelector("#loading-status");
|
| 298 |
const downloadButton = document.querySelector("#download");
|
| 299 |
const downloadFeedback = document.querySelector("#download-feedback");
|
| 300 |
-
let
|
| 301 |
-
let readerDownloadSourceResolved = false;
|
| 302 |
let downloadFeedbackTimer = 0;
|
| 303 |
-
function showDownloadFeedback(message) {
|
| 304 |
clearTimeout(downloadFeedbackTimer);
|
| 305 |
downloadFeedback.textContent = message;
|
| 306 |
downloadFeedback.hidden = !message;
|
| 307 |
-
if (message) downloadFeedbackTimer = setTimeout(() => showDownloadFeedback(""),
|
| 308 |
}
|
| 309 |
downloadButton.addEventListener("click", startReaderDownload);
|
| 310 |
loadingStatus.textContent = "";
|
|
@@ -3859,7 +3860,8 @@ async function start() {
|
|
| 3859 |
// an ID-only Reader link is resolving its source URL. The promise is reused
|
| 3860 |
// by loadPdfDocument, so this does not create a second module request.
|
| 3861 |
if (extension === "pdf" || /\.pdf(?:$|[?#])/i.test(sourceUrl)) preloadPdfEngine().catch(() => {});
|
| 3862 |
-
|
|
|
|
| 3863 |
assertReaderActive();
|
| 3864 |
if (readerId && /\/calibre-chm-epub-[^/]+\/document\.epub(?:$|\?)/i.test(sourceUrl)) {
|
| 3865 |
extension = "epub";
|
|
@@ -3869,7 +3871,6 @@ async function start() {
|
|
| 3869 |
document.querySelector(".page-controls").hidden = true;
|
| 3870 |
}
|
| 3871 |
syncCapabilityControls();
|
| 3872 |
-
readerDownloadSourceResolved = true;
|
| 3873 |
downloadButton.href = readerDownloadUrl(documentState.title, downloadUrl);
|
| 3874 |
if (
|
| 3875 |
(!validSource(sourceUrl) && !validSource(chapterManifestUrl) && !readerId) ||
|
|
@@ -3904,8 +3905,6 @@ async function start() {
|
|
| 3904 |
}
|
| 3905 |
assertReaderActive();
|
| 3906 |
if (!setReaderPhase("ready")) return;
|
| 3907 |
-
readerDownloadReady = true;
|
| 3908 |
-
showDownloadFeedback("");
|
| 3909 |
updateDocumentState({ restorationReady: !restorationFailed });
|
| 3910 |
scheduleSave();
|
| 3911 |
return;
|
|
@@ -3925,8 +3924,6 @@ async function start() {
|
|
| 3925 |
await restoreInitialPosition(documentState.restoredEntry, generation);
|
| 3926 |
assertReaderActive();
|
| 3927 |
if (!setReaderPhase("ready")) return;
|
| 3928 |
-
readerDownloadReady = true;
|
| 3929 |
-
showDownloadFeedback("");
|
| 3930 |
updateDocumentState({ restorationReady: !restorationFailed });
|
| 3931 |
updateProgressTools();
|
| 3932 |
if (fullSearchInput.value.trim()) runFullSearch();
|
|
|
|
| 113 |
async function startReaderDownload(event) {
|
| 114 |
event.preventDefault();
|
| 115 |
const button = event.currentTarget;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
if (button.hasAttribute("aria-busy")) return;
|
| 117 |
+
showDownloadFeedback("正在准备下载…", 0);
|
|
|
|
|
|
|
| 118 |
const controller = new AbortController();
|
| 119 |
+
let timer;
|
| 120 |
button.setAttribute("aria-busy", "true");
|
| 121 |
try {
|
| 122 |
+
// ID-only links share the Reader's in-flight resolution, not its render phase.
|
| 123 |
+
if (!downloadUrl) await readerSourcePromise;
|
| 124 |
+
if (!downloadUrl) throw new Error("无法获取原文件地址");
|
| 125 |
+
const filename = documentState.title || "file";
|
| 126 |
+
const checkUrl = readerDownloadApiUrl(`/api/download/check?link=${encodeURIComponent(downloadUrl)}`);
|
| 127 |
+
timer = setTimeout(() => controller.abort(), 8000);
|
| 128 |
const response = await fetch(checkUrl, { signal: controller.signal, cache: "no-store" });
|
| 129 |
const result = await response.json().catch(() => null);
|
| 130 |
if (!response.ok || result?.ok !== true) throw new Error(result?.error || "下载检查失败,请重试");
|
| 131 |
+
if (readerLifecycle.disposed) return;
|
| 132 |
const frame = document.createElement("iframe");
|
| 133 |
frame.hidden = true;
|
| 134 |
frame.setAttribute("aria-hidden", "true");
|
| 135 |
frame.src = readerDownloadUrl(filename, downloadUrl);
|
| 136 |
document.body.appendChild(frame);
|
| 137 |
setTimeout(() => frame.remove(), 60000);
|
| 138 |
+
showDownloadFeedback("已发起下载");
|
| 139 |
} catch (error) {
|
| 140 |
if (!readerLifecycle.disposed) {
|
| 141 |
showDownloadFeedback(error?.name === "AbortError" ? "下载检查超时,请重试" : (error.message || "下载失败,请重试"));
|
|
|
|
| 299 |
const loadingStatus = document.querySelector("#loading-status");
|
| 300 |
const downloadButton = document.querySelector("#download");
|
| 301 |
const downloadFeedback = document.querySelector("#download-feedback");
|
| 302 |
+
let readerSourcePromise = null;
|
|
|
|
| 303 |
let downloadFeedbackTimer = 0;
|
| 304 |
+
function showDownloadFeedback(message, duration = 4000) {
|
| 305 |
clearTimeout(downloadFeedbackTimer);
|
| 306 |
downloadFeedback.textContent = message;
|
| 307 |
downloadFeedback.hidden = !message;
|
| 308 |
+
if (message && duration) downloadFeedbackTimer = setTimeout(() => showDownloadFeedback(""), duration);
|
| 309 |
}
|
| 310 |
downloadButton.addEventListener("click", startReaderDownload);
|
| 311 |
loadingStatus.textContent = "";
|
|
|
|
| 3860 |
// an ID-only Reader link is resolving its source URL. The promise is reused
|
| 3861 |
// by loadPdfDocument, so this does not create a second module request.
|
| 3862 |
if (extension === "pdf" || /\.pdf(?:$|[?#])/i.test(sourceUrl)) preloadPdfEngine().catch(() => {});
|
| 3863 |
+
readerSourcePromise = resolveReaderSource();
|
| 3864 |
+
await readerSourcePromise;
|
| 3865 |
assertReaderActive();
|
| 3866 |
if (readerId && /\/calibre-chm-epub-[^/]+\/document\.epub(?:$|\?)/i.test(sourceUrl)) {
|
| 3867 |
extension = "epub";
|
|
|
|
| 3871 |
document.querySelector(".page-controls").hidden = true;
|
| 3872 |
}
|
| 3873 |
syncCapabilityControls();
|
|
|
|
| 3874 |
downloadButton.href = readerDownloadUrl(documentState.title, downloadUrl);
|
| 3875 |
if (
|
| 3876 |
(!validSource(sourceUrl) && !validSource(chapterManifestUrl) && !readerId) ||
|
|
|
|
| 3905 |
}
|
| 3906 |
assertReaderActive();
|
| 3907 |
if (!setReaderPhase("ready")) return;
|
|
|
|
|
|
|
| 3908 |
updateDocumentState({ restorationReady: !restorationFailed });
|
| 3909 |
scheduleSave();
|
| 3910 |
return;
|
|
|
|
| 3924 |
await restoreInitialPosition(documentState.restoredEntry, generation);
|
| 3925 |
assertReaderActive();
|
| 3926 |
if (!setReaderPhase("ready")) return;
|
|
|
|
|
|
|
| 3927 |
updateDocumentState({ restorationReady: !restorationFailed });
|
| 3928 |
updateProgressTools();
|
| 3929 |
if (fullSearchInput.value.trim()) runFullSearch();
|
tests/test_reader_refactor.py
CHANGED
|
@@ -79,7 +79,7 @@ class ReaderRefactorTest(unittest.TestCase):
|
|
| 79 |
self.assertEqual(image.get_attribute("src"), source + "/pages/page-000003.webp")
|
| 80 |
self.assertTrue(image.evaluate("image => image.complete && image.naturalWidth > 0"))
|
| 81 |
|
| 82 |
-
def
|
| 83 |
pending_content = []
|
| 84 |
checks = []
|
| 85 |
downloads = []
|
|
@@ -102,10 +102,9 @@ class ReaderRefactorTest(unittest.TestCase):
|
|
| 102 |
self.page.wait_for_function("() => document.querySelector('#download').hasAttribute('href')")
|
| 103 |
self.assertNotEqual(self.page.locator("html").get_attribute("data-reader-phase"), "ready")
|
| 104 |
self.page.locator("#download").click()
|
| 105 |
-
self.page.
|
| 106 |
-
self.assertEqual(checks,
|
| 107 |
self.assertEqual(downloads, [])
|
| 108 |
-
self.assertEqual(self.page.locator("#download-feedback").text_content(), "正在准备原文件,请稍候")
|
| 109 |
self.assertNotIn("原文件", self.page.locator("#status").text_content())
|
| 110 |
self.page.set_viewport_size({"width": 390, "height": 844})
|
| 111 |
self.assertTrue(self.page.locator("#download-feedback").evaluate("""node => {
|
|
@@ -113,17 +112,59 @@ class ReaderRefactorTest(unittest.TestCase):
|
|
| 113 |
const button = document.querySelector('#download').getBoundingClientRect();
|
| 114 |
return message.left >= 0 && message.right <= innerWidth && message.top >= button.bottom;
|
| 115 |
}"""))
|
| 116 |
-
pending_content[0].fulfill(status=200, content_type="text/plain", body="Reader download")
|
| 117 |
-
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 118 |
-
self.assertTrue(self.page.locator("#download-feedback").is_hidden())
|
| 119 |
-
self.page.locator("#download").click()
|
| 120 |
-
self.page.wait_for_function("() => document.querySelector('#download-feedback').textContent === '下载检查失败,请重试'")
|
| 121 |
-
self.assertEqual(downloads, [])
|
| 122 |
with self.page.expect_download() as event:
|
| 123 |
self.page.locator("#download").click()
|
| 124 |
self.assertEqual(event.value.suggested_filename, "refactor.txt")
|
|
|
|
| 125 |
self.assertEqual(len(checks), 2)
|
| 126 |
self.assertEqual(len(downloads), 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
def test_failed_reader_still_allows_original_download(self):
|
| 129 |
checks = []
|
|
|
|
| 79 |
self.assertEqual(image.get_attribute("src"), source + "/pages/page-000003.webp")
|
| 80 |
self.assertTrue(image.evaluate("image => image.complete && image.naturalWidth > 0"))
|
| 81 |
|
| 82 |
+
def test_download_during_prepare_does_not_interrupt_reader(self):
|
| 83 |
pending_content = []
|
| 84 |
checks = []
|
| 85 |
downloads = []
|
|
|
|
| 102 |
self.page.wait_for_function("() => document.querySelector('#download').hasAttribute('href')")
|
| 103 |
self.assertNotEqual(self.page.locator("html").get_attribute("data-reader-phase"), "ready")
|
| 104 |
self.page.locator("#download").click()
|
| 105 |
+
self.page.wait_for_function("() => document.querySelector('#download-feedback').textContent === '下载检查失败,请重试'")
|
| 106 |
+
self.assertEqual(len(checks), 1)
|
| 107 |
self.assertEqual(downloads, [])
|
|
|
|
| 108 |
self.assertNotIn("原文件", self.page.locator("#status").text_content())
|
| 109 |
self.page.set_viewport_size({"width": 390, "height": 844})
|
| 110 |
self.assertTrue(self.page.locator("#download-feedback").evaluate("""node => {
|
|
|
|
| 112 |
const button = document.querySelector('#download').getBoundingClientRect();
|
| 113 |
return message.left >= 0 && message.right <= innerWidth && message.top >= button.bottom;
|
| 114 |
}"""))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
with self.page.expect_download() as event:
|
| 116 |
self.page.locator("#download").click()
|
| 117 |
self.assertEqual(event.value.suggested_filename, "refactor.txt")
|
| 118 |
+
self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "prepare")
|
| 119 |
self.assertEqual(len(checks), 2)
|
| 120 |
self.assertEqual(len(downloads), 1)
|
| 121 |
+
pending_content[0].fulfill(status=200, content_type="text/plain", body="Reader download")
|
| 122 |
+
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 123 |
+
self.assertIn("Reader download", self.page.locator("#content").text_content())
|
| 124 |
+
|
| 125 |
+
def test_id_only_download_joins_reader_resolution(self):
|
| 126 |
+
resolved = []
|
| 127 |
+
content = []
|
| 128 |
+
checks = []
|
| 129 |
+
source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/shared.txt"
|
| 130 |
+
self.page.route("**/api/reader-resolve?**", lambda route: resolved.append(route))
|
| 131 |
+
self.page.route("**/api/reader-content?**", lambda route: content.append(route))
|
| 132 |
+
self.page.route("**/api/download/check?**", lambda route: (
|
| 133 |
+
checks.append(route.request.url), route.fulfill(json={"ok": True})))
|
| 134 |
+
self.page.route("**/api/download?**", lambda route: route.fulfill(
|
| 135 |
+
body=b"original", headers={"Content-Disposition": "attachment; filename=shared.txt"}))
|
| 136 |
+
self.page.goto(self.origin + "/static/reader.html?id=" + "a" * 13 + "&ext=txt", wait_until="domcontentloaded")
|
| 137 |
+
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'resolve'")
|
| 138 |
+
self.page.locator("#download").click()
|
| 139 |
+
self.page.locator("#download").click()
|
| 140 |
+
self.assertEqual(len(resolved), 1)
|
| 141 |
+
self.assertEqual(checks, [])
|
| 142 |
+
with self.page.expect_download() as event:
|
| 143 |
+
resolved[0].fulfill(json={"url": source, "download": source, "title": "shared", "extension": "txt"})
|
| 144 |
+
self.assertEqual(event.value.suggested_filename, "shared.txt")
|
| 145 |
+
self.assertEqual(len(checks), 1)
|
| 146 |
+
self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "prepare")
|
| 147 |
+
content[0].fulfill(body="Resolved text")
|
| 148 |
+
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 149 |
+
|
| 150 |
+
def test_pdf_can_finish_preparing_after_download_starts(self):
|
| 151 |
+
pending_content = []
|
| 152 |
+
self.page.route("**/api/reader-content**", lambda route: pending_content.append(route))
|
| 153 |
+
self.page.route("**/api/download/check**", lambda route: route.fulfill(json={"ok": True}))
|
| 154 |
+
self.page.route("**/api/download?**", lambda route: route.fulfill(
|
| 155 |
+
content_type="application/octet-stream", body=b"original",
|
| 156 |
+
headers={"Content-Disposition": "attachment; filename=book.pdf"}))
|
| 157 |
+
self.page.goto(self.reader_url("pdf"), wait_until="domcontentloaded")
|
| 158 |
+
self.page.wait_for_function("() => document.querySelector('#download').hasAttribute('href')")
|
| 159 |
+
with self.page.expect_download() as event:
|
| 160 |
+
self.page.locator("#download").click()
|
| 161 |
+
self.assertEqual(event.value.suggested_filename, "book.pdf")
|
| 162 |
+
self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "prepare")
|
| 163 |
+
self.page.wait_for_timeout(200)
|
| 164 |
+
self.assertTrue(pending_content)
|
| 165 |
+
pending_content[0].fulfill(content_type="application/pdf", body=support.minimal_pdf())
|
| 166 |
+
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 167 |
+
self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for(state="attached")
|
| 168 |
|
| 169 |
def test_failed_reader_still_allows_original_download(self):
|
| 170 |
checks = []
|