user_notify.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. // TODO: 实现webhook通知
  48. _ = webhookURL // 临时处理未使用警告,等待webhook实现
  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. }