sendWxTmplMsg.go 11 KB

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