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;
16 my $train = shift or die "usage: $usage\n";
17 if ($train !~ /\A(?:ham|spam)\z/) {
18 die "`$train' not recognized.\nusage: $usage\n";
21 my $pi_config = PublicInbox::Config->new;
22 my $mime = Email::MIME->new(eval {
24 my $data = scalar <STDIN>;
25 $data =~ s/\AFrom [^\r\n]*\r?\n//s;
31 foreach my $h (qw(Cc To)) {
32 foreach my $recipient (Email::Address->parse($mime->header($h))) {
33 $dests{lc($recipient->address)} = 1;
37 if ($train eq "ham") {
38 require PublicInbox::MDA;
39 require PublicInbox::Filter;
40 PublicInbox::Filter->run($mime);
44 my @output = qw(> /dev/null > /dev/null);
46 # n.b. message may be cross-posted to multiple public-inboxes
47 foreach my $recipient (keys %dests) {
48 my $dst = $pi_config->lookup($recipient) or next;
49 my $git_dir = $dst->{mainrepo} or next;
50 my ($out, $err) = ("", "");
51 my $git = PublicInbox::Git->new($git_dir);
52 # We do not touch GIT_COMMITTER_* env here so we can track
53 # who trained the message.
54 my $name = $ENV{GIT_COMMITTER_NAME} || $dst->{listname};
55 my $email = $ENV{GIT_COMMITTER_EMAIL} || $recipient;
56 my $im = PublicInbox::Import->new($git, $name, $email);
58 if ($train eq "spam") {
59 # This needs to be idempotent, as my inotify trainer
60 # may train for each cross-posted message, and this
61 # script already learns for every list in
62 # ~/.public-inbox/config
64 } else { # $train eq "ham"
65 # no checking for spam here, we assume the message has
66 # been reviewed by a human at this point:
67 PublicInbox::MDA->set_list_headers($mime, $dst);
69 # Ham messages are trained when they're marked into
70 # a SEEN state, so this is idempotent:
74 my $in = $mime->as_string;
75 if (!run([qw(spamc -L), $train], \$in, @output)) {
80 require PublicInbox::SearchIdx;
81 PublicInbox::SearchIdx->new($git_dir, 2)->index_sync;