diff --git a/Snap2HTML-NG.CommandLine/Program.cs b/Snap2HTML-NG.CommandLine/Program.cs index 169d92f..551014e 100644 --- a/Snap2HTML-NG.CommandLine/Program.cs +++ b/Snap2HTML-NG.CommandLine/Program.cs @@ -2,76 +2,121 @@ using Snap2HTMLNG.Shared.Models; using System; using System.Collections.Generic; -using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Reflection; -using static System.Net.Mime.MediaTypeNames; namespace Snap2HTMLNG.CommandLine { internal class Program { + + private static bool _validationCheck = false; static void Main(string[] args) { - List normalizedArgs = Shared.Utils.CommandLine.Helpers.CommandLineSplit(args); - InitialValidation(normalizedArgs); +#if DEBUG + // Information + Shared.Utils.CommandLine.Helpers.WriteDebug($" THIS IS A PREVIEW BUILD."); + // New Lines + Console.WriteLine(""); +#endif - string scanPath = normalizedArgs.Find(x => x.Name == "path").Value; - string savePath = normalizedArgs.Find(x => x.Name == "output").Value; - - // Validate that the Scan Path actually exists - if(!Directory.Exists(scanPath)) - { - Shared.Utils.CommandLine.Helpers.WriteError($"Your scan path {scanPath} does not exist or Snap2HTML-NG does not have access."); - return; - } + List normalizedArgs = Shared.Utils.CommandLine.Helpers.CommandLineSplit(args); - // Check if the Save location actually exists - if(!Directory.Exists(Path.GetDirectoryName(savePath))) + if(normalizedArgs.Exists(x => x.Name == "help")) { - Shared.Utils.CommandLine.Helpers.WriteError($"Your save path {savePath} does not exist or Snap2HTML-NG does not have access."); + HelpInformation(); return; } - // Check if the rest of the settigns have been passed and assign - bool skipHidden = !normalizedArgs.Exists(x => x.Name == "hidden"); // if found, do not skip - bool skipSystem = !normalizedArgs.Exists(x => x.Name == "system"); // if found, do not skip - - // Check if the user wants to link files to the root which allows them to be easily selected when viewing in a browser - bool linkFilesToRoot = false; - if(normalizedArgs.Exists(x => x.Name == "link")) - { - linkFilesToRoot = true; - string linkPath = normalizedArgs.Find(x => x.Name == "link").Value; - } + InitialValidation(normalizedArgs); - string title = $"Snapshot of {savePath}"; - if(normalizedArgs.Exists(x => x.Name == "title")) + // Check if the initial validation checks have passed + if(_validationCheck) { - title = normalizedArgs.Find(x => x.Name == "title").Value; - } + string rootDirectory = normalizedArgs.Find(x => x.Name == "path").Value;// + @"\"; + string saveDirectory = normalizedArgs.Find(x => x.Name == "output").Value; + + // Check if the user has requested a randomized file name and set if they have + if(normalizedArgs.Exists(x =>x.Name == "randomize")) + { + Shared.Utils.CommandLine.Helpers.WriteInformation($"Randomized file name requested..."); + + string randomFileName = $"{Guid.NewGuid()}.html"; + + saveDirectory = $@"{saveDirectory}\{randomFileName}"; + + Shared.Utils.CommandLine.Helpers.WriteInformation($"Randomized file set to {randomFileName}"); + + Shared.Utils.CommandLine.Helpers.WriteInformation($"Output path is now: {saveDirectory}"); + + } + + // Validate that the Scan Path actually exists + if (!Directory.Exists(rootDirectory)) + { + Shared.Utils.CommandLine.Helpers.WriteError($"Your scan path {rootDirectory} does not exist or Snap2HTML-NG does not have access."); + return; + } + + // Check if the Save location actually exists + if (!Directory.Exists(Path.GetDirectoryName(saveDirectory))) + { + Shared.Utils.CommandLine.Helpers.WriteError($"Your save path {saveDirectory} does not exist or Snap2HTML-NG does not have access."); + return; + } + + // Check if the rest of the settigns have been passed and assign + bool skipHidden = !normalizedArgs.Exists(x => x.Name == "hidden"); // if found, do not skip + bool skipSystem = !normalizedArgs.Exists(x => x.Name == "system"); // if found, do not skip + + // Check if the user wants to link files to the root which allows them to be easily selected when viewing in a browser + bool linkFilesToRoot = false; + string linkDirectory = ""; + if (normalizedArgs.Exists(x => x.Name == "link")) + { + linkFilesToRoot = true; + linkDirectory = normalizedArgs.Find(x => x.Name == "link").Value; + } + + string title = $"Snapshot of {saveDirectory}"; + if (normalizedArgs.Exists(x => x.Name == "title")) + { + title = normalizedArgs.Find(x => x.Name == "title").Value; + } + + string searchPattern = "*"; // default is all + if (normalizedArgs.Exists(x => x.Name == "pattern")) + { + searchPattern = normalizedArgs.Find(x => x.Name == "pattern").Value; + } #if DEBUG - foreach (var normalizedArg in normalizedArgs) - { - Console.WriteLine($"Name: {normalizedArg.Name}, Value: {normalizedArg.Value}"); - } + foreach (var normalizedArg in normalizedArgs) + { + Shared.Utils.CommandLine.Helpers.WriteDebug($"Name: {normalizedArg.Name}, Value: {normalizedArg.Value}"); + } #endif + // Create the settings model and assign the relevant information to each property + UserSettingsModel usm = new UserSettingsModel + { + RootDirectory = rootDirectory, + Title = title, + OutputFile = saveDirectory, + SkipHiddenItems = skipHidden, + SkipSystemItems = skipSystem, + OpenInBrowserAfterCapture = false, // this will always be false in console mode + LinkFiles = linkFilesToRoot, + LinkRoot = linkDirectory, + SearchPattern = searchPattern + }; - // Get product name etc. - Assembly assembly = Assembly.GetExecutingAssembly(); - FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); - var productName = fvi.ProductName; - var productVersion = fvi.ProductVersion; - - // TODO: Need to change DataBuilder.cs in Shared to not read from the settings file and to accept - // data passed through from the commandLine. - DataBuilder.Build(productName, productVersion); + DataBuilder.Build(usm, ApplicationInformation().ProductName, ApplicationInformation().ProductVersion); - Console.ReadKey(); + Console.ReadKey(); + } } @@ -86,22 +131,96 @@ static void InitialValidation(List normalizedArgs) // Check if we have included any arguments at all, otherwise exit out. if (normalizedArgs.Count == 0) { - Shared.Utils.CommandLine.Helpers.WriteError("No arguments have been supplied that are recognized."); + Shared.Utils.CommandLine.Helpers.WriteError("No arguments have been supplied that are recognized. Use -h for help."); + _validationCheck = false; return; } // Check if we have included the REQUIRED argument -path:, otherwise exit out. if (!normalizedArgs.Exists(x => x.Name == "path")) { - Shared.Utils.CommandLine.Helpers.WriteError("You are missing the required argument '-path:'"); + Shared.Utils.CommandLine.Helpers.WriteError("You are missing the required argument '-path:'. Use -h for help."); + _validationCheck = false; return; } // Check if we have included the REQUIRED argument -output:, otherwise exit out. if (!normalizedArgs.Exists(x => x.Name == "output")) { - Shared.Utils.CommandLine.Helpers.WriteError("You are missing the required argument '-output:'"); + Shared.Utils.CommandLine.Helpers.WriteError("You are missing the required argument '-output:'. Use -h for help."); + _validationCheck = false; + return; } + + _validationCheck = true; + } + + /// + /// Returns Help information for using the Command Line + /// + static void HelpInformation() + { + Console.ForegroundColor = ConsoleColor.White; + + // Information + Console.WriteLine(" Application Information"); + Console.WriteLine($" {ApplicationInformation().ProductName} v{ApplicationInformation().ProductVersion}"); + + // New Lines + Console.WriteLine(""); + + // Description + Console.WriteLine(" Description:"); + Console.WriteLine(" Help information for Snap2HTML-NG.CommandLine"); + + // New Lines + Console.WriteLine(""); + + // Usage + Console.WriteLine(" Usage:"); + Console.WriteLine(" Snap2HTML-NG.CommandLine [options]"); + + // New Lines + Console.WriteLine(""); + + // Options + Console.WriteLine(" Options:"); + Console.WriteLine(" -path: [Required] The directory you want to scan"); + Console.WriteLine(" -output: [Required] The directory where you want to save the file, including the filename unless using -randomize"); + Console.WriteLine(" -link: [Optional] The directory where you want to link files in the html file"); + Console.WriteLine(" -title: [Optional] The title of the file which appears at the top of the html file"); + Console.WriteLine(" -hidden [Optional] Hides Hidden files from the scan, default is TRUE"); + Console.WriteLine(" -system [Optional] Hides System files from the scan, default is TRUE"); + Console.WriteLine(" -help, -h [Optional] Shows this information"); + Console.WriteLine(" -pattern [Optional] Search pattern to only return certain files, default is *"); + Console.WriteLine(" -randomize [Optional] Generates a random file name instead of needing to specify one in -output"); + + // New Lines + Console.WriteLine(""); + + // Examples + Console.WriteLine(" Examples:"); + Console.WriteLine(" Snap2HTML-NG.CommandLine -path:\"C:\\John.Doe\\Downloads\" -output:\"C:\\John.Doe\\Desktop\\Downloads.html\" "); + Console.WriteLine(" Snap2HTML-NG.CommandLine -path:\"C:\\John.Doe\\Downloads\" -output:\"C:\\John.Doe\\Desktop\" -randomize "); + Console.WriteLine(" Snap2HTML-NG.CommandLine -path:\"C:\\John.Doe\\Downloads\" -output:\"C:\\John.Doe\\Desktop\" -link:\"C:\\John.Doe\\Downloads\" -randomize "); + Console.WriteLine(" Snap2HTML-NG.CommandLine -path:\"C:\\John.Doe\\Downloads\" -output:\"C:\\John.Doe\\Desktop\" -link:\"C:\\John.Doe\\Downloads\" -randomize -pattern:\"*.mp4\""); + Console.WriteLine(" Snap2HTML-NG.CommandLine -path:\"C:\\John.Doe\\Videos\" -output:\"C:\\John.Doe\\Desktop\\videos.html\" -link:\"C:\\John.Doe\\Videos\" -pattern:\"*.mp4\" -title:\"Home Videos\""); + + } + + /// + /// Gets the application information using and + /// + /// + /// + /// + static FileVersionInfo ApplicationInformation() + { + // Get product name etc. + Assembly assembly = Assembly.GetExecutingAssembly(); + FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); + + return fvi; } } } diff --git a/Snap2HTML-NG.CommandLine/Properties/AssemblyInfo.cs b/Snap2HTML-NG.CommandLine/Properties/AssemblyInfo.cs index 57078c0..96eb99f 100644 --- a/Snap2HTML-NG.CommandLine/Properties/AssemblyInfo.cs +++ b/Snap2HTML-NG.CommandLine/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersion("3.0.0.0")] diff --git a/Snap2HTML-NG.GUI/Forms/frmMain.cs b/Snap2HTML-NG.GUI/Forms/frmMain.cs index 5901476..3fa2824 100644 --- a/Snap2HTML-NG.GUI/Forms/frmMain.cs +++ b/Snap2HTML-NG.GUI/Forms/frmMain.cs @@ -19,6 +19,9 @@ public frmMain() private void frmMain_Load(object sender, EventArgs e) { + Shared.Updater.Updater updater = new Shared.Updater.Updater(); + updater.CheckForUpdate(); + LoadUserSettings(); Text = Application.ProductName + " (Press F1 for Help)"; @@ -156,35 +159,6 @@ private void cmdCreate_Click(object sender, EventArgs e) private void StartProcessing() { - // ensure source path format - var rootFolder = Path.GetFullPath(XmlConfigurator.Read("RootFolder")); - - if (rootFolder.EndsWith(@"\")) rootFolder = rootFolder.Substring(0, rootFolder.Length - 1); - if (Shared.Utils.Legacy.Helpers.IsWildcardMatch("?:", rootFolder, false)) rootFolder += @"\"; // add backslash to path if only letter and colon eg "c:" - - // add slash or backslash to end of link (in cases where it is clear that we we can) - - bool linkFiles = bool.Parse(XmlConfigurator.Read("LinkFiles")); - string linkRoot = XmlConfigurator.Read("LinkRoot"); - if (linkFiles) - { - if (!linkRoot.EndsWith(@"/")) - { - if (linkRoot.ToLower().StartsWith(@"http") || linkRoot.ToLower().StartsWith(@"https")) // web site - { - linkRoot += @"/"; - } - if (Shared.Utils.Legacy.Helpers.IsWildcardMatch("?:*", linkRoot, false)) // local disk - { - linkRoot += @"\"; - } - if (linkRoot.StartsWith(@"\\")) // unc path - { - linkRoot += @"\"; - } - } - } - Cursor.Current = Cursors.WaitCursor; Text = "Snap2HTMLNG (Working... Press Escape to Cancel)"; tabCtrl.Enabled = false; diff --git a/Snap2HTML-NG.GUI/Forms/frmMain_BackgroundWorker.cs b/Snap2HTML-NG.GUI/Forms/frmMain_BackgroundWorker.cs index 33214e7..13951e1 100644 --- a/Snap2HTML-NG.GUI/Forms/frmMain_BackgroundWorker.cs +++ b/Snap2HTML-NG.GUI/Forms/frmMain_BackgroundWorker.cs @@ -1,6 +1,8 @@ using System.ComponentModel; using System.Windows.Forms; using Snap2HTMLNG.Shared.Builder; +using Snap2HTMLNG.Shared.Models; +using Snap2HTMLNG.Shared.Settings; namespace Snap2HTMLNG { @@ -9,7 +11,22 @@ public partial class frmMain : Form // This runs on a separate thread from the GUI private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { - DataBuilder.Build(Application.ProductName, Application.ProductVersion, backgroundWorker); + + // Load the user settings from the configuration file as we're using the GUI here + UserSettingsModel usm = new UserSettingsModel + { + RootDirectory = XmlConfigurator.Read("RootFolder"), + Title = XmlConfigurator.Read("Title"), + OutputFile = XmlConfigurator.Read("OutputFile"), + SkipHiddenItems = bool.Parse(XmlConfigurator.Read("SkipHiddenItems")), + SkipSystemItems = bool.Parse(XmlConfigurator.Read("SkipSystemItems")), + OpenInBrowserAfterCapture = bool.Parse(XmlConfigurator.Read("OpenInBrowserAfterCapture")), + LinkFiles = bool.Parse(XmlConfigurator.Read("LinkFiles")), + LinkRoot = XmlConfigurator.Read("LinkRoot"), + SearchPattern = XmlConfigurator.Read("SearchPattern") + }; + + DataBuilder.Build(usm, Application.ProductName, Application.ProductVersion, backgroundWorker); } } diff --git a/Snap2HTML-NG.Shared/Builder/DataBuilder.cs b/Snap2HTML-NG.Shared/Builder/DataBuilder.cs index 7e24b3c..3dcf430 100644 --- a/Snap2HTML-NG.Shared/Builder/DataBuilder.cs +++ b/Snap2HTML-NG.Shared/Builder/DataBuilder.cs @@ -5,11 +5,8 @@ using System.Text; using System; using Snap2HTMLNG.Shared.Utils.Legacy; -using Snap2HTMLNG.Shared.Settings; using System.Diagnostics; -using static System.Net.Mime.MediaTypeNames; using System.Windows.Forms; -using System.Drawing; namespace Snap2HTMLNG.Shared.Builder { @@ -73,7 +70,8 @@ public static void BuildJavascriptContentArray(List content, int } catch (Exception ex) { - // orphan file or folder? + Utils.CommandLine.Helpers.WriteError("POTENTIAL ERROR"); + Utils.CommandLine.Helpers.WriteInformation($"{ex.Message} - {ex}"); } } } @@ -133,7 +131,7 @@ public static void BuildJavascriptContentArray(List content, int /// Application Settings /// [Optional] BackgroundWorker Instance, only used by the GUI. /// - public static List GetContent(BackgroundWorker bgWorker = null) + public static List GetContent(UserSettingsModel settings, BackgroundWorker bgWorker = null) { // Prevents background worker calls if we're using the Command Line bool commandLine = false; @@ -149,8 +147,8 @@ public static List GetContent(BackgroundWorker bgWorker = null) // Get all folders var dirs = new List(); - dirs.Insert(0, XmlConfigurator.Read("RootFolder")); - DirSearch(XmlConfigurator.Read("RootFolder"), dirs, bool.Parse(XmlConfigurator.Read("SkipHiddenItems")), bool.Parse(XmlConfigurator.Read("SkipSystemItems")), stopwatch, bgWorker); + dirs.Insert(0, settings.RootDirectory); + DirSearch(settings.RootDirectory, dirs, settings.SkipHiddenItems, settings.SkipSystemItems, stopwatch, bgWorker); dirs = Helpers.SortDirList(dirs); // If we're using the GUI, account for BGworker cancellation @@ -192,7 +190,7 @@ public static List GetContent(BackgroundWorker bgWorker = null) } catch (Exception ex) { - Console.WriteLine("{0} Exception caught.", ex); + Utils.CommandLine.Helpers.WriteError($"{ex.Message} - {ex}"); } currentDir.Properties.Add("Modified", modified_date); currentDir.Properties.Add("Created", created_date); @@ -201,11 +199,11 @@ public static List GetContent(BackgroundWorker bgWorker = null) List files; try { - files = new List(Directory.GetFiles(dirName, XmlConfigurator.Read("SearchPattern"), SearchOption.TopDirectoryOnly)); + files = new List(Directory.GetFiles(dirName, settings.SearchPattern, SearchOption.TopDirectoryOnly)); } catch (Exception ex) { - Console.WriteLine("{0} Exception caught.", ex); + Utils.CommandLine.Helpers.WriteError($"{ex.Message} - {ex}"); result.Add(currentDir); continue; } @@ -236,11 +234,11 @@ public static List GetContent(BackgroundWorker bgWorker = null) var currentFile = new SnappedFile(Path.GetFileName(sFile)); try { - System.IO.FileInfo fi = new System.IO.FileInfo(sFile); - var isHidden = (fi.Attributes & System.IO.FileAttributes.Hidden) == System.IO.FileAttributes.Hidden; - var isSystem = (fi.Attributes & System.IO.FileAttributes.System) == System.IO.FileAttributes.System; + FileInfo fi = new FileInfo(sFile); + var isHidden = (fi.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden; + var isSystem = (fi.Attributes & FileAttributes.System) == FileAttributes.System; - if (isHidden && bool.Parse(XmlConfigurator.Read("SkipHiddenItems")) || (isSystem && bool.Parse(XmlConfigurator.Read("SkipSystemItems")))) + if (isHidden && settings.SkipHiddenItems || (isSystem && settings.SkipSystemItems)) { continue; } @@ -256,7 +254,7 @@ public static List GetContent(BackgroundWorker bgWorker = null) } catch (Exception ex) { - Console.WriteLine("{0} Exception caught.", ex); + Utils.CommandLine.Helpers.WriteError($"{ex.Message} "); } currentFile.Properties.Add("Modified", modified_date); @@ -265,7 +263,7 @@ public static List GetContent(BackgroundWorker bgWorker = null) } catch (Exception ex) { - Console.WriteLine("{0} Exception caught.", ex); + Utils.CommandLine.Helpers.WriteError($"{ex.Message} - {ex}"); } currentDir.Files.Add(currentFile); @@ -274,9 +272,9 @@ public static List GetContent(BackgroundWorker bgWorker = null) result.Add(currentDir); } } - catch (System.Exception ex) + catch (Exception ex) { - Console.WriteLine("{0} exception caught: {1}", ex, ex.Message); + Utils.CommandLine.Helpers.WriteError($"{ex.Message} - {ex}"); } return result; @@ -302,13 +300,20 @@ public static void DirSearch(string sDir, List lstDirs, bool skipHidden, // If we're using the GUI, account for bgWorker cancellation if (!commandLine && bgWorker.CancellationPending) + { return; + } - Console.WriteLine(sDir); +#if DEBUG + if(commandLine) + { + Utils.CommandLine.Helpers.WriteDebug($">> {sDir}"); + } +#endif try { - foreach (string d in System.IO.Directory.GetDirectories(sDir)) + foreach (string d in Directory.GetDirectories(sDir)) { bool includeThisFolder = true; @@ -341,25 +346,22 @@ public static void DirSearch(string sDir, List lstDirs, bool skipHidden, { lstDirs.Add(d); - if (stopwatch.ElapsedMilliseconds >= 50) + if (!commandLine) { - if(!commandLine) - { - bgWorker.ReportProgress(0, $"Getting directories {lstDirs.Count} ({d})"); - } else - { - Console.WriteLine($"Getting directories {lstDirs.Count} ({d})"); - } - stopwatch.Restart(); + bgWorker.ReportProgress(0, $"Getting directory # {lstDirs.Count}, Path: ({d})"); + } + else + { + Utils.CommandLine.Helpers.WriteInformation($"Getting directory # {lstDirs.Count}, Path: ({d})"); } DirSearch(d, lstDirs, skipHidden, skipSystem, stopwatch, bgWorker); } } } - catch (System.Exception ex) + catch (Exception ex) { - Console.WriteLine("ERROR in DirSearch(): " + ex.Message); + Utils.CommandLine.Helpers.WriteError("ERROR in DirSearch(): " + ex.Message); } } @@ -375,10 +377,10 @@ public static void DirSearch(string sDir, List lstDirs, bool skipHidden, /// Integer of Total Directories found /// Long of total size of all files /// - public static StringBuilder BuildHtml(StringBuilder template, string productName, string version, int totalFiles, int totalDirectories, long totalSize) + public static StringBuilder BuildHtml(UserSettingsModel settings, StringBuilder template, string productName, string version, int totalFiles, int totalDirectories, long totalSize) { // Build HTML - template.Replace("[TITLE]", XmlConfigurator.Read("Title")); + template.Replace("[TITLE]", settings.Title); template.Replace("[APP LINK]", "https://github.com/laim/Snap2HTML-NG"); template.Replace("[APP NAME]", productName); template.Replace("[APP VER]", version.Split('.')[0] + "." + version.Split('.')[1]); @@ -387,15 +389,15 @@ public static StringBuilder BuildHtml(StringBuilder template, string productName template.Replace("[NUM FILES]", totalFiles.ToString()); template.Replace("[NUM DIRS]", totalDirectories.ToString()); template.Replace("[TOT SIZE]", totalSize.ToString()); - template.Replace("[SEARCH_PATTERN]", XmlConfigurator.Read("SearchPattern")); + template.Replace("[SEARCH_PATTERN]", settings.SearchPattern); - if (bool.Parse(XmlConfigurator.Read("LinkFiles"))) + if (settings.LinkFiles) { template.Replace("[LINK FILES]", "true"); - template.Replace("[LINK ROOT]", XmlConfigurator.Read("LinkRoot").Replace(@"\", "/")); - template.Replace("[SOURCE ROOT]", XmlConfigurator.Read("RootFolder").Replace(@"\", "/")); + template.Replace("[LINK ROOT]", settings.LinkRoot.Replace(@"\", "/")); + template.Replace("[SOURCE ROOT]", settings.RootDirectory.Replace(@"\", "/")); - string link_root = XmlConfigurator.Read("LinkRoot").Replace(@"\", "/"); + string link_root = settings.LinkRoot.Replace(@"\", "/"); if (Helpers.IsWildcardMatch(@"?:/*", link_root, false)) // "file://" is needed in the browser if path begins with drive letter, else it should not be used { template.Replace("[LINK PROTOCOL]", @"file://"); @@ -415,18 +417,58 @@ public static StringBuilder BuildHtml(StringBuilder template, string productName template.Replace("[LINK FILES]", "false"); template.Replace("[LINK PROTOCOL]", ""); template.Replace("[LINK ROOT]", ""); - template.Replace("[SOURCE ROOT]", XmlConfigurator.Read("RootFolder").Replace(@"\", "/")); + template.Replace("[SOURCE ROOT]", settings.RootDirectory.Replace(@"\", "/")); } return template; } - - public static void Build(string applicationName, string applicationVersion, BackgroundWorker bgWorker = null) + + /// + /// Builds the output and saves it to the system + /// + /// + /// Settings information to be used as a + /// + /// + /// The application name as a + /// + /// + /// The application name as a + /// + /// + /// [Optional] BackgroundWorker Instance, only used by the GUI. + /// + public static void Build(UserSettingsModel settings, string applicationName, string applicationVersion, BackgroundWorker bgWorker = null) { + + // make some changes the settings information that has been passed through + // ensure source path format + if (settings.RootDirectory.EndsWith(@"\")) settings.RootDirectory = settings.RootDirectory.Substring(0, settings.RootDirectory.Length - 1); + if (Helpers.IsWildcardMatch("?:", settings.RootDirectory, false)) settings.RootDirectory += @"\"; // add backslash to path if only letter and colon eg "c:" + + // add slash or backslash to end of link (in cases where it is clear that we we can) + if (settings.LinkFiles) + { + if (!settings.LinkRoot.EndsWith(@"/")) + { + if (settings.LinkRoot.ToLower().StartsWith(@"http") || settings.LinkRoot.ToLower().StartsWith(@"https")) // web site + { + settings.LinkRoot += @"/"; + } + if (Helpers.IsWildcardMatch("?:*", settings.LinkRoot, false)) // local disk + { + settings.LinkRoot += @"\"; + } + if (settings.LinkRoot.StartsWith(@"\\")) // unc path + { + settings.LinkRoot += @"\"; + } + } + } + + // Get the directories and files - // TODO: Does this need switched to only include bgWorker if its passed? - // might need to do a null reference check - var content = GetContent(bgWorker); + var content = GetContent(settings, bgWorker); // Prevents background worker calls if we're using the Command Line bool commandLine = false; @@ -451,7 +493,7 @@ public static void Build(string applicationName, string applicationVersion, Back return; } else { - Console.WriteLine("Error reading source"); + Utils.CommandLine.Helpers.WriteError("Error reading source"); return; } } @@ -479,7 +521,7 @@ public static void Build(string applicationName, string applicationVersion, Back bgWorker.ReportProgress(0, "Generating HTML File"); } else { - Console.WriteLine("Generating HTML file"); + Utils.CommandLine.Helpers.WriteInformation("Generating HTML file"); } // Read the template into memory @@ -500,18 +542,18 @@ public static void Build(string applicationName, string applicationVersion, Back } else { Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"Failed to open Template.html, error {ex.Message}"); + Utils.CommandLine.Helpers.WriteError($"Failed to open Template.html, error {ex.Message}"); Console.ForegroundColor = ConsoleColor.White; } } // Build the intial section of the template - var builtHtml = BuildHtml(template, applicationName, applicationVersion, totalFiles, totalDirs, totalSize); + var builtHtml = BuildHtml(settings, template, applicationName, applicationVersion, totalFiles, totalDirs, totalSize); // Write the file / directory content to the file try { - using (StreamWriter writer = new StreamWriter(XmlConfigurator.Read("OutputFile"), false, Encoding.UTF8)) + using (StreamWriter writer = new StreamWriter(settings.OutputFile, false, Encoding.UTF8)) { writer.AutoFlush = true; @@ -529,20 +571,32 @@ public static void Build(string applicationName, string applicationVersion, Back bgWorker.ReportProgress(0, "Cancelled via User Request"); return; } - - writer.Write(builtTemplate.Substring(dataStart + 10)); } + writer.Write(builtTemplate.Substring(dataStart + 10)); + builtHtml = null; template = null; // Check if we're using the GUI and if we want to open in the browser after the data capture. // This does not work in command line mode as we assume that you'd be running it via a task or something. - if(!commandLine && bool.Parse(XmlConfigurator.Read("OpenInBrowserAfterCapture"))) + if(!commandLine && settings.OpenInBrowserAfterCapture) { - Process.Start(XmlConfigurator.Read("OutputFile")); + Process.Start(settings.OutputFile); } } + + // if we get this far, everything should be complete. + // Generate the actual output + if (!commandLine) + { + bgWorker.ReportProgress(100, $"File generated to {settings.OutputFile}"); + } + else + { + Utils.CommandLine.Helpers.WriteInformation($"File generated to {settings.OutputFile}"); + Environment.Exit(0); + } } catch (Exception ex) { if (!commandLine) @@ -554,7 +608,7 @@ public static void Build(string applicationName, string applicationVersion, Back else { Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"Failed to open file for writing, error {ex.Message}"); + Utils.CommandLine.Helpers.WriteError($"Failed to open file for writing, error {ex.Message}"); Console.ForegroundColor = ConsoleColor.White; } } diff --git a/Snap2HTML-NG.Shared/Models/ReleasesModel.cs b/Snap2HTML-NG.Shared/Models/ReleasesModel.cs new file mode 100644 index 0000000..f080f00 --- /dev/null +++ b/Snap2HTML-NG.Shared/Models/ReleasesModel.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Xml.Serialization; + +namespace Snap2HTMLNG.Shared.Models +{ + public class ReleasesModel + { + public string url { get; set; } + public string assets_url { get; set; } + public string upload_url { get; set; } + public string html_url { get; set; } + public int id { get; set; } + public Author author { get; set; } + public string node_id { get; set; } + public string tag_name { get; set; } + public string target_commitish { get; set; } + public string name { get; set; } + public bool draft { get; set; } + public bool prerelease { get; set; } + public DateTime created_at { get; set; } + public DateTime published_at { get; set; } + public List assets { get; set; } + public string tarball_url { get; set; } + public string zipball_url { get; set; } + public string body { get; set; } + + public class Asset + { + public string url { get; set; } + public int id { get; set; } + public string node_id { get; set; } + public string name { get; set; } + public object label { get; set; } + public Uploader uploader { get; set; } + public string content_type { get; set; } + public string state { get; set; } + public int size { get; set; } + public int download_count { get; set; } + public DateTime created_at { get; set; } + public DateTime updated_at { get; set; } + public string browser_download_url { get; set; } + } + + public class Author + { + public string login { get; set; } + public int id { get; set; } + public string node_id { get; set; } + public string avatar_url { get; set; } + public string gravatar_id { get; set; } + public string url { get; set; } + public string html_url { get; set; } + public string followers_url { get; set; } + public string following_url { get; set; } + public string gists_url { get; set; } + public string starred_url { get; set; } + public string subscriptions_url { get; set; } + public string organizations_url { get; set; } + public string repos_url { get; set; } + public string events_url { get; set; } + public string received_events_url { get; set; } + public string type { get; set; } + public bool site_admin { get; set; } + } + + public class Uploader + { + public string login { get; set; } + public int id { get; set; } + public string node_id { get; set; } + public string avatar_url { get; set; } + public string gravatar_id { get; set; } + public string url { get; set; } + public string html_url { get; set; } + public string followers_url { get; set; } + public string following_url { get; set; } + public string gists_url { get; set; } + public string starred_url { get; set; } + public string subscriptions_url { get; set; } + public string organizations_url { get; set; } + public string repos_url { get; set; } + public string events_url { get; set; } + public string received_events_url { get; set; } + public string type { get; set; } + public bool site_admin { get; set; } + } + + } +} diff --git a/Snap2HTML-NG.Shared/Models/UserSettingsModel.cs b/Snap2HTML-NG.Shared/Models/UserSettingsModel.cs new file mode 100644 index 0000000..baa6f03 --- /dev/null +++ b/Snap2HTML-NG.Shared/Models/UserSettingsModel.cs @@ -0,0 +1,80 @@ +using System.Runtime.CompilerServices; + +namespace Snap2HTMLNG.Shared.Models +{ + public class UserSettingsModel + { + private string _rootDirectory; + + public string RootDirectory + { + get { return _rootDirectory; } + set { _rootDirectory = value; } + } + + private string _title; + + public string Title + { + get { return _title; } + set { _title = value; } + } + + private string _outputFile; + + public string OutputFile + { + get { return _outputFile; } + set { _outputFile = value; } + } + + private bool _skipHiddenItems; + + public bool SkipHiddenItems + { + get { return _skipHiddenItems; } + set { _skipHiddenItems = value; } + } + + private bool _skipSystemItems; + + public bool SkipSystemItems + { + get { return _skipSystemItems; } + set { _skipSystemItems = value; } + } + + private bool _openInBrowserAfterCapture; + + public bool OpenInBrowserAfterCapture + { + get { return _openInBrowserAfterCapture; } + set { _openInBrowserAfterCapture = value; } + } + + private bool _linkFiles; + + public bool LinkFiles + { + get { return _linkFiles; } + set { _linkFiles = value; } + } + + private string _linkRoot; + + public string LinkRoot + { + get { return _linkRoot; } + set { _linkRoot = value; } + } + + private string _searchPattern; + + public string SearchPattern + { + get { return _searchPattern; } + set { _searchPattern = value; } + } + + } +} diff --git a/Snap2HTML-NG.Shared/Snap2HTML-NG.Shared.csproj b/Snap2HTML-NG.Shared/Snap2HTML-NG.Shared.csproj index 50be658..e14e09f 100644 --- a/Snap2HTML-NG.Shared/Snap2HTML-NG.Shared.csproj +++ b/Snap2HTML-NG.Shared/Snap2HTML-NG.Shared.csproj @@ -31,9 +31,13 @@ 4 + + ..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll + + @@ -45,15 +49,20 @@ + + + - + + + PreserveNewest diff --git a/Snap2HTML-NG.Shared/Updater/Updater.cs b/Snap2HTML-NG.Shared/Updater/Updater.cs new file mode 100644 index 0000000..d0953c3 --- /dev/null +++ b/Snap2HTML-NG.Shared/Updater/Updater.cs @@ -0,0 +1,48 @@ +using Newtonsoft.Json; +using Snap2HTMLNG.Shared.Models; +using Snap2HTMLNG.Shared.Settings; +using System; +using System.IO; +using System.Net; + +namespace Snap2HTMLNG.Shared.Updater +{ + public class Updater + { + + // Repo Release Feed + private const string _updateURL = "https://api.github.com/repos/laim/snap2html-ng/releases/latest"; + + // fall back should always be false, we don't want to force check for + // updates on people as Snap2HTML OG never had a check for update at all + private bool _checkForUpdates = false; + + public Updater() + { + _checkForUpdates = bool.Parse(XmlConfigurator.Read("CheckForUpdates")); + } + + public void CheckForUpdate() + { + if(_checkForUpdates) + { + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_updateURL); + request.UserAgent = new Random(new Random().Next()).ToString(); + + var response = request.GetResponse(); + if(response != null) + { + StreamReader reader = new StreamReader(response.GetResponseStream()); + + string output = reader.ReadToEnd(); + + var data = JsonConvert.DeserializeObject(output); + + Console.WriteLine(data.tag_name); + } + + } + } + + } +} diff --git a/Snap2HTML-NG.Shared/UserSettings.xml b/Snap2HTML-NG.Shared/UserSettings.xml index 200c55d..b86cc15 100644 --- a/Snap2HTML-NG.Shared/UserSettings.xml +++ b/Snap2HTML-NG.Shared/UserSettings.xml @@ -11,5 +11,7 @@ false * + + false diff --git a/Snap2HTML-NG.Shared/Utils/CommandLine/Helpers.cs b/Snap2HTML-NG.Shared/Utils/CommandLine/Helpers.cs index 421277e..9fa28ee 100644 --- a/Snap2HTML-NG.Shared/Utils/CommandLine/Helpers.cs +++ b/Snap2HTML-NG.Shared/Utils/CommandLine/Helpers.cs @@ -70,6 +70,24 @@ public static List CommandLineSplit(string[] args) list.Add(new CommandLineModel { Name = "system", Value = "" }); } + // Return Help information + if(arg.StartsWith("-help") || arg.StartsWith("-h")) + { + list.Add(new CommandLineModel { Name = "help", Value = "" }); + } + + // Search Pattern, default is * + if(arg.StartsWith("-pattern:")) + { + list.Add(new CommandLineModel { Name = "pattern", Value = arg.Split(new char[] {':'}, 2).Last() }); + } + + // Randomize the file name + if(arg.StartsWith("-randomize")) + { + list.Add(new CommandLineModel { Name = "randomize", Value = "" }); + } + } @@ -89,5 +107,31 @@ public static void WriteError(string message) Console.WriteLine($"{message}"); Console.ForegroundColor = ConsoleColor.White; } + + /// + /// Changes the foreground color of the console to cyan, writes the message, then changes it back to white + /// + /// + /// Desired informational message to show the user as a + /// + public static void WriteInformation(string message) + { + Console.ForegroundColor = ConsoleColor.Cyan; + Console.WriteLine($"{message}"); + Console.ForegroundColor = ConsoleColor.White; + } + + /// + /// Changes the foreground color of the console to Magenta, writes the message, then changes it back to white + /// + /// + /// Desired informational message to show the user as a + /// + public static void WriteDebug(string message) + { + Console.ForegroundColor = ConsoleColor.DarkMagenta; + Console.WriteLine($"{message}"); + Console.ForegroundColor = ConsoleColor.White; + } } } diff --git a/Snap2HTML-NG.Shared/packages.config b/Snap2HTML-NG.Shared/packages.config new file mode 100644 index 0000000..e46d5a8 --- /dev/null +++ b/Snap2HTML-NG.Shared/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file