user_notify.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package service
  2. import (
  3. "fmt"
  4. "one-api/common"
  5. "one-api/dto"
  6. "one-api/logger"
  7. "one-api/model"
  8. "strings"
  9. )
  10. func NotifyRootUser(t string, subject string, content string) {
  11. user := model.GetRootUser().ToBaseUser()
  12. err := NotifyUser(user.Id, user.Email, user.GetSetting(), dto.NewNotify(t, subject, content, nil))
  13. if err != nil {
  14. logger.SysError(fmt.Sprintf("failed to notify root user: %s", err.Error()))
  15. }
  16. }
  17. func NotifyUser(userId int, userEmail string, userSetting dto.UserSetting, data dto.Notify) error {
  18. notifyType := userSetting.NotifyType
  19. if notifyType == "" {
  20. notifyType = dto.NotifyTypeEmail
  21. }
  22. // Check notification limit
  23. canSend, err := CheckNotificationLimit(userId, data.Type)
  24. if err != nil {
  25. logger.SysError(fmt.Sprintf("failed to check notification limit: %s", err.Error()))
  26. return err
  27. }
  28. if !canSend {
  29. return fmt.Errorf("notification limit exceeded for user %d with type %s", userId, notifyType)
  30. }
  31. switch notifyType {
  32. case dto.NotifyTypeEmail:
  33. // check setting email
  34. userEmail = userSetting.NotificationEmail
  35. if userEmail == "" {
  36. logger.SysLog(fmt.Sprintf("user %d has no email, skip sending email", userId))
  37. return nil
  38. }
  39. return sendEmailNotify(userEmail, data)
  40. case dto.NotifyTypeWebhook:
  41. webhookURLStr := userSetting.WebhookUrl
  42. if webhookURLStr == "" {
  43. logger.SysError(fmt.Sprintf("user %d has no webhook url, skip sending webhook", userId))
  44. return nil
  45. }
  46. // 获取 webhook secret
  47. webhookSecret := userSetting.WebhookSecret
  48. return SendWebhookNotify(webhookURLStr, webhookSecret, data)
  49. }
  50. return nil
  51. }
  52. func sendEmailNotify(userEmail string, data dto.Notify) error {
  53. // make email content
  54. content := data.Content
  55. // 处理占位符
  56. for _, value := range data.Values {
  57. content = strings.Replace(content, dto.ContentValueParam, fmt.Sprintf("%v", value), 1)
  58. }
  59. return common.SendEmail(data.Title, userEmail, content)
  60. }