forked from LMS-Community/slimserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueries.pm
More file actions
6896 lines (5448 loc) · 203 KB
/
Queries.pm
File metadata and controls
6896 lines (5448 loc) · 203 KB
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::Control::Queries;
# Logitech Media Server Copyright 2001-2024 Logitech.
# Lyrion Music Server Copyright 2025 Lyrion Community.
# 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 program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
################################################################################
=head1 NAME
Slim::Control::Queries
=head1 DESCRIPTION
L<Slim::Control::Queries> implements most Lyrion Music Server queries and is designed to
be exclusively called through Request.pm and the mechanisms it defines.
Except for subscribe-able queries (such as status and serverstatus), there are no
important differences between the code for a query and one for
a command. Please check the commented command in Commands.pm.
=cut
use strict;
use File::Basename qw(basename);
use File::Spec::Functions qw(catdir);
use Storable ();
use JSON::XS::VersionOneAndTwo;
use Digest::MD5 qw(md5_hex);
use List::Util qw(first max);
use MIME::Base64 ();
use Scalar::Util qw(blessed);
use URI::Escape ();
use Tie::Cache::LRU::Expires;
use Slim::Music::VirtualLibraries;
use Slim::Utils::Misc qw( specified );
use Slim::Utils::Alarm;
use Slim::Utils::Log;
use Slim::Utils::Unicode;
use Slim::Utils::Prefs;
use Slim::Utils::Text;
use Slim::Utils::Strings qw(cstring);
use Slim::Web::ImageProxy qw(proxiedImage);
{
if (main::ISWINDOWS) {
require Slim::Utils::OS::Win32;
}
}
my $log = logger('control.queries');
my $prefs = preferences('server');
# Frequently used data can be cached in memory, such as the list of albums for Jive
my $cache = {};
# small, short lived cache of folder entries to prevent repeated disk reads on BMF
tie my %bmfCache, 'Tie::Cache::LRU::Expires', EXPIRES => 60, ENTRIES => $prefs->get('dbhighmem') ? 1024 : 5;
sub init {
my $class = shift;
# Wipe cached data after rescan
if ( !main::SCANNER ) {
Slim::Control::Request::subscribe( sub {
$class->wipeCaches;
}, [['rescan'], ['done']] );
}
}
sub alarmPlaylistsQuery {
my $request = shift;
# check this is the correct query.
if ($request->isNotQuery([['alarm'], ['playlists']])) {
$request->setStatusBadDispatch();
return;
}
# get our parameters
my $client = $request->client();
my $index = $request->getParam('_index');
my $quantity = $request->getParam('_quantity');
my $menuMode = $request->getParam('menu') || 0;
my $id = $request->getParam('id');
my $playlists = Slim::Utils::Alarm->getPlaylists($client);
my $alarm = Slim::Utils::Alarm->getAlarm($client, $id) if $id;
my $currentSetting = $alarm ? $alarm->playlist() : '';
my @playlistChoices;
my $loopname = 'item_loop';
my $cnt = 0;
my ($valid, $start, $end) = ( $menuMode ? (1, 0, scalar @$playlists) : $request->normalize(scalar($index), scalar($quantity), scalar @$playlists) );
for my $typeRef (@$playlists[$start..$end]) {
my $type = $typeRef->{type};
my @choices = ();
my $aref = $typeRef->{items};
for my $choice (@$aref) {
if ($menuMode) {
my $radio = (
( $currentSetting && $currentSetting eq $choice->{url} )
|| ( !defined $choice->{url} && !defined $currentSetting )
);
my $subitem = {
text => $choice->{title},
radio => $radio + 0,
nextWindow => 'refreshOrigin',
actions => {
do => {
cmd => [ 'alarm', 'update' ],
params => {
id => $id,
playlisturl => $choice->{url} || 0, # send 0 for "current playlist"
},
},
preview => {
title => $choice->{title},
cmd => [ 'playlist', 'preview' ],
params => {
url => $choice->{url},
title => $choice->{title},
},
},
},
};
if ( ! $choice->{url} ) {
$subitem->{actions}->{preview} = {
cmd => [ 'play' ],
};
}
if ($typeRef->{singleItem}) {
$subitem->{'nextWindow'} = 'refresh';
}
push @choices, $subitem;
}
else {
$request->addResultLoop($loopname, $cnt, 'category', $type);
$request->addResultLoop($loopname, $cnt, 'title', $choice->{title});
$request->addResultLoop($loopname, $cnt, 'url', $choice->{url});
$request->addResultLoop($loopname, $cnt, 'singleton', $typeRef->{singleItem} ? '1' : '0');
$cnt++;
}
}
if ( scalar(@choices) ) {
my $item = {
text => $type,
offset => 0,
count => scalar(@choices),
item_loop => \@choices,
};
$request->setResultLoopHash($loopname, $cnt, $item);
$cnt++;
}
}
$request->addResult("offset", $start);
$request->addResult("count", $cnt);
$request->addResult('window', { textareaToken => 'SLIMBROWSER_ALARM_SOUND_HELP' } );
$request->setStatusDone;
}
sub alarmsQuery {
my $request = shift;
# check this is the correct query.
if ($request->isNotQuery([['alarms']])) {
$request->setStatusBadDispatch();
return;
}
# get our parameters
my $client = $request->client();
my $index = $request->getParam('_index');
my $quantity = $request->getParam('_quantity');
my $filter = $request->getParam('filter');
my $alarmDOW = $request->getParam('dow');
# being nice: we'll still be accepting 'defined' though this doesn't make sense any longer
if ($request->paramNotOneOfIfDefined($filter, ['all', 'defined', 'enabled'])) {
$request->setStatusBadParams();
return;
}
$request->addResult('fade', $prefs->client($client)->get('alarmfadeseconds'));
$filter = 'enabled' if !defined $filter;
my @alarms = grep {
defined $alarmDOW
? $_->day() == $alarmDOW
: ($filter eq 'all' || ($filter eq 'enabled' && $_->enabled()))
} Slim::Utils::Alarm->getAlarms($client, 1);
my $count = scalar @alarms;
$count += 0;
$request->addResult('count', $count);
my ($valid, $start, $end) = $request->normalize(scalar($index), scalar($quantity), $count);
if ($valid) {
my $loopname = 'alarms_loop';
my $cnt = 0;
for my $alarm (@alarms[$start..$end]) {
my @dow;
foreach (0..6) {
push @dow, $_ if $alarm->day($_);
}
$request->addResultLoop($loopname, $cnt, 'id', $alarm->id());
$request->addResultLoop($loopname, $cnt, 'dow', join(',', @dow));
$request->addResultLoop($loopname, $cnt, 'enabled', $alarm->enabled());
$request->addResultLoop($loopname, $cnt, 'repeat', $alarm->repeat());
$request->addResultLoop($loopname, $cnt, 'shufflemode', $alarm->shufflemode());
$request->addResultLoop($loopname, $cnt, 'time', $alarm->time());
$request->addResultLoop($loopname, $cnt, 'volume', $alarm->volume());
$request->addResultLoop($loopname, $cnt, 'url', $alarm->playlist() || 'CURRENT_PLAYLIST');
$cnt++;
}
}
$request->setStatusDone();
}
sub _colNamesWithASMapping {
my ($c, $as, $sql) = @_;
# Add selected columns
# ** use customised 'AS' if provided in $as->{<column>} **
my @cols = sort keys %{$c};
$sql = sprintf $sql, join( ', ', map { $_ . " AS '" . ($as->{$_} || $_) . "'" } @cols );
@cols = map { $as->{$_} || $_ } @cols;
%{$c} = map { $as->{$_} ? ($as->{$_} => $c->{$_}) : ($_ => $c->{$_}) } keys %{$c};
return ($sql, @cols);
}
sub albumsQuery {
my $request = shift;
# check this is the correct query.
if ($request->isNotQuery([['albums']])) {
$request->setStatusBadDispatch();
return;
}
if (!Slim::Schema::hasLibrary()) {
$request->setStatusNotDispatchable();
return;
}
my $sqllog = main::DEBUGLOG && logger('database.sql');
# get our parameters
my $client = $request->client();
my $index = $request->getParam('_index');
my $quantity = $request->getParam('_quantity');
my $tags = $request->getParam('tags') || 'l';
my $search = $request->getParam('search');
my $compilation = $request->getParam('compilation');
my $contributorID = $request->getParam('artist_id');
my $genreID = $request->getParam('genre_id');
my $trackID = $request->getParam('track_id');
my $albumID = $request->getParam('album_id');
my $roleID = $request->getParam('role_id');
my $releaseType = $request->getParam('release_type');
my $libraryID = Slim::Music::VirtualLibraries->getRealId($request->getParam('library_id'));
my $year = $request->getParam('year');
my $sort = $request->getParam('sort') || ($roleID ? 'artistalbum' : 'album');
# a work_id of -1 would mean "all works"
my $work = $request->getParam('work_id');
my $composerID = $request->getParam('composer_id');
my $fromSearch = $request->getParam('from_search');
my $ignoreNewAlbumsCache = $search || $compilation || $contributorID || $genreID || $trackID || $albumID || $year || Slim::Music::Import->stillScanning();
# FIXME: missing genrealbum, genreartistalbum
if ($request->paramNotOneOfIfDefined($sort, ['new', 'playcount', 'recentlyplayed', 'changed', 'album', 'artflow', 'artistalbum', 'yearalbum', 'yearartistalbum', 'random'])) {
$request->setStatusBadParams();
return;
}
my $collate = Slim::Utils::OSDetect->getOS()->sqlHelperClass()->collate();
my $sql = 'SELECT %s FROM albums ';
my $c = { 'albums.id' => 1, 'albums.titlesearch' => 1, 'albums.titlesort' => 1 };
my $as = {};
my $w = [];
my $p = [];
my $order_by = "albums.titlesort $collate, albums.disc"; # XXX old code prepended 0 to titlesort, but not other titlesorts
my $limit;
my $page_key = "SUBSTR(albums.titlesort,1,1)";
my $newAlbumsCacheKey = 'newAlbumIds' . Slim::Music::Import->lastScanTime . ($libraryID || Slim::Music::VirtualLibraries->getLibraryIdForClient($client)) . $sort;
# Normalize and add any search parameters
if ( defined $trackID ) {
$sql .= 'JOIN tracks ON tracks.album = albums.id ';
push @{$w}, 'tracks.id = ?';
push @{$p}, $trackID;
}
# ignore everything if a single $album_id was specified
elsif ( defined $albumID && $albumID !~ /,/ ) {
push @{$w}, 'albums.id = ?';
push @{$p}, $albumID;
}
else {
if ( defined $albumID ) {
my @albumIds = split(',', $albumID);
push @{$w}, 'albums.id IN (' . join(',', map {'?'} @albumIds) . ')';
push @{$p}, @albumIds;
}
elsif (specified($search)) {
if ( Slim::Schema->canFulltextSearch ) {
Slim::Plugin::FullTextSearch::Plugin->createHelperTable({
name => 'albumsSearch',
search => $search,
type => 'album',
});
$sql = 'SELECT %s FROM albumsSearch, albums ';
unshift @{$w}, "albums.id = albumsSearch.id";
if ($tags ne 'CC') {
$order_by = $sort = "albumsSearch.fulltextweight DESC, LENGTH(albums.titlesearch)";
}
}
else {
my $strings = Slim::Utils::Text::searchStringSplit($search);
if ( ref $strings->[0] eq 'ARRAY' ) {
push @{$w}, '(' . join( ' OR ', map { 'albums.titlesearch LIKE ?' } @{ $strings->[0] } ) . ')';
push @{$p}, @{ $strings->[0] };
}
else {
push @{$w}, 'albums.titlesearch LIKE ?';
push @{$p}, @{$strings};
}
}
}
my @roles;
if (defined $contributorID) {
# handle the case where we're asked for the VA id => return compilations
if ($contributorID == Slim::Schema->variousArtistsObject->id) {
$compilation = 1;
}
else {
$sql .= 'JOIN contributor_album ON contributor_album.album = albums.id ';
push @{$w}, 'contributor_album.contributor = ?';
push @{$p}, $contributorID;
# only albums on which the contributor has a specific role?
if ($roleID) {
@roles = split /,/, $roleID;
push @roles, 'ARTIST' if $roleID eq 'ALBUMARTIST' && !$prefs->get('useUnifiedArtistsList');
}
elsif ($prefs->get('useUnifiedArtistsList')) {
@roles = Slim::Schema::Contributor->activeContributorRoles(1);
}
else {
@roles = Slim::Schema::Contributor->contributorRoles();
}
}
}
elsif ($roleID) {
$sql .= 'JOIN contributor_album ON contributor_album.album = albums.id ';
@roles = split /,/, $roleID;
push @roles, 'ARTIST' if $roleID eq 'ALBUMARTIST' && !$prefs->get('useUnifiedArtistsList');
}
if (scalar @roles) {
push @{$p}, map { Slim::Schema::Contributor->typeToRole($_) } @roles;
push @{$w}, 'contributor_album.role IN (' . join(', ', map {'?'} @roles) . ')';
}
if ($tags ne 'CC') {
if ( $sort =~ /^(?:new|changed|playcount|recentlyplayed)$/ ) {
$sql .= 'JOIN tracks ON tracks.album = albums.id ';
$limit = $prefs->get('browseagelimit') || 100;
$order_by = "MAX(tracks.timestamp) DESC";
# Force quantity to not exceed max
if ( $quantity && $quantity > $limit ) {
$quantity = $limit;
}
my $useStats = main::STATISTICS && $sort =~ /^(?:new|playcount|recentlyplayed)$/;
if (main::STATISTICS && $useStats) {
$sql .= 'LEFT JOIN tracks_persistent ON tracks_persistent.urlmd5 = tracks.urlmd5 ';
if ($sort eq 'new') {
$order_by = 'MIN(tracks_persistent.added) DESC';
}
elsif ($sort eq 'playcount') {
$order_by = 'albums_playcount DESC';
}
elsif ($sort eq 'recentlyplayed') {
$order_by = 'MAX(tracks_persistent.lastplayed) DESC';
}
}
# cache the most recent album IDs - need to query the tracks table, which is expensive
if ( !$ignoreNewAlbumsCache ) {
my $ids = $cache->{$newAlbumsCacheKey} || [];
if (!scalar @$ids) {
my $_cache = Slim::Utils::Cache->new;
$ids = $_cache->get($newAlbumsCacheKey) || [];
# get rid of stale cache entries
my @oldCacheKeys = grep /newAlbumIds/, keys %$cache;
foreach (@oldCacheKeys) {
next if $_ eq $newAlbumsCacheKey;
$_cache->remove($_);
delete $cache->{$_};
}
my $join = '';
$join .= "JOIN library_track ON library_track.library = '$libraryID' AND tracks.id = library_track.track " if $libraryID;
my $additionalCols = '';
if (main::STATISTICS && $useStats) {
$join .= 'LEFT JOIN tracks_persistent ON tracks_persistent.urlmd5 = tracks.urlmd5 ';
$additionalCols = ', AVG(tracks_persistent.playcount) AS albums_playcount' if $sort eq 'playcount';
}
my $countSQL = qq{
SELECT tracks.album $additionalCols
FROM tracks
$join
WHERE tracks.album > 0
GROUP BY tracks.album
ORDER BY $order_by
};
# get the list of album IDs ordered by timestamp
$ids = Slim::Schema->dbh->selectcol_arrayref( $countSQL, { Slice => {} } ) unless scalar @$ids;
$cache->{$newAlbumsCacheKey} = $ids;
$_cache->set($newAlbumsCacheKey, $ids, 86400 * 7) if scalar @$ids;
}
my $start = scalar($index);
my $end = $start + scalar($quantity || scalar($limit)-1);
if ($end >= scalar @$ids) {
$end = scalar(@$ids) - 1;
}
push @{$w}, 'albums.id IN (' . join(',', @$ids[$start..$end]) . ')';
# reset $index, as we're already limiting results using the id list
$index = 0;
}
$page_key = undef;
}
elsif ( $sort eq 'artflow' ) {
$order_by = "contributors.namesort $collate, albums.year, albums.titlesort $collate";
$c->{'contributors.namesort'} = 1;
$page_key = "SUBSTR(contributors.namesort,1,1)";
}
elsif ( $sort eq 'artistalbum' ) {
$order_by = "contributors.namesort $collate, albums.titlesort $collate";
$c->{'contributors.namesort'} = 1;
$page_key = "SUBSTR(contributors.namesort,1,1)";
}
elsif ( $sort eq 'yearartistalbum' ) {
$order_by = "albums.year, contributors.namesort $collate, albums.titlesort $collate";
$page_key = "albums.year";
}
elsif ( $sort eq 'yearalbum' ) {
$order_by = "albums.year, albums.titlesort $collate";
$page_key = "albums.year";
}
elsif ( $sort eq 'random' ) {
$limit = $prefs->get('itemsPerPage');
# Force quantity to not exceed max
if ( $quantity && $quantity > $limit ) {
$quantity = $limit;
}
$order_by = Slim::Utils::OSDetect->getOS()->sqlHelperClass()->randomFunction();
$page_key = undef;
}
}
if (defined $libraryID) {
push @{$w}, 'albums.id IN (SELECT library_album.album FROM library_album WHERE library_album.library = ?)';
push @{$p}, $libraryID;
}
if (defined $releaseType) {
my @releaseTypes = map { uc($_) } split(',', $releaseType);
push @{$w}, 'albums.release_type IN (' . join(', ', map {'?'} @releaseTypes) . ')';
push @{$p}, @releaseTypes;
}
if (defined $year) {
push @{$w}, 'albums.year = ?';
push @{$p}, $year;
}
if (defined $fromSearch && !defined $search) {
# If we've got here from a search, we don't want to show the album unless it matches all the user's search criteria.
# This matters for a Works search: we've shown the user a Work because it matches their criteria, but it is possible
# that not all albums containing the Work match the all the criteria. (In this context, a work is a group of albums.)
if ( Slim::Schema->canFulltextSearch ) {
Slim::Plugin::FullTextSearch::Plugin->createHelperTable({
name => 'albumsSearch',
search => $fromSearch,
type => 'album',
});
$sql .= "JOIN albumsSearch ON albums.id = albumsSearch.id ";
} else {
my $strings = Slim::Utils::Text::searchStringSplit($fromSearch);
if ( ref $strings->[0] eq 'ARRAY' ) {
push @{$w}, '(' . join( ' OR ', map { 'albums.titlesearch LIKE ?' } @{ $strings->[0] } ) . ')';
push @{$p}, @{ $strings->[0] };
}
else {
push @{$w}, 'albums.titlesearch LIKE ?';
push @{$p}, @{$strings};
}
}
}
if (defined $genreID) {
my @genreIDs = split(/,/, $genreID);
$sql .= 'JOIN tracks ON tracks.album = albums.id ' unless $sql =~ /JOIN tracks/;
$sql .= 'JOIN genre_track ON genre_track.track = tracks.id ';
push @{$w}, 'genre_track.genre IN (' . join(', ', map {'?'} @genreIDs) . ')';
push @{$p}, @genreIDs;
}
if (defined $compilation) {
if ($compilation == 1) {
push @{$w}, 'albums.compilation = 1';
}
else {
push @{$w}, '(albums.compilation IS NULL OR albums.compilation = 0)';
}
}
}
if ($work) {
$sql .= 'JOIN tracks ON tracks.album = albums.id ' unless $sql =~ /JOIN tracks/;
$sql .= 'JOIN works ON tracks.work = works.id ' unless $sql =~ /JOIN works/;
$sql .= 'JOIN contributors AS composer ON works.composer = composer.id ' ;
$sql .= 'JOIN contributor_track ON contributor_track.track = tracks.id ' unless $sql =~ /JOIN contributor_track/;
$c->{'tracks.work'} = 1;
$c->{'works.title'} = 1;
$c->{'composer.name'} = 1;
$c->{'tracks.performance'} = 1;
$order_by .= ", tracks.tracknum";
# -1 -> all works
if ($work ne '-1') {
push @{$w}, 'tracks.work = ?';
push @{$p}, $work;
if ( defined $composerID ) {
push @{$w}, 'contributor_track.contributor = ? AND contributor_track.role = 2';
push @{$p}, $composerID;
}
}
}
if ( $tags =~ /l/ ) {
# title/disc/discc is needed to construct (N of M) title
map { $c->{$_} = 1 } qw(albums.title albums.disc albums.discc);
}
if ( $tags =~ /y/ ) {
$c->{'albums.year'} = 1;
}
if ( $tags =~ /j/ ) {
$c->{'albums.artwork'} = 1 if !$work;
$c->{'tracks.coverid'} = 1 if $work;
}
if ( $tags =~ /t/ ) {
$c->{'albums.title'} = 1;
}
if ( $tags =~ /i/ ) {
$c->{'albums.disc'} = 1;
}
if ( $tags =~ /q/ ) {
$c->{'albums.discc'} = 1;
}
if ( $tags =~ /w/ ) {
$c->{'albums.compilation'} = 1;
}
my $wantsReleaseTypes = !$prefs->get('ignoreReleaseTypes');
if ( $tags =~ /W/ && $wantsReleaseTypes ) {
$c->{'albums.release_type'} = 1;
}
if ( $tags =~ /E/ ) {
$c->{'albums.extid'} = 1;
}
if ( $tags =~ /X/ ) {
$c->{'albums.replay_gain'} = 1;
}
if ( $tags =~ /R|S|a/ ) {
$c->{'albums.contributor'} = 1;
}
if ( $tags ne 'CC' ) {
# We need the main albums.contributor name for favorites, so always do this join unless getting count only.
$sql .= 'JOIN contributors ON contributors.id = albums.contributor ';
$c->{'contributors.name'} = 1;
}
if ( $tags =~ /s/ ) {
$c->{'albums.titlesort'} = 1;
}
if ( $tags =~ /2/ ) {
my $col = '(SELECT COUNT(1) FROM (SELECT 1 FROM tracks WHERE tracks.album=albums.id GROUP BY work,grouping,performance))';
$c->{$col} = 1;
$as->{$col} = 'group_count';
$col = "(SELECT GROUP_CONCAT(COALESCE(SUBSTR('00000'||disc,-5),'00001') || SUBSTR('00000'||tracknum,-5) || COALESCE(work,'') || '##' || COALESCE(performance,'') || '##' || COALESCE(grouping,''),',,') FROM tracks WHERE tracks.album = albums.id)";
$c->{$col} = 1;
$as->{$col} = 'group_structure';
}
if ( $tags =~ /4/ && !$work ) {
$c->{'contributors.portraitid'} = 1;
}
if ( main::STATISTICS && $sort eq 'playcount' ) {
$c->{'AVG(tracks_persistent.playcount)'} = 1;
$as->{'AVG(tracks_persistent.playcount)'} = 'albums_playcount';
}
if ( @{$w} ) {
$sql .= 'WHERE ';
my $s .= join( ' AND ', @{$w} );
$s =~ s/\%/\%\%/g;
$sql .= $s . ' ';
}
my $dbh = Slim::Schema->dbh;
$sql .= $work ? "GROUP BY tracks.performance, tracks.work, albums.id " : "GROUP BY albums.id ";
if ($page_key && $tags =~ /Z/) {
$request->addResult('indexList', _createIndexList(sprintf($sql, "$page_key AS n") . " ORDER BY $order_by", $p));
if ($tags =~ /ZZ/) {
$request->setStatusDone();
return
}
}
$sql .= "ORDER BY $order_by " unless $tags eq 'CC';
($sql, my @cols) = _colNamesWithASMapping($c, $as, $sql);
my $stillScanning = Slim::Music::Import->stillScanning();
# Get count of all results, the count is cached until the next rescan done event
my $cacheKey = _buildCacheKey($sql, $p, $search, $client);
if ( $sort =~ /^(?:new|changed|playcount|recentlyplayed)$/ && $cache->{$newAlbumsCacheKey} && !$ignoreNewAlbumsCache ) {
my $albumCount = scalar @{$cache->{$newAlbumsCacheKey}};
$albumCount = $limit if ($limit && $limit < $albumCount);
$cache->{$cacheKey} ||= $albumCount;
$limit = undef;
}
my $countsql = $sql;
$countsql .= ' LIMIT ' . $limit if $limit;
my $count = $cache->{$cacheKey};
if ( !$count ) {
my $total_sth = $dbh->prepare_cached( qq{
SELECT COUNT(1) FROM ( $countsql ) AS t1
} );
if ( main::DEBUGLOG && $sqllog->is_debug ) {
$sqllog->debug( "Albums totals query: $countsql / " . Data::Dump::dump($p) );
}
$total_sth->execute( @{$p} );
($count) = $total_sth->fetchrow_array();
$total_sth->finish;
if ( !$stillScanning ) {
$cache->{$cacheKey} = $count;
}
}
if ($stillScanning) {
$request->addResult('rescan', 1);
}
$count += 0;
# now build the result
my ($valid, $start, $end) = $request->normalize(scalar($index), scalar($quantity), $count);
my $loopname = 'albums_loop';
my $chunkCount = 0;
if ($valid && $tags ne 'CC') {
# We need to know the 'No album' name so that those items
# which have been grouped together under it do not get the
# album art of the first album.
# It looks silly to go to Madonna->No album and see the
# picture of '2 Unlimited'.
my $noAlbumName = $request->string('NO_ALBUM');
# Limit the real query
if ($limit && !$quantity) {
$quantity = "$limit";
$index ||= "0";
}
if ( $index =~ /^\d+$/ && defined $quantity && $quantity =~ /^\d+$/ ) {
$sql .= "LIMIT ?,? ";
push @$p, $index, $quantity;
}
if ( main::DEBUGLOG && $sqllog->is_debug ) {
$sqllog->debug( "Albums query: $sql / " . Data::Dump::dump($p) );
}
my $sth = $dbh->prepare_cached($sql);
$sth->execute( @{$p} );
# Bind selected columns in order
my $i = 1;
for my $col ( @cols ) {
$sth->bind_col( $i++, \$c->{$col} );
}
# Little function to construct nice title from title/disc counts
my $groupdiscs_pref = $prefs->get('groupdiscs');
my $construct_title = $groupdiscs_pref ? sub {
return $c->{'albums.title'};
} : sub {
return Slim::Music::Info::addDiscNumberToAlbumTitle(
$c->{'albums.title'}, $c->{'albums.disc'}, $c->{'albums.discc'}
);
};
my ($contributorSql, $contributorSth, $contributorNameSth, $contributorRoleSth, @linkRoleIds);
if ( $tags =~ /(?:aa|SS)/ ) {
# Override $contributorSql if we're dealing with a Work: output Artist, Orchestra, Conductor in that order.
if ($work) {
@linkRoleIds = map { Slim::Schema::Contributor->typeToRole($_) } ( 'ARTIST', 'BAND', 'CONDUCTOR' );
$contributorSql = sprintf( qq{
SELECT contributor_track.role AS role, contributors.name AS name, contributors.id AS id
FROM tracks
JOIN contributor_track ON tracks.id = contributor_track.track
JOIN contributors ON contributors.id = contributor_track.contributor
WHERE tracks.album = :album AND tracks.work = :work
AND ( (:performance IS NULL AND tracks.performance IS NULL) OR tracks.performance = :performance )
AND contributor_track.role IN (%s)
GROUP BY contributor_track.role, contributors.name, contributors.id
ORDER BY contributor_track.role, contributors.namesort
},
join(',', @linkRoleIds));
} else {
my @linkRoles = Slim::Schema::Contributor->allAlbumLinkRoles();
# when filtering by role and not by contributor, put that role at the head of the list if it wasn't in there yet
if ($roleID && !$contributorID) {
unshift @linkRoles, map { Slim::Schema::Contributor->roleToType($_) || $_ } split(/,/, $roleID);
@linkRoles = Slim::Utils::Misc::uniq(@linkRoles);
}
@linkRoleIds = map { Slim::Schema::Contributor->typeToRole($_) } @linkRoles;
$contributorSql = sprintf( qq{
SELECT contributor_album.role AS role, contributors.name AS name, contributors.id AS id
FROM contributor_album
JOIN contributors ON contributors.id = contributor_album.contributor
WHERE contributor_album.album = :album
AND contributor_album.role IN (%s)
ORDER BY contributor_album.role, contributors.namesort
}, join(',', @linkRoleIds) );
}
}
my $vaObjId = Slim::Schema->variousArtistsObject->id;
while ( $sth->fetch ) {
utf8::decode( $c->{'albums.title'} ) if exists $c->{'albums.title'};
utf8::decode( $c->{'works.title'} ) if exists $c->{'works.title'};
utf8::decode( $c->{'composer.name'} ) if exists $c->{'composer.name'};
utf8::decode( $c->{'tracks.performance'} ) if exists $c->{'tracks.performance'};
utf8::decode( $c->{'contributors.name'} ) if exists $c->{'contributors.name'};
$request->addResultLoop($loopname, $chunkCount, 'id', $c->{'albums.id'});
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'work_id', $c->{'tracks.work'});
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'work_name', $c->{'works.title'});
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'composer', $c->{'composer.name'});
$request->addResultLoop($loopname, $chunkCount, 'performance', $c->{'tracks.performance'}||"");
my $favoritesUrl = $work
? sprintf('db:album.title=%s&contributor.name=%s&work.title=%s&composer.name=%s&track.performance=%s',
URI::Escape::uri_escape_utf8($c->{'albums.title'}), URI::Escape::uri_escape_utf8($c->{'contributors.name'}),
URI::Escape::uri_escape_utf8($c->{'works.title'}), URI::Escape::uri_escape_utf8($c->{'composer.name'}), URI::Escape::uri_escape_utf8($c->{'tracks.performance'}))
: sprintf('db:album.title=%s&contributor.name=%s', URI::Escape::uri_escape_utf8($c->{'albums.title'}), URI::Escape::uri_escape_utf8($c->{'contributors.name'}));
# even if we have an extid, it cannot be used when we're dealing here with a work, which is a subset of the album.
$request->addResultLoop($loopname, $chunkCount, 'favorites_url', $c->{'albums.extid'} && !$c->{'tracks.work'} ? $c->{'albums.extid'} : $favoritesUrl);
my $favoritesTitle = $c->{'albums.title'};
if ( $work ) {
$favoritesTitle = $c->{'composer.name'} ? $c->{'composer.name'} . cstring($client, 'COLON') . ' ' : '';
$favoritesTitle .= $c->{'works.title'} . ' (';
$favoritesTitle .= "$c->{'tracks.performance'} " if $c->{'tracks.performance'};
$favoritesTitle .= cstring($client,'FROM') . ' ' . $c->{'albums.title'} . ')';
}
$request->addResultLoop($loopname, $chunkCount, 'favorites_title', $favoritesTitle);
$tags =~ /l/ && $request->addResultLoop($loopname, $chunkCount, 'album', $construct_title->());
$tags =~ /y/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'year', $c->{'albums.year'});
if ($tags =~ /j/) {
my $albumCover = $c->{'tracks.coverid'} ? $c->{'tracks.coverid'} : $c->{'albums.artwork'};
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'artwork_track_id', $albumCover) if ($albumCover || '') !~ /^https?:/;
}
$tags =~ /K/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'artwork_url', $c->{'albums.artwork'}) if ($c->{'albums.artwork'} || '') =~ /^https?:/;
$tags =~ /t/ && $request->addResultLoop($loopname, $chunkCount, 'title', $c->{'albums.title'});
$tags =~ /i/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'disc', $c->{'albums.disc'});
$tags =~ /q/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'disccount', $c->{'albums.discc'});
$tags =~ /w/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'compilation', $c->{'albums.compilation'});
$tags =~ /W/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'release_type', $wantsReleaseTypes ? $c->{'albums.release_type'} : 'ALBUM');
$tags =~ /E/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'extid', $c->{'albums.extid'});
$tags =~ /X/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'album_replay_gain', $c->{'albums.replay_gain'});
if ( $tags =~ /2/ ) {
my $nonContiguous;
if ( $c->{'group_count'} > 1 ) {
my $previousGroup;
my $groupSeen = {};
foreach ( sort split(',,', $c->{'group_structure'}) ) {
my $thisTrackGroup = substr($_, 10);
if ( $previousGroup ne $thisTrackGroup ) {
if ( $nonContiguous = $groupSeen->{$thisTrackGroup} && $thisTrackGroup ne '####' ) {
last;
}
else {
$groupSeen->{$thisTrackGroup} = 1;
$previousGroup = $thisTrackGroup;
}
}
}
}
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'group_count', $c->{'group_count'});
$request->addResultLoop($loopname, $chunkCount, 'contiguous_groups', $nonContiguous ? 0 : 1);
}
#Don't use albums.contributor to set artist_id/artist for Works, it may well be completely wrong!
if ( !$work ) {
$tags =~ /S/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'artist_id', $c->{'albums.contributor'});
$tags =~ /a/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'artist', $c->{'contributors.name'});
$tags =~ /4/ && $request->addResultLoopIfValueDefined($loopname, $chunkCount, 'portraitid', $c->{'contributors.portraitid'});
}
if ($tags =~ /s/) {
#FIXME: see if multiple char textkey is doable for year/genre sort
my $textKey;
if ($sort eq 'artflow' || $sort eq 'artistalbum') {
utf8::decode( $c->{'contributors.namesort'} ) if exists $c->{'contributors.namesort'};
$textKey = substr $c->{'contributors.namesort'}, 0, 1;
} elsif ( $sort eq 'album' ) {
utf8::decode( $c->{'albums.titlesort'} ) if exists $c->{'albums.titlesort'};
$textKey = substr $c->{'albums.titlesort'}, 0, 1;
}
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'textkey', $textKey);
}
# want multiple artists?
if ( $contributorSql && $c->{'albums.contributor'} != $vaObjId && !$c->{'albums.compilation'} ) {
$contributorSth ||= $dbh->prepare_cached($contributorSql);
$contributorSth->bind_param(":album", $c->{'albums.id'});
if ( $work ) {
$contributorSth->bind_param(":work", $work);
$contributorSth->bind_param(":performance", $c->{'tracks.performance'}||undef);
}
my $contributorArray = $dbh->selectall_arrayref($contributorSth,{ Slice => {} });
my $contributorHash = {};
foreach (@$contributorArray) {
push @{$contributorHash->{$_->{'role'}}->{'id'}}, $_->{'id'};
push @{$contributorHash->{$_->{'role'}}->{'name'}}, $_->{'name'};
}
my @artists;
my @artistIds;
foreach my $role ( @linkRoleIds ) {
if ($contributorHash->{$role}) {
push @artists, map { utf8::decode($_); $_ } @{$contributorHash->{$role}->{'name'}};
push @artistIds, @{$contributorHash->{$role}->{'id'}};
}
}
# if not dealing with a work, put the main album artist at the top of the list
if (!$work) {
unshift @artists, $c->{'contributors.name'} if $c->{'contributors.name'};
unshift @artistIds, $c->{'albums.contributor'} if $c->{'albums.contributor'};
}
@artists = Slim::Utils::Misc::uniq(@artists);
@artistIds = Slim::Utils::Misc::uniq(@artistIds);
# XXX - what if the artist name itself contains ','?
if ( $tags =~ /aa/ && scalar @artists ) {
my $artists = join(',',@artists);
utf8::decode($artists);
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'artist', (split(/,/, $artists))[0]) if $work;
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'artists', $artists);
}
if ( $tags =~ /SS/ && scalar @artistIds ) {
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'artist_id', @artistIds[0]) if $work;
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'artist_ids', join(',',@artistIds));
}
}
if ( $tags =~ /R/ ) {
my $rolesRef;
my $contributorRoleSql = "SELECT role FROM contributor_album WHERE album = ?";
if ( $contributorID ) {
$contributorRoleSql .= " AND contributor = ?";
$contributorRoleSth ||= $dbh->prepare_cached($contributorRoleSql);
$rolesRef = $dbh->selectall_arrayref( $contributorRoleSth, undef, ($c->{'albums.id'}, $contributorID) );
} else {
$contributorRoleSth ||= $dbh->prepare_cached($contributorRoleSql);
$rolesRef = $dbh->selectall_arrayref( $contributorRoleSth, undef, ($c->{'albums.id'}) );
}
if ($rolesRef) {
my $roles = join(',', map { $_->[0] } @$rolesRef);
$request->addResultLoopIfValueDefined($loopname, $chunkCount, 'role_ids', $roles);
}
}
$chunkCount++;
main::idleStreams() if !($chunkCount % 5);
}
}
$request->addResult('count', $count);
$request->setStatusDone();
}
sub artistsQuery {
my $request = shift;
# check this is the correct query.
if ($request->isNotQuery([['artists']])) {
$request->setStatusBadDispatch();
return;
}
if (!Slim::Schema::hasLibrary()) {
$request->setStatusNotDispatchable();
return;
}
my $sqllog = main::DEBUGLOG && logger('database.sql');