# $Id: FileServe 12189 2011-03-04 17:30:09Z sparky $
# Get::FileServe - File getter plugin for rsget.pl
#
# 2010 (c) Paweł Zuzelski <pawelz@pld-linux.org>
# 2011 (c) Przemysław Iskra <sparky@pld-linux.org>
#		This program is free software,
# you may distribute it under GPL v2 or newer.

name: FileServe
short: FSRV
web: "http://fileserve.com/"
tos: "http://fileserve.com/terms.php"
uri: qr{fileserve\.com/file/[A-Za-z0-9]+(/.*)?}
cookie: fsrv
status: OK 2011-03-03

unify:
	s/#.*//;
	return "http://fileserve.com/file/$1"
		if m{fileserve\.com/file/([A-Za-z0-9]+)};

start:
	GET( $-{_uri} );

	ERROR( "file not found: $1" ) if m#<span class="fail_info">\s*(.*?)\s*</span>#s
		or m{<img src="/images/stop_error\.gif".*?<h1>.*?</h1></li><li>(.*?)</li>}s;

	! m#<h1>(.+?)<br/></h1>#;
	my $fname = $1;
	! m#<span.*?><strong>($STDSIZE)</strong> \| Uploaded on #o;
	INFO( name => $fname, asize => $1 );

	! ( $-{captcha_key} ) = m{var reCAPTCHA_publickey='(.*?)';};
	! ( $-{captcha_encode} ) = m{"recaptcha_shortencode_field".*? value="(.*?)" />};

	! m{src="(/landing/.+?/download_captcha\.js)"};
	$-{captcha_uri} = $1;

	CLICK( "", post => { checkDownload => "check" }, keep_referer => 1 );

	MULTI() if /{"fail":"parallelDownload"}/;
	RESTART( 900, "free limit reached" ) if /{"fail":"timeLimit"}/;

	ERROR( "some error: $_" ) if /{"fail"/;
	! /{"success":"showCaptcha"}/;

	GET( $-{captcha_uri}, keep_referer => 1,
		headers => [ "X-Requested-With: XMLHttpRequest" ] );

stage_getcaptcha:
	GET( "http://www.google.com/recaptcha/api/challenge?k=$-{captcha_key}&ajax=1&cachestop=" . rand,
		keep_referer => 1 );

	! ( $-{captcha_challenge} ) = m{challenge\s*:\s*'(.*?)'};

	GET( "http://www.google.com/recaptcha/api/image?c=" . $-{captcha_challenge},
		keep_referer => 1 );

	CAPTCHA(
		qr/\S+ \S+/
	);

	RESTART( 1, "Captcha not solved" ) unless $_;

	CLICK( "/checkReCaptcha.php", post => {
			recaptcha_shortencode_field => $-{captcha_encode},
			recaptcha_response_field => $_,
			recaptcha_challenge_field => $-{captcha_challenge},
		}, keep_referer => 1 );

	if ( /{"success":1}/ ) {
		CAPTCHA_RESULT( "OK" );
	} else {
		CAPTCHA_RESULT( "FAIL" );
		GOTO stage_getcaptcha;
	}

	GET( "", post => { downloadLink => "wait" }, keep_referer => 1 );

	! /^\xef\xbb\xbf(\d+)$/s;
	WAIT( -$1, "expecting download link" );

	CLICK( "", post => { downloadLink => "show" }, keep_referer => 1, );

	CLICK_DOWNLOAD( "", post => { download => "normal" } );

	RESTART( 1, "free limit reached" )
		if m#You need to wait (\d+) seconds to start another download\.#;

	RESTART( 1, "download link expired" )
		if /<li class="title">Your download link has expired/;

	RESTART( 60, "captcha error, this shouldn't happen" )
		if /<li class="title">Captcha error/;

	RESTART( 1, "multi download not allowed" )
		if m{URL=http://www\.fileserve\.com/landing-1403\.php};

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