feat: 完善后端并新增 Vue3 WebUI
后端: - 修复登录校验、DB 并发(单例+WAL+纯Go sqlite)、会话密钥持久化等核心缺陷 - 新增 Timer CRUD/签到/手动触发、执行日志、仪表盘、驱动元数据等 API - 统一驱动接口: 带 context 的执行器、真实错误返回、敏感字段掩码、连通性测试 - 补全钉钉执行器; Timer 触发/提醒去重; 配置支持默认值与环境变量覆盖 前端: - Vite+Vue3+TS+Pinia+Element Plus, 由驱动元数据动态渲染配置表单 - 登录/仪表盘(倒计时环)/定时器/规则/账号/日志/设置页面, 支持暗色模式 - 主题色 #66ccff, 信号波纹 logo, go:embed 单二进制部署 构建: Dockerfile 增加前端构建阶段; 补充各驱动配置文档 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,19 +3,21 @@ package bilibili
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/internal/meta"
|
||||
)
|
||||
|
||||
// BilibiliAccountConfigValidator B站账号配置验证器
|
||||
type BilibiliAccountConfigValidator struct{}
|
||||
|
||||
func (v *BilibiliAccountConfigValidator) GetType() string {
|
||||
return "bilibili-account"
|
||||
return AccountType
|
||||
}
|
||||
|
||||
func (v *BilibiliAccountConfigValidator) Validate(config string) error {
|
||||
var cfg BiliAccount
|
||||
if err := json.Unmarshal([]byte(config), &cfg); err != nil {
|
||||
return fmt.Errorf("解析B站账号配置失败: %v", err)
|
||||
cfg, err := parseAccount(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cfg.RawCookies == "" {
|
||||
@@ -24,3 +26,49 @@ func (v *BilibiliAccountConfigValidator) Validate(config string) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Test 用 cookie 拉一次账号信息,验证 cookie 是否还有效
|
||||
func (v *BilibiliAccountConfigValidator) Test(config string) error {
|
||||
cfg, err := parseAccount(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
client := newClient(cfg.RawCookies)
|
||||
info, err := client.GetAccountInformation()
|
||||
if err != nil {
|
||||
return fmt.Errorf("B站 cookie 校验失败: %w", err)
|
||||
}
|
||||
if info == nil || info.Mid == 0 {
|
||||
return fmt.Errorf("B站 cookie 无效或已过期")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *BilibiliAccountConfigValidator) Meta() meta.AccountMeta {
|
||||
return meta.AccountMeta{
|
||||
Type: AccountType,
|
||||
Label: "哔哩哔哩",
|
||||
Description: "使用浏览器中的完整 Cookie 登录 B 站,用于发送动态。",
|
||||
Docs: "docs/bilibili-config.md",
|
||||
Fields: []meta.Field{
|
||||
{
|
||||
Key: "raw_cookies",
|
||||
Label: "Cookies",
|
||||
Type: meta.FieldTextarea,
|
||||
Required: true,
|
||||
Secret: true,
|
||||
Placeholder: "SESSDATA=xxx; bili_jct=xxx; DedeUserID=xxx",
|
||||
Help: "登录 bilibili.com 后从浏览器开发者工具复制完整的 Cookie 字符串",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func parseAccount(config string) (*BiliAccount, error) {
|
||||
var cfg BiliAccount
|
||||
if err := json.Unmarshal([]byte(config), &cfg); err != nil {
|
||||
return nil, fmt.Errorf("解析B站账号配置失败: %v", err)
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
@@ -2,55 +2,40 @@ package bilibili
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
"fmt"
|
||||
|
||||
"github.com/CuteReimu/bilibili/v2"
|
||||
"github.com/cenkalti/backoff/v5"
|
||||
"github.com/ssdomei232/goodBaby/configs"
|
||||
"github.com/ssdomei232/goodBaby/internal/retry"
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
)
|
||||
|
||||
// 在Bilibili动态发送消息
|
||||
// SendBiliDynamicMsg 在 Bilibili 动态发送消息
|
||||
//
|
||||
// 暂时没有处理 429 和 403 的区别对待
|
||||
func SendBiliDynamicMsg(rule *model.Rule) {
|
||||
config, err := configs.GetConfig()
|
||||
if err != nil {
|
||||
log.Printf("获取配置失败: %v", err)
|
||||
return
|
||||
}
|
||||
var timeout time.Duration = time.Duration(config.TimeoutDurationHours) * time.Hour
|
||||
|
||||
func SendBiliDynamicMsg(ctx context.Context, rule *model.Rule) error {
|
||||
biliClient, err := getBiliClient(rule)
|
||||
if err != nil {
|
||||
log.Printf("获取B站客户端失败: %v", err)
|
||||
return
|
||||
}
|
||||
biliDyncmicConfig, err := getBiliDynamicConfig(rule)
|
||||
if err != nil {
|
||||
log.Printf("获取B站动态配置失败: %v", err)
|
||||
return
|
||||
return fmt.Errorf("获取B站客户端失败: %w", err)
|
||||
}
|
||||
|
||||
var dynamicParams bilibili.CreateDynamicParam
|
||||
dynamicParams = bilibili.CreateDynamicParam{
|
||||
biliDynamicConfig, err := getBiliDynamicConfig(rule)
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取B站动态配置失败: %w", err)
|
||||
}
|
||||
|
||||
dynamicParams := bilibili.CreateDynamicParam{
|
||||
DynamicId: 0,
|
||||
Type: 4,
|
||||
Rid: 0,
|
||||
Content: biliDyncmicConfig.Msg,
|
||||
Content: biliDynamicConfig.Msg,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
operation := func() (string, error) {
|
||||
if err := retry.Do(ctx, func() error {
|
||||
_, err := biliClient.CreateDynamic(dynamicParams)
|
||||
return "", err
|
||||
return err
|
||||
}); err != nil {
|
||||
return fmt.Errorf("发送B站动态失败: %w", err)
|
||||
}
|
||||
|
||||
_, err = backoff.Retry(ctx, operation, backoff.WithBackOff(backoff.NewExponentialBackOff()))
|
||||
if err != nil {
|
||||
log.Printf("发送B站动态失败: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
package bilibili
|
||||
|
||||
const (
|
||||
// AccountType B 站账号类型标识
|
||||
AccountType = "bilibili"
|
||||
// RuleTypeDynamic 发送 B 站动态的规则类型标识
|
||||
RuleTypeDynamic = "bilibili-dynamic"
|
||||
)
|
||||
|
||||
type BiliAccount struct {
|
||||
RawCookies string `json:"raw_cookies"`
|
||||
}
|
||||
|
||||
@@ -3,13 +3,15 @@ package bilibili
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/internal/meta"
|
||||
)
|
||||
|
||||
// BilibiliDynamicRuleValidator B站动态规则验证器
|
||||
type BilibiliDynamicRuleValidator struct{}
|
||||
|
||||
func (v *BilibiliDynamicRuleValidator) GetType() string {
|
||||
return "bilibili-dynamic"
|
||||
return RuleTypeDynamic
|
||||
}
|
||||
|
||||
func (v *BilibiliDynamicRuleValidator) Validate(configJSON string) error {
|
||||
@@ -22,5 +24,28 @@ func (v *BilibiliDynamicRuleValidator) Validate(configJSON string) error {
|
||||
return fmt.Errorf("B站动态规则配置中 msg 不能为空")
|
||||
}
|
||||
|
||||
if len([]rune(config.Msg)) > 1000 {
|
||||
return fmt.Errorf("B站动态内容过长")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *BilibiliDynamicRuleValidator) Meta() meta.RuleMeta {
|
||||
return meta.RuleMeta{
|
||||
Type: RuleTypeDynamic,
|
||||
Label: "发送 B 站动态",
|
||||
Description: "触发时以关联的 B 站账号发送一条动态。",
|
||||
Docs: "docs/bilibili-config.md",
|
||||
AccountType: AccountType,
|
||||
Fields: []meta.Field{
|
||||
{
|
||||
Key: "msg",
|
||||
Label: "动态内容",
|
||||
Type: meta.FieldTextarea,
|
||||
Required: true,
|
||||
Placeholder: "要发送的动态正文",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package bilibili
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
@@ -10,13 +11,11 @@ import (
|
||||
type BilibiliDynamicExecutor struct{}
|
||||
|
||||
func (e *BilibiliDynamicExecutor) GetType() string {
|
||||
return "bilibili-dynamic"
|
||||
return RuleTypeDynamic
|
||||
}
|
||||
|
||||
func (e *BilibiliDynamicExecutor) Execute(rule *model.Rule) error {
|
||||
func (e *BilibiliDynamicExecutor) Execute(ctx context.Context, rule *model.Rule) error {
|
||||
log.Printf("执行B站动态规则: %s (ID: %d)", rule.Name, rule.ID)
|
||||
|
||||
SendBiliDynamicMsg(rule)
|
||||
|
||||
return nil
|
||||
return SendBiliDynamicMsg(ctx, rule)
|
||||
}
|
||||
|
||||
+10
-22
@@ -8,38 +8,26 @@ import (
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
)
|
||||
|
||||
func newClient(rawCookies string) *bilibili.Client {
|
||||
client := bilibili.New()
|
||||
client.SetRawCookies(rawCookies)
|
||||
return client
|
||||
}
|
||||
|
||||
// 获取 Bilibili Client
|
||||
func getBiliClient(rule *model.Rule) (*bilibili.Client, error) {
|
||||
client := bilibili.New()
|
||||
gormDB, err := db.GetGormDB()
|
||||
if err != nil {
|
||||
var accountConfig BiliAccount
|
||||
if err := db.LoadAccountConfig(rule.AccountID, &accountConfig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 1. 通过 account_id 获取到对应的 account 配置
|
||||
var biliAccount model.Account
|
||||
result := gormDB.Where("id = ?", rule.AccountID).First(&biliAccount)
|
||||
if result.Error != nil {
|
||||
return nil, result.Error
|
||||
}
|
||||
|
||||
// 2. 通过 account 配置中的 config 字段获取到 CookiesString
|
||||
var biliAccountConfig BiliAccount
|
||||
err = json.Unmarshal([]byte(biliAccount.Config), &biliAccountConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client.SetRawCookies(biliAccountConfig.RawCookies)
|
||||
|
||||
return client, nil
|
||||
return newClient(accountConfig.RawCookies), nil
|
||||
}
|
||||
|
||||
// 获取 Bilibili Dynamic Config
|
||||
func getBiliDynamicConfig(rule *model.Rule) (*BiliDynamicConfig, error) {
|
||||
var biliDynamicConfig BiliDynamicConfig
|
||||
err := json.Unmarshal([]byte(rule.ConfigJson), &biliDynamicConfig)
|
||||
if err != nil {
|
||||
if err := json.Unmarshal([]byte(rule.ConfigJson), &biliDynamicConfig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
@@ -1,23 +1,33 @@
|
||||
// dingtalk 仅用于发送提醒
|
||||
// Package dingtalk 提供钉钉自定义机器人的提醒与规则执行能力
|
||||
package dingtalk
|
||||
|
||||
import (
|
||||
"log"
|
||||
"fmt"
|
||||
|
||||
"github.com/CatchZeng/dingtalk/pkg/dingtalk"
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
)
|
||||
|
||||
func SendDingTalkMsg(user *model.User, title string, msg string) {
|
||||
dingtalkAccount := getDingTalkConfigFromUser(user)
|
||||
if dingtalkAccount == nil {
|
||||
return
|
||||
}
|
||||
|
||||
client := dingtalk.NewClient(dingtalkAccount.AccessToken, dingtalkAccount.Secret)
|
||||
sendMsg := dingtalk.NewMarkdownMessage().SetMarkdown(title, msg)
|
||||
_, _, err := client.Send(sendMsg)
|
||||
if err != nil {
|
||||
log.Printf("发送钉钉消息失败: %v", err)
|
||||
// SendDingTalkMsg 使用用户配置的钉钉机器人发送提醒
|
||||
//
|
||||
// 用户没有配置钉钉机器人时返回 ErrNoUserConfig
|
||||
func SendDingTalkMsg(user *model.User, title string, msg string) error {
|
||||
config := getDingTalkConfigFromUser(user)
|
||||
if config == nil {
|
||||
return ErrNoUserConfig
|
||||
}
|
||||
return send(config, title, msg)
|
||||
}
|
||||
|
||||
// ErrNoUserConfig 表示用户没有配置钉钉提醒
|
||||
var ErrNoUserConfig = fmt.Errorf("用户未配置钉钉机器人")
|
||||
|
||||
func send(config *DingTalkConfig, title, msg string) error {
|
||||
client := dingtalk.NewClient(config.AccessToken, config.Secret)
|
||||
message := dingtalk.NewMarkdownMessage().SetMarkdown(title, msg)
|
||||
|
||||
if _, _, err := client.Send(message); err != nil {
|
||||
return fmt.Errorf("发送钉钉消息失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
package dingtalk
|
||||
|
||||
// RuleType 钉钉机器人规则类型标识
|
||||
const RuleType = "dingtalk"
|
||||
|
||||
// DingTalkConfig 钉钉自定义机器人凭据,用户级提醒配置也用这个结构
|
||||
type DingTalkConfig struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
Secret string `json:"secret"`
|
||||
}
|
||||
|
||||
// DingTalkRuleConfig 钉钉规则配置:凭据 + 要发送的内容
|
||||
type DingTalkRuleConfig struct {
|
||||
DingTalkConfig
|
||||
Title string `json:"title"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
@@ -3,24 +3,56 @@ package dingtalk
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/internal/meta"
|
||||
)
|
||||
|
||||
// DingTalkRuleValidator 钉钉规则验证器
|
||||
type DingTalkRuleValidator struct{}
|
||||
|
||||
func (v *DingTalkRuleValidator) GetType() string {
|
||||
return "dingtalk"
|
||||
return RuleType
|
||||
}
|
||||
|
||||
func (v *DingTalkRuleValidator) Validate(configJSON string) error {
|
||||
var config DingTalkConfig
|
||||
if err := json.Unmarshal([]byte(configJSON), &config); err != nil {
|
||||
return fmt.Errorf("解析钉钉规则配置失败: %v", err)
|
||||
config, err := ParseRuleConfig(configJSON)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if config.AccessToken == "" {
|
||||
return fmt.Errorf("钉钉规则配置中 access_token 不能为空")
|
||||
}
|
||||
if config.Title == "" {
|
||||
return fmt.Errorf("钉钉规则配置中 title 不能为空")
|
||||
}
|
||||
if config.Msg == "" {
|
||||
return fmt.Errorf("钉钉规则配置中 msg 不能为空")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *DingTalkRuleValidator) Meta() meta.RuleMeta {
|
||||
return meta.RuleMeta{
|
||||
Type: RuleType,
|
||||
Label: "钉钉机器人消息",
|
||||
Description: "触发时通过钉钉自定义机器人发送一条 Markdown 消息,不需要关联账号。",
|
||||
AccountType: "", // 凭据直接写在规则里,无需账号
|
||||
Fields: []meta.Field{
|
||||
{Key: "access_token", Label: "Access Token", Type: meta.FieldPassword, Required: true, Secret: true, Help: "机器人 Webhook 中 access_token 参数的值"},
|
||||
{Key: "secret", Label: "加签 Secret", Type: meta.FieldPassword, Secret: true, Help: "机器人安全设置选择“加签”时填写"},
|
||||
{Key: "title", Label: "消息标题", Type: meta.FieldString, Required: true},
|
||||
{Key: "msg", Label: "消息内容", Type: meta.FieldTextarea, Required: true, Help: "支持 Markdown"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ParseRuleConfig 解析钉钉规则配置
|
||||
func ParseRuleConfig(configJSON string) (*DingTalkRuleConfig, error) {
|
||||
var config DingTalkRuleConfig
|
||||
if err := json.Unmarshal([]byte(configJSON), &config); err != nil {
|
||||
return nil, fmt.Errorf("解析钉钉规则配置失败: %v", err)
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package dingtalk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/internal/retry"
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
)
|
||||
|
||||
// DingTalkExecutor 钉钉机器人执行器
|
||||
//
|
||||
// 之前只注册了校验器却没有执行器,导致钉钉规则可以创建但永远不会被执行。
|
||||
type DingTalkExecutor struct{}
|
||||
|
||||
func (e *DingTalkExecutor) GetType() string {
|
||||
return RuleType
|
||||
}
|
||||
|
||||
func (e *DingTalkExecutor) Execute(ctx context.Context, rule *model.Rule) error {
|
||||
log.Printf("执行钉钉规则: %s (ID: %d)", rule.Name, rule.ID)
|
||||
|
||||
config, err := ParseRuleConfig(rule.ConfigJson)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return retry.Do(ctx, func() error {
|
||||
return send(&config.DingTalkConfig, config.Title, config.Msg)
|
||||
})
|
||||
}
|
||||
@@ -1,29 +1,33 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/mail"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/internal/meta"
|
||||
"github.com/ssdomei232/goodBaby/internal/retry"
|
||||
)
|
||||
|
||||
// EmailAccountConfigValidator 邮箱账号配置验证器
|
||||
type EmailAccountConfigValidator struct{}
|
||||
|
||||
func (v *EmailAccountConfigValidator) GetType() string {
|
||||
return "email-account"
|
||||
return AccountType
|
||||
}
|
||||
|
||||
func (v *EmailAccountConfigValidator) Validate(config string) error {
|
||||
// 邮箱账号配置验证逻辑
|
||||
var cfg EmailAccountConfig
|
||||
if err := json.Unmarshal([]byte(config), &cfg); err != nil {
|
||||
return fmt.Errorf("解析邮箱账号配置失败: %v", err)
|
||||
cfg, err := parseAccountConfig(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cfg.SMTPServer == "" {
|
||||
return fmt.Errorf("邮箱账号配置中 SMTP 服务器不能为空")
|
||||
}
|
||||
if cfg.Port == 0 {
|
||||
return fmt.Errorf("邮箱账号配置中 SMTP 端口不能为空")
|
||||
if cfg.Port <= 0 || cfg.Port > 65535 {
|
||||
return fmt.Errorf("邮箱账号配置中 SMTP 端口不合法")
|
||||
}
|
||||
if cfg.Username == "" {
|
||||
return fmt.Errorf("邮箱账号配置中用户名不能为空")
|
||||
@@ -31,6 +35,79 @@ func (v *EmailAccountConfigValidator) Validate(config string) error {
|
||||
if cfg.Password == "" {
|
||||
return fmt.Errorf("邮箱账号配置中密码不能为空")
|
||||
}
|
||||
switch cfg.SecurityOrDefault() {
|
||||
case SecuritySSL, SecuritySTARTTLS, SecurityNone:
|
||||
default:
|
||||
return fmt.Errorf("不支持的加密方式: %s", cfg.Security)
|
||||
}
|
||||
if cfg.From != "" {
|
||||
if _, err := mail.ParseAddress(cfg.From); err != nil {
|
||||
return fmt.Errorf("发件人地址不合法: %s", cfg.From)
|
||||
}
|
||||
}
|
||||
if cfg.TestDestination != "" {
|
||||
if _, err := mail.ParseAddress(cfg.TestDestination); err != nil {
|
||||
return fmt.Errorf("测试收件地址不合法: %s", cfg.TestDestination)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Test 连接 SMTP 服务器并完成认证;填写了测试收件地址时会真的发一封测试邮件
|
||||
func (v *EmailAccountConfigValidator) Test(config string) error {
|
||||
cfg, err := parseAccountConfig(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
client, err := newSMTPClient(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), retry.TestTimeout)
|
||||
defer cancel()
|
||||
|
||||
if cfg.TestDestination == "" {
|
||||
if err := client.DialWithContext(ctx); err != nil {
|
||||
return fmt.Errorf("连接 SMTP 服务器失败: %w", err)
|
||||
}
|
||||
return client.Close()
|
||||
}
|
||||
|
||||
message, err := buildMessage(cfg, cfg.TestDestination, "goodBaby 测试邮件", "这是一封来自 goodBaby 的测试邮件,收到即表示邮箱账号配置正确。")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := client.DialAndSendWithContext(ctx, message); err != nil {
|
||||
return fmt.Errorf("发送测试邮件失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *EmailAccountConfigValidator) Meta() meta.AccountMeta {
|
||||
return meta.AccountMeta{
|
||||
Type: AccountType,
|
||||
Label: "邮箱 (SMTP)",
|
||||
Description: "配置一个用于发信的 SMTP 账号。",
|
||||
Docs: "docs/email-config.md",
|
||||
Fields: []meta.Field{
|
||||
{Key: "smtp_server", Label: "SMTP 服务器", Type: meta.FieldString, Required: true, Placeholder: "smtp.example.com"},
|
||||
{Key: "port", Label: "端口", Type: meta.FieldNumber, Required: true, Default: 465, Help: "SSL 一般为 465,STARTTLS 一般为 587"},
|
||||
{Key: "security", Label: "加密方式", Type: meta.FieldString, Required: false, Default: SecuritySSL, Help: "可选 ssl / starttls / none,留空按 ssl 处理"},
|
||||
{Key: "username", Label: "用户名", Type: meta.FieldString, Required: true, Placeholder: "you@example.com"},
|
||||
{Key: "password", Label: "密码 / 授权码", Type: meta.FieldPassword, Required: true, Secret: true},
|
||||
{Key: "from", Label: "发件人地址", Type: meta.FieldString, Help: "留空则使用用户名作为发件人"},
|
||||
{Key: "test_destination", Label: "测试收件地址", Type: meta.FieldString, Help: "填写后点击“测试”会真的发送一封测试邮件"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func parseAccountConfig(config string) (*EmailAccountConfig, error) {
|
||||
var cfg EmailAccountConfig
|
||||
if err := json.Unmarshal([]byte(config), &cfg); err != nil {
|
||||
return nil, fmt.Errorf("解析邮箱账号配置失败: %v", err)
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
+38
-7
@@ -1,20 +1,51 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"log"
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
)
|
||||
|
||||
// 向邮件列表发送消息
|
||||
func SendMail(rule *model.Rule) {
|
||||
// SendMail 向规则配置里的所有地址发送邮件。
|
||||
//
|
||||
// 每个地址单独重试,互不阻塞;全部失败/部分失败都会汇总成错误返回,
|
||||
// 由 runner 记录到执行日志中。
|
||||
func SendMail(ctx context.Context, rule *model.Rule) error {
|
||||
emailRule, err := GetEmailRuleFromRule(rule)
|
||||
if err != nil {
|
||||
log.Printf("获取邮件规则配置失败: %v", err)
|
||||
return
|
||||
return fmt.Errorf("获取邮件规则配置失败: %w", err)
|
||||
}
|
||||
|
||||
for _, destinations := range emailRule.Destinations {
|
||||
go sendMailMsgWithRetry(rule, destinations) // 使用 goroutine 发送邮件,避免指数退避阻塞其他地址
|
||||
accountConfig, err := GetEmailAccountFromRule(rule)
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取邮件账户配置失败: %w", err)
|
||||
}
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
fails []string
|
||||
)
|
||||
|
||||
for _, destination := range emailRule.Destinations {
|
||||
wg.Add(1)
|
||||
go func(address string) {
|
||||
defer wg.Done()
|
||||
if err := sendMailMsgWithRetry(ctx, accountConfig, emailRule, address); err != nil {
|
||||
mu.Lock()
|
||||
fails = append(fails, fmt.Sprintf("%s: %v", address, err))
|
||||
mu.Unlock()
|
||||
}
|
||||
}(destination)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if len(fails) > 0 {
|
||||
return fmt.Errorf("%d/%d 封邮件发送失败: %s",
|
||||
len(fails), len(emailRule.Destinations), strings.Join(fails, "; "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+40
-5
@@ -1,11 +1,46 @@
|
||||
package email
|
||||
|
||||
const (
|
||||
// AccountType 邮箱账号类型标识
|
||||
AccountType = "email"
|
||||
// RuleType 发送邮件的规则类型标识
|
||||
RuleType = "email"
|
||||
)
|
||||
|
||||
// SMTP 加密方式
|
||||
const (
|
||||
SecuritySSL = "ssl" // 隐式 TLS,一般是 465 端口
|
||||
SecuritySTARTTLS = "starttls" // 显式 TLS,一般是 587 端口
|
||||
SecurityNone = "none" // 不加密,一般是 25 端口
|
||||
)
|
||||
|
||||
type EmailAccountConfig struct {
|
||||
SMTPServer string `json:"smtp_server"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
TestDestination string `json:"test_destination"` // 用于测试邮件发送的地址
|
||||
SMTPServer string `json:"smtp_server"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
// 加密方式,留空时按 ssl 处理(兼容旧配置)
|
||||
Security string `json:"security"`
|
||||
// 发件人地址,留空时使用 Username
|
||||
From string `json:"from"`
|
||||
// 用于测试邮件发送的地址
|
||||
TestDestination string `json:"test_destination"`
|
||||
}
|
||||
|
||||
// SecurityOrDefault 返回加密方式,兼容没有该字段的旧配置
|
||||
func (c *EmailAccountConfig) SecurityOrDefault() string {
|
||||
if c.Security == "" {
|
||||
return SecuritySSL
|
||||
}
|
||||
return c.Security
|
||||
}
|
||||
|
||||
// FromOrDefault 返回发件人地址
|
||||
func (c *EmailAccountConfig) FromOrDefault() string {
|
||||
if c.From == "" {
|
||||
return c.Username
|
||||
}
|
||||
return c.From
|
||||
}
|
||||
|
||||
type EmailRule struct {
|
||||
|
||||
@@ -4,13 +4,15 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/mail"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/internal/meta"
|
||||
)
|
||||
|
||||
// EmailRuleValidator 邮件规则验证器
|
||||
type EmailRuleValidator struct{}
|
||||
|
||||
func (v *EmailRuleValidator) GetType() string {
|
||||
return "email"
|
||||
return RuleType
|
||||
}
|
||||
|
||||
func (v *EmailRuleValidator) Validate(configJSON string) error {
|
||||
@@ -40,3 +42,18 @@ func (v *EmailRuleValidator) Validate(configJSON string) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *EmailRuleValidator) Meta() meta.RuleMeta {
|
||||
return meta.RuleMeta{
|
||||
Type: RuleType,
|
||||
Label: "发送邮件",
|
||||
Description: "触发时通过关联的 SMTP 账号向指定地址发送邮件。",
|
||||
Docs: "docs/email-config.md",
|
||||
AccountType: AccountType,
|
||||
Fields: []meta.Field{
|
||||
{Key: "title", Label: "邮件标题", Type: meta.FieldString, Required: true},
|
||||
{Key: "msg", Label: "邮件正文", Type: meta.FieldTextarea, Required: true},
|
||||
{Key: "destinations", Label: "收件人", Type: meta.FieldStringList, Required: true, Placeholder: "someone@example.com"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
@@ -10,13 +11,11 @@ import (
|
||||
type EmailExecutor struct{}
|
||||
|
||||
func (e *EmailExecutor) GetType() string {
|
||||
return "email"
|
||||
return RuleType
|
||||
}
|
||||
|
||||
func (e *EmailExecutor) Execute(rule *model.Rule) error {
|
||||
func (e *EmailExecutor) Execute(ctx context.Context, rule *model.Rule) error {
|
||||
log.Printf("执行邮件规则: %s (ID: %d)", rule.Name, rule.ID)
|
||||
|
||||
SendMail(rule)
|
||||
|
||||
return nil
|
||||
return SendMail(ctx, rule)
|
||||
}
|
||||
|
||||
+53
-78
@@ -4,113 +4,88 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/cenkalti/backoff/v5"
|
||||
"github.com/ssdomei232/goodBaby/configs"
|
||||
"github.com/ssdomei232/goodBaby/handler/db"
|
||||
"github.com/ssdomei232/goodBaby/internal/retry"
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
"github.com/wneessen/go-mail"
|
||||
)
|
||||
|
||||
// 从 Rule 中获取 EmailAccount 配置
|
||||
// GetEmailAccountFromRule 从 Rule 中获取 EmailAccount 配置
|
||||
func GetEmailAccountFromRule(rule *model.Rule) (*EmailAccountConfig, error) {
|
||||
gormDB, err := db.GetGormDB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 1. 通过 account_id 获取到对应的 account 配置
|
||||
var emailAccount model.Account
|
||||
result := gormDB.Where("id = ?", rule.AccountID).First(&emailAccount)
|
||||
if result.Error != nil {
|
||||
return nil, result.Error
|
||||
}
|
||||
|
||||
// 2. 通过 account 配置中的 config 字段获取到 EmailAccount
|
||||
var emailAccountConfig EmailAccountConfig
|
||||
err = json.Unmarshal([]byte(emailAccount.Config), &emailAccountConfig)
|
||||
if err != nil {
|
||||
if err := db.LoadAccountConfig(rule.AccountID, &emailAccountConfig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &emailAccountConfig, nil
|
||||
}
|
||||
|
||||
// 从 Rule 中获取 EmailRule 配置
|
||||
// GetEmailRuleFromRule 从 Rule 中获取 EmailRule 配置
|
||||
func GetEmailRuleFromRule(rule *model.Rule) (*EmailRule, error) {
|
||||
var emailRule EmailRule
|
||||
err := json.Unmarshal([]byte(rule.ConfigJson), &emailRule)
|
||||
if err != nil {
|
||||
if err := json.Unmarshal([]byte(rule.ConfigJson), &emailRule); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &emailRule, nil
|
||||
}
|
||||
func sendMailMsgWithRetry(rule *model.Rule, address string) {
|
||||
config, err := configs.GetConfig()
|
||||
|
||||
// newSMTPClient 按账号配置里的加密方式创建 SMTP 客户端
|
||||
func newSMTPClient(cfg *EmailAccountConfig) (*mail.Client, error) {
|
||||
options := []mail.Option{
|
||||
mail.WithPort(cfg.Port),
|
||||
mail.WithUsername(cfg.Username),
|
||||
mail.WithPassword(cfg.Password),
|
||||
mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover),
|
||||
}
|
||||
|
||||
switch cfg.SecurityOrDefault() {
|
||||
case SecuritySSL:
|
||||
options = append(options, mail.WithSSL())
|
||||
case SecuritySTARTTLS:
|
||||
options = append(options, mail.WithTLSPolicy(mail.TLSMandatory))
|
||||
case SecurityNone:
|
||||
options = append(options, mail.WithTLSPolicy(mail.NoTLS))
|
||||
}
|
||||
|
||||
client, err := mail.NewClient(cfg.SMTPServer, options...)
|
||||
if err != nil {
|
||||
log.Printf("获取配置失败: %v", err)
|
||||
return
|
||||
}
|
||||
var timeout time.Duration = time.Duration(config.TimeoutDurationHours) * time.Hour
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
operation := func() (string, error) {
|
||||
err := sendMailMsg(address, rule)
|
||||
return "", err
|
||||
}
|
||||
|
||||
_, err = backoff.Retry(ctx, operation, backoff.WithBackOff(backoff.NewExponentialBackOff()))
|
||||
if err != nil {
|
||||
log.Printf("发送邮件失败: %v", err)
|
||||
return nil, fmt.Errorf("创建邮件客户端失败: %w", err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func sendMailMsg(address string, rule *model.Rule) error {
|
||||
emailAccountConfig, err := GetEmailAccountFromRule(rule)
|
||||
if err != nil {
|
||||
log.Printf("获取邮件账户配置失败: %v", err)
|
||||
return fmt.Errorf("获取邮件账户配置失败: %v", err)
|
||||
}
|
||||
|
||||
emailRule, err := GetEmailRuleFromRule(rule)
|
||||
if err != nil {
|
||||
log.Printf("获取邮件规则配置失败: %v", err)
|
||||
return fmt.Errorf("获取邮件规则配置失败: %v", err)
|
||||
}
|
||||
|
||||
client, err := mail.NewClient(
|
||||
emailAccountConfig.SMTPServer,
|
||||
mail.WithPort(emailAccountConfig.Port),
|
||||
mail.WithSSL(),
|
||||
mail.WithUsername(emailAccountConfig.Username),
|
||||
mail.WithPassword(emailAccountConfig.Password),
|
||||
mail.WithSMTPAuth(mail.SMTPAuthPlain),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建邮件客户端失败: %v", err)
|
||||
}
|
||||
|
||||
// 创建邮件
|
||||
func buildMessage(cfg *EmailAccountConfig, address, title, body string) (*mail.Msg, error) {
|
||||
message := mail.NewMsg()
|
||||
if err := message.From(emailAccountConfig.Username); err != nil {
|
||||
return fmt.Errorf("设置发件人失败: %v", err)
|
||||
if err := message.From(cfg.FromOrDefault()); err != nil {
|
||||
return nil, fmt.Errorf("设置发件人失败: %w", err)
|
||||
}
|
||||
|
||||
if err := message.To(address); err != nil {
|
||||
return fmt.Errorf("设置收件人失败: %v", err)
|
||||
return nil, fmt.Errorf("设置收件人失败: %w", err)
|
||||
}
|
||||
message.Subject(title)
|
||||
message.SetBodyString(mail.TypeTextPlain, body)
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func sendMailMsgWithRetry(ctx context.Context, cfg *EmailAccountConfig, rule *EmailRule, address string) error {
|
||||
return retry.Do(ctx, func() error {
|
||||
return sendMailMsg(ctx, cfg, rule, address)
|
||||
})
|
||||
}
|
||||
|
||||
func sendMailMsg(ctx context.Context, cfg *EmailAccountConfig, rule *EmailRule, address string) error {
|
||||
client, err := newSMTPClient(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
message.Subject(emailRule.Title)
|
||||
message.SetBodyString(mail.TypeTextPlain, emailRule.Msg)
|
||||
|
||||
// 发送邮件
|
||||
if err := client.DialAndSend(message); err != nil {
|
||||
return fmt.Errorf("发送邮件失败: %v", err)
|
||||
message, err := buildMessage(cfg, address, rule.Title, rule.Msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := client.DialAndSendWithContext(ctx, message); err != nil {
|
||||
return fmt.Errorf("发送邮件失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,22 +1,26 @@
|
||||
package github
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/go-github/v84/github"
|
||||
"github.com/ssdomei232/goodBaby/internal/meta"
|
||||
"github.com/ssdomei232/goodBaby/internal/retry"
|
||||
)
|
||||
|
||||
// GitHubAccountConfigValidator GitHub账号配置验证器
|
||||
type GitHubAccountConfigValidator struct{}
|
||||
|
||||
func (v *GitHubAccountConfigValidator) GetType() string {
|
||||
return "github-account"
|
||||
return AccountType
|
||||
}
|
||||
|
||||
func (v *GitHubAccountConfigValidator) Validate(config string) error {
|
||||
// GitHub账号配置验证逻辑
|
||||
var cfg GithubAccount
|
||||
if err := json.Unmarshal([]byte(config), &cfg); err != nil {
|
||||
return fmt.Errorf("解析GitHub账号配置失败: %v", err)
|
||||
cfg, err := parseAccount(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cfg.Token == "" {
|
||||
@@ -28,3 +32,44 @@ func (v *GitHubAccountConfigValidator) Validate(config string) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Test 用 token 拉一次当前用户信息,验证 token 是否有效
|
||||
func (v *GitHubAccountConfigValidator) Test(config string) error {
|
||||
cfg, err := parseAccount(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), retry.TestTimeout)
|
||||
defer cancel()
|
||||
|
||||
client := github.NewClient(nil).WithAuthToken(cfg.Token)
|
||||
user, _, err := client.Users.Get(ctx, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("GitHub Token 校验失败: %w", err)
|
||||
}
|
||||
if user == nil || user.GetLogin() == "" {
|
||||
return fmt.Errorf("GitHub Token 无效")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *GitHubAccountConfigValidator) Meta() meta.AccountMeta {
|
||||
return meta.AccountMeta{
|
||||
Type: AccountType,
|
||||
Label: "GitHub",
|
||||
Description: "使用 Personal Access Token 操作仓库,需要 repo 权限。",
|
||||
Fields: []meta.Field{
|
||||
{Key: "token", Label: "Personal Access Token", Type: meta.FieldPassword, Required: true, Secret: true, Placeholder: "ghp_xxx", Help: "需要勾选 repo 权限"},
|
||||
{Key: "owner", Label: "仓库所有者", Type: meta.FieldString, Required: true, Placeholder: "your-github-name", Help: "用户名或组织名"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func parseAccount(config string) (*GithubAccount, error) {
|
||||
var cfg GithubAccount
|
||||
if err := json.Unmarshal([]byte(config), &cfg); err != nil {
|
||||
return nil, fmt.Errorf("解析GitHub账号配置失败: %v", err)
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
+19
-27
@@ -2,41 +2,33 @@ package github
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/cenkalti/backoff/v5"
|
||||
"github.com/ssdomei232/goodBaby/configs"
|
||||
"github.com/ssdomei232/goodBaby/internal/retry"
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
)
|
||||
|
||||
// 将repos设置为public
|
||||
func MakeRepositoryPublic(rule *model.Rule) {
|
||||
reposConfig, account := GetGithubReposAndAccountFromRule(rule)
|
||||
if reposConfig == nil || account == nil {
|
||||
log.Printf("无法获取 GitHub 配置或账户信息")
|
||||
return
|
||||
// MakeRepositoryPublic 将规则中配置的仓库设置为 public
|
||||
func MakeRepositoryPublic(ctx context.Context, rule *model.Rule) error {
|
||||
reposConfig, account, err := GetGithubReposAndAccountFromRule(rule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var fails []string
|
||||
for _, repo := range reposConfig.Repos {
|
||||
config, err := configs.GetConfig()
|
||||
err := retry.Do(ctx, func() error {
|
||||
return SetRepositoryPublic(ctx, account.Token, account.Owner, repo)
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("获取配置失败: %v", err)
|
||||
return
|
||||
}
|
||||
var timeout time.Duration = time.Duration(config.TimeoutDurationHours) * time.Hour
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
operation := func() (string, error) {
|
||||
err := SetRepositoryPublic(account.Token, account.Owner, repo)
|
||||
return "", err
|
||||
}
|
||||
|
||||
_, err = backoff.Retry(ctx, operation, backoff.WithBackOff(backoff.NewExponentialBackOff()))
|
||||
if err != nil {
|
||||
log.Printf("将仓库 %s 设置为 public 失败: %v", repo, err)
|
||||
fails = append(fails, fmt.Sprintf("%s: %v", repo, err))
|
||||
}
|
||||
}
|
||||
|
||||
if len(fails) > 0 {
|
||||
return fmt.Errorf("%d/%d 个仓库设置为 public 失败: %s",
|
||||
len(fails), len(reposConfig.Repos), strings.Join(fails, "; "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+10
-3
@@ -1,10 +1,17 @@
|
||||
package github
|
||||
|
||||
const (
|
||||
// AccountType GitHub 账号类型标识
|
||||
AccountType = "github"
|
||||
// RuleTypeMakeRepoPublic 公开仓库的规则类型标识
|
||||
RuleTypeMakeRepoPublic = "github-repo-public"
|
||||
)
|
||||
|
||||
type GithubReposConfig struct {
|
||||
Repos []string `yaml:"repos"`
|
||||
Repos []string `json:"repos"`
|
||||
}
|
||||
|
||||
type GithubAccount struct {
|
||||
Token string
|
||||
Owner string
|
||||
Token string `json:"token"`
|
||||
Owner string `json:"owner"`
|
||||
}
|
||||
|
||||
@@ -3,12 +3,15 @@ package github
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/internal/meta"
|
||||
)
|
||||
|
||||
type GithubMakeRepositoryPublicRuleValidator struct{}
|
||||
|
||||
func (v *GithubMakeRepositoryPublicRuleValidator) GetType() string {
|
||||
return "github_make_repository_public"
|
||||
return RuleTypeMakeRepoPublic
|
||||
}
|
||||
|
||||
func (v *GithubMakeRepositoryPublicRuleValidator) Validate(configJSON string) error {
|
||||
@@ -21,5 +24,33 @@ func (v *GithubMakeRepositoryPublicRuleValidator) Validate(configJSON string) er
|
||||
return fmt.Errorf("GitHub 规则配置错误: 至少需要指定一个仓库")
|
||||
}
|
||||
|
||||
for _, repo := range config.Repos {
|
||||
if strings.TrimSpace(repo) == "" {
|
||||
return fmt.Errorf("GitHub 规则配置错误: 仓库名不能为空")
|
||||
}
|
||||
if strings.Contains(repo, "/") {
|
||||
return fmt.Errorf("GitHub 规则配置错误: 只填写仓库名(不含所有者),收到 %q", repo)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *GithubMakeRepositoryPublicRuleValidator) Meta() meta.RuleMeta {
|
||||
return meta.RuleMeta{
|
||||
Type: RuleTypeMakeRepoPublic,
|
||||
Label: "公开 GitHub 仓库",
|
||||
Description: "触发时把指定的私有仓库改为公开。",
|
||||
AccountType: AccountType,
|
||||
Fields: []meta.Field{
|
||||
{
|
||||
Key: "repos",
|
||||
Label: "仓库列表",
|
||||
Type: meta.FieldStringList,
|
||||
Required: true,
|
||||
Placeholder: "my-repo",
|
||||
Help: "只填仓库名,所有者取自关联的 GitHub 账号",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package github
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
@@ -10,13 +11,11 @@ import (
|
||||
type GithubMakeRepoPublicExecutor struct{}
|
||||
|
||||
func (e *GithubMakeRepoPublicExecutor) GetType() string {
|
||||
return "github-make-repo-public"
|
||||
return RuleTypeMakeRepoPublic
|
||||
}
|
||||
|
||||
func (e *GithubMakeRepoPublicExecutor) Execute(rule *model.Rule) error {
|
||||
func (e *GithubMakeRepoPublicExecutor) Execute(ctx context.Context, rule *model.Rule) error {
|
||||
log.Printf("执行GitHub仓库公开规则: %s (ID: %d)", rule.Name, rule.ID)
|
||||
|
||||
MakeRepositoryPublic(rule)
|
||||
|
||||
return nil
|
||||
return MakeRepositoryPublic(ctx, rule)
|
||||
}
|
||||
|
||||
+12
-31
@@ -3,55 +3,36 @@ package github
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/go-github/v84/github"
|
||||
"github.com/ssdomei232/goodBaby/handler/db"
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
)
|
||||
|
||||
// 从 rule 中获取 GithubReposConfig 和 GithubAccount
|
||||
func GetGithubReposAndAccountFromRule(rule *model.Rule) (*GithubReposConfig, *GithubAccount) {
|
||||
// GetGithubReposAndAccountFromRule 从 rule 中获取 GithubReposConfig 和 GithubAccount
|
||||
func GetGithubReposAndAccountFromRule(rule *model.Rule) (*GithubReposConfig, *GithubAccount, error) {
|
||||
var githubReposConfig GithubReposConfig
|
||||
if err := json.Unmarshal([]byte(rule.ConfigJson), &githubReposConfig); err != nil {
|
||||
return nil, nil, fmt.Errorf("解析 GitHub 规则配置失败: %w", err)
|
||||
}
|
||||
|
||||
var githubAccount GithubAccount
|
||||
|
||||
// 获取 GithubReposConfig
|
||||
err := json.Unmarshal([]byte(rule.ConfigJson), &githubReposConfig)
|
||||
if err != nil {
|
||||
log.Printf("获取 GitHub 配置失败: %v", err)
|
||||
return nil, nil
|
||||
if err := db.LoadAccountConfig(rule.AccountID, &githubAccount); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// 获取 GithubAccount
|
||||
gormDB, err := db.GetGormDB()
|
||||
if err != nil {
|
||||
log.Printf("获取 Gorm DB 失败: %v", err)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
err = gormDB.Where("id = ?", rule.AccountID).First(&githubAccount).Error
|
||||
if err != nil {
|
||||
log.Printf("获取 GitHub 账户失败: %v", err)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return &githubReposConfig, &githubAccount
|
||||
return &githubReposConfig, &githubAccount, nil
|
||||
}
|
||||
|
||||
// 将仓库设置为 public
|
||||
func SetRepositoryPublic(token, owner, repo string) error {
|
||||
ctx := context.Background()
|
||||
|
||||
// 1. 初始化客户端
|
||||
// SetRepositoryPublic 将仓库设置为 public
|
||||
func SetRepositoryPublic(ctx context.Context, token, owner, repo string) error {
|
||||
client := github.NewClient(nil).WithAuthToken(token)
|
||||
|
||||
// 2. 准备修改的参数
|
||||
opts := &github.Repository{
|
||||
Visibility: github.Ptr("public"),
|
||||
}
|
||||
|
||||
// 3. 执行更新操作
|
||||
_, _, err := client.Repositories.Edit(ctx, owner, repo, opts)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -3,19 +3,23 @@ package onebot
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/internal/meta"
|
||||
)
|
||||
|
||||
// AccountConfigValidator OneBot账号配置验证器接口
|
||||
// OneBotAccountConfigValidator OneBot账号配置验证器
|
||||
type OneBotAccountConfigValidator struct{}
|
||||
|
||||
func (v *OneBotAccountConfigValidator) GetType() string {
|
||||
return "onebot"
|
||||
return AccountType
|
||||
}
|
||||
|
||||
func (v *OneBotAccountConfigValidator) Validate(config string) error {
|
||||
var cfg OneBotAccount
|
||||
if err := json.Unmarshal([]byte(config), &cfg); err != nil {
|
||||
return fmt.Errorf("解析OneBot账号配置失败: %v", err)
|
||||
cfg, err := parseAccount(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cfg.Token == "" {
|
||||
@@ -25,5 +29,44 @@ func (v *OneBotAccountConfigValidator) Validate(config string) error {
|
||||
return fmt.Errorf("OneBot账号配置中URL不能为空")
|
||||
}
|
||||
|
||||
parsed, err := url.Parse(cfg.URL)
|
||||
if err != nil || parsed.Host == "" || !strings.HasPrefix(parsed.Scheme, "http") {
|
||||
return fmt.Errorf("OneBot账号配置中URL不合法,应形如 http://localhost:3000")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Test 调用 get_login_info 验证地址与 Token
|
||||
func (v *OneBotAccountConfigValidator) Test(config string) error {
|
||||
cfg, err := parseAccount(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var resp apiResponse
|
||||
if err := newClient(cfg).DoRequest("POST", "/get_login_info", map[string]any{}, &resp); err != nil {
|
||||
return fmt.Errorf("连接 OneBot 失败: %w", err)
|
||||
}
|
||||
return resp.err()
|
||||
}
|
||||
|
||||
func (v *OneBotAccountConfigValidator) Meta() meta.AccountMeta {
|
||||
return meta.AccountMeta{
|
||||
Type: AccountType,
|
||||
Label: "OneBot (QQ)",
|
||||
Description: "对接 NapCat / go-cqhttp 等 OneBot HTTP 服务,用于发送 QQ 消息。",
|
||||
Fields: []meta.Field{
|
||||
{Key: "url", Label: "HTTP 服务地址", Type: meta.FieldString, Required: true, Placeholder: "http://localhost:3000"},
|
||||
{Key: "token", Label: "Access Token", Type: meta.FieldPassword, Required: true, Secret: true},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func parseAccount(config string) (*OneBotAccount, error) {
|
||||
var cfg OneBotAccount
|
||||
if err := json.Unmarshal([]byte(config), &cfg); err != nil {
|
||||
return nil, fmt.Errorf("解析OneBot账号配置失败: %v", err)
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
+44
-2
@@ -1,11 +1,53 @@
|
||||
package onebot
|
||||
|
||||
const (
|
||||
// AccountType OneBot 账号类型标识
|
||||
AccountType = "onebot"
|
||||
// RuleType 发送 OneBot 消息的规则类型标识
|
||||
RuleType = "onebot"
|
||||
)
|
||||
|
||||
type OneBotConfig struct {
|
||||
SendGroups []int `json:"send_groups"`
|
||||
Msg string `json:"msg"`
|
||||
SendGroups []int64 `json:"send_groups"` // 群号列表
|
||||
SendUsers []int64 `json:"send_users"` // 好友 QQ 号列表
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
type OneBotAccount struct {
|
||||
URL string `json:"url"` // 例如 "http://localhost:5700"
|
||||
Token string `json:"token"` // 例如 "your_token_here"
|
||||
}
|
||||
|
||||
// apiResponse OneBot HTTP API 的通用响应信封
|
||||
type apiResponse struct {
|
||||
Status string `json:"status"`
|
||||
Retcode int `json:"retcode"`
|
||||
Message string `json:"message"`
|
||||
Wording string `json:"wording"`
|
||||
}
|
||||
|
||||
// err 把 OneBot 返回的业务错误转换成 Go error
|
||||
func (r *apiResponse) err() error {
|
||||
if r.Status == "ok" && r.Retcode == 0 {
|
||||
return nil
|
||||
}
|
||||
detail := r.Wording
|
||||
if detail == "" {
|
||||
detail = r.Message
|
||||
}
|
||||
if detail == "" {
|
||||
detail = "请检查 OneBot 地址与 Token"
|
||||
}
|
||||
return &APIError{Status: r.Status, Retcode: r.Retcode, Detail: detail}
|
||||
}
|
||||
|
||||
// APIError OneBot 返回的业务错误
|
||||
type APIError struct {
|
||||
Status string
|
||||
Retcode int
|
||||
Detail string
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string {
|
||||
return "OneBot 返回错误(status=" + e.Status + "): " + e.Detail
|
||||
}
|
||||
|
||||
+34
-25
@@ -2,41 +2,50 @@ package onebot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/cenkalti/backoff/v5"
|
||||
"github.com/ssdomei232/goodBaby/configs"
|
||||
"github.com/ssdomei232/goodBaby/internal/retry"
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
)
|
||||
|
||||
func SendOneBotMsg(rule *model.Rule) {
|
||||
oneBotConfig := getOneBotConfigFromRule(rule)
|
||||
// SendOneBotMsg 向规则中配置的群和好友发送消息
|
||||
func SendOneBotMsg(ctx context.Context, rule *model.Rule) error {
|
||||
oneBotConfig, err := getOneBotConfigFromRule(rule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
oneBotAccount, err := getOneBotAccountFromRule(rule)
|
||||
if err != nil {
|
||||
log.Printf("获取OneBot账户失败: %v", err)
|
||||
return
|
||||
return fmt.Errorf("获取OneBot账户失败: %w", err)
|
||||
}
|
||||
|
||||
var fails []string
|
||||
total := 0
|
||||
|
||||
for _, groupID := range oneBotConfig.SendGroups {
|
||||
config, err := configs.GetConfig()
|
||||
total++
|
||||
err := retry.Do(ctx, func() error {
|
||||
return sendGroupMsg(oneBotAccount, groupID, oneBotConfig.Msg)
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("获取配置失败: %v", err)
|
||||
return
|
||||
}
|
||||
var timeout time.Duration = time.Duration(config.TimeoutDurationHours) * time.Hour
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
operation := func() (string, error) {
|
||||
err := sendOneBotMsg(oneBotAccount, groupID, oneBotConfig.Msg)
|
||||
return "", err
|
||||
}
|
||||
|
||||
_, err = backoff.Retry(ctx, operation, backoff.WithBackOff(backoff.NewExponentialBackOff()))
|
||||
if err != nil {
|
||||
log.Printf("发送OneBot消息失败: %v", err)
|
||||
fails = append(fails, fmt.Sprintf("群 %d: %v", groupID, err))
|
||||
}
|
||||
}
|
||||
|
||||
for _, userID := range oneBotConfig.SendUsers {
|
||||
total++
|
||||
err := retry.Do(ctx, func() error {
|
||||
return sendPrivateMsg(oneBotAccount, userID, oneBotConfig.Msg)
|
||||
})
|
||||
if err != nil {
|
||||
fails = append(fails, fmt.Sprintf("好友 %d: %v", userID, err))
|
||||
}
|
||||
}
|
||||
|
||||
if len(fails) > 0 {
|
||||
return fmt.Errorf("%d/%d 条消息发送失败: %s", len(fails), total, strings.Join(fails, "; "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3,13 +3,15 @@ package onebot
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/internal/meta"
|
||||
)
|
||||
|
||||
// OneBotRuleValidator OneBot规则验证器
|
||||
type OneBotRuleValidator struct{}
|
||||
|
||||
func (v *OneBotRuleValidator) GetType() string {
|
||||
return "onebot"
|
||||
return RuleType
|
||||
}
|
||||
|
||||
func (v *OneBotRuleValidator) Validate(configJSON string) error {
|
||||
@@ -22,9 +24,29 @@ func (v *OneBotRuleValidator) Validate(configJSON string) error {
|
||||
return fmt.Errorf("OneBot规则配置中 msg 不能为空")
|
||||
}
|
||||
|
||||
if len(config.SendGroups) == 0 {
|
||||
return fmt.Errorf("OneBot规则配置中 send_groups 不能为空")
|
||||
if len(config.SendGroups) == 0 && len(config.SendUsers) == 0 {
|
||||
return fmt.Errorf("OneBot规则配置中 send_groups 与 send_users 不能同时为空")
|
||||
}
|
||||
|
||||
for _, id := range append(append([]int64{}, config.SendGroups...), config.SendUsers...) {
|
||||
if id <= 0 {
|
||||
return fmt.Errorf("OneBot规则配置中存在非法的群号/QQ号: %d", id)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *OneBotRuleValidator) Meta() meta.RuleMeta {
|
||||
return meta.RuleMeta{
|
||||
Type: RuleType,
|
||||
Label: "发送 QQ 消息",
|
||||
Description: "触发时通过 OneBot 向指定的群或好友发送消息。",
|
||||
AccountType: AccountType,
|
||||
Fields: []meta.Field{
|
||||
{Key: "msg", Label: "消息内容", Type: meta.FieldTextarea, Required: true},
|
||||
{Key: "send_groups", Label: "群号", Type: meta.FieldNumberList, Placeholder: "123456789"},
|
||||
{Key: "send_users", Label: "好友 QQ 号", Type: meta.FieldNumberList, Placeholder: "123456789"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package onebot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
@@ -10,13 +11,11 @@ import (
|
||||
type OneBotExecutor struct{}
|
||||
|
||||
func (e *OneBotExecutor) GetType() string {
|
||||
return "onebot"
|
||||
return RuleType
|
||||
}
|
||||
|
||||
func (e *OneBotExecutor) Execute(rule *model.Rule) error {
|
||||
func (e *OneBotExecutor) Execute(ctx context.Context, rule *model.Rule) error {
|
||||
log.Printf("执行OneBot规则: %s (ID: %d)", rule.Name, rule.ID)
|
||||
|
||||
SendOneBotMsg(rule)
|
||||
|
||||
return nil
|
||||
return SendOneBotMsg(ctx, rule)
|
||||
}
|
||||
|
||||
+34
-22
@@ -2,46 +2,58 @@ package onebot
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"fmt"
|
||||
|
||||
"github.com/ssdomei232/goodBaby/handler/db"
|
||||
"github.com/ssdomei232/goodBaby/model"
|
||||
napcat "github.com/ssdomei232/napcat-http-go-sdk"
|
||||
)
|
||||
|
||||
func newClient(account *OneBotAccount) *napcat.Client {
|
||||
return napcat.NewClient(account.Token, account.URL)
|
||||
}
|
||||
|
||||
// 从 Rule 中获取 OneBotConfig
|
||||
func getOneBotConfigFromRule(rule *model.Rule) *OneBotConfig {
|
||||
func getOneBotConfigFromRule(rule *model.Rule) (*OneBotConfig, error) {
|
||||
var oneBotConfig OneBotConfig
|
||||
err := json.Unmarshal([]byte(rule.ConfigJson), &oneBotConfig)
|
||||
if err != nil {
|
||||
return nil
|
||||
if err := json.Unmarshal([]byte(rule.ConfigJson), &oneBotConfig); err != nil {
|
||||
return nil, fmt.Errorf("解析OneBot规则配置失败: %w", err)
|
||||
}
|
||||
return &oneBotConfig
|
||||
return &oneBotConfig, nil
|
||||
}
|
||||
|
||||
// 从 Rule 中获取 OneBotAccount
|
||||
func getOneBotAccountFromRule(rule *model.Rule) (*OneBotAccount, error) {
|
||||
gormDB, err := db.GetGormDB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var oneBotAccountEntry model.Account
|
||||
gormDB.Where("id = ?", rule.AccountID).First(&oneBotAccountEntry)
|
||||
|
||||
var oneBotAccount OneBotAccount
|
||||
err = json.Unmarshal([]byte(oneBotAccountEntry.Config), &oneBotAccount)
|
||||
if err != nil {
|
||||
if err := db.LoadAccountConfig(rule.AccountID, &oneBotAccount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oneBotAccount, nil
|
||||
}
|
||||
|
||||
// 发送一条消息到OneBot
|
||||
func sendOneBotMsg(account *OneBotAccount, groupID int, msg string) error {
|
||||
client := napcat.NewClient(account.Token, account.URL)
|
||||
// 发送一条群消息
|
||||
//
|
||||
// SDK 只返回传输层错误,这里自己解析 OneBot 的响应信封,
|
||||
// 否则 token 错误、群号不存在这类失败会被当成发送成功。
|
||||
func sendGroupMsg(account *OneBotAccount, groupID int64, msg string) error {
|
||||
return call(account, "/send_group_msg", map[string]any{
|
||||
"group_id": groupID,
|
||||
"message": msg,
|
||||
})
|
||||
}
|
||||
|
||||
err := client.SendGroupMsg(strconv.Itoa(groupID), msg)
|
||||
return err
|
||||
// 发送一条私聊消息
|
||||
func sendPrivateMsg(account *OneBotAccount, userID int64, msg string) error {
|
||||
return call(account, "/send_private_msg", map[string]any{
|
||||
"user_id": userID,
|
||||
"message": msg,
|
||||
})
|
||||
}
|
||||
|
||||
func call(account *OneBotAccount, endpoint string, payload map[string]any) error {
|
||||
var resp apiResponse
|
||||
if err := newClient(account).DoRequest("POST", endpoint, payload, &resp); err != nil {
|
||||
return fmt.Errorf("请求 OneBot 失败: %w", err)
|
||||
}
|
||||
return resp.err()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user