Example #1
0
        private async Task <string> DownloadAsync(DownloadData download, string path, string targetPath, string tempPath, CancellationToken cancellationToken)
        {
            var fileName = Path.GetFileName(targetPath);
            var filePath = Path.Combine(tempPath, fileName);

            if (File.Exists(filePath))
            {
                Logger.LogTrace("Skipping {0}", filePath);
                return(filePath);
            }

            SetTitle(nameof(Resources.Download_Downloading_Text));
            ViewModel.FileName = Path.GetFileName(path);
            TryParseSize(download.Size, out int size);
            ViewModel.ProgressMaximum = size;

            try
            {
                return(await DownloadService.DownloadAsync(
                           baseUri : download.BaseUri,
                           path : path,
                           filePath : filePath,
                           cancellationToken : cancellationToken));
            }
            catch (TaskCanceledException ex)
            {
                Logger.LogError(0, ex, "Canceled");
                //cts = null;
                return(null);
            }
        }
Example #2
0
        /// <summary>
        ///     Convert class into parameters to pass to youtube-dl process, then create and run process.
        ///     Also handle output from process.
        /// </summary>
        /// <param name="videoUrl">URL of video to download</param>
        public async Task DownloadAsync(string videoUrl)
        {
            await this.semaphore.WaitAsync();

            await DownloadService.DownloadAsync(this, videoUrl);

            this.semaphore.Release();
        }
Example #3
0
        /// <summary>
        ///     Convert class into parameters to pass to youtube-dl process, then create and run process.
        ///     Also handle output from process.
        /// </summary>
        public async Task DownloadAsync()
        {
            await this.semaphore.WaitAsync();

            await DownloadService.DownloadAsync(this, downloadTokenSource.Token);

            this.semaphore.Release();
        }
Example #4
0
        /// <summary>
        ///     Convert class into parameters to pass to youtube-dl process, then create and run process.
        ///     Also handle output from process.
        /// </summary>
        public async Task DownloadAsync()
        {
            await this.semaphore.WaitAsync();

            await DownloadService.DownloadAsync(this);

            this.semaphore.Release();
        }
Example #5
0
        /// <summary>
        ///     Convert class into parameters to pass to youtube-dl process, then create and run process.
        ///     Also handle output from process.
        /// </summary>
        /// <param name="videoUrl">URL of video to download</param>
        public async Task DownloadAsync(string videoUrl)
        {
            await this.semaphore.WaitAsync();

            await this.UpdateExecutable();

            await DownloadService.DownloadAsync(this, videoUrl, downloadTokenSource.Token);

            this.semaphore.Release();
        }
Example #6
0
 public void throws_without_saving_file_when_connectivity_failed()
 {
     using (var messageHandler = new FakeHttpMessageHandler(new HttpRequestException()))
         using (var httpClient = new HttpClient(messageHandler))
         {
             var service = new DownloadService(httpClient, _fileSystem);
             Assert.ThrowsAsync <DownloadFailureException>(() => service.DownloadAsync(GoodUrl, Destination)).Wait();
         }
     Assert.False(_fileSystem.FileExists(Destination), "saves file on disk");
 }
Example #7
0
        public static async Task HardWork(int item)
        {
            var content = await DownloadService.DownloadAsync(Address);

            var value = Random.Next(1, 10);

            if (value > 6)
            {
                throw new Exception($"Processing item \"{item}\" failed cause random value is {value}. Test data {content.Substring(0, 50)}");
            }
        }
        public async Task Test_That_DownloadService_Returns_Null_If_Api_Error()
        {
            var httpClientFactory = new FakeHttpClientFactory
            {
                ExpectedResponseCode = HttpStatusCode.InternalServerError, ExpectedResponse = ""
            };

            var downloadService = new DownloadService(httpClientFactory);
            var downloadedFiles = await downloadService.DownloadAsync(new[] { "des moines" });

            Assert.AreEqual(1, downloadedFiles.Count());
            Assert.IsNull(downloadedFiles.First());
        }
Example #9
0
 public void throws_without_saving_file_when_got_return_code_else_than_2XX()
 {
     if (!RunningOnWindows)
     {
         ReportSkip(nameof(throws_without_saving_file_when_got_return_code_else_than_2XX));
         return;
     }
     using (var messageHandler = new FakeHttpMessageHandler(_messages))
         using (var httpClient = new HttpClient(messageHandler))
         {
             var service = new DownloadService(httpClient, _fileSystem);
             Assert.ThrowsAsync <DownloadFailureException>(() => service.DownloadAsync(BadUrl, Destination)).Wait();
         }
     Assert.False(_fileSystem.FileExists(Destination), "saves file on disk");
 }
Example #10
0
 public void Start()
 {
     Result      = "等待";
     IsCompleted = false;
     _client     = new WebClient();
     _cancellationTokenSource = new CancellationTokenSource();
     _downloadProgress        = new DownloadProgress
     {
         FilePath = _filePath,
         Url      = _url,
         No       = _no,
         Type     = Type
     };
     _downloadProgress.DownloadReport += GetReport;
     Task.Run(async() =>
     {
         await _downloadService.DownloadAsync(_client, _downloadProgress, _cancellationTokenSource.Token);
         _downloadProgress.DownloadReport -= GetReport;
     });
 }
Example #11
0
        public void downloads_directly_from_url_to_file()
        {
            if (!RunningOnWindows)
            {
                ReportSkip(nameof(downloads_directly_from_url_to_file));
                return;
            }
            using (var messageHandler = new FakeHttpMessageHandler(_messages))
                using (var httpClient = new HttpClient(messageHandler))
                {
                    var service = new DownloadService(httpClient, _fileSystem);
                    service.DownloadAsync(GoodUrl, Destination).Wait();
                }

            Assert.True(_fileSystem.FileExists(Destination), "file is missing");

            var fileContent = _fileSystem.File.ReadAllText(Destination);

            Assert.Equal(fileContent, ResponseData);
        }
        public async Task Test_That_DownloadService_DownloadsFile_For_City()
        {
            var apiResponseJsonFilename =
                Path.Combine("unit", "JsonFiles", "CompleteApiResponseForCity.json");

            var httpClientFactory = new FakeHttpClientFactory
            {
                ExpectedResponseCode = HttpStatusCode.OK,
                ExpectedResponse     = await File.ReadAllTextAsync(apiResponseJsonFilename)
            };

            var downloadService = new DownloadService(httpClientFactory);
            var downloadedFiles = await downloadService.DownloadAsync(new[] { "des moines" });

            Assert.AreEqual(1, downloadedFiles.Count());

            foreach (var downloadedFile in downloadedFiles)
            {
                File.Delete(downloadedFile);
            }
        }
Example #13
0
        public async Task DownloadAsync()
        {
            decimal minutesElapsed = await _download.DownloadAsync();

            await ReplyAsync($"Download completed in {minutesElapsed:F} minutes!");
        }
Example #14
0
        public void Start()
        {
            if (!CanStart)
            {
                return;
            }

            IsActive     = true;
            IsSuccessful = false;
            IsCanceled   = false;
            IsFailed     = false;

            Task.Run(async() =>
            {
                _cancellationTokenSource = new CancellationTokenSource();
                ProgressOperation        = ProgressManager?.CreateOperation();

                try
                {
                    // If download option is not set - get the best download option
                    VideoOption ??= await _downloadService.TryGetBestVideoDownloadOptionAsync(
                        Video.Id,
                        Format,
                        QualityPreference
                        );

                    // It's possible that video has no streams
                    if (VideoOption == null)
                    {
                        throw new InvalidOperationException($"Video '{Video.Id}' contains no streams.");
                    }

                    await _downloadService.DownloadAsync(
                        VideoOption,
                        SubtitleOption,
                        FilePath,
                        ProgressOperation,
                        _cancellationTokenSource.Token
                        );

                    if (_settingsService.ShouldInjectTags)
                    {
                        await _taggingService.InjectTagsAsync(
                            Video,
                            Format,
                            FilePath,
                            _cancellationTokenSource.Token
                            );
                    }

                    IsSuccessful = true;
                }
                catch (OperationCanceledException)
                {
                    IsCanceled = true;
                }
                catch (Exception ex)
                {
                    IsFailed = true;

                    // Short error message for expected errors, full for unexpected
                    FailReason = ex is YoutubeExplodeException
                        ? ex.Message
                        : ex.ToString();
                }
                finally
                {
                    IsActive = false;
                    _cancellationTokenSource?.Dispose();
                    _cancellationTokenSource = null;
                    ProgressOperation?.Dispose();
                }
            });
        }
Example #15
0
 private async Task DownloadAsync(Server server)
 {
     await _downloadService.DownloadAsync(server);
 }