extension.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 api
  17. import (
  18. "bytes"
  19. "io"
  20. "net/url"
  21. "os"
  22. "path"
  23. "path/filepath"
  24. "strconv"
  25. "strings"
  26. "github.com/88250/gulu"
  27. "github.com/88250/lute"
  28. "github.com/88250/lute/ast"
  29. "github.com/88250/lute/parse"
  30. "github.com/gabriel-vasile/mimetype"
  31. "github.com/gin-gonic/gin"
  32. "github.com/siyuan-note/filelock"
  33. "github.com/siyuan-note/logging"
  34. "github.com/siyuan-note/siyuan/kernel/model"
  35. "github.com/siyuan-note/siyuan/kernel/util"
  36. )
  37. func extensionCopy(c *gin.Context) {
  38. ret := gulu.Ret.NewResult()
  39. defer c.JSON(200, ret)
  40. form, _ := c.MultipartForm()
  41. dom := form.Value["dom"][0]
  42. assets := filepath.Join(util.DataDir, "assets")
  43. if notebookVal := form.Value["notebook"]; 0 < len(notebookVal) {
  44. assets = filepath.Join(util.DataDir, notebookVal[0], "assets")
  45. if !gulu.File.IsDir(assets) {
  46. assets = filepath.Join(util.DataDir, "assets")
  47. }
  48. }
  49. if err := os.MkdirAll(assets, 0755); nil != err {
  50. logging.LogErrorf("create assets folder [%s] failed: %s", assets, err)
  51. ret.Msg = err.Error()
  52. return
  53. }
  54. uploaded := map[string]string{}
  55. for originalName, file := range form.File {
  56. oName, err := url.PathUnescape(originalName)
  57. if nil != err {
  58. if strings.Contains(originalName, "%u") {
  59. originalName = strings.ReplaceAll(originalName, "%u", "\\u")
  60. originalName, err = strconv.Unquote("\"" + originalName + "\"")
  61. if nil != err {
  62. continue
  63. }
  64. oName, err = url.PathUnescape(originalName)
  65. if nil != err {
  66. continue
  67. }
  68. } else {
  69. continue
  70. }
  71. }
  72. u, _ := url.Parse(oName)
  73. if "" == u.Path {
  74. continue
  75. }
  76. fName := path.Base(u.Path)
  77. f, err := file[0].Open()
  78. if nil != err {
  79. ret.Code = -1
  80. ret.Msg = err.Error()
  81. break
  82. }
  83. data, err := io.ReadAll(f)
  84. if nil != err {
  85. ret.Code = -1
  86. ret.Msg = err.Error()
  87. break
  88. }
  89. ext := path.Ext(fName)
  90. originalExt := ext
  91. if "" == ext || strings.Contains(ext, "!") {
  92. // 改进浏览器剪藏扩展转换本地图片后缀 https://github.com/siyuan-note/siyuan/issues/7467
  93. if mtype := mimetype.Detect(data); nil != mtype {
  94. ext = mtype.Extension()
  95. }
  96. }
  97. if "" == ext && bytes.HasPrefix(data, []byte("<svg ")) && bytes.HasSuffix(data, []byte("</svg>")) {
  98. ext = ".svg"
  99. }
  100. fName = fName[0 : len(fName)-len(originalExt)]
  101. fName = util.FilterUploadFileName(fName)
  102. fName = fName + "-" + ast.NewNodeID() + ext
  103. writePath := filepath.Join(assets, fName)
  104. if err = filelock.WriteFile(writePath, data); nil != err {
  105. ret.Code = -1
  106. ret.Msg = err.Error()
  107. break
  108. }
  109. uploaded[oName] = "assets/" + fName
  110. }
  111. md, withMath, _ := model.HTML2Markdown(dom)
  112. md = strings.TrimSpace(md)
  113. luteEngine := util.NewLute()
  114. if withMath {
  115. luteEngine.SetInlineMath(true)
  116. }
  117. var unlinks []*ast.Node
  118. tree := parse.Parse("", []byte(md), luteEngine.ParseOptions)
  119. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  120. if !entering {
  121. return ast.WalkContinue
  122. }
  123. if ast.NodeText == n.Type {
  124. // 剔除行首空白
  125. if ast.NodeParagraph == n.Parent.Type && n.Parent.FirstChild == n {
  126. n.Tokens = bytes.TrimLeft(n.Tokens, " \t\n")
  127. }
  128. } else if ast.NodeImage == n.Type {
  129. if dest := n.ChildByType(ast.NodeLinkDest); nil != dest {
  130. assetPath := uploaded[string(dest.Tokens)]
  131. if "" != assetPath {
  132. dest.Tokens = []byte(assetPath)
  133. }
  134. }
  135. }
  136. return ast.WalkContinue
  137. })
  138. for _, unlink := range unlinks {
  139. unlink.Unlink()
  140. }
  141. parse.NestedInlines2FlattedSpansHybrid(tree, false)
  142. md, _ = lute.FormatNodeSync(tree.Root, luteEngine.ParseOptions, luteEngine.RenderOptions)
  143. ret.Data = map[string]interface{}{
  144. "md": md,
  145. "withMath": withMath,
  146. }
  147. ret.Msg = model.Conf.Language(72)
  148. }