channel_monitor_v2_handler.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. package handler
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "github.com/Wei-Shaw/sub2api/internal/pkg/response"
  9. "github.com/Wei-Shaw/sub2api/internal/server/middleware"
  10. "github.com/Wei-Shaw/sub2api/internal/service"
  11. "github.com/gin-gonic/gin"
  12. )
  13. type ChannelMonitorV2Handler struct {
  14. service *service.ChannelMonitorV2Service
  15. apiKeyService channelMonitorV2GroupAuthorizer
  16. }
  17. type channelMonitorV2GroupAuthorizer interface {
  18. GetAvailableGroups(ctx context.Context, userID int64) ([]service.Group, error)
  19. }
  20. func NewChannelMonitorV2Handler(svc *service.ChannelMonitorV2Service, apiKeyService *service.APIKeyService) *ChannelMonitorV2Handler {
  21. return &ChannelMonitorV2Handler{service: svc, apiKeyService: apiKeyService}
  22. }
  23. // channelMonitorV2IsAdmin is true when the request already passed admin auth
  24. // (shared Dimensions/Errors handlers serve both user and admin route groups).
  25. func channelMonitorV2IsAdmin(c *gin.Context) bool {
  26. role, ok := middleware.GetUserRoleFromContext(c)
  27. return ok && service.IsAdminRole(role)
  28. }
  29. func (h *ChannelMonitorV2Handler) GetConfig(c *gin.Context) {
  30. cfg, err := h.service.GetConfig(c.Request.Context())
  31. if err != nil {
  32. response.ErrorFrom(c, err)
  33. return
  34. }
  35. response.Success(c, cfg)
  36. }
  37. func (h *ChannelMonitorV2Handler) UpdateConfig(c *gin.Context) {
  38. var input service.ChannelMonitorV2Config
  39. if err := c.ShouldBindJSON(&input); err != nil {
  40. response.BadRequest(c, "invalid channel monitor v2 config")
  41. return
  42. }
  43. subject, ok := middleware.GetAuthSubjectFromContext(c)
  44. if !ok || subject.UserID <= 0 {
  45. response.Unauthorized(c, "user not found in context")
  46. return
  47. }
  48. updated, err := h.service.UpdateConfig(c.Request.Context(), input, input.Version, subject.UserID)
  49. if err != nil {
  50. if errors.Is(err, service.ErrChannelMonitorV2ConfigConflict) {
  51. response.Error(c, http.StatusConflict, err.Error())
  52. return
  53. }
  54. if errors.Is(err, service.ErrChannelMonitorV2InvalidConfig) {
  55. response.BadRequest(c, err.Error())
  56. return
  57. }
  58. response.ErrorFrom(c, err)
  59. return
  60. }
  61. response.Success(c, updated)
  62. }
  63. func (h *ChannelMonitorV2Handler) Dimensions(c *gin.Context) {
  64. filter, ok := h.parseFilter(c)
  65. if !ok {
  66. return
  67. }
  68. admin := channelMonitorV2IsAdmin(c)
  69. if !h.scopeFilter(c, &filter, admin) {
  70. return
  71. }
  72. result, err := h.service.Dimensions(c.Request.Context(), filter)
  73. if err != nil {
  74. response.ErrorFrom(c, err)
  75. return
  76. }
  77. // Admin and user share this handler; only non-admin responses strip volume.
  78. if !admin {
  79. service.RedactChannelMonitorV2Dimensions(result)
  80. }
  81. response.Success(c, result)
  82. }
  83. func (h *ChannelMonitorV2Handler) Snapshot(c *gin.Context) { h.snapshot(c, false) }
  84. func (h *ChannelMonitorV2Handler) AdminSnapshot(c *gin.Context) { h.snapshot(c, true) }
  85. func (h *ChannelMonitorV2Handler) Models(c *gin.Context) { h.models(c, false) }
  86. func (h *ChannelMonitorV2Handler) AdminModels(c *gin.Context) { h.models(c, true) }
  87. func (h *ChannelMonitorV2Handler) Matrix(c *gin.Context) { h.matrix(c, false) }
  88. func (h *ChannelMonitorV2Handler) AdminMatrix(c *gin.Context) { h.matrix(c, true) }
  89. func (h *ChannelMonitorV2Handler) Users(c *gin.Context) { h.users(c, false) }
  90. func (h *ChannelMonitorV2Handler) AdminUsers(c *gin.Context) { h.users(c, true) }
  91. func (h *ChannelMonitorV2Handler) snapshot(c *gin.Context, admin bool) {
  92. filter, ok := h.parseFilter(c)
  93. if !ok {
  94. return
  95. }
  96. if !h.scopeFilter(c, &filter, admin) {
  97. return
  98. }
  99. result, err := h.service.Snapshot(c.Request.Context(), filter, admin)
  100. if err != nil {
  101. response.ErrorFrom(c, err)
  102. return
  103. }
  104. response.Success(c, result)
  105. }
  106. func (h *ChannelMonitorV2Handler) models(c *gin.Context, admin bool) {
  107. filter, ok := h.parseFilter(c)
  108. if !ok {
  109. return
  110. }
  111. if !h.scopeFilter(c, &filter, admin) {
  112. return
  113. }
  114. result, err := h.service.Models(c.Request.Context(), filter, admin)
  115. if err != nil {
  116. response.ErrorFrom(c, err)
  117. return
  118. }
  119. response.Success(c, result)
  120. }
  121. func (h *ChannelMonitorV2Handler) matrix(c *gin.Context, admin bool) {
  122. filter, ok := h.parseFilter(c)
  123. if !ok {
  124. return
  125. }
  126. groupBy, err := service.ParseChannelMonitorV2GroupBy(c.Query("group_by"))
  127. if err != nil {
  128. response.BadRequest(c, err.Error())
  129. return
  130. }
  131. if !h.scopeFilter(c, &filter, admin) {
  132. return
  133. }
  134. result, err := h.service.Matrix(c.Request.Context(), filter, groupBy, admin)
  135. if err != nil {
  136. response.ErrorFrom(c, err)
  137. return
  138. }
  139. response.Success(c, result)
  140. }
  141. func (h *ChannelMonitorV2Handler) Errors(c *gin.Context) {
  142. filter, ok := h.parseFilter(c)
  143. if !ok {
  144. return
  145. }
  146. admin := channelMonitorV2IsAdmin(c)
  147. if !h.scopeFilter(c, &filter, admin) {
  148. return
  149. }
  150. result, err := h.service.ErrorsForViewer(c.Request.Context(), filter, admin)
  151. if err != nil {
  152. response.ErrorFrom(c, err)
  153. return
  154. }
  155. response.Success(c, result)
  156. }
  157. func (h *ChannelMonitorV2Handler) users(c *gin.Context, admin bool) {
  158. filter, ok := h.parseFilter(c)
  159. if !ok {
  160. return
  161. }
  162. subject, exists := middleware.GetAuthSubjectFromContext(c)
  163. if !exists {
  164. response.Error(c, http.StatusUnauthorized, "user not found in context")
  165. return
  166. }
  167. if !h.scopeFilter(c, &filter, admin) {
  168. return
  169. }
  170. result, err := h.service.Users(c.Request.Context(), filter, subject.UserID, admin)
  171. if err != nil {
  172. response.ErrorFrom(c, err)
  173. return
  174. }
  175. response.Success(c, result)
  176. }
  177. func (h *ChannelMonitorV2Handler) scopeFilter(c *gin.Context, filter *service.ChannelMonitorV2Filter, admin bool) bool {
  178. if admin {
  179. return true
  180. }
  181. if h.apiKeyService == nil {
  182. response.Error(c, http.StatusInternalServerError, "channel monitor group authorization unavailable")
  183. return false
  184. }
  185. subject, ok := middleware.GetAuthSubjectFromContext(c)
  186. if !ok || subject.UserID <= 0 {
  187. response.Unauthorized(c, "user not found in context")
  188. return false
  189. }
  190. groups, err := h.apiKeyService.GetAvailableGroups(c.Request.Context(), subject.UserID)
  191. if err != nil {
  192. response.ErrorFrom(c, err)
  193. return false
  194. }
  195. filter.RestrictGroups = true
  196. filter.AllowedGroupIDs = make([]int64, 0, len(groups))
  197. for i := range groups {
  198. filter.AllowedGroupIDs = append(filter.AllowedGroupIDs, groups[i].ID)
  199. }
  200. return true
  201. }
  202. func (h *ChannelMonitorV2Handler) parseFilter(c *gin.Context) (service.ChannelMonitorV2Filter, bool) {
  203. groups, err := parseChannelMonitorV2GroupIDs(queryList(c, "group_id"))
  204. if err != nil {
  205. response.BadRequest(c, "invalid group_id")
  206. return service.ChannelMonitorV2Filter{}, false
  207. }
  208. filter, err := h.service.ParseFilter(c.Query("range"), queryList(c, "platform"), queryList(c, "model"), groups)
  209. if err != nil {
  210. response.BadRequest(c, err.Error())
  211. return service.ChannelMonitorV2Filter{}, false
  212. }
  213. return filter, true
  214. }
  215. func queryList(c *gin.Context, key string) []string {
  216. values := c.QueryArray(key)
  217. result := make([]string, 0, len(values))
  218. for _, value := range values {
  219. for _, part := range strings.Split(value, ",") {
  220. if part = strings.TrimSpace(part); part != "" {
  221. result = append(result, part)
  222. }
  223. }
  224. }
  225. return result
  226. }
  227. func parseChannelMonitorV2GroupIDs(values []string) ([]int64, error) {
  228. result := make([]int64, 0, len(values))
  229. for _, value := range values {
  230. id, err := strconv.ParseInt(value, 10, 64)
  231. if err != nil || id <= 0 {
  232. return nil, errors.New("invalid group id")
  233. }
  234. result = append(result, id)
  235. }
  236. return result, nil
  237. }