Fixed announceEmail.pl to be less busy
[clearscm.git] / bin / announceEmail.pl
index 71c96dd..a0113a1 100755 (executable)
@@ -17,7 +17,7 @@ Andrew DeFaria <Andrew@DeFaria.com>
 
 =item Revision
 
-$Revision: 1.0 $
+$Revision: 1.2 $
 
 =item Created:
 
@@ -29,7 +29,7 @@ $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 <username>] [-p|assword <password>]
@@ -41,10 +41,10 @@ $Date: 2019/04/04 13:40:10 $
    -v|erbose:  Verbose mode (Default: -verbose)
    -de|bug:    Turn on debugging (Default: Off)
    -da|emon:   Run in daemon mode (Default: -daemon)
-   -use|rname: User name to log in with (Default: $USER)
+   -user|name: User name to log in with (Default: $USER)
    -p|assword: Password to use (Default: prompted)
    -i|map:     IMAP server to talk to (Default: defaria.com)
-   -s|leep:    Number of minutes to sleep inbetween checking mail (Default: 1)
+   -uses|sl:   Whether or not to use SSL to connect (Default: False)
 
 =head1 DESCRIPTION
 
@@ -63,8 +63,7 @@ use warnings;
 use FindBin;
 use Getopt::Long;
 use Pod::Usage;
-use Net::IMAP::Simple;
-use Email::Simple;
+use Mail::IMAPTalk;
 use MIME::Base64;
 
 use lib "$FindBin::Bin/../lib";
@@ -74,11 +73,23 @@ use Logger;
 use Utils;
 
 my $defaultIMAPServer = 'defaria.com';
-my $defaultSleeptime  = 1;
 my $IMAP;
 my %unseen;
 my $log;
 
+my @greetings = (
+  'Incoming message',
+  'You have received a new message',
+  'Hey I found this in your inbox',
+  'For some unknown reason this guy send you a message',
+  'Did you know you just got a message',
+  'Potential spam',
+  'You received a communique',
+  'I was looking in your inbox and found a message',
+  'Not sure you want to hear this message',
+  'Good news',
+);
+
 my %opts = (
   usage    => sub { pod2usage },
   help     => sub { pod2usage(-verbose => 2)},
@@ -88,115 +99,131 @@ my %opts = (
   username => $ENV{USER},
   password => $ENV{PASSWORD},
   imap     => $defaultIMAPServer,
-  sleep    => $defaultSleeptime,
+  usessl   => 0,
 );
 
-sub unseenMsgs() {
-  my %unseenMsgs;
+sub interrupted {
+  if (get_debug) {
+    $log->msg("Turning off debugging");
+    set_debug 0;
+  } else {
+    $log->msg("Turning on debugging");
+    set_debug 1;
+  } # if
 
-  for (my $i = 1; $i <= $IMAP->status; $i++) {
-    $unseenMsgs{$i} = 0 unless $IMAP->seen($i);
-  } # for
+  return;
+} # interrupted
+
+$SIG{USR1} = \&interrupted;
+
+sub unseenMsgs() {
+  $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}");
 
-  $IMAP = Net::IMAP::Simple->new($opts{imap}) ||
-    error("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},
+  ) or $log->err("Unable to connect to IMAP server $opts{imap}: $@", 1);
 
-  $log->msg("Connected");
-
-  $log->msg("Logging onto $opts{imap} as $opts{username}");
-
-  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->msg('Connected');
 
   # 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
   %unseen = unseenMsgs;
+
+  return;
 } # Connect2IMAP
 
 sub MonitorMail() {
-  $log->msg("Monitoring email");
-
-  while () {
-    # First close and reselect the INBOX to get its current status
-    $IMAP->close;
-    $IMAP->select('INBOX');
-
-    # 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{$_}
+  # 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
 
-    for (keys %newUnseen) {
-      next if $unseen{$_};
+  for (keys %newUnseen) {
+    next if $unseen{$_};
 
-      my $email = Email::Simple->new(join '', @{$IMAP->top($_)});
+    my $envelope = $IMAP->fetch($_, '(envelope)');
+    my $from     = $envelope->{$_}{envelope}{From};
+    my $subject  = $envelope->{$_}{envelope}{Subject};
+       $subject //= 'Unknown subject';
 
-      my $from = $email->header('From');
+    # Extract the name only when the email is of the format "name <email>"
+    if ($from =~ /^"?(.*?)"?\s*\<(\S*)>/) {
+      $from = $1 if $1 ne '';
+    } # if
 
-      # Extract the name only when the email is of the format "name <email>"
-      if ($from =~ /^(.*)\<(\S*)>/) {
-        $from = $1 if $1 ne '';
-      } # if
+    if ($subject =~ /=?\S+?(Q|B)\?(.+)\?=/) {
+      $subject = decode_base64($2);
+    } # if
 
-      my $subject = $email->header('Subject');
+    # Google Talk doesn't like #
+    $subject =~ s/\#//g;
 
-      if ($subject =~ /=?\S+?(Q|B)\?(.+)\?=/) {
-        $subject = decode_base64($2);
-      } # if
+    # Now speak it!
+    my $logmsg = "From $from $subject";
 
-      # Now speak it!
-      my $logmsg = "From $from $subject";
-      my $msg = "Message from $from... " . quotemeta $subject;
-      $msg =~ s/\"/\\"/g;
+    my $greeting = $greetings[int rand $#greetings];
+    my $msg      = "$greeting from $from... " . quotemeta $subject;
+       $msg      =~ s/\"/\\"/g;
 
-      if (get_verbose) {
-        $log->msg($logmsg);
-      } else {
-        $log->log($logmsg);
-      } # if
+    # Log it
+    $log->msg($logmsg);
 
-      my $cmd = "/usr/local/bin/gt \"$msg\"";
+    my $hour = (localtime)[2];
 
+    # 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) {
+      my $cmd = "/usr/local/bin/gt \"$msg\"";
       my ($status, @output) = Execute $cmd;
 
       if ($status) {
         $log->err("Unable to execute $cmd" . join("\n", @output));
       } # if
+    } # if
+
+    $unseen{$_} = 1;
+  } # for
 
-      $unseen{$_} = 1;
-    } # for
+  # Re-establish callback
+  $IMAP->idle(\&MonitorMail);
 
-    verbose "Sleeping for $opts{sleep} minutes";
-    sleep 60 * $opts{sleep};
-    verbose "Ah that was refreshing!";
-  } # while
+  # Should not get here
+  $log->err("Unable to re-establish IDLE callback from IMAP server $opts{imap}", 1);
 } # MonitorMail
 
 END {
   $IMAP->quit if $IMAP;
+
+  $log->msg("$FindBin::Script ending unexpectedly!");
 } # END
 
 ## Main
@@ -210,6 +237,7 @@ GetOptions(
   'username=s',
   'password=s',
   'imap=s',
+  'usessl',
   'sleep',
 );
 
@@ -218,7 +246,11 @@ unless ($opts{password}) {
   $opts{password} = GetPassword;
 } # unless
 
-EnterDaemonMode if $opts{daemon};
+$opts{debug} = get_debug;
+
+if ($opts{daemon}) {
+  EnterDaemonMode unless defined $DB::OUT;
+} # if
 
 $log = Logger->new(
   path        => '/var/log',
@@ -228,7 +260,15 @@ $log = Logger->new(
 
 Connect2IMAP;
 
-my $cmd = "/usr/local/bin/gt \"Now monitoring email for $opts{username}\@$opts{imap}\"";
+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;
 
-MonitorMail;
+$IMAP->idle(\&MonitorMail);
+
+# Should not get here
+$log->err("Falling off the edge of $0", 1);