public void Download_Error() { var downloadUri = "http://www.sample.com?alt=media"; var chunkSize = 100; // reset the steam StreamContent.Position = 0; var handler = new MultipleChunksMessageHandler(); handler.StatusCode = HttpStatusCode.BadRequest; handler.ChunkSize = chunkSize; handler.DownloadUri = new Uri(downloadUri); using (var service = new MockClientService(new BaseClientService.Initializer() { HttpClientFactory = new MockHttpClientFactory(handler) })) { var downloader = new MediaDownloader(service); downloader.ChunkSize = chunkSize; IList <IDownloadProgress> progressList = new List <IDownloadProgress>(); downloader.ProgressChanged += (p) => { progressList.Add(p); }; var outputStream = new MemoryStream(); downloader.Download(downloadUri, outputStream); var lastProgress = progressList.LastOrDefault(); Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed)); } }
private async Task DownloadObjectAsyncImpl( string baseUri, Stream destination, DownloadObjectOptions options, CancellationToken cancellationToken, IProgress <IDownloadProgress> progress) { Preconditions.CheckNotNull(destination, nameof(destination)); var downloader = new MediaDownloader(Service); options?.ModifyDownloader(downloader); string uri = options == null ? baseUri : options.GetUri(baseUri); if (progress != null) { downloader.ProgressChanged += progress.Report; // Avoid reporting progress synchronously in the original call. await Task.Yield(); progress.Report(InitialDownloadProgress.Instance); } var result = await downloader.DownloadAsync(uri, destination, cancellationToken).ConfigureAwait(false); if (result.Status == DownloadStatus.Failed) { throw result.Exception; } }
/// <summary>Downloads the media from the given URL.</summary> private async Task DownloadFile(DriveService service, string url) { var downloader = new MediaDownloader(service); downloader.ChunkSize = DownloadChunkSize; // add a delegate for the progress changed event for writing to console on changes downloader.ProgressChanged += Download_ProgressChanged; // figure out the right file type base on UploadFileName extension var lastDot = UploadFileName.LastIndexOf('.'); var fileName = DownloadDirectoryName + @"\Download" + (lastDot != -1 ? "." + UploadFileName.Substring(lastDot + 1) : ""); using (var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { var progress = await downloader.DownloadAsync(url, fileStream); if (progress.Status == DownloadStatus.Completed) { Console.WriteLine(fileName + " was downloaded successfully"); } else { Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ", fileName, progress.BytesDownloaded); } } }
/// <summary> /// 取回檔案儲存 /// </summary> /// <param name="sourcePathWithFileName">來源路徑與檔案名稱</param> /// <param name="targetPathWithFileName">目標路徑與檔案名稱</param> /// <returns></returns> public bool DownloadToFile(string sourcePathWithFileName, string targetPathWithFileName) { sourcePathWithFileName = sourcePathWithFileName.Replace("\\", "/"); var objectToDownload = _storage.Objects.Get(_bucketName, sourcePathWithFileName).Execute(); var downloader = new MediaDownloader(_storage); downloader.ProgressChanged += progress => { Console.WriteLine($"{progress.Status} {progress.BytesDownloaded} bytes"); }; using (var fileStream = new FileStream(targetPathWithFileName, FileMode.Create)) { var progress = downloader.Download(objectToDownload.MediaLink, fileStream); if (progress.Status == DownloadStatus.Completed) { Console.WriteLine($"Downloaded {sourcePathWithFileName} to {targetPathWithFileName}"); return(true); } } return(false); }
public Updater() { Downloader = new MediaDownloader(Global.GoogleDrive) { ChunkSize = 512 * 1024 }; }
// Downloading a file stream with progress public void DownloadToFile(string bucketName) { StorageService storage = CreateStorageClient(); var objectToDownload = storage.Objects.Get(bucketName, "testFile.txt").Execute(); var downloader = new MediaDownloader(storage); // Subscribe a function to the event ProgressChanged // The return type of the event is IDownloadProgress which has properties Status and BytesDownloaded downloader.ProgressChanged += progress => { Console.WriteLine($"{progress.Status} {progress.BytesDownloaded} bytes"); }; using (var fileStream = new FileStream(@"C:\Users\Varderes\Desktop\downloadedFile.txt", FileMode.Create)) { var progress = downloader.Download(objectToDownload.MediaLink, fileStream); if (progress.Status == DownloadStatus.Completed) { Console.WriteLine("Downloaded testFile.txt to downloadedFile.txt"); } } }
public void Download_Error_PlaintextResponse(string responseText) { var downloadUri = "http://www.sample.com"; var chunkSize = 100; var handler = new MultipleChunksMessageHandler { ErrorResponse = responseText }; handler.StatusCode = HttpStatusCode.NotFound; handler.ChunkSize = chunkSize; // The media downloader adds the parameter... handler.DownloadUri = new Uri(downloadUri + "?alt=media"); using (var service = CreateMockClientService(handler)) { var downloader = new MediaDownloader(service); downloader.ChunkSize = chunkSize; IList <IDownloadProgress> progressList = new List <IDownloadProgress>(); downloader.ProgressChanged += (p) => { progressList.Add(p); }; var outputStream = new MemoryStream(); downloader.Download(downloadUri, outputStream); var lastProgress = progressList.LastOrDefault(); Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed)); GoogleApiException exception = (GoogleApiException)lastProgress.Exception; Assert.That(exception.HttpStatusCode, Is.EqualTo(handler.StatusCode)); Assert.That(exception.Message, Is.EqualTo(responseText)); Assert.IsNull(exception.Error); } }
public void Download_Error_JsonResponse() { using (var service = new MockClientService()) { var downloader = new MediaDownloader(service); IList <IDownloadProgress> progressList = new List <IDownloadProgress>(); downloader.ProgressChanged += (p) => { progressList.Add(p); }; var outputStream = new MemoryStream(); downloader.Download(_httpPrefix + "BadRequestJson", outputStream); var lastProgress = progressList.LastOrDefault(); Assert.Equal(DownloadStatus.Failed, lastProgress.Status); GoogleApiException exception = (GoogleApiException)lastProgress.Exception; Assert.Equal(HttpStatusCode.BadRequest, exception.HttpStatusCode); // Just a smattering of checks - if these two pass, it's surely okay. Assert.Equal(BadRequestError.Code, exception.Error.Code); Assert.Equal(BadRequestError.Errors[0].Message, exception.Error.Errors[0].Message); Assert.NotNull(exception.Error.ErrorResponseContent); Assert.Contains(BadRequestError.Errors[0].Message, exception.Error.ErrorResponseContent); } }
public void Download_Error_PlaintextResponse() { using (var service = new MockClientService()) { var downloader = new MediaDownloader(service); IList <IDownloadProgress> progressList = new List <IDownloadProgress>(); downloader.ProgressChanged += (p) => { progressList.Add(p); }; var outputStream = new MemoryStream(); downloader.Download(_httpPrefix + "NotFoundPlainText", outputStream); var lastProgress = progressList.LastOrDefault(); Assert.Equal(DownloadStatus.Failed, lastProgress.Status); GoogleApiException exception = Assert.IsType <GoogleApiException>(lastProgress.Exception); Assert.Equal(HttpStatusCode.NotFound, exception.HttpStatusCode); Assert.Equal("The service TestService has thrown an exception. HttpStatusCode is NotFound. No error message was specified.", exception.Message); Assert.Contains( $"The service TestService has thrown an exception.{Environment.NewLine}" + $"HttpStatusCode is NotFound.{Environment.NewLine}" + $"No JSON error details were specified.{Environment.NewLine}" + $"Raw error details are: {NotFoundError}", exception.ToString()); Assert.True(exception.Error.IsOnlyRawContent); } }
internal void ModifyDownloader(MediaDownloader downloader) { if (ChunkSize != null) { downloader.ChunkSize = ChunkSize.Value; } }
private void DownloadObjectImpl( string baseUri, Stream destination, DownloadObjectOptions options, IProgress <IDownloadProgress> progress) { // URI will definitely not be null; that's constructed internally. Preconditions.CheckNotNull(destination, nameof(destination)); var downloader = new MediaDownloader(Service); options?.ModifyDownloader(downloader); string uri = options == null ? baseUri : options.GetUri(baseUri); if (progress != null) { downloader.ProgressChanged += progress.Report; progress.Report(InitialDownloadProgress.Instance); } var result = downloader.Download(uri, destination); if (result.Status == DownloadStatus.Failed) { throw result.Exception; } }
private bool RestoreDatabase(DriveService driveservice, string downloadurl) { bool flag = false; var downloader = new MediaDownloader(driveservice); int last_dot; var file_name = ""; //if database type is sqlite if (StaticClass.GeneralClass.flag_database_type_general == false) { download_file_name = @"Databses\CheckOut.db"; last_dot = download_file_name.LastIndexOf("."); download_directory_name = "Databases"; file_name = download_directory_name + @"\CheckOut" + (last_dot != -1 ? "." + download_file_name.Substring(last_dot + 1) : ""); } //if database type is sqlserver else { //check exist of folder temp contain database backup if (System.IO.Directory.Exists(current_directory + @"\Database_Ser_Temp") == false) { System.IO.Directory.CreateDirectory(current_directory + @"\Database_Ser_Temp"); } //check database exist if (System.IO.File.Exists(current_directory + @"\Database_Ser_Temp\CheckOut.sql") == true) { System.IO.File.Delete(current_directory + @"\Database_Ser_Temp\CheckOut.sql"); } if (!string.IsNullOrEmpty(extDownload) && extDownload == "bak") { download_file_name = @"Databses\CheckOut.bak"; } else { download_file_name = @"Databses\CheckOut.db"; } last_dot = download_file_name.LastIndexOf("."); download_directory_name = "Database_Ser_Temp"; file_name = download_directory_name + @"\CheckOut" + (last_dot != -1 ? "." + download_file_name.Substring(last_dot + 1) : ""); } var full_path = System.IO.Path.Combine(file_name); filestream = new System.IO.FileStream(full_path, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite); if (downloader.Download(downloadurl, filestream) != null) { flag = true; } else { flag = false; } filestream.Dispose(); return(flag); }
public void DownloadFileTest() { MediaDownloader downloader = new MediaDownloader(); MediaFile file = MediaFile.CreateNew(VboxDownloadVideo); string downloadedFile = downloader.Download(file, Environment.GetFolderPath(Environment.SpecialFolder.Desktop)).DownloadPath; Assert.AreEqual(VboxDownloadedVideoPath, downloadedFile); }
public void ModifyDownloader_DefaultOptions() { var downloader = new MediaDownloader(null); var options = new DownloadObjectOptions(); options.ModifyDownloader(downloader); Assert.Equal(MediaDownloader.MaximumChunkSize, downloader.ChunkSize); }
protected override void ProcessRecord() { base.ProcessRecord(); var service = GetStorageService(); if (InputObject != null) { Bucket = InputObject.Bucket; ObjectName = InputObject.Name; } string uri = GetBaseUri(Bucket, ObjectName); var downloader = new MediaDownloader(service); // Write object contents to the pipeline if no -OutFile is specified. if (string.IsNullOrEmpty(OutFile)) { // Start with a 1MiB buffer. We could get the object's metadata and use its exact // file size, but making a web request << just allocating more memory. using (var memStream = new MemoryStream(1024 * 1024)) { var result = downloader.Download(uri, memStream); if (result.Status == DownloadStatus.Failed || result.Exception != null) { throw result.Exception; } // Stream cursor is at the end (data just written). memStream.Position = 0; using (var streamReader = new StreamReader(memStream)) { string objectContents = streamReader.ReadToEnd(); WriteObject(objectContents); } } return; } // Write object contents to disk. Fail if the local file exists, unless -Force is specified. string qualifiedPath = GetFullPath(OutFile); bool fileExists = File.Exists(qualifiedPath); if (fileExists && !Force.IsPresent) { throw new PSArgumentException($"File '{qualifiedPath}' already exists. Use -Force to overwrite."); } using (var writer = new FileStream(qualifiedPath, FileMode.Create)) { var result = downloader.Download(uri, writer); if (result.Status == DownloadStatus.Failed || result.Exception != null) { throw result.Exception; } } }
public void ModifyDownloader_WithChunkSize() { var downloader = new MediaDownloader(null); var options = new DownloadObjectOptions { ChunkSize = 2048 }; options.ModifyDownloader(downloader); Assert.Equal(2048, downloader.ChunkSize); }
public void IsDownloadingTest() { MediaFile file = MediaFile.CreateNew(BasicSoundCloudFileTests.SoundCloudLink); MediaDownloader downloader = new MediaDownloader(); var result = downloader.Download(file, Directory.GetCurrentDirectory()); Assert.IsTrue(result.IsDownloaded); Assert.IsTrue(File.Exists(result.DownloadPath)); }
public void DownloadFileStartingEventTest() { MediaDownloader downloader = new MediaDownloader(); bool fired = false; MediaFile file = MediaFile.CreateNew(VboxDownloadVideo); downloader.MediaFileDownloadStarting += (s, e) => fired = true; string downloadedFile = downloader.Download(file, Environment.GetFolderPath(Environment.SpecialFolder.Desktop)).DownloadPath; Assert.AreEqual(fired, true); }
public Stream Download(StorageCredentials credentials, string path, string fileName) { var downloader = new MediaDownloader(GetClient(credentials)); downloader.ChunkSize = DownloadChunkSize; using (var fileStream = new System.IO.FileStream(string.Format(@"{0}/{1}", path, fileName), System.IO.FileMode.Create, System.IO.FileAccess.Write)) { var task = downloader.DownloadAsync(fileName, fileStream); task.Wait(); return(fileStream); } }
private MediaDownloader CreateDownloader(DownloadObjectOptions options) { DownloadValidationMode mode = options?.DownloadValidationMode ?? DownloadValidationMode.Always; GaxPreconditions.CheckEnumValue(mode, nameof(DownloadObjectOptions.DownloadValidationMode)); MediaDownloader downloader = mode == DownloadValidationMode.Never ? new MediaDownloader(Service) : new HashValidatingDownloader(Service); options?.ModifyDownloader(downloader); ApplyEncryptionKey(options?.EncryptionKey, downloader); return(downloader); }
public ExportContext( ExportRequest request, IReadOnlyCollection <Member> members, IReadOnlyCollection <Channel> channels, IReadOnlyCollection <Role> roles) { Request = request; Members = members; Channels = channels; Roles = roles; _mediaDownloader = new MediaDownloader(request.OutputMediaDirPath, request.ShouldReuseMedia); }
/// <summary> /// Uses MediaDownloader to download the contents of a URI. /// Asserts that the download succeeded and returns the resulting content as a string. /// </summary> /// <param name="uri">Uri to download</param> /// <returns></returns> private string SimpleDownload(string uri) { using (var service = new MockClientService()) { var downloader = new MediaDownloader(service); var outputStream = new MemoryStream(); var result = downloader.Download(uri, outputStream); Assert.AreEqual(result.Status, DownloadStatus.Completed); Assert.IsNull(result.Exception); Assert.AreEqual(result.BytesDownloaded, outputStream.Position); return(Encoding.UTF8.GetString(outputStream.GetBuffer(), 0, (int)outputStream.Position)); } }
public void IsConvertingToMp3() { MediaDownloader downloader = new MediaDownloader(); MediaFile mediaFile = MediaFile.CreateNew(VboxDownloadConvertTests.VboxDownloadVideo); string existingPath = Path.Combine(Directory.GetCurrentDirectory(), mediaFile.Metadata.FileName + mediaFile.Metadata.FileExtension); if (!File.Exists(existingPath)) { downloader.Download(mediaFile, Directory.GetCurrentDirectory()); } MediaConverter converter = new MediaConverter(); ConvertResult result = converter.Convert(mediaFile, existingPath, Directory.GetCurrentDirectory(), new MediaConverterMetadata(Bitrates.Kbps192)); Assert.IsTrue(result.IsConverted); Assert.IsTrue(File.Exists(result.ConvertedPath)); }
public void DownloadFileCompletedEventTest() { MediaDownloader downloader = new MediaDownloader(); bool downloaded = false; MediaFile file = MediaFile.CreateNew(VboxDownloadVideo); downloader.MediaFileDownloadFinished += (s, e) => { downloaded = true; }; string downloadedFile = downloader.Download(file, Environment.GetFolderPath(Environment.SpecialFolder.Desktop)).DownloadPath; Assert.AreEqual(true, downloaded); }
void Recite() { switch ((ClickMode)CurrentState.CtlSetting.ClickMode) { case ClickMode.Recite: var rec = BLL.quran_data.getReciter(CurrentState.ReciterId); string _Prefix = rec.mediaurl; string SurahKey = CurrentState.Surah.ToString().PadLeft(3, '0'); string AyahKey = CurrentState.Ayah.ToString().PadLeft(3, '0'); string MediaUrl = string.Format(_Prefix, SurahKey, AyahKey); if (!CurrentState.isPlaying) { CurrentState.isPlaying = true; } else { QuranPlayer.Stop(); } string NamaFile = string.Format("{0}_{1}.mp3", SurahKey, AyahKey); string SubFolder = string.Format("reciter_{0}", rec.idx); string UrlMedia = null; if (InternetState) { UrlMedia = MediaDownloader.DownloadAndPlay(MediaUrl, SubFolder, NamaFile); } else { UrlMedia = MediaDownloader.CheckOfflineMedia(MediaUrl, SubFolder, NamaFile); } if (!string.IsNullOrEmpty(UrlMedia)) { QuranPlayer.Source = new Uri(UrlMedia, UriKind.RelativeOrAbsolute); QuranPlayer.Play(); } break; case ClickMode.ReadTranslation: //only english if (CurrentState.LanguageId == 11) { BLL.quran_data.AyahData item = (BLL.quran_data.AyahData)CurrentState.CtlAyah.ListData.SelectedItem; speechSynthesizer.SpeakAsync(item.translation); } break; } }
public void Download_Error_JsonResponse() { var downloadUri = "http://www.sample.com"; var chunkSize = 100; var error = new RequestError { Code = 12345, Message = "Text", Errors = new[] { new SingleError { Message = "Nested error" } } }; var response = new StandardResponse <object> { Error = error }; var responseText = new NewtonsoftJsonSerializer().Serialize(response); var handler = new MultipleChunksMessageHandler { ErrorResponse = responseText }; handler.StatusCode = HttpStatusCode.BadRequest; handler.ChunkSize = chunkSize; // The media downloader adds the parameter... handler.DownloadUri = new Uri(downloadUri + "?alt=media"); using (var service = CreateMockClientService(handler)) { var downloader = new MediaDownloader(service); downloader.ChunkSize = chunkSize; IList <IDownloadProgress> progressList = new List <IDownloadProgress>(); downloader.ProgressChanged += (p) => { progressList.Add(p); }; var outputStream = new MemoryStream(); downloader.Download(downloadUri, outputStream); var lastProgress = progressList.LastOrDefault(); Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed)); GoogleApiException exception = (GoogleApiException)lastProgress.Exception; Assert.That(exception.HttpStatusCode, Is.EqualTo(handler.StatusCode)); // Just a smattering of checks - if these two pass, it's surely okay. Assert.That(exception.Error.Code, Is.EqualTo(error.Code)); Assert.That(exception.Error.Errors[0].Message, Is.EqualTo(error.Errors[0].Message)); } }
public void ResumesDownloadProperly() { MediaDownloader downloader = new MediaDownloader(); bool canceled = false; bool downloaded = false; downloader.MediaFileDownloadProgress += (s, e) => { if (((int)e.PercentageComplete >= 25 && (int)e.PercentageComplete <= 30) && !canceled) { e.Cancel = canceled = true; } if (e.PercentageComplete >= 100) { downloaded = true; } }; MediaFile file = MediaFile.CreateNew(MediaFileTests.VboxTestUrl); string path = Path.Combine(Directory.GetCurrentDirectory(), file.Metadata.FileName + file.Metadata.FileExtension); if (File.Exists(path)) { File.Delete(path); } var firstResult = downloader.Download(file, Directory.GetCurrentDirectory()); if (!firstResult.IsDownloaded || firstResult.Exceptions.Any()) { throw new Exception(); } var secondDownload = downloader.Download(file, Directory.GetCurrentDirectory(), true); if (!secondDownload.IsDownloaded || secondDownload.Exceptions.Any()) { throw new Exception(); } Assert.IsTrue(downloaded); }
public void InterceptGzip() { var compressedData = new MemoryStream(); using (var gzipStream = new GZipStream(compressedData, CompressionMode.Compress, true)) { gzipStream.Write(MediaContent, 0, MediaContent.Length); } var interceptedData = new MemoryStream(); StreamInterceptor interceptor = interceptedData.Write; int interceptorProviderCount = 0; using (var service = new MockClientService()) { var downloader = new MediaDownloader(service) { ChunkSize = 10, ResponseStreamInterceptorProvider = _ => { interceptorProviderCount++; return(interceptor); } }; IList <IDownloadProgress> progressList = new List <IDownloadProgress>(); downloader.ProgressChanged += (p) => { progressList.Add(p); }; var outputStream = new MemoryStream(); downloader.Download(_httpPrefix + "GzipContent", outputStream); // We only had one HTTP response, even though we read it in multiple chunks. Assert.Equal(1, interceptorProviderCount); // The end result is decompressed content. Assert.Equal(MediaContent, outputStream.ToArray()); // We intercepted the compressed content. Assert.Equal(compressedData.ToArray(), interceptedData.ToArray()); } }
private void DownloadAll_Execute() { var UrlList = new List <string>(); foreach (var item in Items) { UrlList.Add(item.FullPictureUrl); } var cookies = _memoryManager.CurrentCookies; IMediaDownloader downloader = new MediaDownloader(cookies); downloader.Downloading += Downloader_DownloadFull; downloader.DownloadStarted += delegate(int count) { DownloadProgress = $"Downloading {0}/{count}"; Count = count; }; downloader.DownloadAllImages(UrlList); }
public void ConversionEndedEventTest() { MediaDownloader downloader = new MediaDownloader(); MediaFile file = MediaFile.CreateNew(VboxDownloadVideo); string downloadedPath = downloader.Download(file, Environment.GetFolderPath(Environment.SpecialFolder.Desktop)).DownloadPath; bool converting = false; MediaConverter converter = new MediaConverter(); converter.MediaFileConvertionCompelete += delegate { converting = true; }; converter.Convert(file, downloadedPath, Environment.GetFolderPath(Environment.SpecialFolder.Desktop), new MediaConverterMetadata { AudioBitrate = Bitrates.Kbps192, Extension = SupportedConversionFormats.Mp3, FileName = file.Metadata.FileName }); Assert.AreEqual(true, converting); }