#!/usr/bin/env python3 from dataclasses import dataclass from datetime import datetime def _format_date(dt): """convert a datetime into an RFC 822 formatted date Input date must be in GMT. Stolen from PyRSS2Gen. """ # Looks like: # Sat, 07 Sep 2002 00:00:01 GMT # Can't use strftime because that's locale dependent # # Isn't there a standard way to do this for Python? The # rfc822 and email.Utils modules assume a timestamp. The # following is based on the rfc822 module. weekdays = [ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", ] months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ] return "%s, %02d %s %04d %02d:%02d:%02d GMT" % ( weekdays[dt.weekday()], dt.day, months[dt.month - 1], dt.year, dt.hour, dt.minute, dt.second, ) @dataclass class RSSItem: title: str url: str content: str date: str enclosures: list[str] guid: str @dataclass class RSSFeed: title: str url: str description: str content: list[RSSItem] def escape(str): str = str.replace("&", "&") return str def buildRSS(feed_data: RSSFeed): """ feed_data = { title, url, description, content = [{ title, url, content, date, [enclosures], guid }] } """ feed = f""" {feed_data.title} {feed_data.url} {escape(feed_data.description)} {_format_date(datetime.now())}""" for item in feed_data.content: feed += " " feed += f" <![CDATA[{item.title or 'N/A'}]]>" feed += f" {item.url or 'N/A'}" feed += f" " if item.date: if isinstance(item.date, str): feed += f" {item.date}" else: feed += f" {_format_date(item.date)}" for enclosure in item.enclosures: feed += f' ' if item.guid: feed += f" {item.guid}" feed += " " feed += " " feed += "" return feed