]> git.ktnx.net Git - mpd-feeder.git/blob - bin/mpd-feeder
da60df88a227312970e952c9f4506ecebf33ac2b
[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 => 'error';
8 use Object::Pad;
9 use Syntax::Keyword::Try;
10
11 class Options {
12     use Log::Any qw($log);
13     use Time::Duration qw(duration_exact);
14     use Time::Duration::Parse qw(parse_duration);
15     has $log_level           :reader = 'warn';
16     has $target_queue_length :reader = 10;
17     has $mpd_host            :reader = undef;
18     has $mpd_port            :reader = undef;
19     has $db_path             :reader = 'mpd-feeder';
20     has $db_user             :reader = undef;
21     has $db_password         :reader = undef;
22     has $min_album_interval  :reader = parse_duration('5h');
23     has $min_song_interval   :reader = parse_duration('13d');
24     has $min_artist_interval :reader = parse_duration('1h 15m');
25     has $skip_db_update      :reader = 0;
26
27     method parse_command_line {
28         Getopt::Long::GetOptions(
29             'log-level=s'               => \$log_level,
30             'skip-db-update!'           => \$skip_db_update,
31             'tql|target-queue-length=n' => sub {
32                 $target_queue_length = parse_integer(pop);
33             },
34             'mpd-host=s'           => \$mpd_host,
35             'mpd-port=s'           => \$mpd_port,
36             'db-path=s'            => \$db_path,
37             'db-user=s'            => \$db_user,
38             'min-album-interval=s' => sub {
39                 $min_album_interval = parse_duration(pop);
40             },
41             'min-sing-interval=s' => sub {
42                 $min_song_interval = parse_duration(pop);
43             },
44             'min-artist-interval=s' => sub {
45                 $min_artist_interval = parse_duration(pop);
46             },
47         ) or exit 1;
48     }
49
50     sub handle_config_option( $ini, $section, $option, $target_ref,
51         $converter = undef )
52     {
53         return undef unless exists $ini->{$section}{$option};
54
55         my $value = $ini->{$section}{$option};
56
57         $value = $converter->($value) if $converter;
58
59         $$target_ref = $value;
60
61         $log->trace("Option $section.$option = $value");
62     }
63
64     method dump {
65         say "[mpd-feeder]";
66         say "log_level = $log_level";
67         say "";
68         say "[mpd]";
69         say "host = " . ( $mpd_host // '' );
70         say "port = " . ( $mpd_port // '' );
71         say "";
72         say "[queue]";
73         say "target-length = $target_queue_length";
74         say "min-song-interval = " . duration_exact($min_song_interval);
75         say "min-album-interval = " . duration_exact($min_album_interval);
76         say "min-artist-interval = " . duration_exact($min_artist_interval);
77         say "";
78         say "[db]";
79         say "path = " .     ( $db_path     // '' );
80         say "user = " .     ( $db_user     // '' );
81         say "password = " . ( $db_password // '' );
82     }
83
84     sub parse_integer($input) {
85         die "Invalid integer value '$input'" unless $input =~ /^\+?\d{1,18}$/;
86         return $input + 0;
87     }
88
89     method parse_config_file($path) {
90         $log->trace("Parsing configuration file $path");
91
92         use Config::INI::Reader;
93         my $ini = Config::INI::Reader->read_file($path);
94
95         handle_config_option( $ini => mpd => host => \$mpd_host );
96         handle_config_option( $ini => mpd => port => \$mpd_port );
97
98         handle_config_option( $ini => 'mpd-feeder' => log_level => \$log_level );
99
100         handle_config_option(
101             $ini => queue => 'target-length' => \$target_queue_length,
102             \&parse_integer
103         );
104         handle_config_option(
105             $ini => queue => 'min-song-interval' => \$min_song_interval,
106             \&parse_duration
107         );
108         handle_config_option(
109             $ini => queue => 'min-album-interval' => \$min_album_interval,
110             \&parse_duration
111         );
112         handle_config_option(
113             $ini => queue => 'min-artist-interval' => \$min_artist_interval,
114             \&parse_duration
115         );
116
117         handle_config_option( $ini => db => path     => \$db_path );
118         handle_config_option( $ini => db => user     => \$db_user );
119         handle_config_option( $ini => db => password => \$db_password );
120
121         # FIXME: complain about unknown sections/parameters
122     }
123 }
124
125 class Feeder {
126     has $cfg_file :reader;
127     has $opt :reader;
128     has $db;
129     has $db_generation;
130     has $db_needs_update :writer = 1;
131     has $mpd :reader;
132
133 use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
134
135 use DBD::Pg;
136 use DBI;
137 use Log::Any qw($log);
138 use IO::Async::Signal;
139 use Net::Async::MPD;
140
141     ADJUST {
142         Getopt::Long::Configure('pass_through');
143         Getopt::Long::GetOptions('cfg|config=s' => \$cfg_file);
144         Getopt::Long::Configure('no_pass_through');
145
146         $cfg_file //= DEFAULT_CONFIG_FILE if -e DEFAULT_CONFIG_FILE;
147
148         $self->configure;
149
150         $db_needs_update = 0 if $opt->skip_db_update;
151     }
152
153     method configure {
154         my $new_opt = Options->new;
155
156         $new_opt->parse_config_file($cfg_file) if $cfg_file;
157
158         $new_opt->parse_command_line;
159
160         Log::Any::Adapter->set( Stderr => log_level => $new_opt->log_level );
161
162         $opt = $new_opt;
163     }
164
165     method connect_mpd {
166         return if $mpd;
167
168         my %conn = ( auto_connect => 1 );
169         $conn{host} = $opt->mpd_host if $opt->mpd_host;
170         $conn{port} = $opt->mpd_port if $opt->mpd_port;
171
172         $mpd = Net::Async::MPD->new(%conn);
173
174         $mpd->loop->add(
175             IO::Async::Signal->new(
176                 name       => 'HUP',
177                 on_receipt => sub {
178                     $log->debug("SIGHUP received. Stopping loop");
179                     $mpd->loop->stop('reload');
180                 },
181             )
182         );
183     }
184
185     method connect_db {
186         return if $db;
187
188         $db = DBI->connect( "dbi:Pg:dbname=" . $opt->db_path,
189             $opt->db_user, $opt->db_password,
190             { RaiseError => 1, PrintError => 0, AutoCommit => 1 } );
191
192         $log->info( "Connected to database " . $opt->db_path );
193         $db_generation = $self->db_get_option('generation');
194         $log->debug("DB generation is $db_generation");
195         $self->update_db;
196     }
197
198     method db_get_option($name) {
199         my $sth = $db->prepare_cached("select $name from options");
200         $sth->execute;
201         my @result = $sth->fetchrow_array;
202
203         return $result[0];
204     }
205
206     method db_set_option( $name, $value ) {
207         my $sth = $db->prepare_cached("update options set $name = ?");
208         $sth->execute($value);
209     }
210
211     method db_store_song($song, $artist, $album) {
212         return unless length($song) and length($artist) and length($album);
213
214         $db->prepare_cached(
215             <<'SQL')->execute( $song, $artist, $album, $db_generation );
216 INSERT INTO songs(path, artist, album, generation)
217 VALUES($1, $2, $3, $4)
218 ON CONFLICT ON CONSTRAINT songs_pkey DO
219 UPDATE SET artist = $2
220          , album = $3
221          , generation = $4
222 SQL
223         $db->prepare_cached(<<'SQL')->execute( $artist, $album, $db_generation );
224 INSERT INTO albums(artist, album, generation)
225 VALUES($1, $2, $3)
226 ON CONFLICT ON CONSTRAINT albums_pkey DO
227 UPDATE SET generation = $3
228 SQL
229         $db->prepare_cached(<<'SQL')->execute( $artist, $db_generation );
230 INSERT INTO artists(artist, generation)
231 VALUES($1, $2)
232 ON CONFLICT ON CONSTRAINT artists_pkey DO
233 UPDATE SET generation = $2
234 SQL
235     }
236
237     method db_remove_stale_entries {
238         my $sth =
239             $db->prepare_cached('DELETE FROM songs WHERE generation <> ?');
240         $sth->execute($db_generation);
241         $log->debug( sprintf( "Deleted %d stale songs", $sth->rows ) );
242
243         $sth = $db->prepare_cached('DELETE FROM albums WHERE generation <> ?');
244         $sth->execute($db_generation);
245         $log->debug( sprintf( "Deleted %d stale albums", $sth->rows ) );
246
247         $sth =
248             $db->prepare_cached('DELETE FROM artists WHERE generation <> ?');
249         $sth->execute($db_generation);
250         $log->debug( sprintf( "Deleted %d stale artists", $sth->rows ) );
251     }
252
253     method db_note_song_qeued($item) {
254         $db->prepare_cached(
255             'UPDATE songs SET last_queued=current_timestamp WHERE path=?')
256             ->execute( $item->{song} );
257         $db->prepare_cached(
258             'UPDATE artists SET last_queued=CURRENT_TIMESTAMP WHERE artist=?')
259             ->execute( $item->{artist} );
260         $db->prepare_cached(
261             'UPDATE albums SET last_queued=CURRENT_TIMESTAMP WHERE artist=? AND album=?'
262         )->execute( $item->{artist}, $item->{album} );
263     }
264
265     method update_db($force = undef) {
266         if (!$db_needs_update and !$force) {
267             $log->debug("Skipping DB update");
268             return;
269         }
270
271         $log->info('Updating song database');
272         $self->connect_mpd;
273         $self->connect_db;
274
275         my $rows = $mpd->send('listallinfo')->get;
276         try {
277             $db->begin_work;
278
279             $db_generation++;
280
281             my $song_count;
282
283             foreach my $entry (@$rows) {
284                 next unless exists $entry->{file};
285                 $self->db_store_song( $entry->{file},
286                     $entry->{Artist}, $entry->{Album} );
287                 $song_count++;
288             }
289
290             $log->info("Updated data about $song_count songs");
291
292             $self->db_remove_stale_entries;
293
294             $self->db_set_option( generation => $db_generation );
295
296             $db->commit;
297
298             $db_needs_update = 0;
299         }
300         catch {
301             my $err = $@;
302
303             $db_generation--;
304
305             $db->rollback;
306
307             die $err;
308         }
309     }
310
311     method db_find_suitable_songs($num) {
312         $self->connect_db;
313         $self->update_db;
314
315         my @result;
316         my $sth = $db->prepare_cached(<<SQL);
317 SELECT s.path, s.artist, s.album
318 FROM songs s
319 JOIN artists ar ON ar.artist=s.artist
320 JOIN albums al ON al.album=s.album
321 WHERE (s.last_queued IS NULL OR s.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
322   AND (ar.last_queued IS NULL OR ar.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
323   AND (al.last_queued IS NULL OR al.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
324   AND NOT EXISTS (SELECT 1 FROM unwanted_artists uar WHERE uar.artist = s.artist)
325   AND NOT EXISTS (SELECT 1 FROM unwanted_albums  ual WHERE ual.album  = s.album)
326 ORDER BY random()
327 LIMIT ?
328 SQL
329         $sth->execute(
330             $opt->min_song_interval,
331             $opt->min_artist_interval,
332             $opt->min_album_interval,
333             $num,
334         );
335         while ( my @row = $sth->fetchrow_array ) {
336             push @result,
337                 { song => $row[0], artist => $row[1], album => $row[2] };
338         }
339
340         return @result;
341     }
342
343     method db_add_unwanted_artist($artist) {
344         $self->connect_db;
345
346         try {
347             $db->do(
348                 <<'SQL',
349 INSERT INTO unwanted_artists(artist, generation)
350 VALUES($1, $2)
351 SQL
352                 undef, $artist, $db_generation
353             );
354             return 1;
355         }
356         catch {
357             my $err = $@;
358
359             $log->debug("PostgreSQL error: $err");
360             $log->debug( "SQLSTATE = " . $db->state );
361             return 0 if $db->state eq '23505';
362
363             die $err;
364         }
365     }
366
367     method db_del_unwanted_artist($artist) {
368         $self->connect_db;
369
370         return 1 == $db->do(
371             <<'SQL',
372 DELETE FROM unwanted_artists
373 WHERE artist = $1
374 SQL
375             undef, $artist
376         );
377     }
378
379     method queue_songs($num = undef, $callback = undef) {
380         if (!defined $num) {
381             $self->connect_mpd;
382             $mpd->send('playlist')->on_done(
383                 sub {
384                     my $present = scalar @{ $_[0] };
385
386                     $log->notice("Playlist contains $present songs");
387                     if ( $present < $opt->target_queue_length ) {
388                         $self->queue_songs(
389                             $opt->target_queue_length - $present, $callback );
390                     }
391                     else {
392                         $callback->() if $callback;
393                     }
394                 }
395             );
396
397             return;
398         }
399
400         my @list = $self->db_find_suitable_songs($num);
401
402         die "Found no suitable songs" unless @list;
403
404         if ( @list < $num ) {
405             $log->warn(
406                 sprintf(
407                     'Found only %d suitable songs instead of %d',
408                     scalar(@list), $num
409                 )
410             );
411         }
412
413         $log->info("About to add $num songs to the playlist");
414
415         my @paths;
416         for my $song (@list) {
417             my $path = $song->{song};
418             $path =~ s/"/\\"/g;
419             push @paths, $path;
420         }
421
422         $log->debug( "Adding " . join( ', ', map {"«$_»"} @paths ) );
423         my @commands;
424         for (@paths) {
425             push @commands, [ add => "\"$_\"" ];
426         }
427         $self->connect_mpd;
428         my $f = $mpd->send( \@commands );
429         $f->on_fail( sub { die @_ } );
430         $f->on_done(
431             sub {
432                 $self->db_note_song_qeued($_) for @list;
433                 $callback->(@_) if $callback;
434             }
435         );
436     }
437
438     method prepare_to_wait_idle {
439         $log->trace('declaring idle mode');
440         $mpd->send('idle database playlist')->on_done(
441             sub {
442                 my $result = shift;
443
444                 if ( $result->{changed} eq 'database' ) {
445                     $db_needs_update = 1;
446                     $self->prepare_to_wait_idle;
447                 }
448                 elsif ( $result->{changed} eq 'playlist' ) {
449                     $self->queue_songs( undef,
450                         sub { $self->prepare_to_wait_idle } );
451                 }
452                 else {
453                     use JSON;
454                     $log->warn(
455                         "Unknown result from idle: " . to_json($result) );
456                     $self->prepare_to_wait_idle;
457                 }
458             }
459         );
460     }
461
462     method run {
463         $mpd->on(
464             close => sub {
465                 die "Connection to MPD lost";
466             }
467         );
468
469         $self->prepare_to_wait_idle;
470     }
471
472     method stop {
473         undef $mpd;
474
475         if ($db) {
476             if ($db->{ActiveKids}) {
477                 $log->warn("$db->{ActiveKids} active DB statements");
478                 for my $st ( @{ $db->{ChildHandles} } ) {
479                     next unless $st->{Active};
480                     while(my($k,$v) = each %$st) {
481                         $log->debug("$k = ".($v//'<NULL>'));
482                     }
483                 }
484             }
485
486             $db->disconnect;
487             undef $db;
488         }
489     }
490 }
491
492 my $feeder = Feeder->new();
493
494 if (@ARGV) {
495     my $cmd = shift @ARGV;
496
497     if ($cmd eq 'dump-config') {
498         die "dump-config command accepts no arguments\n" if @ARGV;
499
500         $feeder->opt->dump;
501         exit;
502     }
503
504     if ( $cmd eq 'add-unwanted-artist' ) {
505         die "Missing command arguments\n" unless @ARGV;
506         $feeder->set_db_needs_update(0);
507         for my $artist (@ARGV) {
508             if ( $feeder->db_add_unwanted_artist($artist) ) {
509                 $log->info("Artist '$artist' added to the unwanted list\n");
510             }
511             else {
512                 $log->warn("Artist '$artist' already in the unwanted list\n");
513             }
514         }
515         exit;
516     }
517
518     if ( $cmd eq 'del-unwanted-artist' ) {
519         die "Missing command arguments\n" unless @ARGV;
520         $feeder->set_db_needs_update(0);
521         for my $artist (@ARGV) {
522             if ( $feeder->db_del_unwanted_artist($artist) ) {
523                 $log->info("Artist '$artist' deleted from the unwanted list\n");
524             }
525             else {
526                 $log->warn("Artist '$artist' is not in the unwanted list\n");
527             }
528         }
529         exit;
530     }
531
532     if ( $cmd eq 'add-unwanted-album' ) {
533         die "NOT IMPLEMENTED\n";
534     }
535
536     if ( $cmd eq 'one-shot' ) {
537         die "one-shot command accepts no arguments\n" if @ARGV;
538
539         $feeder->queue_songs(undef, sub { exit });
540         $feeder->mpd->loop->run;
541     }
542     elsif ( $cmd eq 'single' ) {
543         die "single command accepts no arguments\n" if @ARGV;
544
545         $feeder->queue_songs(1, sub { exit });
546         $feeder->mpd->loop->run;
547     }
548     else {
549         die "Unknown command '$cmd'";
550     }
551 }
552
553 for ( ;; ) {
554     $feeder->queue_songs( undef, sub { $feeder->run } );
555
556     $log->debug("Entering event loop. PID=$$");
557
558     my $result = $feeder->mpd->loop->run;
559     $log->trace( "Got loop result of " . ( $result // 'undef' ) );
560
561     if ('reload' eq $result) {
562         $log->notice("disconnecting");
563         $feeder->stop;
564
565         exec( "$0", '--config', $feeder->cfg_file, '--skip-db-update' );
566     }
567 }