Merge upstream/master into develop

Sync upstream changes from perfect-panel/server

  Includes updates from v1.0.1 to v1.2.5:
  - Currency configuration support
  - Subscribe improvements (short token, inventory check, etc.)
  - Node management enhancements
  - Database migrations
  - Bug fixes and optimizations
This commit is contained in:
EUForest
2026-01-02 12:51:55 +08:00
parent 47c41d1d14
commit 80ee9a6acf
63 changed files with 947 additions and 1509 deletions
+3
View File
@@ -27,6 +27,9 @@ type Filter struct {
// GetAnnouncementListByPage get announcement list by page
func (m *customAnnouncementModel) GetAnnouncementListByPage(ctx context.Context, page, size int, filter Filter) (int64, []*Announcement, error) {
if size == 0 {
size = 10
}
var list []*Announcement
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
-141
View File
@@ -1,141 +0,0 @@
package server
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customServerModel)(nil)
var (
cacheServerIdPrefix = "cache:server:id:"
)
type (
Model interface {
serverModel
customServerLogicModel
}
serverModel interface {
Insert(ctx context.Context, data *Server, tx ...*gorm.DB) error
FindOne(ctx context.Context, id int64) (*Server, error)
Update(ctx context.Context, data *Server, tx ...*gorm.DB) error
Delete(ctx context.Context, id int64, tx ...*gorm.DB) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customServerModel struct {
*defaultServerModel
}
defaultServerModel struct {
cache.CachedConn
table string
}
)
func newServerModel(db *gorm.DB, c *redis.Client) *defaultServerModel {
return &defaultServerModel{
CachedConn: cache.NewConn(db, c),
table: "`Server`",
}
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customServerModel{
defaultServerModel: newServerModel(conn, c),
}
}
//nolint:unused
func (m *defaultServerModel) batchGetCacheKeys(Servers ...*Server) []string {
var keys []string
for _, server := range Servers {
keys = append(keys, m.getCacheKeys(server)...)
}
return keys
}
func (m *defaultServerModel) getCacheKeys(data *Server) []string {
if data == nil {
return []string{}
}
detailsKey := fmt.Sprintf("%s%v", CacheServerDetailPrefix, data.Id)
ServerIdKey := fmt.Sprintf("%s%v", cacheServerIdPrefix, data.Id)
//configIdKey := fmt.Sprintf("%s%v", config.ServerConfigCacheKey, data.Id)
//userIDKey := fmt.Sprintf("%s%d", config.ServerUserListCacheKey, data.Id)
// query protocols to get config keys
cacheKeys := []string{
ServerIdKey,
detailsKey,
//configIdKey,
//userIDKey,
}
return cacheKeys
}
func (m *defaultServerModel) Insert(ctx context.Context, data *Server, tx ...*gorm.DB) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Create(&data).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultServerModel) FindOne(ctx context.Context, id int64) (*Server, error) {
ServerIdKey := fmt.Sprintf("%s%v", cacheServerIdPrefix, id)
var resp Server
err := m.QueryCtx(ctx, &resp, ServerIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Server{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultServerModel) Update(ctx context.Context, data *Server, tx ...*gorm.DB) error {
old, err := m.FindOne(ctx, data.Id)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
err = m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Save(data).Error
}, m.getCacheKeys(old)...)
return err
}
func (m *defaultServerModel) Delete(ctx context.Context, id int64, tx ...*gorm.DB) error {
data, err := m.FindOne(ctx, id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil
}
return err
}
err = m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Delete(&Server{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultServerModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
-292
View File
@@ -1,292 +0,0 @@
package server
import (
"context"
"fmt"
"strings"
"gorm.io/gorm"
)
type customServerLogicModel interface {
FindServerListByFilter(ctx context.Context, filter *ServerFilter) (total int64, list []*Server, err error)
ClearCache(ctx context.Context, id int64) error
QueryServerCountByServerGroups(ctx context.Context, groupIds []int64) (int64, error)
QueryAllGroup(ctx context.Context) ([]*Group, error)
BatchDeleteNodeGroup(ctx context.Context, ids []int64) error
InsertGroup(ctx context.Context, data *Group) error
FindOneGroup(ctx context.Context, id int64) (*Group, error)
UpdateGroup(ctx context.Context, data *Group) error
DeleteGroup(ctx context.Context, id int64) error
FindServerDetailByGroupIdsAndIds(ctx context.Context, groupId, ids []int64) ([]*Server, error)
FindServerListByGroupIds(ctx context.Context, groupId []int64) ([]*Server, error)
FindAllServer(ctx context.Context) ([]*Server, error)
FindNodeByServerAddrAndProtocol(ctx context.Context, serverAddr string, protocol string) ([]*Server, error)
FindServerMinSortByIds(ctx context.Context, ids []int64) (int64, error)
FindServerListByIds(ctx context.Context, ids []int64) ([]*Server, error)
InsertRuleGroup(ctx context.Context, data *RuleGroup) error
FindOneRuleGroup(ctx context.Context, id int64) (*RuleGroup, error)
UpdateRuleGroup(ctx context.Context, data *RuleGroup) error
DeleteRuleGroup(ctx context.Context, id int64) error
QueryAllRuleGroup(ctx context.Context) ([]*RuleGroup, error)
FindServersByTag(ctx context.Context, tag string) ([]*Server, error)
FindServerTags(ctx context.Context) ([]string, error)
SetDefaultRuleGroup(ctx context.Context, id int64) error
}
var (
CacheServerDetailPrefix = "cache:server:detail:"
cacheServerGroupAllKeys = "cache:serverGroup:all"
cacheServerRuleGroupAllKeys = "cache:serverRuleGroup:all"
)
// ClearCache Clear Cache
func (m *customServerModel) ClearCache(ctx context.Context, id int64) error {
serverIdKey := fmt.Sprintf("%s%v", cacheServerIdPrefix, id)
//configKey := fmt.Sprintf("%s%d", config.ServerConfigCacheKey, id)
//userListKey := fmt.Sprintf("%s%v", config.ServerUserListCacheKey, id)
return m.DelCacheCtx(ctx, serverIdKey)
}
// QueryServerCountByServerGroups Query Server Count By Server Groups
func (m *customServerModel) QueryServerCountByServerGroups(ctx context.Context, groupIds []int64) (int64, error) {
var count int64
err := m.QueryNoCacheCtx(ctx, &count, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Server{}).Where("group_id IN ?", groupIds).Count(&count).Error
})
return count, err
}
// QueryAllGroup returns all groups.
func (m *customServerModel) QueryAllGroup(ctx context.Context) ([]*Group, error) {
var groups []*Group
err := m.QueryCtx(ctx, &groups, cacheServerGroupAllKeys, func(conn *gorm.DB, v interface{}) error {
return conn.Find(&groups).Error
})
return groups, err
}
// BatchDeleteNodeGroup deletes multiple groups.
func (m *customServerModel) BatchDeleteNodeGroup(ctx context.Context, ids []int64) error {
return m.Transaction(ctx, func(tx *gorm.DB) error {
for _, id := range ids {
if err := m.Delete(ctx, id); err != nil {
return err
}
}
return nil
})
}
// InsertGroup inserts a group.
func (m *customServerModel) InsertGroup(ctx context.Context, data *Group) error {
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(data).Error
}, cacheServerGroupAllKeys)
}
// FindOneGroup finds a group.
func (m *customServerModel) FindOneGroup(ctx context.Context, id int64) (*Group, error) {
var group Group
err := m.QueryCtx(ctx, &group, fmt.Sprintf("cache:serverGroup:%v", id), func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Group{}).Where("id = ?", id).First(&group).Error
})
return &group, err
}
// UpdateGroup updates a group.
func (m *customServerModel) UpdateGroup(ctx context.Context, data *Group) error {
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Model(&Group{}).Where("id = ?", data.Id).Updates(data).Error
}, cacheServerGroupAllKeys, fmt.Sprintf("cache:serverGroup:%v", data.Id))
}
// DeleteGroup deletes a group.
func (m *customServerModel) DeleteGroup(ctx context.Context, id int64) error {
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Where("id = ?", id).Delete(&Group{}).Error
}, cacheServerGroupAllKeys, fmt.Sprintf("cache:serverGroup:%v", id))
}
// FindServerDetailByGroupIdsAndIds finds server details by group IDs and IDs.
func (m *customServerModel) FindServerDetailByGroupIdsAndIds(ctx context.Context, groupId, ids []int64) ([]*Server, error) {
if len(groupId) == 0 && len(ids) == 0 {
return []*Server{}, nil
}
var list []*Server
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
conn = conn.
Model(&Server{}).
Where("`enable` = ?", true)
if len(groupId) > 0 && len(ids) > 0 {
// OR is used to connect group_id and id conditions
conn = conn.Where("(`group_id` IN ? OR `id` IN ?)", groupId, ids)
} else if len(groupId) > 0 {
conn = conn.Where("`group_id` IN ?", groupId)
} else if len(ids) > 0 {
conn = conn.Where("`id` IN ?", ids)
}
return conn.Order("sort ASC").Find(v).Error
})
return list, err
}
func (m *customServerModel) FindServerListByGroupIds(ctx context.Context, groupId []int64) ([]*Server, error) {
var data []*Server
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Server{}).Where("group_id IN ?", groupId).Find(v).Error
})
return data, err
}
func (m *customServerModel) FindAllServer(ctx context.Context) ([]*Server, error) {
var data []*Server
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Server{}).Order("sort ASC").Find(v).Error
})
return data, err
}
func (m *customServerModel) FindNodeByServerAddrAndProtocol(ctx context.Context, serverAddr string, protocol string) ([]*Server, error) {
var data []*Server
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Server{}).Where("server_addr = ? and protocol = ?", serverAddr, protocol).Order("sort ASC").Find(v).Error
})
return data, err
}
func (m *customServerModel) FindServerMinSortByIds(ctx context.Context, ids []int64) (int64, error) {
var minSort int64
err := m.QueryNoCacheCtx(ctx, &minSort, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Server{}).Where("id IN ?", ids).Select("COALESCE(MIN(sort), 0)").Scan(v).Error
})
return minSort, err
}
func (m *customServerModel) FindServerListByIds(ctx context.Context, ids []int64) ([]*Server, error) {
var list []*Server
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Server{}).Where("id IN ?", ids).Find(v).Error
})
return list, err
}
// InsertRuleGroup inserts a group.
func (m *customServerModel) InsertRuleGroup(ctx context.Context, data *RuleGroup) error {
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Where(&RuleGroup{}).Create(data).Error
}, cacheServerRuleGroupAllKeys, fmt.Sprintf("cache:serverRuleGroup:%v", data.Id))
}
// FindOneRuleGroup finds a group.
func (m *customServerModel) FindOneRuleGroup(ctx context.Context, id int64) (*RuleGroup, error) {
var group RuleGroup
err := m.QueryCtx(ctx, &group, fmt.Sprintf("cache:serverRuleGroup:%v", id), func(conn *gorm.DB, v interface{}) error {
return conn.Where(&RuleGroup{}).Model(&RuleGroup{}).Where("id = ?", id).First(&group).Error
})
return &group, err
}
// UpdateRuleGroup updates a group.
func (m *customServerModel) UpdateRuleGroup(ctx context.Context, data *RuleGroup) error {
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Where(&RuleGroup{}).Model(&RuleGroup{}).Where("id = ?", data.Id).Save(data).Error
}, cacheServerRuleGroupAllKeys, fmt.Sprintf("cache:serverRuleGroup:%v", data.Id))
}
// DeleteRuleGroup deletes a group.
func (m *customServerModel) DeleteRuleGroup(ctx context.Context, id int64) error {
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Where(&RuleGroup{}).Where("id = ?", id).Delete(&RuleGroup{}).Error
}, cacheServerRuleGroupAllKeys, fmt.Sprintf("cache:serverRuleGroup:%v", id))
}
// QueryAllRuleGroup returns all rule groups.
func (m *customServerModel) QueryAllRuleGroup(ctx context.Context) ([]*RuleGroup, error) {
var groups []*RuleGroup
err := m.QueryCtx(ctx, &groups, cacheServerRuleGroupAllKeys, func(conn *gorm.DB, v interface{}) error {
return conn.Where(&RuleGroup{}).Find(&groups).Error
})
return groups, err
}
func (m *customServerModel) FindServerListByFilter(ctx context.Context, filter *ServerFilter) (total int64, list []*Server, err error) {
var data []*Server
if filter == nil {
filter = &ServerFilter{
Page: 1,
Size: 10,
}
}
if filter.Page <= 0 {
filter.Page = 1
}
if filter.Size <= 0 {
filter.Size = 10
}
err = m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
query := conn.Model(&Server{}).Order("sort ASC")
if filter.Group > 0 {
query = conn.Where("group_id = ?", filter.Group)
}
if filter.Search != "" {
query = query.Where("name LIKE ? OR server_addr LIKE ? OR tags LIKE ?", "%"+filter.Search+"%", "%"+filter.Search+"%", "%"+filter.Search+"%")
}
if len(filter.Tags) > 0 {
for i, tag := range filter.Tags {
if i == 0 {
query = query.Where("tags LIKE ?", "%"+tag+"%")
} else {
query = query.Or("tags LIKE ?", "%"+tag+"%")
}
}
}
return query.Count(&total).Limit(filter.Size).Offset((filter.Page - 1) * filter.Size).Find(v).Error
})
if err != nil {
return 0, nil, err
}
return total, data, nil
}
func (m *customServerModel) FindServerTags(ctx context.Context) ([]string, error) {
var data []string
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Server{}).Distinct("tags").Pluck("tags", v).Error
})
var tags []string
for _, tag := range data {
if strings.Contains(tag, ",") {
tags = append(tags, strings.Split(tag, ",")...)
} else {
tags = append(tags, tag)
}
}
return tags, err
}
func (m *customServerModel) FindServersByTag(ctx context.Context, tag string) ([]*Server, error) {
var data []*Server
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Server{}).Where("FIND_IN_SET(?, tags)", tag).Order("sort ASC").Find(v).Error
})
return data, err
}
// SetDefaultRuleGroup sets the default rule group.
func (m *customServerModel) SetDefaultRuleGroup(ctx context.Context, id int64) error {
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
// Reset all groups to not default
if err := conn.Model(&RuleGroup{}).Where("`id` != ?", id).Update("default", false).Error; err != nil {
return err
}
// Set the specified group as default
return conn.Model(&RuleGroup{}).Where("`id` = ?", id).Update("default", true).Error
}, cacheServerRuleGroupAllKeys, fmt.Sprintf("cache:serverRuleGroup:%v", id))
}
-219
View File
@@ -1,219 +0,0 @@
package server
import (
"time"
"github.com/perfect-panel/server/pkg/logger"
"gorm.io/gorm"
)
const (
RelayModeNone = "none"
RelayModeAll = "all"
RelayModeRandom = "random"
RuleGroupTypeReject = "reject"
RuleGroupTypeDefault = "default"
RuleGroupTypeDirect = "direct"
)
type ServerFilter struct {
Id int64
Tags []string
Group int64
Search string
Page int
Size int
}
// Deprecated: use internal/model/node/server.go
type Server struct {
Id int64 `gorm:"primary_key"`
Name string `gorm:"type:varchar(100);not null;default:'';comment:Node Name"`
Tags string `gorm:"type:varchar(128);not null;default:'';comment:Tags"`
Country string `gorm:"type:varchar(128);not null;default:'';comment:Country"`
City string `gorm:"type:varchar(128);not null;default:'';comment:City"`
Latitude string `gorm:"type:varchar(128);not null;default:'';comment:Latitude"`
Longitude string `gorm:"type:varchar(128);not null;default:'';comment:Longitude"`
ServerAddr string `gorm:"type:varchar(100);not null;default:'';comment:Server Address"`
RelayMode string `gorm:"type:varchar(20);not null;default:'none';comment:Relay Mode"`
RelayNode string `gorm:"type:text;comment:Relay Node"`
SpeedLimit int `gorm:"type:int;not null;default:0;comment:Speed Limit"`
TrafficRatio float32 `gorm:"type:DECIMAL(4,2);not null;default:0;comment:Traffic Ratio"`
GroupId int64 `gorm:"index:idx_group_id;type:int;default:null;comment:Group ID"`
Protocol string `gorm:"type:varchar(20);not null;default:'';comment:Protocol"`
Config string `gorm:"type:text;comment:Config"`
Enable *bool `gorm:"type:tinyint(1);not null;default:1;comment:Enabled"`
Sort int64 `gorm:"type:int;not null;default:0;comment:Sort"`
LastReportedAt time.Time `gorm:"comment:Last Reported Time"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (*Server) TableName() string {
return "server"
}
func (s *Server) BeforeDelete(tx *gorm.DB) error {
logger.Debugf("[Server] BeforeDelete")
if err := tx.Exec("UPDATE `server` SET sort = sort - 1 WHERE sort > ?", s.Sort).Error; err != nil {
return err
}
return nil
}
func (s *Server) BeforeUpdate(tx *gorm.DB) error {
logger.Debugf("[Server] BeforeUpdate")
var count int64
if err := tx.Set("gorm:query_option", "FOR UPDATE").Model(&Server{}).
Where("sort = ? AND id != ?", s.Sort, s.Id).Count(&count).Error; err != nil {
return err
}
if count > 1 {
// reorder sort
if err := reorderSort(tx); err != nil {
logger.Errorf("[Server] BeforeUpdate reorderSort error: %v", err.Error())
return err
}
// get max sort
var maxSort int64
if err := tx.Model(&Server{}).Select("MAX(sort)").Scan(&maxSort).Error; err != nil {
return err
}
s.Sort = maxSort + 1
}
return nil
}
func (s *Server) BeforeCreate(tx *gorm.DB) error {
logger.Debugf("[Server] BeforeCreate")
if s.Sort == 0 {
var maxSort int64
if err := tx.Model(&Server{}).Select("COALESCE(MAX(sort), 0)").Scan(&maxSort).Error; err != nil {
return err
}
s.Sort = maxSort + 1
}
return nil
}
type Vless struct {
Port int `json:"port"`
Flow string `json:"flow"`
Transport string `json:"transport"`
TransportConfig TransportConfig `json:"transport_config"`
Security string `json:"security"`
SecurityConfig SecurityConfig `json:"security_config"`
}
type Vmess struct {
Port int `json:"port"`
Flow string `json:"flow"`
Transport string `json:"transport"`
TransportConfig TransportConfig `json:"transport_config"`
Security string `json:"security"`
SecurityConfig SecurityConfig `json:"security_config"`
}
type Trojan struct {
Port int `json:"port"`
Flow string `json:"flow"`
Transport string `json:"transport"`
TransportConfig TransportConfig `json:"transport_config"`
Security string `json:"security"`
SecurityConfig SecurityConfig `json:"security_config"`
}
type Shadowsocks struct {
Method string `json:"method"`
Port int `json:"port"`
ServerKey string `json:"server_key"`
}
type Hysteria2 struct {
Port int `json:"port"`
HopPorts string `json:"hop_ports"`
HopInterval int `json:"hop_interval"`
ObfsPassword string `json:"obfs_password"`
SecurityConfig SecurityConfig `json:"security_config"`
}
type Tuic struct {
Port int `json:"port"`
DisableSNI bool `json:"disable_sni"`
ReduceRtt bool `json:"reduce_rtt"`
UDPRelayMode string `json:"udp_relay_mode"`
CongestionController string `json:"congestion_controller"`
SecurityConfig SecurityConfig `json:"security_config"`
}
type AnyTLS struct {
Port int `json:"port"`
SecurityConfig SecurityConfig `json:"security_config"`
}
type TransportConfig struct {
Path string `json:"path,omitempty"` // ws/httpupgrade
Host string `json:"host,omitempty"`
ServiceName string `json:"service_name"` // grpc
}
type SecurityConfig struct {
SNI string `json:"sni"`
AllowInsecure bool `json:"allow_insecure"`
Fingerprint string `json:"fingerprint"`
RealityServerAddr string `json:"reality_server_addr"`
RealityServerPort int `json:"reality_server_port"`
RealityPrivateKey string `json:"reality_private_key"`
RealityPublicKey string `json:"reality_public_key"`
RealityShortId string `json:"reality_short_id"`
}
type NodeRelay struct {
Host string `json:"host"`
Port int `json:"port"`
Prefix string `json:"prefix"`
}
type Group struct {
Id int64 `gorm:"primary_key"`
Name string `gorm:"type:varchar(100);not null;default:'';comment:Group Name"`
Description string `gorm:"type:varchar(255);default:'';comment:Group Description"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Group) TableName() string {
return "server_group"
}
type RuleGroup struct {
Id int64 `gorm:"primary_key"`
Icon string `gorm:"type:MEDIUMTEXT;comment:Rule Group Icon"`
Name string `gorm:"type:varchar(100);not null;default:'';comment:Rule Group Name"`
Type string `gorm:"type:varchar(100);not null;default:'';comment:Rule Group Type"`
Tags string `gorm:"type:text;comment:Selected Node Tags"`
Rules string `gorm:"type:MEDIUMTEXT;comment:Rules"`
Enable bool `gorm:"type:tinyint(1);not null;default:1;comment:Rule Group Enable"`
Default bool `gorm:"type:tinyint(1);not null;default:0;comment:Rule Group is Default"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (RuleGroup) TableName() string {
return "server_rule_group"
}
func reorderSort(tx *gorm.DB) error {
var servers []Server
if err := tx.Order("sort, id").Find(&servers).Error; err != nil {
return err
}
for i, server := range servers {
if server.Sort != int64(i)+1 {
if err := tx.Exec("UPDATE `server` SET sort = ? WHERE id = ?", i+1, server.Id).Error; err != nil {
return err
}
}
}
return nil
}
+25 -24
View File
@@ -7,30 +7,31 @@ import (
)
type Subscribe struct {
Id int64 `gorm:"primaryKey"`
Name string `gorm:"type:varchar(255);not null;default:'';comment:Subscribe Name"`
Language string `gorm:"type:varchar(255);not null;default:'';comment:Language"`
Description string `gorm:"type:text;comment:Subscribe Description"`
UnitPrice int64 `gorm:"type:int;not null;default:0;comment:Unit Price"`
UnitTime string `gorm:"type:varchar(255);not null;default:'';comment:Unit Time"`
Discount string `gorm:"type:text;comment:Discount"`
Replacement int64 `gorm:"type:int;not null;default:0;comment:Replacement"`
Inventory int64 `gorm:"type:int;not null;default:0;comment:Inventory"`
Traffic int64 `gorm:"type:int;not null;default:0;comment:Traffic"`
SpeedLimit int64 `gorm:"type:int;not null;default:0;comment:Speed Limit"`
DeviceLimit int64 `gorm:"type:int;not null;default:0;comment:Device Limit"`
Quota int64 `gorm:"type:int;not null;default:0;comment:Quota"`
Nodes string `gorm:"type:varchar(255);comment:Node Ids"`
NodeTags string `gorm:"type:varchar(255);comment:Node Tags"`
Show *bool `gorm:"type:tinyint(1);not null;default:0;comment:Show portal page"`
Sell *bool `gorm:"type:tinyint(1);not null;default:0;comment:Sell"`
Sort int64 `gorm:"type:int;not null;default:0;comment:Sort"`
DeductionRatio int64 `gorm:"type:int;default:0;comment:Deduction Ratio"`
AllowDeduction *bool `gorm:"type:tinyint(1);default:1;comment:Allow deduction"`
ResetCycle int64 `gorm:"type:int;default:0;comment:Reset Cycle: 0: No Reset, 1: 1st, 2: Monthly, 3: Yearly"`
RenewalReset *bool `gorm:"type:tinyint(1);default:0;comment:Renew Reset"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
Id int64 `gorm:"primaryKey"`
Name string `gorm:"type:varchar(255);not null;default:'';comment:Subscribe Name"`
Language string `gorm:"type:varchar(255);not null;default:'';comment:Language"`
Description string `gorm:"type:text;comment:Subscribe Description"`
UnitPrice int64 `gorm:"type:int;not null;default:0;comment:Unit Price"`
UnitTime string `gorm:"type:varchar(255);not null;default:'';comment:Unit Time"`
Discount string `gorm:"type:text;comment:Discount"`
Replacement int64 `gorm:"type:int;not null;default:0;comment:Replacement"`
Inventory int64 `gorm:"type:int;not null;default:-1;comment:Inventory"`
Traffic int64 `gorm:"type:int;not null;default:0;comment:Traffic"`
SpeedLimit int64 `gorm:"type:int;not null;default:0;comment:Speed Limit"`
DeviceLimit int64 `gorm:"type:int;not null;default:0;comment:Device Limit"`
Quota int64 `gorm:"type:int;not null;default:0;comment:Quota"`
Nodes string `gorm:"type:varchar(255);comment:Node Ids"`
NodeTags string `gorm:"type:varchar(255);comment:Node Tags"`
Show *bool `gorm:"type:tinyint(1);not null;default:0;comment:Show portal page"`
Sell *bool `gorm:"type:tinyint(1);not null;default:0;comment:Sell"`
Sort int64 `gorm:"type:int;not null;default:0;comment:Sort"`
DeductionRatio int64 `gorm:"type:int;default:0;comment:Deduction Ratio"`
AllowDeduction *bool `gorm:"type:tinyint(1);default:1;comment:Allow deduction"`
ResetCycle int64 `gorm:"type:int;default:0;comment:Reset Cycle: 0: No Reset, 1: 1st, 2: Monthly, 3: Yearly"`
RenewalReset *bool `gorm:"type:tinyint(1);default:0;comment:Renew Reset"`
ShowOriginalPrice bool `gorm:"type:tinyint(1);not null;default:1;comment:Show Original Price"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (*Subscribe) TableName() string {
+7 -18
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"github.com/perfect-panel/server/pkg/cache"
"github.com/perfect-panel/server/pkg/logger"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -72,7 +73,7 @@ func (m *defaultUserModel) FindOneByEmail(ctx context.Context, email string) (*U
if err := conn.Model(&AuthMethods{}).Where("`auth_type` = 'email' AND `auth_identifier` = ?", email).First(&data).Error; err != nil {
return err
}
return conn.Model(&User{}).Where("`id` = ?", data.UserId).Preload("UserDevices").Preload("AuthMethods").First(v).Error
return conn.Model(&User{}).Unscoped().Where("`id` = ?", data.UserId).Preload("UserDevices").Preload("AuthMethods").First(v).Error
})
return &user, err
}
@@ -91,7 +92,7 @@ func (m *defaultUserModel) FindOne(ctx context.Context, id int64) (*User, error)
userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, id)
var resp User
err := m.QueryCtx(ctx, &resp, userIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&User{}).Where("`id` = ?", id).Preload("UserDevices").Preload("AuthMethods").First(&resp).Error
return conn.Model(&User{}).Unscoped().Where("`id` = ?", id).Preload("UserDevices").Preload("AuthMethods").First(&resp).Error
})
return &resp, err
}
@@ -119,10 +120,11 @@ func (m *defaultUserModel) Delete(ctx context.Context, id int64, tx ...*gorm.DB)
return err
}
// 使用批量相关缓存清理,包含所有相关数据的缓存
// Use batch related cache cleaning, including a cache of all relevant data
defer func() {
if clearErr := m.BatchClearRelatedCache(ctx, data); clearErr != nil {
// 记录清理缓存错误,但不阻断删除操作
// Record cache cleaning errors, but do not block deletion operations
logger.Errorf("failed to clear related cache for user %d: %v", id, clearErr.Error())
}
}()
@@ -130,24 +132,11 @@ func (m *defaultUserModel) Delete(ctx context.Context, id int64, tx ...*gorm.DB)
if len(tx) > 0 {
db = tx[0]
}
// 删除用户相关的所有数据
// Soft deletion of user information without any processing of other information (Determine whether to allow login/subscription based on the user's deletion status)
if err := db.Model(&User{}).Where("`id` = ?", id).Delete(&User{}).Error; err != nil {
return err
}
if err := db.Model(&AuthMethods{}).Where("`user_id` = ?", id).Delete(&AuthMethods{}).Error; err != nil {
return err
}
if err := db.Model(&Subscribe{}).Where("`user_id` = ?", id).Delete(&Subscribe{}).Error; err != nil {
return err
}
if err := db.Model(&Device{}).Where("`user_id` = ?", id).Delete(&Device{}).Error; err != nil {
return err
}
return nil
})
}
+4
View File
@@ -62,6 +62,7 @@ type UserFilterParams struct {
SubscribeId *int64
UserSubscribeId *int64
Order string // Order by id, e.g., "desc"
Unscoped bool // Whether to include soft-deleted records
}
type customUserLogicModel interface {
@@ -148,6 +149,9 @@ func (m *customUserModel) QueryPageList(ctx context.Context, page, size int, fil
if filter.Order != "" {
conn = conn.Order(fmt.Sprintf("user.id %s", filter.Order))
}
if filter.Unscoped {
conn = conn.Unscoped()
}
}
return conn.Model(&User{}).Group("user.id").Count(&total).Limit(size).Offset((page-1)*size).Preload("UserDevices").Preload("AuthMethods", func(db *gorm.DB) *gorm.DB { return db.Order("user_auth_methods.auth_type desc") }).Find(&list).Error
})
+26 -24
View File
@@ -2,32 +2,35 @@ package user
import (
"time"
"gorm.io/gorm"
)
type User struct {
Id int64 `gorm:"primaryKey"`
Password string `gorm:"type:varchar(100);not null;comment:User Password"`
Algo string `gorm:"type:varchar(20);default:'default';comment:Encryption Algorithm"`
Salt string `gorm:"type:varchar(20);default:null;comment:Password Salt"`
Avatar string `gorm:"type:MEDIUMTEXT;comment:User Avatar"`
Balance int64 `gorm:"default:0;comment:User Balance"` // User Balance Amount
ReferCode string `gorm:"type:varchar(20);default:'';comment:Referral Code"`
RefererId int64 `gorm:"index:idx_referer;comment:Referrer ID"`
Commission int64 `gorm:"default:0;comment:Commission"` // Commission Amount
ReferralPercentage uint8 `gorm:"default:0;comment:Referral"` // Referral Percentage
OnlyFirstPurchase *bool `gorm:"default:true;not null;comment:Only First Purchase"` // Only First Purchase Referral
GiftAmount int64 `gorm:"default:0;comment:User Gift Amount"`
Enable *bool `gorm:"default:true;not null;comment:Is Account Enabled"`
IsAdmin *bool `gorm:"default:false;not null;comment:Is Admin"`
EnableBalanceNotify *bool `gorm:"default:false;not null;comment:Enable Balance Change Notifications"`
EnableLoginNotify *bool `gorm:"default:false;not null;comment:Enable Login Notifications"`
EnableSubscribeNotify *bool `gorm:"default:false;not null;comment:Enable Subscription Notifications"`
EnableTradeNotify *bool `gorm:"default:false;not null;comment:Enable Trade Notifications"`
AuthMethods []AuthMethods `gorm:"foreignKey:UserId;references:Id"`
UserDevices []Device `gorm:"foreignKey:UserId;references:Id"`
Rules string `gorm:"type:TEXT;comment:User Rules"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
Id int64 `gorm:"primaryKey"`
Password string `gorm:"type:varchar(100);not null;comment:User Password"`
Algo string `gorm:"type:varchar(20);default:'default';comment:Encryption Algorithm"`
Salt string `gorm:"type:varchar(20);default:null;comment:Password Salt"`
Avatar string `gorm:"type:MEDIUMTEXT;comment:User Avatar"`
Balance int64 `gorm:"default:0;comment:User Balance"` // User Balance Amount
ReferCode string `gorm:"type:varchar(20);default:'';comment:Referral Code"`
RefererId int64 `gorm:"index:idx_referer;comment:Referrer ID"`
Commission int64 `gorm:"default:0;comment:Commission"` // Commission Amount
ReferralPercentage uint8 `gorm:"default:0;comment:Referral"` // Referral Percentage
OnlyFirstPurchase *bool `gorm:"default:true;not null;comment:Only First Purchase"` // Only First Purchase Referral
GiftAmount int64 `gorm:"default:0;comment:User Gift Amount"`
Enable *bool `gorm:"default:true;not null;comment:Is Account Enabled"`
IsAdmin *bool `gorm:"default:false;not null;comment:Is Admin"`
EnableBalanceNotify *bool `gorm:"default:false;not null;comment:Enable Balance Change Notifications"`
EnableLoginNotify *bool `gorm:"default:false;not null;comment:Enable Login Notifications"`
EnableSubscribeNotify *bool `gorm:"default:false;not null;comment:Enable Subscription Notifications"`
EnableTradeNotify *bool `gorm:"default:false;not null;comment:Enable Trade Notifications"`
AuthMethods []AuthMethods `gorm:"foreignKey:UserId;references:Id"`
UserDevices []Device `gorm:"foreignKey:UserId;references:Id"`
Rules string `gorm:"type:TEXT;comment:User Rules"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:Deletion Time"`
}
func (*User) TableName() string {
@@ -49,7 +52,6 @@ type Subscribe struct {
Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"`
UUID string `gorm:"type:varchar(255);unique;index:idx_uuid;default:'';comment:UUID"`
Status uint8 `gorm:"type:tinyint(1);default:0;comment:Subscription Status: 0: Pending 1: Active 2: Finished 3: Expired 4: Deducted"`
Note string `gorm:"type:varchar(500);default:'';comment:User note for subscription"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}