-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
292 lines (255 loc) · 7.78 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React App</title>
<style>
body, html {
margin: 0;
padding: 0;
}
#root {
background-color: black;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.btn {
background-color: white;
color: black;
padding: 20px;
border-radius: 50%;
font-size: 24px;
width: 200px;
height: 200px;
font-weight: bold;
}
</style>
</head>
<body>
<div id="root">
<button class="btn" id="rewind-button">REWIND</button>
</div>
<script>
const generateRandomString = (length) => {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const values = crypto.getRandomValues(new Uint32Array(length));
return values.reduce((acc, x) => acc + possible[x % possible.length], '');
};
const makeLocalStorageItem = (name, value, duration_s) => {
const now = new Date();
const expirationTime = now.getTime() + duration_s * 1000;
const item = {
value: value,
expires: expirationTime,
};
localStorage.setItem(name, JSON.stringify(item));
}
const maybeGetLocalStorageItem = (name) => {
const storedItem = localStorage.getItem(name);
if (!storedItem) {
return '';
}
const parsedItem = JSON.parse(storedItem);
const now = new Date().getTime();
if (now < parsedItem.expires) {
return parsedItem.value;
} else {
localStorage.removeItem(name);
return '';
}
}
const setAccessToken = (token) => {
const duration_1_hour = 60 * 60;
makeLocalStorageItem('access_token', token, duration_1_hour);
}
const refreshAccessToken = (_) => {
let refreshToken = localStorage.getItem('refresh_token');
const url = 'https://accounts.spotify.com/api/token';
const payload = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: clientId,
}),
}
fetch(url, payload)
.then(response => response.json())
.then(data => {
setAccessToken(data.access_token);
})
.catch(error => console.error(error));
}
const getAccessToken = (_) => {
let accessToken = maybeGetLocalStorageItem('access_token');
if (accessToken === '') {
refreshAccessToken();
accessToken = maybeGetLocalStorageItem('access_token');
if (accessToken === '') {
requestUserAuthorization();
}
} else {
return accessToken;
}
}
const sha256 = (plain) => {
const encoder = new TextEncoder();
const data = encoder.encode(plain);
return window.crypto.subtle.digest('SHA-256', data);
}
const base64encode = (input) => {
return btoa(String.fromCharCode(...new Uint8Array(input)))
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
const areWeOnLocalhost = () => {
return window.location.hostname !== "mcleantom.github.io";
}
const clientId = '63013162bacc41f29f68ce6114ae395b';
const getRootUrl = () => {
if (areWeOnLocalhost()) {
return 'http://localhost:5500'
}
return 'https://mcleantom.github.io/spotify_rewind_button'
}
let redirectUri = '';
if (areWeOnLocalhost()) {
redirectUri = "http://localhost:5500/redirect"
}
else {
redirectUri = "https://mcleantom.github.io/spotify_rewind_button/redirect"
}
const scope = 'user-read-private user-read-email user-modify-playback-state user-read-currently-playing';
const authUrl = new URL('https://accounts.spotify.com/authorize');
const requestUserAuthorization = async () => {
const codeVerifier = generateRandomString(128);
const hashed = await sha256(codeVerifier);
const codeChallenge = base64encode(hashed);
window.localStorage.setItem('code_verifier', codeVerifier);
const params = {
response_type: 'code',
client_id: clientId,
scope,
code_challenge_method: 'S256',
code_challenge: codeChallenge,
redirect_uri: redirectUri,
}
authUrl.search = new URLSearchParams(params).toString();
window.location.href = authUrl.toString();
}
const exchangeToken = async _ => {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const url = 'https://accounts.spotify.com/api/token';
let codeVerifier = window.localStorage.getItem('code_verifier');
const payload = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: clientId,
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
}),
}
const body = await fetch(url, payload).catch(error => console.error(error));
const response = await body.json();
console.log(response);
setAccessToken(response.access_token);
}
async function getProfile() {
let accessToken = localStorage.getItem('access_token');
const response = await fetch('https://api.spotify.com/v1/me', {
headers: {
Authorization: 'Bearer ' + accessToken
}
});
const data = await response.json();
return data;
}
const pauseSong = async () => {
console.log("Pausing");
let accessToken = getAccessToken();
const response = await fetch('https://api.spotify.com/v1/me/player/pause', {
method: 'PUT',
headers: {
Authorization: 'Bearer ' + accessToken
}
});
return response.status;
}
const getCurrentlyPlaying = async () => {
let accessToken = getAccessToken();
const response = await fetch('https://api.spotify.com/v1/me/player/currently-playing', {
method: 'GET',
headers: {
Authorization: 'Bearer ' + accessToken
}
});
const data = await response.json();
return data;
}
const play = async () => {
console.log("Playing");
let accessToken = getAccessToken();
const response = await fetch('https://api.spotify.com/v1/me/player/play', {
method: 'PUT',
headers: {
Authorization: 'Bearer ' + accessToken
}
});
return response.status;
}
const seekToPosition = async (position) => {
console.log("Seeking to position " + position);
let accessToken = getAccessToken();
const response = await fetch('https://api.spotify.com/v1/me/player/seek?position_ms=' + position, {
method: 'PUT',
headers: {
Authorization: 'Bearer ' + accessToken
}
});
return response.status;
}
let playRewindSound = () => {
getCurrentlyPlaying().then(data => {
console.log(data);
pauseSong().then(_ => {
const rootUrl = getRootUrl();
const audio_file = rootUrl + "/rewind_sound_effect.mp3";
let audio = new Audio(audio_file);
audio.play();
seekToPosition(data.progress_ms - 10000);
setTimeout(() => {
play().then(_ => {
console.log("Playing");
});
}, 2000);
});
});
};
function onPageLoad() {
const access_token = getAccessToken();
if (access_token == '') {
requestUserAuthorization();
}
}
onPageLoad();
document.getElementById('rewind-button').addEventListener('click', (event) => {
playRewindSound();
})
</script>
</body>
</html>