-
Notifications
You must be signed in to change notification settings - Fork 2
/
spotify.ts
77 lines (67 loc) · 2.09 KB
/
spotify.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
import { v4 as uuidv4 } from 'uuid';
import {
getAccessToken,
getInvalidTime,
setAccessToken,
setInvalidTime,
setSpotifyState,
} from './storage';
const spotifyUri = 'https://accounts.spotify.com/authorize';
const clientId = `client_id=${process.env.REACT_APP_SPOTIFY_CLIENT_ID}`;
const responseType = 'response_type=token';
const redirectUri = `redirect_uri=${process.env.REACT_APP_SPOTIFY_REDIRECT_URI}`;
const scope = `scope=${[
'user-library-read',
'user-read-email',
'user-read-private',
'user-read-recently-played',
'playlist-read-private',
].join(' ')}`;
const showDialog = 'show_dialog=true';
// user-library-read - album
// user-read-email - profile
// user-read-private - profile
// scopes for spotify: https://developer.spotify.com/documentation/general/guides/authorization-guide/#list-of-scopes
const spotifyAlbumUri = 'https://api.spotify.com/v1/me/albums';
export const redirectToSpotifyLogin = () => {
const uuid = uuidv4();
setSpotifyState(uuid);
const url = `${spotifyUri}?${clientId}&${redirectUri}&${scope}&${responseType}&${showDialog}&state=${uuid}`;
window.location.href = url;
};
export const persistAccessToken = (accessToken: string, expireDate: number) => {
setAccessToken(accessToken);
setInvalidTime(expireDate);
};
interface Token {
accessToken: string;
expireTime: number;
}
export const getPersistedAccessToken = (): Token | undefined => {
const accessToken = getAccessToken();
const expireTime = getInvalidTime();
if (accessToken && expireTime) {
return {
accessToken,
expireTime,
};
}
};
export const removePersistedState = () => {
setAccessToken(undefined);
setInvalidTime(0);
};
export const getSpotifyAlbums = async () => {
const accessToken = getAccessToken();
const response = await fetch(spotifyAlbumUri, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return await response.json();
};
export const isTrackObject = (
track: SpotifyApi.TrackObjectFull | SpotifyApi.EpisodeObjectFull
): track is SpotifyApi.TrackObjectFull => {
return !!(track as SpotifyApi.TrackObjectFull).artists;
};