streams.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package streams
  2. import (
  3. "net/http"
  4. "time"
  5. "github.com/0xJacky/Nginx-UI/internal/config"
  6. "github.com/0xJacky/Nginx-UI/internal/helper"
  7. "github.com/0xJacky/Nginx-UI/internal/nginx"
  8. "github.com/0xJacky/Nginx-UI/internal/stream"
  9. "github.com/0xJacky/Nginx-UI/internal/upstream"
  10. "github.com/0xJacky/Nginx-UI/model"
  11. "github.com/0xJacky/Nginx-UI/query"
  12. "github.com/gin-gonic/gin"
  13. "github.com/samber/lo"
  14. "github.com/spf13/cast"
  15. "github.com/uozi-tech/cosy"
  16. "gorm.io/gorm/clause"
  17. )
  18. type Stream struct {
  19. ModifiedAt time.Time `json:"modified_at"`
  20. Advanced bool `json:"advanced"`
  21. Status config.Status `json:"status"`
  22. Name string `json:"name"`
  23. Config string `json:"config"`
  24. Tokenized *nginx.NgxConfig `json:"tokenized,omitempty"`
  25. Filepath string `json:"filepath"`
  26. NamespaceID uint64 `json:"namespace_id"`
  27. Namespace *model.Namespace `json:"namespace,omitempty"`
  28. SyncNodeIDs []uint64 `json:"sync_node_ids" gorm:"serializer:json"`
  29. ProxyTargets []config.ProxyTarget `json:"proxy_targets,omitempty"`
  30. }
  31. // buildProxyTargets processes stream proxy targets similar to list.go logic
  32. func buildStreamProxyTargets(fileName string) []config.ProxyTarget {
  33. indexedStream := stream.GetIndexedStream(fileName)
  34. // Convert proxy targets, expanding upstream references
  35. var proxyTargets []config.ProxyTarget
  36. upstreamService := upstream.GetUpstreamService()
  37. for _, target := range indexedStream.ProxyTargets {
  38. // Check if target.Host is an upstream name
  39. if upstreamDef, exists := upstreamService.GetUpstreamDefinition(target.Host); exists {
  40. // Replace with upstream servers
  41. for _, server := range upstreamDef.Servers {
  42. proxyTargets = append(proxyTargets, config.ProxyTarget{
  43. Host: server.Host,
  44. Port: server.Port,
  45. Type: server.Type,
  46. })
  47. }
  48. } else {
  49. // Regular proxy target
  50. proxyTargets = append(proxyTargets, config.ProxyTarget{
  51. Host: target.Host,
  52. Port: target.Port,
  53. Type: target.Type,
  54. })
  55. }
  56. }
  57. return proxyTargets
  58. }
  59. func GetStreams(c *gin.Context) {
  60. // Parse query parameters
  61. options := &stream.ListOptions{
  62. Search: c.Query("search"),
  63. Name: c.Query("name"),
  64. Status: c.Query("status"),
  65. OrderBy: c.Query("order_by"),
  66. Sort: c.DefaultQuery("sort", "desc"),
  67. NamespaceID: cast.ToUint64(c.Query("namespace_id")),
  68. }
  69. // Get streams from database
  70. s := query.Stream
  71. ns := query.Namespace
  72. // Get environment groups for association
  73. namespaces, err := ns.Find()
  74. if err != nil {
  75. cosy.ErrHandler(c, err)
  76. return
  77. }
  78. // Create environment group map for quick lookup
  79. namespaceMap := lo.SliceToMap(namespaces, func(item *model.Namespace) (uint64, *model.Namespace) {
  80. return item.ID, item
  81. })
  82. // Get streams with optional filtering
  83. var streams []*model.Stream
  84. if options.NamespaceID == 0 {
  85. // Local tab: no namespace OR deploy_mode='local'
  86. localNamespaceIDs := lo.Map(lo.Filter(namespaces, func(item *model.Namespace, _ int) bool {
  87. return item.DeployMode == "local"
  88. }), func(item *model.Namespace, _ int) uint64 {
  89. return item.ID
  90. })
  91. db := cosy.UseDB(c)
  92. if len(localNamespaceIDs) > 0 {
  93. err = db.Where("namespace_id IS NULL OR namespace_id IN (?)", localNamespaceIDs).Find(&streams).Error
  94. } else {
  95. err = db.Where("namespace_id IS NULL").Find(&streams).Error
  96. }
  97. } else {
  98. // Remote tab: specific namespace
  99. streams, err = s.Where(s.NamespaceID.Eq(options.NamespaceID)).Find()
  100. }
  101. if err != nil {
  102. cosy.ErrHandler(c, err)
  103. return
  104. }
  105. // Associate streams with their environment groups
  106. for _, stream := range streams {
  107. if stream.NamespaceID > 0 {
  108. stream.Namespace = namespaceMap[stream.NamespaceID]
  109. }
  110. }
  111. // Get stream configurations using the internal logic
  112. configs, err := stream.GetStreamConfigs(c, options, streams)
  113. if err != nil {
  114. cosy.ErrHandler(c, err)
  115. return
  116. }
  117. c.JSON(http.StatusOK, gin.H{
  118. "data": configs,
  119. })
  120. }
  121. func GetStream(c *gin.Context) {
  122. name := helper.UnescapeURL(c.Param("name"))
  123. // Get stream information using internal logic
  124. info, err := stream.GetStreamInfo(name)
  125. if err != nil {
  126. cosy.ErrHandler(c, err)
  127. return
  128. }
  129. // Build response based on advanced mode
  130. response := Stream{
  131. ModifiedAt: info.FileInfo.ModTime(),
  132. Advanced: info.Model.Advanced,
  133. Status: info.Status,
  134. Name: name,
  135. Filepath: info.Path,
  136. NamespaceID: info.Model.NamespaceID,
  137. Namespace: info.Model.Namespace,
  138. SyncNodeIDs: info.Model.SyncNodeIDs,
  139. ProxyTargets: buildStreamProxyTargets(name),
  140. }
  141. if info.Model.Advanced {
  142. response.Config = info.RawContent
  143. } else {
  144. response.Config = info.NgxConfig.FmtCode()
  145. response.Tokenized = info.NgxConfig
  146. }
  147. c.JSON(http.StatusOK, response)
  148. }
  149. func SaveStream(c *gin.Context) {
  150. name := helper.UnescapeURL(c.Param("name"))
  151. var json struct {
  152. Content string `json:"content" binding:"required"`
  153. NamespaceID uint64 `json:"namespace_id"`
  154. SyncNodeIDs []uint64 `json:"sync_node_ids"`
  155. Overwrite bool `json:"overwrite"`
  156. PostAction string `json:"post_action"`
  157. }
  158. // Validate input JSON
  159. if !cosy.BindAndValid(c, &json) {
  160. return
  161. }
  162. // Save stream configuration using internal logic
  163. err := stream.SaveStreamConfig(name, json.Content, json.NamespaceID, json.SyncNodeIDs, json.Overwrite, json.PostAction)
  164. if err != nil {
  165. cosy.ErrHandler(c, err)
  166. return
  167. }
  168. // Return the updated stream
  169. GetStream(c)
  170. }
  171. func EnableStream(c *gin.Context) {
  172. // Enable the stream by creating a symlink in streams-enabled directory
  173. err := stream.Enable(helper.UnescapeURL(c.Param("name")))
  174. if err != nil {
  175. cosy.ErrHandler(c, err)
  176. return
  177. }
  178. c.JSON(http.StatusOK, gin.H{
  179. "message": "ok",
  180. })
  181. }
  182. func DisableStream(c *gin.Context) {
  183. // Disable the stream by removing the symlink from streams-enabled directory
  184. err := stream.Disable(helper.UnescapeURL(c.Param("name")))
  185. if err != nil {
  186. cosy.ErrHandler(c, err)
  187. return
  188. }
  189. c.JSON(http.StatusOK, gin.H{
  190. "message": "ok",
  191. })
  192. }
  193. func DeleteStream(c *gin.Context) {
  194. // Delete the stream configuration file and its symbolic link if exists
  195. err := stream.Delete(helper.UnescapeURL(c.Param("name")))
  196. if err != nil {
  197. cosy.ErrHandler(c, err)
  198. return
  199. }
  200. c.JSON(http.StatusOK, gin.H{
  201. "message": "ok",
  202. })
  203. }
  204. func RenameStream(c *gin.Context) {
  205. oldName := helper.UnescapeURL(c.Param("name"))
  206. var json struct {
  207. NewName string `json:"new_name"`
  208. }
  209. // Validate input JSON
  210. if !cosy.BindAndValid(c, &json) {
  211. return
  212. }
  213. // Rename the stream configuration file
  214. err := stream.Rename(oldName, json.NewName)
  215. if err != nil {
  216. cosy.ErrHandler(c, err)
  217. return
  218. }
  219. c.JSON(http.StatusOK, gin.H{
  220. "message": "ok",
  221. })
  222. }
  223. func BatchUpdateStreams(c *gin.Context) {
  224. cosy.Core[model.Stream](c).SetValidRules(gin.H{
  225. "namespace_id": "required",
  226. }).SetItemKey("path").
  227. BeforeExecuteHook(func(ctx *cosy.Ctx[model.Stream]) {
  228. effectedPath := make([]string, len(ctx.BatchEffectedIDs))
  229. var streams []*model.Stream
  230. for i, name := range ctx.BatchEffectedIDs {
  231. path := nginx.GetConfPath("streams-available", name)
  232. effectedPath[i] = path
  233. streams = append(streams, &model.Stream{
  234. Path: path,
  235. })
  236. }
  237. s := query.Stream
  238. err := s.Clauses(clause.OnConflict{
  239. DoNothing: true,
  240. }).Create(streams...)
  241. if err != nil {
  242. ctx.AbortWithError(err)
  243. return
  244. }
  245. ctx.BatchEffectedIDs = effectedPath
  246. }).BatchModify()
  247. }