sendMsg.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. package common
  2. import (
  3. "app.yhyue.com/moapp/MessageCenter/entity"
  4. "app.yhyue.com/moapp/MessageCenter/rpc/type/message"
  5. "app.yhyue.com/moapp/MessageCenter/util"
  6. "app.yhyue.com/moapp/jybase/common"
  7. "app.yhyue.com/moapp/jybase/redis"
  8. "fmt"
  9. "github.com/zeromicro/go-zero/core/logx"
  10. "log"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. )
  16. // 类型的顺序
  17. const order = "1,4"
  18. const MsgCountKey = "count_%s_%d" //redis 消息未读数量 Count.用户id.消息类型=数量
  19. const redisModule = "msgCount"
  20. func FindUserMsg(this message.FindUserMsgReq, isClean bool) message.FindUserMsgRes {
  21. var err error
  22. var count int64
  23. cquery := map[string]interface{}{
  24. "receive_userid": this.UserId,
  25. "isdel": 1,
  26. "appid": this.Appid,
  27. }
  28. if this.MsgType > 0 {
  29. cquery["group_id"] = this.MsgType
  30. }
  31. if this.Read != -1 {
  32. cquery["isRead"] = this.Read
  33. }
  34. count = entity.Mysql.Count("message", cquery)
  35. data := message.FindUserMsgRes{}
  36. if this.PageSize == 5 {
  37. //从缓存里边取数据
  38. pc_a, err := entity.GetData(this.UserId)
  39. if err == nil && pc_a != nil {
  40. // 缓存有值
  41. if !isClean {
  42. data.Code = 1
  43. data.Message = "查询成功"
  44. data.Data = pc_a.Data
  45. data.Count = pc_a.Count
  46. return data
  47. }
  48. }
  49. }
  50. count = entity.Mysql.Count("message", cquery)
  51. if count > 0 {
  52. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  53. //log.Println("数据:", res)
  54. if res != nil && len(*res) > 0 {
  55. for _, v := range *res {
  56. _id := util.Int64All(v["id"])
  57. id := strconv.FormatInt(_id, 10)
  58. data.Data = append(data.Data, &message.Messages{
  59. Id: id,
  60. Appid: util.ObjToString(v["appId"]),
  61. ReceiveUserId: util.ObjToString(v["receive_userid"]),
  62. ReceiveName: util.ObjToString(v["receive_name"]),
  63. SendUserId: util.ObjToString(v["send_userid"]),
  64. SendName: util.ObjToString(v["send_name"]),
  65. Createtime: util.ObjToString(v["createtime"]),
  66. Title: util.ObjToString(v["title"]),
  67. MsgType: int64(util.IntAll(v["group_id"])),
  68. Link: util.ObjToString(v["link"]),
  69. CiteId: util.Int64All(v["cite_id"]),
  70. Content: util.ObjToString(v["content"]),
  71. IsRead: util.Int64All(v["isRead"]),
  72. MsgLogId: util.Int64All(v["msg_log_id"]),
  73. })
  74. }
  75. }
  76. }
  77. data.Count = count
  78. if this.PageSize == 5 {
  79. redisData := map[string]interface{}{
  80. "count": count,
  81. "data": data.Data,
  82. }
  83. entity.SetData(this.UserId, redisData, entity.SurvivalTime)
  84. }
  85. if err != nil {
  86. data.Code = 0
  87. data.Message = "查询失败"
  88. } else {
  89. data.Code = 1
  90. data.Message = "查询成功"
  91. }
  92. return data
  93. }
  94. func UserMsgList(this *message.UserMsgListReq) *message.UserMsgList {
  95. var (
  96. unread, count int64
  97. )
  98. data := new(message.UserMsgList)
  99. if !this.IsMsgList && !this.IsColumnNewMsg && !this.IsColumn { //消息未读数统计
  100. var isUnread, isColumn int
  101. for _, v := range entity.MessageColumn {
  102. if util.IntAll(v["group_id"]) > 0 && util.IntAll(v["group_id"]) < 999 {
  103. isColumn++ //去除全部与私信
  104. key := fmt.Sprintf(MsgCountKey, this.UserId, util.IntAll(v["group_id"]))
  105. if exists, _ := redis.Exists(redisModule, key); exists {
  106. isUnread++
  107. unread += util.Int64All(redis.GetInt(redisModule, key))
  108. }
  109. }
  110. }
  111. if isUnread != isColumn {
  112. m := &MessageService{}
  113. unread = m.CountUnread(this.UserId)
  114. }
  115. if this.IsContainLetter { //私信统计
  116. unread += unreadMsg(this)
  117. }
  118. data.Unread = unread
  119. return data
  120. }
  121. cquery := map[string]interface{}{
  122. "receive_userid": this.UserId,
  123. "isdel": 1,
  124. "appid": this.Appid,
  125. }
  126. if this.MsgType > 0 {
  127. cquery["group_id"] = this.MsgType
  128. }
  129. if this.Read != -1 {
  130. cquery["isRead"] = this.Read
  131. }
  132. //获取栏目下的数据
  133. sData := make(map[string][]*message.Messages)
  134. t := time.Now()
  135. if this.IsColumnNewMsg && this.SortSize > 0 {
  136. sortData := entity.Mysql.SelectBySql(fmt.Sprintf(`SELECT * FROM (
  137. SELECT *, ROW_NUMBER() OVER (PARTITION BY group_id, receive_userid ORDER BY createtime DESC) AS row_num
  138. FROM message
  139. WHERE receive_userid = '%s' and isdel = 1 and appid = %s
  140. ) AS message_ranked
  141. WHERE row_num <=%d;`, this.UserId, this.Appid, this.SortSize))
  142. log.Println("消息列表耗时1:", time.Since(t))
  143. if sortData != nil {
  144. for _, v := range *sortData {
  145. _id := util.Int64All(v["id"])
  146. id := strconv.FormatInt(_id, 10)
  147. var msg = message.Messages{
  148. Id: id,
  149. Appid: common.InterfaceToStr(v["appId"]),
  150. ReceiveUserId: common.InterfaceToStr(v["receive_userid"]),
  151. ReceiveName: common.InterfaceToStr(v["receive_name"]),
  152. SendUserId: common.InterfaceToStr(v["send_userid"]),
  153. SendName: common.InterfaceToStr(v["send_name"]),
  154. Createtime: common.InterfaceToStr(v["createtime"]),
  155. Title: common.InterfaceToStr(v["title"]),
  156. MsgType: int64(util.IntAll(v["group_id"])),
  157. Link: common.InterfaceToStr(v["link"]),
  158. CiteId: util.Int64All(v["cite_id"]),
  159. Content: common.InterfaceToStr(v["content"]),
  160. IsRead: util.Int64All(v["isRead"]),
  161. MsgLogId: util.Int64All(v["msg_log_id"]),
  162. }
  163. if sData[common.InterfaceToStr(v["group_id"])] == nil {
  164. sData[common.InterfaceToStr(v["group_id"])] = []*message.Messages{&msg}
  165. } else {
  166. sData[common.InterfaceToStr(v["group_id"])] = append(sData[common.InterfaceToStr(v["group_id"])], &msg)
  167. }
  168. }
  169. }
  170. }
  171. //消息栏目下的最新消息
  172. var columnData []*message.AllSortData
  173. if this.IsColumn {
  174. for _, v := range entity.MessageColumn {
  175. var column message.AllSortData
  176. column.Name = common.InterfaceToStr(v["name"])
  177. column.Img = fmt.Sprintf("/common-module/msgCenter/%s.png", common.InterfaceToStr(v["img"]))
  178. column.MsgType = common.Int64All(v["group_id"])
  179. if column.Name == "私信" {
  180. column.UnreadMessages = unreadMsg(this)
  181. } else if common.IntAll(v["group_id"]) > 0 {
  182. //消息未读数
  183. msgType := common.InterfaceToStr(v["group_id"])
  184. column.UnreadMessages = util.Int64All(redis.GetInt(redisModule, fmt.Sprintf(MsgCountKey, this.UserId, util.IntAll(msgType))))
  185. column.Data = sData[msgType]
  186. }
  187. unread += column.UnreadMessages
  188. columnData = append(columnData, &column)
  189. }
  190. }
  191. data.SortData = columnData
  192. count = entity.Mysql.Count("message", cquery)
  193. if this.IsMsgList {
  194. if count > 0 {
  195. if this.OffSet <= 0 {
  196. this.OffSet = 1
  197. }
  198. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  199. log.Println("消息列表耗时3:", time.Since(t))
  200. if res != nil && len(*res) > 0 {
  201. for _, v := range *res {
  202. _id := util.Int64All(v["id"])
  203. id := strconv.FormatInt(_id, 10)
  204. data.Data = append(data.Data, &message.Messages{
  205. Id: id,
  206. Appid: common.InterfaceToStr(v["appId"]),
  207. ReceiveUserId: common.InterfaceToStr(v["receive_userid"]),
  208. ReceiveName: common.InterfaceToStr(v["receive_name"]),
  209. SendUserId: common.InterfaceToStr(v["send_userid"]),
  210. SendName: common.InterfaceToStr(v["send_name"]),
  211. Createtime: common.InterfaceToStr(v["createtime"]),
  212. Title: common.InterfaceToStr(v["title"]),
  213. MsgType: int64(util.IntAll(v["group_id"])),
  214. Link: common.InterfaceToStr(v["link"]),
  215. CiteId: util.Int64All(v["cite_id"]),
  216. Content: common.InterfaceToStr(v["content"]),
  217. IsRead: util.Int64All(v["isRead"]),
  218. MsgLogId: util.Int64All(v["msg_log_id"]),
  219. })
  220. }
  221. }
  222. }
  223. }
  224. data.Count = count
  225. if !this.IsColumn && this.Read == 0 {
  226. unread = count
  227. if this.IsContainLetter { //是否需要统计私信未读数
  228. unread += unreadMsg(this)
  229. }
  230. }
  231. data.Unread = unread
  232. return data
  233. }
  234. func unreadMsg(this *message.UserMsgListReq) int64 {
  235. if this.PositionId <= 0 {
  236. return 0
  237. }
  238. querySql := fmt.Sprintf("SELECT b.*,(SELECT SUM( a.unread) FROM %s a "+
  239. "LEFT JOIN %s b ON a.message_id = b.id "+
  240. "WHERE a.unread > 0 "+
  241. "AND ( a.my_position_id = %d OR a.user_id = %d )) AS unread "+
  242. "FROM %s a "+
  243. "LEFT JOIN %s b ON a.message_id = b.id "+
  244. "WHERE a.unread > 0 "+
  245. "AND ( a.my_position_id = %d OR a.user_id = %d ) "+
  246. "ORDER BY a.TIMESTAMP DESC LIMIT 0,1", "socialize_summary", "socialize_message", this.PositionId, this.NewUserId,
  247. "socialize_summary", "socialize_message", this.PositionId, this.NewUserId)
  248. log.Println("查询sql", querySql)
  249. msgUnread := entity.BaseMysql.SelectBySql(querySql)
  250. if msgUnread != nil && len(*msgUnread) > 0 {
  251. return common.Int64All((*msgUnread)[0]["unread"])
  252. }
  253. return 0
  254. }
  255. func UserUnreadMsgList(this *message.UserUnreadMsgListReq) (int64, []*message.Messages) {
  256. count := 0
  257. data := []*message.Messages{}
  258. types := entity.Mysql.Find("message_group", map[string]interface{}{}, `"group_id"`, "", -1, -1)
  259. if types != nil && len(*types) > 0 {
  260. for _, v := range *types {
  261. key := fmt.Sprintf(MsgCountKey, this.UserId, util.IntAll(v["group_id"]))
  262. if exists, _ := redis.Exists(redisModule, key); exists {
  263. count += redis.GetInt(redisModule, key)
  264. }
  265. }
  266. }
  267. if this.IsNeedData == 1 && count > 0 {
  268. query := map[string]interface{}{
  269. "receive_userid": this.UserId,
  270. "isdel": 1,
  271. "appid": this.Appid,
  272. "isRead": 0,
  273. }
  274. res := entity.Mysql.Find("message", query, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  275. if res != nil && len(*res) > 0 {
  276. for _, val := range *res {
  277. _id := util.Int64All(val["id"])
  278. id := strconv.FormatInt(_id, 10)
  279. links4 := common.InterfaceToStr(val["link"])
  280. link4, androidUrl4, iosUrl4, weChatUrl4 := util.LinkSplit(links4)
  281. url := map[string]string{
  282. "androidUrl": androidUrl4,
  283. "iosUrl": iosUrl4,
  284. "weChatUrl": weChatUrl4,
  285. }
  286. data = append(data, &message.Messages{
  287. Id: id,
  288. Appid: common.InterfaceToStr(val["appid"]),
  289. ReceiveUserId: common.InterfaceToStr(val["receive_userid"]),
  290. ReceiveName: common.InterfaceToStr(val["receive_name"]),
  291. SendUserId: common.InterfaceToStr(val["send_userid"]),
  292. SendName: common.InterfaceToStr(val["send_name"]),
  293. Createtime: common.InterfaceToStr(val["createtime"]),
  294. Title: common.InterfaceToStr(val["title"]),
  295. MsgType: common.Int64All(val["group_id"]),
  296. Link: link4,
  297. CiteId: common.Int64All(val["cite_id"]),
  298. Content: common.InterfaceToStr(val["content"]),
  299. IsRead: common.Int64All(val["isRead"]),
  300. MsgLogId: common.Int64All(val["msg_log_id"]),
  301. Url: url,
  302. })
  303. }
  304. }
  305. }
  306. return util.Int64All(count), data
  307. }
  308. func MessageGetLast(this *message.UserMsgListReq) *message.Messages {
  309. if !this.IsMsgList && !this.IsColumnNewMsg && !this.IsColumn {
  310. return nil
  311. }
  312. query := map[string]interface{}{
  313. "receive_userid": this.UserId,
  314. "isdel": 1,
  315. "appid": this.Appid,
  316. "isRead": 0,
  317. "group_id": 1,
  318. }
  319. lastMsg := entity.Mysql.FindOne("message", query, "", "createtime desc")
  320. if lastMsg != nil && len(*lastMsg) > 0 {
  321. _id := util.Int64All((*lastMsg)["id"])
  322. id := strconv.FormatInt(_id, 10)
  323. msg := message.Messages{
  324. Id: id,
  325. Appid: common.InterfaceToStr((*lastMsg)["appid"]),
  326. ReceiveUserId: common.InterfaceToStr((*lastMsg)["receive_userid"]),
  327. ReceiveName: common.InterfaceToStr((*lastMsg)["receive_name"]),
  328. SendUserId: common.InterfaceToStr((*lastMsg)["send_userid"]),
  329. SendName: common.InterfaceToStr((*lastMsg)["send_name"]),
  330. Createtime: common.InterfaceToStr((*lastMsg)["createtime"]),
  331. Title: common.InterfaceToStr((*lastMsg)["title"]),
  332. MsgType: common.Int64All((*lastMsg)["group_id"]),
  333. Link: common.InterfaceToStr((*lastMsg)["link"]),
  334. CiteId: common.Int64All((*lastMsg)["cite_id"]),
  335. Content: common.InterfaceToStr((*lastMsg)["content"]),
  336. IsRead: common.Int64All((*lastMsg)["isRead"]),
  337. MsgLogId: common.Int64All((*lastMsg)["msg_log_id"]),
  338. }
  339. return &msg
  340. }
  341. return nil
  342. }
  343. // MsgCountAdd 消息未读数量加1
  344. func MsgCountAdd(userId, appId string, msgType int64) bool {
  345. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  346. exists, _ := redis.Exists(redisModule, keyString)
  347. if exists {
  348. in := redis.Incr(redisModule, keyString)
  349. FindUserMsg(message.FindUserMsgReq{
  350. UserId: userId,
  351. Appid: appId,
  352. OffSet: 1,
  353. PageSize: 5,
  354. MsgType: -1,
  355. Read: 0,
  356. }, true)
  357. return in > 0
  358. }
  359. return true
  360. }
  361. // MsgCountMinusOne 根据消息类型未读消息数量减1
  362. func MsgCountMinusOne(userId, appId string, msgType int64) bool {
  363. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  364. exists, _ := redis.Exists(redisModule, keyString)
  365. if exists {
  366. FindUserMsg(message.FindUserMsgReq{
  367. UserId: userId,
  368. Appid: appId,
  369. OffSet: 1,
  370. PageSize: 5,
  371. MsgType: -1,
  372. Read: 0,
  373. }, true)
  374. if redis.GetInt(redisModule, keyString) <= 0 {
  375. return true
  376. }
  377. in := redis.Decrby(redisModule, keyString, 1)
  378. return in > 0
  379. }
  380. return true
  381. }
  382. // MsgCountZero 把该消息类型未读数量置0
  383. func MsgCountZero(userId, appId string, msgType int64) bool {
  384. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  385. fool := redis.Put(redisModule, keyString, 0, -1)
  386. FindUserMsg(message.FindUserMsgReq{
  387. UserId: userId,
  388. Appid: appId,
  389. OffSet: 1,
  390. PageSize: 5,
  391. MsgType: -1,
  392. Read: 0,
  393. }, true)
  394. return fool
  395. }
  396. func MultSave(this message.MultipleSaveMsgReq) (int64, string) {
  397. userIdArr := strings.Split(this.UserIds, ",")
  398. userNameArr := strings.Split(this.UserNames, ",")
  399. positionIdArr := strings.Split(this.PositionIds, ",")
  400. if len(userIdArr) == 0 {
  401. return 0, "无效的用户id"
  402. }
  403. wg := &sync.WaitGroup{}
  404. var group_id int
  405. class := entity.Mysql.FindOne("message_class", map[string]interface{}{"msg_type": this.MsgType}, "group_id", "")
  406. if class != nil && len(*class) > 0 {
  407. group_id = util.IntAll((*class)["group_id"])
  408. }
  409. for i := 0; i < len(userIdArr); i++ {
  410. if userIdArr[i] == "" {
  411. continue
  412. }
  413. name := userNameArr[i]
  414. wg.Add(1)
  415. entity.SaveConcurrencyChan <- 1
  416. var positionId int64
  417. if len(positionIdArr) == len(userIdArr) {
  418. positionId = common.Int64All(positionIdArr[i])
  419. }
  420. go func(v, userName string, positionId int64) {
  421. defer func() {
  422. <-entity.SaveConcurrencyChan
  423. wg.Done()
  424. }()
  425. //消息数组
  426. nTime := time.Now().Format("2006-01-02 15:04:05")
  427. c := entity.Mysql.Count("conversation", map[string]interface{}{"receive_id": v, "send_id": this.SendUserId})
  428. sql3 := `INSERT INTO message(appid,receive_userid,receive_name,send_userid,send_name,title,content,msg_type,link,cite_id,createtime,isRead,isdel,msg_log_id,show_buoy,show_content,group_id,position_id) values ("%s",'%s','%s','%s','%s','%s','%s',%d,'%s',0,'%s',0,1,%d,%d,'%s',%d,?);`
  429. sql3 = fmt.Sprintf(sql3, this.Appid, v, userName, this.SendUserId, this.SendName, this.Title, this.Content, this.MsgType, this.Link, nTime, this.MsgLogId, this.ShowBuoy, this.ShowContent, group_id)
  430. var in int64
  431. if c <= 0 {
  432. sql1 := `INSERT INTO conversation(appid,secret_key,user_id,receive_id,receive_name,send_id,send_name,sort,createtime) values ('%s','','%s','%s','%s','%s','%s',0,'%s');`
  433. sql1 = fmt.Sprintf(sql1, this.Appid, this.SendUserId, v, userName, this.SendUserId, this.SendName, nTime)
  434. //插入会话表
  435. in1 := entity.Mysql.InsertBySql(sql1)
  436. sql2 := `INSERT INTO conversation(appid,secret_key,user_id,receive_id,receive_name,send_id,send_name,sort,createtime) values ('%s','','%s','%s','%s','%s','%s',0,'%s');`
  437. sql2 = fmt.Sprintf(sql2, this.Appid, v, this.SendUserId, this.SendName, v, userName, nTime)
  438. in2 := entity.Mysql.InsertBySql(sql2)
  439. //插入消息表
  440. in = entity.Mysql.InsertBySql(sql3, common.If(positionId != 0, positionId, nil))
  441. logx.Info(in1, in2, in)
  442. if in1 > -1 && in2 > -1 && in > -1 {
  443. ok1 := MsgCountAdd(v, this.Appid, this.MsgType)
  444. if !ok1 {
  445. log.Println("存redis:", ok1, v)
  446. }
  447. }
  448. } else {
  449. in = entity.Mysql.InsertBySql(sql3, common.If(positionId != 0, positionId, nil))
  450. logx.Info("插入消息返回 in1 id:", in)
  451. if in > -1 {
  452. ok := MsgCountAdd(v, this.Appid, util.Int64All(group_id))
  453. if !ok {
  454. log.Println("存redis:", ok, v)
  455. }
  456. }
  457. }
  458. if in > -1 {
  459. //发送消息成功,推送微信、app
  460. pushConfig, err := GetWxTmplConfig(this.MsgType)
  461. if err != nil {
  462. logx.Error(fmt.Sprintf("SendWxTmplMsg uId %s Error %s", v, err.Error()))
  463. }
  464. p := &WxTmplPush{
  465. Config: pushConfig,
  466. }
  467. p.MgoId = v
  468. if this.MsgType == 10 {
  469. this.Title = this.ProductName
  470. this.Content = this.OrderId
  471. nTime = this.OrderMoney
  472. }
  473. // 消息模版 工单类型 {{thing19.DATA}} 工单标题 {{thing6.DATA}} 项目名称 {{thing13.DATA}} 服务时间 {{time25.DATA}} 服务地址 {{thing26.DATA}}
  474. err = p.SendMsg(this.WxPushUrl, this.Title, this.Content, nTime, this.Row4)
  475. if err != nil {
  476. logx.Error(fmt.Sprintf("SendWxTmplMsg uId %s Error %s", v, err.Error()))
  477. } else {
  478. logx.Infof("SendWxTmplMsg uId success %s ", v)
  479. }
  480. //app推送
  481. uData := p.GetUserPushInfo()
  482. if err = AppPushMsg(uData, pushConfig.Switch, this.AppPushUrl, this.Title, this.Content, this.MsgType); err != nil {
  483. logx.Error(fmt.Sprintf("SendWxTmplMsg uId %s Error %s", v, err.Error()))
  484. }
  485. }
  486. }(userIdArr[i], name, positionId)
  487. }
  488. wg.Wait()
  489. return 0, ""
  490. }