1
0

client_paging.go 25 KB

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