File: mpinsert

package info (click to toggle)
mpdtoys 0.24
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 104 kB
  • ctags: 22
  • sloc: perl: 842; sh: 58; makefile: 21
file content (123 lines) | stat: -rwxr-xr-x 2,304 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/usr/bin/perl
use strict;
use warnings;
use Audio::MPD q{0.19.0};
use MpdToys;
use Encode;

=head1 NAME

mpinsert - insert song after currently playing song

=head1 SYNOPSIS

mpinsert [-n] [song ...]

=head1 DESCRIPTION

B<mpinsert> inserts a song (or songs) into the playlist directly after
the currently playing song.

If no songs are specified on the command line, it will read a list from
stdin.

Songs may be specified the same as they would be to mpc add: As paths to
files in the music database, or urls to stream.

You can also enter the name of a playlist, or part of the name of an
album, artist, or song. Matching items will be added to the playlist.

(If the perl String::Approx module is available, it will be used to handle
typos, etc in the names you enter.)

=head1 OPTIONS

=over 4

=item -n

Print the playlist position number that the first song was inserted at.

=back

=item -p

Play the song after inserting it.

=back

=head1 AUTHOR

Copyright 2007-2009 Joey Hess <joey@kitenet.net>

Licensed under the GNU GPL version 2 or higher.

http://kitenet.net/~joey/code/mpdtoys

=cut

use Getopt::Long;
my $shownum=0;
my $playnow=0;
GetOptions(
	"n" => \$shownum,
	"p" => \$playnow,
) || usage();

sub usage {
	die "Usage: mpinsert [-n] [song ...]\n";
}

my @list=@ARGV;
if (! @list) {
	while (<>) {
		chomp;
		push @list, $_;
	}
}
@list=map { decode_utf8($_) } @list;

my $mpd=Audio::MPD->new(conntype => "reuse");
my $pl=$mpd->playlist;

@list=reverse @list if $mpd->current;

my @out;
my $firstsong;
foreach my $item (@list) {
	if (! length $item) {
		die "no item specified to insert\n";
	}

	my @matches=MpdToys::findmatchingsongs($item, $mpd);
	if (! @matches && MpdToys::canmatch_fuzzy()) {
		@matches=MpdToys::findmatchingsongs_fuzzy($item, $mpd);
	}

	foreach my $song (@matches) {
		$pl->add($song->file);
		my @items=$pl->as_items;
		if (! @items) {
			die "failed!";
		}
		my $pos=$#items;
	
		# move from end to just after current
		my $current=$mpd->current;
		if ($current) {
			$pos=$current->pos+1;
			$pl->move($#items, $pos);
		}
	
		$firstsong=$pos unless defined $firstsong;
		push @out, ($pos+1) if $shownum;
	}
}

if ($shownum) {
	@out=reverse @out if $mpd->current;
	print $out[0]."\n" if @out;
}
if ($playnow && defined $firstsong) {
	$mpd->play($firstsong);
}