Develop (#76)
* refactor: rename queryannouncementhandler.go to queryAnnouncementLogic.go for clarity
* feat(panDomain): update subscription logic to use V2 handler for improved functionality
* refactor(subscribe): replace V2 handler with a unified Handler method for subscription logic
* feat(subscribe): implement user agent limit feature with configurable list
* fix(subscribe): improve error handling and logging for subscription requests
* feat(subscribe): add user agent limit configuration to system settings
* refactor(api): remove deprecated application-related endpoints and types
* refactor(swagger): remove deprecated app.json generation from swagger configuration
* refactor(swagger): remove deprecated app.json check from swagger configuration
* fix(subscribe): update delete method to use Where clause for improved query accuracy
* fix(subscribe): update Id field tag to use primaryKey and improve save method query
* fix(subscribe): update Id field tag to use primaryKey and improve model queries
* fix(subscribe): rename variable for clarity and add special handling for Stash user agent
* fix(email): convert RegisterStartTime and RegisterEndTime to time.Time for accurate query filtering
* refactor(log): consolidate logging models and update related logic for improved clarity and functionality
* fix(types): change Content field type in MessageLog to interface{} for improved flexibility
* fix(log): change MessageLog list to use value type for improved performance and memory efficiency
* fix(email): set EmailTypeVerify in task payload and update content type conversion for verification email
* fix(log): remove unused Id field from SystemLog during login log insertion
* fix(login): remove debug logs and error logging during user login process
* fix(log): add traffic reset logging for subscription resets
* fix(log): insert reset traffic log during subscription activation
* feat(log): add endpoints for retrieving and resetting subscribe traffic logs
* refactor(log): remove Reset Subscribe Traffic Log endpoint and related types
* feat(traffic): add traffic statistics logging and scheduling
* fix(subscribe): ensure active status and reset timestamps during traffic resets
* feat(api): enhance server and node management with new request/response structures
* refactor(api): rename OnlineUser to ServerOnlineUser for clarity
* feat(api): define OnlineUser type with SID and IP fields
* feat(server): implement server management handlers and database schema
* feat(api): add traffic log details filtering and enhance traffic log structures
* feat(api): migrate server and node data handling, update related structures and logic
* feat(server): implement server deletion logic with error handling
* feat(api): update log filtering to use ResetSubscribe type for subscription logs
* feat(api): standardize timestamp field across log structures
* feat(api): refactor cache key handling for server and user lists
* feat(api): enhance server status handling with protocol support and refactor related logic
* fix(traffic): adjust start date for traffic statistics and improve log deletion comment
* feat(api): implement daily traffic ranking for users and servers with error handling
* feat(api): update server total data response to use 'OnlineUsers' and implement daily traffic statistics logging
* feat(api): add log settings management with auto-clear and clear days configuration
* fix(log): correct category in log settings update query
* feat(routes): add handler for scheduled traffic statistics
* feat(model): add user counts struct and update queries for new and renewal users
* feat(api): add referral percentage and only first purchase fields to user model and requests
* feat(database): update user table to add referral percentage and only first purchase fields
* feat(api): add reset sort endpoints for server and node
* feat(api): add sort field to server model
* feat(api): implement sorting functionality for nodes and servers
* fix(database): add sort column to nodes table
* fix(model): enhance user statistics queries with new order and renewal order counts
* fix(log): update timestamp handling in login and registration logs
* fix(log): update sorting logic for server and user subscribe traffic logs
* fix(server): add server status handling based on last reported time
* fix(model): correct filter condition to use 'date' instead of 'data'
* fix(migration): add index for traffic log on timestamp, user_id, and subscribe_id
* fix(log): optimize user traffic rank data handling by using append instead of index assignment
* fix(filter): refactor node list creation to use append and remove duplicates from tags
* fix(node): add ServerId and Enabled fields to node update logic
* feat(tags): add endpoint to query all node tags
* fix(preview): add Preload parameter to FilterNodeList for improved data retrieval
* fix(log): date is empty
* feat(subscribe): add Language field to subscription models and update query logic
* feat(subscription): add Language parameter to GetSubscription request and update query logic
* fix(server): encode ServerKey in base64 and update last reported time for nodes
* feat: delete common GetSubscription
* feat(subscription): implement FilterList method for subscription queries and update related logic
* fix(subscribe): remove duplicate user agents in SubscribeHandler
* fix(push): initialize onlineUsers as a map in pushOnlineUsersLogic
* fix(reset): initialize subs as a map in clearCache method
* refactor(query): simplify node and tag filtering using InSet function
* feat(userlist): enhance GetServerUserListLogic with improved node and tag handling
* fix(userlist): correct node ID assignment and update query logic for tag filtering
* fix(userlist): correct node ID assignment in getServerUserListLogic
* refactor(query): streamline query construction for tag filtering
* fix(statistics): optimize server ranking data handling in QueryServerTotalDataLogic
* refactor(statistics): simplify server ranking data construction in QueryServerTotalDataLogic
* fix(statistics): correct server traffic data assignment in QueryServerTotalDataLogic
* fix(statistics): optimize yesterday's top 10 server traffic data assignment in QueryServerTotalDataLogic
* fix(middleware): remove duplicate elements from user agent list in PanDomainMiddleware
* feat(middleware): enhance user agent handling by querying client list in PanDomainMiddleware
* feat(client): subscribe_template
* feat(oauth): add user agent and IP logging to registration and login processes
* fix(balance): add timestamp to balance logs for payment, refund, and recharge transactions
* fix(log): correct comment for CommissionTypeRefund to improve clarity
* fix(log): replace magic number with constant for gift type in purchase checkout logic
* fix(log): rename OrderId to OrderNo for consistency in balance logging
* feat(log): add logging for balance, gift amount, and commission adjustments
* fix(user): correct placement of DeepCopy for user info update logic
* feat(log): add UserSubscribeId to FilterSubscribeLogRequest for enhanced filtering
* fix(purchase): streamline error handling and improve JSON marshaling for temporary orders
* fix(order): simplify commission handling and improve payload parsing logic
* fix(order): update commission calculation to actual payment amount minus gateway handling fee
* feat(payment): add support for CryptoSaaS payment platform and enhance configuration handling
* fix(balance): update QueryUserBalanceLog response structure to include balance log list
* fix(email): update task progress handling to use specific task ID for updates
* feat(quota): add quota task creation and querying endpoints with updated data structures
* fix(email): update task handling to use generic task model and improve error logging
* fix(order): improve error logging for database transaction and user cache updates
* feat(quota): enhance quota task management with new request structures and processing logic
* fix(quota): remove redundant quota task status endpoint from admin marketing routes
* fix(worker): update task completion status handling in worker logic
* fix(quota): update taskInfo to include current subscription count in quota logic
* doc(log): rename function for clarity and add cache cleanup comment
* fix(quota): update time handling in quota logic and correct subscriber ID query
* fix(quota): update time handling to use UnixMilli for start time in quota logic
* feat(protocol): add server protocol configuration query and enhance protocol options
* fix(quota): correct time range queries for start and expire times in quota logic
* fix(types): update plugin options to include 'none' in the plugin field
---------
Co-authored-by: Chang lue Tsen <tension@ppanel.dev>
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/adapter"
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -28,7 +29,11 @@ func NewPreviewSubscribeTemplateLogic(ctx context.Context, svcCtx *svc.ServiceCo
|
||||
}
|
||||
|
||||
func (l *PreviewSubscribeTemplateLogic) PreviewSubscribeTemplate(req *types.PreviewSubscribeTemplateRequest) (resp *types.PreviewSubscribeTemplateResponse, err error) {
|
||||
servers, err := l.svcCtx.ServerModel.FindAllServer(l.ctx)
|
||||
_, servers, err := l.svcCtx.NodeModel.FilterNodeList(l.ctx, &node.FilterNodeParams{
|
||||
Page: 1,
|
||||
Size: 1000,
|
||||
Preload: true,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorf("[PreviewSubscribeTemplateLogic] FindAllServer error: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindAllServer error: %v", err.Error())
|
||||
|
||||
@@ -6,12 +6,15 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/model/traffic"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type QueryServerTotalDataLogic struct {
|
||||
@@ -35,127 +38,194 @@ func (l *QueryServerTotalDataLogic) QueryServerTotalData() (resp *types.ServerTo
|
||||
return l.mockRevenueStatistics(), nil
|
||||
}
|
||||
|
||||
resp = &types.ServerTotalDataResponse{
|
||||
ServerTrafficRankingToday: make([]types.ServerTrafficData, 0),
|
||||
ServerTrafficRankingYesterday: make([]types.ServerTrafficData, 0),
|
||||
UserTrafficRankingToday: make([]types.UserTrafficData, 0),
|
||||
UserTrafficRankingYesterday: make([]types.UserTrafficData, 0),
|
||||
now := time.Now()
|
||||
|
||||
todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
todayEnd := todayStart.Add(24 * time.Hour).Add(-time.Second)
|
||||
query := l.svcCtx.DB.WithContext(l.ctx)
|
||||
var todayTop10User []log.UserTraffic
|
||||
|
||||
err = query.Model(&traffic.TrafficLog{}).
|
||||
Select("user_id, subscribe_id, SUM(download + upload) AS total, SUM(download) AS download, SUM(upload) AS upload").
|
||||
Where("timestamp BETWEEN ? AND ?", todayStart, todayEnd).
|
||||
Group("user_id, subscribe_id").
|
||||
Order("total DESC").
|
||||
Limit(10).
|
||||
Scan(&todayTop10User).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
logger.Errorf("[Traffic Stat Queue] Query user traffic failed: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), " Query user traffic failed: %v", err.Error())
|
||||
}
|
||||
var userTodayTrafficRanking []types.UserTrafficData
|
||||
for _, item := range todayTop10User {
|
||||
userTodayTrafficRanking = append(userTodayTrafficRanking, types.UserTrafficData{
|
||||
SID: item.SubscribeId,
|
||||
Upload: item.Upload,
|
||||
Download: item.Download,
|
||||
})
|
||||
}
|
||||
|
||||
// Query node server status
|
||||
servers, err := l.svcCtx.ServerModel.FindAllServer(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] FindAllServer error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(err, "FindAllServer error: %v", err)
|
||||
}
|
||||
onlineServers, err := l.svcCtx.NodeCache.GetOnlineNodeStatusCount(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] GetOnlineNodeStatusCount error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(err, "GetOnlineNodeStatusCount error: %v", err)
|
||||
}
|
||||
resp.OnlineServers = onlineServers
|
||||
resp.OfflineServers = int64(len(servers) - int(onlineServers))
|
||||
// query yesterday user traffic rank log
|
||||
yesterday := todayStart.Add(-24 * time.Hour).Format(time.DateOnly)
|
||||
|
||||
// 获取所有节点在线用户
|
||||
allNodeOnlineUser, err := l.svcCtx.NodeCache.GetAllNodeOnlineUser(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Get all node online user failed", logger.Field("error", err.Error()))
|
||||
var yesterdayLog log.SystemLog
|
||||
err = query.Model(&log.SystemLog{}).Where("`date` = ? AND `type` = ?", yesterday, log.TypeUserTrafficRank).First(&yesterdayLog).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Query yesterday user traffic rank log error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query yesterday user traffic rank log error: %v", err)
|
||||
}
|
||||
resp.OnlineUserIPs = int64(len(allNodeOnlineUser))
|
||||
|
||||
// 获取所有节点今日上传下载流量
|
||||
allNodeUploadTraffic, err := l.svcCtx.NodeCache.GetAllNodeUploadTraffic(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Get all node upload traffic failed", logger.Field("error", err.Error()))
|
||||
var yesterdayUserRankData []types.UserTrafficData
|
||||
if yesterdayLog.Id > 0 {
|
||||
var rank log.UserTrafficRank
|
||||
err = rank.Unmarshal([]byte(yesterdayLog.Content))
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Unmarshal yesterday user traffic rank log error", logger.Field("error", err.Error()))
|
||||
}
|
||||
for _, v := range rank.Rank {
|
||||
yesterdayUserRankData = append(yesterdayUserRankData, types.UserTrafficData{
|
||||
SID: v.SubscribeId,
|
||||
Upload: v.Upload,
|
||||
Download: v.Download,
|
||||
})
|
||||
}
|
||||
}
|
||||
resp.TodayUpload = allNodeUploadTraffic
|
||||
allNodeDownloadTraffic, err := l.svcCtx.NodeCache.GetAllNodeDownloadTraffic(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Get all node download traffic failed", logger.Field("error", err.Error()))
|
||||
|
||||
// query server traffic rank today
|
||||
var todayTop10Server []log.ServerTraffic
|
||||
err = query.Model(&traffic.TrafficLog{}).Select("server_id, SUM(download + upload) AS total, SUM(download) AS download, SUM(upload) AS upload").
|
||||
Where("timestamp BETWEEN ? AND ?", todayStart, todayEnd).
|
||||
Group("server_id").
|
||||
Order("total DESC").
|
||||
Limit(10).
|
||||
Scan(&todayTop10Server).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
logger.Errorf("[Traffic Stat Queue] Query server traffic failed: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), " Query server traffic failed: %v", err.Error())
|
||||
}
|
||||
resp.TodayDownload = allNodeDownloadTraffic
|
||||
// 获取节点流量排行榜 前10
|
||||
nodeTrafficRankingToday, err := l.svcCtx.NodeCache.GetNodeTodayTotalTrafficRank(l.ctx, 10)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Get node today total traffic rank failed", logger.Field("error", err.Error()))
|
||||
|
||||
var todayServerRanking []types.ServerTrafficData
|
||||
for _, item := range todayTop10Server {
|
||||
info, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, item.ServerId)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] FindOneServer error", logger.Field("error", err.Error()), logger.Field("server_id", item.ServerId))
|
||||
continue
|
||||
}
|
||||
todayServerRanking = append(todayServerRanking, types.ServerTrafficData{
|
||||
ServerId: item.ServerId,
|
||||
Name: info.Name,
|
||||
Upload: item.Upload,
|
||||
Download: item.Download,
|
||||
})
|
||||
}
|
||||
if len(nodeTrafficRankingToday) > 0 {
|
||||
var serverTrafficData []types.ServerTrafficData
|
||||
for _, rank := range nodeTrafficRankingToday {
|
||||
serverInfo, err := l.svcCtx.ServerModel.FindOne(l.ctx, rank.ID)
|
||||
|
||||
// query server traffic rank yesterday
|
||||
var yesterdayTop10Server []types.ServerTrafficData
|
||||
var yesterdayServerTrafficLog log.SystemLog
|
||||
err = query.Model(&log.SystemLog{}).Where("`date` = ? AND `type` = ?", yesterday, log.TypeServerTrafficRank).First(&yesterdayServerTrafficLog).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Query yesterday server traffic rank log error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query yesterday server traffic rank log error: %v", err)
|
||||
}
|
||||
if yesterdayServerTrafficLog.Id > 0 {
|
||||
var rank log.ServerTrafficRank
|
||||
err = rank.Unmarshal([]byte(yesterdayServerTrafficLog.Content))
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Unmarshal yesterday server traffic rank log error", logger.Field("error", err.Error()))
|
||||
}
|
||||
|
||||
for _, v := range rank.Rank {
|
||||
info, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, v.ServerId)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] FindOne error", logger.Field("error", err))
|
||||
l.Errorw("[QueryServerTotalDataLogic] FindOneServer error", logger.Field("error", err.Error()), logger.Field("server_id", v.ServerId))
|
||||
continue
|
||||
}
|
||||
serverTrafficData = append(serverTrafficData, types.ServerTrafficData{
|
||||
ServerId: rank.ID,
|
||||
Name: serverInfo.Name,
|
||||
Upload: rank.Upload,
|
||||
Download: rank.Download,
|
||||
yesterdayTop10Server = append(yesterdayTop10Server, types.ServerTrafficData{
|
||||
ServerId: v.ServerId,
|
||||
Name: info.Name,
|
||||
Upload: v.Upload,
|
||||
Download: v.Download,
|
||||
})
|
||||
}
|
||||
resp.ServerTrafficRankingToday = serverTrafficData
|
||||
}
|
||||
// 获取用户流量排行榜 前10
|
||||
userTrafficRankingToday, err := l.svcCtx.NodeCache.GetUserTodayTotalTrafficRank(l.ctx, 10)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Get user today total traffic rank failed", logger.Field("error", err.Error()))
|
||||
}
|
||||
|
||||
if len(userTrafficRankingToday) > 0 {
|
||||
var userTrafficData []types.UserTrafficData
|
||||
for _, rank := range userTrafficRankingToday {
|
||||
userTrafficData = append(userTrafficData, types.UserTrafficData{
|
||||
SID: rank.SID,
|
||||
Upload: rank.Upload,
|
||||
Download: rank.Download,
|
||||
})
|
||||
}
|
||||
resp.UserTrafficRankingToday = userTrafficData
|
||||
}
|
||||
// 获取昨日节点流量排行榜 前10
|
||||
nodeTrafficRankingYesterday, err := l.svcCtx.NodeCache.GetYesterdayNodeTotalTrafficRank(l.ctx)
|
||||
// query online user count
|
||||
onlineUsers, err := l.svcCtx.NodeModel.OnlineUserSubscribeGlobal(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Get yesterday node total traffic rank failed", logger.Field("error", err.Error()))
|
||||
}
|
||||
if len(nodeTrafficRankingYesterday) > 0 {
|
||||
var serverTrafficData []types.ServerTrafficData
|
||||
for _, rank := range nodeTrafficRankingYesterday {
|
||||
serverTrafficData = append(serverTrafficData, types.ServerTrafficData{
|
||||
ServerId: rank.ID,
|
||||
Name: rank.Name,
|
||||
Upload: rank.Upload,
|
||||
Download: rank.Download,
|
||||
})
|
||||
}
|
||||
resp.ServerTrafficRankingYesterday = serverTrafficData
|
||||
}
|
||||
// 获取昨日用户流量排行榜 前10
|
||||
userTrafficRankingYesterday, err := l.svcCtx.NodeCache.GetYesterdayUserTotalTrafficRank(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Get yesterday user total traffic rank failed", logger.Field("error", err.Error()))
|
||||
}
|
||||
if len(userTrafficRankingYesterday) > 0 {
|
||||
var userTrafficData []types.UserTrafficData
|
||||
for _, rank := range userTrafficRankingYesterday {
|
||||
userTrafficData = append(userTrafficData, types.UserTrafficData{
|
||||
SID: rank.SID,
|
||||
Upload: rank.Upload,
|
||||
Download: rank.Download,
|
||||
})
|
||||
}
|
||||
resp.UserTrafficRankingYesterday = userTrafficData
|
||||
l.Errorw("[QueryServerTotalDataLogic] OnlineUserSubscribeGlobal error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "OnlineUserSubscribeGlobal error: %v", err)
|
||||
}
|
||||
|
||||
// Query node traffic by monthly
|
||||
nodeTraffic, err := l.svcCtx.TrafficLogModel.QueryTrafficByMonthly(l.ctx, time.Now())
|
||||
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] QueryTrafficByMonthly error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "QueryTrafficByMonthly error: %v", err.Error())
|
||||
// query online/offline server count
|
||||
var onlineServers, offlineServers int64
|
||||
err = query.Model(&node.Server{}).Where("`last_reported_at` > ?", now.Add(-5*time.Minute)).Count(&onlineServers).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Count online servers error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Count online servers error: %v", err)
|
||||
}
|
||||
|
||||
err = query.Model(&node.Server{}).Where("`last_reported_at` <= ? OR `last_reported_at` IS NULL", now.Add(-5*time.Minute)).Count(&offlineServers).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Count offline servers error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Count offline servers error: %v", err)
|
||||
}
|
||||
// TodayUpload, TodayDownload, MonthlyUpload, MonthlyDownload
|
||||
var todayUpload, todayDownload, monthlyUpload, monthlyDownload int64
|
||||
|
||||
type trafficSum struct {
|
||||
Upload int64
|
||||
Download int64
|
||||
}
|
||||
var todayTraffic trafficSum
|
||||
// Today
|
||||
err = query.Model(&traffic.TrafficLog{}).Select("SUM(upload) AS upload, SUM(download) AS download").
|
||||
Where("timestamp BETWEEN ? AND ?", todayStart, todayEnd).
|
||||
Scan(&todayTraffic).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Sum today traffic error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Sum today traffic error: %v", err)
|
||||
}
|
||||
todayUpload = todayTraffic.Upload
|
||||
todayDownload = todayTraffic.Download
|
||||
|
||||
// Monthly
|
||||
monthlyUpload += todayUpload
|
||||
monthlyDownload += todayDownload
|
||||
|
||||
for i := now.Day() - 1; i >= 1; i-- {
|
||||
var logInfo log.SystemLog
|
||||
date := time.Date(now.Year(), now.Month(), i, 0, 0, 0, 0, now.Location()).Format(time.DateOnly)
|
||||
err = query.Model(&log.SystemLog{}).Where("`date` = ? AND `type` = ?", date, log.TypeTrafficStat).First(&logInfo).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Query daily traffic stat log error", logger.Field("error", err.Error()), logger.Field("date", date))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query daily traffic stat log error: %v", err)
|
||||
}
|
||||
if logInfo.Id > 0 {
|
||||
var stat log.TrafficStat
|
||||
err = stat.Unmarshal([]byte(logInfo.Content))
|
||||
if err != nil {
|
||||
l.Errorw("[QueryServerTotalDataLogic] Unmarshal daily traffic stat log error", logger.Field("error", err.Error()), logger.Field("date", date))
|
||||
continue
|
||||
}
|
||||
monthlyUpload += stat.Upload
|
||||
monthlyDownload += stat.Download
|
||||
}
|
||||
}
|
||||
|
||||
resp = &types.ServerTotalDataResponse{
|
||||
OnlineUsers: onlineUsers,
|
||||
OnlineServers: onlineServers,
|
||||
OfflineServers: offlineServers,
|
||||
TodayUpload: todayUpload,
|
||||
TodayDownload: todayDownload,
|
||||
MonthlyUpload: monthlyUpload,
|
||||
MonthlyDownload: monthlyDownload,
|
||||
UpdatedAt: now.Unix(),
|
||||
ServerTrafficRankingToday: todayServerRanking,
|
||||
ServerTrafficRankingYesterday: yesterdayTop10Server,
|
||||
UserTrafficRankingToday: userTodayTrafficRanking,
|
||||
UserTrafficRankingYesterday: yesterdayUserRankData,
|
||||
}
|
||||
resp.MonthlyUpload = nodeTraffic.Upload
|
||||
resp.MonthlyDownload = nodeTraffic.Download
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
@@ -215,7 +285,7 @@ func (l *QueryServerTotalDataLogic) mockRevenueStatistics() *types.ServerTotalDa
|
||||
//}
|
||||
//
|
||||
return &types.ServerTotalDataResponse{
|
||||
OnlineUserIPs: 1688,
|
||||
OnlineUsers: 1688,
|
||||
OnlineServers: 8,
|
||||
OfflineServers: 2,
|
||||
TodayUpload: 8888888888, // ~8.3GB
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterBalanceLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterBalanceLogLogic Filter balance log
|
||||
func NewFilterBalanceLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterBalanceLogLogic {
|
||||
return &FilterBalanceLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterBalanceLogLogic) FilterBalanceLog(req *types.FilterBalanceLogRequest) (resp *types.FilterBalanceLogResponse, err error) {
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeBalance.Uint8(),
|
||||
Data: req.Date,
|
||||
ObjectID: req.UserId,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorw("[FilterBalanceLog] Query User Balance Log Error:", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query User Balance Log Error")
|
||||
}
|
||||
|
||||
list := make([]types.BalanceLog, 0)
|
||||
for _, datum := range data {
|
||||
var content log.Balance
|
||||
if err = content.Unmarshal([]byte(datum.Content)); err != nil {
|
||||
l.Errorf("[QueryUserBalanceLog] unmarshal balance log content failed: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.BalanceLog{
|
||||
UserId: datum.ObjectID,
|
||||
Amount: content.Amount,
|
||||
Type: content.Type,
|
||||
OrderNo: content.OrderNo,
|
||||
Balance: content.Balance,
|
||||
Timestamp: content.Timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterBalanceLogResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterCommissionLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterCommissionLogLogic Filter commission log
|
||||
func NewFilterCommissionLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterCommissionLogLogic {
|
||||
return &FilterCommissionLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterCommissionLogLogic) FilterCommissionLog(req *types.FilterCommissionLogRequest) (resp *types.FilterCommissionLogResponse, err error) {
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Data: req.Date,
|
||||
Type: log.TypeCommission.Uint8(),
|
||||
ObjectID: req.UserId,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("Query User Commission Log failed", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query User Commission Log failed")
|
||||
}
|
||||
var list []types.CommissionLog
|
||||
|
||||
for _, datum := range data {
|
||||
var content log.Commission
|
||||
if err = content.Unmarshal([]byte(datum.Content)); err != nil {
|
||||
l.Errorf("unmarshal commission log content failed: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.CommissionLog{
|
||||
UserId: datum.ObjectID,
|
||||
Type: content.Type,
|
||||
Amount: content.Amount,
|
||||
OrderNo: content.OrderNo,
|
||||
Timestamp: content.Timestamp,
|
||||
})
|
||||
}
|
||||
return &types.FilterCommissionLogResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterEmailLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterEmailLogLogic Filter email log
|
||||
func NewFilterEmailLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterEmailLogLogic {
|
||||
return &FilterEmailLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterEmailLogLogic) FilterEmailLog(req *types.FilterLogParams) (resp *types.FilterEmailLogResponse, err error) {
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeEmailMessage.Uint8(),
|
||||
Data: req.Date,
|
||||
Search: req.Search,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorf("[FilterEmailLog] failed to filter system log: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "failed to filter system log: %v", err.Error())
|
||||
}
|
||||
|
||||
var list []types.MessageLog
|
||||
|
||||
for _, datum := range data {
|
||||
var content log.Message
|
||||
err = content.Unmarshal([]byte(datum.Content))
|
||||
if err != nil {
|
||||
l.Errorf("[FilterEmailLog] failed to unmarshal content: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.MessageLog{
|
||||
Id: datum.Id,
|
||||
Type: datum.Type,
|
||||
Platform: content.Platform,
|
||||
To: content.To,
|
||||
Subject: content.Subject,
|
||||
Content: content.Content,
|
||||
Status: content.Status,
|
||||
CreatedAt: datum.CreatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterEmailLogResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterGiftLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Filter gift log
|
||||
func NewFilterGiftLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterGiftLogLogic {
|
||||
return &FilterGiftLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterGiftLogLogic) FilterGiftLog(req *types.FilterGiftLogRequest) (resp *types.FilterGiftLogResponse, err error) {
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeGift.Uint8(),
|
||||
ObjectID: req.UserId,
|
||||
Data: req.Date,
|
||||
Search: req.Search,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorf("[FilterGiftLog] failed to filter system log: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "failed to filter system log: %v", err.Error())
|
||||
}
|
||||
|
||||
var list []types.GiftLog
|
||||
for _, datum := range data {
|
||||
var content log.Gift
|
||||
err = content.Unmarshal([]byte(datum.Content))
|
||||
if err != nil {
|
||||
l.Errorf("[FilterGiftLog] failed to unmarshal content: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.GiftLog{
|
||||
Type: content.Type,
|
||||
UserId: datum.ObjectID,
|
||||
OrderNo: content.OrderNo,
|
||||
SubscribeId: content.SubscribeId,
|
||||
Amount: content.Amount,
|
||||
Balance: content.Balance,
|
||||
Remark: content.Remark,
|
||||
Timestamp: content.Timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterGiftLogResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterLoginLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterLoginLogLogic Filter login log
|
||||
func NewFilterLoginLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterLoginLogLogic {
|
||||
return &FilterLoginLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterLoginLogLogic) FilterLoginLog(req *types.FilterLoginLogRequest) (resp *types.FilterLoginLogResponse, err error) {
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeLogin.Uint8(),
|
||||
ObjectID: req.UserId,
|
||||
Data: req.Date,
|
||||
Search: req.Search,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorf("[FilterLoginLog] failed to filter system log: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "failed to filter system log: %v", err.Error())
|
||||
}
|
||||
var list []types.LoginLog
|
||||
for _, datum := range data {
|
||||
var item log.Login
|
||||
err = item.Unmarshal([]byte(datum.Content))
|
||||
if err != nil {
|
||||
l.Errorf("[FilterLoginLog] failed to unmarshal content: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.LoginLog{
|
||||
UserId: datum.ObjectID,
|
||||
Method: item.Method,
|
||||
LoginIP: item.LoginIP,
|
||||
UserAgent: item.UserAgent,
|
||||
Success: item.Success,
|
||||
Timestamp: datum.CreatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterLoginLogResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterMobileLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Filter mobile log
|
||||
func NewFilterMobileLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterMobileLogLogic {
|
||||
return &FilterMobileLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterMobileLogLogic) FilterMobileLog(req *types.FilterLogParams) (resp *types.FilterMobileLogResponse, err error) {
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeMobileMessage.Uint8(),
|
||||
Data: req.Date,
|
||||
Search: req.Search,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorf("[FilterMobileLog] failed to filter system log: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "failed to filter system log: %v", err.Error())
|
||||
}
|
||||
|
||||
var list []types.MessageLog
|
||||
|
||||
for _, datum := range data {
|
||||
var content log.Message
|
||||
err = content.Unmarshal([]byte(datum.Content))
|
||||
if err != nil {
|
||||
l.Errorf("[FilterMobileLog] failed to unmarshal content: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.MessageLog{
|
||||
Id: datum.Id,
|
||||
Type: datum.Type,
|
||||
Platform: content.Platform,
|
||||
To: content.To,
|
||||
Subject: content.Subject,
|
||||
Content: content.Content,
|
||||
Status: content.Status,
|
||||
CreatedAt: datum.CreatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterMobileLogResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterRegisterLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Filter register log
|
||||
func NewFilterRegisterLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterRegisterLogLogic {
|
||||
return &FilterRegisterLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterRegisterLogLogic) FilterRegisterLog(req *types.FilterRegisterLogRequest) (resp *types.FilterRegisterLogResponse, err error) {
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeRegister.Uint8(),
|
||||
ObjectID: req.UserId,
|
||||
Data: req.Date,
|
||||
Search: req.Search,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorf("[FilterRegisterLog] failed to filter system log: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "failed to filter system log: %v", err.Error())
|
||||
}
|
||||
|
||||
var list []types.RegisterLog
|
||||
for _, datum := range data {
|
||||
var item log.Register
|
||||
err = item.Unmarshal([]byte(datum.Content))
|
||||
if err != nil {
|
||||
l.Errorf("[FilterLoginLog] failed to unmarshal content: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.RegisterLog{
|
||||
UserId: datum.ObjectID,
|
||||
AuthMethod: item.AuthMethod,
|
||||
Identifier: item.Identifier,
|
||||
RegisterIP: item.RegisterIP,
|
||||
UserAgent: item.UserAgent,
|
||||
Timestamp: item.Timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterRegisterLogResponse{
|
||||
List: list,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterResetSubscribeLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterResetSubscribeLogLogic Filter reset subscribe log
|
||||
func NewFilterResetSubscribeLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterResetSubscribeLogLogic {
|
||||
return &FilterResetSubscribeLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterResetSubscribeLogLogic) FilterResetSubscribeLog(req *types.FilterResetSubscribeLogRequest) (resp *types.FilterResetSubscribeLogResponse, err error) {
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeResetSubscribe.Uint8(),
|
||||
ObjectID: req.UserSubscribeId,
|
||||
Data: req.Date,
|
||||
Search: req.Search,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorf("[FilterResetSubscribeLog] failed to filter system log: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "failed to filter system log: %v", err.Error())
|
||||
}
|
||||
|
||||
var list []types.ResetSubscribeLog
|
||||
|
||||
for _, item := range data {
|
||||
var content log.ResetSubscribe
|
||||
err = content.Unmarshal([]byte(item.Content))
|
||||
if err != nil {
|
||||
l.Errorf("[FilterResetSubscribeLog] failed to unmarshal content: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.ResetSubscribeLog{
|
||||
Type: content.Type,
|
||||
UserId: content.UserId,
|
||||
UserSubscribeId: item.ObjectID,
|
||||
OrderNo: content.OrderNo,
|
||||
Timestamp: content.Timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterResetSubscribeLogResponse{
|
||||
List: list,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/model/traffic"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterServerTrafficLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterServerTrafficLogLogic Filter server traffic log
|
||||
func NewFilterServerTrafficLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterServerTrafficLogLogic {
|
||||
return &FilterServerTrafficLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
func (l *FilterServerTrafficLogLogic) FilterServerTrafficLog(req *types.FilterServerTrafficLogRequest) (resp *types.FilterServerTrafficLogResponse, err error) {
|
||||
today := time.Now().Format("2006-01-02")
|
||||
var list []types.ServerTrafficLog
|
||||
var total int64
|
||||
|
||||
if req.Date == today || req.Date == "" {
|
||||
now := time.Now()
|
||||
start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
|
||||
end := start.Add(24 * time.Hour).Add(-time.Nanosecond)
|
||||
|
||||
var serverTraffic []log.ServerTraffic
|
||||
err = l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&traffic.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("SUM(download + upload) DESC").
|
||||
Scan(&serverTraffic).Error
|
||||
if err != nil {
|
||||
l.Errorw("[FilterServerTrafficLog] Query Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "today traffic query error: %s", err.Error())
|
||||
}
|
||||
|
||||
for _, v := range serverTraffic {
|
||||
list = append(list, types.ServerTrafficLog{
|
||||
ServerId: v.ServerId,
|
||||
Upload: v.Upload,
|
||||
Download: v.Download,
|
||||
Total: v.Total,
|
||||
Date: today,
|
||||
Details: true,
|
||||
})
|
||||
}
|
||||
|
||||
todayTotal := len(list)
|
||||
|
||||
startIdx := (req.Page - 1) * req.Size
|
||||
endIdx := startIdx + req.Size
|
||||
|
||||
if startIdx < todayTotal {
|
||||
if endIdx > todayTotal {
|
||||
endIdx = todayTotal
|
||||
}
|
||||
pageData := list[startIdx:endIdx]
|
||||
return &types.FilterServerTrafficLogResponse{
|
||||
List: pageData,
|
||||
Total: int64(todayTotal),
|
||||
}, nil
|
||||
}
|
||||
|
||||
need := endIdx - todayTotal
|
||||
historyPage := (need + req.Size - 1) / req.Size // 算出需要的历史页数
|
||||
historyData, historyTotal, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: historyPage,
|
||||
Size: need,
|
||||
Type: log.TypeServerTraffic.Uint8(),
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[FilterServerTrafficLog] Query History Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "history query error: %s", err.Error())
|
||||
}
|
||||
|
||||
for _, item := range historyData {
|
||||
var content log.ServerTraffic
|
||||
if err = content.Unmarshal([]byte(item.Content)); err != nil {
|
||||
l.Errorw("[FilterServerTrafficLog] Unmarshal Error", logger.Field("error", err.Error()), logger.Field("content", item.Content))
|
||||
continue
|
||||
}
|
||||
|
||||
hasDetails := true
|
||||
if l.svcCtx.Config.Log.AutoClear {
|
||||
last := now.AddDate(0, 0, int(-l.svcCtx.Config.Log.ClearDays))
|
||||
dataTime, err := time.Parse(time.DateOnly, item.Date)
|
||||
if err != nil {
|
||||
l.Errorw("[FilterServerTrafficLog] Parse Date Error", logger.Field("error", err.Error()), logger.Field("date", item.Date))
|
||||
} else {
|
||||
if dataTime.Before(last) {
|
||||
hasDetails = false
|
||||
} else {
|
||||
hasDetails = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
list = append(list, types.ServerTrafficLog{
|
||||
ServerId: item.ObjectID,
|
||||
Upload: content.Upload,
|
||||
Download: content.Download,
|
||||
Total: content.Total,
|
||||
Date: item.Date,
|
||||
Details: hasDetails,
|
||||
})
|
||||
}
|
||||
|
||||
// 返回最终分页数据
|
||||
if endIdx > len(list) {
|
||||
endIdx = len(list)
|
||||
}
|
||||
pageData := list[startIdx:endIdx]
|
||||
|
||||
return &types.FilterServerTrafficLogResponse{
|
||||
List: pageData,
|
||||
Total: int64(todayTotal) + historyTotal,
|
||||
}, nil
|
||||
}
|
||||
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeServerTraffic.Uint8(),
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[FilterServerTrafficLog] Query Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "history query error: %s", err.Error())
|
||||
}
|
||||
|
||||
for _, item := range data {
|
||||
var content log.ServerTraffic
|
||||
if err = content.Unmarshal([]byte(item.Content)); err != nil {
|
||||
l.Errorw("[FilterServerTrafficLog] Unmarshal Error", logger.Field("error", err.Error()), logger.Field("content", item.Content))
|
||||
continue
|
||||
}
|
||||
list = append(list, types.ServerTrafficLog{
|
||||
ServerId: item.ObjectID,
|
||||
Upload: content.Upload,
|
||||
Download: content.Download,
|
||||
Total: content.Total,
|
||||
Date: item.Date,
|
||||
Details: false,
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterServerTrafficLogResponse{
|
||||
List: list,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterSubscribeLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterSubscribeLogLogic Filter subscribe log
|
||||
func NewFilterSubscribeLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterSubscribeLogLogic {
|
||||
return &FilterSubscribeLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterSubscribeLogLogic) FilterSubscribeLog(req *types.FilterSubscribeLogRequest) (resp *types.FilterSubscribeLogResponse, err error) {
|
||||
params := &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeSubscribe.Uint8(),
|
||||
Data: req.Date,
|
||||
ObjectID: req.UserId,
|
||||
}
|
||||
|
||||
if req.UserSubscribeId != 0 {
|
||||
params.Search = `"user_subscribe_id":` + strconv.FormatInt(req.UserSubscribeId, 10)
|
||||
}
|
||||
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, params)
|
||||
if err != nil {
|
||||
l.Errorf("[FilterSubscribeLog] failed to filter system log: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "failed to filter system log")
|
||||
}
|
||||
|
||||
var list []types.SubscribeLog
|
||||
for _, datum := range data {
|
||||
var content log.Subscribe
|
||||
err = content.Unmarshal([]byte(datum.Content))
|
||||
if err != nil {
|
||||
l.Errorf("[FilterSubscribeLog] failed to unmarshal content: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.SubscribeLog{
|
||||
UserId: datum.ObjectID,
|
||||
Token: content.Token,
|
||||
UserAgent: content.UserAgent,
|
||||
ClientIP: content.ClientIP,
|
||||
UserSubscribeId: content.UserSubscribeId,
|
||||
Timestamp: datum.CreatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterSubscribeLogResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/traffic"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterTrafficLogDetailsLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterTrafficLogDetailsLogic Filter traffic log details
|
||||
func NewFilterTrafficLogDetailsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterTrafficLogDetailsLogic {
|
||||
return &FilterTrafficLogDetailsLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterTrafficLogDetailsLogic) FilterTrafficLogDetails(req *types.FilterTrafficLogDetailsRequest) (resp *types.FilterTrafficLogDetailsResponse, err error) {
|
||||
var start, end time.Time
|
||||
if req.Date != "" {
|
||||
day, err := time.ParseInLocation("2006-01-02", req.Date, time.Local)
|
||||
if err != nil {
|
||||
l.Errorw("[FilterTrafficLogDetails] Date Parse Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), " date parse error: %s", err.Error())
|
||||
}
|
||||
start = day
|
||||
end = day.Add(24*time.Hour - time.Nanosecond)
|
||||
} else {
|
||||
// query today
|
||||
now := time.Now()
|
||||
start = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
end = start.Add(24*time.Hour - time.Nanosecond)
|
||||
}
|
||||
var data []*traffic.TrafficLog
|
||||
tx := l.svcCtx.DB.WithContext(l.ctx).Model(&traffic.TrafficLog{})
|
||||
if req.ServerId != 0 {
|
||||
tx = tx.Where("server_id = ?", req.ServerId)
|
||||
}
|
||||
if !start.IsZero() && !end.IsZero() {
|
||||
tx = tx.Where("timestamp BETWEEN ? AND ?", start, end)
|
||||
}
|
||||
if req.UserId != 0 {
|
||||
tx = tx.Where("user_id = ?", req.UserId)
|
||||
}
|
||||
if req.SubscribeId != 0 {
|
||||
tx = tx.Where("subscribe_id = ?", req.SubscribeId)
|
||||
}
|
||||
var total int64
|
||||
err = tx.Count(&total).Limit(req.Size).Offset((req.Page - 1) * req.Size).Find(&data).Error
|
||||
if err != nil {
|
||||
l.Errorw("[FilterTrafficLogDetails] Query Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), " database query error: %s", err.Error())
|
||||
}
|
||||
|
||||
var logs []types.TrafficLogDetails
|
||||
for _, v := range data {
|
||||
logs = append(logs, types.TrafficLogDetails{
|
||||
Id: v.Id,
|
||||
UserId: v.UserId,
|
||||
ServerId: v.ServerId,
|
||||
SubscribeId: v.SubscribeId,
|
||||
Download: v.Download,
|
||||
Upload: v.Upload,
|
||||
Timestamp: v.Timestamp.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterTrafficLogDetailsResponse{
|
||||
List: logs,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/model/traffic"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterUserSubscribeTrafficLogLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterUserSubscribeTrafficLogLogic Filter user subscribe traffic log
|
||||
func NewFilterUserSubscribeTrafficLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterUserSubscribeTrafficLogLogic {
|
||||
return &FilterUserSubscribeTrafficLogLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterUserSubscribeTrafficLogLogic) FilterUserSubscribeTrafficLog(req *types.FilterSubscribeTrafficRequest) (resp *types.FilterSubscribeTrafficResponse, err error) {
|
||||
if req.Size <= 0 {
|
||||
req.Size = 10
|
||||
}
|
||||
if req.Page <= 0 {
|
||||
req.Page = 1
|
||||
}
|
||||
|
||||
today := time.Now().Format("2006-01-02")
|
||||
var list []types.UserSubscribeTrafficLog
|
||||
var total int64
|
||||
|
||||
if req.Date == today || req.Date == "" {
|
||||
now := time.Now()
|
||||
start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
|
||||
end := start.Add(24 * time.Hour).Add(-time.Nanosecond)
|
||||
|
||||
var userTraffic []types.UserSubscribeTrafficLog
|
||||
err = l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&traffic.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").
|
||||
Order("SUM(download + upload) DESC").
|
||||
Scan(&userTraffic).Error
|
||||
if err != nil {
|
||||
l.Errorw("[FilterUserSubscribeTrafficLog] Query Database Error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, v := range userTraffic {
|
||||
list = append(list, types.UserSubscribeTrafficLog{
|
||||
UserId: v.UserId,
|
||||
SubscribeId: v.SubscribeId,
|
||||
Upload: v.Upload,
|
||||
Download: v.Download,
|
||||
Total: v.Total,
|
||||
Date: today,
|
||||
Details: true,
|
||||
})
|
||||
}
|
||||
todayTotal := len(list)
|
||||
|
||||
startIdx := (req.Page - 1) * req.Size
|
||||
endIdx := startIdx + req.Size
|
||||
if startIdx < todayTotal {
|
||||
if endIdx > todayTotal {
|
||||
endIdx = todayTotal
|
||||
}
|
||||
pageData := list[startIdx:endIdx]
|
||||
return &types.FilterSubscribeTrafficResponse{
|
||||
List: pageData,
|
||||
Total: int64(todayTotal),
|
||||
}, nil
|
||||
}
|
||||
|
||||
need := endIdx - todayTotal
|
||||
historyPage := (need + req.Size - 1) / req.Size // 算出需要的历史页数
|
||||
historyData, historyTotal, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: historyPage,
|
||||
Size: need,
|
||||
Type: log.TypeSubscribeTraffic.Uint8(),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorw("[FilterUserSubscribeTrafficLog] Query Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[FilterUserSubscribeTrafficLog] Query Database Error")
|
||||
}
|
||||
|
||||
for _, datum := range historyData {
|
||||
var item log.UserTraffic
|
||||
err = item.Unmarshal([]byte(datum.Content))
|
||||
if err != nil {
|
||||
l.Errorw("[FilterUserSubscribeTrafficLog] Unmarshal Content Error", logger.Field("error", err.Error()))
|
||||
continue
|
||||
}
|
||||
list = append(list, types.UserSubscribeTrafficLog{
|
||||
UserId: item.UserId,
|
||||
SubscribeId: item.SubscribeId,
|
||||
Upload: item.Upload,
|
||||
Download: item.Download,
|
||||
Total: item.Total,
|
||||
Date: datum.Date,
|
||||
Details: false,
|
||||
})
|
||||
}
|
||||
// 返回最终分页数据
|
||||
if endIdx > len(list) {
|
||||
endIdx = len(list)
|
||||
}
|
||||
pageData := list[startIdx:endIdx]
|
||||
|
||||
return &types.FilterSubscribeTrafficResponse{
|
||||
List: pageData,
|
||||
Total: int64(todayTotal) + historyTotal,
|
||||
}, nil
|
||||
}
|
||||
var data []*log.SystemLog
|
||||
data, total, err = l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeSubscribeTraffic.Uint8(),
|
||||
Data: req.Date,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[FilterUserSubscribeTrafficLog] Query Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[FilterUserSubscribeTrafficLog] Query Database Error")
|
||||
}
|
||||
for _, datum := range data {
|
||||
var item log.UserTraffic
|
||||
err = item.Unmarshal([]byte(datum.Content))
|
||||
if err != nil {
|
||||
l.Errorw("[FilterUserSubscribeTrafficLog] Unmarshal Content Error", logger.Field("error", err.Error()))
|
||||
continue
|
||||
}
|
||||
list = append(list, types.UserSubscribeTrafficLog{
|
||||
UserId: item.UserId,
|
||||
SubscribeId: item.SubscribeId,
|
||||
Upload: item.Upload,
|
||||
Download: item.Download,
|
||||
Total: item.Total,
|
||||
Date: datum.Date,
|
||||
Details: false,
|
||||
})
|
||||
}
|
||||
return &types.FilterSubscribeTrafficResponse{
|
||||
List: list,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
)
|
||||
|
||||
type GetLogSettingLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get log setting
|
||||
func NewGetLogSettingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLogSettingLogic {
|
||||
return &GetLogSettingLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetLogSettingLogic) GetLogSetting() (resp *types.LogSetting, err error) {
|
||||
configs, err := l.svcCtx.SystemModel.GetLogConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[GetLogSetting] Database query error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
resp = &types.LogSetting{}
|
||||
// reflect to response
|
||||
tool.SystemConfigSliceReflectToStruct(configs, resp)
|
||||
return
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
@@ -28,20 +27,39 @@ func NewGetMessageLogListLogic(ctx context.Context, svcCtx *svc.ServiceContext)
|
||||
}
|
||||
|
||||
func (l *GetMessageLogListLogic) GetMessageLogList(req *types.GetMessageLogListRequest) (resp *types.GetMessageLogListResponse, err error) {
|
||||
total, data, err := l.svcCtx.LogModel.FindMessageLogList(l.ctx, req.Page, req.Size, log.MessageLogFilterParams{
|
||||
Type: req.Type,
|
||||
Platform: req.Platform,
|
||||
To: req.To,
|
||||
Subject: req.Subject,
|
||||
Content: req.Content,
|
||||
Status: req.Status,
|
||||
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: req.Type,
|
||||
Search: req.Search,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorw("[GetMessageLogList] Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[GetMessageLogList] Database Error: %s", err.Error())
|
||||
l.Errorf("[GetMessageLogList] failed to filter system log: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "failed to filter system log: %v", err.Error())
|
||||
}
|
||||
|
||||
var list []types.MessageLog
|
||||
tool.DeepCopy(&list, data)
|
||||
|
||||
for _, datum := range data {
|
||||
var content log.Message
|
||||
err = content.Unmarshal([]byte(datum.Content))
|
||||
if err != nil {
|
||||
l.Errorf("[GetMessageLogList] failed to unmarshal content: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.MessageLog{
|
||||
Id: datum.Id,
|
||||
Type: datum.Type,
|
||||
Platform: content.Platform,
|
||||
To: content.To,
|
||||
Subject: content.Subject,
|
||||
Content: content.Content,
|
||||
Status: content.Status,
|
||||
CreatedAt: datum.CreatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.GetMessageLogListResponse{
|
||||
Total: total,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/model/system"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UpdateLogSettingLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewUpdateLogSettingLogic Update log setting
|
||||
func NewUpdateLogSettingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogSettingLogic {
|
||||
return &UpdateLogSettingLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UpdateLogSettingLogic) UpdateLogSetting(req *types.LogSetting) error {
|
||||
v := reflect.ValueOf(*req)
|
||||
// Get the reflection type of the structure
|
||||
t := v.Type()
|
||||
err := l.svcCtx.SystemModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||
var err error
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
// Get the field name
|
||||
fieldName := t.Field(i).Name
|
||||
// Get the field value to string
|
||||
fieldValue := tool.ConvertValueToString(v.Field(i))
|
||||
// Update the server config
|
||||
err = db.Model(&system.System{}).Where("`category` = 'log' and `key` = ?", fieldName).Update("value", fieldValue).Error
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateLogSetting] update log setting error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), " update log setting error: %v", err)
|
||||
}
|
||||
|
||||
l.svcCtx.Config.Log = config.Log{
|
||||
AutoClear: *req.AutoClear,
|
||||
ClearDays: req.ClearDays,
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -24,7 +24,7 @@ type CreateBatchSendEmailTaskLogic struct {
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Create a batch send email task
|
||||
// NewCreateBatchSendEmailTaskLogic Create a batch send email task
|
||||
func NewCreateBatchSendEmailTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateBatchSendEmailTaskLogic {
|
||||
return &CreateBatchSendEmailTaskLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
@@ -45,34 +45,37 @@ func (l *CreateBatchSendEmailTaskLogic) CreateBatchSendEmailTask(req *types.Crea
|
||||
Where("auth_type = ?", "email")
|
||||
|
||||
if req.RegisterStartTime != 0 {
|
||||
query = query.Where("user.created_at >= ?", req.RegisterStartTime)
|
||||
query = query.Where("user.created_at >= ?", time.UnixMilli(req.RegisterStartTime))
|
||||
}
|
||||
if req.RegisterEndTime != 0 {
|
||||
query = query.Where("user.created_at <= ?", req.RegisterEndTime)
|
||||
query = query.Where("user.created_at <= ?", time.UnixMilli(req.RegisterEndTime))
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
var query *gorm.DB
|
||||
|
||||
switch req.Scope {
|
||||
case "all":
|
||||
scope := task.ParseScopeType(req.Scope)
|
||||
|
||||
switch scope {
|
||||
case task.ScopeAll:
|
||||
query = baseQuery()
|
||||
|
||||
case "active":
|
||||
case task.ScopeActive:
|
||||
query = baseQuery().
|
||||
Joins("JOIN user_subscribe ON user.id = user_subscribe.user_id").
|
||||
Where("user_subscribe.status IN ?", []int64{1, 2})
|
||||
|
||||
case "expired":
|
||||
case task.ScopeExpired:
|
||||
query = baseQuery().
|
||||
Joins("JOIN user_subscribe ON user.id = user_subscribe.user_id").
|
||||
Where("user_subscribe.status = ?", 3)
|
||||
|
||||
case "none":
|
||||
case task.ScopeNone:
|
||||
query = baseQuery().
|
||||
Joins("LEFT JOIN user_subscribe ON user.id = user_subscribe.user_id").
|
||||
Where("user_subscribe.user_id IS NULL")
|
||||
default:
|
||||
|
||||
}
|
||||
if query != nil {
|
||||
@@ -85,7 +88,7 @@ func (l *CreateBatchSendEmailTaskLogic) CreateBatchSendEmailTask(req *types.Crea
|
||||
}
|
||||
|
||||
// 邮箱列表为空,返回错误
|
||||
if len(emails) == 0 && req.Scope != "skip" {
|
||||
if len(emails) == 0 && scope != task.ScopeSkip {
|
||||
l.Errorf("[CreateBatchSendEmailTask] No email addresses found for the specified scope")
|
||||
return xerr.NewErrMsg("No email addresses found for the specified scope")
|
||||
}
|
||||
@@ -96,41 +99,59 @@ func (l *CreateBatchSendEmailTaskLogic) CreateBatchSendEmailTask(req *types.Crea
|
||||
var additionalEmails []string
|
||||
// 追加额外的邮箱地址(不覆盖)
|
||||
if req.Additional != "" {
|
||||
additionalEmails = strings.Split(req.Additional, "\n")
|
||||
additionalEmails = tool.RemoveDuplicateElements(strings.Split(req.Additional, "\n")...)
|
||||
}
|
||||
if len(additionalEmails) == 0 && req.Scope == "skip" {
|
||||
if len(additionalEmails) == 0 && scope == task.ScopeSkip {
|
||||
l.Errorf("[CreateBatchSendEmailTask] No additional email addresses provided for skip scope")
|
||||
return xerr.NewErrMsg("No additional email addresses provided for skip scope")
|
||||
}
|
||||
|
||||
var scheduledAt time.Time
|
||||
if req.Scheduled == 0 {
|
||||
scheduledAt = time.Now()
|
||||
} else {
|
||||
scheduledAt := time.Now().Add(10 * time.Second) // 默认延迟10秒执行,防止任务创建和执行时间过于接近
|
||||
if req.Scheduled != 0 {
|
||||
scheduledAt = time.Unix(req.Scheduled, 0)
|
||||
if scheduledAt.Before(time.Now()) {
|
||||
scheduledAt = time.Now()
|
||||
}
|
||||
}
|
||||
|
||||
taskInfo := &task.EmailTask{
|
||||
Subject: req.Subject,
|
||||
Content: req.Content,
|
||||
Recipients: strings.Join(emails, "\n"),
|
||||
Scope: req.Scope,
|
||||
RegisterStartTime: time.Unix(req.RegisterStartTime, 0),
|
||||
RegisterEndTime: time.Unix(req.RegisterEndTime, 0),
|
||||
Additional: req.Additional,
|
||||
Scheduled: scheduledAt,
|
||||
scopeInfo := task.EmailScope{
|
||||
Type: scope.Int8(),
|
||||
RegisterStartTime: req.RegisterStartTime,
|
||||
RegisterEndTime: req.RegisterEndTime,
|
||||
Recipients: emails,
|
||||
Additional: additionalEmails,
|
||||
Scheduled: req.Scheduled,
|
||||
Interval: req.Interval,
|
||||
Limit: req.Limit,
|
||||
Status: 0,
|
||||
Errors: "",
|
||||
Total: uint64(len(emails) + len(additionalEmails)),
|
||||
Current: 0,
|
||||
}
|
||||
scopeBytes, _ := scopeInfo.Marshal()
|
||||
|
||||
taskContent := task.EmailContent{
|
||||
Subject: req.Subject,
|
||||
Content: req.Content,
|
||||
}
|
||||
|
||||
if err = l.svcCtx.DB.Model(&task.EmailTask{}).Create(taskInfo).Error; err != nil {
|
||||
contentBytes, _ := taskContent.Marshal()
|
||||
|
||||
var total uint64
|
||||
if additionalEmails != nil {
|
||||
list := append(emails, additionalEmails...)
|
||||
total = uint64(len(tool.RemoveDuplicateElements(list...)))
|
||||
} else {
|
||||
total = uint64(len(emails))
|
||||
}
|
||||
|
||||
taskInfo := &task.Task{
|
||||
Type: task.TypeEmail,
|
||||
Scope: string(scopeBytes),
|
||||
Content: string(contentBytes),
|
||||
Status: 0,
|
||||
Errors: "",
|
||||
Total: total,
|
||||
Current: 0,
|
||||
}
|
||||
|
||||
if err = l.svcCtx.DB.Model(&task.Task{}).Create(taskInfo).Error; err != nil {
|
||||
l.Errorf("[CreateBatchSendEmailTask] Failed to create email task: %v", err.Error())
|
||||
return xerr.NewErrCode(xerr.DatabaseInsertError)
|
||||
}
|
||||
@@ -138,12 +159,12 @@ func (l *CreateBatchSendEmailTaskLogic) CreateBatchSendEmailTask(req *types.Crea
|
||||
l.Infof("[CreateBatchSendEmailTask] Successfully created email task with ID: %d", taskInfo.Id)
|
||||
|
||||
t := asynq.NewTask(types2.ScheduledBatchSendEmail, []byte(strconv.FormatInt(taskInfo.Id, 10)))
|
||||
info, err := l.svcCtx.Queue.EnqueueContext(l.ctx, t, asynq.ProcessAt(taskInfo.Scheduled))
|
||||
info, err := l.svcCtx.Queue.EnqueueContext(l.ctx, t, asynq.ProcessAt(scheduledAt))
|
||||
if err != nil {
|
||||
l.Errorf("[CreateBatchSendEmailTask] Failed to enqueue email task: %v", err.Error())
|
||||
return xerr.NewErrCode(xerr.QueueEnqueueError)
|
||||
}
|
||||
l.Infof("[CreateBatchSendEmailTask] Successfully enqueued email task with ID: %s, scheduled at: %s", info.ID, taskInfo.Scheduled)
|
||||
l.Infof("[CreateBatchSendEmailTask] Successfully enqueued email task with ID: %s, scheduled at: %s", info.ID, scheduledAt.Format(time.DateTime))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package marketing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/server/internal/model/task"
|
||||
"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/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
queueType "github.com/perfect-panel/server/queue/types"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type CreateQuotaTaskLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewCreateQuotaTaskLogic Create a quota task
|
||||
func NewCreateQuotaTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateQuotaTaskLogic {
|
||||
return &CreateQuotaTaskLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *CreateQuotaTaskLogic) CreateQuotaTask(req *types.CreateQuotaTaskRequest) error {
|
||||
var subs []*user.Subscribe
|
||||
query := l.svcCtx.DB.WithContext(l.ctx).Model(&user.Subscribe{})
|
||||
if len(req.Subscribers) > 0 {
|
||||
query = query.Where("`subscribe_id` IN ?", req.Subscribers)
|
||||
}
|
||||
|
||||
if req.IsActive != nil && *req.IsActive {
|
||||
query = query.Where("`status` IN ?", []int64{0, 1, 2}) // 0: Pending 1: Active 2: Finished
|
||||
}
|
||||
if req.StartTime != 0 {
|
||||
start := time.UnixMilli(req.StartTime)
|
||||
query = query.Where("`start_time` <= ?", start)
|
||||
}
|
||||
if req.EndTime != 0 {
|
||||
end := time.UnixMilli(req.EndTime)
|
||||
query = query.Where("`expire_time` >= ?", end)
|
||||
}
|
||||
|
||||
if err := query.Find(&subs).Error; err != nil {
|
||||
l.Errorf("[CreateQuotaTask] find subscribers error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribers error")
|
||||
}
|
||||
if len(subs) == 0 {
|
||||
return errors.Wrapf(xerr.NewErrMsg("No subscribers found"), "no subscribers found")
|
||||
}
|
||||
var subIds []int64
|
||||
for _, sub := range subs {
|
||||
subIds = append(subIds, sub.Id)
|
||||
}
|
||||
|
||||
scopeInfo := task.QuotaScope{
|
||||
Subscribers: req.Subscribers,
|
||||
IsActive: req.IsActive,
|
||||
StartTime: req.StartTime,
|
||||
EndTime: req.EndTime,
|
||||
Objects: subIds,
|
||||
}
|
||||
scopeBytes, _ := scopeInfo.Marshal()
|
||||
contentInfo := task.QuotaContent{
|
||||
ResetTraffic: req.ResetTraffic,
|
||||
Days: req.Days,
|
||||
GiftType: req.GiftType,
|
||||
GiftValue: req.GiftValue,
|
||||
}
|
||||
contentBytes, _ := contentInfo.Marshal()
|
||||
// create task
|
||||
newTask := &task.Task{
|
||||
Type: task.TypeQuota,
|
||||
Status: 0,
|
||||
Scope: string(scopeBytes),
|
||||
Content: string(contentBytes),
|
||||
Total: uint64(len(subIds)),
|
||||
Current: 0,
|
||||
Errors: "",
|
||||
}
|
||||
|
||||
if err := l.svcCtx.DB.WithContext(l.ctx).Model(&task.Task{}).Create(newTask).Error; err != nil {
|
||||
l.Errorf("[CreateQuotaTask] create task error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create task error")
|
||||
}
|
||||
|
||||
// enqueue task
|
||||
queueTask := asynq.NewTask(queueType.ForthwithQuotaTask, []byte(strconv.FormatInt(newTask.Id, 10)))
|
||||
if _, err := l.svcCtx.Queue.EnqueueContext(l.ctx, queueTask); err != nil {
|
||||
l.Errorf("[CreateQuotaTask] enqueue task error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.QueueEnqueueError), "enqueue task error")
|
||||
}
|
||||
logger.Infof("[CreateQuotaTask] Successfully created task with ID: %d", newTask.Id)
|
||||
return nil
|
||||
}
|
||||
@@ -2,12 +2,12 @@ package marketing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/task"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
)
|
||||
|
||||
@@ -28,12 +28,12 @@ func NewGetBatchSendEmailTaskListLogic(ctx context.Context, svcCtx *svc.ServiceC
|
||||
|
||||
func (l *GetBatchSendEmailTaskListLogic) GetBatchSendEmailTaskList(req *types.GetBatchSendEmailTaskListRequest) (resp *types.GetBatchSendEmailTaskListResponse, err error) {
|
||||
|
||||
var tasks []*task.EmailTask
|
||||
tx := l.svcCtx.DB.Model(&task.EmailTask{})
|
||||
var tasks []*task.Task
|
||||
tx := l.svcCtx.DB.Model(&task.Task{}).Where("`type` = ?", task.TypeEmail)
|
||||
if req.Status != nil {
|
||||
tx = tx.Where("status = ?", *req.Status)
|
||||
}
|
||||
if req.Scope != "" {
|
||||
if req.Scope != nil {
|
||||
tx = tx.Where("scope = ?", req.Scope)
|
||||
}
|
||||
if req.Page == 0 {
|
||||
@@ -49,7 +49,40 @@ func (l *GetBatchSendEmailTaskListLogic) GetBatchSendEmailTaskList(req *types.Ge
|
||||
}
|
||||
|
||||
list := make([]types.BatchSendEmailTask, 0)
|
||||
tool.DeepCopy(&list, tasks)
|
||||
|
||||
for _, t := range tasks {
|
||||
var scopeInfo task.EmailScope
|
||||
if err = scopeInfo.Unmarshal([]byte(t.Scope)); err != nil {
|
||||
l.Errorf("[GetBatchSendEmailTaskList] failed to unmarshal email task scope: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
var contentInfo task.EmailContent
|
||||
if err = contentInfo.Unmarshal([]byte(t.Content)); err != nil {
|
||||
l.Errorf("[GetBatchSendEmailTaskList] failed to unmarshal email task content: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
list = append(list, types.BatchSendEmailTask{
|
||||
Id: t.Id,
|
||||
Subject: contentInfo.Subject,
|
||||
Content: contentInfo.Content,
|
||||
Recipients: strings.Join(scopeInfo.Recipients, "\n"),
|
||||
Scope: scopeInfo.Type,
|
||||
RegisterStartTime: scopeInfo.RegisterStartTime,
|
||||
RegisterEndTime: scopeInfo.RegisterEndTime,
|
||||
Additional: strings.Join(scopeInfo.Additional, "\n"),
|
||||
Scheduled: scopeInfo.Scheduled,
|
||||
Interval: scopeInfo.Interval,
|
||||
Limit: scopeInfo.Limit,
|
||||
Status: uint8(t.Status),
|
||||
Errors: t.Errors,
|
||||
Total: t.Total,
|
||||
Current: t.Current,
|
||||
CreatedAt: t.CreatedAt.UnixMilli(),
|
||||
UpdatedAt: t.UpdatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.GetBatchSendEmailTaskListResponse{
|
||||
List: list,
|
||||
}, nil
|
||||
|
||||
@@ -28,15 +28,15 @@ func NewGetBatchSendEmailTaskStatusLogic(ctx context.Context, svcCtx *svc.Servic
|
||||
func (l *GetBatchSendEmailTaskStatusLogic) GetBatchSendEmailTaskStatus(req *types.GetBatchSendEmailTaskStatusRequest) (resp *types.GetBatchSendEmailTaskStatusResponse, err error) {
|
||||
tx := l.svcCtx.DB
|
||||
|
||||
var taskInfo *task.EmailTask
|
||||
err = tx.Model(&task.EmailTask{}).Where("id = ?", req.Id).First(&taskInfo).Error
|
||||
var taskInfo *task.Task
|
||||
err = tx.Model(&task.Task{}).Where("id = ?", req.Id).First(&taskInfo).Error
|
||||
if err != nil {
|
||||
l.Errorf("failed to get email task status, error: %v", err)
|
||||
return nil, xerr.NewErrCode(xerr.DatabaseQueryError)
|
||||
}
|
||||
|
||||
return &types.GetBatchSendEmailTaskStatusResponse{
|
||||
Status: taskInfo.Status,
|
||||
Status: uint8(taskInfo.Status),
|
||||
Total: int64(taskInfo.Total),
|
||||
Current: int64(taskInfo.Current),
|
||||
Errors: taskInfo.Errors,
|
||||
|
||||
@@ -2,7 +2,9 @@ package marketing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/task"
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
@@ -37,36 +39,41 @@ func (l *GetPreSendEmailCountLogic) GetPreSendEmailCount(req *types.GetPreSendEm
|
||||
Where("auth_type = ?", "email")
|
||||
|
||||
if req.RegisterStartTime != 0 {
|
||||
query = query.Where("user.created_at >= ?", req.RegisterStartTime)
|
||||
|
||||
registerStartTime := time.UnixMilli(req.RegisterStartTime)
|
||||
|
||||
query = query.Where("user.created_at >= ?", registerStartTime)
|
||||
}
|
||||
if req.RegisterEndTime != 0 {
|
||||
query = query.Where("user.created_at <= ?", req.RegisterEndTime)
|
||||
registerEndTime := time.UnixMilli(req.RegisterEndTime)
|
||||
query = query.Where("user.created_at <= ?", registerEndTime)
|
||||
}
|
||||
return query
|
||||
}
|
||||
var query *gorm.DB
|
||||
switch req.Scope {
|
||||
case "all":
|
||||
scope := task.ParseScopeType(req.Scope)
|
||||
|
||||
switch scope {
|
||||
case task.ScopeAll:
|
||||
query = baseQuery()
|
||||
|
||||
case "active":
|
||||
case task.ScopeActive:
|
||||
query = baseQuery().
|
||||
Joins("JOIN user_subscribe ON user.id = user_subscribe.user_id").
|
||||
Where("user_subscribe.status IN ?", []int64{1, 2})
|
||||
|
||||
case "expired":
|
||||
case task.ScopeExpired:
|
||||
query = baseQuery().
|
||||
Joins("JOIN user_subscribe ON user.id = user_subscribe.user_id").
|
||||
Where("user_subscribe.status = ?", 3)
|
||||
|
||||
case "none":
|
||||
case task.ScopeNone:
|
||||
query = baseQuery().
|
||||
Joins("LEFT JOIN user_subscribe ON user.id = user_subscribe.user_id").
|
||||
Where("user_subscribe.user_id IS NULL")
|
||||
case "skip":
|
||||
case task.ScopeSkip:
|
||||
// Skip scope does not require a count
|
||||
query = nil
|
||||
|
||||
default:
|
||||
l.Errorf("[CreateBatchSendEmailTask] Invalid scope: %v", req.Scope)
|
||||
return nil, xerr.NewErrMsg("Invalid email scope")
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package marketing
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/task"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type QueryQuotaTaskListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewQueryQuotaTaskListLogic Query quota task list
|
||||
func NewQueryQuotaTaskListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryQuotaTaskListLogic {
|
||||
return &QueryQuotaTaskListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryQuotaTaskListLogic) QueryQuotaTaskList(req *types.QueryQuotaTaskListRequest) (resp *types.QueryQuotaTaskListResponse, err error) {
|
||||
var data []*task.Task
|
||||
var count int64
|
||||
query := l.svcCtx.DB.Model(&task.Task{}).Where("`type` = ?", task.TypeQuota)
|
||||
if req.Page == 0 {
|
||||
req.Page = 1
|
||||
}
|
||||
if req.Size == 0 {
|
||||
req.Size = 20
|
||||
}
|
||||
|
||||
if req.Status != nil {
|
||||
query = query.Where("`status` = ?", *req.Status)
|
||||
}
|
||||
err = query.Count(&count).Offset((req.Page - 1) * req.Size).Limit(req.Size).Order("created_at DESC").Find(&data).Error
|
||||
if err != nil {
|
||||
l.Errorf("[QueryQuotaTaskList] failed to get quota tasks: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var list []types.QuotaTask
|
||||
for _, item := range data {
|
||||
var scopeInfo task.QuotaScope
|
||||
if err = scopeInfo.Unmarshal([]byte(item.Scope)); err != nil {
|
||||
l.Errorf("[QueryQuotaTaskList] failed to unmarshal quota task scope: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
var contentInfo task.QuotaContent
|
||||
if err = contentInfo.Unmarshal([]byte(item.Content)); err != nil {
|
||||
l.Errorf("[QueryQuotaTaskList] failed to unmarshal quota task content: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.QuotaTask{
|
||||
Id: item.Id,
|
||||
Subscribers: scopeInfo.Subscribers,
|
||||
IsActive: scopeInfo.IsActive,
|
||||
StartTime: scopeInfo.StartTime,
|
||||
EndTime: scopeInfo.EndTime,
|
||||
ResetTraffic: contentInfo.ResetTraffic,
|
||||
Days: contentInfo.Days,
|
||||
GiftType: contentInfo.GiftType,
|
||||
GiftValue: contentInfo.GiftValue,
|
||||
Objects: scopeInfo.Objects,
|
||||
Status: uint8(item.Status),
|
||||
Total: int64(item.Total),
|
||||
Current: int64(item.Current),
|
||||
Errors: item.Errors,
|
||||
CreatedAt: item.CreatedAt.UnixMilli(),
|
||||
UpdatedAt: item.UpdatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.QueryQuotaTaskListResponse{
|
||||
Total: count,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package marketing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"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/logger"
|
||||
)
|
||||
|
||||
type QueryQuotaTaskPreCountLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewQueryQuotaTaskPreCountLogic Query quota task pre-count
|
||||
func NewQueryQuotaTaskPreCountLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryQuotaTaskPreCountLogic {
|
||||
return &QueryQuotaTaskPreCountLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryQuotaTaskPreCountLogic) QueryQuotaTaskPreCount(req *types.QueryQuotaTaskPreCountRequest) (resp *types.QueryQuotaTaskPreCountResponse, err error) {
|
||||
tx := l.svcCtx.DB.WithContext(l.ctx).Model(&user.Subscribe{})
|
||||
var count int64
|
||||
|
||||
if len(req.Subscribers) > 0 {
|
||||
tx = tx.Where("`subscribe_id` IN ?", req.Subscribers)
|
||||
}
|
||||
|
||||
if req.IsActive != nil && *req.IsActive {
|
||||
tx = tx.Where("`status` IN ?", []int64{0, 1, 2}) // 0: Pending 1: Active 2: Finished
|
||||
}
|
||||
if req.StartTime != 0 {
|
||||
start := time.UnixMilli(req.StartTime)
|
||||
tx = tx.Where("`start_time` <= ?", start)
|
||||
}
|
||||
if req.EndTime != 0 {
|
||||
end := time.UnixMilli(req.EndTime)
|
||||
tx = tx.Where("`expire_time` >= ?", end)
|
||||
}
|
||||
if err = tx.Count(&count).Error; err != nil {
|
||||
l.Errorf("[QueryQuotaTaskPreCount] count error: %v", err.Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &types.QueryQuotaTaskPreCountResponse{
|
||||
Count: count,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package marketing
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/task"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type QueryQuotaTaskStatusLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewQueryQuotaTaskStatusLogic Query quota task status
|
||||
func NewQueryQuotaTaskStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryQuotaTaskStatusLogic {
|
||||
return &QueryQuotaTaskStatusLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryQuotaTaskStatusLogic) QueryQuotaTaskStatus(req *types.QueryQuotaTaskStatusRequest) (resp *types.QueryQuotaTaskStatusResponse, err error) {
|
||||
var data *task.Task
|
||||
err = l.svcCtx.DB.Model(&task.Task{}).Where("id = ? AND `type` = ?", req.Id, task.TypeQuota).First(&data).Error
|
||||
if err != nil {
|
||||
l.Errorf("[QueryQuotaTaskStatus] failed to get quota task: %v", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), " failed to get quota task: %v", err.Error())
|
||||
}
|
||||
return &types.QueryQuotaTaskStatusResponse{
|
||||
Status: uint8(data.Status),
|
||||
Current: int64(data.Current),
|
||||
Total: int64(data.Total),
|
||||
Errors: data.Errors,
|
||||
}, nil
|
||||
}
|
||||
@@ -32,7 +32,7 @@ func (l *StopBatchSendEmailTaskLogic) StopBatchSendEmailTask(req *types.StopBatc
|
||||
} else {
|
||||
logger.Error("[StopBatchSendEmailTaskLogic] email.Manager is nil, cannot stop task")
|
||||
}
|
||||
err = l.svcCtx.DB.Model(&task.EmailTask{}).Where("id = ?", req.Id).Update("status", 2).Error
|
||||
err = l.svcCtx.DB.Model(&task.Task{}).Where("id = ?", req.Id).Update("status", 2).Error
|
||||
|
||||
if err != nil {
|
||||
l.Errorf("failed to stop email task, error: %v", err)
|
||||
|
||||
@@ -55,10 +55,9 @@ func (l *CreatePaymentMethodLogic) CreatePaymentMethod(req *types.CreatePaymentM
|
||||
Token: random.KeyNew(8, 1),
|
||||
}
|
||||
err = l.svcCtx.PaymentModel.Transaction(l.ctx, func(tx *gorm.DB) error {
|
||||
|
||||
if req.Platform == "Stripe" {
|
||||
var cfg paymentModel.StripeConfig
|
||||
if err := cfg.Unmarshal(paymentMethod.Config); err != nil {
|
||||
if err = cfg.Unmarshal([]byte(paymentMethod.Config)); err != nil {
|
||||
l.Errorf("[CreatePaymentMethod] unmarshal stripe config error: %s", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "unmarshal stripe config error: %s", err.Error())
|
||||
}
|
||||
@@ -79,7 +78,8 @@ func (l *CreatePaymentMethodLogic) CreatePaymentMethod(req *types.CreatePaymentM
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "create stripe webhook endpoint error: %s", err.Error())
|
||||
}
|
||||
cfg.WebhookSecret = endpoint.Secret
|
||||
paymentMethod.Config = cfg.Marshal()
|
||||
content, _ := cfg.Marshal()
|
||||
paymentMethod.Config = string(content)
|
||||
}
|
||||
if err = tx.Model(&paymentModel.Payment{}).Create(paymentMethod).Error; err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert payment method error: %s", err.Error())
|
||||
@@ -101,27 +101,36 @@ func (l *CreatePaymentMethodLogic) CreatePaymentMethod(req *types.CreatePaymentM
|
||||
func parsePaymentPlatformConfig(ctx context.Context, platform payment.Platform, config interface{}) string {
|
||||
data, err := json.Marshal(config)
|
||||
if err != nil {
|
||||
logger.WithContext(ctx).Errorw("parse payment platform config error", logger.Field("platform", platform), logger.Field("config", config), logger.Field("error", err.Error()))
|
||||
logger.WithContext(ctx).Errorw("marshal config error", logger.Field("platform", platform), logger.Field("config", config), logger.Field("error", err.Error()))
|
||||
return ""
|
||||
}
|
||||
|
||||
// 通用处理函数
|
||||
handleConfig := func(name string, target interface {
|
||||
Unmarshal([]byte) error
|
||||
Marshal() ([]byte, error)
|
||||
}) string {
|
||||
if err = target.Unmarshal(data); err != nil {
|
||||
logger.WithContext(ctx).Errorw("parse "+name+" config error", logger.Field("config", string(data)), logger.Field("error", err.Error()))
|
||||
return ""
|
||||
}
|
||||
content, err := target.Marshal()
|
||||
if err != nil {
|
||||
logger.WithContext(ctx).Errorw("marshal "+name+" config error", logger.Field("error", err.Error()))
|
||||
return ""
|
||||
}
|
||||
return string(content)
|
||||
}
|
||||
|
||||
switch platform {
|
||||
case payment.Stripe:
|
||||
stripe := &paymentModel.StripeConfig{}
|
||||
if err := stripe.Unmarshal(string(data)); err != nil {
|
||||
logger.WithContext(ctx).Errorw("parse stripe config error", logger.Field("config", string(data)), logger.Field("error", err.Error()))
|
||||
}
|
||||
return stripe.Marshal()
|
||||
return handleConfig("Stripe", &paymentModel.StripeConfig{})
|
||||
case payment.AlipayF2F:
|
||||
alipay := &paymentModel.AlipayF2FConfig{}
|
||||
if err := alipay.Unmarshal(string(data)); err != nil {
|
||||
logger.WithContext(ctx).Errorw("parse alipay config error", logger.Field("config", string(data)), logger.Field("error", err.Error()))
|
||||
}
|
||||
return alipay.Marshal()
|
||||
return handleConfig("Alipay", &paymentModel.AlipayF2FConfig{})
|
||||
case payment.EPay:
|
||||
epay := &paymentModel.EPayConfig{}
|
||||
if err := epay.Unmarshal(string(data)); err != nil {
|
||||
logger.WithContext(ctx).Errorw("parse epay config error", logger.Field("config", string(data)), logger.Field("error", err.Error()))
|
||||
}
|
||||
return epay.Marshal()
|
||||
return handleConfig("Epay", &paymentModel.EPayConfig{})
|
||||
case payment.CryptoSaaS:
|
||||
return handleConfig("CryptoSaaS", &paymentModel.CryptoSaaSConfig{})
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ type UpdatePaymentMethodLogic struct {
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Update Payment Method
|
||||
// NewUpdatePaymentMethodLogic Update Payment Method
|
||||
func NewUpdatePaymentMethodLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePaymentMethodLogic {
|
||||
return &UpdatePaymentMethodLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type BatchDeleteNodeGroupLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewBatchDeleteNodeGroupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BatchDeleteNodeGroupLogic {
|
||||
return &BatchDeleteNodeGroupLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *BatchDeleteNodeGroupLogic) BatchDeleteNodeGroup(req *types.BatchDeleteNodeGroupRequest) error {
|
||||
// Check if the group is empty
|
||||
count, err := l.svcCtx.ServerModel.QueryServerCountByServerGroups(l.ctx, req.Ids)
|
||||
if err != nil {
|
||||
l.Errorw("[BatchDeleteNodeGroup] Query Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query server error: %v", err)
|
||||
}
|
||||
if count > 0 {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.NodeGroupNotEmpty), "group is not empty")
|
||||
}
|
||||
// Delete the group
|
||||
err = l.svcCtx.ServerModel.BatchDeleteNodeGroup(l.ctx, req.Ids)
|
||||
if err != nil {
|
||||
l.Errorw("[BatchDeleteNodeGroup] Delete Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type BatchDeleteNodeLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewBatchDeleteNodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BatchDeleteNodeLogic {
|
||||
return &BatchDeleteNodeLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *BatchDeleteNodeLogic) BatchDeleteNode(req *types.BatchDeleteNodeRequest) error {
|
||||
err := l.svcCtx.DB.Transaction(func(db *gorm.DB) error {
|
||||
for _, id := range req.Ids {
|
||||
err := l.svcCtx.ServerModel.Delete(l.ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[BatchDeleteNode] Delete Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package server
|
||||
|
||||
const (
|
||||
ShadowSocks = "shadowsocks"
|
||||
Vmess = "vmess"
|
||||
Vless = "vless"
|
||||
Trojan = "trojan"
|
||||
AnyTLS = "anytls"
|
||||
Tuic = "tuic"
|
||||
Hysteria2 = "hysteria2"
|
||||
)
|
||||
@@ -1,40 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/server"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type CreateNodeGroupLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewCreateNodeGroupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateNodeGroupLogic {
|
||||
return &CreateNodeGroupLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *CreateNodeGroupLogic) CreateNodeGroup(req *types.CreateNodeGroupRequest) error {
|
||||
groupInfo := &server.Group{
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
}
|
||||
err := l.svcCtx.ServerModel.InsertGroup(l.ctx, groupInfo)
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -2,18 +2,13 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/server/internal/model/server"
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
queue "github.com/perfect-panel/server/queue/types"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
@@ -23,6 +18,7 @@ type CreateNodeLogic struct {
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewCreateNodeLogic Create Node
|
||||
func NewCreateNodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateNodeLogic {
|
||||
return &CreateNodeLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
@@ -32,97 +28,18 @@ func NewCreateNodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Create
|
||||
}
|
||||
|
||||
func (l *CreateNodeLogic) CreateNode(req *types.CreateNodeRequest) error {
|
||||
config, err := json.Marshal(req.Config)
|
||||
if err != nil {
|
||||
return err
|
||||
data := node.Node{
|
||||
Name: req.Name,
|
||||
Tags: tool.StringSliceToString(req.Tags),
|
||||
Port: req.Port,
|
||||
Address: req.Address,
|
||||
ServerId: req.ServerId,
|
||||
Protocol: req.Protocol,
|
||||
}
|
||||
var serverInfo server.Server
|
||||
tool.DeepCopy(&serverInfo, req)
|
||||
serverInfo.Config = string(config)
|
||||
nodeRelay, err := json.Marshal(req.RelayNode)
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateNode] Marshal RelayNode Error: ", logger.Field("error", err.Error()))
|
||||
return err
|
||||
}
|
||||
if len(req.Tags) > 0 {
|
||||
serverInfo.Tags = strings.Join(req.Tags, ",")
|
||||
}
|
||||
|
||||
serverInfo.LastReportedAt = time.UnixMicro(1218124800)
|
||||
|
||||
serverInfo.City = req.City
|
||||
serverInfo.Country = req.Country
|
||||
|
||||
serverInfo.RelayNode = string(nodeRelay)
|
||||
if req.Protocol == "vless" {
|
||||
var cfg types.Vless
|
||||
if err = json.Unmarshal(config, &cfg); err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "json.Unmarshal error: %v", err.Error())
|
||||
}
|
||||
if cfg.Security == "reality" && cfg.SecurityConfig.RealityPublicKey == "" {
|
||||
public, private, err := tool.Curve25519Genkey(false, "")
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "generate curve25519 key error")
|
||||
}
|
||||
cfg.SecurityConfig.RealityPublicKey = public
|
||||
cfg.SecurityConfig.RealityPrivateKey = private
|
||||
cfg.SecurityConfig.RealityShortId = tool.GenerateShortID(private)
|
||||
}
|
||||
if cfg.SecurityConfig.RealityServerAddr == "" {
|
||||
cfg.SecurityConfig.RealityServerAddr = cfg.SecurityConfig.SNI
|
||||
}
|
||||
if cfg.SecurityConfig.RealityServerPort == 0 {
|
||||
cfg.SecurityConfig.RealityServerPort = 443
|
||||
}
|
||||
config, _ = json.Marshal(cfg)
|
||||
serverInfo.Config = string(config)
|
||||
} else if req.Protocol == "shadowsocks" {
|
||||
var cfg types.Shadowsocks
|
||||
if err = json.Unmarshal(config, &cfg); err != nil {
|
||||
l.Errorf("[CreateNode] Unmarshal Shadowsocks Config Error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "json.Unmarshal error: %v", err.Error())
|
||||
}
|
||||
if strings.Contains(cfg.Method, "2022") {
|
||||
var length int
|
||||
switch cfg.Method {
|
||||
case "2022-blake3-aes-128-gcm":
|
||||
length = 16
|
||||
default:
|
||||
length = 32
|
||||
}
|
||||
if len(cfg.ServerKey) != length {
|
||||
cfg.ServerKey = tool.GenerateCipher(cfg.ServerKey, length)
|
||||
}
|
||||
}
|
||||
config, _ = json.Marshal(cfg)
|
||||
serverInfo.Config = string(config)
|
||||
}
|
||||
|
||||
err = l.svcCtx.ServerModel.Insert(l.ctx, &serverInfo)
|
||||
err := l.svcCtx.NodeModel.InsertNode(l.ctx, &data)
|
||||
if err != nil {
|
||||
l.Errorw("[CreateNode] Insert Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create server error: %v", err)
|
||||
}
|
||||
|
||||
if req.City == "" || req.Country == "" {
|
||||
// Marshal the task payload
|
||||
payload, err := json.Marshal(queue.GetNodeCountry{
|
||||
Protocol: serverInfo.Protocol,
|
||||
ServerAddr: serverInfo.ServerAddr,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[GetNodeCountry]: Marshal Error", logger.Field("error", err.Error()))
|
||||
return errors.Wrap(xerr.NewErrCode(xerr.ERROR), "Failed to marshal task payload")
|
||||
}
|
||||
// Create a queue task
|
||||
task := asynq.NewTask(queue.ForthwithGetCountry, payload)
|
||||
// Enqueue the task
|
||||
taskInfo, err := l.svcCtx.Queue.Enqueue(task)
|
||||
if err != nil {
|
||||
l.Errorw("[GetNodeCountry]: Enqueue Error", logger.Field("error", err.Error()), logger.Field("payload", string(payload)))
|
||||
return errors.Wrap(xerr.NewErrCode(xerr.ERROR), "Failed to enqueue task")
|
||||
}
|
||||
l.Infow("[GetNodeCountry]: Enqueue Success", logger.Field("taskID", taskInfo.ID), logger.Field("payload", string(payload)))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "[CreateNode] Insert Database Error")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/rules"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/server"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type CreateRuleGroupLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Create rule group
|
||||
func NewCreateRuleGroupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRuleGroupLogic {
|
||||
return &CreateRuleGroupLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
func parseAndValidateRules(ruleText, ruleName string) ([]string, error) {
|
||||
var rs []string
|
||||
ruleArr := strings.Split(ruleText, "\n")
|
||||
if len(ruleArr) == 0 {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "rules is empty")
|
||||
}
|
||||
|
||||
for _, s := range ruleArr {
|
||||
r := rules.NewRule(s, ruleName)
|
||||
if r == nil {
|
||||
continue
|
||||
}
|
||||
if err := r.Validate(); err != nil {
|
||||
continue
|
||||
}
|
||||
rs = append(rs, r.String())
|
||||
}
|
||||
return rs, nil
|
||||
}
|
||||
func (l *CreateRuleGroupLogic) CreateRuleGroup(req *types.CreateRuleGroupRequest) error {
|
||||
rs, err := parseAndValidateRules(req.Rules, req.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
info := &server.RuleGroup{
|
||||
Name: req.Name,
|
||||
Icon: req.Icon,
|
||||
Type: req.Type,
|
||||
Tags: tool.StringSliceToString(req.Tags),
|
||||
Rules: strings.Join(rs, "\n"),
|
||||
Default: req.Default,
|
||||
Enable: req.Enable,
|
||||
}
|
||||
err = l.svcCtx.ServerModel.InsertRuleGroup(l.ctx, info)
|
||||
if err != nil {
|
||||
l.Errorw("[CreateRuleGroup] Insert Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create server rule group error: %v", err)
|
||||
}
|
||||
if req.Default {
|
||||
if err = l.svcCtx.ServerModel.SetDefaultRuleGroup(l.ctx, info.Id); err != nil {
|
||||
l.Errorw("[CreateRuleGroup] Set Default Rule Group Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "set default rule group error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/ip"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type CreateServerLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewCreateServerLogic Create Server
|
||||
func NewCreateServerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateServerLogic {
|
||||
return &CreateServerLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *CreateServerLogic) CreateServer(req *types.CreateServerRequest) error {
|
||||
data := node.Server{
|
||||
Name: req.Name,
|
||||
Country: req.Country,
|
||||
City: req.City,
|
||||
Ratio: req.Ratio,
|
||||
Address: req.Address,
|
||||
Sort: req.Sort,
|
||||
Protocols: "",
|
||||
}
|
||||
protocols := make([]node.Protocol, 0)
|
||||
for _, item := range req.Protocols {
|
||||
if item.Type == "" {
|
||||
return errors.Wrapf(xerr.NewErrCodeMsg(xerr.InvalidParams, "protocols type is empty"), "protocols type is empty")
|
||||
}
|
||||
var protocol node.Protocol
|
||||
tool.DeepCopy(&protocol, item)
|
||||
|
||||
// VLESS Reality Key Generation
|
||||
if protocol.Type == "vless" {
|
||||
if protocol.Security == "reality" {
|
||||
if protocol.RealityPublicKey == "" {
|
||||
public, private, err := tool.Curve25519Genkey(false, "")
|
||||
if err != nil {
|
||||
l.Errorf("[CreateServer] Generate Reality Key Error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "generate reality key error: %v", err)
|
||||
}
|
||||
protocol.RealityPublicKey = public
|
||||
protocol.RealityPrivateKey = private
|
||||
protocol.RealityShortId = tool.GenerateShortID(private)
|
||||
}
|
||||
if protocol.RealityServerAddr == "" {
|
||||
protocol.RealityServerAddr = protocol.SNI
|
||||
}
|
||||
if protocol.RealityServerPort == 0 {
|
||||
protocol.RealityServerPort = 443
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
// ShadowSocks 2022 Key Generation
|
||||
if protocol.Type == "shadowsocks" {
|
||||
if strings.Contains(protocol.Cipher, "2022") {
|
||||
var length int
|
||||
switch protocol.Cipher {
|
||||
case "2022-blake3-aes-128-gcm":
|
||||
length = 16
|
||||
default:
|
||||
length = 32
|
||||
}
|
||||
if len(protocol.ServerKey) != length {
|
||||
protocol.ServerKey = tool.GenerateCipher(protocol.ServerKey, length)
|
||||
}
|
||||
}
|
||||
}
|
||||
protocols = append(protocols, protocol)
|
||||
}
|
||||
|
||||
err := data.MarshalProtocols(protocols)
|
||||
if err != nil {
|
||||
l.Errorf("[CreateServer] Marshal Protocols Error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCodeMsg(xerr.InvalidParams, "protocols marshal error"), "protocols marshal error: %v", err)
|
||||
}
|
||||
if data.City == "" && data.Country == "" {
|
||||
// query server ip location
|
||||
result, err := ip.GetRegionByIp(req.Address)
|
||||
if err != nil {
|
||||
l.Errorf("[CreateServer] GetRegionByIp Error: %v", err.Error())
|
||||
} else {
|
||||
data.City = result.City
|
||||
data.Country = result.Country
|
||||
}
|
||||
}
|
||||
err = l.svcCtx.NodeModel.InsertServer(l.ctx, &data)
|
||||
if err != nil {
|
||||
l.Errorf("[CreateServer] Insert Server error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert server error: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type DeleteNodeGroupLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewDeleteNodeGroupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteNodeGroupLogic {
|
||||
return &DeleteNodeGroupLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DeleteNodeGroupLogic) DeleteNodeGroup(req *types.DeleteNodeGroupRequest) error {
|
||||
// Check if the group is empty
|
||||
count, err := l.svcCtx.ServerModel.QueryServerCountByServerGroups(l.ctx, []int64{req.Id})
|
||||
if err != nil {
|
||||
l.Errorw("[DeleteNodeGroup] Query Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query server error: %v", err)
|
||||
}
|
||||
if count > 0 {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.NodeGroupNotEmpty), "group is not empty")
|
||||
}
|
||||
// Delete the group
|
||||
err = l.svcCtx.ServerModel.DeleteGroup(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[DeleteNodeGroup] Delete Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -2,14 +2,12 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DeleteNodeLogic struct {
|
||||
@@ -18,6 +16,7 @@ type DeleteNodeLogic struct {
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewDeleteNodeLogic Delete Node
|
||||
func NewDeleteNodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteNodeLogic {
|
||||
return &DeleteNodeLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
@@ -27,33 +26,10 @@ func NewDeleteNodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Delete
|
||||
}
|
||||
|
||||
func (l *DeleteNodeLogic) DeleteNode(req *types.DeleteNodeRequest) error {
|
||||
err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
|
||||
// Delete server
|
||||
err := l.svcCtx.ServerModel.Delete(l.ctx, req.Id, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Delete server to subscribe
|
||||
subs, err := l.svcCtx.SubscribeModel.QuerySubscribeIdsByServerIdAndServerGroupId(l.ctx, req.Id, 0)
|
||||
if err != nil {
|
||||
l.Logger.Errorf("[DeleteNode] QuerySubscribeIdsByServerIdAndServerGroupId error: %v", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
for _, sub := range subs {
|
||||
servers := tool.StringToInt64Slice(sub.Server)
|
||||
newServers := tool.RemoveElementBySlice(servers, req.Id)
|
||||
sub.Server = tool.Int64SliceToString(newServers)
|
||||
if err = l.svcCtx.SubscribeModel.Update(l.ctx, sub, tx); err != nil {
|
||||
l.Logger.Errorf("[DeleteNode] UpdateSubscribe error: %v", err.Error())
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
err := l.svcCtx.NodeModel.DeleteNode(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[DeleteNode] Delete Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete server error: %v", err)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "[DeleteNode] Delete Database Error")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+8
-8
@@ -10,26 +10,26 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type DeleteRuleGroupLogic struct {
|
||||
type DeleteServerLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Delete rule group
|
||||
func NewDeleteRuleGroupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteRuleGroupLogic {
|
||||
return &DeleteRuleGroupLogic{
|
||||
// NewDeleteServerLogic Delete Server
|
||||
func NewDeleteServerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteServerLogic {
|
||||
return &DeleteServerLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DeleteRuleGroupLogic) DeleteRuleGroup(req *types.DeleteRuleGroupRequest) error {
|
||||
err := l.svcCtx.ServerModel.DeleteRuleGroup(l.ctx, req.Id)
|
||||
func (l *DeleteServerLogic) DeleteServer(req *types.DeleteServerRequest) error {
|
||||
err := l.svcCtx.NodeModel.DeleteServer(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[DeleteRuleGroup] Delete Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete server rule group error: %v", err)
|
||||
l.Errorw("[DeleteServer] Delete Server Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "[DeleteServer] Delete Server Error")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type FilterNodeListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterNodeListLogic Filter Node List
|
||||
func NewFilterNodeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterNodeListLogic {
|
||||
return &FilterNodeListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterNodeListLogic) FilterNodeList(req *types.FilterNodeListRequest) (resp *types.FilterNodeListResponse, err error) {
|
||||
total, data, err := l.svcCtx.NodeModel.FilterNodeList(l.ctx, &node.FilterNodeParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Search: req.Search,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorw("[FilterNodeList] Query Database Error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[FilterNodeList] Query Database Error")
|
||||
}
|
||||
|
||||
list := make([]types.Node, 0)
|
||||
for _, datum := range data {
|
||||
list = append(list, types.Node{
|
||||
Id: datum.Id,
|
||||
Name: datum.Name,
|
||||
Tags: tool.RemoveDuplicateElements(strings.Split(datum.Tags, ",")...),
|
||||
Port: datum.Port,
|
||||
Address: datum.Address,
|
||||
ServerId: datum.ServerId,
|
||||
Protocol: datum.Protocol,
|
||||
Enabled: datum.Enabled,
|
||||
Sort: datum.Sort,
|
||||
CreatedAt: datum.CreatedAt.UnixMilli(),
|
||||
UpdatedAt: datum.UpdatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.FilterNodeListResponse{
|
||||
List: list,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type FilterServerListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewFilterServerListLogic Filter Server List
|
||||
func NewFilterServerListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterServerListLogic {
|
||||
return &FilterServerListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *FilterServerListLogic) FilterServerList(req *types.FilterServerListRequest) (resp *types.FilterServerListResponse, err error) {
|
||||
total, data, err := l.svcCtx.NodeModel.FilterServerList(l.ctx, &node.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Search: req.Search,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[FilterServerList] Query Database Error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[FilterServerList] Query Database Error")
|
||||
}
|
||||
|
||||
list := make([]types.Server, 0)
|
||||
|
||||
for _, datum := range data {
|
||||
var server types.Server
|
||||
tool.DeepCopy(&server, datum)
|
||||
|
||||
// handler protocols
|
||||
var protocols []types.Protocol
|
||||
dst, err := datum.UnmarshalProtocols()
|
||||
if err != nil {
|
||||
l.Errorf("[FilterServerList] UnmarshalProtocols Error: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
tool.DeepCopy(&protocols, dst)
|
||||
server.Protocols = protocols
|
||||
|
||||
nodeStatus, err := l.svcCtx.NodeModel.StatusCache(l.ctx, datum.Id)
|
||||
if err != nil {
|
||||
if !errors.Is(err, redis.Nil) {
|
||||
l.Errorw("[handlerServerStatus] GetNodeStatus Error: ", logger.Field("error", err.Error()), logger.Field("node_id", datum.Id))
|
||||
}
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetNodeStatus Error")
|
||||
}
|
||||
server.Status = types.ServerStatus{
|
||||
Mem: nodeStatus.Mem,
|
||||
Cpu: nodeStatus.Cpu,
|
||||
Disk: nodeStatus.Disk,
|
||||
Online: l.handlerServerStatus(datum.Id, protocols),
|
||||
Status: l.handlerServerStaus(datum.LastReportedAt),
|
||||
}
|
||||
list = append(list, server)
|
||||
}
|
||||
|
||||
return &types.FilterServerListResponse{
|
||||
List: list,
|
||||
Total: total,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l *FilterServerListLogic) handlerServerStatus(id int64, protocols []types.Protocol) []types.ServerOnlineUser {
|
||||
result := make([]types.ServerOnlineUser, 0)
|
||||
|
||||
for _, protocol := range protocols {
|
||||
// query online user
|
||||
data, err := l.svcCtx.NodeModel.OnlineUserSubscribe(l.ctx, id, protocol.Type)
|
||||
if err != nil {
|
||||
if !errors.Is(err, redis.Nil) {
|
||||
l.Errorw("[handlerServerStatus] OnlineUserSubscribe Error: ", logger.Field("error", err.Error()), logger.Field("node_id", id), logger.Field("protocol", protocol.Type))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(data) > 0 {
|
||||
for sub, online := range data {
|
||||
var ips []types.ServerOnlineIP
|
||||
for _, ip := range online {
|
||||
ips = append(ips, types.ServerOnlineIP{
|
||||
IP: ip,
|
||||
Protocol: protocol.Type,
|
||||
})
|
||||
}
|
||||
|
||||
result = append(result, types.ServerOnlineUser{
|
||||
IP: ips,
|
||||
SubscribeId: sub,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
// merge same subscribe
|
||||
var mapResult = make(map[int64]types.ServerOnlineUser)
|
||||
for _, item := range result {
|
||||
if exist, ok := mapResult[item.SubscribeId]; ok {
|
||||
// merge
|
||||
exist.Traffic += item.Traffic
|
||||
exist.IP = append(exist.IP, item.IP...)
|
||||
mapResult[item.SubscribeId] = exist
|
||||
} else {
|
||||
// get subscribe info
|
||||
info, err := l.svcCtx.UserModel.FindOneUserSubscribe(l.ctx, item.SubscribeId)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[handlerServerStatus] FindOneSubscribe Error: ", logger.Field("error", err.Error()), logger.Field("subscribe_id", item.SubscribeId))
|
||||
}
|
||||
continue
|
||||
}
|
||||
data := types.ServerOnlineUser{
|
||||
IP: item.IP,
|
||||
UserId: info.UserId,
|
||||
Subscribe: "",
|
||||
SubscribeId: item.SubscribeId,
|
||||
Traffic: info.Download + info.Upload,
|
||||
ExpiredAt: info.ExpireTime.UnixMilli(),
|
||||
}
|
||||
if info.Subscribe != nil {
|
||||
data.Subscribe = info.Subscribe.Name
|
||||
}
|
||||
// add new
|
||||
mapResult[item.SubscribeId] = data
|
||||
}
|
||||
}
|
||||
// convert map to slice
|
||||
result = make([]types.ServerOnlineUser, 0, len(mapResult))
|
||||
for _, item := range mapResult {
|
||||
result = append(result, item)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (l *FilterServerListLogic) handlerServerStaus(last *time.Time) string {
|
||||
if last == nil {
|
||||
return "offline"
|
||||
}
|
||||
if time.Since(*last) > time.Minute*5 {
|
||||
return "offline"
|
||||
}
|
||||
if time.Since(*last) > time.Minute*3 {
|
||||
return "warning"
|
||||
}
|
||||
return "online"
|
||||
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetNodeDetailLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetNodeDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetNodeDetailLogic {
|
||||
return &GetNodeDetailLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetNodeDetailLogic) GetNodeDetail(req *types.GetDetailRequest) (resp *types.Server, err error) {
|
||||
detail, err := l.svcCtx.ServerModel.FindOne(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get server detail error: %v", err.Error())
|
||||
}
|
||||
resp = &types.Server{}
|
||||
tool.DeepCopy(resp, detail)
|
||||
var cfg map[string]interface{}
|
||||
err = json.Unmarshal([]byte(detail.Config), &cfg)
|
||||
if err != nil {
|
||||
cfg = make(map[string]interface{})
|
||||
}
|
||||
resp.Config = cfg
|
||||
return
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetNodeGroupListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetNodeGroupListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetNodeGroupListLogic {
|
||||
return &GetNodeGroupListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetNodeGroupListLogic) GetNodeGroupList() (resp *types.GetNodeGroupListResponse, err error) {
|
||||
nodeGroupList, err := l.svcCtx.ServerModel.QueryAllGroup(l.ctx)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), err.Error())
|
||||
}
|
||||
nodeGroups := make([]types.ServerGroup, 0)
|
||||
tool.DeepCopy(&nodeGroups, nodeGroupList)
|
||||
return &types.GetNodeGroupListResponse{
|
||||
Total: int64(len(nodeGroups)),
|
||||
List: nodeGroups,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/server"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetNodeListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetNodeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetNodeListLogic {
|
||||
return &GetNodeListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetNodeListLogic) GetNodeList(req *types.GetNodeServerListRequest) (resp *types.GetNodeServerListResponse, err error) {
|
||||
tags := make([]string, 0)
|
||||
if req.Tags != "" {
|
||||
tags = strings.Split(req.Tags, ",")
|
||||
}
|
||||
total, list, err := l.svcCtx.ServerModel.FindServerListByFilter(l.ctx, &server.ServerFilter{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Search: req.Search,
|
||||
Tags: tags,
|
||||
Group: req.GroupId,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[GetNodeList] Query Database Error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), err.Error())
|
||||
}
|
||||
nodes := make([]types.Server, 0)
|
||||
for _, v := range list {
|
||||
node := types.Server{}
|
||||
tool.DeepCopy(&node, v)
|
||||
// default relay mode
|
||||
if node.RelayMode == "" {
|
||||
node.RelayMode = "none"
|
||||
}
|
||||
if len(v.Tags) > 0 {
|
||||
if strings.Contains(v.Tags, ",") {
|
||||
node.Tags = strings.Split(v.Tags, ",")
|
||||
} else {
|
||||
node.Tags = []string{v.Tags}
|
||||
}
|
||||
}
|
||||
// parse config
|
||||
var cfg map[string]interface{}
|
||||
err = json.Unmarshal([]byte(v.Config), &cfg)
|
||||
if err != nil {
|
||||
cfg = make(map[string]interface{})
|
||||
}
|
||||
node.Config = cfg
|
||||
relayNode := make([]types.NodeRelay, 0)
|
||||
err = json.Unmarshal([]byte(v.RelayNode), &relayNode)
|
||||
if err != nil {
|
||||
l.Errorw("[GetNodeList] Unmarshal RelayNode Error: ", logger.Field("error", err.Error()), logger.Field("relayNode", v.RelayNode))
|
||||
}
|
||||
node.RelayNode = relayNode
|
||||
var status types.NodeStatus
|
||||
nodeStatus, err := l.svcCtx.NodeCache.GetNodeStatus(l.ctx, v.Id)
|
||||
if err != nil {
|
||||
// redis nil is not a Error
|
||||
if !errors.Is(err, redis.Nil) {
|
||||
l.Errorw("[GetNodeList] Get Node Status Error: ", logger.Field("error", err.Error()))
|
||||
}
|
||||
} else {
|
||||
onlineUser, err := l.svcCtx.NodeCache.GetNodeOnlineUser(l.ctx, v.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[GetNodeList] Get Node Online User Error: ", logger.Field("error", err.Error()))
|
||||
} else {
|
||||
status.Online = onlineUser
|
||||
}
|
||||
status.Cpu = nodeStatus.Cpu
|
||||
status.Mem = nodeStatus.Mem
|
||||
status.Disk = nodeStatus.Disk
|
||||
status.UpdatedAt = nodeStatus.UpdatedAt
|
||||
}
|
||||
node.Status = &status
|
||||
nodes = append(nodes, node)
|
||||
}
|
||||
return &types.GetNodeServerListResponse{
|
||||
Total: total,
|
||||
List: nodes,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
)
|
||||
|
||||
type GetNodeTagListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get node tag list
|
||||
func NewGetNodeTagListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetNodeTagListLogic {
|
||||
return &GetNodeTagListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetNodeTagListLogic) GetNodeTagList() (resp *types.GetNodeTagListResponse, err error) {
|
||||
tags, err := l.svcCtx.ServerModel.FindServerTags(l.ctx)
|
||||
return &types.GetNodeTagListResponse{
|
||||
Tags: tool.RemoveDuplicateElements(tags...),
|
||||
}, nil
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetRuleGroupListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get rule group list
|
||||
func NewGetRuleGroupListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRuleGroupListLogic {
|
||||
return &GetRuleGroupListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetRuleGroupListLogic) GetRuleGroupList() (resp *types.GetRuleGroupResponse, err error) {
|
||||
nodeRuleGroupList, err := l.svcCtx.ServerModel.QueryAllRuleGroup(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[GetRuleGroupList] Query Database Error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), err.Error())
|
||||
}
|
||||
nodeRuleGroups := make([]types.ServerRuleGroup, len(nodeRuleGroupList))
|
||||
for i, v := range nodeRuleGroupList {
|
||||
nodeRuleGroups[i] = types.ServerRuleGroup{
|
||||
Id: v.Id,
|
||||
Icon: v.Icon,
|
||||
Name: v.Name,
|
||||
Type: v.Type,
|
||||
Tags: strings.Split(v.Tags, ","),
|
||||
Rules: v.Rules,
|
||||
Enable: v.Enable,
|
||||
Default: v.Default,
|
||||
CreatedAt: v.CreatedAt.UnixMilli(),
|
||||
UpdatedAt: v.UpdatedAt.UnixMilli(),
|
||||
}
|
||||
}
|
||||
return &types.GetRuleGroupResponse{
|
||||
Total: int64(len(nodeRuleGroups)),
|
||||
List: nodeRuleGroups,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetServerProtocolsLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get Server Protocols
|
||||
func NewGetServerProtocolsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetServerProtocolsLogic {
|
||||
return &GetServerProtocolsLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetServerProtocolsLogic) GetServerProtocols(req *types.GetServerProtocolsRequest) (resp *types.GetServerProtocolsResponse, err error) {
|
||||
// find server
|
||||
data, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorf("[GetServerProtocols] FindOneServer Error: %s", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[GetServerProtocols] FindOneServer Error: %s", err.Error())
|
||||
}
|
||||
|
||||
// handler protocols
|
||||
var protocols []types.Protocol
|
||||
dst, err := data.UnmarshalProtocols()
|
||||
if err != nil {
|
||||
l.Errorf("[FilterServerList] UnmarshalProtocols Error: %s", err.Error())
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[FilterServerList] UnmarshalProtocols Error: %s", err.Error())
|
||||
}
|
||||
tool.DeepCopy(&protocols, dst)
|
||||
|
||||
return &types.GetServerProtocolsResponse{
|
||||
Protocols: protocols,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/model/server"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type HasMigrateSeverNodeLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewHasMigrateSeverNodeLogic Check if there is any server or node to migrate
|
||||
func NewHasMigrateSeverNodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HasMigrateSeverNodeLogic {
|
||||
return &HasMigrateSeverNodeLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *HasMigrateSeverNodeLogic) HasMigrateSeverNode() (resp *types.HasMigrateSeverNodeResponse, err error) {
|
||||
var oldCount, newCount int64
|
||||
query := l.svcCtx.DB.WithContext(l.ctx)
|
||||
|
||||
err = query.Model(&server.Server{}).Count(&oldCount).Error
|
||||
if err != nil {
|
||||
l.Errorw("[HasMigrateSeverNode] Query Old Server Count Error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[HasMigrateSeverNode] Query Old Server Count Error")
|
||||
}
|
||||
err = query.Model(&node.Server{}).Count(&newCount).Error
|
||||
if err != nil {
|
||||
l.Errorw("[HasMigrateSeverNode] Query New Server Count Error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[HasMigrateSeverNode] Query New Server Count Error")
|
||||
}
|
||||
var shouldMigrate bool
|
||||
if oldCount != 0 && newCount == 0 {
|
||||
shouldMigrate = true
|
||||
}
|
||||
|
||||
return &types.HasMigrateSeverNodeResponse{
|
||||
HasMigrate: shouldMigrate,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/model/server"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type MigrateServerNodeLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewMigrateServerNodeLogic Migrate server and node data to new database
|
||||
func NewMigrateServerNodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MigrateServerNodeLogic {
|
||||
return &MigrateServerNodeLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *MigrateServerNodeLogic) MigrateServerNode() (resp *types.MigrateServerNodeResponse, err error) {
|
||||
tx := l.svcCtx.DB.WithContext(l.ctx).Begin()
|
||||
var oldServers []*server.Server
|
||||
var newServers []*node.Server
|
||||
var newNodes []*node.Node
|
||||
|
||||
err = tx.Model(&server.Server{}).Find(&oldServers).Error
|
||||
if err != nil {
|
||||
l.Errorw("[MigrateServerNode] Query Old Server List Error: ", logger.Field("error", err.Error()))
|
||||
return &types.MigrateServerNodeResponse{
|
||||
Succee: 0,
|
||||
Fail: 0,
|
||||
Message: fmt.Sprintf("Query Old Server List Error: %s", err.Error()),
|
||||
}, nil
|
||||
}
|
||||
for _, oldServer := range oldServers {
|
||||
data, err := l.adapterServer(oldServer)
|
||||
if err != nil {
|
||||
l.Errorw("[MigrateServerNode] Adapter Server Error: ", logger.Field("error", err.Error()))
|
||||
if resp == nil {
|
||||
resp = &types.MigrateServerNodeResponse{}
|
||||
}
|
||||
resp.Fail++
|
||||
if resp.Message == "" {
|
||||
resp.Message = fmt.Sprintf("Adapter Server Error: %s", err.Error())
|
||||
} else {
|
||||
resp.Message = fmt.Sprintf("%s; Adapter Server Error: %s", resp.Message, err.Error())
|
||||
}
|
||||
continue
|
||||
}
|
||||
newServers = append(newServers, data)
|
||||
|
||||
newNode, err := l.adapterNode(oldServer)
|
||||
if err != nil {
|
||||
l.Errorw("[MigrateServerNode] Adapter Node Error: ", logger.Field("error", err.Error()))
|
||||
if resp == nil {
|
||||
resp = &types.MigrateServerNodeResponse{}
|
||||
}
|
||||
resp.Fail++
|
||||
if resp.Message == "" {
|
||||
resp.Message = fmt.Sprintf("Adapter Node Error: %s", err.Error())
|
||||
} else {
|
||||
resp.Message = fmt.Sprintf("%s; Adapter Node Error: %s", resp.Message, err.Error())
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, item := range newNode {
|
||||
if item.Port == 0 {
|
||||
protocols, _ := data.UnmarshalProtocols()
|
||||
if len(protocols) > 0 {
|
||||
item.Port = protocols[0].Port
|
||||
}
|
||||
}
|
||||
newNodes = append(newNodes, item)
|
||||
}
|
||||
}
|
||||
|
||||
if len(newServers) > 0 {
|
||||
err = tx.Model(&node.Server{}).CreateInBatches(newServers, 20).Error
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
l.Errorw("[MigrateServerNode] Insert New Server List Error: ", logger.Field("error", err.Error()))
|
||||
return &types.MigrateServerNodeResponse{
|
||||
Succee: 0,
|
||||
Fail: uint64(len(newServers)),
|
||||
Message: fmt.Sprintf("Insert New Server List Error: %s", err.Error()),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
if len(newNodes) > 0 {
|
||||
err = tx.Model(&node.Node{}).CreateInBatches(newNodes, 20).Error
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
l.Errorw("[MigrateServerNode] Insert New Node List Error: ", logger.Field("error", err.Error()))
|
||||
return &types.MigrateServerNodeResponse{
|
||||
Succee: uint64(len(newServers)),
|
||||
Fail: uint64(len(newNodes)),
|
||||
Message: fmt.Sprintf("Insert New Node List Error: %s", err.Error()),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
tx.Commit()
|
||||
|
||||
return &types.MigrateServerNodeResponse{
|
||||
Succee: uint64(len(newServers)),
|
||||
Fail: 0,
|
||||
Message: fmt.Sprintf("Migrate Success: %d servers and %d nodes", len(newServers), len(newNodes)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l *MigrateServerNodeLogic) adapterServer(info *server.Server) (*node.Server, error) {
|
||||
result := &node.Server{
|
||||
Id: info.Id,
|
||||
Name: info.Name,
|
||||
Country: info.Country,
|
||||
City: info.City,
|
||||
Ratio: info.TrafficRatio,
|
||||
Address: info.ServerAddr,
|
||||
Sort: int(info.Sort),
|
||||
Protocols: "",
|
||||
}
|
||||
var protocols []node.Protocol
|
||||
|
||||
switch info.Protocol {
|
||||
case ShadowSocks:
|
||||
var src server.Shadowsocks
|
||||
err := json.Unmarshal([]byte(info.Config), &src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
protocols = append(protocols, node.Protocol{
|
||||
Type: "shadowsocks",
|
||||
Cipher: src.Method,
|
||||
Port: uint16(src.Port),
|
||||
ServerKey: src.ServerKey,
|
||||
})
|
||||
case Vmess:
|
||||
var src server.Vmess
|
||||
err := json.Unmarshal([]byte(info.Config), &src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
protocol := node.Protocol{
|
||||
Type: "vmess",
|
||||
Port: uint16(src.Port),
|
||||
Security: src.Security,
|
||||
SNI: src.SecurityConfig.SNI,
|
||||
AllowInsecure: src.SecurityConfig.AllowInsecure,
|
||||
Fingerprint: src.SecurityConfig.Fingerprint,
|
||||
RealityServerAddr: src.SecurityConfig.RealityServerAddr,
|
||||
RealityServerPort: src.SecurityConfig.RealityServerPort,
|
||||
RealityPrivateKey: src.SecurityConfig.RealityPrivateKey,
|
||||
RealityPublicKey: src.SecurityConfig.RealityPublicKey,
|
||||
RealityShortId: src.SecurityConfig.RealityShortId,
|
||||
Transport: src.Transport,
|
||||
Host: src.TransportConfig.Host,
|
||||
Path: src.TransportConfig.Path,
|
||||
ServiceName: src.TransportConfig.ServiceName,
|
||||
Flow: src.Flow,
|
||||
}
|
||||
protocols = append(protocols, protocol)
|
||||
protocols = append(protocols, protocol)
|
||||
case Vless:
|
||||
var src server.Vless
|
||||
err := json.Unmarshal([]byte(info.Config), &src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
protocol := node.Protocol{
|
||||
Type: "vless",
|
||||
Port: uint16(src.Port),
|
||||
Security: src.Security,
|
||||
SNI: src.SecurityConfig.SNI,
|
||||
AllowInsecure: src.SecurityConfig.AllowInsecure,
|
||||
Fingerprint: src.SecurityConfig.Fingerprint,
|
||||
RealityServerAddr: src.SecurityConfig.RealityServerAddr,
|
||||
RealityServerPort: src.SecurityConfig.RealityServerPort,
|
||||
RealityPrivateKey: src.SecurityConfig.RealityPrivateKey,
|
||||
RealityPublicKey: src.SecurityConfig.RealityPublicKey,
|
||||
RealityShortId: src.SecurityConfig.RealityShortId,
|
||||
Transport: src.Transport,
|
||||
Host: src.TransportConfig.Host,
|
||||
Path: src.TransportConfig.Path,
|
||||
ServiceName: src.TransportConfig.ServiceName,
|
||||
Flow: src.Flow,
|
||||
}
|
||||
protocols = append(protocols, protocol)
|
||||
case Trojan:
|
||||
var src server.Trojan
|
||||
err := json.Unmarshal([]byte(info.Config), &src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
protocol := node.Protocol{
|
||||
Type: "trojan",
|
||||
Port: uint16(src.Port),
|
||||
Security: src.Security,
|
||||
SNI: src.SecurityConfig.SNI,
|
||||
AllowInsecure: src.SecurityConfig.AllowInsecure,
|
||||
Fingerprint: src.SecurityConfig.Fingerprint,
|
||||
RealityServerAddr: src.SecurityConfig.RealityServerAddr,
|
||||
RealityServerPort: src.SecurityConfig.RealityServerPort,
|
||||
RealityPrivateKey: src.SecurityConfig.RealityPrivateKey,
|
||||
RealityPublicKey: src.SecurityConfig.RealityPublicKey,
|
||||
RealityShortId: src.SecurityConfig.RealityShortId,
|
||||
Transport: src.Transport,
|
||||
Host: src.TransportConfig.Host,
|
||||
Path: src.TransportConfig.Path,
|
||||
ServiceName: src.TransportConfig.ServiceName,
|
||||
Flow: src.Flow,
|
||||
}
|
||||
protocols = append(protocols, protocol)
|
||||
case Hysteria2:
|
||||
var src server.Hysteria2
|
||||
err := json.Unmarshal([]byte(info.Config), &src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
protocol := node.Protocol{
|
||||
Type: "hysteria2",
|
||||
Port: uint16(src.Port),
|
||||
HopPorts: src.HopPorts,
|
||||
HopInterval: src.HopInterval,
|
||||
ObfsPassword: src.ObfsPassword,
|
||||
SNI: src.SecurityConfig.SNI,
|
||||
AllowInsecure: src.SecurityConfig.AllowInsecure,
|
||||
Fingerprint: src.SecurityConfig.Fingerprint,
|
||||
RealityServerAddr: src.SecurityConfig.RealityServerAddr,
|
||||
RealityServerPort: src.SecurityConfig.RealityServerPort,
|
||||
RealityPrivateKey: src.SecurityConfig.RealityPrivateKey,
|
||||
RealityPublicKey: src.SecurityConfig.RealityPublicKey,
|
||||
RealityShortId: src.SecurityConfig.RealityShortId,
|
||||
}
|
||||
protocols = append(protocols, protocol)
|
||||
case Tuic:
|
||||
var src server.Tuic
|
||||
err := json.Unmarshal([]byte(info.Config), &src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
protocol := node.Protocol{
|
||||
Type: "tuic",
|
||||
Port: uint16(src.Port),
|
||||
DisableSNI: src.DisableSNI,
|
||||
ReduceRtt: src.ReduceRtt,
|
||||
UDPRelayMode: src.UDPRelayMode,
|
||||
CongestionController: src.CongestionController,
|
||||
SNI: src.SecurityConfig.SNI,
|
||||
AllowInsecure: src.SecurityConfig.AllowInsecure,
|
||||
Fingerprint: src.SecurityConfig.Fingerprint,
|
||||
RealityServerAddr: src.SecurityConfig.RealityServerAddr,
|
||||
RealityServerPort: src.SecurityConfig.RealityServerPort,
|
||||
RealityPrivateKey: src.SecurityConfig.RealityPrivateKey,
|
||||
RealityPublicKey: src.SecurityConfig.RealityPublicKey,
|
||||
RealityShortId: src.SecurityConfig.RealityShortId,
|
||||
}
|
||||
protocols = append(protocols, protocol)
|
||||
case AnyTLS:
|
||||
var src server.AnyTLS
|
||||
err := json.Unmarshal([]byte(info.Config), &src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
protocol := node.Protocol{
|
||||
Type: "anytls",
|
||||
Port: uint16(src.Port),
|
||||
SNI: src.SecurityConfig.SNI,
|
||||
AllowInsecure: src.SecurityConfig.AllowInsecure,
|
||||
Fingerprint: src.SecurityConfig.Fingerprint,
|
||||
RealityServerAddr: src.SecurityConfig.RealityServerAddr,
|
||||
RealityServerPort: src.SecurityConfig.RealityServerPort,
|
||||
RealityPrivateKey: src.SecurityConfig.RealityPrivateKey,
|
||||
RealityPublicKey: src.SecurityConfig.RealityPublicKey,
|
||||
RealityShortId: src.SecurityConfig.RealityShortId,
|
||||
}
|
||||
protocols = append(protocols, protocol)
|
||||
}
|
||||
if len(protocols) > 0 {
|
||||
err := result.MarshalProtocols(protocols)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (l *MigrateServerNodeLogic) adapterNode(info *server.Server) ([]*node.Node, error) {
|
||||
var nodes []*node.Node
|
||||
enable := true
|
||||
switch info.RelayMode {
|
||||
case server.RelayModeNone:
|
||||
nodes = append(nodes, &node.Node{
|
||||
Name: info.Name,
|
||||
Tags: "",
|
||||
Port: 0,
|
||||
Address: info.ServerAddr,
|
||||
ServerId: info.Id,
|
||||
Protocol: info.Protocol,
|
||||
Enabled: &enable,
|
||||
})
|
||||
default:
|
||||
var relays []server.NodeRelay
|
||||
err := json.Unmarshal([]byte(info.RelayNode), &relays)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, relay := range relays {
|
||||
nodes = append(nodes, &node.Node{
|
||||
Name: relay.Prefix + info.Name,
|
||||
Tags: "",
|
||||
Port: uint16(relay.Port),
|
||||
Address: relay.Host,
|
||||
ServerId: info.Id,
|
||||
Protocol: info.Protocol,
|
||||
Enabled: &enable,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return nodes, nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type QueryNodeTagLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewQueryNodeTagLogic Query all node tags
|
||||
func NewQueryNodeTagLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryNodeTagLogic {
|
||||
return &QueryNodeTagLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryNodeTagLogic) QueryNodeTag() (resp *types.QueryNodeTagResponse, err error) {
|
||||
|
||||
var nodes []*node.Node
|
||||
if err = l.svcCtx.DB.WithContext(l.ctx).Model(&node.Node{}).Find(&nodes).Error; err != nil {
|
||||
l.Errorw("[QueryNodeTag] Query Database Error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[QueryNodeTag] Query Database Error")
|
||||
}
|
||||
var tags []string
|
||||
for _, item := range nodes {
|
||||
tags = append(tags, strings.Split(item.Tags, ",")...)
|
||||
}
|
||||
|
||||
return &types.QueryNodeTagResponse{
|
||||
Tags: tool.RemoveDuplicateElements(tags...),
|
||||
}, nil
|
||||
}
|
||||
+17
-18
@@ -3,36 +3,35 @@ package server
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/server"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type NodeSortLogic struct {
|
||||
type ResetSortWithNodeLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Node sort
|
||||
func NewNodeSortLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NodeSortLogic {
|
||||
return &NodeSortLogic{
|
||||
// NewResetSortWithNodeLogic Reset node sort
|
||||
func NewResetSortWithNodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetSortWithNodeLogic {
|
||||
return &ResetSortWithNodeLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *NodeSortLogic) NodeSort(req *types.NodeSortRequest) error {
|
||||
err := l.svcCtx.ServerModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||
func (l *ResetSortWithNodeLogic) ResetSortWithNode(req *types.ResetSortRequest) error {
|
||||
err := l.svcCtx.NodeModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||
// find all servers id
|
||||
var existingIDs []int64
|
||||
db.Model(&server.Server{}).Select("id").Find(&existingIDs)
|
||||
db.Model(&node.Node{}).Select("id").Find(&existingIDs)
|
||||
// check if the id is valid
|
||||
validIDMap := make(map[int64]bool)
|
||||
for _, id := range existingIDs {
|
||||
@@ -46,12 +45,12 @@ func (l *NodeSortLogic) NodeSort(req *types.NodeSortRequest) error {
|
||||
}
|
||||
}
|
||||
// query all servers
|
||||
var servers []*server.Server
|
||||
db.Model(&server.Server{}).Order("sort ASC").Find(&servers)
|
||||
var servers []*node.Node
|
||||
db.Model(&node.Node{}).Order("sort ASC").Find(&servers)
|
||||
// create a map of the current sort
|
||||
currentSortMap := make(map[int64]int64)
|
||||
for _, item := range servers {
|
||||
currentSortMap[item.Id] = item.Sort
|
||||
currentSortMap[item.Id] = int64(item.Sort)
|
||||
}
|
||||
|
||||
// new sort map
|
||||
@@ -67,12 +66,12 @@ func (l *NodeSortLogic) NodeSort(req *types.NodeSortRequest) error {
|
||||
}
|
||||
}
|
||||
for _, item := range itemsToUpdate {
|
||||
s, err := l.svcCtx.ServerModel.FindOne(l.ctx, item.Id)
|
||||
s, err := l.svcCtx.NodeModel.FindOneNode(l.ctx, item.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.Sort = item.Sort
|
||||
if err := l.svcCtx.ServerModel.Update(l.ctx, s, db); err != nil {
|
||||
s.Sort = int(item.Sort)
|
||||
if err = l.svcCtx.NodeModel.UpdateNode(l.ctx, s, db); err != nil {
|
||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()), logger.Field("id", item.Id), logger.Field("sort", item.Sort))
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ResetSortWithServerLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewResetSortWithServerLogic Reset server sort
|
||||
func NewResetSortWithServerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetSortWithServerLogic {
|
||||
return &ResetSortWithServerLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *ResetSortWithServerLogic) ResetSortWithServer(req *types.ResetSortRequest) error {
|
||||
err := l.svcCtx.NodeModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||
// find all servers id
|
||||
var existingIDs []int64
|
||||
db.Model(&node.Server{}).Select("id").Find(&existingIDs)
|
||||
// check if the id is valid
|
||||
validIDMap := make(map[int64]bool)
|
||||
for _, id := range existingIDs {
|
||||
validIDMap[id] = true
|
||||
}
|
||||
// check if the sort is valid
|
||||
var validItems []types.SortItem
|
||||
for _, item := range req.Sort {
|
||||
if validIDMap[item.Id] {
|
||||
validItems = append(validItems, item)
|
||||
}
|
||||
}
|
||||
// query all servers
|
||||
var servers []*node.Server
|
||||
db.Model(&node.Server{}).Order("sort ASC").Find(&servers)
|
||||
// create a map of the current sort
|
||||
currentSortMap := make(map[int64]int64)
|
||||
for _, item := range servers {
|
||||
currentSortMap[item.Id] = int64(item.Sort)
|
||||
}
|
||||
|
||||
// new sort map
|
||||
newSortMap := make(map[int64]int64)
|
||||
for _, item := range validItems {
|
||||
newSortMap[item.Id] = item.Sort
|
||||
}
|
||||
|
||||
var itemsToUpdate []types.SortItem
|
||||
for _, item := range validItems {
|
||||
if oldSort, exists := currentSortMap[item.Id]; exists && oldSort != item.Sort {
|
||||
itemsToUpdate = append(itemsToUpdate, item)
|
||||
}
|
||||
}
|
||||
for _, item := range itemsToUpdate {
|
||||
s, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, item.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.Sort = int(item.Sort)
|
||||
if err = l.svcCtx.NodeModel.UpdateServer(l.ctx, s, db); err != nil {
|
||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()), logger.Field("id", item.Id), logger.Field("sort", item.Sort))
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type ToggleNodeStatusLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewToggleNodeStatusLogic Toggle Node Status
|
||||
func NewToggleNodeStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ToggleNodeStatusLogic {
|
||||
return &ToggleNodeStatusLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *ToggleNodeStatusLogic) ToggleNodeStatus(req *types.ToggleNodeStatusRequest) error {
|
||||
data, err := l.svcCtx.NodeModel.FindOneNode(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[ToggleNodeStatus] Query Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "[ToggleNodeStatus] Query Database Error")
|
||||
}
|
||||
data.Enabled = req.Enable
|
||||
|
||||
err = l.svcCtx.NodeModel.UpdateNode(l.ctx, data)
|
||||
if err != nil {
|
||||
l.Errorw("[ToggleNodeStatus] Update Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "[ToggleNodeStatus] Update Database Error")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type UpdateNodeGroupLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewUpdateNodeGroupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateNodeGroupLogic {
|
||||
return &UpdateNodeGroupLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UpdateNodeGroupLogic) UpdateNodeGroup(req *types.UpdateNodeGroupRequest) error {
|
||||
// check server group exist
|
||||
nodeGroup, err := l.svcCtx.ServerModel.FindOneGroup(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), err.Error())
|
||||
}
|
||||
nodeGroup.Name = req.Name
|
||||
nodeGroup.Description = req.Description
|
||||
err = l.svcCtx.ServerModel.UpdateGroup(l.ctx, nodeGroup)
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -2,12 +2,6 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/server/pkg/device"
|
||||
queue "github.com/perfect-panel/server/queue/types"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
@@ -23,6 +17,7 @@ type UpdateNodeLogic struct {
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewUpdateNodeLogic Update Node
|
||||
func NewUpdateNodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateNodeLogic {
|
||||
return &UpdateNodeLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
@@ -32,108 +27,22 @@ func NewUpdateNodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Update
|
||||
}
|
||||
|
||||
func (l *UpdateNodeLogic) UpdateNode(req *types.UpdateNodeRequest) error {
|
||||
// Check server exist
|
||||
nodeInfo, err := l.svcCtx.ServerModel.FindOne(l.ctx, req.Id)
|
||||
data, err := l.svcCtx.NodeModel.FindOneNode(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find server error: %v", err)
|
||||
l.Errorw("[UpdateNode] Query Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "[UpdateNode] Query Database Error")
|
||||
}
|
||||
tool.DeepCopy(nodeInfo, req, tool.CopyWithIgnoreEmpty(false))
|
||||
config, err := json.Marshal(req.Config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
nodeInfo.Config = string(config)
|
||||
nodeRelay, err := json.Marshal(req.RelayNode)
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateNode] Marshal RelayNode Error: ", logger.Field("error", err.Error()))
|
||||
return err
|
||||
}
|
||||
|
||||
// 处理Tags字段
|
||||
switch {
|
||||
case len(req.Tags) > 0:
|
||||
// 有Tags,进行连接
|
||||
nodeInfo.Tags = strings.Join(req.Tags, ",")
|
||||
default:
|
||||
// 空数组,清空Tags
|
||||
nodeInfo.Tags = ""
|
||||
}
|
||||
|
||||
nodeInfo.City = req.City
|
||||
nodeInfo.Country = req.Country
|
||||
|
||||
nodeInfo.RelayNode = string(nodeRelay)
|
||||
if req.Protocol == "vless" {
|
||||
var cfg types.Vless
|
||||
if err := json.Unmarshal(config, &cfg); err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "json.Unmarshal error: %v", err.Error())
|
||||
}
|
||||
if cfg.Security == "reality" && cfg.SecurityConfig.RealityPublicKey == "" {
|
||||
public, private, err := tool.Curve25519Genkey(false, "")
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "generate curve25519 key error")
|
||||
}
|
||||
cfg.SecurityConfig.RealityPublicKey = public
|
||||
cfg.SecurityConfig.RealityPrivateKey = private
|
||||
cfg.SecurityConfig.RealityShortId = tool.GenerateShortID(private)
|
||||
}
|
||||
if cfg.SecurityConfig.RealityServerAddr == "" {
|
||||
cfg.SecurityConfig.RealityServerAddr = cfg.SecurityConfig.SNI
|
||||
}
|
||||
if cfg.SecurityConfig.RealityServerPort == 0 {
|
||||
cfg.SecurityConfig.RealityServerPort = 443
|
||||
}
|
||||
config, _ = json.Marshal(cfg)
|
||||
nodeInfo.Config = string(config)
|
||||
} else if req.Protocol == "shadowsocks" {
|
||||
var cfg types.Shadowsocks
|
||||
if err = json.Unmarshal(config, &cfg); err != nil {
|
||||
l.Errorf("[CreateNode] Unmarshal Shadowsocks Config Error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "json.Unmarshal error: %v", err.Error())
|
||||
}
|
||||
if strings.Contains(cfg.Method, "2022") {
|
||||
var length int
|
||||
switch cfg.Method {
|
||||
case "2022-blake3-aes-128-gcm":
|
||||
length = 16
|
||||
default:
|
||||
length = 32
|
||||
}
|
||||
if len(cfg.ServerKey) != length {
|
||||
cfg.ServerKey = tool.GenerateCipher(cfg.ServerKey, length)
|
||||
}
|
||||
}
|
||||
config, _ = json.Marshal(cfg)
|
||||
nodeInfo.Config = string(config)
|
||||
}
|
||||
err = l.svcCtx.ServerModel.Update(l.ctx, nodeInfo)
|
||||
data.Name = req.Name
|
||||
data.Tags = tool.StringSliceToString(req.Tags)
|
||||
data.ServerId = req.ServerId
|
||||
data.Port = req.Port
|
||||
data.Address = req.Address
|
||||
data.Protocol = req.Protocol
|
||||
data.Enabled = req.Enabled
|
||||
err = l.svcCtx.NodeModel.UpdateNode(l.ctx, data)
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateNode] Update Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create server error: %v", err)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "[UpdateNode] Update Database Error")
|
||||
}
|
||||
|
||||
if req.City == "" || req.Country == "" {
|
||||
// Marshal the task payload
|
||||
payload, err := json.Marshal(queue.GetNodeCountry{
|
||||
Protocol: nodeInfo.Protocol,
|
||||
ServerAddr: nodeInfo.ServerAddr,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[GetNodeCountry]: Marshal Error", logger.Field("error", err.Error()))
|
||||
return errors.Wrap(xerr.NewErrCode(xerr.ERROR), "Failed to marshal task payload")
|
||||
}
|
||||
// Create a queue task
|
||||
task := asynq.NewTask(queue.ForthwithGetCountry, payload)
|
||||
// Enqueue the task
|
||||
taskInfo, err := l.svcCtx.Queue.Enqueue(task)
|
||||
if err != nil {
|
||||
l.Errorw("[GetNodeCountry]: Enqueue Error", logger.Field("error", err.Error()), logger.Field("payload", string(payload)))
|
||||
return errors.Wrap(xerr.NewErrCode(xerr.ERROR), "Failed to enqueue task")
|
||||
}
|
||||
l.Infow("[GetNodeCountry]: Enqueue Success", logger.Field("taskID", taskInfo.ID), logger.Field("payload", string(payload)))
|
||||
}
|
||||
|
||||
l.svcCtx.DeviceManager.Broadcast(device.SubscribeUpdate)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/server"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type UpdateRuleGroupLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewUpdateRuleGroupLogic Update rule group
|
||||
func NewUpdateRuleGroupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateRuleGroupLogic {
|
||||
return &UpdateRuleGroupLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UpdateRuleGroupLogic) UpdateRuleGroup(req *types.UpdateRuleGroupRequest) error {
|
||||
rs, err := parseAndValidateRules(req.Rules, req.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = l.svcCtx.ServerModel.UpdateRuleGroup(l.ctx, &server.RuleGroup{
|
||||
Id: req.Id,
|
||||
Icon: req.Icon,
|
||||
Type: req.Type,
|
||||
Name: req.Name,
|
||||
Tags: tool.StringSliceToString(req.Tags),
|
||||
Rules: strings.Join(rs, "\n"),
|
||||
Default: req.Default,
|
||||
Enable: req.Enable,
|
||||
})
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||
}
|
||||
if req.Default {
|
||||
if err = l.svcCtx.ServerModel.SetDefaultRuleGroup(l.ctx, req.Id); err != nil {
|
||||
l.Errorf("SetDefaultRuleGroup error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/ip"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type UpdateServerLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewUpdateServerLogic Update Server
|
||||
func NewUpdateServerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateServerLogic {
|
||||
return &UpdateServerLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UpdateServerLogic) UpdateServer(req *types.UpdateServerRequest) error {
|
||||
data, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorf("[UpdateServer] FindOneServer Error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find server error: %v", err.Error())
|
||||
}
|
||||
data.Name = req.Name
|
||||
data.Country = req.Country
|
||||
data.City = req.City
|
||||
data.Ratio = req.Ratio
|
||||
// only update address when it's different
|
||||
if req.Address != data.Address {
|
||||
// query server ip location
|
||||
result, err := ip.GetRegionByIp(req.Address)
|
||||
if err != nil {
|
||||
l.Errorf("[UpdateServer] GetRegionByIp Error: %v", err.Error())
|
||||
} else {
|
||||
data.City = result.City
|
||||
data.Country = result.Country
|
||||
}
|
||||
// update address
|
||||
data.Address = req.Address
|
||||
}
|
||||
protocols := make([]node.Protocol, 0)
|
||||
for _, item := range req.Protocols {
|
||||
if item.Type == "" {
|
||||
return errors.Wrapf(xerr.NewErrCodeMsg(xerr.InvalidParams, "protocols type is empty"), "protocols type is empty")
|
||||
}
|
||||
var protocol node.Protocol
|
||||
tool.DeepCopy(&protocol, item)
|
||||
|
||||
// VLESS Reality Key Generation
|
||||
if protocol.Type == "vless" {
|
||||
if protocol.Security == "reality" {
|
||||
if protocol.RealityPublicKey == "" {
|
||||
public, private, err := tool.Curve25519Genkey(false, "")
|
||||
if err != nil {
|
||||
l.Errorf("[CreateServer] Generate Reality Key Error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "generate reality key error: %v", err)
|
||||
}
|
||||
protocol.RealityPublicKey = public
|
||||
protocol.RealityPrivateKey = private
|
||||
protocol.RealityShortId = tool.GenerateShortID(private)
|
||||
}
|
||||
if protocol.RealityServerAddr == "" {
|
||||
protocol.RealityServerAddr = protocol.SNI
|
||||
}
|
||||
if protocol.RealityServerPort == 0 {
|
||||
protocol.RealityServerPort = 443
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
// ShadowSocks 2022 Key Generation
|
||||
if protocol.Type == "shadowsocks" {
|
||||
if strings.Contains(protocol.Cipher, "2022") {
|
||||
var length int
|
||||
switch protocol.Cipher {
|
||||
case "2022-blake3-aes-128-gcm":
|
||||
length = 16
|
||||
default:
|
||||
length = 32
|
||||
}
|
||||
if len(protocol.ServerKey) != length {
|
||||
protocol.ServerKey = tool.GenerateCipher(protocol.ServerKey, length)
|
||||
}
|
||||
}
|
||||
}
|
||||
protocols = append(protocols, protocol)
|
||||
}
|
||||
err = data.MarshalProtocols(protocols)
|
||||
if err != nil {
|
||||
l.Errorf("[UpdateServer] Marshal Protocols Error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCodeMsg(xerr.InvalidParams, "protocols marshal error"), "protocols marshal error: %v", err)
|
||||
}
|
||||
|
||||
err = l.svcCtx.NodeModel.UpdateServer(l.ctx, data)
|
||||
if err != nil {
|
||||
l.Errorf("[UpdateServer] UpdateServer Error: %v", err.Error())
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update server error: %v", err.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -37,6 +37,7 @@ func (l *CreateSubscribeLogic) CreateSubscribe(req *types.CreateSubscribeRequest
|
||||
sub := &subscribe.Subscribe{
|
||||
Id: 0,
|
||||
Name: req.Name,
|
||||
Language: req.Language,
|
||||
Description: req.Description,
|
||||
UnitPrice: req.UnitPrice,
|
||||
UnitTime: req.UnitTime,
|
||||
@@ -47,9 +48,8 @@ func (l *CreateSubscribeLogic) CreateSubscribe(req *types.CreateSubscribeRequest
|
||||
SpeedLimit: req.SpeedLimit,
|
||||
DeviceLimit: req.DeviceLimit,
|
||||
Quota: req.Quota,
|
||||
GroupId: req.GroupId,
|
||||
ServerGroup: tool.Int64SliceToString(req.ServerGroup),
|
||||
Server: tool.Int64SliceToString(req.Server),
|
||||
Nodes: tool.Int64SliceToString(req.Nodes),
|
||||
NodeTags: tool.StringSliceToString(req.NodeTags),
|
||||
Show: req.Show,
|
||||
Sell: req.Sell,
|
||||
Sort: 0,
|
||||
|
||||
@@ -3,6 +3,7 @@ package subscribe
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
@@ -41,7 +42,7 @@ func (l *GetSubscribeDetailsLogic) GetSubscribeDetails(req *types.GetSubscribeDe
|
||||
l.Logger.Error("[GetSubscribeDetailsLogic] JSON unmarshal failed: ", logger.Field("error", err.Error()), logger.Field("discount", sub.Discount))
|
||||
}
|
||||
}
|
||||
resp.Server = tool.StringToInt64Slice(sub.Server)
|
||||
resp.ServerGroup = tool.StringToInt64Slice(sub.ServerGroup)
|
||||
resp.Nodes = tool.StringToInt64Slice(sub.Nodes)
|
||||
resp.NodeTags = strings.Split(sub.NodeTags, ",")
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@ package subscribe
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -28,7 +30,12 @@ func NewGetSubscribeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *
|
||||
}
|
||||
|
||||
func (l *GetSubscribeListLogic) GetSubscribeList(req *types.GetSubscribeListRequest) (resp *types.GetSubscribeListResponse, err error) {
|
||||
total, list, err := l.svcCtx.SubscribeModel.QuerySubscribeListByPage(l.ctx, int(req.Page), int(req.Size), req.GroupId, req.Search)
|
||||
total, list, err := l.svcCtx.SubscribeModel.FilterList(l.ctx, &subscribe.FilterParams{
|
||||
Page: int(req.Page),
|
||||
Size: int(req.Size),
|
||||
Language: req.Language,
|
||||
Search: req.Search,
|
||||
})
|
||||
if err != nil {
|
||||
l.Logger.Error("[GetSubscribeListLogic] get subscribe list failed: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get subscribe list failed: %v", err.Error())
|
||||
@@ -47,8 +54,8 @@ func (l *GetSubscribeListLogic) GetSubscribeList(req *types.GetSubscribeListRequ
|
||||
l.Logger.Error("[GetSubscribeListLogic] JSON unmarshal failed: ", logger.Field("error", err.Error()), logger.Field("discount", item.Discount))
|
||||
}
|
||||
}
|
||||
sub.Server = tool.StringToInt64Slice(item.Server)
|
||||
sub.ServerGroup = tool.StringToInt64Slice(item.ServerGroup)
|
||||
sub.Nodes = tool.StringToInt64Slice(item.Nodes)
|
||||
sub.NodeTags = strings.Split(item.NodeTags, ",")
|
||||
resultList = append(resultList, sub)
|
||||
}
|
||||
|
||||
@@ -59,8 +66,8 @@ func (l *GetSubscribeListLogic) GetSubscribeList(req *types.GetSubscribeListRequ
|
||||
}
|
||||
|
||||
for i, item := range resultList {
|
||||
if subscribe, ok := subscribeMaps[item.Id]; ok {
|
||||
resultList[i].Sold = subscribe
|
||||
if sub, ok := subscribeMaps[item.Id]; ok {
|
||||
resultList[i].Sold = sub
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package subscribe
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
@@ -40,7 +41,11 @@ func (l *SubscribeSortLogic) SubscribeSort(req *types.SubscribeSortRequest) erro
|
||||
l.Logger.Error("[SubscribeSortLogic] query subscribe list by ids error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe list by ids error: %v", err.Error())
|
||||
}
|
||||
subs, err := l.svcCtx.SubscribeModel.QuerySubscribeListByIds(l.ctx, ids)
|
||||
_, subs, err := l.svcCtx.SubscribeModel.FilterList(l.ctx, &subscribe.FilterParams{
|
||||
Page: 1,
|
||||
Size: 9999,
|
||||
Ids: ids,
|
||||
})
|
||||
if err != nil {
|
||||
l.Logger.Error("[SubscribeSortLogic] query subscribe list by ids error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe list by ids error: %v", err.Error())
|
||||
|
||||
@@ -45,6 +45,7 @@ func (l *UpdateSubscribeLogic) UpdateSubscribe(req *types.UpdateSubscribeRequest
|
||||
sub := &subscribe.Subscribe{
|
||||
Id: req.Id,
|
||||
Name: req.Name,
|
||||
Language: req.Language,
|
||||
Description: req.Description,
|
||||
UnitPrice: req.UnitPrice,
|
||||
UnitTime: req.UnitTime,
|
||||
@@ -55,9 +56,8 @@ func (l *UpdateSubscribeLogic) UpdateSubscribe(req *types.UpdateSubscribeRequest
|
||||
SpeedLimit: req.SpeedLimit,
|
||||
DeviceLimit: req.DeviceLimit,
|
||||
Quota: req.Quota,
|
||||
GroupId: req.GroupId,
|
||||
ServerGroup: tool.Int64SliceToString(req.ServerGroup),
|
||||
Server: tool.Int64SliceToString(req.Server),
|
||||
Nodes: tool.Int64SliceToString(req.Nodes),
|
||||
NodeTags: tool.StringSliceToString(req.NodeTags),
|
||||
Show: req.Show,
|
||||
Sell: req.Sell,
|
||||
Sort: req.Sort,
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/application"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type CreateApplicationLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewCreateApplicationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateApplicationLogic {
|
||||
return &CreateApplicationLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *CreateApplicationLogic) CreateApplication(req *types.CreateApplicationRequest) error {
|
||||
var ios []application.ApplicationVersion
|
||||
if len(req.Platform.IOS) > 0 {
|
||||
for _, ios_ := range req.Platform.IOS {
|
||||
ios = append(ios, application.ApplicationVersion{
|
||||
Url: ios_.Url,
|
||||
Version: ios_.Version,
|
||||
Platform: "ios",
|
||||
IsDefault: ios_.IsDefault,
|
||||
Description: ios_.Description,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var mac []application.ApplicationVersion
|
||||
if len(req.Platform.MacOS) > 0 {
|
||||
for _, mac_ := range req.Platform.MacOS {
|
||||
mac = append(mac, application.ApplicationVersion{
|
||||
Url: mac_.Url,
|
||||
Version: mac_.Version,
|
||||
Platform: "macos",
|
||||
IsDefault: mac_.IsDefault,
|
||||
Description: mac_.Description,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var linux []application.ApplicationVersion
|
||||
if len(req.Platform.Linux) > 0 {
|
||||
for _, linux_ := range req.Platform.Linux {
|
||||
linux = append(linux, application.ApplicationVersion{
|
||||
Url: linux_.Url,
|
||||
Version: linux_.Version,
|
||||
Platform: "linux",
|
||||
IsDefault: linux_.IsDefault,
|
||||
Description: linux_.Description,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var android []application.ApplicationVersion
|
||||
if len(req.Platform.Android) > 0 {
|
||||
for _, android_ := range req.Platform.Android {
|
||||
android = append(android, application.ApplicationVersion{
|
||||
Url: android_.Url,
|
||||
Version: android_.Version,
|
||||
Platform: "android",
|
||||
IsDefault: android_.IsDefault,
|
||||
Description: android_.Description,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var windows []application.ApplicationVersion
|
||||
if len(req.Platform.Windows) > 0 {
|
||||
for _, windows_ := range req.Platform.Windows {
|
||||
windows = append(windows, application.ApplicationVersion{
|
||||
Url: windows_.Url,
|
||||
Version: windows_.Version,
|
||||
Platform: "windows",
|
||||
IsDefault: windows_.IsDefault,
|
||||
Description: windows_.Description,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var harmony []application.ApplicationVersion
|
||||
if len(req.Platform.Harmony) > 0 {
|
||||
for _, harmony_ := range req.Platform.Harmony {
|
||||
harmony = append(harmony, application.ApplicationVersion{
|
||||
Url: harmony_.Url,
|
||||
Version: harmony_.Version,
|
||||
Platform: "harmony",
|
||||
IsDefault: harmony_.IsDefault,
|
||||
Description: harmony_.Description,
|
||||
})
|
||||
}
|
||||
}
|
||||
var applicationVersions []application.ApplicationVersion
|
||||
applicationVersions = append(applicationVersions, ios...)
|
||||
applicationVersions = append(applicationVersions, mac...)
|
||||
applicationVersions = append(applicationVersions, linux...)
|
||||
applicationVersions = append(applicationVersions, android...)
|
||||
applicationVersions = append(applicationVersions, windows...)
|
||||
applicationVersions = append(applicationVersions, harmony...)
|
||||
app := application.Application{
|
||||
Name: req.Name,
|
||||
Icon: req.Icon,
|
||||
SubscribeType: req.SubscribeType,
|
||||
ApplicationVersions: applicationVersions,
|
||||
}
|
||||
err := l.svcCtx.ApplicationModel.Insert(l.ctx, &app)
|
||||
if err != nil {
|
||||
l.Errorw("[CreateApplicationLogic] create application error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create application error: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/application"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type CreateApplicationVersionLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Create application version
|
||||
func NewCreateApplicationVersionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateApplicationVersionLogic {
|
||||
return &CreateApplicationVersionLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *CreateApplicationVersionLogic) CreateApplicationVersion(req *types.CreateApplicationVersionRequest) error {
|
||||
create := &application.ApplicationVersion{
|
||||
Url: req.Url,
|
||||
Platform: req.Platform,
|
||||
Version: req.Version,
|
||||
Description: req.Description,
|
||||
IsDefault: req.IsDefault,
|
||||
ApplicationId: req.ApplicationId,
|
||||
}
|
||||
err := l.svcCtx.ApplicationModel.InsertVersion(l.ctx, create)
|
||||
if err != nil {
|
||||
l.Errorw("[CreateApplicationVersion] create application version error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create application version error: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type DeleteApplicationLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewDeleteApplicationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteApplicationLogic {
|
||||
return &DeleteApplicationLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DeleteApplicationLogic) DeleteApplication(req *types.DeleteApplicationRequest) error {
|
||||
// delete application
|
||||
err := l.svcCtx.ApplicationModel.Delete(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[DeleteApplicationLogic] delete application error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete application error: %v", err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type DeleteApplicationVersionLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Delete application
|
||||
func NewDeleteApplicationVersionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteApplicationVersionLogic {
|
||||
return &DeleteApplicationVersionLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DeleteApplicationVersionLogic) DeleteApplicationVersion(req *types.DeleteApplicationVersionRequest) error {
|
||||
// delete application
|
||||
err := l.svcCtx.ApplicationModel.DeleteVersion(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[DeleteApplicationVersion] delete application version error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete application version error: %v", err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type GetApplicationConfigLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// get application config
|
||||
func NewGetApplicationConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApplicationConfigLogic {
|
||||
return &GetApplicationConfigLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetApplicationConfigLogic) GetApplicationConfig() (resp *types.ApplicationConfig, err error) {
|
||||
resp = &types.ApplicationConfig{}
|
||||
appConfig, err := l.svcCtx.ApplicationModel.FindOneConfig(l.ctx, 1)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
l.Errorw("[GetApplicationConfig] Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get app config error: %v", err.Error())
|
||||
}
|
||||
resp.AppId = appConfig.AppId
|
||||
resp.EncryptionKey = appConfig.EncryptionKey
|
||||
resp.EncryptionMethod = appConfig.EncryptionMethod
|
||||
resp.Domains = strings.Split(appConfig.Domains, ";")
|
||||
resp.StartupPicture = appConfig.StartupPicture
|
||||
resp.StartupPictureSkipTime = appConfig.StartupPictureSkipTime
|
||||
return
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/application"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type GetApplicationLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get application
|
||||
func NewGetApplicationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApplicationLogic {
|
||||
return &GetApplicationLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetApplicationLogic) GetApplication() (resp *types.ApplicationResponse, err error) {
|
||||
resp = &types.ApplicationResponse{}
|
||||
var applications []*application.Application
|
||||
err = l.svcCtx.ApplicationModel.Transaction(l.ctx, func(tx *gorm.DB) (err error) {
|
||||
return tx.Model(applications).Preload("ApplicationVersions").Find(&applications).Error
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[GetApplicationLogic] get application error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get application error: %v", err.Error())
|
||||
}
|
||||
|
||||
if len(applications) == 0 {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
for _, app := range applications {
|
||||
applicationResponse := types.ApplicationResponseInfo{
|
||||
Id: app.Id,
|
||||
Name: app.Name,
|
||||
Icon: app.Icon,
|
||||
Description: app.Description,
|
||||
SubscribeType: app.SubscribeType,
|
||||
}
|
||||
applicationVersions := app.ApplicationVersions
|
||||
if len(applicationVersions) != 0 {
|
||||
for _, applicationVersion := range applicationVersions {
|
||||
switch applicationVersion.Platform {
|
||||
case "ios":
|
||||
applicationResponse.Platform.IOS = append(applicationResponse.Platform.IOS, &types.ApplicationVersion{
|
||||
Id: applicationVersion.Id,
|
||||
Url: applicationVersion.Url,
|
||||
Version: applicationVersion.Version,
|
||||
IsDefault: applicationVersion.IsDefault,
|
||||
Description: applicationVersion.Description,
|
||||
})
|
||||
case "macos":
|
||||
applicationResponse.Platform.MacOS = append(applicationResponse.Platform.MacOS, &types.ApplicationVersion{
|
||||
Id: applicationVersion.Id,
|
||||
Url: applicationVersion.Url,
|
||||
Version: applicationVersion.Version,
|
||||
IsDefault: applicationVersion.IsDefault,
|
||||
Description: applicationVersion.Description,
|
||||
})
|
||||
case "linux":
|
||||
applicationResponse.Platform.Linux = append(applicationResponse.Platform.Linux, &types.ApplicationVersion{
|
||||
Id: applicationVersion.Id,
|
||||
Url: applicationVersion.Url,
|
||||
Version: applicationVersion.Version,
|
||||
IsDefault: applicationVersion.IsDefault,
|
||||
Description: applicationVersion.Description,
|
||||
})
|
||||
case "android":
|
||||
applicationResponse.Platform.Android = append(applicationResponse.Platform.Android, &types.ApplicationVersion{
|
||||
Id: applicationVersion.Id,
|
||||
Url: applicationVersion.Url,
|
||||
Version: applicationVersion.Version,
|
||||
IsDefault: applicationVersion.IsDefault,
|
||||
Description: applicationVersion.Description,
|
||||
})
|
||||
case "windows":
|
||||
applicationResponse.Platform.Windows = append(applicationResponse.Platform.Windows, &types.ApplicationVersion{
|
||||
Id: applicationVersion.Id,
|
||||
Url: applicationVersion.Url,
|
||||
Version: applicationVersion.Version,
|
||||
IsDefault: applicationVersion.IsDefault,
|
||||
Description: applicationVersion.Description,
|
||||
})
|
||||
case "harmony":
|
||||
applicationResponse.Platform.Harmony = append(applicationResponse.Platform.Harmony, &types.ApplicationVersion{
|
||||
Id: applicationVersion.Id,
|
||||
Url: applicationVersion.Url,
|
||||
Version: applicationVersion.Version,
|
||||
IsDefault: applicationVersion.IsDefault,
|
||||
Description: applicationVersion.Description,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
resp.Applications = append(resp.Applications, applicationResponse)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/subscribeType"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetSubscribeTypeLogic struct {
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
logger.Logger
|
||||
}
|
||||
|
||||
func NewGetSubscribeTypeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSubscribeTypeLogic {
|
||||
return &GetSubscribeTypeLogic{
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
Logger: logger.WithContext(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetSubscribeTypeLogic) GetSubscribeType() (resp *types.SubscribeType, err error) {
|
||||
var list []*subscribeType.SubscribeType
|
||||
err = l.svcCtx.DB.Model(&subscribeType.SubscribeType{}).Find(&list).Error
|
||||
if err != nil {
|
||||
l.Errorw("[GetSubscribeType] get subscribe type failed", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get subscribe type failed: %v", err)
|
||||
}
|
||||
typeList := make([]string, 0)
|
||||
for _, item := range list {
|
||||
typeList = append(typeList, item.Name)
|
||||
}
|
||||
return &types.SubscribeType{
|
||||
SubscribeTypes: typeList,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/application"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type UpdateApplicationConfigLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// update application config
|
||||
func NewUpdateApplicationConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateApplicationConfigLogic {
|
||||
return &UpdateApplicationConfigLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UpdateApplicationConfigLogic) UpdateApplicationConfig(req *types.ApplicationConfig) error {
|
||||
err := l.svcCtx.ApplicationModel.UpdateConfig(l.ctx, &application.ApplicationConfig{
|
||||
Id: 1,
|
||||
AppId: req.AppId,
|
||||
EncryptionKey: req.EncryptionKey,
|
||||
EncryptionMethod: req.EncryptionMethod,
|
||||
Domains: strings.Join(req.Domains, ";"),
|
||||
StartupPicture: req.StartupPicture,
|
||||
StartupPictureSkipTime: req.StartupPictureSkipTime,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateApplicationConfig] Database Error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update app config error: %v", err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/application"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
)
|
||||
|
||||
type UpdateApplicationLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewUpdateApplicationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateApplicationLogic {
|
||||
return &UpdateApplicationLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UpdateApplicationLogic) UpdateApplication(req *types.UpdateApplicationRequest) error {
|
||||
|
||||
// find application
|
||||
app, err := l.svcCtx.ApplicationModel.FindOne(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateApplication] find application error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find application error: %v", err.Error())
|
||||
}
|
||||
app.Name = req.Name
|
||||
app.Icon = req.Icon
|
||||
app.SubscribeType = req.SubscribeType
|
||||
app.Description = req.Description
|
||||
|
||||
var ios []application.ApplicationVersion
|
||||
if len(req.Platform.IOS) > 0 {
|
||||
for _, ios_ := range req.Platform.IOS {
|
||||
ios = append(ios, application.ApplicationVersion{
|
||||
Url: ios_.Url,
|
||||
Version: ios_.Version,
|
||||
Platform: "ios",
|
||||
IsDefault: ios_.IsDefault,
|
||||
Description: ios_.Description,
|
||||
ApplicationId: app.Id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var mac []application.ApplicationVersion
|
||||
if len(req.Platform.MacOS) > 0 {
|
||||
for _, mac_ := range req.Platform.MacOS {
|
||||
mac = append(mac, application.ApplicationVersion{
|
||||
Url: mac_.Url,
|
||||
Version: mac_.Version,
|
||||
Platform: "macos",
|
||||
IsDefault: mac_.IsDefault,
|
||||
Description: mac_.Description,
|
||||
ApplicationId: app.Id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var linux []application.ApplicationVersion
|
||||
if len(req.Platform.Linux) > 0 {
|
||||
for _, linux_ := range req.Platform.Linux {
|
||||
linux = append(linux, application.ApplicationVersion{
|
||||
Url: linux_.Url,
|
||||
Version: linux_.Version,
|
||||
Platform: "linux",
|
||||
IsDefault: linux_.IsDefault,
|
||||
Description: linux_.Description,
|
||||
ApplicationId: app.Id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var android []application.ApplicationVersion
|
||||
if len(req.Platform.Android) > 0 {
|
||||
for _, android_ := range req.Platform.Android {
|
||||
android = append(android, application.ApplicationVersion{
|
||||
Url: android_.Url,
|
||||
Version: android_.Version,
|
||||
Platform: "android",
|
||||
IsDefault: android_.IsDefault,
|
||||
Description: android_.Description,
|
||||
ApplicationId: app.Id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var windows []application.ApplicationVersion
|
||||
if len(req.Platform.Windows) > 0 {
|
||||
for _, windows_ := range req.Platform.Windows {
|
||||
windows = append(windows, application.ApplicationVersion{
|
||||
Url: windows_.Url,
|
||||
Version: windows_.Version,
|
||||
Platform: "windows",
|
||||
IsDefault: windows_.IsDefault,
|
||||
Description: windows_.Description,
|
||||
ApplicationId: app.Id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var harmony []application.ApplicationVersion
|
||||
if len(req.Platform.Harmony) > 0 {
|
||||
for _, harmony_ := range req.Platform.Harmony {
|
||||
harmony = append(harmony, application.ApplicationVersion{
|
||||
Url: harmony_.Url,
|
||||
Version: harmony_.Version,
|
||||
Platform: "harmony",
|
||||
IsDefault: harmony_.IsDefault,
|
||||
Description: harmony_.Description,
|
||||
ApplicationId: app.Id,
|
||||
})
|
||||
}
|
||||
}
|
||||
var applicationVersions []application.ApplicationVersion
|
||||
applicationVersions = append(applicationVersions, ios...)
|
||||
applicationVersions = append(applicationVersions, mac...)
|
||||
applicationVersions = append(applicationVersions, linux...)
|
||||
applicationVersions = append(applicationVersions, android...)
|
||||
applicationVersions = append(applicationVersions, windows...)
|
||||
applicationVersions = append(applicationVersions, harmony...)
|
||||
app.ApplicationVersions = applicationVersions
|
||||
err = l.svcCtx.ApplicationModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||
|
||||
if err = db.Where("application_id = ?", app.Id).Delete(&application.ApplicationVersion{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err = db.Create(&applicationVersions).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Save(app).Error
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateApplication] update application error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update application error: %v", err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type UpdateApplicationVersionLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Update application version
|
||||
func NewUpdateApplicationVersionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateApplicationVersionLogic {
|
||||
return &UpdateApplicationVersionLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UpdateApplicationVersionLogic) UpdateApplicationVersion(req *types.UpdateApplicationVersionRequest) error {
|
||||
// find application
|
||||
app, err := l.svcCtx.ApplicationModel.FindOneVersion(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateApplicationVersion] find application version error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find application error: %v", err.Error())
|
||||
}
|
||||
app.Url = req.Url
|
||||
app.Version = req.Version
|
||||
app.Description = req.Description
|
||||
app.IsDefault = req.IsDefault
|
||||
err = l.svcCtx.ApplicationModel.UpdateVersion(l.ctx, app)
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateApplicationVersion] update application version error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update application version error: %v", err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -39,10 +39,12 @@ func (l *CreateUserLogic) CreateUser(req *types.CreateUserRequest) error {
|
||||
}
|
||||
pwd := tool.EncodePassWord(req.Password)
|
||||
newUser := &user.User{
|
||||
Password: pwd,
|
||||
ReferCode: req.ReferCode,
|
||||
Balance: req.Balance,
|
||||
IsAdmin: &req.IsAdmin,
|
||||
Password: pwd,
|
||||
ReferralPercentage: req.ReferralPercentage,
|
||||
OnlyFirstPurchase: &req.OnlyFirstPurchase,
|
||||
ReferCode: req.ReferCode,
|
||||
Balance: req.Balance,
|
||||
IsAdmin: &req.IsAdmin,
|
||||
}
|
||||
var ams []user.AuthMethods
|
||||
|
||||
|
||||
@@ -41,20 +41,20 @@ func (l *GetUserListLogic) GetUserList(req *types.GetUserListRequest) (*types.Ge
|
||||
userRespList := make([]types.User, 0, len(list))
|
||||
|
||||
for _, item := range list {
|
||||
var user types.User
|
||||
tool.DeepCopy(&user, item)
|
||||
var u types.User
|
||||
tool.DeepCopy(&u, item)
|
||||
|
||||
// 处理 AuthMethods
|
||||
authMethods := make([]types.UserAuthMethod, len(user.AuthMethods)) // 直接创建目标 slice
|
||||
for i, method := range user.AuthMethods {
|
||||
authMethods := make([]types.UserAuthMethod, len(u.AuthMethods)) // 直接创建目标 slice
|
||||
for i, method := range u.AuthMethods {
|
||||
tool.DeepCopy(&authMethods[i], method)
|
||||
if method.AuthType == "mobile" {
|
||||
authMethods[i].AuthIdentifier = phone.FormatToInternational(method.AuthIdentifier)
|
||||
}
|
||||
}
|
||||
user.AuthMethods = authMethods
|
||||
u.AuthMethods = authMethods
|
||||
|
||||
userRespList = append(userRespList, user)
|
||||
userRespList = append(userRespList, u)
|
||||
}
|
||||
|
||||
return &types.GetUserListResponse{
|
||||
|
||||
@@ -3,11 +3,10 @@ package user
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
@@ -28,15 +27,34 @@ func NewGetUserLoginLogsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *
|
||||
}
|
||||
|
||||
func (l *GetUserLoginLogsLogic) GetUserLoginLogs(req *types.GetUserLoginLogsRequest) (resp *types.GetUserLoginLogsResponse, err error) {
|
||||
data, total, err := l.svcCtx.UserModel.FilterLoginLogList(l.ctx, req.Page, req.Size, &user.LoginLogFilterParams{
|
||||
UserId: req.UserId,
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeLogin.Uint8(),
|
||||
ObjectID: req.UserId,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[GetUserLoginLogs] get user login logs failed", logger.Field("error", err.Error()), logger.Field("request", req))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get user login logs failed: %v", err.Error())
|
||||
}
|
||||
var list []types.UserLoginLog
|
||||
tool.DeepCopy(&list, data)
|
||||
|
||||
for _, datum := range data {
|
||||
var content log.Login
|
||||
if err = content.Unmarshal([]byte(datum.Content)); err != nil {
|
||||
l.Errorf("[GetUserLoginLogs] unmarshal login log content failed: %v", err.Error())
|
||||
continue
|
||||
}
|
||||
list = append(list, types.UserLoginLog{
|
||||
Id: datum.Id,
|
||||
UserId: datum.ObjectID,
|
||||
LoginIP: content.LoginIP,
|
||||
UserAgent: content.UserAgent,
|
||||
Success: content.Success,
|
||||
Timestamp: datum.CreatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
return &types.GetUserLoginLogsResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
|
||||
@@ -3,7 +3,7 @@ package user
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -28,10 +28,7 @@ func NewGetUserSubscribeLogsLogic(ctx context.Context, svcCtx *svc.ServiceContex
|
||||
}
|
||||
|
||||
func (l *GetUserSubscribeLogsLogic) GetUserSubscribeLogs(req *types.GetUserSubscribeLogsRequest) (resp *types.GetUserSubscribeLogsResponse, err error) {
|
||||
data, total, err := l.svcCtx.UserModel.FilterSubscribeLogList(l.ctx, req.Page, req.Size, &user.SubscribeLogFilterParams{
|
||||
UserSubscribeId: req.SubscribeId,
|
||||
UserId: req.UserId,
|
||||
})
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{})
|
||||
|
||||
if err != nil {
|
||||
l.Errorw("[GetUserSubscribeLogs] Get User Subscribe Logs Error:", logger.Field("err", err.Error()))
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetUserSubscribeResetTrafficLogsLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get user subcribe reset traffic logs
|
||||
func NewGetUserSubscribeResetTrafficLogsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserSubscribeResetTrafficLogsLogic {
|
||||
return &GetUserSubscribeResetTrafficLogsLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetUserSubscribeResetTrafficLogsLogic) GetUserSubscribeResetTrafficLogs(req *types.GetUserSubscribeResetTrafficLogsRequest) (resp *types.GetUserSubscribeResetTrafficLogsResponse, err error) {
|
||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &log.FilterParams{
|
||||
Page: req.Page,
|
||||
Size: req.Size,
|
||||
Type: log.TypeResetSubscribe.Uint8(),
|
||||
ObjectID: req.UserSubscribeId,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorf("[ResetSubscribeTrafficLog] failed to filter system log: %v", err)
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FilterSystemLog failed, err: %v", err)
|
||||
}
|
||||
|
||||
var list []types.ResetSubscribeTrafficLog
|
||||
|
||||
for _, item := range data {
|
||||
var content log.ResetSubscribe
|
||||
if err = content.Unmarshal([]byte(item.Content)); err != nil {
|
||||
l.Errorf("[ResetSubscribeTrafficLog] failed to unmarshal log: %v", err)
|
||||
continue
|
||||
}
|
||||
list = append(list, types.ResetSubscribeTrafficLog{
|
||||
Id: item.Id,
|
||||
Type: content.Type,
|
||||
OrderNo: content.OrderNo,
|
||||
Timestamp: content.Timestamp,
|
||||
UserSubscribeId: item.ObjectID,
|
||||
})
|
||||
}
|
||||
|
||||
return &types.GetUserSubscribeResetTrafficLogsResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -37,13 +39,90 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
||||
|
||||
isDemo := strings.ToLower(os.Getenv("PPANEL_MODE")) == "demo"
|
||||
|
||||
tool.DeepCopy(userInfo, req)
|
||||
if req.Avatar != "" && !tool.IsValidImageSize(req.Avatar, 1024) {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Invalid Image Size")
|
||||
}
|
||||
userInfo.Balance = req.Balance
|
||||
userInfo.GiftAmount = req.GiftAmount
|
||||
userInfo.Commission = req.Commission
|
||||
|
||||
if userInfo.Balance != req.Balance {
|
||||
change := req.Balance - userInfo.Balance
|
||||
balanceLog := log.Balance{
|
||||
Type: log.BalanceTypeAdjust,
|
||||
Amount: change,
|
||||
OrderNo: "",
|
||||
Balance: req.Balance,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
content, _ := balanceLog.Marshal()
|
||||
|
||||
err = l.svcCtx.LogModel.Insert(l.ctx, &log.SystemLog{
|
||||
Type: log.TypeBalance.Uint8(),
|
||||
Date: time.Now().Format(time.DateOnly),
|
||||
ObjectID: userInfo.Id,
|
||||
Content: string(content),
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateUserBasicInfoLogic] Insert Balance Log Error:", logger.Field("err", err.Error()), logger.Field("userId", req.UserId))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "Insert Balance Log Error")
|
||||
}
|
||||
userInfo.Balance = req.Balance
|
||||
}
|
||||
|
||||
if userInfo.GiftAmount != req.GiftAmount {
|
||||
change := req.GiftAmount - userInfo.GiftAmount
|
||||
if change != 0 {
|
||||
var changeType uint16
|
||||
if userInfo.GiftAmount < req.GiftAmount {
|
||||
changeType = log.GiftTypeIncrease
|
||||
} else {
|
||||
changeType = log.GiftTypeReduce
|
||||
}
|
||||
giftLog := log.Gift{
|
||||
Type: changeType,
|
||||
Amount: change,
|
||||
Balance: req.GiftAmount,
|
||||
Remark: "Admin adjustment",
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
content, _ := giftLog.Marshal()
|
||||
// Add gift amount change log
|
||||
err = l.svcCtx.LogModel.Insert(l.ctx, &log.SystemLog{
|
||||
Type: log.TypeGift.Uint8(),
|
||||
Date: time.Now().Format(time.DateOnly),
|
||||
ObjectID: userInfo.Id,
|
||||
Content: string(content),
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateUserBasicInfoLogic] Insert Balance Log Error:", logger.Field("err", err.Error()), logger.Field("userId", req.UserId))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "Insert Balance Log Error")
|
||||
}
|
||||
userInfo.GiftAmount = req.GiftAmount
|
||||
}
|
||||
}
|
||||
|
||||
if req.Commission != userInfo.Commission {
|
||||
|
||||
commentLog := log.Commission{
|
||||
Type: log.CommissionTypeAdjust,
|
||||
Amount: req.Commission - userInfo.Commission,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
|
||||
content, _ := commentLog.Marshal()
|
||||
err = l.svcCtx.LogModel.Insert(l.ctx, &log.SystemLog{
|
||||
Type: log.TypeCommission.Uint8(),
|
||||
Date: time.Now().Format(time.DateOnly),
|
||||
ObjectID: userInfo.Id,
|
||||
Content: string(content),
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateUserBasicInfoLogic] Insert Commission Log Error:", logger.Field("err", err.Error()), logger.Field("userId", req.UserId))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "Insert Commission Log Error")
|
||||
}
|
||||
userInfo.Commission = req.Commission
|
||||
}
|
||||
tool.DeepCopy(userInfo, req)
|
||||
userInfo.OnlyFirstPurchase = &req.OnlyFirstPurchase
|
||||
userInfo.ReferralPercentage = req.ReferralPercentage
|
||||
|
||||
if req.Password != "" {
|
||||
if userInfo.Id == 2 && isDemo {
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
package announcement
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/announcement"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type QueryAnnouncementLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewQueryAnnouncementLogic Query announcement
|
||||
func NewQueryAnnouncementLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryAnnouncementLogic {
|
||||
return &QueryAnnouncementLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryAnnouncementLogic) QueryAnnouncement(req *types.QueryAnnouncementRequest) (resp *types.QueryAnnouncementResponse, err error) {
|
||||
enable := true
|
||||
total, list, err := l.svcCtx.AnnouncementModel.GetAnnouncementListByPage(l.ctx, req.Page, req.Size, announcement.Filter{
|
||||
Show: &enable,
|
||||
Pinned: req.Pinned,
|
||||
Popup: req.Popup,
|
||||
})
|
||||
if err != nil {
|
||||
l.Error("[QueryAnnouncementLogic] GetAnnouncementListByPage error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetAnnouncementListByPage error: %v", err.Error())
|
||||
}
|
||||
resp = &types.QueryAnnouncementResponse{}
|
||||
resp.Total = total
|
||||
resp.List = make([]types.Announcement, 0)
|
||||
tool.DeepCopy(&resp.List, list)
|
||||
return
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type CheckLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Check Account
|
||||
func NewCheckLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckLogic {
|
||||
return &CheckLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *CheckLogic) Check(req *types.AppAuthCheckRequest) (resp *types.AppAuthCheckResponse, err error) {
|
||||
resp = &types.AppAuthCheckResponse{}
|
||||
_, err = findUserByMethod(l.ctx, l.svcCtx, req.Method, req.Identifier, req.Account, req.AreaCode)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
resp.Status = false
|
||||
return resp, nil
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
resp.Status = true
|
||||
return
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/authmethod"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/phone"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func findUserByMethod(ctx context.Context, svcCtx *svc.ServiceContext, method, identifier, account, areaCode string) (userInfo *user.User, err error) {
|
||||
var authMethods *user.AuthMethods
|
||||
switch method {
|
||||
case authmethod.Email:
|
||||
authMethods, err = svcCtx.UserModel.FindUserAuthMethodByOpenID(ctx, authmethod.Email, account)
|
||||
case authmethod.Mobile:
|
||||
phoneNumber, err := phone.FormatToE164(areaCode, account)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TelephoneError), "Invalid phone number")
|
||||
}
|
||||
authMethods, err = svcCtx.UserModel.FindUserAuthMethodByOpenID(ctx, authmethod.Mobile, phoneNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case authmethod.Device:
|
||||
userDevice, err := svcCtx.UserModel.FindOneDeviceByIdentifier(ctx, identifier)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user device imei error")
|
||||
}
|
||||
return svcCtx.UserModel.FindOne(ctx, userDevice.UserId)
|
||||
default:
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "unknown method")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return svcCtx.UserModel.FindOne(ctx, authMethods.UserId)
|
||||
}
|
||||
|
||||
func existError(method string) error {
|
||||
switch method {
|
||||
case authmethod.Email:
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.EmailExist), "")
|
||||
case authmethod.Mobile:
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.TelephoneExist), "")
|
||||
case authmethod.Device:
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DeviceExist), "")
|
||||
default:
|
||||
return errors.New("unknown method")
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/application"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type GetAppConfigLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// GetAppConfig
|
||||
func NewGetAppConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAppConfigLogic {
|
||||
return &GetAppConfigLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetAppConfigLogic) GetAppConfig(req *types.AppConfigRequest) (resp *types.AppConfigResponse, err error) {
|
||||
resp = &types.AppConfigResponse{}
|
||||
systems, err := l.svcCtx.SystemModel.GetSiteConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Errorw("[QueryApplicationConfig] GetSiteConfig error: ", logger.Field("error", err.Error()))
|
||||
}
|
||||
for _, sysVal := range systems {
|
||||
if sysVal.Key == "CustomData" {
|
||||
jsonStr := strings.ReplaceAll(sysVal.Value, "\\", "")
|
||||
customData := make(map[string]interface{})
|
||||
if err = json.Unmarshal([]byte(jsonStr), &customData); err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
website := customData["website"]
|
||||
if website != nil {
|
||||
resp.OfficialWebsite = fmt.Sprintf("%v", website)
|
||||
}
|
||||
|
||||
contacts := customData["contacts"]
|
||||
if contacts != nil {
|
||||
contactsJson, err := json.Marshal(contacts)
|
||||
if err == nil {
|
||||
contactsMap := make(map[string]string)
|
||||
err = json.Unmarshal(contactsJson, &contactsMap)
|
||||
if err == nil {
|
||||
resp.OfficialEmail = fmt.Sprintf("%v", contactsMap["email"])
|
||||
resp.OfficialTelegram = fmt.Sprintf("%v", contactsMap["telegram"])
|
||||
resp.OfficialTelephone = fmt.Sprintf("%v", contactsMap["telephone"])
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
var applications []*application.Application
|
||||
err = l.svcCtx.ApplicationModel.Transaction(l.ctx, func(tx *gorm.DB) (err error) {
|
||||
return tx.Model(applications).Preload("ApplicationVersions").Find(&applications).Error
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[QueryApplicationConfig] get application error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get application error: %v", err.Error())
|
||||
}
|
||||
|
||||
if len(applications) == 0 {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
isOk := false
|
||||
for _, app := range applications {
|
||||
if isOk {
|
||||
break
|
||||
}
|
||||
resp.Application.Name = app.Name
|
||||
resp.Application.Description = app.Description
|
||||
applicationVersions := app.ApplicationVersions
|
||||
if len(applicationVersions) != 0 {
|
||||
for _, applicationVersion := range applicationVersions {
|
||||
if applicationVersion.Platform == req.UserAgent {
|
||||
resp.Application.Id = applicationVersion.ApplicationId
|
||||
resp.Application.Url = applicationVersion.Url
|
||||
resp.Application.Version = applicationVersion.Version
|
||||
resp.Application.VersionDescription = applicationVersion.Description
|
||||
resp.Application.IsDefault = applicationVersion.IsDefault
|
||||
isOk = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
configs, err := l.svcCtx.ApplicationModel.FindOneConfig(l.ctx, 1)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Logger.Error("[GetAppInfo] FindOneAppConfig error: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetAppInfo FindOneAppConfig error: %v", err.Error())
|
||||
}
|
||||
resp.EncryptionKey = configs.EncryptionKey
|
||||
resp.EncryptionMethod = configs.EncryptionMethod
|
||||
resp.Domains = strings.Split(configs.Domains, ";")
|
||||
resp.StartupPicture = configs.StartupPicture
|
||||
resp.StartupPictureSkipTime = configs.StartupPictureSkipTime
|
||||
resp.InvitationLink = configs.InvitationLink
|
||||
resp.KrWebsiteId = configs.KrWebsiteId
|
||||
return
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/authmethod"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/phone"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/logic/common"
|
||||
"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/jwt"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/uuidx"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type LoginLogic struct {
|
||||
logger.Logger
|
||||
ctx *gin.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Login
|
||||
func NewLoginLogic(ctx *gin.Context, svcCtx *svc.ServiceContext) *LoginLogic {
|
||||
return &LoginLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *LoginLogic) Login(req *types.AppAuthRequest) (resp *types.AppAuthRespone, err error) {
|
||||
|
||||
loginStatus := false
|
||||
var userInfo *user.User
|
||||
// Record login status
|
||||
defer func(svcCtx *svc.ServiceContext) {
|
||||
if userInfo != nil && userInfo.Id != 0 {
|
||||
if err := svcCtx.UserModel.InsertLoginLog(l.ctx, &user.LoginLog{
|
||||
UserId: userInfo.Id,
|
||||
LoginIP: l.ctx.ClientIP(),
|
||||
UserAgent: l.ctx.Request.UserAgent(),
|
||||
Success: &loginStatus,
|
||||
}); err != nil {
|
||||
l.Errorw("InsertLoginLog Error", logger.Field("error", err.Error()))
|
||||
}
|
||||
}
|
||||
}(l.svcCtx)
|
||||
|
||||
resp = &types.AppAuthRespone{}
|
||||
//query user
|
||||
userInfo, err = findUserByMethod(l.ctx, l.svcCtx, req.Method, req.Identifier, req.Account, req.AreaCode)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserPasswordError), "user password")
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
switch req.Method {
|
||||
case authmethod.Email:
|
||||
|
||||
if !l.svcCtx.Config.Email.Enable {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.EmailNotEnabled), "Email function is not enabled yet")
|
||||
}
|
||||
|
||||
if req.Code != "" {
|
||||
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeCacheKey, constant.Security.String(), req.Account)
|
||||
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err != nil {
|
||||
l.Errorw("Redis Error", logger.Field("error", err.Error()), logger.Field("cacheKey", cacheKey))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
var payload common.CacheKeyPayload
|
||||
err = json.Unmarshal([]byte(value), &payload)
|
||||
if err != nil {
|
||||
l.Errorw("Unmarshal Error", logger.Field("error", err.Error()), logger.Field("value", value))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
if payload.Code != req.Code {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
l.svcCtx.Redis.Del(l.ctx, cacheKey)
|
||||
} else {
|
||||
// Verify password
|
||||
if !tool.VerifyPassWord(req.Password, userInfo.Password) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserPasswordError), "user password")
|
||||
}
|
||||
}
|
||||
case authmethod.Mobile:
|
||||
if !l.svcCtx.Config.Mobile.Enable {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SmsNotEnabled), "sms login is not enabled")
|
||||
}
|
||||
phoneNumber, err := phone.FormatToE164(req.AreaCode, req.Account)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TelephoneError), "Invalid phone number")
|
||||
}
|
||||
|
||||
if req.Code != "" {
|
||||
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeTelephoneCacheKey, constant.Security, phoneNumber)
|
||||
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err != nil {
|
||||
l.Errorw("Redis Error", logger.Field("error", err.Error()), logger.Field("cacheKey", cacheKey))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
if value == "" {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
var payload common.CacheKeyPayload
|
||||
if err := json.Unmarshal([]byte(value), &payload); err != nil {
|
||||
l.Errorw("[SendSmsCode]: Unmarshal Error", logger.Field("error", err.Error()), logger.Field("value", value))
|
||||
}
|
||||
if payload.Code != req.Code {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
l.svcCtx.Redis.Del(l.ctx, cacheKey)
|
||||
} else {
|
||||
// Verify password
|
||||
if !tool.VerifyPassWord(req.Password, userInfo.Password) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserPasswordError), "user password")
|
||||
}
|
||||
}
|
||||
case authmethod.Device:
|
||||
default:
|
||||
return nil, existError(req.Method)
|
||||
}
|
||||
|
||||
device, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, req.Identifier)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
if req.Method == authmethod.Device {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "device not exist")
|
||||
}
|
||||
//Add User Device
|
||||
userInfo.UserDevices = append(userInfo.UserDevices, user.Device{
|
||||
UserAgent: req.UserAgent,
|
||||
Identifier: req.Identifier,
|
||||
Ip: l.ctx.ClientIP(),
|
||||
})
|
||||
err = l.svcCtx.UserModel.Update(l.ctx, userInfo)
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateUserBindDevice] Fail", logger.Field("error", err.Error()))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//Change the user who owns the device
|
||||
if device.UserId != userInfo.Id {
|
||||
device.UserId = userInfo.Id
|
||||
}
|
||||
device.Ip = l.ctx.ClientIP()
|
||||
err = l.svcCtx.UserModel.UpdateDevice(l.ctx, device)
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateUserBindDevice] Fail", logger.Field("error", err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
// Generate session id
|
||||
sessionId := uuidx.NewUUID().String()
|
||||
// Generate token
|
||||
token, err := jwt.NewJwtToken(
|
||||
l.svcCtx.Config.JwtAuth.AccessSecret,
|
||||
time.Now().Unix(),
|
||||
l.svcCtx.Config.JwtAuth.AccessExpire,
|
||||
jwt.WithOption("UserId", userInfo.Id),
|
||||
jwt.WithOption("SessionId", sessionId),
|
||||
)
|
||||
if err != nil {
|
||||
l.Logger.Error("[UserLogin] token generate error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "token generate error: %v", err.Error())
|
||||
}
|
||||
sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
|
||||
if err = l.svcCtx.Redis.Set(l.ctx, sessionIdCacheKey, userInfo.Id, time.Duration(l.svcCtx.Config.JwtAuth.AccessExpire)*time.Second).Err(); err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "set session id error: %v", err.Error())
|
||||
}
|
||||
|
||||
resp.Token = token
|
||||
return
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/authmethod"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/logic/common"
|
||||
"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/jwt"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/phone"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/uuidx"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type CacheKeyPayload struct {
|
||||
Code string `json:"code"`
|
||||
LastAt int64 `json:"lastAt"`
|
||||
}
|
||||
type RegisterLogic struct {
|
||||
logger.Logger
|
||||
ctx *gin.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Register
|
||||
func NewRegisterLogic(ctx *gin.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
|
||||
return &RegisterLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *RegisterLogic) Register(req *types.AppAuthRequest) (resp *types.AppAuthRespone, err error) {
|
||||
resp = &types.AppAuthRespone{}
|
||||
var referer *user.User
|
||||
c := l.svcCtx.Config.Register
|
||||
// Check if the registration is stopped
|
||||
if c.StopRegister {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.StopRegister), "stop register")
|
||||
}
|
||||
|
||||
if req.Invite == "" {
|
||||
if l.svcCtx.Config.Invite.ForcedInvite {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InviteCodeError), "invite code is required")
|
||||
}
|
||||
} else {
|
||||
// Check if the invite code is valid
|
||||
referer, err = l.svcCtx.UserModel.FindOneByReferCode(l.ctx, req.Invite)
|
||||
if err != nil {
|
||||
l.Errorw("FindOneByReferCode Error", logger.Field("error", err))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InviteCodeError), "invite code is invalid")
|
||||
}
|
||||
}
|
||||
|
||||
if req.Password == "" {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.PasswordIsEmpty), "Password required")
|
||||
}
|
||||
|
||||
userInfo, err := findUserByMethod(l.ctx, l.svcCtx, req.Method, req.Identifier, req.Account, req.AreaCode)
|
||||
if err == nil && userInfo != nil {
|
||||
return nil, existError(req.Method)
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
// Generate password
|
||||
pwd := tool.EncodePassWord(req.Password)
|
||||
userInfo = &user.User{
|
||||
Password: pwd,
|
||||
}
|
||||
if referer != nil {
|
||||
userInfo.RefererId = referer.Id
|
||||
}
|
||||
switch req.Method {
|
||||
case authmethod.Email:
|
||||
if !l.svcCtx.Config.Email.Enable {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.EmailNotEnabled), "Email function is not enabled yet")
|
||||
}
|
||||
if l.svcCtx.Config.Email.EnableVerify {
|
||||
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeCacheKey, constant.Register.String(), req.Account)
|
||||
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err != nil {
|
||||
l.Errorw("Redis Error", logger.Field("error", err.Error()), logger.Field("cacheKey", cacheKey))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
var payload common.CacheKeyPayload
|
||||
err = json.Unmarshal([]byte(value), &payload)
|
||||
if err != nil {
|
||||
l.Errorw("Unmarshal Error", logger.Field("error", err.Error()), logger.Field("value", value))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
if payload.Code != req.Code {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
}
|
||||
userInfo.AuthMethods = []user.AuthMethods{{
|
||||
AuthType: authmethod.Email,
|
||||
AuthIdentifier: req.Account,
|
||||
}}
|
||||
|
||||
case authmethod.Mobile:
|
||||
if req.AreaCode == "" {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TelephoneAreaCodeIsEmpty), "area code required")
|
||||
}
|
||||
|
||||
if !l.svcCtx.Config.Mobile.Enable {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SmsNotEnabled), "sms login is not enabled")
|
||||
}
|
||||
phoneNumber, err := phone.FormatToE164(req.AreaCode, req.Account)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TelephoneError), "Invalid phone number")
|
||||
}
|
||||
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeTelephoneCacheKey, constant.Register, phoneNumber)
|
||||
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err != nil {
|
||||
l.Errorw("Redis Error", logger.Field("error", err.Error()), logger.Field("cacheKey", cacheKey))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
var payload CacheKeyPayload
|
||||
_ = json.Unmarshal([]byte(value), &payload)
|
||||
if payload.Code != req.Code {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
userInfo.AuthMethods = []user.AuthMethods{{
|
||||
AuthType: authmethod.Mobile,
|
||||
AuthIdentifier: phoneNumber,
|
||||
Verified: true,
|
||||
}}
|
||||
case authmethod.Device:
|
||||
oneDevice, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, req.Identifier)
|
||||
if err == nil && oneDevice != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DeviceExist), "device exist")
|
||||
}
|
||||
default:
|
||||
return nil, existError(req.Method)
|
||||
}
|
||||
|
||||
device, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, req.Identifier)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
//Add User Device
|
||||
userInfo.UserDevices = append(userInfo.UserDevices, user.Device{
|
||||
Ip: l.ctx.ClientIP(),
|
||||
Identifier: req.Identifier,
|
||||
UserAgent: req.UserAgent,
|
||||
})
|
||||
} else {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user info failed: %v", err.Error())
|
||||
}
|
||||
} else {
|
||||
//Delete Other User Device
|
||||
err = l.svcCtx.UserModel.DeleteDevice(l.ctx, device.Id)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "delete old user device failed: %v", err.Error())
|
||||
} else {
|
||||
//User Add Device
|
||||
userInfo.UserDevices = append(userInfo.UserDevices, user.Device{
|
||||
Ip: l.ctx.ClientIP(),
|
||||
Identifier: req.Identifier,
|
||||
UserAgent: req.UserAgent,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
err = l.svcCtx.UserModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||
// Save user information
|
||||
if err := db.Create(userInfo).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Generate ReferCode
|
||||
userInfo.ReferCode = uuidx.UserInviteCode(userInfo.Id)
|
||||
// Update ReferCode
|
||||
if err := db.Model(&user.User{}).Where("id = ?", userInfo.Id).Update("refer_code", userInfo.ReferCode).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if l.svcCtx.Config.Register.EnableTrial {
|
||||
// Active trial
|
||||
if err = l.activeTrial(userInfo.Id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert user info failed: %v", err.Error())
|
||||
}
|
||||
|
||||
// Generate session id
|
||||
sessionId := uuidx.NewUUID().String()
|
||||
// Generate token
|
||||
token, err := jwt.NewJwtToken(
|
||||
l.svcCtx.Config.JwtAuth.AccessSecret,
|
||||
time.Now().Unix(),
|
||||
l.svcCtx.Config.JwtAuth.AccessExpire,
|
||||
jwt.WithOption("UserId", userInfo.Id),
|
||||
jwt.WithOption("SessionId", sessionId),
|
||||
)
|
||||
if err != nil {
|
||||
l.Logger.Error("[UserLogin] token generate error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "token generate error: %v", err.Error())
|
||||
}
|
||||
|
||||
sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
|
||||
if err := l.svcCtx.Redis.Set(l.ctx, sessionIdCacheKey, userInfo.Id, time.Duration(l.svcCtx.Config.JwtAuth.AccessExpire)*time.Second).Err(); err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "set session id error: %v", err.Error())
|
||||
}
|
||||
|
||||
resp.Token = token
|
||||
return
|
||||
}
|
||||
|
||||
func (l *RegisterLogic) activeTrial(uid int64) error {
|
||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, l.svcCtx.Config.Register.TrialSubscribe)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
userSub := &user.Subscribe{
|
||||
Id: 0,
|
||||
UserId: uid,
|
||||
OrderId: 0,
|
||||
SubscribeId: sub.Id,
|
||||
StartTime: time.Now(),
|
||||
ExpireTime: tool.AddTime(l.svcCtx.Config.Register.TrialTimeUnit, l.svcCtx.Config.Register.TrialTime, time.Now()),
|
||||
Traffic: sub.Traffic,
|
||||
Download: 0,
|
||||
Upload: 0,
|
||||
Token: uuidx.SubscribeToken(fmt.Sprintf("Trial-%v", uid)),
|
||||
UUID: uuidx.NewUUID().String(),
|
||||
Status: 1,
|
||||
}
|
||||
return l.svcCtx.UserModel.InsertSubscribe(l.ctx, userSub)
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/authmethod"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/phone"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/logic/common"
|
||||
"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/jwt"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/uuidx"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ResetPasswordLogic struct {
|
||||
logger.Logger
|
||||
ctx *gin.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Reset Password
|
||||
func NewResetPasswordLogic(ctx *gin.Context, svcCtx *svc.ServiceContext) *ResetPasswordLogic {
|
||||
return &ResetPasswordLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *ResetPasswordLogic) ResetPassword(req *types.AppAuthRequest) (resp *types.AppAuthRespone, err error) {
|
||||
resp = &types.AppAuthRespone{}
|
||||
userInfo, err := findUserByMethod(l.ctx, l.svcCtx, req.Method, req.Identifier, req.Account, req.AreaCode)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserNotExist), "query user info failed")
|
||||
}
|
||||
l.Errorw("FindOneByEmail Error", logger.Field("error", err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch req.Method {
|
||||
case authmethod.Mobile:
|
||||
if !l.svcCtx.Config.Mobile.Enable {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SmsNotEnabled), "sms login is not enabled")
|
||||
}
|
||||
phoneNumber, err := phone.FormatToE164(req.AreaCode, req.Account)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TelephoneError), "Invalid phone number")
|
||||
}
|
||||
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeTelephoneCacheKey, constant.Security, phoneNumber)
|
||||
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err != nil {
|
||||
l.Errorw("Redis Error", logger.Field("error", err.Error()), logger.Field("cacheKey", cacheKey))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
var payload common.CacheKeyPayload
|
||||
err = json.Unmarshal([]byte(value), &payload)
|
||||
if err != nil {
|
||||
l.Errorw("Unmarshal Error", logger.Field("error", err.Error()), logger.Field("value", value))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
if payload.Code != req.Code {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
case authmethod.Email:
|
||||
if !l.svcCtx.Config.Email.Enable {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.EmailNotEnabled), "Email function is not enabled yet")
|
||||
}
|
||||
|
||||
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeCacheKey, constant.Security.String(), req.Account)
|
||||
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err != nil {
|
||||
l.Errorw("Redis Error", logger.Field("error", err.Error()), logger.Field("cacheKey", cacheKey))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
var payload CacheKeyPayload
|
||||
err = json.Unmarshal([]byte(value), &payload)
|
||||
if err != nil {
|
||||
l.Errorw("Unmarshal Error", logger.Field("error", err.Error()), logger.Field("value", value))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
|
||||
if payload.Code != req.Code {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "code error")
|
||||
}
|
||||
default:
|
||||
return nil, errors.New("unknown method")
|
||||
}
|
||||
|
||||
userInfo.Password = tool.EncodePassWord(req.Password)
|
||||
err = l.svcCtx.UserModel.Update(l.ctx, userInfo)
|
||||
if err != nil {
|
||||
l.Errorw("UpdateUser Error", logger.Field("error", err))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update user info failed: %v", err.Error())
|
||||
}
|
||||
|
||||
device, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, req.Identifier)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
//Add User Device
|
||||
userInfo.UserDevices = append(userInfo.UserDevices, user.Device{
|
||||
Ip: l.ctx.ClientIP(),
|
||||
Identifier: req.Identifier,
|
||||
UserAgent: req.UserAgent,
|
||||
})
|
||||
} else {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user info failed: %v", err.Error())
|
||||
}
|
||||
} else {
|
||||
if device.UserId != userInfo.Id {
|
||||
//Change the user who owns the device
|
||||
if device.UserId != userInfo.Id {
|
||||
device.UserId = userInfo.Id
|
||||
}
|
||||
device.Ip = l.ctx.ClientIP()
|
||||
err = l.svcCtx.UserModel.UpdateDevice(l.ctx, device)
|
||||
if err != nil {
|
||||
l.Errorw("[UpdateUserBindDevice] Fail", logger.Field("error", err.Error()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate session id
|
||||
sessionId := uuidx.NewUUID().String()
|
||||
// Generate token
|
||||
token, err := jwt.NewJwtToken(
|
||||
l.svcCtx.Config.JwtAuth.AccessSecret,
|
||||
time.Now().Unix(),
|
||||
l.svcCtx.Config.JwtAuth.AccessExpire,
|
||||
jwt.WithOption("UserId", userInfo.Id),
|
||||
jwt.WithOption("SessionId", sessionId),
|
||||
)
|
||||
if err != nil {
|
||||
l.Logger.Error("[UserLogin] token generate error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "token generate error: %v", err.Error())
|
||||
}
|
||||
|
||||
sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
|
||||
if err := l.svcCtx.Redis.Set(l.ctx, sessionIdCacheKey, userInfo.Id, time.Duration(l.svcCtx.Config.JwtAuth.AccessExpire)*time.Second).Err(); err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "set session id error: %v", err.Error())
|
||||
}
|
||||
resp.Token = token
|
||||
return
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package document
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type QueryDocumentDetailLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewQueryDocumentDetailLogic Get document detail
|
||||
func NewQueryDocumentDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryDocumentDetailLogic {
|
||||
return &QueryDocumentDetailLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryDocumentDetailLogic) QueryDocumentDetail(req *types.QueryDocumentDetailRequest) (resp *types.Document, err error) {
|
||||
// find document
|
||||
data, err := l.svcCtx.DocumentModel.FindOne(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Error("[QueryDocumentDetailLogic] FindOne error", logger.Field("id", req.Id), logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindOne error: %s", err.Error())
|
||||
}
|
||||
resp = &types.Document{}
|
||||
tool.DeepCopy(resp, data)
|
||||
return
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package document
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type QueryDocumentListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get document list
|
||||
func NewQueryDocumentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryDocumentListLogic {
|
||||
return &QueryDocumentListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryDocumentListLogic) QueryDocumentList() (resp *types.QueryDocumentListResponse, err error) {
|
||||
total, data, err := l.svcCtx.DocumentModel.GetDocumentListByAll(l.ctx)
|
||||
if err != nil {
|
||||
l.Error("[QueryDocumentList] error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "QueryDocumentList error: %v", err.Error())
|
||||
}
|
||||
resp = &types.QueryDocumentListResponse{
|
||||
Total: total,
|
||||
List: make([]types.Document, 0),
|
||||
}
|
||||
for _, item := range data {
|
||||
resp.List = append(resp.List, types.Document{
|
||||
Id: item.Id,
|
||||
Title: item.Title,
|
||||
Tags: tool.StringMergeAndRemoveDuplicates(item.Tags),
|
||||
UpdatedAt: item.UpdatedAt.UnixMilli(),
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"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/logger"
|
||||
)
|
||||
|
||||
type GetNodeListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get Node list
|
||||
func NewGetNodeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetNodeListLogic {
|
||||
return &GetNodeListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetNodeListLogic) GetNodeList(req *types.AppUserSubscbribeNodeRequest) (resp *types.AppUserSubscbribeNodeResponse, err error) {
|
||||
resp = &types.AppUserSubscbribeNodeResponse{List: make([]types.AppUserSubscbribeNode, 0)}
|
||||
userInfo := l.ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||
userSubscribe, err := l.svcCtx.UserModel.FindOneUserSubscribe(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscribe: %v", err.Error())
|
||||
}
|
||||
|
||||
if userInfo.Id != userSubscribe.UserId {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "find user subscribe: %v", err.Error())
|
||||
}
|
||||
|
||||
//拿到所有订阅下的服务组id
|
||||
var ids []int64
|
||||
for _, idStr := range strings.Split(userSubscribe.Subscribe.ServerGroup, ",") {
|
||||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
|
||||
//根据服务组id拿到所有节点
|
||||
servers, err := l.svcCtx.ServerModel.FindServerListByGroupIds(l.ctx, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, server := range servers {
|
||||
resp.List = append(resp.List, types.AppUserSubscbribeNode{
|
||||
Id: server.Id,
|
||||
Uuid: userSubscribe.UUID,
|
||||
Traffic: userSubscribe.Traffic,
|
||||
Upload: userSubscribe.Upload,
|
||||
Download: userSubscribe.Download,
|
||||
RelayNode: server.RelayNode,
|
||||
RelayMode: server.RelayMode,
|
||||
Longitude: server.Longitude,
|
||||
Latitude: server.Latitude,
|
||||
Tags: strings.Split(server.Tags, ","),
|
||||
Config: server.Config,
|
||||
ServerAddr: server.ServerAddr,
|
||||
Protocol: server.Protocol,
|
||||
SpeedLimit: server.SpeedLimit,
|
||||
City: server.City,
|
||||
Country: server.Country,
|
||||
Name: server.Name,
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetRuleGroupListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get rule group list
|
||||
func NewGetRuleGroupListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRuleGroupListLogic {
|
||||
return &GetRuleGroupListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetRuleGroupListLogic) GetRuleGroupList() (resp *types.AppRuleGroupListResponse, err error) {
|
||||
nodeRuleGroupList, err := l.svcCtx.ServerModel.QueryAllRuleGroup(l.ctx)
|
||||
if err != nil {
|
||||
l.Logger.Error("[GetRuleGroupList] get subscribe rule group list failed: ", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get subscribe rule group list failed: %v", err.Error())
|
||||
}
|
||||
nodeRuleGroups := make([]types.ServerRuleGroup, 0)
|
||||
tool.DeepCopy(&nodeRuleGroups, nodeRuleGroupList)
|
||||
return &types.AppRuleGroupListResponse{
|
||||
Total: int64(len(nodeRuleGroups)),
|
||||
List: nodeRuleGroups,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"github.com/perfect-panel/server/internal/model/coupon"
|
||||
)
|
||||
|
||||
func calculateCoupon(amount int64, couponInfo *coupon.Coupon) int64 {
|
||||
if couponInfo.Type == 1 {
|
||||
return int64(float64(amount) * (float64(couponInfo.Discount) / float64(100)))
|
||||
} else {
|
||||
return min(couponInfo.Discount, amount)
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package order
|
||||
|
||||
import "github.com/perfect-panel/server/internal/model/payment"
|
||||
|
||||
func calculateFee(amount int64, config *payment.Payment) int64 {
|
||||
var fee float64
|
||||
switch config.FeeMode {
|
||||
case 0:
|
||||
return 0
|
||||
case 1:
|
||||
fee = float64(amount) * (float64(config.FeePercent) / float64(100))
|
||||
case 2:
|
||||
if amount > 0 {
|
||||
fee = float64(config.FeeAmount)
|
||||
}
|
||||
case 3:
|
||||
fee = float64(amount)*(float64(config.FeePercent)/float64(100)) + float64(config.FeeAmount)
|
||||
}
|
||||
return int64(fee)
|
||||
}
|
||||
@@ -1,325 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
paymentPlatform "github.com/perfect-panel/server/pkg/payment"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"github.com/perfect-panel/server/internal/model/payment"
|
||||
"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/exchangeRate"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/payment/alipay"
|
||||
"github.com/perfect-panel/server/pkg/payment/epay"
|
||||
"github.com/perfect-panel/server/pkg/payment/stripe"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
queueType "github.com/perfect-panel/server/queue/types"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type CheckoutOrderLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
type CurrencyConfig struct {
|
||||
CurrencyUnit string
|
||||
CurrencySymbol string
|
||||
AccessKey string
|
||||
}
|
||||
|
||||
const (
|
||||
Stripe = "Stripe"
|
||||
QR = "qr"
|
||||
Link = "link"
|
||||
)
|
||||
|
||||
// NewCheckoutOrderLogic Checkout order
|
||||
func NewCheckoutOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckoutOrderLogic {
|
||||
return &CheckoutOrderLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *CheckoutOrderLogic) CheckoutOrder(req *types.CheckoutOrderRequest, requestHost string) (resp *types.CheckoutOrderResponse, err error) {
|
||||
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||
if !ok {
|
||||
l.Error("[CheckoutOrderLogic] Invalid access")
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid access")
|
||||
}
|
||||
// find order
|
||||
orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] FindOneByOrderNo error", logger.Field("orderNo", req.OrderNo), logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindOneByOrderNo error: %s", err.Error())
|
||||
}
|
||||
|
||||
if orderInfo.Status != 1 {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Order status error")
|
||||
}
|
||||
|
||||
paymentConfig, err := l.svcCtx.PaymentModel.FindOne(l.ctx, orderInfo.PaymentId)
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] FindOneByPaymentMark error", logger.Field("paymentMark", orderInfo.Method), logger.Field("PaymentID", orderInfo.PaymentId), logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindOneByPaymentMark error: %s", err.Error())
|
||||
}
|
||||
var stripePayment *types.StripePayment = nil
|
||||
var url, t string
|
||||
|
||||
// switch payment method
|
||||
switch paymentPlatform.ParsePlatform(paymentConfig.Platform) {
|
||||
case paymentPlatform.Stripe:
|
||||
result, err := l.stripePayment(paymentConfig.Config, orderInfo, u)
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] stripePayment error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
stripePayment = result
|
||||
t = Stripe
|
||||
case paymentPlatform.EPay:
|
||||
// epay
|
||||
url, err = l.epayPayment(paymentConfig, orderInfo, req.ReturnUrl, requestHost)
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] epayPayment error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
t = Link
|
||||
case paymentPlatform.AlipayF2F:
|
||||
// alipay f2f
|
||||
url, err = l.alipayF2fPayment(paymentConfig, orderInfo, requestHost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t = QR
|
||||
case paymentPlatform.Balance:
|
||||
// balance
|
||||
if err = l.balancePayment(u, orderInfo); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t = paymentPlatform.Balance.String()
|
||||
default:
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Payment method not supported")
|
||||
}
|
||||
return &types.CheckoutOrderResponse{
|
||||
Type: t,
|
||||
CheckoutUrl: url,
|
||||
Stripe: stripePayment,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Query exchange rate
|
||||
func (l *CheckoutOrderLogic) queryExchangeRate(to string, src int64) (amount float64, err error) {
|
||||
amount = float64(src) / float64(100)
|
||||
// query system currency
|
||||
currency, err := l.svcCtx.SystemModel.GetCurrencyConfig(l.ctx)
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] GetCurrencyConfig error", logger.Field("error", err.Error()))
|
||||
return 0, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "GetCurrencyConfig error: %s", err.Error())
|
||||
}
|
||||
configs := &CurrencyConfig{}
|
||||
tool.SystemConfigSliceReflectToStruct(currency, configs)
|
||||
if configs.AccessKey == "" {
|
||||
return amount, nil
|
||||
}
|
||||
if configs.CurrencyUnit != to {
|
||||
// query exchange rate
|
||||
result, err := exchangeRate.GetExchangeRete(configs.CurrencyUnit, to, configs.AccessKey, 1)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
amount = result * amount
|
||||
}
|
||||
return amount, nil
|
||||
}
|
||||
|
||||
// Stripe Payment
|
||||
func (l *CheckoutOrderLogic) stripePayment(config string, info *order.Order, u *user.User) (*types.StripePayment, error) {
|
||||
// stripe WeChat pay or stripe alipay
|
||||
stripeConfig := payment.StripeConfig{}
|
||||
if err := json.Unmarshal([]byte(config), &stripeConfig); err != nil {
|
||||
l.Error("[CheckoutOrderLogic] Unmarshal error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Unmarshal error: %s", err.Error())
|
||||
}
|
||||
client := stripe.NewClient(stripe.Config{
|
||||
SecretKey: stripeConfig.SecretKey,
|
||||
PublicKey: stripeConfig.PublicKey,
|
||||
WebhookSecret: stripeConfig.WebhookSecret,
|
||||
})
|
||||
// Calculate the amount with exchange rate
|
||||
amount, err := l.queryExchangeRate("CNY", info.Amount)
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] queryExchangeRate error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "queryExchangeRate error: %s", err.Error())
|
||||
}
|
||||
convertAmount := int64(amount * 100)
|
||||
// create payment
|
||||
result, err := client.CreatePaymentSheet(&stripe.Order{
|
||||
OrderNo: info.OrderNo,
|
||||
Subscribe: strconv.FormatInt(info.SubscribeId, 10),
|
||||
Amount: convertAmount,
|
||||
Currency: "cny",
|
||||
Payment: stripeConfig.Payment,
|
||||
},
|
||||
&stripe.User{
|
||||
UserId: u.Id,
|
||||
})
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] CreatePaymentSheet error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "CreatePaymentSheet error: %s", err.Error())
|
||||
}
|
||||
tradeNo := result.TradeNo
|
||||
stripePayment := &types.StripePayment{
|
||||
PublishableKey: stripeConfig.PublicKey,
|
||||
ClientSecret: result.ClientSecret,
|
||||
Method: stripeConfig.Payment,
|
||||
}
|
||||
// save payment
|
||||
info.TradeNo = tradeNo
|
||||
err = l.svcCtx.OrderModel.Update(l.ctx, info)
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] Update error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Update error: %s", err.Error())
|
||||
}
|
||||
return stripePayment, nil
|
||||
}
|
||||
|
||||
// epay payment
|
||||
func (l *CheckoutOrderLogic) epayPayment(config *payment.Payment, info *order.Order, returnUrl, requestHost string) (string, error) {
|
||||
epayConfig := payment.EPayConfig{}
|
||||
if err := json.Unmarshal([]byte(config.Config), &epayConfig); err != nil {
|
||||
l.Error("[CheckoutOrderLogic] Unmarshal error", logger.Field("error", err.Error()))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Unmarshal error: %s", err.Error())
|
||||
}
|
||||
client := epay.NewClient(epayConfig.Pid, epayConfig.Url, epayConfig.Key)
|
||||
// Calculate the amount with exchange rate
|
||||
amount, err := l.queryExchangeRate("CNY", info.Amount)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var domain string
|
||||
if config.Domain != "" {
|
||||
domain = config.Domain
|
||||
} else {
|
||||
domain = fmt.Sprintf("http://%s", requestHost)
|
||||
}
|
||||
// create payment
|
||||
url := client.CreatePayUrl(epay.Order{
|
||||
Name: l.svcCtx.Config.Site.SiteName,
|
||||
Amount: amount,
|
||||
OrderNo: info.OrderNo,
|
||||
SignType: "MD5",
|
||||
NotifyUrl: domain + "/v1/notify/epay",
|
||||
ReturnUrl: returnUrl,
|
||||
})
|
||||
return url, nil
|
||||
}
|
||||
|
||||
// alipay f2f payment
|
||||
func (l *CheckoutOrderLogic) alipayF2fPayment(pay *payment.Payment, info *order.Order, requestHost string) (string, error) {
|
||||
f2FConfig := payment.AlipayF2FConfig{}
|
||||
if err := json.Unmarshal([]byte(pay.Config), &f2FConfig); err != nil {
|
||||
l.Error("[CheckoutOrderLogic] Unmarshal error", logger.Field("error", err.Error()))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Unmarshal error: %s", err.Error())
|
||||
}
|
||||
var domain string
|
||||
if pay.Domain != "" {
|
||||
domain = pay.Domain
|
||||
} else {
|
||||
domain = fmt.Sprintf("http://%s", requestHost)
|
||||
}
|
||||
client := alipay.NewClient(alipay.Config{
|
||||
AppId: f2FConfig.AppId,
|
||||
PrivateKey: f2FConfig.PrivateKey,
|
||||
PublicKey: f2FConfig.PublicKey,
|
||||
InvoiceName: f2FConfig.InvoiceName,
|
||||
NotifyURL: domain + "/notify/alipay",
|
||||
})
|
||||
// Calculate the amount with exchange rate
|
||||
amount, err := l.queryExchangeRate("CNY", info.Amount)
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] queryExchangeRate error", logger.Field("error", err.Error()))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "queryExchangeRate error: %s", err.Error())
|
||||
}
|
||||
convertAmount := int64(amount * 100)
|
||||
// create payment
|
||||
QRCode, err := client.PreCreateTrade(l.ctx, alipay.Order{
|
||||
OrderNo: info.OrderNo,
|
||||
Amount: convertAmount,
|
||||
})
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] PreCreateTrade error", logger.Field("error", err.Error()))
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "PreCreateTrade error: %s", err.Error())
|
||||
}
|
||||
return QRCode, nil
|
||||
}
|
||||
|
||||
// Balance payment
|
||||
func (l *CheckoutOrderLogic) balancePayment(u *user.User, o *order.Order) error {
|
||||
var userInfo user.User
|
||||
err := l.svcCtx.UserModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||
err := db.Model(&user.User{}).Where("id = ?", u.Id).First(&userInfo).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if userInfo.Balance < o.Amount {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InsufficientBalance), "Insufficient balance")
|
||||
}
|
||||
// deduct balance
|
||||
userInfo.Balance -= o.Amount
|
||||
err = l.svcCtx.UserModel.Update(l.ctx, &userInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// create balance log
|
||||
balanceLog := &user.BalanceLog{
|
||||
Id: 0,
|
||||
UserId: u.Id,
|
||||
Amount: o.Amount,
|
||||
Type: 3,
|
||||
OrderId: o.Id,
|
||||
Balance: userInfo.Balance,
|
||||
}
|
||||
err = db.Create(balanceLog).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.svcCtx.OrderModel.UpdateOrderStatus(l.ctx, o.OrderNo, 2)
|
||||
})
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] Transaction error", logger.Field("error", err.Error()), logger.Field("orderNo", o.OrderNo))
|
||||
return err
|
||||
}
|
||||
// create activity order task
|
||||
payload := queueType.ForthwithActivateOrderPayload{
|
||||
OrderNo: o.OrderNo,
|
||||
}
|
||||
bytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] Marshal error", logger.Field("error", err.Error()))
|
||||
return err
|
||||
}
|
||||
|
||||
task := asynq.NewTask(queueType.ForthwithActivateOrder, bytes)
|
||||
_, err = l.svcCtx.Queue.EnqueueContext(l.ctx, task)
|
||||
if err != nil {
|
||||
l.Error("[CheckoutOrderLogic] Enqueue error", logger.Field("error", err.Error()))
|
||||
return err
|
||||
}
|
||||
l.Logger.Info("[CheckoutOrderLogic] Enqueue success", logger.Field("orderNo", o.OrderNo))
|
||||
return nil
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
paymentPlatform "github.com/perfect-panel/server/pkg/payment"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/pkg/payment/stripe"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"github.com/perfect-panel/server/internal/model/payment"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/payment/alipay"
|
||||
)
|
||||
|
||||
type CloseOrderLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewCloseOrderLogic Close order
|
||||
func NewCloseOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CloseOrderLogic {
|
||||
return &CloseOrderLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *CloseOrderLogic) CloseOrder(req *types.CloseOrderRequest) error {
|
||||
// Find order information by order number
|
||||
orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
|
||||
if err != nil {
|
||||
l.Error("[CloseOrder] Find order info failed",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("orderNo", req.OrderNo),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
// If the order status is not 1, it means that the order has been closed or paid
|
||||
if orderInfo.Status != 1 {
|
||||
l.Info("[CloseOrder] Order status is not 1",
|
||||
logger.Field("orderNo", req.OrderNo),
|
||||
logger.Field("status", orderInfo.Status),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
if l.confirmationPayment(orderInfo) {
|
||||
l.Info("[CloseOrder] Order has been paid",
|
||||
logger.Field("orderNo", req.OrderNo),
|
||||
logger.Field("status", orderInfo.Status),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
err = l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
|
||||
// update order status
|
||||
err := tx.Model(&order.Order{}).Where("order_no = ?", req.OrderNo).Update("status", 3).Error
|
||||
if err != nil {
|
||||
l.Error("[CloseOrder] Update order status failed",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("orderNo", req.OrderNo),
|
||||
)
|
||||
return err
|
||||
}
|
||||
// refund deduction amount to user deduction balance
|
||||
if orderInfo.GiftAmount > 0 {
|
||||
userInfo, err := l.svcCtx.UserModel.FindOne(l.ctx, orderInfo.UserId)
|
||||
if err != nil {
|
||||
l.Error("[CloseOrder] Find user info failed",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("user_id", orderInfo.UserId),
|
||||
)
|
||||
return err
|
||||
}
|
||||
deduction := userInfo.GiftAmount + orderInfo.GiftAmount
|
||||
err = tx.Model(&user.User{}).Where("id = ?", orderInfo.UserId).Update("deduction", deduction).Error
|
||||
if err != nil {
|
||||
l.Error("[CloseOrder] Refund deduction amount failed",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("uid", orderInfo.UserId),
|
||||
logger.Field("deduction", orderInfo.GiftAmount),
|
||||
)
|
||||
return err
|
||||
}
|
||||
// Record the deduction refund log
|
||||
giftAmountLog := &user.GiftAmountLog{
|
||||
UserId: orderInfo.UserId,
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
Amount: orderInfo.GiftAmount,
|
||||
Type: 1,
|
||||
Balance: deduction,
|
||||
Remark: "Order cancellation refund",
|
||||
}
|
||||
err = tx.Model(&user.GiftAmountLog{}).Create(giftAmountLog).Error
|
||||
if err != nil {
|
||||
l.Error("[CloseOrder] Record cancellation refund log failed",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("uid", orderInfo.UserId),
|
||||
logger.Field("deduction", orderInfo.GiftAmount),
|
||||
)
|
||||
return err
|
||||
}
|
||||
// update user cache
|
||||
return l.svcCtx.UserModel.UpdateUserCache(l.ctx, userInfo)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// confirmationPayment Determine whether the payment is successful
|
||||
//
|
||||
//nolint:unused
|
||||
func (l *CloseOrderLogic) confirmationPayment(order *order.Order) bool {
|
||||
paymentConfig, err := l.svcCtx.PaymentModel.FindOne(l.ctx, order.PaymentId)
|
||||
if err != nil {
|
||||
l.Error("[CloseOrder] Find payment config failed", logger.Field("error", err.Error()), logger.Field("paymentMark", order.Method))
|
||||
return false
|
||||
}
|
||||
switch paymentPlatform.ParsePlatform(order.Method) {
|
||||
case paymentPlatform.AlipayF2F:
|
||||
if l.queryAlipay(paymentConfig, order.TradeNo) {
|
||||
return true
|
||||
}
|
||||
case paymentPlatform.Stripe:
|
||||
if l.queryStripe(paymentConfig, order.TradeNo) {
|
||||
return true
|
||||
}
|
||||
default:
|
||||
l.Info("[CloseOrder] Unsupported payment method", logger.Field("paymentMethod", order.Method))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// queryAlipay Query Alipay payment status
|
||||
func (l *CloseOrderLogic) queryAlipay(paymentConfig *payment.Payment, TradeNo string) bool {
|
||||
config := payment.AlipayF2FConfig{}
|
||||
if err := json.Unmarshal([]byte(paymentConfig.Config), &config); err != nil {
|
||||
l.Error("[CloseOrder] Unmarshal payment config failed", logger.Field("error", err.Error()), logger.Field("config", paymentConfig.Config))
|
||||
return false
|
||||
}
|
||||
client := alipay.NewClient(alipay.Config{
|
||||
AppId: config.AppId,
|
||||
PrivateKey: config.PrivateKey,
|
||||
PublicKey: config.PublicKey,
|
||||
InvoiceName: config.InvoiceName,
|
||||
})
|
||||
status, err := client.QueryTrade(l.ctx, TradeNo)
|
||||
if err != nil {
|
||||
l.Error("[CloseOrder] Query trade failed", logger.Field("error", err.Error()), logger.Field("TradeNo", TradeNo))
|
||||
return false
|
||||
}
|
||||
if status == alipay.Success || status == alipay.Finished {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// queryStripe Query Stripe payment status
|
||||
func (l *CloseOrderLogic) queryStripe(paymentConfig *payment.Payment, TradeNo string) bool {
|
||||
config := payment.StripeConfig{}
|
||||
if err := json.Unmarshal([]byte(paymentConfig.Config), &config); err != nil {
|
||||
l.Error("[CloseOrder] Unmarshal payment config failed", logger.Field("error", err.Error()), logger.Field("config", paymentConfig.Config))
|
||||
return false
|
||||
}
|
||||
client := stripe.NewClient(stripe.Config{
|
||||
PublicKey: config.PublicKey,
|
||||
SecretKey: config.SecretKey,
|
||||
WebhookSecret: config.WebhookSecret,
|
||||
})
|
||||
status, err := client.QueryOrderStatus(TradeNo)
|
||||
if err != nil {
|
||||
l.Error("[CloseOrder] Query order status failed", logger.Field("error", err.Error()), logger.Field("TradeNo", TradeNo))
|
||||
return false
|
||||
}
|
||||
return status
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package order
|
||||
|
||||
import "github.com/perfect-panel/server/internal/types"
|
||||
|
||||
func getDiscount(discounts []types.SubscribeDiscount, inputMonths int64) float64 {
|
||||
var finalDiscount int64 = 100
|
||||
|
||||
for _, discount := range discounts {
|
||||
if inputMonths >= discount.Quantity && discount.Discount < finalDiscount {
|
||||
finalDiscount = discount.Discount
|
||||
}
|
||||
}
|
||||
return float64(finalDiscount) / float64(100)
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
|
||||
"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/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PreCreateOrderLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Pre create order
|
||||
func NewPreCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PreCreateOrderLogic {
|
||||
return &PreCreateOrderLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (resp *types.PreOrderResponse, 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")
|
||||
}
|
||||
// find subscribe plan
|
||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, req.SubscribeId)
|
||||
if err != nil {
|
||||
l.Error("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("subscribe_id", req.SubscribeId))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
|
||||
}
|
||||
var discount float64 = 1
|
||||
if sub.Discount != "" {
|
||||
var dis []types.SubscribeDiscount
|
||||
_ = json.Unmarshal([]byte(sub.Discount), &dis)
|
||||
discount = getDiscount(dis, req.Quantity)
|
||||
}
|
||||
price := sub.UnitPrice * req.Quantity
|
||||
amount := int64(float64(price) * discount)
|
||||
discountAmount := price - amount
|
||||
var coupon int64
|
||||
if req.Coupon != "" {
|
||||
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponNotExist), "coupon not found")
|
||||
}
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find coupon error: %v", err.Error())
|
||||
}
|
||||
if couponInfo.Count > 0 && couponInfo.Count <= couponInfo.UsedCount {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponInsufficientUsage), "coupon used")
|
||||
}
|
||||
couponSub := tool.StringToInt64Slice(couponInfo.Subscribe)
|
||||
if len(couponSub) > 0 && !tool.Contains(couponSub, req.SubscribeId) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponNotApplicable), "coupon not match")
|
||||
}
|
||||
var count int64
|
||||
err = l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
|
||||
return tx.Model(&order.Order{}).Where("user_id = ? and coupon = ?", u.Id, req.Coupon).Count(&count).Error
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorw("[Purchase] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id), logger.Field("coupon", req.Coupon))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find coupon error: %v", err.Error())
|
||||
}
|
||||
if couponInfo.UserLimit > 0 && count >= couponInfo.UserLimit {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponInsufficientUsage), "coupon limit exceeded")
|
||||
}
|
||||
coupon = calculateCoupon(amount, couponInfo)
|
||||
}
|
||||
amount -= coupon
|
||||
|
||||
var deductionAmount int64
|
||||
// Check user deduction amount
|
||||
if u.GiftAmount > 0 {
|
||||
if u.GiftAmount >= amount {
|
||||
deductionAmount = amount
|
||||
amount = 0
|
||||
} else {
|
||||
deductionAmount = u.GiftAmount
|
||||
amount -= u.GiftAmount
|
||||
}
|
||||
}
|
||||
|
||||
payment, err := l.svcCtx.PaymentModel.FindOne(l.ctx, req.Payment)
|
||||
if err != nil {
|
||||
l.Logger.Error("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("payment", req.Payment))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find payment method error: %v", err.Error())
|
||||
}
|
||||
var feeAmount int64
|
||||
// Calculate the handling fee
|
||||
if amount > 0 {
|
||||
feeAmount = calculateFee(amount, payment)
|
||||
}
|
||||
amount += feeAmount
|
||||
|
||||
resp = &types.PreOrderResponse{
|
||||
Price: price,
|
||||
Amount: amount,
|
||||
Discount: discountAmount,
|
||||
GiftAmount: deductionAmount,
|
||||
Coupon: req.Coupon,
|
||||
CouponDiscount: coupon,
|
||||
FeeAmount: feeAmount,
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"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/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
queue "github.com/perfect-panel/server/queue/types"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PurchaseLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
const CloseOrderTimeMinutes = 15
|
||||
|
||||
// purchase Subscription
|
||||
func NewPurchaseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PurchaseLogic {
|
||||
return &PurchaseLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.PurchaseOrderResponse, 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")
|
||||
}
|
||||
// find user subscription
|
||||
|
||||
if l.svcCtx.Config.Subscribe.SingleModel {
|
||||
userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, u.Id)
|
||||
if err != nil {
|
||||
l.Error("[Purchase] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscription error: %v", err.Error())
|
||||
}
|
||||
if len(userSub) > 0 {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserSubscribeExist), "user has subscription")
|
||||
}
|
||||
}
|
||||
|
||||
// find subscribe plan
|
||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, req.SubscribeId)
|
||||
|
||||
if err != nil {
|
||||
l.Error("[Purchase] Database query error", logger.Field("error", err.Error()), logger.Field("subscribe_id", req.SubscribeId))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
|
||||
}
|
||||
// check subscribe plan status
|
||||
if !*sub.Sell {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "subscribe not sell")
|
||||
}
|
||||
var discount float64 = 1
|
||||
if sub.Discount != "" {
|
||||
var dis []types.SubscribeDiscount
|
||||
_ = json.Unmarshal([]byte(sub.Discount), &dis)
|
||||
discount = getDiscount(dis, req.Quantity)
|
||||
}
|
||||
price := sub.UnitPrice * req.Quantity
|
||||
// discount amount
|
||||
amount := int64(float64(price) * discount)
|
||||
discountAmount := price - amount
|
||||
var coupon int64 = 0
|
||||
// Calculate the coupon deduction
|
||||
if req.Coupon != "" {
|
||||
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponNotExist), "coupon not found")
|
||||
}
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find coupon error: %v", err.Error())
|
||||
}
|
||||
if couponInfo.Count <= couponInfo.UsedCount {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponInsufficientUsage), "coupon used")
|
||||
}
|
||||
couponSub := tool.StringToInt64Slice(couponInfo.Subscribe)
|
||||
if len(couponSub) > 0 && !tool.Contains(couponSub, req.SubscribeId) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponNotApplicable), "coupon not match")
|
||||
}
|
||||
var count int64
|
||||
err = l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
|
||||
return tx.Model(&order.Order{}).Where("user_id = ? and coupon = ?", u.Id, req.Coupon).Count(&count).Error
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
l.Errorw("[Purchase] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id), logger.Field("coupon", req.Coupon))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find coupon error: %v", err.Error())
|
||||
}
|
||||
if count >= couponInfo.UserLimit {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponInsufficientUsage), "coupon limit exceeded")
|
||||
}
|
||||
coupon = calculateCoupon(amount, couponInfo)
|
||||
}
|
||||
// Calculate the handling fee
|
||||
amount -= coupon
|
||||
var deductionAmount int64
|
||||
// Check user deduction amount
|
||||
if u.GiftAmount > 0 {
|
||||
if u.GiftAmount >= amount {
|
||||
deductionAmount = amount
|
||||
amount = 0
|
||||
u.GiftAmount -= amount
|
||||
} else {
|
||||
deductionAmount = u.GiftAmount
|
||||
amount -= u.GiftAmount
|
||||
u.GiftAmount = 0
|
||||
}
|
||||
}
|
||||
// find payment method
|
||||
payment, err := l.svcCtx.PaymentModel.FindOne(l.ctx, req.Payment)
|
||||
if err != nil {
|
||||
l.Logger.Error("[Purchase] Database query error", logger.Field("error", err.Error()), logger.Field("payment", req.Payment))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find payment method error: %v", err.Error())
|
||||
}
|
||||
var feeAmount int64
|
||||
// Calculate the handling fee
|
||||
if amount > 0 {
|
||||
feeAmount = calculateFee(amount, payment)
|
||||
}
|
||||
// query user is new purchase or renewal
|
||||
isNew, err := l.svcCtx.OrderModel.IsUserEligibleForNewOrder(l.ctx, u.Id)
|
||||
if err != nil {
|
||||
l.Error("[Purchase] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user order error: %v", err.Error())
|
||||
}
|
||||
// create order
|
||||
orderInfo := &order.Order{
|
||||
UserId: u.Id,
|
||||
OrderNo: tool.GenerateTradeNo(),
|
||||
Type: 1,
|
||||
Quantity: req.Quantity,
|
||||
Price: price,
|
||||
Amount: amount,
|
||||
Discount: discountAmount,
|
||||
GiftAmount: deductionAmount,
|
||||
Coupon: req.Coupon,
|
||||
CouponDiscount: coupon,
|
||||
PaymentId: req.Payment,
|
||||
Method: payment.Platform,
|
||||
FeeAmount: feeAmount,
|
||||
Status: 1,
|
||||
IsNew: isNew,
|
||||
SubscribeId: req.SubscribeId,
|
||||
}
|
||||
// Database transaction
|
||||
err = l.svcCtx.DB.Transaction(func(db *gorm.DB) error {
|
||||
// update user deduction && Pre deduction ,Return after canceling the order
|
||||
if orderInfo.GiftAmount > 0 {
|
||||
// update user deduction && Pre deduction ,Return after canceling the order
|
||||
if e := l.svcCtx.UserModel.Update(l.ctx, u, db); err != nil {
|
||||
l.Error("[Purchase] Database update error", logger.Field("error", err.Error()), logger.Field("user", u))
|
||||
return e
|
||||
}
|
||||
// create deduction record
|
||||
giftAmountLog := user.GiftAmountLog{
|
||||
UserId: orderInfo.UserId,
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
Amount: orderInfo.GiftAmount,
|
||||
Type: 2,
|
||||
Balance: u.GiftAmount,
|
||||
Remark: "Purchase order deduction",
|
||||
}
|
||||
if e := db.Model(&user.GiftAmountLog{}).Create(&giftAmountLog).Error; e != nil {
|
||||
l.Error("[Purchase] Database insert error",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("deductionLog", giftAmountLog),
|
||||
)
|
||||
return e
|
||||
}
|
||||
}
|
||||
// insert order
|
||||
return db.Model(&order.Order{}).Create(&orderInfo).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert order error: %v", err.Error())
|
||||
}
|
||||
// Deferred task
|
||||
payload := queue.DeferCloseOrderPayload{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
}
|
||||
val, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
l.Error("[CreateOrder] Marshal payload error", logger.Field("error", err.Error()), logger.Field("payload", payload))
|
||||
}
|
||||
task := asynq.NewTask(queue.DeferCloseOrder, val, asynq.MaxRetry(3))
|
||||
taskInfo, err := l.svcCtx.Queue.Enqueue(task, asynq.ProcessIn(CloseOrderTimeMinutes*time.Minute))
|
||||
if err != nil {
|
||||
l.Error("[CreateOrder] Enqueue task error", logger.Field("error", err.Error()), logger.Field("task", task))
|
||||
} else {
|
||||
l.Info("[CreateOrder] Enqueue task success", logger.Field("TaskID", taskInfo.ID))
|
||||
}
|
||||
|
||||
return &types.PurchaseOrderResponse{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type QueryOrderDetailLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get order
|
||||
func NewQueryOrderDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryOrderDetailLogic {
|
||||
return &QueryOrderDetailLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryOrderDetailLogic) QueryOrderDetail(req *types.QueryOrderDetailRequest) (resp *types.OrderDetail, err error) {
|
||||
orderInfo, err := l.svcCtx.OrderModel.FindOneDetailsByOrderNo(l.ctx, req.OrderNo)
|
||||
if err != nil {
|
||||
l.Error("[QueryOrderDetail] Database query error", logger.Field("error", err.Error()), logger.Field("order_no", req.OrderNo))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find order error: %v", err.Error())
|
||||
}
|
||||
resp = &types.OrderDetail{}
|
||||
tool.DeepCopy(resp, orderInfo)
|
||||
// Prevent commission amount leakage
|
||||
resp.Commission = 0
|
||||
return
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
|
||||
"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/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type QueryOrderListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get order list
|
||||
func NewQueryOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryOrderListLogic {
|
||||
return &QueryOrderListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryOrderListLogic) QueryOrderList(req *types.QueryOrderListRequest) (resp *types.QueryOrderListResponse, 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")
|
||||
}
|
||||
total, data, err := l.svcCtx.OrderModel.QueryOrderListByPage(l.ctx, req.Page, req.Size, 0, u.Id, 0, "")
|
||||
if err != nil {
|
||||
l.Error("[QueryOrderListLogic] Query order list failed", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query order list failed")
|
||||
}
|
||||
resp = &types.QueryOrderListResponse{
|
||||
Total: total,
|
||||
List: make([]types.OrderDetail, 0),
|
||||
}
|
||||
for _, item := range data {
|
||||
var orderInfo types.OrderDetail
|
||||
tool.DeepCopy(&orderInfo, item)
|
||||
// Prevent commission amount leakage
|
||||
orderInfo.Commission = 0
|
||||
resp.List = append(resp.List, orderInfo)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"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/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
queue "github.com/perfect-panel/server/queue/types"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type RechargeLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewRechargeLogic Recharge
|
||||
func NewRechargeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RechargeLogic {
|
||||
return &RechargeLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *RechargeLogic) Recharge(req *types.RechargeOrderRequest) (resp *types.RechargeOrderResponse, 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")
|
||||
}
|
||||
// find payment method
|
||||
payment, err := l.svcCtx.PaymentModel.FindOne(l.ctx, req.Payment)
|
||||
if err != nil {
|
||||
l.Error("[Recharge] Database query error", logger.Field("error", err.Error()), logger.Field("payment", req.Payment))
|
||||
return nil, errors.Wrapf(err, "find payment error: %v", err.Error())
|
||||
}
|
||||
// Calculate the handling fee
|
||||
feeAmount := calculateFee(req.Amount, payment)
|
||||
// query user is new purchase or renewal
|
||||
isNew, err := l.svcCtx.OrderModel.IsUserEligibleForNewOrder(l.ctx, u.Id)
|
||||
if err != nil {
|
||||
l.Error("[Recharge] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
|
||||
return nil, errors.Wrapf(err, "query user error: %v", err.Error())
|
||||
}
|
||||
orderInfo := order.Order{
|
||||
UserId: u.Id,
|
||||
OrderNo: tool.GenerateTradeNo(),
|
||||
Type: 4,
|
||||
Price: req.Amount,
|
||||
Amount: req.Amount + feeAmount,
|
||||
FeeAmount: feeAmount,
|
||||
PaymentId: req.Payment,
|
||||
Method: payment.Platform,
|
||||
Status: 1,
|
||||
IsNew: isNew,
|
||||
}
|
||||
err = l.svcCtx.OrderModel.Insert(l.ctx, &orderInfo)
|
||||
if err != nil {
|
||||
l.Error("[Recharge] Database insert error", logger.Field("error", err.Error()), logger.Field("order", orderInfo))
|
||||
return nil, errors.Wrapf(err, "insert order error: %v", err.Error())
|
||||
}
|
||||
// Deferred task
|
||||
payload := queue.DeferCloseOrderPayload{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
}
|
||||
val, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
l.Error("[Recharge] Marshal payload error", logger.Field("error", err.Error()), logger.Field("payload", payload))
|
||||
}
|
||||
task := asynq.NewTask(queue.DeferCloseOrder, val, asynq.MaxRetry(3))
|
||||
taskInfo, err := l.svcCtx.Queue.Enqueue(task, asynq.ProcessIn(CloseOrderTimeMinutes*time.Minute))
|
||||
if err != nil {
|
||||
l.Error("[Recharge] Enqueue task error", logger.Field("error", err.Error()), logger.Field("task", task))
|
||||
} else {
|
||||
l.Info("[Recharge] Enqueue task success", logger.Field("TaskID", taskInfo.ID))
|
||||
}
|
||||
return &types.RechargeOrderResponse{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"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/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
queue "github.com/perfect-panel/server/queue/types"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type RenewalLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Renewal Subscription
|
||||
func NewRenewalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RenewalLogic {
|
||||
return &RenewalLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *RenewalLogic) Renewal(req *types.RenewalOrderRequest) (resp *types.RenewalOrderResponse, 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")
|
||||
}
|
||||
orderNo := tool.GenerateTradeNo()
|
||||
// find user subscribe
|
||||
userSubscribe, err := l.svcCtx.UserModel.FindOneUserSubscribe(l.ctx, req.UserSubscribeID)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscribe error: %v", err.Error())
|
||||
}
|
||||
// find subscription
|
||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, userSubscribe.SubscribeId)
|
||||
if err != nil {
|
||||
l.Error("[Renewal] Database query error", logger.Field("error", err.Error()), logger.Field("subscribe_id", userSubscribe.SubscribeId))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
|
||||
}
|
||||
// check subscribe plan status
|
||||
if !*sub.Sell {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "subscribe not sell")
|
||||
}
|
||||
var discount float64 = 1
|
||||
if sub.Discount != "" {
|
||||
var dis []types.SubscribeDiscount
|
||||
_ = json.Unmarshal([]byte(sub.Discount), &dis)
|
||||
discount = getDiscount(dis, req.Quantity)
|
||||
}
|
||||
price := sub.UnitPrice * req.Quantity
|
||||
amount := int64(float64(price) * discount)
|
||||
discountAmount := price - amount
|
||||
var coupon int64 = 0
|
||||
if req.Coupon != "" {
|
||||
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
||||
if err != nil {
|
||||
l.Error("[Renewal] Database query error", logger.Field("error", err.Error()), logger.Field("coupon", req.Coupon))
|
||||
return nil, errors.Wrapf(err, "find coupon error: %v", err.Error())
|
||||
}
|
||||
if couponInfo.Count <= couponInfo.UsedCount {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponInsufficientUsage), "coupon used")
|
||||
}
|
||||
coupon = calculateCoupon(amount, couponInfo)
|
||||
}
|
||||
payment, err := l.svcCtx.PaymentModel.FindOne(l.ctx, req.Payment)
|
||||
if err != nil {
|
||||
l.Error("[Renewal] Database query error", logger.Field("error", err.Error()), logger.Field("payment", req.Payment))
|
||||
return nil, errors.Wrapf(err, "find payment error: %v", err.Error())
|
||||
}
|
||||
amount -= coupon
|
||||
|
||||
var deductionAmount int64
|
||||
// Check user deduction amount
|
||||
if u.GiftAmount > 0 {
|
||||
if u.GiftAmount >= amount {
|
||||
deductionAmount = amount
|
||||
amount = 0
|
||||
u.GiftAmount -= amount
|
||||
} else {
|
||||
deductionAmount = u.GiftAmount
|
||||
amount -= u.GiftAmount
|
||||
u.GiftAmount = 0
|
||||
}
|
||||
}
|
||||
|
||||
var feeAmount int64
|
||||
// Calculate the handling fee
|
||||
if amount > 0 {
|
||||
feeAmount = calculateFee(amount, payment)
|
||||
}
|
||||
|
||||
amount += feeAmount
|
||||
|
||||
// create order
|
||||
orderInfo := order.Order{
|
||||
UserId: u.Id,
|
||||
ParentId: userSubscribe.OrderId,
|
||||
OrderNo: orderNo,
|
||||
Type: 2,
|
||||
Quantity: req.Quantity,
|
||||
Price: price,
|
||||
Amount: amount,
|
||||
GiftAmount: deductionAmount,
|
||||
Discount: discountAmount,
|
||||
Coupon: req.Coupon,
|
||||
CouponDiscount: coupon,
|
||||
PaymentId: payment.Id,
|
||||
Method: payment.Platform,
|
||||
FeeAmount: feeAmount,
|
||||
Status: 1,
|
||||
SubscribeId: userSubscribe.SubscribeId,
|
||||
SubscribeToken: userSubscribe.Token,
|
||||
}
|
||||
// Database transaction
|
||||
err = l.svcCtx.DB.Transaction(func(db *gorm.DB) error {
|
||||
// update user deduction && Pre deduction ,Return after canceling the order
|
||||
if orderInfo.GiftAmount > 0 {
|
||||
// update user deduction && Pre deduction ,Return after canceling the order
|
||||
if err := l.svcCtx.UserModel.Update(l.ctx, u, db); err != nil {
|
||||
l.Error("[Purchase] Database update error", logger.Field("error", err.Error()), logger.Field("user", u))
|
||||
return err
|
||||
}
|
||||
// create deduction record
|
||||
deductionLog := user.GiftAmountLog{
|
||||
UserId: orderInfo.UserId,
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
Amount: orderInfo.GiftAmount,
|
||||
Type: 2,
|
||||
Balance: u.GiftAmount,
|
||||
Remark: "Renewal order deduction",
|
||||
}
|
||||
if err := db.Model(&user.GiftAmountLog{}).Create(&deductionLog).Error; err != nil {
|
||||
l.Error("[Renewal] Database insert error", logger.Field("error", err.Error()), logger.Field("deductionLog", deductionLog))
|
||||
return err
|
||||
}
|
||||
}
|
||||
// insert order
|
||||
return db.Model(&order.Order{}).Create(&orderInfo).Error
|
||||
})
|
||||
if err != nil {
|
||||
l.Error("[Renewal] Database insert error", logger.Field("error", err.Error()), logger.Field("order", orderInfo))
|
||||
return nil, errors.Wrapf(err, "insert order error: %v", err.Error())
|
||||
}
|
||||
// Deferred task
|
||||
payload := queue.DeferCloseOrderPayload{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
}
|
||||
val, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
l.Error("[Renewal] Marshal payload error", logger.Field("error", err.Error()), logger.Field("payload", payload))
|
||||
}
|
||||
task := asynq.NewTask(queue.DeferCloseOrder, val, asynq.MaxRetry(3))
|
||||
taskInfo, err := l.svcCtx.Queue.Enqueue(task, asynq.ProcessIn(CloseOrderTimeMinutes*time.Minute))
|
||||
if err != nil {
|
||||
l.Error("[Renewal] Enqueue task error", logger.Field("error", err.Error()), logger.Field("task", task))
|
||||
} else {
|
||||
l.Info("[Renewal] Enqueue task success", logger.Field("TaskID", taskInfo.ID))
|
||||
}
|
||||
return &types.RenewalOrderResponse{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
queue "github.com/perfect-panel/server/queue/types"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
type ResetTrafficLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Reset traffic
|
||||
func NewResetTrafficLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetTrafficLogic {
|
||||
return &ResetTrafficLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *ResetTrafficLogic) ResetTraffic(req *types.ResetTrafficOrderRequest) (resp *types.ResetTrafficOrderResponse, 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")
|
||||
}
|
||||
// find user subscription
|
||||
userSubscribe, err := l.svcCtx.UserModel.FindOneUserSubscribe(l.ctx, req.UserSubscribeID)
|
||||
if err != nil {
|
||||
l.Error("[ResetTraffic] Database query error", logger.Field("error", err.Error()), logger.Field("UserSubscribeID", req.UserSubscribeID))
|
||||
return nil, errors.Wrapf(err, "find user subscribe error: %v", err.Error())
|
||||
}
|
||||
if userSubscribe.Subscribe == nil {
|
||||
l.Error("[ResetTraffic] subscribe not found", logger.Field("UserSubscribeID", req.UserSubscribeID))
|
||||
return nil, errors.New("subscribe not found")
|
||||
}
|
||||
amount := userSubscribe.Subscribe.Replacement
|
||||
var deductionAmount int64
|
||||
// Check user deduction amount
|
||||
if u.GiftAmount > 0 {
|
||||
if u.GiftAmount >= amount {
|
||||
deductionAmount = amount
|
||||
amount = 0
|
||||
u.GiftAmount -= amount
|
||||
} else {
|
||||
deductionAmount = u.GiftAmount
|
||||
amount -= u.GiftAmount
|
||||
u.GiftAmount = 0
|
||||
}
|
||||
}
|
||||
// find payment method
|
||||
payment, err := l.svcCtx.PaymentModel.FindOne(l.ctx, req.Payment)
|
||||
if err != nil {
|
||||
l.Error("[ResetTraffic] Database query error", logger.Field("error", err.Error()), logger.Field("payment", req.Payment))
|
||||
return nil, errors.Wrapf(err, "find payment error: %v", err.Error())
|
||||
}
|
||||
var feeAmount int64
|
||||
// Calculate the handling fee
|
||||
if amount > 0 {
|
||||
feeAmount = calculateFee(amount, payment)
|
||||
}
|
||||
// create order
|
||||
orderInfo := order.Order{
|
||||
Id: 0,
|
||||
ParentId: userSubscribe.OrderId,
|
||||
UserId: u.Id,
|
||||
OrderNo: tool.GenerateTradeNo(),
|
||||
Type: 3,
|
||||
Price: userSubscribe.Subscribe.Replacement,
|
||||
Amount: amount + feeAmount,
|
||||
GiftAmount: deductionAmount,
|
||||
FeeAmount: feeAmount,
|
||||
PaymentId: req.Payment,
|
||||
Method: payment.Platform,
|
||||
Status: 1,
|
||||
SubscribeId: userSubscribe.SubscribeId,
|
||||
SubscribeToken: userSubscribe.Token,
|
||||
}
|
||||
// Database transaction
|
||||
err = l.svcCtx.DB.Transaction(func(db *gorm.DB) error {
|
||||
// update user deduction && Pre deduction ,Return after canceling the order
|
||||
if orderInfo.GiftAmount > 0 {
|
||||
// update user deduction && Pre deduction ,Return after canceling the order
|
||||
if err := l.svcCtx.UserModel.Update(l.ctx, u, db); err != nil {
|
||||
l.Error("[ResetTraffic] Database update error", logger.Field("error", err.Error()), logger.Field("user", u))
|
||||
return err
|
||||
}
|
||||
// create deduction record
|
||||
deductionLog := user.GiftAmountLog{
|
||||
UserId: orderInfo.UserId,
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
Amount: orderInfo.GiftAmount,
|
||||
Type: 2,
|
||||
Balance: u.GiftAmount,
|
||||
Remark: "ResetTraffic order deduction",
|
||||
}
|
||||
if err := db.Model(&user.GiftAmountLog{}).Create(&deductionLog).Error; err != nil {
|
||||
l.Error("[ResetTraffic] Database insert error", logger.Field("error", err.Error()), logger.Field("deductionLog", deductionLog))
|
||||
return err
|
||||
}
|
||||
}
|
||||
// insert order
|
||||
return db.Model(&order.Order{}).Create(&orderInfo).Error
|
||||
})
|
||||
if err != nil {
|
||||
l.Error("[ResetTraffic] Database insert error", logger.Field("error", err.Error()), logger.Field("order", orderInfo))
|
||||
return nil, errors.Wrapf(err, "insert order error: %v", err.Error())
|
||||
}
|
||||
// Deferred task
|
||||
payload := queue.DeferCloseOrderPayload{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
}
|
||||
val, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
l.Error("[ResetTraffic] Marshal payload error", logger.Field("error", err.Error()), logger.Field("payload", payload))
|
||||
}
|
||||
task := asynq.NewTask(queue.DeferCloseOrder, val, asynq.MaxRetry(3))
|
||||
taskInfo, err := l.svcCtx.Queue.Enqueue(task, asynq.ProcessIn(CloseOrderTimeMinutes*time.Minute))
|
||||
if err != nil {
|
||||
l.Error("[ResetTraffic] Enqueue task error", logger.Field("error", err.Error()), logger.Field("task", task))
|
||||
} else {
|
||||
l.Info("[ResetTraffic] Enqueue task success", logger.Field("TaskID", taskInfo.ID))
|
||||
}
|
||||
return &types.ResetTrafficOrderResponse{
|
||||
OrderNo: orderInfo.OrderNo,
|
||||
}, nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user