App-Pimpd

 view release on metacpan or  search on metacpan

lib/App/Pimpd/Validate.pm  view on Meta::CPAN

package App::Pimpd::Validate;
use strict;
no warnings 'experimental::smartmatch';

BEGIN {
  use Exporter;
  use vars qw(@ISA @EXPORT);
  @ISA = qw(Exporter);
  @EXPORT = qw(
    invalid_regex
    to_terminal
    empty_playlist
    invalid_playlist_pos
    remote_host
    escape
    get_valid_lists
    isa_valid_playlist
  );
}

use Carp 'croak';
use App::Pimpd;
use Term::ExtendedColor qw(fg);


sub get_valid_lists {
  my @lists       = @_;
  my @valid_lists = sort($mpd->collection->all_playlists);


  for my $list(@lists) {
    if($list ~~ @valid_lists) {
      next;
    }
    else {
      my @choices = ();

      for my $valid(@valid_lists) {
        if(not invalid_regex($list)) {
          if($valid =~ /$list/im) {
            push(@choices, $valid);
          }
        }
        else {
          if($valid =~ /\Q$list/im) {
            push(@choices, $valid);
          }
        }
      }
      if(scalar(@choices) == 0) {
        print STDERR "No such playlist '" . fg($c[5], $list), "'\n";
        return;
      }


      print "'all' uses all playlists\n\n";

      my $i = 0;
      for my $choice(@choices) {
        print fg('bold', sprintf("%3d", $i)), " $choice\n";
        $i++;
      }
      print "choice: ";
      chomp(my $answer = <STDIN>);

      if( ($answer eq 'all') or ($answer eq '') ) {
        return @choices;
      }
      elsif($answer eq 'current') {
        return(undef);
      }

      if($answer ~~ @valid_lists) {
        $list = $answer;
      }
      # Make sure the number selected is in fact valid
      elsif($answer >= 0 and $answer < scalar(@valid_lists)) {
        $list = $choices[$answer];
      }
      else {
        croak("Playlist '$answer' is not valid\n");
      }
    }
  }
  return(@lists);
}

sub isa_valid_playlist {
  my @playlists = @_;
  my @lists = $mpd->collection->all_playlists;
  map { s/^\s+//m } @lists;
  return ($_[0] ~~ @lists) ? 1 : 0;
}

sub escape {
  my $str = shift;
  $str =~ s/([;<>*|`&\$!#()[\]{}:'" ])/\\$1/g;

  return $str;
}

sub remote_host {
  not exists($config{mpd_host}) and $config{mpd_host} = 'localhost';
  if(($config{mpd_host} eq 'localhost') or ($config{mpd_host} eq '127.0.0.1')) {
    return 0;
  }
  return 1;
}

sub invalid_regex {
  my $re = shift;
  eval { qr/$re/m };
  if($@) {
    return 1;
  }
  else {
    return 0;
  }
}



( run in 2.635 seconds using v1.01-cache-2.11-cpan-437f7b0c052 )