user_notify.go 2.0 KB

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