inbound_traffic.go 40 KB

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