2026-08-28 21:49:05 -04:00
|
|
|
"""Feed helpers shared by the news spider (no Scrapy import)."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import datetime
|
2026-11-14 00:47:04 -05:00
|
|
|
import re
|
2026-08-28 21:49:05 -04:00
|
|
|
from email.utils import parsedate_to_datetime
|
|
|
|
|
from urllib.parse import urlparse
|
|
|
|
|
|
|
|
|
|
AUDIO_EXT = (".mp3", ".m4a", ".ogg", ".wav", ".aac", ".flac", ".opus")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def is_audio_url(url: str) -> bool:
|
|
|
|
|
path = urlparse(url or "").path.lower()
|
|
|
|
|
return any(path.endswith(ext) for ext in AUDIO_EXT)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def article_timestamp(pub_date: str | None) -> datetime.datetime:
|
|
|
|
|
"""Prefer the feed's pubDate/published; fall back to now (UTC)."""
|
|
|
|
|
if pub_date:
|
|
|
|
|
try:
|
|
|
|
|
return parsedate_to_datetime(pub_date).astimezone(datetime.timezone.utc)
|
|
|
|
|
except (TypeError, ValueError, IndexError):
|
|
|
|
|
pass
|
|
|
|
|
try:
|
|
|
|
|
raw = pub_date.replace("Z", "+00:00")
|
|
|
|
|
ts = datetime.datetime.fromisoformat(raw)
|
|
|
|
|
if ts.tzinfo is None:
|
|
|
|
|
ts = ts.replace(tzinfo=datetime.timezone.utc)
|
|
|
|
|
return ts
|
|
|
|
|
except ValueError:
|
|
|
|
|
pass
|
|
|
|
|
return datetime.datetime.now(datetime.timezone.utc)
|
2026-11-14 00:47:04 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# Whole-title CDATA wrapper only. Keep in sync with app/news_title.py —
|
|
|
|
|
# the scraper image and the API image do not share a package.
|
|
|
|
|
_CDATA_WRAPPER = re.compile(
|
|
|
|
|
r"\A\s*<!\[CDATA\[(.*?)\]\]>\s*\Z",
|
|
|
|
|
re.DOTALL,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def unwrap_cdata_title(title):
|
|
|
|
|
"""Strip a surrounding CDATA wrapper. Anything else is unchanged.
|
|
|
|
|
|
|
|
|
|
``<![CDATA[Hello]]>`` and ``\\n <![CDATA[Hello]]>`` become
|
|
|
|
|
``Hello``. Real HTML (``<b>Hello</b>``) and a title that merely contains
|
|
|
|
|
the markers are returned as-is. Non-strings pass through.
|
|
|
|
|
"""
|
|
|
|
|
if not isinstance(title, str):
|
|
|
|
|
return title
|
|
|
|
|
match = _CDATA_WRAPPER.match(title)
|
|
|
|
|
if match is None:
|
|
|
|
|
return title
|
|
|
|
|
return match.group(1).strip()
|