| 1 | """Keyless Reddit listing scrape via shreddit /svc partials — with real scores. |
| 2 | |
| 3 | The subreddit listing partial |
| 4 | ``/svc/shreddit/community-more-posts/{sort}/?name={sub}[&t={range}]`` serves |
| 5 | HTTP 200 with no API key and **server-renders each post's upvote score**, which |
| 6 | the comments endpoint does not provide. Each post is a |
| 7 | ``<shreddit-post>`` element whose start-tag attributes carry ``score``, |
| 8 | ``comment-count``, ``post-title``, ``permalink``, ``author``, ``subreddit-name`` |
| 9 | and ``created-timestamp``. |
| 10 | |
| 11 | This is the keyless source of post-level upvotes. It works for normal users on |
| 12 | ordinary connections (verified), so reddit_keyless uses it both as a scored |
| 13 | discovery source and to backfill scores onto posts discovered elsewhere. |
| 14 | """ |
| 15 | |
| 16 | import html as _html |
| 17 | import re |
| 18 | import time |
| 19 | import sys |
| 20 | from datetime import datetime, timezone |
| 21 | from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError |
| 22 | from typing import Any, Dict, List, Optional, Set |
| 23 | from urllib.parse import quote, urlencode |
| 24 | |
| 25 | from . import http, reddit_refs |
| 26 | from .relevance import token_overlap_relevance, tokenize |
| 27 | |
| 28 | # Generic domain terms that are excluded from the keyword gate — matches |
| 29 | # pipeline._DISCOVERY_GENERIC_DOMAIN_TERMS (duplicated to avoid circular import). |
| 30 | _DISCOVERY_GENERIC_DOMAIN_TERMS: Set[str] = { |
| 31 | "ai", "artificial", "intelligence", "tech", "technology", "trending", "trend", |
| 32 | } |
| 33 | |
| 34 | # Listing sorts pulled per subreddit, by depth. |
| 35 | LISTING_SORTS = { |
| 36 | "quick": ["top"], |
| 37 | "default": ["top", "hot"], |
| 38 | "deep": ["top", "hot", "new"], |
| 39 | } |
| 40 | DEPTH_LIMITS = {"quick": 10, "default": 25, "deep": 50} |
| 41 | TIMEFRAME = "month" |
| 42 | MAX_WORKERS = 4 |
| 43 | LISTING_TIMEOUT = 15 |
| 44 | |
| 45 | _TAG_BODY = r'(?:"[^"]*"|\'[^\']*\'|[^>"\'])*' |
| 46 | _POST_CARD = re.compile(rf"<shreddit-post(?=[\s>]){_TAG_BODY}>", re.IGNORECASE) |
| 47 | _TAG_HEAD = re.compile(r"^<\s*[^\s>/]+") |
| 48 | _TAG_ATTR = re.compile( |
| 49 | r'(?<![A-Za-z0-9_.:-])([A-Za-z_:][A-Za-z0-9_.:-]*)' |
| 50 | r'(?:\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s"\'=<>`]+)))?' |
| 51 | ) |
| 52 | _BLOCK_MARKERS = ( |
| 53 | "verify you are human", |
| 54 | "confirm you are a human", |
| 55 | "just a moment", |
| 56 | "attention required", |
| 57 | "cf-browser-verification", |
| 58 | "challenge-platform", |
| 59 | "/svc/shreddit/js-challenge", |
| 60 | "please wait for verification", |
| 61 | "enable javascript and reload", |
| 62 | "you've been blocked", |
| 63 | "whoa there", |
| 64 | ) |
| 65 | |
| 66 | |
| 67 | def _log(msg: str) -> None: |
| 68 | sys.stderr.write(f"[RedditListing] {msg}\n") |
| 69 | sys.stderr.flush() |
| 70 | |
| 71 | |
| 72 | def _matches_discovery_domain(domain: str, text: str) -> bool: |
| 73 | """Require a distinctive domain term, not a generic token such as ``AI``. |
| 74 | |
| 75 | Duplicated from pipeline._matches_discovery_domain to avoid circular imports. |
| 76 | The rule must stay in sync: pipeline.py owns the authoritative version and |
| 77 | test_reddit_listing.py verifies parity. |
| 78 | """ |
| 79 | def terms(value: str) -> Set[str]: |
| 80 | words: Set[str] = set() |
| 81 | for word in tokenize(value): |
| 82 | words.add(word) |
| 83 | if len(word) > 4 and word.endswith("s") and not word.endswith("ss"): |
| 84 | words.add(word[:-1]) |
| 85 | return words |
| 86 | |
| 87 | domain_terms = terms(domain) |
| 88 | anchors = domain_terms - _DISCOVERY_GENERIC_DOMAIN_TERMS |
| 89 | return bool((anchors or domain_terms) & terms(text)) |
| 90 | |
| 91 | |
| 92 | def _attr(tag: str, name: str) -> Optional[str]: |
| 93 | if not tag or not name: |
| 94 | return None |
| 95 | wanted = name.lower() |
| 96 | body = _TAG_HEAD.sub("", tag.strip()) |
| 97 | if body.endswith(">"): |
| 98 | body = body[:-1].rstrip() |
| 99 | if body.endswith("/"): |
| 100 | body = body[:-1] |
| 101 | for m in _TAG_ATTR.finditer(body): |
| 102 | if m.group(1).lower() != wanted: |
| 103 | continue |
| 104 | raw = ( |
| 105 | m.group(2) |
| 106 | if m.group(2) is not None |
| 107 | else (m.group(3) if m.group(3) is not None else m.group(4)) |
| 108 | ) |
| 109 | if raw is not None: |
| 110 | return _html.unescape(raw) |
| 111 | return None |
| 112 | |
| 113 | |
| 114 | def _to_date(value: Optional[str]) -> Optional[str]: |
| 115 | if not value: |
| 116 | return None |
| 117 | try: |
| 118 | return datetime.fromisoformat(value.strip()).date().isoformat() |
| 119 | except (ValueError, TypeError): |
| 120 | return None |
| 121 | |
| 122 | |
| 123 | def _to_epoch(value: Optional[str]) -> Optional[float]: |
| 124 | if not value: |
| 125 | return None |
| 126 | try: |
| 127 | dt = datetime.fromisoformat(value.strip()) |
| 128 | if dt.tzinfo is None: |
| 129 | dt = dt.replace(tzinfo=timezone.utc) |
| 130 | return dt.timestamp() |
| 131 | except (ValueError, TypeError): |
| 132 | return None |
| 133 | |
| 134 | |
| 135 | def _post_id(permalink: str) -> str: |
| 136 | m = re.search(r"/comments/([A-Za-z0-9]+)", permalink or "") |
| 137 | return m.group(1) if m else "" |
| 138 | |
| 139 | |
| 140 | _ERROR_PATTERN = re.compile(r"^r/(\S+)\s+(\S+):", re.IGNORECASE) |
| 141 | |
| 142 | |
| 143 | def _shreddit_error_recovered(error: str, successes: Set[tuple[str, str]]) -> bool: |
| 144 | """Return True if the error's (sub, sort) pair is in the successes set. |
| 145 | |
| 146 | Error format: "r/{sub} {sort}: {message}". |
| 147 | """ |
| 148 | m = _ERROR_PATTERN.match(error) |
| 149 | if not m: |
| 150 | return False |
| 151 | sub, sort = m.group(1).lower(), m.group(2).lower() |
| 152 | return (sub, sort) in successes |
| 153 | |
| 154 | |
| 155 | def parse_cards(html_text: str, query: str = "") -> List[Dict[str, Any]]: |
| 156 | """Parse <shreddit-post> cards into normalized post dicts with real scores.""" |
| 157 | posts: List[Dict[str, Any]] = [] |
| 158 | for m in _POST_CARD.finditer(html_text or ""): |
| 159 | tag = m.group(0) |
| 160 | permalink = _attr(tag, "permalink") or "" |
| 161 | if "/comments/" not in permalink: |
| 162 | continue |
| 163 | score_raw = _attr(tag, "score") |
| 164 | has_live_score = False |
| 165 | try: |
| 166 | score = int(score_raw or 0) |
| 167 | has_live_score = score_raw is not None and score_raw.strip() != "" |
| 168 | except ValueError: |
| 169 | score = 0 |
| 170 | try: |
| 171 | num_comments = int(_attr(tag, "comment-count") or 0) |
| 172 | except ValueError: |
| 173 | num_comments = 0 |
| 174 | title = _attr(tag, "post-title") or "" |
| 175 | author = _attr(tag, "author") or "[deleted]" |
| 176 | subreddit = _attr(tag, "subreddit-name") or "" |
| 177 | created = _attr(tag, "created-timestamp") |
| 178 | url = f"https://www.reddit.com{permalink}" |
| 179 | |
| 180 | card: Dict[str, Any] = { |
| 181 | "id": "", |
| 182 | "title": title, |
| 183 | "url": url, |
| 184 | "score": score, |
| 185 | "num_comments": num_comments, |
| 186 | "subreddit": subreddit, |
| 187 | "created_utc": _to_epoch(created), |
| 188 | "author": author if author not in ("[deleted]", "[removed]") else "[deleted]", |
| 189 | "selftext": "", |
| 190 | "date": _to_date(created), |
| 191 | "engagement": { |
| 192 | "score": score, |
| 193 | "num_comments": num_comments, |
| 194 | "upvote_ratio": None, |
| 195 | }, |
| 196 | "relevance": round(token_overlap_relevance(query, title), 3) if query else 0.0, |
| 197 | "why_relevant": "Reddit listing", |
| 198 | "metadata": {"post_id": _post_id(permalink)}, |
| 199 | } |
| 200 | card["engagement_source"] = ( |
| 201 | reddit_refs.LIVE if has_live_score else reddit_refs.UNKNOWN |
| 202 | ) |
| 203 | posts.append(card) |
| 204 | return posts |
| 205 | |
| 206 | |
| 207 | _VALID_SORTS = frozenset({"top", "hot", "new", "rising", "controversial", "best"}) |
| 208 | _VALID_TIMEFRAMES = frozenset({"hour", "day", "week", "month", "year", "all"}) |
| 209 | |
| 210 | |
| 211 | def _valid_subreddits(subreddits: List[str]) -> List[str]: |
| 212 | valid: List[str] = [] |
| 213 | seen: Set[str] = set() |
| 214 | for raw in subreddits or []: |
| 215 | sub = reddit_refs.normalize_subreddit(raw, allow_all=True) |
| 216 | if sub and sub.lower() not in seen: |
| 217 | seen.add(sub.lower()) |
| 218 | valid.append(sub) |
| 219 | return valid |
| 220 | |
| 221 | |
| 222 | def _listing_url(subreddit: str, sort: str, timeframe: str = TIMEFRAME) -> str: |
| 223 | sub = reddit_refs.normalize_subreddit(subreddit, allow_all=True) |
| 224 | if not sub: |
| 225 | raise ValueError(f"Invalid subreddit for listing URL: {subreddit!r}") |
| 226 | clean_sort = str(sort or "").strip().lower() |
| 227 | if clean_sort not in _VALID_SORTS: |
| 228 | raise ValueError(f"Invalid sort for listing URL: {sort!r}") |
| 229 | clean_tf = str(timeframe or TIMEFRAME).strip().lower() |
| 230 | if clean_sort == "top" and clean_tf not in _VALID_TIMEFRAMES: |
| 231 | raise ValueError(f"Invalid timeframe for listing URL: {timeframe!r}") |
| 232 | if sub.lower() == "all": |
| 233 | url = f"https://www.reddit.com/r/all/{quote(clean_sort, safe='')}/" |
| 234 | if clean_sort == "top": |
| 235 | url += f"?{urlencode({'t': clean_tf})}" |
| 236 | return url |
| 237 | params = [("name", sub)] |
| 238 | if clean_sort == "top": |
| 239 | params.append(("t", clean_tf)) |
| 240 | return ( |
| 241 | f"https://www.reddit.com/svc/shreddit/community-more-posts/" |
| 242 | f"{quote(clean_sort, safe='')}/?{urlencode(params)}" |
| 243 | ) |
| 244 | |
| 245 | |
| 246 | def _listing_body_problem(subreddit: str, body: str) -> Optional[str]: |
| 247 | lower = body.lower() |
| 248 | is_blocked = any(marker in lower for marker in _BLOCK_MARKERS) |
| 249 | is_all = (reddit_refs.normalize_subreddit(subreddit, allow_all=True) or "").lower() == "all" |
| 250 | if not is_all and not is_blocked: |
| 251 | return None |
| 252 | if parse_cards(body): |
| 253 | return None |
| 254 | if is_blocked: |
| 255 | return "Reddit listing interstitial: HTTP 2xx with no post cards" |
| 256 | return "Reddit r/all listing schema drift: HTTP 2xx with no post cards" |
| 257 | |
| 258 | |
| 259 | def _fetch_one( |
| 260 | subreddit: str, |
| 261 | sort: str, |
| 262 | query: str, |
| 263 | timeframe: str = TIMEFRAME, |
| 264 | ) -> List[Dict[str, Any]]: |
| 265 | items, _ = _fetch_one_with_status(subreddit, sort, query, timeframe) |
| 266 | return items |
| 267 | |
| 268 | |
| 269 | def _fetch_one_with_status( |
| 270 | subreddit: str, |
| 271 | sort: str, |
| 272 | query: str, |
| 273 | timeframe: str = TIMEFRAME, |
| 274 | ) -> tuple[List[Dict[str, Any]], Optional[str]]: |
| 275 | try: |
| 276 | # retry_429 records a terminal miss into the pipeline sink (issue #899) |
| 277 | # and retries a 429 once through the limiter (issue #985). Empty |
| 278 | # dedicated-subreddit fragments can be valid; r/all cannot be empty. |
| 279 | with http.tee_failures() as local_failures: |
| 280 | text, error = http.reddit_keyless_get_text_retry_429( |
| 281 | _listing_url(subreddit, sort, timeframe), |
| 282 | timeout=LISTING_TIMEOUT, |
| 283 | accept="text/html", |
| 284 | validate=lambda body: _listing_body_problem(subreddit, body), |
| 285 | ) |
| 286 | if text is None: |
| 287 | if not local_failures: |
| 288 | http._record_failure(http.HTTPError(error or "no response")) |
| 289 | return [], (error or "no response") |
| 290 | return parse_cards(text, query), None |
| 291 | except Exception as e: |
| 292 | http._record_failure(e if isinstance(e, http.HTTPError) else http.HTTPError(str(e))) |
| 293 | _log(f"listing fetch failed r/{subreddit} {sort}: {e}") |
| 294 | return [], str(e) |
| 295 | |
| 296 | |
| 297 | def _result_timeout(batch_size: int) -> float: |
| 298 | """Per-future wait: the fetch's own timeout plus the bucket's queue depth.""" |
| 299 | return LISTING_TIMEOUT + 5 + http.reddit_keyless_wait_allowance(batch_size) |
| 300 | |
| 301 | |
| 302 | def fetch_listings( |
| 303 | subreddits: List[str], |
| 304 | depth: str = "default", |
| 305 | query: str = "", |
| 306 | sorts: Optional[List[str]] = None, |
| 307 | timeframe: str = TIMEFRAME, |
| 308 | deadline: Optional[float] = None, |
| 309 | ) -> List[Dict[str, Any]]: |
| 310 | """Fetch scored post cards across subreddits × sorts. |
| 311 | |
| 312 | ``deadline`` is a ``time.monotonic()`` bound: feeds still running then are |
| 313 | left behind and the cards of the feeds that answered are returned. |
| 314 | |
| 315 | Returns deduped normalized posts (with real scores), unranked/unsliced — |
| 316 | the caller merges these with other sources, ranks, and slices. |
| 317 | |
| 318 | ``sorts`` overrides the depth-derived sort set. Dedicated-subreddit lanes |
| 319 | pass ``["top", "hot", "new"]`` so fresh threads (which the top-of-month |
| 320 | listing misses) are caught with their scores regardless of depth. |
| 321 | """ |
| 322 | valid_subs = _valid_subreddits(subreddits) |
| 323 | if not valid_subs: |
| 324 | return [] |
| 325 | sorts = sorts or LISTING_SORTS.get(depth, LISTING_SORTS["default"]) |
| 326 | jobs = [(sub, sort) for sub in valid_subs for sort in sorts] |
| 327 | all_posts: List[Dict[str, Any]] = [] |
| 328 | executor = ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(jobs)) or 1) |
| 329 | try: |
| 330 | # submit_with_context, not executor.submit — see the note in |
| 331 | # fetch_discovery_listings below (issue #899). |
| 332 | futures = {http.submit_with_context(executor, _fetch_one, sub, sort, query, timeframe): (sub, sort) |
| 333 | for sub, sort in jobs} |
| 334 | for future in futures: |
| 335 | wait = _result_timeout(len(jobs)) |
| 336 | if deadline is not None: |
| 337 | wait = max(0.0, min(wait, deadline - time.monotonic())) |
| 338 | try: |
| 339 | all_posts.extend(future.result(timeout=wait)) |
| 340 | except FuturesTimeoutError as e: |
| 341 | http._record_failure(http.DeadlineExceeded()) |
| 342 | _log(f"listing future failed: {e or 'still running at the deadline'}") |
| 343 | except Exception as e: |
| 344 | http._record_failure(e if isinstance(e, http.HTTPError) else http.HTTPError(str(e))) |
| 345 | _log(f"listing future failed: {e or 'still running at the deadline'}") |
| 346 | finally: |
| 347 | # Under a deadline a feed still queued or running is not waited for. |
| 348 | executor.shutdown(wait=deadline is None, cancel_futures=deadline is not None) |
| 349 | |
| 350 | seen: set = set() |
| 351 | unique: List[Dict[str, Any]] = [] |
| 352 | for p in all_posts: |
| 353 | if p["url"] not in seen: |
| 354 | seen.add(p["url"]) |
| 355 | unique.append(p) |
| 356 | return unique |
| 357 | |
| 358 | |
| 359 | def fetch_discovery_listings( |
| 360 | subreddits: List[str], |
| 361 | *, |
| 362 | query: str, |
| 363 | depth: str = "default", |
| 364 | ) -> Dict[str, Any]: |
| 365 | """Fetch rising/top-week listings while preserving per-feed failures. |
| 366 | |
| 367 | When shreddit fails and arctic-shift recovers, errors are cleared only for |
| 368 | subreddits whose posts survive the keyword gate. If query is empty (global |
| 369 | ``--discover`` with no domain), the gate is skipped and any arctic result |
| 370 | counts as recovery. |
| 371 | """ |
| 372 | valid_subs = _valid_subreddits(subreddits) |
| 373 | if not valid_subs: |
| 374 | return {"items": [], "errors": []} |
| 375 | jobs = [(subreddit, sort) for subreddit in valid_subs for sort in ("rising", "top")] |
| 376 | items: List[Dict[str, Any]] = [] |
| 377 | errors: List[str] = [] |
| 378 | # Track which (sub, sort) pairs shreddit successfully delivered posts for. |
| 379 | # Used to decide which errors to clear — Arctic can supplement but cannot |
| 380 | # "recover" a failed hot/top/new/rising lane (it's recency-only). |
| 381 | shreddit_successes: Set[tuple[str, str]] = set() |
| 382 | with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(jobs)) or 1) as executor: |
| 383 | # submit_with_context, not executor.submit: a plain submit starts the |
| 384 | # worker with an empty context, dropping the pipeline's |
| 385 | # capture_failures() sink so a listing's 429/403 is silently discarded |
| 386 | # and the source reports a clean no-results (issue #899). |
| 387 | futures = { |
| 388 | http.submit_with_context( |
| 389 | executor, _fetch_one_with_status, subreddit, sort, query, "week" |
| 390 | ): (subreddit, sort) |
| 391 | for subreddit, sort in jobs |
| 392 | } |
| 393 | for future, (subreddit, sort) in futures.items(): |
| 394 | try: |
| 395 | fetched, error = future.result(timeout=_result_timeout(len(jobs))) |
| 396 | except (Exception, FuturesTimeoutError) as exc: |
| 397 | errors.append(f"r/{subreddit} {sort}: {exc}") |
| 398 | continue |
| 399 | items.extend(fetched) |
| 400 | if error: |
| 401 | errors.append(f"r/{subreddit} {sort}: {error}") |
| 402 | elif fetched: |
| 403 | # Shreddit succeeded for this (sub, sort) lane. |
| 404 | shreddit_successes.add((subreddit.lower(), sort.lower())) |
| 405 | |
| 406 | seen: set[str] = set() |
| 407 | unique = [] |
| 408 | for item in items: |
| 409 | if item["url"] in seen: |
| 410 | continue |
| 411 | seen.add(item["url"]) |
| 412 | unique.append(item) |
| 413 | |
| 414 | # Supplement with arctic-shift for all requested subreddits. Shreddit's |
| 415 | # per-sort success/failure is opaque (individual rising/top lanes can fail |
| 416 | # while others succeed), so arctic provides coverage for any failed lanes. |
| 417 | # Deduplication ensures no redundant posts when shreddit fully succeeded. |
| 418 | from . import reddit_arctic |
| 419 | arctic_items = reddit_arctic.fetch_listings( |
| 420 | valid_subs, depth=depth, query=query, sorts=("rising", "top") |
| 421 | ) |
| 422 | if arctic_items: |
| 423 | _log(f"discovery arctic supplement: {len(arctic_items)} posts") |
| 424 | # Apply the same keyword gate that pipeline._fetch_discovery_source |
| 425 | # uses downstream. When query is empty (global --discover), skip the |
| 426 | # gate — there's no keyword to match, and the river feed IS the signal. |
| 427 | if query: |
| 428 | arctic_items = [ |
| 429 | item for item in arctic_items |
| 430 | if _matches_discovery_domain( |
| 431 | query, |
| 432 | f"{item.get('title') or ''} {item.get('selftext') or ''}", |
| 433 | ) |
| 434 | ] |
| 435 | # Merge arctic items into unique list, deduping by URL. |
| 436 | added = 0 |
| 437 | for item in arctic_items: |
| 438 | if item["url"] not in seen: |
| 439 | seen.add(item["url"]) |
| 440 | unique.append(item) |
| 441 | added += 1 |
| 442 | if added: |
| 443 | _log(f"discovery arctic supplement added {added} new posts") |
| 444 | |
| 445 | # Clear errors only for (sub, sort) pairs where shreddit succeeded. |
| 446 | # Arctic supplements recency posts but cannot "recover" a failed hot/top/ |
| 447 | # rising lane — it has no sort lanes. Errors for failed shreddit lanes are |
| 448 | # preserved even when another sort for the same subreddit succeeded. |
| 449 | if errors and shreddit_successes: |
| 450 | errors = [ |
| 451 | e for e in errors |
| 452 | if not _shreddit_error_recovered(e, shreddit_successes) |
| 453 | ] |
| 454 | return {"items": unique, "errors": errors} |
| 455 | |
| 456 | |
| 457 | def score_index(subreddits: List[str], depth: str = "default") -> Dict[str, Dict[str, int]]: |
| 458 | """Build a {post_id: {score, num_comments}} map from subreddit listings. |
| 459 | |
| 460 | Used to backfill real scores onto posts discovered by a lane that carries |
| 461 | no engagement numbers. |
| 462 | """ |
| 463 | index: Dict[str, Dict[str, int]] = {} |
| 464 | for p in fetch_listings(subreddits, depth=depth): |
| 465 | pid = p.get("metadata", {}).get("post_id") or _post_id(p["url"]) |
| 466 | if pid: |
| 467 | index[pid] = {"score": p["score"], "num_comments": p["num_comments"]} |
| 468 | return index |
| 469 |