Skip to content

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

:bug: Isolate encrypted notebook data paths https://github.com/siyuan-note/siyuan/issues/18034

Daniel9bbabe012c12
diff --git a/app/src/block/popover.ts b/app/src/block/popover.ts
index c45ea1667d..3c26d0cda5 100644
--- a/app/src/block/popover.ts
+++ b/app/src/block/popover.ts
@@ -2,7 +2,7 @@ import {BlockPanel} from "./Panel";
import {hasClosestByAttribute, hasClosestByClassName,} from "../protyle/util/hasClosest";
import {fetchPost, fetchSyncPost} from "../util/fetch";
import {hideTooltip, showTooltip} from "../dialog/tooltip";
-import {isLocalPath, parseSiYuanUriInfo} from "../util/pathName";
+import {isEncryptedBox, isLocalPath, parseSiYuanUriInfo} from "../util/pathName";
import type {App} from "../index";
import {Constants} from "../constants";
import {getCellText} from "../protyle/render/av/cell";
@@ -15,6 +15,11 @@ import {Tab} from "../layout/Tab";
/// #endif
let popoverTargetElement: HTMLElement;
+
+const getPopoverNotebookId = () => {
+ const notebookId = popoverTargetElement?.closest("[data-notebook-id]")?.getAttribute("data-notebook-id") || "";
+ return isEncryptedBox(notebookId) ? notebookId : "";
+};
// 异步获取信息后再显示 tooltip,鼠标已移走时需中断请求 https://github.com/siyuan-note/siyuan/issues/14823
let tooltipAbortController: AbortController | null = null;
export const initBlockPopover = (app: App) => {
@@ -503,11 +508,15 @@ export const showPopover = async (app: App, showRef = false) => {
}
let refDefs: IRefDefs[] = [];
let originalRefBlockIDs: IObject;
+ const notebookId = getPopoverNotebookId();
const dataId = popoverTargetElement.getAttribute("data-id");
if (dataId) {
// backlink/util/hint 上的弹层
if (showRef) {
- const postResponse = await fetchSyncPost("/api/block/getRefIDs", {id: dataId});
+ const postResponse = await fetchSyncPost("/api/block/getRefIDs", {
+ id: dataId,
+ notebook: notebookId
+ });
refDefs = postResponse.data.refDefs;
originalRefBlockIDs = postResponse.data.originalRefBlockIDs;
} else {
@@ -522,6 +531,7 @@ export const showPopover = async (app: App, showRef = false) => {
} else if (popoverTargetElement.getAttribute("data-type")?.indexOf("virtual-block-ref") > -1) {
const postResponse = await fetchSyncPost("/api/block/getBlockDefIDsByRefText", {
anchor: popoverTargetElement.textContent,
+ notebook: notebookId
});
refDefs = postResponse.data.refDefs;
} else if (popoverTargetElement.getAttribute("data-type")?.split(" ").includes("a")) {
@@ -569,7 +579,10 @@ export const showPopover = async (app: App, showRef = false) => {
targetId = popoverTargetElement.parentElement.getAttribute("data-node-id");
}
if (url) {
- const postResponse = await fetchSyncPost(url, {id: targetId});
+ const postResponse = await fetchSyncPost(url, {
+ id: targetId,
+ notebook: notebookId
+ });
refDefs = postResponse.data.refDefs;
originalRefBlockIDs = postResponse.data.originalRefBlockIDs;
}
diff --git a/app/src/boot/globalEvent/command/panel.ts b/app/src/boot/globalEvent/command/panel.ts
index 799be5586e..f7dac2a00e 100644
--- a/app/src/boot/globalEvent/command/panel.ts
+++ b/app/src/boot/globalEvent/command/panel.ts
@@ -450,7 +450,8 @@ export const execByCommand = async (options: {
paths: [protyle.path],
range,
flashcard: false,
- rootIDs: [protyle.block.rootID]
+ rootIDs: [protyle.block.rootID],
+ sourceNotebookIds: [protyle.notebookId]
});
} else if (nodeElement && range && protyle.element.contains(range.startContainer)) {
let selectElements = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));
@@ -462,11 +463,14 @@ export const execByCommand = async (options: {
hintMoveBlock(toPath[0], selectElements, protyle);
},
flashcard: false,
- rootIDs: [protyle.block.rootID]
+ rootIDs: [protyle.block.rootID],
+ sourceNotebookIds: [protyle.notebookId]
});
}
} else {
const paths = getTopPaths(fileLiElements);
+ const sourceNotebookIds = fileLiElements.map((item) =>
+ item.getAttribute("data-notebook-id") || item.closest("ul[data-url]")?.getAttribute("data-url") || "");
const rootIDs: string[] = [];
fileLiElements.forEach(item => {
rootIDs.push(item.getAttribute("data-node-id"));
@@ -477,7 +481,8 @@ export const execByCommand = async (options: {
},
paths,
rootIDs,
- flashcard: false
+ flashcard: false,
+ sourceNotebookIds
});
}
break;
diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.ts
index 21a6979954..af2abc826f 100644
--- a/app/src/config/tabs/accessTab.ts
+++ b/app/src/config/tabs/accessTab.ts
@@ -626,9 +626,9 @@ const openChangeMasterPasswordDialog = (onChanged?: () => void) => {
if (response.code === 0) {
showMessage(window.siyuan.languages.changeMasterPasswordSuccessTip);
dialog.destroy();
+ onChanged?.();
} else {
showMessage(response.msg, 6000, "error");
- onChanged?.();
}
});
});
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index 4f77767387..221220a751 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -4,7 +4,7 @@ import {Model} from "../Model";
import {setPanelFocus} from "../util";
import {getDockByType} from "../tabUtil";
import {Constants} from "../../constants";
-import {getDocDisplayName, pathPosix, setNoteBook} from "../../util/pathName";
+import {getDocDisplayName, isMoveTargetAllowed, pathPosix, setNoteBook} from "../../util/pathName";
import {newFileInTree} from "../../util/newFile";
import {initFileMenu, initNavigationMenu, sortMenu} from "../../menus/navigation";
import {MenuItem} from "../../menus/Menu";
@@ -100,6 +100,11 @@ export class Files extends Model {
if (target.classList.contains("b3-list-item__icon")) {
event.preventDefault();
event.stopPropagation();
+ const notebookElement = target.closest("li[data-encrypted=true]");
+ if (notebookElement) {
+ openEncryptedNotebook(this.app, notebookElement.getAttribute("data-url"), notebookElement.querySelector(".b3-list-item__text").textContent);
+ break;
+ }
const rect = target.getBoundingClientRect();
openEmojiPanel(target.parentElement.getAttribute("data-url"), "notebook", {
x: rect.left,
@@ -768,6 +773,13 @@ export class Files extends Model {
}
});
if (newElement.classList.contains("dragover")) {
+ const sourceNotebookIds = selectFileElements.map((item) =>
+ item.getAttribute("data-notebook-id") || item.closest("ul[data-url]")?.getAttribute("data-url") || "");
+ if (!isMoveTargetAllowed(sourceNotebookIds, toURL)) {
+ showMessage(window.siyuan.languages._kernel[313]);
+ newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
+ return;
+ }
fetchPost("/api/filetree/moveDocs", {
toNotebook: toURL,
fromPaths,
@@ -801,6 +813,13 @@ export class Files extends Model {
const toDir = pathPosix().dirname(toPath);
const newElementClassList = newElement.getAttribute("class");
if (fromPaths.length > 0) {
+ const sourceNotebookIds = selectFileElements.map((item) =>
+ item.getAttribute("data-notebook-id") || item.closest("ul[data-url]")?.getAttribute("data-url") || "");
+ if (!isMoveTargetAllowed(sourceNotebookIds, toURL)) {
+ showMessage(window.siyuan.languages._kernel[313]);
+ newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
+ return;
+ }
await fetchSyncPost("/api/filetree/moveDocs", {
toNotebook: toURL,
fromPaths,
diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.ts
index 036c779362..fd1375f091 100644
--- a/app/src/menus/commonMenuItem.ts
+++ b/app/src/menus/commonMenuItem.ts
@@ -1009,7 +1009,7 @@ export const renameMenu = (options: {
}).element;
};
-export const movePathToMenu = (paths: string[]) => {
+export const movePathToMenu = (paths: string[], sourceNotebookIds: string[] = []) => {
return new MenuItem({
id: "move",
label: window.siyuan.languages.move,
@@ -1027,6 +1027,7 @@ export const movePathToMenu = (paths: string[]) => {
paths,
flashcard: false,
rootIDs,
+ sourceNotebookIds,
});
}
}).element;
diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.ts
index 002e9a7b1a..153a5b5a8c 100644
--- a/app/src/menus/navigation.ts
+++ b/app/src/menus/navigation.ts
@@ -89,9 +89,9 @@ const initMultiMenu = (selectItemElements: NodeListOf<Element>, app: App) => {
}).element);
}
- window.siyuan.menus.menu.append(movePathToMenu(getTopPaths(
- Array.from(selectItemElements)
- )));
+ const selectedItems = Array.from(selectItemElements);
+ window.siyuan.menus.menu.append(movePathToMenu(getTopPaths(selectedItems), selectedItems.map((item) =>
+ item.closest("ul[data-url]")?.getAttribute("data-url") || "")));
if (blockIDs.length > 0) {
window.siyuan.menus.menu.append(new MenuItem({
@@ -576,9 +576,9 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
}
}])
}).element);
- window.siyuan.menus.menu.append(movePathToMenu(getTopPaths(
- Array.from(fileElement.querySelectorAll(".b3-list-item--focus"))
- )));
+ const selectedItems = Array.from(fileElement.querySelectorAll(".b3-list-item--focus"));
+ window.siyuan.menus.menu.append(movePathToMenu(getTopPaths(selectedItems), selectedItems.map((item) =>
+ item.closest("ul[data-url]")?.getAttribute("data-url") || "")));
window.siyuan.menus.menu.append(new MenuItem({
id: "addToDatabase",
label: window.siyuan.languages.addToDatabase,
diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.ts
index 08d6b3a40d..cb482186a3 100644
--- a/app/src/mobile/dock/MobileFiles.ts
+++ b/app/src/mobile/dock/MobileFiles.ts
@@ -89,6 +89,13 @@ export class MobileFiles extends Model {
let target = event.target as HTMLElement;
while (target && !target.isEqualNode(this.actionsElement)) {
if (target.classList.contains("b3-list-item__icon")) {
+ const notebookElement = target.closest("li[data-encrypted=true]");
+ if (notebookElement) {
+ openEncryptedNotebook(this.app, notebookElement.getAttribute("data-url"), notebookElement.querySelector(".b3-list-item__text").textContent);
+ event.preventDefault();
+ event.stopPropagation();
+ break;
+ }
target = target.previousElementSibling as HTMLElement;
}
const type = target.getAttribute("data-type");
diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.ts
index e730ca5d3a..393c1c283a 100644
--- a/app/src/protyle/hint/extend.ts
+++ b/app/src/protyle/hint/extend.ts
@@ -489,6 +489,9 @@ export const hintRef = (key: string, protyle: IProtyle, source: THintSource): IH
refParam.notebook = protyle.notebookId;
}
}
+ if (protyle.lite && isEncryptedBox(protyle.notebookId)) {
+ refParam.notebook = protyle.notebookId;
+ }
fetchPost("/api/search/searchRefBlock", refParam, (response) => {
const dataList: IHintData[] = [];
if (response.data.newDoc) {
diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.ts
index 8fa71e1212..1ada651cbf 100644
--- a/app/src/protyle/index.ts
+++ b/app/src/protyle/index.ts
@@ -111,6 +111,11 @@ export class Protyle {
this.protyle.element.innerHTML = "";
this.protyle.element.classList.add("protyle");
+ if (this.protyle.notebookId) {
+ this.protyle.element.setAttribute("data-notebook-id", this.protyle.notebookId);
+ } else {
+ this.protyle.element.removeAttribute("data-notebook-id");
+ }
// 启用 RTL 时给 .protyle 元素添加 .rtl 类名,方便主题开发者判断 RTL 方向
if (window.siyuan.config.editor.rtl) {
this.protyle.element.classList.add("rtl");
@@ -271,6 +276,11 @@ export class Protyle {
if (this.protyle.path === data.data.fromPath) {
this.protyle.path = data.data.newPath;
this.protyle.notebookId = data.data.toNotebook;
+ if (this.protyle.notebookId) {
+ this.protyle.element.setAttribute("data-notebook-id", this.protyle.notebookId);
+ } else {
+ this.protyle.element.removeAttribute("data-notebook-id");
+ }
}
break;
case "closeBox":
diff --git a/app/src/protyle/render/blockRender.ts b/app/src/protyle/render/blockRender.ts
index 7b752ccfe9..4201ee994b 100644
--- a/app/src/protyle/render/blockRender.ts
+++ b/app/src/protyle/render/blockRender.ts
@@ -65,7 +65,8 @@ ${content}
embedBlockID: item.getAttribute("data-node-id"),
includeIDs,
headingMode: ["0", "1", "2"].includes(item.getAttribute("custom-heading-mode")) ? parseInt(item.getAttribute("custom-heading-mode")) : window.siyuan.config.editor.headingEmbedMode,
- breadcrumb
+ breadcrumb,
+ notebook: isEncryptedBox(protyle.notebookId) ? protyle.notebookId : ""
}, (response) => {
renderEmbed(response.data.blocks || [], protyle, item, top, undefined, onEmbedRender);
});
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index 0d37b2415e..48e72747fc 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -3946,9 +3946,13 @@ export class WYSIWYG {
if (virtualRefElement && range.toString() === "") {
event.stopPropagation();
event.preventDefault();
- fetchPost("/api/block/getBlockDefIDsByRefText", {
+ const virtualRefParam: { anchor: string, notebook?: string } = {
anchor: virtualRefElement.textContent,
- }, (response) => {
+ };
+ if (isEncryptedBox(protyle.notebookId)) {
+ virtualRefParam.notebook = protyle.notebookId;
+ }
+ fetchPost("/api/block/getBlockDefIDsByRefText", virtualRefParam, (response) => {
checkFold(response.data.refDefs[0].refID, (zoomIn) => {
mobileBlur = true;
activeBlur();
diff --git a/app/src/util/mount.ts b/app/src/util/mount.ts
index 8a3daf0c51..31d4e250ff 100644
--- a/app/src/util/mount.ts
+++ b/app/src/util/mount.ts
@@ -208,11 +208,20 @@ export const newNotebook = () => {
/// #endif
};
+let newEncryptedNotebookPending = false;
+
export const newEncryptedNotebook = () => {
+ if (window.siyuan.dialogs.some((item) => item.element.getAttribute("data-key") === "newEncryptedNotebook")) {
+ return;
+ }
+ if (newEncryptedNotebookPending) {
+ return;
+ }
+ newEncryptedNotebookPending = true;
// 先检查加密功能是否已启用;未启用则提示去设置页启用
fetchPost("/api/notebook/getEncryptedNotebookStatus", {}, (response) => {
if (response.data.state !== "Enabled") {
- showMessage(window.siyuan.languages.encryptedNotebookTip, 6000);
+ showMessage(window.siyuan.languages.enableEncryptedNotebook, 6000);
return;
}
const dialog = new Dialog({
@@ -230,6 +239,7 @@ export const newEncryptedNotebook = () => {
</div>`,
width: isMobile() ? "92vw" : "520px"
});
+ dialog.element.setAttribute("data-key", "newEncryptedNotebook");
const btnsElement = dialog.element.querySelectorAll<HTMLButtonElement>(".b3-button");
const inputs = dialog.element.querySelectorAll("input");
dialog.bindInput(inputs[0], () => {
@@ -260,10 +270,16 @@ export const newEncryptedNotebook = () => {
btnsElement[1].disabled = false;
}
});
+ }).finally(() => {
+ newEncryptedNotebookPending = false;
});
};
export const openEncryptedNotebook = (app: App, notebookId: string, name: string) => {
+ const dialogKey = "encryptedNotebook-" + notebookId;
+ if (window.siyuan.dialogs.some((item) => item.element.getAttribute("data-key") === dialogKey)) {
+ return;
+ }
const dialog = new Dialog({
title: window.siyuan.languages.unlockEncryptedNotebook.replace("${x}", name),
content: `<div class="b3-dialog__content">
@@ -277,6 +293,7 @@ export const openEncryptedNotebook = (app: App, notebookId: string, name: string
</div>`,
width: isMobile() ? "92vw" : "520px"
});
+ dialog.element.setAttribute("data-key", dialogKey);
const btnsElement = dialog.element.querySelectorAll<HTMLButtonElement>(".b3-button");
const inputElement = dialog.element.querySelector("input");
dialog.bindInput(inputElement, () => {
diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.ts
index 911aab1332..c3e48fbd8c 100644
--- a/app/src/util/pathName.ts
+++ b/app/src/util/pathName.ts
@@ -209,6 +209,18 @@ export const getTopPaths = (liElements: Element[]) => {
return fromPaths;
};
+export const isMoveTargetAllowed = (sourceNotebookIds: string[] = [], targetNotebookId: string) => {
+ const sourceIds = Array.from(new Set(sourceNotebookIds.filter(Boolean)));
+ if (sourceIds.length === 0) {
+ return true;
+ }
+ const encryptedSourceIds = sourceIds.filter(isEncryptedBox);
+ if (encryptedSourceIds.length > 0) {
+ return encryptedSourceIds.length === sourceIds.length && sourceIds.length === 1 && sourceIds[0] === targetNotebookId;
+ }
+ return !isEncryptedBox(targetNotebookId);
+};
+
export const moveToPath = (fromPaths: string[], toNotebook: string, toPath: string) => {
fetchPost("/api/filetree/moveDocs", {
toNotebook,
@@ -224,6 +236,7 @@ export const movePathTo = (options: {
title?: string,
flashcard: boolean
rootIDs?: string[],
+ sourceNotebookIds?: string[],
}) => {
const exitDialog = window.siyuan.dialogs.find((item) => {
if (item.element.querySelector("#foldList")) {
@@ -273,7 +286,7 @@ export const movePathTo = (options: {
setNoteBook((notebooks) => {
let html = "";
notebooks.forEach((item) => {
- if (!item.closed) {
+ if (!item.closed && isMoveTargetAllowed(options.sourceNotebookIds, item.id)) {
let countHTML = "";
if (options.flashcard) {
countHTML = `<span class="counter counter--right b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.flashcardNewCard}">${item.newFlashcardCount}</span>
diff --git a/kernel/api/block.go b/kernel/api/block.go
index 1e002414e4..e685113d3a 100644
--- a/kernel/api/block.go
+++ b/kernel/api/block.go
@@ -809,7 +809,8 @@ func getRefIDsByFileAnnotationID(c *gin.Context) {
}
id := arg["id"].(string)
- refIDs := model.GetBlockRefIDsByFileAnnotationID(id)
+ boxID, _ := arg["notebook"].(string)
+ refIDs := model.GetBlockRefIDsByFileAnnotationIDInBox(id, boxID)
if model.IsReadOnlyRoleContext(c) {
refIDs = model.FilterRefIDsByPublishAccess(c, model.GetPublishAccess(), refIDs)
}
@@ -836,7 +837,8 @@ func getBlockDefIDsByRefText(c *gin.Context) {
}
anchor := arg["anchor"].(string)
- ids := model.GetBlockDefIDsByRefText(anchor)
+ boxID, _ := arg["notebook"].(string)
+ ids := model.GetBlockDefIDsByRefTextInBox(anchor, boxID)
ids = filterBlockIDsByPublishAccess(c, ids, "")
var retRefDefs []model.RefDefs
for _, id := range ids {
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index ba9fab5548..387213a91e 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -1033,7 +1033,7 @@ func getDocCreateSavePath(c *gin.Context) {
}
}
- docCreateSavePath, err := model.RenderGoTemplate(docCreateSavePathTpl)
+ docCreateSavePath, err := model.RenderGoTemplateInBox(docCreateSavePathTpl, docCreateSaveBox)
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
@@ -1088,7 +1088,7 @@ func getRefCreateSavePath(c *gin.Context) {
}
}
- refCreateSavePath, err := model.RenderGoTemplate(refCreateSavePathTpl)
+ refCreateSavePath, err := model.RenderGoTemplateInBox(refCreateSavePathTpl, refCreateSaveBox)
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
@@ -1124,7 +1124,7 @@ func getShorthandSavePath(c *gin.Context) {
}
}
- shorthandSavePath, err := model.RenderGoTemplate(shorthandSavePathTpl)
+ shorthandSavePath, err := model.RenderGoTemplateInBox(shorthandSavePathTpl, shorthandSaveBox)
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index 290507a49e..6001c0bb49 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -183,6 +183,10 @@ func html2BlockDOM(c *gin.Context) {
logging.LogWarnf("skip copying asset [%s] due to sensitive path", localPath)
return ast.WalkContinue
}
+ if encryptedBoxID := model.EncryptedRawPathBoxID(localPath); encryptedBoxID != "" {
+ logging.LogWarnf("skip copying asset [%s] from encrypted notebook [%s]", localPath, encryptedBoxID)
+ return ast.WalkContinue
+ }
name := filepath.Base(localPath)
ext := filepath.Ext(name)
diff --git a/kernel/api/search.go b/kernel/api/search.go
index c07d359864..5ac4eeda6d 100644
--- a/kernel/api/search.go
+++ b/kernel/api/search.go
@@ -337,6 +337,10 @@ func getEmbedBlock(c *gin.Context) {
if nil != breadcrumbArg {
breadcrumb = breadcrumbArg.(bool)
}
+ notebook := ""
+ if notebookArg, ok := arg["notebook"].(string); ok && model.IsEncryptedBox(notebookArg) {
+ notebook = notebookArg
+ }
isReadOnlyRole := model.IsReadOnlyRoleContext(c)
var blocks []*model.EmbedBlock
@@ -350,7 +354,11 @@ func getEmbedBlock(c *gin.Context) {
blocks = model.GetEmbedBlockForPublish(embedBlockID, includeIDs, headingMode, breadcrumb)
blocks = model.FilterEmbedBlocksByPublishAccess(c, publishAccess, blocks)
} else {
- blocks = model.GetEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb)
+ if notebook == "" {
+ blocks = model.GetEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb)
+ } else {
+ blocks = model.GetEmbedBlockInBox(embedBlockID, includeIDs, headingMode, breadcrumb, notebook)
+ }
}
ret.Data = map[string]any{
"blocks": blocks,
diff --git a/kernel/mcp/tools/box_lease.go b/kernel/mcp/tools/box_lease.go
index a5755787f1..a92249aa8e 100644
--- a/kernel/mcp/tools/box_lease.go
+++ b/kernel/mcp/tools/box_lease.go
@@ -42,6 +42,7 @@ var encryptedBoxScopedToolNames = map[string]struct{}{
"ref": {},
"repo": {},
"search": {},
+ "sql": {},
"template": {},
}
diff --git a/kernel/mcp/tools/sql.go b/kernel/mcp/tools/sql.go
index 61ca6bbfd9..2eec6beaae 100644
--- a/kernel/mcp/tools/sql.go
+++ b/kernel/mcp/tools/sql.go
@@ -29,8 +29,9 @@ var SQLTool = &Tool{
InputSchema: ToolSchema{
Type: "object",
Properties: map[string]Property{
- "action": {Type: "string", Description: "Operation", Enum: []string{"query"}},
- "stmt": {Type: "string", Description: "SQL SELECT statement"},
+ "action": {Type: "string", Description: "Operation", Enum: []string{"query"}},
+ "stmt": {Type: "string", Description: "SQL SELECT statement"},
+ "notebook": {Type: "string", Description: "Optional notebook ID used to query an encrypted notebook"},
},
Required: []string{"action", "stmt"},
},
@@ -72,11 +73,25 @@ func sqlQuery(args map[string]any) (CallToolResult, error) {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "invalid SQL: " + err.Error()}}, IsError: true}, nil
}
- if err := sql.CheckReadonlyStatement(stmt); err != nil {
+ boxID, _ := args["notebook"].(string)
+ if boxID == "" {
+ if err := sql.CheckReadonlyStatement(stmt); err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "readonly SQL required: " + err.Error()}}, IsError: true}, nil
+ }
+ } else if err := sql.CheckReadonlyStatementInBox(stmt, boxID); err != nil {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "readonly SQL required: " + err.Error()}}, IsError: true}, nil
}
- rows, err := sql.Query(stmt, 100)
+ var rows []map[string]any
+ var err error
+ if boxID == "" {
+ rows, err = sql.Query(stmt, 100)
+ } else {
+ rows, err = sql.QueryNoLimitInBox(stmt, boxID)
+ if len(rows) > 100 {
+ rows = rows[:100]
+ }
+ }
if err != nil {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "query failed: " + err.Error()}}, IsError: true}, nil
}
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index cc116750b3..729bfacbb4 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -3449,12 +3449,16 @@ func GetBlockAttributeViewKeys(nodeID string) (ret []*BlockAttributeViewKeys) {
blockIDs := treenode.GetMirrorAttrViewBlockIDs(avID)
if 1 > len(blockIDs) {
// 老数据兼容处理
- avBts := treenode.GetBlockTreesByType("av")
+ boxID := ""
+ if tree, _ := LoadTreeByBlockID(nodeID); tree != nil {
+ boxID = tree.Box
+ }
+ avBts := treenode.GetBlockTreesByTypeInBox("av", boxID)
for _, avBt := range avBts {
if nil == avBt {
continue
}
- tree, _ := LoadTreeByBlockID(avBt.ID)
+ tree, _ := LoadTreeByBlockIDInExactBox(avBt.ID, avBt.BoxID)
if nil == tree {
continue
}
diff --git a/kernel/model/attribute_view_new_item.go b/kernel/model/attribute_view_new_item.go
index 6417261dc5..46fc739de0 100644
--- a/kernel/model/attribute_view_new_item.go
+++ b/kernel/model/attribute_view_new_item.go
@@ -322,7 +322,18 @@ func attributeViewItemDocumentTemplate(attrView *av.AttributeView, saveMode stri
}
func resolveAttributeViewNewItemTemplate(blockID string, itemTemplate *av.NewItemTemplate, createdAt time.Time) (*NewItemTemplatePreview, error) {
- primary, err := RenderGoTemplateAt(itemTemplate.PrimaryKeyTemplate, createdAt)
+ boxID := ""
+ if blockTree := treenode.GetBlockTree(blockID); blockTree != nil {
+ boxID = blockTree.BoxID
+ } else {
+ for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ if blockTree := treenode.GetBlockTreeInBox(blockID, encBoxID); blockTree != nil {
+ boxID = encBoxID
+ break
+ }
+ }
+ }
+ primary, err := RenderGoTemplateAtInBox(itemTemplate.PrimaryKeyTemplate, createdAt, boxID)
if nil != err {
return nil, err
}
@@ -336,6 +347,14 @@ func resolveAttributeViewNewItemTemplate(blockID string, itemTemplate *av.NewIte
func resolveAttributeViewItemDocument(blockID, primary string, itemTemplate *av.NewItemTemplate, createdAt time.Time) (*NewItemTemplatePreview, error) {
blockTree := treenode.GetBlockTree(blockID)
+ if blockTree == nil {
+ for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ if candidate := treenode.GetBlockTreeInBox(blockID, encBoxID); candidate != nil {
+ blockTree = candidate
+ break
+ }
+ }
+ }
if nil == blockTree {
return nil, ErrBlockNotFound
}
@@ -347,7 +366,7 @@ func resolveAttributeViewItemDocument(blockID, primary string, itemTemplate *av.
if nil != err {
return nil, err
}
- renderedPath, err := RenderGoTemplateAt(pathTemplate, createdAt)
+ renderedPath, err := RenderGoTemplateAtInBox(pathTemplate, createdAt, boxID)
if nil != err {
return nil, err
}
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.go
index 87b010accf..202eed1bb2 100644
--- a/kernel/model/backlink.go
+++ b/kernel/model/backlink.go
@@ -373,7 +373,7 @@ func buildBacklink(refID string, refTree *parse.Tree, originalRefBlockIDs map[st
}
// 反链面板中显示块引用计数 Display reference counts in the backlink panel https://github.com/siyuan-note/siyuan/issues/13618
- fillBlockRefCount(renderNodes)
+ fillBlockRefCount(renderNodes, refTree.Box)
dom := renderVisibleBlockDOMByNodes(renderNodes, luteEngine)
var blockPaths []*BlockPath
diff --git a/kernel/model/block.go b/kernel/model/block.go
index 9632115537..7774d902e7 100644
--- a/kernel/model/block.go
+++ b/kernel/model/block.go
@@ -903,7 +903,7 @@ func GetHeadingLevelTransaction(id string, level int) (transaction *Transaction,
ccH := c.ChildrenByType(ast.NodeHeading)
childrenHeadings = append(childrenHeadings, ccH...)
}
- fillBlockRefCount(childrenHeadings)
+ fillBlockRefCount(childrenHeadings, tree.Box)
transaction = &Transaction{}
if treenode.IsSelfFolded(node) {
@@ -1439,7 +1439,11 @@ func getBlock(id string, tree *parse.Tree) (ret *Block, err error) {
func getEmbeddedBlock(trees map[string]*parse.Tree, sqlBlock *sql.Block, headingMode int, breadcrumb bool) (block *Block, blockPaths []*BlockPath) {
tree, _ := trees[sqlBlock.RootID]
if nil == tree {
- tree, _ = LoadTreeByBlockID(sqlBlock.RootID)
+ if IsEncryptedBox(sqlBlock.Box) {
+ tree, _ = LoadTreeByBlockIDInExactBox(sqlBlock.RootID, sqlBlock.Box)
+ } else {
+ tree, _ = LoadTreeByBlockID(sqlBlock.RootID)
+ }
}
if nil == tree {
return
@@ -1470,7 +1474,12 @@ func getEmbeddedBlock(trees map[string]*parse.Tree, sqlBlock *sql.Block, heading
nodes = append(nodes, def)
}
- b := treenode.GetBlockTree(def.ID)
+ var b *treenode.BlockTree
+ if IsEncryptedBox(sqlBlock.Box) {
+ b = treenode.GetBlockTreeInBox(def.ID, sqlBlock.Box)
+ } else {
+ b = treenode.GetBlockTree(def.ID)
+ }
if nil == b {
for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
if encBT := treenode.GetBlockTreeInBox(def.ID, encBoxID); nil != encBT {
@@ -1484,7 +1493,7 @@ func getEmbeddedBlock(trees map[string]*parse.Tree, sqlBlock *sql.Block, heading
}
// 嵌入块查询结果中显示块引用计数 https://github.com/siyuan-note/siyuan/issues/7191
- fillBlockRefCount(nodes)
+ fillBlockRefCount(nodes, b.BoxID)
luteEngine := NewLute()
luteEngine.RenderOptions.ProtyleContenteditable = true
diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.go
index fc2ad703c2..791182c291 100644
--- a/kernel/model/blockinfo.go
+++ b/kernel/model/blockinfo.go
@@ -457,8 +457,20 @@ func GetBlockRefIDsByFileAnnotationID(id string) []string {
return sql.QueryRefIDsByAnnotationID(id)
}
+func GetBlockRefIDsByFileAnnotationIDInBox(id, boxID string) []string {
+ return sql.QueryRefIDsByAnnotationIDInBox(id, boxID)
+}
+
func GetBlockDefIDsByRefText(refText string) (ret []string) {
- ret = sql.QueryBlockDefIDsByRefText(refText)
+ return GetBlockDefIDsByRefTextInBox(refText, "")
+}
+
+func GetBlockDefIDsByRefTextInBox(refText, boxID string) (ret []string) {
+ if boxID == "" {
+ ret = sql.QueryBlockDefIDsByRefText(refText)
+ } else {
+ ret = sql.QueryBlockDefIDsByRefTextInBox(refText, boxID)
+ }
sort.Sort(sort.Reverse(sort.StringSlice(ret)))
if 1 > len(ret) {
ret = []string{}
diff --git a/kernel/model/box.go b/kernel/model/box.go
index c0f8e8040e..38203412fe 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -183,6 +183,7 @@ func ListNotebooks() (ret []*Box, err error) {
markRuntimeEncryptedBox(id)
}
if boxConf.Encrypted && !missingEncryptedIdentity {
+ repairEncryptedBoxStateFromDEK(id)
if metadataErr := revealBoxMetadataIfUnlocked(id, boxConf); metadataErr != nil {
logging.LogErrorf("decrypt encrypted notebook metadata [%s] failed: %s", id, metadataErr)
}
diff --git a/kernel/model/box_conf_crypto.go b/kernel/model/box_conf_crypto.go
index 88134f016c..c5016853d3 100644
--- a/kernel/model/box_conf_crypto.go
+++ b/kernel/model/box_conf_crypto.go
@@ -91,6 +91,9 @@ func prepareBoxConfForSave(boxID string, boxConf *conf.BoxConf) (*conf.BoxConf,
}
persisted := *boxConf
persisted.BoxCrypt = DeepCopyBoxEncryption(boxConf.BoxCrypt)
+ if persisted.Encrypted {
+ forgetRuntimeNormalBox(boxID)
+ }
if !persisted.Encrypted {
if IsEncryptedBox(boxID) {
return nil, errors.New("encrypted notebook cannot be saved as a normal notebook")
@@ -107,7 +110,7 @@ func prepareBoxConfForSave(boxID string, boxConf *conf.BoxConf) (*conf.BoxConf,
if dek, ok := cachedDEKCopy(boxID); ok {
defer zeroAndClear(dek)
- if err := encryptBoxMetadata(boxID, &persisted, dek); err != nil {
+ if err := reuseBoxMetadataIfUnchanged(boxID, &persisted, dek); err != nil {
return nil, err
}
} else if len(persisted.BoxCrypt.Metadata) == 0 {
@@ -127,6 +130,23 @@ func prepareBoxConfForSave(boxID string, boxConf *conf.BoxConf) (*conf.BoxConf,
return &persisted, nil
}
+func reuseBoxMetadataIfUnchanged(boxID string, boxConf *conf.BoxConf, dek []byte) error {
+ existing, err := readRawBoxConf(boxID)
+ if err != nil {
+ return err
+ }
+ if existing != nil && existing.Encrypted && existing.BoxCrypt != nil && len(existing.BoxCrypt.Metadata) > 0 {
+ decrypted := &conf.BoxConf{BoxCrypt: DeepCopyBoxEncryption(existing.BoxCrypt)}
+ if err = decryptBoxMetadata(boxID, decrypted, dek); err == nil &&
+ filterBoxIcon(decrypted.Icon) == filterBoxIcon(boxConf.Icon) &&
+ decrypted.Sort == boxConf.Sort && decrypted.SortMode == boxConf.SortMode {
+ boxConf.BoxCrypt.Metadata = append([]byte(nil), existing.BoxCrypt.Metadata...)
+ return nil
+ }
+ }
+ return encryptBoxMetadata(boxID, boxConf, dek)
+}
+
func clearBoxMetadata(boxConf *conf.BoxConf) {
boxConf.Icon = ""
boxConf.Sort = 0
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 002dbb73d8..301aa1834f 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -61,6 +61,9 @@ var errEncryptedNotebookPayloadFound = errors.New("encrypted notebook payload fo
// value 为确认身份时的 DataDir,防止测试或切换工作空间时复用其他工作空间的运行时状态。
var runtimeEncryptedBoxes sync.Map // map[string]string
+// runtimeNormalBoxes 缓存已确认的普通笔记本,减少普通笔记本高频访问时的文件系统探测。
+var runtimeNormalBoxes sync.Map // map[string]string
+
// IsEncryptedNotebookData 判断数据是否以当前文档或资源密文标识开头。
func IsEncryptedNotebookData(data []byte) bool {
return util.IsCiphertext(data) || bytes.HasPrefix(data, encryptedAssetMagic)
@@ -68,6 +71,7 @@ func IsEncryptedNotebookData(data []byte) bool {
func markRuntimeEncryptedBox(boxID string) {
if ast.IsNodeIDPattern(boxID) {
+ forgetRuntimeNormalBox(boxID)
runtimeEncryptedBoxes.Store(boxID, filepath.Clean(util.DataDir))
}
}
@@ -77,6 +81,7 @@ func forgetRuntimeEncryptedBox(boxID string) {
if ok && dataDir == filepath.Clean(util.DataDir) {
runtimeEncryptedBoxes.Delete(boxID)
}
+ forgetRuntimeNormalBox(boxID)
}
func isRuntimeEncryptedBox(boxID string) bool {
@@ -84,12 +89,33 @@ func isRuntimeEncryptedBox(boxID string) bool {
return ok && dataDir == filepath.Clean(util.DataDir)
}
+func markRuntimeNormalBox(boxID string) {
+ if ast.IsNodeIDPattern(boxID) {
+ runtimeNormalBoxes.Store(boxID, filepath.Clean(util.DataDir))
+ }
+}
+
+func forgetRuntimeNormalBox(boxID string) {
+ dataDir, ok := runtimeNormalBoxes.Load(boxID)
+ if ok && dataDir == filepath.Clean(util.DataDir) {
+ runtimeNormalBoxes.Delete(boxID)
+ }
+}
+
+func isRuntimeNormalBox(boxID string) bool {
+ dataDir, ok := runtimeNormalBoxes.Load(boxID)
+ return ok && dataDir == filepath.Clean(util.DataDir)
+}
+
// hasEncryptedNotebookPayload 在密钥身份文件缺失或损坏时检查磁盘密文标识,防止自动修复为普通笔记本。
func hasEncryptedNotebookPayload(boxID string) (bool, error) {
if !ast.IsNodeIDPattern(boxID) {
return false, errors.New("invalid notebook ID")
}
- boxDir := filepath.Join(util.DataDir, boxID)
+ return hasEncryptedNotebookPayloadAtPath(filepath.Join(util.DataDir, boxID))
+}
+
+func hasEncryptedNotebookPayloadAtPath(boxDir string) (bool, error) {
if !filelock.IsExist(boxDir) {
return false, nil
}
@@ -142,6 +168,8 @@ var errMasterPasswordMigrationPending = errors.New("master password migration is
// 避免 ChangeMasterPassword 枚举与 CreateEncryptedBox 并发导致新笔记本用旧 KEK 但 verifier 已切换的不可恢复状态。
var notebookCryptoMu sync.Mutex
+var masterPasswordMigrationMu sync.Mutex
+
// boxLifecycleLocks 为每个 box 提供一个 RWMutex,协调锁定操作与在途解密请求。
// 在途解密请求持读锁,LockBox 持写锁,确保锁定后不会有新的解密输出。
var boxLifecycleLocks = sync.Map{} // map[string]*sync.RWMutex
@@ -483,6 +511,12 @@ func masterPasswordMigrationPath() string {
}
func writeMasterPasswordMigration(m *masterPasswordMigration) error {
+ masterPasswordMigrationMu.Lock()
+ defer masterPasswordMigrationMu.Unlock()
+ return writeMasterPasswordMigrationUnlocked(m)
+}
+
+func writeMasterPasswordMigrationUnlocked(m *masterPasswordMigration) error {
p := masterPasswordMigrationPath()
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
return fmt.Errorf("mkdir master password migration dir failed: %w", err)
@@ -495,6 +529,12 @@ func writeMasterPasswordMigration(m *masterPasswordMigration) error {
}
func readMasterPasswordMigration() (*masterPasswordMigration, error) {
+ masterPasswordMigrationMu.Lock()
+ defer masterPasswordMigrationMu.Unlock()
+ return readMasterPasswordMigrationUnlocked()
+}
+
+func readMasterPasswordMigrationUnlocked() (*masterPasswordMigration, error) {
p := masterPasswordMigrationPath()
if !filelock.IsExist(p) {
return nil, nil
@@ -511,12 +551,51 @@ func readMasterPasswordMigration() (*masterPasswordMigration, error) {
}
func removeMasterPasswordMigration() {
+ masterPasswordMigrationMu.Lock()
+ defer masterPasswordMigrationMu.Unlock()
+ removeMasterPasswordMigrationUnlocked()
+}
+
+func removeMasterPasswordMigrationUnlocked() {
p := masterPasswordMigrationPath()
if err := filelock.Remove(p); err != nil && !os.IsNotExist(err) {
logging.LogErrorf("remove master password migration failed: %s", err)
}
}
+func removeMasterPasswordMigrationBox(boxID string) {
+ if boxID == "" {
+ return
+ }
+ masterPasswordMigrationMu.Lock()
+ defer masterPasswordMigrationMu.Unlock()
+
+ mig, err := readMasterPasswordMigrationUnlocked()
+ if err != nil || mig == nil {
+ return
+ }
+ remaining := make([]migrationBoxEntry, 0, len(mig.Boxes))
+ found := false
+ for _, entry := range mig.Boxes {
+ if entry.BoxID == boxID {
+ found = true
+ continue
+ }
+ remaining = append(remaining, entry)
+ }
+ if !found {
+ return
+ }
+ if len(remaining) == 0 {
+ removeMasterPasswordMigrationUnlocked()
+ return
+ }
+ mig.Boxes = remaining
+ if err = writeMasterPasswordMigrationUnlocked(mig); err != nil {
+ logging.LogErrorf("remove notebook [%s] from master password migration failed: %s", boxID, err)
+ }
+}
+
// MasterPasswordMigrationStatus 返回是否存在待完成的改密迁移及受影响的笔记本。
func MasterPasswordMigrationStatus() (pending bool, boxIDs []string) {
mig, err := readMasterPasswordMigration()
@@ -540,6 +619,29 @@ func recoverMasterPasswordMigration() {
if mig == nil {
return // 无待恢复的迁移
}
+ remaining := make([]migrationBoxEntry, 0, len(mig.Boxes))
+ for _, entry := range mig.Boxes {
+ if !ast.IsNodeIDPattern(entry.BoxID) {
+ logging.LogWarnf("drop invalid notebook [%s] from master password migration", entry.BoxID)
+ continue
+ }
+ if !filelock.IsExist(filepath.Join(util.DataDir, entry.BoxID)) {
+ logging.LogInfof("drop deleted notebook [%s] from master password migration", entry.BoxID)
+ continue
+ }
+ remaining = append(remaining, entry)
+ }
+ if len(remaining) != len(mig.Boxes) {
+ mig.Boxes = remaining
+ if len(mig.Boxes) == 0 {
+ removeMasterPasswordMigration()
+ return
+ }
+ if writeErr := writeMasterPasswordMigration(mig); writeErr != nil {
+ logging.LogErrorf("update master password migration after notebook removal failed: %s", writeErr)
+ return
+ }
+ }
Conf.m.RLock()
currentVerifier := Conf.NotebookCrypto.KEKVerifier
@@ -817,7 +919,11 @@ func EnableEncryptedNotebook(password string) error {
hasBackup := filelock.IsExist(dataCryptoBackupPath())
if hasEncrypted || hasHistory || hasBackup {
// 现存笔记本、已删除笔记本历史或全局备份均表示已有密钥域,必须恢复并认证,不能生成新 MasterSalt。
- if _, restoreErr := tryRestoreNotebookCryptoFromBackupLocked(password); restoreErr != nil {
+ kek, restoreErr := tryRestoreNotebookCryptoFromBackupLocked(password)
+ if kek != nil {
+ zeroAndClear(kek)
+ }
+ if restoreErr != nil {
if strings.Contains(restoreErr.Error(), Conf.Language(311)) {
return errors.New(Conf.Language(311))
}
@@ -1645,6 +1751,9 @@ func IsEncryptedBox(boxID string) bool {
if isRuntimeEncryptedBox(boxID) {
return true
}
+ if isRuntimeNormalBox(boxID) {
+ return false
+ }
normalConf := false
boxConfPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")
@@ -1667,25 +1776,30 @@ func IsEncryptedBox(boxID string) bool {
backup, err := readNotebookCryptBackup(boxID)
if err != nil {
logging.LogWarnf("failed to read notebook crypt backup for [%s]: %s", boxID, err)
+ forgetRuntimeNormalBox(boxID)
markRuntimeEncryptedBox(boxID)
return true
}
if backup != nil && len(backup.WrappedDEK) > 0 {
+ forgetRuntimeNormalBox(boxID)
markRuntimeEncryptedBox(boxID)
return true
}
}
if normalConf {
+ markRuntimeNormalBox(boxID)
return false
}
found, err := hasEncryptedNotebookPayload(boxID)
if err != nil {
logging.LogWarnf("failed to inspect notebook encryption identity for [%s]: %s", boxID, err)
+ forgetRuntimeNormalBox(boxID)
markRuntimeEncryptedBox(boxID)
return true
}
if found {
+ forgetRuntimeNormalBox(boxID)
markRuntimeEncryptedBox(boxID)
}
return found
@@ -1893,6 +2007,7 @@ func GetDEKIfUnlocked(boxID string) ([]byte, error) {
if !IsEncryptedBox(boxID) {
return nil, nil
}
+ repairEncryptedBoxStateFromDEK(boxID)
if !isBoxUnlockedForAccess(boxID) {
return nil, errors.New("encrypted notebook is locked, please unlock it first")
}
@@ -1910,7 +2025,17 @@ func GetDEKIfUnlocked(boxID string) ([]byte, error) {
// HoldBoxReadLock 获取 box 读锁,防止 LockBox 在持锁期间清除缓存/临时文件。
// 调用方完成解密输出后必须调 ReleaseBoxReadLock。
func HoldBoxReadLock(boxID string) {
+ if !IsEncryptedBox(boxID) {
+ acquireBoxReadLock(boxID)
+ return
+ }
+ lifecycle := getEncryptedBoxLifecycle(boxID)
+ lifecycle.lock.Lock()
+ for lifecycle.state == EncryptedBoxStateUnlocking || lifecycle.state == EncryptedBoxStateLocking {
+ lifecycle.condition.Wait()
+ }
acquireBoxReadLock(boxID)
+ lifecycle.lock.Unlock()
}
// ReleaseBoxReadLock 释放 HoldBoxReadLock 获取的 box 读锁。
@@ -2434,6 +2559,7 @@ func cleanupFailedEncryptedBox(boxID string) {
treenode.RemoveEncryptedBlockTreeDBFile(boxID)
removeEncryptedBoxLifecycle(boxID)
forgetRuntimeEncryptedBox(boxID)
+ removeMasterPasswordMigrationBox(boxID)
if err := filelock.Remove(boxDir); err != nil {
logging.LogErrorf("cleanup failed encrypted box [%s]: %s", boxID, err)
}
@@ -2445,6 +2571,7 @@ func finalizeSyncedEncryptedBoxRemoval(boxID string) {
return
}
LockBox(boxID)
+ removeMasterPasswordMigrationBox(boxID)
removeEncryptedBoxLifecycle(boxID)
forgetRuntimeEncryptedBox(boxID)
invalidateEncryptedPublishAccessCache()
diff --git a/kernel/model/crypto_lifecycle.go b/kernel/model/crypto_lifecycle.go
index af3da96ed9..c7cdcb88fc 100644
--- a/kernel/model/crypto_lifecycle.go
+++ b/kernel/model/crypto_lifecycle.go
@@ -83,13 +83,20 @@ func removeEncryptedBoxLifecycle(boxID string) {
// GetEncryptedBoxState 返回加密笔记本当前的显式生命周期状态。
func GetEncryptedBoxState(boxID string) EncryptedBoxState {
+ lifecycle := getEncryptedBoxLifecycle(boxID)
+ lifecycle.lock.Lock()
+ defer lifecycle.lock.Unlock()
+ return lifecycle.state
+}
+
+func repairEncryptedBoxStateFromDEK(boxID string) {
lifecycle := getEncryptedBoxLifecycle(boxID)
lifecycle.lock.Lock()
defer lifecycle.lock.Unlock()
if lifecycle.state == EncryptedBoxStateLocked && IsBoxUnlocked(boxID) {
lifecycle.state = EncryptedBoxStateUnlocked
+ lifecycle.condition.Broadcast()
}
- return lifecycle.state
}
// NotebookCryptoLifecycleState 返回全局加密功能状态。
@@ -139,6 +146,7 @@ func AcquireEncryptedBoxOperation(boxID string) error {
defer lifecycle.lock.Unlock()
if lifecycle.state == EncryptedBoxStateLocked && IsBoxUnlocked(boxID) {
lifecycle.state = EncryptedBoxStateUnlocked
+ lifecycle.condition.Broadcast()
}
if lifecycle.state != EncryptedBoxStateUnlocked {
return errors.New("encrypted notebook is not unlocked")
diff --git a/kernel/model/export.go b/kernel/model/export.go
index a3555aa7c7..64a991eaa5 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -66,6 +66,34 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+func getExportBlockTree(id string) *treenode.BlockTree {
+ if bt := treenode.GetBlockTree(id); bt != nil {
+ return bt
+ }
+ for _, boxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ if bt := treenode.GetBlockTreeInBox(id, boxID); bt != nil {
+ return bt
+ }
+ }
+ return nil
+}
+
+func getExportBlockTreeInBox(id, boxID string) *treenode.BlockTree {
+ if boxID == "" {
+ return getExportBlockTree(id)
+ }
+ return treenode.GetBlockTreeInExactBox(id, boxID)
+}
+
+func getExportBlockTrees(ids []string) (ret []*treenode.BlockTree) {
+ for _, id := range ids {
+ if bt := getExportBlockTree(id); bt != nil {
+ ret = append(ret, bt)
+ }
+ }
+ return
+}
+
func ExportCodeBlock(blockID string) (filePath string, err error) {
// Supports exporting a code block as a file https://github.com/siyuan-note/siyuan/pull/16774
@@ -124,7 +152,7 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {
err = withExportReadLockByBlockID(blockID, func() error {
avBoxID := ""
- if bt := treenode.GetBlockTree(blockID); nil != bt && IsEncryptedBox(bt.BoxID) {
+ if bt := getExportBlockTree(blockID); nil != bt && IsEncryptedBox(bt.BoxID) {
avBoxID = bt.BoxID
av.SetAVBoxID(avID, avBoxID)
}
@@ -536,7 +564,7 @@ func ExportSystemLog() (zipPath string) {
// 未解锁返回 true(调用方应中止导出并返回空结果);普通笔记本或已解锁返回 false。
// 用于文档级导出入口的统一 guard,避免未解锁时读出密文或空结果。
func exportLockedByBlockID(id string) bool {
- bt := treenode.GetBlockTree(id)
+ bt := getExportBlockTree(id)
if nil == bt {
return false // 找不到块树,交给后续流程处理
}
@@ -547,7 +575,7 @@ func exportLockedByBlockID(id string) bool {
// 持锁期间 LockBox(自动锁定)会阻塞等待,避免操作中途清 DEK/删导出目录导致部分明文写出。
// 普通笔记本或块树不存在时直接执行 fn。嵌套调用安全:sync.RWMutex.RLock 可重入。
func withExportReadLockByBlockID(id string, fn func() error) error {
- bt := treenode.GetBlockTree(id)
+ bt := getExportBlockTree(id)
if nil == bt || !IsEncryptedBox(bt.BoxID) {
return fn()
}
@@ -573,7 +601,13 @@ func ExportNotebookSY(id string) (zipPath string) {
}
func ExportSYs(ids []string) (zipPath string) {
- block := treenode.GetBlockTree(ids[0])
+ if len(ids) == 0 {
+ return
+ }
+ block := getExportBlockTree(ids[0])
+ if block == nil {
+ return
+ }
if nil != block && IsEncryptedBox(block.BoxID) && !IsBoxUnlocked(block.BoxID) {
logging.LogErrorf("export encrypted doc [%s] failed: box [%s] locked", ids[0], block.BoxID)
return
@@ -585,7 +619,7 @@ func ExportSYs(ids []string) (zipPath string) {
}
var docPaths []string
- bts := treenode.GetBlockTrees(ids)
+ bts := getExportBlockTrees(ids)
for _, bt := range bts {
docPaths = append(docPaths, bt.Path)
@@ -917,7 +951,7 @@ func exportResourcesEncryptedBox(resourcePaths []string) (encryptedBoxID string,
func ExportPreview(id string, fillCSSVar bool) (retStdHTML string) {
if exportErr := withExportReadLockByBlockID(id, func() error {
blockRefMode := Conf.Export.BlockRefMode
- bt := treenode.GetBlockTree(id)
+ bt := getExportBlockTree(id)
if nil == bt {
return nil
}
@@ -997,7 +1031,7 @@ func ExportDocx(id, savePath string, removeAssets, merge bool) (fullPath string,
}
tmpDir := filepath.Join(util.TempDir, "export", gulu.Rand.String(7))
- if bt := treenode.GetBlockTree(id); bt != nil && IsEncryptedBox(bt.BoxID) {
+ if bt := getExportBlockTree(id); bt != nil && IsEncryptedBox(bt.BoxID) {
exportID, idErr := newManagedEncryptedExportID()
if idErr != nil {
return idErr
@@ -1067,7 +1101,7 @@ func ExportDocx(id, savePath string, removeAssets, merge bool) (fullPath string,
func ExportMarkdownHTML(id, savePath string, docx, merge bool) (name, dom string) {
if exportErr := withExportReadLockByBlockID(id, func() error {
- bt := treenode.GetBlockTree(id)
+ bt := getExportBlockTree(id)
if nil == bt {
return nil
}
@@ -1250,7 +1284,7 @@ func ExportHTML(id, savePath string, pdf, keepFold, merge bool) (name, dom strin
if exportErr := withExportReadLockByBlockID(id, func() error {
savePath = strings.TrimSpace(savePath)
- bt := treenode.GetBlockTree(id)
+ bt := getExportBlockTree(id)
if nil == bt {
return nil
}
@@ -1541,7 +1575,7 @@ func ProcessPDF(id, p string, merge, removeAssets, watermark bool) (err error) {
return nil
}
- processPDFBookmarks(pdfCtx, headings, headingNumbers)
+ processPDFBookmarks(pdfCtx, headings, headingNumbers, tree.Box)
processPDFLinkEmbedAssets(pdfCtx, assetDests, tree.Box, removeAssets)
processPDFWatermark(pdfCtx, watermark)
@@ -1662,7 +1696,7 @@ func processPDFWatermark(pdfCtx *model.Context, watermark bool) {
}
}
-func processPDFBookmarks(pdfCtx *model.Context, headings []*ast.Node, headingNumbers map[string]string) {
+func processPDFBookmarks(pdfCtx *model.Context, headings []*ast.Node, headingNumbers map[string]string, boxID string) {
links, err := PdfListToCLinks(pdfCtx)
if err != nil {
return
@@ -1676,7 +1710,7 @@ func processPDFBookmarks(pdfCtx *model.Context, headings []*ast.Node, headingNum
bms := map[string]*pdfcpu.Bookmark{}
for _, link := range links {
linkID := link.URI[strings.LastIndex(link.URI, "/")+1:]
- b := sql.GetBlock(linkID)
+ b := sql.GetBlockInBox(linkID, boxID)
if nil == b {
logging.LogWarnf("pdf outline block [%s] not found", linkID)
continue
@@ -1980,7 +2014,7 @@ func processPDFLinkEmbedAssets(pdfCtx *model.Context, assetDests []string, boxID
func ExportStdMarkdown(id string, assetsDestSpace2Underscore, fillCSSVar, adjustHeadingLevel, imgTag bool) string {
var ret string
if exportErr := withExportReadLockByBlockID(id, func() error {
- bt := treenode.GetBlockTree(id)
+ bt := getExportBlockTree(id)
if nil == bt {
logging.LogErrorf("block tree [%s] not found", id)
return nil
@@ -2008,7 +2042,7 @@ func ExportStdMarkdown(id string, assetsDestSpace2Underscore, fillCSSVar, adjust
}
if "" != defID {
- if defBt := treenode.GetBlockTree(defID); nil != defBt {
+ if defBt := getExportBlockTreeInBox(defID, tree.Box); nil != defBt {
defBlockIDs = append(defBlockIDs, defID)
defBlockIDs = gulu.Str.RemoveDuplicatedElem(defBlockIDs)
}
@@ -2175,7 +2209,13 @@ func ParseExportOptions(arg map[string]any) (opts *ExportOptions) {
}
func ExportPandocConvertZip(ids []string, pandocTo, ext string) (name, zipPath string) {
- block := treenode.GetBlockTree(ids[0])
+ if len(ids) == 0 {
+ return
+ }
+ block := getExportBlockTree(ids[0])
+ if block == nil {
+ return
+ }
if nil != block && IsEncryptedBox(block.BoxID) && !IsBoxUnlocked(block.BoxID) {
logging.LogErrorf("export pandoc zip [%s] failed: encrypted notebook locked", ids[0])
return
@@ -2187,7 +2227,7 @@ func ExportPandocConvertZip(ids []string, pandocTo, ext string) (name, zipPath s
}
var docPaths []string
- bts := treenode.GetBlockTrees(ids)
+ bts := getExportBlockTrees(ids)
for _, bt := range bts {
docPaths = append(docPaths, bt.Path)
@@ -2206,7 +2246,7 @@ func ExportPandocConvertZip(ids []string, pandocTo, ext string) (name, zipPath s
}
}
- defBlockIDs, docPaths := prepareExportTrees(docPaths)
+ defBlockIDs, docPaths := prepareExportTrees(docPaths, block.BoxID)
zipPath = exportPandocConvertZip(block.BoxID, baseFolderName, docPaths, defBlockIDs, "gfm+footnotes+hard_line_breaks", pandocTo, ext)
name = util.GetTreeID(block.Path)
return
@@ -2232,7 +2272,7 @@ func ExportNotebookMarkdown(boxID string) (zipPath string) {
docPaths = append(docPaths, docFile.path)
}
- defBlockIDs, docPaths := prepareExportTrees(docPaths)
+ defBlockIDs, docPaths := prepareExportTrees(docPaths, boxID)
zipPath = exportPandocConvertZip(boxID, box.Name, docPaths, defBlockIDs, "", "", ".md")
return
}
@@ -2830,7 +2870,7 @@ func walkRelationAvs(avID, boxID string, exportAvIDs *hashset.Set) {
func ExportMarkdownContent(id string, refMode, embedMode int, addYfm, fillCSSVar, adjustHeadingLv, imgTag, addTitle bool) (hPath, exportedMd string) {
if exportErr := withExportReadLockByBlockID(id, func() error {
- bt := treenode.GetBlockTree(id)
+ bt := getExportBlockTree(id)
if nil == bt {
return nil
}
@@ -2861,7 +2901,7 @@ func exportMarkdownContent(rootID, ext string, exportRefMode int, defBlockIDs []
return
}
- refCount := sql.QueryRootChildrenRefCount(tree.ID)
+ refCount := sql.QueryRootChildrenRefCountInBox(tree.ID, tree.Box)
if !Conf.Export.MarkdownYFM && treenode.ContainOnlyDefaultIAL(tree) && 1 > len(refCount) {
for c := tree.Root.FirstChild; nil != c; c = c.Next {
if ast.NodeParagraph == c.Type {
@@ -2899,7 +2939,7 @@ func exportMarkdownContent0(id string, tree *parse.Tree, cloudAssetsBase string,
blockRefTextLeft, blockRefTextRight,
addTitle, inlineMemo, 0 < len(defBlockIDs), singleFile)
if adjustHeadingLv {
- bt := treenode.GetBlockTree(id)
+ bt := treenode.GetBlockTreeInBox(id, tree.Box)
adjustHeadingLevel(bt, tree)
}
@@ -2977,10 +3017,10 @@ func exportMarkdownContent0(id string, tree *parse.Tree, cloudAssetsBase string,
if treenode.IsBlockRef(n) {
// 如果是引用元素,则将其转换为超链接,指向 xxx.md#block-id
- defID, linkText := getExportBlockRefLinkText(n, blockRefTextLeft, blockRefTextRight)
+ defID, linkText := getExportBlockRefLinkText(n, blockRefTextLeft, blockRefTextRight, tree.Box)
if gulu.Str.Contains(defID, defBlockIDs) {
var href string
- bt := treenode.GetBlockTree(defID)
+ bt := getExportBlockTreeInBox(defID, tree.Box)
if nil != bt {
href += bt.HPath + ext
if "d" != bt.Type {
@@ -3116,7 +3156,7 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,
}
// 处理引用节点
- defID, linkText := getExportBlockRefLinkText(n, blockRefTextLeft, blockRefTextRight)
+ defID, linkText := getExportBlockRefLinkText(n, blockRefTextLeft, blockRefTextRight, tree.Box)
switch blockRefMode {
case 2: // 锚文本块链
@@ -3687,7 +3727,12 @@ func resolveFootnotesDefs(refFootnoteOrder *[]string, refFootnotesByID map[strin
footnotesDefBlock = &ast.Node{Type: ast.NodeFootnotesDefBlock}
var rendered []string
- bts := treenode.GetBlockTrees(*refFootnoteOrder)
+ var bts map[string]*treenode.BlockTree
+ if currentTree.Box == "" {
+ bts = treenode.GetBlockTrees(*refFootnoteOrder)
+ } else {
+ bts = treenode.GetBlockTreesInBox(*refFootnoteOrder, currentTree.Box)
+ }
for _, defID := range *refFootnoteOrder {
foot := refFootnotesByID[defID]
if nil == foot {
@@ -3699,7 +3744,13 @@ func resolveFootnotesDefs(refFootnoteOrder *[]string, refFootnotesByID map[strin
continue
}
- t, err := LoadTreeByBlockID(bt.RootID)
+ var t *parse.Tree
+ var err error
+ if currentTree.Box == "" {
+ t, err = LoadTreeByBlockID(bt.RootID)
+ } else {
+ t, err = LoadTreeByBlockIDInExactBox(bt.RootID, currentTree.Box)
+ }
if nil != err {
logging.LogWarnf("load tree for footnote def [%s] refNum [%s] failed: %s", defID, foot.refNum, err)
continue
@@ -3762,9 +3813,14 @@ func resolveFootnotesDefs(refFootnoteOrder *[]string, refFootnotesByID map[strin
stmt := n.ChildByType(ast.NodeBlockQueryEmbedScript).TokensStr()
stmt = html.UnescapeString(stmt)
stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")
- sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)
+ var sqlBlocks []*sql.Block
+ if IsEncryptedBox(currentTree.Box) {
+ sqlBlocks = sql.SelectBlocksRawStmtInBox(stmt, 1, Conf.Search.Limit, currentTree.Box)
+ } else {
+ sqlBlocks = sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)
+ }
for _, b := range sqlBlocks {
- subNodes := renderBlockMarkdownR(b.ID, &rendered)
+ subNodes := renderBlockMarkdownR(b.ID, &rendered, currentTree.Box)
for _, subNode := range subNodes {
if ast.NodeListItem == subNode.Type {
parentList := &ast.Node{Type: ast.NodeList, ListData: &ast.ListData{Typ: subNode.ListData.Typ}}
@@ -3808,7 +3864,13 @@ func resolveFootnotesDefs(refFootnoteOrder *[]string, refFootnotesByID map[strin
docID := util.GetTreeID(n.Path)
if currentTree.ID == docID {
// 同文档块引转脚注缩略定义 https://github.com/siyuan-note/siyuan/issues/3299
- if text := sql.GetRefText(n.ID); 64 < utf8.RuneCountInString(text) {
+ var text string
+ if IsEncryptedBox(currentTree.Box) {
+ text = GetBlockRefTextInBox(n.ID, currentTree.Box)
+ } else {
+ text = sql.GetRefText(n.ID)
+ }
+ if 64 < utf8.RuneCountInString(text) {
var unlinkChildren []*ast.Node
for c := n.FirstChild; nil != c; c = c.Next {
unlinkChildren = append(unlinkChildren, c)
@@ -3851,11 +3913,11 @@ func collectFootnotesDefs(currentTree *parse.Tree, id string, refFootnoteOrder *
if 4096 < *depth {
return
}
- b := treenode.GetBlockTree(id)
+ b := treenode.GetBlockTreeInBox(id, currentTree.Box)
if nil == b {
return
}
- t, err := LoadTreeByBlockID(b.RootID)
+ t, err := LoadTreeByBlockIDInExactBox(b.RootID, currentTree.Box)
if nil != err {
return
}
@@ -3907,7 +3969,11 @@ func collectFootnotesDefs0(currentTree *parse.Tree, node *ast.Node, refFootnoteO
defID := strings.TrimPrefix(n.TextMarkAHref, "siyuan://blocks/")
anchorText := n.TextMarkTextContent
if "" == anchorText {
- anchorText = sql.GetRefText(defID)
+ if IsEncryptedBox(currentTree.Box) {
+ anchorText = GetBlockRefTextInBox(defID, currentTree.Box)
+ } else {
+ anchorText = sql.GetRefText(defID)
+ }
}
addRefFootnoteAndRecurse(currentTree, defID, anchorText, refFootnoteOrder, refFootnotesByID, depth)
return ast.WalkSkipChildren
@@ -4251,10 +4317,14 @@ func removeAssetsID(tree *parse.Tree, assetsOldNew, assetsNewOld map[string]stri
}
}
-func getExportBlockRefLinkText(blockRef *ast.Node, blockRefTextLeft, blockRefTextRight string) (defID, linkText string) {
+func getExportBlockRefLinkText(blockRef *ast.Node, blockRefTextLeft, blockRefTextRight, boxID string) (defID, linkText string) {
defID, linkText, _ = treenode.GetBlockRef(blockRef)
if "" == linkText {
- linkText = sql.GetRefText(defID)
+ if IsEncryptedBox(boxID) {
+ linkText = GetBlockRefTextInBox(defID, boxID)
+ } else {
+ linkText = sql.GetRefText(defID)
+ }
}
linkText = util.UnescapeHTML(linkText) // 块引锚文本导出时 `&` 变为实体 `&amp;` https://github.com/siyuan-note/siyuan/issues/7659
if Conf.Editor.BlockRefDynamicAnchorTextMaxLen < utf8.RuneCountInString(linkText) {
@@ -4264,16 +4334,26 @@ func getExportBlockRefLinkText(blockRef *ast.Node, blockRefTextLeft, blockRefTex
return
}
-func prepareExportTrees(docPaths []string) (defBlockIDs []string, relatedDocPaths []string) {
+func prepareExportTrees(docPaths []string, boxIDs ...string) (defBlockIDs []string, relatedDocPaths []string) {
trees := map[string]*parse.Tree{}
defBlockIDs = []string{}
+ boxID := ""
+ if len(boxIDs) > 0 {
+ boxID = boxIDs[0]
+ }
for i, p := range docPaths {
rootID := strings.TrimSuffix(path.Base(p), ".sy")
if !ast.IsNodeIDPattern(rootID) {
continue
}
- tree, err := LoadTreeByBlockID(rootID)
+ var tree *parse.Tree
+ var err error
+ if boxID == "" {
+ tree, err = LoadTreeByBlockID(rootID)
+ } else {
+ tree, err = LoadTreeByBlockIDInExactBox(rootID, boxID)
+ }
if err != nil {
continue
}
@@ -4305,12 +4385,12 @@ func exportRefTrees(tree *parse.Tree, defBlockIDs *[]string, retTrees map[string
if "" == defID {
return ast.WalkContinue
}
- defBlock := treenode.GetBlockTree(defID)
+ defBlock := treenode.GetBlockTreeInBox(defID, tree.Box)
if nil == defBlock {
return ast.WalkSkipChildren
}
- defTree, err := LoadTreeByBlockID(defBlock.RootID)
+ defTree, err := LoadTreeByBlockIDInExactBox(defBlock.RootID, tree.Box)
if err != nil {
return ast.WalkSkipChildren
}
@@ -4325,12 +4405,12 @@ func exportRefTrees(tree *parse.Tree, defBlockIDs *[]string, retTrees map[string
if "" == defID {
return ast.WalkContinue
}
- defBlock := treenode.GetBlockTree(defID)
+ defBlock := treenode.GetBlockTreeInBox(defID, tree.Box)
if nil == defBlock {
return ast.WalkSkipChildren
}
- defTree, err := LoadTreeByBlockID(defBlock.RootID)
+ defTree, err := LoadTreeByBlockIDInExactBox(defBlock.RootID, tree.Box)
if err != nil {
return ast.WalkSkipChildren
}
@@ -4349,7 +4429,12 @@ func exportRefTrees(tree *parse.Tree, defBlockIDs *[]string, retTrees map[string
return ast.WalkContinue
}
- attrView, _ := av.ParseAttributeView(avID)
+ var attrView *av.AttributeView
+ if IsEncryptedBox(tree.Box) {
+ attrView, _ = av.ParseAttributeViewInBox(avID, tree.Box)
+ } else {
+ attrView, _ = av.ParseAttributeView(avID)
+ }
if nil == attrView {
return ast.WalkContinue
}
@@ -4369,12 +4454,12 @@ func exportRefTrees(tree *parse.Tree, defBlockIDs *[]string, retTrees map[string
continue
}
- defBlock := treenode.GetBlockTree(blockID)
+ defBlock := getExportBlockTreeInBox(blockID, tree.Box)
if nil == defBlock {
continue
}
- defTree, err := LoadTreeByBlockID(defBlock.RootID)
+ defTree, err := LoadTreeByBlockIDInExactBox(defBlock.RootID, tree.Box)
if err != nil {
continue
}
diff --git a/kernel/model/file.go b/kernel/model/file.go
index a4faeff5b5..0dab1e8549 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -184,12 +184,45 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[
}
boxes[box.ID] = box
}
+ queryRootBlocks := func(condition, exactKeyword string, limit int, args ...any) (ret []*sql.Block) {
+ seen := map[string]struct{}{}
+ appendBlocks := func(blocks []*sql.Block) {
+ for _, block := range blocks {
+ if block == nil {
+ continue
+ }
+ key := block.Box + "\x00" + block.ID
+ if _, exists := seen[key]; exists {
+ continue
+ }
+ seen[key] = struct{}{}
+ ret = append(ret, block)
+ if len(ret) >= limit {
+ return
+ }
+ }
+ }
+ appendBlocks(sql.QueryRootBlockByCondition(condition, exactKeyword, limit, args...))
+ if len(ret) >= limit {
+ return ret[:limit]
+ }
+ for boxID := range boxes {
+ if !IsEncryptedBox(boxID) {
+ continue
+ }
+ appendBlocks(sql.QueryRootBlockByConditionInBox(condition, exactKeyword, limit-len(ret), boxID, args...))
+ if len(ret) >= limit {
+ break
+ }
+ }
+ return
+ }
keyword = strings.TrimSpace(keyword)
var rootBlocks []*sql.Block
if ast.IsNodeIDPattern(keyword) {
- rootBlocks = sql.QueryRootBlockByCondition("id = ?", keyword, 1, keyword)
+ rootBlocks = queryRootBlocks("id = ?", keyword, 1, keyword)
} else {
keywords := strings.Fields(keyword)
if 0 < len(keywords) {
@@ -210,7 +243,7 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[
}
condition, args := buildSearchDocsCondition(keywords, excludeIDs, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo)
- rootBlocks = sql.QueryRootBlockByCondition(condition, keyword, Conf.Search.Limit, args...)
+ rootBlocks = queryRootBlocks(condition, keyword, Conf.Search.Limit, args...)
} else {
for _, box := range boxes {
data := map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon}
@@ -1366,7 +1399,7 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) {
return
}
- hPath, err := RenderGoTemplate(boxConf.DailyNoteSavePath)
+ hPath, err := RenderGoTemplateInBox(boxConf.DailyNoteSavePath, box.ID)
if err != nil {
return
}
diff --git a/kernel/model/heading.go b/kernel/model/heading.go
index 7b1b2e330b..f74a7ef547 100644
--- a/kernel/model/heading.go
+++ b/kernel/model/heading.go
@@ -160,7 +160,7 @@ func (tx *Transaction) doUnfoldHeading(operation *Operation) (ret *TxErr) {
sql.UpsertTreeQueue(tree)
// 展开折叠的标题后显示块引用计数 Display reference counts after unfolding headings https://github.com/siyuan-note/siyuan/issues/13618
- fillBlockRefCount(children)
+ fillBlockRefCount(children, tree.Box)
operation.RetData = renderVisibleBlockDOMByNodes(children, NewLute())
if 0 < len(legacyNodes) {
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 7794c67d03..29d15cd333 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -1013,6 +1013,81 @@ func replaceAssetName(path string, assetNameMap map[string]string, boxSuffix str
return path
}
+func validateImportedNotebookIdentities(tmpDataPath string) ([]string, error) {
+ dirs, err := os.ReadDir(tmpDataPath)
+ if err != nil {
+ return nil, err
+ }
+
+ var encryptedBoxIDs []string
+ for _, entry := range dirs {
+ if !entry.IsDir() || !ast.IsNodeIDPattern(entry.Name()) {
+ continue
+ }
+
+ boxID := entry.Name()
+ boxDir := filepath.Join(tmpDataPath, boxID)
+ confPath := filepath.Join(boxDir, ".siyuan", "conf.json")
+ backupPath := filepath.Join(boxDir, ".siyuan", notebookCryptoBackupFilename)
+
+ var boxConf *conf.BoxConf
+ if filelock.IsExist(confPath) {
+ data, readErr := filelock.ReadFile(confPath)
+ if readErr != nil {
+ return nil, fmt.Errorf("read imported notebook conf [%s] failed: %w", boxID, readErr)
+ }
+ boxConf = conf.NewBoxConf()
+ if unmarshalErr := gulu.JSON.UnmarshalJSON(data, boxConf); unmarshalErr != nil {
+ return nil, fmt.Errorf("parse imported notebook conf [%s] failed: %w", boxID, unmarshalErr)
+ }
+ }
+
+ var backup *conf.BoxEncryption
+ if filelock.IsExist(backupPath) {
+ backup, err = readBoxEncryptionFile(backupPath)
+ if err != nil {
+ return nil, fmt.Errorf("invalid imported notebook identity [%s]: %w", boxID, err)
+ }
+ }
+
+ var boxCrypt *conf.BoxEncryption
+ if boxConf != nil && boxConf.Encrypted {
+ if boxConf.BoxCrypt != nil && validateBoxEncryption(boxConf.BoxCrypt) == nil {
+ boxCrypt = boxConf.BoxCrypt
+ } else {
+ boxCrypt = backup
+ }
+ if boxCrypt == nil {
+ return nil, fmt.Errorf("encrypted notebook [%s] has no valid identity", boxID)
+ }
+ } else if boxConf != nil && backup != nil {
+ return nil, fmt.Errorf("notebook [%s] has conflicting normal and encrypted identities", boxID)
+ } else if backup != nil {
+ boxCrypt = backup
+ }
+
+ payloadFound, payloadErr := hasEncryptedNotebookPayloadAtPath(boxDir)
+ if payloadErr != nil {
+ return nil, fmt.Errorf("inspect imported notebook [%s] failed: %w", boxID, payloadErr)
+ }
+ if boxCrypt == nil && payloadFound {
+ return nil, fmt.Errorf("imported notebook [%s] contains encrypted payload without identity", boxID)
+ }
+ if boxCrypt == nil {
+ continue
+ }
+
+ if err = validateBoxEncryption(boxCrypt); err != nil {
+ return nil, fmt.Errorf("invalid imported notebook identity [%s]: %w", boxID, err)
+ }
+ if filelock.IsExist(filepath.Join(util.DataDir, boxID)) && IsEncryptedBox(boxID) {
+ return nil, fmt.Errorf("refuse to overwrite existing encrypted notebook [%s]", boxID)
+ }
+ encryptedBoxIDs = append(encryptedBoxIDs, boxID)
+ }
+ return encryptedBoxIDs, nil
+}
+
func ImportData(zipPath string) (err error) {
util.PushEndlessProgress(Conf.Language(73))
defer util.ClearPushProgress(100)
@@ -1068,11 +1143,18 @@ func ImportData(zipPath string) (err error) {
}
return nil
})
+ importedEncryptedBoxIDs, err := validateImportedNotebookIdentities(tmpDataPath)
+ if err != nil {
+ return err
+ }
if err = filelock.Copy(tmpDataPath, util.DataDir); err != nil {
logging.LogErrorf("copy data dir from [%s] to [%s] failed: %s", tmpDataPath, util.DataDir, err)
err = errors.New("copy data failed")
return
}
+ for _, boxID := range importedEncryptedBoxIDs {
+ forgetRuntimeNormalBox(boxID)
+ }
// 导入的 Data.zip 可能含加密笔记本备份文件:若本机未启用,自动把配置装回 conf.json,
// 让用户输主密码即可解锁导入的加密笔记本(不需主密码,仅装回 salt/verifier 配置)。
diff --git a/kernel/model/index.go b/kernel/model/index.go
index c462231257..a4fc164e22 100644
--- a/kernel/model/index.go
+++ b/kernel/model/index.go
@@ -364,6 +364,9 @@ func autoIndexEmbedBlock() {
defer indexEmbedBlockLock.Unlock()
embedBlocks := sql.QueryEmptyContentEmbedBlocks()
+ for _, boxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ embedBlocks = append(embedBlocks, sql.QueryEmptyContentEmbedBlocksInBox(boxID)...)
+ }
for i, embedBlock := range embedBlocks {
markdown := strings.TrimSpace(embedBlock.Markdown)
markdown = strings.TrimPrefix(markdown, "{{")
@@ -385,7 +388,12 @@ func autoIndexEmbedBlock() {
continue
}
- queryResultBlocks := sql.SelectBlocksRawStmtNoParse(stmt, 102400)
+ var queryResultBlocks []*sql.Block
+ if IsEncryptedBox(embedBlock.Box) {
+ queryResultBlocks = sql.SelectBlocksRawStmtNoParseInBox(stmt, 102400, embedBlock.Box)
+ } else {
+ queryResultBlocks = sql.SelectBlocksRawStmtNoParse(stmt, 102400)
+ }
for _, block := range queryResultBlocks {
embedBlock.Content += block.Content
}
@@ -400,8 +408,12 @@ func autoIndexEmbedBlock() {
}
}
-func updateEmbedBlockContent(embedBlockID string, queryResultBlocks []*EmbedBlock) {
- embedBlock := sql.GetBlock(embedBlockID)
+func updateEmbedBlockContent(embedBlockID string, queryResultBlocks []*EmbedBlock, boxIDs ...string) {
+ boxID := ""
+ if len(boxIDs) > 0 {
+ boxID = boxIDs[0]
+ }
+ embedBlock := sql.GetBlockInBox(embedBlockID, boxID)
if nil == embedBlock {
return
}
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index e3cd00bb4f..447074c37d 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -179,6 +179,8 @@ func RemoveBox(boxID string) (err error) {
isUserGuide := IsUserGuide(boxID)
localPath := filepath.Join(util.DataDir, boxID)
if !filelock.IsExist(localPath) {
+ forgetRuntimeNormalBox(boxID)
+ removeMasterPasswordMigrationBox(boxID)
return
}
if !gulu.File.IsDir(localPath) {
@@ -244,7 +246,10 @@ func RemoveBox(boxID string) (err error) {
treenode.RemoveEncryptedBlockTreeDBFile(boxID)
removeEncryptedBoxLifecycle(boxID)
forgetRuntimeEncryptedBox(boxID)
+ } else {
+ forgetRuntimeNormalBox(boxID)
}
+ removeMasterPasswordMigrationBox(boxID)
if isUserGuide {
if avFiles, readAvErr := getUserGuideAVJSONFiles(boxID); nil == readAvErr {
diff --git a/kernel/model/path.go b/kernel/model/path.go
index c41fc20a26..1c080229f5 100644
--- a/kernel/model/path.go
+++ b/kernel/model/path.go
@@ -286,11 +286,20 @@ func toSubTreeInBox(blocks []*Block, keyword, boxID string, originalRefBlockIDs
if ast.NodeList == next.Type {
for subLi := next.FirstChild; nil != subLi; subLi = subLi.Next {
subLiBlock, _ := getBlock(subLi.ID, tree)
+ if nil == subLiBlock || nil == subLi.FirstChild {
+ continue
+ }
var subFirst *sql.Block
if 3 != subLi.ListData.Typ {
- subFirst = sql.GetBlock(subLi.FirstChild.ID)
+ subFirst = sql.GetBlockInBox(subLi.FirstChild.ID, boxID)
} else {
- subFirst = sql.GetBlock(subLi.FirstChild.Next.ID)
+ if nil == subLi.FirstChild.Next {
+ continue
+ }
+ subFirst = sql.GetBlockInBox(subLi.FirstChild.Next.ID, boxID)
+ }
+ if nil == subFirst {
+ continue
}
subPos := 0
content := subFirst.Content
@@ -389,11 +398,20 @@ func toSubTreeInBox(blocks []*Block, keyword, boxID string, originalRefBlockIDs
if ast.NodeList == headingChild.Type {
for subLi := headingChild.FirstChild; nil != subLi; subLi = subLi.Next {
subLiBlock, _ := getBlock(subLi.ID, tree)
+ if nil == subLiBlock || nil == subLi.FirstChild {
+ continue
+ }
var subFirst *sql.Block
if 3 != subLi.ListData.Typ {
- subFirst = sql.GetBlock(subLi.FirstChild.ID)
+ subFirst = sql.GetBlockInBox(subLi.FirstChild.ID, boxID)
} else {
- subFirst = sql.GetBlock(subLi.FirstChild.Next.ID)
+ if nil == subLi.FirstChild.Next {
+ continue
+ }
+ subFirst = sql.GetBlockInBox(subLi.FirstChild.Next.ID, boxID)
+ }
+ if nil == subFirst {
+ continue
}
subPos := 0
content := subFirst.Content
diff --git a/kernel/model/render.go b/kernel/model/render.go
index 8670a582c3..e87698185a 100644
--- a/kernel/model/render.go
+++ b/kernel/model/render.go
@@ -145,7 +145,7 @@ func renderBlockText(node *ast.Node, excludeTypes []string, removeLineBreak bool
return
}
-func fillBlockRefCount(nodes []*ast.Node) {
+func fillBlockRefCount(nodes []*ast.Node, boxID string) {
var defIDs []string
for _, n := range nodes {
ast.Walk(n, func(n *ast.Node, entering bool) ast.WalkStatus {
@@ -160,7 +160,7 @@ func fillBlockRefCount(nodes []*ast.Node) {
})
}
defIDs = gulu.Str.RemoveDuplicatedElem(defIDs)
- refCount := sql.QueryRefCount(defIDs)
+ refCount := sql.QueryRefCountInBox(defIDs, boxID)
for _, n := range nodes {
ast.Walk(n, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || !n.IsBlock() {
@@ -500,20 +500,33 @@ func resolveEmbedR(n *ast.Node, blockEmbedMode int, luteEngine *lute.Lute, resol
return
}
-func renderBlockMarkdownR(id string, rendered *[]string) (ret []*ast.Node) {
- if gulu.Str.Contains(id, *rendered) {
+func renderBlockMarkdownR(id string, rendered *[]string, boxIDs ...string) (ret []*ast.Node) {
+ boxID := ""
+ if len(boxIDs) > 0 {
+ boxID = boxIDs[0]
+ }
+ renderedID := id
+ if boxID != "" {
+ renderedID = boxID + "\x00" + id
+ }
+ if gulu.Str.Contains(renderedID, *rendered) {
return
}
- *rendered = append(*rendered, id)
+ *rendered = append(*rendered, renderedID)
- b := treenode.GetBlockTree(id)
+ b := treenode.GetBlockTreeInBox(id, boxID)
if nil == b {
return
}
var err error
var t *parse.Tree
- if t, err = LoadTreeByBlockID(b.ID); err != nil {
+ if boxID == "" {
+ t, err = LoadTreeByBlockID(b.ID)
+ } else {
+ t, err = LoadTreeByBlockIDInExactBox(b.ID, boxID)
+ }
+ if err != nil {
return
}
node := treenode.GetNodeInTree(t, b.ID)
@@ -544,9 +557,14 @@ func renderBlockMarkdownR(id string, rendered *[]string) (ret []*ast.Node) {
stmt := n.ChildByType(ast.NodeBlockQueryEmbedScript).TokensStr()
stmt = html.UnescapeString(stmt)
stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")
- sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)
+ var sqlBlocks []*sql.Block
+ if boxID != "" && IsEncryptedBox(boxID) {
+ sqlBlocks = sql.SelectBlocksRawStmtInBox(stmt, 1, Conf.Search.Limit, boxID)
+ } else {
+ sqlBlocks = sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)
+ }
for _, sqlBlock := range sqlBlocks {
- subNodes := renderBlockMarkdownR(sqlBlock.ID, rendered)
+ subNodes := renderBlockMarkdownR(sqlBlock.ID, rendered, boxID)
for _, subNode := range subNodes {
inserts = append(inserts, subNode)
}
diff --git a/kernel/model/search.go b/kernel/model/search.go
index a8ca036036..dc2edd3dda 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -213,21 +213,30 @@ func UpdateEmbedBlock(id, content string) (err error) {
},
}
- updateEmbedBlockContent(id, []*EmbedBlock{embedBlock})
+ updateEmbedBlockContent(id, []*EmbedBlock{embedBlock}, bt.BoxID)
return
}
func GetEmbedBlock(embedBlockID string, includeIDs []string, headingMode int, breadcrumb bool) (ret []*EmbedBlock) {
- return getEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb, true)
+ return getEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb, true, "")
+}
+
+func GetEmbedBlockInBox(embedBlockID string, includeIDs []string, headingMode int, breadcrumb bool, boxID string) (ret []*EmbedBlock) {
+ return getEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb, true, boxID)
}
func GetEmbedBlockForPublish(embedBlockID string, includeIDs []string, headingMode int, breadcrumb bool) (ret []*EmbedBlock) {
- return getEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb, false)
+ return getEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb, false, "")
}
-func getEmbedBlock(embedBlockID string, includeIDs []string, headingMode int, breadcrumb, updateIndex bool) (ret []*EmbedBlock) {
+func getEmbedBlock(embedBlockID string, includeIDs []string, headingMode int, breadcrumb, updateIndex bool, boxID string) (ret []*EmbedBlock) {
validIDs := validEmbedBlockIDs(includeIDs, 1024)
- sqlBlocks := sql.GetBlocks(validIDs)
+ var sqlBlocks []*sql.Block
+ if boxID != "" {
+ sqlBlocks = sql.GetBlocksInBox(validIDs, boxID)
+ } else {
+ sqlBlocks = sql.GetBlocks(validIDs)
+ }
var existingBlocks []*sql.Block
for _, block := range sqlBlocks {
if nil != block {
@@ -245,7 +254,7 @@ func getEmbedBlock(embedBlockID string, includeIDs []string, headingMode int, br
return m[sqlBlocks[i].ID] < m[sqlBlocks[j].ID]
})
- ret = buildEmbedBlock(embedBlockID, []string{}, headingMode, breadcrumb, "", sqlBlocks, updateIndex)
+ ret = buildEmbedBlock(embedBlockID, []string{}, headingMode, breadcrumb, "", sqlBlocks, updateIndex, boxID)
return
}
@@ -326,12 +335,12 @@ func searchEmbedBlockInBox(embedBlockID, stmt string, excludeIDs []string, headi
} else {
sqlBlocks = sql.SelectBlocksRawStmtNoParse(stmt, Conf.Search.Limit)
}
- ret = buildEmbedBlock(embedBlockID, excludeIDs, headingMode, breadcrumb, treenode.GetEmbedBlockRefID(stmt), sqlBlocks, updateIndex)
+ ret = buildEmbedBlock(embedBlockID, excludeIDs, headingMode, breadcrumb, treenode.GetEmbedBlockRefID(stmt), sqlBlocks, updateIndex, boxID)
return
}
func buildEmbedBlock(embedBlockID string, excludeIDs []string, headingMode int, breadcrumb bool, embedBlockRefID string,
- sqlBlocks []*sql.Block, updateIndex bool) (ret []*EmbedBlock) {
+ sqlBlocks []*sql.Block, updateIndex bool, boxID string) (ret []*EmbedBlock) {
var tmp []*sql.Block
for _, b := range sqlBlocks {
if "query_embed" == b.Type { // 嵌入块不再嵌入
@@ -376,7 +385,7 @@ func buildEmbedBlock(embedBlockID string, excludeIDs []string, headingMode int,
if updateIndex {
// 嵌入块支持搜索 https://github.com/siyuan-note/siyuan/issues/7112
- task.AppendTaskWithTimeout(task.DatabaseIndexEmbedBlock, 30*time.Second, updateEmbedBlockContent, embedBlockID, ret)
+ task.AppendTaskWithTimeout(task.DatabaseIndexEmbedBlock, 30*time.Second, updateEmbedBlockContent, embedBlockID, ret, boxID)
}
// 添加笔记本名称
diff --git a/kernel/model/shortcuts.go b/kernel/model/shortcuts.go
index eadd4ce933..4c984fd36a 100644
--- a/kernel/model/shortcuts.go
+++ b/kernel/model/shortcuts.go
@@ -74,7 +74,7 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {
hPath := Conf.FileTree.ShorthandSavePath
if "" != hPath {
var renderErr error
- hPath, renderErr = RenderGoTemplate(hPath)
+ hPath, renderErr = RenderGoTemplateInBox(hPath, boxID)
if nil != renderErr {
logging.LogErrorf("render shorthand save path failed: %s", renderErr)
hPath = ""
diff --git a/kernel/model/template.go b/kernel/model/template.go
index ad35c82474..4c7fc19464 100644
--- a/kernel/model/template.go
+++ b/kernel/model/template.go
@@ -52,15 +52,23 @@ type TemplateSearchResult struct {
}
func RenderGoTemplate(templateContent string) (ret string, err error) {
- return RenderGoTemplateAt(templateContent, time.Now())
+ return RenderGoTemplateAtInBox(templateContent, time.Now(), "")
}
// RenderGoTemplateAt 使用固定时间渲染 Go 模板,保证同一次业务操作中的多个模板结果一致。
func RenderGoTemplateAt(templateContent string, now time.Time) (ret string, err error) {
+ return RenderGoTemplateAtInBox(templateContent, now, "")
+}
+
+func RenderGoTemplateInBox(templateContent, boxID string) (ret string, err error) {
+ return RenderGoTemplateAtInBox(templateContent, time.Now(), boxID)
+}
+
+func RenderGoTemplateAtInBox(templateContent string, now time.Time, boxID string) (ret string, err error) {
tmpl := template.New("")
tplFuncMap := filesys.BuiltInTemplateFuncs()
tplFuncMap["now"] = func() time.Time { return now }
- sql.SQLTemplateFuncs(&tplFuncMap)
+ sql.SQLTemplateFuncs(&tplFuncMap, boxID)
tmpl = tmpl.Funcs(tplFuncMap)
tpl, err := tmpl.Parse(templateContent)
if err != nil {
@@ -378,7 +386,7 @@ func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, e
goTpl := template.New("").Delims(".action{", "}")
tplFuncMap := filesys.BuiltInTemplateFuncs()
- sql.SQLTemplateFuncs(&tplFuncMap)
+ sql.SQLTemplateFuncs(&tplFuncMap, tree.Box)
goTpl = goTpl.Funcs(tplFuncMap)
tpl, err := goTpl.Funcs(tplFuncMap).Parse(gulu.Str.FromBytes(md))
if err != nil {
@@ -500,7 +508,11 @@ func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, e
} else {
// 外部引用:保持 ID 不变,补全空锚文本
if refText := n.Text(); "" == refText {
- refText = strings.TrimSpace(sql.GetRefText(defID))
+ if IsEncryptedBox(tree.Box) {
+ refText = strings.TrimSpace(GetBlockRefTextInBox(defID, tree.Box))
+ } else {
+ refText = strings.TrimSpace(sql.GetRefText(defID))
+ }
if "" != refText {
treenode.SetDynamicBlockRefText(n, refText)
} else {
@@ -518,7 +530,11 @@ func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, e
} else {
// 外部引用:保持 ID 不变,补全空锚文本
if refText := n.Text(); "" == refText {
- refText = strings.TrimSpace(sql.GetRefText(defID))
+ if IsEncryptedBox(tree.Box) {
+ refText = strings.TrimSpace(GetBlockRefTextInBox(defID, tree.Box))
+ } else {
+ refText = strings.TrimSpace(sql.GetRefText(defID))
+ }
if "" != refText {
treenode.SetDynamicBlockRefText(n, refText)
} else {
diff --git a/kernel/model/virutalref.go b/kernel/model/virutalref.go
index 6e17c20334..b73ce1bfe8 100644
--- a/kernel/model/virutalref.go
+++ b/kernel/model/virutalref.go
@@ -69,7 +69,7 @@ func getBlockVirtualRefKeywords(root *ast.Node, boxID string) (ret []string) {
}
func putBlockVirtualRefKeywords(blockContent string, root *ast.Node, boxID string) (ret []string) {
- keywords := getVirtualRefKeywords(root)
+ keywords := getVirtualRefKeywords(root, boxID)
if 1 > len(keywords) {
return
}
@@ -124,6 +124,10 @@ func ResetVirtualBlockRefCache() {
refSearchIgnoreLines := getRefSearchIgnoreLines()
keywords := sql.QueryVirtualRefKeywords(Conf.Search.VirtualRefName, Conf.Search.VirtualRefAlias, Conf.Search.VirtualRefAnchor, Conf.Search.VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines)
virtualBlockRefCache.Set("virtual_ref", keywords, 1)
+ for _, boxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ boxKeywords := sql.QueryVirtualRefKeywords(Conf.Search.VirtualRefName, Conf.Search.VirtualRefAlias, Conf.Search.VirtualRefAnchor, Conf.Search.VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines, boxID)
+ virtualBlockRefCache.Set(boxID+"\x00virtual_ref", boxKeywords, 1)
+ }
}
// addNewKeywords 将新关键字添加到虚拟引用关键字列表中,如果不存在则追加,保留空白字符
@@ -272,13 +276,23 @@ func parseKeywords(keywordsStr string) (keywords []string) {
return
}
-func getVirtualRefKeywords(root *ast.Node) (ret []string) {
+func getVirtualRefKeywords(root *ast.Node, boxIDs ...string) (ret []string) {
if !Conf.Editor.VirtualBlockRef {
return
}
- if val, ok := virtualBlockRefCache.Get("virtual_ref"); ok {
+ key := "virtual_ref"
+ if len(boxIDs) > 0 && boxIDs[0] != "" {
+ key = boxIDs[0] + "\x00virtual_ref"
+ }
+ if val, ok := virtualBlockRefCache.Get(key); ok {
ret = val.([]string)
+ } else {
+ searchIgnoreLines := getSearchIgnoreLines()
+ refSearchIgnoreLines := getRefSearchIgnoreLines()
+ ret = sql.QueryVirtualRefKeywords(Conf.Search.VirtualRefName, Conf.Search.VirtualRefAlias,
+ Conf.Search.VirtualRefAnchor, Conf.Search.VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines, boxIDs...)
+ virtualBlockRefCache.Set(key, ret, 1)
}
includes := parseKeywords(Conf.Editor.VirtualBlockRefInclude)
diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.go
index 7204f6bdca..df181d52c8 100644
--- a/kernel/sql/block_query.go
+++ b/kernel/sql/block_query.go
@@ -51,6 +51,22 @@ func QueryEmptyContentEmbedBlocks() (ret []*Block) {
return
}
+func QueryEmptyContentEmbedBlocksInBox(boxID string) (ret []*Block) {
+ stmt := "SELECT * FROM blocks WHERE type = 'query_embed' AND content = ''"
+ rows, err := queryForBox(boxID, stmt)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", stmt, err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ if block := scanBlockRows(rows); block != nil {
+ ret = append(ret, block)
+ }
+ }
+ return
+}
+
func queryBlockHashes(tx *sql.Tx, rootID string) (ret map[string]string) {
stmt := "SELECT id, hash FROM blocks WHERE root_id = ?"
rows, err := queryTx(tx, stmt, rootID)
@@ -94,6 +110,29 @@ func QueryRootBlockByCondition(condition, exactKeyword string, limit int, args .
return
}
+func QueryRootBlockByConditionInBox(condition, exactKeyword string, limit int, boxID string, args ...any) (ret []*Block) {
+ exactCondition, exactArg := rootBlockExactMatchCondition(exactKeyword, caseSensitive)
+ sqlStmt := "SELECT *, length(hpath) - length(replace(hpath, '/', '')) AS lv FROM blocks WHERE type = 'd' AND " + condition +
+ " ORDER BY CASE WHEN " + exactCondition + " THEN 0 ELSE 1 END ASC, box DESC, lv ASC LIMIT ?"
+ args = append(args, exactArg, limit)
+ rows, err := queryForBox(boxID, sqlStmt, args...)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var block Block
+ var sepCount int
+ if err = rows.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated, &sepCount); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret = append(ret, &block)
+ }
+ return
+}
+
func rootBlockExactMatchCondition(keyword string, sensitive bool) (condition, arg string) {
if sensitive {
return "content = ?", keyword
@@ -162,7 +201,7 @@ func QueryBlockAliases(rootID string) (ret []string) {
return
}
-func queryNames(searchIgnoreLines []string) (ret []string) {
+func queryNames(searchIgnoreLines []string, boxIDs ...string) (ret []string) {
ret = []string{}
sqlStmt := "SELECT name FROM blocks WHERE name != ''"
buf := bytes.Buffer{}
@@ -172,7 +211,11 @@ func queryNames(searchIgnoreLines []string) (ret []string) {
}
sqlStmt += buf.String()
sqlStmt += " LIMIT ?"
- rows, err := query(sqlStmt, 10240)
+ boxID := ""
+ if len(boxIDs) > 0 {
+ boxID = boxIDs[0]
+ }
+ rows, err := queryForBox(boxID, sqlStmt, 10240)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return
@@ -202,7 +245,7 @@ func queryNames(searchIgnoreLines []string) (ret []string) {
return
}
-func queryAliases(searchIgnoreLines []string) (ret []string) {
+func queryAliases(searchIgnoreLines []string, boxIDs ...string) (ret []string) {
ret = []string{}
sqlStmt := "SELECT alias FROM blocks WHERE alias != ''"
buf := bytes.Buffer{}
@@ -212,7 +255,11 @@ func queryAliases(searchIgnoreLines []string) (ret []string) {
}
sqlStmt += buf.String()
sqlStmt += " LIMIT ?"
- rows, err := query(sqlStmt, 10240)
+ boxID := ""
+ if len(boxIDs) > 0 {
+ boxID = boxIDs[0]
+ }
+ rows, err := queryForBox(boxID, sqlStmt, 10240)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return
@@ -242,7 +289,7 @@ func queryAliases(searchIgnoreLines []string) (ret []string) {
return
}
-func queryDocTitles(searchIgnoreLines []string) (ret []string) {
+func queryDocTitles(searchIgnoreLines []string, boxIDs ...string) (ret []string) {
ret = []string{}
sqlStmt := "SELECT content FROM blocks WHERE type = 'd'"
buf := bytes.Buffer{}
@@ -251,7 +298,11 @@ func queryDocTitles(searchIgnoreLines []string) (ret []string) {
buf.WriteString(line)
}
sqlStmt += buf.String()
- rows, err := query(sqlStmt)
+ boxID := ""
+ if len(boxIDs) > 0 {
+ boxID = boxIDs[0]
+ }
+ rows, err := queryForBox(boxID, sqlStmt)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return
diff --git a/kernel/sql/block_ref_query.go b/kernel/sql/block_ref_query.go
index c50b2685c6..cb4605ab00 100644
--- a/kernel/sql/block_ref_query.go
+++ b/kernel/sql/block_ref_query.go
@@ -44,18 +44,22 @@ func GetRefDuplicatedDefRootIDs() (ret []string) {
return
}
-func QueryVirtualRefKeywords(name, alias, anchor, doc bool, searchIgnoreLines, refSearchIgnoreLines []string) (ret []string) {
+func QueryVirtualRefKeywords(name, alias, anchor, doc bool, searchIgnoreLines, refSearchIgnoreLines []string, boxIDs ...string) (ret []string) {
+ boxID := ""
+ if len(boxIDs) > 0 {
+ boxID = boxIDs[0]
+ }
if name {
- ret = append(ret, queryNames(searchIgnoreLines)...)
+ ret = append(ret, queryNames(searchIgnoreLines, boxID)...)
}
if alias {
- ret = append(ret, queryAliases(searchIgnoreLines)...)
+ ret = append(ret, queryAliases(searchIgnoreLines, boxID)...)
}
if anchor {
- ret = append(ret, queryRefTexts(refSearchIgnoreLines)...)
+ ret = append(ret, queryRefTexts(refSearchIgnoreLines, boxID)...)
}
if doc {
- ret = append(ret, queryDocTitles(searchIgnoreLines)...)
+ ret = append(ret, queryDocTitles(searchIgnoreLines, boxID)...)
}
ret = gulu.Str.RemoveDuplicatedElem(ret)
sort.SliceStable(ret, func(i, j int) bool {
@@ -64,7 +68,7 @@ func QueryVirtualRefKeywords(name, alias, anchor, doc bool, searchIgnoreLines, r
return
}
-func queryRefTexts(refSearchIgnoreLines []string) (ret []string) {
+func queryRefTexts(refSearchIgnoreLines []string, boxIDs ...string) (ret []string) {
ret = []string{}
sqlStmt := "SELECT DISTINCT content FROM refs WHERE 1 = 1"
buf := bytes.Buffer{}
@@ -74,7 +78,11 @@ func queryRefTexts(refSearchIgnoreLines []string) (ret []string) {
}
sqlStmt += buf.String()
sqlStmt += " LIMIT 10240"
- rows, err := query(sqlStmt)
+ boxID := ""
+ if len(boxIDs) > 0 {
+ boxID = boxIDs[0]
+ }
+ rows, err := queryForBox(boxID, sqlStmt)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return
@@ -349,6 +357,62 @@ func QueryBlockDefIDsByRefText(refText string) (ret []string) {
return
}
+func QueryBlockDefIDsByRefTextInBox(refText, boxID string) (ret []string) {
+ var q, arg string
+ if caseSensitive {
+ q = "SELECT DISTINCT(def_block_id) FROM refs WHERE content = ?"
+ arg = refText
+ } else {
+ q = "SELECT DISTINCT(def_block_id) FROM refs WHERE content LIKE ? ESCAPE '\\'"
+ arg = escapeLikePattern(refText)
+ }
+ rows, err := queryForBox(boxID, q, arg)
+ if err != nil {
+ logging.LogErrorf("sql query failed: %s", err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id string
+ if err = rows.Scan(&id); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret = append(ret, id)
+ }
+
+ escaped := escapeLikePattern(refText)
+ aliasArg := "%," + escaped + ",%"
+ var nameCond, docCond, exactArg string
+ if caseSensitive {
+ nameCond = "name = ?"
+ docCond = "content = ?"
+ exactArg = refText
+ } else {
+ nameCond = "name LIKE ? ESCAPE '\\'"
+ docCond = "content LIKE ? ESCAPE '\\'"
+ exactArg = escaped
+ }
+ q = "SELECT id FROM blocks WHERE " + nameCond + " OR (',' || alias || ',') LIKE ? ESCAPE '\\'" +
+ " UNION ALL SELECT id FROM (SELECT id FROM blocks WHERE type = 'd' AND " + docCond + " LIMIT ?)"
+ rows, err = queryForBox(boxID, q, exactArg, aliasArg, exactArg, 32)
+ if err != nil {
+ logging.LogErrorf("sql query failed: %s", err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id string
+ if err = rows.Scan(&id); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret = append(ret, id)
+ }
+ ret = gulu.Str.RemoveDuplicatedElem(ret)
+ return
+}
+
func queryDefIDsByDefText(keyword string) (ret []string) {
ret = []string{}
var q, arg string
diff --git a/kernel/sql/cache.go b/kernel/sql/cache.go
index d3c79898e6..0c50786743 100644
--- a/kernel/sql/cache.go
+++ b/kernel/sql/cache.go
@@ -173,7 +173,7 @@ func GetRefsCacheByDefIDInBox(defID, boxID string) (ret []*Ref) {
}
}
if 1 > len(ret) {
- allRefs := QueryRefsByDefID(defID, false)
+ allRefs := QueryRefsByDefIDInBox(defID, false, boxID)
for _, ref := range allRefs {
// 按 box 过滤:boxID 非空时只选同 box 的 Ref,boxID 为空时全部保留
if boxID == "" || ref.Box == boxID {
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index 4969719248..2542ef1bb7 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -1831,13 +1831,24 @@ func closeDatabase() {
return
}
-func SQLTemplateFuncs(templateFuncMap *template.FuncMap) {
+func SQLTemplateFuncs(templateFuncMap *template.FuncMap, boxIDs ...string) {
+ boxID := ""
+ if len(boxIDs) > 0 {
+ boxID = boxIDs[0]
+ }
readonlyStmts := &sync.Map{}
isReadonlyStmt := func(stmt string) bool {
if _, ok := readonlyStmts.Load(stmt); ok {
return true
}
- if CheckSingleStatement(stmt) != nil || CheckReadonlyStatement(stmt) != nil {
+ if CheckSingleStatement(stmt) != nil {
+ return false
+ }
+ if boxID == "" {
+ if CheckReadonlyStatement(stmt) != nil {
+ return false
+ }
+ } else if CheckReadonlyStatementInBox(stmt, boxID) != nil {
return false
}
readonlyStmts.Store(stmt, struct{}{})
@@ -1851,16 +1862,20 @@ func SQLTemplateFuncs(templateFuncMap *template.FuncMap) {
if !isReadonlyStmt(stmt) {
return
}
- retBlocks = SelectBlocksRawStmt(stmt, 1, 512)
+ if boxID == "" {
+ retBlocks = SelectBlocksRawStmt(stmt, 1, 512)
+ } else {
+ retBlocks = SelectBlocksRawStmtInBox(stmt, 1, 512, boxID)
+ }
return
}
(*templateFuncMap)["getBlock"] = func(arg any) (retBlock *Block) {
switch v := arg.(type) {
case string:
- retBlock = GetBlock(v)
+ retBlock = GetBlockInBox(v, boxID)
case map[string]any:
if id, ok := v["id"]; ok {
- retBlock = GetBlock(id.(string))
+ retBlock = GetBlockInBox(id.(string), boxID)
}
}
return
@@ -1872,14 +1887,25 @@ func SQLTemplateFuncs(templateFuncMap *template.FuncMap) {
if !isReadonlyStmt(stmt) {
return
}
- retSpans = SelectSpansRawStmt(stmt, 512)
+ if boxID == "" {
+ retSpans = SelectSpansRawStmt(stmt, 512)
+ } else {
+ retSpans = SelectSpansRawStmtInBox(stmt, 512, boxID)
+ }
return
}
(*templateFuncMap)["querySQL"] = func(stmt string) (ret []map[string]any) {
if !isReadonlyStmt(stmt) {
return
}
- ret, _ = Query(stmt, 1024)
+ if boxID == "" {
+ ret, _ = Query(stmt, 1024)
+ } else {
+ ret, _ = QueryNoLimitInBox(stmt, boxID)
+ if len(ret) > 1024 {
+ ret = ret[:1024]
+ }
+ }
return
}
}
diff --git a/kernel/sql/file_annotation_ref.go b/kernel/sql/file_annotation_ref.go
index f1c2da1369..c8a660226d 100644
--- a/kernel/sql/file_annotation_ref.go
+++ b/kernel/sql/file_annotation_ref.go
@@ -33,8 +33,12 @@ type FileAnnotationRef struct {
}
func QueryRefIDsByAnnotationID(annotationID string) (refIDs []string) {
+ return QueryRefIDsByAnnotationIDInBox(annotationID, "")
+}
+
+func QueryRefIDsByAnnotationIDInBox(annotationID, boxID string) (refIDs []string) {
refIDs = []string{}
- rows, err := query("SELECT block_id FROM file_annotation_refs WHERE annotation_id = ?", annotationID)
+ rows, err := queryForBox(boxID, "SELECT block_id FROM file_annotation_refs WHERE annotation_id = ?", annotationID)
if err != nil {
logging.LogErrorf("sql query failed: %s", err)
return
diff --git a/kernel/sql/queue.go b/kernel/sql/queue.go
index 32b9b60b18..4521169f42 100644
--- a/kernel/sql/queue.go
+++ b/kernel/sql/queue.go
@@ -265,7 +265,9 @@ func FlushQueue() {
tx, err := beginTxForBox(op.boxID())
if err != nil {
- return
+ logging.LogWarnf("skip queue operation [%s] for box [%s]: %s", op.action, op.boxID(), err)
+ requeueOperation(op)
+ continue
}
groupOpsCurrent[op.action]++
@@ -604,3 +606,11 @@ func appendOperation(op *dbQueueOperation) {
appendToIndexQueue(op)
eventbus.Publish(eventbus.EvtSQLIndexChanged)
}
+
+func requeueOperation(op *dbQueueOperation) {
+ dbQueueLock.Lock()
+ operationQueue = append(operationQueue, op)
+ dbQueueLock.Unlock()
+ appendToIndexQueue(op)
+ eventbus.Publish(eventbus.EvtSQLIndexChanged)
+}
diff --git a/kernel/sql/span.go b/kernel/sql/span.go
index 267abacf62..3bc7457922 100644
--- a/kernel/sql/span.go
+++ b/kernel/sql/span.go
@@ -50,6 +50,18 @@ type Span struct {
}
func SelectSpansRawStmt(stmt string, limit int) (ret []*Span) {
+ return selectSpansRawStmt(stmt, limit, func(stmt string) (*sql.Rows, error) {
+ return query(stmt)
+ })
+}
+
+func SelectSpansRawStmtInBox(stmt string, limit int, boxID string) (ret []*Span) {
+ return selectSpansRawStmt(stmt, limit, func(stmt string) (*sql.Rows, error) {
+ return queryForBox(boxID, stmt)
+ })
+}
+
+func selectSpansRawStmt(stmt string, limit int, queryFn func(string) (*sql.Rows, error)) (ret []*Span) {
parsedStmt, err := sqlparser.Parse(stmt)
if err != nil {
//logging.LogErrorf("select [%s] failed: %s", stmt, err)
@@ -76,7 +88,7 @@ func SelectSpansRawStmt(stmt string, limit int) (ret []*Span) {
stmt = strings.ReplaceAll(stmt, "\\\"", "\"")
stmt = strings.ReplaceAll(stmt, "\\\\*", "\\*")
stmt = strings.ReplaceAll(stmt, "from dual", "")
- rows, err := query(stmt)
+ rows, err := queryFn(stmt)
if err != nil {
if strings.Contains(err.Error(), "syntax error") {
return
diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.go
index 567006761c..ceb3304ae9 100644
--- a/kernel/treenode/blocktree.go
+++ b/kernel/treenode/blocktree.go
@@ -172,6 +172,30 @@ func GetBlockTreesByType(typ string) (ret []*BlockTree) {
return
}
+// GetBlockTreesByTypeInBox 按类型在指定笔记本的块树数据库中查询块。
+func GetBlockTreesByTypeInBox(typ, boxID string) (ret []*BlockTree) {
+ if boxID == "" {
+ return GetBlockTreesByType(typ)
+ }
+
+ sqlStmt := "SELECT * FROM blocktrees WHERE type = ? AND box_id = ?"
+ rows, err := queryForBox(boxID, sqlStmt, typ, boxID)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var block BlockTree
+ if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret = append(ret, &block)
+ }
+ return
+}
+
func GetBlockTreeByBoxPath(boxID, path string) (ret *BlockTree) {
ret = &BlockTree{}
sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND path = ?"