예제 #1
0
        /// <summary>
        /// Attempts to download a string from a remote URL. Throws WebException if anything goes awry/the request times out/task is cancelled.
        /// </summary>
        /// <param name="Url">The URL to download the string from.</param>
        /// <param name="TimeOut">After this specified amount of time in seconds, the request will timeout.</param>
        /// <param name="cancellationToken">The cancellation token to use for the download task.</param>
        /// <returns>The downloaded string, or null if it failed to download.</returns>
        public static async Task <string> DownloadStringTimeoutAsync(string Url, int TimeOut, CancellationToken cancellationToken)
        {
            string downloadResult = null;

            WebClientWithTimeout webClient = new WebClientWithTimeout(TimeOut);

            webClient.Headers["user-agent"] = "WebUtils Parsing";

            using (webClient)
            {
                using (var registration = cancellationToken.Register(() => webClient.CancelAsync()))
                {
                    downloadResult = await webClient.DownloadStringTaskAsync(Url);
                }
            }

            return(downloadResult);
        }
예제 #2
0
        public void checkAvailability()
        {
            text.Text        = "Launcher Status - Checking...";
            description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7);
            status.Image     = Properties.Resources.ac_unknown;
            text.ForeColor   = Color.FromArgb(0x848484);

            try {
                WebClientWithTimeout update_data = new WebClientWithTimeout();
                update_data.CancelAsync();
                update_data.DownloadStringAsync(new Uri(Self.mainserver + "/update.php?version=" + Application.ProductVersion));
                update_data.DownloadStringCompleted += (sender, e) => {
                    if (description.InvokeRequired == true)
                    {
                        description.Invoke(new Action(delegate()
                        {
                            description.Visible = true;
                        }));
                    }
                    else
                    {
                        description.Visible = true;
                    }

                    if (e.Cancelled)
                    {
                        text.Text        = "Launcher Status - Error";
                        status.Image     = Properties.Resources.ac_error;
                        text.ForeColor   = Color.FromArgb(254, 0, 0);
                        description.Text = "Event cancelled.";
                    }
                    else if (e.Error != null)
                    {
                        text.Text        = "Launcher Status";
                        status.Image     = Properties.Resources.ac_success;
                        text.ForeColor   = Color.FromArgb(0x9fc120);
                        description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7);
                    }
                    else
                    {
                        UpdateCheckResponse updater = JsonConvert.DeserializeObject <UpdateCheckResponse>(e.Result);

                        try {
                            if (updater.Code == 0)
                            {
                                if (updater.Payload.UpdateExists == false)
                                {
                                    if (updater.Payload.LatestVersion.CompareTo(updater.Payload.ClientVersion) >= 0)
                                    {
                                        text.Text      = "Launcher Status - Updated";
                                        status.Image   = Properties.Resources.ac_success;
                                        text.ForeColor = Color.FromArgb(0x9fc120);
                                    }
                                    else
                                    {
                                        text.Text      = "Launcher Status - Prerelease";
                                        status.Image   = Properties.Resources.ac_warning;
                                        text.ForeColor = Color.Yellow;
                                    }

                                    description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7);
                                }
                                else
                                {
                                    text.Text        = "Launcher Status - Available";
                                    status.Image     = Properties.Resources.ac_warning;
                                    text.ForeColor   = Color.Yellow;
                                    description.Text = "New Version : " + updater.Payload.LatestVersion;

                                    var settingFile = new IniFile("Settings.ini");
                                    if (settingFile.Read("IgnoreUpdateVersion") != updater.Payload.LatestVersion)
                                    {
                                        var dia = new TaskDialog {
                                            Caption               = "Update",
                                            InstructionText       = "An update is available!",
                                            DetailsExpanded       = true,
                                            Icon                  = TaskDialogStandardIcon.Warning,
                                            DetailsCollapsedLabel = "Show Changelog",
                                            Text                  = "An update is available. Do you want to download it?\nYour version: " +
                                                                    Application.ProductVersion + "\nUpdated version: " + updater.Payload.LatestVersion,
                                            DetailsExpandedText =
                                                new WebClientWithTimeout().DownloadString(Self.mainserver + "/launcher/changelog"),
                                            ExpansionMode = TaskDialogExpandedDetailsLocation.ExpandFooter
                                        };

                                        var update     = new TaskDialogCommandLink("update", "Yes", "Launcher will be updated to " + updater.Payload.LatestVersion + ".");
                                        var cancel     = new TaskDialogCommandLink("cancel", "No", "Launcher will ask you to update on the next launch.");
                                        var skipupdate = new TaskDialogCommandLink("skipupdate", "Ignore", "This update will be skipped. A new prompt will apear as soon as a newer update is available.");

                                        update.UseElevationIcon = true;

                                        skipupdate.Click += (sender3, e3) => {
                                            settingFile.Write("IgnoreUpdateVersion", updater.Payload.LatestVersion);
                                            dia.Close();
                                        };

                                        cancel.Click += (sender3, e3) => {
                                            dia.Close();
                                        };

                                        update.Click += (sender3, e3) => {
                                            if (File.Exists("GameLauncherUpdater.exe"))
                                            {
                                                Process.Start(@"GameLauncherUpdater.exe", Process.GetCurrentProcess().Id.ToString());
                                            }
                                            else
                                            {
                                                Process.Start(@"https://github.com/worldunitedgg/GameLauncher_NFSW/releases/latest");
                                            }

                                            dia.Close();
                                        };

                                        dia.Controls.Add(update);
                                        dia.Controls.Add(cancel);
                                        dia.Controls.Add(skipupdate);

                                        dia.Show();
                                    }
                                }
                            }
                            else
                            {
                                text.Text        = "Launcher Status - GitHub Error";
                                status.Image     = Properties.Resources.ac_error;
                                text.ForeColor   = Color.FromArgb(254, 0, 0);
                                description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7);
                            }
                        } catch (Exception) {
                            if (text.InvokeRequired == true) //checks skip, because we only need to know if we can access ui from actual thread
                            {
                                text.Invoke(new Action(delegate()
                                {
                                    text.Text      = "Launcher Status - Backend Error";
                                    text.ForeColor = Color.FromArgb(254, 0, 0);
                                }));
                                status.Invoke(new Action(delegate()
                                {
                                    status.Image = Properties.Resources.ac_error;
                                }));
                                description.Invoke(new Action(delegate()
                                {
                                    description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7);
                                }));
                            }
                            else
                            {
                                text.Text        = "Launcher Status - Backend Error";
                                status.Image     = Properties.Resources.ac_error;
                                text.ForeColor   = Color.FromArgb(254, 0, 0);
                                description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7);
                            }
                        }
                    }
                };
            } catch {
                text.Text        = "Launcher Status - Internal Error";
                status.Image     = Properties.Resources.ac_error;
                text.ForeColor   = Color.FromArgb(254, 0, 0);
                description.Text = "Version : v" + Application.ProductVersion + "build-" + SHA.HashFile(AppDomain.CurrentDomain.FriendlyName).Substring(0, 7);
            }
        }
예제 #3
0
        public void checkAvailability()
        {
            text.Text        = "Launcher Status - Checking...";
            description.Text = "Version : v" + Application.ProductVersion;
            status.Image     = Properties.Resources.ac_unknown;
            text.ForeColor   = Color.FromArgb(0x848484);

            try {
                WebClientWithTimeout update_data = new WebClientWithTimeout();
                update_data.CancelAsync();
                update_data.DownloadStringAsync(new Uri(Self.mainserver + "/update.php?version=" + Application.ProductVersion));
                update_data.DownloadStringCompleted += (sender, e) => {
                    if (description.InvokeRequired == true)
                    {
                        description.Invoke(new Action(delegate() {
                            description.Visible = true;
                        }));
                    }
                    else
                    {
                        description.Visible = true;
                    }

                    if (e.Cancelled)
                    {
                        text.Text        = "Launcher Status - Error";
                        status.Image     = Properties.Resources.ac_error;
                        text.ForeColor   = Color.FromArgb(254, 0, 0);
                        description.Text = "Event cancelled.";
                    }
                    else if (e.Error != null)
                    {
                        text.Text        = "Launcher Status";
                        status.Image     = Properties.Resources.ac_success;
                        text.ForeColor   = Color.FromArgb(0x9fc120);
                        description.Text = "Version : v" + Application.ProductVersion;
                    }
                    else
                    {
                        UpdateCheckResponse updater = JsonConvert.DeserializeObject <UpdateCheckResponse>(e.Result);

                        try {
                            if (updater.Code == 0)
                            {
                                if (updater.Payload.UpdateExists == false)
                                {
                                    if (updater.Payload.LatestVersion.CompareTo(updater.Payload.ClientVersion) >= 0)
                                    {
                                        text.Text      = "Launcher Status - Updated";
                                        status.Image   = Properties.Resources.ac_success;
                                        text.ForeColor = Color.FromArgb(0x9fc120);
                                    }
                                    else
                                    {
                                        text.Text      = "Launcher Status - Prerelease";
                                        status.Image   = Properties.Resources.ac_warning;
                                        text.ForeColor = Color.Yellow;
                                    }

                                    description.Text = "Version : v" + Application.ProductVersion;
                                }
                                else
                                {
                                    text.Text        = "Launcher Status - Available";
                                    status.Image     = Properties.Resources.ac_warning;
                                    text.ForeColor   = Color.Yellow;
                                    description.Text = "New Version : " + updater.Payload.LatestVersion;

                                    Application.DoEvents();
                                    Thread.Sleep(3000);

                                    DialogResult updateConfirm = new UpdatePopup(updater).ShowDialog();

                                    if (updateConfirm == DialogResult.OK)
                                    {
                                        progress.Text = "DOWNLOADING GAMELAUNCHERUPDATER.EXE";
                                        new WebClientWithTimeout().DownloadFile(new Uri(Self.fileserver + "/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe");
                                        Process.Start(@"GameLauncherUpdater.exe", Process.GetCurrentProcess().Id.ToString());
                                        //Let's fetch new downloader

                                        /*Properties.Settings.Default.IsRestarting = false;
                                         * Properties.Settings.Default.Save();
                                         *
                                         * WebClientWithTimeout updateDownload = new WebClientWithTimeout();
                                         * updateDownload.DownloadFileAsync(new Uri(updater.Payload.Update.DownloadUrl), "update.sbrw");
                                         * updateDownload.DownloadProgressChanged += (x, y) => {
                                         *  progress.Text = "DOWNLOADING UPDATE: " + y.ProgressPercentage + "%";
                                         * };
                                         *
                                         * updateDownload.DownloadFileCompleted += (x, y) => {
                                         *  progress.Text = "READY!";
                                         *
                                         *  if (File.Exists("Update.exe")) {
                                         *      Process.Start(@"Update.exe");
                                         *  } else {
                                         *      Process.Start(@"https://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases/latest");
                                         *  }
                                         *
                                         *  Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                                         * };*/
                                    }
                                    ;
                                }
                            }
                            else
                            {
                                text.Text        = "Launcher Status - GitHub Error";
                                status.Image     = Properties.Resources.ac_error;
                                text.ForeColor   = Color.FromArgb(254, 0, 0);
                                description.Text = "Version : v" + Application.ProductVersion;
                            }
                        } catch (Exception ex) {
                            MessageBox.Show(ex.Message);

                            if (text.InvokeRequired == true) //checks skip, because we only need to know if we can access ui from actual thread
                            {
                                text.Invoke(new Action(delegate()
                                {
                                    text.Text      = "Launcher Status - Backend Error";
                                    text.ForeColor = Color.FromArgb(254, 0, 0);
                                }));
                                status.Invoke(new Action(delegate()
                                {
                                    status.Image = Properties.Resources.ac_error;
                                }));
                                description.Invoke(new Action(delegate()
                                {
                                    description.Text = "Version : v" + Application.ProductVersion;
                                }));
                            }
                            else
                            {
                                text.Text        = "Launcher Status - Backend Error";
                                status.Image     = Properties.Resources.ac_error;
                                text.ForeColor   = Color.FromArgb(254, 0, 0);
                                description.Text = "Version : v" + Application.ProductVersion;
                            }
                        }
                    }
                };
            } catch {
                text.Text        = "Launcher Status - Internal Error";
                status.Image     = Properties.Resources.ac_error;
                text.ForeColor   = Color.FromArgb(254, 0, 0);
                description.Text = "Version : v" + Application.ProductVersion;
            }
        }
예제 #4
0
 private void _CloseWebClient()
 {
     _webClient.CancelAsync();
     _webClient.Dispose();
 }
예제 #5
0
        internal static void CheckForUpdate(object sender, EventArgs e)
        {
            try
            {
                var client = new WebClientWithTimeout();

                var uri = new Uri(Self.mainserver + "/launcher/update?version=" + Application.ProductVersion);
                client.CancelAsync();
                client.DownloadStringAsync(uri);
                client.DownloadStringCompleted += (sender2, e2) =>
                {
                    try
                    {
                        var json = JsonConvert.DeserializeObject <UpdateCheckResponse>(e2.Result);

                        if (json.Code != 0)
                        {
                            MessageBox.Show("Launchpad update service returned an error: " + json.Code);
                            return;
                        }

                        if (json.Payload.UpdateExists)
                        {
                            var settingFile = new IniFile("Settings.ini");
                            if (settingFile.Read("IgnoreUpdateVersion") != json.Payload.LatestVersion)
                            {
                                var dia = new TaskDialog
                                {
                                    Caption               = "Update",
                                    InstructionText       = "An update is available!",
                                    DetailsExpanded       = true,
                                    Icon                  = TaskDialogStandardIcon.Information,
                                    DetailsCollapsedLabel = "Show Changelog",
                                    Text                  = "An update is available. Do you want to download it?\nYour version: " +
                                                            Application.ProductVersion + "\nUpdated version: " + json.Payload.LatestVersion,
                                    DetailsExpandedText =
                                        new WebClientWithTimeout().DownloadString(Self.mainserver + "/launcher/changelog"),
                                    ExpansionMode = TaskDialogExpandedDetailsLocation.ExpandFooter
                                };

                                var update     = new TaskDialogCommandLink("update", "Yes", "Launcher will be updated to " + json.Payload.LatestVersion + ".");
                                var cancel     = new TaskDialogCommandLink("cancel", "No", "Launcher will ask you to update on the next launch.");
                                var skipupdate = new TaskDialogCommandLink("skipupdate", "Ignore", "This update will be skipped. A new prompt will apear as soon as a newer update is available.");

                                update.UseElevationIcon = true;

                                skipupdate.Click += (sender3, e3) =>
                                {
                                    settingFile.Write("IgnoreUpdateVersion", json.Payload.LatestVersion);
                                    dia.Close();
                                };

                                cancel.Click += (sender3, e3) =>
                                {
                                    dia.Close();
                                };

                                update.Click += (sender3, e3) =>
                                {
                                    if (File.Exists("GameLauncherUpdater.exe"))
                                    {
                                        Process.Start(@"GameLauncherUpdater.exe", Process.GetCurrentProcess().Id.ToString());
                                    }
                                    else
                                    {
                                        Process.Start(@"https://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases/latest");
                                    }

                                    dia.Close();
                                };

                                dia.Controls.Add(update);
                                dia.Controls.Add(cancel);
                                dia.Controls.Add(skipupdate);

                                dia.Show();

                                //new UpdatePopup(json.github_build).Show();
                            }
                        }
                        else
                        {
                            try
                            {
                                if (((Form)sender).Name == "mainScreen")
                                {
                                }
                            }
                            catch
                            {
                                MessageBox.Show("Your launcher is up-to-date");
                            }
                        }
                    }
                    catch
                    {
                        try
                        {
                            if (((Form)sender).Name == "mainScreen")
                            {
                            }
                        }
                        catch
                        {
                            MessageBox.Show("Failed to check for update!");
                        }
                    }
                };
            }
            catch
            {
                MessageBox.Show("Failed to check for update!");
            }
        }
 private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs args)
 {
     try
     {
         if (WebCalls.Alternative())
         {
             using (WebClient webClient = new WebClient())
             {
                 webClient.Headers.Add("user-agent", "SBRW Launcher " +
                                       Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                 webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.DownloadManager_DownloadDataCompleted);
                 webClient.CachePolicy            = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
                 while (true)
                 {
                     if (this._freeChunks <= 0)
                     {
                         Thread.Sleep(100);
                     }
                     else
                     {
                         lock (this._downloadQueue)
                         {
                             if (this._downloadQueue.Count == 0)
                             {
                                 lock (this._workers)
                                 {
                                     this._workers.Remove((BackgroundWorker)sender);
                                 }
                                 DownloaderHandler._workerCount--;
                                 break;
                             }
                         }
                         string value = null;
                         lock (this._downloadQueue)
                         {
                             value = this._downloadQueue.Last.Value;
                             this._downloadQueue.RemoveLast();
                             lock (this._freeChunksLock)
                             {
                                 this._freeChunks--;
                             }
                         }
                         lock (this._downloadList[value])
                         {
                             if (this._downloadList[value].Status != DownloaderHandler.DownloadStatus.Canceled)
                             {
                                 this._downloadList[value].Status = DownloaderHandler.DownloadStatus.Downloading;
                             }
                         }
                         while (webClient.IsBusy)
                         {
                             Thread.Sleep(100);
                         }
                         webClient.DownloadDataAsync(new Uri(value), value);
                         DownloaderHandler.DownloadStatus status = DownloaderHandler.DownloadStatus.Downloading;
                         while (status == DownloaderHandler.DownloadStatus.Downloading)
                         {
                             status = this._downloadList[value].Status;
                             if (status == DownloaderHandler.DownloadStatus.Canceled)
                             {
                                 break;
                             }
                             Thread.Sleep(100);
                         }
                         if (status == DownloaderHandler.DownloadStatus.Canceled)
                         {
                             webClient.CancelAsync();
                         }
                         lock (this._workers)
                         {
                             if (DownloaderHandler._workerCount > this._maxWorkers || !this._managerRunning)
                             {
                                 this._workers.Remove((BackgroundWorker)sender);
                                 DownloaderHandler._workerCount--;
                                 break;
                             }
                         }
                     }
                 }
             }
         }
         else
         {
             using (WebClientWithTimeout webClient = new WebClientWithTimeout())
             {
                 webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.DownloadManager_DownloadDataCompleted);
                 webClient.CachePolicy            = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
                 while (true)
                 {
                     if (this._freeChunks <= 0)
                     {
                         Thread.Sleep(100);
                     }
                     else
                     {
                         lock (this._downloadQueue)
                         {
                             if (this._downloadQueue.Count == 0)
                             {
                                 lock (this._workers)
                                 {
                                     this._workers.Remove((BackgroundWorker)sender);
                                 }
                                 DownloaderHandler._workerCount--;
                                 break;
                             }
                         }
                         string value = null;
                         lock (this._downloadQueue)
                         {
                             value = this._downloadQueue.Last.Value;
                             this._downloadQueue.RemoveLast();
                             lock (this._freeChunksLock)
                             {
                                 this._freeChunks--;
                             }
                         }
                         lock (this._downloadList[value])
                         {
                             if (this._downloadList[value].Status != DownloaderHandler.DownloadStatus.Canceled)
                             {
                                 this._downloadList[value].Status = DownloaderHandler.DownloadStatus.Downloading;
                             }
                         }
                         while (webClient.IsBusy)
                         {
                             Thread.Sleep(100);
                         }
                         webClient.DownloadDataAsync(new Uri(value), value);
                         DownloaderHandler.DownloadStatus status = DownloaderHandler.DownloadStatus.Downloading;
                         while (status == DownloaderHandler.DownloadStatus.Downloading)
                         {
                             status = this._downloadList[value].Status;
                             if (status == DownloaderHandler.DownloadStatus.Canceled)
                             {
                                 break;
                             }
                             Thread.Sleep(100);
                         }
                         if (status == DownloaderHandler.DownloadStatus.Canceled)
                         {
                             webClient.CancelAsync();
                         }
                         lock (this._workers)
                         {
                             if (DownloaderHandler._workerCount > this._maxWorkers || !this._managerRunning)
                             {
                                 this._workers.Remove((BackgroundWorker)sender);
                                 DownloaderHandler._workerCount--;
                                 break;
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (Exception Error)
     {
         LogToFileAddons.OpenLog("CDN DOWNLOADER [Background Work DH]", null, Error, null, true);
         Exception exception = Error;
         lock (this._workers)
         {
             this._workers.Remove((BackgroundWorker)sender);
             DownloaderHandler._workerCount--;
         }
     }
 }