public async Task <IActionResult> EditServer(int serverId, int sshServerId, bool create = false,
                                                     bool remove = false)
        {
            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), serverId, _service, _pavlovServerService))
            {
                return(Forbid());
            }
            var server = new PavlovServer();

            if (serverId != 0)
            {
                server = await _pavlovServerService.FindOne(serverId);
            }

            if (server.SshServer == null)
            {
                server.SshServer = await _sshServerSerivce.FindOne(sshServerId);
            }

            var viewModel = new PavlovServerViewModel();

            viewModel = viewModel.fromPavlovServer(server, sshServerId);

            viewModel.LiteDbUsers = (await _userservice.FindAll()).ToList();

            viewModel.create = create;
            viewModel.remove = remove;
            return(View("Server", viewModel));
        }
예제 #2
0
        public bool SaveBlackListEntry(PavlovServer server, List <ServerBans> NewBlackListContent)
        {
            var blacklistArray = NewBlackListContent.Select(x => x.SteamId).ToArray();

            RconStatic.WriteFile(server.SshServer, server.ServerFolderPath + FilePaths.BanList, blacklistArray, _notifyService);
            return(true);
        }
예제 #3
0
 public async Task <ServerSelectedMods[]> FindAllFrom(PavlovServer pavlovServer)
 {
     return((await _liteDb.LiteDatabaseAsync.GetCollection <ServerSelectedMods>("ServerSelectedMods")
             .Include(x => x.LiteDbUser)
             .Include(x => x.PavlovServer)
             .FindAsync(x => x.PavlovServer.Id == pavlovServer.Id)).ToArray());
 }
예제 #4
0
        private async Task <bool> SaveToFile(PavlovServer pavlovServer, List <string> steamIds)
        {
            var lines = steamIds.Select(steamIdentity => steamIdentity).ToList();

            RconStatic.WriteFile(pavlovServer.SshServer, pavlovServer.ServerFolderPath + FilePaths.ModList, lines.ToArray(),
                                 _notifyService);
            return(true);
        }
        private async Task <PavlovServer> HasToStop(PavlovServer pavlovServer, bool hasToStop, bool root)
        {
            if (hasToStop)
            {
                DataBaseLogger.LogToDatabaseAndResultPlusNotify("stop server again!", LogEventLevel.Verbose,
                                                                _notifyService);
                await RconStatic.SystemDStop(pavlovServer, this);

                pavlovServer = await GetServerServiceState(pavlovServer);
            }

            return(pavlovServer);
        }
        public async Task <PavlovServer> Upsert(PavlovServer pavlovServer, bool withCheck = true)
        {
            if (withCheck)
            {
                pavlovServer = await ValidatePavlovServer(pavlovServer, false);
            }
            var result = await _liteDb.LiteDatabaseAsync.GetCollection <PavlovServer>("PavlovServer")
                         .UpsertAsync(pavlovServer);

            if (result)
            {
                await _liteDb.LiteDatabaseAsync.GetCollection <PavlovServer>("PavlovServer")
                .FindOneAsync(x => x.Id == pavlovServer.Id);
            }

            return(pavlovServer);
        }
        public async Task <bool> SaveWhiteListToFileAndDb(List <string> steamIds, PavlovServer server)
        {
            //delete old stuff
            foreach (var old in await FindAllFrom(server))
            {
                await Delete(old.Id);
            }
            //only save SteamIdsList to DB
            foreach (var newId in steamIds)
            {
                var entry = new ServerSelectedWhiteList
                {
                    PavlovServer    = server,
                    SteamIdentityId = newId
                };
                await Insert(entry);
            }

            SaveToFile(server, steamIds);
            return(true);
        }
예제 #8
0
        public async Task <bool> SaveModListToFileAndDb(List <string> userIds, PavlovServer server)
        {
            var steamIdentities = (await _steamIdentityService.FindAll()).ToList();

            //delete old stuff
            foreach (var old in await FindAllFrom(server))
            {
                await Delete(old.Id);
            }
            //only save SteamIdsList to DB

            var steamIdentitiesToReturn = await SteamIdentitiesToReturn(userIds, server, steamIdentities);

            //Find all mods and add it to the list steamIdentitiesToReturn
            var additionalUsers = new List <LiteDbUser>();

            if (server.Owner == null || server.SshServer.Owner == null)
            {
                additionalUsers = (await _userService.FindAllInRole("Admin")).ToList(); // admins
                additionalUsers.AddRange(await _userService.FindAllInRole("Mod"));      // mods
            }

            if (server.Shack)
            {
                steamIdentitiesToReturn.AddRange(await SteamIdentitiesToReturn(
                                                     additionalUsers.Select(x => x.Id.ToString()).ToList(), server, steamIdentities, false));
            }
            else
            {
                steamIdentitiesToReturn.AddRange(await SteamIdentitiesToReturn(
                                                     additionalUsers.Select(x => x.Id.ToString()).ToList(), server, steamIdentities, false));
            }

            await SaveToFile(server, steamIdentitiesToReturn);

            return(true);
        }
        /// <summary>
        /// </summary>
        /// <param name="pavlovServer"></param>
        /// <param name="rconService"></param>
        /// <returns></returns>
        public async Task <PavlovServer> GetServerServiceState(PavlovServer pavlovServer)
        {
            var state = await RconStatic.SystemDCheckState(pavlovServer, _notifyService);

            // state can be: active, inactive,disabled
            if (state == "active")
            {
                pavlovServer.ServerServiceState = ServerServiceState.active;
            }
            else if (state == "inactive")
            {
                pavlovServer.ServerServiceState = ServerServiceState.inactive;
            }
            else if (state == "disabled")
            {
                pavlovServer.ServerServiceState = ServerServiceState.disabled;
            }
            else
            {
                pavlovServer.ServerServiceState = ServerServiceState.none;
            }

            return(pavlovServer);
        }
        public async Task IsValidOnly(PavlovServer pavlovServer, bool parseMd5 = true)
        {
            if (string.IsNullOrEmpty(pavlovServer.TelnetPassword) && pavlovServer.Id != 0)
            {
                pavlovServer.TelnetPassword = (await FindOne(pavlovServer.Id)).TelnetPassword;
            }
            if (!RconHelper.IsMD5(pavlovServer.TelnetPassword))
            {
                if (string.IsNullOrEmpty(pavlovServer.TelnetPassword))
                {
                    throw new ValidateException("Password", "The telnet password is required!");
                }

                if (parseMd5)
                {
                    pavlovServer.TelnetPassword = RconHelper.CreateMD5(pavlovServer.TelnetPassword);
                }
            }

            if (pavlovServer.SshServer.SshPort <= 0)
            {
                throw new ValidateException("SshPort", "You need a SSH port!");
            }

            if (string.IsNullOrEmpty(pavlovServer.SshServer.SshUsername))
            {
                throw new ValidateException("SshUsername", "You need a username!");
            }


            if (string.IsNullOrEmpty(pavlovServer.SshServer.SshPassword) &&
                (pavlovServer.SshServer.SshKeyFileName == null || !pavlovServer.SshServer.SshKeyFileName.Any()))
            {
                throw new ValidateException("SshPassword", "You need at least a password or a key file!");
            }
        }
예제 #11
0
        public async Task <ConnectionResult> StartMatchWithAuth(RconService.AuthType authType,
                                                                PavlovServer server,
                                                                Match match)
        {
            var connectionInfo = RconStatic.ConnectionInfoInternal(server.SshServer, authType, out var result);

            using var clientSsh  = new SshClient(connectionInfo);
            using var clientSftp = new SftpClient(connectionInfo);
            try
            {
                var listOfSteamIdentietiesWhichCanPlay = match.MatchTeam0SelectedSteamIdentities;
                listOfSteamIdentietiesWhichCanPlay.AddRange(match.MatchTeam1SelectedSteamIdentities);
                var list = new List <string>();
                if (listOfSteamIdentietiesWhichCanPlay.Count <= 0 && match.MatchSelectedSteamIdentities.Count <= 0)
                {
                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("There are no team members so no match will start!",
                                                                    LogEventLevel.Fatal, _notifyService, result);
                    return(result);
                }


                if (match.MatchSelectedSteamIdentities.Count > 0)
                {
                    list = match.MatchSelectedSteamIdentities
                           .Select(x => Strings.Trim(x.SteamIdentityId)).ToList();
                }
                else if (listOfSteamIdentietiesWhichCanPlay.Count > 0)
                {
                    list = listOfSteamIdentietiesWhichCanPlay.Select(x => Strings.Trim(x.SteamIdentityId)).ToList();
                }

                list = list.Distinct().ToList();
                //GetAllAdminsForTheMatch
                var mods = new List <string>();
                //Todo what if the match is not team based? there are no mods or admins?
                mods = listOfSteamIdentietiesWhichCanPlay.Where(x => x.OverWriteRole == "Mod" || x.OverWriteRole == "Admin").Select(x => x.SteamIdentityId).ToList();


                //Write whitelist and set server settings


                RconStatic.WriteFile(server.SshServer,
                                     server.ServerFolderPath + FilePaths.WhiteList,
                                     list.ToArray(), _notifyService);
                RconStatic.WriteFile(server.SshServer,
                                     server.ServerFolderPath + FilePaths.ModList,
                                     mods.ToArray(), _notifyService);
                RconStatic.WriteFile(server.SshServer,
                                     server.ServerFolderPath + FilePaths.BanList,
                                     Array.Empty <string>(), _notifyService);


                var oldSettings = new PavlovServerGameIni();
                oldSettings.ReadFromFile(server, _notifyService);

                var serverSettings = new PavlovServerGameIni
                {
                    bEnabled        = true,
                    ServerName      = match.Name,
                    MaxPlayers      = match.PlayerSlots,
                    bSecured        = true,
                    bCustomServer   = true,
                    bWhitelist      = true,
                    RefreshListTime = 120,
                    LimitedAmmoType = 0,
                    TickRate        = 90,
                    TimeLimit       = match.TimeLimit,
                    Password        = "",
                    BalanceTableURL = "",
                    bVerboseLogging = true,
                    bCompetitive    = true,
                    MapRotation     = new List <PavlovServerGameIniMap>
                    {
                        new()
                        {
                            MapLabel = match.MapId,
                            GameMode = match.GameMode
                        }
                    },
                    ApiKey = oldSettings.ApiKey
                };
                var map = await _mapsService.FindOne(match.MapId.Replace("UGC", ""));

                serverSettings.SaveToFile(server, new[]
                {
                    new ServerSelectedMap()
                    {
                        Map      = map,
                        GameMode = match.GameMode
                    }
                }, _notifyService);
                await RconStatic.SystemDStart(server, _pavlovServerService);

                //StartWatchServiceForThisMatch
                match.Status = Status.StartetWaitingForPlayer;
                await Upsert(match);

                DataBaseLogger.LogToDatabaseAndResultPlusNotify("Start backgroundjob", LogEventLevel.Verbose,
                                                                _notifyService);

                BackgroundJob.Enqueue(
                    () => MatchInspector(match.Id)); // ChecjServerState
            }
예제 #12
0
        /// <summary>
        /// Return back if the server should forceStop
        /// </summary>
        /// <param name="server"></param>
        /// <param name="match"></param>
        /// <returns></returns>
        /// <exception cref="CommandException"></exception>
        public async Task <bool> SShTunnelGetAllInfoFromPavlovServer(PavlovServer server, Match match = null)
        {
            var result        = RconStatic.StartClient(server, out var client);
            var costumesToSet = new Dictionary <string, string>();

            try
            {
                client.Connect();

                if (client.IsConnected)
                {
                    var nextFreePort  = RconStatic.GetAvailablePort();
                    var portToForward = nextFreePort;
                    var portForwarded = new ForwardedPortLocal("127.0.0.1", (uint)portToForward, "127.0.0.1",
                                                               (uint)server.TelnetPort);
                    client.AddForwardedPort(portForwarded);
                    portForwarded.Start();
                    using (var client2 = new Client("127.0.0.1", portToForward, new CancellationToken()))
                    {
                        if (client2.IsConnected)
                        {
                            var password = await client2.ReadAsync(TimeSpan.FromMilliseconds(2000));

                            DataBaseLogger.LogToDatabaseAndResultPlusNotify("Answer: " + password,
                                                                            LogEventLevel.Verbose, _notifyService);
                            if (password.ToLower().Contains("password"))
                            {
                                DataBaseLogger.LogToDatabaseAndResultPlusNotify("start sending password!",
                                                                                LogEventLevel.Verbose, _notifyService);
                                await client2.WriteLine(server.TelnetPassword);

                                DataBaseLogger.LogToDatabaseAndResultPlusNotify("did send password and wait for auth",
                                                                                LogEventLevel.Verbose, _notifyService);

                                var auth = await client2.ReadAsync(TimeSpan.FromMilliseconds(2000));

                                DataBaseLogger.LogToDatabaseAndResultPlusNotify("waited for auth get : " + auth,
                                                                                LogEventLevel.Verbose, _notifyService);
                                if (auth.ToLower().Contains("authenticated=1"))
                                {
                                    // it is authetificated
                                    var commandOne           = "RefreshList";
                                    var singleCommandResult1 =
                                        await RconStatic.SingleCommandResult(client2, commandOne);

                                    var playersList =
                                        JsonConvert.DeserializeObject <PlayerListClass>(singleCommandResult1);
                                    var steamIds = playersList?.PlayerList.Select(x => x.UniqueId);
                                    //Inspect PlayerList
                                    var commands = new List <string>();
                                    if (steamIds != null)
                                    {
                                        foreach (var steamId in steamIds)
                                        {
                                            commands.Add("InspectPlayer " + steamId);
                                        }
                                    }

                                    var playerListRaw = new List <string>();
                                    foreach (var command in commands)
                                    {
                                        var commandResult = await RconStatic.SingleCommandResult(client2, command);

                                        playerListRaw.Add(commandResult);
                                    }

                                    var playerListJson = string.Join(",", playerListRaw);
                                    playerListJson = "[" + playerListJson + "]";
                                    var finsihedPlayerList = new List <PlayerModelExtended>();
                                    var tmpPlayers         = JsonConvert.DeserializeObject <List <PlayerModelExtendedRconModel> >(
                                        playerListJson, new JsonSerializerSettings {
                                        CheckAdditionalContent = false
                                    });
                                    var steamIdentities = (await _steamIdentityService.FindAll()).ToList();

                                    if (tmpPlayers != null)
                                    {
                                        foreach (var player in tmpPlayers)
                                        {
                                            player.PlayerInfo.Username = player.PlayerInfo.PlayerName;
                                            var identity =
                                                steamIdentities?.FirstOrDefault(x =>
                                                                                x.Id == player.PlayerInfo.UniqueId);
                                            if (identity != null && (identity.Costume != "None" ||
                                                                     !string.IsNullOrEmpty(identity.Costume)))
                                            {
                                                if (server.Shack)
                                                {
                                                    costumesToSet.Add(identity.OculusId, identity.Costume);
                                                }
                                                else
                                                {
                                                    costumesToSet.Add(identity.Id, identity.Costume);
                                                }
                                            }
                                        }

                                        finsihedPlayerList = tmpPlayers.Select(x => x.PlayerInfo).ToList();
                                    }

                                    var pavlovServerPlayerList = finsihedPlayerList.Select(x =>
                                    {
                                        var player      = new PavlovServerPlayer();
                                        player.Username = x.Username;
                                        player.UniqueId = x.UniqueId;
                                        player.KDA      = x.KDA;
                                        player.Cash     = x.Cash;
                                        player.TeamId   = x.TeamId;
                                        player.Score    = x.Score;
                                        player.ServerId = server.Id;
                                        return(player);
                                    }).ToList();
                                    var oldServerInfo = await _pavlovServerInfoService.FindServer(server.Id);

                                    //Todo maybe check if we lost a player its possible that we need that if allstats after the end of a match doesent give back all the player if some had a disconnect
                                    await _pavlovServerPlayerService.Upsert(pavlovServerPlayerList, server.Id);

                                    await _pavlovServerPlayerHistoryService.Upsert(pavlovServerPlayerList.Select(x =>
                                    {
                                        var history = new PavlovServerPlayerHistory();
                                        history.Username = x.Username;
                                        history.UniqueId = x.UniqueId;
                                        history.PlayerName = x.PlayerName;
                                        history.KDA = x.KDA;
                                        history.Cash = x.Cash;
                                        history.TeamId = x.TeamId;
                                        history.Score = x.Score;
                                        history.ServerId = x.ServerId;
                                        history.date = DateTime.Now;
                                        return(history);
                                    }).ToList(), server.Id, 1);

                                    var singleCommandResultTwo =
                                        await RconStatic.SingleCommandResult(client2, "ServerInfo");

                                    var tmp = JsonConvert.DeserializeObject <ServerInfoViewModel>(
                                        singleCommandResultTwo.Replace("\"\"", "\"ServerInfo\""));
                                    if (tmp == null || tmp.ServerInfo == null)
                                    {
                                        return(false);
                                    }
                                    if (!string.IsNullOrEmpty(tmp.ServerInfo.GameMode))
                                    {
                                        DataBaseLogger.LogToDatabaseAndResultPlusNotify(
                                            "Got the server info for the server: " + server.Name + "\n " +
                                            singleCommandResultTwo, LogEventLevel.Verbose, _notifyService);
                                    }


                                    tmp.ServerId = server.Id;
                                    var map = await _mapsService.FindOne(tmp.ServerInfo.MapLabel.Replace("UGC", ""));

                                    if (map != null)
                                    {
                                        tmp.ServerInfo.MapPictureLink = map.ImageUrl;
                                    }

                                    //Check of next round
                                    bool nextRound = oldServerInfo != null && oldServerInfo.MapLabel != tmp.ServerInfo.MapLabel;
                                    if (!nextRound && oldServerInfo != null && match is { Status : Status.OnGoing }) // more checks cause in a match the map is only one and will not trigger the first try
                                    {
                                        var gotResult1 = int.TryParse(oldServerInfo.Team0Score, out var oldTeam0Score);
                                        var gotResult2 = int.TryParse(oldServerInfo.Team1Score, out var oldTeam1Score);
                                        var gotResult3 = int.TryParse(tmp.ServerInfo.Team0Score, out var newTeam0Score);
                                        var gotResult4 = int.TryParse(tmp.ServerInfo.Team1Score, out var newTeam1Score);

                                        if (gotResult1 && gotResult2 && gotResult3 && gotResult4 && (
                                                oldTeam0Score > newTeam0Score ||
                                                oldTeam1Score > newTeam1Score)
                                            )
                                        {
                                            nextRound = true;
                                        }
                                    }
                                    var round = oldServerInfo?.Round ?? 0;
                                    if (nextRound)
                                    {
                                        if (round == 999)
                                        {
                                            round = 0; // reset value that's why you have to use the nextRound bool down from here to know if its the next round
                                        }

                                        round++;
                                    }

                                    if (match is { Status : Status.OnGoing } && nextRound)
        private async Task UpdateServerState(PavlovServer signleServer, bool withCheck)
        {
            var serverWithState = await GetServerServiceState(signleServer);

            await Upsert(serverWithState, withCheck);
        }
        public async Task <IActionResult> SaveServer(PavlovServerViewModel server)
        {
            if (!ModelState.IsValid)
            {
                return(View("Server", server));
            }

            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), server.Id, _service, _pavlovServerService))
            {
                return(Forbid());
            }

            server.LiteDbUsers = (await _userservice.FindAll()).ToList();

            server.Owner = (await _userservice.FindAll())
                           .FirstOrDefault(x => x.Id == new ObjectId(server.LiteDbUserId));
            var resultServer = new PavlovServer();

            server.SshServer = await _service.FindOne(server.sshServerId);

            if (server.create)
            {
                // Duplicate Database entries check
                try
                {
                    await _pavlovServerService.IsValidOnly(server, false);

                    if (string.IsNullOrEmpty(server.SshServer.SshPassword))
                    {
                        throw new ValidateException("Id",
                                                    "Please add a sshPassword to the ssh user (Not root user). Sometimes the systems asks for the password even if the keyfile and passphrase is used.");
                    }
                    if (string.IsNullOrEmpty(server.ServerFolderPath))
                    {
                        throw new ValidateException("ServerFolderPath",
                                                    "The server ServerFolderPath is needed!");
                    }
                    if (!server.ServerFolderPath.EndsWith("/"))
                    {
                        throw new ValidateException("ServerFolderPath",
                                                    "The server ServerFolderPath needs a / at the end!");
                    }
                    if (!server.ServerFolderPath.StartsWith("/"))
                    {
                        throw new ValidateException("ServerFolderPath",
                                                    "The server ServerFolderPath needs a / at the start!");
                    }
                    if (server.ServerPort <= 0)
                    {
                        throw new ValidateException("ServerPort", "The server port is needed!");
                    }
                    if (server.TelnetPort <= 0)
                    {
                        throw new ValidateException("TelnetPort", "The rcon port is needed!");
                    }
                    if (string.IsNullOrEmpty(server.ServerSystemdServiceName))
                    {
                        throw new ValidateException("ServerSystemdServiceName",
                                                    "The server service name is needed!");
                    }
                    if (string.IsNullOrEmpty(server.Name))
                    {
                        throw new ValidateException("Name", "The Gui name is needed!");
                    }
                }
                catch (ValidateException e)
                {
                    ModelState.AddModelError(e.FieldName, e.Message);
                    return(await GoBackEditServer(server,
                                                  "Field is not set: " + e.Message));
                }

                if (server.SshKeyFileNameForm != null)
                {
                    await using var ms = new MemoryStream();
                    await server.SshKeyFileNameForm.CopyToAsync(ms);

                    var fileBytes = ms.ToArray();
                    server.SshKeyFileNameRoot = fileBytes;
                    // act on the Base64 data
                }

                try
                {
                    await _pavlovServerService.CreatePavlovServer(server);
                }
                catch (Exception e)
                {
                    return(await GoBackEditServer(server, e.Message, true));
                }
            }

            try
            {
                //save and validate server a last time
                resultServer = await _pavlovServerService.Upsert(server.toPavlovServer(server));
            }
            catch (ValidateException e)
            {
                ModelState.AddModelError(e.FieldName, e.Message);
                return(await GoBackEditServer(server,
                                              "Could not validate server -> " + e.Message, server.create));
            }

            if (ModelState.ErrorCount > 0)
            {
                return(await EditServer(server));
            }
            if (server.create)
            {
                return(Redirect("/PavlovServer/EditServerSelectedMaps/" + resultServer.Id));
            }

            return(RedirectToAction("Index", "SshServer"));
        }
예제 #15
0
 public static ServerBans CreatePavlovServerBans(ServerBansService serverBansService, PavlovServer pavlovServer)
 {
     serverBansService.Upsert(
         new ServerBans
     {
         SteamId        = "test",
         SteamName      = "test",
         BannedDateTime = DateTime.Now,
         BanSpan        = new TimeSpan(0, 0, 1),
         Comment        = "test",
         PavlovServer   = pavlovServer
     }).GetAwaiter().GetResult();
     return(serverBansService.FindOne(pavlovServer.Id).GetAwaiter().GetResult());
 }
예제 #16
0
        public async Task <List <string> > SteamIdentitiesToReturn(List <string> userdIds, PavlovServer server,
                                                                   List <SteamIdentity> steamIdentities, bool withInsert = true)
        {
            var steamIdentitiesToReturn = new List <string>();

            foreach (var newId in userdIds)
            {
                var steamIdentity = steamIdentities.FirstOrDefault(x => x.LiteDbUser?.Id == new ObjectId(newId));
                if (steamIdentity != null)
                {
                    var entry = new ServerSelectedMods
                    {
                        PavlovServer = server,
                        LiteDbUser   = steamIdentity.LiteDbUser
                    };
                    if (server.Shack)
                    {
                        steamIdentitiesToReturn.Add(steamIdentity.OculusId);
                    }
                    else
                    {
                        steamIdentitiesToReturn.Add(steamIdentity.Id);
                    }
                    if (withInsert)
                    {
                        await Insert(entry);
                    }
                }
            }

            return(steamIdentitiesToReturn);
        }
예제 #17
0
 public async Task <int> DeleteFromServer(PavlovServer server)
 {
     return(await _liteDb.LiteDatabaseAsync.GetCollection <ServerSelectedMods>("ServerSelectedMods")
            .DeleteManyAsync(x => x.PavlovServer == server));
 }
 public async Task <ServerSelectedWhiteList[]> FindAllFrom(PavlovServer sshServer)
 {
     return((await _liteDb.LiteDatabaseAsync.GetCollection <ServerSelectedWhiteList>("ServerSelectedWhiteList")
             .Include(x => x.PavlovServer)
             .FindAsync(x => x.PavlovServer.Id == sshServer.Id)).ToArray());
 }
        public static Match CreateMatch(MatchService matchService, PavlovServer pavlovServer, bool teamMatch,
                                        TeamService teamService, SteamIdentityService steamIdentityService, UserManager <LiteDbUser> userManager,
                                        MatchSelectedSteamIdentitiesService matchSelectedSteamIdentitiesService,
                                        MatchSelectedTeamSteamIdentitiesService matchSelectedTeamSteamIdentitiesService)
        {
            var user = ServerSelectedModServiceTests.InsertUserAndSteamIdentity(steamIdentityService, userManager,
                                                                                "test");
            var user2 = ServerSelectedModServiceTests.InsertUserAndSteamIdentity(steamIdentityService, userManager,
                                                                                 "test2", "2");
            var steamIdentity1 = steamIdentityService.FindOne(user.Id).GetAwaiter().GetResult();
            var steamIdentity2 = steamIdentityService.FindOne(user2.Id).GetAwaiter().GetResult();
            var team1          = TeamSelectedSteamIdentityServiceTest.CreateTeam(teamService);
            var team2          = TeamSelectedSteamIdentityServiceTest.CreateTeam(teamService, "test2");

            if (teamMatch)
            {
                matchService.Upsert(new Match
                {
                    Name         = "Test",
                    MapId        = "null",
                    GameMode     = "TDM",
                    ForceStart   = false,
                    ForceSop     = false,
                    TimeLimit    = 40,
                    PlayerSlots  = 10,
                    Team0        = team1,
                    Team1        = team2,
                    PavlovServer = pavlovServer,
                    Status       = Status.Preparing
                }).GetAwaiter().GetResult();
            }
            else
            {
                matchService.Upsert(new Match
                {
                    Name         = "Test",
                    MapId        = "null",
                    GameMode     = "GUN",
                    ForceStart   = false,
                    ForceSop     = false,
                    TimeLimit    = 40,
                    PlayerSlots  = 10,
                    Team0        = team1,
                    PavlovServer = pavlovServer,
                    Status       = Status.Preparing
                }).GetAwaiter().GetResult();
            }


            var match = matchService.FindAll().GetAwaiter().GetResult().FirstOrDefault();

            if (teamMatch)
            {
                match.MatchTeam0SelectedSteamIdentities = new List <MatchTeamSelectedSteamIdentity>
                {
                    new()
                    {
                        SteamIdentityId = steamIdentity1.Id,
                        SteamIdentity   = steamIdentity1,
                        matchId         = match.Id,
                        TeamId          = 0
                    }
                };
                match.MatchTeam1SelectedSteamIdentities = new List <MatchTeamSelectedSteamIdentity>
                {
                    new()
                    {
                        SteamIdentityId = steamIdentity2.Id,
                        SteamIdentity   = steamIdentity2,
                        matchId         = match.Id,
                        TeamId          = 1
                    }
                };
                matchSelectedTeamSteamIdentitiesService.Upsert(match.MatchTeam0SelectedSteamIdentities, match.Id, 0)
                .GetAwaiter().GetResult();
                matchSelectedTeamSteamIdentitiesService.Upsert(match.MatchTeam1SelectedSteamIdentities, match.Id, 1)
                .GetAwaiter().GetResult();
            }
            else
            {
                match.MatchSelectedSteamIdentities = new List <MatchSelectedSteamIdentity>
                {
                    new()
                    {
                        SteamIdentityId = steamIdentity1.Id,
                        SteamIdentity   = steamIdentity1,
                        matchId         = match.Id
                    },
                    new()
                    {
                        SteamIdentityId = steamIdentity2.Id,
                        SteamIdentity   = steamIdentity2,
                        matchId         = match.Id
                    }
                };

                matchSelectedSteamIdentitiesService.Upsert(match.MatchSelectedSteamIdentities, match.Id).GetAwaiter()
                .GetResult();
            }

            matchService.Upsert(match);
            return(match);
        }
        public virtual async Task <PavlovServer> ValidatePavlovServer(PavlovServer pavlovServer, bool root)
        {
            DataBaseLogger.LogToDatabaseAndResultPlusNotify("start validate", LogEventLevel.Verbose, _notifyService);
            var hasToStop = false;

            await IsValidOnly(pavlovServer);


            DataBaseLogger.LogToDatabaseAndResultPlusNotify("try to start service", LogEventLevel.Verbose,
                                                            _notifyService);
            //try if the service realy exist
            try
            {
                pavlovServer = await GetServerServiceState(pavlovServer);

                if (pavlovServer.ServerServiceState != ServerServiceState.active)
                {
                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("has to start", LogEventLevel.Verbose,
                                                                    _notifyService);
                    hasToStop = true;
                    //the problem is here for the validating part if it has to start the service first it has problems
                    await RconStatic.SystemDStart(pavlovServer, this);

                    pavlovServer = await GetServerServiceState(pavlovServer);

                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("state = " + pavlovServer.ServerServiceState,
                                                                    LogEventLevel.Verbose, _notifyService);
                }
            }
            catch (CommandException e)
            {
                throw new ValidateException(e.Message);
            }

            DataBaseLogger.LogToDatabaseAndResultPlusNotify("try to send serverinfo", LogEventLevel.Verbose,
                                                            _notifyService);
            //try to send Command ServerInfo
            try
            {
                await RconStatic.SendCommandSShTunnel(pavlovServer, "ServerInfo", _notifyService);
            }
            catch (CommandException e)
            {
                await HasToStop(pavlovServer, hasToStop, root);

                throw new ValidateException(e.Message);
            }

            //try if the user have rights to delete maps cache
            try
            {
                DataBaseLogger.LogToDatabaseAndResultPlusNotify("delete unused maps", LogEventLevel.Verbose,
                                                                _notifyService);
                RconStatic.DeleteUnusedMaps(pavlovServer,
                                            (await _serverSelectedMapService.FindAllFrom(pavlovServer)).ToList());
            }
            catch (CommandException e)
            {
                await HasToStop(pavlovServer, hasToStop, root);

                throw new ValidateException(e.Message);
            }

            if (!string.IsNullOrEmpty(pavlovServer.SshServer.ShackMapsPath))
            {
                try
                {
                    DataBaseLogger.LogToDatabaseAndResultPlusNotify("check if ShackMapsPath exist!", LogEventLevel.Verbose,
                                                                    _notifyService);
                    RconStatic.DoesPathExist(pavlovServer, pavlovServer.SshServer.ShackMapsPath, _notifyService);
                }
                catch (CommandException e)
                {
                    await HasToStop(pavlovServer, hasToStop, root);

                    throw new ValidateException("ShackMapsPath does not exist: " + pavlovServer.SshServer.ShackMapsPath + "additional info:" + e.Message);
                }
            }

            await HasToStop(pavlovServer, hasToStop, root);

            return(pavlovServer);
        }