Files
SabreTools/SabreTools.FileTypes/Folder.cs

406 lines
14 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using SabreTools.Core.Tools;
using SabreTools.Hashing;
2020-12-07 15:08:57 -08:00
using SabreTools.IO;
2024-04-24 13:45:38 -04:00
using SabreTools.IO.Extensions;
2024-10-24 00:36:44 -04:00
using SabreTools.IO.Logging;
2020-12-08 14:53:49 -08:00
namespace SabreTools.FileTypes
{
/// <summary>
/// Represents a folder for reading and writing
/// </summary>
public class Folder : BaseFile
{
#region Protected instance variables
/// <summary>
/// Hashes that are available for children
/// </summary>
protected HashType[] _hashTypes = [HashType.CRC32, HashType.MD5, HashType.SHA1];
/// <summary>
/// Set of children file objects
/// </summary>
2024-02-28 19:19:50 -05:00
protected List<BaseFile>? _children;
/// <summary>
/// Logging object
/// </summary>
protected Logger _logger;
/// <summary>
/// Static logger for static methods
/// </summary>
protected static Logger _staticLogger = new();
2020-08-28 20:46:12 -07:00
/// <summary>
/// Flag specific to Folder to omit Machine name from output path
/// </summary>
2025-01-04 20:24:56 -05:00
private readonly bool _writeToParent;
#endregion
#region Constructors
/// <summary>
2025-01-04 20:24:56 -05:00
/// Create a new Folder with no base file
/// </summary>
2020-08-28 20:46:12 -07:00
/// <param name="writeToParent">True to write directly to parent, false otherwise</param>
public Folder(bool writeToParent = false) : base()
{
2024-10-19 23:17:37 -04:00
_writeToParent = writeToParent;
_logger = new Logger(this);
}
/// <summary>
2025-01-04 20:24:56 -05:00
/// Create a new Folder from the given file
/// </summary>
2025-01-04 20:24:56 -05:00
/// <param name="filename">Name of the folder to use</param>
/// <param name="writeToParent">True to write directly to parent, false otherwise</param>
public Folder(string filename, bool writeToParent = false) : base(filename)
{
2025-01-04 20:24:56 -05:00
_writeToParent = writeToParent;
_logger = new Logger(this);
}
#endregion
#region Extraction
/// <summary>
/// Attempt to extract a file as an archive
/// </summary>
/// <param name="outDir">Output directory for archive extraction</param>
/// <returns>True if the extraction was a success, false otherwise</returns>
public virtual bool CopyAll(string outDir)
{
2024-02-28 19:19:50 -05:00
// If we have an invalid filename
2024-10-19 23:17:37 -04:00
if (Filename == null)
2024-02-28 19:19:50 -05:00
return false;
// Copy all files from the current folder to the output directory recursively
try
{
// Make sure the folders exist
2024-10-19 23:17:37 -04:00
Directory.CreateDirectory(Filename);
Directory.CreateDirectory(outDir);
2024-10-19 23:17:37 -04:00
DirectoryCopy(Filename, outDir, true);
}
catch (Exception ex)
{
_logger.Error(ex);
return false;
}
return true;
}
// https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
/// <summary>
/// Attempt to extract a file from an archive
/// </summary>
/// <param name="entryName">Name of the entry to be extracted</param>
/// <param name="outDir">Output directory for archive extraction</param>
/// <returns>Name of the extracted file, null on error</returns>
2024-02-28 19:19:50 -05:00
public virtual string? CopyToFile(string entryName, string outDir)
{
2024-02-28 19:19:50 -05:00
string? realentry = null;
2024-02-28 21:59:13 -05:00
2024-02-28 19:19:50 -05:00
// If we have an invalid filename
2024-10-19 23:17:37 -04:00
if (Filename == null)
2024-02-28 19:19:50 -05:00
return null;
// Copy single file from the current folder to the output directory, if exists
try
{
// Make sure the folders exist
2024-10-19 23:17:37 -04:00
Directory.CreateDirectory(Filename);
Directory.CreateDirectory(outDir);
// Get all files from the input directory
2024-10-19 23:17:37 -04:00
List<string> files = PathTool.GetFilesOrdered(Filename);
// Now sort through to find the first file that matches
2024-11-12 21:12:06 -05:00
string? match = files.Find(s => s.EndsWith(entryName));
// If we had a file, copy that over to the new name
2024-02-28 21:59:13 -05:00
if (!string.IsNullOrEmpty(match))
{
realentry = match;
File.Copy(match, Path.Combine(outDir, entryName));
}
}
catch (Exception ex)
{
_logger.Error(ex);
return realentry;
}
return realentry;
}
/// <summary>
/// Attempt to extract a stream from an archive
/// </summary>
/// <param name="entryName">Name of the entry to be extracted</param>
2024-07-15 21:37:38 -04:00
/// <returns>Stream representing the entry, null on error</returns>
public virtual (Stream?, string?) GetEntryStream(string entryName)
{
2024-02-28 19:19:50 -05:00
// If we have an invalid filename
2024-10-19 23:17:37 -04:00
if (Filename == null)
2024-02-28 19:19:50 -05:00
return (null, null);
// Copy single file from the current folder to the output directory, if exists
try
{
// Make sure the folders exist
2024-10-19 23:17:37 -04:00
Directory.CreateDirectory(Filename);
// Get all files from the input directory
2024-10-19 23:17:37 -04:00
List<string> files = PathTool.GetFilesOrdered(Filename);
// Now sort through to find the first file that matches
2024-11-12 21:12:06 -05:00
string? match = files.Find(s => s.EndsWith(entryName));
2024-07-16 14:58:04 -04:00
// If we had a file, open and return the stream
2024-02-28 21:59:13 -05:00
if (!string.IsNullOrEmpty(match))
{
2024-07-16 14:58:04 -04:00
var stream = File.OpenRead(match);
return (stream, match);
}
2024-07-16 14:58:04 -04:00
return (null, null);
}
catch (Exception ex)
{
_logger.Error(ex);
2024-07-16 14:58:04 -04:00
return (null, null);
}
}
#endregion
#region Information
/// <summary>
/// Set the hash type that can be included in children
/// </summary>
public void SetHashType(HashType hashType)
=> SetHashTypes([hashType]);
/// <summary>
/// Set the hash types that can be included in children
/// </summary>
public void SetHashTypes(HashType[] hashTypes)
=> _hashTypes = hashTypes;
/// <summary>
/// Generate a list of immediate children from the current folder
/// </summary>
/// <returns>List of BaseFile objects representing the found data</returns>
2024-02-28 19:19:50 -05:00
public virtual List<BaseFile>? GetChildren()
{
2024-02-28 19:19:50 -05:00
// If we have an invalid filename
2024-10-19 23:17:37 -04:00
if (Filename == null)
2024-02-28 19:19:50 -05:00
return null;
if (_children == null || _children.Count == 0)
{
2024-02-28 19:19:50 -05:00
_children = [];
2024-02-29 00:14:16 -05:00
#if NET20 || NET35
2024-10-19 23:17:37 -04:00
foreach (string file in Directory.GetFiles(Filename, "*"))
2024-02-28 21:59:13 -05:00
#else
2024-10-19 23:17:37 -04:00
foreach (string file in Directory.EnumerateFiles(Filename, "*", SearchOption.TopDirectoryOnly))
2024-02-28 21:59:13 -05:00
#endif
{
BaseFile? nf = FileTypeTool.GetInfo(file, _hashTypes);
2024-02-28 19:19:50 -05:00
if (nf != null)
_children.Add(nf);
}
2024-02-29 00:14:16 -05:00
#if NET20 || NET35
2024-10-19 23:17:37 -04:00
foreach (string dir in Directory.GetDirectories(Filename, "*"))
2024-02-28 21:59:13 -05:00
#else
2024-10-19 23:17:37 -04:00
foreach (string dir in Directory.EnumerateDirectories(Filename, "*", SearchOption.TopDirectoryOnly))
2024-02-28 21:59:13 -05:00
#endif
{
2025-01-04 20:24:56 -05:00
var fl = new Folder(dir);
_children.Add(fl);
}
}
return _children;
}
/// <summary>
/// Generate a list of empty folders in an archive
/// </summary>
/// <param name="input">Input file to get data from</param>
/// <returns>List of empty folders in the folder</returns>
2024-02-28 19:19:50 -05:00
public virtual List<string>? GetEmptyFolders()
{
2024-10-19 23:17:37 -04:00
return Filename.ListEmpty();
}
#endregion
#region Writing
/// <summary>
/// Write an input file to an output folder
/// </summary>
/// <param name="inputFile">Input filename to be moved</param>
/// <param name="outDir">Output directory to build to</param>
2020-12-08 11:09:05 -08:00
/// <param name="baseFile">BaseFile representing the new information</param>
/// <returns>True if the write was a success, false otherwise</returns>
/// <remarks>This works for now, but it can be sped up by using Ionic.Zip or another zlib wrapper that allows for header values built-in. See edc's code.</remarks>
2024-02-28 19:19:50 -05:00
public virtual bool Write(string inputFile, string outDir, BaseFile? baseFile)
{
2020-12-08 00:13:22 -08:00
FileStream fs = File.OpenRead(inputFile);
2020-12-08 11:09:05 -08:00
return Write(fs, outDir, baseFile);
}
/// <summary>
/// Write an input stream to an output folder
/// </summary>
/// <param name="inputStream">Input stream to be moved</param>
/// <param name="outDir">Output directory to build to</param>
2020-12-08 11:09:05 -08:00
/// <param name="baseFile">BaseFile representing the new information</param>
/// <returns>True if the write was a success, false otherwise</returns>
/// <remarks>This works for now, but it can be sped up by using Ionic.Zip or another zlib wrapper that allows for header values built-in. See edc's code.</remarks>
2024-02-28 19:19:50 -05:00
public virtual bool Write(Stream? inputStream, string outDir, BaseFile? baseFile)
{
// If either input is null or empty, return
2020-12-08 11:09:05 -08:00
if (inputStream == null || baseFile == null || baseFile.Filename == null)
2024-07-17 15:19:15 -04:00
return false;
// If the stream is not readable, return
if (!inputStream.CanRead)
2024-07-17 15:19:15 -04:00
return false;
// Set internal variables
2024-02-28 19:19:50 -05:00
FileStream? outputStream = null;
// Get the output folder name from the first rebuild rom
2020-08-28 20:46:12 -07:00
string fileName;
2024-10-19 23:17:37 -04:00
if (_writeToParent)
2024-02-28 19:19:50 -05:00
fileName = Path.Combine(outDir, TextHelper.RemovePathUnsafeCharacters(baseFile.Filename) ?? string.Empty);
2020-08-28 20:46:12 -07:00
else
2024-02-28 21:59:13 -05:00
#if NET20 || NET35
fileName = Path.Combine(Path.Combine(outDir, TextHelper.RemovePathUnsafeCharacters(baseFile.Parent) ?? string.Empty), TextHelper.RemovePathUnsafeCharacters(baseFile.Filename) ?? string.Empty);
#else
2024-02-28 19:19:50 -05:00
fileName = Path.Combine(outDir, TextHelper.RemovePathUnsafeCharacters(baseFile.Parent) ?? string.Empty, TextHelper.RemovePathUnsafeCharacters(baseFile.Filename) ?? string.Empty);
2024-02-28 21:59:13 -05:00
#endif
// Replace any incorrect directory characters
if (Path.DirectorySeparatorChar == '\\')
fileName = fileName.Replace('/', '\\');
else if (Path.DirectorySeparatorChar == '/')
fileName = fileName.Replace('\\', '/');
try
{
// If the full output path doesn't exist, create it
2024-02-28 19:19:50 -05:00
string? dir = Path.GetDirectoryName(fileName);
if (dir != null && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
// Overwrite output files by default
2020-12-08 00:13:22 -08:00
outputStream = File.Create(fileName);
2024-07-17 15:19:15 -04:00
if (outputStream == null)
return false;
2024-07-17 15:19:15 -04:00
if (inputStream.CanSeek)
inputStream.Seek(0, SeekOrigin.Begin);
2024-07-17 15:19:15 -04:00
// Copy the input stream to the output
int bufferSize = 4096 * 128;
byte[] ibuffer = new byte[bufferSize];
int ilen;
while ((ilen = inputStream.Read(ibuffer, 0, bufferSize)) > 0)
{
outputStream.Write(ibuffer, 0, ilen);
outputStream.Flush();
}
2020-08-28 21:38:27 -07:00
2024-07-17 15:19:15 -04:00
outputStream.Dispose();
2024-07-18 00:00:23 -04:00
// Try to set the creation time
try
{
if (!string.IsNullOrEmpty(baseFile.Date))
File.SetCreationTime(fileName, DateTime.Parse(baseFile.Date));
}
catch { }
2024-07-17 15:19:15 -04:00
return true;
}
catch (Exception ex)
{
_logger.Error(ex);
2024-07-17 15:19:15 -04:00
return false;
}
finally
{
outputStream?.Dispose();
}
}
/// <summary>
/// Write a set of input files to an output folder (assuming the same output archive name)
/// </summary>
/// <param name="inputFiles">Input files to be moved</param>
/// <param name="outDir">Output directory to build to</param>
2020-12-08 11:09:05 -08:00
/// <param name="baseFiles">BaseFiles representing the new information</param>
/// <returns>True if the inputs were written properly, false otherwise</returns>
2024-02-28 19:19:50 -05:00
public virtual bool Write(List<string> inputFiles, string outDir, List<BaseFile>? baseFiles)
{
throw new NotImplementedException();
}
#endregion
}
}