#!/usr/bin/perl

# 日本語EUC-JP、LF

use strict;

use Jcode;
use File::Basename;

die "Please specify filenames" if ( $#ARGV < 0 );

while ( my $file = shift @ARGV ) {
	my $lyr = GetInferedLyrics( $file )
		or
			do {
				warn "Lyrics not found for " . basename( $file );
				next;
			}
		;
	$lyr = jcode( $lyr, 'euc' )->sjis;
	$lyr =~ s/\x0D\x0A|\x0D|\x0A/\x0D\x0A/g;

	my $txtFile = $file;
	$txtFile =~ s/\.mp3$/.txt/i;
	open( W, ">" . $txtFile )
		or next;
	binmode W;
	print W $lyr;
	close( W );
}

warn "All done";
my $i = <>;
exit;

use Jcode;
use LWP::UserAgent;
use MP3::Tag;
# http://search.cpan.org/~ilyaz/MP3-Tag-0.9709/Tag.pm

sub GetInferedLyrics {
	my $file = shift @_;
	my( $title, $art ) = GetFuzzyID3Tags( $file )
		or return; # エラー

	my @list = GetCandidates(
		$art,
		$title
	) or return; # エラー
	return if ( $#list != 0 ); # エラー
	return ExtractLyrics( $list[0]->{url} );
}

sub GetFuzzyID3Tags {
	my $file = shift @_;

	my( $title, $art ) = GetID3Tags( $file )
		or return; # エラー
	$title =~ s/\(.*?\)//g;
	$art =~ s/\(.*?\)//g;

	return( $title, $art );
}

sub GetID3Tags {
	my $file = shift @_;

	my $mp3 = MP3::Tag->new( $file )
		or return; # エラー
	my( $title, $track, $art ) = $mp3->autoinfo()
		or return; # エラー
	$mp3->close;
	# ID3タグがないときは勝手にファイル名が参照される
	$title =~ s/\t/ /g;
	$art =~ s/\t/ /g;

	my $from =
		'０１２３４５６７８９'
		. 'ＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＺＷＸＹＺ'
		. 'ａｂｃｄｅｆｇｈｉｊｋｌｍｎｏｐｑｒｓｔｕｚｗｘｙｚ'
		. '（）“”［］'
		. '＝：；！？＃'
		. '　' #全角スペース
		;
	my $to =
		'0123456789'
		. 'ABCDEFGHIJKLMNOPQRSTUZWXYZ'
		. 'abcdefghijklmnopqrstuzwxyz'
		. '()""[]'
		. '=:;!?#'
		. ' ' #半角スペース
		;

	my $str = jcode( "$title\t$art" )
		->h2z
		->tr( $from, $to )
		->euc;

	$str =~ s/－/-/g;

	return( split( /\t/, $str ) );
}

sub ExtractLyrics {
	my $url = shift @_;

	my $eucContent = GetEucContent( $url )
		or return; # エラー

	$eucContent =~ s|^.*<p class="fs16">(.*?)</p>
<\!--c24_1-->
<hr>
<\!--/c24_1-->
<p class="fs12">本ページでの歌詞本文の印刷、コピー＆ペーストは著作権保護の観点から禁止しています。</p>
.*$|$1|s;

	$eucContent =~ s/<[^>]+>//gs;
	$eucContent = DeAmp( $eucContent );

	return $eucContent . "\n";
}

sub DeAmp {
	my $str = shift @_;
	$str =~ s/\&[^;]+;//g;
	return $str;
}

sub GetEucContent {
	my $url = shift @_;

	my $ua = LWP::UserAgent->new(
		agent =>		'Mozilla/4.0 (compatible; MSIE 6.0)',
		timeout =>		15,
		max_size =>		128 * 1024,
	);
	my $response = $ua->get( $url )
		or return; # エラー
	return # エラー
		if ( !$response->is_success );
	my $eucContent;
	eval {
		$eucContent = jcode( $response->content )->h2z->euc;
	};
	return # エラー
		if ( $@ );
	$eucContent =~ s/\x0D\x0A|\x0D|\x0A/\n/g;

	return $eucContent;
}

sub GetCandidates {
	my $art = shift @_;
	my $title = shift @_;

	my $baseurl = 'http://music.goo.ne.jp';
	my $url = $baseurl . '/lyric/db.php?a=%ART%&k=%TITLE%';

	$art = jcode( $art )->euc;
	$art =~ s/(\W)/'%' . unpack('H2', $1)/eg;
	$title = jcode( $title )->euc;
	$title =~ s/(\W)/'%' . unpack('H2', $1)/eg;

	$url =~ s/\%ART\%/$art/;
	$url =~ s/\%TITLE\%/$title/;

	my $eucContent = GetEucContent( $url )
		or return; # エラー
	my $found = ( $eucContent =~ s|^.*<\!--c06_1-->
<div class="lst1">
<ul>
(.*?)
</ul><div class="clearboth"></div>
</div>
<\!--/c06_1-->
.*$|$1|s );

	return
		unless ( $found ); # エラー

	my @candidates;
	foreach my $i ( split( /<li>/, $eucContent ) ) {
		next if ( $i eq '' );
		my $this;
		(
			$this->{url},
			$this->{title},
			$this->{head},
		) =
			( $i =~ m|
				^.*href="(/lyric/[^a].*?)">
				(.*?)
				</a>.*<br>.
				(.*?)
				</li>$
			|sx );
		$this->{url} = $baseurl . $this->{url};
		$this->{title} = DeAmp( $this->{title} );
		$this->{head} = DeAmp( $this->{head} );
		push( @candidates, $this );
	}

	return @candidates;
}

1;
