-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
264 lines (243 loc) · 7.38 KB
/
index.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
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
require('dotenv').config()
const axios = require('axios').default
const bodyParser = require('body-parser')
const express = require('express')
const cors = require('cors')
const querystring = require('query-string')
const CLIENT_ID = process.env.CLIENT_ID
const CLIENT_SECRET = process.env.CLIENT_SECRET
const PORT = process.env.PORT || 5000
const REDIRECT_URI = process.env.REDIRECT_URI || `http://localhost:5500/docs/callback/index.html`
const SPOTIFY_ACCOUNT_API_PREFIX = 'https://accounts.spotify.com'
const SPOTIFY_API_PREFIX = 'https://api.spotify.com/v1'
const app = express()
app.use(cors())
app.use(bodyParser.urlencoded({ extended: true }))
function getAuthHeaders() {
const base64ClientSecrets = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')
return {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${base64ClientSecrets}`,
}
}
function getHeaders(data) {
return {
Authorization: `Bearer ${data.access_token}`
}
}
/**
* Returns the request authorization link.
*/
app.get('/', async (_req, res) => {
const queryObject = {
client_id: CLIENT_ID,
response_type: 'code',
scope: ['playlist-read-collaborative', 'playlist-modify-public', 'playlist-modify-private'],
redirect_uri: REDIRECT_URI,
}
const query = querystring.stringify(queryObject, { arrayFormat: 'comma' })
res.status(200).json({
url: `${SPOTIFY_ACCOUNT_API_PREFIX}/authorize?${query}`
})
})
/**
* Callback route for getting get the token.
*/
app.post('/auth/callback', async (req, res) => {
const { code } = req.body
const body = {
code,
grant_type: 'authorization_code',
redirect_uri: REDIRECT_URI,
}
try {
const response = await axios.post(`${SPOTIFY_ACCOUNT_API_PREFIX}/api/token`,
querystring.stringify(body),
{
headers: getAuthHeaders(),
})
const { data } = response
res.status(200).json({ ok: true, data })
} catch (error) {
console.log(error.message)
res.status(500).json({
error
})
}
})
/**
* Refresh user token when it becomes invalid.
*/
app.post('/auth/refresh', async (req, res) => {
const { refresh_token } = req.body
if (!refresh_token) {
return res.status(500).json({
error: 'refresh token required.'
})
}
const body = {
refresh_token,
redirect_uri: REDIRECT_URI,
grant_type: 'refresh_token',
}
try {
const response = await axios.post(`${SPOTIFY_ACCOUNT_API_PREFIX}/api/token`,
querystring.stringify(body),
{
headers: getAuthHeaders(),
})
data = response.data
res.status(200).json({ ok: true })
} catch (error) {
res.status(500).json({
error
})
}
})
/**
* Get all colaborative playlists of an user.
*
* @returns {object} all user's colaborative playlists.
*/
async function getUserCollaborativePlaylists(data) {
const headers = getHeaders(data)
const response = await axios.get(`${SPOTIFY_API_PREFIX}/me/playlists?limit=50`, {
headers
})
const userResponse = await axios.get(`${SPOTIFY_API_PREFIX}/me`, { headers })
const userId = userResponse.data.id
return response.data.items.filter(playlist => playlist.owner.id === userId)
}
/**
* Get one playlist's details, given its id.
*
* @param {string} playlistId the playlist id.
* @returns {object} the playlist details.
*/
async function getPlaylistDetails(playlistId, data) {
const { data: responseData } = await axios.get(`${SPOTIFY_API_PREFIX}/playlists/${playlistId}`, {
headers: getHeaders(data)
})
return {
id: responseData.id,
snapshotId: responseData.snapshot_id,
name: responseData.name,
tracks: responseData.tracks.items.map((track, index) => ({
user: track.added_by.id,
index,
details: {
id: track.track.id,
name: track.track.name,
uri: track.track.uri,
}
}))
}
}
/**
* Get the tracks grouped by user.
*
* @param {object} playlistDetails the playlist details.
* @returns {object} an object where the keys are the users ids and the values are the tracks added by one user.
*/
function getPlaylistTracksGroupedByUser(playlistDetails) {
return playlistDetails.tracks.reduce((cumulativeTracks, track) => {
const userTracks = cumulativeTracks[track.user] || []
return {
...cumulativeTracks,
[track.user]: [...userTracks, track]
}
}, {})
}
async function reorderColaborativePlaylist(playlistId, numberOfTracks, tracksGroupedByUser, data) {
const users = Object.keys(tracksGroupedByUser)
const headers = getHeaders(data)
for (let i = 0; i < (numberOfTracks / users.length); i++) {
for (let user of users) {
const userTracks = tracksGroupedByUser[user]
const [track] = userTracks
if (track) {
console.log(i, user, track.details.name)
const playlistDetails = await getPlaylistDetails(playlistId, data)
const { tracks } = playlistDetails
const findTrack = tracks.find(tr => tr.details.id === track.details.id)
const trackIndex = tracks.indexOf(findTrack)
const url = `${SPOTIFY_API_PREFIX}/playlists/${playlistId}/tracks`
await axios.put(url, {
range_start: trackIndex,
range_length: 1,
insert_before: numberOfTracks,
}, { headers }).catch((error) => {
if (error.response) {
console.log(error.response.data)
}
})
tracksGroupedByUser[user] = userTracks.slice(1, userTracks.length)
}
}
}
}
/**
* Route to get user colaborative playlists
*/
app.get('/playlists', async (req, res) => {
const { authorization } = req.headers
if (!authorization) {
return res.status(403).json({ error: 'No credentials sent' });
}
const [, access_token] = authorization.split(' ')
const data = { access_token }
try {
const collaborativePlaylists = await getUserCollaborativePlaylists(data)
res.status(200).json({
ok: true,
playlists: collaborativePlaylists,
})
} catch (error) {
res.status(500).json({
error: error.message
})
}
})
/**
* Reorder a collaborative playlist alternately by its contributors.
*/
app.post('/reorder', async (req, res) => {
const { authorization } = req.headers
if (!authorization) {
return res.status(403).json({ error: 'No credentials sent' });
}
const [, access_token] = authorization.split(' ')
const data = { access_token }
const { playlistName } = req.body
if (!data.access_token) {
return res.status(401).json({
error: 'you need to authorize first: request `GET /` will provide you a link for authentication'
})
}
if (!playlistName) {
return res.status(400).json({
error: 'playlistName is required on request body'
})
}
try {
const collaborativePlaylists = await getUserCollaborativePlaylists(data)
const playlist = collaborativePlaylists.find(
playlist => playlist.name.toUpperCase() === playlistName.toUpperCase()
)
const playlistDetails = await getPlaylistDetails(playlist.id, data)
const tracksGroupedByUser = getPlaylistTracksGroupedByUser(playlistDetails)
await reorderColaborativePlaylist(playlistDetails.id, playlistDetails.tracks.length, tracksGroupedByUser, data)
console.log("Reorder finished!")
res.status(200).json({
ok: true,
})
} catch (error) {
console.log(error)
res.status(500).json({
error: error.message
})
}
})
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`)
})