Beispiel #1
0
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            //get praticipant model by connection id
            var participant = await _participantRepo.FindByConnectionIdAsync(Context.ConnectionId);

            if (participant == null)
            {
                return;
            }
            //get room of participant
            var room = await _roomRepo.FindByIdAsync(participant.RoomId);

            if (room == null)
            {
                return;
            }
            // remove participant from the room
            await _participantRepo.RemoveAsync(participant, false);

            var activeParticipants = await _participantRepo
                                     .GetAsync(p => p.RoomId == room.Id);

            //check if there are participants in the room
            if (!activeParticipants.Any())
            {
                await _participantRepo.SaveChangesAsync();

                //if there are no participants in the room, remove room
                await _roomRepo.RemoveAsync(room);

                return;
            }

            var players = activeParticipants
                          .Where(p => p.ParticipantType == ParticipantType.Player)
                          .AsEnumerable();

            //check if there are players in the room
            if (!players.Any())
            {
                //send "Leave Command" for all participants in the room
                //command means that everyone in this room must leave it
                await Clients.Group(room.Name).SendAsync("LeaveCommand");
            }
            else
            {
                await Clients.Group(room.Name).SendAsync("Leave", participant.Adapt <ParticipantViewModel>());
            }
            await _participantRepo.SaveChangesAsync();
        }