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