]> git.draconx.ca Git - mpdhacks.git/blobdiff - mpdexec.pl
mpdreload: Simplify script operation.
[mpdhacks.git] / mpdexec.pl
index 0d477dae465d0923b297fea31d2af3919508d54a..4d25ead18d81c979860f4044aa7e1da4f429a01a 100755 (executable)
@@ -1,6 +1,6 @@
 #!/usr/bin/env perl
 #
-# Copyright © 2012,2019 Nick Bowler
+# Copyright © 2012,2019-2020 Nick Bowler
 #
 # Send commands to MPD.  Each command-line argument is quoted as necessary
 # so it appears as a single argument at the protocol level.  The result is
@@ -20,12 +20,13 @@ decode_argv(Encode::FB_CROAK);
 
 binmode(STDOUT, ":utf8");
 binmode(STDIN, ":utf8");
-use IO::Socket::INET6;
 
 use Getopt::Long qw(:config gnu_getopt);
 
-my $host = $ENV{MPD_HOST} // "localhost";
-my $port = $ENV{MPD_PORT} // 6600;
+use FindBin;
+use lib "$FindBin::Bin";
+use MPDHacks;
+
 my ($quiet, $binary, $ignore_errors, $download);
 
 sub print_version {
@@ -39,10 +40,10 @@ EOF
 }
 
 sub print_usage {
-       my $fh = $_[1] // *STDERR;
+       my ($fh) = (@_, *STDERR);
 
        print $fh "Usage: $0 [options] [command ...]\n";
-       print "Try $0 --help for more information.\n" unless (@_ > 0);
+       print $fh "Try $0 --help for more information.\n" unless (@_ > 0);
 }
 
 sub print_help {
@@ -73,8 +74,8 @@ EOF
 }
 
 GetOptions(
-       'host|h=s'         => \$host,
-       'port|p=s'         => \$port,
+       'host|h=s'         => \$MPD::host,
+       'port|p=s'         => \$MPD::port,
 
        'quiet|q'          => \$quiet,
        'no-quiet'         => sub { $quiet = 0; },
@@ -100,32 +101,7 @@ if ($binary) {
 }
 $quiet = 1 if (defined($binary) && $binary eq "");
 
-my $sock = new IO::Socket::INET6(
-       PeerAddr => $host,
-       PeerPort => $port,
-       Proto    => 'tcp',
-) or die "failed to connect to MPD: $!";
-#binmode($sock, ":utf8");
-binmode($sock);
-
-if (!(<$sock> =~ /^OK MPD ([0-9]+)\.([0-9]+)\.([0-9]+)$/)) {
-       die "MPD failed to announce version: $!";
-}
-
-sub mpd_escape {
-       ($_) = @_;
-
-       # No way to encode literal newlines in the protocol, so we convert
-       # any newlines in the arguments into a space, which can help with
-       # shell quoting.
-       s/\n/ /g;
-
-       if (/[ \t\\"]/) {
-               s/[\\"]/\\$&/g;
-               return "\"$_\"";
-       }
-       return $_;
-}
+my $sock = MPD::connect(binmode => ":raw");
 
 sub read_binary {
        my ($count) = @_;
@@ -185,7 +161,7 @@ sub mpd_exec {
 }
 
 if (@ARGV) {
-       mpd_exec(map { mpd_escape($_) } @ARGV)
+       mpd_exec(map { MPD::escape($_) } @ARGV)
 } else {
        while (<>) {
                chomp;