add.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package config
  2. import (
  3. "github.com/0xJacky/Nginx-UI/api"
  4. "github.com/0xJacky/Nginx-UI/internal/config"
  5. "github.com/0xJacky/Nginx-UI/internal/helper"
  6. "github.com/0xJacky/Nginx-UI/internal/nginx"
  7. "github.com/0xJacky/Nginx-UI/model"
  8. "github.com/0xJacky/Nginx-UI/query"
  9. "github.com/gin-gonic/gin"
  10. "github.com/sashabaranov/go-openai"
  11. "github.com/uozi-tech/cosy"
  12. "net/http"
  13. "os"
  14. "path/filepath"
  15. "time"
  16. )
  17. func AddConfig(c *gin.Context) {
  18. var json struct {
  19. Name string `json:"name" binding:"required"`
  20. BaseDir string `json:"base_dir"`
  21. Content string `json:"content"`
  22. Overwrite bool `json:"overwrite"`
  23. SyncNodeIds []uint64 `json:"sync_node_ids"`
  24. }
  25. if !cosy.BindAndValid(c, &json) {
  26. return
  27. }
  28. name := json.Name
  29. content := json.Content
  30. dir := nginx.GetConfPath(json.BaseDir)
  31. path := filepath.Join(dir, json.Name)
  32. if !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
  33. c.JSON(http.StatusForbidden, gin.H{
  34. "message": "filepath is not under the nginx conf path",
  35. })
  36. return
  37. }
  38. if !json.Overwrite && helper.FileExists(path) {
  39. c.JSON(http.StatusNotAcceptable, gin.H{
  40. "message": "File exists",
  41. })
  42. return
  43. }
  44. // check if the dir exists, if not, use mkdirAll to create the dir
  45. if !helper.FileExists(dir) {
  46. err := os.MkdirAll(dir, 0755)
  47. if err != nil {
  48. api.ErrHandler(c, err)
  49. return
  50. }
  51. }
  52. err := os.WriteFile(path, []byte(content), 0644)
  53. if err != nil {
  54. api.ErrHandler(c, err)
  55. return
  56. }
  57. output := nginx.Reload()
  58. if nginx.GetLogLevel(output) >= nginx.Warn {
  59. c.JSON(http.StatusInternalServerError, gin.H{
  60. "message": output,
  61. })
  62. return
  63. }
  64. q := query.Config
  65. _, err = q.Where(q.Filepath.Eq(path)).Delete()
  66. if err != nil {
  67. api.ErrHandler(c, err)
  68. return
  69. }
  70. cfg := &model.Config{
  71. Name: name,
  72. Filepath: path,
  73. SyncNodeIds: json.SyncNodeIds,
  74. SyncOverwrite: json.Overwrite,
  75. }
  76. err = q.Create(cfg)
  77. if err != nil {
  78. api.ErrHandler(c, err)
  79. return
  80. }
  81. err = config.SyncToRemoteServer(cfg, path)
  82. if err != nil {
  83. api.ErrHandler(c, err)
  84. return
  85. }
  86. c.JSON(http.StatusOK, config.Config{
  87. Name: name,
  88. Content: content,
  89. ChatGPTMessages: make([]openai.ChatCompletionMessage, 0),
  90. FilePath: path,
  91. ModifiedAt: time.Now(),
  92. })
  93. }