Skip to content

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

:recycle: Migrate asset API contracts https://github.com/siyuan-note/siyuan/issues/19378

Daniel67c8d90c8ae5
diff --git a/.github/workflows/api-contracts.yml b/.github/workflows/api-contracts.yml
index bded6aafb3..8011f84161 100644
--- a/.github/workflows/api-contracts.yml
+++ b/.github/workflows/api-contracts.yml
@@ -43,7 +43,10 @@ jobs:
run: go test ./apicontract/...
working-directory: kernel
- name: Test actual API responses and compatibility
- run: go test -tags "fts5 sqlcipher" ./api ./plugin -run "TestAPIContract|TestBazaarContract|TestRepoContract|TestRepoFileWireCompatibility|TestRPC.*Contract|TestRPCWebSocketOriginCheck|TestBlockAttrsRespectPublishAccess|TestGetBlockInfoRecovery|TestGetBlockInfoPublishAccess|TestListNotebooksSortsBySubDocCount|TestContract.*NotebookResponseLease" -count=1
+ run: go test -tags "fts5 sqlcipher" ./api ./plugin -run "TestAPIContract|TestAsset.*Contract|TestInsertLocalAssets|TestSetFileAnnotation|TestDeferredAsset|TestExportBrowserHTML|TestCopyExport|TestBazaarContract|TestRepoContract|TestRepoFileWireCompatibility|TestRPC.*Contract|TestRPCWebSocketOriginCheck|TestBlockAttrsRespectPublishAccess|TestGetBlockInfoRecovery|TestGetBlockInfoPublishAccess|TestListNotebooksSortsBySubDocCount|TestContract.*NotebookResponseLease" -count=1
+ working-directory: kernel
+ - name: Test upload model compatibility
+ run: go test -tags "fts5 sqlcipher" ./model -run "TestMultipartUpload|TestInsertLocalAssets|TestRecordAssetUpload|TestReadRTFD|TestCopyRTFD" -count=1
working-directory: kernel
- name: Test frontend transport behavior
run: pnpm exec tsx --test src/util/fetch.test.ts src/util/fetchTimeout.test.ts
diff --git a/app/src/asset/anno.ts b/app/src/asset/anno.ts
index ec97abc213..774717f4f2 100644
--- a/app/src/asset/anno.ts
+++ b/app/src/asset/anno.ts
@@ -1170,7 +1170,7 @@ const getConfig = (pdf: any) => {
path: urlPath,
}, (response) => {
let config = {};
- if (response.code !== 1) {
+ if (response.code === 0) {
try {
config = JSON.parse(response.data.data);
} catch (e) {
diff --git a/app/src/asset/index.ts b/app/src/asset/index.ts
index ff37582b5e..2f4fdf92df 100644
--- a/app/src/asset/index.ts
+++ b/app/src/asset/index.ts
@@ -67,7 +67,7 @@ export class Asset extends Model {
if (this.pdfLoadState.isDestroyed) {
return;
}
- if (response.code !== 1) {
+ if (response.code === 0) {
const config = JSON.parse(response.data.data);
if (config[this.pdfId]) {
this.pdfPage = config[this.pdfId].page ? config[this.pdfId].page + 1 : config[this.pdfId].pages[0].index + 1;
diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.ts
index 8576d99bbf..d9138f976b 100644
--- a/app/src/menus/protyle.ts
+++ b/app/src/menus/protyle.ts
@@ -1361,7 +1361,6 @@ export const imgMenu = (protyle: IProtyle, range: Range, assetElement: HTMLEleme
click() {
fetchPost("/api/asset/ocr", {
path: imgElement.getAttribute("src"),
- force: true
});
}
}],
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 3251fc3f82..676361536c 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -10,12 +10,48 @@ export type AppendBlockRequestInput = { "data": string; "dataType": string; "par
export type AppendHeadingChildrenRequestInput = { "childrenDOM": string; "id": string; };
+export type AssetAnnotationData = { "data": string; };
+
+export type AssetCloudUploadRequestInput = { "id": string; "ignorePushMsg"?: boolean | null; };
+
export type AssetContent = { "content": string; "ext": string; "hSize": string; "id": string; "name": string; "path": string; "size": number; "updated": number; };
export type AssetContentData = { "assetContent": AssetContent | null; };
export type AssetContentRequestInput = { "id": string; "query": string; "queryMethod": number; };
+export type AssetDocumentAssetsRequestInput = { "id": string; "retainQueryStr"?: boolean | null; };
+
+export type AssetDocumentRequestInput = { "id": string; };
+
+export type AssetInsertCoverData = { "succFiles": Array<AssetUploadSuccess> | null; "succMap": Record<string, string> | null; };
+
+export type AssetOCRData = { "ocrJSON": Array<Record<string, string> | null> | null; "text": string; };
+
+export type AssetOCRTextRequestInput = { "path"?: string | null; };
+
+export type AssetPathData = { "path": string; };
+
+export type AssetPathRequestInput = { "path": string; };
+
+export type AssetPathsCloudUploadRequestInput = { "ignorePushMsg"?: boolean | null; "paths": Array<string>; };
+
+export type AssetPathsData = { "paths": Array<string> | null; };
+
+export type AssetRenameData = { "newPath": string; };
+
+export type AssetStatData = { "created": number; "downloaded"?: false; "hCreated": string; "hSize": string; "hUpdated": string; "size": number; "updated": number; };
+
+export type AssetTextData = { "text": string; };
+
+export type AssetUnusedItem = { "blockIDs"?: Array<string>; "item": string; "name": string; "path"?: string; };
+
+export type AssetUploadData = { "errFiles": Array<string> | null; "failedFiles": Array<AssetUploadFailure> | null; "succFiles": Array<AssetUploadSuccess> | null; "succMap": Record<string, string> | null; };
+
+export type AssetUploadFailure = { "error": string; "index": number; "name": string; };
+
+export type AssetUploadSuccess = { "index": number; "name": string; "path": string; };
+
export type AttributeViewColorTheme = { "backgroundColor": string; "color": string; };
export type AttributeViewColorThemeInput = { "backgroundColor"?: string | null; "color"?: string | null; };
@@ -556,6 +592,10 @@ export type InlineStyles = { "av": InlineStyleAV | null; "builtin": InlineStyleB
export type InsertBlockRequestInput = { "data": string; "dataType": string; "nextID"?: string | null; "parentID"?: string | null; "previousID"?: string | null; };
+export type InsertCoverRequestInput = { "id": string; "name": string; };
+
+export type InsertLocalAssetsRequestInput = { "assetPaths": Array<string>; "fromHTMLPaste"?: boolean | null; "id"?: string | null; "isUpload"?: boolean | null; };
+
export type InstallBazaarIconRequestInput = { "keyword"?: string | null; "packageName": string; "repoHash": string; "repoRef"?: string | null; "repoURL": string; };
export type InstallBazaarPluginRequestInput = { "frontend": string; "keyword"?: string | null; "packageName": string; "repoHash": string; "repoRef"?: string | null; "repoURL": string; };
@@ -728,6 +768,8 @@ export type RemoveShorthandsRequestInput = { "ids": Array<string>; };
export type RemoveTagRequestInput = { "label": string; };
+export type RenameAssetRequestInput = { "newName": string; "oldPath": string; };
+
export type RenameBookmarkRequestInput = { "newBookmark": string; "oldBookmark": string; };
export type RenameFileRequestInput = { "newPath": string; "path": string; };
@@ -892,6 +934,10 @@ export type SearchWidgetData = { "k": string; "widgets": Array<SearchWidgetResul
export type SearchWidgetResult = { "content": string; "name": string; };
+export type SetAssetAnnotationRequestInput = { "data": string; "path": string; };
+
+export type SetAssetOCRTextRequestInput = { "path": string; "text": string; };
+
export type SetBazaarPackageRatingRequestInput = { "packageName": string; "packageType": string; "rating": number; };
export type SetBlockAttrsRequestInput = { "attrs": Record<string, string | null>; "id": string; };
@@ -1056,6 +1102,8 @@ export type UpdateEmbedBlockRequestInput = { "content": string; "id": string; };
export type UpdatePinnedDocsRequestInput = { "action": string; "after"?: boolean; "ids": Array<string>; "targetID"?: string; };
+export type UploadAssetRequestInput = { "assetsDirPath"?: string; "file[]"?: Array<Blob>; "id"?: string; };
+
export type UploadCloudSnapshotRequestInput = { "id": string; "tag": string; };
export type ViewStatePatchRequestInput = { "key": string; "removeKeys"?: Array<string> | null; "values"?: { [key: string]: JSONValue }; };
@@ -1169,26 +1217,6 @@ export type APILegacyPOSTPath =
"/api/ai/testEmbeddingModel" |
"/api/ai/testModel" |
"/api/ai/testRerankModel" |
- "/api/asset/fullReindexAssetContent" |
- "/api/asset/getDocAssets" |
- "/api/asset/getDocImageAssets" |
- "/api/asset/getFileAnnotation" |
- "/api/asset/getImageOCRText" |
- "/api/asset/getMissingAssets" |
- "/api/asset/getUnusedAssets" |
- "/api/asset/insertCover" |
- "/api/asset/insertLocalAssets" |
- "/api/asset/ocr" |
- "/api/asset/removeUnusedAsset" |
- "/api/asset/removeUnusedAssets" |
- "/api/asset/renameAsset" |
- "/api/asset/resolveAssetPath" |
- "/api/asset/setFileAnnotation" |
- "/api/asset/setImageOCRText" |
- "/api/asset/statAsset" |
- "/api/asset/upload" |
- "/api/asset/uploadCloud" |
- "/api/asset/uploadCloudByAssetsPaths" |
"/api/av/addAttributeViewBlocks" |
"/api/av/addAttributeViewKey" |
"/api/av/appendAttributeViewDetachedBlocksWithValues" |
@@ -1385,6 +1413,106 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/asset/fullReindexAssetContent": {
+ request: EmptyRequestInput;
+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "none";
+ };
+ "/api/asset/getDocAssets": {
+ request: AssetDocumentAssetsRequestInput;
+ response: { "code": 0; "data": Array<string> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/getDocImageAssets": {
+ request: AssetDocumentRequestInput;
+ response: { "code": 0; "data": Array<string> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/getFileAnnotation": {
+ request: AssetPathRequestInput;
+ response: { "code": 0; "data": AssetAnnotationData; "msg": string; } | { "code": -1 | 1 | 403; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/getImageOCRText": {
+ request: AssetOCRTextRequestInput;
+ response: { "code": 0; "data": AssetTextData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/getMissingAssets": {
+ request: EmptyRequestInput;
+ response: { "code": 0; "data": Array<AssetUnusedItem | null> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "none";
+ };
+ "/api/asset/getUnusedAssets": {
+ request: EmptyRequestInput;
+ response: { "code": 0; "data": Array<AssetUnusedItem | null> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "none";
+ };
+ "/api/asset/insertCover": {
+ request: InsertCoverRequestInput;
+ response: { "code": 0; "data": AssetInsertCoverData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/insertLocalAssets": {
+ request: InsertLocalAssetsRequestInput;
+ response: { "code": 0; "data": AssetUploadData; "msg": string; } | { "code": -1; "data": ({ "closeTimeout": number; } & { "errFiles"?: never; "failedFiles"?: never; "succFiles"?: never; "succMap"?: never; }) | null | (AssetUploadData & { "closeTimeout"?: never; }); "msg": string; };
+ body: "json";
+ };
+ "/api/asset/ocr": {
+ request: AssetPathRequestInput;
+ response: { "code": 0; "data": AssetOCRData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/removeUnusedAsset": {
+ request: AssetPathRequestInput;
+ response: { "code": 0; "data": AssetPathData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/removeUnusedAssets": {
+ request: EmptyRequestInput;
+ response: { "code": 0; "data": AssetPathsData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "none";
+ };
+ "/api/asset/renameAsset": {
+ request: RenameAssetRequestInput;
+ response: { "code": 0; "data": AssetRenameData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/resolveAssetPath": {
+ request: AssetPathRequestInput;
+ response: { "code": 0; "data": string; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/setFileAnnotation": {
+ request: SetAssetAnnotationRequestInput;
+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/setImageOCRText": {
+ request: SetAssetOCRTextRequestInput;
+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/statAsset": {
+ request: AssetPathRequestInput;
+ response: { "code": 0; "data": AssetStatData; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/upload": {
+ request: UploadAssetRequestInput;
+ response: { "code": 0; "data": AssetUploadData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "multipart";
+ };
+ "/api/asset/uploadCloud": {
+ request: AssetCloudUploadRequestInput;
+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/asset/uploadCloudByAssetsPaths": {
+ request: AssetPathsCloudUploadRequestInput;
+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/attr/batchGetBlockAttrs": {
request: BlockIDsRequestInput;
response: { "code": 0; "data": Record<string, Record<string, string> | null>; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/tests/api-contract.types.ts b/app/tests/api-contract.types.ts
index ce719d1849..2a878fce94 100644
--- a/app/tests/api-contract.types.ts
+++ b/app/tests/api-contract.types.ts
@@ -6,6 +6,24 @@ declare const fetchGet: FetchGet;
declare const fetchSyncPost: FetchSyncPost;
declare const dynamicURL: string;
+fetchPost("/api/asset/upload", new ContractFormData({"file[]": [new Blob(), new Blob()], assetsDirPath: "assets"}), response => {
+ const uploaded: string | undefined = response.data.succMap?.["example.txt"];
+ void uploaded;
+});
+fetchPost("/api/asset/statAsset", {path: "assets/example.txt"}, response => {
+ if (response.code === 0) {
+ const downloaded: false | undefined = response.data.downloaded;
+ void downloaded;
+ }
+});
+fetchPost("/api/asset/getImageOCRText", {path: null});
+// @ts-expect-error 批量上传文件必须为二进制数组。
+fetchPost("/api/asset/upload", new ContractFormData({"file[]": ["example.txt"]}));
+// @ts-expect-error 附件地址必须为字符串。
+fetchPost("/api/asset/statAsset", {path: 123});
+// @ts-expect-error 本地附件插入必须提供路径数组。
+fetchPost("/api/asset/insertLocalAssets", {id: "document"});
+
fetchPost("/api/export/exportHTML", {id: "document", pdf: false}, response => {
const folder: string | undefined = response.data.folder;
void folder;
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index 1b7d6b5a88..3f3d819b18 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -24,6 +24,8 @@ Encrypted notebook lifecycle endpoints use typed requests and responses while re
## Compatibility requirements
+Asset contracts retain nullable result lists, per-file upload order and duplicate names, successful partial-upload messages, and local-insertion failure payloads. OCR columns remain string-valued. Annotation validation, published-file admission, encrypted reads and writes, deferred downloads, and upload target selection keep their existing behavior. The non-API upload entry uses the same typed model operation.
+
Export contracts retain Markdown option defaults and numeric truncation, notebook-list filtering, ignored title-option types, optional HTML folders, and file-upload field selection. Error responses preserve message durations and empty-string resource payloads. Publish filtering, encrypted-notebook admission, response-held leases, and temporary export cleanup remain in the existing lifecycle.
Repository contracts retain key encoding, snapshot metadata, numeric truncation and retention defaults, cloud pagination, and file access leases. Repository-file reads retain their media type and bytes; empty files retain the success envelope. Both file success and JSON failure use HTTP 200. For this explicitly declared shared status, `ValidateHTTPResponse` accepts raw file bytes and `ValidateErrorResponse` separately verifies known error payloads. No key material, encrypted file format, or snapshot recovery behavior changes.
@@ -92,6 +94,8 @@ Optional `*string` form fields preserve omission separately from an explicit emp
Use `MultipartBody` for file uploads. Request structs declare string fields and `*multipart.FileHeader` fields using their wire names; file schemas use `type: string` and `format: binary`, generating `Blob` declarations. The adapter retains Gin multipart parsing and binds the first value for repeated fields. File contents remain available through `Open`, so handlers preserve their read and recovery logic. Unsupported field types and binding options fail generation.
+Fixed fields declared as `[]*multipart.FileHeader` receive all files in their original order and generate `Array<Blob>`. An optional absent file list remains nil. Text and single-file fields still select the first value. `SuccessWithMessage` retains nonempty messages on successful responses, including partial batch uploads.
+
Frontend callers construct `ContractFormData` from typed fields before passing it to the existing fetch functions. The generated signatures require the endpoint's fields and distinguish file values from strings; raw `FormData` cannot satisfy a migrated upload contract. Optional fields are omitted and string values are not trimmed. Plugin callers can implement the generated `APIFormData<Request>` interface when constructing their forms.
## Endpoint maintenance
@@ -124,7 +128,8 @@ Run from `kernel/`:
```text
go test ./apicontract/...
-go test -tags "fts5 sqlcipher" ./api ./plugin -run "TestAPIContract|TestBazaarContract|TestRepoContract|TestRepoFileWireCompatibility|TestRPC.*Contract|TestRPCWebSocketOriginCheck|TestBlockAttrsRespectPublishAccess|TestGetBlockInfoRecovery|TestGetBlockInfoPublishAccess|TestListNotebooksSortsBySubDocCount|TestContract.*NotebookResponseLease" -count=1
+go test -tags "fts5 sqlcipher" ./model -run "TestMultipartUpload|TestInsertLocalAssets|TestRecordAssetUpload|TestReadRTFD|TestCopyRTFD" -count=1
+go test -tags "fts5 sqlcipher" ./api ./plugin -run "TestAPIContract|TestAsset.*Contract|TestInsertLocalAssets|TestSetFileAnnotation|TestDeferredAsset|TestExportBrowserHTML|TestCopyExport|TestBazaarContract|TestRepoContract|TestRepoFileWireCompatibility|TestRPC.*Contract|TestRPCWebSocketOriginCheck|TestBlockAttrsRespectPublishAccess|TestGetBlockInfoRecovery|TestGetBlockInfoPublishAccess|TestListNotebooksSortsBySubDocCount|TestContract.*NotebookResponseLease" -count=1
```
`tsconfig.api.json` separately enables strict checks and declaration-file checking for invalid parameters, misspelled fields, required bodies, success and failure branches, nullability, and method mismatches. The main application retains its existing configuration; do not assume strict null checks apply to every call. Handler tests use temporary workspaces and isolated test processes without starting or restarting the running kernel.
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index 7480fdac5f..9abed44d05 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -24,6 +24,8 @@
## 兼容要求
+附件契约保留结果列表的空值、逐文件上传顺序与重名文件、部分上传成功时的提示及本地插入失败载荷。OCR 列保持字符串值。标注校验、发布文件准入、加密读写、延迟下载和上传目标选择保持既有行为。非 API 上传入口复用同一个有类型的模型操作。
+
导出契约保留 Markdown 选项默认值与数字截断、笔记本列表过滤、标题选项类型忽略规则、可省略的 HTML 目录字段及上传字段选择规则。错误响应保留消息显示时长与资源错误中的空字符串载荷。发布过滤、加密笔记本准入、覆盖响应阶段的租约及临时导出清理保持既有生命周期。
仓库契约保留密钥编码、快照元数据、数值截断与保留期限默认值、云端分页及文件访问租约。仓库文件读取保留媒体类型和原始字节,空文件保留成功信封。文件成功与 JSON 失败均返回 HTTP 200。对于显式声明的共用状态,`ValidateHTTPResponse` 接受文件原始字节,`ValidateErrorResponse` 单独验证已知错误载荷。密钥材料、加密文件格式及快照恢复行为保持不变。
@@ -92,6 +94,8 @@ SQL 查询契约保留成功信封顶层的 `limit` 和 `truncated`。`SuccessSQ
文件上传使用 `MultipartBody`。请求结构体以线协议字段名声明字符串和 `*multipart.FileHeader` 字段;文件 schema 使用 `type: string` 与 `format: binary`,生成 `Blob` 类型。适配器保留 Gin 的表单解析方式,重复字段取首值;文件内容继续通过 `Open` 读取,处理函数保留读取及恢复逻辑。未支持的字段类型和绑定选项会使生成失败。
+声明为 `[]*multipart.FileHeader` 的固定字段按原顺序接收全部文件,生成 `Array<Blob>`。可选文件列表缺省时保留 nil;文本与单文件字段仍取首值。`SuccessWithMessage` 保留成功响应中的非空提示,包括批量上传部分成功的情况。
+
前端从类型化字段构造 `ContractFormData`,再交给现有请求函数。生成签名检查端点所需字段并区分文件与字符串,普通 `FormData` 不能满足已迁移上传接口的契约。可缺省字段不写入表单,字符串不裁剪空白。插件调用方构造表单时可实现生成的 `APIFormData<Request>` 接口。
## 接口维护流程
@@ -124,7 +128,8 @@ pnpm exec tsx --test src/util/fetch.test.ts src/util/fetchTimeout.test.ts
```text
go test ./apicontract/...
-go test -tags "fts5 sqlcipher" ./api ./plugin -run "TestAPIContract|TestBazaarContract|TestRepoContract|TestRepoFileWireCompatibility|TestRPC.*Contract|TestRPCWebSocketOriginCheck|TestBlockAttrsRespectPublishAccess|TestGetBlockInfoRecovery|TestGetBlockInfoPublishAccess|TestListNotebooksSortsBySubDocCount|TestContract.*NotebookResponseLease" -count=1
+go test -tags "fts5 sqlcipher" ./model -run "TestMultipartUpload|TestInsertLocalAssets|TestRecordAssetUpload|TestReadRTFD|TestCopyRTFD" -count=1
+go test -tags "fts5 sqlcipher" ./api ./plugin -run "TestAPIContract|TestAsset.*Contract|TestInsertLocalAssets|TestSetFileAnnotation|TestDeferredAsset|TestExportBrowserHTML|TestCopyExport|TestBazaarContract|TestRepoContract|TestRepoFileWireCompatibility|TestRPC.*Contract|TestRPCWebSocketOriginCheck|TestBlockAttrsRespectPublishAccess|TestGetBlockInfoRecovery|TestGetBlockInfoPublishAccess|TestListNotebooksSortsBySubDocCount|TestContract.*NotebookResponseLease" -count=1
```
`tsconfig.api.json` 单独启用严格检查并检查声明文件,覆盖参数错误、字段拼写、必填请求体、成功与失败分支、可空值和方法不匹配。主应用继续沿用现有配置,不假定全部调用都启用了严格空值检查。处理函数测试使用临时工作区和独立测试进程,不启动或重启运行中的内核。
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index 349d7fc458..0d694943b3 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -30,40 +30,31 @@ import (
"github.com/djherbis/times"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/util"
)
-func statAsset(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+var statAsset = contractHandler(apicontract.StatAsset, func(c *gin.Context, request apicontract.AssetPathRequest) apicontract.Response[apicontract.AssetStatData] {
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
-
- path := arg["path"].(string)
+ path := request.Path
var p string
if strings.HasPrefix(path, "assets/") {
var err error
p, err = model.GetAssetAbsPathInBox(path, "")
if err != nil {
- ret.Code = 1
- return
+ return apicontract.Failure[apicontract.AssetStatData](1, "")
}
} else if localPath := util.FileURLToLocalPath(path); localPath != "" {
p = localPath
} else {
- ret.Code = 1
- return
+ return apicontract.Failure[apicontract.AssetStatData](1, "")
}
if !util.IsAbsPathInWorkspace(p) {
- ret.Code = 1
- return
+ return apicontract.Failure[apicontract.AssetStatData](1, "")
}
info, err := os.Stat(p)
@@ -71,107 +62,68 @@ func statAsset(c *gin.Context) {
if os.IsNotExist(err) {
files, readErr := model.DeferredSyncAssets()
if readErr != nil {
- ret.Code = 1
- ret.Msg = readErr.Error()
- return
+ return apicontract.Failure[apicontract.AssetStatData](1, readErr.Error())
}
for _, file := range files {
if filepath.Clean(p) != filepath.Join(util.DataDir, filepath.FromSlash(strings.TrimPrefix(file.Path, "/"))) {
continue
}
updated := time.UnixMilli(file.Updated).Format("2006-01-02 15:04:05")
- ret.Data = map[string]any{
- "size": file.Size, "hSize": humanize.IBytesCustomCeil(uint64(file.Size), 2),
- "created": file.Updated, "hCreated": updated, "updated": file.Updated, "hUpdated": updated,
- "downloaded": false,
- }
- return
+ return apicontract.Success(apicontract.AssetStatData{Size: file.Size, HSize: humanize.IBytesCustomCeil(uint64(file.Size), 2), Created: file.Updated, HCreated: updated, Updated: file.Updated, HUpdated: updated, Downloaded: new(false)})
}
}
- ret.Code = 1
- return
+ return apicontract.Failure[apicontract.AssetStatData](1, "")
}
t, err := times.Stat(p)
if err != nil {
- ret.Code = 1
- return
+ return apicontract.Failure[apicontract.AssetStatData](1, "")
}
updated := t.ModTime().UnixMilli()
hUpdated := t.ModTime().Format("2006-01-02 15:04:05")
created := updated
hCreated := hUpdated
- // Check birthtime before use
+ // 存在创建时间时优先使用创建时间
if t.HasBirthTime() {
created = t.BirthTime().UnixMilli()
hCreated = t.BirthTime().Format("2006-01-02 15:04:05")
}
- ret.Data = map[string]any{
- "size": info.Size(),
- "hSize": humanize.IBytesCustomCeil(uint64(info.Size()), 2),
- "created": created,
- "hCreated": hCreated,
- "updated": updated,
- "hUpdated": hUpdated,
- }
-}
+ return apicontract.Success(apicontract.AssetStatData{Size: info.Size(), HSize: humanize.IBytesCustomCeil(uint64(info.Size()), 2), Created: created, HCreated: hCreated, Updated: updated, HUpdated: hUpdated})
+})
-func fullReindexAssetContent(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+var fullReindexAssetContent = contractHandler(apicontract.FullReindexAssetContent, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {
model.ReindexAssetContent()
-}
-func getImageOCRText(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+ return apicontract.Success(apicontract.Null{})
+})
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var getImageOCRText = contractHandler(apicontract.GetImageOCRText, func(c *gin.Context, request apicontract.AssetOCRTextRequest) apicontract.Response[apicontract.AssetTextData] {
- var path string
- if nil == arg["path"] {
- ret.Data = map[string]any{
- "text": "",
- }
- return
+ if request.Path == nil {
+ return apicontract.Success(apicontract.AssetTextData{Text: ""})
}
-
- path = arg["path"].(string)
+ path := *request.Path
// 加密笔记本的资源不参与全局 OCR(OCR 文本存在全局 data/assets/ocr-texts.json)
if absPath, absErr := model.GetAssetAbsPathInBox(path, ""); absErr == nil && model.IsEncryptedAssetPath(absPath) {
- ret.Data = map[string]any{
- "text": "",
- }
- return
- }
+ return apicontract.Success(apicontract.AssetTextData{Text: ""})
- ret.Data = map[string]any{
- "text": util.GetAssetText(path),
}
-}
-func setImageOCRText(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+ return apicontract.Success(apicontract.AssetTextData{Text: util.GetAssetText(path)})
+})
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var setImageOCRText = contractHandler(apicontract.SetImageOCRText, func(c *gin.Context, request apicontract.SetAssetOCRTextRequest) apicontract.Response[apicontract.Null] {
- path := arg["path"].(string)
- text := arg["text"].(string)
+ path := request.Path
+ text := request.Text
// 加密笔记本的资源不参与全局 OCR
if absPath, absErr := model.GetAssetAbsPathInBox(path, ""); absErr == nil && model.IsEncryptedAssetPath(absPath) {
- return
+ return apicontract.Success(apicontract.Null{})
}
util.SetAssetText(path, text)
@@ -182,133 +134,81 @@ func setImageOCRText(c *gin.Context) {
sql.IndexNodeQueue(id)
}
util.NodeOCRQueue = nil
-}
-func ocr(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+ return apicontract.Success(apicontract.Null{})
+})
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var ocr = contractHandler(apicontract.AssetOCR, func(c *gin.Context, request apicontract.AssetPathRequest) apicontract.Response[apicontract.AssetOCRData] {
- path := arg["path"].(string)
+ path := request.Path
// 加密笔记本的资源不参与全局 OCR
absPath, err := model.GetAssetAbsPathInBox(path, "")
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.AssetOCRData](-1, err.Error())
}
if model.IsEncryptedAssetPath(absPath) {
- ret.Code = -1
- ret.Msg = model.Conf.Language(380)
- ret.Data = map[string]any{"closeTimeout": 3000}
- return
+ return apicontract.FailureWithTimeout[apicontract.AssetOCRData](-1, model.Conf.Language(380), 3000)
}
if err = model.EnsureAssetLocal(absPath); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.AssetOCRData](-1, err.Error())
}
ocrJSON, err := util.OcrAsset(path)
if nil != err {
- ret.Code = -1
- ret.Msg = err.Error()
- ret.Data = map[string]any{"closeTimeout": 7000}
- return
- }
-
- ret.Data = map[string]any{
- "text": util.GetOcrJsonText(ocrJSON),
- "ocrJSON": ocrJSON,
+ return apicontract.FailureWithTimeout[apicontract.AssetOCRData](-1, err.Error(), 7000)
}
-}
-func renameAsset(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+ return apicontract.Success(apicontract.AssetOCRData{Text: util.GetOcrJsonText(ocrJSON), OCRJSON: ocrJSON})
+})
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var renameAsset = contractHandler(apicontract.RenameAsset, func(c *gin.Context, request apicontract.RenameAssetRequest) apicontract.Response[apicontract.AssetRenameData] {
- oldPath := arg["oldPath"].(string)
- newName := arg["newName"].(string)
+ oldPath := request.OldPath
+ newName := request.NewName
newPath, err := model.RenameAsset(oldPath, newName)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- ret.Data = map[string]any{"closeTimeout": 5000}
- return
- }
- ret.Data = map[string]any{
- "newPath": newPath,
+ return apicontract.FailureWithTimeout[apicontract.AssetRenameData](-1, err.Error(), 5000)
}
-}
-
-func getDocImageAssets(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+ return apicontract.Success(apicontract.AssetRenameData{NewPath: newPath})
+})
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var getDocImageAssets = contractHandler(apicontract.GetDocImageAssets, func(c *gin.Context, request apicontract.AssetDocumentRequest) apicontract.Response[[]string] {
- id := arg["id"].(string)
+ id := request.ID
assets, err := model.DocImageAssets(id)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[[]string](-1, err.Error())
}
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
if !model.CheckBlockIdAccessableByPublishAccess(c, publishAccess, id) {
- ret.Code = -1
- ret.Msg = fmt.Sprintf(model.Conf.Language(15), id)
- return
+ return apicontract.Failure[[]string](-1, fmt.Sprintf(model.Conf.Language(15), id))
}
}
- ret.Data = assets
-}
+ return apicontract.Success(assets)
+})
-func getDocAssets(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+var getDocAssets = contractHandler(apicontract.GetDocAssets, func(c *gin.Context, request apicontract.AssetDocumentAssetsRequest) apicontract.Response[[]string] {
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
-
- id := arg["id"].(string)
+ id := request.ID
retainQueryStr := true
- if nil != arg["retainQueryStr"] {
- retainQueryStr = arg["retainQueryStr"].(bool)
+ if request.RetainQueryStr != nil {
+ retainQueryStr = *request.RetainQueryStr
}
assets, err := model.DocAssets(id, retainQueryStr)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[[]string](-1, err.Error())
}
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
if !model.CheckBlockIdAccessableByPublishAccess(c, publishAccess, id) {
- ret.Code = -1
- ret.Msg = fmt.Sprintf(model.Conf.Language(15), id)
- return
+ return apicontract.Failure[[]string](-1, fmt.Sprintf(model.Conf.Language(15), id))
}
}
- ret.Data = assets
-}
+ return apicontract.Success(assets)
+})
// fileAnno 是 PDF 文件标注 .sya 的校验结构,setFileAnnotation 通过它约束客户端提交的数据结构,避免任意字符串落盘
// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-fqpw-c3pj-w8g9
@@ -324,145 +224,99 @@ type fileAnno struct {
IDs []string `json:"ids"`
}
-func setFileAnnotation(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
-
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var setFileAnnotation = contractHandler(apicontract.SetFileAnnotation, func(c *gin.Context, request apicontract.SetAssetAnnotationRequest) apicontract.Response[apicontract.Null] {
- p := arg["path"].(string)
+ p := request.Path
p = strings.ReplaceAll(p, "%23", "#")
- data := arg["data"].(string)
+ data := request.Data
writePath, _, err := resolveFileAnnotationAbsPath(p)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
}
boxID := model.ExtractBoxIDFromAssetsPath(writePath)
if err = holdEncryptedBoxRequest(c, boxID); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
}
if "{}" == data {
if err = filelock.Remove(writePath); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
}
} else {
var annos map[string]fileAnno
if err = json.Unmarshal([]byte(data), &annos); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
}
if annos == nil {
- ret.Code = -1
- ret.Msg = "invalid annotation"
- return
+ return apicontract.Failure[apicontract.Null](-1, "invalid annotation")
}
normalized, err := json.Marshal(annos)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
}
// 加密笔记本的 .sya 写盘前必须加密;加密笔记本未解锁时拒绝写入(fail-closed,避免明文落盘)
writeData := normalized
if boxID != "" && model.IsEncryptedBox(boxID) {
dek, dekErr := model.GetDEKIfUnlocked(boxID)
if dekErr != nil {
- ret.Code = -1
- ret.Msg = dekErr.Error()
- return
+ return apicontract.Failure[apicontract.Null](-1, dekErr.Error())
}
diskName := filepath.Base(writePath)
enc, encErr := model.EncryptAsset(boxID, diskName, diskName, dek, writeData)
if encErr != nil {
- ret.Code = -1
- ret.Msg = encErr.Error()
- return
+ return apicontract.Failure[apicontract.Null](-1, encErr.Error())
}
writeData = enc
}
if err = filelock.WriteFile(writePath, writeData); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
}
}
model.IncSync()
-}
-func getFileAnnotation(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+ return apicontract.Success(apicontract.Null{})
+})
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var getFileAnnotation = contractHandler(apicontract.GetFileAnnotation, func(c *gin.Context, request apicontract.AssetPathRequest) apicontract.Response[apicontract.AssetAnnotationData] {
- p := arg["path"].(string)
+ p := request.Path
p = strings.ReplaceAll(p, "%23", "#")
readPath, assetAbsPath, err := resolveFileAnnotationAbsPath(p)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- ret.Data = map[string]any{"closeTimeout": 5000}
- return
+ return apicontract.FailureWithTimeout[apicontract.AssetAnnotationData](-1, err.Error(), 5000)
}
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
if !model.CheckAbsPathAccessableByPublishAccess(c, assetAbsPath, publishAccess) {
- ret.Code = http.StatusForbidden
- ret.Msg = http.StatusText(http.StatusForbidden)
- return
+ return apicontract.Failure[apicontract.AssetAnnotationData](http.StatusForbidden, http.StatusText(http.StatusForbidden))
}
}
if !filelock.IsExist(readPath) {
- ret.Code = 1
- return
+ return apicontract.Failure[apicontract.AssetAnnotationData](1, "")
}
boxID := model.ExtractBoxIDFromAssetsPath(readPath)
if err = holdEncryptedBoxRequest(c, boxID); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.AssetAnnotationData](-1, err.Error())
}
data, err := filelock.ReadFile(readPath)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.AssetAnnotationData](-1, err.Error())
}
// 加密笔记本的 .sya 读盘后必须解密;未解锁时拒绝返回(fail-closed,避免返回密文或误判)
if boxID != "" && model.IsEncryptedBox(boxID) {
dek, dekErr := model.GetDEKIfUnlocked(boxID)
if dekErr != nil {
- ret.Code = -1
- ret.Msg = dekErr.Error()
- return
+ return apicontract.Failure[apicontract.AssetAnnotationData](-1, dekErr.Error())
}
plain, decErr := model.DecryptAsset(boxID, filepath.Base(readPath), dek, data)
if decErr != nil {
- ret.Code = -1
- ret.Msg = decErr.Error()
- return
+ return apicontract.Failure[apicontract.AssetAnnotationData](-1, decErr.Error())
}
data = plain
}
- ret.Data = map[string]any{
- "data": string(data),
- }
-}
+ return apicontract.Success(apicontract.AssetAnnotationData{Data: string(data)})
+})
func resolveFileAnnotationAbsPath(assetRelPath string) (annotationAbsPath, assetAbsPath string, err error) {
// .sya 在 URL 末尾,例如 assets/a.pdf?box=<id>.sya
@@ -476,182 +330,102 @@ func resolveFileAnnotationAbsPath(assetRelPath string) (annotationAbsPath, asset
return
}
-func removeUnusedAsset(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+var removeUnusedAsset = contractHandler(apicontract.RemoveUnusedAsset, func(c *gin.Context, request apicontract.AssetPathRequest) apicontract.Response[apicontract.AssetPathData] {
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
-
- p := arg["path"].(string)
+ p := request.Path
asset, err := model.RemoveUnusedAsset(p)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.AssetPathData](-1, err.Error())
}
- ret.Data = map[string]any{
- "path": asset,
- }
-}
+ return apicontract.Success(apicontract.AssetPathData{Path: asset})
+})
-func removeUnusedAssets(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+var removeUnusedAssets = contractHandler(apicontract.RemoveUnusedAssets, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.AssetPathsData] {
paths := model.RemoveUnusedAssets()
- ret.Data = map[string]any{
- "paths": paths,
- }
-}
+ return apicontract.Success(apicontract.AssetPathsData{Paths: paths})
+})
-func getUnusedAssets(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+var getUnusedAssets = contractHandler(apicontract.GetUnusedAssets, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[[]*apicontract.AssetUnusedItem] {
unusedAssets := model.UnusedAssets(true)
total := len(unusedAssets)
- // List only 512 unreferenced assets https://github.com/siyuan-note/siyuan/issues/13075
+ // 最多返回 512 个未引用资源。
const maxUnusedAssets = 512
if total > maxUnusedAssets {
unusedAssets = unusedAssets[:maxUnusedAssets]
util.PushMsg(fmt.Sprintf(model.Conf.Language(251), total, maxUnusedAssets), 5000)
}
- ret.Data = unusedAssets
-}
+ return apicontract.Success(assetUnusedItems(unusedAssets))
+})
-func getMissingAssets(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+var getMissingAssets = contractHandler(apicontract.GetMissingAssets, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[[]*apicontract.AssetUnusedItem] {
missingAssets := model.MissingAssets()
- ret.Data = missingAssets
-}
+ return apicontract.Success(assetUnusedItems(missingAssets))
+})
-func resolveAssetPath(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
-
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var resolveAssetPath = contractHandler(apicontract.ResolveAssetPath, func(c *gin.Context, request apicontract.AssetPathRequest) apicontract.Response[string] {
- path := arg["path"].(string)
+ path := request.Path
p, err := model.GetAssetAbsPathInBox(path, "")
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- ret.Data = map[string]any{"closeTimeout": 3000}
- return
+ return apicontract.FailureWithTimeout[string](-1, err.Error(), 3000)
}
if model.IsEncryptedAssetPath(p) {
- ret.Code = -1
- ret.Msg = model.Conf.Language(314)
- ret.Data = map[string]any{"closeTimeout": 3000}
- return
+ return apicontract.FailureWithTimeout[string](-1, model.Conf.Language(314), 3000)
}
if err = model.EnsureAssetPrefixLocal(p); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- ret.Data = map[string]any{"closeTimeout": 7000}
- return
+ return apicontract.FailureWithTimeout[string](-1, err.Error(), 7000)
}
- ret.Data = p
- return
-}
+ return apicontract.Success(p)
+})
-func uploadCloud(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
-
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var uploadCloud = contractHandler(apicontract.AssetUploadCloud, func(c *gin.Context, request apicontract.AssetCloudUploadRequest) apicontract.Response[apicontract.Null] {
- ignorePushMsg := false
- if nil != arg["ignorePushMsg"] {
- ignorePushMsg = arg["ignorePushMsg"].(bool)
- }
+ ignorePushMsg := request.IgnorePushMsg
+ id := request.ID
- id := arg["id"].(string)
count, err := model.UploadAssets2Cloud(id, ignorePushMsg)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- ret.Data = map[string]any{"closeTimeout": 3000}
- return
+ return apicontract.FailureWithTimeout[apicontract.Null](-1, err.Error(), 3000)
}
util.PushMsg(fmt.Sprintf(model.Conf.Language(41), count), 3000)
-}
-func uploadCloudByAssetsPaths(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+ return apicontract.Success(apicontract.Null{})
+})
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var uploadCloudByAssetsPaths = contractHandler(apicontract.AssetUploadCloudByAssetsPaths, func(c *gin.Context, request apicontract.AssetPathsCloudUploadRequest) apicontract.Response[apicontract.Null] {
- if nil == arg["paths"] {
- ret.Code = -1
- ret.Msg = "[paths] is required"
- return
- }
-
- pathsArg := arg["paths"].([]any)
- var assets []string
- for _, pathArg := range pathsArg {
- assets = append(assets, pathArg.(string))
- }
-
- ignorePushMsg := false
- if nil != arg["ignorePushMsg"] {
- ignorePushMsg = arg["ignorePushMsg"].(bool)
- }
+ assets := append([]string(nil), request.Paths...)
+ ignorePushMsg := request.IgnorePushMsg
count, err := model.UploadAssets2CloudByAssetsPaths(assets, ignorePushMsg)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- ret.Data = map[string]any{"closeTimeout": 3000}
- return
+ return apicontract.FailureWithTimeout[apicontract.Null](-1, err.Error(), 3000)
}
if !ignorePushMsg {
util.PushMsg(fmt.Sprintf(model.Conf.Language(41), count), 3000)
}
-}
-func insertLocalAssets(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+ return apicontract.Success(apicontract.Null{})
+})
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var insertLocalAssets = contractHandler(apicontract.InsertLocalAssets, func(c *gin.Context, request apicontract.InsertLocalAssetsRequest) apicontract.Response[apicontract.AssetUploadData] {
- assetPathsArg := arg["assetPaths"].([]any)
- var assetPaths []string
- for _, pathArg := range assetPathsArg {
- assetPaths = append(assetPaths, pathArg.(string))
- }
+ assetPaths := append([]string(nil), request.AssetPaths...)
isUpload := true
- isUploadArg := arg["isUpload"]
- if nil != isUploadArg {
- isUpload = isUploadArg.(bool)
+ if request.IsUpload != nil {
+ isUpload = *request.IsUpload
}
- id, _ := arg["id"].(string)
- fromHTMLPaste, _ := arg["fromHTMLPaste"].(bool)
- var succMap map[string]any
+ id := request.ID
+ fromHTMLPaste := request.FromHTMLPaste
+
+ var succMap map[string]string
var succFiles []model.AssetUploadSuccess
var failedFiles []model.AssetUploadFailure
var err error
@@ -661,71 +435,85 @@ func insertLocalAssets(c *gin.Context) {
succMap, succFiles, failedFiles, err = model.InsertLocalAssets(id, assetPaths, isUpload)
}
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.AssetUploadData](-1, err.Error())
}
errFiles := make([]string, 0, len(failedFiles))
for _, failedFile := range failedFiles {
errFiles = append(errFiles, failedFile.Name)
}
- ret.Data = map[string]any{
- "errFiles": errFiles,
- "failedFiles": failedFiles,
- "succFiles": succFiles,
- "succMap": succMap,
+ data := assetUploadData(errFiles, failedFiles, succFiles, succMap)
+ if len(failedFiles) > 0 {
+ return apicontract.InsertLocalAssets.FailureWithData(-1, failedFiles[0].Error, data)
}
- if 0 < len(failedFiles) {
- ret.Code = -1
- ret.Msg = failedFiles[0].Error
- }
-}
+ return apicontract.Success(data)
+})
-func insertCover(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+var insertCover = contractHandler(apicontract.InsertCover, func(c *gin.Context, request apicontract.InsertCoverRequest) apicontract.Response[apicontract.AssetInsertCoverData] {
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
-
- name := arg["name"].(string)
+ name := request.Name
// 防止路径穿越:只允许文件名,不能含分隔符或 ..
name = filepath.Base(name)
if "" == name || "." == name || ".." == name {
- ret.Code = -1
- ret.Msg = "invalid name"
- return
+ return apicontract.Failure[apicontract.AssetInsertCoverData](-1, "invalid name")
}
srcPath := filepath.Join(util.AppearancePath, "covers", name)
if gulu.File.IsDir(srcPath) {
- ret.Code = -1
- ret.Msg = "invalid cover"
- return
+ return apicontract.Failure[apicontract.AssetInsertCoverData](-1, "invalid cover")
}
if _, statErr := os.Stat(srcPath); nil != statErr {
- ret.Code = -1
- ret.Msg = "cover not found"
- return
+ return apicontract.Failure[apicontract.AssetInsertCoverData](-1, "cover not found")
}
- id := arg["id"].(string)
+ id := request.ID
succMap, succFiles, failedFiles, err := model.InsertLocalAssets(id, []string{srcPath}, true)
if nil != err {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.AssetInsertCoverData](-1, err.Error())
}
if 0 < len(failedFiles) {
- ret.Code = -1
- ret.Msg = failedFiles[0].Error
- return
+ return apicontract.Failure[apicontract.AssetInsertCoverData](-1, failedFiles[0].Error)
+ }
+
+ return apicontract.Success(apicontract.AssetInsertCoverData{SuccFiles: assetUploadSuccesses(succFiles), SuccMap: succMap})
+})
+
+var uploadAsset = contractHandler(apicontract.UploadAsset, func(c *gin.Context, request apicontract.UploadAssetRequest) apicontract.Response[apicontract.AssetUploadData] {
+ result, message, err := model.UploadAssets(model.AssetUploadRequest{ID: request.ID, AssetsDirPath: request.AssetsDirPath, Files: request.Files})
+ if err != nil {
+ return apicontract.Failure[apicontract.AssetUploadData](-1, err.Error())
}
+ return apicontract.SuccessWithMessage(assetUploadData(result.ErrFiles, result.FailedFiles, result.SuccFiles, result.SuccMap), message)
+})
- ret.Data = map[string]any{
- "succFiles": succFiles,
- "succMap": succMap,
+func assetUploadSuccesses(values []model.AssetUploadSuccess) []apicontract.AssetUploadSuccess {
+ if values == nil {
+ return nil
+ }
+ ret := make([]apicontract.AssetUploadSuccess, len(values))
+ for i, value := range values {
+ ret[i] = apicontract.AssetUploadSuccess(value)
+ }
+ return ret
+}
+func assetUploadData(errFiles []string, failures []model.AssetUploadFailure, successes []model.AssetUploadSuccess, successMap map[string]string) apicontract.AssetUploadData {
+ ret := apicontract.AssetUploadData{ErrFiles: errFiles, SuccFiles: assetUploadSuccesses(successes), SuccMap: successMap}
+ if failures != nil {
+ ret.FailedFiles = make([]apicontract.AssetUploadFailure, len(failures))
+ for i, value := range failures {
+ ret.FailedFiles[i] = apicontract.AssetUploadFailure(value)
+ }
+ }
+ return ret
+}
+func assetUnusedItems(values []*model.UnusedItem) []*apicontract.AssetUnusedItem {
+ if values == nil {
+ return nil
+ }
+ ret := make([]*apicontract.AssetUnusedItem, len(values))
+ for i, value := range values {
+ if value != nil {
+ ret[i] = &apicontract.AssetUnusedItem{Item: value.Item, Name: value.Name, Path: value.Path, BlockIDs: value.BlockIDs}
+ }
}
+ return ret
}
diff --git a/kernel/api/contract_asset_test.go b/kernel/api/contract_asset_test.go
new file mode 100644
index 0000000000..bebb88867a
--- /dev/null
+++ b/kernel/api/contract_asset_test.go
@@ -0,0 +1,214 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func setupAssetContractWorkspace(t *testing.T) string {
+ t.Helper()
+ previousConf, previousData, previousWorkspace := model.Conf, util.DataDir, util.WorkspaceDir
+ model.Conf = model.NewAppConf()
+ model.Conf.Sync = conf.NewSync()
+ util.WorkspaceDir = t.TempDir()
+ util.DataDir = filepath.Join(util.WorkspaceDir, "data")
+ t.Cleanup(func() { model.Conf, util.DataDir, util.WorkspaceDir = previousConf, previousData, previousWorkspace })
+ dir := filepath.Join(util.DataDir, "assets")
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ return dir
+}
+
+func TestAssetUploadContractAdapter(t *testing.T) {
+ assets := setupAssetContractWorkspace(t)
+ content := []byte("upload fixture")
+ name := "sample-20260101000000-abcdefg.txt"
+ if err := os.WriteFile(filepath.Join(assets, name), content, 0644); err != nil {
+ t.Fatal(err)
+ }
+ hash, err := util.GetEtagByHandle(bytes.NewReader(content), int64(len(content)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ cache.SetAssetHash(hash, "assets/"+name)
+ t.Cleanup(func() { cache.RemoveAssetHash(hash) })
+ bundle, err := apicontract.BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, test := range []struct {
+ name string
+ files bool
+ failure bool
+ emptyID bool
+ }{
+ {name: "empty"},
+ {name: "duplicate names", files: true},
+ {name: "partial failure", files: true, failure: true},
+ {name: "explicit empty document", emptyID: true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ request := func() *http.Request {
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ if test.files {
+ for i := 0; i < 2; i++ {
+ part, err := writer.CreateFormFile("file[]", "sample.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := part.Write(content); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ if test.emptyID {
+ if err := writer.WriteField("id", ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ request := httptest.NewRequest(http.MethodPost, "/api/asset/upload", &body)
+ request.Header.Set("Content-Type", writer.FormDataContentType())
+ if err := request.ParseMultipartForm(1 << 20); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = request.MultipartForm.RemoveAll() })
+ if test.failure {
+ request.MultipartForm.File["file[]"][0] = &multipart.FileHeader{Filename: "missing.png", Size: 1}
+ }
+ return request
+ }
+ var responses []map[string]interface{}
+ for _, handler := range []gin.HandlerFunc{model.Upload, uploadAsset} {
+ engine := gin.New()
+ engine.POST("/api/asset/upload", handler)
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request())
+ if err := bundle.ValidateHTTPResponse("POST", "/api/asset/upload", recorder.Code, recorder.Header().Get("Content-Type"), recorder.Body.Bytes()); err != nil {
+ t.Fatal(err)
+ }
+ var response map[string]interface{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ responses = append(responses, response)
+ }
+ if !reflect.DeepEqual(responses[0], responses[1]) {
+ t.Fatalf("upload adapter differs: %+v / %+v", responses[0], responses[1])
+ }
+ if test.failure && (responses[1]["code"] != float64(0) || responses[1]["msg"] == "") {
+ t.Fatalf("partial upload must retain success code and failure message: %+v", responses[1])
+ }
+ })
+ }
+}
+
+func TestAssetOCRMissingPathContract(t *testing.T) {
+ setupAssetContractWorkspace(t)
+ previous := util.GetAssetText("")
+ util.SetAssetText("", "empty path content")
+ t.Cleanup(func() { util.SetAssetText("", previous) })
+ engine := gin.New()
+ engine.POST("/api/asset/getImageOCRText", getImageOCRText)
+ for _, test := range []struct{ body, text string }{
+ {`{}`, ""}, {`{"path":null}`, ""}, {`{"path":""}`, "empty path content"},
+ } {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/getImageOCRText", strings.NewReader(test.body)))
+ requireAPIContract(t, "POST", "/api/asset/getImageOCRText", recorder)
+ var response struct{ Data apicontract.AssetTextData }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Data.Text != test.text {
+ t.Fatalf("OCR response: %s %v", recorder.Body.String(), err)
+ }
+ }
+}
+
+func TestAssetAnnotationContractFormat(t *testing.T) {
+ assets := setupAssetContractWorkspace(t)
+ if err := os.WriteFile(filepath.Join(assets, "fixture.pdf"), []byte("PDF fixture"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ data := `{"one":{"pages":[{"index":1,"positions":[[1.5,2.5]]}],"color":"red","type":"highlight","content":"note","mode":"rect","ids":["id"],"ignored":true}}`
+ body, err := json.Marshal(apicontract.SetAssetAnnotationRequest{Path: "assets/fixture.pdf.sya", Data: data})
+ if err != nil {
+ t.Fatal(err)
+ }
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) {
+ c.Set(model.RoleContextKey, model.RoleAdministrator)
+ c.Next()
+ })
+ engine.POST("/api/asset/setFileAnnotation", setFileAnnotation)
+ engine.POST("/api/asset/getFileAnnotation", getFileAnnotation)
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/setFileAnnotation", bytes.NewReader(body)))
+ requireAPIContract(t, "POST", "/api/asset/setFileAnnotation", recorder)
+ var response struct{ Code int }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 {
+ t.Fatalf("annotation write failed: %s %v", recorder.Body.String(), err)
+ }
+ var expected map[string]fileAnno
+ if err := json.Unmarshal([]byte(data), &expected); err != nil {
+ t.Fatal(err)
+ }
+ normalized, _ := json.Marshal(expected)
+ stored, err := os.ReadFile(filepath.Join(assets, "fixture.pdf.sya"))
+ if err != nil || !bytes.Equal(stored, normalized) {
+ t.Fatalf("annotation format differs: %s %v", stored, err)
+ }
+ recorder = httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/getFileAnnotation", strings.NewReader(`{"path":"assets/fixture.pdf.sya"}`)))
+ requireAPIContract(t, "POST", "/api/asset/getFileAnnotation", recorder)
+ var read struct {
+ Data apicontract.AssetAnnotationData
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &read); err != nil || read.Data.Data != string(normalized) {
+ t.Fatalf("annotation read differs: %s %v", recorder.Body.String(), err)
+ }
+ reader := gin.New()
+ reader.POST("/api/asset/getFileAnnotation", getFileAnnotation)
+ recorder = httptest.NewRecorder()
+ reader.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/getFileAnnotation", strings.NewReader(`{"path":"assets/fixture.pdf.sya"}`)))
+ requireAPIContract(t, "POST", "/api/asset/getFileAnnotation", recorder)
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != http.StatusForbidden {
+ t.Fatalf("unpublished annotation must remain forbidden: %s %v", recorder.Body.String(), err)
+ }
+}
+
+func TestAssetUploadResultContractNullability(t *testing.T) {
+ for _, test := range []struct {
+ errors []string
+ failures []model.AssetUploadFailure
+ successes []model.AssetUploadSuccess
+ mapping map[string]string
+ }{
+ {},
+ {errors: []string{}, failures: []model.AssetUploadFailure{}, successes: []model.AssetUploadSuccess{}, mapping: map[string]string{}},
+ {errors: []string{"file"}, failures: []model.AssetUploadFailure{{Index: 1, Name: "file", Error: "failed"}}, successes: []model.AssetUploadSuccess{{Index: 0, Name: "file", Path: "assets/file"}}, mapping: map[string]string{"file": "assets/file"}},
+ } {
+ expected, _ := json.Marshal(model.AssetUploadResult{ErrFiles: test.errors, FailedFiles: test.failures, SuccFiles: test.successes, SuccMap: test.mapping})
+ actual, _ := json.Marshal(assetUploadData(test.errors, test.failures, test.successes, test.mapping))
+ if !bytes.Equal(expected, actual) {
+ t.Fatalf("upload data differs: %s / %s", expected, actual)
+ }
+ }
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 8aed3e5cb8..534f1a96b7 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -382,7 +382,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/asset/insertLocalAssets", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, insertLocalAssets)
ginServer.Handle("POST", "/api/asset/insertCover", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, insertCover)
ginServer.Handle("POST", "/api/asset/resolveAssetPath", model.CheckAuth, model.CheckAdminRole, resolveAssetPath)
- ginServer.Handle("POST", "/api/asset/upload", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, model.Upload)
+ ginServer.Handle("POST", "/api/asset/upload", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, uploadAsset)
ginServer.Handle("POST", "/api/asset/setFileAnnotation", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setFileAnnotation)
ginServer.Handle("POST", "/api/asset/getFileAnnotation", model.CheckAuth, getFileAnnotation)
ginServer.Handle("POST", "/api/asset/getUnusedAssets", model.CheckAuth, model.CheckAdminRole, getUnusedAssets)
diff --git a/kernel/apicontract/asset.go b/kernel/apicontract/asset.go
new file mode 100644
index 0000000000..34f2228258
--- /dev/null
+++ b/kernel/apicontract/asset.go
@@ -0,0 +1,163 @@
+package apicontract
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "mime/multipart"
+ "reflect"
+)
+
+type AssetPathRequest struct {
+ Path string `json:"path"`
+}
+
+type AssetOCRTextRequest struct {
+ Path *string `json:"path" api:"optional"`
+}
+
+type SetAssetOCRTextRequest struct {
+ Path string `json:"path"`
+ Text string `json:"text"`
+}
+
+type RenameAssetRequest struct {
+ OldPath string `json:"oldPath"`
+ NewName string `json:"newName"`
+}
+
+type AssetDocumentRequest struct {
+ ID string `json:"id"`
+}
+
+type AssetDocumentAssetsRequest struct {
+ ID string `json:"id"`
+ RetainQueryStr *bool `json:"retainQueryStr" api:"optional"`
+}
+
+type SetAssetAnnotationRequest struct {
+ Path string `json:"path"`
+ Data string `json:"data"`
+}
+
+type AssetCloudUploadRequest struct {
+ IgnorePushMsg bool `json:"ignorePushMsg" api:"optional,nullable"`
+ ID string `json:"id"`
+}
+
+type AssetPathsCloudUploadRequest struct {
+ Paths []string `json:"paths"`
+ IgnorePushMsg bool `json:"ignorePushMsg" api:"optional,nullable"`
+}
+
+type InsertLocalAssetsRequest struct {
+ AssetPaths []string `json:"assetPaths"`
+ IsUpload *bool `json:"isUpload" api:"optional"`
+ ID string `json:"id" api:"optional,nullable,ignoretype"`
+ FromHTMLPaste bool `json:"fromHTMLPaste" api:"optional,nullable"`
+}
+
+type InsertCoverRequest struct {
+ Name string `json:"name"`
+ ID string `json:"id"`
+}
+
+type UploadAssetRequest struct {
+ ID *string `json:"id" api:"optional,nonnullable"`
+ AssetsDirPath *string `json:"assetsDirPath" api:"optional,nonnullable"`
+ Files []*multipart.FileHeader `json:"file[]" api:"optional"`
+}
+
+type AssetStatData struct {
+ Size int64 `json:"size"`
+ HSize string `json:"hSize"`
+ Created int64 `json:"created"`
+ HCreated string `json:"hCreated"`
+ Updated int64 `json:"updated"`
+ HUpdated string `json:"hUpdated"`
+ Downloaded *bool `json:"downloaded,omitempty" api:"const=false"`
+}
+
+type AssetTextData struct {
+ Text string `json:"text"`
+}
+
+// AssetOCRData 的列名来自识别工具的 TSV 表头,单元格均为文本。
+type AssetOCRData struct {
+ Text string `json:"text"`
+ OCRJSON []map[string]string `json:"ocrJSON"`
+}
+
+type AssetRenameData struct {
+ NewPath string `json:"newPath"`
+}
+
+type AssetAnnotationData struct {
+ Data string `json:"data"`
+}
+
+type AssetPathData struct {
+ Path string `json:"path"`
+}
+
+type AssetPathsData struct {
+ Paths []string `json:"paths"`
+}
+
+type AssetUnusedItem struct {
+ Item string `json:"item"`
+ Name string `json:"name"`
+ Path string `json:"path,omitempty"`
+ BlockIDs []string `json:"blockIDs,omitempty"`
+}
+
+type AssetUploadSuccess struct {
+ Index int `json:"index"`
+ Name string `json:"name"`
+ Path string `json:"path"`
+}
+
+type AssetUploadFailure struct {
+ Index int `json:"index"`
+ Name string `json:"name"`
+ Error string `json:"error"`
+}
+
+type AssetUploadData struct {
+ ErrFiles []string `json:"errFiles"`
+ FailedFiles []AssetUploadFailure `json:"failedFiles"`
+ SuccFiles []AssetUploadSuccess `json:"succFiles"`
+ SuccMap map[string]string `json:"succMap"`
+}
+
+type AssetInsertCoverData struct {
+ SuccFiles []AssetUploadSuccess `json:"succFiles"`
+ SuccMap map[string]string `json:"succMap"`
+}
+
+func init() {
+ InsertLocalAssets.decodeRequest = func(reader io.Reader) (request InsertLocalAssetsRequest, err error) {
+ fields, err := blockRequestFields(reader, "/api/asset/insertLocalAssets")
+ if err != nil {
+ return request, err
+ }
+ fromHTMLPaste := fields["fromHTMLPaste"]
+ delete(fields, "fromHTMLPaste")
+ if err = decodeRequestFields(reflect.ValueOf(&request).Elem(), fields); err != nil {
+ return request, err
+ }
+ _ = json.Unmarshal(fromHTMLPaste, &request.FromHTMLPaste)
+ return request, nil
+ }
+ AssetUploadCloudByAssetsPaths.decodeRequest = func(reader io.Reader) (request AssetPathsCloudUploadRequest, err error) {
+ fields, err := blockRequestFields(reader, "/api/asset/uploadCloudByAssetsPaths")
+ if err != nil {
+ return request, err
+ }
+ if len(fields["paths"]) == 0 || string(fields["paths"]) == "null" {
+ return request, errors.New("[paths] is required")
+ }
+ err = decodeRequestFields(reflect.ValueOf(&request).Elem(), fields)
+ return request, err
+ }
+}
diff --git a/kernel/apicontract/asset_test.go b/kernel/apicontract/asset_test.go
new file mode 100644
index 0000000000..d3b08edd99
--- /dev/null
+++ b/kernel/apicontract/asset_test.go
@@ -0,0 +1,73 @@
+package apicontract
+
+import (
+ "mime/multipart"
+ "strings"
+ "testing"
+)
+
+func TestAssetRequestCompatibility(t *testing.T) {
+ for _, body := range []string{
+ `{"assetPaths":[],"id":false,"fromHTMLPaste":"true"}`,
+ `{"assetPaths":[],"id":null,"fromHTMLPaste":null,"isUpload":null}`,
+ `{"assetPaths":[]}`,
+ } {
+ request, err := InsertLocalAssets.Decode(strings.NewReader(body))
+ if err != nil || request.ID != "" || request.FromHTMLPaste || request.IsUpload != nil {
+ t.Fatalf("optional upload arguments changed: %+v %v", request, err)
+ }
+ }
+ request, err := InsertLocalAssets.Decode(strings.NewReader(`{"assetPaths":[" /file "],"isUpload":false,"id":" id ","fromHTMLPaste":true}`))
+ if err != nil || request.AssetPaths[0] != " /file " || request.ID != " id " || request.IsUpload == nil || *request.IsUpload || !request.FromHTMLPaste {
+ t.Fatalf("explicit upload arguments changed: %+v %v", request, err)
+ }
+ for _, body := range []string{`{}`, `{"paths":null}`} {
+ if _, err := AssetUploadCloudByAssetsPaths.Decode(strings.NewReader(body)); err == nil || err.Error() != "[paths] is required" {
+ t.Fatalf("missing paths response changed: %v", err)
+ }
+ }
+ if _, err := AssetUploadCloudByAssetsPaths.Decode(strings.NewReader(`{"paths":[null]}`)); err == nil {
+ t.Fatal("null path accepted")
+ }
+ files := []*multipart.FileHeader{{Filename: "first"}, {Filename: "second"}}
+ upload, err := UploadAsset.DecodeMultipart(&multipart.Form{Value: map[string][]string{"id": {"", "ignored"}, "assetsDirPath": {" path ", "ignored"}}, File: map[string][]*multipart.FileHeader{"file[]": files}})
+ if err != nil || upload.ID == nil || *upload.ID != "" || upload.AssetsDirPath == nil || *upload.AssetsDirPath != " path " || len(upload.Files) != 2 || upload.Files[0] != files[0] || upload.Files[1] != files[1] {
+ t.Fatalf("multipart values changed: %+v %v", upload, err)
+ }
+ upload, err = UploadAsset.DecodeMultipart(&multipart.Form{})
+ if err != nil || upload.ID != nil || upload.AssetsDirPath != nil || upload.Files != nil {
+ t.Fatalf("multipart omissions changed: %+v %v", upload, err)
+ }
+}
+
+func TestAssetResponseVariants(t *testing.T) {
+ bundle, err := BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, test := range []struct {
+ path string
+ body string
+ }{
+ {"statAsset", `{"code":0,"msg":"","data":{"size":1,"hSize":"1B","created":1,"hCreated":"date","updated":2,"hUpdated":"date"}}`},
+ {"statAsset", `{"code":0,"msg":"","data":{"size":1,"hSize":"1B","created":1,"hCreated":"date","updated":2,"hUpdated":"date","downloaded":false}}`},
+ {"ocr", `{"code":0,"msg":"","data":{"text":"text","ocrJSON":[{"text":"text","customColumn":"value"}]}}`},
+ {"upload", `{"code":0,"msg":"first failed","data":{"errFiles":["first"],"failedFiles":[{"index":0,"name":"first","error":"first failed"}],"succFiles":[],"succMap":{}}}`},
+ {"upload", `{"code":0,"msg":"","data":{"errFiles":null,"failedFiles":[],"succFiles":[],"succMap":{}}}`},
+ {"insertLocalAssets", `{"code":-1,"msg":"failed","data":{"errFiles":["first"],"failedFiles":[{"index":0,"name":"first","error":"failed"}],"succFiles":[],"succMap":{}}}`},
+ {"getFileAnnotation", `{"code":403,"msg":"Forbidden","data":null}`},
+ } {
+ if err := bundle.ValidateResponse("POST", "/api/asset/"+test.path, []byte(test.body)); err != nil {
+ t.Errorf("%s: %v", test.path, err)
+ }
+ }
+ for _, test := range []struct{ path, body string }{
+ {"statAsset", `{"code":0,"msg":"","data":{"size":1,"hSize":"1B","created":1,"hCreated":"date","updated":2,"hUpdated":"date","downloaded":true}}`},
+ {"ocr", `{"code":0,"msg":"","data":{"text":"text","ocrJSON":[{"text":42}]}}`},
+ {"upload", `{"code":0,"msg":"","data":{"errFiles":null,"failedFiles":[],"succFiles":[],"succMap":{"file":false}}}`},
+ } {
+ if err := bundle.ValidateResponse("POST", "/api/asset/"+test.path, []byte(test.body)); err == nil {
+ t.Errorf("invalid asset payload accepted: %s", test.body)
+ }
+ }
+}
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 207b8f0262..fddb947079 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -710,3 +710,24 @@ var ExportOPML = define[ExportIDRequest, ExportNamedZipData]("exportOPML", "/api
var ExportTextile = define[ExportIDRequest, ExportNamedZipData]("exportTextile", "/api/export/exportTextile", JSONBody, ResponseOptions{}, "POST")
var ExportAsciiDoc = define[ExportIDRequest, ExportNamedZipData]("exportAsciiDoc", "/api/export/exportAsciiDoc", JSONBody, ResponseOptions{}, "POST")
var ExportReStructuredText = define[ExportIDRequest, ExportNamedZipData]("exportReStructuredText", "/api/export/exportReStructuredText", JSONBody, ResponseOptions{}, "POST")
+
+var StatAsset = define[AssetPathRequest, AssetStatData]("statAsset", "/api/asset/statAsset", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
+var FullReindexAssetContent = define[EmptyRequest, Null]("fullReindexAssetContent", "/api/asset/fullReindexAssetContent", NoBody, ResponseOptions{}, "POST")
+var GetImageOCRText = define[AssetOCRTextRequest, AssetTextData]("getImageOCRText", "/api/asset/getImageOCRText", JSONBody, ResponseOptions{}, "POST")
+var SetImageOCRText = define[SetAssetOCRTextRequest, Null]("setImageOCRText", "/api/asset/setImageOCRText", JSONBody, ResponseOptions{}, "POST")
+var AssetOCR = define[AssetPathRequest, AssetOCRData]("ocr", "/api/asset/ocr", JSONBody, ResponseOptions{}, "POST")
+var RenameAsset = define[RenameAssetRequest, AssetRenameData]("renameAsset", "/api/asset/renameAsset", JSONBody, ResponseOptions{}, "POST")
+var GetDocImageAssets = define[AssetDocumentRequest, []string]("getDocImageAssets", "/api/asset/getDocImageAssets", JSONBody, ResponseOptions{}, "POST")
+var GetDocAssets = define[AssetDocumentAssetsRequest, []string]("getDocAssets", "/api/asset/getDocAssets", JSONBody, ResponseOptions{}, "POST")
+var SetFileAnnotation = define[SetAssetAnnotationRequest, Null]("setFileAnnotation", "/api/asset/setFileAnnotation", JSONBody, ResponseOptions{}, "POST")
+var GetFileAnnotation = define[AssetPathRequest, AssetAnnotationData]("getFileAnnotation", "/api/asset/getFileAnnotation", JSONBody, ResponseOptions{AdditionalCodes: []int{1,403}}, "POST")
+var RemoveUnusedAsset = define[AssetPathRequest, AssetPathData]("removeUnusedAsset", "/api/asset/removeUnusedAsset", JSONBody, ResponseOptions{}, "POST")
+var RemoveUnusedAssets = define[EmptyRequest, AssetPathsData]("removeUnusedAssets", "/api/asset/removeUnusedAssets", NoBody, ResponseOptions{}, "POST")
+var GetUnusedAssets = define[EmptyRequest, []*AssetUnusedItem]("getUnusedAssets", "/api/asset/getUnusedAssets", NoBody, ResponseOptions{}, "POST")
+var GetMissingAssets = define[EmptyRequest, []*AssetUnusedItem]("getMissingAssets", "/api/asset/getMissingAssets", NoBody, ResponseOptions{}, "POST")
+var ResolveAssetPath = define[AssetPathRequest, string]("resolveAssetPath", "/api/asset/resolveAssetPath", JSONBody, ResponseOptions{}, "POST")
+var AssetUploadCloud = define[AssetCloudUploadRequest, Null]("uploadCloud", "/api/asset/uploadCloud", JSONBody, ResponseOptions{}, "POST")
+var AssetUploadCloudByAssetsPaths = define[AssetPathsCloudUploadRequest, Null]("uploadCloudByAssetsPaths", "/api/asset/uploadCloudByAssetsPaths", JSONBody, ResponseOptions{}, "POST")
+var InsertLocalAssets = define[InsertLocalAssetsRequest, AssetUploadData]("insertLocalAssets", "/api/asset/insertLocalAssets", JSONBody, ResponseOptions{DataOnError: true}, "POST")
+var InsertCover = define[InsertCoverRequest, AssetInsertCoverData]("insertCover", "/api/asset/insertCover", JSONBody, ResponseOptions{}, "POST")
+var UploadAsset = define[UploadAssetRequest, AssetUploadData]("uploadAsset", "/api/asset/upload", MultipartBody, ResponseOptions{}, "POST")
diff --git a/kernel/apicontract/legacy_routes.json b/kernel/apicontract/legacy_routes.json
index f13fff5041..df7fd0610f 100644
--- a/kernel/apicontract/legacy_routes.json
+++ b/kernel/apicontract/legacy_routes.json
@@ -47,26 +47,6 @@
{"method":"POST","path":"/api/ai/testEmbeddingModel","handler":"testEmbeddingModel"},
{"method":"POST","path":"/api/ai/testModel","handler":"testModel"},
{"method":"POST","path":"/api/ai/testRerankModel","handler":"testRerankModel"},
- {"method":"POST","path":"/api/asset/fullReindexAssetContent","handler":"fullReindexAssetContent"},
- {"method":"POST","path":"/api/asset/getDocAssets","handler":"getDocAssets"},
- {"method":"POST","path":"/api/asset/getDocImageAssets","handler":"getDocImageAssets"},
- {"method":"POST","path":"/api/asset/getFileAnnotation","handler":"getFileAnnotation"},
- {"method":"POST","path":"/api/asset/getImageOCRText","handler":"getImageOCRText"},
- {"method":"POST","path":"/api/asset/getMissingAssets","handler":"getMissingAssets"},
- {"method":"POST","path":"/api/asset/getUnusedAssets","handler":"getUnusedAssets"},
- {"method":"POST","path":"/api/asset/insertCover","handler":"insertCover"},
- {"method":"POST","path":"/api/asset/insertLocalAssets","handler":"insertLocalAssets"},
- {"method":"POST","path":"/api/asset/ocr","handler":"ocr"},
- {"method":"POST","path":"/api/asset/removeUnusedAsset","handler":"removeUnusedAsset"},
- {"method":"POST","path":"/api/asset/removeUnusedAssets","handler":"removeUnusedAssets"},
- {"method":"POST","path":"/api/asset/renameAsset","handler":"renameAsset"},
- {"method":"POST","path":"/api/asset/resolveAssetPath","handler":"resolveAssetPath"},
- {"method":"POST","path":"/api/asset/setFileAnnotation","handler":"setFileAnnotation"},
- {"method":"POST","path":"/api/asset/setImageOCRText","handler":"setImageOCRText"},
- {"method":"POST","path":"/api/asset/statAsset","handler":"statAsset"},
- {"method":"POST","path":"/api/asset/upload","handler":"model.Upload"},
- {"method":"POST","path":"/api/asset/uploadCloud","handler":"uploadCloud"},
- {"method":"POST","path":"/api/asset/uploadCloudByAssetsPaths","handler":"uploadCloudByAssetsPaths"},
{"method":"POST","path":"/api/av/addAttributeViewBlocks","handler":"addAttributeViewBlocks"},
{"method":"POST","path":"/api/av/addAttributeViewKey","handler":"addAttributeViewKey"},
{"method":"POST","path":"/api/av/appendAttributeViewDetachedBlocksWithValues","handler":"appendAttributeViewDetachedBlocksWithValues"},
diff --git a/kernel/apicontract/multipart.go b/kernel/apicontract/multipart.go
index 9e2f807fb6..48979e6e0b 100644
--- a/kernel/apicontract/multipart.go
+++ b/kernel/apicontract/multipart.go
@@ -22,7 +22,7 @@ func validateMultipartRequest(t reflect.Type) error {
if !field.IsExported() || field.Anonymous || field.Tag.Get("json") == "" {
return fmt.Errorf("multipart fields must be named and exported: %s", field.Name)
}
- if field.Type != reflect.TypeFor[string]() && field.Type != reflect.TypeFor[*string]() && field.Type != reflect.TypeFor[*multipart.FileHeader]() {
+ if field.Type != reflect.TypeFor[string]() && field.Type != reflect.TypeFor[*string]() && field.Type != reflect.TypeFor[*multipart.FileHeader]() && field.Type != reflect.TypeFor[[]*multipart.FileHeader]() {
return fmt.Errorf("unsupported multipart field: %s", field.Name)
}
for _, option := range strings.Split(field.Tag.Get("api"), ",") {
@@ -58,7 +58,7 @@ func (e Endpoint[Request, Data]) DecodeMultipart(form *multipart.Form) (request
name := strings.Split(field.Tag.Get("json"), ",")[0]
optional := strings.Contains(","+field.Tag.Get("api")+",", ",optional,")
switch field.Type {
- case reflect.TypeFor[*multipart.FileHeader]():
+ case reflect.TypeFor[*multipart.FileHeader](), reflect.TypeFor[[]*multipart.FileHeader]():
files := form.File[name]
if len(files) == 0 {
if !optional {
@@ -66,7 +66,11 @@ func (e Endpoint[Request, Data]) DecodeMultipart(form *multipart.Form) (request
}
continue
}
- value.Field(i).Set(reflect.ValueOf(files[0]))
+ if field.Type.Kind() == reflect.Slice {
+ value.Field(i).Set(reflect.ValueOf(files))
+ } else {
+ value.Field(i).Set(reflect.ValueOf(files[0]))
+ }
case reflect.TypeFor[string](), reflect.TypeFor[*string]():
values := form.Value[name]
if len(values) == 0 {
diff --git a/kernel/apicontract/multipart_files_test.go b/kernel/apicontract/multipart_files_test.go
new file mode 100644
index 0000000000..29deeacec4
--- /dev/null
+++ b/kernel/apicontract/multipart_files_test.go
@@ -0,0 +1,43 @@
+package apicontract
+
+import (
+ "encoding/json"
+ "mime/multipart"
+ "strings"
+ "testing"
+)
+
+type multiFileRequest struct {
+ Files []*multipart.FileHeader `json:"files"`
+}
+
+func TestMultipartFileListAndSuccessMessage(t *testing.T) {
+ previous := definitions
+ t.Cleanup(func() { definitions = previous })
+ endpoint := define[multiFileRequest, []string]("multiFiles", "/test/multi-files", MultipartBody, ResponseOptions{}, "POST")
+ files := []*multipart.FileHeader{{Filename: "first.txt"}, {Filename: "second.txt"}}
+ request, err := endpoint.DecodeMultipart(&multipart.Form{File: map[string][]*multipart.FileHeader{"files": files}})
+ if err != nil || len(request.Files) != 2 || request.Files[0] != files[0] || request.Files[1] != files[1] {
+ t.Fatalf("upload list changed: %+v, %v", request, err)
+ }
+ if _, err := endpoint.DecodeMultipart(&multipart.Form{}); err == nil {
+ t.Fatal("required file list accepted missing files")
+ }
+ bundle, err := BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(bundle.TypeScript(nil)), `"files": Array<Blob>`) {
+ t.Fatal("file list declaration is missing")
+ }
+ payload, err := json.Marshal(SuccessWithMessage([]string{"first.txt"}, "second file failed"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(payload) != `{"code":0,"msg":"second file failed","data":["first.txt"]}` {
+ t.Fatal(string(payload))
+ }
+ if err := bundle.ValidateHTTPResponse("POST", "/test/multi-files", 200, "application/json", payload); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/kernel/apicontract/response.go b/kernel/apicontract/response.go
index e043080413..63b2b1916a 100644
--- a/kernel/apicontract/response.go
+++ b/kernel/apicontract/response.go
@@ -124,6 +124,11 @@ func (e Endpoint[Request, Data]) WithHTTPStatus(response Response[Data], status
func Success[Data any](data Data) Response[Data] { return Response[Data]{data: data} }
+// SuccessWithMessage 保留成功响应中的提示,例如批量上传中部分文件未完成。
+func SuccessWithMessage[Data any](data Data, message string) Response[Data] {
+ return Response[Data]{data: data, msg: message}
+}
+
func Failure[Data any](code int, msg string) Response[Data] {
return Response[Data]{code: code, msg: msg}
}
diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.go
index ccaea53337..84007a612d 100644
--- a/kernel/apicontract/schema.go
+++ b/kernel/apicontract/schema.go
@@ -275,6 +275,12 @@ func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {
}
return nullable(&Schema{Type: "string"}), nil
}
+ if t == reflect.TypeFor[[]*multipart.FileHeader]() {
+ if !input {
+ return nil, fmt.Errorf("uploaded files are request-only")
+ }
+ return &Schema{Type: "array", Items: &Schema{Type: "string", Format: "binary"}}, nil
+ }
if t == reflect.TypeFor[*multipart.FileHeader]() {
if !input {
return nil, fmt.Errorf("uploaded files are request-only")
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 04727cf6b0..ec05cc0bfc 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -114,6 +114,40 @@
],
"additionalProperties": false
},
+ "AssetAnnotationData": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ "AssetCloudUploadRequestInput": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "ignorePushMsg": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "id"
+ ],
+ "additionalProperties": false
+ },
"AssetContent": {
"type": "object",
"properties": {
@@ -193,39 +227,16 @@
],
"additionalProperties": false
},
- "AttributeViewColorTheme": {
+ "AssetDocumentAssetsRequestInput": {
"type": "object",
"properties": {
- "backgroundColor": {
- "type": "string"
- },
- "color": {
+ "id": {
"type": "string"
- }
- },
- "required": [
- "backgroundColor",
- "color"
- ],
- "additionalProperties": false
- },
- "AttributeViewColorThemeInput": {
- "type": "object",
- "properties": {
- "backgroundColor": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ]
},
- "color": {
+ "retainQueryStr": {
"anyOf": [
{
- "type": "string"
+ "type": "boolean"
},
{
"type": "null"
@@ -233,68 +244,102 @@
]
}
},
+ "required": [
+ "id"
+ ],
"additionalProperties": false
},
- "AttributeViewCustomColor": {
+ "AssetDocumentRequestInput": {
"type": "object",
"properties": {
- "dark": {
- "$ref": "#/$defs/AttributeViewColorTheme"
- },
- "hidden": {
- "type": "boolean"
- },
- "index": {
- "type": "integer"
- },
- "light": {
- "$ref": "#/$defs/AttributeViewColorTheme"
+ "id": {
+ "type": "string"
}
},
"required": [
- "dark",
- "index",
- "light"
+ "id"
],
"additionalProperties": false
},
- "AttributeViewCustomColorInput": {
+ "AssetInsertCoverData": {
"type": "object",
"properties": {
- "dark": {
+ "succFiles": {
"anyOf": [
{
- "$ref": "#/$defs/AttributeViewColorThemeInput"
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/AssetUploadSuccess"
+ }
},
{
"type": "null"
}
]
},
- "hidden": {
+ "succMap": {
"anyOf": [
{
- "type": "boolean"
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
},
{
"type": "null"
}
]
- },
- "index": {
+ }
+ },
+ "required": [
+ "succFiles",
+ "succMap"
+ ],
+ "additionalProperties": false
+ },
+ "AssetOCRData": {
+ "type": "object",
+ "properties": {
+ "ocrJSON": {
"anyOf": [
{
- "type": "integer"
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
},
{
"type": "null"
}
]
},
- "light": {
+ "text": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "ocrJSON",
+ "text"
+ ],
+ "additionalProperties": false
+ },
+ "AssetOCRTextRequestInput": {
+ "type": "object",
+ "properties": {
+ "path": {
"anyOf": [
{
- "$ref": "#/$defs/AttributeViewColorThemeInput"
+ "type": "string"
},
{
"type": "null"
@@ -304,79 +349,64 @@
},
"additionalProperties": false
},
- "AutoLaunchRequestInput": {
+ "AssetPathData": {
"type": "object",
"properties": {
- "autoLaunch": {
- "type": "number"
+ "path": {
+ "type": "string"
}
},
"required": [
- "autoLaunch"
+ "path"
],
"additionalProperties": false
},
- "BacklinkAttributeViewMatch": {
+ "AssetPathRequestInput": {
"type": "object",
"properties": {
- "defIDs": {
+ "path": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "path"
+ ],
+ "additionalProperties": false
+ },
+ "AssetPathsCloudUploadRequestInput": {
+ "type": "object",
+ "properties": {
+ "ignorePushMsg": {
"anyOf": [
{
- "type": "array",
- "items": {
- "type": "string"
- }
+ "type": "boolean"
},
{
"type": "null"
}
]
},
- "itemID": {
- "type": "string"
- },
- "keyID": {
- "type": "string"
- },
- "keyName": {
- "type": "string"
- },
- "title": {
- "type": "string"
- },
- "valueID": {
- "type": "string"
+ "paths": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
},
"required": [
- "defIDs",
- "itemID",
- "keyID",
- "keyName",
- "title",
- "valueID"
+ "paths"
],
"additionalProperties": false
},
- "BacklinkAttributeViewTarget": {
+ "AssetPathsData": {
"type": "object",
"properties": {
- "blockID": {
- "type": "string"
- },
- "matches": {
+ "paths": {
"anyOf": [
{
"type": "array",
"items": {
- "anyOf": [
- {
- "$ref": "#/$defs/BacklinkAttributeViewMatch"
- },
- {
- "type": "null"
- }
- ]
+ "type": "string"
}
},
{
@@ -386,91 +416,106 @@
}
},
"required": [
- "blockID",
- "matches"
+ "paths"
],
"additionalProperties": false
},
- "BacklinkContext": {
+ "AssetRenameData": {
"type": "object",
"properties": {
- "attributeViewTargets": {
- "type": "array",
- "items": {
- "anyOf": [
- {
- "$ref": "#/$defs/BacklinkAttributeViewTarget"
- },
- {
- "type": "null"
- }
- ]
- }
+ "newPath": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "newPath"
+ ],
+ "additionalProperties": false
+ },
+ "AssetStatData": {
+ "type": "object",
+ "properties": {
+ "created": {
+ "type": "integer"
},
- "blockPaths": {
- "anyOf": [
- {
- "type": "array",
- "items": {
- "anyOf": [
- {
- "$ref": "#/$defs/BlockPath"
- },
- {
- "type": "null"
- }
- ]
- }
- },
- {
- "type": "null"
- }
+ "downloaded": {
+ "type": "boolean",
+ "enum": [
+ false
]
},
- "dom": {
+ "hCreated": {
"type": "string"
},
- "expand": {
- "type": "boolean"
- },
- "id": {
+ "hSize": {
"type": "string"
},
- "referenceBlockID": {
+ "hUpdated": {
"type": "string"
},
- "revision": {
- "type": "string"
+ "size": {
+ "type": "integer"
},
- "type": {
+ "updated": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "created",
+ "hCreated",
+ "hSize",
+ "hUpdated",
+ "size",
+ "updated"
+ ],
+ "additionalProperties": false
+ },
+ "AssetTextData": {
+ "type": "object",
+ "properties": {
+ "text": {
"type": "string"
}
},
"required": [
- "blockPaths",
- "dom",
- "expand",
- "id",
- "revision"
+ "text"
],
"additionalProperties": false
},
- "BacklinkContextData": {
+ "AssetUnusedItem": {
"type": "object",
"properties": {
- "backlinks": {
+ "blockIDs": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "item": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "item",
+ "name"
+ ],
+ "additionalProperties": false
+ },
+ "AssetUploadData": {
+ "type": "object",
+ "properties": {
+ "errFiles": {
"anyOf": [
{
"type": "array",
"items": {
- "anyOf": [
- {
- "$ref": "#/$defs/BacklinkContext"
- },
- {
- "type": "null"
- }
- ]
+ "type": "string"
}
},
{
@@ -478,19 +523,12 @@
}
]
},
- "backmentions": {
+ "failedFiles": {
"anyOf": [
{
"type": "array",
"items": {
- "anyOf": [
- {
- "$ref": "#/$defs/BacklinkContext"
- },
- {
- "type": "null"
- }
- ]
+ "$ref": "#/$defs/AssetUploadFailure"
}
},
{
@@ -498,11 +536,24 @@
}
]
},
- "keywords": {
+ "succFiles": {
"anyOf": [
{
"type": "array",
"items": {
+ "$ref": "#/$defs/AssetUploadSuccess"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "succMap": {
+ "anyOf": [
+ {
+ "type": "object",
+ "additionalProperties": {
"type": "string"
}
},
@@ -510,72 +561,158 @@
"type": "null"
}
]
+ }
+ },
+ "required": [
+ "errFiles",
+ "failedFiles",
+ "succFiles",
+ "succMap"
+ ],
+ "additionalProperties": false
+ },
+ "AssetUploadFailure": {
+ "type": "object",
+ "properties": {
+ "error": {
+ "type": "string"
},
- "revision": {
+ "index": {
+ "type": "integer"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "error",
+ "index",
+ "name"
+ ],
+ "additionalProperties": false
+ },
+ "AssetUploadSuccess": {
+ "type": "object",
+ "properties": {
+ "index": {
+ "type": "integer"
+ },
+ "name": {
"type": "string"
},
- "unchanged": {
- "type": "boolean"
+ "path": {
+ "type": "string"
}
},
"required": [
- "backlinks",
- "backmentions",
- "keywords",
- "revision",
- "unchanged"
+ "index",
+ "name",
+ "path"
],
"additionalProperties": false
},
- "BacklinkDocumentRequestInput": {
+ "AttributeViewColorTheme": {
"type": "object",
"properties": {
- "containChildren": {
+ "backgroundColor": {
+ "type": "string"
+ },
+ "color": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "backgroundColor",
+ "color"
+ ],
+ "additionalProperties": false
+ },
+ "AttributeViewColorThemeInput": {
+ "type": "object",
+ "properties": {
+ "backgroundColor": {
"anyOf": [
{
- "type": "boolean"
+ "type": "string"
},
{
"type": "null"
}
]
},
- "defID": {
- "type": "string"
- },
- "highlight": {
+ "color": {
"anyOf": [
{
- "type": "boolean"
+ "type": "string"
},
{
"type": "null"
}
]
+ }
+ },
+ "additionalProperties": false
+ },
+ "AttributeViewCustomColor": {
+ "type": "object",
+ "properties": {
+ "dark": {
+ "$ref": "#/$defs/AttributeViewColorTheme"
},
- "keyword": {
- "type": "string"
+ "hidden": {
+ "type": "boolean"
},
- "knownRevision": {
+ "index": {
+ "type": "integer"
+ },
+ "light": {
+ "$ref": "#/$defs/AttributeViewColorTheme"
+ }
+ },
+ "required": [
+ "dark",
+ "index",
+ "light"
+ ],
+ "additionalProperties": false
+ },
+ "AttributeViewCustomColorInput": {
+ "type": "object",
+ "properties": {
+ "dark": {
"anyOf": [
{
- "type": "string"
+ "$ref": "#/$defs/AttributeViewColorThemeInput"
},
{
"type": "null"
}
]
},
- "notebook": {
- "type": "string"
+ "hidden": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
},
- "refTreeID": {
- "type": "string"
+ "index": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
},
- "sourceFilter": {
+ "light": {
"anyOf": [
{
- "$ref": "#/$defs/BacklinkSourceFilterInput"
+ "$ref": "#/$defs/AttributeViewColorThemeInput"
},
{
"type": "null"
@@ -583,29 +720,29 @@
]
}
},
+ "additionalProperties": false
+ },
+ "AutoLaunchRequestInput": {
+ "type": "object",
+ "properties": {
+ "autoLaunch": {
+ "type": "number"
+ }
+ },
"required": [
- "defID",
- "keyword",
- "refTreeID"
+ "autoLaunch"
],
"additionalProperties": false
},
- "BacklinkList": {
+ "BacklinkAttributeViewMatch": {
"type": "object",
"properties": {
- "backlinks": {
+ "defIDs": {
"anyOf": [
{
"type": "array",
"items": {
- "anyOf": [
- {
- "$ref": "#/$defs/BacklinkPath"
- },
- {
- "type": "null"
- }
- ]
+ "type": "string"
}
},
{
@@ -613,131 +750,218 @@
}
]
},
- "backmentions": {
- "anyOf": [
- {
- "type": "array",
- "items": {
- "anyOf": [
- {
- "$ref": "#/$defs/BacklinkPath"
- },
- {
- "type": "null"
- }
- ]
- }
- },
- {
- "type": "null"
- }
- ]
- },
- "box": {
+ "itemID": {
"type": "string"
},
- "k": {
+ "keyID": {
"type": "string"
},
- "linkRefsCount": {
- "type": "integer"
- },
- "mentionsCount": {
- "type": "integer"
- },
- "mk": {
+ "keyName": {
"type": "string"
},
- "revision": {
+ "title": {
"type": "string"
},
- "unchanged": {
- "type": "boolean"
+ "valueID": {
+ "type": "string"
}
},
"required": [
- "backlinks",
- "backmentions",
- "box",
- "k",
- "linkRefsCount",
- "mentionsCount",
- "mk",
- "revision",
- "unchanged"
+ "defIDs",
+ "itemID",
+ "keyID",
+ "keyName",
+ "title",
+ "valueID"
],
"additionalProperties": false
},
- "BacklinkListRequestInput": {
+ "BacklinkAttributeViewTarget": {
"type": "object",
"properties": {
- "containChildren": {
+ "blockID": {
+ "type": "string"
+ },
+ "matches": {
"anyOf": [
{
- "type": "boolean"
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BacklinkAttributeViewMatch"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
},
{
"type": "null"
}
]
+ }
+ },
+ "required": [
+ "blockID",
+ "matches"
+ ],
+ "additionalProperties": false
+ },
+ "BacklinkContext": {
+ "type": "object",
+ "properties": {
+ "attributeViewTargets": {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BacklinkAttributeViewTarget"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
},
- "id": {
+ "blockPaths": {
"anyOf": [
{
- "type": "string"
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BlockPath"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
},
{
"type": "null"
}
]
},
- "includeMentions": {
+ "dom": {
+ "type": "string"
+ },
+ "expand": {
+ "type": "boolean"
+ },
+ "id": {
+ "type": "string"
+ },
+ "referenceBlockID": {
+ "type": "string"
+ },
+ "revision": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "blockPaths",
+ "dom",
+ "expand",
+ "id",
+ "revision"
+ ],
+ "additionalProperties": false
+ },
+ "BacklinkContextData": {
+ "type": "object",
+ "properties": {
+ "backlinks": {
"anyOf": [
{
- "type": "boolean"
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BacklinkContext"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
},
{
"type": "null"
}
]
},
- "k": {
- "type": "string"
- },
- "knownRevision": {
+ "backmentions": {
"anyOf": [
{
- "type": "string"
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BacklinkContext"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
},
{
"type": "null"
}
]
},
- "mSort": {
+ "keywords": {
"anyOf": [
{
- "type": "string"
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
},
{
"type": "null"
}
]
},
- "mk": {
+ "revision": {
"type": "string"
},
- "notebook": {
+ "unchanged": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "backlinks",
+ "backmentions",
+ "keywords",
+ "revision",
+ "unchanged"
+ ],
+ "additionalProperties": false
+ },
+ "BacklinkDocumentRequestInput": {
+ "type": "object",
+ "properties": {
+ "containChildren": {
"anyOf": [
{
- "type": "string"
+ "type": "boolean"
},
{
"type": "null"
}
]
},
- "refDefCandidates": {
+ "defID": {
+ "type": "string"
+ },
+ "highlight": {
"anyOf": [
{
"type": "boolean"
@@ -747,7 +971,10 @@
}
]
},
- "sort": {
+ "keyword": {
+ "type": "string"
+ },
+ "knownRevision": {
"anyOf": [
{
"type": "string"
@@ -757,6 +984,12 @@
}
]
},
+ "notebook": {
+ "type": "string"
+ },
+ "refTreeID": {
+ "type": "string"
+ },
"sourceFilter": {
"anyOf": [
{
@@ -768,29 +1001,214 @@
]
}
},
+ "required": [
+ "defID",
+ "keyword",
+ "refTreeID"
+ ],
"additionalProperties": false
},
- "BacklinkPath": {
+ "BacklinkList": {
"type": "object",
"properties": {
- "blocks": {
- "type": "array",
- "items": {
- "anyOf": [
- {
- "$ref": "#/$defs/SearchBlock"
- },
- {
- "type": "null"
+ "backlinks": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BacklinkPath"
+ },
+ {
+ "type": "null"
+ }
+ ]
}
- ]
- }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "backmentions": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BacklinkPath"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
},
"box": {
"type": "string"
},
- "children": {
- "type": "array",
+ "k": {
+ "type": "string"
+ },
+ "linkRefsCount": {
+ "type": "integer"
+ },
+ "mentionsCount": {
+ "type": "integer"
+ },
+ "mk": {
+ "type": "string"
+ },
+ "revision": {
+ "type": "string"
+ },
+ "unchanged": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "backlinks",
+ "backmentions",
+ "box",
+ "k",
+ "linkRefsCount",
+ "mentionsCount",
+ "mk",
+ "revision",
+ "unchanged"
+ ],
+ "additionalProperties": false
+ },
+ "BacklinkListRequestInput": {
+ "type": "object",
+ "properties": {
+ "containChildren": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "includeMentions": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "k": {
+ "type": "string"
+ },
+ "knownRevision": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "mSort": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "mk": {
+ "type": "string"
+ },
+ "notebook": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "refDefCandidates": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "sort": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "sourceFilter": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BacklinkSourceFilterInput"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "additionalProperties": false
+ },
+ "BacklinkPath": {
+ "type": "object",
+ "properties": {
+ "blocks": {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SearchBlock"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "box": {
+ "type": "string"
+ },
+ "children": {
+ "type": "array",
"items": {
"anyOf": [
{
@@ -10102,6 +10520,67 @@
],
"additionalProperties": false
},
+ "InsertCoverRequestInput": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "name"
+ ],
+ "additionalProperties": false
+ },
+ "InsertLocalAssetsRequestInput": {
+ "type": "object",
+ "properties": {
+ "assetPaths": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "fromHTMLPaste": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "isUpload": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "assetPaths"
+ ],
+ "additionalProperties": false
+ },
"InstallBazaarIconRequestInput": {
"type": "object",
"properties": {
@@ -12671,6 +13150,22 @@
],
"additionalProperties": false
},
+ "RenameAssetRequestInput": {
+ "type": "object",
+ "properties": {
+ "newName": {
+ "type": "string"
+ },
+ "oldPath": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "newName",
+ "oldPath"
+ ],
+ "additionalProperties": false
+ },
"RenameBookmarkRequestInput": {
"type": "object",
"properties": {
@@ -15444,6 +15939,38 @@
],
"additionalProperties": false
},
+ "SetAssetAnnotationRequestInput": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "data",
+ "path"
+ ],
+ "additionalProperties": false
+ },
+ "SetAssetOCRTextRequestInput": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string"
+ },
+ "text": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "path",
+ "text"
+ ],
+ "additionalProperties": false
+ },
"SetBazaarPackageRatingRequestInput": {
"type": "object",
"properties": {
@@ -17445,15 +17972,34 @@
],
"additionalProperties": false
},
- "UploadCloudSnapshotRequestInput": {
+ "UploadAssetRequestInput": {
"type": "object",
"properties": {
- "id": {
+ "assetsDirPath": {
"type": "string"
},
- "tag": {
- "type": "string"
- }
+ "file[]": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "binary"
+ }
+ },
+ "id": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false
+ },
+ "UploadCloudSnapshotRequestInput": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "tag": {
+ "type": "string"
+ }
},
"required": [
"id",
@@ -17814,12 +18360,1738 @@
}
},
{
- "method": "GET",
- "path": "/api/plugin/rpc",
- "handler": "getLoadedPluginRPC",
+ "method": "GET",
+ "path": "/api/plugin/rpc",
+ "handler": "getLoadedPluginRPC",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/LoadedPluginRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/LoadedPlugin"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 1,
+ 2,
+ 3,
+ 4
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "GET",
+ "path": "/api/plugin/rpc/:name",
+ "handler": "getLoadedPluginRPCByName",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/LoadedPluginRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/LoadedPlugin"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 1,
+ 2,
+ 3,
+ 4
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "GET",
+ "path": "/api/system/bootProgress",
+ "handler": "bootProgress",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/BootProgressData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "GET",
+ "path": "/api/system/version",
+ "handler": "version",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "string"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "GET",
+ "path": "/ws/plugin/rpc",
+ "handler": "pluginJsonRpcWebSocket",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/PluginRPCFailure"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "websocket",
+ "websocket": {
+ "incoming": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/PluginRPCRequestFieldsInput"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/PluginRPCRequestFieldsInput"
+ },
+ "minItems": 1
+ }
+ ]
+ },
+ "outgoing": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/PluginRPCSuccess"
+ },
+ {
+ "$ref": "#/$defs/PluginRPCFailure"
+ },
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/PluginRPCSuccess"
+ },
+ {
+ "$ref": "#/$defs/PluginRPCFailure"
+ }
+ ]
+ },
+ "minItems": 1
+ },
+ {
+ "$ref": "#/$defs/PluginRPCNotification"
+ }
+ ]
+ },
+ "failureStatus": 404
+ }
+ },
+ {
+ "method": "GET",
+ "path": "/ws/plugin/rpc/:name",
+ "handler": "pluginJsonRpcWebSocketByName",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/PluginRPCFailure"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "websocket",
+ "websocket": {
+ "incoming": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/PluginRPCRequestFieldsInput"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/PluginRPCRequestFieldsInput"
+ },
+ "minItems": 1
+ }
+ ]
+ },
+ "outgoing": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/PluginRPCSuccess"
+ },
+ {
+ "$ref": "#/$defs/PluginRPCFailure"
+ },
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/PluginRPCSuccess"
+ },
+ {
+ "$ref": "#/$defs/PluginRPCFailure"
+ }
+ ]
+ },
+ "minItems": 1
+ },
+ {
+ "$ref": "#/$defs/PluginRPCNotification"
+ }
+ ]
+ },
+ "failureStatus": 404
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/account/checkActivationcode",
+ "handler": "checkActivationcode",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/CheckActivationCodeRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "null"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/account/deactivate",
+ "handler": "deactivateUser",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "null"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/account/login",
+ "handler": "login",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/AccountLoginRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/AccountLoginData"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 1,
+ 10
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ },
+ {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/AccountLoginData"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/account/startFreeTrial",
+ "handler": "startFreeTrial",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "null"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/account/useActivationcode",
+ "handler": "useActivationcode",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/ActivationCodeRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "null"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/archive/unzip",
+ "handler": "unzip",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/UnzipRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "null"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/archive/zip",
+ "handler": "zip",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/ZipRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "null"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/asset/fullReindexAssetContent",
+ "handler": "fullReindexAssetContent",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "null"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/asset/getDocAssets",
+ "handler": "getDocAssets",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/AssetDocumentAssetsRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/asset/getDocImageAssets",
+ "handler": "getDocImageAssets",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/AssetDocumentRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/asset/getFileAnnotation",
+ "handler": "getFileAnnotation",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/AssetPathRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/AssetAnnotationData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 1,
+ 403
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/asset/getImageOCRText",
+ "handler": "getImageOCRText",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/AssetOCRTextRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/AssetTextData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/asset/getMissingAssets",
+ "handler": "getMissingAssets",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/AssetUnusedItem"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/asset/getUnusedAssets",
+ "handler": "getUnusedAssets",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/AssetUnusedItem"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/asset/insertCover",
+ "handler": "insertCover",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/InsertCoverRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/AssetInsertCoverData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/asset/insertLocalAssets",
+ "handler": "insertLocalAssets",
"body": "json",
"request": {
- "$ref": "#/$defs/LoadedPluginRequestInput"
+ "$ref": "#/$defs/InsertLocalAssetsRequestInput"
},
"response": {
"anyOf": [
@@ -17833,14 +20105,7 @@
]
},
"data": {
- "anyOf": [
- {
- "$ref": "#/$defs/LoadedPlugin"
- },
- {
- "type": "null"
- }
- ]
+ "$ref": "#/$defs/AssetUploadData"
},
"msg": {
"type": "string"
@@ -17859,11 +20124,7 @@
"code": {
"type": "integer",
"enum": [
- -1,
- 1,
- 2,
- 3,
- 4
+ -1
]
},
"data": {
@@ -17882,6 +20143,9 @@
},
{
"type": "null"
+ },
+ {
+ "$ref": "#/$defs/AssetUploadData"
}
]
},
@@ -17900,12 +20164,12 @@
}
},
{
- "method": "GET",
- "path": "/api/plugin/rpc/:name",
- "handler": "getLoadedPluginRPCByName",
+ "method": "POST",
+ "path": "/api/asset/ocr",
+ "handler": "ocr",
"body": "json",
"request": {
- "$ref": "#/$defs/LoadedPluginRequestInput"
+ "$ref": "#/$defs/AssetPathRequestInput"
},
"response": {
"anyOf": [
@@ -17919,14 +20183,7 @@
]
},
"data": {
- "anyOf": [
- {
- "$ref": "#/$defs/LoadedPlugin"
- },
- {
- "type": "null"
- }
- ]
+ "$ref": "#/$defs/AssetOCRData"
},
"msg": {
"type": "string"
@@ -17945,11 +20202,7 @@
"code": {
"type": "integer",
"enum": [
- -1,
- 1,
- 2,
- 3,
- 4
+ -1
]
},
"data": {
@@ -17986,12 +20239,12 @@
}
},
{
- "method": "GET",
- "path": "/api/system/bootProgress",
- "handler": "bootProgress",
- "body": "none",
+ "method": "POST",
+ "path": "/api/asset/removeUnusedAsset",
+ "handler": "removeUnusedAsset",
+ "body": "json",
"request": {
- "$ref": "#/$defs/EmptyRequestInput"
+ "$ref": "#/$defs/AssetPathRequestInput"
},
"response": {
"anyOf": [
@@ -18005,7 +20258,7 @@
]
},
"data": {
- "$ref": "#/$defs/BootProgressData"
+ "$ref": "#/$defs/AssetPathData"
},
"msg": {
"type": "string"
@@ -18061,9 +20314,9 @@
}
},
{
- "method": "GET",
- "path": "/api/system/version",
- "handler": "version",
+ "method": "POST",
+ "path": "/api/asset/removeUnusedAssets",
+ "handler": "removeUnusedAssets",
"body": "none",
"request": {
"$ref": "#/$defs/EmptyRequestInput"
@@ -18080,7 +20333,7 @@
]
},
"data": {
- "type": "string"
+ "$ref": "#/$defs/AssetPathsData"
},
"msg": {
"type": "string"
@@ -18136,45 +20389,26 @@
}
},
{
- "method": "GET",
- "path": "/ws/plugin/rpc",
- "handler": "pluginJsonRpcWebSocket",
- "body": "none",
+ "method": "POST",
+ "path": "/api/asset/renameAsset",
+ "handler": "renameAsset",
+ "body": "json",
"request": {
- "$ref": "#/$defs/EmptyRequestInput"
+ "$ref": "#/$defs/RenameAssetRequestInput"
},
"response": {
"anyOf": [
- {
- "$ref": "#/$defs/PluginRPCFailure"
- },
{
"type": "object",
"properties": {
"code": {
"type": "integer",
"enum": [
- -1
+ 0
]
},
"data": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "closeTimeout": {
- "type": "number"
- }
- },
- "required": [
- "closeTimeout"
- ],
- "additionalProperties": false
- },
- {
- "type": "null"
- }
- ]
+ "$ref": "#/$defs/AssetRenameData"
},
"msg": {
"type": "string"
@@ -18185,68 +20419,7 @@
"msg",
"data"
],
- "additionalProperties": true
- }
- ]
- },
- "output": "websocket",
- "websocket": {
- "incoming": {
- "anyOf": [
- {
- "$ref": "#/$defs/PluginRPCRequestFieldsInput"
- },
- {
- "type": "array",
- "items": {
- "$ref": "#/$defs/PluginRPCRequestFieldsInput"
- },
- "minItems": 1
- }
- ]
- },
- "outgoing": {
- "anyOf": [
- {
- "$ref": "#/$defs/PluginRPCSuccess"
- },
- {
- "$ref": "#/$defs/PluginRPCFailure"
- },
- {
- "type": "array",
- "items": {
- "anyOf": [
- {
- "$ref": "#/$defs/PluginRPCSuccess"
- },
- {
- "$ref": "#/$defs/PluginRPCFailure"
- }
- ]
- },
- "minItems": 1
- },
- {
- "$ref": "#/$defs/PluginRPCNotification"
- }
- ]
- },
- "failureStatus": 404
- }
- },
- {
- "method": "GET",
- "path": "/ws/plugin/rpc/:name",
- "handler": "pluginJsonRpcWebSocketByName",
- "body": "none",
- "request": {
- "$ref": "#/$defs/EmptyRequestInput"
- },
- "response": {
- "anyOf": [
- {
- "$ref": "#/$defs/PluginRPCFailure"
+ "additionalProperties": false
},
{
"type": "object",
@@ -18288,60 +20461,15 @@
"additionalProperties": true
}
]
- },
- "output": "websocket",
- "websocket": {
- "incoming": {
- "anyOf": [
- {
- "$ref": "#/$defs/PluginRPCRequestFieldsInput"
- },
- {
- "type": "array",
- "items": {
- "$ref": "#/$defs/PluginRPCRequestFieldsInput"
- },
- "minItems": 1
- }
- ]
- },
- "outgoing": {
- "anyOf": [
- {
- "$ref": "#/$defs/PluginRPCSuccess"
- },
- {
- "$ref": "#/$defs/PluginRPCFailure"
- },
- {
- "type": "array",
- "items": {
- "anyOf": [
- {
- "$ref": "#/$defs/PluginRPCSuccess"
- },
- {
- "$ref": "#/$defs/PluginRPCFailure"
- }
- ]
- },
- "minItems": 1
- },
- {
- "$ref": "#/$defs/PluginRPCNotification"
- }
- ]
- },
- "failureStatus": 404
}
},
{
"method": "POST",
- "path": "/api/account/checkActivationcode",
- "handler": "checkActivationcode",
+ "path": "/api/asset/resolveAssetPath",
+ "handler": "resolveAssetPath",
"body": "json",
"request": {
- "$ref": "#/$defs/CheckActivationCodeRequestInput"
+ "$ref": "#/$defs/AssetPathRequestInput"
},
"response": {
"anyOf": [
@@ -18355,7 +20483,7 @@
]
},
"data": {
- "type": "null"
+ "type": "string"
},
"msg": {
"type": "string"
@@ -18374,8 +20502,7 @@
"code": {
"type": "integer",
"enum": [
- -1,
- 1
+ -1
]
},
"data": {
@@ -18392,9 +20519,6 @@
],
"additionalProperties": false
},
- {
- "type": "null"
- },
{
"type": "null"
}
@@ -18416,11 +20540,11 @@
},
{
"method": "POST",
- "path": "/api/account/deactivate",
- "handler": "deactivateUser",
- "body": "none",
+ "path": "/api/asset/setFileAnnotation",
+ "handler": "setFileAnnotation",
+ "body": "json",
"request": {
- "$ref": "#/$defs/EmptyRequestInput"
+ "$ref": "#/$defs/SetAssetAnnotationRequestInput"
},
"response": {
"anyOf": [
@@ -18491,11 +20615,11 @@
},
{
"method": "POST",
- "path": "/api/account/login",
- "handler": "login",
+ "path": "/api/asset/setImageOCRText",
+ "handler": "setImageOCRText",
"body": "json",
"request": {
- "$ref": "#/$defs/AccountLoginRequestInput"
+ "$ref": "#/$defs/SetAssetOCRTextRequestInput"
},
"response": {
"anyOf": [
@@ -18509,14 +20633,7 @@
]
},
"data": {
- "anyOf": [
- {
- "$ref": "#/$defs/AccountLoginData"
- },
- {
- "type": "null"
- }
- ]
+ "type": "null"
},
"msg": {
"type": "string"
@@ -18535,9 +20652,7 @@
"code": {
"type": "integer",
"enum": [
- -1,
- 1,
- 10
+ -1
]
},
"data": {
@@ -18556,16 +20671,6 @@
},
{
"type": "null"
- },
- {
- "anyOf": [
- {
- "$ref": "#/$defs/AccountLoginData"
- },
- {
- "type": "null"
- }
- ]
}
]
},
@@ -18585,11 +20690,11 @@
},
{
"method": "POST",
- "path": "/api/account/startFreeTrial",
- "handler": "startFreeTrial",
- "body": "none",
+ "path": "/api/asset/statAsset",
+ "handler": "statAsset",
+ "body": "json",
"request": {
- "$ref": "#/$defs/EmptyRequestInput"
+ "$ref": "#/$defs/AssetPathRequestInput"
},
"response": {
"anyOf": [
@@ -18603,7 +20708,7 @@
]
},
"data": {
- "type": "null"
+ "$ref": "#/$defs/AssetStatData"
},
"msg": {
"type": "string"
@@ -18622,7 +20727,8 @@
"code": {
"type": "integer",
"enum": [
- -1
+ -1,
+ 1
]
},
"data": {
@@ -18660,11 +20766,11 @@
},
{
"method": "POST",
- "path": "/api/account/useActivationcode",
- "handler": "useActivationcode",
- "body": "json",
+ "path": "/api/asset/upload",
+ "handler": "uploadAsset",
+ "body": "multipart",
"request": {
- "$ref": "#/$defs/ActivationCodeRequestInput"
+ "$ref": "#/$defs/UploadAssetRequestInput"
},
"response": {
"anyOf": [
@@ -18678,7 +20784,7 @@
]
},
"data": {
- "type": "null"
+ "$ref": "#/$defs/AssetUploadData"
},
"msg": {
"type": "string"
@@ -18735,11 +20841,11 @@
},
{
"method": "POST",
- "path": "/api/archive/unzip",
- "handler": "unzip",
+ "path": "/api/asset/uploadCloud",
+ "handler": "uploadCloud",
"body": "json",
"request": {
- "$ref": "#/$defs/UnzipRequestInput"
+ "$ref": "#/$defs/AssetCloudUploadRequestInput"
},
"response": {
"anyOf": [
@@ -18810,11 +20916,11 @@
},
{
"method": "POST",
- "path": "/api/archive/zip",
- "handler": "zip",
+ "path": "/api/asset/uploadCloudByAssetsPaths",
+ "handler": "uploadCloudByAssetsPaths",
"body": "json",
"request": {
- "$ref": "#/$defs/ZipRequestInput"
+ "$ref": "#/$defs/AssetPathsCloudUploadRequestInput"
},
"response": {
"anyOf": [
diff --git a/kernel/model/upload.go b/kernel/model/upload.go
index a818a53bbc..a94faf5837 100644
--- a/kernel/model/upload.go
+++ b/kernel/model/upload.go
@@ -21,6 +21,7 @@ import (
"errors"
"fmt"
"io"
+ "mime/multipart"
"os"
"path"
"path/filepath"
@@ -107,7 +108,7 @@ type AssetUploadFailure struct {
Error string `json:"error"`
}
-func recordAssetUploadSuccess(succMap map[string]any, succFiles *[]AssetUploadSuccess, index int, name, assetPath string) {
+func recordAssetUploadSuccess(succMap map[string]string, succFiles *[]AssetUploadSuccess, index int, name, assetPath string) {
succMap[name] = assetPath
*succFiles = append(*succFiles, AssetUploadSuccess{Index: index, Name: name, Path: assetPath})
}
@@ -159,19 +160,19 @@ func copyRTFDEntries(entries []os.DirEntry, srcDir, destDir string, copyFile fun
return nil
}
-func InsertLocalAssets(id string, assetAbsPaths []string, isUpload bool) (succMap map[string]any,
+func InsertLocalAssets(id string, assetAbsPaths []string, isUpload bool) (succMap map[string]string,
succFiles []AssetUploadSuccess, failedFiles []AssetUploadFailure, err error) {
return insertLocalAssets(id, assetAbsPaths, isUpload, false)
}
-func InsertHTMLLocalAssets(id string, assetAbsPaths []string) (succMap map[string]any,
+func InsertHTMLLocalAssets(id string, assetAbsPaths []string) (succMap map[string]string,
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,
+func insertLocalAssets(id string, assetAbsPaths []string, isUpload, validateHTMLPath bool) (succMap map[string]string,
succFiles []AssetUploadSuccess, failedFiles []AssetUploadFailure, err error) {
- succMap = map[string]any{}
+ succMap = map[string]string{}
succFiles = make([]AssetUploadSuccess, 0, len(assetAbsPaths))
failedFiles = make([]AssetUploadFailure, 0)
@@ -302,7 +303,6 @@ func insertLocalAssets(id string, assetAbsPaths []string, isUpload, validateHTML
func Upload(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(200, ret)
-
form, err := c.MultipartForm()
if err != nil {
logging.LogErrorf("insert asset failed: %s", err)
@@ -310,10 +310,43 @@ func Upload(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ request := AssetUploadRequest{Files: form.File["file[]"]}
+ if values := form.Value["id"]; values != nil {
+ request.ID = &values[0]
+ }
+ if values := form.Value["assetsDirPath"]; values != nil {
+ request.AssetsDirPath = &values[0]
+ }
+ result, message, err := UploadAssets(request)
+ ret.Msg = message
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ ret.Data = result
+}
+
+// AssetUploadRequest 保留目标字段的缺省状态,并按输入顺序接收全部文件。
+type AssetUploadRequest struct {
+ ID *string
+ AssetsDirPath *string
+ Files []*multipart.FileHeader
+}
+type AssetUploadResult struct {
+ ErrFiles []string `json:"errFiles"`
+ FailedFiles []AssetUploadFailure `json:"failedFiles"`
+ SuccFiles []AssetUploadSuccess `json:"succFiles"`
+ SuccMap map[string]string `json:"succMap"`
+}
+
+// UploadAssets 将附件写入目标资源目录,保留逐文件结果、加密写入和首条失败提示。
+func UploadAssets(request AssetUploadRequest) (result *AssetUploadResult, message string, err error) {
+
assetsDirPath := filepath.Join(util.DataDir, "assets")
var uploadBoxID string // 记录上传目标 boxID,供 writeAssetFile 判断是否需加密
- if nil != form.Value["id"] {
- id := form.Value["id"][0]
+ if request.ID != nil {
+ id := *request.ID
bt := treenode.GetBlockTree(id)
if nil == bt {
// 全局 blocktree 找不到时,遍历已打开的加密笔记本查找
@@ -325,8 +358,7 @@ func Upload(c *gin.Context) {
}
}
if nil == bt {
- ret.Code = -1
- ret.Msg = Conf.Language(71)
+ err = errors.New(Conf.Language(71))
return
}
uploadBoxID = bt.BoxID
@@ -335,12 +367,11 @@ func Upload(c *gin.Context) {
}
relAssetsDirPath := "assets"
- if nil != form.Value["assetsDirPath"] {
- relAssetsDirPath = form.Value["assetsDirPath"][0]
+ if request.AssetsDirPath != nil {
+ relAssetsDirPath = *request.AssetsDirPath
assetsDirPath = filepath.Join(util.DataDir, relAssetsDirPath)
if !util.IsAbsPathInWorkspace(assetsDirPath) {
- ret.Code = -1
- ret.Msg = "Path [" + assetsDirPath + "] is not in workspace"
+ err = errors.New("Path [" + assetsDirPath + "] is not in workspace")
return
}
// assetsDirPath 可能指向加密 box(调用方未传 id),反查 boxID 让文件名脱敏和内容加密生效
@@ -356,22 +387,20 @@ func Upload(c *gin.Context) {
}
if !gulu.File.IsExist(assetsDirPath) {
if err = os.MkdirAll(assetsDirPath, 0755); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
return
}
}
var errFiles []string
- succMap := map[string]any{}
- files := form.File["file[]"]
+ succMap := map[string]string{}
+ files := request.Files
succFiles := make([]AssetUploadSuccess, 0, len(files))
failedFiles := make([]AssetUploadFailure, 0)
recordFailure := func(index int, inputName, errorName string, uploadErr error) {
errFiles = append(errFiles, errorName)
recordAssetUploadFailure(&failedFiles, index, inputName, uploadErr)
- if ret.Msg == "" {
- ret.Msg = uploadErr.Error()
+ if message == "" {
+ message = uploadErr.Error()
}
}
@@ -535,14 +564,11 @@ func Upload(c *gin.Context) {
}
}
- ret.Data = map[string]any{
- "errFiles": errFiles,
- "failedFiles": failedFiles,
- "succFiles": succFiles,
- "succMap": succMap,
- }
+ result = &AssetUploadResult{ErrFiles: errFiles, FailedFiles: failedFiles, SuccFiles: succFiles, SuccMap: succMap}
IncSync()
+
+ return result, message, nil
}
func getAssetsDir(boxLocalPath, docDirLocalPath string) (assets string) {
diff --git a/kernel/model/upload_test.go b/kernel/model/upload_test.go
index 50ca01d38b..6ab64b0d2a 100644
--- a/kernel/model/upload_test.go
+++ b/kernel/model/upload_test.go
@@ -133,7 +133,7 @@ func cleanupAssetUploadTestHashes(t *testing.T, successes []AssetUploadSuccess)
}
func TestRecordAssetUploadSuccessPreservesDuplicateNames(t *testing.T) {
- succMap := map[string]any{}
+ succMap := map[string]string{}
var succFiles []AssetUploadSuccess
recordAssetUploadSuccess(succMap, &succFiles, 0, "image.png", "assets/image-first.png")
recordAssetUploadSuccess(succMap, &succFiles, 1, "image.png", "assets/image-second.png")
diff --git a/kernel/util/ocr.go b/kernel/util/ocr.go
index ce4ebc0ce7..3d7c2721cf 100644
--- a/kernel/util/ocr.go
+++ b/kernel/util/ocr.go
@@ -157,7 +157,7 @@ func ExistsAssetText(asset string) (ret bool) {
return
}
-func OcrAsset(asset string) (ret []map[string]any, err error) {
+func OcrAsset(asset string) (ret []map[string]string, err error) {
if !TesseractEnabled {
err = errors.New(Langs[Lang][266])
return
@@ -219,7 +219,7 @@ func IsTesseractExtractable(p string) bool {
// tesseractOCRLock 用于 Tesseract OCR 加锁串行执行提升稳定性 https://github.com/siyuan-note/siyuan/issues/7265
var tesseractOCRLock = sync.Mutex{}
-func Tesseract(imgAbsPath string) (ret []map[string]any) {
+func Tesseract(imgAbsPath string) (ret []map[string]string) {
if ContainerStd != Container || !TesseractEnabled {
return
}
@@ -283,7 +283,7 @@ func Tesseract(imgAbsPath string) (ret []map[string]any) {
// 分割每列数据
fields := strings.Split(line, "\t")
// 将字段名和字段值映射到一个 map 中
- dataMap := make(map[string]any)
+ dataMap := make(map[string]string)
headers := strings.Split(lines[0], "\t")
for i, header := range headers {
if i < len(fields) {
@@ -303,14 +303,11 @@ func Tesseract(imgAbsPath string) (ret []map[string]any) {
}
// GetOcrJsonText 提取并连接所有 text 字段的函数
-func GetOcrJsonText(jsonData []map[string]any) (ret string) {
+func GetOcrJsonText(jsonData []map[string]string) (ret string) {
for _, dataMap := range jsonData {
// 检查 text 字段是否存在
if text, ok := dataMap["text"]; ok {
- // 确保 text 是字符串类型
- if textStr, ok := text.(string); ok {
- ret += " " + strings.ReplaceAll(textStr, "\r", "")
- }
+ ret += " " + strings.ReplaceAll(text, "\r", "")
}
}
ret = RemoveInvalid(ret)