返回 last30days-skill
reddit_refs.py
根目录 / skills / last30days / scripts / lib / reddit_refs.py
1 """Canonical Reddit thread identity, shared by every Reddit discovery path.
2
3 One thread reaches the engine in many shapes: ``old.`` and ``new.`` hosts,
4 slugless links, comment permalinks, ``redd.it/<id>`` short links, bare ids.
5 :func:`canonical_thread` turns each of them into one :class:`ThreadRef` so the
6 lanes, the hydrator and fusion agree on what "the same thread" is. Share links
7 (``/r/<sub>/s/<code>``), search-engine redirect wrappers and other hosts are
8 rejected: their target cannot be known without following them.
9
10 This module also names where a thread's score came from, so a live score can
11 beat an archive snapshot when copies merge, and holds the comment union used
12 by that merge. It imports nothing from the rest of the engine.
13 """
14
15 from __future__ import annotations
16
17 import re
18 from dataclasses import dataclass, field
19 from typing import Any, Iterable
20 from urllib.parse import urlsplit
21
22 # Where a thread's score came from, best first. A score Reddit itself served
23 # (site search, a listing, a logged-in session, ScrapeCreators) is live. Arctic
24 # Shift snapshots a post when it ingests it and rescans it about once, so a post
25 # under PENDING_SECONDS old still reads 0 or 1 there: that score is withheld
26 # (``None``) and labeled pending. An older archive score is frozen but real.
27 # A thread nothing hydrated has an unknown score.
28 LIVE = "live"
29 ARCTIC = "arctic"
30 ARCTIC_PENDING = "arctic-pending"
31 UNKNOWN = "unknown"
32 _SCORE_RANK = {LIVE: 3, ARCTIC: 2, ARCTIC_PENDING: 1, UNKNOWN: 0}
33 PENDING_SECONDS = 36 * 3600
34
35 _HOSTS = frozenset({
36 "reddit.com", "www.reddit.com", "old.reddit.com", "new.reddit.com",
37 "np.reddit.com", "m.reddit.com", "sh.reddit.com",
38 })
39 _SHORT_HOSTS = frozenset({"redd.it", "www.redd.it"})
40 _ID = re.compile(r"^[0-9a-z]{1,13}\Z")
41 _SUBREDDIT = re.compile(r"^[A-Za-z0-9_]{2,21}\Z")
42 _SUBREDDIT_PREFIX = re.compile(r"^/?r/", re.IGNORECASE)
43
44
45 @dataclass
46 class MatchedComment:
47 """The comment a comment search matched inside a thread."""
48
49 comment_id: str
50 created_utc: int | None = None
51 permalink: str = ""
52
53
54 @dataclass
55 class ThreadRef:
56 """One discovered thread, before hydration.
57
58 ``provenance`` names the discovery paths that found it (``web``, ``host``,
59 ``session``). ``title`` and ``date`` are what the search result showed;
60 they stand in only when no hydrator could fill the thread.
61 """
62
63 post_id: str
64 url: str
65 subreddit: str = ""
66 provenance: set[str] = field(default_factory=set)
67 matched_comment: MatchedComment | None = None
68 title: str = ""
69 date: str | None = None
70 matched_comment_verified: bool = False
71
72
73 def _canonical_url(post_id: str, subreddit: str) -> str:
74 if subreddit:
75 return f"https://www.reddit.com/r/{subreddit}/comments/{post_id}/"
76 return f"https://www.reddit.com/comments/{post_id}/"
77
78
79 def _bare_id(text: str) -> str | None:
80 candidate = text.strip().lower().removeprefix("t3_")
81 return candidate if _ID.match(candidate) else None
82
83
84 def normalize_subreddit(value: Any, *, allow_all: bool = False) -> str | None:
85 """Normalize and validate a subreddit name (stripping optional ``/?r/``), else ``None``."""
86 if not isinstance(value, str):
87 return None
88 sub = _SUBREDDIT_PREFIX.sub("", value.strip()).strip("/")
89 if not _SUBREDDIT.match(sub):
90 return None
91 if not allow_all and sub.lower() == "all":
92 return None
93 return sub
94
95
96 def normalize_post_id(value: Any) -> str | None:
97 """Normalize and validate a base36 Reddit post id (stripping optional ``t3_``), else ``None``."""
98 if not isinstance(value, str):
99 return None
100 return _bare_id(value)
101
102
103 def canonical_thread(url_or_id: str) -> ThreadRef | None:
104 """The canonical ref for a Reddit thread URL or base36 id, else ``None``."""
105 if not isinstance(url_or_id, str):
106 return None
107 text = url_or_id.strip()
108 if not text:
109 return None
110 if "/" not in text and "." not in text:
111 post_id = _bare_id(text)
112 return ThreadRef(post_id=post_id, url=_canonical_url(post_id, "")) if post_id else None
113 if "://" not in text:
114 text = "https://" + text
115 try:
116 parts = urlsplit(text)
117 port = parts.port
118 except ValueError:
119 return None
120 if parts.scheme not in ("http", "https"):
121 return None
122 if parts.username is not None or parts.password is not None or "@" in parts.netloc:
123 return None
124 default_port = 443 if parts.scheme == "https" else 80
125 if port is not None and port != default_port:
126 return None
127 host = (parts.hostname or "").lower()
128 segments = [s for s in parts.path.split("/") if s]
129 if any(seg in (".", "..") for seg in segments):
130 return None
131 if host in _SHORT_HOSTS:
132 post_id = _bare_id(segments[0]) if len(segments) == 1 else None
133 return ThreadRef(post_id=post_id, url=_canonical_url(post_id, "")) if post_id else None
134 if host not in _HOSTS:
135 return None
136 subreddit = ""
137 if len(segments) >= 2 and segments[0].lower() == "r":
138 subreddit = segments[1]
139 if not _SUBREDDIT.match(subreddit):
140 return None
141 segments = segments[2:]
142 if len(segments) < 2 or segments[0].lower() != "comments":
143 return None
144 post_id = _bare_id(segments[1])
145 if not post_id:
146 return None
147 return ThreadRef(post_id=post_id, url=_canonical_url(post_id, subreddit), subreddit=subreddit)
148
149
150 def canonical_thread_url(url: Any) -> ThreadRef | None:
151 """The canonical ref for a full ``http(s)`` Reddit thread URL, else ``None``."""
152 if not isinstance(url, str):
153 return None
154 text = url.strip()
155 if not text or "://" not in text:
156 return None
157 return canonical_thread(text)
158
159
160 def thread_key(url: str) -> str | None:
161 """A merge key every URL form of one thread shares, or ``None``."""
162 ref = canonical_thread(url)
163 return f"https://reddit.com/comments/{ref.post_id}" if ref else None
164
165
166 def score_rank(engagement_source: str | None) -> int:
167 """How much a score from ``engagement_source`` is trusted (higher wins).
168
169 A copy with no label came from a lane that served Reddit's own score.
170 """
171 return _SCORE_RANK.get(engagement_source or LIVE, _SCORE_RANK[LIVE])
172
173
174 def score_pending(metadata: dict[str, Any] | None) -> bool:
175 """Whether an item's score is a withheld fresh archive snapshot."""
176 return bool(metadata) and metadata.get("engagement_source") == ARCTIC_PENDING
177
178
179 def comment_key(comment: dict[str, Any]) -> str:
180 """A comment's identity: its id, the last segment of its permalink, or its text."""
181 cid = str(comment.get("id") or "").strip().removeprefix("t1_")
182 if cid:
183 return cid
184 link = str(comment.get("permalink") or comment.get("url") or "")
185 segments = [s for s in urlsplit(link).path.split("/") if s]
186 if len(segments) >= 2 and "comments" in segments:
187 after = segments[segments.index("comments") + 1:]
188 if len(after) >= 3:
189 return after[2].lower()
190 text = str(comment.get("excerpt") or comment.get("body") or comment.get("text") or "")
191 return " ".join(text.split())[:80].lower()
192
193
194 def _comment_order(comment: dict[str, Any]) -> tuple:
195 score = comment.get("score")
196 scored = isinstance(score, (int, float)) and not isinstance(score, bool) and not comment.get("score_pending")
197 return (0, -score) if scored else (1, 0)
198
199
200 def union_comments(
201 mine: Iterable[dict[str, Any]], theirs: Iterable[dict[str, Any]],
202 ) -> list[dict[str, Any]]:
203 """Both comment lists, one entry per comment id, scored comments first by score.
204
205 Where both lists hold a comment, the copy in ``mine`` stays unless it is
206 pending and the other copy carries a score. Pending comments keep their
207 order after every scored one.
208 """
209 merged: dict[str, dict[str, Any]] = {}
210 for comment in [*mine, *theirs]:
211 if not isinstance(comment, dict):
212 continue
213 key = comment_key(comment)
214 current = merged.get(key)
215 if current is None or (_comment_order(current)[0] == 1 and _comment_order(comment)[0] == 0):
216 merged[key] = comment
217 return sorted(merged.values(), key=_comment_order)
218
218 lines PYTHON