public async Task PrepareSizeDataAsync() { ulong TotalSize = 0; foreach (string Path in FromPath) { switch (await FileSystemStorageItemBase.OpenAsync(Path)) { case FileSystemStorageFolder Folder: { TotalSize += await Folder.GetFolderSizeAsync(); break; } case FileSystemStorageFile File: { TotalSize += File.SizeRaw; break; } } } Calculator = new ProgressCalculator(TotalSize); }
private static async Task <string> MakeSureCreateFolderHelperAsync(string Path) { switch (await FileSystemStorageItemBase.OpenAsync(Path)) { case FileSystemStorageFile: { if (await FileSystemStorageItemBase.CreateAsync(Path, StorageItemTypes.Folder, CreateOption.GenerateUniqueName) is FileSystemStorageFolder NewFolder) { return(NewFolder.Path); } else { throw new UnauthorizedAccessException("Could not create folder"); } } default: { if (await FileSystemStorageItemBase.CreateAsync(Path, StorageItemTypes.Folder, CreateOption.OpenIfExist) is FileSystemStorageFolder) { return(Path); } else { throw new UnauthorizedAccessException("Could not create folder"); } } } }
public static async Task <bool> CheckIfNeedToUpdate() { try { if (await FileSystemStorageItemBase.OpenAsync(ApplicationData.Current.TemporaryFolder.Path) is FileSystemStorageFolder TempFolder) { IEnumerable <FileSystemStorageItemBase> AllPreviousPictureList = await TempFolder.GetChildItemsAsync(false, false, Filter : ItemFilters.File, AdvanceFilter : (Name) => Name.StartsWith("BingDailyPicture_Cache", StringComparison.OrdinalIgnoreCase)); if (AllPreviousPictureList.All((Item) => DateTime.TryParseExact(Regex.Match(Item.Name, @"(?<=\[)(.+)(?=\])").Value, "yyyy-MM-dd HH-mm-ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out DateTime LastUpdateDate) && LastUpdateDate < DateTime.Now.Date)) { foreach (FileSystemStorageItemBase ToDelete in AllPreviousPictureList) { await ToDelete.DeleteAsync(true); } return(true); } else { return(false); } } else { return(false); } }
public static async Task ExtractGZipAsync(IEnumerable <FileSystemStorageFile> FileList, ProgressChangedEventHandler ProgressHandler = null) { ulong TotalSize = 0; ulong CurrentPosition = 0; foreach (FileSystemStorageFile File in FileList) { TotalSize += File.SizeRaw; } if (TotalSize == 0) { return; } if (await FileSystemStorageItemBase.OpenAsync(Path.GetDirectoryName(FileList.First().Path)).ConfigureAwait(true) is FileSystemStorageFolder NewFolder) { foreach (FileSystemStorageFile File in FileList) { await ExtractGZipAsync(NewFolder, File, (s, e) => { ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((e.ProgressPercentage *Convert.ToDouble(File.SizeRaw) + CurrentPosition * 100) / TotalSize), null)); }).ConfigureAwait(true); CurrentPosition += File.SizeRaw; } } else { throw new UnauthorizedAccessException(); } }
public static async Task ExtractBZip2Async(string Source, string NewDirectoryPath, ProgressChangedEventHandler ProgressHandler = null) { if (await FileSystemStorageItemBase.OpenAsync(Source) is FileSystemStorageFile File) { await ExtractBZip2Async(File, NewDirectoryPath, ProgressHandler); } else { throw new FileNotFoundException("Could not found the file path"); } }
public static async Task CreateGzipAsync(string Source, string NewZipPath, CompressionLevel ZipLevel, ProgressChangedEventHandler ProgressHandler = null) { if (await FileSystemStorageItemBase.OpenAsync(Source) is FileSystemStorageFile File) { await CreateGzipAsync(File, NewZipPath, ZipLevel, ProgressHandler); } else { throw new FileNotFoundException("Could not found the file path"); } }
public static async Task CreateZipAsync(IEnumerable <string> SourceItemGroup, string NewZipPath, CompressionLevel ZipLevel, CompressionAlgorithm Algorithm, ProgressChangedEventHandler ProgressHandler = null) { List <FileSystemStorageItemBase> TransformList = new List <FileSystemStorageItemBase>(); foreach (string Path in SourceItemGroup) { if (await FileSystemStorageItemBase.OpenAsync(Path) is FileSystemStorageItemBase Item) { TransformList.Add(Item); } else { throw new FileNotFoundException("Could not found the file or path is a directory"); } } await CreateZipAsync(TransformList, NewZipPath, ZipLevel, Algorithm, ProgressHandler); }
private async void Modified(string Path) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() => { try { await Locker.WaitAsync(); try { if (CurrentLocation == System.IO.Path.GetDirectoryName(Path)) { if (await FileSystemStorageItemBase.OpenAsync(Path) is FileSystemStorageItemBase ModifiedItem) { PathConfiguration Config = await SQLite.Current.GetPathConfigurationAsync(CurrentLocation); if (CurrentCollection.FirstOrDefault((Item) => Item.Path.Equals(Path, StringComparison.OrdinalIgnoreCase)) is FileSystemStorageItemBase OldItem) { if (ModifiedItem.GetType() == OldItem.GetType()) { await OldItem.RefreshAsync(); } else { CurrentCollection.Remove(OldItem); if (!SettingControl.IsDisplayProtectedSystemItems || !ModifiedItem.IsSystemItem) { if ((ModifiedItem is IHiddenStorageItem && SettingControl.IsDisplayHiddenItem) || ModifiedItem is not IHiddenStorageItem) { if (CurrentCollection.Any()) { int Index = SortCollectionGenerator.SearchInsertLocation(CurrentCollection, ModifiedItem, Config.SortTarget.GetValueOrDefault(), Config.SortDirection.GetValueOrDefault()); if (Index >= 0) { CurrentCollection.Insert(Index, ModifiedItem); } else { CurrentCollection.Add(ModifiedItem); } } else { CurrentCollection.Add(ModifiedItem); } } } } } else if (ModifiedItem is not IHiddenStorageItem) { if (CurrentCollection.Any()) { int Index = SortCollectionGenerator.SearchInsertLocation(CurrentCollection, ModifiedItem, Config.SortTarget.GetValueOrDefault(), Config.SortDirection.GetValueOrDefault()); if (Index >= 0) { CurrentCollection.Insert(Index, ModifiedItem); } else { CurrentCollection.Add(ModifiedItem); } } else { CurrentCollection.Add(ModifiedItem); } } } } } finally { Locker.Release(); } } catch (Exception ex) { LogTracer.Log(ex, $"{ nameof(StorageAreaWatcher)}: Modify item in collection failed"); } });
public static async Task ExtractAllAsync(IEnumerable <string> SourceItemGroup, string BaseDestPath, bool CreateFolder, ProgressChangedEventHandler ProgressHandler) { ulong TotalSize = 0; ulong CurrentPosition = 0; List <FileSystemStorageFile> TransformList = new List <FileSystemStorageFile>(); foreach (string FileItem in SourceItemGroup) { if (await FileSystemStorageItemBase.OpenAsync(FileItem).ConfigureAwait(false) is FileSystemStorageFile File) { TransformList.Add(File); TotalSize += File.SizeRaw; } else { throw new FileNotFoundException("Could not found the file or path is a directory"); } } if (TotalSize == 0) { return; } foreach (FileSystemStorageFile File in TransformList) { string DestPath = BaseDestPath; //如果解压到独立文件夹,则要额外创建目录 if (CreateFolder) { string NewFolderName = File.Name.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase) ? File.Name.Substring(0, File.Name.Length - 7) : (File.Name.EndsWith(".tar.bz2", StringComparison.OrdinalIgnoreCase) ? File.Name.Substring(0, File.Name.Length - 8) : Path.GetFileNameWithoutExtension(File.Name)); if (string.IsNullOrEmpty(NewFolderName)) { NewFolderName = Globalization.GetString("Operate_Text_CreateFolder"); } DestPath = await MakeSureCreateFolderHelperAsync(Path.Combine(BaseDestPath, NewFolderName)); } if (File.Name.EndsWith(".gz", StringComparison.OrdinalIgnoreCase) && !File.Name.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase)) { await ExtractGZipAsync(File, DestPath, (s, e) => { ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToUInt64(e.ProgressPercentage / 100d * File.SizeRaw)) * 100d / TotalSize), null)); }); CurrentPosition += Convert.ToUInt64(File.SizeRaw); ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(CurrentPosition * 100d / TotalSize), null)); } else if (File.Name.EndsWith(".bz2", StringComparison.OrdinalIgnoreCase) && !File.Name.EndsWith(".tar.bz2", StringComparison.OrdinalIgnoreCase)) { await ExtractBZip2Async(File, DestPath, (s, e) => { ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToUInt64(e.ProgressPercentage / 100d * File.SizeRaw)) * 100d / TotalSize), null)); }); CurrentPosition += Convert.ToUInt64(File.SizeRaw); ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(CurrentPosition * 100d / TotalSize), null)); } else { ReaderOptions ReadOptions = new ReaderOptions(); ReadOptions.ArchiveEncoding.Default = EncodingSetting; using (FileStream InputStream = await File.GetFileStreamFromFileAsync(AccessMode.Read)) using (IReader Reader = ReaderFactory.Open(InputStream, ReadOptions)) { Dictionary <string, string> DirectoryMap = new Dictionary <string, string>(); while (Reader.MoveToNextEntry()) { if (Reader.Entry.IsDirectory) { string DirectoryPath = Path.Combine(DestPath, Reader.Entry.Key.Replace("/", @"\").TrimEnd('\\')); string NewDirectoryPath = await MakeSureCreateFolderHelperAsync(DirectoryPath); if (!DirectoryPath.Equals(NewDirectoryPath, StringComparison.OrdinalIgnoreCase)) { DirectoryMap.Add(DirectoryPath, NewDirectoryPath); } } else { string[] PathList = (Reader.Entry.Key?.Replace("/", @"\")?.Split(@"\")) ?? Array.Empty <string>(); string LastFolder = DestPath; for (int i = 0; i < PathList.Length - 1; i++) { LastFolder = Path.Combine(LastFolder, PathList[i]); if (DirectoryMap.ContainsKey(LastFolder)) { LastFolder = DirectoryMap[LastFolder]; } string NewDirectoryPath = await MakeSureCreateFolderHelperAsync(LastFolder); if (!LastFolder.Equals(NewDirectoryPath, StringComparison.OrdinalIgnoreCase)) { DirectoryMap.Add(LastFolder, NewDirectoryPath); LastFolder = NewDirectoryPath; } } string DestFileName = Path.Combine(LastFolder, PathList.LastOrDefault() ?? Path.GetFileNameWithoutExtension(File.Name)); if (await FileSystemStorageItemBase.CreateAsync(DestFileName, StorageItemTypes.File, CreateOption.GenerateUniqueName).ConfigureAwait(false) is FileSystemStorageFile NewFile) { using (FileStream OutputStream = await NewFile.GetFileStreamFromFileAsync(AccessMode.Write)) using (EntryStream EntryStream = Reader.OpenEntryStream()) { await EntryStream.CopyToAsync(OutputStream, Reader.Entry.Size, (s, e) => { ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToUInt64(e.ProgressPercentage / 100d * Reader.Entry.CompressedSize)) * 100d / TotalSize), null)); }); CurrentPosition += Convert.ToUInt64(Reader.Entry.CompressedSize); ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(CurrentPosition * 100d / TotalSize), null)); } } } } } } } }
/// <summary> /// 启动WIFI连接侦听器 /// </summary> public async Task StartToListenRequest() { if (IsListeningThreadWorking) { return; } if (IsDisposed) { throw new ObjectDisposedException("This Object has been disposed"); } IsListeningThreadWorking = true; try { Listener.Start(); while (true) { HttpListenerContext Context = await Listener.GetContextAsync().ConfigureAwait(false); _ = Task.Factory.StartNew(async(Para) => { try { HttpListenerContext HttpContext = Para as HttpListenerContext; if (HttpContext.Request.Url.LocalPath.Substring(1) == FilePathMap.Key) { if (await FileSystemStorageItemBase.OpenAsync(FilePathMap.Value) is FileSystemStorageFile ShareFile) { using (FileStream Stream = await ShareFile.GetFileStreamFromFileAsync(AccessMode.Read)) { try { Context.Response.AddHeader("Pragma", "No-cache"); Context.Response.AddHeader("Cache-Control", "No-cache"); Context.Response.AddHeader("Content-Disposition", $"Attachment;filename={Uri.EscapeDataString(ShareFile.Name)}"); Context.Response.ContentLength64 = Stream.Length; Context.Response.ContentType = "application/octet-stream"; Stream.CopyTo(Context.Response.OutputStream); } catch (HttpListenerException ex) { LogTracer.Log(ex); } finally { Context.Response.Close(); } } } } else { string ErrorMessage = $"<html><head><title>Error 404 Bad Request</title></head><body><p style=\"font-size:50px\">HTTP ERROR 404</p><p style=\"font-size:40px\">{Globalization.GetString("WIFIShare_Error_Web_Content")}</p></body></html>"; Context.Response.StatusCode = 404; Context.Response.StatusDescription = "Bad Request"; Context.Response.ContentType = "text/html"; Context.Response.ContentEncoding = Encoding.UTF8; using (StreamWriter Writer = new StreamWriter(Context.Response.OutputStream, Encoding.UTF8)) { Writer.Write(ErrorMessage); } Context.Response.Close(); } } catch (Exception e) { LogTracer.Log(e); ThreadExitedUnexpectly?.Invoke(this, e); } }, Context, Cancellation.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current); } } catch (ObjectDisposedException) { IsListeningThreadWorking = false; } catch (Exception e) { IsListeningThreadWorking = false; ThreadExitedUnexpectly?.Invoke(this, e); } finally { Cancellation?.Dispose(); Cancellation = null; } }
public async Task InitializeAsync() { if (!IsInitialized) { try { switch (CurrentType) { case BackgroundBrushType.Picture: { string UriString = Convert.ToString(ApplicationData.Current.LocalSettings.Values["PictureBackgroundUri"]); if (!string.IsNullOrEmpty(UriString)) { BitmapImage Bitmap = new BitmapImage(); PictureBackgroundBrush.ImageSource = Bitmap; string PicturePath = Path.Combine(Package.Current.InstalledPath, UriString.Replace("ms-appx:///", string.Empty).Replace("/", @"\")); if (await FileSystemStorageItemBase.OpenAsync(PicturePath) is FileSystemStorageFile File) { using (IRandomAccessStream Stream = await File.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read)) { await Bitmap.SetSourceAsync(Stream); } PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BackgroundBrush))); } else { LogTracer.Log($"PicturePath is \"{PicturePath}\" but could not found, {nameof(BackgroundController.InitializeAsync)} is not finished"); } } else { LogTracer.Log($"PicturePath is empty, {nameof(BackgroundController.InitializeAsync)} is not finished"); } break; } case BackgroundBrushType.BingPicture: { if (await BingPictureDownloader.GetBingPictureAsync() is FileSystemStorageFile ImageFile) { BitmapImage Bitmap = new BitmapImage(); BingPictureBursh.ImageSource = Bitmap; using (IRandomAccessStream Stream = await ImageFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read)) { await Bitmap.SetSourceAsync(Stream); } PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BackgroundBrush))); } else { LogTracer.Log("Download Bing picture failed, BackgroundController.Initialize is not finished"); } break; } } } catch (Exception ex) { LogTracer.Log(ex, "Exception happend when loading image for background"); } finally { IsInitialized = true; } } }
public static async Task <FileSystemStorageFile> GetBingPictureAsync() { string Path = await GetDailyPhotoPath().ConfigureAwait(false); if (await FileSystemStorageItemBase.OpenAsync(System.IO.Path.Combine(ApplicationData.Current.LocalFolder.Path, "BingDailyPicture.jpg")) is FileSystemStorageFile ExistFile) { try { if (string.IsNullOrWhiteSpace(Path)) { return(ExistFile); } if (await CheckIfNeedToUpdate()) { if (await FileSystemStorageItemBase.CreateAsync(System.IO.Path.Combine(ApplicationData.Current.TemporaryFolder.Path, $"BingDailyPicture_Cache_[{DateTime.Now:yyyy-MM-dd HH-mm-ss}].jpg"), StorageItemTypes.File, CreateOption.GenerateUniqueName) is FileSystemStorageFile TempFile) { using (FileStream TempFileStream = await TempFile.GetFileStreamFromFileAsync(AccessMode.ReadWrite)) { HttpWebRequest Request = WebRequest.CreateHttp(new Uri($"https://www.bing.com{Path}")); Request.Timeout = 10000; Request.ReadWriteTimeout = 10000; using (WebResponse Response = await Request.GetResponseAsync()) using (Stream ResponseStream = Response.GetResponseStream()) { await ResponseStream.CopyToAsync(TempFileStream); } using (Stream FileStream = await ExistFile.GetFileStreamFromFileAsync(AccessMode.Read)) using (MD5 MD5Alg1 = MD5.Create()) using (MD5 MD5Alg2 = MD5.Create()) { Task <string> CalTask1 = MD5Alg1.GetHashAsync(FileStream); Task <string> CalTask2 = MD5Alg2.GetHashAsync(TempFileStream); string[] ResultArray = await Task.WhenAll(CalTask1, CalTask2); if (ResultArray[0] == ResultArray[1]) { return(ExistFile); } } TempFileStream.Seek(0, SeekOrigin.Begin); using (StorageStreamTransaction Transaction = await ExistFile.GetTransactionStreamFromFileAsync()) { await TempFileStream.CopyToAsync(Transaction.Stream.AsStreamForWrite()); await Transaction.CommitAsync(); } } } else { LogTracer.Log($"Could not create temp file as needed in {nameof(GetBingPictureAsync)}"); } return(ExistFile); } else { return(ExistFile); } } catch (Exception ex) { LogTracer.Log(ex, $"An error was threw in {nameof(GetBingPictureAsync)}"); return(ExistFile); } } else { try { if (string.IsNullOrWhiteSpace(Path)) { return(null); } if (await FileSystemStorageItemBase.CreateAsync(System.IO.Path.Combine(ApplicationData.Current.TemporaryFolder.Path, $"BingDailyPicture_Cache_[{DateTime.Now:yyyy-MM-dd HH-mm-ss}].jpg"), StorageItemTypes.File, CreateOption.GenerateUniqueName) is FileSystemStorageFile TempFile) { using (Stream TempFileStream = await TempFile.GetFileStreamFromFileAsync(AccessMode.ReadWrite)) { HttpWebRequest Request = WebRequest.CreateHttp(new Uri($"https://www.bing.com{Path}")); Request.Timeout = 10000; Request.ReadWriteTimeout = 10000; using (WebResponse Response = await Request.GetResponseAsync()) using (Stream ResponseStream = Response.GetResponseStream()) { await ResponseStream.CopyToAsync(TempFileStream); } if (await FileSystemStorageItemBase.CreateAsync(System.IO.Path.Combine(ApplicationData.Current.LocalFolder.Path, "BingDailyPicture.jpg"), StorageItemTypes.File, CreateOption.ReplaceExisting) is FileSystemStorageFile BingDailyPictureFile) { using (StorageStreamTransaction Transaction = await BingDailyPictureFile.GetTransactionStreamFromFileAsync()) { TempFileStream.Seek(0, SeekOrigin.Begin); await TempFileStream.CopyToAsync(Transaction.Stream.AsStreamForWrite()); await Transaction.CommitAsync(); } return(BingDailyPictureFile); } else { LogTracer.Log($"Could not create BingPicture file as needed in {nameof(GetBingPictureAsync)}"); return(null); } } } else { LogTracer.Log($"Could not create temp file as needed in {nameof(GetBingPictureAsync)}"); return(null); } } catch (Exception ex) { LogTracer.Log(ex, $"An error was threw in {nameof(GetBingPictureAsync)}"); return(null); } } }