streams.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 environment 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 environment 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 environment 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 environment 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 environment group info
  109. if stream, ok := streamsMap[file.Name()]; ok {
  110. envGroupId = stream.EnvGroupID
  111. envGroup = stream.EnvGroup
  112. }
  113. // Apply environment 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. }
  217. // Validate input JSON
  218. if !cosy.BindAndValid(c, &json) {
  219. return
  220. }
  221. // Get stream from database or create if not exists
  222. path := nginx.GetConfPath("streams-available", name)
  223. s := query.Stream
  224. streamModel, err := s.Where(s.Path.Eq(path)).FirstOrCreate()
  225. if err != nil {
  226. cosy.ErrHandler(c, err)
  227. return
  228. }
  229. // Update environment group ID if provided
  230. if json.EnvGroupID > 0 {
  231. streamModel.EnvGroupID = json.EnvGroupID
  232. }
  233. // Update synchronization node IDs if provided
  234. if json.SyncNodeIDs != nil {
  235. streamModel.SyncNodeIDs = json.SyncNodeIDs
  236. }
  237. // Save the updated stream model to database
  238. _, err = s.Where(s.ID.Eq(streamModel.ID)).Updates(streamModel)
  239. if err != nil {
  240. cosy.ErrHandler(c, err)
  241. return
  242. }
  243. // Save the stream configuration file
  244. err = stream.Save(name, json.Content, json.Overwrite, json.SyncNodeIDs)
  245. if err != nil {
  246. cosy.ErrHandler(c, err)
  247. return
  248. }
  249. // Return the updated stream
  250. GetStream(c)
  251. }
  252. func EnableStream(c *gin.Context) {
  253. // Enable the stream by creating a symlink in streams-enabled directory
  254. err := stream.Enable(c.Param("name"))
  255. if err != nil {
  256. cosy.ErrHandler(c, err)
  257. return
  258. }
  259. c.JSON(http.StatusOK, gin.H{
  260. "message": "ok",
  261. })
  262. }
  263. func DisableStream(c *gin.Context) {
  264. // Disable the stream by removing the symlink from streams-enabled directory
  265. err := stream.Disable(c.Param("name"))
  266. if err != nil {
  267. cosy.ErrHandler(c, err)
  268. return
  269. }
  270. c.JSON(http.StatusOK, gin.H{
  271. "message": "ok",
  272. })
  273. }
  274. func DeleteStream(c *gin.Context) {
  275. // Delete the stream configuration file and its symbolic link if exists
  276. err := stream.Delete(c.Param("name"))
  277. if err != nil {
  278. cosy.ErrHandler(c, err)
  279. return
  280. }
  281. c.JSON(http.StatusOK, gin.H{
  282. "message": "ok",
  283. })
  284. }
  285. func RenameStream(c *gin.Context) {
  286. oldName := c.Param("name")
  287. var json struct {
  288. NewName string `json:"new_name"`
  289. }
  290. // Validate input JSON
  291. if !cosy.BindAndValid(c, &json) {
  292. return
  293. }
  294. // Rename the stream configuration file
  295. err := stream.Rename(oldName, json.NewName)
  296. if err != nil {
  297. cosy.ErrHandler(c, err)
  298. return
  299. }
  300. c.JSON(http.StatusOK, gin.H{
  301. "message": "ok",
  302. })
  303. }
  304. func BatchUpdateStreams(c *gin.Context) {
  305. cosy.Core[model.Stream](c).SetValidRules(gin.H{
  306. "env_group_id": "required",
  307. }).SetItemKey("path").
  308. BeforeExecuteHook(func(ctx *cosy.Ctx[model.Stream]) {
  309. effectedPath := make([]string, len(ctx.BatchEffectedIDs))
  310. var streams []*model.Stream
  311. for i, name := range ctx.BatchEffectedIDs {
  312. path := nginx.GetConfPath("streams-available", name)
  313. effectedPath[i] = path
  314. streams = append(streams, &model.Stream{
  315. Path: path,
  316. })
  317. }
  318. s := query.Stream
  319. err := s.Clauses(clause.OnConflict{
  320. DoNothing: true,
  321. }).Create(streams...)
  322. if err != nil {
  323. ctx.AbortWithError(err)
  324. return
  325. }
  326. ctx.BatchEffectedIDs = effectedPath
  327. }).BatchModify()
  328. }