askrobots / dbbasic-rss
Public
RSS feeds from TSV, CSV, JSON or Python lists, for any Python web framework or a static site.
feed.py · 7.6 KB · 239 lines
| 1 | """Core RSS Feed and Item classes""" |
| 2 | |
| 3 | from datetime import datetime |
| 4 | from typing import Optional, List, Dict, Any |
| 5 | |
| 6 | |
| 7 | class FeedItem: |
| 8 | """Represents a single RSS feed item (article/post)""" |
| 9 | |
| 10 | def __init__( |
| 11 | self, |
| 12 | title: str, |
| 13 | link: str, |
| 14 | description: str = "", |
| 15 | content: Optional[str] = None, |
| 16 | pub_date: Optional[str] = None, |
| 17 | guid: Optional[str] = None, |
| 18 | author: Optional[str] = None, |
| 19 | categories: Optional[List[str]] = None, |
| 20 | enclosure: Optional[Dict[str, str]] = None, |
| 21 | ): |
| 22 | """ |
| 23 | Create a feed item. |
| 24 | |
| 25 | Args: |
| 26 | title: Article title |
| 27 | link: Article URL |
| 28 | description: Short description/summary |
| 29 | content: Full HTML content (optional) |
| 30 | pub_date: Publication date (ISO format or datetime) |
| 31 | guid: Unique identifier (uses link if not provided) |
| 32 | author: Author name |
| 33 | categories: List of category/tag names |
| 34 | enclosure: Media attachment dict with 'url', 'type', 'length' (for podcasts) |
| 35 | """ |
| 36 | self.title = title |
| 37 | self.link = link |
| 38 | self.description = description |
| 39 | self.content = content |
| 40 | self.pub_date = self._parse_date(pub_date) if pub_date else None |
| 41 | self.guid = guid or link |
| 42 | self.author = author |
| 43 | self.categories = categories or [] |
| 44 | self.enclosure = enclosure |
| 45 | |
| 46 | def _parse_date(self, date_input): |
| 47 | """Parse various date formats to RFC 822 format for RSS""" |
| 48 | if isinstance(date_input, datetime): |
| 49 | return date_input.strftime("%a, %d %b %Y %H:%M:%S GMT") |
| 50 | |
| 51 | if isinstance(date_input, str): |
| 52 | # Try parsing ISO format |
| 53 | try: |
| 54 | dt = datetime.fromisoformat(date_input.replace('Z', '+00:00')) |
| 55 | return dt.strftime("%a, %d %b %Y %H:%M:%S GMT") |
| 56 | except ValueError: |
| 57 | # If already in RSS format, return as-is |
| 58 | return date_input |
| 59 | |
| 60 | return None |
| 61 | |
| 62 | |
| 63 | class Feed: |
| 64 | """Main RSS Feed class""" |
| 65 | |
| 66 | def __init__( |
| 67 | self, |
| 68 | title: str = "RSS Feed", |
| 69 | link: str = "", |
| 70 | description: str = "", |
| 71 | language: str = "en", |
| 72 | author: Optional[str] = None, |
| 73 | author_email: Optional[str] = None, |
| 74 | image_url: Optional[str] = None, |
| 75 | image_title: Optional[str] = None, |
| 76 | image_link: Optional[str] = None, |
| 77 | ttl: Optional[int] = None, |
| 78 | category: Optional[str] = None, |
| 79 | ): |
| 80 | """ |
| 81 | Create an RSS feed. |
| 82 | |
| 83 | Args: |
| 84 | title: Feed title |
| 85 | link: Feed/site URL |
| 86 | description: Feed description |
| 87 | language: Language code (default: 'en') |
| 88 | author: Author/creator name |
| 89 | author_email: Author email |
| 90 | image_url: Feed image/logo URL |
| 91 | image_title: Image title (defaults to feed title) |
| 92 | image_link: Image link (defaults to feed link) |
| 93 | ttl: Time-to-live in minutes (cache duration) |
| 94 | category: Feed category |
| 95 | """ |
| 96 | self.title = title |
| 97 | self.link = link |
| 98 | self.description = description |
| 99 | self.language = language |
| 100 | self.author = author |
| 101 | self.author_email = author_email |
| 102 | self.image_url = image_url |
| 103 | self.image_title = image_title or title |
| 104 | self.image_link = image_link or link |
| 105 | self.ttl = ttl |
| 106 | self.category = category |
| 107 | self.items: List[FeedItem] = [] |
| 108 | self.build_date = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT") |
| 109 | |
| 110 | def add_item(self, item: FeedItem) -> None: |
| 111 | """Add a FeedItem to the feed""" |
| 112 | self.items.append(item) |
| 113 | |
| 114 | def add_post( |
| 115 | self, |
| 116 | title: str, |
| 117 | link: str, |
| 118 | description: str = "", |
| 119 | **kwargs |
| 120 | ) -> FeedItem: |
| 121 | """ |
| 122 | Convenience method to add a post without creating FeedItem manually. |
| 123 | |
| 124 | Args: |
| 125 | title: Article title |
| 126 | link: Article URL |
| 127 | description: Short description |
| 128 | **kwargs: Additional FeedItem arguments (content, pub_date, author, etc.) |
| 129 | |
| 130 | Returns: |
| 131 | The created FeedItem |
| 132 | """ |
| 133 | item = FeedItem(title=title, link=link, description=description, **kwargs) |
| 134 | self.add_item(item) |
| 135 | return item |
| 136 | |
| 137 | def count(self) -> int: |
| 138 | """Return number of items in feed""" |
| 139 | return len(self.items) |
| 140 | |
| 141 | def oldest(self) -> Optional[str]: |
| 142 | """Return oldest publication date""" |
| 143 | dates = [item.pub_date for item in self.items if item.pub_date] |
| 144 | return min(dates) if dates else None |
| 145 | |
| 146 | def newest(self) -> Optional[str]: |
| 147 | """Return newest publication date""" |
| 148 | dates = [item.pub_date for item in self.items if item.pub_date] |
| 149 | return max(dates) if dates else None |
| 150 | |
| 151 | def to_xml(self) -> str: |
| 152 | """ |
| 153 | Generate RSS 2.0 XML. |
| 154 | |
| 155 | Returns: |
| 156 | RSS XML as string |
| 157 | """ |
| 158 | from .templates import render_rss |
| 159 | return render_rss(self) |
| 160 | |
| 161 | def write(self, filepath: str, format: str = "rss") -> None: |
| 162 | """ |
| 163 | Write feed to file. |
| 164 | |
| 165 | Args: |
| 166 | filepath: Output file path |
| 167 | format: 'rss' or 'atom' (currently only RSS supported) |
| 168 | """ |
| 169 | if format != "rss": |
| 170 | raise NotImplementedError(f"Format '{format}' not yet implemented") |
| 171 | |
| 172 | with open(filepath, 'w', encoding='utf-8') as f: |
| 173 | f.write(self.to_xml()) |
| 174 | |
| 175 | def validate(self) -> List[str]: |
| 176 | """ |
| 177 | Validate feed structure and return list of warnings. |
| 178 | |
| 179 | Returns: |
| 180 | List of warning messages (empty if valid) |
| 181 | """ |
| 182 | warnings = [] |
| 183 | |
| 184 | if not self.title: |
| 185 | warnings.append("Feed title is missing") |
| 186 | if not self.link: |
| 187 | warnings.append("Feed link is missing") |
| 188 | if not self.description: |
| 189 | warnings.append("Feed description is missing") |
| 190 | |
| 191 | for i, item in enumerate(self.items): |
| 192 | if not item.title: |
| 193 | warnings.append(f"Item {i}: title is missing") |
| 194 | if not item.link: |
| 195 | warnings.append(f"Item {i}: link is missing") |
| 196 | |
| 197 | return warnings |
| 198 | |
| 199 | def serve(self, request) -> Any: |
| 200 | """ |
| 201 | Flask/Django helper: Auto-detect browser vs feed reader. |
| 202 | |
| 203 | Args: |
| 204 | request: Flask request or Django request object |
| 205 | |
| 206 | Returns: |
| 207 | Appropriate response (XML for readers, could be HTML for browsers) |
| 208 | |
| 209 | Example: |
| 210 | @app.route('/rss') |
| 211 | def rss_feed(): |
| 212 | feed = Feed(...) |
| 213 | return feed.serve(request) |
| 214 | """ |
| 215 | # Try to detect user agent |
| 216 | user_agent = "" |
| 217 | if hasattr(request, 'headers'): |
| 218 | user_agent = request.headers.get('User-Agent', '').lower() |
| 219 | elif hasattr(request, 'META'): |
| 220 | user_agent = request.META.get('HTTP_USER_AGENT', '').lower() |
| 221 | |
| 222 | # Check if it's a browser (not a feed reader) |
| 223 | is_browser = any(browser in user_agent for browser in [ |
| 224 | 'mozilla', 'chrome', 'safari', 'edge', 'opera' |
| 225 | ]) and 'feed' not in user_agent and 'rss' not in user_agent |
| 226 | |
| 227 | # Generate XML |
| 228 | xml_content = self.to_xml() |
| 229 | |
| 230 | # Return appropriate response based on framework |
| 231 | if hasattr(request, 'app'): # Flask |
| 232 | from flask import Response |
| 233 | if is_browser: |
| 234 | # Could render HTML preview here in the future |
| 235 | return Response(xml_content, mimetype='application/rss+xml') |
| 236 | return Response(xml_content, mimetype='application/rss+xml') |
| 237 | else: # Django or other |
| 238 | from django.http import HttpResponse |
| 239 | return HttpResponse(xml_content, content_type='application/rss+xml') |