public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error) { try { Logger.Log("INFO: DidCompleteWithError: " + error); if (error != null) { if (task.OriginalRequest == null) { return; } string itemID = task.OriginalRequest.Url.ToString(); string title = task.OriginalRequest.Url.ToString(); var downloadItem = DownloadSessionMetadata.GetDownloadItem(task.OriginalRequest.Url.ToString()); if (downloadItem != null) { itemID = downloadItem.Id; if (!string.IsNullOrEmpty(downloadItem.FileName)) { title = downloadItem.FileName.Replace(".mp4", string.Empty); } DownloadSessionMetadata.RemoveDownloadItem(task.OriginalRequest.Url.ToString()); } var isCanceled = (error.Code == -999); DownloadProgress progress = new DownloadProgress() { Status = isCanceled ? DownloadStatus.Canceled : DownloadStatus.Failed, Id = itemID, Title = title, Url = task.OriginalRequest.Url.ToString() }; if (!isCanceled && (downloadItem != null) && (downloadItem.RetryCount <= 3)) { progress.WillRetryOnError = true; } Logger.Log("INFO: DidCompleteWithError: ID: " + progress.Id + ". Error: " + error); if (itemDownloader != null) { InvokeOnMainThread(() => itemDownloader.Fire_DownloadComplete(new AsyncCompletedEventArgs(new NSErrorException(error), isCanceled, progress))); } if (!isCanceled && (downloadItem != null) && (downloadItem.RetryCount <= 3)) { downloadItem.RetryCount++; #pragma warning disable 4014 itemDownloader.Download(downloadItem); #pragma warning restore 4014 } } } catch (Exception ex) { Logger.Log("ERROR: DidCompleteWithError: " + ex); } }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is DownloadProgress) { DownloadProgress progress = value as DownloadProgress; if (progress.Status == DownloadStatus.Downloading) { //XXX: wait 3 sec before calculating the estimated time left if (progress.DownloadedDuration > 3000) { return(string.Format("{0} remaining - {1}/{2}", StringTools.GetTimeString(progress.ExpectedDuration - progress.DownloadedDuration), StringTools.GetFileSizeString(progress.DownloadedLength), StringTools.GetFileSizeString(progress.TotalLength))); } else { return(string.Format("{0}/{1}", StringTools.GetFileSizeString(progress.DownloadedLength), StringTools.GetFileSizeString(progress.TotalLength))); } } } return(string.Empty); }
void DownloadFileProcessFile() { DownloadProgress CurrentDownloadProgress = new DownloadProgress(); try { FileInfo FileInfoThis = new FileInfo(Current.FullURL); // передаем размер файла Current.FileSize = (int)FileInfoThis.Length; CurrentDownloadProgress.Type = DownloadMessageType.DownloadStarted; CurrentDownloadProgress.DownloadSize = Current.FileSize; SygnalEventProgress(CurrentDownloadProgress); Stream dataStream = FileInfoThis.OpenRead(); dataStream.Position = Current.BytesDownloaded; Current.Filename = FileInfoThis.Name; DownloadFileStreamly(dataStream); dataStream.Close(); } catch (Exception ex) { CurrentDownloadProgress.Type = DownloadMessageType.DownloadError; CurrentDownloadProgress.AdditionalInfo = ex.ToString(); SygnalEventProgress(CurrentDownloadProgress); EndDownloadFileProcess.Set(); throw ex; } finally { EndDownloadFileProcess.Set(); } }
private void Downloader_DownloadCompleted(DownloadProgress ProgData) { try { if (ProgData.ProgType == ProgressType.Completed) { Log.WriteLog(LogType.General, "Successfully downloaded file for vidID: " + ProgData.VidID); YTDownload finishedDownload = new YTDownload(); foreach (YTDownload download in RunningDownloads) { if (download.VidID == ProgData.VidID && download.aQuality.AudNo == ProgData.AudQual.AudNo && download.vQuality.VidNo == ProgData.VidQual.VidNo) { string linkName = download.FileName.Replace(' ', '*'); linkName = linkName.Replace('&', '|'); linkName = linkName.Replace('=', '<'); download.context.Response.StatusCode = (int)HttpStatusCode.OK; string responseString = "COMPLETED:" + linkName; byte[] data = Encoding.UTF8.GetBytes(responseString); download.context.Response.OutputStream.Write(data, 0, data.Length); download.context.Response.OutputStream.Flush(); download.context.Response.Close(); finishedDownload = download; } } RunningDownloads.Remove(finishedDownload); Log.WriteLog(LogType.General, "Download VidID: " + finishedDownload.VidID + " successfully completed"); } } catch (Exception ex) { Log.WriteLog(LogType.Error, ex.ToString()); } }
public GoogleDrive() { webClient = new CookieAwareWebClient(); webClient.DownloadProgressChanged += DownloadProgressChangedCallback; webClient.DownloadFileCompleted += DownloadFileCompletedCallback; downloadProgress = new DownloadProgress(); }
public override void DidWriteData(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { try { if ((downloadTask == null) || (downloadTask.OriginalRequest == null) || (downloadTask.OriginalRequest.Url == null)) { return; } if (DateTime.UtcNow.Subtract(lastProgressUpdate).TotalSeconds < 1) { return; } DownloadProgress progress = new DownloadProgress() { Status = DownloadStatus.Downloading, TotalLength = totalBytesExpectedToWrite, DownloadedLength = totalBytesWritten, Url = downloadTask.OriginalRequest.Url.ToString(), }; calculateTimeRemaining(progress); lastProgressUpdate = DateTime.UtcNow; if (itemDownloader != null) { InvokeOnMainThread(() => itemDownloader.Fire_DownloadProgress(progress)); } } catch (Exception ex) { Logger.Log("ERROR: DidWriteData: " + ex); } }
static void Main() { Utils.ReleaseMemory(true); using (Mutex mutex = new Mutex(false, "Global\\V2RayShell_" + Application.StartupPath.GetHashCode())) { Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += Application_ThreadException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ApplicationExit += Application_ApplicationExit; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var processesName = Process.GetCurrentProcess().MainModule?.ModuleName ?? "V2RayShell.exe"; var processesNameWithoutExtension = Path.GetFileNameWithoutExtension(processesName); if (!mutex.WaitOne(0, false)) { Process[] oldProcesses = Process.GetProcessesByName(processesNameWithoutExtension); if (oldProcesses.Length > 0) { Process oldProcess = oldProcesses[0]; } MessageBox.Show(I18N.GetString("Find V2RayShell icon in your notify tray.") + "\n" + I18N.GetString("If you want to start multiple V2RayShell, make a copy in another directory."), I18N.GetString("V2RayShell is already running.")); return; } Logging.OpenLogFile(); //check if (V2Ray.CoreExsis) { if (V2Ray.Version != null) { Logging.Info("V2RayCore version : " + V2Ray.Version); } else { throw new Exception(I18N.GetString("v2ray.exe -version parse fail!")); } } else { //need do sth var download = new DownloadProgress(); var result = download.ShowDialog(); if (result == DialogResult.Abort || result == DialogResult.Cancel) { MessageBox.Show(I18N.GetString("download fail!"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Logging.Info("V2RayCore version : " + V2Ray.Version); } var controller = new V2RayShellController(); var viewController = new MenuViewController(controller); Hotkeys.HotKeys.Init(controller, viewController); controller.StartAsync(); Application.Run(); } }
private void btnDescargar_Click(object sender, EventArgs e) { if (FormUtils.HayFilaElegida(listaArchivos)) { FileObject fileSelected = (FileObject)listaArchivos.SelectedItems[0].Tag; if (fileSelected != null) { ServerInfo serverInfo = serversToSearch[fileSelected.Server]; SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "Descargar Archivo"; sfd.FileName = fileSelected.Name; sfd.OverwritePrompt = false; if (sfd.ShowDialog() == DialogResult.OK) { FileDownloader fd = new FileDownloader() { Destination = sfd.FileName, FileSelected = fileSelected, ServerInfo = serverInfo }; //muestro la ventana del progress bar DownloadProgress dp = new DownloadProgress(fd); dp.Show(); //inicio la descarga en otro sred fd.DownloadThread(); } } } }
private void ItemDownloaderOnDownloadProgress(object sender, DownloadProgress itemDownloaderProgress) { if (cloudItems == null) { return; } var itemBeingDownloaded = cloudItems.FirstOrDefault(item => item.ID == itemDownloaderProgress.Id || item.DownloadUrl == itemDownloaderProgress.Url); if (itemBeingDownloaded != null) { if (itemBeingDownloaded.DownloadStatus != DownloadStatus.Downloading) { itemBeingDownloaded.DownloadStatus = DownloadStatus.Downloading; try { SuspendOnSelectedItemDetailsChangedEvent = true; Download.ChangeCanExecute(); CancelDownload.ChangeCanExecute(); Delete.ChangeCanExecute(); Play.ChangeCanExecute(); SuspendOnSelectedItemDetailsChangedEvent = false; } catch { } } itemBeingDownloaded.DownloadProgress = itemDownloaderProgress; } }
private void DownloadProgressChanged(DownloadProgress downloadProgress, long bytesReceived, long totalBytesToReceive) { if (downloadProgress.StartedAt == default(DateTime)) { downloadProgress.StartedAt = DateTime.Now; } else { var timeSpan = DateTime.Now - downloadProgress.StartedAt; if (timeSpan.TotalSeconds > 0) { downloadProgress.Info.Speed = bytesReceived / timeSpan.TotalMilliseconds; downloadProgress.Info.TotalBytes = totalBytesToReceive; downloadProgress.Info.RecievedBytes = bytesReceived; } } downloadProgress.Report(new DownloadInfo { IsCompleted = false, RecievedBytes = downloadProgress.Info.RecievedBytes, TotalBytes = downloadProgress.Info.TotalBytes, Speed = downloadProgress.Info.Speed, }); }
private async Task DownloadFileChunk(string url, DownloadProgress progress, long?totalSize, CancellationToken cancellationToken, Tuple <long, long> readRange, int index, ConcurrentDictionary <int, string> tempFilesDictionary) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url); httpRequestMessage.Headers.Range = new RangeHeaderValue(readRange.Item1, readRange.Item2); using (var resp = await _client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken)) { string tempFilePath = Path.GetTempFileName(); Trace.WriteLine("DownloadChunk" + index + ": " + tempFilePath); using (var fileStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write, FileShare.Write)) using (var inStream = await resp.Content.ReadAsStreamAsync()) { byte[] buf = new byte[1024 * 1024]; while (true) { int n = await inStream.ReadAsync(buf, 0, buf.Length, cancellationToken); if (n == 0) { break; } await fileStream.WriteAsync(buf, 0, n, cancellationToken); progress(n, totalSize); } tempFilesDictionary.TryAdd((int)index, tempFilePath); } } }
private void DownloadOutputDataReceived(DataReceivedEventArgs eventArgs, VideoConfig video) { _downloadLog += eventArgs.Data + "\r\n"; Log.Debug(eventArgs.Data); ParseDownloadProgress(video, eventArgs); DownloadProgress?.Invoke(video); }
private void beginResponse(CancellationToken cancellationToken) { using (var responseStream = response.Content.ReadAsStreamAsync().Result) { reportForwardProgress(); Started?.Invoke(); buffer = new byte[buffer_size]; while (true) { cancellationToken.ThrowIfCancellationRequested(); int read = responseStream.Read(buffer, 0, buffer_size); reportForwardProgress(); if (read > 0) { ResponseStream.Write(buffer, 0, read); responseBytesRead += read; DownloadProgress?.Invoke(responseBytesRead, response.Content.Headers.ContentLength ?? responseBytesRead); } else { ResponseStream.Seek(0, SeekOrigin.Begin); Complete(); break; } } } }
private async Task DownloadFile(string url, string to, DownloadProgress progress, CancellationToken cancellationToken) { using (var resp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken)) { using (var inStream = await resp.Content.ReadAsStreamAsync()) using (var outStream = new FileStream(to, FileMode.Create)) { long?totalSize = resp.Content.Headers.ContentLength; progress(0, totalSize); long transferred = 0; byte[] buf = new byte[1024 * 1024]; while (true) { int n = await inStream.ReadAsync(buf, 0, buf.Length, cancellationToken); if (n == 0) { break; } await outStream.WriteAsync(buf, 0, n, cancellationToken); transferred += n; progress(transferred, totalSize); } } } }
private void SygnalEventProgress(DownloadProgress CurrentDownloadProgress) { if (DownloadProcessingEvent != null) { DownloadProcessingEvent.Invoke(CurrentDownloadProgress, null); } }
void notifyIcon1_BalloonTipClicked(object sender, EventArgs e) { if (updateflag == 1) { updateflag = 0; /* Reset the flag */ System.Diagnostics.Process.Start(UpdateChecker.SHELL_URL); } else if (updateflag == 2) { updateflag = 0; var download = new DownloadProgress(); var dg = download.ShowDialog(); if (dg == DialogResult.Abort || dg == DialogResult.Cancel) { MessageBox.Show(I18N.GetString("download fail!"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } controller.RestartCore(); } else if (updateflag == 3) { updateflag = 0; System.Diagnostics.Process.Start(UpdateChecker.SHELL_URL); var download = new DownloadProgress(); var dg = download.ShowDialog(); if (dg == DialogResult.Abort || dg == DialogResult.Cancel) { MessageBox.Show(I18N.GetString("download fail!"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } controller.RestartCore(); } }
public async Task <StorageFile> Download(string uri) { Uri source = new Uri(uri + @"/download"); HttpClient client = new HttpClient(); var result = await client.GetAsync(source, HttpCompletionOption.ResponseHeadersRead); var content = result.Content; var header = content.Headers; //Clean invalid chars in filename string fileName = CleanFileName(header.ContentDisposition.FileName); StorageFolder d = await StorageFolder.GetFolderFromPathAsync(ApplicationData.Current.LocalCacheFolder.Path); StorageFile file = await d.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists); var size = await file.GetBasicPropertiesAsync(); if (size.Size == 0) { _progress = new DownloadProgress(); _progress.ShowAsync(); _backgroundDownloader = new BackgroundDownloader(); Progress <DownloadOperation> progress = new Progress <DownloadOperation>(progressChanged); _downloadOperation = _backgroundDownloader.CreateDownload(source, file); _downloadOperation.StartAsync(); await _downloadOperation.AttachAsync().AsTask(_cancellationTokenSourceken.Token, progress); } return(file); }
public async Task DownloadAsync(WebClient client, DownloadProgress downloadProgress, CancellationToken cancellationToken) { // Ensure throttling and increment concurrent download count await EnsureThrottlingAsync(cancellationToken); try { client.DownloadFileCompleted += (s, e) => DownloadFileCompleted(downloadProgress, s, e); client.DownloadProgressChanged += (_, e) => DownloadProgressChanged(downloadProgress, e.BytesReceived, e.TotalBytesToReceive); downloadProgress.Report(new DownloadInfo { IsCompleted = true, RecievedBytes = 0, TotalBytes = 100, Speed = 0, Result = "正在下载" }); await client.DownloadFileTaskAsync(new Uri(downloadProgress.Url), downloadProgress.FilePath); } //catch (Exception ex) //{ // Console.WriteLine(); //} finally { // Decrement concurrent download count Interlocked.Decrement(ref _concurrentDownloadCount); } }
private void calculateTimeRemaining(DownloadProgress progress) { DownloadItem item = DownloadSessionMetadata.GetDownloadItem(progress.Url.ToString()); if (item == null) { return; } if (!item.TimeStarted.HasValue) { item.TimeStarted = DateTime.UtcNow; } try { var timeElapsed = DateTime.UtcNow.Subtract(item.TimeStarted.Value); var lastSpeed = progress.DownloadedLength / timeElapsed.TotalSeconds; progress.ExpectedDuration = (long)((progress.TotalLength / lastSpeed) * 1000); progress.DownloadedDuration = (long)timeElapsed.TotalMilliseconds; progress.Percent = (double)progress.DownloadedLength / progress.TotalLength; progress.Id = item.Id; DownloadSessionMetadata.SaveDownloadItem(item); } catch (Exception ex) { Logger.Log("ERROR: calculateTimeRemaining: " + ex); } }
private void OnDownloadProgress(object sender, DownloadOperation op) { Debug.WriteLine($"{op.RequestedUri}:{op.Progress.TotalBytesToReceive}"); var info = NiconicoMediaManager.CacheRequestInfoFromFileName(op.ResultFile); DownloadProgress?.Invoke(this, info, op); }
private void OnDownloadProgressChanged(DownloadProgress progress) { lock (mutex) { lastDownloadProgress = progress; } }
public void SetValue(float value) { DoubleAnimation animation = new DoubleAnimation(value, new TimeSpan(0, 0, 0, 0, 200)); animation.AccelerationRatio = animation.DecelerationRatio = .5; DownloadProgress.BeginAnimation(ProgressBar.ValueProperty, animation); }
private static async Task DownloadFileWithProgress(string url, string saveTo, CancellationToken ct = default) { var download_response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); download_response.EnsureSuccessStatusCode(); var filesize = download_response.Content.Headers.ContentLength.GetValueOrDefault(-1); var reprfilesize = filesize > 0 ? FormatSize(filesize) : "unknown size"; long bytes_transferred = 0; DownloadProgress?.Invoke(bytes_transferred, filesize); using var download_stream = await download_response.Content.ReadAsStreamAsync(); using var fs = File.OpenWrite(saveTo); var buffer = ArrayPool <byte> .Shared.Rent(81920); while (true) { var len = await download_stream.ReadAsync(buffer, 0, buffer.Length, ct); if (len == 0) { break; } bytes_transferred += len; await fs.WriteAsync(buffer, 0, len, ct); DownloadProgress?.Invoke(bytes_transferred, filesize); } DownloadProgress?.Invoke(bytes_transferred, filesize); DownloadProgress?.Invoke(-1, -1); ArrayPool <byte> .Shared.Return(buffer); }
private void OnDownloadProgressChanged(IList <IDownloadWorkerProgress> progressList) { if (_downloadProgressChanged.IsDisposed) { return; } var orderedList = progressList.ToList().OrderBy(x => x.Id).ToList(); StringBuilder builder = new StringBuilder(); foreach (var progress in orderedList) { builder.Append($"({progress.Id} - {progress.Percentage} {progress.DownloadSpeedFormatted}) + "); } // Remove the last " + " if (builder.Length > 3) { builder.Length -= 3; } var downloadProgress = new DownloadProgress(orderedList) { Id = DownloadTaskId, DataTotal = TotalBytesToReceive, }; builder.Append($" = ({downloadProgress.DownloadSpeedFormatted} - {downloadProgress.TimeRemaining})"); Log.Verbose(builder.ToString()); _downloadProgressChanged.OnNext(downloadProgress); }
/* Methode zum asynchronen Download einer Datei */ public void DownloadAsync(string url, Stream destStream, int blockSize, DownloadProgress downloadProgress, DownloadEnd downloadEnd) { // Das Download-Status-Objekt, das über das Status- // Feld des asynchronen Aufrufs weitergegeben wird, // erzeugen und initialisieren DownloadStatus downloadStatus = new DownloadStatus(); downloadStatus.BlockSize = blockSize; downloadStatus.ReadBuffer = new Byte[blockSize]; downloadStatus.DownloadProgress = downloadProgress; downloadStatus.DownloadEnd = downloadEnd; downloadStatus.DestStream = destStream; downloadStatus.manualResetEvent = new ManualResetEvent(false); downloadStatus.manualResetEvent.Reset(); // WebRequest-Instanz für den Download erzeugen downloadStatus.Request = WebRequest.Create(url); // Die Antwort asynchron abfragen IAsyncResult asyncResult = (IAsyncResult)downloadStatus.Request.BeginGetResponse( new AsyncCallback(ResponseCallback), downloadStatus); //downloadStatus.manualResetEvent.WaitOne(); }
protected void Step_DownloadAudiobook_End(DownloadProgress zeroProgress) { AaxFile.Close(); CloseInputFileStream(); OnDecryptProgressUpdate(zeroProgress); }
internal static void OnDownloadProgress(Image image, int downloadPercentage) { #if WPF image.RaiseEvent(new DownloadProgressEventArgs(image, downloadPercentage)); #elif WINRT || SILVERLIGHT DownloadProgress?.Invoke(image, new DownloadProgressEventArgs(downloadPercentage)); #endif }
void DownloadFileProcessHTTP() { DownloadProgress CurrentDownloadProgress = new DownloadProgress(); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Current.FullURL); if (!string.IsNullOrEmpty(Current.Proxy.ProxyAddress)) { WebProxy MyProxy = new WebProxy(Current.Proxy.ProxyAddress, Current.Proxy.Port); MyProxy.Credentials = new NetworkCredential(Current.Proxy.UserName, Current.Proxy.Password); request.Proxy = MyProxy; } if (Current.BytesDownloaded != 0) { request.AddRange(Current.BytesDownloaded); } request.KeepAlive = true; // Get the response. HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Display the status. string Status = response.StatusDescription; if (Current.BytesDownloaded == 0) { Current.FileSize = (int)response.ContentLength; } // передаем размер файла CurrentDownloadProgress.Type = DownloadMessageType.DownloadStarted; CurrentDownloadProgress.DownloadSize = Current.FileSize; SygnalEventProgress(CurrentDownloadProgress); Stream dataStream = response.GetResponseStream(); Current.Filename = response.ResponseUri.Segments[response.ResponseUri.Segments.Length - 1]; DownloadFileStreamly(dataStream); request.Abort(); dataStream.Close(); response.Close(); } catch (Exception ex) { CurrentDownloadProgress.Type = DownloadMessageType.DownloadError; CurrentDownloadProgress.AdditionalInfo = ex.ToString(); SygnalEventProgress(CurrentDownloadProgress); EndDownloadFileProcess.Set(); throw ex; } finally { EndDownloadFileProcess.Set(); } }
public void UpdateProgressQueueInformation(string format, params object[] args) { var newProgress = new DownloadProgress { Progress = string.Format(CultureInfo.CurrentCulture, format, args) }; progress.Report(newProgress); }
private void StartDownload(List <DownloadFileInfo> downloadList) { DownloadProgress dp = new DownloadProgress(downloadList); if (dp.ShowDialog() == DialogResult.OK) { new frmMessageBox(Properties.Settings.Default.SoftwareUpdate_Restart_Text, "Close Operator Station to apply this update.", MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button2); } }
/* Konstruktor */ public Download(string url, Stream destStream, int blockSize, DownloadProgress downloadProgress, DownloadEnd downloadEnd, DownloadError downloadError) { this.Url = url; this.BlockSize = blockSize; this.DownloadProgress = downloadProgress; this.DownloadEnd = downloadEnd; this.DestStream = destStream; this.DownloadError = downloadError ; }
/* Methode zum synchronen Download einer Datei */ public void DownloadSync(string url, Stream destStream, int blockSize, DownloadProgress downloadProgress, DownloadEnd downloadEnd, DownloadError downloadError) { // Download-Objekt erzeugen und initialisieren Download download = new Download(url, destStream, blockSize, downloadProgress, downloadEnd, downloadError); // Download synchron starten download.PerformDownload(); }
/* Methode zum asynchronen Download einer Datei */ public void DownloadAsync(string url, Stream destStream, int blockSize, DownloadProgress downloadProgress, DownloadEnd downloadEnd, DownloadError downloadError) { // Download-Objekt erzeugen und initialisieren Download download = new Download(url, destStream, blockSize, downloadProgress, downloadEnd, downloadError); // Thread für den Download starten Thread downloadThread = new Thread(new ThreadStart(download.PerformDownload)); downloadThread.Start(); }
public static string postDownload(DownloadProgress dp, PendingResponse pr, BackgroundWorker worker) { int percentComplete = (int)(100 * dp.bytesDownloaded / pr.fileSize); if (dp.isFailed) { dp.attempts = dp.attempts + 1; if (dp.attempts > 10) { dp.status = "Failed"; dp.isFailedUnrecoverably = true; worker.ReportProgress(percentComplete, dp); return null; } dp.status = "Retrying.. (" + dp.attempts + ")"; dp.isFailed = false; worker.ReportProgress(percentComplete, dp); System.Threading.Thread.Sleep(3000); return "FAILED"; } BackgroundWorker updateWorker = new BackgroundWorker(); updateWorker.DoWork += Downloads.updateWorker_DoWork; updateWorker.RunWorkerCompleted += Downloads.updateWorker_RunWorkerCompleted; // Set update parameters UpdateRequest updateRequest = new UpdateRequest(); updateRequest.transferID = dp.transferID; updateRequest.uploader = dp.mac; if (dp.isCanceled) { try { File.Delete(dp.downloadedFilePath); } catch (Exception e2) { } // Do nothing. We only want to try and delete the file. // Remove from pendingToDownload DownloadProgress temp = null; pendingToDownload.TryRemove(pr, out temp); updateRequest.newHash = dp.hash; updateRequest.status = "canceled"; updateWorker.RunWorkerAsync(updateRequest); return null; } // Download neither canceled nor failed String newHash = Indexer.GenerateHash(dp.downloadedFilePath); if (dp.type == "secondleg" || dp.type == "direct") { if (newHash == dp.hash) { Utils.writeLog("download: Hash verified"); dp.isComplete = true; dp.status = "Completed"; worker.ReportProgress(100, dp); // Removing from partially-downloaded-files list Settings.Default.partiallyDownloadedFiles.Replace(dp.downloadedFilePath + "; ", ""); } else { Utils.writeLog("download: Hash verification failed"); dp.status = "Failed integrity check"; dp.isHashMismatch = true; dp.isFailed = true; dp.isFailedUnrecoverably = true; worker.ReportProgress(100, dp); try { File.Delete(dp.downloadedFilePath); } catch (Exception e2) { } // Do nothing. We only want to try and delete the file. } updateRequest.newHash = newHash; updateRequest.status = "done"; updateWorker.RunWorkerAsync(updateRequest); return newHash; } if (dp.type == "firstleg") { // Rename the file to the new hash String newPath = dp.downloadedFilePath.Substring(0, dp.downloadedFilePath.LastIndexOf(@"\")); newPath = newPath + "\\" + newHash + ".bounced"; // Removing from partially-downloaded-files list Settings.Default.partiallyDownloadedFiles.Replace(dp.downloadedFilePath + "; ", ""); try { File.Move(dp.downloadedFilePath, newPath); } catch (Exception e) { Utils.writeLog("download: Critical. Unable to rename file to the new hash."); } dp.status = "Completed"; dp.isComplete = true; worker.ReportProgress(100, dp); } updateRequest.newHash = newHash; updateRequest.status = "done"; updateWorker.RunWorkerAsync(updateRequest); return newHash; }
/// <summary> /// The core download logic. It downloads the media in parts, where each part's size is defined by /// <see cref="ChunkSize"/> (in bytes). /// </summary> /// <param name="url">The URL of the resource to download.</param> /// <param name="stream">The download will download the resource into this stream.</param> /// <param name="cancellationToken">A cancellation token to cancel this download in the middle.</param> /// <returns>A task with the download progress object. If an exception occurred during the download, its /// <see cref="IDownloadProgress.Exception "/> property will contain the exception.</returns> private async Task<IDownloadProgress> DownloadCoreAsync(string url, Stream stream, CancellationToken cancellationToken) { url.ThrowIfNull("url"); stream.ThrowIfNull("stream"); if (!stream.CanWrite) { throw new ArgumentException("stream doesn't support write operations"); } RequestBuilder builder = null; var uri = new Uri(url); if (string.IsNullOrEmpty(uri.Query)) { builder = new RequestBuilder() { BaseUri = new Uri(url) }; } else { builder = new RequestBuilder() { BaseUri = new Uri(url.Substring(0, url.IndexOf("?"))) }; // Remove '?' at the beginning. var query = uri.Query.Substring(1); var pairs = from parameter in query.Split('&') select parameter.Split('='); // Add each query parameter. each pair contains the key [0] and then its value [1]. foreach (var p in pairs) { builder.AddParameter(RequestParameterType.Query, p[0], p[1]); } } builder.AddParameter(RequestParameterType.Query, "alt", "media"); long currentRequestFirstBytePos = 0; try { // This "infinite" loop stops when the "to" byte position in the "Content-Range" header is the last // byte of the media ("length"-1 in the "Content-Range" header). // e.g. "Content-Range: 200-299/300" - "to"(299) = "length"(300) - 1. while (true) { var currentRequestLastBytePos = currentRequestFirstBytePos + ChunkSize - 1; // Create the request and set the Range header. var request = builder.CreateRequest(); request.Headers.Range = new RangeHeaderValue(currentRequestFirstBytePos, currentRequestLastBytePos); using (var response = await service.HttpClient.SendAsync(request, cancellationToken). ConfigureAwait(false)) { // Read the content and copy to the parameter's stream. var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); responseStream.CopyTo(stream); // Read the headers and check if all the media content was already downloaded. var contentRange = response.Content.Headers.ContentRange; long mediaContentLength; if (contentRange == null) { // Content range is null when the server doesn't adhere the media download protocol, in // that case we got all the media in one chunk. currentRequestFirstBytePos = mediaContentLength = response.Content.Headers.ContentLength.Value; } else { currentRequestFirstBytePos = contentRange.To.Value + 1; mediaContentLength = contentRange.Length.Value; } if (currentRequestFirstBytePos == mediaContentLength) { var progress = new DownloadProgress(DownloadStatus.Completed, mediaContentLength); UpdateProgress(progress); return progress; } } UpdateProgress(new DownloadProgress(DownloadStatus.Downloading, currentRequestFirstBytePos)); } } catch (TaskCanceledException ex) { Logger.Error(ex, "Download media was canceled"); UpdateProgress(new DownloadProgress(ex, currentRequestFirstBytePos)); throw ex; } catch (Exception ex) { Logger.Error(ex, "Exception occurred while downloading media"); var progress = new DownloadProgress(ex, currentRequestFirstBytePos); UpdateProgress(progress); return progress; } }
/// <summary> /// The core download logic. We download the media and write it to an output stream /// ChunkSize bytes at a time, raising the ProgressChanged event after each chunk. /// /// The chunking behavior is largely a historical artifact: a previous implementation /// issued multiple web requests, each for ChunkSize bytes. Now we do everything in /// one request, but the API and client-visible behavior are retained for compatibility. /// </summary> /// <param name="url">The URL of the resource to download.</param> /// <param name="stream">The download will download the resource into this stream.</param> /// <param name="cancellationToken">A cancellation token to cancel this download in the middle.</param> /// <returns>A task with the download progress object. If an exception occurred during the download, its /// <see cref="IDownloadProgress.Exception "/> property will contain the exception.</returns> private async Task<IDownloadProgress> DownloadCoreAsync(string url, Stream stream, CancellationToken cancellationToken) { url.ThrowIfNull("url"); stream.ThrowIfNull("stream"); if (!stream.CanWrite) { throw new ArgumentException("stream doesn't support write operations"); } // Add alt=media to the query parameters. var uri = new UriBuilder(url); if (uri.Query == null || uri.Query.Length <= 1) { uri.Query = "alt=media"; } else { // Remove the leading '?'. UriBuilder.Query doesn't round-trip. uri.Query = uri.Query.Substring(1) + "&alt=media"; } var request = new HttpRequestMessage(HttpMethod.Get, uri.ToString()); // Number of bytes sent to the caller's stream. long bytesReturned = 0; try { // Signal SendAsync to return as soon as the response headers are read. // We'll stream the content ourselves as it becomes available. var completionOption = HttpCompletionOption.ResponseHeadersRead; using (var response = await service.HttpClient.SendAsync(request, completionOption, cancellationToken).ConfigureAwait(false)) { if (!response.IsSuccessStatusCode) { throw await MediaApiErrorHandling.ExceptionForResponseAsync(service, response).ConfigureAwait(false); } using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { // We send ChunkSize bytes at a time to the caller, but we keep ChunkSize + 1 bytes // buffered. That way we can tell when we've reached the end of the response, even if the // response length is evenly divisible by ChunkSize, and we can avoid sending a Downloading // event followed by a Completed event with no bytes downloaded in between. // // This maintains the client-visible behavior of a previous implementation. var buffer = new CountedBuffer(ChunkSize + 1); while (true) { await buffer.Fill(responseStream, cancellationToken).ConfigureAwait(false); // Send one chunk to the caller's stream. int bytesToReturn = Math.Min(ChunkSize, buffer.Count); await stream.WriteAsync(buffer.Data, 0, bytesToReturn, cancellationToken).ConfigureAwait(false); bytesReturned += bytesToReturn; buffer.RemoveFromFront(ChunkSize); if (buffer.IsEmpty) { // We had <= ChunkSize bytes buffered, so we've read and returned the entire response. // Skip sending a Downloading event. We'll send Completed instead. break; } UpdateProgress(new DownloadProgress(DownloadStatus.Downloading, bytesReturned)); } } var finalProgress = new DownloadProgress(DownloadStatus.Completed, bytesReturned); UpdateProgress(finalProgress); return finalProgress; } } catch (TaskCanceledException ex) { Logger.Error(ex, "Download media was canceled"); UpdateProgress(new DownloadProgress(ex, bytesReturned)); throw; } catch (Exception ex) { Logger.Error(ex, "Exception occurred while downloading media"); var progress = new DownloadProgress(ex, bytesReturned); UpdateProgress(progress); return progress; } }
public static string download(BackgroundWorker worker, PendingResponse pr, DownloadProgress dp, long startByte) { TcpClient tcpClient = new TcpClient(); NetworkStream clientStream = null; try { tcpClient.Connect(pr.uploaderIP, 8002); clientStream = tcpClient.GetStream(); Utils.writeLog("download: Sending download instruction to peer " + pr.uploaderIP + "..."); //Format: fileHash | transfer ID | transfer-type Utils.writeLog("tid is "+ pr.transferID); ASCIIEncoding encoder = new ASCIIEncoding(); byte[] buffer = encoder.GetBytes(pr.fileHash + "|" + pr.transferID + "|" + pr.type + "|" + startByte); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); Utils.writeLog("download: Download started."); } catch (Exception e) { Utils.writeLog("download: Could not establish connection. Error : " + e); dp.isFailed = true; return postDownload(dp, pr, worker); } // Begin file transfer FileStream strLocal = null; Downloads.currentDownloads.Add(dp); // Add the download to the gridview worker.ReportProgress(0, dp); #region initvars long bytesDownloaded = startByte; //Total bytes downloaded for the file int bytesSize; //Number of bytes read by the stream reader int tempTransferRate = 0; //Instantaneous (for 1 refresh cycle) download rate long downloadedInCycle = 0; //Total bytes downloaded in the last refresh cycle int percentComplete = 0; DateTime startTime = DateTime.Now; //To track total download time DateTime refresh = DateTime.Now; //To track time since last refresh byte[] downBuffer = new byte[4096]; bool appendToExistingFile = false; // Find a free filename if (File.Exists(dp.downloadedFilePath)) { long existingFileLength = new FileInfo(dp.downloadedFilePath).Length; // First file found should be appended to if (startByte > 0 && startByte == existingFileLength) appendToExistingFile = true; else { String candidatePath = ""; for (int i = 2; i < 100; i++) // 100 here is arbitrary, just want to make sure it doesnt loop forever { candidatePath = dp.downloadedFilePath.Substring(0, dp.downloadedFilePath.LastIndexOf('.')); candidatePath += " (" + i + ")"; candidatePath += dp.downloadedFilePath.Substring(dp.downloadedFilePath.LastIndexOf('.')); if (!File.Exists(candidatePath)) { Utils.writeLog("download: Found free file path " + candidatePath); dp.downloadedFilePath = candidatePath; dp.fileName = dp.downloadedFilePath.Substring(dp.downloadedFilePath.LastIndexOf(@"\") + 1); break; } else { existingFileLength = new FileInfo(candidatePath).Length; if (startByte > 0 && startByte == existingFileLength) { dp.downloadedFilePath = candidatePath; appendToExistingFile = true; break; } } } } } try { if (appendToExistingFile) { strLocal = new FileStream(dp.downloadedFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); } else { strLocal = new FileStream(dp.downloadedFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); } } catch (Exception e) { Utils.writeLog("download: Error creating file : " + e); // Attempt to recover from error that download folder doesn't exist. String filePath = dp.downloadedFilePath; String folderPath = filePath.Substring(0, filePath.LastIndexOf("\\")); try { System.IO.Directory.CreateDirectory(folderPath); strLocal = new FileStream(dp.downloadedFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); } catch (Exception e2) { Utils.writeLog("download: Unrecoverable error while creating folder to hold file"); MessageBox.Show("Could not download file as the download folder could not be found or created", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } } Settings.Default.partiallyDownloadedFiles = dp.downloadedFilePath + "; " + Settings.Default.partiallyDownloadedFiles; #endregion try { // Perform file transfer. clientStream.ReadTimeout = 6000; // Need to timeout now to prevent stalled appearance in UI while ((bytesSize = clientStream.Read(downBuffer, 0, downBuffer.Length)) > 0) { // In case user cancels download if (pendingToDownload[pr] == null || worker.CancellationPending) { throw new DownloadCanceledException("Download canceled"); } downloadedInCycle += bytesSize; bytesDownloaded = bytesDownloaded + bytesSize; dp.bytesDownloaded = bytesDownloaded; strLocal.Write(downBuffer, 0, bytesSize); if (pr.fileSize != 0) percentComplete = (int)(100 * bytesDownloaded / pr.fileSize); // Report progress to UI at intervals double msElapsedSinceRefresh = (DateTime.Now - refresh).TotalMilliseconds; if (msElapsedSinceRefresh > 1000) { tempTransferRate = (int)((downloadedInCycle / 1024.0) / (DateTime.Now - refresh).TotalSeconds); dp.status = "Downloading"; // Initialize download speed if (dp.averageTransferRate == 0) dp.averageTransferRate = tempTransferRate; // Compute download speed with smoothing factor dp.transferRate = tempTransferRate; dp.averageTransferRate = (0.01) * tempTransferRate + (0.99) * dp.averageTransferRate; worker.ReportProgress(percentComplete, dp); refresh = DateTime.Now; downloadedInCycle = 0; } } dp.bytesDownloaded = bytesDownloaded; dp.transferRate = tempTransferRate; worker.ReportProgress(100, dp); Utils.writeLog("download: Completed download of " + pr.fileName + " (" + dp.fileSize + ") Type:" + dp.type); dp.status = "Checking file.."; } catch (DownloadCanceledException dce) // Occurs when user cancels { Utils.writeLog("download: Canceled by user"); dp.status = "Canceled"; dp.isCanceled = true; } catch (Exception e) // Should only occur due to poor network/peer going offline { Utils.writeLog("download: Error:" + e.ToString()); dp.status = "Failed"; dp.isFailed = true; } finally { worker.ReportProgress(percentComplete, dp); strLocal.Close(); clientStream.Close(); } return postDownload(dp, pr, worker); }
private void pollPendingWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { List<PendingResponse> latestPending = (List<PendingResponse>)e.Result; if (latestPending == null) { statusPictureBox.Image = Resources.connection_working; mainToolTip.SetToolTip(statusPictureBox, "Trying to connect.."); statusLabel.Text = "Lost connection to network"; pollPendingTimer.Enabled = false; reconnectTimer.Enabled = true; Utils.writeLog("pollPendingWorker_RunWorkerCompleted: Received null response from server"); return; } foreach (PendingResponse pr in latestPending) { if (pr == null || pr.type == null) { Utils.writeLog("pollPendingWorker_RunWorkerCompleted: Received a null pending"); continue; } if (pr.type.Equals("delete")) { Utils.writeLog("pollPendingWorker_RunWorkerCompleted: Got delete request for " + pr.fileHash + " (" + pr.fileName + ") "); String filePath = Utils.getAppDataPath(@"\Bounces\" + pr.fileHash + ".bounced"); try { File.Delete(filePath); } catch (Exception e2) { //TODO: Do nothing. } // Tell the server we have deleted the file BackgroundWorker updateWorker = new BackgroundWorker(); updateWorker.DoWork += Downloads.updateWorker_DoWork; updateWorker.RunWorkerCompleted += Downloads.updateWorker_RunWorkerCompleted; // Set update parameters and kick off update UpdateRequest ur = new UpdateRequest(); ur.transferID = pr.transferID; ur.status = "done"; ur.uploader = pr.uploader; updateWorker.RunWorkerAsync(ur); continue; } bool performPending = false; // Checking if the same file is already being downloaded by the client if (!Downloads.pendingToDownload.ContainsKey(pr)) { foreach(PendingResponse existingPending in Downloads.pendingToDownload.Keys) { if (existingPending.fileHash.Equals(pr.fileHash)) return; } performPending = true; } if (performPending) { Utils.writeLog("Added " + pr.fileName + " to download queue"); DownloadProgress dip = new DownloadProgress(pr); Downloads.pendingToDownload[pr] = dip; BackgroundWorker downloadWorker = new BackgroundWorker(); downloadWorker.WorkerReportsProgress = true; downloadWorker.WorkerSupportsCancellation = true; downloadWorker.DoWork += downloadWorker_DoWork; downloadWorker.ProgressChanged += downloadWorker_ProgressChanged; downloadWorker.RunWorkerCompleted += downloadWorker_RunWorkerCompleted; // This is what is sent to the backgroundworker Tuple<PendingResponse, DownloadProgress> downloadArgs = new Tuple<PendingResponse, DownloadProgress>(pr, dip); downloadWorker.RunWorkerAsync(downloadArgs); } } }
private void Helper_DownloadProgress(object sender, DownloadProgress e) { ProgressDownload.Value = e.TotalBytesRead; ProgressDownload.UpdateLayout(); double progressCount = ((e.ProgressMb * 100) / e.TotalMb); LblProgressDownload.Text = ((int)progressCount).ToString(); LblProgressDownload.UpdateLayout(); }
/// <summary> /// Chunked download, based on the iplayer-dl code. /// Downloads a megabyte between reporting progress. /// /// Resumes downloads if they are partially down. /// </summary> private void DownloadToFile(string streamingUrl, string outputFilename, DownloadProgress OnDownloadProgress, DownloadFinished OnDownloadFinished) { Console.WriteLine("Downloading {0}\r\nto {1}.", streamingUrl, outputFilename); int fileSize = GetTotalFilesize(streamingUrl); int bufferSize = 1 * 1024 * 1024; //half a meg int bytesTransfered = 0; bool lastOne = false; //int debugIterations = 0; //might need to change this if/when we do pause/resume/cancel etc? FileStream fs; if (File.Exists(outputFilename)) { Console.WriteLine("resuming download"); fs = new FileStream(outputFilename, FileMode.Append); bytesTransfered = (int)fs.Length; } else { fs = new FileStream(outputFilename, FileMode.Create); } using (fs) { while (lastOne == false && fileSize > 0) { //debugIterations ++; //if (debugIterations == 14) //{ // lastOne = true; // Console.WriteLine("Exting the downloader as we are using the debug version!!"); //} HttpWebRequest req = new HttpWebRequest(new Uri(streamingUrl)); req.CookieContainer = cookieContainer; req.UserAgent = IplayerConst.QT_UA; int endByte = bytesTransfered + bufferSize; if (endByte > fileSize) { endByte = fileSize; lastOne = true; } req.AddRange("bytes", bytesTransfered, endByte); req.Accept = "*/*"; Console.WriteLine("getting block: {0} / {1} of {2} ", bytesTransfered, endByte, fileSize); using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) { byte[] buffer = null; using (Stream s = resp.GetResponseStream()) { buffer = new byte[bufferSize]; while (true) { int bytesRead = s.Read(buffer, 0, bufferSize); if (bytesRead == 0) break; fs.Write(buffer, 0, bytesRead); bytesTransfered += bytesRead; } resp.Close(); fs.Flush(); buffer = null; } if (OnDownloadProgress != null) { float f = (float)bytesTransfered / (float)fileSize; OnDownloadProgress(f); } } } fs.Flush(); fs.Close(); } if (OnDownloadFinished != null) { OnDownloadFinished(); } Console.WriteLine("download is done"); }