# $Id: TurboBit 11994 2010-12-18 21:44:41Z sparky $
# Get::TurboBit - 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.

# TODO: there are two captcha methods: their own (kohana) and recaptcha
# the latter is not supported, but it doesn't seem to be a big problem

name: TurboBit
short: TB
web: "http://turbobit.net/"
tos: "http://turbobit.net/rules"
uri: qr{turbobit\.net/[a-z0-9]+(/.+)?\.html}
uri: qr{turbobit\.ru/[a-z0-9]+(/.+)?\.html}
cookie: tb
slots: max
status: OK 2010-07-26

unify:
	return "http://turbobit.net/$1.html"
		if m{turbobit\.[a-z]{2,3}/([a-z0-9]+)};

start:
	GET( $-{_uri} );

	MULTI( "e404" ) if m#<head><title>404 Not Found</title></head>#;
	MULTI( "e502, will try again" ) if m#<head><title>502 Bad Gateway</title></head>#;
	ERROR( "file not found" ) if m#<div class="code-404">404</div>#;
	ERROR( "file not found" ) if m#Файл не найден. Возможно он был удален|File was not found. It could possibly be deleted#;
	ERROR( "file not found" ) if m#\Q'h1').html('File not found. Probably it was deleted\E#;

	! m#<h1 class="download-file">.*?<span.*?>(.*?)</span></h1>#;
	my $name = $1;
	if ( $name =~ /\.\.\./ ) {
		$name =~ s/\.\.\./\0/;
		m#<title>\s+Download (.*?)\. Free download#s and $name = $1;
	}
	! m#<b>File size:</b> ([\d,\.]+ .b)</div>#;
	( my $size = $1 ) =~ tr/,/./;
	INFO( name => $name, asize => $size );

	! m#<a class="free wide" href="(.*?)" #;
	CLICK( $1 );

stage_captcha:
	RESTART( irand( 10, 60 ), "received empty page, restarting" ) unless length $_;
	RESTART( 10, "recaptcha is not supported, restarting" ) if m#src="http://api\.recaptcha\.net/challenge.*"#;
	if ( m#<img alt="Captcha" src="(.*?)"# ) {
		$-{capimg} = $1;
	} else {
		! m#var Timeout = {\s*limit: (\d+),#s;
		RESTART( $1, "free limit reached" );
	}

	! $-{form} = $self->form( match => { body => qr#<img alt="Captcha"# } );

stage_getimg:
	GET( $-{capimg}, keep_referer => 1 );

	CAPTCHA(
		qr/[A-Z0-9]{4}/i,
	);

	GOTO stage_getimg unless defined $_;
	
	$-{form}->set( captcha_response => uc $_ );
	GET( $-{form}->post() );

	if ( /updateTime: function/ ) {
		CAPTCHA_RESULT( "OK" );
	} else {
		CAPTCHA_RESULT( "FAIL" );
		GOTO stage_captcha;
	}

	! m{\$\("#timeoutBox"\)\.load\("(/download/timeout/.*?)"};
	$-{dl_link} = $1;

	! m#var Timeout = {\s*limit: (\d+),#;
	WAIT( -$1, "starting download" );

	GET( $-{dl_link}, keep_referer => 1 );

	! m#<a href='(.*?)'>#;

	CLICK_DOWNLOAD( $1 );

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