An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support block order API https://github.com/siyuan-note/siyuan/issues/18416
Daniel0e002ebbee81
diff --git a/kernel/api/block.go b/kernel/api/block.goindex dd9bffa2ec..e59d9b390e 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -827,6 +827,67 @@ func getBlocksIndexes(c *gin.Context) {ret.Data = index}+func getBlocksOrders(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }++ _, hasID := arg["id"]+ _, hasIDs := arg["ids"]+ if hasID == hasIDs {+ ret.Code = -1+ ret.Msg = "Exactly one of [id] and [ids] must be provided"+ 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, "")+ }++ orders, err := model.GetBlocksOrders(id, ids)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ ret.Data = orders+}+func getBlockInfo(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/block_test.go b/kernel/api/block_test.goindex b28c3aa722..a76c90b89d 100644--- a/kernel/api/block_test.go+++ b/kernel/api/block_test.go@@ -17,10 +17,12 @@package apiimport (+ "encoding/json""net/http""net/http/httptest""path/filepath""slices"+ "strings""testing""github.com/88250/lute/ast"@@ -90,3 +92,74 @@ func TestFilterBlockIDsByPublishAccess(t *testing.T) {t.Fatalf("administrator block IDs should remain unchanged: %v", filtered)}}++func TestGetBlocksOrdersArguments(t *testing.T) {+ tests := []struct {+ name string+ body string+ expectedCode int+ expectEmpty bool+ }{+ {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},+ }++ 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)+ }+ }+ })+ }+}++type blocksOrdersResponse struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data json.RawMessage `json:"data"`+}++func postBlocksOrders(t *testing.T, body string) *blocksOrdersResponse {+ t.Helper()++ gin.SetMode(gin.TestMode)+ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, model.RoleAdministrator)+ c.Next()+ })+ engine.POST("/api/block/getBlocksOrders", getBlocksOrders)++ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, "/api/block/getBlocksOrders", strings.NewReader(body))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)++ response := &blocksOrdersResponse{}+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {+ t.Fatalf("unmarshal response failed: %v", err)+ }+ return response+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 1ee3e2e5f3..8f279e2eed 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -237,6 +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/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.goindex 2e0ddf5d5d..1bda3b7751 100644--- a/kernel/model/blockinfo.go+++ b/kernel/model/blockinfo.go@@ -18,6 +18,7 @@ package modelimport ("errors"+ "fmt""os""path/filepath""sort"@@ -527,6 +528,64 @@ func GetBlocksIndexes(ids []string) (ret map[string]int) {return}+func GetBlocksOrders(id string, ids []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{}{}+ }+ }++ ret = getBlocksOrdersInTree(tree, included)+ return+}++func getBlocksOrdersInTree(tree *parse.Tree, included map[string]struct{}) (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)+ }+ return ast.WalkContinue+ })+ return+}+type BlockPath struct {ID string `json:"id"`Name string `json:"name"`diff --git a/kernel/model/blockinfo_test.go b/kernel/model/blockinfo_test.goindex 08065f4113..f22a0df89b 100644--- a/kernel/model/blockinfo_test.go+++ b/kernel/model/blockinfo_test.go@@ -1,10 +1,16 @@package modelimport (+ "path/filepath""reflect""testing""github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util")func TestWalkBlockBreadcrumbChildren(t *testing.T) {@@ -97,3 +103,119 @@ func assertBlockBreadcrumbChildIDs(t *testing.T, node *ast.Node, expected []strit.Fatalf("unexpected breadcrumb children: expected %v, got %v", expected, actual)}}++func TestGetBlocksOrdersInTree(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"}+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("content")})+ item.AppendChild(paragraph)+ list.AppendChild(item)++ blockquote := &ast.Node{Type: ast.NodeBlockquote, ID: "blockquote"}+ quoteParagraph := &ast.Node{Type: ast.NodeParagraph, ID: "quote-paragraph"}+ blockquote.AppendChild(quoteParagraph)++ table := &ast.Node{Type: ast.NodeTable, ID: "table"}+ table.AppendChild(&ast.Node{Type: ast.NodeTableRow, ID: "table-row"})+ emptyIDParagraph := &ast.Node{Type: ast.NodeParagraph}+ blockIAL := &ast.Node{Type: ast.NodeKramdownBlockIAL, ID: "block-ial"}+ for _, node := range []*ast.Node{list, blockquote, table, emptyIDParagraph, blockIAL} {+ root.AppendChild(node)+ }+ tree := &parse.Tree{Root: root}++ expected := []string{"list", "item", "paragraph", "blockquote", "quote-paragraph", "table"}+ if actual := getBlocksOrdersInTree(tree, nil); !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) {+ const (+ boxID = "20260728000100-box0001"+ doc1ID = "20260728000101-doc0001"+ child1ID = "20260728000102-para001"+ child1BID = "20260728000103-para002"+ doc2ID = "20260728000104-doc0002"+ child2ID = "20260728000105-para003"+ )++ previousDataDir := util.DataDir+ previousBlockTreeDBPath := util.BlockTreeDBPath+ util.DataDir = t.TempDir()+ 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)+ }++ t.Cleanup(func() {+ for _, tree := range []*parse.Tree{tree1, tree2} {+ cache.RemoveTreeDataInBox(tree.ID, tree.Box)+ cache.RemoveDocIALInBox(tree.Path, tree.Box)+ }+ treenode.CloseDatabase()+ util.DataDir = previousDataDir+ util.BlockTreeDBPath = previousBlockTreeDBPath+ if "" != previousBlockTreeDBPath {+ treenode.InitBlockTree(false)+ }+ })++ expected := []string{child1ID, child1BID}+ actual, err := GetBlocksOrders(doc1ID, nil)+ if err != nil {+ t.Fatalf("get document block orders failed: %v", err)+ }+ if !reflect.DeepEqual(expected, actual) {+ 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 {+ 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 {+ tree := treenode.NewTree(boxID, "/"+docID+".sy", "/Test", "Test")+ tree.Root.FirstChild.Unlink()+ for _, childID := range childIDs {+ tree.Root.AppendChild(treenode.NewParagraph(childID))+ }+ return tree+}