-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
98 lines (83 loc) · 2.49 KB
/
routes.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
const express = require('express');
const router = express.Router();
const config = require("./config")
const spotifyApi = require("./api")
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {title: 'Express'});
});
router.get('/login', function (req, res, next) {
const authorizeURL = spotifyApi.createAuthorizeURL(config.scopes, config.state);
res.redirect(authorizeURL)
});
router.get("/delete_playlists", async (req, res, next) => {
const errHandler = err => {
console.log('Something went wrong!', err);
res.json(err)
}
const userData = await spotifyApi.getMe()
const user = userData.body
const pListsToDelete = []
let offset = 0
const timer = setInterval(() => {
spotifyApi.getUserPlaylists(user.id, {
limit: 50,
offset: offset
}).then(resp => {
const {total, items} = resp.body
offset += 50
for (const itemsKey in items) {
if (items[itemsKey].tracks.total === 0) {
pListsToDelete.push({
id: items[itemsKey].id,
name: items[itemsKey].name,
tracks: items[itemsKey].tracks.total
})
}
}
if (offset > total) {
clearInterval(timer)
console.log("interval cleared")
if (pListsToDelete.length) {
deletePlaylists(pListsToDelete).then(() => {
res.json({
msg: "Success - Empty Playlists deleted"
})
})
}
res.json({
msg: "No empty playlists found - No deletions made"
})
}
}).catch(errHandler)
}, 350)
})
function deletePlaylists(pListsToDelete) {
return new Promise((resolve, reject) => {
const deletionTimer = setInterval(() => {
spotifyApi.unfollowPlaylist(pListsToDelete.pop().id).catch(console.log)
if (pListsToDelete.length === 0) {
clearInterval(deletionTimer)
resolve()
}
}, 350)
})
}
router.get('/callback', function (req, res, next) {
// your application requests refresh and access tokens
const code = req.query.code || null;
spotifyApi.authorizationCodeGrant(code)
.then(data => {
// Set the access token on the API object to use it in later calls
spotifyApi.setAccessToken(data.body['access_token']);
spotifyApi.setRefreshToken(data.body['refresh_token']);
},
err => {
console.log('Something went wrong!', err);
}
).then(() => {
res.redirect("/delete_playlists")
}
)
});
module.exports = router;