App-MPDJ
view release on metacpan or search on metacpan
lib/App/MPDJ.pm view on Meta::CPAN
}
sub execute {
my ($self) = @_;
local @SIG{qw( INT TERM HUP )} = sub {
$self->log->notice('Exiting');
exit 0;
};
my @loggers;
push @loggers,
([ 'Screen', min_level => $self->config->get('conlog'), newline => 1 ])
if $self->config->get('conlog');
push @loggers,
([ 'Syslog', min_level => $self->config->get('syslog'), ident => 'mpdj' ])
if $self->config->get('syslog');
$self->{log} = Log::Dispatch->new(outputs => \@loggers);
if ($self->config->get('daemon')) {
$self->log->notice('Forking to background');
Proc::Daemon::Init;
}
$self->connect;
$self->configure;
$self->mpd->subscribe('mpdj');
$self->update_cache;
while (1) {
$self->log->debug('Waiting');
my @changes =
$self->mpd->idle(qw(database player playlist message options));
$self->mpd->update_status();
foreach my $subsystem (@changes) {
my $function = $subsystem . '_changed';
$self->$function();
}
}
}
sub configure {
my ($self) = @_;
$self->log->notice('Configuring MPD server');
$self->mpd->repeat(0);
$self->mpd->random(0);
if ($self->config->get('calls-freq')) {
my $now = time;
$self->{last_call} = $now - $now % $self->config->get('calls-freq');
$self->log->notice("Set last call to $self->{last_call}");
}
}
sub update_cache {
my ($self) = @_;
$self->log->notice('Updating music and calls cache...');
foreach my $category (('music', 'calls')) {
@{ $self->{$category} } = grep { $_->{type} eq 'file' }
$self->mpd->list_all($self->config->get("${category}-path"));
my $total = scalar(@{ $self->{$category} });
if ($total) {
$self->log->notice(sprintf 'Total %s available: %d', $category, $total);
} else {
$self->log->warning(
"No $category available. Path should be mpd path not file system.");
}
}
}
sub remove_old_songs {
my ($self) = @_;
my $song = $self->mpd->song || 0;
my $count = $song - $self->config->get('before');
if ($count > 0) {
$self->log->info("Deleting $count old songs");
$self->mpd->delete("0:$count");
}
}
sub add_new_songs {
my ($self) = @_;
my $song = $self->mpd->song || 0;
my $count =
$self->config->get('after') + $song - $self->mpd->playlist_length + 1;
if ($count > 0) {
$self->log->info("Adding $count new songs");
$self->add_song for 1 .. $count;
}
}
sub add_song {
my ($self) = @_;
$self->add_random_item_from_category('music');
}
sub add_call {
my ($self) = @_;
$self->log->info('Injecting call');
$self->add_random_item_from_category('calls', 'immediate');
my $now = time;
$self->{last_call} = $now - $now % $self->config->get('calls-freq');
$self->log->info('Set last call to ' . $self->{last_call});
}
( run in 2.845 seconds using v1.01-cache-2.11-cpan-524268b4103 )