diff --git a/Fb2Kindle/Convertor.cs b/Fb2Kindle/Convertor.cs index c5bf49c..e37f952 100644 --- a/Fb2Kindle/Convertor.cs +++ b/Fb2Kindle/Convertor.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Drawing; -using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; @@ -91,7 +90,7 @@ internal bool ConvertBookSequence(string[] books) { if (ProcessImages(book, tempDir, $"Images\\{bookPostfix}", coverDone)) { var imgSrc = Util.AttributeValue(book.Elements("description").Elements("title-info").Elements("coverpage").Elements("div").Elements("img"), "src"); if (!string.IsNullOrEmpty(imgSrc)) { - AutoScaleImage(Path.Combine(tempDir, imgSrc)); + ImagesHelper.AutoScaleImage(Path.Combine(tempDir, imgSrc)); if (!coverDone) { opfFile.Elements("metadata").First().Elements("x-metadata").First().Add(new XElement("EmbeddedCover", imgSrc)); AddGuideItem("Cover", imgSrc, "other.ms-coverimage-standard"); @@ -237,7 +236,7 @@ private void UpdateLinksInBook(XElement book, string filename) { } //update found links hrefs foreach (var a in book.Descendants("a")) { - var href = a.Attribute("href").Value; + var href = a.Attribute("href")?.Value; if (string.IsNullOrEmpty(href) || !links.ContainsKey(href)) continue; var value = a.Value; a.RemoveAll(); @@ -246,14 +245,13 @@ private void UpdateLinksInBook(XElement book, string filename) { } } - private int SaveSubSections(XElement section, int bookNum, XElement toc, string postfix, string bookFileName) { + private static int SaveSubSections(XElement section, int bookNum, XElement toc, string postfix, string bookFileName) { var bookId = "i" + bookNum + postfix; var t = section.Elements("title").FirstOrDefault(el => !string.IsNullOrWhiteSpace(el.Value)); //var t = section.Descendants("title").FirstOrDefault(el => !string.IsNullOrWhiteSpace(el.Value)); - // if (t == null || string.IsNullOrEmpty(t.Value)) - // { - // t = section.Elements("p").FirstOrDefault(); - // } + // if (t == null || string.IsNullOrEmpty(t.Value)) { + // t = section.Elements("p").FirstOrDefault(); + // } if (t != null && !string.IsNullOrEmpty(t.Value)) { Util.RenameTag(t, "div", "title"); @@ -291,14 +289,13 @@ private void ProcessAllData(XElement book, XElement bookRoot, string postfix, XE var additionalParts = new List>(); for (var i = 1; i < bodies.Length; i++) { Util.RenameTag(bodies[i], "section"); - // if (i < bodies.Length - 1) - // { - // //all but last -> merge into first body - // if (bodies[i].Parent != null) - // bodies[i].Remove(); - // bodies[0].Add(bodies[i]); - // continue; - // } + // if (i < bodies.Length - 1) { + // //all but last -> merge into first body + // if (bodies[i].Parent != null) + // bodies[i].Remove(); + // bodies[0].Add(bodies[i]); + // continue; + // } additionalParts.Add(new KeyValuePair($"body{i}", bodies[i])); } @@ -346,7 +343,7 @@ private void ProcessAllData(XElement book, XElement bookRoot, string postfix, XE Util.WriteLine("(OK)", ConsoleColor.Green); } - private void SetBigFirstLetters(XElement body) { + private static void SetBigFirstLetters(XElement body) { var regex = new Regex(@"^

(\w{1})([\s\w]+.+?)

$"); var sections = body.Descendants("section"); foreach (var sec in sections) { @@ -460,7 +457,7 @@ private static string GetVersionedPath(string filePath, string fileName = null, private bool SendAndClean(string bookName, string bookPath, string tempDir, string tmpBookPath, bool showOutput, string extension) { - bool saveLocal = true; + var saveLocal = true; if (!string.IsNullOrWhiteSpace(MailTo)) { // Wait for it to finish saveLocal = !SendBookByMail(bookName, tmpBookPath); @@ -530,18 +527,19 @@ private bool SendBookByMail(string bookName, string tmpBookPath) { return false; } - private static List GetAuthors(IEnumerable avtorbook, int maxCount = int.MaxValue) { - var result = new List(); - foreach (var ai in avtorbook) { + private static IEnumerable GetAuthors(IEnumerable bookAuthors, int maxCount = int.MaxValue) { + var returned = 0; + foreach (var ai in bookAuthors) { var author = $"{Util.Value(ai.Elements("last-name"))} {Util.Value(ai.Elements("first-name"))} {Util.Value(ai.Elements("middle-name"))}"; - if (!string.IsNullOrWhiteSpace(author)) - result.Add(author.Trim()); - if (result.Count >= maxCount) - break; - } - if (result.Count == 0) - result.Add(NoAuthorText); - return result; + if (!string.IsNullOrWhiteSpace(author)) { + yield return author.Trim(); + returned++; + } + if (returned >= maxCount) + yield break; + } + if (returned == 0) + yield return NoAuthorText; } private static XElement CreateTitlePage(XElement book) { @@ -625,7 +623,7 @@ private static void ConvertTagsToHtml(XElement book, bool full = false) { private static XElement LoadBookWithoutNs(string fileName) { try { XElement book; - // book = ReadXDocumentWithInvalidCharacters(fileName).Root; + //book = ReadXDocumentWithInvalidCharacters(fileName).Root; using (Stream file = File.OpenRead(fileName)) { book = XElement.Load(file, LoadOptions.PreserveWhitespace); } @@ -817,30 +815,29 @@ private bool ExtractImages(XElement book, string workFolder, string imagesPrefix foreach (var binEl in book.Elements("binary")) { try { var file = GetImageNameWithExt($"{workFolder}\\{imagesPrefix}{binEl.Attribute("id").Value}"); - var format = GetImageFormatFromMimeType(binEl.Attribute("content-type")?.Value, currentSettings.Jpeg ? ImageFormat.Jpeg : ImageFormat.Png); + var format = ImagesHelper.GetImageFormatFromMimeType(binEl.Attribute("content-type")?.Value, currentSettings.Jpeg ? ImageFormat.Jpeg : ImageFormat.Png); //todo: we can get format from img.RawFormat var fileBytes = Convert.FromBase64String(binEl.Value); try { using (Stream str = new MemoryStream(fileBytes)) { using (var img = Image.FromStream(str)) { - // var pngCodec = Util.GetEncoderInfo(ImageFormat.Png); - // if (pngCodec != null) - // { - // var parameters = new EncoderParameters(1) { - // Param = { - // [0] = new EncoderParameter(Encoder.ColorDepth, 24) - // } - // }; - // img.Save(file, pngCodec, parameters); - // } - // else + // var pngCodec = Util.GetEncoderInfo(ImageFormat.Png); + // if (pngCodec != null) { + // var parameters = new EncoderParameters(1) { + // Param = { + // [0] = new EncoderParameter(Encoder.ColorDepth, 24) + // } + // }; + // img.Save(file, pngCodec, parameters); + // } + // else img.Save(file, format); } } if (currentSettings.Grayscaled) { Image gsImage; using (var img = Image.FromFile(file)) { - gsImage = GrayScale(img, true, format); + gsImage = ImagesHelper.GrayScale(img, true, format); } gsImage.Save(file, format); } @@ -858,136 +855,6 @@ private bool ExtractImages(XElement book, string workFolder, string imagesPrefix return true; } - private static void AutoScaleImage(string coverFilePath, int width = 600, int height = 800) { - Image scaledImage = null; - var imgFormat = ImageFormat.Png; - using (var img = Image.FromFile(coverFilePath)) { - if (img.Size.Width < width && img.Size.Height < height) { - imgFormat = GetImageFormatFromMimeType(GetMimeType(img), ImageFormat.Png); - scaledImage = ResizeImage(img, 600, 800); - } - } - if (scaledImage == null) return; - scaledImage.Save(coverFilePath, imgFormat); - scaledImage.Dispose(); - } - - private static double GetScaleFactor(Image original, int width, int height) { - var originalWidth = original.Width; - var originalHeight = original.Height; - double factor; - if (originalWidth > originalHeight) - factor = (double)width / originalWidth; - else - factor = (double)height / originalHeight; - return factor; - } - - private static Image ResizeImage(Image image, int width, int height) { - var factor = GetScaleFactor(image, width, height); - width = (int)Math.Round(image.Width * factor); - height = (int)Math.Round(image.Height * factor); - var destRect = new Rectangle(0, 0, width, height); - var destImage = new Bitmap(width, height); - destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - using (var graphics = Graphics.FromImage(destImage)) { - graphics.CompositingMode = CompositingMode.SourceCopy; - graphics.CompositingQuality = CompositingQuality.HighQuality; - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.SmoothingMode = SmoothingMode.HighQuality; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - - using (var wrapMode = new ImageAttributes()) { - wrapMode.SetWrapMode(WrapMode.TileFlipXY); - graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); - } - } - return destImage; - } - - // private static ImageCodecInfo GetEncoderInfo(string extension) { - // extension = extension.ToLower(); - // var codecs = ImageCodecInfo.GetImageEncoders(); - // for (var i = 0; i < codecs.Length; i++) - // if (codecs[i].FilenameExtension.ToLower().Contains(extension)) - // return codecs[i]; - // return null; - // } - // - // private static ImageCodecInfo GetEncoderInfo(ImageFormat format) { - // return ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID.Equals(format.Guid)); - // } - - private static string GetMimeType(Image image) { - return GetMimeType(image.RawFormat); - } - - private static string GetMimeType(ImageFormat imageFormat) { - var codecs = ImageCodecInfo.GetImageEncoders(); - return codecs.First(codec => codec.FormatID == imageFormat.Guid).MimeType; - } - - private static ImageFormat GetImageFormatFromMimeType(string contentType, ImageFormat defaultResult) { - if (GetMimeType(ImageFormat.Jpeg).Equals(contentType, StringComparison.OrdinalIgnoreCase)) { - return ImageFormat.Jpeg; - } - if (GetMimeType(ImageFormat.Bmp).Equals(contentType, StringComparison.OrdinalIgnoreCase)) { - return ImageFormat.Bmp; - } - if (GetMimeType(ImageFormat.Png).Equals(contentType, StringComparison.OrdinalIgnoreCase)) { - return ImageFormat.Png; - } - // foreach (var codecInfo in ImageCodecInfo.GetImageEncoders()) - // { - // if (codecInfo.MimeType.Equals(contentType, StringComparison.OrdinalIgnoreCase)) - // { - // return codecInfo.FormatID; - // } - // } - return defaultResult; - } - - private static Image GrayScale(Image img, bool fast, ImageFormat format) { - Stream imageStream = new MemoryStream(); - if (fast) { - using (var bmp = new Bitmap(img)) { - var gsBmp = MakeGrayscale3(bmp); - gsBmp.Save(imageStream, format); - } - } - else { - using (var bmp = new Bitmap(img)) { - for (var y = 0; y < bmp.Height; y++) - for (var x = 0; x < bmp.Width; x++) { - var c = bmp.GetPixel(x, y); - var rgb = (c.R + c.G + c.B) / 3; - bmp.SetPixel(x, y, Color.FromArgb(rgb, rgb, rgb)); - } - bmp.Save(imageStream, format); - } - } - return Image.FromStream(imageStream); - } - - private static Bitmap MakeGrayscale3(Bitmap original) { - var newBitmap = new Bitmap(original.Width, original.Height); - var g = Graphics.FromImage(newBitmap); - var colorMatrix = new ColorMatrix(new[] - { - new[] {.3f, .3f, .3f, 0, 0}, - new[] {.59f, .59f, .59f, 0, 0}, - new[] {.11f, .11f, .11f, 0, 0}, - new float[] {0, 0, 0, 1, 0}, - new float[] {0, 0, 0, 0, 1} - }); - var attributes = new ImageAttributes(); - attributes.SetColorMatrix(colorMatrix); - g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), - 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); - g.Dispose(); - return newBitmap; - } - #endregion Images } } diff --git a/Fb2Kindle/Fb2Kindle.csproj b/Fb2Kindle/Fb2Kindle.csproj index efdc5e0..4e0a973 100644 --- a/Fb2Kindle/Fb2Kindle.csproj +++ b/Fb2Kindle/Fb2Kindle.csproj @@ -67,6 +67,7 @@ + diff --git a/Fb2Kindle/ImagesHelper.cs b/Fb2Kindle/ImagesHelper.cs new file mode 100644 index 0000000..6211680 --- /dev/null +++ b/Fb2Kindle/ImagesHelper.cs @@ -0,0 +1,141 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; + +namespace Fb2Kindle { + public static class ImagesHelper { + + internal static Bitmap MakeGrayscale3(Bitmap original) { + var newBitmap = new Bitmap(original.Width, original.Height); + var g = Graphics.FromImage(newBitmap); + var colorMatrix = new ColorMatrix(new[] { + new[] {.3f, .3f, .3f, 0, 0}, + new[] {.59f, .59f, .59f, 0, 0}, + new[] {.11f, .11f, .11f, 0, 0}, + new float[] {0, 0, 0, 1, 0}, + new float[] {0, 0, 0, 0, 1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), + 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); + g.Dispose(); + return newBitmap; + } + + internal static Image GrayScale(Image img, bool fast, ImageFormat format) { + Stream imageStream = new MemoryStream(); + if (fast) { + using (var bmp = new Bitmap(img)) { + var gsBmp = ImagesHelper.MakeGrayscale3(bmp); + gsBmp.Save(imageStream, format); + } + } + else { + using (var bmp = new Bitmap(img)) { + for (var y = 0; y < bmp.Height; y++) + for (var x = 0; x < bmp.Width; x++) { + var c = bmp.GetPixel(x, y); + var rgb = (c.R + c.G + c.B) / 3; + bmp.SetPixel(x, y, Color.FromArgb(rgb, rgb, rgb)); + } + bmp.Save(imageStream, format); + } + } + return Image.FromStream(imageStream); + } + + internal static string GetMimeType(Image image) { + return GetMimeType(image.RawFormat); + } + + internal static string GetMimeType(ImageFormat imageFormat) { + var codecs = ImageCodecInfo.GetImageEncoders(); + return codecs.First(codec => codec.FormatID == imageFormat.Guid).MimeType; + } + + internal static ImageFormat GetImageFormatFromMimeType(string contentType, ImageFormat defaultResult) { + if (GetMimeType(ImageFormat.Jpeg).Equals(contentType, StringComparison.OrdinalIgnoreCase)) { + return ImageFormat.Jpeg; + } + if (GetMimeType(ImageFormat.Bmp).Equals(contentType, StringComparison.OrdinalIgnoreCase)) { + return ImageFormat.Bmp; + } + if (GetMimeType(ImageFormat.Png).Equals(contentType, StringComparison.OrdinalIgnoreCase)) { + return ImageFormat.Png; + } + + // foreach (var codecInfo in ImageCodecInfo.GetImageEncoders()) { + // if (codecInfo.MimeType.Equals(contentType, StringComparison.OrdinalIgnoreCase)) { + // return codecInfo.FormatID; + // } + // } + + return defaultResult; + } + + internal static void AutoScaleImage(string coverFilePath, int width = 600, int height = 800) { + Image scaledImage = null; + var imgFormat = ImageFormat.Png; + using (var img = Image.FromFile(coverFilePath)) { + if (img.Size.Width < width && img.Size.Height < height) { + imgFormat = ImagesHelper.GetImageFormatFromMimeType(ImagesHelper.GetMimeType(img), ImageFormat.Png); + scaledImage = ResizeImage(img, 600, 800); + } + } + if (scaledImage == null) return; + scaledImage.Save(coverFilePath, imgFormat); + scaledImage.Dispose(); + } + + internal static double GetScaleFactor(Image original, int width, int height) { + var originalWidth = original.Width; + var originalHeight = original.Height; + double factor; + if (originalWidth > originalHeight) + factor = (double)width / originalWidth; + else + factor = (double)height / originalHeight; + return factor; + } + + internal static Image ResizeImage(Image image, int width, int height) { + var factor = GetScaleFactor(image, width, height); + width = (int)Math.Round(image.Width * factor); + height = (int)Math.Round(image.Height * factor); + var destRect = new Rectangle(0, 0, width, height); + var destImage = new Bitmap(width, height); + destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); + using (var graphics = Graphics.FromImage(destImage)) { + graphics.CompositingMode = CompositingMode.SourceCopy; + graphics.CompositingQuality = CompositingQuality.HighQuality; + graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; + graphics.SmoothingMode = SmoothingMode.HighQuality; + graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; + + using (var wrapMode = new ImageAttributes()) { + wrapMode.SetWrapMode(WrapMode.TileFlipXY); + graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); + } + } + return destImage; + } + + // private static ImageCodecInfo GetEncoderInfo(string extension) { + // extension = extension.ToLower(); + // var codecs = ImageCodecInfo.GetImageEncoders(); + // for (var i = 0; i < codecs.Length; i++) + // if (codecs[i].FilenameExtension.ToLower().Contains(extension)) + // return codecs[i]; + // return null; + // } + // + // private static ImageCodecInfo GetEncoderInfo(ImageFormat format) { + // return ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID.Equals(format.Guid)); + // } + + } +} \ No newline at end of file diff --git a/Fb2Kindle/Program.cs b/Fb2Kindle/Program.cs index 489cfcd..30f73e0 100644 --- a/Fb2Kindle/Program.cs +++ b/Fb2Kindle/Program.cs @@ -2,25 +2,24 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; -using System.Reflection; using System.Text; namespace Fb2Kindle { static class Program { - private static void ShowHelpText(Assembly asm) { + private static void ShowHelpText() { Util.WriteLine(); - Util.WriteLine(asm.GetName().Name + " [-css ] [-d] [-ni] [-mailto:recipient@mail.org]"); + Util.WriteLine(Updater.AppName + " [-css ] [-d] [-ni] [-mailto:recipient@mail.org]"); Util.WriteLine(); Util.WriteLine(": input fb2 file or files mask (ex: *.fb2) or path to *fb2 files"); Util.WriteLine("-epub: create file in epub format"); Util.WriteLine("-css : styles used in destination book"); - Util.WriteLine("-d: delete source file after successful convertion"); + Util.WriteLine("-d: delete source file after successful conversion"); Util.WriteLine("-c: use compression (slow)"); Util.WriteLine("-o: hide detailed output"); Util.WriteLine("-s: add sequence and number to title"); Util.WriteLine("-ni: no images"); Util.WriteLine("-dc: DropCaps mode"); - Util.WriteLine("-g: grayscaled images"); + Util.WriteLine("-g: grayscale images"); Util.WriteLine("-jpeg: save images in jpeg"); Util.WriteLine("-ntoc: no table of content"); Util.WriteLine("-nch: no chapters"); @@ -36,19 +35,16 @@ private static void ShowHelpText(Assembly asm) { Util.WriteLine("-w: wait for key press on finish"); Util.WriteLine("-preview: keep generated source files"); - Util.WriteLine("-debug: keep all generated source files"); Util.WriteLine("-u or -update: update application to the latest version"); Util.WriteLine(); } - private static void ShowMainInfo(Assembly asm) { - // Console.Clear(); + private static void ShowMainInfo() { + //Console.Clear(); Util.WriteLine(); - var ver = asm.GetName().Version; - Util.WriteLine($"{asm.GetName().Name} Version: {ver.ToString(3)}; Build time: {Util.GetBuildTime(ver):yyyy/MM/dd HH:mm:ss}", ConsoleColor.White); - var title = Util.GetAttribute(asm); - if (title != null) - Util.WriteLine(title.Title, ConsoleColor.White); + Util.WriteLine($"{Updater.AppName} Version: {Updater.CurrentVersion}", ConsoleColor.White); + if (Updater.AppTitle != null) + Util.WriteLine(Updater.AppTitle, ConsoleColor.White); Util.WriteLine(); } @@ -63,11 +59,10 @@ public static void Main(string[] args) { var startedTime = DateTime.Now; DefaultOptions currentSettings = null; try { - var asm = Assembly.GetExecutingAssembly(); - ShowMainInfo(asm); + ShowMainInfo(); var appPath = Util.GetAppPath(); - var settingsFile = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, ".json"); + var settingsFile = Path.ChangeExtension(Updater.CurrentFileLocation, ".json"); currentSettings = SerializerHelper.ReadJsonFile(settingsFile) ?? new DefaultOptions(); //var settingsFile = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, ".xml"); //var currentSettings = XmlSerializerHelper.DeserializeFile(settingsFile) ?? new DefaultOptions(); @@ -76,7 +71,7 @@ public static void Main(string[] args) { string mailTo = null; if (args.Length == 0) { - ShowHelpText(asm); + ShowHelpText(); Util.Write("Process all files with default parameters (-a -r -w)? Press 'Enter' to continue: ", ConsoleColor.White); if (Console.ReadKey().Key != ConsoleKey.Enter) return; @@ -86,7 +81,7 @@ public static void Main(string[] args) { } else { if (args[0] == "newconsole") { - string parameters = string.Empty; + var parameters = string.Empty; if (args.Length > 1) { for (var i = 1; i < args.Length; i++) { if (args[i].Contains(" ")) @@ -96,11 +91,11 @@ public static void Main(string[] args) { } } //Console.WriteLine($"Executing external with parameters: '{parameters}'..."); - Process.Start(asm.Location, parameters); + Process.Start(Updater.CurrentFileLocation, parameters); return; } - Console.WriteLine($"Executing '{asm.Location}' with parameters: '{string.Join(" ", args)}'"); + Console.WriteLine($"Executing '{Updater.CurrentFileLocation}' with parameters: '{string.Join(" ", args)}'"); for (var j = 0; j < args.Length; j++) { switch (args[j].ToLower().Trim()) { case "-u": diff --git a/Fb2Kindle/Updater.cs b/Fb2Kindle/Updater.cs index abc2ba5..b5eb770 100644 --- a/Fb2Kindle/Updater.cs +++ b/Fb2Kindle/Updater.cs @@ -35,16 +35,27 @@ internal static class Updater { private const string GITHUB_LANDING_PAGE = "sergiye/fb2kindle"; private static readonly string selfFileName; + internal static readonly string AppName; + internal static readonly string AppTitle; internal static readonly string CurrentVersion; internal static readonly string CurrentFileLocation; static Updater() { var asm = Assembly.GetExecutingAssembly(); + AppName = asm.GetName().Name; + AppTitle = GetAttribute(asm)?.Title; CurrentVersion = asm.GetName().Version.ToString(3); CurrentFileLocation = asm.Location; selfFileName = Path.GetFileName(CurrentFileLocation); } + private static T GetAttribute(ICustomAttributeProvider assembly, bool inherit = false) where T : Attribute { + foreach (var o in assembly.GetCustomAttributes(typeof(T), inherit)) + if (o is T attribute) + return attribute; + return null; + } + private static string GetJsonData(string uri, int timeout = 10, string method = "GET") { var request = (HttpWebRequest) WebRequest.Create(uri); request.Method = method; @@ -84,17 +95,15 @@ internal static void CheckForUpdates(bool silent) { } if (string.Compare(CurrentVersion, newVersion, StringComparison.Ordinal) >= 0) { - if (!silent) - Util.WriteLine($"Your version is: {CurrentVersion}\nLatest released version is: {newVersion}\nNo need to update.", ConsoleColor.White); return; } - Util.WriteLine($"Your version is: {CurrentVersion}\nLatest released version is: {newVersion}\nDownloading update...", ConsoleColor.White); + Util.WriteLine($"New version found: {newVersion}, app will be updated after close.", ConsoleColor.White); update = true; } catch (Exception ex) { if (!silent) - Util.WriteLine($"Error checking for a new version.\n{ex.Message}", ConsoleColor.Red); + Util.WriteLine($"Error checking for a new version: {ex.Message}", ConsoleColor.Red); update = false; } @@ -122,12 +131,11 @@ internal static void CheckForUpdates(bool silent) { WorkingDirectory = tempPath }; Process.Start(startInfo); - Util.WriteLine("Updating...", ConsoleColor.White); Environment.Exit(0); } catch (Exception ex) { if (!silent) - Util.WriteLine($"Error downloading new version\n{ex.Message}", ConsoleColor.Red); + Util.WriteLine($"Error downloading new version: {ex.Message}", ConsoleColor.Red); } } } diff --git a/Fb2Kindle/Util.cs b/Fb2Kindle/Util.cs index 4ed6da8..915d87e 100644 --- a/Fb2Kindle/Util.cs +++ b/Fb2Kindle/Util.cs @@ -5,21 +5,12 @@ using System.Linq; using System.Reflection; using System.Text; -using System.Xml; using System.Xml.Linq; namespace Fb2Kindle { internal static class Util { - internal static T GetAttribute(ICustomAttributeProvider assembly, bool inherit = false) where T : Attribute { - var attr = assembly.GetCustomAttributes(typeof(T), inherit); - foreach (var o in attr) - if (o is T) - return o as T; - return null; - } - internal static string GetScriptFromResource(string resourceName) { using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(String.Format("Fb2Kindle.{0}", resourceName))) { if (stream != null) @@ -43,7 +34,7 @@ internal static bool GetFileFromResource(string resourceName, string filename) { } internal static string GetAppPath() { - return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + return Path.GetDirectoryName(Updater.CurrentFileLocation); } internal static void CopyDirectory(string sourceDirName, string destDirName, bool copySubDirs) { @@ -76,13 +67,6 @@ internal static string AttributeValue(IEnumerable source, XName name, } - internal static DateTime GetBuildTime(Version ver) { - var buildTime = new DateTime(2000, 1, 1).AddDays(ver.Build).AddSeconds(ver.Revision * 2); - if (TimeZone.IsDaylightSavingTime(DateTime.Now, TimeZone.CurrentTimeZone.GetDaylightChanges(DateTime.Now.Year))) - buildTime = buildTime.AddHours(1); - return buildTime; - } - internal static XElement[] RenameTags(XElement root, string tagName, string newName, string className = null, bool clearData = false) { var list = root.Descendants(tagName).ToArray(); foreach (var element in list) @@ -111,28 +95,26 @@ internal static int StartProcess(string fileName, string args, bool addToConsole StandardOutputEncoding = Encoding.UTF8 //WindowStyle = ProcessWindowStyle.Hidden }; - // using (var process = Process.Start(startInfo)) - // { - // if (addToConsole) - // { - // while (!process.StandardOutput.EndOfStream) - // WriteLine(process.StandardOutput.ReadLine()); - // } - // process.WaitForExit(); - // return process.ExitCode; - // } - - // using (var process = Process.Start(startInfo)) - // { - // using (var reader = process.StandardOutput) - // { - // string result = reader.ReadToEnd(); - // if (addToConsole) WriteLine(result); - // } - // return process.ExitCode; - // } - - using (var process = new Process { StartInfo = startInfo }) { + + // using (var process = Process.Start(startInfo)) { + // if (addToConsole) { + // while (!process.StandardOutput.EndOfStream) + // WriteLine(process.StandardOutput.ReadLine()); + // } + // process.WaitForExit(); + // return process.ExitCode; + // } + // + // using (var process = Process.Start(startInfo)) { + // using (var reader = process.StandardOutput) { + // string result = reader.ReadToEnd(); + // if (addToConsole) WriteLine(result); + // } + // return process.ExitCode; + // } + + using (var process = new Process()) { + process.StartInfo = startInfo; process.OutputDataReceived += (sender, e) => { if (addToConsole) WriteLine(e.Data); }; diff --git a/readme.md b/readme.md index db0390f..5d31f66 100644 --- a/readme.md +++ b/readme.md @@ -50,7 +50,7 @@ To use: * `-a`: all `.fb2` books in app folder * `-r`: process files in subfolders (work with -a key) * `-j`: join files from each folder to the single book - * `-d`: delete source file after successful convertion + * `-d`: delete source file after successful conversion * `-css` : styles used in destination book @@ -64,16 +64,11 @@ To use: * `-s`: add sequence and number to title * `-ni`: no images * `-dc`: DropCaps mode - * `-g`: grayscaled images + * `-g`: grayscale images * `-jpeg`: save images in jpeg * `-ntoc`: no table of content * `-nch`: no chapters - - * `-preview`: keep generated source files - * `-debug`: keep all generated source files - - * `-u` or `-update`: update application to the latest version. You can combine it with the `-save` option to enable auto-update check on every start ### Examples: