Пример #1
0
        public void StopResumeDownloadFromLastPositionTest()
        {
            // arrange
            var expectedStopCount            = 5;
            var stopCount                    = 0;
            var downloadFileExecutionCounter = 0;
            var totalDownloadSize            = 0L;
            var config = (DownloadConfiguration)Config.Clone();

            config.BufferBlockSize = 1024;
            var downloader = new DownloadService(Config);

            downloader.DownloadProgressChanged += (s, e) => {
                totalDownloadSize += e.ReceivedBytes.Length;
                if (expectedStopCount > stopCount)
                {
                    // Stopping after start of downloading
                    downloader.CancelAsync();
                    stopCount++;
                }
            };

            // act
            downloader.DownloadFileTaskAsync(DownloadTestHelper.File16KbUrl).Wait();
            while (expectedStopCount > downloadFileExecutionCounter++)
            {
                downloader.DownloadFileTaskAsync(downloader.Package).Wait(); // resume download from stopped point.
            }

            // assert
            Assert.AreEqual(DownloadTestHelper.FileSize16Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(DownloadTestHelper.FileSize16Kb, totalDownloadSize);
        }
Пример #2
0
        public void TestTotalReceivedBytesOnResumeDownloadWhenLostDownloadedData()
        {
            // arrange
            var canStopDownload        = true;
            var totalDownloadSize      = 0L;
            var lastProgressPercentage = 0.0;
            var config = (DownloadConfiguration)Config.Clone();

            config.BufferBlockSize = 1024;
            config.ChunkCount      = 1;
            var downloader = new DownloadService(config);

            downloader.DownloadProgressChanged += (s, e) => {
                totalDownloadSize      = e.ReceivedBytesSize;
                lastProgressPercentage = e.ProgressPercentage;
                if (canStopDownload && totalDownloadSize > DownloadTestHelper.FileSize16Kb / 2)
                {
                    // Stopping after start of downloading
                    downloader.CancelAsync();
                    canStopDownload = false;
                }
            };

            // act
            downloader.DownloadFileTaskAsync(DownloadTestHelper.File16KbUrl).Wait();
            downloader.Package.Chunks[0].Storage.Clear();                // set position to zero
            downloader.DownloadFileTaskAsync(downloader.Package).Wait(); // resume download from stopped point.

            // assert
            Assert.AreEqual(DownloadTestHelper.FileSize16Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(DownloadTestHelper.FileSize16Kb, totalDownloadSize);
            Assert.AreEqual(100.0, lastProgressPercentage);
        }
Пример #3
0
        public void StopResumeDownloadOverFirstPackagePositionTest()
        {
            // arrange
            var packageCheckPoint = new DownloadPackage()
            {
                Address = DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb)
            };
            var stopThreshold            = 4100;
            var totalReceivedBytes       = 0L;
            var downloader               = new DownloadService(Config);
            var isSavingStateOnCancel    = false;
            var isSavingStateBeforCancel = false;

            downloader.DownloadProgressChanged += (s, e) => {
                totalReceivedBytes       += e.ReceivedBytes.Length;
                isSavingStateBeforCancel |= downloader.Package.IsSaving;
                if (e.ReceivedBytesSize > stopThreshold)
                {
                    // Stopping after start of downloading
                    downloader.CancelAsync();
                    stopThreshold *= 2;

                    // check point of package for once time
                    packageCheckPoint.Chunks ??= downloader.Package.Chunks.Clone() as Chunk[];
                }
            };

            // act
            downloader.DownloadFileTaskAsync(packageCheckPoint.Address).Wait();
            while (downloader.IsCancelled)
            {
                isSavingStateOnCancel |= downloader.Package.IsSaving;
                var firstCheckPointClone = new DownloadPackage()
                {
                    Address = packageCheckPoint.Address,
                    Chunks  = packageCheckPoint.Chunks.Clone() as Chunk[]
                };
                // resume download from first stopped point.
                downloader.DownloadFileTaskAsync(firstCheckPointClone).Wait();
            }

            // assert
            Assert.IsTrue(downloader.Package.IsSaveComplete);
            Assert.IsFalse(downloader.Package.IsSaving);
            Assert.IsFalse(isSavingStateOnCancel);
            Assert.IsTrue(isSavingStateBeforCancel);
            Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(DummyFileHelper.FileSize16Kb, totalReceivedBytes);
        }
        public async void start()
        {
            await Task.Delay(5000);

            await Task.Run(async() =>
            {
                var downloadOpt = new DownloadConfiguration()
                {
                    ParallelDownload      = true,         // download parts of file as parallel or not
                    BufferBlockSize       = 10240,        // usually, hosts support max to 8000 bytes
                    ChunkCount            = 8,            // file parts to download
                    MaxTryAgainOnFailover = int.MaxValue, // the maximum number of times to fail.
                    OnTheFlyDownload      = true,         // caching in-memory mode
                    Timeout = 1000                        // timeout (millisecond) per stream block reader
                };
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                              async() =>
                {
                    var downloader = new DownloadService(downloadOpt);
                    downloader.DownloadProgressChanged += OnDownloadProgressChangedAsync;

                    downloader.DownloadFileCompleted += OnDownloadFileCompleted;
                    var file = @"Downloads\Annotation-2019-10-04-194747.png";
                    await downloader.DownloadFileTaskAsync("https://i.ibb.co/YDHN1HY/Annotation-2019-10-04-194747.png", file);
                });
            });
        }
Пример #5
0
        public void DynamicSpeedLimitTest()
        {
            // arrange
            double upperTolerance       = 1.2;                               // 20% upper than expected avg speed
            double expectedAverageSpeed = DummyFileHelper.FileSize16Kb / 30; // == (256*16 + 512*8 + 1024*4 + 2048*2)/30
            double averageSpeed         = 0;
            var    progressCounter      = 0;

            Config.MaximumBytesPerSecond = 256; // 256 Byte/s
            var downloader = new DownloadService(Config);

            downloader.DownloadProgressChanged += (s, e) => {
                averageSpeed += e.BytesPerSecondSpeed;
                progressCounter++;

                var oneSpeedStepSize = 4096;                                // DummyFileHelper.FileSize16Kb / 4
                var pow = Math.Ceiling((double)e.ReceivedBytesSize / oneSpeedStepSize);
                Config.MaximumBytesPerSecond = 128 * (int)Math.Pow(2, pow); // 256, 512, 1024, 2048
            };

            // act
            downloader.DownloadFileTaskAsync(DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb)).Wait();
            averageSpeed /= progressCounter;

            // assert
            Assert.AreEqual(DummyFileHelper.FileSize16Kb, downloader.Package.TotalFileSize);
            Assert.IsTrue(averageSpeed <= expectedAverageSpeed * upperTolerance,
                          $"Avg Speed: {averageSpeed} , Expected Avg Speed Limit: {expectedAverageSpeed*upperTolerance}, " +
                          $"Progress Count: {progressCounter}");
        }
Пример #6
0
 private async void btnGetHashWeb_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (!string.IsNullOrEmpty(txtUrl.Text) && txtUrl.Text.IsUrl())
         {
             prgStatus.IsIndeterminate = false;
             btnGetHashWeb.IsEnabled   = false;
             btnGetHashLocal.IsEnabled = false;
             txtHash.IsEnabled         = false;
             try
             {
                 var downloader = new DownloadService();
                 downloader.DownloadProgressChanged += OnDownloadProgressChanged;
                 downloader.DownloadFileCompleted   += OnDownloadFileCompleted;
                 await downloader.DownloadFileTaskAsync(txtUrl.Text, new DirectoryInfo(Consts.TempSetupPath));
             }
             catch (Exception ex)
             {
                 prgStatus.IsIndeterminate = true;
                 prgStatus.ShowError       = true;
                 Growl.ErrorGlobal(ex.Message);
             }
         }
         else
         {
             Growl.ErrorGlobal("Url field is Empty or Invalid");
         }
     }
     catch (Exception ex)
     {
         Growl.ErrorGlobal(ex.Message);
     }
 }
        public async void StartDownload()
        {
            await _downloader.DownloadFileTaskAsync(Url, FilePath);

            intermation.Status   = "下载中";
            intermation.StatusId = 1;
        }
Пример #8
0
        public void Download1KbWithFilenameTest()
        {
            // arrange
            var downloadCompletedSuccessfully = false;
            var downloader = new DownloadService(Config);

            downloader.DownloadFileCompleted += (s, e) => {
                if (e.Cancelled == false && e.Error == null)
                {
                    downloadCompletedSuccessfully = true;
                }
            };

            // act
            var downloadTask = downloader.DownloadFileTaskAsync(DownloadTestHelper.File1KbUrl);

            downloadTask.Wait();
            using var memoryStream = downloadTask.Result;

            // assert
            Assert.IsTrue(downloadCompletedSuccessfully);
            Assert.IsNotNull(memoryStream);
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, memoryStream.Length);
            Assert.IsTrue(DownloadTestHelper.AreEqual(DownloadTestHelper.File1Kb, memoryStream));
        }
Пример #9
0
        public void TestDownloadAndExecuteFileInDownloadCompletedEvent()
        {
            // arrange
            byte[] downloadedBytes = null;
            var    downloadCompletedSuccessfully = false;
            var    downloader = new DownloadService(Config);

            downloader.DownloadFileCompleted += (s, e) => {
                if (e.Cancelled == false && e.Error == null)
                {
                    // Execute the downloaded file within completed event
                    // Note: Execute within this event caused to an IOException:
                    // The process cannot access the file '...\Temp\tmp14D3.tmp' because it is being used by another process.)

                    downloadCompletedSuccessfully = true;
                    downloadedBytes = File.ReadAllBytes(downloader.Package.FileName);
                }
            };

            // act
            downloader.DownloadFileTaskAsync(DownloadTestHelper.File1KbUrl, Path.GetTempFileName()).Wait();

            // assert
            Assert.IsTrue(downloadCompletedSuccessfully);
            Assert.IsNotNull(downloadedBytes);
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, downloadedBytes.Length);
            Assert.IsTrue(DownloadTestHelper.File1Kb.AreEqual(new MemoryStream(downloadedBytes)));
        }
Пример #10
0
        public void StopResumeDownloadTest()
        {
            // arrange
            var expectedStopCount             = 5;
            var stopCount                     = 0;
            var cancellationsOccurrenceCount  = 0;
            var downloadFileExecutionCounter  = 0;
            var downloadCompletedSuccessfully = false;
            var downloader                    = new DownloadService(Config);

            downloader.DownloadFileCompleted += (s, e) => {
                if (e.Cancelled && e.Error != null)
                {
                    cancellationsOccurrenceCount++;
                }
                else
                {
                    downloadCompletedSuccessfully = true;
                }
            };
            downloader.DownloadStarted += delegate {
                if (expectedStopCount > stopCount)
                {
                    // Stopping after start of downloading
                    downloader.CancelAsync();
                    stopCount++;
                }
            };

            // act
            downloader.DownloadFileTaskAsync(DownloadTestHelper.File150KbUrl, Path.GetTempFileName()).Wait();
            while (expectedStopCount > downloadFileExecutionCounter++)
            {
                downloader.DownloadFileTaskAsync(downloader.Package).Wait(); // resume download from stopped point.
            }

            // assert
            Assert.IsTrue(File.Exists(downloader.Package.FileName));
            Assert.AreEqual(DownloadTestHelper.FileSize150Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(expectedStopCount, stopCount);
            Assert.AreEqual(expectedStopCount, cancellationsOccurrenceCount);
            Assert.IsTrue(downloadCompletedSuccessfully);

            File.Delete(downloader.Package.FileName);
        }
Пример #11
0
        private async Task OnStartDownload()
        {
            Model.InfoText = "Starting...";
            Model.IsReady  = false;
            InitDownloader();

            if (Model.UrlAddress.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                await _downloader.DownloadFileTaskAsync(Model.UrlAddress, Model.FilePath);
            }
            else
            {
                IFormatter formatter = new BinaryFormatter();
                await using var packageStream = File.OpenRead(Model.UrlAddress);
                var package = formatter.Deserialize(packageStream) as DownloadPackage;
                await _downloader.DownloadFileTaskAsync(package);
            }
        }
Пример #12
0
        private static async Task <DownloadService> DownloadFile(DownloadItem downloadItem)
        {
            _currentDownloadService = new DownloadService(GetDownloadConfiguration());
            _currentDownloadService.ChunkDownloadProgressChanged += OnChunkDownloadProgressChanged;
            _currentDownloadService.DownloadProgressChanged      += OnDownloadProgressChanged;
            _currentDownloadService.DownloadFileCompleted        += OnDownloadFileCompleted;
            _currentDownloadService.DownloadStarted += OnDownloadStarted;

            if (string.IsNullOrWhiteSpace(downloadItem.FileName))
            {
                await _currentDownloadService.DownloadFileTaskAsync(downloadItem.Url, new DirectoryInfo(downloadItem.FolderPath)).ConfigureAwait(false);
            }
            else
            {
                await _currentDownloadService.DownloadFileTaskAsync(downloadItem.Url, downloadItem.FileName).ConfigureAwait(false);
            }

            return(_currentDownloadService);
        }
Пример #13
0
        public void DownloadOnMemoryStreamContentTest()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            using var stream = (MemoryStream)downloader.DownloadFileTaskAsync(DownloadTestHelper.File1KbUrl).Result;

            // assert
            Assert.IsTrue(DownloadTestHelper.File1Kb.SequenceEqual(stream.ToArray()));
        }
Пример #14
0
        public void DownloadOnMemoryStreamTypeTest()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            using var stream = downloader.DownloadFileTaskAsync(DownloadTestHelper.File1KbUrl).Result;

            // assert
            Assert.IsTrue(stream is MemoryStream);
        }
Пример #15
0
        public void TestTypeWhenDownloadOnMemoryStream()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            using var stream = downloader.DownloadFileTaskAsync(DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize1Kb)).Result;

            // assert
            Assert.IsTrue(stream is MemoryStream);
        }
Пример #16
0
        public void TestContentWhenDownloadOnMemoryStream()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            using var stream = (MemoryStream)downloader.DownloadFileTaskAsync(DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize1Kb)).Result;

            // assert
            Assert.IsTrue(DummyFileHelper.File1Kb.SequenceEqual(stream.ToArray()));
        }
Пример #17
0
        public void DownloadOnMemoryStreamSizeTest()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            using var stream = downloader.DownloadFileTaskAsync(DownloadTestHelper.File1KbUrl).Result;

            // assert
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, stream.Length);
        }
Пример #18
0
        public void TestSizeWhenDownloadOnMemoryStream()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            using var stream = downloader.DownloadFileTaskAsync(DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize1Kb)).Result;

            // assert
            Assert.AreEqual(DummyFileHelper.FileSize1Kb, downloader.Package.TotalFileSize);
            Assert.AreEqual(DummyFileHelper.FileSize1Kb, stream.Length);
        }
Пример #19
0
        private async void DownloadPackageWithInternalDownloader()
        {
            try
            {
                var isConnected = ApplicationHelper.IsConnectedToInternet();

                if (isConnected)
                {
                    var item = cmbArchitectures.SelectedItem as Installer;
                    if (item != null)
                    {
                        var url = Helper.RemoveUrlComment(item.InstallerUrl);

                        if (Helper.Settings.IsIDMEnabled)
                        {
                            toogleDownload.IsChecked = false;
                            Helper.DownloadWithIDM(url);
                        }
                        else
                        {
                            txtStatus.Text           = $"Preparing to download {txtId.Text}";
                            progress.IsIndeterminate = false;
                            progress.ShowError       = false;
                            progress.Value           = 0;
                            downloadedInstallerPath  = $@"{Consts.TempPath}\{txtId.Text}-{txtVersion.Text}-{(cmbArchitectures.SelectedItem as Installer)?.Architecture}{Helper.GetExtension(url)}".Trim();
                            if (!File.Exists(downloadedInstallerPath))
                            {
                                downloaderService = new DownloadService();
                                downloaderService.DownloadProgressChanged += DownloaderService_DownloadProgressChanged;
                                downloaderService.DownloadFileCompleted   += DownloaderService_DownloadFileCompleted;
                                await downloaderService.DownloadFileTaskAsync(url, downloadedInstallerPath);
                            }
                            else
                            {
                                txtStatus.Text = $"{txtId.Text} Already downloaded, We are running it now!";
                                Helper.StartProcess(downloadedInstallerPath);
                                toogleDownload.IsChecked = false;
                            }
                        }
                    }
                }
                else
                {
                    Helper.CreateInfoBar("Network UnAvailable", "Unable to connect to the Internet", panel, Severity.Error);
                }
            }
            catch (Exception ex)
            {
                Helper.CreateInfoBar("Error", ex.Message, panel, Severity.Error);
                toogleDownload.IsChecked = false;
            }
        }
Пример #20
0
        static async Task <Image <Rgba32> > DownloadImage(string url)
        {
            var downloader = new DownloadService(new DownloadConfiguration()
            {
                BufferBlockSize  = 4096,
                ChunkCount       = 5,
                OnTheFlyDownload = false,
                ParallelDownload = true
            });
            var stream = await downloader.DownloadFileTaskAsync(url);

            stream.Seek(0, SeekOrigin.Begin);
            return(ReadGif(stream));
        }
Пример #21
0
        public static async void DowloadServer(string url, string fileName)
        {
            var downloadOpt = new DownloadConfiguration()
            {
                BufferBlockSize       = 10240,        // usually, hosts support max to 8000 bytes, default values is 8000
                ChunkCount            = 8,            // file parts to download, default value is 1
                MaximumBytesPerSecond = int.MaxValue, // download speed limited to 1MB/s, default values is zero or unlimited
                MaxTryAgainOnFailover = int.MaxValue, // the maximum number of times to fail
                OnTheFlyDownload      = false,        // caching in-memory or not? default values is true
                ParallelDownload      = true,         // download parts of file as parallel or not. Default value is false
                TempDirectory         = "C:\\temp",   // Set the temp path for buffering chunk files, the default path is Path.GetTempPath()
                Timeout = 1000,                       // timeout (millisecond) per stream block reader, default values is 1000
                RequestConfiguration =                // config and customize request headers
                {
                    Accept                 = "*/*",
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                    CookieContainer        = new CookieContainer(),    // Add your cookies
                    Headers               = new WebHeaderCollection(), // Add your custom headers
                    KeepAlive             = false,
                    ProtocolVersion       = HttpVersion.Version11,     // Default value is HTTP 1.1
                    UseDefaultCredentials = false,
                    UserAgent             = $"DownloaderSample/{Assembly.GetExecutingAssembly().GetName().Version.ToString(3)}"
                }
            };

            DownloadService downloader = new DownloadService(downloadOpt);

            downloader.DownloadStarted         += OnDowloadStarted;
            downloader.DownloadFileCompleted   += OnDownloadFileCompleted;
            downloader.DownloadProgressChanged += OnDowloadProgresChanged;

            await downloader.DownloadFileTaskAsync(url, fileName);


            void OnDowloadStarted(object sender, DownloadStartedEventArgs e)
            {
                UCLogsViewModel.TextLogs.Value += "\nDowload started";
            }

            void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
            {
                DowloadInfoUpdater.OnStopUpdateInfo();
            }

            void OnDowloadProgresChanged(object sender, DownloadProgressChangedEventArgs e)
            {
                DowloadInfoUpdater.OnNewUpdateInfo(e);
            }
        }
Пример #22
0
        public void DownloadProgressChangedTest()
        {
            // arrange
            var downloader           = new DownloadService(Config);
            var progressChangedCount = (int)Math.Ceiling((double)DownloadTestHelper.FileSize16Kb / Config.BufferBlockSize);
            var progressCounter      = 0;

            downloader.DownloadProgressChanged += (s, e) => Interlocked.Increment(ref progressCounter);

            // act
            downloader.DownloadFileTaskAsync(DownloadTestHelper.File16KbUrl).Wait();

            // assert
            // Note: some times received bytes on read stream method was less than block size!
            Assert.IsTrue(progressChangedCount <= progressCounter);
        }
Пример #23
0
        public void Download16KbWithoutFilenameTest()
        {
            // arrange
            var downloader = new DownloadService(Config);

            // act
            downloader.DownloadFileTaskAsync(DownloadTestHelper.File16KbUrl,
                                             new DirectoryInfo(DownloadTestHelper.TempDirectory)).Wait();

            // assert
            Assert.IsTrue(File.Exists(downloader.Package.FileName));
            Assert.IsTrue(downloader.Package.FileName.StartsWith(DownloadTestHelper.TempDirectory));
            Assert.AreEqual(DownloadTestHelper.FileSize16Kb, downloader.Package.TotalFileSize);
            Assert.IsTrue(DownloadTestHelper.AreEqual(DownloadTestHelper.File16Kb, File.OpenRead(downloader.Package.FileName)));

            File.Delete(downloader.Package.FileName);
        }
        public override async Task StartDownloadAsync(string url, FileInfo outFile)
        {
            _dlService = new DownloadService(_downloadOpt);

            _dlService.DownloadProgressChanged += (sender, args) =>
            {
                OnProgressChanged(new AcquisitionProgress
                {
                    BytesPerSecondSpeed = (long)args.BytesPerSecondSpeed,
                    Progress            = args.ReceivedBytesSize
                });
            };

            _dlService.DownloadFileCompleted += (sender, args) =>
            {
                if (args.Error != null)
                {
                    Log.Error(args.Error, "[WEB] Download failed for {0} with reason {1}", url, args.Error);

                    // If we cancel downloads, we don't want to see an error message
                    if (args.Error is OperationCanceledException)
                    {
                        OnComplete(AcquisitionResult.Cancelled);
                        return;
                    }

                    OnComplete(AcquisitionResult.Error);
                    return;
                }

                if (args.Cancelled)
                {
                    Log.Error("[WEB] Download cancelled for {0} with reason {1}", url, args.Error);

                    /*
                     * Cancellation should not produce an error message, since it is always triggered by another error or the user.
                     */
                    OnComplete(AcquisitionResult.Cancelled);
                    return;
                }

                OnComplete(AcquisitionResult.Success);
            };

            await _dlService.DownloadFileTaskAsync(url, outFile.FullName);
        }
Пример #25
0
        public void DownloadProgressChangedTest()
        {
            // arrange
            var downloader           = new DownloadService(Config);
            var progressChangedCount = (int)Math.Ceiling((double)DummyFileHelper.FileSize16Kb / Config.BufferBlockSize);
            var progressCounter      = 0;

            downloader.DownloadProgressChanged += (s, e) => Interlocked.Increment(ref progressCounter);

            // act
            downloader.DownloadFileTaskAsync(DummyFileHelper.GetFileUrl(DummyFileHelper.FileSize16Kb)).Wait();

            // assert
            // Note: some times received bytes on read stream method was less than block size!
            Assert.IsTrue(progressChangedCount <= progressCounter);
            Assert.AreEqual(100.0, downloader.Package.SaveProgress);
            Assert.IsTrue(downloader.Package.IsSaveComplete);
            Assert.IsFalse(downloader.Package.IsSaving);
        }
Пример #26
0
        public void SpeedLimitTest()
        {
            // arrange
            double averageSpeed    = 0;
            var    progressCounter = 0;

            Config.MaximumBytesPerSecond = 128; // 128 Byte/s
            var downloader = new DownloadService(Config);

            downloader.DownloadProgressChanged += (s, e) => {
                averageSpeed = ((averageSpeed * progressCounter) + e.BytesPerSecondSpeed) / (progressCounter + 1);
                progressCounter++;
            };

            // act
            downloader.DownloadFileTaskAsync(DownloadTestHelper.File1KbUrl).Wait();

            // assert
            Assert.AreEqual(DownloadTestHelper.FileSize1Kb, downloader.Package.TotalFileSize);
            Assert.IsTrue(averageSpeed <= Config.MaximumBytesPerSecond, $"Average Speed: {averageSpeed} , Speed Limit: {Config.MaximumBytesPerSecond}");
        }
Пример #27
0
        /// <summary>
        /// Download MSIX from Azure
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            btnUpdate.IsEnabled = false;
            bool isConnected = ApplicationHelper.IsConnectedToInternet();

            if (isConnected)
            {
                txtStatus.Text          = "Downloading Database...";
                txtMSIXStatus.Text      = string.Empty;
                prgMSIX.Value           = 0;
                prgMSIX.Visibility      = Visibility.Visible;
                prgMSIX.IsIndeterminate = false;
                var downloader = new DownloadService();
                downloader.DownloadProgressChanged += Downloader_DownloadProgressChanged;
                downloader.DownloadFileCompleted   += Downloader_DownloadFileCompleted;
                await downloader.DownloadFileTaskAsync(Consts.MSIXSourceUrl, new DirectoryInfo(Consts.MSIXPath));
            }
            else
            {
                CreateInfoBar("Network UnAvailable", "Unable to connect to the Internet", panel, Severity.Error);
                btnUpdate.IsEnabled = true;
            }
        }
Пример #28
0
    public static async Task <string> MultiThreadDownloadFileAsync(
        this string url,
        string tempDir,
        string fileName = ""
        )
    {
        var throttleDispatcher = new ThrottleDispatcher(2000);

        var pathFileName = Path.GetFileName(url);

        if (fileName.IsNotNullOrEmpty())
        {
            pathFileName = fileName;
        }

        var paths = Path.Combine(
            "Storage/Caches/",
            tempDir,
            pathFileName
            );

        var downloadOpt = new DownloadConfiguration()
        {
            ChunkCount            = 8,
            ParallelDownload      = true,
            MaxTryAgainOnFailover = 10,
            OnTheFlyDownload      = false,
            RequestConfiguration  = // config and customize request headers
            {
                Accept                 = "*/*",
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                CookieContainer        = new CookieContainer(),    // Add your cookies
                Headers               = new WebHeaderCollection(), // Add your custom headers
                KeepAlive             = false,                     // default value is false
                ProtocolVersion       = HttpVersion.Version11,     // Default value is HTTP 1.1
                UseDefaultCredentials = false,
                UserAgent             = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.53"
            }
        };

        var downloader = new DownloadService(downloadOpt);

        downloader.DownloadStarted += (
            sender,
            args
            ) => {
            Log.Information(
                "Downloading File. FileName: {FileName}, Size: {Size}",
                args.FileName,
                args.TotalBytesToReceive
                );
        };

        downloader.DownloadProgressChanged += (
            sender,
            args
            ) => {
            var downloadService = sender as DownloadService;
            if (downloadService == null)
            {
                return;
            }

            var downloadPackage = downloadService.Package;
            throttleDispatcher.Throttle(
                () => {
                Log.Debug(
                    "Downloading URL: {FileName}. {Run}/{Size} - {Speed} ({Progress}%)",
                    downloadPackage.Address,
                    downloadPackage.ReceivedBytesSize.SizeFormat(),
                    downloadPackage.TotalFileSize.SizeFormat(),
                    args.AverageBytesPerSecondSpeed.SizeFormat("/s"),
                    args.ProgressPercentage.ToString("N2")
                    );
            }
                );
        };

        downloader.DownloadFileCompleted += (
            sender,
            args
            ) => {
            var downloadService = sender as DownloadService;
            if (downloadService == null)
            {
                return;
            }

            var downloadPackage = downloadService.Package;

            Log.Information(
                "Download completed. Url: {Address}. Size: {Size}",
                downloadPackage.Address,
                downloadPackage.TotalFileSize.SizeFormat()
                );
        };

        await downloader.DownloadFileTaskAsync(url, paths);

        return(paths);
    }
Пример #29
0
        private async Task DownloadPatchAsync(PatchDownload download, int index)
        {
            var outFile = GetPatchFile(download.Patch);

            Log.Information("Downloading patch {0} at {1} to {2}", download.Patch.VersionId, download.Patch.Url, outFile.FullName);

            Actives[index] = download;

            if (outFile.Exists && CheckPatchValidity(download.Patch, outFile) == HashCheckResult.Pass)
            {
                download.State    = PatchState.Downloaded;
                Slots[index]      = SlotState.Done;
                Progresses[index] = download.Patch.Length;
                return;
            }

            var dlService = new DownloadService(_downloadOpt);

            dlService.DownloadProgressChanged += (sender, args) =>
            {
                Progresses[index] = args.ReceivedBytesSize;
                Speeds[index]     = args.BytesPerSecondSpeed;
            };

            dlService.DownloadFileCompleted += (sender, args) =>
            {
                if (args.Error != null)
                {
                    Log.Error(args.Error, "Download failed for {0} with reason {1}", download.Patch.VersionId, args.Error);

                    // If we cancel downloads, we don't want to see an error message
                    if (args.Error is OperationCanceledException)
                    {
                        return;
                    }

                    CancelAllDownloads();
                    CustomMessageBox.Show(string.Format(Loc.Localize("PatchManDlFailure", "XIVLauncher could not verify the downloaded game files.\n\nThis usually indicates a problem with your internet connection.\nIf this error occurs again, try using a VPN set to Japan.\n\nContext: {0}\n{1}"), "Problem", download.Patch.VersionId), "XIVLauncher Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Environment.Exit(0);
                    return;
                }

                if (args.Cancelled)
                {
                    Log.Error("Download cancelled for {0} with reason {1}", download.Patch.VersionId, args.Error);

                    /*
                     * Cancellation should not produce an error message, since it is always triggered by another error or the user.
                     *
                     * CancelAllDownloads();
                     * CustomMessageBox.Show(string.Format(Loc.Localize("PatchManDlFailure", "XIVLauncher could not verify the downloaded game files.\n\nThis usually indicates a problem with your internet connection.\nIf this error occurs again, try using a VPN set to Japan.\n\nContext: {0}\n{1}"), "Cancelled", download.Patch.VersionId), "XIVLauncher Error", MessageBoxButton.OK, MessageBoxImage.Error);
                     * Environment.Exit(0);
                     */
                    return;
                }

                var checkResult = CheckPatchValidity(download.Patch, outFile);

                // Indicate "Checking..."
                Slots[index] = SlotState.Checking;

                // Let's just bail for now, need better handling of this later
                if (checkResult != HashCheckResult.Pass)
                {
                    CancelAllDownloads();
                    Log.Error("IsHashCheckPass failed for {0} after DL", download.Patch.VersionId);
                    CustomMessageBox.Show(string.Format(Loc.Localize("PatchManDlFailure", "XIVLauncher could not verify the downloaded game files.\n\nThis usually indicates a problem with your internet connection.\nIf this error occurs again, try using a VPN set to Japan.\n\nContext: {0}\n{1}"), $"IsHashCheckPass({checkResult})", download.Patch.VersionId), "XIVLauncher Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    outFile.Delete();
                    Environment.Exit(0);
                    return;
                }

                download.State    = PatchState.Downloaded;
                Slots[index]      = SlotState.Done;
                Progresses[index] = 0;
                Speeds[index]     = 0;

                Log.Information("Patch at {0} downloaded completely", download.Patch.Url);

                this.CheckIsDone();
            };

            DownloadServices[index] = dlService;

            await dlService.DownloadFileTaskAsync(download.Patch.Url, outFile.FullName);
        }
Пример #30
0
        public async void DownloadSubtitle()
        {
            ISubtitleDownloadPage.Instance.CloseStatus();

            if (GeneralHelper.IsNetworkAvailable())
            {
                if (!Helper.Settings.IsIDMEnabled)
                {
                    DownloadButton.IsEnabled       = false;
                    ProgressStatus.IsIndeterminate = true;
                    ProgressStatus.Visibility      = Visibility.Visible;
                    ProgressStatus.Value           = 0;
                }

                try
                {
                    var web = new HtmlWeb();
                    var doc = await web.LoadFromWebAsync(Link);

                    if (doc != null)
                    {
                        var downloadLink = Constants.ISubtitleBaseUrl + doc?.DocumentNode
                                           ?.SelectSingleNode("//div[@class='col-lg-16 col-md-24 col-sm-16']//a")?.Attributes["href"]
                                           ?.Value;

                        if (!string.IsNullOrEmpty(downloadLink))
                        {
                            // if luanched from ContextMenu set location next to the movie file
                            if (!string.IsNullOrEmpty(App.StartUpArguments.Name))
                            {
                                location = App.StartUpArguments.Path;
                            }
                            else
                            {
                                // get location from config
                                location = Helper.Settings.DefaultDownloadLocation;

                                // get location from FolderPicker
                                if (Helper.Settings.IsAskLocationEnabled)
                                {
                                    var path = await Helper.OpenAndSelectFolder();

                                    if (!string.IsNullOrEmpty(path))
                                    {
                                        location = path;
                                    }
                                }
                            }

                            if (!Helper.Settings.IsIDMEnabled)
                            {
                                downloadLink = await Helper.GetRedirectedUrl(downloadLink);

                                Debug.WriteLine(downloadLink);
                                var downloader = new DownloadService();
                                downloader.DownloadProgressChanged += Downloader_DownloadProgressChanged;
                                downloader.DownloadFileCompleted   += Downloader_DownloadFileCompleted;
                                await downloader.DownloadFileTaskAsync(downloadLink, new DirectoryInfo(location));
                            }
                            else
                            {
                                ProgressStatus.Visibility = Visibility.Collapsed;
                                Helper.OpenLinkWithIDM(downloadLink);
                            }
                        }
                    }
                }
                catch (NullReferenceException ex)
                {
                    ISubtitleDownloadPage.Instance.ShowStatus(null, ex.Message, InfoBarSeverity.Error);
                    DownloadButton.IsEnabled = true;
                }
                catch (UnauthorizedAccessException ex)
                {
                    ISubtitleDownloadPage.Instance.ShowStatus(null, ex.Message, InfoBarSeverity.Error);
                    DownloadButton.IsEnabled = true;
                }
                catch (NotSupportedException)
                {
                }
                catch (ArgumentException)
                {
                }
                catch (Exception ex)
                {
                    ISubtitleDownloadPage.Instance.ShowStatus(null, ex.Message, InfoBarSeverity.Error);
                    DownloadButton.IsEnabled = true;
                }
                finally
                {
                    ProgressStatus.Visibility = Visibility.Collapsed;
                    DownloadButton.IsEnabled  = true;
                }
            }
            else
            {
                ISubtitleDownloadPage.Instance.ShowStatus(Constants.InternetIsNotAvailableTitle, Constants.InternetIsNotAvailable, InfoBarSeverity.Error);
            }
        }