sendMsg.go 17 KB

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