From 98fa47348c1a53ad3e14e3883aebd1aad8c0dca8 Mon Sep 17 00:00:00 2001 From: jeffvli Date: Mon, 5 Jun 2023 02:45:27 -0700 Subject: [PATCH] Replace main lyrics listener with promise handler --- src/main/features/core/lyrics/index.ts | 28 +++++++++++++++----------- src/main/preload/lyrics.ts | 3 ++- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/main/features/core/lyrics/index.ts b/src/main/features/core/lyrics/index.ts index 644e4a29..0927da2e 100644 --- a/src/main/features/core/lyrics/index.ts +++ b/src/main/features/core/lyrics/index.ts @@ -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; @@ -19,7 +18,7 @@ const MAX_CACHED_ITEMS = 10; const lyricCache = new Map(); -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; }); diff --git a/src/main/preload/lyrics.ts b/src/main/preload/lyrics.ts index c21473b4..d0c25f38 100644 --- a/src/main/preload/lyrics.ts +++ b/src/main/preload/lyrics.ts @@ -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 = (