feishin/src/main/features/core/lyrics/netease.ts

114 lines
2.6 KiB
TypeScript
Raw Normal View History

import axios, { AxiosResponse } from 'axios';
2023-06-09 02:36:38 -07:00
import { LyricSource } from '../../../../renderer/api/types';
2023-06-08 03:40:34 -07:00
import type {
InternetProviderLyricResponse,
InternetProviderLyricSearchResponse,
LyricSearchQuery,
} from '/@/renderer/api/types';
const SEARCH_URL = 'https://music.163.com/api/search/get';
const LYRICS_URL = 'https://music.163.com/api/song/lyric';
2023-06-03 07:15:02 -07:00
// Adapted from https://github.com/NyaomiDEV/Sunamu/blob/master/src/main/lyricproviders/netease.ts
interface NetEaseResponse {
artist: string;
id: string;
2023-06-05 02:42:25 -07:00
name: string;
}
2023-06-08 03:40:34 -07:00
export async function getSearchResults(
params: LyricSearchQuery,
): Promise<InternetProviderLyricSearchResponse[] | null> {
let result: AxiosResponse<any, any>;
2023-06-09 04:08:33 -07:00
const searchQuery = [params.artist, params.name].join(' ');
if (!searchQuery) {
return null;
}
try {
result = await axios.get(SEARCH_URL, {
params: {
2023-06-08 03:40:34 -07:00
limit: 5,
offset: 0,
2023-06-09 04:08:33 -07:00
s: searchQuery,
type: '1',
},
});
} catch (e) {
console.error('NetEase search request got an error!', e);
2023-06-08 03:40:34 -07:00
return null;
}
2023-06-08 03:40:34 -07:00
const songs = result?.data.result?.songs;
2023-06-08 03:40:34 -07:00
if (!songs) return null;
return songs.map((song: any) => {
const artist = song.artists ? song.artists.map((artist: any) => artist.name).join(', ') : '';
2023-06-08 03:40:34 -07:00
return {
artist,
id: song.id,
name: song.name,
source: LyricSource.NETEASE,
};
});
}
async function getSongId(params: LyricSearchQuery): Promise<NetEaseResponse | undefined> {
const results = await getSearchResults(params);
const song = results?.[0];
if (!song) return undefined;
return {
2023-06-08 03:40:34 -07:00
artist: song.artist,
id: song.id,
2023-06-05 02:42:25 -07:00
name: song.name,
};
}
2023-06-09 02:36:38 -07:00
export async function getLyricsBySongId(songId: string): Promise<string | null> {
let result: AxiosResponse<any, any>;
try {
result = await axios.get(LYRICS_URL, {
params: {
id: songId,
kv: '-1',
lv: '-1',
},
});
} catch (e) {
console.error('NetEase lyrics request got an error!', e);
2023-06-09 02:36:38 -07:00
return null;
}
return result.data.klyric?.lyric || result.data.lrc?.lyric;
}
2023-06-08 03:40:34 -07:00
export async function query(
params: LyricSearchQuery,
): Promise<InternetProviderLyricResponse | null> {
const response = await getSongId(params);
if (!response) {
console.error('Could not find the song on NetEase!');
return null;
}
2023-06-09 02:36:38 -07:00
const lyrics = await getLyricsBySongId(response.id);
if (!lyrics) {
console.error('Could not get lyrics on NetEase!');
return null;
}
return {
artist: response.artist,
lyrics,
2023-06-05 02:42:25 -07:00
name: response.name,
source: LyricSource.NETEASE,
};
}