2d11a46f8eb2c4384fc129419ff05127fa60d936
[silc.git] / apps / irssi / scripts / mail.pl
1 # Mail counter statusbar item
2 # for irssi 0.7.99 by Timo Sirainen
3 #  /SET mail_ext_program - specify external mail checker program
4 #  /SET mail_file - specifies mbox file location
5 #  /SET mail_refresh_time - in seconds, how often to check for new mail
6
7 use strict;
8 use Irssi::TextUI;
9
10 my $extprog;
11 my ($last_refresh_time, $refresh_tag);
12
13 # for mbox caching
14 my ($last_size, $last_mtime, $last_mailcount);
15
16 sub mbox_count {
17   my $mailfile = shift;
18
19   my @stat = stat($mailfile);
20   my $size = $stat[7];
21   my $mtime = $stat[9];
22
23   # if the file hasn't changed, get the count from cache
24   return $last_mailcount if ($last_size == $size && $last_mtime == $mtime);
25   $last_size = $size;
26   $last_mtime = $mtime;
27
28   my $count;
29   if ($extprog ne "") {
30     $count = `$extprog`;
31     chomp $count;
32   } else {
33     return 0 if (!open(F, $mailfile));
34
35     $count = 0;
36     while (<F>) {
37       $count++ if (/^From /);
38       $count-- if (/^Subject: .*FOLDER INTERNAL DATA/);
39     }
40     close(F);
41   }
42
43   $last_mailcount = $count;
44   return $count;
45 }
46
47 sub mail {
48   my ($item, $get_size_only) = @_;
49
50   my $count = mbox_count(Irssi::settings_get_str('mail_file'));
51   if ($count == 0) {
52     # no mail - don't print the [Mail: ] at all
53     if ($get_size_only) {
54       $item->{min_size} = $item->{max_size} = 0;
55     }
56   } else {
57     $item->default_handler($get_size_only, undef, $count, 1);
58   }
59 }
60
61 sub refresh_mail {
62   Irssi::statusbar_items_redraw('mail');
63 }
64
65 sub read_settings {
66   $extprog = Irssi::settings_get_str('mail_ext_program');
67   my $time = Irssi::settings_get_int('mail_refresh_time');
68   return if ($time == $last_refresh_time);
69
70   $last_refresh_time = $time;
71   Irssi::timeout_remove($refresh_tag) if ($refresh_tag);
72   $refresh_tag = Irssi::timeout_add($time*1000, 'refresh_mail', undef);
73 }
74
75 Irssi::settings_add_str('misc', 'mail_ext_program', '');
76 Irssi::settings_add_str('misc', 'mail_file', $ENV{'MAIL'});
77 Irssi::settings_add_int('misc', 'mail_refresh_time', 60);
78
79 Irssi::statusbar_item_register('mail', '{sb Mail: $0-}', 'mail');
80
81 read_settings();
82 Irssi::signal_add('setup changed', 'read_settings');
83 mbox_count(Irssi::settings_get_str('mail_file'));