This repository was archived by the owner on Mar 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathcantata-dynamic
More file actions
executable file
·1586 lines (1479 loc) · 51.8 KB
/
cantata-dynamic
File metadata and controls
executable file
·1586 lines (1479 loc) · 51.8 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
#!/usr/bin/perl
# Cantata-Dynamic
#
# Copyright (c) 2011-2016 Craig Drummond <craig.p.drummond@gmail.com>
#
# ----
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
use IO::Socket::IP;
use POSIX;
use File::stat;
use File::Basename;
use Cwd 'abs_path';
use Socket;
use IO::Socket;
use threads;
use threads::shared;
use URI::Escape;
use Encode;
use Socket qw(:all);
my $isServerMode =0;
my $dynamicIsActive =1;
my $currentStatus ="IDLE";
$testMode=0;
$MIN_PLAY_QUEUE_DESIRED_LENGTH=10;
$MAX_PLAY_QUEUE_DESIRED_LENGTH=500;
$DEFAULT_PLAY_QUEUE_DESIRED_LENGTH=10;
$playQueueDesiredLength=$DEFAULT_PLAY_QUEUE_DESIRED_LENGTH;
my $mpdHost : shared = "localhost";
my $mpdPort : shared = "6600";
my $mpdPasswd : shared ="";
my $readChannel : shared = "cantata-dynamic-in";
my $writeChannel = "cantata-dynamic-out";
my $sock; # This is NOT shared between HTTP thread and standard thread...
my $currentStatusTime = time;
my $httpPort : shared = 0;
# Read MPDs host, port, and password details from env - if set
sub readConnectionDetails() {
my $hostEnv=$ENV{'MPD_HOST'};
my $portEnv=$ENV{'MPD_PORT'};
if (length($portEnv)>2) {
$mpdPort=$portEnv;
}
if (length($hostEnv)>2) {
my $sep = index($hostEnv, '@');
if ($sep>0) {
$mpdPasswd=substr($hostEnv, 0, $sep);
$mpdHost=substr($hostEnv, $sep+1, length($hostEnv)-$sep);
} else {
$mpdHost=$hostEnv;
}
}
}
sub readReply() {
local $data;
my $socketData;
while ($sock->connected()) {
$sock->recv($data, 1024);
if (! $data) {
return '';
}
$socketData="${socketData}${data}";
$data="";
if (($socketData=~ m/(OK)$/) || ($socketData=~ m/^(OK)/)) {
return $socketData;
} elsif ($socketData=~ m/^(ACK)/) {
return '';
}
}
}
# Connect to MPD
sub connectToMpd() {
if ($testMode==1) { print "Connecting to MPD ${mpdHost}:${mpdPort}\n"; }
my $connDetails="";
if ($mpdHost=~ m/^(\/)/) {
$sock = new IO::Socket::UNIX(Peer => $mpdHost, Type => 0);
$connDetails=$mpdHost;
} else {
$sock = new IO::Socket::IP(PeerAddr => $mpdHost, PeerPort => $mpdPort, Proto => 'tcp');
$connDetails="${mpdHost}:${mpdPort}";
}
if ($sock && $sock->connected()) {
if (&readReply($sock)) {
if ($mpdPasswd) {
if ($testMode==1) { print "Send password\n"; }
$sock->send("password ${mpdPasswd} \n");
if (! &readReply($sock)) {
print "ERROR: Invalid password\n";
eval { close $sock; };undef $sock;
}
}
if ($isServerMode==1) {
$sock->send("subscribe ${readChannel}\n");
&readReply($sock)
}
} else {
print "ERROR: Failed to read connection reply fom MPD (${connDetails})\n";
close($sock);
}
} else {
print "ERROR: Failed to connect to MPD (${connDetails})\n";
}
return $sock;
}
sub sendCommand() {
my $cmd = shift;
if ($testMode==1) { print "Send command ${cmd}\n"; }
my $status = 0;
if (! ($sock && $sock->connected())) {
$sock=&connectToMpd();
}
my $sockData;
$cmd="${cmd}\n";
if ($sock && $sock->connected()) {
print $sock encode('utf-8' => $cmd);
$sockData=&readReply($sock);
}
my $dataLen=length($sockData);
if ($testMode==1) { print "Received ${dataLen} bytes\n"; }
if ($sockData ne '') {
return decode_utf8($sockData);
}
return $sockData;
}
sub waitForEvent() {
while (1) {
if (! ($sock && $sock->connected())) {
$sock=&connectToMpd();
}
if ($sock && $sock->connected()) {
if (0==$isServerMode) {
&sendCommand("idle player playlist");
return 1;
} else {
my $sockData=&sendCommand("idle player playlist message");
my @lines = split("\n", $sockData);
my $haveNonMsg=0;
foreach my $line (@lines) {
if ($line=~ m/^(changed\:\ message)/) {
&handleClientMessage();
} else {
$haveNonMsg=1;
if ($testMode==1) { printf "Idle message: $line\n"; }
}
}
if ($haveNonMsg==1) {
return 1;
}
}
} else {
return 0;
}
}
}
sub getEntries() {
my $command=shift;
my $key=shift;
my @entries = ();
my $data=&sendCommand($command);
if (defined($data)) {
my @lines=split('\n', $data);
foreach my $line (@lines) {
if ($line=~ m/^($key\:)/) {
my $sep = index($line, ':');
if ($sep>0) {
my $entry=substr($line, $sep+2, length($line)-($sep+1));
push (@entries, $entry);
}
}
}
}
return @entries;
}
sub baseDir() {
if ($^O eq "darwin") {
# MacOSX
return "$ENV{'HOME'}/Library/Caches/cantata/cantata/dynamic";
}
# Linux
my $cacheDir=$ENV{'XDG_CACHE_HOME'};
if (!$cacheDir) {
$cacheDir="$ENV{'HOME'}/.cache";
}
$cacheDir="${cacheDir}/cantata/dynamic";
return $cacheDir
}
sub lockFile() {
my $fileName=&baseDir();
$fileName="${fileName}/lock";
return $fileName;
}
$lastArtistSearch="";
@artistSearchResults=();
$api_key="5a854b839b10f8d46e630e8287c2299b";
# Query LastFM for artists similar to supplied artist
sub querySimilarArtists() {
my $artist=uri_escape(shift);
if ($artist ne $lastArtistSearch) {
@artistSearchResults=();
@artists=`wget "https://ws.audioscrobbler.com/2.0/?method=artist.getSimilar&api_key=${api_key}&artist=${artist}&format=xml&limit=50" -O - | grep "<artist><name>" | grep -v "similarartists artist"`;
foreach my $artist (@artists) {
$artist =~ s/<artist><name>//g;
$artist =~ s/<\/name>//g;
$artist =~ s/&/&/g;
$artist =~ s/\n//g;
$artistSearchResults[$artistNum]=$artist;
$artistNum++;
}
}
}
$mpdDbUpdated=0;
$rulesChanged=1;
$includeRules;
$excludeRules;
$lastIncludeRules;
$lastExcludeRules;
$initialRead=1;
$rulesTimestamp=0;
$numMpdSongs=0;
$ratingFrom=0;
$ratingTo=0;
$lastRatingFrom=0;
$lastRatingTo=0;
$includeUnrated=0;
$minDuration=0;
$maxDuration=0;
$lastMinDuration=0;
$lastMaxDuration=0;
# Determine if rules file has been updated
sub checkRulesChanged() {
if ($initialRead==1) { # Always changed on first run...
$rulesChanged=1;
$initialRead=0;
} elsif ($lastRatingFrom!=$ratingFrom || $lastRatingTo!=$ratingTo) {
$rulesChanged=1;
} elsif ($lastMinDuration!=$minDuration || $lastMaxDuration!=$maxDuration) {
$rulesChanged=1;
} elsif ( scalar(@lastIncludeRules)!=scalar(@includeRules) ||
scalar(@lastExcludeRules)!=scalar(@excludeRules)) { # Different number of rules
$rulesChanged=1;
} else { # Same number of rules, so need to check if the rules themselves have changed or not...
$rulesChanged=0;
for (my $i=0; $i<scalar(@includeRules) && $rulesChanged==0; $i++) {
if ($includeRules[$i] ne $lastIncludeRules[$i]) {
$rulesChanged=1;
}
}
for (my $i=0; $i<scalar(@excludeRules) && $rulesChanged==0; $i++) {
if ($excludeRules[$i] ne $lastExcludeRules[$i]) {
$rulesChanged=1;
}
}
}
@lastIncludeRules=@includeRules;
@lastExcludeRules=@excludeRules;
}
# Add a rule to the list of rules that will be used to query MPD
sub saveRule() {
my $rule=$_[0];
my @dates=@{ $_[1] };
my @artistList=@{ $_[2] };
my @genreList=@{ $_[3] };
my $ruleMatch=$_[4];
my $isInclude=$_[5];
my $maxAge=$_[6];
my @type=();
if ($isInclude == 1) {
@type=@includeRules;
} else {
@type=@excludeRules;
}
# We iterate through the list of artists - so if this is empty, add a blank artist.
# artistList will only be set if we have been told to find tracks by similar artists...
if (scalar(@artistList)==0) {
$artistList[0]="";
}
if (scalar(@genreList)==0) {
$genreList[0]="";
}
my $ruleNum=scalar(@type);
for my $genre (@genreList) {
for my $artist (@artistList) {
$line =~ s/\"//g;
if (scalar(@dates)>0) { # Create rule for each date (as MPDs search does not take ranges)
my $baseRule=$rule;
foreach my $date (@dates) {
$type[$ruleNum]="${ruleMatch} ${baseRule} Date \"${date}\"";
if ($artist ne "") {
$type[$ruleNum]=$type[$ruleNum]." Artist \"${artist}\"";
}
if ($genre ne "") {
$type[$ruleNum]=$type[$ruleNum]." Genre \"${genre}\"";
}
if ($isInclude && $maxAge>0) {
$type[$ruleNum]=$type[$ruleNum]." modified-since ${maxAge}";
}
$ruleNum++;
}
} elsif ($artist ne "" || $genre ne "" || $rule ne "" || ($isInclude && $maxAge>0)) {
$type[$ruleNum]="${ruleMatch} $rule";
if ($artist ne "") {
$type[$ruleNum]=$type[$ruleNum]." Artist \"${artist}\"";
}
if ($genre ne "") {
$type[$ruleNum]=$type[$ruleNum]." Genre \"${genre}\"";
}
if ($maxAge>0) {
$type[$ruleNum]=$type[$ruleNum]." modified-since ${maxAge}";
}
$ruleNum++;
}
}
}
if ($isInclude == 1) {
@includeRules=@type;
} else {
@excludeRules=@type;
}
}
# Read rules from ~/.cache/cantata/dynamic/rules
# (or from ${filesDir}/rules in server mode)
#
# File format:
#
# Rating:<Range>
# Duration:<Range>
# Rule
# <Tag>:<Value>
# <Tag>:<Value>
# Rule
#
# e.g.
#
# Rating:1-5
# Duration:30-900
# Rule
# AlbumArtist:Various Artists
# Genre:Dance
# Rule
# AlbumArtist:Wibble
# Date:1980-1989
# Exact:false
# Exclude:true
#
$activeFile="";
$activeLinksTo="";
sub readRules() {
if ($activeFile eq "") {
$activeFile=&baseDir();
$activeFile="${activeFile}/rules";
}
unless (-e $activeFile) {
$rulesChanged=0;
return;
}
# Check if rules (well, the file it points to), has changed since the last read...
my $currentActiveLink=abs_path($activeFile);
$fileTime = stat($currentActiveLink)->mtime;
if ($initialRead!=1 && $fileTime==$rulesTimestamp && $activeLinksTo eq $currentActiveLink) {
# No change, so no need to read it again!
$rulesChanged=0;
return;
}
$activeLinksTo=$currentActiveLink;
$rulesTimestamp=$fileTime;
for(my $i=0; $i<10; $i++) {
open(my $fileHandle, "<:encoding(utf8)", $activeFile);
if (tell($fileHandle) != -1) {
my @lines = <$fileHandle>; # Read into an array...
my $ruleMatch="find";
my @dates=();
my @similarArtists=();
my $isInclude=1;
my $currentRule="";
my $maxAge=0;
@includeRules=();
@excludeRules=();
$ratingFrom=0;
$ratingTo=0;
$includeUnrated=0;
$minDuration=0;
$maxDuration=0;
$playQueueDesiredLength=$DEFAULT_PLAY_QUEUE_DESIRED_LENGTH;
close($fileHandle);
foreach my $line (@lines) {
if (! ($line=~ m/^(#)/)) {
$line =~ s/\n//g;
my $sep = index($line, ':');
if ($sep>0) {
$key=substr($line, 0, $sep);
$val=substr($line, $sep+1, length($line)-$sep);
} else {
$key=$line;
$val="";
}
if ($key=~ m/^(Rule)/) { # New rule...
if (length($currentRule)>1 || scalar(@similarArtists)>0 || scalar(@dates)>0 || scalar(@genres)>0) {
&saveRule($currentRule, \@dates, \@similarArtists, \@genres, $ruleMatch, $isInclude, $maxAge);
}
$currentRule="";
@dates=();
@similarArtists=();
@genres=();
$isInclude=1;
$ruleMatch="find";
} elsif ($key=~ m/^(Rating)/) {
my @vals = split("-", $val);
if (scalar(@vals)==2) {
$ratingFrom=int($vals[0]);
$ratingTo=int($vals[1]);
if ($ratingFrom > $ratingTo) {
my $tmp=$ratingFrom;
$ratingFrom=$ratingTo;
$ratingTo=$tmp;
}
# Check id we have a rating range of 0..MAX - if so, then we need to include
# all songs => cant't filter on rating. Issue #1334
if ($ratingFrom == 0 && $ratingTo == 10) {
$ratingTo = 0;
}
}
} elsif ($key=~ m/^(IncludeUnrated)/) {
$includeUnrated = $val eq "true";
} elsif ($key=~ m/^(Duration)/) {
my @vals = split("-", $val);
if (scalar(@vals)==2) {
$minDuration=int($vals[0]);
$maxDuration=int($vals[1]);
if ($minDuration > $maxDuration && $maxDuration > 0 ) {
my $tmp=$minDuration;
$minDuration=$maxDuration;
$maxDuration=$tmp;
}
}
} elsif ($key=~ m/^(NumTracks)/) {
if ($val >= $MIN_PLAY_QUEUE_DESIRED_LENGTH && $val <= $MAX_PLAY_QUEUE_DESIRED_LENGTH) {
$playQueueDesiredLength=$val;
if ($playQueueDesiredLength % 2 > 0) {
$playQueueDesiredLength += 1;
}
}
} elsif ($key=~ m/^(MaxAge)/) {
if ($val > 0) {
$maxAge = time() - ($val * 24 * 60 * 60);
}
} else {
if ($key eq "Date") {
my @dateVals = split("-", $val);
if (scalar(@dateVals)==2) {
my $fromDate=int($dateVals[0]);
my $toDate=int($dateVals[1]);
if ($fromDate > $toDate) { # Fix dates if from>to!!!
my $tmp=$fromDate;
$fromDate=$toDate;
$toDate=$tmp;
}
my $pos=0;
for(my $d=$fromDate; $d<=$toDate; $d++) {
$dates[$pos]=$d;
$pos++;
}
} else {
@dates=($val)
}
} elsif ($key eq "Genre" && $val =~ m{\*}) {
# Wildcard genre - get list of genres from MPD, and find the ones that contain the genre string.
$val =~ s/\*//g;
my @mpdGenres = &getEntries("list genre", 'Genre');
my $pos=0;
foreach my $genre (@mpdGenres) {
if ($genre ne "" && $genre =~/$val/i) {
$genres[$pos]=$genre;
$pos++;
}
}
if ($pos == 0) {
# No genres matching pattern - add dummy genre, so that no tracks will be found
$genres[$pos]="XXXXXXXX";
}
} elsif ($key eq "Artist" || $key eq "Album" || $key eq "AlbumArtist" || $key eq "Composer" || $key eq "Comment" || $key eq "Title" || $key eq "Genre" || $key eq "File") {
$currentRule="${currentRule} ${key} \"${val}\"";
} elsif ($key eq "SimilarArtists") {
&querySimilarArtists($val); # Perform a last.fm query to find similar artists
@artistSearchResults; # Save results of query
@artistSearchResults=uniq(@artistSearchResults); # Ensure we only have unique entries...
if (scalar(@artistSearchResults)>1) {
my @mpdArtists = ();
my $pos=0;
# Get MPD artists...
my @mpdResponse=&getEntries("list artist", 'Artist');
foreach my $artist (@mpdResponse) {
if ($artist ne "" && $artist ne $val) {
$mpdArtists[$pos]=$artist;
$pos++;
}
}
@mpdArtists=uniq(@mpdArtists);
# Now check which last.fm artists MPD actually has...
my $pos=0;
foreach my $artist (@artistSearchResults) {
my @match = grep(/^$artist/i, @mpdArtists);
if (scalar(@match)>0) {
$similarArtists[$pos]=$artist;
$pos++;
}
}
}
$similarArtists[scalar(@similarArtists)]=$val; # Add ourselves!!!
} elsif ($key eq "Exact" && $val eq "false") {
$ruleMatch="search";
} elsif ($key eq "Exclude" && $val eq "true") {
$isInclude=0;
}
}
}
}
if (length($currentRule)>1 || scalar(@similarArtists)>0 || scalar(@dates)>0 || scalar(@genres)>0) {
&saveRule($currentRule, \@dates, \@similarArtists, \@genres, $ruleMatch, $isInclude, $maxAge);
} elsif ($maxAge>0 && 0 == scalar(@includeRules)) {
&saveRule("", "", "", "", "find", 1, $maxAge); # No include rules but have max-age, so create a rule
}
if (1==$testMode) {
print "INCLUDE--------------\n";
foreach my $rule (@includeRules) {
print "${rule}\n";
}
print "EXCLUDE--------------\n";
foreach my $rule (@excludeRules) {
print "${rule}\n";
}
print "---------------------\n";
print "RATING: ${ratingFrom} -> ${ratingTo} (unrated:${includeUnrated})\n";
print "DURATION: ${minDuration} -> ${maxDuration}\n";
}
&checkRulesChanged();
return 1;
}
}
&checkRulesChanged();
return 0;
}
# Remove duplicate entries from an array...
sub uniq {
return keys %{{ map { $_ => 1 } @_ }};
}
# Send message to Cantata application...
sub sendMessage() {
my $method=shift;
my $argument=shift;
if (0==$isServerMode) {
if ($^O eq "darwin") {
# MacOSX
# TODO: How to send a dbus (or other) message to Cantata application????
} else {
# Linux
system("qdbus mpd.cantata /cantata ${method} ${argument}");
if ( $? == -1 ) {
# Maybe qdbus is not installed? Try dbus-send...
system("dbus-send --type=method_call --session --dest=mpd.cantata /cantata mpd.cantata.${method} string:${argument}");
}
}
} else {
my $clientId=shift;
if ($clientId eq "http") {
return;
}
if ($clientId ne '') {
&sendCommand("sendmessage ${writeChannel}-${clientId} \"${method}:${argument}\"");
} else {
&sendCommand("sendmessage ${writeChannel} \"${method}:${argument}\"");
}
}
}
# Parse sticker value, and check that its in range.
sub songRatingInRange() {
my $stickerEntry=shift;
my @parts = split("=", $stickerEntry);
if (2==scalar(@parts)) {
my $rating=scalar($parts[1]);
if (($rating >= $ratingFrom && $rating <= $ratingTo) || ($rating==0 && $includeUnrated==1)) {
return 1;
}
}
return 0;
}
# Get all songs with a rating between ratingFrom & ratingTo
sub getRatedSongs() {
my @entries = ();
my $data=&sendCommand("sticker find song \"\" rating");
if (defined($data)) {
my @lines=split('\n', $data);
my $file="";
foreach my $line (@lines) {
if ($line=~ m/^(file\:)/) {
my $sep = index($line, ':');
if ($sep>0) {
$file=substr($line, $sep+2, length($line)-($sep+1));
}
} elsif ($line=~ m/^(sticker\:)/) {
my $sep = index($line, ':');
if ($sep>0) {
my $entry=substr($line, $sep+2, length($line)-($sep+1));
if (1==&songRatingInRange($entry)) {
push (@entries, $file);
}
}
}
}
}
return @entries;
}
# Is a file with rating from .. rating to?
sub checkSongRatingInRange() {
if ($ratingFrom<=0 && $ratingTo<=0) { # No filter, so must be in range!
return 1;
}
if ($numMpdSongs<1) { # No songs!
return 0;
}
if (0 == scalar(@includeRules)) {
# There were no include rules, so all files matching rating range were chose.
# Therefore, no need to check ratings now.
return 1;
}
my $file=shift;
my @entries = &getEntries("sticker get song \"${file}\" rating", 'sticker');
if (@entries == 0 && $includeUnrated == 1) { # Song has no ratings, and unrated songs are included!
return 1;
}
foreach my $entry (@entries) {
if (1==&songRatingInRange($entry)) {
return 1;
}
}
# Song is not within range, so 'blank' its name out of list
my $pos=shift;
if (1==$testMode) {
print "$file is NOT in rating range - remove:${pos} total:${numMpdSongs}!\n";
}
splice @mpdSongs, $pos, 1;
$numMpdSongs--;
return 0;
}
# Check song duration is in range
sub checkSongDurationInRange() {
if ($minDuration<=0 && $maxDuration<=0) {
return 1;
}
if ($numMpdSongs<1) { # No songs!
return 0;
}
my $file=shift;
my @entries = &getEntries("lsinfo \"${file}\"", 'Time');
if (scalar(@entries)==1) {
my $val=int(@entries[0]);
if ( (0==$minDuration || $val>=$minDuration) && (0==$maxDuration || $val<=$maxDuration) ) {
return 1;
}
}
# Song is not within range, so 'blank' its name out of list
my $pos=shift;
if (1==$testMode) {
print "$file is NOT in duration range - remove:${pos} total:${numMpdSongs}!\n";
}
splice @mpdSongs, $pos, 1;
$numMpdSongs--;
return 0;
}
# Use rules to obtain a list of songs from MPD...
sub getSongs() {
# If we have no current songs, or rules have changed, or MPD has been updated - then we need to run the rules against MPD to get song list...
if (scalar(@mpdSongs)<1 || $rulesChanged==1 || $mpdDbUpdated==1) {
$numMpdSongs=0;
my @excludeSongs=();
if (scalar(@excludeRules)>0) {
# Get list of songs that should be removed from the song list...
my $mpdSong=0;
foreach my $rule (@excludeRules) {
my @songs = &getEntries($rule, 'file');
foreach my $song (@songs) {
$excludeSongs[$mpdSong]=$song;
$mpdSong++;
}
@excludeSongs=uniq(@excludeSongs);
}
}
my %excludeSongSet = map { $_ => 1 } @excludeSongs;
@mpdSongs=();
my $mpdSong=0;
if (scalar(@includeRules)>0) {
foreach my $rule (@includeRules) {
my @songs = &getEntries($rule, 'file');
foreach my $song (@songs) {
if (! $excludeSongSet{$song}) {
$mpdSongs[$mpdSong]=$song;
$mpdSong++;
}
}
@mpdSongs=uniq(@mpdSongs);
}
} elsif ($ratingTo>=1 && $ratingFrom>=0) {
if (1==$testMode) { print "No include rules, so get all songs in rating range ${ratingFrom}..${ratingTo}...\n"; }
my @songs = &getRatedSongs();
foreach my $song (@songs) {
if (! $excludeSongSet{$song}) {
$mpdSongs[$mpdSong]=$song;
$mpdSong++;
}
}
} else {
if (1==$testMode) { print "No include rules, so get all songs...\n"; }
# No 'include' rules => get all songs! Do this by getting all Artists, and then all songs by each...
my $tag='Artist';
my @entries = &getEntries("list ${tag}", $tag);
foreach my $entry (@entries) {
my @songs = &getEntries("find ${tag} \"${entry}\"", 'file');
foreach my $song (@songs) {
if (! $excludeSongSet{$song}) {
$mpdSongs[$mpdSong]=$song;
$mpdSong++;
}
}
}
}
if (scalar(@mpdSongs)<1) {
if (1==$isServerMode) {
$currentStatus="NO_SONGS";
$dynamicIsActive=0;
&sendStatus();
} else {
&sendMessage("showError", "NO_SONGS");
exit(0);
}
} elsif (1==$isServerMode) {
&sendMessage("status", "HAVE_SONGS");
}
if (1==$testMode) {
print "SONGS--------------\n";
foreach my $song (@mpdSongs) {
print "${song}\n";
}
print "---------------------\n"
}
$numMpdSongs=scalar(@mpdSongs);
}
}
#
# Following canAdd/storeSong are used to remember songs that have been added to the playqueue, so that
# we don't re-add them too soon!
#
@playQueueHistory=();
$playQueueHistoryLimit=0;
$playQueueHistoryPos=0;
sub canAdd() {
my $file=shift;
my $numSongs=shift;
my $pqLimit=0;
# Calculate a reasonable level for the history...
if (1==$numSongs) {
return 1;
} elsif ($numSongs<5) {
$pqLimit=int(($numSongs/2)+0.5);
} else {
$pqLimit=int(($numSongs*0.75)+0.5);
if ($pqLimit>200) {
$pqLimit=200;
}
}
# If the history level has changed, then so must have the rules/mpd/whatever, so add this song anyway...
if ($pqLimit != $playQueueHistoryLimit) {
$playQueueHistoryLimit=$pqLimit;
@playQueueHistory=();
return 1;
}
my $size=scalar(@playQueueHistory);
if ($size>$playQueueHistoryLimit) {
$size=$playQueueHistoryLimit;
}
for (my $i=0; $i<$size; ++$i) {
if ($playQueueHistory[$i] eq $file) {
return 0;
}
}
return 1;
}
sub storeSong() {
my $file=shift;
if ($playQueueHistoryLimit<=0) {
$playQueueHistoryLimit=5;
}
if ($playQueueHistoryPos>=$playQueueHistoryLimit) {
$playQueueHistoryPos=0;
}
$playQueueHistory[$playQueueHistoryPos]=$file;
$playQueueHistoryPos++;
}
#
# This is the 'main' function of the dynamizer
#
sub populatePlayQueue() {
&readConnectionDetails();
my $lastMpdDbUpdate=-1;
while (1) {
my $socketData='';
if (1==$dynamicIsActive) {
# Use status to obtain the current song pos, and to check that MPD is running...
$socketData=&sendCommand("status");
} elsif (1==$isServerMode) {
while (0==$dynamicIsActive) {
&waitForEvent();
}
}
if (defined($socketData)) {
my @lines = split('\n', $socketData);
my $playQueueLength=0;
my $playQueueCurrentTrackPos=0;
my $isPlaying=0;
foreach my $val (@lines) {
if ($val=~ m/^(song\:)/) {
my @vals = split(": ", $val);
if (scalar(@vals)==2) {
$playQueueCurrentTrackPos=scalar($vals[1]);
}
} elsif ($val=~ m/^(state\:)/) {
my @vals = split(": ", $val);
if (scalar(@vals)==2 && $vals[1]=~ m/^(play)/) {
$isPlaying=1;
}
}
}
# Call stats, so that we can obtain the last time MPD was updated.
# We use this to determine when we need to refresh the searched set of songs
$mpdDbUpdated=0;
$socketData=&sendCommand("stats");
if (defined($socketData)) {
my @lines = split('\n', $socketData);
foreach my $val (@lines) {
if ($val=~ m/^(db_update\:)/) {
my @vals = split(": ", $val);
if (scalar(@vals)==2) {
my $mpdDbUpdate=scalar($vals[1]);
if ($mpdDbUpdate!=$lastMpdDbUpdate) {
$lastMpdDbUpdate=$mpdDbUpdate;
$mpdDbUpdated=1;
}
}
break;
}
}
}
# Get current playlist info
$socketData=&sendCommand("playlist");
if (defined($socketData)) {
my @lines = split('\n', $socketData);
my $playQueueLength=scalar(@lines);
if ($playQueueLength>0 && $lines[$playQueueLength-1]=~ m/^(OK)/) {
$playQueueLength--;
}
# trim playlist start so that current becomes <=$playQueueDesiredLength/2
my $wantCurrentPos = $playQueueDesiredLength/2;
for (my $i=0; $i < $playQueueCurrentTrackPos - ($wantCurrentPos-1); $i++) {
&sendCommand("delete 0");
$playQueueLength--;
}
if ($playQueueLength<0) {
$playQueueLength=0;
}
&readRules();
&getSongs();
if ($numMpdSongs>0) {
# fill up playlist to 10 random tunes
my $failues=0;
my $added=0;
while ($playQueueLength < $playQueueDesiredLength && $numMpdSongs>0) {
my $pos=int(rand($numMpdSongs));
my $origFile=${mpdSongs[$pos]};
my $file=$origFile;
$file =~ s/\\/\\\\/g;
$file =~ s/\"/\\\"/g;
if (&checkSongDurationInRange($file, $pos) && &checkSongRatingInRange($file, $pos)) {
if ($failues > 100 || &canAdd($origFile, $numMpdSongs)) {
if (&sendCommand("add \"${file}\"") ne '') {
&storeSong($origFile);
$playQueueLength++;
$failues=0;
$added++;
}
} else { # Song is already in playqueue history...
$failues++;
}
}
}
# If we are not currently playing and we filled playqueue - then play first!
if ($numMpdSongs>0 && $isPlaying==0 && $added==$playQueueDesiredLength) {
&sendCommand("play 0")
}
}
if ($numMpdSongs>0) {
&waitForEvent();
} else {
if (1==$isServerMode) {
$currentStatus="NO_SONGS";
$dynamicIsActive=0;
&sendStatus();
} else {
&sendMessage("showError", "NO_SONGS");
exit(0);
}
}
} elsif (0==$isServerMode) {
sleep 2;
}
} elsif (0==$isServerMode) {
sleep 2;
}
}
}
sub readPid() {
my $fileName=shift;
if (-e $fileName) {
open(my $fileHandle, $fileName);
my @lines = <$fileHandle>;