| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- package service
- import (
- "fmt"
- "one-api/common"
- "one-api/constant"
- "one-api/dto"
- "one-api/model"
- "strings"
- )
- func NotifyRootUser(t string, subject string, content string) {
- user := model.GetRootUser().ToBaseUser()
- _ = NotifyUser(&user, dto.NewNotify(t, subject, content, nil))
- }
- func NotifyUser(user *model.UserBase, data dto.Notify) error {
- userSetting := user.GetSetting()
- notifyType, ok := userSetting[constant.UserSettingNotifyType]
- if !ok {
- notifyType = constant.NotifyTypeEmail
- }
- // Check notification limit
- canSend, err := CheckNotificationLimit(user.Id, data.Type)
- if err != nil {
- common.SysError(fmt.Sprintf("failed to check notification limit: %s", err.Error()))
- return err
- }
- if !canSend {
- return fmt.Errorf("notification limit exceeded for user %d with type %s", user.Id, notifyType)
- }
- switch notifyType {
- case constant.NotifyTypeEmail:
- userEmail := user.Email
- // check setting email
- if settingEmail, ok := userSetting[constant.UserSettingNotificationEmail]; ok {
- userEmail = settingEmail.(string)
- }
- if userEmail == "" {
- common.SysLog(fmt.Sprintf("user %d has no email, skip sending email", user.Id))
- return nil
- }
- return sendEmailNotify(userEmail, data)
- case constant.NotifyTypeWebhook:
- webhookURL, ok := userSetting[constant.UserSettingWebhookUrl]
- if !ok {
- common.SysError(fmt.Sprintf("user %d has no webhook url, skip sending webhook", user.Id))
- return nil
- }
- // TODO: 实现webhook通知
- _ = webhookURL // 临时处理未使用警告,等待webhook实现
- }
- return nil
- }
- func sendEmailNotify(userEmail string, data dto.Notify) error {
- // make email content
- content := data.Content
- // 处理占位符
- for _, value := range data.Values {
- content = strings.Replace(content, dto.ContentValueParam, fmt.Sprintf("%v", value), 1)
- }
- return common.SendEmail(data.Title, userEmail, content)
- }
|