feishin/src/renderer/features/player/hooks/use-handle-playqueue-add.ts

208 lines
7.8 KiB
TypeScript
Raw Normal View History

import { useCallback, useRef } from 'react';
2022-12-20 04:11:06 -08:00
import { useQueryClient } from '@tanstack/react-query';
import { useCurrentServer, usePlayerControls, usePlayerStore } from '/@/renderer/store';
2022-12-25 01:55:00 -08:00
import { usePlayerType } from '/@/renderer/store/settings.store';
import {
PlayQueueAddOptions,
Play,
PlaybackType,
PlayerStatus,
PlayerShuffle,
} from '/@/renderer/types';
import { toast } from '/@/renderer/components/toast/index';
2022-12-25 01:25:46 -08:00
import isElectron from 'is-electron';
2022-12-28 15:31:04 -08:00
import { nanoid } from 'nanoid/non-secure';
import {
2023-07-01 19:10:05 -07:00
LibraryItem,
QueueSong,
Song,
SongListResponse,
instanceOfCancellationError,
} from '/@/renderer/api/types';
import {
2023-07-01 19:10:05 -07:00
getPlaylistSongsById,
getSongById,
getAlbumSongsById,
getAlbumArtistSongsById,
getSongsByQuery,
2023-08-04 02:27:04 -07:00
getGenreSongsById,
} from '/@/renderer/features/player/utils';
import { queryKeys } from '/@/renderer/api/query-keys';
import { useTranslation } from 'react-i18next';
const getRootQueryKey = (itemType: LibraryItem, serverId: string) => {
2023-07-01 19:10:05 -07:00
let queryKey;
switch (itemType) {
case LibraryItem.ALBUM:
queryKey = queryKeys.songs.list(serverId);
break;
case LibraryItem.ALBUM_ARTIST:
queryKey = queryKeys.songs.list(serverId);
break;
2023-08-04 02:27:04 -07:00
case LibraryItem.GENRE:
queryKey = queryKeys.songs.list(serverId);
break;
2023-07-01 19:10:05 -07:00
case LibraryItem.PLAYLIST:
queryKey = queryKeys.playlists.songList(serverId);
break;
case LibraryItem.SONG:
queryKey = queryKeys.songs.list(serverId);
break;
default:
queryKey = queryKeys.songs.list(serverId);
break;
}
return queryKey;
};
2022-12-20 04:11:06 -08:00
2022-12-25 01:25:46 -08:00
const mpvPlayer = isElectron() ? window.electron.mpvPlayer : null;
const remote = isElectron() ? window.electron.remote : null;
const addToQueue = usePlayerStore.getState().actions.addToQueue;
2022-12-20 04:11:06 -08:00
export const useHandlePlayQueueAdd = () => {
const { t } = useTranslation();
2023-07-01 19:10:05 -07:00
const queryClient = useQueryClient();
const playerType = usePlayerType();
const server = useCurrentServer();
const { play } = usePlayerControls();
const timeoutIds = useRef<Record<string, ReturnType<typeof setTimeout>> | null>({});
const handlePlayQueueAdd = useCallback(
async (options: PlayQueueAddOptions) => {
if (!server) return toast.error({ message: 'No server selected', type: 'error' });
const { initialIndex, initialSongId, playType, byData, byItemType, query } = options;
let songs: QueueSong[] | null = null;
let initialSongIndex = 0;
if (byItemType) {
let songList: SongListResponse | undefined;
const { type: itemType, id } = byItemType;
const fetchId = nanoid();
timeoutIds.current = {
...timeoutIds.current,
[fetchId]: setTimeout(() => {
toast.info({
autoClose: false,
id: fetchId,
message: t('player.playbackFetchCancel', {
postProcess: 'sentenceCase',
}),
2023-07-01 19:10:05 -07:00
onClose: () => {
queryClient.cancelQueries({
exact: false,
queryKey: getRootQueryKey(itemType, server?.id),
});
},
title: t('player.playbackFetchInProgress', {
postProcess: 'sentenceCase',
}),
2023-07-01 19:10:05 -07:00
});
}, 2000),
};
try {
if (itemType === LibraryItem.PLAYLIST) {
songList = await getPlaylistSongsById({
id: id?.[0],
query,
queryClient,
server,
});
} else if (itemType === LibraryItem.ALBUM) {
songList = await getAlbumSongsById({ id, query, queryClient, server });
} else if (itemType === LibraryItem.ALBUM_ARTIST) {
songList = await getAlbumArtistSongsById({
id,
query,
queryClient,
server,
});
2023-08-04 02:27:04 -07:00
} else if (itemType === LibraryItem.GENRE) {
songList = await getGenreSongsById({ id, query, queryClient, server });
2023-07-01 19:10:05 -07:00
} else if (itemType === LibraryItem.SONG) {
if (id?.length === 1) {
songList = await getSongById({ id: id?.[0], queryClient, server });
} else {
songList = await getSongsByQuery({ query, queryClient, server });
}
}
clearTimeout(timeoutIds.current[fetchId] as ReturnType<typeof setTimeout>);
delete timeoutIds.current[fetchId];
toast.hide(fetchId);
} catch (err: any) {
if (instanceOfCancellationError(err)) {
return null;
}
clearTimeout(timeoutIds.current[fetchId] as ReturnType<typeof setTimeout>);
delete timeoutIds.current[fetchId];
toast.hide(fetchId);
return toast.error({
message: err.message,
title: t('error.genericError', { postProcess: 'sentenceCase' }) as string,
2023-07-01 19:10:05 -07:00
});
}
songs =
songList?.items?.map((song: Song) => ({ ...song, uniqueId: nanoid() })) || null;
} else if (byData) {
songs = byData.map((song) => ({ ...song, uniqueId: nanoid() })) || null;
}
if (!songs || songs?.length === 0)
return toast.warn({
message: t('common.noResultsFromQuery', { postProcess: 'sentenceCase' }),
title: t('player.playbackFetchNoResults'),
});
2023-07-01 19:10:05 -07:00
if (initialIndex) {
initialSongIndex = initialIndex;
} else if (initialSongId) {
initialSongIndex = songs.findIndex((song) => song.id === initialSongId);
2023-05-21 08:13:48 -07:00
}
const hadSong = usePlayerStore.getState().queue.default.length > 0;
2023-07-01 19:10:05 -07:00
const playerData = addToQueue({ initialIndex: initialSongIndex, playType, songs });
if (playerType === PlaybackType.LOCAL) {
mpvPlayer!.volume(usePlayerStore.getState().volume);
2023-07-01 19:10:05 -07:00
if (playType === Play.NEXT || playType === Play.LAST) {
mpvPlayer!.setQueueNext(playerData);
2023-07-01 19:10:05 -07:00
}
if (playType === Play.NOW) {
2023-08-07 14:48:02 -07:00
mpvPlayer!.pause();
mpvPlayer!.setQueue(playerData);
mpvPlayer!.play();
2023-07-01 19:10:05 -07:00
}
}
// We should only play if the queue was empty, or we are doing play NOW
// (override the queue).
if (playType === Play.NOW || !hadSong) {
play();
}
2023-07-01 19:10:05 -07:00
remote?.updateSong({
2023-07-01 19:10:05 -07:00
currentTime: usePlayerStore.getState().current.time,
repeat: usePlayerStore.getState().repeat,
shuffle: usePlayerStore.getState().shuffle !== PlayerShuffle.NONE,
2023-07-01 19:10:05 -07:00
song: playerData.current.song,
status: PlayerStatus.PLAYING,
2023-07-01 19:10:05 -07:00
});
return null;
2023-07-01 19:10:05 -07:00
},
[play, playerType, queryClient, server, t],
2023-07-01 19:10:05 -07:00
);
return handlePlayQueueAdd;
2022-12-20 04:11:06 -08:00
};