-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrestore.js
More file actions
58 lines (55 loc) · 1.89 KB
/
Copy pathrestore.js
File metadata and controls
58 lines (55 loc) · 1.89 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
var MongoClient = require('mongodb').MongoClient
var config = require('./config')
var spotify = require('./spotify')
var auth = require('./auth')
function addSongs(api, user, playlistId, tracks) {
console.log('adding', tracks.length, 'tracks')
var offset = 0
function addChunk() {
var chunk = tracks.slice(offset, offset + 50)
.map(function(trackId) {
return 'spotify:track:' + trackId
})
return api.addTracksToPlaylist(user.id, playlistId, chunk)
.then(function() {
offset += 50
if (offset < tracks.length) {
return addChunk()
}
})
};
return addChunk()
}
function restore(id, user, name) {
console.log('restoring', id, 'as', name, 'for', user.displayName)
var api = spotify.userApi(user)
return MongoClient.connect(config.db_url)
.then(function(db) {
return db.collection('playlists').findOne({
id: id
})
}).then(function(snapshot) {
return api.refresh()
.then(function() {
return api.createPlaylist(user.id, name, {
'public': false
})
}).then(function(newPlaylist) {
console.log('added playlist', newPlaylist.body.id)
return addSongs(api, user, newPlaylist.body.id, snapshot.tracks)
})
})
}
module.exports.routes = function(router) {
router.get('/restore', auth.isAuthorized, function(req, res) {
var id = req.query.id
var name = req.query.name
return restore(id, req.user, name).then(function() {
console.log('Restored')
res.send(true)
}, function(err) {
console.log('Something went wrong!', err)
res.send(false)
})
})
}