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