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;
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;
24 my $mime = Email::MIME->new(eval {
26 my $data = scalar <STDIN>;
27 $data =~ s/\AFrom [^\r\n]*\r?\n//s;
33 foreach my $h (qw(Cc To)) {
34 my $val = $mime->header($h) or next;
35 foreach my $email (PublicInbox::Address::emails($val)) {
36 $dests{lc($email)} = 1;
40 if ($train eq "ham") {
41 require PublicInbox::MDA;
42 require PublicInbox::Filter;
43 PublicInbox::Filter->run($mime);
47 my @output = qw(> /dev/null > /dev/null);
49 # n.b. message may be cross-posted to multiple public-inboxes
50 foreach my $recipient (keys %dests) {
51 my $dst = $pi_config->lookup($recipient) or next;
52 my $git_dir = $dst->{mainrepo} or next;
53 my ($out, $err) = ("", "");
54 my $git = PublicInbox::Git->new($git_dir);
55 # We do not touch GIT_COMMITTER_* env here so we can track
56 # who trained the message.
57 my $name = $ENV{GIT_COMMITTER_NAME} || $dst->{inbox};
58 my $email = $ENV{GIT_COMMITTER_EMAIL} || $recipient;
59 my $im = PublicInbox::Import->new($git, $name, $email);
61 if ($train eq "spam") {
62 # This needs to be idempotent, as my inotify trainer
63 # may train for each cross-posted message, and this
64 # script already learns for every list in
65 # ~/.public-inbox/config
67 } else { # $train eq "ham"
68 # no checking for spam here, we assume the message has
69 # been reviewed by a human at this point:
70 PublicInbox::MDA->set_list_headers($mime, $dst);
72 # Ham messages are trained when they're marked into
73 # a SEEN state, so this is idempotent:
77 my $in = $mime->as_string;
78 if (!run([qw(spamc -L), $train], \$in, @output)) {
83 require PublicInbox::SearchIdx;
84 PublicInbox::SearchIdx->new($git_dir, 2)->index_sync;