-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathconnect.js
534 lines (511 loc) · 20.8 KB
/
connect.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
const alexa = require('alexa-app');
const request = require('request-promise-native');
const express = require('express');
const nodecache = require('node-cache');
const i18n = require('i18n');
const rq = require('./request-helper');
const { findDeviceByNumber } = require('./device-helper');
// Create instance of express
var express_app = express();
// Create a 1 hour cache for storing user devices
var cache = new nodecache({ stdTTL: 3600, checkperiod: 120 });
// Create instance of alexa-app
var app = new alexa.app('connect');
// Bind alexa-app to express instance
app.express({ expressApp: express_app });
i18n.configure({
directory: __dirname + '/locales'
});
const successSound = "<audio src='soundbank://soundlibrary/ui/gameshow/amzn_ui_sfx_gameshow_neutral_response_02'/>";
const connectDeviceCard = {
type: "Simple",
title: i18n.__("Connecting to a device using Spotify Connect"),
content: i18n.__("To add a device to Spotify Connect,"
+ " log in to your Spotify account on a supported device"
+ " such as an Echo, phone, or computer"
+ "\nhttps://support.spotify.com/uk/article/spotify-connect/")
};
// Run every time the skill is accessed
app.pre = function (req, res, _type) {
const applicationId = require('./package.json').alexa.applicationId;
i18n.setLocale(req.data.request.locale || "en-GB");
// Error if the application ID of the request is not for this skill
if (req.applicationId != applicationId &&
req.getSession().details.application.applicationId != applicationId) {
throw "Invalid applicationId";
}
// Check that the user has an access token, if they have linked their account
if (!(req.context.System.user.accessToken || req.getSession().details.user.accessToken)) {
res.say(i18n.__("You have not linked your Spotify account, check your Alexa app to link the account"));
res.linkAccount();
}
};
// Run after every request
app.post = function (_req, res, _type, exception) {
if (exception) {
return res.clear().say(i18n.__("An error occured: ") + exception).send();
}
};
// Function for when skill is invoked without intent
app.launch(function (_req, res) {
res.say(i18n.__("I can control your Spotify Connect devices, to start, ask me to list your devices"))
.reprompt(i18n.__("To start, ask me to list your devices"));
// Keep session open
res.shouldEndSession(false);
});
// Handle default Amazon help intent
// No slots or utterances required
app.intent("AMAZON.HelpIntent", {
"slots": {},
"utterances": []
}, function (_req, res) {
res.say(i18n.__("You can ask me to list your connect devices and then control them. "))
.say(i18n.__("For example, tell me to play on a device number after listing devices"))
.reprompt(i18n.__("What would you like to do?"));
// Keep session open
res.shouldEndSession(false);
});
// Handle default Amazon stop intent
// No slots or utterances required
app.intent("AMAZON.StopIntent", {
"slots": {},
"utterances": []
}, function (_req, _res) {
return;
});
// Handle default Amazon cancel intent
// No slots or utterances required
app.intent("AMAZON.CancelIntent", {
"slots": {},
"utterances": []
}, function (_req, _res) {
return;
});
// Handle play intent
// No slots required
app.intent('PlayIntent', {
"utterances": [
"play",
"resume",
"continue"
]
},
function (req, res) {
// PUT to Spotify REST API
return rq.put("https://api.spotify.com/v1/me/player/play", req.getSession().details.user.accessToken)
.then((r) => {
req.getSession().set("statusCode", r.statusCode);
res.say(successSound);
}).catch((err) => {
if (err.statusCode === 403) res.say(i18n.__("Make sure your Spotify account is premium"));
if (err.statusCode === 404) {
res.say(i18n.__("I couldn't find any connect devices, check your Alexa app for information on connecting a device"));
res.card(connectDeviceCard);
}
});
}
);
// Handle pause intent
// No slots required
app.intent('PauseIntent', {
"utterances": [
"pause"
]
},
function (req, res) {
// PUT to Spotify REST API
return rq.put("https://api.spotify.com/v1/me/player/pause", req.getSession().details.user.accessToken)
.then((r) => {
req.getSession().set("statusCode", r.statusCode);
res.say(successSound);
}).catch((err) => {
if (err.statusCode === 403) res.say(i18n.__("Make sure your Spotify account is premium"));
if (err.statusCode === 404) {
res.say(i18n.__("I couldn't find any connect devices, check your Alexa app for information on connecting a device"));
res.card(connectDeviceCard);
}
});
}
);
// Handle skip next intent
// No slots required
app.intent('SkipNextIntent', {
"utterances": [
"skip",
"next",
"forwards"
]
},
function (req, res) {
// POST to Spotify REST API
return rq.post("https://api.spotify.com/v1/me/player/next", req.getSession().details.user.accessToken)
.then((r) => {
req.getSession().set("statusCode", r.statusCode);
res.say(successSound);
}).catch((err) => {
if (err.statusCode === 403) res.say(i18n.__("Make sure your Spotify account is premium"));
if (err.statusCode === 404) {
res.say(i18n.__("I couldn't find any connect devices, check your Alexa app for information on connecting a device"));
res.card(connectDeviceCard);
}
});
}
);
// Handle skip previous intent
// No slots required
app.intent('SkipPreviousIntent', {
"utterances": [
"previous",
"last",
"back",
"backwards"
]
},
function (req, res) {
// POST to Spotify REST API
return rq.post("https://api.spotify.com/v1/me/player/previous", req.getSession().details.user.accessToken)
.then((r) => {
req.getSession().set("statusCode", r.statusCode);
res.say(successSound);
}).catch((err) => {
if (err.statusCode === 403) res.say(i18n.__("Make sure your Spotify account is premium"));
if (err.statusCode === 404) {
res.say(i18n.__("I couldn't find any connect devices, check your Alexa app for information on connecting a device"));
res.card(connectDeviceCard);
}
});
}
);
// Handle volume level intent
// Slot for new volume
app.intent('VolumeLevelIntent', {
"slots": {
"VOLUMELEVEL": "AMAZON.NUMBER"
},
"utterances": [
"{set the|set|} volume {level|} {to|} {-|VOLUMELEVEL}"
]
},
function (req, res) {
// Check that request contains session
if (req.hasSession()) {
// Check that the slot has a value
if (req.slot("VOLUMELEVEL")) {
// Check if the slot is a number
if (!isNaN(req.slot("VOLUMELEVEL"))) {
var volumeLevel = req.slot("VOLUMELEVEL");
// Check that the volume is valid
if (volumeLevel >= 0 && volumeLevel <= 10) {
res.say(successSound);
// PUT to Spotify REST API
return request.put({
// Send new volume * 10 (convert to percentage)
url: "https://api.spotify.com/v1/me/player/volume?volume_percent=" + 10 * volumeLevel,
// Send access token as bearer auth
auth: {
"bearer": req.getSession().details.user.accessToken
},
// Handle sending as JSON
json: true
}).catch((err) => {
if (err.statusCode === 403) res.say(i18n.__("Make sure your Spotify account is premium"));
if (err.statusCode === 404) {
res.say(i18n.__("I couldn't find any connect devices, check your Alexa app for information on connecting a device"));
res.card(connectDeviceCard);
}
});
}
else {
// If not valid volume
res.say(i18n.__("You can only set the volume between 0 and 10"));
// Keep session open
res.shouldEndSession(false);
}
}
else {
// Not a number
res.say(i18n.__("Try setting a volume between 0 and 10"))
.reprompt(i18n.__("What would you like to do?"));
// Keep session open
res.shouldEndSession(false);
}
}
else {
// No slot value
res.say(i18n.__("I couldn't work out the volume to use."))
.say(i18n.__("Try setting a volume between 0 and 10"))
.reprompt(i18n.__("What would you like to do?"));
// Keep session open
res.shouldEndSession(false);
}
}
}
);
// Handle get devices intent
// No slots required
app.intent('GetDevicesIntent', {
"utterances": [
"devices",
"list",
"search",
"find"
]
},
function (req, res) {
// GET from Spotify REST API
return request.get({
url: "https://api.spotify.com/v1/me/player/devices",
// Send access token as bearer auth
auth: {
"bearer": req.getSession().details.user.accessToken
},
// Parse results as JSON
json: true
})
.then(function (body) {
var devices = body.devices || [];
var deviceNames = [];
for (var i = 0; i < devices.length; i++) {
// Number each device
deviceNames.push((i + 1) + ". " + devices[i].name);
// Add the device number to JSON
devices[i].number = (i + 1);
}
req.getSession().set("devices", devices);
cache.set(req.getSession().details.user.userId + ":devices", devices);
// Check if user has devices
if (devices.length > 0) {
// Comma separated list of device names
res.say(i18n.__("I found these connect devices: "))
.say([deviceNames.slice(0, -1).join(', '), deviceNames.slice(-1)[0]].join(deviceNames.length < 2 ? '' : ',' + i18n.__(' and ')) + ". ")
.say(i18n.__("What would you like to do with these devices?")).reprompt(i18n.__("What would you like to do?"));
// Keep session open
res.shouldEndSession(false);
}
else {
// No devices found
res.say(i18n.__("I couldn't find any connect devices, check your Alexa app for information on connecting a device"));
res.card(connectDeviceCard);
}
})
// Handle errors
.catch(function (err) {
req.getSession().set("statusCode", err.statusCode);
});
}
);
// Handle device play intent
// Slot for device number
app.intent('DevicePlayIntent', {
"slots": {
"DEVICENUMBER": "AMAZON.NUMBER"
},
"utterances": [
"play on {number|device|device number|} {-|DEVICENUMBER}"
]
},
function (req, res) {
// Check that request contains session
if (req.hasSession()) {
// Check that the slot has a value
if (req.slot("DEVICENUMBER")) {
// Check if the slot is a number
if (!isNaN(req.slot("DEVICENUMBER"))) {
var deviceNumber = req.slot("DEVICENUMBER");
var device = findDeviceByNumber(req, cache, deviceNumber);
// Check that the device for the number was found
if (device.id) {
// PUT to Spotify REST API
return request.put({
url: "https://api.spotify.com/v1/me/player",
// Send access token as bearer auth
auth: {
"bearer": req.getSession().details.user.accessToken
},
body: {
// Send device ID
"device_ids": [
device.id
],
// Make sure that music plays
"play": true
},
// Handle sending as JSON
json: true
}).then((_r) => {
res.say(i18n.__("Playing on device {{deviceNumber}}: {{deviceName}}", { deviceNumber, deviceName: device.name }));
}).catch((err) => {
if (err.statusCode === 403) res.say(i18n.__("Make sure your Spotify account is premium"));
if (err.statusCode === 404) {
res.say(i18n.__("I couldn't find any connect devices, check your Alexa app for information on connecting a device"));
res.card(connectDeviceCard);
}
});
}
else {
// If device for number not found
res.say(i18n.__("I couldn't find device {{deviceNumber}}. ", { deviceNumber }))
.say(i18n.__("Try asking me to list devices first"));
// Keep session open
res.shouldEndSession(false);
}
}
else {
// Not a number
res.say(i18n.__("I couldn't work out which device to play on, make sure you refer to the device by number."))
.say(i18n.__("Try asking me to play on a device number"))
.reprompt(i18n.__("What would you like to do?"));
// Keep session open
res.shouldEndSession(false);
}
}
else {
// No slot value
res.say(i18n.__("I couldn't work out which device number to play on."))
.say(i18n.__("Try asking me to play on a device number"))
.reprompt(i18n.__("What would you like to do?"));
// Keep session open
res.shouldEndSession(false);
}
}
}
);
// Handle device transfer intent
// Slot for device number
app.intent('DeviceTransferIntent', {
"slots": {
"DEVICENUMBER": "AMAZON.NUMBER"
},
"utterances": [
"transfer to {number|device|device number|} {-|DEVICENUMBER}"
]
},
function (req, res) {
// Check that request contains session
if (req.hasSession()) {
// Check that the slot has a value
if (req.slot("DEVICENUMBER")) {
// Check if the slot is a number
if (!isNaN(req.slot("DEVICENUMBER"))) {
var deviceNumber = req.slot("DEVICENUMBER");
var device = findDeviceByNumber(req, cache, deviceNumber);
// Check that the device for the number was found
if (device.id) {
// PUT to Spotify REST API
return request.put({
url: "https://api.spotify.com/v1/me/player",
// Send access token as bearer auth
auth: {
"bearer": req.getSession().details.user.accessToken
},
body: {
// Send device ID
"device_ids": [
device.id
]
},
// Handle sending as JSON
json: true
}).then((_r) => {
res.say(i18n.__("Transferring to device {{deviceNumber}}: {{deviceName}}", { deviceNumber, deviceName: device.name }));
}).catch((err) => {
if (err.statusCode === 403) res.say(i18n.__("Make sure your Spotify account is premium"));
if (err.statusCode === 404) {
res.say(i18n.__("I couldn't find any connect devices, check your Alexa app for information on connecting a device"));
res.card(connectDeviceCard);
}
});
}
else {
// If device for number not found
res.say(i18n.__("I couldn't find device {{deviceNumber}}. ", { deviceNumber }))
.say(i18n.__("Try asking me to list devices first"));
// Keep session open
res.shouldEndSession(false);
}
}
else {
// Not a number
res.say(i18n.__("I couldn't work out which device to transfer to, make sure you refer to the device by number."))
.say(i18n.__("Try asking me to transfer to a device number"))
.reprompt(i18n.__("What would you like to do?"));
// Keep session open
res.shouldEndSession(false);
}
}
else {
// No slot value
res.say(i18n.__("I couldn't work out which device number to transfer to."))
.say(i18n.__("Try asking me to transfer to a device number"))
.reprompt(i18n.__("What would you like to do?"));
// Keep session open
res.shouldEndSession(false);
}
}
}
);
// Handle get track intent
// No slots required
app.intent('GetTrackIntent', {
"utterances": [
"{what is|what's} {playing|this song}",
"what {song|track|} is this"
]
},
function (req, res) {
// GET from Spotify REST API
return request.get({
url: "https://api.spotify.com/v1/me/player/currently-playing",
// Send access token as bearer auth
auth: {
"bearer": req.getSession().details.user.accessToken
},
// Parse results as JSON
json: true
})
.then(function (body) {
if (body.is_playing) {
res.say(i18n.__("This is {{name}} by {{artist}}", { name: body.item.name, artist: body.item.artists[0].name }));
}
else {
if (body.item.name) {
// If not playing but last track known
res.say(i18n.__("That was {{name}} by {{artist}}", { name: body.item.name, artist: body.item.artists[0].name }));
}
else {
// If unknown
res.say(i18n.__("Nothing is playing"));
}
}
})
// Handle errors
.catch(function (err) {
req.getSession().set("statusCode", err.statusCode);
});
}
);
// Set up redirect to project page
express_app.use(express.static(__dirname));
/* istanbul ignore next */
express_app.get('/', function (_, res) {
res.redirect('https://github.com/thorpelawrence/alexa-spotify-connect');
});
/* istanbul ignore if */
// Only listen if run directly, not if required as a module
if (require.main === module) {
var port = process.env.PORT || 8888;
console.log("Listening on port " + port);
express_app.listen(port);
}
/* istanbul ignore next */
express_app.get('/skill', function (_, res) {
const skill = require('./skill/skill.js');
skill.forEach(locale => {
res.write(locale.name + '\n');
res.write(JSON.stringify(locale.data, null, 2) + '\n');
res.write('='.repeat(80) + '\n');
});
res.end();
});
// Export alexa-app instance for skill.js
module.exports = app;