Beispiel #1
0
 /// <summary>
 /// 销毁对象,会停止所有的下载
 /// </summary>
 public void Dispose()
 {
     if (_httpDownloader != null)
     {
         _httpDownloader.onProgress -= OnDownloadProgress;
         _httpDownloader.onComplete -= OnDownloadComplete;
         _httpDownloader.Cancel();
         _httpDownloader = null;
         if (false == _isDone)
         {
             SetError("Canceled");
             _isDone = true;
         }
     }
 }
Beispiel #2
0
        public void TestContinue()
        {
            var zipUrl = "http://sjres.icantw.com/g1-resources-package/trunk/g1.resources.trunk.1.3.0.3.zip";
//            var zipUrl = "http://dzp79b220mp4w.cloudfront.net/g1-resources-package/trunk/g1.resources.trunk.1.4.0.0.zip"; // very slow, 弱网络
            var savePath = "test_continue.zip";

            if (File.Exists(savePath))
            {
                File.Delete(savePath);
            }

            var downloader = new HttpDownloader(zipUrl, savePath, true);

            downloader.Start();

            Thread.Sleep(2000);
            downloader.Cancel();
            Console.WriteLine("Canceled! Now : {0}B/{1}B, {2}%", downloader.DownloadedSize, downloader.TotalSize,
                              downloader.Progress * 100d);


            Assert.True(File.Exists(savePath + ".download"));
            Assert.True(!File.Exists(savePath));


            Console.WriteLine("Start continue downloader...");
            downloader = new HttpDownloader(zipUrl, savePath, true);
            downloader.Start();

            while (!downloader.IsFinished)
            {
                Console.WriteLine("Continue! Now : {0}B/{1}B, {2}%", downloader.DownloadedSize, downloader.TotalSize,
                                  downloader.Progress * 100d);
                Thread.Sleep(50);
            }

            Console.WriteLine("Finish! Now : {0}B/{1}B, {2}%", downloader.DownloadedSize, downloader.TotalSize,
                              downloader.Progress * 100d);
            Assert.True(!File.Exists(savePath + ".download"));
            Assert.True(File.Exists(savePath));
        }
Beispiel #3
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            MinecraftVersion version = _verList.SelectedItem as MinecraftVersion;

            if (version == null)
            {
                return;
            }

            ViewModel.isWorking = true;

            try
            {
                string jsonPath = CoreManager.CoreMCL.Core.GameRootPath + "\\" + version.GetJsonPath();
                using (HttpClient client = new HttpClient())
                {
                    FileInfo file = new FileInfo(jsonPath);
                    if (!file.Directory.Exists)
                    {
                        file.Directory.Create();
                    }
                    File.Create(jsonPath).Dispose();
                    File.WriteAllText(jsonPath, await client.GetStringAsync(version.url));

                    string jarPath;
                    KMCCC.Launcher.Version kver = CoreManager.CoreMCL.Core.GetVersion(version.id);
                    jarPath = CoreManager.CoreMCL.Core.GameRootPath + "\\" + version.GetJarPath();

                    file = new FileInfo(jarPath);
                    if (!file.Directory.Exists)
                    {
                        file.Directory.Create();
                    }
                    File.Create(jarPath);

                    HttpDownloader downloader         = new HttpDownloader(kver.Downloads.Client.Url, jarPath);
                    var            progressController = await MainWindow.Current.ShowProgressAsync("正在下载:  " + kver.Id, "", true, DefaultDialogSettings);

                    downloader.DownloadProgressChanged += async delegate
                    {
                        if (downloader.ProgressInPercent == 100)
                        {
                            await progressController.CloseAsync();
                        }
                        else
                        {
                            progressController.SetProgress(downloader.ProgressInPercent / 100);
                            progressController.SetMessage("下载速度: " + GetDownloadSpeedFriendlyText(downloader));
                        }
                    };
                    progressController.Canceled += delegate
                    {
                        if (downloader.State != DownloadState.Completed)
                        {
                            downloader.Cancel();
                        }
                    };
                    downloader.Start();
                }
            }
            catch (IOException ex)
            {
                await MainWindow.Current.ShowMessageAsync("下载失败", ex.Message + ex.StackTrace);
            }
            catch (HttpRequestException ex)
            {
                await MainWindow.Current.ShowMessageAsync("下载失败", ex.Message + ex.StackTrace);
            }

            ViewModel.isWorking = false;
        }
Beispiel #4
0
        private async Task TestWithSize(long size)
        {
            var rd          = new Random((int)(DateTime.Now.Ticks % int.MaxValue));
            var targetBytes = new byte[size];

            rd.NextBytes(targetBytes);
            int port = 8080;

            using (var server = new FakeHttpServer(port, targetBytes))
            {
                var folderProvider = new FakeFolderProvider();
                var cacheProvider  = new FakeCacheProvider();
                var bufferProvider = new FakeBufferProvider();
                var downloader     = new HttpDownloader(
                    new DownloadTask(
                        "test-task",
                        new HttpTarget(
                            new Uri($"http://localhost:{port}/"),
                            "test-file"
                            ),
                        "test-destination-file",
                        "test-destination-folder",
                        DateTime.Now,
                        false
                        ),
                    folderProvider,
                    cacheProvider,
                    bufferProvider
                    );

                downloader.Start();

                TimeSpan cancellationStep = TimeSpan.FromSeconds(1);
                CancellationTokenSource completeTokenSource = new CancellationTokenSource();

                downloader.StatusChanged += async(sender, newStatus) =>
                {
                    switch (downloader.Status)
                    {
                    case DownloaderStatus.Running:
                        var step = cancellationStep;
                        cancellationStep *= 2;
                        await Task.Delay(step);

                        if (downloader.CanCancel)
                        {
                            downloader.Cancel();
                        }
                        break;

                    case DownloaderStatus.Ready:
                        downloader.Start();
                        break;

                    case DownloaderStatus.Completed:
                        completeTokenSource.Cancel();
                        break;

                    case DownloaderStatus.Pending:
                        break;

                    case DownloaderStatus.Disposed:
                        break;

                    case DownloaderStatus.Error:
                        throw downloader.Errors.First();

                    default:
                        throw new Exception($"unknown status {downloader.Status}");
                    }
                };

                try
                {
                    await Task.Delay(TimeSpan.FromMinutes(5), completeTokenSource.Token);
                }
                catch (TaskCanceledException) { }

                Assert.AreEqual(downloader.Status, DownloaderStatus.Completed);

                if (downloader.Result is StorageFile file)
                {
                    using (var istream = await file.OpenReadAsync())
                    {
                        using (var ostream = new MemoryStream(targetBytes))
                        {
                            Assert.IsTrue(istream.AsStream().Compare(ostream));
                        }
                    }
                }

                await downloader.Result.DeleteAsync();

                await downloader.DisposeAsync();
            }
        }