-
Notifications
You must be signed in to change notification settings - Fork 276
/
XMLBrowser.pm
1422 lines (1135 loc) · 44.1 KB
/
XMLBrowser.pm
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
package Slim::Web::XMLBrowser;
# Logitech Media Server Copyright 2001-2020 Logitech.
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License,
# version 2.
# This class displays a generic web interface for XML feeds
use strict;
use URI::Escape qw(uri_unescape uri_escape_utf8);
use List::Util qw(min);
use Tie::RegexpHash;
use Slim::Control::XMLBrowser;
use Slim::Formats::XML;
use Slim::Player::ProtocolHandlers;
use Slim::Utils::Cache;
use Slim::Utils::Log;
use Slim::Utils::Misc;
use Slim::Utils::Strings qw(string);
use Slim::Utils::Favorites;
use Slim::Utils::Prefs;
use Slim::Music::TitleFormatter;
use Slim::Web::HTTP;
use Slim::Web::ImageProxy qw(proxiedImage);
use Slim::Web::Pages;
use constant CACHE_TIME => 3600; # how long to cache browse sessions
my $log = logger('formats.xml');
my $prefs = preferences('server');
# use a timestamp to let cached pages expire on certain events
my $cacheTimestamp;
if ( !main::SCANNER ) {
# Wipe cached data after rescan or library change
Slim::Control::Request::subscribe( \&wipeCaches, [['library','rescan','favorites'], ['changed','done','changed']] );
$prefs->setChange( \&wipeCaches, qw(itemsPerPage thumbSize showArtist showYear additionalPlaylistButtons noGenreFilter noRoleFilter searchSubString browseagelimit
composerInArtists conductorInArtists bandInArtists variousArtistAutoIdentification titleFormat titleFormatWeb language useUnifiedArtistsList
groupArtistAlbumsByReleaseType ignoreReleaseTypes releaseTypesToIgnore showComposerReleasesbyAlbum showComposerReleasesbyAlbumGenres) );
}
tie my %cacheables, 'Tie::RegexpHash';
sub handleWebIndex {
my ( $class, $args ) = @_;
my $client = $args->{'client'};
my $feed = $args->{'feed'};
my $type = $args->{'type'} || 'link';
my $path = $args->{'path'} || 'index.html';
my $title = $args->{'title'};
my $expires = $args->{'expires'};
my $timeout = $args->{'timeout'};
my $asyncArgs = $args->{'args'};
my $item = $args->{'item'} || {};
my $pageicon = $Slim::Web::Pages::additionalLinks{icons}{$title};
main::DEBUGLOG && $log->is_debug && $log->debug( "feed is :" . Data::Dump::dump($feed) );
if ($title eq uc($title)) {
$title = string($title);
}
# If the feed is already XML data (Podcast List), send it to handleFeed
if ( ref $feed eq 'HASH' ) {
handleFeed( $feed, {
'url' => $feed->{'url'},
'path' => $path,
'title' => $title,
'expires' => $expires,
'args' => $asyncArgs,
'pageicon'=> $pageicon
} );
return;
}
my $params = {
'client' => $client,
'url' => $feed,
'type' => $type,
'path' => $path,
'title' => $title,
'expires' => $expires,
'timeout' => $timeout,
'args' => $asyncArgs,
'pageicon'=> $pageicon,
};
# Handle plugins that want to use callbacks to fetch their own URLs
if ( ref $feed eq 'CODE' ) {
my $callback = sub {
my $data = shift;
my $opml;
if ( ref $data eq 'HASH' ) {
$opml = $data;
$opml->{'type'} ||= 'opml';
$opml->{'title'} ||= $title;
} else {
$opml = {
type => 'opml',
title => $title,
items => (ref $data ne 'ARRAY' ? [$data] : $data),
};
}
handleFeed( $opml, $params );
};
# get passthrough params if supplied
my $pt = $item->{'passthrough'} || [];
if ( main::DEBUGLOG && $log->is_debug ) {
my $cbname = Slim::Utils::PerlRunTime::realNameForCodeRef($feed);
$log->debug( "Fetching OPML from coderef $cbname" );
$log->debug($asyncArgs->[1]->{url_query});
}
# XXX: maybe need to pass orderBy through
return $feed->( $client, $callback, {isWeb => 1, wantMetadata => 1, wantIndex => 1, params => $asyncArgs->[1]}, @{$pt});
}
# Handle type = search at the top level, i.e. Radio Search
if ( $type eq 'search' ) {
my $query = $asyncArgs->[1]->{q};
if ( !$query ) {
my $index = $asyncArgs->[1]->{index};
($query) = $index =~ m/^(?:[a-f0-9]{8})?_([^.]+)/;
$query = uri_unescape( $query ) if $query;
}
if ( $query ) {
$params->{url} =~ s/{QUERY}/$query/g;
}
else {
my $opml = {
type => 'opml',
title => Slim::Utils::Strings::getString($title),
items => [{
type => 'search',
name => Slim::Utils::Strings::getString($title),
url => $params->{url},
}],
};
handleFeed( $opml, $params );
return;
}
}
# Lookup this browse session in cache if user is browsing below top-level
# This avoids repated lookups to drill down the menu
my $index = $params->{args}->[1]->{index};
if ( $index && $index =~ /^([a-f0-9]{8})/ ) {
my $sid = $1;
# Do not use cache if this is a search query
if ( $asyncArgs->[1]->{q} ) {
# Generate a new sid
my $newsid = Slim::Utils::Misc::createUUID();
$params->{args}->[1]->{index} =~ s/^$sid/$newsid/;
}
else {
my $cache = Slim::Utils::Cache->new;
if ( my $cached = $cache->get("xmlbrowser_$sid") ) {
main::DEBUGLOG && $log->is_debug && $log->debug( "Using cached session $sid" );
handleFeed( $cached, $params );
return;
}
}
}
# fetch the remote content
Slim::Formats::XML->getFeedAsync(
\&handleFeed,
\&handleError,
$params,
);
return;
}
sub handleFeed {
my ( $feed, $params ) = @_;
my ( $client, $stash, $callback, $httpClient, $response ) = @{ $params->{'args'} };
my $cache = Slim::Utils::Cache->new;
$feed->{'title'} ||= Slim::Utils::Strings::getString($params->{'title'});
$stash->{'pageicon'} = $params->{pageicon};
if ($feed->{'query'}) {
$stash->{'mquery'} = join('&', map {$_ . '=' . $feed->{'query'}->{$_}} keys(%{$feed->{'query'}}));
}
my $template = 'xmlbrowser.html';
# Session ID for this browse session
my $sid;
# select the proper list of items
my @index = ();
if ( defined $stash->{'index'} && length( $stash->{'index'} ) ) {
main::DEBUGLOG && $log->is_debug && $log->debug("item_id: ", $stash->{'index'});
@index = split (/\./, $stash->{'index'});
if ( length( $index[0] ) >= 8 && $index[0] =~ /^[a-f0-9]{8}/ ) {
# Session ID is first element in index
$sid = shift @index;
}
}
else {
# Create a new session ID, unless the list has coderefs
my $refs = scalar grep { ref $_->{url} } @{ $feed->{items} };
if ( !$refs ) {
$sid = Slim::Utils::Misc::createUUID();
}
}
# breadcrumb
my @crumb = ( {
'name' => $feed->{'title'},
'index' => $sid,
} );
# Persist search query from top level item
if ( $params->{type} && $params->{type} eq 'search' && !scalar @index ) {
$crumb[0]->{index} = ($sid || '') . '_' . uri_escape_utf8( $stash->{q}, "^A-Za-z0-9" );
};
# favorites class to allow add/del of urls to favorites, but not when browsing favorites list itself
my $favs = Slim::Utils::Favorites->new($client) unless $feed->{'favorites'};
my $favsItem;
# action is add/delete favorite: pop the last item off the index as we want to display the whole page not the item
# keep item id in $favsItem so we can process it later
if ($stash->{'action'} && $stash->{'action'} =~ /^(favadd|favdel)$/ && @index) {
$favsItem = pop @index;
}
if ( $sid ) {
# Cache the feed structure for this session
# cachetime is only set by parsers which known the content is dynamic and so can't be cached
# for all other cases we always cache for CACHE_TIME to ensure the menu stays the same throughout the session
my $cachetime = defined $feed->{'cachetime'} ? $feed->{'cachetime'} : CACHE_TIME;
main::DEBUGLOG && $log->is_debug && $log->debug( "Caching session $sid for $cachetime" );
eval { $cache->set( "xmlbrowser_$sid", $feed, $cachetime ) };
if ( $@ && $log->is_warn ) {
$log->warn("Session not cached: $@");
}
}
if ( my $levels = scalar @index ) {
# index links for each crumb item
my @crumbIndex = $sid ? ( $sid ) : ();
# descend to the selected item
my $depth = 0;
my $subFeed = $feed;
my $superFeed;
for my $i ( @index ) {
$depth++;
my ($in) = $i =~ /^(\d+)/;
$superFeed = $subFeed;
$subFeed = $subFeed->{'items'}->[$in - ($subFeed->{'offset'} || 0)];
push @crumbIndex, $i;
my $crumbText = join '.', @crumbIndex;
$superFeed->{offset} ||= 0;
main::DEBUGLOG && $log->is_debug && $log->debug("Considering $i=$in ($crumbText) from ", $stash->{'index'}, ' offset=', $superFeed->{'offset'});
my $crumbName = Slim::Control::XMLBrowser::getTitle($subFeed->{name}, $subFeed);
# Add search query to crumb list
my $searchQuery;
if ( $subFeed->{'type'} && $subFeed->{'type'} eq 'search' && defined $stash->{'q'} ) {
# bug 17373 - remove period from search expression, as it breaks our index (and is ignored during the search anyway)
$stash->{q} =~ s/\./ /g;
$crumbText .= '_' . uri_escape_utf8( $stash->{q}, "^A-Za-z0-9" );
$searchQuery = $stash->{'q'};
}
elsif ( $i =~ /(?:\d+)?_(.+)/ ) {
$searchQuery = Slim::Utils::Unicode::utf8on(uri_unescape($1));
}
# Add search query to crumbName
if ( defined $searchQuery ) {
$crumbName .= ' (' . $searchQuery . ')';
}
push @crumb, {
'name' => $crumbName,
'index' => $crumbText,
};
if ( $subFeed->{type} && $subFeed->{type} eq 'slideshow' ) {
$stash->{slideshow} = 1;
}
# Change type to audio if it's an action request and we have a play attribute
# and it's the last item
if (
$subFeed->{'play'}
&& $depth == $levels
&& $stash->{'action'}
&& $stash->{'action'} =~ /^(?:play|add|insert)$/
) {
$subFeed->{'type'} = 'audio';
$subFeed->{'url'} = $subFeed->{'play'};
}
# Change URL if there is a playlist attribute and it's the last item
if (
$subFeed->{'playlist'}
&& $depth == $levels
&& $stash->{'action'}
&& $stash->{'action'} =~ /^(?:playall|addall|insert|remove)$/
) {
$subFeed->{'type'} = 'playlist';
$subFeed->{'url'} = $subFeed->{'playlist'};
}
# Bug 15343, if we are at the lowest menu level, and we have already
# fetched and cached this menu level, check if we should always
# re-fetch this menu. This is used to ensure things like the Pandora
# station list are always up to date. The reason we check depth==levels
# is so that when you are browsing at a lower level we don't allow
# the parent menu to be refreshed out from under the user
if ( $depth == $levels && $subFeed->{fetched} && $subFeed->{forceRefresh} && !$params->{fromSubFeed} ) {
main::DEBUGLOG && $log->is_debug && $log->debug(" Forcing refresh of menu");
delete $subFeed->{fetched};
}
# short-circuit fetch if possible
# If we have an action and we have an equivalent superFeed action
# and we are about to fetch the last level then we can just use the feed-defined action.
my ($feedAction, $feedActions);
if ($depth == $levels
&& $stash->{'action'} && $stash->{'action'} =~ /^((?:play|add|insert)(?:all)?)$/
)
{
($feedAction, $feedActions) = Slim::Control::XMLBrowser::findAction($superFeed, $subFeed, $1);
}
if ($feedAction) {
my @params = @{$feedAction->{'command'}};
if (my $params = $feedAction->{'fixedParams'}) {
push @params, map { $_ . ':' . $params->{$_}} keys %{$params};
}
my @vars = exists $feedAction->{'variables'} ? @{$feedAction->{'variables'}} : @{$feedActions->{'commonVariables'} || []};
for (my $i = 0; $i < scalar @vars; $i += 2) {
push @params, $vars[$i] . ':' . $subFeed->{$vars[$i+1]} if defined $subFeed->{$vars[$i+1]};
}
main::INFOLOG && $log->is_info && $log->info('CLI action (', $stash->{'action'}, '): ', join(' ', @params));
Slim::Control::Request::executeRequest( $client, \@params );
my $webroot = $stash->{'webroot'};
$webroot =~ s/(.*?)plugins.*$/$1/;
$template = 'xmlbrowser_redirect.html';
my $output = processTemplate($template, $stash);
# done, send output back to Web module for display
$callback->( $client, $stash, $output, $httpClient, $response );
return;
}
# If the feed is another URL, fetch it and insert it into the
# current cached feed
$subFeed->{'type'} ||= '';
if ( defined $subFeed->{'url'} && !$subFeed->{'fetched'} ) {
# Rewrite the URL if it was a search request
if ( $subFeed->{'type'} eq 'search' && defined ( $stash->{'q'} || $searchQuery ) ) {
my $search = URI::Escape::uri_escape_utf8($stash->{'q'} || $searchQuery);
$subFeed->{'url'} =~ s/{QUERY}/$search/g;
}
# Setup passthrough args
my $args = {
'client' => $client,
'item' => $subFeed,
'url' => $subFeed->{'url'},
'path' => $params->{'path'},
'feedTitle' => $subFeed->{'name'} || $subFeed->{'title'},
'parser' => $subFeed->{'parser'},
'expires' => $params->{'expires'},
'timeout' => $params->{'timeout'},
'parent' => $feed,
'parentURL' => $params->{'parentURL'} || $params->{'url'},
'currentIndex' => \@crumbIndex,
'args' => [ $client, $stash, $callback, $httpClient, $response ],
'pageicon' => $subFeed->{'icon'} || $params->{'pageicon'},
};
my ($feedAction, $feedActions) = Slim::Control::XMLBrowser::findAction( $superFeed, $subFeed,
($subFeed->{'type'} eq 'audio') ? 'info' : 'items' );
if ($feedAction && !($depth == $levels && $stash->{'action'})) {
my @params = @{$feedAction->{'command'}};
# All items requests take _index and _quantity parameters
if ($depth < $levels) {
push @params, ($index[$depth], 1);
} else {
push @params, (($stash->{'start'} || 0), ($args->{'itemsPerPage'} || $prefs->get('itemsPerPage')));
}
if (my $params = $feedAction->{'fixedParams'}) {
push @params, map { $_ . ':' . $params->{$_}} keys %{$params};
}
my @vars = exists $feedAction->{'variables'} ? @{$feedAction->{'variables'}} : @{$feedActions->{'commonVariables'} || []};
for (my $i = 0; $i < scalar @vars; $i += 2) {
push @params, $vars[$i] . ':' . $subFeed->{$vars[$i+1]} if defined $subFeed->{$vars[$i+1]};
}
push @params, 'feedMode:1';
push @params, 'wantMetadata:1';
push @params, 'wantIndex:1';
push @params, 'orderBy:' . $stash->{'orderBy'} if $stash->{'orderBy'};
main::INFOLOG && $log->is_info && $log->info('CLI browse: ', join(' ', @params));
my $callback = sub {
my $opml = shift;
$opml->{'type'} ||= 'opml';
$opml->{'title'} ||= $args->{feedTitle};
handleSubFeed( $opml, $args );
};
my $proxiedRequest = Slim::Control::Request::executeRequest( $client, \@params );
# wrap async requests
if ( $proxiedRequest->isStatusProcessing ) {
$proxiedRequest->callbackFunction( sub { $callback->($_[0]->getResults); } );
} else {
$callback->($proxiedRequest->getResults);
}
return;
}
elsif ( ref $subFeed->{'url'} eq 'CODE' ) {
my $callback = sub {
my $data = shift;
my $opml;
if ( ref $data eq 'HASH' ) {
$opml = $data;
$opml->{'type'} ||= 'opml';
$opml->{'title'} = $args->{feedTitle};
} else {
$opml = {
type => 'opml',
title => $args->{feedTitle},
items => (ref $data ne 'ARRAY' ? [$data] : $data),
};
}
handleSubFeed( $opml, $args );
};
# get passthrough params if supplied
my $pt = $subFeed->{'passthrough'} || [undef];
my $search;
if (defined $searchQuery && $searchQuery ne '' && $subFeed->{type} && $subFeed->{type} eq 'search') {
$search = $searchQuery;
}
if ( main::DEBUGLOG && $log->is_debug ) {
my $cbname = Slim::Utils::PerlRunTime::realNameForCodeRef( $subFeed->{url} );
$log->debug( "Fetching OPML from coderef $cbname" );
}
my %args = (isWeb => 1, wantMetadata => 1, wantIndex => 1, search => $search, params => $stash->{'query'}, library_id => $stash->{library_id}, orderBy => $stash->{'orderBy'});
my $index = $stash->{'start'};
if ($depth == $levels) {
$args{'index'} = $index;
$args{'quantity'} = $stash->{'itemsPerPage'} || ($stash->{action} && $stash->{action} =~ /^(?:play|add)all$/i && $prefs->get('maxPlaylistLength')) || $prefs->get('itemsPerPage');
} elsif ($depth < $levels) {
$args{'index'} = $index[$depth];
$args{'quantity'} = 1;
}
# first param is a $client object, but undef from webpages
$subFeed->{url}->( $client, $callback, \%args, @{$pt} );
return;
}
# No need to check for a cached version of this subfeed URL as getFeedAsync() will do that
elsif ($subFeed->{'type'} ne 'audio') {
# We need to fetch the URL
main::INFOLOG && $log->info( "Fetching OPML from:", $subFeed->{'url'} );
Slim::Formats::XML->getFeedAsync(
\&handleSubFeed,
\&handleError,
$args,
);
return;
}
}
}
# If the feed contains no sub-items, display item details
if ( (!$subFeed->{'items'}
||
( ref $subFeed->{'items'} eq 'ARRAY' && !scalar @{ $subFeed->{'items'} })
&& !($subFeed->{type} && $subFeed->{type} eq 'search')
&& !(ref $subFeed->{'url'}) )
) {
$subFeed->{'image'} ||= $subFeed->{'cover'} || $subFeed->{'icon'} || Slim::Player::ProtocolHandlers->iconForURL($subFeed->{'play'} || $subFeed->{'url'});
$subFeed->{'image'} = proxiedImage($subFeed->{'image'});
$stash->{'streaminfo'} = {
'item' => $subFeed,
'index' => $sid ? join( '.', $sid, @index ) : join( '.', @index ),
};
}
# Construct index param for each item in the list
my $itemIndex = $sid ? join( '.', $sid, @index ) : join( '.', @index );
if ( $stash->{'q'} ) {
$itemIndex .= '_' . uri_escape_utf8( $stash->{'q'}, "^A-Za-z0-9" );
}
$itemIndex .= '.';
$stash->{'pagetitle'} = Slim::Control::XMLBrowser::getTitle($subFeed->{'name'}, $subFeed);
$stash->{'index'} = $itemIndex;
$stash->{'icon'} = $subFeed->{'icon'};
$stash->{'playUrl'} = $subFeed->{'play'}
|| ($subFeed->{'type'} && $subFeed->{'type'} eq 'audio'
? $subFeed->{'url'}
: undef);
$feed = $subFeed;
}
else {
$stash->{'pagetitle'} = $feed->{'name'} || $feed->{'title'};
$stash->{'playUrl'} = $feed->{'play'};
if ( $sid ) {
$stash->{index} = $sid;
}
# Persist search term from top-level item (i.e. Search Radio)
if ( $stash->{q} ) {
$stash->{index} .= '_' . uri_escape_utf8( $stash->{'q'}, "^A-Za-z0-9" );
}
if ( $stash->{index} ) {
$stash->{index} .= '.';
}
if (defined $favsItem) {
$stash->{'index'} = undef;
}
}
$stash->{'crumb'} = \@crumb;
$stash->{'image'} = proxiedImage($feed->{'image'} || $feed->{'cover'} || $stash->{'image'});
foreach (qw(items type orderByList playlist_id playlistTitle total)) {
$stash->{$_} = $feed->{$_} if defined $feed->{$_};
}
# Only want plain URLs as play-URL
if ($stash->{'playUrl'} && ref $stash->{'playUrl'}) {
delete $stash->{'playUrl'};
}
my $action = $stash->{'action'};
my $streamItem = $stash->{'streaminfo'}->{'item'} if $stash->{'streaminfo'};
# Play of a playlist should be playall
if ($action
&& ($streamItem && $streamItem->{'type'} ? $streamItem->{'type'} eq 'playlist'
: $stash->{'type'} && $stash->{'type'} eq 'playlist')
&& $action =~ /^(?:play|add)$/
) {
$action .= 'all';
}
# play/add stream
if ( $client && $action && $action =~ /^(play|add)$/ ) {
my $url = $streamItem->{'url'};
my $title = $streamItem->{'name'} || $streamItem->{'title'};
# Podcast enclosures
if ( my $enc = $streamItem->{'enclosure'} ) {
$url = $enc->{'url'};
}
# Items with a 'play' attribute will use this for playback
if ( my $play = $streamItem->{'play'} ) {
$url = $play;
}
if ( $url ) {
main::INFOLOG && $log->info("Playing/adding $url");
main::DEBUGLOG && $log->is_debug && $log->debug("streamItem is " . Data::Dump::dump($streamItem));
# Set metadata about this URL
Slim::Music::Info::setRemoteMetadata( $url, {
title => $title,
ct => $streamItem->{'mime'},
secs => $streamItem->{'duration'},
bitrate => $streamItem->{'bitrate'},
cover => $streamItem->{'cover'} || $streamItem->{'image'} || $streamItem->{'icon'},
year => $streamItem->{'year'},
} );
$client->execute([ 'playlist', $action, $url ]);
my $webroot = $stash->{'webroot'};
$webroot =~ s/(.*?)plugins.*$/$1/;
$template = 'xmlbrowser_redirect.html';
}
else {
main::INFOLOG && $log->info('No URL to play');
}
}
# play all/add all
elsif ( $client && $action && $action =~ /^(playall|addall|insert|remove)$/ ) {
$action =~ s/all$//;
my (@urls, @itemActions);
# XXX: Why is $stash->{streaminfo}->{item} added on here, it seems to be undef?
for my $item ( @{ $stash->{'items'} }, $streamItem ) {
my $url;
if ( $item->{'type'} && $item->{'type'} eq 'audio' && $item->{'url'} ) {
$url = $item->{'url'};
}
elsif ( $item->{'enclosure'} && $item->{'enclosure'}->{'url'} ) {
$url = $item->{'enclosure'}->{'url'};
}
elsif ( $item->{'play'} ) {
$url = $item->{'play'};
}
elsif ( my $itemAction = Slim::Control::XMLBrowser::findAction(undef, $item, $action) ) {
push @itemActions, $itemAction if $itemAction->{command} && $itemAction->{fixedParams};
}
next if !$url;
main::INFOLOG && $log->info("Playing/adding $url");
main::DEBUGLOG && $log->is_debug && $log->debug("item is " . Data::Dump::dump($item));
# Set metadata about this URL
Slim::Music::Info::setRemoteMetadata( $url, {
title => $item->{'name'} || $item->{'title'},
ct => $item->{'mime'},
secs => $item->{'duration'},
bitrate => $item->{'bitrate'},
cover => $item->{'cover'} || $item->{'image'} || $item->{'icon'},
year => $item->{'year'},
} );
main::idleStreams();
push @urls, $url;
}
if ( @urls || @itemActions ) {
if ( main::INFOLOG && $log->is_info ) {
$log->info(sprintf("Playing/adding all items:\n%s", Data::Dump::dump(@urls, @itemActions)));
}
if ( @itemActions ) {
my $i;
foreach my $actionItem (@itemActions) {
# if this isn't the first item, then we'll have to add the rest to the end of the list
if ($i++ && $actionItem->{fixedParams}->{cmd} =~ /load/i) {
$actionItem->{fixedParams}->{cmd} = 'add';
}
my $command = $actionItem->{command};
push @$command, map {
"$_:" . $actionItem->{fixedParams}->{$_}
} keys %{ $actionItem->{fixedParams} };
main::DEBUGLOG && $log->is_debug && $log->debug(Data::Dump::dump($command));
$client->execute($command);
}
} elsif ($action eq 'insert') {
$client->execute([ 'playlist', 'inserttracks', 'listRef', \@urls ]);
} elsif ($action eq 'remove') {
$client->execute([ 'playlist', 'deletetracks', 'listRef', \@urls ]);
} else {
$client->execute([ 'playlist', $action, \@urls ]);
}
my $webroot = $stash->{'webroot'};
$webroot =~ s/(.*?)plugins.*$/$1/;
$template = 'xmlbrowser_redirect.html';
}
else {
main::INFOLOG && $log->info('No URLs to play');
}
}
else {
# Not in use because it messes up title breadcrumbs
# if ($feed->{'actions'} && $feed->{'actions'}->{'items'}) {
# my $action = $feed->{'actions'}->{'items'};
#
# my $base = 'clixmlbrowser/clicmd=' . join('+', @{$action->{'command'}});
# if (my $params = $action->{'fixedParams'}) {
# $base .= '&' . join('&', map { $_ . '=' . $params->{$_}} keys %{$params});
# }
#
# main::INFOLOG && $log->is_info && $log->info($base);
#
# my @vars = @{$action->{'variables'} || []};
# foreach my $item (@{ $stash->{'items'} }) {
# my $link = $base;
# for (my $i = 0; $i < scalar @vars; $i += 2) {
# $link .= '&' . $vars[$i] . '=' . $item->{$vars[$i+1]};
# }
# $item->{'web'}->{'url'} = $link . '/';
# }
# }
main::INFOLOG && $log->info('Item details or list');
# Check if any of our items contain audio as well as a duration value, so we can display an
# 'All Songs' link. Lists with no duration values are lists of radio stations where it doesn't
# make sense to have an All Songs link. (bug 6531)
for my $item ( @{ $stash->{'items'} } ) {
next unless ( $item->{'type'} && $item->{'type'} eq 'audio' ) || $item->{'enclosure'} || $item->{'play'};
next unless defined $item->{'duration'} || $item->{'playall'};
$stash->{'itemsHaveAudio'} = 1;
$stash->{'currentIndex'} = $crumb[-1]->{index};
last;
}
my $itemCount = $feed->{'total'} || scalar @{ $stash->{'items'} };
my $clientId = ( $client ) ? $client->id : '';
my $crumbIndex = $crumb[-1]->{index};
$crumbIndex = '' if !defined $crumbIndex;
my $otherParams = '&index=' . $crumbIndex . '&player=' . $clientId;
if ( $stash->{'query'} ) {
$otherParams = '&query=' . $stash->{'query'} . $otherParams;
}
$stash->{'pageinfo'} = Slim::Web::Pages::Common->pageInfo({
'itemCount' => $itemCount,
'indexList' => $feed->{'indexList'},
'path' => $params->{'path'} || 'index.html',
'otherParams' => $otherParams,
'start' => $stash->{'start'},
'perPage' => $stash->{'itemsPerPage'},
});
$stash->{'path'} = $params->{'path'} || 'index.html';
my $offset = $feed->{'offset'} || 0;
my $start = $stash->{'pageinfo'}{'startitem'} || 0;
$start = $offset if ($start < $offset);
$stash->{'start'} = $start;
if ($offset || $stash->{'pageinfo'}{'totalpages'} > 1) {
my $count = scalar @{ $stash->{'items'} };
# the following ensures the original array is not altered by creating a slice to show this page only
my $finish = $stash->{'pageinfo'}{'enditem'} + 1 - $offset;
$finish = $count if ($count < $finish);
if ($start > $offset || $finish < $count) {
main::DEBUGLOG && $log->is_debug && $log->info("start=$start, offset=$offset, count=$count: cutting slice ", $start - $offset, "..$finish");
my @items = @{ $stash->{'items'} };
my @slice = @items [ $start - $offset .. $finish - 1 ];
$stash->{'items'} = \@slice;
}
else {
main::DEBUGLOG && $log->is_debug && $log->info("start=$start, offset=$offset, count=$count: no slice needed");
}
}
my $item_index = $start;
my $format = $stash->{ajaxSearch} || ($stash->{type} || '') eq 'search'
? 'TRACKNUM. TITLE - ALBUM - ARTIST'
: $prefs->get('titleFormat')->[ $prefs->get('titleFormatWeb') ];
foreach (@{ $stash->{'items'} }) {
if ( !defined $stash->{'index'} ) {
$_->{'index'} = $item_index++;
} else {
$_->{'index'} = $stash->{'index'} . $item_index++;
}
if (my $hasMetadata = $_->{'hasMetadata'}) {
if ($hasMetadata eq 'track') {
$_->{'name'} = Slim::Music::TitleFormatter::infoFormat(undef, $format, 'TITLE', $_);
} elsif ($hasMetadata eq 'album') {
$_->{'showYear'} = 1 if ($prefs->get('showYear') && $_->{'year'});
$_->{'showArtist'} = 1 if ($prefs->get('showArtist') && $_->{'artist'});
}
}
# keep track of station icons
if ( $_->{url} && !ref $_->{url}
&& ( $_->{play} || $_->{playlist} || ($_->{type} && ($_->{type} eq 'audio' || $_->{type} eq 'playlist')) )
&& $_->{url} =~ /^http/
&& $_->{url} !~ m|\.com/api/\w+/v1/opml|
&& ( my $cover = $_->{image} || $_->{cover} )
&& !Slim::Utils::Cache->new->get("remote_image_" . $_->{url})
) {
$cache->set("remote_image_" . $_->{url}, $cover, 86400);
}
}
# Find special stuff that we either want to pull up into the metadata for the
# songinfo header block or which needs unfolding.
{
my $details = {};
my $i = 0;
my $roles = join ('|', Slim::Schema::Contributor->contributorRoles());
my $allLabels = join ('|', $roles, qw(ALBUM GENRE YEAR ALBUMREPLAYGAIN ALBUMLENGTH COMPILATION));
foreach my $item ( @{ $feed->{'albumData'} || $stash->{'items'} } ) {
my $label = $item->{'label'} || '';
if ($label =~ /^($allLabels)$/) {
if ($label =~ /^($roles)$/) {
$details->{'contributors'} ||= {};
$details->{'contributors'}->{$label} ||= [];
push @{ $details->{'contributors'}->{ $label } }, {
name => $item->{'name'},
index=> $item->{'index'},
link => _makeWebLink(undef, $item, 'items', sprintf('%s (%s)', string('ARTIST'), $item->{'name'})),
};
$item->{'ignore'} = 1;
}
elsif ($label eq 'GENRE') {
$details->{'genres'} ||= [];
push @{ $details->{'genres'} }, {
name => $item->{'name'},
link => _makeWebLink(undef, $item, 'items', sprintf('%s (%s)', string($label), $item->{'name'})),
};
$item->{'ignore'} = 1;
$item->{'type'} = 'redirect';
}
else {
my $tag = lc $label;
$details->{$tag} = {
name => $item->{'name'},
};
if ($item->{'type'} ne 'text') {
$details->{$tag}->{'link'} = _makeWebLink(undef, $item, 'items', sprintf('%s (%s)', string($label), $item->{'name'}));
}
$item->{'ignore'} = 1;
$item->{'type'} = 'redirect';
# if this is a compilation, provide a link to the album with all artists
if ($label eq 'COMPILATION' && $stash->{artist_id}) {
$details->{album} = {
id => $feed->{id},
title => $feed->{name},
};
}
}
}
# unfold items which are folded for smaller UIs;
elsif ( $item->{'items'} && ($item->{'unfold'} || $item->{'web'}->{'unfold'}) ) {
$details->{'unfold'} ||= [];
my $new_index = 0;
foreach my $moreItem ( @{ $item->{'items'} } ) {
$moreItem->{'index'} = $item->{'index'} . '.' . $new_index;
$new_index++;
my $label = $moreItem->{'label'} || '';
if ($label =~ /^($allLabels)$/) {
my $tag = lc $label;
$details->{$tag} = {
name => $moreItem->{'name'},
};
if ($moreItem->{'type'} ne 'text') {
$details->{$tag}->{'link'} = _makeWebLink(undef, $moreItem, 'items', sprintf('%s (%s)', string($label), $moreItem->{'name'}));
}
$moreItem->{'ignore'} = 1;
$moreItem->{'type'} = 'redirect';
}
}
push @{ $details->{'unfold'} }, {
items => $item->{'items'},
start => $i,
};
}
$i++;
}
if (my $c = $details->{'contributors'}) {
if ($c->{'TRACKARTIST'} && $c->{'ALBUMARTIST'}) {
my $t = join(' ', (sort (map {$_->{'name'}} @{$c->{'TRACKARTIST'}})));
my $a = join(' ', (sort (map {$_->{'name'}} @{$c->{'ALBUMARTIST'}})));
delete $c->{'TRACKARTIST'} if $t eq $a;
}
}
if ($details->{'unfold'}) {
# unfold nested groups of additional items
my $new_index = 0;
foreach my $group (@{ $details->{'unfold'} }) {
splice @{ $stash->{'items'} }, ($group->{'start'} + $new_index), 1, @{ $group->{'items'} };
$new_index = $#{ $group->{'items'} };
}
delete $details->{'unfold'};
}
$feed->{'favorites_url'} ||= $stash->{'playUrl'};
if ($feed->{'hasMetadata'} && $feed->{'hasMetadata'} eq 'album' && $feed->{'albumInfo'}) {
my $morelink = _makeWebLink({ actions => $feed->{'albumInfo'} }, $feed, 'info',
sprintf('%s (%s)', string('INFORMATION'), ($feed->{'album'} || '')));
$details->{'mixersLink'} = $morelink if $morelink;
}
if (scalar keys %$details) {
# This is really just for Trackinfo
if ($stash->{'playUrl'}) {
$details->{'playLink'} = 'anyurl?p0=playlist&p1=play&p2=' .
Slim::Utils::Misc::escape($stash->{'playUrl'});
$details->{'addLink'} = 'anyurl?p0=playlist&p1=add&p2=' .
Slim::Utils::Misc::escape($stash->{'playUrl'});
$details->{'insertLink'} = 'anyurl?p0=playlist&p1=insert&p2=' .
Slim::Utils::Misc::escape($stash->{'playUrl'});
$details->{'removeLink'} = 'anyurl?p0=playlist&p1=deleteitem&p2=' .
Slim::Utils::Misc::escape($stash->{'playUrl'});
}
if ($feed->{'favorites_url'} && $favs) {
$details->{'favorites_url'} = $feed->{'favorites_url'};
$details->{'favorites'} = $favs->hasUrl($feed->{'favorites_url'}) ? 2 : 1;
}
$stash->{'songinfo'} = $details;
}
}
}
if ($favs && defined $favsItem && scalar @{$stash->{'items'}}) {
if (my $item = $stash->{'items'}->[$favsItem - ($stash->{'start'} || 0)]) {
my $furl = _favoritesUrl($item);
if ($stash->{'action'} eq 'favadd') {
my $type = $item->{'favorites_type'} || $item->{'type'} || 'link';