private async Task Execute() { txtLog.Clear(); Logger.StartLogging(); ToggleUi(false); if (!VerifyInput()) { Logger.StopLogging(); ToggleUi(true); return; } var selectedPlugin = (PluginElement)cmbPlugins.SelectedItem; _batchProcessor.PluginId = selectedPlugin.IsEmpty ? Guid.Empty : selectedPlugin.Plugin.PluginId; _batchProcessor.ScanSubDirectories = chkSubDirectories.Checked; var sourceFileSystem = FileSystemFactory.CreatePhysicalFileSystem(txtSourcePath.Text, new StreamManager()); var destinationFileSystem = FileSystemFactory.CreatePhysicalFileSystem(txtDestinationPath.Text, new StreamManager()); await _batchProcessor.Process(sourceFileSystem, destinationFileSystem); ToggleUi(true); }
private void ExtractWith(IFileSystem sourceFileSystem, UPath filePath, Guid pluginId) { // Load file LoadResult loadResult; try { loadResult = pluginId == Guid.Empty ? _pluginManager.LoadFile(sourceFileSystem, filePath).Result : _pluginManager.LoadFile(sourceFileSystem, filePath, pluginId).Result; } catch (Exception e) { Console.WriteLine($"Batch Error: {filePath}: {e.Message}"); return; } if (!loadResult.IsSuccessful) { Console.WriteLine($"Batch Error: {filePath}: {loadResult.Message}"); return; } var absolutePath = (UPath)sourceFileSystem.ConvertPathToInternal(filePath); var destinationDirectory = absolutePath.GetDirectory() / absolutePath.GetName().Replace('.', '_'); var destinationFileSystem = FileSystemFactory.CreatePhysicalFileSystem(destinationDirectory, new StreamManager()); switch (loadResult.LoadedState.PluginState) { case IArchiveState archiveState: foreach (var afi in archiveState.Files) { var newFileStream = destinationFileSystem.OpenFile(afi.FilePath, FileMode.Create, FileAccess.Write); afi.GetFileData().Result.CopyTo(newFileStream); newFileStream.Close(); } break; case IImageState imageState: var index = 0; foreach (var img in imageState.Images) { var kanvasImage = new KanvasImage(imageState, img); kanvasImage.GetImage().Save(destinationDirectory + "/" + (img.Name ?? $"{index:00}") + ".png"); index++; } break; default: Console.WriteLine($"Batch Error: {filePath}: '{loadResult.LoadedState.PluginState.GetType().Name}' is not supported."); break; } _pluginManager.Close(loadResult.LoadedState); }
private void ExtractAllImage(UPath directoryPath) { var destinationFileSystem = FileSystemFactory.CreatePhysicalFileSystem(directoryPath, new StreamManager()); for (var i = 0; i < _imageState.Images.Count; i++) { var imageFileName = _imageState.Images[i].Name; if (string.IsNullOrEmpty(imageFileName)) { imageFileName = _stateInfo.FilePath.GetNameWithoutExtension() + $".{i:00}"; } ExtractImageInternal(new KanvasImage(_imageState, _imageState.Images[i]), destinationFileSystem, imageFileName + ".png"); } }
private void BatchExtract(UPath directory, string pluginIdArgument) { var pluginId = Guid.Empty; if (!string.IsNullOrEmpty(pluginIdArgument)) { if (!Guid.TryParse(pluginIdArgument, out pluginId)) { Console.WriteLine($"'{pluginIdArgument}' is not a valid plugin ID."); return; } } var sourceFileSystem = FileSystemFactory.CreatePhysicalFileSystem(directory, new StreamManager()); EnumerateFiles(sourceFileSystem).ToArray().AsParallel().ForAll(x => ExtractWith(sourceFileSystem, x, pluginId)); }
private void ExtractImage(string imageIndexArgument, UPath filePath) { if (!int.TryParse(imageIndexArgument, out var imageIndex)) { Console.WriteLine($"'{imageIndexArgument}' is not a valid number."); return; } if (imageIndex >= _imageState.Images.Count) { Console.WriteLine($"Index '{imageIndex}' was out of bounds."); return; } var destinationFileSystem = FileSystemFactory.CreatePhysicalFileSystem(filePath.GetDirectory(), new StreamManager()); ExtractImageInternal(new KanvasImage(_imageState, _imageState.Images[imageIndex]), destinationFileSystem, filePath.GetName()); }
private async Task BatchExtract(UPath directory, string pluginIdArgument) { var pluginId = Guid.Empty; if (!string.IsNullOrEmpty(pluginIdArgument)) { if (!Guid.TryParse(pluginIdArgument, out pluginId)) { Console.WriteLine($"'{pluginIdArgument}' is not a valid plugin ID."); return; } } var sourceFileSystem = FileSystemFactory.CreatePhysicalFileSystem(directory, new StreamManager()); var destinationFileSystem = FileSystemFactory.CreatePhysicalFileSystem(directory, new StreamManager()); _batchExtractor.ScanSubDirectories = true; await _batchExtractor.Process(sourceFileSystem, destinationFileSystem); }
public Task <LoadResult> LoadFile(string file, Guid pluginId, LoadFileContext loadFileContext) { // 1. Get UPath var path = new UPath(file); // If file is already loaded if (IsLoaded(path)) { return(Task.FromResult(new LoadResult(GetLoadedFile(path)))); } // 2. Create file system action var fileSystemAction = new Func <IStreamManager, IFileSystem>(streamManager => FileSystemFactory.CreatePhysicalFileSystem(path.GetDirectory(), streamManager)); // 3. Load file // Physical files don't have a parent, if loaded like this return(LoadFile(fileSystemAction, path.GetName(), null, pluginId, loadFileContext)); }
private async Task Execute() { log.Text = string.Empty; if (!VerifyInput()) { return; } ToggleUi(false); var selectedPlugin = (PluginElement)plugins.SelectedValue; _batchProcessor.PluginId = selectedPlugin.IsEmpty ? Guid.Empty : selectedPlugin.Plugin.PluginId; _batchProcessor.ScanSubDirectories = subDirectoryBox.Checked ?? false; var sourceFileSystem = FileSystemFactory.CreatePhysicalFileSystem(selectedInputPath.Text, new StreamManager()); var destinationFileSystem = FileSystemFactory.CreatePhysicalFileSystem(selectedOutputPath.Text, new StreamManager()); await _batchProcessor.Process(sourceFileSystem, destinationFileSystem); ToggleUi(true); }
/// <summary> /// Creates an <see cref="IFileSystem"/> to save the files to. /// </summary> /// <param name="stateInfo">The state from which to create the file system.</param> /// <param name="savePath">The path for the root destination.</param> /// <returns></returns> private IFileSystem CreateDestinationFileSystem(IStateInfo stateInfo, UPath savePath) { return(stateInfo.FilePath == savePath? stateInfo.FileSystem.Clone(stateInfo.StreamManager) : FileSystemFactory.CreatePhysicalFileSystem(savePath.GetDirectory(), stateInfo.StreamManager)); }
private async Task ReplaceDirectory(TreeGridItem item) { var itemPath = GetAbsolutePath(item); var filePaths = _archiveFileSystem.EnumerateAllFiles(itemPath).Select(x => x.GetSubDirectory(itemPath).ToRelative()).ToArray(); if (filePaths.Length <= 0) { _communicator.ReportStatus(true, "No files to replace."); return; } // Select folder var replacePath = SelectFolder(); if (replacePath.IsNull || replacePath.IsEmpty) { _communicator.ReportStatus(false, "No folder selected."); return; } // Extract elements _communicator.ReportStatus(true, string.Empty); var sourceFileSystem = FileSystemFactory.CreatePhysicalFileSystem(replacePath, _stateInfo.StreamManager); _progress.StartProgress(); await _asyncOperation.StartAsync(cts => { var count = 0; var replaceState = _stateInfo.PluginState as IReplaceFiles; foreach (var filePath in filePaths) { if (cts.IsCancellationRequested) { break; } _progress.ReportProgress("Replace files", count++, filePaths.Length); var afi = ((AfiFileEntry)_archiveFileSystem.GetFileEntry(itemPath / filePath)).ArchiveFileInfo; if (IsFileLocked(afi, true)) { continue; } if (!sourceFileSystem.FileExists(filePath)) { continue; } var currentFileStream = sourceFileSystem.OpenFile(filePath); replaceState?.ReplaceFile(afi, currentFileStream); AddChangedDirectory(afi.FilePath.GetDirectory()); } }); _progress.ReportProgress("Replace files", 1, 1); _progress.FinishProgress(); if (_asyncOperation.WasCancelled) { _communicator.ReportStatus(false, "File replacement cancelled."); } else { _communicator.ReportStatus(true, "File(s) replaced successfully."); } UpdateFiles(GetAbsolutePath((TreeGridItem)folderView.SelectedItem)); UpdateDirectories(); _communicator.Update(true, false); }
private async Task ReplaceFiles(IList <IArchiveFileInfo> files) { if (files.Count <= 0) { _communicator.ReportStatus(true, "No files to replace."); return; } // Select destination UPath replaceDirectory; UPath replaceFileName; if (files.Count == 1) { var selectedPath = SelectFile(files[0].FilePath.GetName()); if (selectedPath.IsNull || selectedPath.IsEmpty) { _communicator.ReportStatus(false, "No file selected."); return; } replaceDirectory = selectedPath.GetDirectory(); replaceFileName = selectedPath.GetName(); } else { var selectedPath = SelectFolder(); if (selectedPath.IsNull || selectedPath.IsEmpty) { _communicator.ReportStatus(false, "No folder selected."); return; } replaceDirectory = selectedPath; replaceFileName = UPath.Empty; } // Extract elements _communicator.ReportStatus(true, string.Empty); var sourceFileSystem = FileSystemFactory.CreatePhysicalFileSystem(replaceDirectory, _stateInfo.StreamManager); _progress.StartProgress(); await _asyncOperation.StartAsync(cts => { var count = 0; var replaceState = _stateInfo.PluginState as IReplaceFiles; foreach (var file in files) { if (cts.IsCancellationRequested) { break; } _progress.ReportProgress("Replace files", count++, files.Count); if (IsFileLocked(file, true)) { continue; } var filePath = replaceFileName.IsEmpty ? file.FilePath.GetName() : replaceFileName; if (!sourceFileSystem.FileExists(filePath)) { continue; } var currentFileStream = sourceFileSystem.OpenFile(filePath); replaceState?.ReplaceFile(file, currentFileStream); AddChangedDirectory(file.FilePath.GetDirectory()); } }); _progress.ReportProgress("Replace files", 1, 1); _progress.FinishProgress(); if (_asyncOperation.WasCancelled) { _communicator.ReportStatus(false, "File replacement cancelled."); } else { _communicator.ReportStatus(true, "File(s) replaced successfully."); } UpdateFiles(GetAbsolutePath((TreeGridItem)folderView.SelectedItem)); UpdateDirectories(); _communicator.Update(true, false); }
private async Task ExtractDirectory(TreeGridItem item) { var itemPath = GetAbsolutePath(item); var filePaths = _archiveFileSystem.EnumerateAllFiles(itemPath).Select(x => x.GetSubDirectory(itemPath).ToRelative()).ToArray(); if (filePaths.Length <= 0) { _communicator.ReportStatus(true, "No files to extract."); return; } // Select folder var extractPath = SelectFolder(); if (extractPath.IsNull || extractPath.IsEmpty) { _communicator.ReportStatus(false, "No folder selected."); return; } // Extract elements _communicator.ReportStatus(true, string.Empty); var subFolder = item == folders[0] ? GetRootName() : GetAbsolutePath(item).ToRelative(); var destinationFileSystem = FileSystemFactory.CreatePhysicalFileSystem(extractPath / subFolder, _stateInfo.StreamManager); _progress.StartProgress(); await _asyncOperation.StartAsync(async cts => { var count = 0; foreach (var filePath in filePaths) { if (cts.IsCancellationRequested) { break; } _progress.ReportProgress("Extract files", count++, filePaths.Length); var afi = ((AfiFileEntry)_archiveFileSystem.GetFileEntry(itemPath / filePath)).ArchiveFileInfo; if (IsFileLocked(afi, false)) { continue; } Stream newFileStream; try { newFileStream = destinationFileSystem.OpenFile(filePath, FileMode.Create, FileAccess.Write); } catch (IOException) { continue; } var currentFileStream = await afi.GetFileData(); currentFileStream.CopyTo(newFileStream); newFileStream.Close(); } }); _progress.ReportProgress("Extract files", 1, 1); _progress.FinishProgress(); if (_asyncOperation.WasCancelled) { _communicator.ReportStatus(false, "File extraction cancelled."); } else { _communicator.ReportStatus(true, "File(s) extracted successfully."); } }
private async Task ExtractFiles(IList <IArchiveFileInfo> files) { if (files.Count <= 0) { _communicator.ReportStatus(true, "No files to extract."); return; } // Select folder var extractPath = SelectFolder(); if (extractPath.IsNull || extractPath.IsEmpty) { _communicator.ReportStatus(false, "No folder selected."); return; } // Extract elements _communicator.ReportStatus(true, string.Empty); var destinationFileSystem = FileSystemFactory.CreatePhysicalFileSystem(extractPath, _stateInfo.StreamManager); _progress.StartProgress(); await _asyncOperation.StartAsync(async cts => { var count = 0; foreach (var file in files) { if (cts.IsCancellationRequested) { break; } _progress.ReportProgress("Extract files", count++, files.Count); if (IsFileLocked(file, false)) { continue; } Stream newFileStream; try { newFileStream = destinationFileSystem.OpenFile(file.FilePath.GetName(), FileMode.Create, FileAccess.Write); } catch (IOException) { continue; } var currentFileStream = await file.GetFileData(); currentFileStream.CopyTo(newFileStream); newFileStream.Close(); } }); _progress.ReportProgress("Extract files", 1, 1); _progress.FinishProgress(); if (_asyncOperation.WasCancelled) { _communicator.ReportStatus(false, "File extraction cancelled."); } else { _communicator.ReportStatus(true, "File(s) extracted successfully."); } }
private async Task AddFiles(TreeGridItem item) { // Select folder var selectedPath = SelectFolder(); if (selectedPath.IsNull || selectedPath.IsEmpty) { _communicator.ReportStatus(false, "No folder selected."); return; } // Add elements var subFolder = GetAbsolutePath(item); var sourceFileSystem = FileSystemFactory.CreatePhysicalFileSystem(selectedPath, _stateInfo.StreamManager); var elements = sourceFileSystem.EnumerateAllFiles(UPath.Root).ToArray(); if (elements.Length <= 0) { _communicator.ReportStatus(false, "No files to add."); return; } _communicator.ReportStatus(true, string.Empty); _progress.StartProgress(); await _asyncOperation.StartAsync(cts => { var count = 0; foreach (var filePath in elements) { if (cts.IsCancellationRequested) { break; } _progress.ReportProgress("Add files", count++, elements.Length); // TODO: This will currently copy files to memory, instead of just using a reference to any more memory efficient stream (like FileStream) var createdFile = _archiveFileSystem.OpenFile(subFolder / filePath.ToRelative(), FileMode.Create, FileAccess.Write); var sourceFile = sourceFileSystem.OpenFile(filePath); sourceFile.CopyTo(createdFile); sourceFile.Close(); } }); _progress.ReportProgress("Add files", 1, 1); _progress.FinishProgress(); if (_asyncOperation.WasCancelled) { _communicator.ReportStatus(false, "File adding cancelled."); } else { _communicator.ReportStatus(true, "File(s) added successfully."); } UpdateFiles(GetAbsolutePath((TreeGridItem)folderView.SelectedItem)); _communicator.Update(true, false); }
private async Task AddFiles(TreeGridItem item) { // Select folder var selectedPath = SelectFolder(); if (selectedPath.IsNull || selectedPath.IsEmpty) { _formInfo.FormCommunicator.ReportStatus(false, "No folder selected."); return; } // Add elements var subFolder = GetAbsolutePath(item); var sourceFileSystem = FileSystemFactory.CreatePhysicalFileSystem(selectedPath, _formInfo.StateInfo.StreamManager); var elements = sourceFileSystem.EnumerateAllFiles(UPath.Root).ToArray(); if (elements.Length <= 0) { _formInfo.FormCommunicator.ReportStatus(false, "No files to add."); return; } _formInfo.FormCommunicator.ReportStatus(true, string.Empty); _formInfo.Progress.StartProgress(); var filesNotAdded = false; await _asyncOperation.StartAsync(cts => { var count = 0; foreach (var filePath in elements) { if (cts.IsCancellationRequested) { break; } _formInfo.Progress.ReportProgress("Add files", count++, elements.Length); // Do not add file if it already exists // This would be replacement and is not part of this operation if (_archiveFileSystem.FileExists(subFolder / filePath.ToRelative())) { continue; } // TODO: This will currently copy files to memory, instead of just using a reference to any more memory efficient stream (like FileStream) Stream createdFile; try { // The plugin can throw if a file is not addable createdFile = _archiveFileSystem.OpenFile(subFolder / filePath.ToRelative(), FileMode.Create, FileAccess.Write); } catch (Exception e) { _formInfo.Logger.Fatal(e, "Could not add the file {0}", filePath); filesNotAdded = true; continue; } var sourceFile = sourceFileSystem.OpenFile(filePath); sourceFile.CopyTo(createdFile); sourceFile.Close(); } }); _formInfo.Progress.ReportProgress("Add files", 1, 1); _formInfo.Progress.FinishProgress(); if (_asyncOperation.WasCancelled) { _formInfo.FormCommunicator.ReportStatus(false, "File adding cancelled."); } else if (filesNotAdded) { _formInfo.FormCommunicator.ReportStatus(true, "Some file(s) could not be added successfully. Refer to the log for more information."); } else { _formInfo.FormCommunicator.ReportStatus(true, "File(s) added successfully."); } UpdateFiles(GetAbsolutePath((TreeGridItem)folderView.SelectedItem)); _formInfo.FormCommunicator.Update(true, false); }