-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
spotify.js
executable file
·357 lines (347 loc) · 11.8 KB
/
spotify.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
const request = require("request");
const fs = require("fs");
/*global Buffer:true*/
class spotify {
constructor(cid, secret, refresh_token, auth_url, rurl, log, config, api) {
this.log = log;
this.config = config;
this.api = api;
this.auth_url = auth_url;
this.rurl = rurl;
this.port = rurl.split("/callback")[0];
this.refresh_token = refresh_token;
this.cid = cid;
this.secret = secret;
if (refresh_token === undefined) {
this.log.error(
"You have not yet given homebridge-display access to your Spotify account. To do so go to: " +
this.auth_url +
"\nthen restart the server."
);
} else {
this.log.debug("Refreshing access token with refresh token '" + this.refresh_token + "'");
this.refresh();
}
}
refresh() {
let headers = {
Authorization: "Basic " + new Buffer(this.cid + ":" + this.secret).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded",
};
let dataString = "grant_type=refresh_token&refresh_token=" + this.refresh_token;
let options = {
url: "https://accounts.spotify.com/api/token",
method: "POST",
headers: headers,
body: dataString,
};
request(options, (err, res, body) => {
if (err) {
this.log.debug("[SPOTIFY] - " + err);
} else if (JSON.parse(body).error !== undefined) {
this.log.debug("[SPOTIFY] - " + JSON.parse(body).error);
} else {
this.access_token = JSON.parse(body).access_token;
this.log.debug("[SPOTIFY] - Access token generated: " + JSON.parse(body).access_token);
}
});
}
callback(code) {
let dataString = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + this.rurl;
let headers = {
Authorization: "Basic " + new Buffer(this.cid + ":" + this.secret).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded",
};
let options = {
url: "https://accounts.spotify.com/api/token",
method: "POST",
headers: headers,
body: dataString,
};
request(options, (err, res, body) => {
if (err) {
this.log.debug("[SPOTIFY] - " + err);
} else if (JSON.parse(body).error !== undefined) {
this.log.debug("[SPOTIFY] - " + JSON.parse(body).error);
} else {
this.access_token = JSON.parse(body).access_token;
this.refresh_token = JSON.parse(body).refresh_token;
let plugin_data = {};
let storage_path = this.api.user.storagePath() + "/homebridge-display.json";
try {
plugin_data = JSON.parse(fs.readFileSync(storage_path));
} catch (err) {
// the file just likely doesn't exist yet but we may need to catch this error so it doesn't override
}
plugin_data["refresh"] = this.refresh_token;
fs.writeFileSync(storage_path, JSON.stringify(plugin_data));
this.log.debug("[SPOTIFY] - Access token generated: " + this.access_token);
}
});
}
get(access_token, log, port, endpoint, call) {
let headers = {
Authorization: "Bearer " + access_token,
"User-Agent": "request",
"Content-Type": "application/json",
};
let options = {
url: "https://api.spotify.com/v1/me/player" + endpoint,
method: "GET",
headers: headers,
};
request(options, (err, res, body) => {
if (err !== null && err !== undefined) {
log.debug("[SPOTIFY] - " + err);
return call(null);
} else {
if (body !== undefined) {
let data;
try {
data = JSON.parse(body);
} catch {
return call(body);
}
if (data.error !== undefined) {
log.debug("[SPOTIFY] - " + data.error.message);
if (data.error.message === "The access token expired") {
refresh_token(port, log);
}
return call(null);
} else {
return call(data);
}
} else {
return call(null);
}
}
});
}
put(endpoint, json_body) {
let headers = {
Authorization: "Bearer " + this.access_token,
"Content-Type": "application/json",
};
let options = {
url: "https://api.spotify.com/v1/me/player" + endpoint,
method: "PUT",
headers: headers,
body: json_body,
};
request(options, (err, res, body) => {
if (err) {
this.log.debug("[SPOTIFY] - " + err);
} else {
try {
if (JSON.parse(body).error !== undefined) {
this.log.debug("[SPOTIFY] - " + JSON.parse(body).error.message);
}
} catch {}
}
});
}
post(endpoint) {
let headers = {
Authorization: "Bearer " + this.access_token,
};
let options = {
url: "https://api.spotify.com/v1/me/player" + endpoint,
method: "POST",
headers: headers,
};
request(options, (err, res, body) => {
if (err) {
this.log.debug("[SPOTIFY] - " + err);
} else {
try {
if (JSON.parse(body).error !== undefined) {
this.log.debug("[SPOTIFY] - " + JSON.parse(body).error.message);
}
} catch {}
}
});
}
like(song_id) {
let headers = {
Authorization: "Bearer " + this.access_token,
};
let options = {
url: "https://api.spotify.com/v1/me/tracks?ids=" + song_id,
method: "PUT",
headers: headers,
};
request(options, (err, res, body) => {
if (err) {
this.log.debug("[SPOTIFY] - " + err);
} else {
try {
if (JSON.parse(body).error !== undefined) {
this.log.debug("[SPOTIFY] - " + JSON.parse(body).error.message);
}
} catch {}
}
});
}
unlike(song_id) {
let headers = {
Authorization: "Bearer " + this.access_token,
};
let options = {
url: "https://api.spotify.com/v1/me/tracks?ids=" + song_id,
method: "DELETE",
headers: headers,
};
request(options, (err, res, body) => {
if (err) {
this.log.debug("[SPOTIFY] - " + err);
} else {
try {
if (JSON.parse(body).error !== undefined) {
this.log.debug("[SPOTIFY] - " + JSON.parse(body).error.message);
}
} catch {}
}
});
}
update(call) {
const log = this.log;
const get = this.get;
const refresh_token = this.refresh_token;
const access_token = this.access_token;
const port = this.port;
let canupdate = false;
try {
if (refresh_token) {
canupdate = true;
}
} catch (err) {
// keep canupdate to false as there is no refresh token
}
if (canupdate) {
get(access_token, log, port, "", function (result) {
let user_playback = result;
let update_json = {};
try {
update_json["is_playing"] = user_playback.is_playing;
} catch (err) {
update_json["is_playing"] = false;
}
if (update_json.is_playing) {
try {
update_json["device"] = user_playback["device"]["name"];
update_json["device_type"] = user_playback["device"]["type"];
update_json["device_id"] = user_playback["device"]["id"];
update_json["volume"] = user_playback["device"]["volume_percent"];
update_json["shuffle_state"] = user_playback["shuffle_state"];
update_json["repeat_state"] = user_playback["repeat_state"];
} catch (err) {
if (user_playback !== "API rate limit exceeded") {
try {
if (user_playback.currently_playing_type === "episode") {
// do nothing, we know that it is a podcast playing, which is not supported right now
} else {
log.debug("[SPOTIFY] - " + JSON.stringify(user_playback));
}
} catch {
log.debug("[SPOTIFY] - " + JSON.stringify(user_playback));
}
}
return call({ error: user_playback });
}
get(access_token, log, port, "/currently-playing", function (result) {
let currently_playing = result;
try {
update_json["progress_ms"] = currently_playing["progress_ms"];
update_json["img_url"] = currently_playing["item"]["album"]["images"][0]["url"];
let artist_names = [];
for (const artist of currently_playing["item"]["artists"]) {
artist_names.push(artist["name"]);
}
update_json["artists"] = artist_names.join(", ");
update_json["duration_ms"] = currently_playing["item"]["duration_ms"];
update_json["title"] = currently_playing["item"]["name"];
update_json["song_id"] = currently_playing["item"]["id"];
} catch (err) {
if (currently_playing !== "API rate limit exceeded") {
try {
if (currently_playing.currently_playing_type === "episode") {
// do nothing, we know that it is a podcast playing, which is not supported right now
} else {
log.debug("[SPOTIFY] - " + JSON.stringify(currently_playing));
}
} catch {
log.debug("[SPOTIFY] - " + JSON.stringify(currently_playing));
}
}
return call({ error: currently_playing });
}
try {
let headers = {
Authorization: "Bearer " + access_token,
};
let options = {
url: "https://api.spotify.com/v1/me/tracks/contains?ids=" + update_json.song_id,
method: "GET",
headers: headers,
};
request(options, (err, res, body) => {
request(options, (err, res, body) => {
if (err) {
log.debug("[SPOTIFY] - " + err);
} else {
try {
if (JSON.parse(body).error !== undefined) {
log.debug("[SPOTIFY] - " + JSON.parse(body).error.message);
} else {
update_json["liked"] = JSON.parse(body)[0];
get(access_token, log, port, "/devices", function (result) {
let devices = result;
update_json["avaliable_devices"] = {};
try {
for (const device of devices["devices"]) {
update_json["avaliable_devices"][device["name"]] = device["id"];
return call(update_json);
}
} catch (err) {
if (devices !== "API rate limit exceeded") {
log.debug("[SPOTIFY] - " + JSON.stringify(devices));
}
return call({
error: devices,
});
}
});
}
} catch (err) {
log.debug("[SPOTIFY] - " + err);
}
}
});
});
} catch (err) {
// ignore
}
});
} else {
return call(update_json);
}
});
} else {
return call({ error: "cannot update, check logs" });
}
}
}
function refresh_token(port, log) {
let options = {
url: port + "/refresh-spotify-token",
method: "GET",
};
request(options, (err, res, body) => {
if (err) {
log.debug("[SPOTIFY] - " + err);
} else {
log.debug("[SPOTIFY] - " + body);
}
});
}
module.exports = spotify;