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 $log->notice( "Playlist contains $present songs. Wanted: "
209 . $opt->target_queue_length );
210 if ( $present < $opt->target_queue_length ) {
211 $self->queue_songs( $opt->target_queue_length - $present );
214 $playlist_needs_filling = 0;
220 my @list = $self->db->find_suitable_songs($num);
222 die "Found no suitable songs" unless @list;
224 if ( @list < $num ) {
227 'Found only %d suitable songs instead of %d',
233 $log->info("About to add $num songs to the playlist");
236 for my $song (@list) {
237 my $path = $song->{song};
242 $log->debug( "Adding " . join( ', ', map {"«$_»"} @paths ) );
244 # MPD needs raw bytes
245 utf8::encode($_) for @paths;
248 push @commands, [ add => "\"$_\"" ];
250 my $f = $mpd->send( \@commands );
251 $f->on_fail( sub { die @_ } );
254 $self->db->note_song_qeued($_) for @list;
255 $playlist_needs_filling = 0;
262 $log->notice("disconnecting and re-starting");
266 my @exec = ( $0, '--config', $self->cfg_file, '--skip-db-update' );
267 if ( $log->is_trace ) {
268 $log->trace( 'exec ' . join( ' ', map { /\s/ ? "'$_'" : $_ } @exec ) );
274 if ( $idler && !$idler->is_ready ) {
275 if ($mpd_connected) {
276 $log->trace("hand-sending 'noidle'");
278 $mpd->{mpd_handle}->write("noidle\n");
281 $log->trace("not connected to MPD: skipping 'noidle'");
285 $log->trace("no idler found");
289 method sleep_before_reconnection {
290 $log->debug( "Waiting for "
291 . duration_exact($reconnect_delay)
292 . " before re-connecting" );
295 IO::Async::Timer::Countdown->new(
296 delay => $reconnect_delay,
297 on_expire => sub { $mpd->loop->stop },
301 $reconnect_delay = $reconnect_delay * 1.5;
302 $reconnect_delay = 120 if $reconnect_delay > 120;
307 unless ($mpd_connected) {
308 $log->trace("Connecting to MPD...");
309 my $f = $mpd->connect->await;
313 $playlist_needs_filling = 1;
314 $reconnect_delay = $opt->initial_reconnect_delay;
315 $mpd->loop->later( sub { $self->pulse } );
317 elsif ( $f->is_failed ) {
318 $mpd->loop->stop('disconnected');
319 $log->warn($f->failure);
320 $self->sleep_before_reconnection;
323 die "connect Future neither done nor failed!?";
329 if ($db_needs_update) {
331 $mpd->loop->later( sub { $self->pulse } );
335 if ($playlist_needs_filling) {
337 $mpd->loop->later( sub { $self->pulse } );
341 $log->debug("Waiting idle. PID=$$");
342 $last_mpd_comm = time;
343 $idler = $mpd->send("idle database playlist");
346 $log->trace('got out of idle');
349 if ( $idler->is_done ) {
350 my $result = $idler->get;
352 if ( ref $result and $result->{changed} ) {
353 my $changed = $result->{changed};
354 $changed = [$changed] unless ref $changed;
356 $mpd->emit($_) for @$changed;
359 elsif ( $idler->is_cancelled ) {
360 $log->trace("idle was cancelled");
363 elsif ( $idler->is_failed ) {
364 $log->warn("idle failed: ".$idler->failure);
377 my $loop = $mpd->loop;
380 IO::Async::Timer::Periodic->new(
383 if (!$mpd_connected) {
384 $log->trace("Not connected to MPD. Skipping alive check.");
385 $loop->stop('disconnected');
389 if ( time - $last_mpd_comm > 300 ) {
392 "no active MPD communication for more that 5 minutes");
393 $log->debug("forcing alive check");
398 "contacted MPD less than 5 minutes ago. skipping alive check"
406 if ( $quit_requested ) {
407 $log->trace("about to quit");
412 elsif ( $reload_requested ) {
417 $log->trace('About to run the loop');
419 $mpd->loop->later( sub { $self->pulse } );