| 1 | """Keyless Reddit comment enrichment via shreddit /svc endpoints. |
| 2 | |
| 3 | Reddit's ``{thread}.json`` endpoint now returns HTTP 403. The shreddit partial |
| 4 | endpoint ``/svc/shreddit/comments/r/{sub}/t3_{id}`` still serves HTTP 200 HTML |
| 5 | with no API key, embedding each comment as a ``<shreddit-comment>`` custom |
| 6 | element whose start-tag attributes carry ``score`` / ``author`` / ``created`` / |
| 7 | ``permalink``, and whose body lives in a ``<div id="{thingId}-post-rtjson-content">`` |
| 8 | block. This module parses that markup into top comments, matching the |
| 9 | ``top_comments`` / ``comment_insights`` shape produced by ``reddit_enrich`` so |
| 10 | the renderer is unaffected. |
| 11 | |
| 12 | Limitation: the comments endpoint carries the real comment count |
| 13 | (``total-comments``) but not the post's upvote score, so post-level ``score`` |
| 14 | cannot be recovered keylessly here (ScrapeCreators backup still provides it). |
| 15 | """ |
| 16 | |
| 17 | import html as _html |
| 18 | import re |
| 19 | import sys |
| 20 | import time |
| 21 | from datetime import datetime |
| 22 | from typing import Any, Dict, List, Optional |
| 23 | from urllib.parse import quote, urlencode |
| 24 | |
| 25 | from . import http |
| 26 | from . import reddit_arctic |
| 27 | from . import reddit_enrich |
| 28 | from . import reddit_refs |
| 29 | from . import snippet |
| 30 | |
| 31 | # Up to N posts enriched per subquery, by depth. Raised from 3/5/8 once the |
| 32 | # per-command memo (http.reddit_keyless_get_text) collapsed repeat shreddit |
| 33 | # fetches across subqueries and the 1 req/s bucket stopped the 429s: eight |
| 34 | # fetches fit inside ENRICH_BUDGET at four workers, and the comments are the |
| 35 | # lane's headline value. |
| 36 | ENRICH_LIMITS = { |
| 37 | "quick": 4, |
| 38 | "default": 8, |
| 39 | "deep": 12, |
| 40 | } |
| 41 | |
| 42 | # Max comments returned per post (independent of how many posts get enriched). |
| 43 | # Twelve so a thousand-comment thread feeds more than ten candidates into the |
| 44 | # cross-platform Top Community Comments block. |
| 45 | MAX_COMMENTS = 12 |
| 46 | |
| 47 | SVC_TIMEOUT = 12 |
| 48 | |
| 49 | # Known bots whose comments carry no community signal. |
| 50 | BOT_AUTHORS = frozenset({ |
| 51 | "automoderator", |
| 52 | "remindmebot", |
| 53 | "repostsleuthbot", |
| 54 | "sneakpeekbot", |
| 55 | "savevideo", |
| 56 | "videodownloadbot", |
| 57 | "totesmessenger", |
| 58 | "b0trank", |
| 59 | "amputatorbot", |
| 60 | "stabbot", |
| 61 | "gifreversingbot", |
| 62 | "haikubotinaction", |
| 63 | "imagesofnetwork", |
| 64 | "botdefense", |
| 65 | }) |
| 66 | |
| 67 | _BOT_SUFFIXES = ("-bot", "_bot") |
| 68 | |
| 69 | # CamelCase catches WikiTextBot without swallowing names such as Talbot. |
| 70 | _CAMEL_BOT = re.compile(r"[a-z0-9]Bot\d*$") |
| 71 | |
| 72 | # Match the exact <shreddit-comment> element start tag, not <shreddit-comment-tree> |
| 73 | # or <shreddit-comment-tree-stats> (lookahead requires whitespace or '>'). |
| 74 | _TAG_BODY = r'(?:"[^"]*"|\'[^\']*\'|[^>"\'])*' |
| 75 | _COMMENT_START = re.compile(rf"<shreddit-comment(?=[\s>]){_TAG_BODY}>", re.IGNORECASE) |
| 76 | _TOTAL_COMMENTS = re.compile(r'(?<![A-Za-z0-9_.:-])total-comments="(\d+)"', re.IGNORECASE) |
| 77 | _PARA = re.compile(rf"<p(?=[\s>]){_TAG_BODY}(?<!/)>(.*?)</p\s*>", re.S | re.IGNORECASE) |
| 78 | _TAG = re.compile(r'<(?:"[^"]*"|\'[^\']*\'|[^>"\'])+>') |
| 79 | _WS = re.compile(r"\s+") |
| 80 | _NEXT_RTJSON = re.compile( |
| 81 | r'(?<![A-Za-z0-9_.:-])id\s*=\s*(?:"([A-Za-z0-9_]+)-(?:comment|post)-rtjson-content"' |
| 82 | r"|\'([A-Za-z0-9_]+)-(?:comment|post)-rtjson-content\')", |
| 83 | re.IGNORECASE, |
| 84 | ) |
| 85 | _DIV_OPEN = re.compile(rf"<div(?=[\s>]){_TAG_BODY}>", re.IGNORECASE) |
| 86 | _BODY_BOUNDARY = re.compile( |
| 87 | rf"<div(?=[\s>/]){_TAG_BODY}>" |
| 88 | r"|</div\s*>" |
| 89 | r"|<shreddit-comment(?=[\s>])" |
| 90 | r"|</shreddit-comment\s*>", |
| 91 | re.IGNORECASE, |
| 92 | ) |
| 93 | _CHALLENGE_MARKERS = re.compile( |
| 94 | r"js-challenge|challenge-form|please wait for verification|" |
| 95 | r"checking that your connection is secure|blocked by network security|" |
| 96 | r"whoa there, pardner|captcha", |
| 97 | re.IGNORECASE, |
| 98 | ) |
| 99 | _OP_ATTR_NAMES = ("is-op", "is-submitter", "is_op", "is_submitter") |
| 100 | _TAG_HEAD = re.compile(r"^<\s*[^\s>/]+") |
| 101 | _TAG_ATTR = re.compile( |
| 102 | r'(?<![A-Za-z0-9_.:-])([A-Za-z_:][A-Za-z0-9_.:-]*)' |
| 103 | r'(?:\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s"\'=<>`]+)))?' |
| 104 | ) |
| 105 | |
| 106 | |
| 107 | def _log(msg: str) -> None: |
| 108 | sys.stderr.write(f"[RedditShreddit] {msg}\n") |
| 109 | sys.stderr.flush() |
| 110 | |
| 111 | |
| 112 | def unrecognized_comments_body(text: str) -> Optional[str]: |
| 113 | """Validator for shreddit comment fetches: None if recognized, else a reason.""" |
| 114 | if not text or not text.strip(): |
| 115 | return "empty shreddit comments response" |
| 116 | if _COMMENT_START.search(text) or _TOTAL_COMMENTS.search(text): |
| 117 | return None |
| 118 | if "<shreddit-comment-tree" in text.lower(): |
| 119 | return None |
| 120 | if _CHALLENGE_MARKERS.search(text): |
| 121 | return "challenge page instead of Reddit comments" |
| 122 | return "not a Reddit shreddit comments page" |
| 123 | |
| 124 | |
| 125 | def extract_post_ref(url: str) -> Optional[tuple]: |
| 126 | """Return (subreddit, post_id) from a Reddit thread URL, or None. |
| 127 | |
| 128 | ``subreddit`` is ``""`` for valid subreddit-less canonical URLs |
| 129 | (``/comments/{id}/`` or ``redd.it/{id}``) so callers can still fall back |
| 130 | to the archive by ``post_id``. |
| 131 | """ |
| 132 | ref = reddit_refs.canonical_thread_url(url) |
| 133 | if ref is None: |
| 134 | return None |
| 135 | return ref.subreddit, ref.post_id |
| 136 | |
| 137 | |
| 138 | def _svc_url(subreddit: str, post_id: str) -> str: |
| 139 | # sort=top guarantees Reddit front-loads the highest-scored comments on the |
| 140 | # first page, so the true top comments are captured even on huge threads |
| 141 | # (we still re-sort by score locally as a backstop). |
| 142 | sub = reddit_refs.normalize_subreddit(subreddit, allow_all=True) |
| 143 | pid = reddit_refs.normalize_post_id(post_id) |
| 144 | if not sub or not pid: |
| 145 | raise ValueError(f"Invalid Reddit post reference: subreddit={subreddit!r}, post_id={post_id!r}") |
| 146 | query = urlencode({"sort": "top"}) |
| 147 | return ( |
| 148 | f"https://www.reddit.com/svc/shreddit/comments/r/{quote(sub, safe='')}/t3_{quote(pid, safe='')}" |
| 149 | f"?{query}" |
| 150 | ) |
| 151 | |
| 152 | |
| 153 | def _attr(tag: str, name: str) -> str: |
| 154 | # HTML attribute names are case-insensitive: the server partial emits |
| 155 | # ``thingId``, a DOM round-trip serializes it as ``thingid``. Match the exact |
| 156 | # attribute name (not hyphenated suffixes such as ``data-author`` or |
| 157 | # ``hide-score``) either way; the value keeps its case. |
| 158 | if not tag or not name: |
| 159 | return "" |
| 160 | wanted = name.lower() |
| 161 | body = _TAG_HEAD.sub("", tag.strip()) |
| 162 | if body.endswith(">"): |
| 163 | body = body[:-1].rstrip() |
| 164 | if body.endswith("/"): |
| 165 | body = body[:-1] |
| 166 | for m in _TAG_ATTR.finditer(body): |
| 167 | if m.group(1).lower() != wanted: |
| 168 | continue |
| 169 | raw = ( |
| 170 | m.group(2) |
| 171 | if m.group(2) is not None |
| 172 | else (m.group(3) if m.group(3) is not None else m.group(4)) |
| 173 | ) |
| 174 | if raw is not None: |
| 175 | return _html.unescape(raw) |
| 176 | return "" |
| 177 | |
| 178 | |
| 179 | def _bool_attr(tag: str, names: tuple[str, ...]) -> Optional[bool]: |
| 180 | """Read an explicit HTML boolean/valued flag from a start tag, or None if absent.""" |
| 181 | wanted = {n.lower() for n in names} |
| 182 | body = _TAG_HEAD.sub("", tag.strip()).rstrip(">/ \t\r\n") |
| 183 | for m in _TAG_ATTR.finditer(body): |
| 184 | if m.group(1).lower() not in wanted: |
| 185 | continue |
| 186 | raw = m.group(2) if m.group(2) is not None else ( |
| 187 | m.group(3) if m.group(3) is not None else m.group(4) |
| 188 | ) |
| 189 | if raw is None or raw.strip() == "": |
| 190 | return True |
| 191 | lowered = raw.strip().lower() |
| 192 | if lowered in ("true", "1", "yes"): |
| 193 | return True |
| 194 | if lowered in ("false", "0", "no"): |
| 195 | return False |
| 196 | return None |
| 197 | |
| 198 | |
| 199 | def _iso_to_date(value: str) -> Optional[str]: |
| 200 | if not value: |
| 201 | return None |
| 202 | try: |
| 203 | return datetime.fromisoformat(value.strip()).date().isoformat() |
| 204 | except (ValueError, TypeError): |
| 205 | return None |
| 206 | |
| 207 | |
| 208 | def _index_body_divs(html_text: str) -> Dict[str, int]: |
| 209 | """Index opening body ``<div>`` end offsets by lowercased thingId in one pass. |
| 210 | |
| 211 | Prefers ``-post-rtjson-content`` over ``-comment-rtjson-content`` when both |
| 212 | exist for the same comment (live shreddit markup nests the post div inside |
| 213 | the comment div). |
| 214 | """ |
| 215 | starts: Dict[str, int] = {} |
| 216 | has_post_variant: set[str] = set() |
| 217 | for m in _DIV_OPEN.finditer(html_text or ""): |
| 218 | tag = m.group(0) |
| 219 | if tag.rstrip().endswith("/>"): |
| 220 | continue |
| 221 | div_id = _attr(tag, "id").lower() |
| 222 | if div_id.endswith("-post-rtjson-content"): |
| 223 | tid = div_id.removesuffix("-post-rtjson-content") |
| 224 | if tid and tid not in has_post_variant: |
| 225 | starts[tid] = m.end() |
| 226 | has_post_variant.add(tid) |
| 227 | elif div_id.endswith("-comment-rtjson-content"): |
| 228 | tid = div_id.removesuffix("-comment-rtjson-content") |
| 229 | if tid and tid not in starts: |
| 230 | starts[tid] = m.end() |
| 231 | return starts |
| 232 | |
| 233 | |
| 234 | def _find_body_div_start(html_text: str, thing_id: str) -> Optional[int]: |
| 235 | """Return the index right after the opening body ``<div>`` for ``thing_id``.""" |
| 236 | thing_lower = thing_id.lower() |
| 237 | post_target = f"{thing_lower}-post-rtjson-content" |
| 238 | comment_target = f"{thing_lower}-comment-rtjson-content" |
| 239 | comment_match_end: Optional[int] = None |
| 240 | for m in _DIV_OPEN.finditer(html_text): |
| 241 | tag = m.group(0) |
| 242 | if tag.rstrip().endswith("/>"): |
| 243 | continue |
| 244 | div_id = _attr(tag, "id").lower() |
| 245 | if div_id == post_target: |
| 246 | return m.end() |
| 247 | if div_id == comment_target and comment_match_end is None: |
| 248 | comment_match_end = m.end() |
| 249 | return comment_match_end |
| 250 | |
| 251 | |
| 252 | def _body_for( |
| 253 | html_text: str, |
| 254 | thing_id: str, |
| 255 | body_starts: Optional[Dict[str, int]] = None, |
| 256 | ) -> str: |
| 257 | """Extract a comment's text body, anchored on its unique thingId. |
| 258 | |
| 259 | The body div id embeds the comment's thingId (``-post-rtjson-content`` or |
| 260 | ``-comment-rtjson-content``), so this assigns body→comment correctly even |
| 261 | for nested replies. The slice is bounded by the matching closing ``</div>`` |
| 262 | (tracking nested ``<div>`` elements), ``<shreddit-comment>`` boundaries, |
| 263 | and any other comment's rtjson anchor so deleted/removed child comments or |
| 264 | UI footers are never concatenated into the parent body. |
| 265 | """ |
| 266 | if not html_text or not thing_id: |
| 267 | return "" |
| 268 | start = ( |
| 269 | body_starts.get(thing_id.lower()) |
| 270 | if body_starts is not None |
| 271 | else _find_body_div_start(html_text, thing_id) |
| 272 | ) |
| 273 | if start is None: |
| 274 | return "" |
| 275 | window = html_text[start: start + 16000] |
| 276 | thing_lower = thing_id.lower() |
| 277 | depth = 1 |
| 278 | cut = len(window) |
| 279 | for m in _BODY_BOUNDARY.finditer(window): |
| 280 | tok = m.group(0) |
| 281 | lower = tok.lower() |
| 282 | if lower.startswith("</div"): |
| 283 | depth -= 1 |
| 284 | if depth == 0: |
| 285 | cut = m.start() |
| 286 | break |
| 287 | elif lower.startswith("<div"): |
| 288 | div_id = _attr(tok, "id").lower() |
| 289 | if div_id.endswith(("-comment-rtjson-content", "-post-rtjson-content")): |
| 290 | other_id = ( |
| 291 | div_id.removesuffix("-comment-rtjson-content") |
| 292 | .removesuffix("-post-rtjson-content") |
| 293 | ) |
| 294 | if other_id != thing_lower: |
| 295 | cut = m.start() |
| 296 | break |
| 297 | if not tok.rstrip().endswith("/>"): |
| 298 | depth += 1 |
| 299 | else: |
| 300 | cut = m.start() |
| 301 | break |
| 302 | window = window[:cut] |
| 303 | for m in _NEXT_RTJSON.finditer(window): |
| 304 | other_id = (m.group(1) or m.group(2) or "").lower() |
| 305 | if other_id != thing_lower: |
| 306 | window = window[: m.start()] |
| 307 | break |
| 308 | paras = _PARA.findall(window) |
| 309 | if not paras: |
| 310 | return "" |
| 311 | text = " ".join(_TAG.sub("", p) for p in paras) |
| 312 | return _WS.sub(" ", _html.unescape(text)).strip() |
| 313 | |
| 314 | |
| 315 | def _is_bot_author(author: str) -> bool: |
| 316 | """Whether an author is a bot whose comments carry no community signal.""" |
| 317 | raw = (author or "").strip() |
| 318 | if not raw: |
| 319 | return False |
| 320 | name = raw.lower() |
| 321 | return (name in BOT_AUTHORS |
| 322 | or name.endswith(_BOT_SUFFIXES) |
| 323 | or bool(_CAMEL_BOT.search(raw))) |
| 324 | |
| 325 | |
| 326 | def parse_comments(html_text: str, limit: int = MAX_COMMENTS) -> List[Dict[str, Any]]: |
| 327 | """Parse <shreddit-comment> elements into scored comment dicts (sorted desc). |
| 328 | |
| 329 | Deleted, removed, and bot authors are dropped: they occupy top-comment slots |
| 330 | on high-traffic threads without saying anything about the topic. |
| 331 | """ |
| 332 | comments: List[Dict[str, Any]] = [] |
| 333 | body_starts: Optional[Dict[str, int]] = None |
| 334 | for m in _COMMENT_START.finditer(html_text or ""): |
| 335 | tag = m.group(0) |
| 336 | author = _attr(tag, "author") or "[deleted]" |
| 337 | if author in ("[deleted]", "[removed]") or _is_bot_author(author): |
| 338 | continue |
| 339 | thing_id = _attr(tag, "thingId") |
| 340 | if body_starts is None: |
| 341 | body_starts = _index_body_divs(html_text) |
| 342 | body = _body_for(html_text, thing_id, body_starts=body_starts) |
| 343 | if not body or body in ("[deleted]", "[removed]"): |
| 344 | continue |
| 345 | try: |
| 346 | score = int(_attr(tag, "score") or 0) |
| 347 | except ValueError: |
| 348 | score = 0 |
| 349 | try: |
| 350 | depth = int(_attr(tag, "depth") or 0) |
| 351 | except ValueError: |
| 352 | depth = 0 |
| 353 | permalink = _attr(tag, "permalink") |
| 354 | entry: Dict[str, Any] = { |
| 355 | "depth": depth, |
| 356 | "score": score, |
| 357 | "author": author, |
| 358 | "body": body[:300], |
| 359 | "excerpt": snippet.cut_quote(body), |
| 360 | "permalink": permalink, |
| 361 | "date": _iso_to_date(_attr(tag, "created")), |
| 362 | "url": f"https://reddit.com{permalink}" if permalink else "", |
| 363 | } |
| 364 | is_op = _bool_attr(tag, _OP_ATTR_NAMES) |
| 365 | if isinstance(is_op, bool): |
| 366 | entry["is_uploader"] = is_op |
| 367 | comments.append(entry) |
| 368 | |
| 369 | comments.sort(key=lambda c: c.get("score", 0), reverse=True) |
| 370 | return comments[:limit] |
| 371 | |
| 372 | |
| 373 | def _total_comments(html_text: str) -> Optional[int]: |
| 374 | m = _TOTAL_COMMENTS.search(html_text or "") |
| 375 | return int(m.group(1)) if m else None |
| 376 | |
| 377 | |
| 378 | def _clean_post_author(post_author: Optional[str]) -> str: |
| 379 | cleaned = str(post_author or "").strip().lower().removeprefix("/").removeprefix("u/") |
| 380 | return "" if cleaned in ("", "[deleted]", "[removed]") else cleaned |
| 381 | |
| 382 | |
| 383 | def fetch_comments( |
| 384 | post_url: str, |
| 385 | timeout: int = SVC_TIMEOUT, |
| 386 | deadline: Optional[float] = None, |
| 387 | post_author: Optional[str] = None, |
| 388 | ) -> Dict[str, Any]: |
| 389 | """Fetch and parse top comments for a Reddit post via the shreddit endpoint. |
| 390 | |
| 391 | Args: |
| 392 | post_url: Reddit thread URL (…/r/{sub}/comments/{id}/…) |
| 393 | timeout: HTTP timeout in seconds |
| 394 | deadline: absolute ``time.monotonic()`` bound shared by shreddit and the archive fallback |
| 395 | post_author: optional OP username used to stamp ``is_uploader`` when a comment lacks one |
| 396 | |
| 397 | Returns: |
| 398 | Dict with 'top_comments' (list, reddit_enrich shape), 'comment_insights' |
| 399 | (list[str]), and 'num_comments' (int or None). Empty/None on any |
| 400 | failure — never raises, so the caller can fall through to SC backup. |
| 401 | """ |
| 402 | ref = extract_post_ref(post_url) |
| 403 | if not ref: |
| 404 | return {"top_comments": [], "comment_insights": [], "num_comments": None} |
| 405 | if deadline is not None and time.monotonic() >= deadline: |
| 406 | return {"top_comments": [], "comment_insights": [], "num_comments": None} |
| 407 | sub, post_id = ref |
| 408 | |
| 409 | html_text: Optional[str] = None |
| 410 | if sub: |
| 411 | remaining = (deadline - time.monotonic()) if deadline is not None else None |
| 412 | if remaining is None or remaining > 0: |
| 413 | req_timeout = min(timeout, remaining) if remaining is not None else timeout |
| 414 | get_kwargs: Dict[str, Any] = { |
| 415 | "timeout": req_timeout, |
| 416 | "retries": 1, |
| 417 | "accept": "text/html", |
| 418 | "validate": unrecognized_comments_body, |
| 419 | } |
| 420 | if deadline is not None: |
| 421 | get_kwargs["deadline_monotonic"] = deadline |
| 422 | html_text = http.reddit_keyless_get_text(_svc_url(sub, post_id), **get_kwargs) |
| 423 | comments = parse_comments(html_text, limit=MAX_COMMENTS) if html_text else [] |
| 424 | total = _total_comments(html_text) if html_text else None |
| 425 | else: |
| 426 | comments = [] |
| 427 | total = None |
| 428 | # Skip Arctic Shift when shreddit returned a recognized 0-comment thread page. |
| 429 | skip_arctic = html_text is not None and total == 0 |
| 430 | if not comments and not skip_arctic: |
| 431 | if deadline is not None and time.monotonic() >= deadline: |
| 432 | return {"top_comments": [], "comment_insights": [], "num_comments": total} |
| 433 | # The shreddit comment partials 403 on some hosts (datacenter egress). |
| 434 | # Fall back to the arctic-shift archive, which serves scored comments |
| 435 | # from any IP keyless (ranked by score client-side). |
| 436 | try: |
| 437 | comments = reddit_arctic.fetch_post_comments( |
| 438 | post_id, limit=MAX_COMMENTS, skip_author=_is_bot_author, |
| 439 | deadline=deadline) |
| 440 | except Exception as exc: # the fallback must never break enrichment |
| 441 | _log(f"arctic comment fallback failed: {exc}") |
| 442 | comments = [] |
| 443 | if not comments: |
| 444 | return {"top_comments": [], "comment_insights": [], "num_comments": total} |
| 445 | |
| 446 | op_author = _clean_post_author(post_author) |
| 447 | top_comments: List[Dict[str, Any]] = [] |
| 448 | for c in comments: |
| 449 | entry: Dict[str, Any] = { |
| 450 | "score": c["score"], |
| 451 | "date": c["date"], |
| 452 | "author": c["author"], |
| 453 | "excerpt": c["excerpt"], |
| 454 | "url": c["url"], |
| 455 | "depth": c.get("depth", 0), |
| 456 | } |
| 457 | if isinstance(c.get("is_uploader"), bool): |
| 458 | entry["is_uploader"] = c["is_uploader"] |
| 459 | elif op_author: |
| 460 | cname = _clean_post_author(c.get("author")) |
| 461 | if cname: |
| 462 | entry["is_uploader"] = cname == op_author |
| 463 | top_comments.append(entry) |
| 464 | |
| 465 | insights = reddit_enrich.extract_comment_insights(comments) |
| 466 | return { |
| 467 | "top_comments": top_comments, |
| 468 | "comment_insights": insights, |
| 469 | "num_comments": total, |
| 470 | } |
| 471 |