-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
449 lines (409 loc) · 23.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mixtape Creator</title>
<script src="https://unpkg.com/vue@3.4.23/dist/vue.global.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/1.0.0/css/bulma.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
<style>
/* This style element is for extra CSS */
html {
background-color: #000;
background-image: linear-gradient(rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.5)), url('images/background_1.png');
background-size: cover;
background-repeat: no-repeat;
min-height: 100%;
background-position: center;
}
.container {
padding: 20px 0px;
background-image: linear-gradient(rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.5));
border-radius: 10px; /* Rounded border */
}
#app {
margin: auto 20px;
}
</style>
</head>
<body>
<section class="section">
<div class="container">
<div id="app">
<div id="spotifyCredentials" v-if="showSpotifyCredentials" class="box">
<h2 class="title is-4">Allow Access to Spotify</h2>
<p class="block">In order to be able to search for songs and create a mixtape playlist you need to grant access to your spotify account.</p>
<div class="field">
<div class="control">
<button class="button is-link" @click="loginWithSpotify">Login with Spotify</button>
</div>
</div>
</div>
<div id="mixtape" v-else>
<div class="modal is-active" v-if="showModal">
<div class="modal-background"></div>
<div class="modal-content">
<div class="box">
<h3 class="title is-4">Playlists Created Successfully</h3>
<div v-html="modalContent"></div>
<button class="button is-success" @click="closeModal()">Close</button>
</div>
</div>
</div>
<h1 class="title">Mixtape Creator</h1>
<div class="field">
<label for="mixtape-length" class="label">Select Mixtape Length:</label>
<div class="control">
<div class="select">
<select v-model="mixtapeLength" @change="updateRemainingTime">
<option value="3600">60 minutes</option>
<option value="5400">90 minutes</option>
<option value="6000">100 minutes</option>
<option value="7200">120 minutes</option>
</select>
</div>
</div>
</div>
<div class="field">
<label for="mixtape-title" class="label">Mixtape Title:</label>
<div class="control">
<input class="input" type="text" id="mixtape-title" v-model="mixtapeTitle" placeholder="Enter Mixtape Title">
</div>
</div>
<div class="columns">
<div class="column is-half">
<div class="box">
<h2 class="title is-5">Side A</h2>
<div class="block">Remaining: <span class="tag is-info">{{ formattedTime(remainingTimeA) }}</span></div>
<ul>
<li v-for="song in sideA" :key="song.id" class="song-details">
<div class="columns">
<div class="column">
{{ song.name }} by {{ song.artists[0].name }} <span class="tag is-info is-light">{{ formattedTime(song.duration_ms / 1000) }}</span>
</div>
<div class="column is-narrow">
<div class="buttons are-small">
<button class="button is-small" @click="moveSongUp('A', song)">
<span class="icon"><i class="fas fa-arrow-up"></i></span>
</button>
<button class="button is-small" @click="moveSongDown('A', song)">
<span class="icon"><i class="fas fa-arrow-down"></i></span>
</button>
<button class="button is-small is-danger" @click="removeSong('A', song)">
<span class="icon"><i class="fa fa-times"></i></span>
</button>
<button class="button is-small is-info" @click="moveSong('B', song)">
<span class="icon"><i class="fas fa-arrow-right"></i></span> <span>Move to B</span>
</button>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
<div class="column is-half">
<div class="box">
<h2 class="title is-5">Side B</h2>
<div class="block">Remaining: <span class="tag is-info">{{ formattedTime(remainingTimeB) }}</span></div>
<ul>
<li v-for="song in sideB" :key="song.id" class="song-details">
<div class="columns">
<div class="column">
{{ song.name }} by {{ song.artists[0].name }} <span class="tag is-info is-light">{{ formattedTime(song.duration_ms / 1000) }}</span>
</div>
<div class="column is-narrow">
<div class="buttons are-small">
<button class="button is-small" @click="moveSongUp('B', song)">
<span class="icon"><i class="fas fa-arrow-up"></i></span>
</button>
<button class="button is-small" @click="moveSongDown('B', song)">
<span class="icon"><i class="fas fa-arrow-down"></i></span>
</button>
<button class="button is-small is-danger" @click="removeSong('B', song)">
<span class="icon"><i class="fa fa-times"></i></span>
</button>
<button class="button is-small is-info" @click="moveSong('A', song)">
<span class="icon"><i class="fas fa-arrow-left"></i></span> <span>Move to A</span>
</button>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
<div class="field">
<div class="control">
<button class="button is-primary" @click="createMixtapePlaylist">Save the Mix</button>
</div>
</div>
<label class="label is-medium">Add songs to your mixtape</label>
<div class="field has-addons">
<div class="control is-expanded">
<input class="input" type="text" v-model="searchQuery" placeholder="Search for songs">
</div>
<div class="control">
<button class="button is-info" @click="searchSongs">Search</button>
</div>
</div>
<ul>
<li v-for="song in searchResults" :key="song.id" class="song">
<div class="columns">
<div class="column">
{{ song.name }} ({{song.album.name}}) by {{ song.artists[0].name }} <span class="tag is-info is-light">{{ formattedTime(song.duration_ms / 1000) }}</span>
</div>
<div class="column">
<div class="buttons">
<button class="button is-small is-success" @click="addSong('A', song)">Add to Side A</button>
<button class="button is-small is-success" @click="addSong('B', song)">Add to Side B</button>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</section>
<script>
const { createApp, ref, watch } = Vue;
createApp({
setup() {
// authorization
const clientId = 'ce6afc8d146f440785acdb00ee2e4013';
const authorizationEndpoint = "https://accounts.spotify.com/authorize";
const scope = 'user-read-private user-read-email playlist-modify-private playlist-modify-public';
const redirectUrl = window.location.href.split('?')[0];
// Data structure that manages the current active token, caching it in localStorage
const currentToken = {
get access_token() { return localStorage.getItem('access_token') || null; },
get refresh_token() { return localStorage.getItem('refresh_token') || null; },
get expires_in() { return localStorage.getItem('refresh_in') || null },
get expires() { return localStorage.getItem('expires') || null },
save: function (response) {
const { access_token, refresh_token, expires_in } = response;
localStorage.setItem('access_token', access_token);
localStorage.setItem('refresh_token', refresh_token);
localStorage.setItem('expires_in', expires_in);
const now = new Date();
const expiry = new Date(now.getTime() + (expires_in * 1000));
localStorage.setItem('expires', expiry);
}
};
// app data
const mixtapeLength = ref(3600);
const remainingTimeA = ref(mixtapeLength.value / 2);
const remainingTimeB = ref(mixtapeLength.value / 2);
const mixtapeTitle = ref('');
const sideA = ref([]);
const sideB = ref([]);
const searchQuery = ref('');
const searchResults = ref([]);
const showModal = ref(false);
const modalContent = ref('');
const accessToken = ref('');
const songs = ref([]);
const showSpotifyCredentials = ref(!currentToken.access_token);
async function loginWithSpotify() {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const randomValues = crypto.getRandomValues(new Uint8Array(64));
const randomString = randomValues.reduce((acc, x) => acc + possible[x % possible.length], "");
const code_verifier = randomString;
const data = new TextEncoder().encode(code_verifier);
const hashed = await crypto.subtle.digest('SHA-256', data);
const code_challenge_base64 = btoa(String.fromCharCode(...new Uint8Array(hashed)))
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
window.localStorage.setItem('code_verifier', code_verifier);
const authUrl = new URL(authorizationEndpoint)
const params = {
response_type: 'code',
client_id: clientId,
scope: scope,
code_challenge_method: 'S256',
code_challenge: code_challenge_base64,
redirect_uri: redirectUrl,
};
authUrl.search = new URLSearchParams(params).toString();
window.location.href = authUrl.toString(); // Redirect the user to the authorization server for login
}
async function checkCallback() {
// On page load, try to fetch auth code from current browser search URL
const args = new URLSearchParams(window.location.search);
const code = args.get('code');
// If we find a code, we're in a callback, do a token exchange
if (code) {
const token = await getToken(code);
currentToken.save(token);
// Remove code from URL so we can refresh correctly.
const url = new URL(window.location.href);
url.searchParams.delete("code");
const updatedUrl = url.search ? url.href : url.href.replace('?', '');
window.history.replaceState({}, document.title, updatedUrl);
}
// If we have a token, we're logged in, so fetch user data and render logged in template
if (currentToken.access_token) {
showSpotifyCredentials.value = false;
}
}
checkCallback();
// Spotify API Calls
async function fetchAccountsApi(endpoint, method, body) {
const response = await fetch(`https://accounts.spotify.com/${endpoint}`, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method,
body: new URLSearchParams(body)
});
return await response.json();
}
async function getToken(code) {
const code_verifier = localStorage.getItem('code_verifier');
const bodyParams = {
client_id: clientId,
grant_type: 'authorization_code',
code: code,
redirect_uri: redirectUrl,
code_verifier: code_verifier,
};
return await fetchAccountsApi("api/token", 'POST', bodyParams);
}
async function refreshToken() {
const bodyParams = {
client_id: clientId,
grant_type: 'refresh_token',
refresh_token: currentToken.refresh_token
};
const newToken = await fetchAccountsApi("api/token", 'POST', bodyParams);
currentToken.save(newToken);
return newToken;
}
async function fetchWebApi(endpoint, method, body) {
const res = await fetch(`https://api.spotify.com/${endpoint}`, {
headers: {
Authorization: `Bearer ${currentToken.access_token}`,
},
method,
body: JSON.stringify(body)
});
if (res.status === 401) {
await refreshToken();
return fetchWebApi(endpoint, method, body);
}
return await res.json();
}
function searchSongs() {
fetchWebApi(`v1/search?q=${encodeURIComponent(searchQuery.value)}&type=track`, 'GET')
.then(data => {
searchResults.value = data.tracks.items;
console.log('Search Results:', data.tracks.items)
})
.catch(error => console.error('Error:', error));
}
async function createMixtapePlaylist() {
const playlistNames = [`${mixtapeTitle.value} (Mixtape Side A)`, `${mixtapeTitle.value} (Mixtape Side B)`];
const playlistIds = [];
const playlistLinks = [];
const { id: user_id } = await fetchWebApi('v1/me', 'GET');
for (const name of playlistNames) {
const playlist = await fetchWebApi(`v1/users/${user_id}/playlists`, 'POST', {
name: name,
description: 'Generated by Mixtape Creator',
public: false
});
playlistIds.push(playlist.id);
playlistLinks.push(`https://open.spotify.com/playlist/${playlist.id}`);
}
await addTracksToPlaylist(playlistIds[0], sideA.value);
await addTracksToPlaylist(playlistIds[1], sideB.value);
showModalWithLinks(playlistNames, playlistLinks);
}
function showModalWithLinks(playlistNames, playlistLinks) {
modalContent.value = playlistNames.map((name, index) =>
`<p>${name}: <a href="${playlistLinks[index]}" target="_blank">${playlistLinks[index]}</a></p>`
).join('');
showModal.value = true;
}
function closeModal() {
showModal.value = false;
modalContent.value = '';
}
async function addTracksToPlaylist(playlistId, tracks) {
const trackUris = tracks.map(track => track.uri);
await fetchWebApi(`v1/playlists/${playlistId}/tracks`, 'POST', { uris: trackUris });
}
function addSong(side, song) {
if (side === 'A' && remainingTimeA.value >= song.duration_ms / 1000) {
sideA.value.push(song);
remainingTimeA.value -= song.duration_ms / 1000;
} else if (side === 'B' && remainingTimeB.value >= song.duration_ms / 1000) {
sideB.value.push(song);
remainingTimeB.value -= song.duration_ms / 1000;
} else {
alert(`Cannot add "${song.name}" to Side ${side}. Not enough remaining time.`);
return false;
}
return true;
}
function removeSong(side, song) {
if (side === 'A') {
const index = sideA.value.findIndex(s => s.id === song.id);
if (index !== -1) {
sideA.value.splice(index, 1);
}
remainingTimeA.value += song.duration_ms / 1000;
} else {
const index = sideB.value.findIndex(s => s.id === song.id);
if (index !== -1) {
sideB.value.splice(index, 1);
}
remainingTimeB.value += song.duration_ms / 1000;
}
}
function moveSong(targetSide, song) {
const success = addSong(targetSide, song);
if (success) {
removeSong(targetSide === 'A' ? 'B' : 'A', song);
}
}
function moveSongUp(side, song) {
const sideList = side === 'A' ? sideA.value : sideB.value;
const index = sideList.findIndex(s => s.id === song.id);
if (index > 0) {
const item = sideList[index];
sideList.splice(index, 1);
sideList.splice(index - 1, 0, item);
}
}
function moveSongDown(side, song) {
const sideList = side === 'A' ? sideA.value : sideB.value;
const index = sideList.findIndex(s => s.id === song.id);
if (index !== -1 && index < sideList.length - 1) {
const item = sideList[index];
sideList.splice(index, 1);
sideList.splice(index + 1, 0, item);
}
}
function formattedTime(seconds) {
seconds = Math.round(seconds);
const min = Math.floor(seconds / 60);
const sec = seconds % 60;
return `${min}:${sec.toString().padStart(2, '0')}`;
}
function updateRemainingTime() {
remainingTimeA.value = mixtapeLength.value / 2;
remainingTimeB.value = mixtapeLength.value / 2;
sideA.value = [];
sideB.value = [];
}
return { showModal, modalContent, closeModal, moveSongUp, moveSongDown, showSpotifyCredentials, mixtapeLength, mixtapeTitle, remainingTimeA, remainingTimeB, sideA, sideB, searchQuery, searchResults, loginWithSpotify, addSong, removeSong, moveSong, searchSongs, formattedTime, updateRemainingTime, createMixtapePlaylist };
}
}).mount('#app');
</script>
</body>
</html>