2022-06-11 22:51:39 +00:00
|
|
|
from rss import RssReader, FeedItem
|
|
|
|
from database import Database
|
|
|
|
from telegram import Notifier
|
|
|
|
|
|
|
|
|
|
|
|
class UpdateManager:
|
2022-07-08 20:57:41 +00:00
|
|
|
"""Implement the feed update."""
|
|
|
|
|
2022-06-11 22:51:39 +00:00
|
|
|
def __init__(self, database: Database, notifier: Notifier, rss_reader: RssReader) -> None:
|
2022-06-12 22:13:30 +00:00
|
|
|
self.database: Database = database
|
|
|
|
self.notifier: Notifier = notifier
|
|
|
|
self.rss_reader: RssReader = rss_reader
|
2022-06-11 22:51:39 +00:00
|
|
|
|
|
|
|
def update(self):
|
2022-07-08 20:57:41 +00:00
|
|
|
"""Send new feed items to the user."""
|
2022-06-11 22:51:39 +00:00
|
|
|
feeds = self.database.find_feeds()
|
|
|
|
|
|
|
|
for feed_id, feed_url in feeds:
|
2022-06-12 22:13:30 +00:00
|
|
|
feed = self.rss_reader.get_feed(feed_url)
|
|
|
|
new_items = feed.items
|
2022-06-12 17:13:58 +00:00
|
|
|
old_items_urls = self.database.find_feed_items_urls(feed_id)
|
2022-06-11 22:51:39 +00:00
|
|
|
|
2022-06-12 17:13:58 +00:00
|
|
|
diff = self.__calculate_difference(new_items, old_items_urls)
|
2022-06-11 22:51:39 +00:00
|
|
|
|
|
|
|
if not diff:
|
|
|
|
continue
|
|
|
|
|
|
|
|
chat_ids = self.database.find_feed_subscribers(feed_id)
|
2022-06-12 22:13:30 +00:00
|
|
|
self.notifier.send_updates(chat_ids, diff, feed.title)
|
2022-06-11 22:51:39 +00:00
|
|
|
self.database.update_feed_items(feed_id, new_items)
|
|
|
|
|
2022-06-12 17:13:58 +00:00
|
|
|
def __calculate_difference(self, new_items: list[FeedItem], old_items_urls: list[str]) -> list[FeedItem]:
|
2022-07-08 20:57:41 +00:00
|
|
|
"""Calculate new feed items."""
|
2022-06-12 17:13:58 +00:00
|
|
|
if not old_items_urls:
|
2022-06-11 22:51:39 +00:00
|
|
|
return new_items
|
2022-07-08 20:57:41 +00:00
|
|
|
|
2022-06-11 22:51:39 +00:00
|
|
|
diff = []
|
|
|
|
|
|
|
|
for item in new_items:
|
2022-06-12 17:13:58 +00:00
|
|
|
if item.url not in old_items_urls:
|
2022-06-11 22:51:39 +00:00
|
|
|
diff.append(item)
|
|
|
|
|
|
|
|
return diff
|