1
0

client_paging.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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. LimitHwid int `json:"limitHwid"`
  24. Reset int `json:"reset"`
  25. ResetDay int `json:"resetDay"`
  26. ResetMax int `json:"resetMax"`
  27. Group string `json:"group,omitempty"`
  28. Comment string `json:"comment,omitempty"`
  29. InboundIds []int `json:"inboundIds"`
  30. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  31. CreatedAt int64 `json:"createdAt"`
  32. UpdatedAt int64 `json:"updatedAt"`
  33. }
  34. // ClientPageParams are the query params accepted by /panel/api/clients/list/paged.
  35. // All fields are optional — the empty value means "no filter" / defaults.
  36. //
  37. // Filter / Protocol / Inbound accept either a single value or a comma-separated
  38. // list; matching is OR within a field and AND across fields. The numeric range
  39. // fields treat 0 as "unset" on the lower bound and 0 (or negative) as
  40. // "unbounded" on the upper bound.
  41. type ClientPageParams struct {
  42. Page int `form:"page"`
  43. PageSize int `form:"pageSize"`
  44. Search string `form:"search"`
  45. Filter string `form:"filter"`
  46. Protocol string `form:"protocol"`
  47. Inbound string `form:"inbound"`
  48. Sort string `form:"sort"`
  49. Order string `form:"order"`
  50. ExpiryFrom int64 `form:"expiryFrom"`
  51. ExpiryTo int64 `form:"expiryTo"`
  52. UsageFrom int64 `form:"usageFrom"`
  53. UsageTo int64 `form:"usageTo"`
  54. AutoRenew string `form:"autoRenew"`
  55. HasTgID string `form:"hasTgId"`
  56. HasComment string `form:"hasComment"`
  57. Group string `form:"group"`
  58. }
  59. // ClientPageResponse is the shape returned by ListPaged. `Total` is the
  60. // row count in the DB; `Filtered` is the count after Search/Filter/Protocol
  61. // were applied, before pagination. The page contains at most PageSize items.
  62. // Summary is computed across the full DB row set so dashboard counters
  63. // on the clients page stay stable as the user paginates/filters.
  64. type ClientPageResponse struct {
  65. Items []ClientSlim `json:"items"`
  66. Total int `json:"total"`
  67. Filtered int `json:"filtered"`
  68. Page int `json:"page"`
  69. PageSize int `json:"pageSize"`
  70. Summary ClientsSummary `json:"summary"`
  71. Groups []string `json:"groups"`
  72. }
  73. // ClientsSummary collects per-bucket counts plus the matching email lists so
  74. // the clients page can render the dashboard stat cards and their hover
  75. // popovers without shipping the full client array. The counters are exact;
  76. // the lists stop at clientSummaryEmailCap entries and only back the popovers.
  77. type ClientsSummary struct {
  78. Total int `json:"total"`
  79. Active int `json:"active"`
  80. OnlineCount int `json:"onlineCount"`
  81. DepletedCount int `json:"depletedCount"`
  82. ExpiringCount int `json:"expiringCount"`
  83. DeactiveCount int `json:"deactiveCount"`
  84. Online []string `json:"online"`
  85. Depleted []string `json:"depleted"`
  86. Expiring []string `json:"expiring"`
  87. Deactive []string `json:"deactive"`
  88. }
  89. const (
  90. clientPageDefaultSize = 25
  91. clientPageMaxSize = 200
  92. // clientSummaryEmailCap bounds each bucket's email list. Shipping every
  93. // matching email made the response — and the Zod validation the page runs
  94. // over it — grow with the client count on a request that repeats every 5s,
  95. // and left the hover popover rendering thousands of rows.
  96. clientSummaryEmailCap = 200
  97. // sqlNeverSentinel sorts "never expires" / "unlimited quota" clients last,
  98. // matching the sentinel the in-memory comparator used.
  99. sqlNeverSentinel = "4611686018427387903"
  100. // sqlClientEnabled tolerates a NULL enable column, which GORM scans as
  101. // false: without the COALESCE such a row would match neither the enabled
  102. // nor the disabled branch of any predicate.
  103. sqlClientEnabled = "COALESCE(c.enable, FALSE)"
  104. )
  105. const clientSearchCond = `(LOWER(c.email) LIKE ? ESCAPE '\'
  106. OR LOWER(COALESCE(c.sub_id, '')) LIKE ? ESCAPE '\'
  107. OR LOWER(COALESCE(c.comment, '')) LIKE ? ESCAPE '\'
  108. OR LOWER(COALESCE(c.uuid, '')) LIKE ? ESCAPE '\'
  109. OR LOWER(COALESCE(c.password, '')) LIKE ? ESCAPE '\'
  110. OR LOWER(COALESCE(c.auth, '')) LIKE ? ESCAPE '\'
  111. OR (COALESCE(c.tg_id, 0) <> 0 AND CAST(c.tg_id AS TEXT) LIKE ? ESCAPE '\'))`
  112. // clientQuery builds the statements behind the clients page: a clients row
  113. // joined to its traffic counters, plus the expressions every bucket predicate
  114. // shares. Filtering, sorting, paging and the summary all run in the database.
  115. // Loading every client (with attachments and traffic) into Go and doing it in
  116. // memory cost ~200ms per request at 20k clients on a page that polls every
  117. // 5 seconds, which is what made the table feel stuck on large panels.
  118. type clientQuery struct {
  119. db *gorm.DB
  120. joins []clientQueryJoin
  121. usedExpr string
  122. nowMs int64
  123. expireDiffMs int64
  124. trafficDiffBytes int64
  125. }
  126. type clientQueryJoin struct {
  127. sql string
  128. args []any
  129. }
  130. func newClientQuery(db *gorm.DB, nowMs, expireDiffMs, trafficDiffBytes int64) clientQuery {
  131. q := clientQuery{
  132. db: db,
  133. nowMs: nowMs,
  134. expireDiffMs: expireDiffMs,
  135. trafficDiffBytes: trafficDiffBytes,
  136. joins: []clientQueryJoin{{sql: "LEFT JOIN client_traffics ct ON ct.email = c.email"}},
  137. usedExpr: "(COALESCE(ct.up, 0) + COALESCE(ct.down, 0))",
  138. }
  139. freshSince := globalTrafficFreshSince()
  140. var probe int64
  141. err := db.Model(&model.ClientGlobalTraffic{}).
  142. Where("updated_at >= ?", freshSince).
  143. Limit(1).Count(&probe).Error
  144. if err != nil || probe == 0 {
  145. return q
  146. }
  147. // A master still pushes cross-panel usage here, so the predicates have to
  148. // see the same raised counters overlayGlobalTraffic applies on read.
  149. q.joins = append(q.joins, clientQueryJoin{
  150. sql: "LEFT JOIN (SELECT email, MAX(up) AS up, MAX(down) AS down FROM client_global_traffics" +
  151. " WHERE updated_at >= ? GROUP BY email) g ON g.email = c.email",
  152. args: []any{freshSince},
  153. })
  154. q.usedExpr = "(CASE WHEN COALESCE(g.up, 0) > COALESCE(ct.up, 0) THEN COALESCE(g.up, 0) ELSE COALESCE(ct.up, 0) END" +
  155. " + CASE WHEN COALESCE(g.down, 0) > COALESCE(ct.down, 0) THEN COALESCE(g.down, 0) ELSE COALESCE(ct.down, 0) END)"
  156. return q
  157. }
  158. func (q clientQuery) from() *gorm.DB {
  159. tx := q.db.Table("clients AS c")
  160. for _, j := range q.joins {
  161. tx = tx.Joins(j.sql, j.args...)
  162. }
  163. return tx
  164. }
  165. func (q clientQuery) depletedExpr() string {
  166. return "((c.total_gb > 0 AND " + q.usedExpr + " >= c.total_gb)" +
  167. " OR (c.expiry_time > 0 AND c.expiry_time <= " + sqlInt(q.nowMs) + "))"
  168. }
  169. func (q clientQuery) nearDepletionExpr() string {
  170. return "((c.expiry_time > 0 AND c.expiry_time - " + sqlInt(q.nowMs) + " < " + sqlInt(q.expireDiffMs) + ")" +
  171. " OR (c.total_gb > 0 AND c.total_gb - " + q.usedExpr + " < " + sqlInt(q.trafficDiffBytes) + "))"
  172. }
  173. func (q clientQuery) expiringExpr() string {
  174. return "(" + sqlClientEnabled + " AND NOT " + q.depletedExpr() + " AND " + q.nearDepletionExpr() + ")"
  175. }
  176. func (q clientQuery) activeExpr() string {
  177. return "(" + sqlClientEnabled + " AND NOT " + q.depletedExpr() + " AND NOT " + q.nearDepletionExpr() + ")"
  178. }
  179. // summaryDeactiveExpr is narrower than the "deactive" bucket filter: a disabled
  180. // client that also ran out counts once, under depleted, so the stat cards add
  181. // up to the client total.
  182. func (q clientQuery) summaryDeactiveExpr() 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)")
  230. case "off":
  231. where("(COALESCE(c.reset, 0) <= 0 AND COALESCE(c.reset_day, 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, "("+sqlClientEnabled+" AND NOT "+q.depletedExpr()+")")
  257. case "deactive":
  258. conds = append(conds, "(NOT "+sqlClientEnabled+")")
  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.summaryDeactiveExpr() + " 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.summaryDeactiveExpr(), 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. ResetMax: c.ResetMax,
  566. Group: c.Group,
  567. Comment: c.Comment,
  568. InboundIds: c.InboundIds,
  569. Traffic: c.Traffic,
  570. CreatedAt: c.CreatedAt,
  571. UpdatedAt: c.UpdatedAt,
  572. }
  573. }
  574. // escapeLikeLiteral neutralises LIKE wildcards so searching for "a_b" keeps
  575. // matching literally, the way strings.Contains did.
  576. func escapeLikeLiteral(s string) string {
  577. return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
  578. }
  579. // emailInCond renders an IN over a possibly large email set, split so no single
  580. // IN list outgrows the drivers' bind-parameter ceiling.
  581. func emailInCond(column string, emails []string) (string, []any) {
  582. if len(emails) == 0 {
  583. return "1 = 0", nil
  584. }
  585. chunks := chunkStrings(emails, sqlInChunk)
  586. parts := make([]string, 0, len(chunks))
  587. args := make([]any, 0, len(chunks))
  588. for _, chunk := range chunks {
  589. parts = append(parts, column+" IN ?")
  590. args = append(args, chunk)
  591. }
  592. return "(" + strings.Join(parts, " OR ") + ")", args
  593. }
  594. // parseCSVStrings splits a comma-separated list, trims/lower-cases each item,
  595. // and drops blanks. Returns nil when the input has no usable entries — the
  596. // caller can then skip the predicate entirely.
  597. func parseCSVStrings(raw string) []string {
  598. if raw == "" {
  599. return nil
  600. }
  601. parts := strings.Split(raw, ",")
  602. out := make([]string, 0, len(parts))
  603. for _, p := range parts {
  604. s := strings.ToLower(strings.TrimSpace(p))
  605. if s != "" {
  606. out = append(out, s)
  607. }
  608. }
  609. if len(out) == 0 {
  610. return nil
  611. }
  612. return out
  613. }
  614. // parseCSVInts is parseCSVStrings for positive integer IDs; non-numeric or
  615. // non-positive entries are silently dropped.
  616. func parseCSVInts(raw string) []int {
  617. if raw == "" {
  618. return nil
  619. }
  620. parts := strings.Split(raw, ",")
  621. out := make([]int, 0, len(parts))
  622. for _, p := range parts {
  623. s := strings.TrimSpace(p)
  624. if s == "" {
  625. continue
  626. }
  627. if n, err := strconv.Atoi(s); err == nil && n > 0 {
  628. out = append(out, n)
  629. }
  630. }
  631. if len(out) == 0 {
  632. return nil
  633. }
  634. return out
  635. }