Skip to content

Commit

Permalink
feat: remove spotify built in lyrics
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed Jun 2, 2024
1 parent 83e2b99 commit f342697
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 135 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "spotify-lyrics",
"version": "1.6.3",
"version": "1.6.4",
"description": "Desktop Spotify Web Player Instant Synchronized Lyrics",
"scripts": {
"lint": "tsc --noEmit && eslint --ext .ts --fix src/",
Expand Down
2 changes: 1 addition & 1 deletion public/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "https://raw.githubusercontent.com/extend-chrome/manifest-json-schema/main/schema/manifest.schema.json",
"name": "__MSG_extensionName__",
"version": "1.6.3",
"version": "1.6.4",
"manifest_version": 3,
"description": "__MSG_extensionDescription__",
"default_locale": "en",
Expand Down
17 changes: 4 additions & 13 deletions src/page/lyrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import { captureException } from './utils';
export interface Query {
name: string;
artists: string;
/**sec */
duration?: number;
}

export interface Artist {
Expand Down Expand Up @@ -177,7 +175,7 @@ async function fetchSongList(s: string, fetchOptions?: RequestInit): Promise<Son

interface MatchingLyricsOptions {
onlySearchName?: boolean;
getAudioElement?: () => HTMLAudioElement | Promise<HTMLAudioElement>;
getDuration?: () => Promise<number>;
fetchData?: (s: string, fetchOptions?: RequestInit) => Promise<Song[]>;
fetchTransName?: (s: string, fetchOptions?: RequestInit) => Promise<Record<string, string>>;
fetchOptions?: RequestInit;
Expand All @@ -188,21 +186,14 @@ export async function matchingLyrics(
): Promise<{ list: Song[]; id: number; score: number }> {
const { name = '', artists = '' } = query;
const {
getAudioElement,
getDuration,
onlySearchName = false,
fetchData = fetchSongList,
fetchTransName = fetchChineseName,
fetchOptions,
} = options;

let duration = query.duration || 0;
if (getAudioElement && !duration) {
const audio = await getAudioElement();
if (!audio.duration) {
await new Promise((res) => audio.addEventListener('loadedmetadata', res, { once: true }));
duration = audio.duration;
}
}
const duration = (await getDuration?.()) || 0;

const queryName = normalize(name);
const queryName1 = queryName.toLowerCase();
Expand Down Expand Up @@ -361,7 +352,7 @@ export async function matchingLyrics(
list: listForMissingName,
score: scoreForMissingName,
} = await matchingLyrics(query, {
getAudioElement,
getDuration,
onlySearchName: true,
fetchData,
fetchTransName: async () => singerAlias,
Expand Down
63 changes: 32 additions & 31 deletions src/page/observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,42 +130,43 @@ const originFetch = globalThis.fetch;

let latestHeader = new Headers();

Check warning on line 131 in src/page/observer.ts

View workflow job for this annotation

GitHub Actions / lint

'latestHeader' is assigned a value but never used. Allowed unused vars must match /^_/u

Check warning on line 131 in src/page/observer.ts

View workflow job for this annotation

GitHub Actions / lint

'latestHeader' is assigned a value but never used. Allowed unused vars must match /^_/u

// Priority to detect track switching through API
// Priority to use build-in lyrics through API
globalThis.fetch = async (...rest) => {
const res = await originFetch(...rest);
const url = new URL(rest[0] instanceof Request ? rest[0].url : rest[0], location.origin);
latestHeader = new Headers(rest[0] instanceof Request ? rest[0].headers : rest[1]?.headers);
const spotifyAPI = 'https://spclient.wg.spotify.com';
if (url.origin === spotifyAPI && url.pathname.startsWith('/metadata/4/track/')) {
const metadata: SpotifyTrackMetadata = await res.clone().json();
const { name = '', artist = [], duration = 0, canonical_uri, has_lyrics } = metadata || {};
const trackId = canonical_uri?.match(/spotify:track:([^:]*)/)?.[1];
// match artists element textContent
const artists = artist?.map((e) => e?.name).join(', ');
sharedData.cacheTrackAndLyrics({
name,
artists,
duration: duration / 1000,
getLyrics: has_lyrics
? async () => {
const res = await fetch(`${spotifyAPI}/lyrics/v1/track/${trackId}?market=from_token`, {
headers: latestHeader,
});
const spLyrics: SpotifyTrackLyrics = await res.json();
if (spLyrics.kind === 'LINE') {
return spLyrics.lines
.map(({ time, words }) =>
words.map(({ string }) => ({
startTime: time / 1000,
text: string,
})),
)
.flat();
}
}
: undefined,
});
latestHeader = new Headers(rest[0] instanceof Request ? rest[0].headers : rest[1]?.headers);

// const metadata: SpotifyTrackMetadata = await res.clone().json();
// const { name = '', artist = [], duration = 0, canonical_uri, has_lyrics } = metadata || {};
// const trackId = canonical_uri?.match(/spotify:track:([^:]*)/)?.[1];
// // match artists element textContent
// const artists = artist?.map((e) => e?.name).join(', ');
// sharedData.cacheTrackAndLyrics({
// name,
// artists,
// duration: duration / 1000,
// getLyrics: has_lyrics
// ? async ({ signal }) => {
// const res = await fetch(`${spotifyAPI}/lyrics/v1/track/${trackId}?market=from_token`, {
// headers: latestHeader,
// signal,
// });
// if (!res.ok) return '';
// const spLyrics: SpotifyTrackLyrics = await res.json();
// if (spLyrics.kind !== 'LINE') return '';
// return spLyrics.lines
// .map(({ time, words }) =>
// words.map(({ string }) => {
// const sec = time / 1000;
// return `[${Math.floor(sec / 60)}:${sec % 60}]\n${string}`;
// }),
// )
// .flat()
// .join('\n');
// }
// : undefined,
// });
}
return res;
};
14 changes: 7 additions & 7 deletions src/page/rate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,16 +267,16 @@ const key = 'spotify.lyrics.test';

const listPromise = new Promise<Query[]>((res, rej) => {
const fn = () => {
const querys = [...document.querySelectorAll('.tracklist li')].map((item) => {
const queryList = [...document.querySelectorAll('.tracklist li')].map((item) => {
return {
name: item.querySelector('.tracklist-name')?.textContent || '',
artists: item.querySelector('.TrackListRow__artists')?.textContent || '',
};
});
if (!querys.length) {
if (!queryList.length) {
setTimeout(fn, 100);
} else {
res(querys);
res(queryList);
}
};
setTimeout(rej, 5000);
Expand All @@ -300,14 +300,14 @@ window.addEventListener('load', async () => {
detail: [],
};

const querys = await listPromise;
const queryList = await listPromise;

// test
querys.length = 1;
queryList.length = 1;

await Promise.all(
querys.map(async (query, i) => {
console.log(`${i + 1}/${querys.length} matching: `, query);
queryList.map(async (query, i) => {
console.log(`${i + 1}/${queryList.length} matching: `, query);
const { id } = await matchingLyrics(query);
if (id === 0) {
data[location.pathname].noMatch++;
Expand Down
Loading

0 comments on commit f342697

Please sign in to comment.