RikoBot-Sharp/RssBotFeed.cs

96 lines
2.9 KiB
C#
Raw Normal View History

2020-01-30 20:57:41 +01:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CodeHollow.FeedReader;
namespace RSSBot {
public class RssBotFeed {
2020-11-05 19:34:45 +01:00
public readonly HashSet<long> Subs = new HashSet<long>();
2020-01-30 20:57:41 +01:00
public readonly string Url;
public string LastEntry;
2020-11-05 19:34:45 +01:00
public RssBotFeed(string url, string lastEntry = null, HashSet<long> subs = null)
{
2020-01-30 20:57:41 +01:00
Url = url;
if (!string.IsNullOrWhiteSpace(lastEntry)) {
LastEntry = lastEntry;
}
if (subs != null) {
Subs = subs;
}
}
2020-11-05 19:34:45 +01:00
public string MainLink { get; private set; }
public string Title { get; private set; }
public List<FeedItem> NewEntries { get; private set; }
public async Task Check()
{
2020-01-30 20:57:41 +01:00
Feed feed = await FeedReader.ReadAsync(Url);
if (string.IsNullOrWhiteSpace(feed.Link)) {
throw new Exception("Kein gültiger RSS-Feed.");
}
MainLink = feed.Link;
Title = feed.Title;
2020-11-05 19:34:45 +01:00
if (feed.Items == null || feed.Items.Count <= 0) {
return;
}
2020-01-30 20:57:41 +01:00
NewEntries = string.IsNullOrWhiteSpace(LastEntry)
? feed.Items.ToList()
: GetNewEntries(feed.Items);
LastEntry = string.IsNullOrWhiteSpace(feed.Items.First().Id)
? feed.Items.First().Link
: feed.Items.First().Id;
}
2020-11-05 19:34:45 +01:00
private List<FeedItem> GetNewEntries(IEnumerable<FeedItem> entries)
{
2020-01-30 20:57:41 +01:00
List<FeedItem> newEntries = new List<FeedItem>();
foreach (FeedItem entry in entries) {
if (!string.IsNullOrWhiteSpace(entry.Id)) {
if (entry.Id.Equals(LastEntry)) {
break;
}
newEntries.Add(entry);
} else {
if (entry.Link.Equals(LastEntry)) {
break;
}
newEntries.Add(entry);
}
}
newEntries.Reverse();
return newEntries;
}
2020-11-05 19:34:45 +01:00
public override string ToString()
{
2020-01-30 20:57:41 +01:00
return $"RSS-Feed: '{Url}'";
}
2020-11-05 19:34:45 +01:00
public void Cleanup(long chatId)
{
2020-01-30 20:57:41 +01:00
Subs.Remove(chatId);
string feedKey = $"{Configuration.RedisHash}:{Url}";
Configuration.Database.SetRemove($"{feedKey}:subs", chatId);
// No subscribers, delete all references
2020-11-05 19:34:45 +01:00
if (Subs.Count != 0 || !Configuration.Database.KeyExists(feedKey)) {
return;
}
2020-01-30 20:57:41 +01:00
Configuration.Database.KeyDelete(feedKey);
Configuration.Database.KeyDelete($"{feedKey}:subs");
Configuration.Database.SetRemove($"{Configuration.RedisHash}:feeds", Url);
}
}
}