void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { if (DownloadFileCompleted != null) { DownloadFileCompleted.Invoke(this, e); } }
/// <summary> /// Downloads the specified subtitle from subscene. /// </summary> /// <param name="url">The URL of the subtitle page.</param> /// <param name="target">The target location.</param> /// <param name="token">The user token.</param> private void InternalDownload(string url, string target, string token) { // get the info page var info = Utils.GetHTML(url); DownloadProgressChanged.Fire(this, 25); // extract the download link var dllink = "http://simple.podnapisi.net" + info.DocumentNode.GetNodeAttributeValue("//img[@title='Download']/..", "href"); if (dllink == "http://simple.podnapisi.net") { DownloadFileCompleted.Fire(this, null, null, null); return; } // pass the rest of the work to HTTPDownloader _dl = new HTTPDownloader(); _dl.DownloadProgressChanged += (s, e) => DownloadProgressChanged.Fire(this, e.Data); _dl.DownloadFileCompleted += (s, e) => DownloadFileCompleted.Fire(this, e.First, e.Second, e.Third); _dl.Download(dllink, target, token); }
private void DownloadCompleted(object sender, AsyncCompletedEventArgs e) { if (State == DownloadState.Restart) { State = DownloadState.InQueue; Start(); return; } DownloadFileCompleted?.Invoke(this, e); if (State == DownloadState.InQueue) { return; } _webClient.DownloadFileCompleted -= DownloadCompleted; if (State == DownloadState.Cancelled) { try { File.Delete(DestinationalFile); } catch (Exception fileError) { ErrorMessage = fileError.Message; State = DownloadState.HasError; return; } return; } State = e.Error != null ? DownloadState.HasError : DownloadState.Completed; }
/// <summary> /// Downloads the specified subtitle from subscene. /// </summary> /// <param name="url">The URL of the subtitle page.</param> /// <param name="target">The target location.</param> /// <param name="token">The user token.</param> private void InternalDownload(string url, string target, string token) { // get the info page var info = Utils.GetJSON("http://aliensubtitles.com/?d=" + Regex.Match(url, "/download#([0-9a-z]+)").Groups[1].Value + "&a=3a2677106d44d238f13ba200dd9ff53454af87a6"); DownloadProgressChanged.Fire(this, 25); // check download link if (info["url"] == null) { DownloadFileCompleted.Fire(this, null, null, null); return; } // pass the rest of the work to HTTPDownloader _dl = new HTTPDownloader(); _dl.DownloadProgressChanged += (s, e) => DownloadProgressChanged.Fire(this, e.Data); _dl.DownloadFileCompleted += (s, e) => DownloadFileCompleted.Fire(this, e.First, e.Second, e.Third); _dl.Download((string)info["url"], target, token); }
/// <summary> /// Asynchronously downloads the specified link. /// </summary> /// <param name="link"> /// The object containing the link. /// This can be an URL in a string or a <c>Link</c>/<c>Subtitle</c> object. /// </param> /// <param name="target">The target location.</param> /// <param name="token">The user token.</param> public void Download(object link, string target, string token = null) { string url; if (link is string) { url = link as string; } else if (link is Link) { url = (link as Link).FileURL; } else if (link is Subtitle) { url = (link as Subtitle).FileURL; } else { throw new Exception("The link object is an unsupported type."); } // we need to check if the URL is really an HTTP link. // if we don't do this, the software could be exploited into running any command if (!Regex.IsMatch(url, @"(https?|ftp)://", RegexOptions.IgnoreCase)) { throw new Exception("The specified URL doesn't look like a HTTP/FTP link."); } DownloadProgressChanged.Fire(this, 50); Utils.Run(url); DownloadProgressChanged.Fire(this, 100); DownloadFileCompleted.Fire(this, null, null, "LaunchedBrowser"); }
public void Stop() { DownloadFileCompleted?.Invoke(this, null); lock (statusSyncRoot) { fileDownloader?.CancelDownloadAsync(); } }
/// <summary> /// 下载完成 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { RunThrad--; ((DownloadService)sender).Package.Status = DownloadStatus.Finished; DownloadFileCompleted?.Invoke(sender, e); if (RunThrad == 0) { DownloadAllFileCompleted?.Invoke(null, EventArgs.Empty); } }
private void RaiseDownloadCompleted(object sender, AsyncCompletedEventArgs e) { _culcDownloadSpeedStopwatch.Reset(); _limitRaiseEventSw.Reset(); DownloadCompletedArgs args = new DownloadCompletedArgs(); args.ReceivedBytes = TotalSize; NowDownloading = false; DownloadFileCompleted?.Invoke(this, args, UserToken); }
private void InvokeDownloadCompleted(CompletedState downloadCompletedState, string fileName, System.Exception error = null, bool fromCache = false) { TimeSpan downloadTime = fromCache ? TimeSpan.Zero : DateTime.Now.Subtract(this.DownloadStartTime); if (this.worker != null) { this.BytesReceived = this.worker.Position; } DownloadFileCompleted.SafeInvoke(this, new DownloadFileCompletedArgs(downloadCompletedState, fileName, this.fileSource, downloadTime, this.TotalBytesToReceive, this.BytesReceived, error)); }
/// <summary> /// Downloads the specified subtitle from subscene. /// </summary> /// <param name="url">The URL of the subtitle page.</param> /// <param name="target">The target location.</param> /// <param name="token">The user token.</param> private void InternalDownload(string url, string target, string token) { var parts = url.Split(';'); var nzb = Utils.GetURL(parts[0], parts[1], encoding: new Utils.Base64Encoding()); DownloadProgressChanged.Fire(this, 75); File.WriteAllBytes(target, Convert.FromBase64String(nzb)); DownloadProgressChanged.Fire(this, 100); DownloadFileCompleted.Fire(this, target, parts[2], token ?? string.Empty); }
public void Cancel() { State = DownloadState.Cancelled; if (_webClient.IsBusy) { _webClient.CancelAsync(); } else { var args = new AsyncCompletedEventArgs(null, true, null); DownloadFileCompleted?.Invoke(this, args); _webClient.DownloadFileCompleted -= DownloadCompleted; } }
/// <summary> /// Downloads the specified subtitle from subscene. /// </summary> /// <param name="url">The URL of the subtitle page.</param> /// <param name="target">The target location.</param> /// <param name="token">The user token.</param> private void InternalDownload(string url, string target, string token) { // get the info page var info = Utils.GetURL(url); DownloadProgressChanged.Fire(this, 25); // extract required info var dllink = "http://subscene.com" + Regex.Match(info, "href=\"([^\"]+)\".*?id=\"downloadButton\"", RegexOptions.IgnoreCase).Groups[1].Value; // pass the rest of the work to HTTPDownloader _dl = new HTTPDownloader(); _dl.DownloadProgressChanged += (s, e) => DownloadProgressChanged.Fire(this, e.Data); _dl.DownloadFileCompleted += (s, e) => DownloadFileCompleted.Fire(this, e.First, e.Second, e.Third); _dl.Download(dllink, target, token); }
public async Task <ResultSuccess> DownloadFile(string ServerPath, string FileName, string SavePath, string SaveAsFileName, DownloadFileCompleted OnDownloadFileCompleted, DownloadProgressChanged OnDownloadProgressChanged) { var webClient = new WebClient(); webClient.DownloadFileCompleted += Client_DownloadFileCompleted; webClient.DownloadProgressChanged += Client_DownloadProgressChanged; try { DownloadFileCompleted_EventHandler = OnDownloadFileCompleted; DownloadProgressChanged_EventHandler = OnDownloadProgressChanged; var url = new Uri(ServerPath + FileName); var localDirectory = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), SavePath); var localSavePath = System.IO.Path.Combine(localDirectory, !string.IsNullOrEmpty(SaveAsFileName) ? SaveAsFileName : FileName); if (!System.IO.Directory.Exists(localDirectory)) { System.IO.Directory.CreateDirectory(localDirectory); } var task = webClient.DownloadFileTaskAsync(url, localSavePath); await task; if (task.Exception != null) { throw new Exception(task.Exception.Message); } webClient.DownloadFileCompleted += Client_DownloadFileCompleted; webClient.DownloadProgressChanged += Client_DownloadProgressChanged; return(new ResultSuccess(true, "")); } catch (System.Exception err) { webClient.DownloadFileCompleted += Client_DownloadFileCompleted; webClient.DownloadProgressChanged += Client_DownloadProgressChanged; return(new ResultSuccess(false, err.Message)); } }
private async Task DownloadResultFilesAsync( TaskInfo task, Options options, object state) { try { using (_scope.Start("Downloading Results")) using (var httpClient = new HttpClient()) { var urls = GetResultUrls(task.ResultUrls, options.OutputFormat.Split(',')); foreach (var url in urls) { if (url.Url is null) { throw new InvalidOperationException(); } var path = Path.Combine(options.TargetPath, $"{options.FileName ?? "document"}.{url.Format.ToExtension()}"); using (var fileStream = File.Open(path, FileMode.Create, FileAccess.Write)) { var resultStream = await httpClient .GetStreamAsync(url.Url) .ConfigureAwait(false); resultStream.CopyTo(fileStream); } } } DownloadFileCompleted?.Invoke(this, new TaskEventArgs(task, null, state)); } catch (Exception e) { DownloadFileCompleted?.Invoke(this, new TaskEventArgs(task, e, state)); throw; } }
private void RegisterDownloadDelegates() { // We do all this magic because other threads should NOT change the UI. // We want the changes made to the reusable `TransferFileProgressArgs` instance // to raise change events on the context of the Main thread. Implementation.DownloadStarted += (TransferFileProgressArgs args, Action action) => { EventDispatcher.Invoke(() => { if (action != null) { action.Invoke(); } if (DownloadFileStarted != null) { DownloadFileStarted.Invoke(this, args); } }); }; Implementation.DownloadProgressed += (TransferFileProgressArgs args, Action action) => { EventDispatcher.Invoke(() => { if (action != null) { action.Invoke(); } if (DownloadFileProgress != null) { DownloadFileProgress.Invoke(this, args); } }); }; Implementation.DownloadCanceled += (TransferFileProgressArgs args, Action action) => { EventDispatcher.Invoke(() => { if (action != null) { action.Invoke(); } if (DownloadFileCanceled != null) { DownloadFileCanceled.Invoke(this, args); } }); }; Implementation.DownloadFailed += (TransferFileProgressArgs args, Action action) => { EventDispatcher.Invoke(() => { if (action != null) { action.Invoke(); } if (DownloadFileFailed != null) { DownloadFileFailed.Invoke(this, args); } }); }; Implementation.DownloadCompleted += (TransferFileProgressArgs args, Action action) => { EventDispatcher.Invoke(() => { if (action != null) { action.Invoke(); } if (DownloadFileCompleted != null) { DownloadFileCompleted.Invoke(this, args); } }); }; }
protected void OnDownloadFileCompleted(object sender, DownloadFileCompletedEventArgs e) { DownloadFileCompleted?.Invoke(sender, e); }
public async Task Download(Uri uri, String filePath) { try { _bytesLastUpdate = 0; _nextUpdate = DateTime.UtcNow.AddSeconds(1); // Determine the file size var webRequest = WebRequest.Create(uri); webRequest.Method = "HEAD"; webRequest.Timeout = 5000; Int64 responseLength; using (var webResponse = await webRequest.GetResponseAsync()) { responseLength = Int64.Parse(webResponse.Headers.Get("Content-Length")); } var timeout = DateTimeOffset.UtcNow.AddHours(1); while (timeout > DateTimeOffset.UtcNow && !_cancelled) { try { var request = WebRequest.Create(uri); using var response = await request.GetResponseAsync(); await using var stream = response.GetResponseStream(); if (stream == null) { throw new IOException("No stream"); } await using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write); var buffer = new Byte[64 * 1024]; while (fileStream.Length < response.ContentLength && !_cancelled) { var read = await stream.ReadAsync(buffer.AsMemory(0, buffer.Length)); if (read > 0) { fileStream.Write(buffer, 0, read); BytesDone = fileStream.Length; BytesTotal = responseLength; if (DateTime.UtcNow > _nextUpdate) { Speed = fileStream.Length - _bytesLastUpdate; _nextUpdate = DateTime.UtcNow.AddSeconds(1); _bytesLastUpdate = fileStream.Length; timeout = DateTimeOffset.UtcNow.AddHours(1); DownloadProgressChanged?.Invoke(this, new DownloadProgressChangedEventArgs(null) { BytesPerSecondSpeed = Speed, ProgressedByteSize = _bytesLastUpdate, TotalBytesToReceive = BytesTotal, AverageBytesPerSecondSpeed = Speed, ReceivedBytesSize = BytesDone, }); } } else { break; } } break; } catch (IOException) { await Task.Delay(1000); } catch (WebException) { await Task.Delay(1000); } } if (timeout <= DateTimeOffset.UtcNow) { throw new Exception($"Download timed out"); } DownloadFileCompleted?.Invoke(this, new AsyncCompletedEventArgs(null, false, null)); } catch (Exception ex) { DownloadFileCompleted?.Invoke(this, new AsyncCompletedEventArgs(ex, false, null)); } }
void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Error != null || e.Cancelled) { if (_mode == 0 && System.IO.File.Exists(_file)) { // delete temp file that was downloaded when trying to get gdrive direct download url System.IO.File.Delete(_file); } DownloadFileCompleted(this, e); } else { if (_mode == 0) { if (new System.IO.FileInfo(_file).Length < 100 * 1024) { string text = System.IO.File.ReadAllText(_file); int html = text.IndexOf("<html", StringComparison.InvariantCultureIgnoreCase); if (html >= 0 && html < 100) { int ilink = text.IndexOf("\"uc-download-link\"", StringComparison.InvariantCultureIgnoreCase); if (ilink > 0) { int href = text.IndexOf("href=\"", ilink, StringComparison.InvariantCultureIgnoreCase); if (href > 0) { int hrefend = text.IndexOf('"', href + 6); if (hrefend > 0) { string url = text.Substring(href + 6, hrefend - href - 6).Replace("&", "&"); if (url.IndexOf("://") < 0) { url = new Uri(_url).GetLeftPart(UriPartial.Authority) + url; } System.Diagnostics.Debug.WriteLine("GDrive: redirecting to " + url); System.Diagnostics.Debug.WriteLine("GDrive: {0} cookies set", _cookies.Count); DownloadItem downloadInfo = _state as DownloadItem; FileDownloadTask fileDownload = new FileDownloadTask(url, _file, downloadInfo, _cookies) { Headers = new WebHeaderCollection() }; fileDownload.Headers.Add("Referer", _url); downloadInfo.PerformCancel = () => { fileDownload.CancelAsync(); downloadInfo.OnCancel?.Invoke(); }; fileDownload.DownloadProgressChanged += FileDownload_DownloadProgressChanged; fileDownload.DownloadFileCompleted += wc_DownloadFileCompleted; System.IO.File.Delete(_file); // delete temp html file just downloaded downloadInfo.FileDownloadTask = fileDownload; fileDownload.Start(); _mode = 1; CleanUpWebClient(); return; } } } int tstart = text.IndexOf("<title>", StringComparison.InvariantCultureIgnoreCase); int tend = text.IndexOf("</title>", StringComparison.InvariantCultureIgnoreCase); string err = "Couldn't parse data"; if (tstart > 0 && tend > 0) { err = text.Substring(tstart + 7, tend - tstart - 7); } //If we get here, it went wrong System.IO.File.Delete(_file); DownloadFileCompleted?.Invoke(this, new AsyncCompletedEventArgs(new Exception(err), false, _state)); } else { DownloadFileCompleted?.Invoke(this, e); } } else { DownloadFileCompleted?.Invoke(this, e); } } else { // actual file being downloaded has finished successfully at this point CleanUpFileDownloadTask(); DownloadFileCompleted?.Invoke(this, e); } } }
/// <summary> /// Asynchronously downloads the specified link. /// </summary> /// <param name="link"> /// The object containing the link. /// This can be an URL in a string or a <c>Link</c>/<c>Subtitle</c> object. /// </param> /// <param name="target">The target location.</param> /// <param name="token">The user token.</param> public void Download(object link, string target, string token = null) { var id = Utils.Rand.Next(short.MaxValue); var st = DateTime.Now; _wc = new Utils.SmarterWebClient(); Uri uri; if (link is string) { uri = new Uri(link as string); } else if (link is Link) { uri = new Uri((link as Link).FileURL); if (!string.IsNullOrWhiteSpace((link as Link).Source.Cookies)) { _wc.Headers[HttpRequestHeader.Cookie] = (link as Link).Source.Cookies; } } else if (link is Subtitle) { uri = new Uri((link as Subtitle).FileURL); if (!string.IsNullOrWhiteSpace((link as Subtitle).Source.Cookies)) { _wc.Headers[HttpRequestHeader.Cookie] = (link as Subtitle).Source.Cookies; } } else { throw new Exception("The link object is an unsupported type."); } var domain = uri.Host.Replace("www.", string.Empty); Log.Debug("HTTP#{0} GET {1}", new[] { id.ToString(), uri.ToString() }); _wc.Headers[HttpRequestHeader.Referer] = "http://" + uri.DnsSafeHost + "/"; _wc.DownloadProgressChanged += (s, e) => DownloadProgressChanged.Fire(this, e.ProgressPercentage); _wc.DownloadFileCompleted += (s, e) => { Log.Debug("HTTP#" + id + " [" + domain + "] is " + Utils.GetFileSize(new FileInfo(target).Length) + " and took " + (DateTime.Now - st).TotalSeconds + "s."); if (Log.IsTraceEnabled) { Log.Trace("HTTP#" + id + " [" + domain + "] is " + (s as Utils.SmarterWebClient).ContentType + ", saved to " + target + " with token " + token); } DownloadFileCompleted.Fire(this, target, (s as Utils.SmarterWebClient).FileName, token ?? string.Empty); }; var proxy = default(string); var proxyId = default(object); if (Settings.Get <Dictionary <string, object> >("Proxied Domains").TryGetValue(domain, out proxyId)) { proxy = (string)Settings.Get <Dictionary <string, object> >("Proxies")[(string)proxyId]; } if (proxy != null) { var proxyUri = new Uri(proxy.Replace("$domain.", string.Empty)); switch (proxyUri.Scheme.ToLower()) { case "http": if (proxy.Contains("$url")) { uri = new Uri(proxy.Replace("$url", Utils.EncodeURL(uri.ToString()))); } else if (proxy.Contains("$domain") && proxy.Contains("$path")) { uri = new Uri(proxy.Replace("$domain", uri.DnsSafeHost).Replace("$path", uri.AbsolutePath)); } else { _wc.Proxy = new WebProxy(proxyUri.Host + ":" + proxyUri.Port); } break; case "socks4": case "socks4a": case "socks5": var tunnel = new HttpToSocks { RemoteProxy = HttpToSocks.Proxy.ParseUri(proxyUri) }; tunnel.Listen(); _wc.Proxy = (WebProxy)tunnel.LocalProxy; break; } Log.Debug("HTTP#" + id + " [" + domain + "] is proxied through " + proxyId + " (" + proxyUri + ")"); } _wc.DownloadFileAsync(uri, target); }
public UpdateUtil() { _client = new WebClient(); _client.DownloadFileCompleted += (sender, args) => { DownloadFileCompleted?.Invoke(sender, args); }; _client.DownloadProgressChanged += (sender, args) => { DownloadProgressChanged?.Invoke(sender, args); }; }
private void WebClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { DownloadFileCompleted?.Invoke(sender, e); }
private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { DownloadFileCompleted?.Invoke(this, e); }
private void OnDownloadFileCompleted(AsyncCompletedEventArgs e) { IsBusy = false; DownloadFileCompleted?.Invoke(this, e); }
private void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) => DownloadFileCompleted?.Invoke(sender, e);
protected virtual void OnDownloadFileCompleted(AsyncCompletedEventArgs e) { IsBusy = false; DownloadFileCompleted?.Invoke(this, e); }
protected virtual void OnDownloadFileCompleted(EventArgs e) { DownloadFileCompleted?.Invoke(this, e); }