Replace main lyrics listener with promise handler

This commit is contained in:
jeffvli 2023-06-05 02:45:27 -07:00 committed by Jeff
parent d38c846e80
commit 98fa47348c
2 changed files with 18 additions and 13 deletions

View file

@ -3,7 +3,6 @@ import { query as queryGenius } from './genius';
import { query as queryNetease } from './netease';
import { LyricSource } from '../../../../renderer/types';
import { ipcMain } from 'electron';
import { getMainWindow } from '../../../main';
import { store } from '../settings/index';
type SongFetcher = (song: QueueSong) => Promise<InternetProviderLyricResponse | null>;
@ -19,7 +18,7 @@ const MAX_CACHED_ITEMS = 10;
const lyricCache = new Map<string, CachedLyrics>();
ipcMain.on('lyric-fetch', async (_event, song: QueueSong) => {
const getRemoteLyrics = async (song: QueueSong) => {
const sources = store.get('lyrics', []) as LyricSource[];
const cached = lyricCache.get(song.id);
@ -27,23 +26,21 @@ ipcMain.on('lyric-fetch', async (_event, song: QueueSong) => {
if (cached) {
for (const source of sources) {
const data = cached[source];
if (data) {
getMainWindow()?.webContents.send('lyric-get', song.name, source, data);
return;
}
if (data) return data;
}
}
let lyricsFromSource = null;
for (const source of sources) {
const lyric = await FETCHERS[source](song);
if (lyric) {
const response = await FETCHERS[source](song);
if (response) {
const newResult = cached
? {
...cached,
[source]: lyric,
[source]: response,
}
: ({ [source]: lyric } as CachedLyrics);
: ({ [source]: response } as CachedLyrics);
if (lyricCache.size === MAX_CACHED_ITEMS && cached === undefined) {
const toRemove = lyricCache.keys().next().value;
@ -52,8 +49,15 @@ ipcMain.on('lyric-fetch', async (_event, song: QueueSong) => {
lyricCache.set(song.id, newResult);
getMainWindow()?.webContents.send('lyric-get', song.name, source, lyric);
lyricsFromSource = response;
break;
}
}
return lyricsFromSource;
};
ipcMain.handle('lyric-fetch-manual', async (_event, song: QueueSong) => {
const lyric = await getRemoteLyrics(song);
return lyric;
});

View file

@ -2,7 +2,8 @@ import { IpcRendererEvent, ipcRenderer } from 'electron';
import { InternetProviderLyricResponse, QueueSong } from '/@/renderer/api/types';
const fetchRemoteLyrics = (song: QueueSong) => {
ipcRenderer.send('lyric-fetch', song);
const result = ipcRenderer.invoke('lyric-fetch-manual', song);
return result;
};
const remoteLyricsListener = (