inbound_traffic.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "maps"
  8. "slices"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  16. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  17. "gorm.io/gorm"
  18. "gorm.io/gorm/clause"
  19. )
  20. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
  21. var disabledNodeIDs []int
  22. err = submitTrafficWrite(func() error {
  23. var inner error
  24. needRestart, clientsDisabled, disabledNodeIDs, inner = s.addTrafficLocked(inboundTraffics, clientTraffics)
  25. return inner
  26. })
  27. if err == nil && len(disabledNodeIDs) > 0 {
  28. s.restartRemoteNodesOnDisable(disabledNodeIDs)
  29. }
  30. return
  31. }
  32. func (s *InboundService) addTrafficLocked(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, []int, error) {
  33. db := database.GetDB()
  34. // Commit durable traffic before best-effort lifecycle maintenance so helper
  35. // failures cannot discard usage already reported by Xray.
  36. if err := db.Transaction(func(tx *gorm.DB) error {
  37. if err := s.addInboundTraffic(tx, inboundTraffics); err != nil {
  38. return err
  39. }
  40. return s.addClientTraffic(tx, clientTraffics)
  41. }); err != nil {
  42. return false, false, nil, err
  43. }
  44. var (
  45. needRestart bool
  46. clientsDisabled bool
  47. disabledNodeIDs []int
  48. disabledClientsCount int64
  49. )
  50. batch := newTrafficMutationBatch()
  51. err := db.Transaction(func(tx *gorm.DB) error {
  52. needRestart0, count, err := s.autoRenewClients(tx, batch)
  53. if err != nil {
  54. return fmt.Errorf("renew clients: %w", err)
  55. }
  56. if count > 0 {
  57. logger.Debugf("%v clients renewed", count)
  58. }
  59. needRestart1, count, nodeIDs, err := s.disableInvalidClients(tx, batch)
  60. if err != nil {
  61. return fmt.Errorf("disable invalid clients: %w", err)
  62. }
  63. if count > 0 {
  64. logger.Debugf("%v clients disabled", count)
  65. disabledClientsCount = count
  66. }
  67. needRestart2, count, err := s.disableInvalidInbounds(tx, batch)
  68. if err != nil {
  69. return fmt.Errorf("disable invalid inbounds: %w", err)
  70. }
  71. if count > 0 {
  72. logger.Debugf("%v inbounds disabled", count)
  73. }
  74. if err := batch.markNodesTx(tx); err != nil {
  75. return err
  76. }
  77. needRestart = needRestart0 || needRestart1 || needRestart2
  78. clientsDisabled = disabledClientsCount > 0
  79. disabledNodeIDs = nodeIDs
  80. return nil
  81. })
  82. if err != nil {
  83. logger.Warning("traffic lifecycle maintenance failed after traffic commit:", err)
  84. return false, false, nil, nil
  85. }
  86. needRestart = needRestart || s.applyTrafficMutationBatch(batch)
  87. return needRestart, clientsDisabled, disabledNodeIDs, nil
  88. }
  89. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  90. if len(traffics) == 0 {
  91. return nil
  92. }
  93. var err error
  94. for _, traffic := range traffics {
  95. if traffic.IsInbound {
  96. err = tx.Model(&model.Inbound{}).Where("tag = ? AND node_id IS NULL", traffic.Tag).
  97. Updates(map[string]any{
  98. "up": gorm.Expr(database.ClampedAddExpr("up"), traffic.Up),
  99. "down": gorm.Expr(database.ClampedAddExpr("down"), traffic.Down),
  100. }).Error
  101. if err != nil {
  102. return err
  103. }
  104. }
  105. }
  106. return nil
  107. }
  108. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  109. if len(traffics) == 0 {
  110. return nil
  111. }
  112. emails := make([]string, 0, len(traffics))
  113. for _, traffic := range traffics {
  114. emails = append(emails, traffic.Email)
  115. }
  116. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  117. // Match purely by email. client_traffics is email-keyed (one shared row per
  118. // email regardless of how many inbounds the client is attached to), and these
  119. // emails come from the local xray's report, so they always belong to a client
  120. // attached to a local inbound. The old `inbound_id NOT IN (node inbounds)`
  121. // filter dropped the local traffic of a client attached to both a node and the
  122. // mother inbound whenever the node inbound happened to be attached first — its
  123. // shared row then carried the node inbound's id (AddClientStat used to use
  124. // OnConflict DoNothing and never refreshed it; it now refreshes inbound_id on
  125. // conflict, but this filter was removed rather than relying on that ordering).
  126. err = tx.Model(xray.ClientTraffic{}).
  127. Where("email IN (?)", emails).
  128. Find(&dbClientTraffics).Error
  129. if err != nil {
  130. return err
  131. }
  132. // Avoid empty slice error
  133. if len(dbClientTraffics) == 0 {
  134. return nil
  135. }
  136. dbClientTraffics, convertedExpiryByEmail, err := s.adjustTraffics(tx, dbClientTraffics)
  137. if err != nil {
  138. return err
  139. }
  140. // Index by email for O(N) merge.
  141. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  142. for i := range traffics {
  143. if traffics[i] != nil {
  144. trafficByEmail[traffics[i].Email] = traffics[i]
  145. }
  146. }
  147. now := time.Now().UnixMilli()
  148. // Use atomic per-row UPDATE instead of read-modify-write Save. tx.Save
  149. // issues UPDATEs in slice order, which varies between concurrent callers;
  150. // on PostgreSQL two transactions locking the same rows in opposite order
  151. // deadlock. An atomic "SET up = up + ?" never holds a row lock across a
  152. // subsequent lock acquisition, so concurrent writers cannot deadlock.
  153. for _, ct := range dbClientTraffics {
  154. t, ok := trafficByEmail[ct.Email]
  155. if !ok || (t.Up == 0 && t.Down == 0) {
  156. continue
  157. }
  158. if err = tx.Exec(
  159. fmt.Sprintf(
  160. `UPDATE client_traffics SET up = %s, down = %s, last_online = %s WHERE email = ?`,
  161. database.ClampedAddExpr("up"),
  162. database.ClampedAddExpr("down"),
  163. database.GreatestExpr("last_online", "?"),
  164. ),
  165. t.Up, t.Down, now, ct.Email,
  166. ).Error; err != nil {
  167. logger.Warning("AddClientTraffic update data ", err)
  168. }
  169. }
  170. // adjustTraffics converts delayed-start rows (negative ExpiryTime → absolute
  171. // deadline) in-memory. Persist that conversion now since the traffic UPDATE
  172. // above only touches up/down/last_online. Only converted emails are written:
  173. // updating every polled row issued one no-op UPDATE per active client per
  174. // poll. Sorted order keeps concurrent writers lock-compatible on Postgres.
  175. for _, email := range slices.Sorted(maps.Keys(convertedExpiryByEmail)) {
  176. if err = tx.Exec(
  177. `UPDATE client_traffics SET expiry_time = ? WHERE email = ? AND expiry_time < 0`,
  178. convertedExpiryByEmail[email], email,
  179. ).Error; err != nil {
  180. logger.Warning("AddClientTraffic update expiry_time ", err)
  181. }
  182. }
  183. return nil
  184. }
  185. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, map[string]int64, error) {
  186. now := time.Now().UnixMilli()
  187. // "Start After First Use" stores a negative expiry (the duration). On the
  188. // first traffic tick it becomes an absolute deadline of now+duration. Compute
  189. // it once per email so every inbound the client is attached to lands on the
  190. // same value (recomputing per inbound would skip all but the first one).
  191. newExpiryByEmail := make(map[string]int64, len(dbClientTraffics))
  192. for traffic_index := range dbClientTraffics {
  193. if dbClientTraffics[traffic_index].ExpiryTime < 0 {
  194. newExpiryByEmail[dbClientTraffics[traffic_index].Email] = now - dbClientTraffics[traffic_index].ExpiryTime
  195. }
  196. }
  197. if len(newExpiryByEmail) == 0 {
  198. return dbClientTraffics, nil, nil
  199. }
  200. delayedEmails := make([]string, 0, len(newExpiryByEmail))
  201. for email := range newExpiryByEmail {
  202. delayedEmails = append(delayedEmails, email)
  203. }
  204. // Resolve the owning inbounds through the client_inbounds link, which is
  205. // authoritative. client_traffics.inbound_id goes stale when an inbound is
  206. // deleted and recreated, which would leave the negative expiry unconverted.
  207. var inboundIds []int
  208. err := tx.Table("client_inbounds").
  209. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  210. Where("clients.email IN (?)", delayedEmails).
  211. Distinct().
  212. Pluck("client_inbounds.inbound_id", &inboundIds).Error
  213. if err != nil {
  214. return nil, nil, err
  215. }
  216. if len(inboundIds) == 0 {
  217. return dbClientTraffics, nil, nil
  218. }
  219. var inbounds []*model.Inbound
  220. err = tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  221. if err != nil {
  222. return nil, nil, err
  223. }
  224. for inbound_index := range inbounds {
  225. settings := map[string]any{}
  226. _ = json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  227. clients, ok := settings["clients"].([]any)
  228. if ok {
  229. var newClients []any
  230. for client_index := range clients {
  231. c := clients[client_index].(map[string]any)
  232. email, _ := c["email"].(string)
  233. if newExpiry, ok := newExpiryByEmail[email]; ok {
  234. c["expiryTime"] = newExpiry
  235. c["updated_at"] = now
  236. }
  237. if _, ok := c["created_at"]; !ok {
  238. c["created_at"] = now
  239. }
  240. if _, ok := c["updated_at"]; !ok {
  241. c["updated_at"] = now
  242. }
  243. newClients = append(newClients, any(c))
  244. }
  245. settings["clients"] = newClients
  246. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  247. if err != nil {
  248. return nil, nil, err
  249. }
  250. inbounds[inbound_index].Settings = string(modifiedSettings)
  251. }
  252. }
  253. for traffic_index := range dbClientTraffics {
  254. if newExpiry, ok := newExpiryByEmail[dbClientTraffics[traffic_index].Email]; ok {
  255. dbClientTraffics[traffic_index].ExpiryTime = newExpiry
  256. }
  257. }
  258. err = tx.Save(inbounds).Error
  259. if err != nil {
  260. logger.Warning("AddClientTraffic update inbounds ", err)
  261. logger.Error(inbounds)
  262. } else {
  263. for _, ib := range inbounds {
  264. if ib == nil {
  265. continue
  266. }
  267. cs, gcErr := s.GetClients(ib)
  268. if gcErr != nil {
  269. logger.Warning("AddClientTraffic sync clients: GetClients failed", gcErr)
  270. continue
  271. }
  272. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  273. logger.Warning("AddClientTraffic sync clients: SyncInbound failed", syncErr)
  274. }
  275. }
  276. }
  277. return dbClientTraffics, newExpiryByEmail, nil
  278. }
  279. // apiUserFromClient prepares a stored client object for the runtime AddUser
  280. // call. The copy matters twice over: the stored object keeps being mutated and
  281. // marshalled back into the inbound's settings, which must not gain an API-only
  282. // key, and shadowsocks clients carry no cipher of their own — it lives on the
  283. // inbound, and without it the API cannot tell which of xray's two shadowsocks
  284. // account types the running inbound expects.
  285. func apiUserFromClient(client map[string]any, cipher string) map[string]any {
  286. user := maps.Clone(client)
  287. if user == nil {
  288. user = map[string]any{}
  289. }
  290. if cipher != "" {
  291. user["cipher"] = cipher
  292. }
  293. return user
  294. }
  295. func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMutationBatch) (bool, int64, error) {
  296. // check for time expired
  297. var traffics []*xray.ClientTraffic
  298. now := time.Now().Unix() * 1000
  299. var err error
  300. // Filter to clients that have at least one local inbound. Using
  301. // client_traffics.inbound_id is wrong: it goes stale after an inbound is
  302. // deleted/recreated and always points to the first inbound the client was
  303. // attached to, so it could be a node inbound even when the client also has
  304. // local inbounds. The email-based join through client_inbounds is authoritative.
  305. err = tx.Model(xray.ClientTraffic{}).
  306. Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).
  307. Where("email IN (?)", tx.Table("client_inbounds ci").
  308. Select("c.email").
  309. Joins("JOIN clients c ON c.id = ci.client_id").
  310. Joins("JOIN inbounds i ON i.id = ci.inbound_id").
  311. Where("i.node_id IS NULL")).
  312. Find(&traffics).Error
  313. if err != nil {
  314. return false, 0, err
  315. }
  316. // return if there is no client to renew
  317. if len(traffics) == 0 {
  318. return false, 0, nil
  319. }
  320. var inbound_ids []int
  321. var inbounds []*model.Inbound
  322. needRestart := false
  323. var clientsToAdd []struct {
  324. inbound model.Inbound
  325. client map[string]any
  326. }
  327. // Resolve the inbounds to renew through the client_inbounds link rather than
  328. // client_traffics.inbound_id, which goes stale after an inbound is deleted and
  329. // recreated and would otherwise skip the renew entirely.
  330. renewEmails := make([]string, 0, len(traffics))
  331. for _, traffic := range traffics {
  332. renewEmails = append(renewEmails, traffic.Email)
  333. }
  334. for _, batch := range chunkStrings(renewEmails, sqliteMaxVars) {
  335. var ids []int
  336. if err = tx.Table("client_inbounds").
  337. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  338. Where("clients.email IN ?", batch).
  339. Distinct().
  340. Pluck("client_inbounds.inbound_id", &ids).Error; err != nil {
  341. return false, 0, err
  342. }
  343. inbound_ids = append(inbound_ids, ids...)
  344. }
  345. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  346. // per tick instead of N times across chunk boundaries.
  347. inbound_ids = uniqueInts(inbound_ids)
  348. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  349. // are touched in a single tick.
  350. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  351. var page []*model.Inbound
  352. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  353. return false, 0, err
  354. }
  355. inbounds = append(inbounds, page...)
  356. }
  357. // Index the expired traffics by email so each client is an O(1) lookup
  358. // instead of a linear scan of every expired row (O(clients × expired) per
  359. // inbound, quadratic at scale). Pointers keep the in-place mutation below.
  360. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  361. for i := range traffics {
  362. trafficByEmail[traffics[i].Email] = traffics[i]
  363. }
  364. for inbound_index := range inbounds {
  365. settings := map[string]any{}
  366. _ = json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  367. clients, _ := settings["clients"].([]any)
  368. if len(clients) == 0 {
  369. continue
  370. }
  371. cipher := ""
  372. if inbounds[inbound_index].Protocol == model.Shadowsocks {
  373. cipher, _ = settings["method"].(string)
  374. }
  375. for client_index := range clients {
  376. c := clients[client_index].(map[string]any)
  377. email, _ := c["email"].(string)
  378. traffic, ok := trafficByEmail[email]
  379. if !ok {
  380. continue
  381. }
  382. newExpiryTime := traffic.ExpiryTime
  383. for newExpiryTime < now {
  384. newExpiryTime += (int64(traffic.Reset) * 86400000)
  385. }
  386. c["expiryTime"] = newExpiryTime
  387. traffic.ExpiryTime = newExpiryTime
  388. traffic.Down = 0
  389. traffic.Up = 0
  390. if !traffic.Enable {
  391. traffic.Enable = true
  392. c["enable"] = true
  393. clientsToAdd = append(clientsToAdd,
  394. struct {
  395. inbound model.Inbound
  396. client map[string]any
  397. }{
  398. inbound: *inbounds[inbound_index],
  399. client: apiUserFromClient(c, cipher),
  400. })
  401. }
  402. clients[client_index] = any(c)
  403. }
  404. settings["clients"] = clients
  405. newSettings, err := json.MarshalIndent(settings, "", " ")
  406. if err != nil {
  407. return false, 0, err
  408. }
  409. inbounds[inbound_index].Settings = string(newSettings)
  410. }
  411. err = tx.Save(inbounds).Error
  412. if err != nil {
  413. return false, 0, err
  414. }
  415. for _, ib := range inbounds {
  416. if ib == nil {
  417. continue
  418. }
  419. cs, gcErr := s.GetClients(ib)
  420. if gcErr != nil {
  421. logger.Warning("autoRenewClients sync clients: GetClients failed", gcErr)
  422. continue
  423. }
  424. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  425. logger.Warning("autoRenewClients sync clients: SyncInbound failed", syncErr)
  426. }
  427. }
  428. err = tx.Save(traffics).Error
  429. if err != nil {
  430. return false, 0, err
  431. }
  432. // A renewed client starts a fresh quota window: drop the cross-panel rows
  433. // too, or the stale pushed totals would re-deplete it immediately.
  434. if err = clearGlobalTraffic(tx, renewEmails...); err != nil {
  435. return false, 0, err
  436. }
  437. for _, clientToAdd := range clientsToAdd {
  438. if clientToAdd.inbound.NodeID != nil {
  439. mutationBatch.addNode(*clientToAdd.inbound.NodeID)
  440. continue
  441. }
  442. mutationBatch.localPlans = append(mutationBatch.localPlans, trafficLocalApplyPlan{
  443. action: trafficAddUser, inbound: clientToAdd.inbound, client: clientToAdd.client,
  444. })
  445. }
  446. return needRestart, int64(len(traffics)), nil
  447. }
  448. // AddClientStat inserts a per-client accounting row, or refreshes the
  449. // config-derived columns on an email conflict. Xray reports traffic per
  450. // email, so the surviving row also acts as the shared accumulator for
  451. // inbounds that re-use the same identity — every call for that identity
  452. // (one per attached inbound) carries the same enable/expiry/reset/total,
  453. // so re-asserting them here is idempotent for that legitimate case.
  454. //
  455. // The conflict path matters on its own for a second reason: an inbound
  456. // delete detaches its clients (InboundService.DelInbound) without deleting
  457. // their client_traffics row, by design — mirroring ClientService.Detach,
  458. // which intentionally leaves a fully-detached client's row in place so a
  459. // later Attach can resume it with its accumulated traffic intact. If that
  460. // same email is instead reused for a freshly (re)created client, the new
  461. // config's enable/expiry/reset/total must win over whatever the orphaned
  462. // row still holds; DoNothing left them stale indefinitely (#5958).
  463. //
  464. // up/down are deliberately excluded from the refresh: they are the
  465. // accumulated traffic totals, and zeroing them here would erase real usage
  466. // every time an existing, actively-used client is attached to one more
  467. // inbound. One tradeoff this does not resolve: a genuinely new client that
  468. // happens to reuse an orphaned email still inherits that row's leftover
  469. // up/down, since nothing at this call site can tell the two cases apart.
  470. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  471. clientTraffic := xray.ClientTraffic{
  472. InboundId: inboundId,
  473. Email: client.Email,
  474. Total: client.TotalGB,
  475. ExpiryTime: client.ExpiryTime,
  476. Enable: client.Enable,
  477. Reset: client.Reset,
  478. }
  479. return tx.Clauses(clause.OnConflict{
  480. Columns: []clause.Column{{Name: "email"}},
  481. DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset"}),
  482. }).Create(&clientTraffic).Error
  483. }
  484. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  485. result := tx.Model(xray.ClientTraffic{}).
  486. Where("email = ?", email).
  487. Updates(map[string]any{
  488. "enable": client.Enable,
  489. "email": client.Email,
  490. "total": client.TotalGB,
  491. "expiry_time": client.ExpiryTime,
  492. "reset": client.Reset,
  493. })
  494. err := result.Error
  495. return err
  496. }
  497. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  498. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{email}); err != nil {
  499. return err
  500. }
  501. if err := tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error; err != nil {
  502. return err
  503. }
  504. if err := clearGlobalTraffic(tx, email); err != nil {
  505. return err
  506. }
  507. return tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error
  508. }
  509. func (s *InboundService) delClientStatsByEmails(tx *gorm.DB, emails []string) error {
  510. if err := adjustGroupBaselinesForRemovedTraffic(tx, emails); err != nil {
  511. return err
  512. }
  513. const chunk = 400
  514. for start := 0; start < len(emails); start += chunk {
  515. end := min(start+chunk, len(emails))
  516. batch := emails[start:end]
  517. if err := tx.Where("email IN ?", batch).Delete(xray.ClientTraffic{}).Error; err != nil {
  518. return err
  519. }
  520. if err := tx.Where("email IN ?", batch).Delete(&model.ClientGlobalTraffic{}).Error; err != nil {
  521. return err
  522. }
  523. if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  524. return err
  525. }
  526. }
  527. return nil
  528. }
  529. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  530. err := submitTrafficWrite(func() error {
  531. return database.GetDB().Transaction(func(tx *gorm.DB) error {
  532. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  533. return err
  534. }
  535. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  536. return err
  537. }
  538. if err := tx.Model(xray.ClientTraffic{}).
  539. Where("email = ?", clientEmail).
  540. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error; err != nil {
  541. return err
  542. }
  543. return tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error
  544. })
  545. })
  546. if err == nil {
  547. s.resetMtprotoClientQuota(clientEmail)
  548. }
  549. return err
  550. }
  551. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  552. var resetInbound *model.Inbound
  553. err = submitTrafficWrite(func() error {
  554. var inner error
  555. needRestart, resetInbound, inner = s.resetClientTrafficLocked(id, clientEmail)
  556. return inner
  557. })
  558. if err == nil {
  559. s.resetMtprotoClientQuota(clientEmail)
  560. if resetInbound != nil && resetInbound.NodeID != nil {
  561. if rt, rterr := s.runtimeFor(resetInbound); rterr == nil {
  562. if e := rt.ResetClientTraffic(context.Background(), resetInbound, clientEmail); e != nil {
  563. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  564. }
  565. } else {
  566. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  567. }
  568. }
  569. }
  570. return
  571. }
  572. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, *model.Inbound, error) {
  573. needRestart := false
  574. var reenablePlan *trafficLocalApplyPlan
  575. var reenableNodeID *int
  576. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  577. if err != nil {
  578. return false, nil, err
  579. }
  580. if !traffic.Enable {
  581. inbound, err := s.GetInbound(id)
  582. if err != nil {
  583. return false, nil, err
  584. }
  585. clients, err := s.GetClients(inbound)
  586. if err != nil {
  587. return false, nil, err
  588. }
  589. for _, client := range clients {
  590. if client.Email == clientEmail && client.Enable {
  591. cipher := ""
  592. if string(inbound.Protocol) == "shadowsocks" {
  593. var oldSettings map[string]any
  594. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  595. if err != nil {
  596. return false, nil, err
  597. }
  598. cipher, _ = oldSettings["method"].(string)
  599. }
  600. clientMap := map[string]any{
  601. "email": client.Email,
  602. "id": client.ID,
  603. "auth": client.Auth,
  604. "security": client.Security,
  605. "flow": client.Flow,
  606. "password": client.Password,
  607. "cipher": cipher,
  608. }
  609. if inbound.NodeID != nil {
  610. reenableNodeID = inbound.NodeID
  611. } else {
  612. reenablePlan = &trafficLocalApplyPlan{action: trafficAddUser, inbound: *inbound, client: clientMap}
  613. }
  614. break
  615. }
  616. }
  617. }
  618. traffic.Up = 0
  619. traffic.Down = 0
  620. traffic.Enable = true
  621. db := database.GetDB()
  622. now := time.Now().UnixMilli()
  623. inbound, err := s.GetInbound(id)
  624. if err != nil {
  625. return false, nil, err
  626. }
  627. if err := db.Transaction(func(tx *gorm.DB) error {
  628. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  629. return err
  630. }
  631. if err := tx.Save(traffic).Error; err != nil {
  632. return err
  633. }
  634. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  635. return err
  636. }
  637. if err := tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  638. return err
  639. }
  640. if err := tx.Model(model.Inbound{}).
  641. Where("id = ?", id).
  642. Update("last_traffic_reset_time", now).Error; err != nil {
  643. return err
  644. }
  645. if reenableNodeID != nil {
  646. return (&NodeService{}).MarkNodeDirtyTx(tx, *reenableNodeID)
  647. }
  648. if inbound != nil && inbound.NodeID != nil {
  649. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  650. }
  651. return nil
  652. }); err != nil {
  653. return false, nil, err
  654. }
  655. if reenablePlan != nil {
  656. rt, err := s.runtimeFor(&reenablePlan.inbound)
  657. if err != nil {
  658. needRestart = true
  659. } else if err := rt.AddUser(context.Background(), &reenablePlan.inbound, reenablePlan.client); err != nil {
  660. logger.Debug("Error in enabling client on", rt.Name(), ":", err)
  661. needRestart = true
  662. } else {
  663. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  664. }
  665. }
  666. return needRestart, inbound, nil
  667. }
  668. func (s *InboundService) ResetAllTraffics() error {
  669. err := submitTrafficWrite(func() error {
  670. return s.resetAllTrafficsLocked()
  671. })
  672. if err == nil {
  673. s.propagateResetAllTrafficsToNodes()
  674. s.resetAllMtprotoQuotas()
  675. }
  676. return err
  677. }
  678. func (s *InboundService) resetAllTrafficsLocked() error {
  679. db := database.GetDB()
  680. now := time.Now().UnixMilli()
  681. return db.Model(model.Inbound{}).
  682. Where("user_id > ?", 0).
  683. Updates(map[string]any{
  684. "up": 0,
  685. "down": 0,
  686. "last_traffic_reset_time": now,
  687. }).Error
  688. }
  689. // propagateResetAllTrafficsToNodes tells every node to zero its own counters.
  690. // Kept OUT of the traffic-writer transaction: each remote call can block up to
  691. // remoteHTTPTimeout, and holding the single serial writer across N such calls
  692. // stalls traffic accounting and drops the deltas of every concurrent poll.
  693. func (s *InboundService) propagateResetAllTrafficsToNodes() {
  694. nodes, err := (&NodeService{}).GetAll()
  695. if err != nil {
  696. return
  697. }
  698. for _, node := range nodes {
  699. if rt, err := runtime.GetManager().RuntimeFor(&node.Id); err == nil {
  700. if e := rt.ResetAllTraffics(context.Background()); e != nil {
  701. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  702. }
  703. }
  704. }
  705. }
  706. func (s *InboundService) ResetInboundTraffic(id int) error {
  707. var inbound *model.Inbound
  708. if err := submitTrafficWrite(func() error {
  709. db := database.GetDB()
  710. if err := db.Model(model.Inbound{}).
  711. Where("id = ?", id).
  712. Updates(map[string]any{"up": 0, "down": 0}).Error; err != nil {
  713. return err
  714. }
  715. var err error
  716. inbound, err = s.GetInbound(id)
  717. if err != nil {
  718. return err
  719. }
  720. return nil
  721. }); err != nil {
  722. return err
  723. }
  724. if inbound != nil && inbound.NodeID != nil {
  725. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  726. if e := rt.ResetInboundTraffic(context.Background(), inbound); e != nil {
  727. logger.Warning("ResetInboundTraffic: remote propagation to", rt.Name(), "failed:", e)
  728. }
  729. } else {
  730. logger.Warning("ResetInboundTraffic: runtime lookup failed:", rterr)
  731. }
  732. }
  733. return nil
  734. }
  735. func (s *InboundService) DelDepletedClients(id int) (err error) {
  736. db := database.GetDB()
  737. var deletedInbounds []model.Inbound
  738. err = db.Transaction(func(tx *gorm.DB) error {
  739. // Collect depleted emails globally — a shared-email row owned by one
  740. // inbound depletes every sibling that lists the email.
  741. now := time.Now().Unix() * 1000
  742. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  743. var depletedRows []xray.ClientTraffic
  744. if err := tx.Model(xray.ClientTraffic{}).
  745. Where(depletedClause, now).
  746. Find(&depletedRows).Error; err != nil {
  747. return err
  748. }
  749. if len(depletedRows) == 0 {
  750. return nil
  751. }
  752. depletedEmails := make(map[string]struct{}, len(depletedRows))
  753. for _, r := range depletedRows {
  754. if r.Email == "" {
  755. continue
  756. }
  757. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  758. }
  759. if len(depletedEmails) == 0 {
  760. return nil
  761. }
  762. var inbounds []*model.Inbound
  763. inboundQuery := tx.Model(model.Inbound{})
  764. if id >= 0 {
  765. inboundQuery = inboundQuery.Where("id = ?", id)
  766. }
  767. if err := inboundQuery.Find(&inbounds).Error; err != nil {
  768. return err
  769. }
  770. for _, inbound := range inbounds {
  771. var settings map[string]any
  772. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  773. return err
  774. }
  775. rawClients, ok := settings["clients"].([]any)
  776. if !ok {
  777. continue
  778. }
  779. newClients := make([]any, 0, len(rawClients))
  780. removed := 0
  781. for _, client := range rawClients {
  782. c, ok := client.(map[string]any)
  783. if !ok {
  784. newClients = append(newClients, client)
  785. continue
  786. }
  787. email, _ := c["email"].(string)
  788. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  789. removed++
  790. continue
  791. }
  792. newClients = append(newClients, client)
  793. }
  794. if removed == 0 {
  795. continue
  796. }
  797. if len(newClients) == 0 {
  798. deletedInbounds = append(deletedInbounds, *inbound)
  799. if err := s.clientService.DetachInbound(tx, inbound.Id); err != nil {
  800. return err
  801. }
  802. if err := tx.Where("inbound_id = ?", inbound.Id).Delete(&model.Host{}).Error; err != nil {
  803. return err
  804. }
  805. if err := tx.Delete(model.Inbound{}, inbound.Id).Error; err != nil {
  806. return err
  807. }
  808. if inbound.NodeID != nil {
  809. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); err != nil {
  810. return err
  811. }
  812. }
  813. continue
  814. }
  815. settings["clients"] = newClients
  816. ns, mErr := json.MarshalIndent(settings, "", " ")
  817. if mErr != nil {
  818. return mErr
  819. }
  820. inbound.Settings = string(ns)
  821. if err := tx.Save(inbound).Error; err != nil {
  822. return err
  823. }
  824. survivingClients, gcErr := s.GetClients(inbound)
  825. if gcErr != nil {
  826. return gcErr
  827. }
  828. if err := s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  829. return err
  830. }
  831. if inbound.NodeID != nil {
  832. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); err != nil {
  833. return err
  834. }
  835. }
  836. }
  837. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  838. // no out-of-scope inbound still references the email.
  839. if id < 0 {
  840. return tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  841. }
  842. emails := make([]string, 0, len(depletedEmails))
  843. for e := range depletedEmails {
  844. emails = append(emails, e)
  845. }
  846. var stillReferenced []string
  847. emailExpr := database.JSONFieldText("client.value", "email")
  848. stillQuery := fmt.Sprintf(
  849. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  850. emailExpr,
  851. database.JSONClientsFromInbound(),
  852. emailExpr,
  853. )
  854. if err := tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  855. return err
  856. }
  857. stillSet := make(map[string]struct{}, len(stillReferenced))
  858. for _, e := range stillReferenced {
  859. stillSet[e] = struct{}{}
  860. }
  861. toDelete := make([]string, 0, len(emails))
  862. for _, e := range emails {
  863. if _, kept := stillSet[e]; !kept {
  864. toDelete = append(toDelete, e)
  865. }
  866. }
  867. if len(toDelete) > 0 {
  868. if err := tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  869. return err
  870. }
  871. }
  872. return nil
  873. })
  874. if err != nil {
  875. return err
  876. }
  877. for i := range deletedInbounds {
  878. inbound := &deletedInbounds[i]
  879. if rt, rtErr := s.runtimeFor(inbound); rtErr != nil {
  880. logger.Warning("DelDepletedClients: runtime lookup failed after commit:", rtErr)
  881. } else if rtErr = rt.DelInbound(context.Background(), inbound); rtErr != nil && !xray.IsMissingHandlerErr(rtErr) {
  882. logger.Warning("DelDepletedClients: runtime cleanup failed after commit:", rtErr)
  883. }
  884. if inbound.Tag != "" {
  885. if _, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(inbound.Tag); syncErr != nil {
  886. logger.Warning("DelDepletedClients: routing cleanup failed after commit:", syncErr)
  887. }
  888. }
  889. }
  890. return nil
  891. }
  892. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  893. db := database.GetDB()
  894. idQuery := fmt.Sprintf(
  895. "SELECT DISTINCT inbounds.id %s WHERE %s = ?",
  896. database.JSONClientsFromInbound(),
  897. database.JSONFieldText("client.value", "tgId"),
  898. )
  899. var inboundIds []int
  900. if err := db.Raw(idQuery, strconv.FormatInt(tgId, 10)).Scan(&inboundIds).Error; err != nil {
  901. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  902. return nil, err
  903. }
  904. var inbounds []*model.Inbound
  905. if len(inboundIds) > 0 {
  906. err := db.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error
  907. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  908. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  909. return nil, err
  910. }
  911. }
  912. var emails []string
  913. for _, inbound := range inbounds {
  914. clients, err := s.GetClients(inbound)
  915. if err != nil {
  916. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  917. continue
  918. }
  919. for _, client := range clients {
  920. if client.TgID == tgId {
  921. emails = append(emails, client.Email)
  922. }
  923. }
  924. }
  925. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  926. // account owns thousands of clients across inbounds.
  927. uniqEmails := uniqueNonEmptyStrings(emails)
  928. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  929. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  930. var page []*xray.ClientTraffic
  931. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  932. if errors.Is(err, gorm.ErrRecordNotFound) {
  933. continue
  934. }
  935. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  936. return nil, err
  937. }
  938. traffics = append(traffics, page...)
  939. }
  940. if len(traffics) == 0 {
  941. logger.Warning("No ClientTraffic records found for emails:", emails)
  942. return nil, nil
  943. }
  944. // Populate UUID and other client data for each traffic record
  945. for i := range traffics {
  946. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  947. traffics[i].Enable = client.Enable
  948. traffics[i].UUID = client.ID
  949. traffics[i].SubId = client.SubID
  950. }
  951. }
  952. return traffics, nil
  953. }
  954. // BumpClientsLastOnline sets client_traffics.last_online to now for the given
  955. // emails. Used in online-API mode for clients that hold a live connection but
  956. // moved no bytes this poll — the traffic path (addClientTraffic) only bumps
  957. // last_online on a non-zero delta, so idle-but-connected clients would
  958. // otherwise show a stale "last online" while being reported online.
  959. func (s *InboundService) BumpClientsLastOnline(emails []string) error {
  960. uniq := uniqueNonEmptyStrings(emails)
  961. if len(uniq) == 0 {
  962. return nil
  963. }
  964. now := time.Now().UnixMilli()
  965. return submitTrafficWrite(func() error {
  966. db := database.GetDB()
  967. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  968. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("last_online", now).Error; err != nil {
  969. return err
  970. }
  971. }
  972. return nil
  973. })
  974. }
  975. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  976. uniq := uniqueNonEmptyStrings(emails)
  977. if len(uniq) == 0 {
  978. return nil, nil
  979. }
  980. db := database.GetDB()
  981. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  982. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  983. var page []*xray.ClientTraffic
  984. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  985. return nil, err
  986. }
  987. traffics = append(traffics, page...)
  988. }
  989. overlayGlobalTraffic(db, traffics)
  990. return traffics, nil
  991. }
  992. // GetAllClientTraffics returns the full set of client_traffics rows so the
  993. // websocket broadcasters can ship a complete snapshot every cycle. A pure
  994. // delta path silently dropped the per-client section whenever no client moved
  995. // bytes in the cycle or a node sync failed, leaving client rows in the UI
  996. // stuck at stale numbers — so small installs broadcast this snapshot, and only
  997. // above the traffic job's snapshot threshold (where the marshaled snapshot
  998. // would exceed the hub's payload cap and be dropped wholesale) does the job
  999. // fall back to active-row deltas.
  1000. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  1001. db := database.GetDB()
  1002. var traffics []*xray.ClientTraffic
  1003. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  1004. return nil, err
  1005. }
  1006. overlayGlobalTraffic(db, traffics)
  1007. return traffics, nil
  1008. }
  1009. func (s *InboundService) CountClientTraffics() (int64, error) {
  1010. db := database.GetDB()
  1011. var count int64
  1012. err := db.Model(xray.ClientTraffic{}).Count(&count).Error
  1013. return count, err
  1014. }
  1015. type InboundTrafficSummary struct {
  1016. Id int `json:"id"`
  1017. Up int64 `json:"up"`
  1018. Down int64 `json:"down"`
  1019. Total int64 `json:"total"`
  1020. Enable bool `json:"enable"`
  1021. }
  1022. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  1023. db := database.GetDB()
  1024. var summaries []InboundTrafficSummary
  1025. if err := db.Model(&model.Inbound{}).
  1026. Select("id, up, down, total, enable").
  1027. Find(&summaries).Error; err != nil {
  1028. return nil, err
  1029. }
  1030. return summaries, nil
  1031. }
  1032. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1033. db := database.GetDB()
  1034. var traffics []*xray.ClientTraffic
  1035. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error; err != nil {
  1036. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1037. return nil, err
  1038. }
  1039. if len(traffics) == 0 {
  1040. return nil, nil
  1041. }
  1042. overlayGlobalTraffic(db, traffics)
  1043. t := traffics[0]
  1044. if rec, rErr := s.clientService.GetRecordByEmail(db, email); rErr == nil && rec != nil {
  1045. c := rec.ToClient()
  1046. t.UUID = c.ID
  1047. t.SubId = c.SubID
  1048. return t, nil
  1049. }
  1050. t2, client, err := s.GetClientByEmail(email)
  1051. if err != nil {
  1052. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1053. return nil, err
  1054. }
  1055. if t2 != nil && client != nil {
  1056. t2.UUID = client.ID
  1057. t2.SubId = client.SubID
  1058. return t2, nil
  1059. }
  1060. return nil, nil
  1061. }
  1062. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  1063. return submitTrafficWrite(func() error {
  1064. db := database.GetDB()
  1065. err := db.Model(xray.ClientTraffic{}).
  1066. Where("email = ?", email).
  1067. Updates(map[string]any{
  1068. "up": upload,
  1069. "down": download,
  1070. }).Error
  1071. if err != nil {
  1072. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  1073. }
  1074. return err
  1075. })
  1076. }
  1077. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1078. db := database.GetDB()
  1079. inbound := &model.Inbound{}
  1080. traffic = &xray.ClientTraffic{}
  1081. // Search for inbound settings that contain the query
  1082. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1083. if err != nil {
  1084. if errors.Is(err, gorm.ErrRecordNotFound) {
  1085. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1086. return nil, err
  1087. }
  1088. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1089. return nil, err
  1090. }
  1091. traffic.InboundId = inbound.Id
  1092. clients, err := ParseInboundSettingsClients(inbound.Settings)
  1093. if err != nil {
  1094. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1095. return nil, err
  1096. }
  1097. for _, client := range clients {
  1098. if (client.ID == query || client.Password == query) && client.Email != "" {
  1099. traffic.Email = client.Email
  1100. break
  1101. }
  1102. }
  1103. if traffic.Email == "" {
  1104. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1105. return nil, gorm.ErrRecordNotFound
  1106. }
  1107. // Retrieve ClientTraffic based on the found email
  1108. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1109. if err != nil {
  1110. if errors.Is(err, gorm.ErrRecordNotFound) {
  1111. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1112. return nil, err
  1113. }
  1114. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1115. return nil, err
  1116. }
  1117. return traffic, nil
  1118. }