mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
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.
This commit is contained in:
@@ -399,6 +399,8 @@ func (a *ClientController) resetAllTraffics(c *gin.Context) {
|
||||
}
|
||||
|
||||
type bulkAdjustRequest struct {
|
||||
Group string `json:"group"`
|
||||
ScopeToken string `json:"scopeToken"`
|
||||
Emails []string `json:"emails"`
|
||||
AddDays int `json:"addDays"`
|
||||
AddBytes int64 `json:"addBytes"`
|
||||
@@ -414,22 +416,30 @@ func (a *ClientController) bulkAdjust(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
emails, err := a.resolveGroupBulkEmails(c, req.Emails, req.Group, req.ScopeToken)
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
var result service.BulkAdjustResult
|
||||
var needRestart bool
|
||||
var err error
|
||||
if req.ExternalLinks != nil {
|
||||
if req.AddDays != 0 || req.AddBytes != 0 || req.Flow != "" || req.LimitHwid != nil || req.AdTag != "" {
|
||||
jsonMsg(c, "append external links separately from other adjustments", errors.New("externalLinks cannot be combined with other adjustments"))
|
||||
return
|
||||
}
|
||||
result, err = a.clientService.BulkAppendExternalLinks(req.Emails, req.ExternalLinks)
|
||||
result, err = a.clientService.BulkAppendExternalLinks(emails, req.ExternalLinks)
|
||||
} else {
|
||||
result, needRestart, err = a.clientService.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag)
|
||||
result, needRestart, err = a.clientService.BulkAdjust(&a.inboundService, emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag)
|
||||
}
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
if req.Group != "" && len(result.Skipped) > 0 {
|
||||
result.SkippedCount = len(result.Skipped)
|
||||
result.Skipped = result.Skipped[:min(len(result.Skipped), 20)]
|
||||
}
|
||||
jsonObj(c, result, nil)
|
||||
if needRestart {
|
||||
a.xrayService.SetToNeedRestart()
|
||||
@@ -438,10 +448,22 @@ func (a *ClientController) bulkAdjust(c *gin.Context) {
|
||||
}
|
||||
|
||||
type bulkDeleteRequest struct {
|
||||
Group string `json:"group"`
|
||||
ScopeToken string `json:"scopeToken"`
|
||||
Emails []string `json:"emails"`
|
||||
KeepTraffic bool `json:"keepTraffic"`
|
||||
}
|
||||
|
||||
func (a *ClientController) resolveGroupBulkEmails(c *gin.Context, emails []string, group, scopeToken string) ([]string, error) {
|
||||
if group == "" && scopeToken == "" {
|
||||
return emails, nil
|
||||
}
|
||||
if len(emails) != 0 || strings.TrimSpace(group) == "" {
|
||||
return nil, errors.New("use either emails or a group scope")
|
||||
}
|
||||
return a.clientService.GroupOperationEmails(c.Request.Context(), group, scopeToken)
|
||||
}
|
||||
|
||||
type bulkAttachRequest struct {
|
||||
Emails []string `json:"emails"`
|
||||
InboundIds []int `json:"inboundIds"`
|
||||
@@ -503,11 +525,20 @@ func (a *ClientController) bulkDelete(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic)
|
||||
emails, err := a.resolveGroupBulkEmails(c, req.Emails, req.Group, req.ScopeToken)
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, emails, req.KeepTraffic)
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
if req.Group != "" && len(result.Skipped) > 0 {
|
||||
result.SkippedCount = len(result.Skipped)
|
||||
result.Skipped = result.Skipped[:min(len(result.Skipped), 20)]
|
||||
}
|
||||
jsonObj(c, result, nil)
|
||||
if needRestart {
|
||||
a.xrayService.SetToNeedRestart()
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
|
||||
@@ -10,8 +14,9 @@ import (
|
||||
)
|
||||
|
||||
type GroupController struct {
|
||||
clientService service.ClientService
|
||||
xrayService service.XrayService
|
||||
clientService service.ClientService
|
||||
xrayService service.XrayService
|
||||
settingService service.SettingService
|
||||
}
|
||||
|
||||
func NewGroupController(g *gin.RouterGroup) *GroupController {
|
||||
@@ -22,6 +27,8 @@ func NewGroupController(g *gin.RouterGroup) *GroupController {
|
||||
|
||||
func (a *GroupController) initRouter(g *gin.RouterGroup) {
|
||||
g.GET("/groups", a.list)
|
||||
g.GET("/groups/clientPage", a.clientPage)
|
||||
g.GET("/groups/subLinks/export", a.exportSubLinks)
|
||||
g.GET("/groups/:name/emails", a.emails)
|
||||
g.POST("/groups/create", a.create)
|
||||
g.POST("/groups/rename", a.rename)
|
||||
@@ -158,8 +165,10 @@ func (a *GroupController) resetTraffic(c *gin.Context) {
|
||||
}
|
||||
|
||||
type bulkAddToGroupRequest struct {
|
||||
Emails []string `json:"emails"`
|
||||
Group string `json:"group"`
|
||||
Emails []string `json:"emails"`
|
||||
Group string `json:"group"`
|
||||
InboundID *int `json:"inboundId"`
|
||||
Selection *service.GroupClientSelection `json:"selection"`
|
||||
}
|
||||
|
||||
func (a *GroupController) bulkAdd(c *gin.Context) {
|
||||
@@ -172,7 +181,21 @@ func (a *GroupController) bulkAdd(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("group name is required"))
|
||||
return
|
||||
}
|
||||
affected, err := a.clientService.AddToGroup(req.Emails, req.Group)
|
||||
if (req.InboundID != nil && (*req.InboundID <= 0 || req.Selection != nil || len(req.Emails) != 0)) ||
|
||||
(req.Selection != nil && len(req.Emails) != 0) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("use one client scope"))
|
||||
return
|
||||
}
|
||||
var affected int
|
||||
var err error
|
||||
switch {
|
||||
case req.InboundID != nil:
|
||||
affected, err = a.clientService.AddInboundToGroup(c.Request.Context(), *req.InboundID, req.Group)
|
||||
case req.Selection != nil:
|
||||
affected, err = a.clientService.ChangeGroupSelection(c.Request.Context(), req.Group, "add", *req.Selection)
|
||||
default:
|
||||
affected, err = a.clientService.AddToGroup(req.Emails, req.Group)
|
||||
}
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
@@ -182,7 +205,9 @@ func (a *GroupController) bulkAdd(c *gin.Context) {
|
||||
}
|
||||
|
||||
type bulkRemoveFromGroupRequest struct {
|
||||
Emails []string `json:"emails"`
|
||||
Emails []string `json:"emails"`
|
||||
Group string `json:"group"`
|
||||
Selection *service.GroupClientSelection `json:"selection"`
|
||||
}
|
||||
|
||||
func (a *GroupController) bulkRemove(c *gin.Context) {
|
||||
@@ -191,12 +216,79 @@ func (a *GroupController) bulkRemove(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
affected, err := a.clientService.RemoveFromGroup(req.Emails)
|
||||
if (req.Selection != nil && len(req.Emails) != 0) || (req.Selection == nil && req.Group != "") {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("use one client scope"))
|
||||
return
|
||||
}
|
||||
var affected int
|
||||
var err error
|
||||
if req.Selection != nil {
|
||||
affected, err = a.clientService.ChangeGroupSelection(c.Request.Context(), req.Group, "remove", *req.Selection)
|
||||
} else {
|
||||
affected, err = a.clientService.RemoveFromGroup(req.Emails)
|
||||
}
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
jsonObj(c, gin.H{"affected": affected}, nil)
|
||||
a.xrayService.SetToNeedRestart()
|
||||
notifyClientsChanged()
|
||||
if affected > 0 {
|
||||
a.xrayService.SetToNeedRestart()
|
||||
notifyClientsChanged()
|
||||
}
|
||||
}
|
||||
|
||||
func (a *GroupController) clientPage(c *gin.Context) {
|
||||
var params service.GroupClientPageParams
|
||||
if err := c.ShouldBindQuery(¶ms); err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
page, err := a.clientService.ListGroupClients(c.Request.Context(), params)
|
||||
jsonObj(c, page, err)
|
||||
}
|
||||
|
||||
func (a *GroupController) exportSubLinks(c *gin.Context) {
|
||||
links, err := a.settingService.GetPanelSubscriptionLinks(c.Request.Host)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong"))
|
||||
return
|
||||
}
|
||||
group := strings.TrimSpace(c.Query("group"))
|
||||
if !links.Enable || links.URI == "" || group == "" {
|
||||
c.String(http.StatusBadRequest, "group and enabled subscriptions are required")
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "text/plain; charset=utf-8")
|
||||
c.Header("Content-Disposition", `attachment; filename="sub-links.txt"`)
|
||||
c.Header("Cache-Control", "no-store")
|
||||
out := bufio.NewWriter(c.Writer)
|
||||
first := true
|
||||
err = a.clientService.WalkGroupSubscriptionClients(c.Request.Context(), group, func(email, subID string) error {
|
||||
if !first {
|
||||
if err := out.WriteByte('\n'); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
first = false
|
||||
if _, err := fmt.Fprintf(out, "%s\t%s%s", email, links.URI, subID); err != nil {
|
||||
return err
|
||||
}
|
||||
if links.JSONEnable && links.JSONURI != "" {
|
||||
_, err := fmt.Fprintf(out, "\t%s%s", links.JSONURI, subID)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err == nil {
|
||||
err = out.Flush()
|
||||
}
|
||||
if err != nil && c.Request.Context().Err() == nil {
|
||||
logger.Warning("group subscription export failed:", err)
|
||||
if !c.Writer.Written() {
|
||||
c.Header("Content-Disposition", "")
|
||||
c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
const groupAPI = "/panel/api/clients"
|
||||
|
||||
func groupTestRouter(t *testing.T) *gin.Engine {
|
||||
t.Helper()
|
||||
cleanup, err := testpg.IsolatePackage("group_client_http")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
router := gin.New()
|
||||
routes := router.Group(groupAPI)
|
||||
NewGroupController(routes)
|
||||
NewClientController(routes)
|
||||
return router
|
||||
}
|
||||
|
||||
func groupAPIRequest(router *gin.Engine, method, route, body string) *httptest.ResponseRecorder {
|
||||
out := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, groupAPI+route, strings.NewReader(body))
|
||||
if method == http.MethodPost {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
router.ServeHTTP(out, req)
|
||||
return out
|
||||
}
|
||||
|
||||
func groupPage(t *testing.T, router *gin.Engine, query string) service.GroupClientPage {
|
||||
t.Helper()
|
||||
out := groupAPIRequest(router, http.MethodGet, "/groups/clientPage?"+query, "")
|
||||
var result struct {
|
||||
Success bool
|
||||
Obj service.GroupClientPage
|
||||
}
|
||||
if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success {
|
||||
t.Fatalf("group page %q returned %s (%v)", query, out.Body, err)
|
||||
}
|
||||
return result.Obj
|
||||
}
|
||||
|
||||
func groupMutation(t *testing.T, router *gin.Engine, route string, body any, success bool, field string, want int) {
|
||||
t.Helper()
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := groupAPIRequest(router, http.MethodPost, route, string(payload))
|
||||
var result struct {
|
||||
Success bool
|
||||
Obj map[string]json.RawMessage
|
||||
}
|
||||
if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || result.Success != success {
|
||||
t.Fatalf("%s returned %s (wanted success=%t): %v", route, out.Body, success, err)
|
||||
}
|
||||
if success {
|
||||
var got int
|
||||
if err := json.Unmarshal(result.Obj[field], &got); err != nil || got != want {
|
||||
t.Fatalf("%s returned %s, want %s=%d", route, out.Body, field, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func createTestGroupClients(t *testing.T, size, memberCount int) []model.ClientRecord {
|
||||
t.Helper()
|
||||
db := database.GetDB()
|
||||
if err := db.Create(&model.ClientGroup{Name: "staff"}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := make([]model.ClientRecord, size)
|
||||
for i := range rows {
|
||||
rows[i] = model.ClientRecord{Email: fmt.Sprintf("client-%06d", i), SubID: fmt.Sprintf("s-%06d", i), Comment: "literal_%", Group: "previous", TotalGB: 1024, Enable: true}
|
||||
if i < memberCount {
|
||||
rows[i].Group = "staff"
|
||||
}
|
||||
}
|
||||
if err := db.CreateInBatches(rows, 300).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
func TestGroupClientPageAndFrozenWriteHTTP(t *testing.T) {
|
||||
router := groupTestRouter(t)
|
||||
rows := createTestGroupClients(t, 230, 110)
|
||||
page := groupPage(t, router, "group=staff&mode=add&page=2")
|
||||
if page.Total != 120 || len(page.Items) != 20 || page.Items[0].ID != rows[210].Id {
|
||||
t.Fatalf("second add page = %d rows out of %d, expected clients 210–229", len(page.Items), page.Total)
|
||||
}
|
||||
search := url.QueryEscape("literal_%")
|
||||
frozen := groupPage(t, router, "group=STAFF&mode=add&freeze=true&search="+search)
|
||||
if frozen.Total != 120 || len(frozen.Items) != 0 || frozen.MaxID != rows[229].Id {
|
||||
t.Fatalf("frozen add scope = %+v", frozen)
|
||||
}
|
||||
db := database.GetDB()
|
||||
newer := model.ClientRecord{Email: "newer", Comment: "literal_%", Group: "previous"}
|
||||
if err := db.Create(&newer).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
alternate := model.ClientRecord{Email: "wildcard-would-match", Comment: "literalXY", Group: "previous"}
|
||||
if err := db.Create(&alternate).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
last := groupPage(t, router, fmt.Sprintf("group=staff&mode=add&page=2&maxId=%d&scopeSearch=%s", frozen.MaxID, search))
|
||||
if len(last.Items) != 22 || last.Items[20].InScope || last.Items[21].InScope || !last.Items[19].InScope {
|
||||
t.Fatalf("new and out-of-filter clients were included in the frozen scope: %+v", last.Items)
|
||||
}
|
||||
selection := service.GroupClientSelection{
|
||||
Mode: "allMatching", ScopeToken: frozen.ScopeToken,
|
||||
Search: "literal_%", ExcludedClientIDs: []int{rows[110].Id},
|
||||
}
|
||||
body := map[string]any{"group": "staff", "selection": selection}
|
||||
if err := db.Model(&rows[111]).UpdateColumn("group_name", "staff").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groupMutation(t, router, "/groups/bulkAdd", body, false, "", 0)
|
||||
staff := groupPage(t, router, "group=staff&mode=remove")
|
||||
if staff.Total != 111 {
|
||||
t.Fatalf("stale selection changed client groups: staff=%d", staff.Total)
|
||||
}
|
||||
if err := db.Model(&rows[111]).UpdateColumn("group_name", "previous").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groupMutation(t, router, "/groups/bulkAdd", body, true, "affected", 119)
|
||||
groupMutation(t, router, "/groups/bulkAdd", body, false, "", 0)
|
||||
for _, id := range []int{rows[110].Id, newer.Id, alternate.Id} {
|
||||
var row model.ClientRecord
|
||||
if err := db.First(&row, id).Error; err != nil || row.Group != "previous" {
|
||||
t.Fatalf("client %d left its group: %q, err=%v", id, row.Group, err)
|
||||
}
|
||||
}
|
||||
selection = service.GroupClientSelection{Mode: "explicit", ClientIDs: []int{rows[0].Id, newer.Id}}
|
||||
groupMutation(t, router, "/groups/bulkRemove", map[string]any{"group": "staff", "selection": selection}, false, "", 0)
|
||||
selection.ClientIDs = []int{rows[0].Id, rows[0].Id}
|
||||
groupMutation(t, router, "/groups/bulkRemove", map[string]any{"group": "staff", "selection": selection}, true, "affected", 1)
|
||||
if page := groupPage(t, router, "group=staff&mode=remove&page=3"); page.Total != 228 || len(page.Items) != 28 {
|
||||
t.Fatalf("remove page after mutations = %d out of %d", len(page.Items), page.Total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupBulkOperationsRespectFrozenMembersHTTP(t *testing.T) {
|
||||
router := groupTestRouter(t)
|
||||
rows := createTestGroupClients(t, 6, 2)
|
||||
freeze := groupPage(t, router, "group=staff&mode=remove&freeze=true")
|
||||
db := database.GetDB()
|
||||
if err := db.Model(&rows[0]).UpdateColumn("group_name", "previous").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groupMutation(t, router, "/bulkDel", map[string]any{"group": "staff", "scopeToken": freeze.ScopeToken}, false, "", 0)
|
||||
|
||||
freeze = groupPage(t, router, "group=staff&mode=remove&freeze=true")
|
||||
body := map[string]any{"group": "staff", "scopeToken": freeze.ScopeToken}
|
||||
newer := model.ClientRecord{Email: "new-member", Group: "staff", TotalGB: 1024}
|
||||
if err := db.Create(&newer).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, record := range []model.ClientRecord{rows[0], rows[1], newer} {
|
||||
if err := db.Create(&xray.ClientTraffic{Email: record.Email, Total: record.TotalGB, Enable: true}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
groupMutation(t, router, "/bulkAdjust", map[string]any{
|
||||
"group": "staff", "scopeToken": freeze.ScopeToken, "addBytes": 256,
|
||||
}, true, "adjusted", 1)
|
||||
for email, want := range map[string]int64{rows[0].Email: 1024, rows[1].Email: 1280, newer.Email: 1024} {
|
||||
var row xray.ClientTraffic
|
||||
if err := db.Where("email = ?", email).First(&row).Error; err != nil || row.Total != want {
|
||||
t.Fatalf("client %s quota = %d, want %d: %v", email, row.Total, want, err)
|
||||
}
|
||||
}
|
||||
groupMutation(t, router, "/bulkDel", body, true, "deleted", 1)
|
||||
groupMutation(t, router, "/bulkDel", body, false, "", 0)
|
||||
groupMutation(t, router, "/bulkDel", map[string]any{"emails": []string{rows[0].Email}}, true, "deleted", 1)
|
||||
if page := groupPage(t, router, "group=staff&mode=remove"); page.Total != 1 || page.Items[0].ID != newer.Id {
|
||||
t.Fatalf("bulk deletion selected clients outside the frozen scope: %+v", page)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupAdjustCapsReportedSkipsWithoutChangingExplicitResponses(t *testing.T) {
|
||||
router := groupTestRouter(t)
|
||||
rows := createTestGroupClients(t, 25, 25)
|
||||
if err := database.GetDB().Model(&model.ClientRecord{}).
|
||||
Where("group_name = ?", "staff").UpdateColumn("total_gb", 0).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
emails := make([]string, len(rows))
|
||||
for i, row := range rows {
|
||||
emails[i] = row.Email
|
||||
}
|
||||
var result struct {
|
||||
Success bool
|
||||
Obj service.BulkAdjustResult
|
||||
}
|
||||
groupResponse := groupAPIRequest(router, http.MethodPost, "/bulkAdjust", `{"group":"staff","addBytes":1}`)
|
||||
if err := json.Unmarshal(groupResponse.Body.Bytes(), &result); err != nil || !result.Success ||
|
||||
result.Obj.Adjusted != 0 || len(result.Obj.Skipped) != 20 || result.Obj.SkippedCount != 25 {
|
||||
t.Fatalf("group adjust response = %s (%v)", groupResponse.Body, err)
|
||||
}
|
||||
body, err := json.Marshal(map[string]any{"emails": emails, "addBytes": 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := groupAPIRequest(router, http.MethodPost, "/bulkAdjust", string(body))
|
||||
result.Obj = service.BulkAdjustResult{}
|
||||
if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success ||
|
||||
result.Obj.Adjusted != 0 || len(result.Obj.Skipped) != 25 || strings.Contains(out.Body.String(), "skippedCount") {
|
||||
t.Fatalf("explicit adjust response = %s (%v)", out.Body, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupSubscriptionExportAndPagingHTTP(t *testing.T) {
|
||||
sizes := []int{1000}
|
||||
if os.Getenv("XUI_SCALE_TEST") != "" {
|
||||
sizes = append(sizes, 10000, 50000)
|
||||
}
|
||||
for _, size := range sizes {
|
||||
t.Run(fmt.Sprint(size), func(t *testing.T) {
|
||||
testGroupSubscriptionExportAndPaging(t, size)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testGroupSubscriptionExportAndPaging(t *testing.T, size int) {
|
||||
t.Helper()
|
||||
router := groupTestRouter(t)
|
||||
rows := createTestGroupClients(t, size, min(size, 10000))
|
||||
db := database.GetDB()
|
||||
if err := db.Model(&rows[1]).UpdateColumn("sub_id", "").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for key, val := range map[string]string{
|
||||
"subEnable": "true", "subURI": "https://sub.example.test/plain/", "subJsonEnable": "true", "subJsonURI": "https://sub.example.test/json/",
|
||||
} {
|
||||
var setting model.Setting
|
||||
if err := db.Where("key = ?", key).Assign(model.Setting{Value: val}).FirstOrCreate(&setting, model.Setting{Key: key}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
total := min(size, 10000) - 1
|
||||
page := groupPage(t, router, "group=staff&mode=links")
|
||||
if os.Getenv("XUI_SCALE_TEST") != "" {
|
||||
pageResponse := groupAPIRequest(router, http.MethodGet, "/groups/clientPage?group=staff&mode=links", "")
|
||||
emailResponse := groupAPIRequest(router, http.MethodGet, "/groups/staff/emails", "")
|
||||
t.Logf("%d clients, %d links: page %d bytes, legacy emails %d bytes", size, total, pageResponse.Body.Len(), emailResponse.Body.Len())
|
||||
}
|
||||
if page.Total != int64(total) || len(page.Items) != 100 || page.Items[1].Email != rows[2].Email {
|
||||
t.Fatalf("link page returned %d rows out of %d", len(page.Items), page.Total)
|
||||
}
|
||||
if size == 50000 {
|
||||
add := groupPage(t, router, "group=staff&mode=add&page=400")
|
||||
if add.Total != 40000 || len(add.Items) != 100 || add.Items[99].Email != rows[49999].Email {
|
||||
t.Fatalf("last page of 40,000 candidates returned %d out of %d", len(add.Items), add.Total)
|
||||
}
|
||||
}
|
||||
out := groupAPIRequest(router, http.MethodGet, "/groups/subLinks/export?group=staff", "")
|
||||
lines := strings.Split(out.Body.String(), "\n")
|
||||
if out.Code != http.StatusOK || out.Header().Get("Cache-Control") != "no-store" || len(lines) != total {
|
||||
t.Fatalf("export returned HTTP %d and %d rows, want %d rows", out.Code, len(lines), total)
|
||||
}
|
||||
for index, line := range lines {
|
||||
if index > 0 {
|
||||
index++
|
||||
}
|
||||
row := rows[index]
|
||||
want := row.Email + "\thttps://sub.example.test/plain/" + row.SubID + "\thttps://sub.example.test/json/" + row.SubID
|
||||
if line != want {
|
||||
t.Fatalf("export row %d = %q, want %q", index, line, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
|
||||
)
|
||||
|
||||
func TestGroupBulkAddResolvesInboundMembershipHTTP(t *testing.T) {
|
||||
cleanup, err := testpg.IsolatePackage("group_client_http")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
db := database.GetDB()
|
||||
first := model.Inbound{Tag: "source", Port: 50111, Protocol: model.VLESS, Settings: `{"clients":[{"email":"shared"}]}`}
|
||||
second := model.Inbound{Tag: "other", Port: 50112, Protocol: model.VLESS, Settings: `{"clients":[{"email":"shared"},{"email":"other"}]}`}
|
||||
shared := model.ClientRecord{Email: "shared", Group: "previous"}
|
||||
other := model.ClientRecord{Email: "other", Group: "previous"}
|
||||
for _, row := range []any{&first, &second, &shared, &other} {
|
||||
if err := db.Create(row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
links := []model.ClientInbound{
|
||||
{ClientId: shared.Id, InboundId: first.Id},
|
||||
{ClientId: shared.Id, InboundId: second.Id},
|
||||
{ClientId: other.Id, InboundId: second.Id},
|
||||
}
|
||||
if err := db.Create(&links).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
originalSettings := second.Settings
|
||||
if err := db.Model(&second).UpdateColumn("settings", "{").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
router := gin.New()
|
||||
NewGroupController(router.Group("/panel/api/clients"))
|
||||
groupMutation(t, router, "/groups/bulkAdd", map[string]any{"group": "staff", "inboundId": first.Id}, false, "", 0)
|
||||
var unchanged model.ClientRecord
|
||||
if err := db.First(&unchanged, shared.Id).Error; err != nil || unchanged.Group != "previous" {
|
||||
t.Fatalf("malformed sibling inbound left a committed group change: %q, err=%v", unchanged.Group, err)
|
||||
}
|
||||
if err := db.Model(&second).UpdateColumn("settings", originalSettings).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := fmt.Sprintf(`{"group":"staff","inboundId":%d}`, first.Id)
|
||||
for _, want := range []int{1, 0} {
|
||||
req := httptest.NewRequest(http.MethodPost, "/panel/api/clients/groups/bulkAdd", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
out := httptest.NewRecorder()
|
||||
router.ServeHTTP(out, req)
|
||||
var result struct {
|
||||
Success bool
|
||||
Obj struct{ Affected int }
|
||||
}
|
||||
if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success || result.Obj.Affected != want {
|
||||
t.Fatalf("group add returned %s, want %d changed: %v", out.Body, want, err)
|
||||
}
|
||||
}
|
||||
for id, want := range map[int]string{shared.Id: "staff", other.Id: "previous"} {
|
||||
var got model.ClientRecord
|
||||
if err := db.First(&got, id).Error; err != nil || got.Group != want {
|
||||
t.Fatalf("client %d group = %q, want %q: %v", id, got.Group, want, err)
|
||||
}
|
||||
}
|
||||
for _, id := range []int{first.Id, second.Id} {
|
||||
var inbound model.Inbound
|
||||
if err := db.First(&inbound, id).Error; err != nil || !strings.Contains(inbound.Settings, `"group":"staff"`) {
|
||||
t.Fatalf("inbound %d settings were not updated: %s (%v)", id, inbound.Settings, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user