mina86 / tinyapps

A collection of tiny applications, mirror of repository at SourceForge.net

tinyapps / getlyrics.pl
100755 478 lines (378 sloc) 11.737 kb
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
#!/usr/bin/perl
##
## Get lyrics from Internet for specified song
## Copyright (c) 2005 by Berislav Kovacki (beca/AT/sezampro.yu)
## Copyright (c) 2005-2007 by Michal Nazarewicz (mina86/AT/mina86.com)
##
## This software is OSI Certified Open Source Software.
## OSI Certified is a certification mark of the Open Source Initiative.
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
##
## This is part of Tiny Applications Collection
## -> http://tinyapps.sourceforge.net/
##
 
#
# Documentation at the end of file.
#
 
use strict;
use warnings;
 
use Pod::Usage;
use LWP::UserAgent;
 
my $VERSION = '0.5';
my $GLOBAL_CACHE = '/usr/share/lyrics/';
my $LOCAL_CACHE = $ENV{'HOME'} . '/.lyrics/';
 
 
## editFile ($file, $editor, $delete)
sub editFile ($$$);
 
 
##
## Parse args
##
my ($edit, $editor) = ( 0, '' );
if ($ARGV[0] =~ /^--edit(?:=(.*))?$/) {
$edit = 1;
$editor = $1 ? $1 : '';
shift @ARGV;
}
 
if (!@ARGV) {
pod2usage( -exitval => 1, -verbose => 0, -output => \*STDERR );
} elsif ($ARGV[0] eq '--help' || $ARGV[0] eq '-h' || $ARGV[0] eq '-?') {
pod2usage( -exitval => 0, -verbose => 1 );
} elsif ($ARGV[0] eq '--man') {
pod2usage( -exitval => 0, -verbose => 2 );
}
 
 
my ($src, $arg, $foo, @foo) = ('args');
if ($ARGV[0] =~ /^--(.*)$/) {
$src = $1;
shift;
}
$arg = "@ARGV";
 
 
sub run($) {
my $ret = `$_[0]`;
if ($?) {
die $_[1] . ": failed\n";
}
$ret;
}
 
 
##
## Source: mpc
##
if ($src eq 'mpc') {
$foo[0] = run 'mpc --format %artist% | head -n 1';
$foo[1] = run 'mpc --format %title% | head -n 1';
 
 
##
## Source: audacious
##
} elsif ($src eq 'audacious' || $src eq 'aud' || $src eq 'audtool') {
$foo[0] = run 'audtool current-song-tuple-data performer' ;
$foo[1] = run 'audtool current-song-tuple-data track_name';
 
 
##
## Source: mpd
##
} elsif ($src eq 'mpd') {
my $port = undef;
if ($arg =~ m/(.*)(?::(\d+))/) {
$arg = $1;
$port = $2;
}
 
eval { require Audio::MPD; } or
die "You are missing Audio::MPD module.\n";
 
$arg = new Audio::MPD($arg, $port);
if ($arg) {
eval { # New API
my $song = $arg->song();
@foo = ( $song->artist(), $song->title() );
1;
} or eval { # Old API
$foo = $arg->get_title();
$foo =~ s#^.*/##;
$arg->close_connection();
}
} else {
die "Could not connect to MPD.\n";
}
 
 
##
## Source: pipe
##
} elsif ($src eq 'pipe') {
$foo = run $arg;
 
 
##
## Source: file or read
##
} elsif ($src eq 'file' || $src eq 'read') {
$foo = join '', <>;
 
 
##
## Source: xmms
##
} elsif ($src eq 'xmms') {
 
$foo = eval {
require XMMS::InfoPipe;
my $xmms = XMMS::InfoPipe->new();
return unless $xmms->is_running;
return $xmms->{'info'}->{'Title'} if defined $xmms->{'info'}->{'Title'};
return $xmms->{'info'}->{'File'} if defined $xmms->{'info'}->{'File'} ;
return; # unusual event
 
} || eval {
my ($in, $out, $ret);
return unless sysopen($out, $ENV{'HOME'} . '/.xmms/inpipe' , 1);
return unless sysopen($in , $ENV{'HOME'} . '/.xmms/outpipe', 0);
syswrite $out, "\nout flush\nreport title\n";
return unless sysread $in, $ret, 4096;
return $ret;
};
 
if ($foo) {
$foo =~ s#.*[/\\]##;
} else {
die "Could not obtain song from XMMS\n";
}
 
 
##
## Source: args
##
} elsif ($src eq 'args' || $src eq '') {
if (!@ARGV) {
die "Artist and song name required\n";
} elsif (@ARGV == 2) {
@foo = @ARGV;
} elsif (@ARGV == 3 && $ARGV[1] =~ /\s*-\s*/) {
@foo = ($ARGV[0], $ARGV[1]);
} else {
$foo = "@ARGV";
}
 
 
##
## Unknown source
##
} else {
die "Invalid argument: --$src\n";
exit 1;
}
 
 
##
## Parse $foo and @foo
##
if (defined($foo)) {
$_ = $foo;
s/^[\s-]+|[\s-]*$//g;
s/\s+/ /g;
if (m/^(.+?) - (.+)$/ || m/^(\S+) (.+)$/ || m/^(.+?)-([^ ].*)$/) {
@foo = ($1, $2);
} else {
die "Cannot parse: $foo\n";
}
} else {
$foo[0] =~ s/^\s+|\s+$//mg;
$foo[1] =~ s/^\s+|\s+$//mg;
}
 
 
##
## Try cache
##
for ($LOCAL_CACHE . '/' . lc($foo[0]) . '/' . lc($foo[1]),
     $GLOBAL_CACHE . '/' . lc($foo[0]) . '/' . lc($foo[1])) {
if (-e) {
if ($edit) {
editFile $_, $editor, 0;
exit 0;
} elsif (open FH, '<', $_) {
print while <FH>;
close FH;
exit 0;
} else {
warn "$_: $!\n";
}
}
}
 
 
 
##
## Download page
##
print STDERR "Getting lyrics for ${foo[0]} - ${foo[1]}\n";
my $res = LWP::UserAgent->new()->post(
'http://www.lyrc.com.ar/en/tema1en.php', [
artist => $foo[0],
songname => $foo[1]
]);
die "unable to connect to www.lyrc.com.ar\n" unless ($res->is_success);
$res = $res->content;
die("No lyrics for ${foo[0]} - ${foo[1]} found\n") if ($res =~ /<form/i);
 
 
##
## HTML to text
##
$res =~ s/<head>.*<\/head>/ /igs; # Remove HTML Heading
$res =~ s/<scrip.*?script>/ /igs; # Remove Script blocks
$res =~ s/<a.*?\/a>/ /igs; # Remove Links
$res =~ s/&nbsp;/ /g; # Replace &nbsp with spaces
$res =~ s/\s+/ /g; # Squeeze blanks
$res =~ s/<p[^>]*>/\n\n/gi; # Replace paragraph tags with empty line
# Replace some formating html tags witConverth new line marks
$res =~ s/<(?:br|h[1-6]|li|d[td]||tr)[^>]*>/\n/gi;
$res =~ s/(<[^>]*>)+//g; # Remove HTML tags
$res =~ s/\n\s*\n\s*/\n\n/g; # Squeeze blank lines
$res =~ s/^ +| +$//mg; # Trim lines
$res =~ s/^\s+|\s$//g; # Trime whole code
# Add 2 empty lines after song name and artist
$res =~ s/^([^\n]+)\n+([^\n]+)\n+/$1\n$2\n\n\n/g;
$res .= "\n";
 
unless ($edit) {
print $res;
}
 
 
##
## Save in cache
##
my ($dir, $file);
for ($GLOBAL_CACHE, $LOCAL_CACHE) {
$dir = $_ . '/' . lc $foo[0];
$file = $dir . '/' . lc $foo[1];
 
if (-d $dir) {
next if ! -w _;
} else {
next if ! -d || ! -w _;
if (!mkdir $dir) {
warn "$dir: $!\n";
next;
}
}
 
if (open FH, '>', $file) {
print FH $res;
close FH;
if ($edit) {
editFile $file, $editor, 0;
}
exit 0;
}
 
# warn "$file: $!\n";
}
 
 
##
## Save in /tmp and edit
##
if ($edit) {
$file = $foo[0] . ' - ' . $foo[1];
for ($ENV{'TEMP'}, $ENV{'TMP'}, '/tmp') {
next unless -d && -w _;
unless (open FH, '>', "$_/$file") {
warn "$_/$file: $!\n";
next;
}
print FH $res;
close FH;
editFile "$_/$file", $editor, 1;
}
}
 
 
 
sub editFile ($$$) {
my ($file, $editor, $delete) = @_;
 
for my $e ($editor, $ENV{'VISUAL'}, $ENV{'EDITOR'}, 'vi') {
if (defined $e && $e) {
$editor = $e;
last;
}
}
 
$ENV{'GETLYRICS_LYRICS_FILE'} = $file;
unless ($delete) {
exec "$editor \"\$GETLYRICS_LYRICS_FILE\"";
die "exec: $!\n";
}
 
system "$editor \"\$GETLYRICS_LYRICS_FILE\"";
unlink $file;
exit $?;
}
 
 
__END__
 
=head1 NAME
 
getlyrics - Get lyrics from Internet for specified song
 
=head1 DESCRIPTION
 
The getlyrics utility retrieves lyrics from the Internet for the specified
artist and song name. Internally, this utility uses http://www.lyrc.com.ar/
to search for lyrics.
 
=head1 SYNOPSIS
 
getlyrics.pl --help | --man
 
getlyrics.pl [ --edit[=<editor>] ] --I<scheme> I<arguments>
 
=head1 OPTIONS
 
Script need to know artist and song name of the track you want lyrics
for. There are several schemes which instructs getlyrics.pl how should
it obtain this information. Some schemes requires arguments and if
they do you shall specify them as command line arguments just after the
B<-->I<scheme> part.
 
If no scheme is given (ie. the first command line argument (or the
second if first was B<--edit>) does not start with B<-->) or empty
scheme (ie. the first command line argument is B<-->) B<--args> is
assumed.
 
If B<--edit> option was given instead of printing lyrics script will
run an editor. If lyrics were not in cache and script didn't manage
to save them there it will save it in temporary location ($TEMP, $TMP
or "/tmp") and delete it after editor exists. As an editor script
will try argument given to B<--edit> option, $VISUAL environment
variable, $EDITOR environment variable or "vi" whatever is set.
 
=over 8
 
=item B<--args>
 
Will get artist and song name from given arguments. If two arguments
are given the first will be used as artist and the second as song
name. If three arguments are given and the second is a single minus
sign with optional white spaces the first argument will be used as
artist and the third as song name. Otherwise all arguments will be
concated and parsed as described in PARSING STRING section of man page (see
B<--man>).
 
=item B<--pipe>
 
Script will run command given as arguments and parse it's output
according to the rules described in PARSING STRING section of man page
(see B<--man>).
 
=item B<--file>
 
=item B<--read>
 
Reads content of files given as arguments or from standard input if no
files where given.
 
=item B<--mpd>
 
Instructs the script to get the song artist and title from MPD.
Argument to this scheme is of the fallowing format:
[password@][host][:port]. If host or port is not specified environment
variables B<MPD_HOST> and B<MPD_PORT> are checked. Finally if all
else fails the defaults B<localhost> and B<6600> are used.
 
If tags for artist and song name are missing script will try to parse
current song's file name according to the rules described in PARSING
STRING section of man page (see B<--man>).
 
=item B<--mpc>
 
Runs B<mpc --format %artist%> to obtain artist name and then B<mpc
--format %title%> to obtain title.
 
=item B<--audacious>
 
=item B<--audtool>
 
=item B<--aud>
 
Runs B<audtool current-song-tuple-data performer> to obtain artist
name and then B<audtool current-song-tuple-data track_name> to obtain
title.
 
=item B<--xmms>
 
Instructs the script to get the song artist from XMMS. Script first
tries to use XMMS::InfoPipe module. If it doesn't exist or
xmms-infopipe is not running, script tries to open
B<$HOME/.xmms/inpipe> and B<$HOME/.xmms/outpipe> pipes to use xmmspipe
plugin.
 
=back
 
=head1 PARSING STRING
 
Output of a pipe and some other strings need to be parsed to obtain
artist and song name. First, white space and minus signs are removed
from the beginning and the end of the string. Then, all white spaces
are changed into a single space character. Finally, the string is
splited into two strings first using ' - ' and if that fails a single
space character and if that fails a single minus sign.
 
For example, "Metallica - One", "Metallica One" and "Metallica-One"
are splited into "Metallica" being artist and "One" being song
name. However, "Metallica -One" will be splited into "Metallica" and
"-One". Also "Black Sabbath Changes" and "Black Sabbath-Changes" won't
be splited into "Black Sabbath" and "Changes" so you have to use
"Black Sabbath - Changes".
 
=head1 CACHE
 
Starting from version 0.5 this script supports caching. That is,
lyrics once downloaded don't get downloaded again. There are two
places where cached lyrics are kept: a global cache under
B</usr/share/lyrics/> and a local, per-user cache under B<~/.lyrics>.
When reading lyrics or saving them script first tries global and then
local cache. To enable caching at least one of those directories have
to be created. Note also, that the global cache is meant to be filled
by root and that lyrics kept there are available for all users to read
but only for root (or some other privileged user) to write.
 
 
=head1 AUTHOR
 
Berislav Kovacki <beca@sezampro.yu>,
Michal Nazarewicz <mina86@mina86.com>
 
=cut