Skip to content

Give your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.

fix(v2ex): encode caller values in URLs

SEPURI-SAI-KRISHNA544e0e76f2cc
diff --git a/agent_reach/channels/v2ex.py b/agent_reach/channels/v2ex.py
index 0b4c6967..d11d2455 100644
--- a/agent_reach/channels/v2ex.py
+++ b/agent_reach/channels/v2ex.py
@@ -7,7 +7,7 @@ import ssl
import subprocess
import urllib.request
from typing import Any
-from urllib.parse import urlsplit
+from urllib.parse import quote, urlencode, urlsplit
from agent_reach.utils.process import utf8_subprocess_env
from agent_reach.utils.text import scrub_url_credentials
@@ -17,6 +17,12 @@ from .base import Channel
_UA = "agent-reach/1.0"
_TIMEOUT = 10
_MAX_RESPONSE_BYTES = 1024 * 1024
+_API_BASE = "https://www.v2ex.com"
+
+
+def _v2ex_url(path: str, **params: Any) -> str:
+ """Build a V2EX URL without letting caller values alter its query."""
+ return f"{_API_BASE}{path}?{urlencode(params)}"
def _validate_api_url(url: str) -> None:
@@ -203,9 +209,10 @@ class V2EXChannel(Channel):
Returns a list of dicts with keys:
title, url, replies, node_name, node_title, content
"""
- url = (
- f"https://www.v2ex.com/api/topics/show.json"
- f"?node_name={node_name}&page=1"
+ url = _v2ex_url(
+ "/api/topics/show.json",
+ node_name=node_name,
+ page=1,
)
data = _get_json(url)
results = []
@@ -237,7 +244,7 @@ class V2EXChannel(Channel):
author, created, replies (list of dicts with: author, content, created)
"""
topic_data = _get_json(
- f"https://www.v2ex.com/api/topics/show.json?id={topic_id}"
+ _v2ex_url("/api/topics/show.json", id=topic_id)
)
# API returns a list even for single-ID queries
if isinstance(topic_data, list):
@@ -251,8 +258,11 @@ class V2EXChannel(Channel):
# Fetch replies (first page)
try:
replies_raw = _get_json(
- f"https://www.v2ex.com/api/replies/show.json"
- f"?topic_id={topic_id}&page=1"
+ _v2ex_url(
+ "/api/replies/show.json",
+ topic_id=topic_id,
+ page=1,
+ )
)
except Exception:
replies_raw = []
@@ -269,7 +279,10 @@ class V2EXChannel(Channel):
return {
"id": topic.get("id", topic_id),
"title": topic.get("title", ""),
- "url": topic.get("url", f"https://www.v2ex.com/t/{topic_id}"),
+ "url": topic.get(
+ "url",
+ f"{_API_BASE}/t/{quote(str(topic_id), safe='')}",
+ ),
"content": topic.get("content", ""),
"replies_count": topic.get("replies", 0),
"node_name": node.get("name", ""),
@@ -290,12 +303,15 @@ class V2EXChannel(Channel):
location, bio, avatar, created
"""
data = _get_json(
- f"https://www.v2ex.com/api/members/show.json?username={username}"
+ _v2ex_url("/api/members/show.json", username=username)
)
return {
"id": data.get("id", 0),
"username": data.get("username", username),
- "url": data.get("url", f"https://www.v2ex.com/member/{username}"),
+ "url": data.get(
+ "url",
+ f"{_API_BASE}/member/{quote(str(username), safe='')}",
+ ),
"website": data.get("website", ""),
"twitter": data.get("twitter", ""),
"psn": data.get("psn", ""),
@@ -320,11 +336,12 @@ class V2EXChannel(Channel):
list of dicts with keys: title, url, snippet
如果搜索不可用,返回包含单条 {"error": str} 的列表。
"""
+ search_url = _v2ex_url("/", q=query)
return [
{
"error": (
"V2EX 公开 API 不提供搜索端点。"
- f"建议改用:https://www.v2ex.com/?q={query} "
+ f"建议改用:{search_url} "
"或通过 Exa channel 使用 site:v2ex.com 搜索。"
)
}
diff --git a/tests/test_v2ex_channel.py b/tests/test_v2ex_channel.py
index 7964fa81..4704c09a 100644
--- a/tests/test_v2ex_channel.py
+++ b/tests/test_v2ex_channel.py
@@ -16,6 +16,7 @@ import ssl
import subprocess
from unittest.mock import patch
from urllib.error import URLError
+from urllib.parse import parse_qs, urlsplit
import pytest
@@ -186,6 +187,28 @@ def test_get_node_topics_falls_back_to_requested_node_name():
assert topics[0]["node_name"] == "jobs"
+ "node_name",
+ ["python&page=99", "foo#bar", "c++", "Python 开发"],
+)
+def test_get_node_topics_percent_encodes_node_name(node_name):
+ ch = V2EXChannel()
+ captured = {}
+
+ def fake_get_json(url):
+ captured["url"] = url
+ return []
+
+ with patch.object(v2, "_get_json", side_effect=fake_get_json):
+ ch.get_node_topics(node_name)
+
+ parts = urlsplit(captured["url"])
+ query = parse_qs(parts.query)
+ assert parts.fragment == ""
+ assert query["node_name"] == [node_name]
+ assert query["page"] == ["1"]
+
+
# --- get_topic: list-or-dict shape + replies fetch + fallbacks ---
def test_get_topic_unwraps_list_and_maps_replies():
@@ -226,6 +249,26 @@ def test_get_topic_url_fallback_when_missing():
assert result["url"] == "https://www.v2ex.com/t/99"
+def test_get_topic_percent_encodes_topic_id_in_both_requests():
+ ch = V2EXChannel()
+ captured = []
+
+ def fake_get_json(url):
+ captured.append(url)
+ return [{"id": 1}] if len(captured) == 1 else []
+
+ with patch.object(v2, "_get_json", side_effect=fake_get_json):
+ ch.get_topic("1#&page=99")
+
+ topic_parts = urlsplit(captured[0])
+ replies_parts = urlsplit(captured[1])
+ assert topic_parts.fragment == ""
+ assert replies_parts.fragment == ""
+ assert parse_qs(topic_parts.query)["id"] == ["1#&page=99"]
+ assert parse_qs(replies_parts.query)["topic_id"] == ["1#&page=99"]
+ assert parse_qs(replies_parts.query)["page"] == ["1"]
+
+
# --- get_user: field mapping + avatar/url fallbacks ---
def test_get_user_maps_fields_and_prefers_large_avatar():
@@ -250,6 +293,33 @@ def test_get_user_avatar_falls_back_to_normal():
assert user["url"] == "https://www.v2ex.com/member/neo"
+def test_get_user_percent_encodes_username():
+ ch = V2EXChannel()
+ captured = {}
+
+ def fake_get_json(url):
+ captured["url"] = url
+ return {}
+
+ with patch.object(v2, "_get_json", side_effect=fake_get_json):
+ ch.get_user("张三&admin=true")
+
+ parts = urlsplit(captured["url"])
+ assert parts.fragment == ""
+ assert parse_qs(parts.query)["username"] == ["张三&admin=true"]
+
+
+def test_fallback_display_urls_percent_encode_path_segments():
+ ch = V2EXChannel()
+ with patch.object(v2, "_get_json", return_value={}):
+ user_url = ch.get_user("a b/c")["url"]
+ with patch.object(v2, "_get_json", side_effect=[{}, []]):
+ topic_url = ch.get_topic("9 9")["url"]
+
+ assert user_url == "https://www.v2ex.com/member/a%20b%2Fc"
+ assert topic_url == "https://www.v2ex.com/t/9%209"
+
+
# --- search: intentionally offline (no public search endpoint) ---
def test_search_returns_guidance_without_network():
@@ -259,3 +329,11 @@ def test_search_returns_guidance_without_network():
assert len(results) == 1
assert "error" in results[0]
assert "python" in results[0]["error"]
+
+
+def test_search_guidance_percent_encodes_query():
+ ch = V2EXChannel()
+ message = ch.search("rust & go#lang")[0]["error"]
+
+ assert "?q=rust+%26+go%23lang" in message
+ assert "?q=rust & go#lang" not in message