Exemple #1
0
        //------------------------------------------------------------------------------------------
        /// <summary>
        /// Asynchronously downloads, from the Source address, a file to the specified Target.
        /// Plus, a progress-informer and progress-finisher can be specified.
        /// </summary>
        public static void DownloadFileAsync(System.Uri Source, string Target,
                                             Func <System.Net.DownloadProgressChangedEventArgs, bool> ProgressInformer,
                                             Action <OperationResult <bool> > ProgressFinisher)
        {
            var Client = new System.Net.WebClient();

            Client.DownloadProgressChanged +=
                ((sender, evargs) =>
            {
                if (!ProgressInformer(evargs))
                {
                    Client.CancelAsync();
                }
            });

            Client.DownloadFileCompleted +=
                ((sender, evargs) =>
            {
                if (evargs.Cancelled || evargs.Error != null)
                {
                    ProgressFinisher(OperationResult.Failure <bool>("Download " + (evargs.Error == null ? "Cancelled" : "Failed") + "." +
                                                                    (evargs.Error == null
                                                                 ? "" :
                                                                     "\nProblem:" + evargs.Error.Message)));
                    return;
                }

                ProgressFinisher(OperationResult.Success(true));
            });

            Client.DownloadFileAsync(Source, Target);
        }
Exemple #2
0
 private void canbtn_Click(object sender, EventArgs e)
 {
     if (downloadClient != null)
     {
         downloadClient.CancelAsync();
     }
 }
        public async Task DoDownload()
        {
            var enclosure = VersionInfo.First().Enclosures.First(e => e.InstallerType == Updater.CurrentInstallerType);

            if (Updater.CurrentInstallerType == InstallerType.Archive ||
                Updater.CurrentInstallerType == InstallerType.ServiceArchive)
            {
                downloadPath = enclosure.Url.AbsolutePath;
                this.State   = UpdateActionState.Downloaded;
                return;
            }
            using (var client = new System.Net.WebClient())
                using (cancelSource.Token.Register(() => client.CancelAsync(), true)) {
                    client.DownloadProgressChanged += (sender, args) => {
                        this.Progress = args.ProgressPercentage / 100.0;
                    };
                    this.State = UpdateActionState.Downloading;
                    try {
                        downloadPath = System.IO.Path.Combine(
                            Shell.GetKnownFolder(Shell.KnownFolder.Downloads),
                            System.IO.Path.GetFileName(enclosure.Url.AbsolutePath));
                        await client.DownloadFileTaskAsync(
                            enclosure.Url.ToString(),
                            downloadPath);

                        this.State = UpdateActionState.Downloaded;
                    }
                    catch (System.Net.WebException) {
                        this.State = UpdateActionState.Aborted;
                    }
                }
        }
 /*public void ClearRunePreviewSubscribers()
  * {
  *  foreach (var subs in RunePreviewSubscribers.Values)
  *      subs.Clear();
  * }*/
 public void BreakRunePreviewDownload()
 {
     QueuedRunePreviewHashes.Clear();
     wc.CancelAsync();
     NewPreviewRequested = false;
     CheckNewPreviewTimer.Stop();
 }
Exemple #5
0
 private void restart_Click(object sender, RoutedEventArgs e)
 {
     if (down != null)
     {
         down.CancelAsync();
     }
 }
Exemple #6
0
        public static async Task <DownloadResult> DownloadAsync(VersionDescription version, Action <float> onprogress, CancellationToken ct)
        {
            var enclosure = version.Enclosures.First(e => e.InstallerType == Updater.CurrentInstallerType);

            if (Updater.CurrentInstallerType == InstallerType.Archive ||
                Updater.CurrentInstallerType == InstallerType.ServiceArchive)
            {
                return(new DownloadResult(null, version, enclosure));
            }
            using (var client = new System.Net.WebClient())
                using (ct.Register(() => client.CancelAsync(), false)) {
                    if (onprogress != null)
                    {
                        client.DownloadProgressChanged += (sender, args) => {
                            onprogress(args.ProgressPercentage / 100.0f);
                        };
                    }
                    var filepath =
                        System.IO.Path.Combine(
                            GetDownloadPath(),
                            System.IO.Path.GetFileName(enclosure.Url.AbsolutePath));
                    await client.DownloadFileTaskAsync(enclosure.Url.ToString(), filepath).ConfigureAwait(false);

                    return(new DownloadResult(filepath, version, enclosure));
                }
        }
        public async System.Threading.Tasks.Task DoDownload()
        {
            var client = new System.Net.WebClient();

            client.DownloadProgressChanged += (sender, args) => {
                this.Progress = args.ProgressPercentage / 100.0;
            };
            cancelSource.Token.Register(() => {
                client.CancelAsync();
            }, true);
            this.State = UpdateActionState.Downloading;
            try {
                downloadPath = System.IO.Path.Combine(
                    Shell.GetKnownFolder(Shell.KnownFolder.Downloads),
                    System.IO.Path.GetFileName(SelectedEnclosure.Url.AbsolutePath));
                await client.DownloadFileTaskAsync(
                    selectedEnclosure.Url.ToString(),
                    downloadPath);

                this.State = UpdateActionState.Downloaded;
            }
            catch (System.Net.WebException) {
                this.State = UpdateActionState.Aborted;
            }
        }
Exemple #8
0
        public DownloadItemViewModel Download(string link, string saveFilePath, string description, Action onCancel, Action onComplete)
        {
            DownloadLocationType type;
            string location;

            if (!AssetCatalog.TryParseDownloadUrl(link, out type, out location))
            {
                return(null);
            }

            Action onError = () =>
            {
            };


            DownloadItemViewModel newDownload = new DownloadItemViewModel()
            {
                ItemName      = description,
                OnCancel      = onCancel,
                OnError       = onError,
                OnComplete    = onComplete,
                DownloadSpeed = "Calculating ...",
                DownloadType  = DownloadType.Asset
            };

            switch (type)
            {
            case DownloadLocationType.Url:
                using (var wc = new System.Net.WebClient())
                {
                    newDownload.PerformCancel = () =>
                    {
                        wc.CancelAsync();
                        newDownload.OnCancel?.Invoke();
                    };
                    wc.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
                    wc.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
                    wc.DownloadFileAsync(new Uri(location), saveFilePath, newDownload);
                }

                break;

            case DownloadLocationType.GDrive:
                var gd = new GDrive();
                newDownload.PerformCancel = () =>
                {
                    gd.CancelAsync();
                    newDownload.OnCancel?.Invoke();
                };
                gd.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
                gd.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
                gd.Download(location, saveFilePath, newDownload);
                break;
            }

            newDownload.IsStarted = true;
            return(newDownload);
        }
Exemple #9
0
 void webClient_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
 {
     if (mMonitor != null)
     {
         mMonitor.SetProgress(e.ProgressPercentage);
         if (mMonitor.Canceled)
         {
             mWebClient.CancelAsync();
         }
     }
 }
 private void DownloadFileFromUrl(DownloadItemViewModel newDownload, string url)
 {
     using (var wc = new System.Net.WebClient())
     {
         newDownload.PerformCancel = () =>
         {
             wc.CancelAsync();
             newDownload.OnCancel?.Invoke();
         };
         wc.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
         wc.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
         wc.DownloadFileAsync(new Uri(url), newDownload.SaveFilePath, newDownload);
     }
 }
        public void CancelDownload()
        {
            _downloadCanceled = true;
            if (_wc != null && _wc.IsBusy)
            {
                _wc.CancelAsync();
            }


            Logger.Log("Download canceled");

            if (DownloadCanceled != null)
            {
                Task.Run(() => DownloadCanceled.Invoke(null));
            }
        }
Exemple #12
0
 private void CancelBtn_Click(object sender, RoutedEventArgs e)
 {
     if (proc != null)
     {
         proc.Kill();
     }
     if (appAction == AppAction.Play)
     {
         DialogResult = true;
     }
     else if (appAction == AppAction.Download)
     {
         webClient.CancelAsync();
         Utils.KillFile(targetFileName);
         Close();
     }
 }
Exemple #13
0
        public void Download(DownloadItemViewModel newDownload)
        {
            DownloadLocationType type;
            string location;

            if (!AssetCatalog.TryParseDownloadUrl(newDownload.DownloadUrl, out type, out location))
            {
                return;
            }

            switch (type)
            {
            case DownloadLocationType.Url:
                using (var wc = new System.Net.WebClient())
                {
                    newDownload.PerformCancel = () =>
                    {
                        wc.CancelAsync();
                        newDownload.OnCancel?.Invoke();
                    };
                    wc.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
                    wc.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
                    wc.DownloadFileAsync(new Uri(location), newDownload.SaveFilePath, newDownload);
                }

                break;

            case DownloadLocationType.GDrive:
                var gd = new GDrive();
                newDownload.PerformCancel = () =>
                {
                    gd.CancelAsync();
                    newDownload.OnCancel?.Invoke();
                };
                gd.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
                gd.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
                gd.Download(location, newDownload.SaveFilePath, newDownload);
                break;
            }

            newDownload.IsStarted = true;
        }
		public async System.Threading.Tasks.Task DoDownload()
		{
			var client = new System.Net.WebClient();
			client.DownloadProgressChanged += (sender, args) => {
				this.Progress = args.ProgressPercentage/100.0;
			};
			cancelSource.Token.Register(() => {
				client.CancelAsync();
			}, true);
			this.State = UpdateActionState.Downloading;
			try {
				downloadPath = System.IO.Path.Combine(
					Shell.GetKnownFolder(Shell.KnownFolder.Downloads),
					System.IO.Path.GetFileName(SelectedEnclosure.Url.AbsolutePath));
				await client.DownloadFileTaskAsync(
					selectedEnclosure.Url.ToString(),
					downloadPath);
				this.State = UpdateActionState.Downloaded;
			}
			catch (System.Net.WebException) {
				this.State = UpdateActionState.Aborted;
			}
		}
Exemple #15
0
        private void Download()
        {
            //the temp file is owned by this thread
            var fn = TempFileManager.GetTempFilename("ffmpeg_download", ".7z", false);

            try
            {
                using (var evt = new ManualResetEvent(false))
                {
                    using (var client = new System.Net.WebClient())
                    {
                        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                        client.DownloadFileAsync(new Uri(FFmpegService.Url), fn);
                        client.DownloadProgressChanged += (object sender, System.Net.DownloadProgressChangedEventArgs e) =>
                        {
                            pct = e.ProgressPercentage;
                        };
                        client.DownloadFileCompleted += (object sender, System.ComponentModel.AsyncCompletedEventArgs e) =>
                        {
                            //we don't really need a status. we'll just try to unzip it when it's done
                            evt.Set();
                        };

                        for (; ;)
                        {
                            if (evt.WaitOne(10))
                            {
                                break;
                            }

                            //if the gui thread ordered an exit, cancel the download and wait for it to acknowledge
                            if (exiting)
                            {
                                client.CancelAsync();
                                evt.WaitOne();
                                break;
                            }
                        }
                    }
                }

                //throw new Exception("test of download failure");

                //if we were ordered to exit, bail without wasting any more time
                if (exiting)
                {
                    return;
                }

                //try acquiring file
                using (var hf = new HawkFile(fn))
                {
                    using (var exe = OSTailoredCode.IsUnixHost ? hf.BindArchiveMember("ffmpeg") : hf.BindFirstOf(".exe"))
                    {
                        var data = exe !.ReadAllBytes();

                        //last chance. exiting, don't dump the new ffmpeg file
                        if (exiting)
                        {
                            return;
                        }

                        DirectoryInfo parentDir = new(Path.GetDirectoryName(FFmpegService.FFmpegPath) !);
                        if (!parentDir.Exists)
                        {
                            parentDir.Create();
                        }
                        File.WriteAllBytes(FFmpegService.FFmpegPath, data);
                        if (OSTailoredCode.IsUnixHost)
                        {
                            OSTailoredCode.ConstructSubshell("chmod", $"+x {FFmpegService.FFmpegPath}", checkStdout: false).Start();
                            Thread.Sleep(50);                             // Linux I/O flush idk
                        }
                    }
                }

                //make sure it worked
                if (!FFmpegService.QueryServiceAvailable())
                {
                    throw new Exception("download failed");
                }

                succeeded = true;
            }
            catch
            {
                failed = true;
            }
            finally
            {
                try { File.Delete(fn); }
                catch { }
            }
        }
Exemple #16
0
        private void Download()
        {
            //the temp file is owned by this thread
            var fn = TempFileManager.GetTempFilename("ffmpeg_download", ".7z", false);

            try
            {
                using (var evt = new ManualResetEvent(false))
                {
                    using (var client = new System.Net.WebClient())
                    {
                        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                        client.DownloadFileAsync(new Uri(FFmpegService.Url), fn);
                        client.DownloadProgressChanged += (object sender, System.Net.DownloadProgressChangedEventArgs e) =>
                        {
                            pct = e.ProgressPercentage;
                        };
                        client.DownloadFileCompleted += (object sender, System.ComponentModel.AsyncCompletedEventArgs e) =>
                        {
                            //we don't really need a status. we'll just try to unzip it when it's done
                            evt.Set();
                        };

                        for (; ;)
                        {
                            if (evt.WaitOne(10))
                            {
                                break;
                            }

                            //if the gui thread ordered an exit, cancel the download and wait for it to acknowledge
                            if (exiting)
                            {
                                client.CancelAsync();
                                evt.WaitOne();
                                break;
                            }
                        }
                    }
                }

                //throw new Exception("test of download failure");

                //if we were ordered to exit, bail without wasting any more time
                if (exiting)
                {
                    return;
                }

                //try acquiring file
                using (var hf = new HawkFile(fn))
                {
                    using (var exe = hf.BindFirstOf(".exe"))
                    {
                        var data = exe.ReadAllBytes();

                        //last chance. exiting, don't dump the new ffmpeg file
                        if (exiting)
                        {
                            return;
                        }

                        File.WriteAllBytes(FFmpegService.FFmpegPath, data);
                    }
                }

                //make sure it worked
                if (!new FFmpegService().QueryServiceAvailable())
                {
                    throw new Exception("download failed");
                }

                succeeded = true;
            }
            catch
            {
                failed = true;
            }
            finally
            {
                try { File.Delete(fn); }
                catch { }
            }
        }
Exemple #17
0
 private void buttonCancel_Click(object sender, EventArgs e)
 {
     client.CancelAsync();
 }
Exemple #18
0
        private async void subscribeUpdateItem_Click(object sender, EventArgs e)
        {
            var config = controller.GetConfigurationCopy();

            if (config.subscribes == null || !config.subscribes.Any())
            {
                return;
            }
            subscribeUpdateItem.Enabled = false;
            var before = config.configs.Count(c => !string.IsNullOrEmpty(c.@group));

            foreach (var item in config.subscribes)
            {
                var wc = new System.Net.WebClient();
                if (item.useProxy)
                {
                    wc.Proxy = new System.Net.WebProxy(System.Net.IPAddress.Loopback.ToString(), config.localPort);
                }
                var cts = new System.Threading.CancellationTokenSource();
                // ReSharper disable once AccessToDisposedClosure
                // ReSharper disable once ConvertToLambdaExpressionWhenPossible
                cts.Token.Register(() => { wc?.CancelAsync(); });
                cts.CancelAfter(10000);
                string downloadString;
                try
                {
                    downloadString = await wc.DownloadStringTaskAsync(item.url);
                }
                catch //TODO maybe we can notify?
                {
                    continue;
                }
                wc.Dispose();
                var lst = new List <ServerObject>();
                if (downloadString.Contains("vmess://"))
                {
                    var mcg = Regex.Matches(downloadString, @"vmess://(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);
                    foreach (Match s in mcg)
                    {
                        if (ServerObject.TryParse(s.Value, out ServerObject svc))
                        {
                            svc.@group = item.name;
                            lst.Add(svc);
                        }
                    }
                }
                else
                {
                    try
                    {
                        var debase64 = downloadString.DeBase64();
                        var split    = debase64.Split('\r', '\n');
                        foreach (var s in split)
                        {
                            if (ServerObject.TryParse(s, out ServerObject svc))
                            {
                                svc.@group = item.name;
                                lst.Add(svc);
                            }
                        }
                    }
                    catch
                    {
                        MessageBox.Show(I18N.GetString("Invalid Base64 string."), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                if (lst.Any())
                {
                    config.configs.RemoveAll(c => c.@group == item.name);
                    config.configs.AddRange(lst);
                }
            }
            controller.SaveServers(config.configs, config.localPort, config.corePort);
            var after = config.configs.Count(c => !string.IsNullOrEmpty(c.@group));

            if (before != after)
            {
                RebuildMenu();
            }
            ShowBalloonTip(I18N.GetString("Update finished"), I18N.GetString("{0} before, {1} after.", before, after));
            subscribeUpdateItem.Enabled = true;
        }