streams.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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/helper"
  10. "github.com/0xJacky/Nginx-UI/internal/nginx"
  11. "github.com/0xJacky/Nginx-UI/internal/stream"
  12. "github.com/0xJacky/Nginx-UI/model"
  13. "github.com/0xJacky/Nginx-UI/query"
  14. "github.com/gin-gonic/gin"
  15. "github.com/samber/lo"
  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. Tokenized *nginx.NgxConfig `json:"tokenized,omitempty"`
  27. Filepath string `json:"filepath"`
  28. EnvGroupID uint64 `json:"env_group_id"`
  29. EnvGroup *model.EnvGroup `json:"env_group,omitempty"`
  30. SyncNodeIDs []uint64 `json:"sync_node_ids" gorm:"serializer:json"`
  31. ProxyTargets []config.ProxyTarget `json:"proxy_targets,omitempty"`
  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[nginx.GetConfNameBySymlinkName(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. // Get indexed stream for proxy targets
  116. indexedStream := stream.GetIndexedStream(file.Name())
  117. // Convert stream.ProxyTarget to config.ProxyTarget
  118. var proxyTargets []config.ProxyTarget
  119. for _, target := range indexedStream.ProxyTargets {
  120. proxyTargets = append(proxyTargets, config.ProxyTarget{
  121. Host: target.Host,
  122. Port: target.Port,
  123. Type: target.Type,
  124. })
  125. }
  126. // Add the config to the result list after passing all filters
  127. configs = append(configs, config.Config{
  128. Name: file.Name(),
  129. ModifiedAt: fileInfo.ModTime(),
  130. Size: fileInfo.Size(),
  131. IsDir: fileInfo.IsDir(),
  132. Status: enabledConfigMap[file.Name()],
  133. EnvGroupID: envGroupId,
  134. EnvGroup: envGroup,
  135. ProxyTargets: proxyTargets,
  136. })
  137. }
  138. // Sort the configs based on the provided sort parameters
  139. configs = config.Sort(orderBy, sort, configs)
  140. c.JSON(http.StatusOK, gin.H{
  141. "data": configs,
  142. })
  143. }
  144. func GetStream(c *gin.Context) {
  145. name := helper.UnescapeURL(c.Param("name"))
  146. // Get the absolute path to the stream configuration file
  147. path := nginx.GetConfPath("streams-available", name)
  148. file, err := os.Stat(path)
  149. if os.IsNotExist(err) {
  150. c.JSON(http.StatusNotFound, gin.H{
  151. "message": "file not found",
  152. })
  153. return
  154. }
  155. // Check if the stream is enabled
  156. status := config.StatusEnabled
  157. if _, err := os.Stat(nginx.GetConfPath("streams-enabled", name)); os.IsNotExist(err) {
  158. status = config.StatusDisabled
  159. }
  160. // Retrieve or create stream model from database
  161. s := query.Stream
  162. streamModel, err := s.Where(s.Path.Eq(path)).FirstOrCreate()
  163. if err != nil {
  164. cosy.ErrHandler(c, err)
  165. return
  166. }
  167. // For advanced mode, return the raw content
  168. if streamModel.Advanced {
  169. origContent, err := os.ReadFile(path)
  170. if err != nil {
  171. cosy.ErrHandler(c, err)
  172. return
  173. }
  174. c.JSON(http.StatusOK, Stream{
  175. ModifiedAt: file.ModTime(),
  176. Advanced: streamModel.Advanced,
  177. Status: status,
  178. Name: name,
  179. Config: string(origContent),
  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. Status: status,
  197. Name: name,
  198. Config: nginxConfig.FmtCode(),
  199. Tokenized: nginxConfig,
  200. Filepath: path,
  201. EnvGroupID: streamModel.EnvGroupID,
  202. EnvGroup: streamModel.EnvGroup,
  203. SyncNodeIDs: streamModel.SyncNodeIDs,
  204. })
  205. }
  206. func SaveStream(c *gin.Context) {
  207. name := helper.UnescapeURL(c.Param("name"))
  208. var json struct {
  209. Content string `json:"content" binding:"required"`
  210. EnvGroupID uint64 `json:"env_group_id"`
  211. SyncNodeIDs []uint64 `json:"sync_node_ids"`
  212. Overwrite bool `json:"overwrite"`
  213. PostAction string `json:"post_action"`
  214. }
  215. // Validate input JSON
  216. if !cosy.BindAndValid(c, &json) {
  217. return
  218. }
  219. // Get stream from database or create if not exists
  220. path := nginx.GetConfPath("streams-available", name)
  221. s := query.Stream
  222. streamModel, err := s.Where(s.Path.Eq(path)).FirstOrCreate()
  223. if err != nil {
  224. cosy.ErrHandler(c, err)
  225. return
  226. }
  227. // Update Node Group ID if provided
  228. if json.EnvGroupID > 0 {
  229. streamModel.EnvGroupID = json.EnvGroupID
  230. }
  231. // Update synchronization node IDs if provided
  232. if json.SyncNodeIDs != nil {
  233. streamModel.SyncNodeIDs = json.SyncNodeIDs
  234. }
  235. // Save the updated stream model to database
  236. _, err = s.Where(s.ID.Eq(streamModel.ID)).Updates(streamModel)
  237. if err != nil {
  238. cosy.ErrHandler(c, err)
  239. return
  240. }
  241. // Save the stream configuration file
  242. err = stream.Save(name, json.Content, json.Overwrite, json.SyncNodeIDs, json.PostAction)
  243. if err != nil {
  244. cosy.ErrHandler(c, err)
  245. return
  246. }
  247. // Return the updated stream
  248. GetStream(c)
  249. }
  250. func EnableStream(c *gin.Context) {
  251. // Enable the stream by creating a symlink in streams-enabled directory
  252. err := stream.Enable(helper.UnescapeURL(c.Param("name")))
  253. if err != nil {
  254. cosy.ErrHandler(c, err)
  255. return
  256. }
  257. c.JSON(http.StatusOK, gin.H{
  258. "message": "ok",
  259. })
  260. }
  261. func DisableStream(c *gin.Context) {
  262. // Disable the stream by removing the symlink from streams-enabled directory
  263. err := stream.Disable(helper.UnescapeURL(c.Param("name")))
  264. if err != nil {
  265. cosy.ErrHandler(c, err)
  266. return
  267. }
  268. c.JSON(http.StatusOK, gin.H{
  269. "message": "ok",
  270. })
  271. }
  272. func DeleteStream(c *gin.Context) {
  273. // Delete the stream configuration file and its symbolic link if exists
  274. err := stream.Delete(helper.UnescapeURL(c.Param("name")))
  275. if err != nil {
  276. cosy.ErrHandler(c, err)
  277. return
  278. }
  279. c.JSON(http.StatusOK, gin.H{
  280. "message": "ok",
  281. })
  282. }
  283. func RenameStream(c *gin.Context) {
  284. oldName := helper.UnescapeURL(c.Param("name"))
  285. var json struct {
  286. NewName string `json:"new_name"`
  287. }
  288. // Validate input JSON
  289. if !cosy.BindAndValid(c, &json) {
  290. return
  291. }
  292. // Rename the stream configuration file
  293. err := stream.Rename(oldName, json.NewName)
  294. if err != nil {
  295. cosy.ErrHandler(c, err)
  296. return
  297. }
  298. c.JSON(http.StatusOK, gin.H{
  299. "message": "ok",
  300. })
  301. }
  302. func BatchUpdateStreams(c *gin.Context) {
  303. cosy.Core[model.Stream](c).SetValidRules(gin.H{
  304. "env_group_id": "required",
  305. }).SetItemKey("path").
  306. BeforeExecuteHook(func(ctx *cosy.Ctx[model.Stream]) {
  307. effectedPath := make([]string, len(ctx.BatchEffectedIDs))
  308. var streams []*model.Stream
  309. for i, name := range ctx.BatchEffectedIDs {
  310. path := nginx.GetConfPath("streams-available", name)
  311. effectedPath[i] = path
  312. streams = append(streams, &model.Stream{
  313. Path: path,
  314. })
  315. }
  316. s := query.Stream
  317. err := s.Clauses(clause.OnConflict{
  318. DoNothing: true,
  319. }).Create(streams...)
  320. if err != nil {
  321. ctx.AbortWithError(err)
  322. return
  323. }
  324. ctx.BatchEffectedIDs = effectedPath
  325. }).BatchModify()
  326. }