Exemplo n.º 1
0
        public async Task ConnectToGame([GameCode] string gameCode, string nickname)
        {
            _logger.LogInformation($"Client with connection id: {Context.ConnectionId} is attempting connection using code: {gameCode} under nickname: {nickname}");
            int.TryParse(Context.Items[KeyConstants.GameCode] as string, out int gameId);
            int?userId = Context.UserIdentifier != null ? (int?)int.Parse(Context.UserIdentifier) : null;

            var playerProfile = await _profileService.CreateOrUpdatePlayerProfile(new PlayerProfileCreateRequest
            {
                GameId   = gameId,
                Nickname = nickname,
                UserId   = userId
            });

            await Clients.Caller.SendPlayerProfileId(playerProfile.Id);

            await Groups.AddToGroupAsync(Context.ConnectionId, gameCode);

            ConnectionObserver.ConnectionStates[Context.ConnectionId] = new PlayerEntry
            {
                Group           = gameCode,
                PlayerProfileId = playerProfile.Id,
                Nickname        = playerProfile.Nickname,
            };
            await Clients.GroupExcept(gameCode, Context.ConnectionId).SendMessage($"Player {playerProfile.Nickname} has joined!", MessageType.Success);

            var playersList = ConnectionObserver.GetPlayersList(gameCode);
            await Clients.Group(gameCode).RefreshPlayersList(playersList);

            var items = await _itemService.GetItemsByGameId(gameId);

            await Clients.Caller.RefreshItemList(items);

            var categories = await _categoryService.GetCategoriesByGameId(gameId);

            await Clients.Caller.RefreshCategories(categories);

            if (_gameService.IsUserGameOwner(userId, gameId))
            {
                await Clients.Caller.AllowGameControl((int)userId);

                await Groups.AddToGroupAsync(Context.ConnectionId, $"{gameCode}-master");
            }
            await Clients.Group($"{gameCode}-master").RequestCurrentItemId(gameCode);

            await Clients.Caller.SendMessage("Game joined successfully", MessageType.Success);
        }