koel/resources/assets/js/services/download.js

81 lines
1.9 KiB
JavaScript
Raw Normal View History

2016-11-26 03:25:35 +00:00
import $ from 'jquery'
import { map } from 'lodash'
2016-06-02 17:53:26 +00:00
2016-11-26 03:25:35 +00:00
import { playlistStore, favoriteStore } from '../stores'
import { ls } from '.'
2016-06-02 17:53:26 +00:00
2016-06-25 10:15:57 +00:00
export const download = {
2016-06-25 16:05:24 +00:00
/**
* Download individual song(s).
*
* @param {Array.<Object>|Object} songs
*/
2016-11-26 03:25:35 +00:00
fromSongs (songs) {
songs = [].concat(songs)
const ids = map(songs, 'id')
const params = $.param({ songs: ids })
2016-06-02 17:53:26 +00:00
2016-11-26 03:25:35 +00:00
return this.trigger(`songs?${params}`)
2016-06-25 16:05:24 +00:00
},
2016-06-02 17:53:26 +00:00
2016-06-25 16:05:24 +00:00
/**
* Download all songs in an album.
*
* @param {Object} album
*/
2016-11-26 03:25:35 +00:00
fromAlbum (album) {
return this.trigger(`album/${album.id}`)
2016-06-25 16:05:24 +00:00
},
2016-06-02 17:53:26 +00:00
2016-06-25 16:05:24 +00:00
/**
* Download all songs performed by an artist.
*
* @param {Object} artist
*/
2016-11-26 03:25:35 +00:00
fromArtist (artist) {
2016-06-25 16:05:24 +00:00
// It's safe to assume an artist always has songs.
// After all, what's an artist without her songs?
// (See what I did there? Yes, I'm advocating for women's rights).
2016-11-26 03:25:35 +00:00
return this.trigger(`artist/${artist.id}`)
2016-06-25 16:05:24 +00:00
},
2016-06-02 17:53:26 +00:00
2016-06-25 16:05:24 +00:00
/**
* Download all songs in a playlist.
*
* @param {Object} playlist
*/
2016-11-26 03:25:35 +00:00
fromPlaylist (playlist) {
2016-06-25 16:05:24 +00:00
if (!playlistStore.getSongs(playlist).length) {
2016-11-26 03:25:35 +00:00
console.warn('Empty playlist.')
return
2016-06-25 16:05:24 +00:00
}
2016-06-02 17:53:26 +00:00
2016-11-26 03:25:35 +00:00
return this.trigger(`playlist/${playlist.id}`)
2016-06-25 16:05:24 +00:00
},
2016-06-02 17:53:26 +00:00
2016-06-25 16:05:24 +00:00
/**
* Download all favorite songs.
*/
2016-11-26 03:25:35 +00:00
fromFavorites () {
2016-06-25 16:05:24 +00:00
if (!favoriteStore.all.length) {
2016-11-26 03:25:35 +00:00
console.warn("You don't like any song? Come on, don't be that grumpy.")
return
2016-06-25 16:05:24 +00:00
}
2016-11-26 03:25:35 +00:00
return this.trigger('favorites')
2016-06-25 16:05:24 +00:00
},
2016-06-25 16:05:24 +00:00
/**
* 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.
*/
2016-11-26 03:25:35 +00:00
trigger (uri) {
const sep = uri.indexOf('?') === -1 ? '?' : '&'
const frameId = `downloader${Date.now()}`
$(`<iframe id="${frameId}" style="display:none"></iframe`).appendTo('body')
document.getElementById(frameId).src = `/api/download/${uri}${sep}jwt-token=${ls.get('jwt-token')}`
}
2016-06-02 17:53:26 +00:00
}