diff --git a/locales/en.json b/locales/en.json index 86da7a3..53d8e94 100644 --- a/locales/en.json +++ b/locales/en.json @@ -52,7 +52,10 @@ "import-pdf-only": "Only PDF files can create paper pages.", "import-failed": "Some files could not be imported.", "attachment-missing": "The attachment was not found.", - "attachment-owned": "An attachment can belong to only one file attribute on one page.", + "attachment-image-required": "The file must be an image.", + "attachment-image-decode": "The image could not be decoded.", + "attachment-transfer-ended": "The file transfer has ended.", + "attachment-save-directory": "Choose a location outside the workspace attachments folder.", "annotation-owned": "An annotation can belong to only one paper.", "annotation-unavailable": "The annotation page is unavailable.", "page-body-forbidden": "This type of page cannot have a body.", @@ -153,6 +156,7 @@ "block-invalid-identity": "The block identity, type or child UUIDs are invalid.", "block-invalid-version": "The block content format version is invalid.", "block-invalid-language": "Only code blocks can specify a supported code language.", + "block-invalid-media": "The media block contains invalid file or display information.", "block-invalid-collapse": "The collapsed state is invalid.", "block-invalid-inline": "The rich text node is invalid.", "block-empty-text": "A text node cannot be empty.", @@ -348,6 +352,8 @@ "chooseDate": "Choose date property" }, "dialog": { + "imageFilter": "Images", + "videoFilter": "Video and audio", "close": "Close", "cancel": "Cancel", "confirm": "Confirm changes", @@ -469,6 +475,16 @@ "perl": "Perl" }, "editor": { + "pasteLink": "Paste link", + "embedImage": "Embed as image", + "imageViewer": "Image viewer", + "imageCount": "{{current}} / {{total}}", + "previousImage": "Previous image", + "nextImage": "Next image", + "mediaTransfer": "Importing files ({{current}} / {{total}})", + "addCaption": "Add caption", + "missingFile": "File missing", + "resizeMedia": "Resize media", "language": "Code language", "copyCode": "Copy code", "insertBlock": "Insert block", @@ -732,7 +748,10 @@ "code": "Code", "table": "Table", "hr": "Divider", - "blocked_reference": "Linked reference" + "blocked_reference": "Linked reference", + "image": "Image", + "video": "Video", + "file": "File" }, "color": { "default": "Default", diff --git a/locales/zh-CN.json b/locales/zh-CN.json index 0bd1d5a..423c05f 100644 --- a/locales/zh-CN.json +++ b/locales/zh-CN.json @@ -52,7 +52,10 @@ "import-pdf-only": "只能用 PDF 文件新建文献。", "import-failed": "部分文件导入失败。", "attachment-missing": "附件不存在。", - "attachment-owned": "附件只能属于一个页面的一个文件属性。", + "attachment-image-required": "文件必须是图片。", + "attachment-image-decode": "无法解码图片。", + "attachment-transfer-ended": "文件传输已结束。", + "attachment-save-directory": "请选择工作区附件目录之外的位置。", "annotation-owned": "批注只能属于一篇文献。", "annotation-unavailable": "批注页面不可用。", "page-body-forbidden": "这种页面不能有正文。", @@ -153,6 +156,7 @@ "block-invalid-identity": "块的身份、类型或子块 UUID 无效。", "block-invalid-version": "块内容的格式版本无效。", "block-invalid-language": "只有代码块可以指定语言,且必须使用支持的代码语言。", + "block-invalid-media": "多媒体块的文件或显示数据无效。", "block-invalid-collapse": "折叠状态无效。", "block-invalid-inline": "富文本节点无效。", "block-empty-text": "文本节点不能为空。", @@ -348,6 +352,8 @@ "chooseDate": "选择日期属性" }, "dialog": { + "imageFilter": "图片", + "videoFilter": "视频和音频", "close": "关闭", "cancel": "取消", "confirm": "确认更改", @@ -469,6 +475,16 @@ "perl": "Perl" }, "editor": { + "pasteLink": "粘贴链接", + "embedImage": "嵌入为图片", + "imageViewer": "图片查看器", + "imageCount": "{{current}} / {{total}}", + "previousImage": "上一张图片", + "nextImage": "下一张图片", + "mediaTransfer": "正在导入文件({{current}} / {{total}})", + "addCaption": "添加说明", + "missingFile": "文件缺失", + "resizeMedia": "调整媒体宽度", "language": "代码语言", "copyCode": "复制代码", "insertBlock": "插入块", @@ -732,7 +748,10 @@ "code": "代码", "table": "表格", "hr": "分隔线", - "blocked_reference": "链接引用" + "blocked_reference": "链接引用", + "image": "图片", + "video": "视频", + "file": "文件" }, "color": { "default": "默认", diff --git a/main/attachments/download.ts b/main/attachments/download.ts index 3e95fcb..2d2aa11 100644 --- a/main/attachments/download.ts +++ b/main/attachments/download.ts @@ -6,13 +6,13 @@ import { LabloomError, diagnostic } from "../../shared/failure"; import { httpURL } from "../../shared/utils/url"; import * as metadata from "./metadata"; -export type DownloadOptions = { expectedType?: string; timeoutMs?: number }; +export type DownloadOptions = { expectedType?: string; timeoutMs?: number; signal?: AbortSignal; progress?: (bytes: number, total?: number) => void }; type Request = DownloadOptions & { directory: string; fetcher: typeof fetch; signal: AbortSignal }; export const pdfHeader = Buffer.from("%PDF-"); const active = new Set(); -// Only staging files left by interrupted downloads are candidates. A previous session may still be closing its handle. +// Only managed staging files are candidates. A previous session may still be closing its handle. export function discardInterrupted(directory: string): void { for (const entry of readdirSync(directory, { withFileTypes: true })) { if (!entry.isFile() || !/^\.download-[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}\.part$/.test(entry.name)) continue; @@ -21,11 +21,19 @@ export function discardInterrupted(directory: string): void { } } -async function stage(directory: string, chunks: AsyncIterable, publish: (path: string) => T): Promise { +export async function stageFile(directory: string, chunks: AsyncIterable): Promise<{ path: string; discard: () => Promise }> { // The temporary file and its final name are on the same volume. const path = join(directory, ".download-" + randomUUID() + ".part"); active.add(path); let owned = false; + const discard = async (): Promise => { + try { + if (owned) await rm(path, { force: true }); + } + finally { + active.delete(path); + } + }; try { const file = await open(path, "wx"); owned = true; @@ -35,15 +43,21 @@ async function stage(directory: string, chunks: AsyncIterable, pu finally { await file.close(); } - return publish(path); + return { path, discard }; + } + catch (error) { + await discard(); + throw error; + } +} + +export async function stage(directory: string, chunks: AsyncIterable, publish: (path: string) => T): Promise { + const file = await stageFile(directory, chunks); + try { + return publish(file.path); } finally { - try { - if (owned) await rm(path, { force: true }); - } - finally { - active.delete(path); - } + await file.discard(); } } @@ -55,6 +69,7 @@ export async function receive(url: string, request: Request, save: (path: str idle = setTimeout(() => controller.abort(new LabloomError({ kind: "download-timeout" })), request.timeoutMs ?? 30_000); }; let reader: ReadableStreamDefaultReader | undefined; + let total: number | undefined; const cancel = (): void => { void reader?.cancel(signal.reason).catch(() => {}); }; @@ -64,7 +79,7 @@ export async function receive(url: string, request: Request, save: (path: str } async function* chunks(): AsyncGenerator { - let checked = 0; + let checked = 0, bytes = 0; startWaiting(); while (reader) { const { done, value } = await reader.read().catch(networkFailure); @@ -78,6 +93,8 @@ export async function receive(url: string, request: Request, save: (path: str checked += prefix.length; } yield value; + bytes += value.byteLength; + request.progress?.(bytes, total); startWaiting(); } clearTimeout(idle); @@ -94,8 +111,12 @@ export async function receive(url: string, request: Request, save: (path: str signal.throwIfAborted(); if (!response.ok) throw new LabloomError({ kind: "download-http", status: response.status }); const info = metadata.fromResponse(response, address); + const length = response.headers.get("content-length"); + if (length !== null && /^\d+$/.test(length) && Number.isSafeInteger(Number(length))) total = Number(length); + request.progress?.(0, total); if (expected === "application/pdf") info.mediaType = expected; // Verified from the bytes, including on extensionless URLs. - else if (expected && expected !== info.mediaType) throw new LabloomError({ kind: "download-type-mismatch", expected, actual: info.mediaType }); + else if (expected && (expected.endsWith("/*") ? !info.mediaType.startsWith(expected.slice(0, -1)) : expected !== info.mediaType)) + throw new LabloomError({ kind: "download-type-mismatch", expected, actual: info.mediaType }); return await stage(request.directory, chunks(), path => { signal.throwIfAborted(); return save(path, info); diff --git a/main/attachments/ipc.ts b/main/attachments/ipc.ts new file mode 100644 index 0000000..ce81bd0 --- /dev/null +++ b/main/attachments/ipc.ts @@ -0,0 +1,115 @@ +import { dialog, type BrowserWindow } from "electron"; +import { TransformStream, type WritableStreamDefaultWriter } from "node:stream/web"; +import typia from "typia"; +import { attachmentProgress, attachmentsChannels, type AttachmentsAPI } from "../../shared/attachments/ipc"; +import { validUUID } from "../../shared/attrs/values"; +import type { MediaFile } from "../../shared/content/media"; +import { LabloomError } from "../../shared/failure"; +import { invalid, register, route, type Routes } from "../ipc"; +import { t } from "../ui/i18n"; +import { selectPDF } from "../ui/fileDialogs"; +import * as workspace from "../workspace-state"; +import { extensionsFor } from "./metadata"; +import * as service from "./service"; + +export function registerAttachmentIPCs(window: BrowserWindow): void { + type Args = Parameters; + type Upload = { writer: WritableStreamDefaultWriter; result: Promise }; + const tasks = new Map(); + function start(id: string): AbortController { + if (!validUUID(id) || tasks.has(id)) throw new LabloomError({ kind: "invalid-argument" }); + const cancel = new AbortController(); + tasks.set(id, { cancel }); + return cancel; + } + function cancelTransfer(id: string): void { + const task = tasks.get(id); + task?.cancel.abort(new LabloomError({ kind: "attachment-transfer-ended" })); + if (task?.upload) tasks.delete(id); + } + window.webContents.once("destroyed", () => { + for (const id of tasks.keys()) cancelTransfer(id); + }); + function progress(id: string): (bytes: number, total?: number) => void { + let last = -Infinity; + return (bytes, total) => { + const now = performance.now(); + if (now - last < 80 && bytes !== total || window.isDestroyed()) return; + last = now; + window.webContents.send(attachmentProgress, { id, bytes, total }); + }; + } + function upload(id: string): Upload { + const entry = tasks.get(id)?.upload; + if (!entry) throw new LabloomError({ kind: "attachment-transfer-ended" }); + return entry; + } + const routes: Routes = { + available: route(typia.createAssert>(invalid), service.available), + saveAs: route(typia.createAssert>(invalid), id => service.saveAs(id, async name => { + const result = await dialog.showSaveDialog(window, { defaultPath: name }); + return result.canceled ? undefined : result.filePath; + })), + choose: route(typia.createAssert>(invalid), async (...[kind, multiple = true]) => { + if (kind === "pdf") return selectPDF(window); + const result = await dialog.showOpenDialog(window, { properties: multiple ? ["openFile", "multiSelections"] : ["openFile"], + ...(kind === "file" ? {} : { filters: [{ name: t(kind === "image" ? "dialog.imageFilter" : "dialog.videoFilter"), extensions: extensionsFor(kind) }] }) }); + return result.canceled ? [] : result.filePaths; + }), + stagePaths: route(typia.createAssert>(invalid), service.stagePaths), + importPath: route(typia.createAssert>(invalid), async (...[id, path, source]) => { + const cancel = start(id); + try { + return await service.importPath(path, { source, signal: cancel.signal, progress: progress(id) }); + } + finally { + tasks.delete(id); + } + }), + downloadImage: route(typia.createAssert>(invalid), async (id, url) => { + const cancel = start(id); + try { + const file = await service.downloadFile(url, { expectedType: "image/*", signal: cancel.signal, progress: progress(id) }); + if (!file) throw new LabloomError({ kind: "attachment-transfer-ended" }); + return file; + } + finally { + tasks.delete(id); + } + }), + uploadStart: route(typia.createAssert>(invalid), (id, name, type) => { + const session = workspace.requireWorkspace(), cancel = start(id); + const signal = AbortSignal.any([session.controller.signal, cancel.signal]); + const { readable, writable } = new TransformStream(); + const writer = writable.getWriter(); + const abort = (): void => { + void writer.abort(signal.reason).catch(() => {}); + tasks.delete(id); + }; + try { + const result = service.importImage(name, type, readable, signal); + tasks.set(id, { cancel, upload: { writer, result } }); + signal.addEventListener("abort", abort, { once: true }); + void result.catch(error => writer.abort(error).catch(() => {})).finally(() => signal.removeEventListener("abort", abort)); + } + catch (error) { + tasks.delete(id); + throw error; + } + }), + uploadChunk: route(typia.createAssert>(invalid), (id, bytes) => upload(id).writer.write(bytes)), + uploadFinish: route(typia.createAssert>(invalid), async id => { + const { writer, result } = upload(id); + try { + await writer.close().catch(() => {}); + return await result; + } + finally { + tasks.delete(id); + } + }), + cancelTransfer: route(typia.createAssert>(invalid), cancelTransfer), + releaseHandoffs: route(typia.createAssert>(invalid), service.releaseHandoffs) + }; + register(window.webContents, attachmentsChannels, routes); +} \ No newline at end of file diff --git a/main/attachments/metadata.ts b/main/attachments/metadata.ts index ace2a08..0ece83a 100644 --- a/main/attachments/metadata.ts +++ b/main/attachments/metadata.ts @@ -1,6 +1,8 @@ import { extname } from "node:path"; import { MIMEType } from "node:util"; import { type Attachment } from "../../shared/types/papers"; +import { imageTypes } from "../../shared/content/media"; +import type { MediaKind } from "../../shared/types/content"; export type Metadata = Pick; export const binary = "application/octet-stream"; @@ -12,10 +14,17 @@ const mediaTypes: Record = { ppt: "application/vnd.ms-powerpoint", pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation", odt: "application/vnd.oasis.opendocument.text", rtf: "application/rtf", epub: "application/epub+zip", zip: "application/zip", gz: "application/gzip", tar: "application/x-tar", "7z": "application/x-7z-compressed", rar: "application/vnd.rar", - png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", svg: "image/svg+xml", tif: "image/tiff", tiff: "image/tiff", bmp: "image/bmp", - mp3: "audio/mpeg", wav: "audio/wav", ogg: "audio/ogg", mp4: "video/mp4", webm: "video/webm", mov: "video/quicktime" + ...imageTypes, + mp3: "audio/mpeg", wav: "audio/wav", ogg: "audio/ogg", oga: "audio/ogg", opus: "audio/ogg", + m4a: "audio/mp4", flac: "audio/flac", aac: "audio/aac", aiff: "audio/aiff", wma: "audio/x-ms-wma", + mp4: "video/mp4", m4v: "video/mp4", webm: "video/webm", mov: "video/quicktime", ogv: "video/ogg", + avi: "video/x-msvideo", mkv: "video/x-matroska", mpg: "video/mpeg", mpeg: "video/mpeg", wmv: "video/x-ms-wmv", hevc: "video/hevc" }; +export function extensionsFor(kind: Exclude): string[] { + return Object.keys(mediaTypes).filter(key => mediaTypes[key].startsWith(kind + "/") || kind === "video" && mediaTypes[key].startsWith("audio/")); +} + export function typeFor(name: string): string | undefined { const extension = extname(name).slice(1).toLowerCase(); return Object.hasOwn(mediaTypes, extension) ? mediaTypes[extension] : undefined; @@ -27,7 +36,7 @@ export function suffixFor(type: string): string { } // A response filename is display metadata. Keep only a usable final path component. -function safeName(name: string): string { +export function safeName(name: string): string { return (name.split(/[\\/]/).pop() ?? "").replace(/[\p{Cc}<>:"|?*]/gu, "_").trim().replace(/[. ]+$/, ""); } diff --git a/main/attachments/protocol.ts b/main/attachments/protocol.ts new file mode 100644 index 0000000..8b5be88 --- /dev/null +++ b/main/attachments/protocol.ts @@ -0,0 +1,8 @@ +import { app, protocol } from "electron"; +import { attachmentScheme } from "../../shared/content/media"; +import { readAttachment } from "./read"; + +export function registerAttachmentProtocol(): void { + protocol.registerSchemesAsPrivileged([{ scheme: attachmentScheme, privileges: { standard: true, secure: true, stream: true } }]); + void app.whenReady().then(() => protocol.handle(attachmentScheme, readAttachment)); +} \ No newline at end of file diff --git a/main/attachments/read.ts b/main/attachments/read.ts new file mode 100644 index 0000000..7f34c37 --- /dev/null +++ b/main/attachments/read.ts @@ -0,0 +1,61 @@ +import { lstat, open } from "node:fs/promises"; +import { Readable } from "node:stream"; +import { validUUID } from "../../shared/attrs/values"; +import { attachmentOrigin } from "../../shared/content/media"; +import { attachmentPath } from "../storage/files"; +import * as workspace from "../workspace-state"; +import { storedAttachment } from "./service"; + +function byteRange(header: string, size: number): { start: number; end: number } | null { + const match = /^bytes=(\d*)-(\d*)$/i.exec(header); + if (!match || !size || !match[1] && !match[2]) return null; + const start = match[1] ? Number(match[1]) : Math.max(0, size - Number(match[2])); + const end = match[1] && match[2] ? Math.min(size - 1, Number(match[2])) : size - 1; + return start <= end ? { start, end } : null; +} + +export async function readAttachment(request: Request): Promise { + const missing = (): Response => new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } }); + if (request.method !== "GET" && request.method !== "HEAD") return new Response(null, { status: 405, headers: { Allow: "GET, HEAD" } }); + const prefix = attachmentOrigin + "/", id = request.url.slice(prefix.length); + if (!request.url.startsWith(prefix) || !validUUID(id) || !workspace.ready()) return missing(); + const session = workspace.requireWorkspace(), row = storedAttachment(id); + if (!row) return missing(); + const signal = AbortSignal.any([session.controller.signal, request.signal]); + try { + const path = attachmentPath(session.info.path, row.storedName); + const stat = await lstat(path); + if (!stat.isFile() || stat.size !== row.size || signal.aborted) return missing(); + const headers = new Headers({ + "Accept-Ranges": "bytes", + "Cache-Control": "no-store", + "Content-Security-Policy": "default-src 'none'; sandbox", + "Content-Type": row.mediaType, + "X-Content-Type-Options": "nosniff" + }); + if (!/^(?:image|video|audio)\//.test(row.mediaType)) headers.set("Content-Disposition", "attachment"); + const range = request.method === "GET" && request.headers.get("range"); + const bounds = range ? byteRange(range, stat.size) : { start: 0, end: stat.size - 1 }; + if (!bounds) { + headers.set("Content-Range", "bytes */" + stat.size); + return new Response(null, { status: 416, headers }); + } + const { start, end } = bounds; + headers.set("Content-Length", String(end - start + 1)); + if (range) headers.set("Content-Range", `bytes ${start}-${end}/${stat.size}`); + const status = range ? 206 : 200; + if (request.method === "HEAD" || !stat.size) return new Response(null, { status, headers }); + const file = await open(path, "r"); + if (signal.aborted) { + await file.close(); + return missing(); + } + // Count queued chunks explicitly. The filesystem high-water mark is measured in bytes. + const stream = file.createReadStream({ start, end, signal }); + const body = Readable.toWeb(stream, { strategy: { highWaterMark: 1 } }) as ReadableStream; + return new Response(body, { status, headers }); + } + catch { + return missing(); + } +} \ No newline at end of file diff --git a/main/attachments/service.ts b/main/attachments/service.ts index 348f8fe..59619c3 100644 --- a/main/attachments/service.ts +++ b/main/attachments/service.ts @@ -1,9 +1,14 @@ import { randomUUID } from "node:crypto"; -import { closeSync, constants, copyFileSync, existsSync, mkdirSync, openSync, readSync, renameSync, statSync, unlinkSync } from "node:fs"; -import { basename, extname, join } from "node:path"; -import { LabloomError } from "../../shared/failure"; -import { type Attachment } from "../../shared/types/papers"; +import { createReadStream, createWriteStream, existsSync, renameSync, statSync, unlinkSync } from "node:fs"; +import { lstat, open, realpath, rename, rm, stat } from "node:fs/promises"; +import { basename, dirname, extname, isAbsolute, join, relative, sep } from "node:path"; +import { pipeline } from "node:stream/promises"; +import { validUUID } from "../../shared/attrs/values"; +import type { AttachmentBatch } from "../../shared/attachments/ipc"; +import type { MediaFile } from "../../shared/content/media"; +import { LabloomError, toFailureInfo } from "../../shared/failure"; import * as events from "../knowledge/events"; +import { statement } from "../knowledge/records"; import { type WorkspaceDatabase } from "../storage/database"; import { attachmentPath } from "../storage/files"; import { attachments } from "../storage/tables"; @@ -12,22 +17,53 @@ import * as transfer from "./download"; import * as metadata from "./metadata"; type StoredAttachment = typeof attachments.$inferSelect; -type Store = (info: metadata.Metadata, place: (target: string) => void, validate?: (target: string) => void) => Attachment; +export function storedAttachment(id: string): StoredAttachment | undefined { + return statement(`SELECT id, stored_name AS storedName, original_name AS originalName, media_type AS mediaType, size + FROM attachments WHERE id=?`).get(id) as StoredAttachment | undefined; +} + +export async function available(id: string): Promise { + if (!workspace.ready() || !validUUID(id)) return false; + const session = workspace.requireWorkspace(), file = storedAttachment(id); + if (!file) return false; + const stat = await lstat(attachmentPath(session.info.path, file.storedName)).catch(() => null); + return workspace.isCurrent(session) && !!stat?.isFile() && stat.size === file.size; +} + +export async function saveAs(id: string, select: (name: string) => Promise): Promise { + const session = workspace.requireWorkspace(), file = validUUID(id) && storedAttachment(id); + if (!file || !await available(id)) throw new LabloomError({ kind: "attachment-missing" }); + if (!workspace.isCurrent(session)) return; + const destination = await select(file.originalName); + if (!destination || !workspace.isCurrent(session)) return; + const mediaDirectory = await realpath(join(session.info.path, "attachments")); + const directory = await realpath(dirname(destination)), within = relative(mediaDirectory, directory); + if (!within || !isAbsolute(within) && within !== ".." && !within.startsWith(".." + sep)) throw new LabloomError({ kind: "attachment-save-directory" }); + const temporary = join(directory, ".labloom-save-" + randomUUID() + ".part"); + const signal = session.controller.signal; + try { + await pipeline(createReadStream(attachmentPath(session.info.path, file.storedName)), createWriteStream(temporary, { flags: "wx" }), { signal }); + signal.throwIfAborted(); + await rename(temporary, destination); + } + finally { + await rm(temporary, { force: true }); + } +} +type Store = (info: metadata.Metadata, path: string) => MediaFile; function storing(action: (store: Store) => T): T { const created: string[] = [], db = workspace.database(); try { - return action((info, place, validate) => { + return action((info, path) => { const id = randomUUID(), storedName = id + (extname(info.originalName) || metadata.suffixFor(info.mediaType)); const target = attachmentPath(workspace.root(), storedName); - mkdirSync(join(workspace.root(), "attachments"), { recursive: true }); - place(target); + renameSync(path, target); try { - validate?.(target); const file = { id, ...info, size: statSync(target).size }; db.insert(attachments).values({ ...file, storedName }).run(); created.push(target); - return file; + return { ...file, path: target }; } catch (error) { unlinkSync(target); @@ -41,28 +77,7 @@ function storing(action: (store: Store) => T): T { } } -// Local imports accept the PDF signature within the first 1024 bytes, as before. -export function checkLocalPDF(path: string): void { - const fd = openSync(path, "r"); - try { - const header = Buffer.alloc(1024); - const length = readSync(fd, header, 0, header.length, 0); - if (!header.subarray(0, length).includes(transfer.pdfHeader)) throw new LabloomError({ kind: "pdf-invalid" }); - } - finally { - closeSync(fd); - } -} - -export function importing(action: (store: (path: string) => Attachment) => T): T { - return storing(store => action(path => { - const originalName = basename(path), mediaType = metadata.typeFor(originalName) ?? metadata.binary; - return store({ originalName, mediaType }, target => copyFileSync(path, target, constants.COPYFILE_EXCL), - mediaType === "application/pdf" ? checkLocalPDF : undefined); - })); -} - -// Downloaded files have no page owner until a renderer commits its edit. +// Stored files wait here until a renderer commits a reference. const handedOut = new Set(); let stopWatching: (() => void) | undefined; export function release(): void { @@ -75,17 +90,21 @@ export function recoverDownloads(): void { transfer.discardInterrupted(join(workspace.root(), "attachments")); } -export async function download(url: string, options: transfer.DownloadOptions = {}): Promise { +function publish(path: string, info: metadata.Metadata, session: workspace.WorkspaceState, signal: AbortSignal): MediaFile { + signal.throwIfAborted(); + const file = storing(store => store(info, path)); + protect(file.id, session.db); + return file; +} + +export async function downloadFile(url: string, options: transfer.DownloadOptions = {}): Promise { const session = workspace.requireWorkspace(); + const signal = options.signal ? AbortSignal.any([session.controller.signal, options.signal]) : session.controller.signal; try { - const id = await transfer.receive(url, { - ...options, directory: join(session.info.path, "attachments"), fetcher: session.fetchAttachment, signal: session.controller.signal - }, (path, info) => { - const file = storing(store => store(info, target => renameSync(path, target))); - protect(file.id, session.db); - return file.id; - }); - return workspace.isCurrent(session) ? id : null; + const file = await transfer.receive(url, { + ...options, directory: join(session.info.path, "attachments"), fetcher: session.fetchAttachment, signal + }, (path, info) => publish(path, info, session, signal)); + return workspace.isCurrent(session) ? file : null; } catch (error) { if (!workspace.isCurrent(session)) return null; @@ -93,26 +112,136 @@ export async function download(url: string, options: transfer.DownloadOptions = } } -// Watch committed property references only while a downloaded file is waiting for an owner. +export async function download(url: string, options?: transfer.DownloadOptions): Promise { + return (await downloadFile(url, options))?.id ?? null; +} + +type Progress = (bytes: number, total?: number) => void; +type SourceFile = Pick; + +// Local imports accept a PDF signature within the first 1024 bytes. +async function checkPDF(path: string): Promise { + const handle = await open(path, "r"); + try { + const header = Buffer.alloc(1024), { bytesRead } = await handle.read(header, 0, header.length, 0); + if (!header.subarray(0, bytesRead).includes(transfer.pdfHeader)) throw new LabloomError({ kind: "pdf-invalid" }); + } + finally { + await handle.close(); + } +} + +type PathOptions = { signal?: AbortSignal; progress?: Progress; source?: SourceFile; pdfOnly?: boolean }; +export async function importPath(path: string, options: PathOptions = {}): Promise { + const session = workspace.requireWorkspace(); + const signal = options.signal ? AbortSignal.any([session.controller.signal, options.signal]) : session.controller.signal; + const file = await preparePath(path, session.info.path, signal, options); + try { + return publish(file.path, file.info, session, signal); + } + finally { + await file.discard(); + } +} + +type StagedPath = { path: string; discard: () => Promise; info: metadata.Metadata }; +async function preparePath(path: string, root: string, signal: AbortSignal, { source, progress, pdfOnly }: PathOptions = {}): Promise { + if (!isAbsolute(path)) throw new LabloomError({ kind: "import-regular-file" }); + if (source) { + const directory = dirname(path), name = basename(path); + if (!validUUID(source.id) || basename(directory) !== "attachments" || ![source.id, source.id + extname(name)].includes(name)) + throw new LabloomError({ kind: "attachment-missing" }); + } + const originalName = source ? metadata.safeName(source.originalName) || basename(path) : basename(path); + const mediaType = source?.mediaType || metadata.typeFor(originalName) || metadata.binary; + const info = { originalName, mediaType }; + const size = await (source ? lstat(path) : stat(path)).then(entry => { + if (!entry.isFile()) throw new LabloomError({ kind: "import-regular-file" }); + return entry.size; + }); + if (pdfOnly && mediaType !== "application/pdf") throw new LabloomError({ kind: "import-pdf-only" }); + signal.throwIfAborted(); + progress?.(0, size); + async function* chunks(): AsyncGenerator { + let bytes = 0; + for await (const chunk of createReadStream(path, { signal, highWaterMark: 256 * 1024 })) { + yield chunk as Buffer; + bytes += chunk.length; + progress?.(bytes, size); + } + } + const file = await transfer.stageFile(join(root, "attachments"), chunks()); + if (mediaType === "application/pdf") { + try { + await checkPDF(file.path); + } + catch (error) { + await file.discard(); + throw error; + } + } + return { ...file, info }; +} + +export async function stagePaths(paths: string[], pdfOnly: boolean, atomic = false): Promise { + const session = workspace.requireWorkspace(), signal = session.controller.signal; + const pending: StagedPath[] = [], failures: AttachmentBatch["failures"] = []; + try { + for (const path of paths) { + signal.throwIfAborted(); + try { + pending.push(await preparePath(path, session.info.path, signal, { pdfOnly })); + } + catch (error) { + if (atomic || signal.aborted) throw error; + failures.push({ name: basename(path), error: toFailureInfo(error) }); + } + } + signal.throwIfAborted(); + const files = storing(store => session.database.transaction(() => pending.map(file => store(file.info, file.path)))()); + for (const file of files) protect(file.id, session.db); + return { files: files.map(({ path: _path, ...file }) => file), failures }; + } + finally { + await Promise.all(pending.map(file => file.discard())); + } +} + +export function importImage(name: string, mediaType: string, chunks: AsyncIterable, cancel: AbortSignal): Promise { + const session = workspace.requireWorkspace(), signal = AbortSignal.any([session.controller.signal, cancel]); + if (!/^image\/[a-z0-9.+-]+$/i.test(mediaType)) throw new LabloomError({ kind: "attachment-image-required" }); + const originalName = metadata.safeName(name) || "image" + metadata.suffixFor(mediaType); + return transfer.stage(join(session.info.path, "attachments"), chunks, target => publish(target, { originalName, mediaType }, session, signal)); +} + +export function releaseHandoffs(ids: string[]): void { + for (const id of ids) handedOut.delete(id); + if (!handedOut.size) release(); +} + +// Watch committed references while an imported file is waiting to be linked. function protect(id: string, db: WorkspaceDatabase): void { handedOut.add(id); if (stopWatching) return; - const references = db.$client.prepare(`SELECT DISTINCT target_id FROM link_refs WHERE source_kind='page' - AND source_id IN (SELECT value FROM json_each(?)) AND target_kind='file'`).pluck(); + const references = db.$client.prepare(`SELECT target_id FROM link_refs l JOIN json_each(?) j + ON l.source_kind=? AND l.source_id=j.value WHERE l.target_kind='file'`).pluck(); stopWatching = events.subscribe(event => { - if (event.type !== "knowledge" || !event.change.pages.length) return; - for (const file of references.all(JSON.stringify(event.change.pages)) as string[]) handedOut.delete(file); + if (event.type !== "knowledge") return; + for (const [kind, ids] of [["page", event.change.pages], ["block", event.change.blocks]] as const) { + if (ids.length) for (const file of references.all(JSON.stringify(ids), kind) as string[]) handedOut.delete(file); + } if (!handedOut.size) release(); }); } -/** Actual property values retain files, including properties on recycled pages. */ +/** Properties and retained blocks on both live and recycled pages can hold files. */ export function unreferencedFiles(db: WorkspaceDatabase): StoredAttachment[] { return db.$client.prepare(`SELECT a.id, a.stored_name AS storedName, a.original_name AS originalName, a.media_type AS mediaType, a.size FROM attachments a WHERE a.id NOT IN ( SELECT f.value FROM page_attrs p JOIN attrs_meta m ON m.id=p.attr_id JOIN json_each(CASE m.type WHEN 'file' THEN json_array(p.value) WHEN 'files' THEN p.value ELSE '[]' END) f - WHERE m.type IN ('file','files') AND f.value IS NOT NULL)`).all() as StoredAttachment[]; + WHERE m.type IN ('file','files') AND f.value IS NOT NULL) + AND NOT EXISTS (SELECT 1 FROM link_refs l WHERE l.target_kind='file' AND l.target_id=a.id AND l.source_kind='block')`).all() as StoredAttachment[]; } /** Collect irreversible garbage together; failed deletion restores rows and bytes. */ diff --git a/main/index.ts b/main/index.ts index 7505ce7..e528d4f 100644 --- a/main/index.ts +++ b/main/index.ts @@ -10,6 +10,7 @@ import * as lifecycle from "./lifecycle"; import * as windows from "./ui/window"; import * as reminders from "./ui/reminders"; import { openReminderPage } from "../shared/timers/ipc"; +import { registerAttachmentProtocol } from "./attachments/protocol"; // Set both paths before ready, so development also isolates Chromium state. const dataPath = app.isPackaged @@ -18,6 +19,7 @@ const dataPath = app.isPackaged app.setPath("userData", dataPath); if (!app.requestSingleInstanceLock()) app.exit(0); else { + registerAttachmentProtocol(); const sessionPath = join(dataPath, "chromium"); mkdirSync(sessionPath, { recursive: true }); app.setPath("sessionData", sessionPath); diff --git a/main/knowledge/attributes.ts b/main/knowledge/attributes.ts index f3cad62..9d83355 100644 --- a/main/knowledge/attributes.ts +++ b/main/knowledge/attributes.ts @@ -71,20 +71,12 @@ export function prepareValues(pageId: string, values: Record item.id)), incoming = new Set(); - for (const { id, definition, row } of values) { - const file = attributeTargetKind(definition.type) === "file" && id !== "annotation_file"; - if (!row || !file && id !== "paper_annotations") continue; - for (const target of attributeTargets(definition.type, decodeValue(definition, row.value))) { - const key = target.kind + ":" + target.id; - const owners = workspace.database().$client.prepare(`SELECT source_id AS pageId,source_field AS attrId FROM link_refs - WHERE source_kind='page' AND target_kind=? AND target_id=? AND ${file ? "source_field<>'annotation_file'" : "source_field='paper_annotations'"}`).all(target.kind, target.id) as { pageId: string; attrId: string }[]; - if (incoming.has(key) || owners.some(owner => owner.pageId !== pageId || !changed.has(owner.attrId))) { - throw new LabloomError({ kind: file ? "attachment-owned" : "annotation-owned" }); - } - if (!file && !workspace.database().$client.prepare("SELECT 1 FROM pages WHERE id=? AND kind='annotation'").get(target.id)) throw new LabloomError({ kind: "annotation-unavailable" }); - incoming.add(key); - } + const value = values.find(value => value.id === "paper_annotations"); + if (!value?.row) return; + for (const target of attributeTargets(value.definition.type, decodeValue(value.definition, value.row.value))) { + if (statement(`SELECT 1 FROM link_refs WHERE source_kind='page' AND source_field='paper_annotations' + AND target_kind=? AND target_id=? AND source_id<>? LIMIT 1`).get(target.kind, target.id, pageId)) throw new LabloomError({ kind: "annotation-owned" }); + if (!statement("SELECT 1 FROM pages WHERE id=? AND kind='annotation'").get(target.id)) throw new LabloomError({ kind: "annotation-unavailable" }); } } diff --git a/main/knowledge/changes.ts b/main/knowledge/changes.ts index bfb5ba6..4a2a187 100644 --- a/main/knowledge/changes.ts +++ b/main/knowledge/changes.ts @@ -114,6 +114,8 @@ export class EditChanges { putBlock(value: ContentBlock, stored?: BlockRow): BlockRow | null { validateBlock(value); + const fileId = value.payload.media?.fileId; + if (fileId && !data.statement("SELECT 1 FROM attachments WHERE id=?").get(fileId)) throw new LabloomError({ kind: "attachment-missing" }); if (value.children.length && data.owners(value.id).some(id => bodylessPageKinds.includes(data.header(id).kind))) throw new LabloomError({ kind: "page-body-forbidden" }); const id = "block:" + value.id; const before = data.blockRow(value.id); diff --git a/main/knowledge/commit.ts b/main/knowledge/commit.ts index 88eba06..6db2fcd 100644 --- a/main/knowledge/commit.ts +++ b/main/knowledge/commit.ts @@ -179,9 +179,9 @@ function changePreview(plan: EditChanges, { action, deletedBlocks = [], position direct: ids.filter(id => plan.direct.has(id)).map(name), causes: [...plan.causes], deletedBlocks }; } -export function finish(plan: EditChanges, pageId: string, batch: number, review?: Review): Extract { +export function finish(plan: EditChanges, pageId: string, batch: number, review?: Review, historyRows?: RowChanges): Extract { const context = current(); - const changed = context.persist(plan, pageId, undefined, review && (projected => { + const changed = context.persist(plan, pageId, historyRows, review && (projected => { const preview = changePreview(plan, review, projected); if (preview && contexts.at(-1)?.options.confirmation !== preview.token) throw new ConfirmationRollback(preview); })); diff --git a/main/knowledge/edits.ts b/main/knowledge/edits.ts index 61b6e76..898ab9b 100644 --- a/main/knowledge/edits.ts +++ b/main/knowledge/edits.ts @@ -1,5 +1,6 @@ import { type HistorySource } from "../../shared/history/ipc"; import { randomUUID } from "node:crypto"; +import { extname } from "node:path"; import { attributeTargets, decodeValue, record, validUUID } from "../../shared/attrs/values"; import { blockText, payload } from "../../shared/content/blocks"; import { nowSeconds } from "../../shared/content/time"; @@ -7,6 +8,7 @@ import { LabloomError } from "../../shared/failure"; import { type AttributeDefinition, type AttributeImpact, type AttributeValue } from "../../shared/types/attributes"; import { bodylessPageKinds, pageKinds, type BlockDeletion, type ChangePreview, type CommitResult, type ContentBlock, type EditCommit, type PageKind, type PageRecord, type Placement, type Target } from "../../shared/types/content"; import * as workspace from "../workspace-state"; +import { storedAttachment } from "../attachments/service"; import * as attributes from "./attributes"; import { fingerprint } from "./attributes"; import { EditChanges, type PagePatch, type RowChanges } from "./changes"; @@ -69,7 +71,30 @@ export function commitEdit(input: EditCommit, source: HistorySource | false, con workspace.requireWorkspace(); return commit.edit({ history: source, directPage: input?.pageId, confirmation, writeId }, () => { const plan = planEdit(input); - return commit.finish(plan, input.pageId, input.batch, { action: input }); + const linked = input.linkedPapers; + let rows: RowChanges | undefined; + if (linked?.length) { + const links = new Set(); + for (const block of input.blocks) { + const target = block.payload.target; + if (block.type === "blocked_reference" && target?.kind === "page" && plan.owners(block.id).includes(input.pageId)) + links.add(target.id); + } + const newPages = new Set(); + for (const { id, fileId } of linked) { + if (!validUUID(id) || !validUUID(fileId) || newPages.has("page:" + id) || !links.has(id)) throw new LabloomError({ kind: "page-invalid-create" }); + const file = storedAttachment(fileId); + if (file?.mediaType !== "application/pdf") throw new LabloomError({ kind: "attachment-pdf-required" }); + const name = file.originalName, title = name.slice(0, name.length - extname(name).length); + for (const block of createPageRows(plan, id, "paper", title, { independent: false, paper_files: [fileId], source_snapshot: { originalName: name } })) + plan.blocks.add(block); + newPages.add("page:" + id); + } + const forHistory = (value: RowChanges["before"]): RowChanges["before"] => + Object.fromEntries(Object.entries(value).filter(([key]) => !newPages.has(key))); + rows = { before: forHistory(plan.rows.before), after: forHistory(plan.rows.after) }; + } + return commit.finish(plan, input.pageId, input.batch, { action: input }, rows); }); } @@ -99,7 +124,8 @@ function deletionSubject(block: ContentBlock): string { const names: Record = { title: "标题", paragraph: "段落", heading_1: "一级标题", heading_2: "二级标题", heading_3: "三级标题", unordered_list: "无序列表项", ordered_list: "有序列表项", blockquote: "引言", callout: "提示块", - code: "代码块", table: "表格", hr: "分隔线", blocked_reference: "链接引用" + code: "代码块", table: "表格", hr: "分隔线", blocked_reference: "链接引用", + image: "图片", video: "视频", file: "文件" }; const target = block.payload.target; if (block.type === "blocked_reference" && target) { @@ -256,6 +282,25 @@ export function restore(ids: string[], source: HistorySource, writeId?: string): }); } +function createPageRows(plan: EditChanges, id: string, kind: PageKind, title: string, initial: Record): string[] { + const titleId = randomUUID(), children: string[] = []; + putBlock({ id: titleId, type: "title", payload: payload("title", title), children: [] }); + if (!bodylessPageKinds.includes(kind)) { + const bodyId = randomUUID(); + putBlock({ id: bodyId, type: "paragraph", payload: payload("paragraph"), children: [] }); + children.push(bodyId); + } + data.statement("INSERT INTO pages(id,kind,title_block_id,children) VALUES (?,?,?,?)").run(id, kind, titleId, JSON.stringify(children)); + attributes.initializePage(id); + const now = nowSeconds(); + plan.attributes(id, { + ...(kind === "feed" ? { feed_status: "enabled", feed_refresh: { every: 60, unit: "minute" } } : {}), ...initial, + independent: initial.independent ?? kind !== "annotation", created_at: now, modified_at: now + }, [], true); + plan.seed({ kind: "page", id }); + return [titleId, ...children]; +} + export function createPage(kind: PageKind = "editable", title = "", initial: Record = {}, parentId?: string, history?: HistorySource): PageRecord { workspace.requireWorkspace(); if (!pageKinds.includes(kind) || typeof title !== "string" || !record(initial)) throw new LabloomError({ kind: "page-invalid-create" }); @@ -267,22 +312,8 @@ export function createPage(kind: PageKind = "editable", title = "", initial: Rec const files = data.get(parentId).attributes.paper_files as string[]; if (!files.includes(String(initial.annotation_file))) throw new LabloomError({ kind: "paper-file-removed" }); } - const id = randomUUID(), titleId = randomUUID(), children: string[] = [], plan = new EditChanges(); - putBlock({ id: titleId, type: "title", payload: payload("title", title), children: [] }); - if (!bodylessPageKinds.includes(kind)) { - const bodyId = randomUUID(); - putBlock({ id: bodyId, type: "paragraph", payload: payload("paragraph"), children: [] }); - children.push(bodyId); - } - data.statement("INSERT INTO pages(id,kind,title_block_id,children) VALUES (?,?,?,?)").run(id, kind, titleId, JSON.stringify(children)); - attributes.initializePage(id); - const now = nowSeconds(); - plan.attributes(id, { - ...(kind === "feed" ? { feed_status: "enabled", feed_refresh: { every: 60, unit: "minute" } } : {}), ...initial, - independent: parentId ? false : initial.independent ?? kind !== "annotation", - created_at: now, modified_at: now - }, [], true); - plan.seed({ kind: "page", id }); + const id = randomUUID(), plan = new EditChanges(); + const created = createPageRows(plan, id, kind, title, parentId ? { ...initial, independent: false } : initial); if (parentId && kind === "annotation") { if (data.header(parentId).kind !== "paper") throw new LabloomError({ kind: "annotation-paper-required" }); const current = (data.get(parentId).attributes.paper_annotations as string[]).filter(id => @@ -315,7 +346,7 @@ export function createPage(kind: PageKind = "editable", title = "", initial: Rec if (data.flags(id).deleted) throw new LabloomError({ kind: "page-retaining-reference-required" }); if (!history && parentId && kind !== "annotation") context.invalidate(["page:" + parentId]); changed.pages = [...plan.pages]; - changed.blocks = [titleId, ...children, ...plan.blocks]; + changed.blocks = [...created, ...plan.blocks]; context.change(changed); return data.get(id); }); diff --git a/main/knowledge/papers.ts b/main/knowledge/papers.ts index f01eebd..bbd69a1 100644 --- a/main/knowledge/papers.ts +++ b/main/knowledge/papers.ts @@ -1,8 +1,8 @@ import { type HistorySource } from "../../shared/history/ipc"; import { eq, sql } from "drizzle-orm"; -import { accessSync, constants, readFileSync, statSync } from "node:fs"; +import { readFileSync } from "node:fs"; import { createRequire } from "node:module"; -import { basename, dirname, extname, isAbsolute, join } from "node:path"; +import { basename, dirname, extname, join } from "node:path"; import { fileURLToPath } from "node:url"; import type { PDFDocumentLoadingTask, PDFDocumentProxy } from "pdfjs-dist/types/src/display/api"; import { record, validUUID } from "../../shared/attrs/values"; @@ -12,8 +12,7 @@ import { charactersFromTextContent, extractText, PDF_EXTRACTOR_VERSION, type Pdf import { diagnostic, LabloomError, toFailureInfo } from "../../shared/failure"; import { type AttributeValue } from "../../shared/types/attributes"; import { type CommitResult, type PageRecord } from "../../shared/types/content"; -import { type AnnotationInput, type AnnotationPaper, type Attachment, type PaperAnnotation, type PaperImport, type PaperImportBatch, type PaperResources, type ReadingPosition } from "../../shared/types/papers"; -import * as attachmentFiles from "../attachments/service"; +import { type AnnotationInput, type AnnotationPaper, type Attachment, type PaperAnnotation, type PaperResources, type ReadingPosition } from "../../shared/types/papers"; import { attachmentPath } from "../storage/files"; import { attachments } from "../storage/tables"; import * as workspace from "../workspace-state"; @@ -179,69 +178,35 @@ export function attachFile(pageId: string, attributeId: string, fileId: string, append(pageId, attributeId, [file], source); } -export function attachFiles(paths: string[], pageId: string, attributeId: string, source?: HistorySource): Attachment[] { - workspace.requireWorkspace(); - if (!Array.isArray(paths) || !paths.length) throw new LabloomError({ kind: "attachment-selection-required" }); - return attachmentFiles.importing(store => commit.run({ history: false }, () => { - const localFiles = paths.map(store); - append(pageId, attributeId, localFiles, source); - return localFiles; - })); +function requiredFiles(ids: string[]): Attachment[] { + const found = files(ids); + if (found.length !== ids.length) throw new LabloomError({ kind: "attachment-missing" }); + return found; } -export function importFile(path: string, pageId?: string, source?: HistorySource): PaperImport { +export function attachImported(ids: string[], pageId: string, attributeId: string, source?: HistorySource): Attachment[] { workspace.requireWorkspace(); - if (pageId) paper(pageId, true); - return attachmentFiles.importing(store => commit.run({ history: false }, () => { - const file = store(path); - const page = pageId ? paper(pageId, true) : edits.createPage("paper", basename(path, extname(path)), { source_snapshot: { originalName: basename(path) } }, undefined, source); - append(page.id, "paper_files", [file], source); - return { pageId: page.id }; - })); + if (!Array.isArray(ids) || !ids.length) throw new LabloomError({ kind: "attachment-selection-required" }); + return commit.run({ history: false }, () => { + const localFiles = requiredFiles(ids); + append(pageId, attributeId, localFiles, source); + return localFiles; + }); } -export function importPaths(paths: string[], source: HistorySource, pageId?: string, pdfOnly = !pageId): PaperImportBatch { +export function importPrepared(ids: string[], source?: HistorySource, pageId?: string): string[] { workspace.requireWorkspace(); - type Entry = { path: string; error?: ReturnType; page?: string }; - const entries: Entry[] = paths.map(path => ({ path })); - for (const entry of entries) { - try { - const { path } = entry; - if (!isAbsolute(path) || !statSync(path).isFile()) throw new LabloomError({ kind: "import-regular-file" }); - accessSync(path, constants.R_OK); - const pdf = extname(path).toLowerCase() === ".pdf"; - if (pdfOnly && !pdf) throw new LabloomError({ kind: "import-pdf-only" }); - if (pageId && pdf) attachmentFiles.checkLocalPDF(path); - if (!pageId) entry.page = importFile(path, undefined, source).pageId; - } - catch (error) { - entry.error = toFailureInfo(error); - } + if (!ids.length) return []; + if (pageId) { + paper(pageId, true); + attachImported(ids, pageId, "paper_files", source); + return ids.map(() => pageId); } - const accepted = entries.filter(entry => !entry.error); - if (pageId && accepted.length) { - try { - paper(pageId, true); - attachmentFiles.importing(store => commit.run({ history: false }, () => { - const files: Attachment[] = []; - for (const entry of accepted) { - try { - files.push(store(entry.path)); - } - catch (error) { - entry.error = toFailureInfo(error); - } - } - if (files.length) append(pageId, "paper_files", files, source); - })); - for (const entry of accepted) if (!entry.error) entry.page = pageId; - } - catch (error) { - for (const entry of accepted) entry.error ??= toFailureInfo(error); - } - } - return { pages: entries.flatMap(entry => entry.page ? [entry.page] : []), - failures: entries.flatMap(entry => entry.error ? [{ name: basename(entry.path), error: entry.error }] : []) }; + const files = requiredFiles(ids); + if (files.some(file => file.mediaType !== "application/pdf")) throw new LabloomError({ kind: "import-pdf-only" }); + return files.map(file => edits.createPage("paper", basename(file.originalName, extname(file.originalName)), { + paper_files: [file.id], source_snapshot: { originalName: file.originalName } + }, undefined, source).id); } export function read(id: string): Uint8Array { @@ -420,10 +385,4 @@ export async function get(pageId: string): Promise { const session = workspace.requireWorkspace(), page = data.get(pageId); if (page.kind === "annotation" && !page.attributes.deleted) await getAnnotation(pageId); return workspace.isCurrent(session) ? data.get(pageId) : page; -} -export function fileSelection(attributeId: string): boolean { - workspace.requireWorkspace(); - const definition = attributes.definition(attributeId); - if (definition.type !== "file" && definition.type !== "files") throw new LabloomError({ kind: "attribute-file-required" }); - return definition.type === "files"; } \ No newline at end of file diff --git a/main/knowledge/records.ts b/main/knowledge/records.ts index 58ab55e..021a480 100644 --- a/main/knowledge/records.ts +++ b/main/knowledge/records.ts @@ -5,11 +5,13 @@ import { libraryText, search } from "../../shared/attrs/format"; import { attributeTargetKind, decodeValue, emptyValue, encodeValue, nullable, record, validUUID } from "../../shared/attrs/values"; import { blockText, payload, validateBlock, validTarget } from "../../shared/content/blocks"; import { matchRanges } from "../../shared/content/matches"; +import type { MediaFile } from "../../shared/content/media"; import { isTimeType, resolveTimeZone, validTimeSeconds } from "../../shared/content/time"; import { LabloomError } from "../../shared/failure"; import { type AttributeDefinition, type AttributeValue } from "../../shared/types/attributes"; import { pageKinds, type Backlink, type ContentBlock, type LinkTarget, type PageKind, type PageList, type PageObjects, type PageQuery, type PageRecord, type PageSummary, type PageSearchResult, type ResolvedTarget, type Target } from "../../shared/types/content"; import { type blocks, type pages } from "../storage/tables"; +import { attachmentPath } from "../storage/files"; import * as workspace from "../workspace-state"; import { overviewBatchSize, type OverviewIndex, type OverviewPage, type OverviewQuery } from "../../shared/workspace/overview"; @@ -129,7 +131,9 @@ export function readObjects(pageId: string, ids: string[]): PageObjects { workspace.requireWorkspace(); const page = ids.includes(pageId) ? { children: children({ kind: "page", id: pageId }), attributes: valuesFor([pageId]).get(pageId) ?? {} } : undefined; const blocks = ids.filter(id => id !== pageId); - return { page, blocks: readBatch(blocks), uses: sharedUses(blocks) }; + const content = readBatch(blocks), files = new Set(); + for (const block of content) if (block.payload.media?.fileId) files.add(block.payload.media.fileId); + return { page, blocks: content, uses: sharedUses(blocks), ...(files.size ? { mediaFiles: mediaFiles(files) } : {}) }; } export function uses(id: string): Use[] { @@ -191,6 +195,7 @@ export function get(id: string): PageRecord { const row = header(id), pageChildren = children({ kind: "page", id }); const visible: Record = {}; const seen = new Set(); + let files: Set | undefined; let level = [row.titleBlockId, ...pageChildren]; while (level.length) { const batch = [...new Set(level)].filter(id => !seen.has(id)); @@ -198,16 +203,25 @@ export function get(id: string): PageRecord { level = []; for (const block of readBatch(batch)) { visible[block.id] = block; + if (block.payload.media?.fileId) (files ??= new Set()).add(block.payload.media.fileId); for (const child of block.children) if (!seen.has(child)) level.push(child); } } const localTitle = visible[row.titleBlockId]; return { ...row, kind: row.kind as PageKind, children: pageChildren, title: localTitle ? blockText(localTitle) : "", excerpt: excerpt(pageChildren, visible), - blocks: visible, sharedUses: sharedUses([...seen]), attributes: valuesFor([id]).get(id) ?? {} + blocks: visible, sharedUses: sharedUses([...seen]), attributes: valuesFor([id]).get(id) ?? {}, + ...(files ? { mediaFiles: mediaFiles(files) } : {}) }; } +function mediaFiles(ids: Set): Record { + const root = workspace.root(); + const rows = statement(`SELECT id, original_name AS originalName, media_type AS mediaType, size, stored_name AS storedName + FROM attachments WHERE id IN (SELECT value FROM json_each(?))`).all(JSON.stringify([...ids])) as (Omit & { storedName: string })[]; + return Object.fromEntries(rows.map(({ storedName, ...file }) => [file.id, { ...file, path: attachmentPath(root, storedName) }])); +} + function excerpt(ids: string[], blocks: Record): string { let text = ""; for (const id of ids) { @@ -245,8 +259,16 @@ function attributeText(): string { ) END) END`; } -const blockHits = `block_hits(id) AS MATERIALIZED ( +const blockHits = `file_hits(id, name) AS MATERIALIZED ( + SELECT l.source_id, f.original_name FROM attachments f CROSS JOIN link_refs l + ON l.target_kind='file' AND l.target_id=f.id AND l.source_kind='block' + WHERE instr(knowledge_lower(f.original_name), @keyword)>0 + UNION ALL + SELECT b.id, b.content ->> '$.media.name' FROM blocks b WHERE b.type IN ('image','video','file') + AND b.content ->> '$.media.fileId' IS NULL AND instr(knowledge_lower(coalesce(b.content ->> '$.media.name', '')), @keyword)>0 +), block_hits(id) AS MATERIALIZED ( SELECT b.id FROM blocks b WHERE instr(knowledge_lower(knowledge_text(b.type,b.content)), @keyword)>0 + UNION SELECT id FROM file_hits ), owners(kind,id) AS ( SELECT 'block', id FROM block_hits UNION SELECT u.container_kind,u.container_id FROM owners o JOIN sync_refs u ON u.block_id=o.id WHERE o.kind='block' @@ -366,9 +388,10 @@ const searchSQL = searchMatches + `, ranked AS MATERIALIZED ( AND r.block_id IN (SELECT id FROM owners WHERE kind='block') ORDER BY r.position LIMIT 1 ) FROM walk w WHERE w.kind='page' OR w.id NOT IN block_hits ), body AS ( - SELECT w.page, b.type, b.content FROM walk w JOIN blocks b ON b.id=w.id WHERE w.kind='block' AND w.id IN block_hits + SELECT w.page, coalesce(f.name, knowledge_text(b.type,b.content)) AS text + FROM walk w JOIN blocks b ON b.id=w.id LEFT JOIN file_hits f ON f.id=b.id WHERE w.kind='block' AND w.id IN block_hits ) -SELECT r.*, a.name, CASE r.field WHEN 'body' THEN knowledge_text(b.type,b.content) +SELECT r.*, a.name, CASE r.field WHEN 'body' THEN b.text WHEN 'attribute' THEN ${attributeText()} END AS text FROM ranked r LEFT JOIN body b ON b.page=r.id LEFT JOIN page_attrs v ON r.field='attribute' AND v.page_id=r.id AND v.attr_id=r.attr diff --git a/main/papers/ipc.ts b/main/papers/ipc.ts index 9e3a9e0..c60c25d 100644 --- a/main/papers/ipc.ts +++ b/main/papers/ipc.ts @@ -4,21 +4,13 @@ import { papersChannels, type PapersAPI } from "../../shared/papers/ipc"; import { invalid, register, route, type Routes } from "../ipc"; import * as papers from "../knowledge/papers"; import { LabloomError } from "../../shared/failure"; -import * as dialogs from "../ui/fileDialogs"; type Args = Parameters; export function registerPapersIPCs(window: BrowserWindow): void { const routes = { - importPDF: route(typia.createAssert>(invalid), async (...[source, pageId]) => { - const paths = await dialogs.selectPDF(window); - return papers.importPaths(paths, source, pageId, true); - }), - importPaths: route(typia.createAssert>(invalid), papers.importPaths), - importFiles: route(typia.createAssert>(invalid), async (...[pageId, attributeId, source]) => { - const paths = await dialogs.selectFiles(window, papers.fileSelection(attributeId)); - return paths.length ? papers.attachFiles(paths, pageId, attributeId, source) : null; - }), + importPrepared: route(typia.createAssert>(invalid), papers.importPrepared), + attachImported: route(typia.createAssert>(invalid), papers.attachImported), attachFile: route(typia.createAssert>(invalid), papers.attachFile), files: route(typia.createAssert>(invalid), papers.files), openFile: route(typia.createAssert>(invalid), async id => { diff --git a/main/register.ts b/main/register.ts index 01e3786..b4c90d0 100644 --- a/main/register.ts +++ b/main/register.ts @@ -4,6 +4,7 @@ import { registerPagesIPCs } from "./pages/ipc"; import { registerAttributesIPCs } from "./attributes/ipc"; import { registerHistoryIPCs } from "./history/ipc"; import { registerPapersIPCs } from "./papers/ipc"; +import { registerAttachmentIPCs } from "./attachments/ipc"; import { registerTimersIPCs } from "./timers/ipc"; import { registerWorkspaceIPCs } from "./workspace/ipc"; import { registerSettingsIPCs } from "./settings/ipc"; @@ -16,6 +17,7 @@ export function registerIPCs(window: BrowserWindow, rememberWindow: () => void): registerAttributesIPCs(window); registerHistoryIPCs(window); registerPapersIPCs(window); + registerAttachmentIPCs(window); registerTimersIPCs(window); registerWorkspaceIPCs(window); registerSettingsIPCs(window, rememberWindow); diff --git a/main/ui/fileDialogs.ts b/main/ui/fileDialogs.ts index 1235bcd..033303e 100644 --- a/main/ui/fileDialogs.ts +++ b/main/ui/fileDialogs.ts @@ -7,11 +7,6 @@ export async function selectPDF(window: BrowserWindow): Promise { const result = await dialog.showOpenDialog(window, { properties: ["openFile", "multiSelections"], filters: [{ name: t("dialog.pdfFilter"), extensions: ["pdf"] }] }); return result.canceled ? [] : result.filePaths; } -export async function selectFiles(window: BrowserWindow, multiple: boolean): Promise { - const result = await dialog.showOpenDialog(window, { properties: multiple ? ["openFile", "multiSelections"] : ["openFile"] }); - return result.canceled ? [] : result.filePaths; -} - // One dialog at a time prevents repeated clicks in the current window. let choosingWorkspace = false; diff --git a/preload/index.ts b/preload/index.ts index a16b6e1..11ef2a6 100644 --- a/preload/index.ts +++ b/preload/index.ts @@ -1,7 +1,7 @@ import { contextBridge, ipcRenderer, webUtils } from "electron"; import type { AppAPI, AppCommands, AppQueries, BridgeAPI } from "../shared/ipc"; import type { Channels, InvokeKeys } from "../shared/ipc/contract"; -import { appChannels, appQueryChannels, beforeQuit, feedChanged, historyChanged, pagesChanged, settingsChanged, openReminderPage, pagesChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels } from "../shared/ipc"; +import { appChannels, appQueryChannels, attachmentProgress, beforeQuit, feedChanged, historyChanged, pagesChanged, settingsChanged, openReminderPage, pagesChannels, attachmentsChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels } from "../shared/ipc"; function methods(channels: Record, call: (channel: string, ...args: unknown[]) => unknown): API { return Object.fromEntries(Object.entries(channels).map(([key, channel]) => [key, (...args: unknown[]) => call(channel, ...args)])) as API; @@ -37,6 +37,7 @@ const api: BridgeAPI = { attributes: invokes(attributesChannels), history: { ...invokes(historyChannels), onChanged: listener => subscribe(historyChanged, listener) }, papers: invokes(papersChannels), + attachments: { ...invokes(attachmentsChannels), onTransferProgress: listener => subscribe(attachmentProgress, listener) }, timers: { ...invokes(timersChannels), onOpenNotice: listener => subscribe(openReminderPage, listener) }, workspace: invokes(workspaceChannels), settings: { ...invokes(settingsChannels), onChanged: listener => subscribe(settingsChanged, listener) }, diff --git a/renderer/components/Editor/Editor.svelte b/renderer/components/Editor/Editor.svelte index adc567c..ee738ba 100644 --- a/renderer/components/Editor/Editor.svelte +++ b/renderer/components/Editor/Editor.svelte @@ -1,4 +1,15 @@ +{#each [...mediaInsertions.jobs] as [job, transfer] (job)} + {#if transfer} +
+ {t("editor.mediaTransfer", transfer)} + + +
+ {/if} +{/each}