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;
14 my $train = shift or die "usage: $usage\n";
15 if ($train !~ /\A(?:ham|spam)\z/) {
16 die "`$train' not recognized.\nusage: $usage\n";
19 my $pi_config = PublicInbox::Config->new;
20 my $mime = Email::MIME->new(eval {
22 my $data = scalar <STDIN>;
23 $data =~ s/\AFrom [^\r\n]*\r?\n//s;
29 foreach my $h (qw(Cc To)) {
30 foreach my $recipient (Email::Address->parse($mime->header($h))) {
31 $dests{lc($recipient->address)} = 1;
35 my ($name, $email, $date);
37 if ($train eq "ham") {
38 require PublicInbox::MDA;
39 require PublicInbox::Filter;
40 PublicInbox::Filter->run($mime);
41 ($name, $email, $date) = PublicInbox::MDA->author_info($mime);
44 my $in = $mime->as_string;
46 my @output = qw(> /dev/null > /dev/null);
48 # n.b. message may be cross-posted to multiple public-inboxes
49 foreach my $recipient (keys %dests) {
50 my $dst = $pi_config->lookup($recipient) or next;
51 my $git_dir = $dst->{mainrepo} or next;
52 my ($out, $err) = ("", "");
54 # We do not touch GIT_COMMITTER_* env here so we can track
55 # who trained the message.
56 # We will not touch GIT_AUTHOR_* when learning spam messages, either
57 if ($train eq "spam") {
58 # This needs to be idempotent, as my inotify trainer
59 # may train for each cross-posted message, and this
60 # script already learns for every list in
61 # ~/.public-inbox/config
62 if (!run(["ssoma-rm", $git_dir], \$in, \$out, \$err)) {
63 if ($err !~ /^git cat-file .+ failed: 32768$/) {
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);
71 my $s = $mime->as_string;
73 local $ENV{GIT_AUTHOR_NAME} = $name;
74 local $ENV{GIT_AUTHOR_EMAIL} = $email;
75 local $ENV{GIT_AUTHOR_DATE} = $date;
77 # Ham messages are trained when they're marked into
78 # a SEEN state, so this is idempotent:
79 run([PublicInbox::MDA->cmd, $git_dir], \$s, \$out, \$err);
80 if ($err !~ /CONFLICT/) {
84 if (!run([qw(spamc -L), $train], \$in, @output)) {
89 require PublicInbox::SearchIdx;
90 PublicInbox::SearchIdx->new($git_dir, 2)->index_sync;