client_link.go 7.1 KB

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