streams.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package streams
  2. import (
  3. "net/http"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "time"
  8. "github.com/0xJacky/Nginx-UI/internal/config"
  9. "github.com/0xJacky/Nginx-UI/internal/nginx"
  10. "github.com/0xJacky/Nginx-UI/internal/stream"
  11. "github.com/0xJacky/Nginx-UI/model"
  12. "github.com/0xJacky/Nginx-UI/query"
  13. "github.com/gin-gonic/gin"
  14. "github.com/samber/lo"
  15. "github.com/sashabaranov/go-openai"
  16. "github.com/spf13/cast"
  17. "github.com/uozi-tech/cosy"
  18. "gorm.io/gorm/clause"
  19. )
  20. type Stream struct {
  21. ModifiedAt time.Time `json:"modified_at"`
  22. Advanced bool `json:"advanced"`
  23. Status config.ConfigStatus `json:"status"`
  24. Name string `json:"name"`
  25. Config string `json:"config"`
  26. ChatGPTMessages []openai.ChatCompletionMessage `json:"chatgpt_messages,omitempty"`
  27. Tokenized *nginx.NgxConfig `json:"tokenized,omitempty"`
  28. Filepath string `json:"filepath"`
  29. EnvGroupID uint64 `json:"env_group_id"`
  30. EnvGroup *model.EnvGroup `json:"env_group,omitempty"`
  31. SyncNodeIDs []uint64 `json:"sync_node_ids" gorm:"serializer:json"`
  32. ProxyTargets []config.ProxyTarget `json:"proxy_targets,omitempty"`
  33. }
  34. func GetStreams(c *gin.Context) {
  35. name := c.Query("name")
  36. status := c.Query("status")
  37. orderBy := c.Query("order_by")
  38. sort := c.DefaultQuery("sort", "desc")
  39. queryEnvGroupId := cast.ToUint64(c.Query("env_group_id"))
  40. configFiles, err := os.ReadDir(nginx.GetConfPath("streams-available"))
  41. if err != nil {
  42. cosy.ErrHandler(c, cosy.WrapErrorWithParams(stream.ErrReadDirFailed, err.Error()))
  43. return
  44. }
  45. enabledConfig, err := os.ReadDir(nginx.GetConfPath("streams-enabled"))
  46. if err != nil {
  47. cosy.ErrHandler(c, cosy.WrapErrorWithParams(stream.ErrReadDirFailed, err.Error()))
  48. return
  49. }
  50. enabledConfigMap := make(map[string]config.ConfigStatus)
  51. for _, file := range configFiles {
  52. enabledConfigMap[file.Name()] = config.StatusDisabled
  53. }
  54. for i := range enabledConfig {
  55. enabledConfigMap[nginx.GetConfNameBySymlinkName(enabledConfig[i].Name())] = config.StatusEnabled
  56. }
  57. var configs []config.Config
  58. // Get all streams map for Node Group lookup
  59. s := query.Stream
  60. var streams []*model.Stream
  61. if queryEnvGroupId != 0 {
  62. streams, err = s.Where(s.EnvGroupID.Eq(queryEnvGroupId)).Find()
  63. } else {
  64. streams, err = s.Find()
  65. }
  66. if err != nil {
  67. cosy.ErrHandler(c, err)
  68. return
  69. }
  70. // Retrieve Node Groups data
  71. eg := query.EnvGroup
  72. envGroups, err := eg.Find()
  73. if err != nil {
  74. cosy.ErrHandler(c, err)
  75. return
  76. }
  77. // Create a map of Node Groups for quick lookup by ID
  78. envGroupMap := lo.SliceToMap(envGroups, func(item *model.EnvGroup) (uint64, *model.EnvGroup) {
  79. return item.ID, item
  80. })
  81. // Convert streams slice to map for efficient lookups
  82. streamsMap := lo.SliceToMap(streams, func(item *model.Stream) (string, *model.Stream) {
  83. // Associate each stream with its corresponding Node Group
  84. if item.EnvGroupID > 0 {
  85. item.EnvGroup = envGroupMap[item.EnvGroupID]
  86. }
  87. return filepath.Base(item.Path), item
  88. })
  89. for i := range configFiles {
  90. file := configFiles[i]
  91. fileInfo, _ := file.Info()
  92. if file.IsDir() {
  93. continue
  94. }
  95. // Apply name filter if specified
  96. if name != "" && !strings.Contains(file.Name(), name) {
  97. continue
  98. }
  99. // Apply enabled status filter if specified
  100. if status != "" && enabledConfigMap[file.Name()] != config.ConfigStatus(status) {
  101. continue
  102. }
  103. var (
  104. envGroupId uint64
  105. envGroup *model.EnvGroup
  106. )
  107. // Lookup stream in the streams map to get Node Group info
  108. if stream, ok := streamsMap[file.Name()]; ok {
  109. envGroupId = stream.EnvGroupID
  110. envGroup = stream.EnvGroup
  111. }
  112. // Apply Node Group filter if specified
  113. if queryEnvGroupId != 0 && envGroupId != queryEnvGroupId {
  114. continue
  115. }
  116. // Get indexed stream for proxy targets
  117. indexedStream := stream.GetIndexedStream(file.Name())
  118. // Convert stream.ProxyTarget to config.ProxyTarget
  119. var proxyTargets []config.ProxyTarget
  120. for _, target := range indexedStream.ProxyTargets {
  121. proxyTargets = append(proxyTargets, config.ProxyTarget{
  122. Host: target.Host,
  123. Port: target.Port,
  124. Type: target.Type,
  125. })
  126. }
  127. // Add the config to the result list after passing all filters
  128. configs = append(configs, config.Config{
  129. Name: file.Name(),
  130. ModifiedAt: fileInfo.ModTime(),
  131. Size: fileInfo.Size(),
  132. IsDir: fileInfo.IsDir(),
  133. Status: enabledConfigMap[file.Name()],
  134. EnvGroupID: envGroupId,
  135. EnvGroup: envGroup,
  136. ProxyTargets: proxyTargets,
  137. })
  138. }
  139. // Sort the configs based on the provided sort parameters
  140. configs = config.Sort(orderBy, sort, configs)
  141. c.JSON(http.StatusOK, gin.H{
  142. "data": configs,
  143. })
  144. }
  145. func GetStream(c *gin.Context) {
  146. name := c.Param("name")
  147. // Get the absolute path to the stream configuration file
  148. path := nginx.GetConfPath("streams-available", name)
  149. file, err := os.Stat(path)
  150. if os.IsNotExist(err) {
  151. c.JSON(http.StatusNotFound, gin.H{
  152. "message": "file not found",
  153. })
  154. return
  155. }
  156. // Check if the stream is enabled
  157. status := config.StatusEnabled
  158. if _, err := os.Stat(nginx.GetConfPath("streams-enabled", name)); os.IsNotExist(err) {
  159. status = config.StatusDisabled
  160. }
  161. // Retrieve or create ChatGPT log for this stream
  162. g := query.ChatGPTLog
  163. chatgpt, err := g.Where(g.Name.Eq(path)).FirstOrCreate()
  164. if err != nil {
  165. cosy.ErrHandler(c, err)
  166. return
  167. }
  168. // Initialize empty content if nil
  169. if chatgpt.Content == nil {
  170. chatgpt.Content = make([]openai.ChatCompletionMessage, 0)
  171. }
  172. // Retrieve or create stream model from database
  173. s := query.Stream
  174. streamModel, err := s.Where(s.Path.Eq(path)).FirstOrCreate()
  175. if err != nil {
  176. cosy.ErrHandler(c, err)
  177. return
  178. }
  179. // For advanced mode, return the raw content
  180. if streamModel.Advanced {
  181. origContent, err := os.ReadFile(path)
  182. if err != nil {
  183. cosy.ErrHandler(c, err)
  184. return
  185. }
  186. c.JSON(http.StatusOK, Stream{
  187. ModifiedAt: file.ModTime(),
  188. Advanced: streamModel.Advanced,
  189. Status: status,
  190. Name: name,
  191. Config: string(origContent),
  192. ChatGPTMessages: chatgpt.Content,
  193. Filepath: path,
  194. EnvGroupID: streamModel.EnvGroupID,
  195. EnvGroup: streamModel.EnvGroup,
  196. SyncNodeIDs: streamModel.SyncNodeIDs,
  197. })
  198. return
  199. }
  200. // For normal mode, parse and tokenize the configuration
  201. nginxConfig, err := nginx.ParseNgxConfig(path)
  202. if err != nil {
  203. cosy.ErrHandler(c, err)
  204. return
  205. }
  206. c.JSON(http.StatusOK, Stream{
  207. ModifiedAt: file.ModTime(),
  208. Advanced: streamModel.Advanced,
  209. Status: status,
  210. Name: name,
  211. Config: nginxConfig.FmtCode(),
  212. Tokenized: nginxConfig,
  213. ChatGPTMessages: chatgpt.Content,
  214. Filepath: path,
  215. EnvGroupID: streamModel.EnvGroupID,
  216. EnvGroup: streamModel.EnvGroup,
  217. SyncNodeIDs: streamModel.SyncNodeIDs,
  218. })
  219. }
  220. func SaveStream(c *gin.Context) {
  221. name := c.Param("name")
  222. var json struct {
  223. Content string `json:"content" binding:"required"`
  224. EnvGroupID uint64 `json:"env_group_id"`
  225. SyncNodeIDs []uint64 `json:"sync_node_ids"`
  226. Overwrite bool `json:"overwrite"`
  227. PostAction string `json:"post_action"`
  228. }
  229. // Validate input JSON
  230. if !cosy.BindAndValid(c, &json) {
  231. return
  232. }
  233. // Get stream from database or create if not exists
  234. path := nginx.GetConfPath("streams-available", name)
  235. s := query.Stream
  236. streamModel, err := s.Where(s.Path.Eq(path)).FirstOrCreate()
  237. if err != nil {
  238. cosy.ErrHandler(c, err)
  239. return
  240. }
  241. // Update Node Group ID if provided
  242. if json.EnvGroupID > 0 {
  243. streamModel.EnvGroupID = json.EnvGroupID
  244. }
  245. // Update synchronization node IDs if provided
  246. if json.SyncNodeIDs != nil {
  247. streamModel.SyncNodeIDs = json.SyncNodeIDs
  248. }
  249. // Save the updated stream model to database
  250. _, err = s.Where(s.ID.Eq(streamModel.ID)).Updates(streamModel)
  251. if err != nil {
  252. cosy.ErrHandler(c, err)
  253. return
  254. }
  255. // Save the stream configuration file
  256. err = stream.Save(name, json.Content, json.Overwrite, json.SyncNodeIDs, json.PostAction)
  257. if err != nil {
  258. cosy.ErrHandler(c, err)
  259. return
  260. }
  261. // Return the updated stream
  262. GetStream(c)
  263. }
  264. func EnableStream(c *gin.Context) {
  265. // Enable the stream by creating a symlink in streams-enabled directory
  266. err := stream.Enable(c.Param("name"))
  267. if err != nil {
  268. cosy.ErrHandler(c, err)
  269. return
  270. }
  271. c.JSON(http.StatusOK, gin.H{
  272. "message": "ok",
  273. })
  274. }
  275. func DisableStream(c *gin.Context) {
  276. // Disable the stream by removing the symlink from streams-enabled directory
  277. err := stream.Disable(c.Param("name"))
  278. if err != nil {
  279. cosy.ErrHandler(c, err)
  280. return
  281. }
  282. c.JSON(http.StatusOK, gin.H{
  283. "message": "ok",
  284. })
  285. }
  286. func DeleteStream(c *gin.Context) {
  287. // Delete the stream configuration file and its symbolic link if exists
  288. err := stream.Delete(c.Param("name"))
  289. if err != nil {
  290. cosy.ErrHandler(c, err)
  291. return
  292. }
  293. c.JSON(http.StatusOK, gin.H{
  294. "message": "ok",
  295. })
  296. }
  297. func RenameStream(c *gin.Context) {
  298. oldName := c.Param("name")
  299. var json struct {
  300. NewName string `json:"new_name"`
  301. }
  302. // Validate input JSON
  303. if !cosy.BindAndValid(c, &json) {
  304. return
  305. }
  306. // Rename the stream configuration file
  307. err := stream.Rename(oldName, json.NewName)
  308. if err != nil {
  309. cosy.ErrHandler(c, err)
  310. return
  311. }
  312. c.JSON(http.StatusOK, gin.H{
  313. "message": "ok",
  314. })
  315. }
  316. func BatchUpdateStreams(c *gin.Context) {
  317. cosy.Core[model.Stream](c).SetValidRules(gin.H{
  318. "env_group_id": "required",
  319. }).SetItemKey("path").
  320. BeforeExecuteHook(func(ctx *cosy.Ctx[model.Stream]) {
  321. effectedPath := make([]string, len(ctx.BatchEffectedIDs))
  322. var streams []*model.Stream
  323. for i, name := range ctx.BatchEffectedIDs {
  324. path := nginx.GetConfPath("streams-available", name)
  325. effectedPath[i] = path
  326. streams = append(streams, &model.Stream{
  327. Path: path,
  328. })
  329. }
  330. s := query.Stream
  331. err := s.Clauses(clause.OnConflict{
  332. DoNothing: true,
  333. }).Create(streams...)
  334. if err != nil {
  335. ctx.AbortWithError(err)
  336. return
  337. }
  338. ctx.BatchEffectedIDs = effectedPath
  339. }).BatchModify()
  340. }