1
0

inbound_traffic.go 39 KB

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