diff --git a/packages/chat/README.md b/packages/chat/README.md index e82e66b..9bef310 100644 --- a/packages/chat/README.md +++ b/packages/chat/README.md @@ -20,6 +20,7 @@ It then has a tab, **Chat** (对话, 對話, チャット), under Plugins in the - **magpie's models.** The list comes from the gateway's `/v1/models`. Models with reasoning levels get an effort picker. Each model shows its brand icon (OpenAI, Claude, Gemini, DeepSeek, Qwen, Kimi, GLM, MiniMax and more) in the picker and next to its name in the transcript. The icons come from [@lobehub/icons](https://github.com/lobehub/lobe-icons) (MIT); see `chat/icons/models/NOTICE`. - **magpie's library.** Tick instructions and skills from `~/.config/magpie/library/` (folded into the system prompt), and MCP servers from `library.json` (their tools run as real `tool_calls`, at most 8 rounds, Streamable HTTP and stdio). The switch "使用 magpie 的全部 MCP 服务器" at the top of the MCP list uses every server in the library instead, one added to magpie later too; it is off by default, and turning it off brings back the servers you ticked. magpie's own MCP servers (web search, image recognition, image generation, plugin tools) are in the list beside the library's while they are on in magpie (asked of the gateway's `/v1/magpie/mcp`, magpie v0.1.2397 and later; an older magpie lists none); one turned off in magpie's Settings is left out, and a library server of the same name, such as an installed `magpie-image`, is used in its place. +- **EPUB books.** Chat reads selectable text in chapter order when you send a message. An EPUB already in the conversation history also works. Each follow-up sends the text again while the attachment is in history, so it counts toward the selected model's input limit each time. Attaching the same file twice sends one copy of the text. Chat does not transcribe images. - **Images and files.** Pick, drop or paste them. Images go to the model as `image_url`. Replies can carry base64 data-URI images, which render inline and open full size on click. Remote `` images are shown as a link instead of being loaded — fetching them automatically would let a reply make the page request an arbitrary URL. - **Streaming.** Reasoning unfolds while it arrives, then collapses. While the answer streams, the page follows it down unless you scroll up yourself; scroll back to the bottom and it resumes. - **Model status.** Every reply ends with a line saying what the model is doing: `Magpie正在觅食ing… · 2s` with a running timer while it generates, green `Magpie找到了食物! · 2s` when done, red `Magpie没有找到食物` on failure. The elapsed time is kept with the conversation. diff --git a/packages/chat/chat.test.mjs b/packages/chat/chat.test.mjs index 8825db5..9c9a681 100644 --- a/packages/chat/chat.test.mjs +++ b/packages/chat/chat.test.mjs @@ -6,6 +6,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test" import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { request } from "node:http" +import { runInNewContext } from "node:vm" import { tmpdir } from "node:os" import { join } from "node:path" @@ -150,6 +151,79 @@ test("with the token, a chat streams from the gateway with the caller key", asyn expect(got.body.messages.at(-1)).toEqual({ role: "user", content: "hi" }) }) +function chatPage(setup = "") { + const page = { + document: { readyState: "loading", querySelector: () => ({ getAttribute: () => token }), addEventListener() {} }, + TextDecoder, + fetch: (path, init) => { + if (path !== "api/chat") throw new Error("unexpected request: " + path) + return fetch(`http://127.0.0.1:${port}/api/chat`, init) + }, + window: { addEventListener() {} }, location: { search: "" }, + MagpieEpub: { isEpub: f => f.name?.endsWith(".epub") }, + } + runInNewContext(readFileSync(join(dir, "chat/app.js"), "utf8") + "\n" + setup, page) + return page +} + +test("a saved EPUB reaches the gateway once, including on a follow-up", async () => { + const page = chatPage("toast = message => globalThis.warnings.push(message);") + page.warnings = [] + const chapters = "The lamp is blue.\n\nThe lamp goes out." + const file = { name: "lamp.epub", kind: "file", data: "data:;base64,Ym9vaw==" } + const image = { name: "lamp.png", kind: "image", data: "data:image/png;base64,cG5n" } + const broken = { ...file, name: "broken.epub", data: "data:;base64,YmFk" } + const h = { ...json, "x-magpie-chat-token": token } + page.MagpieEpub.read = async data => { + if (data === broken.data) throw new Error("damaged") + expect(data).toBe(file.data) + return { text: chapters, imagePages: 1 } + } + const past = [ + { role: "user", content: "", files: [file, image] }, + { role: "assistant", content: "A blue lamp." }, + { role: "user", content: "What changed?", files: [{ ...file, name: "copy.epub" }, broken] }, + ] + const saved = JSON.parse((await raw("POST", "/api/conversations", h, { messages: past })).body) + const history = JSON.parse((await raw("GET", "/api/conversations/" + saved.id, h)).body).messages + const events = [] + await page.streamChat({ ...chatBody, messages: history }, event => events.push(event)) + expect(events.at(-1).type).toBe("done") + const sent = seen.at(-1).body.messages + expect(sent.at(-3).content[0].text).toContain(chapters) + expect(sent.at(-3).content[0].text).toContain("1 个章节仅含图片") + expect(sent.at(-3).content[1]).toEqual({ type: "image_url", image_url: { url: image.data } }) + expect(sent.at(-1).content).toContain("What changed?") + expect(sent.at(-1).content).toContain("broken.epub:damaged") + expect(page.warnings).toEqual(["旧附件未发送。broken.epub:damaged"]) + expect(JSON.stringify(sent).match(/The lamp goes out/g)).toHaveLength(1) + expect(JSON.stringify(sent)).not.toContain("Ym9vaw==") + expect(history[0].content).toBe("") + expect(history[0].files[0].data).toBe(file.data) +}) + +test("switching chats discards a book that is still being read", async () => { + const page = chatPage(` + updateSend = renderAttachments = renderMessages = renderSessions = scrollBottom = () => {}; + api = async () => ({ id: "other", messages: [] }); + readAsDataURL = () => globalThis.reading; + globalThis.pending = () => pendingBooks; + `) + const reading = Promise.withResolvers() + page.reading = reading.promise + page.MagpieEpub.read = async () => ({ text: "A page", characters: 5 }) + page.state.attachments.push({ name: "ready.epub" }) + const job = page.addFiles([{ name: "first.epub", type: "application/epub+zip", size: 12 }]) + expect(page.pending()).toBe(1) + page.openConversation("other") + await Promise.resolve() + reading.resolve("data:;base64,Ym9vaw==") + await job + expect(page.state.convId).toBe("other") + expect(page.state.attachments).toHaveLength(0) + expect(page.pending()).toBe(0) +}) + test("conversations save and list with the token", async () => { const h = { ...json, origin: "null", "x-magpie-chat-token": token } const saved = JSON.parse((await raw("POST", "/api/conversations", h, { title: "t", messages: [{ role: "user", content: "x" }] })).body) diff --git a/packages/chat/chat/app.js b/packages/chat/chat/app.js index 779936c..1827982 100644 --- a/packages/chat/chat/app.js +++ b/packages/chat/chat/app.js @@ -672,7 +672,8 @@ function parseEventBlock(block) { return data; } -function streamChat(payload, onEvent, signal) { +async function streamChat(payload, onEvent, signal) { + payload.messages = await requestMessages(payload.messages, function (reason) { toast("旧附件未发送。" + reason, true); }); return fetch("api/chat", { method: "POST", headers: authHeaders({ "content-type": "application/json" }), @@ -972,14 +973,26 @@ function readAsDataURL(file) { function guessType(file) { if (file.type) return file.type; var ext = String(file.name || "").split(".").pop().toLowerCase(); - var map = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", svg: "image/svg+xml", pdf: "application/pdf", txt: "text/plain", md: "text/markdown", json: "application/json" }; + var map = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", svg: "image/svg+xml", pdf: "application/pdf", epub: "application/epub+zip", txt: "text/plain", md: "text/markdown", json: "application/json" }; return map[ext] || "application/octet-stream"; } // 一批 File → 加入待发送列表 +var attachmentContext = 0, pendingBooks = 0; +function clearPendingAttachments() { + attachmentContext++; + pendingBooks = 0; + state.attachments = []; + renderAttachments(); +} + function addFiles(files) { var list = Array.from(files || []).slice(0, 8); if (!list.length) return Promise.resolve(); + var context = attachmentContext; + var books = list.filter(MagpieEpub.isEpub).length; + pendingBooks += books; + updateSend(); var jobs = list.map(function (file) { var type = guessType(file); var isImage = /^image\//.test(type); @@ -987,7 +1000,11 @@ function addFiles(files) { toast((isImage ? "图片" : "文件") + "太大:" + (file.name || ""), true); return null; } - return readAsDataURL(file).then(function (data) { + return readAsDataURL(file).then(async function (data) { + var book = MagpieEpub.isEpub(file) ? await MagpieEpub.read(data) : null; + if (book) { + return { name: file.name, type: type, kind: "file", size: file.size, data: data, bookChars: book.characters, imagePages: book.imagePages }; + } return api("api/upload", { method: "POST", body: { name: file.name || "file", type: type, data: data, clientType: type } @@ -995,11 +1012,19 @@ function addFiles(files) { // 上传接口挂了也还能本地显示:直接按 data URL 用 return { name: file.name || "file", type: type, kind: isImage ? "image" : "file", size: data.length, data: data }; }); + }).catch(function (err) { + if (context === attachmentContext) toast((file.name || "文件") + ":" + err.message, true); + return null; }); }).filter(Boolean); return Promise.all(jobs).then(function (out) { + if (context !== attachmentContext) return; out.forEach(function (f) { if (f && f.data) state.attachments.push(f); }); renderAttachments(); + }).finally(function () { + if (context !== attachmentContext) return; + pendingBooks -= books; + updateSend(); }); } @@ -1013,6 +1038,7 @@ function renderAttachments() { if (f.kind === "image") chip.appendChild(el("img", { src: f.data, alt: f.name || "" })); else chip.appendChild(el("span", { class: "ic", text: (String(f.name || "F").split(".").pop() || "F").slice(0, 3).toUpperCase() })); chip.appendChild(el("span", { class: "nm", text: f.name || "文件" })); + if (f.bookChars) chip.appendChild(el("span", { text: "随消息发送 " + f.bookChars.toLocaleString() + " 字" + (f.imagePages ? "(" + f.imagePages + " 个章节仅含图片)" : "") })); var rm = el("button", { class: "rm", type: "button", title: "移除", "aria-label": "移除" }); rm.appendChild(el("span", { text: "\u00d7" })); rm.addEventListener("click", function () { @@ -1461,6 +1487,7 @@ function askDelete(id, title) { state.settings.pinned = pinned; api("api/settings", { method: "POST", body: { pinned: pinned } }).catch(function () {}); if (state.convId === id) { + clearPendingAttachments(); state.convId = null; state.title = "新对话"; state.messages = []; @@ -1488,6 +1515,7 @@ function openConversation(id) { dropBlankDraft(); // 切换到别的对话时,空着的"新对话"不该留在列表里 api("api/conversations/" + encodeURIComponent(id)).then(function (conv) { if (!conv) return; + if (state.convId !== conv.id) clearPendingAttachments(); state.convId = conv.id; state.title = conv.title || "新对话"; state.messages = (conv.messages || []).map(normalizeMessage); @@ -1789,7 +1817,7 @@ function mediaBlock(files, opts) { } else { wrap.appendChild(el("span", { class: "msg-file", title: f.name || "" }, el("span", { class: "nm", text: f.name || "文件" }), - el("span", { class: "hint", text: f.size ? fmtBytes(f.size) : "" }) + el("span", { class: "hint", text: MagpieEpub.isEpub(f) ? "提问时读取正文" : (f.size ? fmtBytes(f.size) : "") }) )); } }); @@ -2121,20 +2149,60 @@ function updateSend() { var btn = $("#send"); var input = $("#input"); $("#app").classList.toggle("busy", state.busy); - btn.disabled = state.busy ? false : (!input.value.trim() && !(state.attachments || []).length); + btn.disabled = !state.busy && (pendingBooks > 0 || (!input.value.trim() && !(state.attachments || []).length)); btn.setAttribute("aria-label", state.busy ? "停止生成" : "发送"); input.title = state.busy ? "生成中…(Esc 停止)" : "Enter 发送 · Shift+Enter 换行"; } +async function requestMessages(history, warn) { + var seen = new Set(), messages = []; + for (var m of history) { + var files = (m.files || []).filter(Boolean); + if (m.role === "assistant") { + var calls = (m.toolCalls || []).filter(function (c) { return c && c.name && (c.result || c.isError); }); + if (m.content || calls.length) messages.push({ role: m.role, content: m.content, toolCalls: calls, files: files }); + continue; + } + var parts = [], otherFiles = []; + for (var f of files) { + if (!MagpieEpub.isEpub(f)) { + if (f.data) otherFiles.push(f); + continue; + } + var bytes = typeof f.data === "string" ? f.data.slice(f.data.indexOf(",") + 1) : ""; + if (seen.has(bytes)) { + parts.push("(" + f.name + " 的正文已附在前文。)"); + continue; + } + try { + var book = await MagpieEpub.read(f.data); + parts.push("【电子书:" + f.name + "】\n" + book.text + "\n【电子书结束】"); + if (book.imagePages) parts.push("(" + book.imagePages + " 个章节仅含图片,未提取文字。)"); + seen.add(bytes); + } catch (err) { + var reason = f.name + ":" + err.message; + parts.push("(未附上这本电子书的正文。" + reason + ")"); + warn(reason); + } + } + if (String(m.content || "").trim()) parts.push(m.content); + if (parts.length || otherFiles.some(function (f) { return f.kind === "image"; })) { + messages.push({ role: m.role, content: parts.join("\n\n"), files: otherFiles }); + } + } + return messages; +} + function send() { if (state.busy) { stop(); return; } + if (pendingBooks) { toast("电子书还在读取,请稍候。"); return; } var input = $("#input"); var text = input.value.trim(); if (!text && !(state.attachments || []).length) return; if (!state.settings.model) { toast("先选一个模型", true); return; } var files = (state.attachments || []).map(function (f) { - return { name: f.name, type: f.type, kind: f.kind, size: f.size, data: f.data }; + return { name: f.name, type: f.type, kind: f.kind, size: f.size, data: f.data, bookChars: f.bookChars, imagePages: f.imagePages }; }); var userMsg = { role: "user", content: text, reasoning: "", toolCalls: [], files: files }; state.attachments = []; @@ -2150,7 +2218,7 @@ function send() { state.messages.push(userMsg, asstMsg); if (!state.convId && state.title === "新对话") { - state.title = text.replace(/\s+/g, " ").slice(0, 30); + state.title = (text || files[0].name || "新对话").replace(/\s+/g, " ").slice(0, 30); } // 草稿发了第一条消息:先把列表里那条的标题换成刚输入的内容(不用等服务器), // 等保存成功再把它换成真正的对话条目(见 persistConversation)。 @@ -2177,28 +2245,8 @@ function send() { updateSend(); scrollBottom(true); - var history = state.messages.filter(function (m) { - if (m === asstMsg) return false; - if (m.role === "user") return Boolean(String(m.content || "").trim()); - return Boolean(m.content) || (m.toolCalls && m.toolCalls.length > 0); - }).map(function (m) { - // 上一轮的工具调用也带上,模型才知道它已经查过什么;服务端会把 - // assistant.tool_calls 和对应的 tool 结果一起重放,缺结果的调用它自己丢掉。 - var calls = m.role === "assistant" && Array.isArray(m.toolCalls) - ? m.toolCalls.filter(function (c) { return c && c.name && (c.result || c.isError); }) - : []; - return { - role: m.role, - content: m.content, - toolCalls: calls, - files: (m.files || []).filter(function (f) { return f && f.data; }).map(function (f) { - return { name: f.name, type: f.type, kind: f.kind, size: f.size, data: f.data }; - }) - }; - }); - var payload = { - messages: history, + messages: state.messages.slice(0, -1), model: state.settings.model, effort: state.settings.effort || "", system: state.settings.systemEnabled === false ? "" : (state.settings.system || ""), @@ -2461,6 +2509,7 @@ function newChat() { if (state.busy) { toast("正在生成,先停止再新建对话", true); return; } // 已经在一个空白的新对话里了:再点"新对话"就保持原样,别叠出第二个 if (isBlankDraft()) { $("#input").focus(); return; } + clearPendingAttachments(); state.draft = { id: DRAFT_ID, title: "新对话", updated: Date.now() }; state.convId = null; state.title = "新对话"; diff --git a/packages/chat/chat/epub-reader.js b/packages/chat/chat/epub-reader.js new file mode 100644 index 0000000..49de9db --- /dev/null +++ b/packages/chat/chat/epub-reader.js @@ -0,0 +1,267 @@ +(() => { + "use strict"; + const MiB = 1024 * 1024, fileLimit = 8 * MiB, extractLimit = 24 * MiB, textLimit = 2 * MiB; + const damaged = "EPUB 文件损坏或目录不完整。"; + const tooLarge = "EPUB 正文太大,请分卷后添加。"; + const encrypted = "EPUB 正文已加密,无法读取。"; + const fail = message => { throw new Error(message); }; + const utf8 = new TextDecoder("utf-8", { fatal: true }); + + function isEpub(file) { + return !!file && (/\.epub$/i.test(file.name || "") || + [file.type, file.mime].some(type => /^application\/epub\+zip(?:\s*;|$)/i.test(type || ""))); + } + + function fileBytes(url) { + if (typeof url !== "string") fail(damaged); + const comma = url.indexOf(","); + if (comma < 0 || !/^data:[^,]*;base64$/i.test(url.slice(0, comma))) fail(damaged); + if (url.length - comma - 1 > 4 * Math.ceil(fileLimit / 3)) fail("EPUB 文件超过 8 MiB,请分卷后添加。"); + let binary; + try { binary = atob(url.slice(comma + 1)); } catch { fail(damaged); } + if (binary.length > fileLimit) fail("EPUB 文件超过 8 MiB,请分卷后添加。"); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < bytes.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; + } + + const crcTable = Uint32Array.from({ length: 256 }, (_, n) => { + for (let i = 0; i < 8; i++) n = n & 1 ? 0xedb88320 ^ (n >>> 1) : n >>> 1; + return n; + }); + function checksum(bytes) { + let crc = -1; + for (const byte of bytes) crc = (crc >>> 8) ^ crcTable[(crc ^ byte) & 255]; + return (crc ^ -1) >>> 0; + } + + async function inflate(packed, size) { + let inflater; + try { inflater = new DecompressionStream("deflate-raw"); } + catch { fail("当前浏览器无法解压 EPUB,请更新后再试。"); } + let pos = 0; + const input = new ReadableStream({ pull(controller) { + if (pos === packed.length) return controller.close(); + const next = Math.min(pos + 4096, packed.length); + controller.enqueue(packed.subarray(pos, next)); + pos = next; + } }); + const reader = input.pipeThrough(inflater).getReader(); + const bytes = new Uint8Array(size); + let written = 0; + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + if (value.length > size - written) { + await reader.cancel(); + fail(damaged); + } + bytes.set(value, written); + written += value.length; + } + } catch { fail(damaged); } + if (written !== size) fail(damaged); + return bytes; + } + + function openZip(bytes) { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const u16 = p => view.getUint16(p, true), u32 = p => view.getUint32(p, true); + let end = bytes.length - 22; + for (; end >= Math.max(0, bytes.length - 65557); end--) { + if (u32(end) === 0x06054b50 && end + 22 + u16(end + 20) === bytes.length) break; + } + if (end < Math.max(0, bytes.length - 65557)) fail(damaged); + const count = u16(end + 10), start = u32(end + 16); + if (u16(end + 4) || u16(end + 6) || u16(end + 8) !== count || + count > 10000 || start + u32(end + 12) !== end) fail(damaged); + const names = new Map(); + let pos = start, extracted = 0; + function nameAt(offset, length) { + try { return utf8.decode(bytes.subarray(offset, offset + length)); } catch { fail(damaged); } + } + for (let i = 0; i < count; i++) { + if (pos + 46 > end || u32(pos) !== 0x02014b50 || u16(pos + 34)) fail(damaged); + const length = u16(pos + 28); + const next = pos + 46 + length + u16(pos + 30) + u16(pos + 32); + if (next > end) fail(damaged); + const name = nameAt(pos + 46, length); + if (!name || names.has(name)) fail(damaged); + names.set(name, pos); + pos = next; + } + if (pos !== end) fail(damaged); + return { + has: name => names.has(name), + async read(name, maxSize) { + const c = names.get(name); + if (c === undefined) fail(damaged); + const flags = u16(c + 8), method = u16(c + 10), packed = u32(c + 20), size = u32(c + 24); + if (flags & 0x41) fail(encrypted); + if (size > maxSize || size > extractLimit - extracted) fail(tooLarge); + extracted += size; + const local = u32(c + 42); + if (local + 30 > start || u32(local) !== 0x04034b50 || u16(local + 6) !== flags || + u16(local + 8) !== method) fail(damaged); + const length = u16(local + 26), data = local + 30 + length + u16(local + 28); + if (data + packed > start || nameAt(local + 30, length) !== name) fail(damaged); + let raw = bytes.subarray(data, data + packed); + if (method === 8) raw = await inflate(raw, size); + else if (method !== 0) fail("这种 EPUB 压缩格式暂不支持。"); + if (raw.length !== size || checksum(raw) !== u32(c + 16)) fail(damaged); + let encoding = "utf-8"; + if ((raw[0] === 255 && raw[1] === 254) || (raw[0] === 60 && raw[1] === 0)) encoding = "utf-16le"; + if ((raw[0] === 254 && raw[1] === 255) || (raw[0] === 0 && raw[1] === 60)) encoding = "utf-16be"; + try { return new TextDecoder(encoding, { fatal: true }).decode(raw); } catch { fail(damaged); } + } + }; + } + + // References are paths within the ZIP. Decode each segment after separating URL fragments. + function pathFor(baseFile, href) { + if (!href || /^(?:[a-z][\w+.-]*:|\/)/i.test(href)) fail(damaged); + const parts = baseFile.split("/"); + parts.pop(); + for (const segment of href.split(/[?#]/, 1)[0].split("/")) { + let name; + try { name = decodeURIComponent(segment); } catch { fail(damaged); } + if (/[\/\\\0]/.test(name)) fail(damaged); + if (name === "..") { + if (!parts.length) fail(damaged); + parts.pop(); + } else if (name && name !== ".") parts.push(name); + } + return parts.join("/"); + } + + // Older XHTML books use named HTML entities from a DTD. Decode them locally, as numeric + // XML references; CDATA, comments and processing instructions must retain their literal text. + function expandHtmlEntities(source) { + const template = document.createElement("template"), cache = new Map(); + return source.replace(/|$)||$)|<\?[\s\S]*?(?:\?>|$)|&([a-z][a-z0-9]{0,31});/gi, (token, name) => { + if (!name) return token; + if (!cache.has(token)) { + template.innerHTML = ''; + const value = template.content.firstChild.getAttribute("data-value"); + if (value === token) fail(damaged); + cache.set(token, Array.from(value, c => "" + c.codePointAt(0) + ";").join("")); + } + return cache.get(token); + }); + } + + function xml(source, chapter = false) { + // External declarations are unnecessary for reading text; never resolve entities from the book. + if (/"'\[]|"[^"]*"|'[^']*')*>/i.exec(source.slice(start)); + if (!decl) fail(damaged); + source = source.slice(0, start) + source.slice(start + decl[0].length); + if (/ Array.from(root.getElementsByTagNameNS("*", name)); + const blocks = new Set("address article aside blockquote br caption dd div dl dt figcaption figure footer h1 h2 h3 h4 h5 h6 header hr li main nav ol p pre section table td th tr ul".split(" ")); + const ignored = new Set("head title script style noscript template iframe object".split(" ")); + + function chapterText(source, type) { + let body; + if (type === "text/html") { + // The template's owner document has no browsing context, so image and frame URLs stay inert. + const html = document.createElement("template").content.ownerDocument.createElement("html"); + html.innerHTML = source; + body = html.querySelector("body"); + } else { + body = elements(xml(source, true), "body")[0]; + } + if (!body) fail(damaged); + const lines = []; + let pieces = []; + function flush() { + if (!pieces.length) return; + const line = pieces.join("").replace(/\p{White_Space}+/gu, " ").replace(/^ | $/g, ""); + if (line) lines.push(line); + pieces = []; + } + for (let node = body.firstChild; node;) { + const tag = node.nodeType === 1 ? node.localName.toLowerCase() : ""; + if (node.nodeType === 3 || node.nodeType === 4) pieces.push(node.nodeValue); + if (blocks.has(tag)) flush(); + if (!ignored.has(tag) && node.firstChild) { + node = node.firstChild; + continue; + } + while (node !== body) { + if (node.nodeType === 1 && blocks.has(node.localName.toLowerCase())) flush(); + if (node.nextSibling) break; + node = node.parentNode; + } + node = node === body ? null : node.nextSibling; + } + flush(); + const text = lines.join("\n\n"); + const imageOnly = !text && !!body.querySelector("img, picture, svg, image, canvas, object[type^='image/']"); + return { text, imageOnly }; + } + + async function read(dataUrl) { + const archive = openZip(fileBytes(dataUrl)); + const locked = new Set(); + const encryption = "META-INF/encryption.xml"; + if (archive.has(encryption)) { + const doc = xml(await archive.read(encryption, MiB)); + for (const el of elements(doc, "CipherReference")) locked.add(pathFor("", el.getAttribute("URI"))); + } + function readFile(name, maxSize) { + if (locked.has(name)) fail(encrypted); + return archive.read(name, maxSize); + } + const container = xml(await readFile("META-INF/container.xml", MiB)); + const roots = elements(container, "rootfile"); + const root = roots.find(el => el.getAttribute("media-type") === "application/oebps-package+xml") || roots[0]; + const opfPath = pathFor("", root?.getAttribute("full-path")); + const opf = xml(await readFile(opfPath, MiB)); + const manifest = elements(opf, "manifest")[0], spine = elements(opf, "spine")[0]; + if (!manifest || !spine) fail(damaged); + const items = new Map(); + for (const item of elements(manifest, "item")) { + const id = item.getAttribute("id"); + if (!id || items.has(id)) fail(damaged); + items.set(id, item); + } + const chapters = [], seenPaths = new Set(); + let length = 0, imagePages = 0; + for (const ref of elements(spine, "itemref")) { + const item = items.get(ref.getAttribute("idref")); + if (!item) fail(damaged); + const name = pathFor(opfPath, item.getAttribute("href")); + if (seenPaths.has(name)) continue; + seenPaths.add(name); + const type = item.getAttribute("media-type"); + if (type !== "application/xhtml+xml" && type !== "text/html") fail("EPUB 含有暂不支持的章节格式。"); + const { text, imageOnly } = chapterText(await readFile(name, 8 * MiB), type); + if (imageOnly) imagePages++; + if (!text) continue; + length += text.length + (chapters.length ? 2 : 0); + if (length > textLimit) fail(tooLarge); + chapters.push(text); + } + if (!chapters.length) fail("EPUB 中没有可读取的文字,可能是扫描版。"); + const text = chapters.join("\n\n"); + let characters = 0; + for (const char of text) if (!/\p{White_Space}/u.test(char)) characters++; + return { text, characters, imagePages }; + } + + globalThis.MagpieEpub = { isEpub, read }; +})(); diff --git a/packages/chat/chat/index.html b/packages/chat/chat/index.html index a1d01f6..4166626 100644 --- a/packages/chat/chat/index.html +++ b/packages/chat/chat/index.html @@ -169,6 +169,7 @@