user_notify.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. _ = NotifyUser(user.Id, user.Email, user.GetSetting(), dto.NewNotify(t, subject, content, nil))
  13. }
  14. func NotifyUser(userId int, userEmail string, userSetting map[string]interface{}, data dto.Notify) error {
  15. notifyType, ok := userSetting[constant.UserSettingNotifyType]
  16. if !ok {
  17. notifyType = constant.NotifyTypeEmail
  18. }
  19. // Check notification limit
  20. canSend, err := CheckNotificationLimit(userId, data.Type)
  21. if err != nil {
  22. common.SysError(fmt.Sprintf("failed to check notification limit: %s", err.Error()))
  23. return err
  24. }
  25. if !canSend {
  26. return fmt.Errorf("notification limit exceeded for user %d with type %s", userId, notifyType)
  27. }
  28. switch notifyType {
  29. case constant.NotifyTypeEmail:
  30. // check setting email
  31. if settingEmail, ok := userSetting[constant.UserSettingNotificationEmail]; ok {
  32. userEmail = settingEmail.(string)
  33. }
  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 constant.NotifyTypeWebhook:
  40. webhookURL, ok := userSetting[constant.UserSettingWebhookUrl]
  41. if !ok {
  42. common.SysError(fmt.Sprintf("user %d has no webhook url, skip sending webhook", userId))
  43. return nil
  44. }
  45. webhookURLStr, ok := webhookURL.(string)
  46. if !ok {
  47. common.SysError(fmt.Sprintf("user %d webhook url is not string type", userId))
  48. return nil
  49. }
  50. // 获取 webhook secret
  51. var webhookSecret string
  52. if secret, ok := userSetting[constant.UserSettingWebhookSecret]; ok {
  53. webhookSecret, _ = secret.(string)
  54. }
  55. return SendWebhookNotify(webhookURLStr, webhookSecret, data)
  56. }
  57. return nil
  58. }
  59. func sendEmailNotify(userEmail string, data dto.Notify) error {
  60. // make email content
  61. content := data.Content
  62. // 处理占位符
  63. for _, value := range data.Values {
  64. content = strings.Replace(content, dto.ContentValueParam, fmt.Sprintf("%v", value), 1)
  65. }
  66. return common.SendEmail(data.Title, userEmail, content)
  67. }