sendMsg.go 16 KB

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