返回 last30days-skill
xiaohongshu_api.py
根目录 / skills / last30days / scripts / lib / xiaohongshu_api.py
1 """Xiaohongshu HTTP API search client for last30days.
2
3 Uses xpzouying/xiaohongshu-mcp REST endpoints:
4 - GET/POST /api/v1/feeds/search
5 - GET /api/v1/login/status
6 """
7
8 from datetime import datetime, timezone
9 import ipaddress
10 from typing import Any, Callable, Dict, List, Optional
11 from urllib.parse import urlsplit, urlunsplit
12
13 from . import http, public_host
14
15 _BLOCKED_METADATA_HOSTS = frozenset({
16 "metadata",
17 "metadata.google.internal",
18 "metadata.goog",
19 "metadata.azure.internal",
20 "metadata.tencentyun.com",
21 "metadata.packet.net",
22 "metadata.platformequinix.com",
23 "instance-data",
24 "instance-data.ec2.internal",
25 })
26 _BLOCKED_METADATA_IPS = frozenset({
27 ipaddress.ip_address("100.100.100.200"),
28 ipaddress.ip_address("fd00:ec2::254"),
29 })
30 _NAT64_WELL_KNOWN = ipaddress.IPv6Network("64:ff9b::/96")
31 _NAT64_LOCAL = ipaddress.IPv6Network("64:ff9b:1::/48")
32
33
34 def _is_blocked_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
35 if (
36 ip in _BLOCKED_METADATA_IPS
37 or ip.is_link_local
38 or ip.is_unspecified
39 or ip.is_multicast
40 ):
41 return True
42 if isinstance(ip, ipaddress.IPv6Address):
43 for embedded in (
44 ip.ipv4_mapped,
45 ip.sixtofour,
46 ip.teredo[1] if ip.teredo else None,
47 ):
48 if embedded is not None and _is_blocked_ip(embedded):
49 return True
50 if ip in _NAT64_WELL_KNOWN or ip in _NAT64_LOCAL:
51 embedded = ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF)
52 if _is_blocked_ip(embedded):
53 return True
54 return False
55
56
57 def _is_local_bridge_host(
58 host: str,
59 ip: ipaddress.IPv4Address | ipaddress.IPv6Address | None,
60 ) -> bool:
61 if ip is not None:
62 return http._is_local_bridge_ip(ip)
63 return (
64 host == "localhost"
65 or host.endswith(".localhost")
66 or host in ("host.docker.internal", "gateway.docker.internal")
67 or host.endswith(".local")
68 or "." not in host
69 )
70
71
72 def _validate_base_url(base_url: Any) -> tuple[str, bool]:
73 """Validate XIAOHONGSHU_API_BASE and return ``(normalized_base, is_local_bridge)``.
74
75 Permits local/Docker/LAN self-hosted bridges over http(s) and remote bridges
76 over https:// while rejecting non-http(s) schemes, cloud metadata endpoints,
77 cleartext public internet URLs, embedded credentials, queries, and fragments.
78 """
79 if not isinstance(base_url, str) or not base_url.strip():
80 raise ValueError("Missing Xiaohongshu API base URL")
81 raw = base_url.strip()
82 if any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in raw):
83 raise ValueError("Invalid Xiaohongshu API base URL")
84 try:
85 parts = urlsplit(raw)
86 port = parts.port
87 except ValueError as exc:
88 raise ValueError("Invalid Xiaohongshu API base URL") from exc
89
90 scheme = parts.scheme.lower()
91 if scheme not in ("http", "https"):
92 raise ValueError(f"Unsupported Xiaohongshu API base URL scheme: {scheme or '<empty>'}")
93 if parts.username is not None or parts.password is not None:
94 raise ValueError("Xiaohongshu API base URL must not contain embedded credentials")
95 if "\\" in parts.netloc:
96 raise ValueError("Invalid Xiaohongshu API base URL")
97 if port is not None and not (1 <= port <= 65535):
98 raise ValueError("Invalid Xiaohongshu API base URL port")
99 if parts.query or parts.fragment:
100 raise ValueError("Xiaohongshu API base URL must not contain query or fragment")
101
102 lower_path = parts.path.lower()
103 if ".." in parts.path.split("/") or any(tok in lower_path for tok in ("%2e", "%2f", "%5c")):
104 raise ValueError("Invalid Xiaohongshu API base URL path")
105
106 host = (parts.hostname or "").removesuffix(".").lower()
107 if not host or host.startswith(".") or host.endswith(".") or ".." in host:
108 raise ValueError("Missing hostname in Xiaohongshu API base URL")
109 if host in _BLOCKED_METADATA_HOSTS or host.endswith(".metadata.google.internal"):
110 raise ValueError("Refused cloud metadata host in Xiaohongshu API base URL")
111
112 ip = public_host._parse_ip_literal(host)
113 if ip is not None and _is_blocked_ip(ip):
114 raise ValueError("Refused blocked IP address in Xiaohongshu API base URL")
115
116 is_local_bridge = _is_local_bridge_host(host, ip)
117 if scheme == "http" and not is_local_bridge:
118 raise ValueError("Xiaohongshu API base URL must use https:// for remote hosts")
119
120 normalized = urlunsplit((scheme, parts.netloc, parts.path.rstrip("/"), "", ""))
121 return normalized, is_local_bridge
122
123
124 def _same_origin_redirect_guard(base_url: str) -> Callable[[str], bool]:
125 expected_origin = http._request_origin(base_url)
126
127 def _guard(newurl: str) -> bool:
128 if not isinstance(newurl, str) or not newurl or newurl != newurl.strip():
129 return False
130 if any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in newurl):
131 return False
132 try:
133 parts = urlsplit(newurl)
134 _ = parts.port
135 except ValueError:
136 return False
137 if parts.username is not None or parts.password is not None or "\\" in parts.netloc:
138 return False
139 return http._request_origin(newurl) == expected_origin
140
141 return _guard
142
143
144 def _to_int(value: Any) -> int:
145 """Convert Xiaohongshu count strings to int.
146
147 Supports plain ints and Chinese suffixes like 1.2万 / 3亿.
148 """
149 if value is None:
150 return 0
151 if isinstance(value, (int, float)):
152 return int(value)
153
154 text = str(value).strip().lower().replace(",", "")
155 if not text:
156 return 0
157
158 try:
159 if text.endswith("万"):
160 return int(float(text[:-1]) * 10000)
161 if text.endswith("亿"):
162 return int(float(text[:-1]) * 100000000)
163 return int(float(text))
164 except (TypeError, ValueError):
165 return 0
166
167
168 def _timestamp_to_date_ms(ts: Any) -> Optional[str]:
169 """Convert millisecond timestamp to YYYY-MM-DD."""
170 try:
171 iv = int(ts)
172 if iv <= 0:
173 return None
174 # API examples use milliseconds.
175 dt = datetime.fromtimestamp(iv / 1000.0, tz=timezone.utc)
176 return dt.strftime("%Y-%m-%d")
177 except (TypeError, ValueError, OSError):
178 return None
179
180
181 def _relevance_from_interactions(likes: int, comments: int, favorites: int) -> float:
182 """Heuristic relevance score from engagement metrics."""
183 # Weighted engagement with soft caps to [0, 1].
184 weighted = (likes * 1.0) + (comments * 2.5) + (favorites * 1.5)
185 # 5000 weighted engagement ~= strong relevance.
186 score = min(1.0, max(0.05, weighted / 5000.0))
187 return round(score, 3)
188
189
190 def _build_note_url(feed_id: str, xsec_token: str) -> str:
191 """Build a stable Xiaohongshu note URL."""
192 if xsec_token:
193 return f"https://www.xiaohongshu.com/explore/{feed_id}?xsec_token={xsec_token}"
194 return f"https://www.xiaohongshu.com/explore/{feed_id}"
195
196
197 def _request_options(base_url: Any) -> tuple[str, Dict[str, Any]]:
198 """Validate ``base_url`` and build pinned HTTP kwargs for Xiaohongshu requests."""
199 base, is_local_bridge = _validate_base_url(base_url)
200 req_kwargs: Dict[str, Any] = {
201 "redirect_guard": _same_origin_redirect_guard(base),
202 }
203 if is_local_bridge:
204 req_kwargs["local_bridge_only"] = True
205 else:
206 req_kwargs["public_only"] = True
207 return base, req_kwargs
208
209
210 def search_feeds(
211 topic: str,
212 from_date: str,
213 to_date: str,
214 base_url: str,
215 depth: str = "default",
216 ) -> List[Dict[str, Any]]:
217 """Search Xiaohongshu feeds and normalize to web-item shape."""
218 base, req_kwargs = _request_options(base_url)
219
220 # Quick login sanity check.
221 login = http.get(f"{base}/api/v1/login/status", timeout=8, retries=1, **req_kwargs)
222 login_data = login.get("data") if isinstance(login, dict) else None
223 is_logged_in = (
224 bool(login_data.get("is_logged_in"))
225 if isinstance(login_data, dict) else False
226 )
227 if not is_logged_in:
228 raise http.HTTPError("Xiaohongshu API reachable but not logged in")
229
230 # API supports filters; use recency-oriented defaults.
231 publish_time = "一天内" if depth == "quick" else "一周内" if depth == "default" else "半年内"
232 payload = {
233 "keyword": topic,
234 "filters": {
235 "sort_by": "综合",
236 "note_type": "不限",
237 "publish_time": publish_time,
238 "search_scope": "不限",
239 "location": "不限",
240 },
241 }
242
243 resp = http.post(f"{base}/api/v1/feeds/search", payload, timeout=20, retries=1, **req_kwargs)
244 resp_data = resp.get("data") if isinstance(resp, dict) else None
245 feeds = resp_data.get("feeds") if isinstance(resp_data, dict) else []
246 if not isinstance(feeds, list):
247 feeds = []
248
249 # Cap source volume similarly to other web sources.
250 limit = {"quick": 8, "default": 15, "deep": 25}.get(depth, 15)
251 items: List[Dict[str, Any]] = []
252
253 for i, feed in enumerate(feeds[:limit]):
254 if not isinstance(feed, dict):
255 continue
256 note = feed.get("noteCard") or {}
257 if not isinstance(note, dict):
258 note = {}
259 interact = note.get("interactInfo") or {}
260 if not isinstance(interact, dict):
261 interact = {}
262
263 feed_id = str(feed.get("id") or note.get("noteId") or "").strip()
264 if not feed_id:
265 continue
266
267 xsec_token = str(feed.get("xsecToken") or note.get("xsecToken") or "").strip()
268 title = str(
269 note.get("displayTitle")
270 or note.get("title")
271 or ""
272 ).strip()
273 snippet = str(
274 note.get("desc")
275 or note.get("displayDesc")
276 or title
277 or ""
278 ).strip()
279
280 likes = _to_int(interact.get("likedCount"))
281 comments = _to_int(interact.get("commentCount"))
282 favorites = _to_int(interact.get("collectedCount"))
283
284 date_value = _timestamp_to_date_ms(note.get("time"))
285 why = f"Xiaohongshu engagement: likes={likes}, comments={comments}, favorites={favorites}"
286
287 items.append({
288 "id": f"XHS{i+1}",
289 "title": title[:200] if title else f"Xiaohongshu note {feed_id}",
290 "url": _build_note_url(feed_id, xsec_token),
291 "source_domain": "xiaohongshu.com",
292 "snippet": snippet[:500],
293 "date": date_value,
294 "date_confidence": "high" if date_value else "low",
295 "relevance": _relevance_from_interactions(likes, comments, favorites),
296 "why_relevant": why,
297 # Keep raw engagement for debugging/possible future rendering.
298 "engagement": {
299 "likes": likes,
300 "comments": comments,
301 "favorites": favorites,
302 },
303 })
304
305 return items
306
306 lines PYTHON