Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -348,6 +352,8 @@
"chooseDate": "Choose date property"
},
"dialog": {
"imageFilter": "Images",
"videoFilter": "Video and audio",
"close": "Close",
"cancel": "Cancel",
"confirm": "Confirm changes",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
23 changes: 21 additions & 2 deletions locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "这种页面不能有正文。",
Expand Down Expand Up @@ -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": "文本节点不能为空。",
Expand Down Expand Up @@ -348,6 +352,8 @@
"chooseDate": "选择日期属性"
},
"dialog": {
"imageFilter": "图片",
"videoFilter": "视频和音频",
"close": "关闭",
"cancel": "取消",
"confirm": "确认更改",
Expand Down Expand Up @@ -469,6 +475,16 @@
"perl": "Perl"
},
"editor": {
"pasteLink": "粘贴链接",
"embedImage": "嵌入为图片",
"imageViewer": "图片查看器",
"imageCount": "{{current}} / {{total}}",
"previousImage": "上一张图片",
"nextImage": "下一张图片",
"mediaTransfer": "正在导入文件({{current}} / {{total}})",
"addCaption": "添加说明",
"missingFile": "文件缺失",
"resizeMedia": "调整媒体宽度",
"language": "代码语言",
"copyCode": "复制代码",
"insertBlock": "插入块",
Expand Down Expand Up @@ -732,7 +748,10 @@
"code": "代码",
"table": "表格",
"hr": "分隔线",
"blocked_reference": "链接引用"
"blocked_reference": "链接引用",
"image": "图片",
"video": "视频",
"file": "文件"
},
"color": {
"default": "默认",
Expand Down
45 changes: 33 additions & 12 deletions main/attachments/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();

// 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;
Expand All @@ -21,11 +21,19 @@ export function discardInterrupted(directory: string): void {
}
}

async function stage<T>(directory: string, chunks: AsyncIterable<Uint8Array>, publish: (path: string) => T): Promise<T> {
export async function stageFile(directory: string, chunks: AsyncIterable<Uint8Array>): Promise<{ path: string; discard: () => Promise<void> }> {
// 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<void> => {
try {
if (owned) await rm(path, { force: true });
}
finally {
active.delete(path);
}
};
try {
const file = await open(path, "wx");
owned = true;
Expand All @@ -35,15 +43,21 @@ async function stage<T>(directory: string, chunks: AsyncIterable<Uint8Array>, pu
finally {
await file.close();
}
return publish(path);
return { path, discard };
}
catch (error) {
await discard();
throw error;
}
}

export async function stage<T>(directory: string, chunks: AsyncIterable<Uint8Array>, publish: (path: string) => T): Promise<T> {
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();
}
}

Expand All @@ -55,6 +69,7 @@ export async function receive<T>(url: string, request: Request, save: (path: str
idle = setTimeout(() => controller.abort(new LabloomError({ kind: "download-timeout" })), request.timeoutMs ?? 30_000);
};
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
let total: number | undefined;
const cancel = (): void => {
void reader?.cancel(signal.reason).catch(() => {});
};
Expand All @@ -64,7 +79,7 @@ export async function receive<T>(url: string, request: Request, save: (path: str
}

async function* chunks(): AsyncGenerator<Uint8Array> {
let checked = 0;
let checked = 0, bytes = 0;
startWaiting();
while (reader) {
const { done, value } = await reader.read().catch(networkFailure);
Expand All @@ -78,6 +93,8 @@ export async function receive<T>(url: string, request: Request, save: (path: str
checked += prefix.length;
}
yield value;
bytes += value.byteLength;
request.progress?.(bytes, total);
startWaiting();
}
clearTimeout(idle);
Expand All @@ -94,8 +111,12 @@ export async function receive<T>(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);
Expand Down
115 changes: 115 additions & 0 deletions main/attachments/ipc.ts
Original file line number Diff line number Diff line change
@@ -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<K extends keyof AttachmentsAPI> = Parameters<AttachmentsAPI[K]>;
type Upload = { writer: WritableStreamDefaultWriter<Uint8Array>; result: Promise<MediaFile> };
const tasks = new Map<string, { cancel: AbortController; upload?: Upload }>();
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<AttachmentsAPI> = {
available: route(typia.createAssert<Args<"available">>(invalid), service.available),
saveAs: route(typia.createAssert<Args<"saveAs">>(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<Args<"choose">>(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<Args<"stagePaths">>(invalid), service.stagePaths),
importPath: route(typia.createAssert<Args<"importPath">>(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<Args<"downloadImage">>(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<Args<"uploadStart">>(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<Uint8Array, Uint8Array>();
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<Args<"uploadChunk">>(invalid), (id, bytes) => upload(id).writer.write(bytes)),
uploadFinish: route(typia.createAssert<Args<"uploadFinish">>(invalid), async id => {
const { writer, result } = upload(id);
try {
await writer.close().catch(() => {});
return await result;
}
finally {
tasks.delete(id);
}
}),
cancelTransfer: route(typia.createAssert<Args<"cancelTransfer">>(invalid), cancelTransfer),
releaseHandoffs: route(typia.createAssert<Args<"releaseHandoffs">>(invalid), service.releaseHandoffs)
};
register(window.webContents, attachmentsChannels, routes);
}
15 changes: 12 additions & 3 deletions main/attachments/metadata.ts
Original file line number Diff line number Diff line change
@@ -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<Attachment, "originalName" | "mediaType">;
export const binary = "application/octet-stream";
Expand All @@ -12,10 +14,17 @@ const mediaTypes: Record<string, string> = {
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<MediaKind, "file">): 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;
Expand All @@ -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(/[. ]+$/, "");
}

Expand Down
8 changes: 8 additions & 0 deletions main/attachments/protocol.ts
Original file line number Diff line number Diff line change
@@ -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));
}
Loading
Loading