wireguard-dashboard/http/api/dashboard.go
coward 4fa123baa8
All checks were successful
continuous-integration/drone/tag Build is passing
🎨优化一下子
2024-08-22 14:16:33 +08:00

103 lines
2.4 KiB
Go

package api
import (
"fmt"
"github.com/gin-gonic/gin"
"strings"
"time"
"wireguard-ui/component"
"wireguard-ui/http/param"
"wireguard-ui/http/response"
"wireguard-ui/http/vo"
"wireguard-ui/service"
"wireguard-ui/utils"
)
type DashboardApi struct{}
func Dashboard() DashboardApi {
return DashboardApi{}
}
// List
// @description: 操作日志
// @receiver DashboardApi
// @param c
func (DashboardApi) List(c *gin.Context) {
var p param.Page
if err := c.ShouldBind(&p); err != nil {
response.R(c).Validator(err)
return
}
var loginUser *vo.User
if loginUser = GetCurrentLoginUser(c); c.IsAborted() {
return
}
data, total, err := service.Log().List(p, loginUser)
if err != nil {
response.R(c).FailedWithError(fmt.Errorf("获取操作日志失败: %v", err.Error()))
return
}
response.R(c).Paginate(data, total, p.Current, p.Size)
}
// DailyPoetry
// @description: 每日诗词
// @receiver DashboardApi
// @param c
func (DashboardApi) DailyPoetry(c *gin.Context) {
data, err := utils.DailyPoetry().HitokotoPoetry()
if err != nil {
response.R(c).FailedWithError("获取失败")
return
}
response.R(c).OkWithData(data)
}
// ConnectionList
// @description: 客户端链接信息列表
// @receiver DashboardApi
// @param c
func (DashboardApi) ConnectionList(c *gin.Context) {
peers, err := component.Wireguard().GetClients()
if err != nil {
response.R(c).FailedWithError("获取失败")
return
}
var connections []vo.DataTraffic
for _, peer := range peers {
// 获取客户端链接信息
clientInfo, err := service.Client().GetByPublicKey(peer.PublicKey.String())
if err != nil {
continue
}
var ipAllocation string
for _, iaip := range peer.AllowedIPs {
ipAllocation += iaip.String() + ","
}
// 去除一下最右边的逗号
if len(ipAllocation) > 0 {
ipAllocation = strings.TrimRight(ipAllocation, ",")
}
connections = append(connections, vo.DataTraffic{
Name: clientInfo.Name,
Email: clientInfo.Email,
IpAllocation: ipAllocation,
Online: time.Since(peer.LastHandshakeTime).Minutes() < 3,
ReceiveBytes: utils.FlowCalculation().Parse(peer.TransmitBytes),
TransmitBytes: utils.FlowCalculation().Parse(peer.ReceiveBytes),
ConnectEndpoint: peer.Endpoint.String(),
LastHandAt: peer.LastHandshakeTime.Format("2006-01-02 15:04:05"),
})
}
if len(connections) <= 0 {
connections = []vo.DataTraffic{}
}
response.R(c).OkWithData(connections)
}