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