1
0

client_lookup.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "strings"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  9. "gorm.io/gorm"
  10. )
  11. func (s *ClientService) GetRecordByEmail(tx *gorm.DB, email string) (*model.ClientRecord, error) {
  12. if tx == nil {
  13. tx = database.GetDB()
  14. }
  15. row := &model.ClientRecord{}
  16. err := tx.Where("email = ?", email).First(row).Error
  17. if err != nil {
  18. return nil, err
  19. }
  20. return row, nil
  21. }
  22. // EffectiveFlow returns the client's flow from the first flow-capable inbound
  23. // it is attached to (lowest inbound_id with a non-empty flow_override). The
  24. // canonical clients.Flow column is unreliable for multi-inbound clients: a
  25. // non-flow inbound (Hysteria, WS, gRPC, …) carries an empty flow and, when its
  26. // SyncInbound runs last, overwrites the column to "" even though a VLESS Reality
  27. // inbound stored a real flow. The per-inbound flow_override is always correct,
  28. // so derive the display flow from it (order-independent). See issue #4792.
  29. func (s *ClientService) EffectiveFlow(tx *gorm.DB, recordId int) (string, error) {
  30. if tx == nil {
  31. tx = database.GetDB()
  32. }
  33. var flows []string
  34. err := tx.Model(&model.ClientInbound{}).
  35. Where("client_id = ? AND flow_override <> ?", recordId, "").
  36. Order("inbound_id ASC").
  37. Limit(1).
  38. Pluck("flow_override", &flows).Error
  39. if err != nil {
  40. return "", err
  41. }
  42. if len(flows) == 0 {
  43. return "", nil
  44. }
  45. return flows[0], nil
  46. }
  47. // EffectiveFlowsByEmails resolves the intended flow (non-empty flow_override,
  48. // lowest inbound_id first — same rule as EffectiveFlow) for many clients in one
  49. // query, keyed by email. Emails absent from the result carry no flow anywhere.
  50. // Batched so flow restoration on an inbound with many clients is O(1) queries
  51. // instead of O(clients). Used to restore a stripped flow onto an inbound that
  52. // has just become flow-eligible.
  53. func (s *ClientService) EffectiveFlowsByEmails(tx *gorm.DB, emails []string) (map[string]string, error) {
  54. if tx == nil {
  55. tx = database.GetDB()
  56. }
  57. out := make(map[string]string, len(emails))
  58. if len(emails) == 0 {
  59. return out, nil
  60. }
  61. type row struct {
  62. Email string
  63. Flow string `gorm:"column:flow_override"`
  64. }
  65. for _, batch := range chunkStrings(emails, sqlInChunk) {
  66. var rows []row
  67. err := tx.Table("client_inbounds").
  68. Select("clients.email AS email, client_inbounds.flow_override AS flow_override").
  69. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  70. Where("clients.email IN ? AND client_inbounds.flow_override <> ?", batch, "").
  71. Order("client_inbounds.inbound_id ASC").
  72. Scan(&rows).Error
  73. if err != nil {
  74. return nil, err
  75. }
  76. for _, r := range rows {
  77. if _, seen := out[r.Email]; !seen { // ordered by inbound_id ASC → first = lowest
  78. out[r.Email] = r.Flow
  79. }
  80. }
  81. }
  82. return out, nil
  83. }
  84. func (s *ClientService) GetInboundIdsForEmail(tx *gorm.DB, email string) ([]int, error) {
  85. if tx == nil {
  86. tx = database.GetDB()
  87. }
  88. var ids []int
  89. err := tx.Table("client_inbounds").
  90. Select("client_inbounds.inbound_id").
  91. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  92. Where("clients.email = ?", email).
  93. Scan(&ids).Error
  94. if err != nil {
  95. return nil, err
  96. }
  97. return ids, nil
  98. }
  99. func (s *ClientService) GetRecordsByTgID(tgId int64) ([]*model.ClientRecord, error) {
  100. if tgId <= 0 {
  101. return nil, errors.New("tg_id must be a positive integer")
  102. }
  103. var rows []*model.ClientRecord
  104. err := database.GetDB().Where("tg_id = ?", tgId).Find(&rows).Error
  105. return rows, err
  106. }
  107. func (s *ClientService) GetByID(id int) (*model.ClientRecord, error) {
  108. row := &model.ClientRecord{}
  109. if err := database.GetDB().Where("id = ?", id).First(row).Error; err != nil {
  110. return nil, err
  111. }
  112. return row, nil
  113. }
  114. func (s *ClientService) GetInboundIdsForRecord(id int) ([]int, error) {
  115. var ids []int
  116. err := database.GetDB().Table("client_inbounds").
  117. Where("client_id = ?", id).
  118. Order("inbound_id ASC").
  119. Pluck("inbound_id", &ids).Error
  120. if err != nil {
  121. return nil, err
  122. }
  123. return ids, nil
  124. }
  125. func (s *ClientService) List() ([]ClientWithAttachments, error) {
  126. db := database.GetDB()
  127. var rows []model.ClientRecord
  128. if err := db.Order("id ASC").Find(&rows).Error; err != nil {
  129. return nil, err
  130. }
  131. if len(rows) == 0 {
  132. return []ClientWithAttachments{}, nil
  133. }
  134. clientIds := make([]int, 0, len(rows))
  135. emails := make([]string, 0, len(rows))
  136. for i := range rows {
  137. clientIds = append(clientIds, rows[i].Id)
  138. if rows[i].Email != "" {
  139. emails = append(emails, rows[i].Email)
  140. }
  141. }
  142. attachments := make(map[int][]int, len(rows))
  143. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  144. var links []model.ClientInbound
  145. if err := db.Where("client_id IN ?", batch).Find(&links).Error; err != nil {
  146. return nil, err
  147. }
  148. for _, l := range links {
  149. attachments[l.ClientId] = append(attachments[l.ClientId], l.InboundId)
  150. }
  151. }
  152. trafficByEmail := make(map[string]*xray.ClientTraffic, len(emails))
  153. if len(emails) > 0 {
  154. var stats []xray.ClientTraffic
  155. for _, batch := range chunkStrings(emails, sqlInChunk) {
  156. var batchStats []xray.ClientTraffic
  157. if err := db.Where("email IN ?", batch).Find(&batchStats).Error; err != nil {
  158. return nil, err
  159. }
  160. stats = append(stats, batchStats...)
  161. }
  162. overlayGlobalTrafficValues(db, stats)
  163. for i := range stats {
  164. trafficByEmail[stats[i].Email] = &stats[i]
  165. }
  166. }
  167. out := make([]ClientWithAttachments, 0, len(rows))
  168. for i := range rows {
  169. out = append(out, ClientWithAttachments{
  170. ClientRecord: rows[i],
  171. InboundIds: attachments[rows[i].Id],
  172. Traffic: trafficByEmail[rows[i].Email],
  173. })
  174. }
  175. return out, nil
  176. }
  177. func (s *ClientService) HasPendingNode(inboundSvc *InboundService, email string) bool {
  178. if strings.TrimSpace(email) == "" {
  179. return false
  180. }
  181. ids, err := s.GetInboundIdsForEmail(nil, email)
  182. if err != nil {
  183. return false
  184. }
  185. return inboundSvc.AnyNodePending(ids)
  186. }
  187. // findInboundIdsByClientEmail returns every inbound whose settings.clients[]
  188. // JSON contains an entry with the given email. Driver-portable (no JSON
  189. // operators) by parsing in Go — fine for the rare fallback path.
  190. func (s *ClientService) findInboundIdsByClientEmail(email string) ([]int, error) {
  191. var inbounds []model.Inbound
  192. if err := database.GetDB().
  193. Select("id, settings").
  194. Where("settings LIKE ?", "%"+email+"%").
  195. Find(&inbounds).Error; err != nil {
  196. return nil, err
  197. }
  198. out := make([]int, 0, len(inbounds))
  199. for _, ib := range inbounds {
  200. var settings map[string]any
  201. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  202. continue
  203. }
  204. clients, ok := settings["clients"].([]any)
  205. if !ok {
  206. continue
  207. }
  208. for _, c := range clients {
  209. cm, ok := c.(map[string]any)
  210. if !ok {
  211. continue
  212. }
  213. if cEmail, _ := cm["email"].(string); cEmail == email {
  214. out = append(out, ib.Id)
  215. break
  216. }
  217. }
  218. }
  219. return out, nil
  220. }