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.
 
 
 
 

451 lines
13 KiB

  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. }))
  158. if len(receiverDevices) <= 0 {
  159. //isOpenAppPush := svc.SysCfgGet(masterId, "is_open_app_push")
  160. if sender.SenderType == pb.SenderType_ST_USER && req.ReceiverType == pb.ReceiverType_RT_USER && isOpenAppPush == "1" && req.ReceiverId != toUserId {
  161. uid := strconv.FormatInt(req.ReceiverId, 10)
  162. alia := db.DbUserPushForJg.UserPushForJgGetWithDb(masterId, uid)
  163. if alia != "" {
  164. if sender.Nickname == "" {
  165. sendUser, err := repo2.UserRepo.Get(sender.SenderId)
  166. if err != nil {
  167. logger.Sugar.Error(err)
  168. return 0, err
  169. }
  170. sender.Nickname = sendUser.Nickname
  171. sender.AvatarUrl = sendUser.AvatarUrl
  172. }
  173. var pushContent string
  174. if req.MessageType != pb.MessageType_MT_TEXT {
  175. switch req.MessageType {
  176. case pb.MessageType_MT_UNKNOWN:
  177. pushContent = "您收到一条\"未知\"消息"
  178. break
  179. case pb.MessageType_MT_FACE:
  180. pushContent = "您收到一条表情消息"
  181. break
  182. case pb.MessageType_MT_VOICE:
  183. pushContent = "您收到一条语音消息"
  184. break
  185. case pb.MessageType_MT_IMAGE:
  186. pushContent = "您收到一条图片消息"
  187. break
  188. case pb.MessageType_MT_FILE:
  189. pushContent = "您收到一条视频消息"
  190. break
  191. case pb.MessageType_MT_LOCATION:
  192. pushContent = "您收到一条地理位置消息"
  193. break
  194. case pb.MessageType_MT_COMMAND:
  195. pushContent = "您收到一条指令推送消息"
  196. break
  197. case pb.MessageType_MT_CUSTOM:
  198. pushContent = "您收到一条\"自定义\"推送消息"
  199. break
  200. }
  201. } else {
  202. pushContent = string(req.MessageContent)
  203. }
  204. //TODO::接收者类型为`user`, 进行极光推送
  205. CommAddPush(md.PushParams{
  206. MasterId: masterId,
  207. Uid: uid,
  208. PushAlia: alia,
  209. Title: sender.Nickname,
  210. Content: pushContent,
  211. //Content: "您收到一条新消息,来自会员\"[消息发送者-会员昵称]\",发送时间\"[时间]\"",
  212. //Content: "您收到一条新消息,来自会员\"[消息发送者-会员昵称]\",发送时间\"[时间]\",消息类型\"[消息类型]\",备注\"[备注]\"",
  213. PushType: "zhi_ying_gim",
  214. MessageType: req.MessageType.String(),
  215. SendUserNickname: sender.Nickname,
  216. SendUserAvatarUrl: sender.AvatarUrl,
  217. Memo: sender.SenderType.String(),
  218. Times: time.Now().Format("2006-01-02 15:04:05"),
  219. })
  220. }
  221. }
  222. }
  223. for i := range devices {
  224. if sender.DeviceId == devices[i].DeviceId {
  225. // 消息不需要投递给发送消息的设备
  226. continue
  227. }
  228. err = MessageService.SendToDevice(ctx, devices[i], &message)
  229. if err != nil {
  230. logger.Sugar.Error(err, zap.Any("SendToUser error", devices[i]), zap.Error(err))
  231. }
  232. }
  233. return seq, nil
  234. }
  235. // RecallMessageSendToUser 撤回消息用户
  236. func (*messageService) RecallMessageSendToUser(ctx context.Context, sender *pb.Sender, toUserId int64, req *pb.RecallMessageReq, sendTime time.Time) (int64, error) {
  237. masterId, _ := grpclib.GetCtxMasterId(ctx)
  238. logger.Logger.Debug("SendToUser",
  239. zap.String("master_id", masterId),
  240. zap.Int64("request_id", grpclib.GetCtxRequestId(ctx)),
  241. zap.Int64("to_user_id", toUserId))
  242. var (
  243. seq int64 = 0
  244. err error
  245. )
  246. //1、改变消息状态
  247. _, err = repo.MessageRepo.UpdateStatus(toUserId, sendTime, int(pb.MessageStatus_MS_RECALL))
  248. if err != nil {
  249. return 0, err
  250. }
  251. //3、发送一条新的消息
  252. if req.IsPersist {
  253. seq, err = SeqService.GetUserNext(ctx, toUserId)
  254. if err != nil {
  255. return 0, err
  256. }
  257. selfMessage := model.Message{
  258. UserId: toUserId,
  259. RequestId: grpclib.GetCtxRequestId(ctx),
  260. SenderType: int32(sender.SenderType),
  261. SenderId: sender.SenderId,
  262. ReceiverType: int32(req.ReceiverType),
  263. ReceiverId: req.ReceiverId,
  264. ToUserIds: model.FormatUserIds(req.ToUserIds),
  265. Type: int(req.MessageType),
  266. Content: req.MessageContent,
  267. Seq: seq,
  268. SendTime: util.UnunixMilliTime(req.SendTime),
  269. Status: int32(pb.MessageStatus_MS_NORMAL),
  270. }
  271. err = repo.MessageRepo.Save(selfMessage)
  272. if err != nil {
  273. logger.Sugar.Error(err)
  274. return 0, err
  275. }
  276. if sender.SenderType == pb.SenderType_ST_USER && sender.SenderId == toUserId {
  277. // 用户需要增加自己的已经同步的序列号
  278. err = repo.DeviceACKRepo.Set(sender.SenderId, sender.DeviceId, seq)
  279. if err != nil {
  280. return 0, err
  281. }
  282. }
  283. }
  284. message := pb.Message{
  285. Sender: sender,
  286. ReceiverType: req.ReceiverType,
  287. ReceiverId: req.ReceiverId,
  288. ToUserIds: req.ToUserIds,
  289. MessageType: req.MessageType,
  290. MessageContent: req.MessageContent,
  291. Seq: seq,
  292. SendTime: req.SendTime,
  293. Status: pb.MessageStatus_MS_NORMAL,
  294. }
  295. // 查询用户在线设备
  296. devices, err := proxy.DeviceProxy.ListOnlineByUserId(ctx, toUserId)
  297. if err != nil {
  298. logger.Sugar.Error(err)
  299. return 0, err
  300. }
  301. for i := range devices {
  302. if sender.DeviceId == devices[i].DeviceId {
  303. // 消息不需要投递给发送消息的设备
  304. continue
  305. }
  306. err = MessageService.SendToDevice(ctx, devices[i], &message)
  307. if err != nil {
  308. logger.Sugar.Error(err, zap.Any("SendToUser error", devices[i]), zap.Error(err))
  309. }
  310. }
  311. return seq, nil
  312. }
  313. // SendRedPackageToUser 发送红包给用户
  314. func (*messageService) SendRedPackageToUser(ctx context.Context, sender *pb.Sender, toUserId int64, req *pb.SendRedPacketReq) (int64, error) {
  315. masterId, _ := grpclib.GetCtxMasterId(ctx)
  316. logger.Logger.Debug("SendRedPackageToUser",
  317. zap.String("master_id", masterId),
  318. zap.Int64("request_id", grpclib.GetCtxRequestId(ctx)),
  319. zap.Int64("to_user_id", toUserId))
  320. var (
  321. seq int64 = 0
  322. err error
  323. )
  324. //1、发送一条新的消息
  325. seq, err = SeqService.GetUserNext(ctx, toUserId)
  326. if err != nil {
  327. return 0, err
  328. }
  329. selfMessage := model.Message{
  330. UserId: toUserId,
  331. RequestId: grpclib.GetCtxRequestId(ctx),
  332. SenderType: int32(sender.SenderType),
  333. SenderId: sender.SenderId,
  334. ReceiverType: int32(req.ReceiverType),
  335. ReceiverId: req.ReceiverId,
  336. //ToUserIds: model.FormatUserIds(req.ToUserIds),
  337. Type: int(req.MessageType),
  338. Content: req.MessageContent,
  339. Seq: seq,
  340. SendTime: util.UnunixMilliTime(req.SendTime),
  341. Status: int32(pb.MessageStatus_MS_NORMAL),
  342. }
  343. err = repo.MessageRepo.Save(selfMessage)
  344. if err != nil {
  345. logger.Sugar.Error(err)
  346. return 0, err
  347. }
  348. if sender.SenderType == pb.SenderType_ST_USER && sender.SenderId == toUserId {
  349. // 用户需要增加自己的已经同步的序列号
  350. err = repo.DeviceACKRepo.Set(sender.SenderId, sender.DeviceId, seq)
  351. if err != nil {
  352. return 0, err
  353. }
  354. }
  355. message := pb.Message{
  356. Sender: sender,
  357. ReceiverType: req.ReceiverType,
  358. ReceiverId: req.ReceiverId,
  359. //ToUserIds: req.ToUserIds,
  360. MessageType: pb.MessageType_MT_RED_PACKAGE,
  361. MessageContent: req.MessageContent,
  362. Seq: seq,
  363. SendTime: req.SendTime,
  364. Status: pb.MessageStatus_MS_NORMAL,
  365. }
  366. // 查询用户在线设备
  367. devices, err := proxy.DeviceProxy.ListOnlineByUserId(ctx, toUserId)
  368. if err != nil {
  369. logger.Sugar.Error(err)
  370. return 0, err
  371. }
  372. for i := range devices {
  373. if sender.DeviceId == devices[i].DeviceId {
  374. // 消息不需要投递给发送消息的设备
  375. continue
  376. }
  377. err = MessageService.SendToDevice(ctx, devices[i], &message)
  378. if err != nil {
  379. logger.Sugar.Error(err, zap.Any("SendToUser error", devices[i]), zap.Error(err))
  380. }
  381. }
  382. return seq, nil
  383. }
  384. // SendToDevice 将消息发送给设备
  385. func (*messageService) SendToDevice(ctx context.Context, device *pb.Device, message *pb.Message) error {
  386. messageSend := pb.MessageSend{Message: message}
  387. _, err := rpc.GetConnectIntClient().DeliverMessage(picker.ContextWithAddr(ctx, device.ConnAddr), &pb.DeliverMessageReq{
  388. DeviceId: device.DeviceId,
  389. MessageSend: &messageSend,
  390. })
  391. if err != nil {
  392. logger.Logger.Error("SendToDevice error", zap.Error(err))
  393. return err
  394. }
  395. // todo 其他推送厂商
  396. return nil
  397. }
  398. func (*messageService) AddSenderInfo(sender *pb.Sender) {
  399. if sender.SenderType == pb.SenderType_ST_USER {
  400. user, err := rpc.GetBusinessIntClient().GetUser(context.TODO(), &pb.GetUserReq{UserId: sender.SenderId})
  401. if err == nil && user != nil {
  402. sender.AvatarUrl = user.User.AvatarUrl
  403. sender.Nickname = user.User.Nickname
  404. sender.Extra = user.User.Extra
  405. }
  406. }
  407. }