Skip to content

Commit 8099464

Browse files
committed
fix: 修复网络故障误报和连续跳曲 fixed #314
1 parent 181640d commit 8099464

6 files changed

Lines changed: 156 additions & 20 deletions

File tree

‎src/core/player/index.ts‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ interface SourceRetryState {
6868
*/
6969
type LoadSourceResult =
7070
| { status: "loaded"; result: LoadOutcome; resolved: ResolvedTrackSource }
71-
| { status: "unresolved" }
71+
| { status: "unresolved"; error?: string }
7272
| { status: "cancelled" };
7373

7474
/** 引擎 load 竞态 token */
@@ -233,8 +233,11 @@ const createSourceRetryState = (): SourceRetryState => ({
233233
const resolveTrackSourceWithRetry = (
234234
track: Track,
235235
retry: SourceRetryState,
236+
onError: (error: string) => void,
236237
): Promise<ResolvedTrackSource | null> =>
237238
resolveTrackSource(track, {
239+
silent: true,
240+
onError,
238241
skipOfficialOnline: retry.skipOfficialOnline,
239242
skipPluginIds: [...retry.skippedPluginIds],
240243
});
@@ -260,9 +263,6 @@ const markRetryableSourceFailure = (
260263
return false;
261264
};
262265

263-
const shouldSuppressLoadError = (resolved: ResolvedTrackSource): boolean =>
264-
resolved.provider === "official" || resolved.provider === "plugin";
265-
266266
/**
267267
* 解析并加载 Track,遇到可兜底的音源失败时继续尝试下一个来源
268268
* @param track - 要加载的 Track
@@ -285,18 +285,26 @@ const loadTrackSourceWithFallback = async (
285285
): Promise<LoadSourceResult> => {
286286
const retry = createSourceRetryState();
287287
let firstTry = initialResolved ?? null;
288+
let lastFailure: Extract<LoadSourceResult, { status: "loaded" }> | undefined;
288289
while (true) {
289290
const usingInitial = firstTry !== null;
290-
const resolved = firstTry ?? (await resolveTrackSourceWithRetry(track, retry));
291+
let resolutionError: string | undefined;
292+
const resolved =
293+
firstTry ??
294+
(await resolveTrackSourceWithRetry(track, retry, (error) => {
295+
resolutionError = error;
296+
}));
291297
firstTry = null;
292298
if (!shouldContinue()) return { status: "cancelled" };
293-
if (!resolved) return { status: "unresolved" };
299+
// 没有可用插件不代表原音源失败原因,优先保留实际加载错误
300+
if (!resolved) return lastFailure ?? { status: "unresolved", error: resolutionError };
294301
const result = await load(resolved.source, autoPlay, track, {
295302
preparedId: usingInitial ? preparedId : undefined,
296-
suppressErrorToast: usingInitial || shouldSuppressLoadError(resolved),
303+
suppressErrorToast: true,
297304
context,
298305
});
299306
if (!shouldContinue()) return { status: "cancelled" };
307+
if (!result.ok) lastFailure = { status: "loaded", result, resolved };
300308
// 预载 URL 可能已经过期,非本地来源失败后重新解析一次最新地址
301309
if (
302310
usingInitial &&
@@ -308,6 +316,8 @@ const loadTrackSourceWithFallback = async (
308316
}
309317
const canRetry =
310318
!result.ok &&
319+
result.error !== ErrorCode.NETWORK_ERROR &&
320+
result.error !== ErrorCode.NETWORK_TIMEOUT &&
311321
(retryOnAnyFailure || Boolean(result.error && isSkippableError(result.error))) &&
312322
markRetryableSourceFailure(resolved, retry);
313323
if (canRetry) continue;
@@ -379,7 +389,8 @@ const loadTrack = async (
379389
status.state = "idle";
380390
void window.api.player.stop();
381391
useMediaStore().setLyric(null, null);
382-
shouldSkip = true;
392+
if (loaded.error) handleError(loaded.error);
393+
shouldSkip = Boolean(loaded.error && isSkippableError(loaded.error));
383394
} else {
384395
const { result, resolved } = loaded;
385396
if (!result.ok && result.error && isSkippableError(result.error)) {
@@ -435,10 +446,14 @@ export const reloadCurrentTrack = async (forcePlay?: boolean): Promise<boolean>
435446
// 被更新的加载接管:由它负责结果,不算本次失败
436447
if (loaded.status === "cancelled") return true;
437448
if (loaded.status === "unresolved") {
449+
if (loaded.error) handleError(loaded.error);
438450
status.trackLoading = false;
439451
return false;
440452
}
441-
if (!loaded.result.ok) return false;
453+
if (!loaded.result.ok) {
454+
if (loaded.result.error) handleError(loaded.result.error);
455+
return false;
456+
}
442457
if (resumePosition > 0) await seek(resumePosition);
443458
if (shouldPlay) await play();
444459
if (loaded.resolved.cacheRequest) {

‎src/core/player/preload.spec.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => {
88
setPlaybackContext: vi.fn(),
99
enrichTrack: vi.fn(),
1010
updateLyricIndex: vi.fn(),
11+
setLyric: vi.fn(),
1112
};
1213
return {
1314
track,
@@ -125,6 +126,57 @@ describe("切歌消费真实预载", () => {
125126
});
126127
});
127128

129+
it.each(["NETWORK_ERROR", "NETWORK_TIMEOUT"])("%s 保留真实错误并停止自动跳曲", async (error) => {
130+
mocks.consume.mockReturnValue(null);
131+
mocks.resolve.mockResolvedValue({
132+
source: "https://music/next",
133+
fromCache: false,
134+
provider: "official",
135+
});
136+
mocks.load.mockResolvedValueOnce({ success: false, error });
137+
const timer = vi.spyOn(globalThis, "setTimeout");
138+
const { playFrom } = await import("./index");
139+
const { handleError } = await import("@/utils/errors");
140+
await playFrom([mocks.track as Track]);
141+
expect(mocks.resolve).toHaveBeenCalledOnce();
142+
expect(handleError).toHaveBeenCalledExactlyOnceWith(error);
143+
expect(timer.mock.calls.some((call) => call[1] === 1000)).toBe(false);
144+
expect(mocks.status.state).toBe("idle");
145+
});
146+
147+
it("解析接口网络失败不会当成无音源连续跳曲", async () => {
148+
mocks.consume.mockReturnValue(null);
149+
mocks.resolve.mockImplementationOnce((_track, options) => {
150+
options.onError("NETWORK_ERROR");
151+
return null;
152+
});
153+
const timer = vi.spyOn(globalThis, "setTimeout");
154+
const { playFrom } = await import("./index");
155+
const { handleError } = await import("@/utils/errors");
156+
await playFrom([mocks.track as Track]);
157+
expect(handleError).toHaveBeenCalledExactlyOnceWith("NETWORK_ERROR");
158+
expect(mocks.load).not.toHaveBeenCalled();
159+
expect(timer.mock.calls.some((call) => call[1] === 1000)).toBe(false);
160+
});
161+
162+
it("换源耗尽时保留原加载错误,不替换为缺少插件", async () => {
163+
mocks.resolve.mockResolvedValueOnce({
164+
source: "https://music/next",
165+
fromCache: false,
166+
provider: "official",
167+
});
168+
mocks.resolve.mockImplementationOnce((_track, options) => {
169+
options.onError("NO_PLUGIN_AVAILABLE");
170+
return null;
171+
});
172+
mocks.load.mockResolvedValueOnce({ success: false, error: "FILE_DECODE_ERROR" });
173+
const { reloadCurrentTrack } = await import("./index");
174+
const { handleError } = await import("@/utils/errors");
175+
expect(await reloadCurrentTrack(false)).toBe(false);
176+
expect(handleError).toHaveBeenCalledExactlyOnceWith("FILE_DECODE_ERROR");
177+
expect(mocks.resolve).toHaveBeenCalledTimes(2);
178+
});
179+
128180
it("主动停止在等待主进程响应前就作废预载", async () => {
129181
let finish!: (result: { success: boolean }) => void;
130182
mocks.stop.mockImplementationOnce(

‎src/services/audioSource.spec.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { Track } from "@shared/types/player";
3+
import { ErrorCode } from "@shared/types/errors";
4+
5+
const mocks = vi.hoisted(() => ({
6+
netease: vi.fn(),
7+
qqmusic: vi.fn(),
8+
kugou: vi.fn(),
9+
error: vi.fn(),
10+
}));
11+
vi.mock("@/stores/settings", () => ({
12+
useSettingsStore: () => ({ player: { songLevel: "hq", allowTrialPlay: false }, system: {} }),
13+
}));
14+
vi.mock("@/stores/plugins", () => ({ usePluginsStore: () => ({ list: [] }) }));
15+
vi.mock("@/stores/user", () => ({ useUserStore: () => ({ isLoggedIn: false }) }));
16+
vi.mock("@/stores/streaming", () => ({ useStreamingStore: vi.fn() }));
17+
vi.mock("@/apis/song/netease", () => ({ resolveNeteaseUrl: mocks.netease }));
18+
vi.mock("@/apis/song/qqmusic", () => ({ resolveQQMusicUrl: mocks.qqmusic }));
19+
vi.mock("@/apis/song/kugou", () => ({ resolveKugouUrl: mocks.kugou }));
20+
vi.mock("@/utils/errors", () => ({ handleError: mocks.error }));
21+
import { resolveTrackSource } from "./audioSource";
22+
23+
describe("音源解析失败原因", () => {
24+
beforeEach(() => {
25+
vi.clearAllMocks();
26+
});
27+
it.each(["netease", "qqmusic", "kugou"] as const)(
28+
"%s API 异常不会被无插件覆盖",
29+
async (source) => {
30+
mocks[source].mockRejectedValueOnce(new Error("fetch failed"));
31+
const onError = vi.fn();
32+
const track: Track = { id: "1", title: "test", source, artists: [], duration: 1000 };
33+
expect(await resolveTrackSource(track, { silent: true, onError })).toBeNull();
34+
expect(onError).toHaveBeenCalledExactlyOnceWith(ErrorCode.NETWORK_ERROR);
35+
expect(mocks.error).not.toHaveBeenCalled();
36+
},
37+
);
38+
it("歌曲无版权仍保留单曲错误", async () => {
39+
mocks.netease.mockResolvedValueOnce({
40+
available: false,
41+
errorCode: ErrorCode.NETEASE_UNAVAILABLE,
42+
});
43+
await resolveTrackSource({
44+
id: "1",
45+
title: "test",
46+
source: "netease",
47+
artists: [],
48+
duration: 1000,
49+
});
50+
expect(mocks.error).toHaveBeenCalledExactlyOnceWith(ErrorCode.NETEASE_UNAVAILABLE);
51+
});
52+
});

‎src/services/audioSource.ts‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ const PLATFORM_TO_PLUGIN_SOURCE: Record<Platform, string> = {
2020

2121
/** 解析选项 */
2222
export interface ResolveTrackSourceOptions {
23+
/** 将解析失败原因交给播放流程,供提示和跳曲决策使用 */
24+
onError?: (error: string) => void;
2325
/** 要跳过的插件 ID 列表 */
2426
skipPluginIds?: readonly string[];
2527
/** 是否跳过官方在线接口,直接进入插件兜底 */
@@ -179,7 +181,7 @@ const resolveOnlineUrl = async (
179181
}
180182
} catch (err) {
181183
console.warn("[audio-source] official URL resolve failed:", err);
182-
officialErrorCode = ErrorCode.URL_RESOLVE_FAILED;
184+
officialErrorCode = ErrorCode.NETWORK_ERROR;
183185
}
184186
}
185187
if (track.source === "qqmusic" && !options.skipOfficialOnline) {
@@ -191,7 +193,7 @@ const resolveOnlineUrl = async (
191193
officialErrorCode = resolved.errorCode;
192194
} catch (err) {
193195
console.warn("[audio-source] official QQMusic URL resolve failed:", err);
194-
officialErrorCode = ErrorCode.URL_RESOLVE_FAILED;
196+
officialErrorCode = ErrorCode.NETWORK_ERROR;
195197
}
196198
}
197199
if (track.source === "kugou" && !options.skipOfficialOnline) {
@@ -203,7 +205,7 @@ const resolveOnlineUrl = async (
203205
officialErrorCode = resolved.errorCode;
204206
} catch (err) {
205207
console.warn("[audio-source] official Kugou URL resolve failed:", err);
206-
officialErrorCode = ErrorCode.URL_RESOLVE_FAILED;
208+
officialErrorCode = ErrorCode.NETWORK_ERROR;
207209
}
208210
}
209211
const pluginResolved = await resolveByPlugin(track, songLevel, options.skipPluginIds ?? []);
@@ -238,10 +240,11 @@ export interface ResolvedTrackSource {
238240
/**
239241
* 记录解析错误,支持静默模式抑制
240242
* @param err - 错误信息或错误码
241-
* @param silent - 是否开启静默模式
243+
* @param options - 提示方式和错误接收回调
242244
*/
243-
const reportLoadError = (err: ErrorCode | string, silent?: boolean): void => {
244-
if (!silent) handleError(err);
245+
const reportLoadError = (err: ErrorCode | string, options: ResolveTrackSourceOptions): void => {
246+
options.onError?.(err);
247+
if (!options.silent) handleError(err);
245248
};
246249

247250
/**
@@ -257,6 +260,7 @@ export const resolveTrackSource = async (
257260
// 本地文件
258261
if (track.source === "local") {
259262
const localPath = track.cueAudioPath ?? track.path;
263+
if (!localPath) reportLoadError(ErrorCode.FILE_NOT_FOUND, options);
260264
return localPath ? { source: localPath, fromCache: false, provider: "local" } : null;
261265
}
262266
const settings = useSettingsStore();
@@ -299,7 +303,7 @@ export const resolveTrackSource = async (
299303
}
300304
return result;
301305
} catch (err) {
302-
reportLoadError(err instanceof Error ? err.message : String(err), options.silent);
306+
reportLoadError(err instanceof Error ? err.message : String(err), options);
303307
return null;
304308
}
305309
}
@@ -308,7 +312,7 @@ export const resolveTrackSource = async (
308312
try {
309313
const resolved = await resolveOnlineUrl(track, songLevel, options);
310314
if (!resolved.ok) {
311-
reportLoadError(resolved.errorCode, options.silent);
315+
reportLoadError(resolved.errorCode, options);
312316
return null;
313317
}
314318
const url = resolved.url;
@@ -326,7 +330,7 @@ export const resolveTrackSource = async (
326330
}
327331
return result;
328332
} catch (err) {
329-
reportLoadError(err instanceof Error ? err.message : String(err), options.silent);
333+
reportLoadError(err instanceof Error ? err.message : String(err), options);
330334
return null;
331335
}
332336
}

‎src/utils/errors.spec.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { ErrorCode } from "@shared/types/errors";
3+
vi.mock("@/composables/useToast", () => ({ toast: {} }));
4+
vi.mock("@/composables/useDialog", () => ({ dialog: {} }));
5+
vi.mock("@/i18n", () => ({ default: {} }));
6+
import { isSkippableError } from "./errors";
7+
8+
describe("播放失败跳曲范围", () => {
9+
it("网络故障停留当前歌曲,单曲损坏和无版权允许跳过", () => {
10+
expect(isSkippableError(ErrorCode.NETWORK_ERROR)).toBe(false);
11+
expect(isSkippableError(ErrorCode.NETWORK_TIMEOUT)).toBe(false);
12+
expect(isSkippableError(ErrorCode.FILE_DECODE_ERROR)).toBe(true);
13+
expect(isSkippableError(ErrorCode.NETEASE_UNAVAILABLE)).toBe(true);
14+
});
15+
});

‎src/utils/errors.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@ const SKIPPABLE_ERRORS = new Set<string>([
1515
ErrorCode.FILE_NOT_FOUND,
1616
ErrorCode.FILE_NO_AUDIO_STREAM,
1717
ErrorCode.FILE_DECODE_ERROR,
18-
ErrorCode.NETWORK_ERROR,
19-
ErrorCode.NETWORK_TIMEOUT,
2018
ErrorCode.URL_RESOLVE_FAILED,
2119
ErrorCode.NO_PLUGIN_AVAILABLE,
2220
ErrorCode.NETEASE_LOGIN_EXPIRED,

0 commit comments

Comments
 (0)