template.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. "bytes"
  19. "errors"
  20. "fmt"
  21. "io/fs"
  22. "os"
  23. "path/filepath"
  24. "sort"
  25. "strings"
  26. "text/template"
  27. "time"
  28. "github.com/88250/gulu"
  29. "github.com/88250/lute/ast"
  30. "github.com/88250/lute/parse"
  31. "github.com/88250/lute/render"
  32. sprig "github.com/Masterminds/sprig/v3"
  33. "github.com/araddon/dateparse"
  34. "github.com/siyuan-note/filelock"
  35. "github.com/siyuan-note/logging"
  36. "github.com/siyuan-note/siyuan/kernel/search"
  37. "github.com/siyuan-note/siyuan/kernel/sql"
  38. "github.com/siyuan-note/siyuan/kernel/treenode"
  39. "github.com/siyuan-note/siyuan/kernel/util"
  40. )
  41. func RenderGoTemplate(templateContent string) (ret string, err error) {
  42. tpl, err := template.New("").Funcs(sprig.TxtFuncMap()).Parse(templateContent)
  43. if nil != err {
  44. return "", errors.New(fmt.Sprintf(Conf.Language(44), err.Error()))
  45. }
  46. buf := &bytes.Buffer{}
  47. buf.Grow(4096)
  48. err = tpl.Execute(buf, nil)
  49. if nil != err {
  50. return "", errors.New(fmt.Sprintf(Conf.Language(44), err.Error()))
  51. }
  52. ret = buf.String()
  53. return
  54. }
  55. func RemoveTemplate(p string) (err error) {
  56. err = filelock.Remove(p)
  57. if nil != err {
  58. logging.LogErrorf("remove template failed: %s", err)
  59. }
  60. return
  61. }
  62. func SearchTemplate(keyword string) (ret []*Block) {
  63. ret = []*Block{}
  64. templates := filepath.Join(util.DataDir, "templates")
  65. if !util.IsPathRegularDirOrSymlinkDir(templates) {
  66. return
  67. }
  68. groups, err := os.ReadDir(templates)
  69. if nil != err {
  70. logging.LogErrorf("read templates failed: %s", err)
  71. return
  72. }
  73. sort.Slice(ret, func(i, j int) bool {
  74. return util.PinYinCompare(filepath.Base(groups[i].Name()), filepath.Base(groups[j].Name()))
  75. })
  76. k := strings.ToLower(keyword)
  77. for _, group := range groups {
  78. if strings.HasPrefix(group.Name(), ".") {
  79. continue
  80. }
  81. if group.IsDir() {
  82. var templateBlocks []*Block
  83. templateDir := filepath.Join(templates, group.Name())
  84. // filepath.Walk 与 filepath.WalkDir 均不支持跟踪符号链接
  85. filepath.WalkDir(templateDir, func(path string, entry fs.DirEntry, err error) error {
  86. name := strings.ToLower(entry.Name())
  87. if strings.HasPrefix(name, ".") {
  88. if entry.IsDir() {
  89. return filepath.SkipDir
  90. }
  91. return nil
  92. }
  93. if !strings.HasSuffix(name, ".md") || strings.HasPrefix(name, "readme") || !strings.Contains(name, k) {
  94. return nil
  95. }
  96. content := strings.TrimPrefix(path, templates)
  97. content = strings.TrimSuffix(content, ".md")
  98. content = filepath.ToSlash(content)
  99. content = strings.TrimPrefix(content, "/")
  100. _, content = search.MarkText(content, keyword, 32, Conf.Search.CaseSensitive)
  101. b := &Block{Path: path, Content: content}
  102. templateBlocks = append(templateBlocks, b)
  103. return nil
  104. })
  105. sort.Slice(templateBlocks, func(i, j int) bool {
  106. return util.PinYinCompare(filepath.Base(templateBlocks[i].Path), filepath.Base(templateBlocks[j].Path))
  107. })
  108. ret = append(ret, templateBlocks...)
  109. } else {
  110. name := strings.ToLower(group.Name())
  111. if strings.HasPrefix(name, ".") || !strings.HasSuffix(name, ".md") || "readme.md" == name || !strings.Contains(name, k) {
  112. continue
  113. }
  114. content := group.Name()
  115. content = strings.TrimSuffix(content, ".md")
  116. content = filepath.ToSlash(content)
  117. _, content = search.MarkText(content, keyword, 32, Conf.Search.CaseSensitive)
  118. b := &Block{Path: filepath.Join(templates, group.Name()), Content: content}
  119. ret = append(ret, b)
  120. }
  121. }
  122. return
  123. }
  124. func DocSaveAsTemplate(id, name string, overwrite bool) (code int, err error) {
  125. bt := treenode.GetBlockTree(id)
  126. if nil == bt {
  127. return
  128. }
  129. tree := prepareExportTree(bt)
  130. addBlockIALNodes(tree, true)
  131. luteEngine := NewLute()
  132. formatRenderer := render.NewFormatRenderer(tree, luteEngine.RenderOptions)
  133. md := formatRenderer.Render()
  134. name = util.FilterFileName(name) + ".md"
  135. name = util.TruncateLenFileName(name)
  136. savePath := filepath.Join(util.DataDir, "templates", name)
  137. if gulu.File.IsExist(savePath) {
  138. if !overwrite {
  139. code = 1
  140. return
  141. }
  142. }
  143. err = filelock.WriteFile(savePath, md)
  144. return
  145. }
  146. func RenderTemplate(p, id string) (string, error) {
  147. return renderTemplate(p, id)
  148. }
  149. func renderTemplate(p, id string) (string, error) {
  150. tree, err := loadTreeByBlockID(id)
  151. if nil != err {
  152. return "", err
  153. }
  154. node := treenode.GetNodeInTree(tree, id)
  155. if nil == node {
  156. return "", ErrBlockNotFound
  157. }
  158. block := sql.BuildBlockFromNode(node, tree)
  159. md, err := os.ReadFile(p)
  160. if nil != err {
  161. return "", err
  162. }
  163. dataModel := map[string]string{}
  164. var titleVar string
  165. if nil != block {
  166. titleVar = block.Name
  167. if "d" == block.Type {
  168. titleVar = block.Content
  169. }
  170. dataModel["title"] = titleVar
  171. dataModel["id"] = block.ID
  172. dataModel["name"] = block.Name
  173. dataModel["alias"] = block.Alias
  174. }
  175. funcMap := sprig.TxtFuncMap()
  176. funcMap["queryBlocks"] = func(stmt string, args ...string) (ret []*sql.Block) {
  177. for _, arg := range args {
  178. stmt = strings.Replace(stmt, "?", arg, 1)
  179. }
  180. ret = sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)
  181. return
  182. }
  183. funcMap["querySpans"] = func(stmt string, args ...string) (ret []*sql.Span) {
  184. for _, arg := range args {
  185. stmt = strings.Replace(stmt, "?", arg, 1)
  186. }
  187. ret = sql.SelectSpansRawStmt(stmt, Conf.Search.Limit)
  188. return
  189. }
  190. funcMap["parseTime"] = func(dateStr string) time.Time {
  191. now := time.Now()
  192. ret, err := dateparse.ParseIn(dateStr, now.Location())
  193. if nil != err {
  194. logging.LogWarnf("parse date [%s] failed [%s], return current time instead", dateStr, err)
  195. return now
  196. }
  197. return ret
  198. }
  199. goTpl := template.New("").Delims(".action{", "}")
  200. tpl, err := goTpl.Funcs(funcMap).Parse(gulu.Str.FromBytes(md))
  201. if nil != err {
  202. return "", errors.New(fmt.Sprintf(Conf.Language(44), err.Error()))
  203. }
  204. buf := &bytes.Buffer{}
  205. buf.Grow(4096)
  206. if err = tpl.Execute(buf, dataModel); nil != err {
  207. return "", errors.New(fmt.Sprintf(Conf.Language(44), err.Error()))
  208. }
  209. md = buf.Bytes()
  210. tree = parseKTree(md)
  211. if nil == tree {
  212. msg := fmt.Sprintf("parse tree [%s] failed", p)
  213. logging.LogErrorf(msg)
  214. return "", errors.New(msg)
  215. }
  216. var nodesNeedAppendChild, unlinks []*ast.Node
  217. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  218. if !entering {
  219. return ast.WalkContinue
  220. }
  221. if "" != n.ID {
  222. // 重新生成 ID
  223. n.ID = ast.NewNodeID()
  224. n.SetIALAttr("id", n.ID)
  225. // Blocks created via template update time earlier than creation time https://github.com/siyuan-note/siyuan/issues/8607
  226. refreshUpdated(n)
  227. }
  228. if (ast.NodeListItem == n.Type && (nil == n.FirstChild ||
  229. (3 == n.ListData.Typ && (nil == n.FirstChild.Next || ast.NodeKramdownBlockIAL == n.FirstChild.Next.Type)))) ||
  230. (ast.NodeBlockquote == n.Type && nil != n.FirstChild && nil != n.FirstChild.Next && ast.NodeKramdownBlockIAL == n.FirstChild.Next.Type) {
  231. nodesNeedAppendChild = append(nodesNeedAppendChild, n)
  232. }
  233. // 块引缺失锚文本情况下自动补全 https://github.com/siyuan-note/siyuan/issues/6087
  234. if n.IsTextMarkType("block-ref") {
  235. if refText := n.Text(); "" == refText {
  236. refText = sql.GetRefText(n.TextMarkBlockRefID)
  237. if "" != refText {
  238. treenode.SetDynamicBlockRefText(n, refText)
  239. } else {
  240. unlinks = append(unlinks, n)
  241. }
  242. }
  243. }
  244. return ast.WalkContinue
  245. })
  246. for _, n := range nodesNeedAppendChild {
  247. if ast.NodeBlockquote == n.Type {
  248. n.FirstChild.InsertAfter(treenode.NewParagraph())
  249. } else {
  250. n.AppendChild(treenode.NewParagraph())
  251. }
  252. }
  253. for _, n := range unlinks {
  254. n.Unlink()
  255. }
  256. // 折叠标题导出为模板后使用会出现内容重复 https://github.com/siyuan-note/siyuan/issues/4488
  257. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  258. if !entering {
  259. return ast.WalkContinue
  260. }
  261. if "1" == n.IALAttr("heading-fold") { // 为标题折叠下方块添加属性,前端渲染以后会统一做移除处理
  262. n.SetIALAttr("status", "temp")
  263. }
  264. return ast.WalkContinue
  265. })
  266. luteEngine := NewLute()
  267. dom := luteEngine.Tree2BlockDOM(tree, luteEngine.RenderOptions)
  268. return dom, nil
  269. }
  270. func addBlockIALNodes(tree *parse.Tree, removeUpdated bool) {
  271. var blocks []*ast.Node
  272. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  273. if !entering || !n.IsBlock() {
  274. return ast.WalkContinue
  275. }
  276. if ast.NodeBlockQueryEmbed == n.Type {
  277. if script := n.ChildByType(ast.NodeBlockQueryEmbedScript); nil != script {
  278. script.Tokens = bytes.ReplaceAll(script.Tokens, []byte("\n"), []byte(" "))
  279. }
  280. } else if ast.NodeHTMLBlock == n.Type {
  281. n.Tokens = bytes.TrimSpace(n.Tokens)
  282. // 使用 <div> 包裹,否则后续解析时会识别为行级 HTML https://github.com/siyuan-note/siyuan/issues/4244
  283. if !bytes.HasPrefix(n.Tokens, []byte("<div>")) {
  284. n.Tokens = append([]byte("<div>\n"), n.Tokens...)
  285. }
  286. if !bytes.HasSuffix(n.Tokens, []byte("</div>")) {
  287. n.Tokens = append(n.Tokens, []byte("\n</div>")...)
  288. }
  289. }
  290. if removeUpdated {
  291. n.RemoveIALAttr("updated")
  292. }
  293. if 0 < len(n.KramdownIAL) {
  294. blocks = append(blocks, n)
  295. }
  296. return ast.WalkContinue
  297. })
  298. for _, block := range blocks {
  299. block.InsertAfter(&ast.Node{Type: ast.NodeKramdownBlockIAL, Tokens: parse.IAL2Tokens(block.KramdownIAL)})
  300. }
  301. }