X-Git-Url: https://defaria.com/gitweb/?a=blobdiff_plain;f=bin%2FannounceEmail.pl;h=94789e84d27a695ecead72c234fb7043e99c1ef8;hb=e0126eea04c6d0de501af304c30d0276d78799bb;hp=13b92be5c4c45f5411632af01f0e9f92560c25b9;hpb=6afcca61b1f4ebfcb3ed8164df166b4fa69ddd97;p=clearscm.git diff --git a/bin/announceEmail.pl b/bin/announceEmail.pl index 13b92be..94789e8 100755 --- a/bin/announceEmail.pl +++ b/bin/announceEmail.pl @@ -17,7 +17,7 @@ Andrew DeFaria =item Revision -$Revision: 1.0 $ +$Revision: 1.2 $ =item Created: @@ -29,22 +29,25 @@ $Date: 2019/04/04 13:40:10 $ =back -=hade1 SYNOPSIS +=head1 SYNOPSIS Usage: announceEmail.pl [-usa|ge] [-h|elp] [-v|erbose] [-de|bug] [-da|emon] [-use|rname ] [-p|assword ] [-i|map sub { pod2usage }, - help => sub { pod2usage(-verbose => 2)}, - verbose => sub { set_verbose }, - debug => sub { set_debug }, - daemon => 1, - username => $ENV{USER}, - password => $ENV{PASSWORD}, - imap => $defaultIMAPServer, - sleep => $defaultSleeptime, + usage => sub { pod2usage }, + help => sub { pod2usage(-verbose => 2)}, + verbose => sub { set_verbose }, + debug => sub { set_debug }, + daemon => 1, + username => $ENV{USER}, + password => $ENV{PASSWORD}, + imap => $defaultIMAPServer, + usessl => 0, + useblocking => 0, + announce => 0, ); sub interrupted { @@ -105,42 +122,28 @@ sub interrupted { $SIG{USR1} = \&interrupted; -sub debugit($) { - my ($msg) = @_; - - $log->msg($msg) if get_debug; - - return; -} # logit - sub unseenMsgs() { - my %unseenMsgs; - - for (my $i = 1; $i <= $IMAP->status; $i++) { - $unseenMsgs{$i} = 0 unless $IMAP->seen($i); - } # for + $IMAP->select('inbox') or + $log->err("Unable to select inbox: " . get_last_error(), 1); - return %unseenMsgs; + return map { $_=> 0 } @{$IMAP->search('not', 'seen')}; } # unseenMsgs sub Connect2IMAP() { - $log->msg("Connecting to $opts{imap} as $opts{username}...", 1); + $log->dbug("Connecting to $opts{imap} as $opts{username}"); - $IMAP = Net::IMAP::Simple->new($opts{imap}) || - $log->err("Unable to connect to IMAP server $opts{imap}: " . $Net::IMAP::Simple::errstr, 1); + $IMAP = Mail::IMAPTalk->new( + Server => $opts{imap}, + Username => $opts{username}, + Password => $opts{password}, + UseSSL => $opts{usessl}, + UseBlocking => $opts{useblocking}, + ) or $log->err("Unable to connect to IMAP server $opts{imap}: $@", 1); - $log->msg(' connected'); - - $log->msg("Logging onto $opts{imap} as $opts{username}...", 1); - - unless ($IMAP->login($opts{username}, $opts{password})) { - $log->err("Login to $opts{imap} as $opts{username} failed: " . $IMAP->errstr, 1); - } # unless - - $log->msg(' logged on'); + $log->dbug("Connected to $opts{imap} as $opts{username}"); # Focus on INBOX only - $IMAP->select('INBOX'); + $IMAP->select('inbox'); # Setup %unseen to have each unseen message index set to 0 meaning not read # aloud yet @@ -149,105 +152,119 @@ sub Connect2IMAP() { return; } # Connect2IMAP +sub Say($) { + my ($msg) = @_; + + my ($status, @output) = Execute "/usr/local/bin/gt \"$msg\""; + + $log->err("Unable to speak (Status: $status) - " + . join ("\n", @output), $status) if $status; + + return; +} # Say + sub MonitorMail() { - my $msg = "Now monitoring email for $opts{username}\@$opts{imap}"; - - $log->msg($msg); - - my $cmd = "/usr/local/bin/gt \"$msg\""; - - my ($status, @output) = Execute $cmd; - - while () { - # First close and reselect the INBOX to get its current status - debugit "Reconnecting to INBOX"; - $IMAP->close; - $IMAP->select('INBOX') - or $log->err("Unable to select INBOX - ". $IMAP->errstr(), 1); - - # Go through all of the unseen messages and add them to %unseen if they were - # not there already from a prior run and read - my %newUnseen = unseenMsgs; - - # Now clean out any messages in %unseen that were not in the %newUnseen and - # marked as previously read - for (keys %unseen) { - if (defined $newUnseen{$_}) { - if ($unseen{$_}) { - delete $newUnseen{$_}; - } # if - } else { - delete $unseen{$_} + MONITORMAIL: + + # First close and reselect the INBOX to get its current status + $IMAP->close; + $IMAP->select('INBOX') + or $log->err("Unable to select INBOX - ". $IMAP->errstr(), 1); + + # Go through all of the unseen messages and add them to %unseen if they were + # not there already from a prior run and read + my %newUnseen = unseenMsgs; + + # Now clean out any messages in %unseen that were not in the %newUnseen and + # marked as previously read + for (keys %unseen) { + if (defined $newUnseen{$_}) { + if ($unseen{$_}) { + delete $newUnseen{$_}; } # if - } # for + } else { + delete $unseen{$_} + } # if + } # for - debugit "Processing newUnseen"; - for (keys %newUnseen) { - next if $unseen{$_}; + for (keys %newUnseen) { + next if $unseen{$_}; - my @msglines = $IMAP->top($_); + my $envelope = $IMAP->fetch($_, '(envelope)'); + my $from = $envelope->{$_}{envelope}{From}; + my $subject = $envelope->{$_}{envelope}{Subject}; + $subject //= 'Unknown subject'; - # What happens at INBOX 0? Does top return empty array? - $log->err("Unable to get top for $_ - " . $IMAP->errstr(), 1) unless @msglines; + # Extract the name only when the email is of the format "name " + if ($from =~ /^"?(.*?)"?\s*\<(\S*)>/) { + $from = $1 if $1 ne ''; + } # if - my $email = Email::Simple->new(join '', @msglines); + if ($subject =~ /=?\S+?(Q|B)\?(.+)\?=/) { + $subject = decode_base64($2); + } # if - my $from = $email->header('From'); + # Google Talk doesn't like # + $subject =~ s/\#//g; - # Extract the name only when the email is of the format "name " - if ($from =~ /^"?(.*?)"?\s*\<(\S*)>/) { - $from = $1 if $1 ne ''; - } # if + # Now speak it! + my $logmsg = "From $from $subject"; - my $subject = $email->header('Subject'); + my $greeting = $greetings[int rand $#greetings]; + my $msg = "$greeting from $from... $subject"; + $msg =~ s/\"/\\"/g; - if ($subject =~ /=?\S+?(Q|B)\?(.+)\?=/) { - $subject = decode_base64($2); - } # if + my $hour = (localtime)[2]; - # Google Talk doesn't like # - $subject =~ s/\#//g; + # Only announce if after 6 Am. Note this will announce up until + # midnight but that's ok. I want midnight to 6 Am as silent time. + if ($hour >= 6) { + Say $msg; + $log->msg($logmsg); + } else { + $log->msg("$logmsg [silent]"); + } # if - # Now speak it! - debugit "Speaking message from $from"; - my $logmsg = "From $from $subject"; + $unseen{$_} = 1; + } # for - $msg = "Message from $from... " . quotemeta $subject; - $msg =~ s/\"/\\"/g; + # Re-establish callback + eval { $IMAP->idle(\&MonitorMail) }; - debugit $logmsg; + # If we return from idle then the server went away for some reason. With Gmail + # the server seems to time out around 30-40 minutes. Here we simply reconnect + # to the imap server and continue to MonitorMail. + $log->dbug("MonitorMail: Connection to $opts{imap} ended. Reconnecting"); - $cmd = "/usr/local/bin/gt \"$msg\""; + # Destroy current IMAP connection + $log->dbug("MonitorMail: Destorying IMAP connection to $opts{imap}"); - my $hour = (localtime)[2]; + undef $IMAP; - # Only announce if after 6 Am. Not this will announce up until - # midnight but that's ok. I want midnight to 6 Am as silent time. - if ($hour > 6) { - ($status, @output) = Execute $cmd; + # Re-establish connection + Connect2IMAP; - if ($status) { - $log->err("Unable to execute $cmd" . join("\n", @output)); - } # if - } # if + $log->dbug("MonitorMail: Reconnected to IMAP server $opts{imap}"); - $unseen{$_} = 1; - } # for + # MonitorMail again - the dreaded goto! Seems the cleanest way to restart + # in this instance. I could call MonitorMail() recursively but that would + # leave junk on the stack. + $log->dbug('MonitorMail: Going back to the top of the loop'); - debugit "Sleeping for $opts{sleep} minutes"; - sleep 60 * $opts{sleep}; - debugit "Ah that was refreshing!"; - } # while + goto MONITORMAIL; - return; + return; # To make perlcritic happy } # MonitorMail -$SIG{USR2} = \&MonitorMail; - END { - $IMAP->quit if $IMAP; + # If $log is not yet defined then the exit is not unexpected + if ($log) { + my $msg = "$FindBin::Script ending unexpectedly!"; + + Say $msg; - $log->msg("$FindBin::Script ending!"); + $log->err($msg); + } # if } # END ## Main @@ -259,26 +276,53 @@ GetOptions( 'debug', 'daemon!', 'username=s', + 'name=s', 'password=s', 'imap=s', - 'sleep', -); + 'usessl', + 'useblocking', + 'announce!', +) || pod2usage; unless ($opts{password}) { verbose "I need $opts{username}'s password"; $opts{password} = GetPassword; } # unless -$opts{debug} = get_debug; +$opts{name} //= $opts{imap}; -EnterDaemonMode if $opts{daemon}; +if ($opts{username} =~ /.*\@(.*)$/) { + $opts{name} = $1; +} # if + +if ($opts{daemon}) { + # Perl complains if we reference $DB::OUT only once + my $foo = $DB::OUT; + EnterDaemonMode unless defined $DB::OUT; +} # if $log = Logger->new( path => '/var/log', + name => "$Logger::me.$opts{name}", timestamped => 'yes', append => 'yes', ); Connect2IMAP; +if ($opts{username} =~ /(.*)\@/) { + $opts{user} = $1; +} else { + $opts{user} = $opts{username}; +} # if + +my $msg = "Now monitoring email for $opts{user}\@$opts{name}"; + +Say $msg if $opts{announce}; + +$log->msg($msg); + MonitorMail; + +# Should not get here +$log->err("Falling off the edge of $0", 1);