#!/usr/bin/perl 

###
# No Copyright.	 Use as you wish.  Don't blame me if it doesn't work as it should.
# Send me a note if you feel like it.  Bug fixes and enhancements appreciated.
# Shawn Van Every: vanevery@walking-productions.com
# 
###

###
# Perl modules that need to be installed
###
use MIME::Parser;
use MIME::Entity;
use MIME::Base64;
use Net::POP3;
use XMLRPC::Lite;

###
# User Configurable Variables
###
my $username = "xxxxx"; ## CHANGE THIS LINE
my $password = "xxxxx";  ## CHANGE THIS LINE
my $mailserver = "mail.xxxx.com"; ## CHANGE THIS LINE
my $temp_folder = "/home/sve204/redial_popper/temp/"; ## CHANGE THIS LINE
my $attachment_output_folder = "/home/sve204/public_html/redial_vmail/"; ## CHANGE THIS LINE
my $attachment_output_folder_relative = "http://itp.nyu.edu/~sve204/redial_vmail/"; ## CHANGE THIS LINE
my $blog_xmlrpc_url = "http://www.mobvcasting.com/wp/xmlrpc.php"; ## CHANGE THIS LINE
my $blog_id = 0; ## CHANGE THIS LINE
my $blog_username = "xxxx"; ## CHANGE THIS LINE
my $blog_password = "xxxx"; ## CHANGE THIS LINE

my $use_wp_plugin = 1; ## If you are using this with WordPress and 
## you are using my Word Press Plugin: 
## http://www.walking-productions.com/QuickTimePostWPP/

###
# Other Variables that *may be* changed
###
my $pop = Net::POP3->new($mailserver, Timeout => 15);
my $delete_messages = 0; # Delete messages from your inbox as they are processed
my $delete_temp_files = 0; # Delete temporary files that are created
my $print_output = 1; # Print output
my $post_to_blog = 1; # Post to your blog?

my $umask = '0002';	 # File creation to 775, 0022 would be 755

my %mime_types = (	"audio\/x-wav", "wav",
					"audio\/wav", "wav",
				); # A list of the attachment mime types to extract

###
# Parsing Subroutine
###
sub parseMessageParts
{
	my @messageParts = @_;
	
	my $partnum = 0;
	my $is_mime_message = 0;

	while(my $part = shift(@messageParts)) 
	{		   
		$is_mime_message = 1;  # Yes we have a mime message
		my $known_type = 0;	 # Did we find the type yet?

		# Get the Mime type of the part
		my $type=$part->head->mime_type || $part->head->effective_type; 

		my $already_matched = 0;
		
		## Loop through the types we understand
		foreach $valid_type (keys %mime_types)
		{
		  if ($already_matched != 1) # This is a hack because my matching isn't right
		  {		   
			if ($type =~ $valid_type)
			{
				$known_type = 1;
				
				my $attachment = $part->bodyhandle->as_string;
				my $file_name = "attachment_" . time() . "_" . int(rand(1000)) . "\." . $mime_types{$valid_type};
				my $image_file = $attachment_output_folder . $file_name;
				my $fh = new FileHandle "> $image_file";
				if (defined $fh) {
						print $fh $attachment;
						$fh->close;
				}
			
				$attachments[++$#attachments] = $file_name;
				$attachments_type[++$#attachments_type] = $mime_types{$valid_type};
				$attachments_relative[++$#attachments_relative] = $attachment_output_folder_relative . $file_name;
					
				$attachments_mime_type[++$#attachments_mime_type] = $valid_type;
				$already_matched = 1;
			}
		  } # End $already_matched
		}
		
		## Not in our list, let's check for text or multipart messages
		if ($known_type == 0)
		{
			if ($type =~ /text\/plain/i)
			{	
				my $message_bodyhandle = $part->bodyhandle;
				$mime_message_body = $message_bodyhandle->as_string;
			 
				$body = $mime_message_body;
			}						
			elsif ($type =~ /multipart\/.*/i || $type =~ /message\/.*/i)
			{
				# Multipart Message, Parse This Again
				my @otherparts=$part->parts;
				&parseMessageParts(@otherparts);
			}
			else
			{
				if ($print_output)
				{
					print "Other Type: " . $type . "\n\n"; # OUTPUT
				}
			}
		}
		
		$partnum++;
	}
	return $is_mime_message;
}

###
# Main Program Execution
###
if ($print_output)
{
	print("Running at: " . localtime() . "\n");
}

if ($pop->login($username, $password)) 
{
		$umask = oct($umask) if $umask =~ /^0/;
		umask $umask;
		
		if ($print_output)
		{
			print("Logged into mailserver\n");
		}	 
		
		# Create the parser object
		my $parser = MIME::Parser->new();
		$parser->output_dir($temp_folder);
		
		my $msgnums = $pop->list; # hashref of msgnum => size
		foreach my $msgnum (keys %$msgnums) 
		{
				my $msg = $pop->get($msgnum); 
				
				my $entity = $parser->parse_data($msg);
				
				###
				# GET MESSAGE HEADER
				###
				my $msg_head = $entity->head;
				my $subject = "";
				my $to = "";
				my $from = "";
				
				my $vm_name = "";
				my $vm_duration = "";
				my $vm_messagenum = "";
				my $vm_mailbox = "";
				my $vm_callerid = "";
				my $vm_date = "";
				
				###
				# MESSAGE Related Vars
				###
				$body = "";
				@attachments = ();
				@attachments_type = ();
				@attachments_relative = ();
				@attachments_mime_type = ();
				
				##
				# GET MESSAGE SUBJECT
				##
				if ($msg_head->count('Subject') > 0)
				{
					$subject = $msg_head->get('Subject');			 
				}
				
				##
				# GET MESSAGE FROM
				##
				if ($msg_head->count('From') > 0)
				{
					$from = $msg_head->get('From');
					if ($from =~ /<(.*)>/)
					{
						$from = $1;
					}
				}
				
				##
				# GET MESSAGE TO
				##
				if ($msg_head->count('To') > 0)
				{
					$to = $msg_head->get('To');
					if ($to =~ /<(.*)>/)
						{
							$to = $1;
						}					
				}
				
				###
				# GET MESSAGE PARTS (BODY AND ATTACHMENTS)
				###
				my @parts=$entity->parts;
				my $is_mime = &parseMessageParts(@parts);  ## Calling our parse subroutine
								
				##
				# IF IT ISN'T A MIME MESSAGE (NO ATTACHMENTS)
				##
				if (!$is_mime)
				{
					###
					# GET MESSAGE BODY LINES
					###
					$body = $entity->body;
				}
				
				###
				# PARSE THE BODY
				###
				@body_array = split('\n',$body);
				
				$line_count = 0;
				foreach $message_line (@body_array)
				{
					print("***" . $message_line . "\n");
					if ($line_count == 0)
					{
						$vm_name = $message_line;
					}
					elsif ($line_count == 1)
					{		
						$vm_duration = $message_line;
					}
					elsif ($line_count == 2)
					{
						$vm_messagenum = $message_line;
					}
					elsif ($line_count == 3)
					{
						$vm_mailbox = $message_line;
					}
					elsif ($line_count == 4)
					{
						$vm_callerid = $message_line;
					}
					elsif ($line_count == 5)
					{
						$vm_date = $message_line;
					}
					else
					{
						if ($print_output)
						{
							print "skipping " . $message_line . "\n";
						}
					}
					$line_count++;						
				}
				
				$body = "New Message from $vm_callerid at $vm_date.  It is message number $vm_messagenum and is $vm_duration long.  The name is $vm_name and the mailbox is $vm_mailbox\n";
			   		
				chomp($to); # REMOVE TRAILING LINE BREAKS
				chomp($from);
				chomp($subject);
				#chomp($body);
				
				if ($post_to_blog)
				{
					my $attachment_html = "";
					for (my $i = 0; $i <= $#attachments; $i++)
					{
						my $attachment = $attachments[$i];
						my $attachment_type = $attachments_type[$i];
						my $attachment_relative = $attachments_relative[$i];
						my $attachment_mime_type = $attachments_mime_type[$i];
					 
						if ($attachment_type eq "wav")
						{
						
							if ($use_wp_plugin)
							{
								$attachment_html .= "[QUICKTIME $attachment_relative 320 257]";
							}
							else
							{
								$attachment_html .= "
			<OBJECT CLASSID=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" WIDTH=\"320\" HEIGHT=\"257\" CODEBASE=\"http://www.apple.com/qtactivex/qtplugin.cab\">
				<PARAM name=\"SRC\" VALUE=\"$attachment_relative\">
				<PARAM name=\"AUTOPLAY\" VALUE=\"false\">
				<PARAM name=\"CONTROLLER\" VALUE=\"true\">
				<EMBED SRC=\"$attachment_relative\" WIDTH=\"320\" HEIGHT=\"257\" AUTOPLAY=\"false\" CONTROLLER=\"true\" PLUGINSPAGE=\"http://www.apple.com/quicktime/download/\"></EMBED>
			</OBJECT>"; 
						   }
						}
						print("The HTML:" . $attachment_html . "\n");
					}
			
					my $postresult=XMLRPC::Lite
							   ->proxy($blog_xmlrpc_url)
							   ->call('metaWeblog.newPost',$blog_id,$blog_username,$blog_password,
								{
									'title'=>$subject,
									'description'=>$body . "\n" . $attachment_html,
									'mt_allow_comments'=>1,
									'mt_allow_pings'=>1
								},
								1
					)
					->result;

				   for (my $i = 0; $i <= $#attachments; $i++)
				   {
						my $attachment = $attachment_output_folder . $attachments[$i];
						my $attachment_type = $attachments_type[$i];
						my $attachment_relative = $attachments_relative[$i];
						my $attachment_mime_type = $attachments_mime_type[$i];

						my $filesize = -s $attachment;
						if ($print_output)
						{
							print $filesize;
						}

					
						if ($print_output)
						{
							print "Message To: $to\n";
							print "Message From $from\n";
							print "Message Subject $subject\n";
							print "Message Body $body\n";
							for (my $i = 0; $i <= $#attachments; $i++)
							{
								print "Message Attachment $attachments[$i]	-  $attachments_type[$i]  -	 $attachments_relative[$i]\n";
							}
							print "Post to Blog Result: " . $postresult . "\n";
							print "--------------------------\n";
						}
					}					
				}
				elsif ($print_output)
				{
					print "Message To: $to\n";
					print "Message From $from\n";
					print "Message Subject $subject\n";
					print "Message Body $body\n";
					for (my $i = 0; $i <= $#attachments; $i++)
					{
						print "Message Attachment $attachments[$i]	-  $attachments_type[$i]  -	 $attachments_relative[$i]\n";
					}
					print "Not Posted to Blog";
					print "--------------------------\n";
				}
			
				if ($delete_messages)
				{
						$pop->delete($msgnum);
				}
					 
		}

		if ($delete_temp_files)
		{		
			$parser->filer->purge;
		}  
}
$pop->quit;