user_notify.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. package service
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/dto"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/QuantumNous/new-api/setting/system_setting"
  13. )
  14. func NotifyRootUser(t string, subject string, content string) {
  15. user := model.GetRootUser().ToBaseUser()
  16. err := NotifyUser(user.Id, user.Email, user.GetSetting(), dto.NewNotify(t, subject, content, nil))
  17. if err != nil {
  18. common.SysLog(fmt.Sprintf("failed to notify root user: %s", err.Error()))
  19. }
  20. }
  21. func NotifyUser(userId int, userEmail string, userSetting dto.UserSetting, data dto.Notify) error {
  22. notifyType := userSetting.NotifyType
  23. if notifyType == "" {
  24. notifyType = dto.NotifyTypeEmail
  25. }
  26. // Check notification limit
  27. canSend, err := CheckNotificationLimit(userId, data.Type)
  28. if err != nil {
  29. common.SysLog(fmt.Sprintf("failed to check notification limit: %s", err.Error()))
  30. return err
  31. }
  32. if !canSend {
  33. return fmt.Errorf("notification limit exceeded for user %d with type %s", userId, notifyType)
  34. }
  35. switch notifyType {
  36. case dto.NotifyTypeEmail:
  37. // 优先使用设置中的通知邮箱,如果为空则使用用户的默认邮箱
  38. emailToUse := userSetting.NotificationEmail
  39. if emailToUse == "" {
  40. emailToUse = userEmail
  41. }
  42. if emailToUse == "" {
  43. common.SysLog(fmt.Sprintf("user %d has no email, skip sending email", userId))
  44. return nil
  45. }
  46. return sendEmailNotify(emailToUse, data)
  47. case dto.NotifyTypeWebhook:
  48. webhookURLStr := userSetting.WebhookUrl
  49. if webhookURLStr == "" {
  50. common.SysLog(fmt.Sprintf("user %d has no webhook url, skip sending webhook", userId))
  51. return nil
  52. }
  53. // 获取 webhook secret
  54. webhookSecret := userSetting.WebhookSecret
  55. return SendWebhookNotify(webhookURLStr, webhookSecret, data)
  56. case dto.NotifyTypeBark:
  57. barkURL := userSetting.BarkUrl
  58. if barkURL == "" {
  59. common.SysLog(fmt.Sprintf("user %d has no bark url, skip sending bark", userId))
  60. return nil
  61. }
  62. return sendBarkNotify(barkURL, data)
  63. case dto.NotifyTypeGotify:
  64. gotifyUrl := userSetting.GotifyUrl
  65. gotifyToken := userSetting.GotifyToken
  66. if gotifyUrl == "" || gotifyToken == "" {
  67. common.SysLog(fmt.Sprintf("user %d has no gotify url or token, skip sending gotify", userId))
  68. return nil
  69. }
  70. return sendGotifyNotify(gotifyUrl, gotifyToken, userSetting.GotifyPriority, data)
  71. }
  72. return nil
  73. }
  74. func sendEmailNotify(userEmail string, data dto.Notify) error {
  75. // make email content
  76. content := data.Content
  77. // 处理占位符
  78. for _, value := range data.Values {
  79. content = strings.Replace(content, dto.ContentValueParam, fmt.Sprintf("%v", value), 1)
  80. }
  81. return common.SendEmail(data.Title, userEmail, content)
  82. }
  83. func sendBarkNotify(barkURL string, data dto.Notify) error {
  84. // 处理占位符
  85. content := data.Content
  86. for _, value := range data.Values {
  87. content = strings.Replace(content, dto.ContentValueParam, fmt.Sprintf("%v", value), 1)
  88. }
  89. // 替换模板变量
  90. finalURL := strings.ReplaceAll(barkURL, "{{title}}", url.QueryEscape(data.Title))
  91. finalURL = strings.ReplaceAll(finalURL, "{{content}}", url.QueryEscape(content))
  92. // 发送GET请求到Bark
  93. var req *http.Request
  94. var resp *http.Response
  95. var err error
  96. if system_setting.EnableWorker() {
  97. // 使用worker发送请求
  98. workerReq := &WorkerRequest{
  99. URL: finalURL,
  100. Key: system_setting.WorkerValidKey,
  101. Method: http.MethodGet,
  102. Headers: map[string]string{
  103. "User-Agent": "OneAPI-Bark-Notify/1.0",
  104. },
  105. }
  106. resp, err = DoWorkerRequest(workerReq)
  107. if err != nil {
  108. return fmt.Errorf("failed to send bark request through worker: %v", err)
  109. }
  110. defer resp.Body.Close()
  111. // 检查响应状态
  112. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  113. return fmt.Errorf("bark request failed with status code: %d", resp.StatusCode)
  114. }
  115. } else {
  116. // SSRF防护:验证Bark URL(非Worker模式)
  117. fetchSetting := system_setting.GetFetchSetting()
  118. if err := common.ValidateURLWithFetchSetting(finalURL, fetchSetting.EnableSSRFProtection, fetchSetting.AllowPrivateIp, fetchSetting.DomainFilterMode, fetchSetting.IpFilterMode, fetchSetting.DomainList, fetchSetting.IpList, fetchSetting.AllowedPorts, fetchSetting.ApplyIPFilterForDomain); err != nil {
  119. return fmt.Errorf("request reject: %v", err)
  120. }
  121. // 直接发送请求
  122. req, err = http.NewRequest(http.MethodGet, finalURL, nil)
  123. if err != nil {
  124. return fmt.Errorf("failed to create bark request: %v", err)
  125. }
  126. // 设置User-Agent
  127. req.Header.Set("User-Agent", "OneAPI-Bark-Notify/1.0")
  128. // 发送请求
  129. client := GetHttpClient()
  130. resp, err = client.Do(req)
  131. if err != nil {
  132. return fmt.Errorf("failed to send bark request: %v", err)
  133. }
  134. defer resp.Body.Close()
  135. // 检查响应状态
  136. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  137. return fmt.Errorf("bark request failed with status code: %d", resp.StatusCode)
  138. }
  139. }
  140. return nil
  141. }
  142. func sendGotifyNotify(gotifyUrl string, gotifyToken string, priority int, data dto.Notify) error {
  143. // 处理占位符
  144. content := data.Content
  145. for _, value := range data.Values {
  146. content = strings.Replace(content, dto.ContentValueParam, fmt.Sprintf("%v", value), 1)
  147. }
  148. // 构建完整的 Gotify API URL
  149. // 确保 URL 以 /message 结尾
  150. finalURL := strings.TrimSuffix(gotifyUrl, "/") + "/message?token=" + url.QueryEscape(gotifyToken)
  151. // Gotify优先级范围0-10,如果超出范围则使用默认值5
  152. if priority < 0 || priority > 10 {
  153. priority = 5
  154. }
  155. // 构建 JSON payload
  156. type GotifyMessage struct {
  157. Title string `json:"title"`
  158. Message string `json:"message"`
  159. Priority int `json:"priority"`
  160. }
  161. payload := GotifyMessage{
  162. Title: data.Title,
  163. Message: content,
  164. Priority: priority,
  165. }
  166. // 序列化为 JSON
  167. payloadBytes, err := json.Marshal(payload)
  168. if err != nil {
  169. return fmt.Errorf("failed to marshal gotify payload: %v", err)
  170. }
  171. var req *http.Request
  172. var resp *http.Response
  173. if system_setting.EnableWorker() {
  174. // 使用worker发送请求
  175. workerReq := &WorkerRequest{
  176. URL: finalURL,
  177. Key: system_setting.WorkerValidKey,
  178. Method: http.MethodPost,
  179. Headers: map[string]string{
  180. "Content-Type": "application/json; charset=utf-8",
  181. "User-Agent": "OneAPI-Gotify-Notify/1.0",
  182. },
  183. Body: payloadBytes,
  184. }
  185. resp, err = DoWorkerRequest(workerReq)
  186. if err != nil {
  187. return fmt.Errorf("failed to send gotify request through worker: %v", err)
  188. }
  189. defer resp.Body.Close()
  190. // 检查响应状态
  191. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  192. return fmt.Errorf("gotify request failed with status code: %d", resp.StatusCode)
  193. }
  194. } else {
  195. // SSRF防护:验证Gotify URL(非Worker模式)
  196. fetchSetting := system_setting.GetFetchSetting()
  197. if err := common.ValidateURLWithFetchSetting(finalURL, fetchSetting.EnableSSRFProtection, fetchSetting.AllowPrivateIp, fetchSetting.DomainFilterMode, fetchSetting.IpFilterMode, fetchSetting.DomainList, fetchSetting.IpList, fetchSetting.AllowedPorts, fetchSetting.ApplyIPFilterForDomain); err != nil {
  198. return fmt.Errorf("request reject: %v", err)
  199. }
  200. // 直接发送请求
  201. req, err = http.NewRequest(http.MethodPost, finalURL, bytes.NewBuffer(payloadBytes))
  202. if err != nil {
  203. return fmt.Errorf("failed to create gotify request: %v", err)
  204. }
  205. // 设置请求头
  206. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  207. req.Header.Set("User-Agent", "NewAPI-Gotify-Notify/1.0")
  208. // 发送请求
  209. client := GetHttpClient()
  210. resp, err = client.Do(req)
  211. if err != nil {
  212. return fmt.Errorf("failed to send gotify request: %v", err)
  213. }
  214. defer resp.Body.Close()
  215. // 检查响应状态
  216. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  217. return fmt.Errorf("gotify request failed with status code: %d", resp.StatusCode)
  218. }
  219. }
  220. return nil
  221. }