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