@duanz/pi-d-reach 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/SKILL.md +480 -0
- package/fanout-defaults.example.json +33 -0
- package/package.json +52 -4
- package/plugin/index.ts +4097 -0
- package/plugin/pwa.ts +1078 -0
- package/plugin/scripts/fanout.sh +1944 -0
- package/plugin/scripts/load_key.sh +36 -0
- package/plugin/scripts/mcp_call.py +137 -0
- package/plugin/scripts/pdf2text.py +39 -0
- package/plugin/scripts/quota.py +281 -0
- package/plugin/scripts/quota_probe.py +272 -0
- package/plugin/scripts/render.mjs +234 -0
- package/plugin/scripts/route_config.py +156 -0
- package/references/channels.md +226 -0
- package/references/cn-reach.md +153 -0
- package/references/dev.md +65 -0
- package/references/finance.md +84 -0
- package/references/scrape.md +283 -0
- package/references/search.md +308 -0
- package/references/social.md +76 -0
- package/references/video.md +82 -0
- package/scripts/fanout.sh +1944 -0
- package/scripts/load_key.sh +36 -0
- package/scripts/mcp_call.py +137 -0
- package/scripts/quota.py +281 -0
- package/scripts/quota_probe.py +272 -0
- package/scripts/route_config.py +156 -0
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""D-Reach 额度官方校准(quota probe)。
|
|
3
|
+
|
|
4
|
+
本地 quota.json 记的是「我们发过几次请求」,不是「厂商还剩多少」。
|
|
5
|
+
本脚本去各家官方接口取真实额度,写进 quota.json 的 `_official` 段,
|
|
6
|
+
不覆盖本地计数 —— 两者互为校验:本地计数漏记时,官方数字能纠回来。
|
|
7
|
+
|
|
8
|
+
quota_probe.py 校准并打印人类可读结果
|
|
9
|
+
quota_probe.py --json 机器可读
|
|
10
|
+
quota_probe.py --quiet fanout 结束时静默调用(只在异常时出声)
|
|
11
|
+
|
|
12
|
+
已确认可查(2026-10-28 实测):
|
|
13
|
+
firecrawl GET /v2/team/credit-usage → remainingCredits / planCredits / 账期
|
|
14
|
+
tinyfish MCP get_wallet → 钱包余额(search/fetch 本身 $0)
|
|
15
|
+
未开放 / 权限不足(如实记录,不猜):
|
|
16
|
+
brightdata token 无 account 读权限(/customer/balance 403)
|
|
17
|
+
exa 官方团队接口需申请 access
|
|
18
|
+
jina 只有 dashboard,无公开额度 API
|
|
19
|
+
langsearch 官方只给 token 日额度,无查询端点
|
|
20
|
+
"""
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
import sys
|
|
25
|
+
import time
|
|
26
|
+
import urllib.request
|
|
27
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
28
|
+
from datetime import datetime, timezone
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
FILE = Path(os.environ.get("D_REACH_QUOTA_FILE") or Path.home() / ".agent-reach/quota.json")
|
|
32
|
+
KEY_SH = Path(__file__).with_name("load_key.sh")
|
|
33
|
+
TIMEOUT = 12
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def key(name):
|
|
37
|
+
"""走 load_key.sh,与全技能同一条查找链(env → ~/.config/agents/env → .env)。"""
|
|
38
|
+
import subprocess
|
|
39
|
+
try:
|
|
40
|
+
out = subprocess.run(
|
|
41
|
+
["sh", str(KEY_SH), name, ""],
|
|
42
|
+
capture_output=True, text=True, timeout=8,
|
|
43
|
+
)
|
|
44
|
+
return out.stdout.strip() or None
|
|
45
|
+
except Exception:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _get(url, headers):
|
|
50
|
+
req = urllib.request.Request(url, headers=headers)
|
|
51
|
+
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
|
52
|
+
return json.loads(r.read().decode("utf-8", "replace"))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def probe_firecrawl():
|
|
56
|
+
k = key("FIRECRAWL_API_KEY")
|
|
57
|
+
if not k:
|
|
58
|
+
return {"state": "no_key"}
|
|
59
|
+
d = _get("https://api.firecrawl.dev/v2/team/credit-usage",
|
|
60
|
+
{"Authorization": f"Bearer {k}"})
|
|
61
|
+
box = d.get("data") or {}
|
|
62
|
+
return {
|
|
63
|
+
"state": "ok",
|
|
64
|
+
"remaining": box.get("remainingCredits"),
|
|
65
|
+
"total": box.get("planCredits"),
|
|
66
|
+
"period_start": box.get("billingPeriodStart"),
|
|
67
|
+
"period_end": box.get("billingPeriodEnd"),
|
|
68
|
+
"source": "api:/v2/team/credit-usage",
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def probe_tinyfish():
|
|
73
|
+
"""TinyFish 走 hosted MCP:initialize 拿 session,再调 get_wallet。"""
|
|
74
|
+
k = key("TINYFISH_API_KEY")
|
|
75
|
+
if not k:
|
|
76
|
+
return {"state": "no_key"}
|
|
77
|
+
url = "https://agent.tinyfish.ai/mcp"
|
|
78
|
+
|
|
79
|
+
def rpc(payload, sid=None):
|
|
80
|
+
hdr = {"Content-Type": "application/json",
|
|
81
|
+
"Accept": "application/json, text/event-stream",
|
|
82
|
+
"X-API-Key": k}
|
|
83
|
+
if sid:
|
|
84
|
+
hdr["Mcp-Session-Id"] = sid
|
|
85
|
+
req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers=hdr)
|
|
86
|
+
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
|
87
|
+
raw = r.read().decode("utf-8", "replace")
|
|
88
|
+
return dict(r.headers), raw
|
|
89
|
+
|
|
90
|
+
hdrs, _ = rpc({"jsonrpc": "2.0", "id": 1, "method": "initialize",
|
|
91
|
+
"params": {"protocolVersion": "2024-11-05", "capabilities": {},
|
|
92
|
+
"clientInfo": {"name": "d-reach-probe", "version": "1"}}})
|
|
93
|
+
sid = hdrs.get("Mcp-Session-Id") or hdrs.get("mcp-session-id")
|
|
94
|
+
_, raw = rpc({"jsonrpc": "2.0", "id": 2, "method": "tools/call",
|
|
95
|
+
"params": {"name": "get_wallet", "arguments": {}}}, sid)
|
|
96
|
+
m = re.search(r"\{.*\}", raw, re.S)
|
|
97
|
+
if not m:
|
|
98
|
+
return {"state": "error", "error": "响应里没有 JSON"}
|
|
99
|
+
body = json.loads(m.group(0))
|
|
100
|
+
text = ""
|
|
101
|
+
for c in (body.get("result") or {}).get("content") or []:
|
|
102
|
+
if c.get("type") == "text":
|
|
103
|
+
text = c.get("text") or ""
|
|
104
|
+
break
|
|
105
|
+
try:
|
|
106
|
+
wallet = json.loads(text)
|
|
107
|
+
except Exception:
|
|
108
|
+
return {"state": "error", "error": "wallet 解析失败"}
|
|
109
|
+
return {
|
|
110
|
+
"state": "ok",
|
|
111
|
+
"balance": wallet.get("available_balance"),
|
|
112
|
+
"currency": wallet.get("currency"),
|
|
113
|
+
"as_of": wallet.get("as_of"),
|
|
114
|
+
"source": "mcp:get_wallet",
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def probe_brightdata():
|
|
119
|
+
k = key("BRIGHTDATA_APITOKEN")
|
|
120
|
+
if not k:
|
|
121
|
+
return {"state": "no_key"}
|
|
122
|
+
try:
|
|
123
|
+
_get("https://api.brightdata.com/customer/balance", {"Authorization": f"Bearer {k}"})
|
|
124
|
+
return {"state": "ok", "source": "api:/customer/balance"}
|
|
125
|
+
except urllib.error.HTTPError as e:
|
|
126
|
+
if e.code in (401, 403):
|
|
127
|
+
return {"state": "no_permission",
|
|
128
|
+
"error": "token 没有 account 读取权限(在控制台 Settings→Users 勾选后再试)"}
|
|
129
|
+
return {"state": "error", "error": f"HTTP {e.code}"}
|
|
130
|
+
except Exception as e:
|
|
131
|
+
return {"state": "error", "error": str(e)[:80]}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def unimplemented(reason):
|
|
135
|
+
return {"state": "unavailable", "error": reason}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def probe_zhihu():
|
|
139
|
+
"""知乎开放平台:/api/v1/quota 一次拿到全部 9 项能力当日限免额度,不消耗业务额度。"""
|
|
140
|
+
k = key("ZHIHU_SEARCH_API_KEY")
|
|
141
|
+
if not k:
|
|
142
|
+
return {"state": "no_key"}
|
|
143
|
+
d = _get("https://developer.zhihu.com/api/v1/quota",
|
|
144
|
+
{"Authorization": f"Bearer {k}", "X-Request-Timestamp": str(int(time.time()))})
|
|
145
|
+
if d.get("Code") not in (0, None):
|
|
146
|
+
return {"state": "error", "error": f'{d.get("Code")}: {d.get("Message")}'}
|
|
147
|
+
items = [
|
|
148
|
+
{
|
|
149
|
+
"id": it.get("APIID"),
|
|
150
|
+
"name": it.get("APIName"),
|
|
151
|
+
"total": it.get("TotalQuota"),
|
|
152
|
+
"used": it.get("TotalUsed"),
|
|
153
|
+
"remaining": it.get("RemainingQuota"),
|
|
154
|
+
}
|
|
155
|
+
for it in (d.get("Data") or [])
|
|
156
|
+
]
|
|
157
|
+
return {"state": "ok", "items": items, "source": "api:/api/v1/quota"}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
PROBES = {
|
|
161
|
+
"firecrawl": probe_firecrawl,
|
|
162
|
+
"tinyfish": probe_tinyfish,
|
|
163
|
+
"zhihu": probe_zhihu,
|
|
164
|
+
"exa": lambda: unimplemented("官方 usage 接口需向 support 申请 access,默认不可用"),
|
|
165
|
+
"jina_reader": lambda: unimplemented("只有 dashboard 看余额,没有公开额度 API"),
|
|
166
|
+
"langsearch": lambda: unimplemented("官方只给 token 日额度,没有查询端点"),
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def load():
|
|
171
|
+
try:
|
|
172
|
+
return json.loads(FILE.read_text())
|
|
173
|
+
except Exception:
|
|
174
|
+
return {}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def save(d):
|
|
178
|
+
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
179
|
+
tmp = FILE.with_suffix(FILE.suffix + ".tmp")
|
|
180
|
+
tmp.write_text(json.dumps(d, indent=2))
|
|
181
|
+
tmp.replace(FILE)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def run(max_age=0):
|
|
185
|
+
"""max_age>0 时:如果上次校准已在 N 秒内,直接复用,不重复请求厂商接口。"""
|
|
186
|
+
if max_age:
|
|
187
|
+
old = (load().get("_official") or {})
|
|
188
|
+
stamps = [v.get("probed_at") for v in old.values() if v.get("state") == "ok"]
|
|
189
|
+
if stamps:
|
|
190
|
+
try:
|
|
191
|
+
last = max(datetime.fromisoformat(t) for t in stamps)
|
|
192
|
+
if (datetime.now(timezone.utc) - last).total_seconds() < max_age:
|
|
193
|
+
return old
|
|
194
|
+
except Exception:
|
|
195
|
+
pass
|
|
196
|
+
with ThreadPoolExecutor(max_workers=len(PROBES)) as ex:
|
|
197
|
+
futs = {name: ex.submit(fn) for name, fn in PROBES.items()}
|
|
198
|
+
out = {}
|
|
199
|
+
for name, fut in futs.items():
|
|
200
|
+
try:
|
|
201
|
+
out[name] = fut.result()
|
|
202
|
+
except Exception as e:
|
|
203
|
+
out[name] = {"state": "error", "error": str(e)[:100]}
|
|
204
|
+
stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
205
|
+
for v in out.values():
|
|
206
|
+
v["probed_at"] = stamp
|
|
207
|
+
d = load()
|
|
208
|
+
d["_official"] = out
|
|
209
|
+
save(d)
|
|
210
|
+
return out
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def render(out, as_json=False):
|
|
214
|
+
if as_json:
|
|
215
|
+
print(json.dumps(out, indent=2, ensure_ascii=False))
|
|
216
|
+
return
|
|
217
|
+
lines = []
|
|
218
|
+
for name, v in out.items():
|
|
219
|
+
st = v.get("state")
|
|
220
|
+
if st == "ok":
|
|
221
|
+
if name == "firecrawl":
|
|
222
|
+
rem, tot = v.get("remaining"), v.get("total")
|
|
223
|
+
pct = f"({rem / tot * 100:.0f}% 剩余)" if rem is not None and tot else ""
|
|
224
|
+
lines.append(f" {name:12s} ✅ 剩余 {rem}/{tot} credits{pct} 账期至 {str(v.get('period_end'))[:10]}")
|
|
225
|
+
elif name == "tinyfish":
|
|
226
|
+
lines.append(f" {name:12s} ✅ 钱包 {v.get('balance')} {v.get('currency')}(search/fetch 本身 $0)")
|
|
227
|
+
elif name == "zhihu":
|
|
228
|
+
parts = [f"{i.get('name')} {i.get('remaining')}/{i.get('total')}"
|
|
229
|
+
for i in (v.get("items") or [])]
|
|
230
|
+
lines.append(f" {name:12s} ✅ " + " · ".join(parts) + "(当日限免)")
|
|
231
|
+
else:
|
|
232
|
+
lines.append(f" {name:12s} ✅ {v.get('source')}")
|
|
233
|
+
elif st == "no_key":
|
|
234
|
+
lines.append(f" {name:12s} 🔇 未配置 key")
|
|
235
|
+
elif st == "unavailable":
|
|
236
|
+
lines.append(f" {name:12s} ⚪ 无公开接口:{v.get('error')}")
|
|
237
|
+
elif st == "no_permission":
|
|
238
|
+
lines.append(f" {name:12s} ⚠️ {v.get('error')}")
|
|
239
|
+
else:
|
|
240
|
+
lines.append(f" {name:12s} ❌ {v.get('error')}")
|
|
241
|
+
print("官方额度校准(写入 quota.json 的 _official 段)")
|
|
242
|
+
print("\n".join(lines))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def main(argv):
|
|
246
|
+
as_json = "--json" in argv
|
|
247
|
+
quiet = "--quiet" in argv
|
|
248
|
+
max_age = 600 if quiet else 0 # fanout 高频调用时 10 分钟内复用上次结果
|
|
249
|
+
for i, a in enumerate(argv):
|
|
250
|
+
if a == "--max-age" and i + 1 < len(argv):
|
|
251
|
+
max_age = int(argv[i + 1])
|
|
252
|
+
try:
|
|
253
|
+
out = run(max_age)
|
|
254
|
+
except Exception as e:
|
|
255
|
+
if not quiet:
|
|
256
|
+
print(f"[quota_probe] 校准失败:{e}", file=sys.stderr)
|
|
257
|
+
return 1
|
|
258
|
+
if not quiet:
|
|
259
|
+
render(out, as_json)
|
|
260
|
+
else:
|
|
261
|
+
ok = [k for k, v in out.items() if v.get("state") == "ok"]
|
|
262
|
+
# 只报还在 PROBES 里的通道 —— 已退役的(如 brightdata)留在 quota.json 里的
|
|
263
|
+
# 旧异常不该每轮都喊一次
|
|
264
|
+
bad = [k for k, v in out.items()
|
|
265
|
+
if k in PROBES and v.get("state") in ("error", "no_permission")]
|
|
266
|
+
if bad:
|
|
267
|
+
print(f"[quota_probe] 校准异常:{', '.join(bad)}(其余 {len(ok)} 家正常)", file=sys.stderr)
|
|
268
|
+
return 0
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
if __name__ == "__main__":
|
|
272
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 本地 Playwright 渲染档(d_reach_fetch 的免费真渲染兜底)。
|
|
4
|
+
*
|
|
5
|
+
* 为什么单独一个进程:扩展由 pi 用 TS 加载,直接 import playwright 会撞模块解析;
|
|
6
|
+
* 起子进程最省事,也让「没装 playwright」变成可判定的 fail class 而不是崩溃。
|
|
7
|
+
*
|
|
8
|
+
* 用法:node render.mjs <url>
|
|
9
|
+
* 输出:单行 JSON { ok, text, html, chars, lines, avgLine, linkDen, finalUrl, ms, err }
|
|
10
|
+
* - text 是正文(优先 article/main/#js_content,退回 body.innerText),保留换行
|
|
11
|
+
* - html 只截前 200KB,够做站点标记判定
|
|
12
|
+
* - lines / avgLine / linkDen 是「骨架页」判据,调用方据此拒绝假装成功
|
|
13
|
+
* - finalUrl 是跳转后的真实地址,登录墙(passport./login./sso.)靠它识别
|
|
14
|
+
*/
|
|
15
|
+
import { pathToFileURL } from "node:url";
|
|
16
|
+
|
|
17
|
+
const url = process.argv[2];
|
|
18
|
+
if (!url) {
|
|
19
|
+
console.log(JSON.stringify({ ok: false, err: "no_url" }));
|
|
20
|
+
process.exit(0);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const UA =
|
|
24
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36";
|
|
25
|
+
|
|
26
|
+
// 微信正文是服务端渲染的,但部分站点要等 XHR 回填,统一给一个短的静默窗口
|
|
27
|
+
const SETTLE_MS = 1200;
|
|
28
|
+
const TIMEOUT_MS = 25_000;
|
|
29
|
+
|
|
30
|
+
// ESM 的 package 解析不认 NODE_PATH,得自己找全局安装位置
|
|
31
|
+
async function loadChromium() {
|
|
32
|
+
const candidates = [
|
|
33
|
+
"playwright",
|
|
34
|
+
...(process.env.DREACH_PLAYWRIGHT ? [process.env.DREACH_PLAYWRIGHT] : []),
|
|
35
|
+
`${process.env.HOME}/.npm-global/lib/node_modules/playwright/index.mjs`,
|
|
36
|
+
"/usr/lib/node_modules/playwright/index.mjs",
|
|
37
|
+
"/usr/local/lib/node_modules/playwright/index.mjs",
|
|
38
|
+
];
|
|
39
|
+
let last;
|
|
40
|
+
for (const c of candidates) {
|
|
41
|
+
try {
|
|
42
|
+
const spec = c.startsWith("/") ? pathToFileURL(c).href : c;
|
|
43
|
+
return (await import(spec)).chromium;
|
|
44
|
+
} catch (e) {
|
|
45
|
+
last = e;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
throw new Error(
|
|
49
|
+
`找不到 playwright(设 DREACH_PLAYWRIGHT=<...>/playwright/index.mjs):${last?.message ?? ""}`,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 取页面快照。
|
|
55
|
+
*
|
|
56
|
+
* 页面在 evaluate 途中跳转(风控页重定向到首页/验证页)时,chromium 会抛
|
|
57
|
+
* `Execution context was destroyed`。这不是抓取失败,是「取样时页面换了」,
|
|
58
|
+
* 等跳转落地后重取一次通常就正常 —— 之前直接把这个异常往上抛,豆瓣那类站必崩。
|
|
59
|
+
*/
|
|
60
|
+
async function snapshot(page) {
|
|
61
|
+
let lastErr;
|
|
62
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
63
|
+
try {
|
|
64
|
+
return await page.evaluate(() => {
|
|
65
|
+
// 真浏览器里 <noscript> 里的东西本来就该忽略。但脚本启用时浏览器把它当**原始文本**解析,
|
|
66
|
+
// innerText 会把里面的整段 JS 吐出来(实测淘宝搜索页吐了 4 万字 JS 冒充正文)。
|
|
67
|
+
document.querySelectorAll("noscript").forEach((e) => e.remove());
|
|
68
|
+
const pick = document.querySelector("article, main, #js_content");
|
|
69
|
+
const node =
|
|
70
|
+
pick && pick.innerText.trim().length > 200 ? pick : document.body;
|
|
71
|
+
const bodyText = document.body.innerText || "";
|
|
72
|
+
const links = [...document.querySelectorAll("a[href]")];
|
|
73
|
+
let linkChars = 0;
|
|
74
|
+
for (const a of links) linkChars += (a.innerText || "").trim().length;
|
|
75
|
+
const lines = bodyText
|
|
76
|
+
.split("\n")
|
|
77
|
+
.map((s) => s.trim())
|
|
78
|
+
.filter((s) => s.length > 0);
|
|
79
|
+
const totalChars = lines.reduce((s, l) => s + l.length, 0);
|
|
80
|
+
return {
|
|
81
|
+
text: node.innerText,
|
|
82
|
+
html: document.documentElement.outerHTML.slice(0, 200_000),
|
|
83
|
+
lines: lines.length,
|
|
84
|
+
avgLine: lines.length ? totalChars / lines.length : 0,
|
|
85
|
+
// 嵌套 <a> 会让比率略微超过 1,取 min 无所谓,只要远大于 0 就是导航页
|
|
86
|
+
linkDen: bodyText.length ? linkChars / bodyText.length : 0,
|
|
87
|
+
};
|
|
88
|
+
});
|
|
89
|
+
} catch (e) {
|
|
90
|
+
lastErr = e;
|
|
91
|
+
if (
|
|
92
|
+
!/Execution context was destroyed|navigat|Target closed/i.test(
|
|
93
|
+
String(e?.message ?? e),
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
throw e;
|
|
97
|
+
await page.waitForTimeout(700);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
throw lastErr;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 把子框架(iframe)的正文拼起来。
|
|
105
|
+
*
|
|
106
|
+
* 主文档只有导航、正文在 iframe 里时,单看 body.innerText 会得到一个「骨架页」,
|
|
107
|
+
* 而页面本身并不反爬 —— 之前直接判失败。子框架读不到(跨域限制、已销毁)就跳过。
|
|
108
|
+
*/
|
|
109
|
+
// 子框架/影子树里的文本不一定可信:实测淘宝把一个 JS bundle 塞进子框架,
|
|
110
|
+
// innerText 拿到 15 万字源码冒充正文。符号密度是最便宜的区分方式(源码里 ;{}()=> 满地都是)。
|
|
111
|
+
function codey(t) {
|
|
112
|
+
const sym = (t.match(/[;{}()\[\]=<>|&$]/g) || []).length;
|
|
113
|
+
return t.length > 0 && sym / t.length > 0.04;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function shadowText(page) {
|
|
117
|
+
// innerText 不穿透 shadow root,用 Web Components 写的站点正文会整段拿不到。
|
|
118
|
+
// 递归下去把每层 shadowRoot 的文本捞出来。
|
|
119
|
+
try {
|
|
120
|
+
return await page.evaluate(() => {
|
|
121
|
+
const SKIP = new Set([
|
|
122
|
+
"STYLE",
|
|
123
|
+
"SCRIPT",
|
|
124
|
+
"TEMPLATE",
|
|
125
|
+
"NOSCRIPT",
|
|
126
|
+
"LINK",
|
|
127
|
+
"META",
|
|
128
|
+
]);
|
|
129
|
+
const out = [];
|
|
130
|
+
const collect = (root) => {
|
|
131
|
+
let s = "";
|
|
132
|
+
for (const n of root.childNodes) {
|
|
133
|
+
if (n.nodeType === 3) s += n.nodeValue || "";
|
|
134
|
+
else if (n.nodeType === 1 && !SKIP.has(n.tagName)) s += collect(n);
|
|
135
|
+
}
|
|
136
|
+
return s;
|
|
137
|
+
};
|
|
138
|
+
const walk = (root) => {
|
|
139
|
+
for (const el of root.querySelectorAll("*")) {
|
|
140
|
+
const sr = el.shadowRoot;
|
|
141
|
+
if (!sr) continue;
|
|
142
|
+
const t = collect(sr).replace(/\s+/g, " ").trim();
|
|
143
|
+
if (t.length > 40) out.push(t);
|
|
144
|
+
walk(sr);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
walk(document);
|
|
148
|
+
return out.join("\n\n");
|
|
149
|
+
});
|
|
150
|
+
} catch {
|
|
151
|
+
return "";
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function iframeText(page) {
|
|
156
|
+
const parts = [];
|
|
157
|
+
for (const frame of page.frames()) {
|
|
158
|
+
if (frame === page.mainFrame()) continue;
|
|
159
|
+
try {
|
|
160
|
+
const t = await frame.evaluate(() => document.body?.innerText ?? "");
|
|
161
|
+
if (t.trim().length > 200 && !codey(t)) parts.push(t.trim());
|
|
162
|
+
} catch {
|
|
163
|
+
/* 跨域/已卸载:正常,跳过 */
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return parts.join("\n\n");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const t0 = Date.now();
|
|
170
|
+
let browser;
|
|
171
|
+
try {
|
|
172
|
+
const chromium = await loadChromium();
|
|
173
|
+
browser = await chromium.launch({ headless: true });
|
|
174
|
+
const ctx = await browser.newContext({
|
|
175
|
+
userAgent: UA,
|
|
176
|
+
locale: "zh-CN",
|
|
177
|
+
viewport: { width: 1440, height: 900 },
|
|
178
|
+
extraHTTPHeaders: { "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8" },
|
|
179
|
+
});
|
|
180
|
+
const page = await ctx.newPage();
|
|
181
|
+
const resp = await page.goto(url, {
|
|
182
|
+
waitUntil: "domcontentloaded",
|
|
183
|
+
timeout: TIMEOUT_MS,
|
|
184
|
+
});
|
|
185
|
+
// 目标站状态码:chromium 会把 404 页照常渲染出正文,不带上这个值,
|
|
186
|
+
// 调用方只能看到「抓到了 900 字」,把错误页当文章交付。
|
|
187
|
+
const httpStatus = resp ? resp.status() : 0;
|
|
188
|
+
await page.waitForTimeout(SETTLE_MS);
|
|
189
|
+
const out = await snapshot(page);
|
|
190
|
+
let text = out.text;
|
|
191
|
+
// 正文被塞进 iframe:老政府站、招聘站、文档预览都这么干。
|
|
192
|
+
// 主文档只有导航时,把子框架的 innerText 接上。
|
|
193
|
+
if (text.trim().length < 300) {
|
|
194
|
+
const inner = await iframeText(page);
|
|
195
|
+
if (inner) text = `${text.trim()}\n\n${inner}`;
|
|
196
|
+
}
|
|
197
|
+
if (text.trim().length < 400) {
|
|
198
|
+
const sh = await shadowText(page);
|
|
199
|
+
if (!codey(sh) && sh.trim().length > text.trim().length) text = sh;
|
|
200
|
+
}
|
|
201
|
+
// 行长指标必须跟着最终的 text 走:主文档是一片导航(avgLine=2),
|
|
202
|
+
// 但把 iframe 正文接上后它就该按真实正文算,否则还会被判成「骨架页」。
|
|
203
|
+
const finalLines = text
|
|
204
|
+
.split("\n")
|
|
205
|
+
.map((s) => s.trim())
|
|
206
|
+
.filter((s) => s.length > 0);
|
|
207
|
+
const finalChars = finalLines.reduce((s, l) => s + l.length, 0);
|
|
208
|
+
console.log(
|
|
209
|
+
JSON.stringify({
|
|
210
|
+
ok: true,
|
|
211
|
+
text,
|
|
212
|
+
html: out.html,
|
|
213
|
+
chars: text.trim().length,
|
|
214
|
+
lines: finalLines.length,
|
|
215
|
+
avgLine:
|
|
216
|
+
Math.round(
|
|
217
|
+
(finalLines.length ? finalChars / finalLines.length : 0) * 10,
|
|
218
|
+
) / 10,
|
|
219
|
+
linkDen: Math.round(out.linkDen * 100) / 100,
|
|
220
|
+
finalUrl: page.url(),
|
|
221
|
+
httpStatus,
|
|
222
|
+
ms: Date.now() - t0,
|
|
223
|
+
}),
|
|
224
|
+
);
|
|
225
|
+
} catch (e) {
|
|
226
|
+
const msg = e instanceof Error ? e.message.slice(0, 200) : String(e);
|
|
227
|
+
// PDF/图片直链:chromium 不渲染,它直接开始下载
|
|
228
|
+
const err = /Download is starting/i.test(msg)
|
|
229
|
+
? "NOT_A_PAGE: 直接下载,不是网页"
|
|
230
|
+
: msg;
|
|
231
|
+
console.log(JSON.stringify({ ok: false, err, ms: Date.now() - t0 }));
|
|
232
|
+
} finally {
|
|
233
|
+
if (browser) await browser.close().catch(() => {});
|
|
234
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Canonical D-Reach default-route config parser for fanout, plugin, and gateway."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RegistryError(ValueError):
|
|
12
|
+
"""SECTIONS 与 BASE_CHANNELS / DEEP_CHANNELS 不同步 —— 是代码问题,不是配置问题。"""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def parse_routes(script_path: Path, base_arg: str, deep_arg: str):
|
|
16
|
+
source = script_path.read_text(encoding="utf-8")
|
|
17
|
+
match = re.search(r"(?ms)^SECTIONS = \[\n(.*?)^\]", source)
|
|
18
|
+
if not match:
|
|
19
|
+
raise RegistryError("Could not parse SECTIONS route registry")
|
|
20
|
+
|
|
21
|
+
entries = []
|
|
22
|
+
for entry in re.split(r"\n(?= \()", match.group(1)):
|
|
23
|
+
label = re.match(r'\s*\("([a-z]+)",\s*"([^"]+)"', entry)
|
|
24
|
+
if not label:
|
|
25
|
+
continue
|
|
26
|
+
deep = re.search(r",\s*(True|False)\s*\)", entry)
|
|
27
|
+
entries.append(
|
|
28
|
+
{
|
|
29
|
+
"key": label.group(1),
|
|
30
|
+
"name": label.group(2),
|
|
31
|
+
"tier": "deep" if deep and deep.group(1) == "True" else "base",
|
|
32
|
+
}
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
base_keys = base_arg.split()
|
|
36
|
+
deep_keys = deep_arg.split()
|
|
37
|
+
if not entries:
|
|
38
|
+
raise RegistryError("No route entries found in SECTIONS")
|
|
39
|
+
if len(set(base_keys)) != len(base_keys) or len(set(deep_keys)) != len(deep_keys):
|
|
40
|
+
raise RegistryError("Duplicate route key in BASE_CHANNELS or DEEP_CHANNELS")
|
|
41
|
+
if set(base_keys) & set(deep_keys):
|
|
42
|
+
raise RegistryError("Route key appears in both BASE_CHANNELS and DEEP_CHANNELS")
|
|
43
|
+
route_keys = {entry["key"] for entry in entries}
|
|
44
|
+
if route_keys != set(base_keys) | set(deep_keys):
|
|
45
|
+
raise RegistryError("SECTIONS does not match BASE_CHANNELS and DEEP_CHANNELS")
|
|
46
|
+
for entry in entries:
|
|
47
|
+
expected_tier = "deep" if entry["key"] in set(deep_keys) else "base"
|
|
48
|
+
if entry["tier"] != expected_tier:
|
|
49
|
+
raise RegistryError(f"Route tier mismatch for {entry['key']}")
|
|
50
|
+
return entries, base_keys, deep_keys
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def read_list(config, name, allowed):
|
|
54
|
+
values = config.get(name)
|
|
55
|
+
if not isinstance(values, list) or any(not isinstance(value, str) for value in values):
|
|
56
|
+
raise ValueError(f"{name} 必须是字符串数组")
|
|
57
|
+
|
|
58
|
+
result = []
|
|
59
|
+
allowed_set = set(allowed)
|
|
60
|
+
for raw in values:
|
|
61
|
+
value = raw.strip()
|
|
62
|
+
if not value or "," in value:
|
|
63
|
+
raise ValueError(f"{name} 每项必须是一个通道名")
|
|
64
|
+
if value not in allowed_set:
|
|
65
|
+
raise ValueError(f"{name} 含不适用的通道:{value}")
|
|
66
|
+
if value not in result:
|
|
67
|
+
result.append(value)
|
|
68
|
+
return result
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_data(script_path: Path, defaults_path: Path, base_arg: str, deep_arg: str):
|
|
72
|
+
entries, base_keys, deep_keys = parse_routes(script_path, base_arg, deep_arg)
|
|
73
|
+
try:
|
|
74
|
+
try:
|
|
75
|
+
raw_config = defaults_path.read_text(encoding="utf-8")
|
|
76
|
+
except FileNotFoundError:
|
|
77
|
+
enabled_base, enabled_deep = base_keys, deep_keys
|
|
78
|
+
else:
|
|
79
|
+
config = json.loads(raw_config)
|
|
80
|
+
if not isinstance(config, dict):
|
|
81
|
+
raise ValueError("配置顶层必须是对象")
|
|
82
|
+
enabled_base = read_list(config, "enabledByDefault", base_keys)
|
|
83
|
+
enabled_deep = read_list(config, "enabledForDeep", deep_keys)
|
|
84
|
+
error = ""
|
|
85
|
+
except Exception as exc:
|
|
86
|
+
enabled_base, enabled_deep = [], []
|
|
87
|
+
error = f"defaults: {exc}"
|
|
88
|
+
|
|
89
|
+
base_set, deep_set = set(enabled_base), set(enabled_deep)
|
|
90
|
+
channels = []
|
|
91
|
+
for entry in entries:
|
|
92
|
+
is_deep = entry["tier"] == "deep"
|
|
93
|
+
channels.append(
|
|
94
|
+
{
|
|
95
|
+
**entry,
|
|
96
|
+
"default_on": not is_deep and entry["key"] in base_set,
|
|
97
|
+
"deep_on": is_deep and entry["key"] in deep_set,
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
return {
|
|
101
|
+
"enabledByDefault": enabled_base,
|
|
102
|
+
"enabledForDeep": enabled_deep,
|
|
103
|
+
"defaults_error": error,
|
|
104
|
+
"channels": channels,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def main():
|
|
109
|
+
parser = argparse.ArgumentParser()
|
|
110
|
+
parser.add_argument("--script", required=True, type=Path)
|
|
111
|
+
parser.add_argument("--defaults", required=True, type=Path)
|
|
112
|
+
parser.add_argument("--base", required=True)
|
|
113
|
+
parser.add_argument("--deep", required=True)
|
|
114
|
+
parser.add_argument("--format", choices=("json", "table", "lists"), required=True)
|
|
115
|
+
args = parser.parse_args()
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
data = load_data(args.script, args.defaults, args.base, args.deep)
|
|
119
|
+
except Exception as exc:
|
|
120
|
+
prefix = "route-registry: " if isinstance(exc, RegistryError) else "defaults: "
|
|
121
|
+
data = {
|
|
122
|
+
"enabledByDefault": [],
|
|
123
|
+
"enabledForDeep": [],
|
|
124
|
+
"defaults_error": prefix + str(exc),
|
|
125
|
+
"channels": [],
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if args.format == "json":
|
|
129
|
+
print(json.dumps(data, ensure_ascii=False))
|
|
130
|
+
return 0
|
|
131
|
+
|
|
132
|
+
if args.format == "lists":
|
|
133
|
+
if data["defaults_error"]:
|
|
134
|
+
print(data["defaults_error"], file=sys.stderr)
|
|
135
|
+
return 2
|
|
136
|
+
print(",".join(data["enabledByDefault"]) + "|" + ",".join(data["enabledForDeep"]))
|
|
137
|
+
return 0
|
|
138
|
+
|
|
139
|
+
for channel in data["channels"]:
|
|
140
|
+
if channel["tier"] == "deep":
|
|
141
|
+
state = " [deep-on]" if channel["deep_on"] else " [not-deep]"
|
|
142
|
+
else:
|
|
143
|
+
state = " [default-on]" if channel["default_on"] else " [not-default]"
|
|
144
|
+
print(f" {channel['key']:10s} {channel['tier']:4s} {channel['name']}{state}")
|
|
145
|
+
if data["defaults_error"]:
|
|
146
|
+
error = data["defaults_error"]
|
|
147
|
+
if error.startswith("route-registry: "):
|
|
148
|
+
print(f"\n 路由注册表不一致(改代码,不是改配置):{error[len('route-registry: '):]}")
|
|
149
|
+
else:
|
|
150
|
+
print(f"\n 默认启用配置有误:{error[len('defaults: '):]}")
|
|
151
|
+
print('\n 用法: fanout.sh "<query>" [--deep] [--n N] [--on key1,key2] [--en "<english>"]')
|
|
152
|
+
return 2 if data["defaults_error"] else 0
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
if __name__ == "__main__":
|
|
156
|
+
raise SystemExit(main())
|