Skip to content

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

:recycle: Limit block order API to documents https://github.com/siyuan-note/siyuan/issues/18416

Danielb6dca125fab2
diff --git a/kernel/api/block.go b/kernel/api/block.go
index e59d9b390e..8b68978cac 100644
--- a/kernel/api/block.go
+++ b/kernel/api/block.go
@@ -827,7 +827,7 @@ func getBlocksIndexes(c *gin.Context) {
ret.Data = index
}
-func getBlocksOrders(c *gin.Context) {
+func getDocBlocksOrders(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
@@ -836,50 +836,15 @@ func getBlocksOrders(c *gin.Context) {
return
}
- _, hasID := arg["id"]
- _, hasIDs := arg["ids"]
- if hasID == hasIDs {
- ret.Code = -1
- ret.Msg = "Exactly one of [id] and [ids] must be provided"
+ var id string
+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) || util.InvalidIDPattern(id, ret) {
return
}
-
- var id string
- var ids []string
- if hasID {
- if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) || util.InvalidIDPattern(id, ret) {
- return
- }
- if !checkBlockPublishAccess(c, id, ret) {
- return
- }
- } else {
- var idsArg []any
- if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("ids", &idsArg, true, false)) {
- return
- }
-
- seen := map[string]struct{}{}
- for _, idArg := range idsArg {
- idStr, isString := idArg.(string)
- if !isString {
- ret.Code = -1
- ret.Msg = "Field [ids] should contain only strings"
- return
- }
- if !ast.IsNodeIDPattern(idStr) {
- continue
- }
- if _, added := seen[idStr]; added {
- continue
- }
- seen[idStr] = struct{}{}
- ids = append(ids, idStr)
- }
- ids = filterBlockIDsByPublishAccess(c, ids, "")
+ if !checkBlockPublishAccess(c, id, ret) {
+ return
}
- orders, err := model.GetBlocksOrders(id, ids)
+ orders, err := model.GetDocBlocksOrders(id)
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
diff --git a/kernel/api/block_test.go b/kernel/api/block_test.go
index a76c90b89d..cc14cd4974 100644
--- a/kernel/api/block_test.go
+++ b/kernel/api/block_test.go
@@ -93,55 +93,35 @@ func TestFilterBlockIDsByPublishAccess(t *testing.T) {
}
}
-func TestGetBlocksOrdersArguments(t *testing.T) {
+func TestGetDocBlocksOrdersArguments(t *testing.T) {
tests := []struct {
- name string
- body string
- expectedCode int
- expectEmpty bool
+ name string
+ body string
}{
- {name: "missing mode", body: `{}`, expectedCode: -1},
- {
- name: "mutually exclusive modes",
- body: `{"id":"20260728000200-doc0001","ids":[]}`,
- expectedCode: -1,
- },
- {name: "empty IDs", body: `{"ids":[]}`, expectedCode: 0, expectEmpty: true},
- {name: "invalid IDs are ignored", body: `{"ids":["invalid"]}`, expectedCode: 0, expectEmpty: true},
- {name: "non-string ID", body: `{"ids":[1]}`, expectedCode: -1},
- {name: "wrong document ID type", body: `{"id":1}`, expectedCode: -1},
- {name: "invalid document ID", body: `{"id":"invalid"}`, expectedCode: -1},
- {name: "null document ID", body: `{"id":null}`, expectedCode: -1},
- {name: "null IDs", body: `{"ids":null}`, expectedCode: -1},
+ {name: "missing document ID", body: `{}`},
+ {name: "IDs only", body: `{"ids":[]}`},
+ {name: "wrong document ID type", body: `{"id":1}`},
+ {name: "invalid document ID", body: `{"id":"invalid"}`},
+ {name: "null document ID", body: `{"id":null}`},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
- response := postBlocksOrders(t, test.body)
- if test.expectedCode != response.Code {
- t.Fatalf("unexpected response code: expected %d, got %d, message %q",
- test.expectedCode, response.Code, response.Msg)
- }
- if test.expectEmpty {
- var ids []string
- if err := json.Unmarshal(response.Data, &ids); err != nil {
- t.Fatalf("unmarshal block orders failed: %v", err)
- }
- if nil == ids || 0 != len(ids) {
- t.Fatalf("expected an empty non-nil block order list, got %v", ids)
- }
+ response := postDocBlocksOrders(t, test.body)
+ if -1 != response.Code {
+ t.Fatalf("unexpected response code: expected -1, got %d, message %q", response.Code, response.Msg)
}
})
}
}
-type blocksOrdersResponse struct {
+type docBlocksOrdersResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data json.RawMessage `json:"data"`
}
-func postBlocksOrders(t *testing.T, body string) *blocksOrdersResponse {
+func postDocBlocksOrders(t *testing.T, body string) *docBlocksOrdersResponse {
t.Helper()
gin.SetMode(gin.TestMode)
@@ -150,14 +130,14 @@ func postBlocksOrders(t *testing.T, body string) *blocksOrdersResponse {
c.Set(model.RoleContextKey, model.RoleAdministrator)
c.Next()
})
- engine.POST("/api/block/getBlocksOrders", getBlocksOrders)
+ engine.POST("/api/block/getDocBlocksOrders", getDocBlocksOrders)
recorder := httptest.NewRecorder()
- request := httptest.NewRequest(http.MethodPost, "/api/block/getBlocksOrders", strings.NewReader(body))
+ request := httptest.NewRequest(http.MethodPost, "/api/block/getDocBlocksOrders", strings.NewReader(body))
request.Header.Set("Content-Type", "application/json")
engine.ServeHTTP(recorder, request)
- response := &blocksOrdersResponse{}
+ response := &docBlocksOrdersResponse{}
if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
t.Fatalf("unmarshal response failed: %v", err)
}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 8f279e2eed..53ec08c23a 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -237,7 +237,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/block/getBlockBreadcrumbChildren", model.CheckAuth, getBlockBreadcrumbChildren)
ginServer.Handle("POST", "/api/block/getBlockIndex", model.CheckAuth, getBlockIndex)
ginServer.Handle("POST", "/api/block/getBlocksIndexes", model.CheckAuth, getBlocksIndexes)
- ginServer.Handle("POST", "/api/block/getBlocksOrders", model.CheckAuth, getBlocksOrders)
+ ginServer.Handle("POST", "/api/block/getDocBlocksOrders", model.CheckAuth, getDocBlocksOrders)
ginServer.Handle("POST", "/api/block/getRefIDs", model.CheckAuth, getRefIDs)
ginServer.Handle("POST", "/api/block/getRefIDsByFileAnnotationID", model.CheckAuth, getRefIDsByFileAnnotationID)
ginServer.Handle("POST", "/api/block/getBlockDefIDsByRefText", model.CheckAuth, getBlockDefIDsByRefText)
diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.go
index 1bda3b7751..14728612b7 100644
--- a/kernel/model/blockinfo.go
+++ b/kernel/model/blockinfo.go
@@ -528,59 +528,33 @@ func GetBlocksIndexes(ids []string) (ret map[string]int) {
return
}
-func GetBlocksOrders(id string, ids []string) (ret []string, err error) {
+func GetDocBlocksOrders(id string) (ret []string, err error) {
ret = []string{}
- var tree *parse.Tree
- var included map[string]struct{}
- if "" != id {
- tree, err = LoadTreeByBlockID(id)
- if err != nil {
- return
- }
- if nil == tree || nil == tree.Root {
- err = ErrTreeNotFound
- return
- }
- if tree.Root.ID != id {
- err = fmt.Errorf("block [%s] is not a document", id)
- return
- }
- } else {
- for _, blockID := range ids {
- if !ast.IsNodeIDPattern(blockID) {
- continue
- }
- tree, _ = LoadTreeByBlockID(blockID)
- if nil != tree {
- break
- }
- }
- if nil == tree {
- return
- }
-
- included = map[string]struct{}{}
- for _, blockID := range ids {
- included[blockID] = struct{}{}
- }
+ tree, err := LoadTreeByBlockID(id)
+ if err != nil {
+ return
+ }
+ if nil == tree || nil == tree.Root {
+ err = ErrTreeNotFound
+ return
+ }
+ if tree.Root.ID != id {
+ err = fmt.Errorf("block [%s] is not a document", id)
+ return
}
- ret = getBlocksOrdersInTree(tree, included)
+ ret = getDocBlocksOrdersInTree(tree)
return
}
-func getBlocksOrdersInTree(tree *parse.Tree, included map[string]struct{}) (ret []string) {
+func getDocBlocksOrdersInTree(tree *parse.Tree) (ret []string) {
ret = []string{}
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || n == tree.Root || !n.IsBlock() || ast.NodeKramdownBlockIAL == n.Type || "" == n.ID {
return ast.WalkContinue
}
- if nil == included {
- ret = append(ret, n.ID)
- } else if _, ok := included[n.ID]; ok {
- ret = append(ret, n.ID)
- }
+ ret = append(ret, n.ID)
return ast.WalkContinue
})
return
diff --git a/kernel/model/blockinfo_test.go b/kernel/model/blockinfo_test.go
index f22a0df89b..6b77b03ead 100644
--- a/kernel/model/blockinfo_test.go
+++ b/kernel/model/blockinfo_test.go
@@ -104,7 +104,7 @@ func assertBlockBreadcrumbChildIDs(t *testing.T, node *ast.Node, expected []stri
}
}
-func TestGetBlocksOrdersInTree(t *testing.T) {
+func TestGetDocBlocksOrdersInTree(t *testing.T) {
root := &ast.Node{Type: ast.NodeDocument, ID: "doc"}
list := &ast.Node{Type: ast.NodeList, ID: "list"}
item := &ast.Node{Type: ast.NodeListItem, ID: "item"}
@@ -127,30 +127,17 @@ func TestGetBlocksOrdersInTree(t *testing.T) {
tree := &parse.Tree{Root: root}
expected := []string{"list", "item", "paragraph", "blockquote", "quote-paragraph", "table"}
- if actual := getBlocksOrdersInTree(tree, nil); !reflect.DeepEqual(expected, actual) {
+ if actual := getDocBlocksOrdersInTree(tree); !reflect.DeepEqual(expected, actual) {
t.Fatalf("unexpected document block orders: expected %v, got %v", expected, actual)
}
-
- included := map[string]struct{}{
- "quote-paragraph": {},
- "item": {},
- "table-row": {},
- "missing": {},
- }
- expected = []string{"item", "quote-paragraph"}
- if actual := getBlocksOrdersInTree(tree, included); !reflect.DeepEqual(expected, actual) {
- t.Fatalf("unexpected filtered block orders: expected %v, got %v", expected, actual)
- }
}
-func TestGetBlocksOrders(t *testing.T) {
+func TestGetDocBlocksOrders(t *testing.T) {
const (
boxID = "20260728000100-box0001"
doc1ID = "20260728000101-doc0001"
child1ID = "20260728000102-para001"
child1BID = "20260728000103-para002"
- doc2ID = "20260728000104-doc0002"
- child2ID = "20260728000105-para003"
)
previousDataDir := util.DataDir
@@ -159,20 +146,15 @@ func TestGetBlocksOrders(t *testing.T) {
util.BlockTreeDBPath = filepath.Join(util.DataDir, "blocktree.db")
treenode.InitBlockTree(true)
- tree1 := newBlocksOrdersTestTree(boxID, doc1ID, []string{child1ID, child1BID})
- tree2 := newBlocksOrdersTestTree(boxID, doc2ID, []string{child2ID})
- for _, tree := range []*parse.Tree{tree1, tree2} {
- if _, err := filesys.WriteTree(tree); err != nil {
- t.Fatalf("write test tree failed: %v", err)
- }
- treenode.UpsertBlockTree(tree)
+ tree1 := newDocBlocksOrdersTestTree(boxID, doc1ID, []string{child1ID, child1BID})
+ if _, err := filesys.WriteTree(tree1); err != nil {
+ t.Fatalf("write test tree failed: %v", err)
}
+ treenode.UpsertBlockTree(tree1)
t.Cleanup(func() {
- for _, tree := range []*parse.Tree{tree1, tree2} {
- cache.RemoveTreeDataInBox(tree.ID, tree.Box)
- cache.RemoveDocIALInBox(tree.Path, tree.Box)
- }
+ cache.RemoveTreeDataInBox(tree1.ID, tree1.Box)
+ cache.RemoveDocIALInBox(tree1.Path, tree1.Box)
treenode.CloseDatabase()
util.DataDir = previousDataDir
util.BlockTreeDBPath = previousBlockTreeDBPath
@@ -182,7 +164,7 @@ func TestGetBlocksOrders(t *testing.T) {
})
expected := []string{child1ID, child1BID}
- actual, err := GetBlocksOrders(doc1ID, nil)
+ actual, err := GetDocBlocksOrders(doc1ID)
if err != nil {
t.Fatalf("get document block orders failed: %v", err)
}
@@ -190,28 +172,12 @@ func TestGetBlocksOrders(t *testing.T) {
t.Fatalf("unexpected document block orders: expected %v, got %v", expected, actual)
}
- actual, err = GetBlocksOrders("", []string{"invalid", child1BID, child2ID, child1ID, child1ID, doc1ID})
- if err != nil {
- t.Fatalf("get filtered block orders failed: %v", err)
- }
- if !reflect.DeepEqual(expected, actual) {
- t.Fatalf("unexpected filtered block orders: expected %v, got %v", expected, actual)
- }
-
- if _, err = GetBlocksOrders(child1ID, nil); nil == err {
+ if _, err = GetDocBlocksOrders(child1ID); nil == err {
t.Fatal("expected a non-document ID to be rejected")
}
-
- actual, err = GetBlocksOrders("", []string{})
- if err != nil {
- t.Fatalf("get empty block orders failed: %v", err)
- }
- if nil == actual || 0 != len(actual) {
- t.Fatalf("expected an empty non-nil result, got %v", actual)
- }
}
-func newBlocksOrdersTestTree(boxID, docID string, childIDs []string) *parse.Tree {
+func newDocBlocksOrdersTestTree(boxID, docID string, childIDs []string) *parse.Tree {
tree := treenode.NewTree(boxID, "/"+docID+".sy", "/Test", "Test")
tree.Root.FirstChild.Unlink()
for _, childID := range childIDs {