quest-reader/Services/Generator.cs

55 lines
1.8 KiB
C#
Raw Normal View History

2022-02-15 18:38:47 +00:00
namespace QuestReader.Services;
using System.Reflection;
2022-02-19 16:42:47 +00:00
using QuestReader.Models;
2022-02-15 18:38:47 +00:00
public class Generator
{
public StandaloneTemplate<TemplateModel> RazorTemplate { get; set; }
2022-02-15 18:38:47 +00:00
public string QuestName { get; set; }
public PostsSource PostsSource { get; set; }
public string AssetsPath { get; set; }
public string OutputPath { get; set; }
2022-02-15 18:38:47 +00:00
public Generator(string questName)
{
QuestName = questName;
AssetsPath = $"/static/{questName}";
PostsSource = new PostsSource(questName);
2022-02-15 18:38:47 +00:00
var razorEngine = new RazorStandalone<StandaloneTemplate<TemplateModel>>("QuestReader");
2022-02-15 18:38:47 +00:00
var templateFile = "page_template.cshtml";
RazorTemplate = razorEngine.Compile(
"page_template.cshtml"
) ?? throw new Exception("No template");
2022-02-15 18:38:47 +00:00
Console.WriteLine($"Using \"{templateFile}\" with base URL {AssetsPath}");
2022-02-15 18:38:47 +00:00
}
public string Run()
{
2022-02-19 16:42:47 +00:00
RazorTemplate.Model = new TemplateModel
2022-02-15 18:38:47 +00:00
{
Metadata = PostsSource.Metadata,
Posts = PostsSource.Accepted.ToList(),
AllPosts = PostsSource.Posts,
Now = @DateTime.UtcNow,
AssetsPath = AssetsPath.TrimEnd('/'), // Strip trailing slash
ToolVersion = Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "unknown"
};
var outputStream = new MemoryStream();
RazorTemplate.ExecuteAsync(outputStream).Wait();
2022-02-15 18:38:47 +00:00
var outputPath = Path.Join(OutputPath ?? PostsSource.BasePath, "output.html");
Console.WriteLine($"Template output {outputStream.Length} bytes");
File.WriteAllBytes(outputPath, outputStream.ToArray());
2022-02-15 18:38:47 +00:00
Console.WriteLine($"Wrote output to {outputPath}");
return outputPath;
}
}