user_notify.go 2.1 KB

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