# $Id: EasyShare 11521 2010-06-04 16:06:34Z sparky $
# Get::EasyShare - File getter plugin for rsget.pl
#
# 2009-2010 (c) Przemysław Iskra <sparky@pld-linux.org>
#		This program is free software,
# you may distribute it under GPL v2 or newer.

name: EasyShare
short: ES
web: "http://easy-share.com/"
tos: "http://easy-share.com/tos.html"
uri: qr{(?:w\d+\.)?easy-share\.com/(../)?(\d+)}
cookie: !es
status: OK 2010-06-04

start:
	COOKIE( [ (qw(.easy-share.com TRUE / FALSE), time + 80000, 'language', 'en' ) ] );

	GET( $-{_uri} );

	ERROR( "file not found" ) if /File not found/;
	ERROR( "file removed" ) if /Requested file is deleted/;

	! m{<p class="pt15 pb0 px18 txtgray family2 c">You are requesting\s+(.*?) \(($STDSIZE)\)</p>};
	INFO( name => $1, asize => $2 );

	RESTART( - irand( 60, 300 ), "free limit reached" )
		if m#You have downloaded over.*?during last hour#;

	unless ( m#<script type="text/javascript">\s*u='(.*?)';\s*w='(\d+)';# ) {
		GOTO stage_captcha;
	}
	$-{uri} = $1;
	my $wait = $2;

	WAIT( $wait, "expecting captcha or download button" );
stage_cappage:

	GET( $-{uri}, keep_referer => 1 );
stage_captcha:

	RESTART( - irand( 60, 300 ), "free limit reached" )
		if m#You have downloaded over.*?during last hour#;

	if ( m#<script type="text/javascript">\s*u='(.*?)';\s*w='(\d+)';# ) {
		$-{uri} = $1;
		WAIT_NEXT( stage_cappage, $2, "still expecting captcha" );
	}

	! $-{capform} = $self->form( match => { class => qr/^captcha1$/ } );

	GOTO stage_download
		unless m#<p class="pb0"><img src="(.*?)" width="220" height="50" alt="" border="1"></p>#;
	my $img = $1;

	GET( $img, keep_referer => 1 );

	CAPTCHA(
	  	qr/[2-9abcdeghkmnpqsuvxyz]{5,6}/,
	  	process => \&es_decaptcha
	);

	GOTO stage_cappage unless defined $_;
	$-{capform}->set( captcha => $_ );

stage_download:
	DOWNLOAD( $-{capform}->post() );

	if ( /Invalid characters/ ) {
		CAPTCHA_RESULT( "FAIL" );
		RESTART( 1, "invalid captcha" );
	}
	RESTART( 1, "to slow ?" ) if m#<script type="text/javascript">\s*u='(.*?)';\s*w='(\d+)';#;

perl:

sub es_color_get_luma
{
	# for real luma should convert to linear first
	return ($_[0] * 0.30 + $_[1] * 0.59 + $_[2] * 0.11);
}

sub es_histogram_get_min_max
{
	my $h = shift;
	my $min_sum = shift;
	my $max_sum = shift;

	my ( $max, $min, $sum );
	$sum = 0;
	for ( my $i = 255; $i >= 0; $i-- ) {
		$sum += $h->[$i];
		if ( $sum > $max_sum ) {
			$max = $i;
			last;
		}
	}
	$sum = 0;
	for ( my $i = 0; $i < 256; $i++ ) {
		$sum += $h->[$i];
		if ( $sum > $min_sum ) {
			$min = $i;
			last;
		}
	}

	return ( $min, $max )
}

sub es_decaptcha
{
	my $img = shift;

	$img->color_filter( \&es_color_get_luma );
	my $h = $img->histogram();
	$img->luma_emphasize( es_histogram_get_min_max( $h, 50, 3000 ) );
	return $img->ocr();
	#char_fix => { " " => "", G => 6, Z => 2, S => 8, B => 8, X => 'x', Q => 9, },
}



# vim: filetype=perl:ts=4:sw=4
