]> git.ktnx.net Git - mpd-feeder.git/blob - bin/mpd-feeder
097a7a654f3110d2ca1048540285efc5241932eb
[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 $db_needs_update = 1;
117     has $mpd :reader;
118
119 use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
120
121 use DBD::Pg;
122 use DBI;
123 use Log::Any qw($log);
124 use Net::Async::MPD;
125
126     ADJUST {
127         $opt = Options->new;
128
129         {
130             my $cfg_file;
131             Getopt::Long::Configure('pass_through');
132             Getopt::Long::GetOptions('cfg|config=s' => \$cfg_file);
133             Getopt::Long::Configure('no_pass_through');
134
135             $cfg_file //= DEFAULT_CONFIG_FILE if -e DEFAULT_CONFIG_FILE;
136
137             $opt->parse_config_file($cfg_file) if $cfg_file;
138         }
139
140         $opt->parse_command_line;
141
142         $db_needs_update = 0 if $opt->skip_db_update;
143
144         Log::Any::Adapter->set( Stderr => log_level => $opt->log_level );
145     }
146
147     method connect_mpd {
148         return if $mpd;
149
150         my %conn = ( auto_connect => 1 );
151         $conn{host} = $opt->mpd_host if $opt->mpd_host;
152         $conn{port} = $opt->mpd_port if $opt->mpd_port;
153
154         $mpd = Net::Async::MPD->new(%conn);
155     }
156
157     method connect_db {
158         return if $db;
159
160         $db = DBI->connect( "dbi:Pg:dbname=" . $opt->db_path,
161             $opt->db_user, $opt->db_password,
162             { RaiseError => 1, AutoCommit => 1 } );
163
164         $log->info( "Connected to database " . $opt->db_path );
165         $db_generation = $self->db_get_option('generation');
166         $log->debug("DB generation is $db_generation");
167         $self->update_db;
168     }
169
170     method db_get_option($name) {
171         my $sth = $db->prepare_cached("select $name from options");
172         $sth->execute;
173         my @result = $sth->fetchrow_array;
174
175         return $result[0];
176     }
177
178     method db_set_option( $name, $value ) {
179         my $sth = $db->prepare_cached("update options set $name = ?");
180         $sth->execute($value);
181     }
182
183     method db_store_song($song, $artist, $album) {
184         return unless length($song) and length($artist) and length($album);
185
186         $db->prepare_cached(
187             <<'SQL')->execute( $song, $artist, $album, $db_generation );
188 INSERT INTO songs(path, artist, album, generation)
189 VALUES($1, $2, $3, $4)
190 ON CONFLICT ON CONSTRAINT songs_pkey DO
191 UPDATE SET artist = $2
192          , album = $3
193          , generation = $4
194 SQL
195         $db->prepare_cached(<<'SQL')->execute( $artist, $album, $db_generation );
196 INSERT INTO albums(artist, album, generation)
197 VALUES($1, $2, $3)
198 ON CONFLICT ON CONSTRAINT albums_pkey DO
199 UPDATE SET generation = $3
200 SQL
201         $db->prepare_cached(<<'SQL')->execute( $artist, $db_generation );
202 INSERT INTO artists(artist, generation)
203 VALUES($1, $2)
204 ON CONFLICT ON CONSTRAINT artists_pkey DO
205 UPDATE SET generation = $2
206 SQL
207     }
208
209     method db_remove_stale_entries {
210         my $sth =
211             $db->prepare_cached('DELETE FROM songs WHERE generation <> ?');
212         $sth->execute($db_generation);
213         $log->debug( sprintf( "Deleted %d stale songs", $sth->rows ) );
214
215         $sth = $db->prepare_cached('DELETE FROM albums WHERE generation <> ?');
216         $sth->execute($db_generation);
217         $log->debug( sprintf( "Deleted %d stale albums", $sth->rows ) );
218
219         $sth =
220             $db->prepare_cached('DELETE FROM artists WHERE generation <> ?');
221         $sth->execute($db_generation);
222         $log->debug( sprintf( "Deleted %d stale artists", $sth->rows ) );
223     }
224
225     method db_note_song_qeued($item) {
226         $db->prepare_cached(
227             'UPDATE songs SET last_queued=current_timestamp WHERE path=?')
228             ->execute( $item->{song} );
229         $db->prepare_cached(
230             'UPDATE artists SET last_queued=CURRENT_TIMESTAMP WHERE artist=?')
231             ->execute( $item->{artist} );
232         $db->prepare_cached(
233             'UPDATE albums SET last_queued=CURRENT_TIMESTAMP WHERE artist=? AND album=?'
234         )->execute( $item->{artist}, $item->{album} );
235     }
236
237     method update_db($force = undef) {
238         if (!$db_needs_update and !$force) {
239             $log->debug("Skipping DB update");
240             return;
241         }
242
243         $log->info('Updating song database');
244         $self->connect_mpd;
245         $self->connect_db;
246
247         $mpd->send('listallinfo')->on_done(
248             sub {
249                 try {
250                     my $rows = shift;
251                     $db->begin_work;
252
253                     $db_generation++;
254
255                     my $song_count;
256
257                     foreach my $entry (@$rows) {
258                         next unless exists $entry->{file};
259                         $self->db_store_song( $entry->{file},
260                             $entry->{Artist}, $entry->{Album} );
261                         $song_count++;
262                     }
263
264                     $log->info("Updated data about $song_count songs");
265
266                     $self->db_remove_stale_entries;
267
268                     $self->db_set_option( generation => $db_generation );
269
270                     $db->commit;
271                 }
272                 catch {
273                     my $err = $@;
274
275                     $db_generation--;
276
277                     $db->rollback;
278
279                     die $err;
280                 }
281             }
282         );
283     }
284
285     method db_find_suitable_songs($num) {
286         $self->connect_db;
287
288         my @result;
289         my $sth = $db->prepare_cached(<<SQL);
290 SELECT s.path, s.artist, s.album
291 FROM songs s
292 JOIN artists ar ON ar.artist=s.artist
293 JOIN albums al ON al.album=s.album
294 WHERE (s.last_queued IS NULL OR s.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
295   AND (ar.last_queued IS NULL OR ar.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
296   AND (al.last_queued IS NULL OR al.last_queued < CURRENT_TIMESTAMP - (? || ' seconds')::interval)
297   AND NOT EXISTS (SELECT 1 FROM blacklisted_artists bar WHERE bar.artist = s.artist)
298   AND NOT EXISTS (SELECT 1 FROM blacklisted_albums  bal WHERE bal.album  = s.album)
299 ORDER BY random()
300 LIMIT ?
301 SQL
302         $sth->execute(
303             $opt->min_song_interval,
304             $opt->min_artist_interval,
305             $opt->min_album_interval,
306             $num,
307         );
308         while ( my @row = $sth->fetchrow_array ) {
309             push @result,
310                 { song => $row[0], artist => $row[1], album => $row[2] };
311         }
312
313         return @result;
314     }
315
316     method queue_songs($num = undef, $callback = undef) {
317         if (!defined $num) {
318             $self->connect_mpd;
319             $mpd->send('playlist')->on_done(
320                 sub {
321                     my $present = scalar @{ $_[0] };
322
323                     $log->notice("Playlist contains $present songs");
324                     if ( $present < $opt->target_queue_length ) {
325                         $self->queue_songs(
326                             $opt->target_queue_length - $present, $callback );
327                     }
328                     else {
329                         $callback->() if $callback;
330                     }
331                 }
332             );
333
334             return;
335         }
336
337         my @list = $self->db_find_suitable_songs($num);
338
339         die "Found no suitable songs" unless @list;
340
341         if ( @list < $num ) {
342             $log->warn(
343                 sprintf(
344                     'Found only %d suitable songs instead of %d',
345                     scalar(@list), $num
346                 )
347             );
348         }
349
350         $log->info("About to add $num songs to the playlist");
351
352         my @paths;
353         for my $song (@list) {
354             my $path = $song->{song};
355             $path =~ s/"/\\"/g;
356             push @paths, $path;
357         }
358
359         $log->debug( "Adding " . join( ', ', map {"«$_»"} @paths ) );
360         my @commands;
361         for (@paths) {
362             push @commands, [ add => "\"$_\"" ];
363         }
364         $self->connect_mpd;
365         my $f = $mpd->send( \@commands );
366         warn "here";
367         $f->on_fail( sub { die @_ } );
368         $f->on_done(
369             sub {
370                 warn $_ for @_;
371                 $self->db_note_song_qeued($_) for @list;
372                 $callback->(@_) if $callback;
373             }
374         );
375
376         warn "here";
377     }
378
379     method prepare_to_wait_idle {
380         $log->trace('declaring idle mode');
381         $mpd->send('idle database playlist')->on_done(
382             sub {
383                 warn $_ for @_;
384                 my $result = shift;
385                 use JSON; warn to_json($result);
386
387                 if ( $result->{changed} eq 'database' ) {
388                     $self->update_db(1);
389                     $self->prepare_to_wait_idle;
390                 }
391                 elsif ( $result->{changed} eq 'playlist' ) {
392                     $self->queue_songs( undef,
393                         sub { $self->prepare_to_wait_idle } );
394                 }
395                 else {
396                     use JSON;
397                     $log->warn(
398                         "Unknown result from idle: " . to_json($result) );
399                     $self->prepare_to_wait_idle;
400                 }
401             }
402         );
403     }
404
405     method run {
406         $mpd->on(
407             close => sub {
408                 die "Connection to MPD lost";
409             }
410         );
411
412         $self->prepare_to_wait_idle;
413     }
414 }
415
416 my $feeder = Feeder->new();
417
418 sub usage {
419     die "Usage: mpd-feeder [option...] [command]\n";
420 }
421
422 if (@ARGV) {
423     usage if @ARGV > 1;
424
425     my $cmd = shift @ARGV;
426
427     if ($cmd eq 'dump-config') {
428         $feeder->opt->dump;
429         exit;
430     }
431 # FIXME: handle blacklist manipulation
432
433     if ( $cmd eq 'one-shot' ) {
434         $feeder->queue_songs(undef, sub { exit });
435         $feeder->mpd->loop->run;
436     }
437     elsif ( $cmd eq 'single' ) {
438         $feeder->queue_songs(1, sub { exit });
439         $feeder->mpd->loop->run;
440     }
441     else {
442         die "Unknown command '$cmd'";
443     }
444 }
445
446
447 $feeder->queue_songs( undef, sub { $feeder->run } );
448
449 $feeder->mpd->loop->run;