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;
13 use PublicInbox::MIME;
14 use Email::MIME::ContentType;
15 $Email::MIME::ContentType::STRICT_PARAMS = 0; # user input is imperfect
16 use PublicInbox::Address;
17 use PublicInbox::Spamcheck::Spamc;
18 my $train = shift or die "usage: $usage\n";
19 if ($train !~ /\A(?:ham|spam|rm)\z/) {
20 die "`$train' not recognized.\nusage: $usage\n";
23 my $spamc = PublicInbox::Spamcheck::Spamc->new;
24 my $pi_config = PublicInbox::Config->new;
26 my $mime = PublicInbox::MIME->new(eval {
28 my $data = scalar <STDIN>;
29 $data =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
33 if ($train eq 'ham') {
34 $spamc->hamlearn(\$data);
35 } elsif ($train eq 'spam') {
36 $spamc->spamlearn(\$data);
38 die "spamc failed with: $?\n" if $?;
47 foreach my $h (qw(Cc To)) {
48 my $val = $mime->header($h) or next;
49 foreach my $email (PublicInbox::Address::emails($val)) {
50 $dests{lc($email)} = 1;
54 if ($train eq 'spam') {
55 $pi_config->each_inbox(sub {
58 my $name = $ibx->{name};
59 my $addr = $ibx->{-primary_address};
60 my $im = PublicInbox::Import->new($git, $name, $addr, $ibx);
61 $im->remove($mime, 'spam');
66 require PublicInbox::MDA if $train eq "ham";
68 # n.b. message may be cross-posted to multiple public-inboxes
69 foreach my $recipient (keys %dests) {
70 my $dst = $pi_config->lookup($recipient) or next;
71 my $git_dir = $dst->{mainrepo} or next;
72 my $git = PublicInbox::Git->new($git_dir);
73 # We do not touch GIT_COMMITTER_* env here so we can track
74 # who trained the message.
75 my $name = $ENV{GIT_COMMITTER_NAME} || $dst->{name};
76 my $email = $ENV{GIT_COMMITTER_EMAIL} || $recipient;
77 my $im = PublicInbox::Import->new($git, $name, $email);
79 if ($train eq "spam" || $train eq "rm") {
80 # This needs to be idempotent, as my inotify trainer
81 # may train for each cross-posted message, and this
82 # script already learns for every list in
83 # ~/.public-inbox/config
84 $im->remove($mime, $train);
85 } else { # $train eq "ham"
86 # no checking for spam here, we assume the message has
87 # been reviewed by a human at this point:
88 PublicInbox::MDA->set_list_headers($mime, $dst);
90 # Ham messages are trained when they're marked into
91 # a SEEN state, so this is idempotent: