inbound_traffic.go 40 KB

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