2024-01-17 13:20:32 +08:00
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
using YaeBlog.Core.Models;
|
|
|
|
|
|
|
|
|
|
namespace YaeBlog.Core.Services;
|
|
|
|
|
|
|
|
|
|
public class EssayContentService
|
|
|
|
|
{
|
|
|
|
|
private readonly ConcurrentDictionary<string, BlogEssay> _essays = new();
|
|
|
|
|
|
2024-01-26 17:29:37 +08:00
|
|
|
|
private readonly Dictionary<string, List<BlogEssay>> _tags = [];
|
|
|
|
|
|
2024-01-17 13:20:32 +08:00
|
|
|
|
public bool TryGet(string key, out BlogEssay? essay)
|
|
|
|
|
=> _essays.TryGetValue(key, out essay);
|
|
|
|
|
|
|
|
|
|
public bool TryAdd(string key, BlogEssay essay) => _essays.TryAdd(key, essay);
|
|
|
|
|
|
2024-07-22 16:59:43 +08:00
|
|
|
|
public IDictionary<string, BlogEssay> Essays => _essays;
|
2024-01-26 17:29:37 +08:00
|
|
|
|
|
|
|
|
|
public void RefreshTags()
|
|
|
|
|
{
|
|
|
|
|
foreach (BlogEssay essay in _essays.Values)
|
|
|
|
|
{
|
|
|
|
|
foreach (string tag in essay.Tags)
|
|
|
|
|
{
|
|
|
|
|
if (_tags.TryGetValue(tag, out var list))
|
|
|
|
|
{
|
|
|
|
|
list.Add(essay);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
_tags[tag] = [essay];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-01-26 20:54:35 +08:00
|
|
|
|
|
|
|
|
|
foreach (KeyValuePair<string,List<BlogEssay>> pair in _tags)
|
|
|
|
|
{
|
|
|
|
|
pair.Value.Sort();
|
|
|
|
|
}
|
2024-01-26 17:29:37 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public IEnumerable<KeyValuePair<string, int>> Tags => from item in _tags
|
2024-07-22 16:59:43 +08:00
|
|
|
|
orderby item.Value.Count descending
|
2024-01-26 17:29:37 +08:00
|
|
|
|
select KeyValuePair.Create(item.Key, item.Value.Count);
|
|
|
|
|
|
2024-01-31 21:36:00 +08:00
|
|
|
|
public int TagCount => _tags.Count;
|
|
|
|
|
|
2024-01-26 17:29:37 +08:00
|
|
|
|
public IEnumerable<BlogEssay> GetTag(string tag)
|
|
|
|
|
{
|
|
|
|
|
if (_tags.TryGetValue(tag, out var list))
|
|
|
|
|
{
|
|
|
|
|
return list;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw new KeyNotFoundException("Selected tag not found.");
|
|
|
|
|
}
|
2024-01-17 13:20:32 +08:00
|
|
|
|
}
|