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::Countdown;
14 use IO::Async::Timer::Periodic;
15 use Log::Any qw($log);
18 use Syntax::Keyword::Try;
19 use Time::Duration qw(duration_exact);
21 has $cfg_file :reader;
24 has $db_needs_update :writer = 1;
26 has $mpd_connected = 0;
27 has $playlist_needs_filling = 1;
28 has $quit_requested = 0;
29 has $reload_requested = 0;
32 has $reconnect_delay = 5;
34 use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
37 Getopt::Long::Configure('pass_through');
38 Getopt::Long::GetOptions( 'cfg|config=s' => \$cfg_file );
39 Getopt::Long::Configure('no_pass_through');
41 $cfg_file //= DEFAULT_CONFIG_FILE if -e DEFAULT_CONFIG_FILE;
45 $db_needs_update = 0 if $opt->skip_db_update;
49 my $new_opt = App::MPD::Feeder::Options->new;
51 $new_opt->parse_config_file($cfg_file) if $cfg_file;
53 $new_opt->parse_command_line;
55 Log::Any::Adapter->set( Stderr => log_level => $new_opt->log_level );
59 $reconnect_delay = $opt->initial_reconnect_delay;
61 $db = App::MPD::Feeder::DB->new( opt => $opt );
67 my %conn = ( auto_connect => 0 );
68 $conn{host} = $opt->mpd_host if $opt->mpd_host;
69 $conn{port} = $opt->mpd_port if $opt->mpd_port;
71 $mpd = Net::Async::MPD->new(%conn);
75 $log->warn("Connection to MPD lost");
76 $mpd->loop->stop('disconnected');
78 $idler->cancel if $idler;
85 $playlist_needs_filling = 1;
94 my $int_signal_handler = sub {
95 state $signal_count = 0;
98 if ( $signal_count > 1 ) {
99 $log->warn("Another signal received (#$signal_count)");
100 $log->warn("Exiting abruptly");
104 $log->debug("Signal received. Stopping loop");
106 $mpd->loop->stop('quit');
112 IO::Async::Signal->new(
114 on_receipt => $int_signal_handler,
120 IO::Async::Signal->new(
123 $log->debug("SIGHUP received. Scheduling reload");
124 $reload_requested = 1;
125 $mpd->loop->stop('reload');
132 IO::Async::Signal->new(
136 "SIGUSR1 received. Dumping configuration to STDERR");
137 my $old = select \*STDERR;
153 method update_db( $force = undef ) {
154 if ( !$db_needs_update and !$force ) {
155 $log->debug("Skipping DB update");
159 $log->info('Updating song database');
161 my $rows = $mpd->send('listallinfo')->get;
163 $log->trace('got all songs from MPD');
169 foreach my $entry (@$rows) {
170 next unless exists $entry->{file};
172 $self->db->store_song( $entry->{file},
173 $entry->{AlbumArtist} // $entry->{Artist},
179 my ($total_songs, $total_artists, $total_albums,
180 $new_songs, $new_artists, $new_albums
181 ) = $self->db->finish_update;
184 "Updated data about $song_count songs (including $new_songs new), "
185 . "$total_artists artists (including $new_artists new) "
187 . "and $total_albums albums (including $new_albums new)"
190 $db_needs_update = 0;
194 $self->db->cancel_update;
199 method queue_songs( $num = undef ) {
200 if ( !defined $num ) {
201 return unless $playlist_needs_filling;
203 $log->trace("Requesting playlist");
204 my $present = $mpd->send('playlist')->get // [];
205 $present = scalar(@$present);
207 $log->notice( "Playlist contains $present songs. Wanted: "
208 . $opt->target_queue_length );
209 if ( $present < $opt->target_queue_length ) {
210 $self->queue_songs( $opt->target_queue_length - $present );
213 $playlist_needs_filling = 0;
219 my @list = $self->db->find_suitable_songs($num);
221 die "Found no suitable songs" unless @list;
223 if ( @list < $num ) {
226 'Found only %d suitable songs instead of %d',
232 $log->info("About to add $num songs to the playlist");
235 for my $song (@list) {
236 my $path = $song->{song};
241 $log->debug( "Adding " . join( ', ', map {"«$_»"} @paths ) );
243 # MPD needs raw bytes
244 utf8::encode($_) for @paths;
247 push @commands, [ add => "\"$_\"" ];
249 my $f = $mpd->send( \@commands );
250 $f->on_fail( sub { die @_ } );
253 $self->db->note_song_qeued($_) for @list;
254 $playlist_needs_filling = 0;
261 $log->notice("disconnecting and re-starting");
265 my @exec = ( $0, '--config', $self->cfg_file, '--skip-db-update' );
266 if ( $log->is_trace ) {
267 $log->trace( 'exec ' . join( ' ', map { /\s/ ? "'$_'" : $_ } @exec ) );
273 if ( $idler && !$idler->is_ready ) {
274 if ($mpd_connected) {
275 $log->trace("hand-sending 'noidle'");
277 $mpd->{mpd_handle}->write("noidle\n");
280 $log->trace("not connected to MPD: skipping 'noidle'");
284 $log->trace("no idler found");
288 method sleep_before_reconnection {
289 $log->debug( "Waiting for "
290 . duration_exact($reconnect_delay)
291 . " before re-connecting" );
294 IO::Async::Timer::Countdown->new(
295 delay => $reconnect_delay,
296 on_expire => sub { $mpd->loop->stop },
300 $reconnect_delay = $reconnect_delay * 1.5;
301 $reconnect_delay = 120 if $reconnect_delay > 120;
306 unless ($mpd_connected) {
307 $log->trace("Connecting to MPD...");
308 my $f = $mpd->connect->await;
312 $playlist_needs_filling = 1;
313 $reconnect_delay = $opt->initial_reconnect_delay;
314 $mpd->loop->later( sub { $self->pulse } );
316 elsif ( $f->is_failed ) {
317 $mpd->loop->stop('disconnected');
318 $log->warn($f->failure);
319 $self->sleep_before_reconnection;
322 die "connect Future neither done nor failed!?";
328 if ($db_needs_update) {
330 $mpd->loop->later( sub { $self->pulse } );
334 if ($playlist_needs_filling) {
336 $mpd->loop->later( sub { $self->pulse } );
340 $log->debug("Waiting idle. PID=$$");
341 $last_mpd_comm = time;
342 $idler = $mpd->send("idle database playlist");
345 $log->trace('got out of idle');
347 if ( $idler->is_done ) {
348 my $result = $idler->get;
350 if ( ref $result and $result->{changed} ) {
351 my $changed = $result->{changed};
352 $changed = [$changed] unless ref $changed;
354 $mpd->emit($_) for @$changed;
357 elsif ( $idler->is_cancelled ) {
358 $log->trace("idle was cancelled");
361 elsif ( $idler->is_failed ) {
362 $log->warn("idle failed: ".$idler->failure);
375 IO::Async::Timer::Periodic->new(
378 if (!$mpd_connected) {
379 $log->trace("Not connected to MPD. Skipping alive check.");
383 if ( time - $last_mpd_comm > 300 ) {
386 "no active MPD communication for more that 5 minutes");
387 $log->debug("forcing alive check");
392 "contacted MPD less than 5 minutes ago. skipping alive check"
400 if ( $quit_requested ) {
401 $log->trace("about to quit");
406 elsif ( $reload_requested ) {
411 $log->trace('About to run the loop');
413 $mpd->loop->later( sub { $self->pulse } );