Skip to content

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

:art: Complete asset upload interception coverage https://github.com/siyuan-note/siyuan/issues/18878

Daniel85329dee2048
diff --git a/app/src/asset/anno.ts b/app/src/asset/anno.ts
index 9ec0cf1b15..3485329934 100644
--- a/app/src/asset/anno.ts
+++ b/app/src/asset/anno.ts
@@ -22,6 +22,8 @@ import {
PDF_RECT_CAPTURE_SCALE,
PDF_RECT_DISPLAY_SCALE,
} from "./pdfRectCapture";
+import {uploadStandaloneAssetFiles} from "../protyle/upload";
+import {getAssetUploadSuccesses} from "../protyle/upload/uploadResult";
const RECT_RESIZE_MIN_SIZE = 8;
@@ -935,14 +937,21 @@ const copyAnno = (idPath: string, fileName: string, pdf: any) => {
.replace("${y}", filesize(imageData.blob.size, {standard: "iec"}));
}
confirmDialog(msg ? window.siyuan.languages.upload : "", msg, () => {
- const formData = new FormData();
const imageName = getRectImageName(content, imageData.rotation, positionHash,
PDF_RECT_CAPTURE_PROFILE);
- formData.append("file[]", imageData.blob, imageName);
- formData.append("skipIfDuplicated", "true");
- fetchPost(Constants.UPLOAD_ADDRESS, formData, (response) => {
- writeText(`<<${idPath} "${content}">>
-![](${response.data.succMap[imageName]}){: style="width: ${imageData.displayWidth}px;"}`);
+ void uploadStandaloneAssetFiles([
+ new File([imageData.blob], imageName, {type: imageData.blob.type}),
+ ], {
+ source: "programmatic",
+ target: "pdf-annotation",
+ requiredFileCount: 1,
+ extraData: {skipIfDuplicated: "true"},
+ }).then(response => {
+ const path = getAssetUploadSuccesses(response?.data)[0]?.path;
+ if (path) {
+ writeText(`<<${idPath} "${content}">>
+![](${path}){: style="width: ${imageData.displayWidth}px;"}`);
+ }
});
});
}).catch((error) => {
diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.ts
index cb4bcff399..b8d4b76cfa 100644
--- a/app/src/menus/protyle.ts
+++ b/app/src/menus/protyle.ts
@@ -1518,9 +1518,11 @@ export const imgMenu = (protyle: IProtyle, range: Range, assetElement: HTMLEleme
source: "programmatic",
target: "editor",
});
- imgElement.setAttribute("src", base64Src[0]);
- imgElement.setAttribute("data-src", base64Src[0]);
- assetElement.querySelector(".img__net")?.remove();
+ if (base64Src[0]) {
+ imgElement.setAttribute("src", base64Src[0]);
+ imgElement.setAttribute("data-src", base64Src[0]);
+ assetElement.querySelector(".img__net")?.remove();
+ }
}
const ocrElement = window.siyuan.menus.menu.element.querySelector('[data-type="ocr"]') as HTMLTextAreaElement;
diff --git a/app/src/protyle/header/Background.ts b/app/src/protyle/header/Background.ts
index f775433fa1..903095e64a 100644
--- a/app/src/protyle/header/Background.ts
+++ b/app/src/protyle/header/Background.ts
@@ -19,6 +19,7 @@ import {escapeHtml} from "../../util/escape";
import {fetchCoverData, getCategoryLabel} from "./coverData";
import {getAssetUploadSuccesses} from "../upload/uploadResult";
import {hasDataTransferFiles} from "../upload/localDropFiles";
+import {showMessage} from "../../dialog/message";
/// #if !MOBILE
import {openDocTagMenu} from "./openDocTagMenu";
/// #endif
@@ -375,21 +376,9 @@ export class Background {
} else if (target.closest(".b3-cover__card")) {
const card = target.closest(".b3-cover__card") as HTMLElement;
const name = card.getAttribute("data-name");
- fetchPost("/api/asset/insertCover", {
- id: protyle.block.rootID,
- name
- }, (response) => {
- const url = getAssetUploadSuccesses(response.data)[0]?.path;
- if (!url) {
- return;
- }
- this.ial["title-img"] = `background-image:url("${url}")`;
- this.render(this.ial, protyle.block.rootID);
- fetchPost("/api/attr/setBlockAttrs", {
- id: protyle.block.rootID,
- attrs: {"title-img": this.ial["title-img"]}
- });
- });
+ if (name) {
+ this.uploadBuiltInCover(protyle, name);
+ }
dialog.destroy();
}
});
@@ -405,21 +394,7 @@ export class Background {
fetchCoverData().then((coverData) => {
if (coverData && coverData.allCovers.length > 0) {
const randomCover = coverData.allCovers[getRandom(0, coverData.allCovers.length - 1)];
- fetchPost("/api/asset/insertCover", {
- id: protyle.block.rootID,
- name: randomCover.file
- }, (response) => {
- const url = getAssetUploadSuccesses(response.data)[0]?.path;
- if (!url) {
- return;
- }
- this.ial["title-img"] = `background-image:url("${url}")`;
- this.render(this.ial, protyle.block.rootID);
- fetchPost("/api/attr/setBlockAttrs", {
- id: protyle.block.rootID,
- attrs: {"title-img": this.ial["title-img"]}
- });
- });
+ this.uploadBuiltInCover(protyle, randomCover.file);
} else {
this.ial["title-img"] = bgs[getRandom(0, bgs.length - 1)];
this.render(this.ial, protyle.block.rootID);
@@ -704,6 +679,34 @@ export class Background {
});
}
+ private uploadBuiltInCover(protyle: IProtyle, name: string) {
+ void fetch(`/appearance/covers/${encodeURIComponent(name)}`).then(async response => {
+ if (!response.ok) {
+ throw new Error(response.statusText);
+ }
+ const blob = await response.blob();
+ uploadFiles(protyle, [new File([blob], name, {type: blob.type})], undefined, responseText => {
+ const responseData = JSON.parse(responseText);
+ const url = getAssetUploadSuccesses(responseData.data)[0]?.path;
+ if (!url) {
+ return;
+ }
+ this.ial["title-img"] = `background-image:url("${url}")`;
+ this.render(this.ial, protyle.block.rootID);
+ fetchPost("/api/attr/setBlockAttrs", {
+ id: protyle.block.rootID,
+ attrs: {"title-img": this.ial["title-img"]}
+ });
+ }, undefined, {
+ source: "programmatic",
+ target: "background",
+ });
+ }).catch(error => {
+ console.error(error);
+ showMessage(window.siyuan.languages.uploadError);
+ });
+ }
+
private removeTag(protyle: IProtyle, cb?: () => void) {
this.updateTags(protyle, this.getTags(), cb);
}
diff --git a/app/src/protyle/render/av/asset.ts b/app/src/protyle/render/av/asset.ts
index 833a1df8e9..8ec83acbde 100644
--- a/app/src/protyle/render/av/asset.ts
+++ b/app/src/protyle/render/av/asset.ts
@@ -252,7 +252,7 @@ export const editAssetItem = (options: {
source: "programmatic",
target: "av-cell",
});
- currentLink = base64Src[0];
+ currentLink = base64Src[0] || currentLink;
}
updateAssetCell({
diff --git a/app/src/protyle/upload/base64.ts b/app/src/protyle/upload/base64.ts
index 195be47fce..a2d40f53ef 100644
--- a/app/src/protyle/upload/base64.ts
+++ b/app/src/protyle/upload/base64.ts
@@ -1,10 +1,11 @@
import {type IUploadInsertOptions, uploadFiles} from "./index";
-import {getAssetUploadSuccesses} from "./uploadResult";
+import {getAssetUploadPathsByInput} from "./uploadResult";
export const base64ToURL = async (base64SrcList: string[], protyle: IProtyle,
options?: IUploadInsertOptions) => {
const files: File[] = [];
- base64SrcList.forEach(item => {
+ const fileSourceIndices: number[] = [];
+ base64SrcList.forEach((item, sourceIndex) => {
const srcPart = item.split(",");
if (srcPart.length !== 2) return;
// data URL 格式为 data:image/svg+xml;base64,XXX
@@ -22,29 +23,24 @@ export const base64ToURL = async (base64SrcList: string[], protyle: IProtyle,
"image/gif": "gif",
"image/svg+xml": "svg"
}[mime] || "png"}`, {type: mime}));
+ fileSourceIndices.push(sourceIndex);
});
+ const paths: Array<string | undefined> = new Array(base64SrcList.length).fill(undefined);
if (files.length === 0) {
- return [];
+ return paths;
}
- return new Promise<string[]>((resolve, reject) => {
+ return new Promise<Array<string | undefined>>((resolve) => {
let settled = false;
- uploadFiles(protyle, files, undefined, responseText => {
- try {
- const response = JSON.parse(responseText) as IWebSocketData;
- const paths = getAssetUploadSuccesses(response.data).map(item => item.path);
- if (paths.length !== files.length) {
- throw new Error("Asset upload did not return every requested file");
- }
- settled = true;
- resolve(paths);
- } catch (error) {
- settled = true;
- reject(error);
- }
- }, succeeded => {
+ uploadFiles(protyle, files, undefined, (_responseText, result) => {
+ getAssetUploadPathsByInput(files.length, result).forEach((path, fileIndex) => {
+ paths[fileSourceIndices[fileIndex]] = path;
+ });
+ settled = true;
+ resolve(paths);
+ }, () => {
if (!settled) {
settled = true;
- reject(new Error(succeeded ? "Asset upload returned no result" : "Asset upload failed"));
+ resolve(paths);
}
}, {...options, requiredFileCount: files.length});
});
diff --git a/app/src/protyle/upload/htmlLocalAssets.test.ts b/app/src/protyle/upload/htmlLocalAssets.test.ts
new file mode 100644
index 0000000000..89158962a1
--- /dev/null
+++ b/app/src/protyle/upload/htmlLocalAssets.test.ts
@@ -0,0 +1,31 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {applyHTMLLocalAssetPaths, type IHTMLLocalAsset, isHTMLLocalAssetPath} from "./htmlLocalAssets";
+
+describe("HTML local assets", () => {
+ it("recognizes absolute paths without treating web and asset URLs as local", () => {
+ assert.equal(isHTMLLocalAssetPath("file:///tmp/a.png"), true);
+ assert.equal(isHTMLLocalAssetPath("C:\\Images\\a.png"), true);
+ assert.equal(isHTMLLocalAssetPath("/tmp/a.png"), true);
+ assert.equal(isHTMLLocalAssetPath("https://example.com/a.png"), false);
+ assert.equal(isHTMLLocalAssetPath("//example.com/a.png"), false);
+ assert.equal(isHTMLLocalAssetPath("assets/a.png"), false);
+ });
+
+ it("rewrites only successful paths by their input indexes", () => {
+ const values = ["file:///tmp/a.png", "/tmp/b.pdf"];
+ const assets = values.map((path, index) => ({
+ element: {
+ setAttribute(_attribute: string, value: string) {
+ values[index] = value;
+ },
+ } as Element,
+ attribute: index === 0 ? "src" : "href",
+ path,
+ })) as IHTMLLocalAsset[];
+
+ applyHTMLLocalAssetPaths(assets, [undefined, "assets/b.pdf"]);
+
+ assert.deepEqual(values, ["file:///tmp/a.png", "assets/b.pdf"]);
+ });
+});
diff --git a/app/src/protyle/upload/htmlLocalAssets.ts b/app/src/protyle/upload/htmlLocalAssets.ts
new file mode 100644
index 0000000000..289dab2c82
--- /dev/null
+++ b/app/src/protyle/upload/htmlLocalAssets.ts
@@ -0,0 +1,38 @@
+export interface IHTMLLocalAsset {
+ element: Element;
+ attribute: "href" | "src";
+ path: string;
+}
+
+export const isHTMLLocalAssetPath = (value: string) => {
+ const path = value.trim();
+ if (!path || path.toLowerCase().startsWith("assets/")) {
+ return false;
+ }
+ if (/^file:\/\//i.test(path) || /^\\\\/.test(path) || /^[a-z]:[\\/]/i.test(path)) {
+ return true;
+ }
+ return path.startsWith("/") && !path.startsWith("//");
+};
+
+export const collectHTMLLocalAssets = (root: ParentNode) => {
+ const assets: IHTMLLocalAsset[] = [];
+ root.querySelectorAll("[href], [src]").forEach(element => {
+ (["href", "src"] as const).forEach(attribute => {
+ const path = element.getAttribute(attribute);
+ if (path && isHTMLLocalAssetPath(path)) {
+ assets.push({element, attribute, path});
+ }
+ });
+ });
+ return assets;
+};
+
+export const applyHTMLLocalAssetPaths = (assets: IHTMLLocalAsset[], paths: Array<string | undefined>) => {
+ paths.forEach((path, index) => {
+ const asset = assets[index];
+ if (asset && path) {
+ asset.element.setAttribute(asset.attribute, path);
+ }
+ });
+};
diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.ts
index 3ceb448f1b..fb2e83ee26 100644
--- a/app/src/protyle/upload/index.ts
+++ b/app/src/protyle/upload/index.ts
@@ -25,6 +25,7 @@ import {
prepareAssetUpload,
} from "./pluginEvent";
import {getAssetUploadResult, getAssetUploadSuccesses} from "./uploadResult";
+import {AssetUploadHandlerTimeoutError, waitForUploadHandler} from "./uploadHandler";
interface FileWithPath extends File {
path: string;
@@ -38,6 +39,10 @@ export interface IUploadInsertOptions {
position?: IAssetUploadPosition;
/** 目标消费方要求的文件数量。 */
requiredFileCount?: number;
+ /** 目标消费方支持的输入类型。 */
+ allowedInputKinds?: Array<IAssetUploadInput["kind"]>;
+ /** 本机 HTML 粘贴需要沿用内核的敏感路径校验。 */
+ fromHTMLPaste?: boolean;
}
export class Upload {
@@ -309,17 +314,23 @@ export const getUploadInsertRange = (protyle: IProtyle, position?: IUploadInsert
interface IAssetUploadCallbacks {
success(responseText: string, response: IWebSocketData | undefined,
- input: IAssetUploadInput): void | PromiseLike<void>;
+ input: IAssetUploadInput,
+ result: Omit<IAssetUploadResult, "requestId" | "input">): void | PromiseLike<void>;
+ formatResponse?: (responseText: string, input: IAssetUploadInput) => string;
complete?: (succeeded: boolean) => void;
reset?: () => void;
}
-const getAssetUploadContext = (options?: IUploadInsertOptions): IAssetUploadEventContext => ({
- source: options?.source || "programmatic",
- target: options?.target || "editor",
- position: options?.position,
- requiredFileCount: options?.requiredFileCount,
-});
+const getAssetUploadContext = (options?: IUploadInsertOptions): IAssetUploadEventContext => {
+ const target = options?.target || "editor";
+ return {
+ source: options?.source || "programmatic",
+ target,
+ position: options?.position,
+ requiredFileCount: options?.requiredFileCount ?? (target === "background" ? 1 : undefined),
+ allowedInputKinds: options?.allowedInputKinds,
+ };
+};
const captureUploadInsertPosition = (protyle: IProtyle, options?: IUploadInsertOptions): IUploadInsertOptions => {
const result = {...options};
@@ -375,7 +386,7 @@ const finishSuccessfulUpload = (task: IAssetUploadTask | undefined, callbacks: I
return;
}
try {
- const callbackResult = callbacks.success(responseText, response, input);
+ const callbackResult = callbacks.success(responseText, response, input, result);
if (callbackResult && typeof callbackResult.then === "function") {
void Promise.resolve(callbackResult).catch(error => {
console.error(error);
@@ -400,7 +411,7 @@ const finishSuccessfulUpload = (task: IAssetUploadTask | undefined, callbacks: I
const uploadPreparedLocalFiles = (input: Extract<IAssetUploadInput, { kind: "local-files" }>,
protyle: IProtyle, isUpload: boolean, callbacks: IAssetUploadCallbacks,
- task?: IAssetUploadTask) => {
+ task?: IAssetUploadTask, options?: IUploadInsertOptions) => {
let msg = "";
const assetPaths: string[] = [];
input.files.forEach(item => {
@@ -422,7 +433,8 @@ const uploadPreparedLocalFiles = (input: Extract<IAssetUploadInput, { kind: "loc
const response = await fetchSyncPost("/api/asset/insertLocalAssets", {
assetPaths,
isUpload,
- id: protyle.block.rootID
+ id: protyle.block.rootID,
+ fromHTMLPaste: options?.fromHTMLPaste,
});
hideMessage(msgId);
const detached = !document.body.contains(protyle.element);
@@ -484,16 +496,20 @@ const uploadPreparedFiles = (input: Extract<IAssetUploadInput, { kind: "files" }
finishUpload(task, callbacks, {status: "success", acceptedInput: input});
};
const failHandler = (error: unknown) => {
+ if (task.signal.aborted && !(error instanceof AssetUploadHandlerTimeoutError)) {
+ finishUpload(task, callbacks, {status: "canceled"});
+ return;
+ }
const errorMessage = getErrorMessage(error);
finishUpload(task, callbacks, {status: "failed", error: errorMessage});
showMessage(errorMessage || window.siyuan.languages.uploadError);
};
try {
- const handlerResult = protyle.options.upload.handler(fileList);
+ const handlerResult = protyle.options.upload.handler(fileList, {signal: task.signal});
if (typeof handlerResult === "string" || handlerResult === null || handlerResult === undefined) {
finishHandler(handlerResult as string | null);
} else {
- void Promise.resolve(handlerResult).then(finishHandler, failHandler);
+ void waitForUploadHandler(handlerResult, task.signal).then(finishHandler, failHandler);
}
} catch (error) {
failHandler(error);
@@ -568,17 +584,21 @@ const uploadPreparedFiles = (input: Extract<IAssetUploadInput, { kind: "files" }
destroy(protyle);
}
if (xhr.status === 200) {
+ let responseText = xhr.responseText;
+ if (callbacks.formatResponse) {
+ responseText = callbacks.formatResponse(responseText, uploadedInput);
+ }
let response: IWebSocketData;
try {
- response = JSON.parse(xhr.responseText);
+ response = JSON.parse(responseText);
} catch (error) {
response = undefined;
}
- const result = getAssetUploadResult(xhr.responseText, uploadedInput, validateResult.rejected);
+ const result = getAssetUploadResult(responseText, uploadedInput, validateResult.rejected);
if (detached) {
finishUpload(task, callbacks, result);
} else {
- finishSuccessfulUpload(task, callbacks, xhr.responseText, response, uploadedInput, result);
+ finishSuccessfulUpload(task, callbacks, responseText, response, uploadedInput, result);
}
} else if (xhr.status === 0) {
showMessage(window.siyuan.languages["_kernel"][28]);
@@ -633,7 +653,7 @@ const uploadPreparedFiles = (input: Extract<IAssetUploadInput, { kind: "files" }
};
const startPreparedAssetUpload = (prepared: Awaited<ReturnType<typeof prepareAssetUpload>>, protyle: IProtyle,
- callbacks: IAssetUploadCallbacks) => {
+ callbacks: IAssetUploadCallbacks, options: IUploadInsertOptions) => {
if (prepared.state !== "ready") {
finishCallbacks(callbacks, false);
if (prepared.state === "failed") {
@@ -642,6 +662,7 @@ const startPreparedAssetUpload = (prepared: Awaited<ReturnType<typeof prepareAss
return;
}
try {
+ prepared.task.startUpload();
if (prepared.task.input.files.length === 0) {
finishUpload(prepared.task, callbacks, {status: "canceled"});
return;
@@ -653,7 +674,7 @@ const startPreparedAssetUpload = (prepared: Awaited<ReturnType<typeof prepareAss
if (prepared.task.input.kind === "files") {
uploadPreparedFiles(prepared.task.input, protyle, callbacks, prepared.task);
} else {
- uploadPreparedLocalFiles(prepared.task.input, protyle, true, callbacks, prepared.task);
+ uploadPreparedLocalFiles(prepared.task.input, protyle, true, callbacks, prepared.task, options);
}
} catch (error) {
const errorMessage = getErrorMessage(error);
@@ -673,13 +694,13 @@ const startAssetUpload = (input: IAssetUploadInput, protyle: IProtyle, options:
context: getAssetUploadContext(options),
});
if (prepared instanceof Promise) {
- void prepared.then(result => startPreparedAssetUpload(result, protyle, callbacks)).catch(error => {
+ void prepared.then(result => startPreparedAssetUpload(result, protyle, callbacks, options)).catch(error => {
console.error(error);
finishCallbacks(callbacks, false);
showMessage(getErrorMessage(error) || window.siyuan.languages.uploadError);
});
} else {
- startPreparedAssetUpload(prepared, protyle, callbacks);
+ startPreparedAssetUpload(prepared, protyle, callbacks, options);
}
} catch (error) {
console.error(error);
@@ -688,14 +709,62 @@ const startAssetUpload = (input: IAssetUploadInput, protyle: IProtyle, options:
}
};
+export const uploadStandaloneAssetFiles = async (files: File[], options: {
+ source: TAssetUploadSource;
+ target: TAssetUploadTarget;
+ requiredFileCount?: number;
+ extraData?: Record<string, string | Blob>;
+}) => {
+ const prepared = await prepareAssetUpload({
+ plugins: [...(window.siyuan.ws?.app?.plugins || [])],
+ input: {kind: "files", files},
+ context: {
+ source: options.source,
+ target: options.target,
+ requiredFileCount: options.requiredFileCount,
+ allowedInputKinds: ["files"],
+ },
+ });
+ if (prepared.state !== "ready") {
+ if (prepared.state === "failed") {
+ showMessage(prepared.error || window.siyuan.languages.uploadError);
+ }
+ return;
+ }
+ prepared.task.startUpload();
+ if (prepared.task.input.kind !== "files" || prepared.task.input.files.length === 0) {
+ prepared.task.complete({status: "canceled"});
+ return;
+ }
+ const input = prepared.task.input;
+ const formData = new FormData();
+ input.files.forEach(file => formData.append("file[]", file));
+ Object.entries(options.extraData || {}).forEach(([key, value]) => formData.append(key, value));
+ try {
+ const response = await fetchSyncPost(Constants.UPLOAD_ADDRESS, formData);
+ const responseText = JSON.stringify(response);
+ const result = getAssetUploadResult(responseText, input);
+ prepared.task.complete(result);
+ if (getAssetUploadSuccesses(response.data).length === 0) {
+ return;
+ }
+ return response;
+ } catch (error) {
+ const errorMessage = getErrorMessage(error);
+ prepared.task.complete({status: "failed", error: errorMessage});
+ showMessage(errorMessage || window.siyuan.languages.uploadError);
+ }
+};
+
export const uploadLocalFiles = (files: ILocalFiles[], protyle: IProtyle, isUpload: boolean,
- options?: IUploadInsertOptions, successCB?: (response: IWebSocketData) => void,
+ options?: IUploadInsertOptions, successCB?: (response: IWebSocketData,
+ result: Omit<IAssetUploadResult, "requestId" | "input">) => void,
completeCB?: (succeeded: boolean) => void) => {
const uploadOptions = captureUploadInsertPosition(protyle, options);
const callbacks: IAssetUploadCallbacks = {
- success(responseText, response) {
+ success(responseText, response, _input, result) {
if (successCB) {
- return successCB(response);
+ return successCB(response, result);
} else {
return genUploadedLabel(responseText, protyle, uploadOptions);
}
@@ -704,7 +773,7 @@ export const uploadLocalFiles = (files: ILocalFiles[], protyle: IProtyle, isUplo
};
const input: IAssetUploadInput = {kind: "local-files", files: Array.from(files)};
if (!isUpload) {
- uploadPreparedLocalFiles(input, protyle, false, callbacks);
+ uploadPreparedLocalFiles(input, protyle, false, callbacks, undefined, uploadOptions);
return;
}
const linkedFiles = input.files.filter(item => {
@@ -717,7 +786,7 @@ export const uploadLocalFiles = (files: ILocalFiles[], protyle: IProtyle, isUplo
success: callbacks.success,
complete: assetFiles.length === 0 ? callbacks.complete : undefined,
reset: assetFiles.length === 0 ? callbacks.reset : undefined,
- });
+ }, undefined, uploadOptions);
}
if (assetFiles.length > 0) {
startAssetUpload({kind: "local-files", files: assetFiles}, protyle, uploadOptions, callbacks);
@@ -725,7 +794,9 @@ export const uploadLocalFiles = (files: ILocalFiles[], protyle: IProtyle, isUplo
};
export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferItemList | File[], element?: HTMLInputElement,
- successCB?: (res: string) => void, completeCB?: (succeeded: boolean) => void,
+ successCB?: (res: string,
+ result: Omit<IAssetUploadResult, "requestId" | "input">) => void,
+ completeCB?: (succeeded: boolean) => void,
options?: IUploadInsertOptions) => {
const uploadOptions = captureUploadInsertPosition(protyle, options);
let fileList: File[] = [];
@@ -772,18 +843,18 @@ export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferIte
}
const callbacks: IAssetUploadCallbacks = {
- success(responseText, response, input) {
+ success(responseText, response, input, result) {
if (protyle.options.upload.success) {
return protyle.options.upload.success(protyle.wysiwyg.element, responseText);
} else if (successCB) {
- return successCB(responseText);
+ return successCB(responseText, result);
} else {
- if (protyle.options.upload.format && input.kind === "files") {
- responseText = protyle.options.upload.format(input.files, responseText);
- }
return genUploadedLabel(responseText, protyle, uploadOptions);
}
},
+ formatResponse: !protyle.options.upload.success && !successCB && protyle.options.upload.format ?
+ (responseText, input) => input.kind === "files" ?
+ protyle.options.upload.format(input.files, responseText) : responseText : undefined,
complete: completeCB,
reset() {
if (element) {
diff --git a/app/src/protyle/upload/pluginEvent.test.ts b/app/src/protyle/upload/pluginEvent.test.ts
index 7f75f7571d..db8df24ca5 100644
--- a/app/src/protyle/upload/pluginEvent.test.ts
+++ b/app/src/protyle/upload/pluginEvent.test.ts
@@ -19,6 +19,28 @@ const protyle = {} as IProtyle;
const context = {source: "paste", target: "editor"} as const;
describe("asset upload plugin event", () => {
+ it("exposes target constraints for uploads without an editor", async () => {
+ let detail: IBeforeUploadAssetsDetail;
+ const prepared = await prepareAssetUpload({
+ plugins: [createPlugin(event => {
+ detail = event.detail;
+ })],
+ input: {kind: "files", files: [createFile("annotation.png")]},
+ context: {
+ source: "programmatic",
+ target: "pdf-annotation",
+ requiredFileCount: 1,
+ allowedInputKinds: ["files"],
+ },
+ });
+
+ assert.equal(prepared.state, "ready");
+ assert.equal(detail.protyle, undefined);
+ assert.equal(detail.requiredFileCount, 1);
+ assert.deepEqual(detail.allowedInputKinds, ["files"]);
+ prepared.task.complete({status: "canceled"});
+ });
+
it("preserves files when plugins do not respond", async () => {
const input: IAssetUploadInput = {kind: "files", files: [createFile("a.png")]};
const result = prepareAssetUpload({
@@ -363,6 +385,23 @@ describe("asset upload plugin event", () => {
assert.equal(signal.aborted, true);
});
+ it("aborts the upload phase when the editor is destroyed", async () => {
+ const currentProtyle = {} as IProtyle;
+ const prepared = await prepareAssetUpload({
+ plugins: [],
+ protyle: currentProtyle,
+ input: {kind: "files", files: [createFile("a.png")]},
+ context,
+ });
+ assert.equal(prepared.state, "ready");
+ prepared.task.startUpload();
+
+ cancelAssetUploads(currentProtyle);
+
+ assert.equal(prepared.task.signal.aborted, true);
+ prepared.task.complete({status: "canceled"});
+ });
+
it("cancels pending processing when the active plugin is unloaded", async () => {
let signal: AbortSignal;
const plugin = createPlugin(event => {
diff --git a/app/src/protyle/upload/pluginEvent.ts b/app/src/protyle/upload/pluginEvent.ts
index 5c948cee60..0442b74495 100644
--- a/app/src/protyle/upload/pluginEvent.ts
+++ b/app/src/protyle/upload/pluginEvent.ts
@@ -3,12 +3,14 @@ export interface IAssetUploadEventContext {
target: TAssetUploadTarget;
position?: IAssetUploadPosition;
requiredFileCount?: number;
+ allowedInputKinds?: Array<IAssetUploadInput["kind"]>;
}
export interface IAssetUploadTask {
readonly requestId: string;
readonly signal: AbortSignal;
input: IAssetUploadInput;
+ startUpload(): void;
complete(result: Omit<IAssetUploadResult, "requestId" | "input">): boolean;
}
@@ -43,6 +45,7 @@ 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 activeTasksByProtyle = new WeakMap<IProtyle, Set<AssetUploadTask>>();
const genRequestId = () => {
requestSequence++;
@@ -126,12 +129,15 @@ const getErrorMessage = (error: unknown) => {
const getPluginLabel = (plugin: IAssetUploadPlugin, index: number) => plugin.name || `#${index + 1}`;
const validateTargetInput = (input: IAssetUploadInput, context: IAssetUploadEventContext) => {
+ if (context.allowedInputKinds && !context.allowedInputKinds.includes(input.kind)) {
+ return `this upload only accepts ${context.allowedInputKinds.join(" or ")} input`;
+ }
if (context.requiredFileCount !== undefined && input.files.length !== context.requiredFileCount) {
+ if (context.target === "background") {
+ return "background uploads require exactly one file";
+ }
return `this upload requires exactly ${context.requiredFileCount} file(s)`;
}
- if (context.target === "background" && input.files.length !== 1) {
- return "background uploads require exactly one file";
- }
return "";
};
@@ -142,10 +148,11 @@ class AssetUploadTask implements IAssetUploadTask {
private completed = false;
private readonly abortController = new AbortController();
private readonly callbacks: Array<(result: IAssetUploadResult) => any> = [];
- private readonly protyle: IProtyle;
+ private readonly protyle?: IProtyle;
private waitingPlugins: IAssetUploadPlugin[] = [];
+ private uploadStarted = false;
- constructor(input: IAssetUploadInput, requestId: string, protyle: IProtyle) {
+ constructor(input: IAssetUploadInput, requestId: string, protyle?: IProtyle) {
this.input = cloneInput(input);
this.requestId = requestId;
this.protyle = protyle;
@@ -159,12 +166,14 @@ class AssetUploadTask implements IAssetUploadTask {
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);
+ if (this.protyle) {
+ let protyleTasks = waitingTasksByProtyle.get(this.protyle);
+ if (!protyleTasks) {
+ protyleTasks = new Set();
+ waitingTasksByProtyle.set(this.protyle, protyleTasks);
+ }
+ protyleTasks.add(this);
}
- protyleTasks.add(this);
plugins.forEach(plugin => {
let pluginTasks = waitingTasksByPlugin.get(plugin);
if (!pluginTasks) {
@@ -176,11 +185,26 @@ class AssetUploadTask implements IAssetUploadTask {
}
public stopWaiting() {
- waitingTasksByProtyle.get(this.protyle)?.delete(this);
+ if (this.protyle) {
+ waitingTasksByProtyle.get(this.protyle)?.delete(this);
+ }
this.waitingPlugins.forEach(plugin => waitingTasksByPlugin.get(plugin)?.delete(this));
this.waitingPlugins = [];
}
+ public startUpload() {
+ if (this.uploadStarted || !this.protyle) {
+ return;
+ }
+ this.uploadStarted = true;
+ let tasks = activeTasksByProtyle.get(this.protyle);
+ if (!tasks) {
+ tasks = new Set();
+ activeTasksByProtyle.set(this.protyle, tasks);
+ }
+ tasks.add(this);
+ }
+
public abort(reason: Error) {
if (!this.signal.aborted) {
this.abortController.abort(reason);
@@ -193,6 +217,9 @@ class AssetUploadTask implements IAssetUploadTask {
}
this.completed = true;
this.stopWaiting();
+ if (this.protyle) {
+ activeTasksByProtyle.get(this.protyle)?.delete(this);
+ }
const detail: IAssetUploadResult = {
...result,
requestId: this.requestId,
@@ -224,6 +251,7 @@ const cancelWaitingTasks = (tasks: Set<AssetUploadTask> | undefined, reason: str
export const cancelAssetUploads = (protyle: IProtyle) => {
cancelWaitingTasks(waitingTasksByProtyle.get(protyle), "The editor was destroyed");
+ cancelWaitingTasks(activeTasksByProtyle.get(protyle), "The editor was destroyed");
};
export const cancelAssetUploadsByPlugin = (plugin: IAssetUploadPlugin) => {
@@ -259,7 +287,7 @@ const waitForDecision = (response: PromiseLike<IAssetUploadDecision>, task: Asse
export const prepareAssetUpload = (options: {
plugins: IAssetUploadPlugin[];
- protyle: IProtyle;
+ protyle?: IProtyle;
input: IAssetUploadInput;
context: IAssetUploadEventContext;
requestId?: string;
@@ -268,6 +296,11 @@ export const prepareAssetUpload = (options: {
const task = new AssetUploadTask(options.input, options.requestId || genRequestId(), options.protyle);
const plugins = Array.from(options.plugins);
const timeout = options.timeout ?? ASSET_UPLOAD_PLUGIN_TIMEOUT;
+ const context = {
+ ...options.context,
+ requiredFileCount: options.context.requiredFileCount ??
+ (options.context.target === "background" ? 1 : undefined),
+ };
const fail = (error: unknown): TPreparedAssetUpload => {
const errorMessage = getErrorMessage(error);
task.abort(error instanceof Error ? error : new Error(errorMessage));
@@ -279,7 +312,7 @@ export const prepareAssetUpload = (options: {
task.complete({status: "canceled"});
return {state: "canceled", task};
};
- const initialValidationError = validateTargetInput(task.input, options.context);
+ const initialValidationError = validateTargetInput(task.input, context);
if (initialValidationError) {
return fail(initialValidationError);
}
@@ -309,9 +342,11 @@ export const prepareAssetUpload = (options: {
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 ? {...options.context.position} : undefined,
+ source: context.source,
+ target: context.target,
+ position: context.position ? {...context.position} : undefined,
+ requiredFileCount: context.requiredFileCount,
+ allowedInputKinds: context.allowedInputKinds ? Array.from(context.allowedInputKinds) : undefined,
input: cloneInput(task.input),
signal: task.signal,
respondWith(value) {
@@ -369,7 +404,7 @@ export const prepareAssetUpload = (options: {
if (validationError) {
throw new Error(`Plugin ${pluginLabel} returned invalid input: ${validationError}`);
}
- const targetValidationError = validateTargetInput(decision.input, options.context);
+ const targetValidationError = validateTargetInput(decision.input, context);
if (targetValidationError) {
throw new Error(`Plugin ${pluginLabel} returned invalid input: ${targetValidationError}`);
}
diff --git a/app/src/protyle/upload/uploadHandler.test.ts b/app/src/protyle/upload/uploadHandler.test.ts
new file mode 100644
index 0000000000..711eba62be
--- /dev/null
+++ b/app/src/protyle/upload/uploadHandler.test.ts
@@ -0,0 +1,18 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {AssetUploadHandlerTimeoutError, waitForUploadHandler} from "./uploadHandler";
+
+describe("custom upload handler", () => {
+ it("stops waiting when the editor signal is aborted", async () => {
+ const controller = new AbortController();
+ const pending = waitForUploadHandler(new Promise<null>(() => undefined), controller.signal, 1_000);
+ controller.abort(new Error("The editor was destroyed"));
+
+ await assert.rejects(pending, /The editor was destroyed/);
+ });
+
+ it("stops waiting after the handler timeout", async () => {
+ await assert.rejects(waitForUploadHandler(new Promise<null>(() => undefined),
+ new AbortController().signal, 1), AssetUploadHandlerTimeoutError);
+ });
+});
diff --git a/app/src/protyle/upload/uploadHandler.ts b/app/src/protyle/upload/uploadHandler.ts
new file mode 100644
index 0000000000..bb03390ca3
--- /dev/null
+++ b/app/src/protyle/upload/uploadHandler.ts
@@ -0,0 +1,30 @@
+export const ASSET_UPLOAD_HANDLER_TIMEOUT = 120_000;
+
+export class AssetUploadHandlerTimeoutError extends Error {
+}
+
+export const waitForUploadHandler = <T>(result: PromiseLike<T>, signal: AbortSignal,
+ timeout = ASSET_UPLOAD_HANDLER_TIMEOUT) => {
+ return new Promise<T>((resolve, reject) => {
+ let settled = false;
+ const finish = (callback: (value: any) => void, value: any) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ clearTimeout(timeoutId);
+ signal.removeEventListener("abort", onAbort);
+ callback(value);
+ };
+ 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);
+ signal.addEventListener("abort", onAbort, {once: true});
+ if (signal.aborted) {
+ onAbort();
+ return;
+ }
+ Promise.resolve(result).then(value => finish(resolve, value), error => finish(reject, error));
+ });
+};
diff --git a/app/src/protyle/upload/uploadResult.test.ts b/app/src/protyle/upload/uploadResult.test.ts
index 62ff69aac2..ccd34cddec 100644
--- a/app/src/protyle/upload/uploadResult.test.ts
+++ b/app/src/protyle/upload/uploadResult.test.ts
@@ -1,6 +1,6 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {getAssetUploadResult, getAssetUploadSuccesses} from "./uploadResult";
+import {getAssetUploadPathsByInput, getAssetUploadResult, getAssetUploadSuccesses} from "./uploadResult";
const createFile = (name: string) => new File(["content"], name, {type: "image/png"});
@@ -69,6 +69,24 @@ describe("asset upload result", () => {
assert.deepEqual(result.rejected, rejected);
});
+ it("maps partial successes back to the original input indexes", () => {
+ const result = {
+ status: "partial" as const,
+ rejected: [{index: 1, name: "b.png", reasons: ["size-limit" as const]}],
+ succFiles: [
+ {index: 0, name: "a.png", path: "assets/a.png"},
+ {index: 2, name: "d.png", path: "assets/d.png"},
+ ],
+ };
+
+ assert.deepEqual(getAssetUploadPathsByInput(4, result), [
+ "assets/a.png",
+ undefined,
+ undefined,
+ "assets/d.png",
+ ]);
+ });
+
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 0a04691e06..b7a3496465 100644
--- a/app/src/protyle/upload/uploadResult.ts
+++ b/app/src/protyle/upload/uploadResult.ts
@@ -8,6 +8,22 @@ export const getAssetUploadSuccesses = (data?: {
return Object.entries(data?.succMap || {}).map(([name, path], index) => ({index, name, path}));
};
+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]));
+ let acceptedIndex = 0;
+ for (let inputIndex = 0; inputIndex < inputCount; inputIndex++) {
+ if (rejected.has(inputIndex)) {
+ continue;
+ }
+ paths[inputIndex] = succeeded.get(acceptedIndex);
+ acceptedIndex++;
+ }
+ return paths;
+};
+
export const getAssetUploadResult = (responseText: string, acceptedInput: IAssetUploadInput,
rejected: IAssetUploadRejection[] = []):
Omit<IAssetUploadResult, "requestId" | "input"> => {
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index 7661f81337..3d77991b83 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -19,6 +19,8 @@ import {fixAdjacentTags, getCalloutInfo, getContenteditableElement} from "../wys
import {clearBlockElement} from "./clear";
import {removeZWJ} from "./normalizeText";
import {base64ToURL} from "../upload/base64";
+import {applyHTMLLocalAssetPaths, collectHTMLLocalAssets} from "../upload/htmlLocalAssets";
+import {getAssetUploadPathsByInput} from "../upload/uploadResult";
import {resolveLinkDest} from "../toolbar/util";
import {updateTransaction} from "../wysiwyg/transaction";
import * as dayjs from "dayjs";
@@ -1037,6 +1039,19 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
insertHTML(tempElement.innerHTML, protyle, false, false, true);
return;
}
+ const localAssets = collectHTMLLocalAssets(tempElement);
+ if (localAssets.length > 0) {
+ await new Promise<void>(resolve => {
+ uploadLocalFiles(localAssets.map(item => ({path: item.path, size: null})), protyle, true, {
+ ...assetUploadOptions,
+ requiredFileCount: localAssets.length,
+ fromHTMLPaste: true,
+ }, (_response, result) => {
+ applyHTMLLocalAssetPaths(localAssets,
+ getAssetUploadPathsByInput(localAssets.length, result));
+ }, () => resolve());
+ });
+ }
fetchPost("/api/lute/html2BlockDOM", {
dom: tempElement.innerHTML,
text: textPlain,
@@ -1044,6 +1059,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
office,
officeMathHTML,
wps,
+ skipLocalAssets: localAssets.length > 0,
}, (response) => {
insertConvertedBlockDOM(protyle, response.data);
});
@@ -1094,14 +1110,19 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
const tempElement = document.createElement("template");
tempElement.innerHTML = textPlainDom;
const imgSrcList: string[] = [];
- const imageElements = tempElement.content.querySelectorAll("img");
- imageElements.forEach((item) => {
- if (item.getAttribute("data-src").startsWith("data:image/")) {
- imgSrcList.push(item.getAttribute("data-src"));
+ const imageElements: HTMLImageElement[] = [];
+ tempElement.content.querySelectorAll("img").forEach((item) => {
+ const dataSrc = item.getAttribute("data-src");
+ if (dataSrc?.startsWith("data:image/")) {
+ imgSrcList.push(dataSrc);
+ imageElements.push(item);
}
});
const base64SrcList = await base64ToURL(imgSrcList, protyle, assetUploadOptions);
base64SrcList.forEach((item, index) => {
+ if (!item) {
+ return;
+ }
imageElements[index].setAttribute("src", item);
imageElements[index].setAttribute("data-src", item);
imageElements[index].parentElement.querySelector(".img__net")?.remove();
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 38738754e4..f4065b8349 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -385,7 +385,7 @@ interface ILocalFiles {
}
type TAssetUploadSource = "paste" | "drop" | "file-picker" | "programmatic"
-type TAssetUploadTarget = "editor" | "av-cell" | "background"
+type TAssetUploadTarget = "editor" | "av-cell" | "background" | "pdf-annotation"
type TAssetUploadStatus = "success" | "partial" | "failed" | "canceled"
type TAssetUploadRejectionReason = "name-empty" | "size-limit" | "type-not-accepted"
@@ -448,16 +448,24 @@ interface IAssetUploadResult {
/** 不得在该事件上调用 `preventDefault()`,取消上传应使用 `respondWith({action: "cancel"})`。 */
interface IBeforeUploadAssetsDetail {
requestId: string,
- protyle: IProtyle,
+ /** PDF 标注等无编辑器上传场景不提供该字段。 */
+ protyle?: IProtyle,
source: TAssetUploadSource,
target: TAssetUploadTarget,
position?: IAssetUploadPosition,
+ /** 替换输入必须保持的精确文件数量。 */
+ requiredFileCount?: number,
+ /** 当前目标支持的输入类型;未提供时支持 files 和 local-files。 */
+ allowedInputKinds?: Array<IAssetUploadInput["kind"]>,
input: IAssetUploadInput,
/** 插件处理的取消信号,编辑器销毁、插件卸载或处理超时时触发。 */
signal: AbortSignal,
/** 必须同步调用且每次事件只允许调用一次,异步处理应将 Promise 作为参数传入,每个插件默认 120 秒超时。 */
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 b56f2049e8..0a97310d88 100644
--- a/app/src/types/protyle.d.ts
+++ b/app/src/types/protyle.d.ts
@@ -357,8 +357,8 @@ interface IUpload {
/** 校验,成功时返回 true 否则返回错误信息 */
validate?(files: File[]): string | boolean;
- /** 自定义上传,返回 Promise 时将在其完成后报告上传结果,发生错误时返回错误信息 */
- handler?(files: File[]): string | null | PromiseLike<string | null>;
+ /** 自定义上传,返回 Promise 时将在其完成后报告上传结果,发生错误时返回错误信息,默认 120 秒超时 */
+ handler?(files: File[], options?: { signal: AbortSignal }): string | null | PromiseLike<string | null>;
/** 对服务端返回的数据进行转换,以满足内置的数据结构 */
format?(files: File[], responseText: string): string;
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index 3c942b0783..d1cbba0fc8 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -612,7 +612,16 @@ func insertLocalAssets(c *gin.Context) {
isUpload = isUploadArg.(bool)
}
id := arg["id"].(string)
- succMap, succFiles, failedFiles, err := model.InsertLocalAssets(id, assetPaths, isUpload)
+ fromHTMLPaste, _ := arg["fromHTMLPaste"].(bool)
+ var succMap map[string]any
+ var succFiles []model.AssetUploadSuccess
+ var failedFiles []model.AssetUploadFailure
+ var err error
+ if fromHTMLPaste {
+ succMap, succFiles, failedFiles, err = model.InsertHTMLLocalAssets(id, assetPaths)
+ } else {
+ succMap, succFiles, failedFiles, err = model.InsertLocalAssets(id, assetPaths, isUpload)
+ }
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index 57726d8aef..0891fa28d6 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -110,6 +110,7 @@ func html2BlockDOM(c *gin.Context) {
office, _ := arg["office"].(string)
officeMathHTML, _ := arg["officeMathHTML"].(string)
wps, _ := arg["wps"].(string)
+ skipLocalAssets, _ := arg["skipLocalAssets"].(bool)
luteEngine := util.NewLute()
luteEngine.SetHTMLTag2TextMark(true)
luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})
@@ -179,7 +180,7 @@ func html2BlockDOM(c *gin.Context) {
}
}
- if util.ContainerStd == model.Conf.System.Container {
+ if util.ContainerStd == model.Conf.System.Container && !skipLocalAssets {
// 处理本地资源文件复制
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || ast.NodeLinkDest != n.Type {
diff --git a/kernel/model/upload.go b/kernel/model/upload.go
index 0c4ef26462..620d712652 100644
--- a/kernel/model/upload.go
+++ b/kernel/model/upload.go
@@ -118,6 +118,16 @@ func recordAssetUploadFailure(failedFiles *[]AssetUploadFailure, index int, name
}
func InsertLocalAssets(id string, assetAbsPaths []string, isUpload bool) (succMap map[string]any,
+ succFiles []AssetUploadSuccess, failedFiles []AssetUploadFailure, err error) {
+ return insertLocalAssets(id, assetAbsPaths, isUpload, false)
+}
+
+func InsertHTMLLocalAssets(id string, assetAbsPaths []string) (succMap map[string]any,
+ succFiles []AssetUploadSuccess, failedFiles []AssetUploadFailure, err error) {
+ return insertLocalAssets(id, assetAbsPaths, true, true)
+}
+
+func insertLocalAssets(id string, assetAbsPaths []string, isUpload, validateHTMLPath bool) (succMap map[string]any,
succFiles []AssetUploadSuccess, failedFiles []AssetUploadFailure, err error) {
succMap = map[string]any{}
succFiles = make([]AssetUploadSuccess, 0, len(assetAbsPaths))
@@ -138,7 +148,14 @@ func InsertLocalAssets(id string, assetAbsPaths []string, isUpload bool) (succMa
}
for index, assetAbsPath := range assetAbsPaths {
+ if strings.HasPrefix(strings.ToLower(assetAbsPath), "file://") {
+ assetAbsPath = util.FileURLToLocalPath(assetAbsPath)
+ }
baseName := filepath.Base(assetAbsPath)
+ if validateHTMLPath && (util.IsSensitivePath(assetAbsPath) || EncryptedRawPathBoxID(assetAbsPath) != "") {
+ recordAssetUploadFailure(&failedFiles, index, baseName, errors.New("local asset path is not allowed"))
+ continue
+ }
fName := baseName
fName = util.FilterUploadFileName(fName)
ext := filepath.Ext(fName)