Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/v0.1.0-beta4.txt
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ SYNC

MUSIC
- Autoplay radio no longer stops after about 20 songs. A station keeps adding songs while it has more to play.
- Instrumental songs no longer show KuGou's notice as their lyrics.
- Clicking an empty part of the music bar now opens the full player. The buttons, the seek line and dragging up work as before.
- Hiding or showing the Queue or Lyrics pane in the full player no longer stretches the title and controls, and the artwork moves with the text.

Expand Down
27 changes: 27 additions & 0 deletions src/lib/lyrics/lyricsHelper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,17 @@ vi.mock("./registry", () => ({
}));
vi.mock("../../store/useAppSettingsStore", () => ({ getSettingValue: () => "" }));

const disk = vi.hoisted(() => new Map<string, string>());
vi.mock("../api/lyrics", () => ({
getCachedLyrics: async (id: string) => disk.get(id) ?? null,
putCachedLyrics: async (id: string, entries: string) => {
disk.set(id, entries);
},
evictCachedLyrics: async (id: string) => {
disk.delete(id);
},
}));

const { getLyrics, forceRefresh } = await import("./lyricsHelper");
const { seedOfflineLyrics } = await import("./offline");

Expand Down Expand Up @@ -40,13 +51,29 @@ const request = () => ({ videoId: `video-${++id}`, title: "Song", artist: "Band"

beforeEach(() => {
providers.length = 0;
disk.clear();
localStorage.clear();
});
afterEach(() => {
vi.useRealTimers();
});

describe("lyrics helper", () => {
it("drops KuGou's instrumental notice saved in the disk cache", async () => {
const song = request();
disk.set(song.videoId, JSON.stringify([{ time: 1580, text: "纯音乐,请欣赏" }]));
expect(await getLyrics(song)).toBeNull();
expect(disk.has(song.videoId)).toBe(false);
});

it("still falls back to other line-synced lyrics from the disk cache", async () => {
const song = request();
disk.set(song.videoId, JSON.stringify(lineSynced));
const result = await getLyrics(song);
expect(result?.provider).toBe("DiskCache");
expect(disk.has(song.videoId)).toBe(true);
});

it("returns word sync at once without asking later providers", async () => {
const later = provider("Later", async () => lineSynced);
providers.push(provider("Words", async () => wordSynced), later);
Expand Down
8 changes: 5 additions & 3 deletions src/lib/lyrics/lyricsHelper.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { LyricsEntry, LyricsProvider, LyricsResult } from "./types";
import type { SongItem } from "../../types/music";
import { getEnabledProviders, parseProviderEnabledStates } from "./registry";
import { filterCreditLines, normalizeEntries, stripWordTimings } from "./lyricsUtils";
import { filterCreditLines, isInstrumentalNotice, normalizeEntries, stripWordTimings } from "./lyricsUtils";
import { cleanArtist, cleanTitle } from "./matching";
import { entriesAreSynced, hasWordSync, hasReasonableTimestamps } from "./sync";
import * as cache from "./cache";
Expand Down Expand Up @@ -125,11 +125,13 @@ async function fetchLyrics(request: LyricsRequest, signal: AbortSignal): Promise
const disk = await cache.getDisk(videoId);
if (disk && disk.length > 0) {
const norm = normalizeEntries(sorted(disk));
if (hasWordSync(norm) && hasReasonableTimestamps(norm, durationSec)) {
// A notice saved before KuGou's was read as no lyrics would otherwise come back as the fallback.
const usable = !isInstrumentalNotice(norm) && hasReasonableTimestamps(norm, durationSec);
if (hasWordSync(norm) && usable) {
cache.setMemory(videoId, norm);
return { entries: norm, provider: "DiskCache" };
}
if (hasReasonableTimestamps(norm, durationSec)) {
if (usable) {
cachedFallback = { entries: stripWordTimings(norm), provider: "DiskCache" };
} else {
cache.evict(videoId);
Expand Down
6 changes: 6 additions & 0 deletions src/lib/lyrics/lyricsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ export function filterCreditLines(entries: LyricsEntry[]): LyricsEntry[] {
});
}

// KuGou answers instrumentals with one line, "纯音乐,请欣赏" ("pure music, please enjoy"), not with no lyrics.
const INSTRUMENTAL_NOTICE = /^纯音乐[,,]?\s*请欣赏$/;

export const isInstrumentalNotice = (entries: LyricsEntry[]): boolean =>
entries.length > 0 && entries.every((entry) => INSTRUMENTAL_NOTICE.test(entry.text.trim()));

export function normalizeEntries(entries: LyricsEntry[]): LyricsEntry[] {
return entries.map((e) => ({
...e,
Expand Down
61 changes: 61 additions & 0 deletions src/lib/lyrics/providers/kugou.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { beforeEach, describe, expect, it, vi } from "vitest";

const requests = vi.hoisted(() => ({ downloads: [] as number[] }));
const answers = vi.hoisted(() => ({
songs: [] as Array<{ hash: string; songname: string; singername: string; duration: number }>,
keyword: [] as Array<{ id: number; accesskey: string; song: string; singer: string; duration: number }>,
lrc: new Map<number, string>(),
}));

vi.mock("../http", () => ({
enc: encodeURIComponent,
lyricsGetJson: async (url: string) => {
if (url.includes("/search/song")) return { data: { info: answers.songs } };
if (url.includes("/download")) {
const id = Number(new URL(url).searchParams.get("id"));
requests.downloads.push(id);
const bytes = new TextEncoder().encode(answers.lrc.get(id) ?? "");
return { content: btoa(String.fromCharCode(...bytes)) };
}
const hash = new URL(url).searchParams.get("hash");
if (hash) return { candidates: [{ id: Number(hash), accesskey: "key" }] };
return { candidates: answers.keyword };
},
}));

import { kugouProvider } from "./kugou";

const NOTICE = "[00:01.58]纯音乐,请欣赏";
const VOCALS = "[00:10.00]First\n[00:20.00]Second";
const hit = (hash: number, duration: number) => ({ hash: String(hash), songname: "Song", singername: "Band", duration });
const lookup = () => kugouProvider.getLyrics("id", "Song", "Band", 200, null);

describe("KuGou lookup", () => {
beforeEach(() => {
requests.downloads.length = 0;
answers.songs = [];
answers.keyword = [];
answers.lrc = new Map([
[1, NOTICE],
[2, VOCALS],
]);
});

it("stops at the instrumental notice, so a vocal version of the song can't answer for it", async () => {
answers.songs = [hit(1, 200), hit(2, 180)];
expect(await lookup()).toEqual([]);
expect(requests.downloads).toEqual([1]);
});

it("reads a notice from the keyword search as no lyrics too", async () => {
answers.keyword = [{ id: 1, accesskey: "key", song: "Song", singer: "Band", duration: 200_000 }];
expect(await lookup()).toEqual([]);
});

it("still tries the next match when one has no lyrics at all", async () => {
answers.lrc.delete(1);
answers.songs = [hit(1, 200), hit(2, 180)];
expect(await lookup()).toHaveLength(2);
expect(requests.downloads).toEqual([1, 2]);
});
});
8 changes: 5 additions & 3 deletions src/lib/lyrics/providers/kugou.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { LyricsEntry, LyricsProvider } from "../types";
import { lyricsGetJson, enc } from "../http";
import { parseLyrics } from "../lyricsUtils";
import { isInstrumentalNotice, parseLyrics } from "../lyricsUtils";
import { ranked, type MatchSong } from "../matching";

const SONG_SEARCH = "https://mobileservice.kugou.com/api/v3/search/song";
Expand Down Expand Up @@ -142,7 +142,8 @@ export const kugouProvider: LyricsProvider = {
const entries = await fromCandidate(
await firstCandidate(`${LYRIC_SEARCH}?ver=1&man=yes&client=pc&hash=${enc(song.hash)}`),
);
if (entries.length > 0) return entries;
// The notice is KuGou's answer for this song; a later match could be a vocal version of it.
if (entries.length > 0) return isInstrumentalNotice(entries) ? [] : entries;
}

let url = `${LYRIC_SEARCH}?ver=1&man=yes&client=pc`;
Expand All @@ -154,6 +155,7 @@ export const kugouProvider: LyricsProvider = {
request,
(c) => ({ title: stripTags(c.song), artist: stripTags(c.singer), durationSec: Math.round((c.duration ?? 0) / 1000) }),
);
return fromCandidate(candidates[0] ?? null);
const entries = await fromCandidate(candidates[0] ?? null);
return isInstrumentalNotice(entries) ? [] : entries;
},
};
9 changes: 9 additions & 0 deletions src/lib/lyrics/providers/providers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { matchKuGou, normalizeKuGouLrc } from "./kugou";
import { matchAppleSongs, parseItunesSearch } from "./paxsenix";
import { isUncachedMiss } from "./betterLyrics";
import { lrcOffsetMs, parseOfflineLyrics } from "../offline";
import { isInstrumentalNotice, parseLyrics } from "../lyricsUtils";

describe("BetterLyrics", () => {
it("reads an uncached 401 as a miss for this song only", () => {
Expand Down Expand Up @@ -81,6 +82,14 @@ describe("KuGou", () => {
const lrc = ["[00:00.00]Song - Singer", "[00:01.00]作词:Someone", "plain", "[00:10.00]First", "[00:20.00]Second"].join("\n");
expect(normalizeKuGouLrc(lrc)).toBe("[00:10.00]First\n[00:20.00]Second");
});

it("reads the instrumental notice as no lyrics, but not lyrics that contain it", () => {
const notice = ["\uFEFF[id:$00000000]", "[ar:arkady sevidov]", "[ti:June]", "[total:320317]", "[00:01.58]纯音乐,请欣赏"].join("\n");
expect(isInstrumentalNotice(parseLyrics(normalizeKuGouLrc(notice)))).toBe(true);
expect(isInstrumentalNotice(parseLyrics("[00:01.58]纯音乐,请欣赏"))).toBe(true);
expect(isInstrumentalNotice(parseLyrics("[00:01.00]纯音乐,请欣赏\n[00:05.00]First"))).toBe(false);
expect(isInstrumentalNotice([])).toBe(false);
});
});

describe("Paxsenix", () => {
Expand Down
Loading