Files
mirror-3x-ui/internal/web/service/client_group_scope.go
T
Hamed Sanaei 1ac11c7783 fix(groups): page client dialogs and submit server-resolved scopes
Keep group client tables and bulk requests bounded with paged queries, frozen selections, and a streamed subscription export. Reuse existing bulk mutations and preserve the explicit-email contracts.
2026-12-01 11:36:45 +03:30

351 lines
10 KiB
Go

package service
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"hash"
"strconv"
"strings"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
const (
groupClientPageSize = 100
maxGroupSelectionExclusions = 1000
)
var errGroupSelectionStale = errors.New("client group selection changed. Reopen the action or select clients again.")
type GroupClientPageParams struct {
Group string `form:"group"`
Mode string `form:"mode"`
Page int `form:"page"`
Search string `form:"search"`
Freeze bool `form:"freeze"`
ScopeSearch string `form:"scopeSearch"`
MaxID *int `form:"maxId"`
}
type GroupClientRow struct {
ID int `json:"id" example:"1"`
Email string `json:"email" example:"alice"`
Comment string `json:"comment" example:"Example client"`
Group string `json:"group" example:"staff"`
Enable bool `json:"enable" example:"true"`
SubID string `json:"subId" example:"example-sub-id"`
InScope bool `json:"inScope" example:"true"`
}
type GroupClientPage struct {
Items []GroupClientRow `json:"items"`
Total int64 `json:"total" example:"120"`
ScopeToken string `json:"scopeToken,omitempty"`
MaxID int `json:"maxId,omitempty"`
}
type GroupClientSelection struct {
Mode string `json:"mode" example:"allMatching"`
ClientIDs []int `json:"clientIds,omitempty"`
ExcludedClientIDs []int `json:"excludedClientIds,omitempty"`
ScopeToken string `json:"scopeToken,omitempty"`
Search string `json:"search,omitempty"`
}
type groupClientScope struct {
name string
mode string
}
func (scope groupClientScope) candidates(db *gorm.DB) *gorm.DB {
q := attachCandidates(db, 0)
if scope.mode == "add" {
return q.Where("COALESCE(c.group_name, '') <> ?", scope.name)
}
q = q.Where("c.group_name = ?", scope.name)
if scope.mode == "links" {
q = q.Where("c.sub_id <> ''")
}
return q
}
func findGroupClientScope(db *gorm.DB, group, mode string) (groupClientScope, error) {
group = strings.TrimSpace(group)
if group == "" || (mode != "add" && mode != "remove" && mode != "links") {
return groupClientScope{}, fmt.Errorf("invalid client group scope")
}
if mode != "add" {
return groupClientScope{name: group, mode: mode}, nil
}
var stored model.ClientGroup
err := db.Where("LOWER(name) = LOWER(?)", group).Order("id").Take(&stored).Error
if err == nil {
return groupClientScope{name: stored.Name, mode: mode}, nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return groupClientScope{}, err
}
var derived model.ClientRecord
err = db.Table("clients").Where("group_name = ?", group).Select("id").Take(&derived).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return groupClientScope{}, fmt.Errorf("client group no longer exists")
}
return groupClientScope{name: group, mode: mode}, err
}
func groupSearchCond(needle string) (string, []any) {
parts, args := clientTextSearch(caseVariants(needle), []string{"c.email", "c.comment", "c.group_name"})
return "(" + strings.Join(parts, " OR ") + ")", args
}
func groupClientSearch(q *gorm.DB, search string) *gorm.DB {
if needle := strings.TrimSpace(search); needle != "" {
filter, args := groupSearchCond(needle)
return q.Where(filter, args...)
}
return q
}
func (scope groupClientScope) digest(search string) hash.Hash {
h := sha256.New()
for _, part := range []string{"group-client-scope", scope.mode, scope.name, strings.TrimSpace(search)} {
writeClientScopeID(h, len(part))
_, _ = h.Write([]byte(part))
}
return h
}
func groupClientToken(h hash.Hash, maxID int) string {
writeClientScopeID(h, maxID)
return strconv.Itoa(maxID) + "." + hex.EncodeToString(h.Sum(nil))
}
func (s *ClientService) ListGroupClients(ctx context.Context, p GroupClientPageParams) (*GroupClientPage, error) {
if p.Page < 0 || p.Page > 1_000_000 || len(p.Search) > 1024 || len(p.ScopeSearch) > 1024 ||
(p.MaxID != nil && *p.MaxID < 1) || (p.Freeze && p.Mode == "links") {
return nil, fmt.Errorf("invalid client group page")
}
db := database.GetDB().WithContext(ctx)
scope, err := findGroupClientScope(db, p.Group, p.Mode)
if err != nil {
return nil, err
}
page := &GroupClientPage{Items: []GroupClientRow{}}
q := groupClientSearch(scope.candidates(db), p.Search)
if p.Freeze {
rows, err := q.Select("c.id").Order("c.id").Rows()
if err != nil {
return nil, err
}
defer rows.Close()
h := scope.digest(p.Search)
for rows.Next() {
if err := rows.Scan(&page.MaxID); err != nil {
return nil, err
}
writeClientScopeID(h, page.MaxID)
page.Total++
}
if err := rows.Err(); err != nil {
return nil, err
}
page.ScopeToken = groupClientToken(h, page.MaxID)
return page, nil
}
if err := q.Session(&gorm.Session{}).Count(&page.Total).Error; err != nil {
return nil, err
}
const fields = "c.id, c.email, COALESCE(c.comment, '') AS comment, COALESCE(c.group_name, '') AS \"group\", COALESCE(c.enable, false) AS enable, COALESCE(c.sub_id, '') AS sub_id, "
inScope := "true"
var args []any
if p.MaxID != nil {
inScope = "(c.id <= ?)"
args = append(args, *p.MaxID)
if needle := strings.TrimSpace(p.ScopeSearch); needle != "" {
filter, filterArgs := groupSearchCond(needle)
inScope = "(" + inScope + " AND COALESCE(" + filter + ", false))"
args = append(args, filterArgs...)
}
}
order := "c.id"
if p.Mode == "links" {
order = "c.email, c.id"
}
err = q.Select(fields+inScope+" AS in_scope", args...).Order(order).
Offset(max(0, p.Page-1) * groupClientPageSize).Limit(groupClientPageSize).Scan(&page.Items).Error
return page, err
}
func (scope groupClientScope) selectionEmails(db *gorm.DB, selection GroupClientSelection) ([]string, error) {
q := scope.candidates(db)
switch selection.Mode {
case "explicit":
if len(selection.ClientIDs) == 0 || len(selection.ClientIDs) > 50_000 || selection.ScopeToken != "" ||
len(selection.ExcludedClientIDs) != 0 || selection.Search != "" {
return nil, fmt.Errorf("invalid explicit client group selection")
}
ids := uniqueInts(selection.ClientIDs)
var emails []string
for _, chunk := range chunkInts(ids, sqlInChunk) {
var part []string
if err := q.Session(&gorm.Session{}).Where("c.id IN ?", chunk).Pluck("c.email", &part).Error; err != nil {
return nil, err
}
if len(part) != len(chunk) {
return nil, errGroupSelectionStale
}
emails = append(emails, part...)
}
return emails, nil
case "allMatching":
return scope.frozenEmails(q, selection)
default:
return nil, fmt.Errorf("invalid client group selection mode")
}
}
func (scope groupClientScope) frozenEmails(q *gorm.DB, selection GroupClientSelection) ([]string, error) {
cutoff, digest, ok := strings.Cut(selection.ScopeToken, ".")
maxID, parseErr := strconv.Atoi(cutoff)
if !ok || parseErr != nil || maxID < 0 || len(digest) != sha256.Size*2 || len(selection.ClientIDs) != 0 ||
len(selection.ExcludedClientIDs) > maxGroupSelectionExclusions || len(selection.Search) > 1024 {
return nil, fmt.Errorf("invalid frozen client group selection")
}
excluded := make(map[int]struct{}, len(selection.ExcludedClientIDs))
for _, id := range selection.ExcludedClientIDs {
excluded[id] = struct{}{}
}
rows, err := groupClientSearch(q, selection.Search).Where("c.id <= ?", maxID).
Select("c.id, c.email").Order("c.id").Rows()
if err != nil {
return nil, err
}
defer rows.Close()
h := scope.digest(selection.Search)
var emails []string
for rows.Next() {
var id int
var email string
if err := rows.Scan(&id, &email); err != nil {
return nil, err
}
writeClientScopeID(h, id)
if _, skip := excluded[id]; skip {
delete(excluded, id)
} else {
emails = append(emails, email)
}
}
if err := rows.Err(); err != nil {
return nil, err
}
if len(excluded) != 0 || groupClientToken(h, maxID) != selection.ScopeToken {
return nil, errGroupSelectionStale
}
return emails, nil
}
func (s *ClientService) GroupOperationEmails(ctx context.Context, group, token string) ([]string, error) {
db := database.GetDB().WithContext(ctx)
scope, err := findGroupClientScope(db, group, "remove")
if err != nil {
return nil, err
}
if token != "" {
return scope.selectionEmails(db, GroupClientSelection{Mode: "allMatching", ScopeToken: token})
}
var emails []string
err = scope.candidates(db).Order("c.id").Pluck("c.email", &emails).Error
return emails, err
}
func (s *ClientService) ChangeGroupSelection(ctx context.Context, group, mode string, selection GroupClientSelection) (int, error) {
if mode != "add" && mode != "remove" {
return 0, fmt.Errorf("invalid client group action")
}
var affected int
err := runSerializedTx(func(tx *gorm.DB) error {
tx = tx.WithContext(ctx)
scope, err := findGroupClientScope(tx, group, mode)
if err != nil {
return err
}
emails, err := scope.selectionEmails(tx, selection)
if err != nil {
return err
}
target := ""
if mode == "add" && len(emails) != 0 {
record, err := database.EnsureClientGroup(tx, scope.name)
if err != nil {
return err
}
target = record.Name
}
affected, err = applyClientGroup(tx, emails, target)
return err
})
return affected, err
}
func (s *ClientService) AddInboundToGroup(ctx context.Context, inboundID int, group string) (int, error) {
if inboundID <= 0 {
return 0, fmt.Errorf("invalid source inbound ID")
}
var affected int
err := runSerializedTx(func(tx *gorm.DB) error {
tx = tx.WithContext(ctx)
var inbound model.Inbound
if err := tx.Select("id").First(&inbound, inboundID).Error; err != nil {
return err
}
var emails []string
if err := attachCandidates(tx, inbound.Id).Pluck("c.email", &emails).Error; err != nil {
return err
}
if len(emails) == 0 {
return nil
}
target, err := database.EnsureClientGroup(tx, group)
if err != nil {
return err
}
if target == nil {
return fmt.Errorf("group name is required")
}
affected, err = applyClientGroup(tx, emails, target.Name)
return err
})
return affected, err
}
func (s *ClientService) WalkGroupSubscriptionClients(ctx context.Context, group string, visit func(email, subID string) error) error {
db := database.GetDB().WithContext(ctx)
scope, err := findGroupClientScope(db, group, "links")
if err != nil {
return err
}
rows, err := scope.candidates(db).Select("c.email, c.sub_id").Order("c.email, c.id").Rows()
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var email, subID string
if err := rows.Scan(&email, &subID); err != nil {
return err
}
if err := visit(email, subID); err != nil {
return err
}
}
return rows.Err()
}