-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.html
381 lines (330 loc) · 13.5 KB
/
main.html
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
<!doctype html>
<html>
<head>
<title>Shuffle-by-album</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
<style type="text/css">
#login, #loggedin {
display: none;
}
.text-overflow {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 500px;
}
</style>
</head>
<body>
<div class="container">
<div id="login">
<h1>This is an example of the Implicit Grant flow</h1>
<button id="login-button" class="btn btn-primary">Log in with Spotify</button>
</div>
<div id="loggedin">
<div id="user-profile">
</div>
<div id="oauth">
</div>
<button id="shuffle-button" class="btn btn-primary">Shuffle!</button>
<div id="device-container">
</div>
<div id="playlists-container">
</div>
</div>
</div>
<script id="user-profile-template" type="text/x-handlebars-template">
<h1>Logged in as {{display_name}}</h1>
<div class="media">
<div class="pull-left">
<img class="media-object" width="150" src="{{images.0.url}}" />
</div>
<div class="media-body">
<dl class="dl-horizontal">
<dt>Display name</dt><dd class="clearfix">{{display_name}}</dd>
</dl>
</div>
</div>
</script>
<script id="devices-template" type="text/x-handlebars-template">
<label for="devices">Device:</label>
<select name="devices" id="devices" class="custom-select">
{{#each devices}}
<option value="{{this.id}}">{{this.name}}</option>
{{/each}}
</select>
</script>
<script id="playlists-template" type="text/x-handlebars-template">
<div class="row">
{{#each items}}
<div class="col-sm-2">
<div class="card">
{{#if this.images.0.url}}
<img class="card-img-top" src="{{this.images.0.url}}" alt="Card image cap">
{{else}}
<img class="card-img-top" src="http://localhost:8000/download.png" alt="Card image cap">
{{/if}}
<div class="card-body">
<p class="card-text">{{this.name}}</p>
</div>
</div>
</div>
{{/each}}
</div>
</script>
<script id="oauth-template" type="text/x-handlebars-template">
<h2>oAuth info</h2>
<dl class="dl-horizontal">
<dt>Access token</dt><dd class="text-overflow">{{access_token}}</dd>
</dl>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
(function() {
var stateKey = 'spotify_auth_state';
/**
* Obtains parameters from the hash of the URL
* @return Object
*/
function getHashParams() {
var hashParams = {};
var e, r = /([^&;=]+)=?([^&;]*)/g,
q = window.location.hash.substring(1);
while ( e = r.exec(q)) {
hashParams[e[1]] = decodeURIComponent(e[2]);
}
return hashParams;
}
/**
* Generates a random string containing numbers and letters
* @param {number} length The length of the string
* @return {string} The generated string
*/
function generateRandomString(length) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
var userProfileSource = document.getElementById('user-profile-template').innerHTML,
userProfileTemplate = Handlebars.compile(userProfileSource),
userProfilePlaceholder = document.getElementById('user-profile');
oauthSource = document.getElementById('oauth-template').innerHTML,
oauthTemplate = Handlebars.compile(oauthSource),
oauthPlaceholder = document.getElementById('oauth');
devicesSource = document.getElementById('devices-template').innerHTML,
devicesTemplate = Handlebars.compile(devicesSource),
devicesPlaceholder = document.getElementById('device-container');
playListsSource = document.getElementById('playlists-template').innerHTML,
playlistsTemplate = Handlebars.compile(playListsSource),
playlistsPlaceholder = document.getElementById('playlists-container');
var params = getHashParams();
var access_token = params.access_token,
state = params.state,
storedState = localStorage.getItem(stateKey);
console.log(access_token)
console.log(state)
console.log(storedState)
function login() {
var client_id = 'd37324d4e03641e3a5f23ca1acc9e952'; // Your client id
var redirect_uri = 'http://localhost:8000/main.html'; // Your redirect uri
var state = generateRandomString(16);
localStorage.setItem(stateKey, state);
var scope = 'user-read-private user-read-email user-modify-playback-state user-read-playback-state playlist-read-private playlist-read-collaborative playlist-modify-private playlist-modify-public';
var url = 'https://accounts.spotify.com/authorize';
url += '?response_type=token';
url += '&client_id=' + encodeURIComponent(client_id);
url += '&scope=' + encodeURIComponent(scope);
url += '&redirect_uri=' + encodeURIComponent(redirect_uri);
url += '&state=' + encodeURIComponent(state);
window.location = url;
}
async function list_devices() {
let promise = fetch("https://api.spotify.com/v1/me/player/devices", {
method: "GET",
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token},
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw new Error('Network response was not OK');
}
}).then(result => {
console.log(result);
devicesPlaceholder.innerHTML = devicesTemplate(result);
})
.catch(() => {
console.log("Booo");
});
return await promise;
}
async function get_target_playlist_id() {
const KEY = 'target-playlist-id';
let playlist_id = localStorage.getItem(KEY);
// If we remember a playlist id, verify it exists and return it if so
if (playlist_id) {
// Ask just for id since we are just doing a presence check
let response = await fetch(`https://api.spotify.com/v1/playlists/${playlist_id}?fields=id`, {
method: "GET",
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token},
});
if (response.ok) {
return playlist_id;
}
}
// If we do not remember a playlist id, or it does not exist anymore, create one
let response = await fetch(`https://api.spotify.com/v1/me/playlists`, {
method: "POST",
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token},
body: JSON.stringify({
"name": "Shuffle by Album Playlist",
"description": "Powers shuffle by album",
"public": false
})
});
let content = await response.json();
localStorage.setItem(KEY, content.id);
return content.id;
}
async function get_playlist_albums(source_playlist_id) {
const limit = 100;
let offset = 0
let all_tracks = [];
while(true) {
let res = await fetch(`https://api.spotify.com/v1/playlists/${source_playlist_id}/tracks?fields=items(track(id,track_number,%20album(id,name))),next&offset=${offset}&limit=${limit}`, {
method: "GET",
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token},
});
if (res.status == 429) {
console.log(res)
const retryAfter = res.headers.get('retry-after');
console.log(`Hit rate limit, sleeping for ${retryAfter} seconds`);
await new Promise(r => setTimeout(r, retryAfter * 1000));
} else if (res.ok) {
let content = await res.json();
all_tracks = all_tracks.concat(content.items);
if (content.next == null) {
break;
} else {
offset += limit;
}
}
}
let albums = {};
for (track of all_tracks) {
let album_id = track.track.album.id
if (!(album_id in albums)) {
albums[album_id] = {
tracks: [],
name: track.track.album.name
}
}
albums[album_id].tracks.push({track_number: track.track.track_number, track_id: track.track.id})
}
return albums;
}
async function list_playlists() {
let promise = fetch("https://api.spotify.com/v1/me/playlists", {
method: "GET",
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token},
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw new Error('Network response was not OK');
}
}).then(result => {
console.log(result);
playlistsPlaceholder.innerHTML = playlistsTemplate(result);
})
.catch((error) => {
console.error(error );
});
return await promise;
}
if (access_token && (state == null || state !== storedState)) {
alert('There was an error during the authentication');
} else {
if (access_token) {
$.ajax({
url: 'https://api.spotify.com/v1/me',
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(response) {
userProfilePlaceholder.innerHTML = userProfileTemplate(response);
$('#login').hide();
$('#loggedin').show();
}
});
list_devices();
list_playlists();
} else {
$('#login').show();
$('#loggedin').hide();
}
document.getElementById('login-button').addEventListener('click', login, false);
async function play_playlist(target_playlist_id) {
await fetch(`https://api.spotify.com/v1/me/player/play`, {
method: "PUT",
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token},
// TODO care about device
body: JSON.stringify({context_uri: `spotify:playlist:${target_playlist_id}`})
});
}
async function populate_target_playlist(source_playlist_id, target_playlist_id) {
let albums = await get_playlist_albums(source_playlist_id);
let shuffled_album_ids = shuffle(Object.keys(albums));
songs = [];
for (var key of shuffled_album_ids) {
let album = albums[key]
album.tracks.sort((a, b) => (a.track_number > b.track_number) ? 1 : -1)
for (track of album.tracks) {
songs.push("spotify:track:" + track.track_id);
}
}
for(i = 0; i < songs.length; i += 100) {
var some_songs = songs.slice(i, i+100);
if (some_songs.length == 0) {
break;
}
// TODO error handling?
if (i == 0) {
const response = await fetch(`https://api.spotify.com/v1/playlists/${target_playlist_id}/tracks`, {
method: "PUT",
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token},
body: JSON.stringify({uris: some_songs})
});
} else {
const response = await fetch(`https://api.spotify.com/v1/playlists/${target_playlist_id}/tracks`, {
method: "POST",
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token},
body: JSON.stringify({uris: some_songs})
});
}
}
}
document.getElementById('shuffle-button').addEventListener('click', async function() {
const target_playlist_id = await get_target_playlist_id();
let source_playlist_id = "5fip4J4Vw84VLlZuAVllUf"
await populate_target_playlist(source_playlist_id, target_playlist_id);
await play_playlist(target_playlist_id);
}, false);
}
})();
</script>
</html>