1
0

client_paging.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. package service
  2. import (
  3. "sort"
  4. "strconv"
  5. "strings"
  6. "time"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  9. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  10. "gorm.io/gorm"
  11. )
  12. // ClientSlim is the row-shape used by the clients page. It drops fields the
  13. // table never reads (UUID, password, auth, flow, security, reverse, tgId)
  14. // so the list payload stays compact even when the panel manages thousands
  15. // of clients. Modals that need the full record still call /get/:email.
  16. type ClientSlim struct {
  17. Email string `json:"email" example:"[email protected]"`
  18. SubID string `json:"subId" example:"abcd1234"`
  19. Enable bool `json:"enable" example:"true"`
  20. TotalGB int64 `json:"totalGB" example:"53687091200"`
  21. ExpiryTime int64 `json:"expiryTime" example:"1735689600000"`
  22. LimitIP int `json:"limitIp" example:"0"`
  23. LimitHwid int `json:"limitHwid" example:"0"`
  24. Reset int `json:"reset" example:"0"`
  25. ResetDay int `json:"resetDay" example:"0"`
  26. ResetWeekday int `json:"resetWeekday" example:"0"`
  27. ResetMax int `json:"resetMax" example:"0"`
  28. Group string `json:"group,omitempty" example:"staff"`
  29. Comment string `json:"comment,omitempty" example:"Primary device"`
  30. InboundIds []int `json:"inboundIds" example:"[3,5]"`
  31. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  32. CreatedAt int64 `json:"createdAt" example:"1735000000000"`
  33. UpdatedAt int64 `json:"updatedAt" example:"1735100000000"`
  34. }
  35. // ClientPageParams are the query params accepted by /panel/api/clients/list/paged.
  36. // All fields are optional — the empty value means "no filter" / defaults.
  37. //
  38. // Filter / Protocol / Inbound accept either a single value or a comma-separated
  39. // list; matching is OR within a field and AND across fields. The numeric range
  40. // fields treat 0 as "unset" on the lower bound and 0 (or negative) as
  41. // "unbounded" on the upper bound.
  42. type ClientPageParams struct {
  43. Page int `form:"page"`
  44. PageSize int `form:"pageSize"`
  45. Search string `form:"search"`
  46. Filter string `form:"filter"`
  47. Protocol string `form:"protocol"`
  48. Inbound string `form:"inbound"`
  49. Sort string `form:"sort"`
  50. Order string `form:"order"`
  51. ExpiryFrom int64 `form:"expiryFrom"`
  52. ExpiryTo int64 `form:"expiryTo"`
  53. UsageFrom int64 `form:"usageFrom"`
  54. UsageTo int64 `form:"usageTo"`
  55. AutoRenew string `form:"autoRenew"`
  56. HasTgID string `form:"hasTgId"`
  57. HasComment string `form:"hasComment"`
  58. Group string `form:"group"`
  59. }
  60. // ClientPageResponse is the shape returned by ListPaged. `Total` is the
  61. // row count in the DB; `Filtered` is the count after Search/Filter/Protocol
  62. // were applied, before pagination. The page contains at most PageSize items.
  63. // Summary is computed across the full DB row set so dashboard counters
  64. // on the clients page stay stable as the user paginates/filters.
  65. type ClientPageResponse struct {
  66. Items []ClientSlim `json:"items"`
  67. Total int `json:"total" example:"2000"`
  68. Filtered int `json:"filtered" example:"47"`
  69. Page int `json:"page" example:"1"`
  70. PageSize int `json:"pageSize" example:"25"`
  71. Summary ClientsSummary `json:"summary"`
  72. Groups []string `json:"groups" example:"[\"staff\",\"trial\"]"`
  73. }
  74. // ClientsSummary collects per-bucket counts plus the matching email lists so
  75. // the clients page can render the dashboard stat cards and their hover
  76. // popovers without shipping the full client array. The counters are exact;
  77. // the lists stop at clientSummaryEmailCap entries and only back the popovers.
  78. type ClientsSummary struct {
  79. Total int `json:"total" example:"2000"`
  80. Active int `json:"active" example:"1850"`
  81. OnlineCount int `json:"onlineCount" example:"1"`
  82. DepletedCount int `json:"depletedCount" example:"0"`
  83. ExpiringCount int `json:"expiringCount" example:"0"`
  84. DeactiveCount int `json:"deactiveCount" example:"150"`
  85. Online []string `json:"online" example:"[\"[email protected]\"]"`
  86. Depleted []string `json:"depleted" example:"[]"`
  87. Expiring []string `json:"expiring" example:"[]"`
  88. Deactive []string `json:"deactive" example:"[\"[email protected]\"]"`
  89. }
  90. const (
  91. clientPageDefaultSize = 25
  92. clientPageMaxSize = 200
  93. // clientSummaryEmailCap bounds each bucket's email list. Shipping every
  94. // matching email made the response — and the Zod validation the page runs
  95. // over it — grow with the client count on a request that repeats every 5s,
  96. // and left the hover popover rendering thousands of rows.
  97. clientSummaryEmailCap = 200
  98. // sqlNeverSentinel sorts "never expires" / "unlimited quota" clients last,
  99. // matching the sentinel the in-memory comparator used.
  100. sqlNeverSentinel = "4611686018427387903"
  101. // sqlClientEnabled tolerates a NULL enable column, which GORM scans as
  102. // false: without the COALESCE such a row would match neither the enabled
  103. // nor the disabled branch of any predicate.
  104. sqlClientEnabled = "COALESCE(c.enable, FALSE)"
  105. )
  106. const clientSearchCond = `(LOWER(c.email) LIKE ? ESCAPE '\'
  107. OR LOWER(COALESCE(c.sub_id, '')) LIKE ? ESCAPE '\'
  108. OR LOWER(COALESCE(c.comment, '')) LIKE ? ESCAPE '\'
  109. OR LOWER(COALESCE(c.uuid, '')) LIKE ? ESCAPE '\'
  110. OR LOWER(COALESCE(c.password, '')) LIKE ? ESCAPE '\'
  111. OR LOWER(COALESCE(c.auth, '')) LIKE ? ESCAPE '\'
  112. OR (COALESCE(c.tg_id, 0) <> 0 AND CAST(c.tg_id AS TEXT) LIKE ? ESCAPE '\'))`
  113. // clientQuery builds the statements behind the clients page: a clients row
  114. // joined to its traffic counters, plus the expressions every bucket predicate
  115. // shares. Filtering, sorting, paging and the summary all run in the database.
  116. // Loading every client (with attachments and traffic) into Go and doing it in
  117. // memory cost ~200ms per request at 20k clients on a page that polls every
  118. // 5 seconds, which is what made the table feel stuck on large panels.
  119. type clientQuery struct {
  120. db *gorm.DB
  121. joins []clientQueryJoin
  122. usedExpr string
  123. nowMs int64
  124. expireDiffMs int64
  125. trafficDiffBytes int64
  126. }
  127. type clientQueryJoin struct {
  128. sql string
  129. args []any
  130. }
  131. func newClientQuery(db *gorm.DB, nowMs, expireDiffMs, trafficDiffBytes int64) clientQuery {
  132. q := clientQuery{
  133. db: db,
  134. nowMs: nowMs,
  135. expireDiffMs: expireDiffMs,
  136. trafficDiffBytes: trafficDiffBytes,
  137. joins: []clientQueryJoin{{sql: "LEFT JOIN client_traffics ct ON ct.email = c.email"}},
  138. usedExpr: "(COALESCE(ct.up, 0) + COALESCE(ct.down, 0))",
  139. }
  140. freshSince := globalTrafficFreshSince()
  141. var probe int64
  142. err := db.Model(&model.ClientGlobalTraffic{}).
  143. Where("updated_at >= ?", freshSince).
  144. Limit(1).Count(&probe).Error
  145. if err != nil || probe == 0 {
  146. return q
  147. }
  148. // A master still pushes cross-panel usage here, so the predicates have to
  149. // see the same raised counters overlayGlobalTraffic applies on read.
  150. q.joins = append(q.joins, clientQueryJoin{
  151. sql: "LEFT JOIN (SELECT email, MAX(up) AS up, MAX(down) AS down FROM client_global_traffics" +
  152. " WHERE updated_at >= ? GROUP BY email) g ON g.email = c.email",
  153. args: []any{freshSince},
  154. })
  155. q.usedExpr = "(CASE WHEN COALESCE(g.up, 0) > COALESCE(ct.up, 0) THEN COALESCE(g.up, 0) ELSE COALESCE(ct.up, 0) END" +
  156. " + CASE WHEN COALESCE(g.down, 0) > COALESCE(ct.down, 0) THEN COALESCE(g.down, 0) ELSE COALESCE(ct.down, 0) END)"
  157. return q
  158. }
  159. func (q clientQuery) from() *gorm.DB {
  160. tx := q.db.Table("clients AS c")
  161. for _, j := range q.joins {
  162. tx = tx.Joins(j.sql, j.args...)
  163. }
  164. return tx
  165. }
  166. func (q clientQuery) depletedExpr() string {
  167. return "((c.total_gb > 0 AND " + q.usedExpr + " >= c.total_gb)" +
  168. " OR (c.expiry_time > 0 AND c.expiry_time <= " + sqlInt(q.nowMs) + "))"
  169. }
  170. func (q clientQuery) nearDepletionExpr() string {
  171. return "((c.expiry_time > 0 AND c.expiry_time - " + sqlInt(q.nowMs) + " < " + sqlInt(q.expireDiffMs) + ")" +
  172. " OR (c.total_gb > 0 AND c.total_gb - " + q.usedExpr + " < " + sqlInt(q.trafficDiffBytes) + "))"
  173. }
  174. func (q clientQuery) expiringExpr() string {
  175. return "(" + sqlClientEnabled + " AND NOT " + q.depletedExpr() + " AND " + q.nearDepletionExpr() + ")"
  176. }
  177. func (q clientQuery) activeExpr() string {
  178. return "(" + sqlClientEnabled + " AND NOT " + q.depletedExpr() + " AND NOT " + q.nearDepletionExpr() + ")"
  179. }
  180. // deactiveExpr leaves a disabled client that also ran out to depleted, so the
  181. // stat cards add up to the total and each card's filter lists what it counts.
  182. func (q clientQuery) deactiveExpr() string {
  183. return "(NOT " + sqlClientEnabled + " AND NOT " + q.depletedExpr() + ")"
  184. }
  185. // applyParams narrows tx by every predicate the clients page sends. Matching is
  186. // OR within a field and AND across fields, mirroring the query-param contract.
  187. // The second return says whether anything narrowed the set, so an unfiltered
  188. // request can reuse the total count instead of scanning for it again.
  189. func (q clientQuery) applyParams(tx *gorm.DB, params ClientPageParams, onlines []string) (*gorm.DB, bool) {
  190. narrowed := false
  191. where := func(cond string, args ...any) {
  192. narrowed = true
  193. tx = tx.Where(cond, args...)
  194. }
  195. if needle := strings.ToLower(strings.TrimSpace(params.Search)); needle != "" {
  196. pattern := "%" + escapeLikeLiteral(needle) + "%"
  197. where(clientSearchCond, pattern, pattern, pattern, pattern, pattern, pattern, pattern)
  198. }
  199. if protocols := parseCSVStrings(params.Protocol); len(protocols) > 0 {
  200. where("EXISTS (SELECT 1 FROM client_inbounds ci JOIN inbounds ib ON ib.id = ci.inbound_id"+
  201. " WHERE ci.client_id = c.id AND LOWER(ib.protocol) IN ?)", protocols)
  202. }
  203. if inboundIds := parseCSVInts(params.Inbound); len(inboundIds) > 0 {
  204. where("EXISTS (SELECT 1 FROM client_inbounds ci WHERE ci.client_id = c.id AND ci.inbound_id IN ?)", inboundIds)
  205. }
  206. if buckets := parseCSVStrings(params.Filter); len(buckets) > 0 {
  207. cond, args := q.bucketCond(buckets, onlines)
  208. where(cond, args...)
  209. }
  210. if params.ExpiryFrom > 0 || params.ExpiryTo > 0 {
  211. // 0 means "never expires" and a negative value is the delayed-start
  212. // sentinel; both sit outside any bounded range.
  213. where("c.expiry_time > 0")
  214. if params.ExpiryFrom > 0 {
  215. where("c.expiry_time >= ?", params.ExpiryFrom)
  216. }
  217. if params.ExpiryTo > 0 {
  218. where("c.expiry_time <= ?", params.ExpiryTo)
  219. }
  220. }
  221. if params.UsageFrom > 0 {
  222. where(q.usedExpr+" >= ?", params.UsageFrom)
  223. }
  224. if params.UsageTo > 0 {
  225. where(q.usedExpr+" <= ?", params.UsageTo)
  226. }
  227. switch strings.ToLower(strings.TrimSpace(params.AutoRenew)) {
  228. case "on":
  229. where("(COALESCE(c.reset, 0) > 0 OR COALESCE(c.reset_day, 0) > 0 OR COALESCE(c.reset_weekday, 0) > 0)")
  230. case "off":
  231. where("(COALESCE(c.reset, 0) <= 0 AND COALESCE(c.reset_day, 0) <= 0 AND COALESCE(c.reset_weekday, 0) <= 0)")
  232. }
  233. switch strings.ToLower(strings.TrimSpace(params.HasTgID)) {
  234. case "yes":
  235. where("COALESCE(c.tg_id, 0) <> 0")
  236. case "no":
  237. where("COALESCE(c.tg_id, 0) = 0")
  238. }
  239. switch strings.ToLower(strings.TrimSpace(params.HasComment)) {
  240. case "yes":
  241. where("TRIM(COALESCE(c.comment, '')) <> ''")
  242. case "no":
  243. where("TRIM(COALESCE(c.comment, '')) = ''")
  244. }
  245. if groups := parseCSVStrings(params.Group); len(groups) > 0 {
  246. where("LOWER(TRIM(COALESCE(c.group_name, ''))) IN ?", groups)
  247. }
  248. return tx, narrowed
  249. }
  250. func (q clientQuery) bucketCond(buckets, onlines []string) (string, []any) {
  251. conds := make([]string, 0, len(buckets))
  252. args := make([]any, 0, len(buckets))
  253. for _, b := range buckets {
  254. switch b {
  255. case "active":
  256. conds = append(conds, q.activeExpr())
  257. case "deactive":
  258. conds = append(conds, q.deactiveExpr())
  259. case "depleted":
  260. conds = append(conds, q.depletedExpr())
  261. case "expiring":
  262. conds = append(conds, q.expiringExpr())
  263. case "online":
  264. cond, inArgs := emailInCond("c.email", onlines)
  265. conds = append(conds, "("+sqlClientEnabled+" AND "+cond+")")
  266. args = append(args, inArgs...)
  267. default:
  268. // An unrecognised bucket name matched every client before the
  269. // predicates moved into SQL; keep that so a stale saved filter
  270. // cannot silently empty the table.
  271. conds = append(conds, "(1 = 1)")
  272. }
  273. }
  274. return "(" + strings.Join(conds, " OR ") + ")", args
  275. }
  276. func (q clientQuery) applyOrder(tx *gorm.DB, sortKey, order string) *gorm.DB {
  277. dir := " ASC"
  278. if order == "descend" {
  279. dir = " DESC"
  280. }
  281. // createdAt / updatedAt / lastOnline broke ties on the client id inside the
  282. // comparator, so reversing the sort reversed the tiebreak with it. The
  283. // other keys leaned on a stable sort over an id-ordered slice instead.
  284. tieDir := " ASC"
  285. var expr string
  286. switch sortKey {
  287. case "enable":
  288. expr = sqlClientEnabled
  289. case "email":
  290. expr = "LOWER(c.email)"
  291. case "inboundIds":
  292. expr = "(SELECT COUNT(*) FROM client_inbounds ci WHERE ci.client_id = c.id)"
  293. case "traffic":
  294. expr = q.usedExpr
  295. case "remaining":
  296. expr = "CASE WHEN c.total_gb > 0 THEN c.total_gb - " + q.usedExpr + " ELSE " + sqlNeverSentinel + " END"
  297. case "expiryTime":
  298. expr = "CASE WHEN c.expiry_time > 0 THEN c.expiry_time ELSE " + sqlNeverSentinel + " END"
  299. case "createdAt":
  300. expr, tieDir = "c.created_at", dir
  301. case "updatedAt":
  302. expr, tieDir = "c.updated_at", dir
  303. case "lastOnline":
  304. expr, tieDir = "COALESCE(ct.last_online, 0)", dir
  305. default:
  306. return tx.Order("c.id ASC")
  307. }
  308. return tx.Order(expr + dir + ", c.id" + tieDir)
  309. }
  310. // ListPaged returns one page of clients together with the counts the clients
  311. // page header needs. Every predicate runs in SQL, so the cost tracks the page
  312. // size rather than the number of clients on the panel.
  313. func (s *ClientService) ListPaged(inboundSvc *InboundService, settingSvc *SettingService, params ClientPageParams) (*ClientPageResponse, error) {
  314. db := database.GetDB()
  315. pageSize := params.PageSize
  316. if pageSize <= 0 {
  317. pageSize = clientPageDefaultSize
  318. }
  319. if pageSize > clientPageMaxSize {
  320. pageSize = clientPageMaxSize
  321. }
  322. page := params.Page
  323. if page <= 0 {
  324. page = 1
  325. }
  326. var expireDiffMs, trafficDiffBytes int64
  327. if settingSvc != nil {
  328. if v, err := settingSvc.GetExpireDiff(); err == nil {
  329. expireDiffMs = int64(v) * 86400000
  330. }
  331. if v, err := settingSvc.GetTrafficDiff(); err == nil {
  332. trafficDiffBytes = int64(v) * 1073741824
  333. }
  334. }
  335. onlines := inboundSvc.GetOnlineClients()
  336. q := newClientQuery(db, time.Now().UnixMilli(), expireDiffMs, trafficDiffBytes)
  337. var total int64
  338. if err := db.Model(&model.ClientRecord{}).Count(&total).Error; err != nil {
  339. return nil, err
  340. }
  341. summary, err := q.summary(onlines, int(total))
  342. if err != nil {
  343. return nil, err
  344. }
  345. filtered := total
  346. if scoped, narrowed := q.applyParams(q.from(), params, onlines); narrowed {
  347. if err := scoped.Count(&filtered).Error; err != nil {
  348. return nil, err
  349. }
  350. }
  351. items := []ClientSlim{}
  352. offset := (page - 1) * pageSize
  353. if int64(offset) < filtered {
  354. items, err = q.pageRows(params, onlines, offset, pageSize)
  355. if err != nil {
  356. return nil, err
  357. }
  358. }
  359. groups, err := s.listGroupNames()
  360. if err != nil {
  361. return nil, err
  362. }
  363. return &ClientPageResponse{
  364. Items: items,
  365. Total: int(total),
  366. Filtered: int(filtered),
  367. Page: page,
  368. PageSize: pageSize,
  369. Summary: summary,
  370. Groups: groups,
  371. }, nil
  372. }
  373. // pageRows resolves the requested page to client ids, then loads the records,
  374. // attachments and traffic for those ids only. A page never exceeds
  375. // clientPageMaxSize rows, which stays under sqlInChunk, so the follow-up IN
  376. // lists need no chunking.
  377. func (q clientQuery) pageRows(params ClientPageParams, onlines []string, offset, limit int) ([]ClientSlim, error) {
  378. tx, _ := q.applyParams(q.from(), params, onlines)
  379. var ids []int
  380. if err := q.applyOrder(tx, params.Sort, params.Order).
  381. Offset(offset).Limit(limit).
  382. Pluck("c.id", &ids).Error; err != nil {
  383. return nil, err
  384. }
  385. if len(ids) == 0 {
  386. return []ClientSlim{}, nil
  387. }
  388. var records []model.ClientRecord
  389. if err := q.db.Where("id IN ?", ids).Find(&records).Error; err != nil {
  390. return nil, err
  391. }
  392. byId := make(map[int]*model.ClientRecord, len(records))
  393. emails := make([]string, 0, len(records))
  394. for i := range records {
  395. byId[records[i].Id] = &records[i]
  396. if records[i].Email != "" {
  397. emails = append(emails, records[i].Email)
  398. }
  399. }
  400. var links []model.ClientInbound
  401. if err := q.db.Where("client_id IN ?", ids).Order("inbound_id ASC").Find(&links).Error; err != nil {
  402. return nil, err
  403. }
  404. attachments := make(map[int][]int, len(ids))
  405. for _, l := range links {
  406. attachments[l.ClientId] = append(attachments[l.ClientId], l.InboundId)
  407. }
  408. trafficByEmail := make(map[string]*xray.ClientTraffic, len(emails))
  409. if len(emails) > 0 {
  410. var stats []xray.ClientTraffic
  411. if err := q.db.Where("email IN ?", emails).Find(&stats).Error; err != nil {
  412. return nil, err
  413. }
  414. overlayGlobalTrafficValues(q.db, stats)
  415. for i := range stats {
  416. trafficByEmail[stats[i].Email] = &stats[i]
  417. }
  418. }
  419. items := make([]ClientSlim, 0, len(ids))
  420. for _, id := range ids {
  421. rec := byId[id]
  422. if rec == nil {
  423. continue
  424. }
  425. items = append(items, toClientSlim(ClientWithAttachments{
  426. ClientRecord: *rec,
  427. InboundIds: attachments[rec.Id],
  428. Traffic: trafficByEmail[rec.Email],
  429. }))
  430. }
  431. return items, nil
  432. }
  433. func (q clientQuery) summary(onlines []string, total int) (ClientsSummary, error) {
  434. s := ClientsSummary{
  435. Total: total,
  436. Online: []string{},
  437. Depleted: []string{},
  438. Expiring: []string{},
  439. Deactive: []string{},
  440. }
  441. var counts struct {
  442. Active int64
  443. Depleted int64
  444. Expiring int64
  445. Deactive int64
  446. }
  447. // SUM over an empty table yields NULL, which not every driver scans into an
  448. // int; COALESCE keeps a panel with no clients from erroring out.
  449. if err := q.from().Select(
  450. "COALESCE(SUM(CASE WHEN " + q.activeExpr() + " THEN 1 ELSE 0 END), 0) AS active," +
  451. " COALESCE(SUM(CASE WHEN " + q.depletedExpr() + " THEN 1 ELSE 0 END), 0) AS depleted," +
  452. " COALESCE(SUM(CASE WHEN " + q.expiringExpr() + " THEN 1 ELSE 0 END), 0) AS expiring," +
  453. " COALESCE(SUM(CASE WHEN " + q.deactiveExpr() + " THEN 1 ELSE 0 END), 0) AS deactive",
  454. ).Scan(&counts).Error; err != nil {
  455. return s, err
  456. }
  457. s.Active = int(counts.Active)
  458. s.DepletedCount = int(counts.Depleted)
  459. s.ExpiringCount = int(counts.Expiring)
  460. s.DeactiveCount = int(counts.Deactive)
  461. buckets := []struct {
  462. cond string
  463. count int
  464. out *[]string
  465. }{
  466. {q.depletedExpr(), s.DepletedCount, &s.Depleted},
  467. {q.expiringExpr(), s.ExpiringCount, &s.Expiring},
  468. {q.deactiveExpr(), s.DeactiveCount, &s.Deactive},
  469. }
  470. for _, b := range buckets {
  471. // The counter already says the bucket is empty, so skip the scan that
  472. // would look for emails it cannot find.
  473. if b.count == 0 {
  474. continue
  475. }
  476. var emails []string
  477. if err := q.from().Where(b.cond).
  478. Order("c.id ASC").Limit(clientSummaryEmailCap).
  479. Pluck("c.email", &emails).Error; err != nil {
  480. return s, err
  481. }
  482. if len(emails) > 0 {
  483. *b.out = emails
  484. }
  485. }
  486. online, onlineCount, err := q.onlineEmails(onlines)
  487. if err != nil {
  488. return s, err
  489. }
  490. s.Online = online
  491. s.OnlineCount = onlineCount
  492. return s, nil
  493. }
  494. // onlineEmails intersects the emails xray reports as connected with the enabled
  495. // clients this panel stores. The online set lives in memory and is bounded by
  496. // live connections, so it drives the query rather than a scan of every client.
  497. func (q clientQuery) onlineEmails(onlines []string) ([]string, int, error) {
  498. matched := []string{}
  499. count := 0
  500. for _, batch := range chunkStrings(onlines, sqlInChunk) {
  501. var page []string
  502. if err := q.db.Model(&model.ClientRecord{}).
  503. Where("COALESCE(enable, FALSE) = TRUE AND email IN ?", batch).
  504. Order("id ASC").
  505. Pluck("email", &page).Error; err != nil {
  506. return nil, 0, err
  507. }
  508. count += len(page)
  509. if room := clientSummaryEmailCap - len(matched); room > 0 {
  510. matched = append(matched, page[:min(room, len(page))]...)
  511. }
  512. }
  513. return matched, count, nil
  514. }
  515. // listGroupNames returns the group names the clients page offers as filters:
  516. // the stored groups plus any name a client still carries. ListGroups also sums
  517. // per-client traffic per group, which this page never reads and which costs a
  518. // full join over client_traffics on every poll.
  519. func (s *ClientService) listGroupNames() ([]string, error) {
  520. db := database.GetDB()
  521. var stored []string
  522. if err := db.Model(&model.ClientGroup{}).Pluck("name", &stored).Error; err != nil {
  523. return nil, err
  524. }
  525. var used []string
  526. if err := db.Model(&model.ClientRecord{}).
  527. Where("group_name <> ''").
  528. Distinct().
  529. Pluck("group_name", &used).Error; err != nil {
  530. return nil, err
  531. }
  532. seen := make(map[string]struct{}, len(stored)+len(used))
  533. out := make([]string, 0, len(stored)+len(used))
  534. for _, list := range [][]string{stored, used} {
  535. for _, name := range list {
  536. if name == "" {
  537. continue
  538. }
  539. if _, dup := seen[name]; dup {
  540. continue
  541. }
  542. seen[name] = struct{}{}
  543. out = append(out, name)
  544. }
  545. }
  546. sort.Slice(out, func(i, j int) bool {
  547. return strings.ToLower(out[i]) < strings.ToLower(out[j])
  548. })
  549. return out, nil
  550. }
  551. func sqlInt(v int64) string {
  552. return strconv.FormatInt(v, 10)
  553. }
  554. func toClientSlim(c ClientWithAttachments) ClientSlim {
  555. return ClientSlim{
  556. Email: c.Email,
  557. SubID: c.SubID,
  558. Enable: c.Enable,
  559. TotalGB: c.TotalGB,
  560. ExpiryTime: c.ExpiryTime,
  561. LimitIP: c.LimitIP,
  562. LimitHwid: c.LimitHwid,
  563. Reset: c.Reset,
  564. ResetDay: c.ResetDay,
  565. ResetWeekday: c.ResetWeekday,
  566. ResetMax: c.ResetMax,
  567. Group: c.Group,
  568. Comment: c.Comment,
  569. InboundIds: c.InboundIds,
  570. Traffic: c.Traffic,
  571. CreatedAt: c.CreatedAt,
  572. UpdatedAt: c.UpdatedAt,
  573. }
  574. }
  575. // escapeLikeLiteral neutralises LIKE wildcards so searching for "a_b" keeps
  576. // matching literally, the way strings.Contains did.
  577. func escapeLikeLiteral(s string) string {
  578. return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
  579. }
  580. // emailInCond renders an IN over a possibly large email set, split so no single
  581. // IN list outgrows the drivers' bind-parameter ceiling.
  582. func emailInCond(column string, emails []string) (string, []any) {
  583. if len(emails) == 0 {
  584. return "1 = 0", nil
  585. }
  586. chunks := chunkStrings(emails, sqlInChunk)
  587. parts := make([]string, 0, len(chunks))
  588. args := make([]any, 0, len(chunks))
  589. for _, chunk := range chunks {
  590. parts = append(parts, column+" IN ?")
  591. args = append(args, chunk)
  592. }
  593. return "(" + strings.Join(parts, " OR ") + ")", args
  594. }
  595. // parseCSVStrings splits a comma-separated list, trims/lower-cases each item,
  596. // and drops blanks. Returns nil when the input has no usable entries — the
  597. // caller can then skip the predicate entirely.
  598. func parseCSVStrings(raw string) []string {
  599. if raw == "" {
  600. return nil
  601. }
  602. parts := strings.Split(raw, ",")
  603. out := make([]string, 0, len(parts))
  604. for _, p := range parts {
  605. s := strings.ToLower(strings.TrimSpace(p))
  606. if s != "" {
  607. out = append(out, s)
  608. }
  609. }
  610. if len(out) == 0 {
  611. return nil
  612. }
  613. return out
  614. }
  615. // parseCSVInts is parseCSVStrings for positive integer IDs; non-numeric or
  616. // non-positive entries are silently dropped.
  617. func parseCSVInts(raw string) []int {
  618. if raw == "" {
  619. return nil
  620. }
  621. parts := strings.Split(raw, ",")
  622. out := make([]int, 0, len(parts))
  623. for _, p := range parts {
  624. s := strings.TrimSpace(p)
  625. if s == "" {
  626. continue
  627. }
  628. if n, err := strconv.Atoi(s); err == nil && n > 0 {
  629. out = append(out, n)
  630. }
  631. }
  632. if len(out) == 0 {
  633. return nil
  634. }
  635. return out
  636. }