tree.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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, removeAvBinding bool) {
  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. if removeAvBinding {
  114. // 清空文档绑定的数据库
  115. tree.Root.RemoveIALAttr(av.NodeAttrNameAvs)
  116. }
  117. }
  118. func pagedPaths(localPath string, pageSize int) (ret map[int][]string) {
  119. ret = map[int][]string{}
  120. page := 1
  121. filelock.Walk(localPath, func(path string, info fs.FileInfo, err error) error {
  122. if info.IsDir() {
  123. if strings.HasPrefix(info.Name(), ".") {
  124. return filepath.SkipDir
  125. }
  126. return nil
  127. }
  128. if !strings.HasSuffix(info.Name(), ".sy") {
  129. return nil
  130. }
  131. ret[page] = append(ret[page], path)
  132. if pageSize <= len(ret[page]) {
  133. page++
  134. }
  135. return nil
  136. })
  137. return
  138. }
  139. func loadTree(localPath string, luteEngine *lute.Lute) (ret *parse.Tree, err error) {
  140. data, err := filelock.ReadFile(localPath)
  141. if nil != err {
  142. logging.LogErrorf("get data [path=%s] failed: %s", localPath, err)
  143. return
  144. }
  145. ret, err = filesys.ParseJSONWithoutFix(data, luteEngine.ParseOptions)
  146. if nil != err {
  147. logging.LogErrorf("parse json to tree [%s] failed: %s", localPath, err)
  148. return
  149. }
  150. return
  151. }
  152. var (
  153. ErrBoxNotFound = errors.New("notebook not found")
  154. ErrBlockNotFound = errors.New("block not found")
  155. ErrTreeNotFound = errors.New("tree not found")
  156. ErrIndexing = errors.New("indexing")
  157. )
  158. func LoadTreeByBlockIDWithReindex(id string) (ret *parse.Tree, err error) {
  159. // 仅提供给 getBlockInfo 接口使用
  160. if "" == id {
  161. logging.LogWarnf("block id is empty")
  162. return nil, ErrTreeNotFound
  163. }
  164. bt := treenode.GetBlockTree(id)
  165. if nil == bt {
  166. if task.ContainIndexTask() {
  167. err = ErrIndexing
  168. return
  169. }
  170. // 尝试从文件系统加载
  171. searchTreeInFilesystem(id)
  172. bt = treenode.GetBlockTree(id)
  173. if nil == bt {
  174. logging.LogWarnf("block tree not found [id=%s], stack: [%s]", id, logging.ShortStack())
  175. return nil, ErrTreeNotFound
  176. }
  177. }
  178. luteEngine := util.NewLute()
  179. ret, err = filesys.LoadTree(bt.BoxID, bt.Path, luteEngine)
  180. return
  181. }
  182. func LoadTreeByBlockID(id string) (ret *parse.Tree, err error) {
  183. if "" == id {
  184. logging.LogErrorf("block id is empty")
  185. return nil, ErrTreeNotFound
  186. }
  187. bt := treenode.GetBlockTree(id)
  188. if nil == bt {
  189. if task.ContainIndexTask() {
  190. err = ErrIndexing
  191. return
  192. }
  193. logging.LogWarnf("block tree not found [id=%s], stack: [%s]", id, logging.ShortStack())
  194. return nil, ErrTreeNotFound
  195. }
  196. ret, err = loadTreeByBlockTree(bt)
  197. return
  198. }
  199. func loadTreeByBlockTree(bt *treenode.BlockTree) (ret *parse.Tree, err error) {
  200. luteEngine := util.NewLute()
  201. ret, err = filesys.LoadTree(bt.BoxID, bt.Path, luteEngine)
  202. return
  203. }
  204. var searchTreeLimiter = rate.NewLimiter(rate.Every(3*time.Second), 1)
  205. func searchTreeInFilesystem(rootID string) {
  206. if !searchTreeLimiter.Allow() {
  207. return
  208. }
  209. msdID := util.PushMsg(Conf.language(45), 7000)
  210. defer util.PushClearMsg(msdID)
  211. logging.LogWarnf("searching tree on filesystem [rootID=%s]", rootID)
  212. var treePath string
  213. filepath.Walk(util.DataDir, func(path string, info fs.FileInfo, err error) error {
  214. if info.IsDir() {
  215. if strings.HasPrefix(info.Name(), ".") {
  216. return filepath.SkipDir
  217. }
  218. return nil
  219. }
  220. if !strings.HasSuffix(info.Name(), ".sy") {
  221. return nil
  222. }
  223. baseName := filepath.Base(path)
  224. if rootID+".sy" != baseName {
  225. return nil
  226. }
  227. treePath = path
  228. return filepath.SkipAll
  229. })
  230. if "" == treePath {
  231. logging.LogErrorf("tree not found on filesystem [rootID=%s]", rootID)
  232. return
  233. }
  234. boxID := strings.TrimPrefix(treePath, util.DataDir)
  235. boxID = boxID[1:]
  236. boxID = boxID[:strings.Index(boxID, string(os.PathSeparator))]
  237. treePath = strings.TrimPrefix(treePath, util.DataDir)
  238. treePath = strings.TrimPrefix(treePath, string(os.PathSeparator))
  239. treePath = strings.TrimPrefix(treePath, boxID)
  240. treePath = filepath.ToSlash(treePath)
  241. if nil == Conf.Box(boxID) {
  242. logging.LogInfof("box [%s] not found", boxID)
  243. // 如果笔记本不存在或者已经关闭,则不处理 https://github.com/siyuan-note/siyuan/issues/11149
  244. return
  245. }
  246. tree, err := filesys.LoadTree(boxID, treePath, util.NewLute())
  247. if nil != err {
  248. logging.LogErrorf("load tree [%s] failed: %s", treePath, err)
  249. return
  250. }
  251. treenode.UpsertBlockTree(tree)
  252. sql.IndexTreeQueue(tree)
  253. logging.LogInfof("reindexed tree by filesystem [rootID=%s]", rootID)
  254. }