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

272 lines
7.6 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'
import { arrayify, 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
2022-07-24 11:47:18 +00:00
export type SongUpdateData = {
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> {
sort: SongListSortField
order: SortOrder
page: number
own_songs_only: boolean
}
export interface GenreSongListPaginateParams extends Record<string, any> {
sort: SongListSortField
order: SortOrder
page: number
}
2022-04-15 14:24:30 +00:00
export const songStore = {
2024-03-18 22:04:01 +00:00
vault: new Map<Song['id'], Song>(),
2022-04-15 14:24:30 +00:00
2022-04-20 09:37:22 +00:00
state: reactive({
2022-06-10 10:47:46 +00:00
songs: [] as Song[]
2022-04-20 09:37:22 +00:00
}),
2022-04-15 14:24:30 +00:00
getFormattedLength: (songs: Song | Song[]) => secondsToHumanReadable(sumBy(arrayify(songs), 'length')),
2022-04-15 14:24:30 +00:00
byId (id: string) {
const song = this.vault.get(id)
return song?.deleted ? undefined : song
2022-04-15 14:24:30 +00:00
},
byIds (ids: string[]) {
2022-04-15 14:24:30 +00:00
const songs = [] as Song[]
2022-06-10 10:47:46 +00:00
ids.forEach(id => use(this.byId(id), song => songs.push(song!)))
2022-04-15 14:24:30 +00:00
return songs
},
2022-06-10 10:47:46 +00:00
byAlbum (album: Album) {
2024-01-24 22:39:47 +00:00
return Array.from(this.vault.values()).filter(({ album_id }) => album_id === album.id)
2022-06-10 10:47:46 +00:00
},
2022-07-05 21:43:35 +00:00
async resolve (id: string) {
2022-07-24 11:47:18 +00:00
let song = this.byId(id)
2022-07-05 21:43:35 +00:00
2022-07-24 11:47:18 +00:00
if (!song) {
try {
song = this.syncWithVault(await http.get<Song>(`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 song
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
},
/**
* Increase a play count for a song.
*/
registerPlay: async (song: Song) => {
const interaction = await http.silently.post<Interaction>('interaction/play', { song: song.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.
2022-06-10 10:47:46 +00:00
song.play_count = interaction.play_count
2022-04-15 14:24:30 +00:00
},
scrobble: async (song: Song) => await http.silently.post(`songs/${song.id}/scrobble`, {
2022-07-24 11:47:18 +00:00
timestamp: song.play_start_time
}),
2022-04-15 14:24:30 +00:00
2022-07-24 11:47:18 +00:00
async update (songsToUpdate: Song[], data: SongUpdateData) {
const result = await http.put<SongUpdateResult>('songs', {
2022-04-15 14:24:30 +00:00
data,
songs: songsToUpdate.map(song => song.id)
})
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
},
getSourceUrl: (song: Song) => {
return isMobile.any && preferenceStore.transcode_on_mobile
2022-11-16 17:57:38 +00:00
? `${commonStore.state.cdn_url}play/${song.id}/1/128?t=${authService.getAudioToken()}`
: `${commonStore.state.cdn_url}play/${song.id}?t=${authService.getAudioToken()}`
2022-06-10 10:47:46 +00:00
},
getShareableUrl: (song: Song) => `${window.BASE_URL}#/song/${song.id}`,
2022-06-10 10:47:46 +00:00
syncWithVault (songs: Song | Song[]) {
return arrayify(songs).map(song => {
let local = this.byId(song.id)
2022-04-15 14:24:30 +00:00
2022-06-10 10:47:46 +00:00
if (local) {
2022-07-24 11:47:18 +00:00
merge(local, song)
2022-06-10 10:47:46 +00:00
} else {
local = reactive(song)
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-03-18 22:04:01 +00:00
watchPlayCount: (song: Song) => {
watch(() => song.play_count, () => overviewStore.refreshPlayStats())
2022-04-15 14:24:30 +00:00
},
2024-01-24 22:39:47 +00:00
ensureNotDeleted: (songs: Song | Song[]) => arrayify(songs).filter(({ deleted }) => !deleted),
2022-07-30 15:08:20 +00:00
async fetchForAlbum (album: Album | number) {
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
},
2022-07-30 15:08:20 +00:00
async fetchForArtist (artist: Artist | number) {
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)!.songs = songs
return songs
2022-04-15 14:24:30 +00:00
},
async fetchForPlaylistFolder (folder: PlaylistFolder) {
const songs: Song[] = []
for await (const playlist of playlistStore.byFolder(folder)) {
songs.push(...await songStore.fetchForPlaylist(playlist))
}
return uniqBy(songs, 'id')
},
async paginateForGenre (genre: Genre | Genre['name'], params: GenreSongListPaginateParams) {
2022-10-21 20:06:43 +00:00
const name = typeof genre === 'string' ? genre : genre.name
const resource = await http.get<PaginatorResource>(`genres/${name}/songs?${new URLSearchParams(params).toString()}`)
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
}
},
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) {
const resource = await http.get<PaginatorResource>(`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-04-23 21:01:27 +00:00
Array.from(this.vault.values()).filter(({ deleted, play_count }) => !deleted && 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-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[]) {
const privatizedIds = await http.put<Song['id'][]>('songs/privatize', {
songs: songs.map(({ id }) => id)
})
privatizedIds.forEach(id => {
const song = this.byId(id)
song && (song.is_public = false)
})
return privatizedIds
2022-06-10 10:47:46 +00:00
}
2022-04-15 14:24:30 +00:00
}