Port to Redux and add settings
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
import React, { Component } from 'react';
|
||||
import { Provider } from 'react-redux';
|
||||
import TrackPlayer from 'react-native-track-player';
|
||||
import { PersistGate } from 'redux-persist/integration/react';
|
||||
import { NavigationContainer } from '@react-navigation/native';
|
||||
import Routes from '../screens';
|
||||
import store, { persistedStore } from '../store';
|
||||
|
||||
interface State {
|
||||
isReady: boolean;
|
||||
@@ -34,9 +37,13 @@ export default class App extends Component<State> {
|
||||
}
|
||||
|
||||
return (
|
||||
<NavigationContainer>
|
||||
<Routes />
|
||||
</NavigationContainer>
|
||||
<Provider store={store}>
|
||||
<PersistGate loading={null} persistor={persistedStore}>
|
||||
<NavigationContainer>
|
||||
<Routes />
|
||||
</NavigationContainer>
|
||||
</PersistGate>
|
||||
</Provider>
|
||||
);
|
||||
}
|
||||
}
|
||||
10
src/components/Input.tsx
Normal file
10
src/components/Input.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import styled from 'styled-components/native';
|
||||
|
||||
const Input = styled.TextInput`
|
||||
margin: 10px 0;
|
||||
background-color: #f6f6f6;
|
||||
border-radius: 5px;
|
||||
padding: 15px;
|
||||
`;
|
||||
|
||||
export default Input;
|
||||
29
src/components/Modal.tsx
Normal file
29
src/components/Modal.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import React from 'react';
|
||||
import styled from 'styled-components/native';
|
||||
import { SafeAreaView } from 'react-native';
|
||||
|
||||
const Background = styled.View`
|
||||
background-color: #eeeeeeee;
|
||||
padding: 100px 25px;
|
||||
flex: 1;
|
||||
`;
|
||||
|
||||
const Container = styled.View`
|
||||
background-color: white;
|
||||
border-radius: 20px;
|
||||
flex: 1;
|
||||
`;
|
||||
|
||||
const Modal: React.FC = ({ children }) => {
|
||||
return (
|
||||
<Background>
|
||||
<SafeAreaView style={{ flex: 1}}>
|
||||
<Container>
|
||||
{children}
|
||||
</Container>
|
||||
</SafeAreaView>
|
||||
</Background>
|
||||
);
|
||||
};
|
||||
|
||||
export default Modal;
|
||||
@@ -1,18 +1,15 @@
|
||||
import React, { Component, useCallback } from 'react';
|
||||
import React, { useCallback, useEffect } from 'react';
|
||||
import TrackPlayer from 'react-native-track-player';
|
||||
import { StackScreenProps } from '@react-navigation/stack';
|
||||
import { RootStackParamList, AlbumTrack } from '../types';
|
||||
import { Text, ScrollView, Dimensions, FlatList, Button, TouchableOpacity } from 'react-native';
|
||||
import { retrieveAlbumTracks, getImage, generateTrack } from '../../../utility/JellyfinApi';
|
||||
import { StackParams } from '../types';
|
||||
import { Text, ScrollView, Dimensions, Button, TouchableOpacity } from 'react-native';
|
||||
import { generateTrack, useGetImage } from '../../../utility/JellyfinApi';
|
||||
import styled from 'styled-components/native';
|
||||
import { useRoute, RouteProp } from '@react-navigation/native';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { useTypedSelector } from '../../../store';
|
||||
import { fetchTracksByAlbum } from '../../../store/music/actions';
|
||||
|
||||
interface Props extends StackScreenProps<RootStackParamList, 'Album'> {
|
||||
//
|
||||
}
|
||||
|
||||
interface State {
|
||||
tracks: AlbumTrack[];
|
||||
}
|
||||
type Route = RouteProp<StackParams, 'Album'>;
|
||||
|
||||
const Screen = Dimensions.get('screen');
|
||||
|
||||
@@ -49,48 +46,50 @@ const TouchableTrack: React.FC<TouchableTrackProps> = ({ id, onPress, children
|
||||
);
|
||||
};
|
||||
|
||||
export default class Album extends Component<Props, State> {
|
||||
state: State = {
|
||||
tracks: [],
|
||||
}
|
||||
const Album: React.FC = () => {
|
||||
// Retrieve state
|
||||
const { params: { id } } = useRoute<Route>();
|
||||
const tracks = useTypedSelector((state) => state.music.tracks.entities);
|
||||
const album = useTypedSelector((state) => state.music.albums.entities[id]);
|
||||
const credentials = useTypedSelector((state) => state.settings.jellyfin);
|
||||
|
||||
async componentDidMount() {
|
||||
const tracks = await retrieveAlbumTracks(this.props.route.params.id);
|
||||
this.setState({ tracks });
|
||||
}
|
||||
// Retrieve helpers
|
||||
const dispatch = useDispatch();
|
||||
const getImage = useGetImage();
|
||||
|
||||
selectTrack = async (id: string) => {
|
||||
const track = await generateTrack(id);
|
||||
await TrackPlayer.add([ track ]);
|
||||
await TrackPlayer.skip(id);
|
||||
// Set callbacks
|
||||
const selectTrack = useCallback(async (trackId) => {
|
||||
const newTrack = generateTrack(tracks[trackId], credentials);
|
||||
console.log(newTrack);
|
||||
await TrackPlayer.add([ newTrack ]);
|
||||
await TrackPlayer.skip(trackId);
|
||||
TrackPlayer.play();
|
||||
}
|
||||
|
||||
playAlbum = async () => {
|
||||
const tracks = await Promise.all(this.state.tracks.map(track => generateTrack(track.Id)));
|
||||
}, [tracks, credentials]);
|
||||
const playAlbum = useCallback(async () => {
|
||||
const newTracks = album.Tracks.map((trackId) => generateTrack(tracks[trackId], credentials));
|
||||
await TrackPlayer.removeUpcomingTracks();
|
||||
await TrackPlayer.add(tracks);
|
||||
await TrackPlayer.skip(tracks[0].id);
|
||||
await TrackPlayer.add(newTracks);
|
||||
await TrackPlayer.skip(album.Tracks[0]);
|
||||
TrackPlayer.play();
|
||||
}
|
||||
}, [tracks, credentials]);
|
||||
|
||||
render() {
|
||||
const { tracks } = this.state;
|
||||
const { album } = this.props.route.params;
|
||||
// Retrieve album tracks on load
|
||||
useEffect(() => { dispatch(fetchTracksByAlbum(id)); }, []);
|
||||
|
||||
return (
|
||||
<ScrollView style={{ backgroundColor: '#f6f6f6', padding: 20, paddingBottom: 50 }}>
|
||||
<AlbumImage source={{ uri: getImage(album.Id) }} />
|
||||
<Text style={{ fontSize: 36, fontWeight: 'bold' }} >{album.Name}</Text>
|
||||
<Text style={{ fontSize: 24, opacity: 0.5, marginBottom: 24 }}>{album.AlbumArtist}</Text>
|
||||
<Button title="Play Album" onPress={this.playAlbum} />
|
||||
{tracks.length ? tracks.map((track) =>
|
||||
<TouchableTrack key={track.Id} id={track.Id} onPress={this.selectTrack}>
|
||||
<Text style={{ width: 20, opacity: 0.5, marginRight: 5 }}>{track.IndexNumber}</Text>
|
||||
<Text>{track.Name}</Text>
|
||||
</TouchableTrack>
|
||||
) : undefined}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<ScrollView style={{ backgroundColor: '#f6f6f6', padding: 20, paddingBottom: 50 }}>
|
||||
<AlbumImage source={{ uri: getImage(album.Id) }} />
|
||||
<Text style={{ fontSize: 36, fontWeight: 'bold' }} >{album?.Name}</Text>
|
||||
<Text style={{ fontSize: 24, opacity: 0.5, marginBottom: 24 }}>{album?.AlbumArtist}</Text>
|
||||
<Button title="Play Album" onPress={playAlbum} />
|
||||
{album?.Tracks?.length ? album.Tracks.map((trackId) =>
|
||||
<TouchableTrack key={trackId} id={trackId} onPress={selectTrack}>
|
||||
<Text style={{ width: 20, opacity: 0.5, marginRight: 5 }}>{tracks[trackId]?.IndexNumber}</Text>
|
||||
<Text>{tracks[trackId]?.Name}</Text>
|
||||
</TouchableTrack>
|
||||
) : undefined}
|
||||
</ScrollView>
|
||||
);
|
||||
};
|
||||
|
||||
export default Album;
|
||||
@@ -1,19 +1,13 @@
|
||||
import React, { Component, useCallback } from 'react';
|
||||
import { retrieveAlbums, getImage } from '../../../utility/JellyfinApi';
|
||||
import { Album, RootStackParamList } from '../types';
|
||||
import React, { useCallback, useEffect } from 'react';
|
||||
import { useGetImage } from '../../../utility/JellyfinApi';
|
||||
import { Album, NavigationProp } from '../types';
|
||||
import { Text, SafeAreaView, FlatList, Dimensions } from 'react-native';
|
||||
import styled from 'styled-components/native';
|
||||
import { TouchableOpacity } from 'react-native-gesture-handler';
|
||||
import { StackNavigationProp } from '@react-navigation/stack';
|
||||
|
||||
interface Props {
|
||||
navigation: StackNavigationProp<RootStackParamList, 'Albums'>;
|
||||
}
|
||||
|
||||
interface State {
|
||||
albums: Album[];
|
||||
refreshing: boolean;
|
||||
}
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { useTypedSelector } from '../../../store';
|
||||
import { fetchAllAlbums } from '../../../store/music/actions';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
|
||||
const Screen = Dimensions.get('screen');
|
||||
|
||||
@@ -57,51 +51,44 @@ const TouchableAlbumItem: React.FC<TouchableAlbumItemProps> = ({ id, onPress, c
|
||||
);
|
||||
};
|
||||
|
||||
class Albums extends Component<Props, State> {
|
||||
state: State = {
|
||||
albums: [],
|
||||
refreshing: false,
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.retrieveData();
|
||||
}
|
||||
|
||||
retrieveData = async () => {
|
||||
this.setState({ refreshing: true });
|
||||
const albums = await retrieveAlbums() as Album[];
|
||||
this.setState({ albums, refreshing: false });
|
||||
}
|
||||
const Albums: React.FC = () => {
|
||||
// Retrieve data from store
|
||||
const { ids, entities: albums } = useTypedSelector((state) => state.music.albums);
|
||||
const isLoading = useTypedSelector((state) => state.music.albums.isLoading);
|
||||
|
||||
selectAlbum = (id: string) => {
|
||||
const album = this.state.albums.find((d) => d.Id === id) as Album;
|
||||
this.props.navigation.navigate('Album', { id, album });
|
||||
}
|
||||
// Initialise helpers
|
||||
const dispatch = useDispatch();
|
||||
const navigation = useNavigation<NavigationProp>();
|
||||
const getImage = useGetImage();
|
||||
|
||||
render() {
|
||||
const { albums, refreshing } = this.state;
|
||||
// Set callbacks
|
||||
const retrieveData = useCallback(() => dispatch(fetchAllAlbums()), [dispatch]);
|
||||
const selectAlbum = useCallback((id: string) => navigation.navigate('Album', { id, album: albums[id] as Album }), [navigation, albums]);
|
||||
|
||||
// Retrieve data on mount
|
||||
useEffect(() => { retrieveData(); }, []);
|
||||
|
||||
return (
|
||||
<SafeAreaView>
|
||||
<Container>
|
||||
<FlatList
|
||||
data={ids as string[]}
|
||||
refreshing={isLoading}
|
||||
onRefresh={retrieveData}
|
||||
numColumns={2}
|
||||
keyExtractor={d => d}
|
||||
renderItem={({ item }) => (
|
||||
<TouchableAlbumItem id={item} onPress={selectAlbum}>
|
||||
<AlbumImage source={{ uri: getImage(item) }} />
|
||||
<Text>{albums[item]?.Name}</Text>
|
||||
<Text style={{ opacity: 0.5 }}>{albums[item]?.AlbumArtist}</Text>
|
||||
</TouchableAlbumItem>
|
||||
)}
|
||||
/>
|
||||
</Container>
|
||||
</SafeAreaView>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<SafeAreaView>
|
||||
<Container>
|
||||
<FlatList
|
||||
data={albums}
|
||||
keyExtractor={(item: Album) => item.Id}
|
||||
refreshing={refreshing}
|
||||
onRefresh={this.retrieveData}
|
||||
numColumns={2}
|
||||
renderItem={({ item }: { item: Album }) => (
|
||||
<TouchableAlbumItem id={item.Id} onPress={this.selectAlbum}>
|
||||
<AlbumImage source={{ uri: getImage(item.Id) }} />
|
||||
<Text>{item.Name}</Text>
|
||||
<Text style={{ opacity: 0.5 }}>{item.AlbumArtist}</Text>
|
||||
</TouchableAlbumItem>
|
||||
)}
|
||||
/>
|
||||
</Container>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default Albums;
|
||||
@@ -1,3 +1,5 @@
|
||||
import { StackNavigationProp } from '@react-navigation/stack';
|
||||
|
||||
export interface UserData {
|
||||
PlaybackPositionTicks: number;
|
||||
PlayCount: number;
|
||||
@@ -63,8 +65,9 @@ export interface AlbumTrack {
|
||||
MediaType: string;
|
||||
}
|
||||
|
||||
export type RootStackParamList = {
|
||||
export type StackParams = {
|
||||
Albums: undefined;
|
||||
Album: { id: string, album: Album };
|
||||
};
|
||||
|
||||
export type NavigationProp = StackNavigationProp<StackParams>;
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import React from 'react';
|
||||
import { View, Text, SafeAreaView } from 'react-native';
|
||||
import React, { useCallback } from 'react';
|
||||
import { View, Text, SafeAreaView, Button } from 'react-native';
|
||||
import { Picker } from '@react-native-community/picker';
|
||||
import { ScrollView } from 'react-native-gesture-handler';
|
||||
import styled from 'styled-components/native';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { AppState } from '../../store';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { NavigationProp } from '..';
|
||||
|
||||
const InputContainer = styled.View`
|
||||
margin: 10px 0;
|
||||
@@ -15,7 +20,9 @@ const Input = styled.TextInput`
|
||||
`;
|
||||
|
||||
export default function Settings() {
|
||||
|
||||
const { jellyfin, bitrate } = useSelector((state: AppState) => state.settings);
|
||||
const navigation = useNavigation<NavigationProp>();
|
||||
const handleClick = useCallback(() => navigation.navigate('SetJellyfinServer'), []);
|
||||
|
||||
return (
|
||||
<ScrollView>
|
||||
@@ -24,15 +31,22 @@ export default function Settings() {
|
||||
<Text style={{ fontSize: 36, marginBottom: 24, fontWeight: 'bold' }}>Settings</Text>
|
||||
<InputContainer>
|
||||
<Text>Jellyfin Server URL</Text>
|
||||
<Input placeholder="https://jellyfin.yourserver.com/" />
|
||||
<Input placeholder="https://jellyfin.yourserver.com/" value={jellyfin?.uri} editable={false} />
|
||||
</InputContainer>
|
||||
<InputContainer>
|
||||
<Text>Jellyfin API Key</Text>
|
||||
<Input placeholder="deadbeefdeadbeefdeadbeef" />
|
||||
<Text>Jellyfin Access Token</Text>
|
||||
<Input placeholder="deadbeefdeadbeefdeadbeef" value={jellyfin?.access_token} editable={false} />
|
||||
</InputContainer>
|
||||
<InputContainer>
|
||||
<Text>Jellyfin User ID</Text>
|
||||
<Input placeholder="deadbeefdeadbeefdeadbeef" />
|
||||
<Input placeholder="deadbeefdeadbeefdeadbeef" value={jellyfin?.user_id} editable={false} />
|
||||
</InputContainer>
|
||||
<Button title="Set Jellyfin server" onPress={handleClick} />
|
||||
<InputContainer>
|
||||
<Text>Bitrate</Text>
|
||||
<Picker selectedValue={bitrate}>
|
||||
<Picker.Item label="320kbps" value={140000000} />
|
||||
</Picker>
|
||||
</InputContainer>
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
|
||||
@@ -1,17 +1,51 @@
|
||||
import React from 'react';
|
||||
import { createBottomTabNavigator, BottomTabNavigationOptions } from '@react-navigation/bottom-tabs';
|
||||
import { createBottomTabNavigator, BottomTabNavigationProp } from '@react-navigation/bottom-tabs';
|
||||
import Player from './Player';
|
||||
import Albums from './Albums';
|
||||
import Settings from './Settings';
|
||||
import { createStackNavigator, StackNavigationProp } from '@react-navigation/stack';
|
||||
import SetJellyfinServer from './modals/SetJellyfinServer';
|
||||
import { CompositeNavigationProp } from '@react-navigation/native';
|
||||
|
||||
const Stack = createStackNavigator();
|
||||
const Tab = createBottomTabNavigator();
|
||||
|
||||
export default function Routes() {
|
||||
type Screens = {
|
||||
NowPlaying: undefined;
|
||||
Albums: undefined;
|
||||
Settings: undefined;
|
||||
}
|
||||
|
||||
function Screens() {
|
||||
return (
|
||||
<Tab.Navigator>
|
||||
<Tab.Screen name="Now Playing" component={Player} />
|
||||
<Tab.Screen name="NowPlaying" component={Player} />
|
||||
<Tab.Screen name="Albums" component={Albums} />
|
||||
<Tab.Screen name="Settings" component={Settings} />
|
||||
</Tab.Navigator>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
type Routes = {
|
||||
Screens: undefined;
|
||||
SetJellyfinServer: undefined;
|
||||
}
|
||||
|
||||
|
||||
export default function Routes() {
|
||||
return (
|
||||
<Stack.Navigator mode="modal" headerMode="none" screenOptions={{
|
||||
cardStyle: {
|
||||
backgroundColor: 'transparent'
|
||||
}
|
||||
}}>
|
||||
<Stack.Screen name="Screens" component={Screens} />
|
||||
<Stack.Screen name="SetJellyfinServer" component={SetJellyfinServer} />
|
||||
</Stack.Navigator>
|
||||
);
|
||||
}
|
||||
|
||||
export type NavigationProp = CompositeNavigationProp<
|
||||
StackNavigationProp<Routes>,
|
||||
BottomTabNavigationProp<Screens>
|
||||
>;
|
||||
@@ -0,0 +1,63 @@
|
||||
import React, { Component, createRef } from 'react';
|
||||
import { WebView, WebViewMessageEvent } from 'react-native-webview';
|
||||
import { debounce } from 'lodash';
|
||||
import { AppState } from '../../../../store';
|
||||
|
||||
interface Props {
|
||||
serverUrl: string;
|
||||
onCredentialsRetrieved: (credentials: AppState['settings']['jellyfin']) => void;
|
||||
}
|
||||
|
||||
class CredentialGenerator extends Component<Props> {
|
||||
ref = createRef<WebView>();
|
||||
|
||||
handleStateChange = () => {
|
||||
// Call a debounced version to check if the credentials are there
|
||||
this.checkIfCredentialsAreThere();
|
||||
}
|
||||
|
||||
checkIfCredentialsAreThere = debounce(() => {
|
||||
// Inject some javascript to check if the credentials can be extracted
|
||||
// from localstore
|
||||
this.ref.current?.injectJavaScript(`
|
||||
try {
|
||||
let credentials = JSON.parse(window.localStorage.getItem('jellyfin_credentials'));
|
||||
let deviceId = window.localStorage.getItem('_deviceId2');
|
||||
window.ReactNativeWebView.postMessage(JSON.stringify({ credentials, deviceId }))
|
||||
} catch(e) { }; true;
|
||||
`);
|
||||
}, 500);
|
||||
|
||||
handleMessage = (event: WebViewMessageEvent) => {
|
||||
// GUARD: Something must be returned for this thing to work
|
||||
if (!event.nativeEvent.data) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If a message is received, the credentials should be there
|
||||
const { credentials: { Servers: [ credentials ] }, deviceId } = JSON.parse(event.nativeEvent.data);
|
||||
this.props.onCredentialsRetrieved({
|
||||
uri: credentials.ManualAddress,
|
||||
user_id: credentials.UserId,
|
||||
access_token: credentials.AccessToken,
|
||||
device_id: deviceId,
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const { serverUrl } = this.props;
|
||||
|
||||
return (
|
||||
<WebView
|
||||
source={{ uri: serverUrl as string }}
|
||||
style={{ borderRadius: 20 }}
|
||||
onNavigationStateChange={this.handleStateChange}
|
||||
onMessage={this.handleMessage}
|
||||
ref={this.ref}
|
||||
startInLoadingState={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default CredentialGenerator;
|
||||
48
src/screens/modals/SetJellyfinServer/index.tsx
Normal file
48
src/screens/modals/SetJellyfinServer/index.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import React, { useState, useCallback } from 'react';
|
||||
import { Text, Button, View } from 'react-native';
|
||||
import Modal from '../../../components/Modal';
|
||||
import Input from '../../../components/Input';
|
||||
import { setJellyfinCredentials } from '../../../store/settings/actions';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { useNavigation, StackActions } from '@react-navigation/native';
|
||||
import CredentialGenerator from './components/CredentialGenerator';
|
||||
|
||||
export default function SetJellyfinServer() {
|
||||
// State for first screen
|
||||
const [serverUrl, setServerUrl] = useState<string>();
|
||||
const [isLogginIn, setIsLogginIn] = useState<boolean>(false);
|
||||
|
||||
// Handlers needed for dispatching stuff
|
||||
const dispatch = useDispatch();
|
||||
const navigation = useNavigation();
|
||||
|
||||
// Save creedentials to store and close the modal
|
||||
const saveCredentials = useCallback((credentials) => {
|
||||
dispatch(setJellyfinCredentials(credentials));
|
||||
navigation.dispatch(StackActions.popToTop());
|
||||
}, [navigation, dispatch]);
|
||||
|
||||
return (
|
||||
<Modal>
|
||||
{isLogginIn ? (
|
||||
<CredentialGenerator
|
||||
serverUrl={serverUrl as string}
|
||||
onCredentialsRetrieved={saveCredentials}
|
||||
/>
|
||||
) : (
|
||||
<View style={{ padding: 20}}>
|
||||
<Text>Please enter your Jellyfin server URL first. Make sure to include the protocol and port</Text>
|
||||
<Input
|
||||
placeholder="https://jellyfin.yourserver.io/"
|
||||
onChangeText={setServerUrl}
|
||||
value={serverUrl}
|
||||
keyboardType="url"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
<Button title="Set server" onPress={() => setIsLogginIn(true)} disabled={!serverUrl?.length} />
|
||||
</View>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
0
src/screens/types.ts
Normal file
0
src/screens/types.ts
Normal file
34
src/store/index.ts
Normal file
34
src/store/index.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { configureStore, getDefaultMiddleware, combineReducers } from '@reduxjs/toolkit';
|
||||
import { useSelector, TypedUseSelectorHook } from 'react-redux';
|
||||
import AsyncStorage from '@react-native-community/async-storage';
|
||||
import { persistStore, persistReducer } from 'redux-persist';
|
||||
import logger from 'redux-logger';
|
||||
|
||||
const persistConfig = {
|
||||
key: 'root',
|
||||
storage: AsyncStorage,
|
||||
};
|
||||
|
||||
import settings from './settings';
|
||||
import music from './music';
|
||||
|
||||
const reducers = combineReducers({
|
||||
settings,
|
||||
music: music.reducer,
|
||||
});
|
||||
|
||||
const persistedReducer = persistReducer(persistConfig, reducers);
|
||||
|
||||
const store = configureStore({
|
||||
reducer: persistedReducer,
|
||||
middleware: getDefaultMiddleware({ serializableCheck: false }).concat(logger, ),
|
||||
});
|
||||
|
||||
export type AppState = ReturnType<typeof store.getState>;
|
||||
export type AppDispatch = typeof store.dispatch;
|
||||
export type AsyncThunkAPI = { state: AppState, dispatch: AppDispatch };
|
||||
export const useTypedSelector: TypedUseSelectorHook<AppState> = useSelector;
|
||||
|
||||
export const persistedStore = persistStore(store);
|
||||
|
||||
export default store;
|
||||
32
src/store/music/actions.ts
Normal file
32
src/store/music/actions.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { createAsyncThunk, createEntityAdapter } from '@reduxjs/toolkit';
|
||||
import { Album, AlbumTrack } from './types';
|
||||
import { AsyncThunkAPI } from '..';
|
||||
import { retrieveAlbums, retrieveAlbumTracks } from '../../utility/JellyfinApi';
|
||||
|
||||
export const albumAdapter = createEntityAdapter<Album>({
|
||||
selectId: album => album.Id,
|
||||
sortComparer: (a, b) => a.Name.localeCompare(b.Name),
|
||||
});
|
||||
|
||||
export const fetchAllAlbums = createAsyncThunk<Album[], undefined, AsyncThunkAPI>(
|
||||
'/albums/all',
|
||||
async (empty, thunkAPI) => {
|
||||
console.log('RETRIEVING ALBUMS');
|
||||
const credentials = thunkAPI.getState().settings.jellyfin;
|
||||
return retrieveAlbums(credentials) as Promise<Album[]>;
|
||||
}
|
||||
);
|
||||
|
||||
export const trackAdapter = createEntityAdapter<AlbumTrack>({
|
||||
selectId: track => track.Id,
|
||||
sortComparer: (a, b) => a.IndexNumber - b.IndexNumber,
|
||||
});
|
||||
|
||||
export const fetchTracksByAlbum = createAsyncThunk<AlbumTrack[], string, AsyncThunkAPI>(
|
||||
'/tracks/byAlbum',
|
||||
async (ItemId, thunkAPI) => {
|
||||
console.log('RETRIEVING ALBUMS');
|
||||
const credentials = thunkAPI.getState().settings.jellyfin;
|
||||
return retrieveAlbumTracks(ItemId, credentials) as Promise<AlbumTrack[]>;
|
||||
}
|
||||
);
|
||||
41
src/store/music/index.ts
Normal file
41
src/store/music/index.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { fetchAllAlbums, albumAdapter, fetchTracksByAlbum, trackAdapter } from './actions';
|
||||
import { createSlice } from '@reduxjs/toolkit';
|
||||
|
||||
const initialState = {
|
||||
albums: {
|
||||
...albumAdapter.getInitialState(),
|
||||
isLoading: false,
|
||||
},
|
||||
tracks: {
|
||||
...trackAdapter.getInitialState(),
|
||||
isLoading: false,
|
||||
},
|
||||
};
|
||||
|
||||
const music = createSlice({
|
||||
name: 'music',
|
||||
initialState,
|
||||
reducers: {},
|
||||
extraReducers: builder => {
|
||||
builder.addCase(fetchAllAlbums.fulfilled, (state, { payload }) => {
|
||||
albumAdapter.setAll(state.albums, payload);
|
||||
state.albums.isLoading = false;
|
||||
});
|
||||
builder.addCase(fetchAllAlbums.pending, (state) => { state.albums.isLoading = true; });
|
||||
builder.addCase(fetchAllAlbums.rejected, (state) => { state.albums.isLoading = false; });
|
||||
builder.addCase(fetchTracksByAlbum.fulfilled, (state, { payload }) => {
|
||||
trackAdapter.setAll(state.tracks, payload);
|
||||
|
||||
// Also store all the track ids in the album
|
||||
const album = state.albums.entities[payload[0].AlbumId];
|
||||
if (album) {
|
||||
album.Tracks = payload.map(d => d.Id);
|
||||
}
|
||||
state.tracks.isLoading = false;
|
||||
});
|
||||
builder.addCase(fetchTracksByAlbum.pending, (state) => { state.tracks.isLoading = true; });
|
||||
builder.addCase(fetchTracksByAlbum.rejected, (state) => { state.tracks.isLoading = false; });
|
||||
}
|
||||
});
|
||||
|
||||
export default music;
|
||||
75
src/store/music/types.ts
Normal file
75
src/store/music/types.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { Dictionary } from 'lodash';
|
||||
|
||||
export interface UserData {
|
||||
PlaybackPositionTicks: number;
|
||||
PlayCount: number;
|
||||
IsFavorite: boolean;
|
||||
Played: boolean;
|
||||
Key: string;
|
||||
}
|
||||
|
||||
export interface ArtistItem {
|
||||
Name: string;
|
||||
Id: string;
|
||||
}
|
||||
|
||||
export interface AlbumArtist {
|
||||
Name: string;
|
||||
Id: string;
|
||||
}
|
||||
|
||||
export interface ImageTags {
|
||||
Primary: string;
|
||||
}
|
||||
|
||||
export interface Album {
|
||||
Name: string;
|
||||
ServerId: string;
|
||||
Id: string;
|
||||
SortName: string;
|
||||
RunTimeTicks: number;
|
||||
ProductionYear: number;
|
||||
IsFolder: boolean;
|
||||
Type: string;
|
||||
UserData: UserData;
|
||||
PrimaryImageAspectRatio: number;
|
||||
Artists: string[];
|
||||
ArtistItems: ArtistItem[];
|
||||
AlbumArtist: string;
|
||||
AlbumArtists: AlbumArtist[];
|
||||
ImageTags: ImageTags;
|
||||
BackdropImageTags: any[];
|
||||
LocationType: string;
|
||||
Tracks?: string[];
|
||||
}
|
||||
|
||||
export interface AlbumTrack {
|
||||
Name: string;
|
||||
ServerId: string;
|
||||
Id: string;
|
||||
RunTimeTicks: number;
|
||||
ProductionYear: number;
|
||||
IndexNumber: number;
|
||||
IsFolder: boolean;
|
||||
Type: string;
|
||||
UserData: UserData;
|
||||
Artists: string[];
|
||||
ArtistItems: ArtistItem[];
|
||||
Album: string;
|
||||
AlbumId: string;
|
||||
AlbumPrimaryImageTag: string;
|
||||
AlbumArtist: string;
|
||||
AlbumArtists: AlbumArtist[];
|
||||
ImageTags: ImageTags;
|
||||
BackdropImageTags: any[];
|
||||
LocationType: string;
|
||||
MediaType: string;
|
||||
}
|
||||
|
||||
export interface State {
|
||||
albums: {
|
||||
ids: string[];
|
||||
entities: Dictionary<Album>;
|
||||
isLoading: boolean;
|
||||
}
|
||||
}
|
||||
4
src/store/settings/actions.ts
Normal file
4
src/store/settings/actions.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { createAction } from '@reduxjs/toolkit';
|
||||
|
||||
export const setJellyfinCredentials = createAction<{ access_token: string, user_id: string, uri: string, deviced_id: string; }>('SET_JELLYFIN_CREDENTIALS');
|
||||
export const setBitrate = createAction<number>('SET_BITRATE');
|
||||
29
src/store/settings/index.ts
Normal file
29
src/store/settings/index.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { createReducer } from '@reduxjs/toolkit';
|
||||
import { setBitrate, setJellyfinCredentials } from './actions';
|
||||
|
||||
interface State {
|
||||
jellyfin?: {
|
||||
uri: string;
|
||||
user_id: string;
|
||||
access_token: string;
|
||||
device_id: string;
|
||||
}
|
||||
bitrate: number;
|
||||
}
|
||||
|
||||
const initialState: State = {
|
||||
bitrate: 140000000
|
||||
};
|
||||
|
||||
const settings = createReducer(initialState, {
|
||||
[setJellyfinCredentials.type]: (state, action) => ({
|
||||
...state,
|
||||
jellyfin: action.payload,
|
||||
}),
|
||||
[setBitrate.type]: (state, action) => ({
|
||||
...state,
|
||||
bitrate: action.payload,
|
||||
}),
|
||||
});
|
||||
|
||||
export default settings;
|
||||
@@ -1,15 +1,18 @@
|
||||
import { Track } from 'react-native-track-player';
|
||||
import { AppState, useTypedSelector } from '../store';
|
||||
import { AlbumTrack } from '../store/music/types';
|
||||
|
||||
const JELLYFIN_SERVER = '***REMOVED***';
|
||||
const API_KEY = '***REMOVED***';
|
||||
const DEVICE_ID =
|
||||
'***REMOVED***';
|
||||
const USER_ID = '***REMOVED***';
|
||||
type Credentials = AppState['settings']['jellyfin'];
|
||||
|
||||
const trackOptions: Record<string, string> = {
|
||||
DeviceId: DEVICE_ID,
|
||||
UserId: USER_ID,
|
||||
api_key: API_KEY,
|
||||
function generateConfig(credentials: Credentials): RequestInit {
|
||||
return {
|
||||
headers: {
|
||||
'X-Emby-Authorization': `MediaBrowser Client="", Device="", DeviceId="", Version="", Token="${credentials?.access_token}"`
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const baseTrackOptions: Record<string, string> = {
|
||||
// Not sure where this number refers to, but setting it to 140000000 appears
|
||||
// to do wonders for making stuff work
|
||||
MaxStreamingBitrate: '140000000',
|
||||
@@ -24,37 +27,33 @@ const trackOptions: Record<string, string> = {
|
||||
Container: 'mp3,aac,m4a,m4b|aac,alac,m4a,m4b|alac',
|
||||
AudioCodec: 'aac',
|
||||
static: 'true',
|
||||
// These last few options appear to be redundant
|
||||
// EnableRedirection: 'true',
|
||||
// EnableRemoteMedia: 'false',
|
||||
// // this should be generated client-side and is intended to be a unique value per stream URL
|
||||
// PlaySessionId: Math.floor(Math.random() * 10000000).toString(),
|
||||
// StartTimeTicks: '0',
|
||||
};
|
||||
|
||||
const trackParams = new URLSearchParams(trackOptions).toString();
|
||||
|
||||
/**
|
||||
* Generate a track object from a Jellyfin ItemId so that
|
||||
* react-native-track-player can easily consume it.
|
||||
*/
|
||||
export async function generateTrack(ItemId: string): Promise<Track> {
|
||||
// First off, fetch all the metadata for this particular track from the
|
||||
// Jellyfin server
|
||||
const track = await fetch(`${JELLYFIN_SERVER}/Users/${USER_ID}/Items/${ItemId}?api_key=${API_KEY}`)
|
||||
.then(response => response.json());
|
||||
|
||||
export function generateTrack(track: AlbumTrack, credentials: Credentials): Track {
|
||||
// Also construct the URL for the stream
|
||||
const url = encodeURI(`${JELLYFIN_SERVER}/Audio/${ItemId}/universal.mp3?${trackParams}`);
|
||||
const trackOptions = {
|
||||
...baseTrackOptions,
|
||||
UserId: credentials?.user_id || '',
|
||||
api_key: credentials?.access_token || '',
|
||||
DeviceId: credentials?.device_id || '',
|
||||
};
|
||||
const trackParams = new URLSearchParams(trackOptions).toString();
|
||||
const url = encodeURI(`${credentials?.uri}/Audio/${track.Id}/universal.mp3?${trackParams}`);
|
||||
|
||||
return {
|
||||
id: ItemId,
|
||||
id: track.Id,
|
||||
url,
|
||||
title: track.Name,
|
||||
artist: track.Artists.join(', '),
|
||||
album: track.Album,
|
||||
genre: Array.isArray(track.Genres) ? track.Genres[0] : undefined,
|
||||
artwork: getImage(ItemId),
|
||||
// genre: Array.isArray(track.Genres) ? track.Genres[0] : undefined,
|
||||
artwork: getImage(track.Id, credentials),
|
||||
...generateConfig(credentials),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -66,10 +65,6 @@ const albumOptions = {
|
||||
Fields: 'PrimaryImageAspectRatio,SortName,BasicSyncInfo',
|
||||
ImageTypeLimit: '1',
|
||||
EnableImageTypes: 'Primary,Backdrop,Banner,Thumb',
|
||||
api_key: API_KEY,
|
||||
// StartIndex: '0',
|
||||
// Limit: '100',
|
||||
// ParentId: '7e64e319657a9516ec78490da03edccb',
|
||||
};
|
||||
|
||||
const albumParams = new URLSearchParams(albumOptions).toString();
|
||||
@@ -77,8 +72,10 @@ const albumParams = new URLSearchParams(albumOptions).toString();
|
||||
/**
|
||||
* Retrieve all albums that are available on the Jellyfin server
|
||||
*/
|
||||
export async function retrieveAlbums() {
|
||||
const albums = await fetch(`${JELLYFIN_SERVER}/Users/${USER_ID}/Items?${albumParams}`)
|
||||
export async function retrieveAlbums(credentials: Credentials) {
|
||||
const config = generateConfig(credentials);
|
||||
console.log(`${credentials?.uri}/Users/${credentials?.user_id}/Items?${albumParams}`);
|
||||
const albums = await fetch(`${credentials?.uri}/Users/${credentials?.user_id}/Items?${albumParams}`, config)
|
||||
.then(response => response.json());
|
||||
|
||||
return albums.Items;
|
||||
@@ -87,20 +84,25 @@ export async function retrieveAlbums() {
|
||||
/**
|
||||
* Retrieve a single album from the Emby server
|
||||
*/
|
||||
export async function retrieveAlbumTracks(ItemId: string) {
|
||||
export async function retrieveAlbumTracks(ItemId: string, credentials: Credentials) {
|
||||
const singleAlbumOptions = {
|
||||
ParentId: ItemId,
|
||||
SortBy: 'SortName',
|
||||
api_key: API_KEY,
|
||||
};
|
||||
const singleAlbumParams = new URLSearchParams(singleAlbumOptions).toString();
|
||||
|
||||
const album = await fetch(`${JELLYFIN_SERVER}/Users/${USER_ID}/Items?${singleAlbumParams}`)
|
||||
const config = generateConfig(credentials);
|
||||
const album = await fetch(`${credentials?.uri}/Users/${credentials?.user_id}/Items?${singleAlbumParams}`, config)
|
||||
.then(response => response.json());
|
||||
|
||||
return album.Items;
|
||||
}
|
||||
|
||||
export function getImage(ItemId: string): string {
|
||||
return encodeURI(`${JELLYFIN_SERVER}/Items/${ItemId}/Images/Primary?format=jpeg`);
|
||||
export function getImage(ItemId: string, credentials: Credentials): string {
|
||||
return encodeURI(`${credentials?.uri}/Items/${ItemId}/Images/Primary?format=jpeg`);
|
||||
}
|
||||
|
||||
export function useGetImage() {
|
||||
const credentials = useTypedSelector((state) => state.settings.jellyfin);
|
||||
return (ItemId: string) => getImage(ItemId, credentials);
|
||||
}
|
||||
Reference in New Issue
Block a user