aboutsummaryrefslogtreecommitdiff
path: root/lib/Emails.Transactional.Plugin/src/Templates/EmailTemplateStore.cs
blob: d589262061022b7333176df394b0560840c8a8c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: Emails.Transactional
* File: EmailTemplateStore.cs 
*
* EmailTemplateStore.cs is part of Emails.Transactional which is part of the larger 
* VNLib collection of libraries and utilities.
*
* Emails.Transactional 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 2 of the License,
* or (at your option) any later version.
*
* Emails.Transactional 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 Emails.Transactional. If not, see http://www.gnu.org/licenses/.
*/


using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

using Fluid;

using VNLib.Utils.IO;
using VNLib.Utils.Extensions;
using VNLib.Utils.Memory.Caching;
using VNLib.Plugins;
using VNLib.Plugins.Extensions.Loading;
using VNLib.Plugins.Extensions.Data.Storage;

using Emails.Transactional.Mta;

namespace Emails.Transactional.Templates
{
    [ConfigurationName("templates")]
    internal sealed class EmailTemplateStore : ITemplateStorage
    {
        private readonly FluidParser _parser;
        private readonly Dictionary<string, EmailTemplate> _templateCache;
        private readonly ISimpleFilesystem _filesystem;
        private readonly TimeSpan _cacheValidFor;

        public EmailTemplateStore(PluginBase plugin, IConfigScope config)
        {
            _parser = new();
            _templateCache = new(StringComparer.OrdinalIgnoreCase);

            _cacheValidFor = config["cache_valid_for_sec"].GetTimeSpan(TimeParseType.Seconds);
            string fsPath = config.GetRequiredProperty("template_path", e => e.GetString()!);

            //Get the filesystem
            ISimpleFilesystem baseFs = plugin.GetOrCreateSingleton<MinioStorage>();

            //Create a new scope for the base path
            _filesystem = baseFs.CreateNewScope(fsPath);
        }

        public Task<IEmailTemplate> GetTemplateAsync(string templateId, CancellationToken cancellation)
        {
            //try to get the template from the cache
            if (_templateCache.TryGetOrEvictRecord(templateId, out EmailTemplate? template) > 0)
            {
                return Task.FromResult<IEmailTemplate>(template!);
            }

            //Load the template from the store
            return GetTemplateFromStoreAsync(templateId, cancellation);
        }

        private async Task<IEmailTemplate> GetTemplateFromStoreAsync(string templateId, CancellationToken cancellation)
        {
            //memory stream for template data
            using VnMemoryStream templateData = new();

            //remove leading slash
            if (templateId.StartsWith('/'))
            {
                templateId = templateId[1..];
            }

            //Recover template data
            long read = await _filesystem.ReadFileAsync(templateId, templateData, cancellation);

            if(read <= 0)
            {
                throw new TemplateLookupFailedException($"Template {templateId} not found");
            }

            //Rewind the stream
            templateData.Seek(0, SeekOrigin.Begin);

            //To string
            string templateString = Encoding.UTF8.GetString(templateData.AsSpan());

            //Try to parse the template and raise exception if it fails
            if (!_parser.TryParse(templateString, out IFluidTemplate template, out string error))
            {
                throw new TemplateLookupFailedException($"A template parse error occured: {error}");
            }

            //Create new email template
            EmailTemplate et = new(template);

            //Store template in cache
            _templateCache.StoreRecord(templateId, et, _cacheValidFor);

            return et;
        }

        private sealed record class EmailTemplate(IFluidTemplate Template) : IEmailTemplate, ICacheable
        {
            ///<inheritdoc/>
            public DateTime Expires { get; set; }

            ///<inheritdoc/>
            public bool Equals(ICacheable? other) => ReferenceEquals(this, other);

            ///<inheritdoc/>
            public void Evicted()
            { }

            ///<inheritdoc/>
            public IEmailMessageData RenderTemplate(object variables)
            {
                //Create a template model
                TemplateContext ctx = new(variables);
                string html = Template.Render(ctx);
                return new EmailMessageData(html);
            }

            private sealed record class EmailMessageData(string Rendered) : IEmailMessageData
            {
                public string GetHtml() => Rendered;
            }
        }
    }
}