wechat_push.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. log "github.com/sirupsen/logrus"
  6. "github.com/spf13/cast"
  7. "io"
  8. "net/http"
  9. "os"
  10. "pmail/config"
  11. "pmail/dto/parsemail"
  12. "pmail/hooks/framework"
  13. "pmail/models"
  14. "pmail/utils/context"
  15. "strings"
  16. "time"
  17. )
  18. type accessTokenRes struct {
  19. AccessToken string `db:"access_token" json:"access_token"`
  20. ExpiresIn int `db:"expires_in" json:"expires_in"`
  21. }
  22. type WeChatPushHook struct {
  23. appId string
  24. secret string
  25. token string
  26. tokenExpires int64
  27. templateId string
  28. pushUser string
  29. mainConfig *config.Config
  30. }
  31. func (w *WeChatPushHook) ReceiveSaveAfter(ctx *context.Context, email *parsemail.Email, ue []*models.UserEmail) {
  32. if w.appId == "" || w.secret == "" || w.pushUser == "" {
  33. return
  34. }
  35. for _, u := range ue {
  36. // 管理员(Uid=1)收到邮件且非已读、非已删除 触发通知
  37. if u.UserID == 1 && u.IsRead == 0 && u.Status != 3 && email.MessageId > 0 {
  38. content := "<<" + email.Subject + ">> " + string(email.Text)
  39. w.sendUserMsg(nil, w.pushUser, content)
  40. }
  41. }
  42. }
  43. func (w *WeChatPushHook) SendBefore(ctx *context.Context, email *parsemail.Email) {
  44. }
  45. func (w *WeChatPushHook) SendAfter(ctx *context.Context, email *parsemail.Email, err map[string]error) {
  46. }
  47. func (w *WeChatPushHook) ReceiveParseBefore(ctx *context.Context, email *[]byte) {
  48. }
  49. func (w *WeChatPushHook) ReceiveParseAfter(ctx *context.Context, email *parsemail.Email) {}
  50. func (w *WeChatPushHook) getWxAccessToken() string {
  51. if w.tokenExpires > time.Now().Unix() {
  52. return w.token
  53. }
  54. resp, err := http.Get(fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", w.appId, w.secret))
  55. if err != nil {
  56. return ""
  57. }
  58. defer resp.Body.Close()
  59. body, _ := io.ReadAll(resp.Body)
  60. var ret accessTokenRes
  61. _ = json.Unmarshal(body, &ret)
  62. if ret.AccessToken != "" {
  63. w.token = ret.AccessToken
  64. w.tokenExpires = time.Now().Unix() + cast.ToInt64(ret.ExpiresIn)
  65. }
  66. return ret.AccessToken
  67. }
  68. type sendMsgRequest struct {
  69. Touser string `db:"touser" json:"touser"`
  70. Template_id string `db:"template_id" json:"template_id"`
  71. Url string `db:"url" json:"url"`
  72. Data SendData `db:"data" json:"data"`
  73. }
  74. type SendData struct {
  75. Content DataItem `json:"Content"`
  76. }
  77. type DataItem struct {
  78. Value string `json:"value"`
  79. Color string `json:"color"`
  80. }
  81. func (w *WeChatPushHook) sendUserMsg(ctx *context.Context, userId string, content string) {
  82. url := w.mainConfig.WebDomain
  83. if w.mainConfig.HttpsEnabled > 1 {
  84. url = "http://" + url
  85. } else {
  86. url = "https://" + url
  87. }
  88. sendMsgReq, _ := json.Marshal(sendMsgRequest{
  89. Touser: userId,
  90. Template_id: w.templateId,
  91. Url: url,
  92. Data: SendData{Content: DataItem{Value: content, Color: "#000000"}},
  93. })
  94. _, err := http.Post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+w.getWxAccessToken(), "application/json", strings.NewReader(string(sendMsgReq)))
  95. if err != nil {
  96. log.WithContext(ctx).Errorf("wechat push error %+v", err)
  97. }
  98. }
  99. type Config struct {
  100. WeChatPushAppId string `json:"weChatPushAppId"`
  101. WeChatPushSecret string `json:"weChatPushSecret"`
  102. WeChatPushTemplateId string `json:"weChatPushTemplateId"`
  103. WeChatPushUserId string `json:"weChatPushUserId"`
  104. }
  105. func NewWechatPushHook() *WeChatPushHook {
  106. var cfgData []byte
  107. var err error
  108. cfgData, err = os.ReadFile("./config/config.json")
  109. if err != nil {
  110. panic(err)
  111. }
  112. var mainConfig *config.Config
  113. err = json.Unmarshal(cfgData, &mainConfig)
  114. if err != nil {
  115. panic(err)
  116. }
  117. var pluginConfig *Config
  118. if _, err := os.Stat("./plugins/wechat_push_config.json"); err == nil {
  119. cfgData, err = os.ReadFile("./plugins/wechat_push_config.json")
  120. if err != nil {
  121. panic(err)
  122. }
  123. err = json.Unmarshal(cfgData, &pluginConfig)
  124. if err != nil {
  125. panic(err)
  126. }
  127. }
  128. appid := ""
  129. secret := ""
  130. templateId := ""
  131. userId := ""
  132. if pluginConfig != nil {
  133. appid = pluginConfig.WeChatPushAppId
  134. secret = pluginConfig.WeChatPushSecret
  135. templateId = pluginConfig.WeChatPushTemplateId
  136. userId = pluginConfig.WeChatPushUserId
  137. } else {
  138. appid = mainConfig.WeChatPushAppId
  139. secret = mainConfig.WeChatPushSecret
  140. templateId = mainConfig.WeChatPushTemplateId
  141. userId = mainConfig.WeChatPushUserId
  142. }
  143. ret := &WeChatPushHook{
  144. appId: appid,
  145. secret: secret,
  146. templateId: templateId,
  147. pushUser: userId,
  148. mainConfig: mainConfig,
  149. }
  150. return ret
  151. }
  152. // 插件将以独立进程运行,因此需要主函数。
  153. func main() {
  154. framework.CreatePlugin("wechat_push", NewWechatPushHook()).Run()
  155. }