streams.go 9.3 KB

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