Skip to content

Commit

Permalink
updater fix; toc depth; small fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiye committed Sep 29, 2023
1 parent 0616bf0 commit a0932d7
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 52 deletions.
5 changes: 1 addition & 4 deletions Fb2Kindle/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("fb2 to kindle book converter by Sergiy Yegoshyn")]
[assembly: AssemblyTitle("Fb2Kindle book converter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sergiy Yegoshyn ([email protected])")]
Expand Down
66 changes: 36 additions & 30 deletions Fb2Kindle/Convertor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,9 @@ internal bool ConvertBookSequence(string[] books) {
//create temp working folder
if (string.IsNullOrWhiteSpace(tempDir))
tempDir = $"{Path.GetTempPath()}\\{Guid.NewGuid()}";
if (!Directory.Exists(tempDir))
Directory.CreateDirectory(tempDir);

tempDir = GetVersionedPath(tempDir);
Directory.CreateDirectory(tempDir);

if (defaultCss.Contains("src: url(\"fonts/") && Directory.Exists(workingFolder + @"\fonts")) {
Directory.CreateDirectory(tempDir + @"\fonts");
Expand Down Expand Up @@ -189,7 +190,7 @@ private static void CreateNcxFile(XElement toc, string bookName, string folder,
var ncx = new XElement("ncx");
var head = new XElement("head", "");
head.Add(new XElement("meta", new XAttribute("name", "dtb:uid"), new XAttribute("content", "BookId")));
head.Add(new XElement("meta", new XAttribute("name", "dtb:depth"), new XAttribute("content", "1")));
head.Add(new XElement("meta", new XAttribute("name", "dtb:depth"), new XAttribute("content", "3")));
head.Add(new XElement("meta", new XAttribute("name", "dtb:totalPageCount"), new XAttribute("content", "0")));
head.Add(new XElement("meta", new XAttribute("name", "dtb:maxPageNumber"), new XAttribute("content", "0")));
ncx.Add(head);
Expand All @@ -199,31 +200,29 @@ private static void CreateNcxFile(XElement toc, string bookName, string folder,
AddNcxItem(navMap, 0, "Описание", "book.html#it");
var playOrder = 2;
var listEls = toc.Elements("body").Elements(TocElement);
AddTocListItems(listEls, navMap, ref playOrder, true);
AddTocListItems(listEls, navMap, ref playOrder, 1);
if (!addToc)
AddNcxItem(navMap, 1, "Содержание", "toc.html#toc");
ncx.Add(navMap);
SaveXmlToFile(ncx, folder + "\\" + NcxName);
ncx.RemoveAll();
}

private static void AddTocListItems(IEnumerable<XElement> listEls, XElement navMap, ref int playOrder, bool rootLevel = false) {
private static void AddTocListItems(IEnumerable<XElement> listEls, XElement navMap, ref int playOrder, int depth) {
foreach (var list in listEls) {
AddTocListItems(list.Elements(TocElement), navMap, ref playOrder);
AddTocListItems(list.Elements(TocElement), navMap, ref playOrder, depth + 1);
foreach (var li in list.Elements("li")) {
var navPoint = navMap;
var a = li.Elements("a").FirstOrDefault();
if (a != null) {
// if (rootLevel)
// {
// navPoint = AddNcxItem(navMap, playOrder++, a.Value, (string) a.Attribute("href"));
// }
// else
{
if (depth == 3) {
navPoint = AddNcxItem(navMap, playOrder++, a.Value, (string) a.Attribute("href"));
}
else {
AddNcxItem(navMap, playOrder++, a.Value, (string)a.Attribute("href"));
}
}
AddTocListItems(li.Elements(TocElement), navPoint, ref playOrder);
AddTocListItems(li.Elements(TocElement), navPoint, ref playOrder, depth + 1);
}
}
}
Expand Down Expand Up @@ -410,8 +409,8 @@ private bool CreateEpub(string tempDir, string bookName, string bookPath,
Directory.CreateDirectory($"{tempDir}/META-INF");
File.WriteAllText($"{tempDir}/META-INF/container.xml", @"<?xml version=""1.0"" encoding=""UTF-8""?><container xmlns=""urn:oasis:names:tc:opendocument:xmlns:container"" version=""1.0""><rootfiles><rootfile full-path=""OPS/content.opf"" media-type=""application/oebps-package+xml""/></rootfiles></container>");
File.WriteAllText($"{tempDir}/mimetype", "application/epub+zip");
var tmpBookPath = $"{tempDir}\\{bookName}.epub";

var tmpBookPath = GetVersionedPath(tempDir, bookName, ".epub");
using (var zip = new ZipFile(tmpBookPath)) {
zip.AddDirectory(tempDir);
zip.Save();
Expand Down Expand Up @@ -443,6 +442,22 @@ private bool CreateMobi(string workFolder, string tempDir, string bookName, stri
return SendAndClean(bookName, bookPath, tempDir, tmpBookPath, showOutput, ".mobi");
}

private static string GetVersionedPath(string filePath, string fileName = null, string fileExtension = null) {
var versionNumber = 1;
if (string.IsNullOrWhiteSpace(fileName)) {
var result = filePath;
while (Directory.Exists(result))
result = $"{filePath}(v{versionNumber++})";
return result;
}
else {
var result = $"{filePath}\\{fileName}{fileExtension}";
while (File.Exists(result))
result = $"{filePath}\\{fileName}(v{versionNumber++}){fileExtension}";
return result;
}
}

private bool SendAndClean(string bookName, string bookPath, string tempDir, string tmpBookPath, bool showOutput, string extension) {

bool saveLocal = true;
Expand All @@ -453,27 +468,18 @@ private bool SendAndClean(string bookName, string bookPath, string tempDir, stri

if (saveLocal) {
//save to output folder
var versionNumber = 1;
var resultPath = Path.GetDirectoryName(bookPath);
var resultName = bookName;
while (File.Exists($"{resultPath}\\{resultName}{extension}")) {
resultName = bookName + "(v" + versionNumber + ")";
versionNumber++;
}

File.Move(tmpBookPath, $"{resultPath}\\{resultName}{extension}");
var resultName = GetVersionedPath(Path.GetDirectoryName(bookPath), bookName, extension);
File.Move(tmpBookPath, resultName);

if (currentSettings.CleanupMode == ConverterCleanupMode.Partial) {
if (!string.IsNullOrWhiteSpace(tempDir)) {
foreach (var f in Directory.EnumerateFiles(tempDir, "*.opf"))
File.Delete(f);
//File.Delete(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(inputFile) + ".opf"));
File.Delete(Path.Combine(tempDir, "kindlegen.exe"));
File.Delete(Path.Combine(tempDir, "toc.ncx"));

var destFolder = $"{resultPath}\\{resultName}";
if (!tempDir.Equals(destFolder, StringComparison.OrdinalIgnoreCase))
Directory.Move(tempDir, destFolder);
//for Partial mode UseSourceAsTempFolder is always true
// var destFolder = GetVersionedPath(Path.GetDirectoryName(bookPath) +"\\" + bookName);
// if (!tempDir.Equals(destFolder, StringComparison.OrdinalIgnoreCase))
// Directory.Move(tempDir, destFolder);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions Fb2Kindle/DefaultOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
namespace Fb2Kindle {
public enum ConverterCleanupMode {
Full = 0,
Partial, //keep html files, styles & images
No //for debug
Partial = 1, //keep html files, styles & images
No = 2 //for debug
}

[Serializable]
Expand Down
14 changes: 7 additions & 7 deletions Fb2Kindle/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,19 +219,19 @@ public static void Main(string[] args) {
Util.WriteLine();
Util.WriteLine($"Time wasted: {timeWasted:G}", ConsoleColor.White);

if (currentSettings is {CheckUpdates: true}) {
Util.WriteLine();
Util.WriteLine($"Checking for updates...", ConsoleColor.White);
Updater.CheckForUpdates(false);
Util.WriteLine();
}

if (wait) {
Util.WriteLine();
Util.WriteLine("Press any key to continue...", ConsoleColor.White);
Console.ReadKey();
}
}

if (currentSettings.CheckUpdates) {
Util.WriteLine();
Util.WriteLine("Checking for updates...", ConsoleColor.White);
Updater.CheckForUpdates(false);
Util.WriteLine();
}
}

private static void ProcessFolder(Convertor conv, string workPath, string searchMask, bool recursive, bool join) {
Expand Down
27 changes: 18 additions & 9 deletions Fb2Kindle/Updater.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
Expand Down Expand Up @@ -63,7 +64,6 @@ private static string GetJsonData(string uri, int timeout = 10, string method =
}

internal static void CheckForUpdates(bool silent) {
string newVersion;
string newVersionUrl = null;
bool update;
try {
Expand All @@ -72,29 +72,37 @@ internal static void CheckForUpdates(bool silent) {
if (releases == null || releases.Length == 0)
throw new Exception("Error getting list of releases.");

newVersion = releases[0].tag_name;
newVersionUrl = releases[0].assets[0].browser_download_url;
var newVersion = releases[0].tag_name;
newVersionUrl = releases[0].assets
.FirstOrDefault(a => selfFileName.Equals(a.name, StringComparison.OrdinalIgnoreCase))
?.browser_download_url;

if (newVersionUrl == null) {
if (!silent)
Util.WriteLine("Error getting released asset information.", ConsoleColor.White);
return;
}

if (string.Compare(CurrentVersion, newVersion, StringComparison.Ordinal) >= 0) {
if (!silent)
Util.Write($"Your version is: {CurrentVersion}\nLatest released version is: {newVersion}\nNo need to update.", ConsoleColor.White);
Util.WriteLine($"Your version is: {CurrentVersion}\nLatest released version is: {newVersion}\nNo need to update.", ConsoleColor.White);
return;
}

Util.Write($"Your version is: {CurrentVersion}\nLatest released version is: {newVersion}\nDownloading update...", ConsoleColor.White);
Util.WriteLine($"Your version is: {CurrentVersion}\nLatest released version is: {newVersion}\nDownloading update...", ConsoleColor.White);
update = true;
}
catch (Exception ex) {
if (!silent)
Util.Write($"Error checking for a new version.\n{ex.Message}", ConsoleColor.Red);
Util.WriteLine($"Error checking for a new version.\n{ex.Message}", ConsoleColor.Red);
update = false;
}

if (!update) return;

try {
var tempPath = Path.GetTempPath();
var updateFilePath = $"{tempPath}{selfFileName}";
var updateFilePath = $"{tempPath}{selfFileName}{Environment.TickCount}";

using (var wc = new WebClient())
wc.DownloadFile(newVersionUrl, updateFilePath);
Expand All @@ -105,7 +113,7 @@ internal static void CheckForUpdates(bool silent) {
batFile.WriteLine("TIMEOUT /t 3 /nobreak > NUL");
batFile.WriteLine("TASKKILL /IM \"{0}\" > NUL", selfFileName);
batFile.WriteLine("MOVE \"{0}\" \"{1}\"", updateFilePath, CurrentFileLocation);
batFile.WriteLine("DEL \"%~f0\" & START \"\" /B \"{0}\"", CurrentFileLocation);
batFile.WriteLine("DEL \"%~f0\"");
}

var startInfo = new ProcessStartInfo(cmdFilePath) {
Expand All @@ -114,11 +122,12 @@ 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.Write($"Error downloading new version\n{ex.Message}", ConsoleColor.Red);
Util.WriteLine($"Error downloading new version\n{ex.Message}", ConsoleColor.Red);
}
}
}
Expand Down

0 comments on commit a0932d7

Please sign in to comment.