koel/resources/assets/js/stores/songStore.ts

317 lines
8.9 KiB
TypeScript
Raw Normal View History

2022-04-15 14:24:30 +00:00
import isMobile from 'ismobilejs'
2022-06-10 10:47:46 +00:00
import slugify from 'slugify'
import { merge, orderBy, sumBy, take, unionBy, uniqBy } from 'lodash'
2024-03-18 22:04:01 +00:00
import { reactive, watch } from 'vue'
2024-05-19 05:49:42 +00:00
import { arrayify, isSong, logger, secondsToHumanReadable, use } from '@/utils'
import { authService, cache, http } from '@/services'
import { albumStore, artistStore, commonStore, overviewStore, playlistStore, preferenceStore } from '@/stores'
2022-04-15 14:24:30 +00:00
export interface SongUpdateData {
2022-07-24 11:47:18 +00:00
title?: string
artist_name?: string
album_name?: string
album_artist_name?: string
track?: number | null
disc?: number | null
lyrics?: string
year?: number | null
genre?: string
visibility?: 'public' | 'private' | 'unchanged'
2022-04-15 14:24:30 +00:00
}
2022-07-24 11:47:18 +00:00
export interface SongUpdateResult {
2022-04-15 14:24:30 +00:00
songs: Song[]
artists: Artist[]
albums: Album[]
2022-06-10 10:47:46 +00:00
removed: {
albums: Pick<Album, 'id' | 'artist_id' | 'name' | 'cover' | 'created_at'>[]
artists: Pick<Artist, 'id' | 'name' | 'image' | 'created_at'>[]
}
2022-04-15 14:24:30 +00:00
}
export interface SongListPaginateParams extends Record<string, any> {
2024-05-19 05:49:42 +00:00
sort: MaybeArray<PlayableListSortField>
order: SortOrder
page: number
own_songs_only: boolean
}
export interface GenreSongListPaginateParams extends Record<string, any> {
2024-05-19 05:49:42 +00:00
sort: MaybeArray<PlayableListSortField>
order: SortOrder
page: number
}
2022-04-15 14:24:30 +00:00
export const songStore = {
2024-05-19 05:49:42 +00:00
vault: new Map<Playable['id'], Playable>(),
2022-04-15 14:24:30 +00:00
state: reactive<{ songs: Playable[] }>({
songs: [],
2022-04-20 09:37:22 +00:00
}),
2022-04-15 14:24:30 +00:00
getFormattedLength: (playables: MaybeArray<Playable>) => secondsToHumanReadable(sumBy(arrayify(playables), 'length')),
2022-04-15 14:24:30 +00:00
2024-07-05 12:20:30 +00:00
byId (id: Playable['id']) {
const playable = this.vault.get(id)
2024-05-19 05:49:42 +00:00
if (!playable) {
return
}
if (isSong(playable) && playable.deleted) {
return
}
2024-07-05 12:20:30 +00:00
return playable
2022-04-15 14:24:30 +00:00
},
2024-07-05 12:20:30 +00:00
byIds (ids: Playable['id'][]) {
2024-05-19 05:49:42 +00:00
const playables: Playable[] = []
ids.forEach(id => use(this.byId(id), song => playables.push(song!)))
return playables
2022-04-15 14:24:30 +00:00
},
2022-06-10 10:47:46 +00:00
byAlbum (album: Album) {
2024-07-05 10:04:31 +00:00
return Array.from(this.vault.values())
.filter(playable => isSong(playable) && playable.album_id === album.id) as Song[]
2022-06-10 10:47:46 +00:00
},
2024-07-05 12:20:30 +00:00
async resolve (id: Playable['id']) {
let playable = this.byId(id)
2022-07-05 21:43:35 +00:00
if (!playable) {
2022-07-24 11:47:18 +00:00
try {
playable = this.syncWithVault(await http.get<Playable>(`songs/${id}`))[0]
} catch (error: unknown) {
logger.error(error)
2022-07-24 11:47:18 +00:00
}
2022-07-05 21:43:35 +00:00
}
2022-07-24 11:47:18 +00:00
return playable
2022-07-05 21:43:35 +00:00
},
2022-04-15 14:24:30 +00:00
/**
2022-06-10 10:47:46 +00:00
* Match a title to a song.
2022-04-15 14:24:30 +00:00
* Forget about Levenshtein distance, this implementation is good enough.
*/
2022-06-10 10:47:46 +00:00
match: (title: string, songs: Song[]) => {
2022-04-15 14:24:30 +00:00
title = slugify(title.toLowerCase())
2022-06-10 10:47:46 +00:00
for (const song of songs) {
2022-04-15 14:24:30 +00:00
if (slugify(song.title.toLowerCase()) === title) {
return song
}
}
return null
},
/**
2024-05-19 05:49:42 +00:00
* Increase a play count for a playable.
2022-04-15 14:24:30 +00:00
*/
2024-05-19 05:49:42 +00:00
registerPlay: async (playable: Playable) => {
const interaction = await http.silently.post<Interaction>('interaction/play', { song: playable.id })
2022-04-15 14:24:30 +00:00
// Use the data from the server to make sure we don't miss a play from another device.
2024-05-19 05:49:42 +00:00
playable.play_count = interaction.play_count
2022-04-15 14:24:30 +00:00
},
2024-05-19 05:49:42 +00:00
scrobble: async (song: Song) => {
if (!isSong(song)) {
throw new Error('Scrobble is only supported for songs.')
2024-05-19 05:49:42 +00:00
}
return await http.silently.post(`songs/${song.id}/scrobble`, {
timestamp: song.play_start_time,
2024-05-19 05:49:42 +00:00
})
},
2022-04-15 14:24:30 +00:00
2022-07-24 11:47:18 +00:00
async update (songsToUpdate: Song[], data: SongUpdateData) {
2024-05-19 05:49:42 +00:00
if (songsToUpdate.some(song => !isSong(song))) {
throw new Error('Only songs can be updated.')
2024-05-19 05:49:42 +00:00
}
const result = await http.put<SongUpdateResult>('songs', {
2022-04-15 14:24:30 +00:00
data,
songs: songsToUpdate.map(song => song.id),
2022-04-15 14:24:30 +00:00
})
this.syncWithVault(result.songs)
2022-04-15 14:24:30 +00:00
albumStore.syncWithVault(result.albums)
artistStore.syncWithVault(result.artists)
2022-04-15 14:24:30 +00:00
albumStore.removeByIds(result.removed.albums.map(album => album.id))
artistStore.removeByIds(result.removed.artists.map(artist => artist.id))
return result
2022-06-10 10:47:46 +00:00
},
2024-05-19 05:49:42 +00:00
getSourceUrl: (playable: Playable) => {
return isMobile.any && preferenceStore.transcode_on_mobile
? `${commonStore.state.cdn_url}play/${playable.id}/1?t=${authService.getAudioToken()}`
2024-05-19 05:49:42 +00:00
: `${commonStore.state.cdn_url}play/${playable.id}?t=${authService.getAudioToken()}`
2022-06-10 10:47:46 +00:00
},
getShareableUrl: (song: Playable) => `${window.BASE_URL}#/song/${song.id}`,
2022-06-10 10:47:46 +00:00
syncWithVault (playables: MaybeArray<Playable>) {
return arrayify(playables).map(playable => {
let local = this.byId(playable.id)
2022-04-15 14:24:30 +00:00
2022-06-10 10:47:46 +00:00
if (local) {
merge(local, playable)
2022-06-10 10:47:46 +00:00
} else {
local = reactive(playable)
2022-07-24 11:47:18 +00:00
local.playback_state = 'Stopped'
this.watchPlayCount(local)
2022-07-24 11:47:18 +00:00
this.vault.set(local.id, local)
2022-04-15 14:24:30 +00:00
}
2022-06-10 10:47:46 +00:00
return local
2022-04-15 14:24:30 +00:00
})
2022-06-10 10:47:46 +00:00
},
2022-04-15 14:24:30 +00:00
2024-05-19 05:49:42 +00:00
watchPlayCount: (playable: Playable) => {
watch(() => playable.play_count, () => overviewStore.refreshPlayStats())
2022-04-15 14:24:30 +00:00
},
ensureNotDeleted: (songs: MaybeArray<Song>) => arrayify(songs).filter(({ deleted }) => !deleted),
2024-07-05 12:20:30 +00:00
async fetchForAlbum (album: Album | Album['id']) {
2022-07-30 15:08:20 +00:00
const id = typeof album === 'number' ? album : album.id
return this.ensureNotDeleted(await cache.remember<Song[]>(
[`album.songs`, id],
async () => this.syncWithVault(await http.get<Song[]>(`albums/${id}/songs`)),
))
2022-04-15 14:24:30 +00:00
},
2024-07-05 12:20:30 +00:00
async fetchForArtist (artist: Artist | Artist['id']) {
2022-07-30 15:08:20 +00:00
const id = typeof artist === 'number' ? artist : artist.id
return this.ensureNotDeleted(await cache.remember<Song[]>(
[`artist.songs`, id],
async () => this.syncWithVault(await http.get<Song[]>(`artists/${id}/songs`)),
))
2022-06-10 10:47:46 +00:00
},
2022-04-15 14:24:30 +00:00
async fetchForPlaylist (playlist: Playlist | Playlist['id'], refresh = false) {
2024-01-18 11:13:05 +00:00
const id = typeof playlist === 'string' ? playlist : playlist.id
if (refresh) {
cache.remove(['playlist.songs', id])
}
const songs = this.ensureNotDeleted(await cache.remember<Song[]>(
[`playlist.songs`, id],
async () => this.syncWithVault(await http.get<Song[]>(`playlists/${id}/songs`)),
))
playlistStore.byId(id)!.playables = songs
return songs
2022-04-15 14:24:30 +00:00
},
async fetchForPlaylistFolder (folder: PlaylistFolder) {
const playables: Playable[] = []
for await (const playlist of playlistStore.byFolder(folder)) {
playables.push(...await songStore.fetchForPlaylist(playlist))
}
return uniqBy(playables, 'id')
},
2024-07-05 12:20:30 +00:00
async fetchForPodcast (podcast: Podcast | Podcast['id'], refresh = false) {
2024-05-19 05:49:42 +00:00
const id = typeof podcast === 'string' ? podcast : podcast.id
if (refresh) {
cache.remove(['podcast.episodes', id])
}
return await cache.remember<Episode[]>(
[`podcast.episodes`, id],
async () => this.syncWithVault(await http.get<Episode[]>(`podcasts/${id}/episodes${refresh ? '?refresh=1' : ''}`)),
2024-05-19 05:49:42 +00:00
)
},
async paginateForGenre (genre: Genre | Genre['name'], params: GenreSongListPaginateParams) {
2022-10-21 20:06:43 +00:00
const name = typeof genre === 'string' ? genre : genre.name
2024-07-05 10:04:31 +00:00
const resource = await http.get<PaginatorResource<Song>>(
`genres/${name}/songs?${new URLSearchParams(params).toString()}`,
2024-07-05 10:04:31 +00:00
)
2022-10-21 20:06:43 +00:00
const songs = this.syncWithVault(resource.data)
return {
songs,
nextPage: resource.links.next ? ++resource.meta.current_page : null,
2022-10-21 20:06:43 +00:00
}
},
async fetchRandomForGenre (genre: Genre | Genre['name'], limit = 500) {
2022-10-21 20:06:43 +00:00
const name = typeof genre === 'string' ? genre : genre.name
return this.syncWithVault(await http.get<Song[]>(`genres/${name}/songs/random?limit=${limit}`))
},
async paginate (params: SongListPaginateParams) {
2024-07-05 10:04:31 +00:00
const resource = await http.get<PaginatorResource<Song>>(`songs?${new URLSearchParams(params).toString()}`)
2022-07-22 21:56:13 +00:00
this.state.songs = unionBy(this.state.songs, this.syncWithVault(resource.data), 'id')
2022-04-15 14:24:30 +00:00
2022-06-10 10:47:46 +00:00
return resource.links.next ? ++resource.meta.current_page : null
2022-04-15 14:24:30 +00:00
},
2022-06-10 10:47:46 +00:00
getMostPlayed (count: number) {
return take(
orderBy(
2024-05-19 05:49:42 +00:00
Array
.from(this.vault.values())
.filter(playable => isSong(playable) && !playable.deleted && playable.play_count > 0),
'play_count',
'desc',
),
count,
)
2022-04-15 14:24:30 +00:00
},
async deleteFromFilesystem (songs: Song[]) {
const ids = songs.map(song => {
// Whenever a vault sync is requested (e.g. upon playlist/album/artist fetching)
// songs marked as "deleted" will be excluded.
song.deleted = true
return song.id
})
await http.delete('songs', { songs: ids })
},
async publicize (songs: Song[]) {
2024-05-19 05:49:42 +00:00
if (songs.some(song => !isSong(song))) {
throw new Error('This action is only supported for songs.')
2024-05-19 05:49:42 +00:00
}
2024-01-16 21:14:14 +00:00
await http.put('songs/publicize', {
songs: songs.map(song => song.id),
})
songs.forEach(song => (song.is_public = true))
},
async privatize (songs: Song[]) {
2024-05-19 05:49:42 +00:00
if (songs.some(song => !isSong(song))) {
throw new Error('This action is only supported for songs.')
2024-05-19 05:49:42 +00:00
}
const privatizedIds = await http.put<Song['id'][]>('songs/privatize', {
songs: songs.map(({ id }) => id),
})
privatizedIds.forEach(id => {
2024-05-19 05:49:42 +00:00
const song = this.byId(id) as Song
song && (song.is_public = false)
})
return privatizedIds
},
2022-04-15 14:24:30 +00:00
}