public async Task <bool> TryToPack(AcCommonObjectPackerParams packerParams)
        {
            try {
                using (var waiting = packerParams.Progress == null ? WaitingDialog.Create("Packing…") : null) {
                    var progress     = waiting ?? packerParams.Progress;
                    var cancellation = waiting?.CancellationToken ?? packerParams.Cancellation;

                    await Task.Run(() => {
                        var destination = packerParams.Destination ?? Path.Combine(Location,
                                                                                   $"{Id}-{(this as IAcObjectVersionInformation)?.Version ?? "0"}-{DateTime.Now.ToUnixTimestamp()}.zip");
                        using (var output = File.Create(destination)) {
                            Pack(output, packerParams,
                                 new Progress <string>(x => progress?.Report(AsyncProgressEntry.FromStringIndetermitate($"Packing: {x}…"))),
                                 cancellation);
                        }

                        if (cancellation.IsCancellationRequested)
                        {
                            return;
                        }
                        if (packerParams.ShowInExplorer)
                        {
                            WindowsHelper.ViewFile(destination);
                        }
                    });
                }

                return(true);
            } catch (Exception e) {
                NonfatalError.Notify("Can’t pack", e);
                return(false);
            }
        }
            public Task EnableMod(GenericMod mod)
            {
                return(_busy.Task(async() => {
                    if (_enabler == null || mod.IsEnabled)
                    {
                        return;
                    }

                    var conflicts = await _enabler.CheckConflictsAsync(mod);
                    if (conflicts.Length > 0 && ModernDialog.ShowMessage(
                            conflicts.Select(x => $@"• “{Path.GetFileName(x.RelativeName)}” has already been altered by the “{x.ModName}” mod;")
                            .JoinToString("\n").ToSentence
                                () + $"\n\nEnabling {BbCodeBlock.Encode(mod.DisplayName)} may have adverse effects. Are you sure you want to enable this mod?",
                            "Conflict", MessageBoxButton.YesNo, "genericMods.conflict") != MessageBoxResult.Yes)
                    {
                        return;
                    }

                    try {
                        using (var waiting = WaitingDialog.Create("Enabling mod…")) {
                            await _enabler.EnableAsync(mod, waiting, waiting.CancellationToken);
                            Changed?.Invoke(this, EventArgs.Empty);

                            if (waiting.CancellationToken.IsCancellationRequested)
                            {
                                waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Cancellation…"));
                                await _enabler.DisableAsync(mod);
                            }
                        }
                    } catch (Exception e) {
                        NonfatalError.Notify("Can’t enable mod", e);
                    }
                }));
            }
            void IUserPresetable.ImportFromPresetData(string data)
            {
                if (_enabler == null || Enabled == null || Disabled == null)
                {
                    return;
                }

                _busy.Task(async() => {
                    await Task.Delay(10);

                    var names   = data.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                    var enabled = Enabled.OfType <GenericMod>().OrderByDescending(x => x.AppliedOrder).ToList();

                    try {
                        using (var waiting = WaitingDialog.Create("Loading mod profile…")) {
                            for (var i = 0; i < enabled.Count; i++)
                            {
                                var mod = enabled[i];
                                waiting.Report(mod.DisplayName, i, enabled.Count);
                                if (waiting.CancellationToken.IsCancellationRequested)
                                {
                                    return;
                                }

                                await _enabler.DisableAsync(mod, null, waiting.CancellationToken);
                                if (waiting.CancellationToken.IsCancellationRequested)
                                {
                                    waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Cancellation…"));
                                    await _enabler.EnableAsync(mod);
                                }
                            }

                            for (var i = 0; i < names.Length; i++)
                            {
                                var mod = _enabler.GetByName(names[i]);
                                if (mod == null)
                                {
                                    continue;
                                }

                                waiting.Report(mod.DisplayName, i, enabled.Count);
                                if (waiting.CancellationToken.IsCancellationRequested)
                                {
                                    return;
                                }

                                await _enabler.EnableAsync(mod, null, waiting.CancellationToken);
                                if (waiting.CancellationToken.IsCancellationRequested)
                                {
                                    waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Cancellation…"));
                                    await _enabler.DisableAsync(mod);
                                }
                            }
                        }
                    } catch (Exception e) {
                        NonfatalError.Notify("Can’t load mod profile", e);
                    }
                }).Forget();
            }
Exemple #4
0
        private async Task <bool> FixAsync([NotNull] CarObject car, CarObject donor, IProgress <AsyncProgressEntry> progress = null,
                                           CancellationToken cancellation = default(CancellationToken))
        {
            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Fixing sound…"));
            await car.ReplaceSound(donor);

            return(true);
        }
        private Func <IProgress <AsyncProgressEntry>, CancellationToken, Task <bool> > FixAsync([NotNull] CarObject car, CarObject donor)
        {
            return(async(p, c) => {
                p?.Report(AsyncProgressEntry.FromStringIndetermitate("Fixing sound…"));
                await car.ReplaceSound(donor);

                return true;
            });
        }
Exemple #6
0
        protected override Task <bool> FixAsync(CarObject car, IProgress <AsyncProgressEntry> progress = null,
                                                CancellationToken cancellation = default(CancellationToken))
        {
            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Fixing car…"));

            var data = car.AcdData;

            if (data == null || data.IsEmpty)
            {
                return(Task.FromResult(false));
            }

            Lut torque, power;

            try {
                torque = TorquePhysicUtils.LoadCarTorque(data);
                power  = TorquePhysicUtils.TorqueToPower(torque);
            } catch (Exception e) {
                Logging.Error(e);
                return(Task.FromResult(false));
            }

            var multipler = ActionExtension.InvokeInMainThread(() => {
                var dlg = new CarTransmissionLossSelector(car, torque.MaxY, power.MaxY);
                dlg.ShowDialog();
                return(dlg.IsResultOk ? dlg.Multipler : (double?)null);
            });

            if (!multipler.HasValue)
            {
                return(Task.FromResult(false));
            }

            torque.TransformSelf(x => x.Y * multipler.Value);
            power.TransformSelf(x => x.Y * multipler.Value);

            if (car.SpecsTorqueCurve != null)
            {
                var torqueUi = new Lut(car.SpecsTorqueCurve.Points);
                torqueUi.TransformSelf(x => x.Y * multipler.Value);
                car.SpecsTorqueCurve = new GraphData(torqueUi);
            }

            if (car.SpecsPowerCurve != null)
            {
                var powerUi = new Lut(car.SpecsPowerCurve.Points);
                powerUi.TransformSelf(x => x.Y * multipler.Value);
                car.SpecsPowerCurve = new GraphData(powerUi);
            }

            car.SpecsTorque = SelectedAcObjectViewModel.SpecsFormat(AppStrings.CarSpecs_Torque_FormatTooltip,
                                                                    torque.MaxY.ToString(@"F0", CultureInfo.InvariantCulture)) + (multipler.Value == 1d ? "*" : "");
            car.SpecsBhp = SelectedAcObjectViewModel.SpecsFormat(multipler.Value == 1d ? AppStrings.CarSpecs_PowerAtWheels_FormatTooltip
                    : AppStrings.CarSpecs_Power_FormatTooltip, power.MaxY.ToString(@"F0", CultureInfo.InvariantCulture));
            return(Task.FromResult(true));
        }
Exemple #7
0
        protected override async Task <bool> LoadOverride(IProgress <AsyncProgressEntry> progress, CancellationToken cancellation)
        {
            if (_id != null)
            {
                var car = CarsManager.Instance.GetById(_id);
                if (car != null)
                {
                    progress.Report(AsyncProgressEntry.Indetermitate);
                    ObsoleteCars = new List <ObsoleteDetails> {
                        await Task.Run(() => GetDetails(car, _models, true))
                    };
                }
                else
                {
                    ObsoleteCars = new List <ObsoleteDetails>();
                }
            }
            else
            {
                var entries = new List <ObsoleteDetails>();
                var filter  = _filter == null ? null : Filter.Create(CarObjectTester.Instance, _filter);

                progress.Report(AsyncProgressEntry.FromStringIndetermitate("Loading cars…"));
                await CarsManager.Instance.EnsureLoadedAsync();

                IEnumerable <CarObject> carsEnumerable = CarsManager.Instance.LoadedOnly.OrderBy(x => x.Name);
                if (filter != null)
                {
                    carsEnumerable = carsEnumerable.Where(filter.Test);
                }

                var cars = carsEnumerable.ToList();
                for (var i = 0; i < cars.Count; i++)
                {
                    var car = cars[i];
                    progress.Report(new AsyncProgressEntry(car.Name, i, cars.Count));

                    try {
                        var details = await Task.Run(() => GetDetails(car, _models, false));

                        if (details != null)
                        {
                            entries.Add(details);
                        }
                    } catch (Exception e) {
                        NonfatalError.Notify($"Can’t check {car.DisplayName}", e);
                    }
                }

                ObsoleteCars = entries;
            }

            return(ObsoleteCars.Count > 0);
        }
Exemple #8
0
 protected Task <bool> FixAsync([NotNull] CarObject car, Action <DataWrapper> action, IProgress <AsyncProgressEntry> progress = null,
                                CancellationToken cancellation = default(CancellationToken))
 {
     progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Fixing car…"));
     return(Task.Run(() => {
         var data = car.AcdData;
         if (data == null || data.IsEmpty)
         {
             return false;
         }
         action(data);
         return true;
     }));
 }
Exemple #9
0
        private static async Task <byte[]> GetFlamesTexturesAsync(IProgress <AsyncProgressEntry> progress = null,
                                                                  CancellationToken cancellation          = default(CancellationToken))
        {
            if (_flamesTextures == null)
            {
                progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Loading flames textures…"));
                _flamesTextures = await CmApiProvider.GetStaticDataBytesAsync("flames", TimeSpan.FromDays(3), cancellation : cancellation);

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

            return(_flamesTextures);
        }
Exemple #10
0
        public static async Task <bool> FixSuspensionNodesAsync(CarObject car, IProgress <AsyncProgressEntry> progress = null,
                                                                CancellationToken cancellation = default(CancellationToken))
        {
            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Fixing car…"));
            return(await Task.Run(() => {
                var kn5Filename = FileUtils.GetMainCarFilename(car.Location, car.AcdData);
                if (kn5Filename == null || !File.Exists(kn5Filename))
                {
                    return false;
                }

                var kn5 = Kn5.FromFile(kn5Filename);
                FixSuspensionNodes(kn5);
                kn5.SaveRecyclingOriginal(kn5Filename);
                return true;
            }));
        }
Exemple #11
0
        public static async Task <bool> FixMissingTexturesAsync(CarObject car, IProgress <AsyncProgressEntry> progress = null,
                                                                CancellationToken cancellation = default(CancellationToken))
        {
            var flamesTextures = await GetFlamesTexturesAsync(progress, cancellation);

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

            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Unpacking textures…"));
            return(await Task.Run(() => {
                var flamesDirectory = Path.Combine(car.Location, @"texture", @"flames");
                flamesTextures.ExtractAsArchiveTo(flamesDirectory);
                return true;
            }));
        }
Exemple #12
0
        private Task <bool> FixAsync([NotNull] CarObject car, Action <Kn5> fix, IProgress <AsyncProgressEntry> progress = null,
                                     CancellationToken cancellation = default(CancellationToken))
        {
            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Fixing car…"));
            return(Task.Run(() => {
                var kn5Filename = FileUtils.GetMainCarFilename(car.Location, car.AcdData);
                if (kn5Filename == null || !File.Exists(kn5Filename))
                {
                    return false;
                }

                var kn5 = Kn5.FromFile(kn5Filename);
                fix.Invoke(kn5);
                kn5.SaveRecyclingOriginal(kn5Filename);
                return true;
            }));
        }
Exemple #13
0
        public static async Task <bool> UpgradeToSecondVersionAsync(CarObject car, IProgress <AsyncProgressEntry> progress = null,
                                                                    CancellationToken cancellation = default(CancellationToken))
        {
            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Updating data…"));
            if (!await Task.Run(() => {
                var data = car.AcdData;
                if (data == null || data.IsEmpty)
                {
                    return(false);
                }

                var flames = data.GetIniFile("flames.ini");
                var header = flames["HEADER"];
                header.Set("EDIT_BIG", false);
                header.Set("EDIT_STATE", 4);
                header.Set("BURN_FUEL_MULT", 10);
                header.Set("FLASH_THRESHOLD", 7);

                foreach (var section in flames.GetSections("FLAME"))
                {
                    section.Set("IS_LEFT", section.GetVector3("POSITION").FirstOrDefault() < 0d);
                    section.Set("GROUP", 0);
                }

                flames.Save();
                Logging.Write($"Fixed: flames.ini of {car.DisplayName}");

                var flamesPresetsEncoded = @"jdPBjoIwEAbgOwlvUjedgSJ74MDGgia4kFIPaja8/1s4BVdaW1IPcIDhy/Dzcz/K+iDVX5qMp5uczpdOV5AmaXIflBy" +
                                           @"lnkZdKz1xGtDq1LZSVTxN+qahexX/4ux54AKYS4JGr4M0c6r9qVAIBiVnIGgOfRosGgI0vGR4wmDByBnOk3tfRkvG0NLluvQ+sPTLLm1b/h6cO" +
                                           @"PJIHEVg628aWl7NdSG2cbG6+bbrhmFgjHw/8F0MuMJ2u74ftosBbEfn2V5jhsxdGrBkIpDFTG8Wg5pkbDR9Kj6xTWxv+GY3stnO6alMrLZwQ7Ft" +
                                           @"J5Omq8ejE0rwM3I/bqt4/2mDL8d+Fp59JLuBLHSsInb3Ap0mGpatHw==";
                var flamesPresets = data.GetRawFile(@"flame_presets.ini");
                flamesPresets.Content = Encoding.UTF8.GetString(new DeflateStream(
                                                                    new MemoryStream(Convert.FromBase64String(flamesPresetsEncoded)),
                                                                    CompressionMode.Decompress).ReadAsBytesAndDispose());
                flamesPresets.Save();
                Logging.Write($"Fixed: flame_presets.ini of {car.DisplayName}");

                return(true);
            }) || cancellation.IsCancellationRequested)
            {
                return(false);
            }
            return(await FixMissingTexturesAsync(car, progress, cancellation));
        }
        public async Task <bool> LoadAsync(ListAddCallback <ServerInformation> callback, IProgress <AsyncProgressEntry> progress, CancellationToken cancellation)
        {
            if (SteamIdHelper.Instance.Value == null)
            {
                throw new Exception(ToolsStrings.Common_SteamIdIsMissing);
            }

            var data = await Task.Run(() => KunosApiProvider.TryToGetList(progress == null ? null : new ProgressConverter(progress)), cancellation);

            // if (cancellation.IsCancellationRequested) return false;

            if (data == null)
            {
                throw new InformativeException(ToolsStrings.Online_CannotLoadData, ToolsStrings.Common_MakeSureInternetWorks);
            }

            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Applying list…"));
            callback(data);
            return(true);
        }
            public Task DisableMod(GenericMod mod)
            {
                return(_busy.Task(async() => {
                    if (_enabler == null || !mod.IsEnabled)
                    {
                        return;
                    }

                    try {
                        using (var waiting = WaitingDialog.Create("Disabling mod…")) {
                            await _enabler.DisableAsync(mod, waiting, waiting.CancellationToken);
                            Changed?.Invoke(this, EventArgs.Empty);

                            if (waiting.CancellationToken.IsCancellationRequested)
                            {
                                waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Cancellation…"));
                                await _enabler.EnableAsync(mod);
                            }
                        }
                    } catch (Exception e) {
                        NonfatalError.Notify("Can’t disable mod", e);
                    }
                }));
            }
Exemple #16
0
        public async Task <WorkshopUploadResult> UploadAsync(byte[] data, string group, string name,
                                                             IProgress <AsyncProgressEntry> progress = null, CancellationToken cancellation = default)
        {
            for (var i = 0; i < 3; ++i)
            {
                progress?.Report(AsyncProgressEntry.FromStringIndetermitate(i == 0
                        ? "Starting upload…"
                        : $"Trying again, {(i + 1).ToOrdinal("attempt").ToSentenceMember()} attempt"));
                try {
                    return(await TryToUploadAsync());
                } catch (HttpRequestException e) {
                    Logging.Warning(e);
                    cancellation.ThrowIfCancellationRequested();
                    progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Upload is failed, waiting a bit before the next attempt…"));
                    await Task.Delay(TimeSpan.FromSeconds(i + 1d));

                    cancellation.ThrowIfCancellationRequested();
                } catch (WebException e) {
                    Logging.Warning(e);
                    cancellation.ThrowIfCancellationRequested();
                    progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Upload is failed, waiting a bit before the next attempt…"));
                    await Task.Delay(TimeSpan.FromSeconds(i + 1d));

                    cancellation.ThrowIfCancellationRequested();
                }
            }

            cancellation.ThrowIfCancellationRequested();
            progress?.Report(AsyncProgressEntry.FromStringIndetermitate($"Trying again, last attempt"));
            return(await TryToUploadAsync());

            async Task <WorkshopUploadResult> TryToUploadAsync()
            {
                var request = new HttpRequestMessage(HttpMethod.Post, _endpoint);

                request.Headers.TryAddWithoutValidation("X-Data-File-Group", group);
                request.Headers.TryAddWithoutValidation("X-Data-File-Name", name);
                request.Headers.TryAddWithoutValidation("X-Data-Checksum", _checksum);
                var stopwatch = new AsyncProgressBytesStopwatch();

                request.Content = progress == null
                        ? (HttpContent) new ByteArrayContent(data)
                        : new ProgressableByteArrayContent(data, 8192,
                                                           new Progress <long>(x => progress.Report(AsyncProgressEntry.CreateUploading(x, data.Length, stopwatch))));
                using (var response = await HttpClientHolder.Get().SendAsync(request, cancellation).ConfigureAwait(false)) {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new WebException($"Failed to upload: {response.StatusCode}, response: {await LoadContent()}");
                    }
                    var result = JObject.Parse(await LoadContent());
                    return(new WorkshopUploadResult {
                        Size = data.Length,
                        Tag = result["key"].ToString()
                    });

                    ConfiguredTaskAwaitable <string> LoadContent()
                    {
                        return(response.Content.ReadAsStringAsync().WithCancellation(cancellation).ConfigureAwait(false));
                    }
                }
            }
        }
Exemple #17
0
        public static async Task <string> LoadAsyncTo(string argument,
                                                      FlexibleLoaderGetPreferredDestinationCallback getPreferredDestination, [CanBeNull] FlexibleLoaderReportDestinationCallback reportDestination,
                                                      Action <FlexibleLoaderMetaInformation> reportMetaInformation = null, Func <bool> checkIfPaused = null,
                                                      IProgress <AsyncProgressEntry> progress = null, CancellationToken cancellation = default)
        {
            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Finding fitting loader…"));
            var loader = await CreateLoaderAsync(argument, cancellation) ?? throw new OperationCanceledException();

            try {
                using (var order = KillerOrder.Create(new CookieAwareWebClient(), TimeSpan.FromMinutes(10))) {
                    var client = order.Victim;

                    if (_proxy != null)
                    {
                        client.Proxy = _proxy;
                    }

                    progress?.Report(AsyncProgressEntry.Indetermitate);

                    cancellation.ThrowIfCancellationRequested();
                    cancellation.Register(client.CancelAsync);

                    if (!await loader.PrepareAsync(client, cancellation))
                    {
                        throw new InformativeException("Can’t load file", "Loader preparation failed.");
                    }

                    cancellation.ThrowIfCancellationRequested();
                    reportMetaInformation?.Invoke(FlexibleLoaderMetaInformation.FromLoader(loader));

                    var initialProgressCallback = true;
                    var reportStopwatch         = Stopwatch.StartNew();
                    var progressStopwatch       = new AsyncProgressBytesStopwatch();

                    if (loader.UsesClientToDownload)
                    {
                        client.DownloadProgressChanged += (sender, args) => {
                            if (initialProgressCallback)
                            {
                                reportMetaInformation?.Invoke(FlexibleLoaderMetaInformation.FromLoader(loader));
                                initialProgressCallback = false;
                            }

                            if (reportStopwatch.Elapsed.TotalMilliseconds < 20)
                            {
                                return;
                            }
                            order.Delay();
                            reportStopwatch.Restart();
                            progress?.Report(AsyncProgressEntry.CreateDownloading(args.BytesReceived, args.TotalBytesToReceive == -1 &&
                                                                                  loader.TotalSize.HasValue ? Math.Max(loader.TotalSize.Value, args.BytesReceived) : args.TotalBytesToReceive,
                                                                                  progressStopwatch));
                        };
                    }

                    var loaded = await loader.DownloadAsync(client, getPreferredDestination, reportDestination, checkIfPaused,
                                                            loader.UsesClientToDownload?null : new Progress <long>(p => {
                        if (initialProgressCallback)
                        {
                            reportMetaInformation?.Invoke(FlexibleLoaderMetaInformation.FromLoader(loader));
                            initialProgressCallback = false;
                        }

                        if (reportStopwatch.Elapsed.TotalMilliseconds < 20)
                        {
                            return;
                        }
                        order.Delay();
                        reportStopwatch.Restart();
                        progress?.Report(loader.TotalSize.HasValue ? AsyncProgressEntry.CreateDownloading(p, loader.TotalSize.Value, progressStopwatch)
                                        : new AsyncProgressEntry(string.Format(UiStrings.Progress_Downloading, p.ToReadableSize(1)), null));
                    }), cancellation);

                    cancellation.ThrowIfCancellationRequested();
                    Logging.Write("Loaded: " + loaded);
                    return(loaded);
                }
            } catch (Exception e) when(cancellation.IsCancellationRequested || e.IsCancelled())
            {
                Logging.Warning("Cancelled");
                throw new OperationCanceledException();
            } catch (Exception e) {
                Logging.Warning(e);
                throw;
            }
        }
Exemple #18
0
        public async Task <Scanned> GetEntriesAsync([NotNull] List <IFileInfo> list, string baseId, string baseName,
                                                    [CanBeNull] IProgress <AsyncProgressEntry> progress, CancellationToken cancellation)
        {
            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Scanning…"));

            var       result         = new List <ContentEntryBase>();
            var       missingContent = false;
            Exception readException  = null;

            var s    = Stopwatch.StartNew();
            var root = new DirectoryNode(_installationParams.FallbackId ?? baseId, null);

            root.ForceName(baseName);

            foreach (var info in list)
            {
                root.Add(info);
            }

            Logging.Debug($"Building tree: {s.Elapsed.TotalMilliseconds:F1} ms");

            s.Restart();
            var queue = new Queue <DirectoryNode>();

            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                var directory = queue.Dequeue();

                ContentEntryBase found;
                try {
                    found = await CheckDirectoryNode(directory, cancellation).ConfigureAwait(false); // WHY IT DOES NOT WORK?

                    if (cancellation.IsCancellationRequested)
                    {
                        break;
                    }
                } catch (Exception e) when(e.IsCancelled())
                {
                    break;
                } catch (MissingContentException) {
                    missingContent = true;
                    continue;
                } catch (Exception e) {
                    Logging.Warning(e);
                    readException = e;
                    continue;
                }

                if (found != null)
                {
                    result.Add(found);
                }
                else
                {
                    foreach (var value in directory.Directories)
                    {
                        queue.Enqueue(value);
                    }

                    foreach (var value in directory.Files)
                    {
                        try {
                            found = await CheckFileNode(value, cancellation).ConfigureAwait(false);

                            if (cancellation.IsCancellationRequested)
                            {
                                break;
                            }
                        } catch (Exception e) when(e.IsCancelled())
                        {
                            break;
                        } catch (MissingContentException) {
                            missingContent = true;
                            continue;
                        } catch (Exception e) {
                            Logging.Warning(e);
                            readException = e;
                            continue;
                        }

                        if (found != null)
                        {
                            result.Add(found);
                        }
                    }
                }
            }

            Logging.Debug($"Scanning directories: {s.Elapsed.TotalMilliseconds:F1} ms");
            return(new Scanned(result, missingContent, readException));
        }
Exemple #19
0
 public void Report(int value)
 {
     _target.Report(value == 0 ? AsyncProgressEntry.Indetermitate :
                    AsyncProgressEntry.FromStringIndetermitate(string.Format(ToolsStrings.OnlineSource_Loading_Fallback, value + 1)));
 }
Exemple #20
0
        public async Task <IReadOnlyList <ServerInformationComplete> > ScanForServers(string address, IProgress <AsyncProgressEntry> progress, CancellationToken cancellation)
        {
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            // assume address is something like [HOSTNAME]:[HTTP PORT]
            if (!KunosApiProvider.ParseAddress(address, out var ip, out var port))
            {
                throw new Exception(ToolsStrings.Online_CannotParseAddress);
            }

            if (port > 0)
            {
                progress?.Report(AsyncProgressEntry.FromStringIndetermitate(ToolsStrings.Online_GettingInformationDirectly));

                ServerInformationComplete information;

                try {
                    information = await KunosApiProvider.GetInformationDirectAsync(ip, port);
                } catch (WebException) {
                    if (cancellation.IsCancellationRequested)
                    {
                        return(null);
                    }

                    // assume address is [HOSTNAME]:[TCP PORT]
                    progress?.Report(AsyncProgressEntry.FromStringIndetermitate(ToolsStrings.Online_TryingToFindOutHttpPort));
                    var pair = await KunosApiProvider.TryToPingServerAsync(ip, port, SettingsHolder.Online.PingTimeout);

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

                    if (pair != null)
                    {
                        progress?.Report(AsyncProgressEntry.FromStringIndetermitate(ToolsStrings.Online_GettingInformationDirectly_SecondAttempt));

                        try {
                            information = await KunosApiProvider.GetInformationDirectAsync(ip, pair.Item1);
                        } catch (WebException) {
                            information = null;
                        }
                    }
                    else
                    {
                        information = null;
                    }
                }

                if (cancellation.IsCancellationRequested)
                {
                    return(null);
                }
                return(information == null ? new ServerInformationComplete[0] : new [] { information });
            }
            else
            {
                var result = new List <ServerInformationComplete>();

                // assume address is [HOSTNAME]
                progress?.Report(AsyncProgressEntry.FromStringIndetermitate(ToolsStrings.Common_Scanning));

                var scanned       = 0;
                var portsDiapason = PortsDiapason.Create(SettingsHolder.Online.PortsEnumeration);
                var total         = portsDiapason.Count();

                await portsDiapason.Select(async p => {
                    var pair = await KunosApiProvider.TryToPingServerAsync(ip, p, SettingsHolder.Online.ScanPingTimeout);
                    if (pair != null && pair.Item1 > 1024 && pair.Item1 < 65536)
                    {
                        if (cancellation.IsCancellationRequested)
                        {
                            return;
                        }

                        try {
                            var information = await KunosApiProvider.GetInformationDirectAsync(ip, pair.Item1);
                            if (cancellation.IsCancellationRequested)
                            {
                                return;
                            }
                            result.Add(information);
                        } catch (WebException) { }
                    }

                    scanned++;
                    progress?.Report(new AsyncProgressEntry(string.Format(ToolsStrings.Online_ScanningProgress, scanned, total,
                                                                          PluralizingConverter.PluralizeExt(result.Count, ToolsStrings.Online_ScanningProgress_Found)), scanned, total));
                }).WhenAll(200, cancellation);

                return(result);
            }
        }
Exemple #21
0
        public async Task <WorkshopUploadResult> UploadAsync(byte[] data, string group, string name,
                                                             IProgress <AsyncProgressEntry> progress = null, CancellationToken cancellation = default)
        {
            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Authorizing…"));
            await Authorize().WithCancellation(cancellation).ConfigureAwait(false);

            cancellation.ThrowIfCancellationRequested();

            progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Finding a vault to upload…"));
            var uploadUrl = await _b2Client.Files.GetUploadUrl(cancelToken : cancellation);

            cancellation.ThrowIfCancellationRequested();

            for (var i = 0; i < 4; ++i)
            {
                progress?.Report(AsyncProgressEntry.FromStringIndetermitate(i == 0
                        ? "Starting upload…"
                        : $"Trying again, {(i + 1).ToOrdinal("attempt").ToSentenceMember()} attempt"));
                try {
                    return(await TryToUploadAsync(uploadUrl));
                } catch (B2Exception e) when(e.Code == "bad_auth_token" || e.ShouldRetryRequest)
                {
                    cancellation.ThrowIfCancellationRequested();
                    uploadUrl = await _b2Client.Files.GetUploadUrl(cancelToken : cancellation);
                } catch (HttpRequestException e) {
                    Logging.Warning(e);
                    cancellation.ThrowIfCancellationRequested();
                    progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Target vault is not available, waiting a bit before the next attempt…"));
                    await Task.Delay(TimeSpan.FromSeconds(i + 1d));

                    cancellation.ThrowIfCancellationRequested();
                } catch (WebException e) {
                    Logging.Warning(e);
                    cancellation.ThrowIfCancellationRequested();
                    progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Target vault is not available, waiting a bit before the next attempt…"));
                    await Task.Delay(TimeSpan.FromSeconds(i + 1d));

                    cancellation.ThrowIfCancellationRequested();
                } catch (B2Exception e) when(e.Status == "500" || e.Status == "503")
                {
                    Logging.Warning(e);
                    cancellation.ThrowIfCancellationRequested();
                    progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Target vault is not full, waiting a bit before the next attempt…"));
                    await Task.Delay(TimeSpan.FromSeconds(i + 1d));

                    cancellation.ThrowIfCancellationRequested();
                } catch (B2Exception e) {
                    Logging.Warning("B2Exception.Code=" + e.Code);
                    Logging.Warning("B2Exception.Status=" + e.Status);
                    Logging.Warning("B2Exception.Message=" + e.Message);
                    Logging.Warning("B2Exception.ShouldRetryRequest=" + e.ShouldRetryRequest);
                    throw;
                }
            }

            cancellation.ThrowIfCancellationRequested();
            progress?.Report(AsyncProgressEntry.FromStringIndetermitate($"Trying again, last attempt"));
            return(await TryToUploadAsync(uploadUrl));

            async Task <WorkshopUploadResult> TryToUploadAsync(B2UploadUrl url)
            {
                var fileName  = _b2ClientPrefix + group + "/" + name;
                var stopwatch = new AsyncProgressBytesStopwatch();
                var file      = await _b2Client.Files.Upload(data, fileName, url, "", "", new Dictionary <string, string> {
                    ["b2-content-disposition"] = Regex.IsMatch(name, @"\.(png|jpg)$") ? "inline" : "attachment",
                    ["b2-cache-control"]       = "immutable"
                }, progress == null?null : new Progress <long>(x => progress.Report(AsyncProgressEntry.CreateUploading(x, data.Length, stopwatch))),
                                                             cancellation).ConfigureAwait(false);

                return(new WorkshopUploadResult {
                    Tag = JsonConvert.SerializeObject(new { fileName = file.FileName, fileID = file.FileId }),
                    Size = data.LongLength
                });
            }
        }
Exemple #22
0
        private static async Task ShowCarInShowroomAsync(string carId)
        {
            if (_showingCarInShowroom)
            {
                return;
            }
            _showingCarInShowroom = true;

            try {
                var temporaryDirectory = FilesStorage.Instance.GetTemporaryDirectory("Workshop", "Showroom", carId);
                var temporaryFilename  = Path.Combine(temporaryDirectory, "data.zip");

                byte[] modelData  = null;
                string mainSkidId = null;
                var    carData    = new VirtualDataWrapper();

                using (var waiting = WaitingDialog.Create("Loading showroom…")) {
                    await WorkshopHolder.Client.DownloadFileAsync($"/cars/{carId}/download-showroom", temporaryFilename, false,
                                                                  waiting, waiting.CancellationToken);

                    waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Loading…"));

                    await Task.Run(() => {
                        using (var stream = File.OpenRead(temporaryFilename))
                            using (var archive = new ZipArchive(stream)) {
                                foreach (var entry in archive.Entries)
                                {
                                    if (entry.Length == 0)
                                    {
                                        continue;
                                    }
                                    if (entry.FullName == @"model.kn5")
                                    {
                                        modelData = entry.Open().ReadAsBytesAndDispose();
                                    }
                                    else if (entry.FullName.StartsWith(@"data"))
                                    {
                                        carData.Data[Path.GetFileName(entry.FullName)] = entry.Open().ReadAsStringAndDispose();
                                    }
                                    else
                                    {
                                        if (mainSkidId == null && entry.FullName.StartsWith(@"skins"))
                                        {
                                            mainSkidId = Path.GetFileName(Path.GetDirectoryName(entry.FullName));
                                        }
                                        var newFilename = Path.Combine(temporaryDirectory, entry.FullName);
                                        FileUtils.EnsureFileDirectoryExists(newFilename);
                                        entry.ExtractToFile(newFilename, true);
                                    }
                                    waiting.CancellationToken.ThrowIfCancellationRequested();
                                }
                            }
                    });

                    waiting.CancellationToken.ThrowIfCancellationRequested();
                }

                if (modelData == null)
                {
                    throw new Exception("Model is missing");
                }

                if (mainSkidId == null)
                {
                    throw new Exception("Skins are missing");
                }

                var description = CarDescription.FromKn5(Kn5.FromBytes(modelData), temporaryDirectory, carData);
                var renderer    = new DarkKn5ObjectRenderer(description)
                {
                    FlatMirror = true,
                    FlatMirrorReflectiveness = 0.3f,
                    FlatMirrorReflectedLight = true,
                    BackgroundColor          = Color.White,
                    BackgroundBrightness     = 0.05f,
                    LightBrightness          = 2f,
                    AmbientBrightness        = 2f,
                    AmbientUp                   = Color.FromArgb(0xEEEEEE),
                    AmbientDown                 = Color.FromArgb(0x333333),
                    UseDof                      = true,
                    UseAccumulationDof          = true,
                    AccumulationDofIterations   = 40,
                    AccumulationDofApertureSize = 0f,
                    UseSslr                     = true,
                    VisibleUi                   = false,
                    UseSprite                   = false,
                    AnyGround                   = false,
                    ToneMapping                 = ToneMappingFn.Uncharted2,
                    ToneExposure                = 1.2f,
                    ToneGamma                   = 1f,
                    ToneWhitePoint              = 2.2f,
                };
                renderer.SelectSkin(mainSkidId);
                await FormWrapperBase.PrepareAsync();

                var wrapper = new LiteShowroomFormWrapper(renderer);
                wrapper.Form.Icon = AppIconService.GetAppIcon();
                CustomShowroomWrapper.SetProperties(wrapper, renderer);
                wrapper.Run();
            } catch (Exception e) when(!e.IsCancelled())
            {
                Logging.Warning(e);
                NonfatalError.Notify("Failed to load showroom", e);
            } finally {
                _showingCarInShowroom = false;
            }
        }
 public void Report(int value)
 {
     _target.Report(value == 0 ? AsyncProgressEntry.Indetermitate :
                    AsyncProgressEntry.FromStringIndetermitate($"Fallback to server #{value + 1}"));
 }
Exemple #24
0
        private async Task RunWrapper(string serverExecutable, ICollection <string> log, IProgress <AsyncProgressEntry> progress, CancellationToken cancellation)
        {
            progress.Report(AsyncProgressEntry.FromStringIndetermitate("Loading wrapper…"));
            var wrapperFilename = await LoadWinWrapper(cancellation);

            if (cancellation.IsCancellationRequested)
            {
                return;
            }

            if (wrapperFilename == null)
            {
                throw new InformativeException("Can’t run server", "Can’t load server wrapper.");
            }

            try {
                using (var process = ProcessExtension.Start(wrapperFilename, new[] {
                    "-e", serverExecutable, $"presets/{Id}"
                }, new ProcessStartInfo {
                    UseShellExecute = false,
                    WorkingDirectory = Path.GetDirectoryName(serverExecutable) ?? "",
                    RedirectStandardOutput = true,
                    CreateNoWindow = true,
                    RedirectStandardError = true,
                    StandardOutputEncoding = Encoding.UTF8,
                    StandardErrorEncoding = Encoding.UTF8,
                })) {
                    process.Start();
                    SetRunning(process);
                    ChildProcessTracker.AddProcess(process);

                    progress?.Report(AsyncProgressEntry.Finished);
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    process.OutputDataReceived += (sender, args) => {
                        if (!string.IsNullOrWhiteSpace(args.Data))
                        {
                            ActionExtension.InvokeInMainThread(() => log.Add(Regex.Replace(args.Data, @"\b(WARNING: .+)", @"[color=#ff8800]$1[/color]")));
                        }
                    };

                    process.ErrorDataReceived += (sender, args) => {
                        if (!string.IsNullOrWhiteSpace(args.Data))
                        {
                            ActionExtension.InvokeInMainThread(() => log.Add($@"[color=#ff0000]{args.Data}[/color]"));
                        }
                    };

                    await process.WaitForExitAsync(cancellation);

                    if (!process.HasExitedSafe())
                    {
                        process.Kill();
                    }

                    log.Add($@"[CM] Stopped: {process.ExitCode}");
                }
            } finally {
                SetRunning(null);
            }
        }
Exemple #25
0
        private static async Task <IReadOnlyList <ExtraOption> > GetGbwRelatedExtraOptions(ContentEntryBase[] entries)
        {
            const string gbwWeatherPart  = "_gbW_";
            const string gbwPpFilterPart = "__gbW";

            if (!entries.Any(x => x.Id.Contains(gbwWeatherPart)))
            {
                // This is not the GBW pack
                return(new ExtraOption[0]);
            }

            var gbwWeatherIds = entries.Where(x => x.Id.Contains(gbwWeatherPart) && x is WeatherContentEntry)
                                .Select(x => x.Id).ToList();

            if (gbwWeatherIds.Count < 10)
            {
                // It contains some GBW weather, but not a lot — not the pack
                return(new ExtraOption[0]);
            }

            await WeatherManager.Instance.EnsureLoadedAsync();

            // Now, when data is loaded, we’re ready to create some extra options
            IEnumerable <ExtraOption> GetOptions()
            {
                {
                    var installedWeatherIds = WeatherManager.Instance.WrappersList.Select(x => x.Id).Where(x => x.Contains(gbwWeatherPart)).ToList();
                    var obsoleteWeatherIds  = installedWeatherIds.ApartFrom(gbwWeatherIds).ToList();

                    if (obsoleteWeatherIds.Count > 0)
                    {
                        var obsoleteLine = obsoleteWeatherIds.Select(x => $"“{WeatherManager.Instance.GetById(x)?.DisplayName ?? x}”")
                                           .JoinToReadableString();
                        yield return(new ExtraOption("Remove obsolete GBW weather",
                                                     $"Installed, but not found here: {obsoleteLine}.",
                                                     async(progress, cancellation) => {
                            progress.Report(AsyncProgressEntry.FromStringIndetermitate("Removing obsolete GBW weather…"));
                            await WeatherManager.Instance.EnsureLoadedAsync();
                            await WeatherManager.Instance.DeleteAsync(obsoleteWeatherIds);
                        }, activeByDefault: true));
                    }
                }

                {
                    var gbwPpFilterIds = entries.Where(x => x.Id.Contains(gbwPpFilterPart) && x is PpFilterContentEntry)
                                         .Select(x => x.Id).ToList();
                    var installedPpFilterIds = PpFiltersManager.Instance.WrappersList.Select(x => x.Id).Where(x => x.Contains(gbwPpFilterPart)).ToList();
                    var obsoletePpFilterIds  = installedPpFilterIds.ApartFrom(gbwPpFilterIds).ToList();

                    if (obsoletePpFilterIds.Count > 0)
                    {
                        var obsoleteLine = obsoletePpFilterIds.Select(x => $"“{PpFiltersManager.Instance.GetById(x)?.DisplayName ?? x}”")
                                           .JoinToReadableString();
                        yield return(new ExtraOption("Remove obsolete GBW PP-filters",
                                                     $"Installed, but not found here: {obsoleteLine}.",
                                                     async(progress, cancellation) => {
                            progress.Report(AsyncProgressEntry.FromStringIndetermitate("Removing obsolete GBW PP-filters…"));
                            await PpFiltersManager.Instance.EnsureLoadedAsync();
                            await PpFiltersManager.Instance.DeleteAsync(obsoletePpFilterIds);
                        }, activeByDefault: true));
                    }
                }
            }

            return(GetOptions().ToList());
        }
Exemple #26
0
        private async Task RunShootingProcess(bool manualMode = false)
        {
            if (SelectedShowroom == null)
            {
                if (ShowMessage(AppStrings.CarPreviews_ShowroomIsMissingOptions, AppStrings.Common_OneMoreThing, MessageBoxButton.YesNo) ==
                    MessageBoxResult.Yes)
                {
                    SelectPhase(Phase.Options);
                }
                else
                {
                    _cancelled = true;
                    Top        = -9999;
                    await Task.Delay(1);

                    Close();
                }
                return;
            }

            if (SelectedFilter == null)
            {
                if (ShowMessage(AppStrings.CarPreviews_FilterIsMissingOptions, AppStrings.Common_OneMoreThing, MessageBoxButton.YesNo) ==
                    MessageBoxResult.Yes)
                {
                    SelectPhase(Phase.Options);
                }
                else
                {
                    _cancelled = true;
                    Top        = -9999;
                    await Task.Delay(1);

                    Close();
                }
                return;
            }

            if (_toUpdate.Any(u => !u.Car.Enabled || u.Skins?.Any(x => x.Enabled == false) == true))
            {
                SelectPhase(Phase.Error, AppStrings.CarPreviews_CannotUpdateForDisabled);
                return;
            }

            Progress = AsyncProgressEntry.FromStringIndetermitate(UiStrings.Common_PleaseWait);
            SelectPhase(Phase.Waiting);

            _cancellationTokenSource = new CancellationTokenSource();

            try {
                string filterId;

                var builtInPpFilter = SelectedFilter as BuiltInPpFilter;
                if (builtInPpFilter != null)
                {
                    builtInPpFilter.EnsureInstalled();
                    filterId = builtInPpFilter.Name;
                }
                else
                {
                    var filterObject = SelectedFilter as PpFilterObject;
                    filterId = filterObject?.Name;
                }

                var begin = DateTime.Now;

                if (_toUpdate.Count > 1 && !ApplyImmediately)
                {
                    throw new Exception("Can’t apply previews later if there are more than one car");
                }

                for (var i = 0; i < _toUpdate.Count; i++)
                {
                    var toUpdate = _toUpdate[i];
                    SeriesProgress = new AsyncProgressEntry(toUpdate.Car.DisplayName, i, _toUpdate.Count);

                    await ShootCar(toUpdate, filterId, manualMode, ApplyImmediately, _cancellationTokenSource.Token);

                    if (_cancellationTokenSource.IsCancellationRequested)
                    {
                        SelectPhase(Phase.Error, AppStrings.CarPreviews_CancelledMessage);
                        return;
                    }
                }

                TakenTime = DateTime.Now - begin;
                SelectPhase(ApplyImmediately ? Phase.ResultSummary : Phase.Result);
            } catch (ShotingCancelledException e) {
                SelectPhase(Phase.Error, e.UserCancelled ? AppStrings.CarPreviews_CancelledMessage : e.Message);

                if (!e.UserCancelled)
                {
                    Logging.Warning("Cannot update previews: " + e);
                }
            } catch (ProcessExitedException e) {
                SelectPhase(Phase.Error, e.Message, AcLogHelper.TryToDetermineWhatsGoingOn());
                Logging.Warning("Cannot update previews: " + e);
            } catch (Exception e) {
                SelectPhase(Phase.Error, e.Message);
                Logging.Warning("Cannot update previews: " + e);
            }
        }
 protected override Task <bool> FixAsync(CarObject car, IProgress <AsyncProgressEntry> progress = null,
                                         CancellationToken cancellation = default(CancellationToken))
 {
     progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Fixing car…"));
     return(CarReplaceTyresDialog.Run(car));
 }