use strict;

use vars qw($VERSION %IRSSI);

$VERSION = "20141208"
%IRSSI = (
	authors		=>	"winnetou",
	contact		=>	"me\@winnetou.pl",
	name		=>	"grabimgs",
	description	=>	"Get urls to images, dowlnload them and add to web gallery",
	license		=>	"GPLv2",
	url			=> 	"svn co https://valhalla.org.pl/svn/irssi-scripts/";
	changed		=>	$VERSION,
	commands	=>	"grabimg"
);

use Irssi;
use Regexp::Common qw /URI/;
use File::Type;
use LWP::Simple;
use Digest::MD5 qw(md5_hex);
use File::Basename;
use File::Find::Rule;

sub url_public{
	my($server,$text,$nick,$hostmask,$channel)=@_;
	get_it($1,$channel) if $text =~ /($RE{URI})/;
}

sub get_it{
	my %fileext = (
	        'image/bmp'     =>  '.bmp',
	        'image/gif'     =>  '.gif',
	        'image/jpeg'    =>  '.jpeg',
	        'image/png'     =>  '.png',
	        'image/x-png'   =>  '.png',
	        'image/tiff'    =>  '.tiff',
	);
	my $output = "/PATH/WHERE/IMAGES/SHOULD/BE/SAVED/";
	my @files = File::Find::Rule->file()
								->maxdepth(1)
								->in($output);
	my $filetype = File::Type->new();
	my($url,$channel)=@_;
	if ($channel == "#CHANNEL"){
		my $remotefile = get($url);
		my $type = $filetype->checktype_contents($remotefile);
		if (exists $fileext{$type}){
			$output .= md5_hex($remotefile);
			$output.=$fileext{$type};
			if ( not ($output ~~ @files)){
				open FILE, ">", $output;
				print FILE $remotefile;
				close FILE;
				Irssi::print("$url saved as $output")
			}else{
				Orssi::print("$url already fetched!")
			}
		}else{
			Irssi::print("$url it's not a image!\n");
		}
	}
}

Irssi::signal_add_last("message public", "url_public");
