dsh-klbq 0.1.1 → 0.2.1

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 CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 CSAHuan
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CSAHuan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
package/README.md CHANGED
@@ -1,78 +1,124 @@
1
- # dsh-klbq
2
-
3
- 卡拉彼丘(Strinova)战绩查询的 DSH 插件:按游戏昵称从 [dakanu.com](https://dakanu.com) 取数,
4
- 渲染成一张长图(排位段位 / 总览 / 模式 / 角色 / 最近对局),并把工具 `klbq_query` 暴露给 agent。
5
-
6
- ## 提供的工具
7
-
8
- ### `klbq_query`
9
-
10
- | 参数 | 类型 | 说明 |
11
- |---|---|---|
12
- | `nickname` | string(必填) | 游戏昵称或 UID |
13
- | `maxMatches` | number | 最近对局条数 0~20,默认 10 |
14
-
15
- 返回:
16
-
17
- ```jsonc
18
- {
19
- "ok": true,
20
- "nickname": "ahiahdiawh",
21
- "level": 62,
22
- "currentRank": "束缚电子 II", // 排位当前段位
23
- "topRank": "禁闭夸克 III", // 排位历史最高
24
- "summary": { "rounds": 30, "winRate": 0.5, "kda": 2.86, "avgDamage": 3220, ... },
25
- "recent": [ { "result": "win", "mode": "排位爆破", "kda": "8/6/15", "score": "9:4" } ],
26
- "imagePath": "C:\\Users\\...\\Temp\\dsh-klbq-cards\\ahiahdiawh-1794051495410.png",
27
- "imageBytes": 413696
28
- }
29
- ```
30
-
31
- 图片写到系统临时目录的 `dsh-klbq-cards/` 下。**工具不返回 base64**——
32
- 一张 500KB 的 PNG 进上下文会非常浪费,所以「模型看摘要、人看图片」。
33
-
34
- ## 安装
35
-
36
- 插件以本地 link 方式挂在 DSH profile 上:
37
-
38
- ```json
39
- // ~/.dsh/profiles/<profile>/package.json
40
- "dependencies": { "dsh-klbq": "link:C:/Users/<you>/.dsh/plugins/dsh-klbq" },
41
- "dsh": { "profile": { "bundles": [ ..., "dsh-klbq" ] } }
42
- ```
43
-
44
- 并把插件目录软链到 profile 的 `node_modules/dsh-klbq`。DSH 重启后生效。
45
-
46
- ## 两个实现要点(改代码前务必先读)
47
-
48
- 1. **SNI 阻断**:本机直连 `https://dakanu.com` 会在 TLS 握手阶段被 RST
49
- (ClientHello 带这个域名就被重置;不带 SNI 直连 IP 能拿到 301/200)。
50
- 因此请求统一「连 IP + `servername: ''` + `Host` 头」,并 `rejectUnauthorized: false`。
51
- `servername` 必须是**空字符串**,写成 `undefined` 时 Node 会补成域名 → 必被重置。
52
- 这条通道只取公开战绩、不传凭据;**不要**用它传输密钥或隐私数据。
53
-
54
- 2. **两套段位体系**:排位是「至纯物质 / 升格分子 / 虚空原子 / 聚变质子 / 自由中子 /
55
- 束缚电子 / 禁闭夸克 / 无限超弦 / 奇点」(按 `rank.segment` 号段);
56
- 挑战赛是「青铜…传奇」(按 `gradeScore` 算)。卡片右上角用排位,别混用。
57
-
58
- ## 渲染
59
-
60
- 用系统自带的 Edge / Chrome 无头截图(两趟:先 `--dump-dom` 量内容高度,再按高度截图),
61
- 不引入 canvas / puppeteer 之类的重依赖。找不到浏览器时可用环境变量 `KLBQ_BROWSER` 指定路径。
62
-
63
- ## 更新日志
64
-
65
- ### 0.1.1 — 取数提速
66
-
67
- dakanu 站点有两个 A 记录,快慢差 **5 倍**(实测搜索接口 5.37s vs 0.93s)。
68
- 旧版按 DNS 顺序依次尝试,会稳定命中慢的那个,用户感知就是「查一次要八九秒」。
69
-
70
- - **双 IP 并行对冲**:两个 IP 同时发请求,谁先成功用谁,耗时取决于较快者
71
- - **连接复用**:一次查询的「搜索 + 详情」共用同一条 TLS 连接,省掉第二次握手
72
- - **结果缓存**:搜索映射缓存 10 分钟、详情缓存 90 秒,重复查询不再走网络
73
-
74
- 实测:搜索 3565ms → ~700ms,详情 5555ms → ~1000ms,重复查询整链 ~2s(原 ~9s)。
75
-
76
- ## 许可
77
-
1
+ # dsh-klbq
2
+
3
+ 卡拉彼丘(Strinova)战绩查询的 DSH 插件:按游戏昵称从 [dakanu.com](https://dakanu.com) 取数,
4
+ 渲染成一张长图(排位段位 / 总览 / 模式 / 角色 / 最近对局),并把工具 `klbq_query` 暴露给 agent。
5
+
6
+ ## 提供的工具
7
+
8
+ ### `klbq_query`
9
+
10
+ | 参数 | 类型 | 说明 |
11
+ |---|---|---|
12
+ | `nickname` | string(必填) | 游戏昵称或 UID |
13
+ | `maxMatches` | number | 最近对局条数 0~20,默认 10 |
14
+
15
+ 返回:
16
+
17
+ ```jsonc
18
+ {
19
+ "ok": true,
20
+ "nickname": "ahiahdiawh",
21
+ "level": 62,
22
+ "currentRank": "束缚电子 II", // 排位当前段位
23
+ "topRank": "禁闭夸克 III", // 排位历史最高
24
+ "summary": { "rounds": 30, "winRate": 0.5, "kda": 2.86, "avgDamage": 3220, ... },
25
+ "recent": [ { "result": "win", "mode": "排位爆破", "kda": "8/6/15", "score": "9:4" } ],
26
+ "imagePath": "C:\\Users\\...\\Temp\\dsh-klbq-cards\\ahiahdiawh-1794051495410.png",
27
+ "imageBytes": 413696
28
+ }
29
+ ```
30
+
31
+ 图片写到系统临时目录的 `dsh-klbq-cards/` 下。**工具不返回 base64**——
32
+ 一张 500KB 的 PNG 进上下文会非常浪费,所以「模型看摘要、人看图片」。
33
+
34
+ ## 安装
35
+
36
+ 插件以本地 link 方式挂在 DSH profile 上:
37
+
38
+ ```json
39
+ // ~/.dsh/profiles/<profile>/package.json
40
+ "dependencies": { "dsh-klbq": "link:C:/Users/<you>/.dsh/plugins/dsh-klbq" },
41
+ "dsh": { "profile": { "bundles": [ ..., "dsh-klbq" ] } }
42
+ ```
43
+
44
+ 并把插件目录软链到 profile 的 `node_modules/dsh-klbq`。DSH 重启后生效。
45
+
46
+ ## 两个实现要点(改代码前务必先读)
47
+
48
+ 1. **SNI 阻断**:本机直连 `https://dakanu.com` 会在 TLS 握手阶段被 RST
49
+ (ClientHello 带这个域名就被重置;不带 SNI 直连 IP 能拿到 301/200)。
50
+ 因此请求统一「连 IP + `servername: ''` + `Host` 头」,并 `rejectUnauthorized: false`。
51
+ `servername` 必须是**空字符串**,写成 `undefined` 时 Node 会补成域名 → 必被重置。
52
+ 这条通道只取公开战绩、不传凭据;**不要**用它传输密钥或隐私数据。
53
+
54
+ 2. **两套段位体系**:排位是「至纯物质 / 升格分子 / 虚空原子 / 聚变质子 / 自由中子 /
55
+ 束缚电子 / 禁闭夸克 / 无限超弦 / 奇点」(按 `rank.segment` 号段);
56
+ 挑战赛是「青铜…传奇」(按 `gradeScore` 算)。卡片右上角用排位,别混用。
57
+
58
+ ## 渲染
59
+
60
+ 用系统自带的 Edge / Chrome 无头截图(两趟:先 `--dump-dom` 量内容高度,再按高度截图),
61
+ 不引入 canvas / puppeteer 之类的重依赖。找不到浏览器时可用环境变量 `KLBQ_BROWSER` 指定路径。
62
+
63
+ ## 与 QQ 官方机器人(`@tencent-connect/dsh-qqbot`)配合使用
64
+
65
+ 装了这个通道之后,在 QQ 私聊或群里直接发:
66
+
67
+ ```
68
+ /klbq 才知道左键能开枪
69
+ ```
70
+
71
+ 图片会作为本轮交付物自动发回聊天。
72
+
73
+ **实现方式**(不是注册斜杠命令):
74
+
75
+ `dsh-qqbot` 的命令表是硬编码的(`dist/commands/index.js` 的 `buildCommandList`),
76
+ 没有对外扩展点,第三方插件加不进 `/klbq`。但它用的 `slashCommand` 中间件对
77
+ **未注册**的命令是 `await next()` 放行的(`qqbot-nodejs/dist/middleware/slash-command.js`),
78
+ 所以 `/klbq xxx` 不会被吞掉,会当作普通消息进入 agent 回合。
79
+
80
+ 于是本插件挂到 `system-prompt/assemble` 瀑布流上,注入一小段说明,告诉 agent:
81
+ 收到 `/klbq` 就调用 `klbq_query`,拿到 `imagePath` 后再用 `present` 声明为交付物
82
+ (`dsh-qqbot` 的 `DeliverablesDeliverer` 会在轮末把文件发出去)。
83
+
84
+ **配置**
85
+
86
+ ```jsonc
87
+ // cordis 配置片段
88
+ {
89
+ "integrations": {
90
+ "qqbot": {
91
+ "promptInjection": true, // 默认 true;关掉就不再注入说明
92
+ "prompt": "……" // 可选,完全替换默认那段说明
93
+ }
94
+ }
95
+ }
96
+ ```
97
+
98
+ > 注入的说明每轮都在 system prompt 里(约 150 token)。没装 `dsh-qqbot` 时
99
+ > 插件会自动跳过,不产生任何开销。检测要求**同一个 profile** 里既有本插件又有 `dsh-qqbot`,避免别的 profile 装了它导致误注入。
100
+
101
+ ## 更新日志
102
+
103
+ ### 0.2.0 — 适配 QQ 官方机器人
104
+
105
+ - 新增 `lib/qqbot.js`:检测 `@tencent-connect/dsh-qqbot` 是否存在,存在则向
106
+ `system-prompt/assemble` 注入 `/klbq` 用法,让 QQ 里发指令可直接出图
107
+ - 检测兼容 `link:` 安装(插件在 `~/.dsh/plugins`,依赖在 `~/.dsh/profiles/*/node_modules`,
108
+ 不是祖先目录,`require.resolve` 会漏判,所以同时扫 profile 目录)
109
+ - 工具描述补充「IM 通道拿到 imagePath 后应调用 present 交付」
110
+
111
+ ### 0.1.1 — 取数提速
112
+
113
+ dakanu 站点有两个 A 记录,快慢差 **5 倍**(实测搜索接口 5.37s vs 0.93s)。
114
+ 旧版按 DNS 顺序依次尝试,会稳定命中慢的那个,用户感知就是「查一次要八九秒」。
115
+
116
+ - **双 IP 并行对冲**:两个 IP 同时发请求,谁先成功用谁,耗时取决于较快者
117
+ - **连接复用**:一次查询的「搜索 + 详情」共用同一条 TLS 连接,省掉第二次握手
118
+ - **结果缓存**:搜索映射缓存 10 分钟、详情缓存 90 秒,重复查询不再走网络
119
+
120
+ 实测:搜索 3565ms → ~700ms,详情 5555ms → ~1000ms,重复查询整链 ~2s(原 ~9s)。
121
+
122
+ ## 许可
123
+
78
124
  MIT
package/cordis.patch.yml CHANGED
@@ -1,9 +1,9 @@
1
- # 把 dsh-klbq 挂进 DSH 的插件链。
2
- #
3
- # entry 的 `id` 与 `name` 都写成 dsh-klbq:id 用于 loader 内定位,
4
- # name 是包名(node_modules 里解析到的就是它)。
5
- # 这个插件只注册工具,不注入 UI,所以不需要 Config 之外的额外接线。
6
- - insert:
7
- - id: dsh-klbq
8
- name: dsh-klbq
1
+ # 把 dsh-klbq 挂进 DSH 的插件链。
2
+ #
3
+ # entry 的 `id` 与 `name` 都写成 dsh-klbq:id 用于 loader 内定位,
4
+ # name 是包名(node_modules 里解析到的就是它)。
5
+ # 这个插件只注册工具,不注入 UI,所以不需要 Config 之外的额外接线。
6
+ - insert:
7
+ - id: dsh-klbq
8
+ name: dsh-klbq
9
9
  config: {}
package/lib/dakanu.js CHANGED
@@ -1,192 +1,192 @@
1
- // dakanu.com 数据访问层。
2
- //
3
- // 两个必须保留的细节(都是实测结论,改动前先读):
4
- //
5
- // 1) **SNI 阻断**:本机直连 https://dakanu.com 会在 TLS 握手阶段被 RST
6
- // (ClientHello 里带这个域名就被重置;不带 SNI 直连 IP 能正常拿到 301/200)。
7
- // 因此统一「连 IP + servername:'' 不发 SNI + Host 头指明站点」,
8
- // 并设置 rejectUnauthorized:false —— 证书是签给域名的,省略 SNI 后必然对不上。
9
- // 这条通道只取公开战绩、不传任何凭据;不要用它传输密钥或隐私数据。
10
- // 注意:servername 必须是**空字符串**,写 undefined 时 Node 会补成域名 → 必被重置。
11
- //
12
- // 2) **两套段位体系**:排位是「原子/质子/中子/电子/夸克/超弦…」(按 segment 号段),
13
- // 挑战赛是「青铜…传奇」(按 gradeScore 算)。卡片右上角用排位,别混用。
14
-
15
- import https from 'node:https';
16
- import dns from 'node:dns';
17
-
18
- const SITE_HOST = 'www.dakanu.com';
19
- // 2026-11 实测的 A 记录;解析失败时兜底
20
- const FALLBACK_IPS = ['43.169.14.133', '43.169.13.133'];
21
- const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
22
-
23
- let ipCache = { at: 0, ips: [] };
24
-
25
- // 连接复用:一次查询要走「搜索 + 详情」两次请求,共用一条 TLS 连接能省掉
26
- // 第二次 0.4~0.7 秒的握手开销。注意 servername 保持空字符串(见 httpsGetOnce 的说明)。
27
- // 结果缓存:dakanu 后端不稳定(同一接口实测 0.6~25 秒都有),
28
- // 同一个玩家短时间内重复查询没必要再走网络。搜索映射缓存 10 分钟(昵称极少变),
29
- // 详情缓存 90 秒(战绩不会秒变)。
30
- const resultCache = new Map();
31
- const CACHE_TTL_SEARCH = 10 * 60 * 1000;
32
- const CACHE_TTL_SUMMONER = 90 * 1000;
33
- const CACHE_MAX_ENTRIES = 200;
34
-
35
- function cached(key, ttlMs, loader) {
36
- const hit = resultCache.get(key);
37
- if (hit && Date.now() - hit.at < ttlMs) return Promise.resolve(hit.value);
38
- return loader().then((value) => {
39
- if (resultCache.size >= CACHE_MAX_ENTRIES) {
40
- const oldest = resultCache.keys().next().value;
41
- if (oldest !== undefined) resultCache.delete(oldest);
42
- }
43
- resultCache.set(key, { at: Date.now(), value });
44
- return value;
45
- });
46
- }
47
- const keepAliveAgent = new https.Agent({ keepAlive: true, maxSockets: 4, keepAliveMsecs: 30000 });
48
-
49
- /** 解析站点 IP:系统 DNS 没被拦(只有 SNI 被拦),失败退回内置列表 */
50
- async function resolveSiteIps() {
51
- const now = Date.now();
52
- if (ipCache.ips.length && now - ipCache.at < 10 * 60 * 1000) return ipCache.ips;
53
- try {
54
- const list = await dns.promises.resolve4(SITE_HOST);
55
- if (list.length) {
56
- ipCache = { at: now, ips: list };
57
- return list;
58
- }
59
- } catch { /* 用兜底 IP */ }
60
- return FALLBACK_IPS;
61
- }
62
-
63
- function httpsGetOnce(ip, pathname, { timeoutMs = 20000 } = {}) {
64
- return new Promise((resolve, reject) => {
65
- const req = https.request({
66
- host: ip,
67
- port: 443,
68
- path: pathname,
69
- method: 'GET',
70
- servername: '', // 关键:空字符串,不能是 undefined
71
- rejectUnauthorized: false, // 证书签给域名;这条通道只取公开数据
72
- agent: keepAliveAgent, // 复用连接:省下每次 0.4~0.7 秒的 TLS 握手
73
- headers: {
74
- host: SITE_HOST,
75
- 'user-agent': UA,
76
- accept: 'application/json, text/plain, */*',
77
- 'accept-language': 'zh-CN,zh;q=0.9',
78
- 'accept-encoding': 'identity',
79
- },
80
- timeout: timeoutMs,
81
- }, (res) => {
82
- const chunks = [];
83
- res.on('data', (c) => chunks.push(c));
84
- res.on('end', () => resolve({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString('utf8') }));
85
- });
86
- req.on('timeout', () => req.destroy(new Error(`请求超时(${ip}${pathname})`)));
87
- req.on('error', reject);
88
- req.end();
89
- });
90
- }
91
-
92
- /**
93
- * 并行对冲取数。
94
- *
95
- * 为什么不能「按 DNS 顺序依次尝试」:站点两个 A 记录**快慢差 5 倍**
96
- * (实测 43.169.13.133 搜索接口 5.4s,43.169.14.133 只要 0.9s)。
97
- * 顺序尝试会稳定选中那个慢的,用户看到的就是「查一次要八九秒」。
98
- * 改成两个 IP 同时发、谁先成功用谁,慢 IP 只做备份,总耗时取决于快的那个。
99
- */
100
- export async function dakanuGet(pathname, opts = {}) {
101
- const ips = await resolveSiteIps();
102
- if (ips.length === 1) return httpsGetOnce(ips[0], pathname, opts);
103
-
104
- return new Promise((resolve, reject) => {
105
- let settled = false;
106
- let pending = ips.length;
107
- let lastError = null;
108
-
109
- const fail = (error) => {
110
- lastError = error;
111
- pending -= 1;
112
- if (pending === 0 && !settled) reject(lastError ?? new Error('dakanu 请求失败'));
113
- };
114
-
115
- for (const ip of ips) {
116
- httpsGetOnce(ip, pathname, opts).then((res) => {
117
- if (settled) return;
118
- if (res.status >= 500) { fail(new Error(`HTTP ${res.status}`)); return; }
119
- settled = true;
120
- resolve(res);
121
- }).catch((error) => {
122
- if (settled) return;
123
- fail(error);
124
- });
125
- }
126
- });
127
- }
128
-
129
- async function dakanuJson(pathname) {
130
- // 缓存放在这一层最省事:搜索和详情都从这里出去,按 pathname 分档过期。
131
- const ttl = pathname.startsWith('/api/search/players') ? CACHE_TTL_SEARCH
132
- : pathname.startsWith('/api/summoner/') ? CACHE_TTL_SUMMONER
133
- : 60 * 1000;
134
- return cached(pathname, ttl, async () => {
135
- const res = await dakanuGet(pathname);
136
- let json = null;
137
- try { json = JSON.parse(res.text); } catch { /* 下面统一报错 */ }
138
- if (!json) throw new Error(`返回非 JSON(HTTP ${res.status})`);
139
- return json;
140
- });
141
- }
142
-
143
- /** 按昵称搜索玩家 */
144
- export async function searchPlayers(query) {
145
- const q = String(query ?? '').trim();
146
- if (!q) throw new Error('昵称不能为空');
147
- const json = await dakanuJson(`/api/search/players?q=${encodeURIComponent(q)}`);
148
- const list = Array.isArray(json?.suggestions) ? json.suggestions : [];
149
- return list
150
- .map((s) => ({
151
- playerId: String(s.playerId ?? ''),
152
- nickname: String(s.nickname ?? ''),
153
- exact: s.exact === true,
154
- level: s.level ?? null,
155
- }))
156
- .filter((s) => s.playerId && s.nickname);
157
- }
158
-
159
- /** 拉取玩家详情(段位/总览/模式/角色/最近对局) */
160
- export async function fetchSummoner(playerId, nickname) {
161
- const qs = nickname ? `?nickname=${encodeURIComponent(nickname)}` : '';
162
- const json = await dakanuJson(`/api/summoner/${encodeURIComponent(playerId)}${qs}`);
163
- if (!json?.ok || !json.profile) throw new Error(json?.error || '查询失败:站点未返回战绩数据');
164
- return json.profile;
165
- }
166
-
167
- /** 排位段位表(站点前端 es[]):按 segment 号段映射,段内分 IV~I */
168
- export const RANKED_TIERS = [
169
- { id: 'substance', name: '至纯物质', fromSeg: 1, toSeg: 3, divisions: ['III', 'II', 'I'], color: '#6c7178' },
170
- { id: 'molecule', name: '升格分子', fromSeg: 4, toSeg: 6, divisions: ['III', 'II', 'I'], color: '#c07a52' },
171
- { id: 'atom', name: '虚空原子', fromSeg: 7, toSeg: 10, divisions: ['IV', 'III', 'II', 'I'], color: '#9aa7b5' },
172
- { id: 'proton', name: '聚变质子', fromSeg: 11, toSeg: 14, divisions: ['IV', 'III', 'II', 'I'], color: '#d0a63c' },
173
- { id: 'neutron', name: '自由中子', fromSeg: 15, toSeg: 18, divisions: ['IV', 'III', 'II', 'I'], color: '#28b3a4' },
174
- { id: 'electron', name: '束缚电子', fromSeg: 19, toSeg: 23, divisions: ['V', 'IV', 'III', 'II', 'I'], color: '#3f8fd6' },
175
- { id: 'quark', name: '禁闭夸克', fromSeg: 24, toSeg: 28, divisions: ['V', 'IV', 'III', 'II', 'I'], color: '#9b5cd6' },
176
- { id: 'superstring', name: '无限超弦', fromSeg: 29, toSeg: 29, divisions: [], color: '#d94a44' },
177
- { id: 'singularity', name: '奇点', fromSeg: 30, toSeg: 30, divisions: [], color: '#d84a4a' },
178
- ];
179
-
180
- export function rankedTierOf(segment) {
181
- const seg = Number(segment);
182
- if (!Number.isFinite(seg) || seg < 1) return null;
183
- const tier = RANKED_TIERS.find((t) => seg >= t.fromSeg && seg <= t.toSeg);
184
- if (!tier) return null;
185
- return { name: tier.name, division: tier.divisions[seg - tier.fromSeg] ?? '', color: tier.color, segment: seg };
186
- }
187
-
188
- export function rankedLabel(segment) {
189
- const t = rankedTierOf(segment);
190
- if (!t) return '未定级';
191
- return t.division ? `${t.name} ${t.division}` : t.name;
1
+ // dakanu.com 数据访问层。
2
+ //
3
+ // 两个必须保留的细节(都是实测结论,改动前先读):
4
+ //
5
+ // 1) **SNI 阻断**:本机直连 https://dakanu.com 会在 TLS 握手阶段被 RST
6
+ // (ClientHello 里带这个域名就被重置;不带 SNI 直连 IP 能正常拿到 301/200)。
7
+ // 因此统一「连 IP + servername:'' 不发 SNI + Host 头指明站点」,
8
+ // 并设置 rejectUnauthorized:false —— 证书是签给域名的,省略 SNI 后必然对不上。
9
+ // 这条通道只取公开战绩、不传任何凭据;不要用它传输密钥或隐私数据。
10
+ // 注意:servername 必须是**空字符串**,写 undefined 时 Node 会补成域名 → 必被重置。
11
+ //
12
+ // 2) **两套段位体系**:排位是「原子/质子/中子/电子/夸克/超弦…」(按 segment 号段),
13
+ // 挑战赛是「青铜…传奇」(按 gradeScore 算)。卡片右上角用排位,别混用。
14
+
15
+ import https from 'node:https';
16
+ import dns from 'node:dns';
17
+
18
+ const SITE_HOST = 'www.dakanu.com';
19
+ // 2026-11 实测的 A 记录;解析失败时兜底
20
+ const FALLBACK_IPS = ['43.169.14.133', '43.169.13.133'];
21
+ const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
22
+
23
+ let ipCache = { at: 0, ips: [] };
24
+
25
+ // 连接复用:一次查询要走「搜索 + 详情」两次请求,共用一条 TLS 连接能省掉
26
+ // 第二次 0.4~0.7 秒的握手开销。注意 servername 保持空字符串(见 httpsGetOnce 的说明)。
27
+ // 结果缓存:dakanu 后端不稳定(同一接口实测 0.6~25 秒都有),
28
+ // 同一个玩家短时间内重复查询没必要再走网络。搜索映射缓存 10 分钟(昵称极少变),
29
+ // 详情缓存 90 秒(战绩不会秒变)。
30
+ const resultCache = new Map();
31
+ const CACHE_TTL_SEARCH = 10 * 60 * 1000;
32
+ const CACHE_TTL_SUMMONER = 90 * 1000;
33
+ const CACHE_MAX_ENTRIES = 200;
34
+
35
+ function cached(key, ttlMs, loader) {
36
+ const hit = resultCache.get(key);
37
+ if (hit && Date.now() - hit.at < ttlMs) return Promise.resolve(hit.value);
38
+ return loader().then((value) => {
39
+ if (resultCache.size >= CACHE_MAX_ENTRIES) {
40
+ const oldest = resultCache.keys().next().value;
41
+ if (oldest !== undefined) resultCache.delete(oldest);
42
+ }
43
+ resultCache.set(key, { at: Date.now(), value });
44
+ return value;
45
+ });
46
+ }
47
+ const keepAliveAgent = new https.Agent({ keepAlive: true, maxSockets: 4, keepAliveMsecs: 30000 });
48
+
49
+ /** 解析站点 IP:系统 DNS 没被拦(只有 SNI 被拦),失败退回内置列表 */
50
+ async function resolveSiteIps() {
51
+ const now = Date.now();
52
+ if (ipCache.ips.length && now - ipCache.at < 10 * 60 * 1000) return ipCache.ips;
53
+ try {
54
+ const list = await dns.promises.resolve4(SITE_HOST);
55
+ if (list.length) {
56
+ ipCache = { at: now, ips: list };
57
+ return list;
58
+ }
59
+ } catch { /* 用兜底 IP */ }
60
+ return FALLBACK_IPS;
61
+ }
62
+
63
+ function httpsGetOnce(ip, pathname, { timeoutMs = 20000 } = {}) {
64
+ return new Promise((resolve, reject) => {
65
+ const req = https.request({
66
+ host: ip,
67
+ port: 443,
68
+ path: pathname,
69
+ method: 'GET',
70
+ servername: '', // 关键:空字符串,不能是 undefined
71
+ rejectUnauthorized: false, // 证书签给域名;这条通道只取公开数据
72
+ agent: keepAliveAgent, // 复用连接:省下每次 0.4~0.7 秒的 TLS 握手
73
+ headers: {
74
+ host: SITE_HOST,
75
+ 'user-agent': UA,
76
+ accept: 'application/json, text/plain, */*',
77
+ 'accept-language': 'zh-CN,zh;q=0.9',
78
+ 'accept-encoding': 'identity',
79
+ },
80
+ timeout: timeoutMs,
81
+ }, (res) => {
82
+ const chunks = [];
83
+ res.on('data', (c) => chunks.push(c));
84
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString('utf8') }));
85
+ });
86
+ req.on('timeout', () => req.destroy(new Error(`请求超时(${ip}${pathname})`)));
87
+ req.on('error', reject);
88
+ req.end();
89
+ });
90
+ }
91
+
92
+ /**
93
+ * 并行对冲取数。
94
+ *
95
+ * 为什么不能「按 DNS 顺序依次尝试」:站点两个 A 记录**快慢差 5 倍**
96
+ * (实测 43.169.13.133 搜索接口 5.4s,43.169.14.133 只要 0.9s)。
97
+ * 顺序尝试会稳定选中那个慢的,用户看到的就是「查一次要八九秒」。
98
+ * 改成两个 IP 同时发、谁先成功用谁,慢 IP 只做备份,总耗时取决于快的那个。
99
+ */
100
+ export async function dakanuGet(pathname, opts = {}) {
101
+ const ips = await resolveSiteIps();
102
+ if (ips.length === 1) return httpsGetOnce(ips[0], pathname, opts);
103
+
104
+ return new Promise((resolve, reject) => {
105
+ let settled = false;
106
+ let pending = ips.length;
107
+ let lastError = null;
108
+
109
+ const fail = (error) => {
110
+ lastError = error;
111
+ pending -= 1;
112
+ if (pending === 0 && !settled) reject(lastError ?? new Error('dakanu 请求失败'));
113
+ };
114
+
115
+ for (const ip of ips) {
116
+ httpsGetOnce(ip, pathname, opts).then((res) => {
117
+ if (settled) return;
118
+ if (res.status >= 500) { fail(new Error(`HTTP ${res.status}`)); return; }
119
+ settled = true;
120
+ resolve(res);
121
+ }).catch((error) => {
122
+ if (settled) return;
123
+ fail(error);
124
+ });
125
+ }
126
+ });
127
+ }
128
+
129
+ async function dakanuJson(pathname) {
130
+ // 缓存放在这一层最省事:搜索和详情都从这里出去,按 pathname 分档过期。
131
+ const ttl = pathname.startsWith('/api/search/players') ? CACHE_TTL_SEARCH
132
+ : pathname.startsWith('/api/summoner/') ? CACHE_TTL_SUMMONER
133
+ : 60 * 1000;
134
+ return cached(pathname, ttl, async () => {
135
+ const res = await dakanuGet(pathname);
136
+ let json = null;
137
+ try { json = JSON.parse(res.text); } catch { /* 下面统一报错 */ }
138
+ if (!json) throw new Error(`返回非 JSON(HTTP ${res.status})`);
139
+ return json;
140
+ });
141
+ }
142
+
143
+ /** 按昵称搜索玩家 */
144
+ export async function searchPlayers(query) {
145
+ const q = String(query ?? '').trim();
146
+ if (!q) throw new Error('昵称不能为空');
147
+ const json = await dakanuJson(`/api/search/players?q=${encodeURIComponent(q)}`);
148
+ const list = Array.isArray(json?.suggestions) ? json.suggestions : [];
149
+ return list
150
+ .map((s) => ({
151
+ playerId: String(s.playerId ?? ''),
152
+ nickname: String(s.nickname ?? ''),
153
+ exact: s.exact === true,
154
+ level: s.level ?? null,
155
+ }))
156
+ .filter((s) => s.playerId && s.nickname);
157
+ }
158
+
159
+ /** 拉取玩家详情(段位/总览/模式/角色/最近对局) */
160
+ export async function fetchSummoner(playerId, nickname) {
161
+ const qs = nickname ? `?nickname=${encodeURIComponent(nickname)}` : '';
162
+ const json = await dakanuJson(`/api/summoner/${encodeURIComponent(playerId)}${qs}`);
163
+ if (!json?.ok || !json.profile) throw new Error(json?.error || '查询失败:站点未返回战绩数据');
164
+ return json.profile;
165
+ }
166
+
167
+ /** 排位段位表(站点前端 es[]):按 segment 号段映射,段内分 IV~I */
168
+ export const RANKED_TIERS = [
169
+ { id: 'substance', name: '至纯物质', fromSeg: 1, toSeg: 3, divisions: ['III', 'II', 'I'], color: '#6c7178' },
170
+ { id: 'molecule', name: '升格分子', fromSeg: 4, toSeg: 6, divisions: ['III', 'II', 'I'], color: '#c07a52' },
171
+ { id: 'atom', name: '虚空原子', fromSeg: 7, toSeg: 10, divisions: ['IV', 'III', 'II', 'I'], color: '#9aa7b5' },
172
+ { id: 'proton', name: '聚变质子', fromSeg: 11, toSeg: 14, divisions: ['IV', 'III', 'II', 'I'], color: '#d0a63c' },
173
+ { id: 'neutron', name: '自由中子', fromSeg: 15, toSeg: 18, divisions: ['IV', 'III', 'II', 'I'], color: '#28b3a4' },
174
+ { id: 'electron', name: '束缚电子', fromSeg: 19, toSeg: 23, divisions: ['V', 'IV', 'III', 'II', 'I'], color: '#3f8fd6' },
175
+ { id: 'quark', name: '禁闭夸克', fromSeg: 24, toSeg: 28, divisions: ['V', 'IV', 'III', 'II', 'I'], color: '#9b5cd6' },
176
+ { id: 'superstring', name: '无限超弦', fromSeg: 29, toSeg: 29, divisions: [], color: '#d94a44' },
177
+ { id: 'singularity', name: '奇点', fromSeg: 30, toSeg: 30, divisions: [], color: '#d84a4a' },
178
+ ];
179
+
180
+ export function rankedTierOf(segment) {
181
+ const seg = Number(segment);
182
+ if (!Number.isFinite(seg) || seg < 1) return null;
183
+ const tier = RANKED_TIERS.find((t) => seg >= t.fromSeg && seg <= t.toSeg);
184
+ if (!tier) return null;
185
+ return { name: tier.name, division: tier.divisions[seg - tier.fromSeg] ?? '', color: tier.color, segment: seg };
186
+ }
187
+
188
+ export function rankedLabel(segment) {
189
+ const t = rankedTierOf(segment);
190
+ if (!t) return '未定级';
191
+ return t.division ? `${t.name} ${t.division}` : t.name;
192
192
  }