2020-06-21 10:30:41 +02:00
|
|
|
import { useTypedSelector } from 'store';
|
|
|
|
|
import { useCallback } from 'react';
|
|
|
|
|
import TrackPlayer, { Track } from 'react-native-track-player';
|
|
|
|
|
import { generateTrack } from './JellyfinApi';
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Generate a callback function that starts playing a full album given its
|
|
|
|
|
* supplied id.
|
|
|
|
|
*/
|
|
|
|
|
export default function usePlayAlbum() {
|
|
|
|
|
const credentials = useTypedSelector(state => state.settings.jellyfin);
|
|
|
|
|
const albums = useTypedSelector(state => state.music.albums.entities);
|
|
|
|
|
const tracks = useTypedSelector(state => state.music.tracks.entities);
|
|
|
|
|
|
2021-12-31 15:04:37 +01:00
|
|
|
return useCallback(async function playAlbum(albumId: string, play: boolean = true): Promise<Track[] | undefined> {
|
2020-06-21 10:30:41 +02:00
|
|
|
const album = albums[albumId];
|
2021-12-31 15:04:37 +01:00
|
|
|
const backendTrackIds = album?.Tracks;
|
2020-06-21 10:30:41 +02:00
|
|
|
|
2021-12-31 15:04:37 +01:00
|
|
|
// GUARD: Check if the album has songs
|
|
|
|
|
if (!backendTrackIds?.length) {
|
2020-06-21 10:30:41 +02:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2021-12-31 15:04:37 +01:00
|
|
|
// Convert all backendTrackIds to the relevant format for react-native-track-player
|
|
|
|
|
const newTracks = backendTrackIds.map((trackId) => {
|
2020-06-21 10:30:41 +02:00
|
|
|
const track = tracks[trackId];
|
|
|
|
|
if (!trackId || !track) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return generateTrack(track, credentials);
|
|
|
|
|
}).filter((t): t is Track => typeof t !== 'undefined');
|
|
|
|
|
|
|
|
|
|
// Clear the queue and add all tracks
|
2021-12-31 15:04:37 +01:00
|
|
|
await TrackPlayer.reset();
|
2020-06-21 10:30:41 +02:00
|
|
|
await TrackPlayer.add(newTracks);
|
2020-08-28 16:28:49 +02:00
|
|
|
|
2021-12-31 15:04:37 +01:00
|
|
|
// Play the queue
|
2020-08-28 16:28:49 +02:00
|
|
|
if (play) {
|
|
|
|
|
await TrackPlayer.play();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return newTracks;
|
2021-12-31 15:04:37 +01:00
|
|
|
}, [credentials, albums, tracks]);
|
2020-06-21 10:30:41 +02:00
|
|
|
}
|