client_traffic.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. package service
  2. import (
  3. "strings"
  4. "time"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  7. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  8. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  9. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  10. "gorm.io/gorm"
  11. )
  12. func (s *ClientService) ResetTrafficByEmail(inboundSvc *InboundService, email string) (bool, error) {
  13. if email == "" {
  14. return false, common.NewError("client email is required")
  15. }
  16. rec, err := s.GetRecordByEmail(nil, email)
  17. if err != nil {
  18. return false, err
  19. }
  20. inboundIds, err := s.GetInboundIdsForRecord(rec.Id)
  21. if err != nil {
  22. return false, err
  23. }
  24. needRestart := false
  25. if !rec.Enable {
  26. updated := rec.ToClient()
  27. updated.Enable = true
  28. nr, uErr := s.Update(inboundSvc, rec.Id, *updated, rec.LimitHwid)
  29. if uErr != nil {
  30. logger.Warning("Failed to auto-enable client during traffic reset:", uErr)
  31. }
  32. if nr {
  33. needRestart = true
  34. }
  35. }
  36. if len(inboundIds) == 0 {
  37. if rErr := inboundSvc.ResetClientTrafficByEmail(email); rErr != nil {
  38. return false, rErr
  39. }
  40. return needRestart, nil
  41. }
  42. applies := make([]inboundApply, 0, len(inboundIds))
  43. for _, ibId := range inboundIds {
  44. applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) {
  45. return inboundSvc.ResetClientTraffic(ibId, email)
  46. }})
  47. }
  48. nr, applyErr := fanoutInboundApplies(applies)
  49. return needRestart || nr, applyErr
  50. }
  51. func (s *ClientService) BulkResetTraffic(inboundSvc *InboundService, emails []string) (int, error) {
  52. if len(emails) == 0 {
  53. return 0, nil
  54. }
  55. seen := map[string]struct{}{}
  56. cleanEmails := make([]string, 0, len(emails))
  57. for _, e := range emails {
  58. e = strings.TrimSpace(e)
  59. if e == "" {
  60. continue
  61. }
  62. if _, ok := seen[e]; ok {
  63. continue
  64. }
  65. seen[e] = struct{}{}
  66. cleanEmails = append(cleanEmails, e)
  67. }
  68. if len(cleanEmails) == 0 {
  69. return 0, nil
  70. }
  71. for _, e := range cleanEmails {
  72. rec, err := s.GetRecordByEmail(nil, e)
  73. if err == nil && !rec.Enable {
  74. updated := rec.ToClient()
  75. updated.Enable = true
  76. if _, uErr := s.Update(inboundSvc, rec.Id, *updated, rec.LimitHwid); uErr != nil {
  77. logger.Warning("Failed to auto-enable client during bulk traffic reset:", uErr)
  78. }
  79. }
  80. }
  81. affected := 0
  82. err := submitTrafficWrite(func() error {
  83. db := database.GetDB()
  84. return db.Transaction(func(tx *gorm.DB) error {
  85. if err := adjustGroupBaselinesForRemovedTraffic(tx, cleanEmails); err != nil {
  86. return err
  87. }
  88. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  89. res := tx.Model(xray.ClientTraffic{}).
  90. Where("email IN ?", batch).
  91. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  92. if res.Error != nil {
  93. return res.Error
  94. }
  95. affected += int(res.RowsAffected)
  96. }
  97. if err := clearGlobalTraffic(tx, cleanEmails...); err != nil {
  98. return err
  99. }
  100. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  101. if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  102. return err
  103. }
  104. }
  105. return nil
  106. })
  107. })
  108. if err != nil {
  109. return 0, err
  110. }
  111. return affected, nil
  112. }
  113. func (s *ClientService) ResetAllClientTraffics(inboundSvc *InboundService, id int) error {
  114. err := submitTrafficWrite(func() error {
  115. return s.resetAllClientTrafficsLocked(id)
  116. })
  117. if err == nil {
  118. inboundSvc.resetAllMtprotoQuotas()
  119. }
  120. return err
  121. }
  122. func (s *ClientService) resetAllClientTrafficsLocked(id int) error {
  123. db := database.GetDB()
  124. now := time.Now().Unix() * 1000
  125. if err := db.Transaction(func(tx *gorm.DB) error {
  126. // client_traffics.inbound_id is stale: it reflects the inbound the row was
  127. // first inserted under and is never refreshed. Use the client_inbounds join
  128. // as the authoritative source for which emails belong to a given inbound.
  129. var resetEmails []string
  130. if id == -1 {
  131. if err := tx.Model(xray.ClientTraffic{}).Pluck("email", &resetEmails).Error; err != nil {
  132. return err
  133. }
  134. } else {
  135. if err := tx.Table("client_inbounds ci").
  136. Select("c.email").
  137. Joins("JOIN clients c ON c.id = ci.client_id").
  138. Where("ci.inbound_id = ?", id).
  139. Pluck("c.email", &resetEmails).Error; err != nil {
  140. return err
  141. }
  142. }
  143. if len(resetEmails) == 0 {
  144. return nil
  145. }
  146. if err := adjustGroupBaselinesForRemovedTraffic(tx, resetEmails); err != nil {
  147. return err
  148. }
  149. result := tx.Model(xray.ClientTraffic{}).
  150. Where("email IN ?", resetEmails).
  151. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  152. if result.Error != nil {
  153. return result.Error
  154. }
  155. if err := clearGlobalTraffic(tx, resetEmails...); err != nil {
  156. return err
  157. }
  158. for _, batch := range chunkStrings(resetEmails, sqlInChunk) {
  159. if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  160. return err
  161. }
  162. }
  163. inboundWhereText := "id "
  164. if id == -1 {
  165. inboundWhereText += " > ?"
  166. } else {
  167. inboundWhereText += " = ?"
  168. }
  169. result = tx.Model(model.Inbound{}).
  170. Where(inboundWhereText, id).
  171. Update("last_traffic_reset_time", now)
  172. return result.Error
  173. }); err != nil {
  174. return err
  175. }
  176. return nil
  177. }
  178. func (s *ClientService) ResetAllTraffics() (bool, error) {
  179. var affected int64
  180. err := submitTrafficWrite(func() error {
  181. return database.GetDB().Transaction(func(tx *gorm.DB) error {
  182. res := tx.Model(&xray.ClientTraffic{}).
  183. Where("1 = 1").
  184. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  185. if res.Error != nil {
  186. return res.Error
  187. }
  188. affected = res.RowsAffected
  189. if err := tx.Where("1 = 1").Delete(&model.ClientGlobalTraffic{}).Error; err != nil {
  190. return err
  191. }
  192. return tx.Where("1 = 1").Delete(&model.NodeClientTraffic{}).Error
  193. })
  194. })
  195. if err != nil {
  196. return false, err
  197. }
  198. return affected > 0, nil
  199. }