streams.go 9.4 KB

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