-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
executable file
·681 lines (626 loc) · 25.6 KB
/
main.js
File metadata and controls
executable file
·681 lines (626 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
/// SPOTIFY EMAIL PLAYLIST GENERATOR
// Instantiate Spotify API object
var spotifyApi = new SpotifyWebApi();
// Spotify API credentials
var spotifyClientId = "f97ea406999b45bb8beeabbcffc3bacd";
var spotifyClientSecret = "982df03acdf34caeb18026bc041733f8";
var redirectUri = chrome.identity.getRedirectURL() + 'spotify';
// Attempt to set Spotify API object with locally stored
// tokens and update if tokens missing or expired
checkLocalSpotifyTokens();
function checkLocalSpotifyTokens() {
chrome.storage.local.get('tokens', function(tokenObj) {
console.log("Local storage token object:", tokenObj);
var spotifyAccessToken = tokenObj['tokens']['spotifyAccessToken'];
console.log("Spotify Access Token in Chrome local storage:", spotifyAccessToken);
if (spotifyAccessToken !== undefined) {
// Set Spotify API with access token
setSpotifyAccessToken(spotifyAccessToken);
console.log("Spotify API object access token set to:", spotifyApi.getAccessToken());
// Check that access token is not expired
return checkTokenExpiration();
} else {
console.log("Access token not found in Chrome local storage, authorizing with Spotify...");
return beginSpotifyAuthProcess();
}
});
}
function setSpotifyAccessToken(spotifyAccessToken) {
spotifyApi.setAccessToken(spotifyAccessToken);
console.log("Spotify API object access token set to:", spotifyApi.getAccessToken());
}
function checkTokenExpiration() {
var user = spotifyApi.getMe(function(error, userObj) {
if (error !== null) {
// Refresh if expired
if (error.status == 401 &&
error.response.indexOf("The access token expired") > -1) {
console.log("Token expired! Refreshing token...");
// Get refresh token from local storage
chrome.storage.local.get('tokens', function(tokenObj) {
var spotifyRefreshToken = tokenObj['tokens']['spotifyRefreshToken'];
console.log("Spotify Refresh Token in Chrome local storage:", spotifyRefreshToken);
return getSpotifyTokens("refresh_token", spotifyRefreshToken);
});
} else {
console.log("Error retrieving user object...");
return beginSpotifyAuthProcess();
}
} else {
console.log("Access token valid. User object:", userObj);
return true;
}
});
}
// // Check local storage for access tokens & set Spotify API object
// // with them if they exist. Otherwise, authorize & retrieve
// // tokens from Spotify API
// function checkLocalTokens2() {
// chrome.storage.local.get('tokens', function(tokenObj) {
// console.log("Local storage token object:", tokenObj);
// // Try to get user tokens from Chrome local storage, otherwise
// // authorize with Spotify API if they don't exist
// try {
// var spotifyAccessToken = tokenObj['tokens']['spotifyAccessToken'];
// var spotifyRefreshToken = tokenObj['tokens']['spotifyRefreshToken'];
// console.log("Spotify Access Token in Chrome local storage:", spotifyAccessToken);
// console.log("Spotify Refresh Token in Chrome local storage:", spotifyRefreshToken);
// if (tokenObj['tokens']['spotifyAccessToken'] !== undefined) {
// // Set Spotify API object token
// spotifyApi.setAccessToken(spotifyAccessToken);
// // Try to retrieve user object from Spotify API object
// var user = spotifyApi.getMe(function(error, userObj) {
// if (error !== null) {
// console.log("Error retrieving user object:", error);
// // Check if token expired & refresh if expired
// if (error.status == 401 &&
// error.response.indexOf("The access token expired") > -1) {
// console.log("Token expired! Refreshing token...");
// return getSpotifyTokens("refresh_token", spotifyRefreshToken);
// }
// } else {
// console.log("User object retrieved successfully", userObj);
// return true;
// }
// });
// } else {
// // Authorize with Spotify API
// return beginSpotifyAuthProcess();
// }
// } catch (e) {
// console.log("Error in retrieving Chrome local storage access tokens:", e)
// // Authorize with Spotify API
// return beginSpotifyAuthProcess();
// }
// });
// }
function beginSpotifyAuthProcess() {
// Initiate Spotify Authorization sequence
// Set authorization scopes
var scopes = "playlist-read-private playlist-read-collaborative playlist-modify-public playlist-modify-private user-follow-read user-follow-modify";
// Use Chrome's built-in auth handler
chrome.identity.launchWebAuthFlow({
"url": "https://accounts.spotify.com/authorize?client_id="+spotifyClientId+
"&response_type=code"+
"&redirect_uri="+ encodeURIComponent(redirectUri) +
"&scope="+
encodeURIComponent(scopes),
'interactive': true,
},
function(rawResponse) {
// Parse raw response with code
console.log("Raw response:", rawResponse);
var splitCodeResponse = rawResponse.split('=');
var parsedCodeResponse = splitCodeResponse[1].split('&')[0];
console.log("Parsed response code:", parsedCodeResponse);
// Now get access & refresh tokens using parsed response code
return getSpotifyTokens("authorization_code", parsedCodeResponse);
});
}
// Handler to get Spotify access tokens using code or refresh token
function getSpotifyTokens(grant_type, accessCodeOrRefreshToken) {
console.log('Fetching Spotify Access Tokens for grant_type: '+
grant_type+' with code/token:', accessCodeOrRefreshToken);
var data = {grant_type: grant_type,
redirect_uri: encodeURIComponent(redirectUri),
client_id: spotifyClientId,
client_secret: spotifyClientSecret
};
if (grant_type == 'authorization_code') {
data.code = accessCodeOrRefreshToken;
} else if (grant_type == 'refresh_token') {
data.refresh_token = accessCodeOrRefreshToken;
}
$.ajax({
type: "POST",
url: "https://accounts.spotify.com/api/token",
data: data,
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error hitting Spotify API:", jqXHR.responseText);
// If refresh token expired, initialize new authorization process
if (grant_type == 'refresh_token') {
return beginSpotifyAuthProcess();
}
},
success: function(tokenResponse) {
console.log("Spotify token response:", tokenResponse);
// Retrieve Spotify access token, token duration, and
// refresh token from token response object
var spotifyAccessToken = tokenResponse.access_token;
console.log("Spotify access token:", spotifyAccessToken);
var spotifyTokenDuration = tokenResponse.expires_in;
console.log("Spotify access token expires in:", spotifyTokenDuration+" seconds");
var spotifyRefreshToken = tokenResponse.refresh_token;
console.log("Spotify refresh token:", spotifyRefreshToken);
// Create token object with new access token
var tokenObject = {
spotifyAccessToken: spotifyAccessToken
};
// If new refresh token given, update token object - not sure which
// check is necessary - will have to see when an access token expires
// and a new one is given, but guessing it's either undefined or null
if (spotifyRefreshToken !== undefined) {
tokenObject.spotifyRefreshToken = spotifyRefreshToken;
}
// Update Spotify API object with new access token
setSpotifyAccessToken(spotifyAccessToken);
// Save new tokens to local storage
return setSpotifyTokensToLocalStorage(tokenObject);
}
});
}
function setSpotifyTokensToLocalStorage(tokenObject) {
// Set Spotify API object access token & save to local storage
chrome.storage.local.set({
'tokens': tokenObject
}, function() {
// Verify that new token(s) have been set in local storage
chrome.storage.local.get('tokens', function(tokens) {
console.log("Chrome local storage access tokens:", tokens);
});
return true;
});
}
function playlistNameCheck(playlistName, playlistObjs) {
for (var i=0; i < playlistObjs.items.length; i++) {
if (playlistObjs.items[i]['name'].indexOf(playlistName) > -1) {
return [true, i];
}
}
return [false];
}
$('#follow-artists').on('click', function() {
followArtists('found in discover weekly');
});
function followArtists(playlistName) {
console.log("Attempting to authorize with Spotify");
var initiateFollowArtists = new Promise(function(resolve, reject) {
if (checkTokenExpiration) {
console.log('1');
resolve("Successfully authorized with Spotify!");
}
else {
reject("Error authorizing with Spotify!");
}
});
initiateFollowArtists.then(function(success) {
console.log(success);
console.log('2');
console.log("Attempting to follow artists from playlist", playlistName)
followArtistsStep1(playlistName);
}, function(error) {
console.log(error);
});
}
function followArtistsStep1(playlistName) {
console.log('3');
var user = spotifyApi.getMe(function(error, userObj) {
if (error !== null) {
console.log("Error retrieving user object:", error);
// Check if token expired & refresh if expired
if (error.status == 401 &&
error.response.indexOf("The access token expired") > -1) {
console.log("Token expired! Refreshing token...");
getSpotifyTokens("refresh_token", spotifyRefreshToken);
user = spotifyApi.getMe(function(error2, userObj2) {
if (error2 !== null) {
console.log("Still getting an error!...", error2);
} else {
console.log("User object retrieved successfully", userObj2);
followArtistsStep2(playlistName, userObj2);
}
});
}
} else {
console.log("User object retrieved successfully", userObj);
followArtistsStep2(playlistName, userObj);
}
});
}
function followArtistsStep2(playlistName, userObj) {
var userId;
var artistIds = [];
var artistIdsSlice = [];
var numTracks;
var offset;
var searchPlaylist = playlistName;
var playlistId;
var nameCheckReturn;
var nameCheckReturnBoolean;
var nameCheckReturnIndex;
var counter = 0;
userId = userObj.id;
var userPlaylists = spotifyApi.getUserPlaylists(userId, function(error, playlistObjs) {
if (error !== null) {
console.log("Error getting user's playlists!...", error);
} else {
console.log("User playlists retrieved!...", playlistObjs);
playlistIds = playlistObjs;
nameCheckReturn = playlistNameCheck(searchPlaylist, playlistObjs);
nameCheckReturnBoolean = nameCheckReturn[0];
if (nameCheckReturnBoolean) {
nameCheckReturnIndex = nameCheckReturn[1];
playlistId = playlistObjs.items[nameCheckReturnIndex].id;
// Build artists list from matched playlist
spotifyApi.getPlaylistTracks(userId, playlistId, function(error, response) {
if (error !== null) {
console.log("Error retrieving playlist!...", error);
} else {
numTracks = response.total;
console.log(numTracks, "total tracks in playlist");
for (var i=0; i<=Math.floor(numTracks/100); i++) {
spotifyApi.getPlaylistTracks(userId, playlistId, {offset: i*100}, function(error2, response2) {
if (error2 !== null) {
console.log("Error retrieving playlist!...", error2);
} else {
console.log("Request items:", response2.items);
for (var i2=0; i2<response2.items.length; i2++) {
counter++;
for (var i3=0; i3<response2.items[i2].track.artists.length; i3++) {
artistIds.push(response2.items[i2].track.artists[i3].id);
}
// console.log("numTracks:", numTracks, " ---- counter:", counter);
// console.log("numTracks:", numTracks, " ---- i2+1:", i2+1);
if (numTracks === counter || counter%50 === 0) {
// Now start following artists
artistIdsSlice = artistIds.slice(counter-50, counter);
console.log("artistIdsSlice:", artistIdsSlice);
spotifyApi.followArtists(artistIdsSlice, function(error3, success) {
if (error3 !== null) {
console.log("Error following artists!...", error3);
} else {
console.log("Successfully followed"+artistIdsSlice.length+"artists!");
}
});
}
}
}
});
}
}
});
} else {
console.log(searchPlaylist, " -- Playlist not found in user playlists!");
}
}
});
}
// function appendMessageRow(message) {
// $('.table-inbox tbody').append(
// '<tr>\
// <td>'+getHeader(message.payload.headers, 'From')+'</td>\
// <td>\
// <a href="#message-modal-' + message.id +
// '" data-toggle="modal" id="message-link-' + message.id+'">' +
// getHeader(message.payload.headers, 'Subject') +
// '</a>\
// </td>\
// <td>'+getHeader(message.payload.headers, 'Date')+'</td>\
// </tr>'
// );
// $('body').append(
// '<div class="modal fade" id="message-modal-' + message.id +
// '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">\
// <div class="modal-dialog modal-lg">\
// <div class="modal-content">\
// <div class="modal-header">\
// <button type="button"\
// class="close"\
// data-dismiss="modal"\
// aria-label="Close">\
// <span aria-hidden="true">×</span></button>\
// <h4 class="modal-title" id="myModalLabel">' +
// getHeader(message.payload.headers, 'Subject') +
// '</h4>\
// </div>\
// <div class="modal-body">\
// <iframe id="message-iframe-'+message.id+'" srcdoc="<p>Loading...</p>">\
// </iframe>\
// </div>\
// </div>\
// </div>\
// </div>'
// );
// $('#message-link-'+message.id).on('click', function(){
// var ifrm = $('#message-iframe-'+message.id)[0].contentWindow.document;
// $('body', ifrm).html(getBody(message.payload));
// });
// }
// function getHeader(headers, index) {
// var header = '';
// $.each(headers, function(){
// if(this.name === index){
// header = this.value;
// }
// });
// return header;
// }
// function getBody(message) {
// var encodedBody = '';
// if(typeof message.parts === 'undefined')
// {
// encodedBody = message.body.data;
// }
// else
// {
// encodedBody = getHTMLPart(message.parts);
// }
// encodedBody = encodedBody.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
// return decodeURIComponent(escape(window.atob(encodedBody)));
// }
// function getHTMLPart(arr) {
// for(var x = 0; x <= arr.length; x++)
// {
// if(typeof arr[x].parts === 'undefined')
// {
// if(arr[x].mimeType === 'text/html')
// {
// return arr[x].body.data;
// }
// }
// else
// {
// return getHTMLPart(arr[x].parts);
// }
// }
// return '';
// }
// Wait 5 seconds to run everything so
// gapi has a chance to load
// setTimeout(function() {
// checkLocalTokens();
// // setTimeout(function() {
// // handleClientLoad();
// // }, 5000);
// }, 5000);
// Poll user's inbox every hour for any new emails
// setInterval(function() {
// checkAuth();
// }, 1000*60*60);
// Gmail API credentials
// var gmailClientId = '166859819073-rv7t4945r8toh7ek9ab99enelke8mtbb.apps.googleusercontent.com';
// var gmailApiKey = 'AIzaSyBYQPC4-1SENmvv-0TlM18X6ay98s0A0Lo';
// var gmailScopes = 'https://www.googleapis.com/auth/gmail.readonly';
// function handleClientLoad() {
// gapi.client.setApiKey(gmailApiKey);
// window.setTimeout(checkAuth, 1);
// }
// function checkAuth() {
// gapi.auth.authorize({
// client_id: gmailClientId,
// scope: gmailScopes,
// immediate: true
// }, handleAuthResult);
// }
// function handleAuthClick() {
// gapi.auth.authorize({
// client_id: gmailClientId,
// scope: gmailScopes,
// immediate: false
// }, handleAuthResult);
// return false;
// }
// function handleAuthResult(authResult) {
// if(authResult && !authResult.error) {
// loadGmailApi();
// //$('#authorize-button').remove();
// $('.table-inbox').removeClass("hidden");
// } else {
// $('#authorize-button').removeClass("hidden");
// $('#authorize-button').on('click', function(){
// handleAuthClick();
// });
// }
// }
// function loadGmailApi() {
// gapi.client.load('gmail', 'v1', displayInbox);
// }
// function displayInbox() {
// // Look for most recently processed email id in local storage
// // If it's there, initialize a variable to its value in order to
// // compare current emails against - only process emails that haven't
// // already been processed
// var newestEmailId = null;
// chrome.storage.local.get('newestEmailId', function(emailIdObj) {
// console.log("Newest email ID:", emailIdObj['newestEmailId']);
// if (emailIdObj['newestEmailId'] !== undefined) {
// newestEmailId = emailIdObj['newestEmailId'];
// }
// });
// var request = gapi.client.gmail.users.messages.list({
// 'userId': 'me',
// 'labelIds': 'INBOX',
// 'q': 'spotify is now available',
// 'maxResults': 10
// });
// request.execute(function(response) {
// console.log(response);
// for (var i=0; i < response.messages.length; i++) {
// var messageObj = response.messages[i];
// processGmailMessageObj(messageObj, i, newestEmailId);
// }
// });
// }
// // Process given email
// // 1. Extract deep link
// // 2. Extract album id
// // 3. Add album's songs to Email Digest playlist
// function processGmailMessageObj(messageObj, index, newestEmailId) {
// setTimeout(function() {
// console.log(messageObj);
// var x = (messageObj.id == newestEmailId);
// console.log(x);
// console.log(messageObj.id);
// // Check if this email has already been processed
// if (messageObj.id > newestEmailId || newestEmailId === null) {
// chrome.storage.local.set({
// 'newestEmailId': messageObj.id
// }, function(){
// chrome.storage.local.get('newestEmailId', function(response){
// console.log(index, response);
// });
// });
// var messageRequest = gapi.client.gmail.users.messages.get({
// 'userId': 'me',
// 'id': messageObj.id
// });
// console.log(messageRequest);
// // Code to display emails in extension pop-up ui
// //messageRequest.execute(appendMessageRow);
// // Get deep links from Spotify messages
// messageRequest.execute(getMessageLink);
// }
// console.log("Waiting 15 secs to process next email. Hang tight...");
// }, 15000*(index+1));
// }
// function getMessageLink(message) {
// // Check to make sure message is from Spotify
// if (getHeader(message.payload.headers, 'From').indexOf("Spotify") > -1) {
// var rawHTMLBody = getBody(message.payload);
// var parser = new DOMParser();
// var bodyDOM = parser.parseFromString(rawHTMLBody, "text/html");
// var deepLink = bodyDOM.links[1].href;
// // Now process deep link from email
// openTab(deepLink);
// }
// }
// var spotifyTabs = [];
// var processedSpotifyTabs = [];
// // Open new tab with Spotify deep link
// function openTab(url) {
// chrome.tabs.create({url: url, active: false}, function(tab) {
// var tabId = tab.id;
// spotifyTabs.push(tab.id);
// //console.log('Newly opened tab!', tab.id);
// // Create listener to check once a tab is finished loading
// // so we can extract the URL
// chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
// if (changeInfo.status == 'complete') {
// //console.log('Tab status changed (tab is also complete)!', tab.id);
// chrome.tabs.get(tabId, function(tab) {
// // Check to make sure we haven't already processed this URL
// if (spotifyTabs.indexOf(tab.id) > -1 &&
// processedSpotifyTabs.indexOf(tab.id) == -1) {
// processedSpotifyTabs.push(tab.id);
// //console.log("Tab added to processedSpotifyTabs", processedSpotifyTabs);
// parseSpotifyEntityId(tab.url, tabId);
// }
// });
// }
// });
// });
// }
// // Get entity (album, song, etc) ID from URL
// function parseSpotifyEntityId(url, tabId) {
// var firstSplit = url.split("/");
// var rawEndpoint = firstSplit[4];
// var parsedEndpoint = rawEndpoint.split("?")[0];
// // Call Spotify API with album endpoint
// spotifyApi.getAlbum(parsedEndpoint)
// .then(function(data) {
// console.log('Album', data);
// getUserPlaylists(data);
// chrome.tabs.remove(tabId);
// }, function(err) {
// console.error(err);
// });
// }
// // Get user playlists
// function getUserPlaylists(album) {
// var userId;
// // Set userId
// var user = spotifyApi.getMe(function(error, userObj) {
// if (error !== null) {
// console.log(error);
// } else {
// console.log(userObj);
// userId = userObj.id;
// // Get user playlists then check if Email Digest playlist
// // already exists
// var userPlaylists = spotifyApi.getUserPlaylists(userId, function(error, playlistObjs) {
// if (error !== null) {
// console.log("Error getting user's playlists!...", error);
// } else {
// console.log("User playlists retrieved!...", playlistObjs);
// checkForPlaylist(userId, "Email Digest", playlistObjs, album);
// }
// });
// }
// });
// }
// // Check if given playlist name already exists in user's playlists
// function checkForPlaylist(userId, playlistName, playlistObjs, album) {
// var nameCheckReturn = playlistNameCheck(playlistName, playlistObjs);
// var nameCheckReturnBoolean = nameCheckReturn[0];
// var nameCheckReturnIndex;
// if (nameCheckReturnBoolean) {
// console.log("Playlist found! --- Adding track(s)...");
// nameCheckReturnIndex = nameCheckReturn[1];
// // If playlist exists, add to playlist object by calling addToPlaylist
// addToPlaylist(userId, playlistObjs.items[nameCheckReturnIndex], album);
// } else {
// console.log("Playlist not found! --- Creating playlist and adding track(s)...");
// // If playlist does not exist, create new playlist and add by calling createPlaylist
// createPlaylist(userId, playlistName, album);
// }
// }
// // Add track(s) from a given album to a given playlist for a given user
// function addToPlaylist(userId, playlistObj, album) {
// // Grab the playlist ID
// var playlistId = playlistObj.id;
// // Initialize empty array in which to add track(s) from an album
// var songUris = [];
// // Add each track from the album to the songUris array
// for (var i=0; i < album.tracks.items.length; i++) {
// songUris.push(album.tracks.items[i].uri);
// // Check if songUris array is same length as number of
// // tracks in album. If so, add tracks from songUris to
// // given playlist
// if (songUris.length === album.tracks.items.length) {
// // Add each track from the songUris array to the playlist
// spotifyApi.addTracksToPlaylist(userId, playlistId, songUris, function(error, success) {
// if (error != null) {
// console.log("Error adding tracks to playlist!...", error)
// } else {
// console.log("Successfully added "+album.tracks.items.length+" tracks to playlist!");
// }
// });
// }
// }
// }
// // Create a new playlist with a given name for a given user,
// // and add given album tracks to the newly created playlist
// function createPlaylist(userId, playlistName, album) {
// // Create new playlist, then add given album's
// // song(s) to newly created playlist
// spotifyApi.createPlaylist(userId,
// {name: playlistName, public: false},
// function(error, newPlaylistObj) {
// if (error !== null) {
// console.log("Error creating playlist!...", error);
// } else {
// console.log("Successfully created new playlist!", newPlaylistObj);
// addToPlaylist(userId, newPlaylistObj, album);
// }
// });
// }