示例#1
0
            public void SetCars(string json)
            {
                Sync(async() => {
                    if (json == null || Associated == null)
                    {
                        return;
                    }

                    var ids = JArray.Parse(json).ToObject <string[]>();
                    var i   = 0;
                    using (var waiting = new WaitingDialog()) {
                        waiting.Report(0);

                        foreach (var id in ids.NonNull())
                        {
                            var car = await CarsManager.Instance.GetByIdAsync(id);
                            if (car == null)
                            {
                                continue;
                            }

                            await car.SkinsManager.EnsureLoadedAsync();

                            var skins = car.SkinsManager.LoadedOnly.ToList();
                            var skin  = skins.FirstOrDefault();
                            if (skin == null)
                            {
                                continue;
                            }

                            var liveries = new StringBuilder();
                            foreach (var x in skins)
                            {
                                liveries.Append(
                                    $@"<img data-skin-id='{HttpUtility.HtmlEncode(x.Id)}' width=24 style='margin-left:2px' src='{await
                                                Associated.GetImageUrlAsync(x.LiveryImage)}'>");
                            }

                            Associated.Execute($@"
document.querySelector('[id^=""{id}1""]').innerHTML = ""<img width=280 style='margin-right:10px' src='{await Associated.GetImageUrlAsync(skin.PreviewImage)}'>"";
document.querySelector('[id^=""{id}2""]').innerHTML = ""{HttpUtility.HtmlEncode(car.DisplayName)}<img width=48 style='margin-left:2px;margin-right:10px;margin-top:-10px;float:left' src='{await
                                    Associated.GetImageUrlAsync(car.LogoIcon)}'>"";
document.querySelector('[id^=""{id}3""]').innerHTML = ""{liveries}"";
document.querySelector('[id^=""{id}4""]').textContent = {JsonConvert.SerializeObject(skin.Id)};

var l = document.querySelectorAll('[id^=""{id}3""] img');
for (var i = 0; i < l.length; i++){{
    l[i].addEventListener('click', function(){{
        var s = this.getAttribute('data-skin-id');
        document.querySelector('[id^=""{id}4""]').innerHTML = s;
        window.external.UpdatePreview(""{id}"", s);
    }}, false);                   
}}
");

                            waiting.Report(new AsyncProgressEntry(car.DisplayName, i++, ids.Length));
                        }
                    }
                });
            }
示例#2
0
        public static WaitingDialog Create(string reportValue)
        {
            var w = new WaitingDialog();

            w.Report(reportValue);
            return(w);
        }
示例#3
0
        private static async Task InstallShowroom(string showroomName, string showroomId, CarUpdatePreviewsDialog instance = null)
        {
            if (instance != null)
            {
                instance._mode = UpdatePreviewMode.Options;
                await Task.Delay(100);
            }

            using (var dialog = new WaitingDialog(showroomName)) {
                dialog.Report(ControlsStrings.Common_Downloading);

                var destination = FileUtils.GetShowroomsDirectory(AcRootDirectory.Instance.Value);
                var data        = await CmApiProvider.GetDataAsync($"static/get/{showroomId}", dialog, dialog.CancellationToken);

                if (data == null)
                {
                    dialog.Close();
                    NonfatalError.Notify(string.Format(AppStrings.CarPreviews_CannotDownloadShowroom, showroomName), ToolsStrings.Common_CannotDownloadFile_Commentary);
                    return;
                }

                dialog.Content = ControlsStrings.Common_Installing;
                try {
                    await Task.Run(() => {
                        using (var stream = new MemoryStream(data, false))
                            using (var archive = new ZipArchive(stream)) {
                                archive.ExtractToDirectory(destination);
                            }
                    });
                } catch (Exception e) {
                    dialog.Close();
                    NonfatalError.Notify(string.Format(AppStrings.CarPreviews_CannotInstallShowroom, showroomName), e);
                    return;
                }

                await Task.Delay(1000);

                if (instance != null)
                {
                    instance.SelectedShowroom = ShowroomsManager.Instance.GetById(showroomId) ?? instance.SelectedShowroom;
                }
            }
        }
示例#4
0
        private async Task Apply()
        {
            if (_resultDirectory == null)
            {
                return;
            }

            using (var waiting = new WaitingDialog {
                Owner = Application.Current?.MainWindow
            }) {
                try {
                    var car = _toUpdate[0].Car;
                    await ImageUtils.ApplyPreviewsAsync(AcRootDirectory.Instance.RequireValue, car.Id, _resultDirectory, ResizePreviews,
                                                        new AcPreviewImageInformation {
                        Name  = car.DisplayName,
                        Style = Path.GetFileNameWithoutExtension(UserPresetsControl.SelectedPresetFilename)
                    }, waiting, waiting.CancellationToken);
                } catch (Exception e) {
                    NonfatalError.Notify(AppStrings.CarPreviews_CannotSave, e);
                }
            }
        }
示例#5
0
        public static async Task ShareAsync(SharedEntryType type, [CanBeNull] string defaultName, [CanBeNull] string target, [NotNull] byte[] data)
        {
            if (_sharingInProcess)
            {
                return;
            }
            _sharingInProcess = true;

            try {
                var contentName = defaultName;
                if (!SettingsHolder.Sharing.ShareWithoutName)
                {
                    contentName = Prompt.Show(ControlsStrings.Share_EnterName, ControlsStrings.Share_EnterNameHeader, defaultName, ToolsStrings.Common_None,
                                              maxLength: 60);
                    if (contentName == null)
                    {
                        return;                      // cancelled
                    }
                    if (string.IsNullOrWhiteSpace(contentName))
                    {
                        contentName = null;
                    }
                }

                string id = null;
                if (SettingsHolder.Sharing.CustomIds)
                {
                    id =
                        Prompt.Show(ControlsStrings.Share_EnterCustomId, ControlsStrings.Share_EnterCustomIdHeader, "", ToolsStrings.Common_None,
                                    maxLength: 200)?.Trim();
                    if (id == null)
                    {
                        return;             // cancelled
                    }
                    if (string.IsNullOrWhiteSpace(id))
                    {
                        id = null;
                    }
                }

                var authorName = SettingsHolder.Sharing.ShareAnonymously ? null : SettingsHolder.Sharing.SharingName;
                if (SettingsHolder.Sharing.VerifyBeforeSharing && ModernDialog.ShowMessage(
                        string.Format(ControlsStrings.Share_VerifyMessage, authorName ?? @"?", contentName ?? @"?",
                                      type.GetDescription()), ControlsStrings.Share_VerifyMessageHeader, MessageBoxButton.YesNo) != MessageBoxResult.Yes)
                {
                    return;
                }

                string link;
                using (var waiting = new WaitingDialog()) {
                    waiting.Report(ControlsStrings.Share_InProgress);

                    link = await SharingHelper.ShareAsync(type, contentName, target, data, id, waiting.CancellationToken);

                    if (link == null)
                    {
                        return;
                    }
                }

                ShowShared(type, link);
                await Task.Delay(2000);
            } catch (Exception e) {
                NonfatalError.Notify(string.Format(ControlsStrings.Share_CannotShare, type.GetDescription()), ToolsStrings.Common_CannotDownloadFile_Commentary,
                                     e);
            } finally {
                _sharingInProcess = false;
            }
        }
示例#6
0
            public void SetCars(string json) {
                Sync(async () => {
                    if (json == null || Associated == null) return;

                    var ids = JArray.Parse(json).ToObject<string[]>();
                    var i = 0;
                    using (var waiting = new WaitingDialog()) {
                        waiting.Report(0);

                        foreach (var id in ids.NonNull()) {
                            var car = await CarsManager.Instance.GetByIdAsync(id);
                            if (car == null) continue;

                            await car.SkinsManager.EnsureLoadedAsync();

                            var skins = car.SkinsManager.LoadedOnly.ToList();
                            var skin = skins.FirstOrDefault();
                            if (skin == null) continue;

                            var liveries = new StringBuilder();
                            foreach (var x in skins) {
                                liveries.Append(
                                        $@"<img data-skin-id='{HttpUtility.HtmlEncode(x.Id)}' width=24 style='margin-left:2px' src='{await
                                                Associated.GetImageUrlAsync(x.LiveryImage)}'>");
                            }

                            Associated.Execute($@"
document.querySelector('[id^=""{id}1""]').innerHTML = ""<img width=280 style='margin-right:10px' src='{await Associated.GetImageUrlAsync(skin.PreviewImage)}'>"";
document.querySelector('[id^=""{id}2""]').innerHTML = ""{HttpUtility.HtmlEncode(car.DisplayName)}<img width=48 style='margin-left:2px;margin-right:10px;margin-top:-10px;float:left' src='{await
                                    Associated.GetImageUrlAsync(car.LogoIcon)}'>"";
document.querySelector('[id^=""{id}3""]').innerHTML = ""{liveries}"";
document.querySelector('[id^=""{id}4""]').textContent = {JsonConvert.SerializeObject(skin.Id)};

var l = document.querySelectorAll('[id^=""{id}3""] img');
for (var i = 0; i < l.length; i++){{
    l[i].addEventListener('click', function(){{
        var s = this.getAttribute('data-skin-id');
        document.querySelector('[id^=""{id}4""]').innerHTML = s;
        window.external.UpdatePreview(""{id}"", s);
    }}, false);                   
}}
");

                            waiting.Report(new AsyncProgressEntry(car.DisplayName, i++, ids.Length));
                        }
                    }
                });
            }
示例#7
0
        public static async Task ShareReplay(string name, string filename, [CanBeNull] CarObject car, [CanBeNull] TrackObjectBase track, bool forceUpload)
        {
            if (!forceUpload)
            {
                var existing = GetShared(filename);
                if (existing != null)
                {
                    SharingUiHelper.ShowShared(SharedEntryType.Replay, existing);
                    return;
                }
            }

            UploadResult result;

            try {
                using (var waiting = new WaitingDialog(ControlsStrings.Common_Uploading)) {
                    waiting.Report(ControlsStrings.Common_Preparing);

                    var uploader = LargeFileUploaderParams.ShareReplays.SelectedUploader;
                    await uploader.SignInAsync(waiting.CancellationToken);

                    waiting.Report(ControlsStrings.Common_Compressing);

                    using (var memory = new MemoryStream()) {
                        await Task.Run(() => {
                            using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                                using (var writer = WriterFactory.Open(memory, ArchiveType.Zip, CompressionType.Deflate)) {
                                    var readMe = string.Format(AppStrings.Replay_SharedReadMe, GetDescription(car, track),
                                                               Path.GetFileName(filename));
                                    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(readMe))) {
                                        writer.Write(@"ReadMe.txt", stream);
                                    }

                                    writer.Write(Path.GetFileName(filename), file, new FileInfo(filename).CreationTime);
                                }

                                Logging.Write($"Compressed: {file.Length.ToReadableSize()} to {memory.Position.ToReadableSize()}");
                            }
                        });

                        memory.Position = 0;
                        result          = await uploader.UploadAsync(name ?? AppStrings.Replay_DefaultUploadedName,
                                                                     Path.GetFileNameWithoutExtension(filename) + @".zip",
                                                                     @"application/zip", GetDescription(car, track), memory, UploadAs.Replay, waiting,
                                                                     waiting.CancellationToken);
                    }
                }
            } catch (Exception e) when(e.IsCancelled())
            {
                return;
            } catch (WebException e) {
                NonfatalError.Notify(AppStrings.Replay_CannotShare, ToolsStrings.Common_MakeSureInternetWorks, e);
                return;
            } catch (Exception e) {
                NonfatalError.Notify(AppStrings.Replay_CannotShare, e);
                return;
            }

            SharingHelper.Instance.AddToHistory(SharedEntryType.Replay, name, car?.DisplayName, result);
            SharingUiHelper.ShowShared(SharedEntryType.Replay, result.Url);
            SetShared(filename, result.Url);
        }