返回 last30days-skill
news_rss.py
根目录 / skills / last30days / scripts / lib / news_rss.py
1 """Mainstream news & RSS/OPML source for last30days.
2
3 Shells out to ``news-rss-pp-cli`` (free, keyless). The CLI combines Google News
4 RSS (primary), Bing News RSS (summaries, direct publisher URLs, failover), and
5 any local OPML/pack feeds synced into its SQLite FTS5 store, with built-in
6 anti-spam guardrails (evergreen-domain blocking, syndication demotion,
7 cross-source deduplication, per-publisher domain caps).
8
9 Activation gate: default-on whenever ``news-rss-pp-cli`` is on PATH.
10 ``pipeline.available_sources`` checks ``shutil.which`` before including
11 ``news_rss``. The functions below also detect the missing-binary case.
12
13 Surface choice: ``news --json --days <N> --limit <L> -- <query>`` (NOT
14 ``--agent``, which enables ``--compact`` and trims summary/metadata fields).
15 """
16
17 from __future__ import annotations
18
19 import datetime
20 import json
21 import os
22 import re
23 import shutil
24 from typing import Any, Dict, List
25 from urllib.parse import parse_qs, urlparse
26
27 from . import cjk, log, subproc
28 from .relevance import token_overlap_relevance
29
30
31 CLI_BIN = "news-rss-pp-cli"
32
33 DEPTH_CONFIG = {
34 "quick": 4,
35 "default": 8,
36 "deep": 15,
37 }
38
39 SEARCH_TIMEOUT = 30
40 MIN_HEADLINE_WORDS = 3
41
42 _ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
43 _URL_USERINFO_RE = re.compile(r"([A-Za-z][A-Za-z0-9+.-]{0,15}://)[^\s/?#]+@")
44 _ALLOWED_SOURCES = frozenset({"google", "bing", "local"})
45
46 # Keep only OS, cache/config-dir, locale, TLS, and proxy settings.
47 # Never inherit unrelated provider secrets or runtime-injection vars like NODE_OPTIONS.
48 _CHILD_ENV_ALLOWLIST = frozenset({
49 "PATH", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "APPDATA",
50 "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME",
51 "XDG_STATE_HOME", "SYSTEMROOT", "WINDIR", "SYSTEMDRIVE", "COMSPEC",
52 "PATHEXT", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "LC_CTYPE",
53 "TZ", "NO_COLOR", "TERM", "SSL_CERT_FILE", "SSL_CERT_DIR",
54 "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
55 })
56
57
58 def _scrub_url_userinfo(text: str) -> str:
59 return _URL_USERINFO_RE.sub(r"\1", text) if text else text
60
61
62 def _child_env() -> Dict[str, str]:
63 """Allowlisted child environment for news-rss-pp-cli."""
64 return {
65 name: value
66 for name, value in os.environ.items()
67 if name.upper() in _CHILD_ENV_ALLOWLIST or name.upper().startswith("LC_")
68 }
69
70
71 def _log(msg: str) -> None:
72 log.source_log("News RSS", msg, tty_only=False)
73
74
75 def _is_available() -> bool:
76 """True when the news-rss-pp-cli binary is on PATH."""
77 return shutil.which(CLI_BIN) is not None
78
79
80 def _parse_iso_date(value: Any) -> datetime.date | None:
81 if not isinstance(value, str):
82 return None
83 raw = value.strip()
84 if len(raw) >= 10 and _ISO_DATE_RE.match(raw[:10]):
85 try:
86 return datetime.date.fromisoformat(raw[:10])
87 except ValueError:
88 return None
89 return None
90
91
92 def _window_days(from_date: str | None, to_date: str | None) -> int:
93 """Compute a safe ``--days`` value covering ``from_date`` through today."""
94 start = _parse_iso_date(from_date)
95 if start is None:
96 return 30
97 end = _parse_iso_date(to_date) or datetime.date.today()
98 today = datetime.date.today()
99 anchor = max(end, today)
100 span = (anchor - start).days + 1
101 return max(1, min(365, span))
102
103
104 def _sanitize_sources_csv(raw: Any) -> str:
105 """Validate optional comma-separated source override (google,bing,local)."""
106 if not isinstance(raw, str) or not raw.strip():
107 return ""
108 tokens = [
109 tok.strip().lower()
110 for tok in raw.split(",")
111 if tok.strip().lower() in _ALLOWED_SOURCES
112 ]
113 seen: list[str] = []
114 for tok in tokens:
115 if tok not in seen:
116 seen.append(tok)
117 return ",".join(seen)
118
119
120 def _build_search_args(
121 topic: str,
122 *,
123 days: int = 30,
124 limit: int = 18,
125 sources_csv: str = "",
126 db_path: str = "",
127 ) -> List[str]:
128 args = [
129 CLI_BIN,
130 "news",
131 "--json",
132 "--days",
133 str(max(1, min(365, days))),
134 "--limit",
135 str(max(1, limit)),
136 ]
137 if sources_csv:
138 args += ["--sources", sources_csv]
139 if db_path:
140 args += ["--db", db_path]
141 args += ["--", topic]
142 return args
143
144
145 def _record_iso_date(rec: Dict[str, Any]) -> str | None:
146 """Return the article's YYYY-MM-DD date from published_date or published_at."""
147 for key in ("published_date", "published_at", "date"):
148 parsed = _parse_iso_date(rec.get(key))
149 if parsed is not None:
150 return parsed.isoformat()
151 return None
152
153
154 def _unwrap_bing_redirect(raw_url: str) -> str:
155 """Extract the target publisher URL from Bing News ``apiclick.aspx`` redirects."""
156 if not raw_url:
157 return ""
158 try:
159 parsed = urlparse(raw_url)
160 except ValueError:
161 return raw_url
162 host = (parsed.hostname or "").lower()
163 if (host == "bing.com" or host.endswith(".bing.com")) and "/news/apiclick.aspx" in parsed.path.lower():
164 targets = parse_qs(parsed.query).get("url") or []
165 for candidate in targets:
166 cand = candidate.strip()
167 if not cand:
168 continue
169 try:
170 inner = urlparse(cand)
171 except ValueError:
172 continue
173 if inner.scheme.lower() in {"http", "https"} and inner.netloc:
174 return cand
175 return raw_url
176
177
178 def _clean_publisher(raw: str) -> str:
179 """Trim SEO tagline suffixes from verbose RSS publisher names."""
180 pub = raw.strip()
181 if len(pub) <= 30:
182 return pub
183 for sep in (" - ", " | "):
184 if sep in pub:
185 head = pub.split(sep, 1)[0].strip()
186 if len(head) >= 2:
187 return head
188 return pub
189
190
191 def _best_url(rec: Dict[str, Any]) -> str:
192 """Prefer a direct canonical publisher URL over Google/Bing News redirects."""
193 canonical = _unwrap_bing_redirect(str(rec.get("canonical_url") or "").strip())
194 url = _unwrap_bing_redirect(str(rec.get("url") or "").strip())
195 if canonical and "news.google.com/rss/articles/" not in canonical:
196 return canonical
197 return url or canonical
198
199
200 def _coerce_items(data: Any) -> List[Dict[str, Any]] | None:
201 """Extract the items array from ``news-rss-pp-cli news --json`` output.
202
203 Returns None when the top-level JSON shape is unexpected so callers can
204 distinguish malformed output from a legitimate empty result set.
205 """
206 if isinstance(data, dict):
207 items = data.get("items")
208 if items is None and "query" in data:
209 return []
210 if isinstance(items, list):
211 return [r for r in items if isinstance(r, dict)]
212 results = data.get("results")
213 if isinstance(results, list):
214 return [r for r in results if isinstance(r, dict)]
215 return None
216 if isinstance(data, list):
217 return [r for r in data if isinstance(r, dict)]
218 return None
219
220
221 def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:
222 """Invoke news-rss-pp-cli and return ``{"results": [...]}``. Never raises."""
223 if not _is_available():
224 return {"results": [], "error": f"{CLI_BIN} not on PATH"}
225 try:
226 result = subproc.run_with_timeout(cmd, timeout=timeout, env=_child_env())
227 except subproc.SubprocTimeout as exc:
228 msg = _scrub_url_userinfo(str(exc))
229 _log(f"Timeout: {msg}")
230 return {"results": [], "error": msg}
231 except FileNotFoundError as exc:
232 msg = _scrub_url_userinfo(str(exc))
233 _log(f"Binary missing: {msg}")
234 return {"results": [], "error": msg}
235 except OSError as exc:
236 msg = _scrub_url_userinfo(str(exc))
237 _log(f"Spawn failed: {msg}")
238 return {"results": [], "error": msg}
239
240 if result.returncode != 0:
241 stderr = _scrub_url_userinfo(result.stderr or "")
242 snippet = stderr.strip().splitlines()[:1]
243 first = snippet[0] if snippet else f"exit {result.returncode}"
244 _log(f"CLI exit {result.returncode}: {first}")
245 return {"results": [], "error": first}
246
247 stdout = (result.stdout or "").strip()
248 if not stdout:
249 return {"results": []}
250 try:
251 data = json.loads(stdout)
252 except json.JSONDecodeError as exc:
253 msg = _scrub_url_userinfo(str(exc))
254 _log(f"JSON decode failed: {msg}")
255 return {"results": [], "error": f"json decode: {msg}"}
256
257 items = _coerce_items(data)
258 if items is None:
259 msg = "unexpected News RSS response shape"
260 _log(msg)
261 return {"results": [], "error": msg}
262
263 out: Dict[str, Any] = {"results": items}
264 if isinstance(data, dict):
265 if isinstance(data.get("sources_used"), list):
266 out["sources_used"] = data["sources_used"]
267 if isinstance(data.get("fetch_failures"), list) and data["fetch_failures"]:
268 out["fetch_failures"] = data["fetch_failures"]
269 return out
270
271
272 def search_news_rss(
273 topic: str,
274 from_date: str,
275 to_date: str,
276 depth: str = "default",
277 config: Dict[str, Any] | None = None,
278 ) -> Dict[str, Any]:
279 """Search mainstream news and synced OPML RSS feeds via news-rss-pp-cli.
280
281 Windows records strictly to ``from_date..to_date`` on each article's ISO
282 date; undated articles (rare) pass through with low date confidence.
283 """
284 if not topic or not topic.strip():
285 return {"results": []}
286 if not _is_available():
287 return {"results": [], "error": f"{CLI_BIN} not on PATH"}
288
289 cfg = config or {}
290 limit = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
291 days = _window_days(from_date, to_date)
292 sources_csv = _sanitize_sources_csv(
293 cfg.get("LAST30DAYS_NEWS_RSS_SOURCES")
294 or os.environ.get("LAST30DAYS_NEWS_RSS_SOURCES")
295 )
296 db_path = str(
297 cfg.get("LAST30DAYS_NEWS_RSS_DB")
298 or os.environ.get("LAST30DAYS_NEWS_RSS_DB")
299 or ""
300 ).strip()
301
302 # Request a modest buffer when filtering a historical window so client-side
303 # trimming after to_date still leaves enough in-window articles.
304 fetch_limit = min(40, limit + 8)
305 cmd = _build_search_args(
306 topic.strip(),
307 days=days,
308 limit=fetch_limit,
309 sources_csv=sources_csv,
310 db_path=db_path,
311 )
312 _log(f"news '{topic.strip()}' (days={days}, cap={limit})")
313 response = _run_cli(cmd, timeout=SEARCH_TIMEOUT)
314
315 records = response.get("results") or []
316 if isinstance(records, list):
317 in_window: list[dict[str, Any]] = []
318 undated: list[dict[str, Any]] = []
319 dropped = 0
320 for rec in records:
321 iso = _record_iso_date(rec)
322 if iso is None:
323 undated.append(rec)
324 elif from_date <= iso <= to_date:
325 in_window.append(rec)
326 else:
327 dropped += 1
328 if dropped:
329 _log(f"dropped {dropped} articles outside {from_date}..{to_date}")
330 kept = in_window + undated
331 if len(kept) > limit:
332 kept = kept[:limit]
333 response["results"] = kept
334
335 return response
336
337
338 def summarize_fetch_failures(response: Dict[str, Any]) -> str:
339 """Summarize upstream ``fetch_failures`` reported by news-rss-pp-cli.
340
341 Returns an empty string when no fetch failures are present.
342 """
343 if not isinstance(response, dict):
344 return ""
345 failures = response.get("fetch_failures")
346 if not isinstance(failures, list) or not failures:
347 return ""
348 parts: list[str] = []
349 for entry in failures[:3]:
350 if not isinstance(entry, dict):
351 continue
352 src = str(entry.get("source") or "feed").strip()
353 err = _scrub_url_userinfo(str(entry.get("error") or "fetch failed").strip())
354 parts.append(f"{src}: {err}")
355 if len(failures) > 3:
356 parts.append(f"+{len(failures) - 3} more")
357 return "; ".join(parts)
358
359
360 def _is_valid_headline(title: str) -> bool:
361 """Reject bare publication-name header rows while keeping CJK headlines without spaces."""
362 if not title:
363 return False
364 if cjk.has_cjk(title):
365 return len(title) >= 4
366 return len(title.split()) >= MIN_HEADLINE_WORDS
367
368
369 def parse_news_rss_response(
370 response: Dict[str, Any],
371 query: str = "",
372 ) -> List[Dict[str, Any]]:
373 """Transform ``search_news_rss()`` output into normalized raw dicts for
374 ``normalize._normalize_news_rss``.
375 """
376 raw_items = response.get("results") or []
377 if not isinstance(raw_items, list):
378 return []
379
380 parsed: List[Dict[str, Any]] = []
381 seen_urls: set[str] = set()
382 for idx, rec in enumerate(raw_items):
383 if not isinstance(rec, dict):
384 continue
385 title = str(rec.get("clean_title") or rec.get("title") or "").strip()
386 if not _is_valid_headline(title):
387 continue
388 url = _best_url(rec)
389 if not url:
390 continue
391 url_key = url.rstrip("/").lower()
392 if url_key in seen_urls:
393 continue
394 seen_urls.add(url_key)
395
396 publisher = _clean_publisher(str(rec.get("publisher") or ""))
397 domain = str(rec.get("publisher_domain") or "").strip()
398 summary = str(rec.get("summary") or "").strip()
399 content = str(rec.get("content") or "").strip()
400 body = summary or content[:600] or title
401 iso_date = _record_iso_date(rec)
402 rss_source = str(rec.get("source") or "").strip()
403
404 raw_cluster = rec.get("cluster_count")
405 try:
406 cluster_count = max(1, int(raw_cluster)) if raw_cluster is not None else 1
407 except (TypeError, ValueError):
408 cluster_count = 1
409
410 outlets_raw = rec.get("cluster_outlets")
411 cluster_outlets: list[str] = []
412 if isinstance(outlets_raw, list):
413 for o in outlets_raw:
414 if isinstance(o, dict):
415 pub = _clean_publisher(str(o.get("publisher") or ""))
416 if pub and pub not in cluster_outlets:
417 cluster_outlets.append(pub)
418 elif isinstance(o, str):
419 pub = _clean_publisher(o)
420 if pub and pub not in cluster_outlets:
421 cluster_outlets.append(pub)
422
423 if query:
424 text_for_rel = f"{title} {body}".strip() if body != title else title
425 rel = token_overlap_relevance(query, text_for_rel)
426 min_rel = 0.15 if cjk.has_cjk(query) else 0.20
427 if rel < min_rel:
428 continue
429 else:
430 rel = 0.7
431
432 rank_decay = max(0.0, 0.10 - idx * 0.005)
433 cluster_bonus = min(0.10, max(0, cluster_count - 1) * 0.03)
434 relevance = round(min(1.0, max(0.2, rel * 0.85 + rank_decay + cluster_bonus)), 2)
435
436 why_parts: list[str] = []
437 if publisher:
438 why_parts.append(publisher)
439 if cluster_count > 1:
440 why_parts.append(f"{cluster_count} outlets")
441 if rss_source:
442 why_parts.append(rss_source)
443 why = " · ".join(why_parts) if why_parts else "Mainstream news RSS"
444
445 parsed.append({
446 "id": str(rec.get("id") or url),
447 "title": title,
448 "summary": body,
449 "url": url,
450 "publisher": publisher or domain,
451 "publisher_domain": domain,
452 "date": iso_date,
453 "cluster_count": cluster_count,
454 "cluster_outlets": cluster_outlets,
455 "rss_source": rss_source,
456 "relevance": relevance,
457 "why_relevant": why,
458 })
459
460 return parsed
461
461 lines PYTHON