YaeBlog/YaeBlog.Core/Services/EssayContentService.cs

62 lines
1.8 KiB
C#
Raw Permalink Normal View History

2024-01-17 13:20:32 +08:00
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using YaeBlog.Core.Abstractions;
2024-01-17 13:20:32 +08:00
using YaeBlog.Core.Models;
namespace YaeBlog.Core.Services;
public class EssayContentService : IEssayContentService
2024-01-17 13:20:32 +08:00
{
private readonly ConcurrentDictionary<string, BlogEssay> _essays = new();
private readonly Dictionary<EssayTag, List<BlogEssay>> _tags = [];
2024-01-26 17:29:37 +08:00
private readonly ConcurrentDictionary<string, BlogHeadline> _headlines = new();
public bool TryAdd(BlogEssay essay) => _essays.TryAdd(essay.FileName, essay);
2024-01-17 13:20:32 +08:00
public bool TryAddHeadline(string filename, BlogHeadline headline) => _headlines.TryAdd(filename, headline);
public IReadOnlyDictionary<string, BlogEssay> Essays => _essays;
2024-01-17 13:20:32 +08:00
public IReadOnlyDictionary<EssayTag, List<BlogEssay>> Tags => _tags;
2024-01-26 17:29:37 +08:00
public IReadOnlyDictionary<string, BlogHeadline> Headlines => _headlines;
2024-01-26 17:29:37 +08:00
public void RefreshTags()
{
_tags.Clear();
foreach (BlogEssay essay in _essays.Values)
{
foreach (EssayTag essayTag in essay.Tags.Select(tag => new EssayTag(tag)))
{
if (_tags.TryGetValue(essayTag, out List<BlogEssay>? essays))
{
essays.Add(essay);
}
else
{
_tags.Add(essayTag, [essay]);
}
}
}
2024-01-26 17:29:37 +08:00
}
public bool SearchByUrlEncodedTag(string tag, [NotNullWhen(true)] out List<BlogEssay>? result)
2024-01-26 17:29:37 +08:00
{
result = (from item in _tags
where item.Key.UrlEncodedTagName == tag
select item.Value).FirstOrDefault();
2024-01-26 17:29:37 +08:00
return result is not null;
2024-01-26 17:29:37 +08:00
}
public void Clear()
{
_essays.Clear();
_tags.Clear();
_headlines.Clear();
}
2024-01-17 13:20:32 +08:00
}