public async Task DownloadAsync(HttpClient client) { var file = await folder.TryGetFileAsync(filename).ConfigureAwait(false); if (file != null) { tcs.TrySetResult(file); return; } DebugUtil.LogSensitive(() => "Start downloading: {0}", uri); try { var res = await client.SendRequestAsync(new HttpRequestMessage(HttpMethod.Get, uri)); using (var stream = (await res.Content.ReadAsInputStreamAsync()).AsStreamForRead()) { DebugUtil.LogSensitive(() => "Writing: {0}", filename); var dst = await folder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); using (var outStream = await dst.OpenStreamForWriteAsync().ConfigureAwait(false)) { await stream.CopyToAsync(outStream).ConfigureAwait(false); } tcs.TrySetResult(dst); } } catch (Exception e) { DebugUtil.Log(() => e.StackTrace); tcs.TrySetException(e); } }
/// <summary> /// Asynchronously download thumbnail image and return local storage file. /// </summary> /// <param name="uuid">UUID of the target device.</param> /// <param name="content">Source of thumbnail image.</param> /// <returns>Local storage file</returns> public async Task <StorageFile> LoadCacheFileAsync(string uuid, ContentInfo content) { var uri = new Uri(content.ThumbnailUrl); var directory = uuid.Replace(":", "-") + "/"; var filename = content.CreatedTime.Replace(":", "-").Replace("/", "-") + "--" + Path.GetFileName(uri.LocalPath); if (!filename.Contains(".")) { filename += ".jpg"; } else if (filename.EndsWith(".arw", StringComparison.OrdinalIgnoreCase)) { filename = filename.Substring(0, filename.Length - 3) + "jpg"; } DebugUtil.LogSensitive(() => "Loading {0} into {1}", content.ThumbnailUrl, directory); await LoadCacheRoot().ConfigureAwait(false); var folder = await CacheFolder.CreateFolderAsync(directory, CreationCollisionOption.OpenIfExists); var file = await folder.TryGetFileAsync(filename).ConfigureAwait(false); if (file != null) { return(file); } var tcs = new TaskCompletionSource <StorageFile>(); var taskSource = new TaskSource { uri = uri, folder = folder, filename = filename, tcs = tcs }; lock (HolderLock) { if (Stack.Count == 0 && Queue.Count < FIFO_THRESHOLD) { Queue.Enqueue(taskSource); } else { Stack.Push(taskSource); } } TryRunTask(); return(await tcs.Task.ConfigureAwait(false)); }
/// <summary> /// /// </summary> /// <param name="uuid">Specify uuid to delete directory for the device, otherwise delete all of stored cache.</param> public async Task DeleteCache(string uuid = null) { var root = ApplicationData.Current.TemporaryFolder; if (uuid == null) { DebugUtil.Log(() => "Delete all of thumbnail cache."); await LoadCacheRoot().ConfigureAwait(false); await CacheFolder.DeleteDirectoryRecursiveAsync(false).ConfigureAwait(false); } else { DebugUtil.LogSensitive(() => "Delete thumbnail cache of {0}", uuid); await LoadCacheRoot().ConfigureAwait(false); var uuidRoot = await CacheFolder.GetFolderAsync(uuid.Replace(":", "-")); await uuidRoot.DeleteDirectoryRecursiveAsync().ConfigureAwait(false); } }
private async Task Enqueue(Uri uri, string namebase, Mediatype type, CancellationTokenSource cts, string extension = null) { DebugUtil.LogSensitive(() => "ContentsDownloader: Enqueue {0}", uri.AbsolutePath); if (extension == null) { var split = uri.AbsolutePath.Split('.'); if (split.Length > 0) { extension = "." + split[split.Length - 1].ToLower(); DebugUtil.Log(() => "detected file extension: " + extension); } } var tcs = new TaskCompletionSource <bool>(); await SystemUtil.GetCurrentDispatcher().RunAsync(CoreDispatcherPriority.Low, () => { var req = new DownloadRequest { Uri = uri, NameBase = namebase, Completed = OnFetched, Error = OnFailed, Mediatype = type, FileExtension = extension, CompletionSource = tcs, CancellationTokenSource = cts, }; DownloadQueue.Enqueue(req); QueueStatusUpdated?.Invoke(DownloadQueue.Count); ProcessQueueSequentially(); }); await tcs.Task; }
private async Task DownloadToSave(DownloadRequest req) { DebugUtil.LogSensitive(() => "Download picture: {0}", req.Uri.OriginalString); try { var geoResult = GeotaggingResult.Result.NotRequested; var task = HttpClient.GetAsync(req.Uri, HttpCompletionOption.ResponseContentRead); HttpResponseMessage res; try { res = await task; } catch (Exception e) { req.Error?.Invoke(DownloaderError.Network, geoResult); req.CompletionSource?.TrySetException(e); return; } if (req.CancellationTokenSource?.IsCancellationRequested ?? false) { req.CompletionSource?.TrySetCanceled(req.CancellationTokenSource.Token); req.Error?.Invoke(DownloaderError.Cancelled, geoResult); return; } var imageStream = (await res.Content.ReadAsInputStreamAsync()).AsStreamForRead(); if (req.Mediatype == Mediatype.Image) { if (ApplicationSettings.GetInstance().GeotagEnabled) { var position = await GeolocatorManager.INSTANCE.GetLatestPosition(); if (position == null) { geoResult = GeotaggingResult.Result.FailedToAcquireLocation; } else { var result = await GeopositionUtil.AddGeotag(imageStream, position); imageStream = result.Image; geoResult = result.OperationResult; } } } if (req.CancellationTokenSource?.IsCancellationRequested ?? false) { req.CompletionSource?.TrySetCanceled(req.CancellationTokenSource.Token); req.Error?.Invoke(DownloaderError.Cancelled, geoResult); return; } using (imageStream) { StorageFolder rootFolder; switch (req.Mediatype) { case Mediatype.Image: rootFolder = KnownFolders.PicturesLibrary; break; case Mediatype.Video: rootFolder = KnownFolders.PicturesLibrary; // Use Pictures folder according to the behavior of built-in Camera apps // rootFolder = KnownFolders.VideosLibrary; break; default: req.CompletionSource?.TrySetException(new NotSupportedException(req.Mediatype + " is not supported")); return; } var folder = await rootFolder.CreateFolderAsync(DIRECTORY_NAME, CreationCollisionOption.OpenIfExists); var filename = string.Format(req.NameBase + "_{0:yyyyMMdd_HHmmss}" + req.FileExtension, DateTime.Now); var file = await folder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName); using (var outStream = await file.OpenStreamForWriteAsync()) { if (req.CancellationTokenSource == null) { await imageStream.CopyToAsync(outStream); } else { await imageStream.CopyToAsync(outStream, 81920, req.CancellationTokenSource.Token); } } req.Completed?.Invoke(folder, file, geoResult); req.CompletionSource?.TrySetResult(true); return; } } catch (Exception e) { DebugUtil.Log(() => e.Message); DebugUtil.Log(() => e.StackTrace); req.Error?.Invoke(DownloaderError.Unknown, GeotaggingResult.Result.NotRequested); // TODO req.CompletionSource?.TrySetException(e); } }
private void Geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args) { DebugUtil.LogSensitive(() => "Location updated: {0}, {1}", args.Position.Coordinate.Point.Position.Longitude, args.Position.Coordinate.Point.Position.Latitude); LatestPosition = args.Position; }