feat: add message push function call
This commit is contained in:
@@ -34,6 +34,7 @@ const (
|
||||
SectionSystem = "system"
|
||||
SectionScheduler = "scheduler"
|
||||
SectionSecurity = "security"
|
||||
SectionNotify = "notify"
|
||||
|
||||
// Site Settings Key 常量
|
||||
KeyTitle = "title"
|
||||
@@ -54,6 +55,25 @@ const (
|
||||
KeyQueueSize = "queue_size"
|
||||
KeyRateInterval = "rate_interval"
|
||||
|
||||
// Notify Settings Key 常量
|
||||
KeyNotifyChannels = "channels"
|
||||
KeyNotifyEvents = "events"
|
||||
KeyNotifyToken = "notify_token"
|
||||
|
||||
// 事件绑定类型
|
||||
BindingTypeSystem = "system"
|
||||
BindingTypeTask = "task"
|
||||
|
||||
// 系统事件类型
|
||||
EventUserLogin = "user_login"
|
||||
EventBruteForceLogin = "brute_force_login"
|
||||
EventPasswordChanged = "password_changed"
|
||||
|
||||
// 任务事件类型
|
||||
EventTaskSuccess = "task_success"
|
||||
EventTaskFailed = "task_failed"
|
||||
EventTaskTimeout = "task_timeout"
|
||||
|
||||
// WebSocket 消息类型
|
||||
WSTypeHeartbeat = "heartbeat"
|
||||
WSTypeHeartbeatAck = "heartbeat_ack"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -54,6 +55,10 @@ func (ac *AuthController) Login(c *gin.Context) {
|
||||
attempt := val.(*loginAttempt)
|
||||
if attempt.Count >= 5 && time.Since(attempt.LastAttempt) < time.Minute {
|
||||
ac.loginLogService.Create(req.Username, ip, userAgent, "failed", "尝试次数过多,请一分钟后再试")
|
||||
go services.NewNotificationService().TriggerEvent(constant.BindingTypeSystem, constant.EventBruteForceLogin, "", map[string]interface{}{
|
||||
"ip": ip,
|
||||
"username": req.Username,
|
||||
})
|
||||
utils.TooManyRequests(c, "尝试次数过多,请一分钟后再试")
|
||||
return
|
||||
}
|
||||
@@ -102,6 +107,11 @@ func (ac *AuthController) Login(c *gin.Context) {
|
||||
// 记录登录成功日志
|
||||
ac.loginLogService.Create(req.Username, ip, userAgent, "success", "登录成功")
|
||||
|
||||
go services.NewNotificationService().TriggerEvent(constant.BindingTypeSystem, constant.EventUserLogin, "", map[string]interface{}{
|
||||
"ip": ip,
|
||||
"username": req.Username,
|
||||
})
|
||||
|
||||
utils.Success(c, gin.H{
|
||||
"user": user.Username,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/engigu/baihu-panel/internal/models"
|
||||
"github.com/engigu/baihu-panel/internal/services"
|
||||
"github.com/engigu/baihu-panel/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type NotificationController struct {
|
||||
notifyService *services.NotificationService
|
||||
}
|
||||
|
||||
func NewNotificationController() *NotificationController {
|
||||
return &NotificationController{
|
||||
notifyService: services.NewNotificationService(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetChannelTypes 获取支持的渠道类型
|
||||
func (nc *NotificationController) GetChannelTypes(c *gin.Context) {
|
||||
utils.Success(c, gin.H{
|
||||
"channel_types": services.SupportedChannelTypes,
|
||||
"event_types": services.SupportedEvents,
|
||||
})
|
||||
}
|
||||
|
||||
// GetChannels 获取所有渠道
|
||||
func (nc *NotificationController) GetChannels(c *gin.Context) {
|
||||
channels := nc.notifyService.GetChannels()
|
||||
utils.Success(c, channels)
|
||||
}
|
||||
|
||||
// SaveChannel 保存/更新渠道
|
||||
func (nc *NotificationController) SaveChannel(c *gin.Context) {
|
||||
var req services.NotifyChannel
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name == "" || req.Type == "" {
|
||||
utils.BadRequest(c, "渠道名称和类型不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
if err := nc.notifyService.SaveChannel(req); err != nil {
|
||||
utils.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
utils.SuccessMsg(c, "保存成功")
|
||||
}
|
||||
|
||||
// DeleteChannel 删除渠道
|
||||
func (nc *NotificationController) DeleteChannel(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
utils.BadRequest(c, "缺少渠道ID")
|
||||
return
|
||||
}
|
||||
|
||||
if err := nc.notifyService.DeleteChannel(id); err != nil {
|
||||
utils.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
utils.SuccessMsg(c, "删除成功")
|
||||
}
|
||||
|
||||
// TestChannel 测试渠道
|
||||
func (nc *NotificationController) TestChannel(c *gin.Context) {
|
||||
var req services.NotifyChannel
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
result := nc.notifyService.SendToChannel(req, &services.NotifyMessage{
|
||||
Title: "🔔 白虎面板测试通知",
|
||||
Text: "如果你看到这条消息,说明通知渠道配置正确!",
|
||||
})
|
||||
|
||||
utils.Success(c, result)
|
||||
}
|
||||
|
||||
|
||||
// GetBindings 获取事件绑定列表
|
||||
func (nc *NotificationController) GetBindings(c *gin.Context) {
|
||||
bindings := nc.notifyService.GetBindings()
|
||||
utils.Success(c, bindings)
|
||||
}
|
||||
|
||||
// SaveBinding 保存事件绑定
|
||||
func (nc *NotificationController) SaveBinding(c *gin.Context) {
|
||||
var req struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Event string `json:"event"`
|
||||
WayID string `json:"way_id"`
|
||||
DataID string `json:"data_id"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
if req.Type == "" || req.Event == "" || req.WayID == "" {
|
||||
utils.BadRequest(c, "类型、事件和渠道ID不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
binding := &models.NotifyBinding{
|
||||
ID: req.ID,
|
||||
Type: req.Type,
|
||||
Event: req.Event,
|
||||
WayID: req.WayID,
|
||||
DataID: req.DataID,
|
||||
}
|
||||
|
||||
if err := nc.notifyService.SaveBinding(binding); err != nil {
|
||||
utils.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
utils.Success(c, binding)
|
||||
}
|
||||
|
||||
// DeleteBinding 删除事件绑定
|
||||
func (nc *NotificationController) DeleteBinding(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
utils.BadRequest(c, "缺少绑定ID")
|
||||
return
|
||||
}
|
||||
|
||||
if err := nc.notifyService.DeleteBinding(id); err != nil {
|
||||
utils.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
utils.SuccessMsg(c, "删除成功")
|
||||
}
|
||||
|
||||
// SendNotification API 发送通知(供脚本调用)
|
||||
func (nc *NotificationController) SendNotification(c *gin.Context) {
|
||||
var req struct {
|
||||
ChannelID string `json:"channel_id"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
if req.ChannelID == "" || req.Title == "" {
|
||||
utils.BadRequest(c, "channel_id 和 title 不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
result := nc.notifyService.SendByChannelID(req.ChannelID, &services.NotifyMessage{
|
||||
Title: req.Title,
|
||||
Text: req.Text,
|
||||
})
|
||||
|
||||
utils.Success(c, result)
|
||||
}
|
||||
@@ -76,6 +76,10 @@ func (sc *SettingsController) ChangePassword(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
go services.NewNotificationService().TriggerEvent(constant.BindingTypeSystem, constant.EventPasswordChanged, "", map[string]interface{}{
|
||||
"username": user.Username,
|
||||
})
|
||||
|
||||
utils.SuccessMsg(c, "密码修改成功")
|
||||
}
|
||||
|
||||
@@ -373,3 +377,39 @@ func (sc *SettingsController) RestoreBackup(c *gin.Context) {
|
||||
|
||||
utils.SuccessMsg(c, "恢复成功")
|
||||
}
|
||||
|
||||
// GetSetting 获取单个设置值
|
||||
func (sc *SettingsController) GetSetting(c *gin.Context) {
|
||||
section := c.Param("section")
|
||||
key := c.Param("key")
|
||||
|
||||
if section == "" || key == "" {
|
||||
utils.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
value := sc.settingsService.Get(section, key)
|
||||
utils.Success(c, value)
|
||||
}
|
||||
|
||||
// GenerateSettingToken 为指定设置生成随机token
|
||||
func (sc *SettingsController) GenerateSettingToken(c *gin.Context) {
|
||||
section := c.Param("section")
|
||||
key := c.Param("key")
|
||||
|
||||
if section == "" || key == "" {
|
||||
utils.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
// 生成32位随机token
|
||||
token := strings.ToLower(utils.RandomString(32))
|
||||
|
||||
// 保存到数据库
|
||||
if err := sc.settingsService.Set(section, key, token); err != nil {
|
||||
utils.ServerError(c, "保存失败")
|
||||
return
|
||||
}
|
||||
|
||||
utils.Success(c, token)
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ func Migrate() error {
|
||||
&models.Agent{},
|
||||
&models.AgentToken{},
|
||||
&models.Language{},
|
||||
&models.NotifyWay{},
|
||||
&models.NotifyBinding{},
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/engigu/baihu-panel/internal/constant"
|
||||
"github.com/engigu/baihu-panel/internal/services"
|
||||
"github.com/engigu/baihu-panel/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// NotifyTokenAuth 通知 Token 认证中间件
|
||||
func NotifyTokenAuth() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token := c.GetHeader("notify-token")
|
||||
if token == "" {
|
||||
utils.Unauthorized(c, "缺少通知 Token")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 从 settings 表读取配置的通知 Token
|
||||
settingsService := services.NewSettingsService()
|
||||
savedToken := settingsService.Get(constant.SectionNotify, constant.KeyNotifyToken)
|
||||
|
||||
if savedToken == "" {
|
||||
utils.Unauthorized(c, "通知 Token 未配置")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if token != savedToken {
|
||||
utils.Unauthorized(c, "通知 Token 无效")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/engigu/baihu-panel/internal/constant"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// NotifyBinding 事件绑定表
|
||||
type NotifyBinding struct {
|
||||
ID string `json:"id" gorm:"primaryKey;size:20"`
|
||||
Type string `json:"type" gorm:"size:20;not null;index"` // system 或 task
|
||||
Event string `json:"event" gorm:"size:50;not null;index"` // 事件类型
|
||||
WayID string `json:"way_id" gorm:"size:20;not null;index"` // 通知渠道ID
|
||||
DataID string `json:"data_id" gorm:"size:20;index"` // 关联ID,系统事件为空,任务事件为任务ID
|
||||
CreatedAt LocalTime `json:"created_at"`
|
||||
UpdatedAt LocalTime `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
|
||||
}
|
||||
|
||||
func (NotifyBinding) TableName() string {
|
||||
return constant.TablePrefix + "notify_bindings"
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/engigu/baihu-panel/internal/constant"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// NotifyWay 消息推送渠道
|
||||
type NotifyWay struct {
|
||||
ID string `json:"id" gorm:"primaryKey;size:20"`
|
||||
Name string `json:"name" gorm:"size:100;not null"`
|
||||
Type string `json:"type" gorm:"size:50;not null;index"`
|
||||
Config string `json:"config" gorm:"type:text"`
|
||||
Enabled bool `json:"enabled" gorm:"default:true;index"`
|
||||
CreatedAt LocalTime `json:"created_at"`
|
||||
UpdatedAt LocalTime `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
|
||||
}
|
||||
|
||||
func (NotifyWay) TableName() string {
|
||||
return constant.TablePrefix + "notify_ways"
|
||||
}
|
||||
+16
-15
@@ -30,7 +30,7 @@ func RegisterControllers() *Controllers {
|
||||
// 清理 task 运行状态的任务可以直接由 executorService 承担或在此处通过 Database 直接清理
|
||||
// 简单期间,我们使用一个新方法 tasks.CleanupRunningTasks() 或者让 executorService 启动时清理
|
||||
|
||||
executorService = tasks.NewExecutorService(taskService, taskLogService, agentWSManager, settingsService, envService)
|
||||
executorService = tasks.NewExecutorService(taskService, taskLogService, agentWSManager, settingsService, envService, services.NewNotificationService())
|
||||
// 启动时清理残留的运行状态
|
||||
_ = executorService.CleanupRunningTasks()
|
||||
|
||||
@@ -39,20 +39,21 @@ func RegisterControllers() *Controllers {
|
||||
|
||||
// 初始化并返回控制器
|
||||
return &Controllers{
|
||||
Task: controllers.NewTaskController(taskService, executorService),
|
||||
Auth: controllers.NewAuthController(userService, settingsService, loginLogService),
|
||||
Env: controllers.NewEnvController(envService),
|
||||
Script: controllers.NewScriptController(scriptService),
|
||||
Executor: controllers.NewExecutorController(executorService),
|
||||
File: controllers.NewFileController(constant.ScriptsWorkDir),
|
||||
Dashboard: controllers.NewDashboardController(executorService),
|
||||
Log: controllers.NewLogController(),
|
||||
LogWS: controllers.NewLogWSController(),
|
||||
Terminal: controllers.NewTerminalController(envService),
|
||||
Settings: controllers.NewSettingsController(userService, loginLogService, executorService),
|
||||
Dependency: controllers.NewDependencyController(),
|
||||
Agent: controllers.NewAgentController(settingsService),
|
||||
Mise: controllers.NewMiseController(services.NewMiseService()),
|
||||
Task: controllers.NewTaskController(taskService, executorService),
|
||||
Auth: controllers.NewAuthController(userService, settingsService, loginLogService),
|
||||
Env: controllers.NewEnvController(envService),
|
||||
Script: controllers.NewScriptController(scriptService),
|
||||
Executor: controllers.NewExecutorController(executorService),
|
||||
File: controllers.NewFileController(constant.ScriptsWorkDir),
|
||||
Dashboard: controllers.NewDashboardController(executorService),
|
||||
Log: controllers.NewLogController(),
|
||||
LogWS: controllers.NewLogWSController(),
|
||||
Terminal: controllers.NewTerminalController(envService),
|
||||
Settings: controllers.NewSettingsController(userService, loginLogService, executorService),
|
||||
Dependency: controllers.NewDependencyController(),
|
||||
Agent: controllers.NewAgentController(settingsService),
|
||||
Mise: controllers.NewMiseController(services.NewMiseService()),
|
||||
Notification: controllers.NewNotificationController(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,8 +26,9 @@ type Controllers struct {
|
||||
Terminal *controllers.TerminalController
|
||||
Settings *controllers.SettingsController
|
||||
Dependency *controllers.DependencyController
|
||||
Agent *controllers.AgentController
|
||||
Mise *controllers.MiseController
|
||||
Agent *controllers.AgentController
|
||||
Mise *controllers.MiseController
|
||||
Notification *controllers.NotificationController
|
||||
}
|
||||
|
||||
func mustSubFS(fsys fs.FS, dir string) fs.FS {
|
||||
@@ -199,6 +200,9 @@ func Setup(c *Controllers) *gin.Engine {
|
||||
settings.GET("/backup/status", c.Settings.GetBackupStatus)
|
||||
settings.GET("/backup/download", c.Settings.DownloadBackup)
|
||||
settings.POST("/restore", c.Settings.RestoreBackup)
|
||||
// 通用设置接口
|
||||
settings.GET("/:section/:key", c.Settings.GetSetting)
|
||||
settings.POST("/:section/:key/generate", c.Settings.GenerateSettingToken)
|
||||
}
|
||||
|
||||
// Dependency routes (依赖管理)
|
||||
@@ -246,6 +250,26 @@ func Setup(c *Controllers) *gin.Engine {
|
||||
{
|
||||
agentAPIv1.GET("/download", c.Agent.Download)
|
||||
}
|
||||
|
||||
// 通知推送模块
|
||||
notify := authorized.Group("/notify")
|
||||
{
|
||||
notify.GET("/types", c.Notification.GetChannelTypes)
|
||||
notify.GET("/channels", c.Notification.GetChannels)
|
||||
notify.POST("/channels", c.Notification.SaveChannel)
|
||||
notify.DELETE("/channels/:id", c.Notification.DeleteChannel)
|
||||
notify.POST("/channels/test", c.Notification.TestChannel)
|
||||
notify.GET("/bindings", c.Notification.GetBindings)
|
||||
notify.POST("/bindings", c.Notification.SaveBinding)
|
||||
notify.DELETE("/bindings/:id", c.Notification.DeleteBinding)
|
||||
}
|
||||
}
|
||||
|
||||
// 通知发送 API(使用通知 Token 认证,供脚本调用)
|
||||
notifyAPI := api.Group("/notify")
|
||||
notifyAPI.Use(middleware.NotifyTokenAuth())
|
||||
{
|
||||
notifyAPI.POST("/send", c.Notification.SendNotification)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type barkResponse struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type Bark struct {
|
||||
PushKey string
|
||||
Archive string
|
||||
Group string
|
||||
Sound string
|
||||
Icon string
|
||||
Level string
|
||||
URL string
|
||||
Key string
|
||||
IV string
|
||||
}
|
||||
|
||||
func (b *Bark) Request(title, content string) ([]byte, error) {
|
||||
data := map[string]interface{}{
|
||||
"title": title,
|
||||
"body": content,
|
||||
}
|
||||
if b.Archive != "" {
|
||||
data["isArchive"] = b.Archive
|
||||
}
|
||||
if b.Group != "" {
|
||||
data["group"] = b.Group
|
||||
}
|
||||
if b.Sound != "" {
|
||||
data["sound"] = b.Sound
|
||||
}
|
||||
if b.Icon != "" {
|
||||
data["icon"] = b.Icon
|
||||
}
|
||||
if b.Level != "" {
|
||||
data["level"] = b.Level
|
||||
}
|
||||
if b.URL != "" {
|
||||
data["url"] = b.URL
|
||||
}
|
||||
|
||||
var postData interface{}
|
||||
url := b.getURL()
|
||||
|
||||
if b.Key != "" && b.IV != "" {
|
||||
// Use encryption
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ciphertext, err := b.encryptPayload(string(jsonData))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encryption failed: %v", err)
|
||||
}
|
||||
postData = map[string]interface{}{
|
||||
"ciphertext": ciphertext,
|
||||
"device_key": b.PushKey,
|
||||
"sound": b.Sound,
|
||||
}
|
||||
// When using encryption, use the push endpoint if PushKey is just a key
|
||||
if !strings.HasPrefix(b.PushKey, "http") {
|
||||
url = "https://api.day.app/push"
|
||||
}
|
||||
} else {
|
||||
// Normal request
|
||||
postData = data
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(postData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := http.Post(url, "application/json;charset=utf-8", bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var r barkResponse
|
||||
err = json.Unmarshal(body, &r)
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
|
||||
if r.Code != 200 {
|
||||
return body, fmt.Errorf("bark response error: %s", string(body))
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (b *Bark) getURL() string {
|
||||
pushKey := b.PushKey
|
||||
if strings.HasPrefix(pushKey, "http") {
|
||||
return pushKey
|
||||
}
|
||||
return fmt.Sprintf("https://api.day.app/%s", pushKey)
|
||||
}
|
||||
|
||||
func (b *Bark) encryptPayload(payload string) (string, error) {
|
||||
key := []byte(b.Key)
|
||||
iv := []byte(b.IV)
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
paddedPayload := b.pkcs7Pad([]byte(payload), aes.BlockSize)
|
||||
mode := cipher.NewCBCEncrypter(block, iv)
|
||||
ciphertext := make([]byte, len(paddedPayload))
|
||||
mode.CryptBlocks(ciphertext, paddedPayload)
|
||||
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
|
||||
func (b *Bark) pkcs7Pad(data []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(data)%blockSize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(data, padtext...)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type CustomWebhook struct {
|
||||
Webhook string
|
||||
Body string
|
||||
}
|
||||
|
||||
var Client = &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
|
||||
func (cw *CustomWebhook) Request(url string, msg string) ([]byte, error) {
|
||||
resp, err := Client.Post(url, "application/json", bytes.NewBuffer([]byte(msg)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(Body io.ReadCloser) {
|
||||
err := Body.Close()
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
}(resp.Body)
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return body, err
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type response struct {
|
||||
Code int `json:"errcode"`
|
||||
Msg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
type Dtalk struct {
|
||||
AccessToken string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func (t *Dtalk) Request(msg interface{}) ([]byte, error) {
|
||||
b, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := http.Post(t.getURL(), "application/json", bytes.NewBuffer(b))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func(Body io.ReadCloser) {
|
||||
err := Body.Close()
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
}(resp.Body)
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r response
|
||||
err = json.Unmarshal(body, &r)
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
if r.Code != 0 {
|
||||
return body, fmt.Errorf("response error: %s", string(body))
|
||||
}
|
||||
return body, err
|
||||
}
|
||||
|
||||
// SendMessageText Function to send message
|
||||
func (t *Dtalk) SendMessageText(text string, at ...string) ([]byte, error) {
|
||||
msg := map[string]interface{}{
|
||||
"msgtype": "text",
|
||||
"text": map[string]string{
|
||||
"content": text,
|
||||
},
|
||||
}
|
||||
|
||||
// 添加@功能
|
||||
if len(at) > 0 {
|
||||
atMobiles := []string{}
|
||||
isAtAll := false
|
||||
|
||||
for _, mobile := range at {
|
||||
if mobile == "all" || mobile == "@all" {
|
||||
isAtAll = true
|
||||
} else {
|
||||
atMobiles = append(atMobiles, mobile)
|
||||
}
|
||||
}
|
||||
|
||||
msg["at"] = map[string]interface{}{
|
||||
"atMobiles": atMobiles,
|
||||
"isAtAll": isAtAll,
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := t.Request(msg)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (t *Dtalk) SendMessageMarkdown(title, text string, at ...string) ([]byte, error) {
|
||||
msg := map[string]interface{}{
|
||||
"msgtype": "markdown",
|
||||
"markdown": map[string]string{
|
||||
"title": title,
|
||||
"text": text,
|
||||
},
|
||||
}
|
||||
|
||||
// 添加@功能
|
||||
if len(at) > 0 {
|
||||
atMobiles := []string{}
|
||||
isAtAll := false
|
||||
|
||||
for _, mobile := range at {
|
||||
if mobile == "all" || mobile == "@all" {
|
||||
isAtAll = true
|
||||
} else {
|
||||
atMobiles = append(atMobiles, mobile)
|
||||
}
|
||||
}
|
||||
|
||||
msg["at"] = map[string]interface{}{
|
||||
"atMobiles": atMobiles,
|
||||
"isAtAll": isAtAll,
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := t.Request(msg)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (t *Dtalk) hmacSha256(stringToSign string, secret string) string {
|
||||
h := hmac.New(sha256.New, []byte(secret))
|
||||
h.Write([]byte(stringToSign))
|
||||
return base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
func (t *Dtalk) getURL() string {
|
||||
wh := "https://oapi.dingtalk.com/robot/send?access_token=" + t.AccessToken
|
||||
timestamp := time.Now().UnixNano() / 1e6
|
||||
stringToSign := fmt.Sprintf("%d\n%s", timestamp, t.Secret)
|
||||
sign := t.hmacSha256(stringToSign, t.Secret)
|
||||
url := fmt.Sprintf("%s×tamp=%d&sign=%s", wh, timestamp, sign)
|
||||
return url
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gopkg.in/gomail.v2"
|
||||
)
|
||||
|
||||
type EmailMessage struct {
|
||||
Server string
|
||||
Port int
|
||||
Account string
|
||||
Passwd string
|
||||
FromName string
|
||||
GM *gomail.Dialer
|
||||
}
|
||||
|
||||
func (e *EmailMessage) Init(host string, port int, account string, passwd string, fromName string) {
|
||||
e.Server = host
|
||||
e.Port = port
|
||||
e.Account = account
|
||||
e.Passwd = passwd
|
||||
e.FromName = fromName
|
||||
e.GM = gomail.NewDialer(host, port, account, passwd)
|
||||
}
|
||||
|
||||
func (e *EmailMessage) SendTextMessage(toEmail string, title string, content string) string {
|
||||
m := gomail.NewMessage()
|
||||
if e.FromName != "" {
|
||||
m.SetAddressHeader("From", e.Account, e.FromName)
|
||||
} else {
|
||||
m.SetHeader("From", e.Account)
|
||||
}
|
||||
m.SetHeader("To", toEmail)
|
||||
m.SetHeader("Subject", title)
|
||||
m.SetBody("text/html", content)
|
||||
|
||||
if err := e.GM.DialAndSend(m); err != nil {
|
||||
return fmt.Sprintf("邮件发送失败: %s", err)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (e *EmailMessage) SendHtmlMessage(toEmail string, title string, content string) string {
|
||||
return e.SendTextMessage(toEmail, title, content)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type feishuResponse struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
type Feishu struct {
|
||||
AccessToken string
|
||||
Secret string
|
||||
}
|
||||
|
||||
// genSign 生成飞书签名
|
||||
func (f *Feishu) genSign(timestamp int64) string {
|
||||
if f.Secret == "" {
|
||||
return ""
|
||||
}
|
||||
stringToSign := fmt.Sprintf("%v\n%s", timestamp, f.Secret)
|
||||
h := hmac.New(sha256.New, []byte(stringToSign))
|
||||
signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
return signature
|
||||
}
|
||||
|
||||
// SendMessageText 发送文本消息
|
||||
func (f *Feishu) SendMessageText(content string, atMobiles ...string) ([]byte, error) {
|
||||
timestamp := time.Now().Unix()
|
||||
sign := f.genSign(timestamp)
|
||||
|
||||
msg := map[string]interface{}{
|
||||
"timestamp": strconv.FormatInt(timestamp, 10),
|
||||
"sign": sign,
|
||||
"msg_type": "text",
|
||||
"content": map[string]interface{}{
|
||||
"text": content,
|
||||
},
|
||||
}
|
||||
|
||||
return f.send(msg)
|
||||
}
|
||||
|
||||
// SendMessageMarkdown 发送 Markdown 消息
|
||||
func (f *Feishu) SendMessageMarkdown(title, content string, atMobiles ...string) ([]byte, error) {
|
||||
timestamp := time.Now().Unix()
|
||||
sign := f.genSign(timestamp)
|
||||
|
||||
// 处理 @ 人员
|
||||
atContent := ""
|
||||
if len(atMobiles) > 0 {
|
||||
for _, mobile := range atMobiles {
|
||||
if mobile == "all" {
|
||||
atContent += "<at user_id=\"all\">所有人</at>"
|
||||
} else {
|
||||
atContent += fmt.Sprintf("<at user_id=\"%s\"></at>", mobile)
|
||||
}
|
||||
}
|
||||
content = atContent + "\n" + content
|
||||
}
|
||||
|
||||
msg := map[string]interface{}{
|
||||
"timestamp": strconv.FormatInt(timestamp, 10),
|
||||
"sign": sign,
|
||||
"msg_type": "interactive",
|
||||
"card": map[string]interface{}{
|
||||
"header": map[string]interface{}{
|
||||
"title": map[string]interface{}{
|
||||
"tag": "plain_text",
|
||||
"content": title,
|
||||
},
|
||||
},
|
||||
"elements": []map[string]interface{}{
|
||||
{
|
||||
"tag": "markdown",
|
||||
"content": content,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return f.send(msg)
|
||||
}
|
||||
|
||||
// send 发送请求
|
||||
func (f *Feishu) send(msg map[string]interface{}) ([]byte, error) {
|
||||
url := fmt.Sprintf("https://open.feishu.cn/open-apis/bot/v2/hook/%s", f.AccessToken)
|
||||
|
||||
jsonData, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("JSON序列化失败: %v", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建请求失败: %v", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("发送请求失败: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取响应失败: %v", err)
|
||||
}
|
||||
|
||||
var result feishuResponse
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return body, fmt.Errorf("解析响应失败: %v", err)
|
||||
}
|
||||
|
||||
if result.Code != 0 {
|
||||
return body, fmt.Errorf("飞书返回错误: %s", result.Msg)
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type gotifyResponse struct {
|
||||
Id int `json:"id"`
|
||||
Message string `json:"message"`
|
||||
ErrorCode int `json:"errorCode"`
|
||||
}
|
||||
|
||||
type Gotify struct {
|
||||
Url string
|
||||
Token string
|
||||
Priority int
|
||||
}
|
||||
|
||||
func (g *Gotify) Request(title, content string) ([]byte, error) {
|
||||
// Construct the URL with token
|
||||
u, err := url.Parse(fmt.Sprintf("%s/message", g.Url))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("token", g.Token)
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
data := map[string]interface{}{
|
||||
"title": title,
|
||||
"message": content,
|
||||
"priority": g.Priority,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := http.Post(u.String(), "application/json", bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var r gotifyResponse
|
||||
err = json.Unmarshal(body, &r)
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
|
||||
if r.Id == 0 {
|
||||
return body, fmt.Errorf("gotify response error: %s", string(body))
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Ntfy struct {
|
||||
Url string
|
||||
Topic string
|
||||
Priority string
|
||||
Icon string
|
||||
Token string
|
||||
Username string
|
||||
Password string
|
||||
Actions string
|
||||
}
|
||||
|
||||
func encodeRFC2047(text string) string {
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(text))
|
||||
return fmt.Sprintf("=?utf-8?B?%s?=", encoded)
|
||||
}
|
||||
|
||||
func (n *Ntfy) Request(title, content string) ([]byte, error) {
|
||||
if n.Url == "" {
|
||||
n.Url = "https://ntfy.sh"
|
||||
}
|
||||
url := fmt.Sprintf("%s/%s", n.Url, n.Topic)
|
||||
|
||||
req, err := http.NewRequest("POST", url, bytes.NewBufferString(content))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Title", encodeRFC2047(title))
|
||||
priority := n.Priority
|
||||
if priority == "" {
|
||||
priority = "3"
|
||||
}
|
||||
req.Header.Set("Priority", priority)
|
||||
if n.Icon != "" {
|
||||
req.Header.Set("Icon", n.Icon)
|
||||
}
|
||||
if n.Actions != "" {
|
||||
req.Header.Set("Actions", encodeRFC2047(n.Actions))
|
||||
}
|
||||
|
||||
if n.Token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+n.Token)
|
||||
} else if n.Username != "" && n.Password != "" {
|
||||
authStr := n.Username + ":" + n.Password
|
||||
encodedAuth := base64.StdEncoding.EncodeToString([]byte(authStr))
|
||||
req.Header.Set("Authorization", "Basic "+encodedAuth)
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return body, fmt.Errorf("ntfy response error: %s", string(body))
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type PushMe struct {
|
||||
PushKey string
|
||||
URL string
|
||||
Date string
|
||||
Type string
|
||||
}
|
||||
|
||||
func (p *PushMe) Request(title, content string) (string, error) {
|
||||
apiURL := p.URL
|
||||
if apiURL == "" {
|
||||
apiURL = "https://push.i-i.me/"
|
||||
}
|
||||
|
||||
data := url.Values{}
|
||||
data.Set("push_key", p.PushKey)
|
||||
data.Set("title", title)
|
||||
data.Set("content", content)
|
||||
if p.Date != "" {
|
||||
data.Set("date", p.Date)
|
||||
}
|
||||
if p.Type != "" {
|
||||
data.Set("type", p.Type)
|
||||
}
|
||||
|
||||
resp, err := http.Post(apiURL, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if resp.StatusCode == 200 && string(body) == "success" {
|
||||
return string(body), nil
|
||||
}
|
||||
|
||||
return string(body), fmt.Errorf("PushMe response error: %s", string(body))
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type qywxResponse struct {
|
||||
Code int `json:"errcode"`
|
||||
Msg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
type QyWeiXin struct {
|
||||
AccessToken string
|
||||
}
|
||||
|
||||
func (t *QyWeiXin) Request(msg interface{}) ([]byte, error) {
|
||||
b, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := http.Post(t.getURL(), "application/json", bytes.NewBuffer(b))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func(Body io.ReadCloser) {
|
||||
err := Body.Close()
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
}(resp.Body)
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r qywxResponse
|
||||
err = json.Unmarshal(body, &r)
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
if r.Code != 0 {
|
||||
return body, fmt.Errorf("response error: %s", string(body))
|
||||
}
|
||||
return body, err
|
||||
}
|
||||
|
||||
// SendMessageText Function to send message
|
||||
func (t *QyWeiXin) SendMessageText(text string, at ...string) ([]byte, error) {
|
||||
msg := map[string]interface{}{
|
||||
"msgtype": "text",
|
||||
"text": map[string]interface{}{
|
||||
"content": text,
|
||||
},
|
||||
}
|
||||
|
||||
// 添加@功能
|
||||
// 企业微信支持两种@方式:
|
||||
// 1. mentioned_list: userid列表或"@all"
|
||||
// 2. mentioned_mobile_list: 手机号列表
|
||||
if len(at) > 0 {
|
||||
mentionedList := []string{}
|
||||
mentionedMobileList := []string{}
|
||||
|
||||
for _, item := range at {
|
||||
if item == "@all" || item == "all" {
|
||||
mentionedList = append(mentionedList, "@all")
|
||||
} else if len(item) == 11 && item[0] == '1' {
|
||||
// 判断是否为手机号(简单判断:11位且以1开头)
|
||||
mentionedMobileList = append(mentionedMobileList, item)
|
||||
} else {
|
||||
// 否则当作userid处理
|
||||
mentionedList = append(mentionedList, item)
|
||||
}
|
||||
}
|
||||
|
||||
textContent := msg["text"].(map[string]interface{})
|
||||
if len(mentionedList) > 0 {
|
||||
textContent["mentioned_list"] = mentionedList
|
||||
}
|
||||
if len(mentionedMobileList) > 0 {
|
||||
textContent["mentioned_mobile_list"] = mentionedMobileList
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := t.Request(msg)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (t *QyWeiXin) SendMessageMarkdown(title, text string, at ...string) ([]byte, error) {
|
||||
msg := map[string]interface{}{
|
||||
"msgtype": "markdown",
|
||||
"markdown": map[string]interface{}{
|
||||
"content": text,
|
||||
},
|
||||
}
|
||||
|
||||
// 企业微信Markdown消息不支持@功能,但可以在内容中手动添加
|
||||
// 如果需要@功能,建议使用text类型
|
||||
|
||||
resp, err := t.Request(msg)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (t *QyWeiXin) getURL() string {
|
||||
url := "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + t.AccessToken
|
||||
return url
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
type telegramResponse struct {
|
||||
Ok bool `json:"ok"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
type Telegram struct {
|
||||
BotToken string
|
||||
ChatID string
|
||||
ApiHost string // 可选的自定义API地址(优先级最高)
|
||||
ProxyURL string // 可选的代理地址,支持 http://、https://、socks5:// 格式
|
||||
}
|
||||
|
||||
func (t *Telegram) Request(params map[string]interface{}) ([]byte, error) {
|
||||
apiURL := t.getAPIURL()
|
||||
|
||||
// 构建请求体
|
||||
data := url.Values{}
|
||||
for key, value := range params {
|
||||
data.Set(key, fmt.Sprintf("%v", value))
|
||||
}
|
||||
|
||||
// 创建 HTTP 客户端
|
||||
client := t.getHTTPClient()
|
||||
|
||||
resp, err := client.Post(apiURL, "application/x-www-form-urlencoded", bytes.NewBufferString(data.Encode()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func(Body io.ReadCloser) {
|
||||
err := Body.Close()
|
||||
if err != nil {
|
||||
// 忽略关闭错误
|
||||
}
|
||||
}(resp.Body)
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var r telegramResponse
|
||||
err = json.Unmarshal(body, &r)
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
|
||||
if !r.Ok {
|
||||
return body, fmt.Errorf("telegram api error: %s", r.Description)
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// SendMessageText 发送文本消息
|
||||
func (t *Telegram) SendMessageText(text string) ([]byte, error) {
|
||||
params := map[string]interface{}{
|
||||
"chat_id": t.ChatID,
|
||||
"text": text,
|
||||
"disable_web_page_preview": "true",
|
||||
}
|
||||
|
||||
return t.Request(params)
|
||||
}
|
||||
|
||||
// SendMessageMarkdown 发送Markdown格式消息
|
||||
func (t *Telegram) SendMessageMarkdown(text string) ([]byte, error) {
|
||||
params := map[string]interface{}{
|
||||
"chat_id": t.ChatID,
|
||||
"text": text,
|
||||
"parse_mode": "Markdown",
|
||||
"disable_web_page_preview": "true",
|
||||
}
|
||||
|
||||
return t.Request(params)
|
||||
}
|
||||
|
||||
// SendMessageHTML 发送HTML格式消息
|
||||
func (t *Telegram) SendMessageHTML(text string) ([]byte, error) {
|
||||
params := map[string]interface{}{
|
||||
"chat_id": t.ChatID,
|
||||
"text": text,
|
||||
"parse_mode": "HTML",
|
||||
"disable_web_page_preview": "true",
|
||||
}
|
||||
|
||||
return t.Request(params)
|
||||
}
|
||||
|
||||
func (t *Telegram) getAPIURL() string {
|
||||
// 自定义 API 地址优先级最高
|
||||
if t.ApiHost != "" {
|
||||
return fmt.Sprintf("%s/bot%s/sendMessage", t.ApiHost, t.BotToken)
|
||||
}
|
||||
return fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", t.BotToken)
|
||||
}
|
||||
|
||||
// getHTTPClient 获取配置了代理的 HTTP 客户端
|
||||
func (t *Telegram) getHTTPClient() *http.Client {
|
||||
client := &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
}
|
||||
|
||||
// 如果配置了代理且没有自定义 API 地址,则使用代理
|
||||
// 自定义 API 地址优先级更高,通常用于自建代理服务器
|
||||
if t.ProxyURL != "" && t.ApiHost == "" {
|
||||
proxyURL, err := url.Parse(t.ProxyURL)
|
||||
if err == nil {
|
||||
// 判断是否为 SOCKS5 代理
|
||||
if strings.HasPrefix(strings.ToLower(t.ProxyURL), "socks5://") {
|
||||
// 使用 SOCKS5 代理
|
||||
dialer, err := t.createSOCKS5Dialer(proxyURL)
|
||||
if err == nil {
|
||||
client.Transport = &http.Transport{
|
||||
DialContext: dialer.DialContext,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 使用 HTTP/HTTPS 代理
|
||||
client.Transport = &http.Transport{
|
||||
Proxy: http.ProxyURL(proxyURL),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
// createSOCKS5Dialer 创建 SOCKS5 代理拨号器
|
||||
func (t *Telegram) createSOCKS5Dialer(proxyURL *url.URL) (proxy.ContextDialer, error) {
|
||||
// 解析代理地址
|
||||
host := proxyURL.Host
|
||||
|
||||
// 检查是否有认证信息
|
||||
var auth *proxy.Auth
|
||||
if proxyURL.User != nil {
|
||||
password, _ := proxyURL.User.Password()
|
||||
auth = &proxy.Auth{
|
||||
User: proxyURL.User.Username(),
|
||||
Password: password,
|
||||
}
|
||||
}
|
||||
|
||||
// 创建基础拨号器
|
||||
baseDialer := &net.Dialer{
|
||||
Timeout: 30 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}
|
||||
|
||||
// 创建 SOCKS5 拨号器
|
||||
dialer, err := proxy.SOCKS5("tcp", host, auth, baseDialer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 转换为 ContextDialer
|
||||
contextDialer, ok := dialer.(proxy.ContextDialer)
|
||||
if !ok {
|
||||
return nil, errors.New("failed to convert to ContextDialer")
|
||||
}
|
||||
|
||||
return contextDialer, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"github.com/silenceper/wechat/v2"
|
||||
"github.com/silenceper/wechat/v2/cache"
|
||||
offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/message"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type WeChatOFAccount struct {
|
||||
AppID string
|
||||
AppSecret string
|
||||
ToUser string
|
||||
TemplateID string
|
||||
URL string
|
||||
}
|
||||
|
||||
// 使用内存缓存进行token的存储
|
||||
var memory = cache.NewMemory()
|
||||
|
||||
func (cw *WeChatOFAccount) Send(title string, content string) (string, error) {
|
||||
wc := wechat.NewWechat()
|
||||
cfg := &offConfig.Config{
|
||||
AppID: cw.AppID,
|
||||
AppSecret: cw.AppSecret,
|
||||
Cache: memory,
|
||||
}
|
||||
officialAccount := wc.GetOfficialAccount(cfg)
|
||||
|
||||
// 获取 Access Token
|
||||
_, err := officialAccount.GetAccessToken()
|
||||
if err != nil {
|
||||
logrus.Errorf("获取access token失败:%s", err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
msgData := make(map[string]*message.TemplateDataItem)
|
||||
msgData["content"] = &message.TemplateDataItem{
|
||||
Value: content,
|
||||
}
|
||||
msgData["title"] = &message.TemplateDataItem{
|
||||
Value: title,
|
||||
//Color: "#173177",
|
||||
}
|
||||
|
||||
// 创建模板消息
|
||||
templateMessage := &message.TemplateMessage{
|
||||
ToUser: cw.ToUser,
|
||||
TemplateID: cw.TemplateID,
|
||||
URL: cw.URL,
|
||||
Data: msgData,
|
||||
}
|
||||
|
||||
// 发送模板消息
|
||||
_, err = officialAccount.GetTemplate().Send(templateMessage)
|
||||
if err != nil {
|
||||
logrus.Errorf("发送模板消息失败: %s", err)
|
||||
return "", err
|
||||
}
|
||||
//logrus.Infof("模板消息发送成功。 消息ID: %d", msgID)
|
||||
return "", nil
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
# Messenger SDK
|
||||
|
||||
统一消息发送 SDK,可独立于 Message-Push-Nest 业务层使用。
|
||||
|
||||
## 特点
|
||||
|
||||
- **零业务依赖**:不依赖数据库、路由、认证等业务代码
|
||||
- **开箱即用**:直接传配置 + 消息即可发送
|
||||
- **支持 12 种渠道**:Email, 钉钉, 企业微信, 飞书, Telegram, Bark, Ntfy, Gotify, PushMe, 自定义Webhook, 微信公众号, 阿里云短信
|
||||
- **可扩展**:通过 `RegisterChannel` 注册自定义渠道
|
||||
|
||||
## 快速使用
|
||||
|
||||
```go
|
||||
import "message-nest/pkg/sdk/messenger"
|
||||
|
||||
// 方式1: 直接发送
|
||||
result, err := messenger.Send("Telegram", messenger.ChannelConfig{
|
||||
"bot_token": "your-bot-token",
|
||||
"chat_id": "123456",
|
||||
}, &messenger.Message{
|
||||
Title: "告警通知",
|
||||
Text: "服务器 CPU 超过 90%",
|
||||
Markdown: "**服务器 CPU** 超过 `90%`",
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if !result.Success {
|
||||
log.Printf("发送失败: %s", result.Error)
|
||||
}
|
||||
```
|
||||
|
||||
### 使用 Client(预设默认配置)
|
||||
|
||||
```go
|
||||
client := messenger.NewClient()
|
||||
|
||||
// 预设 Telegram 配置
|
||||
client.SetDefaultConfig("Telegram", messenger.ChannelConfig{
|
||||
"bot_token": "your-bot-token",
|
||||
"chat_id": "default-chat",
|
||||
})
|
||||
|
||||
// 后续发送可以覆盖部分配置,也可以传 nil 使用全部默认值
|
||||
result, err := client.Send("Telegram", nil, &messenger.Message{
|
||||
Title: "Hello",
|
||||
Text: "World",
|
||||
})
|
||||
```
|
||||
|
||||
## 各渠道配置参数
|
||||
|
||||
### Email
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `server` | ✅ | SMTP 服务地址 |
|
||||
| `port` | ✅ | SMTP 端口 |
|
||||
| `account` | ✅ | 邮箱账号 |
|
||||
| `passwd` | ✅ | 邮箱密码 |
|
||||
| `from_name` | ❌ | 发信人名称 |
|
||||
| `to_account` | ✅ | 收件邮箱 |
|
||||
|
||||
### Dtalk(钉钉)
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `access_token` | ✅ | 钉钉 access_token |
|
||||
| `secret` | ❌ | 加签秘钥 |
|
||||
|
||||
### QyWeiXin(企业微信)
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `access_token` | ✅ | 企业微信 access_token |
|
||||
|
||||
### Feishu(飞书)
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `access_token` | ✅ | 飞书 access_token |
|
||||
| `secret` | ❌ | 加签秘钥 |
|
||||
|
||||
### Telegram
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `bot_token` | ✅ | Bot Token |
|
||||
| `chat_id` | ✅ | Chat ID |
|
||||
| `api_host` | ❌ | 自定义 API 地址 |
|
||||
| `proxy_url` | ❌ | 代理地址 (http/https/socks5) |
|
||||
|
||||
### Bark
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `push_key` | ✅ | Bark Push Key |
|
||||
| `archive` | ❌ | 是否存档 |
|
||||
| `group` | ❌ | 推送分组 |
|
||||
| `sound` | ❌ | 推送声音 |
|
||||
| `icon` | ❌ | 推送图标 |
|
||||
| `level` | ❌ | 时效性 |
|
||||
| `url` | ❌ | 跳转URL |
|
||||
| `key` | ❌ | 加密Key |
|
||||
| `iv` | ❌ | 加密IV |
|
||||
|
||||
### Ntfy
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `topic` | ✅ | Topic |
|
||||
| `url` | ❌ | 自定义 API 地址 |
|
||||
| `priority` | ❌ | 优先级 |
|
||||
| `icon` | ❌ | 图标 URL |
|
||||
| `token` | ❌ | Token |
|
||||
| `username` | ❌ | 用户名 |
|
||||
| `password` | ❌ | 密码 |
|
||||
| `actions` | ❌ | Actions |
|
||||
|
||||
### Gotify
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `url` | ✅ | Gotify 服务地址 |
|
||||
| `token` | ✅ | Token |
|
||||
| `priority` | ❌ | 优先级 |
|
||||
|
||||
### PushMe
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `push_key` | ✅ | PushMe Push Key |
|
||||
| `url` | ❌ | 自定义 API 地址 |
|
||||
| `date` | ❌ | 日期 |
|
||||
| `type` | ❌ | 类型 |
|
||||
|
||||
### Custom(自定义Webhook)
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `webhook` | ✅ | Webhook URL |
|
||||
| `body` | ❌ | 请求体模板(`TEXT` 占位符会被替换) |
|
||||
|
||||
### WeChatOFAccount(微信公众号)
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `appID` | ✅ | 公众号 AppID |
|
||||
| `appsecret` | ✅ | 公众号 AppSecret |
|
||||
| `tempid` | ❌ | 模板消息 ID |
|
||||
| `to_account` | ✅ | 接收者 OpenID |
|
||||
|
||||
### AliyunSMS(阿里云短信)
|
||||
| 参数 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `access_key_id` | ✅ | AccessKeyId |
|
||||
| `access_key_secret` | ✅ | AccessKeySecret |
|
||||
| `sign_name` | ✅ | 短信签名 |
|
||||
| `region_id` | ❌ | 区域ID(默认 cn-hangzhou) |
|
||||
| `phone_number` | ✅ | 手机号码 |
|
||||
| `template_code` | ✅ | 短信模板 CODE |
|
||||
|
||||
## 自定义扩展
|
||||
|
||||
```go
|
||||
// 注册自定义渠道
|
||||
messenger.RegisterChannel("MyChannel", func() messenger.Channel {
|
||||
return &myCustomChannel{}
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
package channels
|
||||
|
||||
type AliyunSMSChannel struct{ *BaseChannel }
|
||||
|
||||
func NewAliyunSMSChannel() Channel {
|
||||
return &AliyunSMSChannel{NewBaseChannel(ChannelAliyunSMS, []string{FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *AliyunSMSChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
accessKeyId := config.GetString("access_key_id")
|
||||
accessKeySecret := config.GetString("access_key_secret")
|
||||
signName := config.GetString("sign_name")
|
||||
regionId := config.GetString("region_id")
|
||||
phoneNumber := config.GetString("phone_number")
|
||||
templateCode := config.GetString("template_code")
|
||||
|
||||
if accessKeyId == "" || accessKeySecret == "" || signName == "" {
|
||||
return SendError("aliyun sms config missing: access_key_id, access_key_secret, sign_name are required"), nil
|
||||
}
|
||||
if phoneNumber == "" || templateCode == "" {
|
||||
return SendError("aliyun sms config missing: phone_number, template_code are required"), nil
|
||||
}
|
||||
|
||||
_, formattedContent := c.FormatContent(msg)
|
||||
|
||||
if regionId == "" {
|
||||
regionId = "cn-hangzhou"
|
||||
}
|
||||
|
||||
client, err := createAliyunSMSClient(accessKeyId, accessKeySecret, regionId)
|
||||
if err != nil {
|
||||
return SendError("创建阿里云短信客户端失败: %s", err.Error()), nil
|
||||
}
|
||||
|
||||
result, err := sendAliyunSMS(client, phoneNumber, signName, templateCode, formattedContent, msg.Extra)
|
||||
if err != nil {
|
||||
return ErrorResult("", err), nil
|
||||
}
|
||||
return SuccessResult(result), nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package channels
|
||||
|
||||
import "github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
|
||||
type BarkChannel struct{ *BaseChannel }
|
||||
|
||||
func NewBarkChannel() Channel {
|
||||
return &BarkChannel{NewBaseChannel(ChannelBark, []string{FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *BarkChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
pushKey := config.GetString("push_key")
|
||||
if pushKey == "" {
|
||||
return SendError("bark config missing: push_key is required"), nil
|
||||
}
|
||||
|
||||
cli := message.Bark{
|
||||
PushKey: pushKey,
|
||||
Archive: config.GetString("archive"),
|
||||
Group: config.GetString("group"),
|
||||
Sound: config.GetString("sound"),
|
||||
Icon: config.GetString("icon"),
|
||||
Level: config.GetString("level"),
|
||||
URL: config.GetString("url"),
|
||||
Key: config.GetString("key"),
|
||||
IV: config.GetString("iv"),
|
||||
}
|
||||
|
||||
res, err := cli.Request(msg.Title, msg.Text)
|
||||
if err != nil {
|
||||
return ErrorResult(string(res), err), nil
|
||||
}
|
||||
return SuccessResult(string(res)), nil
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package channels
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Channel 渠道接口 - SDK 版本,零业务依赖
|
||||
type Channel interface {
|
||||
// GetType 返回渠道类型标识
|
||||
GetType() string
|
||||
// GetSupportedFormats 返回支持的消息格式
|
||||
GetSupportedFormats() []string
|
||||
// Send 发送消息
|
||||
Send(config ChannelConfig, msg *Message) (*Result, error)
|
||||
}
|
||||
|
||||
// BaseChannel 渠道基础实现
|
||||
type BaseChannel struct {
|
||||
channelType string
|
||||
supportedFormats []string
|
||||
}
|
||||
|
||||
func NewBaseChannel(channelType string, supportedFormats []string) *BaseChannel {
|
||||
return &BaseChannel{channelType: channelType, supportedFormats: supportedFormats}
|
||||
}
|
||||
|
||||
func (c *BaseChannel) GetType() string { return c.channelType }
|
||||
func (c *BaseChannel) GetSupportedFormats() []string { return c.supportedFormats }
|
||||
|
||||
// FormatContent 根据渠道支持的格式选择最佳内容
|
||||
func (c *BaseChannel) FormatContent(msg *Message) (formatType string, content string) {
|
||||
for _, ft := range c.supportedFormats {
|
||||
switch ft {
|
||||
case FormatTypeMarkdown:
|
||||
if msg.HasMarkdown() {
|
||||
return FormatTypeMarkdown, msg.Markdown
|
||||
}
|
||||
case FormatTypeHTML:
|
||||
if msg.HasHTML() {
|
||||
return FormatTypeHTML, msg.HTML
|
||||
}
|
||||
case FormatTypeText:
|
||||
if msg.HasText() {
|
||||
return FormatTypeText, msg.Text
|
||||
}
|
||||
}
|
||||
}
|
||||
if msg.HasText() {
|
||||
return FormatTypeText, msg.Text
|
||||
}
|
||||
return FormatTypeText, ""
|
||||
}
|
||||
|
||||
// SuccessResult 创建成功结果
|
||||
func SuccessResult(response string) *Result {
|
||||
return &Result{Success: true, Response: response}
|
||||
}
|
||||
|
||||
// ErrorResult 创建失败结果
|
||||
func ErrorResult(response string, err error) *Result {
|
||||
errMsg := ""
|
||||
if err != nil {
|
||||
errMsg = err.Error()
|
||||
}
|
||||
return &Result{Success: false, Response: response, Error: errMsg}
|
||||
}
|
||||
|
||||
// ErrorResultStr 创建失败结果(字符串错误)
|
||||
func ErrorResultStr(response string, errMsg string) *Result {
|
||||
return &Result{Success: false, Response: response, Error: errMsg}
|
||||
}
|
||||
|
||||
// SendError 发送失败时的格式化错误
|
||||
func SendError(format string, args ...any) *Result {
|
||||
return &Result{Success: false, Error: fmt.Sprintf(format, args...)}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package channels
|
||||
|
||||
import "github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
|
||||
type CustomChannel struct{ *BaseChannel }
|
||||
|
||||
func NewCustomChannel() Channel {
|
||||
return &CustomChannel{NewBaseChannel(ChannelCustom, []string{FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *CustomChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
webhook := config.GetString("webhook")
|
||||
body := config.GetString("body")
|
||||
|
||||
if webhook == "" {
|
||||
return SendError("custom config missing: webhook is required"), nil
|
||||
}
|
||||
|
||||
_, formattedContent := c.FormatContent(msg)
|
||||
cli := message.CustomWebhook{}
|
||||
|
||||
// 替换 body 模板中的 TEXT 占位符
|
||||
bodyStr := body
|
||||
if bodyStr != "" {
|
||||
bodyStr = replaceBodyPlaceholder(bodyStr, formattedContent)
|
||||
} else {
|
||||
bodyStr = formattedContent
|
||||
}
|
||||
|
||||
res, err := cli.Request(webhook, bodyStr)
|
||||
if err != nil {
|
||||
return ErrorResult(string(res), err), nil
|
||||
}
|
||||
return SuccessResult(string(res)), nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package channels
|
||||
|
||||
import "github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
|
||||
type DtalkChannel struct{ *BaseChannel }
|
||||
|
||||
func NewDtalkChannel() Channel {
|
||||
return &DtalkChannel{NewBaseChannel(ChannelDtalk, []string{FormatTypeMarkdown, FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *DtalkChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
accessToken := config.GetString("access_token")
|
||||
secret := config.GetString("secret")
|
||||
|
||||
if accessToken == "" {
|
||||
return SendError("dtalk config missing: access_token is required"), nil
|
||||
}
|
||||
|
||||
contentType, formattedContent := c.FormatContent(msg)
|
||||
atMobiles := msg.GetAtMobiles()
|
||||
if msg.AtAll {
|
||||
atMobiles = append(atMobiles, "all")
|
||||
}
|
||||
|
||||
cli := message.Dtalk{AccessToken: accessToken, Secret: secret}
|
||||
var res []byte
|
||||
var err error
|
||||
|
||||
if contentType == FormatTypeText {
|
||||
res, err = cli.SendMessageText(formattedContent, atMobiles...)
|
||||
} else if contentType == FormatTypeMarkdown {
|
||||
res, err = cli.SendMessageMarkdown(msg.Title, formattedContent, atMobiles...)
|
||||
} else {
|
||||
return SendError("未知的钉钉发送内容类型:%s", contentType), nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return ErrorResult(string(res), err), nil
|
||||
}
|
||||
return SuccessResult(string(res)), nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package channels
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type EmailChannel struct{ *BaseChannel }
|
||||
|
||||
func NewEmailChannel() Channel {
|
||||
return &EmailChannel{NewBaseChannel(ChannelEmail, []string{FormatTypeHTML, FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *EmailChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
server := config.GetString("server")
|
||||
portStr := config.GetString("port")
|
||||
account := config.GetString("account")
|
||||
passwd := config.GetString("passwd")
|
||||
fromName := config.GetString("from_name")
|
||||
toAccount := config.GetString("to_account")
|
||||
|
||||
if server == "" || account == "" || passwd == "" {
|
||||
return SendError("email config missing: server, account, passwd are required"), nil
|
||||
}
|
||||
if toAccount == "" {
|
||||
return SendError("email config missing: to_account is required"), nil
|
||||
}
|
||||
|
||||
port, _ := strconv.Atoi(portStr)
|
||||
contentType, formattedContent := c.FormatContent(msg)
|
||||
|
||||
var emailer message.EmailMessage
|
||||
emailer.Init(server, port, account, passwd, fromName)
|
||||
|
||||
var errMsg string
|
||||
if contentType == FormatTypeText {
|
||||
errMsg = emailer.SendTextMessage(toAccount, msg.Title, formattedContent)
|
||||
} else if contentType == FormatTypeHTML {
|
||||
errMsg = emailer.SendHtmlMessage(toAccount, msg.Title, formattedContent)
|
||||
} else {
|
||||
errMsg = fmt.Sprintf("未知的邮件发送内容类型:%s", contentType)
|
||||
}
|
||||
|
||||
if errMsg != "" {
|
||||
return ErrorResultStr("", errMsg), nil
|
||||
}
|
||||
return SuccessResult(""), nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package channels
|
||||
|
||||
import "github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
|
||||
type FeishuChannel struct{ *BaseChannel }
|
||||
|
||||
func NewFeishuChannel() Channel {
|
||||
return &FeishuChannel{NewBaseChannel(ChannelFeishu, []string{FormatTypeMarkdown, FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *FeishuChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
accessToken := config.GetString("access_token")
|
||||
secret := config.GetString("secret")
|
||||
|
||||
if accessToken == "" {
|
||||
return SendError("feishu config missing: access_token is required"), nil
|
||||
}
|
||||
|
||||
contentType, formattedContent := c.FormatContent(msg)
|
||||
atMobiles := msg.GetAtMobiles()
|
||||
atUserIds := msg.GetAtUserIds()
|
||||
atList := append(atMobiles, atUserIds...)
|
||||
if msg.AtAll {
|
||||
atList = append(atList, "all")
|
||||
}
|
||||
|
||||
cli := message.Feishu{AccessToken: accessToken, Secret: secret}
|
||||
var res []byte
|
||||
var err error
|
||||
|
||||
if contentType == FormatTypeText {
|
||||
res, err = cli.SendMessageText(formattedContent, atList...)
|
||||
} else if contentType == FormatTypeMarkdown {
|
||||
res, err = cli.SendMessageMarkdown(msg.Title, formattedContent, atList...)
|
||||
} else {
|
||||
return SendError("未知的飞书发送内容类型:%s", contentType), nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return ErrorResult(string(res), err), nil
|
||||
}
|
||||
return SuccessResult(string(res)), nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package channels
|
||||
|
||||
import (
|
||||
"github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type GotifyChannel struct{ *BaseChannel }
|
||||
|
||||
func NewGotifyChannel() Channel {
|
||||
return &GotifyChannel{NewBaseChannel(ChannelGotify, []string{FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *GotifyChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
url := config.GetString("url")
|
||||
token := config.GetString("token")
|
||||
|
||||
if url == "" || token == "" {
|
||||
return SendError("gotify config missing: url and token are required"), nil
|
||||
}
|
||||
|
||||
priority, _ := strconv.Atoi(config.GetString("priority"))
|
||||
cli := message.Gotify{
|
||||
Url: url,
|
||||
Token: token,
|
||||
Priority: priority,
|
||||
}
|
||||
|
||||
res, err := cli.Request(msg.Title, msg.Text)
|
||||
if err != nil {
|
||||
return ErrorResult(string(res), err), nil
|
||||
}
|
||||
return SuccessResult(string(res)), nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package channels
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
|
||||
)
|
||||
|
||||
// replaceBodyPlaceholder 替换自定义 webhook body 中的 TEXT 占位符
|
||||
func replaceBodyPlaceholder(body string, content string) string {
|
||||
data, _ := json.Marshal(content)
|
||||
dataStr := strings.Trim(string(data), "\"")
|
||||
return strings.Replace(body, "TEXT", dataStr, -1)
|
||||
}
|
||||
|
||||
// createAliyunSMSClient 创建阿里云短信客户端
|
||||
func createAliyunSMSClient(accessKeyId, accessKeySecret, regionId string) (*dysmsapi.Client, error) {
|
||||
return dysmsapi.NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret)
|
||||
}
|
||||
|
||||
// sendAliyunSMS 发送短信
|
||||
func sendAliyunSMS(client *dysmsapi.Client, phoneNumber, signName, templateCode, content string, extra map[string]any) (string, error) {
|
||||
templateParam := map[string]interface{}{
|
||||
"content": content,
|
||||
}
|
||||
if extra != nil {
|
||||
for k, v := range extra {
|
||||
templateParam[k] = v
|
||||
}
|
||||
}
|
||||
templateParamJSON, _ := json.Marshal(templateParam)
|
||||
|
||||
request := dysmsapi.CreateSendSmsRequest()
|
||||
request.Scheme = "https"
|
||||
request.PhoneNumbers = phoneNumber
|
||||
request.SignName = signName
|
||||
request.TemplateCode = templateCode
|
||||
request.TemplateParam = string(templateParamJSON)
|
||||
|
||||
response, err := client.SendSms(request)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("发送短信失败: %s", err.Error())
|
||||
}
|
||||
|
||||
if response.Code != "OK" {
|
||||
return "", fmt.Errorf("发送失败: %s - %s", response.Code, response.Message)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("RequestId: %s, BizId: %s", response.RequestId, response.BizId), nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package channels
|
||||
|
||||
import "github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
|
||||
type NtfyChannel struct{ *BaseChannel }
|
||||
|
||||
func NewNtfyChannel() Channel {
|
||||
return &NtfyChannel{NewBaseChannel(ChannelNtfy, []string{FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *NtfyChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
topic := config.GetString("topic")
|
||||
if topic == "" {
|
||||
return SendError("ntfy config missing: topic is required"), nil
|
||||
}
|
||||
|
||||
cli := message.Ntfy{
|
||||
Url: config.GetString("url"),
|
||||
Topic: topic,
|
||||
Priority: config.GetString("priority"),
|
||||
Icon: config.GetString("icon"),
|
||||
Token: config.GetString("token"),
|
||||
Username: config.GetString("username"),
|
||||
Password: config.GetString("password"),
|
||||
Actions: config.GetString("actions"),
|
||||
}
|
||||
|
||||
res, err := cli.Request(msg.Title, msg.Text)
|
||||
if err != nil {
|
||||
return ErrorResult(string(res), err), nil
|
||||
}
|
||||
return SuccessResult(string(res)), nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package channels
|
||||
|
||||
import "github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
|
||||
type PushMeChannel struct{ *BaseChannel }
|
||||
|
||||
func NewPushMeChannel() Channel {
|
||||
return &PushMeChannel{NewBaseChannel(ChannelPushMe, []string{FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *PushMeChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
pushKey := config.GetString("push_key")
|
||||
if pushKey == "" {
|
||||
return SendError("pushme config missing: push_key is required"), nil
|
||||
}
|
||||
|
||||
cli := message.PushMe{
|
||||
PushKey: pushKey,
|
||||
URL: config.GetString("url"),
|
||||
Date: config.GetString("date"),
|
||||
Type: config.GetString("type"),
|
||||
}
|
||||
|
||||
res, err := cli.Request(msg.Title, msg.Text)
|
||||
if err != nil {
|
||||
return ErrorResult(res, err), nil
|
||||
}
|
||||
return SuccessResult(res), nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package channels
|
||||
|
||||
import "github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
|
||||
type QyWeiXinChannel struct{ *BaseChannel }
|
||||
|
||||
func NewQyWeiXinChannel() Channel {
|
||||
return &QyWeiXinChannel{NewBaseChannel(ChannelQyWeiXin, []string{FormatTypeMarkdown, FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *QyWeiXinChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
accessToken := config.GetString("access_token")
|
||||
|
||||
if accessToken == "" {
|
||||
return SendError("qyweixin config missing: access_token is required"), nil
|
||||
}
|
||||
|
||||
contentType, formattedContent := c.FormatContent(msg)
|
||||
atList := []string{}
|
||||
atList = append(atList, msg.GetAtUserIds()...)
|
||||
atList = append(atList, msg.GetAtMobiles()...)
|
||||
if msg.AtAll {
|
||||
atList = append(atList, "@all")
|
||||
}
|
||||
|
||||
cli := message.QyWeiXin{AccessToken: accessToken}
|
||||
var res []byte
|
||||
var err error
|
||||
|
||||
if contentType == FormatTypeText {
|
||||
res, err = cli.SendMessageText(formattedContent, atList...)
|
||||
} else if contentType == FormatTypeMarkdown {
|
||||
res, err = cli.SendMessageMarkdown(msg.Title, formattedContent, atList...)
|
||||
} else {
|
||||
return SendError("未知的企业微信发送内容类型:%s", contentType), nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return ErrorResult(string(res), err), nil
|
||||
}
|
||||
return SuccessResult(string(res)), nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package channels
|
||||
|
||||
import "github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
|
||||
type TelegramChannel struct{ *BaseChannel }
|
||||
|
||||
func NewTelegramChannel() Channel {
|
||||
return &TelegramChannel{NewBaseChannel(ChannelTelegram, []string{FormatTypeMarkdown, FormatTypeHTML, FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *TelegramChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
botToken := config.GetString("bot_token")
|
||||
chatID := config.GetString("chat_id")
|
||||
apiHost := config.GetString("api_host")
|
||||
proxyURL := config.GetString("proxy_url")
|
||||
|
||||
if botToken == "" || chatID == "" {
|
||||
return SendError("telegram config missing: bot_token, chat_id are required"), nil
|
||||
}
|
||||
|
||||
contentType, formattedContent := c.FormatContent(msg)
|
||||
cli := message.Telegram{
|
||||
BotToken: botToken,
|
||||
ChatID: chatID,
|
||||
ApiHost: apiHost,
|
||||
ProxyURL: proxyURL,
|
||||
}
|
||||
|
||||
var res []byte
|
||||
var err error
|
||||
|
||||
switch contentType {
|
||||
case FormatTypeText:
|
||||
res, err = cli.SendMessageText(formattedContent)
|
||||
case FormatTypeMarkdown:
|
||||
res, err = cli.SendMessageMarkdown(formattedContent)
|
||||
case FormatTypeHTML:
|
||||
res, err = cli.SendMessageHTML(formattedContent)
|
||||
default:
|
||||
return SendError("未知的Telegram发送内容类型:%s", contentType), nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return ErrorResult(string(res), err), nil
|
||||
}
|
||||
return SuccessResult(string(res)), nil
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package channels
|
||||
|
||||
// Message 统一消息内容
|
||||
type Message struct {
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
HTML string `json:"html"`
|
||||
Markdown string `json:"markdown"`
|
||||
URL string `json:"url"`
|
||||
ImageURL string `json:"image_url"`
|
||||
Summary string `json:"summary"`
|
||||
AtMobiles []string `json:"at_mobiles"`
|
||||
AtUserIds []string `json:"at_user_ids"`
|
||||
AtAll bool `json:"at_all"`
|
||||
Extra map[string]any `json:"extra"`
|
||||
}
|
||||
|
||||
func (m *Message) HasText() bool { return m.Text != "" }
|
||||
func (m *Message) HasHTML() bool { return m.HTML != "" }
|
||||
func (m *Message) HasMarkdown() bool { return m.Markdown != "" }
|
||||
|
||||
func (m *Message) GetAtMobiles() []string {
|
||||
if m.AtMobiles == nil {
|
||||
return []string{}
|
||||
}
|
||||
return m.AtMobiles
|
||||
}
|
||||
|
||||
func (m *Message) GetAtUserIds() []string {
|
||||
if m.AtUserIds == nil {
|
||||
return []string{}
|
||||
}
|
||||
return m.AtUserIds
|
||||
}
|
||||
|
||||
// ChannelConfig 渠道认证配置(Key-Value 形式,各渠道自行定义字段)
|
||||
type ChannelConfig map[string]string
|
||||
|
||||
// GetString 安全获取配置值
|
||||
func (c ChannelConfig) GetString(key string) string {
|
||||
if v, ok := c[key]; ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Result 发送结果
|
||||
type Result struct {
|
||||
Success bool `json:"success"`
|
||||
Response string `json:"response"` // 原始响应
|
||||
Error string `json:"error"` // 错误信息
|
||||
}
|
||||
|
||||
// 消息格式类型常量
|
||||
const (
|
||||
FormatTypeText = "text"
|
||||
FormatTypeHTML = "html"
|
||||
FormatTypeMarkdown = "markdown"
|
||||
)
|
||||
|
||||
// 渠道类型常量
|
||||
const (
|
||||
ChannelEmail = "Email"
|
||||
ChannelDtalk = "Dtalk"
|
||||
ChannelQyWeiXin = "QyWeiXin"
|
||||
ChannelFeishu = "Feishu"
|
||||
ChannelCustom = "Custom"
|
||||
ChannelWeChatOFAccount = "WeChatOFAccount"
|
||||
ChannelAliyunSMS = "AliyunSMS"
|
||||
ChannelTelegram = "Telegram"
|
||||
ChannelBark = "Bark"
|
||||
ChannelPushMe = "PushMe"
|
||||
ChannelNtfy = "Ntfy"
|
||||
ChannelGotify = "Gotify"
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
package channels
|
||||
|
||||
import "github.com/engigu/baihu-panel/internal/sdk/message"
|
||||
|
||||
type WeChatOFAccountChannel struct{ *BaseChannel }
|
||||
|
||||
func NewWeChatOFAccountChannel() Channel {
|
||||
return &WeChatOFAccountChannel{NewBaseChannel(ChannelWeChatOFAccount, []string{FormatTypeText})}
|
||||
}
|
||||
|
||||
func (c *WeChatOFAccountChannel) Send(config ChannelConfig, msg *Message) (*Result, error) {
|
||||
appID := config.GetString("appID")
|
||||
appSecret := config.GetString("appsecret")
|
||||
tempID := config.GetString("tempid")
|
||||
toAccount := config.GetString("to_account")
|
||||
|
||||
if appID == "" || appSecret == "" {
|
||||
return SendError("wechat config missing: appID, appsecret are required"), nil
|
||||
}
|
||||
if toAccount == "" {
|
||||
return SendError("wechat config missing: to_account is required"), nil
|
||||
}
|
||||
|
||||
_, formattedContent := c.FormatContent(msg)
|
||||
cli := message.WeChatOFAccount{
|
||||
AppID: appID,
|
||||
AppSecret: appSecret,
|
||||
TemplateID: tempID,
|
||||
ToUser: toAccount,
|
||||
URL: msg.URL,
|
||||
}
|
||||
|
||||
res, err := cli.Send(msg.Title, formattedContent)
|
||||
if err != nil {
|
||||
return ErrorResult(res, err), nil
|
||||
}
|
||||
return SuccessResult(res), nil
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
// Package messenger 提供统一的消息发送SDK
|
||||
//
|
||||
// 此包可独立于 Message-Push-Nest 的业务层(数据库、HTTP路由等)使用
|
||||
// 适合在其他服务中直接引入来发送消息
|
||||
//
|
||||
// 快速使用:
|
||||
//
|
||||
// result, err := messenger.Send("Telegram", messenger.ChannelConfig{
|
||||
// "bot_token": "your-bot-token",
|
||||
// "chat_id": "your-chat-id",
|
||||
// }, &messenger.Message{
|
||||
// Title: "Hello",
|
||||
// Text: "World",
|
||||
// })
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/engigu/baihu-panel/internal/sdk/messenger/channels"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// 重导出 channels 包的类型,方便外部使用
|
||||
type (
|
||||
Channel = channels.Channel
|
||||
Message = channels.Message
|
||||
ChannelConfig = channels.ChannelConfig
|
||||
Result = channels.Result
|
||||
BaseChannel = channels.BaseChannel
|
||||
)
|
||||
|
||||
// 重导出常量
|
||||
const (
|
||||
FormatTypeText = channels.FormatTypeText
|
||||
FormatTypeHTML = channels.FormatTypeHTML
|
||||
FormatTypeMarkdown = channels.FormatTypeMarkdown
|
||||
|
||||
ChannelEmail = channels.ChannelEmail
|
||||
ChannelDtalk = channels.ChannelDtalk
|
||||
ChannelQyWeiXin = channels.ChannelQyWeiXin
|
||||
ChannelFeishu = channels.ChannelFeishu
|
||||
ChannelCustom = channels.ChannelCustom
|
||||
ChannelWeChatOFAccount = channels.ChannelWeChatOFAccount
|
||||
ChannelAliyunSMS = channels.ChannelAliyunSMS
|
||||
ChannelTelegram = channels.ChannelTelegram
|
||||
ChannelBark = channels.ChannelBark
|
||||
ChannelPushMe = channels.ChannelPushMe
|
||||
ChannelNtfy = channels.ChannelNtfy
|
||||
ChannelGotify = channels.ChannelGotify
|
||||
)
|
||||
|
||||
// 重导出辅助函数
|
||||
var (
|
||||
SuccessResult = channels.SuccessResult
|
||||
ErrorResult = channels.ErrorResult
|
||||
ErrorResultStr = channels.ErrorResultStr
|
||||
SendError = channels.SendError
|
||||
NewBaseChannel = channels.NewBaseChannel
|
||||
)
|
||||
|
||||
// channelFactory 渠道工厂注册表
|
||||
var (
|
||||
channelFactories = map[string]func() Channel{}
|
||||
factoryMu sync.RWMutex
|
||||
)
|
||||
|
||||
func init() {
|
||||
// 注册所有内置渠道
|
||||
RegisterChannel(ChannelEmail, func() Channel { return channels.NewEmailChannel() })
|
||||
RegisterChannel(ChannelDtalk, func() Channel { return channels.NewDtalkChannel() })
|
||||
RegisterChannel(ChannelQyWeiXin, func() Channel { return channels.NewQyWeiXinChannel() })
|
||||
RegisterChannel(ChannelFeishu, func() Channel { return channels.NewFeishuChannel() })
|
||||
RegisterChannel(ChannelTelegram, func() Channel { return channels.NewTelegramChannel() })
|
||||
RegisterChannel(ChannelBark, func() Channel { return channels.NewBarkChannel() })
|
||||
RegisterChannel(ChannelNtfy, func() Channel { return channels.NewNtfyChannel() })
|
||||
RegisterChannel(ChannelGotify, func() Channel { return channels.NewGotifyChannel() })
|
||||
RegisterChannel(ChannelPushMe, func() Channel { return channels.NewPushMeChannel() })
|
||||
RegisterChannel(ChannelCustom, func() Channel { return channels.NewCustomChannel() })
|
||||
RegisterChannel(ChannelWeChatOFAccount, func() Channel { return channels.NewWeChatOFAccountChannel() })
|
||||
RegisterChannel(ChannelAliyunSMS, func() Channel { return channels.NewAliyunSMSChannel() })
|
||||
}
|
||||
|
||||
// RegisterChannel 注册自定义渠道(可用于扩展)
|
||||
func RegisterChannel(channelType string, factory func() Channel) {
|
||||
factoryMu.Lock()
|
||||
defer factoryMu.Unlock()
|
||||
channelFactories[channelType] = factory
|
||||
}
|
||||
|
||||
// GetChannel 获取渠道实例
|
||||
func GetChannel(channelType string) (Channel, error) {
|
||||
factoryMu.RLock()
|
||||
defer factoryMu.RUnlock()
|
||||
factory, ok := channelFactories[channelType]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("未知的渠道类型: %s", channelType)
|
||||
}
|
||||
return factory(), nil
|
||||
}
|
||||
|
||||
// ListChannels 列出所有已注册的渠道类型
|
||||
func ListChannels() []string {
|
||||
factoryMu.RLock()
|
||||
defer factoryMu.RUnlock()
|
||||
types := make([]string, 0, len(channelFactories))
|
||||
for t := range channelFactories {
|
||||
types = append(types, t)
|
||||
}
|
||||
return types
|
||||
}
|
||||
|
||||
// Send 发送消息的便捷函数
|
||||
//
|
||||
// 参数:
|
||||
// - channelType: 渠道类型(如 "Telegram", "Dtalk" 等)
|
||||
// - config: 渠道必要的认证配置
|
||||
// - msg: 消息内容
|
||||
//
|
||||
// 使用示例:
|
||||
//
|
||||
// result, err := messenger.Send("Ntfy", messenger.ChannelConfig{
|
||||
// "topic": "my-topic",
|
||||
// }, &messenger.Message{
|
||||
// Title: "Alert",
|
||||
// Text: "Something happened!",
|
||||
// })
|
||||
func Send(channelType string, config ChannelConfig, msg *Message) (*Result, error) {
|
||||
ch, err := GetChannel(channelType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ch.Send(config, msg)
|
||||
}
|
||||
|
||||
// Client 消息发送客户端(支持预设默认配置)
|
||||
type Client struct {
|
||||
defaultConfigs map[string]ChannelConfig
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewClient 创建消息发送客户端
|
||||
func NewClient() *Client {
|
||||
return &Client{
|
||||
defaultConfigs: make(map[string]ChannelConfig),
|
||||
}
|
||||
}
|
||||
|
||||
// SetDefaultConfig 为指定渠道设置默认配置
|
||||
//
|
||||
// 使用示例:
|
||||
//
|
||||
// client := messenger.NewClient()
|
||||
// client.SetDefaultConfig("Telegram", messenger.ChannelConfig{
|
||||
// "bot_token": "default-token",
|
||||
// "chat_id": "default-chat",
|
||||
// })
|
||||
// // 后续发送时不需要再传 config 的相关字段
|
||||
// result, err := client.Send("Telegram", nil, &messenger.Message{...})
|
||||
func (c *Client) SetDefaultConfig(channelType string, config ChannelConfig) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.defaultConfigs[channelType] = config
|
||||
}
|
||||
|
||||
// Send 使用客户端发送消息(会合并默认配置)
|
||||
func (c *Client) Send(channelType string, config ChannelConfig, msg *Message) (*Result, error) {
|
||||
mergedConfig := c.mergeConfig(channelType, config)
|
||||
return Send(channelType, mergedConfig, msg)
|
||||
}
|
||||
|
||||
func (c *Client) mergeConfig(channelType string, config ChannelConfig) ChannelConfig {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
defaultConfig, hasDefault := c.defaultConfigs[channelType]
|
||||
if !hasDefault && config == nil {
|
||||
return ChannelConfig{}
|
||||
}
|
||||
if !hasDefault {
|
||||
return config
|
||||
}
|
||||
if config == nil {
|
||||
return defaultConfig
|
||||
}
|
||||
|
||||
// 合并:config 覆盖 defaultConfig
|
||||
merged := make(ChannelConfig, len(defaultConfig)+len(config))
|
||||
for k, v := range defaultConfig {
|
||||
merged[k] = v
|
||||
}
|
||||
for k, v := range config {
|
||||
merged[k] = v
|
||||
}
|
||||
return merged
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/engigu/baihu-panel/internal/constant"
|
||||
"github.com/engigu/baihu-panel/internal/database"
|
||||
"github.com/engigu/baihu-panel/internal/logger"
|
||||
"github.com/engigu/baihu-panel/internal/models"
|
||||
"github.com/engigu/baihu-panel/internal/utils"
|
||||
|
||||
"github.com/engigu/baihu-panel/internal/sdk/messenger"
|
||||
)
|
||||
|
||||
// NotifyChannel 通知渠道配置
|
||||
type NotifyChannel struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Config map[string]string `json:"config"`
|
||||
}
|
||||
|
||||
// NotifyMessage 通知消息
|
||||
type NotifyMessage struct {
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// NotifyResult 发送结果
|
||||
type NotifyResult struct {
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// SupportedChannelTypes 支持的渠道类型
|
||||
var SupportedChannelTypes = []map[string]string{
|
||||
{"type": messenger.ChannelTelegram, "label": "Telegram"},
|
||||
{"type": messenger.ChannelBark, "label": "Bark"},
|
||||
{"type": messenger.ChannelDtalk, "label": "钉钉"},
|
||||
{"type": messenger.ChannelQyWeiXin, "label": "企业微信"},
|
||||
{"type": messenger.ChannelFeishu, "label": "飞书"},
|
||||
{"type": messenger.ChannelEmail, "label": "邮件"},
|
||||
{"type": messenger.ChannelCustom, "label": "自定义Webhook"},
|
||||
{"type": messenger.ChannelNtfy, "label": "Ntfy"},
|
||||
{"type": messenger.ChannelGotify, "label": "Gotify"},
|
||||
{"type": messenger.ChannelPushMe, "label": "PushMe"},
|
||||
// {"type": messenger.ChannelWeChatOFAccount, "label": "微信公众号"},
|
||||
{"type": messenger.ChannelAliyunSMS, "label": "阿里云短信"},
|
||||
}
|
||||
|
||||
// SupportedEvents 支持的事件类型
|
||||
var SupportedEvents = []map[string]string{
|
||||
{"type": constant.EventUserLogin, "label": "用户登录", "binding_type": constant.BindingTypeSystem},
|
||||
{"type": constant.EventBruteForceLogin, "label": "密码多次错误", "binding_type": constant.BindingTypeSystem},
|
||||
{"type": constant.EventPasswordChanged, "label": "密码修改", "binding_type": constant.BindingTypeSystem},
|
||||
{"type": constant.EventTaskSuccess, "label": "任务成功", "binding_type": constant.BindingTypeTask},
|
||||
{"type": constant.EventTaskFailed, "label": "任务失败", "binding_type": constant.BindingTypeTask},
|
||||
{"type": constant.EventTaskTimeout, "label": "任务超时", "binding_type": constant.BindingTypeTask},
|
||||
}
|
||||
|
||||
type NotificationService struct {
|
||||
settingsService *SettingsService
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewNotificationService() *NotificationService {
|
||||
return &NotificationService{
|
||||
settingsService: NewSettingsService(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetChannels 获取所有渠道
|
||||
func (s *NotificationService) GetChannels() []NotifyChannel {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.getChannelsInternal()
|
||||
}
|
||||
|
||||
// SaveChannel 保存/更新渠道
|
||||
func (s *NotificationService) SaveChannel(channel NotifyChannel) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
configJSON, err := json.Marshal(channel.Config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if channel.ID == "" {
|
||||
// 新建
|
||||
channel.ID = utils.GenerateID()
|
||||
notifyWay := &models.NotifyWay{
|
||||
ID: channel.ID,
|
||||
Name: channel.Name,
|
||||
Type: channel.Type,
|
||||
Config: string(configJSON),
|
||||
Enabled: channel.Enabled,
|
||||
}
|
||||
return database.DB.Create(notifyWay).Error
|
||||
}
|
||||
|
||||
// 更新
|
||||
updates := map[string]interface{}{
|
||||
"name": channel.Name,
|
||||
"type": channel.Type,
|
||||
"config": string(configJSON),
|
||||
"enabled": channel.Enabled,
|
||||
}
|
||||
return database.DB.Model(&models.NotifyWay{}).Where("id = ?", channel.ID).Updates(updates).Error
|
||||
}
|
||||
|
||||
// DeleteChannel 删除渠道
|
||||
func (s *NotificationService) DeleteChannel(id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
// 检查渠道是否存在
|
||||
var count int64
|
||||
database.DB.Model(&models.NotifyWay{}).Where("id = ?", id).Count(&count)
|
||||
if count == 0 {
|
||||
return fmt.Errorf("渠道 %s 不存在", id)
|
||||
}
|
||||
|
||||
// 删除渠道
|
||||
if err := database.DB.Unscoped().Where("id = ?", id).Delete(&models.NotifyWay{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 同时清理事件绑定中引用此渠道的配置
|
||||
if err := database.DB.Unscoped().Where("way_id = ?", id).Delete(&models.NotifyBinding{}).Error; err != nil {
|
||||
logger.Errorf("[Notify] 清理事件绑定失败: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBindings 获取事件绑定列表(新接口,用于前端展示)
|
||||
func (s *NotificationService) GetBindings() []models.NotifyBinding {
|
||||
var bindings []models.NotifyBinding
|
||||
database.DB.Find(&bindings)
|
||||
return bindings
|
||||
}
|
||||
|
||||
// SaveBinding 保存事件绑定
|
||||
func (s *NotificationService) SaveBinding(binding *models.NotifyBinding) error {
|
||||
if binding.ID == "" {
|
||||
// 检查是否已经存在相同的绑定(避免重复点击导致多个记录)
|
||||
var existing models.NotifyBinding
|
||||
err := database.DB.Where("type = ? AND event = ? AND way_id = ? AND data_id = ?",
|
||||
binding.Type, binding.Event, binding.WayID, binding.DataID).First(&existing).Error
|
||||
if err == nil {
|
||||
// 如果已存在且未删除,直接返回(或者更新它)
|
||||
*binding = existing
|
||||
return nil
|
||||
}
|
||||
|
||||
binding.ID = utils.GenerateID()
|
||||
return database.DB.Create(binding).Error
|
||||
}
|
||||
return database.DB.Save(binding).Error
|
||||
}
|
||||
|
||||
// DeleteBinding 删除事件绑定
|
||||
func (s *NotificationService) DeleteBinding(id string) error {
|
||||
return database.DB.Unscoped().Where("id = ?", id).Delete(&models.NotifyBinding{}).Error
|
||||
}
|
||||
|
||||
// GetBindingsByEvent 根据事件类型和数据ID获取绑定
|
||||
func (s *NotificationService) GetBindingsByEvent(bindingType, event, dataID string) []models.NotifyBinding {
|
||||
var bindings []models.NotifyBinding
|
||||
|
||||
// 如果是任务事件且带有 dataID,只获取特定任务的绑定(禁用全局任务配置)
|
||||
if bindingType == constant.BindingTypeTask && dataID != "" {
|
||||
database.DB.Where("type = ? AND event = ? AND data_id = ?", constant.BindingTypeTask, event, dataID).Find(&bindings)
|
||||
return bindings
|
||||
}
|
||||
|
||||
// 对于系统事件或其他情况
|
||||
query := database.DB.Where("event = ?", event)
|
||||
if bindingType != "" {
|
||||
query = query.Where("type = ?", bindingType)
|
||||
}
|
||||
|
||||
if dataID != "" {
|
||||
query = query.Where("data_id = ?", dataID)
|
||||
} else {
|
||||
query = query.Where("data_id = ? OR data_id IS NULL", "")
|
||||
}
|
||||
|
||||
query.Find(&bindings)
|
||||
return bindings
|
||||
}
|
||||
|
||||
// SendToChannel 使用 messenger SDK 发送通知到指定渠道
|
||||
func (s *NotificationService) SendToChannel(channel NotifyChannel, msg *NotifyMessage) *NotifyResult {
|
||||
result, err := messenger.Send(channel.Type, messenger.ChannelConfig(channel.Config), &messenger.Message{
|
||||
Title: msg.Title,
|
||||
Text: msg.Text,
|
||||
})
|
||||
if err != nil {
|
||||
return &NotifyResult{Success: false, Error: err.Error()}
|
||||
}
|
||||
if !result.Success {
|
||||
return &NotifyResult{Success: false, Error: result.Error}
|
||||
}
|
||||
return &NotifyResult{Success: true}
|
||||
}
|
||||
|
||||
// SendByChannelID 根据渠道ID发送通知
|
||||
func (s *NotificationService) SendByChannelID(channelID string, msg *NotifyMessage) *NotifyResult {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
var notifyWay models.NotifyWay
|
||||
if err := database.DB.Where("id = ?", channelID).First(¬ifyWay).Error; err != nil {
|
||||
return &NotifyResult{Success: false, Error: "渠道不存在"}
|
||||
}
|
||||
|
||||
if !notifyWay.Enabled {
|
||||
return &NotifyResult{Success: false, Error: "渠道已禁用"}
|
||||
}
|
||||
|
||||
var config map[string]string
|
||||
if err := json.Unmarshal([]byte(notifyWay.Config), &config); err != nil {
|
||||
return &NotifyResult{Success: false, Error: "渠道配置解析失败"}
|
||||
}
|
||||
|
||||
ch := NotifyChannel{
|
||||
ID: notifyWay.ID,
|
||||
Name: notifyWay.Name,
|
||||
Type: notifyWay.Type,
|
||||
Enabled: notifyWay.Enabled,
|
||||
Config: config,
|
||||
}
|
||||
return s.SendToChannel(ch, msg)
|
||||
}
|
||||
|
||||
// TriggerEvent 触发事件通知(实现 tasks.Notifier 接口)
|
||||
func (s *NotificationService) TriggerEvent(bindingType string, eventType string, dataID string, templateData map[string]interface{}) {
|
||||
var title, text string
|
||||
|
||||
switch eventType {
|
||||
case constant.EventUserLogin:
|
||||
title = "用户登录通知"
|
||||
text = fmt.Sprintf("用户 %v 在 IP %v 登录成功", templateData["username"], templateData["ip"])
|
||||
case constant.EventBruteForceLogin:
|
||||
title = "系统安全警告"
|
||||
text = fmt.Sprintf("检测到 IP %v 正在尝试暴力破解用户 %v", templateData["ip"], templateData["username"])
|
||||
case constant.EventPasswordChanged:
|
||||
title = "账户安全通知"
|
||||
text = fmt.Sprintf("用户 %v 刚刚修改了密码", templateData["username"])
|
||||
case constant.EventTaskSuccess:
|
||||
title = fmt.Sprintf("任务[%v] 成功", templateData["task_name"])
|
||||
text = fmt.Sprintf("任务 #%v %v\n状态: 成功\n耗时: %vms", templateData["task_id"], templateData["task_name"], templateData["duration"])
|
||||
case constant.EventTaskFailed:
|
||||
title = fmt.Sprintf("任务[%v] 失败", templateData["task_name"])
|
||||
if errStr, ok := templateData["error"]; ok {
|
||||
text = fmt.Sprintf("任务 #%v %v\n执行失败\n错误: %v", templateData["task_id"], templateData["task_name"], errStr)
|
||||
} else {
|
||||
text = fmt.Sprintf("任务 #%v %v\n执行失败\n状态: %v\n耗时: %vms", templateData["task_id"], templateData["task_name"], templateData["status"], templateData["duration"])
|
||||
}
|
||||
case constant.EventTaskTimeout:
|
||||
title = fmt.Sprintf("任务[%v] 超时", templateData["task_name"])
|
||||
text = fmt.Sprintf("任务 #%v %v\n执行超时\n耗时: %vms", templateData["task_id"], templateData["task_name"], templateData["duration"])
|
||||
default:
|
||||
title = "系统通知"
|
||||
text = "收到未知事件"
|
||||
}
|
||||
|
||||
msg := &NotifyMessage{Title: title, Text: text}
|
||||
|
||||
bindings := s.GetBindingsByEvent(bindingType, eventType, dataID)
|
||||
if len(bindings) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
channels := s.GetChannels()
|
||||
channelMap := make(map[string]NotifyChannel)
|
||||
for _, ch := range channels {
|
||||
channelMap[ch.ID] = ch
|
||||
}
|
||||
|
||||
for _, binding := range bindings {
|
||||
ch, ok := channelMap[binding.WayID]
|
||||
if !ok || !ch.Enabled {
|
||||
continue
|
||||
}
|
||||
go func(channel NotifyChannel) {
|
||||
result := s.SendToChannel(channel, msg)
|
||||
if !result.Success {
|
||||
logger.Warnf("[Notify] 发送事件 %s 到渠道 %s(%s) 失败: %s", eventType, channel.Name, channel.Type, result.Error)
|
||||
}
|
||||
}(ch)
|
||||
}
|
||||
}
|
||||
|
||||
// --- 内部方法 ---
|
||||
|
||||
// getChannelsInternal 从 notify_ways 表中读取所有渠道配置
|
||||
func (s *NotificationService) getChannelsInternal() []NotifyChannel {
|
||||
var notifyWays []models.NotifyWay
|
||||
database.DB.Find(¬ifyWays)
|
||||
|
||||
channels := make([]NotifyChannel, 0, len(notifyWays))
|
||||
for _, nw := range notifyWays {
|
||||
var config map[string]string
|
||||
if err := json.Unmarshal([]byte(nw.Config), &config); err != nil {
|
||||
logger.Warnf("[Notify] 解析渠道 %s 配置失败: %v", nw.ID, err)
|
||||
continue
|
||||
}
|
||||
channels = append(channels, NotifyChannel{
|
||||
ID: nw.ID,
|
||||
Name: nw.Name,
|
||||
Type: nw.Type,
|
||||
Enabled: nw.Enabled,
|
||||
Config: config,
|
||||
})
|
||||
}
|
||||
return channels
|
||||
}
|
||||
@@ -89,6 +89,11 @@ func (s *SettingsService) Set(section, key, value string) error {
|
||||
return database.DB.Model(&setting).Update("value", value).Error
|
||||
}
|
||||
|
||||
// Delete 删除单个设置
|
||||
func (s *SettingsService) Delete(section, key string) error {
|
||||
return database.DB.Where("section = ? AND `key` = ?", section, key).Delete(&models.Setting{}).Error
|
||||
}
|
||||
|
||||
// GetSection 获取整个 section 的设置
|
||||
func (s *SettingsService) GetSection(section string) map[string]string {
|
||||
if section == constant.SectionSite {
|
||||
|
||||
@@ -39,6 +39,11 @@ type EnvService interface {
|
||||
GetEnvVarsByIDs(ids string) []string
|
||||
}
|
||||
|
||||
// Notifier 通知服务接口定义(避免循环依赖)
|
||||
type Notifier interface {
|
||||
TriggerEvent(bindingType string, eventType string, dataID string, templateData map[string]interface{})
|
||||
}
|
||||
|
||||
// ExecutorService handles task execution and scheduling
|
||||
type ExecutorService struct {
|
||||
taskService *TaskService
|
||||
@@ -46,6 +51,7 @@ type ExecutorService struct {
|
||||
agentWSManager AgentWSManager
|
||||
settingsService SettingsService
|
||||
envService EnvService
|
||||
notifier Notifier
|
||||
scheduler *executor.Scheduler
|
||||
cronManager *executor.CronManager
|
||||
results []executor.ExecutionResult
|
||||
@@ -65,6 +71,7 @@ func NewExecutorService(
|
||||
agentWSManager AgentWSManager,
|
||||
settingsService SettingsService,
|
||||
envService EnvService,
|
||||
notifier Notifier,
|
||||
) *ExecutorService {
|
||||
es := &ExecutorService{
|
||||
taskService: taskService,
|
||||
@@ -72,6 +79,7 @@ func NewExecutorService(
|
||||
agentWSManager: agentWSManager,
|
||||
settingsService: settingsService,
|
||||
envService: envService,
|
||||
notifier: notifier,
|
||||
results: make([]executor.ExecutionResult, 0, 100),
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
@@ -246,6 +254,29 @@ func (h *ServerSchedulerHandler) OnTaskCompleted(req *executor.ExecutionRequest,
|
||||
|
||||
// ======= 重试逻辑 =======
|
||||
h.es.HandleTaskRetry(task, req, result.Success, result.Status, result.ExitCode)
|
||||
|
||||
// ======= 通知触发 =======
|
||||
if h.es.notifier != nil {
|
||||
go func() {
|
||||
var eventType string
|
||||
switch result.Status {
|
||||
case constant.TaskStatusSuccess:
|
||||
eventType = constant.EventTaskSuccess
|
||||
case constant.TaskStatusFailed:
|
||||
eventType = constant.EventTaskFailed
|
||||
case constant.TaskStatusTimeout:
|
||||
eventType = constant.EventTaskTimeout
|
||||
}
|
||||
if eventType != "" {
|
||||
h.es.notifier.TriggerEvent(constant.BindingTypeTask, eventType, task.ID, map[string]interface{}{
|
||||
"task_id": task.ID,
|
||||
"task_name": task.Name,
|
||||
"status": result.Status,
|
||||
"duration": result.Duration,
|
||||
})
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *ServerSchedulerHandler) OnTaskFailed(req *executor.ExecutionRequest, err error) {
|
||||
@@ -305,6 +336,21 @@ func (h *ServerSchedulerHandler) OnTaskFailed(req *executor.ExecutionRequest, er
|
||||
|
||||
// ======= 重试逻辑 =======
|
||||
h.es.HandleTaskRetry(task, req, false, constant.TaskStatusFailed, 1)
|
||||
|
||||
// ======= 通知触发 =======
|
||||
if h.es.notifier != nil {
|
||||
go func() {
|
||||
taskName := "未知任务"
|
||||
if task != nil {
|
||||
taskName = task.Name
|
||||
}
|
||||
h.es.notifier.TriggerEvent(constant.BindingTypeTask, constant.EventTaskFailed, taskID, map[string]interface{}{
|
||||
"task_id": taskID,
|
||||
"task_name": taskName,
|
||||
"error": err.Error(),
|
||||
})
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// HandleTaskRetry 处理任务失败重试逻辑
|
||||
|
||||
@@ -124,6 +124,9 @@ func (ts *TaskService) UpdateTask(id string, name, command, schedule string, tim
|
||||
}
|
||||
|
||||
func (ts *TaskService) DeleteTask(id string) bool {
|
||||
// 同时删除关联的通知推送设置
|
||||
database.DB.Where("type = ? AND data_id = ?", constant.BindingTypeTask, id).Delete(&models.NotifyBinding{})
|
||||
|
||||
result := database.DB.Where("id = ?", id).Delete(&models.Task{})
|
||||
return result.RowsAffected > 0
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user