snippet.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // SiYuan - Build Your Eternal Digital Garden
  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. "mime"
  19. "net/http"
  20. "path/filepath"
  21. "strings"
  22. "github.com/88250/gulu"
  23. "github.com/gin-gonic/gin"
  24. "github.com/siyuan-note/logging"
  25. "github.com/siyuan-note/siyuan/kernel/conf"
  26. "github.com/siyuan-note/siyuan/kernel/model"
  27. "github.com/siyuan-note/siyuan/kernel/util"
  28. )
  29. func serveSnippets(c *gin.Context) {
  30. name := strings.TrimPrefix(c.Request.URL.Path, "/snippets/")
  31. ext := filepath.Ext(name)
  32. name = strings.TrimSuffix(name, ext)
  33. confSnippets, err := model.LoadSnippets()
  34. if nil != err {
  35. logging.LogErrorf("load snippets failed: %s", name, err)
  36. c.Status(404)
  37. return
  38. }
  39. for _, s := range confSnippets {
  40. if s.Name == name && ("" != ext && s.Type == ext[1:]) {
  41. c.Header("Content-Type", mime.TypeByExtension(ext))
  42. c.String(http.StatusOK, s.Content)
  43. return
  44. }
  45. }
  46. c.Status(404)
  47. }
  48. func getSnippet(c *gin.Context) {
  49. ret := gulu.Ret.NewResult()
  50. defer c.JSON(http.StatusOK, ret)
  51. arg, ok := util.JsonArg(c, ret)
  52. if !ok {
  53. return
  54. }
  55. typ := arg["type"].(string) // js/css/all
  56. enabledArg := int(arg["enabled"].(float64)) // 0:禁用,1:启用,2:全部
  57. enabled := true
  58. if 0 == enabledArg {
  59. enabled = false
  60. }
  61. confSnippets, err := model.LoadSnippets()
  62. if nil != err {
  63. ret.Code = -1
  64. ret.Msg = "load snippets failed: " + err.Error()
  65. return
  66. }
  67. var snippets []*conf.Snippet
  68. for _, s := range confSnippets {
  69. if ("all" == typ || s.Type == typ) && (2 == enabledArg || s.Enabled == enabled) {
  70. snippets = append(snippets, s)
  71. }
  72. }
  73. if 1 > len(snippets) {
  74. snippets = []*conf.Snippet{}
  75. }
  76. ret.Data = map[string]interface{}{
  77. "snippets": snippets,
  78. }
  79. }