init: 1.0.0

This commit is contained in:
Chang lue Tsen
2025-04-25 12:08:29 +09:00
commit 8addcc584b
1031 changed files with 76472 additions and 0 deletions
+130
View File
@@ -0,0 +1,130 @@
package server
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/internal/config"
"github.com/perfect-panel/ppanel-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) error
FindOne(ctx context.Context, id int64) (*Server, error)
Update(ctx context.Context, data *Server) error
Delete(ctx context.Context, id int64) 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)
cacheKeys := []string{
ServerIdKey,
detailsKey,
configIdKey,
}
return cacheKeys
}
func (m *defaultServerModel) Insert(ctx context.Context, data *Server) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
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) 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 {
db := conn
return db.Save(data).Error
}, m.getCacheKeys(old)...)
return err
}
func (m *defaultServerModel) Delete(ctx context.Context, id int64) 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 {
db := conn
return db.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)
}
+241
View File
@@ -0,0 +1,241 @@
package server
import (
"context"
"fmt"
"github.com/perfect-panel/ppanel-server/internal/config"
"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)
}
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)
return m.DelCacheCtx(ctx, serverIdKey, configKey)
}
// 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 {
conn = conn.Where("group_id IN ?", groupId)
}
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 ?", "%"+filter.Search+"%", "%"+filter.Search+"%")
}
if filter.Tag != "" {
query = query.Where("tag LIKE ?", "%"+filter.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
}
+210
View File
@@ -0,0 +1,210 @@
package server
import (
"time"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"gorm.io/gorm"
)
const (
RelayModeNone = "none"
RelayModeAll = "all"
RelayModeRandom = "random"
)
type ServerFilter struct {
Id int64
Tag string
Group int64
Search string
Page int
Size int
}
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
}
// 删除后重新排序,防止因 sort 缺口导致问题
if err := reorderSort(tx); err != nil {
return err
}
return nil
}
func (s *Server) BeforeUpdate(tx *gorm.DB) error {
logger.Debugf("[Server] BeforeUpdate")
var count int64
if err := tx.Model(&Server{}).Where("sort = ? AND id != ?", s.Sort, s.Id).Count(&count).Error; err != nil {
return err
}
if count > 0 {
logger.Debugf("[Server] Duplicate sort found, reordering...")
if err := reorderSort(tx); err != nil {
return err
}
}
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"`
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"`
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"`
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.Model(&Server{}).Order("sort ASC").Find(&servers).Error; err != nil {
return err
}
for i, server := range servers {
newSort := int64(i + 1)
if server.Sort != newSort {
if err := tx.Model(&Server{}).
Where("id = ?", server.Id).
Update("sort", newSort).Error; err != nil {
return err
}
}
}
return nil
}