|
| 1 | +using Dove.Blog.Abstractions; |
| 2 | +using Markdig.Extensions.Yaml; |
| 3 | +using Markdig; |
| 4 | +using YamlDotNet.Serialization.NamingConventions; |
| 5 | +using YamlDotNet.Serialization; |
| 6 | +using Dove.Blog.Data; |
| 7 | +using Microsoft.Extensions.Caching.Memory; |
| 8 | +using Markdig.Syntax; |
| 9 | +using Microsoft.Extensions.Logging; |
| 10 | +using System.Text; |
| 11 | +using System.Text.RegularExpressions; |
| 12 | + |
| 13 | +namespace Dove.Blog.Logic; |
| 14 | + |
| 15 | +public interface IBlogProvider |
| 16 | +{ |
| 17 | + Task<IEnumerable<(string category, int posts)>> GetCategories(); |
| 18 | + Task<Post> GetPost(string? postTitle); |
| 19 | + Task<IEnumerable<string>> GetTags(); |
| 20 | +} |
| 21 | + |
| 22 | +public class BlogProvider(IDataProvider dataProvider, IMemoryCache memoryCache, ILogger<BlogProvider> logger) : IBlogProvider |
| 23 | +{ |
| 24 | + protected readonly IDataProvider _provider = dataProvider ?? throw new ArgumentNullException(nameof(dataProvider)); |
| 25 | + protected readonly IMemoryCache _cache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache)); |
| 26 | + private readonly ILogger<BlogProvider> _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| 27 | + |
| 28 | + private static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled); |
| 29 | + |
| 30 | + public async Task<IEnumerable<string>> GetTags() |
| 31 | + { |
| 32 | + try |
| 33 | + { |
| 34 | + var files = await _provider.GetFileList("Posts"); |
| 35 | + var posts = files.Select(x => GetPost(x).Result) |
| 36 | + .ToList(); |
| 37 | + |
| 38 | + var tags = posts.Where(p => p.Tags != null) |
| 39 | + .SelectMany(p => p.Tags!) |
| 40 | + .Distinct() |
| 41 | + .ToArray(); |
| 42 | + return tags; |
| 43 | + |
| 44 | + } |
| 45 | + catch (Exception ex) |
| 46 | + { |
| 47 | + _logger.LogError(ex, "Error loading tags"); |
| 48 | + throw; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public async Task<IEnumerable<(string category, int posts)>> GetCategories() |
| 53 | + { |
| 54 | + try |
| 55 | + { |
| 56 | + var result = new Dictionary<string, int>(); |
| 57 | + |
| 58 | + var files = await _provider.GetFileList("Posts"); |
| 59 | + foreach (var fileName in files) |
| 60 | + { |
| 61 | + var post = await GetPost(fileName); |
| 62 | + if (post.Categories != null) |
| 63 | + { |
| 64 | + foreach (var category in post.Categories) |
| 65 | + { |
| 66 | + if (result.ContainsKey(category)) |
| 67 | + { |
| 68 | + result[category]++; |
| 69 | + } |
| 70 | + else |
| 71 | + { |
| 72 | + result.Add(category, 1); |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return result.Select(x => (x.Key, x.Value)); |
| 79 | + } |
| 80 | + catch (Exception ex) |
| 81 | + { |
| 82 | + _logger.LogError(ex, "Error loading categories"); |
| 83 | + throw; |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + public async Task<IEnumerable<PostSummary>> GetPosts(string? category = null, params string[] tags) |
| 88 | + { |
| 89 | + try |
| 90 | + { |
| 91 | + var files = await _provider.GetFileList("Posts"); |
| 92 | + var posts = files.Select(x => GetPost(x).Result) |
| 93 | + .ToList(); |
| 94 | + |
| 95 | + if (!string.IsNullOrEmpty(category)) |
| 96 | + { |
| 97 | + posts = posts.Where(p => p.Categories != null && p.Categories.Contains(category)) |
| 98 | + .ToList(); |
| 99 | + } |
| 100 | + if (tags.Length > 0) |
| 101 | + { |
| 102 | + posts = posts.Where(p => p.Tags != null && p.Tags.Intersect(tags).Any()) |
| 103 | + .ToList(); |
| 104 | + } |
| 105 | + |
| 106 | + |
| 107 | + |
| 108 | + return posts.Select(p => |
| 109 | + { |
| 110 | + return new PostSummary |
| 111 | + { |
| 112 | + Slug = p.Slug, |
| 113 | + Title = p.Title, |
| 114 | + Summary = p.Summary ?? _htmlRegex.Replace(p.Content?.Substring(0, 200) + " ...", string.Empty), |
| 115 | + Author = p.Author, |
| 116 | + Posted = p.Posted, |
| 117 | + Updated = p.Updated |
| 118 | + }; |
| 119 | + }); |
| 120 | + |
| 121 | + } |
| 122 | + catch (Exception ex) |
| 123 | + { |
| 124 | + _logger.LogError(ex, "Error loading posts"); |
| 125 | + throw; |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + public async Task<Post> GetPost(string? postTitle) |
| 130 | + { |
| 131 | + ArgumentNullException.ThrowIfNull(postTitle, nameof(postTitle)); |
| 132 | + try |
| 133 | + { |
| 134 | + Post? postObject = (_cache.TryGetValue("Post/" + postTitle!, out var page) ? page : null) as Post; |
| 135 | + if (postObject != null) |
| 136 | + { |
| 137 | + return postObject; |
| 138 | + } |
| 139 | + |
| 140 | + var markdown = await _provider.ReadPageContent($"Posts/{postTitle}"); |
| 141 | + var pipeline = new MarkdownPipelineBuilder() |
| 142 | + .UseYamlFrontMatter() |
| 143 | + .UseEmojiAndSmiley() |
| 144 | + .Build(); |
| 145 | + |
| 146 | + var document = Markdown.Parse(markdown, pipeline); |
| 147 | + var yamlBlock = document.Descendants<YamlFrontMatterBlock>().FirstOrDefault(); |
| 148 | + if (yamlBlock != null) |
| 149 | + { |
| 150 | + var yaml = markdown.Substring(yamlBlock.Span.Start + 3, yamlBlock.Span.Length - 6); |
| 151 | + markdown = markdown.Substring(yamlBlock.Span.Length + 1); |
| 152 | + document = Markdown.Parse(markdown, pipeline); |
| 153 | + |
| 154 | + var deserializer = new DeserializerBuilder() |
| 155 | + .WithNamingConvention(UnderscoredNamingConvention.Instance) |
| 156 | + .Build(); |
| 157 | + |
| 158 | + postObject = deserializer.Deserialize<Post>(yaml); |
| 159 | + } |
| 160 | + |
| 161 | + postObject ??= new Post |
| 162 | + { |
| 163 | + Slug = Slugify(postTitle), |
| 164 | + Author = string.Empty, |
| 165 | + Posted = DateTimeOffset.Now, |
| 166 | + Title = postTitle, |
| 167 | + }; |
| 168 | + |
| 169 | + postObject.Content = document.ToHtml(); |
| 170 | + |
| 171 | + _cache.Set("Post/" + postTitle!, postObject); |
| 172 | + return postObject; |
| 173 | + |
| 174 | + } |
| 175 | + catch (Exception ex) |
| 176 | + { |
| 177 | + _logger.LogError(ex, "Error loading post {postTitle}", postTitle); |
| 178 | + throw; |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + private string Slugify(string text) |
| 183 | + { |
| 184 | + var cleaned = Regex.Replace(text, @"\s+", " "); |
| 185 | + var trimmed = cleaned.Replace(" ", "-"); |
| 186 | + var normalized = trimmed.Normalize(NormalizationForm.FormD); |
| 187 | + var finalized = Regex.Replace(normalized, @"[^a-zA-Z0-9\-\._]", string.Empty); |
| 188 | + |
| 189 | + return finalized.ToLower(); |
| 190 | + } |
| 191 | + |
| 192 | + private static string RemoveHTMLTagsCompiled(string html) |
| 193 | + { |
| 194 | + return _htmlRegex.Replace(html, string.Empty); |
| 195 | + } |
| 196 | + |
| 197 | +} |
0 commit comments