返回 last30days-skill
reddit_search.py
根目录 / skills / last30days / scripts / lib / reddit_search.py
1 """Keyless Reddit discovery via Reddit's own site search fragment.
2
3 ``/svc/shreddit/search/?q=...&type=posts`` is the server-rendered HTML the
4 reddit.com search page loads. It serves HTTP 200 with no API key, and
5 ``/svc/shreddit/r/{sub}/search/`` restricts the same search to one subreddit.
6 Each post result unit carries:
7
8 - a ``<search-telemetry-tracker>`` whose JSON tracking context has
9 ``action_info.type == "post"``, the post id, title, and subreddit,
10 - the post-title link (the canonical permalink),
11 - a ``<faceplate-timeago ts=...>`` post date,
12 - a counter row of ``<faceplate-number>`` votes and comments.
13
14 So every discovered post arrives dated and scored, with no extra listing fetch.
15 The next page is a lazy ``<faceplate-partial>`` whose ``src`` carries a
16 ``cursor``. Output dicts match ``reddit_listing.parse_cards`` so downstream
17 code is unaffected.
18 """
19
20 import copy
21 import html as _html
22 import json
23 import re
24 import sys
25 import threading
26 import time
27 from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError
28 from dataclasses import dataclass, field
29 from typing import Any, Dict, List, Optional, Tuple
30 from urllib.parse import parse_qs, quote, urlencode, urlsplit
31
32 from . import http, reddit_listing, reddit_refs
33 from .relevance import token_overlap_relevance
34
35 BASE = "https://www.reddit.com"
36
37 # Post caps per run by depth.
38 DEPTH_LIMITS = {"quick": 10, "default": 25, "deep": 50}
39 # Global search pages per depth (about 7 posts per page).
40 GLOBAL_PAGE_CAPS = {"quick": 2, "default": 4, "deep": 8}
41 # Targeted subreddits get one page each.
42 SUB_PAGE_CAP = 1
43 MAX_WORKERS = 4
44 SEARCH_TIMEOUT = 15
45
46 # A recognizable page has post result units or Reddit's explicit no-results
47 # unit. Anything else (challenge page, changed markup) is a lane failure.
48 RESULTS_MARKER = 'view-events="search/view/post"'
49 NO_RESULTS_MARKER = 'view-events="search/view/no_results"'
50
51 _TRACKER = re.compile(
52 r'<search-telemetry-tracker\b[^>]*?\bdata-faceplate-tracking-context="([^"]*)"'
53 )
54 _TITLE_HREF = re.compile(
55 r'<a\b[^>]*?data-testid="post-title"[^>]*?\bhref="([^"]*)"'
56 r'|<a\b[^>]*?\bhref="([^"]*)"[^>]*?data-testid="post-title"'
57 )
58 _TIMEAGO = re.compile(r'<faceplate-timeago\b[^>]*?\bts="([^"]+)"')
59 _COUNTER = re.compile(
60 r'<faceplate-number\b[^>]*?\bnumber="(\d+)"[^>]*>\s*</faceplate-number>\s*(vote|comment)'
61 )
62 _NEXT_PAGE = re.compile(
63 r'<faceplate-partial\b[^>]*?\bsrc="([^"]*/svc/shreddit/[^"]*search/[^"]*)"'
64 )
65
66
67 # Run state. Reddit answers this endpoint with HTTP 403 "blocked by network
68 # security" (or a challenge page) for some networks, for every query alike, so
69 # the first such answer stops the remaining searches of the command instead of
70 # spending a rate-limit token on each subreddit. The lane is dispatched with
71 # the raw topic for every subquery, so one search also serves them all.
72 class _StreamCollector:
73 """Thread-safe per-stream buffer so earlier pages survive a timeout."""
74
75 def __init__(self) -> None:
76 self._lock = threading.Lock()
77 self._posts: List[Dict[str, Any]] = []
78 self._incomplete = False
79
80 def add(self, posts: List[Dict[str, Any]]) -> None:
81 if not posts:
82 return
83 with self._lock:
84 self._posts.extend(posts)
85
86 def mark_incomplete(self) -> None:
87 with self._lock:
88 self._incomplete = True
89
90 @property
91 def incomplete(self) -> bool:
92 with self._lock:
93 return self._incomplete
94
95 def snapshot(self) -> List[Dict[str, Any]]:
96 with self._lock:
97 return list(self._posts)
98
99
100 def _merge_streams(
101 streams: List[List[Dict[str, Any]]],
102 limit: int,
103 *,
104 deepcopy_posts: bool = False,
105 ) -> List[Dict[str, Any]]:
106 """Round-robin interleave across streams, dedupe by URL/post_id, and cap to ``limit``."""
107 results = [
108 stream[i]
109 for i in range(max((len(s) for s in streams), default=0))
110 for stream in streams
111 if i < len(stream)
112 ]
113 seen_urls: set = set()
114 seen_ids: set = set()
115 unique: List[Dict[str, Any]] = []
116 for post in results:
117 url = post.get("url")
118 pid = (post.get("metadata") or {}).get("post_id")
119 if (url and url in seen_urls) or (pid and pid in seen_ids):
120 continue
121 if url:
122 seen_urls.add(url)
123 if pid:
124 seen_ids.add(pid)
125 copied = copy.deepcopy(post) if deepcopy_posts else {**post}
126 copied["id"] = f"R{len(unique) + 1}"
127 unique.append(copied)
128 if len(unique) >= limit:
129 break
130 return unique
131
132
133 @dataclass
134 class _InflightSearch:
135 """In-flight search coordination slot shared between owner and waiting callers."""
136
137 done: threading.Event = field(default_factory=threading.Event)
138 partial: Optional[List[Dict[str, Any]]] = None
139 _lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
140 _collectors: List[_StreamCollector] = field(default_factory=list, init=False, repr=False)
141
142 def set_collectors(self, collectors: List[_StreamCollector]) -> None:
143 with self._lock:
144 self._collectors = list(collectors)
145
146 def live_snapshot(self, limit: int) -> List[Dict[str, Any]]:
147 with self._lock:
148 collectors = list(self._collectors)
149 streams = [snap for c in collectors if (snap := c.snapshot())]
150 return _merge_streams(streams, limit, deepcopy_posts=True)
151
152
153 _run_lock = threading.Lock()
154 _blocked_reason: Optional[str] = None
155 _failed_reason: Optional[str] = None
156 _run_results: Dict[tuple, List[Dict[str, Any]]] = {}
157 _run_inflight: Dict[tuple, _InflightSearch] = {}
158 _BLOCK_SIGNALS = ("HTTP 403: Blocked", "not a Reddit search results page")
159
160
161 def _log(msg: str) -> None:
162 sys.stderr.write(f"[RedditSearch] {msg}\n")
163 sys.stderr.flush()
164
165
166 def reset_run_state() -> None:
167 """Forget the block flag and shared results. Called once per command, and by tests."""
168 global _blocked_reason, _failed_reason
169 with _run_lock:
170 _blocked_reason = None
171 _failed_reason = None
172 _run_results.clear()
173 _run_inflight.clear()
174
175
176 def failed_reason() -> Optional[str]:
177 """Why site search found nothing this command, when Reddit refused it; else None."""
178 return _failed_reason
179
180
181 def _note_block(error: Optional[str]) -> None:
182 global _blocked_reason
183 if not error or not any(signal in error for signal in _BLOCK_SIGNALS):
184 return
185 reason = "HTTP 403: Blocked" if "403" in error else "challenge page instead of results"
186 with _run_lock:
187 first = _blocked_reason is None
188 if first:
189 _blocked_reason = reason
190 if first:
191 _log(f"site search is blocked for this network ({reason}); skipping the remaining searches")
192
193
194 def unrecognized_body(text: str) -> Optional[str]:
195 """Validator for the fetch hook: None for a search page, else a reason."""
196 if NO_RESULTS_MARKER in text:
197 return None
198 if RESULTS_MARKER in text:
199 # Marker kept but tracking context changed shape: a clean zero-result
200 # parse would hide the drift, so treat it as a lane failure.
201 if _post_units(text):
202 return None
203 return "Reddit search result units no longer parse"
204 return "not a Reddit search results page"
205
206
207 def search_url(
208 query: str,
209 time_filter: str = "month",
210 subreddit: Optional[str] = None,
211 cursor: Optional[str] = None,
212 kind: str = "posts",
213 sort: str = "relevance",
214 ) -> str:
215 """Build a deterministic search URL so concurrent streams share the memo.
216
217 ``kind`` is Reddit's result type: ``posts`` (the default), or
218 ``comments`` and ``communities`` for the logged-in session layer.
219 A communities search takes no time filter or sort. Reddit applies the
220 time filter to comment search only with ``sort=new``.
221 """
222 if subreddit:
223 sub = subreddit.strip().removeprefix("r/").strip("/")
224 path = f"/svc/shreddit/r/{quote(sub, safe='')}/search/"
225 else:
226 path = "/svc/shreddit/search/"
227 if kind == "communities":
228 params = [("q", query), ("type", kind)]
229 else:
230 params = [("q", query), ("type", kind), ("t", time_filter), ("sort", sort)]
231 if cursor:
232 params.append(("cursor", cursor))
233 return f"{BASE}{path}?{urlencode(params)}"
234
235
236 def _post_units(html_text: str) -> List[Tuple[int, Dict[str, Any]]]:
237 """(offset, tracking context) for each post-title tracker, in page order."""
238 units = []
239 for m in _TRACKER.finditer(html_text):
240 try:
241 ctx = json.loads(_html.unescape(m.group(1)))
242 except (ValueError, TypeError):
243 continue
244 if not isinstance(ctx, dict):
245 continue
246 action = ctx.get("action_info")
247 post = ctx.get("post")
248 # A field that is no longer an object is drift: skip the unit, and a
249 # page left with none is flagged by unrecognized_body.
250 if not isinstance(action, dict) or not isinstance(post, dict):
251 continue
252 if action.get("type") == "post" and post.get("id"):
253 units.append((m.start(), ctx))
254 return units
255
256
257 def _next_cursor(html_text: str) -> Optional[str]:
258 for m in _NEXT_PAGE.finditer(html_text):
259 query = urlsplit(_html.unescape(m.group(1))).query
260 cursor = (parse_qs(query).get("cursor") or [None])[0]
261 if cursor:
262 return cursor
263 return None
264
265
266 def next_cursor(html_text: str) -> Optional[str]:
267 """The next page's cursor in a search fragment, or None (no run state)."""
268 return _next_cursor(html_text)
269
270
271 def parse_page(html_text: str, query: str = "") -> Tuple[List[Dict[str, Any]], Optional[str]]:
272 """Parse one search fragment into (normalized posts, next-page cursor)."""
273 html_text = html_text or ""
274 units = _post_units(html_text)
275 posts: List[Dict[str, Any]] = []
276 seen: set = set()
277 for i, (start, ctx) in enumerate(units):
278 post_id = str(ctx["post"]["id"]).removeprefix("t3_")
279 if post_id in seen:
280 continue
281 seen.add(post_id)
282 end = units[i + 1][0] if i + 1 < len(units) else len(html_text)
283 chunk = html_text[start:end]
284
285 sub_ctx = ctx.get("subreddit")
286 subreddit = str(sub_ctx.get("name") or "") if isinstance(sub_ctx, dict) else ""
287 profile_ctx = ctx.get("profile")
288 raw_author = profile_ctx.get("name") if isinstance(profile_ctx, dict) else None
289 author = raw_author.strip() if isinstance(raw_author, str) else ""
290 title = str(ctx["post"].get("title") or "")
291 href_match = _TITLE_HREF.search(chunk)
292 href = _html.unescape((href_match.group(1) or href_match.group(2))) if href_match else ""
293 href = href.split("?", 1)[0]
294 if f"/comments/{post_id}/" in href and href.startswith("/r/"):
295 url = f"{BASE}{href}"
296 else:
297 url = f"{BASE}/r/{subreddit}/comments/{post_id}/"
298
299 ts_match = _TIMEAGO.search(chunk)
300 ts = ts_match.group(1) if ts_match else None
301 # First counter of each kind wins: this post's own counters precede any
302 # that belong to a skipped (malformed) neighbour sharing the chunk.
303 counts: Dict[str, int] = {}
304 for number, label in _COUNTER.findall(chunk):
305 counts.setdefault(label, int(number))
306 score, num_comments = counts.get("vote", 0), counts.get("comment", 0)
307
308 post_item: Dict[str, Any] = {
309 "id": "",
310 "title": title,
311 "url": url,
312 "score": score,
313 "num_comments": num_comments,
314 "subreddit": subreddit,
315 "created_utc": reddit_listing._to_epoch(ts),
316 "author": author,
317 "selftext": "",
318 "date": reddit_listing._to_date(ts),
319 "engagement": {
320 "score": score,
321 "num_comments": num_comments,
322 "upvote_ratio": None,
323 },
324 "relevance": round(token_overlap_relevance(query, title), 3) if query else 0.0,
325 "why_relevant": "Reddit search",
326 "metadata": {"post_id": post_id},
327 }
328 post_item["engagement_source"] = (
329 reddit_refs.LIVE if "vote" in counts else reddit_refs.UNKNOWN
330 )
331 posts.append(post_item)
332 return posts, _next_cursor(html_text)
333
334
335 def _fetch_page(
336 url: str, deadline: Optional[float] = None,
337 ) -> Tuple[Optional[str], Optional[str]]:
338 """(body, error). Shared limiter, run memo, one 429 retry, failure sink."""
339 req_timeout: float = SEARCH_TIMEOUT
340 if deadline is not None:
341 remaining = deadline - time.monotonic()
342 if remaining <= 0:
343 return None, "deadline exceeded"
344 req_timeout = min(float(SEARCH_TIMEOUT), remaining)
345 kwargs: Dict[str, Any] = {
346 "timeout": req_timeout,
347 "accept": "text/html",
348 "validate": unrecognized_body,
349 }
350 if deadline is not None:
351 kwargs["deadline_monotonic"] = deadline
352 try:
353 return http.reddit_keyless_get_text_retry_429(url, **kwargs)
354 except Exception as e: # defensive: one bad page must not sink the run
355 _log(f"search fetch failed for {url}: {e}")
356 return None, str(e)
357
358
359 def _search_stream(
360 query: str,
361 time_filter: str,
362 max_pages: int,
363 subreddit: Optional[str] = None,
364 deadline: Optional[float] = None,
365 collector: Optional[_StreamCollector] = None,
366 ) -> List[Dict[str, Any]]:
367 """Page one search sequentially. Keeps earlier pages when a later one fails."""
368 label = f"r/{subreddit}" if subreddit else "global"
369 posts: List[Dict[str, Any]] = []
370 seen_ids: set = set()
371 used_cursors: set = set()
372 cursor: Optional[str] = None
373 for page in range(1, max_pages + 1):
374 if _blocked_reason:
375 break
376 if deadline is not None and time.monotonic() >= deadline:
377 if collector is not None:
378 collector.mark_incomplete()
379 _log(f"{label} stopped before page {page}: deadline reached")
380 break
381 text, error = _fetch_page(
382 search_url(query, time_filter, subreddit, cursor),
383 deadline=deadline,
384 )
385 if text is None:
386 _log(f"{label} page {page} failed: {error or 'no response'}")
387 _note_block(error)
388 if collector is not None and not _blocked_reason:
389 collector.mark_incomplete()
390 break
391 page_posts, next_cursor = parse_page(text, query)
392 new = [p for p in page_posts if p["metadata"]["post_id"] not in seen_ids]
393 for p in new:
394 seen_ids.add(p["metadata"]["post_id"])
395 posts.extend(new)
396 if collector is not None:
397 collector.add(new)
398 if not new or not next_cursor or next_cursor in used_cursors:
399 break
400 used_cursors.add(next_cursor)
401 cursor = next_cursor
402 return posts
403
404
405 def _result_timeout(batch_size: int, pages: int = 1) -> float:
406 """Per-future wait: each sequential page's own timeout plus the bucket's queue."""
407 return pages * (SEARCH_TIMEOUT + 5) + http.reddit_keyless_wait_allowance(batch_size)
408
409
410 def _time_filter(from_date: Optional[str], to_date: Optional[str]) -> str:
411 # Same mapping as the ScrapeCreators path; falls back to "month".
412 from .reddit import _window_to_time_filter
413 return _window_to_time_filter(from_date or "", to_date or "")
414
415
416 def search(
417 query: str,
418 depth: str = "default",
419 subreddits: Optional[List[str]] = None,
420 from_date: Optional[str] = None,
421 to_date: Optional[str] = None,
422 deadline: Optional[float] = None,
423 ) -> List[Dict[str, Any]]:
424 """Discover Reddit posts for a query via the site search fragment.
425
426 ``deadline`` is a ``time.monotonic()`` bound: streams still running then
427 are left behind and the posts of the streams that answered are returned.
428
429 Runs a paged global search plus one page of per-subreddit search for each
430 targeted subreddit. Returns normalized, dated, scored posts, deduped by URL
431 and capped by depth. Streams are interleaved round-robin before the cap so
432 neither the targeted subreddits nor the global search crowds out the other. Returns ``[]`` on total failure and never raises; failures
433 land in the pipeline's failure sink. Callers of one command that ask for
434 the same search share one run of it.
435 """
436 try:
437 global_pages = GLOBAL_PAGE_CAPS.get(depth, GLOBAL_PAGE_CAPS["default"])
438 time_filter = _time_filter(from_date, to_date)
439 subs = []
440 for raw in subreddits or []:
441 sub = (raw or "").strip().removeprefix("r/").strip("/")
442 if sub and sub.lower() not in {s.lower() for s in subs}:
443 subs.append(sub)
444 limit = DEPTH_LIMITS.get(depth, DEPTH_LIMITS["default"])
445 key = (query, depth, time_filter, tuple(sub.lower() for sub in subs))
446 owner = False
447 slot: Optional[_InflightSearch] = None
448 partial_fallback: Optional[List[Dict[str, Any]]] = None
449 for _round in range(2):
450 with _run_lock:
451 if key in _run_results:
452 return copy.deepcopy(_run_results[key])
453 if deadline is not None and time.monotonic() >= deadline:
454 return copy.deepcopy(partial_fallback or [])
455 slot = _run_inflight.get(key)
456 owner = slot is None
457 if owner:
458 slot = _InflightSearch()
459 _run_inflight[key] = slot
460 if owner:
461 break
462 wait = _result_timeout(len(subs) + global_pages, global_pages)
463 if deadline is not None:
464 remaining = deadline - time.monotonic()
465 if remaining <= 0:
466 return copy.deepcopy(partial_fallback or [])
467 wait = min(wait, remaining)
468 slot.done.wait(timeout=wait)
469 if slot.partial:
470 partial_fallback = slot.partial
471 else:
472 live = slot.live_snapshot(limit)
473 if live:
474 partial_fallback = live
475 if deadline is not None and time.monotonic() >= deadline:
476 with _run_lock:
477 if key in _run_results:
478 return copy.deepcopy(_run_results[key])
479 return copy.deepcopy(partial_fallback or [])
480 else:
481 with _run_lock:
482 if key in _run_results:
483 return copy.deepcopy(_run_results[key])
484 return copy.deepcopy(partial_fallback or [])
485 try:
486 unique, complete = _search_uncached_with_status(
487 query, depth, subs, time_filter, global_pages, deadline, inflight=slot,
488 )
489 # Only cache complete non-empty runs or network-wide blocks;
490 # partial runs from a timeout stay uncached so later callers with
491 # more time can fetch all pages, while concurrent waiters can still
492 # fall back to the salvaged posts if they have no time left.
493 if (complete and unique) or (unique is not None and _blocked_reason):
494 with _run_lock:
495 _run_results[key] = unique
496 elif unique:
497 slot.partial = unique
498 return copy.deepcopy(unique if unique else (partial_fallback or []))
499 finally:
500 if owner:
501 with _run_lock:
502 if _run_inflight.get(key) is slot:
503 _run_inflight.pop(key, None)
504 if slot is not None:
505 slot.done.set()
506 except Exception as e: # defensive: discovery must never raise into the pipeline
507 _log(f"search failed: {e}")
508 return []
509
510
511 def _search_uncached_with_status(
512 query: str,
513 depth: str,
514 subs: List[str],
515 time_filter: str,
516 global_pages: int,
517 deadline: Optional[float] = None,
518 inflight: Optional[_InflightSearch] = None,
519 ) -> Tuple[Optional[List[Dict[str, Any]]], bool]:
520 """One run of the search streams: ``(posts_or_none, complete)``."""
521 global _failed_reason
522 try:
523 if deadline is not None and time.monotonic() >= deadline:
524 return [], False
525 limit = DEPTH_LIMITS.get(depth, DEPTH_LIMITS["default"])
526 jobs = [(sub, SUB_PAGE_CAP) for sub in subs] + [(None, global_pages)]
527 batch = sum(pages for _sub, pages in jobs)
528 streams: List[List[Dict[str, Any]]] = []
529 complete = True
530 executor = ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(jobs)))
531 try:
532 # submit_with_context, not executor.submit: a plain submit starts the
533 # worker with an empty context, dropping the pipeline's
534 # capture_failures() sink so a 429/403 or a challenge page is
535 # silently discarded (issue #899).
536 collectors = [_StreamCollector() for _ in jobs]
537 if inflight is not None:
538 inflight.set_collectors(collectors)
539 futures = [
540 (
541 http.submit_with_context(
542 executor, _search_stream, query, time_filter, pages, sub,
543 deadline=deadline, collector=collector,
544 ),
545 sub,
546 pages,
547 collector,
548 )
549 for (sub, pages), collector in zip(jobs, collectors)
550 ]
551 for future, sub, pages, collector in futures:
552 wait = _result_timeout(batch, pages)
553 if deadline is not None:
554 wait = max(0.0, min(wait, deadline - time.monotonic()))
555 try:
556 streams.append(future.result(timeout=wait))
557 if collector.incomplete:
558 complete = False
559 except (Exception, FuturesTimeoutError) as e:
560 complete = False
561 salvaged = collector.snapshot()
562 if salvaged:
563 streams.append(salvaged)
564 _log(
565 f"{'r/' + sub if sub else 'global'} search future failed: "
566 f"{e or 'still running at the deadline'}"
567 + (f" (kept {len(salvaged)} posts from earlier pages)" if salvaged else "")
568 )
569 finally:
570 # Under a deadline a stream still queued or running is not waited for.
571 executor.shutdown(wait=deadline is None, cancel_futures=deadline is not None)
572
573 unique = _merge_streams(streams, limit)
574 _log(f"{len(unique)} posts (t={time_filter}, {len(subs)} targeted subs)")
575 if not unique and _blocked_reason:
576 _failed_reason = _blocked_reason
577 return unique, complete
578 except Exception as e: # defensive: discovery must never raise into the pipeline
579 _log(f"search failed: {e}")
580 return None, False
581
582
583 def _search_uncached(
584 query: str,
585 depth: str,
586 subs: List[str],
587 time_filter: str,
588 global_pages: int,
589 deadline: Optional[float] = None,
590 ) -> Optional[List[Dict[str, Any]]]:
591 """One run of the search streams; None when it raised."""
592 unique, _complete = _search_uncached_with_status(
593 query, depth, subs, time_filter, global_pages, deadline,
594 )
595 return unique
596
596 lines PYTHON