package Plugins::openfile;
#
# openfile.pm module is a part of Web Share Downloader
# Copyright (C) 2006,2007 by Aleksey Luzin
#
#

use strict;
use warnings;
use lib '..';
use sql;
use WSD::Download qw/&direct_download &create_request/;
use Common;
use HTTP::Request::Common qw(POST);
use MIME::Base64;
use Data::Dumper;
use Exporter ();
use vars qw($VERSION);

our (@ISA, @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(&check_link &download);
$VERSION = "1.0" ;


sub check_link {
	shift;
	my $link = shift;
	if (($link =~ /openfile\.ru/)) {
		return 1;
	}
	return 0;
}
sub step1 {
	$log->write(2,"openfile::Step1");
	my $link = shift;
	my $id = shift;
	my $req = create_request($link);
	my $response = $browser->request($req);
	unless ($response->is_success) {return '';  }
	my $content = $response->content;
	$content =~ /name\=[\"\']file_id[\"\']\s*?value\=[\"\'](\d+)[\"\']/;
	my $file_id = $1;
	$response = $browser->get('http://openfile.ru/secret.php');
	$content = $response->content;
	my $image = encode_base64($content);
	my $rnd = int(rand(1000000));
#wait for input image numbers
	my $tmp = 'rnd='.$rnd.'|file_id='.$file_id.'|image='.$image;
	$links->setstatus($id, {status=>5, statustext=>'Waiting for input', tmp=>$tmp,input=>'', nexttry=>'3 minute', hostname=>$config->{host}});
	return '';   
}
sub strtohash {
	my $str = shift;
	my %hash;
	my @a = split(/\|/, $str);
	foreach my $a (@a) {
		my @a1 = split('=', $a);
		$hash{$a1[0]} = $a1[1];
	}	
	return \%hash;
}

sub step2 {
	my $link = shift;
	$log->write(2,"openfile::Step2");
	my $h = strtohash($link->{tmp});
	my $content = ['file_id'=>$h->{file_id}, 'secret'=>$link->{input}];
	my $req = POST $link->{link},
		Referer=>$link->{link},
		Content => $content;
	my $response = $browser->request($req);
	$content = $response->content;
	$content =~ /a href=\"(.*?download.*?)\"/;
	$log->write(2,"Dlink::$1");
	return $1;
	    
}
sub download {
	shift;
	my $id = shift;
	my $link = $links->getlink($id);
	my $dlink = '';
	if(($link->{status} == '5')&&($link->{nexttry} > $link->{now})) {
		$links->setstatus($id, {status=>1});
		$dlink = step2($link) if($link->{input});
	} else {
		$links->setstatus($id, {status=>1});
		step1($link->{link}, $id);
		return '';
	}
	if ($dlink) {
		my $req = create_request($dlink);
		WSD::Download::direct_download($id, $req);    
	} else {
		my $error = 'Не могу получить прямую ссылку';
		$links->setstatus($id, {status=>3, statustext=>$error, nexttry=>"5 minute"});
	}
}
1;