add.go 2.0 KB

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