An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: https://github.com/siyuan-note/siyuan/issues/13847
Vanessaa4d65410bef3
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.tsindex 32eb9bacf4..0830fa5699 100644--- a/app/src/config/entryVisibility/catalog.test.ts+++ b/app/src/config/entryVisibility/catalog.test.ts@@ -151,7 +151,20 @@ test("document loading actions follow the document menu order", () => {});test("multiple document and notebook entries follow their document tree menus", () => {- assert.deepEqual(getEntryCatalogChildren("docTree.notebooks").map((item) => item.key), ["close", "delete"]);+ assert.deepEqual(getEntryCatalogChildren("docTree.notebooks").map((item) => item.key), [+ "sort",+ "search",+ "replace",+ "separator_1",+ "close",+ "delete",+ "separator_2",+ "export",+ ]);+ assert.deepEqual(getEntryCatalogChildren("docTree.notebooks.export").map((item) => item.key), [+ "exportSiYuanZip",+ "exportMarkdown",+ ]);assert.ok(getEntryCatalogChildren("docTree.multi").some((item) => item.key === "delete"));});diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 1a0099cd16..8f639a6b13 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -460,7 +460,19 @@ export const entryCatalog: IEntryCatalogSection[] = [{key: "docTree.notebooks",label: location(lang("entryDocPanel"), lang("agentCatNotebook"), lang("multiSelect"), lang("more")),- children: [node("close", lang("close")), node("delete", lang("delete"))],+ children: [+ node("sort", lang("sort"), true, sortChildren()),+ node("search", lang("search")),+ node("replace", lang("replace")),+ separator("separator_1"),+ node("close", lang("close")),+ node("delete", lang("delete")),+ separator("separator_2"),+ node("export", lang("export"), true, [+ node("exportSiYuanZip", literal("SiYuan .sy.zip")),+ node("exportMarkdown", literal("Markdown .zip")),+ ]),+ ],},{key: "document.title",diff --git a/app/src/editor/deleteFile.ts b/app/src/editor/deleteFile.tsindex 1f3016880b..a2640d66f8 100644--- a/app/src/editor/deleteFile.ts+++ b/app/src/editor/deleteFile.ts@@ -61,7 +61,8 @@ export const deleteNotebooks = async (notebookIds: string[]) => {if (refResults.some((result) => result === undefined)) {return;}- const notebookNames = uniqueNotebookIds.map((notebook) => escapeHtml(getNotebookName(notebook))).join("<br>");+ const notebookNames = uniqueNotebookIds.map((notebook) => escapeHtml(getNotebookName(notebook)))+ .join(", ");let tip = `${window.siyuan.languages.confirmDeleteTip.replace("${x}", notebookNames)}<div class="fn__hr"></div><div class="ft__smaller ft__on-surface">${window.siyuan.languages.rollbackTip.replace("${x}", window.siyuan.config.editor.historyRetentionDays)}</div>`;@@ -144,7 +145,7 @@ export const deleteFiles = async (liElements: Element[]) => {return notebook ? escapeHtml(getNotebookName(notebook)) : "";}return escapeHtml(getDisplayName(item.getAttribute("data-path"), true, true));- }).filter(Boolean).join("<br>");+ }).filter(Boolean).join(", ");let tip = `${window.siyuan.languages.confirmDeleteTip.replace("${x}", itemNames)}<div class="fn__hr"></div><div class="ft__smaller ft__on-surface">${window.siyuan.languages.rollbackTip.replace("${x}", window.siyuan.config.editor.historyRetentionDays)}</div>`;diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.tsindex 9815803a70..60285dc3f2 100644--- a/app/src/menus/navigation.ts+++ b/app/src/menus/navigation.ts@@ -56,8 +56,93 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>const items = getDocTreeMenuItems(selectedItems);if (type === "notebooks") {window.siyuan.menus.menu.element.setAttribute("data-from", Constants.MENU_FROM_DOC_TREE_MORE_NOTEBOOKS);+ const notebookIds = items.map((item) => item.id);+ const notebookNames = notebookIds.map((notebookId) => getNotebookName(notebookId)).join(" ");if (!window.siyuan.config.readonly) {- const notebookIds = items.map((item) => item.id);+ const sortModes = selectedItems.map((item) => parseInt(item.parentElement?.getAttribute("data-sortmode")));+ const sortMode = sortModes.every((item) => item === sortModes[0]) ? sortModes[0] : -1;+ const subMenu = sortMenu("notebook", sortMode, async (sort) => {+ let files;+ /// #if MOBILE+ files = window.siyuan.mobile.docks.file;+ /// #else+ files = (getDockByType("file").data["file"] as Files);+ /// #endif+ for (const item of selectedItems) {+ const notebookId = item.parentElement?.getAttribute("data-url");+ if (!notebookId) {+ continue;+ }+ const response = await fetchSyncPost("/api/notebook/setNotebookConf", {+ notebook: notebookId,+ conf: {sortMode: sort},+ });+ if (response.code !== 0) {+ continue;+ }+ item.parentElement.setAttribute("data-sortmode", sort.toString());+ const toggleElement = item.querySelector(".b3-list-item__arrow--open");+ if (toggleElement) {+ toggleElement.classList.remove("b3-list-item__arrow--open");+ item.nextElementSibling?.remove();+ files.getLeaf(item, notebookId);+ }+ }+ });+ window.siyuan.menus.menu.append(new MenuItem({+ id: "sort",+ icon: "iconSort",+ label: window.siyuan.languages.sort,+ type: "submenu",+ submenu: subMenu,+ }).element);+ }+ window.siyuan.menus.menu.append(new MenuItem({+ id: "search",+ label: window.siyuan.languages.search,+ accelerator: window.siyuan.config.keymap.general.search.custom,+ icon: "iconSearch",+ click() {+ /// #if MOBILE+ popSearch(app, {+ hasReplace: false,+ hPath: notebookNames,+ idPath: notebookIds,+ page: 1,+ });+ /// #else+ openSearch({+ app,+ hotkey: Constants.DIALOG_SEARCH,+ notebookIds,+ });+ /// #endif+ }+ }).element);+ if (!window.siyuan.config.readonly) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "replace",+ label: window.siyuan.languages.replace,+ accelerator: window.siyuan.config.keymap.general.replace.custom,+ icon: "iconReplace",+ click() {+ /// #if MOBILE+ popSearch(app, {+ hasReplace: true,+ hPath: notebookNames,+ idPath: notebookIds,+ page: 1,+ });+ /// #else+ openSearch({+ app,+ hotkey: Constants.DIALOG_REPLACE,+ notebookIds,+ });+ /// #endif+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);if (notebookIds.every((notebookId) => !Object.values(Constants.HELP_PATH).includes(notebookId))) {window.siyuan.menus.menu.append(new MenuItem({id: "close",@@ -80,12 +165,41 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>}}).element);}+ const ignoreExport = notebookIds.some((notebookId) => isEncryptedBox(notebookId));+ window.siyuan.menus.menu.append(new MenuItem({+ id: "separator_2",+ type: "separator",+ ignore: ignoreExport,+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "export",+ label: window.siyuan.languages.export,+ type: "submenu",+ icon: "iconUpload",+ ignore: ignoreExport,+ submenu: [{+ id: "exportSiYuanZip",+ label: "SiYuan .sy.zip",+ icon: "iconSiYuan",+ click: () => {+ const msgId = showMessage(window.siyuan.languages.exporting, -1);+ fetchPost("/api/export/exportNotebooksSY", {notebooks: notebookIds}, (response) => {+ saveExportFile(response.data.zip, msgId);+ });+ }+ }, {+ id: "exportMarkdown",+ label: "Markdown .zip",+ icon: "iconMarkdown",+ click: () => exportMarkdownZip({notebooks: notebookIds}),+ }]+ }).element);if (app.plugins) {emitOpenMenu({plugins: app.plugins,type: "open-menu-doctree",detail: {elements: selectItemElements, type: "notebooks", items},- separatorPosition: !window.siyuan.config.readonly ? "top" : undefined,+ separatorPosition: "top",});}return window.siyuan.menus.menu;diff --git a/app/src/protyle/export/exportMd.ts b/app/src/protyle/export/exportMd.tsindex ab274bf943..c275faefd9 100644--- a/app/src/protyle/export/exportMd.ts+++ b/app/src/protyle/export/exportMd.ts@@ -20,6 +20,7 @@ interface IExportMdOptions {id?: string;ids?: string[];notebook?: string;+ notebooks?: string[];}// openExportOptionsDialog 渲染「通用 + Markdown 专属」两组开关,确认时回调 onConfirm 传出全部 13 项。@@ -139,7 +140,7 @@ interface IExportMdOptionsPayload {removeAssetsID: boolean;}-// exportMarkdownZip 为 Markdown .zip 导出入口:弹参数对话框,确认后按 id/ids/notebook 调对应 API。+// exportMarkdownZip 为 Markdown .zip 导出入口:弹参数对话框,确认后按文档、文档集合或笔记本集合调用对应 API。// 单文档时先查询文档信息,若无子文档/关联文档则隐藏对应配置项,减少干扰。export const exportMarkdownZip = async(options: IExportMdOptions) => {let showSubDocs = true;@@ -156,15 +157,17 @@ export const exportMarkdownZip = async(options: IExportMdOptions) => {}openExportOptionsDialog(params => {const exportMarkdown = () => {- const msgId = showMessage(window.siyuan.languages.exporting, -1);- const cb = (response: IWebSocketData) => saveExportFile(response.data.zip, msgId);- if (options.id) {- fetchPost("/api/export/exportMd", {id: options.id, ...params}, cb);- } else if (options.ids) {- fetchPost("/api/export/exportMds", {ids: options.ids, ...params}, cb);- } else {- fetchPost("/api/export/exportNotebookMd", {notebook: options.notebook, ...params}, cb);- }+ const msgId = showMessage(window.siyuan.languages.exporting, -1);+ const cb = (response: IWebSocketData) => saveExportFile(response.data.zip, msgId);+ if (options.notebooks?.length) {+ fetchPost("/api/export/exportNotebooksMd", {notebooks: options.notebooks, ...params}, cb);+ } else if (options.id) {+ fetchPost("/api/export/exportMd", {id: options.id, ...params}, cb);+ } else if (options.ids) {+ fetchPost("/api/export/exportMds", {ids: options.ids, ...params}, cb);+ } else {+ fetchPost("/api/export/exportNotebookMd", {notebook: options.notebook, ...params}, cb);+ }};if (encrypted) {confirmDialog("⚠️ " + window.siyuan.languages.export, window.siyuan.languages.encryptedExportRiskTip, exportMarkdown);diff --git a/app/src/search/spread.ts b/app/src/search/spread.tsindex 3821dd24df..05334ea514 100644--- a/app/src/search/spread.ts+++ b/app/src/search/spread.ts@@ -12,12 +12,16 @@ export const openSearch = async (options: {hotkey: string,key?: string,notebookId?: string,+ notebookIds?: string[],searchPath?: string}) => {const localData = window.siyuan.storage[Constants.LOCAL_SEARCHDATA];let hPath = "";let idPath: string[] = [];- if (options.notebookId) {+ if (options.notebookIds?.length) {+ idPath = [...options.notebookIds];+ hPath = options.notebookIds.map((notebookId) => getNotebookName(notebookId)).join(" ");+ } else if (options.notebookId) {hPath = getNotebookName(options.notebookId);idPath.push(options.notebookId);if (options.searchPath && options.searchPath !== "/") {@@ -66,7 +70,12 @@ export const openSearch = async (options: {cloneData.k = selectText;}item.element.setAttribute("data-key", options.hotkey);- if (options.hotkey === Constants.DIALOG_REPLACE) {+ if (options.notebookId || options.notebookIds?.length) {+ cloneData.hasReplace = options.hotkey === Constants.DIALOG_REPLACE;+ cloneData.hPath = hPath;+ cloneData.idPath = [...idPath];+ item.data = updateConfig(searchElement, cloneData, item.data, item.editors.edit);+ } else if (options.hotkey === Constants.DIALOG_REPLACE) {cloneData.hasReplace = true;item.data = updateConfig(searchElement, cloneData, item.data, item.editors.edit);} else if (options.hotkey === Constants.DIALOG_GLOBALSEARCH) {diff --git a/kernel/api/export.go b/kernel/api/export.goindex aa08f50bd5..79a96a9099 100644--- a/kernel/api/export.go+++ b/kernel/api/export.go@@ -436,6 +436,33 @@ func exportNotebookMd(c *gin.Context) {}}+func exportNotebooksMd(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ notebooks := parseExportNotebookIDs(arg)+ if len(notebooks) < 1 {+ ret.Code = -1+ return+ }+ for _, notebook := range notebooks {+ if model.IsEncryptedBox(notebook) {+ ret.Code = -1+ ret.Msg = model.Conf.Language(313)+ return+ }+ }+ zipPath := model.ExportNotebooksMarkdownWithOptions(notebooks, model.ParseExportOptions(arg))+ ret.Data = map[string]any{+ "name": path.Base(zipPath),+ "zip": zipPath,+ }+}+func exportMds(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)@@ -508,6 +535,45 @@ func exportNotebookSY(c *gin.Context) {}}+func exportNotebooksSY(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ notebooks := parseExportNotebookIDs(arg)+ if len(notebooks) < 1 {+ ret.Code = -1+ return+ }+ for _, notebook := range notebooks {+ if model.IsEncryptedBox(notebook) {+ ret.Code = -1+ ret.Msg = model.Conf.Language(313)+ return+ }+ }+ zipPath := model.ExportNotebooksSY(notebooks)+ ret.Data = map[string]any{+ "zip": zipPath,+ }+}++func parseExportNotebookIDs(arg map[string]any) (ret []string) {+ values, ok := arg["notebooks"].([]any)+ if !ok {+ return+ }+ for _, value := range values {+ if notebook, valueOK := value.(string); valueOK && notebook != "" {+ ret = append(ret, notebook)+ }+ }+ return+}+func exportSYs(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/import.go b/kernel/api/import.goindex f17e5bff87..9e2be7797d 100644--- a/kernel/api/import.go+++ b/kernel/api/import.go@@ -87,6 +87,21 @@ func importSYNotebook(c *gin.Context) {return}defer cleanup()+ if ids, bundle, bundleErr := model.ImportSYNotebookBundle(writePath); bundle {+ if bundleErr != nil {+ ret.Code = -1+ ret.Msg = bundleErr.Error()+ return+ }+ boxes, mountErr := mountImportedNotebooks(ids)+ if nil != mountErr {+ ret.Code = -1+ ret.Msg = mountErr.Error()+ return+ }+ ret.Data = map[string]any{"notebooks": boxes}+ return+ }id, err := model.ImportSYNotebook(writePath)if err != nil {@@ -129,6 +144,21 @@ func importSYAuto(c *gin.Context) {return}defer cleanup()+ if ids, bundle, bundleErr := model.ImportSYNotebookBundle(writePath); bundle {+ if bundleErr != nil {+ ret.Code = -1+ ret.Msg = bundleErr.Error()+ return+ }+ boxes, mountErr := mountImportedNotebooks(ids)+ if nil != mountErr {+ ret.Code = -1+ ret.Msg = mountErr.Error()+ return+ }+ ret.Data = map[string]any{"type": "notebooks", "notebooks": boxes}+ return+ }var notebook stringif values := form.Value["notebook"]; len(values) > 0 {@@ -177,6 +207,25 @@ func importSYAuto(c *gin.Context) {util.PushEvent(event)}+func mountImportedNotebooks(ids []string) (ret []*model.Box, err error) {+ for _, id := range ids {+ var existed bool+ existed, err = model.Mount(id)+ if nil != err {+ return+ }+ box := model.Conf.Box(id)+ if nil == box {+ return nil, fmt.Errorf("opened notebook [%s] not found", id)+ }+ ret = append(ret, box)+ event := util.NewCmdResult("createnotebook", 0, util.PushModeBroadcast)+ event.Data = map[string]any{"box": box, "existed": existed}+ util.PushEvent(event)+ }+ return+}+func continueImportSY(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/router.go b/kernel/api/router.goindex d0dc3579a3..762c45915f 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -385,11 +385,13 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/asset/statAsset", model.CheckAuth, model.CheckAdminRole, statAsset)ginServer.Handle("POST", "/api/export/exportNotebookMd", model.CheckAuth, model.CheckAdminRole, exportNotebookMd)+ ginServer.Handle("POST", "/api/export/exportNotebooksMd", model.CheckAuth, model.CheckAdminRole, exportNotebooksMd)ginServer.Handle("POST", "/api/export/exportMds", model.CheckAuth, model.CheckAdminRole, exportMds)ginServer.Handle("POST", "/api/export/exportMd", model.CheckAuth, model.CheckAdminRole, exportMd)ginServer.Handle("POST", "/api/export/exportSYs", model.CheckAuth, model.CheckAdminRole, exportSYs)ginServer.Handle("POST", "/api/export/exportSY", model.CheckAuth, model.CheckAdminRole, exportSY)ginServer.Handle("POST", "/api/export/exportNotebookSY", model.CheckAuth, model.CheckAdminRole, exportNotebookSY)+ ginServer.Handle("POST", "/api/export/exportNotebooksSY", model.CheckAuth, model.CheckAdminRole, exportNotebooksSY)ginServer.Handle("POST", "/api/export/exportMdContent", model.CheckAuth, model.CheckAdminRole, exportMdContent)ginServer.Handle("POST", "/api/export/exportHTML", model.CheckAuth, model.CheckAdminRole, exportHTML)ginServer.Handle("POST", "/api/export/exportPreviewHTML", model.CheckAuth, model.CheckAdminRole, exportPreviewHTML)diff --git a/kernel/model/export.go b/kernel/model/export.goindex 41053e7844..aee24d9fe6 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -450,7 +450,7 @@ func Export2Liandi(id string) (err error) {".md", 3, 1, 1,"#", "#","", "",- false, false, nil, true, false)+ false, false, nil, true, false, nil)result := gulu.Ret.NewResult()request := httpclient.NewCloudRequest30s()request = request.@@ -600,6 +600,25 @@ func ExportNotebookSY(id string) (zipPath string) {return}+// ExportNotebooksSY 将多个笔记本打包到同一个可批量导入的 .sy.zip 中。+func ExportNotebooksSY(ids []string) (zipPath string) {+ return exportNotebooksSYBundle(ids)+}++func exportNotebooksBaseName(boxes []*Box) string {+ if len(boxes) < 1 {+ return "notebooks"+ }+ name := util.FilterFileName(boxes[0].Name)+ if name == "" {+ name = boxes[0].ID+ }+ if len(boxes) > 1 {+ name += "-" + strconv.Itoa(len(boxes))+ }+ return name+}+func ExportSYs(ids []string) (zipPath string) {if len(ids) == 0 {return@@ -2070,7 +2089,7 @@ func ExportStdMarkdown(id string, assetsDestSpace2Underscore, fillCSSVar, adjust".md", Conf.Export.BlockRefMode, Conf.Export.BlockEmbedMode, Conf.Export.FileAnnotationRefMode,Conf.Export.TagOpenMarker, Conf.Export.TagCloseMarker,Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight,- Conf.Export.AddTitle, Conf.Export.InlineMemo, defBlockIDs, true, fillCSSVar)+ Conf.Export.AddTitle, Conf.Export.InlineMemo, defBlockIDs, true, fillCSSVar, nil)return nil}); exportErr != nil {logging.LogErrorf("export std markdown [%s] failed: %s", id, exportErr)@@ -2162,6 +2181,13 @@ func ExportNotebookMarkdownWithOptions(boxID string, opts *ExportOptions) (zipPareturn ExportNotebookMarkdown(boxID)}+// ExportNotebooksMarkdownWithOptions 在一次导出中保留多个笔记本的目录边界和跨笔记本引用。+func ExportNotebooksMarkdownWithOptions(boxIDs []string, opts *ExportOptions) (zipPath string) {+ restore := applyExportOptions(opts)+ defer restore()+ return ExportNotebooksMarkdown(boxIDs)+}+// ParseExportOptions 从 JSON 请求参数中解析导出选项,未传入的字段保持 nil(沿用全局配置)#17031。func ParseExportOptions(arg map[string]any) (opts *ExportOptions) {opts = &ExportOptions{}@@ -2278,6 +2304,90 @@ func ExportNotebookMarkdown(boxID string) (zipPath string) {return}+func ExportNotebooksMarkdown(boxIDs []string) (zipPath string) {+ boxIDs = gulu.Str.RemoveDuplicatedElem(boxIDs)+ if len(boxIDs) < 1 {+ return+ }++ util.PushEndlessProgress(Conf.Language(65))+ defer util.ClearPushProgress(100)++ var boxes []*Box+ trees := map[string]*parse.Tree{}+ defBlockIDs := []string{}+ for _, boxID := range boxIDs {+ box := Conf.Box(boxID)+ if nil == box || IsEncryptedBox(boxID) {+ return+ }+ boxes = append(boxes, box)+ for _, docFile := range box.ListFiles("/") {+ if docFile.path == boxDocPath(boxID) {+ continue+ }+ rootID := util.GetTreeID(docFile.path)+ tree, err := LoadTreeByBlockIDInExactBox(rootID, boxID)+ if nil != err {+ continue+ }+ exportRefTrees(tree, &defBlockIDs, trees)+ }+ }+ if len(trees) < 1 {+ return+ }++ boxPaths := exportNotebookMarkdownPaths(boxes, trees)+ rootIDs := make([]string, 0, len(trees))+ for rootID := range trees {+ rootIDs = append(rootIDs, "/"+rootID+".sy")+ }+ sort.Strings(rootIDs)+ zipPath = exportPandocConvertZip0("", exportNotebooksBaseName(boxes), rootIDs, defBlockIDs, "", "", ".md", boxPaths)+ return+}++func exportNotebookMarkdownPaths(boxes []*Box, trees map[string]*parse.Tree) map[string]string {+ ret := map[string]string{}+ used := map[string]struct{}{}+ addBox := func(boxID, name string) {+ name = util.FilterFileName(name)+ if name == "" {+ name = boxID+ }+ candidate := name+ if _, ok := used[strings.ToLower(candidate)]; ok {+ candidate = name + "-" + boxID+ }+ for index := 2; ; index++ {+ if _, ok := used[strings.ToLower(candidate)]; !ok {+ break+ }+ candidate = name + "-" + boxID + "-" + strconv.Itoa(index)+ }+ used[strings.ToLower(candidate)] = struct{}{}+ ret[boxID] = candidate+ }+ for _, box := range boxes {+ addBox(box.ID, box.Name)+ }+ var relatedBoxIDs []string+ for _, tree := range trees {+ if _, ok := ret[tree.Box]; !ok {+ relatedBoxIDs = append(relatedBoxIDs, tree.Box)+ }+ }+ relatedBoxIDs = gulu.Str.RemoveDuplicatedElem(relatedBoxIDs)+ sort.Strings(relatedBoxIDs)+ for _, boxID := range relatedBoxIDs {+ if box := Conf.Box(boxID); nil != box {+ addBox(boxID, box.Name)+ }+ }+ return ret+}+func yfm(docIAL map[string]string) string {// 导出 Markdown 文件时开头附上一些元数据 https://github.com/siyuan-note/siyuan/issues/6880@@ -2910,7 +3020,7 @@ func ExportMarkdownContent(id string, refMode, embedMode int, addYfm, fillCSSVar".md", refMode, embedMode, Conf.Export.FileAnnotationRefMode,Conf.Export.TagOpenMarker, Conf.Export.TagCloseMarker,Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight,- addTitle, Conf.Export.InlineMemo, nil, true, fillCSSVar)+ addTitle, Conf.Export.InlineMemo, nil, true, fillCSSVar, nil)docIAL := parse.IAL2Map(tree.Root.KramdownIAL)if addYfm {exportedMd = yfm(docIAL) + exportedMd@@ -2923,7 +3033,8 @@ func ExportMarkdownContent(id string, refMode, embedMode int, addYfm, fillCSSVarreturn}-func exportMarkdownContent(rootID, ext string, exportRefMode int, defBlockIDs []string, singleFile bool) (tree *parse.Tree, exportedMd string, isEmpty bool) {+func exportMarkdownContent(rootID, ext string, exportRefMode int, defBlockIDs []string, singleFile bool,+ boxPaths map[string]string) (tree *parse.Tree, exportedMd string, isEmpty bool) {tree, err := LoadTreeByBlockID(rootID)if err != nil {logging.LogErrorf("load tree by block id [%s] failed: %s", rootID, err)@@ -2949,7 +3060,7 @@ func exportMarkdownContent(rootID, ext string, exportRefMode int, defBlockIDs []ext, exportRefMode, Conf.Export.BlockEmbedMode, Conf.Export.FileAnnotationRefMode,Conf.Export.TagOpenMarker, Conf.Export.TagCloseMarker,Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight,- Conf.Export.AddTitle, Conf.Export.InlineMemo, defBlockIDs, singleFile, false)+ Conf.Export.AddTitle, Conf.Export.InlineMemo, defBlockIDs, singleFile, false, boxPaths)docIAL := parse.IAL2Map(tree.Root.KramdownIAL)if Conf.Export.MarkdownYFM {// 导出 Markdown 时在文档头添加 YFM 开关 https://github.com/siyuan-note/siyuan/issues/7727@@ -2961,7 +3072,7 @@ func exportMarkdownContent(rootID, ext string, exportRefMode int, defBlockIDs []func exportMarkdownContent0(id string, tree *parse.Tree, cloudAssetsBase string, assetsDestSpace2Underscore, adjustHeadingLv, imgTag bool,ext string, blockRefMode, blockEmbedMode, fileAnnotationRefMode int,tagOpenMarker, tagCloseMarker string, blockRefTextLeft, blockRefTextRight string,- addTitle, inlineMemo bool, defBlockIDs []string, singleFile, fillCSSVar bool) (ret string) {+ addTitle, inlineMemo bool, defBlockIDs []string, singleFile, fillCSSVar bool, boxPaths map[string]string) (ret string) {tree = exportTree(tree, false, false, false,blockRefMode, blockEmbedMode, fileAnnotationRefMode,tagOpenMarker, tagCloseMarker,@@ -3004,7 +3115,8 @@ func exportMarkdownContent0(id string, tree *parse.Tree, cloudAssetsBase string,})}- currentDocDir := path.Dir(tree.HPath)+ currentDocPath := exportMarkdownHPath(tree.Box, tree.HPath, boxPaths)+ currentDocDir := path.Dir(currentDocPath)currentDocDir = util.FilterFilePath(currentDocDir)var unlinks []*ast.Node@@ -3050,8 +3162,11 @@ func exportMarkdownContent0(id string, tree *parse.Tree, cloudAssetsBase string,if gulu.Str.Contains(defID, defBlockIDs) {var href stringbt := getExportBlockTreeInBox(defID, tree.Box)+ if len(boxPaths) > 0 {+ bt = getExportBlockTree(defID)+ }if nil != bt {- href += bt.HPath + ext+ href = exportMarkdownHPath(bt.BoxID, bt.HPath+ext, boxPaths)if "d" != bt.Type {href += "#" + defID}@@ -3060,21 +3175,7 @@ func exportMarkdownContent0(id string, tree *parse.Tree, cloudAssetsBase string,}}- sameDir := path.Dir(href) == currentDocDir- if strings.HasPrefix(href, "#") {- sameDir = true- }- href = util.FilterFilePath(href)- if !sameDir {- var relErr error- href, relErr = filepath.Rel(currentDocDir, href)- if nil != relErr {- logging.LogWarnf("get relative path from [%s] to [%s] failed: %s", currentDocDir, href, relErr)- }- href = filepath.ToSlash(href)- } else {- href = strings.TrimPrefix(href, currentDocDir+"/")- }+ href = exportMarkdownRelativePath(currentDocDir, href)blockRefLink := &ast.Node{Type: ast.NodeTextMark, TextMarkType: "a", TextMarkTextContent: linkText, TextMarkAHref: href}blockRefLink.KramdownIAL = n.KramdownIALn.InsertBefore(blockRefLink)@@ -3099,6 +3200,27 @@ func exportMarkdownContent0(id string, tree *parse.Tree, cloudAssetsBase string,return}+func exportMarkdownHPath(boxID, hPath string, boxPaths map[string]string) string {+ if boxPath := boxPaths[boxID]; boxPath != "" {+ return path.Join("/", boxPath, strings.TrimPrefix(hPath, "/"))+ }+ return hPath+}++func exportMarkdownRelativePath(currentDocDir, href string) string {+ sameDir := path.Dir(href) == currentDocDir || strings.HasPrefix(href, "#")+ href = util.FilterFilePath(href)+ if sameDir {+ return strings.TrimPrefix(href, currentDocDir+"/")+ }+ relative, err := filepath.Rel(currentDocDir, href)+ if nil != err {+ logging.LogWarnf("get relative path from [%s] to [%s] failed: %s", currentDocDir, href, err)+ return href+ }+ return filepath.ToSlash(relative)+}+func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,blockRefMode, blockEmbedMode, fileAnnotationRefMode int,tagOpenMarker, tagCloseMarker string,@@ -4095,6 +4217,11 @@ func processFileAnnotationRef(refID string, n *ast.Node, fileAnnotationRefMode i}func exportPandocConvertZip(boxID, baseFolderName string, docPaths, defBlockIDs []string, pandocFrom, pandocTo, ext string) (zipPath string) {+ return exportPandocConvertZip0(boxID, baseFolderName, docPaths, defBlockIDs, pandocFrom, pandocTo, ext, nil)+}++func exportPandocConvertZip0(boxID, baseFolderName string, docPaths, defBlockIDs []string, pandocFrom, pandocTo, ext string,+ boxPaths map[string]string) (zipPath string) {defer util.ClearPushProgress(100)dir, name := path.Split(baseFolderName)@@ -4147,17 +4274,17 @@ func exportPandocConvertZip(boxID, baseFolderName string, docPaths, defBlockIDsluteEngine.SetExportNormalizeTaskListMarker(true)for i, p := range docPaths {rootID := util.GetTreeID(p)- tree, md, isEmpty := exportMarkdownContent(rootID, ext, exportRefMode, defBlockIDs, false)+ tree, md, isEmpty := exportMarkdownContent(rootID, ext, exportRefMode, defBlockIDs, false, boxPaths)if nil == tree {continue}- hPath := tree.HPath+ hPath := exportMarkdownHPath(tree.Box, tree.HPath, boxPaths)dir, name = path.Split(hPath)dir = util.FilterFilePath(dir) // 导出文档时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/4590name = util.FilterFileName(name)hPath = path.Join(dir, name)p = hPath + ext- if 1 == len(docPaths) {+ if 1 == len(docPaths) && len(boxPaths) < 1 {// 如果仅导出单个文档则使用文档标题作为文件名,不使用父路径 https://github.com/siyuan-note/siyuan/issues/13635#issuecomment-3794560233p = name + ext}diff --git a/kernel/model/export_notebooks_test.go b/kernel/model/export_notebooks_test.gonew file mode 100644index 0000000000..21c3b9a6a2--- /dev/null+++ b/kernel/model/export_notebooks_test.go@@ -0,0 +1,220 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "archive/zip"+ "bytes"+ "io"+ "path/filepath"+ "strings"+ "testing"++ "github.com/88250/gulu"+ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestExportNotebookMarkdownPathsKeepsDuplicateNamesSeparate(t *testing.T) {+ boxes := []*Box{+ {ID: "20260814000000-box0001", Name: "Notes"},+ {ID: "20260814000000-box0002", Name: "Notes"},+ {ID: "20260814000000-box0003", Name: "notes"},+ }+ paths := exportNotebookMarkdownPaths(boxes, nil)+ if paths[boxes[0].ID] != "Notes" {+ t.Fatalf("unexpected first notebook path: %q", paths[boxes[0].ID])+ }+ expectedSecond := "Notes-" + boxes[1].ID+ if paths[boxes[1].ID] != expectedSecond {+ t.Fatalf("unexpected second notebook path: %q", paths[boxes[1].ID])+ }+ expectedThird := "notes-" + boxes[2].ID+ if paths[boxes[2].ID] != expectedThird {+ t.Fatalf("unexpected third notebook path: %q", paths[boxes[2].ID])+ }+}++func TestExportMarkdownHPathIncludesNotebook(t *testing.T) {+ boxPaths := map[string]string{+ "20260814000000-box0001": "Notebook A",+ "20260814000000-box0002": "Notebook B",+ }+ source := exportMarkdownHPath("20260814000000-box0001", "/Source", boxPaths)+ target := exportMarkdownHPath("20260814000000-box0002", "/Folder/Target.md", boxPaths)+ if source != "/Notebook A/Source" {+ t.Fatalf("unexpected source path: %q", source)+ }+ if target != "/Notebook B/Folder/Target.md" {+ t.Fatalf("unexpected target path: %q", target)+ }+ reference := exportMarkdownRelativePath(filepath.ToSlash(filepath.Dir(source)), target+"#20260814000000-block01")+ if reference != "../Notebook B/Folder/Target.md#20260814000000-block01" {+ t.Fatalf("unexpected cross-notebook reference: %q", reference)+ }+}++func TestExportNotebooksSYKeepsCrossNotebookReferences(t *testing.T) {+ const (+ sourceBoxID = "20260814000100-box0001"+ targetBoxID = "20260814000101-box0002"+ sourceDocID = "20260814000102-doc0001"+ targetDocID = "20260814000103-doc0002"+ sourceBlockID = "20260814000104-block01"+ targetBlockID = "20260814000105-block02"+ )+ setupExportRelatedTest(t, sourceBoxID, targetBoxID)+ for _, boxID := range []string{sourceBoxID, targetBoxID} {+ box := &Box{ID: boxID}+ boxConf := box.GetConf()+ boxConf.Name = "Notebook"+ if err := box.SaveConf(boxConf); nil != err {+ t.Fatal(err)+ }+ }++ for _, boxID := range []string{sourceBoxID, targetBoxID} {+ boxTree := treenode.NewTree(boxID, boxDocPath(boxID), "/"+boxID, boxID)+ boxTree.Root.SetIALAttr(DocHiddenAttr, "true")+ writeExportRelatedTestTree(t, boxTree)+ }+ sourceTree := treenode.NewTree(sourceBoxID, "/"+sourceDocID+".sy", "/Source", "Source")+ sourceBlock := treenode.NewParagraph(sourceBlockID)+ sourceBlock.AppendChild(&ast.Node{+ Type: ast.NodeTextMark,+ TextMarkType: "block-ref",+ TextMarkBlockRefID: targetBlockID,+ TextMarkBlockRefSubtype: "d",+ TextMarkTextContent: "Target",+ })+ sourceTree.Root.AppendChild(sourceBlock)+ targetTree := treenode.NewTree(targetBoxID, "/"+targetDocID+".sy", "/Target", "Target")+ targetTree.Root.AppendChild(treenode.NewParagraph(targetBlockID))+ writeExportRelatedTestTree(t, sourceTree)+ writeExportRelatedTestTree(t, targetTree)++ exportPath := ExportNotebooksSY([]string{sourceBoxID, targetBoxID})+ syArchive := openExportArchive(t, exportPath)+ syRoot := "Notebook-2"+ sourceArchivePath := filepath.ToSlash(filepath.Join(syRoot, "notebooks", "Notebook.sy.zip"))+ targetArchivePath := filepath.ToSlash(filepath.Join(syRoot, "notebooks", "Notebook-"+targetBoxID+".sy.zip"))+ for _, expected := range []string{+ filepath.ToSlash(filepath.Join(syRoot, syNotebookBundleManifestPath)),+ sourceArchivePath,+ targetArchivePath,+ } {+ if findArchiveFile(syArchive.File, expected) == nil {+ t.Fatalf("missing SiYuan archive entry: %s", expected)+ }+ }+ manifest := &syNotebookBundleManifest{}+ manifestPath := filepath.ToSlash(filepath.Join(syRoot, syNotebookBundleManifestPath))+ if err := gulu.JSON.UnmarshalJSON([]byte(readArchiveFile(t, syArchive, manifestPath)), manifest); nil != err {+ t.Fatal(err)+ }+ if manifest.Spec != syNotebookBundleSpec || len(manifest.Notebooks) != 2 {+ t.Fatalf("unexpected notebook bundle manifest: %+v", manifest)+ }+ sourceArchive := openNestedArchive(t, syArchive, sourceArchivePath)+ sourceSYPath := filepath.ToSlash(filepath.Join("Notebook", sourceDocID+".sy"))+ if sourceSY := readNestedArchiveFile(t, sourceArchive, sourceSYPath); !strings.Contains(sourceSY, targetBlockID) {+ t.Fatalf("cross-notebook reference %q not found in exported source document", targetBlockID)+ }+ if findArchiveFile(sourceArchive.File, filepath.ToSlash(filepath.Join("Notebook", targetDocID+".sy"))) != nil {+ t.Fatal("target notebook document was duplicated into the source notebook archive")+ }+ targetArchive := openNestedArchive(t, syArchive, targetArchivePath)+ if findArchiveFile(targetArchive.File, filepath.ToSlash(filepath.Join("Notebook", targetDocID+".sy"))) == nil {+ t.Fatal("target document is missing from its notebook archive")+ }+}++func openExportArchive(t *testing.T, exportPath string) *zip.ReadCloser {+ t.Helper()+ if exportPath == "" {+ t.Fatal("export returned an empty archive path")+ }+ absPath := filepath.Join(util.TempDir, filepath.FromSlash(strings.TrimPrefix(exportPath, "/")))+ archive, err := zip.OpenReader(absPath)+ if err != nil {+ t.Fatalf("open exported archive failed: %s", err)+ }+ t.Cleanup(func() {+ _ = archive.Close()+ })+ return archive+}++func readArchiveFile(t *testing.T, archive *zip.ReadCloser, name string) string {+ t.Helper()+ return readZipFile(t, findArchiveFile(archive.File, name), name)+}++func openNestedArchive(t *testing.T, archive *zip.ReadCloser, name string) *zip.Reader {+ t.Helper()+ file := findArchiveFile(archive.File, name)+ if nil == file {+ t.Fatalf("archive entry not found: %s", name)+ }+ reader, err := file.Open()+ if nil != err {+ t.Fatal(err)+ }+ data, err := io.ReadAll(reader)+ _ = reader.Close()+ if nil != err {+ t.Fatal(err)+ }+ nested, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))+ if nil != err {+ t.Fatal(err)+ }+ return nested+}++func readNestedArchiveFile(t *testing.T, archive *zip.Reader, name string) string {+ t.Helper()+ return readZipFile(t, findArchiveFile(archive.File, name), name)+}++func findArchiveFile(files []*zip.File, name string) *zip.File {+ for _, file := range files {+ if file.Name == name {+ return file+ }+ }+ return nil+}++func readZipFile(t *testing.T, file *zip.File, name string) string {+ t.Helper()+ if nil != file {+ reader, err := file.Open()+ if err != nil {+ t.Fatal(err)+ }+ defer reader.Close()+ data, err := io.ReadAll(reader)+ if err != nil {+ t.Fatal(err)+ }+ return string(data)+ }+ t.Fatalf("archive entry not found: %s", name)+ return ""+}diff --git a/kernel/model/import.go b/kernel/model/import.goindex 0db01c4f38..653ee9aa10 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -158,6 +158,11 @@ func isSYNotebookExport(hasBoxConf, hasBoxDocMeta bool) bool {}func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (createdBoxID string, err error) {+ return importSY0(zipPath, boxID, toPath, createNotebook, autoDetect, nil, false)+}++func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, sharedBlockIDs map[string]string,+ precreatedBox bool) (createdBoxID string, err error) {util.PushEndlessProgress(Conf.Language(73))defer util.ClearPushProgress(100)@@ -271,9 +276,11 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (cif importedBoxConf != nil && importedBoxConf.Name != "" {name = importedBoxConf.Name}- boxID, err = CreateBox(util.RemoveInvalid(name))- if err != nil {- return "", err+ if !precreatedBox {+ boxID, err = CreateBox(util.RemoveInvalid(name))+ if err != nil {+ return "", err+ }}createdBoxID = boxIDdefer func() {@@ -311,7 +318,10 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (ctoPath = normalizeBoxDocTarget(boxID, toPath)luteEngine := util.NewLute()- blockIDs := map[string]string{}+ blockIDs := sharedBlockIDs+ if nil == blockIDs {+ blockIDs = map[string]string{}+ }trees := map[string]*parse.Tree{}importedBoxDoc := falsecontainsFlashcardAttrs := false@@ -344,7 +354,10 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c// 新 ID 保留时间部分,仅修改随机值,避免时间变化导致更新时间早于创建时间// Keep original creation time when importing .sy.zip https://github.com/siyuan-note/siyuan/issues/9923- newNodeID := util.TimeFromID(n.ID) + "-" + util.RandString(7)+ newNodeID := blockIDs[n.ID]+ if "" == newNodeID {+ newNodeID = util.TimeFromID(n.ID) + "-" + util.RandString(7)+ }if createNotebook && oldRootID == importedBoxDocID && n.ID == importedBoxDocID {newNodeID = boxID}diff --git a/kernel/model/notebook_bundle.go b/kernel/model/notebook_bundle.gonew file mode 100644index 0000000000..3e3af82763--- /dev/null+++ b/kernel/model/notebook_bundle.go@@ -0,0 +1,378 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "archive/zip"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "net/url"+ "os"+ "path"+ "path/filepath"+ "strings"++ "github.com/88250/gulu"+ "github.com/88250/lute/ast"+ "github.com/siyuan-note/dataparser"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const (+ syNotebookBundleSpec = 1+ syNotebookBundleManifestPath = ".siyuan/notebooks.json"+)++type syNotebookBundleManifest struct {+ Spec int `json:"spec"`+ Notebooks []syNotebookBundleEntry `json:"notebooks"`+}++type syNotebookBundleEntry struct {+ Archive string `json:"archive"`+}++type inspectedSYNotebook struct {+ archivePath string+ name string+ boxDocID string+ blockIDs []string+}++func exportNotebooksSYBundle(ids []string) (zipPath string) {+ ids = gulu.Str.RemoveDuplicatedElem(ids)+ if len(ids) < 1 {+ return+ }++ var boxes []*Box+ for _, id := range ids {+ box := Conf.Box(id)+ if nil == box || IsEncryptedBox(id) {+ return+ }+ boxes = append(boxes, box)+ }++ originalIncludeRelatedDocs := Conf.Export.IncludeRelatedDocs+ Conf.Export.IncludeRelatedDocs = false+ defer func() {+ Conf.Export.IncludeRelatedDocs = originalIncludeRelatedDocs+ }()++ workDir := filepath.Join(util.TempDir, "export", "notebooks-"+gulu.Rand.String(7))+ if err := os.MkdirAll(workDir, 0755); nil != err {+ logging.LogErrorf("create notebook bundle temp folder failed: %s", err)+ return+ }+ defer os.RemoveAll(workDir)++ boxPaths := exportNotebookMarkdownPaths(boxes, nil)+ manifest := &syNotebookBundleManifest{Spec: syNotebookBundleSpec}+ innerArchives := map[string]string{}+ for _, box := range boxes {+ innerURI := exportBoxSYZip(box.ID)+ innerPath, err := exportedFilePath(innerURI)+ if nil != err {+ logging.LogErrorf("resolve exported notebook archive failed: %s", err)+ return ""+ }+ archiveName := boxPaths[box.ID] + ".sy.zip"+ archivePath := path.Join("notebooks", archiveName)+ stagedPath := filepath.Join(workDir, archiveName)+ if err = filelock.Copy(innerPath, stagedPath); nil != err {+ logging.LogErrorf("stage exported notebook archive failed: %s", err)+ return ""+ }+ _ = os.Remove(innerPath)+ manifest.Notebooks = append(manifest.Notebooks, syNotebookBundleEntry{Archive: archivePath})+ innerArchives[archivePath] = stagedPath+ }++ baseFolderName := exportNotebooksBaseName(boxes)+ manifestData, err := gulu.JSON.MarshalIndentJSON(manifest, "", " ")+ if nil != err {+ logging.LogErrorf("marshal notebook bundle manifest failed: %s", err)+ return+ }+ manifestPath := filepath.Join(workDir, "notebooks.json")+ if err = os.WriteFile(manifestPath, manifestData, 0644); nil != err {+ logging.LogErrorf("write notebook bundle manifest failed: %s", err)+ return+ }++ partialPath := filepath.Join(workDir, "notebooks.sy.zip.partial")+ archive, err := gulu.Zip.Create(partialPath)+ if nil != err {+ logging.LogErrorf("create notebook bundle failed: %s", err)+ return+ }+ closed := false+ defer func() {+ if !closed {+ _ = archive.Close()+ }+ }()+ callback := func(filename string) {+ util.PushEndlessProgress(Conf.language(65) + " " + fmt.Sprintf(Conf.language(253), filename))+ }+ if err = archive.AddEntry(path.Join(baseFolderName, syNotebookBundleManifestPath), manifestPath, callback); nil != err {+ logging.LogErrorf("add notebook bundle manifest failed: %s", err)+ return ""+ }+ for archivePath, innerPath := range innerArchives {+ if err = archive.AddEntry(path.Join(baseFolderName, archivePath), innerPath, callback); nil != err {+ logging.LogErrorf("add notebook archive [%s] failed: %s", archivePath, err)+ return ""+ }+ }+ if err = archive.Close(); nil != err {+ logging.LogErrorf("close notebook bundle failed: %s", err)+ return ""+ }+ closed = true++ finalPath := filepath.Join(util.TempDir, "export", baseFolderName+".sy.zip")+ if err = os.Remove(finalPath); nil != err && !os.IsNotExist(err) {+ logging.LogErrorf("remove previous notebook bundle failed: %s", err)+ return ""+ }+ if err = os.Rename(partialPath, finalPath); nil != err {+ logging.LogErrorf("publish notebook bundle failed: %s", err)+ return ""+ }+ return "/export/" + url.PathEscape(filepath.Base(finalPath))+}++func exportedFilePath(exportPath string) (ret string, err error) {+ encoded, ok := strings.CutPrefix(exportPath, "/export/")+ if !ok || encoded == "" {+ return "", errors.New("invalid export path")+ }+ decoded, err := url.PathUnescape(encoded)+ if nil != err {+ return "", err+ }+ ret = filepath.Join(util.TempDir, "export", filepath.FromSlash(decoded))+ if !gulu.File.IsSubPath(filepath.Join(util.TempDir, "export"), ret) {+ return "", errors.New("export path is outside export directory")+ }+ return+}++// ImportSYNotebookBundle 导入批量笔记本包。普通 .sy.zip 返回 bundle=false,由原有导入流程继续处理。+func ImportSYNotebookBundle(zipPath string) (boxIDs []string, bundle bool, err error) {+ archive, openErr := zip.OpenReader(zipPath)+ if nil != openErr {+ err = openErr+ return+ }+ var manifestData []byte+ rootName := ""+ manifestSuffix := "/" + syNotebookBundleManifestPath+ for _, file := range archive.File {+ if !strings.HasSuffix(file.Name, manifestSuffix) {+ continue+ }+ candidateRoot := strings.TrimSuffix(file.Name, manifestSuffix)+ if candidateRoot == "" || strings.Contains(candidateRoot, "/") || rootName != "" {+ _ = archive.Close()+ return nil, true, errors.New(Conf.Language(199))+ }+ reader, readErr := file.Open()+ if nil != readErr {+ _ = archive.Close()+ return nil, true, readErr+ }+ manifestData, readErr = io.ReadAll(reader)+ _ = reader.Close()+ if nil != readErr {+ _ = archive.Close()+ return nil, true, readErr+ }+ rootName = candidateRoot+ }+ _ = archive.Close()+ if rootName == "" {+ return nil, false, nil+ }+ bundle = true+ manifest := &syNotebookBundleManifest{}+ if err = gulu.JSON.UnmarshalJSON(manifestData, manifest); nil != err || manifest.Spec != syNotebookBundleSpec || len(manifest.Notebooks) < 1 {+ err = errors.New(Conf.Language(199))+ return+ }++ unzipPath := filepath.Join(filepath.Dir(zipPath), strings.TrimSuffix(filepath.Base(zipPath), filepath.Ext(zipPath))+"-bundle-"+gulu.Rand.String(7))+ if err = gulu.Zip.Unzip(zipPath, unzipPath); nil != err {+ return+ }+ defer os.RemoveAll(unzipPath)+ rootPath := filepath.Join(unzipPath, filepath.FromSlash(rootName))+ if !gulu.File.IsDir(rootPath) {+ err = errors.New(Conf.Language(199))+ return+ }++ var notebooks []*inspectedSYNotebook+ seenArchives := map[string]struct{}{}+ for _, item := range manifest.Notebooks {+ archivePath := path.Clean("/" + item.Archive)+ archivePath = strings.TrimPrefix(archivePath, "/")+ if !strings.HasPrefix(archivePath, "notebooks/") || !strings.HasSuffix(strings.ToLower(archivePath), ".sy.zip") {+ err = errors.New(Conf.Language(199))+ return+ }+ if _, ok := seenArchives[archivePath]; ok {+ err = errors.New(Conf.Language(199))+ return+ }+ seenArchives[archivePath] = struct{}{}+ innerPath := filepath.Join(rootPath, filepath.FromSlash(archivePath))+ if !gulu.File.IsSubPath(rootPath, innerPath) || !filelock.IsExist(innerPath) {+ err = errors.New(Conf.Language(199))+ return+ }+ var inspected *inspectedSYNotebook+ if inspected, err = inspectSYNotebookArchive(innerPath); nil != err {+ return+ }+ notebooks = append(notebooks, inspected)+ }++ sharedBlockIDs := map[string]string{}+ blockOwners := map[string]int{}+ for index, notebook := range notebooks {+ for _, oldID := range notebook.blockIDs {+ if owner, ok := blockOwners[oldID]; ok && owner != index {+ err = errors.New(Conf.Language(199))+ return+ }+ blockOwners[oldID] = index+ if sharedBlockIDs[oldID] == "" {+ sharedBlockIDs[oldID] = util.TimeFromID(oldID) + "-" + util.RandString(7)+ }+ }+ }++ cleanupCreated := true+ defer func() {+ if !cleanupCreated {+ return+ }+ for _, boxID := range boxIDs {+ treenode.RemoveBlockTreesByBoxID(boxID)+ sql.DeleteBoxQueue(boxID)+ _ = filelock.Remove(filepath.Join(util.DataDir, boxID))+ }+ }()+ for _, notebook := range notebooks {+ var boxID string+ boxID, err = CreateBox(util.RemoveInvalid(notebook.name))+ if nil != err {+ return+ }+ boxIDs = append(boxIDs, boxID)+ if notebook.boxDocID != "" {+ sharedBlockIDs[notebook.boxDocID] = boxID+ }+ }+ for index, notebook := range notebooks {+ if _, err = importSY0(notebook.archivePath, boxIDs[index], "/", true, false, sharedBlockIDs, true); nil != err {+ return+ }+ }+ cleanupCreated = false+ return+}++func inspectSYNotebookArchive(zipPath string) (ret *inspectedSYNotebook, err error) {+ unzipPath := filepath.Join(filepath.Dir(zipPath), strings.TrimSuffix(filepath.Base(zipPath), filepath.Ext(zipPath))+"-inspect-"+gulu.Rand.String(7))+ if err = gulu.Zip.Unzip(zipPath, unzipPath); nil != err {+ return+ }+ defer os.RemoveAll(unzipPath)++ entries, readErr := os.ReadDir(unzipPath)+ if nil != readErr || len(entries) != 1 || !entries[0].IsDir() {+ return nil, errors.New(Conf.Language(199))+ }+ rootPath := filepath.Join(unzipPath, entries[0].Name())+ ret = &inspectedSYNotebook{archivePath: zipPath, name: entries[0].Name()}+ confPath := filepath.Join(rootPath, ".siyuan", "conf.json")+ if filelock.IsExist(confPath) {+ boxConf := conf.NewBoxConf()+ confData, readConfErr := filelock.ReadFile(confPath)+ if nil != readConfErr || gulu.JSON.UnmarshalJSON(confData, boxConf) != nil {+ return nil, errors.New(Conf.Language(199))+ }+ if boxConf.Name != "" {+ ret.name = boxConf.Name+ }+ }+ boxDocPath := filepath.Join(rootPath, ".siyuan", boxDocMetaName)+ if filelock.IsExist(boxDocPath) {+ meta := &boxDocMeta{}+ metaData, readMetaErr := filelock.ReadFile(boxDocPath)+ if nil != readMetaErr || gulu.JSON.UnmarshalJSON(metaData, meta) != nil || meta.Spec != boxDocMetaSpec || !ast.IsNodeIDPattern(meta.BoxDocID) {+ return nil, errors.New(Conf.Language(199))+ }+ ret.boxDocID = meta.BoxDocID+ }++ luteEngine := util.NewLute()+ seenBlockIDs := map[string]struct{}{}+ syCount := 0+ err = filelock.Walk(rootPath, func(currentPath string, entry fs.DirEntry, walkErr error) error {+ if nil != walkErr {+ return walkErr+ }+ if nil == entry || entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sy") {+ return nil+ }+ syCount+++ data, readTreeErr := filelock.ReadFile(currentPath)+ if nil != readTreeErr {+ return readTreeErr+ }+ tree, _, parseErr := dataparser.ParseJSON(data, luteEngine.ParseOptions)+ if nil != parseErr {+ return parseErr+ }+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && node.ID != "" {+ seenBlockIDs[node.ID] = struct{}{}+ }+ return ast.WalkContinue+ })+ return nil+ })+ if nil != err || syCount < 1 {+ return nil, errors.New(Conf.Language(199))+ }+ for blockID := range seenBlockIDs {+ ret.blockIDs = append(ret.blockIDs, blockID)+ }+ return+}