=item Revision
-$Revision: 1.1 $
+$Revision: 1.2 $
=item Created:
=head1 SYNOPSIS
- Usage: announceEmail.pl [-usa|ge] [-h|elp] [-v|erbose] [-de|bug] [-da|emon]
+ Usage: announceEmail.pl [-usa|ge] [-h|elp] [-v|erbose] [-de|bug]
[-use|rname <username>] [-p|assword <password>]
- [-i|map <server]
+ [-i|map <server>] [-t|imeout <secs>]
+ [-an|nouce] [-ap|pend] [-da|emon] [-n|name <name>]
+ [-uses|sl] [-useb|locking]
Where:
- -usa|ge: Print this usage
- -h|elp: Detailed help
- -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)
- -p|assword: Password to use (Default: prompted)
- -i|map: IMAP server to talk to (Default: defaria.com)
+ -usa|ge Print this usage
+ -h|elp Detailed help
+ -v|erbose Verbose mode (Default: -verbose)
+ -de|bug Turn on debugging (Default: Off)
+
+ -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)
+ -t|imeout <s> Timeout IMAP idle call (Sefault: 600 seconds or 10 minutes)
+
+ -an|nounce Announce startup (Default: False)
+ -ap|pend Append to logfile (Default: Noappend)
+ -da|emon Run in daemon mode (Default: -daemon)
+ -n|ame Name of account (Default: imap)
+ -uses|sl Whether or not to use SSL to connect (Default: False)
+ -useb|locking Whether to block on socket (Default: False)
+
+ Signals:
+ $SIG{USR1}: Toggles debug option
+ $SIG{USR2}: Reestablishes connection to IMAP server
=head1 DESCRIPTION
use Display;
use Logger;
+use Speak;
+use TimeUtils;
use Utils;
+local $0 = "$FindBin::Script " . join ' ', @ARGV;
+
my $defaultIMAPServer = 'defaria.com';
my $IMAP;
my %unseen;
'I was looking in your inbox and found a message',
'Not sure you want to hear this message',
'Good news',
+ "What's this? A new message",
);
+my $icon = '/home/andrew/.icons/Thunderbird.jpg';
+my $timeout = 5 * 1000;
+
my %opts = (
- 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,
+ usage => sub { pod2usage },
+ help => sub { pod2usage(-verbose => 2)},
+ verbose => sub { set_verbose },
+ debug => sub { set_debug },
+ daemon => 1,
+ timeout => 600, # 10 minutes
+ username => $ENV{USER},
+ password => $ENV{PASSWORD},
+ imap => $defaultIMAPServer,
);
+sub notify($) {
+ my ($msg) = @_;
+
+ my $cmd = "notify-send -i $icon -t $timeout '$msg'";
+
+ Execute $cmd;
+
+ return;
+} # notify
+
sub interrupted {
if (get_debug) {
- $log->msg("Turning off debugging");
+ notify 'Turning off debugging';
set_debug 0;
} else {
- $log->msg("Turning on debugging");
+ notify ('Turning on debugging');
set_debug 1;
} # if
return;
} # interrupted
-$SIG{USR1} = \&interrupted;
-
-sub debugit($) {
- my ($msg) = @_;
+sub Connect2IMAP;
- $log->msg($msg) if get_debug;
+#sub restart {
+# $log->dbug("Re-establishing connection to $opts{imap} as $opts{username}");
+#
+# Connect2IMAP;
+#
+# goto MONITORMAIL;
+#} # restart
- return;
-} # logit
+$SIG{USR1} = \&interrupted;
+#$SIG{USR2} = \&restart;
sub unseenMsgs() {
$IMAP->select('inbox') or
} # unseenMsgs
sub Connect2IMAP() {
- $log->msg("Connecting to $opts{imap} as $opts{username}");
+ $log->dbug("Connecting to $opts{imap} as $opts{username}");
+
+ # Destroy any old connections
+ undef $IMAP;
$IMAP = Mail::IMAPTalk->new(
- Server => $opts{imap},
- Username => $opts{username},
- Password => $opts{password},
+ 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->dbug("Connected to $opts{imap} as $opts{username}");
# Focus on INBOX only
$IMAP->select('inbox');
} # Connect2IMAP
sub MonitorMail() {
- 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{$_}
- } # if
- } # for
-
- debugit "Processing newUnseen";
- for (keys %newUnseen) {
- next if $unseen{$_};
-
- my $envelope = $IMAP->fetch($_, '(envelope)');
- my $from = $envelope->{$_}{envelope}{From};
- my $subject = $envelope->{$_}{envelope}{Subject};
- $subject //= 'Unknown subject';
-
- # Extract the name only when the email is of the format "name <email>"
- if ($from =~ /^"?(.*?)"?\s*\<(\S*)>/) {
- $from = $1 if $1 ne '';
- } # if
-
- if ($subject =~ /=?\S+?(Q|B)\?(.+)\?=/) {
- $subject = decode_base64($2);
+# MONITORMAIL:
+ $log->dbug("Top of MonitorMail loop");
+
+ # 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);
+
+ $log->dbug("Closed and reselected 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
+ $log->dbug("Cleaning out unseen");
+ for (keys %unseen) {
+ if (defined $newUnseen{$_}) {
+ if ($unseen{$_}) {
+ delete $newUnseen{$_};
} # if
-
- # Google Talk doesn't like #
- $subject =~ s/\#//g;
-
- # Now speak it!
- debugit "Speaking message from $from";
-
- my $logmsg = "From $from $subject";
-
- my $greeting = $greetings[int rand $#greetings];
- my $msg = "$greeting from $from... " . quotemeta $subject;
- $msg =~ s/\"/\\"/g;
-
- # Log it
+ } else {
+ delete $unseen{$_}
+ } # if
+ } # for
+
+ $log->dbug("Processing new unseen messages");
+ for (keys %newUnseen) {
+ next if $unseen{$_};
+
+ my $envelope = $IMAP->fetch($_, '(envelope)');
+ my $from = $envelope->{$_}{envelope}{From};
+ my $subject = $envelope->{$_}{envelope}{Subject};
+ $subject //= 'Unknown subject';
+
+ # Extract the name only when the email is of the format "name <email>"
+ if ($from =~ /^"?(.*?)"?\s*\<(\S*)>/) {
+ $from = $1 if $1 ne '';
+ } # if
+
+ if ($subject =~ /=?\S+?(Q|B)\?(.+)\?=/) {
+ $subject = decode_base64($2);
+ } # if
+
+ # Google Talk doesn't like #
+ $subject =~ s/\#//g;
+
+ # Remove long strings of numbers like order numbers. They are uninteresting
+ my $longNumber = 5;
+ $subject =~ s/\s+\S*\d{$longNumber,}\S*\s*//g;
+
+ # Now speak it!
+ my $logmsg = "From $from $subject";
+
+ my $greeting = $greetings[int rand $#greetings];
+ my $msg = "$greeting from $from... $subject";
+ $msg =~ s/\"/\\"/g;
+
+ 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.
+ $log->dbug("About to speak/log");
+ if ($hour >= 7) {
+ $log->dbug("Calling speak");
+ speak $msg, $log;
$log->msg($logmsg);
+ } else {
+ $log->msg("$logmsg [silent]");
+ } # if
- debugit $logmsg;
+ $unseen{$_} = 1;
+ } # for
- my $cmd = "/usr/local/bin/gt \"$msg\"";
+ # Let's time things
+ my $startTime = time;
- my $hour = (localtime)[2];
+ # Re-establish callback
+ $log->dbug("Evaling idle");
+ eval { $IMAP->idle(\&MonitorMail, $opts{timeout}) };
- # 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 ($status, @output) = Execute $cmd;
+ $log->err("Unable to set IMAP Idle - AS $@", 1) if $@;
+ $log->msg("IMAP Idle for $opts{name} timed out in " . howlong $startTime, time);
- if ($status) {
- $log->err("Unable to execute $cmd" . join("\n", @output));
- } # if
- } # if
+ # 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 return
+ # back to main which will re-establish the connection and call us again.
+ unless ($IMAP->get_response_code('timeout')) {
+ my $errstr = $IMAP->get_last_error;
- $unseen{$_} = 1;
- } # for
- } # while
+ $log->dbug("$opts{name} went away - $errstr");
+ } # unless
- return;
+ return 0;
} # MonitorMail
END {
- $IMAP->quit if $IMAP;
+ # If $log is not yet defined then the exit is not unexpected
+ if ($log) {
+ my $msg = "$FindBin::Script $opts{name} ended unexpectedly!";
+
+ speak $msg, $log;
- $log->msg("$FindBin::Script ending!");
+ $log->err($msg);
+ } # if
} # END
## Main
'debug',
'daemon!',
'username=s',
+ 'name=s',
'password=s',
'imap=s',
- 'sleep',
-);
+ 'timeout=i',
+ 'usessl',
+ 'useblocking',
+ 'announce!',
+ 'append',
+) || 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
+ no warnings;
+ EnterDaemonMode unless defined $DB::OUT or get_debug;
+ use warnings;
+} # if
$log = Logger->new(
- path => '/var/log',
+ path => '/var/local/log',
+ name => "$Logger::me.$opts{name}",
timestamped => 'yes',
- append => 'yes',
+ append => $opts{append},
);
-Connect2IMAP;
+if ($opts{username} =~ /(.*)\@/) {
+ $opts{user} = $1;
+} else {
+ $opts{user} = $opts{username};
+} # if
+
+my $msg = "Now monitoring email for $opts{user}\@$opts{name}";
-my $msg = "Now monitoring email for $opts{username}\@$opts{imap}";
+# Changed to loop here - better than using a goto. This kinda kills the idea of
+# using siguser2 to interrupt announceEmail.pl to kick it into re-establishing
+# the connection.
+while () {
+ Connect2IMAP;
-$log->msg($msg);
+ speak $msg, $log if $opts{announce};
-my $cmd = "/usr/local/bin/gt \"$msg\"";
+ $log->msg($msg);
-my ($status, @output) = Execute $cmd;
+ MonitorMail;
-$IMAP->idle(\&MonitorMail);
+ $log->dbug("$opts{name} timed out! Re-establishing connection");
+} # while
+# Should not get here
+$log->err("Falling off the edge of $0", 1);