user_notify.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. switch notifyType {
  26. case constant.NotifyTypeEmail:
  27. userEmail := user.Email
  28. // check setting email
  29. if settingEmail, ok := userSetting[constant.UserSettingNotificationEmail]; ok {
  30. userEmail = settingEmail.(string)
  31. }
  32. if userEmail == "" {
  33. common.SysLog(fmt.Sprintf("user %d has no email, skip sending email", user.Id))
  34. return nil
  35. }
  36. return sendEmailNotify(userEmail, data)
  37. case constant.NotifyTypeWebhook:
  38. webhookURL, ok := userSetting[constant.UserSettingWebhookUrl]
  39. if !ok {
  40. common.SysError(fmt.Sprintf("user %d has no webhook url, skip sending webhook", user.Id))
  41. return nil
  42. }
  43. // TODO: 实现webhook通知
  44. _ = webhookURL // 临时处理未使用警告,等待webhook实现
  45. }
  46. return nil // 添加缺失的return
  47. }
  48. func sendEmailNotify(userEmail string, data dto.Notify) error {
  49. // make email content
  50. content := data.Content
  51. // 处理占位符
  52. for _, value := range data.Values {
  53. content = strings.Replace(content, dto.ContentValueParam, fmt.Sprintf("%v", value), 1)
  54. }
  55. return common.SendEmail(data.Title, userEmail, content)
  56. }