inbound_traffic.go 41 KB

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