#!/usr/bin/perl

# Author: tomekk
# e-mail:  tomekk/@/tomekk/./org
# home page: http://tomekk.org/
#
# Version 0.1
#
# This file is Copyrighted under the GNU Public License.
# http://www.gnu.org/copyleft/gpl.html
##########################################################

# some uses
use utf8;
use strict;
use File::Copy;
use MIME::Parser;
use String::Random;
use Mail::POP3Client;

# e-mail account
my $e_user = 'user';
my $e_pass = 'pass';
my $e_host = 'somehost';
my $e_port = 995;
my $e_ssl = 'yes'; # or no
my $e_timeout = 30;

# pics dir
my $pics_dir = "/var/www/stream/photos";

##########################################################
# farm of vars
my ($parser, $entity, $head, $subject);
my (@parts, $part, $path, $rs, $new_file, @trash, $rp, $t);
my ($pop, $i, $msg, $mails, $attchs);

# setup parser
$parser = new MIME::Parser;
$parser->output_dir($pics_dir);

# connect to POP3
$pop = new Mail::POP3Client(USER => $e_user, PASSWORD => $e_pass, HOST => $e_host, PORT => $e_port, USESSL => $e_ssl, TIMEOUT => $e_timeout);

# reset stats
$mails = 0;
$attchs = 0;

for $i (1 .. $pop->Count())
{
	# e-mail data
	$msg = $pop->HeadAndBody($i);

	$entity = $parser->parse_data($msg);
	$subject = $entity->head->get('Subject');

	# split it
	@parts = $entity->parts;

	# 'one' timestamp for all attachaments in mail
	$t = time;

	# go through each part
	for $part (@parts) 
	{
		$path = $part->bodyhandle->path;

		# we want only pics
		if ($path =~ /.*\.(PNG|JPG|GIF|BMP)/i)
		{
			# use magic and make some 'random' name
			$rs = new String::Random;
			$rp = $rs->randpattern("CcCcCcCcCcCcCcCcCcCcCcCcC");
			$new_file = $t . "_" . $rp . "." . lc(substr($path, rindex($path, '.') + 1));

			# create text file with desc. taken from e-mail subject
			open (FH, ">" , $pics_dir . "/" . $t . "_" . $rp . ".txt");
			print FH $subject;
			close (FH); 

			# do move
			move ($path, $pics_dir . "/" . $new_file);

			# stats +1 for image attachment
			$attchs++;
		} else {
			# delete other attachments
			unlink ($path);
		}
	}   

	# delete messages
	# fe. when e-mail is empty (without attachment)
	chdir ($pics_dir);
	my @trash = <msg-*.txt>;

	# for sure
	if (@trash) 
	{
		unlink (@trash);
	}

	# delete e-mail
	$pop->Delete($i);

	# stats +1 for mail
	$mails++;
	
	# let each email has its own timestamp
	sleep (1);
}

# hmm...
$pop->Close();

# basic stats
print "mails: " . $mails . "\n";
print "images: " . $attchs . "\n";
