#!/usr/bin/perl -w

# Takes a Megaupload URL in argument, displays the captcha and ask for
# you to decode it, wait 60 seconds then download the file.
# Requires ImageMagick, WWW::Mechanize and LWP::Simple.
# Will overwrite anything that's in /tmp/captcha.gif
# Probably full of bugs but it works for my purpose.

use strict;
use WWW::Mechanize;
use LWP::Simple;

sub countdown($)
{
	my $timeleft = shift;
	while ($timeleft) {
		sleep 1;
		printf STDERR "\rnow waiting %02d seconds", $timeleft--;
	}
	print STDERR "\n";
}

sub decode_captcha($)
{
	my $url = shift;
	my $file = '/tmp/captcha.gif';
	my $captcha;

	getstore($url, $file) or return undef;
	system 'display /tmp/captcha.gif &';
	print "type in the captcha: ";
	$captcha = <STDIN>;
	chomp $captcha;
	return $captcha;
}

my $bot = WWW::Mechanize->new;
$bot->get($ARGV[0]);

my $captcha = $bot->find_image( url_regex => qr/megaupload\.com\/gencap\.php/ );
die "couldn't find captcha" unless $captcha;

$captcha = decode_captcha($captcha->url_abs) or die "couldn't decode captcha";

$bot->submit_form(
	fields => {
		captcha => $captcha
	}
);

#$bot->save_content("samples/megaupload-after-submit.html");
my $link = $bot->find_link( url_regex => qr/\/files\// ) or die "couldn't find download link";
my $filename = ($link->URI->path_components)[-1];
print STDERR "found link: ".$link->url."\n";
countdown(60);
print STDERR "now saving to $filename\n";
getstore($link->url, $filename);
