sendMsg.go 16 KB

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