返回 last30days-skill
juejin.py
根目录 / skills / last30days / scripts / lib / juejin.py
1 """Juejin (掘金) source for last30days.
2
3 Juejin (juejin.cn) is a large Chinese-language developer article platform.
4 Its web client calls two keyless JSON endpoints, both POST:
5
6 - ``api.juejin.cn/search_api/v1/search`` searches articles. It takes no date
7 filter and returns 20 rows a page whatever ``limit`` says. ``sort_type=1``
8 favors recent articles, but pages are not in date order: every page of a
9 busy term mixes dates from the whole month. ``sort_type=0`` and ``2``
10 return mostly articles from months or years ago. So the source pages
11 through ``sort_type=1``, keeps the in-window rows, and ranks them locally.
12 - ``api.juejin.cn/interact_api/v1/comment/list`` returns an article's
13 top-level comments with like counts.
14
15 Most recent Juejin articles have no likes (a 2026-11 sample of 467 in-window
16 articles had a median of 0 likes and 35 views), so views count toward
17 engagement.
18
19 The source is off by default: ``INCLUDE_SOURCES=juejin`` or
20 ``--search juejin`` turns it on.
21 """
22
23 from __future__ import annotations
24
25 import datetime
26 import html
27 import time
28 from concurrent.futures import ThreadPoolExecutor, as_completed
29 from concurrent.futures import TimeoutError as FuturesTimeout
30 from typing import Any
31
32 from . import dates, http, log, signals
33 from .relevance import token_overlap_relevance
34
35 # aid=2608 is the Juejin web client's app id; the API rejects calls without it.
36 SEARCH_URL = "https://api.juejin.cn/search_api/v1/search?aid=2608&spider=0"
37 COMMENTS_URL = "https://api.juejin.cn/interact_api/v1/comment/list?aid=2608"
38 ARTICLE_URL = "https://juejin.cn/post/{id}"
39 _HEADERS = {"Content-Type": "application/json"}
40
41 SEARCH_PAGES = {"quick": 1, "default": 3, "deep": 5}
42 KEEP_LIMIT = {"quick": 10, "default": 20, "deep": 30}
43 ENRICH_LIMIT = 3
44 MAX_COMMENTS = 5
45 # Same bar as dev.to and V2EX search hits: Juejin search also matches a term
46 # buried in an unrelated article.
47 SEARCH_RELEVANCE_FLOOR = 0.25
48 REQUEST_DEADLINE_SECONDS = 20.0
49 SEARCH_BUDGET_SECONDS = 30.0
50 ENRICH_WAIT_SECONDS = 25.0
51 TEXT_LIMIT = 500
52
53
54 def _log(msg: str) -> None:
55 log.source_log("Juejin", msg, tty_only=False)
56
57
58 def _epoch(day: str | None, *, end_of_day: bool = False) -> int | None:
59 """UTC epoch seconds for the start (or end) of an ISO date."""
60 try:
61 date = datetime.date.fromisoformat(day or "")
62 except ValueError:
63 return None
64 moment = datetime.datetime.combine(
65 date,
66 datetime.time.max if end_of_day else datetime.time.min,
67 tzinfo=datetime.timezone.utc,
68 )
69 return int(moment.timestamp())
70
71
72 def _post(url: str, body: dict[str, Any], deadline: float | None = None) -> dict[str, Any]:
73 data = http.request(
74 "POST", url, headers=_HEADERS, json_data=body, timeout=15, retries=2,
75 deadline_monotonic=min(
76 time.monotonic() + REQUEST_DEADLINE_SECONDS,
77 deadline if deadline is not None else float("inf"),
78 ),
79 )
80 if not isinstance(data, dict) or data.get("err_no") != 0:
81 detail = (data.get("err_msg") or data.get("err_no")) if isinstance(data, dict) else type(data).__name__
82 raise ValueError(f"unexpected Juejin response: {detail}")
83 return data
84
85
86 def _int(value: Any) -> int:
87 """Parse a count or id, treating malformed or negative input as absent."""
88 try:
89 return max(0, int(value or 0))
90 except (TypeError, ValueError, OverflowError):
91 return 0
92
93
94 def _clean(text: Any) -> str:
95 return " ".join(html.unescape(str(text or "")).split())
96
97
98 def _tags(row: dict[str, Any]) -> list[str]:
99 return [str(tag.get("tag_name")) for tag in row.get("tags") or [] if isinstance(tag, dict) and tag.get("tag_name")]
100
101
102 def _article_text(row: dict[str, Any]) -> str:
103 info = row.get("article_info") or {}
104 return " ".join([str(info.get("title") or ""), str(info.get("brief_content") or ""), " ".join(_tags(row))])
105
106
107 def _engagement(row: dict[str, Any]) -> dict[str, int]:
108 info = row.get("article_info") or {}
109 return {
110 "likes": _int(info.get("digg_count")),
111 "comments": _int(info.get("comment_count")),
112 "saves": _int(info.get("collect_count")),
113 "views": _int(info.get("view_count")),
114 }
115
116
117 def _engagement_mix(row: dict[str, Any]) -> float:
118 """The weighted log mix signals scores Juejin engagement on.
119
120 Ranking on the same mix keeps the articles the engine will score highest;
121 likes first would let one like outrank thousands of views.
122 """
123 engagement = _engagement(row)
124 return sum(
125 weight * signals.log1p_safe(engagement.get(field, 0))
126 for field, weight in signals.ENGAGEMENT_WEIGHTS["juejin"]
127 )
128
129
130 def search_juejin(
131 topic: str,
132 from_date: str | None = None,
133 to_date: str | None = None,
134 *,
135 depth: str = "default",
136 search_query: str | None = None,
137 ) -> dict[str, Any]:
138 """Page through recent Juejin articles and keep the in-window, on-topic ones.
139
140 Returns ``{"articles": [...]}``, plus ``"error"`` when the first page
141 failed so the run reports a source failure instead of a quiet empty result.
142 A later page failing keeps the pages already fetched and adds "partial_error".
143 """
144 # Planner queries quote phrases for engines with phrase syntax; Juejin
145 # treats the quotes as literal characters.
146 query = " ".join((search_query or topic or "").replace('"', " ").split())
147 if not query:
148 return {"articles": []}
149 start = _epoch(from_date)
150 end = _epoch(to_date, end_of_day=True)
151 deadline = time.monotonic() + SEARCH_BUDGET_SECONDS
152 pages = SEARCH_PAGES.get(depth, SEARCH_PAGES["default"])
153 rows: list[dict[str, Any]] = []
154 partial_error = None
155 cursor = "0"
156 for page in range(1, pages + 1):
157 if page > 1 and time.monotonic() >= deadline:
158 _log(f"search '{query}': stopped after {page - 1} pages at the time budget")
159 break
160 body = {
161 "key_word": query, "id_type": 2, "cursor": cursor, "limit": 20,
162 "search_type": 0, "sort_type": 1, "version": 1,
163 }
164 try:
165 data = _post(SEARCH_URL, body, deadline=deadline if page > 1 else None)
166 if not isinstance(data.get("data"), list):
167 # A changed reply shape is a failure, not "no matches".
168 raise ValueError(f"unexpected Juejin search data: {type(data.get('data')).__name__}")
169 except Exception as exc:
170 if page == 1:
171 _log(f"search failed for '{query}': {exc}")
172 return {"articles": [], "error": f"search: {exc}"}
173 partial_error = f"search: page {page} failed ({exc})"
174 _log(f"{partial_error}; keeping the {page - 1} pages fetched")
175 break
176 batch = [
177 r["result_model"] for r in data["data"]
178 if isinstance(r, dict) and isinstance(r.get("result_model"), dict)
179 and isinstance(r["result_model"].get("article_info"), dict)
180 ]
181 rows.extend(batch)
182 created = [_int(row["article_info"].get("ctime")) for row in batch]
183 # Pages are only loosely date-ordered, so stop early only once a whole
184 # page predates the window.
185 if not data.get("has_more") or not data.get("cursor") or (
186 start is not None and created and max(created) < start
187 ):
188 break
189 cursor = str(data["cursor"])
190
191 articles: dict[str, dict[str, Any]] = {}
192 dropped = 0
193 for row in rows:
194 article_id = str(row.get("article_id") or row["article_info"].get("article_id") or "")
195 created = _int(row["article_info"].get("ctime"))
196 if not article_id or article_id in articles or not created:
197 continue
198 if (start is not None and created < start) or (end is not None and created > end):
199 continue
200 if token_overlap_relevance(topic or query, _article_text(row)) < SEARCH_RELEVANCE_FLOOR:
201 dropped += 1
202 continue
203 articles[article_id] = row
204 kept = sorted(articles.values(), key=_engagement_mix, reverse=True)
205 kept = kept[: KEEP_LIMIT.get(depth, KEEP_LIMIT["default"])]
206 _log(f"search '{query}': kept {len(kept)} of {len(rows)} rows, dropped {dropped} off-topic")
207 if partial_error is not None:
208 return {"articles": kept, "partial_error": partial_error}
209 return {"articles": kept}
210
211
212 def parse_juejin_response(response: dict[str, Any], query: str = "") -> list[dict[str, Any]]:
213 """Map Juejin articles to engine item dicts (the HN item shape)."""
214 items: list[dict[str, Any]] = []
215 for row in response.get("articles") or []:
216 info = row.get("article_info") or {}
217 author = row.get("author_user_info") or {}
218 article_id = str(row.get("article_id") or info.get("article_id"))
219 engagement = _engagement(row)
220 likes, comments = engagement["likes"], engagement["comments"]
221 content_score = token_overlap_relevance(query, _article_text(row)) if query else 0.5
222 # Cap each counter before adding: an extreme upstream int would overflow
223 # the division's float conversion, and the sum was capped at 0.3 anyway.
224 # A negative counter is no signal, not a reason to lower the score.
225 engagement_bonus = min(0.3, (min(likes, 100) + min(comments, 100)) / 100)
226 relevance = min(1.0, 0.7 * content_score + engagement_bonus)
227 created_at = dates.parse_date(_int(info.get("ctime")))
228 text = _clean(info.get("brief_content"))
229 items.append({
230 "id": article_id,
231 "title": _clean(info.get("title")),
232 "url": ARTICLE_URL.format(id=article_id),
233 "author": str(author.get("user_name") or ""),
234 "date": created_at.date().isoformat() if created_at else "",
235 "text": text[:TEXT_LIMIT] + "..." if len(text) > TEXT_LIMIT else text,
236 "engagement": engagement,
237 "relevance": round(relevance, 2),
238 "why_relevant": "Juejin article (search)",
239 "metadata": {
240 "tags": _tags(row),
241 "category": str((row.get("category") or {}).get("category_name") or ""),
242 "author_id": str(author.get("user_id") or info.get("user_id") or ""),
243 },
244 })
245 return items
246
247
248 def _comment_date(created: Any) -> str:
249 try:
250 return datetime.datetime.fromtimestamp(int(created), datetime.timezone.utc).date().isoformat()
251 except (TypeError, ValueError, OverflowError, OSError):
252 return ""
253
254
255 def _fetch_comments(article_id: str, author_id: str, deadline: float | None = None) -> list[dict[str, Any]]:
256 """Return an article's most-liked community comments.
257
258 Bot comments (``bot_id`` set) and the article author's own comments are
259 never community comments.
260 """
261 if deadline is not None and time.monotonic() >= deadline:
262 return []
263 body = {"client_type": 2608, "cursor": "0", "item_id": article_id, "item_type": 2, "limit": 20}
264 try:
265 data = _post(COMMENTS_URL, body, deadline=deadline)
266 except Exception as exc:
267 _log(f"comments failed for article {article_id}: {exc}")
268 return []
269 comments = []
270 for row in data.get("data") or []:
271 if not isinstance(row, dict):
272 continue
273 info = row.get("comment_info")
274 user = row.get("user_info")
275 if not isinstance(info, dict) or not isinstance(user, dict):
276 continue
277 text = _clean(info.get("comment_content"))
278 if not text or _int(info.get("bot_id")):
279 continue
280 if author_id and str(info.get("user_id") or user.get("user_id") or "") == author_id:
281 continue
282 comments.append({
283 "author": str(user.get("user_name") or ""),
284 "text": text[:300] + "..." if len(text) > 300 else text,
285 "likes": _int(info.get("digg_count")),
286 "date": _comment_date(info.get("ctime")),
287 })
288 comments.sort(key=lambda c: c["likes"], reverse=True)
289 return comments[:MAX_COMMENTS]
290
291
292 def enrich_source_items(
293 items: list[Any],
294 top_k: int = ENRICH_LIMIT,
295 deadline: float | None = None,
296 ) -> list[Any]:
297 """Attach top comments to the first ``top_k`` ranked SourceItems with comments.
298
299 Runs from ``_finalize_items_by_source`` so the comment calls land on the
300 articles that survived relevance pruning and dedupe.
301 """
302 from .normalize import _remap_comments
303
304 targets = [
305 item for item in items
306 if getattr(item, "source", None) == "juejin"
307 and not (item.metadata or {}).get("top_comments")
308 and (item.engagement or {}).get("comments")
309 ][:top_k]
310 if not targets:
311 return items
312 wait_budget = ENRICH_WAIT_SECONDS
313 if deadline is not None:
314 remaining = deadline - time.monotonic()
315 if remaining <= 0:
316 _log("comment enrichment skipped: no time left")
317 return items
318 wait_budget = min(wait_budget, remaining)
319 executor = ThreadPoolExecutor(max_workers=len(targets))
320 futures = {
321 (
322 http.submit_with_context(
323 executor, _fetch_comments, item.item_id, (item.metadata or {}).get("author_id", ""), deadline,
324 )
325 if deadline is not None
326 else http.submit_with_context(
327 executor, _fetch_comments, item.item_id, (item.metadata or {}).get("author_id", ""),
328 )
329 ): item
330 for item in targets
331 }
332 try:
333 for future in as_completed(futures, timeout=wait_budget):
334 item = futures[future]
335 item.metadata["top_comments"] = _remap_comments(
336 future.result(),
337 score_keys=("likes",),
338 excerpt_keys=("text", "excerpt"),
339 )
340 except FuturesTimeout:
341 _log("comment enrichment hit its time limit; keeping the comments that arrived")
342 finally:
343 # Never block report finalization on a straggling comment fetch.
344 executor.shutdown(wait=False, cancel_futures=True)
345 attached = sum(1 for item in targets if item.metadata.get("top_comments"))
346 _log(f"attached comments to {attached} of {len(targets)} top articles")
347 return items
348
348 lines PYTHON