private async Task <ImageSource> GetChachedThumbnail(Thumbnail thumbnail) { ImageSource imageSource = null; //캐싱 이미지 로드 ThumbnailDAO.FillThumnailData(thumbnail); await DispatcherHelper.RunAsync(async() => { //PNG의 경우 스트림으로 로드해야 정상적으로 출력이됨 (WriteableBitmapEx의 FromStream 또는 BitmapDecoder 사용시 await가 걸리지 않는 버그가 있음) BitmapImage image = new BitmapImage(); if (thumbnail.ThumbnailData != null) { using (InMemoryRandomAccessStream imras = new InMemoryRandomAccessStream()) { await imras.WriteAsync(thumbnail.ThumbnailData.AsBuffer()); imras.Seek(0); image.SetSource(imras); imageSource = image; } } else { Debugger.Break(); //여기 걸리면 안되는건디... } }); return(imageSource); }
private void LoadThumbnailMetadataInFolder(IList <Item> itemList) { if (itemList.Any() && !_ThumbnailListInCurrentFolder.Any()) { var thumbDirectory = itemList.Where(x => x.ParentReference != null).Select(x => x.ParentReference.Path).FirstOrDefault(); ThumbnailDAO.LoadThumnailInFolder(thumbDirectory, _ThumbnailListInCurrentFolder); } }
protected void LoadCachedThumbnail(IMediaItemInfo item, Thumbnail thumbnail) { //캐싱 이미지 로드 ThumbnailDAO.FillThumnailData(thumbnail); DispatcherHelper.CheckBeginInvokeOnUI(async() => { //상영시간 item.Duration = thumbnail.RunningTime; //PNG의 경우 스트림으로 로드해야 정상적으로 출력이됨 using (MemoryStream ms = new MemoryStream(thumbnail.ThumbnailData)) { //item.ImageItemsSource = await BitmapFactory.New(0, 0).FromStream(ms); item.ImageItemsSource = await BitmapFactory.FromStream(ms); } }); }
protected async Task SaveThumbail(Func <byte[], Thumbnail> funcGetThumbnail, byte[] data) { using (InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream()) { // Encode pixels into stream var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ras); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)ThumbnailSize.Width, (uint)ThumbnailSize.Height, 96, 96, data); await encoder.FlushAsync(); byte[] pngPixel = new byte[ras.Size]; ras.AsStreamForRead().Read(pngPixel, 0, (int)ras.Size); //DB 등록 ThumbnailDAO.InsertThumbnail(funcGetThumbnail.Invoke(pngPixel)); } }
//원드라이브로 부터 썸네일로 이미지를 다운로드 받아, //NetworItemInfo에 이미지를 로딩 시킨후 DB에 캐쉬로 저장한다. private async Task StoreImageFromWeb(NetworkItemInfo networkItem, Microsoft.OneDrive.Sdk.Thumbnail itemThumb) { if (itemThumb != null) { try { var webReq = System.Net.WebRequest.Create(itemThumb.Url); await GalaSoft.MvvmLight.Threading.DispatcherHelper.RunAsync(async() => { using (var webRes = await webReq.GetResponseAsync()) { using (var imageStream = webRes.GetResponseStream()) { WriteableBitmap wb = await BitmapFactory.FromStream(imageStream); networkItem.ImageItemsSource = wb; using (InMemoryRandomAccessStream newStream = new InMemoryRandomAccessStream()) { await wb.ToStream(newStream, BitmapEncoder.PngEncoderId); byte[] pngData = new byte[newStream.Size]; await newStream.ReadAsync(pngData.AsBuffer(), (uint)pngData.Length, InputStreamOptions.None); //DB 등록 ThumbnailDAO.InsertThumbnail(new Models.Thumbnail { Name = networkItem.Name, ParentPath = networkItem.ParentFolderPath, Size = (ulong)networkItem.Size, RunningTime = networkItem.Duration, CreatedDateTime = networkItem.Modified, ThumbnailData = pngData }); } } } }); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } }
private async void LoadFilesAsync(StorageItemInfo fi) { if (fi != null) { string nonGroupName = ResourceLoader.GetForCurrentView().GetString("List/File/Text"); ///파일 로딩 표시기 실행 IsLoadingFiles = true; //폴더 로딩 표시기 정지 IsLoadingFolders = false; await ThreadPool.RunAsync(async (handler) => { StorageFolder currentFolder = await fi.GetStorageFolderAsync(); if (currentFolder != null) { var queryResult = currentFolder.CreateFileQueryWithOptions(_VideoFileQueryOptions); var list = await queryResult.GetFilesAsync(); if (list.Any()) { //썸네일 캐시 로드 ThumbnailDAO.LoadThumnailInFolder(fi.Path, _ThumbnailListInCurrentFolder); //아이템을 정렬하여 화면에 표시 await LoadItemsAsync(list.Select(x => new StorageItemInfo(x) { Tapped = FileTapped, RightTapped = FileRightTapped, Holding = FileHolding, IsOrderByName = (_Sort == SortType.Name || _Sort == SortType.NameDescending) }), list.Count, nonGroupName, true, 9); } } await DispatcherHelper.RunAsync(() => { IsLoadingFiles = false; }); }); } else { IsLoadingFolders = false; } }
private void ClearThumbnailCacheTapped(object sender, TappedRoutedEventArgs e) { ThumbnailDAO.DeletePastPeriodThumbnail(0); ThumbnailRetentionSize = ThumbnailDAO.GetThumbnailRetentionSize(); }
private void Loaded(object sender, RoutedEventArgs e) { ThumbnailRetentionSize = ThumbnailDAO.GetThumbnailRetentionSize(); }
private async void LoadExtraInfoAsync(PlayListFile playListFile) { //썸네일 및 사이즈 등 추가 데이터 로드 await Task.Factory.StartNew(async() => { var storageItem = await playListFile.GetStorageFileAsync(); if (storageItem != null) { if (playListFile.Name != storageItem.Name) { //이름 변경 playListFile.Name = storageItem.Name; //표시 이름 갱신 playListFile.SetDisplayName(); } playListFile.DateCreated = storageItem.DateCreated; System.Diagnostics.Debug.WriteLine(storageItem.Path); var basicProperties = await storageItem.GetBasicPropertiesAsync(); playListFile.Size = basicProperties.Size; List <Thumbnail> thumbnailList = new List <Thumbnail>(); //기간 지난 썸네일 캐시 삭제 ThumbnailDAO.DeletePastPeriodThumbnail(Settings.Thumbnail.RetentionPeriod); //썸네일 데이터 로드 Thumbnail thumbnail = ThumbnailDAO.GetThumnail(playListFile.ParentFolderPath, playListFile.Name); if (thumbnail != null) { thumbnailList.Add(thumbnail); } //썸네일 로드 LoadThumbnailAsync(playListFile as StorageItemInfo, thumbnailList, Settings.Thumbnail.UseUnsupportedLocalFile); //자막 여부 표시 try { List <string> tmp = new List <string>(); //DB에서 로드된 자막리스트를 다시 추가 if (playListFile.SubtitleList != null) { tmp.AddRange(playListFile.SubtitleList); } if (_SubtitlesList.ContainsKey(playListFile.ParentFolderPath)) { List <string> subtitles = _SubtitlesList[playListFile.ParentFolderPath]; //현재 폴더내에서 검색가능한 경우, 발견된 자막리스트를 추가 if (subtitles != null && subtitles.Count > 0) { tmp.AddRange(subtitles.Where(x => x.ToUpper().Contains(PathHelper.GetFullPathWithoutExtension(playListFile.Path).ToUpper())).ToList()); } } //모든 추가된 자막리스트로 교체 playListFile.SubtitleList = tmp.Distinct().ToList(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } }); //System.Diagnostics.Debug.WriteLine("재생목록 ExtraInfo 로드완료"); }
private async void LoadFoldersAsync(StorageItemInfo fi) { var groupName = ResourceLoader.GetForCurrentView().GetString("List/Folder/Text"); var mru = StorageApplicationPermissions.MostRecentlyUsedList; //키에 해당되는 모든 데이터 삭제 var removeList = mru.Entries.Where(x => x.Metadata.StartsWith(LastestMediaServerFolder)).ToArray(); foreach (var entry in removeList) { mru.Remove(entry.Token); } if (fi != null) { var folder = await fi.GetStorageFolderAsync(); if (folder != null && !_FolderStack.Contains(folder)) { _FolderStack.Push(folder); } //탭된 폴더 저장 var fullPath = _FolderStack.Select(x => x.DisplayName).Aggregate((x, y) => y + "/" + x); mru.Add(folder, LastestMediaServerFolder + fullPath); } CurrentFolderInfo = fi; _CurrentSubtitleFileList = null; IsLoadingFolders = true; var isOrderByName = _Sort == SortType.Name || _Sort == SortType.NameDescending; //모든 자식 요소 삭제 StorageItemGroupSource.Clear(); _ThumbnailListInCurrentFolder.Clear(); //기간 지난 썸네일 캐시 삭제 ThumbnailDAO.DeletePastPeriodThumbnail(Settings.Thumbnail.RetentionPeriod); if (fi == null) { await ThreadPool.RunAsync(async handler => { var dlna = KnownFolders.MediaServerDevices; var dlnaFolders = await dlna.GetFoldersAsync(); //DLNA 루트 폴더 로딩 var rootFolderList = dlnaFolders.Select(s => new StorageItemInfo(s) { DateCreated = s.DateCreated, Tapped = FolderTapped, RightTapped = FolderRightTapped, Holding = FolderHolding, IsOrderByName = isOrderByName, SubType = SubType.RootFolder }).TakeWhile(s => { s.SetDisplayName(); return(true); });; await LoadItemsAsync(rootFolderList, rootFolderList.Count(), groupName, false, 2); await DispatcherHelper.RunAsync(() => { //폴더 로딩 표시기 정지 IsLoadingFolders = false; //정렬 옵션 표시 ShowOrderBy = rootFolderList.Count() > 0; }); }); //뒤로버튼 상태 변경 Frame rootFrame = Window.Current.Content as Frame; if (rootFrame != null && !rootFrame.CanGoBack) { SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed; } //위로 버튼 비활성화 VisibleToUpper = false; } else { //위로버튼 활성화 VisibleToUpper = true; await ThreadPool.RunAsync(async handler => { if (Settings.General.UseHardwareBackButtonWithinVideo) { await DispatcherHelper.RunAsync(() => SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible); } var lastStorageFolder = await fi.GetStorageFolderAsync(); if (lastStorageFolder != null) { IReadOnlyList <StorageFolder> folderList = null; try { //부모에 접근 권한이 있는 경우이므로 해당 부모의 자식 폴더 및 파일 로드 folderList = await lastStorageFolder.GetFoldersAsync(); if (folderList.Count > 0) { await LoadItemsAsync(folderList.Select(x => new StorageItemInfo(x) { Tapped = FolderTapped, RightTapped = FolderRightTapped, Holding = FolderHolding, RootPath = fi.RootPath, IsOrderByName = isOrderByName }), folderList.Count, groupName, false, 2); } DispatcherHelper.CheckBeginInvokeOnUI(() => { //파일 리스트업 LoadFilesAsync(fi); }); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("폴더 로드 실패 : " + e.Message); if (e is OperationCanceledException) { //폴더 로딩이 취소됨 System.Diagnostics.Debug.WriteLine(fi.Path + " 폴더내의 자식 폴더 로딩이 취소됨"); } } } else { DispatcherHelper.CheckBeginInvokeOnUI(() => { LoadFoldersAsync(null); }); } }); } }
private async void SetExtraPropertiesAsync(StorageItemInfo itemInfo) { if (itemInfo.IsFile) { //파일 용량 조회 var file = await itemInfo.GetStorageFileAsync(); if (file != null) { //System.Diagnostics.Debug.WriteLine(file.DisplayName); var bi = await file.GetBasicPropertiesAsync(); //파일 크기 설정 itemInfo.Size = bi.Size; //썸네일 로드 this.LoadThumbnailAsync(itemInfo, _ThumbnailListInCurrentFolder, Settings.Thumbnail.UseUnsupportedDLNAFile); //자막 목록 설정 if (_CurrentSubtitleFileList != null && _CurrentSubtitleFileList.Any()) { itemInfo.SubtitleList = _CurrentSubtitleFileList.Where(x => x.Contains(System.IO.Path.GetFileNameWithoutExtension(itemInfo.Name).ToUpper())).ToList(); } } } else { var folder = await itemInfo.GetStorageFolderAsync(); if (folder != null) { itemInfo.DateCreated = folder.DateCreated; //비디오 파일 갯수를 알아내기 위한 필터링 옵션 var queryResult = folder.CreateFileQueryWithOptions(_VideoFileQueryOptions); itemInfo.FileCount = (int)await queryResult.GetItemCountAsync(); var folderCount = await folder.CreateFolderQuery().GetItemCountAsync(); if (itemInfo.FileCount > 0) { itemInfo.FileCountDescription = itemInfo.FileCount.ToString() + (folderCount > 0 ? "+" : string.Empty); } else { itemInfo.FileCountDescription = "0" + (folderCount > 0 ? "*" : string.Empty); } if (itemInfo.FileCount > 0) { var fileList = await queryResult.GetFilesAsync(); List <ImageSource> imageSourceList = new List <ImageSource>(); List <Thumbnail> thumbnailList = new List <Thumbnail>(); ThumbnailDAO.LoadThumnailInFolder(itemInfo.Path, thumbnailList); for (int i = 0; i < fileList.Count; i++) { //썸네일 로드 var imgSrc = await GetThumbnailAsync(fileList[i], thumbnailList, Settings.Thumbnail.UseUnsupportedDLNAFolder); if (imgSrc != null) { imageSourceList.Add(imgSrc); } //4장의 이미지를 채우지 못할 것으로 확신되거나, 이미 4장을 채운경우 정지 if (((imageSourceList.Count > 0 && imageSourceList.Count >= 4) || (itemInfo.FileCount - (i + 1) + imageSourceList.Count < 4)) && imageSourceList.Count > 0) { break; } } itemInfo.ImageItemsSource = imageSourceList; } else if (!_FolderStack.Any()) { //NAS아이콘 추출 ImageSource imageSource = null; var thumb = await folder.GetThumbnailAsync(ThumbnailMode.SingleItem); if (thumb?.Type == ThumbnailType.Image) { //썸네일 설정 await DispatcherHelper.RunAsync(() => { var bi = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); bi.SetSource(thumb); imageSource = bi; itemInfo.IsFullFitImage = false; itemInfo.ImageItemsSource = imageSource; }); } } } } }
private async Task LoadOneDriveFoldersAsync() { if (_CancellationTokenSource != null) { //썸네일 로드 실행전 이전 요청을 취소시킴 _CancellationTokenSource.Cancel(); } if (_CancellationTokenSource == null || _CancellationTokenSource.IsCancellationRequested) { _CancellationTokenSource = new CancellationTokenSource(); } _CurrentSubtitleFileList = null; //모든 자식 요소 삭제 NetworkItemGroupSource.Clear(); //로딩 표시 IsLoadingFolders = true; IsLoadingFiles = true; var folderGroupName = ResourceLoader.GetForCurrentView().GetString("List/Folder/Text"); var fileGroupName = ResourceLoader.GetForCurrentView().GetString("List/File/Text"); var isOrderByName = _Sort == SortType.Name || _Sort == SortType.NameDescending; string path = string.Join("/", pathStack.Select(x => x.Name).Reverse()); //경로를 타이틀 영역에 표시 DisplayCurrentPath = path; await ThreadPool.RunAsync(async handler => { try { IItemChildrenCollectionPage page = null; //var suffixed = MediaFileSuffixes.VIDEO_SUFFIX.Union(MediaFileSuffixes.CLOSED_CAPTION_SUFFIX); //var endswithFilter = string.Join(" or ", suffixed.Select(s => $"endswith(name, '{s}')")); var filterString = "folder ne null or (file ne null and image eq null and audio eq null)"; var sortString = _Sort == SortType.Name ? "name" : _Sort == SortType.NameDescending ? "name desc" : _Sort == SortType.CreatedDate ? "lastModifiedDateTime" : "lastModifiedDateTime desc"; if (pathStack.Any()) { //var itemRequest = OneDriveClient.Drive.Items[networkItem.Id].Children.Request();// new List<Option> { new QueryOption("filter", "folder ne null or video ne null or (file ne null and image eq null and audio eq null)") }); var itemRequest = OneDriveClient.Drive.Root.ItemWithPath(path).Children.Request(); page = await itemRequest.Filter(filterString) .Expand("thumbnails(select=medium)") .OrderBy(sortString) .GetAsync(); } else { var itemRequest = OneDriveClient.Drive.Root.Children.Request();//.Expand("thumbnails,children(expand=thumbnails)"); page = await itemRequest.Filter(filterString) .Expand("thumbnails(select=medium)") .OrderBy(sortString) .GetAsync(); } //상위 버튼 및 하드웨어 백버튼 변경 처리 ChangeToUpperAndBackButton(); _ThumbnailListInCurrentFolder.Clear(); //기간 지난 썸네일 캐시 삭제 ThumbnailDAO.DeletePastPeriodThumbnail(Settings.Thumbnail.RetentionPeriod); //썸네일 캐시 (이미지 바이트 데이터 제외)를 로드 LoadThumbnailMetadataInFolder(page.CurrentPage); var ffList = page.CurrentPage.Select(x => x.ToNetworkItemInfo(NetworkItemTapped, NetworkItemRightTapped, NetworkItemHolding, isOrderByName)); var folderList = ffList.Where(x => !x.IsFile).ToList(); await LoadBatchOneDriveFolderAsync(folderList, folderGroupName); await GalaSoft.MvvmLight.Threading.DispatcherHelper.RunAsync(() => IsLoadingFolders = false); var fileList = ffList.Where(x => x.IsFile).ToList(); await LoadBatchOneDriveFilesAsync(fileList, fileGroupName); await GalaSoft.MvvmLight.Threading.DispatcherHelper.RunAsync(() => IsLoadingFiles = false); //페이징 처리 await Task.Factory.StartNew(async() => { //폴더 로딩 표시기 시작 await GalaSoft.MvvmLight.Threading.DispatcherHelper.RunAsync(() => { IsLoadingFolders = true; IsLoadingFiles = true; }); while (page.NextPageRequest != null) { //다음 페이지 패치 page = await page.NextPageRequest.GetAsync(); //썸네일 캐시 (이미지 바이트 데이터 제외)를 로드 LoadThumbnailMetadataInFolder(page.CurrentPage); ffList = page.CurrentPage.Select(x => x.ToNetworkItemInfo(NetworkItemTapped, NetworkItemRightTapped, NetworkItemHolding, isOrderByName)); folderList = ffList.Where(x => !x.IsFile).ToList(); await LoadBatchOneDriveFolderAsync(folderList, folderGroupName); fileList = ffList.Where(x => x.IsFile).ToList(); await LoadBatchOneDriveFilesAsync(fileList, fileGroupName); } //폴더 로딩 표시기 정지 await GalaSoft.MvvmLight.Threading.DispatcherHelper.RunAsync(() => { IsLoadingFolders = false; IsLoadingFiles = false; }); }); } catch (Exception) { GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(async() => { await DisconnectOneDriveServer(true); }); } }); }