using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SabreTools.Library.Data;
using SabreTools.Library.Items;
using SabreTools.Library.Tools;
#if MONO
using System.IO;
#else
using Alphaleonis.Win32.Filesystem;
using FileStream = System.IO.FileStream;
using StreamReader = System.IO.StreamReader;
using StreamWriter = System.IO.StreamWriter;
#endif
using NaturalSort;
namespace SabreTools.Library.DatFiles
{
///
/// Represents parsing and writing of a hashfile such as an SFV, MD5, or SHA-1 file
///
public class Hashfile
{
///
/// Parse a hashfile or SFV and return all found games and roms within
///
/// DatFile to populate with the read information
/// Name of the file to be parsed
/// System ID for the DAT
/// Source ID for the DAT
/// Hash type that should be assumed
/// True if game names are sanitized, false otherwise (default)
/// True if we should remove non-ASCII characters from output, false otherwise (default)
public static void Parse(
DatFile datFile,
// Standard Dat parsing
string filename,
int sysid,
int srcid,
// Specific to hash files
Hash hashtype,
// Miscellaneous
bool clean,
bool remUnicode)
{
// Open a file reader
Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
// Split the line and get the name and hash
string[] split = line.Split(' ');
string name = "";
string hash = "";
// If we have CRC, then it's an SFV file and the name is first are
if ((hashtype & Hash.CRC) != 0)
{
name = split[0].Replace("*", String.Empty);
hash = split[1];
}
// Otherwise, the name is second
else
{
name = split[1].Replace("*", String.Empty);
hash = split[0];
}
Rom rom = new Rom
{
Name = name,
Size = -1,
CRC = ((hashtype & Hash.CRC) != 0 ? hash : null),
MD5 = ((hashtype & Hash.MD5) != 0 ? hash : null),
SHA1 = ((hashtype & Hash.SHA1) != 0 ? hash : null),
SHA256 = ((hashtype & Hash.SHA256) != 0 ? hash : null),
SHA384 = ((hashtype & Hash.SHA384) != 0 ? hash : null),
SHA512 = ((hashtype & Hash.SHA512) != 0 ? hash : null),
ItemStatus = ItemStatus.None,
MachineName = Path.GetFileNameWithoutExtension(filename),
SystemID = sysid,
SourceID = srcid,
};
// Now process and add the rom
datFile.ParseAddHelper(rom, clean, remUnicode);
}
sr.Dispose();
}
///
/// Create and open an output file for writing direct from a dictionary
///
/// DatFile to write out from
/// Name of the file to write to
/// Hash that should be written out
/// True if blank roms should be skipped on output, false otherwise (default)
/// True if the DAT was written correctly, false otherwise
public static bool WriteToFile(DatFile datFile, string outfile, Hash hash, bool ignoreblanks = false)
{
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)
{
Globals.Logger.Warning("File '{0}' could not be created for writing! Please check to see if the file is writable", outfile);
return false;
}
StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(true));
// Get a properly sorted set of keys
List keys = datFile.Keys.ToList();
keys.Sort(new NaturalComparer());
foreach (string key in keys)
{
List roms = datFile[key];
// Resolve the names in the block
roms = DatItem.ResolveNames(roms);
for (int index = 0; index < roms.Count; index++)
{
DatItem rom = roms[index];
// There are apparently times when a null rom can skip by, skip them
if (rom.Name == null || rom.MachineName == null)
{
Globals.Logger.Warning("Null rom found!");
continue;
}
// If we have a "null" game (created by DATFromDir or something similar), log it to file
if (rom.Type == ItemType.Rom
&& ((Rom)rom).Size == -1
&& ((Rom)rom).CRC == "null")
{
Globals.Logger.Verbose("Empty folder found: {0}", rom.MachineName);
}
// Now, output the rom data
WriteRomData(datFile, sw, hash, rom, ignoreblanks);
}
}
Globals.Logger.Verbose("File written!" + Environment.NewLine);
sw.Dispose();
fs.Dispose();
}
catch (Exception ex)
{
Globals.Logger.Error(ex.ToString());
return false;
}
return true;
}
///
/// Write out RomData using the supplied StreamWriter
///
/// DatFile to write out from
/// StreamWriter to output to
/// Hash that should be written out
/// RomData object to be output
/// True if blank roms should be skipped on output, false otherwise (default)
/// True if the data was written, false on error
private static bool WriteRomData(DatFile datFile, StreamWriter sw, Hash hash, DatItem rom, bool ignoreblanks = false)
{
// If we are in ignore blanks mode AND we have a blank (0-size) rom, skip
if (ignoreblanks
&& (rom.Type == ItemType.Rom
&& (((Rom)rom).Size == 0 || ((Rom)rom).Size == -1)))
{
return true;
}
try
{
string state = "";
switch (hash)
{
case Hash.MD5:
if (rom.Type == ItemType.Rom)
{
state += ((Rom)rom).MD5 + " *" + (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + "\n";
}
else if (rom.Type == ItemType.Disk)
{
state += ((Disk)rom).MD5 + " *" + (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + "\n";
}
break;
case Hash.CRC:
if (rom.Type == ItemType.Rom)
{
state += (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + " " + ((Rom)rom).CRC + "\n";
}
break;
case Hash.SHA1:
if (rom.Type == ItemType.Rom)
{
state += ((Rom)rom).SHA1 + " *" + (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + "\n";
}
else if (rom.Type == ItemType.Disk)
{
state += ((Disk)rom).SHA1 + " *" + (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + "\n";
}
break;
case Hash.SHA256:
if (rom.Type == ItemType.Rom)
{
state += ((Rom)rom).SHA256 + " *" + (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + "\n";
}
else if (rom.Type == ItemType.Disk)
{
state += ((Disk)rom).SHA256 + " *" + (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + "\n";
}
break;
case Hash.SHA384:
if (rom.Type == ItemType.Rom)
{
state += ((Rom)rom).SHA384 + " *" + (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + "\n";
}
else if (rom.Type == ItemType.Disk)
{
state += ((Disk)rom).SHA384 + " *" + (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + "\n";
}
break;
case Hash.SHA512:
if (rom.Type == ItemType.Rom)
{
state += ((Rom)rom).SHA512 + " *" + (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + "\n";
}
else if (rom.Type == ItemType.Disk)
{
state += ((Disk)rom).SHA512 + " *" + (datFile.GameName ? rom.MachineName + Path.DirectorySeparatorChar : "") + rom.Name + "\n";
}
break;
}
sw.Write(state);
sw.Flush();
}
catch (Exception ex)
{
Globals.Logger.Error(ex.ToString());
return false;
}
return true;
}
}
}