client_link.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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.ResetDay = incoming.ResetDay
  63. row.ResetMax = incoming.ResetMax
  64. if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
  65. row.CreatedAt = incoming.CreatedAt
  66. }
  67. }
  68. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error {
  69. if tx == nil {
  70. tx = database.GetDB()
  71. }
  72. if err := tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error; err != nil {
  73. return err
  74. }
  75. emails := make([]string, 0, len(clients))
  76. seen := make(map[string]struct{}, len(clients))
  77. for i := range clients {
  78. email := strings.TrimSpace(clients[i].Email)
  79. if email == "" {
  80. continue
  81. }
  82. if _, ok := seen[email]; ok {
  83. continue
  84. }
  85. seen[email] = struct{}{}
  86. emails = append(emails, email)
  87. }
  88. existing := make(map[string]*model.ClientRecord, len(emails))
  89. const selectChunk = 400
  90. for start := 0; start < len(emails); start += selectChunk {
  91. end := min(start+selectChunk, len(emails))
  92. var rows []model.ClientRecord
  93. if err := tx.Where("email IN ?", emails[start:end]).Find(&rows).Error; err != nil {
  94. return err
  95. }
  96. for i := range rows {
  97. r := rows[i]
  98. existing[r.Email] = &r
  99. }
  100. }
  101. idByEmail := make(map[string]int, len(emails))
  102. pending := make(map[string]*model.ClientRecord, len(emails))
  103. toCreate := make([]*model.ClientRecord, 0, len(emails))
  104. for i := range clients {
  105. email := strings.TrimSpace(clients[i].Email)
  106. if email == "" {
  107. continue
  108. }
  109. incoming := clients[i].ToRecord()
  110. // ToRecord copies the raw email; store the trimmed key this function
  111. // looks up by, or a padded email is inserted and never found again.
  112. incoming.Email = email
  113. row, ok := existing[email]
  114. if !ok {
  115. if _, dup := pending[email]; !dup {
  116. pending[email] = incoming
  117. toCreate = append(toCreate, incoming)
  118. }
  119. continue
  120. }
  121. before := *row
  122. applyClientRecordMerge(row, incoming)
  123. preservedUpdatedAt := max(incoming.UpdatedAt, row.UpdatedAt)
  124. row.UpdatedAt = preservedUpdatedAt
  125. idByEmail[email] = row.Id
  126. if *row == before {
  127. continue
  128. }
  129. if err := tx.Save(row).Error; err != nil {
  130. return err
  131. }
  132. if err := tx.Model(&model.ClientRecord{}).
  133. Where("id = ?", row.Id).
  134. UpdateColumn("updated_at", preservedUpdatedAt).Error; err != nil {
  135. return err
  136. }
  137. }
  138. if len(toCreate) > 0 {
  139. if err := tx.CreateInBatches(toCreate, 200).Error; err != nil {
  140. return err
  141. }
  142. for _, rec := range toCreate {
  143. idByEmail[rec.Email] = rec.Id
  144. }
  145. }
  146. links := make([]model.ClientInbound, 0, len(clients))
  147. linked := make(map[int]struct{}, len(clients))
  148. for i := range clients {
  149. email := strings.TrimSpace(clients[i].Email)
  150. if email == "" {
  151. continue
  152. }
  153. id, ok := idByEmail[email]
  154. if !ok {
  155. continue
  156. }
  157. if _, dup := linked[id]; dup {
  158. continue
  159. }
  160. linked[id] = struct{}{}
  161. links = append(links, model.ClientInbound{
  162. ClientId: id,
  163. InboundId: inboundId,
  164. FlowOverride: clients[i].Flow,
  165. })
  166. }
  167. if len(links) > 0 {
  168. if err := tx.CreateInBatches(links, 200).Error; err != nil {
  169. return err
  170. }
  171. }
  172. return nil
  173. }
  174. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  175. if tx == nil {
  176. tx = database.GetDB()
  177. }
  178. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  179. }
  180. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  181. if tx == nil {
  182. tx = database.GetDB()
  183. }
  184. type joinedRow struct {
  185. model.ClientRecord
  186. FlowOverride string
  187. }
  188. var rows []joinedRow
  189. err := tx.Table("clients").
  190. Select("clients.*, client_inbounds.flow_override AS flow_override").
  191. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  192. Where("client_inbounds.inbound_id = ?", inboundId).
  193. Order("clients.id ASC").
  194. Find(&rows).Error
  195. if err != nil {
  196. return nil, err
  197. }
  198. out := make([]model.Client, 0, len(rows))
  199. for i := range rows {
  200. c := rows[i].ToClient()
  201. c.Flow = rows[i].FlowOverride
  202. out = append(out, *c)
  203. }
  204. return out, nil
  205. }
  206. // ListForInboundBySubId is ListForInbound narrowed to one subscription id —
  207. // both filter columns are indexed, so the subscription server resolves a
  208. // subscriber's clients without touching the inbound's settings JSON.
  209. func (s *ClientService) ListForInboundBySubId(tx *gorm.DB, inboundId int, subId string) ([]model.Client, error) {
  210. if tx == nil {
  211. tx = database.GetDB()
  212. }
  213. type joinedRow struct {
  214. model.ClientRecord
  215. FlowOverride string
  216. }
  217. var rows []joinedRow
  218. err := tx.Table("clients").
  219. Select("clients.*, client_inbounds.flow_override AS flow_override").
  220. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  221. Where("client_inbounds.inbound_id = ? AND clients.sub_id = ?", inboundId, subId).
  222. Order("clients.id ASC").
  223. Find(&rows).Error
  224. if err != nil {
  225. return nil, err
  226. }
  227. out := make([]model.Client, 0, len(rows))
  228. for i := range rows {
  229. c := rows[i].ToClient()
  230. c.Flow = rows[i].FlowOverride
  231. out = append(out, *c)
  232. }
  233. return out, nil
  234. }