1
0

client_link.go 6.8 KB

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