-
Notifications
You must be signed in to change notification settings - Fork 1
/
spotifyPlaylist.js
162 lines (144 loc) · 5.8 KB
/
spotifyPlaylist.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
/**
* Created by chris on 06.01.16.
*/
"use strict";
var Promise = require('bluebird');
var https = require('https');
var fs = require('fs');
var spotifyHelper = require('./spotifyHelper');
var spotifyOAuth = require('./spotifyOAuth');
var logger = require('./logger');
var config = JSON.parse(fs.readFileSync('config.json', 'utf8'));
var spotifyPlaylist = {
addTracks: addTracks,
getTracks: getTracks,
getAllTracks: getAllTracks,
tracks: []
};
function getAllTracks(playlistName){
console.log('getting tracks from playlist '+playlistName);
return getTracks(playlistName, 0);
}
/**
* getTracks
* @param {String} playlistName like in config
* @param {int} offset - 0 for first page
* @returns {Promise}
*/
function getTracks(playlistName, offset){
return new Promise((resolve, reject) => {
let playlistId = config.playlists[playlistName].playlistId;
let LIMIT = 100;
let accessToken = spotifyOAuth.getAccessToken(),
playlistRequest;
if(accessToken === false || accessToken === ''){
return reject('no access token found');
}
playlistRequest = https.request({
hostname: 'api.spotify.com',
path: '/v1/users/'+config.userId+'/playlists/'+playlistId+'/tracks?fields=next,items.track.uri&limit='+LIMIT+'&offset='+offset,
method: 'GET',
headers: {
'Authorization': 'Bearer '+ accessToken,
'Accept': 'application/json'
}
}, function(res){
let data = '';
if(res.statusCode !== 200) {
spotifyHelper.checkForRateLimit(res, 'requesting playlist tracks', () => resolve(spotifyPlaylist.getTracks(playlistName, offset)))
.then(() => {
if(res.statusCode === 401){
spotifyOAuth.refresh()
.then(require('./main').start);
} else if(res.statusCode !== 429) {
var error = "Error getting tracks from playlist. Status "+res.statusCode;
logger.log(error, playlistName);
process.exit(1);
}
});
return;
}
res.on('data', function(chunk){
data += chunk;
});
res.on('end', function(){
var jsonData = JSON.parse(data);
jsonData.items.forEach(function(item){
spotifyPlaylist.tracks.push(item.track.uri);
});
if(jsonData.next === null){
resolve();
} else if(typeof jsonData.next === 'string'){
resolve(spotifyPlaylist.getTracks(playlistName, offset + LIMIT));
} else {
reject('error getting data from playlist request');
}
});
});
playlistRequest.end();
});
}
/**
* addTracks
* @param {String} playlistName
* @param {Array} results
*/
function addTracks(playlistName, results){
let playlistConfig = config.playlists[playlistName];
let accessToken = spotifyOAuth.getAccessToken(),
LIMIT = 40; // limit how many tracks will be added in one request
if(accessToken === false){
return;
}
if(results.length === 0){
logger.log('no new tracks to add', playlistName);
process.exit();
return;
}
var requests = results
// we can only add max 40 tracks at once. So we split all results in chunks of 40 tracks
.map((item, i) => (i % LIMIT === 0) ? results.slice(i, i + LIMIT) : null)
.filter(item => item && item.length)
.map((items, i) => makeAddRequest(items, i * 100));
return Promise.all(requests);
function makeAddRequest(items, timeout){
return new Promise((resolve, reject) => {
let tryCounter = 0; // count how often this was tried to prevent endless loop
setTimeout(sendRequest, timeout);
function sendRequest(){
if(tryCounter > 5){
return reject('request to add to playlist failed 5 times');
}
tryCounter += 1;
let addRequest = https.request({
hostname: 'api.spotify.com',
path: '/v1/users/' + config.userId + '/playlists/' + playlistConfig.playlistId + '/tracks?position=0&uris=' + items.join(), // join all 40 track ids for the query string
method: 'POST',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Accept': 'application/json'
}
}, function(res){
if (res.statusCode === 201) {
logger.log('Success! Added ' + items.length + ' tracks.', playlistName);
resolve();
} else {
spotifyHelper.checkForRateLimit(res, 'adding to playlist', () => resolve(spotifyPlaylist.addTracks(playlistName, results)))
.then(() =>{
if (res.statusCode === 401) {
spotifyOAuth.refresh()
.then(sendRequest) // try again
.catch(error => logger.log(error, playlistName));
} else {
logger.log("Error adding to playlist. Status " + res.statusCode, playlistName);
process.exit(1);
}
});
}
});
addRequest.end();
}
});
}
}
module.exports = spotifyPlaylist;