Example #1
0
        private static void LaunchReport(string filename)
        {
            try {
                using (var stream = File.OpenRead(Path.Combine(Path.GetDirectoryName(filename) ?? "", Path.GetFileNameWithoutExtension(filename) + ".zip")))
                    using (var archive = new ZipArchive(stream)) {
                        // Apply video config
                        var currentVideo  = new IniFile(AcPaths.GetCfgVideoFilename());
                        var currentWidth  = currentVideo["VIDEO"].GetInt("WIDTH", 1920);
                        var currentHeight = currentVideo["VIDEO"].GetInt("HEIGHT", 1080);
                        var newVideo      =
                            IniFile.Parse((archive.GetEntry("video.ini") ?? throw new Exception("Video config is missing")).Open().ReadAsStringAndDispose());
                        newVideo["VIDEO"].Set("WIDTH", Math.Min(currentWidth, newVideo["VIDEO"].GetInt("WIDTH", 1920)));
                        newVideo["VIDEO"].Set("HEIGHT", Math.Min(currentHeight, newVideo["VIDEO"].GetInt("HEIGHT", 1080)));
                        File.WriteAllText(AcPaths.GetCfgVideoFilename(), newVideo.ToString());

                        // Apply CSP config
                        PatchSettingsModel.Create().ImportFromPresetData(archive.GetEntry("csp.ini")?.Open().ReadAsStringAndDispose() ?? string.Empty);

                        // Apply race config
                        File.WriteAllText(AcPaths.GetRaceIniFilename(),
                                          (archive.GetEntry("race.ini") ?? throw new Exception("Race config is missing")).Open().ReadAsStringAndDispose());

                        Process.Start(new ProcessStartInfo {
                            FileName         = Path.Combine(AcRootDirectory.Instance.Value ?? "", "acs.exe"),
                            WorkingDirectory = AcRootDirectory.Instance.Value ?? ""
                        });
                    }
            } catch (Exception e) {
                NonfatalError.Notify("Failed to launch report race", e);
            }
        }
Example #2
0
 public override void CleanUp()
 {
     base.CleanUp();
     new IniFile(AcPaths.GetRaceIniFilename())
     {
         ["AUTOSPAWN"] =
         {
             ["ACTIVE"]       = IniFile.Nothing,
             ["__CM_SERVICE"] = IniFile.Nothing
         }
     }.Save();
 }
Example #3
0
        public void AddNewResult([NotNull] Game.StartProperties startProperties, [NotNull] Game.Result result)
        {
            var directory = SessionsDirectory;

            FileUtils.EnsureDirectoryExists(directory);

            var fileName = DateTime.Now.ToString("yyMMdd-HHmmss") + ".json";
            var raceOut  = AcPaths.GetResultJsonFilename();

            JObject data = null;

            if (File.Exists(raceOut))
            {
                try {
                    // Let’s try to save original data instead in case we missed something during parsing.
                    // But let’s remove formatting just in case.
                    data = JObject.Parse(File.ReadAllText(raceOut));
                } catch (Exception e) {
                    Logging.Warning(e);
                }
            }

            if (data == null)
            {
                data = JObject.FromObject(result);
            }

            // Trying to keep race params as well…
            // TODO: Do it the other way around, from start params?

            var raceIni = AcPaths.GetRaceIniFilename();

            if (File.Exists(raceIni))
            {
                data[KeyRaceIni] = File.ReadAllText(raceIni);
            }

            var quickDrive = startProperties.GetAdditional <QuickDrivePresetProperty>();

            if (quickDrive?.SerializedData != null)
            {
                data[KeyQuickDrive] = quickDrive.SerializedData;
            }

            File.WriteAllText(FileUtils.EnsureUnique(Path.Combine(directory, fileName)), data.ToString(Formatting.None));
        }
Example #4
0
        public static IEnumerable <SteamProfile> TryToFind()
        {
            // TODO: if (OptionForceValue != null) return OptionForceValue;

            Vdf parsed;

            try {
                var regKey = Registry.CurrentUser.OpenSubKey(@"Software\Valve\Steam");
                if (regKey == null)
                {
                    yield break;
                }

                var steamPath = regKey.GetValue("SteamPath").ToString();
                var config    = File.ReadAllText(Path.Combine(steamPath, @"config", @"loginusers.vdf"));

                parsed = Vdf.Parse(config).Children.GetValueOrDefault("users");
                if (parsed == null)
                {
                    throw new Exception("Config is invalid");
                }
            } catch (Exception e) {
                NonfatalError.Notify("Can’t get Steam ID from its config", e);
                yield break;
            }

            string selectedId = null;

            try {
                var selectedKey = new IniFile(AcPaths.GetRaceIniFilename());
                selectedId = selectedKey["REMOTE"].GetNonEmpty("GUID");
            } catch (Exception) {
                // ignored
            }

            if (selectedId != null && parsed.Children.TryGetValue(selectedId, out var selectedSection))
            {
                yield return(new SteamProfile(selectedId, selectedSection.Values.GetValueOrDefault("PersonaName")));
            }

            foreach (var pair in parsed.Children.Where(x => x.Key != selectedId))
            {
                yield return(new SteamProfile(pair.Key, pair.Value.Values.GetValueOrDefault("PersonaName")));
            }
        }
Example #5
0
        public override void CleanUp()
        {
            if (File.Exists(BackgroundFlagFilename))
            {
                File.Delete(BackgroundFlagFilename);
            }

            new IniFile(AcPaths.GetRaceIniFilename())
            {
                ["AUTOSPAWN"] =
                {
                    ["ACTIVE"]       = IniFile.Nothing,
                    ["__CM_SERVICE"] = IniFile.Nothing
                }
            }.Save();

            base.CleanUp();
        }
Example #6
0
        private void RunInner()
        {
            SteamRunningHelper.EnsureSteamIsRunning(RunSteamIfNeeded, false);
            new IniFile(AcPaths.GetRaceIniFilename())
            {
                ["AUTOSPAWN"] =
                {
                    ["ACTIVE"]       = true,
                    ["__CM_SERVICE"] = IniFile.Nothing
                }
            }.Save();

            SetAcX86Param();
            RaisePreviewRunEvent(AcsFilename);
            LauncherProcess = Process.Start(new ProcessStartInfo {
                FileName         = LauncherFilename,
                WorkingDirectory = AcRootDirectory.Instance.RequireValue
            });
        }
Example #7
0
        public override async Task RunAsync(CancellationToken cancellation)
        {
            AppIdStarter.CleanUpForOthers();
            await Task.Run(() => SteamRunningHelper.EnsureSteamIsRunning(RunSteamIfNeeded, false));

            new IniFile(AcPaths.GetRaceIniFilename())
            {
                ["AUTOSPAWN"] =
                {
                    ["ACTIVE"]       = true,
                    ["__CM_SERVICE"] = true
                }
            }.Save();

            await Task.Run(() => InstallSidePassage());

            if (cancellation.IsCancellationRequested)
            {
                return;
            }

            var passage = await EstablishConnectionAsync(cancellation);

            if (cancellation.IsCancellationRequested)
            {
                return;
            }

            if (passage == null)
            {
                throw new InformativeException("Can’t connect to side passage", "Please, make sure AC Service is running well or switch starters.");
            }

            RaisePreviewRunEvent(AcsFilename);
            passage.Start(AcsName);
        }
Example #8
0
            internal void Set()
            {
                _disposeLater = new List <IDisposable>();
                _removeLater  = new List <string>();

                var iniFilename = AcPaths.GetRaceIniFilename();

                if (OptionEnableRaceIniRestoration)
                {
                    _disposeLater.Add(FileUtils.RestoreLater(iniFilename));
                }

                var iniFile = PreparedConfig;

                if (iniFile == null)
                {
                    iniFile = new IniFile(iniFilename);

                    ClearUpIniFile(iniFile);
                    SetDefaultProperies(iniFile);

                    if (BasicProperties != null)
                    {
                        BasicProperties?.Set(iniFile);
                        ModeProperties?.Set(iniFile);
                        ConditionProperties?.Set(iniFile);
                        TrackProperties?.Set(iniFile);
                    }
                    else if (ReplayProperties != null)
                    {
                        if (ReplayProperties.Name == null && ReplayProperties.Filename != null)
                        {
                            var dir = AcPaths.GetReplaysDirectory();
                            if (Path.GetDirectoryName(ReplayProperties.Filename)?.Equals(dir, StringComparison.OrdinalIgnoreCase) == true)
                            {
                                ReplayProperties.Name = Path.GetFileName(ReplayProperties.Filename);
                            }
                            else
                            {
                                var removeLaterFilename = FileUtils.GetTempFileName(dir, ".tmp");
                                ReplayProperties.Name = Path.GetFileName(removeLaterFilename);
                                File.Copy(ReplayProperties.Filename, removeLaterFilename);
                                _removeLater.Add(removeLaterFilename);
                            }
                        }

                        ReplayProperties.Set(iniFile);
                    }
                    else if (BenchmarkProperties != null)
                    {
                        BenchmarkProperties.Set(iniFile);
                    }
                    else
                    {
                        throw new NotSupportedException();
                    }
                }

                foreach (var properties in AdditionalPropertieses.OfType <RaceIniProperties>())
                {
                    properties.Set(iniFile);
                }

                iniFile.Save(iniFilename);

                _disposeLater.AddRange(AdditionalPropertieses.OfType <AdditionalProperties>().Select(x => x.Set())
                                       .Prepend(AssistsProperties?.Set()).NonNull());

                StartTime = DateTime.Now;
            }
Example #9
0
        public static async Task <Result> StartAsync(IAcsStarter starter, StartProperties properties, IProgress <ProgressState> progress = null,
                                                     CancellationToken cancellation = default)
        {
            if (_busy)
            {
                return(null);
            }
            _busy = true;

            if (OptionDebugMode)
            {
                progress?.Report(ProgressState.Waiting);
                await Task.Delay(500, cancellation);

                _busy = false;
                return(GetResult(DateTime.MinValue));
            }

            RemoveResultJson();
            IKeyboardListener listener = null;

            if (properties.SetKeyboardListener)
            {
                try {
                    listener = KeyboardListenerFactory.Get();
                    listener.Subscribe();
                } catch (Exception e) {
                    AcToolsLogging.Write("Can’t set listener: " + e);
                }
            }

            var start = DateTime.Now;

            try {
                progress?.Report(ProgressState.Preparing);
                await Task.Run(() => properties.Set(), cancellation);

                if (cancellation.IsCancellationRequested || OptionRaceIniTestMode)
                {
                    return(null);
                }

                while (true)
                {
                    progress?.Report(ProgressState.Launching);
                    await starter.RunAsync(cancellation);

                    if (cancellation.IsCancellationRequested)
                    {
                        return(null);
                    }

                    var process = await starter.WaitUntilGameAsync(cancellation);

                    await Task.Run(() => properties.SetGame(process), cancellation);

                    if (cancellation.IsCancellationRequested)
                    {
                        return(null);
                    }

                    progress?.Report(ProgressState.Waiting);
                    await starter.WaitGameAsync(cancellation);

                    if (cancellation.IsCancellationRequested)
                    {
                        return(null);
                    }

                    var raceIni = new IniFile(AcPaths.GetRaceIniFilename());
                    if (raceIni["RESTART"].GetBool("ACTIVE", false))
                    {
                        raceIni["RESTART"].Set("ACTIVE", false);
                        raceIni.Save();
                    }
                    else
                    {
                        break;
                    }
                }
            } finally {
                _busy = false;

                if (cancellation.IsCancellationRequested)
                {
                    starter.CleanUp();
                }
                else
                {
                    progress?.Report(ProgressState.Finishing);
                    await starter.CleanUpAsync(cancellation);
                }

                properties.RevertChanges();
                listener?.Dispose();
            }

            return(GetResult(start));
        }