| 1 | """V2EX source for last30days. |
| 2 | |
| 3 | V2EX (v2ex.com) is the largest Chinese-language developer community. Its own |
| 4 | public API (v1) has no search, so retrieval goes through two keyless |
| 5 | endpoints: |
| 6 | |
| 7 | - SOV2EX (``www.sov2ex.com/api/search``), the community-run full-text index |
| 8 | of V2EX topics. It takes ``gte``/``lte`` epoch-second bounds, so past |
| 9 | windows are filtered server-side. ``operator=and`` requires every query |
| 10 | term; the default OR matching returns topics that share one common word. |
| 11 | ``size`` is capped at 50. |
| 12 | - V2EX API v1 (``www.v2ex.com/api/replies/show.json``) returns a topic's |
| 13 | replies in thread order. Replies carry no votes. The API allows about 120 |
| 14 | requests an hour per IP, so only the top-ranked topics are enriched. |
| 15 | |
| 16 | SOV2EX's ``replies`` count is a snapshot from indexing time (a new topic |
| 17 | reads 0), so enrichment refreshes it from the replies it fetches. |
| 18 | |
| 19 | The source is off by default: ``INCLUDE_SOURCES=v2ex`` or ``--search v2ex`` |
| 20 | turns it on. |
| 21 | """ |
| 22 | |
| 23 | from __future__ import annotations |
| 24 | |
| 25 | import datetime |
| 26 | import html |
| 27 | import re |
| 28 | import time |
| 29 | import urllib.parse |
| 30 | from concurrent.futures import ThreadPoolExecutor, as_completed |
| 31 | from concurrent.futures import TimeoutError as FuturesTimeout |
| 32 | from typing import Any |
| 33 | |
| 34 | from . import http, log, signals |
| 35 | from .relevance import token_overlap_relevance |
| 36 | |
| 37 | SEARCH_URL = "https://www.sov2ex.com/api/search" |
| 38 | REPLIES_URL = "https://www.v2ex.com/api/replies/show.json" |
| 39 | TOPIC_URL = "https://www.v2ex.com/t/{id}" |
| 40 | |
| 41 | SEARCH_SIZE = {"quick": 10, "default": 20, "deep": 40} |
| 42 | ENRICH_LIMIT = 3 |
| 43 | MAX_COMMENTS = 5 |
| 44 | # Same bar as dev.to search hits: SOV2EX matches every term somewhere in the |
| 45 | # topic, but a term buried in a long job post is not a topic about it. |
| 46 | SEARCH_RELEVANCE_FLOOR = 0.25 |
| 47 | REQUEST_DEADLINE_SECONDS = 20.0 |
| 48 | ENRICH_WAIT_SECONDS = 25.0 |
| 49 | TEXT_LIMIT = 500 |
| 50 | |
| 51 | |
| 52 | def _log(msg: str) -> None: |
| 53 | log.source_log("V2EX", msg, tty_only=False) |
| 54 | |
| 55 | |
| 56 | def _epoch(day: str | None, *, end_of_day: bool = False) -> int | None: |
| 57 | """UTC epoch seconds for the start (or end) of an ISO date.""" |
| 58 | try: |
| 59 | date = datetime.date.fromisoformat(day or "") |
| 60 | except ValueError: |
| 61 | return None |
| 62 | moment = datetime.datetime.combine( |
| 63 | date, |
| 64 | datetime.time.max if end_of_day else datetime.time.min, |
| 65 | tzinfo=datetime.timezone.utc, |
| 66 | ) |
| 67 | return int(moment.timestamp()) |
| 68 | |
| 69 | |
| 70 | def _get(url: str, deadline: float | None = None) -> Any: |
| 71 | return http.request( |
| 72 | "GET", url, timeout=15, retries=2, |
| 73 | deadline_monotonic=min( |
| 74 | time.monotonic() + REQUEST_DEADLINE_SECONDS, |
| 75 | deadline if deadline is not None else float("inf"), |
| 76 | ), |
| 77 | owned_get=True, |
| 78 | ) |
| 79 | |
| 80 | |
| 81 | def _topic_text(topic: dict[str, Any]) -> str: |
| 82 | return " ".join([str(topic.get("title") or ""), str(topic.get("content") or "")]) |
| 83 | |
| 84 | |
| 85 | def search_v2ex( |
| 86 | topic: str, |
| 87 | from_date: str | None = None, |
| 88 | to_date: str | None = None, |
| 89 | *, |
| 90 | depth: str = "default", |
| 91 | search_query: str | None = None, |
| 92 | ) -> dict[str, Any]: |
| 93 | """Search V2EX topics created in the window. |
| 94 | |
| 95 | Returns ``{"topics": [...]}``, plus ``"error"`` when the search failed so |
| 96 | the run reports a source failure instead of a quiet empty result. |
| 97 | """ |
| 98 | # Planner queries quote phrases for engines with phrase syntax; SOV2EX |
| 99 | # treats the quotes as literal characters. |
| 100 | query = " ".join((search_query or topic or "").replace('"', " ").split()) |
| 101 | if not query: |
| 102 | return {"topics": []} |
| 103 | params: dict[str, Any] = { |
| 104 | "q": query, |
| 105 | "size": SEARCH_SIZE.get(depth, SEARCH_SIZE["default"]), |
| 106 | "sort": "sumup", |
| 107 | "operator": "and", |
| 108 | } |
| 109 | gte = _epoch(from_date) |
| 110 | lte = _epoch(to_date, end_of_day=True) |
| 111 | if gte is not None: |
| 112 | params["gte"] = gte |
| 113 | if lte is not None: |
| 114 | params["lte"] = lte |
| 115 | try: |
| 116 | data = _get(f"{SEARCH_URL}?{urllib.parse.urlencode(params)}") |
| 117 | if not isinstance(data, dict) or not isinstance(data.get("hits"), list): |
| 118 | # SOV2EX answers a rejected query with {"message": ...}, not hits. |
| 119 | detail = data.get("message") if isinstance(data, dict) else type(data).__name__ |
| 120 | raise ValueError(f"unexpected SOV2EX response: {detail}") |
| 121 | except Exception as exc: |
| 122 | _log(f"search failed for '{query}': {exc}") |
| 123 | return {"topics": [], "error": f"search: {exc}"} |
| 124 | |
| 125 | topics: list[dict[str, Any]] = [] |
| 126 | seen: set[int] = set() |
| 127 | dropped = 0 |
| 128 | for hit in data["hits"]: |
| 129 | source = hit.get("_source") if isinstance(hit, dict) else None |
| 130 | if not isinstance(source, dict) or source.get("id") is None: |
| 131 | continue |
| 132 | if source["id"] in seen: |
| 133 | continue |
| 134 | if token_overlap_relevance(topic or query, _topic_text(source)) < SEARCH_RELEVANCE_FLOOR: |
| 135 | dropped += 1 |
| 136 | continue |
| 137 | seen.add(source["id"]) |
| 138 | topics.append(source) |
| 139 | _log(f"search '{query}': kept {len(topics)}, dropped {dropped} off-topic") |
| 140 | return {"topics": topics} |
| 141 | |
| 142 | |
| 143 | def _clean(text: Any) -> str: |
| 144 | return " ".join(html.unescape(str(text or "")).split()) |
| 145 | |
| 146 | |
| 147 | def parse_v2ex_response(response: dict[str, Any], query: str = "") -> list[dict[str, Any]]: |
| 148 | """Map SOV2EX topics to engine item dicts (the HN item shape).""" |
| 149 | items: list[dict[str, Any]] = [] |
| 150 | for topic in response.get("topics") or []: |
| 151 | replies = int(topic.get("replies") or 0) |
| 152 | content_score = token_overlap_relevance(query, _topic_text(topic)) if query else 0.5 |
| 153 | relevance = min(1.0, 0.7 * content_score + min(0.3, replies / 100)) |
| 154 | content = _clean(topic.get("content")) |
| 155 | items.append({ |
| 156 | "id": str(topic.get("id")), |
| 157 | "title": _clean(topic.get("title")), |
| 158 | "url": TOPIC_URL.format(id=topic.get("id")), |
| 159 | "author": str(topic.get("member") or ""), |
| 160 | # SOV2EX timestamps are UTC without an offset. |
| 161 | "date": str(topic.get("created") or "")[:10] or None, |
| 162 | "text": content[:TEXT_LIMIT] + "..." if len(content) > TEXT_LIMIT else content, |
| 163 | "engagement": {"replies": replies}, |
| 164 | "relevance": round(relevance, 2), |
| 165 | "why_relevant": "V2EX topic (search)", |
| 166 | "metadata": {"node_id": topic.get("node")}, |
| 167 | }) |
| 168 | return items |
| 169 | |
| 170 | |
| 171 | _LEADING_MENTIONS = re.compile(r"^(?:@\S+\s*)+") |
| 172 | |
| 173 | |
| 174 | def _fetch_replies(topic_id: str, op: str, deadline: float | None = None) -> tuple[int, list[dict[str, Any]]] | None: |
| 175 | """Return the topic's reply count and its leading community replies. |
| 176 | |
| 177 | Replies arrive in thread order with no votes. Replies that open with an |
| 178 | ``@handle`` answer another reply, so replies to the topic itself lead and |
| 179 | keep their thread order. The topic's own author is never a community |
| 180 | comment. |
| 181 | """ |
| 182 | if deadline is not None and time.monotonic() >= deadline: |
| 183 | return None |
| 184 | url = f"{REPLIES_URL}?{urllib.parse.urlencode({'topic_id': topic_id})}" |
| 185 | try: |
| 186 | rows = _get(url, deadline=deadline) |
| 187 | if not isinstance(rows, list): |
| 188 | raise ValueError(f"unexpected V2EX response shape: {type(rows).__name__}") |
| 189 | except Exception as exc: |
| 190 | _log(f"replies failed for topic {topic_id}: {exc}") |
| 191 | return None |
| 192 | direct: list[dict[str, Any]] = [] |
| 193 | mentions: list[dict[str, Any]] = [] |
| 194 | for row in rows: |
| 195 | if not isinstance(row, dict): |
| 196 | continue |
| 197 | member = row.get("member") |
| 198 | if not isinstance(member, dict): |
| 199 | continue |
| 200 | author = str(member.get("username") or "") |
| 201 | raw_text = _clean(row.get("content")) |
| 202 | text = _LEADING_MENTIONS.sub("", raw_text) |
| 203 | if not text or (op and author == op): |
| 204 | continue |
| 205 | (mentions if text != raw_text else direct).append({ |
| 206 | "author": author, |
| 207 | "text": text[:300] + "..." if len(text) > 300 else text, |
| 208 | "date": _reply_date(row.get("created")), |
| 209 | }) |
| 210 | return len(rows), (direct + mentions)[:MAX_COMMENTS] |
| 211 | |
| 212 | |
| 213 | def _reply_date(created: Any) -> str: |
| 214 | try: |
| 215 | return datetime.datetime.fromtimestamp(int(created), datetime.timezone.utc).date().isoformat() |
| 216 | except (TypeError, ValueError, OverflowError, OSError): |
| 217 | return "" |
| 218 | |
| 219 | |
| 220 | def enrich_source_items( |
| 221 | items: list[Any], |
| 222 | top_k: int = ENRICH_LIMIT, |
| 223 | deadline: float | None = None, |
| 224 | ) -> list[Any]: |
| 225 | """Attach replies to the first ``top_k`` ranked SourceItems. |
| 226 | |
| 227 | Runs from ``_finalize_items_by_source`` so the reply calls land on topics |
| 228 | that survived relevance pruning and dedupe. Every target is fetched, not |
| 229 | only topics with replies, because SOV2EX's reply count can be stale. |
| 230 | """ |
| 231 | from .normalize import _remap_comments |
| 232 | |
| 233 | targets = [ |
| 234 | item for item in items |
| 235 | if getattr(item, "source", None) == "v2ex" |
| 236 | and not (item.metadata or {}).get("top_comments") |
| 237 | ][:top_k] |
| 238 | if not targets: |
| 239 | return items |
| 240 | wait_budget = ENRICH_WAIT_SECONDS |
| 241 | if deadline is not None: |
| 242 | remaining = deadline - time.monotonic() |
| 243 | if remaining <= 0: |
| 244 | _log("reply enrichment skipped: no time left") |
| 245 | return items |
| 246 | wait_budget = min(wait_budget, remaining) |
| 247 | executor = ThreadPoolExecutor(max_workers=len(targets)) |
| 248 | futures = { |
| 249 | ( |
| 250 | http.submit_with_context(executor, _fetch_replies, item.item_id, item.author, deadline) |
| 251 | if deadline is not None |
| 252 | else http.submit_with_context(executor, _fetch_replies, item.item_id, item.author) |
| 253 | ): item |
| 254 | for item in targets |
| 255 | } |
| 256 | try: |
| 257 | for future in as_completed(futures, timeout=wait_budget): |
| 258 | result = future.result() |
| 259 | if result is None: |
| 260 | continue |
| 261 | item = futures[future] |
| 262 | count, comments = result |
| 263 | item.engagement = {**(item.engagement or {}), "replies": max(count, int((item.engagement or {}).get("replies") or 0))} |
| 264 | # Scores were set before enrichment; fusion ranks on this one, so |
| 265 | # the refreshed count must reach it (as fusion's own merge does). |
| 266 | item.engagement_score = signals.engagement_score(item) |
| 267 | item.metadata["top_comments"] = _remap_comments( |
| 268 | comments, |
| 269 | # V2EX replies carry no votes; the absent score stays None. |
| 270 | score_keys=("score",), |
| 271 | excerpt_keys=("text", "excerpt"), |
| 272 | preserve_absent_score=True, |
| 273 | ) |
| 274 | except FuturesTimeout: |
| 275 | _log("reply enrichment hit its time limit; keeping the replies that arrived") |
| 276 | finally: |
| 277 | # Never block report finalization on a straggling reply fetch. |
| 278 | executor.shutdown(wait=False, cancel_futures=True) |
| 279 | attached = sum(1 for item in targets if item.metadata.get("top_comments")) |
| 280 | _log(f"attached replies to {attached} of {len(targets)} top topics") |
| 281 | return items |
| 282 |