# $Id: SharingMatrix 11643 2010-07-09 22:51:00Z sparky $
# Get::SharingMatrix - 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: SharingMatrix
short: SM
web: "http://sharingmatrix.com/"
tos: "http://sharingmatrix.com/user_agreement"
uri: qr{(?:www\d+\.)?sharingmatrix\.com/file/\d+}
cookie: sm
status: OK 2010-06-04

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

start:
	GET( $-{_uri} );

	ERROR( "file not found" )
		if m#<h1><span>The file has been deleted</span></h1>#;

	if ( $self->{_cmd} ne "check" ) {
		DELAY( 600, "free limit reached" )
			if /Your daily download limit is over/;
	}

	if ( /You are already downloading file/ ) {
		! m#link_name = '(.*?)';#;
		my $name = $1;
		! m#fsize = '(.*?)';#;
		my $size = $1;
		$size =~ s/&nbsp;//;
		INFO( name => $name, asize => $size );

		MULTI();
	}

	! m#link_id = '(\d+)';#;
	$-{link_id} = $1;

	! m#case 'free':.*?sUrl2 = '(.*?)' \+ link_id;#s;
	my $link = $1 . $-{link_id};

	CLICK( $link, keep_referer => 1 );

	! m#link_name = '(.*?)';#;
	$-{link_name} = $1;
	! m#file_size = '(\d+)';#;
	INFO( name => $-{link_name}, size => $1 );

	! m#sid='(.*?)';#;
	$-{sid} = $1;

	! m#CAPTCHA_IMAGE_URL = '(.*?)';#;
	$-{img_base} = $1;

stage_captcha:
	GET( "/ajax_scripts/check_timer.php?tmp=" . (irand 1000) . 1, keep_referer => 1 );

	if ( m{^(\d+)$} ) {
		WAIT( $1, "expecting captcha" );
		GOTO stage_captcha;
	}

	! m{img:(\S+)};
	$-{img} = $-{img_base} . $1 . ".jpg";

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

	CAPTCHA(
		qr/[a-z]{5}/,
		#process => \&sm_decaptcha,
	);

	GOTO stage_captcha unless defined $_;

	GET( '/ajax_scripts/verifier.php', post => "?$-{sid}&code=$_", keep_referer => 1 );

	if ( /^\s*1\s*$/s ) {
		CAPTCHA_RESULT( "OK" );
	} else {
		CAPTCHA_RESULT( "FAIL" );
		GOTO stage_captcha;
	}

	GET( '/ajax_scripts/dl.php', keep_referer => 1 );

	s/\s+//sg;
	$-{dl_id} = $_;

	GET( '/ajax_scripts/update_dl.php?id=' . $-{dl_id}, keep_referer => 1 );

	GET( "/ajax_scripts/_get.php?link_id=$-{link_id}&link_name=$-{link_name}&dl_id=$-{dl_id}&password=",
		keep_referer => 1 );

	! !/"You can not download now/;

	s/^{//; s/}$//;
	my %js = map { /^(.*?)\s*:\s*"(.*?)"/ } split /\s*,\s*/, $_;

	CLICK_DOWNLOAD( "$js{serv}/download/$js{hash}/$-{dl_id}/" );


	# most likely multi-download
	RESTART( 0, "download error" ) if /Download Error/;

perl:

sub sm_color_select
{
	my @s = sort { $a <=> $b } @_;
	return $s[0];
}

sub sm_decaptcha
{
	my $img = shift;

	$img->color_filter( \&sm_color_select );
	$img->luma_emphasize( 50, 150 );
	return $img->ocr();
}

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