/// <summary> /// start running the task - the task is started in the background and the method will return /// </summary> public void Start(object state) { lock (_lock) { if (SyncItem == null) { throw new DownloaderException("SyncItem has not been set before calling the downloader"); } if (_started || _client != null) { throw new DownloaderException("Cannot start the task twice"); } _started = true; _progressPercentage = 0; _bytesDownloaded = 0; _stopWatch = new Stopwatch(); _stopWatch.Start(); _client = _webClientFactory.CreateWebClient(); _client.ProgressUpdate += new EventHandler <ProgressEventArgs>(ClientProgressUpdate); _client.DownloadFileCompleted += new AsyncCompletedEventHandler(ClientDownloadFileCompleted); CreateFolderIfNeeded(); _client.DownloadFileAsync(SyncItem.EpisodeUrl, GetDownloadFilename(), SyncItem); } }
public async Task DownloadWantedEpisodes() { var episodesToDownload = _service.GetWantedEpisodes(); foreach (var episode in episodesToDownload) { var search = BuildSearchQuery(episode); var torrent = _searchProvider.GetTorrent(search); if (torrent == null) { _logger.Info($"No torrent found for {search}"); _analyticsService.ReportEvent(AnalyticEvent.SearchFailed); continue; } try { var torrentFileName = $"{_settings.TorrentWatchFolder}{torrent.Name}.torrent"; await _webClient.DownloadFileAsync(torrent.DownloadUrl, torrentFileName); } catch (Exception ex) { _logger.Error(ex); } episode.DownloadStatus = "DOWN"; _service.AddOrUpdate(episode); _logger.Debug($"Updating {episode.SeriesName} s{episode.Season:D2}e{episode.EpisodeNumber:D2} as Downloaded"); } _service.SaveChanges(); }
public static void DownloadFileSync(this IWebClient client, Uri address, string filename, CancellationToken cancellationToken) { // Events are only fired when downloading asynchronously with DownloadFileAsync. // This method allows for synchronous downloads while still firing events. // Based on the solution given here: https://stackoverflow.com/a/25834736 (user195275) object mutex = new object(); bool downloadCancelled = false; void handleDownloadComplete(object sender, AsyncCompletedEventArgs e) { downloadCancelled = e.Cancelled; lock (e.UserState) Monitor.Pulse(e.UserState); } client.DownloadFileCompleted += handleDownloadComplete; try { lock (mutex) { using (cancellationToken.Register(() => client.CancelAsync())) { client.DownloadFileAsync(address, filename, mutex); Monitor.Wait(mutex); } } } finally { client.DownloadFileCompleted -= handleDownloadComplete; } if (downloadCancelled) { throw new WebException(Properties.ExceptionMessages.TheRequestWasCancelled, WebExceptionStatus.RequestCanceled); } }
public static void DownloadFileAsync(this IWebClient client, Uri address) { client.DownloadFileAsync(address, PathUtilities.GetFilename(address.AbsoluteUri)); }