Files
jellyfin-audio-player/src/store/music/index.ts

85 lines
2.8 KiB
TypeScript
Raw Normal View History

2020-06-21 13:02:23 +02:00
import { fetchAllAlbums, albumAdapter, fetchTracksByAlbum, trackAdapter, fetchRecentAlbums } from './actions';
2020-06-20 23:10:19 +02:00
import { createSlice, Dictionary, EntityId } from '@reduxjs/toolkit';
import { Album, AlbumTrack } from './types';
import { setJellyfinCredentials } from 'store/settings/actions';
2020-06-17 14:58:04 +02:00
2020-06-20 23:10:19 +02:00
export interface State {
albums: {
isLoading: boolean;
entities: Dictionary<Album>;
ids: EntityId[];
},
tracks: {
isLoading: boolean;
entities: Dictionary<AlbumTrack>;
ids: EntityId[];
},
lastRefreshed?: number,
2020-06-20 23:10:19 +02:00
}
const initialState: State = {
2020-06-17 14:58:04 +02:00
albums: {
...albumAdapter.getInitialState(),
isLoading: false,
},
tracks: {
...trackAdapter.getInitialState(),
isLoading: false,
},
};
const music = createSlice({
name: 'music',
initialState,
reducers: {
reset: () => initialState,
},
2020-06-17 14:58:04 +02:00
extraReducers: builder => {
2020-06-21 13:02:23 +02:00
/**
* Fetch All albums
*/
2020-06-17 14:58:04 +02:00
builder.addCase(fetchAllAlbums.fulfilled, (state, { payload }) => {
albumAdapter.setAll(state.albums, payload);
state.albums.isLoading = false;
state.lastRefreshed = new Date().getTime();
2020-06-17 14:58:04 +02:00
});
builder.addCase(fetchAllAlbums.pending, (state) => { state.albums.isLoading = true; });
builder.addCase(fetchAllAlbums.rejected, (state) => { state.albums.isLoading = false; });
2020-06-21 13:02:23 +02:00
/**
* Fetch most recent albums
*/
builder.addCase(fetchRecentAlbums.fulfilled, (state, { payload }) => {
albumAdapter.upsertMany(state.albums, payload);
state.albums.isLoading = false;
});
builder.addCase(fetchRecentAlbums.pending, (state) => { state.albums.isLoading = true; });
builder.addCase(fetchRecentAlbums.rejected, (state) => { state.albums.isLoading = false; });
/**
* Fetch tracks by album
*/
2020-06-17 14:58:04 +02:00
builder.addCase(fetchTracksByAlbum.fulfilled, (state, { payload }) => {
if (!payload.length) {
return;
}
trackAdapter.upsertMany(state.tracks, payload);
2020-06-17 14:58:04 +02:00
// 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);
album.lastRefreshed = new Date().getTime();
2020-06-17 14:58:04 +02:00
}
state.tracks.isLoading = false;
});
builder.addCase(fetchTracksByAlbum.pending, (state) => { state.tracks.isLoading = true; });
builder.addCase(fetchTracksByAlbum.rejected, (state) => { state.tracks.isLoading = false; });
// Reset any caches we have when a new server is set
builder.addCase(setJellyfinCredentials, () => initialState);
2020-06-17 14:58:04 +02:00
}
});
export default music;