]> git.ktnx.net Git - mpd-feeder.git/blob - lib/App/MPD/Feeder.pm
whitespace
[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(
120                     "SIGUSR1 received. Dumping configuration to STDERR");
121                 my $old = select \*STDERR;
122                 try {
123                     $opt->dump;
124                 }
125                 finally {
126                     select $old;
127                 }
128             },
129         )
130     );
131 }
132
133 method connect_db {
134     $db->connect($opt);
135     $self->update_db;
136 }
137
138 method update_db( $force = undef ) {
139     if ( !$db_needs_update and !$force ) {
140         $log->debug("Skipping DB update");
141         return;
142     }
143
144     $log->info('Updating song database');
145     $self->connect_mpd;
146
147     my $rows = $mpd->send('listallinfo')->get;
148
149     $log->trace('got all songs from MPD');
150
151     $db->start_update;
152     try {
153         my $song_count;
154
155         foreach my $entry (@$rows) {
156             next unless exists $entry->{file};
157
158             $self->db->store_song( $entry->{file},
159                 $entry->{AlbumArtist} // $entry->{Artist},
160                 $entry->{Album} );
161
162             $song_count++;
163         }
164
165         my ($total_songs, $total_artists, $total_albums,
166             $new_songs,   $new_artists,   $new_albums
167         ) = $self->db->finish_update;
168
169         $log->info(
170             "Updated data about $song_count songs (including $new_songs new), "
171                 . "$total_artists artists (including $new_artists new) "
172
173                 . "and $total_albums albums (including $new_albums new)"
174         );
175
176         $db_needs_update = 0;
177     }
178     catch {
179         my $err = $@;
180         $self->db->cancel_update;
181         die $err;
182     }
183 }
184
185 method queue_songs( $num = undef ) {
186     $self->connect_db;
187     if ( !defined $num ) {
188         $self->connect_mpd;
189         $log->trace("Requesting playlist");
190         my $present = $mpd->send('playlist')->get // [];
191         $present = scalar(@$present);
192
193         $log->notice( "Playlist contains $present songs. Wanted: "
194                 . $opt->target_queue_length );
195         if ( $present < $opt->target_queue_length ) {
196             $self->queue_songs( $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
226     # MPD needs raw bytes
227     utf8::encode($_) for @paths;
228     my @commands;
229     for (@paths) {
230         push @commands, [ add => "\"$_\"" ];
231     }
232     $self->connect_mpd;
233     my $f = $mpd->send( \@commands );
234     $f->on_fail( sub { die @_ } );
235     $f->on_done(
236         sub {
237             $self->db->note_song_qeued($_) for @list;
238         }
239     );
240     $f->get;
241 }
242
243 method stop {
244     undef $mpd;
245
246     $db->disconnect;
247 }
248
249 method handle_work_queue {
250     while ( my $item = $work_queue->next ) {
251         if ( $item eq 'playlist' ) {
252             $self->queue_songs;
253         }
254         elsif ( $item eq 'database' ) {
255             $db_needs_update = 1;
256             $self->update_db;
257         }
258         elsif ( $item eq 'reload' ) {
259             $log->notice("disconnecting and re-starting");
260             $self->stop;
261
262             my @exec = ( $0, '--config', $self->cfg_file, '--skip-db-update' );
263             if ( $log->is_trace ) {
264                 $log->trace(
265                     'exec ' . 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                     $log->trace("forcing alive check");
304                     $self->break_idle;
305                 }
306                 else {
307                     $log->trace(
308                         "contacted MPD less than 5 minutes ago. skipping alive check"
309                     );
310                 }
311             },
312         )->start
313     );
314
315     $self->queue_songs;
316
317     for ( ;; ) {
318         $log->debug("Waiting idle. PID=$$");
319         $last_mpd_comm = time;
320         $idler         = $mpd->send("idle database playlist");
321         my $result = $idler->get;
322         undef $idler;
323
324         if ( $result and $result->{changed} ) {
325             my $changed = $result->{changed};
326             $changed = [$changed] unless ref $changed;
327
328             $mpd->emit($_) for @$changed;
329         }
330
331         $log->trace('got out of idle');
332
333         $self->handle_work_queue;
334     }
335 }
336
337 1;