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
+21
View File
@@ -0,0 +1,21 @@
package ads
import "time"
type Ads struct {
Id int64 `gorm:"primaryKey"`
Title string `gorm:"type:varchar(255);default:'';not null;comment:Ads title"`
Type string `gorm:"type:varchar(255);default:'';not null;comment:Ads type"`
Content string `gorm:"type:text;comment:Ads content"`
Description string `gorm:"type:text;comment:Ads descriptor"`
TargetURL string `gorm:"type:varchar(512);default:'';comment:Ads target url"`
StartTime time.Time `gorm:"type:datetime;comment:Ads start time"`
EndTime time.Time `gorm:"type:datetime;comment:Ads end time"`
Status int `gorm:"type:TINYINT;default:0;comment:Ads status,0 disable,1 enable"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Ads) TableName() string {
return "ads"
}
+112
View File
@@ -0,0 +1,112 @@
package ads
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customAdsModel)(nil)
var (
cacheAdsIdPrefix = "cache:ads:id:"
)
type (
Model interface {
adsModel
customAdsLogicModel
}
adsModel interface {
Insert(ctx context.Context, data *Ads) error
FindOne(ctx context.Context, id int64) (*Ads, error)
Update(ctx context.Context, data *Ads) error
Delete(ctx context.Context, id int64) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customAdsModel struct {
*defaultAdsModel
}
defaultAdsModel struct {
cache.CachedConn
table string
}
)
func newAdsModel(db *gorm.DB, c *redis.Client) *defaultAdsModel {
return &defaultAdsModel{
CachedConn: cache.NewConn(db, c),
table: "`ads`",
}
}
//nolint:unused
func (m *defaultAdsModel) batchGetCacheKeys(ads ...*Ads) []string {
var keys []string
for _, ad := range ads {
keys = append(keys, m.getCacheKeys(ad)...)
}
return keys
}
func (m *defaultAdsModel) getCacheKeys(data *Ads) []string {
if data == nil {
return []string{}
}
adsIdKey := fmt.Sprintf("%s%v", cacheAdsIdPrefix, data.Id)
cacheKeys := []string{
adsIdKey,
}
return cacheKeys
}
func (m *defaultAdsModel) Insert(ctx context.Context, data *Ads) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(&data).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultAdsModel) FindOne(ctx context.Context, id int64) (*Ads, error) {
AdsIdKey := fmt.Sprintf("%s%v", cacheAdsIdPrefix, id)
var resp Ads
err := m.QueryCtx(ctx, &resp, AdsIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Ads{}).Where("`id` = ?", id).First(&resp).Error
})
return &resp, err
}
func (m *defaultAdsModel) Update(ctx context.Context, data *Ads) 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 *defaultAdsModel) 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(&Ads{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultAdsModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+41
View File
@@ -0,0 +1,41 @@
package ads
import (
"context"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type customAdsLogicModel interface {
GetAdsListByPage(ctx context.Context, page, size int, filter Filter) (int64, []*Ads, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customAdsModel{
defaultAdsModel: newAdsModel(conn, c),
}
}
type Filter struct {
Status *int
Search string
}
// GetAdsListByPage get ads list by page
func (m *customAdsModel) GetAdsListByPage(ctx context.Context, page, size int, filter Filter) (int64, []*Ads, error) {
var list []*Ads
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
conn = conn.Model(&Ads{})
if filter.Status != nil {
conn = conn.Where("`status` = ?", *filter.Status)
}
if filter.Search != "" {
conn = conn.Where("`title` LIKE ? OR `content` LIKE ?", "%"+filter.Search+"%", "%"+filter.Search+"%")
}
return conn.Count(&total).Offset((page - 1) * size).Limit(size).Find(v).Error
})
return total, list, err
}
@@ -0,0 +1,18 @@
package announcement
import "time"
type Announcement struct {
Id int64 `gorm:"primaryKey"`
Title string `gorm:"type:varchar(255);not null;default:'';comment:Title"`
Content string `gorm:"type:text;comment:Content"`
Show *bool `gorm:"type:tinyint(1);not null;default:0;comment:Show"`
Pinned *bool `gorm:"type:tinyint(1);not null;default:0;comment:Pinned"`
Popup *bool `gorm:"type:tinyint(1);not null;default:0;comment:Popup"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Announcement) TableName() string {
return "announcement"
}
+117
View File
@@ -0,0 +1,117 @@
package announcement
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customAnnouncementModel)(nil)
var (
cacheAnnouncementIdPrefix = "cache:announcement:id:"
)
type (
Model interface {
announcementModel
customAnnouncementLogicModel
}
announcementModel interface {
Insert(ctx context.Context, data *Announcement) error
FindOne(ctx context.Context, id int64) (*Announcement, error)
Update(ctx context.Context, data *Announcement) error
Delete(ctx context.Context, id int64) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customAnnouncementModel struct {
*defaultAnnouncementModel
}
defaultAnnouncementModel struct {
cache.CachedConn
table string
}
)
func newAnnouncementModel(db *gorm.DB, c *redis.Client) *defaultAnnouncementModel {
return &defaultAnnouncementModel{
CachedConn: cache.NewConn(db, c),
table: "`announcement`",
}
}
//nolint:unused
func (m *defaultAnnouncementModel) batchGetCacheKeys(Announcements ...*Announcement) []string {
var keys []string
for _, announcement := range Announcements {
keys = append(keys, m.getCacheKeys(announcement)...)
}
return keys
}
func (m *defaultAnnouncementModel) getCacheKeys(data *Announcement) []string {
if data == nil {
return []string{}
}
announcementIdKey := fmt.Sprintf("%s%v", cacheAnnouncementIdPrefix, data.Id)
cacheKeys := []string{
announcementIdKey,
}
return cacheKeys
}
func (m *defaultAnnouncementModel) Insert(ctx context.Context, data *Announcement) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(&data).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultAnnouncementModel) FindOne(ctx context.Context, id int64) (*Announcement, error) {
AnnouncementIdKey := fmt.Sprintf("%s%v", cacheAnnouncementIdPrefix, id)
var resp Announcement
err := m.QueryCtx(ctx, &resp, AnnouncementIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Announcement{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultAnnouncementModel) Update(ctx context.Context, data *Announcement) 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 *defaultAnnouncementModel) 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(&Announcement{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultAnnouncementModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+49
View File
@@ -0,0 +1,49 @@
package announcement
import (
"context"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type customAnnouncementLogicModel interface {
GetAnnouncementListByPage(ctx context.Context, page, size int, filter Filter) (int64, []*Announcement, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customAnnouncementModel{
defaultAnnouncementModel: newAnnouncementModel(conn, c),
}
}
type Filter struct {
Show *bool
Pinned *bool
Popup *bool
Search string
}
// GetAnnouncementListByPage get announcement list by page
func (m *customAnnouncementModel) GetAnnouncementListByPage(ctx context.Context, page, size int, filter Filter) (int64, []*Announcement, error) {
var list []*Announcement
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
conn = conn.Model(&Announcement{})
if filter.Show != nil {
conn = conn.Where("`show` = ?", *filter.Show)
}
if filter.Pinned != nil {
conn = conn.Where("`pinned` = ?", *filter.Pinned)
}
if filter.Popup != nil {
conn = conn.Where("`popup` = ?", *filter.Popup)
}
if filter.Search != "" {
conn = conn.Where("`title` LIKE ? OR `content` LIKE ?", "%"+filter.Search+"%", "%"+filter.Search+"%")
}
return conn.Count(&total).Offset((page - 1) * size).Limit(size).Find(v).Error
})
return total, list, err
}
+54
View File
@@ -0,0 +1,54 @@
package application
import (
"time"
)
type Application struct {
Id int64 `gorm:"primary_key"`
Name string `gorm:"type:varchar(255);default:'';not null;comment:应用名称"`
Icon string `gorm:"type:text;not null;comment:应用图标"`
Description string `gorm:"type:text;comment:更新描述"`
SubscribeType string `gorm:"type:varchar(50);default:'';not null;comment:订阅类型"`
ApplicationVersions []ApplicationVersion
CreatedAt time.Time `gorm:"<-:create;comment:创建时间"`
UpdatedAt time.Time `gorm:"comment:更新时间"`
}
func (Application) TableName() string {
return "application"
}
type ApplicationVersion struct {
Id int64 `gorm:"primary_key"`
Url string `gorm:"type:varchar(255);default:'';not null;comment:应用地址"`
Version string `gorm:"type:varchar(255);default:'';not null;comment:应用版本"`
Platform string `gorm:"type:varchar(50);default:'';not null;comment:应用平台"`
IsDefault bool `gorm:"type:tinyint(1);not null;default:0;comment:默认版本"`
Description string `gorm:"type:text;comment:更新描述"`
ApplicationId int64 `gorm:"comment:所属应用"`
CreatedAt time.Time `gorm:"<-:create;comment:创建时间"`
UpdatedAt time.Time `gorm:"comment:更新时间"`
}
func (ApplicationVersion) TableName() string {
return "application_version"
}
type ApplicationConfig struct {
Id int64 `gorm:"primary_key"`
AppId int64 `gorm:"type:int;not null;default:0;comment:App id"`
EncryptionKey string `gorm:"type:text;comment:Encryption Key"`
EncryptionMethod string `gorm:"type:varchar(255);comment:Encryption Method"`
Domains string `gorm:"type:text;comment:Domains"`
StartupPicture string `gorm:"type:text;comment:Startup Picture"`
StartupPictureSkipTime int64 `gorm:"type:int;not null;default:0;comment:Startup Picture Skip Time"`
InvitationLink string `gorm:"type:text;comment:Invitation Link"`
KrWebsiteId string `gorm:"type:varchar(255);default:'';comment:Kr Website ID"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (ApplicationConfig) TableName() string {
return "application_config"
}
+245
View File
@@ -0,0 +1,245 @@
package application
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 = (*customApplicationModel)(nil)
var (
cacheApplicationIdPrefix = "cache:application:id:"
cacheApplicationConfigIdPrefix = "cache:application:config:id:"
cacheApplicationVersionIdPrefix = "cache:application:version:id:"
)
type (
Model interface {
applicationModel
customApplicationLogicModel
}
applicationModel interface {
Insert(ctx context.Context, data *Application) error
FindOne(ctx context.Context, id int64) (*Application, error)
Update(ctx context.Context, data *Application) error
Delete(ctx context.Context, id int64) error
InsertVersion(ctx context.Context, data *ApplicationVersion) error
FindOneVersion(ctx context.Context, id int64) (*ApplicationVersion, error)
UpdateVersion(ctx context.Context, data *ApplicationVersion) error
InsertConfig(ctx context.Context, data *ApplicationConfig) error
FindOneConfig(ctx context.Context, id int64) (*ApplicationConfig, error)
UpdateConfig(ctx context.Context, data *ApplicationConfig) error
DeleteVersion(ctx context.Context, id int64) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customApplicationModel struct {
*defaultApplicationModel
}
defaultApplicationModel struct {
cache.CachedConn
table string
}
)
func newApplicationModel(db *gorm.DB, c *redis.Client) *defaultApplicationModel {
return &defaultApplicationModel{
CachedConn: cache.NewConn(db, c),
table: "`Application`",
}
}
func (m *defaultApplicationModel) getCacheKeys(data *Application) []string {
if data == nil {
return []string{}
}
ApplicationIdKey := fmt.Sprintf("%s%v", cacheApplicationIdPrefix, data.Id)
cacheKeys := []string{
ApplicationIdKey,
config.ApplicationKey,
}
return cacheKeys
}
func (m *defaultApplicationModel) Insert(ctx context.Context, data *Application) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(&data).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultApplicationModel) FindOne(ctx context.Context, id int64) (*Application, error) {
ApplicationIdKey := fmt.Sprintf("%s%v", cacheApplicationIdPrefix, id)
var resp Application
err := m.QueryCtx(ctx, &resp, ApplicationIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Application{}).Preload("ApplicationVersions").Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultApplicationModel) Update(ctx context.Context, data *Application) 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 *defaultApplicationModel) 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
err = db.Where("application_id = ?", id).Delete(&ApplicationVersion{}).Error
if err != nil {
return err
}
return db.Delete(&Application{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultApplicationModel) getVersionCacheKeys(data *ApplicationVersion) []string {
if data == nil {
return []string{}
}
ApplicationVersionIdKey := fmt.Sprintf("%s%v", cacheApplicationVersionIdPrefix, data.Id)
cacheKeys := []string{
ApplicationVersionIdKey,
config.ApplicationKey,
}
return cacheKeys
}
func (m *defaultApplicationModel) getConfigCacheKeys(data *ApplicationConfig) []string {
if data == nil {
return []string{}
}
ApplicationConfigIdKey := fmt.Sprintf("%s%v", cacheApplicationConfigIdPrefix, data.Id)
cacheKeys := []string{
ApplicationConfigIdKey,
config.ApplicationKey,
}
return cacheKeys
}
func (m *defaultApplicationModel) InsertVersion(ctx context.Context, data *ApplicationVersion) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Transaction(func(tx *gorm.DB) error {
if data.IsDefault {
err := tx.Model(&ApplicationVersion{}).
Where("application_id = ? and platform = ? and default_version = ?", data.ApplicationId, data.Platform, data.IsDefault).
Updates(map[string]interface{}{"default_version": false}).Error
if err != nil {
return err
}
}
return tx.Create(&data).Error
})
}, m.getVersionCacheKeys(data)...)
return err
}
func (m *defaultApplicationModel) FindOneVersion(ctx context.Context, id int64) (*ApplicationVersion, error) {
ApplicationVersionIdKey := fmt.Sprintf("%s%v", cacheApplicationVersionIdPrefix, id)
var resp ApplicationVersion
err := m.QueryCtx(ctx, &resp, ApplicationVersionIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&ApplicationVersion{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultApplicationModel) UpdateVersion(ctx context.Context, data *ApplicationVersion) error {
old, err := m.FindOneVersion(ctx, data.Id)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
err = m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Transaction(func(tx *gorm.DB) error {
if data.IsDefault {
err := tx.Model(&ApplicationVersion{}).
Where("application_id = ? and platform = ? and default_version = ?", data.ApplicationId, data.Platform, data.IsDefault).
Updates(map[string]interface{}{"default_version": false}).Error
if err != nil {
return err
}
}
return tx.Save(data).Error
})
}, m.getVersionCacheKeys(old)...)
return err
}
func (m *defaultApplicationModel) InsertConfig(ctx context.Context, data *ApplicationConfig) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(&data).Error
}, m.getConfigCacheKeys(data)...)
return err
}
func (m *defaultApplicationModel) FindOneConfig(ctx context.Context, id int64) (*ApplicationConfig, error) {
ApplicationConfigIdKey := fmt.Sprintf("%s%v", cacheApplicationConfigIdPrefix, id)
var resp ApplicationConfig
err := m.QueryCtx(ctx, &resp, ApplicationConfigIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&ApplicationConfig{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultApplicationModel) UpdateConfig(ctx context.Context, data *ApplicationConfig) error {
old, err := m.FindOneConfig(ctx, data.Id)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
err = m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Save(data).Error
}, m.getConfigCacheKeys(old)...)
return err
}
func (m *defaultApplicationModel) DeleteVersion(ctx context.Context, id int64) error {
data, err := m.FindOneVersion(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(&ApplicationVersion{}, id).Error
}, m.getVersionCacheKeys(data)...)
return err
}
func (m *defaultApplicationModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+16
View File
@@ -0,0 +1,16 @@
package application
import (
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type customApplicationLogicModel interface {
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customApplicationModel{
defaultApplicationModel: newApplicationModel(conn, c),
}
}
+272
View File
@@ -0,0 +1,272 @@
package auth
import (
"encoding/json"
"time"
)
type Auth struct {
Id int64 `gorm:"primaryKey"`
Method string `gorm:"unique;type:varchar(255);not null;default:'';comment:platform"`
Config string `gorm:"type:text;not null;comment:Auth Configuration"`
Enabled *bool `gorm:"type:tinyint(1);not null;default:false;comment:Is Enabled"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Auth) TableName() string {
return "auth_method"
}
type AppleAuthConfig struct {
TeamID string `json:"team_id"`
KeyID string `json:"key_id"`
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURL string `json:"redirect_url"`
}
func (l *AppleAuthConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(AppleAuthConfig))
}
return string(bytes)
}
func (l *AppleAuthConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), &l)
}
type GoogleAuthConfig struct {
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURL string `json:"redirect_url"`
}
func (l *GoogleAuthConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(GoogleAuthConfig))
}
return string(bytes)
}
func (l *GoogleAuthConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), &l)
}
type GithubAuthConfig struct {
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURL string `json:"redirect_url"`
}
func (l *GithubAuthConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(GithubAuthConfig))
}
return string(bytes)
}
func (l *GithubAuthConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), &l)
}
type FacebookAuthConfig struct {
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURL string `json:"redirect_url"`
}
func (l *FacebookAuthConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(FacebookAuthConfig))
}
return string(bytes)
}
func (l *FacebookAuthConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), &l)
}
type TelegramAuthConfig struct {
BotToken string `json:"bot_token"`
EnableNotify bool `json:"enable_notify"`
WebHookDomain string `json:"webhook_domain"`
}
func (l *TelegramAuthConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(TelegramAuthConfig))
}
return string(bytes)
}
func (l *TelegramAuthConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), &l)
}
type EmailAuthConfig struct {
Platform string `json:"platform"`
PlatformConfig interface{} `json:"platform_config"`
EnableVerify bool `json:"enable_verify"`
EnableNotify bool `json:"enable_notify"`
EnableDomainSuffix bool `json:"enable_domain_suffix"`
DomainSuffixList string `json:"domain_suffix_list"`
VerifyEmailTemplate string `json:"verify_email_template"`
ExpirationEmailTemplate string `json:"expiration_email_template"`
MaintenanceEmailTemplate string `json:"maintenance_email_template"`
TrafficExceedEmailTemplate string `json:"traffic_exceed_email_template"`
}
func (l *EmailAuthConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(EmailAuthConfig))
}
return string(bytes)
}
func (l *EmailAuthConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), &l)
}
// SMTPConfig Email SMTP configuration
type SMTPConfig struct {
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
Pass string `json:"pass"`
From string `json:"from"`
SSL bool `json:"ssl"`
}
func (l *SMTPConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(SMTPConfig))
}
return string(bytes)
}
func (l *SMTPConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), &l)
}
type MobileAuthConfig struct {
Platform string `json:"platform"`
PlatformConfig interface{} `json:"platform_config"`
EnableWhitelist bool `json:"enable_whitelist"`
Whitelist []string `json:"whitelist"`
}
func (l *MobileAuthConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(MobileAuthConfig))
}
return string(bytes)
}
func (l *MobileAuthConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), &l)
}
type AlibabaCloudConfig struct {
Access string `json:"access"`
Secret string `json:"secret"`
SignName string `json:"sign_name"`
Endpoint string `json:"endpoint"`
TemplateCode string `json:"template_code"`
}
func (l *AlibabaCloudConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(AlibabaCloudConfig))
}
return string(bytes)
}
func (l *AlibabaCloudConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), l)
}
type SmsbaoConfig struct {
Access string `json:"access"`
Secret string `json:"secret"`
Template string `json:"template"`
}
func (l *SmsbaoConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(SmsbaoConfig))
}
return string(bytes)
}
func (l *SmsbaoConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), l)
}
type AbosendConfig struct {
ApiDomain string `json:"api_domain"`
Access string `json:"access"`
Secret string `json:"secret"`
Template string `json:"template"`
}
func (l *AbosendConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(AbosendConfig))
}
return string(bytes)
}
func (l *AbosendConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), l)
}
type TwilioConfig struct {
Access string `json:"access"`
Secret string `json:"secret"`
PhoneNumber string `json:"phone_number"`
Template string `json:"template"`
}
func (l *TwilioConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(TwilioConfig))
}
return string(bytes)
}
func (l *TwilioConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), l)
}
type DeviceConfig struct {
ShowAds bool `json:"show_ads"`
OnlyRealDevice bool `json:"only_real_device"`
EnableSecurity bool `json:"enable_security"`
SecuritySecret string `json:"security_secret"`
}
func (l *DeviceConfig) Marshal() string {
bytes, err := json.Marshal(l)
if err != nil {
bytes, _ = json.Marshal(new(DeviceConfig))
}
return string(bytes)
}
func (l *DeviceConfig) Unmarshal(data string) error {
return json.Unmarshal([]byte(data), l)
}
+30
View File
@@ -0,0 +1,30 @@
package auth
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestAlibabaCloudConfig_Marshal(t *testing.T) {
v := new(AlibabaCloudConfig)
t.Log(v.Marshal())
}
func TestAlibabaCloudConfig_Unmarshal(t *testing.T) {
cfg := AlibabaCloudConfig{
Access: "AccessKeyId",
Secret: "AccessKeySecret",
SignName: "SignName",
Endpoint: "Endpoint",
TemplateCode: "VerifyTemplateCode",
}
data := cfg.Marshal()
v := new(AlibabaCloudConfig)
err := v.Unmarshal(data)
if err != nil {
t.Fatal(err.Error())
}
assert.Equal(t, "AccessKeyId", v.Access)
}
+120
View File
@@ -0,0 +1,120 @@
package auth
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customAuthModel)(nil)
var (
cacheAuthIdPrefix = "cache:auth:id:"
cacheAuthMethodPrefix = "cache:auth:method:"
)
type (
Model interface {
authModel
customAuthLogicModel
}
authModel interface {
Insert(ctx context.Context, data *Auth) error
FindOne(ctx context.Context, id int64) (*Auth, error)
Update(ctx context.Context, data *Auth) error
Delete(ctx context.Context, id int64) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customAuthModel struct {
*defaultAuthModel
}
defaultAuthModel struct {
cache.CachedConn
table string
}
)
func newAuthModel(db *gorm.DB, c *redis.Client) *defaultAuthModel {
return &defaultAuthModel{
CachedConn: cache.NewConn(db, c),
table: "`auth_config`",
}
}
//nolint:unused
func (m *defaultAuthModel) batchGetCacheKeys(Auths ...*Auth) []string {
var keys []string
for _, auth := range Auths {
keys = append(keys, m.getCacheKeys(auth)...)
}
return keys
}
func (m *defaultAuthModel) getCacheKeys(data *Auth) []string {
if data == nil {
return []string{}
}
authIdKey := fmt.Sprintf("%s%v", cacheAuthIdPrefix, data.Id)
platformKey := fmt.Sprintf("%s%s", cacheAuthMethodPrefix, data.Method)
cacheKeys := []string{
authIdKey,
platformKey,
}
return cacheKeys
}
func (m *defaultAuthModel) Insert(ctx context.Context, data *Auth) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(&data).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultAuthModel) FindOne(ctx context.Context, id int64) (*Auth, error) {
AuthIdKey := fmt.Sprintf("%s%v", cacheAuthIdPrefix, id)
var resp Auth
err := m.QueryCtx(ctx, &resp, AuthIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Auth{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultAuthModel) Update(ctx context.Context, data *Auth) 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 *defaultAuthModel) 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(&Auth{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultAuthModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+60
View File
@@ -0,0 +1,60 @@
package auth
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type customAuthLogicModel interface {
GetAuthListByPage(ctx context.Context) ([]*Auth, error)
FindOneByMethod(ctx context.Context, platform string) (*Auth, error)
FindAll(ctx context.Context) ([]*Auth, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customAuthModel{
defaultAuthModel: newAuthModel(conn, c),
}
}
type Filter struct {
Show *bool
Pinned *bool
Popup *bool
Search string
}
// GetAuthListByPage get auth list by page
func (m *customAuthModel) GetAuthListByPage(ctx context.Context) ([]*Auth, error) {
var list []*Auth
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
conn = conn.Model(&Auth{})
return conn.Find(v).Error
})
return list, err
}
// FindOneByMethod find one by method
func (m *customAuthModel) FindOneByMethod(ctx context.Context, method string) (*Auth, error) {
key := fmt.Sprintf("%s%s", cacheAuthMethodPrefix, method)
var data Auth
err := m.QueryCtx(ctx, &data, key, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Auth{}).Where("method = ?", method).First(v).Error
})
return &data, err
}
// FindAll find all
func (m *customAuthModel) FindAll(ctx context.Context) ([]*Auth, error) {
var list []*Auth
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
conn = conn.Model(&Auth{})
return conn.Find(v).Error
})
return list, err
}
+52
View File
@@ -0,0 +1,52 @@
package cache
const (
// UserTodayUploadTrafficCacheKey 用户当日上传流量
UserTodayUploadTrafficCacheKey = "node:user_today_upload_traffic"
// UserTodayDownloadTrafficCacheKey 用户当日下载流量
UserTodayDownloadTrafficCacheKey = "node:user_today_download_traffic"
// UserTodayTotalTrafficCacheKey 用户当日总流量
UserTodayTotalTrafficCacheKey = "node:user_today_total_traffic"
// NodeTodayUploadTrafficCacheKey 节点当日上传流量
NodeTodayUploadTrafficCacheKey = "node:node_today_upload_traffic"
// NodeTodayDownloadTrafficCacheKey 节点当日下载流量
NodeTodayDownloadTrafficCacheKey = "node:node_today_download_traffic"
// NodeTodayTotalTrafficCacheKey 节点当日总流量
NodeTodayTotalTrafficCacheKey = "node:node_today_total_traffic"
// UserTodayUploadTrafficRankKey 用户当日上传流量排行榜
UserTodayUploadTrafficRankKey = "node:user_today_upload_traffic_rank"
// UserTodayDownloadTrafficRankKey 用户当日下载流量排行榜
UserTodayDownloadTrafficRankKey = "node:user_today_download_traffic_rank"
// UserTodayTotalTrafficRankKey 用户当日总流量排行榜
UserTodayTotalTrafficRankKey = "node:user_today_total_traffic_rank"
// NodeTodayUploadTrafficRankKey 节点当日上传流量排行榜
NodeTodayUploadTrafficRankKey = "node:node_today_upload_traffic_rank"
// NodeTodayDownloadTrafficRankKey 节点当日下载流量排行榜
NodeTodayDownloadTrafficRankKey = "node:node_today_download_traffic_rank"
// NodeTodayTotalTrafficRankKey 节点当日总流量排行榜
NodeTodayTotalTrafficRankKey = "node:node_today_total_traffic_rank"
// NodeOnlineUserCacheKey 节点在线用户
NodeOnlineUserCacheKey = "node:node_online_user:%d"
// UserOnlineIpCacheKey 用户在线IP
UserOnlineIpCacheKey = "node:user_online_ip:%d"
// AllNodeOnlineUserCacheKey 所有节点在线用户
AllNodeOnlineUserCacheKey = "node:all_node_online_user"
// NodeStatusCacheKey 节点状态
NodeStatusCacheKey = "node:status:%d"
// AllNodeDownloadTrafficCacheKey 所有节点下载流量
AllNodeDownloadTrafficCacheKey = "node:all_node_download_traffic"
// AllNodeUploadTrafficCacheKey 所有节点上传流量
AllNodeUploadTrafficCacheKey = "node:all_node_upload_traffic"
// YesterdayTotalTrafficRank 昨日节点总流量排行榜
YesterdayNodeTotalTrafficRank = "node:yesterday_total_traffic_rank"
// YesterdayUploadTrafficRank 昨日节点上传流量排行榜
YesterdayNodeUploadTrafficRank = "node:yesterday_upload_traffic_rank"
// YesterdayDownloadTrafficRank 昨日节点下载流量排行榜
YesterdayNodeDownloadTrafficRank = "node:yesterday_download_traffic_rank"
// YesterdayUserTotalTrafficRank 昨日用户总流量排行榜
YesterdayUserTotalTrafficRank = "node:yesterday_user_total_traffic_rank"
// YesterdayUserUploadTrafficRank 昨日用户上传流量排行榜
YesterdayUserUploadTrafficRank = "node:yesterday_user_upload_traffic_rank"
// YesterdayUserDownloadTrafficRank 昨日用户下载流量排行榜
YesterdayUserDownloadTrafficRank = "node:yesterday_user_download_traffic_rank"
)
+584
View File
@@ -0,0 +1,584 @@
package cache
import (
"context"
"encoding/json"
"fmt"
"strconv"
"sync"
"time"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/redis/go-redis/v9"
)
type NodeCacheClient struct {
*redis.Client
resetMutex sync.Mutex
}
func NewNodeCacheClient(rds *redis.Client) *NodeCacheClient {
return &NodeCacheClient{
Client: rds,
}
}
// AddOnlineUserIP adds user's online IP
func (c *NodeCacheClient) AddOnlineUserIP(ctx context.Context, users []NodeOnlineUser) error {
if len(users) == 0 {
// No users to add
return nil
}
// Use Pipeline to optimize Redis operations
pipe := c.Pipeline()
// Add user online IPs and clean up expired IPs for each user
for _, user := range users {
if user.SID <= 0 || user.IP == "" {
logger.Errorf("invalid user data: uid=%d, ip=%s", user.SID, user.IP)
continue
}
key := fmt.Sprintf(UserOnlineIpCacheKey, user.SID)
now := time.Now()
expireTime := now.Add(5 * time.Minute)
// Clean up expired user online IPs
pipe.ZRemRangeByScore(ctx, key, "0", fmt.Sprintf("%d", now.Unix()))
pipe.ZRemRangeByScore(ctx, AllNodeOnlineUserCacheKey, "0", fmt.Sprintf("%d", now.Unix()))
// Add or update user online IP
// XX: Only update elements that already exist
// NX: Only add new elements
_ = pipe.ZAdd(ctx, key, redis.Z{
Score: float64(expireTime.Unix()),
Member: user.IP,
}).Err()
_ = pipe.ZAdd(ctx, AllNodeOnlineUserCacheKey, redis.Z{
Score: float64(expireTime.Unix()),
Member: user.IP,
}).Err()
// Set key expiration to 5 minutes (slightly longer than IP expiration)
pipe.Expire(ctx, key, 5*time.Minute)
pipe.Expire(ctx, AllNodeOnlineUserCacheKey, 5*time.Minute)
}
// Execute all commands
_, err := pipe.Exec(ctx)
if err != nil {
return fmt.Errorf("failed to add node user online ip: %w", err)
}
return nil
}
// GetUserOnlineIp gets user's online IPs
func (c *NodeCacheClient) GetUserOnlineIp(ctx context.Context, uid int64) ([]string, error) {
if uid <= 0 {
return nil, fmt.Errorf("invalid parameters: uid=%d", uid)
}
// Get user's online IPs
ips, err := c.ZRevRangeByScore(ctx, fmt.Sprintf(UserOnlineIpCacheKey, uid), &redis.ZRangeBy{
Min: "0",
Max: fmt.Sprintf("%d", time.Now().Add(5*time.Minute).Unix()),
Offset: 0,
Count: 100,
}).Result()
if err != nil {
return nil, fmt.Errorf("failed to get user online ip: %w", err)
}
return ips, nil
}
// UpdateNodeOnlineUser updates node's online users and IPs
func (c *NodeCacheClient) UpdateNodeOnlineUser(ctx context.Context, nodeId int64, users []NodeOnlineUser) error {
if nodeId <= 0 || len(users) == 0 {
return fmt.Errorf("invalid parameters: nodeId=%d, users=%v", nodeId, users)
}
// Organize data
data := make(map[int64][]string)
for _, user := range users {
data[user.SID] = append(data[user.SID], user.IP)
}
value, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("failed to marshal data: %w", err)
}
c.Set(ctx, fmt.Sprintf(NodeOnlineUserCacheKey, nodeId), value, time.Minute*5)
return nil
}
// GetNodeOnlineUser gets node's online users and IPs
func (c *NodeCacheClient) GetNodeOnlineUser(ctx context.Context, nodeId int64) (map[int64][]string, error) {
if nodeId <= 0 {
return nil, fmt.Errorf("invalid parameters: nodeId=%d", nodeId)
}
value, err := c.Get(ctx, fmt.Sprintf(NodeOnlineUserCacheKey, nodeId)).Result()
if err != nil {
return nil, fmt.Errorf("failed to get node online user: %w", err)
}
var data map[int64][]string
if err := json.Unmarshal([]byte(value), &data); err != nil {
return nil, fmt.Errorf("failed to unmarshal data: %w", err)
}
return data, nil
}
// AddUserTodayTraffic Add user's today traffic
func (c *NodeCacheClient) AddUserTodayTraffic(ctx context.Context, uid int64, upload, download int64) error {
if uid <= 0 || upload <= 0 {
return fmt.Errorf("invalid parameters: uid=%d, upload=%d", uid, upload)
}
pipe := c.Pipeline()
// User's today upload traffic
pipe.HIncrBy(ctx, UserTodayUploadTrafficCacheKey, fmt.Sprintf("%d", uid), upload)
// User's today download traffic
pipe.HIncrBy(ctx, UserTodayDownloadTrafficCacheKey, fmt.Sprintf("%d", uid), download)
// User's today total traffic
pipe.HIncrBy(ctx, UserTodayTotalTrafficCacheKey, fmt.Sprintf("%d", uid), upload+download)
// User's today traffic ranking
pipe.ZIncrBy(ctx, UserTodayUploadTrafficRankKey, float64(upload), fmt.Sprintf("%d", uid))
pipe.ZIncrBy(ctx, UserTodayDownloadTrafficRankKey, float64(download), fmt.Sprintf("%d", uid))
pipe.ZIncrBy(ctx, UserTodayTotalTrafficRankKey, float64(upload+download), fmt.Sprintf("%d", uid))
// All node upload traffic
pipe.IncrBy(ctx, AllNodeUploadTrafficCacheKey, upload)
// All node download traffic
pipe.IncrBy(ctx, AllNodeDownloadTrafficCacheKey, download)
// Execute commands
_, err := pipe.Exec(ctx)
if err != nil {
return fmt.Errorf("failed to add user today upload traffic: %w", err)
}
return nil
}
// AddNodeTodayTraffic Add node's today traffic
func (c *NodeCacheClient) AddNodeTodayTraffic(ctx context.Context, nodeId int64, userTraffic []UserTraffic) error {
if nodeId <= 0 || len(userTraffic) == 0 {
return fmt.Errorf("invalid parameters: nodeId=%d, userTraffic=%v", nodeId, userTraffic)
}
pipe := c.Pipeline()
upload, download, total := c.calculateTraffic(userTraffic)
pipe.HIncrBy(ctx, NodeTodayUploadTrafficCacheKey, fmt.Sprintf("%d", nodeId), upload)
pipe.HIncrBy(ctx, NodeTodayDownloadTrafficCacheKey, fmt.Sprintf("%d", nodeId), download)
pipe.HIncrBy(ctx, NodeTodayTotalTrafficCacheKey, fmt.Sprintf("%d", nodeId), total)
pipe.ZIncrBy(ctx, NodeTodayUploadTrafficRankKey, float64(upload), fmt.Sprintf("%d", nodeId))
pipe.ZIncrBy(ctx, NodeTodayDownloadTrafficRankKey, float64(download), fmt.Sprintf("%d", nodeId))
pipe.ZIncrBy(ctx, NodeTodayTotalTrafficRankKey, float64(total), fmt.Sprintf("%d", nodeId))
// Execute commands
_, err := pipe.Exec(ctx)
if err != nil {
return fmt.Errorf("failed to add node today upload traffic: %w", err)
}
return nil
}
// Get user's traffic data
func (c *NodeCacheClient) getUserTrafficData(ctx context.Context, uid int64) (upload, download int64, err error) {
upload, err = c.HGet(ctx, UserTodayUploadTrafficCacheKey, fmt.Sprintf("%d", uid)).Int64()
if err != nil {
return 0, 0, fmt.Errorf("failed to get user today upload traffic: %w", err)
}
download, err = c.HGet(ctx, UserTodayDownloadTrafficCacheKey, fmt.Sprintf("%d", uid)).Int64()
if err != nil {
return 0, 0, fmt.Errorf("failed to get user today download traffic: %w", err)
}
return upload, download, nil
}
// Get node's traffic data
func (c *NodeCacheClient) getNodeTrafficData(ctx context.Context, nodeId int64) (upload, download int64, err error) {
upload, err = c.HGet(ctx, NodeTodayUploadTrafficCacheKey, fmt.Sprintf("%d", nodeId)).Int64()
if err != nil {
return 0, 0, fmt.Errorf("failed to get node today upload traffic: %w", err)
}
download, err = c.HGet(ctx, NodeTodayDownloadTrafficCacheKey, fmt.Sprintf("%d", nodeId)).Int64()
if err != nil {
return 0, 0, fmt.Errorf("failed to get node today download traffic: %w", err)
}
return upload, download, nil
}
// Parse ID
func (c *NodeCacheClient) parseID(member interface{}, idType string) (int64, error) {
id, err := strconv.ParseInt(member.(string), 10, 64)
if err != nil {
return 0, fmt.Errorf("failed to parse %s id %v: %w", idType, member, err)
}
return id, nil
}
// GetUserTodayTotalTrafficRank Get user's today total traffic ranking top N
func (c *NodeCacheClient) GetUserTodayTotalTrafficRank(ctx context.Context, n int64) ([]UserTodayTrafficRank, error) {
if n <= 0 {
return nil, fmt.Errorf("invalid parameters: n=%d", n)
}
data, err := c.ZRevRangeWithScores(ctx, UserTodayTotalTrafficRankKey, 0, n-1).Result()
if err != nil {
return nil, fmt.Errorf("failed to get user today total traffic rank: %w", err)
}
users := make([]UserTodayTrafficRank, 0, len(data))
for _, user := range data {
uid, err := c.parseID(user.Member, "user")
if err != nil {
logger.Errorf("%v", err)
continue
}
upload, download, err := c.getUserTrafficData(ctx, uid)
if err != nil {
logger.Errorf("%v", err)
continue
}
users = append(users, UserTodayTrafficRank{
SID: uid,
Upload: upload,
Download: download,
Total: int64(user.Score),
})
}
return users, nil
}
// GetNodeTodayTotalTrafficRank Get node's today total traffic ranking top N
func (c *NodeCacheClient) GetNodeTodayTotalTrafficRank(ctx context.Context, n int64) ([]NodeTodayTrafficRank, error) {
if n <= 0 {
return nil, fmt.Errorf("invalid parameters: n=%d", n)
}
data, err := c.ZRevRangeWithScores(ctx, NodeTodayTotalTrafficRankKey, 0, n-1).Result()
if err != nil {
return nil, fmt.Errorf("failed to get node today total traffic rank: %w", err)
}
nodes := make([]NodeTodayTrafficRank, 0, len(data))
for _, node := range data {
nodeId, err := c.parseID(node.Member, "node")
if err != nil {
logger.Errorf("%v", err)
continue
}
upload, download, err := c.getNodeTrafficData(ctx, nodeId)
if err != nil {
logger.Errorf("%v", err)
continue
}
nodes = append(nodes, NodeTodayTrafficRank{
ID: nodeId,
Upload: upload,
Download: download,
Total: int64(node.Score),
})
}
return nodes, nil
}
// GetUserTodayUploadTrafficRank Get user's today upload traffic ranking top N
func (c *NodeCacheClient) GetUserTodayUploadTrafficRank(ctx context.Context, n int64) ([]UserTodayTrafficRank, error) {
if n <= 0 {
return nil, fmt.Errorf("invalid parameters: n=%d", n)
}
data, err := c.ZRevRangeWithScores(ctx, UserTodayUploadTrafficRankKey, 0, n-1).Result()
if err != nil {
return nil, fmt.Errorf("failed to get user today upload traffic rank: %w", err)
}
users := make([]UserTodayTrafficRank, 0, len(data))
for _, user := range data {
uid, err := c.parseID(user.Member, "user")
if err != nil {
logger.Errorf("%v", err)
continue
}
upload, download, err := c.getUserTrafficData(ctx, uid)
if err != nil {
logger.Errorf("%v", err)
continue
}
users = append(users, UserTodayTrafficRank{
SID: uid,
Upload: upload,
Download: download,
Total: int64(user.Score),
})
}
return users, nil
}
// GetUserTodayDownloadTrafficRank Get user's today download traffic ranking top N
func (c *NodeCacheClient) GetUserTodayDownloadTrafficRank(ctx context.Context, n int64) ([]UserTodayTrafficRank, error) {
if n <= 0 {
return nil, fmt.Errorf("invalid parameters: n=%d", n)
}
data, err := c.ZRevRangeWithScores(ctx, UserTodayDownloadTrafficRankKey, 0, n-1).Result()
if err != nil {
return nil, fmt.Errorf("failed to get user today download traffic rank: %w", err)
}
users := make([]UserTodayTrafficRank, 0, len(data))
for _, user := range data {
uid, err := c.parseID(user.Member, "user")
if err != nil {
logger.Errorf("%v", err)
continue
}
upload, download, err := c.getUserTrafficData(ctx, uid)
if err != nil {
logger.Errorf("%v", err)
continue
}
users = append(users, UserTodayTrafficRank{
SID: uid,
Upload: upload,
Download: download,
Total: int64(user.Score),
})
}
return users, nil
}
// GetNodeTodayUploadTrafficRank Get node's today upload traffic ranking top N
func (c *NodeCacheClient) GetNodeTodayUploadTrafficRank(ctx context.Context, n int64) ([]NodeTodayTrafficRank, error) {
if n <= 0 {
return nil, fmt.Errorf("invalid parameters: n=%d", n)
}
data, err := c.ZRevRangeWithScores(ctx, NodeTodayUploadTrafficRankKey, 0, n-1).Result()
if err != nil {
return nil, fmt.Errorf("failed to get node today upload traffic rank: %w", err)
}
nodes := make([]NodeTodayTrafficRank, 0, len(data))
for _, node := range data {
nodeId, err := c.parseID(node.Member, "node")
if err != nil {
logger.Errorf("%v", err)
continue
}
upload, download, err := c.getNodeTrafficData(ctx, nodeId)
if err != nil {
logger.Errorf("%v", err)
continue
}
nodes = append(nodes, NodeTodayTrafficRank{
ID: nodeId,
Upload: upload,
Download: download,
Total: int64(node.Score),
})
}
return nodes, nil
}
// GetNodeTodayDownloadTrafficRank Get node's today download traffic ranking top N
func (c *NodeCacheClient) GetNodeTodayDownloadTrafficRank(ctx context.Context, n int64) ([]NodeTodayTrafficRank, error) {
if n <= 0 {
return nil, fmt.Errorf("invalid parameters: n=%d", n)
}
data, err := c.ZRevRangeWithScores(ctx, NodeTodayDownloadTrafficRankKey, 0, n-1).Result()
if err != nil {
return nil, fmt.Errorf("failed to get node today download traffic rank: %w", err)
}
nodes := make([]NodeTodayTrafficRank, 0, len(data))
for _, node := range data {
nodeId, err := c.parseID(node.Member, "node")
if err != nil {
logger.Errorf("%v", err)
continue
}
upload, download, err := c.getNodeTrafficData(ctx, nodeId)
if err != nil {
logger.Errorf("%v", err)
continue
}
nodes = append(nodes, NodeTodayTrafficRank{
ID: nodeId,
Upload: upload,
Download: download,
Total: int64(node.Score),
})
}
return nodes, nil
}
// ResetTodayTrafficData Reset today's traffic data
func (c *NodeCacheClient) ResetTodayTrafficData(ctx context.Context) error {
c.resetMutex.Lock()
defer c.resetMutex.Unlock()
pipe := c.Pipeline()
pipe.Del(ctx, UserTodayUploadTrafficCacheKey)
pipe.Del(ctx, UserTodayDownloadTrafficCacheKey)
pipe.Del(ctx, UserTodayTotalTrafficCacheKey)
pipe.Del(ctx, NodeTodayUploadTrafficCacheKey)
pipe.Del(ctx, NodeTodayDownloadTrafficCacheKey)
pipe.Del(ctx, NodeTodayTotalTrafficCacheKey)
pipe.Del(ctx, UserTodayUploadTrafficRankKey)
pipe.Del(ctx, UserTodayDownloadTrafficRankKey)
pipe.Del(ctx, UserTodayTotalTrafficRankKey)
pipe.Del(ctx, NodeTodayUploadTrafficRankKey)
pipe.Del(ctx, NodeTodayDownloadTrafficRankKey)
pipe.Del(ctx, NodeTodayTotalTrafficRankKey)
pipe.Del(ctx, AllNodeDownloadTrafficCacheKey)
pipe.Del(ctx, AllNodeUploadTrafficCacheKey)
_, err := pipe.Exec(ctx)
if err != nil {
return fmt.Errorf("failed to reset today traffic data: %w", err)
}
return nil
}
// Calculate traffic
func (c *NodeCacheClient) calculateTraffic(data []UserTraffic) (upload, download, total int64) {
for _, userTraffic := range data {
upload += userTraffic.Upload
download += userTraffic.Download
total += userTraffic.Upload + userTraffic.Download
}
return upload, download, total
}
// GetAllNodeOnlineUser Get all node online user
func (c *NodeCacheClient) GetAllNodeOnlineUser(ctx context.Context) ([]string, error) {
users, err := c.ZRevRange(ctx, AllNodeOnlineUserCacheKey, 0, -1).Result()
if err != nil {
return nil, fmt.Errorf("failed to get all node online user: %w", err)
}
return users, nil
}
// UpdateNodeStatus Update node status
func (c *NodeCacheClient) UpdateNodeStatus(ctx context.Context, nodeId int64, status NodeStatus) error {
// 参数验证
if nodeId <= 0 {
return fmt.Errorf("invalid node id: %d", nodeId)
}
// 验证状态数据
if status.UpdatedAt <= 0 {
return fmt.Errorf("invalid status data: updated_at=%d", status.UpdatedAt)
}
// 序列化状态数据
value, err := json.Marshal(status)
if err != nil {
return fmt.Errorf("failed to marshal node status: %w", err)
}
// 使用 Pipeline 优化性能
pipe := c.Pipeline()
// 设置状态数据
pipe.Set(ctx, fmt.Sprintf(NodeStatusCacheKey, nodeId), value, time.Minute*5)
// 执行命令
_, err = pipe.Exec(ctx)
if err != nil {
return fmt.Errorf("failed to update node status: %w", err)
}
return nil
}
// GetNodeStatus Get node status
func (c *NodeCacheClient) GetNodeStatus(ctx context.Context, nodeId int64) (NodeStatus, error) {
status, err := c.Get(ctx, fmt.Sprintf(NodeStatusCacheKey, nodeId)).Result()
if err != nil {
return NodeStatus{}, fmt.Errorf("failed to get node status: %w", err)
}
var nodeStatus NodeStatus
if err := json.Unmarshal([]byte(status), &nodeStatus); err != nil {
return NodeStatus{}, fmt.Errorf("failed to unmarshal node status: %w", err)
}
return nodeStatus, nil
}
// GetOnlineNodeStatusCount Get Online Node Status Count
func (c *NodeCacheClient) GetOnlineNodeStatusCount(ctx context.Context) (int64, error) {
// 获取所有节点Key
keys, err := c.Keys(ctx, "node:status:*").Result()
if err != nil {
return 0, fmt.Errorf("failed to get all node status keys: %w", err)
}
var count int64
for _, key := range keys {
status, err := c.Get(ctx, key).Result()
if err != nil {
logger.Errorf("failed to get node status: %v", err.Error())
continue
}
if status != "" {
count++
}
}
return count, nil
}
// GetAllNodeUploadTraffic Get all node upload traffic
func (c *NodeCacheClient) GetAllNodeUploadTraffic(ctx context.Context) (int64, error) {
upload, err := c.Get(ctx, AllNodeUploadTrafficCacheKey).Int64()
if err != nil {
return 0, fmt.Errorf("failed to get all node upload traffic: %w", err)
}
return upload, nil
}
// GetAllNodeDownloadTraffic Get all node download traffic
func (c *NodeCacheClient) GetAllNodeDownloadTraffic(ctx context.Context) (int64, error) {
download, err := c.Get(ctx, AllNodeDownloadTrafficCacheKey).Int64()
if err != nil {
return 0, fmt.Errorf("failed to get all node download traffic: %w", err)
}
return download, nil
}
// UpdateYesterdayNodeTotalTrafficRank Update yesterday node total traffic rank
func (c *NodeCacheClient) UpdateYesterdayNodeTotalTrafficRank(ctx context.Context, nodes []NodeTodayTrafficRank) error {
expireAt := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Local).Add(time.Hour * 24)
t := time.Until(expireAt)
pipe := c.Pipeline()
value, _ := json.Marshal(nodes)
pipe.Set(ctx, YesterdayNodeTotalTrafficRank, value, t)
_, err := pipe.Exec(ctx)
if err != nil {
return fmt.Errorf("failed to update yesterday node total traffic rank: %w", err)
}
return nil
}
// UpdateYesterdayUserTotalTrafficRank Update yesterday user total traffic rank
func (c *NodeCacheClient) UpdateYesterdayUserTotalTrafficRank(ctx context.Context, users []UserTodayTrafficRank) error {
expireAt := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Local).Add(time.Hour * 24)
t := time.Until(expireAt)
pipe := c.Pipeline()
value, _ := json.Marshal(users)
pipe.Set(ctx, YesterdayUserTotalTrafficRank, value, t)
_, err := pipe.Exec(ctx)
if err != nil {
return fmt.Errorf("failed to update yesterday user total traffic rank: %w", err)
}
return nil
}
// GetYesterdayNodeTotalTrafficRank Get yesterday node total traffic rank
func (c *NodeCacheClient) GetYesterdayNodeTotalTrafficRank(ctx context.Context) ([]NodeTodayTrafficRank, error) {
value, err := c.Get(ctx, YesterdayNodeTotalTrafficRank).Result()
if err != nil {
return nil, fmt.Errorf("failed to get yesterday node total traffic rank: %w", err)
}
var nodes []NodeTodayTrafficRank
if err := json.Unmarshal([]byte(value), &nodes); err != nil {
return nil, fmt.Errorf("failed to unmarshal yesterday node total traffic rank: %w", err)
}
return nodes, nil
}
// GetYesterdayUserTotalTrafficRank Get yesterday user total traffic rank
func (c *NodeCacheClient) GetYesterdayUserTotalTrafficRank(ctx context.Context) ([]UserTodayTrafficRank, error) {
value, err := c.Get(ctx, YesterdayUserTotalTrafficRank).Result()
if err != nil {
return nil, fmt.Errorf("failed to get yesterday user total traffic rank: %w", err)
}
var users []UserTodayTrafficRank
if err := json.Unmarshal([]byte(value), &users); err != nil {
return nil, fmt.Errorf("failed to unmarshal yesterday user total traffic rank: %w", err)
}
return users, nil
}
+575
View File
@@ -0,0 +1,575 @@
package cache
import (
"context"
"encoding/json"
"fmt"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Create a test Redis client
func newTestRedisClient(t *testing.T) *redis.Client {
mr, err := miniredis.Run()
require.NoError(t, err)
client := redis.NewClient(&redis.Options{
Addr: mr.Addr(),
})
require.NoError(t, client.Ping(context.Background()).Err())
return client
}
// Clean up test data
func cleanupTestData(t *testing.T, client *redis.Client) {
ctx := context.Background()
keys := []string{
UserTodayUploadTrafficCacheKey,
UserTodayDownloadTrafficCacheKey,
UserTodayTotalTrafficCacheKey,
NodeTodayUploadTrafficCacheKey,
NodeTodayDownloadTrafficCacheKey,
NodeTodayTotalTrafficCacheKey,
UserTodayUploadTrafficRankKey,
UserTodayDownloadTrafficRankKey,
UserTodayTotalTrafficRankKey,
NodeTodayUploadTrafficRankKey,
NodeTodayDownloadTrafficRankKey,
NodeTodayTotalTrafficRankKey,
}
// Clean up all cache keys
for _, key := range keys {
require.NoError(t, client.Del(ctx, key).Err())
}
// Clean up user online IP cache
for uid := int64(1); uid <= 3; uid++ {
require.NoError(t, client.Del(ctx, fmt.Sprintf(UserOnlineIpCacheKey, uid)).Err())
}
// Clean up node online user cache
for nodeId := int64(1); nodeId <= 3; nodeId++ {
require.NoError(t, client.Del(ctx, fmt.Sprintf(NodeOnlineUserCacheKey, nodeId)).Err())
}
}
func TestNodeCacheClient_AddUserTodayTraffic(t *testing.T) {
client := newTestRedisClient(t)
defer cleanupTestData(t, client)
cache := NewNodeCacheClient(client)
ctx := context.Background()
tests := []struct {
name string
uid int64
upload int64
download int64
wantErr bool
}{
{
name: "Add traffic normally",
uid: 1,
upload: 100,
download: 200,
wantErr: false,
},
{
name: "Invalid SID",
uid: 0,
upload: 100,
download: 200,
wantErr: true,
},
{
name: "Invalid upload traffic",
uid: 1,
upload: 0,
download: 200,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := cache.AddUserTodayTraffic(ctx, tt.uid, tt.upload, tt.download)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
// Verify data is added correctly
upload, err := client.HGet(ctx, UserTodayUploadTrafficCacheKey, "1").Int64()
assert.NoError(t, err)
assert.Equal(t, tt.upload, upload)
download, err := client.HGet(ctx, UserTodayDownloadTrafficCacheKey, "1").Int64()
assert.NoError(t, err)
assert.Equal(t, tt.download, download)
})
}
}
func TestNodeCacheClient_AddNodeTodayTraffic(t *testing.T) {
client := newTestRedisClient(t)
defer cleanupTestData(t, client)
cache := NewNodeCacheClient(client)
ctx := context.Background()
tests := []struct {
name string
nodeId int64
userTraffic []UserTraffic
wantErr bool
}{
{
name: "Add node traffic normally",
nodeId: 1,
userTraffic: []UserTraffic{
{UID: 1, Upload: 100, Download: 200},
{UID: 2, Upload: 300, Download: 400},
},
wantErr: false,
},
{
name: "Invalid node ID",
nodeId: 0,
userTraffic: []UserTraffic{
{UID: 1, Upload: 100, Download: 200},
},
wantErr: true,
},
{
name: "Empty user traffic data",
nodeId: 1,
userTraffic: []UserTraffic{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := cache.AddNodeTodayTraffic(ctx, tt.nodeId, tt.userTraffic)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
// Verify data is added correctly
upload, err := client.HGet(ctx, NodeTodayUploadTrafficCacheKey, "1").Int64()
assert.NoError(t, err)
assert.Equal(t, int64(400), upload) // 100 + 300
download, err := client.HGet(ctx, NodeTodayDownloadTrafficCacheKey, "1").Int64()
assert.NoError(t, err)
assert.Equal(t, int64(600), download) // 200 + 400
})
}
}
func TestNodeCacheClient_GetUserTodayTrafficRank(t *testing.T) {
client := newTestRedisClient(t)
defer cleanupTestData(t, client)
cache := NewNodeCacheClient(client)
ctx := context.Background()
// Prepare test data
testData := []struct {
uid int64
upload int64
download int64
}{
{1, 100, 200},
{2, 300, 400},
{3, 500, 600},
}
for _, data := range testData {
err := cache.AddUserTodayTraffic(ctx, data.uid, data.upload, data.download)
require.NoError(t, err)
}
tests := []struct {
name string
n int64
wantErr bool
}{
{
name: "Get top 2 ranks",
n: 2,
wantErr: false,
},
{
name: "Get all ranks",
n: 3,
wantErr: false,
},
{
name: "Invalid N value",
n: 0,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ranks, err := cache.GetUserTodayTotalTrafficRank(ctx, tt.n)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Len(t, ranks, int(tt.n))
// Verify sorting is correct
for i := 1; i < len(ranks); i++ {
assert.GreaterOrEqual(t, ranks[i-1].Total, ranks[i].Total)
}
})
}
}
func TestNodeCacheClient_ResetTodayTrafficData(t *testing.T) {
client := newTestRedisClient(t)
defer cleanupTestData(t, client)
cache := NewNodeCacheClient(client)
ctx := context.Background()
// Prepare test data
err := cache.AddUserTodayTraffic(ctx, 1, 100, 200)
require.NoError(t, err)
err = cache.AddNodeTodayTraffic(ctx, 1, []UserTraffic{{UID: 1, Upload: 100, Download: 200}})
require.NoError(t, err)
// Test reset functionality
err = cache.ResetTodayTrafficData(ctx)
assert.NoError(t, err)
// Verify data is cleared
keys := []string{
UserTodayUploadTrafficCacheKey,
UserTodayDownloadTrafficCacheKey,
UserTodayTotalTrafficCacheKey,
NodeTodayUploadTrafficCacheKey,
NodeTodayDownloadTrafficCacheKey,
NodeTodayTotalTrafficCacheKey,
}
for _, key := range keys {
exists, err := client.Exists(ctx, key).Result()
assert.NoError(t, err)
assert.Equal(t, int64(0), exists)
}
}
func TestNodeCacheClient_GetNodeTodayTrafficRank(t *testing.T) {
client := newTestRedisClient(t)
defer cleanupTestData(t, client)
cache := NewNodeCacheClient(client)
ctx := context.Background()
// Prepare test data
testData := []struct {
nodeId int64
traffic []UserTraffic
}{
{1, []UserTraffic{{UID: 1, Upload: 100, Download: 200}}},
{2, []UserTraffic{{UID: 2, Upload: 300, Download: 400}}},
{3, []UserTraffic{{UID: 3, Upload: 500, Download: 600}}},
}
for _, data := range testData {
err := cache.AddNodeTodayTraffic(ctx, data.nodeId, data.traffic)
require.NoError(t, err)
}
tests := []struct {
name string
n int64
wantErr bool
}{
{
name: "Get top 2 ranks",
n: 2,
wantErr: false,
},
{
name: "Get all ranks",
n: 3,
wantErr: false,
},
{
name: "Invalid N value",
n: 0,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ranks, err := cache.GetNodeTodayTotalTrafficRank(ctx, tt.n)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Len(t, ranks, int(tt.n))
// Verify sorting is correct
for i := 1; i < len(ranks); i++ {
assert.GreaterOrEqual(t, ranks[i-1].Total, ranks[i].Total)
}
})
}
}
func TestNodeCacheClient_AddNodeOnlineUser(t *testing.T) {
client := newTestRedisClient(t)
defer cleanupTestData(t, client)
cache := NewNodeCacheClient(client)
ctx := context.Background()
tests := []struct {
name string
nodeId int64
users []NodeOnlineUser
wantErr bool
}{
{
name: "Add online users normally",
nodeId: 1,
users: []NodeOnlineUser{
{SID: 1, IP: "192.168.1.1"},
{SID: 2, IP: "192.168.1.2"},
},
wantErr: false,
},
{
name: "Invalid node ID",
nodeId: 0,
users: []NodeOnlineUser{
{SID: 1, IP: "192.168.1.1"},
},
wantErr: false,
},
{
name: "Empty user list",
nodeId: 1,
users: []NodeOnlineUser{},
wantErr: false,
},
{
name: "Add duplicate user IP",
nodeId: 1,
users: []NodeOnlineUser{
{SID: 1, IP: "192.168.1.1"},
{SID: 1, IP: "192.168.1.1"},
},
wantErr: false,
},
{
name: "Multiple IPs for same user",
nodeId: 1,
users: []NodeOnlineUser{
{SID: 1, IP: "192.168.1.1"},
{SID: 1, IP: "192.168.1.2"},
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := cache.AddOnlineUserIP(ctx, tt.users)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
// Verify data is added correctly
for _, user := range tt.users {
// Get user online IPs
ips, err := cache.GetUserOnlineIp(ctx, user.SID)
assert.NoError(t, err)
assert.Contains(t, ips, user.IP)
// Verify score is within valid range (current time to 5 minutes later)
score, err := client.ZScore(ctx, fmt.Sprintf(UserOnlineIpCacheKey, user.SID), user.IP).Result()
assert.NoError(t, err)
now := time.Now().Unix()
assert.GreaterOrEqual(t, score, float64(now))
assert.LessOrEqual(t, score, float64(now+300)) // 5 minutes = 300 seconds
// Verify key exists
exists, err := client.Exists(ctx, fmt.Sprintf(UserOnlineIpCacheKey, user.SID)).Result()
assert.NoError(t, err)
assert.Equal(t, int64(1), exists)
}
})
}
}
func TestNodeCacheClient_GetUserOnlineIp(t *testing.T) {
client := newTestRedisClient(t)
defer cleanupTestData(t, client)
cache := NewNodeCacheClient(client)
ctx := context.Background()
// Prepare test data
testData := []struct {
nodeId int64
users []NodeOnlineUser
}{
{
nodeId: 1,
users: []NodeOnlineUser{
{SID: 1, IP: "192.168.1.1"},
{SID: 1, IP: "192.168.1.2"},
{SID: 2, IP: "192.168.1.3"},
},
},
}
// Add test data
for _, data := range testData {
err := cache.AddOnlineUserIP(ctx, data.users)
require.NoError(t, err)
}
tests := []struct {
name string
uid int64
wantErr bool
wantIPs []string
}{
{
name: "Get existing user IPs",
uid: 1,
wantErr: false,
wantIPs: []string{"192.168.1.1", "192.168.1.2"},
},
{
name: "Get another user's IPs",
uid: 2,
wantErr: false,
wantIPs: []string{"192.168.1.3"},
},
{
name: "Get non-existent user IPs",
uid: 3,
wantErr: false,
wantIPs: []string{},
},
{
name: "Invalid user ID",
uid: 0,
wantErr: true,
},
{
name: "Expired IPs should not be returned",
uid: 1,
wantErr: false,
wantIPs: []string{"192.168.1.1", "192.168.1.2"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ips, err := cache.GetUserOnlineIp(ctx, tt.uid)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.ElementsMatch(t, tt.wantIPs, ips)
// Verify all returned IPs are valid
for _, ip := range ips {
score, err := client.ZScore(ctx, fmt.Sprintf(UserOnlineIpCacheKey, tt.uid), ip).Result()
assert.NoError(t, err)
now := time.Now().Unix()
assert.GreaterOrEqual(t, score, float64(now))
}
})
}
}
func TestNodeCacheClient_UpdateNodeOnlineUser(t *testing.T) {
client := newTestRedisClient(t)
defer cleanupTestData(t, client)
cache := NewNodeCacheClient(client)
ctx := context.Background()
tests := []struct {
name string
nodeId int64
users []NodeOnlineUser
wantErr bool
}{
{
name: "Update online users normally",
nodeId: 1,
users: []NodeOnlineUser{
{SID: 1, IP: "192.168.1.1"},
{SID: 2, IP: "192.168.1.2"},
},
wantErr: false,
},
{
name: "Invalid node ID",
nodeId: 0,
users: []NodeOnlineUser{
{SID: 1, IP: "192.168.1.1"},
},
wantErr: true,
},
{
name: "Empty user list",
nodeId: 1,
users: []NodeOnlineUser{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := cache.UpdateNodeOnlineUser(ctx, tt.nodeId, tt.users)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
// Verify data is updated correctly
data, err := client.Get(ctx, fmt.Sprintf(NodeOnlineUserCacheKey, tt.nodeId)).Result()
assert.NoError(t, err)
var result map[int64][]string
err = json.Unmarshal([]byte(data), &result)
assert.NoError(t, err)
// Verify data content
for _, user := range tt.users {
ips, exists := result[user.SID]
assert.True(t, exists)
assert.Contains(t, ips, user.IP)
}
})
}
}
+34
View File
@@ -0,0 +1,34 @@
package cache
type NodeOnlineUser struct {
SID int64
IP string
}
type NodeTodayTrafficRank struct {
ID int64
Name string
Upload int64
Download int64
Total int64
}
type UserTodayTrafficRank struct {
SID int64
Upload int64
Download int64
Total int64
}
type UserTraffic struct {
UID int64
Upload int64
Download int64
}
type NodeStatus struct {
Cpu float64
Mem float64
Disk float64
UpdatedAt int64
}
+24
View File
@@ -0,0 +1,24 @@
package coupon
import "time"
type Coupon struct {
Id int64 `gorm:"primaryKey"`
Name string `gorm:"type:varchar(255);not null;default:'';comment:Coupon Name"`
Code string `gorm:"type:varchar(255);not null;default:'';unique;comment:Coupon Code"`
Count int64 `gorm:"type:int;not null;default:0;comment:Count Limit"`
Type uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Coupon Type: 1: Percentage 2: Fixed Amount"`
Discount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount"`
StartTime int64 `gorm:"type:int;not null;default:0;comment:Start Time"`
ExpireTime int64 `gorm:"type:int;not null;default:0;comment:Expire Time"`
UserLimit int64 `gorm:"type:int;not null;default:0;comment:User Limit"`
Subscribe string `gorm:"type:varchar(255);not null;default:'';comment:Subscribe Limit"`
UsedCount int64 `gorm:"type:int;not null;default:0;comment:Used Count"`
Enable *bool `gorm:"type:tinyint(1);not null;default:1;comment:Enable"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Coupon) TableName() string {
return "coupon"
}
+135
View File
@@ -0,0 +1,135 @@
package coupon
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customCouponModel)(nil)
var (
cacheCouponIdPrefix = "cache:coupon:id:"
cacheCouponCodePrefix = "cache:coupon:code:"
)
type (
Model interface {
couponModel
customCouponLogicModel
}
couponModel interface {
Insert(ctx context.Context, data *Coupon) error
FindOne(ctx context.Context, id int64) (*Coupon, error)
FindOneByCode(ctx context.Context, code string) (*Coupon, error)
Update(ctx context.Context, data *Coupon) error
Delete(ctx context.Context, id int64) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customCouponModel struct {
*defaultCouponModel
}
defaultCouponModel struct {
cache.CachedConn
table string
}
)
func newCouponModel(db *gorm.DB, c *redis.Client) *defaultCouponModel {
return &defaultCouponModel{
CachedConn: cache.NewConn(db, c),
table: "`coupon`",
}
}
//nolint:unused
func (m *defaultCouponModel) batchGetCacheKeys(Coupons ...*Coupon) []string {
var keys []string
for _, coupon := range Coupons {
keys = append(keys, m.getCacheKeys(coupon)...)
}
return keys
}
func (m *defaultCouponModel) getCacheKeys(data *Coupon) []string {
if data == nil {
return []string{}
}
couponIdKey := fmt.Sprintf("%s%v", cacheCouponIdPrefix, data.Id)
couponCodeKey := fmt.Sprintf("%s%v", cacheCouponCodePrefix, data.Code)
cacheKeys := []string{
couponIdKey,
couponCodeKey,
}
return cacheKeys
}
func (m *defaultCouponModel) Insert(ctx context.Context, data *Coupon) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(&data).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultCouponModel) FindOne(ctx context.Context, id int64) (*Coupon, error) {
CouponIdKey := fmt.Sprintf("%s%v", cacheCouponIdPrefix, id)
var resp Coupon
err := m.QueryCtx(ctx, &resp, CouponIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Coupon{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultCouponModel) FindOneByCode(ctx context.Context, code string) (*Coupon, error) {
CouponCodeKey := fmt.Sprintf("%s%v", cacheCouponCodePrefix, code)
var resp Coupon
err := m.QueryCtx(ctx, &resp, CouponCodeKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Coupon{}).Where("`code` = ?", code).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultCouponModel) Update(ctx context.Context, data *Coupon) 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 *defaultCouponModel) 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(&Coupon{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultCouponModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+55
View File
@@ -0,0 +1,55 @@
package coupon
import (
"context"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type customCouponLogicModel interface {
UpdateCount(ctx context.Context, code string) error
QueryCouponListByPage(ctx context.Context, page, size int, subscribe int64, search string) (total int64, list []*Coupon, err error)
BatchDelete(ctx context.Context, ids []int64) error
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customCouponModel{
defaultCouponModel: newCouponModel(conn, c),
}
}
// QueryCouponListByPage query coupon list by page
func (m *customCouponModel) QueryCouponListByPage(ctx context.Context, page, size int, subscribe int64, search string) (total int64, list []*Coupon, err error) {
err = m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
db := conn.Model(&Coupon{})
if subscribe != 0 {
db = db.Where("FIND_IN_SET(?, subscribe)", subscribe)
}
if search != "" {
db = db.Where("name like ? or code like ?", "%"+search+"%", "%"+search+"%")
}
return db.Count(&total).Limit(size).Offset((page - 1) * size).Find(v).Error
})
return total, list, err
}
func (m *customCouponModel) BatchDelete(ctx context.Context, ids []int64) error {
var err error
for _, id := range ids {
if err = m.Delete(ctx, id); err != nil {
return err
}
}
return nil
}
func (m *customCouponModel) UpdateCount(ctx context.Context, code string) error {
data, err := m.FindOneByCode(ctx, code)
if err != nil {
return err
}
data.UsedCount++
return m.Update(ctx, data)
}
+117
View File
@@ -0,0 +1,117 @@
package document
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customDocumentModel)(nil)
var (
cacheDocumentIdPrefix = "cache:document:id:"
)
type (
Model interface {
documentModel
customDocumentLogicModel
}
documentModel interface {
Insert(ctx context.Context, data *Document) error
FindOne(ctx context.Context, id int64) (*Document, error)
Update(ctx context.Context, data *Document) error
Delete(ctx context.Context, id int64) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customDocumentModel struct {
*defaultDocumentModel
}
defaultDocumentModel struct {
cache.CachedConn
table string
}
)
func newDocumentModel(db *gorm.DB, c *redis.Client) *defaultDocumentModel {
return &defaultDocumentModel{
CachedConn: cache.NewConn(db, c),
table: "`document`",
}
}
//nolint:unused
func (m *defaultDocumentModel) batchGetCacheKeys(Documents ...*Document) []string {
var keys []string
for _, document := range Documents {
keys = append(keys, m.getCacheKeys(document)...)
}
return keys
}
func (m *defaultDocumentModel) getCacheKeys(data *Document) []string {
if data == nil {
return []string{}
}
documentIdKey := fmt.Sprintf("%s%v", cacheDocumentIdPrefix, data.Id)
cacheKeys := []string{
documentIdKey,
}
return cacheKeys
}
func (m *defaultDocumentModel) Insert(ctx context.Context, data *Document) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(&data).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultDocumentModel) FindOne(ctx context.Context, id int64) (*Document, error) {
DocumentIdKey := fmt.Sprintf("%s%v", cacheDocumentIdPrefix, id)
var resp Document
err := m.QueryCtx(ctx, &resp, DocumentIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Document{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultDocumentModel) Update(ctx context.Context, data *Document) 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 *defaultDocumentModel) 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(&Document{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultDocumentModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+17
View File
@@ -0,0 +1,17 @@
package document
import "time"
type Document struct {
Id int64 `gorm:"primaryKey"`
Title string `gorm:"type:varchar(255);not null;default:'';comment:Document Title"`
Content string `gorm:"type:text;comment:Document Content"`
Tags string `gorm:"type:varchar(255);not null;default:'';comment:Document Tags"`
Show *bool `gorm:"type:tinyint(1);not null;default:1;comment:Show"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Document) TableName() string {
return "document"
}
+58
View File
@@ -0,0 +1,58 @@
package document
import (
"context"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type customDocumentLogicModel interface {
QueryDocumentDetail(ctx context.Context, id int64) (*Document, error)
QueryDocumentList(ctx context.Context, page, size int, tag string, search string) (int64, []*Document, error)
GetDocumentListByAll(ctx context.Context) (int64, []*Document, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customDocumentModel{
defaultDocumentModel: newDocumentModel(conn, c),
}
}
// QueryDocumentDetail queries the details of a document.
func (m *customDocumentModel) QueryDocumentDetail(ctx context.Context, id int64) (*Document, error) {
var data Document
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Document{}).Preload("Group").Where("id = ?", id).Find(v).Error
})
return &data, err
}
// QueryDocumentList queries a list of documents.
func (m *customDocumentModel) QueryDocumentList(ctx context.Context, page, size int, tag string, search string) (int64, []*Document, error) {
var data []*Document
var total int64
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
db := conn.Model(&Document{})
if tag != "" {
db = db.Where("FIND_IN_SET(?, tags)", tag)
}
if search != "" {
db = db.Where("title LIKE ? OR content LIKE ?", "%"+search+"%", "%"+search+"%")
}
return db.Count(&total).Offset((page - 1) * size).Limit(size).Find(v).Error
})
return total, data, err
}
// GetDocumentListByAll queries a list of documents.
func (m *customDocumentModel) GetDocumentListByAll(ctx context.Context) (int64, []*Document, error) {
var data []*Document
var total int64
show := true
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Document{}).Where("`show` = ?", &show).Count(&total).Find(v).Error
})
return total, data, err
}
+79
View File
@@ -0,0 +1,79 @@
package log
import (
"context"
"gorm.io/gorm"
)
var _ Model = (*customLogModel)(nil)
type (
Model interface {
messageLogModel
}
messageLogModel interface {
InsertMessageLog(ctx context.Context, data *MessageLog) error
FindOneMessageLog(ctx context.Context, id int64) (*MessageLog, error)
UpdateMessageLog(ctx context.Context, data *MessageLog) error
DeleteMessageLog(ctx context.Context, id int64) error
FindMessageLogList(ctx context.Context, page, size int, filter MessageLogFilterParams) (int64, []*MessageLog, error)
}
customLogModel struct {
*defaultLogModel
}
defaultLogModel struct {
Connection *gorm.DB
}
)
func newLogModel(db *gorm.DB) *defaultLogModel {
return &defaultLogModel{
Connection: db,
}
}
func (m *defaultLogModel) InsertMessageLog(ctx context.Context, data *MessageLog) error {
return m.Connection.WithContext(ctx).Create(&data).Error
}
func (m *defaultLogModel) FindOneMessageLog(ctx context.Context, id int64) (*MessageLog, error) {
var resp MessageLog
err := m.Connection.WithContext(ctx).Model(&MessageLog{}).Where("`id` = ?", id).First(&resp).Error
return &resp, err
}
func (m *defaultLogModel) UpdateMessageLog(ctx context.Context, data *MessageLog) error {
return m.Connection.WithContext(ctx).Model(&MessageLog{}).Where("id = ?", data.Id).Updates(data).Error
}
func (m *defaultLogModel) DeleteMessageLog(ctx context.Context, id int64) error {
return m.Connection.WithContext(ctx).Model(&MessageLog{}).Where("id = ?", id).Delete(&MessageLog{}).Error
}
func (m *defaultLogModel) FindMessageLogList(ctx context.Context, page, size int, filter MessageLogFilterParams) (int64, []*MessageLog, error) {
var list []*MessageLog
var total int64
conn := m.Connection.WithContext(ctx).Model(&MessageLog{})
if filter.Type != "" {
conn = conn.Where("`type` = ?", filter.Type)
}
if filter.Platform != "" {
conn = conn.Where("`platform` = ?", filter.Platform)
}
if filter.To != "" {
conn = conn.Where("`to` LIKE ?", "%"+filter.To+"%")
}
if filter.Subject != "" {
conn = conn.Where("`subject` LIKE ?", "%"+filter.Subject+"%")
}
if filter.Content != "" {
conn = conn.Where("`content` = ?", "%"+filter.Content+"%")
}
if filter.Status > 0 {
conn = conn.Where("`status` = ?", filter.Status)
}
err := conn.Count(&total).Offset((page - 1) * size).Limit(size).Find(&list).Error
return total, list, err
}
+45
View File
@@ -0,0 +1,45 @@
package log
import "time"
type MessageType int
const (
Email MessageType = iota + 1
Mobile
)
func (t MessageType) String() string {
switch t {
case Email:
return "email"
case Mobile:
return "mobile"
}
return "unknown"
}
type MessageLog struct {
Id int64 `gorm:"primaryKey"`
Type string `gorm:"type:varchar(50);not null;default:'email';comment:Message Type"`
Platform string `gorm:"type:varchar(50);not null;default:'smtp';comment:Platform"`
To string `gorm:"type:text;not null;comment:To"`
Subject string `gorm:"type:varchar(255);not null;default:'';comment:Subject"`
Content string `gorm:"type:text;comment:Content"`
Status int `gorm:"type:tinyint(1);not null;default:0;comment:Status"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (m *MessageLog) TableName() string {
return "message_log"
}
type MessageLogFilterParams struct {
Type string
Platform string
To string
Subject string
Content string
Status int
}
+9
View File
@@ -0,0 +1,9 @@
package log
import (
"gorm.io/gorm"
)
func NewModel(conn *gorm.DB) Model {
return newLogModel(conn)
}
+142
View File
@@ -0,0 +1,142 @@
package order
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customOrderModel)(nil)
var (
cacheOrderIdPrefix = "cache:order:id:"
cacheOrderNoPrefix = "cache:order:no:"
)
type (
Model interface {
orderModel
customOrderLogicModel
}
orderModel interface {
Insert(ctx context.Context, data *Order, tx ...*gorm.DB) error
FindOne(ctx context.Context, id int64) (*Order, error)
FindOneByOrderNo(ctx context.Context, orderNo string) (*Order, error)
Update(ctx context.Context, data *Order, 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
}
customOrderModel struct {
*defaultOrderModel
}
defaultOrderModel struct {
cache.CachedConn
table string
}
)
func newOrderModel(db *gorm.DB, c *redis.Client) *defaultOrderModel {
return &defaultOrderModel{
CachedConn: cache.NewConn(db, c),
table: "`order`",
}
}
//nolint:unused
func (m *defaultOrderModel) batchGetCacheKeys(Orders ...*Order) []string {
var keys []string
for _, order := range Orders {
keys = append(keys, m.getCacheKeys(order)...)
}
return keys
}
func (m *defaultOrderModel) getCacheKeys(data *Order) []string {
if data == nil {
return []string{}
}
orderIdKey := fmt.Sprintf("%s%v", cacheOrderIdPrefix, data.Id)
orderNoKey := fmt.Sprintf("%s%v", cacheOrderNoPrefix, data.OrderNo)
cacheKeys := []string{
orderIdKey,
orderNoKey,
}
return cacheKeys
}
func (m *defaultOrderModel) Insert(ctx context.Context, data *Order, 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 *defaultOrderModel) FindOne(ctx context.Context, id int64) (*Order, error) {
OrderIdKey := fmt.Sprintf("%s%v", cacheOrderIdPrefix, id)
var resp Order
err := m.QueryCtx(ctx, &resp, OrderIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Order{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultOrderModel) FindOneByOrderNo(ctx context.Context, orderNo string) (*Order, error) {
OrderNoKey := fmt.Sprintf("%s%v", cacheOrderNoPrefix, orderNo)
var resp Order
err := m.QueryCtx(ctx, &resp, OrderNoKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Order{}).Where("`order_no` = ?", orderNo).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultOrderModel) Update(ctx context.Context, data *Order, 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 *defaultOrderModel) 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(&Order{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultOrderModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+213
View File
@@ -0,0 +1,213 @@
package order
import (
"context"
"time"
"github.com/perfect-panel/ppanel-server/internal/model/payment"
"github.com/perfect-panel/ppanel-server/internal/model/subscribe"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type Details struct {
Id int64 `gorm:"primaryKey"`
ParentId int64 `gorm:"type:bigint;default:null;comment:Parent Order Id"`
SubOrders []*Order `gorm:"foreignKey:ParentId;references:Id"`
UserId int64 `gorm:"type:bigint;not null;default:0;comment:User Id"`
OrderNo string `gorm:"type:varchar(255);not null;default:'';unique;comment:Order No"`
Type uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Type: 1: Subscribe, 2: Renewal, 3: ResetTraffic, 4: Recharge"`
Quantity int64 `gorm:"type:bigint;not null;default:1;comment:Quantity"`
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
Discount int64 `gorm:"type:int;not null;default:0;comment:Order Discount"`
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount"`
PaymentId int64 `gorm:"type:bigint;not null;default:0;comment:Payment Id"`
Payment *payment.Payment `gorm:"foreignKey:PaymentId;references:Id"`
Method string `gorm:"type:varchar(255);not null;default:'';comment:Payment Method"`
FeeAmount int64 `gorm:"type:int;not null;default:0;comment:Fee Amount"`
TradeNo string `gorm:"type:varchar(255);default:null;comment:Trade No"`
GiftAmount int64 `gorm:"type:int;not null;default:0;comment:User Gift Amount"`
Commission int64 `gorm:"type:int;not null;default:0;comment:Order Commission"`
Status uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Status: 1: Pending, 2: Paid, 3: Failed"`
SubscribeId int64 `gorm:"type:bigint;not null;default:0;comment:Subscribe Id"`
SubscribeToken string `gorm:"type:varchar(255);default:null;comment:Renewal Subscribe Token"`
Subscribe *subscribe.Subscribe `gorm:"foreignKey:SubscribeId;references:Id"`
IsNew bool `gorm:"type:tinyint(1);not null;default:0;comment:Is New Order"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
type customOrderLogicModel interface {
UpdateOrderStatus(ctx context.Context, orderNo string, status uint8, tx ...*gorm.DB) error
QueryOrderListByPage(ctx context.Context, page, size int, status uint8, user, subscribe int64, search string) (int64, []*Details, error)
FindOneDetails(ctx context.Context, id int64) (*Details, error)
FindOneDetailsByOrderNo(ctx context.Context, orderNo string) (*Details, error)
QueryMonthlyOrders(ctx context.Context, date time.Time) (OrdersTotal, error)
QueryDateOrders(ctx context.Context, date time.Time) (OrdersTotal, error)
QueryTotalOrders(ctx context.Context) (OrdersTotal, error)
QueryMonthlyUserCounts(ctx context.Context, date time.Time) (int64, int64, error)
QueryDateUserCounts(ctx context.Context, date time.Time) (int64, int64, error)
IsUserEligibleForNewOrder(ctx context.Context, userID int64) (bool, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customOrderModel{
defaultOrderModel: newOrderModel(conn, c),
}
}
// QueryOrderListByPage Query order list by page
func (m *customOrderModel) QueryOrderListByPage(ctx context.Context, page, size int, status uint8, user, subscribe int64, search string) (int64, []*Details, error) {
var list []*Details
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
conn = conn.Model(&Order{})
if status > 0 {
conn = conn.Where("status = ?", status)
}
if user > 0 {
conn = conn.Where("user_id = ?", user)
}
if subscribe > 0 {
conn = conn.Where("subscribe_id = ?", subscribe)
}
if search != "" {
conn = conn.Where("order_no like ? or trade_no like ? or coupon like ?", "%"+search+"%", "%"+search+"%", "%"+search+"%")
}
return conn.Order("id desc").Preload("Subscribe").Preload("Payment").Count(&total).Offset((page - 1) * size).Limit(size).Find(v).Error
})
return total, list, err
}
// UpdateOrderStatus Update order status
func (m *customOrderModel) UpdateOrderStatus(ctx context.Context, orderNo string, status uint8, tx ...*gorm.DB) error {
orderInfo, err := m.FindOneByOrderNo(ctx, orderNo)
if err != nil {
return err
}
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&Order{}).Where("order_no = ?", orderNo).Update("status", status).Error
}, m.getCacheKeys(orderInfo)...)
}
// FindOneDetailsByOrderNo Find order details by order number
func (m *customOrderModel) FindOneDetailsByOrderNo(ctx context.Context, orderNo string) (*Details, error) {
var orderInfo Details
err := m.QueryNoCacheCtx(ctx, &orderInfo, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Order{}).Where("order_no = ?", orderNo).Preload("Subscribe").Preload("Payment").First(v).Error
})
return &orderInfo, err
}
func (m *customOrderModel) FindOneDetails(ctx context.Context, id int64) (*Details, error) {
var orderInfo Details
err := m.QueryNoCacheCtx(ctx, &orderInfo, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Order{}).
Where("id = ?", id).
Preload("Subscribe").
Preload("SubOrders").
First(v).Error
})
return &orderInfo, err
}
func (m *customOrderModel) QueryMonthlyOrders(ctx context.Context, date time.Time) (OrdersTotal, error) {
firstDay := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, date.Location())
lastDay := firstDay.AddDate(0, 1, 0).Add(-time.Nanosecond)
var result OrdersTotal
err := m.QueryNoCacheCtx(ctx, &result, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Order{}).
Where("status IN ? AND created_at BETWEEN ? AND ? AND method != ?", []int64{2, 5}, firstDay, lastDay, "balance").
Select(
"SUM(amount) as amount_total, " +
"SUM(CASE WHEN is_new = 1 THEN amount ELSE 0 END) as new_order_amount, " +
"SUM(CASE WHEN is_new = 0 THEN amount ELSE 0 END) as renewal_order_amount",
).
Scan(v).Error
})
return result, err
}
// QueryDateOrders Query orders by date
func (m *customOrderModel) QueryDateOrders(ctx context.Context, date time.Time) (OrdersTotal, error) {
start := date.Truncate(24 * time.Hour)
end := start.Add(24 * time.Hour).Add(-time.Nanosecond)
var result OrdersTotal
err := m.QueryNoCacheCtx(ctx, &result, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Order{}).
Where("status IN ? AND created_at BETWEEN ? AND ? AND method != ?", []int64{2, 5}, start, end, "balance").
Select(
"SUM(amount) as amount_total, " +
"SUM(CASE WHEN is_new = 1 THEN amount ELSE 0 END) as new_order_amount, " +
"SUM(CASE WHEN is_new = 0 THEN amount ELSE 0 END) as renewal_order_amount",
).
Scan(v).Error
})
return result, err
}
func (m *customOrderModel) QueryTotalOrders(ctx context.Context) (OrdersTotal, error) {
var result OrdersTotal
err := m.QueryNoCacheCtx(ctx, &result, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Order{}).
Where("status IN ? AND method != ?", []int64{2, 5}, "balance").
Select(
"SUM(amount) as amount_total, " +
"SUM(CASE WHEN is_new = 1 THEN amount ELSE 0 END) as new_order_amount, " +
"SUM(CASE WHEN is_new = 0 THEN amount ELSE 0 END) as renewal_order_amount",
).
Scan(v).Error
})
return result, err
}
func (m *customOrderModel) QueryMonthlyUserCounts(ctx context.Context, date time.Time) (int64, int64, error) {
firstDay := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, date.Location())
lastDay := firstDay.AddDate(0, 1, -1)
var newUsers int64
var renewalUsers int64
err := m.QueryNoCacheCtx(ctx, nil, func(conn *gorm.DB, _ interface{}) error {
return conn.Model(&Order{}).
Where("status IN ? AND created_at BETWEEN ? AND ? AND method != ?", []int64{2, 5}, firstDay, lastDay, "balance").
Select(
"COUNT(DISTINCT CASE WHEN is_new = 1 THEN user_id END) as new_users, "+
"COUNT(DISTINCT CASE WHEN is_new = 0 THEN user_id END) as renewal_users").
Row().Scan(&newUsers, &renewalUsers)
})
return newUsers, renewalUsers, err
}
func (m *customOrderModel) QueryDateUserCounts(ctx context.Context, date time.Time) (int64, int64, error) {
start := date.Truncate(24 * time.Hour)
end := start.Add(24 * time.Hour).Add(-time.Nanosecond)
var newUsers int64
var renewalUsers int64
err := m.QueryNoCacheCtx(ctx, nil, func(conn *gorm.DB, _ interface{}) error {
return conn.Model(&Order{}).
Where("status IN ? AND created_at BETWEEN ? AND ? AND method != ?", []int64{2, 5}, start, end, "balance").
Select(
"COUNT(DISTINCT CASE WHEN is_new = 1 THEN user_id END) as new_users, "+
"COUNT(DISTINCT CASE WHEN is_new = 0 THEN user_id END) as renewal_users").
Row().Scan(&newUsers, &renewalUsers)
})
return newUsers, renewalUsers, err
}
func (m *customOrderModel) IsUserEligibleForNewOrder(ctx context.Context, userID int64) (bool, error) {
var count int64
err := m.QueryNoCacheCtx(ctx, nil, func(conn *gorm.DB, _ interface{}) error {
return conn.Model(&Order{}).
Where("user_id = ? AND status IN ?", userID, []int64{2, 5}).
Count(&count).Error
})
return count == 0, err
}
+39
View File
@@ -0,0 +1,39 @@
package order
import "time"
type Order struct {
Id int64 `gorm:"primaryKey"`
ParentId int64 `gorm:"type:bigint;default:null;comment:Parent Order Id"`
UserId int64 `gorm:"type:bigint;not null;default:0;comment:User Id"`
OrderNo string `gorm:"type:varchar(255);not null;default:'';unique;comment:Order No"`
Type uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Type: 1: Subscribe, 2: Renewal, 3: ResetTraffic, 4: Recharge"`
Quantity int64 `gorm:"type:bigint;not null;default:1;comment:Quantity"`
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
GiftAmount int64 `gorm:"type:int;not null;default:0;comment:User Gift Amount"`
Discount int64 `gorm:"type:int;not null;default:0;comment:Discount Amount"`
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount Amount"`
Commission int64 `gorm:"type:int;not null;default:0;comment:Order Commission"`
PaymentId int64 `gorm:"type:bigint;not null;default:0;comment:Payment Method Id"`
Method string `gorm:"type:varchar(255);not null;default:'';comment:Payment Method"`
FeeAmount int64 `gorm:"type:int;not null;default:0;comment:Fee Amount"`
TradeNo string `gorm:"type:varchar(255);default:null;comment:Trade No"`
Status uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Status: 1: Pending, 2: Paid, 3:Close, 4: Failed, 5:Finished;"`
SubscribeId int64 `gorm:"type:bigint;not null;default:0;comment:Subscribe Id"`
SubscribeToken string `gorm:"type:varchar(255);default:null;comment:Renewal Subscribe Token"`
IsNew bool `gorm:"type:tinyint(1);not null;default:0;comment:Is New Order"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
type OrdersTotal struct {
AmountTotal int64
NewOrderAmount int64
RenewalOrderAmount int64
}
func (Order) TableName() string {
return "order"
}
+127
View File
@@ -0,0 +1,127 @@
package payment
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customPaymentModel)(nil)
var (
cachePaymentIdPrefix = "cache:payment:id:"
cachePaymentTokenPrefix = "cache:payment:token:"
)
type (
Model interface {
paymentModel
customPaymentLogicModel
}
paymentModel interface {
Insert(ctx context.Context, data *Payment, tx ...*gorm.DB) error
FindOne(ctx context.Context, id int64) (*Payment, error)
Update(ctx context.Context, data *Payment, 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
}
customPaymentModel struct {
*defaultPaymentModel
}
defaultPaymentModel struct {
cache.CachedConn
table string
}
)
func newPaymentModel(db *gorm.DB, c *redis.Client) *defaultPaymentModel {
return &defaultPaymentModel{
CachedConn: cache.NewConn(db, c),
table: "`Payment`",
}
}
//nolint:unused
func (m *defaultPaymentModel) batchGetCacheKeys(Payments ...*Payment) []string {
var keys []string
for _, payment := range Payments {
keys = append(keys, m.getCacheKeys(payment)...)
}
return keys
}
func (m *defaultPaymentModel) getCacheKeys(data *Payment) []string {
if data == nil {
return []string{}
}
paymentIdKey := fmt.Sprintf("%s%v", cachePaymentIdPrefix, data.Id)
paymentNameKey := fmt.Sprintf("%s%v", cachePaymentTokenPrefix, data.Token)
cacheKeys := []string{
paymentIdKey,
paymentNameKey,
}
return cacheKeys
}
func (m *defaultPaymentModel) Insert(ctx context.Context, data *Payment, 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 *defaultPaymentModel) FindOne(ctx context.Context, id int64) (*Payment, error) {
PaymentIdKey := fmt.Sprintf("%s%v", cachePaymentIdPrefix, id)
var resp Payment
err := m.QueryCtx(ctx, &resp, PaymentIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Payment{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultPaymentModel) Update(ctx context.Context, data *Payment, 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 *defaultPaymentModel) 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(&Payment{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultPaymentModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+69
View File
@@ -0,0 +1,69 @@
package payment
import (
"context"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type customPaymentLogicModel interface {
FindOneByPaymentToken(ctx context.Context, token string) (*Payment, error)
FindAll(ctx context.Context) ([]*Payment, error)
FindListByPage(ctx context.Context, page, size int, req *Filter) (int64, []*Payment, error)
FindAvailableMethods(ctx context.Context) ([]*Payment, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customPaymentModel{
defaultPaymentModel: newPaymentModel(conn, c),
}
}
func (m *customPaymentModel) FindOneByPaymentToken(ctx context.Context, token string) (*Payment, error) {
var resp *Payment
key := cachePaymentTokenPrefix + token
err := m.QueryCtx(ctx, &resp, key, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Payment{}).Where("token = ?", token).First(v).Error
})
return resp, err
}
func (m *customPaymentModel) FindAll(ctx context.Context) ([]*Payment, error) {
var resp []*Payment
err := m.QueryNoCacheCtx(ctx, &resp, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Payment{}).Find(v).Error
})
return resp, err
}
func (m *customPaymentModel) FindAvailableMethods(ctx context.Context) ([]*Payment, error) {
var resp []*Payment
err := m.QueryNoCacheCtx(ctx, &resp, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Payment{}).Where("enable = ?", true).Find(v).Error
})
return resp, err
}
func (m *customPaymentModel) FindListByPage(ctx context.Context, page, size int, req *Filter) (int64, []*Payment, error) {
var resp []*Payment
var total int64
err := m.QueryNoCacheCtx(ctx, &resp, func(conn *gorm.DB, v interface{}) error {
conn = conn.Model(&Payment{})
if req != nil {
if req.Enable != nil {
conn = conn.Where("`enable` = ?", *req.Enable)
}
if req.Mark != "" {
conn = conn.Where("`mark` = ?", req.Mark)
}
if req.Search != "" {
conn = conn.Where("`name` LIKE ?", "%"+req.Search+"%")
}
}
return conn.Count(&total).Offset((page - 1) * size).Limit(size).Find(v).Error
})
return total, resp, err
}
+88
View File
@@ -0,0 +1,88 @@
package payment
import (
"encoding/json"
"fmt"
"gorm.io/gorm"
)
type Payment struct {
Id int64 `gorm:"primaryKey"`
Name string `gorm:"type:varchar(100);not null;default:'';comment:Payment Name"`
Platform string `gorm:"<-:create;type:varchar(100);not null;comment:Payment Platform"`
Icon string `gorm:"type:varchar(255);default:'';comment:Payment Icon"`
Domain string `gorm:"type:varchar(255);default:'';comment:Notification Domain"`
Config string `gorm:"type:text;not null;comment:Payment Configuration"`
Description string `gorm:"type:text;comment:Payment Description"`
FeeMode uint `gorm:"type:tinyint(1);not null;default:0;comment:Fee Mode: 0: No Fee 1: Percentage 2: Fixed Amount 3: Percentage + Fixed Amount"`
FeePercent int64 `gorm:"type:int;default:0;comment:Fee Percentage"`
FeeAmount int64 `gorm:"type:int;default:0;comment:Fixed Fee Amount"`
Enable *bool `gorm:"type:tinyint(1);not null;default:0;comment:Is Enabled"`
Token string `gorm:"type:varchar(255);unique;not null;default:'';comment:Payment Token"`
}
func (*Payment) TableName() string {
return "payment"
}
func (l *Payment) BeforeDelete(_ *gorm.DB) (err error) {
if l.Id == -1 {
return fmt.Errorf("can't delete default payment method")
}
return nil
}
type Filter struct {
Mark string
Enable *bool
Search string
}
type StripeConfig struct {
PublicKey string `json:"public_key"`
SecretKey string `json:"secret_key"`
WebhookSecret string `json:"webhook_secret"`
Payment string `json:"payment"`
}
func (l *StripeConfig) Marshal() string {
b, _ := json.Marshal(l)
return string(b)
}
func (l *StripeConfig) Unmarshal(s string) error {
return json.Unmarshal([]byte(s), l)
}
type AlipayF2FConfig struct {
AppId string `json:"app_id"`
PrivateKey string `json:"private_key"`
PublicKey string `json:"public_key"`
InvoiceName string `json:"invoice_name"`
Sandbox bool `json:"sandbox"`
}
func (l *AlipayF2FConfig) Marshal() string {
b, _ := json.Marshal(l)
return string(b)
}
func (l *AlipayF2FConfig) Unmarshal(s string) error {
return json.Unmarshal([]byte(s), l)
}
type EPayConfig struct {
Pid string `json:"pid"`
Url string `json:"url"`
Key string `json:"key"`
}
func (l *EPayConfig) Marshal() string {
b, _ := json.Marshal(l)
return string(b)
}
func (l *EPayConfig) Unmarshal(s string) error {
return json.Unmarshal([]byte(s), l)
}
+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
}
+126
View File
@@ -0,0 +1,126 @@
package subscribe
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customSubscribeModel)(nil)
var (
cacheSubscribeIdPrefix = "cache:subscribe:id:"
)
type (
Model interface {
subscribeModel
customSubscribeLogicModel
}
subscribeModel interface {
Insert(ctx context.Context, data *Subscribe, tx ...*gorm.DB) error
FindOne(ctx context.Context, id int64) (*Subscribe, error)
Update(ctx context.Context, data *Subscribe, 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
}
customSubscribeModel struct {
*defaultSubscribeModel
}
defaultSubscribeModel struct {
cache.CachedConn
table string
}
)
func newSubscribeModel(db *gorm.DB, c *redis.Client) *defaultSubscribeModel {
return &defaultSubscribeModel{
CachedConn: cache.NewConn(db, c),
table: "`subscribe`",
}
}
//nolint:unused
func (m *defaultSubscribeModel) batchGetCacheKeys(Subscribes ...*Subscribe) []string {
var keys []string
for _, subscribe := range Subscribes {
keys = append(keys, m.getCacheKeys(subscribe)...)
}
return keys
}
func (m *defaultSubscribeModel) getCacheKeys(data *Subscribe) []string {
if data == nil {
return []string{}
}
SubscribeIdKey := fmt.Sprintf("%s%v", cacheSubscribeIdPrefix, data.Id)
cacheKeys := []string{
SubscribeIdKey,
}
return cacheKeys
}
func (m *defaultSubscribeModel) Insert(ctx context.Context, data *Subscribe, 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 *defaultSubscribeModel) FindOne(ctx context.Context, id int64) (*Subscribe, error) {
SubscribeIdKey := fmt.Sprintf("%s%v", cacheSubscribeIdPrefix, id)
var resp Subscribe
err := m.QueryCtx(ctx, &resp, SubscribeIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Subscribe{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultSubscribeModel) Update(ctx context.Context, data *Subscribe, 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 {
db := conn
if len(tx) > 0 {
db = tx[0]
}
return db.Save(data).Error
}, m.getCacheKeys(old)...)
return err
}
func (m *defaultSubscribeModel) 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 {
db := conn
if len(tx) > 0 {
db = tx[0]
}
return db.Delete(&Subscribe{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultSubscribeModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+109
View File
@@ -0,0 +1,109 @@
package subscribe
import (
"context"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
// type Details struct {
// Id int64 `gorm:"primaryKey"`
// Name string `gorm:"type:varchar(255);not null;default:'';comment:Subscribe Name"`
// 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"`
// GroupId int64 `gorm:"type:bigint;comment:Group Id"`
// Quota int64 `gorm:"type:int;not null;default:0;comment:Quota"`
// Show *bool `gorm:"type:tinyint(1);not null;default:0;comment:Show"`
// Sell *bool `gorm:"type:tinyint(1);not null;default:0;comment:Sell"`
// DeductionRatio int64 `gorm:"type:int;default:0;comment:Deduction Ratio"`
// PurchaseWithDiscount bool `gorm:"type:tinyint(1);default:0;comment:PurchaseWithDiscount"`
// ResetCycle int64 `gorm:"type:int;default:0;comment:Reset Cycle"`
// RenewalReset bool `gorm:"type:tinyint(1);default:0;comment:Renew Reset"`
// }
type customSubscribeLogicModel interface {
QuerySubscribeListByPage(ctx context.Context, page, size int, group int64, search string) (total int64, list []*Subscribe, err error)
QuerySubscribeList(ctx context.Context) ([]*Subscribe, error)
QuerySubscribeListByShow(ctx context.Context) ([]*Subscribe, error)
QuerySubscribeIdsByServerIdAndServerGroupId(ctx context.Context, serverId, serverGroupId int64) ([]*Subscribe, error)
QuerySubscribeMinSortByIds(ctx context.Context, ids []int64) (int64, error)
QuerySubscribeListByIds(ctx context.Context, ids []int64) ([]*Subscribe, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customSubscribeModel{
defaultSubscribeModel: newSubscribeModel(conn, c),
}
}
// QuerySubscribeListByPage Get Subscribe List
func (m *customSubscribeModel) QuerySubscribeListByPage(ctx context.Context, page, size int, group int64, search string) (total int64, list []*Subscribe, err error) {
err = m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
// About to be abandoned
_ = conn.Model(&Subscribe{}).
Where("sort = ?", 0).
Update("sort", gorm.Expr("id"))
conn = conn.Model(&Subscribe{})
if group > 0 {
conn = conn.Where("group_id = ?", group)
}
if search != "" {
conn = conn.Where("`name` like ? or `description` like ?", "%"+search+"%", "%"+search+"%")
}
return conn.Count(&total).Order("sort ASC").Limit(size).Offset((page - 1) * size).Find(v).Error
})
return total, list, err
}
// QuerySubscribeList Get Subscribe List
func (m *customSubscribeModel) QuerySubscribeList(ctx context.Context) ([]*Subscribe, error) {
var list []*Subscribe
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
conn = conn.Model(&Subscribe{})
return conn.Where("`sell` = true").Order("sort ").Find(v).Error
})
return list, err
}
func (m *customSubscribeModel) QuerySubscribeIdsByServerIdAndServerGroupId(ctx context.Context, serverId, serverGroupId int64) ([]*Subscribe, error) {
var data []*Subscribe
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Subscribe{}).Where("FIND_IN_SET(?, server)", serverId).Or("FIND_IN_SET(?, server_group)", serverGroupId).Find(v).Error
})
return data, err
}
// QuerySubscribeListByShow Get Subscribe List By Show
func (m *customSubscribeModel) QuerySubscribeListByShow(ctx context.Context) ([]*Subscribe, error) {
var list []*Subscribe
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
conn = conn.Model(&Subscribe{})
return conn.Where("`show` = true").Find(v).Error
})
return list, err
}
func (m *customSubscribeModel) QuerySubscribeMinSortByIds(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(&Subscribe{}).Where("id IN ?", ids).Select("COALESCE(MIN(sort), 0)").Scan(v).Error
})
return minSort, err
}
func (m *customSubscribeModel) QuerySubscribeListByIds(ctx context.Context, ids []int64) ([]*Subscribe, error) {
var list []*Subscribe
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Subscribe{}).Where("id IN ?", ids).Find(v).Error
})
return list, err
}
+66
View File
@@ -0,0 +1,66 @@
package subscribe
import (
"time"
"gorm.io/gorm"
)
type Subscribe struct {
Id int64 `gorm:"primaryKey"`
Name string `gorm:"type:varchar(255);not null;default:'';comment:Subscribe Name"`
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"`
GroupId int64 `gorm:"type:bigint;comment:Group Id"`
ServerGroup string `gorm:"type:varchar(255);comment:Server Group"`
Server string `gorm:"type:varchar(255);comment:Server"`
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"`
}
func (*Subscribe) TableName() string {
return "subscribe"
}
func (s *Subscribe) BeforeCreate(tx *gorm.DB) error {
if s.Sort == 0 {
var maxSort int64
if err := tx.Model(&Subscribe{}).Select("COALESCE(MAX(sort), 0)").Scan(&maxSort).Error; err != nil {
return err
}
s.Sort = maxSort + 1
}
return nil
}
type Discount struct {
Months int64 `json:"months"`
Discount int64 `json:"discount"`
}
type Group struct {
Id int64 `gorm:"primaryKey"`
Name string `gorm:"type:varchar(255);not null;default:'';comment:Group Name"`
Description string `gorm:"type:text;comment:Group Description"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Group) TableName() string {
return "subscribe_group"
}
+117
View File
@@ -0,0 +1,117 @@
package subscribeType
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customSubscribeTypeModel)(nil)
var (
cacheSubscribeTypeIdPrefix = "cache:subscribeType:id:"
)
type (
Model interface {
subscribeTypeModel
customSubscribeTypeLogicModel
}
subscribeTypeModel interface {
Insert(ctx context.Context, data *SubscribeType) error
FindOne(ctx context.Context, id int64) (*SubscribeType, error)
Update(ctx context.Context, data *SubscribeType) error
Delete(ctx context.Context, id int64) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customSubscribeTypeModel struct {
*defaultSubscribeTypeModel
}
defaultSubscribeTypeModel struct {
cache.CachedConn
table string
}
)
func newSubscribeTypeModel(db *gorm.DB, c *redis.Client) *defaultSubscribeTypeModel {
return &defaultSubscribeTypeModel{
CachedConn: cache.NewConn(db, c),
table: "`SubscribeType`",
}
}
//nolint:unused
func (m *defaultSubscribeTypeModel) batchGetCacheKeys(SubscribeTypes ...*SubscribeType) []string {
var keys []string
for _, subscribeType := range SubscribeTypes {
keys = append(keys, m.getCacheKeys(subscribeType)...)
}
return keys
}
func (m *defaultSubscribeTypeModel) getCacheKeys(data *SubscribeType) []string {
if data == nil {
return []string{}
}
SubscribeTypeIdKey := fmt.Sprintf("%s%v", cacheSubscribeTypeIdPrefix, data.Id)
cacheKeys := []string{
SubscribeTypeIdKey,
}
return cacheKeys
}
func (m *defaultSubscribeTypeModel) Insert(ctx context.Context, data *SubscribeType) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(&data).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultSubscribeTypeModel) FindOne(ctx context.Context, id int64) (*SubscribeType, error) {
SubscribeTypeIdKey := fmt.Sprintf("%s%v", cacheSubscribeTypeIdPrefix, id)
var resp SubscribeType
err := m.QueryCtx(ctx, &resp, SubscribeTypeIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&SubscribeType{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultSubscribeTypeModel) Update(ctx context.Context, data *SubscribeType) 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 *defaultSubscribeTypeModel) 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(&SubscribeType{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultSubscribeTypeModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+16
View File
@@ -0,0 +1,16 @@
package subscribeType
import (
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type customSubscribeTypeLogicModel interface {
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customSubscribeTypeModel{
defaultSubscribeTypeModel: newSubscribeTypeModel(conn, c),
}
}
@@ -0,0 +1,15 @@
package subscribeType
import "time"
type SubscribeType struct {
Id int64 `gorm:"primary_key"`
Name string `gorm:"type:varchar(50);default:'';not null;comment:订阅类型"`
Mark string `gorm:"type:varchar(255);default:'';not null;comment:订阅标识"`
CreatedAt time.Time `gorm:"<-:create;comment:创建时间"`
UpdatedAt time.Time `gorm:"comment:更新时间"`
}
func (SubscribeType) TableName() string {
return "subscribe_type"
}
+119
View File
@@ -0,0 +1,119 @@
package system
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var (
cacheSystemIdPrefix = "cache:System:id:"
cacheSystemKeyPrefix = "cache:System:key:"
)
var _ Model = (*customSystemModel)(nil)
type (
Model interface {
systemModel
customSystemLogicModel
}
systemModel interface {
Insert(ctx context.Context, data *System) error
FindOne(ctx context.Context, id int64) (*System, error)
FindOneByKey(ctx context.Context, email string) (*System, error)
Update(ctx context.Context, data *System) error
Delete(ctx context.Context, id int64) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customSystemModel struct {
*defaultSystemModel
}
defaultSystemModel struct {
cache.CachedConn
table string
}
)
func newSystemModel(db *gorm.DB, c *redis.Client) *defaultSystemModel {
return &defaultSystemModel{
CachedConn: cache.NewConn(db, c),
table: "`System`",
}
}
func (m *defaultSystemModel) getCacheKeys(data *System) []string {
if data == nil {
return []string{}
}
SystemIdKey := fmt.Sprintf("%s%v", cacheSystemIdPrefix, data.Id)
cacheKeys := []string{
SystemIdKey,
}
return cacheKeys
}
func (m *defaultSystemModel) FindOneByKey(ctx context.Context, key string) (*System, error) {
system := new(System)
cacheKey := fmt.Sprintf("%s%v", cacheSystemKeyPrefix, key)
err := m.QueryCtx(ctx, system, cacheKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&System{}).Where("`key` = ?", key).First(v).Error
})
return system, err
}
func (m *defaultSystemModel) Insert(ctx context.Context, data *System) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(&data).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultSystemModel) FindOne(ctx context.Context, id int64) (*System, error) {
SystemIdKey := fmt.Sprintf("%s%v", cacheSystemIdPrefix, id)
var resp System
err := m.QueryCtx(ctx, &resp, SystemIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&System{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultSystemModel) Update(ctx context.Context, data *System) 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 *defaultSystemModel) 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(&System{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultSystemModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+154
View File
@@ -0,0 +1,154 @@
package system
import (
"context"
"github.com/perfect-panel/ppanel-server/internal/config"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type customSystemLogicModel interface {
GetSmsConfig(ctx context.Context) ([]*System, error)
GetSiteConfig(ctx context.Context) ([]*System, error)
GetSubscribeConfig(ctx context.Context) ([]*System, error)
GetRegisterConfig(ctx context.Context) ([]*System, error)
GetVerifyConfig(ctx context.Context) ([]*System, error)
GetNodeConfig(ctx context.Context) ([]*System, error)
GetInviteConfig(ctx context.Context) ([]*System, error)
GetTosConfig(ctx context.Context) ([]*System, error)
GetCurrencyConfig(ctx context.Context) ([]*System, error)
GetVerifyCodeConfig(ctx context.Context) ([]*System, error)
UpdateNodeMultiplierConfig(ctx context.Context, config string) error
FindNodeMultiplierConfig(ctx context.Context) (*System, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customSystemModel{
defaultSystemModel: newSystemModel(conn, c),
}
}
// GetSmsConfig returns the sms config.
func (m *customSystemModel) GetSmsConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.SmsConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "sms").Find(v).Error
})
return configs, err
}
// GetSiteConfig returns the site config.
func (m *customSystemModel) GetSiteConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.SiteConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "site").Find(v).Error
})
return configs, err
}
// GetEmailConfig returns the email config.
func (m *customSystemModel) GetEmailConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.EmailSmtpConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "email").Find(v).Error
})
return configs, err
}
// GetSubscribeConfig returns the subscribe config.
func (m *customSystemModel) GetSubscribeConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.SubscribeConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "subscribe").Find(v).Error
})
return configs, err
}
// GetRegisterConfig returns the register config.
func (m *customSystemModel) GetRegisterConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.RegisterConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "register").Find(v).Error
})
return configs, err
}
// GetVerifyConfig returns the verify config.
func (m *customSystemModel) GetVerifyConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.VerifyConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "verify").Find(v).Error
})
return configs, err
}
// GetNodeConfig returns the server config.
func (m *customSystemModel) GetNodeConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.NodeConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "server").Find(v).Error
})
return configs, err
}
// GetInviteConfig returns the invite config.
func (m *customSystemModel) GetInviteConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.InviteConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "invite").Find(v).Error
})
return configs, err
}
// GetTelegramConfig returns the telegram config.
func (m *customSystemModel) GetTelegramConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.TelegramConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "telegram").Find(v).Error
})
return configs, err
}
// GetTosConfig returns the tos config.
func (m *customSystemModel) GetTosConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.TosConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "tos").Find(v).Error
})
return configs, err
}
// GetCurrencyConfig returns the currency config.
func (m *customSystemModel) GetCurrencyConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.CurrencyConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "currency").Find(v).Error
})
return configs, err
}
func (m *customSystemModel) UpdateNodeMultiplierConfig(ctx context.Context, config string) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
return conn.Model(&System{}).Where("`category` = ? AND `key` = ?", "server", "NodeMultiplierConfig").Update("value", config).Error
})
}
func (m *customSystemModel) FindNodeMultiplierConfig(ctx context.Context) (*System, error) {
var data System
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ? AND `key` = ?", "server", "NodeMultiplierConfig").Find(v).Error
})
return &data, err
}
// GetVerifyCodeConfig returns the verify code config.
func (m *customSystemModel) GetVerifyCodeConfig(ctx context.Context) ([]*System, error) {
var configs []*System
err := m.QueryCtx(ctx, &configs, config.VerifyCodeConfigKey, func(conn *gorm.DB, v interface{}) error {
return conn.Where("`category` = ?", "verify_code").Find(v).Error
})
return configs, err
}
+18
View File
@@ -0,0 +1,18 @@
package system
import "time"
type System struct {
Id int64 `gorm:"primarykey"`
Category string `gorm:"type:varchar(100);default:'';not null;comment:Category"`
Key string `gorm:"index:index_key;unique;type:varchar(100);default:'';not null;comment:Key Name"`
Value string `gorm:"type:text;not null;comment:Key Value"`
Type string `gorm:"type:varchar(50);default:'';not null;comment:Type"`
Desc string `gorm:"type:text;not null;comment:Description"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (System) TableName() string {
return "system"
}
+118
View File
@@ -0,0 +1,118 @@
package ticket
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var _ Model = (*customTicketModel)(nil)
var (
cacheTicketIdPrefix = "cache:ticket:id:"
)
type (
Model interface {
ticketModel
customTicketLogicModel
}
ticketModel interface {
Insert(ctx context.Context, data *Ticket) error
FindOne(ctx context.Context, id int64) (*Ticket, error)
Update(ctx context.Context, data *Ticket) error
Delete(ctx context.Context, id int64) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customTicketModel struct {
*defaultTicketModel
}
defaultTicketModel struct {
cache.CachedConn
table string
}
)
func newTicketModel(db *gorm.DB, c *redis.Client) *defaultTicketModel {
return &defaultTicketModel{
CachedConn: cache.NewConn(db, c),
table: "`ticket`",
}
}
//nolint:unused
func (m *defaultTicketModel) batchGetCacheKeys(Tickets ...*Ticket) []string {
var keys []string
for _, ticket := range Tickets {
keys = append(keys, m.getCacheKeys(ticket)...)
}
return keys
}
func (m *defaultTicketModel) getCacheKeys(data *Ticket) []string {
if data == nil {
return []string{}
}
ticketIdKey := fmt.Sprintf("%s%v", cacheTicketIdPrefix, data.Id)
cacheKeys := []string{
ticketIdKey,
}
return cacheKeys
}
func (m *defaultTicketModel) Insert(ctx context.Context, data *Ticket) error {
err := m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(&data).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultTicketModel) FindOne(ctx context.Context, id int64) (*Ticket, error) {
TicketIdKey := fmt.Sprintf("%s%v", cacheTicketIdPrefix, id)
var resp Ticket
err := m.QueryCtx(ctx, &resp, TicketIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Ticket{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultTicketModel) Update(ctx context.Context, data *Ticket) 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 *defaultTicketModel) 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(&Ticket{}, id).Error
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultTicketModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+98
View File
@@ -0,0 +1,98 @@
package ticket
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var cacheTicketDetailPrefix = "cache:ticket:detail:"
type Details struct {
Id int64 `gorm:"primaryKey"`
Title string `gorm:"type:varchar(255);not null;default:'';comment:Title"`
Description string `gorm:"type:text;comment:Description"`
UserId int64 `gorm:"type:bigint;not null;default:0;comment:UserId"`
Status uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Status"`
Follows []Follow `gorm:"foreignKey:TicketId;references:Id"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
type customTicketLogicModel interface {
QueryTicketDetail(ctx context.Context, id int64) (*Details, error)
InsertTicketFollow(ctx context.Context, data *Follow) error
QueryTicketList(ctx context.Context, page, size int, userId int64, status *uint8, search string) (int64, []*Ticket, error)
UpdateTicketStatus(ctx context.Context, id, userId int64, status uint8) error
QueryWaitReplyTotal(ctx context.Context) (int64, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customTicketModel{
defaultTicketModel: newTicketModel(conn, c),
}
}
// QueryTicketDetail returns the ticket details.
func (m *customTicketModel) QueryTicketDetail(ctx context.Context, id int64) (*Details, error) {
key := fmt.Sprintf("%s%v", cacheTicketDetailPrefix, id)
var data *Details
err := m.QueryCtx(ctx, &data, key, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Ticket{}).Where("id = ?", id).Preload("Follows").First(v).Error
})
return data, err
}
// InsertTicketFollow inserts a follow record.
func (m *customTicketModel) InsertTicketFollow(ctx context.Context, data *Follow) error {
key := fmt.Sprintf("%s%v", cacheTicketDetailPrefix, data.TicketId)
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Model(&Follow{}).Create(data).Error
}, key)
}
// QueryTicketList returns the ticket list.
func (m *customTicketModel) QueryTicketList(ctx context.Context, page, size int, userId int64, status *uint8, search string) (int64, []*Ticket, error) {
var data []*Ticket
var total int64
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
query := conn.Model(&Ticket{})
if userId > 0 {
query = query.Where("user_id = ?", userId)
}
if status != nil {
query = query.Where("status = ?", status)
} else {
query = query.Where("status != ?", 4)
}
if search != "" {
query = query.Where("title like ? or description like ?", "%"+search+"%", "%"+search+"%")
}
return query.Count(&total).Order("id desc").Limit(size).Offset((page - 1) * size).Find(v).Error
})
return total, data, err
}
// UpdateTicketStatus updates the ticket status.
func (m *customTicketModel) UpdateTicketStatus(ctx context.Context, id, userId int64, status uint8) error {
key := fmt.Sprintf("%s%v", cacheTicketDetailPrefix, id)
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
conn = conn.Model(&Ticket{})
if userId > 0 {
conn = conn.Where("user_id = ?", userId)
}
return conn.Where("id = ?", id).Update("status", status).Error
}, key)
}
// QueryWaitReplyTotal returns the total number of tickets that are waiting for a reply.
func (m *customTicketModel) QueryWaitReplyTotal(ctx context.Context) (int64, error) {
var total int64
err := m.QueryNoCacheCtx(ctx, &total, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Ticket{}).Where("status = ?", Pending).Count(&total).Error
})
return total, err
}
+37
View File
@@ -0,0 +1,37 @@
package ticket
import "time"
const (
Pending = 1 // Pending # Pending follow up
Waiting = 2 // Waiting # Waiting for user response
Processed = 3 // Processed
Closed = 4 // Closed
)
type Ticket struct {
Id int64 `gorm:"primaryKey"`
Title string `gorm:"type:varchar(255);not null;default:'';comment:Title"`
Description string `gorm:"type:text;comment:Description"`
UserId int64 `gorm:"type:bigint;not null;default:0;comment:UserId"`
Status uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Status"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Ticket) TableName() string {
return "ticket"
}
type Follow struct {
Id int64 `gorm:"primaryKey"`
TicketId int64 `gorm:"type:bigint;not null;default:0;comment:TicketId"`
From string `gorm:"type:varchar(255);not null;default:'';comment:From"`
Type uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Type: 1 text, 2 image"`
Content string `gorm:"type:text;comment:Content"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
}
func (Follow) TableName() string {
return "ticket_follow"
}
+69
View File
@@ -0,0 +1,69 @@
package traffic
import (
"context"
"errors"
"gorm.io/gorm"
)
var _ Model = (*customTrafficModel)(nil)
type (
Model interface {
trafficModel
customTrafficLogicModel
}
trafficModel interface {
Insert(ctx context.Context, data *TrafficLog) error
FindOne(ctx context.Context, id int64) (*TrafficLog, error)
Update(ctx context.Context, data *TrafficLog) error
Delete(ctx context.Context, id int64) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customTrafficModel struct {
*defaultTrafficModel
}
defaultTrafficModel struct {
Conn *gorm.DB
table string
}
)
func newTrafficModel(db *gorm.DB) *defaultTrafficModel {
return &defaultTrafficModel{
Conn: db,
table: "`traffic`",
}
}
func (m *defaultTrafficModel) Insert(ctx context.Context, data *TrafficLog) error {
return m.Conn.WithContext(ctx).Create(&data).Error
}
func (m *defaultTrafficModel) FindOne(ctx context.Context, id int64) (*TrafficLog, error) {
var data TrafficLog
err := m.Conn.WithContext(ctx).Model(&TrafficLog{}).Where("`id` = ?", id).First(&data).Error
return &data, err
}
func (m *defaultTrafficModel) Update(ctx context.Context, data *TrafficLog) error {
return m.Conn.WithContext(ctx).Save(data).Error
}
func (m *defaultTrafficModel) Delete(ctx context.Context, id int64) error {
_, err := m.FindOne(ctx, id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil
}
return err
}
return m.Conn.WithContext(ctx).Delete(&TrafficLog{}, id).Error
}
func (m *defaultTrafficModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.Conn.WithContext(ctx).Transaction(fn)
}
+123
View File
@@ -0,0 +1,123 @@
package traffic
import (
"context"
"time"
"gorm.io/gorm"
)
type customTrafficLogicModel interface {
QueryServerTrafficByDay(ctx context.Context, serverId int64, date time.Time) (*TotalTraffic, error)
QueryTrafficByDay(ctx context.Context, date time.Time) (*TotalTraffic, error)
QueryTrafficByMonthly(ctx context.Context, date time.Time) (*TotalTraffic, error)
TopServersTrafficByDay(ctx context.Context, date time.Time, limit int) ([]ServerTrafficRanking, error)
TopServersTrafficByMonthly(ctx context.Context, date time.Time, limit int) ([]ServerTrafficRanking, error)
TopUsersTrafficByDay(ctx context.Context, date time.Time, limit int) ([]UserTrafficRanking, error)
TopUsersTrafficByMonthly(ctx context.Context, date time.Time, limit int) ([]UserTrafficRanking, error)
QueryTrafficLogPageList(ctx context.Context, userId, subscribeId int64, page, size int) ([]*TrafficLog, int64, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB) Model {
return &customTrafficModel{
defaultTrafficModel: newTrafficModel(conn),
}
}
func (m *customTrafficModel) QueryServerTrafficByDay(ctx context.Context, serverId int64, date time.Time) (*TotalTraffic, error) {
var data TotalTraffic
start := date.Truncate(24 * time.Hour)
end := start.Add(24 * time.Hour).Add(-time.Nanosecond)
err := m.Conn.WithContext(ctx).Model(&TrafficLog{}).
Select("sum(download) as download, sum(upload) as upload").
Where("server_id = ? AND timestamp BETWEEN ? AND ?", serverId, start, end).
Scan(&data).Error
return &data, err
}
func (m *customTrafficModel) QueryTrafficByDay(ctx context.Context, date time.Time) (*TotalTraffic, error) {
var data TotalTraffic
start := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.Local)
end := start.Add(24 * time.Hour).Add(-time.Nanosecond)
err := m.Conn.WithContext(ctx).Model(&TrafficLog{}).
Select("sum(download) as download, sum(upload) as upload").
Where("timestamp BETWEEN ? AND ?", start, end).
Scan(&data).Error
return &data, err
}
func (m *customTrafficModel) QueryTrafficByMonthly(ctx context.Context, date time.Time) (*TotalTraffic, error) {
var data TotalTraffic
start := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.Local)
end := start.AddDate(0, 1, 0).Add(-time.Nanosecond)
err := m.Conn.WithContext(ctx).Model(&TrafficLog{}).
Select("sum(download) as download, sum(upload) as upload").
Where("timestamp BETWEEN ? AND ?", start, end).
Scan(&data).Error
return &data, err
}
func (m *customTrafficModel) TopServersTrafficByDay(ctx context.Context, date time.Time, limit int) ([]ServerTrafficRanking, error) {
var summaries []ServerTrafficRanking
start := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.Local)
end := start.Add(24 * time.Hour).Add(-time.Nanosecond)
err := m.Conn.Debug().WithContext(ctx).Model(&TrafficLog{}).
Select("server_id, SUM(download + upload) AS total, SUM(download) AS download, SUM(upload) AS upload").
Where("timestamp BETWEEN ? AND ?", start, end).
Group("server_id").
Order("total DESC").
Limit(limit).
Scan(&summaries).Error
return summaries, err
}
func (m *customTrafficModel) TopServersTrafficByMonthly(ctx context.Context, date time.Time, limit int) ([]ServerTrafficRanking, error) {
var summaries []ServerTrafficRanking
start := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.Local)
end := start.AddDate(0, 1, 0).Add(-time.Nanosecond)
err := m.Conn.WithContext(ctx).Model(&TrafficLog{}).
Select("server_id, SUM(download + upload) AS total, SUM(download) AS download, SUM(upload) AS upload").
Where("timestamp BETWEEN ? AND ?", start, end).
Group("server_id").
Order("total DESC").
Limit(limit).
Scan(&summaries).Error
return summaries, err
}
func (m *customTrafficModel) TopUsersTrafficByDay(ctx context.Context, date time.Time, limit int) ([]UserTrafficRanking, error) {
var summaries []UserTrafficRanking
start := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.Local)
end := start.Add(24 * time.Hour).Add(-time.Nanosecond)
err := m.Conn.WithContext(ctx).Model(&TrafficLog{}).
Select("user_id, subscribe_id, SUM(download + upload) AS total, SUM(download) AS download, SUM(upload) AS upload").
Where("timestamp BETWEEN ? AND ?", start, end).
Group("user_id, subscribe_id"). // 修改这里,添加 subscribe_id 到 GROUP BY 子句
Order("total DESC").
Limit(limit).
Scan(&summaries).Error
return summaries, err
}
func (m *customTrafficModel) TopUsersTrafficByMonthly(ctx context.Context, date time.Time, limit int) ([]UserTrafficRanking, error) {
var summaries []UserTrafficRanking
start := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.Local)
end := start.AddDate(0, 1, 0).Add(-time.Nanosecond)
err := m.Conn.WithContext(ctx).Model(&TrafficLog{}).
Select("user_id, subscribe_id, SUM(download + upload) AS total, SUM(download) AS download, SUM(upload) AS upload"). // 添加 subscribe_id 到 SELECT 列表
Where("timestamp BETWEEN ? AND ?", start, end).
Group("user_id, subscribe_id"). // 修改这里,添加 subscribe_id 到 GROUP BY 子句
Order("total DESC").
Limit(limit).
Scan(&summaries).Error
return summaries, err
}
// QueryTrafficLogPageList returns a list of records that meet the conditions.
func (m *customTrafficModel) QueryTrafficLogPageList(ctx context.Context, userId, subscribeId int64, page, size int) ([]*TrafficLog, int64, error) {
var list []*TrafficLog
var total int64
err := m.Conn.WithContext(ctx).Model(&TrafficLog{}).Where("user_id = ? and subscribe_id= ?", userId, subscribeId).Count(&total).Limit(size).Offset((page - 1) * size).Find(&list).Error
return list, total, err
}
+38
View File
@@ -0,0 +1,38 @@
package traffic
import "time"
//goland:noinspection GoNameStartsWithPackageName
type TrafficLog struct {
Id int64 `gorm:"primaryKey"`
ServerId int64 `gorm:"index:idx_server_id;not null;comment:Server ID"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
SubscribeId int64 `gorm:"index:idx_subscribe_id;not null;comment:Subscription ID"`
Download int64 `gorm:"default:0;comment:Download Traffic"`
Upload int64 `gorm:"default:0;comment:Upload Traffic"`
Timestamp time.Time `gorm:"default:CURRENT_TIMESTAMP(3);not null;comment:Traffic Log Time"`
}
type TotalTraffic struct {
Download int64
Upload int64
}
type ServerTrafficRanking struct {
ServerId int64
Download int64
Upload int64
Total int64
}
type UserTrafficRanking struct {
UserId int64
SubscribeId int64
Download int64
Upload int64
Total int64
}
func (TrafficLog) TableName() string {
return "traffic_log"
}
+66
View File
@@ -0,0 +1,66 @@
package user
import (
"context"
"gorm.io/gorm"
)
func (m *defaultUserModel) FindUserAuthMethods(ctx context.Context, userId int64) ([]*AuthMethods, error) {
var data []*AuthMethods
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&AuthMethods{}).Where("user_id = ?", userId).Find(&data).Error
})
return data, err
}
func (m *defaultUserModel) FindUserAuthMethodByOpenID(ctx context.Context, method, openID string) (*AuthMethods, error) {
var data AuthMethods
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&AuthMethods{}).Where("auth_type = ? AND auth_identifier = ?", method, openID).First(&data).Error
})
return &data, err
}
func (m *defaultUserModel) FindUserAuthMethodByPlatform(ctx context.Context, userId int64, platform string) (*AuthMethods, error) {
var data AuthMethods
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&AuthMethods{}).Where("user_id = ? AND auth_type = ?", userId, platform).First(&data).Error
})
return &data, err
}
func (m *defaultUserModel) InsertUserAuthMethods(ctx context.Context, data *AuthMethods, tx ...*gorm.DB) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&AuthMethods{}).Create(data).Error
})
}
func (m *defaultUserModel) UpdateUserAuthMethods(ctx context.Context, data *AuthMethods, tx ...*gorm.DB) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&AuthMethods{}).Where("user_id = ? AND auth_type = ?", data.UserId, data.AuthType).Save(data).Error
})
}
func (m *defaultUserModel) DeleteUserAuthMethods(ctx context.Context, userId int64, platform string, tx ...*gorm.DB) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&AuthMethods{}).Where("user_id = ? AND auth_type = ?", userId, platform).Delete(&AuthMethods{}).Error
})
}
func (m *defaultUserModel) FindUserAuthMethodByUserId(ctx context.Context, method string, userId int64) (*AuthMethods, error) {
var data AuthMethods
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&AuthMethods{}).Where("auth_type = ? AND user_id = ?", method, userId).First(&data).Error
})
return &data, err
}
+181
View File
@@ -0,0 +1,181 @@
package user
import (
"context"
"errors"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var (
cacheUserIdPrefix = "cache:user:id:"
cacheUserEmailPrefix = "cache:user:email:"
)
var _ Model = (*customUserModel)(nil)
type (
Model interface {
userModel
customUserLogicModel
}
userModel interface {
Insert(ctx context.Context, data *User, tx ...*gorm.DB) error
FindOne(ctx context.Context, id int64) (*User, error)
Update(ctx context.Context, data *User, 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
}
customUserModel struct {
*defaultUserModel
}
defaultUserModel struct {
cache.CachedConn
table string
}
)
func newUserModel(db *gorm.DB, c *redis.Client) *defaultUserModel {
return &defaultUserModel{
CachedConn: cache.NewConn(db, c),
table: "`user`",
}
}
func (m *defaultUserModel) batchGetCacheKeys(users ...*User) []string {
var keys []string
for _, user := range users {
keys = append(keys, m.getCacheKeys(user)...)
}
return keys
}
func (m *defaultUserModel) getCacheKeys(data *User) []string {
if data == nil {
return []string{}
}
userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, data.Id)
cacheKeys := []string{
userIdKey,
}
// email key
if len(data.AuthMethods) > 0 {
for _, auth := range data.AuthMethods {
if auth.AuthType == "email" {
cacheKeys = append(cacheKeys, fmt.Sprintf("%s%v", cacheUserEmailPrefix, auth.AuthIdentifier))
break
}
}
}
return cacheKeys
}
func (m *defaultUserModel) FindOneByEmail(ctx context.Context, email string) (*User, error) {
var user User
key := fmt.Sprintf("%s%v", cacheUserEmailPrefix, email)
err := m.QueryCtx(ctx, &user, key, func(conn *gorm.DB, v interface{}) error {
var data AuthMethods
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 &user, err
}
func (m *defaultUserModel) Insert(ctx context.Context, data *User, 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 *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 &resp, err
}
func (m *defaultUserModel) Update(ctx context.Context, data *User, 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 *defaultUserModel) 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.Transaction(func(db *gorm.DB) error {
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(&User{}).Error; err != nil {
return err
}
if err := db.Model(&Subscribe{}).Where("`user_id` = ?", id).Delete(&User{}).Error; err != nil {
return err
}
if err := db.Model(&BalanceLog{}).Where("`user_id` = ?", id).Delete(&User{}).Error; err != nil {
return err
}
if err := db.Model(&GiftAmountLog{}).Where("`user_id` = ?", id).Delete(&User{}).Error; err != nil {
return err
}
if err := db.Model(&LoginLog{}).Where("`user_id` = ?", id).Delete(&User{}).Error; err != nil {
return err
}
if err := db.Model(&SubscribeLog{}).Where("`user_id` = ?", id).Delete(&User{}).Error; err != nil {
return err
}
if err := db.Model(&Device{}).Where("`user_id` = ?", id).Delete(&User{}).Error; err != nil {
return err
}
subs, err := m.QueryUserSubscribe(ctx, id)
if err != nil {
return err
}
for _, sub := range subs {
if err := m.DeleteSubscribeById(ctx, sub.Id, db); err != nil {
return err
}
}
if err := db.Model(&CommissionLog{}).Where("`user_id` = ?", id).Delete(&User{}).Error; err != nil {
return err
}
return nil
})
}, m.getCacheKeys(data)...)
return err
}
func (m *defaultUserModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.TransactCtx(ctx, fn)
}
+80
View File
@@ -0,0 +1,80 @@
package user
import (
"context"
"errors"
"fmt"
"gorm.io/gorm"
)
func (m *customUserModel) FindOneDevice(ctx context.Context, id int64) (*Device, error) {
deviceIdKey := fmt.Sprintf("%s%v", cacheUserDeviceIdPrefix, id)
var resp Device
err := m.QueryCtx(ctx, &resp, deviceIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Device{}).Where("`id` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *customUserModel) FindOneDeviceByIdentifier(ctx context.Context, id string) (*Device, error) {
deviceIdKey := fmt.Sprintf("%s%v", cacheUserDeviceNumberPrefix, id)
var resp Device
err := m.QueryCtx(ctx, &resp, deviceIdKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Device{}).Where("`identifier` = ?", id).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
// QueryDevicePageList returns a list of records that meet the conditions.
func (m *customUserModel) QueryDevicePageList(ctx context.Context, userId, subscribeId int64, page, size int) ([]*Device, int64, error) {
var list []*Device
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Device{}).Where("`user_id` = ? and `subscribe_id` = ?", userId, subscribeId).Count(&total).Limit(size).Offset((page - 1) * size).Find(&list).Error
})
return list, total, err
}
func (m *customUserModel) UpdateDevice(ctx context.Context, data *Device, tx ...*gorm.DB) error {
old, err := m.FindOneDevice(ctx, data.Id)
if err != nil {
return err
}
deviceIdKey := fmt.Sprintf("%s%v", cacheUserDeviceIdPrefix, old.Id)
err = m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Save(data).Error
}, deviceIdKey)
return err
}
func (m *customUserModel) DeleteDevice(ctx context.Context, id int64, tx ...*gorm.DB) error {
data, err := m.FindOneDevice(ctx, id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil
}
return err
}
deviceIdKey := fmt.Sprintf("%s%v", cacheUserDeviceIdPrefix, data.Id)
err = m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Delete(&Device{}, id).Error
}, deviceIdKey)
return err
}
+81
View File
@@ -0,0 +1,81 @@
package user
import (
"context"
"github.com/pkg/errors"
"gorm.io/gorm"
)
func (m *customUserModel) InsertSubscribeLog(ctx context.Context, log *SubscribeLog) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(log).Error
})
}
func (m *customUserModel) FilterSubscribeLogList(ctx context.Context, page, size int, filter *SubscribeLogFilterParams) ([]*SubscribeLog, int64, error) {
var list []*SubscribeLog
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
query := conn.Model(&SubscribeLog{})
if filter != nil {
if filter.UserId != 0 {
query = query.Where("user_id = ?", filter.UserId)
}
if filter.UserSubscribeId != 0 {
query = query.Where("user_subscribe_id = ?", filter.UserSubscribeId)
}
if filter.IP != "" {
query = query.Where("ip LIKE ?", "%"+filter.IP+"%")
}
if filter.Token != "" {
query = query.Where("token LIKE ?", "%"+filter.Token+"%")
}
if filter.UserAgent != "" {
query = query.Where("user_agent LIKE ?", "%"+filter.UserAgent+"%")
}
}
return query.Count(&total).Limit(size).Offset((page - 1) * size).Find(v).Error
})
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, 0, err
}
return list, total, nil
}
func (m *customUserModel) InsertLoginLog(ctx context.Context, log *LoginLog) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
return conn.Create(log).Error
})
}
func (m *customUserModel) FilterLoginLogList(ctx context.Context, page, size int, filter *LoginLogFilterParams) ([]*LoginLog, int64, error) {
var list []*LoginLog
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
query := conn.Model(&LoginLog{})
if filter != nil {
if filter.UserId != 0 {
query = query.Where("user_id = ?", filter.UserId)
}
if filter.IP != "" {
query = query.Where("ip LIKE ?", "%"+filter.IP+"%")
}
if filter.UserAgent != "" {
query = query.Where("user_agent LIKE ?", "%"+filter.UserAgent+"%")
}
if filter.Success != nil {
query = query.Where("success = ?", *filter.Success)
}
}
return query.Count(&total).Limit(size).Offset((page - 1) * size).Find(v).Error
})
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, 0, err
}
return list, total, nil
}
+400
View File
@@ -0,0 +1,400 @@
package user
import (
"context"
"errors"
"fmt"
"time"
"github.com/perfect-panel/ppanel-server/internal/config"
"github.com/perfect-panel/ppanel-server/internal/model/server"
"github.com/perfect-panel/ppanel-server/internal/model/subscribe"
"github.com/perfect-panel/ppanel-server/pkg/logger"
"github.com/perfect-panel/ppanel-server/pkg/tool"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
const (
cacheUserSubscribeTokenPrefix = "cache:user:subscribe:token:"
cacheUserSubscribeUserPrefix = "cache:user:subscribe:user:"
cacheUserSubscribeIdPrefix = "cache:user:subscribe:id:"
cacheUserDeviceNumberPrefix = "cache:user:device:number:"
cacheUserDeviceIdPrefix = "cache:user:device:id:"
)
type SubscribeDetails struct {
Id int64 `gorm:"primarykey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
User *User `gorm:"foreignKey:UserId;references:Id"`
OrderId int64 `gorm:"index:idx_order_id;not null;comment:Order ID"`
SubscribeId int64 `gorm:"index:idx_subscribe_id;not null;comment:Subscription ID"`
Subscribe *subscribe.Subscribe `gorm:"foreignKey:SubscribeId;references:Id"`
StartTime time.Time `gorm:"default:CURRENT_TIMESTAMP(3);not null;comment:Subscription Start Time"`
ExpireTime time.Time `gorm:"default:NULL;comment:Subscription Expire Time"`
Traffic int64 `gorm:"default:0;comment:Traffic"`
Download int64 `gorm:"default:0;comment:Download Traffic"`
Upload int64 `gorm:"default:0;comment:Upload Traffic"`
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: Cancelled"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
type SubscribeLogFilterParams struct {
IP string
UserAgent string
UserId int64
Token string
UserSubscribeId int64
}
type LoginLogFilterParams struct {
IP string
UserId int64
UserAgent string
Success *bool
}
type UserFilterParams struct {
Search string
UserId *int64
SubscribeId *int64
UserSubscribeId *int64
}
type customUserLogicModel interface {
QueryPageList(ctx context.Context, page, size int, filter *UserFilterParams) ([]*User, int64, error)
FindOneByReferCode(ctx context.Context, referCode string) (*User, error)
BatchDeleteUser(ctx context.Context, ids []int64, tx ...*gorm.DB) error
InsertSubscribe(ctx context.Context, data *Subscribe, tx ...*gorm.DB) error
FindOneSubscribeByToken(ctx context.Context, token string) (*Subscribe, error)
FindOneSubscribeByOrderId(ctx context.Context, orderId int64) (*Subscribe, error)
FindOneSubscribe(ctx context.Context, id int64) (*Subscribe, error)
UpdateSubscribe(ctx context.Context, data *Subscribe, tx ...*gorm.DB) error
DeleteSubscribe(ctx context.Context, token string, tx ...*gorm.DB) error
DeleteSubscribeById(ctx context.Context, id int64, tx ...*gorm.DB) error
QueryUserSubscribe(ctx context.Context, userId int64, status ...int64) ([]*SubscribeDetails, error)
FindOneSubscribeDetailsById(ctx context.Context, id int64) (*SubscribeDetails, error)
FindOneUserSubscribe(ctx context.Context, id int64) (*SubscribeDetails, error)
InsertBalanceLog(ctx context.Context, data *BalanceLog, tx ...*gorm.DB) error
FindUsersSubscribeBySubscribeId(ctx context.Context, subscribeId int64) ([]*Subscribe, error)
UpdateUserSubscribeWithTraffic(ctx context.Context, id, download, upload int64, tx ...*gorm.DB) error
QueryResisterUserTotalByDate(ctx context.Context, date time.Time) (int64, error)
QueryResisterUserTotalByMonthly(ctx context.Context, date time.Time) (int64, error)
QueryResisterUserTotal(ctx context.Context) (int64, error)
QueryAdminUsers(ctx context.Context) ([]*User, error)
UpdateUserCache(ctx context.Context, data *User) error
UpdateUserSubscribeCache(ctx context.Context, data *Subscribe) error
InsertCommissionLog(ctx context.Context, data *CommissionLog, tx ...*gorm.DB) error
QueryActiveSubscriptions(ctx context.Context, subscribeId ...int64) (map[int64]int64, error)
FindUserAuthMethods(ctx context.Context, userId int64) ([]*AuthMethods, error)
InsertUserAuthMethods(ctx context.Context, data *AuthMethods, tx ...*gorm.DB) error
UpdateUserAuthMethods(ctx context.Context, data *AuthMethods, tx ...*gorm.DB) error
DeleteUserAuthMethods(ctx context.Context, userId int64, platform string, tx ...*gorm.DB) error
FindUserAuthMethodByOpenID(ctx context.Context, method, openID string) (*AuthMethods, error)
FindUserAuthMethodByUserId(ctx context.Context, method string, userId int64) (*AuthMethods, error)
FindUserAuthMethodByPlatform(ctx context.Context, userId int64, platform string) (*AuthMethods, error)
FindOneByEmail(ctx context.Context, email string) (*User, error)
FindOneDevice(ctx context.Context, id int64) (*Device, error)
QueryDevicePageList(ctx context.Context, userid, subscribeId int64, page, size int) ([]*Device, int64, error)
UpdateDevice(ctx context.Context, data *Device, tx ...*gorm.DB) error
FindOneDeviceByIdentifier(ctx context.Context, id string) (*Device, error)
DeleteDevice(ctx context.Context, id int64, tx ...*gorm.DB) error
InsertSubscribeLog(ctx context.Context, log *SubscribeLog) error
FilterSubscribeLogList(ctx context.Context, page, size int, filter *SubscribeLogFilterParams) ([]*SubscribeLog, int64, error)
InsertLoginLog(ctx context.Context, log *LoginLog) error
FilterLoginLogList(ctx context.Context, page, size int, filter *LoginLogFilterParams) ([]*LoginLog, int64, error)
ClearSubscribeCache(ctx context.Context, data ...*Subscribe) error
InsertResetSubscribeLog(ctx context.Context, log *ResetSubscribeLog, tx ...*gorm.DB) error
UpdateResetSubscribeLog(ctx context.Context, log *ResetSubscribeLog, tx ...*gorm.DB) error
FindResetSubscribeLog(ctx context.Context, id int64) (*ResetSubscribeLog, error)
DeleteResetSubscribeLog(ctx context.Context, id int64, tx ...*gorm.DB) error
FilterResetSubscribeLogList(ctx context.Context, filter *FilterResetSubscribeLogParams) ([]*ResetSubscribeLog, int64, error)
}
// NewModel returns a model for the database table.
func NewModel(conn *gorm.DB, c *redis.Client) Model {
return &customUserModel{
defaultUserModel: newUserModel(conn, c),
}
}
func (m *defaultUserModel) getSubscribeCacheKey(data *Subscribe) []string {
if data == nil {
return []string{}
}
var keys []string
if data.Token != "" {
keys = append(keys, fmt.Sprintf("%s%s", cacheUserSubscribeTokenPrefix, data.Token))
}
if data.UserId != 0 {
keys = append(keys, fmt.Sprintf("%s%d", cacheUserSubscribeUserPrefix, data.UserId))
}
if data.Id != 0 {
keys = append(keys, fmt.Sprintf("%s%d", cacheUserSubscribeIdPrefix, data.Id))
}
if data.SubscribeId != 0 {
var sub *subscribe.Subscribe
err := m.QueryNoCacheCtx(context.Background(), &sub, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&subscribe.Subscribe{}).Where("id = ?", data.SubscribeId).First(&sub).Error
})
if err != nil {
logger.Error("getUserSubscribeCacheKey", logger.Field("error", err.Error()), logger.Field("subscribeId", data.SubscribeId))
return keys
}
if sub.Server != "" {
ids := tool.StringToInt64Slice(sub.Server)
for _, id := range ids {
keys = append(keys, fmt.Sprintf("%s%d", config.ServerUserListCacheKey, id))
}
}
if sub.ServerGroup != "" {
ids := tool.StringToInt64Slice(sub.ServerGroup)
var servers []*server.Server
err = m.QueryNoCacheCtx(context.Background(), &servers, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&server.Server{}).Where("group_id in ?", ids).Find(v).Error
})
if err != nil {
logger.Error("getUserSubscribeCacheKey", logger.Field("error", err.Error()), logger.Field("subscribeId", data.SubscribeId))
return keys
}
for _, s := range servers {
keys = append(keys, fmt.Sprintf("%s%d", config.ServerUserListCacheKey, s.Id))
}
}
}
return keys
}
// QueryPageList returns a list of records that meet the conditions.
func (m *customUserModel) QueryPageList(ctx context.Context, page, size int, filter *UserFilterParams) ([]*User, int64, error) {
var list []*User
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
if filter != nil {
if filter.UserId != nil {
conn = conn.Where("user.id =?", *filter.UserId)
}
if filter.Search != "" {
conn = conn.Joins("LEFT JOIN user_auth_methods ON user.id = user_auth_methods.user_id").
Where("user_auth_methods.auth_identifier LIKE ?", "%"+filter.Search+"%").Or("user.refer_code like ?", "%"+filter.Search+"%")
}
if filter.UserSubscribeId != nil {
conn = conn.Joins("LEFT JOIN user_subscribe ON user.id = user_subscribe.user_id").
Where("user_subscribe.id =? and `status` IN (0,1)", *filter.UserSubscribeId)
}
if filter.SubscribeId != nil {
conn = conn.Joins("LEFT JOIN user_subscribe ON user.id = user_subscribe.user_id").
Where("user_subscribe.subscribe_id =? and `status` IN (0,1)", *filter.SubscribeId)
}
}
return conn.Model(&User{}).Group("user.id").Count(&total).Limit(size).Offset((page - 1) * size).Preload("UserDevices").Preload("AuthMethods").Find(&list).Error
})
return list, total, err
}
// BatchDeleteUser deletes multiple records by primary key.
func (m *customUserModel) BatchDeleteUser(ctx context.Context, ids []int64, tx ...*gorm.DB) error {
var users []*User
err := m.QueryNoCacheCtx(ctx, &users, func(conn *gorm.DB, v interface{}) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Where("id in ?", ids).Find(&users).Error
})
if err != nil {
return err
}
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
return conn.Where("id in ?", ids).Delete(&User{}).Error
}, m.batchGetCacheKeys(users...)...)
}
// InsertBalanceLog insert BalanceLog into the database.
func (m *customUserModel) InsertBalanceLog(ctx context.Context, data *BalanceLog, tx ...*gorm.DB) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Create(data).Error
})
}
// FindUserBalanceLogList returns a list of records that meet the conditions.
func (m *customUserModel) FindUserBalanceLogList(ctx context.Context, userId int64, page, size int) ([]*BalanceLog, int64, error) {
var list []*BalanceLog
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&BalanceLog{}).Where("`user_id` = ?", userId).Count(&total).Limit(size).Offset((page - 1) * size).Find(&list).Error
})
return list, total, err
}
func (m *customUserModel) UpdateUserSubscribeWithTraffic(ctx context.Context, id, download, upload int64, tx ...*gorm.DB) error {
sub, err := m.FindOneSubscribe(ctx, id)
if err != nil {
return err
}
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&Subscribe{}).Where("id = ?", id).Updates(map[string]interface{}{
"download": gorm.Expr("download + ?", download),
"upload": gorm.Expr("upload + ?", upload),
}).Error
}, m.getSubscribeCacheKey(sub)...)
}
func (m *customUserModel) QueryResisterUserTotalByDate(ctx context.Context, date time.Time) (int64, error) {
var total int64
start := date.Truncate(24 * time.Hour)
end := start.Add(24 * time.Hour).Add(-time.Second)
err := m.QueryNoCacheCtx(ctx, &total, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&User{}).Where("created_at > ? and created_at < ?", start, end).Count(&total).Error
})
return total, err
}
func (m *customUserModel) QueryResisterUserTotalByMonthly(ctx context.Context, date time.Time) (int64, error) {
var total int64
start := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.Local)
end := start.AddDate(0, 1, 0).Add(-time.Nanosecond)
err := m.QueryNoCacheCtx(ctx, &total, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&User{}).Where("created_at > ? and created_at < ?", start, end).Count(&total).Error
})
return total, err
}
func (m *customUserModel) QueryResisterUserTotal(ctx context.Context) (int64, error) {
var total int64
err := m.QueryNoCacheCtx(ctx, &total, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&User{}).Count(&total).Error
})
return total, err
}
func (m *customUserModel) QueryAdminUsers(ctx context.Context) ([]*User, error) {
var data []*User
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&User{}).Preload("AuthMethods").Where("is_admin = ?", true).Find(&data).Error
})
return data, err
}
func (m *customUserModel) UpdateUserCache(ctx context.Context, data *User) error {
return m.CachedConn.DelCacheCtx(ctx, m.getCacheKeys(data)...)
}
func (m *customUserModel) InsertCommissionLog(ctx context.Context, data *CommissionLog, tx ...*gorm.DB) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&CommissionLog{}).Create(data).Error
})
}
func (m *customUserModel) FindOneByReferCode(ctx context.Context, referCode string) (*User, error) {
var data User
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&User{}).Where("refer_code = ?", referCode).First(&data).Error
})
return &data, err
}
func (m *customUserModel) FindOneSubscribeDetailsById(ctx context.Context, id int64) (*SubscribeDetails, error) {
var data SubscribeDetails
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Subscribe{}).Preload("Subscribe").Preload("User").Where("id = ?", id).First(&data).Error
})
return &data, err
}
func (m *customUserModel) InsertResetSubscribeLog(ctx context.Context, log *ResetSubscribeLog, tx ...*gorm.DB) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&ResetSubscribeLog{}).Create(log).Error
})
}
func (m *customUserModel) UpdateResetSubscribeLog(ctx context.Context, log *ResetSubscribeLog, tx ...*gorm.DB) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&ResetSubscribeLog{}).Where("id = ?", log.Id).Updates(log).Error
})
}
func (m *customUserModel) FindResetSubscribeLog(ctx context.Context, id int64) (*ResetSubscribeLog, error) {
var data ResetSubscribeLog
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&ResetSubscribeLog{}).Where("id = ?", id).First(&data).Error
})
return &data, err
}
func (m *customUserModel) DeleteResetSubscribeLog(ctx context.Context, id int64, tx ...*gorm.DB) error {
return m.ExecNoCacheCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&ResetSubscribeLog{}).Where("id = ?", id).Delete(&ResetSubscribeLog{}).Error
})
}
func (m *customUserModel) FilterResetSubscribeLogList(ctx context.Context, filter *FilterResetSubscribeLogParams) ([]*ResetSubscribeLog, int64, error) {
if filter == nil {
return nil, 0, errors.New("filter params is nil")
}
var list []*ResetSubscribeLog
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
query := conn.Model(&ResetSubscribeLog{})
// 应用筛选条件
if filter.UserId != 0 {
query = query.Where("user_id = ?", filter.UserId)
}
if filter.UserSubscribeId != 0 {
query = query.Where("user_subscribe_id = ?", filter.UserSubscribeId)
}
if filter.Type != 0 {
query = query.Where("type = ?", filter.Type)
}
if filter.OrderNo != "" {
query = query.Where("order_no = ?", filter.OrderNo)
}
// 计算总数
if err := query.Count(&total).Error; err != nil {
return err
}
// 应用分页
if filter.Page > 0 && filter.Size > 0 {
query = query.Offset((filter.Page - 1) * filter.Size)
}
if filter.Size > 0 {
query = query.Limit(filter.Size)
}
return query.Find(&list).Error
})
return list, total, err
}
+160
View File
@@ -0,0 +1,160 @@
package user
import (
"context"
"fmt"
"time"
"gorm.io/gorm"
)
func (m *defaultUserModel) UpdateUserSubscribeCache(ctx context.Context, data *Subscribe) error {
return m.CachedConn.DelCacheCtx(ctx, m.getSubscribeCacheKey(data)...)
}
// QueryActiveSubscriptions returns the number of active subscriptions.
func (m *defaultUserModel) QueryActiveSubscriptions(ctx context.Context, subscribeId ...int64) (map[int64]int64, error) {
type SubscriptionCount struct {
SubscribeId int64
Total int64
}
var result []SubscriptionCount
err := m.QueryNoCacheCtx(ctx, &result, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Subscribe{}).
Where("subscribe_id IN ? AND `status` IN ?", subscribeId, []int64{1, 0, 3}).
Select("subscribe_id, COUNT(id) as total").
Group("subscribe_id").
Scan(&result).
Error
})
if err != nil {
return nil, err
}
resultMap := make(map[int64]int64)
for _, item := range result {
resultMap[item.SubscribeId] = item.Total
}
return resultMap, nil
}
func (m *defaultUserModel) FindOneSubscribeByOrderId(ctx context.Context, orderId int64) (*Subscribe, error) {
var data Subscribe
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Subscribe{}).Where("order_id = ?", orderId).First(&data).Error
})
return &data, err
}
func (m *defaultUserModel) FindOneSubscribe(ctx context.Context, id int64) (*Subscribe, error) {
var data Subscribe
key := fmt.Sprintf("%s%d", cacheUserSubscribeIdPrefix, id)
err := m.QueryCtx(ctx, &data, key, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Subscribe{}).Where("id = ?", id).First(&data).Error
})
return &data, err
}
func (m *defaultUserModel) FindUsersSubscribeBySubscribeId(ctx context.Context, subscribeId int64) ([]*Subscribe, error) {
var data []*Subscribe
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Subscribe{}).Where("subscribe_id = ? AND `status` IN ?", subscribeId, []int64{1, 0}).Find(&data).Error
})
return data, err
}
// QueryUserSubscribe returns a list of records that meet the conditions.
func (m *defaultUserModel) QueryUserSubscribe(ctx context.Context, userId int64, status ...int64) ([]*SubscribeDetails, error) {
var list []*SubscribeDetails
key := fmt.Sprintf("%s%d", cacheUserSubscribeUserPrefix, userId)
err := m.QueryCtx(ctx, &list, key, func(conn *gorm.DB, v interface{}) error {
// 获取当前时间
now := time.Now()
// 获取当前时间向前推 7 天
sevenDaysAgo := time.Now().Add(-7 * 24 * time.Hour)
// 基础条件查询
conn = conn.Model(&Subscribe{}).Where("`user_id` = ? and `status` IN ?", userId, status)
return conn.Where("`expire_time` > ? OR `finished_at` >= ?", now, sevenDaysAgo).
Preload("Subscribe").
Find(&list).Error
})
return list, err
}
// FindOneUserSubscribe finds a subscribeDetails by id.
func (m *defaultUserModel) FindOneUserSubscribe(ctx context.Context, id int64) (subscribeDetails *SubscribeDetails, err error) {
//TODO cache
//key := fmt.Sprintf("%s%d", cacheUserSubscribeUserPrefix, userId)
err = m.QueryNoCacheCtx(ctx, subscribeDetails, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Subscribe{}).Preload("Subscribe").Where("id = ?", id).First(&subscribeDetails).Error
})
return
}
// FindOneSubscribeByToken finds a record by token.
func (m *defaultUserModel) FindOneSubscribeByToken(ctx context.Context, token string) (*Subscribe, error) {
var data Subscribe
key := fmt.Sprintf("%s%s", cacheUserSubscribeTokenPrefix, token)
err := m.QueryCtx(ctx, &data, key, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Subscribe{}).Where("token = ?", token).First(&data).Error
})
return &data, err
}
// UpdateSubscribe updates a record.
func (m *defaultUserModel) UpdateSubscribe(ctx context.Context, data *Subscribe, tx ...*gorm.DB) error {
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&Subscribe{}).Where("token = ?", data.Token).Save(data).Error
}, m.getSubscribeCacheKey(data)...)
}
// DeleteSubscribe deletes a record.
func (m *defaultUserModel) DeleteSubscribe(ctx context.Context, token string, tx ...*gorm.DB) error {
data, err := m.FindOneSubscribeByToken(ctx, token)
if err != nil {
return err
}
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Where("token = ?", token).Delete(&Subscribe{}).Error
}, m.getSubscribeCacheKey(data)...)
}
// InsertSubscribe insert Subscribe into the database.
func (m *defaultUserModel) InsertSubscribe(ctx context.Context, data *Subscribe, tx ...*gorm.DB) error {
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Create(data).Error
}, m.getSubscribeCacheKey(data)...)
}
func (m *defaultUserModel) DeleteSubscribeById(ctx context.Context, id int64, tx ...*gorm.DB) error {
data, err := m.FindOneSubscribe(ctx, id)
if err != nil {
return err
}
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Where("id = ?", id).Delete(&Subscribe{}).Error
}, m.getSubscribeCacheKey(data)...)
}
func (m *defaultUserModel) ClearSubscribeCache(ctx context.Context, data ...*Subscribe) error {
var keys []string
for _, item := range data {
keys = append(keys, m.getSubscribeCacheKey(item)...)
}
return m.CachedConn.DelCacheCtx(ctx, keys...)
}
+230
View File
@@ -0,0 +1,230 @@
package user
import (
"time"
"gorm.io/gorm"
"gorm.io/plugin/soft_delete"
)
type User struct {
Id int64 `gorm:"primaryKey"`
Password string `gorm:"type:varchar(100);not null;comment:User Password"`
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
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"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (User) TableName() string {
return "user"
}
type OldUser struct {
Id int64 `gorm:"primaryKey"`
Email string `gorm:"index:idx_email;type:varchar(100);comment:Email"`
//Telephone string `gorm:"index:idx_telephone;type:varchar(20);default:'';comment:Telephone"`
//TelephoneAreaCode string `gorm:"index:idx_telephone;type:varchar(20);default:'';comment:TelephoneAreaCode"`
Password string `gorm:"type:varchar(100);not null;comment:User Password"`
Avatar string `gorm:"type:varchar(200);default:'';comment:User Avatar"`
Balance int64 `gorm:"default:0;comment:User Balance"` // User Balance Amount
Telegram int64 `gorm:"default:null;comment:Telegram Account"`
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
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"`
ValidEmail *bool `gorm:"default:false;not null;comment:Is Email Verified"`
EnableEmailNotify *bool `gorm:"default:false;not null;comment:Enable Email Notifications"`
EnableTelegramNotify *bool `gorm:"default:false;not null;comment:Enable Telegram Notifications"`
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"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
DeletedAt gorm.DeletedAt `gorm:"default:null;comment:Deletion Time"`
IsDel soft_delete.DeletedAt `gorm:"softDelete:flag,DeletedAtField:DeletedAt;comment:1: Normal 0: Deleted"` // Using `1` and `0` to indicate
}
func (OldUser) TableName() string {
return "user"
}
type Subscribe struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
User User `gorm:"foreignKey:UserId;references:Id"`
OrderId int64 `gorm:"index:idx_order_id;not null;comment:Order ID"`
SubscribeId int64 `gorm:"index:idx_subscribe_id;not null;comment:Subscription ID"`
StartTime time.Time `gorm:"default:CURRENT_TIMESTAMP(3);not null;comment:Subscription Start Time"`
ExpireTime time.Time `gorm:"default:NULL;comment:Subscription Expire Time"`
FinishedAt *time.Time `gorm:"default:NULL;comment:Finished Time"`
Traffic int64 `gorm:"default:0;comment:Traffic"`
Download int64 `gorm:"default:0;comment:Download Traffic"`
Upload int64 `gorm:"default:0;comment:Upload Traffic"`
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"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Subscribe) TableName() string {
return "user_subscribe"
}
type BalanceLog struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
Amount int64 `gorm:"not null;comment:Amount"`
Type uint8 `gorm:"type:tinyint(1);not null;comment:Type: 1: Recharge 2: Withdraw 3: Payment 4: Refund 5: Reward"`
OrderId int64 `gorm:"default:null;comment:Order ID"`
Balance int64 `gorm:"not null;comment:Balance"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
}
func (BalanceLog) TableName() string {
return "user_balance_log"
}
type GiftAmountLog struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
UserSubscribeId int64 `gorm:"default:null;comment:Deduction User Subscribe ID"`
OrderNo string `gorm:"default:null;comment:Order No."`
Type uint8 `gorm:"type:tinyint(1);not null;comment:Type: 1: Increase 2: Reduce"`
Amount int64 `gorm:"not null;comment:Amount"`
Balance int64 `gorm:"not null;comment:Balance"`
Remark string `gorm:"type:varchar(255);default:'';comment:Remark"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
}
func (GiftAmountLog) TableName() string {
return "user_gift_amount_log"
}
type CommissionLog struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
OrderNo string `gorm:"default:null;comment:Order No."`
Amount int64 `gorm:"not null;comment:Amount"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
}
func (CommissionLog) TableName() string {
return "user_commission_log"
}
type AuthMethods struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
AuthType string `gorm:"type:varchar(255);not null;comment:Auth Type 1: apple 2: google 3: github 4: facebook 5: telegram 6: email 7: mobile 8: device"`
AuthIdentifier string `gorm:"type:varchar(255);unique;index:idx_auth_identifier;not null;comment:Auth Identifier"`
Verified bool `gorm:"default:false;not null;comment:Is Verified"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (AuthMethods) TableName() string {
return "user_auth_methods"
}
type Device struct {
Id int64 `gorm:"primaryKey"`
Ip string `gorm:"type:varchar(255);not null;comment:Device IP"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
UserAgent string `gorm:"default:null;comment:UserAgent."`
Identifier string `gorm:"type:varchar(255);unique;index:idx_identifier;default:'';comment:Device Identifier"`
Online bool `gorm:"default:false;not null;comment:Online"`
Enabled bool `gorm:"default:true;not null;comment:Enabled"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Device) TableName() string {
return "user_device"
}
type DeviceOnlineRecord struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"type:bigint;not null;comment:User ID"`
Identifier string `gorm:"type:varchar(255);not null;comment:Device Identifier"`
OnlineTime time.Time `gorm:"comment:Online Time"` // The time when the device goes online
OfflineTime time.Time `gorm:"comment:Offline Time"`
OnlineSeconds int64 `gorm:"comment:Offline Seconds"`
DurationDays int64 `gorm:"comment:Duration Days"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
}
func (DeviceOnlineRecord) TableName() string {
return "user_device_online_record"
}
type LoginLog struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
LoginIP string `gorm:"type:varchar(255);not null;comment:Login IP"`
UserAgent string `gorm:"type:text;not null;comment:UserAgent"`
Success *bool `gorm:"default:false;not null;comment:Login Success"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
}
func (LoginLog) TableName() string {
return "user_login_log"
}
type SubscribeLog struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
UserSubscribeId int64 `gorm:"index:idx_user_subscribe_id;not null;comment:User Subscribe ID"`
Token string `gorm:"type:varchar(255);not null;comment:Token"`
IP string `gorm:"type:varchar(255);not null;comment:IP"`
UserAgent string `gorm:"type:text;not null;comment:UserAgent"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
}
func (SubscribeLog) TableName() string {
return "user_subscribe_log"
}
const (
ResetSubscribeTypeAuto uint8 = 1
ResetSubscribeTypeAdvance uint8 = 2
ResetSubscribeTypePaid uint8 = 3
)
type FilterResetSubscribeLogParams struct {
Page int
Size int
Type uint8
UserId int64
OrderNo string
UserSubscribeId int64
}
type ResetSubscribeLog struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"type:bigint;index:idx_user_id;not null;comment:User ID"`
Type uint8 `gorm:"type:tinyint(1);not null;comment:Type: 1: Auto 2: Advance 3: Paid"`
OrderNo string `gorm:"type:varchar(255);default:null;comment:Order No."`
UserSubscribeId int64 `gorm:"type:bigint;index:idx_user_subscribe_id;not null;comment:User Subscribe ID"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
}
func (ResetSubscribeLog) TableName() string {
return "user_reset_subscribe_log"
}