sendMsg.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. "fmt"
  9. "github.com/zeromicro/go-zero/core/logx"
  10. "log"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. )
  16. // 类型的顺序
  17. const order = "1,4"
  18. const MsgCountKey = "count_%s_%d" //redis 消息未读数量 Count.用户id.消息类型=数量
  19. const redisModule = "msgCount"
  20. func FindUserMsg(this message.FindUserMsgReq, isClean bool) message.FindUserMsgRes {
  21. var err error
  22. var count int64
  23. cquery := map[string]interface{}{
  24. "receive_userid": this.UserId,
  25. "isdel": 1,
  26. "appid": this.Appid,
  27. }
  28. if this.MsgType > 0 {
  29. cquery["group_id"] = this.MsgType
  30. }
  31. if this.Read != -1 {
  32. cquery["isRead"] = this.Read
  33. }
  34. count = entity.Mysql.Count("message", cquery)
  35. data := message.FindUserMsgRes{}
  36. if this.PageSize == 5 {
  37. //从缓存里边取数据
  38. pc_a, err := entity.GetData(this.UserId)
  39. if err == nil && pc_a != nil {
  40. // 缓存有值
  41. if !isClean {
  42. data.Code = 1
  43. data.Message = "查询成功"
  44. data.Data = pc_a.Data
  45. data.Count = pc_a.Count
  46. return data
  47. }
  48. }
  49. }
  50. count = entity.Mysql.Count("message", cquery)
  51. if count > 0 {
  52. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  53. //log.Println("数据:", res)
  54. if res != nil && len(*res) > 0 {
  55. for _, v := range *res {
  56. _id := util.Int64All(v["id"])
  57. id := strconv.FormatInt(_id, 10)
  58. data.Data = append(data.Data, &message.Messages{
  59. Id: id,
  60. Appid: util.ObjToString(v["appId"]),
  61. ReceiveUserId: util.ObjToString(v["receive_userid"]),
  62. ReceiveName: util.ObjToString(v["receive_name"]),
  63. SendUserId: util.ObjToString(v["send_userid"]),
  64. SendName: util.ObjToString(v["send_name"]),
  65. Createtime: util.ObjToString(v["createtime"]),
  66. Title: util.ObjToString(v["title"]),
  67. MsgType: int64(util.IntAll(v["group_id"])),
  68. Link: util.ObjToString(v["link"]),
  69. CiteId: util.Int64All(v["cite_id"]),
  70. Content: util.ObjToString(v["content"]),
  71. IsRead: util.Int64All(v["isRead"]),
  72. MsgLogId: util.Int64All(v["msg_log_id"]),
  73. })
  74. }
  75. }
  76. }
  77. data.Count = count
  78. if this.PageSize == 5 {
  79. redisData := map[string]interface{}{
  80. "count": count,
  81. "data": data.Data,
  82. }
  83. entity.SetData(this.UserId, redisData, entity.SurvivalTime)
  84. }
  85. if err != nil {
  86. data.Code = 0
  87. data.Message = "查询失败"
  88. } else {
  89. data.Code = 1
  90. data.Message = "查询成功"
  91. }
  92. return data
  93. }
  94. func UserMsgList(this *message.UserMsgListReq) *message.UserMsgList {
  95. var (
  96. unread, count int64
  97. )
  98. m := &MessageService{}
  99. data := new(message.UserMsgList)
  100. if !this.IsMsgList && !this.IsColumnNewMsg && !this.IsColumn { //消息未读数统计
  101. //获取总未读数 初始化
  102. _, unread = m.CountUnread(this.UserId, true)
  103. if this.IsContainLetter { //私信统计
  104. unread += unreadMsg(this)
  105. }
  106. data.Unread = unread
  107. return data
  108. }
  109. cquery := map[string]interface{}{
  110. "receive_userid": this.UserId,
  111. "isdel": 1,
  112. "appid": this.Appid,
  113. }
  114. if this.MsgType > 0 {
  115. cquery["group_id"] = this.MsgType
  116. }
  117. if this.Read != -1 {
  118. cquery["isRead"] = this.Read
  119. }
  120. //获取栏目下的数据
  121. sData := make(map[string][]*message.Messages)
  122. t := time.Now()
  123. if this.IsColumnNewMsg && this.SortSize > 0 {
  124. sortData := entity.Mysql.SelectBySql(fmt.Sprintf(`SELECT * FROM (
  125. SELECT *, ROW_NUMBER() OVER (PARTITION BY group_id, receive_userid ORDER BY createtime DESC) AS row_num
  126. FROM message
  127. WHERE receive_userid = '%s' and isdel = 1 and appid = %s
  128. ) AS message_ranked
  129. WHERE row_num <=%d;`, this.UserId, this.Appid, this.SortSize))
  130. log.Println("消息列表耗时1:", time.Since(t))
  131. if sortData != nil {
  132. for _, v := range *sortData {
  133. _id := util.Int64All(v["id"])
  134. id := strconv.FormatInt(_id, 10)
  135. var msg = message.Messages{
  136. Id: id,
  137. Appid: common.InterfaceToStr(v["appId"]),
  138. ReceiveUserId: common.InterfaceToStr(v["receive_userid"]),
  139. ReceiveName: common.InterfaceToStr(v["receive_name"]),
  140. SendUserId: common.InterfaceToStr(v["send_userid"]),
  141. SendName: common.InterfaceToStr(v["send_name"]),
  142. Createtime: common.InterfaceToStr(v["createtime"]),
  143. Title: common.InterfaceToStr(v["title"]),
  144. MsgType: int64(util.IntAll(v["group_id"])),
  145. Link: common.InterfaceToStr(v["link"]),
  146. CiteId: util.Int64All(v["cite_id"]),
  147. Content: common.InterfaceToStr(v["content"]),
  148. IsRead: util.Int64All(v["isRead"]),
  149. MsgLogId: util.Int64All(v["msg_log_id"]),
  150. }
  151. if sData[common.InterfaceToStr(v["group_id"])] == nil {
  152. sData[common.InterfaceToStr(v["group_id"])] = []*message.Messages{&msg}
  153. } else {
  154. sData[common.InterfaceToStr(v["group_id"])] = append(sData[common.InterfaceToStr(v["group_id"])], &msg)
  155. }
  156. }
  157. }
  158. }
  159. //消息栏目下的最新消息
  160. var columnData []*message.AllSortData
  161. if this.IsColumn {
  162. //获取所有分类未读数 不初始化
  163. sortUnread, _ := m.CountUnread(this.UserId, false)
  164. for _, v := range entity.MessageColumn {
  165. var column message.AllSortData
  166. column.Name = common.InterfaceToStr(v["name"])
  167. column.Img = fmt.Sprintf("/common-module/msgCenter/%s.png", common.InterfaceToStr(v["img"]))
  168. column.MsgType = common.Int64All(v["group_id"])
  169. if column.Name == "私信" {
  170. column.UnreadMessages = unreadMsg(this)
  171. } else if common.IntAll(v["group_id"]) > 0 {
  172. //消息未读数
  173. msgType := common.InterfaceToStr(v["group_id"])
  174. column.UnreadMessages = sortUnread[msgType]
  175. unread += sortUnread[msgType]
  176. column.Data = sData[msgType]
  177. }
  178. columnData = append(columnData, &column)
  179. }
  180. }
  181. data.SortData = columnData
  182. count = entity.Mysql.Count("message", cquery)
  183. if this.IsMsgList {
  184. if count > 0 {
  185. if this.OffSet <= 0 {
  186. this.OffSet = 1
  187. }
  188. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  189. log.Println("消息列表耗时3:", time.Since(t))
  190. if res != nil && len(*res) > 0 {
  191. for _, v := range *res {
  192. _id := util.Int64All(v["id"])
  193. id := strconv.FormatInt(_id, 10)
  194. data.Data = append(data.Data, &message.Messages{
  195. Id: id,
  196. Appid: common.InterfaceToStr(v["appId"]),
  197. ReceiveUserId: common.InterfaceToStr(v["receive_userid"]),
  198. ReceiveName: common.InterfaceToStr(v["receive_name"]),
  199. SendUserId: common.InterfaceToStr(v["send_userid"]),
  200. SendName: common.InterfaceToStr(v["send_name"]),
  201. Createtime: common.InterfaceToStr(v["createtime"]),
  202. Title: common.InterfaceToStr(v["title"]),
  203. MsgType: int64(util.IntAll(v["group_id"])),
  204. Link: common.InterfaceToStr(v["link"]),
  205. CiteId: util.Int64All(v["cite_id"]),
  206. Content: common.InterfaceToStr(v["content"]),
  207. IsRead: util.Int64All(v["isRead"]),
  208. MsgLogId: util.Int64All(v["msg_log_id"]),
  209. })
  210. }
  211. }
  212. }
  213. }
  214. data.Count = count
  215. if this.Read == 0 {
  216. unread = count
  217. if this.IsContainLetter { //是否需要统计私信未读数
  218. unread += unreadMsg(this)
  219. }
  220. }
  221. data.Unread = unread
  222. return data
  223. }
  224. func unreadMsg(this *message.UserMsgListReq) int64 {
  225. if this.PositionId <= 0 {
  226. return 0
  227. }
  228. querySql := fmt.Sprintf("SELECT b.*,(SELECT SUM( a.unread) FROM %s a "+
  229. "LEFT JOIN %s b ON a.message_id = b.id "+
  230. "WHERE a.unread > 0 "+
  231. "AND ( a.my_position_id = %d OR a.user_id = %d )) AS unread "+
  232. "FROM %s a "+
  233. "LEFT JOIN %s b ON a.message_id = b.id "+
  234. "WHERE a.unread > 0 "+
  235. "AND ( a.my_position_id = %d OR a.user_id = %d ) "+
  236. "ORDER BY a.TIMESTAMP DESC LIMIT 0,1", "socialize_summary", "socialize_message", this.PositionId, this.NewUserId,
  237. "socialize_summary", "socialize_message", this.PositionId, this.NewUserId)
  238. log.Println("查询sql", querySql)
  239. msgUnread := entity.BaseMysql.SelectBySql(querySql)
  240. if msgUnread != nil && len(*msgUnread) > 0 {
  241. return common.Int64All((*msgUnread)[0]["unread"])
  242. }
  243. return 0
  244. }
  245. func UserUnreadMsgList(this *message.UserUnreadMsgListReq) (int64, []*message.Messages) {
  246. count := 0
  247. data := []*message.Messages{}
  248. types := entity.Mysql.Find("message_group", map[string]interface{}{}, `"group_id"`, "", -1, -1)
  249. if types != nil && len(*types) > 0 {
  250. for _, v := range *types {
  251. key := fmt.Sprintf(MsgCountKey, this.UserId, util.IntAll(v["group_id"]))
  252. if exists, _ := redis.Exists(redisModule, key); exists {
  253. count += redis.GetInt(redisModule, key)
  254. }
  255. }
  256. }
  257. if this.IsNeedData == 1 && count > 0 {
  258. query := map[string]interface{}{
  259. "receive_userid": this.UserId,
  260. "isdel": 1,
  261. "appid": this.Appid,
  262. "isRead": 0,
  263. }
  264. res := entity.Mysql.Find("message", query, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  265. if res != nil && len(*res) > 0 {
  266. for _, val := range *res {
  267. _id := util.Int64All(val["id"])
  268. id := strconv.FormatInt(_id, 10)
  269. links4 := common.InterfaceToStr(val["link"])
  270. link4, androidUrl4, iosUrl4, weChatUrl4 := util.LinkSplit(links4)
  271. url := map[string]string{
  272. "androidUrl": androidUrl4,
  273. "iosUrl": iosUrl4,
  274. "weChatUrl": weChatUrl4,
  275. }
  276. data = append(data, &message.Messages{
  277. Id: id,
  278. Appid: common.InterfaceToStr(val["appid"]),
  279. ReceiveUserId: common.InterfaceToStr(val["receive_userid"]),
  280. ReceiveName: common.InterfaceToStr(val["receive_name"]),
  281. SendUserId: common.InterfaceToStr(val["send_userid"]),
  282. SendName: common.InterfaceToStr(val["send_name"]),
  283. Createtime: common.InterfaceToStr(val["createtime"]),
  284. Title: common.InterfaceToStr(val["title"]),
  285. MsgType: common.Int64All(val["group_id"]),
  286. Link: link4,
  287. CiteId: common.Int64All(val["cite_id"]),
  288. Content: common.InterfaceToStr(val["content"]),
  289. IsRead: common.Int64All(val["isRead"]),
  290. MsgLogId: common.Int64All(val["msg_log_id"]),
  291. Url: url,
  292. })
  293. }
  294. }
  295. }
  296. return util.Int64All(count), data
  297. }
  298. func MessageGetLast(this *message.UserMsgListReq) *message.Messages {
  299. if !this.IsMsgList && !this.IsColumnNewMsg && !this.IsColumn {
  300. return nil
  301. }
  302. query := map[string]interface{}{
  303. "receive_userid": this.UserId,
  304. "isdel": 1,
  305. "appid": this.Appid,
  306. "isRead": 0,
  307. "group_id": 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)["group_id"]),
  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. return nil
  332. }
  333. // MsgCountAdd 消息未读数量加1
  334. func MsgCountAdd(userId, appId string, msgType int64) bool {
  335. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  336. exists, _ := redis.Exists(redisModule, keyString)
  337. if exists {
  338. in := redis.Incr(redisModule, keyString)
  339. FindUserMsg(message.FindUserMsgReq{
  340. UserId: userId,
  341. Appid: appId,
  342. OffSet: 1,
  343. PageSize: 5,
  344. MsgType: -1,
  345. Read: 0,
  346. }, true)
  347. return in > 0
  348. }
  349. return true
  350. }
  351. // MsgCountMinusOne 根据消息类型未读消息数量减1
  352. func MsgCountMinusOne(userId, appId string, msgType int64) bool {
  353. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  354. exists, _ := redis.Exists(redisModule, keyString)
  355. if exists {
  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. if redis.GetInt(redisModule, keyString) <= 0 {
  365. return true
  366. }
  367. in := redis.Decrby(redisModule, keyString, 1)
  368. return in > 0
  369. }
  370. return true
  371. }
  372. // MsgCountZero 把该消息类型未读数量置0
  373. func MsgCountZero(userId, appId string, msgType int64) bool {
  374. if msgType > 0 && msgType < 999 { //全部私信不统计
  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. return true
  388. }
  389. func MultSave(this message.MultipleSaveMsgReq) (int64, string) {
  390. userIdArr := strings.Split(this.UserIds, ",")
  391. userNameArr := strings.Split(this.UserNames, ",")
  392. positionIdArr := strings.Split(this.PositionIds, ",")
  393. if len(userIdArr) == 0 {
  394. return 0, "无效的用户id"
  395. }
  396. wg := &sync.WaitGroup{}
  397. var group_id int
  398. class := entity.Mysql.FindOne("message_class", map[string]interface{}{"msg_type": this.MsgType}, "group_id", "")
  399. if class != nil && len(*class) > 0 {
  400. group_id = util.IntAll((*class)["group_id"])
  401. }
  402. for i := 0; i < len(userIdArr); i++ {
  403. if userIdArr[i] == "" {
  404. continue
  405. }
  406. name := userNameArr[i]
  407. wg.Add(1)
  408. entity.SaveConcurrencyChan <- 1
  409. var positionId int64
  410. if len(positionIdArr) == len(userIdArr) {
  411. positionId = common.Int64All(positionIdArr[i])
  412. }
  413. go func(v, userName string, positionId int64) {
  414. defer func() {
  415. <-entity.SaveConcurrencyChan
  416. wg.Done()
  417. }()
  418. //消息数组
  419. nTime := time.Now().Format("2006-01-02 15:04:05")
  420. //c := entity.Mysql.Count("conversation", map[string]interface{}{"receive_id": v, "send_id": this.SendUserId})
  421. 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,group_id,position_id) values ("%s",'%s','%s','%s','%s','%s','%s',%d,'%s',0,'%s',0,1,%d,%d,'%s',%d,?);`
  422. sql3 = fmt.Sprintf(sql3, this.Appid, v, userName, this.SendUserId, this.SendName, this.Title, this.Content, this.MsgType, this.Link, nTime, this.MsgLogId, this.ShowBuoy, this.ShowContent, group_id)
  423. var in int64
  424. /*if c <= 0 {
  425. 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');`
  426. sql1 = fmt.Sprintf(sql1, this.Appid, this.SendUserId, v, userName, this.SendUserId, this.SendName, nTime)
  427. //插入会话表
  428. in1 := entity.Mysql.InsertBySql(sql1)
  429. 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');`
  430. sql2 = fmt.Sprintf(sql2, this.Appid, v, this.SendUserId, this.SendName, v, userName, nTime)
  431. in2 := entity.Mysql.InsertBySql(sql2)
  432. //插入消息表
  433. in = entity.Mysql.InsertBySql(sql3, common.If(positionId != 0, positionId, nil))
  434. logx.Info(in1, in2, in)
  435. if in1 > -1 && in2 > -1 && in > -1 {
  436. ok1 := MsgCountAdd(v, this.Appid, this.MsgType)
  437. if !ok1 {
  438. log.Println("存redis:", ok1, v)
  439. }
  440. }
  441. } else {*/
  442. in = entity.Mysql.InsertBySql(sql3, common.If(positionId != 0, positionId, nil))
  443. logx.Info("插入消息返回 in1 id:", in)
  444. if in > -1 {
  445. ok := MsgCountAdd(v, this.Appid, util.Int64All(group_id))
  446. if !ok {
  447. log.Println("存redis:", ok, v)
  448. }
  449. }
  450. //}
  451. if in > -1 {
  452. //发送消息成功,推送微信、app
  453. pushConfig, err := GetWxTmplConfig(this.MsgType)
  454. if err != nil {
  455. logx.Error(fmt.Sprintf("SendWxTmplMsg uId %s Error %s", v, err.Error()))
  456. }
  457. p := &WxTmplPush{
  458. Config: pushConfig,
  459. }
  460. p.MgoId = v
  461. if this.MsgType == 10 {
  462. this.Title = this.ProductName
  463. this.Content = this.OrderId
  464. nTime = this.OrderMoney
  465. }
  466. // 消息模版 工单类型 {{thing19.DATA}} 工单标题 {{thing6.DATA}} 项目名称 {{thing13.DATA}} 服务时间 {{time25.DATA}} 服务地址 {{thing26.DATA}}
  467. err = p.SendMsg(this.WxPushUrl, this.Title, this.Content, nTime, this.Row4)
  468. if err != nil {
  469. logx.Error(fmt.Sprintf("SendWxTmplMsg uId %s Error %s", v, err.Error()))
  470. } else {
  471. logx.Infof("SendWxTmplMsg uId success %s ", v)
  472. }
  473. //app推送
  474. uData := p.GetUserPushInfo()
  475. if err = AppPushMsg(uData, pushConfig.Switch, this.AppPushUrl, this.Title, this.Content, this.MsgType); err != nil {
  476. logx.Error(fmt.Sprintf("SendWxTmplMsg uId %s Error %s", v, err.Error()))
  477. }
  478. }
  479. }(userIdArr[i], name, positionId)
  480. }
  481. wg.Wait()
  482. return 0, ""
  483. }