SharpRSS/SharpRss/FeedCache.cs

43 lines
1.3 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CodeHollow.FeedReader;
using Serilog;
using ToolQit.Extensions;
namespace SharpRss
{
/// <summary>
/// Global memory feed cache.
/// </summary>
public static class FeedCache
{
private static readonly Dictionary<string, Feed> CachedFeeds = new Dictionary<string, Feed>();
public static async Task<Feed> GetFeed(string urlKey)
{
Log.Verbose("Fetching feed: {UrlKey}", urlKey);
if (urlKey.IsNullEmptyWhiteSpace())
{
Log.Error("RSS Url is empty!");
return new Feed();
}
if (CachedFeeds.TryGetValue(urlKey, out Feed? fModel))
return fModel;
string feedUrl;
var urls = await FeedReader.GetFeedUrlsFromUrlAsync(urlKey);
if (!urls.Any())
feedUrl = urlKey;
else
feedUrl = urls.First().Url;
Feed feed = await FeedReader.ReadAsync(feedUrl);
if (feed != null)
{
Log.Warning("Could not get feed: {FeedUrl}", feedUrl);
CachedFeeds[feedUrl] = feed;
}
return feed;
}
}
}