Exemplo n.º 1
0
        public void SendMessage(string message)
        {
            var hubContext = GlobalHost.ConnectionManager.GetHubContext <MyChatHub>();

            //未开启多租户时,默认为1;
            //see:Abp.Runtime.Session.ClaimsAbpSession 实现
            var user        = new UserIdentifier(1, AbpSession.GetUserId());
            var userClients = onlineClientManager.GetAllByUserId(user);

            foreach (var userClient in userClients)
            {
                hubContext.Clients.Client(userClient.ConnectionId).getMessage(string.Format("User {0}: {1}", AbpSession?.UserId, message));
                Logger.Debug($"TenantId: {userClient.Properties},UserId: {userClient.UserId},IP: {userClient.IpAddress},ConnectionId: {userClient.ConnectionId}");
            }
        }
        private void NotifyUserConnectionStateChange(UserIdentifier user, bool isConnected)
        {
            var cacheItem = _userFriendsCache.GetCacheItem(user);

            foreach (var friend in cacheItem.Friends)
            {
                var friendUserClients = _onlineClientManager.GetAllByUserId(new UserIdentifier(friend.FriendTenantId, friend.FriendUserId));
                if (!friendUserClients.Any())
                {
                    continue;
                }

                AsyncHelper.RunSync(() => _chatCommunicator.SendUserConnectionChangeToClients(friendUserClients, user, isConnected));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 发送点对点消息
        /// </summary>
        /// <param name="recipientId"></param>
        /// <param name="chatDetailed"></param>
        /// <param name="severity"></param>
        /// <returns></returns>
        public virtual async Task SendChatAsync(long recipientId, string chatDetailed, NotificationSeverity severity = NotificationSeverity.Info)
        {
            UserIdentifier userIdentifier = new UserIdentifier(AbpSessionExtens.TenantId, recipientId);
            //用户不在线直接返回
            var onlineClients = _onlineClientManager.GetAllByUserId(userIdentifier);

            if (onlineClients == null || onlineClients.Count == 0)
            {
                return;
            }

            UserInfo userModel     = _cacheManagerExtens.GetUserInfoCache(recipientId);
            string   promptContent = "您有一条来自[" + userModel.UserNameCn + "]的消息";
            string   promptTitle   = "您有一条新消息";

            FrameNotificationData frameNotificationData = new FrameNotificationData(promptContent);

            frameNotificationData.NotificationType     = "chat"; //推送的类型用于前端JS判断
            frameNotificationData.Title                = promptTitle;
            frameNotificationData.NotificationDetailed = chatDetailed;
            frameNotificationData.SendId               = AbpSessionExtens.UserId.Value;

            TenantNotification tenantNotification = new TenantNotification()
            {
                Id               = Guid.NewGuid(),
                Data             = frameNotificationData,
                Severity         = severity,
                NotificationName = "站内短信",
                TenantId         = userIdentifier.TenantId,
                CreationTime     = DateTime.Now
            };

            List <UserNotification> userNotification = new List <UserNotification>();

            userNotification.Add(
                new UserNotification
            {
                Id           = Guid.NewGuid(),
                Notification = tenantNotification,
                UserId       = userIdentifier.UserId,
                State        = UserNotificationState.Unread,
                TenantId     = userIdentifier.TenantId
            });

            await _realTimeNotifier.SendNotificationsAsync(userNotification.ToArray());
        }
Exemplo n.º 4
0
        public async Task <FriendDto> CreateFriendshipRequest(CreateFriendshipRequestInput input)
        {
            var userIdentifier = AbpSession.ToUserIdentifier();
            var probableFriend = new UserIdentifier(input.TenantId, input.UserId);

            _chatFeatureChecker.CheckChatFeatures(userIdentifier.TenantId, probableFriend.TenantId);

            if (_friendshipManager.GetFriendshipOrNull(userIdentifier, probableFriend) != null)
            {
                throw new UserFriendlyException(L("YouAlreadySentAFriendshipRequestToThisUser"));
            }

            var user = await UserManager.FindByIdAsync(AbpSession.GetUserId());

            User probableFriendUser;

            using (CurrentUnitOfWork.SetTenantId(input.TenantId))
            {
                probableFriendUser = (await UserManager.FindByIdAsync(input.UserId));
            }

            var friendTenancyName = probableFriend.TenantId.HasValue ? _tenantCache.Get(probableFriend.TenantId.Value).TenancyName : null;
            var sourceFriendship  = new Friendship(userIdentifier, probableFriend, friendTenancyName, probableFriendUser.UserName, probableFriendUser.ProfilePictureId, FriendshipState.Accepted);

            _friendshipManager.CreateFriendship(sourceFriendship);

            var userTenancyName  = user.TenantId.HasValue ? _tenantCache.Get(user.TenantId.Value).TenancyName : null;
            var targetFriendship = new Friendship(probableFriend, userIdentifier, userTenancyName, user.UserName, user.ProfilePictureId, FriendshipState.Accepted);

            _friendshipManager.CreateFriendship(targetFriendship);

            var clients = _onlineClientManager.GetAllByUserId(probableFriend);

            if (clients.Any())
            {
                var isFriendOnline = _onlineClientManager.IsOnline(sourceFriendship.ToUserIdentifier());
                _chatCommunicator.SendFriendshipRequestToClient(clients, targetFriendship, false, isFriendOnline);
            }

            var senderClients = _onlineClientManager.GetAllByUserId(userIdentifier);

            if (senderClients.Any())
            {
                var isFriendOnline = _onlineClientManager.IsOnline(targetFriendship.ToUserIdentifier());
                _chatCommunicator.SendFriendshipRequestToClient(senderClients, sourceFriendship, true, isFriendOnline);
            }

            var sourceFriendshipRequest = sourceFriendship.MapTo <FriendDto>();

            sourceFriendshipRequest.IsOnline = _onlineClientManager.GetAllByUserId(probableFriend).Any();

            return(sourceFriendshipRequest);
        }
Exemplo n.º 5
0
        public async Task MarkAllUnreadMessagesOfUserAsRead(MarkAllUnreadMessagesOfUserAsReadInput input)
        {
            var userId   = AbpSession.GetUserId();
            var tenantId = AbpSession.TenantId;

            // receiver messages
            var messages = await _chatMessageRepository
                           .GetAll()
                           .Where(m =>
                                  m.UserId == userId &&
                                  m.TargetTenantId == input.TenantId &&
                                  m.TargetUserId == input.UserId &&
                                  m.ReadState == ChatMessageReadState.Unread)
                           .ToListAsync();

            if (!messages.Any())
            {
                return;
            }

            foreach (var message in messages)
            {
                message.ChangeReadState(ChatMessageReadState.Read);
            }

            // sender messages
            using (CurrentUnitOfWork.SetTenantId(input.TenantId))
            {
                var reverseMessages = await _chatMessageRepository.GetAll()
                                      .Where(m => m.UserId == input.UserId && m.TargetTenantId == tenantId && m.TargetUserId == userId)
                                      .ToListAsync();

                if (!reverseMessages.Any())
                {
                    return;
                }

                foreach (var message in reverseMessages)
                {
                    message.ChangeReceiverReadState(ChatMessageReadState.Read);
                }
            }

            var userIdentifier   = AbpSession.ToUserIdentifier();
            var friendIdentifier = input.ToUserIdentifier();

            _userFriendsCache.ResetUnreadMessageCount(userIdentifier, friendIdentifier);

            var onlineUserClients = _onlineClientManager.GetAllByUserId(userIdentifier);

            if (onlineUserClients.Any())
            {
                await _chatCommunicator.SendAllUnreadMessagesOfUserReadToClients(onlineUserClients, friendIdentifier);
            }

            var onlineFriendClients = _onlineClientManager.GetAllByUserId(friendIdentifier);

            if (onlineFriendClients.Any())
            {
                await _chatCommunicator.SendReadStateChangeToClients(onlineFriendClients, userIdentifier);
            }
        }
 /// <summary>
 /// Determines whether the specified user is online or not.
 /// </summary>
 /// <param name="onlineClientManager">The online client manager.</param>
 /// <param name="user">User.</param>
 public static bool IsOnline(
     [NotNull] this IOnlineClientManager onlineClientManager,
     [NotNull] UserIdentifier user)
 {
     return(onlineClientManager.GetAllByUserId(user).Any());
 }
Exemplo n.º 7
0
        public Task SendMessageToUser(IUserIdentifier userId, ChatMessage message)
        {
            var senders = _onlineClientManager.GetAllByUserId(userId);

            return(SendMessageToClient(senders, message));
        }