7 use Log::Any::Adapter Stderr => log_level => 'trace';
9 use Syntax::Keyword::Try;
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;
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);
44 'min-sing-interval=s' => sub {
45 $min_song_interval = parse_duration(pop);
47 'min-artist-interval=s' => sub {
48 $min_artist_interval = parse_duration(pop);
53 sub handle_config_option( $ini, $section, $option, $target_ref,
56 return undef unless exists $ini->{$section}{$option};
58 my $value = $ini->{$section}{$option};
60 $value = $converter->($value) if $converter;
62 $$target_ref = $value;
67 say "log_level = $log_level";
70 say "host = " . ( $mpd_host // '' );
71 say "port = " . ( $mpd_port // '' );
72 say "target-queue-length = $target_queue_length";
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);
81 say "path = " . ( $db_path // '' );
82 say "user = " . ( $db_user // '' );
83 say "password = " . ( $db_password // '' );
86 method parse_config_file($path) {
87 use Config::INI::Reader;
88 my $ini = Config::INI::Reader->read_file($path);
90 handle_config_option( $ini => mpd => host => \$mpd_host );
91 handle_config_option( $ini => mpd => port => \$mpd_port );
93 handle_config_option( $ini => 'mpd-feeder' => log_level => \$log_level );
96 $ini => queue => 'target-length' => \$target_queue_length );
98 $ini => queue => 'min-song-interval' => \$min_song_interval,
101 handle_config_option(
102 $ini => queue => 'min-album-interval' => \$min_album_interval,
105 handle_config_option(
106 $ini => queue => 'min-artist-interval' => \$min_artist_interval,
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 );
114 # FIXME: complain about unknown sections/parameters
124 use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';
128 use Log::Any qw($log);
136 Getopt::Long::Configure('pass_through');
137 Getopt::Long::GetOptions('cfg|config=s' => \$cfg_file);
138 Getopt::Long::Configure('no_pass_through');
140 $cfg_file //= DEFAULT_CONFIG_FILE if -e DEFAULT_CONFIG_FILE;
142 $opt->parse_config_file($cfg_file) if $cfg_file;
145 $opt->parse_command_line;
147 Log::Any::Adapter->set( Stderr => log_level => $opt->log_level );
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;
154 $mpd = Net::Async::MPD->new(%conn);
157 $self->update_db unless $self->opt->skip_db_update;
165 DBI->connect( "dbi:Pg:dbname=" . $opt->db_path,
166 $opt->db_user, $opt->db_password,
167 { RaiseError => 1, AutoCommit => 1 } );
169 $log->info("Connected to ".$opt->db_path);
170 $db_generation = $self->db_get_option('generation');
171 $log->debug("DB generation is $db_generation");
174 method db_get_option($name) {
175 my $sth = $db->prepare_cached("select $name from options");
177 my @result = $sth->fetchrow_array;
182 method db_set_option( $name, $value ) {
183 my $sth = $db->prepare_cached("update options set $name = ?");
184 $sth->execute($value);
187 method db_store_song($song, $artist, $album) {
188 return unless length($song) and length($artist) and length($album);
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
199 $db->prepare_cached(<<'SQL')->execute( $artist, $album, $db_generation );
200 INSERT INTO albums(artist, album, generation)
202 ON CONFLICT ON CONSTRAINT albums_pkey DO
203 UPDATE SET generation = $3
205 $db->prepare_cached(<<'SQL')->execute( $artist, $db_generation );
206 INSERT INTO artists(artist, generation)
208 ON CONFLICT ON CONSTRAINT artists_pkey DO
209 UPDATE SET generation = $2
213 method db_remove_stale_entries {
215 $db->prepare_cached('DELETE FROM songs WHERE generation <> ?');
216 $sth->execute($db_generation);
217 $log->debug( sprintf( "Deleted %d stale songs", $sth->rows ) );
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 ) );
224 $db->prepare_cached('DELETE FROM artists WHERE generation <> ?');
225 $sth->execute($db_generation);
226 $log->debug( sprintf( "Deleted %d stale artists", $sth->rows ) );
229 method db_note_song_qeued($item) {
231 'UPDATE songs SET last_queued=current_timestamp WHERE path=?')
232 ->execute( $item->{song} );
234 'UPDATE artists SET last_queued=CURRENT_TIMESTAMP WHERE artist=?')
235 ->execute( $item->{artist} );
237 'UPDATE albums SET last_queued=CURRENT_TIMESTAMP WHERE artist=? AND album=?'
238 )->execute( $item->{artist}, $item->{album} );
242 $log->info('Updating song database');
243 $mpd->send('listallinfo')->on_done(
253 foreach my $entry (@$rows) {
254 next unless exists $entry->{file};
255 $self->db_store_song( $entry->{file},
256 $entry->{Artist}, $entry->{Album} );
260 $log->info("Updated data about $song_count songs");
262 $self->db_remove_stale_entries;
264 $self->db_set_option( generation => $db_generation );
281 method db_find_suitable_songs($num) {
283 my $sth = $db->prepare_cached(<<SQL);
284 SELECT s.path, s.artist, s.album
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)
297 $self->opt->min_song_interval,
298 $self->opt->min_artist_interval,
299 $self->opt->min_album_interval,
302 while ( my @row = $sth->fetchrow_array ) {
304 { song => $row[0], artist => $row[1], album => $row[2] };
310 method queue_songs($num = undef, $callback = undef) {
312 $mpd->send('playlist')->on_done(
314 my $present = scalar @{ $_[0] };
316 $log->notice("Playlist contains $present songs");
317 if ( $present < $opt->target_queue_length ) {
319 $opt->target_queue_length - $present, $callback );
322 $callback->() if $callback;
330 my @list = $self->db_find_suitable_songs($num);
332 die "Found no suitable songs" unless @list;
334 if ( @list < $num ) {
337 'Found only %d suitable songs instead of %d',
343 $log->info("About to add $num songs to the playlist");
346 for my $song (@list) {
347 my $path = $song->{song};
352 $log->debug( "Adding " . join( ', ', map {"«$_»"} @paths ) );
355 push @commands, [ add => "\"$_\"" ];
357 my $f = $mpd->send( \@commands );
359 $f->on_fail( sub { die @_ } );
363 $self->db_note_song_qeued($_) for @list;
364 $callback->(@_) if $callback;
371 method prepare_to_wait_idle {
372 $log->trace('declaring idle mode');
373 $mpd->send('idle database playlist')->on_done(
377 use JSON; warn to_json($result);
379 if ( $result->{changed} eq 'database' ) {
381 $self->prepare_to_wait_idle;
383 elsif ( $result->{changed} eq 'playlist' ) {
384 $self->queue_songs( undef,
385 sub { $self->prepare_to_wait_idle } );
390 "Unknown result from idle: " . to_json($result) );
391 $self->prepare_to_wait_idle;
400 die "Connection to MPD lost";
404 $self->prepare_to_wait_idle;
408 my $feeder = Feeder->new();
410 $feeder->opt->dump, exit if $feeder->opt->dump_config;
412 $feeder->queue_songs(1), exit if $feeder->opt->single;
414 # FIXME: handle blacklist manipulation
416 $feeder->queue_songs;
418 exit if $feeder->opt->one_shot;
428 $feeder->queue_songs;
432 $feeder->mpd->idle(qw(database playlist));