sendWxTmplMsg.go 10 KB

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