2 # Copyright (C) 2014-2015 all contributors <meta@public-inbox.org>
3 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
5 # Used for training spam (via SpamAssassin) and removing messages from a
7 my $usage = "$0 (spam|ham) < /path/to/message";
10 use PublicInbox::Config;
12 use PublicInbox::Import;
14 use Email::MIME::ContentType;
15 $Email::MIME::ContentType::STRICT_PARAMS = 0; # user input is imperfect
16 use PublicInbox::Address;
17 use PublicInbox::Spawn qw(spawn);
18 my $train = shift or die "usage: $usage\n";
19 if ($train !~ /\A(?:ham|spam)\z/) {
20 die "`$train' not recognized.\nusage: $usage\n";
23 my $pi_config = PublicInbox::Config->new;
25 my $mime = Email::MIME->new(eval {
27 my $data = scalar <STDIN>;
28 $data =~ s/\AFrom [^\r\n]*\r?\n//s;
30 my @cmd = (qw(spamc -L), $train);
32 pipe($r, $w) or die "pipe failed: $!";
33 open my $null, '>', '/dev/null' or
34 die "failed to open /dev/null: $!";
35 my $nullfd = fileno($null);
36 my %rdr = (0 => fileno($r), 1 => $nullfd, 2 => $nullfd);
37 my $pid = spawn(\@cmd, undef, \%rdr);
39 close $r or die "close \$r failed: $!";
40 print $w $data or die "print \$w failed: $!";
41 close $w or die "close \$w failed: $!";
43 die "spamc failed with: $?\n" if $?;
51 foreach my $h (qw(Cc To)) {
52 my $val = $mime->header($h) or next;
53 foreach my $email (PublicInbox::Address::emails($val)) {
54 $dests{lc($email)} = 1;
58 if ($train eq "ham") {
59 require PublicInbox::MDA;
60 require PublicInbox::Filter;
61 PublicInbox::Filter->run($mime);
64 # n.b. message may be cross-posted to multiple public-inboxes
65 foreach my $recipient (keys %dests) {
66 my $dst = $pi_config->lookup($recipient) or next;
67 my $git_dir = $dst->{mainrepo} or next;
68 my $git = PublicInbox::Git->new($git_dir);
69 # We do not touch GIT_COMMITTER_* env here so we can track
70 # who trained the message.
71 my $name = $ENV{GIT_COMMITTER_NAME} || $dst->{inbox};
72 my $email = $ENV{GIT_COMMITTER_EMAIL} || $recipient;
73 my $im = PublicInbox::Import->new($git, $name, $email);
75 if ($train eq "spam") {
76 # This needs to be idempotent, as my inotify trainer
77 # may train for each cross-posted message, and this
78 # script already learns for every list in
79 # ~/.public-inbox/config
81 } else { # $train eq "ham"
82 # no checking for spam here, we assume the message has
83 # been reviewed by a human at this point:
84 PublicInbox::MDA->set_list_headers($mime, $dst);
86 # Ham messages are trained when they're marked into
87 # a SEEN state, so this is idempotent:
92 require PublicInbox::SearchIdx;
93 PublicInbox::SearchIdx->new($git_dir, 2)->index_sync;