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