sendMsg.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. /*
  22. var (
  23. UserLockMap = map[string]*sync.Mutex{}
  24. //MainLock = sync.Mutex{}
  25. )
  26. */
  27. func SendMsg(this message.SendMsgRequest) (int64, string) {
  28. r, err := entity.Mysql11.Query("select count(*) as c from conversation where receive_id = ? and send_id = ? ", this.ReceiveUserId, this.SendUserId)
  29. c := 0
  30. for r.Next() {
  31. err := r.Scan(&c)
  32. if err != nil {
  33. panic(err.Error())
  34. }
  35. }
  36. logx.Info("查询数量:", c)
  37. sql3 := `INSERT INTO message(appid,receive_userid,receive_name,send_userid,send_name,title,content,msg_type,link,cite_id,createtime,isRead,isdel)
  38. values ("%s",'%s','%s','%s','%s','%s','%s','%d','%s',0,'%s',0,1);`
  39. sql3 = fmt.Sprintf(sql3, this.Appid, this.ReceiveUserId, this.ReceiveName, this.SendUserId, this.SendName, this.Title, this.Content, this.MsgType, this.Link, time.Now().Format("2006-01-02 15:04:05"))
  40. if c < 1 {
  41. sql1 := `INSERT INTO conversation(appid,` + "`key`" + `,user_id,receive_id,receive_name,send_id,send_name,sort,createtime)
  42. values ('%s','','%s','%s','%s','%s','%s',0,'%s');`
  43. sql1 = fmt.Sprintf(sql1, this.Appid, this.SendUserId, this.ReceiveUserId, this.ReceiveName, this.SendUserId, this.SendName, time.Now().Format("2006-01-02 15:04:05"))
  44. ok := entity.Mysql.ExecTx("发送消息事务", func(tx *sql.Tx) bool {
  45. //插入会话表
  46. _, err := entity.Mysql11.Exec(sql1)
  47. sql2 := `INSERT INTO conversation(appid,` + "`key`" + `,user_id,receive_id,receive_name,send_id,send_name,sort,createtime)
  48. values ('%s','','%s','%s','%s','%s','%s',0,'%s');`
  49. sql2 = fmt.Sprintf(sql2, this.Appid, this.ReceiveUserId, this.SendUserId, this.SendName, this.ReceiveUserId, this.ReceiveName, time.Now().Format("2006-01-02 15:04:05"))
  50. _, err = entity.Mysql11.Exec(sql2)
  51. //插入消息表
  52. _, err = entity.Mysql11.Exec(sql3)
  53. if err != nil {
  54. return false
  55. }
  56. return true
  57. })
  58. if ok {
  59. return 1, "消息发送成功"
  60. }
  61. }
  62. _, err = entity.Mysql11.Exec(sql3)
  63. if err == nil {
  64. MsgCountAdd(this.ReceiveUserId, strconv.Itoa(int(this.MsgType)), this.Appid)
  65. return 1, "消息发送成功"
  66. }
  67. return 0, "消息发送失败"
  68. }
  69. func FindUserMsg(this message.FindUserMsgReq, isClean bool) message.FindUserMsgRes {
  70. var err error
  71. var count int64
  72. cquery := map[string]interface{}{
  73. "receive_userid": this.UserId,
  74. "isdel": 1,
  75. "appid": this.Appid,
  76. }
  77. if this.MsgType != -1 {
  78. cquery["msg_type"] = this.MsgType
  79. }
  80. if this.Read != -1 {
  81. cquery["isRead"] = this.Read
  82. }
  83. count = entity.Mysql.Count("message", cquery)
  84. data := message.FindUserMsgRes{}
  85. if this.PageSize == 5 {
  86. //从缓存里边取数据
  87. pc_a, err := entity.GetData(this.UserId)
  88. if err == nil && pc_a != nil {
  89. // 缓存有值
  90. if !isClean {
  91. data.Code = 1
  92. data.Message = "查询成功"
  93. data.Data = pc_a.Data
  94. data.Count = pc_a.Count
  95. return data
  96. }
  97. }
  98. }
  99. count = entity.Mysql.Count("message", cquery)
  100. if count > 0 {
  101. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  102. //log.Println("数据:", res)
  103. if res != nil && len(*res) > 0 {
  104. for _, v := range *res {
  105. _id := util.Int64All(v["id"])
  106. id := strconv.FormatInt(_id, 10)
  107. data.Data = append(data.Data, &message.Messages{
  108. Id: id,
  109. Appid: util.ObjToString(v["appId"]),
  110. ReceiveUserId: util.ObjToString(v["receive_userid"]),
  111. ReceiveName: util.ObjToString(v["receive_name"]),
  112. SendUserId: util.ObjToString(v["send_userid"]),
  113. SendName: util.ObjToString(v["send_name"]),
  114. Createtime: util.ObjToString(v["createtime"]),
  115. Title: util.ObjToString(v["title"]),
  116. MsgType: int64(util.IntAll(v["msg_type"])),
  117. Link: util.ObjToString(v["link"]),
  118. CiteId: util.Int64All(v["cite_id"]),
  119. Content: util.ObjToString(v["content"]),
  120. IsRead: util.Int64All(v["isRead"]),
  121. MsgLogId: util.Int64All(v["msg_log_id"]),
  122. })
  123. }
  124. }
  125. }
  126. data.Count = count
  127. if this.PageSize == 5 {
  128. redisData := map[string]interface{}{
  129. "count": count,
  130. "data": data.Data,
  131. }
  132. entity.SetData(this.UserId, redisData, entity.SurvivalTime)
  133. }
  134. if err != nil {
  135. data.Code = 0
  136. data.Message = "查询失败"
  137. } else {
  138. data.Code = 1
  139. data.Message = "查询成功"
  140. }
  141. return data
  142. }
  143. // this.IsPc 是否pc端请求 this.MobileHome是否移动消息列表页
  144. func UserMsgList(this *message.UserMsgListReq) *message.UserMsgList {
  145. var count int64
  146. cquery := map[string]interface{}{
  147. "receive_userid": this.UserId,
  148. "isdel": 1,
  149. "appid": this.Appid,
  150. }
  151. if this.MsgType > 0 {
  152. cquery["msg_type"] = this.MsgType
  153. }
  154. if this.Read != -1 {
  155. cquery["isRead"] = this.Read
  156. }
  157. data := new(message.UserMsgList)
  158. //获取栏目下的数据
  159. sData := make(map[string][]*message.Messages)
  160. if this.MobileHome {
  161. if this.SortSize > 0 {
  162. sortData := entity.Mysql.SelectBySql(fmt.Sprintf(`SELECT * FROM (
  163. SELECT *, ROW_NUMBER() OVER (PARTITION BY msg_type, receive_userid ORDER BY createtime DESC) AS row_num
  164. FROM message
  165. WHERE receive_userid = '%s' and isdel = 1 and appid = %s
  166. ) AS message_ranked
  167. WHERE row_num <=%d;`, this.UserId, this.Appid, this.SortSize))
  168. if sortData != nil {
  169. for _, v := range *sortData {
  170. _id := util.Int64All(v["id"])
  171. id := strconv.FormatInt(_id, 10)
  172. var msg = message.Messages{
  173. Id: id,
  174. Appid: common.InterfaceToStr(v["appId"]),
  175. ReceiveUserId: common.InterfaceToStr(v["receive_userid"]),
  176. ReceiveName: common.InterfaceToStr(v["receive_name"]),
  177. SendUserId: common.InterfaceToStr(v["send_userid"]),
  178. SendName: common.InterfaceToStr(v["send_name"]),
  179. Createtime: common.InterfaceToStr(v["createtime"]),
  180. Title: common.InterfaceToStr(v["title"]),
  181. MsgType: int64(util.IntAll(v["msg_type"])),
  182. Link: common.InterfaceToStr(v["link"]),
  183. CiteId: util.Int64All(v["cite_id"]),
  184. Content: common.InterfaceToStr(v["content"]),
  185. IsRead: util.Int64All(v["isRead"]),
  186. MsgLogId: util.Int64All(v["msg_log_id"]),
  187. }
  188. if sData[common.InterfaceToStr(v["msg_type"])] == nil {
  189. sData[common.InterfaceToStr(v["msg_type"])] = []*message.Messages{&msg}
  190. } else {
  191. sData[common.InterfaceToStr(v["msg_type"])] = append(sData[common.InterfaceToStr(v["msg_type"])], &msg)
  192. }
  193. }
  194. }
  195. }
  196. }
  197. //消息栏目下的最新消息
  198. var columnData []*message.AllSortData
  199. if this.IsPc || this.MobileHome {
  200. for _, v := range entity.MessageColumn {
  201. var column message.AllSortData
  202. column.Name = common.InterfaceToStr(v["name"])
  203. column.Img = common.InterfaceToStr(v["img"])
  204. column.MsgType = common.Int64All(v["msg_type"])
  205. //消息未读数
  206. sQuery := map[string]interface{}{
  207. "receive_userid": this.UserId,
  208. "isdel": 1,
  209. "appid": this.Appid,
  210. "msg_type": column.MsgType,
  211. "isRead": 0,
  212. }
  213. column.UnreadMessages = entity.Mysql.Count("message", sQuery)
  214. column.Data = sData[common.InterfaceToStr(v["msg_type"])]
  215. columnData = append(columnData, &column)
  216. }
  217. }
  218. if this.IsPc || !this.MobileHome {
  219. data.SortData = columnData
  220. count = entity.Mysql.Count("message", cquery)
  221. if count > 0 {
  222. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  223. if res != nil && len(*res) > 0 {
  224. for _, v := range *res {
  225. _id := util.Int64All(v["id"])
  226. id := strconv.FormatInt(_id, 10)
  227. data.Data = append(data.Data, &message.Messages{
  228. Id: id,
  229. Appid: common.InterfaceToStr(v["appId"]),
  230. ReceiveUserId: common.InterfaceToStr(v["receive_userid"]),
  231. ReceiveName: common.InterfaceToStr(v["receive_name"]),
  232. SendUserId: common.InterfaceToStr(v["send_userid"]),
  233. SendName: common.InterfaceToStr(v["send_name"]),
  234. Createtime: common.InterfaceToStr(v["createtime"]),
  235. Title: common.InterfaceToStr(v["title"]),
  236. MsgType: int64(util.IntAll(v["msg_type"])),
  237. Link: common.InterfaceToStr(v["link"]),
  238. CiteId: util.Int64All(v["cite_id"]),
  239. Content: common.InterfaceToStr(v["content"]),
  240. IsRead: util.Int64All(v["isRead"]),
  241. MsgLogId: util.Int64All(v["msg_log_id"]),
  242. })
  243. }
  244. }
  245. }
  246. data.Count = count
  247. }
  248. return data
  249. }
  250. func MessageGetLast(this *message.UserMsgListReq) *message.Messages {
  251. if this.IsPc || this.MobileHome {
  252. query := map[string]interface{}{
  253. "receive_userid": this.UserId,
  254. "isdel": 1,
  255. "appid": this.Appid,
  256. "isRead": 0,
  257. "msg_type": 1,
  258. }
  259. lastMsg := entity.Mysql.FindOne("message", query, "", "createtime desc")
  260. if lastMsg != nil && len(*lastMsg) > 0 {
  261. _id := util.Int64All((*lastMsg)["id"])
  262. id := strconv.FormatInt(_id, 10)
  263. msg := message.Messages{
  264. Id: id,
  265. Appid: common.InterfaceToStr((*lastMsg)["appid"]),
  266. ReceiveUserId: common.InterfaceToStr((*lastMsg)["receive_userid"]),
  267. ReceiveName: common.InterfaceToStr((*lastMsg)["receive_name"]),
  268. SendUserId: common.InterfaceToStr((*lastMsg)["send_userid"]),
  269. SendName: common.InterfaceToStr((*lastMsg)["send_name"]),
  270. Createtime: common.InterfaceToStr((*lastMsg)["createtime"]),
  271. Title: common.InterfaceToStr((*lastMsg)["title"]),
  272. MsgType: common.Int64All((*lastMsg)["msg_type"]),
  273. Link: common.InterfaceToStr((*lastMsg)["link"]),
  274. CiteId: common.Int64All((*lastMsg)["cite_id"]),
  275. Content: common.InterfaceToStr((*lastMsg)["content"]),
  276. IsRead: common.Int64All((*lastMsg)["isRead"]),
  277. MsgLogId: common.Int64All((*lastMsg)["msg_log_id"]),
  278. }
  279. return &msg
  280. }
  281. }
  282. return nil
  283. }
  284. // 指定分类未读消息合计
  285. func ClassCountUnread(msgType int, userId string, appId string) (int64, string, int64) {
  286. query := map[string]interface{}{
  287. "msg_type": msgType,
  288. "receive_userid": userId,
  289. "isdel": 1,
  290. "appid": appId,
  291. "isRead": 0,
  292. }
  293. count := entity.Mysql.Count("message", query)
  294. return 1, "查询指定分类未读消息成功", count
  295. }
  296. // MsgCountAdd 消息未读数量加1
  297. func MsgCountAdd(userId, msgType, appId string) bool {
  298. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  299. in := redis.Incr(redisModule, keyString)
  300. FindUserMsg(message.FindUserMsgReq{
  301. UserId: userId,
  302. Appid: appId,
  303. OffSet: 1,
  304. PageSize: 5,
  305. MsgType: -1,
  306. Read: 0,
  307. }, true)
  308. return in > 0
  309. }
  310. // MsgCountMinusOne 根据消息类型未读消息数量减1
  311. func MsgCountMinusOne(userId, msgType, appId string) bool {
  312. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  313. FindUserMsg(message.FindUserMsgReq{
  314. UserId: userId,
  315. Appid: appId,
  316. OffSet: 1,
  317. PageSize: 5,
  318. MsgType: -1,
  319. Read: 0,
  320. }, true)
  321. if redis.GetInt(redisModule, keyString) <= 0 {
  322. return redis.Put(redisModule, keyString, 0, -1)
  323. }
  324. in := redis.Decrby(redisModule, keyString, 1)
  325. return in > 0
  326. }
  327. // MsgCountZero 把该消息类型未读数量置0
  328. func MsgCountZero(userId, msgType, appId string) bool {
  329. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  330. fool := redis.Put(redisModule, keyString, 0, -1)
  331. FindUserMsg(message.FindUserMsgReq{
  332. UserId: userId,
  333. Appid: appId,
  334. OffSet: 1,
  335. PageSize: 5,
  336. MsgType: -1,
  337. Read: 0,
  338. }, true)
  339. return fool
  340. }
  341. func MultSave(this message.MultipleSaveMsgReq) (int64, string) {
  342. userIdArr := strings.Split(this.UserIds, ",")
  343. userNameArr := strings.Split(this.UserNames, ",")
  344. positionIdArr := strings.Split(this.PositionIds, ",")
  345. if len(userIdArr) == 0 {
  346. return 0, "无效的用户id"
  347. }
  348. wg := &sync.WaitGroup{}
  349. for i := 0; i < len(userIdArr); i++ {
  350. if userIdArr[i] == "" {
  351. continue
  352. }
  353. name := userNameArr[i]
  354. wg.Add(1)
  355. entity.SaveConcurrencyChan <- 1
  356. var positionId int64
  357. if len(positionIdArr) == len(userIdArr) {
  358. positionId = common.Int64All(positionIdArr[i])
  359. }
  360. go func(v, userName string, positionId int64) {
  361. defer func() {
  362. <-entity.SaveConcurrencyChan
  363. wg.Done()
  364. }()
  365. //消息数组
  366. c := entity.Mysql.Count("conversation", map[string]interface{}{"receive_id": v, "send_id": this.SendUserId})
  367. 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',?);`
  368. 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)
  369. if c <= 0 {
  370. 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');`
  371. sql1 = fmt.Sprintf(sql1, this.Appid, this.SendUserId, v, userName, this.SendUserId, this.SendName, time.Now().Format("2006-01-02 15:04:05"))
  372. ok := entity.Mysql.ExecTx("发送消息事务", func(tx *sql.Tx) bool {
  373. //插入会话表
  374. in1 := entity.Mysql.InsertBySqlByTx(tx, sql1)
  375. 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');`
  376. sql2 = fmt.Sprintf(sql2, this.Appid, v, this.SendUserId, this.SendName, v, userName, time.Now().Format("2006-01-02 15:04:05"))
  377. in2 := entity.Mysql.InsertBySqlByTx(tx, sql2)
  378. //插入消息表
  379. in3 := entity.Mysql.InsertBySqlByTx(tx, sql3, common.If(positionId != 0, positionId, nil))
  380. logx.Info(in1, in2, in3)
  381. return in1 > -1 && in2 > -1 && in3 > -1
  382. })
  383. logx.Info("执行事务是否成功:", ok)
  384. if ok {
  385. ok1 := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)), this.Appid)
  386. if !ok1 {
  387. log.Println("存redis:", ok1, v)
  388. }
  389. }
  390. } else {
  391. in := entity.Mysql.InsertBySql(sql3, common.If(positionId != 0, positionId, nil))
  392. logx.Info("插入消息返回 in1 id:", in)
  393. if in > -1 {
  394. ok := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)), this.Appid)
  395. if !ok {
  396. log.Println("存redis:", ok, v)
  397. }
  398. }
  399. }
  400. }(userIdArr[i], name, positionId)
  401. }
  402. wg.Wait()
  403. return 0, ""
  404. }