]> git.ktnx.net Git - mpd-feeder.git/blobdiff - lib/App/MPD/Feeder.pm
rework idling again, walking around Net::Async::MPD interface
[mpd-feeder.git] / lib / App / MPD / Feeder.pm
index 2381689a20d4f6dd555b3c1e517562809568a555..60b54a56b7a33c8e563dfbc7f8c6130091bc1f72 100644 (file)
@@ -5,24 +5,28 @@ use warnings;
 use utf8;
 use feature 'state';
 
-use App::MPD::Feeder::Options;
 use App::MPD::Feeder::DB;
+use App::MPD::Feeder::Options;
+use App::MPD::Feeder::WorkQueue;
 use DBD::Pg;
 use DBI;
 use Getopt::Long;
 use IO::Async::Signal;
+use IO::Async::Timer::Periodic;
 use Log::Any qw($log);
 use Net::Async::MPD;
 use Object::Pad;
 use Syntax::Keyword::Try;
 
-
 class App::MPD::Feeder {
     has $cfg_file :reader;
     has $opt :reader;
     has $db :reader;
     has $db_needs_update :writer = 1;
     has $mpd :reader;
+    has $idler;
+    has $work_queue = App::MPD::Feeder::WorkQueue->new;
+    has $last_mpd_comm;
 
 use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
 
@@ -61,11 +65,28 @@ use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
 
         $mpd = Net::Async::MPD->new(%conn);
 
+        $mpd->on(
+            close => sub {
+                die "Connection to MPD lost";
+            }
+        );
+        $mpd->on(
+            playlist => sub {
+                $work_queue->add('playlist');
+            }
+        );
+        $mpd->on(
+            database => sub {
+                $work_queue->add('database');
+            }
+        );
+
         my $int_signal_handler = sub {
             state $signal_count = 0;
             $signal_count++;
             $log->debug("Signal received. Stopping loop");
-            $mpd->loop->stop('quit');
+            $work_queue->add('quit');
+            $self->break_idle;
 
             if ( $signal_count > 1 ) {
                 $log->warn("Another signal received (#$signal_count)");
@@ -88,7 +109,8 @@ use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
                 name       => 'HUP',
                 on_receipt => sub {
                     $log->debug("SIGHUP received. Scheduling reload");
-                    $mpd->loop->stop('reload');
+                    $work_queue->add('reload');
+                    $self->break_idle;
                 },
             )
         );
@@ -126,6 +148,8 @@ use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
 
         my $rows = $mpd->send('listallinfo')->get;
 
+        $log->trace('got all songs from MPD');
+
         $db->start_update;
         try {
             my $song_count;
@@ -136,14 +160,20 @@ use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
                 $self->db->store_song( $entry->{file},
                     $entry->{AlbumArtist} // $entry->{Artist},
                     $entry->{Album} );
+
                 $song_count++;
             }
 
-            $log->info("Updated data about $song_count songs");
+            my ($total_songs, $total_artists, $total_albums,
+                $new_songs,   $new_artists,   $new_albums
+            ) = $self->db->finish_update;
 
-            $self->db->remove_stale_entries;
+            $log->info(
+                "Updated data about $song_count songs (including $new_songs new), "
+                    . "$total_artists artists (including $new_artists new) "
 
-            $self->db->finish_update;
+                    . "and $total_albums albums (including $new_albums new)"
+            );
 
             $db_needs_update = 0;
         }
@@ -154,25 +184,20 @@ use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
         }
     }
 
-    method queue_songs($num = undef, $callback = undef) {
+    method queue_songs($num = undef) {
         $self->connect_db;
         if (!defined $num) {
             $self->connect_mpd;
-            $mpd->send('playlist')->on_done(
-                sub {
-                    my $present = scalar @{ $_[0] };
-
-                    $log->notice( "Playlist contains $present songs. Wanted: "
-                            . $opt->target_queue_length );
-                    if ( $present < $opt->target_queue_length ) {
-                        $self->queue_songs(
-                            $opt->target_queue_length - $present, $callback );
-                    }
-                    else {
-                        $callback->() if $callback;
-                    }
-                }
-            );
+            $log->trace("Requesting playlist");
+            my $present = $mpd->send('playlist')->get // [];
+            $present = scalar(@$present);
+
+            $log->notice( "Playlist contains $present songs. Wanted: "
+                    . $opt->target_queue_length );
+            if ( $present < $opt->target_queue_length ) {
+                $self->queue_songs(
+                    $opt->target_queue_length - $present );
+            }
 
             return;
         }
@@ -212,79 +237,102 @@ use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
         $f->on_done(
             sub {
                 $self->db->note_song_qeued($_) for @list;
-                $callback->(@_) if $callback;
             }
         );
+        $f->get;
     }
 
-    method prepare_to_wait_idle {
-        $log->trace('declaring idle mode');
-        $mpd->send('idle database playlist')->on_done(
-            sub {
-                my $result = shift;
+    method stop {
+        undef $mpd;
 
-                if ( $result->{changed} eq 'database' ) {
-                    $db_needs_update = 1;
-                    $self->prepare_to_wait_idle;
-                }
-                elsif ( $result->{changed} eq 'playlist' ) {
-                    $self->queue_songs( undef,
-                        sub { $self->prepare_to_wait_idle } );
-                }
-                else {
-                    use JSON;
-                    $log->warn(
-                        "Unknown result from idle: " . to_json($result) );
-                    $self->prepare_to_wait_idle;
-                }
-            }
-        );
+        $db->disconnect;
     }
 
-    method run {
-        $mpd->on(
-            close => sub {
-                die "Connection to MPD lost";
+    method handle_work_queue {
+        while ( my $item = $work_queue->next ) {
+            if ( $item eq 'playlist' ) {
+                $self->queue_songs;
             }
-        );
+            elsif ( $item eq 'database' ) {
+                $db_needs_update = 1;
+                $self->update_db;
+            }
+            elsif ( $item eq 'reload' ) {
+                $log->notice("disconnecting and re-starting");
+                $self->stop;
 
-        $self->prepare_to_wait_idle;
+                my @exec =
+                    ( $0, '--config', $self->cfg_file, '--skip-db-update' );
+                if ( $log->is_trace ) {
+                    $log->trace( 'exec '
+                            . join( ' ', map { /\s/ ? "'$_'" : $_ } @exec ) );
+                }
+                exec(@exec);
+            }
+            elsif ( $item eq 'quit' ) {
+                $log->trace("quitting");
+                $self->stop;
+                exit 0;
+            }
+            else {
+                die "Unknown work queue item '$item'";
+            }
+        }
     }
 
-    method stop {
-        undef $mpd;
-
-        $db->disconnect;
+    method break_idle {
+        if ($idler && !$idler->is_ready) {
+            $log->trace("hand-sending 'noidle'");
+            undef $idler;
+            $mpd->{mpd_handle}->write("noidle\n");;
+        }
+        else {
+            $log->trace("no idler found");
+        }
     }
 
     method run_loop {
+        $self->connect_mpd;
         $self->connect_db;
 
-        for ( ;; ) {
-            $self->queue_songs( undef, sub { $self->run } );
+        $mpd->loop->add(
+            IO::Async::Timer::Periodic->new(
+                interval => 60,
+                on_tick  => sub {
+                    if ( time - $last_mpd_comm > 300 ) {
+
+                        $log->trace(
+                            "no active MPD communication for more that 5 minutes"
+                        );
+                        $log->trace("forcing alive check");
+                        $self->break_idle;
+                    }
+                    else {
+                        $log->trace("contacted MPD less than 5 minutes ago. skipping alive check");
+                    }
+                },
+            )->start
+        );
 
-            $log->debug("Entering event loop. PID=$$");
+        $self->queue_songs;
 
-            my $result = $mpd->loop->run;
-            $log->trace( "Got loop result of " . ( $result // 'undef' ) );
+        for ( ;; ) {
+            $log->debug("Waiting idle. PID=$$");
+            $last_mpd_comm = time;
+            $idler = $mpd->send("idle database playlist");
+            my $result = $idler->get;
+            undef $idler;
 
-            if ( 'reload' eq $result ) {
-                $log->notice("disconnecting");
-                $self->stop;
+            if ($result and $result->{changed}){
+                my $changed = $result->{changed};
+                $changed = [ $changed ] unless ref $changed;
 
-                my @exec = ( $0, '--config', $self->cfg_file, '--skip-db-update' );
-                if ( $log->is_trace ) {
-                    $log->trace( 'exec '
-                            . join( ' ', map { /\s/ ? "'$_'" : $_ } @exec ) );
-                }
-                exec(@exec);
+                $mpd->emit($_) for @$changed;
             }
 
-            if ( 'quit' eq $result ) {
-                $log->trace("quitting because of 'quit' loop result");
-                $self->stop;
-                exit 0;
-            }
+            $log->trace('got out of idle');
+
+            $self->handle_work_queue;
         }
     }
 }