sendMsg.go 14 KB

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