tree.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // SiYuan - Refactor your thinking
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package model
  17. import (
  18. "errors"
  19. "io/fs"
  20. "os"
  21. "path"
  22. "path/filepath"
  23. "strings"
  24. "time"
  25. "github.com/88250/lute"
  26. "github.com/88250/lute/ast"
  27. "github.com/88250/lute/parse"
  28. "github.com/siyuan-note/filelock"
  29. "github.com/siyuan-note/logging"
  30. "github.com/siyuan-note/siyuan/kernel/av"
  31. "github.com/siyuan-note/siyuan/kernel/filesys"
  32. "github.com/siyuan-note/siyuan/kernel/sql"
  33. "github.com/siyuan-note/siyuan/kernel/task"
  34. "github.com/siyuan-note/siyuan/kernel/treenode"
  35. "github.com/siyuan-note/siyuan/kernel/util"
  36. "golang.org/x/time/rate"
  37. )
  38. func resetTree(tree *parse.Tree, titleSuffix string) {
  39. tree.ID = ast.NewNodeID()
  40. tree.Root.ID = tree.ID
  41. if "" != titleSuffix {
  42. if t, parseErr := time.Parse("20060102150405", util.TimeFromID(tree.ID)); nil == parseErr {
  43. titleSuffix += " " + t.Format("2006-01-02 15:04:05")
  44. } else {
  45. titleSuffix = "Duplicated " + time.Now().Format("2006-01-02 15:04:05")
  46. }
  47. titleSuffix = "(" + titleSuffix + ")"
  48. titleSuffix = " " + titleSuffix
  49. }
  50. tree.Root.SetIALAttr("id", tree.ID)
  51. tree.Root.SetIALAttr("title", tree.Root.IALAttr("title")+titleSuffix)
  52. tree.Root.RemoveIALAttr("scroll")
  53. p := path.Join(path.Dir(tree.Path), tree.ID) + ".sy"
  54. tree.Path = p
  55. tree.HPath = tree.HPath + " " + titleSuffix
  56. // 收集所有引用
  57. refIDs := map[string]string{}
  58. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  59. if !entering || !treenode.IsBlockRef(n) {
  60. return ast.WalkContinue
  61. }
  62. defID, _, _ := treenode.GetBlockRef(n)
  63. if "" == defID {
  64. return ast.WalkContinue
  65. }
  66. refIDs[defID] = "1"
  67. return ast.WalkContinue
  68. })
  69. // 重置块 ID
  70. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  71. if !entering || ast.NodeDocument == n.Type {
  72. return ast.WalkContinue
  73. }
  74. if n.IsBlock() && "" != n.ID {
  75. newID := ast.NewNodeID()
  76. if "1" == refIDs[n.ID] {
  77. // 如果是文档自身的内部引用
  78. refIDs[n.ID] = newID
  79. }
  80. n.ID = newID
  81. n.SetIALAttr("id", n.ID)
  82. }
  83. return ast.WalkContinue
  84. })
  85. // 重置内部引用
  86. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  87. if !entering || !treenode.IsBlockRef(n) {
  88. return ast.WalkContinue
  89. }
  90. defID, _, _ := treenode.GetBlockRef(n)
  91. if "" == defID {
  92. return ast.WalkContinue
  93. }
  94. if "1" != refIDs[defID] {
  95. if ast.NodeTextMark == n.Type {
  96. n.TextMarkBlockRefID = refIDs[defID]
  97. }
  98. }
  99. return ast.WalkContinue
  100. })
  101. var attrViewIDs []string
  102. // 绑定镜像数据库
  103. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  104. if !entering {
  105. return ast.WalkContinue
  106. }
  107. if ast.NodeAttributeView == n.Type {
  108. av.UpsertBlockRel(n.AttributeViewID, n.ID)
  109. attrViewIDs = append(attrViewIDs, n.AttributeViewID)
  110. }
  111. return ast.WalkContinue
  112. })
  113. // 清空文档绑定的数据库
  114. tree.Root.RemoveIALAttr(av.NodeAttrNameAvs)
  115. }
  116. func pagedPaths(localPath string, pageSize int) (ret map[int][]string) {
  117. ret = map[int][]string{}
  118. page := 1
  119. filelock.Walk(localPath, func(path string, info fs.FileInfo, err error) error {
  120. if info.IsDir() {
  121. if strings.HasPrefix(info.Name(), ".") {
  122. return filepath.SkipDir
  123. }
  124. return nil
  125. }
  126. if !strings.HasSuffix(info.Name(), ".sy") {
  127. return nil
  128. }
  129. ret[page] = append(ret[page], path)
  130. if pageSize <= len(ret[page]) {
  131. page++
  132. }
  133. return nil
  134. })
  135. return
  136. }
  137. func loadTree(localPath string, luteEngine *lute.Lute) (ret *parse.Tree, err error) {
  138. data, err := filelock.ReadFile(localPath)
  139. if nil != err {
  140. logging.LogErrorf("get data [path=%s] failed: %s", localPath, err)
  141. return
  142. }
  143. ret, err = filesys.ParseJSONWithoutFix(data, luteEngine.ParseOptions)
  144. if nil != err {
  145. logging.LogErrorf("parse json to tree [%s] failed: %s", localPath, err)
  146. return
  147. }
  148. return
  149. }
  150. var (
  151. ErrBoxNotFound = errors.New("notebook not found")
  152. ErrBlockNotFound = errors.New("block not found")
  153. ErrTreeNotFound = errors.New("tree not found")
  154. ErrIndexing = errors.New("indexing")
  155. )
  156. func LoadTreeByBlockIDWithReindex(id string) (ret *parse.Tree, err error) {
  157. // 仅提供给 getBlockInfo 接口使用
  158. if "" == id {
  159. return nil, ErrTreeNotFound
  160. }
  161. bt := treenode.GetBlockTree(id)
  162. if nil == bt {
  163. if task.ContainIndexTask() {
  164. err = ErrIndexing
  165. return
  166. }
  167. // 尝试从文件系统加载
  168. searchTreeInFilesystem(id)
  169. bt = treenode.GetBlockTree(id)
  170. if nil == bt {
  171. return nil, ErrTreeNotFound
  172. }
  173. }
  174. luteEngine := util.NewLute()
  175. ret, err = filesys.LoadTree(bt.BoxID, bt.Path, luteEngine)
  176. return
  177. }
  178. func LoadTreeByBlockID(id string) (ret *parse.Tree, err error) {
  179. if "" == id {
  180. return nil, ErrTreeNotFound
  181. }
  182. bt := treenode.GetBlockTree(id)
  183. if nil == bt {
  184. if task.ContainIndexTask() {
  185. err = ErrIndexing
  186. return
  187. }
  188. return nil, ErrTreeNotFound
  189. }
  190. luteEngine := util.NewLute()
  191. ret, err = filesys.LoadTree(bt.BoxID, bt.Path, luteEngine)
  192. return
  193. }
  194. var searchTreeLimiter = rate.NewLimiter(rate.Every(3*time.Second), 1)
  195. func searchTreeInFilesystem(rootID string) {
  196. if !searchTreeLimiter.Allow() {
  197. return
  198. }
  199. msdID := util.PushMsg(Conf.language(45), 7000)
  200. defer util.PushClearMsg(msdID)
  201. logging.LogWarnf("searching tree on filesystem [rootID=%s]", rootID)
  202. var treePath string
  203. filepath.Walk(util.DataDir, func(path string, info fs.FileInfo, err error) error {
  204. if info.IsDir() {
  205. if strings.HasPrefix(info.Name(), ".") {
  206. return filepath.SkipDir
  207. }
  208. return nil
  209. }
  210. if !strings.HasSuffix(info.Name(), ".sy") {
  211. return nil
  212. }
  213. baseName := filepath.Base(path)
  214. if rootID+".sy" != baseName {
  215. return nil
  216. }
  217. treePath = path
  218. return filepath.SkipAll
  219. })
  220. if "" == treePath {
  221. logging.LogErrorf("tree not found on filesystem [rootID=%s]", rootID)
  222. return
  223. }
  224. boxID := strings.TrimPrefix(treePath, util.DataDir)
  225. boxID = boxID[1:]
  226. boxID = boxID[:strings.Index(boxID, string(os.PathSeparator))]
  227. treePath = strings.TrimPrefix(treePath, util.DataDir)
  228. treePath = strings.TrimPrefix(treePath, string(os.PathSeparator))
  229. treePath = strings.TrimPrefix(treePath, boxID)
  230. treePath = filepath.ToSlash(treePath)
  231. if nil == Conf.Box(boxID) {
  232. logging.LogInfof("box [%s] not found", boxID)
  233. // 如果笔记本不存在或者已经关闭,则不处理 https://github.com/siyuan-note/siyuan/issues/11149
  234. return
  235. }
  236. tree, err := filesys.LoadTree(boxID, treePath, util.NewLute())
  237. if nil != err {
  238. logging.LogErrorf("load tree [%s] failed: %s", treePath, err)
  239. return
  240. }
  241. treenode.IndexBlockTree(tree)
  242. sql.IndexTreeQueue(tree)
  243. logging.LogInfof("reindexed tree by filesystem [rootID=%s]", rootID)
  244. }