streams.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. package streams
  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/query"
  8. "github.com/gin-gonic/gin"
  9. "github.com/sashabaranov/go-openai"
  10. "github.com/uozi-tech/cosy"
  11. "net/http"
  12. "os"
  13. "strings"
  14. "time"
  15. )
  16. type Stream struct {
  17. ModifiedAt time.Time `json:"modified_at"`
  18. Advanced bool `json:"advanced"`
  19. Enabled bool `json:"enabled"`
  20. Name string `json:"name"`
  21. Config string `json:"config"`
  22. ChatGPTMessages []openai.ChatCompletionMessage `json:"chatgpt_messages,omitempty"`
  23. Tokenized *nginx.NgxConfig `json:"tokenized,omitempty"`
  24. Filepath string `json:"filepath"`
  25. }
  26. func GetStreams(c *gin.Context) {
  27. name := c.Query("name")
  28. orderBy := c.Query("order_by")
  29. sort := c.DefaultQuery("sort", "desc")
  30. configFiles, err := os.ReadDir(nginx.GetConfPath("streams-available"))
  31. if err != nil {
  32. api.ErrHandler(c, err)
  33. return
  34. }
  35. enabledConfig, err := os.ReadDir(nginx.GetConfPath("streams-enabled"))
  36. if err != nil {
  37. api.ErrHandler(c, err)
  38. return
  39. }
  40. enabledConfigMap := make(map[string]bool)
  41. for i := range enabledConfig {
  42. enabledConfigMap[enabledConfig[i].Name()] = true
  43. }
  44. var configs []config.Config
  45. for i := range configFiles {
  46. file := configFiles[i]
  47. fileInfo, _ := file.Info()
  48. if !file.IsDir() {
  49. if name != "" && !strings.Contains(file.Name(), name) {
  50. continue
  51. }
  52. configs = append(configs, config.Config{
  53. Name: file.Name(),
  54. ModifiedAt: fileInfo.ModTime(),
  55. Size: fileInfo.Size(),
  56. IsDir: fileInfo.IsDir(),
  57. Enabled: enabledConfigMap[file.Name()],
  58. })
  59. }
  60. }
  61. configs = config.Sort(orderBy, sort, configs)
  62. c.JSON(http.StatusOK, gin.H{
  63. "data": configs,
  64. })
  65. }
  66. func GetStream(c *gin.Context) {
  67. rewriteName, ok := c.Get("rewriteConfigFileName")
  68. name := c.Param("name")
  69. // for modify filename
  70. if ok {
  71. name = rewriteName.(string)
  72. }
  73. path := nginx.GetConfPath("streams-available", name)
  74. file, err := os.Stat(path)
  75. if os.IsNotExist(err) {
  76. c.JSON(http.StatusNotFound, gin.H{
  77. "message": "file not found",
  78. })
  79. return
  80. }
  81. enabled := true
  82. if _, err := os.Stat(nginx.GetConfPath("streams-enabled", name)); os.IsNotExist(err) {
  83. enabled = false
  84. }
  85. g := query.ChatGPTLog
  86. chatgpt, err := g.Where(g.Name.Eq(path)).FirstOrCreate()
  87. if err != nil {
  88. api.ErrHandler(c, err)
  89. return
  90. }
  91. if chatgpt.Content == nil {
  92. chatgpt.Content = make([]openai.ChatCompletionMessage, 0)
  93. }
  94. s := query.Stream
  95. stream, err := s.Where(s.Path.Eq(path)).FirstOrInit()
  96. if err != nil {
  97. api.ErrHandler(c, err)
  98. return
  99. }
  100. if stream.Advanced {
  101. origContent, err := os.ReadFile(path)
  102. if err != nil {
  103. api.ErrHandler(c, err)
  104. return
  105. }
  106. c.JSON(http.StatusOK, Stream{
  107. ModifiedAt: file.ModTime(),
  108. Advanced: stream.Advanced,
  109. Enabled: enabled,
  110. Name: name,
  111. Config: string(origContent),
  112. ChatGPTMessages: chatgpt.Content,
  113. Filepath: path,
  114. })
  115. return
  116. }
  117. nginxConfig, err := nginx.ParseNgxConfig(path)
  118. if err != nil {
  119. api.ErrHandler(c, err)
  120. return
  121. }
  122. c.JSON(http.StatusOK, Stream{
  123. ModifiedAt: file.ModTime(),
  124. Advanced: stream.Advanced,
  125. Enabled: enabled,
  126. Name: name,
  127. Config: nginxConfig.FmtCode(),
  128. Tokenized: nginxConfig,
  129. ChatGPTMessages: chatgpt.Content,
  130. Filepath: path,
  131. })
  132. }
  133. func SaveStream(c *gin.Context) {
  134. name := c.Param("name")
  135. if name == "" {
  136. c.JSON(http.StatusNotAcceptable, gin.H{
  137. "message": "param name is empty",
  138. })
  139. return
  140. }
  141. var json struct {
  142. Name string `json:"name" binding:"required"`
  143. Content string `json:"content" binding:"required"`
  144. Overwrite bool `json:"overwrite"`
  145. }
  146. if !cosy.BindAndValid(c, &json) {
  147. return
  148. }
  149. path := nginx.GetConfPath("streams-available", name)
  150. if !json.Overwrite && helper.FileExists(path) {
  151. c.JSON(http.StatusNotAcceptable, gin.H{
  152. "message": "File exists",
  153. })
  154. return
  155. }
  156. err := os.WriteFile(path, []byte(json.Content), 0644)
  157. if err != nil {
  158. api.ErrHandler(c, err)
  159. return
  160. }
  161. enabledConfigFilePath := nginx.GetConfPath("streams-enabled", name)
  162. // rename the config file if needed
  163. if name != json.Name {
  164. newPath := nginx.GetConfPath("streams-available", json.Name)
  165. s := query.Stream
  166. _, err = s.Where(s.Path.Eq(path)).Update(s.Path, newPath)
  167. // check if dst file exists, do not rename
  168. if helper.FileExists(newPath) {
  169. c.JSON(http.StatusNotAcceptable, gin.H{
  170. "message": "File exists",
  171. })
  172. return
  173. }
  174. // recreate a soft link
  175. if helper.FileExists(enabledConfigFilePath) {
  176. _ = os.Remove(enabledConfigFilePath)
  177. enabledConfigFilePath = nginx.GetConfPath("streams-enabled", json.Name)
  178. err = os.Symlink(newPath, enabledConfigFilePath)
  179. if err != nil {
  180. api.ErrHandler(c, err)
  181. return
  182. }
  183. }
  184. err = os.Rename(path, newPath)
  185. if err != nil {
  186. api.ErrHandler(c, err)
  187. return
  188. }
  189. name = json.Name
  190. c.Set("rewriteConfigFileName", name)
  191. }
  192. enabledConfigFilePath = nginx.GetConfPath("streams-enabled", name)
  193. if helper.FileExists(enabledConfigFilePath) {
  194. // Test nginx configuration
  195. output := nginx.TestConf()
  196. if nginx.GetLogLevel(output) > nginx.Warn {
  197. c.JSON(http.StatusInternalServerError, gin.H{
  198. "message": output,
  199. })
  200. return
  201. }
  202. output = nginx.Reload()
  203. if nginx.GetLogLevel(output) > nginx.Warn {
  204. c.JSON(http.StatusInternalServerError, gin.H{
  205. "message": output,
  206. })
  207. return
  208. }
  209. }
  210. GetStream(c)
  211. }
  212. func EnableStream(c *gin.Context) {
  213. configFilePath := nginx.GetConfPath("streams-available", c.Param("name"))
  214. enabledConfigFilePath := nginx.GetConfPath("streams-enabled", c.Param("name"))
  215. _, err := os.Stat(configFilePath)
  216. if err != nil {
  217. api.ErrHandler(c, err)
  218. return
  219. }
  220. if _, err = os.Stat(enabledConfigFilePath); os.IsNotExist(err) {
  221. err = os.Symlink(configFilePath, enabledConfigFilePath)
  222. if err != nil {
  223. api.ErrHandler(c, err)
  224. return
  225. }
  226. }
  227. // Test nginx config, if not pass, then disable the stream.
  228. output := nginx.TestConf()
  229. if nginx.GetLogLevel(output) > nginx.Warn {
  230. _ = os.Remove(enabledConfigFilePath)
  231. c.JSON(http.StatusInternalServerError, gin.H{
  232. "message": output,
  233. })
  234. return
  235. }
  236. output = nginx.Reload()
  237. if nginx.GetLogLevel(output) > nginx.Warn {
  238. c.JSON(http.StatusInternalServerError, gin.H{
  239. "message": output,
  240. })
  241. return
  242. }
  243. c.JSON(http.StatusOK, gin.H{
  244. "message": "ok",
  245. })
  246. }
  247. func DisableStream(c *gin.Context) {
  248. enabledConfigFilePath := nginx.GetConfPath("streams-enabled", c.Param("name"))
  249. _, err := os.Stat(enabledConfigFilePath)
  250. if err != nil {
  251. api.ErrHandler(c, err)
  252. return
  253. }
  254. err = os.Remove(enabledConfigFilePath)
  255. if err != nil {
  256. api.ErrHandler(c, err)
  257. return
  258. }
  259. output := nginx.Reload()
  260. if nginx.GetLogLevel(output) > nginx.Warn {
  261. c.JSON(http.StatusInternalServerError, gin.H{
  262. "message": output,
  263. })
  264. return
  265. }
  266. c.JSON(http.StatusOK, gin.H{
  267. "message": "ok",
  268. })
  269. }
  270. func DeleteStream(c *gin.Context) {
  271. var err error
  272. name := c.Param("name")
  273. availablePath := nginx.GetConfPath("streams-available", name)
  274. enabledPath := nginx.GetConfPath("streams-enabled", name)
  275. if _, err = os.Stat(availablePath); os.IsNotExist(err) {
  276. c.JSON(http.StatusNotFound, gin.H{
  277. "message": "stream not found",
  278. })
  279. return
  280. }
  281. if _, err = os.Stat(enabledPath); err == nil {
  282. c.JSON(http.StatusNotAcceptable, gin.H{
  283. "message": "stream is enabled",
  284. })
  285. return
  286. }
  287. if err = os.Remove(availablePath); err != nil {
  288. api.ErrHandler(c, err)
  289. return
  290. }
  291. c.JSON(http.StatusOK, gin.H{
  292. "message": "ok",
  293. })
  294. }