inbound_traffic.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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 or reset_day > 0) and expiry_time > 0 and expiry_time <= ?", now).
  307. // A prepaid plan stops itself: once as many renewals have fired as the
  308. // operator allowed, the client is left to expire like any other.
  309. Where("reset_max <= 0 or reset_count < reset_max").
  310. Where("email IN (?)", tx.Table("client_inbounds ci").
  311. Select("c.email").
  312. Joins("JOIN clients c ON c.id = ci.client_id").
  313. Joins("JOIN inbounds i ON i.id = ci.inbound_id").
  314. Where("i.node_id IS NULL")).
  315. Find(&traffics).Error
  316. if err != nil {
  317. return false, 0, err
  318. }
  319. // return if there is no client to renew
  320. if len(traffics) == 0 {
  321. return false, 0, nil
  322. }
  323. renewLocation, locErr := (&SettingService{}).GetTimeLocation()
  324. if locErr != nil || renewLocation == nil {
  325. // Falling back to UTC keeps renewals happening; the alternative is
  326. // skipping them entirely because a setting could not be read.
  327. logger.Warning("autoRenewClients: could not read the panel time zone, using UTC:", locErr)
  328. renewLocation = time.UTC
  329. }
  330. var inbound_ids []int
  331. var inbounds []*model.Inbound
  332. needRestart := false
  333. var clientsToAdd []struct {
  334. inbound model.Inbound
  335. client map[string]any
  336. }
  337. // Resolve the inbounds to renew through the client_inbounds link rather than
  338. // client_traffics.inbound_id, which goes stale after an inbound is deleted and
  339. // recreated and would otherwise skip the renew entirely.
  340. renewEmails := make([]string, 0, len(traffics))
  341. for _, traffic := range traffics {
  342. renewEmails = append(renewEmails, traffic.Email)
  343. }
  344. for _, batch := range chunkStrings(renewEmails, sqliteMaxVars) {
  345. var ids []int
  346. if err = tx.Table("client_inbounds").
  347. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  348. Where("clients.email IN ?", batch).
  349. Distinct().
  350. Pluck("client_inbounds.inbound_id", &ids).Error; err != nil {
  351. return false, 0, err
  352. }
  353. inbound_ids = append(inbound_ids, ids...)
  354. }
  355. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  356. // per tick instead of N times across chunk boundaries.
  357. inbound_ids = uniqueInts(inbound_ids)
  358. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  359. // are touched in a single tick.
  360. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  361. var page []*model.Inbound
  362. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  363. return false, 0, err
  364. }
  365. inbounds = append(inbounds, page...)
  366. }
  367. // Index the expired traffics by email so each client is an O(1) lookup
  368. // instead of a linear scan of every expired row (O(clients × expired) per
  369. // inbound, quadratic at scale). Pointers keep the in-place mutation below.
  370. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  371. for i := range traffics {
  372. trafficByEmail[traffics[i].Email] = traffics[i]
  373. }
  374. for inbound_index := range inbounds {
  375. settings := map[string]any{}
  376. _ = json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  377. clients, _ := settings["clients"].([]any)
  378. if len(clients) == 0 {
  379. continue
  380. }
  381. cipher := ""
  382. if inbounds[inbound_index].Protocol == model.Shadowsocks {
  383. cipher, _ = settings["method"].(string)
  384. }
  385. for client_index := range clients {
  386. c := clients[client_index].(map[string]any)
  387. email, _ := c["email"].(string)
  388. traffic, ok := trafficByEmail[email]
  389. if !ok {
  390. continue
  391. }
  392. // One allowance per period, not per tick: a client away for three
  393. // cycles must not catch up three of them against a prepaid cap.
  394. newExpiryTime := traffic.ExpiryTime
  395. if traffic.ResetDay <= 0 && traffic.Reset <= 0 {
  396. // Unreachable while the selection filter holds: a zero step below
  397. // would spin forever on the single traffic writer and hang the panel.
  398. continue
  399. }
  400. at := time.UnixMilli(newExpiryTime)
  401. renewals := 0
  402. for newExpiryTime < now {
  403. if traffic.ResetMax > 0 && traffic.ResetCount+renewals >= traffic.ResetMax {
  404. break
  405. }
  406. if traffic.ResetDay > 0 {
  407. // Calendar mode: step whole months in the panel's zone, so the
  408. // renewal date does not drift the way a fixed 30-day step does.
  409. at = nextCalendarRenewal(at, traffic.ResetDay, renewLocation)
  410. newExpiryTime = at.UnixMilli()
  411. } else {
  412. newExpiryTime += (int64(traffic.Reset) * 86400000)
  413. }
  414. renewals++
  415. }
  416. if renewals == 0 {
  417. continue
  418. }
  419. c["expiryTime"] = newExpiryTime
  420. traffic.ExpiryTime = newExpiryTime
  421. traffic.ResetCount += renewals
  422. if newExpiryTime <= now {
  423. // Cap ran out mid-catch-up and the client is still expired: enabling it
  424. // for disableInvalidClients to undo adds and removes an xray user for nothing.
  425. clients[client_index] = any(c)
  426. continue
  427. }
  428. traffic.Down = 0
  429. traffic.Up = 0
  430. if !traffic.Enable {
  431. traffic.Enable = true
  432. c["enable"] = true
  433. clientsToAdd = append(clientsToAdd,
  434. struct {
  435. inbound model.Inbound
  436. client map[string]any
  437. }{
  438. inbound: *inbounds[inbound_index],
  439. client: apiUserFromClient(c, cipher),
  440. })
  441. }
  442. clients[client_index] = any(c)
  443. }
  444. settings["clients"] = clients
  445. newSettings, err := json.MarshalIndent(settings, "", " ")
  446. if err != nil {
  447. return false, 0, err
  448. }
  449. inbounds[inbound_index].Settings = string(newSettings)
  450. }
  451. err = tx.Save(inbounds).Error
  452. if err != nil {
  453. return false, 0, err
  454. }
  455. for _, ib := range inbounds {
  456. if ib == nil {
  457. continue
  458. }
  459. cs, gcErr := s.GetClients(ib)
  460. if gcErr != nil {
  461. logger.Warning("autoRenewClients sync clients: GetClients failed", gcErr)
  462. continue
  463. }
  464. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  465. logger.Warning("autoRenewClients sync clients: SyncInbound failed", syncErr)
  466. }
  467. }
  468. err = tx.Save(traffics).Error
  469. if err != nil {
  470. return false, 0, err
  471. }
  472. // A renewed client starts a fresh quota window: drop the cross-panel rows
  473. // too, or the stale pushed totals would re-deplete it immediately.
  474. if err = clearGlobalTraffic(tx, renewEmails...); err != nil {
  475. return false, 0, err
  476. }
  477. for _, clientToAdd := range clientsToAdd {
  478. if clientToAdd.inbound.NodeID != nil {
  479. mutationBatch.addNode(*clientToAdd.inbound.NodeID)
  480. continue
  481. }
  482. mutationBatch.localPlans = append(mutationBatch.localPlans, trafficLocalApplyPlan{
  483. action: trafficAddUser, inbound: clientToAdd.inbound, client: clientToAdd.client,
  484. })
  485. }
  486. return needRestart, int64(len(traffics)), nil
  487. }
  488. // AddClientStat inserts a per-client accounting row, or refreshes the
  489. // config-derived columns on an email conflict. Xray reports traffic per
  490. // email, so the surviving row also acts as the shared accumulator for
  491. // inbounds that re-use the same identity — every call for that identity
  492. // (one per attached inbound) carries the same enable/expiry/reset/total,
  493. // so re-asserting them here is idempotent for that legitimate case.
  494. //
  495. // The conflict path matters on its own for a second reason: an inbound
  496. // delete detaches its clients (InboundService.DelInbound) without deleting
  497. // their client_traffics row, by design — mirroring ClientService.Detach,
  498. // which intentionally leaves a fully-detached client's row in place so a
  499. // later Attach can resume it with its accumulated traffic intact. If that
  500. // same email is instead reused for a freshly (re)created client, the new
  501. // config's enable/expiry/reset/total must win over whatever the orphaned
  502. // row still holds; DoNothing left them stale indefinitely (#5958).
  503. //
  504. // up/down are deliberately excluded from the refresh: they are the
  505. // accumulated traffic totals, and zeroing them here would erase real usage
  506. // every time an existing, actively-used client is attached to one more
  507. // inbound. One tradeoff this does not resolve: a genuinely new client that
  508. // happens to reuse an orphaned email still inherits that row's leftover
  509. // up/down, since nothing at this call site can tell the two cases apart.
  510. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  511. clientTraffic := xray.ClientTraffic{
  512. InboundId: inboundId,
  513. Email: client.Email,
  514. Total: client.TotalGB,
  515. ExpiryTime: client.ExpiryTime,
  516. Enable: client.Enable,
  517. Reset: client.Reset,
  518. ResetDay: client.ResetDay,
  519. ResetMax: client.ResetMax,
  520. }
  521. return tx.Clauses(clause.OnConflict{
  522. Columns: []clause.Column{{Name: "email"}},
  523. DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset", "reset_day", "reset_max"}),
  524. }).Create(&clientTraffic).Error
  525. }
  526. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  527. result := tx.Model(xray.ClientTraffic{}).
  528. Where("email = ?", email).
  529. Updates(map[string]any{
  530. "enable": client.Enable,
  531. "email": client.Email,
  532. "total": client.TotalGB,
  533. "expiry_time": client.ExpiryTime,
  534. "reset": client.Reset,
  535. "reset_day": client.ResetDay,
  536. "reset_max": client.ResetMax,
  537. })
  538. err := result.Error
  539. return err
  540. }
  541. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  542. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{email}); err != nil {
  543. return err
  544. }
  545. if err := tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error; err != nil {
  546. return err
  547. }
  548. if err := clearGlobalTraffic(tx, email); err != nil {
  549. return err
  550. }
  551. return tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error
  552. }
  553. func (s *InboundService) delClientStatsByEmails(tx *gorm.DB, emails []string) error {
  554. if err := adjustGroupBaselinesForRemovedTraffic(tx, emails); err != nil {
  555. return err
  556. }
  557. const chunk = 400
  558. for start := 0; start < len(emails); start += chunk {
  559. end := min(start+chunk, len(emails))
  560. batch := emails[start:end]
  561. if err := tx.Where("email IN ?", batch).Delete(xray.ClientTraffic{}).Error; err != nil {
  562. return err
  563. }
  564. if err := tx.Where("email IN ?", batch).Delete(&model.ClientGlobalTraffic{}).Error; err != nil {
  565. return err
  566. }
  567. if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  568. return err
  569. }
  570. }
  571. return nil
  572. }
  573. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  574. err := submitTrafficWrite(func() error {
  575. return database.GetDB().Transaction(func(tx *gorm.DB) error {
  576. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  577. return err
  578. }
  579. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  580. return err
  581. }
  582. if err := tx.Model(xray.ClientTraffic{}).
  583. Where("email = ?", clientEmail).
  584. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error; err != nil {
  585. return err
  586. }
  587. return tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error
  588. })
  589. })
  590. if err == nil {
  591. s.resetMtprotoClientQuota(clientEmail)
  592. }
  593. return err
  594. }
  595. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  596. var resetInbound *model.Inbound
  597. err = submitTrafficWrite(func() error {
  598. var inner error
  599. needRestart, resetInbound, inner = s.resetClientTrafficLocked(id, clientEmail)
  600. return inner
  601. })
  602. if err == nil {
  603. s.resetMtprotoClientQuota(clientEmail)
  604. if resetInbound != nil && resetInbound.NodeID != nil {
  605. if rt, rterr := s.runtimeFor(resetInbound); rterr == nil {
  606. if e := rt.ResetClientTraffic(context.Background(), resetInbound, clientEmail); e != nil {
  607. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  608. }
  609. } else {
  610. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  611. }
  612. }
  613. }
  614. return
  615. }
  616. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, *model.Inbound, error) {
  617. needRestart := false
  618. var reenablePlan *trafficLocalApplyPlan
  619. var reenableNodeID *int
  620. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  621. if err != nil {
  622. return false, nil, err
  623. }
  624. if !traffic.Enable {
  625. inbound, err := s.GetInbound(id)
  626. if err != nil {
  627. return false, nil, err
  628. }
  629. clients, err := s.GetClients(inbound)
  630. if err != nil {
  631. return false, nil, err
  632. }
  633. for _, client := range clients {
  634. if client.Email == clientEmail && client.Enable {
  635. cipher := ""
  636. if string(inbound.Protocol) == "shadowsocks" {
  637. var oldSettings map[string]any
  638. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  639. if err != nil {
  640. return false, nil, err
  641. }
  642. cipher, _ = oldSettings["method"].(string)
  643. }
  644. clientMap := map[string]any{
  645. "email": client.Email,
  646. "id": client.ID,
  647. "auth": client.Auth,
  648. "security": client.Security,
  649. "flow": client.Flow,
  650. "password": client.Password,
  651. "cipher": cipher,
  652. }
  653. if inbound.NodeID != nil {
  654. reenableNodeID = inbound.NodeID
  655. } else {
  656. reenablePlan = &trafficLocalApplyPlan{action: trafficAddUser, inbound: *inbound, client: clientMap}
  657. }
  658. break
  659. }
  660. }
  661. }
  662. traffic.Up = 0
  663. traffic.Down = 0
  664. traffic.Enable = true
  665. db := database.GetDB()
  666. now := time.Now().UnixMilli()
  667. inbound, err := s.GetInbound(id)
  668. if err != nil {
  669. return false, nil, err
  670. }
  671. if err := db.Transaction(func(tx *gorm.DB) error {
  672. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  673. return err
  674. }
  675. if err := tx.Save(traffic).Error; err != nil {
  676. return err
  677. }
  678. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  679. return err
  680. }
  681. if err := tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  682. return err
  683. }
  684. if err := tx.Model(model.Inbound{}).
  685. Where("id = ?", id).
  686. Update("last_traffic_reset_time", now).Error; err != nil {
  687. return err
  688. }
  689. if reenableNodeID != nil {
  690. return (&NodeService{}).MarkNodeDirtyTx(tx, *reenableNodeID)
  691. }
  692. if inbound != nil && inbound.NodeID != nil {
  693. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  694. }
  695. return nil
  696. }); err != nil {
  697. return false, nil, err
  698. }
  699. if reenablePlan != nil {
  700. rt, err := s.runtimeFor(&reenablePlan.inbound)
  701. if err != nil {
  702. needRestart = true
  703. } else if err := rt.AddUser(context.Background(), &reenablePlan.inbound, reenablePlan.client); err != nil {
  704. logger.Debug("Error in enabling client on", rt.Name(), ":", err)
  705. needRestart = true
  706. } else {
  707. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  708. }
  709. }
  710. return needRestart, inbound, nil
  711. }
  712. func (s *InboundService) ResetAllTraffics() error {
  713. err := submitTrafficWrite(func() error {
  714. return s.resetAllTrafficsLocked()
  715. })
  716. if err == nil {
  717. s.propagateResetAllTrafficsToNodes()
  718. s.resetAllMtprotoQuotas()
  719. }
  720. return err
  721. }
  722. func (s *InboundService) resetAllTrafficsLocked() error {
  723. db := database.GetDB()
  724. now := time.Now().UnixMilli()
  725. return db.Model(model.Inbound{}).
  726. Where("user_id > ?", 0).
  727. Updates(map[string]any{
  728. "up": 0,
  729. "down": 0,
  730. "last_traffic_reset_time": now,
  731. }).Error
  732. }
  733. // propagateResetAllTrafficsToNodes tells every node to zero its own counters.
  734. // Kept OUT of the traffic-writer transaction: each remote call can block up to
  735. // remoteHTTPTimeout, and holding the single serial writer across N such calls
  736. // stalls traffic accounting and drops the deltas of every concurrent poll.
  737. func (s *InboundService) propagateResetAllTrafficsToNodes() {
  738. nodes, err := (&NodeService{}).GetAll()
  739. if err != nil {
  740. return
  741. }
  742. for _, node := range nodes {
  743. if rt, err := runtime.GetManager().RuntimeFor(&node.Id); err == nil {
  744. if e := rt.ResetAllTraffics(context.Background()); e != nil {
  745. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  746. }
  747. }
  748. }
  749. }
  750. func (s *InboundService) ResetInboundTraffic(id int) error {
  751. var inbound *model.Inbound
  752. if err := submitTrafficWrite(func() error {
  753. db := database.GetDB()
  754. if err := db.Model(model.Inbound{}).
  755. Where("id = ?", id).
  756. Updates(map[string]any{"up": 0, "down": 0}).Error; err != nil {
  757. return err
  758. }
  759. var err error
  760. inbound, err = s.GetInbound(id)
  761. if err != nil {
  762. return err
  763. }
  764. return nil
  765. }); err != nil {
  766. return err
  767. }
  768. if inbound != nil && inbound.NodeID != nil {
  769. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  770. if e := rt.ResetInboundTraffic(context.Background(), inbound); e != nil {
  771. logger.Warning("ResetInboundTraffic: remote propagation to", rt.Name(), "failed:", e)
  772. }
  773. } else {
  774. logger.Warning("ResetInboundTraffic: runtime lookup failed:", rterr)
  775. }
  776. }
  777. return nil
  778. }
  779. func (s *InboundService) DelDepletedClients(id int) (err error) {
  780. db := database.GetDB()
  781. var deletedInbounds []model.Inbound
  782. err = db.Transaction(func(tx *gorm.DB) error {
  783. // Collect depleted emails globally — a shared-email row owned by one
  784. // inbound depletes every sibling that lists the email.
  785. now := time.Now().Unix() * 1000
  786. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  787. var depletedRows []xray.ClientTraffic
  788. if err := tx.Model(xray.ClientTraffic{}).
  789. Where(depletedClause, now).
  790. Find(&depletedRows).Error; err != nil {
  791. return err
  792. }
  793. if len(depletedRows) == 0 {
  794. return nil
  795. }
  796. depletedEmails := make(map[string]struct{}, len(depletedRows))
  797. for _, r := range depletedRows {
  798. if r.Email == "" {
  799. continue
  800. }
  801. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  802. }
  803. if len(depletedEmails) == 0 {
  804. return nil
  805. }
  806. var inbounds []*model.Inbound
  807. inboundQuery := tx.Model(model.Inbound{})
  808. if id >= 0 {
  809. inboundQuery = inboundQuery.Where("id = ?", id)
  810. }
  811. if err := inboundQuery.Find(&inbounds).Error; err != nil {
  812. return err
  813. }
  814. for _, inbound := range inbounds {
  815. var settings map[string]any
  816. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  817. return err
  818. }
  819. rawClients, ok := settings["clients"].([]any)
  820. if !ok {
  821. continue
  822. }
  823. newClients := make([]any, 0, len(rawClients))
  824. removed := 0
  825. for _, client := range rawClients {
  826. c, ok := client.(map[string]any)
  827. if !ok {
  828. newClients = append(newClients, client)
  829. continue
  830. }
  831. email, _ := c["email"].(string)
  832. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  833. removed++
  834. continue
  835. }
  836. newClients = append(newClients, client)
  837. }
  838. if removed == 0 {
  839. continue
  840. }
  841. if len(newClients) == 0 {
  842. deletedInbounds = append(deletedInbounds, *inbound)
  843. if err := s.clientService.DetachInbound(tx, inbound.Id); err != nil {
  844. return err
  845. }
  846. if err := tx.Where("inbound_id = ?", inbound.Id).Delete(&model.Host{}).Error; err != nil {
  847. return err
  848. }
  849. if err := tx.Delete(model.Inbound{}, inbound.Id).Error; err != nil {
  850. return err
  851. }
  852. if inbound.NodeID != nil {
  853. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); err != nil {
  854. return err
  855. }
  856. }
  857. continue
  858. }
  859. settings["clients"] = newClients
  860. ns, mErr := json.MarshalIndent(settings, "", " ")
  861. if mErr != nil {
  862. return mErr
  863. }
  864. inbound.Settings = string(ns)
  865. if err := tx.Save(inbound).Error; err != nil {
  866. return err
  867. }
  868. survivingClients, gcErr := s.GetClients(inbound)
  869. if gcErr != nil {
  870. return gcErr
  871. }
  872. if err := s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  873. return err
  874. }
  875. if inbound.NodeID != nil {
  876. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); err != nil {
  877. return err
  878. }
  879. }
  880. }
  881. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  882. // no out-of-scope inbound still references the email.
  883. if id < 0 {
  884. return tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  885. }
  886. emails := make([]string, 0, len(depletedEmails))
  887. for e := range depletedEmails {
  888. emails = append(emails, e)
  889. }
  890. var stillReferenced []string
  891. emailExpr := database.JSONFieldText("client.value", "email")
  892. stillQuery := fmt.Sprintf(
  893. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  894. emailExpr,
  895. database.JSONClientsFromInbound(),
  896. emailExpr,
  897. )
  898. if err := tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  899. return err
  900. }
  901. stillSet := make(map[string]struct{}, len(stillReferenced))
  902. for _, e := range stillReferenced {
  903. stillSet[e] = struct{}{}
  904. }
  905. toDelete := make([]string, 0, len(emails))
  906. for _, e := range emails {
  907. if _, kept := stillSet[e]; !kept {
  908. toDelete = append(toDelete, e)
  909. }
  910. }
  911. if len(toDelete) > 0 {
  912. if err := tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  913. return err
  914. }
  915. }
  916. return nil
  917. })
  918. if err != nil {
  919. return err
  920. }
  921. for i := range deletedInbounds {
  922. inbound := &deletedInbounds[i]
  923. if rt, rtErr := s.runtimeFor(inbound); rtErr != nil {
  924. logger.Warning("DelDepletedClients: runtime lookup failed after commit:", rtErr)
  925. } else if rtErr = rt.DelInbound(context.Background(), inbound); rtErr != nil && !xray.IsMissingHandlerErr(rtErr) {
  926. logger.Warning("DelDepletedClients: runtime cleanup failed after commit:", rtErr)
  927. }
  928. if inbound.Tag != "" {
  929. if _, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(inbound.Tag); syncErr != nil {
  930. logger.Warning("DelDepletedClients: routing cleanup failed after commit:", syncErr)
  931. }
  932. }
  933. }
  934. return nil
  935. }
  936. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  937. db := database.GetDB()
  938. idQuery := fmt.Sprintf(
  939. "SELECT DISTINCT inbounds.id %s WHERE %s = ?",
  940. database.JSONClientsFromInbound(),
  941. database.JSONFieldText("client.value", "tgId"),
  942. )
  943. var inboundIds []int
  944. if err := db.Raw(idQuery, strconv.FormatInt(tgId, 10)).Scan(&inboundIds).Error; err != nil {
  945. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  946. return nil, err
  947. }
  948. var inbounds []*model.Inbound
  949. if len(inboundIds) > 0 {
  950. err := db.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error
  951. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  952. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  953. return nil, err
  954. }
  955. }
  956. var emails []string
  957. for _, inbound := range inbounds {
  958. clients, err := s.GetClients(inbound)
  959. if err != nil {
  960. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  961. continue
  962. }
  963. for _, client := range clients {
  964. if client.TgID == tgId {
  965. emails = append(emails, client.Email)
  966. }
  967. }
  968. }
  969. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  970. // account owns thousands of clients across inbounds.
  971. uniqEmails := uniqueNonEmptyStrings(emails)
  972. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  973. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  974. var page []*xray.ClientTraffic
  975. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  976. if errors.Is(err, gorm.ErrRecordNotFound) {
  977. continue
  978. }
  979. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  980. return nil, err
  981. }
  982. traffics = append(traffics, page...)
  983. }
  984. if len(traffics) == 0 {
  985. logger.Warning("No ClientTraffic records found for emails:", emails)
  986. return nil, nil
  987. }
  988. // Populate UUID and other client data for each traffic record
  989. for i := range traffics {
  990. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  991. traffics[i].Enable = client.Enable
  992. traffics[i].UUID = client.ID
  993. traffics[i].SubId = client.SubID
  994. }
  995. }
  996. return traffics, nil
  997. }
  998. // BumpClientsLastOnline sets client_traffics.last_online to now for the given
  999. // emails. Used in online-API mode for clients that hold a live connection but
  1000. // moved no bytes this poll — the traffic path (addClientTraffic) only bumps
  1001. // last_online on a non-zero delta, so idle-but-connected clients would
  1002. // otherwise show a stale "last online" while being reported online.
  1003. func (s *InboundService) BumpClientsLastOnline(emails []string) error {
  1004. uniq := uniqueNonEmptyStrings(emails)
  1005. if len(uniq) == 0 {
  1006. return nil
  1007. }
  1008. now := time.Now().UnixMilli()
  1009. return submitTrafficWrite(func() error {
  1010. db := database.GetDB()
  1011. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  1012. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("last_online", now).Error; err != nil {
  1013. return err
  1014. }
  1015. }
  1016. return nil
  1017. })
  1018. }
  1019. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  1020. uniq := uniqueNonEmptyStrings(emails)
  1021. if len(uniq) == 0 {
  1022. return nil, nil
  1023. }
  1024. db := database.GetDB()
  1025. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  1026. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  1027. var page []*xray.ClientTraffic
  1028. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  1029. return nil, err
  1030. }
  1031. traffics = append(traffics, page...)
  1032. }
  1033. overlayGlobalTraffic(db, traffics)
  1034. return traffics, nil
  1035. }
  1036. // GetAllClientTraffics returns the full set of client_traffics rows so the
  1037. // websocket broadcasters can ship a complete snapshot every cycle. A pure
  1038. // delta path silently dropped the per-client section whenever no client moved
  1039. // bytes in the cycle or a node sync failed, leaving client rows in the UI
  1040. // stuck at stale numbers — so small installs broadcast this snapshot, and only
  1041. // above the traffic job's snapshot threshold (where the marshaled snapshot
  1042. // would exceed the hub's payload cap and be dropped wholesale) does the job
  1043. // fall back to active-row deltas.
  1044. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  1045. db := database.GetDB()
  1046. var traffics []*xray.ClientTraffic
  1047. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  1048. return nil, err
  1049. }
  1050. overlayGlobalTraffic(db, traffics)
  1051. return traffics, nil
  1052. }
  1053. func (s *InboundService) CountClientTraffics() (int64, error) {
  1054. db := database.GetDB()
  1055. var count int64
  1056. err := db.Model(xray.ClientTraffic{}).Count(&count).Error
  1057. return count, err
  1058. }
  1059. type InboundTrafficSummary struct {
  1060. Id int `json:"id"`
  1061. Up int64 `json:"up"`
  1062. Down int64 `json:"down"`
  1063. Total int64 `json:"total"`
  1064. Enable bool `json:"enable"`
  1065. }
  1066. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  1067. db := database.GetDB()
  1068. var summaries []InboundTrafficSummary
  1069. if err := db.Model(&model.Inbound{}).
  1070. Select("id, up, down, total, enable").
  1071. Find(&summaries).Error; err != nil {
  1072. return nil, err
  1073. }
  1074. return summaries, nil
  1075. }
  1076. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1077. db := database.GetDB()
  1078. var traffics []*xray.ClientTraffic
  1079. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error; err != nil {
  1080. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1081. return nil, err
  1082. }
  1083. if len(traffics) == 0 {
  1084. return nil, nil
  1085. }
  1086. overlayGlobalTraffic(db, traffics)
  1087. t := traffics[0]
  1088. if rec, rErr := s.clientService.GetRecordByEmail(db, email); rErr == nil && rec != nil {
  1089. c := rec.ToClient()
  1090. t.UUID = c.ID
  1091. t.SubId = c.SubID
  1092. return t, nil
  1093. }
  1094. t2, client, err := s.GetClientByEmail(email)
  1095. if err != nil {
  1096. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1097. return nil, err
  1098. }
  1099. if t2 != nil && client != nil {
  1100. t2.UUID = client.ID
  1101. t2.SubId = client.SubID
  1102. return t2, nil
  1103. }
  1104. return nil, nil
  1105. }
  1106. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  1107. return submitTrafficWrite(func() error {
  1108. db := database.GetDB()
  1109. err := db.Model(xray.ClientTraffic{}).
  1110. Where("email = ?", email).
  1111. Updates(map[string]any{
  1112. "up": upload,
  1113. "down": download,
  1114. }).Error
  1115. if err != nil {
  1116. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  1117. }
  1118. return err
  1119. })
  1120. }
  1121. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1122. db := database.GetDB()
  1123. inbound := &model.Inbound{}
  1124. traffic = &xray.ClientTraffic{}
  1125. // Search for inbound settings that contain the query
  1126. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1127. if err != nil {
  1128. if errors.Is(err, gorm.ErrRecordNotFound) {
  1129. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1130. return nil, err
  1131. }
  1132. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1133. return nil, err
  1134. }
  1135. traffic.InboundId = inbound.Id
  1136. clients, err := ParseInboundSettingsClients(inbound.Settings)
  1137. if err != nil {
  1138. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1139. return nil, err
  1140. }
  1141. for _, client := range clients {
  1142. if (client.ID == query || client.Password == query) && client.Email != "" {
  1143. traffic.Email = client.Email
  1144. break
  1145. }
  1146. }
  1147. if traffic.Email == "" {
  1148. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1149. return nil, gorm.ErrRecordNotFound
  1150. }
  1151. // Retrieve ClientTraffic based on the found email
  1152. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1153. if err != nil {
  1154. if errors.Is(err, gorm.ErrRecordNotFound) {
  1155. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1156. return nil, err
  1157. }
  1158. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1159. return nil, err
  1160. }
  1161. return traffic, nil
  1162. }