-
Notifications
You must be signed in to change notification settings - Fork 3
/
sonos.pl
executable file
·2293 lines (1938 loc) · 84.3 KB
/
sonos.pl
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
#!/usr/bin/perl
use lib "./UPnP/lib";
use lib ".";
use UPnP::ControlPoint;
use Socket;
use IO::Select;
use IO::Handle;
use Data::Dumper;
use HTML::Parser;
use HTML::Entities;
use URI::Escape;
use XML::Simple;
use HTTP::Daemon;
use HTML::Template;
use LWP::MediaTypes qw(add_type);
use POSIX qw(strftime);
use Encode qw(encode decode);
use LWP::UserAgent;
use SOAP::Lite maptype => {};
use MIME::Base64;
use strict;
use Carp qw(cluck);
$main::VERSION = "0.72";
###############################################################################
# Default config if config.pl doesn't exist
$main::MAX_LOG_LEVEL = 0; # Lower, the less output
$main::HTTP_PORT = 8001; # Port our fake http server listens on
$main::MAX_SEARCH = 500; # Default max search results to return
$main::RENEW_SUB_TIME = 1800; # How often do we do a UPnP renew in seconds
$main::DEFAULT = "index.html";
$main::AACACHE = 3600; # How long do we tell browser to cache album art in secs
$main::MUSICDIR = ""; # Local directory that sonos indexs that we can create music files in
$main::PASSWORD = ""; # Password for basic auth
$main::IGNOREIPS = ""; # Ignore this ip
do "./config.pl" if (-f "./config.pl");
foreach my $ip (split (",", $main::IGNOREIPS)) {
$UPnP::ControlPoint::IGNOREIP{$ip} = 1;
}
$| = 1;
foreach my $arg (@ARGV) {
$main::MAX_LOG_LEVEL = 4 if ($arg eq "-debug");
$main::MAX_LOG_LEVEL = 1 if ($arg eq "-alert");
doconfig() if ($arg eq "-config");
}
if ($main::MUSICDIR ne "") {
$main::MUSICDIR = "$main::MUSICDIR/SonosWeb";
if (! -d $main::MUSICDIR) {
mkdir ($main::MUSICDIR);
die "Couldn't create directory '$main::MUSICDIR'" if (! -d $main::MUSICDIR);
}
}
$SIG{INT} = "main::quit";
$SIG{PIPE} = sub {};
$SIG{CHLD} = \&main::sigchld;
$Data::Dumper::Indent = 1;
@main::TIMERS = ();
$main::SONOS_UPDATENUM = time();
%main::PREFS = ();
%main::CHLD = ();
$main::ZONESUPDATE = 0;
###############################################################################
use POSIX ":sys_wait_h";
sub sigchld {
my $child;
while (($child = waitpid(-1,WNOHANG)) > 0) {
delete $main::CHLD{$child};
}
$SIG{CHLD} = \&main::sigchld;
}
###############################################################################
sub doconfig {
print "Configure the defaults for sonos.pl by creating a config.pl file.\n";
print "Press return or enter key to keep current values.\n";
print "Remove the config.pl to reset to the system defaults.\n";
print "\n";
print "Port to listen on [$main::HTTP_PORT]: ";
my $port = int(<STDIN>);
$port = $main::HTTP_PORT if ($port == 0);
$port = 8001 if ($port > 0xffff || $port <= 0);
print "Max log level 0=crit 4=debug [$main::MAX_LOG_LEVEL]: ";
my $loglevel = int(<STDIN>);
$loglevel = $main::MAX_LOG_LEVEL if ($loglevel == 0);
$loglevel = 1 if ($loglevel < 0 || $loglevel > 4);
print "Max search results [$main::MAX_SEARCH]: ";
my $maxsearch = int(<STDIN>);
$maxsearch = $main::MAX_SEARCH if ($maxsearch == 0);
$maxsearch = 500 if ($maxsearch < 0);
print "Default web page, must exist in html directory [$main::DEFAULT]: ";
my $defaultweb = <STDIN>;
$defaultweb =~ s/[\r\n]//m;
if ($defaultweb eq " ") {
$defaultweb = "";
} elsif ($defaultweb eq "") {
$defaultweb = $main::DEFAULT;
}
die "The file html/$defaultweb was not found\n" if ($defaultweb ne "" && ! -f "html/$defaultweb");
print "\n";
print "Location on local disk that Sonos indexes, a subdirectory SonosWeb will be created.\n";
print "Use forward slashes only (ex c:/Music), enter single space to clear [$main::MUSICDIR]: ";
my $musicdir = <STDIN>;
$musicdir =~ s/[\r\n]//m;
if ($musicdir eq " ") {
$musicdir = "";
} elsif ($musicdir eq "") {
$musicdir = "$main::MUSICDIR";
}
die "$musicdir is not a directory\n" if ($musicdir ne "" && ! -d $musicdir);
print "\n";
print "Password for access to web site. (Notice, this isn't secure at all.)\n";
print "Enter single space to clear [$main::PASSWORD]: ";
my $password = <STDIN>;
$password =~ s/[\r\n]//m;
if ($password eq " ") {
$password = "";
} elsif ($password eq "") {
$password = "$main::PASSWORD";
}
print "\n";
print "Ignore traffic from these comma seperated ips\n";
print "Enter single space to clear [$main::IGNOREIPS]: ";
my $ignoreips = <STDIN>;
$ignoreips =~ s/[\r\n]//m;
if ($ignoreips eq " ") {
$ignoreips = "";
} elsif ($ignoreips eq "") {
$ignoreips = "$main::IGNOREIPS";
}
open (CONFIG, ">./config.pl");
print CONFIG "# This file uses perl syntax\n";
print CONFIG "\$main::HTTP_PORT = $port;\n";
print CONFIG "\$main::MAX_LOG_LEVEL = $loglevel;\n";
print CONFIG "\$main::MAX_SEARCH = $maxsearch;\n";
print CONFIG "\$main::DEFAULT = \"$defaultweb\";\n";
print CONFIG "\$main::MUSICDIR =\"$musicdir\";\n";
print CONFIG "\$main::PASSWORD =\"$password\";\n";
print CONFIG "\$main::IGNOREIPS =\"$ignoreips\";\n";
close CONFIG;
print "\nPlease restart sonos.pl now\n";
exit 0;
}
###############################################################################
sub quit {
plugin_quit();
http_quit();
sonos_quit();
Log (0, "Shutting Down");
exit 0;
}
###############################################################################
# main
sub main {
Log (0, "Starting up version $main::VERSION!\n" .
"If the application doesn't seem to work:\n" .
" * you may need to disable your firewall or allow the application\n" .
" * make sure the computer is on the same network as Sonos boxes\n" .
" * make sure the Sonos Controller software isn't running on the same computer\n" .
"\n" .
"Now, point your browser to http://localhost:$main::HTTP_PORT and leave this running\n");
add_type("text/css" => qw(css));
$main::useragent = LWP::UserAgent->new(env_proxy => 1, keep_alive => 2, parse_head => 0);
$main::daemon = HTTP::Daemon->new(LocalPort => $main::HTTP_PORT, Reuse => 1) || die;
$main::cp = UPnP::ControlPoint->new ();
my $search = $main::cp->searchByType("urn:schemas-upnp-org:device:ZonePlayer:1", \&main::upnp_search_cb);
my @selsockets = $main::cp->sockets();
@selsockets = (@selsockets, $main::daemon);
$main::select = IO::Select->new(@selsockets);
http_register_handler("/getaa", \&http_albumart_request);
http_register_handler("/getAA", \&http_albumart_request);
add_macro("Play", "/simple/control.html?zone=%zone%&action=Play");
add_macro("Pause", "/simple/control.html?zone=%zone%&action=Pause");
add_macro("Next", "/simple/control.html?zone=%zone%&action=Next");
add_macro("Previous", "/simple/control.html?zone=%zone%&action=Previous");
sonos_containers_init();
sonos_musicdb_load();
sonos_prefsdb_load();
sonos_renew_subscriptions();
plugin_load();
# MAIN LOOP
while (1) {
# Check the callbacks we have waiting
my $timeout = 5;
my $now = time;
while ($#main::TIMERS >= 0) {
if ($main::TIMERS[0][0] <= $now) {
my($time, $callback, @args) = @{shift @main::TIMERS};
&$callback(@args);
} else {
$timeout = $main::TIMERS[0][0] - $now;
last;
}
}
# Find if any sockets are ready for reading
my @sockets = $main::select->can_read($timeout);
# Call the handlers for the sockets
for my $sock (@sockets) {
if ($sock == $main::daemon) {
my $c = $main::daemon->accept;
my $r = $c->get_request;
http_handle_request($c, $r);
} elsif (defined $main::SOCKETCB{$sock}) {
&{$main::SOCKETCB{$sock}}();
} else {
$main::cp->handleOnce($sock);
}
}
}
}
###############################################################################
# PLUGINS
###############################################################################
###############################################################################
sub plugin_load {
Log(1, "Loading Plugins");
eval "us" . "e lib '.'"; # Defeat pp stripping
opendir(DIR, "Plugins") || return;
for my $plugin (readdir(DIR)) {
if ($plugin =~ /(.+)\.pm$/) {
$main::PLUGINS{$plugin} = () if (!$main::PLUGINS{$plugin});
$main::PLUGINS{$plugin}->{require} = "Plugins::" . $1;
} elsif (-d "Plugins/$plugin" && -e "Plugins/$plugin/Plugin.pm") {
$main::PLUGINS{$plugin} = () if (!$main::PLUGINS{$plugin});
$main::PLUGINS{$plugin}->{require} = "Plugins::" . $plugin . "::Plugin";
if ( -d "Plugins/$plugin/html") {
$main::PLUGINS{$plugin}->{html} = "Plugins/$plugin/html/";
}
}
}
closedir(DIR);
# First load the plugins
foreach my $plugin (keys %main::PLUGINS) {
eval "require ". $main::PLUGINS{$plugin}->{require};
if ($@) {
Log(0, "Did not load $plugin: " . $@);
delete $main::PLUGINS{$plugin};
next;
}
}
# Now init the plugins. We do in two steps so plugin inits can talk to other plugins
foreach my $plugin (keys %main::PLUGINS) {
eval "Plugins::${plugin}::init();";
if ($@) {
Log(0, "Did not init $plugin: " . $@);
delete $main::PLUGINS{$plugin};
next;
}
}
}
###############################################################################
sub plugin_register {
my ($plugin, $name, $link, $tmplhook) = @_;
$main::PLUGINS{$plugin}->{name} = $name;
$main::PLUGINS{$plugin}->{link} = $link;
$main::PLUGINS{$plugin}->{tmplhook} = $tmplhook;
}
###############################################################################
sub plugin_quit {
foreach my $plugin (keys %main::PLUGINS) {
eval "Plugins::${plugin}::quit();";
if ($@) {
Log(0, "Can not quit $plugin: " . $@);
}
}
}
###############################################################################
# SONOS
###############################################################################
%main::UPDATEID = (
ShareIndexInProgress => 0,
ShareIndexInProgress2 => 0,
ShareListUpdateID => "",
MasterRadioUpdateID => "",
SavedQueuesUpdateID => ""
);
###############################################################################
sub sonos_quit {
foreach my $sub (keys %main::SUBSCRIPTIONS) {
Log (2, "Unsubscribe $sub");
$main::SUBSCRIPTIONS{$sub}->unsubscribe;
}
}
###############################################################################
sub sonos_reindex {
if ($main::UPDATEID{ShareIndexInProgress} || $main::UPDATEID{ShareIndexInProgress2}) {
Log (2, "Alreadying reindexing");
return;
}
upnp_content_dir_refresh_share_index();
}
###############################################################################
sub sonos_fetch_music {
$main::UPDATEID{ShareIndexInProgress2} = 1;
my ($zone) = split(",", $main::UPDATEID{ShareListUpdateID});
my $contentDir = upnp_zone_get_service($zone, "urn:schemas-upnp-org:service:ContentDirectory:1");
if (! defined $contentDir) {
if ($zone eq "") {
Log(0, "Main zone not found yet, will retry. Windows XP *WILL* require rerunning SonosWeb after selecting 'Unblock' in the Windows Security Alert.");
} else {
Log(1, "$zone not available, will retry");
}
add_timeout (time()+5, \&sonos_fetch_music);
return
}
undef %main::REINDEX_DATA;
Log (1, "Fetching Music DB");
$main::REINDEX{start} = 0;
sonos_fetch_music_callback();
}
###############################################################################
sub sonos_fetch_music_callback {
# We only do 200 at a time otherwise we lock out everything else
my ($zone) = split(",", $main::UPDATEID{ShareListUpdateID});
my $contentDir = upnp_zone_get_service($zone, "urn:schemas-upnp-org:service:ContentDirectory:1");
my $contentDirProxy = $contentDir->controlProxy;
my $result = $contentDirProxy->Browse("A:TRACKS", 'BrowseDirectChildren',
'dc:title,res,dc:creator,upnp:artist,upnp:album',
$main::REINDEX{start}, 200, "");
if (!$result->isSuccessful) {
Log (2, "Failed to fetch all tracks: " . Dumper($result));
Log (3, "Proxy is: " . Dumper($main::REINDEX{contentDirProxy}));
$main::UPDATEID{ShareIndexInProgress2} = 0;
$main::MUSICUPDATE = $main::SONOS_UPDATENUM++;
sonos_containers_del("A:");
sonos_process_waiting("MUSIC");
return;
}
$main::REINDEX{start} += $result->getValue("NumberReturned");
Log (2, "DB: $main::REINDEX{start} of " . $result->getValue("TotalMatches"));
my $results = $result->getValue("Result");
my $tree = XMLin($results, forcearray => ["item"]);
foreach my $objectid (keys %{$tree->{item}}) {
my $entry = $tree->{item}{$objectid};
my $artist = $entry->{"dc:creator"};
my $album = $entry->{"upnp:album"};
my $title = $entry->{"dc:title"};
$artist = "" if (! $entry->{"dc:creator"});
$album = "" if (! $entry->{"upnp:album"});
#Only copy the stuff we want
$main::REINDEX_DATA{$artist}{$album}{$title} = $objectid
}
if ($main::REINDEX{start} >= $result->getValue("TotalMatches")) {
%main::MUSIC = %main::REINDEX_DATA;
undef %main::REINDEX_DATA;
sonos_musicdb_save();
$main::UPDATEID{ShareIndexInProgress2} = 0;
$main::MUSICUPDATE = $main::SONOS_UPDATENUM++;
sonos_containers_del("A:");
sonos_process_waiting("MUSIC");
} else {
add_timeout (time(), \&sonos_fetch_music_callback);
}
}
###############################################################################
sub sonos_musicdb_save {
$main::MUSIC{_info}->{ShareListUpdateID} = $main::UPDATEID{ShareListUpdateID};
$main::MUSIC{_info}->{version} = $main::VERSION;
{
local $Data::Dumper::Purity = 1;
Log (1, "Saving Music DB");
open (DB, ">musicdb.pl");
my $dumper = Data::Dumper->new( [\%main::MUSIC], [ qw( *main::MUSIC) ] );
print DB $dumper->Dump();
close DB;
Log (1, "Finshed Saving Music DB");
}
delete $main::MUSIC{_info};
}
###############################################################################
sub sonos_musicdb_load {
if ( -f "musicdb.pl") {
Log (1, "Loading Music DB");
do "./musicdb.pl";
if ($@) {
Log (0, "Error loading Music DB: $@");
}
$main::LASTUPDATE = $main::SONOS_UPDATENUM;
Log (1, "Finished Loading Music DB");
# To make life easier, we always update the music index on new version install
if ($main::MUSIC{_info}->{version} != $main::VERSION) {
Log (1, "Old version of Music DB (". $main::MUSIC{_info}->{version}.") must rebuild for (" . $main::VERSION .")");
undef %main::MUSIC;
} else {
$main::UPDATEID{ShareListUpdateID} = $main::MUSIC{_info}->{ShareListUpdateID};
delete $main::MUSIC{_info};
}
}
}
###############################################################################
sub sonos_mkcontainer {
my ($parent, $class, $title, $id, $content) = @_;
my %data;
$data{'upnp:class'} = $class;
$data{'dc:title'} = $title;
$data{parentID} = $parent;
$data{id} = $id;
$data{res}->{content} = $content if (defined $content);
push (@{$main::CONTAINERS{$parent}}, \%data);
$main::ITEMS{$data{id}} = \%data;
}
###############################################################################
sub sonos_mkitem {
my ($parent, $class, $title, $id, $content) = @_;
$main::ITEMS{$id}->{"upnp:class"} = $class;
$main::ITEMS{$id}->{parentID} = $parent;
$main::ITEMS{$id}->{"dc:title"} = $title;
$main::ITEMS{$id}->{id} = $id;
$main::ITEMS{$id}->{res}->{content} = $content if (defined $content);
}
###############################################################################
sub sonos_containers_init {
$main::MUSICUPDATE = $main::SONOS_UPDATENUM++;
undef %main::CONTAINERS;
sonos_mkcontainer("", "object.container", "Artists", "A:ARTIST");
sonos_mkcontainer("", "object.container", "Albums", "A:ALBUM");
sonos_mkcontainer("", "object.container", "Genres", "A:GENRE");
sonos_mkcontainer("", "object.container", "Composers", "A:COMPOSER");
sonos_mkcontainer("", "object.container", "Imported Playlists", "A:PLAYLISTS");
sonos_mkcontainer("", "object.container", "Folders", "S:");
sonos_mkcontainer("", "object.container", "Radio", "R:");
sonos_mkcontainer("", "object.container", "Line In", "AI:");
sonos_mkcontainer("", "object.container", "Playlists", "SQ:");
sonos_mkitem("", "object.container", "", "");
}
###############################################################################
sub sonos_containers_get {
my ($what) = @_;
my ($zone) = split(",", $main::UPDATEID{ShareListUpdateID});
if (!defined $zone) {
my $foo = ();
return $foo;
}
my $type = substr ($what, 0, index($what, ':'));
if (defined $main::HOOK{"CONTAINER_$type"}) {
sonos_process_hook("CONTAINER_$type", $what);
}
if (exists $main::CONTAINERS{$what}) {
Log (2, "Using cache for $what");
} elsif ($what eq "AI:") {
$main::CONTAINERS{$what} = ();
foreach my $zone (keys %main::ZONES) {
my $linein = upnp_content_dir_browse($zone, "AI:");
if (defined $linein->[0]) {
$linein->[0]->{id} .= "/" . $linein->[0]->{"dc:title"};
push @{$main::CONTAINERS{$what}}, $linein->[0];
}
}
} else {
$main::CONTAINERS{$what} = upnp_content_dir_browse($zone, $what);
}
foreach my $item (@{$main::CONTAINERS{$what}}) {
$main::ITEMS{$item->{id}} = $item;
}
return $main::CONTAINERS{$what};
}
###############################################################################
sub sonos_containers_del {
my ($what) = @_;
$main::MUSICUPDATE = $main::SONOS_UPDATENUM++;
foreach my $key (keys %main::CONTAINERS) {
next if (! ($key =~ /^$what/));
foreach my $item (@{$main::CONTAINERS{$key}}) {
delete $main::ITEMS{$item->{id}};
}
delete $main::CONTAINERS{$key};
}
}
###############################################################################
sub sonos_prefsdb_save {
{
local $Data::Dumper::Purity = 1;
Log (1, "Saving Prefs DB");
open (DB, ">prefsdb.pl");
my $dumper = Data::Dumper->new( [\%main::PREFS], [ qw( *main::PREFS) ] );
print DB $dumper->Dump();
close DB;
Log (1, "Finshed Saving Prefs DB");
}
}
###############################################################################
sub sonos_prefsdb_load {
if ( -f "prefsdb.pl") {
Log (1, "Loading Prefs DB");
do "./prefsdb.pl";
if ($@) {
Log (0, "Error loading Prefs DB: $@");
}
}
}
###############################################################################
sub sonos_renew_subscriptions {
Log (3, "invoked");
foreach my $sub (keys %main::SUBSCRIPTIONS) {
Log (3, "renew $sub");
my $previousStart = $main::SUBSCRIPTIONS{$sub}->{_startTime};
$main::SUBSCRIPTIONS{$sub}->renew();
if($previousStart == $main::SUBSCRIPTIONS{$sub}->{_startTime}) {
Log (1, "renew failed " . Dumper($@));
# Renew failed, lets subscribe again
my ($location, $name) = split (",", $sub);
my $device = $main::DEVICE{$location};
my $service = upnp_device_get_service($device, $name);
$main::SUBSCRIPTIONS{"$location,$name"} = $service->subscribe(\&sonos_upnp_update);
}
}
add_timeout(time()+$main::RENEW_SUB_TIME, \&sonos_renew_subscriptions);
}
###############################################################################
sub sonos_location_to_id {
my ($location) = @_;
foreach my $zone (keys %main::ZONES) {
return $zone if ($main::ZONES{$zone}->{Location} eq $location);
}
return undef;
}
###############################################################################
sub sonos_upnp_update {
my ($service, %properties) = @_;
Log (2, "Event received for service=" . $service->{BASE} . " id = " . $service->serviceId);
# Log(4, Dumper(\%properties));
# Save off the zone names
if ($service->serviceId =~ /serviceId:ZoneGroupTopology/) {
foreach my $key (keys %properties) {
if ($key eq "ZoneGroupState") {
my $tree = XMLin(decode_entities($properties{$key}),
forcearray => ["ZoneGroup", "ZoneGroupMember"]);
Log(4, "ZoneGroupTopology " . Dumper($tree));
foreach my $group (@{$tree->{ZoneGroup}}) {
my %zonegroup = %{$group};
foreach my $member (@{$zonegroup{ZoneGroupMember}}) {
my $zkey = $member->{UUID};
foreach my $mkey (keys %{$member}) {
$main::ZONES{$zkey}->{$mkey} = $member->{$mkey};
}
$main::ZONES{$zkey}->{Coordinator} = $zonegroup{Coordinator};
my @ip = split(/\//, $member->{Location});
$main::ZONES{$zkey}->{IPPORT} = $ip[2];
$main::ZONES{$zkey}->{AV}->{LASTUPDATE} = 1 if (!defined $main::ZONES{$zkey}->{AV}->{LASTUPDATE});
$main::ZONES{$zkey}->{RENDER}->{LASTUPDATE} = 1 if (!defined $main::ZONES{$zkey}->{RENDER}->{LASTUPDATE});
$main::ZONES{$zkey}->{AV}->{CurrentTrackMetaData} = "" if (!defined $main::ZONES{$zkey}->{AV}->{CurrentTrackMetaData});
$main::QUEUEUPDATE{$zkey} = 1 if (!defined $main::QUEUEUPDATE{$zkey});
}
}
$main::LASTUPDATE = $main::SONOS_UPDATENUM;
$main::ZONESUPDATE = $main::SONOS_UPDATENUM++;
sonos_process_waiting("ZONES");
} elsif ($key eq "ThirdPartyMediaServers") {
my $tree = XMLin(decode_entities($properties{$key}), forcearray => ["Service"]);
for my $item ( @{ $tree->{Service} } ) {
if($item->{UDN} =~ "SA_RINCON1_") { #Rhapsody
Log(2, "Adding Rhapsody Subscription");
$main::SERVICES{Rhapsody} = $item;
} elsif($item->{UDN} =~ "SA_RINCON4_") { #PANDORA
Log(2, "Adding Pandora Subscription");
$main::SERVICES{Pandora} = $item;
} elsif($item->{UDN} =~ "SA_RINCON6_") { #SIRIUS
Log(2, "Adding Sirius Subscription");
$main::SERVICES{Sirius} = $item;
}
}
sonos_process_waiting("SERVICES");
} else {
Log(4, "$key " . Dumper($properties{$key}));
}
}
}
my $zone = sonos_location_to_id($service->{BASE});
# Save off the current status
if ($service->serviceId =~ /serviceId:RenderingControl/) {
if (decode_entities($properties{LastChange}) eq "") {
Log(3, "Unknown RenderingControl " . Dumper(\%properties));
return;
}
my $tree = XMLin(decode_entities($properties{LastChange}),
forcearray => ["ZoneGroup"],
keyattr=>{"Volume" => "channel",
"Mute" => "channel",
"Loudness" => "channel"});
Log(4, "RenderingControl " . Dumper($tree));
foreach my $key ("Volume", "Treble", "Bass", "Mute", "Loudness") {
if ($tree->{InstanceID}->{$key}) {
$main::ZONES{$zone}->{RENDER}->{$key} = $tree->{InstanceID}->{$key};
$main::LASTUPDATE = $main::SONOS_UPDATENUM;
$main::ZONES{$zone}->{RENDER}->{LASTUPDATE} = $main::SONOS_UPDATENUM++;
}
}
sonos_process_waiting("RENDER", $zone);
return;
}
if ($service->serviceId =~ /serviceId:AVTransport/) {
if (decode_entities($properties{LastChange}) eq "") {
Log(3, "Unknown AVTransport " . Dumper(\%properties));
return;
}
my $tree = XMLin(decode_entities($properties{LastChange}));
Log(4, "AVTransport " . Dumper($tree));
foreach my $key ("CurrentTrackMetaData", "CurrentPlayMode", "NumberOfTracks", "CurrentTrack", "TransportState", "AVTransportURIMetaData", "AVTransportURI", "r:NextTrackMetaData", "CurrentTrackDuration") {
if ($tree->{InstanceID}->{$key}) {
$main::LASTUPDATE = $main::SONOS_UPDATENUM;
$main::ZONES{$zone}->{AV}->{LASTUPDATE} = $main::SONOS_UPDATENUM++;
if ($tree->{InstanceID}->{$key}->{val} =~ /^</) {
$tree->{InstanceID}->{$key}->{val} = decode_entities($tree->{InstanceID}->{$key}->{val});
}
if ($tree->{InstanceID}->{$key}->{val} =~ /^</) {
$main::ZONES{$zone}->{AV}->{$key} = \%{XMLin($tree->{InstanceID}->{$key}->{val})};
} else {
$main::ZONES{$zone}->{AV}->{$key} = $tree->{InstanceID}->{$key}->{val};
}
}
}
sonos_process_waiting("AV", $zone);
return;
}
if ($service->serviceId =~ /serviceId:ContentDirectory/) {
Log(4, "ContentDirectory " . Dumper(\%properties));
if (defined $properties{ContainerUpdateIDs} && $properties{ContainerUpdateIDs} =~ /AI:/) {
sonos_containers_del("AI:");
}
if (!defined $main::ZONES{$zone}->{QUEUE} || $properties{ContainerUpdateIDs} =~ /Q:0/) {
Log (2, "Refetching Q for $main::ZONES{$zone}->{ZoneName} updateid $properties{ContainerUpdateIDs}");
$main::ZONES{$zone}->{QUEUE} = upnp_content_dir_browse($zone, "Q:0");
$main::LASTUPDATE = $main::SONOS_UPDATENUM;
$main::QUEUEUPDATE{$zone} = $main::SONOS_UPDATENUM++;
sonos_process_waiting("QUEUE", $zone);
}
if (defined $properties{ShareIndexInProgress}) {
$main::UPDATEID{ShareIndexInProgress} = $properties{ShareIndexInProgress};
}
if (defined $properties{MasterRadioUpdateID} && ($properties{MasterRadioUpdateID} ne $main::UPDATEID{MasterRadioUpdateID})) {
$main::UPDATEID{MasterRadioUpdateID} = $properties{MasterRadioUpdateID};
sonos_containers_del("R:");
}
if (defined $properties{SavedQueuesUpdateID} && $properties{SavedQueuesUpdateID} ne $main::UPDATEID{SavedQueuesUpdateID}) {
$main::UPDATEID{SavedQueuesUpdateID} = $properties{SavedQueuesUpdateID};
sonos_containers_del("SQ:");
}
if (defined $properties{ShareListUpdateID} && $properties{ShareListUpdateID} ne $main::UPDATEID{ShareListUpdateID}) {
$main::UPDATEID{ShareListUpdateID} = $properties{ShareListUpdateID};
Log (2, "Refetching Index, update id $properties{ShareListUpdateID}");
add_timeout (time(), \&sonos_fetch_music);
}
return;
}
while (my ($key, $val) = each %properties) {
if ($val =~ /</) {
my $d = decode_entities($val);
my $tree = XMLin($d, forcearray => ["ZoneGroup"], keyattr=>{"ZoneGroup" => "ID"});
Log(3, "Property ${key}'s value is " . Dumper($tree));
} else {
Log(3, "Property ${key}'s value is " . $val);
}
}
}
###############################################################################
sub sonos_music_class {
my ($mpath) = @_;
my $entry = sonos_music_entry($mpath);
return undef if (!defined $entry);
return $entry->{"upnp:class"};
}
###############################################################################
sub sonos_music_entry {
my ($mpath) = @_;
my $type = substr ($mpath, 0, index($mpath, ':'));
if (exists $main::ITEMS{$mpath}) {
} elsif (defined $main::HOOK{"ITEM_$type"}) {
sonos_process_hook("ITEM_$type", $mpath);
} else {
my ($zone) = split(",", $main::UPDATEID{ShareListUpdateID});
my $entry = upnp_content_dir_browse($zone, $mpath, "BrowseMetadata");
$main::ITEMS{$mpath} = $entry->[0] if (defined $entry->[0]);
}
return $main::ITEMS{$mpath};
}
###############################################################################
sub sonos_avtransport_set_radio {
my ($zone, $mpath) = @_;
my @parts = split("/", $mpath);
my $entry = sonos_music_entry($mpath);
# So, I'm very lazy :-)
my $urimetadata = '<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="' . $entry->{id} . '" parentID="' . $entry->{parentID} . '" restricted="true"><dc:title>'. $entry->{"dc:title"} . '</dc:title><upnp:class>object.item.audioItem.audioBroadcast</upnp:class><desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">RINCON_AssociatedZPUDN</desc></item></DIDL-Lite>';
upnp_avtransport_set_uri($zone, $entry->{res}->{content}, decode_entities($urimetadata));
upnp_avtransport_play($zone);
return;
}
###############################################################################
sub sonos_avtransport_set_queue {
my ($zone) = @_;
upnp_avtransport_set_uri($zone, "x-rincon-queue:" . $zone . "#0", "");
return;
}
###############################################################################
sub sonos_avtransport_set_linein {
my ($zone, $mpath) = @_;
my @parts = split("/", $mpath);
my $entry = sonos_music_entry($mpath);
# So, I'm very lazy :-)
my $urimetadata = '<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="AI:0" parentID="AI:" restricted="true"><dc:title>' . $parts[2] .'</dc:title><upnp:class>object.item.audioItem</upnp:class><desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">'. $entry->{zone} . '</desc></item></DIDL-Lite>';
upnp_avtransport_set_uri($zone, $entry->{res}->{content}, decode_entities($urimetadata));
return;
}
###############################################################################
sub sonos_avtransport_add {
my ($zone, $mpath, $queueSlot) = @_;
my $entry = sonos_music_entry($mpath);
Log(3, "before mpath = $mpath entry = " . Dumper($entry));
if ($entry->{"upnp:class"} eq "object.item.audioItem.audioBroadcast") {
return
}
my $type = substr ($mpath, 0, index($mpath, ':'));
my $metadata = "";
if (defined $main::HOOK{"META_$type"}) {
$metadata = sonos_process_hook("META_$type", $mpath, $entry);
}
upnp_avtransport_add_uri($zone, $entry->{res}->{content}, $metadata, $queueSlot);
return;
}
###############################################################################
sub sonos_add_waiting {
my $what = shift @_;
my $zone = shift @_;
my $cb = shift @_;
push @{$main::WAITING{$what}{$zone}}, [$cb, @_];
}
###############################################################################
sub sonos_process_waiting {
my ($what, $zone) = @_;
sonos_process_waiting_internal ($what, $zone, $what, $zone) if (defined $zone);
sonos_process_waiting_internal ($what, "*", $what, $zone);
sonos_process_waiting_internal ("*", $zone, $what, $zone) if (defined $zone);
sonos_process_waiting_internal ("*", "*", $what, $zone);
}
###############################################################################
sub sonos_process_waiting_internal {
my ($mwhat, $mzone, $what, $zone) = @_;
return if (!defined $main::WAITING{$mwhat}{$mzone});
my @waiting = @{$main::WAITING{$mwhat}{$mzone}};
@{$main::WAITING{$mwhat}{$mzone}} = ();
while ($#waiting >= 0) {
my($callback, @args) = @{shift @waiting};
&$callback($what, $zone, @args);
}
}
###############################################################################
sub sonos_add_hook {
my $what = shift @_;
my $cb = shift @_;
push @{$main::HOOK{$what}}, [$cb, @_];
}
###############################################################################
sub sonos_process_hook {
my ($what, @other) = @_;
return undef if (!defined $main::HOOK{$what});
my @hooks = @{$main::HOOK{$what}};
while ($#hooks >= 0) {
my($callback, @args) = @{shift @hooks};
my $out = &$callback($what, @other, @args);
return $out if (defined $out);
}
return undef;
}
###############################################################################
sub sonos_link_all_zones {
my ($masterzone) = @_;
foreach my $linkedzone (keys %main::ZONES) {
next if ($linkedzone eq $masterzone);
sonos_link_zone($masterzone, $linkedzone);
}
}
###############################################################################
sub sonos_link_zone {
my ($masterzone, $linkedzone) = @_;
# No need to do anything
return if ($main::ZONES{$linkedzone}->{Coordinator} eq $masterzone);
my $result = upnp_avtransport_set_uri($linkedzone, "x-rincon:" . $masterzone, "");
$main::ZONES{$linkedzone}->{Coordinator} = $masterzone if ($result->isSuccessful);
return $result;
}
###############################################################################
sub sonos_unlink_zone {
my ($linkedzone) = @_;
# First if this is a coordinator for any zones, make a new coordinator
my $newcoord;
foreach my $zone (keys %main::ZONES) {
next if ($zone eq $linkedzone);
if ($linkedzone eq $main::ZONES{$zone}->{Coordinator}) {
if ($newcoord) {
sonos_link_zone($newcoord, $zone);
} else {
upnp_avtransport_standalone_coordinator($zone);
upnp_avtransport_set_uri($zone, "x-rincon-queue:" . $zone . "#0", "");
$main::ZONES{$zone}->{Coordinator} = $zone;
$newcoord = $zone
}
}
}
# No need to do anything else
return if ($main::ZONES{$linkedzone}->{Coordinator} eq $linkedzone);
upnp_avtransport_standalone_coordinator($linkedzone);
my $result = upnp_avtransport_set_uri($linkedzone, "x-rincon-queue:" . $linkedzone . "#0", "");
# Perform the unlink locally also
$main::ZONES{$linkedzone}->{Coordinator} = $linkedzone if ($result->isSuccessful);
return $result;
}
###############################################################################
sub sonos_add_radio {
my ($name, $station) = @_;
Log(3, "Adding radio name:$name, station:$station");
$station = substr($station, 5) if (substr($station, 0, 5) eq "http:");
$name = encode_entities($name);
my $item = '<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" ' .
'xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" ' .
'xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">' .
'<item id="" restricted="false"><dc:title>' .
$name . '</dc:title><res>x-rincon-mp3radio:' .
$station . '</res></item></DIDL-Lite>';
my ($zone) = split(",", $main::UPDATEID{MasterRadioUpdateID});
return upnp_content_dir_create_object($zone, "R:0", $item);
}
###############################################################################
# UPNP
###############################################################################
###############################################################################
sub upnp_device_get_service {
my ($device, $name) = @_;
my $service = $device->getService($name);
return $service if ($service);
for my $child ($device->children) {
$service = $child->getService($name);
return $service if ($service);
}
return undef;
}
###############################################################################
sub upnp_zone_get_service {
my ($zone, $name) = @_;
if (! exists $main::ZONES{$zone} ||
! defined $main::ZONES{$zone}->{Location} ||
! defined $main::DEVICE{$main::ZONES{$zone}->{Location}}) {
main::Log(0, "Zone '$zone' not found");
return undef;
}