client_link.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package service
  2. import (
  3. "strings"
  4. "github.com/mhsanaei/3x-ui/v3/internal/database"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  6. "gorm.io/gorm"
  7. )
  8. // applyClientRecordMerge merges incoming client-record fields onto row using the
  9. // same rules everywhere a client record is persisted: scalar quota / lifecycle /
  10. // subscription fields are applied unconditionally (so clearing them takes
  11. // effect), while credentials and identifiers are only overwritten when the
  12. // incoming value is non-empty (so a partial update preserves the stored UUID /
  13. // password / keys). CreatedAt keeps the earliest known value. Email, UpdatedAt,
  14. // and the Id primary key are intentionally not touched here — callers handle
  15. // those separately. Shared by SyncInbound (per-inbound persistence) and Update
  16. // (the no-attached-inbound fallback) so the two paths cannot diverge.
  17. func applyClientRecordMerge(row *model.ClientRecord, incoming *model.ClientRecord) {
  18. if incoming.UUID != "" {
  19. row.UUID = incoming.UUID
  20. }
  21. if incoming.Password != "" {
  22. row.Password = incoming.Password
  23. }
  24. if incoming.Auth != "" {
  25. row.Auth = incoming.Auth
  26. }
  27. if incoming.Secret != "" {
  28. row.Secret = incoming.Secret
  29. }
  30. if incoming.AdTag != "" {
  31. row.AdTag = incoming.AdTag
  32. }
  33. row.Flow = incoming.Flow
  34. if incoming.Security != "" {
  35. row.Security = incoming.Security
  36. }
  37. if incoming.Reverse != "" {
  38. row.Reverse = incoming.Reverse
  39. }
  40. if incoming.PrivateKey != "" {
  41. row.PrivateKey = incoming.PrivateKey
  42. }
  43. if incoming.PublicKey != "" {
  44. row.PublicKey = incoming.PublicKey
  45. }
  46. if incoming.AllowedIPs != "" {
  47. row.AllowedIPs = incoming.AllowedIPs
  48. }
  49. row.PreSharedKey = incoming.PreSharedKey
  50. row.KeepAlive = incoming.KeepAlive
  51. row.SubID = incoming.SubID
  52. row.LimitIP = incoming.LimitIP
  53. row.TotalGB = incoming.TotalGB
  54. row.ExpiryTime = incoming.ExpiryTime
  55. row.Enable = incoming.Enable
  56. row.TgID = incoming.TgID
  57. if incoming.Group != "" {
  58. row.Group = incoming.Group
  59. }
  60. row.Comment = incoming.Comment
  61. row.Reset = incoming.Reset
  62. row.ResetMax = incoming.ResetMax
  63. if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
  64. row.CreatedAt = incoming.CreatedAt
  65. }
  66. }
  67. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error {
  68. if tx == nil {
  69. tx = database.GetDB()
  70. }
  71. if err := tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error; err != nil {
  72. return err
  73. }
  74. emails := make([]string, 0, len(clients))
  75. seen := make(map[string]struct{}, len(clients))
  76. for i := range clients {
  77. email := strings.TrimSpace(clients[i].Email)
  78. if email == "" {
  79. continue
  80. }
  81. if _, ok := seen[email]; ok {
  82. continue
  83. }
  84. seen[email] = struct{}{}
  85. emails = append(emails, email)
  86. }
  87. existing := make(map[string]*model.ClientRecord, len(emails))
  88. const selectChunk = 400
  89. for start := 0; start < len(emails); start += selectChunk {
  90. end := min(start+selectChunk, len(emails))
  91. var rows []model.ClientRecord
  92. if err := tx.Where("email IN ?", emails[start:end]).Find(&rows).Error; err != nil {
  93. return err
  94. }
  95. for i := range rows {
  96. r := rows[i]
  97. existing[r.Email] = &r
  98. }
  99. }
  100. idByEmail := make(map[string]int, len(emails))
  101. pending := make(map[string]*model.ClientRecord, len(emails))
  102. toCreate := make([]*model.ClientRecord, 0, len(emails))
  103. for i := range clients {
  104. email := strings.TrimSpace(clients[i].Email)
  105. if email == "" {
  106. continue
  107. }
  108. incoming := clients[i].ToRecord()
  109. // ToRecord copies the raw email; store the trimmed key this function
  110. // looks up by, or a padded email is inserted and never found again.
  111. incoming.Email = email
  112. row, ok := existing[email]
  113. if !ok {
  114. if _, dup := pending[email]; !dup {
  115. pending[email] = incoming
  116. toCreate = append(toCreate, incoming)
  117. }
  118. continue
  119. }
  120. before := *row
  121. applyClientRecordMerge(row, incoming)
  122. preservedUpdatedAt := max(incoming.UpdatedAt, row.UpdatedAt)
  123. row.UpdatedAt = preservedUpdatedAt
  124. idByEmail[email] = row.Id
  125. if *row == before {
  126. continue
  127. }
  128. if err := tx.Save(row).Error; err != nil {
  129. return err
  130. }
  131. if err := tx.Model(&model.ClientRecord{}).
  132. Where("id = ?", row.Id).
  133. UpdateColumn("updated_at", preservedUpdatedAt).Error; err != nil {
  134. return err
  135. }
  136. }
  137. if len(toCreate) > 0 {
  138. if err := tx.CreateInBatches(toCreate, 200).Error; err != nil {
  139. return err
  140. }
  141. for _, rec := range toCreate {
  142. idByEmail[rec.Email] = rec.Id
  143. }
  144. }
  145. links := make([]model.ClientInbound, 0, len(clients))
  146. linked := make(map[int]struct{}, len(clients))
  147. for i := range clients {
  148. email := strings.TrimSpace(clients[i].Email)
  149. if email == "" {
  150. continue
  151. }
  152. id, ok := idByEmail[email]
  153. if !ok {
  154. continue
  155. }
  156. if _, dup := linked[id]; dup {
  157. continue
  158. }
  159. linked[id] = struct{}{}
  160. links = append(links, model.ClientInbound{
  161. ClientId: id,
  162. InboundId: inboundId,
  163. FlowOverride: clients[i].Flow,
  164. })
  165. }
  166. if len(links) > 0 {
  167. if err := tx.CreateInBatches(links, 200).Error; err != nil {
  168. return err
  169. }
  170. }
  171. return nil
  172. }
  173. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  174. if tx == nil {
  175. tx = database.GetDB()
  176. }
  177. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  178. }
  179. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  180. if tx == nil {
  181. tx = database.GetDB()
  182. }
  183. type joinedRow struct {
  184. model.ClientRecord
  185. FlowOverride string
  186. }
  187. var rows []joinedRow
  188. err := tx.Table("clients").
  189. Select("clients.*, client_inbounds.flow_override AS flow_override").
  190. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  191. Where("client_inbounds.inbound_id = ?", inboundId).
  192. Order("clients.id ASC").
  193. Find(&rows).Error
  194. if err != nil {
  195. return nil, err
  196. }
  197. out := make([]model.Client, 0, len(rows))
  198. for i := range rows {
  199. c := rows[i].ToClient()
  200. c.Flow = rows[i].FlowOverride
  201. out = append(out, *c)
  202. }
  203. return out, nil
  204. }
  205. // ListForInboundBySubId is ListForInbound narrowed to one subscription id —
  206. // both filter columns are indexed, so the subscription server resolves a
  207. // subscriber's clients without touching the inbound's settings JSON.
  208. func (s *ClientService) ListForInboundBySubId(tx *gorm.DB, inboundId int, subId string) ([]model.Client, error) {
  209. if tx == nil {
  210. tx = database.GetDB()
  211. }
  212. type joinedRow struct {
  213. model.ClientRecord
  214. FlowOverride string
  215. }
  216. var rows []joinedRow
  217. err := tx.Table("clients").
  218. Select("clients.*, client_inbounds.flow_override AS flow_override").
  219. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  220. Where("client_inbounds.inbound_id = ? AND clients.sub_id = ?", inboundId, subId).
  221. Order("clients.id ASC").
  222. Find(&rows).Error
  223. if err != nil {
  224. return nil, err
  225. }
  226. out := make([]model.Client, 0, len(rows))
  227. for i := range rows {
  228. c := rows[i].ToClient()
  229. c.Flow = rows[i].FlowOverride
  230. out = append(out, *c)
  231. }
  232. return out, nil
  233. }