]> git.ktnx.net Git - mpd-feeder.git/blob - lib/App/MPD/Feeder.pm
a second HIP/INT signal causes a hard exit()
[mpd-feeder.git] / lib / App / MPD / Feeder.pm
1 package App::MPD::Feeder;
2
3 use strict;
4 use warnings;
5 use utf8;
6 use feature 'state';
7
8 use App::MPD::Feeder::Options;
9 use App::MPD::Feeder::DB;
10 use DBD::Pg;
11 use DBI;
12 use Getopt::Long;
13 use IO::Async::Signal;
14 use Log::Any qw($log);
15 use Net::Async::MPD;
16 use Object::Pad;
17 use Syntax::Keyword::Try;
18
19
20 class App::MPD::Feeder {
21     has $cfg_file :reader;
22     has $opt :reader;
23     has $db :reader;
24     has $db_needs_update = 1;
25     has $mpd :reader;
26
27 use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
28
29     ADJUST {
30         Getopt::Long::Configure('pass_through');
31         Getopt::Long::GetOptions('cfg|config=s' => \$cfg_file);
32         Getopt::Long::Configure('no_pass_through');
33
34         $cfg_file //= DEFAULT_CONFIG_FILE if -e DEFAULT_CONFIG_FILE;
35
36         $self->configure;
37
38         $db_needs_update = 0 if $opt->skip_db_update;
39     }
40
41     method configure {
42         my $new_opt = App::MPD::Feeder::Options->new;
43
44         $new_opt->parse_config_file($cfg_file) if $cfg_file;
45
46         $new_opt->parse_command_line;
47
48         Log::Any::Adapter->set( Stderr => log_level => $new_opt->log_level );
49
50         $opt = $new_opt;
51
52         $db = App::MPD::Feeder::DB->new( opt => $opt );
53     }
54
55     method connect_mpd {
56         return if $mpd;
57
58         my %conn = ( auto_connect => 1 );
59         $conn{host} = $opt->mpd_host if $opt->mpd_host;
60         $conn{port} = $opt->mpd_port if $opt->mpd_port;
61
62         $mpd = Net::Async::MPD->new(%conn);
63
64         my $int_signal_handler = sub {
65             state $signal_count = 0;
66             $signal_count++;
67             $log->debug("Signal received. Stopping loop");
68             $mpd->loop->stop('quit');
69
70             if ( $signal_count > 1 ) {
71                 $log->warn("Another signal received (#$signal_count)");
72                 $log->warn("Exiting abruptly");
73                 exit 2;
74             }
75         };
76
77         for (qw(TERM INT)) {
78             $mpd->loop->add(
79                 IO::Async::Signal->new(
80                     name       => $_,
81                     on_receipt => $int_signal_handler,
82                 )
83             );
84         }
85
86         $mpd->loop->add(
87             IO::Async::Signal->new(
88                 name       => 'HUP',
89                 on_receipt => sub {
90                     $log->debug("SIGHUP received. Scheduling reload");
91                     $mpd->loop->stop('reload');
92                 },
93             )
94         );
95
96         $mpd->loop->add(
97             IO::Async::Signal->new(
98                 name       => 'USR1',
99                 on_receipt => sub {
100                     $log->debug("SIGUSR1 received. Dumping configuration to STDERR");
101                     my $old = select \*STDERR;
102                     try {
103                         $opt->dump;
104                     }
105                     finally {
106                         select $old;
107                     }
108                 },
109             )
110         );
111     }
112
113     method connect_db {
114         $db->connect($opt);
115         $self->update_db;
116     }
117
118     method update_db($force = undef) {
119         if (!$db_needs_update and !$force) {
120             $log->debug("Skipping DB update");
121             return;
122         }
123
124         $log->info('Updating song database');
125         $self->connect_mpd;
126
127         my $rows = $mpd->send('listallinfo')->get;
128
129         $db->start_update;
130         try {
131             my $song_count;
132
133             foreach my $entry (@$rows) {
134                 next unless exists $entry->{file};
135
136                 $self->db->store_song( $entry->{file},
137                     $entry->{AlbumArtist} // $entry->{Artist},
138                     $entry->{Album} );
139                 $song_count++;
140             }
141
142             $log->info("Updated data about $song_count songs");
143
144             $self->db->remove_stale_entries;
145
146             $self->db->finish_update;
147
148             $db_needs_update = 0;
149         }
150         catch {
151             my $err = $@;
152             $self->db->cancel_update;
153             die $err;
154         }
155     }
156
157     method queue_songs($num = undef, $callback = undef) {
158         $self->connect_db;
159         if (!defined $num) {
160             $self->connect_mpd;
161             $mpd->send('playlist')->on_done(
162                 sub {
163                     my $present = scalar @{ $_[0] };
164
165                     $log->notice( "Playlist contains $present songs. Wanted: "
166                             . $opt->target_queue_length );
167                     if ( $present < $opt->target_queue_length ) {
168                         $self->queue_songs(
169                             $opt->target_queue_length - $present, $callback );
170                     }
171                     else {
172                         $callback->() if $callback;
173                     }
174                 }
175             );
176
177             return;
178         }
179
180         my @list = $self->db->find_suitable_songs($num);
181
182         die "Found no suitable songs" unless @list;
183
184         if ( @list < $num ) {
185             $log->warn(
186                 sprintf(
187                     'Found only %d suitable songs instead of %d',
188                     scalar(@list), $num
189                 )
190             );
191         }
192
193         $log->info("About to add $num songs to the playlist");
194
195         my @paths;
196         for my $song (@list) {
197             my $path = $song->{song};
198             $path =~ s/"/\\"/g;
199             push @paths, $path;
200         }
201
202         $log->debug( "Adding " . join( ', ', map {"«$_»"} @paths ) );
203         # MPD needs raw bytes
204         utf8::encode($_) for @paths;
205         my @commands;
206         for (@paths) {
207             push @commands, [ add => "\"$_\"" ];
208         }
209         $self->connect_mpd;
210         my $f = $mpd->send( \@commands );
211         $f->on_fail( sub { die @_ } );
212         $f->on_done(
213             sub {
214                 $self->db->note_song_qeued($_) for @list;
215                 $callback->(@_) if $callback;
216             }
217         );
218     }
219
220     method prepare_to_wait_idle {
221         $log->trace('declaring idle mode');
222         $mpd->send('idle database playlist')->on_done(
223             sub {
224                 my $result = shift;
225
226                 if ( $result->{changed} eq 'database' ) {
227                     $db_needs_update = 1;
228                     $self->prepare_to_wait_idle;
229                 }
230                 elsif ( $result->{changed} eq 'playlist' ) {
231                     $self->queue_songs( undef,
232                         sub { $self->prepare_to_wait_idle } );
233                 }
234                 else {
235                     use JSON;
236                     $log->warn(
237                         "Unknown result from idle: " . to_json($result) );
238                     $self->prepare_to_wait_idle;
239                 }
240             }
241         );
242     }
243
244     method run {
245         $mpd->on(
246             close => sub {
247                 die "Connection to MPD lost";
248             }
249         );
250
251         $self->prepare_to_wait_idle;
252     }
253
254     method stop {
255         undef $mpd;
256
257         $db->disconnect;
258     }
259
260     method run_loop {
261         $self->connect_db;
262
263         for ( ;; ) {
264             $self->queue_songs( undef, sub { $self->run } );
265
266             $log->debug("Entering event loop. PID=$$");
267
268             my $result = $mpd->loop->run;
269             $log->trace( "Got loop result of " . ( $result // 'undef' ) );
270
271             if ( 'reload' eq $result ) {
272                 $log->notice("disconnecting");
273                 $self->stop;
274
275                 my @exec = ( $0, '--config', $self->cfg_file, '--skip-db-update' );
276                 if ( $log->is_trace ) {
277                     $log->trace( 'exec '
278                             . join( ' ', map { /\s/ ? "'$_'" : $_ } @exec ) );
279                 }
280                 exec(@exec);
281             }
282
283             if ( 'quit' eq $result ) {
284                 $log->trace("quitting because of 'quit' loop result");
285                 $self->stop;
286                 exit 0;
287             }
288         }
289     }
290 }
291