-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
322 lines (309 loc) · 12.7 KB
/
index.ts
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
export default class SpotifyController_PKCE {
// Spotify API endpoints
private static readonly TOKEN = "https://accounts.spotify.com/api/token";
private static readonly DEVICES: string = "https://api.spotify.com/v1/me/player/devices";
private static readonly PLAY: string = "https://api.spotify.com/v1/me/player/play";
private static readonly PAUSE: string = "https://api.spotify.com/v1/me/player/pause";
private static readonly NEXT: string = "https://api.spotify.com/v1/me/player/next";
private static readonly PREVIOUS: string = "https://api.spotify.com/v1/me/player/previous";
private static readonly CURRENTLYPLAYING: string = "https://api.spotify.com/v1/me/player/currently-playing";
private static readonly SEARCH: string = "https://api.spotify.com/v1/search";
// some other endpoints I haven't used yet
// private static readonly PLAYLISTS: string = "https://api.spotify.com/v1/me/playlists";
// private static readonly PLAYER: string = "https://api.spotify.com/v1/me/player";
// private static readonly TRACKS: string = "https://api.spotify.com/v1/playlists/{{PlaylistId}}/tracks";
// private static readonly SHUFFLE: string = "https://api.spotify.com/v1/me/player/shuffle";
private access_token: string;
private refresh_token: string;
private expire_time: number;
private refreshTimeout: any;
private client_id: string;
private auth_code: string;
private redirect_uri: string;
private code_verifier: string;
constructor(
auth_code: string,
redirect_uri: string,
client_id: string,
code_verifier: string,
callback?: (err?: any) => void,
) {
this.auth_code = auth_code;
this.redirect_uri = redirect_uri;
this.client_id = client_id;
this.code_verifier = code_verifier;
this.expire_time = 3600; // default expiration time of spotify api
this.refreshTimeout = undefined;
//try to get from sessionStorage
this.access_token = sessionStorage.getItem("access_token") || "";
this.refresh_token = sessionStorage.getItem("refresh_token") || "";
if (this.redirect_uri) {
if (this.auth_code) {
this.requestAuthorization() // authorize with given athCode
.then(
(err: any) => {
if (callback) {
if (err) {
callback(err);
} else {
callback();
}
}
}
)
} else {
//if no auth_code provided, try to use tokens from session storage
if (this.access_token && this.refresh_token) {
this.refreshAccessToken()
// try refresh token to make sure it's not expired and renew the timer
.then(
(err: any) => {
if (callback) {
if (err) {
callback(new Error(err));
} else {
callback();
}
}
}
)
} else {
if (callback) {
callback(new Error("No auth code provided && No token in sessionStorage"));
}
}
}
}
}
private requestAuthorization: () => Promise<Error | undefined> = async () => {
let body = "grant_type=authorization_code";
body += "&code=" + this.auth_code;
body += "&redirect_uri=" + this.redirect_uri;
body += "&client_id=" + this.client_id;
body += "&code_verifier=" + this.code_verifier;
const response = await fetch(
SpotifyController_PKCE.TOKEN,
{
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: body
});
if (response.ok) {
const data = await response.json();
this.access_token = data.access_token ? data.access_token : this.access_token;
this.refresh_token = data.refresh_token ? data.refresh_token : this.refresh_token;
this.expire_time = data.expires_in ? data.expires_in : this.expire_time;
sessionStorage.setItem("access_token", this.access_token);
sessionStorage.setItem("refresh_token", this.refresh_token);
clearTimeout(this.refreshTimeout);
this.refreshTimeout = setTimeout(() => {
this.refreshAccessToken();
}, this.expire_time * 1000);
} else {
return new Error('Authorization request failed');
}
}
private refreshAccessToken: () => Promise<Error | undefined> = async () => {
let body = "grant_type=refresh_token";
body += "&refresh_token=" + this.access_token;
body += "&client_id=" + this.client_id;
const response = await fetch(
SpotifyController_PKCE.TOKEN,
{
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: body
});
if (response.ok) {
const data = await response.json();
this.access_token = data.access_token ? data.access_token : this.access_token;
this.refresh_token = data.refresh_token ? data.refresh_token : this.refresh_token;
this.expire_time = data.expires_in ? data.expires_in : this.expire_time;
sessionStorage.setItem("access_token", this.access_token);
sessionStorage.setItem("refresh_token", this.refresh_token);
clearTimeout(this.refreshTimeout);
this.refreshTimeout = setTimeout(() => {
this.refreshAccessToken();
}, this.expire_time * 1000);
} else {
return new Error("Refresh request failed");
}
}
private callSpotifyApi(
method: string,
url: string,
body: string,
responseHandler?: (res: any) => void
) {
fetch(
url,
{
method: method,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.access_token
},
...(body != '' && { body })
}
)
.then(
response => {
if (response.status == 401) {
//token expired, try refresh token once
this.refreshAccessToken();
}
if (responseHandler) {
responseHandler(response); // pass the response to handler
}
}
)
}
public getDevices = (callback: (devices: Array<any>, err?: any) => void) => {
if (this.access_token) {
const method = 'GET';
this.callSpotifyApi(method, SpotifyController_PKCE.DEVICES, '', (response) => {
if (response.ok) {
response.json()
.then((data: any) => {
const devices = data.devices.map((device: any) => ({
id: device.id,
name: device.name,
type: device.type,
}));
callback(devices);
})
.catch((error: Error) => {
callback([], error);
});
} else {
callback([{}], new Error('Failed to get devices'));
}
});
} else {
callback([{}], new Error('Access token not available'));
}
};
public play = (uri: string, deviceId?: string | null) => {
if (this.access_token) {
let url = SpotifyController_PKCE.PLAY;
if (deviceId) {
url += "?device_id=" + deviceId;
}
const method = 'PUT';
const body = { uris: [uri] };
this.callSpotifyApi(method, url, JSON.stringify(body));
} else {
console.error('Access token not available');
}
}
public resume = (deviceId?: string | null) => {
if (this.access_token) {
let url = SpotifyController_PKCE.PLAY;
if (deviceId) {
url += "?device_id=" + deviceId;
}
const method = 'PUT';
this.callSpotifyApi(method, url, '');
} else {
console.error('Access token not available');
}
}
public pause = (deviceId?: string | null) => {
if (this.access_token) {
let url = SpotifyController_PKCE.PAUSE;
if (deviceId) {
url += "?device_id=" + deviceId;
}
const method = 'PUT';
this.callSpotifyApi(method, url, '');
} else {
console.error('Access token not available');
}
}
public next = (deviceId?: string | null) => {
if (this.access_token) {
let url = SpotifyController_PKCE.NEXT;
if (deviceId) {
url += "?device_id=" + deviceId;
}
const method = 'POST';
this.callSpotifyApi(method, url, '');
} else {
console.error('Access token not available');
}
}
public previous = (deviceId?: string | null) => {
if (this.access_token) {
let url = SpotifyController_PKCE.PREVIOUS;
if (deviceId) {
url += "?device_id=" + deviceId;
}
const method = 'POST';
this.callSpotifyApi(method, url, '');
} else {
console.error('Access token not available');
}
}
public search = (
// this only search for tracks
searchQuery: string,
callback: (results: Array<[string, string, string]>, err?: any) => void
) => {
if (this.access_token) {
const url = `${SpotifyController_PKCE.SEARCH}?q=${searchQuery}&type=track&limit=50`;
const method = 'GET';
this.callSpotifyApi(method, url, '', (response) => {
if (response.ok) {
response.json()
.then((data: any) => {
const tracks = data.tracks.items.map((item: any) => [item.name, item.uri, item.album.images[0].url]);
callback(tracks);
})
.catch((error: Error) => {
callback([], error);
});
} else {
callback([], new Error('Search request failed'));
}
});
} else {
callback([], new Error('Access token not available'));
}
};
public getCurrentSong = (callback: (song: { name: string, uri: string, imageUrl: string, artists: Array<string> } | null, err?: any) => void) => {
if (this.access_token) {
const method = "GET";
this.callSpotifyApi(method, SpotifyController_PKCE.CURRENTLYPLAYING, "", (response) => {
if (response.ok) {
response.json()
.then((data: any) => {
if (data.item) {
const artists = data.item.artists.map((artist: any) => artist.name);
//get artists's name
const song = {
name: data.item.name,
uri: data.item.uri,
imageUrl: data.item.album?.images[0]?.url,
artists: artists
};
callback(song);
} else {
callback(null);
}
})
.catch((error: Error) => {
callback(null, error);
});
} else {
callback(null, new Error("Failed to get currently playing song"));
}
});
} else {
callback(null, new Error("Access token not available"));
}
};
}