get.go 1.9 KB

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