client_paging.go 22 KB

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