1
0

client_paging.go 22 KB

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