-
Notifications
You must be signed in to change notification settings - Fork 39
/
index.html
656 lines (572 loc) · 20.9 KB
/
index.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link type="text/css" href="styles.css" rel="stylesheet" />
<link href="dist/sp-bootstrap.min.css" rel="stylesheet" media="screen">
<title>The Playlist Miner</title>
<!-- Custom styles for this template -->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body >
<div class="navbar navbar-default" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">
<span class="navbar-title">Playlist Miner</span>
</a>
</div>
<div class="navbar-collapse collapse">
<a href="http://www.spotify.com" class="btn btn-primary navbar-btn navbar-right">Get
Spotify</a>
</div><!--/.navbar-collapse -->
</div>
</div>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div id='top' class="jumbotron">
<div class="container-fluid" id="jumbo-dialog">
<h1 id='attitle' >The Playlist Miner</h1>
<p class="lead"> The best DJ is everybody.</p>
<p id='ttext'>
The Playlist Miner aggregrates the top tracks from
the most popular public playlists on Spotify that match your
search criteria. Looking for the best <i>workout</i> tracks?
Enter the term <i>workout</i> and we'll find
the tracks that have appeared most frequently in workout playlists.
</p>
<div class='intro-form' id='login-form'>
<p> To get started, login with your Spotify credentials.
</p>
<p><a class="btn btn-primary btn-lg" id='login-button'
role="button">Login with Spotify</a></p>
</div>
<div id="search-form" class="intro-form row">
<div class="col-xs-offset-1 col-xs-10 col-sm-offset-3 col-sm-6">
<input type="text" class="form-control input-lg"
id="playlist-terms" placeholder="'work out' OR workout " value="">
<br>
<button class="btn btn-primary btn-lg" id='go'
role="button">Find playlists</button>
</div>
</div>
</div>
</div>
<div class="container-fluid work">
<div id='info' class="h1 text-center"></div>
<div class="results" id='playlist-table'>
<h1> Matching Playlists for <span class='keywords'></span></h1>
<div class="progress">
<div id='playlist-progress' class="progress-bar" role="progressbar" aria-valuenow="60"
aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only"></span>
</div>
</div>
<!-- <button class='stop-button btn btn-primary'> stop </button> -->
<div class='button-row'>
We've found
<span class="total-playlists"> </span> matching playlists with
a total of <span class='total-tracks'> 0 </span> tracks.
<br>
<div id='fetch-tracks-ready'>
Press
<b> Find top tracks </b> to build a playlist of the top tracks
across all of these playlists or go back and
<a href="index.html">refine your query</a>.
<div class='obutton-row'>
<button id='fetch-tracks' class='btn btn-primary'> Find top tracks</button>
</div>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr> <th style="width:5%"> # </th>
<th style="width: 85%"> Playlist name </th>
<th style="width:10%"> # Tracks </th>
</tr>
</thead>
<tbody id="playlist-items"> </tbody>
</table>
</div>
<div class="results" id='track-table'>
<h1> <a id='playlist-name'>Top <span class='keywords'> </span> Tracks </a></h1>
<div class="button-row">
<div id='fetching-tracks'>
Aggregating <span id='tt-total-tracks'> </span> tracks from all
of the <span class= "keywords"></span> playlists.
<p>
You can stop this at any time, but the longer you wait, the
better your results.
</p>
<button id='stop-button'
class='padded-button stop-button btn btn-primary'>
stop </button>
</div>
<div id='ready-to-save'>
Here are the top 100 <span class='keywords'></span> tracks. You
can save these as your own Spotify playlist by clicking the
button.
<br>
<button id="save-button"
class="padded-button btn btn-primary btn-lg">
Save Playlist to Spotify</button>
</div>
</div>
<div class="progress">
<div id='track-progress' class="progress-bar" role="progressbar" aria-valuenow="60"
aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only"></span>
</div>
</div>
<label><input id='norm-for-pop' type='checkbox'> Prefer more distinctive
<span class='keywords'></span> tracks </label>
<table class="table table-striped table-bordered">
<thead>
<tr> <th style="width:5%"> # </th>
<th style="width:40%"> Title </th>
<th style="width:35%"> Artist </th>
<th style="width:10%"> Score</th> </tr>
</thead>
<tbody id="track-items"> </tbody>
</table>
</div>
</div>
<div id="footer">
<div class="container text-center">
<p class="text-muted">
Powered by <a href="http://spotify.com">Spotify</a>.
Created by <a href="http://twitter.com/plamere">@plamere</a>.
More info at <a href="http://musicmachinery.com/2014/12/19/the-playlist-miner/">MusicMachinery</a>.
</p>
</div>
</div>
<script src="lib/jquery-1.11.1.min.js"></script>
<script src="lib/bootstrap.min.js"></script>
<script src="lib/underscore-min.js"></script>
<script>
"use strict";
var maxPlaylists = 1000;
var maxPlaylistsToDisplay = 1000;
var credentials = null;
var totalTracks = 0;
var totalPlaylistCount = 0;
var abortFetching = false;
var popNormalize = false;
var allPlaylists = [];
var topTracks = null;
var allTracks = {};
function error(s) {
info(s);
}
function info(s) {
$("#info").text(s);
}
function callSpotify(url, data) {
return $.ajax(url, {
dataType: 'json',
data: data,
headers: {
'Authorization': 'Bearer ' + credentials.token
}
});
}
function postSpotify(url, json, callback) {
$.ajax(url, {
type: "POST",
data: JSON.stringify(json),
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + credentials.token,
'Content-Type': 'application/json'
},
success: function(r) {
callback(true, r);
},
error: function(r) {
// 2XX status codes are good, but some have no
// response data which triggers the error handler
// convert it to goodness.
if (r.status >= 200 && r.status < 300) {
callback(true, r);
} else {
callback(false, r);
}
}
});
}
function findMatchingPlaylists(text) {
var outstanding = 0;
function addItem(tbody, which, item) {
var tr= $("<tr>");
var rowNumber = $("<td>").text(which);
var title = $("<td>").append($("<a>").attr('href', item.uri).text(item.name));
var tracks = $("<td>").text(item.tracks.total);
tr.append(rowNumber);
tr.append(title);
tr.append(tracks);
$("#playlist-item").append(tr);
tbody.append(tr);
}
function showSearchResults(data) {
outstanding--;
var matching = data.playlists.total > maxPlaylists ? ">"
+ maxPlaylists : data.playlists.total;
$("#matching").text(matching);
var tbody = $("#playlist-items");
_.each(data.playlists.items, function(item, which) {
if (true || !item.collaborative) {
if (allPlaylists.length < maxPlaylistsToDisplay) {
addItem(tbody, data.playlists.offset + which + 1, item);
}
if (allPlaylists.length < maxPlaylists) {
allPlaylists.push( [item.owner.id, item.id]);
totalTracks += item.tracks.total;
}
} else {
}
});
var totalPlaylists = allPlaylists.length;
var total = Math.min(data.playlists.total, maxPlaylists);
var percentComplete = Math.round(totalPlaylists * 100 / total);
$(".total-tracks").text(totalTracks);
$(".total-playlists").text(totalPlaylists);
$("#playlist-progress").css('width', percentComplete + "%");
if (abortFetching || outstanding == 0) {
abortFetching = false;
if (totalPlaylists > 0) {
$('#fetch-tracks-ready').show(200);
} else {
info("No matching playlists found");
$('#fetch-tracks-ready').show(200);
}
}
}
function processPlaylistError() {
outstanding--;
error("Can't get playlists");
}
function processPlaylists(data) {
var total = Math.min(data.playlists.total, maxPlaylists);
var offset = data.playlists.offset + data.playlists.items.length;
for (var i = offset; i < total; i += 50) {
var url = 'https://api.spotify.com/v1/search';
var params = {
q: text,
type:'playlist',
limit:data.playlists.limit,
offset:i
};
outstanding++;
callSpotify(url, params).then(showSearchResults, processPlaylistError);
}
showSearchResults(data);
}
totalTracks = 0;
abortFetching = false;
allPlaylists = [];
$('#fetch-tracks-ready').hide();
var url = 'https://api.spotify.com/v1/search';
var params = {
q: text,
type:'playlist',
limit:50
};
var offset = 0;
$("#playlist-items").empty();
outstanding++;
callSpotify(url, params).then(processPlaylists, processPlaylistError);
}
function go() {
$("#top").hide(200);
var text = $("#playlist-terms").val()
if (text.length > 0) {
info("");
$(".keywords").text(text);
$(".results").hide();
$("#playlist-table").show();
findMatchingPlaylists(text);
} else {
info("Enter some keywords first");
}
}
function new_getTrackScore(track) {
if (popNormalize) {
var factor = track.popularity > 30 ? track.popularity : 30;
factor = factor * factor;
var score = 1000. * track.count / factor;
return score;
} else {
return track.count;
}
}
function getTrackScore(track) {
//return old_getTrackScore(track);
return new_getTrackScore(track);
}
function refreshTrackList(allTracks) {
info("");
var tracks = [];
_.each(allTracks, function(track, id) {
track.score = getTrackScore(track);
tracks.push(track);
});
tracks.sort(function(a,b) {
return b.score - a.score;
});
topTracks = tracks.slice(0, 100);
var table = $("#track-items");
var newRows = [];
_.each(topTracks, function(track, i) {
var tr = $("<tr>");
tr.append( $("<td>").text(i + 1));
tr.append( $("<td>").append( $("<a>").attr('href', track.uri).text(track.name)));
tr.append( $("<td>").text(track.artists[0].name));
tr.append( $("<td>").text(Math.round(track.score)));
newRows.push(tr);
});
table.empty().append(newRows);
}
function saveTidsToPlaylist(playlist, tids) {
var url = "https://api.spotify.com/v1/users/" + playlist.owner.id +
"/playlists/" + playlist.id + '/tracks';
postSpotify(url, {uris: tids}, function(ok, data) {
if (ok) {
info("Playlist saved");
$("#ready-to-save").hide(100);
$("#playlist-name").attr('href', playlist.uri);
} else {
error("Trouble saving to the playlist");
}
});
}
function savePlaylist() {
var title = getPlaylistTitle();
var tids = [];
_.each(topTracks, function(track, i) {
tids.push(track.uri);
});
var url = "https://api.spotify.com/v1/users/" + credentials.user_id + "/playlists";
var json = { name: title};
postSpotify(url, json, function(ok, playlist) {
if (ok) {
saveTidsToPlaylist(playlist, tids);
} else {
error("Can't create the new playlist");
}
});
}
function getPlaylistTitle() {
return "Top " + $("#playlist-terms").val() + " tracks";
}
function fetchAllTracksFromPlaylist() {
var start = new Date().getTime();
$(".results").hide();
$("#track-table").show();
$("#ready-to-save").hide();
$("#fetching-tracks").show();
allTracks = {};
var queue = allPlaylists.slice(0);
var totalTracks = 0;
totalPlaylistCount = 0;
function isGoodPlaylist(items) {
// good playlist needs multiple artists and
// multiple albums
var albums = {};
var artists = {};
_.each(items, function(item) {
if (item.track) {
var track = item.track;
var rid = track.album.id;
var aid = track.artists[0].id;
albums[rid] = rid;
artists[aid] = aid;
}
});
return Object.keys(albums).length > 1 && Object.keys(artists).length > 1;
}
function doneFetching() {
abortFetching = false;
$("#fetching-tracks").hide(100);
if (topTracks.length == 0) {
info("No matching tracks found");
} else {
$("#ready-to-save").show();
}
var end = new Date().getTime();
var total = end - start;
console.log('delta time', total, 'len',
allPlaylists.length, 'per 1000', Math.round(total / allPlaylists.length));
}
var outstanding = 0;
var maxSimultaneous = 10;
function fetchNextTracksFromPlaylist() {
while (!abortFetching && queue.length > 0 && outstanding < maxSimultaneous) {
var tinfo = queue.pop(0);
var user = tinfo[0];
var pid = tinfo[1];
var url = "https://api.spotify.com/v1/users/"
+ user + "/playlists/" + pid + "/tracks";
outstanding++;
callSpotify(url).then(
function(data) {
var remaining = outstanding + queue.length;
var progress = Math.round(100.0 - (100.0 * remaining / allPlaylists.length));
$("#track-progress").css('width', progress + "%");
$("#tt-total-tracks").text(totalTracks);
$("#tt-unique-tracks").text(Object.keys(allTracks).length);
if (isGoodPlaylist(data.items)) {
totalPlaylistCount += 1;
_.each(data.items, function(item, i) {
var count = i == 0 ? 3 : i <= 2 ? 1 : 1;
if (item.track) {
if (item.track.id) {
if ( !(item.track.id in allTracks) ) {
allTracks[item.track.id] = item.track;
allTracks[item.track.id].count = 0;
}
allTracks[item.track.id].count += count;
totalTracks += 1;
}
}
});
} else {
}
refreshTrackList(allTracks);
--outstanding;
if (outstanding <= 0 && (abortFetching ||queue.length == 0)) {
doneFetching();
} else {
fetchNextTracksFromPlaylist();
}
},
function() {
error("trouble fetching tracks");
--outstanding;
if (outstanding <= 0 && (abortFetching || queue.length == 0)) {
doneFetching();
} else {
fetchNextTracksFromPlaylist();
}
}
);
}
}
fetchNextTracksFromPlaylist();
}
function initApp() {
$(".intro-form").hide();
$(".results").hide();
$("#playlist-terms").keyup(
function(event) {
if (event.keyCode == 13) {
go();
}
}
);
$("#go").on('click', function() {
go();
});
$(".stop-button").on('click', function() {
abortFetching = true;
});
$("#fetch-tracks").on('click', function() {
fetchAllTracksFromPlaylist();
});
$("#login-button").on('click', function() {
loginWithSpotify();
});
$("#save-button").on('click', function() {
savePlaylist();
});
$("#norm-for-pop").on('click', function() {
popNormalize = $("#norm-for-pop").is(':checked');
refreshTrackList(allTracks);
});
}
function loginWithSpotify() {
var client_id = '4042a231fe624583a694f1d6cf9e25b5';
var redirect_uri = 'http://playlistminer.playlistmachinery.com/';
var scopes = 'playlist-modify-public';
if (document.location.hostname == 'localhost') {
redirect_uri = 'http://localhost:8000/index.html';
}
var url = 'https://accounts.spotify.com/authorize?client_id=' + client_id +
'&response_type=token' +
'&scope=' + encodeURIComponent(scopes) +
'&redirect_uri=' + encodeURIComponent(redirect_uri);
document.location = url;
}
function getTime() {
return Math.round(new Date().getTime() / 1000);
}
function performAuthDance() {
// if we already have a token and it hasn't expired, use it,
if ('credentials' in localStorage) {
credentials = JSON.parse(localStorage.credentials);
}
if (credentials && credentials.expires > getTime()) {
$("#search-form").show();
} else {
// we have a token as a hash parameter in the url
// so parse hash
var hash = location.hash.replace(/#/g, '');
var all = hash.split('&');
var args = {};
all.forEach(function(keyvalue) {
var idx = keyvalue.indexOf('=');
var key = keyvalue.substring(0, idx);
var val = keyvalue.substring(idx + 1);
args[key] = val;
});
if (typeof(args['access_token']) != 'undefined') {
var g_access_token = args['access_token'];
var expiresAt = getTime() + 3600;
if (typeof(args['expires_in']) != 'undefined') {
var expires = parseInt(args['expires_in']);
expiresAt = expires + getTime();
}
credentials = {
token:g_access_token,
expires:expiresAt
}
callSpotify('https://api.spotify.com/v1/me').then(
function(user) {
credentials.user_id = user.id;
localStorage['credentials'] = JSON.stringify(credentials);
location.hash = '';
$("#search-form").show();
},
function() {
error("Can't get user info");
}
);
} else {
// otherwise, got to spotify to get auth
$("#login-form").show();
}
}
}
$(document).ready(
function() {
initApp();
performAuthDance();
}
);
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-3675615-45', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>