Refactor some generic components

This commit is contained in:
Lei Nelissen
2020-06-21 10:30:41 +02:00
parent b04026b846
commit 38fa01620d
15 changed files with 153 additions and 90 deletions

View File

@@ -1,6 +1,6 @@
import { Track } from 'react-native-track-player';
import { AppState, useTypedSelector } from '../store';
import { AlbumTrack } from '../store/music/types';
import { AppState, useTypedSelector } from 'store';
import { AlbumTrack } from 'store/music/types';
type Credentials = AppState['settings']['jellyfin'];

View File

@@ -0,0 +1,40 @@
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);
return useCallback(async function playAlbum(albumId: string) {
const album = albums[albumId];
const trackIds = album?.Tracks;
// GUARD: Check that the album actually has tracks
if (!album || !trackIds?.length || !tracks.length) {
return;
}
// Convert all trackIds to the relevant format for react-native-track-player
const newTracks = trackIds.map((trackId) => {
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
await TrackPlayer.removeUpcomingTracks();
await TrackPlayer.add(newTracks);
await TrackPlayer.skip(trackIds[0]);
TrackPlayer.play();
}, [credentials, albums, tracks]);
}

View File

@@ -0,0 +1,36 @@
import { useCallback } from 'react';
import TrackPlayer from 'react-native-track-player';
import { useTypedSelector } from 'store';
import { generateTrack } from './JellyfinApi';
import useQueue from './useQueue';
/**
* A hook that generates a callback that can setup and start playing a
* particular trackId in the player.
*/
export default function usePlayTrack() {
const credentials = useTypedSelector(state => state.settings.jellyfin);
const tracks = useTypedSelector(state => state.music.tracks.entities);
const queue = useQueue();
return useCallback(async function playTrack(trackId: string) {
// Get the relevant track
const track = tracks[trackId];
// GUARD: Check if the track actually exists in the store
if (!track) {
return;
}
// GUARD: Check if the track is already in the queue
if (!queue?.some((t) => t.id === trackId)) {
// If it is not, we must then generate it, and add it to the queue
const newTrack = generateTrack(track, credentials);
await TrackPlayer.add([ newTrack ]);
}
// Then we'll skip to it and play it
await TrackPlayer.skip(trackId);
TrackPlayer.play();
}, [credentials, tracks]);
}