add.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. config.SyncConfigPayload
  20. SyncNodeIds []uint64 `json:"sync_node_ids"`
  21. }
  22. if !cosy.BindAndValid(c, &json) {
  23. return
  24. }
  25. name := json.Name
  26. content := json.Content
  27. dir := nginx.GetConfPath(json.BaseDir)
  28. path := filepath.Join(dir, json.Name)
  29. if !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
  30. c.JSON(http.StatusForbidden, gin.H{
  31. "message": "filepath is not under the nginx conf path",
  32. })
  33. return
  34. }
  35. if !json.Overwrite && helper.FileExists(path) {
  36. c.JSON(http.StatusNotAcceptable, gin.H{
  37. "message": "File exists",
  38. })
  39. return
  40. }
  41. // check if the dir exists, if not, use mkdirAll to create the dir
  42. if !helper.FileExists(dir) {
  43. err := os.MkdirAll(dir, 0755)
  44. if err != nil {
  45. api.ErrHandler(c, err)
  46. return
  47. }
  48. }
  49. err := os.WriteFile(path, []byte(content), 0644)
  50. if err != nil {
  51. api.ErrHandler(c, err)
  52. return
  53. }
  54. output := nginx.Reload()
  55. if nginx.GetLogLevel(output) >= nginx.Warn {
  56. c.JSON(http.StatusInternalServerError, gin.H{
  57. "message": output,
  58. })
  59. return
  60. }
  61. q := query.Config
  62. _, err = q.Where(q.Filepath.Eq(path)).Delete()
  63. if err != nil {
  64. api.ErrHandler(c, err)
  65. return
  66. }
  67. cfg := &model.Config{
  68. Name: name,
  69. Filepath: path,
  70. SyncNodeIds: json.SyncNodeIds,
  71. SyncOverwrite: json.Overwrite,
  72. }
  73. err = q.Create(cfg)
  74. if err != nil {
  75. api.ErrHandler(c, err)
  76. return
  77. }
  78. err = config.SyncToRemoteServer(cfg)
  79. if err != nil {
  80. api.ErrHandler(c, err)
  81. return
  82. }
  83. c.JSON(http.StatusOK, config.Config{
  84. Name: name,
  85. Content: content,
  86. ChatGPTMessages: make([]openai.ChatCompletionMessage, 0),
  87. FilePath: path,
  88. ModifiedAt: time.Now(),
  89. })
  90. }