client_link.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. "gorm.io/gorm/clause"
  8. )
  9. // applyClientRecordMerge merges incoming client-record fields onto row using the
  10. // same rules everywhere a client record is persisted: scalar quota / lifecycle /
  11. // subscription fields are applied unconditionally (so clearing them takes
  12. // effect), while credentials and identifiers are only overwritten when the
  13. // incoming value is non-empty (so a partial update preserves the stored UUID /
  14. // password / keys). CreatedAt keeps the earliest known value. Email, UpdatedAt,
  15. // and the Id primary key are intentionally not touched here — callers handle
  16. // those separately. Shared by SyncInbound (per-inbound persistence) and Update
  17. // (the no-attached-inbound fallback) so the two paths cannot diverge.
  18. func applyClientRecordMerge(row *model.ClientRecord, incoming *model.ClientRecord) {
  19. if incoming.UUID != "" {
  20. row.UUID = incoming.UUID
  21. }
  22. if incoming.Password != "" {
  23. row.Password = incoming.Password
  24. }
  25. if incoming.Auth != "" {
  26. row.Auth = incoming.Auth
  27. }
  28. if incoming.Secret != "" {
  29. row.Secret = incoming.Secret
  30. }
  31. if incoming.AdTag != "" {
  32. row.AdTag = incoming.AdTag
  33. }
  34. row.Flow = incoming.Flow
  35. if incoming.Security != "" {
  36. row.Security = incoming.Security
  37. }
  38. if incoming.Reverse != "" {
  39. row.Reverse = incoming.Reverse
  40. }
  41. if incoming.PrivateKey != "" {
  42. row.PrivateKey = incoming.PrivateKey
  43. }
  44. if incoming.PublicKey != "" {
  45. row.PublicKey = incoming.PublicKey
  46. }
  47. if incoming.AllowedIPs != "" {
  48. row.AllowedIPs = incoming.AllowedIPs
  49. }
  50. row.PreSharedKey = incoming.PreSharedKey
  51. row.KeepAlive = incoming.KeepAlive
  52. row.SubID = incoming.SubID
  53. row.LimitIP = incoming.LimitIP
  54. row.TotalGB = incoming.TotalGB
  55. row.ExpiryTime = incoming.ExpiryTime
  56. row.Enable = incoming.Enable
  57. row.TgID = incoming.TgID
  58. if incoming.Group != "" {
  59. row.Group = incoming.Group
  60. }
  61. row.Comment = incoming.Comment
  62. row.Reset = incoming.Reset
  63. row.ResetDay = incoming.ResetDay
  64. row.ResetMax = incoming.ResetMax
  65. // Guarded like Group and AdTag: a node snapshot rebuilt from settings that
  66. // predate the cycle would otherwise silently erase it.
  67. if incoming.TrafficReset != "" {
  68. row.TrafficReset = incoming.TrafficReset
  69. }
  70. if incoming.TrafficResetDay > 0 {
  71. row.TrafficResetDay = incoming.TrafficResetDay
  72. }
  73. if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
  74. row.CreatedAt = incoming.CreatedAt
  75. }
  76. }
  77. // SyncInbound makes the inbound's client records and links match clients
  78. // exactly: links for clients no longer in the set are removed.
  79. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error {
  80. return s.syncInboundClients(tx, inboundId, clients, nil, true)
  81. }
  82. // ApplyInboundClientDelta persists only the clients an edit actually changed
  83. // plus the emails it detached, leaving every other link on the inbound alone —
  84. // the whole point being that a one-client edit must not rewrite the inbound's
  85. // entire membership set (#6252).
  86. func (s *ClientService) ApplyInboundClientDelta(tx *gorm.DB, inboundId int, changed []model.Client, detachEmails []string) error {
  87. return s.syncInboundClients(tx, inboundId, changed, detachEmails, false)
  88. }
  89. func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool) error {
  90. if tx == nil {
  91. tx = database.GetDB()
  92. }
  93. emails := make([]string, 0, len(clients))
  94. seen := make(map[string]struct{}, len(clients))
  95. for i := range clients {
  96. email := strings.TrimSpace(clients[i].Email)
  97. if email == "" {
  98. continue
  99. }
  100. if _, ok := seen[email]; ok {
  101. continue
  102. }
  103. seen[email] = struct{}{}
  104. emails = append(emails, email)
  105. }
  106. existing := make(map[string]*model.ClientRecord, len(emails))
  107. const selectChunk = 400
  108. for start := 0; start < len(emails); start += selectChunk {
  109. end := min(start+selectChunk, len(emails))
  110. var rows []model.ClientRecord
  111. if err := tx.Where("email IN ?", emails[start:end]).Find(&rows).Error; err != nil {
  112. return err
  113. }
  114. for i := range rows {
  115. r := rows[i]
  116. existing[r.Email] = &r
  117. }
  118. }
  119. idByEmail := make(map[string]int, len(emails))
  120. pending := make(map[string]*model.ClientRecord, len(emails))
  121. toCreate := make([]*model.ClientRecord, 0, len(emails))
  122. for i := range clients {
  123. email := strings.TrimSpace(clients[i].Email)
  124. if email == "" {
  125. continue
  126. }
  127. incoming := clients[i].ToRecord()
  128. // ToRecord copies the raw email; store the trimmed key this function
  129. // looks up by, or a padded email is inserted and never found again.
  130. incoming.Email = email
  131. row, ok := existing[email]
  132. if !ok {
  133. if _, dup := pending[email]; !dup {
  134. pending[email] = incoming
  135. toCreate = append(toCreate, incoming)
  136. }
  137. continue
  138. }
  139. before := *row
  140. applyClientRecordMerge(row, incoming)
  141. preservedUpdatedAt := max(incoming.UpdatedAt, row.UpdatedAt)
  142. row.UpdatedAt = preservedUpdatedAt
  143. idByEmail[email] = row.Id
  144. if *row == before {
  145. continue
  146. }
  147. if err := tx.Save(row).Error; err != nil {
  148. return err
  149. }
  150. if err := tx.Model(&model.ClientRecord{}).
  151. Where("id = ?", row.Id).
  152. UpdateColumn("updated_at", preservedUpdatedAt).Error; err != nil {
  153. return err
  154. }
  155. }
  156. if len(toCreate) > 0 {
  157. if err := tx.CreateInBatches(toCreate, 200).Error; err != nil {
  158. return err
  159. }
  160. for _, rec := range toCreate {
  161. idByEmail[rec.Email] = rec.Id
  162. }
  163. }
  164. wantedFlow := make(map[int]string, len(clients))
  165. wantedIds := make([]int, 0, len(clients))
  166. for i := range clients {
  167. email := strings.TrimSpace(clients[i].Email)
  168. if email == "" {
  169. continue
  170. }
  171. id, ok := idByEmail[email]
  172. if !ok {
  173. continue
  174. }
  175. if _, dup := wantedFlow[id]; dup {
  176. continue
  177. }
  178. wantedFlow[id] = clients[i].Flow
  179. wantedIds = append(wantedIds, id)
  180. }
  181. return s.reconcileInboundLinks(tx, inboundId, wantedFlow, wantedIds, detachEmails, prune)
  182. }
  183. // reconcileInboundLinks writes only the client_inbounds rows that differ. prune
  184. // also removes links absent from wantedFlow, which only a full sync may do.
  185. func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) error {
  186. var current []model.ClientInbound
  187. if prune {
  188. if err := tx.Where("inbound_id = ?", inboundId).Find(&current).Error; err != nil {
  189. return err
  190. }
  191. } else {
  192. for _, batch := range chunkInts(wantedIds, sqlInChunk) {
  193. var rows []model.ClientInbound
  194. if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).Find(&rows).Error; err != nil {
  195. return err
  196. }
  197. current = append(current, rows...)
  198. }
  199. }
  200. var toDelete []int
  201. toUpdate := make(map[string][]int)
  202. have := make(map[int]struct{}, len(current))
  203. for _, link := range current {
  204. have[link.ClientId] = struct{}{}
  205. flow, keep := wantedFlow[link.ClientId]
  206. if !keep {
  207. if prune {
  208. toDelete = append(toDelete, link.ClientId)
  209. }
  210. continue
  211. }
  212. // Plain compare, not non-empty-wins: clearing a flow must persist "".
  213. if flow != link.FlowOverride {
  214. toUpdate[flow] = append(toUpdate[flow], link.ClientId)
  215. }
  216. }
  217. if len(detachEmails) > 0 {
  218. for _, batch := range chunkStrings(detachEmails, sqlInChunk) {
  219. var ids []int
  220. if err := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).Pluck("id", &ids).Error; err != nil {
  221. return err
  222. }
  223. for _, id := range ids {
  224. if _, keep := wantedFlow[id]; !keep {
  225. toDelete = append(toDelete, id)
  226. }
  227. }
  228. }
  229. }
  230. toInsert := make([]model.ClientInbound, 0, len(wantedIds))
  231. for _, id := range wantedIds {
  232. if _, exists := have[id]; exists {
  233. continue
  234. }
  235. toInsert = append(toInsert, model.ClientInbound{
  236. ClientId: id,
  237. InboundId: inboundId,
  238. FlowOverride: wantedFlow[id],
  239. })
  240. }
  241. for _, batch := range chunkInts(toDelete, sqlInChunk) {
  242. if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).
  243. Delete(&model.ClientInbound{}).Error; err != nil {
  244. return err
  245. }
  246. }
  247. for flow, ids := range toUpdate {
  248. for _, batch := range chunkInts(ids, sqlInChunk) {
  249. if err := tx.Model(&model.ClientInbound{}).
  250. Where("inbound_id = ? AND client_id IN ?", inboundId, batch).
  251. Update("flow_override", flow).Error; err != nil {
  252. return err
  253. }
  254. }
  255. }
  256. if len(toInsert) > 0 {
  257. // The delete this replaced also serialized concurrent syncs of one
  258. // inbound; without the clause a racing node poll aborts its whole tx.
  259. if err := tx.Clauses(clause.OnConflict{
  260. Columns: []clause.Column{{Name: "client_id"}, {Name: "inbound_id"}},
  261. DoUpdates: clause.AssignmentColumns([]string{"flow_override"}),
  262. }).CreateInBatches(toInsert, 200).Error; err != nil {
  263. return err
  264. }
  265. }
  266. return nil
  267. }
  268. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  269. if tx == nil {
  270. tx = database.GetDB()
  271. }
  272. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  273. }
  274. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  275. if tx == nil {
  276. tx = database.GetDB()
  277. }
  278. type joinedRow struct {
  279. model.ClientRecord
  280. FlowOverride string
  281. }
  282. var rows []joinedRow
  283. err := tx.Table("clients").
  284. Select("clients.*, client_inbounds.flow_override AS flow_override").
  285. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  286. Where("client_inbounds.inbound_id = ?", inboundId).
  287. Order("clients.id ASC").
  288. Find(&rows).Error
  289. if err != nil {
  290. return nil, err
  291. }
  292. out := make([]model.Client, 0, len(rows))
  293. for i := range rows {
  294. c := rows[i].ToClient()
  295. c.Flow = rows[i].FlowOverride
  296. out = append(out, *c)
  297. }
  298. return out, nil
  299. }
  300. // ListForInboundBySubId is ListForInbound narrowed to one subscription id —
  301. // both filter columns are indexed, so the subscription server resolves a
  302. // subscriber's clients without touching the inbound's settings JSON.
  303. func (s *ClientService) ListForInboundBySubId(tx *gorm.DB, inboundId int, subId string) ([]model.Client, error) {
  304. if tx == nil {
  305. tx = database.GetDB()
  306. }
  307. type joinedRow struct {
  308. model.ClientRecord
  309. FlowOverride string
  310. }
  311. var rows []joinedRow
  312. err := tx.Table("clients").
  313. Select("clients.*, client_inbounds.flow_override AS flow_override").
  314. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  315. Where("client_inbounds.inbound_id = ? AND clients.sub_id = ?", inboundId, subId).
  316. Order("clients.id ASC").
  317. Find(&rows).Error
  318. if err != nil {
  319. return nil, err
  320. }
  321. out := make([]model.Client, 0, len(rows))
  322. for i := range rows {
  323. c := rows[i].ToClient()
  324. c.Flow = rows[i].FlowOverride
  325. out = append(out, *c)
  326. }
  327. return out, nil
  328. }