4 class App::MPD::Feeder;
6 use App::MPD::Feeder::DB;
7 use App::MPD::Feeder::Options;
11 use IO::Async::Signal;
12 use IO::Async::Timer::Countdown;
13 use IO::Async::Timer::Periodic;
14 use Log::Any qw($log);
17 use Syntax::Keyword::Try;
18 use Time::Duration qw(duration_exact);
20 has $cfg_file :reader;
23 has $db_needs_update :writer = 1;
25 has $mpd_connected = 0;
26 has $playlist_needs_filling = 1;
27 has $quit_requested = 0;
28 has $reload_requested = 0;
31 has $reconnect_delay = 5;
33 use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
36 Getopt::Long::Configure('pass_through');
37 Getopt::Long::GetOptions( 'cfg|config=s' => \$cfg_file );
38 Getopt::Long::Configure('no_pass_through');
40 $cfg_file //= DEFAULT_CONFIG_FILE if -e DEFAULT_CONFIG_FILE;
44 $db_needs_update = 0 if $opt->skip_db_update;
48 my $new_opt = App::MPD::Feeder::Options->new;
50 $new_opt->parse_config_file($cfg_file) if $cfg_file;
52 $new_opt->parse_command_line;
54 Log::Any::Adapter->set( Stderr => log_level => $new_opt->log_level );
58 $reconnect_delay = $opt->initial_reconnect_delay;
60 $db = App::MPD::Feeder::DB->new( opt => $opt );
66 my %conn = ( auto_connect => 0 );
67 $conn{host} = $opt->mpd_host if $opt->mpd_host;
68 $conn{port} = $opt->mpd_port if $opt->mpd_port;
70 $mpd = Net::Async::MPD->new(%conn);
74 $log->warn("Connection to MPD lost");
75 $mpd->loop->stop('disconnected');
77 $idler->cancel if $idler;
84 $playlist_needs_filling = 1;
93 my $loop = $mpd->loop;
95 my $int_signal_handler = sub {
96 state $signal_count = 0;
99 if ( $signal_count > 1 ) {
100 $log->warn("Another signal received (#$signal_count)");
101 $log->warn("Exiting abruptly");
105 $log->debug("Signal received. Stopping loop");
113 IO::Async::Signal->new(
115 on_receipt => $int_signal_handler,
121 IO::Async::Signal->new(
124 $log->debug("SIGHUP received. Scheduling reload");
125 $reload_requested = 1;
126 $loop->stop('reload');
133 IO::Async::Signal->new(
137 "SIGUSR1 received. Dumping configuration to STDERR");
138 my $old = select \*STDERR;
154 method update_db( $force = undef ) {
155 if ( !$db_needs_update and !$force ) {
156 $log->debug("Skipping DB update");
160 $log->info('Updating song database');
162 my $rows = $mpd->send('listallinfo')->get;
164 $log->trace('got all songs from MPD');
170 foreach my $entry (@$rows) {
171 next unless exists $entry->{file};
173 $self->db->store_song( $entry->{file},
174 $entry->{AlbumArtist} // $entry->{Artist},
180 my ($total_songs, $total_artists, $total_albums,
181 $new_songs, $new_artists, $new_albums
182 ) = $self->db->finish_update;
185 "Updated data about $song_count songs (including $new_songs new), "
186 . "$total_artists artists (including $new_artists new) "
188 . "and $total_albums albums (including $new_albums new)"
191 $db_needs_update = 0;
195 $self->db->cancel_update;
200 method queue_songs( $num = undef ) {
201 if ( !defined $num ) {
202 return unless $playlist_needs_filling;
204 $log->trace("Requesting playlist");
205 my $present = $mpd->send('playlist')->get // [];
206 $present = scalar(@$present);
208 if ( $present < $opt->target_queue_length ) {
209 $log->notice( "Playlist contains $present songs. Wanted: "
210 . $opt->target_queue_length );
211 $self->queue_songs( $opt->target_queue_length - $present );
214 $log->info("Playlist contains $present songs");
215 $playlist_needs_filling = 0;
221 my @list = $self->db->find_suitable_songs($num);
223 die "Found no suitable songs" unless @list;
225 if ( @list < $num ) {
228 'Found only %d suitable songs instead of %d',
234 $log->debug("About to add $num songs to the playlist");
237 for my $song (@list) {
238 my $path = $song->{song};
243 $log->notice( "Adding " . join( ', ', map {"«$_»"} @paths ) );
245 # MPD needs raw bytes
246 utf8::encode($_) for @paths;
249 push @commands, [ add => "\"$_\"" ];
251 my $f = $mpd->send( \@commands );
252 $f->on_fail( sub { die @_ } );
255 $self->db->note_song_qeued($_) for @list;
256 $playlist_needs_filling = 0;
263 $log->info("disconnecting and re-starting");
267 my @exec = ( $0, '--config', $self->cfg_file, '--skip-db-update' );
268 if ( $log->is_trace ) {
269 $log->trace( 'exec ' . join( ' ', map { /\s/ ? "'$_'" : $_ } @exec ) );
275 if ( $idler && !$idler->is_ready ) {
276 if ($mpd_connected) {
277 $log->trace("hand-sending 'noidle'");
279 $mpd->{mpd_handle}->write("noidle\n");
282 $log->trace("not connected to MPD: skipping 'noidle'");
286 $log->trace("no idler found");
290 method sleep_before_reconnection {
291 $log->debug( "Waiting for "
292 . duration_exact($reconnect_delay)
293 . " before re-connecting" );
296 IO::Async::Timer::Countdown->new(
297 delay => $reconnect_delay,
298 on_expire => sub { $mpd->loop->stop },
302 $reconnect_delay = $reconnect_delay * 1.5;
303 $reconnect_delay = 120 if $reconnect_delay > 120;
308 unless ($mpd_connected) {
309 $log->trace("Connecting to MPD...");
310 my $f = $mpd->connect->await;
314 $playlist_needs_filling = 1;
315 $reconnect_delay = $opt->initial_reconnect_delay;
316 $mpd->loop->later( sub { $self->pulse } );
318 elsif ( $f->is_failed ) {
319 $mpd->loop->stop('disconnected');
320 $log->warn($f->failure);
321 $self->sleep_before_reconnection;
324 die "connect Future neither done nor failed!?";
330 if ($db_needs_update) {
332 $mpd->loop->later( sub { $self->pulse } );
336 if ($playlist_needs_filling) {
338 $mpd->loop->later( sub { $self->pulse } );
342 $log->debug("Waiting idle. PID=$$");
343 $last_mpd_comm = time;
344 $idler = $mpd->send("idle database playlist");
347 $log->trace('got out of idle');
350 if ( $idler->is_done ) {
351 my $result = $idler->get;
353 if ( ref $result and $result->{changed} ) {
354 my $changed = $result->{changed};
355 $changed = [$changed] unless ref $changed;
357 $mpd->emit($_) for @$changed;
360 elsif ( $idler->is_cancelled ) {
361 $log->trace("idle was cancelled");
364 elsif ( $idler->is_failed ) {
365 $log->warn("idle failed: ".$idler->failure);
378 my $loop = $mpd->loop;
381 IO::Async::Timer::Periodic->new(
384 if (!$mpd_connected) {
385 $log->trace("Not connected to MPD. Skipping alive check.");
386 $loop->stop('disconnected');
390 if ( time - $last_mpd_comm > 300 ) {
393 "no active MPD communication for more that 5 minutes");
394 $log->debug("forcing alive check");
399 "contacted MPD less than 5 minutes ago. skipping alive check"
407 if ( $quit_requested ) {
408 $log->trace("about to quit");
413 elsif ( $reload_requested ) {
418 $log->trace('About to run the loop');
420 $mpd->loop->later( sub { $self->pulse } );