Skip to content

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

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

Daniel740b5685bb50
diff --git a/app/src/plugin/EventBus.test.ts b/app/src/plugin/EventBus.test.ts
new file mode 100644
index 0000000000..3b4ba3b7da
--- /dev/null
+++ b/app/src/plugin/EventBus.test.ts
@@ -0,0 +1,56 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {EventBus} from "./EventBusCore";
+
+describe("plugin EventBus", () => {
+ it("preserves on, once, and off behavior", () => {
+ const eventBus = new EventBus<{ value: number }>("", new EventTarget());
+ let persistentCount = 0;
+ let onceCount = 0;
+ const persistentListener = (event: CustomEvent<{ value: number }>) => {
+ persistentCount += event.detail.value;
+ };
+ eventBus.on("before-upload-assets", persistentListener);
+ eventBus.once("before-upload-assets", () => {
+ onceCount++;
+ });
+
+ eventBus.emit("before-upload-assets", {value: 1});
+ eventBus.emit("before-upload-assets", {value: 1});
+ eventBus.off("before-upload-assets", persistentListener);
+ eventBus.emit("before-upload-assets", {value: 1});
+
+ assert.equal(persistentCount, 2);
+ assert.equal(onceCount, 1);
+ });
+
+ it("captures synchronous listener errors during safe dispatch", () => {
+ const eventBus = new EventBus("", new EventTarget());
+ let laterListenerCalled = false;
+ eventBus.on("before-upload-assets", () => {
+ throw new Error("listener failed");
+ });
+ eventBus.on("before-upload-assets", () => {
+ laterListenerCalled = true;
+ });
+
+ const result = eventBus.emitWithErrors("before-upload-assets");
+
+ assert.equal((result.error as Error).message, "listener failed");
+ assert.equal(laterListenerCalled, false);
+ });
+
+ it("reports prevention and asynchronous listeners during safe dispatch", async () => {
+ const eventBus = new EventBus("", new EventTarget());
+ eventBus.on("before-upload-assets", async event => {
+ event.preventDefault();
+ await Promise.resolve();
+ });
+
+ const result = eventBus.emitWithErrors("before-upload-assets");
+ await Promise.resolve();
+
+ assert.equal(result.defaultPrevented, true);
+ assert.equal(result.hasAsyncListener, true);
+ });
+});
diff --git a/app/src/plugin/EventBus.ts b/app/src/plugin/EventBus.ts
index d21ef133d6..9f2fe9a720 100644
--- a/app/src/plugin/EventBus.ts
+++ b/app/src/plugin/EventBus.ts
@@ -1,28 +1,6 @@
import {MenuItem, subMenu} from "../menus/Menu";
-
-export class EventBus<DetailType = any> {
- private eventTarget: EventTarget;
-
- constructor(name = "") {
- this.eventTarget = document.appendChild(document.createComment(name));
- }
-
- on(type: TEventBus, listener: (event: CustomEvent<DetailType>) => void) {
- this.eventTarget.addEventListener(type, listener);
- }
-
- once(type: TEventBus, listener: (event: CustomEvent<DetailType>) => void) {
- this.eventTarget.addEventListener(type, listener, {once: true});
- }
-
- off(type: TEventBus, listener: (event: CustomEvent<DetailType>) => void) {
- this.eventTarget.removeEventListener(type, listener);
- }
-
- emit(type: TEventBus, detail?: DetailType) {
- return this.eventTarget.dispatchEvent(new CustomEvent(type, {detail, cancelable: true}));
- }
-}
+export {EventBus} from "./EventBusCore";
+export type {IEventBusSafeEmitResult} from "./EventBusCore";
export const emitOpenMenu = (options: {
plugins: import("./index").Plugin[],
diff --git a/app/src/plugin/EventBusCore.ts b/app/src/plugin/EventBusCore.ts
new file mode 100644
index 0000000000..65ae6385e8
--- /dev/null
+++ b/app/src/plugin/EventBusCore.ts
@@ -0,0 +1,92 @@
+interface IEventBusListener<DetailType> {
+ listener: (event: CustomEvent<DetailType>) => any;
+ wrapped: EventListener;
+ once: boolean;
+}
+
+export interface IEventBusSafeEmitResult {
+ defaultPrevented: boolean;
+ error?: unknown;
+ hasAsyncListener: boolean;
+}
+
+export class EventBus<DetailType = any> {
+ private eventTarget: EventTarget;
+ private listeners = new Map<TEventBus, Map<(event: CustomEvent<DetailType>) => any, IEventBusListener<DetailType>>>();
+ private safeDispatches = new WeakMap<Event, IEventBusSafeEmitResult>();
+
+ constructor(name = "", eventTarget?: EventTarget) {
+ this.eventTarget = eventTarget || document.appendChild(document.createComment(name));
+ }
+
+ private addListener(type: TEventBus, listener: (event: CustomEvent<DetailType>) => any, once: boolean) {
+ let typeListeners = this.listeners.get(type);
+ if (!typeListeners) {
+ typeListeners = new Map();
+ this.listeners.set(type, typeListeners);
+ }
+ if (typeListeners.has(listener)) {
+ return;
+ }
+ const wrapped: EventListener = (event) => {
+ if (once) {
+ this.off(type, listener);
+ }
+ const safeResult = this.safeDispatches.get(event);
+ try {
+ const result = listener.call(this.eventTarget, event as CustomEvent<DetailType>);
+ if (safeResult && result && typeof result.then === "function") {
+ safeResult.hasAsyncListener = true;
+ void Promise.resolve(result).catch(listenerError => console.error(listenerError));
+ }
+ return result;
+ } catch (error) {
+ if (!safeResult) {
+ throw error;
+ }
+ safeResult.error = error;
+ event.stopImmediatePropagation();
+ }
+ };
+ typeListeners.set(listener, {listener, wrapped, once});
+ this.eventTarget.addEventListener(type, wrapped);
+ }
+
+ on(type: TEventBus, listener: (event: CustomEvent<DetailType>) => any) {
+ this.addListener(type, listener, false);
+ }
+
+ once(type: TEventBus, listener: (event: CustomEvent<DetailType>) => any) {
+ this.addListener(type, listener, true);
+ }
+
+ off(type: TEventBus, listener: (event: CustomEvent<DetailType>) => any) {
+ const typeListeners = this.listeners.get(type);
+ const registered = typeListeners?.get(listener);
+ if (!registered) {
+ return;
+ }
+ this.eventTarget.removeEventListener(type, registered.wrapped);
+ typeListeners.delete(listener);
+ if (typeListeners.size === 0) {
+ this.listeners.delete(type);
+ }
+ }
+
+ emit(type: TEventBus, detail?: DetailType) {
+ return this.eventTarget.dispatchEvent(new CustomEvent(type, {detail, cancelable: true}));
+ }
+
+ emitWithErrors(type: TEventBus, detail?: DetailType): IEventBusSafeEmitResult {
+ const event = new CustomEvent(type, {detail, cancelable: true});
+ const result: IEventBusSafeEmitResult = {defaultPrevented: false, hasAsyncListener: false};
+ this.safeDispatches.set(event, result);
+ try {
+ this.eventTarget.dispatchEvent(event);
+ } finally {
+ this.safeDispatches.delete(event);
+ }
+ result.defaultPrevented = event.defaultPrevented;
+ return result;
+ }
+}
diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.ts
index d704b7decb..3967c1a91a 100644
--- a/app/src/plugin/uninstall.ts
+++ b/app/src/plugin/uninstall.ts
@@ -12,10 +12,12 @@ import {Constants} from "../constants";
import {setStorageVal} from "../protyle/util/compatibility";
import {getAllEditor} from "../layout/getAll";
import {unregisterCapability} from "../layout/dock/agent/frontendCapabilities";
+import {cancelAssetUploadsByPlugin} from "../protyle/upload/pluginEvent";
export const uninstall = (app: App, name: string, isReload: boolean) => {
app.plugins.find((plugin: Plugin, index) => {
if (plugin.name === name) {
+ cancelAssetUploadsByPlugin(plugin);
try {
plugin.onunload();
} catch (e) {
diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.ts
index d54dd4ee91..69dd5ce4b3 100644
--- a/app/src/protyle/upload/index.ts
+++ b/app/src/protyle/upload/index.ts
@@ -24,6 +24,7 @@ import {
type IAssetUploadTask,
prepareAssetUpload,
} from "./pluginEvent";
+import {getAssetUploadResult} from "./uploadResult";
interface FileWithPath extends File {
path: string;
@@ -50,21 +51,25 @@ export class Upload {
const validateFile = (protyle: IProtyle, files: File[]) => {
const uploadFileList = [];
+ const rejected: IAssetUploadRejection[] = [];
let errorTip = "";
let uploadingStr = "";
for (let iMax = files.length, i = 0; i < iMax; i++) {
const file = files[i];
let validate = true;
+ const reasons: TAssetUploadRejectionReason[] = [];
if (!file.name) {
errorTip += `<li>${window.siyuan.languages.nameEmpty}</li>`;
validate = false;
+ reasons.push("name-empty");
}
if (file.size > protyle.options.upload.max) {
errorTip += `<li>${escapeHtml(file.name)} ${window.siyuan.languages.over} ${protyle.options.upload.max / 1024 / 1024}M</li>`;
validate = false;
+ reasons.push("size-limit");
}
const lastIndex = file.name.lastIndexOf(".");
@@ -89,12 +94,15 @@ const validateFile = (protyle: IProtyle, files: File[]) => {
if (!isAccept) {
errorTip += `<li>${escapeHtml(file.name)} ${window.siyuan.languages.fileTypeError}</li>`;
validate = false;
+ reasons.push("type-not-accepted");
}
}
if (validate) {
uploadFileList.push(file);
uploadingStr += `<li>${escapeHtml(filename)} ${window.siyuan.languages.uploading}</li>`;
+ } else {
+ rejected.push({index: i, name: file.name, reasons});
}
}
let msgId;
@@ -102,7 +110,7 @@ const validateFile = (protyle: IProtyle, files: File[]) => {
msgId = showMessage(`<ul>${errorTip}${uploadingStr}</ul>`, -1);
}
- return {files: uploadFileList, msgId};
+ return {files: uploadFileList, rejected, msgId};
};
const genUploadedLabel = async (responseText: string, protyle: IProtyle, options?: IUploadInsertOptions) => {
@@ -197,7 +205,7 @@ const genUploadedLabel = async (responseText: string, protyle: IProtyle, options
if (cellElements.length > 0) {
const blockElement = hasClosestBlock(cellElements[0]);
if (blockElement) {
- updateCellsValue(protyle, blockElement, avAssets, cellElements);
+ await updateCellsValue(protyle, blockElement, avAssets, cellElements);
document.querySelector(".av__panel")?.remove();
return;
}
@@ -225,7 +233,7 @@ const genUploadedLabel = async (responseText: string, protyle: IProtyle, options
}
const stableCells = stableCellCandidates.length > cellElements.length ? stableCellCandidates : [];
if (stableCells.length === 1 || cellElements.length === 1) {
- updateCellsValue(protyle, nodeElement, avAssets, cellElements, undefined, undefined,
+ await updateCellsValue(protyle, nodeElement, avAssets, cellElements, undefined, undefined,
false, false, false, stableCells);
} else if (stableCells.length > 1 || cellElements.length > 1) {
const doOperations: IOperation[] = [];
@@ -299,7 +307,8 @@ export const getUploadInsertRange = (protyle: IProtyle, position?: IUploadInsert
};
interface IAssetUploadCallbacks {
- success(responseText: string, response: IWebSocketData | undefined, input: IAssetUploadInput): void;
+ success(responseText: string, response: IWebSocketData | undefined,
+ input: IAssetUploadInput): void | PromiseLike<void>;
complete?: (succeeded: boolean) => void;
reset?: () => void;
}
@@ -335,27 +344,17 @@ const getErrorMessage = (error: unknown) => {
return typeof error === "string" ? error : "";
};
-const getUploadResult = (responseText: string, input: IAssetUploadInput):
-Omit<IAssetUploadResult, "requestId" | "input"> => {
+const finishCallbacks = (callbacks: IAssetUploadCallbacks, succeeded: boolean) => {
try {
- const response = JSON.parse(responseText);
- const succMap = response.data?.succMap as Record<string, string> | undefined;
- const errFiles = response.data?.errFiles as string[] | undefined;
- if (typeof response.code === "number" && response.code !== 0) {
- return {status: "failed", succMap, errFiles, error: String(response.msg || "")};
- }
- if (succMap) {
- const expected = input.files.length;
- const succeeded = input.kind === "files" ?
- input.files.filter(file => succMap[file.name]).length : Object.keys(succMap).length;
- const status = succeeded === expected && !errFiles?.length ? "success" :
- succeeded > 0 ? "partial" : "failed";
- return {status, succMap, errFiles};
- }
+ callbacks.complete?.(succeeded);
} catch (error) {
- // 自定义上传接口不一定返回 JSON,HTTP 200 仍视为成功。
+ console.error(error);
+ }
+ try {
+ callbacks.reset?.();
+ } catch (error) {
+ console.error(error);
}
- return {status: "success"};
};
const finishUpload = (task: IAssetUploadTask | undefined, callbacks: IAssetUploadCallbacks,
@@ -363,22 +362,37 @@ const finishUpload = (task: IAssetUploadTask | undefined, callbacks: IAssetUploa
if (task && !task.complete(result)) {
return;
}
- callbacks.complete?.(result.status === "success");
- callbacks.reset?.();
+ finishCallbacks(callbacks, result.status === "success");
};
const finishSuccessfulUpload = (task: IAssetUploadTask | undefined, callbacks: IAssetUploadCallbacks,
responseText: string, response: IWebSocketData | undefined,
input: IAssetUploadInput,
result: Omit<IAssetUploadResult, "requestId" | "input">) => {
+ if (task && !task.complete(result)) {
+ return;
+ }
try {
- callbacks.success(responseText, response, input);
- finishUpload(task, callbacks, result);
+ const callbackResult = callbacks.success(responseText, response, input);
+ if (callbackResult && typeof callbackResult.then === "function") {
+ void Promise.resolve(callbackResult).catch(error => {
+ console.error(error);
+ try {
+ showMessage(getErrorMessage(error) || window.siyuan.languages.uploadError);
+ } catch (messageError) {
+ console.error(messageError);
+ }
+ });
+ }
} catch (error) {
console.error(error);
- const errorMessage = getErrorMessage(error);
- showMessage(errorMessage || window.siyuan.languages.uploadError);
- finishUpload(task, callbacks, {status: "failed", error: errorMessage});
+ try {
+ showMessage(getErrorMessage(error) || window.siyuan.languages.uploadError);
+ } catch (messageError) {
+ console.error(messageError);
+ }
+ } finally {
+ finishCallbacks(callbacks, result.status === "success");
}
};
@@ -396,12 +410,13 @@ const uploadPreparedLocalFiles = (input: Extract<IAssetUploadInput, { kind: "loc
confirmDialog(msg ? window.siyuan.languages.upload : "", msg, () => {
void (async () => {
- if (!document.body.contains(protyle.element)) {
- finishUpload(task, callbacks, {status: "canceled"});
- return;
- }
- const msgId = showMessage(window.siyuan.languages.uploading, 0);
+ let msgId: string | undefined;
try {
+ if (!document.body.contains(protyle.element)) {
+ finishUpload(task, callbacks, {status: "canceled"});
+ return;
+ }
+ msgId = showMessage(window.siyuan.languages.uploading, 0);
const response = await fetchSyncPost("/api/asset/insertLocalAssets", {
assetPaths,
isUpload,
@@ -427,12 +442,18 @@ const uploadPreparedLocalFiles = (input: Extract<IAssetUploadInput, { kind: "loc
}
const responseText = JSON.stringify(response);
finishSuccessfulUpload(task, callbacks, responseText, response, input,
- getUploadResult(responseText, input));
+ getAssetUploadResult(responseText, input));
} catch (error) {
- hideMessage(msgId);
const errorMessage = getErrorMessage(error);
- showMessage(errorMessage || window.siyuan.languages["_kernel"][28]);
finishUpload(task, callbacks, {status: "failed", error: errorMessage});
+ try {
+ if (msgId) {
+ hideMessage(msgId);
+ }
+ showMessage(errorMessage || window.siyuan.languages["_kernel"][28]);
+ } catch (messageError) {
+ console.error(messageError);
+ }
}
})();
}, () => {
@@ -451,11 +472,11 @@ const uploadPreparedFiles = (input: Extract<IAssetUploadInput, { kind: "files" }
finishUpload(task, callbacks, {status: "failed", error: isValidate});
return;
}
- finishUpload(task, callbacks, {status: "success"});
+ finishUpload(task, callbacks, {status: "success", acceptedInput: input});
} catch (error) {
const errorMessage = getErrorMessage(error);
- showMessage(errorMessage || window.siyuan.languages.uploadError);
finishUpload(task, callbacks, {status: "failed", error: errorMessage});
+ showMessage(errorMessage || window.siyuan.languages.uploadError);
}
return;
}
@@ -476,11 +497,14 @@ const uploadPreparedFiles = (input: Extract<IAssetUploadInput, { kind: "files" }
}
const validateResult = validateFile(protyle, fileList);
if (validateResult.files.length === 0) {
- finishUpload(task, callbacks, {status: "failed"});
+ finishUpload(task, callbacks, {
+ status: "failed",
+ acceptedInput: {kind: "files", files: []},
+ rejected: validateResult.rejected,
+ });
return;
}
const uploadedInput: IAssetUploadInput = {kind: "files", files: validateResult.files};
- task.input = uploadedInput;
const formData = new FormData();
const extraData = protyle.options.upload.extraData;
@@ -500,110 +524,144 @@ const uploadPreparedFiles = (input: Extract<IAssetUploadInput, { kind: "files" }
formData.append("id", protyle.block?.rootID);
}
confirmDialog(msg ? window.siyuan.languages.upload : "", msg, () => {
- const xhr = new XMLHttpRequest();
- xhr.open("POST", protyle.options.upload.url);
- if (protyle.options.upload.token) {
- xhr.setRequestHeader("X-Upload-Token", protyle.options.upload.token);
- }
- if (protyle.options.upload.withCredentials) {
- xhr.withCredentials = true;
- }
+ try {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", protyle.options.upload.url);
+ if (protyle.options.upload.token) {
+ xhr.setRequestHeader("X-Upload-Token", protyle.options.upload.token);
+ }
+ if (protyle.options.upload.withCredentials) {
+ xhr.withCredentials = true;
+ }
- protyle.upload.isUploading = true;
- xhr.onreadystatechange = () => {
- if (xhr.readyState === XMLHttpRequest.DONE) {
- protyle.upload.isUploading = false;
- hideMessage(validateResult.msgId);
- if (!document.body.contains(protyle.element)) {
- // 网络较慢时,页签已经关闭
- destroy(protyle);
- finishUpload(task, callbacks, {status: "canceled"});
+ protyle.upload.isUploading = true;
+ xhr.onreadystatechange = () => {
+ if (xhr.readyState !== XMLHttpRequest.DONE) {
return;
}
- if (xhr.status === 200) {
- let response: IWebSocketData;
- try {
- response = JSON.parse(xhr.responseText);
- } catch (error) {
- response = undefined;
+ try {
+ protyle.upload.isUploading = false;
+ hideMessage(validateResult.msgId);
+ if (!document.body.contains(protyle.element)) {
+ // 网络较慢时,页签已经关闭
+ destroy(protyle);
+ finishUpload(task, callbacks, {status: "canceled"});
+ return;
}
- finishSuccessfulUpload(task, callbacks, xhr.responseText, response, uploadedInput,
- getUploadResult(xhr.responseText, uploadedInput));
- } else if (xhr.status === 0) {
- showMessage(window.siyuan.languages["_kernel"][28]);
- finishUpload(task, callbacks, {status: "failed"});
- } else {
- if (protyle.options.upload.error) {
- protyle.options.upload.error(xhr.responseText);
+ if (xhr.status === 200) {
+ let response: IWebSocketData;
+ try {
+ response = JSON.parse(xhr.responseText);
+ } catch (error) {
+ response = undefined;
+ }
+ finishSuccessfulUpload(task, callbacks, xhr.responseText, response, uploadedInput,
+ getAssetUploadResult(xhr.responseText, uploadedInput, validateResult.rejected));
+ } else if (xhr.status === 0) {
+ showMessage(window.siyuan.languages["_kernel"][28]);
+ finishUpload(task, callbacks, {status: "failed"});
} else {
- showMessage(xhr.responseText);
+ if (protyle.options.upload.error) {
+ protyle.options.upload.error(xhr.responseText);
+ } else {
+ showMessage(xhr.responseText);
+ }
+ finishUpload(task, callbacks, {status: "failed", error: xhr.responseText});
}
- finishUpload(task, callbacks, {status: "failed", error: xhr.responseText});
+ } catch (error) {
+ const errorMessage = getErrorMessage(error);
+ console.error(error);
+ finishUpload(task, callbacks, {status: "failed", error: errorMessage});
+ showMessage(errorMessage || window.siyuan.languages.uploadError);
+ } finally {
+ protyle.upload.element.style.display = "none";
}
- protyle.upload.element.style.display = "none";
- }
- };
- xhr.upload.onprogress = (event: ProgressEvent) => {
- if (!event.lengthComputable) {
- return;
- }
- const progress = event.loaded / event.total * 100;
- protyle.upload.element.style.display = "block";
- const progressBar = protyle.upload.element;
- progressBar.style.width = progress + "%";
- };
- try {
+ };
+ xhr.upload.onprogress = (event: ProgressEvent) => {
+ if (!event.lengthComputable) {
+ return;
+ }
+ const progress = event.loaded / event.total * 100;
+ protyle.upload.element.style.display = "block";
+ const progressBar = protyle.upload.element;
+ progressBar.style.width = progress + "%";
+ };
xhr.send(formData);
} catch (error) {
- protyle.upload.isUploading = false;
- hideMessage(validateResult.msgId);
const errorMessage = getErrorMessage(error);
- showMessage(errorMessage || window.siyuan.languages.uploadError);
finishUpload(task, callbacks, {status: "failed", error: errorMessage});
+ try {
+ protyle.upload.isUploading = false;
+ hideMessage(validateResult.msgId);
+ showMessage(errorMessage || window.siyuan.languages.uploadError);
+ } catch (messageError) {
+ console.error(messageError);
+ }
}
}, () => {
- hideMessage(validateResult.msgId);
- finishUpload(task, callbacks, {status: "canceled"});
+ try {
+ hideMessage(validateResult.msgId);
+ } catch (error) {
+ console.error(error);
+ } finally {
+ finishUpload(task, callbacks, {status: "canceled"});
+ }
});
};
const startPreparedAssetUpload = (prepared: Awaited<ReturnType<typeof prepareAssetUpload>>, protyle: IProtyle,
callbacks: IAssetUploadCallbacks) => {
if (prepared.state !== "ready") {
+ finishCallbacks(callbacks, false);
if (prepared.state === "failed") {
showMessage(prepared.error || window.siyuan.languages.uploadError);
}
- callbacks.complete?.(false);
- callbacks.reset?.();
- return;
- }
- if (prepared.task.input.files.length === 0) {
- finishUpload(prepared.task, callbacks, {status: "canceled"});
- return;
- }
- if (!document.body.contains(protyle.element)) {
- finishUpload(prepared.task, callbacks, {status: "canceled"});
return;
}
- if (prepared.task.input.kind === "files") {
- uploadPreparedFiles(prepared.task.input, protyle, callbacks, prepared.task);
- } else {
- uploadPreparedLocalFiles(prepared.task.input, protyle, true, callbacks, prepared.task);
+ try {
+ if (prepared.task.input.files.length === 0) {
+ finishUpload(prepared.task, callbacks, {status: "canceled"});
+ return;
+ }
+ if (!document.body.contains(protyle.element)) {
+ finishUpload(prepared.task, callbacks, {status: "canceled"});
+ return;
+ }
+ if (prepared.task.input.kind === "files") {
+ uploadPreparedFiles(prepared.task.input, protyle, callbacks, prepared.task);
+ } else {
+ uploadPreparedLocalFiles(prepared.task.input, protyle, true, callbacks, prepared.task);
+ }
+ } catch (error) {
+ const errorMessage = getErrorMessage(error);
+ console.error(error);
+ finishUpload(prepared.task, callbacks, {status: "failed", error: errorMessage});
+ showMessage(errorMessage || window.siyuan.languages.uploadError);
}
};
const startAssetUpload = (input: IAssetUploadInput, protyle: IProtyle, options: IUploadInsertOptions,
callbacks: IAssetUploadCallbacks) => {
- const prepared = prepareAssetUpload({
- plugins: protyle.app?.plugins || [],
- protyle,
- input,
- context: getAssetUploadContext(options),
- });
- if (prepared instanceof Promise) {
- void prepared.then(result => startPreparedAssetUpload(result, protyle, callbacks));
- } else {
- startPreparedAssetUpload(prepared, protyle, callbacks);
+ try {
+ const prepared = prepareAssetUpload({
+ plugins: [...(protyle.app?.plugins || [])],
+ protyle,
+ input,
+ context: getAssetUploadContext(options),
+ });
+ if (prepared instanceof Promise) {
+ void prepared.then(result => startPreparedAssetUpload(result, protyle, callbacks)).catch(error => {
+ console.error(error);
+ finishCallbacks(callbacks, false);
+ showMessage(getErrorMessage(error) || window.siyuan.languages.uploadError);
+ });
+ } else {
+ startPreparedAssetUpload(prepared, protyle, callbacks);
+ }
+ } catch (error) {
+ console.error(error);
+ finishCallbacks(callbacks, false);
+ showMessage(getErrorMessage(error) || window.siyuan.languages.uploadError);
}
};
@@ -614,9 +672,9 @@ export const uploadLocalFiles = (files: ILocalFiles[], protyle: IProtyle, isUplo
const callbacks: IAssetUploadCallbacks = {
success(responseText, response) {
if (successCB) {
- successCB(response);
+ return successCB(response);
} else {
- genUploadedLabel(responseText, protyle, uploadOptions);
+ return genUploadedLabel(responseText, protyle, uploadOptions);
}
},
complete: completeCB,
@@ -693,14 +751,14 @@ export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferIte
const callbacks: IAssetUploadCallbacks = {
success(responseText, response, input) {
if (protyle.options.upload.success) {
- protyle.options.upload.success(protyle.wysiwyg.element, responseText);
+ return protyle.options.upload.success(protyle.wysiwyg.element, responseText);
} else if (successCB) {
- successCB(responseText);
+ return successCB(responseText);
} else {
if (protyle.options.upload.format && input.kind === "files") {
responseText = protyle.options.upload.format(input.files, responseText);
}
- genUploadedLabel(responseText, protyle, uploadOptions);
+ return genUploadedLabel(responseText, protyle, uploadOptions);
}
},
complete: completeCB,
diff --git a/app/src/protyle/upload/localDropFiles.test.ts b/app/src/protyle/upload/localDropFiles.test.ts
new file mode 100644
index 0000000000..5bc8aba71d
--- /dev/null
+++ b/app/src/protyle/upload/localDropFiles.test.ts
@@ -0,0 +1,21 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {getLocalDropFiles} from "./localDropFiles";
+
+const createFile = (name: string) => new File(["content"], name);
+
+describe("local drop files", () => {
+ it("returns every local file when all paths are available", () => {
+ const files = [createFile("a.png"), createFile("b.png")];
+ const result = getLocalDropFiles(files, file => `C:/${file.name}`);
+
+ assert.deepEqual(result?.map(item => item.path), ["C:/a.png", "C:/b.png"]);
+ });
+
+ it("returns no local batch when any path is unavailable", () => {
+ const files = [createFile("a.png"), createFile("b.png")];
+ const result = getLocalDropFiles(files, file => file.name === "a.png" ? "C:/a.png" : "");
+
+ assert.equal(result, undefined);
+ });
+});
diff --git a/app/src/protyle/upload/localDropFiles.ts b/app/src/protyle/upload/localDropFiles.ts
new file mode 100644
index 0000000000..852e32a640
--- /dev/null
+++ b/app/src/protyle/upload/localDropFiles.ts
@@ -0,0 +1,16 @@
+export const getLocalDropFiles = (files: FileList | File[], getPath: (file: File) => string) => {
+ const localFiles: ILocalFiles[] = [];
+ for (let index = 0; index < files.length; index++) {
+ const file = files[index];
+ const path = getPath(file);
+ if (!path) {
+ return undefined;
+ }
+ localFiles.push({
+ path,
+ size: file.size,
+ isDir: file.size === 0 && file.type === "" && !file.name.includes("."),
+ });
+ }
+ return localFiles;
+};
diff --git a/app/src/protyle/upload/pluginEvent.test.ts b/app/src/protyle/upload/pluginEvent.test.ts
index 7c13e01b9a..1852154950 100644
--- a/app/src/protyle/upload/pluginEvent.test.ts
+++ b/app/src/protyle/upload/pluginEvent.test.ts
@@ -1,26 +1,20 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {prepareAssetUpload} from "./pluginEvent";
+import {EventBus} from "../../plugin/EventBusCore";
+import {cancelAssetUploads, cancelAssetUploadsByPlugin, prepareAssetUpload} from "./pluginEvent";
type TListener = (event: CustomEvent<IBeforeUploadAssetsDetail>) => void;
const createPlugin = (listener: TListener) => ({
- eventBus: {
- emit(type: TEventBus, detail: IBeforeUploadAssetsDetail) {
- assert.equal(type, "before-upload-assets");
- let canceled = false;
- listener({
- detail,
- preventDefault() {
- canceled = true;
- },
- } as CustomEvent<IBeforeUploadAssetsDetail>);
- return !canceled;
- },
- },
+ name: "test-plugin",
+ eventBus: (() => {
+ const eventBus = new EventBus<IBeforeUploadAssetsDetail>("", new EventTarget());
+ eventBus.on("before-upload-assets", listener);
+ return eventBus;
+ })(),
});
-const createFile = (name: string) => ({name}) as File;
+const createFile = (name: string) => new File(["content"], name, {type: "image/png"});
const protyle = {} as IProtyle;
const context = {source: "paste", target: "editor"} as const;
@@ -81,7 +75,7 @@ describe("asset upload plugin event", () => {
let laterPluginCalled = false;
const prepared = await prepareAssetUpload({
plugins: [
- createPlugin(event => event.preventDefault()),
+ createPlugin(event => event.detail.respondWith({action: "cancel"})),
createPlugin(() => {
laterPluginCalled = true;
}),
@@ -95,6 +89,20 @@ describe("asset upload plugin event", () => {
assert.equal(laterPluginCalled, false);
});
+ it("rejects preventDefault as a protocol error", async () => {
+ const prepared = await prepareAssetUpload({
+ plugins: [createPlugin(event => event.preventDefault())],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ assert.equal(prepared.state, "failed");
+ if (prepared.state === "failed") {
+ assert.match(prepared.error, /must use respondWith/);
+ }
+ });
+
it("supports asynchronous cancellation", async () => {
const results: IAssetUploadResult[] = [];
const prepared = await prepareAssetUpload({
@@ -131,12 +139,40 @@ describe("asset upload plugin event", () => {
prepared.task.complete({status: "success", succMap: {"a.jpg": "assets/a.jpg"}});
prepared.task.complete({status: "failed"});
- assert.deepEqual(results, [{
- requestId: "request-2",
- status: "success",
- input: {kind: "files", files: [createFile("a.jpg")]},
- succMap: {"a.jpg": "assets/a.jpg"},
- }]);
+ assert.equal(results.length, 1);
+ assert.equal(results[0].requestId, "request-2");
+ assert.equal(results[0].status, "success");
+ assert.equal(results[0].input.kind, "files");
+ assert.equal((results[0].input.files[0] as File).name, "a.jpg");
+ assert.deepEqual(results[0].succMap, {"a.jpg": "assets/a.jpg"});
+ });
+
+ it("preserves the full input when only an accepted subset is uploaded", async () => {
+ const results: IAssetUploadResult[] = [];
+ const acceptedFile = createFile("a.jpg");
+ const rejectedFile = createFile("b.exe");
+ const prepared = await prepareAssetUpload({
+ plugins: [createPlugin(event => {
+ event.detail.onComplete(result => results.push(result));
+ event.detail.respondWith({
+ action: "replace",
+ input: {kind: "files", files: [acceptedFile, rejectedFile]},
+ });
+ })],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ prepared.task.complete({
+ status: "partial",
+ acceptedInput: {kind: "files", files: [acceptedFile]},
+ rejected: [{index: 1, name: rejectedFile.name, reasons: ["type-not-accepted"]}],
+ });
+
+ assert.equal(results[0].input.files.length, 2);
+ assert.equal(results[0].acceptedInput.files.length, 1);
+ assert.equal(results[0].rejected[0].index, 1);
});
it("reports rejected processing as a failure", async () => {
@@ -158,4 +194,168 @@ describe("asset upload plugin event", () => {
assert.equal(results[0].status, "failed");
assert.equal(results[0].error, "compression failed");
});
+
+ it("fails closed when a listener throws synchronously", async () => {
+ let laterPluginCalled = false;
+ const prepared = await prepareAssetUpload({
+ plugins: [
+ createPlugin(() => {
+ throw new Error("compression crashed");
+ }),
+ createPlugin(() => {
+ laterPluginCalled = true;
+ }),
+ ],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ assert.equal(prepared.state, "failed");
+ assert.equal(laterPluginCalled, false);
+ if (prepared.state === "failed") {
+ assert.match(prepared.error, /test-plugin.*compression crashed/);
+ }
+ });
+
+ it("rejects an async listener that does not claim the request synchronously", async () => {
+ const originalConsoleError = console.error;
+ console.error = () => undefined;
+ try {
+ const prepared = await prepareAssetUpload({
+ plugins: [createPlugin(async event => {
+ await Promise.resolve();
+ event.detail.respondWith({action: "cancel"});
+ })],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ assert.equal(prepared.state, "failed");
+ if (prepared.state === "failed") {
+ assert.match(prepared.error, /must call respondWith synchronously/);
+ }
+ await new Promise(resolve => setTimeout(resolve, 0));
+ } finally {
+ console.error = originalConsoleError;
+ }
+ });
+
+ it("times out plugin processing and aborts its signal", async () => {
+ let signal: AbortSignal;
+ const results: IAssetUploadResult[] = [];
+ const prepared = await prepareAssetUpload({
+ plugins: [createPlugin(event => {
+ signal = event.detail.signal;
+ event.detail.onComplete(result => results.push(result));
+ event.detail.respondWith(new Promise(() => undefined));
+ })],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ timeout: 10,
+ });
+
+ assert.equal(prepared.state, "failed");
+ assert.equal(signal.aborted, true);
+ assert.equal(results[0].status, "failed");
+ assert.match(results[0].error, /timed out/);
+ });
+
+ it("cancels pending processing when the editor is destroyed", async () => {
+ let signal: AbortSignal;
+ const pending = prepareAssetUpload({
+ plugins: [createPlugin(event => {
+ signal = event.detail.signal;
+ event.detail.respondWith(new Promise(() => undefined));
+ })],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ cancelAssetUploads(protyle);
+ const prepared = await pending;
+ assert.equal(prepared.state, "canceled");
+ assert.equal(signal.aborted, true);
+ });
+
+ it("cancels pending processing when the active plugin is unloaded", async () => {
+ let signal: AbortSignal;
+ const plugin = createPlugin(event => {
+ signal = event.detail.signal;
+ event.detail.respondWith(new Promise(() => undefined));
+ });
+ const pending = prepareAssetUpload({
+ plugins: [plugin],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ cancelAssetUploadsByPlugin(plugin);
+ const prepared = await pending;
+ assert.equal(prepared.state, "canceled");
+ assert.equal(signal.aborted, true);
+ });
+
+ it("cancels pending processing when a queued plugin is unloaded", async () => {
+ const activePlugin = createPlugin(event => {
+ event.detail.respondWith(new Promise(() => undefined));
+ });
+ const queuedPlugin = createPlugin(() => undefined);
+ const pending = prepareAssetUpload({
+ plugins: [activePlugin, queuedPlugin],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ cancelAssetUploadsByPlugin(queuedPlugin);
+ const prepared = await pending;
+ assert.equal(prepared.state, "canceled");
+ });
+
+ it("rejects invalid replacement elements with the plugin name and index", async () => {
+ const prepared = await prepareAssetUpload({
+ plugins: [createPlugin(event => event.detail.respondWith({
+ action: "replace",
+ input: {kind: "local-files", files: [null]} as unknown as IAssetUploadInput,
+ }))],
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ assert.equal(prepared.state, "failed");
+ if (prepared.state === "failed") {
+ assert.match(prepared.error, /test-plugin.*input\.files\[0]/);
+ }
+ });
+
+ it("uses a stable plugin snapshot while awaiting a response", async () => {
+ let resolveDecision: (decision: IAssetUploadDecision) => void;
+ let laterPluginCalled = false;
+ const plugins = [
+ createPlugin(event => event.detail.respondWith(new Promise(resolve => {
+ resolveDecision = resolve;
+ }))),
+ createPlugin(() => {
+ laterPluginCalled = true;
+ }),
+ ];
+ const pending = prepareAssetUpload({
+ plugins,
+ protyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+
+ plugins.splice(1, 1);
+ resolveDecision({action: "replace", input: {kind: "files", files: [createFile("b.jpg")]}});
+ const prepared = await pending;
+ assert.equal(prepared.state, "ready");
+ assert.equal(laterPluginCalled, true);
+ });
});
diff --git a/app/src/protyle/upload/pluginEvent.ts b/app/src/protyle/upload/pluginEvent.ts
index 2ef94da28d..f48a97f451 100644
--- a/app/src/protyle/upload/pluginEvent.ts
+++ b/app/src/protyle/upload/pluginEvent.ts
@@ -6,6 +6,7 @@ export interface IAssetUploadEventContext {
export interface IAssetUploadTask {
readonly requestId: string;
+ readonly signal: AbortSignal;
input: IAssetUploadInput;
complete(result: Omit<IAssetUploadResult, "requestId" | "input">): boolean;
}
@@ -20,12 +21,27 @@ export type TPreparedAssetUpload = {
};
interface IAssetUploadPlugin {
+ name?: string;
eventBus: {
- emit(type: TEventBus, detail: IBeforeUploadAssetsDetail): boolean;
+ emitWithErrors(type: TEventBus, detail: IBeforeUploadAssetsDetail): {
+ defaultPrevented: boolean;
+ error?: unknown;
+ hasAsyncListener: boolean;
+ };
};
}
+class AssetUploadCanceledError extends Error {
+}
+
+class AssetUploadTimeoutError extends Error {
+}
+
+export const ASSET_UPLOAD_PLUGIN_TIMEOUT = 120_000;
+
let requestSequence = 0;
+const waitingTasksByProtyle = new WeakMap<IProtyle, Set<AssetUploadTask>>();
+const waitingTasksByPlugin = new WeakMap<IAssetUploadPlugin, Set<AssetUploadTask>>();
const genRequestId = () => {
requestSequence++;
@@ -39,12 +55,38 @@ const cloneInput = (input: IAssetUploadInput): IAssetUploadInput => {
return {kind: "local-files", files: Array.from(input.files)};
};
-const isAssetUploadInput = (input: unknown): input is IAssetUploadInput => {
+const validateAssetUploadInput = (input: unknown) => {
if (!input || typeof input !== "object") {
- return false;
+ return "input must be an object";
}
const value = input as IAssetUploadInput;
- return (value.kind === "files" || value.kind === "local-files") && Array.isArray(value.files);
+ if (!Array.isArray(value.files)) {
+ return "input.files must be an array";
+ }
+ if (value.kind === "files") {
+ const invalidIndex = value.files.findIndex(file => !(file instanceof File) &&
+ Object.prototype.toString.call(file) !== "[object File]");
+ return invalidIndex === -1 ? "" : `input.files[${invalidIndex}] must be a File`;
+ }
+ if (value.kind === "local-files") {
+ for (let index = 0; index < value.files.length; index++) {
+ const file = value.files[index];
+ if (!file || typeof file !== "object") {
+ return `input.files[${index}] must be an object`;
+ }
+ if (typeof file.path !== "string" || file.path.length === 0) {
+ return `input.files[${index}].path must be a non-empty string`;
+ }
+ if (file.size !== null && (typeof file.size !== "number" || !Number.isFinite(file.size) || file.size < 0)) {
+ return `input.files[${index}].size must be null or a non-negative finite number`;
+ }
+ if (file.isDir !== undefined && typeof file.isDir !== "boolean") {
+ return `input.files[${index}].isDir must be a boolean`;
+ }
+ }
+ return "";
+ }
+ return "input.kind must be files or local-files";
};
const getErrorMessage = (error: unknown) => {
@@ -54,34 +96,83 @@ const getErrorMessage = (error: unknown) => {
return typeof error === "string" ? error : "";
};
+const getPluginLabel = (plugin: IAssetUploadPlugin, index: number) => plugin.name || `#${index + 1}`;
+
class AssetUploadTask implements IAssetUploadTask {
public readonly requestId: string;
+ public readonly signal: AbortSignal;
public input: IAssetUploadInput;
private completed = false;
- private readonly callbacks: Array<(result: IAssetUploadResult) => void> = [];
+ private readonly abortController = new AbortController();
+ private readonly callbacks: Array<(result: IAssetUploadResult) => any> = [];
+ private readonly protyle: IProtyle;
+ private waitingPlugins: IAssetUploadPlugin[] = [];
- constructor(input: IAssetUploadInput, requestId: string) {
+ constructor(input: IAssetUploadInput, requestId: string, protyle: IProtyle) {
this.input = cloneInput(input);
this.requestId = requestId;
+ this.protyle = protyle;
+ this.signal = this.abortController.signal;
}
public addCompleteCallback(callback: (result: IAssetUploadResult) => void) {
this.callbacks.push(callback);
}
+ public startWaiting(plugins: IAssetUploadPlugin[]) {
+ this.stopWaiting();
+ this.waitingPlugins = plugins;
+ let protyleTasks = waitingTasksByProtyle.get(this.protyle);
+ if (!protyleTasks) {
+ protyleTasks = new Set();
+ waitingTasksByProtyle.set(this.protyle, protyleTasks);
+ }
+ protyleTasks.add(this);
+ plugins.forEach(plugin => {
+ let pluginTasks = waitingTasksByPlugin.get(plugin);
+ if (!pluginTasks) {
+ pluginTasks = new Set();
+ waitingTasksByPlugin.set(plugin, pluginTasks);
+ }
+ pluginTasks.add(this);
+ });
+ }
+
+ public stopWaiting() {
+ waitingTasksByProtyle.get(this.protyle)?.delete(this);
+ this.waitingPlugins.forEach(plugin => waitingTasksByPlugin.get(plugin)?.delete(this));
+ this.waitingPlugins = [];
+ }
+
+ public abort(reason: Error) {
+ if (!this.signal.aborted) {
+ this.abortController.abort(reason);
+ }
+ }
+
public complete(result: Omit<IAssetUploadResult, "requestId" | "input">) {
if (this.completed) {
return false;
}
this.completed = true;
+ this.stopWaiting();
const detail: IAssetUploadResult = {
...result,
requestId: this.requestId,
input: cloneInput(this.input),
};
+ if (result.acceptedInput) {
+ detail.acceptedInput = cloneInput(result.acceptedInput);
+ }
+ if (result.rejected) {
+ detail.rejected = result.rejected.map(item => ({...item, reasons: Array.from(item.reasons)}));
+ }
this.callbacks.forEach(callback => {
try {
- callback(detail);
+ const callbackResult = callback(detail);
+ if (callbackResult && typeof callbackResult.then === "function") {
+ void Promise.resolve(callbackResult).catch(error => console.error(error));
+ }
} catch (error) {
console.error(error);
}
@@ -90,66 +181,152 @@ class AssetUploadTask implements IAssetUploadTask {
}
}
+const cancelWaitingTasks = (tasks: Set<AssetUploadTask> | undefined, reason: string) => {
+ Array.from(tasks || []).forEach(task => task.abort(new AssetUploadCanceledError(reason)));
+};
+
+export const cancelAssetUploads = (protyle: IProtyle) => {
+ cancelWaitingTasks(waitingTasksByProtyle.get(protyle), "The editor was destroyed");
+};
+
+export const cancelAssetUploadsByPlugin = (plugin: IAssetUploadPlugin) => {
+ cancelWaitingTasks(waitingTasksByPlugin.get(plugin), `Plugin ${plugin.name || ""} was unloaded`.trim());
+};
+
+const waitForDecision = (response: PromiseLike<IAssetUploadDecision>, task: AssetUploadTask,
+ pluginLabel: string, pendingPlugins: IAssetUploadPlugin[], deadline: number) => {
+ task.startWaiting(pendingPlugins);
+ return new Promise<IAssetUploadDecision>((resolve, reject) => {
+ let settled = false;
+ const finish = (callback: (value: any) => void, value: any) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ clearTimeout(timeoutId);
+ task.signal.removeEventListener("abort", onAbort);
+ task.stopWaiting();
+ callback(value);
+ };
+ const onAbort = () => finish(reject, task.signal.reason instanceof Error ? task.signal.reason :
+ new AssetUploadCanceledError("The upload was canceled"));
+ const timeoutId = setTimeout(() => {
+ task.abort(new AssetUploadTimeoutError(`Plugin ${pluginLabel} asset processing timed out`));
+ }, Math.max(0, deadline - Date.now()));
+ task.signal.addEventListener("abort", onAbort, {once: true});
+ if (task.signal.aborted) {
+ onAbort();
+ return;
+ }
+ Promise.resolve(response).then(value => finish(resolve, value), error => finish(reject, error));
+ });
+};
+
export const prepareAssetUpload = (options: {
plugins: IAssetUploadPlugin[];
protyle: IProtyle;
input: IAssetUploadInput;
context: IAssetUploadEventContext;
requestId?: string;
+ timeout?: number;
}): TPreparedAssetUpload | Promise<TPreparedAssetUpload> => {
- const task = new AssetUploadTask(options.input, options.requestId || genRequestId());
+ const task = new AssetUploadTask(options.input, options.requestId || genRequestId(), options.protyle);
+ const plugins = Array.from(options.plugins);
+ const deadline = Date.now() + (options.timeout ?? ASSET_UPLOAD_PLUGIN_TIMEOUT);
const fail = (error: unknown): TPreparedAssetUpload => {
const errorMessage = getErrorMessage(error);
+ task.abort(error instanceof Error ? error : new Error(errorMessage));
task.complete({status: "failed", error: errorMessage});
return {state: "failed", task, error: errorMessage};
};
- const cancel = (): TPreparedAssetUpload => {
+ const cancel = (reason = "The upload was canceled"): TPreparedAssetUpload => {
+ task.abort(new AssetUploadCanceledError(reason));
task.complete({status: "canceled"});
return {state: "canceled", task};
};
const processPlugin = (index: number): TPreparedAssetUpload | Promise<TPreparedAssetUpload> => {
- if (index >= options.plugins.length) {
+ if (index >= plugins.length) {
return {state: "ready", task};
}
+ const plugin = plugins[index];
+ const pluginLabel = getPluginLabel(plugin, index);
let response: PromiseLike<IAssetUploadDecision> | undefined;
+ let responseClaimed = false;
let responseError = "";
- const emitResult = options.plugins[index].eventBus.emit("before-upload-assets", {
- requestId: task.requestId,
- protyle: options.protyle,
- source: options.context.source,
- target: options.context.target,
- position: options.context.position,
- input: cloneInput(task.input),
- respondWith(value) {
- if (response) {
- responseError = "before-upload-assets respondWith can only be called once";
- return;
- }
- response = Promise.resolve(value);
- },
- onComplete(callback) {
- task.addCompleteCallback(callback);
- },
- });
- if (!emitResult) {
- return cancel();
+ let acceptingRegistrations = true;
+ let emitResult: ReturnType<IAssetUploadPlugin["eventBus"]["emitWithErrors"]>;
+ const discardResponse = () => {
+ if (response) {
+ void Promise.resolve(response).catch(error => console.error(error));
+ }
+ };
+ try {
+ emitResult = plugin.eventBus.emitWithErrors("before-upload-assets", {
+ requestId: task.requestId,
+ protyle: options.protyle,
+ source: options.context.source,
+ target: options.context.target,
+ position: options.context.position,
+ input: cloneInput(task.input),
+ signal: task.signal,
+ respondWith(value) {
+ if (!acceptingRegistrations) {
+ console.error(new Error(`Plugin ${pluginLabel} must call respondWith synchronously`));
+ return;
+ }
+ if (responseClaimed) {
+ responseError = `Plugin ${pluginLabel} called respondWith more than once`;
+ return;
+ }
+ responseClaimed = true;
+ response = Promise.resolve(value);
+ },
+ onComplete(callback) {
+ if (!acceptingRegistrations) {
+ console.error(new Error(`Plugin ${pluginLabel} must register onComplete synchronously`));
+ return;
+ }
+ task.addCompleteCallback(callback);
+ },
+ });
+ } catch (error) {
+ acceptingRegistrations = false;
+ discardResponse();
+ return fail(error);
+ }
+ acceptingRegistrations = false;
+ if (emitResult.error) {
+ discardResponse();
+ return fail(new Error(`Plugin ${pluginLabel} failed during before-upload-assets: ${getErrorMessage(emitResult.error)}`));
+ }
+ if (emitResult.defaultPrevented) {
+ discardResponse();
+ return fail(new Error(`Plugin ${pluginLabel} must use respondWith to replace or cancel an asset upload`));
}
if (responseError) {
+ discardResponse();
return fail(responseError);
}
+ if (emitResult.hasAsyncListener && !responseClaimed) {
+ return fail(new Error(`Plugin ${pluginLabel} must call respondWith synchronously before awaiting`));
+ }
if (!response) {
return processPlugin(index + 1);
}
- return Promise.resolve(response).then(decision => {
+ return waitForDecision(response, task, pluginLabel, plugins.slice(index), deadline).then(decision => {
if (decision?.action === "cancel") {
return cancel();
}
- if (decision?.action !== "replace" || !isAssetUploadInput(decision.input)) {
- throw new Error("Invalid before-upload-assets response");
+ if (decision?.action !== "replace") {
+ throw new Error(`Plugin ${pluginLabel} returned an invalid action`);
+ }
+ const validationError = validateAssetUploadInput(decision.input);
+ if (validationError) {
+ throw new Error(`Plugin ${pluginLabel} returned invalid input: ${validationError}`);
}
task.input = cloneInput(decision.input);
return processPlugin(index + 1);
- }).catch(fail);
+ }).catch(error => error instanceof AssetUploadCanceledError ? cancel(error.message) : fail(error));
};
return processPlugin(0);
};
diff --git a/app/src/protyle/upload/uploadResult.test.ts b/app/src/protyle/upload/uploadResult.test.ts
new file mode 100644
index 0000000000..d882cb75fe
--- /dev/null
+++ b/app/src/protyle/upload/uploadResult.test.ts
@@ -0,0 +1,52 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {getAssetUploadResult} from "./uploadResult";
+
+const createFile = (name: string) => new File(["content"], name, {type: "image/png"});
+
+describe("asset upload result", () => {
+ it("reports success when every accepted file is written", () => {
+ const input: IAssetUploadInput = {kind: "files", files: [createFile("a.png")]};
+ const result = getAssetUploadResult(JSON.stringify({
+ code: 0,
+ data: {succMap: {"a.png": "assets/a.png"}, errFiles: []},
+ }), input);
+
+ assert.equal(result.status, "success");
+ assert.deepEqual(result.acceptedInput, input);
+ assert.equal(result.rejected, undefined);
+ });
+
+ it("reports partial when frontend validation rejected part of the input", () => {
+ const acceptedInput: IAssetUploadInput = {kind: "files", files: [createFile("a.png")]};
+ const rejected: IAssetUploadRejection[] = [{
+ index: 1,
+ name: "b.exe",
+ reasons: ["type-not-accepted"],
+ }];
+ const result = getAssetUploadResult(JSON.stringify({
+ code: 0,
+ data: {succMap: {"a.png": "assets/a.png"}, errFiles: []},
+ }), acceptedInput, rejected);
+
+ assert.equal(result.status, "partial");
+ assert.deepEqual(result.acceptedInput, acceptedInput);
+ assert.deepEqual(result.rejected, rejected);
+ });
+
+ it("preserves accepted and rejected details when the server fails", () => {
+ const acceptedInput: IAssetUploadInput = {kind: "files", files: [createFile("a.png")]};
+ const rejected: IAssetUploadRejection[] = [{
+ index: 1,
+ name: "b.exe",
+ reasons: ["type-not-accepted"],
+ }];
+ const result = getAssetUploadResult(JSON.stringify({code: 1, msg: "upload failed", data: {}}),
+ acceptedInput, rejected);
+
+ assert.equal(result.status, "failed");
+ assert.equal(result.error, "upload failed");
+ assert.deepEqual(result.acceptedInput, acceptedInput);
+ assert.deepEqual(result.rejected, rejected);
+ });
+});
diff --git a/app/src/protyle/upload/uploadResult.ts b/app/src/protyle/upload/uploadResult.ts
new file mode 100644
index 0000000000..fa843f52c9
--- /dev/null
+++ b/app/src/protyle/upload/uploadResult.ts
@@ -0,0 +1,27 @@
+export const getAssetUploadResult = (responseText: string, acceptedInput: IAssetUploadInput,
+ rejected: IAssetUploadRejection[] = []):
+Omit<IAssetUploadResult, "requestId" | "input"> => {
+ const inputResult = {
+ acceptedInput,
+ rejected: rejected.length > 0 ? rejected : undefined,
+ };
+ try {
+ const response = JSON.parse(responseText);
+ const succMap = response.data?.succMap as Record<string, string> | undefined;
+ const errFiles = response.data?.errFiles as string[] | undefined;
+ if (typeof response.code === "number" && response.code !== 0) {
+ return {...inputResult, status: "failed", succMap, errFiles, error: String(response.msg || "")};
+ }
+ if (succMap) {
+ const expected = acceptedInput.files.length;
+ const succeeded = acceptedInput.kind === "files" ?
+ acceptedInput.files.filter(file => succMap[file.name]).length : Object.keys(succMap).length;
+ const status = succeeded === expected && !errFiles?.length && rejected.length === 0 ? "success" :
+ succeeded > 0 ? "partial" : "failed";
+ return {...inputResult, status, succMap, errFiles};
+ }
+ } catch (error) {
+ // 自定义上传接口不一定返回 JSON,HTTP 200 仍视为成功。
+ }
+ return {...inputResult, status: rejected.length > 0 ? "partial" : "success"};
+};
diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.ts
index 84df835f3d..07569198ee 100644
--- a/app/src/protyle/util/destroy.ts
+++ b/app/src/protyle/util/destroy.ts
@@ -1,11 +1,13 @@
import {hideElements} from "../ui/hideElements";
import {isSupportCSSHL} from "../render/searchMarkRender";
import {destroyAIEditor} from "../../ai/editor";
+import {cancelAssetUploads} from "../upload/pluginEvent";
export const destroy = (protyle: IProtyle) => {
if (!protyle) {
return;
}
+ cancelAssetUploads(protyle);
hideElements(["util"], protyle, true);
destroyAIEditor(protyle);
protyle.hint?.destroy();
diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.ts
index e3b80d5e2f..5cddd27874 100644
--- a/app/src/protyle/util/editorCommonEvent.ts
+++ b/app/src/protyle/util/editorCommonEvent.ts
@@ -37,6 +37,7 @@ import {updatePanelByEditor} from "../../editor/util";
import {blockRender} from "../render/blockRender";
/// #else
import {uploadFiles, uploadLocalFiles} from "../upload";
+import {getLocalDropFiles} from "../upload/localDropFiles";
import {insertHTML} from "./insertHTML";
import {isBrowser} from "../../util/functions";
import {hideElements} from "../ui/hideElements";
@@ -2085,25 +2086,12 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {
if (!avElement) {
focusByRange(getRangeByPoint(event.clientX, event.clientY));
if (event.dataTransfer.types.includes("Files") && !isBrowser()) {
- const files: ILocalFiles[] = [];
- for (let i = 0; i < event.dataTransfer.files.length; i++) {
- const filePath = webUtils.getPathForFile(event.dataTransfer.files[i]);
- if (filePath) {
- files.push({
- path: filePath,
- size: event.dataTransfer.files[i].size,
- isDir: event.dataTransfer.files[i].size === 0 &&
- event.dataTransfer.files[i].type === "" &&
- !event.dataTransfer.files[i].name.includes("."),
- });
- } else {
- paste(protyle, event, {
- htmlAsIframe: window.siyuan.config.editor.dragHTMLFileToIframe && !event.altKey,
- });
- break;
- }
- }
- if (files.length > 0) {
+ const files = getLocalDropFiles(event.dataTransfer.files, file => webUtils.getPathForFile(file));
+ if (!files) {
+ paste(protyle, event, {
+ htmlAsIframe: window.siyuan.config.editor.dragHTMLFileToIframe && !event.altKey,
+ });
+ } else if (files.length > 0) {
uploadLocalFiles(files, protyle, !event.altKey, {
htmlAsIframe: window.siyuan.config.editor.dragHTMLFileToIframe && !event.altKey,
source: "drop",
@@ -2123,17 +2111,18 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {
if (cellElement) {
if (getTypeByCellElement(cellElement) === "mAsset" && event.dataTransfer.types[0] === "Files") {
/// #if !BROWSER
- 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 files = getLocalDropFiles(event.dataTransfer.files,
+ file => webUtils.getPathForFile(file));
+ if (!files) {
+ focusBlock(hasClosestBlock(cellElement) as HTMLElement);
+ uploadFiles(protyle, event.dataTransfer.files, undefined, undefined, undefined, {
+ source: "drop",
+ target: "av-cell",
+ position: {x: event.clientX, y: event.clientY},
});
+ } else {
+ dragUpload(files, protyle, cellElement, {x: event.clientX, y: event.clientY});
}
- dragUpload(files, protyle, cellElement, {x: event.clientX, y: event.clientY});
/// #else
focusBlock(hasClosestBlock(cellElement) as HTMLElement);
uploadFiles(protyle, event.dataTransfer.files, undefined, undefined, undefined, {
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index e062c9eb95..79137c4255 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -387,6 +387,7 @@ interface ILocalFiles {
type TAssetUploadSource = "paste" | "drop" | "file-picker" | "programmatic"
type TAssetUploadTarget = "editor" | "av-cell" | "background"
type TAssetUploadStatus = "success" | "partial" | "failed" | "canceled"
+type TAssetUploadRejectionReason = "name-empty" | "size-limit" | "type-not-accepted"
interface IAssetUploadPosition {
x: number,
@@ -408,16 +409,27 @@ type IAssetUploadDecision = {
action: "cancel"
}
+interface IAssetUploadRejection {
+ index: number,
+ name: string,
+ reasons: TAssetUploadRejectionReason[]
+}
+
interface IAssetUploadResult {
requestId: string,
status: TAssetUploadStatus,
+ /** 插件链处理结束后的完整输入。 */
input: IAssetUploadInput,
+ /** 通过前端校验并实际提交上传的输入。 */
+ acceptedInput?: IAssetUploadInput,
+ /** 被前端校验拒绝的文件及其在完整输入中的位置。 */
+ rejected?: IAssetUploadRejection[],
succMap?: Record<string, string>,
errFiles?: string[],
error?: string
}
-/** 在事件对象上调用 `preventDefault()` 可立即取消本次上传。 */
+/** 不得在该事件上调用 `preventDefault()`,取消上传应使用 `respondWith({action: "cancel"})`。 */
interface IBeforeUploadAssetsDetail {
requestId: string,
protyle: IProtyle,
@@ -425,9 +437,11 @@ interface IBeforeUploadAssetsDetail {
target: TAssetUploadTarget,
position?: IAssetUploadPosition,
input: IAssetUploadInput,
- /** 返回替换后的输入或取消上传,每次事件只允许调用一次。 */
+ /** 插件处理的取消信号,编辑器销毁、插件卸载或处理超时时触发。 */
+ signal: AbortSignal,
+ /** 必须同步调用且每次事件只允许调用一次,异步处理应将 Promise 作为参数传入,默认 120 秒超时。 */
respondWith(response: IAssetUploadDecision | PromiseLike<IAssetUploadDecision>): void,
- /** 注册上传结束回调,成功、失败或取消时执行一次。 */
+ /** 必须同步注册,资源目录写入成功、失败或取消时执行一次,不包含正文或属性视图写入。 */
onComplete(callback: (result: IAssetUploadResult) => void): void
}