Skip to content

Commit

Permalink
Merge pull request #3 from pdwetz/dev
Browse files Browse the repository at this point in the history
Version 2.0
  • Loading branch information
pdwetz committed Oct 14, 2018
2 parents 25fa528 + d0f4142 commit c75f33c
Show file tree
Hide file tree
Showing 20 changed files with 351 additions and 163 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ TestResults
*.suo
*.user
*.sln.docstates
.vs/

# Build results
[Dd]ebug/
Expand Down
90 changes: 21 additions & 69 deletions KindleBookHelper.Core/Book.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*
KindleBookHelper - Converts raw text file to html format that can be consumed by KindleGen.
Copyright (C) 2016 Peter Wetzel
Copyright (C) 2018 Peter Wetzel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
Expand All @@ -15,18 +15,16 @@
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Newtonsoft.Json;
using Nustache.Core;

namespace KindleBookHelper.Core
{
public class Book
{
public const string EndPlaceholder = "[END]";
public const string DefaultEndPlaceholder = "[END]";

public string RawFilePath { get; set; }
public string Title { get; set; }
Expand Down Expand Up @@ -55,79 +53,33 @@ public class Book
[JsonIgnore]
public int Copyright { get { return DateTime.Now.Year; } }

private readonly Assembly _assembly;

public Book()
{
_assembly = Assembly.GetExecutingAssembly();
}
[JsonIgnore]
public string EndPlaceholder { get; set; }

public static Book Initialize(string sJsonFilePath)
{
var book = JsonConvert.DeserializeObject<Book>(File.ReadAllText(sJsonFilePath));
if (book.Id == Guid.Empty)
{
book.Id = Guid.NewGuid();
File.WriteAllText(sJsonFilePath, JsonConvert.SerializeObject(book, Formatting.Indented));
}
return book;
}

public void Process()
public void Parse()
{
if (string.IsNullOrWhiteSpace(RawFilePath))
{
throw new ArgumentException("RawFilePath parameter must be set");
}

OriginalText = FileUtilities.LoadTextFile(RawFilePath);

Parse();

if (Poems.Count == 0)
Poems = new List<Poem>();
if (string.IsNullOrWhiteSpace(OriginalText))
{
throw new ApplicationException("No poems found in source");
Log.Error("OriginalText is required");
return;
}

var sTargetDirectoryPath = Path.GetDirectoryName(RawFilePath);
RenderTemplate(sTargetDirectoryPath, "html");
RenderTemplate(sTargetDirectoryPath, "ncx");
RenderTemplate(sTargetDirectoryPath, "opf");

var sCssFilePath = Path.Combine(sTargetDirectoryPath, "poetry.css");
if (!File.Exists(sCssFilePath))
if (string.IsNullOrWhiteSpace(EndPlaceholder))
{
var sCss = FileUtilities.LoadTextResource(_assembly, "KindleBookHelper.Core.templates.poetry.css");
FileUtilities.WriteTextFile(sCssFilePath, sCss);
Log.Error("EndPlaceholder is required");
return;
}
}

private void RenderTemplate(string sTargetDirectoryPath, string sTemplate)
{
var targetFilePath = Path.Combine(sTargetDirectoryPath, $"{TitleFileSafe}.{sTemplate}");
using (var reader = new StreamReader(_assembly.GetManifestResourceStream($"KindleBookHelper.Core.templates.{sTemplate}.template")))
{
using (var writer = File.CreateText(targetFilePath))
{
Render.Template(reader, this, writer);
}
}
}

public void Parse()
{
Poems = new List<Poem>();
int iPos = 0;
while (iPos >= 0 && iPos < OriginalText.Length)
int i = 0;
while (i >= 0 && i < OriginalText.Length)
{
int iEndPos = OriginalText.IndexOf(EndPlaceholder, iPos);
if (iEndPos < 0)
int end = OriginalText.IndexOf(EndPlaceholder, i);
if (end < 0)
{
break;
}
string sRawPoem = OriginalText.Substring(iPos, iEndPos - iPos);
Poems.Add(new Poem(sRawPoem));
iPos = iEndPos + EndPlaceholder.Length;
var poem = OriginalText.Substring(i, end - i);
Poems.Add(new Poem(poem));
i = end + EndPlaceholder.Length;
}
}
}
Expand Down
96 changes: 96 additions & 0 deletions KindleBookHelper.Core/BookProcessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
KindleBookHelper - Converts raw text file to html format that can be consumed by KindleGen.
Copyright (C) 2018 Peter Wetzel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Nustache.Core;
using Serilog;

namespace KindleBookHelper.Core
{
public class BookProcessor
{
private readonly string _jsonFilePath;
private readonly string _endPlaceholder;
private readonly Assembly _assembly;

public BookProcessor(string jsonFilePath, string endPlaceholder = Book.DefaultEndPlaceholder)
{
if (string.IsNullOrWhiteSpace(jsonFilePath))
{
throw new ArgumentException($"{nameof(jsonFilePath)} parameter must be set");
}
_jsonFilePath = jsonFilePath;
_endPlaceholder = endPlaceholder;
_assembly = Assembly.GetExecutingAssembly();
}

public Book Process()
{
Log.Information("Processing book file {jsonFilePath}", _jsonFilePath);
var book = JsonConvert.DeserializeObject<Book>(File.ReadAllText(_jsonFilePath));
if (book.Id == Guid.Empty)
{
book.Id = Guid.NewGuid();
Log.Information("Saving new unique Id");
File.WriteAllText(_jsonFilePath, JsonConvert.SerializeObject(book, Formatting.Indented));
}
if (string.IsNullOrWhiteSpace(book.RawFilePath))
{
Log.Error("RawFilePath is required");
return null;
}
book.EndPlaceholder = _endPlaceholder;
book.OriginalText = FileUtilities.LoadTextFile(book.RawFilePath);
book.Parse();
if (!book.Poems.Any())
{
Log.Error("No poems found in source");
return null;
}
Log.Information("Found {Count} poems", book.Poems.Count);
var targetDirectoryPath = Path.GetDirectoryName(book.RawFilePath);
RenderTemplate(targetDirectoryPath, "html", book);
RenderTemplate(targetDirectoryPath, "ncx", book);
RenderTemplate(targetDirectoryPath, "opf", book);
var cssFilePath = Path.Combine(targetDirectoryPath, "poetry.css");
if (!File.Exists(cssFilePath))
{
var css = FileUtilities.LoadTextResource(_assembly, "KindleBookHelper.Core.templates.poetry.css");
FileUtilities.WriteTextFile(cssFilePath, css);
}
Log.Information("Finished processing book {Title}", book.Title);
return book;
}

private void RenderTemplate(string targetDirectoryPath, string template, Book book)
{
var targetFilePath = Path.Combine(targetDirectoryPath, $"{book.TitleFileSafe}.{template}");
Log.Debug("Rendering template {template}", template);
using (var reader = new StreamReader(_assembly.GetManifestResourceStream($"KindleBookHelper.Core.templates.{template}.template")))
{
using (var writer = File.CreateText(targetFilePath))
{
Render.Template(reader, book, writer);
}
}
}
}
}
42 changes: 20 additions & 22 deletions KindleBookHelper.Core/FileUtilities.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*
KindleBookHelper - Converts raw text file to html format that can be consumed by KindleGen.
Copyright (C) 2016 Peter Wetzel
Copyright (C) 2018 Peter Wetzel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
Expand All @@ -20,49 +20,47 @@

namespace KindleBookHelper.Core
{
public class FileUtilities
public static class FileUtilities
{
private FileUtilities() {}

public static string LoadTextFile(string sFilePath)
public static string LoadTextFile(string filePath)
{
string sReturn = "";
using (StreamReader sr = File.OpenText(sFilePath))
var data = "";
using (StreamReader sr = File.OpenText(filePath))
{
sReturn = sr.ReadToEnd();
data = sr.ReadToEnd();
sr.DiscardBufferedData();
sr.Close();
}
return sReturn;
return data;
}

public static string LoadTextResource(Assembly assembly, string sResourceName)
public static string LoadTextResource(Assembly assembly, string resourceName)
{
string sReturn = "";
using (var sr = new StreamReader(assembly.GetManifestResourceStream(sResourceName)))
var data = "";
using (var sr = new StreamReader(assembly.GetManifestResourceStream(resourceName)))
{
sReturn = sr.ReadToEnd();
data = sr.ReadToEnd();
sr.DiscardBufferedData();
sr.Close();
}
return sReturn;
return data;
}

public static void CreateDirectoryIfMissing(string sDirectoryPath)
public static void CreateDirectoryIfMissing(string directoryPath)
{
if (!Directory.Exists(sDirectoryPath))
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(sDirectoryPath);
Directory.CreateDirectory(directoryPath);
}
}

public static void WriteTextFile(string sFilePath, string sData)
public static void WriteTextFile(string filePath, string data)
{
string sDir = Path.GetDirectoryName(sFilePath);
CreateDirectoryIfMissing(sDir);
using (StreamWriter sw = File.CreateText(sFilePath))
var dirName = Path.GetDirectoryName(filePath);
CreateDirectoryIfMissing(dirName);
using (StreamWriter sw = File.CreateText(filePath))
{
sw.Write(sData);
sw.Write(data);
sw.Flush();
sw.Close();
}
Expand Down
14 changes: 9 additions & 5 deletions KindleBookHelper.Core/KindleBookHelper.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>KindleBookHelper.Core</RootNamespace>
<AssemblyName>KindleBookHelper.Core</AssemblyName>
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
Expand All @@ -31,11 +31,14 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="Nustache.Core, Version=1.16.0.4, Culture=neutral, PublicKeyToken=efd6f3d8f76ecd9f, processorArchitecture=MSIL">
<HintPath>..\packages\Nustache.1.16.0.4\lib\net20\Nustache.Core.dll</HintPath>
<Reference Include="Nustache.Core, Version=1.16.0.8, Culture=neutral, PublicKeyToken=efd6f3d8f76ecd9f, processorArchitecture=MSIL">
<HintPath>..\packages\Nustache.1.16.0.8\lib\net20\Nustache.Core.dll</HintPath>
</Reference>
<Reference Include="Serilog, Version=2.0.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10, processorArchitecture=MSIL">
<HintPath>..\packages\Serilog.2.7.1\lib\net46\Serilog.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
Expand All @@ -47,6 +50,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Book.cs" />
<Compile Include="BookProcessor.cs" />
<Compile Include="FileUtilities.cs" />
<Compile Include="Poem.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
Expand Down
6 changes: 3 additions & 3 deletions KindleBookHelper.Core/Poem.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*
KindleBookHelper - Converts raw text file to html format that can be consumed by KindleGen.
Copyright (C) 2016 Peter Wetzel
Copyright (C) 2018 Peter Wetzel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
Expand All @@ -27,10 +27,10 @@ public class Poem
public string TitleUrlSafe { get { return Title.URLFriendly(); } }
public List<Stanza> Stanzas { get; set; }

public Poem(string sRaw)
public Poem(string text)
{
Stanzas = new List<Stanza>();
List<string> lines = sRaw.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).ToList();
List<string> lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).ToList();

// While could do this, still need to account for its location; so, just handling it in full loop
//Title = lines.First(x => !string.IsNullOrWhiteSpace(x));
Expand Down
6 changes: 3 additions & 3 deletions KindleBookHelper.Core/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("KindleBookHelper")]
[assembly: AssemblyCopyright("Copyright © 2016 Peter Wetzel")]
[assembly: AssemblyCopyright("Copyright © 2018 Peter Wetzel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]
[assembly: Guid("3b63a76a-c55e-4cae-84c4-d07a2cbc1afe")]

[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
Loading

0 comments on commit c75f33c

Please sign in to comment.