using Microsoft.WindowsAzure.Storage.Blob; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Tango.Core.IO; namespace Tango.Transport.Web { public class AutoFileDownloader : IWebFileDownloader { public enum DownloadMode { Standard, Blob } private bool _disposed; private StorageBlobDownloader _blobDownloader; private StandardFileDownloader _standardDownloader; private bool _isCdnOK = false; private long _fileSize = -1; public event EventHandler Progress; public String Address { get; private set; } public String FileName { get; private set; } public DownloadMode Mode { get; private set; } public AutoFileDownloader(String blobAddress, String cdnAddress, String fileName) { FileName = fileName; _blobDownloader = new StorageBlobDownloader(blobAddress, fileName); _standardDownloader = new StandardFileDownloader(cdnAddress, fileName); _blobDownloader.Progress += OnProgress; _standardDownloader.Progress += OnProgress; } private void OnProgress(object sender, WebFileDownloaderProgressEventArgs e) { Progress?.Invoke(this, e); } public async Task Download() { if (_disposed) { throw new ObjectDisposedException("The file downloader can only be used once."); } if (_fileSize == -1) { await GetFileSize(); } if (_isCdnOK) { await _standardDownloader.Download(); } else { await _blobDownloader.Download(); } } public async Task ResolveMode() { await GetFileSize(); } public Task GetFileSize() { if (_fileSize == -1) { return Task.Factory.StartNew(() => { try { _fileSize = _standardDownloader.GetFileSize().Result; _isCdnOK = true; Mode = DownloadMode.Standard; Address = _standardDownloader.Address; return _fileSize; } catch { try { _fileSize = _blobDownloader.GetFileSize().Result; Mode = DownloadMode.Blob; Address = _blobDownloader.Address; return _fileSize; } catch { throw new Exception("Invalid address for standard download or blob."); } } }); } else { return Task.FromResult(_fileSize); } } public void Dispose() { if (!_disposed) { _disposed = true; _blobDownloader.Dispose(); _standardDownloader.Dispose(); } } } }