protected async virtual Task <GenerateResult> TryDownloadImageAsync() { try { if (Parameters.Source != ImageSource.Url) { throw new InvalidOperationException("DownloadOnly: Only Url ImageSource is supported."); } var data = await DownloadCache.GetStreamAsync(Parameters.Path, CancellationToken.Token, Parameters.OnDownloadStarted, Parameters.CacheDuration, Parameters.CustomCacheKey, Parameters.CacheType).ConfigureAwait(false); using (var imageStream = data.ImageStream) { if (!data.RetrievedFromDiskCache) { Logger?.Debug(string.Format("DownloadOnly: {0} successfully downloaded.", Parameters.Path)); } } return(GenerateResult.Success); } catch (Exception ex) { if (ex is OperationCanceledException) { return(GenerateResult.Canceled); } Logger?.Error(string.Format("DownloadOnly: {0} downloaded failed.", Parameters.Path), ex); return(GenerateResult.Failed); } }
private async Task <Stream> GetStreamAsync(string path, ImageSource source) { Stream stream = null; if (string.IsNullOrWhiteSpace(path)) { return(null); } try { switch (source) { case ImageSource.ApplicationBundle: stream = Context.Assets.Open(path, Access.Streaming); break; case ImageSource.Filepath: stream = FileStore.GetInputStream(path); break; case ImageSource.Url: stream = await DownloadCache.GetStreamAsync(path, Parameters.CacheDuration).ConfigureAwait(false); break; } } catch (Exception ex) { Logger.Error("Unable to retrieve image data", ex); return(null); } return(stream); }
private async void DownloadCurrentGDB(Exercise exercise, int key, Barrier downloadTrainingBarrier) { Console.WriteLine("S => Exercise id {0}, key = {1}, start at {2}", exercise.ExerciseId, key, DateTime.Now.ToString("hh:MM:ss.fff")); string json = await ApiConnection.GetExerciseGesturesApiAsync(exercise.ExerciseId); JSONConvertor.GettingExerciseGesture(exercise, json); using (DownloadCache dc = new DownloadCache(_currentPatient)) { dc.DownloadGDBfile(exercise); exercise.Downloaded = true; } if (key == FIRST_EXERCISE) //use for the first gdb - that exercise window can be upload (after splash) { finishFirstGDBSemaphore.Release(); } foreach (var item in _currentTraining.Playlist[key]) { if (!item.isDemo && !item.Equals(exercise)) { item.DBPath = exercise.DBPath; item.CopyGesturesFromOrigin(exercise); item.Downloaded = true; } } Console.WriteLine("F => Exercise id {0}, key = {1}, finish at {2}", exercise.ExerciseId, key, DateTime.Now.ToString("hh:MM:ss.fff")); downloadTrainingBarrier.SignalAndWait(); }
/// <summary> /// Downloads a file from a repository. /// Any subsequent attempt to download the same file just return content from the local cache. /// See <see cref="ClearCache"/>. /// </summary> /// <param name="repository">The repository.</param> /// <param name="filePath">The file path from the root of the repository.</param> /// <returns>The file content, null if an error occurred.</returns> public static async Task <byte[]?> DownloadFile(GitHubRepository repository, string filePath) { byte[]? Result = null; if (await Connect()) { string Login = repository.Source.Owner.Login; string Name = repository.Source.Name; string UpdatedFilePath = filePath.Replace("\\", "/"); string RepositoryAddress = $"{Login}/{Name}"; Debug.WriteLine($"Downloading {RepositoryAddress} {UpdatedFilePath}"); if (DownloadCache.ContainsKey(RepositoryAddress)) { Dictionary <string, byte[]> RepositoryCache = DownloadCache[RepositoryAddress]; if (RepositoryCache.ContainsKey(UpdatedFilePath)) { Debug.WriteLine($" (Already downloaded)"); return(RepositoryCache[UpdatedFilePath]); } } try { Result = await Client.Repository.Content.GetRawContent(Login, Name, UpdatedFilePath); } catch (Exception e) when(e is NotFoundException) { Debug.WriteLine("(not found)"); } if (Result != null) { if (!DownloadCache.ContainsKey(RepositoryAddress)) { DownloadCache.Add(RepositoryAddress, new Dictionary <string, byte[]>()); } Dictionary <string, byte[]> RepositoryCache = DownloadCache[RepositoryAddress]; if (!RepositoryCache.ContainsKey(UpdatedFilePath)) { RepositoryCache.Add(UpdatedFilePath, Result); } } return(Result); } return(Result); }
/// <summary> /// 写入下载缓存信息,用于断点续传 /// </summary> void SaveDownloadCacheData() { if (CurrentState < EmState.UpdateAssetBundle) { return; } if (!Directory.Exists(DownLoadCommon.CACHE_PATH)) { return; } //载入新的Manifest string new_manifest_name = DownLoadCommon.GetCacheFileFullName(DownLoadCommon.MAIN_MANIFEST_FILE_NAME); AssetBundleManifest new_manifest = DownLoadCommon.LoadMainManifestByPath(new_manifest_name); if (new_manifest == null) { return; } //先尝试读取旧的缓存信息,再保存现在已经下载的数据 //PS:由于只有版本完整更新完才会移动Cache目录,且玩家可能多次尝试下载更新,所以必须保留旧的缓存信息 DownloadCache cache = new DownloadCache(); cache.Load(DownLoadCommon.DOWNLOADCACHE_FILE_PATH); if (_ab_download != null && _ab_download.CompleteDownloads != null && _ab_download.CompleteDownloads.Count > 0) { for (int i = 0; i < _ab_download.CompleteDownloads.Count; ++i) { string assetbundle_name = _ab_download.CompleteDownloads[i]; Hash128 hash_code = new_manifest.GetAssetBundleHash(assetbundle_name); if (hash_code.isValid && !cache.Data.AssetBundles.ContainsKey(assetbundle_name)) { DownloadCacheData.AssetBundle elem = new DownloadCacheData.AssetBundle() { AssetBundleName = assetbundle_name, Hash = hash_code.ToString(), }; Debug.Log(cache.Data.AssetBundles.Count + " - Cache Add:" + assetbundle_name); cache.Data.AssetBundles.Add(assetbundle_name, elem); } } } if (cache.HasData()) { cache.Save(DownLoadCommon.DOWNLOADCACHE_FILE_PATH); } }
public async virtual Task <DataResolverResult> Resolve(string identifier, TaskParameter parameters, CancellationToken token) { var downloadedData = await DownloadCache.DownloadAndCacheIfNeededAsync(identifier, parameters, Configuration, token).ConfigureAwait(false); if (token.IsCancellationRequested) { downloadedData?.ImageStream.TryDispose(); token.ThrowIfCancellationRequested(); } var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(downloadedData?.FilePath); return(new DataResolverResult( downloadedData?.ImageStream, downloadedData.RetrievedFromDiskCache ? LoadingResult.DiskCache : LoadingResult.Internet, imageInformation)); }
/// <summary> /// Retrive trainings detail from server (such id, all exercises list and etc.) /// </summary> private async void RetriveTrainingDetails() { try { //await _semaphoreSlime.WaitAsync(); if (!isErrorAccure) { Barrier barrier = new Barrier(_currentPatient.PatientTreatment.TrainingList.Count + 1); //downloading all the trainings data in the current treatment foreach (Training training in _currentPatient.PatientTreatment.TrainingList) { Task t = new Task(async() => { string trainingData = await ApiConnection.GetTrainingApiAsync(training.TrainingId); JSONConvertor.GettingPatientTraining2(training, trainingData); barrier.SignalAndWait(); }); t.Start(); } barrier.SignalAndWait(); //downloading current images for treatment screen using (DownloadCache _downloadCache = new DownloadCache(_currentPatient)) { _downloadCache.DownloadAllTreatmentImages(); } } } catch { //throw new Exception(); } finally { _semaphoreSlime.Release(); } }
//<summary> // 比较AssetBundle差异,获得下载列表与删除列表 //</summary> static void CompareAssetBundleDifference(ref List <string> download_files , ref List <string> delete_files , AssetBundleManifest old_manifest , AssetBundleManifest new_manifest ) { if (download_files != null) { download_files.Clear(); } if (delete_files != null) { delete_files.Clear(); } if (old_manifest == null) { return; } if (new_manifest == null) { return; } //采用位标记的方式判断资源 //位标记: 0: 存在旧资源中 1: 存在新资源中 2:本地资源标记 int old_version_bit = 0x1; // 存在旧资源中 int new_version_bit = 0x2; // 存在新资源中 Dictionary <string, int> temp_dic = new Dictionary <string, int>(); //标记旧资源 string[] all_assetbundle = old_manifest.GetAllAssetBundles(); for (int i = 0; i < all_assetbundle.Length; ++i) { string name = all_assetbundle[i]; _SetDictionaryBit(ref temp_dic, name, old_version_bit); } //标记新资源 string[] new_all_assetbundle = new_manifest.GetAllAssetBundles(); for (int i = 0; i < new_all_assetbundle.Length; ++i) { string name = new_all_assetbundle[i]; _SetDictionaryBit(ref temp_dic, name, new_version_bit); } //获得对应需操作的文件名, 优先级: both > add > delete //both: 第0位与第1位都被标记的 //delete: 仅第0位被标记的 //add: 第2位未标记,且第3位被标记的 int both_bit = old_version_bit | new_version_bit; // 二个版本资源都存在 List <string> add_files = new List <string>(); List <string> both_files = new List <string>(); var itr = temp_dic.GetEnumerator(); while (itr.MoveNext()) { string name = itr.Current.Key; int mask = itr.Current.Value; if ((mask & new_version_bit) == new_version_bit && (mask & old_version_bit) == 0) { add_files.Add(name); } else if ((mask & both_bit) == both_bit) { both_files.Add(name); } else if ((mask & old_version_bit) == old_version_bit) { delete_files.Add(name); } } itr.Dispose(); //载入下载缓存数据 DownloadCache download_cache = new DownloadCache(); download_cache.Load(DownLoadCommon.DOWNLOADCACHE_FILE_PATH); if (!download_cache.HasData()) { download_cache = null; } //记录需下载的文件 { //加入新增的文件 download_files.AddRange(add_files); //比较所有同时存在的文件,判断哪些需要更新 for (int i = 0; i < both_files.Count; ++i) { string name = both_files[i]; string full_name = DownLoadCommon.GetFileFullName(name); if (File.Exists(full_name)) { //判断哈希值是否相等 string old_hash = old_manifest.GetAssetBundleHash(name).ToString(); string new_hash = new_manifest.GetAssetBundleHash(name).ToString(); if (old_hash.CompareTo(new_hash) == 0) { continue; } download_files.Add(name); } else { download_files.Add(name); } } //过滤缓存中已下载的文件 if (download_cache != null) { var cache_itr = download_cache.Data.AssetBundles.GetEnumerator(); while (cache_itr.MoveNext()) { DownloadCacheData.AssetBundle elem = cache_itr.Current.Value; string name = elem.AssetBundleName; string full_name = DownLoadCommon.GetFileFullName(name); if (File.Exists(full_name)) { string cache_hash = elem.Hash; string new_hash = new_manifest.GetAssetBundleHash(name).ToString(); if (!string.IsNullOrEmpty(cache_hash) && cache_hash.CompareTo(new_hash) == 0) { download_files.Remove(name); } } } } } }
public void TearDown() { _cache = null; }
public void Setup() { _cache = new DownloadCache(); }
public override void Execute(IEnumerable <string> args) { var days = double.Parse(args.FirstOrDefault() ?? "14"); DownloadCache.CollectGarbage(days); }
/// <summary> /// Clears the file cache. /// </summary> public static void ClearCache() { DownloadCache.Clear(); }
public void CanAdd_NonExistentFile_ReturnsFalse() { //Arrange var downloadCache = new DownloadCache(); var fileName = Guid.NewGuid().ToString(); var isoManagerMock = Mock.Create<IClientStorageManager>(); Mock.Arrange(() => isoManagerMock.GetAvailableSpace(Arg.IsAny<string>())).Returns(0); downloadCache.TheIsolatesStorageManager = isoManagerMock; var streamMock = Mock.Create<Stream>(); Mock.Arrange(() => streamMock.Length).Returns(100); //Act var result = downloadCache.CanAdd(fileName, streamMock); //Assert Assert.IsFalse(result); }
public void Add_WhenCalled_SavesToIsolatedStorage() { //Arrange var downloadCache = new DownloadCache(); var fileName = Guid.NewGuid().ToString(); var streamMock = Mock.Create<Stream>(); var version = new Version(1, 0); var isoMock = Mock.Create<IClientStorageManager>(); Mock.Arrange(() => isoMock.SaveToFile(Arg.AnyString, Arg.IsAny<Stream>())).MustBeCalled(); downloadCache.TheIsolatesStorageManager = isoMock; downloadCache.TheCacheIndex = Mock.Create<CacheIndex>(); //Act downloadCache.Add(fileName, streamMock, version); //Assert isoMock.AssertAll(); }
public void Load_ExistentFile_ReturnsNonNullValue() { //Arrange var downloadCache = new DownloadCache(); var fileName = Guid.NewGuid().ToString(); var version = new Version(1, 0); var isoMock = Mock.Create<IClientStorageManager>(); Mock.Arrange(() => isoMock.IsFileExists(Arg.AnyString)).Returns(true); downloadCache.TheIsolatesStorageManager = isoMock; var cacheIndexMock = Mock.Create<CacheIndex>(); Mock.Arrange(() => cacheIndexMock.IsExpired(Arg.AnyString, Arg.IsAny<Version>())).Returns(false); downloadCache.TheCacheIndex = cacheIndexMock; //Act var result = downloadCache.Load(fileName, version); //Assert Assert.IsNotNull(result); }
public void Load_NonExistentFile_ReturnsNull() { //Arrange var downloadCache = new DownloadCache(); var fileName = Guid.NewGuid().ToString(); var version = new Version(1, 0); downloadCache.TheIsolatesStorageManager = Mock.Create<IClientStorageManager>(); //Act var result = downloadCache.Load(fileName, version); //Assert Assert.IsNull(result); }