sendMsg.go 16 KB

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