summaryrefslogtreecommitdiffstats
path: root/scripts/procmaillog.pl
blob: 34fda3202a5b1c3aee8b36d19fd5364bb6800124 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use strict;
use Irssi;

use Encode qw(decode);
use IO::Handle;
use Log::Procmail;
use MIME::Words qw(decode_mimewords);
use Time::HiRes qw(usleep);

our $VERSION = '2.02';
our %IRSSI = (
    authors     => 'Cyprien Debu',
    contact     => 'frey@notk.org',
    name        => 'procmaillog',
    description => 'Gets new mails from procmail.log file',
    license     => 'Public Domain',
    url         => '',
    changed     => '06-2014'
);

my $sn = $IRSSI{name};

Irssi::settings_add_level $sn, $sn.'_default_level', 'MSGS';
Irssi::settings_add_int   $sn, $sn.'_folder_pad', 15;
Irssi::settings_add_str   $sn, $sn.'_folders_color', '4,^error$';
Irssi::settings_add_str   $sn, $sn.'_folders_level', '';
Irssi::settings_add_str   $sn, $sn.'_folders_silent', 'spam';
Irssi::settings_add_str   $sn, $sn.'_logfile', '~/.procmail.log';
Irssi::settings_add_int   $sn, $sn.'_max_length', 90;
Irssi::settings_add_str   $sn, $sn.'_split_chars', ',;';
Irssi::settings_add_str   $sn, $sn.'_window', '(status)';

Irssi::theme_register([
    $sn.'_mail', '$0',
    $sn.'_crap', '{line_start}{hilight '.$sn.':} $0'
]);

sub print_help
{
  print( <<EOF

This script reads your procmail.log file and prints it in the form:
| folder-name | subject

Many options are available, see /set ${sn}:
- default_level: default level of printed messages
- folder_pad: padding added to the folder name if length(folder name) < folder_pad
- folders_color: semicolon-separated list of pairs of <color, regex>: the folders that match the regex will be colorized following the codes listed here: http://irssi.org/documentation/formats (mIRC colors)
  Example: 5,foo;8,bar -> colorize foo in red and bar in yellow
- folders_level: same behaviour as folders_color but with levels instead of color numbers. NOTICES,foo will print folders matching foo with a NOTICES level
- folders_silent: regex, folders you don't want to print
- logfile: path to your procmail.log (default: ~/.procmail.log)
- max_length: max length of the line
- split_chars: ,; by default, split characters used in folders_color and folders_level strings
  Change them if you use these characters in your folders names
- window: the target window name

Available subcommands: help, start, stop.

The script may fail at first launch if it doesn't find your procmail.log file, just set the option and do /${sn} start.
EOF
  );
}

my $child;

sub print_crap
{
  Irssi::printformat MSGLEVEL_CLIENTCRAP, $sn.'_crap', $_
    foreach @_;
}

sub print_error
{
  print_crap "\x034Error:\x03 ".shift, @_;
}

# Utility function to parse folders_color and folders_level options.
sub parse_option
{
  my $setting = shift;
  my ($s2, $s1) = split '', Irssi::settings_get_str($sn.'_split_chars');
  my %hash;

  foreach (split $s1, Irssi::settings_get_str($setting)) {
    my ($key, $rx) = split $s2;
    $hash{$key} = $rx if $rx;
  }

  return %hash;
}

sub colorize_folder
{
  my $folder = shift;
  my $border = "\x03";
  my %folders = parse_option $sn.'_folders_color';

  foreach (keys %folders) {
    return $border.$_.$folder.$border if ($folder =~ /$folders{$_}/);
  }

  $border = "\x02";
  return $border.$folder.$border;
}

sub format_folder
{
  my $folder = shift;
  my $folder_pad = Irssi::settings_get_int $sn.'_folder_pad';
  my $pad = $folder_pad - length $folder;
  my $padding = $pad > 0 ? ' ' x $pad : '';
  return colorize_folder($folder).$padding;
}

# Used in format_subject
sub decode_mime
{
  my $str = shift;
  my $decoded;

  foreach (decode_mimewords $str) {
    $decoded .= decode $_->[1] || 'US-ASCII',  $_->[0];
  }

  return $decoded;
}

sub format_subject
{
  my $str = shift;

  if (index($str, '=?') == -1)
  { # If no MIME encoding, choose between utf8 and latin-1
    my $utf8 = 0;

    foreach (split '', $str) {
      $utf8 = 1 if (ord == 0xc2 or ord == 0xc3);
    }

    $str = decode('ISO-8859-1', $str) unless $utf8;

    return $str;
  }

  my $tmp = substr $str, rindex($str, '=?');

  if (index($tmp, '?=') == -1)
  {
    if (not $tmp =~ /=\?[a-z0-9_-]+\?[bq]\?/i)
    { # Encoding pattern not complete
      $str = substr $str, 0, rindex($str, '=?');
    }
    elsif (my ($c) = ($tmp =~ /=\?\S+\?([bq])\?/i))
    { # Encoding complete, lacks '?=' or just '='
      if ($c =~ /q/i and index($str, '=', length($str)-2) != -1)
      { # Remove trailing '=' (beginning of new special character)
        $str = substr $str, 0, index($str, '=', length($str)-2)
      }
      $str .= ($str =~ /\?$/) ? '=' : '?=';
    }
  }

  eval { $str = decode_mime $str };

  if ($@) {
    chomp $@;
    print_error "Error while decoding subject: $@";
    $str = "\x034(error)\x03 " . $str;
  }

  return $str;
}

# Get the print level from folder name
sub get_level
{
  my $folder = shift;

  my $level = Irssi::settings_get_level $sn.'_default_level';
  return $level unless $folder;

  my %levels = parse_option $sn.'_folders_level';

  foreach (keys %levels) {
    $level = Irssi::level2bits $_ if ($folder =~ /$levels{$_}/);
  }

  return $level;
}

# Find the right window, build and print the line
sub printfmt
{
  my ($raw_folder, $raw_subject) = @_;

  my $level   = get_level      $raw_folder;
  my $folder  = format_folder  $raw_folder;
  my $subject = format_subject $raw_subject;

  my $line = "| $folder | $subject";
  my $max_length = Irssi::settings_get_int $sn.'_max_length';
  $line = substr($line, 0, $max_length) if ($max_length > 0);

  my $win_name = Irssi::settings_get_str $sn.'_window';
  my $window = Irssi::window_find_item $win_name;

  unless ($window) {
    print_error "Could not find window '$win_name'. Stopping.", "Please set ${sn}_window.";
    do_stop();
    return;
  }

  $window->printformat($level, $sn.'_mail', $line);
}

# Main loop
sub read_log
{
  my $args = shift;
  my ($log, $tagref) = @$args;

  my $rec = $log->next;

  unless ($rec) {
    if (defined $child) {
      # If $child is still running, we just got called too early
      # (the record is not fully written)
      return if (system("kill -0 $child &>/dev/null") == 0);

      # Our child was killed by something external
      print_error "Child killed. Stopping.";
      undef $child;
    }
    # Child killed, close the pipe
    Irssi::input_remove $$tagref;
    return;
  }

  my $folders_silent = Irssi::settings_get_str $sn.'_folders_silent';

  # We can get several mails in a row
  # Double braces to use next in a do-while loop
  do {{
    unless (ref $rec) {
      # If $rec is not a ref it is an error string
      printfmt "error", $rec;
      next;
    }
    next if ($folders_silent and $rec->folder =~ /$folders_silent/);
    printfmt $rec->folder, $rec->subject;
  }} while ($rec = $log->next);
}

sub do_start
{
  my $filename = Irssi::settings_get_str $sn.'_logfile';
  my ($logfile, @rest) = glob $filename;

  if ($#rest != -1) {
    print_crap "I found several files with the given filename ($filename).",
        "I will use $logfile.";
  }

  unless (-f $logfile and -r $logfile) {
    print_error "Could not find $filename, or file not readable.",
        "See /set ${sn}_logfile.";
    return;
  }

  my $log = Log::Procmail->new;
  my $wh = IO::Handle->new;

  pipe $log->fh, $wh;

  $log->errors(1);

  $log->fh->blocking(0);
  $wh->autoflush(1);

  $child = fork;

  if (not defined $child) {
    print_error "Can't fork. Aborting.";
    return;
  }

  if ($child > 0) { # parent
    Irssi::pidwait_add $child;
    my $tag;
    my @args = ($log, \$tag);
    $tag = Irssi::input_add fileno($log->fh), Irssi::INPUT_READ, \&read_log, \@args;
    return $logfile;
  } else { # child
    open STDOUT, '>&', $wh;
    open STDERR, '>&', $wh;
    exec qw(tail -fn0), $logfile;
  }
}

sub do_stop
{
  qx(kill $child);
  undef $child;
}

sub cmd_start
{
  if (defined $child) {
    print_crap "Already started, restarting...";
    do_stop();
    Irssi::timeout_add_once 200, \&cmd_start, undef;
    return;
  }

  my $win_name = Irssi::settings_get_str $sn.'_window';
  my $window = Irssi::window_find_item $win_name;

  unless ($window) {
    print_error "Could not find window '$win_name'. Aborting.", "Please set ${sn}_window.";
    return;
  }

  if (my $file = do_start) {
    print_crap "Started on window '$win_name' and file '$file'.";
  }
}

sub cmd_stop
{
  unless (defined $child) {
    print_crap "Not running.";
    return;
  }

  do_stop();
  print_crap "Stopped.";
}

sub UNLOAD
{
  do_stop() if $child;
}

# Subcommands handler
Irssi::command_bind $sn, sub {
  my ($data, $server, $item) = @_;
  $data =~ s/\s+$//g;
  Irssi::command_runsub $sn, $data, $server, $item;
};

# Subcommands
Irssi::command_bind "$sn help",  \&print_help;
Irssi::command_bind "$sn start", \&cmd_start;
Irssi::command_bind "$sn stop",  \&cmd_stop;

# Help command handler
Irssi::command_bind 'help', sub {
  $_[0] =~ s/\s+$//g;
  return unless $_[0] eq $sn;
  print_help;
  Irssi::signal_stop;
};

# Timeout here to print our message after the loading notice
Irssi::timeout_add_once 200, \&cmd_start, undef;