Smakolykytl2Epub/Utils/Json2HTML.cs

94 lines
2.6 KiB
C#
Raw Permalink Normal View History

2024-08-02 06:03:41 -04:00
using EpubSharp;
using EpubSharp.Format;
2023-08-13 06:59:16 -04:00
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Smakolykytl2Epub.Utils;
public class Content
{
public string type { get; set; }
public List<Mark> marks { get; set; }
public string text { get; set; }
}
2024-08-02 06:03:41 -04:00
public class Attrs
{
public string src { get; set; }
public string alt { get; set; }
public string title { get; set; }
}
2023-08-13 06:59:16 -04:00
public class Mark
{
public string type { get; set; }
}
public class TextJson
{
public string type { get; set; }
2024-08-01 17:27:02 -04:00
public List<Content?> content { get; set; }
2024-08-02 06:03:41 -04:00
public Attrs attrs { get; set; }
2023-08-13 06:59:16 -04:00
}
public class HtmlConverter
{
2024-08-02 06:03:41 -04:00
public static string ConvertJsonToHtml(string json, EpubWriter writer)
2023-08-13 06:59:16 -04:00
{
2024-08-02 06:03:41 -04:00
var client = new HttpClient();
2023-08-13 07:44:06 -04:00
var token = JToken.Parse(json);
2024-08-02 06:03:41 -04:00
return ConvertTokenToHtml(token, client, writer);
2023-08-13 06:59:16 -04:00
}
2024-08-02 06:03:41 -04:00
private static string ConvertTokenToHtml(JToken token, HttpClient client, EpubWriter writer)
2023-08-13 06:59:16 -04:00
{
2023-08-13 07:44:06 -04:00
var html = "";
2023-08-13 06:59:16 -04:00
if (token is JArray)
{
2024-08-02 06:03:41 -04:00
foreach (var childToken in token.Children()) html += ConvertTokenToHtml(childToken, client, writer);
2023-08-13 06:59:16 -04:00
}
else if (token is JObject)
{
2024-08-02 06:03:41 -04:00
2023-08-13 07:44:06 -04:00
var text = JsonConvert.DeserializeObject<TextJson>(token.ToString());
2024-08-02 06:03:41 -04:00
var count = (text?.content?.Count != 0) ? text?.content?.Count : 1;
for (int i = 0; i < count; i++)
2023-08-13 06:59:16 -04:00
{
2024-08-02 06:03:41 -04:00
2024-08-01 17:27:02 -04:00
Content str = text.content[i];
if (str != null)
{
html += str.text;
}
if (str.type == "hardBreak")
{
html += "<br>";
}
if (str.type == "paragraph")
{
html += "<p>";
}
2024-08-02 06:03:41 -04:00
2023-08-13 06:59:16 -04:00
}
2024-08-02 06:03:41 -04:00
if (text.type == "image")
{
//var webRequest = new HttpRequestMessage(HttpMethod.Get, text.attrs.src);
//var response = client.Send(webRequest);
//var type = text.attrs.src.EndsWith(".jpg") ? EpubContentType.ImageJpeg :
//text.attrs.src.EndsWith(".png") ? EpubContentType.ImagePng : throw new Exception($"Unknown image ext {text.attrs.src}");
//using var reader = new StreamReader(response.Content.ReadAsStream());
//writer.AddFile(text.attrs.src, reader.ReadToEnd(), type);
//html += text.attrs.src;
}
2023-08-13 06:59:16 -04:00
html += "<br>";
}
else
{
html += token.ToString();
}
return html;
}
}