user_notify.go 1.8 KB

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