Used to re-organized folders

This commit is contained in:
2023-11-12 18:09:22 -07:00
parent c2757ef46b
commit 0310e06f3c
11 changed files with 193 additions and 151 deletions

View File

@ -4,6 +4,7 @@ using System.Text.Json;
using View_by_Distance.Metadata.Models.Stateless;
using View_by_Distance.Metadata.Models.Stateless.Methods;
using View_by_Distance.Shared.Models;
using View_by_Distance.Shared.Models.Properties;
using View_by_Distance.Shared.Models.Stateless.Methods;
namespace View_by_Distance.Metadata.Models;
@ -26,21 +27,50 @@ public class A_Metadata
_FileGroups = IPath.GetKeyValuePairs(metadataConfiguration.ResultConfiguration, bResultsFullGroupDirectory, [metadataConfiguration.ResultConfiguration.ResultSingleton]);
}
private FileInfo GetFileInfo(ResultConfiguration resultConfiguration, FilePath filePath)
private (int, FileInfo) GetFileInfo(ResultConfiguration resultConfiguration, FilePath filePath)
{
FileInfo result;
FileInfo fileInfo = new(filePath.FullName);
(_, int directoryIndex) = IPath.GetDirectoryNameAndIndex(resultConfiguration, filePath);
DateTime minimumDateTime = fileInfo.CreationTime < fileInfo.LastWriteTime ? fileInfo.CreationTime : fileInfo.LastWriteTime;
int minimumYear = minimumDateTime.Year < resultConfiguration.EpicYear ? resultConfiguration.EpicYear : minimumDateTime.Year;
result = new(Path.Combine(_FileGroups[minimumYear][_MetadataConfiguration.ResultConfiguration.ResultSingleton][directoryIndex], $"{filePath.NameWithoutExtension}{filePath.ExtensionLowered}.json"));
return result;
int fileInfoMinimumYear = minimumDateTime.Year < resultConfiguration.EpicYear ? resultConfiguration.EpicYear : minimumDateTime.Year;
result = new(Path.Combine(_FileGroups[fileInfoMinimumYear][_MetadataConfiguration.ResultConfiguration.ResultSingleton][directoryIndex], $"{filePath.NameWithoutExtension}{filePath.ExtensionLowered}.json"));
return (fileInfoMinimumYear, result);
}
private (int, string) GetJsonFile(ResultConfiguration resultConfiguration, FilePath filePath, ExifDirectory exifDirectory)
{
string? result;
DateTime? dateTime;
dateTime = IDate.GetDateTimeOriginal(exifDirectory);
dateTime ??= IDate.GetMinimum(exifDirectory);
(_, int directoryIndex) = IPath.GetDirectoryNameAndIndex(resultConfiguration, filePath);
int exifYear = dateTime.Value.Year < resultConfiguration.EpicYear ? resultConfiguration.EpicYear : dateTime.Value.Year;
result = Path.Combine(_FileGroups[exifYear][_MetadataConfiguration.ResultConfiguration.ResultSingleton][directoryIndex], $"{filePath.NameWithoutExtension}{filePath.ExtensionLowered}.json");
return (exifYear, result);
}
private static (string, ExifDirectory?) Get(string jsonFile)
{
ExifDirectory? result;
string json = File.ReadAllText(jsonFile);
try
{
result = JsonSerializer.Deserialize(json, ExifDirectorySourceGenerationContext.Default.ExifDirectory);
if (result is null)
throw new Exception();
}
catch (Exception)
{
result = null;
}
return (json, result);
}
public (FileInfo, ExifDirectory) GetMetadataCollection(MetadataConfiguration metadataConfiguration, FilePath filePath, DeterministicHashCode deterministicHashCode)
{
ExifDirectory? results;
FileInfo fileInfo = GetFileInfo(metadataConfiguration.ResultConfiguration, filePath);
ExifDirectory? result;
(int fileInfoMinimumYear, FileInfo fileInfo) = GetFileInfo(metadataConfiguration.ResultConfiguration, filePath);
if (_MetadataConfiguration.ForceMetadataLastWriteTimeToCreationTime && !fileInfo.Exists && File.Exists(Path.ChangeExtension(fileInfo.FullName, ".delete")))
{
File.Move(Path.ChangeExtension(fileInfo.FullName, ".delete"), fileInfo.FullName);
@ -52,9 +82,9 @@ public class A_Metadata
fileInfo.Refresh();
}
if (_MetadataConfiguration.PropertiesChangedForMetadata)
results = null;
result = null;
else if (!fileInfo.Exists)
results = null;
result = null;
else if (!fileInfo.FullName.EndsWith(".json") && !fileInfo.FullName.EndsWith(".old"))
throw new ArgumentException("must be a *.json file");
else
@ -62,59 +92,74 @@ public class A_Metadata
string json = File.ReadAllText(fileInfo.FullName);
try
{
results = JsonSerializer.Deserialize(json, ExifDirectorySourceGenerationContext.Default.ExifDirectory);
if (results is null)
result = JsonSerializer.Deserialize(json, ExifDirectorySourceGenerationContext.Default.ExifDirectory);
if (result is null)
throw new Exception();
}
catch (Exception)
{
results = null;
result = null;
}
}
if (results is null)
if (result is null)
{
System.Drawing.Size? size;
try
{ size = Dimensions.GetDimensions(filePath.FullName); }
catch (Exception) { size = null; }
string json;
System.Drawing.Size? size = Dimensions.GetDimensions(filePath.FullName);
IReadOnlyList<MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(filePath.FullName);
results = Exif.Covert(filePath, deterministicHashCode, size, directories);
string json = JsonSerializer.Serialize(results, ExifDirectorySourceGenerationContext.Default.ExifDirectory);
result = Exif.Covert(filePath, deterministicHashCode, size, directories);
(int exifYear, string jsonFile) = GetJsonFile(metadataConfiguration.ResultConfiguration, filePath, result);
if (exifYear == fileInfoMinimumYear)
json = JsonSerializer.Serialize(result, ExifDirectorySourceGenerationContext.Default.ExifDirectory);
else
{
fileInfo = new(jsonFile);
if (!File.Exists(jsonFile))
json = JsonSerializer.Serialize(result, ExifDirectorySourceGenerationContext.Default.ExifDirectory);
else
{
(string checkJson, ExifDirectory? exifDirectory) = Get(jsonFile);
if (exifDirectory is null)
json = JsonSerializer.Serialize(result, ExifDirectorySourceGenerationContext.Default.ExifDirectory);
else
{
json = checkJson;
result = exifDirectory;
}
}
}
if (IPath.WriteAllText(fileInfo.FullName, json, updateDateWhenMatches: false, compareBeforeWrite: true, updateToWhenMatches: null) && _MetadataConfiguration.ForceMetadataLastWriteTimeToCreationTime)
{
File.SetLastWriteTime(fileInfo.FullName, fileInfo.CreationTime);
fileInfo.Refresh();
}
}
return (fileInfo, results);
return (fileInfo, result);
}
public static Action<string> SetExifDirectoryCollection(IRename rename, MetadataConfiguration metadataConfiguration, A_Metadata metadata, List<(string, FileInfo, ExifDirectory)> exifDirectories, Action tick)
public static Action<string> SetExifDirectoryCollection(IRename rename, IRenameConfiguration renameConfiguration, A_Metadata metadata, List<(string, FileInfo, ExifDirectory)> exifDirectories)
{
return file =>
{
tick.Invoke();
rename.Tick();
FileInfo fileInfo;
FilePath? ffmpegFilePath;
ExifDirectory exifDirectory;
ReadOnlyCollection<string> ffmpegFiles;
DeterministicHashCode deterministicHashCode;
FilePath filePath = IId.GetFilePath(metadataConfiguration, file);
if (filePath.ExtensionLowered is not ".paddedId" and not ".lsv")
FilePath filePath = IId.GetFilePath(renameConfiguration.MetadataConfiguration, file);
if (!renameConfiguration.SkipIdFiles || filePath.Id is null || !filePath.IsIdFormat && !filePath.IsPaddedIdFormat)
{
if (filePath.Id is null || (!filePath.IsIdFormat && !filePath.IsPaddedIdFormat))
{
(ffmpegFiles, ffmpegFilePath) = rename.ConvertAndGetFfmpegFiles(filePath);
if (ffmpegFilePath is not null)
filePath = ffmpegFilePath;
deterministicHashCode = filePath.Id is not null ? deterministicHashCode = new(null, filePath.Id, null) : deterministicHashCode = rename.GetDeterministicHashCode(filePath);
(fileInfo, exifDirectory) = metadata.GetMetadataCollection(metadataConfiguration, filePath, deterministicHashCode);
lock (exifDirectories)
exifDirectories.Add(new(file, fileInfo, exifDirectory));
foreach (string ffmpegFile in ffmpegFiles)
File.Delete(ffmpegFile);
}
(ffmpegFiles, ffmpegFilePath) = rename.ConvertAndGetFfmpegFiles(renameConfiguration, filePath);
if (ffmpegFilePath is not null)
filePath = ffmpegFilePath;
deterministicHashCode = filePath.Id is not null ? deterministicHashCode = new(null, filePath.Id, null) : deterministicHashCode = rename.GetDeterministicHashCode(filePath);
(fileInfo, exifDirectory) = metadata.GetMetadataCollection(renameConfiguration.MetadataConfiguration, filePath, deterministicHashCode);
lock (exifDirectories)
exifDirectories.Add(new(file, fileInfo, exifDirectory));
foreach (string ffmpegFile in ffmpegFiles)
File.Delete(ffmpegFile);
}
};
}

View File

@ -32,6 +32,7 @@ public class MetadataConfiguration
continue;
throw new NotSupportedException(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
}
}

View File

@ -39,6 +39,7 @@ public class ResultConfiguration
continue;
throw new NotSupportedException(physicalFileProvider.Root);
}
throw new NotSupportedException("Not Found!");
}
}

View File

@ -5,10 +5,8 @@ namespace View_by_Distance.Metadata.Models.Stateless.Methods;
internal static class Dimensions
{
const string _ErrorMessage = "Could not recognize image format.";
#pragma warning disable IDE0230
private static readonly Dictionary<byte[], Func<BinaryReader, Size>> _ImageFormatDecoders = new()
private static readonly Dictionary<byte[], Func<BinaryReader, Size?>> _ImageFormatDecoders = new()
{
{ new byte[] { 0x42, 0x4D }, DecodeBitmap },
{ new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },
@ -23,10 +21,9 @@ internal static class Dimensions
{
for (int i = 0; i < thatBytes.Length; i += 1)
{
if (thisBytes[i] != thatBytes[i])
{
return false;
}
if (thisBytes[i] == thatBytes[i])
continue;
return false;
}
return true;
}
@ -35,9 +32,7 @@ internal static class Dimensions
{
byte[] bytes = new byte[sizeof(short)];
for (int i = 0; i < sizeof(short); i += 1)
{
bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();
}
return BitConverter.ToInt16(bytes, 0);
}
@ -45,13 +40,11 @@ internal static class Dimensions
{
byte[] bytes = new byte[sizeof(int)];
for (int i = 0; i < sizeof(int); i += 1)
{
bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();
}
return BitConverter.ToInt32(bytes, 0);
}
private static Size DecodeBitmap(BinaryReader binaryReader)
private static Size? DecodeBitmap(BinaryReader binaryReader)
{
_ = binaryReader.ReadBytes(16);
int width = binaryReader.ReadInt32();
@ -59,14 +52,14 @@ internal static class Dimensions
return new Size(width, height);
}
private static Size DecodeGif(BinaryReader binaryReader)
private static Size? DecodeGif(BinaryReader binaryReader)
{
int width = binaryReader.ReadInt16();
int height = binaryReader.ReadInt16();
return new Size(width, height);
}
private static Size DecodePng(BinaryReader binaryReader)
private static Size? DecodePng(BinaryReader binaryReader)
{
_ = binaryReader.ReadBytes(8);
int width = ReadLittleEndianInt32(binaryReader);
@ -74,100 +67,60 @@ internal static class Dimensions
return new Size(width, height);
}
private static Size DecodeJfif(BinaryReader binaryReader)
private static Size? DecodeJfif(BinaryReader binaryReader)
{
while (binaryReader.ReadByte() == 0xff)
{
byte marker = binaryReader.ReadByte();
short chunkLength = ReadLittleEndianInt16(binaryReader);
if (marker == 0xc0)
{
_ = binaryReader.ReadByte();
int height = ReadLittleEndianInt16(binaryReader);
int width = ReadLittleEndianInt16(binaryReader);
return new Size(width, height);
}
if (chunkLength < 0)
if (chunkLength >= 0)
_ = binaryReader.ReadBytes(chunkLength - 2);
else
{
ushort uChunkLength = (ushort)chunkLength;
_ = binaryReader.ReadBytes(uChunkLength - 2);
}
else
{
_ = binaryReader.ReadBytes(chunkLength - 2);
}
}
throw new ArgumentException(_ErrorMessage);
return null;
}
private static Size DecodeWebP(BinaryReader binaryReader)
private static Size? DecodeWebP(BinaryReader binaryReader)
{
_ = binaryReader.ReadUInt32(); // Size
_ = binaryReader.ReadBytes(15); // WEBP, VP8 + more
_ = binaryReader.ReadBytes(3); // SYNC
int width = binaryReader.ReadUInt16() & 0b00_11111111111111; // 14 bits width
int height = binaryReader.ReadUInt16() & 0b00_11111111111111; // 14 bits height
return new Size(width, height);
}
/// <summary>
/// Gets the dimensions of an image.
/// </summary>
/// <param name="path">The path of the image to get the dimensions of.</param>
/// <returns>The dimensions of the specified image.</returns>
/// <exception cref="ArgumentException">The image was of an unrecognized format.</exception>
internal static Size GetDimensions(BinaryReader binaryReader)
internal static Size? GetDimensions(BinaryReader binaryReader)
{
int maxMagicBytesLength = _ImageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length;
byte[] magicBytes = new byte[maxMagicBytesLength];
for (int i = 0; i < maxMagicBytesLength; i += 1)
{
magicBytes[i] = binaryReader.ReadByte();
foreach (KeyValuePair<byte[], Func<BinaryReader, Size>> kvPair in _ImageFormatDecoders)
foreach (KeyValuePair<byte[], Func<BinaryReader, Size?>> kvPair in _ImageFormatDecoders)
{
if (StartsWith(magicBytes, kvPair.Key))
{
return kvPair.Value(binaryReader);
}
}
}
throw new ArgumentException(_ErrorMessage, nameof(binaryReader));
return null;
}
/// <summary>
/// Gets the dimensions of an image.
///internal </summary>
/// <param name="path">The path of the image to get the dimensions of.</param>
/// <returns>The dimensions of the specified image.</returns>
/// <exception cref="ArgumentException">The image was of an unrecognized format.</exception>
internal static Size GetDimensions(string path)
internal static Size? GetDimensions(string path)
{
using BinaryReader binaryReader = new(File.OpenRead(path));
try
{
return GetDimensions(binaryReader);
}
catch (ArgumentException e)
{
if (e.Message.StartsWith(_ErrorMessage))
{
throw new ArgumentException(_ErrorMessage, nameof(path), e);
}
else
{
throw;
}
}
return GetDimensions(binaryReader);
}
}

View File

@ -357,10 +357,10 @@ internal abstract class Exif
internal static string GetMaker(Shared.Models.ExifDirectoryBase exifDirectoryBase)
{
string result;
if (string.IsNullOrEmpty(exifDirectoryBase.Make))
if (string.IsNullOrEmpty(exifDirectoryBase.Make?.ToString().Trim()))
result = "Unknown";
else
result = $"{exifDirectoryBase.Make[0].ToString().ToUpper()}{exifDirectoryBase.Make[1..]}".Trim();
result = $"{exifDirectoryBase.Make[0].ToString().ToUpper()}{exifDirectoryBase.Make[1..].ToLower()}".Trim();
return result;
}