This repository was archived by the owner on Oct 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspotify.js
More file actions
160 lines (144 loc) · 4.07 KB
/
spotify.js
File metadata and controls
160 lines (144 loc) · 4.07 KB
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
const axios = require('axios');
const querystring = require('querystring');
const SpotifyWebApi = require('spotify-web-api-node');
const _ = require('lodash');
const { UserModel } = require('./database');
const getUser = async (req, res) => {
// check DB first
const { accessToken } = req.cookies;
const tokenUser = await UserModel.findOne({ accessToken });
if (tokenUser) return tokenUser;
// check Spotify and update client
const {
body: { id }
} = await getSpotify(accessToken).getMe();
const idUser = await UserModel.findById(id);
if (idUser) {
res.cookie('accessToken', idUser.accessToken);
return idUser;
}
// logout user
res.sendStatus(401);
};
const getImage = images =>
(images[1] && images[1].url) || '/default-album-art.jpeg';
const getArtist = artists => {
const { name, id } = artists[0];
return { name, id };
};
const getAlbumInfo = ({ id, name, release_date, images, artists }) => ({
id,
name,
release_date,
image: getImage(images),
artist: getArtist(artists)
});
const requestRetry = (accessToken, res, request) =>
request(getSpotify(accessToken)).catch(async () => {
const newToken = await refreshToken(accessToken, res);
return request(getSpotify(newToken));
});
const searchAlbums = async (query, accessToken, res) => {
if (query === '') return [];
const {
body: {
albums: { items }
}
} = await requestRetry(accessToken, res, spotify =>
spotify.searchAlbums(query)
);
return items.map(getAlbumInfo);
};
const spotifyRedirectURI = req =>
`${req.protocol}://${req.get('host')}/spotify`;
const spotifyLogin = req => {
const params = querystring.stringify({
response_type: 'code',
client_id: process.env.SPOTIFY_CLIENT_ID,
redirect_uri: spotifyRedirectURI(req)
});
return `https://accounts.spotify.com/authorize?${params}`;
};
const getSpotifyConfig = () => {
const auth = Buffer.from(
`${process.env.SPOTIFY_CLIENT_ID}:${process.env.SPOTIFY_CLIENT_SECRET}`
).toString('base64');
return {
headers: {
Authorization: `Basic ${auth}`
}
};
};
const getTokens = req => {
const params = querystring.stringify({
code: req.query.code,
redirect_uri: spotifyRedirectURI(req),
grant_type: 'authorization_code'
});
const url = `https://accounts.spotify.com/api/token?${params}`;
return axios.post(url, null, getSpotifyConfig()).then(({ data }) => data);
};
const saveTokens = (id, accessToken, refreshToken) =>
UserModel.findByIdAndUpdate(
id,
{ accessToken, refreshToken },
{ upsert: true }
);
const getSpotify = accessToken => {
const spotifyApi = new SpotifyWebApi({
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET
});
spotifyApi.setAccessToken(accessToken);
return spotifyApi;
};
const refreshToken = async (accessToken, res) => {
console.log('Refreshing token');
const { id, refreshToken } = await UserModel.findOne({ accessToken });
const params = querystring.stringify({
grant_type: 'refresh_token',
refresh_token: refreshToken
});
const url = `https://accounts.spotify.com/api/token?${params}`;
const {
data: { access_token }
} = await axios.post(url, null, getSpotifyConfig());
res.cookie('accessToken', access_token);
await saveTokens(id, access_token, refreshToken);
return access_token;
};
const getRecommendedTracks = (seedArtistsList, accessToken, res) => {
return requestRetry(accessToken, res, spotify =>
Promise.all(
seedArtistsList.map(seed_artists =>
spotify
.getRecommendations({ seed_artists })
.then(({ body: { tracks } }) => tracks)
)
)
);
};
const getRecommendations = async (favorites, accessToken, res) => {
if (favorites === []) return [];
const favoriteIds = favorites.map(({ artist: { id } }) => id);
const seedArtistsList = _.chunk(_.shuffle(favoriteIds), 5);
const tracksList = await getRecommendedTracks(
seedArtistsList,
accessToken,
res
);
const albums = _
.flatten(tracksList)
.map(({ album }) => getAlbumInfo(album));
// filter duplicates and shuffle
return _.shuffle(_.uniqBy(albums, 'id'));
};
module.exports = {
getUser,
searchAlbums,
getSpotify,
spotifyLogin,
saveTokens,
getTokens,
getRecommendations
};