client_link.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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.ResetWeekday = incoming.ResetWeekday
  65. row.ResetMax = incoming.ResetMax
  66. // Guarded like Group and AdTag: a node snapshot rebuilt from settings that
  67. // predate the cycle would otherwise silently erase it.
  68. if incoming.TrafficReset != "" {
  69. row.TrafficReset = incoming.TrafficReset
  70. }
  71. if incoming.TrafficResetDay > 0 {
  72. row.TrafficResetDay = incoming.TrafficResetDay
  73. }
  74. if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
  75. row.CreatedAt = incoming.CreatedAt
  76. }
  77. }
  78. // SyncInbound makes the inbound's client records and links match clients
  79. // exactly: links for clients no longer in the set are removed.
  80. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error {
  81. return s.syncInboundClients(tx, inboundId, clients, nil, true)
  82. }
  83. // ApplyInboundClientDelta persists only the clients an edit actually changed
  84. // plus the emails it detached, leaving every other link on the inbound alone —
  85. // the whole point being that a one-client edit must not rewrite the inbound's
  86. // entire membership set (#6252).
  87. func (s *ClientService) ApplyInboundClientDelta(tx *gorm.DB, inboundId int, changed []model.Client, detachEmails []string) error {
  88. return s.syncInboundClients(tx, inboundId, changed, detachEmails, false)
  89. }
  90. func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool) error {
  91. if err := validateClientsRenewal(clients); err != nil {
  92. return err
  93. }
  94. if tx == nil {
  95. tx = database.GetDB()
  96. }
  97. emails := make([]string, 0, len(clients))
  98. seen := make(map[string]struct{}, len(clients))
  99. for i := range clients {
  100. email := strings.TrimSpace(clients[i].Email)
  101. if email == "" {
  102. continue
  103. }
  104. if _, ok := seen[email]; ok {
  105. continue
  106. }
  107. seen[email] = struct{}{}
  108. emails = append(emails, email)
  109. }
  110. existing := make(map[string]*model.ClientRecord, len(emails))
  111. const selectChunk = 400
  112. for start := 0; start < len(emails); start += selectChunk {
  113. end := min(start+selectChunk, len(emails))
  114. var rows []model.ClientRecord
  115. if err := tx.Where("email IN ?", emails[start:end]).Find(&rows).Error; err != nil {
  116. return err
  117. }
  118. for i := range rows {
  119. r := rows[i]
  120. existing[r.Email] = &r
  121. }
  122. }
  123. idByEmail := make(map[string]int, len(emails))
  124. pending := make(map[string]*model.ClientRecord, len(emails))
  125. toCreate := make([]*model.ClientRecord, 0, len(emails))
  126. for i := range clients {
  127. email := strings.TrimSpace(clients[i].Email)
  128. if email == "" {
  129. continue
  130. }
  131. incoming := clients[i].ToRecord()
  132. // ToRecord copies the raw email; store the trimmed key this function
  133. // looks up by, or a padded email is inserted and never found again.
  134. incoming.Email = email
  135. row, ok := existing[email]
  136. if !ok {
  137. if _, dup := pending[email]; !dup {
  138. pending[email] = incoming
  139. toCreate = append(toCreate, incoming)
  140. }
  141. continue
  142. }
  143. before := *row
  144. applyClientRecordMerge(row, incoming)
  145. preservedUpdatedAt := max(incoming.UpdatedAt, row.UpdatedAt)
  146. row.UpdatedAt = preservedUpdatedAt
  147. idByEmail[email] = row.Id
  148. if *row == before {
  149. continue
  150. }
  151. if err := tx.Save(row).Error; err != nil {
  152. return err
  153. }
  154. if err := tx.Model(&model.ClientRecord{}).
  155. Where("id = ?", row.Id).
  156. UpdateColumn("updated_at", preservedUpdatedAt).Error; err != nil {
  157. return err
  158. }
  159. }
  160. if len(toCreate) > 0 {
  161. // Capture enable before Create: gorm default:true drops explicit false (#6478).
  162. // Restate disabled rows after CreateInBatches.
  163. wantEnable := make([]bool, len(toCreate))
  164. for i, rec := range toCreate {
  165. wantEnable[i] = rec.Enable
  166. }
  167. if err := tx.CreateInBatches(toCreate, 200).Error; err != nil {
  168. return err
  169. }
  170. disabledIDs := make([]int, 0)
  171. for i, rec := range toCreate {
  172. idByEmail[rec.Email] = rec.Id
  173. if !wantEnable[i] {
  174. disabledIDs = append(disabledIDs, rec.Id)
  175. }
  176. }
  177. for _, batch := range chunkInts(disabledIDs, sqlInChunk) {
  178. if err := tx.Model(&model.ClientRecord{}).Where("id IN ?", batch).
  179. UpdateColumn("enable", false).Error; err != nil {
  180. return err
  181. }
  182. }
  183. }
  184. wantedFlow := make(map[int]string, len(clients))
  185. wantedIds := make([]int, 0, len(clients))
  186. for i := range clients {
  187. email := strings.TrimSpace(clients[i].Email)
  188. if email == "" {
  189. continue
  190. }
  191. id, ok := idByEmail[email]
  192. if !ok {
  193. continue
  194. }
  195. if _, dup := wantedFlow[id]; dup {
  196. continue
  197. }
  198. wantedFlow[id] = clients[i].Flow
  199. wantedIds = append(wantedIds, id)
  200. }
  201. return s.reconcileInboundLinks(tx, inboundId, wantedFlow, wantedIds, detachEmails, prune)
  202. }
  203. // reconcileInboundLinks writes only the client_inbounds rows that differ. prune
  204. // also removes links absent from wantedFlow, which only a full sync may do.
  205. func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) error {
  206. var current []model.ClientInbound
  207. if prune {
  208. if err := tx.Where("inbound_id = ?", inboundId).Find(&current).Error; err != nil {
  209. return err
  210. }
  211. } else {
  212. for _, batch := range chunkInts(wantedIds, sqlInChunk) {
  213. var rows []model.ClientInbound
  214. if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).Find(&rows).Error; err != nil {
  215. return err
  216. }
  217. current = append(current, rows...)
  218. }
  219. }
  220. var toDelete []int
  221. toUpdate := make(map[string][]int)
  222. have := make(map[int]struct{}, len(current))
  223. for _, link := range current {
  224. have[link.ClientId] = struct{}{}
  225. flow, keep := wantedFlow[link.ClientId]
  226. if !keep {
  227. if prune {
  228. toDelete = append(toDelete, link.ClientId)
  229. }
  230. continue
  231. }
  232. // Plain compare, not non-empty-wins: clearing a flow must persist "".
  233. if flow != link.FlowOverride {
  234. toUpdate[flow] = append(toUpdate[flow], link.ClientId)
  235. }
  236. }
  237. if len(detachEmails) > 0 {
  238. for _, batch := range chunkStrings(detachEmails, sqlInChunk) {
  239. var ids []int
  240. if err := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).Pluck("id", &ids).Error; err != nil {
  241. return err
  242. }
  243. for _, id := range ids {
  244. if _, keep := wantedFlow[id]; !keep {
  245. toDelete = append(toDelete, id)
  246. }
  247. }
  248. }
  249. }
  250. toInsert := make([]model.ClientInbound, 0, len(wantedIds))
  251. for _, id := range wantedIds {
  252. if _, exists := have[id]; exists {
  253. continue
  254. }
  255. toInsert = append(toInsert, model.ClientInbound{
  256. ClientId: id,
  257. InboundId: inboundId,
  258. FlowOverride: wantedFlow[id],
  259. })
  260. }
  261. for _, batch := range chunkInts(toDelete, sqlInChunk) {
  262. if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).
  263. Delete(&model.ClientInbound{}).Error; err != nil {
  264. return err
  265. }
  266. }
  267. for flow, ids := range toUpdate {
  268. for _, batch := range chunkInts(ids, sqlInChunk) {
  269. if err := tx.Model(&model.ClientInbound{}).
  270. Where("inbound_id = ? AND client_id IN ?", inboundId, batch).
  271. Update("flow_override", flow).Error; err != nil {
  272. return err
  273. }
  274. }
  275. }
  276. if len(toInsert) > 0 {
  277. // The delete this replaced also serialized concurrent syncs of one
  278. // inbound; without the clause a racing node poll aborts its whole tx.
  279. if err := tx.Clauses(clause.OnConflict{
  280. Columns: []clause.Column{{Name: "client_id"}, {Name: "inbound_id"}},
  281. DoUpdates: clause.AssignmentColumns([]string{"flow_override"}),
  282. }).CreateInBatches(toInsert, 200).Error; err != nil {
  283. return err
  284. }
  285. }
  286. return nil
  287. }
  288. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  289. if tx == nil {
  290. tx = database.GetDB()
  291. }
  292. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  293. }
  294. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  295. if tx == nil {
  296. tx = database.GetDB()
  297. }
  298. type joinedRow struct {
  299. model.ClientRecord
  300. FlowOverride string
  301. }
  302. var rows []joinedRow
  303. err := tx.Table("clients").
  304. Select("clients.*, client_inbounds.flow_override AS flow_override").
  305. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  306. Where("client_inbounds.inbound_id = ?", inboundId).
  307. Order("clients.id ASC").
  308. Find(&rows).Error
  309. if err != nil {
  310. return nil, err
  311. }
  312. out := make([]model.Client, 0, len(rows))
  313. for i := range rows {
  314. c := rows[i].ToClient()
  315. c.Flow = rows[i].FlowOverride
  316. out = append(out, *c)
  317. }
  318. return out, nil
  319. }
  320. // ListForInboundBySubId is ListForInbound narrowed to one subscription id —
  321. // both filter columns are indexed, so the subscription server resolves a
  322. // subscriber's clients without touching the inbound's settings JSON.
  323. func (s *ClientService) ListForInboundBySubId(tx *gorm.DB, inboundId int, subId string) ([]model.Client, error) {
  324. if tx == nil {
  325. tx = database.GetDB()
  326. }
  327. type joinedRow struct {
  328. model.ClientRecord
  329. FlowOverride string
  330. }
  331. var rows []joinedRow
  332. err := tx.Table("clients").
  333. Select("clients.*, client_inbounds.flow_override AS flow_override").
  334. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  335. Where("client_inbounds.inbound_id = ? AND clients.sub_id = ?", inboundId, subId).
  336. Order("clients.id ASC").
  337. Find(&rows).Error
  338. if err != nil {
  339. return nil, err
  340. }
  341. out := make([]model.Client, 0, len(rows))
  342. for i := range rows {
  343. c := rows[i].ToClient()
  344. c.Flow = rows[i].FlowOverride
  345. out = append(out, *c)
  346. }
  347. return out, nil
  348. }