sendMsg.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 UserUnreadMsgList(this *message.UserUnreadMsgListReq) (int64, []*message.Messages) {
  251. var count int64
  252. var data []*message.Messages
  253. cquery := map[string]interface{}{
  254. "receive_userid": this.UserId,
  255. "isdel": 1,
  256. "appid": this.Appid,
  257. "isRead": 0,
  258. }
  259. log.Println(cquery)
  260. count = entity.Mysql.Count("message", cquery)
  261. if count > 0 {
  262. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  263. if res != nil && len(*res) > 0 {
  264. for _, val := range *res {
  265. _id := util.Int64All(val["id"])
  266. id := strconv.FormatInt(_id, 10)
  267. links4 := common.InterfaceToStr(val["link"])
  268. link4, androidUrl4, iosUrl4, weChatUrl4 := util.LinkSplit(links4)
  269. url := map[string]string{
  270. "androidUrl": androidUrl4,
  271. "iosUrl": iosUrl4,
  272. "weChatUrl": weChatUrl4,
  273. }
  274. data = append(data, &message.Messages{
  275. Id: id,
  276. Appid: common.InterfaceToStr(val["appid"]),
  277. ReceiveUserId: common.InterfaceToStr(val["receive_userid"]),
  278. ReceiveName: common.InterfaceToStr(val["receive_name"]),
  279. SendUserId: common.InterfaceToStr(val["send_userid"]),
  280. SendName: common.InterfaceToStr(val["send_name"]),
  281. Createtime: common.InterfaceToStr(val["createtime"]),
  282. Title: common.InterfaceToStr(val["title"]),
  283. MsgType: common.Int64All(val["msg_type"]),
  284. Link: link4,
  285. CiteId: common.Int64All(val["cite_id"]),
  286. Content: common.InterfaceToStr(val["content"]),
  287. IsRead: common.Int64All(val["isRead"]),
  288. MsgLogId: common.Int64All(val["msg_log_id"]),
  289. Url: url,
  290. })
  291. }
  292. }
  293. }
  294. return count, data
  295. }
  296. func MessageGetLast(this *message.UserMsgListReq) *message.Messages {
  297. if this.IsPc || this.MobileHome {
  298. query := map[string]interface{}{
  299. "receive_userid": this.UserId,
  300. "isdel": 1,
  301. "appid": this.Appid,
  302. "isRead": 0,
  303. "msg_type": 1,
  304. }
  305. lastMsg := entity.Mysql.FindOne("message", query, "", "createtime desc")
  306. if lastMsg != nil && len(*lastMsg) > 0 {
  307. _id := util.Int64All((*lastMsg)["id"])
  308. id := strconv.FormatInt(_id, 10)
  309. msg := message.Messages{
  310. Id: id,
  311. Appid: common.InterfaceToStr((*lastMsg)["appid"]),
  312. ReceiveUserId: common.InterfaceToStr((*lastMsg)["receive_userid"]),
  313. ReceiveName: common.InterfaceToStr((*lastMsg)["receive_name"]),
  314. SendUserId: common.InterfaceToStr((*lastMsg)["send_userid"]),
  315. SendName: common.InterfaceToStr((*lastMsg)["send_name"]),
  316. Createtime: common.InterfaceToStr((*lastMsg)["createtime"]),
  317. Title: common.InterfaceToStr((*lastMsg)["title"]),
  318. MsgType: common.Int64All((*lastMsg)["msg_type"]),
  319. Link: common.InterfaceToStr((*lastMsg)["link"]),
  320. CiteId: common.Int64All((*lastMsg)["cite_id"]),
  321. Content: common.InterfaceToStr((*lastMsg)["content"]),
  322. IsRead: common.Int64All((*lastMsg)["isRead"]),
  323. MsgLogId: common.Int64All((*lastMsg)["msg_log_id"]),
  324. }
  325. return &msg
  326. }
  327. }
  328. return nil
  329. }
  330. // 指定分类未读消息合计
  331. func ClassCountUnread(msgType int, userId string, appId string) (int64, string, int64) {
  332. query := map[string]interface{}{
  333. "msg_type": msgType,
  334. "receive_userid": userId,
  335. "isdel": 1,
  336. "appid": appId,
  337. "isRead": 0,
  338. }
  339. count := entity.Mysql.Count("message", query)
  340. return 1, "查询指定分类未读消息成功", count
  341. }
  342. // MsgCountAdd 消息未读数量加1
  343. func MsgCountAdd(userId, msgType, appId string) bool {
  344. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  345. in := redis.Incr(redisModule, keyString)
  346. FindUserMsg(message.FindUserMsgReq{
  347. UserId: userId,
  348. Appid: appId,
  349. OffSet: 1,
  350. PageSize: 5,
  351. MsgType: -1,
  352. Read: 0,
  353. }, true)
  354. return in > 0
  355. }
  356. // MsgCountMinusOne 根据消息类型未读消息数量减1
  357. func MsgCountMinusOne(userId, msgType, appId string) bool {
  358. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  359. FindUserMsg(message.FindUserMsgReq{
  360. UserId: userId,
  361. Appid: appId,
  362. OffSet: 1,
  363. PageSize: 5,
  364. MsgType: -1,
  365. Read: 0,
  366. }, true)
  367. if redis.GetInt(redisModule, keyString) <= 0 {
  368. return redis.Put(redisModule, keyString, 0, -1)
  369. }
  370. in := redis.Decrby(redisModule, keyString, 1)
  371. return in > 0
  372. }
  373. // MsgCountZero 把该消息类型未读数量置0
  374. func MsgCountZero(userId, msgType, appId string) bool {
  375. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  376. fool := redis.Put(redisModule, keyString, 0, -1)
  377. FindUserMsg(message.FindUserMsgReq{
  378. UserId: userId,
  379. Appid: appId,
  380. OffSet: 1,
  381. PageSize: 5,
  382. MsgType: -1,
  383. Read: 0,
  384. }, true)
  385. return fool
  386. }
  387. func MultSave(this message.MultipleSaveMsgReq) (int64, string) {
  388. userIdArr := strings.Split(this.UserIds, ",")
  389. userNameArr := strings.Split(this.UserNames, ",")
  390. positionIdArr := strings.Split(this.PositionIds, ",")
  391. if len(userIdArr) == 0 {
  392. return 0, "无效的用户id"
  393. }
  394. wg := &sync.WaitGroup{}
  395. for i := 0; i < len(userIdArr); i++ {
  396. if userIdArr[i] == "" {
  397. continue
  398. }
  399. name := userNameArr[i]
  400. wg.Add(1)
  401. entity.SaveConcurrencyChan <- 1
  402. var positionId int64
  403. if len(positionIdArr) == len(userIdArr) {
  404. positionId = common.Int64All(positionIdArr[i])
  405. }
  406. go func(v, userName string, positionId int64) {
  407. defer func() {
  408. <-entity.SaveConcurrencyChan
  409. wg.Done()
  410. }()
  411. //消息数组
  412. c := entity.Mysql.Count("conversation", map[string]interface{}{"receive_id": v, "send_id": this.SendUserId})
  413. 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',?);`
  414. 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)
  415. if c <= 0 {
  416. 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');`
  417. sql1 = fmt.Sprintf(sql1, this.Appid, this.SendUserId, v, userName, this.SendUserId, this.SendName, time.Now().Format("2006-01-02 15:04:05"))
  418. ok := entity.Mysql.ExecTx("发送消息事务", func(tx *sql.Tx) bool {
  419. //插入会话表
  420. in1 := entity.Mysql.InsertBySqlByTx(tx, sql1)
  421. 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');`
  422. sql2 = fmt.Sprintf(sql2, this.Appid, v, this.SendUserId, this.SendName, v, userName, time.Now().Format("2006-01-02 15:04:05"))
  423. in2 := entity.Mysql.InsertBySqlByTx(tx, sql2)
  424. //插入消息表
  425. in3 := entity.Mysql.InsertBySqlByTx(tx, sql3, common.If(positionId != 0, positionId, nil))
  426. logx.Info(in1, in2, in3)
  427. return in1 > -1 && in2 > -1 && in3 > -1
  428. })
  429. logx.Info("执行事务是否成功:", ok)
  430. if ok {
  431. ok1 := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)), this.Appid)
  432. if !ok1 {
  433. log.Println("存redis:", ok1, v)
  434. }
  435. }
  436. } else {
  437. in := entity.Mysql.InsertBySql(sql3, common.If(positionId != 0, positionId, nil))
  438. logx.Info("插入消息返回 in1 id:", in)
  439. if in > -1 {
  440. ok := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)), this.Appid)
  441. if !ok {
  442. log.Println("存redis:", ok, v)
  443. }
  444. }
  445. }
  446. }(userIdArr[i], name, positionId)
  447. }
  448. wg.Wait()
  449. return 0, ""
  450. }