public async void Download(string path, AsyncCompletedEventHandler progress) { if (FileName == "") { return; } //Org, repo, file Using match index to var rx = new Regex(@"({<owner>})({<repo>})({<release>})", RegexOptions.Compiled | RegexOptions.IgnoreCase); var matches = rx.Matches(Url); // Use github latest foreach (Match match in matches) { GroupCollection collection = match.Groups; var owner = collection["owner"].Value; var repo = collection["repo"].Value; var releasematch = collection["release"].Value; var release = await github.Repository.Release.GetLatest(owner, repo); foreach (var asset in release.Assets) { if (!asset.Name.Contains(releasematch) || matches.Count == 0) { continue; } FileName = asset.Name; Url = asset.BrowserDownloadUrl; } } if (File.Exists($"{path}\\{FileName}") && IsValid(path)) { progress?.Invoke(null, null); return; } if (Url.StartsWith("local:")) { CopyLocal(Url.ToString().Replace("local:", ""), path); progress?.Invoke(null, null); return; } await DownloadHttp(path, progress); }
public async Task <bool> DownloadPodcastAsync( IPodcastEpisode episode, string directoryOut, AsyncCompletedEventHandler completedDownloadEvent = null, DownloadProgressChangedEventHandler downloadProgressChangedEvent = null, bool downloadInsertions = false) { try { if (string.IsNullOrEmpty(directoryOut)) { return(false); } if (!_fileHelper.DirectoryExists(directoryOut)) { _fileHelper.CreateDirectory(directoryOut); } if (episode is Episode naoOuvoEpisode && _fileHelper.DirectoryExists(directoryOut)) { var archiveName = naoOuvoEpisode.Url.Substring(naoOuvoEpisode.Url.LastIndexOf("/") + 1); if (currentFilesDownloading.Any(name => name.Equals(archiveName, StringComparison.CurrentCultureIgnoreCase))) { return(false); } var httpclient = new HttpClient() { Timeout = (new TimeSpan(5, 0, 0)) }; var client = new WebApiClient(httpclient, _fileHelper); currentFilesDownloading.Add(archiveName); directoryOut = directoryOut.EndsWith("\\") ? directoryOut : directoryOut + "\\"; if (downloadInsertions) { await DownloadNaoOuvoInsertions(naoOuvoEpisode, directoryOut, archiveName); } var filePath = string.Concat(directoryOut, archiveName); await client.GetAsync(naoOuvoEpisode.Url, filePath); currentFilesDownloading.Remove(archiveName); completedDownloadEvent?.Invoke(null, null); return(true); } } catch (Exception ex) { Debug.WriteLine($"Error on NaoOuvo download.\n\nDetails{ex.Message}"); return(false); } return(false); }
private async Task DownloadHttp(string path, AsyncCompletedEventHandler handler) { var noCancel = new CancellationTokenSource(); using (var client = new HttpClientDownloadWithProgress(Url, $"{path}\\{FileName}")) { client.ProgressChanged += (totalFileSize, totalBytesDownloaded, progressPercentage) => { if (progressPercentage == null) { return; } if ((int)progressPercentage == 100) { handler?.Invoke(null, null); } }; await client.StartDownload(noCancel.Token); } }
/// <summary> /// Add a new file transfer (either copy/move) request. /// </summary> /// <param name="fileTransferInfo"> /// The file Transfer Info. /// </param> /// <param name="sendFileCompletedCallback"> /// The send File Completed Callback. /// </param> /// <param name="uri"> /// The uri. /// </param> /// <param name="friendlyName"> /// The friendly Name. /// </param> private void AddNewFileTransfer(FileTransferInformation fileTransferInfo, AsyncCompletedEventHandler sendFileCompletedCallback, Uri uri, string friendlyName) { var context = fileTransferInfo.Context; Debug.Assert( context != null, "DataCollectionManager.AddNewFileTransfer: FileDataHeaderMessage with null context."); var testCaseId = fileTransferInfo.Context.HasTestCase ? fileTransferInfo.Context.TestExecId.Id.ToString() : string.Empty; var directoryPath = Path.Combine( this.SessionOutputDirectory, testCaseId); var localFilePath = Path.Combine(directoryPath, Path.GetFileName(fileTransferInfo.FileName)); var task = Task.Factory.StartNew( () => { Validate(fileTransferInfo, localFilePath); if (this.cancellationTokenSource.Token.IsCancellationRequested) { this.cancellationTokenSource.Token.ThrowIfCancellationRequested(); } try { if (fileTransferInfo.PerformCleanup) { if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("DataCollectionAttachmentManager.AddNewFileTransfer : Moving file {0} to {1}", fileTransferInfo.FileName, localFilePath); } this.fileHelper.MoveFile(fileTransferInfo.FileName, localFilePath); if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("DataCollectionAttachmentManager.AddNewFileTransfer : Moved file {0} to {1}", fileTransferInfo.FileName, localFilePath); } } else { if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("DataCollectionAttachmentManager.AddNewFileTransfer : Copying file {0} to {1}", fileTransferInfo.FileName, localFilePath); } this.fileHelper.CopyFile(fileTransferInfo.FileName, localFilePath); if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("DataCollectionAttachmentManager.AddNewFileTransfer : Copied file {0} to {1}", fileTransferInfo.FileName, localFilePath); } } } catch (Exception ex) { this.LogError( ex.ToString(), uri, friendlyName, Guid.Parse(testCaseId)); throw; } }, this.cancellationTokenSource.Token); var continuationTask = task.ContinueWith( (t) => { try { if (t.Exception == null) { lock (attachmentTaskLock) { this.AttachmentSets[fileTransferInfo.Context][uri].Attachments.Add(UriDataAttachment.CreateFrom(localFilePath, fileTransferInfo.Description)); } } sendFileCompletedCallback?.Invoke(this, new AsyncCompletedEventArgs(t.Exception, false, fileTransferInfo.UserToken)); } catch (Exception e) { if (EqtTrace.IsErrorEnabled) { EqtTrace.Error( "DataCollectionAttachmentManager.TriggerCallBack: Error occurred while raising the file transfer completed callback for {0}. Error: {1}", localFilePath, e.ToString()); } } }, this.cancellationTokenSource.Token); this.attachmentTasks[fileTransferInfo.Context].Add(continuationTask); }
/// <summary> /// public void DownloadFile(string url, string destination, AsyncCompletedEventHandler onComplete, /// string report, bool async, bool kurjun) /// Performing file download according to download list /// </summary> /// <param name="url">URL to download from</param> /// <param name="destination">destination path\file</param> /// <param name="onComplete">What will be executed on complete</param> /// <param name="report">String to be written to installation form </param> /// <param name="async">If async download</param> /// <param name="kurjun">If download from kurjun</param> public void DownloadFile(string url, string destination, AsyncCompletedEventHandler onComplete, string report, bool async, bool kurjun) { var md5 = ""; if (kurjun) { var filename = Path.GetFileName(destination); var info = request_kurjun_fileInfo(url, RestFileinfoURL, filename); if (info == null) { Program.ShowError($"File does not exist {filename}", "File error"); Program.form1.Visible = false; } url = url + RestFileURL + info.id; md5 = info.id.Replace("raw.", ""); if (!Program.form1.PrerequisiteFilesInfo.ContainsKey(destination)) { Program.form1.PrerequisiteFilesInfo.Add(destination, info); } logger.Info("Getting file {0} from kurjun, md5sum:{1}", destination, md5); } /////////////////////////////////////////////////////////////////////////////// /////////////This part will be modified (removed) when 3 env deployed////////// /////////////////////////////////////////////////////////////////////////////// var shouldWeDownload = true;//will download in any case now if (destination.Contains("tray-dev")) { destination = destination.Remove(destination.IndexOf('-'), 4); } if (destination.Contains("_dev")) { destination = destination.Remove(destination.IndexOf('_'), 4); } if (destination.Contains("-test") && !destination.Contains("repomd5")) { destination = destination.Remove(destination.IndexOf('-'), 5); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// var fileInfo = new FileInfo(destination); if (fileInfo.Exists) { var calculatedMd5 = Calc_md5(destination, false); if (calculatedMd5 != md5) { shouldWeDownload = true; } else { shouldWeDownload = false; } } if (shouldWeDownload) { var dirInfo = new DirectoryInfo(path: Path.GetDirectoryName(destination)); if (!dirInfo.Exists) { dirInfo.Create(); logger.Info("Directory created: {0}", destination); } StageReporter("", report); var webClient = new WebClient(); if (onComplete != null) { webClient.DownloadFileCompleted += onComplete; } //Add ProgressChanges event handler webClient.DownloadProgressChanged += ProgressChanged; //Add Elapsed event handler dwldTimerHandler = ((sender, args) => { dwldTimer.Elapsed -= dwldTimerHandler; webClient.CancelAsync(); dwldTimer.Enabled = false; dwldTimer.Dispose(); Program.ShowError("Can not download files. Please, check Your Internet connection and try later", "Repository Error"); Program.form1.Visible = false; }); dwldTimer.Elapsed += dwldTimerHandler; dwldTimer.Interval = 300000; dwldTimer.AutoReset = false; dwldTimer.Enabled = true; try { if (async) { webClient.DownloadFileAsync(new Uri(url), destination); } else { webClient.DownloadFile(new Uri(url), destination); } } catch (Exception ex) { dwldTimer.Enabled = false; logger.Error(ex.Message, destination); Program.ShowError("Subutai repository is not available. Check Internet connection.", "Repository Error"); } } else { dwldTimer.Enabled = false; onComplete?.Invoke(null, null); } }