-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspotify.js
300 lines (276 loc) · 10.5 KB
/
spotify.js
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
//breaks user input into strings that can be input into Spotify API Calls
const searchSpotify = function (event) {
event.preventDefault();
const userInput = $("#searchBar").val().trim();
if (userInput.includes(",")) {
if (userInput.substring(0, userInput.indexOf(",")).length > 1) {
const trackName = userInput.substring(0, userInput.indexOf(","));
const artistName = userInput.substring(userInput.indexOf(",") + 1);
queryTrack(trackName, artistName);
$('#searchBar').val("");
}
else {
const artistName = userInput.substring(1);
queryArtist(artistName);
$('#searchBar').val("");
}
}
else {
const trackName = userInput;
const artistName = "";
queryTrack(trackName, artistName);
$('#searchBar').val("");
}
}
//function to parse Access Token in url
const parseAccessToken = function () {
const index1 = window.location.hash.indexOf("=") + 1;
const index2 = window.location.hash.indexOf("&");
const accessToken = window.location.hash.substring(index1, index2);
return accessToken;
}
//API call to Spotify to get tracks related to the search term
const queryTrack = function (track, artist) {
const accessToken = parseAccessToken();
let queryURL = "";
if (artist === "") {
queryURL = `https://api.spotify.com/v1/search?q=${track}&type=track`;
}
else {
queryURL = `https://api.spotify.com/v1/search?q=${track}&type=track,artist`;
}
$.ajax({
url: queryURL,
headers: {
'Authorization': 'Bearer ' + accessToken
},
success: function (response) {
renderTrack(response);
}
})
}
//API call to Spotify to get artists related to the search term
const queryArtist = function (artist) {
const accessToken = parseAccessToken();
const queryURL = `https://api.spotify.com/v1/search?q=${artist}&type=artist`;
$.ajax({
url: queryURL,
headers: {
'Authorization': 'Bearer ' + accessToken
},
success: function (response) {
renderArtist(response);
}
})
}
//API call to Spotify to get playlists in user's account
const queryPlaylist = function () {
const accessToken = parseAccessToken();
$.ajax({
url: "https://api.spotify.com/v1/me/playlists",
headers: {
'Authorization': 'Bearer ' + accessToken
},
success: function (response) {
renderPlaylists(response);
}
})
}
const infoList = [];
//call to render queried tracks from API call in formatted table along with add and delete buttons
const renderTrack = function (response) {
$(".songList").empty();
infoList.length = 0;
const trackArray = response.tracks.items;
for (let i = 0; i < trackArray.length; i++) {
infoList.push({
track: trackArray[i].name,
artist: trackArray[i].artists[0].name,
trackID: trackArray[i].id,
uri: trackArray[i].uri,
albumImage: trackArray[i].album.images[0].url
})
$(".songList").append(
`<tr>
<td data-trackID="${infoList[i].trackID}" class="playSong align-middle">
<p class="metaText">Song: ${infoList[i].track}</p>
<p class="metaText">Artist: ${infoList[i].artist}</p>
<img src =${infoList[i].albumImage} alt="Album Cover" class="albumImage">
</td>
<td data-uri="${infoList[i].uri}" class="addToPlaylist align-middle">
+
</td>
<td data-uri="${infoList[i].uri}" class="deleteFromPlaylist align-middle">
-
</td>
</tr>`);
if (i === trackArray.length - 1) {
$("#songTable > #clearButton").empty();
$("#songTable").prepend(
`<div id="clearButton"><button id="clear" class="align-middle">Clear</button></div>`);
}
}
}
//call to render queried artists from API call in formatted table
const renderArtist = function (response) {
$(".songList").empty();
infoList.length = 0;
const artistArray = response.artists.items;;
for (let i = 0; i < artistArray.length; i++) {
infoList.push({
artist: artistArray[i].name,
artistID: artistArray[i].id
})
$(".songList").append(`<tr>
<td id="${infoList[i].artistID}" class="align-middle">Artist: ${infoList[i].artist}</td></tr>`);
$(`#${infoList[i].artistID}`).on('click', playPlaylist);
}
}
//renders buttons with playlist names
const renderPlaylists = function (response) {
$(".playlist").empty();
for (let i = 0; i < response.items.length; i++) {
$(".playlist").prepend(`<button data-playlistID="${response.items[i].id}" class="addPlaylist btn-light">${response.items[i].name}</button>`);
}
}
//render selected playlist
const embedPlaylist = function () {
playlistID = $(this).attr("data-playlistID");
$(".playlist").html(`<iframe src="https://open.spotify.com/embed/playlist/${playlistID}" width="300" height="380" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>`);
}
//delay display to render playlist after 30 seconds
let delayDisplay = function () {
setTimeout(function () {
$(".playlist").html(`<iframe src="https://open.spotify.com/embed/playlist/${playlistID}" width="300" height="380" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>`);
}, 30000);
}
delayDisplay = _.debounce(delayDisplay, 5000);
//adds selected song to the playlist
const addToPlaylist = function () {
const trackURI = $(this).attr("data-uri").replace(":", "%3A").replace(":", "%3A");
const accessToken = parseAccessToken();
$.ajax({
url: `https://api.spotify.com/v1/playlists/${playlistID}/tracks?uris=${trackURI}`,
method: "POST",
headers: {
'Authorization': 'Bearer ' + accessToken
},
success: delayDisplay
})
}
//deletes selected song from the playlist
const deleteFromPlaylist = function () {
const trackURI = $(this).attr("data-uri");
const accessToken = parseAccessToken();
$.ajax({
url: `https://api.spotify.com/v1/playlists/${playlistID}/tracks`,
method: "DELETE",
data: JSON.stringify({
tracks: [{ uri: trackURI }]
}),
headers: {
'Authorization': 'Bearer ' + accessToken
},
contentType: "application/json",
success: delayDisplay
})
}
//clears songs from songlist div
const clearSongs = function () {
$("#songTable > #clearButton").empty();
$(".songList").empty();
}
//renders input field and submit button to create playlist
const displayInput = function () {
$(".playlist").empty();
$(".playlistHead").append(`<div class="playlistInput"><input id="newPlaylist" type="text" placeholder="Name of Playlist"> <button class ="btn btn-primary" id="submitBtn">Create</button></div>`)
}
//makes API call to get userID
const getUserID = function () {
const accessToken = parseAccessToken();
$.ajax({
url: "https://api.spotify.com/v1/me",
headers: {
'Authorization': 'Bearer ' + accessToken
},
success: function (response) {
createPlaylist(response);
}
})
}
//creates a playlist with the name given by the user input
const createPlaylist = function (response) {
const accessToken = parseAccessToken();
const playlistName = $("#newPlaylist").val();
const userID = response.id;
$.ajax({
url: `https://api.spotify.com/v1/users/${userID}/playlists`,
method: "POST",
data: JSON.stringify({
"name": `${playlistName}`
}),
processData: false,
contentType: "application/json",
headers: {
'Authorization': 'Bearer ' + accessToken,
}
})
$(".playlistInput").empty();
}
//embeds a player with the selected song, passes info to musicmatch.js for meta information and lyrics, and passes info to cookie.js
const playSong = function () {
const trackID = $(this).attr("data-trackID");
$('.spotifyPlayer').empty();
$(".spotifyPlayer").append(`<iframe id="spotify-player" src="https://open.spotify.com/embed/track/${trackID}" width="300" height="80" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>`);
const accessToken = parseAccessToken();
$.ajax({
url: `https://api.spotify.com/v1/tracks/${trackID}`,
headers: {
'Authorization': 'Bearer ' + accessToken
},
method: "GET",
success: function (response) {
const songName = response.name;
const artistName = response.artists[0].name;
infoPull(songName, artistName);
storeCookie(trackID, songName, artistName);
renderCookie();
}
})
}
const playSongForRecentlyPlayed = function () {
const trackID = $(this).attr("data-trackID");
$('.spotifyPlayer').empty();
$(".spotifyPlayer").append(`<iframe id="spotify-player" src="https://open.spotify.com/embed/track/${trackID}" width="300" height="80" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>`);
const accessToken = parseAccessToken();
$.ajax({
url: `https://api.spotify.com/v1/tracks/${trackID}`,
headers: {
'Authorization': 'Bearer ' + accessToken
},
method: "GET",
success: function (response) {
const songName = response.name;
const artistName = response.artists[0].name;
infoPull(songName, artistName);
renderCookie();
}
})
}
//embeds playlist with popular songs of the selected artist
const playPlaylist = function () {
$('.spotifyPlayer').empty();
$(".spotifyPlayer").append(`<iframe src="https://open.spotify.com/embed/artist/${this.id}" width="300" height="380" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>`);
}
//click events
$("#searchBtn").on("click", searchSpotify);
$("#createBtn").on("click", displayInput);
$(".playlistHead").on("click", "#submitBtn", getUserID);
$("#displayBtn").on("click", queryPlaylist);
$("#songTable").on('click', "#clear", clearSongs);
$(`.songList`).on('click', ".playSong", playSong);
$(`.songList`).on('click', ".addToPlaylist", addToPlaylist);
$(".songList").on("click", ".deleteFromPlaylist", deleteFromPlaylist);
$(`.playlist`).on("click", ".addPlaylist", embedPlaylist);
$(`#recentlyPlayed`).on('click', ".playSong", playSongForRecentlyPlayed);
$("#clearButton").click(clearCookie);