user_notify.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package service
  2. import (
  3. "fmt"
  4. "one-api/common"
  5. "one-api/constant"
  6. "one-api/dto"
  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. common.SysError(fmt.Sprintf("failed to notify root user: %s", err.Error()))
  15. }
  16. }
  17. func NotifyUser(userId int, userEmail string, userSetting map[string]interface{}, data dto.Notify) error {
  18. notifyType, ok := userSetting[constant.UserSettingNotifyType]
  19. if !ok {
  20. notifyType = constant.NotifyTypeEmail
  21. }
  22. // Check notification limit
  23. canSend, err := CheckNotificationLimit(userId, data.Type)
  24. if err != nil {
  25. common.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 constant.NotifyTypeEmail:
  33. // check setting email
  34. if settingEmail, ok := userSetting[constant.UserSettingNotificationEmail]; ok {
  35. userEmail = settingEmail.(string)
  36. }
  37. if userEmail == "" {
  38. common.SysLog(fmt.Sprintf("user %d has no email, skip sending email", userId))
  39. return nil
  40. }
  41. return sendEmailNotify(userEmail, data)
  42. case constant.NotifyTypeWebhook:
  43. webhookURL, ok := userSetting[constant.UserSettingWebhookUrl]
  44. if !ok {
  45. common.SysError(fmt.Sprintf("user %d has no webhook url, skip sending webhook", userId))
  46. return nil
  47. }
  48. webhookURLStr, ok := webhookURL.(string)
  49. if !ok {
  50. common.SysError(fmt.Sprintf("user %d webhook url is not string type", userId))
  51. return nil
  52. }
  53. // 获取 webhook secret
  54. var webhookSecret string
  55. if secret, ok := userSetting[constant.UserSettingWebhookSecret]; ok {
  56. webhookSecret, _ = secret.(string)
  57. }
  58. return SendWebhookNotify(webhookURLStr, webhookSecret, data)
  59. }
  60. return nil
  61. }
  62. func sendEmailNotify(userEmail string, data dto.Notify) error {
  63. // make email content
  64. content := data.Content
  65. // 处理占位符
  66. for _, value := range data.Values {
  67. content = strings.Replace(content, dto.ContentValueParam, fmt.Sprintf("%v", value), 1)
  68. }
  69. return common.SendEmail(data.Title, userEmail, content)
  70. }