sendMsg.go 17 KB

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