Skip to content

Instantly share code, notes, and snippets.

@t0ster
Created February 17, 2013 20:53
Show Gist options
  • Save t0ster/4973395 to your computer and use it in GitHub Desktop.
Save t0ster/4973395 to your computer and use it in GitHub Desktop.
function load_and_get(content, id) {
var obj = content.get(id);
if (!obj) {
content.load(id);
obj = content.get(id);
}
return obj;
}
function load_track_from_album(album, options) {
console.log(album.urlRoot + encodeURIComponent(album.id) + '/');
album.fetch({
url: album.urlRoot + encodeURIComponent(album.id) + '/',
success: options.success,
error: options.error
});
}
function get_tracks(albums, callback, tracks) {
if (!tracks)
tracks = [];
album = albums.shift();
if (!album) {
console.log('done');
callback(tracks);
return;
}
load_track_from_album(album, {
success: function(album) {
tracks.push.apply(tracks, album.tracks.models);
get_tracks(albums, callback, tracks);
},
error: function(){
alert('error');
}
});
}
function track_in_playlist(playlist, track) {
if (playlist.tracks.find(function(pl_track) {
return pl_track.get('trackName').toLowerCase() == track.get('trackName').toLowerCase() &&
pl_track.get('artistName').toLowerCase() == track.get('artistName').toLowerCase();
}))
return true;
else
return false;
}
function add_track_to_playlist(playlist, track, callback) {
var data = track.getPostData();
$.ajax({
type: 'POST',
url: playlist.ADD_URL,
data:_.extend(data, {playlistid : playlist.id}),
success: function(data) {
callback && callback();
},
error: function(err) {
callback && callback();
}
});
}
function add_tracks(playlist, tracks, callback) {
track = tracks.shift();
if (!track) {
callback(playlist);
return;
}
if (!track_in_playlist(playlist, track)){
add_track_to_playlist(playlist, track, function() {
console.log('[TRACK] Adding track ' + track.get('trackName'));
add_tracks(playlist, tracks, callback);
});
} else {
console.log('[TRACK] Track already in playlist: ' + track.get('trackName'));
add_tracks(playlist, tracks, callback);
}
}
function add_artist_to_playlist(playlist_id, artist_id) {
var playlist = load_and_get(models.playlists, playlist_id);
playlist.tracks = undefined;
var artist = load_and_get(models.artists, artist_id);
var tracks = null;
playlist.loadTracks({success: function(tracks) {
playlist.tracks = tracks;
artist.loadAlbums({success: function() {
get_tracks(artist.albums.models, function(tracks){
console.log('Got tracks');
add_tracks(playlist, tracks, function() {
console.log('[DONE]');
});
});
}});
}});
}
add_artist_to_playlist('9baee31a-c766-4b98-9d4a-1ae6445fd10d', 'Soundgarden');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment