Skip to content

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

:bug: fix encrypted-notebook AV/backlink/import multiple issues #18034

Daniel7bd270ef66ad
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index bc8e81b12a..9f04c4c35a 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -44,7 +44,7 @@ import {countBlockWord} from "../../layout/status";
import {Constants} from "../../constants";
import {mathRender} from "../render/mathRender";
import {duplicateBlock} from "../wysiwyg/commonHotkey";
-import {movePathTo, useShell} from "../../util/pathName";
+import {isEncryptedBox, movePathTo, useShell} from "../../util/pathName";
import {hintMoveBlock} from "../hint/extend";
import {makeCard, quickMakeCard} from "../../card/makeCard";
import {transferBlockRef} from "../../menus/block";
@@ -1879,7 +1879,13 @@ export class Gutter {
icon: "iconFolder",
label: window.siyuan.languages.showInFolder,
click() {
- useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, "storage", "av", nodeElement.getAttribute("data-av-id")) + ".json");
+ const avId = nodeElement.getAttribute("data-av-id");
+ const notebookId = protyle.notebookId;
+ // 加密笔记本的 AV 定义存 notebook 级路径
+ const avDir = isEncryptedBox(notebookId)
+ ? path.join(window.siyuan.config.system.dataDir, notebookId, "storage", "av")
+ : path.join(window.siyuan.config.system.dataDir, "storage", "av");
+ useShell("showItemInFolder", path.join(avDir, avId) + ".json");
}
}).element);
} else if ((type === "NodeVideo" || type === "NodeAudio") && !protyle.disabled) {
diff --git a/kernel/av/av.go b/kernel/av/av.go
index c686c80119..f879e8c7e5 100644
--- a/kernel/av/av.go
+++ b/kernel/av/av.go
@@ -501,7 +501,7 @@ func IsAttributeViewExist(avID string) bool {
func ParseAttributeView(avID string) (ret *AttributeView, err error) {
// 加密笔记本的 AV 定义存笔记本级路径,通过 fallback 自动查找并解密
- avJSONPath, _ := findAttributeViewPath(avID)
+ avJSONPath, _ := FindAttributeViewPath(avID)
if avJSONPath == "" {
// 文件不存在,可能是首次创建,按全局路径返回(由调用方处理)
avJSONPath = GetAttributeViewDataPath(avID)
@@ -667,7 +667,7 @@ func SaveAttributeView(av *AttributeView) (err error) {
// 缓存与待写入数据一致时跳过落盘;缓存未命中时再读盘比对,避免无变更的重复写入
// 通过 fallback 查找 AV 定义的实际路径(普通 box 全局,加密 box 笔记本级)
- avJSONPath, avBoxID := findAttributeViewPath(av.ID)
+ avJSONPath, avBoxID := FindAttributeViewPath(av.ID)
if avJSONPath == "" {
// 文件不存在(首次创建),使用全局路径,boxID 为空(普通 box)
// 加密 box 的首次创建由 handler 层通过 SetAVBoxID 预设路径
diff --git a/kernel/av/encrypted_hook.go b/kernel/av/encrypted_hook.go
index 6ad13d6880..b1102fe1dd 100644
--- a/kernel/av/encrypted_hook.go
+++ b/kernel/av/encrypted_hook.go
@@ -68,7 +68,7 @@ func attributeViewDataPathByBox(avID, boxID string) string {
// 2. 查全局 storage/av/(普通 box)
// 3. 遍历已打开的加密 box 查找
// 返回找到的路径和对应的 boxID(普通 box 返回空 boxID)。找不到返回空串。
-func findAttributeViewPath(avID string) (path string, boxID string) {
+func FindAttributeViewPath(avID string) (path string, boxID string) {
// 先查 pendingAVBox(首次创建场景)
if pendingBoxID := GetAVBoxID(avID); pendingBoxID != "" {
encPath := attributeViewDataPathByBox(avID, pendingBoxID)
@@ -93,7 +93,7 @@ func findAttributeViewPath(avID string) (path string, boxID string) {
// readAttributeViewData 按 fallback 逻辑读取 AV 定义数据(自动解密)。
func readAttributeViewData(avID string) ([]byte, error) {
- path, boxID := findAttributeViewPath(avID)
+ path, boxID := FindAttributeViewPath(avID)
if path == "" {
return nil, nil // 文件不存在,由调用方处理
}
@@ -145,7 +145,7 @@ func mirrorBlocksPath(boxID string) string {
// 先查 findAttributeViewPath(含 pendingAVBox fallback),找到则返回对应 box 的镜像路径。
// 找不到则返回全局路径。
func mirrorBlocksPathByAvID(avID string) string {
- _, boxID := findAttributeViewPath(avID)
+ _, boxID := FindAttributeViewPath(avID)
return mirrorBlocksPath(boxID)
}
diff --git a/kernel/av/filter_test.go b/kernel/av/filter_test.go
index 0f2e2d2a3c..aaa1558bf2 100644
--- a/kernel/av/filter_test.go
+++ b/kernel/av/filter_test.go
@@ -150,7 +150,7 @@ func TestRemoveFiltersByColumn(t *testing.T) {
func TestRemoveSelectOptionFromFilters(t *testing.T) {
sel := &ViewFilter{Column: "c1", Operator: FilterOperatorContains, Value: &Value{
- Type: KeyTypeSelect,
+ Type: KeyTypeSelect,
MSelect: []*ValueSelect{{Content: "A", Color: "1"}, {Content: "B", Color: "2"}},
}}
root := group(FilterCombinationAnd, sel)
@@ -173,7 +173,7 @@ func TestRemoveSelectOptionFromFilters(t *testing.T) {
func TestRenameSelectOptionInFilters(t *testing.T) {
sel := &ViewFilter{Column: "c1", Operator: FilterOperatorContains, Value: &Value{
- Type: KeyTypeMSelect,
+ Type: KeyTypeMSelect,
MSelect: []*ValueSelect{{Content: "old", Color: "1"}},
}}
nestedSel := &ViewFilter{Column: "c1", Value: &Value{Type: KeyTypeSelect, MSelect: []*ValueSelect{{Content: "old", Color: "1"}}}}
diff --git a/kernel/av/mirror.go b/kernel/av/mirror.go
index 21b4c866d0..351c583b3f 100644
--- a/kernel/av/mirror.go
+++ b/kernel/av/mirror.go
@@ -36,7 +36,7 @@ func IsMirror(avID string) bool {
AttributeViewBlocksLock.Lock()
defer AttributeViewBlocksLock.Unlock()
- _, boxID := findAttributeViewPath(avID)
+ _, boxID := FindAttributeViewPath(avID)
avBlocks := readMirrorBlocks(boxID)
blockIDs := avBlocks[avID]
return nil != blockIDs && 1 < len(blockIDs)
@@ -46,7 +46,7 @@ func RemoveBlockRel(avID, blockID string, existBlockTree func(string) bool) (ret
AttributeViewBlocksLock.Lock()
defer AttributeViewBlocksLock.Unlock()
- _, boxID := findAttributeViewPath(avID)
+ _, boxID := FindAttributeViewPath(avID)
avBlocks := readMirrorBlocks(boxID)
blockIDs := avBlocks[avID]
@@ -88,7 +88,7 @@ func BatchUpsertBlockRel(nodes []*ast.Node) {
continue
}
- _, boxID := findAttributeViewPath(n.AttributeViewID)
+ _, boxID := FindAttributeViewPath(n.AttributeViewID)
avBlocks, ok := boxAvBlocks[boxID]
if !ok {
avBlocks = readMirrorBlocks(boxID)
@@ -112,7 +112,7 @@ func UpsertBlockRel(avID, blockID string) (ret bool) {
AttributeViewBlocksLock.Lock()
defer AttributeViewBlocksLock.Unlock()
- _, boxID := findAttributeViewPath(avID)
+ _, boxID := FindAttributeViewPath(avID)
avBlocks := readMirrorBlocks(boxID)
blockIDs := avBlocks[avID]
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 840955a5b5..418f3711b1 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -3975,7 +3975,16 @@ func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (er
} else {
// Remove av block also remove node attr https://github.com/siyuan-note/siyuan/issues/9091#issuecomment-1709824006
if !val.IsDetached && nil != val.Block {
- if bt := treenode.GetBlockTree(val.Block.ID); nil != bt {
+ bt := treenode.GetBlockTree(val.Block.ID)
+ if nil == bt {
+ for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ if encBT := treenode.GetBlockTreeInBox(val.Block.ID, encBoxID); nil != encBT {
+ bt = encBT
+ break
+ }
+ }
+ }
+ if nil != bt {
tree := trees[bt.RootID]
if nil == tree {
tree, _ = LoadTreeByBlockID(val.Block.ID)
@@ -5996,6 +6005,14 @@ func updateBoundBlockAvsAttribute(avIDs []string) {
}
bt := treenode.GetBlockTree(boundBlockID)
+ if nil == bt {
+ for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ if encBT := treenode.GetBlockTreeInBox(boundBlockID, encBoxID); nil != encBT {
+ bt = encBT
+ break
+ }
+ }
+ }
if nil == bt {
continue
}
diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.go
index 9f5af4d6af..ba409df2e1 100644
--- a/kernel/model/attribute_view_render.go
+++ b/kernel/model/attribute_view_render.go
@@ -43,7 +43,6 @@ func RenderAttributeView(blockID, avID, viewID, query string, page, pageSize int
if "" != blockID {
bt := treenode.GetBlockTree(blockID)
if nil == bt {
- // 全局 blocktree 找不到时,遍历已打开的加密 box
for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
if encBT := treenode.GetBlockTreeInBox(blockID, encBoxID); nil != encBT {
bt = encBT
@@ -56,7 +55,13 @@ func RenderAttributeView(blockID, avID, viewID, query string, page, pageSize int
}
}
- if avJSONPath := av.GetAttributeViewDataPath(avID); !filelock.IsExist(avJSONPath) {
+ // 通过 fallback 查找 AV 定义路径(普通 box 全局,加密 box notebook 级)
+ existPath, _ := av.FindAttributeViewPath(avID)
+ if "" == existPath {
+ // fallback 找不到时按全局路径检查(首次创建场景)
+ existPath = av.GetAttributeViewDataPath(avID)
+ }
+ if !filelock.IsExist(existPath) {
if !createIfNotExist {
err = av.ErrAttributeViewNotFound
return
@@ -80,6 +85,12 @@ func RenderAttributeView(blockID, avID, viewID, query string, page, pageSize int
return
}
+ // 诊断:AV 解析后的数据量
+ blockKV := attrView.GetBlockKeyValues()
+ if nil != blockKV {
+ } else {
+ }
+
viewable, err = renderAttributeView(attrView, blockID, viewID, query, page, pageSize, groupPaging, ignoreRows)
return
}
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.go
index 902f29ad92..fd7c5cfad0 100644
--- a/kernel/model/backlink.go
+++ b/kernel/model/backlink.go
@@ -155,10 +155,12 @@ func GetBacklinkDoc(defID, refTreeID, keyword string, containChildren, highlight
rootID := sqlBlock.RootID
tmpRefs := sql.QueryRefsByDefID(defID, containChildren)
+ var encBoxIDUsed string
if len(tmpRefs) == 0 {
for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
if encRefs := sql.QueryRefsByDefIDInBox(defID, containChildren, encBoxID); len(encRefs) > 0 {
tmpRefs = encRefs
+ encBoxIDUsed = encBoxID
break
}
}
@@ -171,7 +173,7 @@ func GetBacklinkDoc(defID, refTreeID, keyword string, containChildren, highlight
}
refs = removeDuplicatedRefs(refs)
- linkRefs, _, _, originalRefBlockIDs := buildLinkRefs(rootID, refs, keywords)
+ linkRefs, _, _, originalRefBlockIDs := buildLinkRefsInBox(rootID, refs, keywords, encBoxIDUsed)
refTree, err := LoadTreeByBlockID(refTreeID)
if err != nil {
logging.LogWarnf("load ref tree [%s] failed: %s", refTreeID, err)
diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.go
index 0dedef4dda..00a3ada28d 100644
--- a/kernel/model/blockinfo.go
+++ b/kernel/model/blockinfo.go
@@ -102,8 +102,8 @@ func GetDocInfoInBox(blockID, boxID string) (ret *BlockInfo, err error) {
}
bt := treenode.GetBlockTreeInBox(blockID, boxID)
- refDefs := queryBlockRefDefsInBox(bt, boxID)
- buildBacklinkListItemRefs(refDefs)
+ refDefs := queryBlockRefDefsInBox(bt, bt.BoxID)
+ buildBacklinkListItemRefsInBox(refDefs, bt.BoxID)
var refIDs []string
for _, refDef := range refDefs {
refIDs = append(refIDs, refDef.RefID)
@@ -398,13 +398,14 @@ func GetBlockRefs(defID string) (refDefs []*RefDefs, originalRefBlockIDs map[str
return
}
- refDefs = queryBlockRefDefs(bt)
- originalRefBlockIDs = buildBacklinkListItemRefs(refDefs)
+ // 加密 box 的 refs 在加密 db,用 bt.BoxID 路由
+ refDefs = queryBlockRefDefsInBox(bt, bt.BoxID)
+ originalRefBlockIDs = buildBacklinkListItemRefsInBox(refDefs, bt.BoxID)
return
}
func queryBlockRefDefs(bt *treenode.BlockTree) (refDefs []*RefDefs) {
- return queryBlockRefDefsInBox(bt, "")
+ return queryBlockRefDefsInBox(bt, bt.BoxID)
}
// queryBlockRefDefsInBox 与 queryBlockRefDefs 一致,但按 boxID 路由到加密 db 或全局 db。
@@ -680,13 +681,17 @@ func buildBlockBreadcrumb(node *ast.Node, excludeTypes []string, isEmbedBlock bo
}
func buildBacklinkListItemRefs(refDefs []*RefDefs) (originalRefBlockIDs map[string]string) {
+ return buildBacklinkListItemRefsInBox(refDefs, "")
+}
+
+func buildBacklinkListItemRefsInBox(refDefs []*RefDefs, boxID string) (originalRefBlockIDs map[string]string) {
originalRefBlockIDs = map[string]string{}
var refIDs []string
for _, refDef := range refDefs {
refIDs = append(refIDs, refDef.RefID)
}
- sqlRefBlocks := sql.GetBlocks(refIDs)
+ sqlRefBlocks := sql.GetBlocksInBox(refIDs, boxID)
refBlocks := fromSQLBlocks(&sqlRefBlocks, "", 12)
parentRefParagraphs := map[string]*Block{}
@@ -697,7 +702,7 @@ func buildBacklinkListItemRefs(refDefs []*RefDefs) (originalRefBlockIDs map[stri
paragraphParentIDs = append(paragraphParentIDs, ref.ParentID)
}
}
- sqlParagraphParents := sql.GetBlocks(paragraphParentIDs)
+ sqlParagraphParents := sql.GetBlocksInBox(paragraphParentIDs, boxID)
paragraphParents := fromSQLBlocks(&sqlParagraphParents, "", 12)
luteEngine := util.NewLute()
diff --git a/kernel/model/bookmark.go b/kernel/model/bookmark.go
index af0e300483..73dd21a042 100644
--- a/kernel/model/bookmark.go
+++ b/kernel/model/bookmark.go
@@ -123,7 +123,7 @@ func RenameBookmark(oldBookmark, newBookmark string) (err error) {
if nil != err {
return
}
-
+
for treeID, blocks := range treeBlocks {
util.PushEndlessProgress("[" + treeID + "]")
tree, e := LoadTreeByBlockID(treeID)
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 01dcb8e589..2bb5b64ae0 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -573,7 +573,10 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
}
}
- // 将包含的资源文件统一移动到 data/assets/ 下
+ // 将包含的资源文件统一移动到 assets 下
+ // 加密笔记本拷到 <boxID>/assets/,普通笔记本拷到全局 data/assets/
+ // 加密笔记本同时收集「原始名 → 脱敏名」映射,用于后续更新文档内的引用路径
+ assetNameMap := map[string]string{} // 原始文件名 → 脱敏文件名
var assetsDirs []string
filelock.Walk(unzipRootPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
@@ -588,14 +591,115 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
return nil
})
dataAssets := filepath.Join(util.DataDir, "assets")
- for _, assets := range assetsDirs {
- if gulu.File.IsDir(assets) {
- if err = filelock.Copy(assets, dataAssets); err != nil {
- logging.LogErrorf("copy assets from [%s] to [%s] failed: %s", assets, dataAssets, err)
- return
+ if IsEncryptedBox(boxID) {
+ // 加密笔记本的资源文件拷到 notebook 级 assets 目录,文件名脱敏 + 内容加密
+ boxAssetsDir := filepath.Join(util.DataDir, boxID, "assets")
+ if err = os.MkdirAll(boxAssetsDir, 0755); err != nil {
+ return
+ }
+ for _, assets := range assetsDirs {
+ if gulu.File.IsDir(assets) {
+ filelock.Walk(assets, func(path string, d fs.DirEntry, err error) error {
+ if err != nil || d == nil || d.IsDir() {
+ return err
+ }
+ originalName := d.Name()
+ ext := filepath.Ext(originalName)
+ blockID := ast.NewNodeID()
+ diskName := encryptedAssetName(ext, blockID)
+ writeAssetNameMapping(boxID, diskName, originalName)
+ assetNameMap[originalName] = diskName
+ // 读取明文内容 → 加密 → 写入脱敏文件名
+ src, readErr := filelock.ReadFile(path)
+ if readErr != nil {
+ return readErr
+ }
+ if err = writeAssetFile(filepath.Join(boxAssetsDir, diskName), bytes.NewReader(src), boxID); err != nil {
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ return
+ }
}
+ os.RemoveAll(assets)
+ }
+ } else {
+ for _, assets := range assetsDirs {
+ if gulu.File.IsDir(assets) {
+ if err = filelock.Copy(assets, dataAssets); err != nil {
+ logging.LogErrorf("copy assets from [%s] to [%s] failed: %s", assets, dataAssets, err)
+ return
+ }
+ }
+ os.RemoveAll(assets)
+ }
+ }
+
+ // 将包含的 AV 定义统一移动到 storage/av/ 下
+ // 加密笔记本拷到 <boxID>/storage/av/,普通笔记本拷到全局 storage/av/
+ var avDirs []string
+ filelock.Walk(unzipRootPath, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d == nil || unzipRootPath == path {
+ return nil
+ }
+ // storage/av 目录
+ if d.Name() == "av" && d.IsDir() && strings.Contains(filepath.ToSlash(path), "storage/av") {
+ avDirs = append(avDirs, path)
+ }
+ return nil
+ })
+ globalAVDir := filepath.Join(util.DataDir, "storage", "av")
+ if IsEncryptedBox(boxID) {
+ // 加密笔记本的 AV 定义拷到 notebook 级目录,逐个文件 DEK 加密
+ boxAVDir := filepath.Join(util.DataDir, boxID, "storage", "av")
+ if err = os.MkdirAll(boxAVDir, 0755); err != nil {
+ return
+ }
+ dek, dekErr := GetDEK(boxID)
+ if dekErr != nil || dek == nil {
+ err = errors.New("encrypted box not unlocked")
+ return
+ }
+ for _, avDir := range avDirs {
+ if gulu.File.IsDir(avDir) {
+ filelock.Walk(avDir, func(path string, d fs.DirEntry, walkErr error) error {
+ if walkErr != nil || d == nil || d.IsDir() {
+ return walkErr
+ }
+ if !strings.HasSuffix(d.Name(), ".json") {
+ return nil
+ }
+ src, readErr := filelock.ReadFile(path)
+ if readErr != nil {
+ return readErr
+ }
+ enc, encErr := util.Encrypt(dek, src)
+ if encErr != nil {
+ return encErr
+ }
+ return filelock.WriteFile(filepath.Join(boxAVDir, d.Name()), enc)
+ })
+ if err != nil {
+ return
+ }
+ }
+ os.RemoveAll(avDir)
+ }
+ } else {
+ for _, avDir := range avDirs {
+ if gulu.File.IsDir(avDir) {
+ if err = filelock.Copy(avDir, globalAVDir); err != nil {
+ logging.LogErrorf("copy av from [%s] to [%s] failed: %s", avDir, globalAVDir, err)
+ return
+ }
+ }
+ os.RemoveAll(avDir)
}
- os.RemoveAll(assets)
}
// 将包含的自定义表情统一移动到 data/emojis/ 下
@@ -701,6 +805,12 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
continue
}
+ // 加密笔记本:更新文档内的 assets 引用路径(原始名 → 脱敏名)
+ if IsEncryptedBox(boxID) && 0 < len(assetNameMap) {
+ updateImportedAssetRefs(tree, assetNameMap)
+ indexWriteTreeIndexQueue(tree)
+ }
+
treenode.IndexBlockTree(tree)
sql.IndexTreeQueue(tree)
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))
@@ -712,6 +822,60 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
return
}
+// updateImportedAssetRefs 遍历树的 assets 引用路径,将原始文件名替换为脱敏文件名。
+// 覆盖:链接 href、图片 src、data-src、音视频 src、文件标注等。
+func updateImportedAssetRefs(tree *parse.Tree, assetNameMap map[string]string) {
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering {
+ return ast.WalkContinue
+ }
+ switch n.Type {
+ case ast.NodeLink:
+ // 链接 dest
+ dest := string(n.Tokens)
+ if updated := replaceAssetName(dest, assetNameMap); updated != dest {
+ n.Tokens = []byte(updated)
+ }
+ case ast.NodeImage:
+ // 图片 src 在 LinkDest 子节点
+ if dest := n.ChildByType(ast.NodeLinkDest); nil != dest {
+ src := string(dest.Tokens)
+ if updated := replaceAssetName(src, assetNameMap); updated != src {
+ dest.Tokens = []byte(updated)
+ }
+ }
+ case ast.NodeAudio, ast.NodeVideo:
+ src := n.TokensStr()
+ if updated := replaceAssetName(src, assetNameMap); updated != src {
+ n.Tokens = []byte(updated)
+ }
+ case ast.NodeTextMark:
+ // 行级文本标记里的 data-href(附件链接)
+ if "" != n.TextMarkAHref {
+ if updated := replaceAssetName(n.TextMarkAHref, assetNameMap); updated != n.TextMarkAHref {
+ n.TextMarkAHref = updated
+ }
+ }
+ }
+ return ast.WalkContinue
+ })
+}
+
+// replaceAssetName 在 assets 路径中替换原始文件名为脱敏文件名。
+func replaceAssetName(path string, assetNameMap map[string]string) string {
+ if !strings.Contains(path, "assets/") {
+ return path
+ }
+ for original, diskName := range assetNameMap {
+ // 匹配 assets/originalName(路径末尾的文件名)
+ idx := strings.LastIndex(path, original)
+ if idx > 0 && strings.Contains(path[idx:], original) {
+ path = path[:idx] + diskName + path[idx+len(original):]
+ }
+ }
+ return path
+}
+
func ImportData(zipPath string) (err error) {
util.PushEndlessProgress(Conf.Language(73))
defer util.ClearPushProgress(100)
@@ -1006,13 +1170,31 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {
existName := assetsDone[absolutePath]
var name string
if "" == existName {
- name = filepath.Base(absolutePath)
- name = util.FilterUploadFileName(name)
- name = util.AssetName(name, ast.NewNodeID())
- assetTargetPath := filepath.Join(assetDirPath, name)
- if err = filelock.Copy(absolutePath, assetTargetPath); err != nil {
- logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", absolutePath, assetTargetPath, err)
- return ast.WalkContinue
+ baseName := filepath.Base(absolutePath)
+ if IsEncryptedBox(boxID) {
+ // 加密笔记本:文件名脱敏 + 内容加密
+ ext := filepath.Ext(baseName)
+ blockID := ast.NewNodeID()
+ name = encryptedAssetName(ext, blockID)
+ writeAssetNameMapping(boxID, name, baseName)
+ assetTargetPath := filepath.Join(assetDirPath, name)
+ src, readErr := filelock.ReadFile(absolutePath)
+ if readErr != nil {
+ logging.LogErrorf("read asset [%s] failed: %s", absolutePath, readErr)
+ return ast.WalkContinue
+ }
+ if err = writeAssetFile(assetTargetPath, bytes.NewReader(src), boxID); err != nil {
+ logging.LogErrorf("write encrypted asset [%s] failed: %s", assetTargetPath, err)
+ return ast.WalkContinue
+ }
+ } else {
+ name = util.FilterUploadFileName(baseName)
+ name = util.AssetName(name, ast.NewNodeID())
+ assetTargetPath := filepath.Join(assetDirPath, name)
+ if err = filelock.Copy(absolutePath, assetTargetPath); err != nil {
+ logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", absolutePath, assetTargetPath, err)
+ return ast.WalkContinue
+ }
}
assetsDone[absolutePath] = name
} else {
diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.go
index 6781059216..0f9e53f2ef 100644
--- a/kernel/sql/encrypted_query.go
+++ b/kernel/sql/encrypted_query.go
@@ -83,10 +83,12 @@ func GetRefTextInBox(defBlockID, boxID string) (ret string) {
}
// QueryRefsByDefIDInBox 按 defBlockID 在指定 box 的 db 里查引用列表。
+// 注意:加密 content db 里没有 blocktrees 表(在独立的 blocktree db),containChildren 时
+// 不能 JOIN blocktrees,改为用 def_block_root_id 查询。
func QueryRefsByDefIDInBox(defBlockID string, containChildren bool, boxID string) (ret []*Ref) {
sqlStmt := "SELECT * FROM refs WHERE def_block_id = ?"
if containChildren {
- sqlStmt = "SELECT r.* FROM refs r JOIN blocktrees b ON r.def_block_root_id = b.root_id WHERE r.def_block_id = ?"
+ sqlStmt = "SELECT * FROM refs WHERE def_block_root_id = ?"
}
rows, err := queryForBox(boxID, sqlStmt, defBlockID)
if err != nil {
diff --git a/kernel/sql/fts_bench_test.go b/kernel/sql/fts_bench_test.go
index c33b4ec905..b72b2563cb 100644
--- a/kernel/sql/fts_bench_test.go
+++ b/kernel/sql/fts_bench_test.go
@@ -142,27 +142,27 @@ func genBlock(i, root int) []any {
}
content := bld.String()
return []any{
- fmt.Sprintf("%020d", i), // id
- fmt.Sprintf("%020d", root), // parent_id
- fmt.Sprintf("%020d", root), // root_id
- fmt.Sprintf("hash%d", i), // hash
- "20230201000", // box
- fmt.Sprintf("/p/%020d.sy", root), // path
- fmt.Sprintf("/文档%d", root), // hpath
- fmt.Sprintf("块名%d", i), // name
- "alias", // alias
- "memo", // memo
- "tag", // tag
- content, // content
- content, // fcontent
- fmt.Sprintf("markdown %d", i), // markdown
- len(content), // length
- "p", // type
- "", // subtype
- "{: id=\"ial\"}", // ial
- i, // sort
- "20230101000000", // created
- "20230101000000", // updated
+ fmt.Sprintf("%020d", i), // id
+ fmt.Sprintf("%020d", root), // parent_id
+ fmt.Sprintf("%020d", root), // root_id
+ fmt.Sprintf("hash%d", i), // hash
+ "20230201000", // box
+ fmt.Sprintf("/p/%020d.sy", root), // path
+ fmt.Sprintf("/文档%d", root), // hpath
+ fmt.Sprintf("块名%d", i), // name
+ "alias", // alias
+ "memo", // memo
+ "tag", // tag
+ content, // content
+ content, // fcontent
+ fmt.Sprintf("markdown %d", i), // markdown
+ len(content), // length
+ "p", // type
+ "", // subtype
+ "{: id=\"ial\"}", // ial
+ i, // sort
+ "20230101000000", // created
+ "20230101000000", // updated
}
}
@@ -429,10 +429,10 @@ func benchFTSQuery(b *testing.B, mode, keyword string) {
}
}
-func BenchmarkFTSQueryChineseStandard(b *testing.B) { benchFTSQuery(b, "standard", "中文") }
-func BenchmarkFTSQueryChineseExternal(b *testing.B) { benchFTSQuery(b, "external", "中文") }
-func BenchmarkFTSQueryEnglishStandard(b *testing.B) { benchFTSQuery(b, "standard", "code") }
-func BenchmarkFTSQueryEnglishExternal(b *testing.B) { benchFTSQuery(b, "external", "code") }
+func BenchmarkFTSQueryChineseStandard(b *testing.B) { benchFTSQuery(b, "standard", "中文") }
+func BenchmarkFTSQueryChineseExternal(b *testing.B) { benchFTSQuery(b, "external", "中文") }
+func BenchmarkFTSQueryEnglishStandard(b *testing.B) { benchFTSQuery(b, "standard", "code") }
+func BenchmarkFTSQueryEnglishExternal(b *testing.B) { benchFTSQuery(b, "external", "code") }
// TestFTSBenchStorage 是普通测试(非 benchmark),打印两种模式下的数据库文件大小对比。
func TestFTSBenchStorage(t *testing.T) {
diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.go
index c33c71e4b8..7944929df3 100644
--- a/kernel/treenode/blocktree.go
+++ b/kernel/treenode/blocktree.go
@@ -297,12 +297,27 @@ func ExistBlockTree(id string) bool {
err := queryRow(sqlStmt, id).Scan(&count)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
+ // 全局未命中,遍历加密 box
+ for _, encBoxID := range GetOpenedEncryptedBoxIDs() {
+ if ExistBlockTreeInBox(id, encBoxID) {
+ return true
+ }
+ }
return false
}
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return false
}
- return 0 < count
+ if 0 < count {
+ return true
+ }
+ // 全局未命中,遍历加密 box
+ for _, encBoxID := range GetOpenedEncryptedBoxIDs() {
+ if ExistBlockTreeInBox(id, encBoxID) {
+ return true
+ }
+ }
+ return false
}
func ExistBlockTrees(ids []string) (ret map[string]bool) {
@@ -408,6 +423,12 @@ func GetBlockTree(id string) (ret *BlockTree) {
if err != nil {
ret = nil
if errors.Is(err, sql.ErrNoRows) {
+ // 全局 blocktree 未命中,遍历已打开的加密 box 查找
+ for _, encBoxID := range GetOpenedEncryptedBoxIDs() {
+ if encBT := GetBlockTreeInBox(id, encBoxID); nil != encBT {
+ return encBT
+ }
+ }
return
}
logging.LogErrorf("sql query [%s] failed: %v\n\t%s", sqlStmt, err, logging.ShortStack())
diff --git a/kernel/treenode/tree.go b/kernel/treenode/tree.go
index 779d4edffd..9e8be75174 100644
--- a/kernel/treenode/tree.go
+++ b/kernel/treenode/tree.go
@@ -92,6 +92,14 @@ func IALStr(n *ast.Node) string {
func RootChildIDs(rootID string) (ret []string) {
root := GetBlockTree(rootID)
+ if nil == root {
+ for _, encBoxID := range GetOpenedEncryptedBoxIDs() {
+ if encRoot := GetBlockTreeInBox(rootID, encBoxID); nil != encRoot {
+ root = encRoot
+ break
+ }
+ }
+ }
if nil == root {
return
}