2 # Copyright (C) 2014-2018 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <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;
13 use PublicInbox::MIME;
14 use PublicInbox::Address;
15 use PublicInbox::Spamcheck::Spamc;
16 my $train = shift or die "usage: $usage\n";
17 if ($train !~ /\A(?:ham|spam|rm)\z/) {
18 die "`$train' not recognized.\nusage: $usage\n";
21 my $spamc = PublicInbox::Spamcheck::Spamc->new;
22 my $pi_config = PublicInbox::Config->new;
24 my $mime = PublicInbox::MIME->new(eval {
26 my $data = scalar <STDIN>;
27 $data =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
31 if ($train eq 'ham') {
32 $spamc->hamlearn(\$data);
33 } elsif ($train eq 'spam') {
34 $spamc->spamlearn(\$data);
36 die "spamc failed with: $?\n" if $?;
45 foreach my $h (qw(Cc To)) {
46 my $val = $mime->header($h) or next;
47 foreach my $email (PublicInbox::Address::emails($val)) {
48 $dests{lc($email)} = 1;
52 if ($train eq 'spam') {
53 $pi_config->each_inbox(sub {
56 my $name = $ibx->{name};
57 my $addr = $ibx->{-primary_address};
58 my $im = PublicInbox::Import->new($git, $name, $addr, $ibx);
59 $im->remove($mime, 'spam');
64 require PublicInbox::MDA if $train eq "ham";
66 # n.b. message may be cross-posted to multiple public-inboxes
67 foreach my $recipient (keys %dests) {
68 my $dst = $pi_config->lookup($recipient) or next;
69 my $git_dir = $dst->{mainrepo} or next;
70 my $git = PublicInbox::Git->new($git_dir);
71 # We do not touch GIT_COMMITTER_* env here so we can track
72 # who trained the message.
73 my $name = $ENV{GIT_COMMITTER_NAME} || $dst->{name};
74 my $email = $ENV{GIT_COMMITTER_EMAIL} || $recipient;
75 my $im = PublicInbox::Import->new($git, $name, $email);
77 if ($train eq "spam" || $train eq "rm") {
78 # This needs to be idempotent, as my inotify trainer
79 # may train for each cross-posted message, and this
80 # script already learns for every list in
81 # ~/.public-inbox/config
82 $im->remove($mime, $train);
83 } else { # $train eq "ham"
84 # no checking for spam here, we assume the message has
85 # been reviewed by a human at this point:
86 PublicInbox::MDA->set_list_headers($mime, $dst);
88 # Ham messages are trained when they're marked into
89 # a SEEN state, so this is idempotent: