extension.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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/httpclient"
  34. "github.com/siyuan-note/logging"
  35. "github.com/siyuan-note/siyuan/kernel/model"
  36. "github.com/siyuan-note/siyuan/kernel/util"
  37. )
  38. func extensionCopy(c *gin.Context) {
  39. ret := gulu.Ret.NewResult()
  40. defer c.JSON(200, ret)
  41. form, _ := c.MultipartForm()
  42. dom := form.Value["dom"][0]
  43. assets := filepath.Join(util.DataDir, "assets")
  44. if notebookVal := form.Value["notebook"]; 0 < len(notebookVal) {
  45. assets = filepath.Join(util.DataDir, notebookVal[0], "assets")
  46. if !gulu.File.IsDir(assets) {
  47. assets = filepath.Join(util.DataDir, "assets")
  48. }
  49. }
  50. if err := os.MkdirAll(assets, 0755); nil != err {
  51. logging.LogErrorf("create assets folder [%s] failed: %s", assets, err)
  52. ret.Msg = err.Error()
  53. return
  54. }
  55. uploaded := map[string]string{}
  56. for originalName, file := range form.File {
  57. oName, err := url.PathUnescape(originalName)
  58. if nil != err {
  59. if strings.Contains(originalName, "%u") {
  60. originalName = strings.ReplaceAll(originalName, "%u", "\\u")
  61. originalName, err = strconv.Unquote("\"" + originalName + "\"")
  62. if nil != err {
  63. continue
  64. }
  65. oName, err = url.PathUnescape(originalName)
  66. if nil != err {
  67. continue
  68. }
  69. } else {
  70. continue
  71. }
  72. }
  73. u, _ := url.Parse(oName)
  74. if "" == u.Path {
  75. continue
  76. }
  77. fName := path.Base(u.Path)
  78. f, err := file[0].Open()
  79. if nil != err {
  80. ret.Code = -1
  81. ret.Msg = err.Error()
  82. break
  83. }
  84. data, err := io.ReadAll(f)
  85. if nil != err {
  86. ret.Code = -1
  87. ret.Msg = err.Error()
  88. break
  89. }
  90. ext := path.Ext(fName)
  91. originalExt := ext
  92. if "" == ext || strings.Contains(ext, "!") {
  93. // 改进浏览器剪藏扩展转换本地图片后缀 https://github.com/siyuan-note/siyuan/issues/7467
  94. if mtype := mimetype.Detect(data); nil != mtype {
  95. ext = mtype.Extension()
  96. }
  97. }
  98. if "" == ext && bytes.HasPrefix(data, []byte("<svg ")) && bytes.HasSuffix(data, []byte("</svg>")) {
  99. ext = ".svg"
  100. }
  101. fName = fName[0 : len(fName)-len(originalExt)]
  102. fName = util.FilterUploadFileName(fName)
  103. fName = fName + "-" + ast.NewNodeID() + ext
  104. writePath := filepath.Join(assets, fName)
  105. if err = filelock.WriteFile(writePath, data); nil != err {
  106. ret.Code = -1
  107. ret.Msg = err.Error()
  108. break
  109. }
  110. uploaded[oName] = "assets/" + fName
  111. }
  112. luteEngine := util.NewLute()
  113. var md string
  114. var withMath bool
  115. if nil != form.Value["href"] {
  116. if href := form.Value["href"][0]; strings.HasPrefix(href, "https://ld246.com/article/") {
  117. // 剪藏链滴帖子时直接使用 Markdown 接口的返回
  118. // https://ld246.com/article/raw/1724850322251
  119. href = strings.ReplaceAll(href, "https://ld246.com/article/", "https://ld246.com/article/raw/")
  120. resp, err := httpclient.NewCloudRequest30s().Get(href)
  121. if nil != err {
  122. logging.LogWarnf("get [%s] failed: %s", href, err)
  123. } else {
  124. bodyData, readErr := io.ReadAll(resp.Body)
  125. if nil != readErr {
  126. ret.Code = -1
  127. ret.Msg = "read response body failed: " + readErr.Error()
  128. return
  129. }
  130. md = string(bodyData)
  131. tree := parse.Parse("", []byte(md), luteEngine.ParseOptions)
  132. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  133. if ast.NodeInlineMath == n.Type {
  134. withMath = true
  135. return ast.WalkStop
  136. }
  137. return ast.WalkContinue
  138. })
  139. }
  140. }
  141. }
  142. if "" == md {
  143. md, withMath, _ = model.HTML2Markdown(dom)
  144. }
  145. md = strings.TrimSpace(md)
  146. if withMath {
  147. luteEngine.SetInlineMath(true)
  148. }
  149. var unlinks []*ast.Node
  150. tree := parse.Parse("", []byte(md), luteEngine.ParseOptions)
  151. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  152. if !entering {
  153. return ast.WalkContinue
  154. }
  155. if ast.NodeText == n.Type {
  156. // 剔除行首空白
  157. if ast.NodeParagraph == n.Parent.Type && n.Parent.FirstChild == n {
  158. n.Tokens = bytes.TrimLeft(n.Tokens, " \t\n")
  159. }
  160. } else if ast.NodeImage == n.Type {
  161. if dest := n.ChildByType(ast.NodeLinkDest); nil != dest {
  162. assetPath := uploaded[string(dest.Tokens)]
  163. if "" == assetPath {
  164. assetPath = uploaded[string(dest.Tokens)+"?imageView2/2/interlace/1/format/webp"]
  165. }
  166. if "" != assetPath {
  167. dest.Tokens = []byte(assetPath)
  168. }
  169. }
  170. }
  171. return ast.WalkContinue
  172. })
  173. for _, unlink := range unlinks {
  174. unlink.Unlink()
  175. }
  176. parse.NestedInlines2FlattedSpansHybrid(tree, false)
  177. md, _ = lute.FormatNodeSync(tree.Root, luteEngine.ParseOptions, luteEngine.RenderOptions)
  178. ret.Data = map[string]interface{}{
  179. "md": md,
  180. "withMath": withMath,
  181. }
  182. ret.Msg = model.Conf.Language(72)
  183. }