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:
@@ -1,3 +1,83 @@
|
||||
package server
|
||||
|
||||
const Unchanged = "Unchanged"
|
||||
const (
|
||||
Unchanged = "Unchanged"
|
||||
ShadowSocks = "shadowsocks"
|
||||
Vmess = "vmess"
|
||||
Vless = "vless"
|
||||
Trojan = "trojan"
|
||||
AnyTLS = "anytls"
|
||||
Tuic = "tuic"
|
||||
Hysteria2 = "hysteria2"
|
||||
)
|
||||
|
||||
type SecurityConfig struct {
|
||||
SNI string `json:"sni"`
|
||||
AllowInsecure *bool `json:"allow_insecure"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
RealityServerAddress string `json:"reality_server_addr"`
|
||||
RealityServerPort int `json:"reality_server_port"`
|
||||
RealityPrivateKey string `json:"reality_private_key"`
|
||||
RealityPublicKey string `json:"reality_public_key"`
|
||||
RealityShortId string `json:"reality_short_id"`
|
||||
RealityMldsa65seed string `json:"reality_mldsa65seed"`
|
||||
}
|
||||
|
||||
type TransportConfig struct {
|
||||
Path string `json:"path"`
|
||||
Host string `json:"host"`
|
||||
ServiceName string `json:"service_name"`
|
||||
DisableSNI bool `json:"disable_sni"`
|
||||
ReduceRtt bool `json:"reduce_rtt"`
|
||||
UDPRelayMode string `json:"udp_relay_mode"`
|
||||
CongestionController string `json:"congestion_controller"`
|
||||
}
|
||||
|
||||
type VlessNode struct {
|
||||
Port uint16 `json:"port"`
|
||||
Flow string `json:"flow"`
|
||||
Network string `json:"transport"`
|
||||
TransportConfig *TransportConfig `json:"transport_config"`
|
||||
Security string `json:"security"`
|
||||
SecurityConfig *SecurityConfig `json:"security_config"`
|
||||
}
|
||||
|
||||
type VmessNode struct {
|
||||
Port uint16 `json:"port"`
|
||||
Network string `json:"transport"`
|
||||
TransportConfig *TransportConfig `json:"transport_config"`
|
||||
Security string `json:"security"`
|
||||
SecurityConfig *SecurityConfig `json:"security_config"`
|
||||
}
|
||||
|
||||
type ShadowsocksNode struct {
|
||||
Port uint16 `json:"port"`
|
||||
Cipher string `json:"method"`
|
||||
ServerKey string `json:"server_key"`
|
||||
}
|
||||
|
||||
type TrojanNode struct {
|
||||
Port uint16 `json:"port"`
|
||||
Network string `json:"transport"`
|
||||
TransportConfig *TransportConfig `json:"transport_config"`
|
||||
Security string `json:"security"`
|
||||
SecurityConfig *SecurityConfig `json:"security_config"`
|
||||
}
|
||||
|
||||
type AnyTLSNode struct {
|
||||
Port uint16 `json:"port"`
|
||||
SecurityConfig *SecurityConfig `json:"security_config"`
|
||||
}
|
||||
|
||||
type TuicNode struct {
|
||||
Port uint16 `json:"port"`
|
||||
SecurityConfig *SecurityConfig `json:"security_config"`
|
||||
}
|
||||
|
||||
type Hysteria2Node struct {
|
||||
Port uint16 `json:"port"`
|
||||
HopPorts string `json:"hop_ports"`
|
||||
HopInterval int `json:"hop_interval"`
|
||||
ObfsPassword string `json:"obfs_password"`
|
||||
SecurityConfig *SecurityConfig `json:"security_config"`
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -21,7 +21,7 @@ type GetServerConfigLogic struct {
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get server config
|
||||
// NewGetServerConfigLogic Get server config
|
||||
func NewGetServerConfigLogic(ctx *gin.Context, svcCtx *svc.ServiceContext) *GetServerConfigLogic {
|
||||
return &GetServerConfigLogic{
|
||||
Logger: logger.WithContext(ctx.Request.Context()),
|
||||
@@ -31,7 +31,7 @@ func NewGetServerConfigLogic(ctx *gin.Context, svcCtx *svc.ServiceContext) *GetS
|
||||
}
|
||||
|
||||
func (l *GetServerConfigLogic) GetServerConfig(req *types.GetServerConfigRequest) (resp *types.GetServerConfigResponse, err error) {
|
||||
cacheKey := fmt.Sprintf("%s%d", config.ServerConfigCacheKey, req.ServerId)
|
||||
cacheKey := fmt.Sprintf("%s%d:%s", node.ServerConfigCacheKey, req.ServerId, req.Protocol)
|
||||
cache, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err == nil {
|
||||
if cache != "" {
|
||||
@@ -42,7 +42,7 @@ func (l *GetServerConfigLogic) GetServerConfig(req *types.GetServerConfigRequest
|
||||
return nil, xerr.StatusNotModified
|
||||
}
|
||||
l.ctx.Header("ETag", etag)
|
||||
resp := &types.GetServerConfigResponse{}
|
||||
resp = &types.GetServerConfigResponse{}
|
||||
err = json.Unmarshal([]byte(cache), resp)
|
||||
if err != nil {
|
||||
l.Errorw("[ServerConfigCacheKey] json unmarshal error", logger.Field("error", err.Error()))
|
||||
@@ -51,21 +51,21 @@ func (l *GetServerConfigLogic) GetServerConfig(req *types.GetServerConfigRequest
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
nodeInfo, err := l.svcCtx.ServerModel.FindOne(l.ctx, req.ServerId)
|
||||
data, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, req.ServerId)
|
||||
if err != nil {
|
||||
l.Errorw("[GetServerConfig] FindOne error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
cfg := make(map[string]interface{})
|
||||
err = json.Unmarshal([]byte(nodeInfo.Config), &cfg)
|
||||
|
||||
protocols, err := data.UnmarshalProtocols()
|
||||
if err != nil {
|
||||
l.Errorw("[GetServerConfig] json unmarshal error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if nodeInfo.Protocol == "shadowsocks" {
|
||||
if value, ok := cfg["server_key"]; ok && value != "" {
|
||||
cfg["server_key"] = base64.StdEncoding.EncodeToString([]byte(value.(string)))
|
||||
var cfg map[string]interface{}
|
||||
for _, protocol := range protocols {
|
||||
if protocol.Type == req.Protocol {
|
||||
cfg = l.compatible(protocol)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,18 +74,162 @@ func (l *GetServerConfigLogic) GetServerConfig(req *types.GetServerConfigRequest
|
||||
PullInterval: l.svcCtx.Config.Node.NodePullInterval,
|
||||
PushInterval: l.svcCtx.Config.Node.NodePushInterval,
|
||||
},
|
||||
Protocol: nodeInfo.Protocol,
|
||||
Protocol: req.Protocol,
|
||||
Config: cfg,
|
||||
}
|
||||
data, err := json.Marshal(resp)
|
||||
c, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
l.Errorw("[GetServerConfig] json marshal error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
etag := tool.GenerateETag(data)
|
||||
etag := tool.GenerateETag(c)
|
||||
l.ctx.Header("ETag", etag)
|
||||
if err = l.svcCtx.Redis.Set(l.ctx, cacheKey, data, -1).Err(); err != nil {
|
||||
if err = l.svcCtx.Redis.Set(l.ctx, cacheKey, c, -1).Err(); err != nil {
|
||||
l.Errorw("[GetServerConfig] redis set error", logger.Field("error", err.Error()))
|
||||
}
|
||||
// Check If-None-Match header
|
||||
match := l.ctx.GetHeader("If-None-Match")
|
||||
if match == etag {
|
||||
return nil, xerr.StatusNotModified
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (l *GetServerConfigLogic) compatible(config node.Protocol) map[string]interface{} {
|
||||
var result interface{}
|
||||
switch config.Type {
|
||||
case ShadowSocks:
|
||||
result = ShadowsocksNode{
|
||||
Port: config.Port,
|
||||
Cipher: config.Cipher,
|
||||
ServerKey: base64.StdEncoding.EncodeToString([]byte(config.ServerKey)),
|
||||
}
|
||||
case Vless:
|
||||
result = VlessNode{
|
||||
Port: config.Port,
|
||||
Flow: config.Flow,
|
||||
Network: config.Transport,
|
||||
TransportConfig: &TransportConfig{
|
||||
Path: config.Path,
|
||||
Host: config.Host,
|
||||
ServiceName: config.ServiceName,
|
||||
DisableSNI: config.DisableSNI,
|
||||
ReduceRtt: config.ReduceRtt,
|
||||
UDPRelayMode: config.UDPRelayMode,
|
||||
CongestionController: config.CongestionController,
|
||||
},
|
||||
Security: config.Security,
|
||||
SecurityConfig: &SecurityConfig{
|
||||
SNI: config.SNI,
|
||||
AllowInsecure: &config.AllowInsecure,
|
||||
Fingerprint: config.Fingerprint,
|
||||
RealityServerAddress: config.RealityServerAddr,
|
||||
RealityServerPort: config.RealityServerPort,
|
||||
RealityPrivateKey: config.RealityPrivateKey,
|
||||
RealityPublicKey: config.RealityPublicKey,
|
||||
RealityShortId: config.RealityShortId,
|
||||
},
|
||||
}
|
||||
case Vmess:
|
||||
result = VmessNode{
|
||||
Port: config.Port,
|
||||
Network: config.Transport,
|
||||
TransportConfig: &TransportConfig{
|
||||
Path: config.Path,
|
||||
Host: config.Host,
|
||||
ServiceName: config.ServiceName,
|
||||
DisableSNI: config.DisableSNI,
|
||||
ReduceRtt: config.ReduceRtt,
|
||||
UDPRelayMode: config.UDPRelayMode,
|
||||
CongestionController: config.CongestionController,
|
||||
},
|
||||
Security: config.Security,
|
||||
SecurityConfig: &SecurityConfig{
|
||||
SNI: config.SNI,
|
||||
AllowInsecure: &config.AllowInsecure,
|
||||
Fingerprint: config.Fingerprint,
|
||||
RealityServerAddress: config.RealityServerAddr,
|
||||
RealityServerPort: config.RealityServerPort,
|
||||
RealityPrivateKey: config.RealityPrivateKey,
|
||||
RealityPublicKey: config.RealityPublicKey,
|
||||
RealityShortId: config.RealityShortId,
|
||||
},
|
||||
}
|
||||
case Trojan:
|
||||
result = TrojanNode{
|
||||
Port: config.Port,
|
||||
Network: config.Transport,
|
||||
TransportConfig: &TransportConfig{
|
||||
Path: config.Path,
|
||||
Host: config.Host,
|
||||
ServiceName: config.ServiceName,
|
||||
DisableSNI: config.DisableSNI,
|
||||
ReduceRtt: config.ReduceRtt,
|
||||
UDPRelayMode: config.UDPRelayMode,
|
||||
CongestionController: config.CongestionController,
|
||||
},
|
||||
Security: config.Security,
|
||||
SecurityConfig: &SecurityConfig{
|
||||
SNI: config.SNI,
|
||||
AllowInsecure: &config.AllowInsecure,
|
||||
Fingerprint: config.Fingerprint,
|
||||
RealityServerAddress: config.RealityServerAddr,
|
||||
RealityServerPort: config.RealityServerPort,
|
||||
RealityPrivateKey: config.RealityPrivateKey,
|
||||
RealityPublicKey: config.RealityPublicKey,
|
||||
RealityShortId: config.RealityShortId,
|
||||
},
|
||||
}
|
||||
case AnyTLS:
|
||||
result = AnyTLSNode{
|
||||
Port: config.Port,
|
||||
SecurityConfig: &SecurityConfig{
|
||||
SNI: config.SNI,
|
||||
AllowInsecure: &config.AllowInsecure,
|
||||
Fingerprint: config.Fingerprint,
|
||||
RealityServerAddress: config.RealityServerAddr,
|
||||
RealityServerPort: config.RealityServerPort,
|
||||
RealityPrivateKey: config.RealityPrivateKey,
|
||||
RealityPublicKey: config.RealityPublicKey,
|
||||
RealityShortId: config.RealityShortId,
|
||||
},
|
||||
}
|
||||
case Tuic:
|
||||
result = TuicNode{
|
||||
Port: config.Port,
|
||||
SecurityConfig: &SecurityConfig{
|
||||
SNI: config.SNI,
|
||||
AllowInsecure: &config.AllowInsecure,
|
||||
Fingerprint: config.Fingerprint,
|
||||
RealityServerAddress: config.RealityServerAddr,
|
||||
RealityServerPort: config.RealityServerPort,
|
||||
RealityPrivateKey: config.RealityPrivateKey,
|
||||
RealityPublicKey: config.RealityPublicKey,
|
||||
RealityShortId: config.RealityShortId,
|
||||
},
|
||||
}
|
||||
case Hysteria2:
|
||||
result = Hysteria2Node{
|
||||
Port: config.Port,
|
||||
HopPorts: config.HopPorts,
|
||||
HopInterval: config.HopInterval,
|
||||
ObfsPassword: config.ObfsPassword,
|
||||
SecurityConfig: &SecurityConfig{
|
||||
SNI: config.SNI,
|
||||
AllowInsecure: &config.AllowInsecure,
|
||||
Fingerprint: config.Fingerprint,
|
||||
RealityServerAddress: config.RealityServerAddr,
|
||||
RealityServerPort: config.RealityServerPort,
|
||||
RealityPrivateKey: config.RealityPrivateKey,
|
||||
RealityPublicKey: config.RealityPublicKey,
|
||||
RealityShortId: config.RealityShortId,
|
||||
},
|
||||
}
|
||||
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
s, _ := json.Marshal(result)
|
||||
_ = json.Unmarshal(s, &resp)
|
||||
return resp
|
||||
}
|
||||
|
||||
@@ -3,10 +3,12 @@ package server
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/model/node"
|
||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -21,7 +23,7 @@ type GetServerUserListLogic struct {
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Get user list
|
||||
// NewGetServerUserListLogic Get user list
|
||||
func NewGetServerUserListLogic(ctx *gin.Context, svcCtx *svc.ServiceContext) *GetServerUserListLogic {
|
||||
return &GetServerUserListLogic{
|
||||
Logger: logger.WithContext(ctx.Request.Context()),
|
||||
@@ -31,30 +33,53 @@ func NewGetServerUserListLogic(ctx *gin.Context, svcCtx *svc.ServiceContext) *Ge
|
||||
}
|
||||
|
||||
func (l *GetServerUserListLogic) GetServerUserList(req *types.GetServerUserListRequest) (resp *types.GetServerUserListResponse, err error) {
|
||||
cacheKey := fmt.Sprintf("%s%d", config.ServerUserListCacheKey, req.ServerId)
|
||||
cacheKey := fmt.Sprintf("%s%d", node.ServerUserListCacheKey, req.ServerId)
|
||||
cache, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
||||
if err == nil {
|
||||
if cache != "" {
|
||||
etag := tool.GenerateETag([]byte(cache))
|
||||
resp := &types.GetServerUserListResponse{}
|
||||
// Check If-None-Match header
|
||||
if match := l.ctx.GetHeader("If-None-Match"); match == etag {
|
||||
return nil, xerr.StatusNotModified
|
||||
}
|
||||
l.ctx.Header("ETag", etag)
|
||||
err = json.Unmarshal([]byte(cache), resp)
|
||||
if err != nil {
|
||||
l.Errorw("[ServerUserListCacheKey] json unmarshal error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
return resp, nil
|
||||
if cache != "" {
|
||||
etag := tool.GenerateETag([]byte(cache))
|
||||
resp = &types.GetServerUserListResponse{}
|
||||
// Check If-None-Match header
|
||||
if match := l.ctx.GetHeader("If-None-Match"); match == etag {
|
||||
return nil, xerr.StatusNotModified
|
||||
}
|
||||
l.ctx.Header("ETag", etag)
|
||||
err = json.Unmarshal([]byte(cache), resp)
|
||||
if err != nil {
|
||||
l.Errorw("[ServerUserListCacheKey] json unmarshal error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
server, err := l.svcCtx.ServerModel.FindOne(l.ctx, req.ServerId)
|
||||
server, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, req.ServerId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
subs, err := l.svcCtx.SubscribeModel.QuerySubscribeIdsByServerIdAndServerGroupId(l.ctx, server.Id, server.GroupId)
|
||||
|
||||
_, nodes, err := l.svcCtx.NodeModel.FilterNodeList(l.ctx, &node.FilterNodeParams{
|
||||
Page: 1,
|
||||
Size: 1000,
|
||||
ServerId: []int64{server.Id},
|
||||
Protocol: req.Protocol,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("FilterNodeList error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
var nodeTag []string
|
||||
var nodeIds []int64
|
||||
for _, n := range nodes {
|
||||
nodeIds = append(nodeIds, n.Id)
|
||||
if n.Tags != "" {
|
||||
nodeTag = append(nodeTag, strings.Split(n.Tags, ",")...)
|
||||
}
|
||||
}
|
||||
|
||||
_, subs, err := l.svcCtx.SubscribeModel.FilterList(l.ctx, &subscribe.FilterParams{
|
||||
Page: 1,
|
||||
Size: 9999,
|
||||
Node: nodeIds,
|
||||
Tags: nodeTag,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("QuerySubscribeIdsByServerIdAndServerGroupId error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
@@ -76,16 +101,10 @@ func (l *GetServerUserListLogic) GetServerUserList(req *types.GetServerUserListR
|
||||
return nil, err
|
||||
}
|
||||
for _, datum := range data {
|
||||
speedLimit := server.SpeedLimit
|
||||
if (int(sub.SpeedLimit) < server.SpeedLimit && sub.SpeedLimit != 0) ||
|
||||
(int(sub.SpeedLimit) > server.SpeedLimit && sub.SpeedLimit == 0) {
|
||||
speedLimit = int(sub.SpeedLimit)
|
||||
}
|
||||
|
||||
users = append(users, types.ServerUser{
|
||||
Id: datum.Id,
|
||||
UUID: datum.UUID,
|
||||
SpeedLimit: int64(speedLimit),
|
||||
SpeedLimit: sub.SpeedLimit,
|
||||
DeviceLimit: sub.DeviceLimit,
|
||||
})
|
||||
}
|
||||
@@ -106,5 +125,9 @@ func (l *GetServerUserListLogic) GetServerUserList(req *types.GetServerUserListR
|
||||
if err != nil {
|
||||
l.Errorw("[ServerUserListCacheKey] redis set error", logger.Field("error", err.Error()))
|
||||
}
|
||||
// Check If-None-Match header
|
||||
if match := l.ctx.GetHeader("If-None-Match"); match == etag {
|
||||
return nil, xerr.StatusNotModified
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/cache"
|
||||
"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"
|
||||
@@ -40,26 +40,30 @@ func (l *PushOnlineUsersLogic) PushOnlineUsers(req *types.OnlineUsersRequest) er
|
||||
}
|
||||
|
||||
// Find server info
|
||||
_, err := l.svcCtx.ServerModel.FindOne(l.ctx, req.ServerId)
|
||||
_, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, req.ServerId)
|
||||
if err != nil {
|
||||
l.Errorw("[PushOnlineUsers] FindOne error", logger.Field("error", err))
|
||||
return fmt.Errorf("server not found: %w", err)
|
||||
}
|
||||
|
||||
userOnlineIp := make([]cache.NodeOnlineUser, 0)
|
||||
onlineUsers := make(node.OnlineUserSubscribe)
|
||||
for _, user := range req.Users {
|
||||
userOnlineIp = append(userOnlineIp, cache.NodeOnlineUser{
|
||||
SID: user.SID,
|
||||
IP: user.IP,
|
||||
})
|
||||
if online, ok := onlineUsers[user.SID]; ok {
|
||||
// If user already exists, update IP if different
|
||||
online = append(online, user.IP)
|
||||
onlineUsers[user.SID] = online
|
||||
} else {
|
||||
// New user, add to map
|
||||
onlineUsers[user.SID] = []string{user.IP}
|
||||
}
|
||||
}
|
||||
err = l.svcCtx.NodeCache.AddOnlineUserIP(l.ctx, userOnlineIp)
|
||||
err = l.svcCtx.NodeModel.UpdateOnlineUserSubscribe(l.ctx, req.ServerId, req.Protocol, onlineUsers)
|
||||
if err != nil {
|
||||
l.Errorw("[PushOnlineUsers] cache operation error", logger.Field("error", err))
|
||||
return err
|
||||
}
|
||||
|
||||
err = l.svcCtx.NodeCache.UpdateNodeOnlineUser(l.ctx, req.ServerId, userOnlineIp)
|
||||
err = l.svcCtx.NodeModel.UpdateOnlineUserSubscribeGlobal(l.ctx, onlineUsers)
|
||||
|
||||
if err != nil {
|
||||
l.Errorw("[PushOnlineUsers] cache operation error", logger.Field("error", err))
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
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 QueryServerProtocolConfigLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewQueryServerProtocolConfigLogic Get Server Protocol Config
|
||||
func NewQueryServerProtocolConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryServerProtocolConfigLogic {
|
||||
return &QueryServerProtocolConfigLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryServerProtocolConfigLogic) QueryServerProtocolConfig(req *types.QueryServerConfigRequest) (resp *types.QueryServerConfigResponse, err error) {
|
||||
// find server
|
||||
data, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, req.ServerID)
|
||||
if err != nil {
|
||||
l.Errorf("[GetServerProtocols] FindOneServer Error: %s", err.Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// handler protocols
|
||||
var protocols []types.Protocol
|
||||
dst, err := data.UnmarshalProtocols()
|
||||
if err != nil {
|
||||
l.Errorf("[FilterServerList] UnmarshalProtocols Error: %s", err.Error())
|
||||
return nil, err
|
||||
}
|
||||
tool.DeepCopy(&protocols, dst)
|
||||
|
||||
return &types.QueryServerConfigResponse{
|
||||
Protocols: protocols,
|
||||
}, nil
|
||||
}
|
||||
@@ -3,8 +3,9 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/cache"
|
||||
"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"
|
||||
@@ -16,7 +17,7 @@ type ServerPushStatusLogic struct {
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// Push server status
|
||||
// NewServerPushStatusLogic Push server status
|
||||
func NewServerPushStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ServerPushStatusLogic {
|
||||
return &ServerPushStatusLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
@@ -27,12 +28,12 @@ func NewServerPushStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *
|
||||
|
||||
func (l *ServerPushStatusLogic) ServerPushStatus(req *types.ServerPushStatusRequest) error {
|
||||
// Find server info
|
||||
serverInfo, err := l.svcCtx.ServerModel.FindOne(l.ctx, req.ServerId)
|
||||
serverInfo, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, req.ServerId)
|
||||
if err != nil || serverInfo.Id <= 0 {
|
||||
l.Errorw("[PushOnlineUsers] FindOne error", logger.Field("error", err))
|
||||
return errors.New("server not found")
|
||||
}
|
||||
err = l.svcCtx.NodeCache.UpdateNodeStatus(l.ctx, req.ServerId, cache.NodeStatus{
|
||||
err = l.svcCtx.NodeModel.UpdateStatusCache(l.ctx, req.ServerId, &node.Status{
|
||||
Cpu: req.Cpu,
|
||||
Mem: req.Mem,
|
||||
Disk: req.Disk,
|
||||
@@ -42,5 +43,14 @@ func (l *ServerPushStatusLogic) ServerPushStatus(req *types.ServerPushStatusRequ
|
||||
l.Errorw("[ServerPushStatus] UpdateNodeStatus error", logger.Field("error", err))
|
||||
return errors.New("update node status failed")
|
||||
}
|
||||
now := time.Now()
|
||||
serverInfo.LastReportedAt = &now
|
||||
|
||||
err = l.svcCtx.NodeModel.UpdateServer(l.ctx, serverInfo)
|
||||
if err != nil {
|
||||
l.Errorw("[ServerPushStatus] UpdateServer error", logger.Field("error", err))
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3,9 +3,9 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/server/internal/model/cache"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -32,7 +32,7 @@ func NewServerPushUserTrafficLogic(ctx context.Context, svcCtx *svc.ServiceConte
|
||||
|
||||
func (l *ServerPushUserTrafficLogic) ServerPushUserTraffic(req *types.ServerPushUserTrafficRequest) error {
|
||||
// Find server info
|
||||
serverInfo, err := l.svcCtx.ServerModel.FindOne(l.ctx, req.ServerId)
|
||||
serverInfo, err := l.svcCtx.NodeModel.FindOneServer(l.ctx, req.ServerId)
|
||||
if err != nil {
|
||||
l.Errorw("[PushOnlineUsers] FindOne error", logger.Field("error", err))
|
||||
return errors.New("server not found")
|
||||
@@ -40,23 +40,9 @@ func (l *ServerPushUserTrafficLogic) ServerPushUserTraffic(req *types.ServerPush
|
||||
|
||||
// Create traffic task
|
||||
var request task.TrafficStatistics
|
||||
var userTraffic []cache.UserTraffic
|
||||
request.ServerId = serverInfo.Id
|
||||
tool.DeepCopy(&request.Logs, req.Traffic)
|
||||
tool.DeepCopy(&userTraffic, req.Traffic)
|
||||
|
||||
// update today traffic rank
|
||||
err = l.svcCtx.NodeCache.AddNodeTodayTraffic(l.ctx, serverInfo.Id, userTraffic)
|
||||
if err != nil {
|
||||
l.Errorw("[ServerPushUserTraffic] AddNodeTodayTraffic error", logger.Field("error", err))
|
||||
return errors.New("add node today traffic error")
|
||||
}
|
||||
for _, user := range req.Traffic {
|
||||
if err = l.svcCtx.NodeCache.AddUserTodayTraffic(l.ctx, user.SID, user.Upload, user.Download); err != nil {
|
||||
l.Errorw("[ServerPushUserTraffic] AddUserTodayTraffic error", logger.Field("error", err))
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Push traffic task
|
||||
val, _ := json.Marshal(request)
|
||||
t := asynq.NewTask(task.ForthwithTrafficStatistics, val, asynq.MaxRetry(3))
|
||||
@@ -66,5 +52,15 @@ func (l *ServerPushUserTrafficLogic) ServerPushUserTraffic(req *types.ServerPush
|
||||
} else {
|
||||
l.Infow("[ServerPushUserTraffic] Push traffic task success", logger.Field("task", t), logger.Field("info", info))
|
||||
}
|
||||
|
||||
// Update server last reported time
|
||||
now := time.Now()
|
||||
serverInfo.LastReportedAt = &now
|
||||
|
||||
err = l.svcCtx.NodeModel.UpdateServer(l.ctx, serverInfo)
|
||||
if err != nil {
|
||||
l.Errorw("[ServerPushUserTraffic] UpdateServer error", logger.Field("error", err))
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user