golang-im聊天
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

message_service.go 13 KiB

2 years ago
2 years ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. package service
  2. import (
  3. "context"
  4. "gim/internal/business/comm/db"
  5. svc "gim/internal/business/comm/service"
  6. "gim/internal/business/comm/utils"
  7. repo2 "gim/internal/business/domain/user/repo"
  8. "gim/internal/logic/domain/message/md"
  9. "gim/internal/logic/domain/message/model"
  10. "gim/internal/logic/domain/message/repo"
  11. "gim/internal/logic/proxy"
  12. "gim/pkg/grpclib"
  13. "gim/pkg/grpclib/picker"
  14. "gim/pkg/logger"
  15. "gim/pkg/pb"
  16. "gim/pkg/rpc"
  17. "gim/pkg/util"
  18. "go.uber.org/zap"
  19. "google.golang.org/protobuf/proto"
  20. "strconv"
  21. "time"
  22. )
  23. const MessageLimit = 50 // 最大消息同步数量
  24. const MaxSyncBufLen = 65536 // 最大字节数组长度
  25. type messageService struct{}
  26. var MessageService = new(messageService)
  27. // Sync 消息同步
  28. func (*messageService) Sync(ctx context.Context, userId, seq int64) (*pb.SyncResp, error) {
  29. messages, hasMore, err := MessageService.ListByUserIdAndSeq(ctx, userId, seq)
  30. if err != nil {
  31. return nil, err
  32. }
  33. pbMessages := model.MessagesToPB(messages)
  34. length := len(pbMessages)
  35. resp := &pb.SyncResp{Messages: pbMessages, HasMore: hasMore}
  36. bytes, err := proto.Marshal(resp)
  37. if err != nil {
  38. return nil, err
  39. }
  40. // 如果字节数组大于一个包的长度,需要减少字节数组
  41. for len(bytes) > MaxSyncBufLen {
  42. length = length * 2 / 3
  43. resp = &pb.SyncResp{Messages: pbMessages[0:length], HasMore: true}
  44. bytes, err = proto.Marshal(resp)
  45. if err != nil {
  46. return nil, err
  47. }
  48. }
  49. var userIds = make(map[int64]int32, len(resp.Messages))
  50. for i := range resp.Messages {
  51. if resp.Messages[i].Sender.SenderType == pb.SenderType_ST_USER {
  52. userIds[resp.Messages[i].Sender.SenderId] = 0
  53. }
  54. }
  55. usersResp, err := rpc.GetBusinessIntClient().GetUsers(ctx, &pb.GetUsersReq{UserIds: userIds})
  56. if err != nil {
  57. return nil, err
  58. }
  59. for i := range resp.Messages {
  60. if resp.Messages[i].Sender.SenderType == pb.SenderType_ST_USER {
  61. user, ok := usersResp.Users[resp.Messages[i].Sender.SenderId]
  62. if ok {
  63. resp.Messages[i].Sender.Nickname = user.Nickname
  64. resp.Messages[i].Sender.AvatarUrl = user.AvatarUrl
  65. resp.Messages[i].Sender.Extra = user.Extra
  66. } else {
  67. logger.Logger.Warn("get user failed", zap.Int64("user_id", resp.Messages[i].Sender.SenderId))
  68. }
  69. }
  70. }
  71. return resp, nil
  72. }
  73. // ListByUserIdAndSeq 查询消息
  74. func (*messageService) ListByUserIdAndSeq(ctx context.Context, userId, seq int64) ([]model.Message, bool, error) {
  75. var err error
  76. if seq == 0 {
  77. seq, err = DeviceAckService.GetMaxByUserId(ctx, userId)
  78. if err != nil {
  79. return nil, false, err
  80. }
  81. }
  82. return repo.MessageRepo.ListBySeq(userId, seq, MessageLimit)
  83. }
  84. // SendToUser 将消息发送给用户
  85. func (*messageService) SendToUser(ctx context.Context, sender *pb.Sender, toUserId int64, req *pb.SendMessageReq) (int64, error) {
  86. masterId, _ := grpclib.GetCtxMasterId(ctx)
  87. logger.Logger.Debug("SendToUser",
  88. zap.String("master_id", masterId),
  89. zap.Int64("request_id", grpclib.GetCtxRequestId(ctx)),
  90. zap.Int64("to_user_id", toUserId))
  91. var (
  92. seq int64 = 0
  93. err error
  94. )
  95. if req.IsPersist {
  96. seq, err = SeqService.GetUserNext(ctx, toUserId)
  97. if err != nil {
  98. return 0, err
  99. }
  100. selfMessage := model.Message{
  101. UserId: toUserId,
  102. RequestId: grpclib.GetCtxRequestId(ctx),
  103. SenderType: int32(sender.SenderType),
  104. SenderId: sender.SenderId,
  105. ReceiverType: int32(req.ReceiverType),
  106. ReceiverId: req.ReceiverId,
  107. ToUserIds: model.FormatUserIds(req.ToUserIds),
  108. Type: int(req.MessageType),
  109. Content: req.MessageContent,
  110. Seq: seq,
  111. SendTime: util.UnunixMilliTime(req.SendTime),
  112. Status: int32(pb.MessageStatus_MS_NORMAL),
  113. }
  114. err = repo.MessageRepo.Save(selfMessage)
  115. if err != nil {
  116. logger.Sugar.Error(err)
  117. return 0, err
  118. }
  119. if sender.SenderType == pb.SenderType_ST_USER && sender.SenderId == toUserId {
  120. // 用户需要增加自己的已经同步的序列号
  121. err = repo.DeviceACKRepo.Set(sender.SenderId, sender.DeviceId, seq)
  122. if err != nil {
  123. return 0, err
  124. }
  125. }
  126. }
  127. message := pb.Message{
  128. Sender: sender,
  129. ReceiverType: req.ReceiverType,
  130. ReceiverId: req.ReceiverId,
  131. ToUserIds: req.ToUserIds,
  132. MessageType: req.MessageType,
  133. MessageContent: req.MessageContent,
  134. Seq: seq,
  135. SendTime: req.SendTime,
  136. Status: pb.MessageStatus_MS_NORMAL,
  137. }
  138. // 查询用户在线设备
  139. devices, err := proxy.DeviceProxy.ListOnlineByUserId(ctx, toUserId)
  140. if err != nil {
  141. logger.Sugar.Error(err)
  142. return 0, err
  143. }
  144. // 查询接受者用户在线设备
  145. receiverDevices, err := proxy.DeviceProxy.ListOnlineByUserId(ctx, req.ReceiverId)
  146. if err != nil {
  147. logger.Sugar.Error(err)
  148. return 0, err
  149. }
  150. isOpenAppPush := svc.SysCfgGet(masterId, "is_open_app_push")
  151. utils.FilePutContents("SendToUser", utils.SerializeStr(map[string]interface{}{
  152. "devices_len": len(devices),
  153. "sender": sender,
  154. "toUserId": toUserId,
  155. "isOpenAppPush": isOpenAppPush,
  156. "req": req,
  157. "masterId": masterId,
  158. }))
  159. if len(receiverDevices) <= 0 {
  160. //isOpenAppPush := svc.SysCfgGet(masterId, "is_open_app_push")
  161. if sender.SenderType == pb.SenderType_ST_USER && req.ReceiverType == pb.ReceiverType_RT_USER && isOpenAppPush == "1" && req.ReceiverId != toUserId {
  162. uid := strconv.FormatInt(req.ReceiverId, 10)
  163. alia := db.DbUserPushForJg.UserPushForJgGetWithDb(masterId, uid)
  164. if alia != "" {
  165. if sender.Nickname == "" {
  166. sendUser, err := repo2.UserRepo.Get(sender.SenderId)
  167. if err != nil {
  168. logger.Sugar.Error(err)
  169. return 0, err
  170. }
  171. sender.Nickname = sendUser.Nickname
  172. sender.AvatarUrl = sendUser.AvatarUrl
  173. }
  174. var pushContent string
  175. if req.MessageType != pb.MessageType_MT_TEXT {
  176. switch req.MessageType {
  177. case pb.MessageType_MT_UNKNOWN:
  178. pushContent = "您收到一条\"未知\"消息"
  179. break
  180. case pb.MessageType_MT_FACE:
  181. pushContent = "您收到一条表情消息"
  182. break
  183. case pb.MessageType_MT_VOICE:
  184. pushContent = "您收到一条语音消息"
  185. break
  186. case pb.MessageType_MT_IMAGE:
  187. pushContent = "您收到一条图片消息"
  188. break
  189. case pb.MessageType_MT_FILE:
  190. pushContent = "您收到一条视频消息"
  191. break
  192. case pb.MessageType_MT_LOCATION:
  193. pushContent = "您收到一条地理位置消息"
  194. break
  195. case pb.MessageType_MT_COMMAND:
  196. pushContent = "您收到一条指令推送消息"
  197. break
  198. case pb.MessageType_MT_CUSTOM:
  199. pushContent = "您收到一条\"自定义\"推送消息"
  200. break
  201. }
  202. } else {
  203. pushContent = string(req.MessageContent)
  204. }
  205. //TODO::接收者类型为`user`, 进行极光推送
  206. CommAddPush(md.PushParams{
  207. MasterId: masterId,
  208. Uid: uid,
  209. PushAlia: alia,
  210. Title: sender.Nickname,
  211. Content: pushContent,
  212. //Content: "您收到一条新消息,来自会员\"[消息发送者-会员昵称]\",发送时间\"[时间]\"",
  213. //Content: "您收到一条新消息,来自会员\"[消息发送者-会员昵称]\",发送时间\"[时间]\",消息类型\"[消息类型]\",备注\"[备注]\"",
  214. PushType: "zhi_ying_gim",
  215. MessageType: req.MessageType.String(),
  216. SendUserNickname: sender.Nickname,
  217. SendUserAvatarUrl: sender.AvatarUrl,
  218. Memo: sender.SenderType.String(),
  219. Times: time.Now().Format("2006-01-02 15:04:05"),
  220. })
  221. }
  222. }
  223. }
  224. for i := range devices {
  225. if sender.DeviceId == devices[i].DeviceId {
  226. // 消息不需要投递给发送消息的设备
  227. continue
  228. }
  229. err = MessageService.SendToDevice(ctx, devices[i], &message)
  230. if err != nil {
  231. logger.Sugar.Error(err, zap.Any("SendToUser error", devices[i]), zap.Error(err))
  232. }
  233. }
  234. return seq, nil
  235. }
  236. // RecallMessageSendToUser 撤回消息用户
  237. func (*messageService) RecallMessageSendToUser(ctx context.Context, sender *pb.Sender, toUserId int64, req *pb.RecallMessageReq, sendTime time.Time) (int64, error) {
  238. masterId, _ := grpclib.GetCtxMasterId(ctx)
  239. logger.Logger.Debug("SendToUser",
  240. zap.String("master_id", masterId),
  241. zap.Int64("request_id", grpclib.GetCtxRequestId(ctx)),
  242. zap.Int64("to_user_id", toUserId))
  243. var (
  244. seq int64 = 0
  245. err error
  246. )
  247. //1、改变消息状态
  248. _, err = repo.MessageRepo.UpdateStatus(toUserId, sendTime, int(pb.MessageStatus_MS_RECALL))
  249. if err != nil {
  250. return 0, err
  251. }
  252. //3、发送一条新的消息
  253. if req.IsPersist {
  254. seq, err = SeqService.GetUserNext(ctx, toUserId)
  255. if err != nil {
  256. return 0, err
  257. }
  258. selfMessage := model.Message{
  259. UserId: toUserId,
  260. RequestId: grpclib.GetCtxRequestId(ctx),
  261. SenderType: int32(sender.SenderType),
  262. SenderId: sender.SenderId,
  263. ReceiverType: int32(req.ReceiverType),
  264. ReceiverId: req.ReceiverId,
  265. ToUserIds: model.FormatUserIds(req.ToUserIds),
  266. Type: int(req.MessageType),
  267. Content: req.MessageContent,
  268. Seq: seq,
  269. SendTime: util.UnunixMilliTime(req.SendTime),
  270. Status: int32(pb.MessageStatus_MS_NORMAL),
  271. }
  272. err = repo.MessageRepo.Save(selfMessage)
  273. if err != nil {
  274. logger.Sugar.Error(err)
  275. return 0, err
  276. }
  277. if sender.SenderType == pb.SenderType_ST_USER && sender.SenderId == toUserId {
  278. // 用户需要增加自己的已经同步的序列号
  279. err = repo.DeviceACKRepo.Set(sender.SenderId, sender.DeviceId, seq)
  280. if err != nil {
  281. return 0, err
  282. }
  283. }
  284. }
  285. message := pb.Message{
  286. Sender: sender,
  287. ReceiverType: req.ReceiverType,
  288. ReceiverId: req.ReceiverId,
  289. ToUserIds: req.ToUserIds,
  290. MessageType: req.MessageType,
  291. MessageContent: req.MessageContent,
  292. Seq: seq,
  293. SendTime: req.SendTime,
  294. Status: pb.MessageStatus_MS_NORMAL,
  295. }
  296. // 查询用户在线设备
  297. devices, err := proxy.DeviceProxy.ListOnlineByUserId(ctx, toUserId)
  298. if err != nil {
  299. logger.Sugar.Error(err)
  300. return 0, err
  301. }
  302. for i := range devices {
  303. if sender.DeviceId == devices[i].DeviceId {
  304. // 消息不需要投递给发送消息的设备
  305. continue
  306. }
  307. err = MessageService.SendToDevice(ctx, devices[i], &message)
  308. if err != nil {
  309. logger.Sugar.Error(err, zap.Any("SendToUser error", devices[i]), zap.Error(err))
  310. }
  311. }
  312. return seq, nil
  313. }
  314. // SendRedPackageToUser 发送红包给用户
  315. func (*messageService) SendRedPackageToUser(ctx context.Context, sender *pb.Sender, toUserId int64, req *pb.SendRedPacketReq) (int64, error) {
  316. masterId, _ := grpclib.GetCtxMasterId(ctx)
  317. logger.Logger.Debug("SendRedPackageToUser",
  318. zap.String("master_id", masterId),
  319. zap.Int64("request_id", grpclib.GetCtxRequestId(ctx)),
  320. zap.Int64("to_user_id", toUserId))
  321. var (
  322. seq int64 = 0
  323. err error
  324. )
  325. //1、发送一条新的消息
  326. seq, err = SeqService.GetUserNext(ctx, toUserId)
  327. if err != nil {
  328. return 0, err
  329. }
  330. selfMessage := model.Message{
  331. UserId: toUserId,
  332. RequestId: grpclib.GetCtxRequestId(ctx),
  333. SenderType: int32(sender.SenderType),
  334. SenderId: sender.SenderId,
  335. ReceiverType: int32(req.ReceiverType),
  336. ReceiverId: req.ReceiverId,
  337. //ToUserIds: model.FormatUserIds(req.ToUserIds),
  338. Type: int(req.MessageType),
  339. Content: req.MessageContent,
  340. Seq: seq,
  341. SendTime: util.UnunixMilliTime(req.SendTime),
  342. Status: int32(pb.MessageStatus_MS_NORMAL),
  343. }
  344. err = repo.MessageRepo.Save(selfMessage)
  345. if err != nil {
  346. logger.Sugar.Error(err)
  347. return 0, err
  348. }
  349. if sender.SenderType == pb.SenderType_ST_USER && sender.SenderId == toUserId {
  350. // 用户需要增加自己的已经同步的序列号
  351. err = repo.DeviceACKRepo.Set(sender.SenderId, sender.DeviceId, seq)
  352. if err != nil {
  353. return 0, err
  354. }
  355. }
  356. message := pb.Message{
  357. Sender: sender,
  358. ReceiverType: req.ReceiverType,
  359. ReceiverId: req.ReceiverId,
  360. //ToUserIds: req.ToUserIds,
  361. MessageType: pb.MessageType_MT_RED_PACKAGE,
  362. MessageContent: req.MessageContent,
  363. Seq: seq,
  364. SendTime: req.SendTime,
  365. Status: pb.MessageStatus_MS_NORMAL,
  366. }
  367. // 查询用户在线设备
  368. devices, err := proxy.DeviceProxy.ListOnlineByUserId(ctx, toUserId)
  369. if err != nil {
  370. logger.Sugar.Error(err)
  371. return 0, err
  372. }
  373. for i := range devices {
  374. if sender.DeviceId == devices[i].DeviceId {
  375. // 消息不需要投递给发送消息的设备
  376. continue
  377. }
  378. err = MessageService.SendToDevice(ctx, devices[i], &message)
  379. if err != nil {
  380. logger.Sugar.Error(err, zap.Any("SendToUser error", devices[i]), zap.Error(err))
  381. }
  382. }
  383. return seq, nil
  384. }
  385. // SendToDevice 将消息发送给设备
  386. func (*messageService) SendToDevice(ctx context.Context, device *pb.Device, message *pb.Message) error {
  387. messageSend := pb.MessageSend{Message: message}
  388. _, err := rpc.GetConnectIntClient().DeliverMessage(picker.ContextWithAddr(ctx, device.ConnAddr), &pb.DeliverMessageReq{
  389. DeviceId: device.DeviceId,
  390. MessageSend: &messageSend,
  391. })
  392. if err != nil {
  393. logger.Logger.Error("SendToDevice error", zap.Error(err))
  394. return err
  395. }
  396. // todo 其他推送厂商
  397. return nil
  398. }
  399. func (*messageService) AddSenderInfo(sender *pb.Sender) {
  400. if sender.SenderType == pb.SenderType_ST_USER {
  401. user, err := rpc.GetBusinessIntClient().GetUser(context.TODO(), &pb.GetUserReq{UserId: sender.SenderId})
  402. if err == nil && user != nil {
  403. sender.AvatarUrl = user.User.AvatarUrl
  404. sender.Nickname = user.User.Nickname
  405. sender.Extra = user.User.Extra
  406. }
  407. }
  408. }