Skip to content

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

:art: Use notebook IDs for top-level notebook documents https://github.com/siyuan-note/siyuan/issues/18266

Danieldc5051e0b3ce
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index 9f2d62ad74..c997d31635 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -955,7 +955,7 @@ export class Files extends Model {
}
private updateDocInfo(data: IWebSocketData) {
- const notebook = window.siyuan.notebooks.find((item) => item.boxDocID === data.data.rootID);
+ const notebook = window.siyuan.notebooks.find((item) => item.id === data.data.rootID);
const subFileCount = notebook && window.siyuan.isPublish ? notebook.subFileCount : data.data.subFileCount;
if (notebook) {
notebook.subFileCount = subFileCount;
@@ -1056,7 +1056,7 @@ export class Files extends Model {
const iconContent = (item.encrypted && item.closed)
? "🔒️"
: unicode2Emoji(item.icon || window.siyuan.storage[Constants.LOCAL_IMAGES].note);
- const isBoxDoc = !item.closed && window.siyuan.config.fileTree.boxDocEnabled && Boolean(item.boxDocID);
+ const isBoxDoc = !item.closed && window.siyuan.config.fileTree.boxDocEnabled;
const hasChildren = isBoxDoc && item.subFileCount > 0;
const iconUsesDocAction = isBoxDoc && window.siyuan.config.fileTree.docIconClickExpand;
const iconAriaLabel = iconUsesDocAction ?
@@ -1065,7 +1065,7 @@ export class Files extends Model {
const actionClasses = `${iconUsesDocAction && hasChildren && !editingPublishAccess ? " file-tree__item--icon-expand" : ""}${
iconUsesDocAction && !hasChildren && !editingPublishAccess ? " file-tree__item--icon-open" : ""}${
hasChildren && window.siyuan.config.fileTree.parentDocClickExpand ? " file-tree__item--title-expand" : ""}`;
- const emojiHTML = `<span class="b3-list-item__icon ariaLabel${isBoxDoc ? " popover__block" : ""}${editingPublishAccess ? " fn__none" : ""}" data-position="8east"${isBoxDoc ? ` data-id="${item.boxDocID}"` : ""} aria-label="${iconAriaLabel}">${iconContent}</span>`;
+ const emojiHTML = `<span class="b3-list-item__icon ariaLabel${isBoxDoc ? " popover__block" : ""}${editingPublishAccess ? " fn__none" : ""}" data-position="8east"${isBoxDoc ? ` data-id="${item.id}"` : ""} aria-label="${iconAriaLabel}">${iconContent}</span>`;
const switchHTML = `<span class="b3-list-item__switch b3-tooltips b3-tooltips__e${editingPublishAccess ? "" : " fn__none"}" aria-label="${window.siyuan.languages.publishAccess}">${getPublishAccessOptionByLevel("public").iconHTML}</span>`;
if (item.closed) {
return `<li data-url="${item.id}" class="b3-list-item b3-list-item--hide-action"${item.encrypted ? ' data-encrypted="true"' : ""}>
@@ -1083,7 +1083,7 @@ export class Files extends Model {
return `<ul class="b3-list b3-list--background" data-url="${item.id}" data-sort="${item.sort}" data-sortmode="${item.sortMode}">
<li class="b3-list-item b3-list-item--hide-action${actionClasses}" ${window.siyuan.config.fileTree.sort === 6 ? 'draggable="true"' : ""}
style="--file-toggle-width:22px;--file-action-offset:22px"
-data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}" data-node-id="${window.siyuan.config.fileTree.boxDocEnabled ? (item.boxDocID || "") : ""}">
+data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}" data-node-id="${window.siyuan.config.fileTree.boxDocEnabled ? item.id : ""}">
<span class="b3-list-item__toggle b3-list-item__toggle--hl${isBoxDoc && !hasChildren ? " fn__hidden" : ""}">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
</span>
@@ -1464,9 +1464,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
// 有文件树和编辑器的布局初始化时,文件树还未挂载
return;
}
- const boxDocID = window.siyuan.config.fileTree.boxDocEnabled
- ? window.siyuan.notebooks.find((item) => item.id === notebookId)?.boxDocID
- : "";
+ const boxDocID = window.siyuan.config.fileTree.boxDocEnabled ? notebookId : "";
if (boxDocID && filePath === `/${boxDocID}.sy`) {
const boxDocElement = treeElement.querySelector("[data-type=\"navigation-root\"]") as HTMLElement;
if (isSetCurrent) {
diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.ts
index bca4293872..dee7f11b4b 100644
--- a/app/src/mobile/dock/MobileFiles.ts
+++ b/app/src/mobile/dock/MobileFiles.ts
@@ -639,7 +639,7 @@ export class MobileFiles extends Model {
}
private updateDocInfo(data: IWebSocketData) {
- const notebook = window.siyuan.notebooks.find((item) => item.boxDocID === data.data.rootID);
+ const notebook = window.siyuan.notebooks.find((item) => item.id === data.data.rootID);
const subFileCount = notebook && window.siyuan.isPublish ? notebook.subFileCount : data.data.subFileCount;
if (notebook) {
notebook.subFileCount = subFileCount;
@@ -682,7 +682,7 @@ export class MobileFiles extends Model {
const iconContent = (item.encrypted && item.closed)
? "🔒️"
: unicode2Emoji(item.icon || window.siyuan.storage[Constants.LOCAL_IMAGES].note);
- const isBoxDoc = !item.closed && window.siyuan.config.fileTree.boxDocEnabled && Boolean(item.boxDocID);
+ const isBoxDoc = !item.closed && window.siyuan.config.fileTree.boxDocEnabled;
const hasChildren = isBoxDoc && item.subFileCount > 0;
const iconAriaLabel = isBoxDoc ?
(hasChildren ? window.siyuan.languages.docIconClickExpand : window.siyuan.languages.openDocument) :
@@ -703,7 +703,7 @@ export class MobileFiles extends Model {
</li>`;
} else {
return `<ul class="b3-list b3-list--background" data-url="${item.id}" data-sortmode="${item.sortMode}">
-<li class="b3-list-item" data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}" data-node-id="${window.siyuan.config.fileTree.boxDocEnabled ? (item.boxDocID || "") : ""}" style="--file-toggle-width:24px">
+<li class="b3-list-item" data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}" data-node-id="${window.siyuan.config.fileTree.boxDocEnabled ? item.id : ""}" style="--file-toggle-width:24px">
<span class="b3-list-item__toggle${isBoxDoc && !hasChildren ? " fn__hidden" : ""}">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
</span>
@@ -1080,9 +1080,7 @@ export class MobileFiles extends Model {
// 有文件树和编辑器的布局初始化时,文件树还未挂载
return;
}
- const boxDocID = window.siyuan.config.fileTree.boxDocEnabled
- ? window.siyuan.notebooks.find((item) => item.id === notebookId)?.boxDocID
- : "";
+ const boxDocID = window.siyuan.config.fileTree.boxDocEnabled ? notebookId : "";
if (boxDocID && filePath === `/${boxDocID}.sy`) {
const boxDocElement = treeElement.querySelector("[data-type=\"navigation-root\"]") as HTMLElement;
if (isSetCurrent) {
diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.ts
index 0450b1e7e7..3205754996 100644
--- a/app/src/protyle/header/openTitleMenu.ts
+++ b/app/src/protyle/header/openTitleMenu.ts
@@ -44,7 +44,7 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: stri
fetchPost("/api/block/getDocInfo", docInfoParam, (response) => {
window.siyuan.menus.menu.remove();
window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_TITLE);
- const isBoxDoc = window.siyuan.notebooks.find((item) => item.id === protyle.notebookId)?.boxDocID === protyle.block.rootID;
+ const isBoxDoc = protyle.notebookId === protyle.block.rootID;
const popoverElement = hasTopClosestByClassName(protyle.element, "block__popover", true);
window.siyuan.menus.menu.element.setAttribute("data-from", popoverElement ? popoverElement.dataset.level + "popover-" + from : "app-" + from);
const submenu = copySubMenu([protyle.block.rootID], true, undefined, protyle.block.showAll ? protyle.block.id : protyle.block.rootID);
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index ee2c33bbfd..3582aebb35 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -518,7 +518,6 @@ interface IEmoji {
interface INotebook {
name: string;
id: string;
- boxDocID: string;
closed: boolean;
icon: string;
sort: number;
diff --git a/kernel/api/notebook.go b/kernel/api/notebook.go
index 809709e62c..8481df1b7a 100644
--- a/kernel/api/notebook.go
+++ b/kernel/api/notebook.go
@@ -467,11 +467,11 @@ func lsNotebooks(c *gin.Context) {
boxDocEnabled := model.IsBoxDocEnabled()
if !flashcard && boxDocEnabled {
for _, notebook := range notebooks {
- if !notebook.Closed && notebook.BoxDocID != "" {
+ if !notebook.Closed {
if isReadOnlyRole {
- notebook.SubFileCount = model.BoxDocSubFileCountForPublish(notebook.ID, notebook.BoxDocID, publishAccess)
+ notebook.SubFileCount = model.BoxDocSubFileCountForPublish(notebook.ID, publishAccess)
} else {
- notebook.SubFileCount = model.BoxDocSubFileCount(notebook.ID, notebook.BoxDocID)
+ notebook.SubFileCount = model.BoxDocSubFileCount(notebook.ID)
}
}
}
diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.go
index 82228fc88d..a23e4f8fe5 100644
--- a/kernel/model/blockinfo.go
+++ b/kernel/model/blockinfo.go
@@ -136,7 +136,7 @@ func GetDocInfoInBox(blockID, boxID string) (ret *BlockInfo, err error) {
var subFileCount int
if IsBoxDoc(tree.Box, tree.ID) {
- subFileCount = BoxDocSubFileCount(tree.Box, tree.ID)
+ subFileCount = BoxDocSubFileCount(tree.Box)
} else {
boxLocalPath := filepath.Join(util.DataDir, tree.Box)
subFiles, readErr := os.ReadDir(filepath.Join(boxLocalPath, strings.TrimSuffix(tree.Path, ".sy")))
@@ -244,7 +244,7 @@ func GetDocsInfo(blockIDs []string, queryRefCount bool, queryAv bool) (rets []*B
var subFileCount int
if IsBoxDoc(tree.Box, tree.ID) {
- subFileCount = BoxDocSubFileCount(tree.Box, tree.ID)
+ subFileCount = BoxDocSubFileCount(tree.Box)
} else {
boxLocalPath := filepath.Join(util.DataDir, tree.Box)
subFiles, readErr := os.ReadDir(filepath.Join(boxLocalPath, strings.TrimSuffix(tree.Path, ".sy")))
diff --git a/kernel/model/box.go b/kernel/model/box.go
index ad64c31e51..69c10104f9 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -50,7 +50,6 @@ import (
// Box 笔记本。
type Box struct {
ID string `json:"id"`
- BoxDocID string `json:"boxDocID"`
Name string `json:"name"`
Icon string `json:"icon"`
Sort int `json:"sort"`
@@ -165,18 +164,8 @@ func ListNotebooks() (ret []*Box, err error) {
icon = util.FilterUploadEmojiFileName(icon)
}
- var boxDocID string
- if !boxConf.Encrypted && !IsUserGuide(id) {
- var readBoxDocErr error
- boxDocID, readBoxDocErr = readBoxDocID(id)
- if nil != readBoxDocErr {
- logging.LogErrorf("read box document metadata [%s] failed: %s", id, readBoxDocErr)
- }
- }
-
box := &Box{
ID: id,
- BoxDocID: boxDocID,
Name: boxConf.Name,
Icon: icon,
Sort: boxConf.Sort,
@@ -516,7 +505,7 @@ func (box *Box) GetInfo() (ret *BoxInfo) {
continue
}
- if id != box.BoxDocID {
+ if id != box.ID {
ret.DocCount++
}
ret.Size += uint64(info.Size())
diff --git a/kernel/model/box_doc.go b/kernel/model/box_doc.go
index 8fabb47d34..6f40cce05f 100644
--- a/kernel/model/box_doc.go
+++ b/kernel/model/box_doc.go
@@ -17,7 +17,6 @@
package model
import (
- "crypto/sha256"
"errors"
"fmt"
"os"
@@ -51,11 +50,11 @@ func boxDocMetaPath(boxID string) string {
return filepath.Join(util.DataDir, boxID, ".siyuan", boxDocMetaName)
}
-func boxDocPath(boxDocID string) string {
- if "" == boxDocID {
+func boxDocPath(boxID string) string {
+ if "" == boxID {
return ""
}
- return "/" + boxDocID + ".sy"
+ return "/" + boxID + ".sy"
}
func readBoxDocID(boxID string) (ret string, err error) {
@@ -77,11 +76,14 @@ func readBoxDocID(boxID string) (ret string, err error) {
if !ast.IsNodeIDPattern(meta.BoxDocID) {
return "", fmt.Errorf("invalid box document ID [%s]", meta.BoxDocID)
}
- return meta.BoxDocID, nil
+ if boxID != meta.BoxDocID {
+ return "", fmt.Errorf("box document ID [%s] does not match box ID [%s]", meta.BoxDocID, boxID)
+ }
+ return boxID, nil
}
-func writeBoxDocID(boxID, boxDocID string) error {
- meta := &boxDocMeta{Spec: boxDocMetaSpec, BoxDocID: boxDocID}
+func writeBoxDocID(boxID string) error {
+ meta := &boxDocMeta{Spec: boxDocMetaSpec, BoxDocID: boxID}
data, err := gulu.JSON.MarshalIndentJSON(meta, "", " ")
if err != nil {
return fmt.Errorf("marshal box document metadata failed: %w", err)
@@ -89,25 +91,6 @@ func writeBoxDocID(boxID, boxDocID string) error {
return filelock.WriteFile(boxDocMetaPath(boxID), data)
}
-// deterministicBoxDocID 保证多台离线设备迁移同一笔记本时生成相同的文档 ID。
-func deterministicBoxDocID(boxID string) string {
- if !ast.IsNodeIDPattern(boxID) {
- return ""
- }
-
- const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
- digest := sha256.Sum256([]byte("siyuan-box-doc:" + boxID))
- suffix := make([]byte, 7)
- for i := range suffix {
- suffix[i] = alphabet[int(digest[i])%len(alphabet)]
- }
- return boxID[:14] + "-" + string(suffix)
-}
-
-func supportsBoxDoc(boxID string) bool {
- return !IsUserGuide(boxID) && !IsEncryptedBox(boxID)
-}
-
func IsBoxDocEnabled() bool {
return nil != Conf && nil != Conf.FileTree && nil != Conf.FileTree.BoxDocEnabled && *Conf.FileTree.BoxDocEnabled
}
@@ -117,9 +100,7 @@ func hiddenBoxDocRootIDs() (ret []string) {
return
}
for _, box := range Conf.GetOpenedBoxes() {
- if "" != box.BoxDocID {
- ret = append(ret, box.BoxDocID)
- }
+ ret = append(ret, box.ID)
}
return
}
@@ -145,8 +126,8 @@ func EnsureBoxDoc(boxID string) (boxDocID string, err error) {
// ensureBoxDoc0 的调用方必须持有 createDocLock。
func ensureBoxDoc0(boxID string) (boxDocID string, err error) {
- if !supportsBoxDoc(boxID) {
- return
+ if !ast.IsNodeIDPattern(boxID) {
+ return "", fmt.Errorf("invalid box ID [%s]", boxID)
}
box := Conf.GetBox(boxID)
@@ -154,46 +135,42 @@ func ensureBoxDoc0(boxID string) (boxDocID string, err error) {
return "", ErrBoxNotFound
}
- boxDocID, err = readBoxDocID(boxID)
- if err != nil {
- logging.LogErrorf("read box document metadata [%s] failed: %s", boxID, err)
- return "", err
- }
- if "" != boxDocID {
- if !box.Exist(boxDocPath(boxDocID)) {
- return "", fmt.Errorf("box document [%s] is missing", boxDocID)
- }
- indexBoxDocIfNeeded(boxID, boxDocID)
- if err = reconcileBoxDoc(box, boxDocID); err != nil {
- return "", err
- }
- return
- }
if !IsBoxDocEnabled() {
return
}
+ boxDocID = boxID
boxDocID, err = findBoxDoc(box)
if err != nil {
return "", err
}
+ changed := false
if "" == boxDocID {
- boxDocID = deterministicBoxDocID(boxID)
- if "" == boxDocID {
- return "", fmt.Errorf("invalid box ID [%s]", boxID)
- }
+ boxDocID = boxID
if box.Exist(boxDocPath(boxDocID)) || nil != treenode.GetBlockTree(boxDocID) || "" != findUnindexedTreePathInAllBoxes(boxDocID) {
return "", fmt.Errorf("box document ID [%s] is already in use", boxDocID)
}
if err = createBoxDoc(box, boxDocID); err != nil {
return "", err
}
+ changed = true
+ } else {
+ indexBoxDocIfNeeded(boxID, boxDocID)
+ if err = reconcileBoxDoc(box, boxDocID); err != nil {
+ return "", err
+ }
}
- if err = writeBoxDocID(boxID, boxDocID); err != nil {
- return "", err
+ storedBoxDocID, _ := readBoxDocID(boxID)
+ if storedBoxDocID != boxID {
+ if err = writeBoxDocID(boxID); err != nil {
+ return "", err
+ }
+ changed = true
+ }
+ if changed {
+ IncSync()
}
- IncSync()
logging.LogInfof("initialized box document [box=%s, id=%s]", boxID, boxDocID)
return
}
@@ -210,10 +187,17 @@ func RefreshBoxDocFeature() {
}
func findBoxDoc(box *Box) (ret string, err error) {
- boxDocID := deterministicBoxDocID(box.ID)
- if "" == boxDocID || !box.Exist(boxDocPath(boxDocID)) {
+ boxDocID := box.ID
+ if !box.Exist(boxDocPath(boxDocID)) {
return
}
+ tree, err := filesys.LoadTree(box.ID, boxDocPath(boxDocID), util.NewLute())
+ if err != nil {
+ return "", err
+ }
+ if tree.ID != boxDocID || tree.Root.IALAttr(DocHiddenAttr) != "true" {
+ return "", fmt.Errorf("box document ID [%s] is already in use", boxDocID)
+ }
return boxDocID, nil
}
@@ -286,22 +270,19 @@ func reconcileBoxDoc(box *Box, boxDocID string) error {
}
// BoxDocSubFileCount 返回笔记本顶层文档的可见下级文档数。
-func BoxDocSubFileCount(boxID, boxDocID string) int {
- return boxDocSubFileCount(boxID, boxDocID, nil)
+func BoxDocSubFileCount(boxID string) int {
+ return boxDocSubFileCount(boxID, nil)
}
// BoxDocSubFileCountForPublish 返回发布访问控制下笔记本顶层文档的可见下级文档数。
-func BoxDocSubFileCountForPublish(boxID, boxDocID string, publishAccess PublishAccess) int {
+func BoxDocSubFileCountForPublish(boxID string, publishAccess PublishAccess) int {
publishIgnore := GetInvisiblePublishAccess(publishAccess)
- return boxDocSubFileCount(boxID, boxDocID, func(p string) bool {
+ return boxDocSubFileCount(boxID, func(p string) bool {
return CheckPathAccessableByPublishIgnore(boxID, p, publishIgnore)
})
}
-func boxDocSubFileCount(boxID, boxDocID string, include func(string) bool) int {
- if "" == boxDocID {
- return 0
- }
+func boxDocSubFileCount(boxID string, include func(string) bool) int {
entries, err := os.ReadDir(filepath.Join(util.DataDir, boxID))
if err != nil {
return 0
@@ -312,7 +293,7 @@ func boxDocSubFileCount(boxID, boxDocID string, include func(string) bool) int {
continue
}
id := strings.TrimSuffix(entry.Name(), ".sy")
- if id == boxDocID || !ast.IsNodeIDPattern(id) {
+ if id == boxID || !ast.IsNodeIDPattern(id) {
continue
}
p := "/" + entry.Name()
@@ -330,7 +311,7 @@ func boxDocSubFileCount(boxID, boxDocID string, include func(string) bool) int {
func IsBoxDoc(boxID, id string) bool {
box := Conf.Box(boxID)
- return nil != box && "" != box.BoxDocID && box.BoxDocID == id
+ return nil != box && box.ID == id
}
func IsBoxDocPath(boxID, p string) bool {
@@ -340,10 +321,10 @@ func IsBoxDocPath(boxID, p string) bool {
// normalizeBoxDocPath 将虚拟根文档下的路径映射到笔记本物理根路径。
func normalizeBoxDocPath(boxID, p string) string {
box := Conf.Box(boxID)
- if nil == box || "" == box.BoxDocID {
+ if nil == box {
return p
}
- prefix := "/" + box.BoxDocID + "/"
+ prefix := "/" + box.ID + "/"
if strings.HasPrefix(p, prefix) {
return "/" + strings.TrimPrefix(p, prefix)
}
@@ -352,10 +333,10 @@ func normalizeBoxDocPath(boxID, p string) string {
func normalizeBoxDocTarget(boxID, p string) string {
box := Conf.Box(boxID)
- if nil == box || "" == box.BoxDocID {
+ if nil == box {
return p
}
- if boxDocPath(box.BoxDocID) == p {
+ if boxDocPath(box.ID) == p {
return "/"
}
return normalizeBoxDocPath(boxID, p)
@@ -363,18 +344,18 @@ func normalizeBoxDocTarget(boxID, p string) string {
func renameBoxDoc(boxID, name string) error {
box := Conf.Box(boxID)
- if nil == box || "" == box.BoxDocID || !box.Exist(boxDocPath(box.BoxDocID)) {
+ if nil == box || !box.Exist(boxDocPath(box.ID)) {
return nil
}
- return renameDoc0(boxID, boxDocPath(box.BoxDocID), name)
+ return renameDoc0(boxID, boxDocPath(box.ID), name)
}
func setBoxDocIcon(boxID, icon string) error {
box := Conf.Box(boxID)
- if nil == box || "" == box.BoxDocID {
+ if nil == box || !box.Exist(boxDocPath(box.ID)) {
return nil
}
- tree, err := filesys.LoadTree(boxID, boxDocPath(box.BoxDocID), util.NewLute())
+ tree, err := filesys.LoadTree(boxID, boxDocPath(box.ID), util.NewLute())
if err != nil {
return err
}
diff --git a/kernel/model/box_doc_test.go b/kernel/model/box_doc_test.go
index ccc0dc092f..947b35a1b3 100644
--- a/kernel/model/box_doc_test.go
+++ b/kernel/model/box_doc_test.go
@@ -21,21 +21,64 @@ import (
"path/filepath"
"testing"
- "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
-func TestDeterministicBoxDocID(t *testing.T) {
+func TestBoxDocMetadataMatchesBoxID(t *testing.T) {
+ originalDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = originalDataDir
+ })
+
boxID := "20260716120000-abcdefg"
- boxDocID := deterministicBoxDocID(boxID)
- if !ast.IsNodeIDPattern(boxDocID) {
- t.Fatalf("invalid box document ID [%s]", boxDocID)
+ if err := os.MkdirAll(filepath.Dir(boxDocMetaPath(boxID)), 0755); err != nil {
+ t.Fatal(err)
}
- if boxDocID != deterministicBoxDocID(boxID) {
- t.Fatalf("box document ID is not deterministic [%s]", boxDocID)
+ if err := writeBoxDocID(boxID); err != nil {
+ t.Fatal(err)
+ }
+ if boxDocID, err := readBoxDocID(boxID); err != nil || boxDocID != boxID {
+ t.Fatalf("unexpected box document metadata [id=%s, err=%v]", boxDocID, err)
+ }
+
+ data := []byte(`{"spec":1,"boxDocID":"20260716120001-abcdefg"}`)
+ if err := os.WriteFile(boxDocMetaPath(boxID), data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readBoxDocID(boxID); err == nil {
+ t.Fatal("mismatched box document ID was accepted")
+ }
+}
+
+func TestFindBoxDocRejectsOrdinaryDocument(t *testing.T) {
+ originalDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = originalDataDir
+ })
+
+ boxID := "20260716120010-abcdefg"
+ if err := os.MkdirAll(filepath.Join(util.DataDir, boxID), 0755); err != nil {
+ t.Fatal(err)
+ }
+ tree := treenode.NewTree(boxID, boxDocPath(boxID), "/Existing", "Existing")
+ if _, err := filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ box := &Box{ID: boxID}
+ if _, err := findBoxDoc(box); err == nil {
+ t.Fatal("ordinary document was accepted as the box document")
+ }
+
+ tree.Root.SetIALAttr(DocHiddenAttr, "true")
+ if _, err := filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
}
- if boxDocID == deterministicBoxDocID("20260716120000-hijklmn") {
- t.Fatalf("different boxes generated the same document ID [%s]", boxDocID)
+ if boxDocID, err := findBoxDoc(box); err != nil || boxDocID != boxID {
+ t.Fatalf("unexpected recovered box document [id=%s, err=%v]", boxDocID, err)
}
}
@@ -47,7 +90,7 @@ func TestBoxDocSubFileCount(t *testing.T) {
})
boxID := "20260716120000-abcdefg"
- boxDocID := "20260716120001-abcdefg"
+ boxDocID := boxID
boxDir := filepath.Join(util.DataDir, boxID)
if err := os.MkdirAll(boxDir, 0755); err != nil {
t.Fatal(err)
@@ -67,15 +110,15 @@ func TestBoxDocSubFileCount(t *testing.T) {
t.Fatal(err)
}
- if actual := BoxDocSubFileCount(boxID, boxDocID); actual != 1 {
+ if actual := BoxDocSubFileCount(boxID); actual != 1 {
t.Fatalf("unexpected box document subfile count [%d]", actual)
}
publishAccess := PublishAccess{{ID: "20260716120002-abcdefg", Visible: false}}
- if actual := BoxDocSubFileCountForPublish(boxID, boxDocID, publishAccess); actual != 0 {
+ if actual := BoxDocSubFileCountForPublish(boxID, publishAccess); actual != 0 {
t.Fatalf("unexpected published box document subfile count [%d]", actual)
}
publishAccess[0].Visible = true
- if actual := BoxDocSubFileCountForPublish(boxID, boxDocID, publishAccess); actual != 1 {
+ if actual := BoxDocSubFileCountForPublish(boxID, publishAccess); actual != 1 {
t.Fatalf("unexpected visible published box document subfile count [%d]", actual)
}
}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 88400267a0..85d139740a 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -1120,7 +1120,7 @@ func (conf *AppConf) GetBoxes() (ret []*Box) {
name := notebook.Name
closed := notebook.Closed
encrypted := IsEncryptedBox(id) // 使用 IsEncryptedBox 统一判定(含 backup fallback)
- box := &Box{ID: id, BoxDocID: notebook.BoxDocID, Name: name, Closed: closed, Encrypted: encrypted}
+ box := &Box{ID: id, Name: name, Closed: closed, Encrypted: encrypted}
ret = append(ret, box)
}
return
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 6352eae276..07b4f08c06 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -357,7 +357,7 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden boo
boxLocalPath := filepath.Join(util.DataDir, box.ID)
var docs []*File
for _, file := range files {
- if "/" == listPath && "" != box.BoxDocID && box.BoxDocID == util.GetTreeID(file.path) {
+ if "/" == listPath && box.ID == util.GetTreeID(file.path) {
continue
}
if file.isdir {
@@ -1446,7 +1446,7 @@ func GetHPathsByPaths(paths []string) (hPaths []string, err error) {
continue
}
- if box.BoxDocID == bt.RootID {
+ if IsBoxDoc(box.ID, bt.RootID) {
hPaths = append(hPaths, box.Name)
} else {
hPaths = append(hPaths, box.Name+bt.HPath)
@@ -1490,7 +1490,7 @@ func GetFullHPathByID(id string) (hPath string, err error) {
err = ErrBoxNotFound
return
}
- if box.BoxDocID == tree.ID {
+ if IsBoxDoc(box.ID, tree.ID) {
hPath = box.Name
return
}
@@ -1501,8 +1501,8 @@ func GetFullHPathByID(id string) (hPath string, err error) {
func GetIDsByHPath(hpath, boxID string) (ret []string, err error) {
ret = []string{}
if IsBoxDocEnabled() && "/" == hpath {
- if box := Conf.Box(boxID); nil != box && "" != box.BoxDocID {
- return []string{box.BoxDocID}, nil
+ if box := Conf.Box(boxID); nil != box {
+ return []string{box.ID}, nil
}
}
roots := treenode.GetBlockTreeRootsByHPath(boxID, hpath)
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 199dca80c2..23302acccc 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -314,7 +314,7 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c
// Keep original creation time when importing .sy.zip https://github.com/siyuan-note/siyuan/issues/9923
newNodeID := util.TimeFromID(n.ID) + "-" + util.RandString(7)
if createNotebook && oldRootID == importedBoxDocID && n.ID == importedBoxDocID {
- newNodeID = deterministicBoxDocID(boxID)
+ newNodeID = boxID
}
blockIDs[n.ID] = newNodeID
n.ID = newNodeID
@@ -340,7 +340,7 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d", i+1, len(syPaths))))
}
if importedBoxDoc {
- if err = writeBoxDocID(boxID, deterministicBoxDocID(boxID)); err != nil {
+ if err = writeBoxDocID(boxID); err != nil {
return
}
}
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index 412ad102b0..499e6ea210 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -380,7 +380,7 @@ func Mount(boxID string) (alreadyMount bool, err error) {
// 缓存根一级的文档树展开
files, _, _ := ListDocTree(box.ID, "/", util.SortModeUnassigned, false, false, Conf.FileTree.MaxListCount)
box = Conf.Box(boxID)
- if 0 < len(files) || (nil != box && "" != box.BoxDocID) {
+ if 0 < len(files) || (nil != box && box.Exist(boxDocPath(box.ID))) {
box.Index()
}
diff --git a/kernel/model/path.go b/kernel/model/path.go
index d06603c7ee..ec4825216c 100644
--- a/kernel/model/path.go
+++ b/kernel/model/path.go
@@ -42,7 +42,7 @@ func createDocsByHPath(boxID, hPath, content, parentID, id string, titleEmpty bo
hPath = strings.TrimSuffix(hPath, ".sy")
hPath = util.TrimSpaceInPath(hPath)
if "" != parentID {
- if box := Conf.Box(boxID); nil != box && "" != box.BoxDocID && box.BoxDocID == parentID {
+ if IsBoxDoc(boxID, parentID) {
name := path.Base(hPath)
p := "/" + id + ".sy"
if _, err = createDoc(boxID, p, name, content, titleEmpty); err != nil {
diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.go
index c25204c0c9..1d3e35a896 100644
--- a/kernel/model/push_reload.go
+++ b/kernel/model/push_reload.go
@@ -138,7 +138,7 @@ func refreshBoxDocInfoByBoxID(boxID string) {
return
}
box := Conf.Box(boxID)
- if nil == box || "" == box.BoxDocID {
+ if nil == box {
return
}
util.BroadcastByType("filetree", "reloadNotebookInfo", 0, "", boxID)
@@ -155,7 +155,7 @@ func refreshDocInfo0(tree *parse.Tree, size uint64) {
subFileCount := 0
if IsBoxDoc(tree.Box, tree.ID) {
- subFileCount = BoxDocSubFileCount(tree.Box, tree.ID)
+ subFileCount = BoxDocSubFileCount(tree.Box)
} else if "true" != tree.Root.IALAttr(DocHiddenAttr) {
subDir := filepath.Join(util.DataDir, tree.Box, strings.TrimSuffix(tree.Path, ".sy"))
subFiles, err := os.ReadDir(subDir)