sendWxTmplMsg.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package common
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net/url"
  7. "regexp"
  8. "strings"
  9. "time"
  10. "app.yhyue.com/moapp/MessageCenter/entity"
  11. "app.yhyue.com/moapp/MessageCenter/rpc/internal/config"
  12. "app.yhyue.com/moapp/MessageCenter/rpc/type/message"
  13. "app.yhyue.com/moapp/MessageCenter/util"
  14. "app.yhyue.com/moapp/jybase/common"
  15. dataFormat "app.yhyue.com/moapp/jybase/date"
  16. m "app.yhyue.com/moapp/jybase/mongodb"
  17. "app.yhyue.com/moapp/jybase/redis"
  18. qrpc "app.yhyue.com/moapp/jybase/rpc"
  19. )
  20. type WxTmplPush struct {
  21. MgoId, OpenId, Position, OpushId, JpushId, AppPoneType string //UserId 用户mgoId, OpenId 微信id, Position 职位id
  22. Config *WxTmplConfig
  23. CustomWxTpl *message.CustomWxTpl
  24. }
  25. var AllMsgType func() map[int64]WxTmplConfig
  26. var allMsgValueKeys = []string{"$class", "$title", "$detail", "$date", "$row4", "$note"}
  27. var AppPushMsgType map[int]string
  28. type WxTmplConfig struct {
  29. Name string //信息名称
  30. Switch string //开关
  31. TmplId string //微信模版id
  32. TmplValue string //微信模版
  33. }
  34. const CacheDb = "msgCount"
  35. func MessageType() (func() map[int64]WxTmplConfig, []map[string]interface{}) {
  36. var data []map[string]interface{}
  37. rData1 := entity.Mysql.SelectBySql(`SELECT * FROM message_group ORDER BY sequence ASC`)
  38. switchName := map[int64]WxTmplConfig{}
  39. appMsgType := map[int]string{}
  40. if rData1 != nil && len(*rData1) > 0 {
  41. data = *rData1
  42. for _, v := range *rData1 {
  43. groupId := util.IntAll(v["group_id"])
  44. switchs := util.ObjToString(v["switch"])
  45. appMsgType[groupId] = switchs
  46. }
  47. AppPushMsgType = appMsgType
  48. }
  49. rData2 := entity.Mysql.SelectBySql(`SELECT g.switch,c.wxtmpl_Id,c.msg_type,c.msg_name,c.wxtmp_value FROM message_class c INNER JOIN message_group g on c.group_id =g.group_id WHERE c.wxtmpl_Id IS NOT NULL`)
  50. for _, mData := range *rData2 {
  51. if msg_type, settingKey, messageName, tmplId, tmplValue := util.Int64All(mData["msg_type"]), util.ObjToString(mData["switch"]), util.ObjToString(mData["msg_name"]), util.ObjToString(mData["wxtmpl_Id"]), util.ObjToString(mData["wxtmp_value"]); msg_type > 0 && settingKey != "" && messageName != "" && tmplId != "" && tmplValue != "" {
  52. switchName[msg_type] = WxTmplConfig{
  53. Name: messageName,
  54. Switch: settingKey,
  55. TmplId: tmplId,
  56. TmplValue: tmplValue,
  57. }
  58. }
  59. }
  60. return func() map[int64]WxTmplConfig {
  61. return switchName
  62. }, data
  63. }
  64. var getSendTotalRedisKey = func(uFlag ...string) string {
  65. if len(uFlag) == 0 { //统计当日信息总发送量
  66. return fmt.Sprintf("messageCenter_SendWxMsgTotal_%s", time.Now().Format(dataFormat.Date_yyyyMMdd))
  67. } //统计单用户今日发送量
  68. return fmt.Sprintf("messageCenter_SendWxMsgTotal_%s_%s", time.Now().Format(dataFormat.Date_yyyyMMdd), uFlag[0])
  69. }
  70. func GetWxTmplConfig(msgType int64) (*WxTmplConfig, error) {
  71. if val, ok := AllMsgType()[msgType]; ok {
  72. return &val, nil
  73. }
  74. return nil, fmt.Errorf("未知消息类型")
  75. }
  76. func (stm *WxTmplPush) SendMsg(link, title, detail, date, row4 string) error {
  77. if stm.Config == nil || stm.Config.TmplId == "" || (stm.MgoId != "" && stm.OpenId != "" && stm.Position != "") || link == "" {
  78. return fmt.Errorf("缺少参数 stm.Config.TmplId:%v stm.MgoId:%v stm.OpenId:%v stm.Position:%v link:%v ", stm.Config.TmplId, stm.MgoId, stm.OpenId, stm.Position, link)
  79. }
  80. // 校验推送是否开启
  81. if err := stm.getUserOpenIdAndWxPushState(); err != nil {
  82. return err
  83. }
  84. var msg map[string]*qrpc.TmplItem
  85. if stm.CustomWxTpl != nil && stm.CustomWxTpl.TplId != "" {
  86. stm.Config.TmplId = stm.CustomWxTpl.TplId
  87. msg = map[string]*qrpc.TmplItem{}
  88. for k, v := range stm.CustomWxTpl.TmplData {
  89. msg[k] = &qrpc.TmplItem{
  90. Value: v.Value,
  91. Color: v.Color,
  92. }
  93. }
  94. } else {
  95. // 获取消息
  96. msgTemp, err := stm.getMessage(title, detail, date, row4)
  97. if err != nil {
  98. return err
  99. }
  100. msg = msgTemp
  101. }
  102. // 校验发送量及频率
  103. err, noteFunc := stm.IncrCount()
  104. if err != nil {
  105. return err
  106. }
  107. // 发送信息
  108. autoLoginHref := fmt.Sprintf("%s/swordfish/SingleLogin?toHref=%s", config.ConfigJson.WxWebdomain, url.QueryEscape(link))
  109. if _, err := stm.Send(autoLoginHref, msg); err != nil {
  110. // 发送失败数量回滚
  111. stm.RollBack()
  112. return err
  113. }
  114. if noteFunc != nil {
  115. noteFunc()
  116. }
  117. return nil
  118. }
  119. var (
  120. regSpecial = regexp.MustCompile(`\\n|\\t|\\'|\\"|\n|\t|\'|\"`)
  121. )
  122. // getMessage 获取消息内容
  123. func (stm *WxTmplPush) getMessage(title, detail, date, row4 string) (map[string]*qrpc.TmplItem, error) {
  124. var formatValue string = stm.Config.TmplValue
  125. for _, key := range allMsgValueKeys {
  126. switch key {
  127. case "$class":
  128. formatValue = strings.ReplaceAll(formatValue, key, regSpecial.ReplaceAllString(stm.Config.Name, ""))
  129. case "$title":
  130. formatValue = strings.ReplaceAll(formatValue, key, regSpecial.ReplaceAllString(title, ""))
  131. case "$detail":
  132. formatValue = strings.ReplaceAll(formatValue, key, regSpecial.ReplaceAllString(detail, ""))
  133. case "$date":
  134. formatValue = strings.ReplaceAll(formatValue, key, regSpecial.ReplaceAllString(date, ""))
  135. case "$row4":
  136. formatValue = strings.ReplaceAll(formatValue, key, regSpecial.ReplaceAllString(row4, ""))
  137. case "$note":
  138. formatValue = strings.ReplaceAll(formatValue, key, regSpecial.ReplaceAllString(config.ConfigJson.WxTmplConfig.CloseNotice, ""))
  139. }
  140. }
  141. bValue := map[string]*qrpc.TmplItem{}
  142. if err := json.Unmarshal([]byte(formatValue), &bValue); err != nil {
  143. return nil, fmt.Errorf("格式化信息内容异常 %s", err.Error())
  144. }
  145. for _, item := range bValue {
  146. val := []rune(item.Value)
  147. if len(val) > 20 {
  148. item.Value = string(val[:17]) + "..."
  149. }
  150. }
  151. return bValue, nil
  152. }
  153. // RollBack 发送失败数量回滚
  154. func (stm *WxTmplPush) RollBack() {
  155. uCache, allCache := getSendTotalRedisKey(stm.OpenId), getSendTotalRedisKey()
  156. redis.Decrby(CacheDb, allCache, 1)
  157. redis.Decrby(CacheDb, uCache, 1)
  158. redis.Del(CacheDb, fmt.Sprintf("%s_sendwait", uCache)) //清除发送间隔
  159. }
  160. func (stm *WxTmplPush) IncrCount() (error, func()) {
  161. uCache, allCache := getSendTotalRedisKey(stm.OpenId), getSendTotalRedisKey() //当日微信模版消息发送总量
  162. //校验发送间隔
  163. if sendWait, _ := redis.Exists(CacheDb, fmt.Sprintf("%s_sendwait", uCache)); sendWait {
  164. return fmt.Errorf("发送模版消息频繁,稍后重试"), nil
  165. }
  166. var total int64
  167. if total = redis.Incr(CacheDb, allCache); total == 1 {
  168. _ = redis.SetExpire(CacheDb, allCache, 60*60*24)
  169. }
  170. if total > config.ConfigJson.WxTmplConfig.Limit.Total {
  171. redis.Decrby(CacheDb, allCache, 1)
  172. return fmt.Errorf("已达发送总量上限"), nil
  173. }
  174. uTotal := redis.Incr(CacheDb, uCache)
  175. if uTotal == 1 {
  176. _ = redis.SetExpire(CacheDb, uCache, 60*60*24)
  177. } //当日用户发送数量
  178. if uTotal > config.ConfigJson.WxTmplConfig.Limit.OneDayLimit {
  179. redis.Decrby(CacheDb, allCache, 1)
  180. redis.Decrby(CacheDb, uCache, 1)
  181. return fmt.Errorf("已达单该用户发送总量上限"), nil
  182. }
  183. //下次发送时间
  184. redis.Put(CacheDb, fmt.Sprintf("%s_sendwait", uCache), 1, config.ConfigJson.WxTmplConfig.Limit.DuringMine*60)
  185. return nil, func() {
  186. for _, num := range config.ConfigJson.WxTmplConfig.Limit.Alert.Nums {
  187. if total == num {
  188. util.SendRetryMail(3, strings.Join(config.ConfigJson.WxTmplConfig.Limit.Alert.ToMail, ","), strings.Join(config.ConfigJson.WxTmplConfig.Limit.Alert.CcMail, ","),
  189. "剑鱼微信模版告警邮件", fmt.Sprintf("今日发送微信模版信息数量已达%d条,总量%d条", total, config.ConfigJson.WxTmplConfig.Limit.Total), entity.GmailAuth)
  190. }
  191. }
  192. }
  193. }
  194. // getUserOpenIdAndWxPushState 查询微信openid微信消息通知状态
  195. // mId mongoUserid、oId 用户openid、pId positionId 用户职位id
  196. func (stm *WxTmplPush) getUserOpenIdAndWxPushState() error {
  197. uData := stm.GetUserPushInfo()
  198. if uData == nil {
  199. return fmt.Errorf("未查询到用户信息")
  200. }
  201. stm.OpenId = common.ObjToString(uData["s_m_openid"])
  202. if stm.OpenId == "" {
  203. return fmt.Errorf("未查询到用户微信信息")
  204. }
  205. log.Println("======", stm.Config.Switch)
  206. if pushSetMap := common.ObjToMap(uData["o_pushset"]); pushSetMap != nil && len(*pushSetMap) > 0 {
  207. if pushKeyMap := common.ObjToMap((*pushSetMap)[stm.Config.Switch]); pushKeyMap != nil && len(*pushKeyMap) > 0 {
  208. if common.Int64All((*pushKeyMap)["i_wxpush"]) == 1 {
  209. return nil
  210. }
  211. }
  212. }
  213. return fmt.Errorf("未开启推送设置")
  214. }
  215. func (stm *WxTmplPush) GetUserPushInfo() map[string]interface{} {
  216. uData := func() map[string]interface{} {
  217. query := map[string]interface{}{}
  218. if stm.OpenId != "" {
  219. query["s_m_openid"] = stm.OpenId
  220. } else if stm.MgoId != "" {
  221. query["_id"] = m.StringTOBsonId(stm.MgoId)
  222. } else if stm.Position != "" {
  223. uInfo := entity.Mysql.SelectBySql("SELECT user_id FROM base_service.base_position WHERE id = ? ", stm.Position)
  224. if uInfo != nil && len(*uInfo) > 0 {
  225. if baseUserId := common.Int64All((*uInfo)[0]["user_id"]); baseUserId != 0 {
  226. query["base_user_id"] = baseUserId
  227. }
  228. }
  229. }
  230. if len(query) > 0 {
  231. rData, _ := entity.MQFW.FindOneByField("user", query, fmt.Sprintf(`{"s_m_openid":1,"s_opushid": 1, "s_jpushid": 1, "s_appponetype": 1, "s_appversion": 1,"o_pushset.%s":1}`, stm.Config.Switch))
  232. if rData != nil && len(*rData) > 0 {
  233. return *rData
  234. }
  235. }
  236. return nil
  237. }()
  238. return uData
  239. }
  240. // Send 发送微信模版消息
  241. func (stm *WxTmplPush) Send(link string, msg map[string]*qrpc.TmplItem) (pushOk bool, err error) {
  242. return qrpc.WxSendTmplMsg(config.ConfigJson.WxTmplConfig.RpcAddr, &qrpc.WxTmplMsg{
  243. OpenId: stm.OpenId,
  244. TplId: stm.Config.TmplId,
  245. TmplData: msg,
  246. Url: link,
  247. })
  248. }