-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
248 lines (185 loc) · 6.91 KB
/
script.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
// Generate Code Verifier
function generateRandomString(length) {
let text = '';
const possible =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
const codeVerifier = document.getElementById('code-verifier');
codeVerifier.innerText = text;
// await new Promise(r => setTimeout(r, 2000));
return text;
}
// Hash the verifier.
async function generateCodeChallenge(codeVerifier) {
const digest = await crypto.subtle.digest(
'SHA-256',
new TextEncoder().encode(codeVerifier),
);
return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
// User is sent to this URL
function generateUrlWithSearchParams(url, params) {
const urlObject = new URL(url);
urlObject.search = new URLSearchParams(params).toString();
return urlObject.toString();
}
// Send user to the auth url.
// If they accept the below scope, then then they will
// be sent to the redirect URL with a code in the query params.
// this code is then exchanged for an access token.
const scope = 'user-read-currently-playing'
function redirectToSpotifyAuthorizeEndpoint() {
const codeVerifier = generateRandomString(64);
generateCodeChallenge(codeVerifier).then((code_challenge) => {
window.localStorage.setItem('code_verifier', codeVerifier);
window.location = generateUrlWithSearchParams(
'https://accounts.spotify.com/authorize',
{
response_type: 'code',
client_id,
scope: scope,
code_challenge_method: 'S256',
code_challenge,
redirect_uri,
},
)
});
}
// now that we have an auth code, we must provide the verifier along with
// the redirect uri, and client id
function exchangeToken(code) {
console.log("Getting code_verifier, getting access token. Auth code: " + code);
const code_verifier = localStorage.getItem('code_verifier');
fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
body: new URLSearchParams({
client_id,
grant_type: 'authorization_code',
code,
redirect_uri,
code_verifier,
}),
}).then(addThrowErrorToFetch)
.then((data) => {
processTokenResponse(data);
// clear search query params in the url
window.history.replaceState({}, document.title, '/');
})
}
// can be called to clear local storage and reload window
function logout() {
localStorage.clear();
window.location.reload();
}
async function addThrowErrorToFetch(response) {
if (response.ok) {
return response.json();
} else {
throw { response, error: await response.json() };
}
}
function show(input){
if (input === 'login'){
document.getElementById('login').style.display = 'unset';
document.getElementById('loggedin').style.display = 'none';
} else if (input === 'loggedin'){
document.getElementById('login').style.display = 'none';
document.getElementById('loggedin').style.display = 'unset';
}
}
// Process the response upon sending the auth code to the auth server.
// Get the access token.
function processTokenResponse(data) {
console.log(`Access Token Response ${JSON.stringify(data)}`);
console.log("Access Token: " + data.access_token)
access_token = data.access_token;
const t = new Date();
expires_at = t.setSeconds(t.getSeconds() + data.expires_in);
localStorage.setItem('access_token', access_token);
// Replace login screen with logged in screen
show('loggedin');
// load data of logged in user
// TODO: Call function to get currently playing song
console.log(`Access_token in local Storage: ${localStorage.getItem('access_token')}`)
}
// Client ID from spotify dashboard
const client_id = 'b189b96c428d420988bc622dbe88ce57';
const redirect_uri = 'https://geromics.github.io/oauth-pkce-example/'; // Your redirect uri
// Restore tokens from localStorage
let access_token = localStorage.getItem('access_token') || null;
// Get auth code from query params after user has been called back to the redirect uri.
const args = new URLSearchParams(window.location.search);
const code = args.get('code');
// This javascript will either be run when the user initially loads the page, or when the user
// is redirected back to the page after they have accepted the scopes.
// If the user is redirected back to the page, then the code will be in the query params.
// If the user is initially loading the page, then the code will be null.
if (code) {
exchangeToken(code);
} else if (access_token) {
// we have already been logged in
show('loggedin');
} else {
// we are not logged in so show the login button
show('login');
}
document.getElementById('login-button')
.addEventListener('click', () => {redirectToSpotifyAuthorizeEndpoint()}, false);
document.getElementById('logout-button').addEventListener('click', () => {logout()}, false);
// And now... The cool stuff :)
const getCurrent = document.getElementById('getCurrent')
const content = document.getElementById('content')
let currentSongData = ''
let user = ''
fetch(`https://api.spotify.com/v1/me?access_token=${access_token}`)
.then(addThrowErrorToFetch)
.then(data => {
console.log("User data: " + JSON.stringify(data))
user = data
})
getCurrent.addEventListener('click', () => {
fetch('https://api.spotify.com/v1/me/player/currently-playing', {
headers: {
Authorization: 'Bearer ' + access_token,
},
})
.then(addThrowErrorToFetch)
.then((data) => {
console.log("Currently playing: " + JSON.stringify(data))
console.log("Song: " + data.item.name)
currentSongData = data
content.innerHTML = processTrack(data)
const currentSong = document.createElement("h1")
currentSong.innerText = `${data.item.name}`
content.appendChild(currentSong)
const artists = data.item.artists
console.log("Artists: " + JSON.stringify(artists))
artists.forEach((artist,index) => {
console.log("Artist " + index + ": " + artist.name)
const artistName = document.createElement("h2")
artistName.innerText = `${artist.name}`
content.appendChild(artistName)
document.getElementById('recommend').style.display = 'unset';
})
})
.catch((error) => {
if (error === 'no-song'){
console.log("Nothing playing right now...")
content.innerHTML = `<p>Our miners couldn't find your current song...</p>`
}
})
})
function processTrack(data){
return `
<div class="wrapper">
<img src="${data.item.album.images[1].url}" id="albumArt">
</div>`
}