4 class App::MPD::Feeder;
6 use App::MPD::Feeder::DB;
7 use App::MPD::Feeder::Options;
8 use App::MPD::Feeder::WorkQueue;
12 use IO::Async::Signal;
13 use IO::Async::Timer::Periodic;
14 use Log::Any qw($log);
17 use Syntax::Keyword::Try;
19 has $cfg_file :reader;
22 has $db_needs_update :writer = 1;
24 has $mpd_connected = 0;
25 has $playlist_needs_filling = 1;
26 has $quit_requested = 0;
27 has $reload_requested = 0;
30 has $reconnect_delay = 5;
32 use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
35 Getopt::Long::Configure('pass_through');
36 Getopt::Long::GetOptions( 'cfg|config=s' => \$cfg_file );
37 Getopt::Long::Configure('no_pass_through');
39 $cfg_file //= DEFAULT_CONFIG_FILE if -e DEFAULT_CONFIG_FILE;
43 $db_needs_update = 0 if $opt->skip_db_update;
47 my $new_opt = App::MPD::Feeder::Options->new;
49 $new_opt->parse_config_file($cfg_file) if $cfg_file;
51 $new_opt->parse_command_line;
53 Log::Any::Adapter->set( Stderr => log_level => $new_opt->log_level );
57 $reconnect_delay = $opt->initial_reconnect_delay;
59 $db = App::MPD::Feeder::DB->new( opt => $opt );
65 my %conn = ( auto_connect => 0 );
66 $conn{host} = $opt->mpd_host if $opt->mpd_host;
67 $conn{port} = $opt->mpd_port if $opt->mpd_port;
69 $mpd = Net::Async::MPD->new(%conn);
73 $mpd->loop->stop('disconnected');
75 $log->warn("Connection to MPD lost");
80 $playlist_needs_filling = 1;
89 my $int_signal_handler = sub {
90 state $signal_count = 0;
93 if ( $signal_count > 1 ) {
94 $log->warn("Another signal received (#$signal_count)");
95 $log->warn("Exiting abruptly");
99 $log->debug("Signal received. Stopping loop");
101 $mpd->loop->stop('quit');
107 IO::Async::Signal->new(
109 on_receipt => $int_signal_handler,
115 IO::Async::Signal->new(
118 $log->debug("SIGHUP received. Scheduling reload");
119 $reload_requested = 1;
120 $mpd->loop->stop('reload');
127 IO::Async::Signal->new(
131 "SIGUSR1 received. Dumping configuration to STDERR");
132 my $old = select \*STDERR;
148 method update_db( $force = undef ) {
149 if ( !$db_needs_update and !$force ) {
150 $log->debug("Skipping DB update");
154 $log->info('Updating song database');
156 my $rows = $mpd->send('listallinfo')->get;
158 $log->trace('got all songs from MPD');
164 foreach my $entry (@$rows) {
165 next unless exists $entry->{file};
167 $self->db->store_song( $entry->{file},
168 $entry->{AlbumArtist} // $entry->{Artist},
174 my ($total_songs, $total_artists, $total_albums,
175 $new_songs, $new_artists, $new_albums
176 ) = $self->db->finish_update;
179 "Updated data about $song_count songs (including $new_songs new), "
180 . "$total_artists artists (including $new_artists new) "
182 . "and $total_albums albums (including $new_albums new)"
185 $db_needs_update = 0;
189 $self->db->cancel_update;
194 method queue_songs( $num = undef ) {
195 if ( !defined $num ) {
196 return unless $playlist_needs_filling;
198 $log->trace("Requesting playlist");
199 my $present = $mpd->send('playlist')->get // [];
200 $present = scalar(@$present);
202 $log->notice( "Playlist contains $present songs. Wanted: "
203 . $opt->target_queue_length );
204 if ( $present < $opt->target_queue_length ) {
205 $self->queue_songs( $opt->target_queue_length - $present );
208 $playlist_needs_filling = 0;
214 my @list = $self->db->find_suitable_songs($num);
216 die "Found no suitable songs" unless @list;
218 if ( @list < $num ) {
221 'Found only %d suitable songs instead of %d',
227 $log->info("About to add $num songs to the playlist");
230 for my $song (@list) {
231 my $path = $song->{song};
236 $log->debug( "Adding " . join( ', ', map {"«$_»"} @paths ) );
238 # MPD needs raw bytes
239 utf8::encode($_) for @paths;
242 push @commands, [ add => "\"$_\"" ];
244 my $f = $mpd->send( \@commands );
245 $f->on_fail( sub { die @_ } );
248 $self->db->note_song_qeued($_) for @list;
249 $playlist_needs_filling = 0;
256 $log->notice("disconnecting and re-starting");
260 my @exec = ( $0, '--config', $self->cfg_file, '--skip-db-update' );
261 if ( $log->is_trace ) {
262 $log->trace( 'exec ' . join( ' ', map { /\s/ ? "'$_'" : $_ } @exec ) );
268 if ( $idler && !$idler->is_ready ) {
269 $log->trace("hand-sending 'noidle'");
271 $mpd->{mpd_handle}->write("noidle\n");
274 $log->trace("no idler found");
278 method sleep_before_reconnection {
279 $self->debug( "Waiting for "
280 . duration_exact($reconnect_delay)
281 . " before re-connecting" );
284 IO::Async::Timer::Countdown->new(
285 delay => $reconnect_delay,
286 on_expire => sub { $mpd->loop->stop },
290 $reconnect_delay = $reconnect_delay * 1.5;
291 $reconnect_delay = 120 if $reconnect_delay > 120;
296 unless ($mpd_connected) {
300 $playlist_needs_filling = 1;
301 $reconnect_delay = $opt->initial_reconnect_delay;
305 $mpd->loop->later( sub { $self->pulse } );
309 if ($db_needs_update) {
311 $mpd->loop->later( sub { $self->pulse } );
315 if ($playlist_needs_filling) {
317 $mpd->loop->later( sub { $self->pulse } );
321 $log->debug("Waiting idle. PID=$$");
322 $last_mpd_comm = time;
323 $idler = $mpd->send("idle database playlist");
324 my $result = $idler->get;
327 if ( ref $result and $result->{changed} ) {
328 my $changed = $result->{changed};
329 $changed = [$changed] unless ref $changed;
331 $mpd->emit($_) for @$changed;
334 $log->trace('got out of idle');
344 IO::Async::Timer::Periodic->new(
347 if (!$mpd_connected) {
348 $log->trace("Not connected to MPD. Skipping alive check.");
352 if ( time - $last_mpd_comm > 300 ) {
355 "no active MPD communication for more that 5 minutes");
356 $log->debug("forcing alive check");
361 "contacted MPD less than 5 minutes ago. skipping alive check"
369 $mpd->loop->later( sub { $self->pulse } );
371 $log->trace('About to run the loop');
375 if ( $quit_requested ) {
376 $log->trace("about to quit");
381 elsif ( $reload_requested ) {
385 elsif ( !$mpd_connected ) {
386 $self->sleep_before_reconnection;