streams.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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.ConfigStatus `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. streams, err = s.Where(s.NamespaceID.Eq(options.NamespaceID)).Find()
  86. } else {
  87. streams, err = s.Find()
  88. }
  89. if err != nil {
  90. cosy.ErrHandler(c, err)
  91. return
  92. }
  93. // Associate streams with their environment groups
  94. for _, stream := range streams {
  95. if stream.NamespaceID > 0 {
  96. stream.Namespace = namespaceMap[stream.NamespaceID]
  97. }
  98. }
  99. // Get stream configurations using the internal logic
  100. configs, err := stream.GetStreamConfigs(c, options, streams)
  101. if err != nil {
  102. cosy.ErrHandler(c, err)
  103. return
  104. }
  105. c.JSON(http.StatusOK, gin.H{
  106. "data": configs,
  107. })
  108. }
  109. func GetStream(c *gin.Context) {
  110. name := helper.UnescapeURL(c.Param("name"))
  111. // Get stream information using internal logic
  112. info, err := stream.GetStreamInfo(name)
  113. if err != nil {
  114. cosy.ErrHandler(c, err)
  115. return
  116. }
  117. // Build response based on advanced mode
  118. response := Stream{
  119. ModifiedAt: info.FileInfo.ModTime(),
  120. Advanced: info.Model.Advanced,
  121. Status: info.Status,
  122. Name: name,
  123. Filepath: info.Path,
  124. NamespaceID: info.Model.NamespaceID,
  125. Namespace: info.Model.Namespace,
  126. SyncNodeIDs: info.Model.SyncNodeIDs,
  127. ProxyTargets: buildStreamProxyTargets(name),
  128. }
  129. if info.Model.Advanced {
  130. response.Config = info.RawContent
  131. } else {
  132. response.Config = info.NgxConfig.FmtCode()
  133. response.Tokenized = info.NgxConfig
  134. }
  135. c.JSON(http.StatusOK, response)
  136. }
  137. func SaveStream(c *gin.Context) {
  138. name := helper.UnescapeURL(c.Param("name"))
  139. var json struct {
  140. Content string `json:"content" binding:"required"`
  141. NamespaceID uint64 `json:"namespace_id"`
  142. SyncNodeIDs []uint64 `json:"sync_node_ids"`
  143. Overwrite bool `json:"overwrite"`
  144. PostAction string `json:"post_action"`
  145. }
  146. // Validate input JSON
  147. if !cosy.BindAndValid(c, &json) {
  148. return
  149. }
  150. // Save stream configuration using internal logic
  151. err := stream.SaveStreamConfig(name, json.Content, json.NamespaceID, json.SyncNodeIDs, json.Overwrite, json.PostAction)
  152. if err != nil {
  153. cosy.ErrHandler(c, err)
  154. return
  155. }
  156. // Return the updated stream
  157. GetStream(c)
  158. }
  159. func EnableStream(c *gin.Context) {
  160. // Enable the stream by creating a symlink in streams-enabled directory
  161. err := stream.Enable(helper.UnescapeURL(c.Param("name")))
  162. if err != nil {
  163. cosy.ErrHandler(c, err)
  164. return
  165. }
  166. c.JSON(http.StatusOK, gin.H{
  167. "message": "ok",
  168. })
  169. }
  170. func DisableStream(c *gin.Context) {
  171. // Disable the stream by removing the symlink from streams-enabled directory
  172. err := stream.Disable(helper.UnescapeURL(c.Param("name")))
  173. if err != nil {
  174. cosy.ErrHandler(c, err)
  175. return
  176. }
  177. c.JSON(http.StatusOK, gin.H{
  178. "message": "ok",
  179. })
  180. }
  181. func DeleteStream(c *gin.Context) {
  182. // Delete the stream configuration file and its symbolic link if exists
  183. err := stream.Delete(helper.UnescapeURL(c.Param("name")))
  184. if err != nil {
  185. cosy.ErrHandler(c, err)
  186. return
  187. }
  188. c.JSON(http.StatusOK, gin.H{
  189. "message": "ok",
  190. })
  191. }
  192. func RenameStream(c *gin.Context) {
  193. oldName := helper.UnescapeURL(c.Param("name"))
  194. var json struct {
  195. NewName string `json:"new_name"`
  196. }
  197. // Validate input JSON
  198. if !cosy.BindAndValid(c, &json) {
  199. return
  200. }
  201. // Rename the stream configuration file
  202. err := stream.Rename(oldName, json.NewName)
  203. if err != nil {
  204. cosy.ErrHandler(c, err)
  205. return
  206. }
  207. c.JSON(http.StatusOK, gin.H{
  208. "message": "ok",
  209. })
  210. }
  211. func BatchUpdateStreams(c *gin.Context) {
  212. cosy.Core[model.Stream](c).SetValidRules(gin.H{
  213. "namespace_id": "required",
  214. }).SetItemKey("path").
  215. BeforeExecuteHook(func(ctx *cosy.Ctx[model.Stream]) {
  216. effectedPath := make([]string, len(ctx.BatchEffectedIDs))
  217. var streams []*model.Stream
  218. for i, name := range ctx.BatchEffectedIDs {
  219. path := nginx.GetConfPath("streams-available", name)
  220. effectedPath[i] = path
  221. streams = append(streams, &model.Stream{
  222. Path: path,
  223. })
  224. }
  225. s := query.Stream
  226. err := s.Clauses(clause.OnConflict{
  227. DoNothing: true,
  228. }).Create(streams...)
  229. if err != nil {
  230. ctx.AbortWithError(err)
  231. return
  232. }
  233. ctx.BatchEffectedIDs = effectedPath
  234. }).BatchModify()
  235. }