deterministicHashCode

This commit is contained in:
2023-10-23 09:45:18 -07:00
parent 42d202e287
commit 05c27a891b
11 changed files with 240 additions and 63 deletions

View File

@ -1,6 +1,10 @@
using CliWrap;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ShellProgressBar;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using View_by_Distance.Metadata.Models;
using View_by_Distance.Rename.Models;
using View_by_Distance.Shared.Models;
@ -8,7 +12,7 @@ using View_by_Distance.Shared.Models.Stateless.Methods;
namespace View_by_Distance.Rename;
public class Rename
public class Rename : IRename
{
private readonly AppSettings _AppSettings;
@ -94,28 +98,115 @@ public class Rename
return result;
}
string[]? IRename.ConvertAndGetFfmpegFiles(FilePath filePath)
{
string[]? results;
bool isIgnoreExtension;
bool isValidImageFormatExtension = _MetadataConfiguration.ValidImageFormatExtensions.Contains(filePath.ExtensionLowered);
isIgnoreExtension = isValidImageFormatExtension && _MetadataConfiguration.IgnoreExtensions.Contains(filePath.ExtensionLowered);
if (!isIgnoreExtension && isValidImageFormatExtension)
results = null;
else
{
CommandTask<CommandResult> commandTask = Cli.Wrap("ffmpeg.exe")
// .WithArguments(new[] { "-ss", "00:00:00", "-t", "00:00:00", "-i", files[i], "-qscale:v", "2", "-r", "0.01", $"{fileHolder.Name}-%4d.jpg" })
.WithArguments(new[] { "-i", filePath.FullName, "-vframes", "1", $"{filePath.Name}-%4d.jpg" })
.WithWorkingDirectory(filePath.DirectoryName)
.ExecuteAsync();
commandTask.Task.Wait();
results = Directory.GetFiles(filePath.DirectoryName, $"{filePath.Name}-*.jpg", SearchOption.TopDirectoryOnly);
if (results.Length == 0)
throw new Exception();
if (!filePath.Name.EndsWith("-0001.jpg"))
throw new Exception();
isValidImageFormatExtension = _MetadataConfiguration.ValidImageFormatExtensions.Contains(filePath.ExtensionLowered);
isIgnoreExtension = isValidImageFormatExtension && _MetadataConfiguration.IgnoreExtensions.Contains(filePath.ExtensionLowered);
if (isIgnoreExtension || !isValidImageFormatExtension)
throw new Exception();
if (filePath.DirectoryName is null)
throw new NullReferenceException(nameof(filePath.DirectoryName));
}
return results;
}
#pragma warning disable CA1416
DeterministicHashCode IRename.GetDeterministicHashCode(FilePath filePath)
{
DeterministicHashCode result;
int? id;
int? width;
int? height;
try
{
using Image image = Image.FromFile(filePath.FullName);
width = image.Width;
height = image.Height;
using Bitmap bitmap = new(image);
Rectangle rectangle = new(0, 0, image.Width, image.Height);
BitmapData bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, bitmap.PixelFormat);
IntPtr intPtr = bitmapData.Scan0;
int length = bitmapData.Stride * bitmap.Height;
byte[] bytes = new byte[length];
Marshal.Copy(intPtr, bytes, 0, length);
bitmap.UnlockBits(bitmapData);
id = IId.GetDeterministicHashCode(bytes);
}
catch (Exception)
{
id = null;
width = null;
height = null;
}
result = new(height, id, width);
return result;
}
#pragma warning restore CA1416
private void GetResultCollection(IRename rename, List<ExifDirectory> exifDirectories, IEnumerable<string> files, A_Metadata metadata)
{
string[]? ffmpegFiles;
DeterministicHashCode deterministicHashCode;
foreach (string file in files)
{
FilePath filePath = IId.GetFilePath(_MetadataConfiguration, file);
if (filePath.ExtensionLowered is ".paddedId" or ".lsv")
continue;
if (files.Contains($"{filePath.FullName}.paddedId"))
continue;
if (filePath.Id is not null && (filePath.IsIdFormat || filePath.IsPaddedIdFormat))
continue;
ffmpegFiles = rename.ConvertAndGetFfmpegFiles(filePath);
filePath = ffmpegFiles is null || ffmpegFiles.Length < 0 ? filePath : IId.GetFilePath(filePath, ffmpegFiles[0]);
if (filePath.Id is not null)
deterministicHashCode = new(null, filePath.Id, null);
else
deterministicHashCode = rename.GetDeterministicHashCode(filePath);
if (ffmpegFiles is not null)
{
foreach (string ffmpegFile in ffmpegFiles)
File.Delete(ffmpegFile);
}
exifDirectories.Add(metadata.GetMetadataCollection(_MetadataConfiguration, filePath, deterministicHashCode));
}
}
private List<string> RenameFilesInDirectories(ILogger? logger, long ticks, DirectoryInfo directoryInfo)
{
List<string> old = [];
IRename rename = this;
List<ExifDirectory> exifDirectories = [];
bool runToDoCollectionFirst = GetRunToDoCollectionFirst(ticks, directoryInfo);
IEnumerable<string> files = Directory.EnumerateFiles(directoryInfo.FullName, "*", SearchOption.AllDirectories);
A_Metadata metadata = new(_MetadataConfiguration, _Configuration.ForceMetadataLastWriteTimeToCreationTime, _Configuration.PropertiesChangedForMetadata);
if (runToDoCollectionFirst)
{
foreach (string file in files)
{
NameWithoutExtension nameWithoutExtension = IId.GetNameWithoutExtension(_MetadataConfiguration, file);
exifDirectories.Add(metadata.GetMetadataCollection(_MetadataConfiguration, file, nameWithoutExtension));
if (nameWithoutExtension.Id is null || (!nameWithoutExtension.IsIdFormat && !nameWithoutExtension.IsPaddedIdFormat))
;
}
}
GetResultCollection(rename, exifDirectories, files, metadata);
else
{
ParallelOptions parallelOptions = new() { MaxDegreeOfParallelism = _AppSettings.MaxDegreeOfParallelism };
ProgressBar progressBar = new(123000, "EnumerateFiles load", new ProgressBarOptions() { ProgressCharacter = '─', ProgressBarOnBottom = true, DisableBottomPercentage = true });
files.AsParallel().ForAll(A_Metadata.GetResultCollection(_MetadataConfiguration, metadata, exifDirectories, () => progressBar.Tick()));
files.AsParallel().ForAll(A_Metadata.GetResultCollection(rename, _MetadataConfiguration, metadata, exifDirectories, () => progressBar.Tick()));
if (progressBar.CurrentTick != exifDirectories.Count)
throw new NotSupportedException();
}