2024-06-13 17:06:23 +08:00
|
|
|
|
package cron_task
|
2024-06-13 14:34:03 +08:00
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"gitee.ltd/lxh/logger/log"
|
|
|
|
|
"strings"
|
|
|
|
|
"time"
|
|
|
|
|
"wireguard-dashboard/client"
|
|
|
|
|
"wireguard-dashboard/repository"
|
|
|
|
|
"wireguard-dashboard/utils"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// offlineMonitoring
|
|
|
|
|
// @description: 离线监听任务
|
|
|
|
|
func offlineMonitoring() {
|
2024-06-14 08:45:16 +08:00
|
|
|
|
devices, err := client.WireguardClient.Devices()
|
|
|
|
|
if err != nil {
|
|
|
|
|
time.Sleep(5 * time.Minute) // 休眠五分钟再执行
|
|
|
|
|
offlineMonitoring()
|
|
|
|
|
return
|
|
|
|
|
}
|
2024-06-13 14:34:03 +08:00
|
|
|
|
|
2024-06-14 08:45:16 +08:00
|
|
|
|
// 遍历客户端数据,并渲染数据信息
|
|
|
|
|
for _, d := range devices {
|
|
|
|
|
for _, p := range d.Peers {
|
|
|
|
|
clientInfo, err := repository.Client().GetByPublicKey(p.PublicKey.String())
|
|
|
|
|
if err != nil {
|
|
|
|
|
continue
|
|
|
|
|
}
|
2024-06-13 14:34:03 +08:00
|
|
|
|
|
2024-06-14 08:45:16 +08:00
|
|
|
|
// 没有启用离线监听时,即使客户端已经离线则也不执行
|
|
|
|
|
if clientInfo.OfflineMonitoring == nil || *clientInfo.OfflineMonitoring != 1 || clientInfo.Email == "" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
2024-06-13 14:34:03 +08:00
|
|
|
|
|
2024-06-14 08:45:16 +08:00
|
|
|
|
var ipAllocation string
|
|
|
|
|
for _, iaip := range p.AllowedIPs {
|
|
|
|
|
ipAllocation += iaip.String() + ","
|
|
|
|
|
}
|
|
|
|
|
ipAllocation = strings.TrimRight(ipAllocation, ",")
|
|
|
|
|
isOnline := time.Since(p.LastHandshakeTime).Minutes() < 3
|
2024-06-13 14:34:03 +08:00
|
|
|
|
|
2024-06-14 08:45:16 +08:00
|
|
|
|
// 未离线
|
2024-06-14 13:43:40 +08:00
|
|
|
|
if isOnline {
|
2024-06-14 08:45:16 +08:00
|
|
|
|
continue
|
|
|
|
|
}
|
2024-06-13 14:34:03 +08:00
|
|
|
|
|
2024-06-14 08:45:16 +08:00
|
|
|
|
content := fmt.Sprintf("客户端:%s\r\n", clientInfo.Name)
|
|
|
|
|
content += fmt.Sprintf("客户端IP:%s\r\n", ipAllocation)
|
|
|
|
|
content += fmt.Sprintf("端点IP:%s\r\n", p.Endpoint.String())
|
|
|
|
|
content += fmt.Sprintf("最后握手时间:%s\r\n", p.LastHandshakeTime.Format("2006-01-02 15:04:05"))
|
2024-06-13 14:34:03 +08:00
|
|
|
|
|
2024-06-14 08:45:16 +08:00
|
|
|
|
// 离线并且配置了邮箱,准备发送邮件
|
2024-06-14 13:43:40 +08:00
|
|
|
|
err = utils.Mail().SendMail(clientInfo.Email, fmt.Sprintf("客户端[%s]离线通知", clientInfo.Name), content, "")
|
2024-06-14 08:45:16 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
log.Errorf("发送离线通知邮件失败: %v", err.Error())
|
|
|
|
|
continue
|
2024-06-13 14:34:03 +08:00
|
|
|
|
}
|
2024-06-14 08:45:16 +08:00
|
|
|
|
|
2024-06-13 14:34:03 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
2024-06-14 08:45:16 +08:00
|
|
|
|
|
2024-06-13 14:34:03 +08:00
|
|
|
|
}
|