184 lines
9.3 KiB
C#
184 lines
9.3 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Logging;
|
|
using Phares.Shared;
|
|
using ShellProgressBar;
|
|
using View_by_Distance.Delete.By.Distinct.Models;
|
|
using View_by_Distance.Property.Models;
|
|
using View_by_Distance.Shared.Models.Methods;
|
|
|
|
namespace View_by_Distance.Delete.By.Distinct;
|
|
|
|
public class DeleteByDistinct
|
|
{
|
|
|
|
public DeleteByDistinct(List<string> args, ILogger<Program> logger, IsEnvironment isEnvironment, IConfigurationRoot configurationRoot, AppSettings appSettings, string workingDirectory, bool isSilent, IConsole console)
|
|
{
|
|
if (isSilent)
|
|
{ }
|
|
if (console is null)
|
|
{ }
|
|
long ticks = DateTime.Now.Ticks;
|
|
Dictionary<string, List<string>> keyValuePairs = [];
|
|
Configuration configuration = Property.Models.Binder.Configuration.Get(isEnvironment, configurationRoot);
|
|
ProgressBarOptions options = new() { ProgressCharacter = '─', ProgressBarOnBottom = true, DisableBottomPercentage = true };
|
|
logger?.LogInformation(configuration.RootDirectory);
|
|
if (!appSettings.TicksForLong && !appSettings.SizeForLong)
|
|
throw new Exception("Check appSettings file!");
|
|
bool compareIsPopulatedAndNotTheSame = !string.IsNullOrEmpty(appSettings.CompareRootDirectory) && appSettings.CompareRootDirectory != configuration.RootDirectory;
|
|
Work(appSettings, ticks, logger, configuration.RootDirectory, nameof(configuration.RootDirectory), options, keyValuePairs, logOnly: compareIsPopulatedAndNotTheSame);
|
|
if (compareIsPopulatedAndNotTheSame)
|
|
Work(appSettings, ticks, logger, appSettings.CompareRootDirectory, nameof(appSettings.CompareRootDirectory), options, keyValuePairs, logOnly: false);
|
|
_ = Shared.Models.Stateless.Methods.IPath.DeleteEmptyDirectories(appSettings.CompareRootDirectory);
|
|
}
|
|
|
|
private static void Work(AppSettings appSettings, long ticks, ILogger<Program>? logger, string directory, string variable, ProgressBarOptions options, Dictionary<string, List<string>> keyValuePairs, bool logOnly)
|
|
{
|
|
string check;
|
|
string logFile;
|
|
string message;
|
|
int totalSeconds;
|
|
string checkName;
|
|
FileInfo fileInfo;
|
|
List<string>? fileNames;
|
|
ProgressBar progressBar;
|
|
ConsoleKey? consoleKey = null;
|
|
List<string> deletedFiles = [];
|
|
int pad = ticks.ToString().Length + 1;
|
|
List<string> deletedDirectories = [];
|
|
Dictionary<long, List<string>> longToCollectionB = [];
|
|
List<(string Source, string Destination)> renameFiles = [];
|
|
logger?.LogInformation($"Gathering {appSettings.SearchPattern} files from <{directory}>");
|
|
(string directory, string[] files)[] leftCollection = Shared.Models.Stateless.Methods.IFileHolder.GetFiles(directory, appSettings.SearchPattern).ToArray();
|
|
totalSeconds = (int)Math.Floor(new TimeSpan(DateTime.Now.Ticks - ticks).TotalSeconds);
|
|
message = $") Looking for duplicates from <{directory}> - {totalSeconds} total second(s)";
|
|
progressBar = new(leftCollection.Length, message, options);
|
|
foreach ((_, string[] files) in leftCollection)
|
|
{
|
|
progressBar.Tick();
|
|
foreach (string file in files)
|
|
{
|
|
if (file.EndsWith(".id") || file.Contains("Rename") || file.EndsWith(".lsv"))
|
|
continue;
|
|
fileInfo = new(file);
|
|
if (appSettings.SizeForLong && appSettings.TicksForLong)
|
|
{
|
|
if (fileInfo.Length < 100)
|
|
continue;
|
|
if (fileInfo.LastWriteTime.Hour == 0 && fileInfo.LastWriteTime.Minute == 0 && fileInfo.LastWriteTime.Second == 0)
|
|
continue;
|
|
check = string.Concat(fileInfo.Length.ToString().PadRight(pad, '0'), fileInfo.LastWriteTime.Ticks);
|
|
if (!check.ToString().StartsWith(fileInfo.Length.ToString()))
|
|
throw new NotSupportedException();
|
|
}
|
|
else if (appSettings.SizeForLong)
|
|
{
|
|
if (fileInfo.Length < 100)
|
|
continue;
|
|
check = fileInfo.Length.ToString();
|
|
}
|
|
else if (appSettings.TicksForLong)
|
|
{
|
|
if (fileInfo.LastWriteTime.Hour == 0 && fileInfo.LastWriteTime.Minute == 0 && fileInfo.LastWriteTime.Second == 0)
|
|
continue;
|
|
check = fileInfo.LastWriteTime.Ticks.ToString();
|
|
}
|
|
else
|
|
throw new Exception();
|
|
if (!keyValuePairs.TryGetValue(check, out fileNames))
|
|
{
|
|
keyValuePairs.Add(check, []);
|
|
if (!keyValuePairs.TryGetValue(check, out fileNames))
|
|
throw new Exception();
|
|
}
|
|
checkName = fileInfo.Name.ToLower().Replace(".jpeg", ".jpg");
|
|
if (fileNames.Count == 0)
|
|
fileNames.Add(checkName);
|
|
else if (!logOnly && appSettings.RenameToMatch && fileNames.Count == 1 && fileInfo.DirectoryName is not null && fileInfo.Name != fileNames.First())
|
|
renameFiles.Add((fileInfo.FullName, Path.Combine(fileInfo.DirectoryName, fileNames.First())));
|
|
// else if (fileNames.Count == 1)
|
|
// deletedFiles.Add(file);
|
|
else if (fileNames.Contains(checkName))
|
|
deletedFiles.Add(file);
|
|
else
|
|
fileNames.Add(checkName);
|
|
}
|
|
}
|
|
progressBar.Dispose();
|
|
logger?.LogInformation(". . .");
|
|
logFile = $"{ticks}-{variable}-Files-A.lsv";
|
|
if (!logOnly)
|
|
File.WriteAllLines(Path.Combine(directory, logFile), deletedFiles);
|
|
if (deletedFiles.Count != 0 && !logOnly)
|
|
{
|
|
logger?.LogInformation($"Ready to delete {deletedFiles.Count} from {variable} {appSettings.SearchPattern} file(s)? See <{logFile}>");
|
|
for (int y = 0; y < int.MaxValue; y++)
|
|
{
|
|
logger?.LogInformation("Press \"Y\" key to delete file(s), \"N\" key to log file(s) or close console to not delete files");
|
|
consoleKey = Console.ReadKey().Key;
|
|
if (consoleKey is ConsoleKey.Y or ConsoleKey.N)
|
|
break;
|
|
}
|
|
logger?.LogInformation(". . .");
|
|
if (consoleKey is not null && consoleKey.Value == ConsoleKey.Y)
|
|
{
|
|
foreach (string file in deletedFiles)
|
|
{
|
|
if (!appSettings.RecycleOption)
|
|
{
|
|
try
|
|
{ File.Delete(file); }
|
|
catch (Exception) { }
|
|
}
|
|
else
|
|
{
|
|
try
|
|
{ Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(file, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin); }
|
|
catch (Exception) { }
|
|
}
|
|
}
|
|
totalSeconds = (int)Math.Floor(new TimeSpan(DateTime.Now.Ticks - ticks).TotalSeconds);
|
|
message = $") Looking for empty directories from <{directory}> - {totalSeconds} total second(s)";
|
|
progressBar = new(4, message, options);
|
|
for (int i = 1; i < 5; i++)
|
|
{
|
|
progressBar.Tick();
|
|
List<string> collection = [];
|
|
Shared.Models.Stateless.Methods.IPath.DeleteEmptyDirectories(directory, collection);
|
|
if (collection.Count == 0)
|
|
break;
|
|
deletedDirectories.AddRange(collection);
|
|
}
|
|
progressBar.Dispose();
|
|
logger?.LogInformation(". . .");
|
|
logFile = $"{ticks + 1}-{variable}-Directories.lsv";
|
|
File.WriteAllLines(Path.Combine(directory, logFile), deletedDirectories.Distinct());
|
|
}
|
|
}
|
|
if (!logOnly && renameFiles.Count != 0)
|
|
{
|
|
logFile = $"{ticks}-{variable}-Files-B.lsv";
|
|
File.WriteAllLines(Path.Combine(directory, logFile), renameFiles.Select(l => l.Source));
|
|
logFile = $"{ticks}-{variable}-Files-C.lsv";
|
|
File.WriteAllLines(Path.Combine(directory, logFile), renameFiles.Select(l => l.Destination));
|
|
logger?.LogInformation($"Ready to rename to match {renameFiles.Count} from {variable} {appSettings.SearchPattern} file(s)? See <{logFile}>");
|
|
for (int y = 0; y < int.MaxValue; y++)
|
|
{
|
|
logger?.LogInformation("Press \"Y\" key to rename to match file(s), \"N\" key to log file(s) or close console to not rename to match files");
|
|
consoleKey = Console.ReadKey().Key;
|
|
if (consoleKey is ConsoleKey.Y or ConsoleKey.N)
|
|
break;
|
|
}
|
|
logger?.LogInformation(". . .");
|
|
if (consoleKey is not null && consoleKey.Value == ConsoleKey.Y)
|
|
{
|
|
foreach ((string source, string destination) in renameFiles)
|
|
{
|
|
try
|
|
{ File.Move(source, destination); }
|
|
catch (Exception) { }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
} |