Skip to content

Commit 5d5e127

Browse files
committed
fix: 修复收藏请求凭据与无音源歌曲自动跳过 (Refs #375, #372, #336)
1 parent 57e0fc0 commit 5d5e127

29 files changed

Lines changed: 2366 additions & 337 deletions

‎electron/main/apis/netease/core/option.ts‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
1-
/**
2-
* 请求 options 工厂
3-
* 从调用方 query 中抽取 crypto / cookie / ua / proxy / realIP 等,
4-
* 拼成 createRequest 的第三参数
5-
*/
1+
/** 从业务参数中提取请求层配置 */
62

73
import type { CryptoMode } from "./config";
84
import type { RequestOptions } from "./request";
95

106
/** 调用方传入的可选参数 */
117
export interface Query {
8+
/** 网页请求由公共层按路径装配凭据 */
9+
client?: "web";
1210
/** 加密方式 */
1311
crypto?: CryptoMode;
1412
/** 预注入 cookie,可为字符串或对象 */
@@ -31,16 +29,17 @@ export interface Query {
3129

3230
/**
3331
* 创建请求 options
34-
* @param query 调用方传入的可选参数
35-
* @param crypto 加密方式
36-
* @param checkToken 是否附加 anti-cheat token(如 "v3")
32+
* @param query - 调用方传入的可选参数
33+
* @param crypto - 加密方式
34+
* @param checkToken - 是否附加 anti-cheat token(如 "v3")
3735
* @returns 请求 options
3836
*/
3937
export const createOption = (
4038
query: Query,
4139
crypto: CryptoMode | "" = "",
4240
checkToken: string | boolean = false,
4341
): RequestOptions => ({
42+
client: query.client,
4443
crypto: (query.crypto as CryptoMode | undefined) || crypto,
4544
cookie: query.cookie,
4645
ua: query.ua || "",
@@ -50,3 +49,14 @@ export const createOption = (
5049
domain: query.domain || "",
5150
checkToken: query.checkToken || checkToken,
5251
});
52+
53+
/**
54+
* 为浏览器环境提供一致的请求配置,SDK 是否启用由路径规则决定
55+
* @param query - 业务接口接收到的请求参数
56+
* @returns 使用网页加密与公共会话的请求配置
57+
*/
58+
export const createWebOption = (query: Query): RequestOptions => ({
59+
...createOption(query, "weapi"),
60+
crypto: "weapi",
61+
client: "web",
62+
});

‎electron/main/apis/netease/core/request.spec.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,29 @@
11
import { createCipheriv } from "node:crypto";
22
import { beforeEach, describe, expect, it, vi } from "vitest";
33

4-
const api = vi.hoisted(() => ({ fetch: vi.fn(), v3: vi.fn() }));
4+
const api = vi.hoisted(() => ({ fetch: vi.fn(), v3: vi.fn(), web: vi.fn() }));
55
vi.mock("@main/utils/proxy", () => ({ fetchWithProxy: api.fetch }));
6+
vi.mock("./webClient", () => ({ requestWithWebClient: api.web }));
67
vi.mock("./checktoken", () => ({ getAntiCheatTokenV3: api.v3 }));
78
vi.mock("./device", () => ({ getAnonymousToken: () => "", getDeviceId: () => "device" }));
89

910
import { eapiReqDecrypt } from "./crypto";
1011
import { createRequest } from "./request";
1112

12-
describe("网易云请求协议与解析", () => {
13+
describe("平台请求协议与解析", () => {
1314
beforeEach(() => {
1415
api.fetch.mockReset().mockResolvedValue(new Response('{"code":200}'));
1516
api.v3.mockReset().mockResolvedValue("v3-fresh-token");
17+
api.web.mockReset().mockResolvedValue({ status: 200, body: { code: 200 }, cookie: [] });
18+
});
19+
20+
it("网页配置路由到公共请求层,不再经过客户端凭据和自动重试", async () => {
21+
const data = { id: 1 };
22+
const options = { client: "web" as const };
23+
await createRequest("/api/artist/sub", data, options);
24+
expect(api.web).toHaveBeenCalledWith("/api/artist/sub", data, options);
25+
expect(api.fetch).not.toHaveBeenCalled();
26+
expect(api.v3).not.toHaveBeenCalled();
1627
});
1728

1829
it("原收藏请求不获取反作弊凭据", async () => {

‎electron/main/apis/netease/core/request.ts‎

Lines changed: 17 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,4 @@
1-
/**
2-
* Netease API 请求层
3-
*
4-
* 核心职责:根据加密方式(weapi / linuxapi / eapi / api / xeapi)构造 URL、headers、form body,
5-
* 处理 cookie 合并、响应解密、状态码归一化
6-
*/
1+
/** 按客户端协议装配请求并统一处理响应 */
72

83
import { randomBytes } from "node:crypto";
94
import {
@@ -23,9 +18,13 @@ import { getAnonymousToken, getDeviceId } from "./device";
2318
import { ensureXeapiKey, getXeapiSession, updateXeapiSession } from "./xeapi";
2419
import { getAntiCheatTokenV3 } from "./checktoken";
2520
import { fetchWithProxy } from "@main/utils/proxy";
21+
import { NeteaseRequestError, type RequestResponse } from "./response";
22+
import { requestWithWebClient } from "./webClient";
2623

2724
/** 调用方传入的可选参数 */
2825
export interface RequestOptions {
26+
/** 网页请求由公共层匹配 SDK 规则并复用会话 */
27+
client?: "web";
2928
/** 加密方式;省略时依据路径默认规则,详见 createRequest */
3029
crypto?: CryptoMode | "";
3130
/** 预注入 cookie,可为字符串或对象 */
@@ -43,25 +42,7 @@ export interface RequestOptions {
4342
checkToken?: string | boolean;
4443
}
4544

46-
/** 响应统一结构 */
47-
export interface RequestResponse {
48-
status: number;
49-
body: Record<string, unknown>;
50-
cookie: string[];
51-
}
52-
53-
/** 非 200 响应抛出的错误 */
54-
export class NeteaseRequestError extends Error {
55-
readonly response: RequestResponse;
56-
constructor(response: RequestResponse) {
57-
const body = response.body as { code?: number | string; msg?: string; message?: string };
58-
const code = body?.code ?? response.status;
59-
const msg = body?.msg ?? body?.message ?? "";
60-
super(msg ? `netease ${code}: ${msg}` : `netease ${code}`);
61-
this.name = "NeteaseRequestError";
62-
this.response = response;
63-
}
64-
}
45+
export { NeteaseRequestError, type RequestResponse } from "./response";
6546

6647
interface NeteaseBody {
6748
code?: number | string;
@@ -119,7 +100,7 @@ const processCookieObject = (
119100
appver: cookie.appver || os.appver,
120101
};
121102

122-
// 服务端下发条件为不带 NMTID 请求任意 eapi 接口
103+
/** 服务端下发条件为不带 NMTID 请求任意 eapi 接口 */
123104
if (cookie.NMTID) {
124105
processed.NMTID = cookie.NMTID;
125106
} else if (cachedNmtid) {
@@ -147,15 +128,17 @@ const chooseUserAgent = (
147128

148129
/**
149130
* 构造并发送请求
150-
* @param uri 接口路径,例如 `/api/w/login`;weapi 会自动替换前缀为 `/weapi/`
151-
* @param data 业务参数(不含 cookie/csrf,请求层会自动注入)
152-
* @param options 加密方式 / cookie / 代理等
131+
* @param uri - 接口路径,例如 `/api/w/login`;weapi 会自动替换前缀为 `/weapi/`
132+
* @param data - 业务参数(不含 cookie/csrf,请求层会自动注入)
133+
* @param options - 加密方式 / cookie / 代理等
134+
* @returns 接口响应与会话 Cookie
153135
*/
154136
export const createRequest = async (
155137
uri: string,
156138
data: Record<string, unknown>,
157139
options: RequestOptions,
158140
): Promise<RequestResponse> => {
141+
if (options.client === "web") return requestWithWebClient(uri, data, options);
159142
const headers: Record<string, string> = {};
160143
const ip = options.realIP || options.ip || "";
161144
if (ip) {
@@ -166,7 +149,7 @@ export const createRequest = async (
166149
let crypto: CryptoMode | "" = options.crypto ?? "";
167150
if (crypto === "") crypto = "eapi";
168151

169-
// 归一化 cookie 到对象并做一次补全
152+
/** 归一化 cookie 到对象并做一次补全 */
170153
let cookie: Record<string, string> =
171154
typeof options.cookie === "string" ? cookieToJson(options.cookie) : options.cookie || {};
172155
cookie = processCookieObject(cookie, crypto);
@@ -327,7 +310,7 @@ export const createRequest = async (
327310
throw new NeteaseRequestError(answer);
328311
}
329312

330-
// 收集 set-cookie 并提取服务端下发的 NMTID
313+
/** 收集 set-cookie 并提取服务端下发的 NMTID */
331314
const setCookie =
332315
(res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie?.() ??
333316
(res.headers.get("set-cookie") ? [res.headers.get("set-cookie") as string] : []);
@@ -344,7 +327,7 @@ export const createRequest = async (
344327
answer.cookie = setCookie.map(cleanCookie);
345328
}
346329

347-
// xeapi 会话密钥由响应头下发,缓存供后续请求复用
330+
/** xeapi 会话密钥由响应头下发,缓存供后续请求复用 */
348331
if (isXeapi) {
349332
const ssid = res.headers.get("x-encr-ssid");
350333
const sskey = res.headers.get("x-encr-sskey");
@@ -367,7 +350,7 @@ export const createRequest = async (
367350
parsed = JSON.parse(text);
368351
}
369352
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
370-
throw new Error("网易云响应不是有效对象");
353+
throw new Error("平台响应不是有效对象");
371354
}
372355
answer.body = parsed;
373356
if (parsed?.code !== undefined) parsed.code = Number(parsed.code);
@@ -377,7 +360,7 @@ export const createRequest = async (
377360
}
378361
} catch {
379362
answer.status = res.status >= 400 ? res.status : 502;
380-
answer.body = { code: answer.status, msg: "网易云响应解析失败" };
363+
answer.body = { code: answer.status, msg: "平台响应解析失败" };
381364
}
382365

383366
answer.status = answer.status > 100 && answer.status < 600 ? answer.status : 400;
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/** 响应统一结构 */
2+
export interface RequestResponse {
3+
status: number;
4+
body: Record<string, unknown>;
5+
cookie: string[];
6+
}
7+
8+
/** 非 200 响应抛出的错误 */
9+
export class NeteaseRequestError extends Error {
10+
readonly response: RequestResponse;
11+
12+
/**
13+
* 保留服务端业务结果,供调用方识别失败原因
14+
* @param response - 未成功的请求响应
15+
*/
16+
constructor(response: RequestResponse) {
17+
const body = response.body as { code?: number | string; msg?: string; message?: string };
18+
const code = body?.code ?? response.status;
19+
const msg = body?.msg ?? body?.message ?? "";
20+
super(msg ? `netease ${code}: ${msg}` : `netease ${code}`);
21+
this.name = "NeteaseRequestError";
22+
this.response = response;
23+
}
24+
}

0 commit comments

Comments
 (0)