]> git.ktnx.net Git - mpd-feeder.git/blob - bin/mpd-feeder
5760c751633483dd6f02fe95fe908ae6876e42c1
[mpd-feeder.git] / bin / mpd-feeder
1 #!/usr/bin/perl
2
3 use v5.32;
4
5 use Getopt::Long ();
6 use Log::Any qw($log);
7 use Log::Any::Adapter Stderr => log_level => 'trace';
8 use Object::Pad;
9 use Syntax::Keyword::Try;
10
11 class Options {
12     use Time::Duration qw(duration_exact);
13     use Time::Duration::Parse qw(parse_duration);
14     has $log_level           :reader = 'warn';
15     has $target_queue_length :reader = 10;
16     has $mpd_host            :reader = undef;
17     has $mpd_port            :reader = undef;
18     has $db_path             :reader = 'mpd-feeder';
19     has $db_user             :reader = undef;
20     has $db_password         :reader = undef;
21     has $min_album_interval  :reader = parse_duration('5h');
22     has $min_song_interval   :reader = parse_duration('13d');
23     has $min_artist_interval :reader = parse_duration('1h 15m');
24     has $skip_db_update      :reader = 0;
25
26     method parse_command_line {
27         Getopt::Long::GetOptions(
28             'log-level=s'               => \$log_level,
29             'skip-db-update!'           => \$skip_db_update,
30             'tql|target-queue-length=n' => \$target_queue_length,
31             'mpd-host=s'                => \$mpd_host,
32             'mpd-port=s'                => \$mpd_port,
33             'db-path=s'                 => \$db_path,
34             'db-user=s'                 => \$db_user,
35             'min-album-interval=s'      => sub {
36                 $min_album_interval = parse_duration(pop);
37             },
38             'min-sing-interval=s' => sub {
39                 $min_song_interval = parse_duration(pop);
40             },
41             'min-artist-interval=s' => sub {
42                 $min_artist_interval = parse_duration(pop);
43             },
44         ) or exit 1;
45     }
46
47     sub handle_config_option( $ini, $section, $option, $target_ref,
48         $converter = undef )
49     {
50         return undef unless exists $ini->{$section}{$option};
51
52         my $value = $ini->{$section}{$option};
53
54         $value = $converter->($value) if $converter;
55
56         $$target_ref = $value;
57     }
58
59     method dump {
60         say "[mpd-feeder]";
61         say "log_level = $log_level";
62         say "";
63         say "[mpd]";
64         say "host = " . ( $mpd_host // '' );
65         say "port = " . ( $mpd_port // '' );
66         say "target-queue-length = $target_queue_length";
67         say "";
68         say "[queue]";
69         say "target-length = $target_queue_length";
70         say "min-song-interval = " . duration_exact($min_song_interval);
71         say "min-album-interval = " . duration_exact($min_album_interval);
72         say "min-artist-interval = " . duration_exact($min_artist_interval);
73         say "";
74         say "[db]";
75         say "path = " .     ( $db_path     // '' );
76         say "user = " .     ( $db_user     // '' );
77         say "password = " . ( $db_password // '' );
78     }
79
80     method parse_config_file($path) {
81         use Config::INI::Reader;
82         my $ini = Config::INI::Reader->read_file($path);
83
84         handle_config_option( $ini => mpd => host => \$mpd_host );
85         handle_config_option( $ini => mpd => port => \$mpd_port );
86
87         handle_config_option( $ini => 'mpd-feeder' => log_level => \$log_level );
88
89         handle_config_option(
90             $ini => queue => 'target-length' => \$target_queue_length );
91         handle_config_option(
92             $ini => queue => 'min-song-interval' => \$min_song_interval,
93             \&parse_duration
94         );
95         handle_config_option(
96             $ini => queue => 'min-album-interval' => \$min_album_interval,
97             \&parse_duration
98         );
99         handle_config_option(
100             $ini => queue => 'min-artist-interval' => \$min_artist_interval,
101             \&parse_duration
102         );
103
104         handle_config_option( $ini => db => path     => \$db_path );
105         handle_config_option( $ini => db => user     => \$db_user );
106         handle_config_option( $ini => db => password => \$db_password );
107
108         # FIXME: complain about unknown sections/parameters
109     }
110 }
111
112 class Feeder {
113     has $opt :reader;
114     has $db;
115     has $db_generation;
116     has $mpd :reader;
117
118 use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
119
120 use DBD::Pg;
121 use DBI;
122 use Log::Any qw($log);
123 use Net::Async::MPD;
124
125     ADJUST {
126         $opt = Options->new;
127
128         {
129             my $cfg_file;
130             Getopt::Long::Configure('pass_through');
131             Getopt::Long::GetOptions('cfg|config=s' => \$cfg_file);
132             Getopt::Long::Configure('no_pass_through');
133
134             $cfg_file //= DEFAULT_CONFIG_FILE if -e DEFAULT_CONFIG_FILE;
135
136             $opt->parse_config_file($cfg_file) if $cfg_file;
137         }
138
139         $opt->parse_command_line;
140
141         Log::Any::Adapter->set( Stderr => log_level => $opt->log_level );
142     }
143
144     method connect_mpd {
145         return if $mpd;
146
147         my %conn = ( auto_connect => 1 );
148         $conn{host} = $opt->mpd_host if $opt->mpd_host;
149         $conn{port} = $opt->mpd_port if $opt->mpd_port;
150
151         $mpd = Net::Async::MPD->new(%conn);
152     }
153
154     method connect_db {
155         return if $db;
156
157         $db = DBI->connect( "dbi:Pg:dbname=" . $opt->db_path,
158             $opt->db_user, $opt->db_password,
159             { RaiseError => 1, AutoCommit => 1 } );
160
161         $log->info( "Connected to database " . $opt->db_path );
162         $db_generation = $self->db_get_option('generation');
163         $log->debug("DB generation is $db_generation");
164         $self->update_db unless $opt->skip_db_update;
165     }
166
167     method db_get_option($name) {
168         my $sth = $db->prepare_cached("select $name from options");
169         $sth->execute;
170         my @result = $sth->fetchrow_array;
171
172         return $result[0];
173     }
174
175     method db_set_option( $name, $value ) {
176         my $sth = $db->prepare_cached("update options set $name = ?");
177         $sth->execute($value);
178     }
179
180     method db_store_song($song, $artist, $album) {
181         return unless length($song) and length($artist) and length($album);
182
183         $db->prepare_cached(
184             <<'SQL')->execute( $song, $artist, $album, $db_generation );
185 INSERT INTO songs(path, artist, album, generation)
186 VALUES($1, $2, $3, $4)
187 ON CONFLICT ON CONSTRAINT songs_pkey DO
188 UPDATE SET artist = $2
189          , album = $3
190          , generation = $4
191 SQL
192         $db->prepare_cached(<<'SQL')->execute( $artist, $album, $db_generation );
193 INSERT INTO albums(artist, album, generation)
194 VALUES($1, $2, $3)
195 ON CONFLICT ON CONSTRAINT albums_pkey DO
196 UPDATE SET generation = $3
197 SQL
198         $db->prepare_cached(<<'SQL')->execute( $artist, $db_generation );
199 INSERT INTO artists(artist, generation)
200 VALUES($1, $2)
201 ON CONFLICT ON CONSTRAINT artists_pkey DO
202 UPDATE SET generation = $2
203 SQL
204     }
205
206     method db_remove_stale_entries {
207         my $sth =
208             $db->prepare_cached('DELETE FROM songs WHERE generation <> ?');
209         $sth->execute($db_generation);
210         $log->debug( sprintf( "Deleted %d stale songs", $sth->rows ) );
211
212         $sth = $db->prepare_cached('DELETE FROM albums WHERE generation <> ?');
213         $sth->execute($db_generation);
214         $log->debug( sprintf( "Deleted %d stale albums", $sth->rows ) );
215
216         $sth =
217             $db->prepare_cached('DELETE FROM artists WHERE generation <> ?');
218         $sth->execute($db_generation);
219         $log->debug( sprintf( "Deleted %d stale artists", $sth->rows ) );
220     }
221
222     method db_note_song_qeued($item) {
223         $db->prepare_cached(
224             'UPDATE songs SET last_queued=current_timestamp WHERE path=?')
225             ->execute( $item->{song} );
226         $db->prepare_cached(
227             'UPDATE artists SET last_queued=CURRENT_TIMESTAMP WHERE artist=?')
228             ->execute( $item->{artist} );
229         $db->prepare_cached(
230             'UPDATE albums SET last_queued=CURRENT_TIMESTAMP WHERE artist=? AND album=?'
231         )->execute( $item->{artist}, $item->{album} );
232     }
233
234     method update_db() {
235         $log->info('Updating song database');
236         $mpd->send('listallinfo')->on_done(
237             sub {
238                 try {
239                     my $rows = shift;
240                     $db->begin_work;
241
242                     $db_generation++;
243
244                     my $song_count;
245
246                     foreach my $entry (@$rows) {
247                         next unless exists $entry->{file};
248                         $self->db_store_song( $entry->{file},
249                             $entry->{Artist}, $entry->{Album} );
250                         $song_count++;
251                     }
252
253                     $log->info("Updated data about $song_count songs");
254
255                     $self->db_remove_stale_entries;
256
257                     $self->db_set_option( generation => $db_generation );
258
259                     $db->commit;
260                 }
261                 catch {
262                     my $err = $@;
263
264                     $db_generation--;
265
266                     $db->rollback;
267
268                     die $err;
269                 }
270             }
271         );
272     }
273
274     method db_find_suitable_songs($num) {
275         $self->connect_db;
276
277         my @result;
278         my $sth = $db->prepare_cached(<<SQL);
279 SELECT s.path, s.artist, s.album
280 FROM songs s
281 JOIN artists ar ON ar.artist=s.artist
282 JOIN albums al ON al.album=s.album
283 WHERE (s.last_queued IS NULL OR s.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
284   AND (ar.last_queued IS NULL OR ar.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
285   AND (al.last_queued IS NULL OR al.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
286   AND NOT EXISTS (SELECT 1 FROM blacklisted_artists bar WHERE bar.artist = s.artist)
287   AND NOT EXISTS (SELECT 1 FROM blacklisted_albums  bal WHERE bal.album  = s.album)
288 ORDER BY random()
289 LIMIT ?
290 SQL
291         $sth->execute(
292             $opt->min_song_interval,
293             $opt->min_artist_interval,
294             $opt->min_album_interval,
295             $num,
296         );
297         while ( my @row = $sth->fetchrow_array ) {
298             push @result,
299                 { song => $row[0], artist => $row[1], album => $row[2] };
300         }
301
302         return @result;
303     }
304
305     method queue_songs($num = undef, $callback = undef) {
306         $self->connect_mpd;
307         if (!defined $num) {
308             $mpd->send('playlist')->on_done(
309                 sub {
310                     my $present = scalar @{ $_[0] };
311
312                     $log->notice("Playlist contains $present songs");
313                     if ( $present < $opt->target_queue_length ) {
314                         $self->queue_songs(
315                             $opt->target_queue_length - $present, $callback );
316                     }
317                     else {
318                         $callback->() if $callback;
319                     }
320                 }
321             );
322
323             return;
324         }
325
326         my @list = $self->db_find_suitable_songs($num);
327
328         die "Found no suitable songs" unless @list;
329
330         if ( @list < $num ) {
331             $log->warn(
332                 sprintf(
333                     'Found only %d suitable songs instead of %d',
334                     scalar(@list), $num
335                 )
336             );
337         }
338
339         $log->info("About to add $num songs to the playlist");
340
341         my @paths;
342         for my $song (@list) {
343             my $path = $song->{song};
344             $path =~ s/"/\\"/g;
345             push @paths, $path;
346         }
347
348         $log->debug( "Adding " . join( ', ', map {"«$_»"} @paths ) );
349         my @commands;
350         for (@paths) {
351             push @commands, [ add => "\"$_\"" ];
352         }
353         my $f = $mpd->send( \@commands );
354         warn "here";
355         $f->on_fail( sub { die @_ } );
356         $f->on_done(
357             sub {
358                 warn $_ for @_;
359                 $self->db_note_song_qeued($_) for @list;
360                 $callback->(@_) if $callback;
361             }
362         );
363
364         warn "here";
365     }
366
367     method prepare_to_wait_idle {
368         $log->trace('declaring idle mode');
369         $mpd->send('idle database playlist')->on_done(
370             sub {
371                 warn $_ for @_;
372                 my $result = shift;
373                 use JSON; warn to_json($result);
374
375                 if ( $result->{changed} eq 'database' ) {
376                     $self->update_db;
377                     $self->prepare_to_wait_idle;
378                 }
379                 elsif ( $result->{changed} eq 'playlist' ) {
380                     $self->queue_songs( undef,
381                         sub { $self->prepare_to_wait_idle } );
382                 }
383                 else {
384                     use JSON;
385                     $log->warn(
386                         "Unknown result from idle: " . to_json($result) );
387                     $self->prepare_to_wait_idle;
388                 }
389             }
390         );
391     }
392
393     method run {
394         $mpd->on(
395             close => sub {
396                 die "Connection to MPD lost";
397             }
398         );
399
400         $self->prepare_to_wait_idle;
401     }
402 }
403
404 my $feeder = Feeder->new();
405
406 sub usage {
407     die "Usage: mpd-feeder [option...] [command]\n";
408 }
409
410 if (@ARGV) {
411     usage if @ARGV > 1;
412
413     my $cmd = shift @ARGV;
414
415     if ($cmd eq 'dump-config') {
416         $feeder->opt->dump;
417         exit;
418     }
419 # FIXME: handle blacklist manipulation
420
421     if ( $cmd eq 'one-shot' ) {
422         $feeder->queue_songs(undef, sub { exit });
423         $feeder->mpd->loop->run;
424     }
425     elsif ( $cmd eq 'single' ) {
426         $feeder->queue_songs(1, sub { exit });
427         $feeder->mpd->loop->run;
428     }
429     else {
430         die "Unknown command '$cmd'";
431     }
432 }
433
434
435 $feeder->queue_songs( undef, sub { $feeder->run } );
436
437 $feeder->mpd->loop->run;