1"""RSS & Atom Feed to JSON — Apify Actor.
2
3Fetches one or more RSS 2.0 or Atom feeds and normalizes every item into a
4single clean JSON schema, regardless of source format. Handles the messy
5reality of feeds: RSS vs Atom element names, multiple date formats, namespaced
6elements (content:encoded, dc:creator, media:*), and CDATA.
7
8The value here is the normalization: the same tidy record shape whether the
9source is RSS 2.0 or Atom, so downstream code never has to branch on format.
10"""
11
12from __future__ import annotations
13
14import asyncio
15import re
16from datetime import datetime, timezone
17from email.utils import parsedate_to_datetime
18from xml.etree import ElementTree as ET
19
20import httpx
21try:
22 from . import _tier_prices
23except ImportError:
24 import _tier_prices
25from apify import Actor
26
27NS = {
28 "atom": "http://www.w3.org/2005/Atom",
29 "content": "http://purl.org/rss/1.0/modules/content/",
30 "dc": "http://purl.org/dc/elements/1.1/",
31 "media": "http://search.yahoo.com/mrss/",
32}
33
34
35def _strip(s: str | None) -> str | None:
36 if s is None:
37 return None
38 s = s.strip()
39 return s or None
40
41
42def _normalize_date(raw: str | None) -> str | None:
43 """Convert RSS (RFC 822) or Atom (ISO 8601) dates to ISO 8601 UTC."""
44 if not raw:
45 return None
46 raw = raw.strip()
47
48 try:
49 dt = parsedate_to_datetime(raw)
50 if dt is not None:
51 if dt.tzinfo is None:
52 dt = dt.replace(tzinfo=timezone.utc)
53 return dt.astimezone(timezone.utc).isoformat()
54 except (TypeError, ValueError):
55 pass
56
57 try:
58 dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
59 if dt.tzinfo is None:
60 dt = dt.replace(tzinfo=timezone.utc)
61 return dt.astimezone(timezone.utc).isoformat()
62 except ValueError:
63 return raw
64
65
66def _localname(tag: str) -> str:
67 return tag.rsplit("}", 1)[-1]
68
69
70def _find_text(el, names: list[str]) -> str | None:
71 """Find first child whose local name matches any of `names`."""
72 for child in el:
73 if _localname(child.tag) in names and child.text:
74 return _strip(child.text)
75 return None
76
77
78def parse_rss_item(item) -> dict:
79 """Parse an RSS 2.0 <item>."""
80
81 link = _find_text(item, ["link"])
82
83 content = item.find("content:encoded", NS)
84 content_text = _strip(content.text) if content is not None and content.text else None
85 description = _find_text(item, ["description"])
86 creator = item.find("dc:creator", NS)
87 author = (_strip(creator.text) if creator is not None and creator.text else None) or _find_text(item, ["author"])
88
89 cats = [_strip(c.text) for c in item if _localname(c.tag) == "category" and c.text]
90
91 guid = _find_text(item, ["guid"])
92
93 media_url = None
94 for c in item:
95 if _localname(c.tag) == "enclosure" and c.get("url"):
96 media_url = c.get("url")
97 break
98 return {
99 "title": _find_text(item, ["title"]),
100 "link": link,
101 "summary": description,
102 "content": content_text,
103 "author": author,
104 "published": _normalize_date(_find_text(item, ["pubDate", "date"])),
105 "updated": None,
106 "categories": [c for c in cats if c],
107 "guid": guid,
108 "mediaUrl": media_url,
109 }
110
111
112def parse_atom_entry(entry) -> dict:
113 """Parse an Atom <entry>."""
114
115 link = None
116 for ln in entry.findall("atom:link", NS):
117 if ln.get("rel") in (None, "alternate") and ln.get("href"):
118 link = ln.get("href")
119 break
120 if link is None:
121 any_link = entry.find("atom:link", NS)
122 link = any_link.get("href") if any_link is not None else None
123
124 content_el = entry.find("atom:content", NS)
125 content_text = _strip(content_el.text) if content_el is not None and content_el.text else None
126 summary = _find_text(entry, ["summary"])
127
128 authors = [
129 _strip(n.text)
130 for n in entry.findall("atom:author/atom:name", NS)
131 if n is not None and n.text
132 ]
133 cats = [c.get("term") for c in entry.findall("atom:category", NS) if c.get("term")]
134
135 return {
136 "title": _find_text(entry, ["title"]),
137 "link": link,
138 "summary": summary,
139 "content": content_text,
140 "author": authors[0] if authors else None,
141 "published": _normalize_date(_find_text(entry, ["published", "issued"])),
142 "updated": _normalize_date(_find_text(entry, ["updated", "modified"])),
143 "categories": cats,
144 "guid": _find_text(entry, ["id"]),
145 "mediaUrl": None,
146 }
147
148
149def parse_feed(xml_text: str) -> tuple[dict, list[dict], str]:
150 """Parse a feed -> (feed_meta, items, feed_type)."""
151 root = ET.fromstring(xml_text)
152 tag = _localname(root.tag)
153
154 if tag == "rss":
155 channel = root.find("channel")
156 if channel is None:
157 return {}, [], "rss"
158 meta = {
159 "feedTitle": _find_text(channel, ["title"]),
160 "feedLink": _find_text(channel, ["link"]),
161 "feedDescription": _find_text(channel, ["description"]),
162 }
163 items = [parse_rss_item(it) for it in channel.findall("item")]
164 return meta, items, "rss"
165
166 if tag == "feed":
167 meta = {
168 "feedTitle": _find_text(root, ["title"]),
169 "feedLink": None,
170 "feedDescription": _find_text(root, ["subtitle"]),
171 }
172 for ln in root.findall("atom:link", NS):
173 if ln.get("rel") in (None, "alternate") and ln.get("href"):
174 meta["feedLink"] = ln.get("href")
175 break
176 items = [parse_atom_entry(e) for e in root.findall("atom:entry", NS)]
177 return meta, items, "atom"
178
179
180 items = [parse_rss_item(it) for it in root if _localname(it.tag) == "item"]
181 return {"feedTitle": None}, items, "rdf"
182
183
184async def main() -> None:
185 async with Actor:
186 actor_input = await Actor.get_input() or {}
187 urls = [u.strip() for u in (actor_input.get("feedUrls", []) or []) if u and u.strip()]
188 max_items = int(actor_input.get("maxItemsPerFeed", 100))
189 include_content = bool(actor_input.get("includeContent", True))
190
191 if not urls:
192 Actor.log.warning("No feed URLs provided. Add one or more RSS/Atom feed URLs.")
193 await Actor.push_data([])
194 return
195
196 Actor.log.info(f"Fetching {len(urls)} feed(s).")
197
198 async with httpx.AsyncClient(
199 timeout=40.0, follow_redirects=True,
200 headers={"User-Agent": "scrapeworks-rss-to-json/0.1", "Accept": "application/rss+xml, application/atom+xml, application/xml, text/xml"},
201 ) as client:
202 for url in urls:
203 xml_text = None
204 for attempt in range(1, 4):
205 try:
206 resp = await client.get(url)
207 resp.raise_for_status()
208 xml_text = resp.text
209 break
210 except httpx.HTTPError as exc:
211 Actor.log.warning(f"Fetch attempt {attempt} failed for {url}: {exc}")
212 if attempt < 3:
213 await asyncio.sleep(attempt * 2)
214
215 if xml_text is None:
216 await Actor.push_data([{"feedUrl": url, "error": "Failed to fetch feed"}])
217 continue
218
219 try:
220 meta, items, ftype = parse_feed(xml_text)
221 except ET.ParseError as exc:
222 Actor.log.warning(f"Could not parse {url}: {exc}")
223 await Actor.push_data([{"feedUrl": url, "error": f"Invalid feed XML: {exc}"}])
224 continue
225
226 Actor.log.info(f" {url}: {ftype} feed, {len(items)} items")
227 batch = []
228 for it in items[:max_items]:
229 if not include_content:
230 it.pop("content", None)
231 it["feedUrl"] = url
232 it["feedTitle"] = meta.get("feedTitle")
233 batch.append(it)
234 if batch:
235 await Actor.push_data(batch)
236
237 Actor.log.info("Done.")