-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathspfetch.js
98 lines (85 loc) · 2.74 KB
/
spfetch.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
import { client_id, scope } from './config.json';
let accessToken = getTokenFromUrlHash();
const spfetch = (global.spfetch = async (input, init) => {
if (!accessToken) await spfetch.login();
if (!init) init = {};
if (!init.headers) init.headers = {};
init.headers.Authorization = `Bearer ${accessToken}`;
const response = await fetch(
input.startsWith('https://')
? input
: `https://api.spotify.com${input.startsWith('/') ? '' : '/'}${input}`,
{
...init,
body:
typeof init.body === 'object' ? JSON.stringify(init.body) : init.body
}
);
const { ok, status, statusText } = response;
let json = {};
try {
json = await response.json();
} catch (error) {}
const { error: { message: errorMessage } = {} } = json || {};
if (
response.status === 401 &&
(errorMessage === 'The access token expired' ||
errorMessage === 'Invalid access token')
) {
accessToken = await fetchTokenFromPopup();
return spfetch(input, init);
}
return Object.assign(json, { ok, status });
});
spfetch.login = async () =>
(accessToken =
accessToken || getTokenFromUrlHash() || (await fetchTokenFromPopup()));
spfetch.logout = () => (accessToken = null);
spfetch.isLoggedIn = () => !!accessToken;
spfetch.getToken = () => accessToken;
export default spfetch;
function getTokenFromUrlHash() {
return new URLSearchParams(global.location.hash.slice(1)).get('access_token');
}
async function fetchTokenFromPopup() {
return new Promise((resolve, reject) => {
const timeout = setTimeout(
reject,
20000,
new Error('Timeout getting token')
);
window.addEventListener(
'message',
function onMessage(event) {
let data = event.data;
try {
data = JSON.parse(event.data);
} catch (error) {}
const { type, accessToken } = data || {};
if (type === 'access_token') {
clearTimeout(timeout);
resolve(accessToken);
window.removeEventListener('message', onMessage, false);
global.location.hash = new URLSearchParams([
['access_token', accessToken]
]).toString();
}
},
false
);
const width = 450;
const height = 730;
const left = window.screen.width / 2 - width / 2;
const top = window.screen.height / 2 - height / 2;
const url = new URL(window.location.origin);
url.pathname =
window.location.hostname === 'localhost' ? 'auth.html' : 'auth';
url.searchParams.set('client_id', client_id);
url.searchParams.set('scope', scope);
window.open(
url.toString(),
'Spotify',
`menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=${width}, height=${height}, top=${top}, left=${left}`
);
});
}