-
-
Notifications
You must be signed in to change notification settings - Fork 147
/
sonos.js
1197 lines (1137 loc) Β· 47.2 KB
/
sonos.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Constants
*/
var TRANSPORT_ENDPOINT = '/MediaRenderer/AVTransport/Control'
var RENDERING_ENDPOINT = '/MediaRenderer/RenderingControl/Control'
var DEVICE_ENDPOINT = '/DeviceProperties/Control'
/**
* Dependencies
*/
var util = require('util')
var EventEmitter = require('events').EventEmitter
var dgram = require('dgram')
var request = require('request')
var xml2js = require('xml2js')
var debug = require('debug')('sonos')
var _ = require('underscore')
var Buffer = require('safe-buffer').Buffer
/**
* Services
*/
var Services = {
AlarmClock: require('./services/AlarmClock'),
AudioIn: require('./services/AudioIn'),
AVTransport: require('./services/AVTransport'),
ContentDirectory: require('./services/ContentDirectory'),
DeviceProperties: require('./services/DeviceProperties'),
GroupManagement: require('./services/GroupManagement'),
GroupRenderingControl: require('./services/GroupRenderingControl'),
MusicServices: require('./services/MusicServices'),
RenderingControl: require('./services/RenderingControl'),
Service: require('./services/Service'),
SystemProperties: require('./services/SystemProperties'),
ZoneGroupTopology: require('./services/ZoneGroupTopology')
}
/**
* Listener
*/
var Listener = require('./events/listener')
/**
* Helpers
*/
/**
* Wrap in UPnP Envelope
* @param {String} body
* @return {String}
*/
var withinEnvelope = function (body) {
return ['<?xml version="1.0" encoding="utf-8"?>',
'<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">',
'<s:Body>' + body + '</s:Body>',
'</s:Envelope>'].join('')
}
/**
* Encodes characters not allowed within html/xml tags
* @param {String} str
* @return {String}
*/
var htmlEntities = function (str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
}
/**
* Creates object with uri and metadata from Spotify track uri
* @param {String} uri
* @return {Object} options {uri: Spotify uri, metadata: metadata}
*/
var optionsFromSpotifyUri = function (uri, title, region) {
var spotifyIds = uri.split(':')
if (Array.isArray(spotifyIds) && spotifyIds.length < 3) return uri
var spotifyUri = uri.replace(/:/g, '%3a')
var meta = '<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"><item id="##SPOTIFYURI##" restricted="true"><dc:title>##RESOURCETITLE##</dc:title><upnp:class>##SPOTIFYTYPE##</upnp:class><desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">SA_RINCON' + region + '_X_#Svc' + region + '-0-Token</desc></item></DIDL-Lite>'
if (uri.startsWith('spotify:track:')) {
return {
uri: spotifyUri,
metadata: meta.replace('##SPOTIFYURI##', '00032020' + spotifyUri).replace('##RESOURCETITLE##', '').replace('##SPOTIFYTYPE##', 'object.item.audioItem.musicTrack')
}
} else if (uri.startsWith('spotify:album:')) {
return {
uri: 'x-rincon-cpcontainer:0004206c' + spotifyUri,
metadata: meta.replace('##SPOTIFYURI##', '0004206c' + spotifyUri).replace('##RESOURCETITLE##', '').replace('##SPOTIFYTYPE##', 'object.container.album.musicAlbum')
}
} else if (uri.startsWith('spotify:artistTopTracks:')) {
return {
uri: 'x-rincon-cpcontainer:000e206c' + spotifyUri,
metadata: meta.replace('##SPOTIFYURI##', '000e206c' + spotifyUri).replace('##RESOURCETITLE##', '').replace('##SPOTIFYTYPE##', 'object.container.playlistContainer')
}
} else if (uri.startsWith('spotify:user:')) {
return {
uri: 'x-rincon-cpcontainer:0006206c' + spotifyUri,
metadata: meta.replace('##SPOTIFYURI##', '0006206c' + spotifyUri).replace('##RESOURCETITLE##', '').replace('##SPOTIFYTYPE##', 'object.container.playlistContainer')
}
} else if (uri.startsWith('spotify:artistRadio:')) {
var radioTitle = (title !== undefined) ? title : 'Artist Radio'
return {
uri: spotifyUri,
metadata: '<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"><item id="000c206c' + spotifyUri + '" restricted="true"><dc:title>' + radioTitle + '</dc:title><upnp:class>object.item.audioItem.audioBroadcast.#artistRadio</upnp:class><desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">SA_RINCON' + region + '_X_#Svc' + region + '-0-Token</desc></item></DIDL-Lite>'
}
} else {
return uri
}
}
var SpotifyRegion = {
EU: '2311',
US: '3079'
}
/**
* Sonos "Class"
* @param {String} host IP/DNS
* @param {Number} port
*/
var Sonos = function Sonos (host, port, options) {
this.host = host
this.port = port || 1400
this.options = options || {}
if (!this.options.endpoints) this.options.endpoints = {}
if (!this.options.endpoints.transport) this.options.endpoints.transport = TRANSPORT_ENDPOINT
if (!this.options.endpoints.rendering) this.options.endpoints.rendering = RENDERING_ENDPOINT
if (!this.options.endpoints.device) this.options.endpoints.device = DEVICE_ENDPOINT
this.options.spotify = this.options.spotify || {}
this.options.spotify.region = this.options.spotify.region || SpotifyRegion.US
}
/**
* UPnP HTTP Request
* @param {String} endpoint HTTP Path
* @param {String} action UPnP Call/Function/Action
* @param {String} body
* @param {String} responseTag Expected Response Container XML Tag
* @param {Function} callback (err, data)
*/
Sonos.prototype.request = function (endpoint, action, body, responseTag, callback) {
debug('Sonos.request(%j, %j, %j, %j, %j)', endpoint, action, body, responseTag, callback)
request({
uri: 'http://' + this.host + ':' + this.port + endpoint,
method: 'POST',
headers: {
'SOAPAction': action,
'Content-type': 'text/xml; charset=utf8'
},
body: withinEnvelope(body)
}, function (err, res, body) {
if (err) return callback(err)
if (res.statusCode !== 200) {
return callback(new Error('HTTP response code ' + res.statusCode + ' for ' + action))
}
(new xml2js.Parser()).parseString(body, function (err, json) {
if (err) return callback(err)
if ((!json) || (!json['s:Envelope']) || (!Array.isArray(json['s:Envelope']['s:Body']))) {
return callback(new Error('Invalid response for ' + action + ': ' + JSON.stringify(json)))
}
if (typeof json['s:Envelope']['s:Body'][0]['s:Fault'] !== 'undefined') {
return callback(json['s:Envelope']['s:Body'][0]['s:Fault'])
}
return callback(null, json['s:Envelope']['s:Body'][0][responseTag])
})
})
}
/**
* Get Music Library Information
* @param {String} searchType Choice - artists, albumArtists, albums, genres, composers, tracks, playlists, share
* @param {Object} options Optional - default {start: 0, total: 100}
* @param {Function} callback (err, result) result - {returned: {String}, total: {String}, items:[{title:{String}, uri: {String}}]}
*/
Sonos.prototype.getMusicLibrary = function (searchType, options, callback) {
this.searchMusicLibrary(searchType, null, options, callback)
}
/**
* Get Music Library Information
* @param {String} searchType Choice - artists, albumArtists, albums, genres, composers, tracks, playlists, share
* @param {String} searchTerm Optional - search term to search for
* @param {Object} options Optional - default {start: 0, total: 100}
* @param {Function} callback (err, result) result - {returned: {String}, total: {String}, items:[{title:{String}, uri: {String}}]}
*/
Sonos.prototype.searchMusicLibrary = function (searchType, searchTerm, options, callback) {
var self = this
var searches = {
'artists': 'A:ARTIST',
'albumArtists': 'A:ALBUMARTIST',
'albums': 'A:ALBUM',
'genres': 'A:GENRE',
'composers': 'A:COMPOSER',
'tracks': 'A:TRACKS',
'playlists': 'A:PLAYLISTS',
'sonos_playlists': 'SQ:',
'share': 'S:'
}
var defaultOptions = {
BrowseFlag: 'BrowseDirectChildren',
Filter: '*',
StartingIndex: '0',
RequestedCount: '100',
SortCriteria: ''
}
searches = searches[searchType]
var opensearch = (!searchTerm) || (searchTerm === '')
if (!opensearch) searches = searches.concat(':' + searchTerm)
var opts = {
ObjectID: searches
}
if (options.start !== undefined) opts.StartingIndex = options.start
if (options.total !== undefined) opts.RequestedCount = options.total
opts = _.extend(defaultOptions, opts)
var contentDirectory = new Services.ContentDirectory(this.host, this.port)
return contentDirectory.Browse(opts, function (err, data) {
if (err) return callback(err)
return (new xml2js.Parser()).parseString(data.Result, function (err, didl) {
if (err) return callback(err, data)
var items = []
if ((!didl) || (!didl['DIDL-Lite'])) {
return callback(new Error('Cannot parse DIDTL result'), data)
}
var resultcontainer = opensearch ? didl['DIDL-Lite'].container : didl['DIDL-Lite'].item
if (!Array.isArray(resultcontainer)) {
return callback(new Error('Cannot parse DIDTL result'), data)
}
_.each(resultcontainer, function (item) {
var albumArtURL = null
if (Array.isArray(item['upnp:albumArtURI'])) {
if (item['upnp:albumArtURI'][0].indexOf('http') !== -1) {
albumArtURL = item['upnp:albumArtURI'][0]
} else {
albumArtURL = 'http://' + self.host + ':' + self.port + item['upnp:albumArtURI'][0]
}
}
items.push({
'title': Array.isArray(item['dc:title']) ? item['dc:title'][0] : null,
'artist': Array.isArray(item['dc:creator']) ? item['dc:creator'][0] : null,
'albumArtURL': albumArtURL,
'album': Array.isArray(item['upnp:album']) ? item['upnp:album'][0] : null,
'uri': Array.isArray(item.res) ? item.res[0]._ : null
})
})
var result = {
returned: data.NumberReturned,
total: data.TotalMatches,
items: items
}
return callback(null, result)
})
})
}
/**
* Get Current Track
* @param {Function} callback (err, track)
*/
Sonos.prototype.currentTrack = function (callback) {
debug('Sonos.currentTrack(' + ((callback) ? 'callback' : '') + ')')
var self = this
var action = '"urn:schemas-upnp-org:service:AVTransport:1#GetPositionInfo"'
var body = '<u:GetPositionInfo xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><Channel>Master</Channel></u:GetPositionInfo>'
var responseTag = 'u:GetPositionInfoResponse'
return this.request(this.options.endpoints.transport, action, body, responseTag, function (err, data) {
if (err) return callback(err)
if ((!Array.isArray(data)) || (data.length < 1)) return {}
var metadata = data[0].TrackMetaData
var position = (parseInt(data[0].RelTime[0].split(':')[0], 10) * 60 * 60) +
(parseInt(data[0].RelTime[0].split(':')[1], 10) * 60) +
parseInt(data[0].RelTime[0].split(':')[2], 10)
var duration = (parseInt(data[0].TrackDuration[0].split(':')[0], 10) * 60 * 60) +
(parseInt(data[0].TrackDuration[0].split(':')[1], 10) * 60) +
parseInt(data[0].TrackDuration[0].split(':')[2], 10)
var trackUri = data[0].TrackURI ? data[0].TrackURI[0] : null
if ((metadata) && (metadata[0].length > 0) && metadata[0] !== 'NOT_IMPLEMENTED') {
return (new xml2js.Parser()).parseString(metadata, function (err, data) {
if (err) {
return callback(err, data)
}
var track = self.parseDIDL(data)
track.position = position
track.duration = duration
track.albumArtURL = !track.albumArtURI ? null
: track.albumArtURI.startsWith('http') ? track.albumArtURI
: 'http://' + self.host + ':' + self.port + track.albumArtURI
if (trackUri) track.uri = trackUri
return callback(null, track)
})
} else {
var track = { position: position, duration: duration }
if (data[0].TrackURI) track.uri = data[0].TrackURI[0]
return callback(null, track)
}
})
}
/**
* Parse DIDL into track structure
* @param {String} didl
* @return {object}
*/
Sonos.prototype.parseDIDL = function (didl) {
if ((!didl) || (!didl['DIDL-Lite']) || (!Array.isArray(didl['DIDL-Lite'].item)) || (!didl['DIDL-Lite'].item[0])) return {}
var item = didl['DIDL-Lite'].item[0]
return {
title: Array.isArray(item['dc:title']) ? item['dc:title'][0] : null,
artist: Array.isArray(item['dc:creator']) ? item['dc:creator'][0] : null,
album: Array.isArray(item['upnp:album']) ? item['upnp:album'][0] : null,
albumArtURI: Array.isArray(item['upnp:albumArtURI']) ? item['upnp:albumArtURI'][0] : null
}
}
/**
* Get Current Volume
* @param {Function} callback (err, volume)
*/
Sonos.prototype.getVolume = function (callback) {
debug('Sonos.getVolume(' + ((callback) ? 'callback' : '') + ')')
var action = '"urn:schemas-upnp-org:service:RenderingControl:1#GetVolume"'
var body = '<u:GetVolume xmlns:u="urn:schemas-upnp-org:service:RenderingControl:1"><InstanceID>0</InstanceID><Channel>Master</Channel></u:GetVolume>'
var responseTag = 'u:GetVolumeResponse'
return this.request(this.options.endpoints.rendering, action, body, responseTag, function (err, data) {
if (err) return callback(err)
callback(null, parseInt(data[0].CurrentVolume[0], 10))
})
}
/**
* Get Current Muted
* @param {Function} callback (err, muted)
*/
Sonos.prototype.getMuted = function (callback) {
debug('Sonos.getMuted(' + ((callback) ? 'callback' : '') + ')')
var action = '"urn:schemas-upnp-org:service:RenderingControl:1#GetMute"'
var body = '<u:GetMute xmlns:u="urn:schemas-upnp-org:service:RenderingControl:1"><InstanceID>0</InstanceID><Channel>Master</Channel></u:GetMute>'
var responseTag = 'u:GetMuteResponse'
return this.request(this.options.endpoints.rendering, action, body, responseTag, function (err, data) {
if (err) return callback(err)
callback(null, !!parseInt(data[0].CurrentMute[0], 10))
})
}
/**
* Resumes Queue or Plays Provided URI
* @param {String|Object} uri Optional - URI to a Audio Stream or Object with play options
* @param {Function} callback (err, playing)
*/
Sonos.prototype.play = function (uri, callback) {
debug('Sonos.play(%j, %j)', uri, callback)
var action
var body
var self = this
var cb = (typeof uri === 'function' ? uri : callback) || function () {}
if (typeof uri === 'string') uri = optionsFromSpotifyUri(uri, undefined, this.options.spotify.region)
var options = (typeof uri === 'object' ? uri : {})
if (typeof uri === 'object') {
options.uri = uri.uri
options.metadata = uri.metadata
} else {
options.uri = (typeof uri === 'string' ? uri : undefined)
}
if (options.uri) {
return this.queue({
uri: options.uri,
metadata: options.metadata
}, function (err, queueResult) {
if (err || !queueResult || queueResult.length < 0 || !queueResult[0].FirstTrackNumberEnqueued) {
return cb(err)
}
var selectTrackNum = queueResult[0].FirstTrackNumberEnqueued[0]
self.selectTrack(selectTrackNum, function (err) {
if (err) return cb(err)
return self.play(cb)
})
})
} else {
action = '"urn:schemas-upnp-org:service:AVTransport:1#Play"'
body = '<u:Play xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><Speed>1</Speed></u:Play>'
return this.request(this.options.endpoints.transport, action, body, 'u:PlayResponse', function (err, data) {
if (err) return cb(err)
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return cb(null, true)
} else {
return cb(new Error({
err: err,
data: data
}), false)
}
})
}
}
/**
* Stop What's Playing
* @param {Function} callback (err, stopped)
*/
Sonos.prototype.stop = function (callback) {
debug('Sonos.stop(%j)', callback)
var action, body
action = '"urn:schemas-upnp-org:service:AVTransport:1#Stop"'
body = '<u:Stop xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><Speed>1</Speed></u:Stop>'
return this.request(this.options.endpoints.transport, action, body, 'u:StopResponse', function (err, data) {
if (err) return callback(err)
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return callback(null, true)
} else {
return callback(new Error({
err: err,
data: data
}), false)
}
})
}
/**
* Become Coordinator of Standalone Group
* @param {Function} callback (err, stopped)
*/
Sonos.prototype.becomeCoordinatorOfStandaloneGroup = function (callback) {
debug('Sonos.becomeCoordinatorOfStandaloneGroup(%j)', callback)
var action, body
action = '"urn:schemas-upnp-org:service:AVTransport:1#BecomeCoordinatorOfStandaloneGroup"'
body = '<u:BecomeCoordinatorOfStandaloneGroup xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID></u:BecomeCoordinatorOfStandaloneGroup>'
return this.request(this.options.endpoints.transport, action, body, 'u:BecomeCoordinatorOfStandaloneGroupResponse', function (err, data) {
if (err) return callback(err)
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return callback(null, true)
} else {
return callback(new Error({
err: err,
data: data
}), false)
}
})
}
/**
* Pause Current Queue
* @param {Function} callback (err, paused)
*/
Sonos.prototype.pause = function (callback) {
debug('Sonos.pause(%j)', callback)
var action, body
action = '"urn:schemas-upnp-org:service:AVTransport:1#Pause"'
body = '<u:Pause xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><Speed>1</Speed></u:Pause>'
return this.request(this.options.endpoints.transport, action, body, 'u:PauseResponse', function (err, data) {
if (err) return callback(err)
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return callback(null, true)
} else {
return callback(new Error({
err: err,
data: data
}), false)
}
})
}
/**
* Seek the current track
* @param {Function} callback (err, seeked)
*/
Sonos.prototype.seek = function (seconds, callback) {
debug('Sonos.seek(%j)', callback)
var action, body, hh, mm, ss
hh = Math.floor(seconds / 3600)
mm = Math.floor((seconds - (hh * 3600)) / 60)
ss = seconds - ((hh * 3600) + (mm * 60))
if (hh < 10) hh = '0' + hh
if (mm < 10) mm = '0' + mm
if (ss < 10) ss = '0' + ss
action = '"urn:schemas-upnp-org:service:AVTransport:1#Seek"'
body = '<u:Seek xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><Unit>REL_TIME</Unit><Target>' + hh + ':' + mm + ':' + ss + '</Target></u:Seek>'
return this.request(this.options.endpoints.transport, action, body, 'u:SeekResponse', function (err, data) {
if (err) return callback(err)
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return callback(null, true)
} else {
return callback(new Error({
err: err,
data: data
}), false)
}
})
}
/**
* Select specific track in queue
* @param {Number} trackNr Number of track in queue (optional, indexed from 1)
* @param {Function} callback (err, data)
*/
Sonos.prototype.selectTrack = function (trackNr, callback) {
if (typeof trackNr === 'function') {
callback = trackNr
trackNr = 1
}
var action = '"urn:schemas-upnp-org:service:AVTransport:1#Seek"'
var body = '<u:Seek xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><Unit>TRACK_NR</Unit><Target>' + trackNr + '</Target></u:Seek>'
return this.request(this.options.endpoints.transport, action, body, 'u:SeekResponse', function (err, data) {
if (err) return callback(err)
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return callback(null, true)
} else {
return callback(new Error({
err: err,
data: data
}), false)
}
})
}
/**
* Play next in queue
* @param {Function} callback (err, movedToNext)
*/
Sonos.prototype.next = function (callback) {
debug('Sonos.next(%j)', callback)
var action, body
action = '"urn:schemas-upnp-org:service:AVTransport:1#Next"'
body = '<u:Next xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><Speed>1</Speed></u:Next>'
this.request(this.options.endpoints.transport, action, body, 'u:NextResponse', function (err, data) {
if (err) {
return callback(err)
}
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return callback(null, true)
} else {
return callback(new Error({
err: err,
data: data
}), false)
}
})
}
/**
* Play previous in queue
* @param {Function} callback (err, movedToPrevious)
*/
Sonos.prototype.previous = function (callback) {
debug('Sonos.previous(%j)', callback)
var action, body
action = '"urn:schemas-upnp-org:service:AVTransport:1#Previous"'
body = '<u:Previous xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><Speed>1</Speed></u:Previous>'
this.request(this.options.endpoints.transport, action, body, 'u:PreviousResponse', function (err, data) {
if (err) {
return callback(err)
}
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return callback(null, true)
} else {
return callback(new Error({
err: err,
data: data
}), false)
}
})
}
/**
* Select Queue. Mostly required after turning on the speakers otherwise play, setPlaymode and other commands will fail.
* @param {Function} callback (err, data) Optional
*/
Sonos.prototype.selectQueue = function (callback) {
debug('Sonos.selectQueue(%j)', callback)
var cb = callback || function () {}
var self = this
self.getZoneInfo(function (err, data) {
if (!err) {
var action = '"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI"'
var body = '<u:SetAVTransportURI xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><CurrentURI>' + 'x-rincon-queue:RINCON_' + data.MACAddress.replace(/:/g, '') + '0' + self.port + '#0</CurrentURI><CurrentURIMetaData></CurrentURIMetaData></u:SetAVTransportURI>'
self.request(self.options.endpoints.transport, action, body, 'u:SetAVTransportURIResponse', function (err, data) {
if (err) return cb(err)
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return cb(null, true)
} else {
return cb(new Error({
err: err,
data: data
}), false)
}
})
} else {
return cb(err)
}
})
}
/**
* Plays tunein based on radio station id
* @param {String} stationId tunein radio station id
* @param {Function} callback (err, playing)
*/
Sonos.prototype.playTuneinRadio = function (stationId, stationTitle, callback) {
debug('Sonos.playTuneinRadio(%j, %j, %j)', stationId, stationTitle, callback)
var self = this
if (!stationId || !stationTitle) {
return callback(new Error('stationId and stationTitle are required'))
}
var metadata = '<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"><item id="F00092020s##TUNEINSTATIONID##" parentID="L" restricted="true"><dc:title>##TUNEINSTATIONTITLE##</dc:title><upnp:class>object.item.audioItem.audioBroadcast</upnp:class><desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">SA_RINCON65031_</desc></item></DIDL-Lite>'
metadata = metadata.replace('##TUNEINSTATIONID##', stationId).replace('##TUNEINSTATIONTITLE##', stationTitle)
var action = '"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI"'
var body = '<u:SetAVTransportURI xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><CurrentURI>x-sonosapi-stream:s' + stationId + '?sid=254&flags=8224&sn=0</CurrentURI><CurrentURIMetaData>' + htmlEntities(metadata) + '</CurrentURIMetaData></u:SetAVTransportURI>'
return this.request(this.options.endpoints.transport, action, body, 'u:SetAVTransportURIResponse', function (err, data) {
if (err) return callback(err)
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return self.play(callback)
} else {
return callback(new Error({
err: err,
data: data
}), false)
}
})
}
/**
* Add a song from spotify to the queue
* @param {String} trackId The spotify track ID
* @param {Function} callback (err, success)
*/
Sonos.prototype.addSpotify = function (trackId, callback) {
var uri = 'x-sonos-spotify:spotify%3atrack%3a' + trackId
var meta = '<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"><item id="00032020spotify%3atrack%3a' + trackId + '" restricted="true"><dc:title></dc:title><upnp:class>object.item.audioItem.musicTrack</upnp:class><desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">SA_RINCON' + this.options.spotify.region + '_X_#Svc' + this.options.spotify.region + '-0-Token</desc></item></DIDL-Lite>'
this.queue({
uri: uri,
metadata: meta
}, callback)
}
/**
* Plays Spotify radio based on artist uri
* @param {String} artistId Spotify artist id
* @param {Function} callback (err, playing)
*/
Sonos.prototype.playSpotifyRadio = function (artistId, artistName, callback) {
debug('Sonos.playSpotifyRadio(%j, %j, %j)', artistId, artistName, callback)
var self = this
if (!artistId || !artistName) {
return callback(new Error('artistId and artistName are required'))
}
var options = optionsFromSpotifyUri('spotify:artistRadio:' + artistId, artistName, this.options.spotify.region)
var action = '"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI"'
var body = '<u:SetAVTransportURI xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><CurrentURI>x-sonosapi-radio:' + options.uri + '?sid=12&flags=8300&sn=1</CurrentURI><CurrentURIMetaData>' + htmlEntities(options.metadata) + '</CurrentURIMetaData></u:SetAVTransportURI>'
return this.request(this.options.endpoints.transport, action, body, 'u:SetAVTransportURIResponse', function (err, data) {
if (err) return callback(err)
if (data[0].$['xmlns:u'] === 'urn:schemas-upnp-org:service:AVTransport:1') {
return self.play(callback)
} else {
return callback(new Error({
err: err,
data: data
}), false)
}
})
}
/**
* Queue a Song Next
* @param {String|Object} uri URI to Audio Stream or Object containing options (uri, metadata)
* @param {Function} callback (err, queued)
*/
Sonos.prototype.queueNext = function (uri, callback) {
debug('Sonos.queueNext(%j, %j)', uri, callback)
var options = (typeof uri === 'object' ? uri : { metadata: '' })
if (typeof uri === 'object') {
options.metadata = uri.metadata || ''
options.metadata = htmlEntities(options.metadata)
options.uri = uri.uri
} else {
options.uri = uri
}
var action = '"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI"'
var body = '<u:SetAVTransportURI xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><CurrentURI>' + options.uri + '</CurrentURI><CurrentURIMetaData>' + options.metadata + '</CurrentURIMetaData></u:SetAVTransportURI>'
this.request(this.options.endpoints.transport, action, body, 'u:SetAVTransportURIResponse', function (err, data) {
if (callback) {
return callback(err, data)
} else {
return null
}
})
}
/**
* Add a song to the queue.
* @param {String} uri URI to Audio Stream
* @param {Number} positionInQueue Position in queue at which to add song (optional, indexed from 1,
* defaults to end of queue, 0 to explicitly set end of queue)
* @param {Function} callback (err, queued)
*/
Sonos.prototype.queue = function (uri, positionInQueue, callback) {
debug('Sonos.queue(%j, %j, %j)', uri, positionInQueue, callback)
if (typeof positionInQueue === 'function') {
callback = positionInQueue
positionInQueue = 0
}
if (typeof uri === 'string') uri = optionsFromSpotifyUri(uri, undefined, this.options.spotify.region)
var options = (typeof uri === 'object' ? uri : { metadata: '' })
if (typeof uri === 'object') {
options.metadata = uri.metadata || ''
options.metadata = htmlEntities(options.metadata)
options.uri = uri.uri
} else {
options.uri = uri
}
var action = '"urn:schemas-upnp-org:service:AVTransport:1#AddURIToQueue"'
var body = '<u:AddURIToQueue xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><EnqueuedURI>' + options.uri + '</EnqueuedURI><EnqueuedURIMetaData>' + options.metadata + '</EnqueuedURIMetaData><DesiredFirstTrackNumberEnqueued>' + positionInQueue + '</DesiredFirstTrackNumberEnqueued><EnqueueAsNext>1</EnqueueAsNext></u:AddURIToQueue>'
this.request(this.options.endpoints.transport, action, body, 'u:AddURIToQueueResponse', function (err, data) {
return callback(err, data)
})
}
/**
* Flush queue
* @param {Function} callback (err, flushed)
*/
Sonos.prototype.flush = function (callback) {
debug('Sonos.flush(%j)', callback)
var action, body
action = '"urn:schemas-upnp-org:service:AVTransport:1#RemoveAllTracksFromQueue"'
body = '<u:RemoveAllTracksFromQueue xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID></u:RemoveAllTracksFromQueue>'
this.request(this.options.endpoints.transport, action, body, 'u:RemoveAllTracksFromQueueResponse', function (err, data) {
return callback(err, data)
})
}
/**
* Get the LED State
* @param {Function} callback (err, state) state is a string, "On" or "Off"
*/
Sonos.prototype.getLEDState = function (callback) {
debug('Sonos.getLEDState(%j)', callback)
var action = '"urn:schemas-upnp-org:service:DeviceProperties:1#GetLEDState"'
var body = '<u:GetLEDState xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"></u:GetLEDState>'
this.request(this.options.endpoints.device, action, body, 'u:GetLEDStateResponse', function (err, data) {
if (err) return callback(err, data)
if (data[0] && data[0].CurrentLEDState && data[0].CurrentLEDState[0]) {
return callback(null, data[0].CurrentLEDState[0])
}
callback(new Error('unknown response'))
})
}
/**
* Set the LED State
* @param {String} desiredState "On"/"Off"
* @param {Function} callback (err)
*/
Sonos.prototype.setLEDState = function (desiredState, callback) {
debug('Sonos.setLEDState(%j, %j)', desiredState, callback)
var action = '"urn:schemas-upnp-org:service:DeviceProperties:1#SetLEDState"'
var body = '<u:SetLEDState xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"><DesiredLEDState>' + desiredState + '</DesiredLEDState></u:SetLEDState>'
this.request(this.options.endpoints.device, action, body, 'u:SetLEDStateResponse', function (err) {
return callback(err)
})
}
/**
* Get Zone Info
* @param {Function} callback (err, info)
*/
Sonos.prototype.getZoneInfo = function (callback) {
debug('Sonos.getZoneInfo(%j)', callback)
var action = '"urn:schemas-upnp-org:service:DeviceProperties:1#GetZoneInfo"'
var body = '<u:GetZoneInfo xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"></u:GetZoneInfo>'
this.request(this.options.endpoints.device, action, body, 'u:GetZoneInfoResponse', function (err, data) {
if (err) return callback(err, data)
var output = {}
for (var d in data[0]) if (data[0].hasOwnProperty(d) && d !== '$') output[d] = data[0][d][0]
callback(null, output)
})
}
/**
* Get Zone Attributes
* @param {Function} callback (err, data)
*/
Sonos.prototype.getZoneAttrs = function (callback) {
debug('Sonos.getZoneAttrs(%j, %j)', callback)
var action = '"urn:schemas-upnp-org:service:DeviceProperties:1#GetZoneAttributes"'
var body = '"<u:GetZoneAttributes xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"></u:GetZoneAttributes>"'
this.request(this.options.endpoints.device, action, body, 'u:GetZoneAttributesResponse', function (err, data) {
if (err) return callback(err, data)
var output = {}
for (var d in data[0]) if (data[0].hasOwnProperty(d) && d !== '$') output[d] = data[0][d][0]
callback(null, output)
})
}
/**
* Get Information provided by /xml/device_description.xml
* @param {Function} callback (err, info)
*/
Sonos.prototype.deviceDescription = function (callback) {
request({
uri: 'http://' + this.host + ':' + this.port + '/xml/device_description.xml'
}, function (err, res, body) {
if (err) return callback(err)
if (res.statusCode !== 200) {
return callback(new Error('non 200 errorCode'))
}
(new xml2js.Parser()).parseString(body, function (err, json) {
if (err) return callback(err)
var output = {}
for (var d in json.root.device[0]) if (json.root.device[0].hasOwnProperty(d)) output[d] = json.root.device[0][d][0]
callback(null, output)
})
})
}
/**
* Set Name
* @param {String} name
* @param {Function} callback (err, data)
*/
Sonos.prototype.setName = function (name, callback) {
debug('Sonos.setName(%j, %j)', name, callback)
name = name.replace(/[<&]/g, function (str) { return (str === '&') ? '&' : '<' })
var action = '"urn:schemas-upnp-org:service:DeviceProperties:1#SetZoneAttributes"'
var body = '"<u:SetZoneAttributes xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"><DesiredZoneName>' + name + '</DesiredZoneName><DesiredIcon /><DesiredConfiguration /></u:SetZoneAttributes>"'
this.request(this.options.endpoints.device, action, body, 'u:SetZoneAttributesResponse', function (err, data) {
return callback(err, data)
})
}
/**
* Set Play Mode
* @param {String} playmode
* @param {Function} callback (err, data)
* @return {[type]}
*/
Sonos.prototype.setPlayMode = function (playmode, callback) {
debug('Sonos.setPlayMode(%j, %j)', playmode, callback)
var mode = { NORMAL: true, REPEAT_ALL: true, SHUFFLE: true, SHUFFLE_NOREPEAT: true }[playmode.toUpperCase()]
if (!mode) return callback(new Error('invalid play mode ' + playmode))
var action = '"urn:schemas-upnp-org:service:AVTransport:1#SetPlayMode"'
var body = '<u:SetPlayMode xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><NewPlayMode>' + playmode.toUpperCase() + '</NewPlayMode></u:SetPlayMode>'
this.request(this.options.endpoints.transport, action, body, 'u:SetPlayModeResponse', function (err, data) {
return callback(err, data)
})
}
/**
* Set Volume
* @param {String} volume 0..100
* @param {Function} callback (err, data)
* @return {[type]}
*/
Sonos.prototype.setVolume = function (volume, callback) {
debug('Sonos.setVolume(%j, %j)', volume, callback)
var action = '"urn:schemas-upnp-org:service:RenderingControl:1#SetVolume"'
var body = '<u:SetVolume xmlns:u="urn:schemas-upnp-org:service:RenderingControl:1"><InstanceID>0</InstanceID><Channel>Master</Channel><DesiredVolume>' + volume + '</DesiredVolume></u:SetVolume>'
this.request(this.options.endpoints.rendering, action, body, 'u:SetVolumeResponse', function (err, data) {
return callback(err, data)
})
}
/**
* Configure Sleep Timer
* @param {String} sleepTimerDuration
* @param {Function} callback (err, data)
* @return {[type]}
*/
Sonos.prototype.configureSleepTimer = function (sleepTimerDuration, callback) {
debug('Sonos.sleepTimerDuration(%j, %j)', sleepTimerDuration, callback)
var action = '"urn:schemas-upnp-org:service:AVTransport:1#ConfigureSleepTimer"'
var body = '<u:ConfigureSleepTimer xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><NewSleepTimerDuration>' + sleepTimerDuration + '</NewSleepTimerDuration></u:ConfigureSleepTimer>'
return this.request(this.options.endpoints.transport, action, body, 'u:ConfigureSleepTimerResponse', function (err, data) {
return callback(err, data)
})
}
/**
* Set Muted
* @param {Boolean} muted
* @param {Function} callback (err, data)
* @return {[type]}
*/
Sonos.prototype.setMuted = function (muted, callback) {
debug('Sonos.setMuted(%j, %j)', muted, callback)
if (typeof muted === 'string') muted = !!parseInt(muted, 10)
var action = '"urn:schemas-upnp-org:service:RenderingControl:1#SetMute"'
var body = '<u:SetMute xmlns:u="urn:schemas-upnp-org:service:RenderingControl:1"><InstanceID>0</InstanceID><Channel>Master</Channel><DesiredMute>' + (muted ? '1' : '0') + '</DesiredMute></u:SetMute>'
this.request(this.options.endpoints.rendering, action, body, 'u:SetMutedResponse', function (err, data) {
return callback(err, data)
})
}
/**
* Get Zones in contact with current Zone with Group Data
* @param {Function} callback (err, topology)
*/
Sonos.prototype.getTopology = function (callback) {
debug('Sonos.getTopology(%j)', callback)
request('http://' + this.host + ':' + this.port + '/status/topology', function (err, res, body) {
if (err) return callback(err)
debug(body)
xml2js.parseString(body, function (err, topology) {
if (err) return callback(err)
var info = topology.ZPSupportInfo
var zones = null
var mediaServers = null
if (info.ZonePlayers && info.ZonePlayers.length > 0) {
zones = _.map(info.ZonePlayers[0].ZonePlayer, function (zone) {
return _.extend(zone.$, {name: zone._})
})
}
if (info.MediaServers && info.MediaServers.length > 0) {
mediaServers = _.map(info.MediaServers[0].MediaServer, function (zone) {
return _.extend(zone.$, {name: zone._})
})
}
callback(null, {
zones: zones,
mediaServers: mediaServers
})
})
})
}
/**
* Get Current Playback State
* @param {Function} callback (err, state)
*/
Sonos.prototype.getCurrentState = function (callback) {
debug('Sonos.currentState(%j)', callback)
var action = '"urn:schemas-upnp-org:service:AVTransport:1#GetTransportInfo"'
var body = '<u:GetTransportInfo xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID></u:GetTransportInfo>'
var state = null
return this.request(this.options.endpoints.transport, action, body, 'u:GetTransportInfoResponse', function (err, data) {
if (err) {
callback(err)
return
}
if (JSON.stringify(data[0].CurrentTransportState) === '["STOPPED"]') {
state = 'stopped'
} else if (JSON.stringify(data[0].CurrentTransportState) === '["PLAYING"]') {
state = 'playing'
} else if (JSON.stringify(data[0].CurrentTransportState) === '["PAUSED_PLAYBACK"]') {
state = 'paused'
} else if (JSON.stringify(data[0].CurrentTransportState) === '["TRANSITIONING"]') {
state = 'transitioning'
} else if (JSON.stringify(data[0].CurrentTransportState) === '["NO_MEDIA_PRESENT"]') {
state = 'no_media'
}
return callback(err, state)
})
}
/**
* Get Favorites Radio Stations
* @param {Object} options Optional - default {start: 0, total: 100}
* @param {Function} callback (err, result) result - {returned: {String}, total: {String}, items:[{title:{String}, uri: {String}}]}
*/
Sonos.prototype.getFavoritesRadioStations = function (options, callback) {
this.getFavoritesRadio('stations', options, callback)
}
/**
* Get Favorites Radio Shows
* @param {Object} options Optional - default {start: 0, total: 100}
* @param {Function} callback (err, result) result - {returned: {String}, total: {String}, items:[{title:{String}, uri: {String}}]}
*/
Sonos.prototype.getFavoritesRadioShows = function (options, callback) {
this.getFavoritesRadio('shows', options, callback)
}
/**
* Get Favorites Radio for a given radio type
* @param {String} favoriteRadioType Choice - stations, shows
* @param {Object} options Optional - default {start: 0, total: 100}
* @param {Function} callback (err, result) result - {returned: {String}, total: {String}, items:[{title:{String}, uri: {String}}]}
*/
Sonos.prototype.getFavoritesRadio = function (favoriteRadioType, options, callback) {
var radioTypes = {
'stations': 'R:0/0',
'shows': 'R:0/1'
}
var defaultOptions = {
BrowseFlag: 'BrowseDirectChildren',
Filter: '*',
StartingIndex: '0',
RequestedCount: '100',
SortCriteria: '',
ObjectID: 'R:0/0'
}
var opts = {
ObjectID: radioTypes[favoriteRadioType]
}
if (options.start !== undefined) opts.StartingIndex = options.start
if (options.total !== undefined) opts.RequestedCount = options.total
opts = _.extend(defaultOptions, opts)
var contentDirectory = new Services.ContentDirectory(this.host, this.port)
return contentDirectory.Browse(opts, function (err, data) {
if (err) return callback(err)
return (new xml2js.Parser()).parseString(data.Result, function (err, didl) {
if (err) return callback(err, data)
var items = []
if ((!didl) || (!didl['DIDL-Lite'])) {
return callback(new Error('Cannot parse DIDTL result'), data)
}