255 lines
10 KiB
C#
Raw Permalink Normal View History

2021-10-06 15:17:46 +13:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
namespace IP_Camera_Cleanup
{
class Program
{
public enum ExitCodes
{
Success,
InvalidArgument = -1,
FailedRate = -2
}
public static IEnumerable<string> Exemptions;
static bool silent = false;
static void Main(string[] args)
{
string folderPath = "";
string fileTypeString = "*.mp4";
int daysOld = 30;
if (args.Contains("\\f")) // Specify the folder path
{
int flagIndex = Array.IndexOf(args, "\\f");
if(flagIndex + 1 < args.Length)
{
folderPath = args[flagIndex + 1];
}
else
{
throw new ArgumentException("Missing or invalid source folder parameter.");
}
}
if (args.Where((s) => s == "\\s").Count() > 0)
{
// run in silent mode
silent = true;
}
if (args.Contains("\\d")) // specify the age of the file in days
{
int flagIndex = Array.IndexOf(args, "\\d");
if (flagIndex + 1 < args.Length && !args[flagIndex +1].StartsWith("\\"))
{
daysOld = int.Parse(args[flagIndex + 1]);
}
else
{
throw new ArgumentException("Missing or invalid file age parameter.");
}
}
if (args.Contains("\\t")) // specify the file type to search for
{
int flagIndex = Array.IndexOf(args, "\\t");
if (flagIndex + 1 < args.Length && !args[flagIndex + 1].StartsWith("\\") && args[flagIndex + 1].StartsWith("*."))
{
fileTypeString = args[flagIndex + 1];
}
else
{
throw new ArgumentException("Missing or invalid file type parameter.");
}
}
//else
//{
// Console.WriteLine("Invalid option. Valid options are: \'\\f\' {folder path}");
// Console.WriteLine("Enter a folder path or press \'q\' to exit");
// folderPath = Console.ReadLine();
//}
if (folderPath == "q")
{
Environment.ExitCode = (int)ExitCodes.InvalidArgument;
}
else if(folderPath != "")
{
using (FileStream fs = File.Open(".\\Exemptions.lst", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
byte[] exemptionsBytes = new byte[fs.Length];
fs.Read(exemptionsBytes, 0, exemptionsBytes.Length);
Console.WriteLine("Exemptions file Loaded");
Exemptions = Encoding.Unicode.GetString(exemptionsBytes, 0, exemptionsBytes.Length)
.Replace("\r\n", "\n").Split('\n').Where(x => x != "");
}
// Hard-coded exemptions, to prevent bad behaviour
Exemptions = Exemptions.Concat(new List<string> {"System Volume Information", "$RECYCLE.BIN", "C:\\Windows", "hiberfil.sys", "pagefile.sys", "swapfile.sys"});
foreach (var item in Exemptions)
{
Console.WriteLine(item);
}
Result result = DeleteAllFiles(folderPath, daysOld, fileTypeString);
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
if (result.Percentage < 0.75f) // Exit with an error code if more than 25% of files failed
{
eventLog.WriteEntry(string.Format("File Cleanup failed to delete {0}% ({1}/{2}) files.", (int)((1f-result.Percentage)*100), result.Failed ,result.Count), EventLogEntryType.Warning);
Environment.Exit((int)ExitCodes.FailedRate);
}
else
{
eventLog.WriteEntry(string.Format("File Cleanup successfully deleted {0}/{1} files ({2}%)",result.Count-result.Failed,result.Count,(int)(result.Percentage * 100)), EventLogEntryType.Information);
Environment.Exit(0);
}
}
}
}
static Result DeleteAllFiles(string folderPath, int daysOld, string fileTypeString)
{
// Cleaner option for enumerating files
if (silent)
{
long count = 0; // Calling Count() on validFiles would force enumeration of all values. Light-weight method is to just record how many we've iterated through. We're in silent so logging the total files found can be retrospective
long failiures = 0;
var rootDirs = Directory.EnumerateDirectories(folderPath, "*", SearchOption.TopDirectoryOnly).Where(x => Exemptions.All(e => !x.Contains(e)));
foreach (var dir in rootDirs)
{
try
{
IEnumerable<string> files = Directory.EnumerateFiles(dir, fileTypeString, SearchOption.AllDirectories).Where(x => IsDateOlder(x, daysOld));
foreach (var file in files)
{
count++;
try
{
File.Delete(file);
}
catch
{
failiures++;
}
}
}
catch (Exception e)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry("Failed to enumerate files: " + e, EventLogEntryType.Error, 2222, 1);
}
}
}
if (failiures == 0)
{
return new Result() { Count = count, Failed = 0, Percentage = 1f };
}
else
{
return new Result() { Count = count, Failed = failiures, Percentage = 1 - failiures / (float)count };
}
}
else
{
// Old implementation is left here
List<string> validFiles = FindFiles(folderPath).Where((s) => IsDateOlder(s, daysOld)).ToList();
Console.WriteLine("Deleting {0} files...", validFiles.Count());
int completeSize = validFiles.Count().ToString().Length;
int position = 0;
int failiures = 0;
foreach (string file in validFiles)
{
int Cursor_y = Console.CursorTop;
try
{
string line = new string(' ', completeSize - position.ToString().Length) + position;
Console.Write(line);
Console.SetCursorPosition(0, Cursor_y);
File.Delete(file);
position++;
}
catch (Exception e)
{
Console.WriteLine("Could not delete {0}: {1}", file, e);
position++;
failiures++;
}
}
if (failiures == 0)
{
return new Result() { Count = validFiles.Count, Failed = failiures, Percentage = 1f };
}
else
{
return new Result() { Count = validFiles.Count, Failed = failiures, Percentage = 0f};
}
}
}
static List<string> FindFiles(string FolderPath)
{
List<string> currentFound = new List<string>();
try
{
// Only enumerate files that aren't included in the exemptions
currentFound.AddRange(Directory.EnumerateFiles(FolderPath, "*.mp4", SearchOption.TopDirectoryOnly)
.Where((s) => Exemptions.All((e) => !s.Contains(e)))
.ToList());
foreach (string path in Directory.EnumerateDirectories(FolderPath).Where((s) => Exemptions.All((e) => !s.Contains(e))))
{
currentFound.AddRange(FindFiles(path));
}
}
catch (Exception e)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry("Failed to enumerate files in " + FolderPath, EventLogEntryType.Error, 101, 1);
}
if (!silent)
{
Console.WriteLine(e);
}
}
return currentFound;
}
static bool IsDateOlder(string fileName, int daysOld)
{
try
{
if (!Exemptions.Contains(fileName))
{
FileInfo fileInfo = new FileInfo(fileName);
return (DateTime.UtcNow.Subtract(fileInfo.LastWriteTimeUtc) > new TimeSpan(daysOld, 0, 0, 0));
}
}
catch { }
return false;
}
}
class Result
{
public float Percentage { get; set; }
public long Count { get; set; }
public long Failed { get; set; }
}
}