File size: 19,739 Bytes
dac2ca2
 
bef5045
dac2ca2
 
 
822b94b
dac2ca2
 
 
 
 
 
 
 
 
 
 
 
 
822b94b
dac2ca2
 
 
 
 
 
 
 
 
 
49a03ba
dac2ca2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dac2ca2
49a03ba
 
 
 
dac2ca2
ea7d43c
 
 
 
 
 
 
 
dac2ca2
49a03ba
ea7d43c
49a03ba
 
6c8fd46
 
822b94b
49a03ba
 
 
822b94b
6c8fd46
49a03ba
 
 
 
 
 
 
 
 
 
 
 
dac2ca2
49a03ba
dac2ca2
 
49a03ba
 
 
 
6c8fd46
49a03ba
6c8fd46
 
 
 
 
 
 
 
 
49a03ba
6c8fd46
49a03ba
 
 
dac2ca2
49a03ba
 
 
 
 
 
 
dac2ca2
49a03ba
 
 
 
dac2ca2
49a03ba
 
 
1548c9c
dac2ca2
49a03ba
 
 
 
 
89b1837
 
dac2ca2
 
89b1837
 
49a03ba
dac2ca2
1548c9c
 
 
 
 
 
 
 
 
 
 
dac2ca2
1548c9c
 
49a03ba
 
 
 
 
dac2ca2
 
 
aeb21e9
 
 
 
dac2ca2
49a03ba
 
 
 
 
 
 
 
 
81f2c79
 
 
9ceac12
81f2c79
 
 
 
 
479bcbd
81f2c79
 
8b90a8a
49a03ba
 
dac2ca2
 
 
49a03ba
 
 
 
 
 
 
 
 
 
 
082debe
 
 
 
 
 
 
 
49a03ba
082debe
49a03ba
 
dac2ca2
082debe
 
 
 
49a03ba
e52d9cd
49a03ba
 
e52d9cd
9ceac12
082debe
8c2c7af
dac2ca2
8c2c7af
81f2c79
 
082debe
49a03ba
 
dac2ca2
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f1b004
49a03ba
 
 
 
 
bef5045
 
49a03ba
bef5045
2f1b004
49a03ba
2f1b004
 
 
ae3a71a
2f1b004
bef5045
49a03ba
 
 
 
 
5d948f9
 
 
 
 
 
 
 
 
 
 
 
bef5045
5d948f9
 
 
 
 
 
 
dac2ca2
49a03ba
5d948f9
2f1b004
49a03ba
 
 
 
dac2ca2
49a03ba
5d948f9
2f1b004
49a03ba
 
2f1b004
 
 
 
 
 
 
49a03ba
 
 
 
 
dac2ca2
49a03ba
5d948f9
 
2f1b004
49a03ba
2f1b004
 
 
 
 
 
 
49a03ba
 
 
 
 
551ecc9
 
49a03ba
 
 
5d948f9
 
2f1b004
49a03ba
2f1b004
 
 
 
 
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/**
 * @typedef {{[key: string]: unknown}} ReaderMetadata
 * @typedef {{url: URL, prefix: string, bucketPath: string}} AssetFamily
 * @typedef {object} ReaderSourceContext
 * @property {ReaderMetadata | null} resolvedReaderData
 * @property {string} downloadUrl
 * @property {Promise<unknown> | null} readerSourcePromise
 * @property {{title: string}} documentState
 * @property {{disposed: boolean}} readerLifecycle
 * @property {(message: string, duration?: number) => void} showDownloadFeedback
 * @property {(path: string) => string} readerDownloadApiUrl
 * @property {(filename: string, link: string) => string} readerDownloadUrl
 * @property {(dispose: () => void) => () => void} trackReaderResource
 * @property {<T>(promise: Promise<T>) => Promise<T>} awaitReader
 * @property {() => void} assertReaderActive
 * @property {(ms: number) => Promise<void>} waitForReader
 * @property {{requestBuffered: (url: string, timeout: number, limit: number) => Promise<Response>}} readerRequestManager
 * @property {number} READER_PROXY_TIMEOUT_MS
 * @property {string} ocrManifestUrl
 * @property {URLSearchParams} params
 * @property {{update: (key: 'source', value: {metadata: ReaderMetadata | null}) => void}} readerRuntime
 * @property {string} sourceName
 * @property {string} extension
 * @property {(state: {title: string}) => void} updateDocumentState
 * @property {() => boolean} isReaderOverlayFrame
 * @property {string} readerPathLabel
 * @property {URL | null} folderNavigationTarget
 * @property {string} folderReturnUrl
 * @property {HTMLButtonElement} readerPath
 * @param {ReaderSourceContext} readerContext
 */
export function createReaderSource(readerContext) {
  /** @param {unknown} value @returns {value is Record<string, unknown>} */
  function isRecord(value) {
    return value !== null && typeof value === "object" && !Array.isArray(value);
  }

  /** @param {unknown} value @returns {ReaderMetadata} */
  function parseMetadata(value) {
    if (!isRecord(value)) throw new Error("Invalid reader metadata");
    return value;
  }

  /** @param {unknown} error @param {string} key @returns {string | undefined} */
  function errorField(error, key) {
    if ((typeof error !== "object" || error === null) && typeof error !== "function") return undefined;
    try {
      const value = /** @type {Record<string, unknown>} */ (error)[key];
      return typeof value === "string" ? value : undefined;
    } catch (_) {
      return undefined;
    }
  }

  /** @param {string} url */
  function readerContentUrl(url) {
    try {
      const parsed = new URL(url, location.href);
      if (parsed.origin === location.origin && parsed.pathname === "/api/reader-bucket-resource")
        return parsed.href;
      if (parsed.origin === "https://huggingface.co" && !parsed.username && !parsed.password && !parsed.search && !parsed.hash) {
        const prefix = /^\/buckets\/(vomebook\/(?:pdf-pages-v2|reader-assets-v2))\/resolve\//.exec(parsed.pathname);
        const path = prefix && decodeURIComponent(parsed.pathname.slice(prefix[0].length));
        if (path && VoiceOfMLReader.isBucketPath(path, true, prefix[1]))
          return `/api/reader-bucket-resource?path=${encodeURIComponent(path)}`;
      }
    } catch (_) {}
    return `/api/reader-content?url=${encodeURIComponent(url)}`;
  }

  /** @param {string} path */
  function readerDownloadApiUrl(path) {
    return path;
  }

  /** @param {string} fallback */
  function readerOriginalFilename(fallback) {
    // The human-readable title can omit a repeated suffix or normalize spaces;
    // the authoritative metadata keeps the exact source filename separately.
    const name = readerContext.resolvedReaderData?.filename;
    return typeof name === "string" && name.trim() && !/[\/\\\x00-\x1f\x7f]/.test(name)
      ? name : fallback;
  }

  /** @param {string} filename @param {string} link */
  function readerDownloadUrl(filename, link) {
    return readerContext.readerDownloadApiUrl(`/api/download?file=${encodeURIComponent(readerOriginalFilename(filename || "file"))}&link=${encodeURIComponent(link || "")}`);
  }

  let readerDownloadAttempt = 0;

  /** @param {Event} event */
  async function startReaderDownload(event) {
    event.preventDefault();
    const button = event.currentTarget;
    if (!(button instanceof Element) || button.hasAttribute("aria-busy")) return;
    const attempt = ++readerDownloadAttempt;
    readerContext.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 (!readerContext.downloadUrl) await readerContext.readerSourcePromise;
      if (!readerContext.downloadUrl) throw new Error("无法获取原文件地址");
      const filename = readerContext.documentState.title || "file";
      const checkUrl = readerContext.readerDownloadApiUrl(`/api/download/check?link=${encodeURIComponent(readerContext.downloadUrl)}`);
      timer = setTimeout(() => controller.abort(), 8000);
      const response = await fetch(checkUrl, { signal: controller.signal, cache: "no-store" });
      /** @type {unknown} */
      const result = await response.json().catch(() => null);
      if (!response.ok || !isRecord(result) || result.ok !== true)
        throw new Error(isRecord(result) && typeof result.error === "string" && result.error || "下载检查失败,请重试");
      if (readerContext.readerLifecycle.disposed) return;
      const frame = document.createElement("iframe");
      frame.hidden = true;
      frame.setAttribute("aria-hidden", "true");
      frame.setAttribute("sandbox", "allow-downloads");
      frame.src = readerContext.readerDownloadUrl(filename, readerContext.downloadUrl);
      const cleanup = setTimeout(() => frame.remove(), 60000);
      // An attachment goes to the browser; a proxy error loads a document.
      // No DOM access to the (possibly cross-origin) response is needed.
      frame.addEventListener("load", () => {
        clearTimeout(cleanup);
        frame.remove();
        if (attempt === readerDownloadAttempt && !readerContext.readerLifecycle.disposed)
          readerContext.showDownloadFeedback("下载失败,请重试(已发起下载,未收到附件)");
      }, { once: true });
      document.body.appendChild(frame);
      // Request handed off, not server acceptance or download completion.
      readerContext.showDownloadFeedback("已发起下载");
    } catch (error) {
      if (!readerContext.readerLifecycle.disposed) {
        readerContext.showDownloadFeedback(errorField(error, "name") === "AbortError" ? "下载检查超时,请重试" : (errorField(error, "message") || "下载失败,请重试"));
      }
    } finally {
      clearTimeout(timer);
      button.removeAttribute("aria-busy");
    }
  }

  /** @param {string} url */
  function normalizeSourceUrl(url) {
    return url.startsWith("/api/reader-bucket-resource?") ? new URL(url, location.origin).href : url;
  }

  /** @param {string} id */
  async function resolveReaderId(id) {
    const endpoint = `/api/reader-resolve?id=${encodeURIComponent(id)}`;
    for (let attempt = 0; attempt < 2; attempt++) {
      let status;
      const early = /** @type {{id: string, promise: Promise<{ok: boolean, status: number, data: unknown}>, dispose: () => void} | null | undefined} */ (window.__VOICE_READER_RESOLVE__);
      if (!attempt && early?.id === id) {
        window.__VOICE_READER_RESOLVE__ = null;
        const untrack = readerContext.trackReaderResource(early.dispose);
        let result;
        try { result = await readerContext.awaitReader(early.promise); }
        catch (error) {
          readerContext.assertReaderActive();
          const name = errorField(error, "name");
          if (name !== "TimeoutError" && name !== "TypeError") throw error;
          continue;
        }
        finally { untrack(); early.dispose(); }
        if (result.ok) return parseMetadata(result.data);
        status = result.status;
      } else {
        const response = await readerContext.readerRequestManager.requestBuffered(
          endpoint, readerContext.READER_PROXY_TIMEOUT_MS, VoiceOfMLReaderSecurity.LIMITS.manifestBytes);
        if (response.ok) {
          /** @type {unknown} */
          const data = await response.json();
          return parseMetadata(data);
        }
        await response.body?.cancel();
        status = response.status;
      }
      if (![408, 429, 500, 502, 503, 504].includes(status) || attempt)
        throw new Error(`HTTP ${status}`);
      await readerContext.waitForReader(350);
    }
    throw new Error("Reader ID resolution failed");
  }

  /** @param {unknown} input */
  function applyReaderMetadata(input) {
    const data = input == null ? null : parseMetadata(input);
    // Reapplying committed metadata refreshes presentation without replacing the record.
    if (data && data !== readerContext.resolvedReaderData)
      readerContext.resolvedReaderData = { ...readerContext.resolvedReaderData, ...data };
    if (data?.ReaderOcrManifest || data?.ocr_manifest)
      readerContext.ocrManifestUrl = /** @type {string} */ (data.ReaderOcrManifest || data.ocr_manifest);
    readerContext.readerRuntime.update("source", { metadata: readerContext.resolvedReaderData });
    const title = String(readerContext.resolvedReaderData?.title || readerContext.params.get("title") || readerContext.sourceName).trim();
    const suffix = String(
      readerContext.resolvedReaderData?.original_extension || (readerContext.extension === "pdf-pages" ? "pdf" : readerContext.extension)
    )
      .toLowerCase()
      .replace(/^\./, "");
    const value = title + (suffix && !title.toLowerCase().endsWith(`.${suffix}`) ? `.${suffix}` : "");
    readerContext.updateDocumentState({ title: value });
    // Prefer the exact original name when metadata supplies it. The display
    // title can omit a repeated suffix or normalize meaningful whitespace.
    const displayName = readerOriginalFilename(value);
    const heading = /** @type {HTMLElement} */ (document.querySelector("#title"));
    if (heading.textContent !== displayName) {
      heading.textContent = displayName;
      heading.scrollLeft = 0;
    }
    heading.title = displayName;
    document.title = displayName;
    if (readerContext.isReaderOverlayFrame())
      window.parent.postMessage({ type: "voice-reader-title", title: document.title }, location.origin);
    applyReaderPathMetadata(readerContext.resolvedReaderData);
  }

  /** @param {unknown} input */
  function applyReaderPathMetadata(input) {
    const data = input == null ? null : parseMetadata(input);
    const folder = Array.isArray(data?.folder) ? data.folder.join("/") : String(data?.folder || "");
    const value = String(
      data?.path || [data?.repo, folder].filter(Boolean).join("/") || readerContext.readerPathLabel
    ).replace(/^\/+|\/+$/g, "");
    readerContext.folderNavigationTarget = null;
    try {
      const target = new URL(readerContext.folderReturnUrl, location.origin);
      if (
        readerContext.folderReturnUrl &&
        target.origin === location.origin &&
        target.pathname.split("/").filter(Boolean).length === 1
      ) {
        // Legacy explicit targets only carry the direct-folder filter. Keep
        // that filter authoritative and mirror it into the sidebar route.
        const direct = target.searchParams.getAll("folder_self");
        if (direct.length === 1 && !target.searchParams.has("folder_subtree") && !target.searchParams.has("folder")) {
          if (direct[0]) target.searchParams.set("path", direct[0]);
          else target.searchParams.delete("path");
        }
        readerContext.folderNavigationTarget = target;
      }
    } catch (_) {}
    if (!readerContext.folderNavigationTarget && data?.repo) {
      readerContext.folderNavigationTarget = new URL("/" + encodeURIComponent(String(data.repo)), location.origin);
      if (folder) {
        readerContext.folderNavigationTarget.searchParams.set("folder_self", folder);
        readerContext.folderNavigationTarget.searchParams.set("path", folder);
      }
    }
    readerContext.readerPath.textContent = value;
    readerContext.readerPath.hidden = !value;
    readerContext.readerPath.disabled = !readerContext.folderNavigationTarget;
    readerContext.readerPath.setAttribute("aria-label", `筛选文件夹:${value}`);
    const panelPath = /** @type {HTMLButtonElement | null} */ (document.querySelector("#reader-panel-path"));
    if (panelPath) {
      const folderLabel = value || "不可用";
      /** @type {Element} */ (panelPath.querySelector(".reader-panel-folder")).textContent = `所在目录:${folderLabel}`;
      panelPath.disabled = !value || !readerContext.folderNavigationTarget;
      panelPath.setAttribute("aria-label", `${panelPath.disabled ? "所在目录" : "打开所在目录"}:${folderLabel}`);
      panelPath.title = value;
    }
  }

  /** @param {string} raw */
  function validSource(raw) {
    try {
      const url = new URL(raw);
      const bucketPath = url.searchParams.get("path") || "";
      if (
        (url.origin === location.origin || url.origin === "https://voiceofml-search.hf.space") &&
        url.pathname === "/api/reader-bucket-resource" &&
        url.searchParams.getAll("path").length === 1 &&
        [...url.searchParams.keys()].every((key) => key === "path") &&
         (VoiceOfMLReader.isBucketPath(bucketPath, true, "vomebook/pdf-pages-v2") ||
          VoiceOfMLReader.isBucketPath(bucketPath, true, "vomebook/reader-assets-v2"))
      )
        return true;
      if (url.protocol === "https:" && url.hostname === "huggingface.co" &&
          (url.pathname.startsWith("/buckets/vomebook/pdf-pages-v2/resolve/") ||
           url.pathname.startsWith("/buckets/vomebook/reader-assets-v2/resolve/")) && !url.search && !url.hash) {
        const prefix = url.pathname.startsWith("/buckets/vomebook/pdf-pages-v2/resolve/")
          ? "/buckets/vomebook/pdf-pages-v2/resolve/"
          : "/buckets/vomebook/reader-assets-v2/resolve/";
        const path = decodeURIComponent(url.pathname.slice(prefix.length));
        const bucket = prefix.includes("pdf-pages-v2") ? "vomebook/pdf-pages-v2" : "vomebook/reader-assets-v2";
        return VoiceOfMLReader.isBucketPath(path, true, bucket);
      }
      if (url.protocol !== "https:" || !["huggingface.co", "hf-mirror.com"].includes(url.hostname))
        return false;
      return /^\/datasets\/VoiceOfML\/[^/]+\/(resolve|raw)\//.test(url.pathname);
    } catch (_) {
      return false;
    }
  }

  /** @param {string} raw */
  function readerAssetObjectFamily(raw) {
    try {
      const url = new URL(raw, location.href);
      if (url.origin !== "https://voiceofml-search.hf.space" || url.pathname !== "/api/reader-bucket-resource")
        return null;
      const bucketPath = url.searchParams.get("path") || "";
      const match = bucketPath.match(/^(chapters\/ebook\/(?:epub|mobi|azw3|fb2|chm)\/[0-9a-f]{64}\/[0-9a-f]{16}\/)/);
      if (url.hash || url.searchParams.getAll("path").length !== 1 ||
          [...url.searchParams.keys()].some((key) => key !== "path") || !match?.[1] ||
          !VoiceOfMLReader.isBucketPath(bucketPath, true, "vomebook/reader-assets-v2")) return null;
      return { url, prefix: match[1], bucketPath };
    } catch (_) {
      return null;
    }
  }

  /** @type {{raw: string, family: AssetFamily} | null} */
  let manifestFamily = null;
  /** @type {{raw: string, family: AssetFamily} | null} */
  let chapterFamily = null;

  // The rewrite pass resolves many attributes against the same two bases.
  // Keep just the latest validated manifest and chapter bases. Only reuse
  // exact absolute URLs: relative inputs still depend on location.href.
  /** @param {string} raw @param {boolean} isManifest */
  function chapterAssetFamily(raw, isManifest) {
    const cached = isManifest ? manifestFamily : chapterFamily;
    if (cached && raw === cached.raw) return cached.family;
    const family = readerAssetObjectFamily(raw);
    if (family && raw === family.url.href) {
      if (isManifest) manifestFamily = { raw, family };
      else chapterFamily = { raw, family };
    }
    return family;
  }

  /** @param {string} raw */
  function trustedReaderAssetManifestUrl(raw) {
    const family = chapterAssetFamily(raw, true);
    return family && /\/chapter-manifest\.json$/i.test(family.bucketPath || "")
      ? family.url.href
      : null;
  }

  /** @param {string} raw @param {string} base */
  function trustedChapterUrl(raw, base) {
    const manifest = chapterAssetFamily(base, true);
    if (!manifest || !/\/chapter-manifest\.json$/i.test(manifest.bucketPath || ""))
      return null;
    try {
      const url = new URL(String(raw || ""), `https://bucket.invalid/${manifest.bucketPath}`);
      const path = decodeURIComponent(url.pathname.slice(1));
      if (url.origin !== "https://bucket.invalid" || url.search || url.hash ||
           !path.startsWith(manifest.prefix) ||
           !/(?:\/chapters\/chapter-[0-9]{4}\.xhtml|\/epub-search-index\.json\.gz)$/i.test(path) ||
           !VoiceOfMLReader.isBucketPath(path, true, "vomebook/reader-assets-v2")) return null;
      return `${manifest.url.origin}/api/reader-bucket-resource?path=${encodeURIComponent(path)}`;
    } catch (_) {
      return null;
    }
  }

  /** @param {string} raw @param {string} base @param {string} manifestBase */
  function trustedChapterReferenceUrl(raw, base, manifestBase) {
    const family = chapterAssetFamily(manifestBase, true);
    const current = chapterAssetFamily(base, false);
    if (!family || !current) return null;
    try {
      const url = new URL(String(raw || ""), `https://bucket.invalid/${current.bucketPath}`);
      const path = decodeURIComponent(url.pathname.slice(1));
      if (url.origin !== "https://bucket.invalid" || url.search ||
          !path.startsWith(family.prefix) || !/\/chapters\/chapter-[0-9]{4}\.xhtml$/i.test(path) ||
          !VoiceOfMLReader.isBucketPath(path, true, "vomebook/reader-assets-v2")) return null;
      return { url: `${family.url.origin}/api/reader-bucket-resource?path=${encodeURIComponent(path)}`,
               fragment: url.hash };
    } catch (_) {
      return null;
    }
  }

  /** @param {string} raw @param {string} base @param {string} manifestBase */
  function trustedChapterResourceUrl(raw, base, manifestBase) {
    const value = String(raw || "").trim();
    if (!value || /^(?:data:|mailto:|tel:|javascript:)/i.test(value)) return null;
    // Chapters and resources can be siblings within the manifest's asset directory.
    const family = chapterAssetFamily(manifestBase, true);
    const current = chapterAssetFamily(base, false);
    if (!family || !current) return null;
    try {
      const url = new URL(value, `https://bucket.invalid/${current.bucketPath}`);
      const path = decodeURIComponent(url.pathname.slice(1));
      if (url.origin !== "https://bucket.invalid" || url.search || url.hash ||
          !path.startsWith(family.prefix) || !VoiceOfMLReader.isBucketPath(path, true, "vomebook/reader-assets-v2")) return null;
      return `${family.url.origin}/api/reader-bucket-resource?path=${encodeURIComponent(path)}`;
    } catch (_) {
      return null;
    }
  }

  return {
    readerContentUrl,
    readerDownloadApiUrl,
    readerDownloadUrl,
    startReaderDownload,
    normalizeSourceUrl,
    resolveReaderId,
    applyReaderMetadata,
    validSource,
    trustedReaderAssetManifestUrl,
    trustedChapterUrl,
    trustedChapterReferenceUrl,
    trustedChapterResourceUrl
  };
}