oliverbooth.dev/OliverBooth/Services/TemplateService.cs

78 lines
2.5 KiB
C#
Raw Normal View History

2023-08-11 21:33:14 +01:00
using System.Buffers.Binary;
2023-08-11 15:51:20 +01:00
using Microsoft.EntityFrameworkCore;
2023-08-13 18:02:19 +01:00
using OliverBooth.Data;
using OliverBooth.Data.Web;
using OliverBooth.Formatting;
using OliverBooth.Markdown.Template;
using SmartFormat;
using SmartFormat.Extensions;
namespace OliverBooth.Services;
/// <summary>
/// Represents a service that renders MediaWiki-style templates.
/// </summary>
internal sealed class TemplateService : ITemplateService
{
2023-08-11 21:33:14 +01:00
private static readonly Random Random = new();
2023-08-13 18:02:19 +01:00
private readonly IDbContextFactory<WebContext> _webContextFactory;
private readonly SmartFormatter _formatter;
/// <summary>
/// Initializes a new instance of the <see cref="TemplateService" /> class.
/// </summary>
2023-08-11 21:33:14 +01:00
/// <param name="serviceProvider">The <see cref="IServiceProvider" />.</param>
2023-08-13 18:02:19 +01:00
/// <param name="webContextFactory">The <see cref="WebContext" /> factory.</param>
public TemplateService(IServiceProvider serviceProvider,
IDbContextFactory<WebContext> webContextFactory)
{
_formatter = Smart.CreateDefaultSmartFormat();
_formatter.AddExtensions(new DefaultSource());
_formatter.AddExtensions(new ReflectionSource());
_formatter.AddExtensions(new DateFormatter());
_formatter.AddExtensions(new MarkdownFormatter(serviceProvider));
2023-08-11 21:33:14 +01:00
_webContextFactory = webContextFactory;
}
/// <inheritdoc />
2023-08-13 18:02:19 +01:00
public string RenderGlobalTemplate(TemplateInline templateInline)
{
if (templateInline is null) throw new ArgumentNullException(nameof(templateInline));
2023-08-11 21:33:14 +01:00
2023-08-13 18:02:19 +01:00
using WebContext context = _webContextFactory.CreateDbContext();
Template? template = context.Templates.Find(templateInline.Name);
return RenderTemplate(templateInline, template);
}
/// <inheritdoc />
public string RenderTemplate(TemplateInline inline, ITemplate? template)
{
if (template is null)
{
2023-08-13 18:02:19 +01:00
return $"{{{{{inline.Name}}}}}";
}
2023-08-11 21:33:14 +01:00
Span<byte> randomBytes = stackalloc byte[20];
Random.NextBytes(randomBytes);
var formatted = new
{
2023-08-13 18:02:19 +01:00
inline.ArgumentList,
inline.ArgumentString,
inline.Params,
2023-08-11 21:33:14 +01:00
RandomInt = BinaryPrimitives.ReadInt32LittleEndian(randomBytes[..4]),
RandomGuid = new Guid(randomBytes[4..]).ToString("N"),
};
try
{
return _formatter.Format(template.FormatString, formatted);
}
catch
{
2023-08-13 18:02:19 +01:00
return $"{{{{{inline.Name}|{inline.ArgumentString}}}}}";
}
}
}