feat(subscribe): add traffic limit rules and user traffic stats
- Add subscribe traffic_limit schema and migration\n- Support traffic_limit in admin create/update and list/details\n- Apply traffic_limit when building server user list speed limits\n- Add public user traffic stats API
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/group"
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
@@ -88,7 +89,7 @@ func (l *QueryUserSubscribeNodeListLogic) QueryUserSubscribeNodeList() (resp *ty
|
||||
func (l *QueryUserSubscribeNodeListLogic) getServers(userSub *user.Subscribe) (userSubscribeNodes []*types.UserSubscribeNodeInfo, err error) {
|
||||
userSubscribeNodes = make([]*types.UserSubscribeNodeInfo, 0)
|
||||
if l.isSubscriptionExpired(userSub) {
|
||||
return l.createExpiredServers(), nil
|
||||
return l.createExpiredServers(userSub), nil
|
||||
}
|
||||
|
||||
// Check if group management is enabled
|
||||
@@ -312,8 +313,98 @@ func (l *QueryUserSubscribeNodeListLogic) isSubscriptionExpired(userSub *user.Su
|
||||
return userSub.ExpireTime.Unix() < time.Now().Unix() && userSub.ExpireTime.Unix() != 0
|
||||
}
|
||||
|
||||
func (l *QueryUserSubscribeNodeListLogic) createExpiredServers() []*types.UserSubscribeNodeInfo {
|
||||
return nil
|
||||
func (l *QueryUserSubscribeNodeListLogic) createExpiredServers(userSub *user.Subscribe) []*types.UserSubscribeNodeInfo {
|
||||
// 1. 查询过期节点组
|
||||
var expiredGroup group.NodeGroup
|
||||
err := l.svcCtx.DB.Where("is_expired_group = ?", true).First(&expiredGroup).Error
|
||||
if err != nil {
|
||||
l.Debugw("no expired node group configured", logger.Field("error", err))
|
||||
return nil
|
||||
}
|
||||
|
||||
// 2. 检查用户是否在过期天数限制内
|
||||
expiredDays := int(time.Since(userSub.ExpireTime).Hours() / 24)
|
||||
if expiredDays > expiredGroup.ExpiredDaysLimit {
|
||||
l.Debugf("user subscription expired %d days, exceeds limit %d days", expiredDays, expiredGroup.ExpiredDaysLimit)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 3. 检查用户已使用流量是否超过限制(仅使用过期期间的流量)
|
||||
if expiredGroup.MaxTrafficGBExpired != nil && *expiredGroup.MaxTrafficGBExpired > 0 {
|
||||
usedTrafficGB := (userSub.ExpiredDownload + userSub.ExpiredUpload) / (1024 * 1024 * 1024)
|
||||
if usedTrafficGB >= *expiredGroup.MaxTrafficGBExpired {
|
||||
l.Debugf("user expired traffic %d GB, exceeds expired group limit %d GB", usedTrafficGB, *expiredGroup.MaxTrafficGBExpired)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 查询过期节点组的节点
|
||||
enable := true
|
||||
_, nodes, err := l.svcCtx.NodeModel.FilterNodeList(l.ctx, &node.FilterNodeParams{
|
||||
Page: 0,
|
||||
Size: 1000,
|
||||
NodeGroupIds: []int64{expiredGroup.Id},
|
||||
Enabled: &enable,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("failed to query expired group nodes", logger.Field("error", err))
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(nodes) == 0 {
|
||||
l.Debug("no nodes found in expired group")
|
||||
return nil
|
||||
}
|
||||
|
||||
// 5. 查询服务器信息
|
||||
var serverMapIds = make(map[int64]*node.Server)
|
||||
for _, n := range nodes {
|
||||
serverMapIds[n.ServerId] = nil
|
||||
}
|
||||
var serverIds []int64
|
||||
for k := range serverMapIds {
|
||||
serverIds = append(serverIds, k)
|
||||
}
|
||||
|
||||
servers, err := l.svcCtx.NodeModel.QueryServerList(l.ctx, serverIds)
|
||||
if err != nil {
|
||||
l.Errorw("failed to query servers", logger.Field("error", err))
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, s := range servers {
|
||||
serverMapIds[s.Id] = s
|
||||
}
|
||||
|
||||
// 6. 构建节点列表
|
||||
userSubscribeNodes := make([]*types.UserSubscribeNodeInfo, 0, len(nodes))
|
||||
for _, n := range nodes {
|
||||
server := serverMapIds[n.ServerId]
|
||||
if server == nil {
|
||||
continue
|
||||
}
|
||||
userSubscribeNode := &types.UserSubscribeNodeInfo{
|
||||
Id: n.Id,
|
||||
Name: n.Name,
|
||||
Uuid: userSub.UUID,
|
||||
Protocol: n.Protocol,
|
||||
Protocols: server.Protocols,
|
||||
Port: n.Port,
|
||||
Address: n.Address,
|
||||
Tags: strings.Split(n.Tags, ","),
|
||||
Country: server.Country,
|
||||
City: server.City,
|
||||
Latitude: server.Latitude,
|
||||
Longitude: server.Longitude,
|
||||
LongitudeCenter: server.LongitudeCenter,
|
||||
LatitudeCenter: server.LatitudeCenter,
|
||||
CreatedAt: n.CreatedAt.Unix(),
|
||||
}
|
||||
userSubscribeNodes = append(userSubscribeNodes, userSubscribeNode)
|
||||
}
|
||||
|
||||
l.Infof("returned %d nodes from expired group for user %d (expired %d days)", len(userSubscribeNodes), userSub.UserId, expiredDays)
|
||||
return userSubscribeNodes
|
||||
}
|
||||
|
||||
func (l *QueryUserSubscribeNodeListLogic) getFirstHostLine() string {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetUserTrafficStatsLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get User Traffic Statistics
|
||||
func NewGetUserTrafficStatsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserTrafficStatsLogic {
|
||||
return &GetUserTrafficStatsLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetUserTrafficStatsLogic) GetUserTrafficStats(req *types.GetUserTrafficStatsRequest) (resp *types.GetUserTrafficStatsResponse, err error) {
|
||||
// 获取当前用户
|
||||
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||
if !ok {
|
||||
logger.Error("current user is not found in context")
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
||||
}
|
||||
|
||||
// 将字符串 ID 转换为 int64
|
||||
userSubscribeId, err := strconv.ParseInt(req.UserSubscribeId, 10, 64)
|
||||
if err != nil {
|
||||
l.Errorw("[GetUserTrafficStats] Invalid User Subscribe ID:",
|
||||
logger.Field("user_subscribe_id", req.UserSubscribeId),
|
||||
logger.Field("err", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid subscription ID")
|
||||
}
|
||||
|
||||
// 验证订阅归属权 - 直接查询 user_subscribe 表
|
||||
var userSubscribe struct {
|
||||
Id int64
|
||||
UserId int64
|
||||
}
|
||||
err = l.svcCtx.DB.WithContext(l.ctx).
|
||||
Table("user_subscribe").
|
||||
Select("id, user_id").
|
||||
Where("id = ?", userSubscribeId).
|
||||
First(&userSubscribe).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[GetUserTrafficStats] User Subscribe Not Found:",
|
||||
logger.Field("user_subscribe_id", userSubscribeId),
|
||||
logger.Field("user_id", u.Id))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Subscription not found")
|
||||
}
|
||||
l.Errorw("[GetUserTrafficStats] Query User Subscribe Error:", logger.Field("err", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query User Subscribe Error")
|
||||
}
|
||||
|
||||
if userSubscribe.UserId != u.Id {
|
||||
l.Errorw("[GetUserTrafficStats] User Subscribe Access Denied:",
|
||||
logger.Field("user_subscribe_id", userSubscribeId),
|
||||
logger.Field("subscribe_user_id", userSubscribe.UserId),
|
||||
logger.Field("current_user_id", u.Id))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
||||
}
|
||||
|
||||
// 计算时间范围
|
||||
now := time.Now()
|
||||
startDate := now.AddDate(0, 0, -req.Days+1)
|
||||
startDate = time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 0, 0, 0, 0, time.Local)
|
||||
|
||||
// 初始化响应
|
||||
resp = &types.GetUserTrafficStatsResponse{
|
||||
List: make([]types.DailyTrafficStats, 0, req.Days),
|
||||
TotalUpload: 0,
|
||||
TotalDownload: 0,
|
||||
TotalTraffic: 0,
|
||||
}
|
||||
|
||||
// 按天查询流量数据
|
||||
for i := 0; i < req.Days; i++ {
|
||||
currentDate := startDate.AddDate(0, 0, i)
|
||||
dayStart := time.Date(currentDate.Year(), currentDate.Month(), currentDate.Day(), 0, 0, 0, 0, time.Local)
|
||||
dayEnd := dayStart.Add(24 * time.Hour).Add(-time.Nanosecond)
|
||||
|
||||
// 查询当天流量
|
||||
var dailyTraffic struct {
|
||||
Upload int64
|
||||
Download int64
|
||||
}
|
||||
|
||||
// 直接使用 model 的查询方法
|
||||
err := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Table("traffic_log").
|
||||
Select("COALESCE(SUM(upload), 0) as upload, COALESCE(SUM(download), 0) as download").
|
||||
Where("user_id = ? AND subscribe_id = ? AND timestamp BETWEEN ? AND ?",
|
||||
u.Id, userSubscribeId, dayStart, dayEnd).
|
||||
Scan(&dailyTraffic).Error
|
||||
|
||||
if err != nil {
|
||||
l.Errorw("[GetUserTrafficStats] Query Daily Traffic Error:",
|
||||
logger.Field("date", currentDate.Format("2006-01-02")),
|
||||
logger.Field("err", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query Traffic Error")
|
||||
}
|
||||
|
||||
// 添加到结果列表
|
||||
total := dailyTraffic.Upload + dailyTraffic.Download
|
||||
resp.List = append(resp.List, types.DailyTrafficStats{
|
||||
Date: currentDate.Format("2006-01-02"),
|
||||
Upload: dailyTraffic.Upload,
|
||||
Download: dailyTraffic.Download,
|
||||
Total: total,
|
||||
})
|
||||
|
||||
// 累加总计
|
||||
resp.TotalUpload += dailyTraffic.Upload
|
||||
resp.TotalDownload += dailyTraffic.Download
|
||||
}
|
||||
|
||||
resp.TotalTraffic = resp.TotalUpload + resp.TotalDownload
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package user
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
@@ -52,6 +53,9 @@ func (l *QueryUserSubscribeLogic) QueryUserSubscribe() (resp *types.QueryUserSub
|
||||
var sub types.UserSubscribe
|
||||
tool.DeepCopy(&sub, item)
|
||||
|
||||
// 填充 IdStr 字段,避免前端精度丢失
|
||||
sub.IdStr = strconv.FormatInt(item.Id, 10)
|
||||
|
||||
// 解析Discount字段 避免在续订时只能续订一个月
|
||||
if item.Subscribe != nil && item.Subscribe.Discount != "" {
|
||||
var discounts []types.SubscribeDiscount
|
||||
|
||||
Reference in New Issue
Block a user