Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

revert group management #2656

Merged
merged 6 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 6 additions & 48 deletions database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,35 +26,20 @@ const (
)

func initModels() error {
// Order matters: first create tables without dependencies
baseModels := []interface{}{
models := []interface{}{
&model.User{},
&model.Setting{},
}

// Migrate base models
for _, model := range baseModels {
if err := db.AutoMigrate(model); err != nil {
log.Printf("Error auto migrating base model: %v", err)
return err
}
}

// Then migrate models with dependencies
dependentModels := []interface{}{
&model.Inbound{},
&model.OutboundTraffics{},
&model.Setting{},
&model.InboundClientIps{},
&xray.ClientTraffic{},
}

for _, model := range dependentModels {
for _, model := range models {
if err := db.AutoMigrate(model); err != nil {
log.Printf("Error auto migrating dependent model: %v", err)
log.Printf("Error auto migrating model: %v", err)
return err
}
}

return nil
}

Expand Down Expand Up @@ -97,31 +82,9 @@ func InitDB(dbPath string) error {
}

c := &gorm.Config{
Logger: gormLogger,
SkipDefaultTransaction: true,
PrepareStmt: true,
Logger: gormLogger,
}

dsn := dbPath + "?cache=shared&_journal_mode=WAL&_synchronous=NORMAL"
db, err = gorm.Open(sqlite.Open(dsn), c)
if err != nil {
return err
}

sqlDB, err := db.DB()
if err != nil {
return err
}

_, err = sqlDB.Exec("PRAGMA cache_size = -64000;")
if err != nil {
return err
}
_, err = sqlDB.Exec("PRAGMA temp_store = MEMORY;")
if err != nil {
return err
}
_, err = sqlDB.Exec("PRAGMA foreign_keys = ON;")
db, err = gorm.Open(sqlite.Open(dbPath), c)
if err != nil {
return err
}
Expand All @@ -138,11 +101,6 @@ func InitDB(dbPath string) error {

func CloseDB() error {
if db != nil {

if err := Checkpoint(); err != nil {
log.Printf("error executing checkpoint: %v", err)
}

sqlDB, err := db.DB()
if err != nil {
return err
Expand Down
4 changes: 2 additions & 2 deletions database/model/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ type User struct {

type Inbound struct {
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
UserId int `json:"-" gorm:"index"`
UserId int `json:"-"`
Up int64 `json:"up" form:"up"`
Down int64 `json:"down" form:"down"`
Total int64 `json:"total" form:"total"`
Remark string `json:"remark" form:"remark"`
Enable bool `json:"enable" form:"enable"`
ExpiryTime int64 `json:"expiryTime" form:"expiryTime"`
ClientStats []xray.ClientTraffic `gorm:"foreignKey:InboundId;references:Id;constraint:OnDelete:CASCADE" json:"clientStats"`
ClientStats []xray.ClientTraffic `gorm:"foreignKey:InboundId;references:Id" json:"clientStats" form:"clientStats"`

// config part
Listen string `json:"listen" form:"listen"`
Expand Down
2 changes: 1 addition & 1 deletion install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -283,4 +283,4 @@ install_x-ui() {

echo -e "${green}Running...${plain}"
install_base
install_x-ui $1
install_x-ui $1
1 change: 0 additions & 1 deletion web/assets/js/model/setting.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ class AllSetting {
this.xrayTemplateConfig = "";
this.secretEnable = false;
this.subEnable = false;
this.subSyncEnable = true;
this.subListen = "";
this.subPort = 2096;
this.subPath = "/sub/";
Expand Down
35 changes: 0 additions & 35 deletions web/assets/js/util/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,41 +70,6 @@ class HttpUtil {
}
return msg;
}

static async jsonPost(url, data) {
let msg;
try {
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
};
const resp = await fetch(basePath + url.replace(/^\/+|\/+$/g, ''), requestOptions);
const response = await resp.json();

msg = this._respToMsg({data : response});
} catch (e) {
msg = new Msg(false, e.toString());
}
this._handleMsg(msg);
return msg;
}

static async postWithModalJson(url, data, modal) {
if (modal) {
modal.loading(true);
}
const msg = await this.jsonPost(url, data);
if (modal) {
modal.loading(false);
if (msg instanceof Msg && msg.success) {
modal.close();
}
}
return msg;
}
}

class PromiseUtil {
Expand Down
154 changes: 1 addition & 153 deletions web/controller/inbound.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package controller

import (
"errors"
"encoding/json"
"fmt"
"strconv"

"x-ui/database/model"
"x-ui/web/service"
"x-ui/web/session"
Expand Down Expand Up @@ -33,13 +33,9 @@ func (a *InboundController) initRouter(g *gin.RouterGroup) {
g.POST("/clientIps/:email", a.getClientIps)
g.POST("/clearClientIps/:email", a.clearClientIps)
g.POST("/addClient", a.addInboundClient)
g.POST("/addGroupClient", a.addGroupInboundClient)
g.POST("/:id/delClient/:clientId", a.delInboundClient)
g.POST("/delGroupClients", a.delGroupClients)
g.POST("/updateClient/:clientId", a.updateInboundClient)
g.POST("/updateClients", a.updateGroupInboundClient)
g.POST("/:id/resetClientTraffic/:email", a.resetClientTraffic)
g.POST("/resetGroupClientTraffic", a.resetGroupClientTraffic)
g.POST("/resetAllTraffics", a.resetAllTraffics)
g.POST("/resetAllClientTraffics/:id", a.resetAllClientTraffics)
g.POST("/delDepletedClients/:id", a.delDepletedClients)
Expand Down Expand Up @@ -194,34 +190,6 @@ func (a *InboundController) addInboundClient(c *gin.Context) {
}
}

func (a *InboundController) addGroupInboundClient(c *gin.Context) {
var requestData []model.Inbound

err := c.ShouldBindJSON(&requestData)

if err != nil {
jsonMsg(c, I18nWeb(c, "pages.inbounds.update"), err)
return
}

needRestart := true

for _, data := range requestData {

needRestart, err = a.inboundService.AddInboundClient(&data)
if err != nil {
jsonMsg(c, "Something went wrong!", err)
return
}
}

jsonMsg(c, "Client(s) added", nil)
if err == nil && needRestart {
a.xrayService.SetToNeedRestart()
}

}

func (a *InboundController) delInboundClient(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
Expand All @@ -243,38 +211,6 @@ func (a *InboundController) delInboundClient(c *gin.Context) {
}
}

func (a *InboundController) delGroupClients(c *gin.Context) {
var requestData []struct {
InboundID int `json:"inboundId"`
ClientID string `json:"clientId"`
}

if err := c.ShouldBindJSON(&requestData); err != nil {
jsonMsg(c, "Invalid request data", err)
return
}

needRestart := false

for _, req := range requestData {
needRestartTmp, err := a.inboundService.DelInboundClient(req.InboundID, req.ClientID)
if err != nil {
jsonMsg(c, "Failed to delete client", err)
return
}

if needRestartTmp {
needRestart = true
}
}

jsonMsg(c, "Clients deleted successfully", nil)

if needRestart {
a.xrayService.SetToNeedRestart()
}
}

func (a *InboundController) updateInboundClient(c *gin.Context) {
clientId := c.Param("clientId")

Expand All @@ -298,56 +234,6 @@ func (a *InboundController) updateInboundClient(c *gin.Context) {
}
}

func (a *InboundController) updateGroupInboundClient(c *gin.Context) {
var requestData []map[string]interface{}

if err := c.ShouldBindJSON(&requestData); err != nil {
jsonMsg(c, I18nWeb(c, "pages.inbounds.update"), err)
return
}

needRestart := false

for _, item := range requestData {

inboundMap, ok := item["inbound"].(map[string]interface{})
if !ok {
jsonMsg(c, "Something went wrong!", errors.New("Failed to convert 'inbound' to map"))
return
}

clientId, ok := item["clientId"].(string)
if !ok {
jsonMsg(c, "Something went wrong!", errors.New("Failed to convert 'clientId' to string"))
return
}

inboundJSON, err := json.Marshal(inboundMap)
if err != nil {
jsonMsg(c, "Something went wrong!", err)
return
}

var inboundModel model.Inbound
if err := json.Unmarshal(inboundJSON, &inboundModel); err != nil {
jsonMsg(c, "Something went wrong!", err)
return
}

if restart, err := a.inboundService.UpdateInboundClient(&inboundModel, clientId); err != nil {
jsonMsg(c, "Something went wrong!", err)
return
} else {
needRestart = needRestart || restart
}
}

jsonMsg(c, "Client updated", nil)
if needRestart {
a.xrayService.SetToNeedRestart()
}
}

func (a *InboundController) resetClientTraffic(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
Expand All @@ -367,44 +253,6 @@ func (a *InboundController) resetClientTraffic(c *gin.Context) {
}
}

func (a *InboundController) resetGroupClientTraffic(c *gin.Context) {
var requestData []struct {
InboundID int `json:"inboundId"` // Map JSON "inboundId" to struct field "InboundID"
Email string `json:"email"` // Map JSON "email" to struct field "Email"
}

// Parse JSON body directly using ShouldBindJSON
if err := c.ShouldBindJSON(&requestData); err != nil {
jsonMsg(c, "Invalid request data", err)
return
}

needRestart := false

// Process each request data
for _, req := range requestData {
needRestartTmp, err := a.inboundService.ResetClientTraffic(req.InboundID, req.Email)
if err != nil {
jsonMsg(c, "Failed to reset client traffic", err)
return
}

// If any request requires a restart, set needRestart to true
if needRestartTmp {
needRestart = true
}
}

// Send response back to the client
jsonMsg(c, "Traffic reset for all clients", nil)

// Restart the service if required
if needRestart {
a.xrayService.SetToNeedRestart()
}
}


func (a *InboundController) resetAllTraffics(c *gin.Context) {
err := a.inboundService.ResetAllTraffics()
if err != nil {
Expand Down
1 change: 0 additions & 1 deletion web/entity/entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ type AllSetting struct {
TimeLocation string `json:"timeLocation" form:"timeLocation"`
SecretEnable bool `json:"secretEnable" form:"secretEnable"`
SubEnable bool `json:"subEnable" form:"subEnable"`
SubSyncEnable bool `json:"subSyncEnable" form:"subSyncEnable"`
SubListen string `json:"subListen" form:"subListen"`
SubPort int `json:"subPort" form:"subPort"`
SubPath string `json:"subPath" form:"subPath"`
Expand Down
Loading