# $Id: FileSonic 12179 2011-03-03 00:20:16Z sparky $
# Get::FileSonic - File getter plugin for rsget.pl
#
# 2010-2011 (c) Przemysław Iskra <sparky@pld-linux.org>
#		This program is free software,
# you may distribute it under GPL v2 or newer.

name: FileSonic
short: FSC
web: "http://www.filesonic.com/"
tos: "http://www.filesonic.com/terms-and-conditions"
uri: qr{filesonic\.com/file/\d+}
uri: qr{(?:www\d+\.)?sharingmatrix\.com/file/\d+}
cookie: fsc
status: OK 2011-03-02

unify:
	return "http://www.filesonic.com/file/$1"
		if m{/file/(\d+)};

start:
	GET( $-{_uri} );

	ERROR( "file not found: $1" )
		if m#<div class="section CL1">.*?<p>\s*(.*?)\s*</p>#s
		or m#<div id="downloadFileInfo" class="section CL2">\s*<h2><span>[^<]*?</span></h2>\s*<p>\s*(.*?)\s*</p>#s;

	! m#<title>Download (.*?) for free on Filesonic.com</title>#;
	my $fn = de_ml( $1 );
	! m#<span class="size">($STDSIZE)</span>#;
	INFO( name => $fn, asize => $1 );

	! m#href="(.*?)" id="free_download"#;
	$-{dl_start} = $1;
	CLICK( $-{dl_start}, headers => [ "X-Requested-With: XMLHttpRequest" ], post => "", keep_referer => 1 );

	MULTI() if m#<span>Download session in progress</span>#
		or m#<p>Free users may only download 1 file at a time\.</p>#;

	( $-{file_uri} ) = m{<p><a href="(.*?)"><span>Start download now!</span></a></p>};
	GOTO stage_download if $-{file_uri};

	GOTO stage_captcha unless /var countDownDelay = (\d+);/;
	my $wait = $1;

	RESTART( $wait, "download limit" ) if $wait > 300;

	! /<input type='hidden' id='tm' name='tm' value='(.*?)'/;
	my %post = ( tm => $1 );

    ! /<input type='hidden' id='tm_hash' name='tm_hash' value='(.*?)'/;
	$post{tm_hash} = $1;
	$-{wait_post} = \%post;

	WAIT( -$wait, "expecting download information" );

	GET( $-{dl_start}, post => $-{wait_post} );

stage_captcha:
	! m{Recaptcha\.create\("(.*?)"};
	$-{captcha_key} = $1;

	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 $_;

	GET( $-{dl_start}, post => {
			recaptcha_challenge_field => $-{captcha_challenge},
			recaptcha_response_field => $_
		} );

	! m{<p><a href="(.*?)"><span>Start download now!</span></a></p>};
	$-{file_uri} = $1;

stage_download:
	CLICK_DOWNLOAD( $-{file_uri} );

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