# $Id: RapidShark 10867 2009-10-26 22:47:10Z sparky $
# Get::RapidShark - File getter plugin for rsget.pl
#
# 2009 (c) Przemysław Iskra <sparky@pld-linux.org>
#		This program is free software,
# you may distribute it under GPL v2 or newer.

name: RapidShark
short: RK
uri: qr{rapidshark\.pl/}
status: OK 2009-10-22

start:
	GET( $-{_uri} );

	ERROR( "file not found" )
		if m{<b>(Plik nie został odnaleziony|File Not Found|Datei nicht gefunden)</b>};
	ERROR( "file not found" )
		if m{<font class="err">No such file};

	m{<font style="font-size:12px;">Chcesz pobrac plik <font color="red">.*/(.*?)</font> \(($STDSIZE)\)</font>};
	INFO( name => $1, asize => $2 );

	! my $form = $self->form( match => { body => qr/"method_free"/ } );
	! $form->select( method_free => 0 );

	CLICK( $form->post() );

	if ( /(?:You have to wait|Proszę czekać) (.*) (?:till next download|aby ściągnąć kolejny plik)/ ) {
		$_ = $1;
		my $wait = 0;
		$wait += 60 * 60 * $1 if /(\d+) (hour|godzin)/;
		$wait += 60 * $1 if /(\d+) minut/;
		$wait += $1 if /(\d+) (second|sekund)/;
		RESTART( $wait, "free limit reached" );
	}

stage_captcha:
	! $-{form} = $self->form( name => "F1" );

	! m{<span id="countdown">(\d+)</span>};
	$-{wait} = $1;

	! m{<img src="(http://www\.rapidshark\.pl/captchas/.*?jpg)">};
	GET( $1, keep_referer => 1 );

	CAPTCHA(
		qr/[0-9]{4}/,
		process => \&rk_decaptcha
	);

	RESTART( 1, "captcha unsolved" ) unless $_;

	$-{form}->set( code => $_ );

	WAIT( $-{wait}, "starting download" );
	
	DOWNLOAD( $-{form}->post() );

	if ( /{lang_dod_7}/ ) {
		CAPTCHA_RESULT( "FAIL" );
		GOTO stage_captcha;
	}


perl:

sub rk_filter_spots # remove dark pixels
{
	my $pix = shift;

	my $lim = 100;
	return if $pix->isAbove( 10 );

	my $whites = 0;
	my @sides = ( $pix->up, $pix->down, $pix->left, $pix->right );
	foreach my $spix ( @sides ) {
		return unless $spix; # borders are taken care of
		$whites++ if $spix->isAbove( $lim );
	}
	return if $whites < 4;
	my @corners = ( $sides[0]->left, $sides[0]->right,
					$sides[1]->left, $sides[1]->right );
	foreach my $cpix ( @corners ) {
		$whites++ if $cpix->isAbove( $lim );
	}
	
	$pix->set( 0xff ) if $whites >= 7;
	return;
}

sub rk_decaptcha
{
	my $img = shift;
	$img->color_filter( sub { $_[0] } );
	$img = $img->crop( x1 => 21, y1 => 7, x2 => 57, y2 => 18 );
	$img->set_border( 255 );
	$img->luma_emphasize( 50, 80 );
	$img->pix_filter( \&rk_filter_spots );
	return $img->doublesize->ocr();
}

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