sendMsg.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. // this.IsPc 是否pc端请求 this.MobileHome是否移动消息列表页
  96. func UserMsgList(this *message.UserMsgListReq) *message.UserMsgList {
  97. var (
  98. unread, count int64
  99. )
  100. cquery := map[string]interface{}{
  101. "receive_userid": this.UserId,
  102. "isdel": 1,
  103. "appid": this.Appid,
  104. }
  105. if this.MsgType > 0 {
  106. cquery["msg_type"] = this.MsgType
  107. }
  108. if this.Read != -1 {
  109. cquery["isRead"] = this.Read
  110. }
  111. data := new(message.UserMsgList)
  112. //获取栏目下的数据
  113. sData := make(map[string][]*message.Messages)
  114. if this.IsColumnNewMsg && this.SortSize > 0 {
  115. sortData := entity.Mysql.SelectBySql(fmt.Sprintf(`SELECT * FROM (
  116. SELECT *, ROW_NUMBER() OVER (PARTITION BY msg_type, 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. 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["msg_type"])),
  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["msg_type"])] == nil {
  142. sData[common.InterfaceToStr(v["msg_type"])] = []*message.Messages{&msg}
  143. } else {
  144. sData[common.InterfaceToStr(v["msg_type"])] = append(sData[common.InterfaceToStr(v["msg_type"])], &msg)
  145. }
  146. }
  147. }
  148. }
  149. //消息栏目下的最新消息
  150. var columnData []*message.AllSortData
  151. if this.IsColumn {
  152. var msgTypes []string
  153. columnUnread := make(map[string]int64)
  154. for _, v := range entity.MessageColumn {
  155. msgTypes = append(msgTypes, fmt.Sprintf(`"%s"`, common.InterfaceToStr(v["msg_type"])))
  156. }
  157. 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)
  158. if query != nil && len(*query) > 0 {
  159. for _, v := range *query {
  160. columnUnread[common.InterfaceToStr(v["msg_type"])] = common.Int64All(v["count"])
  161. }
  162. }
  163. for _, v := range entity.MessageColumn {
  164. var column message.AllSortData
  165. column.Name = common.InterfaceToStr(v["name"])
  166. column.Img = common.InterfaceToStr(v["img"])
  167. column.MsgType = common.Int64All(v["msg_type"])
  168. msgType := common.InterfaceToStr(v["msg_type"])
  169. //消息未读数
  170. column.UnreadMessages = columnUnread[msgType]
  171. unread += column.UnreadMessages
  172. column.Data = sData[msgType]
  173. columnData = append(columnData, &column)
  174. }
  175. }
  176. data.SortData = columnData
  177. count = entity.Mysql.Count("message", cquery)
  178. if this.IsMsgList {
  179. if count > 0 {
  180. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  181. if res != nil && len(*res) > 0 {
  182. for _, v := range *res {
  183. _id := util.Int64All(v["id"])
  184. id := strconv.FormatInt(_id, 10)
  185. data.Data = append(data.Data, &message.Messages{
  186. Id: id,
  187. Appid: common.InterfaceToStr(v["appId"]),
  188. ReceiveUserId: common.InterfaceToStr(v["receive_userid"]),
  189. ReceiveName: common.InterfaceToStr(v["receive_name"]),
  190. SendUserId: common.InterfaceToStr(v["send_userid"]),
  191. SendName: common.InterfaceToStr(v["send_name"]),
  192. Createtime: common.InterfaceToStr(v["createtime"]),
  193. Title: common.InterfaceToStr(v["title"]),
  194. MsgType: int64(util.IntAll(v["msg_type"])),
  195. Link: common.InterfaceToStr(v["link"]),
  196. CiteId: util.Int64All(v["cite_id"]),
  197. Content: common.InterfaceToStr(v["content"]),
  198. IsRead: util.Int64All(v["isRead"]),
  199. MsgLogId: util.Int64All(v["msg_log_id"]),
  200. })
  201. }
  202. }
  203. }
  204. }
  205. data.Count = count
  206. if !this.IsColumn && this.Read == 0 {
  207. unread = count
  208. }
  209. data.Unread = unread
  210. return data
  211. }
  212. func UserUnreadMsgList(this *message.UserUnreadMsgListReq) (int64, []*message.Messages) {
  213. var count int64
  214. var data []*message.Messages
  215. cquery := map[string]interface{}{
  216. "receive_userid": this.UserId,
  217. "isdel": 1,
  218. "appid": this.Appid,
  219. "isRead": 0,
  220. }
  221. log.Println(cquery)
  222. count = entity.Mysql.Count("message", cquery)
  223. if count > 0 {
  224. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  225. if res != nil && len(*res) > 0 {
  226. for _, val := range *res {
  227. _id := util.Int64All(val["id"])
  228. id := strconv.FormatInt(_id, 10)
  229. links4 := common.InterfaceToStr(val["link"])
  230. link4, androidUrl4, iosUrl4, weChatUrl4 := util.LinkSplit(links4)
  231. url := map[string]string{
  232. "androidUrl": androidUrl4,
  233. "iosUrl": iosUrl4,
  234. "weChatUrl": weChatUrl4,
  235. }
  236. data = append(data, &message.Messages{
  237. Id: id,
  238. Appid: common.InterfaceToStr(val["appid"]),
  239. ReceiveUserId: common.InterfaceToStr(val["receive_userid"]),
  240. ReceiveName: common.InterfaceToStr(val["receive_name"]),
  241. SendUserId: common.InterfaceToStr(val["send_userid"]),
  242. SendName: common.InterfaceToStr(val["send_name"]),
  243. Createtime: common.InterfaceToStr(val["createtime"]),
  244. Title: common.InterfaceToStr(val["title"]),
  245. MsgType: common.Int64All(val["msg_type"]),
  246. Link: link4,
  247. CiteId: common.Int64All(val["cite_id"]),
  248. Content: common.InterfaceToStr(val["content"]),
  249. IsRead: common.Int64All(val["isRead"]),
  250. MsgLogId: common.Int64All(val["msg_log_id"]),
  251. Url: url,
  252. })
  253. }
  254. }
  255. }
  256. return count, data
  257. }
  258. func MessageGetLast(this *message.UserMsgListReq) *message.Messages {
  259. if this.IsColumn {
  260. query := map[string]interface{}{
  261. "receive_userid": this.UserId,
  262. "isdel": 1,
  263. "appid": this.Appid,
  264. "isRead": 0,
  265. "msg_type": 1,
  266. }
  267. lastMsg := entity.Mysql.FindOne("message", query, "", "createtime desc")
  268. if lastMsg != nil && len(*lastMsg) > 0 {
  269. _id := util.Int64All((*lastMsg)["id"])
  270. id := strconv.FormatInt(_id, 10)
  271. msg := message.Messages{
  272. Id: id,
  273. Appid: common.InterfaceToStr((*lastMsg)["appid"]),
  274. ReceiveUserId: common.InterfaceToStr((*lastMsg)["receive_userid"]),
  275. ReceiveName: common.InterfaceToStr((*lastMsg)["receive_name"]),
  276. SendUserId: common.InterfaceToStr((*lastMsg)["send_userid"]),
  277. SendName: common.InterfaceToStr((*lastMsg)["send_name"]),
  278. Createtime: common.InterfaceToStr((*lastMsg)["createtime"]),
  279. Title: common.InterfaceToStr((*lastMsg)["title"]),
  280. MsgType: common.Int64All((*lastMsg)["msg_type"]),
  281. Link: common.InterfaceToStr((*lastMsg)["link"]),
  282. CiteId: common.Int64All((*lastMsg)["cite_id"]),
  283. Content: common.InterfaceToStr((*lastMsg)["content"]),
  284. IsRead: common.Int64All((*lastMsg)["isRead"]),
  285. MsgLogId: common.Int64All((*lastMsg)["msg_log_id"]),
  286. }
  287. return &msg
  288. }
  289. }
  290. return nil
  291. }
  292. // 指定分类未读消息合计
  293. func ClassCountUnread(msgType int, userId string, appId string) (int64, string, int64) {
  294. query := map[string]interface{}{
  295. "msg_type": msgType,
  296. "receive_userid": userId,
  297. "isdel": 1,
  298. "appid": appId,
  299. "isRead": 0,
  300. }
  301. count := entity.Mysql.Count("message", query)
  302. return 1, "查询指定分类未读消息成功", count
  303. }
  304. // MsgCountAdd 消息未读数量加1
  305. func MsgCountAdd(userId, msgType, appId string) bool {
  306. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  307. in := redis.Incr(redisModule, keyString)
  308. FindUserMsg(message.FindUserMsgReq{
  309. UserId: userId,
  310. Appid: appId,
  311. OffSet: 1,
  312. PageSize: 5,
  313. MsgType: -1,
  314. Read: 0,
  315. }, true)
  316. return in > 0
  317. }
  318. // MsgCountMinusOne 根据消息类型未读消息数量减1
  319. func MsgCountMinusOne(userId, msgType, appId string) bool {
  320. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  321. FindUserMsg(message.FindUserMsgReq{
  322. UserId: userId,
  323. Appid: appId,
  324. OffSet: 1,
  325. PageSize: 5,
  326. MsgType: -1,
  327. Read: 0,
  328. }, true)
  329. if redis.GetInt(redisModule, keyString) <= 0 {
  330. return redis.Put(redisModule, keyString, 0, -1)
  331. }
  332. in := redis.Decrby(redisModule, keyString, 1)
  333. return in > 0
  334. }
  335. // MsgCountZero 把该消息类型未读数量置0
  336. func MsgCountZero(userId, msgType, appId string) bool {
  337. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  338. fool := redis.Put(redisModule, keyString, 0, -1)
  339. FindUserMsg(message.FindUserMsgReq{
  340. UserId: userId,
  341. Appid: appId,
  342. OffSet: 1,
  343. PageSize: 5,
  344. MsgType: -1,
  345. Read: 0,
  346. }, true)
  347. return fool
  348. }
  349. func MultSave(this message.MultipleSaveMsgReq) (int64, string) {
  350. userIdArr := strings.Split(this.UserIds, ",")
  351. userNameArr := strings.Split(this.UserNames, ",")
  352. positionIdArr := strings.Split(this.PositionIds, ",")
  353. if len(userIdArr) == 0 {
  354. return 0, "无效的用户id"
  355. }
  356. wg := &sync.WaitGroup{}
  357. for i := 0; i < len(userIdArr); i++ {
  358. if userIdArr[i] == "" {
  359. continue
  360. }
  361. name := userNameArr[i]
  362. wg.Add(1)
  363. entity.SaveConcurrencyChan <- 1
  364. var positionId int64
  365. if len(positionIdArr) == len(userIdArr) {
  366. positionId = common.Int64All(positionIdArr[i])
  367. }
  368. go func(v, userName string, positionId int64) {
  369. defer func() {
  370. <-entity.SaveConcurrencyChan
  371. wg.Done()
  372. }()
  373. //消息数组
  374. c := entity.Mysql.Count("conversation", map[string]interface{}{"receive_id": v, "send_id": this.SendUserId})
  375. 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',?);`
  376. 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)
  377. if c <= 0 {
  378. 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');`
  379. sql1 = fmt.Sprintf(sql1, this.Appid, this.SendUserId, v, userName, this.SendUserId, this.SendName, time.Now().Format("2006-01-02 15:04:05"))
  380. ok := entity.Mysql.ExecTx("发送消息事务", func(tx *sql.Tx) bool {
  381. //插入会话表
  382. in1 := entity.Mysql.InsertBySqlByTx(tx, sql1)
  383. 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');`
  384. sql2 = fmt.Sprintf(sql2, this.Appid, v, this.SendUserId, this.SendName, v, userName, time.Now().Format("2006-01-02 15:04:05"))
  385. in2 := entity.Mysql.InsertBySqlByTx(tx, sql2)
  386. //插入消息表
  387. in3 := entity.Mysql.InsertBySqlByTx(tx, sql3, common.If(positionId != 0, positionId, nil))
  388. logx.Info(in1, in2, in3)
  389. return in1 > -1 && in2 > -1 && in3 > -1
  390. })
  391. logx.Info("执行事务是否成功:", ok)
  392. if ok {
  393. ok1 := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)), this.Appid)
  394. if !ok1 {
  395. log.Println("存redis:", ok1, v)
  396. }
  397. }
  398. } else {
  399. in := entity.Mysql.InsertBySql(sql3, common.If(positionId != 0, positionId, nil))
  400. logx.Info("插入消息返回 in1 id:", in)
  401. if in > -1 {
  402. ok := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)), this.Appid)
  403. if !ok {
  404. log.Println("存redis:", ok, v)
  405. }
  406. }
  407. }
  408. }(userIdArr[i], name, positionId)
  409. }
  410. wg.Wait()
  411. return 0, ""
  412. }