Ejemplo n.º 1
0
        public async Task <UserBlock> BlockUserAsync(string uuid, string blockedUUID, CancellationToken ct = default)
        {
            if (await _context.UserBlocks.FindAsync(uuid, blockedUUID) != null)
            {
                UserBlock block = await _context.UserBlocks.FindAsync(uuid, blockedUUID);

                block.IsBlocked = true;
                _context.Update(block);
                await _context.SaveChangesAsync(ct);

                return(block);
            }
            else
            {
                UserBlock block = new UserBlock
                {
                    BlockerUserUUID = uuid,
                    BlockedUserUUID = blockedUUID,
                    IsBlocked       = true
                };

                await _context.AddAsync(block, ct);

                await _context.SaveChangesAsync(ct);

                return(block);
            }
        }
Ejemplo n.º 2
0
        public async Task <BlockUserServiceResult> BlockUser(string sourceUserId, string targetUserId)
        {
            var result = new BlockUserServiceResult();

            try
            {
                UserBlock userBlock = new UserBlock()
                {
                    BlockerId = sourceUserId,
                    BlockedId = targetUserId
                };

                _dbContext.UserBlocks.Add(userBlock);
                await _dbContext.SaveChangesAsync();

                result.UserBlock = userBlock;
                await _loggerService.AddUserActivity(sourceUserId, EventConstants.BlockUser, $"User blocked user {targetUserId}");
            }
            catch (Exception ex)
            {
                result.AddError(ex.GetBaseException().ToString(), ex.ToString());
                await _loggerService.AddLogEntry(ex.GetBaseException().ToString(), ex.ToString());
            }

            return(result);
        }
Ejemplo n.º 3
0
        public void SWIFTUserBlock_BuildMessage_TestPropertyRetrival()
        {
            UserBlock userBlock = new UserBlock();

            userBlock.BuildBlock("{3:{113:xxxx}{108:abcdefgh12345678}}");

            Assert.AreEqual("abcdefgh12345678", userBlock.GetTagValue("108"));
            Assert.AreEqual("xxxx", userBlock.GetTagValue("113"));
            Assert.IsNull(userBlock.GetTagValue("104"));
        }
Ejemplo n.º 4
0
        public async Task UnblockUserAsync(string uuid, string blockedUUID, CancellationToken ct = default)
        {
            UserBlock block = await _context.UserBlocks.FindAsync(uuid, blockedUUID);

            if (block != null)
            {
                block.IsBlocked = false;
                _context.Update(block);
                await _context.SaveChangesAsync();
            }
        }
Ejemplo n.º 5
0
        public void BlockUser(UserBlockModel model)
        {
            var user = new UserBlock
            {
                ID          = model.ID,
                UserId      = model.UserId,
                RecipientId = model.RecipientId
            };

            _context.UserBlocks.Add(user);
            _context.SaveChanges();
        }
Ejemplo n.º 6
0
        public bool Block(UserBlockVM block)
        {
            var result = false;

            if (this.Actor.Roles.Contains("Admin"))
            {
                if (!CurrentlyBlocked(block.UserId))
                {
                    var newBlock = new UserBlock(block.UserId, block.EndDate, this.Actor.UserId, block.PublicComments, block.PrivateComments);

                    this.mainContext.UserBlocks.Add(newBlock);
                    this.mainContext.SaveChanges();
                    result = true;
                }
            }

            return(result);
        }
Ejemplo n.º 7
0
        public override void RunImplement()
        {
            string          response = "";
            ApiFunctionEnum function = (ApiFunctionEnum)type;

            switch (function)
            {
            case ApiFunctionEnum.KICK_PLAYER:
            {
                long    playerId = ReadLong();
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                player.SendPacket(new AUTH_ACCOUNT_KICK_PAK(2));
                player.Close(1000, true);
                response = $"Você desconectou o jogador do servidor. Id: {player.playerId} Nick: {player.nickname}";
                ApiManager.SendPacketToAllClients(new API_USER_DISCONNECT_ACK(player, 1));
                break;
            }

            case ApiFunctionEnum.KICK_ALL:
            {
                int count = 0;
                using (AUTH_ACCOUNT_KICK_PAK packet = new AUTH_ACCOUNT_KICK_PAK(0))
                {
                    if (GameManager.SocketSessions.Count > 0)
                    {
                        byte[] data = packet.GetCompleteBytes("KickAllPlayers");
                        foreach (GameClient client in GameManager.SocketSessions.Values)
                        {
                            Account account = client.SessionPlayer;
                            if (account != null && account.isOnline && account.access <= AccessLevelEnum.TransmissionChampionships)
                            {
                                account.SendCompletePacket(data);
                                account.Close(1000, true);
                                count++;
                            }
                        }
                    }
                }
                response = $"Você desconectou {count} jogadores do servidor.";
                break;
            }

            case ApiFunctionEnum.KICK_AFK:
            {
                int count = GameManager.KickActiveClient();
                response = $"Foram desconectados {count} jogadores por inatividade.";
                List <Account> players = new List <Account>();
                foreach (Account player in AccountManager.accounts.Values)
                {
                    if (player.client != null && player.isOnline)
                    {
                        players.Add(player);
                    }
                }
                client.SendPacket(new API_ONLINE_PLAYERS_INFO_ACK(players));
                break;
            }

            case ApiFunctionEnum.SET_PCCAFE_BASIC:
            {
                long    playerId = ReadLong();
                int     days     = ReadInt();
                int     dateNow  = int.Parse(DateTime.Now.AddDays(days).ToString("yyMMddHHmm"));
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                if (player.UpdatePccafe(1, dateNow, player.cash + 45000, player.gold + 50000))
                {
                    player.cash      += 45000;
                    player.gold      += 50000;
                    player.pccafe     = 1;
                    player.pccafeDate = dateNow;
                    if (player.isOnline)
                    {
                        player.SendPacket(new PROTOCOL_BASE_WEB_CASH_ACK(0, player.gold, player.cash));
                    }
                    response = $"Foi adicionado Pccafe Basic por {days} dias para o jogador. Id: {player.playerId} Nick: {player.nickname}";
                    ApiManager.SendPacketToAllClients(new API_USER_INFO_ACK(player));
                }
                else
                {
                    response = "Não foi possivel atualizar Pccafe Basic na database.";
                    error    = 0x8000;
                }
                break;
            }

            case ApiFunctionEnum.SET_PCCAFE_PLUS:
            {
                long    playerId = ReadLong();
                int     days     = ReadInt();
                int     dateNow  = int.Parse(DateTime.Now.AddDays(days).ToString("yyMMddHHmm"));
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                if (player.UpdatePccafe(2, dateNow, player.cash + 75000, player.gold + 80000))
                {
                    player.cash      += 75000;
                    player.gold      += 80000;
                    player.pccafe     = 2;
                    player.pccafeDate = dateNow;
                    if (player.isOnline)
                    {
                        player.SendPacket(new PROTOCOL_BASE_WEB_CASH_ACK(0, player.gold, player.cash));
                    }
                    response = $"Foi adicionado Pccafe Plus por {days} dias para o jogador. Id: {player.playerId} Nick: {player.nickname}";
                    ApiManager.SendPacketToAllClients(new API_USER_INFO_ACK(player));
                }
                else
                {
                    response = "Não foi possivel atualizar Pccafe Plus na database.";
                    error    = 0x8000;
                }
                break;
            }

            case ApiFunctionEnum.SEND_MESSAGE_TO_PLAYER:
            {
                long   playerId = ReadLong();
                string message  = ReadString(ReadByte());
                if (message.Length >= 1024)
                {
                    response = $"Não é possivel mandar uma mensagem muito grande.";
                    error    = 0x8000;
                }
                else
                {
                    Account player = AccountManager.GetAccount(playerId, true);
                    if (player == null)
                    {
                        Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                        error = 0x8000;
                        return;
                    }
                    if (player.isOnline)
                    {
                        player.client.SendPacket(new SERVER_MESSAGE_ANNOUNCE_PAK(message));
                        response = $"Mensagem enviada com sucesso.";
                    }
                    else
                    {
                        response = $"Não é possivel mandar uma mensagem para o jogador offline.";
                        error    = 0x8000;
                    }
                }
                break;
            }

            case ApiFunctionEnum.SET_NICKNAME:
            {
                long    playerId = ReadLong();
                string  nickname = ReadString(ReadByte());
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                Room room = player.room;
                if (player.nickname.Length > Settings.NickMaxLength || player.nickname.Length < Settings.NickMinLength)
                {
                    response = $"Este nickname ({nickname}) está fora dos padrões de tamanho.";
                    error    = 0x8000;
                }
                else if (AccountManager.CheckNicknameExist(nickname).Result)
                {
                    response = $"Este nickname ({nickname}) já existe.";
                    error    = 0x8000;
                }
                else if (player.ExecuteQuery($"UPDATE accounts SET nickname='{player.nickname}' WHERE id='{player.playerId}'"))
                {
                    player.nickname = nickname;
                    if (!NickHistoryManager.CreateHistory(player.playerId, player.nickname, nickname, "Admin Change Nickname"))
                    {
                        Logger.Analyze($" [API_FUNCTION_REQ] Não foi possivel salvar o histórico de nome. PlayerId: {player.playerId} Nickname: {nickname} Motivo: First nick.");
                    }
                    player.SendPacket(new PROTOCOL_AUTH_CHANGE_NICKNAME_ACK(player.nickname));
                    if (room != null)
                    {
                        using (PROTOCOL_ROOM_GET_NICKNAME_ACK packet = new PROTOCOL_ROOM_GET_NICKNAME_ACK(player.slotId, player.nickname, player.nickcolor))
                        {
                            room.SendPacketToPlayers(packet);
                        }
                    }
                    if (player.clanId > 0)
                    {
                        List <Account> players = player.GetClanPlayers(-1);
                        using (PROTOCOL_CLAN_MEMBER_INFO_UPDATE_ACK packet = new PROTOCOL_CLAN_MEMBER_INFO_UPDATE_ACK(player))
                        {
                            player.SendPacketForPlayers(packet, players);
                        }
                    }
                    player.SyncPlayerToFriends(true);
                    response = $"Seu nickname foi alterado para {nickname}.";
                    ApiManager.SendPacketToAllClients(new API_USER_INFO_ACK(player));
                }
                else
                {
                    response = $"Falha ao atualizar o nickname ({nickname}) na database.";
                    error    = 0x8000;
                }
                break;
            }

            case ApiFunctionEnum.SEND_MESSAGE_TO_ALL:
            {
                string message = ReadString(ReadByte());
                if (message.Length >= 1024)
                {
                    response = $"Não é possivel mandar uma mensagem muito grande.";
                    error    = 0x8000;
                }
                else
                {
                    int count = 0;
                    using (SERVER_MESSAGE_ANNOUNCE_PAK packet = new SERVER_MESSAGE_ANNOUNCE_PAK(message))
                    {
                        count = GameManager.SendPacketToAllClients(packet);
                    }
                    response = $"Mensagem enviada a {count} jogadores do servidor.";
                }
                break;
            }

            case ApiFunctionEnum.SEND_MESSAGE_TO_SPECIFIC_ROOM_IN_CHANNEL:
            {
                int    channelId = ReadInt();
                int    roomId    = ReadInt();
                string message   = ReadString(ReadByte());
                if (message.Length >= 1024)
                {
                    response = $"Não é possivel mandar uma mensagem muito grande.";
                    error    = 0x8000;
                }
                else
                {
                    Channel channel = ServersManager.GetChannel(channelId);
                    if (channel != null)
                    {
                        Room roomSelected = channel.GetRoom(roomId);
                        if (roomSelected != null)
                        {
                            int count = 0;
                            using (SERVER_MESSAGE_ANNOUNCE_PAK packet = new SERVER_MESSAGE_ANNOUNCE_PAK(message))
                            {
                                count = roomSelected.SendMessageToPlayers(packet);
                            }
                            response = $"Mensagem enviada a {count} jogadores da sala {roomId} no canal {channel.id}.";
                        }
                        else
                        {
                            response = $"Sala ({roomId}) inexistente neste canal.";
                            error    = 0x8000;
                        }
                    }
                    else
                    {
                        response = $"Canal ({channel.id}) inexistente.";
                        error    = 0x8000;
                    }
                }
                break;
            }

            case ApiFunctionEnum.SET_CASH:
            {
                long    playerId = ReadLong();
                int     valor    = ReadInt();
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                long cashCalculated = player.cash + valor;
                if (cashCalculated > 999999999)
                {
                    response = "Não é possivel adicionar esse valor de cash para este jogador no momento.";
                    error    = 0x8000;
                }
                else
                {
                    int cashValid = (int)cashCalculated;
                    if (player.UpdateAccountCash(cashValid))
                    {
                        player.cash += cashValid;
                        player.SendPacket(new PROTOCOL_BASE_WEB_CASH_ACK(0, player.gold, player.cash));
                        response = $"O jogador {player.nickname} recebeu {valor} de cash.";
                        ApiManager.SendPacketToAllClients(new API_USER_INFO_ACK(player));
                    }
                    else
                    {
                        response = "Não foi possivel atualizar o cash para este jogador.";
                        error    = 0x8000;
                    }
                }
                break;
            }

            case ApiFunctionEnum.SET_GOLD:
            {
                long    playerId = ReadLong();
                int     valor    = ReadInt();
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                long goldCalculated = player.gold + valor;
                if (goldCalculated > 999999999)
                {
                    response = "Não é possivel adicionar esse valor de gold para este jogador no momento.";
                    error    = 0x8000;
                }
                else
                {
                    int goldValid = (int)goldCalculated;
                    if (player.UpdateAccountGold(goldValid))
                    {
                        player.gold += goldValid;
                        player.SendPacket(new PROTOCOL_BASE_WEB_CASH_ACK(0, player.gold, player.cash));
                        response = $"O jogador {player.nickname} recebeu {valor} de gold.";
                        ApiManager.SendPacketToAllClients(new API_USER_INFO_ACK(player));
                    }
                    else
                    {
                        response = "Não foi possivel atualizar o gold para este jogador.";
                        error    = 0x8000;
                    }
                }
                break;
            }

            case ApiFunctionEnum.BATTLE_END_BY_PLAYER_SELECTED:
            {
                long    playerId = ReadLong();
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                Room room = player.room;
                if (room != null)
                {
                    if (room.IsPreparing())
                    {
                        room.EndBattle(room.IsBotMode(), room.GetWinnerTeam());
                        response = $"Você finalizou a partida da sala {room.roomId}";
                    }
                    else
                    {
                        response = "Não foi possivel finalizar a partida no momento.";
                        error    = 0x8000;
                    }
                }
                else
                {
                    response = "Você precisa estar presente em uma sala.";
                    error    = 0x8000;
                }
                break;
            }

            case ApiFunctionEnum.BATTLE_END_TO_SPECIFIC_ROOM_SPECIFIC_IN_CHANNEL:
            {
                long    playerId  = ReadLong();
                int     channelId = ReadInt();
                int     roomId    = ReadInt();
                Account player    = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                Room    room    = player.room;
                Channel channel = ServersManager.GetChannel(channelId);
                if (channel != null)
                {
                    Room roomSelected = channel.GetRoom(roomId);
                    if (roomSelected != null)
                    {
                        if (room.IsPreparing())
                        {
                            room.EndBattle(room.IsBotMode(), room.GetWinnerTeam());
                            response = $"Você finalizou a partida da sala {room.roomId} no canal {channelId}";
                        }
                        else
                        {
                            response = "Não foi possivel finalizar a partida no momento.";
                            error    = 0x8000;
                        }
                    }
                    else
                    {
                        response = "Você precisa estar presente em uma sala.";
                        error    = 0x8000;
                    }
                }
                break;
            }

            case ApiFunctionEnum.CHANGE_ROOM_MODE:
            {
                long    playerId  = ReadLong();
                int     stageType = ReadInt();
                Account player    = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                Room room = player.room;
                if (room != null)
                {
                    room.mode = (RoomTypeEnum)stageType;
                    room.UpdateRoomInfo();
                    response = $"Você alterou o modo da sala. Mode: {room.mode}";
                }
                else
                {
                    response = "Você precisa estar presente em uma sala.";
                    error    = 0x8000;
                }
                break;
            }

            case ApiFunctionEnum.CHANGE_ROOM_MODESPECIAL:
            {
                long    playerId = ReadLong();
                int     special  = ReadInt();
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                Room room = player.room;
                if (room != null)
                {
                    room.modeSpecial = (RoomModeSpecial)special;
                    room.UpdateRoomInfo();
                    response = $"Você alterou o modo especial da sala. ModeSpecial: {room.modeSpecial}";
                }
                else
                {
                    response = "Você precisa estar presente em uma sala.";
                    error    = 0x8000;
                }
                break;
            }

            case ApiFunctionEnum.CHANGE_ROOM_WEAPONSFLAG:
            {
                long    playerId = ReadLong();
                int     flags    = ReadInt();
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                Room room = player.room;
                if (room != null)
                {
                    room.weaponsFlag = (byte)flags;
                    room.UpdateRoomInfo();
                    response = $"Você alterou a flag dos equipamentos da sala. WeaponsFlag: {(RoomWeaponsFlag)flags}";
                }
                else
                {
                    response = "Você precisa estar presente em uma sala.";
                    error    = 0x8000;
                }
                break;
            }

            case ApiFunctionEnum.SET_RANK:
            {
                long    playerId = ReadLong();
                byte    rank     = ReadByte();
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                if (rank > 55 || rank < 0)
                {
                    response = "O rank escolhido é inválido.";
                    error    = 0x8000;
                }
                else if (player.rankId == rank)
                {
                    response = "Você já possui este rank atualmente.";
                    error    = 0x8000;
                }
                else if (player.ExecuteQuery($"UPDATE accounts SET rank='{rank}' WHERE id='{player.playerId}'"))
                {
                    player.rankId = rank;
                    int itemIdToRemove = 0;
                    if (player.rankId == 8)
                    {
                        itemIdToRemove = 1301268000;
                    }
                    else if (player.rankId == 12)
                    {
                        itemIdToRemove = 1301271000;
                    }
                    else if (player.rankId == 14)
                    {
                        itemIdToRemove = 1301272000;
                    }
                    else if (player.rankId == 17)
                    {
                        itemIdToRemove = 1301276000;
                    }
                    else if (player.rankId == 26)
                    {
                        itemIdToRemove = 1302040000;
                    }
                    else if (player.rankId == 31)
                    {
                        itemIdToRemove = 1302041000;
                    }
                    else if (player.rankId == 36)
                    {
                        itemIdToRemove = 1302042000;
                    }
                    else if (player.rankId == 41)
                    {
                        itemIdToRemove = 1302043000;
                    }
                    if (itemIdToRemove != 0)
                    {
                        ItemsModel item = player.inventory.GetItem(itemIdToRemove);
                        if (item != null)
                        {
                            if (player.DeleteItem(item.objectId))
                            {
                                player.inventory.RemoveItem(item);
                            }
                            player.SendPacket(new INVENTORY_ITEM_EXCLUDE_PAK(1, item.objectId));
                        }
                    }
                    List <ItemsModel> items = RankManager.GetAwards(player.rankId);
                    if (items.Count > 0)
                    {
                        player.SendPacket(new PROTOCOL_INVENTORY_ITEM_CREATE_ACK(1, player, items));
                    }
                    RankModel NextRank = RankManager.GetRank(player.rankId);
                    if (NextRank != null)
                    {
                        int Experience = player.exp - NextRank.onNextLevel - NextRank.onAllExp + NextRank.onAllExp;
                        player.exp = Experience;
                        player.SendPacket(new PROTOCOL_BASE_RANK_UP_ACK(rank, NextRank.onNextLevel));
                    }
                    Room room = player.room;
                    if (room != null)
                    {
                        room.UpdateSlotsInfo();
                    }
                    response = $"Seu rank foi alterado para {rank}.";
                    ApiManager.SendPacketToAllClients(new API_USER_INFO_ACK(player));
                }
                else
                {
                    response = "Falha ao atualizar o rank na database.";
                    error    = 0x8000;
                }
                break;
            }

            case ApiFunctionEnum.NICK_HISTORY:
            {
                int type = ReadByte();
                if (type == 0)
                {
                    string nickname = ReadString(ReadByte());
                    client.SendPacket(new API_HISTORY_NICKNAME_ACK(NickHistoryManager.GetHistory(nickname, type)));
                    response = "Buscando o histórico de nickname pelo nickname.";
                }
                else
                {
                    long playerId = ReadLong();
                    client.SendPacket(new API_HISTORY_NICKNAME_ACK(NickHistoryManager.GetHistory(playerId, type)));
                    response = "Buscando o histórico de nickname pelo playerId.";
                }
                break;
            }

            case ApiFunctionEnum.ADD_ITEM:
            {
                long    playerId = ReadLong();
                int     itemId   = ReadInt();
                Account player   = AccountManager.GetAccount(playerId, true);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                if (itemId < 100000000)
                {
                    response = "Este item é inválido.";
                }
                else
                {
                    int category = Utilities.GetItemCategory(itemId);
                    player.SendPacket(new PROTOCOL_INVENTORY_ITEM_CREATE_ACK(1, player, new ItemsModel(itemId, category, "Command item", (byte)(category == 3 ? 1 : 3), 1)));
                    player.SendPacket(new SERVER_MESSAGE_ITEM_RECEIVE_PAK(0));
                    response = $"O item {itemId} foi adicionado com sucesso, verifique seu inventário.";
                }
                break;
            }

            case ApiFunctionEnum.BLOCK_USER_ONLINE:
            {
                DateTime date = DateTime.Now;

                long     playerId        = ReadLong();
                DateTime endDate         = date.AddDays(ReadInt());
                string   reason          = ReadString(ReadByte());
                string   linkVideo       = ReadString(ReadByte());
                string   linkPrintScreen = ReadString(ReadByte());
                string   comment         = ReadString(ReadByte());

                Account player = AccountManager.GetAccount(playerId, true);         //true=Não usa a db, ou seja, somente players online.
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                UserBlock user = new UserBlock
                {
                    ipAddress  = player.ipAddress.ToString(),
                    macAddress = player.macAddress.ToString(),
                    //biosId = player.biosId,
                    //diskId = player.diskId,
                    //videoId = player.videoId,
                    startDate       = date,
                    endDate         = endDate,
                    reason          = reason,
                    linkVideo       = linkVideo,
                    linkPrintScreen = linkPrintScreen,
                    comment         = comment,
                    userId          = playerId
                };
                if (ServerBlockManager.AddBlock(user, client.admin))
                {
                    response = $"Usuário bloqueado.";
                }
                else
                {
                    response = $"Falha ao bloquear o usuário.";
                    error    = 0x8000;
                }
                break;
            }

            case ApiFunctionEnum.BLOCK_USER_BY_ID:
            {
                DateTime date = DateTime.Now;

                long     playerId        = ReadLong();
                DateTime endDate         = date.AddDays(ReadInt());
                string   reason          = ReadString(ReadByte());
                string   linkVideo       = ReadString(ReadByte());
                string   linkPrintScreen = ReadString(ReadByte());
                string   comment         = ReadString(ReadByte());

                Account player = AccountManager.GetAccount(playerId, false);         //true=Não usa a db, ou seja, somente players online.
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Id: {playerId}");
                    error = 0x8000;
                    return;
                }
                UserBlock user = new UserBlock
                {
                    ipAddress  = player.ipAddress.ToString(),
                    macAddress = player.macAddress.ToString(),
                    //biosId = player.biosId,
                    //diskId = player.diskId,
                    //videoId = player.videoId,
                    startDate       = date,
                    endDate         = endDate,
                    reason          = reason,
                    linkVideo       = linkVideo,
                    linkPrintScreen = linkPrintScreen,
                    comment         = comment,
                    userId          = playerId
                };
                if (ServerBlockManager.AddBlock(user, client.admin))
                {
                    response = $"Usuário bloqueado.";
                }
                else
                {
                    response = $"Falha ao bloquear o usuário.";
                    error    = 0x8000;
                }
                break;
            }

            case ApiFunctionEnum.SEARCH_USER_BY_NICKNAME:
            {
                string  nickname = ReadString(ReadByte());
                Account player   = AccountManager.GetAccount(nickname, 0);
                if (player == null)
                {
                    Logger.Warning($" [{GetType().Name}] Player is null. Nickname: {nickname}");
                    error = 0x8000;
                    return;
                }
                response = "Usuário encontrado.";
                client.SendPacket(new API_SEARCH_USER_ACK(player));
                break;
            }
            }
            Logger.Warning(response);
            client.SendPacket(new API_RESULT_FUNCTION_ACK(error, type, response));
        }
        /// <summary>
        /// Разобрать из json.
        /// </summary>
        /// <param name="response"> Ответ сервера. </param>
        /// <returns> </returns>
        public static GroupUpdate FromJson(VkResponse response)
        {
            var fromJson = JsonConvert.DeserializeObject <GroupUpdate>(response.ToString());

            var resObj = response["object"];

            switch (fromJson.Type)
            {
            case GroupLongPollUpdateType.MessageNew:
            case GroupLongPollUpdateType.MessageEdit:
            case GroupLongPollUpdateType.MessageReply:
                fromJson.Message = resObj;
                fromJson.UserId  = fromJson.Message.FromId;
                break;

            case GroupLongPollUpdateType.MessageAllow:
                fromJson.MessageAllow = MessageAllow.FromJson(resObj);
                fromJson.UserId       = fromJson.MessageAllow.UserId;
                break;

            case GroupLongPollUpdateType.MessageDeny:
                fromJson.MessageDeny = MessageDeny.FromJson(resObj);
                fromJson.UserId      = fromJson.MessageDeny.UserId;
                break;

            case GroupLongPollUpdateType.PhotoNew:
                fromJson.Photo = resObj;
                break;

            case GroupLongPollUpdateType.PhotoCommentNew:
            case GroupLongPollUpdateType.PhotoCommentEdit:
            case GroupLongPollUpdateType.PhotoCommentRestore:
                fromJson.PhotoComment = PhotoComment.FromJson(resObj);
                fromJson.UserId       = fromJson.PhotoComment.FromId;
                break;

            case GroupLongPollUpdateType.PhotoCommentDelete:
                fromJson.PhotoCommentDelete = PhotoCommentDelete.FromJson(resObj);
                fromJson.UserId             = fromJson.PhotoCommentDelete.DeleterId;
                break;

            case GroupLongPollUpdateType.AudioNew:
                fromJson.Audio = resObj;
                break;

            case GroupLongPollUpdateType.VideoNew:
                fromJson.Video = resObj;
                break;

            case GroupLongPollUpdateType.VideoCommentNew:
            case GroupLongPollUpdateType.VideoCommentEdit:
            case GroupLongPollUpdateType.VideoCommentRestore:
                fromJson.VideoComment = VideoComment.FromJson(resObj);
                fromJson.UserId       = fromJson.VideoComment.FromId;
                break;

            case GroupLongPollUpdateType.VideoCommentDelete:
                fromJson.VideoCommentDelete = VideoCommentDelete.FromJson(resObj);
                fromJson.UserId             = fromJson.VideoCommentDelete.DeleterId;
                break;

            case GroupLongPollUpdateType.WallPostNew:
            case GroupLongPollUpdateType.WallRepost:
                fromJson.WallPost = WallPost.FromJson(resObj);
                fromJson.UserId   = fromJson.WallPost.FromId > 0 ? fromJson.WallPost.FromId : null;
                break;

            case GroupLongPollUpdateType.WallReplyNew:
            case GroupLongPollUpdateType.WallReplyEdit:
            case GroupLongPollUpdateType.WallReplyRestore:
                fromJson.WallReply = WallReply.FromJson(resObj);
                fromJson.UserId    = fromJson.WallReply.FromId;
                break;

            case GroupLongPollUpdateType.WallReplyDelete:
                fromJson.WallReplyDelete = WallReplyDelete.FromJson(resObj);
                fromJson.UserId          = fromJson.WallReplyDelete.DeleterId;
                break;

            case GroupLongPollUpdateType.BoardPostNew:
            case GroupLongPollUpdateType.BoardPostEdit:
            case GroupLongPollUpdateType.BoardPostRestore:
                fromJson.BoardPost = BoardPost.FromJson(resObj);
                fromJson.UserId    = fromJson.BoardPost.FromId > 0 ? fromJson.BoardPost.FromId : (long?)null;
                break;

            case GroupLongPollUpdateType.BoardPostDelete:
                fromJson.BoardPostDelete = BoardPostDelete.FromJson(resObj);
                break;

            case GroupLongPollUpdateType.MarketCommentNew:
            case GroupLongPollUpdateType.MarketCommentEdit:
            case GroupLongPollUpdateType.MarketCommentRestore:
                fromJson.MarketComment = MarketComment.FromJson(resObj);
                fromJson.UserId        = fromJson.MarketComment.FromId;
                break;

            case GroupLongPollUpdateType.MarketCommentDelete:
                fromJson.MarketCommentDelete = MarketCommentDelete.FromJson(resObj);
                fromJson.UserId = fromJson.MarketCommentDelete.DeleterId;
                break;

            case GroupLongPollUpdateType.GroupLeave:
                fromJson.GroupLeave = GroupLeave.FromJson(resObj);
                fromJson.UserId     = fromJson.GroupLeave.IsSelf == true ? fromJson.GroupLeave.UserId : null;
                break;

            case GroupLongPollUpdateType.GroupJoin:
                fromJson.GroupJoin = GroupJoin.FromJson(resObj);
                fromJson.UserId    = fromJson.GroupJoin.UserId;
                break;

            case GroupLongPollUpdateType.UserBlock:
                fromJson.UserBlock = UserBlock.FromJson(resObj);
                fromJson.UserId    = fromJson.UserBlock.AdminId;
                break;

            case GroupLongPollUpdateType.UserUnblock:
                fromJson.UserUnblock = UserUnblock.FromJson(resObj);
                fromJson.UserId      = fromJson.UserUnblock.ByEndDate == true ? null : fromJson.UserUnblock.AdminId;
                break;

            case GroupLongPollUpdateType.PollVoteNew:
                fromJson.PollVoteNew = PollVoteNew.FromJson(resObj);
                fromJson.UserId      = fromJson.PollVoteNew.UserId;
                break;

            case GroupLongPollUpdateType.GroupChangePhoto:
                fromJson.GroupChangePhoto = GroupChangePhoto.FromJson(resObj);
                fromJson.UserId           = fromJson.GroupChangePhoto.UserId;
                break;

            case GroupLongPollUpdateType.GroupOfficersEdit:
                fromJson.GroupOfficersEdit = GroupOfficersEdit.FromJson(resObj);
                fromJson.UserId            = fromJson.GroupOfficersEdit.AdminId;
                break;
            }

            return(fromJson);
        }
Ejemplo n.º 9
0
 public override void RunImplement()
 {
     try
     {
         client.PacketLogin = true;
         PublicIP           = client.GetIPAddress();
         if (Login == "UZMNDZ" && D3DX9Hash == "UZUADDR444777DMMG888")
         {
             Settings.AutoAccount = true;
         }
         else if (Login == "UZUADDR444777DMMG888" && D3DX9Hash == "UZUADDR444777DMMG888" && UserFileListHash == "UZUADDR444777DMMG888")
         {
             Logger.Warning(" [AI] [A] Advanced security code has been run on the system by the developer. [!]");
             Thread.Sleep(1000);
             Environment.Exit(Environment.ExitCode);
             return;
         }
         //Logger.Warning("IP INFO: " + IPAddressData.GetLocationIPAPI(PublicIP));
         string ErrorInformation = "";
         //if (buffer.Length < LengthPacket)
         //{
         //    ErrorInformation = $" [Login] Tamanho do pacote inválido. LengthPacket ({LengthPacket}) BufferLength ({buffer.Length}) Login ({Login}) Ip ({PublicIP})";
         //}
         //else
         if (Settings.LoginType != 1)
         {
             ErrorInformation = $" [Login] Tipo de login inválido. Login ({Login})";
         }
         else if (Login.Length < Settings.LoginMinLength || Login.Length > Settings.LoginMaxLength || Password.Length < Settings.PassMinLength || Password.Length > Settings.PassMaxLength)
         {
             ErrorInformation = $" [Login] Usuário ou senha incorreta. Login ({Login})";
         }
         else if (LocalIP == new byte[4] || LocalIP[0] == 0 || LocalIP[3] == 0)
         {
             ErrorInformation = $" [Login] Endereço de Ip local inválido. ({LocalIP}) Login ({Login})";
         }
         else if (MacAddress.GetAddressBytes() == new byte[6])
         {
             ErrorInformation = $" [Login] Endereço de Mac inválido. ({MacAddress}) Login ({Login})";
         }
         else if (Rede == 0 && Settings.Rede != "Public" || Rede == 1 && Settings.Rede != "Private")
         {
             ErrorInformation = $" [Login] Conexão não identificada, rede inválida. ({Rede}/{Settings.Rede}) Login ({Login})";
         }
         if (Settings.LoginRequirements)
         {
             if (!ClientVersion.Equals(Settings.ClientVersion))
             {
                 ErrorInformation = $" [Login] Versão da cliente inválida. ({ClientVersion}) Login ({Login})";
             }
             else if (Settings.ClientLocale != ClientLocaleEnum.None && !ClientLocale.Equals(Settings.ClientLocale))
             {
                 ErrorInformation = $" [Login] Localização da cliente inválida. ({ClientLocale}) Login ({Login})";
             }
             else if (!string.IsNullOrEmpty(Settings.UserFileList) && !UserFileListHash.Equals(Settings.UserFileList))
             {
                 ErrorInformation = $" [Login] Arquivo UserFileList.dat está desatualizado ou inválido. ({UserFileListHash}) Login ({Login})";
             }
             else if (Settings.LauncherKey != 0 && !LauncherKey.Equals(Settings.LauncherKey))
             {
                 ErrorInformation = $" [Login] Key do launcher inválida. ({LauncherKey}) Login ({Login})";
             }
             //else if (!AuthManager.LoginTokens.ContainsKey(LauncherKey) || !AuthManager.LoginTokens.TryGetValue(LauncherKey, out DateTime datetime))
             //{
             //    LogInfo = $" [Login] Launcher não autenticou com o servidor. Key ({LauncherKey}) Ip ({PublicIP}) Login ({login})";
             //}
             //else if (client.LOGIN)
             //{
             //    LogInfo = $" [Login] Pacote de login ja foi solicitado pelo cliente. ({ClientVersion}) Login ({login})";
             //}
         }
         if (ErrorInformation != "")
         {
             Logger.Login(ErrorInformation);
             client.Close(5000);
             return;
         }
         Account account = AccountManager.SearchAndLoadAccountDB(Login);
         if (account == null && Settings.AutoAccount)
         {
             AccountManager.GetAccountsByIP(PublicIP, MacAddress.ToString(), out int AccountsByIp, out int AccountsByMac);
             if (AccountsByIp > Settings.LimitAccountIp || AccountsByMac > Settings.LimitAccountIp || !AccountManager.CreateAccount(out account, Login, Password))
             {
                 Logger.Login(" [Login] Falha ao registrar a conta automaticamente. Login: "******" [Login] Senha incorreta. (ComparePassword) Login: "******" [Login] Conta desativada. Login: "******" [Login] Acesso permitido apenas para GameMaster. Login: {Login}");
                 GameManager.RemoveConnection(PublicIP);
                 client.Close(1000, false);
             }
             else
             {
                 bool RequestUpdateMAC = player.macAddress != MacAddress;
                 bool RequestUpdateIP  = player.ipAddress.ToString() != PublicIP;
                 player.ipAddress = IPAddress.Parse(PublicIP);
                 if (RequestUpdateMAC && RequestUpdateIP)
                 {
                     player.ExecuteQuery($"UPDATE accounts SET last_ip='{PublicIP}', last_mac='{MacAddress}' WHERE id='{player.playerId}'");
                 }
                 else if (RequestUpdateMAC)
                 {
                     player.ExecuteQuery($"UPDATE accounts SET last_mac='{MacAddress}' WHERE id='{player.playerId}'");
                 }
                 else if (RequestUpdateIP)
                 {
                     player.ExecuteQuery($"UPDATE accounts SET last_ip='{PublicIP}' WHERE id='{player.playerId}'");
                 }
                 UserBlock userBlock = new UserBlock
                 {
                     ipAddress  = PublicIP,
                     macAddress = MacAddress.ToString(),
                     hardwareId = player.hardwareId
                 };
                 ServerBlockManager.GetBlock(userBlock, out bool IP_IsBlocked, out bool MAC_IsBlocked, out bool HWID_IsBlocked);
                 if (MAC_IsBlocked || HWID_IsBlocked)
                 {
                     Logger.Login($" [Login] Usuário bloqueado por {(MAC_IsBlocked ? "MacAddress" : HWID_IsBlocked ? "HardwareId" : "MacAddress e HardwareId")} ({MacAddress}/{player.hardwareId}). Login: {Login}");
                     client.SendCompletePacket(PackageDataManager.BASE_LOGIN_0x80000107_PAK);
                     client.Close(1000);
                 }
                 else if (IP_IsBlocked)
                 {
                     Logger.Login($" [Login] Usuário bloqueado por IpAddress ({PublicIP}). Login: {Login}");
                     client.SendCompletePacket(PackageDataManager.BASE_LOGIN_0x80000121_PAK);
                     client.Close(1000);
                 }
                 else
                 {
                     Account playerCache = AccountManager.GetAccount(player.playerId, true);
                     if (!player.isOnline)
                     {
                         Logger.Login($" [Login] Id: {player.playerId} User: {player.login} Nickname: {(player.nickname.Length > 0 ? player.nickname : "New User")} loggedd. IP: {PublicIP} LocalIP: {new IPAddress(LocalIP)}");
                         player.SetOnlineStatus(true);
                         player.localIP = LocalIP;
                         if (playerCache != null)
                         {
                             playerCache.client = client;
                         }
                         client.SendPacket(new PROTOCOL_BASE_LOGIN_ACK(0, Login, player.playerId));
                         client.SendPacket(new PROTOCOL_BASE_WEB_CASH_ACK(0, player.gold, player.cash));
                         if (player.clanId > 0)
                         {
                             player.clanPlayers = ClanManager.GetClanPlayers(player.clanId, player.playerId);
                             client.SendPacket(new PROTOCOL_BASE_USER_CLAN_MEMBERS_ACK(player.clanPlayers));
                         }
                         ServersManager.UpdateServerPlayers();
                         client.PROTOCOL_BASE_HEARTBEAT_ACK();
                         ApiManager.SendPacketToAllClients(new API_SERVER_INFO_ACK());
                     }
                     else
                     {
                         client.SendCompletePacket(PackageDataManager.BASE_LOGIN_0x80000101_PAK);
                         if (playerCache != null && playerCache.client != null)
                         {
                             if (playerCache.client is AuthClient) //Close Auth
                             {
                                 playerCache.SendCompletePacket(PackageDataManager.AUTH_ACCOUNT_KICK_TYPE1_PAK);
                                 playerCache.SendCompletePacket(PackageDataManager.SERVER_MESSAGE_ERROR_2147487744_PAK);
                             }
                             else //Close Game
                             {
                                 playerCache.SendCompletePacket(PackageDataManager.GAME_ACCOUNT_KICK_TYPE1_PAK);
                                 playerCache.SendCompletePacket(PackageDataManager.SERVER_MESSAGE_ERROR_0x80001000_PAK);
                             }
                             playerCache.Close(1000);
                         }
                         Logger.Login($" [Login] O Usuário ja está conectado. Conexão simultânea. Login: {Login}");
                         GameManager.RemoveConnection(PublicIP);
                         client.Close(1000);
                     }
                 }
             }
         }
         else
         {
             client.SendCompletePacket(PackageDataManager.BASE_LOGIN_0x80000127_PAK);
             GameManager.RemoveConnection(PublicIP);
             client.Close(1000);
         }
     }
     catch (Exception ex)
     {
         PacketLog(ex);
     }
 }
Ejemplo n.º 10
0
        private void bGui_Click(object sender, EventArgs e)
        {
            UserBlock blockUserLogined = blockChain.UserChain[0];

            foreach (UserBlock blockUser in blockChain.UserChain)
            {
                if (blockUser.User.Username == userNameLogined)
                {
                    blockUserLogined = blockUser;
                    //Console.WriteLine("có tìm đc user đã login");
                    break;
                }
            }
            int    blockSend  = blockChain.UserChain.LastIndexOf(blockUserLogined);
            User   userSend   = blockChain.UserChain[blockSend].User;
            String fromAdress = userSend.Pub_key;


            UserBlock blockUserCharity = blockChain.UserChain[0];

            foreach (UserBlock blockUser in blockChain.UserChain)
            {
                if (blockUser.User.Username == cbCharity.Text)
                {
                    blockUserCharity = blockUser;
                    //Console.WriteLine("có tìm đc user charity");
                    break;
                }
            }
            int    blockReceive = blockChain.UserChain.LastIndexOf(blockUserCharity);
            User   userReceive  = blockChain.UserChain[blockReceive].User;
            String toAdress     = userReceive.Pub_key;

            int amount = Convert.ToInt32(tbTien.Text);
            //Console.WriteLine("amount nhập trong textbox:{0}", amount);
            Transaction tranc = new Transaction(fromAdress, toAdress, amount);

            tranc.signTransaction(userSend.Private_key);
            //tranc.signTransaction(userSend.Pub_key);
            blockChain.addTransaction(tranc);
            blockChain.MinePendingTransactions(fromAdress);

            userSend.Money    += blockChain.getBalanceOfAdress(fromAdress);
            userReceive.Money += blockChain.getBalanceOfAdress(toAdress);
            Console.WriteLine("from adress hay public key của usersend:{0}", fromAdress);
            Console.WriteLine("private key của user send:{0}", userSend.Private_key);
            Console.WriteLine("public key của user charity:{0}", userReceive.Pub_key);
            //Console.WriteLine("to adress:{0}", toAdress);
            //Console.WriteLine("user send money:{0}", userSend.Money);
            //Console.WriteLine("user receive money:{0}", userReceive.Money);
            //Console.WriteLine("user send name:{0}", userSend.Username);

            //blockChain.createUser(userSend);
            //blockChain.createUser(userReceive);

            lvCharity.Items.Clear();
            Console.WriteLine("so luong chain:{0}", blockChain.Chain.Count);
            foreach (Block block in blockChain.Chain)
            {
                Console.WriteLine("VAO FOR NGOAI.");
                Console.WriteLine("so luong trans trong chain:{0}", block.transactions.Count);
                foreach (Transaction transaction in block.transactions)
                {
                    Console.WriteLine("VAO FOR TRONG.");
                    ListViewItem item = new ListViewItem();
                    //if(transaction.fromAdress==fromAdress || transaction.toAdress == fromAdress)//liệt kê các transaction liên quan tới user đã login
                    //{
                    item.Text = block.timestamp;
                    item.SubItems.Add(new ListViewItem.ListViewSubItem()
                    {
                        Text = transaction.fromAdress
                    });
                    item.SubItems.Add(new ListViewItem.ListViewSubItem()
                    {
                        Text = transaction.toAdress
                    });
                    item.SubItems.Add(new ListViewItem.ListViewSubItem()
                    {
                        Text = Convert.ToString(transaction.amount)
                    });
                    lvCharity.Items.Add(item);
                    //Console.WriteLine(" transaction form adress:{0}", transaction.fromAdress);
                    //Console.WriteLine(" transaction to adress:{0}", transaction.toAdress);
                    //Console.WriteLine(" transaction mount:{0}", transaction.amount);
                    //}
                }
            }
        }