client_link.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. row, ok := existing[email]
  109. if !ok {
  110. if _, dup := pending[email]; !dup {
  111. pending[email] = incoming
  112. toCreate = append(toCreate, incoming)
  113. }
  114. continue
  115. }
  116. before := *row
  117. applyClientRecordMerge(row, incoming)
  118. preservedUpdatedAt := max(incoming.UpdatedAt, row.UpdatedAt)
  119. row.UpdatedAt = preservedUpdatedAt
  120. idByEmail[email] = row.Id
  121. if *row == before {
  122. continue
  123. }
  124. if err := tx.Save(row).Error; err != nil {
  125. return err
  126. }
  127. if err := tx.Model(&model.ClientRecord{}).
  128. Where("id = ?", row.Id).
  129. UpdateColumn("updated_at", preservedUpdatedAt).Error; err != nil {
  130. return err
  131. }
  132. }
  133. if len(toCreate) > 0 {
  134. if err := tx.CreateInBatches(toCreate, 200).Error; err != nil {
  135. return err
  136. }
  137. for _, rec := range toCreate {
  138. idByEmail[rec.Email] = rec.Id
  139. }
  140. }
  141. links := make([]model.ClientInbound, 0, len(clients))
  142. linked := make(map[int]struct{}, len(clients))
  143. for i := range clients {
  144. email := strings.TrimSpace(clients[i].Email)
  145. if email == "" {
  146. continue
  147. }
  148. id, ok := idByEmail[email]
  149. if !ok {
  150. continue
  151. }
  152. if _, dup := linked[id]; dup {
  153. continue
  154. }
  155. linked[id] = struct{}{}
  156. links = append(links, model.ClientInbound{
  157. ClientId: id,
  158. InboundId: inboundId,
  159. FlowOverride: clients[i].Flow,
  160. })
  161. }
  162. if len(links) > 0 {
  163. if err := tx.CreateInBatches(links, 200).Error; err != nil {
  164. return err
  165. }
  166. }
  167. return nil
  168. }
  169. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  170. if tx == nil {
  171. tx = database.GetDB()
  172. }
  173. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  174. }
  175. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  176. if tx == nil {
  177. tx = database.GetDB()
  178. }
  179. type joinedRow struct {
  180. model.ClientRecord
  181. FlowOverride string
  182. }
  183. var rows []joinedRow
  184. err := tx.Table("clients").
  185. Select("clients.*, client_inbounds.flow_override AS flow_override").
  186. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  187. Where("client_inbounds.inbound_id = ?", inboundId).
  188. Order("clients.id ASC").
  189. Find(&rows).Error
  190. if err != nil {
  191. return nil, err
  192. }
  193. out := make([]model.Client, 0, len(rows))
  194. for i := range rows {
  195. c := rows[i].ToClient()
  196. c.Flow = rows[i].FlowOverride
  197. out = append(out, *c)
  198. }
  199. return out, nil
  200. }
  201. // ListForInboundBySubId is ListForInbound narrowed to one subscription id —
  202. // both filter columns are indexed, so the subscription server resolves a
  203. // subscriber's clients without touching the inbound's settings JSON.
  204. func (s *ClientService) ListForInboundBySubId(tx *gorm.DB, inboundId int, subId string) ([]model.Client, error) {
  205. if tx == nil {
  206. tx = database.GetDB()
  207. }
  208. type joinedRow struct {
  209. model.ClientRecord
  210. FlowOverride string
  211. }
  212. var rows []joinedRow
  213. err := tx.Table("clients").
  214. Select("clients.*, client_inbounds.flow_override AS flow_override").
  215. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  216. Where("client_inbounds.inbound_id = ? AND clients.sub_id = ?", inboundId, subId).
  217. Order("clients.id ASC").
  218. Find(&rows).Error
  219. if err != nil {
  220. return nil, err
  221. }
  222. out := make([]model.Client, 0, len(rows))
  223. for i := range rows {
  224. c := rows[i].ToClient()
  225. c.Flow = rows[i].FlowOverride
  226. out = append(out, *c)
  227. }
  228. return out, nil
  229. }