koel/resources/assets/js/services/downloadService.ts

45 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-06-10 10:47:46 +00:00
import { favoriteStore } from '@/stores'
2022-05-14 18:49:45 +00:00
import { authService } from '@/services'
import { arrayify } from '@/utils'
2022-04-15 14:24:30 +00:00
2022-04-24 08:50:45 +00:00
export const downloadService = {
2022-05-13 17:58:38 +00:00
fromSongs (songs: Song | Song[]) {
2022-04-20 09:37:22 +00:00
const query = arrayify(songs).reduce((q, song) => `songs[]=${song.id}&${q}`, '')
2022-04-15 14:24:30 +00:00
this.trigger(`songs?${query}`)
},
2022-05-13 17:58:38 +00:00
fromAlbum (album: Album) {
2022-04-15 14:24:30 +00:00
this.trigger(`album/${album.id}`)
},
2022-05-13 17:58:38 +00:00
fromArtist (artist: Artist) {
2022-04-15 14:24:30 +00:00
this.trigger(`artist/${artist.id}`)
},
2022-05-13 17:58:38 +00:00
fromPlaylist (playlist: Playlist) {
2022-06-10 10:47:46 +00:00
this.trigger(`playlist/${playlist.id}`)
2022-04-15 14:24:30 +00:00
},
2022-05-13 17:58:38 +00:00
fromFavorites () {
2022-09-14 17:40:08 +00:00
if (favoriteStore.state.songs.length) {
2022-04-15 14:24:30 +00:00
this.trigger('favorites')
}
},
/**
* Build a download link using a segment and trigger it.
*
* @param {string} uri The uri segment, corresponding to the song(s),
* artist, playlist, or album.
*/
trigger: (uri: string) => {
const sep = uri.includes('?') ? '&' : '?'
2022-11-16 17:57:38 +00:00
const url = `${window.BASE_URL}download/${uri}${sep}t=${authService.getAudioToken()}`
2022-04-15 14:24:30 +00:00
const iframe = document.createElement('iframe')
iframe.style.display = 'none'
iframe.setAttribute('src', url)
document.body.appendChild(iframe)
2022-04-15 14:24:30 +00:00
}
}