sendMsg.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. "database/sql"
  9. "fmt"
  10. "github.com/zeromicro/go-zero/core/logx"
  11. "log"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. // 类型的顺序
  18. const order = "1,4"
  19. const MsgCountKey = "count_%s_%d" //redis 消息未读数量 Count.用户id.消息类型=数量
  20. const redisModule = "msgCount"
  21. func FindUserMsg(this message.FindUserMsgReq, isClean bool) message.FindUserMsgRes {
  22. var err error
  23. var count int64
  24. cquery := map[string]interface{}{
  25. "receive_userid": this.UserId,
  26. "isdel": 1,
  27. "appid": this.Appid,
  28. }
  29. if this.MsgType > 0 {
  30. cquery["group_id"] = this.MsgType
  31. }
  32. if this.Read != -1 {
  33. cquery["isRead"] = this.Read
  34. }
  35. count = entity.Mysql.Count("message", cquery)
  36. data := message.FindUserMsgRes{}
  37. if this.PageSize == 5 {
  38. //从缓存里边取数据
  39. pc_a, err := entity.GetData(this.UserId)
  40. if err == nil && pc_a != nil {
  41. // 缓存有值
  42. if !isClean {
  43. data.Code = 1
  44. data.Message = "查询成功"
  45. data.Data = pc_a.Data
  46. data.Count = pc_a.Count
  47. return data
  48. }
  49. }
  50. }
  51. count = entity.Mysql.Count("message", cquery)
  52. if count > 0 {
  53. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  54. //log.Println("数据:", res)
  55. if res != nil && len(*res) > 0 {
  56. for _, v := range *res {
  57. _id := util.Int64All(v["id"])
  58. id := strconv.FormatInt(_id, 10)
  59. data.Data = append(data.Data, &message.Messages{
  60. Id: id,
  61. Appid: util.ObjToString(v["appId"]),
  62. ReceiveUserId: util.ObjToString(v["receive_userid"]),
  63. ReceiveName: util.ObjToString(v["receive_name"]),
  64. SendUserId: util.ObjToString(v["send_userid"]),
  65. SendName: util.ObjToString(v["send_name"]),
  66. Createtime: util.ObjToString(v["createtime"]),
  67. Title: util.ObjToString(v["title"]),
  68. MsgType: int64(util.IntAll(v["group_id"])),
  69. Link: util.ObjToString(v["link"]),
  70. CiteId: util.Int64All(v["cite_id"]),
  71. Content: util.ObjToString(v["content"]),
  72. IsRead: util.Int64All(v["isRead"]),
  73. MsgLogId: util.Int64All(v["msg_log_id"]),
  74. })
  75. }
  76. }
  77. }
  78. data.Count = count
  79. if this.PageSize == 5 {
  80. redisData := map[string]interface{}{
  81. "count": count,
  82. "data": data.Data,
  83. }
  84. entity.SetData(this.UserId, redisData, entity.SurvivalTime)
  85. }
  86. if err != nil {
  87. data.Code = 0
  88. data.Message = "查询失败"
  89. } else {
  90. data.Code = 1
  91. data.Message = "查询成功"
  92. }
  93. return data
  94. }
  95. func UserMsgList(this *message.UserMsgListReq) *message.UserMsgList {
  96. var (
  97. unread, count int64
  98. )
  99. cquery := map[string]interface{}{
  100. "receive_userid": this.UserId,
  101. "isdel": 1,
  102. "appid": this.Appid,
  103. }
  104. if this.MsgType > 0 {
  105. cquery["group_id"] = this.MsgType
  106. }
  107. if this.Read != -1 {
  108. cquery["isRead"] = this.Read
  109. }
  110. data := new(message.UserMsgList)
  111. //获取栏目下的数据
  112. sData := make(map[string][]*message.Messages)
  113. t := time.Now()
  114. if this.IsColumnNewMsg && this.SortSize > 0 {
  115. sortData := entity.Mysql.SelectBySql(fmt.Sprintf(`SELECT * FROM (
  116. SELECT *, ROW_NUMBER() OVER (PARTITION BY group_id, receive_userid ORDER BY createtime DESC) AS row_num
  117. FROM message
  118. WHERE receive_userid = '%s' and isdel = 1 and appid = %s
  119. ) AS message_ranked
  120. WHERE row_num <=%d;`, this.UserId, this.Appid, this.SortSize))
  121. log.Println("消息列表耗时1:", time.Since(t))
  122. if sortData != nil {
  123. for _, v := range *sortData {
  124. _id := util.Int64All(v["id"])
  125. id := strconv.FormatInt(_id, 10)
  126. var msg = message.Messages{
  127. Id: id,
  128. Appid: common.InterfaceToStr(v["appId"]),
  129. ReceiveUserId: common.InterfaceToStr(v["receive_userid"]),
  130. ReceiveName: common.InterfaceToStr(v["receive_name"]),
  131. SendUserId: common.InterfaceToStr(v["send_userid"]),
  132. SendName: common.InterfaceToStr(v["send_name"]),
  133. Createtime: common.InterfaceToStr(v["createtime"]),
  134. Title: common.InterfaceToStr(v["title"]),
  135. MsgType: int64(util.IntAll(v["group_id"])),
  136. Link: common.InterfaceToStr(v["link"]),
  137. CiteId: util.Int64All(v["cite_id"]),
  138. Content: common.InterfaceToStr(v["content"]),
  139. IsRead: util.Int64All(v["isRead"]),
  140. MsgLogId: util.Int64All(v["msg_log_id"]),
  141. }
  142. if sData[common.InterfaceToStr(v["group_id"])] == nil {
  143. sData[common.InterfaceToStr(v["group_id"])] = []*message.Messages{&msg}
  144. } else {
  145. sData[common.InterfaceToStr(v["group_id"])] = append(sData[common.InterfaceToStr(v["group_id"])], &msg)
  146. }
  147. }
  148. }
  149. }
  150. //消息栏目下的最新消息
  151. var columnData []*message.AllSortData
  152. var msgTypes []string
  153. for _, v := range entity.MessageColumn {
  154. if common.IntAll(v["group_id"]) > 0 {
  155. msgTypes = append(msgTypes, fmt.Sprintf(`"%s"`, common.InterfaceToStr(v["group_id"])))
  156. }
  157. }
  158. if this.IsColumn {
  159. columnUnread := make(map[string]int64)
  160. 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)
  161. log.Println("消息列表耗时2:", time.Since(t))
  162. if query != nil && len(*query) > 0 {
  163. for _, v := range *query {
  164. columnUnread[common.InterfaceToStr(v["group_id"])] = common.Int64All(v["count"])
  165. }
  166. }
  167. for _, v := range entity.MessageColumn {
  168. var column message.AllSortData
  169. column.Name = common.InterfaceToStr(v["name"])
  170. column.Img = fmt.Sprintf("/common-module/msgCenter/%s.png", common.InterfaceToStr(v["img"]))
  171. column.MsgType = common.Int64All(v["group_id"])
  172. if column.Name == "私信" {
  173. column.UnreadMessages = unreadMsg(this)
  174. } else {
  175. //消息未读数
  176. msgType := common.InterfaceToStr(v["group_id"])
  177. column.UnreadMessages = columnUnread[msgType]
  178. column.Data = sData[msgType]
  179. }
  180. unread += column.UnreadMessages
  181. columnData = append(columnData, &column)
  182. }
  183. }
  184. data.SortData = columnData
  185. count = entity.Mysql.Count("message", cquery)
  186. if this.IsMsgList {
  187. if count > 0 {
  188. if this.OffSet <= 0 {
  189. this.OffSet = 1
  190. }
  191. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  192. log.Println("消息列表耗时3:", time.Since(t))
  193. if res != nil && len(*res) > 0 {
  194. for _, v := range *res {
  195. _id := util.Int64All(v["id"])
  196. id := strconv.FormatInt(_id, 10)
  197. data.Data = append(data.Data, &message.Messages{
  198. Id: id,
  199. Appid: common.InterfaceToStr(v["appId"]),
  200. ReceiveUserId: common.InterfaceToStr(v["receive_userid"]),
  201. ReceiveName: common.InterfaceToStr(v["receive_name"]),
  202. SendUserId: common.InterfaceToStr(v["send_userid"]),
  203. SendName: common.InterfaceToStr(v["send_name"]),
  204. Createtime: common.InterfaceToStr(v["createtime"]),
  205. Title: common.InterfaceToStr(v["title"]),
  206. MsgType: int64(util.IntAll(v["group_id"])),
  207. Link: common.InterfaceToStr(v["link"]),
  208. CiteId: util.Int64All(v["cite_id"]),
  209. Content: common.InterfaceToStr(v["content"]),
  210. IsRead: util.Int64All(v["isRead"]),
  211. MsgLogId: util.Int64All(v["msg_log_id"]),
  212. })
  213. }
  214. }
  215. }
  216. }
  217. data.Count = count
  218. if !this.IsColumn && this.Read == 0 {
  219. unread = count
  220. if this.IsContainLetter { //是否需要统计私信未读数
  221. unread += unreadMsg(this)
  222. }
  223. }
  224. data.Unread = unread
  225. return data
  226. }
  227. func unreadMsg(this *message.UserMsgListReq) int64 {
  228. if this.PositionId <= 0 {
  229. return 0
  230. }
  231. querySql := fmt.Sprintf("SELECT b.*,(SELECT SUM( a.unread) FROM %s a "+
  232. "LEFT JOIN %s b ON a.message_id = b.id "+
  233. "WHERE a.unread > 0 "+
  234. "AND ( a.my_position_id = %d OR a.user_id = %d )) AS unread "+
  235. "FROM %s a "+
  236. "LEFT JOIN %s b ON a.message_id = b.id "+
  237. "WHERE a.unread > 0 "+
  238. "AND ( a.my_position_id = %d OR a.user_id = %d ) "+
  239. "ORDER BY a.TIMESTAMP DESC LIMIT 0,1", "socialize_summary", "socialize_message", this.PositionId, this.NewUserId,
  240. "socialize_summary", "socialize_message", this.PositionId, this.NewUserId)
  241. log.Println("查询sql", querySql)
  242. msgUnread := entity.BaseMysql.SelectBySql(querySql)
  243. if msgUnread != nil && len(*msgUnread) > 0 {
  244. return common.Int64All((*msgUnread)[0]["unread"])
  245. }
  246. return 0
  247. }
  248. func UserUnreadMsgList(this *message.UserUnreadMsgListReq) (int64, []*message.Messages) {
  249. count := 0
  250. data := []*message.Messages{}
  251. types := entity.Mysql.Find("message_group", map[string]interface{}{}, `"group_id"`, "", -1, -1)
  252. if types != nil && len(*types) > 0 {
  253. for _, v := range *types {
  254. key := fmt.Sprintf(MsgCountKey, this.UserId, util.IntAll(v["group_id"]))
  255. if exists, _ := redis.Exists(redisModule, key); exists {
  256. count += redis.GetInt(redisModule, key)
  257. }
  258. }
  259. }
  260. if this.IsNeedData == 1 && count > 0 {
  261. query := map[string]interface{}{
  262. "receive_userid": this.UserId,
  263. "isdel": 1,
  264. "appid": this.Appid,
  265. "isRead": 0,
  266. }
  267. log.Println(query)
  268. res := entity.Mysql.Find("message", query, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  269. if res != nil && len(*res) > 0 {
  270. for _, val := range *res {
  271. _id := util.Int64All(val["id"])
  272. id := strconv.FormatInt(_id, 10)
  273. links4 := common.InterfaceToStr(val["link"])
  274. link4, androidUrl4, iosUrl4, weChatUrl4 := util.LinkSplit(links4)
  275. url := map[string]string{
  276. "androidUrl": androidUrl4,
  277. "iosUrl": iosUrl4,
  278. "weChatUrl": weChatUrl4,
  279. }
  280. data = append(data, &message.Messages{
  281. Id: id,
  282. Appid: common.InterfaceToStr(val["appid"]),
  283. ReceiveUserId: common.InterfaceToStr(val["receive_userid"]),
  284. ReceiveName: common.InterfaceToStr(val["receive_name"]),
  285. SendUserId: common.InterfaceToStr(val["send_userid"]),
  286. SendName: common.InterfaceToStr(val["send_name"]),
  287. Createtime: common.InterfaceToStr(val["createtime"]),
  288. Title: common.InterfaceToStr(val["title"]),
  289. MsgType: common.Int64All(val["group_id"]),
  290. Link: link4,
  291. CiteId: common.Int64All(val["cite_id"]),
  292. Content: common.InterfaceToStr(val["content"]),
  293. IsRead: common.Int64All(val["isRead"]),
  294. MsgLogId: common.Int64All(val["msg_log_id"]),
  295. Url: url,
  296. })
  297. }
  298. }
  299. }
  300. return util.Int64All(count), data
  301. }
  302. func MessageGetLast(this *message.UserMsgListReq) *message.Messages {
  303. query := map[string]interface{}{
  304. "receive_userid": this.UserId,
  305. "isdel": 1,
  306. "appid": this.Appid,
  307. "isRead": 0,
  308. "group_id": 1,
  309. }
  310. lastMsg := entity.Mysql.FindOne("message", query, "", "createtime desc")
  311. if lastMsg != nil && len(*lastMsg) > 0 {
  312. _id := util.Int64All((*lastMsg)["id"])
  313. id := strconv.FormatInt(_id, 10)
  314. msg := message.Messages{
  315. Id: id,
  316. Appid: common.InterfaceToStr((*lastMsg)["appid"]),
  317. ReceiveUserId: common.InterfaceToStr((*lastMsg)["receive_userid"]),
  318. ReceiveName: common.InterfaceToStr((*lastMsg)["receive_name"]),
  319. SendUserId: common.InterfaceToStr((*lastMsg)["send_userid"]),
  320. SendName: common.InterfaceToStr((*lastMsg)["send_name"]),
  321. Createtime: common.InterfaceToStr((*lastMsg)["createtime"]),
  322. Title: common.InterfaceToStr((*lastMsg)["title"]),
  323. MsgType: common.Int64All((*lastMsg)["group_id"]),
  324. Link: common.InterfaceToStr((*lastMsg)["link"]),
  325. CiteId: common.Int64All((*lastMsg)["cite_id"]),
  326. Content: common.InterfaceToStr((*lastMsg)["content"]),
  327. IsRead: common.Int64All((*lastMsg)["isRead"]),
  328. MsgLogId: common.Int64All((*lastMsg)["msg_log_id"]),
  329. }
  330. return &msg
  331. }
  332. return nil
  333. }
  334. // MsgCountAdd 消息未读数量加1
  335. func MsgCountAdd(userId, appId string, msgType int64) bool {
  336. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  337. in := redis.Incr(redisModule, keyString)
  338. FindUserMsg(message.FindUserMsgReq{
  339. UserId: userId,
  340. Appid: appId,
  341. OffSet: 1,
  342. PageSize: 5,
  343. MsgType: -1,
  344. Read: 0,
  345. }, true)
  346. return in > 0
  347. }
  348. // MsgCountMinusOne 根据消息类型未读消息数量减1
  349. func MsgCountMinusOne(userId, appId string, msgType int64) bool {
  350. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  351. FindUserMsg(message.FindUserMsgReq{
  352. UserId: userId,
  353. Appid: appId,
  354. OffSet: 1,
  355. PageSize: 5,
  356. MsgType: -1,
  357. Read: 0,
  358. }, true)
  359. if redis.GetInt(redisModule, keyString) <= 0 {
  360. return redis.Put(redisModule, keyString, 0, -1)
  361. }
  362. in := redis.Decrby(redisModule, keyString, 1)
  363. return in > 0
  364. }
  365. // MsgCountZero 把该消息类型未读数量置0
  366. func MsgCountZero(userId, appId string, msgType int64) bool {
  367. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  368. fool := redis.Put(redisModule, keyString, 0, -1)
  369. FindUserMsg(message.FindUserMsgReq{
  370. UserId: userId,
  371. Appid: appId,
  372. OffSet: 1,
  373. PageSize: 5,
  374. MsgType: -1,
  375. Read: 0,
  376. }, true)
  377. return fool
  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. c := entity.Mysql.Count("conversation", map[string]interface{}{"receive_id": v, "send_id": this.SendUserId})
  410. 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,position_id,group_id) values ("%s",'%s','%s','%s','%s','%s','%s',%d,'%s',0,'%s',0,1,%d,%d,'%s',%d,?);`
  411. 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)
  412. if c <= 0 {
  413. 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');`
  414. sql1 = fmt.Sprintf(sql1, this.Appid, this.SendUserId, v, userName, this.SendUserId, this.SendName, time.Now().Format("2006-01-02 15:04:05"))
  415. ok := entity.Mysql.ExecTx("发送消息事务", func(tx *sql.Tx) bool {
  416. //插入会话表
  417. in1 := entity.Mysql.InsertBySqlByTx(tx, sql1)
  418. 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');`
  419. sql2 = fmt.Sprintf(sql2, this.Appid, v, this.SendUserId, this.SendName, v, userName, time.Now().Format("2006-01-02 15:04:05"))
  420. in2 := entity.Mysql.InsertBySqlByTx(tx, sql2)
  421. //插入消息表
  422. in3 := entity.Mysql.InsertBySqlByTx(tx, sql3, common.If(positionId != 0, positionId, nil))
  423. logx.Info(in1, in2, in3)
  424. return in1 > -1 && in2 > -1 && in3 > -1
  425. })
  426. logx.Info("执行事务是否成功:", ok)
  427. if ok {
  428. ok1 := MsgCountAdd(v, this.Appid, this.MsgType)
  429. if !ok1 {
  430. log.Println("存redis:", ok1, v)
  431. }
  432. }
  433. } else {
  434. in := entity.Mysql.InsertBySql(sql3, common.If(positionId != 0, positionId, nil))
  435. logx.Info("插入消息返回 in1 id:", in)
  436. if in > -1 {
  437. ok := MsgCountAdd(v, this.Appid, this.MsgType)
  438. if !ok {
  439. log.Println("存redis:", ok, v)
  440. }
  441. }
  442. }
  443. }(userIdArr[i], name, positionId)
  444. }
  445. wg.Wait()
  446. return 0, ""
  447. }