Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve asset upload interception guarantees https://github.com/siyuan-note/siyuan/issues/18878

Daniel35ba8d36e1de
diff --git a/app/src/protyle/render/av/asset.ts b/app/src/protyle/render/av/asset.ts
index 8ec83acbde..1efe367fcb 100644
--- a/app/src/protyle/render/av/asset.ts
+++ b/app/src/protyle/render/av/asset.ts
@@ -493,36 +493,48 @@ ${window.siyuan.languages.title}
menu.element.querySelector("textarea").focus();
};
+const updateCellWithUploadedAssets = (result: Omit<IAssetUploadResult, "requestId" | "input">,
+ protyle: IProtyle, cellElement: HTMLElement) => {
+ const blockElement = hasClosestBlock(cellElement);
+ if (!blockElement) {
+ return;
+ }
+ const addValue: IAVCellAssetValue[] = [];
+ getAssetUploadSuccesses(result).forEach(success => {
+ const type = getAssetExtension(success.name).toLowerCase();
+ const name = success.name.substring(0, success.name.length - type.length);
+ if (Constants.SIYUAN_ASSETS_IMAGE.includes(type)) {
+ addValue.push({
+ type: "image",
+ name,
+ content: success.path,
+ });
+ } else {
+ addValue.push({
+ type: "file",
+ name,
+ content: success.path,
+ });
+ }
+ });
+ updateAssetCell({
+ protyle,
+ blockElement,
+ cellElements: [cellElement],
+ addValue
+ });
+};
+
export const dragUpload = (files: ILocalFiles[], protyle: IProtyle, cellElement: HTMLElement,
position?: IAssetUploadPosition) => {
- uploadLocalFiles(files, protyle, true, {source: "drop", target: "av-cell", position}, (response) => {
- const blockElement = hasClosestBlock(cellElement);
- if (!blockElement) {
- return;
- }
- const addValue: IAVCellAssetValue[] = [];
- getAssetUploadSuccesses(response.data).forEach(success => {
- const type = getAssetExtension(success.name).toLowerCase();
- const name = success.name.substring(0, success.name.length - type.length);
- if (Constants.SIYUAN_ASSETS_IMAGE.includes(type)) {
- addValue.push({
- type: "image",
- name,
- content: success.path,
- });
- } else {
- addValue.push({
- type: "file",
- name,
- content: success.path,
- });
- }
- });
- updateAssetCell({
- protyle,
- blockElement,
- cellElements: [cellElement],
- addValue
- });
+ uploadLocalFiles(files, protyle, true, {source: "drop", target: "av-cell", position}, (_response, result) => {
+ updateCellWithUploadedAssets(result, protyle, cellElement);
});
};
+
+export const dragUploadFiles = (files: FileList | File[], protyle: IProtyle, cellElement: HTMLElement,
+ position?: IAssetUploadPosition) => {
+ uploadFiles(protyle, files, undefined, (_response, result) => {
+ updateCellWithUploadedAssets(result, protyle, cellElement);
+ }, undefined, {source: "drop", target: "av-cell", position});
+};
diff --git a/app/src/protyle/render/av/blockAttr.ts b/app/src/protyle/render/av/blockAttr.ts
index 8fe1807afe..9f3ab528c0 100644
--- a/app/src/protyle/render/av/blockAttr.ts
+++ b/app/src/protyle/render/av/blockAttr.ts
@@ -8,7 +8,7 @@ import {transaction} from "../../wysiwyg/transaction";
import {openMenuPanel} from "./openMenuPanel";
import {uploadFiles} from "../../upload";
import {openLink} from "../../../editor/openLink";
-import {dragUpload, editAssetItem} from "./asset";
+import {dragUpload, dragUploadFiles, editAssetItem} from "./asset";
import {previewImages} from "../../preview/image";
/// #if !BROWSER
import {webUtils} from "electron";
@@ -25,7 +25,7 @@ import {
isAVTemplateLink
} from "./attributeValue";
import {isLastPointerMouse} from "../../../util/touchDragBridge";
-import {hasDataTransferFiles} from "../../upload/localDropFiles";
+import {getLocalDropFiles, hasDataTransferFiles} from "../../upload/localDropFiles";
interface IAVAttributeTableData {
avID: string;
@@ -200,18 +200,19 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr
} else if (!window.siyuan.dragElement && hasDataTransferFiles(event.dataTransfer.types)) {
const cellElement = element.querySelector(".custom-attr__avvalue--active") as HTMLElement;
if (cellElement) {
- if (hasDataTransferFiles(event.dataTransfer.types) && !isBrowser()) {
- const files: ILocalFiles[] = [];
- for (let i = 0; i < event.dataTransfer.files.length; i++) {
- files.push({
- path: webUtils.getPathForFile(event.dataTransfer.files[i]),
- size: event.dataTransfer.files[i].size,
- isDir: event.dataTransfer.files[i].size === 0 &&
- event.dataTransfer.files[i].type === "" &&
- !event.dataTransfer.files[i].name.includes("."),
- });
+ const position = {x: event.clientX, y: event.clientY};
+ if (!isBrowser()) {
+ /// #if !BROWSER
+ const files = getLocalDropFiles(event.dataTransfer.files,
+ file => webUtils.getPathForFile(file));
+ if (files) {
+ dragUpload(files, protyle, cellElement, position);
+ } else {
+ dragUploadFiles(event.dataTransfer.files, protyle, cellElement, position);
}
- dragUpload(files, protyle, cellElement, {x: event.clientX, y: event.clientY});
+ /// #endif
+ } else {
+ dragUploadFiles(event.dataTransfer.files, protyle, cellElement, position);
}
}
}
diff --git a/app/src/protyle/upload/base64.ts b/app/src/protyle/upload/base64.ts
index a2d40f53ef..ac1c0b52d1 100644
--- a/app/src/protyle/upload/base64.ts
+++ b/app/src/protyle/upload/base64.ts
@@ -1,28 +1,17 @@
import {type IUploadInsertOptions, uploadFiles} from "./index";
import {getAssetUploadPathsByInput} from "./uploadResult";
+import {createBase64ImageFile} from "./base64File";
export const base64ToURL = async (base64SrcList: string[], protyle: IProtyle,
options?: IUploadInsertOptions) => {
const files: File[] = [];
const fileSourceIndices: number[] = [];
base64SrcList.forEach((item, sourceIndex) => {
- const srcPart = item.split(",");
- if (srcPart.length !== 2) return;
- // data URL 格式为 data:image/svg+xml;base64,XXX
- const mimeMatch = srcPart[0].match(/data:([^;]+);/);
- const mime = mimeMatch ? mimeMatch[1] : "application/octet-stream";
- const binary = atob(srcPart[1]);
- const u8arr = new Uint8Array(binary.length);
- for (let i = 0; i < binary.length; i++) {
- u8arr[i] = binary.charCodeAt(i);
+ const file = createBase64ImageFile(item, `base64image-${Lute.NewNodeID()}`);
+ if (!file) {
+ return;
}
- files.push(new File([u8arr], `base64image-${Lute.NewNodeID()}.${{
- "image/png": "png",
- "image/jpeg": "jpg",
- "image/webp": "webp",
- "image/gif": "gif",
- "image/svg+xml": "svg"
- }[mime] || "png"}`, {type: mime}));
+ files.push(file);
fileSourceIndices.push(sourceIndex);
});
const paths: Array<string | undefined> = new Array(base64SrcList.length).fill(undefined);
diff --git a/app/src/protyle/upload/base64File.ts b/app/src/protyle/upload/base64File.ts
new file mode 100644
index 0000000000..ac64332454
--- /dev/null
+++ b/app/src/protyle/upload/base64File.ts
@@ -0,0 +1,29 @@
+const getBase64ImageExtension = (mime: string) => ({
+ "image/png": "png",
+ "image/jpeg": "jpg",
+ "image/webp": "webp",
+ "image/gif": "gif",
+ "image/svg+xml": "svg",
+}[mime] || "png");
+
+export const createBase64ImageFile = (source: string, name: string) => {
+ const separator = source.indexOf(",");
+ if (separator < 0) {
+ return;
+ }
+ const mimeMatch = source.substring(0, separator).match(/^data:([^;,]+)(?:;[^,]*)?;base64$/i);
+ if (!mimeMatch) {
+ return;
+ }
+ try {
+ const mime = mimeMatch[1].toLowerCase();
+ const binary = atob(source.substring(separator + 1));
+ const bytes = new Uint8Array(binary.length);
+ for (let index = 0; index < binary.length; index++) {
+ bytes[index] = binary.charCodeAt(index);
+ }
+ return new File([bytes], `${name}.${getBase64ImageExtension(mime)}`, {type: mime});
+ } catch (error) {
+ console.error(error);
+ }
+};
diff --git a/app/src/protyle/upload/htmlEmbeddedAssets.test.ts b/app/src/protyle/upload/htmlEmbeddedAssets.test.ts
new file mode 100644
index 0000000000..26a5cf3f52
--- /dev/null
+++ b/app/src/protyle/upload/htmlEmbeddedAssets.test.ts
@@ -0,0 +1,102 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {createBase64ImageFile} from "./base64File";
+import {
+ applyHTMLEmbeddedAssetPaths,
+ collectHTMLEmbeddedAssets,
+ type IHTMLEmbeddedAsset,
+ isHTMLBase64Image,
+} from "./htmlEmbeddedAssets";
+
+describe("HTML embedded assets", () => {
+ it("recognizes Base64 images without accepting unrelated data URLs", () => {
+ assert.equal(isHTMLBase64Image("data:image/png;base64,YQ=="), true);
+ assert.equal(isHTMLBase64Image("data:image/svg+xml;charset=utf-8;base64,YQ=="), true);
+ assert.equal(isHTMLBase64Image("data:text/plain;base64,YQ=="), false);
+ assert.equal(isHTMLBase64Image("https://example.com/image.png"), false);
+ });
+
+ it("creates image files using the declared content type", () => {
+ const file = createBase64ImageFile("data:image/jpeg;base64,YQ==", "image");
+
+ assert.equal(file.name, "image.jpg");
+ assert.equal(file.type, "image/jpeg");
+ assert.equal(file.size, 1);
+ });
+
+ it("collects Base64 attributes and rewrites them after upload", () => {
+ const attributes = new Map([["src", "data:image/png;base64,YQ=="]]);
+ const element = {
+ getAttribute(name: string) {
+ return attributes.get(name) || null;
+ },
+ setAttribute(name: string, value: string) {
+ attributes.set(name, value);
+ },
+ } as Element;
+ const root = {
+ querySelectorAll(selector: string) {
+ return selector === "pre" ? [] : [element];
+ },
+ } as unknown as ParentNode;
+
+ const assets = collectHTMLEmbeddedAssets(root);
+ applyHTMLEmbeddedAssetPaths(assets, ["assets/image.png"]);
+
+ assert.equal(assets.length, 1);
+ assert.equal(attributes.get("src"), "assets/image.png");
+ });
+
+ it("collects inline SVG blocks and replaces them with uploaded images", () => {
+ const attributes = new Map<string, string>();
+ const image = {
+ setAttribute(name: string, value: string) {
+ attributes.set(name, value);
+ },
+ } as Element;
+ let replacement: Element | undefined;
+ const block = {
+ hasAttributes() {
+ return true;
+ },
+ querySelector() {
+ return {outerHTML: "<svg><rect width=\"1\" height=\"1\"></rect></svg>"};
+ },
+ ownerDocument: {
+ createElement() {
+ return image;
+ },
+ },
+ replaceWith(element: Element) {
+ replacement = element;
+ },
+ } as unknown as Element;
+ const root = {
+ querySelectorAll(selector: string) {
+ return selector === "pre" ? [block] : [];
+ },
+ } as unknown as ParentNode;
+
+ const assets = collectHTMLEmbeddedAssets(root);
+ applyHTMLEmbeddedAssetPaths(assets, ["assets/image.svg"]);
+
+ assert.equal(assets[0].file.type, "image/svg+xml");
+ assert.equal(replacement, image);
+ assert.equal(attributes.get("src"), "assets/image.svg");
+ assert.equal(attributes.get("alt"), "image");
+ });
+
+ it("applies only successful upload paths", () => {
+ const applied: string[] = [];
+ const assets = [0, 1].map(index => ({
+ file: new File(["content"], `${index}.png`, {type: "image/png"}),
+ apply(path: string) {
+ applied.push(`${index}:${path}`);
+ },
+ })) as IHTMLEmbeddedAsset[];
+
+ applyHTMLEmbeddedAssetPaths(assets, [undefined, "assets/image.png"]);
+
+ assert.deepEqual(applied, ["1:assets/image.png"]);
+ });
+});
diff --git a/app/src/protyle/upload/htmlEmbeddedAssets.ts b/app/src/protyle/upload/htmlEmbeddedAssets.ts
new file mode 100644
index 0000000000..cbc5e8f264
--- /dev/null
+++ b/app/src/protyle/upload/htmlEmbeddedAssets.ts
@@ -0,0 +1,63 @@
+import {createBase64ImageFile} from "./base64File";
+
+export interface IHTMLEmbeddedAsset {
+ file: File;
+ apply(path: string): void;
+}
+
+export const isHTMLBase64Image = (value: string) => /^data:image\/[^,]+;base64,/i.test(value.trim());
+
+export const collectHTMLEmbeddedAssets = (root: ParentNode) => {
+ const assets: IHTMLEmbeddedAsset[] = [];
+ const svgBlocks = new Set<Element>();
+ root.querySelectorAll("pre").forEach(element => {
+ if (!element.hasAttributes()) {
+ return;
+ }
+ const svg = element.querySelector("svg");
+ if (!svg) {
+ return;
+ }
+ svgBlocks.add(element);
+ const file = new File([svg.outerHTML], `inline-svg-${assets.length}.svg`, {type: "image/svg+xml"});
+ assets.push({
+ file,
+ apply(path) {
+ const image = element.ownerDocument.createElement("img");
+ image.setAttribute("alt", "image");
+ image.setAttribute("src", path);
+ element.replaceWith(image);
+ },
+ });
+ });
+ root.querySelectorAll("[href], [src]").forEach(element => {
+ if (Array.from(svgBlocks).some(block => block.contains(element))) {
+ return;
+ }
+ (["href", "src"] as const).forEach(attribute => {
+ const source = element.getAttribute(attribute);
+ if (!source || !isHTMLBase64Image(source)) {
+ return;
+ }
+ const file = createBase64ImageFile(source.trim(), `html-image-${assets.length}`);
+ if (!file) {
+ return;
+ }
+ assets.push({
+ file,
+ apply(path) {
+ element.setAttribute(attribute, path);
+ },
+ });
+ });
+ });
+ return assets;
+};
+
+export const applyHTMLEmbeddedAssetPaths = (assets: IHTMLEmbeddedAsset[], paths: Array<string | undefined>) => {
+ paths.forEach((path, index) => {
+ if (path && assets[index]) {
+ assets[index].apply(path);
+ }
+ });
+};
diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.ts
index fb2e83ee26..b8561aeff5 100644
--- a/app/src/protyle/upload/index.ts
+++ b/app/src/protyle/upload/index.ts
@@ -509,7 +509,8 @@ const uploadPreparedFiles = (input: Extract<IAssetUploadInput, { kind: "files" }
if (typeof handlerResult === "string" || handlerResult === null || handlerResult === undefined) {
finishHandler(handlerResult as string | null);
} else {
- void waitForUploadHandler(handlerResult, task.signal).then(finishHandler, failHandler);
+ void waitForUploadHandler(handlerResult, task.signal, undefined,
+ error => task.abort(error)).then(finishHandler, failHandler);
}
} catch (error) {
failHandler(error);
diff --git a/app/src/protyle/upload/pluginEvent.test.ts b/app/src/protyle/upload/pluginEvent.test.ts
index 5898bbe63a..0a715df521 100644
--- a/app/src/protyle/upload/pluginEvent.test.ts
+++ b/app/src/protyle/upload/pluginEvent.test.ts
@@ -464,6 +464,34 @@ describe("asset upload plugin event", () => {
assert.equal(prepared.state, "canceled");
});
+ it("does not cancel later processing when a completed plugin is unloaded", async () => {
+ let resolveDecision: (decision: IAssetUploadDecision) => void;
+ let completedCallbackCalled = false;
+ const completedPlugin = createPlugin(event => {
+ event.detail.onComplete(() => {
+ completedCallbackCalled = true;
+ });
+ });
+ const activePlugin = createPlugin(event => event.detail.respondWith(new Promise(resolve => {
+ resolveDecision = resolve;
+ })));
+ const pending = prepareAssetUpload({
+ plugins: [completedPlugin, activePlugin],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ cancelAssetUploadsByPlugin(completedPlugin);
+ resolveDecision({action: "replace", input: {kind: "files", files: [createFile("b.jpg")]}});
+ const prepared = await pending;
+
+ assert.equal(prepared.state, "ready");
+ assert.equal(prepared.task.signal.aborted, false);
+ prepared.task.complete({status: "success"});
+ assert.equal(completedCallbackCalled, false);
+ });
+
it("does not dispatch a queued plugin unloaded after the active response settles", async () => {
let resolveDecision: (decision: IAssetUploadDecision) => void;
let queuedPluginCalled = false;
@@ -505,6 +533,24 @@ describe("asset upload plugin event", () => {
}
});
+ it("rejects invalid initial input before dispatching plugins", async () => {
+ let pluginCalled = false;
+ const prepared = await prepareAssetUpload({
+ plugins: [createPlugin(() => {
+ pluginCalled = true;
+ })],
+ protyle,
+ input: {kind: "local-files", files: [{path: "", size: 1}]},
+ context,
+ });
+
+ assert.equal(prepared.state, "failed");
+ assert.equal(pluginCalled, false);
+ if (prepared.state === "failed") {
+ assert.match(prepared.error, /non-empty string/);
+ }
+ });
+
it("requires background replacements to contain exactly one file", async () => {
const prepared = await prepareAssetUpload({
plugins: [createPlugin(event => event.detail.respondWith({
diff --git a/app/src/protyle/upload/pluginEvent.ts b/app/src/protyle/upload/pluginEvent.ts
index fcdaf03ce6..81d4000cc8 100644
--- a/app/src/protyle/upload/pluginEvent.ts
+++ b/app/src/protyle/upload/pluginEvent.ts
@@ -13,6 +13,7 @@ export interface IAssetUploadTask {
readonly requestId: string;
readonly signal: AbortSignal;
input: IAssetUploadInput;
+ abort(reason: Error): void;
startUpload(): void;
complete(result: Omit<IAssetUploadResult, "requestId" | "input">): boolean;
}
@@ -43,6 +44,7 @@ let requestSequence = 0;
const waitingTasksByProtyle = new WeakMap<IProtyle, Set<AssetUploadTask>>();
const waitingTasksByPlugin = new WeakMap<IAssetUploadPlugin, Set<AssetUploadTask>>();
const activeTasksByProtyle = new WeakMap<IProtyle, Set<AssetUploadTask>>();
+const completionTasksByPlugin = new WeakMap<IAssetUploadPlugin, Set<AssetUploadTask>>();
const genRequestId = () => {
requestSequence++;
@@ -144,7 +146,10 @@ class AssetUploadTask implements IAssetUploadTask {
public input: IAssetUploadInput;
private completed = false;
private readonly abortController = new AbortController();
- private readonly callbacks: Array<(result: IAssetUploadResult) => any> = [];
+ private readonly callbacks: Array<{
+ plugin: IAssetUploadPlugin;
+ callback: (result: IAssetUploadResult) => any;
+ }> = [];
private readonly protyle?: IProtyle;
private waitingPlugins: IAssetUploadPlugin[] = [];
private uploadStarted = false;
@@ -156,8 +161,23 @@ class AssetUploadTask implements IAssetUploadTask {
this.signal = this.abortController.signal;
}
- public addCompleteCallback(callback: (result: IAssetUploadResult) => void) {
- this.callbacks.push(callback);
+ public addCompleteCallback(plugin: IAssetUploadPlugin, callback: (result: IAssetUploadResult) => void) {
+ this.callbacks.push({plugin, callback});
+ let tasks = completionTasksByPlugin.get(plugin);
+ if (!tasks) {
+ tasks = new Set();
+ completionTasksByPlugin.set(plugin, tasks);
+ }
+ tasks.add(this);
+ }
+
+ public removeCompleteCallbacks(plugin: IAssetUploadPlugin) {
+ for (let index = this.callbacks.length - 1; index >= 0; index--) {
+ if (this.callbacks[index].plugin === plugin) {
+ this.callbacks.splice(index, 1);
+ }
+ }
+ completionTasksByPlugin.get(plugin)?.delete(this);
}
public startWaiting(plugins: IAssetUploadPlugin[]) {
@@ -228,9 +248,11 @@ class AssetUploadTask implements IAssetUploadTask {
if (result.rejected) {
detail.rejected = result.rejected.map(item => ({...item, reasons: Array.from(item.reasons)}));
}
- this.callbacks.forEach(callback => {
+ const callbacks = this.callbacks.splice(0);
+ callbacks.forEach(item => completionTasksByPlugin.get(item.plugin)?.delete(this));
+ callbacks.forEach(item => {
try {
- const callbackResult = callback(cloneResult(detail));
+ const callbackResult = item.callback(cloneResult(detail));
if (callbackResult && typeof callbackResult.then === "function") {
void Promise.resolve(callbackResult).catch(error => console.error(error));
}
@@ -252,6 +274,7 @@ export const cancelAssetUploads = (protyle: IProtyle) => {
};
export const cancelAssetUploadsByPlugin = (plugin: IAssetUploadPlugin) => {
+ Array.from(completionTasksByPlugin.get(plugin) || []).forEach(task => task.removeCompleteCallbacks(plugin));
cancelWaitingTasks(waitingTasksByPlugin.get(plugin), `Plugin ${plugin.name || ""} was unloaded`.trim());
};
@@ -308,7 +331,7 @@ export const prepareAssetUpload = (options: {
task.complete({status: "canceled"});
return {state: "canceled", task};
};
- const initialValidationError = validateTargetInput(task.input, context);
+ const initialValidationError = validateAssetUploadInput(task.input) || validateTargetInput(task.input, context);
if (initialValidationError) {
return fail(initialValidationError);
}
@@ -319,7 +342,6 @@ export const prepareAssetUpload = (options: {
if (plugins.length === 0) {
return {state: "ready", task};
}
- task.startWaiting(plugins);
const processPlugin = (index: number): TPreparedAssetUpload | Promise<TPreparedAssetUpload> => {
if (task.signal.aborted) {
const reason = task.signal.reason instanceof Error ? task.signal.reason.message : "The upload was canceled";
@@ -330,6 +352,7 @@ export const prepareAssetUpload = (options: {
return {state: "ready", task};
}
const plugin = plugins[index];
+ task.startWaiting(plugins.slice(index));
const pluginLabel = getPluginLabel(plugin, index);
let response: PromiseLike<IAssetUploadDecision> | undefined;
let responseClaimed = false;
@@ -369,7 +392,7 @@ export const prepareAssetUpload = (options: {
console.error(new Error(`Plugin ${pluginLabel} must register onComplete synchronously`));
return;
}
- task.addCompleteCallback(callback);
+ task.addCompleteCallback(plugin, callback);
},
});
} catch (error) {
diff --git a/app/src/protyle/upload/uploadHandler.test.ts b/app/src/protyle/upload/uploadHandler.test.ts
index 711eba62be..735f2fd8cb 100644
--- a/app/src/protyle/upload/uploadHandler.test.ts
+++ b/app/src/protyle/upload/uploadHandler.test.ts
@@ -12,7 +12,10 @@ describe("custom upload handler", () => {
});
it("stops waiting after the handler timeout", async () => {
- await assert.rejects(waitForUploadHandler(new Promise<null>(() => undefined),
- new AbortController().signal, 1), AssetUploadHandlerTimeoutError);
+ const controller = new AbortController();
+ await assert.rejects(waitForUploadHandler(new Promise<null>(() => undefined), controller.signal, 1,
+ error => controller.abort(error)), AssetUploadHandlerTimeoutError);
+ assert.equal(controller.signal.aborted, true);
+ assert.equal(controller.signal.reason instanceof AssetUploadHandlerTimeoutError, true);
});
});
diff --git a/app/src/protyle/upload/uploadHandler.ts b/app/src/protyle/upload/uploadHandler.ts
index bb03390ca3..5d391fc7a3 100644
--- a/app/src/protyle/upload/uploadHandler.ts
+++ b/app/src/protyle/upload/uploadHandler.ts
@@ -4,7 +4,8 @@ export class AssetUploadHandlerTimeoutError extends Error {
}
export const waitForUploadHandler = <T>(result: PromiseLike<T>, signal: AbortSignal,
- timeout = ASSET_UPLOAD_HANDLER_TIMEOUT) => {
+ timeout = ASSET_UPLOAD_HANDLER_TIMEOUT,
+ onTimeout?: (error: AssetUploadHandlerTimeoutError) => void) => {
return new Promise<T>((resolve, reject) => {
let settled = false;
const finish = (callback: (value: any) => void, value: any) => {
@@ -18,8 +19,11 @@ export const waitForUploadHandler = <T>(result: PromiseLike<T>, signal: AbortSig
};
const onAbort = () => finish(reject, signal.reason instanceof Error ? signal.reason :
new Error("The upload was canceled"));
- const timeoutId = setTimeout(() => finish(reject,
- new AssetUploadHandlerTimeoutError("Custom upload handler timed out")), timeout);
+ const timeoutId = setTimeout(() => {
+ const error = new AssetUploadHandlerTimeoutError("Custom upload handler timed out");
+ onTimeout?.(error);
+ finish(reject, error);
+ }, timeout);
signal.addEventListener("abort", onAbort, {once: true});
if (signal.aborted) {
onAbort();
diff --git a/app/src/protyle/upload/uploadResult.test.ts b/app/src/protyle/upload/uploadResult.test.ts
index ccd34cddec..ad05de043c 100644
--- a/app/src/protyle/upload/uploadResult.test.ts
+++ b/app/src/protyle/upload/uploadResult.test.ts
@@ -87,6 +87,35 @@ describe("asset upload result", () => {
]);
});
+ it("maps legacy partial successes by unique input names", () => {
+ const acceptedInput: IAssetUploadInput = {
+ kind: "files",
+ files: [createFile("a.png"), createFile("b.png")],
+ };
+ const result = {
+ status: "partial" as const,
+ acceptedInput,
+ succMap: {"b.png": "assets/b.png"},
+ errFiles: ["a.png"],
+ };
+
+ assert.deepEqual(getAssetUploadPathsByInput(2, result), [undefined, "assets/b.png"]);
+ });
+
+ it("does not guess legacy result positions for duplicate input names", () => {
+ const acceptedInput: IAssetUploadInput = {
+ kind: "files",
+ files: [createFile("image.png"), createFile("image.png")],
+ };
+ const result = {
+ status: "partial" as const,
+ acceptedInput,
+ succMap: {"image.png": "assets/image.png"},
+ };
+
+ assert.deepEqual(getAssetUploadPathsByInput(2, result), [undefined, undefined]);
+ });
+
it("preserves successful and failed files from a partial kernel write", () => {
const input: IAssetUploadInput = {
kind: "local-files",
diff --git a/app/src/protyle/upload/uploadResult.ts b/app/src/protyle/upload/uploadResult.ts
index b7a3496465..26c2f61d0b 100644
--- a/app/src/protyle/upload/uploadResult.ts
+++ b/app/src/protyle/upload/uploadResult.ts
@@ -12,7 +12,21 @@ export const getAssetUploadPathsByInput = (inputCount: number,
result: Omit<IAssetUploadResult, "requestId" | "input">) => {
const paths: Array<string | undefined> = new Array(inputCount).fill(undefined);
const rejected = new Set((result.rejected || []).map(item => item.index));
- const succeeded = new Map(getAssetUploadSuccesses(result).map(item => [item.index, item.path]));
+ const succeeded = new Map<number, string>();
+ if (Array.isArray(result.succFiles)) {
+ result.succFiles.forEach(item => succeeded.set(item.index, item.path));
+ } else if (result.succMap && result.acceptedInput) {
+ const names = result.acceptedInput.kind === "files" ?
+ result.acceptedInput.files.map(file => file.name) :
+ result.acceptedInput.files.map(file => file.path.split(/[\\/]/).pop() || "");
+ const nameCounts = new Map<string, number>();
+ names.forEach(name => nameCounts.set(name, (nameCounts.get(name) || 0) + 1));
+ names.forEach((name, index) => {
+ if (nameCounts.get(name) === 1 && Object.prototype.hasOwnProperty.call(result.succMap, name)) {
+ succeeded.set(index, result.succMap[name]);
+ }
+ });
+ }
let acceptedIndex = 0;
for (let inputIndex = 0; inputIndex < inputCount; inputIndex++) {
if (rejected.has(inputIndex)) {
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index 3fcea9170f..9db330d841 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -20,6 +20,7 @@ import {clearBlockElement} from "./clear";
import {removeZWJ} from "./normalizeText";
import {base64ToURL} from "../upload/base64";
import {applyHTMLLocalAssetPaths, collectHTMLLocalAssets} from "../upload/htmlLocalAssets";
+import {applyHTMLEmbeddedAssetPaths, collectHTMLEmbeddedAssets} from "../upload/htmlEmbeddedAssets";
import {getAssetUploadPathsByInput} from "../upload/uploadResult";
import {resolveLinkDest} from "../toolbar/util";
import {updateTransaction} from "../wysiwyg/transaction";
@@ -1063,6 +1064,18 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
}, () => resolve());
});
}
+ const embeddedAssets = collectHTMLEmbeddedAssets(tempElement);
+ if (embeddedAssets.length > 0) {
+ await new Promise<void>(resolve => {
+ uploadFiles(protyle, embeddedAssets.map(item => item.file), undefined, (_response, result) => {
+ applyHTMLEmbeddedAssetPaths(embeddedAssets,
+ getAssetUploadPathsByInput(embeddedAssets.length, result));
+ }, () => resolve(), {
+ ...assetUploadOptions,
+ requiredFileCount: embeddedAssets.length,
+ });
+ });
+ }
fetchPost("/api/lute/html2BlockDOM", {
dom: tempElement.innerHTML,
text: textPlain,
@@ -1071,6 +1084,8 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
officeMathHTML,
wps,
skipLocalAssets: localAssets.length > 0,
+ skipBase64Assets: true,
+ skipInlineSVGAssets: true,
}, (response) => {
insertConvertedBlockDOM(protyle, response.data);
});
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index dca3d0048e..054b5c0e1a 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -466,6 +466,7 @@ interface IBeforeUploadAssetsDetail {
respondWith(response: IAssetUploadDecision | PromiseLike<IAssetUploadDecision>): void,
/**
* 必须同步注册,经思源前端上传协调层发起的资源写入成功、失败或取消时执行一次。
+ * 注册该回调的插件卸载后不再执行。
* 不包含正文或属性视图写入,也不覆盖 HTTP API、CLI、MCP、同步、导入、历史恢复等内核写入。
*/
onComplete(callback: (result: IAssetUploadResult) => void): void
diff --git a/app/src/types/protyle.d.ts b/app/src/types/protyle.d.ts
index 0a97310d88..852ca1fd06 100644
--- a/app/src/types/protyle.d.ts
+++ b/app/src/types/protyle.d.ts
@@ -357,7 +357,7 @@ interface IUpload {
/** 校验,成功时返回 true 否则返回错误信息 */
validate?(files: File[]): string | boolean;
- /** 自定义上传,返回 Promise 时将在其完成后报告上传结果,发生错误时返回错误信息,默认 120 秒超时 */
+ /** 自定义上传,返回 Promise 时将在其完成后报告上传结果,发生错误时返回错误信息,默认 120 秒超时并中止 signal */
handler?(files: File[], options?: { signal: AbortSignal }): string | null | PromiseLike<string | null>;
/** 对服务端返回的数据进行转换,以满足内置的数据结构 */
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index 0891fa28d6..10285a023e 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -111,6 +111,8 @@ func html2BlockDOM(c *gin.Context) {
officeMathHTML, _ := arg["officeMathHTML"].(string)
wps, _ := arg["wps"].(string)
skipLocalAssets, _ := arg["skipLocalAssets"].(bool)
+ skipBase64Assets, _ := arg["skipBase64Assets"].(bool)
+ skipInlineSVGAssets, _ := arg["skipInlineSVGAssets"].(bool)
luteEngine := util.NewLute()
luteEngine.SetHTMLTag2TextMark(true)
luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})
@@ -128,7 +130,10 @@ func html2BlockDOM(c *gin.Context) {
// 将 Word 和 WPS 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748
dom = normalizeWPSComments(dom, text, wps)
dom = normalizeMSWordComments(dom)
- tree, _ := model.HTML2Tree(dom, luteEngine, boxID)
+ tree, _ := model.HTML2TreeWithOptions(dom, luteEngine, boxID, model.HTML2TreeOptions{
+ SkipBase64Assets: skipBase64Assets,
+ SkipInlineSVGAssets: skipInlineSVGAssets,
+ })
if nil == tree {
ret.Data = "Failed to convert"
return
diff --git a/kernel/cli/cmd/asset.go b/kernel/cli/cmd/asset.go
index 59a8e4534c..bfbdc1338b 100644
--- a/kernel/cli/cmd/asset.go
+++ b/kernel/cli/cmd/asset.go
@@ -33,6 +33,41 @@ var assetCmd = &cobra.Command{
Short: "Manage assets",
}
+type assetUploadCommandOutput struct {
+ Status string `json:"status"`
+ Succeeded []model.AssetUploadSuccess `json:"succeeded"`
+ Failed []model.AssetUploadFailure `json:"failed"`
+}
+
+func newAssetUploadCommandOutput(succeeded []model.AssetUploadSuccess,
+ failed []model.AssetUploadFailure) assetUploadCommandOutput {
+ status := "success"
+ if 0 < len(failed) {
+ status = "failed"
+ if 0 < len(succeeded) {
+ status = "partial"
+ }
+ }
+ return assetUploadCommandOutput{Status: status, Succeeded: succeeded, Failed: failed}
+}
+
+func printAssetUploadCommandOutput(result assetUploadCommandOutput) {
+ if outputFormat == "json" {
+ data, _ := json.MarshalIndent(result, "", " ")
+ fmt.Println(string(data))
+ return
+ }
+ w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
+ fmt.Fprintln(w, "STATUS\tFILE\tASSET_PATH\tERROR")
+ for _, item := range result.Succeeded {
+ fmt.Fprintf(w, "success\t%s\t%s\t\n", item.Name, item.Path)
+ }
+ for _, item := range result.Failed {
+ fmt.Fprintf(w, "failed\t%s\t\t%s\n", item.Name, item.Error)
+ }
+ w.Flush()
+}
+
var assetUploadCmd = &cobra.Command{
Use: "upload --id <id> --file <path>",
Short: "Upload files to workspace assets",
@@ -60,25 +95,14 @@ var assetUploadCmd = &cobra.Command{
return nil
}
- succMap, _, failedFiles, err := model.InsertLocalAssets(id, files, true)
+ _, succFiles, failedFiles, err := model.InsertLocalAssets(id, files, true)
if err != nil {
return err
}
+ result := newAssetUploadCommandOutput(succFiles, failedFiles)
+ printAssetUploadCommandOutput(result)
if 0 < len(failedFiles) {
- return fmt.Errorf("upload asset %s failed: %s", failedFiles[0].Name, failedFiles[0].Error)
- }
-
- switch outputFormat {
- case "json":
- data, _ := json.MarshalIndent(succMap, "", " ")
- fmt.Println(string(data))
- default:
- w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
- fmt.Fprintln(w, "FILE\tASSET_PATH")
- for k, v := range succMap {
- fmt.Fprintf(w, "%s\t%v\n", k, v)
- }
- w.Flush()
+ return fmt.Errorf("%d asset upload(s) failed", len(failedFiles))
}
return nil
},
diff --git a/kernel/cli/cmd/asset_test.go b/kernel/cli/cmd/asset_test.go
new file mode 100644
index 0000000000..de96348c65
--- /dev/null
+++ b/kernel/cli/cmd/asset_test.go
@@ -0,0 +1,32 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package cmd
+
+import (
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+func TestNewAssetUploadCommandOutputPreservesPartialResults(t *testing.T) {
+ succeeded := []model.AssetUploadSuccess{{Index: 0, Name: "good.png", Path: "assets/good.png"}}
+ failed := []model.AssetUploadFailure{{Index: 1, Name: "missing.png", Error: "file not found"}}
+
+ result := newAssetUploadCommandOutput(succeeded, failed)
+
+ if result.Status != "partial" {
+ t.Fatalf("status = %q, want partial", result.Status)
+ }
+ if len(result.Succeeded) != 1 || result.Succeeded[0].Path != "assets/good.png" {
+ t.Fatalf("succeeded = %#v", result.Succeeded)
+ }
+ if len(result.Failed) != 1 || result.Failed[0].Name != "missing.png" {
+ t.Fatalf("failed = %#v", result.Failed)
+ }
+}
diff --git a/kernel/mcp/tools/asset.go b/kernel/mcp/tools/asset.go
index 6a88d17f1f..5a9415ed54 100644
--- a/kernel/mcp/tools/asset.go
+++ b/kernel/mcp/tools/asset.go
@@ -192,6 +192,21 @@ func htmlAssetIFrameBlockDOM(assetPath string) (dom, blockID string, err error)
return
}
+func newAssetUploadToolResult(succeeded []model.AssetUploadSuccess, failed []model.AssetUploadFailure) CallToolResult {
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("Uploaded %d file(s):\n", len(succeeded)))
+ for _, result := range succeeded {
+ sb.WriteString(fmt.Sprintf("- %s -> %s\n", result.Name, result.Path))
+ }
+ if 0 < len(failed) {
+ sb.WriteString(fmt.Sprintf("\nFailed %d file(s):\n", len(failed)))
+ for _, result := range failed {
+ sb.WriteString(fmt.Sprintf("- %s: %s\n", result.Name, result.Error))
+ }
+ }
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}, IsError: 0 < len(failed)}
+}
+
func assetUpload(args map[string]any) (CallToolResult, error) {
id, _ := args["id"].(string)
if id == "" {
@@ -211,17 +226,7 @@ func assetUpload(args map[string]any) (CallToolResult, error) {
if err != nil {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "upload assets failed: " + err.Error()}}, IsError: true}, nil
}
- if 0 < len(failedFiles) {
- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "upload asset failed: " +
- failedFiles[0].Name + ": " + failedFiles[0].Error}}, IsError: true}, nil
- }
-
- var sb strings.Builder
- sb.WriteString(fmt.Sprintf("Uploaded %d file(s):\n\n", len(succFiles)))
- for _, result := range succFiles {
- sb.WriteString(fmt.Sprintf("- %s -> %s\n", result.Name, result.Path))
- }
- return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil
+ return newAssetUploadToolResult(succFiles, failedFiles), nil
}
// validateAssetUploadPaths 将上传路径归一化为绝对路径,并拒绝敏感路径,
diff --git a/kernel/mcp/tools/asset_test.go b/kernel/mcp/tools/asset_test.go
index 6d1c5ce842..aa93b21f8b 100644
--- a/kernel/mcp/tools/asset_test.go
+++ b/kernel/mcp/tools/asset_test.go
@@ -14,6 +14,7 @@ import (
"testing"
"github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -81,3 +82,18 @@ func TestValidateAssetUploadPaths(t *testing.T) {
t.Fatal("credential path must be rejected")
}
}
+
+func TestNewAssetUploadToolResultPreservesPartialResults(t *testing.T) {
+ succeeded := []model.AssetUploadSuccess{{Index: 0, Name: "good.png", Path: "assets/good.png"}}
+ failed := []model.AssetUploadFailure{{Index: 1, Name: "missing.png", Error: "file not found"}}
+
+ result := newAssetUploadToolResult(succeeded, failed)
+
+ if !result.IsError {
+ t.Fatal("partial upload result must be marked as an error")
+ }
+ content := result.Content[0].Text
+ if !strings.Contains(content, "good.png -> assets/good.png") || !strings.Contains(content, "missing.png: file not found") {
+ t.Fatalf("partial upload content = %q", content)
+ }
+}
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 9e0a62391f..99b8c24c16 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -87,7 +87,17 @@ func GetImportAssetsDir(boxID, docDirLocalPath string) string {
return globalAssetsDir
}
+type HTML2TreeOptions struct {
+ SkipBase64Assets bool
+ SkipInlineSVGAssets bool
+}
+
func HTML2Tree(htmlStr string, luteEngine *lute.Lute, boxID string) (tree *parse.Tree, withMath bool) {
+ return HTML2TreeWithOptions(htmlStr, luteEngine, boxID, HTML2TreeOptions{})
+}
+
+func HTML2TreeWithOptions(htmlStr string, luteEngine *lute.Lute, boxID string,
+ options HTML2TreeOptions) (tree *parse.Tree, withMath bool) {
htmlStr = gulu.Str.RemovePUA(htmlStr)
assetDirPath := GetImportAssetsDir(boxID, "")
_ = os.MkdirAll(assetDirPath, 0755)
@@ -116,7 +126,7 @@ func HTML2Tree(htmlStr string, luteEngine *lute.Lute, boxID string) (tree *parse
n.AppendChild(c)
}
}
- } else if bytes.Contains(n.Tokens, []byte("<svg")) {
+ } else if !options.SkipInlineSVGAssets && bytes.Contains(n.Tokens, []byte("<svg")) {
processHTMLBlockSvgImg(n, assetDirPath, boxID)
}
}
@@ -130,7 +140,7 @@ func HTML2Tree(htmlStr string, luteEngine *lute.Lute, boxID string) (tree *parse
withMath = true
case ast.NodeLinkDest:
dest := n.TokensStr()
- if strings.HasPrefix(dest, "data:image") && strings.Contains(dest, ";base64,") {
+ if !options.SkipBase64Assets && strings.HasPrefix(dest, "data:image") && strings.Contains(dest, ";base64,") {
processBase64Img(n, dest, assetDirPath, boxID)
}
}
diff --git a/kernel/model/import_test.go b/kernel/model/import_test.go
index 27845ae093..784f263fb1 100644
--- a/kernel/model/import_test.go
+++ b/kernel/model/import_test.go
@@ -165,6 +165,33 @@ func TestHTML2TreeUsesExistingNotebookAssets(t *testing.T) {
}
}
+func TestHTML2TreeCanSkipEmbeddedAssetWrites(t *testing.T) {
+ originalDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = originalDataDir
+ })
+
+ boxID := "20260826000000-htmlimg"
+ boxAssetsDir := filepath.Join(util.DataDir, boxID, "assets")
+ if err := os.MkdirAll(boxAssetsDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ options := HTML2TreeOptions{SkipBase64Assets: true, SkipInlineSVGAssets: true}
+ HTML2TreeWithOptions(`<img alt="diagram" src="data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=">`,
+ util.NewLute(), boxID, options)
+ HTML2TreeWithOptions(`<pre class="language-html"><svg><rect width="1" height="1"></rect></svg></pre>`,
+ util.NewLute(), boxID, options)
+
+ entries, err := os.ReadDir(boxAssetsDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 0 {
+ t.Fatalf("notebook assets count = %d, want 0", len(entries))
+ }
+}
+
func TestHTML2TreeUsesBase64ImageContentType(t *testing.T) {
originalDataDir := util.DataDir
util.DataDir = t.TempDir()