1
0

client_link.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. // Capture enable before Create: gorm default:true drops explicit false (#6478).
  158. // Restate disabled rows after CreateInBatches.
  159. wantEnable := make([]bool, len(toCreate))
  160. for i, rec := range toCreate {
  161. wantEnable[i] = rec.Enable
  162. }
  163. if err := tx.CreateInBatches(toCreate, 200).Error; err != nil {
  164. return err
  165. }
  166. disabledIDs := make([]int, 0)
  167. for i, rec := range toCreate {
  168. idByEmail[rec.Email] = rec.Id
  169. if !wantEnable[i] {
  170. disabledIDs = append(disabledIDs, rec.Id)
  171. }
  172. }
  173. for _, batch := range chunkInts(disabledIDs, sqlInChunk) {
  174. if err := tx.Model(&model.ClientRecord{}).Where("id IN ?", batch).
  175. UpdateColumn("enable", false).Error; err != nil {
  176. return err
  177. }
  178. }
  179. }
  180. wantedFlow := make(map[int]string, len(clients))
  181. wantedIds := make([]int, 0, len(clients))
  182. for i := range clients {
  183. email := strings.TrimSpace(clients[i].Email)
  184. if email == "" {
  185. continue
  186. }
  187. id, ok := idByEmail[email]
  188. if !ok {
  189. continue
  190. }
  191. if _, dup := wantedFlow[id]; dup {
  192. continue
  193. }
  194. wantedFlow[id] = clients[i].Flow
  195. wantedIds = append(wantedIds, id)
  196. }
  197. return s.reconcileInboundLinks(tx, inboundId, wantedFlow, wantedIds, detachEmails, prune)
  198. }
  199. // reconcileInboundLinks writes only the client_inbounds rows that differ. prune
  200. // also removes links absent from wantedFlow, which only a full sync may do.
  201. func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) error {
  202. var current []model.ClientInbound
  203. if prune {
  204. if err := tx.Where("inbound_id = ?", inboundId).Find(&current).Error; err != nil {
  205. return err
  206. }
  207. } else {
  208. for _, batch := range chunkInts(wantedIds, sqlInChunk) {
  209. var rows []model.ClientInbound
  210. if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).Find(&rows).Error; err != nil {
  211. return err
  212. }
  213. current = append(current, rows...)
  214. }
  215. }
  216. var toDelete []int
  217. toUpdate := make(map[string][]int)
  218. have := make(map[int]struct{}, len(current))
  219. for _, link := range current {
  220. have[link.ClientId] = struct{}{}
  221. flow, keep := wantedFlow[link.ClientId]
  222. if !keep {
  223. if prune {
  224. toDelete = append(toDelete, link.ClientId)
  225. }
  226. continue
  227. }
  228. // Plain compare, not non-empty-wins: clearing a flow must persist "".
  229. if flow != link.FlowOverride {
  230. toUpdate[flow] = append(toUpdate[flow], link.ClientId)
  231. }
  232. }
  233. if len(detachEmails) > 0 {
  234. for _, batch := range chunkStrings(detachEmails, sqlInChunk) {
  235. var ids []int
  236. if err := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).Pluck("id", &ids).Error; err != nil {
  237. return err
  238. }
  239. for _, id := range ids {
  240. if _, keep := wantedFlow[id]; !keep {
  241. toDelete = append(toDelete, id)
  242. }
  243. }
  244. }
  245. }
  246. toInsert := make([]model.ClientInbound, 0, len(wantedIds))
  247. for _, id := range wantedIds {
  248. if _, exists := have[id]; exists {
  249. continue
  250. }
  251. toInsert = append(toInsert, model.ClientInbound{
  252. ClientId: id,
  253. InboundId: inboundId,
  254. FlowOverride: wantedFlow[id],
  255. })
  256. }
  257. for _, batch := range chunkInts(toDelete, sqlInChunk) {
  258. if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).
  259. Delete(&model.ClientInbound{}).Error; err != nil {
  260. return err
  261. }
  262. }
  263. for flow, ids := range toUpdate {
  264. for _, batch := range chunkInts(ids, sqlInChunk) {
  265. if err := tx.Model(&model.ClientInbound{}).
  266. Where("inbound_id = ? AND client_id IN ?", inboundId, batch).
  267. Update("flow_override", flow).Error; err != nil {
  268. return err
  269. }
  270. }
  271. }
  272. if len(toInsert) > 0 {
  273. // The delete this replaced also serialized concurrent syncs of one
  274. // inbound; without the clause a racing node poll aborts its whole tx.
  275. if err := tx.Clauses(clause.OnConflict{
  276. Columns: []clause.Column{{Name: "client_id"}, {Name: "inbound_id"}},
  277. DoUpdates: clause.AssignmentColumns([]string{"flow_override"}),
  278. }).CreateInBatches(toInsert, 200).Error; err != nil {
  279. return err
  280. }
  281. }
  282. return nil
  283. }
  284. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  285. if tx == nil {
  286. tx = database.GetDB()
  287. }
  288. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  289. }
  290. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  291. if tx == nil {
  292. tx = database.GetDB()
  293. }
  294. type joinedRow struct {
  295. model.ClientRecord
  296. FlowOverride string
  297. }
  298. var rows []joinedRow
  299. err := tx.Table("clients").
  300. Select("clients.*, client_inbounds.flow_override AS flow_override").
  301. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  302. Where("client_inbounds.inbound_id = ?", inboundId).
  303. Order("clients.id ASC").
  304. Find(&rows).Error
  305. if err != nil {
  306. return nil, err
  307. }
  308. out := make([]model.Client, 0, len(rows))
  309. for i := range rows {
  310. c := rows[i].ToClient()
  311. c.Flow = rows[i].FlowOverride
  312. out = append(out, *c)
  313. }
  314. return out, nil
  315. }
  316. // ListForInboundBySubId is ListForInbound narrowed to one subscription id —
  317. // both filter columns are indexed, so the subscription server resolves a
  318. // subscriber's clients without touching the inbound's settings JSON.
  319. func (s *ClientService) ListForInboundBySubId(tx *gorm.DB, inboundId int, subId string) ([]model.Client, error) {
  320. if tx == nil {
  321. tx = database.GetDB()
  322. }
  323. type joinedRow struct {
  324. model.ClientRecord
  325. FlowOverride string
  326. }
  327. var rows []joinedRow
  328. err := tx.Table("clients").
  329. Select("clients.*, client_inbounds.flow_override AS flow_override").
  330. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  331. Where("client_inbounds.inbound_id = ? AND clients.sub_id = ?", inboundId, subId).
  332. Order("clients.id ASC").
  333. Find(&rows).Error
  334. if err != nil {
  335. return nil, err
  336. }
  337. out := make([]model.Client, 0, len(rows))
  338. for i := range rows {
  339. c := rows[i].ToClient()
  340. c.Flow = rows[i].FlowOverride
  341. out = append(out, *c)
  342. }
  343. return out, nil
  344. }