1
0

get.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package config
  2. import (
  3. "net/http"
  4. "net/url"
  5. "os"
  6. "path/filepath"
  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/query"
  11. "github.com/gin-gonic/gin"
  12. "github.com/sashabaranov/go-openai"
  13. "github.com/uozi-tech/cosy"
  14. )
  15. type APIConfigResp struct {
  16. config.Config
  17. SyncNodeIds []uint64 `json:"sync_node_ids" gorm:"serializer:json"`
  18. SyncOverwrite bool `json:"sync_overwrite"`
  19. }
  20. func GetConfig(c *gin.Context) {
  21. relativePath := c.Param("path")
  22. // Ensure the path is correctly decoded - handle cases where it might be encoded multiple times
  23. decodedPath := relativePath
  24. var err error
  25. // Try decoding until the path no longer changes
  26. for {
  27. newDecodedPath, decodeErr := url.PathUnescape(decodedPath)
  28. if decodeErr != nil || newDecodedPath == decodedPath {
  29. break
  30. }
  31. decodedPath = newDecodedPath
  32. }
  33. relativePath = decodedPath
  34. absPath := nginx.GetConfPath(relativePath)
  35. if !helper.IsUnderDirectory(absPath, nginx.GetConfPath()) {
  36. c.JSON(http.StatusForbidden, gin.H{
  37. "message": "path is not under the nginx conf path",
  38. })
  39. return
  40. }
  41. stat, err := os.Stat(absPath)
  42. if err != nil {
  43. cosy.ErrHandler(c, err)
  44. return
  45. }
  46. content, err := os.ReadFile(absPath)
  47. if err != nil {
  48. cosy.ErrHandler(c, err)
  49. return
  50. }
  51. q := query.Config
  52. g := query.ChatGPTLog
  53. chatgpt, err := g.Where(g.Name.Eq(absPath)).FirstOrCreate()
  54. if err != nil {
  55. cosy.ErrHandler(c, err)
  56. return
  57. }
  58. if chatgpt.Content == nil {
  59. chatgpt.Content = make([]openai.ChatCompletionMessage, 0)
  60. }
  61. cfg, err := q.Where(q.Filepath.Eq(absPath)).FirstOrInit()
  62. if err != nil {
  63. cosy.ErrHandler(c, err)
  64. return
  65. }
  66. c.JSON(http.StatusOK, APIConfigResp{
  67. Config: config.Config{
  68. Name: stat.Name(),
  69. Content: string(content),
  70. ChatGPTMessages: chatgpt.Content,
  71. FilePath: absPath,
  72. ModifiedAt: stat.ModTime(),
  73. Dir: filepath.Dir(relativePath),
  74. },
  75. SyncNodeIds: cfg.SyncNodeIds,
  76. SyncOverwrite: cfg.SyncOverwrite,
  77. })
  78. }