sendMsg.go 16 KB

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