Files
SabreTools/SabreTools.FileTypes/Archives/RarArchive.cs

288 lines
9.3 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
2020-12-08 13:23:59 -08:00
using SabreTools.Core;
using SharpCompress.Archives;
using SharpCompress.Archives.Rar;
using SharpCompress.Readers;
2020-12-10 22:31:23 -08:00
namespace SabreTools.FileTypes.Archives
{
2020-08-18 23:39:13 -07:00
/// <summary>
/// Represents a TorrentRAR archive for reading and writing
/// </summary>
public class RarArchive : BaseArchive
{
#region Constructors
/// <summary>
/// Create a new TorrentRARArchive with no base file
/// </summary>
public RarArchive()
: base()
{
this.Type = FileType.RarArchive;
}
/// <summary>
/// Create a new TorrentRARArchive from the given file
/// </summary>
/// <param name="filename">Name of the file to use as an archive</param>
/// <param name="read">True for opening file as read, false for opening file as write</param>
/// <param name="getHashes">True if hashes for this file should be calculated, false otherwise (default)</param>
public RarArchive(string filename, bool getHashes = false)
: base(filename, getHashes)
{
this.Type = FileType.RarArchive;
}
#endregion
#region Extraction
2020-12-08 11:09:05 -08:00
/// <inheritdoc/>
2020-08-18 23:39:13 -07:00
public override bool CopyAll(string outDir)
{
bool encounteredErrors = true;
2024-02-28 19:19:50 -05:00
// If we have an invalid file
if (this.Filename == null)
return true;
2020-08-18 23:39:13 -07:00
try
{
// Create the temp directory
Directory.CreateDirectory(outDir);
// Extract all files to the temp directory
SharpCompress.Archives.Rar.RarArchive ra = SharpCompress.Archives.Rar.RarArchive.Open(this.Filename);
foreach (RarArchiveEntry entry in ra.Entries)
{
entry.WriteToDirectory(outDir, new SharpCompress.Common.ExtractionOptions { PreserveFileTime = true, ExtractFullPath = true, Overwrite = true });
}
encounteredErrors = false;
ra.Dispose();
}
2020-09-15 12:12:13 -07:00
catch (EndOfStreamException ex)
2020-08-18 23:39:13 -07:00
{
// Catch this but don't count it as an error because SharpCompress is unsafe
logger.Verbose(ex);
2020-08-18 23:39:13 -07:00
}
2020-09-15 12:12:13 -07:00
catch (InvalidOperationException ex)
2020-08-18 23:39:13 -07:00
{
logger.Warning(ex);
2020-08-18 23:39:13 -07:00
encounteredErrors = true;
}
catch (Exception ex)
{
logger.Error(ex);
2020-08-18 23:39:13 -07:00
encounteredErrors = true;
}
return encounteredErrors;
}
2020-12-08 11:09:05 -08:00
/// <inheritdoc/>
2024-02-28 19:19:50 -05:00
public override string? CopyToFile(string entryName, string outDir)
2020-08-18 23:39:13 -07:00
{
// Try to extract a stream using the given information
2024-02-28 19:19:50 -05:00
(MemoryStream? ms, string? realEntry) = CopyToStream(entryName);
2020-08-18 23:39:13 -07:00
// If the memory stream and the entry name are both non-null, we write to file
if (ms != null && realEntry != null)
{
realEntry = Path.Combine(outDir, realEntry);
// Create the output subfolder now
2024-02-28 19:19:50 -05:00
Directory.CreateDirectory(Path.GetDirectoryName(realEntry) ?? string.Empty);
2020-08-18 23:39:13 -07:00
// Now open and write the file if possible
2020-12-08 00:13:22 -08:00
FileStream fs = File.Create(realEntry);
2020-08-18 23:39:13 -07:00
if (fs != null)
{
ms.Seek(0, SeekOrigin.Begin);
byte[] zbuffer = new byte[_bufferSize];
int zlen;
while ((zlen = ms.Read(zbuffer, 0, _bufferSize)) > 0)
{
fs.Write(zbuffer, 0, zlen);
fs.Flush();
}
ms?.Dispose();
fs?.Dispose();
}
else
{
ms?.Dispose();
fs?.Dispose();
realEntry = null;
}
}
return realEntry;
}
2020-12-08 11:09:05 -08:00
/// <inheritdoc/>
2024-02-28 19:19:50 -05:00
public override (MemoryStream?, string?) CopyToStream(string entryName)
2020-08-18 23:39:13 -07:00
{
2024-02-28 19:19:50 -05:00
MemoryStream? ms = new();
string? realEntry = null;
// If we have an invalid file
if (this.Filename == null)
return (null, null);
2020-08-18 23:39:13 -07:00
try
{
SharpCompress.Archives.Rar.RarArchive ra = SharpCompress.Archives.Rar.RarArchive.Open(this.Filename, new ReaderOptions { LeaveStreamOpen = false, });
foreach (RarArchiveEntry entry in ra.Entries)
{
if (entry != null && !entry.IsDirectory && entry.Key.Contains(entryName))
{
// Write the file out
realEntry = entry.Key;
entry.WriteTo(ms);
}
}
ra.Dispose();
}
catch (Exception ex)
{
logger.Error(ex);
2020-08-18 23:39:13 -07:00
ms = null;
realEntry = null;
}
return (ms, realEntry);
}
#endregion
#region Information
2020-12-08 11:09:05 -08:00
/// <inheritdoc/>
2024-02-28 19:19:50 -05:00
public override List<BaseFile>? GetChildren()
2020-08-18 23:39:13 -07:00
{
2024-02-28 19:19:50 -05:00
// If we have an invalid file
if (this.Filename == null)
return null;
List<BaseFile> found = [];
string? gamename = Path.GetFileNameWithoutExtension(this.Filename);
2020-08-18 23:39:13 -07:00
try
{
2020-12-08 00:13:22 -08:00
SharpCompress.Archives.Rar.RarArchive ra = SharpCompress.Archives.Rar.RarArchive.Open(File.OpenRead(this.Filename));
2020-08-18 23:39:13 -07:00
foreach (RarArchiveEntry entry in ra.Entries.Where(e => e != null && !e.IsDirectory))
{
2020-10-04 14:14:57 -07:00
// Create a blank item for the entry
BaseFile rarEntryRom = new();
2020-10-04 14:14:57 -07:00
2020-09-18 01:50:44 -07:00
// Perform a quickscan, if flagged to
2020-10-05 20:39:06 -07:00
if (this.AvailableHashes == Hash.CRC)
2020-08-18 23:39:13 -07:00
{
2020-10-04 14:14:57 -07:00
rarEntryRom.Size = entry.Size;
rarEntryRom.CRC = BitConverter.GetBytes(entry.Crc);
2020-08-18 23:39:13 -07:00
}
// Otherwise, use the stream directly
else
{
using Stream entryStream = entry.OpenEntryStream();
rarEntryRom = GetInfo(entryStream, size: entry.Size, hashes: this.AvailableHashes);
2020-08-18 23:39:13 -07:00
}
2020-10-04 14:14:57 -07:00
// Fill in comon details and add to the list
rarEntryRom.Filename = entry.Key;
rarEntryRom.Parent = gamename;
rarEntryRom.Date = entry.LastModifiedTime?.ToString("yyyy/MM/dd hh:mm:ss");
found.Add(rarEntryRom);
2020-08-18 23:39:13 -07:00
}
// Dispose of the archive
ra.Dispose();
}
catch (Exception ex)
{
logger.Error(ex);
2020-08-18 23:39:13 -07:00
return null;
}
return found;
}
2020-12-08 11:09:05 -08:00
/// <inheritdoc/>
2020-08-18 23:39:13 -07:00
public override List<string> GetEmptyFolders()
{
2024-02-28 19:19:50 -05:00
List<string> empties = [];
// If we have an invalid file
if (this.Filename == null)
return empties;
2020-08-18 23:39:13 -07:00
try
{
SharpCompress.Archives.Rar.RarArchive ra = SharpCompress.Archives.Rar.RarArchive.Open(this.Filename, new ReaderOptions { LeaveStreamOpen = false });
List<RarArchiveEntry> rarEntries = ra.Entries.OrderBy(e => e.Key, new NaturalSort.NaturalReversedComparer()).ToList();
2024-02-28 19:19:50 -05:00
string? lastRarEntry = null;
2020-08-18 23:39:13 -07:00
foreach (RarArchiveEntry entry in rarEntries)
{
if (entry != null)
{
// If the current is a superset of last, we skip it
if (lastRarEntry != null && lastRarEntry.StartsWith(entry.Key))
{
// No-op
}
// If the entry is a directory, we add it
else if (entry.IsDirectory)
{
empties.Add(entry.Key);
lastRarEntry = entry.Key;
}
}
}
}
catch (Exception ex)
{
logger.Error(ex);
2020-08-18 23:39:13 -07:00
}
return empties;
}
2020-12-08 11:09:05 -08:00
/// <inheritdoc/>
2020-08-18 23:39:13 -07:00
public override bool IsTorrent()
{
throw new NotImplementedException();
}
#endregion
#region Writing
2020-12-08 11:09:05 -08:00
/// <inheritdoc/>
2024-02-28 19:19:50 -05:00
public override bool Write(string inputFile, string outDir, BaseFile? baseFile)
2020-08-18 23:39:13 -07:00
{
// Get the file stream for the file and write out
2020-12-08 11:09:05 -08:00
return Write(File.OpenRead(inputFile), outDir, baseFile);
2020-08-18 23:39:13 -07:00
}
2020-12-08 11:09:05 -08:00
/// <inheritdoc/>
2024-02-28 19:19:50 -05:00
public override bool Write(Stream? inputStream, string outDir, BaseFile? baseFile)
2020-08-18 23:39:13 -07:00
{
throw new NotImplementedException();
}
2020-12-08 11:09:05 -08:00
/// <inheritdoc/>
2024-02-28 19:19:50 -05:00
public override bool Write(List<string> inputFiles, string outDir, List<BaseFile>? roms)
2020-08-18 23:39:13 -07:00
{
throw new NotImplementedException();
}
#endregion
}
}