7 use Log::Any::Adapter Stderr => log_level => 'error';
9 use Syntax::Keyword::Try;
12 use Log::Any qw($log);
13 use Time::Duration qw(duration_exact);
14 use Time::Duration::Parse qw(parse_duration);
15 has $log_level :reader = 'warn';
16 has $target_queue_length :reader = 10;
17 has $mpd_host :reader = undef;
18 has $mpd_port :reader = undef;
19 has $db_path :reader = 'mpd-feeder';
20 has $db_user :reader = undef;
21 has $db_password :reader = undef;
22 has $min_album_interval :reader = parse_duration('5h');
23 has $min_song_interval :reader = parse_duration('13d');
24 has $min_artist_interval :reader = parse_duration('1h 15m');
25 has $skip_db_update :reader = 0;
27 method parse_command_line {
28 Getopt::Long::GetOptions(
29 'log-level=s' => \$log_level,
30 'skip-db-update!' => \$skip_db_update,
31 'tql|target-queue-length=n' => sub {
32 $target_queue_length = parse_integer(pop);
34 'mpd-host=s' => \$mpd_host,
35 'mpd-port=s' => \$mpd_port,
36 'db-path=s' => \$db_path,
37 'db-user=s' => \$db_user,
38 'min-album-interval=s' => sub {
39 $min_album_interval = parse_duration(pop);
41 'min-sing-interval=s' => sub {
42 $min_song_interval = parse_duration(pop);
44 'min-artist-interval=s' => sub {
45 $min_artist_interval = parse_duration(pop);
50 sub handle_config_option( $ini, $section, $option, $target_ref,
53 return undef unless exists $ini->{$section}{$option};
55 my $value = $ini->{$section}{$option};
57 $value = $converter->($value) if $converter;
59 $$target_ref = $value;
61 $log->trace("Option $section.$option = $value");
66 say "log_level = $log_level";
69 say "host = " . ( $mpd_host // '' );
70 say "port = " . ( $mpd_port // '' );
73 say "target-length = $target_queue_length";
74 say "min-song-interval = " . duration_exact($min_song_interval);
75 say "min-album-interval = " . duration_exact($min_album_interval);
76 say "min-artist-interval = " . duration_exact($min_artist_interval);
79 say "path = " . ( $db_path // '' );
80 say "user = " . ( $db_user // '' );
81 say "password = " . ( $db_password // '' );
84 sub parse_integer($input) {
85 die "Invalid integer value '$input'" unless $input =~ /^\+?\d{1,18}$/;
89 method parse_config_file($path) {
90 $log->trace("Parsing configuration file $path");
92 use Config::INI::Reader;
93 my $ini = Config::INI::Reader->read_file($path);
95 handle_config_option( $ini => mpd => host => \$mpd_host );
96 handle_config_option( $ini => mpd => port => \$mpd_port );
98 handle_config_option( $ini => 'mpd-feeder' => log_level => \$log_level );
100 handle_config_option(
101 $ini => queue => 'target-length' => \$target_queue_length,
104 handle_config_option(
105 $ini => queue => 'min-song-interval' => \$min_song_interval,
108 handle_config_option(
109 $ini => queue => 'min-album-interval' => \$min_album_interval,
112 handle_config_option(
113 $ini => queue => 'min-artist-interval' => \$min_artist_interval,
117 handle_config_option( $ini => db => path => \$db_path );
118 handle_config_option( $ini => db => user => \$db_user );
119 handle_config_option( $ini => db => password => \$db_password );
121 # FIXME: complain about unknown sections/parameters
126 has $cfg_file :reader;
130 has $db_needs_update :writer = 1;
133 use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
137 use Log::Any qw($log);
138 use IO::Async::Signal;
142 Getopt::Long::Configure('pass_through');
143 Getopt::Long::GetOptions('cfg|config=s' => \$cfg_file);
144 Getopt::Long::Configure('no_pass_through');
146 $cfg_file //= DEFAULT_CONFIG_FILE if -e DEFAULT_CONFIG_FILE;
150 $db_needs_update = 0 if $opt->skip_db_update;
154 my $new_opt = Options->new;
156 $new_opt->parse_config_file($cfg_file) if $cfg_file;
158 $new_opt->parse_command_line;
160 Log::Any::Adapter->set( Stderr => log_level => $new_opt->log_level );
168 my %conn = ( auto_connect => 1 );
169 $conn{host} = $opt->mpd_host if $opt->mpd_host;
170 $conn{port} = $opt->mpd_port if $opt->mpd_port;
172 $mpd = Net::Async::MPD->new(%conn);
175 IO::Async::Signal->new(
178 $log->debug("SIGHUP received. Stopping loop");
179 $mpd->loop->stop('reload');
185 IO::Async::Signal->new(
188 $log->debug("SIGUSR1 received. Dumping configuration to STDERR");
189 my $old = select \*STDERR;
204 $db = DBI->connect( "dbi:Pg:dbname=" . $opt->db_path,
205 $opt->db_user, $opt->db_password,
206 { RaiseError => 1, PrintError => 0, AutoCommit => 1 } );
208 $log->info( "Connected to database " . $opt->db_path );
209 $db_generation = $self->db_get_option('generation');
210 $log->debug("DB generation is $db_generation");
214 method db_get_option($name) {
215 my $sth = $db->prepare_cached("select $name from options");
217 my @result = $sth->fetchrow_array;
224 method db_set_option( $name, $value ) {
225 my $sth = $db->prepare_cached("update options set $name = ?");
226 $sth->execute($value);
229 method db_store_song($song, $artist, $album) {
230 return unless length($song) and length($artist) and length($album);
233 <<'SQL')->execute( $song, $artist, $album, $db_generation );
234 INSERT INTO songs(path, artist, album, generation)
235 VALUES($1, $2, $3, $4)
236 ON CONFLICT ON CONSTRAINT songs_pkey DO
237 UPDATE SET artist = $2
241 $db->prepare_cached(<<'SQL')->execute( $artist, $album, $db_generation );
242 INSERT INTO albums(artist, album, generation)
244 ON CONFLICT ON CONSTRAINT albums_pkey DO
245 UPDATE SET generation = $3
247 $db->prepare_cached(<<'SQL')->execute( $artist, $db_generation );
248 INSERT INTO artists(artist, generation)
250 ON CONFLICT ON CONSTRAINT artists_pkey DO
251 UPDATE SET generation = $2
255 method db_remove_stale_entries {
257 $db->prepare_cached('DELETE FROM songs WHERE generation <> ?');
258 $sth->execute($db_generation);
259 $log->debug( sprintf( "Deleted %d stale songs", $sth->rows ) );
261 $sth = $db->prepare_cached('DELETE FROM albums WHERE generation <> ?');
262 $sth->execute($db_generation);
263 $log->debug( sprintf( "Deleted %d stale albums", $sth->rows ) );
266 $db->prepare_cached('DELETE FROM artists WHERE generation <> ?');
267 $sth->execute($db_generation);
268 $log->debug( sprintf( "Deleted %d stale artists", $sth->rows ) );
271 method db_note_song_qeued($item) {
273 'UPDATE songs SET last_queued=current_timestamp WHERE path=?')
274 ->execute( $item->{song} );
276 'UPDATE artists SET last_queued=CURRENT_TIMESTAMP WHERE artist=?')
277 ->execute( $item->{artist} );
279 'UPDATE albums SET last_queued=CURRENT_TIMESTAMP WHERE artist=? AND album=?'
280 )->execute( $item->{artist}, $item->{album} );
283 method update_db($force = undef) {
284 if (!$db_needs_update and !$force) {
285 $log->debug("Skipping DB update");
289 $log->info('Updating song database');
293 my $rows = $mpd->send('listallinfo')->get;
301 foreach my $entry (@$rows) {
302 next unless exists $entry->{file};
303 $self->db_store_song( $entry->{file},
304 $entry->{AlbumArtist} // $entry->{Artist},
309 $log->info("Updated data about $song_count songs");
311 $self->db_remove_stale_entries;
313 $self->db_set_option( generation => $db_generation );
317 $db_needs_update = 0;
330 method db_find_suitable_songs($num) {
336 SELECT s.path, s.artist, s.album
338 JOIN artists ar ON ar.artist=s.artist
339 JOIN albums al ON al.album=s.album AND al.artist=s.artist
340 WHERE (s.last_queued IS NULL OR s.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
341 AND (ar.last_queued IS NULL OR ar.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
342 AND (al.last_queued IS NULL OR al.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
343 AND NOT EXISTS (SELECT 1 FROM unwanted_artists uar WHERE uar.artist = s.artist)
344 AND NOT EXISTS (SELECT 1 FROM unwanted_albums ual WHERE ual.album = s.album)
349 $opt->min_song_interval, $opt->min_artist_interval,
350 $opt->min_album_interval, $num,
352 my $sth = $db->prepare_cached($sql);
353 $sth->execute(@params);
354 while ( my @row = $sth->fetchrow_array ) {
356 { song => $row[0], artist => $row[1], album => $row[2] };
363 method db_add_unwanted_artist($artist) {
369 INSERT INTO unwanted_artists(artist, generation)
372 undef, $artist, $db_generation
379 $log->debug("PostgreSQL error: $err");
380 $log->debug( "SQLSTATE = " . $db->state );
381 return 0 if $db->state eq '23505';
387 method db_del_unwanted_artist($artist) {
392 DELETE FROM unwanted_artists
399 method queue_songs($num = undef, $callback = undef) {
402 $mpd->send('playlist')->on_done(
404 my $present = scalar @{ $_[0] };
406 $log->notice( "Playlist contains $present songs. Wanted: "
407 . $opt->target_queue_length );
408 if ( $present < $opt->target_queue_length ) {
410 $opt->target_queue_length - $present, $callback );
413 $callback->() if $callback;
421 my @list = $self->db_find_suitable_songs($num);
423 die "Found no suitable songs" unless @list;
425 if ( @list < $num ) {
428 'Found only %d suitable songs instead of %d',
434 $log->info("About to add $num songs to the playlist");
437 for my $song (@list) {
438 my $path = $song->{song};
443 $log->debug( "Adding " . join( ', ', map {"«$_»"} @paths ) );
446 push @commands, [ add => "\"$_\"" ];
449 my $f = $mpd->send( \@commands );
450 $f->on_fail( sub { die @_ } );
453 $self->db_note_song_qeued($_) for @list;
454 $callback->(@_) if $callback;
459 method prepare_to_wait_idle {
460 $log->trace('declaring idle mode');
461 $mpd->send('idle database playlist')->on_done(
465 if ( $result->{changed} eq 'database' ) {
466 $db_needs_update = 1;
467 $self->prepare_to_wait_idle;
469 elsif ( $result->{changed} eq 'playlist' ) {
470 $self->queue_songs( undef,
471 sub { $self->prepare_to_wait_idle } );
476 "Unknown result from idle: " . to_json($result) );
477 $self->prepare_to_wait_idle;
486 die "Connection to MPD lost";
490 $self->prepare_to_wait_idle;
497 if ($db->{ActiveKids}) {
498 $log->warn("$db->{ActiveKids} active DB statements");
499 for my $st ( @{ $db->{ChildHandles} } ) {
500 next unless $st->{Active};
501 while(my($k,$v) = each %$st) {
502 $log->debug("$k = ".($v//'<NULL>'));
513 my $feeder = Feeder->new();
516 my $cmd = shift @ARGV;
518 if ($cmd eq 'dump-config') {
519 die "dump-config command accepts no arguments\n" if @ARGV;
525 if ( $cmd eq 'add-unwanted-artist' ) {
526 die "Missing command arguments\n" unless @ARGV;
527 $feeder->set_db_needs_update(0);
528 for my $artist (@ARGV) {
529 if ( $feeder->db_add_unwanted_artist($artist) ) {
530 $log->info("Artist '$artist' added to the unwanted list\n");
533 $log->warn("Artist '$artist' already in the unwanted list\n");
539 if ( $cmd eq 'del-unwanted-artist' ) {
540 die "Missing command arguments\n" unless @ARGV;
541 $feeder->set_db_needs_update(0);
542 for my $artist (@ARGV) {
543 if ( $feeder->db_del_unwanted_artist($artist) ) {
544 $log->info("Artist '$artist' deleted from the unwanted list\n");
547 $log->warn("Artist '$artist' is not in the unwanted list\n");
553 if ( $cmd eq 'add-unwanted-album' ) {
554 die "NOT IMPLEMENTED\n";
557 if ( $cmd eq 'one-shot' ) {
558 die "one-shot command accepts no arguments\n" if @ARGV;
560 $feeder->queue_songs(undef, sub { exit });
561 $feeder->mpd->loop->run;
563 elsif ( $cmd eq 'single' ) {
564 die "single command accepts no arguments\n" if @ARGV;
566 $feeder->queue_songs(1, sub { exit });
567 $feeder->mpd->loop->run;
570 die "Unknown command '$cmd'";
577 $feeder->queue_songs( undef, sub { $feeder->run } );
579 $log->debug("Entering event loop. PID=$$");
581 my $result = $feeder->mpd->loop->run;
582 $log->trace( "Got loop result of " . ( $result // 'undef' ) );
584 if ('reload' eq $result) {
585 $log->notice("disconnecting");
588 exec( "$0", '--config', $feeder->cfg_file, '--skip-db-update' );