示例#1
0
        public void SendMsg(string msg)
        {
            //{"type":1,"fromId":123,"toId":"8ss_ttkQHMql3M-SFviTFQ","message":"123","dateSent":"2020-05-03T14:22:47.965Z"}
            var message = JsonConvert.DeserializeObject <MessageViewModel>(msg);

            var sender = AllConnectedParticipants.Find(x => x.Participant.Id == message.FromId);

            if (sender != null)
            {
                var groupDestinatary = AllGroupParticipants.Where(x => x.Id == message.ToId).FirstOrDefault();

                if (groupDestinatary != null)
                {
                    // Notify all users in the group except the sender
                    var usersInGroupToNotify = AllConnectedParticipants
                                               .Where(p => p.Participant.Id != sender.Participant.Id &&
                                                      groupDestinatary.ChattingTo.Any(g => g.Id == p.Participant.Id)
                                                      )
                                               .Select(g => g.Participant.Id);

                    Clients.Clients(usersInGroupToNotify.ToList()).SendAsync("messageReceived", groupDestinatary, message);
                }
                else
                {
                    Clients.Client(message.ToId).SendAsync("messageReceived", sender.Participant, message);
                }
            }
        }
示例#2
0
        public void Join(string userName)
        {
            lock (ParticipantsConnectionLock)
            {
                var oldConnectedParticipants = AllConnectedParticipants.Where(x => x.Participant.Id == Context.UserIdentifier);

                if (oldConnectedParticipants.Count() == 0)
                {
                    AllConnectedParticipants.Add(new ParticipantResponseViewModel()
                    {
                        Metadata = new ParticipantMetadataViewModel()
                        {
                            TotalUnreadMessages = 0
                        },
                        Participant = new ChatParticipantViewModel()
                        {
                            DisplayName = userName,
                            Id          = Context.UserIdentifier
                        }
                    });
                }

                // This will be used as the user's unique ID to be used on ng-chat as the connected user.
                // You should most likely use another ID on your application
                Clients.Caller.SendAsync("generatedUserId", Context.UserIdentifier);

                Clients.All.SendAsync("friendsListChanged", AllConnectedParticipants);
            }
        }
示例#3
0
        public void NewMsg(MessageViewModel message)
        {
            var sender = AllConnectedParticipants.Find(x => x.Participant.Id == message.FromId);

            if (sender != null)
            {
                var groupDestinatary = AllGroupParticipants.Where(x => x.Id == message.ToId).FirstOrDefault();

                if (groupDestinatary != null)
                {
                    // Notify all users in the group except the sender
                    var usersInGroupToNotify = AllConnectedParticipants
                                               .Where(p => p.Participant.Id != sender.Participant.Id &&
                                                      groupDestinatary.ChattingTo.Any(g => g.Id == p.Participant.Id)
                                                      )
                                               .Select(g => g.Participant.Id);

                    Clients.Clients(usersInGroupToNotify.ToList()).SendAsync("messageReceived", groupDestinatary, message);
                }
                else
                {
                    Clients.Client(message.ToId).SendAsync("messageReceived", sender.Participant, message);
                }
            }
        }
示例#4
0
        public override Task OnDisconnectedAsync(Exception exception)
        {
            lock (ParticipantsConnectionLock)
            {
                var connectionIndex = AllConnectedParticipants.FindIndex(x => x.Participant.Id == Context.ConnectionId);

                if (connectionIndex >= 0)
                {
                    var participant = AllConnectedParticipants.ElementAt(connectionIndex);

                    var groupsParticipantIsIn = AllGroupParticipants.Where(x => x.ChattingTo.Any(u => u.Id == participant.Participant.Id));

                    RemoveConnect(Context.ConnectionId);
                    AllGroupParticipants.RemoveAll(x => groupsParticipantIsIn.Any(g => g.Id == x.Id));
                    AddDisconnect(participant);

                    //AllConnectedParticipants.Remove(participant);
                    // DisconnectedParticipants.Add(participant);

                    Clients.All.SendAsync("friendsListChanged", AllConnectedParticipants);
                }

                return(base.OnDisconnectedAsync(exception));
            }
        }
示例#5
0
 private IEnumerable <ParticipantResponseViewModel> FilteredGroupParticipants(string currentUserId)
 {
     return(AllConnectedParticipants.ToList()
            .Where(p => p.Participant.ParticipantType == ChatParticipantTypeEnum.User ||
                   AllGroupParticipants.Any(g => g.Id == p.Participant.Id && g.ChattingTo.Any(u => u.Id == currentUserId))
                   ));
 }
示例#6
0
        /// <summary>
        /// Connected handler
        /// Switches user to different pool for connected users and updates his status to online
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            var userId = Context.User.Identity.Name;                                       // fetch id

            DisconnectedParticipants.TryGetValue(userId, out var disconnectedParticipant); // get from disconnected participants
            AllConnectedParticipants.TryGetValue(userId, out var connectedParticipant);    // get from disconnected participants

            if (disconnectedParticipant != null && connectedParticipant == null)
            {
                // if participant exists in disconnected dictionary. Move it to Connected
                disconnectedParticipant.Participant.Status = ChatParticipantStatus.Online;

                DisconnectedParticipants.TryRemove(userId, out var removedParticipant);
                AllConnectedParticipants.TryAdd(userId, removedParticipant);

                await Clients.All.SendAsync("friendsListChanged");
            }

            // if participant doesn't exist in disconnected dict. Fetch user and move it to Connected dictionary
            if (disconnectedParticipant == null && connectedParticipant == null)
            {
                var user = await _mediator.Send(new GetUserRequest(Guid.Parse(userId)));

                var newParticipant = _mapper.Map <ParticipantResponseViewModel>(user);

                newParticipant.Participant.Status = ChatParticipantStatus.Online;

                AllConnectedParticipants.TryAdd(userId, newParticipant);
            }
            // else if connected participant exists.. do nothing because user probably logged in on multiple browsers
        }
示例#7
0
    public void Join(string userName)
    {
        lock (ParticipantsConnectionLock)
        {
            var userId = Context.User.GetClaim(OpenIdConnectConstants.Claims.Subject);
            AllConnectedParticipants.Add(new ChatParticipantViewModel()
            {
                DisplayName  = userName,
                Email        = Context.User.Identity.Name,
                Status       = EnumChatParticipantStatus.Online,
                UserId       = userId,
                HubContextId = Context.ConnectionId
            });

            var chatGrooup = this._ctx.Participants.Include(d => d.User)
                             .Join(
                this._ctx.Participants.Include(d => d.User)
                , p1 => p1.Group.Id, p2 => p2.Group.Id,
                (p1, p2) => new { p2, p1 })
                             .Join(
                AllConnectedParticipants,
                p => p.p2.User.Id, cp => cp.UserId,
                (p, cp) => new { p2 = p.p2, p1 = p.p1, HubContextId = cp.HubContextId }
                )
                             .Where(d => d.p2.Id != d.p1.Id && d.p1.User.Id == userId)
                             .Select(d => d.HubContextId);

            // This will be used as the user's unique ID to be used on ng-chat as the connected user.
            // You should most likely use another ID on your application
            Clients.Caller.SendAsync("generatedUserId", Context.ConnectionId);


            Clients.Clients(chatGrooup.Select(d => d).ToArray()).SendAsync("friendsListChanged", AllConnectedParticipants.Last());
        }
    }
示例#8
0
        public void SendMessage(MessageViewModel message)
        {
            var sender = AllConnectedParticipants.Find(x => x.Participant.Id == message.FromId);

            if (sender != null)
            {
                Clients.Client(message.ToId).SendAsync("messageReceived", sender.Participant, message);
            }
        }
示例#9
0
        /// <summary>
        /// Handler for message sending.
        /// Persists message in database and then sends it through the hub to listeners
        /// </summary>
        /// <param name="message"></param>
        public async Task SendMessage(MessageViewModel message)
        {
            var createRequest = _mapper.Map <MessageViewModel, CreateChatMessageRequest>(message);
            await _mediator.Send(createRequest);

            var sender = AllConnectedParticipants.FirstOrDefault(x => x.Key == message.FromId);

            if (sender.Value != null)
            {
                // get fresh presigned url for display
                message.DownloadUrl = await _s3AccessService.RenewPresignedUrl(message.DownloadUrl, message.S3Filename);

                // send message
                await Clients.User(message.ToId).SendAsync("messageReceived", sender.Value.Participant, message);
            }
        }
示例#10
0
        /// <summary>
        /// Disconnected handler
        /// Switches user to different pool for disconnected users and updates his status to offline
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            var userId = Context.User.Identity.Name;

            AllConnectedParticipants.TryGetValue(userId, out var participant);

            if (participant != null)
            {
                participant.Participant.Status = ChatParticipantStatus.Offline;

                AllConnectedParticipants.TryRemove(userId, out var removedParticipant);
                DisconnectedParticipants.TryAdd(userId, removedParticipant);

                await Clients.All.SendAsync("friendsListChanged");
            }
        }
示例#11
0
    public override Task OnDisconnectedAsync(Exception exception)
    {
        lock (ParticipantsConnectionLock)
        {
            var connectionIndex = AllConnectedParticipants.FindIndex(x => x.HubContextId == Context.ConnectionId);

            if (connectionIndex >= 0)
            {
                var participant = AllConnectedParticipants.ElementAt(connectionIndex);

                AllConnectedParticipants.Remove(participant);

                Clients.All.SendAsync("friendsListChanged", AllConnectedParticipants);
            }

            return(base.OnDisconnectedAsync(exception));
        }
    }
示例#12
0
    public async Task SendMessage(MessageViewModel message)
    {
        var sender = AllConnectedParticipants.Find(x => x.HubContextId == message.FromUser.HubContextId &&
                                                   x.UserId == Context.User.GetClaim(OpenIdConnectConstants.Claims.Subject));

        if (sender != null)
        {
            var userList = await(from p in this._ctx.Participants
                                 where p.Group.Id.ToString() == message.GroupId
                                 select p.User.Id).ToArrayAsync();

            // Notify all users in the group except the sender
            var usersInGroupToNotify = AllConnectedParticipants
                                       .Where(p => p.HubContextId != sender.HubContextId &&
                                              userList.Contains(p.UserId));

            this.insertMessage(usersInGroupToNotify, message, sender);

            Clients.Clients(usersInGroupToNotify.Select(d => d.HubContextId).ToList()).SendAsync("messageReceived", message);
        }
    }
示例#13
0
        public override Task OnConnectedAsync()
        {
            lock (ParticipantsConnectionLock)
            {
                Groups.AddToGroupAsync(Context.ConnectionId, Context.UserIdentifier);

                var connectionIndex = DisconnectedParticipants.FindIndex(x => x.Participant.Id == Context.UserIdentifier);

                if (connectionIndex >= 0)
                {
                    var participant = DisconnectedParticipants.ElementAt(connectionIndex);

                    DisconnectedParticipants.Remove(participant);
                    AllConnectedParticipants.Add(participant);

                    Clients.All.SendAsync("friendsListChanged", AllConnectedParticipants);
                }

                return(base.OnConnectedAsync());
            }
        }
示例#14
0
        public void GroupCreated(GroupChatParticipantViewModel group)
        {
            AllGroupParticipants.Add(group);

            // Pushing the current user to the "chatting to" list to keep track of who's created the group as well.
            // In your application you'll probably want a more sofisticated group persistency and management
            group.ChattingTo.Add(new ChatParticipantViewModel()
            {
                Id = Context.ConnectionId
            });

            AllConnectedParticipants.Add(new ParticipantResponseViewModel()
            {
                Metadata = new ParticipantMetadataViewModel()
                {
                    TotalUnreadMessages = 0
                },
                Participant = group
            });

            Clients.All.SendAsync("friendsListChanged", AllConnectedParticipants);
        }
示例#15
0
        public async Task SendMessage(MessageViewModel message)
        {
            var sender = AllConnectedParticipants.Find(x => x.Participant.Id == message.FromId);

            if (sender != null)
            {
                var destinataryProfile = await _profileRepository.GetDestinataryProfileByAuth0Id(message.ToId);

                var currentUserProfileId = await _profileRepository.GetCurrentProfileIdByAuth0Id(Context.UserIdentifier);

                // If currentUser is on the destinataryProfile's ChatMemberslist AND is blocked then do not go any further.
                if (!destinataryProfile.ChatMemberslist.Any(m => m.ProfileId == currentUserProfileId && m.Blocked == true))
                {
                    var encryptedMessage = _cryptography.Encrypt(message.Message);
                    message.Message = encryptedMessage;

                    await _profileRepository.SaveMessage(message);

                    await _profileRepository.NotifyNewChatMember(Context.UserIdentifier, destinataryProfile.Auth0Id);

                    await Clients.Group(message.ToId).SendAsync("messageReceived", sender.Participant, message);
                }
            }
        }
示例#16
0
 public static IEnumerable <ChatParticipantViewModel> getConnectedParticpant(string UserId)
 {
     return(AllConnectedParticipants.Where(d => d.UserId == UserId));
 }
示例#17
0
 public static IEnumerable <ParticipantResponseViewModel> ConnectedParticipants(string currentUserId)
 {
     return(AllConnectedParticipants
            .Where(x => x.Participant.Id != currentUserId));
 }