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 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)\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 = Email::MIME->new(eval {
28 my $data = scalar <STDIN>;
29 $data =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
31 if ($train eq 'ham') {
32 $spamc->hamlearn(\$data);
34 $spamc->spamlearn(\$data);
36 die "spamc failed with: $?\n" if $?;
44 foreach my $h (qw(Cc To)) {
45 my $val = $mime->header($h) or next;
46 foreach my $email (PublicInbox::Address::emails($val)) {
47 $dests{lc($email)} = 1;
51 require PublicInbox::MDA if $train eq "ham";
53 # n.b. message may be cross-posted to multiple public-inboxes
54 foreach my $recipient (keys %dests) {
55 my $dst = $pi_config->lookup($recipient) or next;
56 my $git_dir = $dst->{mainrepo} or next;
57 my $git = PublicInbox::Git->new($git_dir);
58 # We do not touch GIT_COMMITTER_* env here so we can track
59 # who trained the message.
60 my $name = $ENV{GIT_COMMITTER_NAME} || $dst->{inbox};
61 my $email = $ENV{GIT_COMMITTER_EMAIL} || $recipient;
62 my $im = PublicInbox::Import->new($git, $name, $email);
64 if ($train eq "spam") {
65 # This needs to be idempotent, as my inotify trainer
66 # may train for each cross-posted message, and this
67 # script already learns for every list in
68 # ~/.public-inbox/config
70 } else { # $train eq "ham"
71 # no checking for spam here, we assume the message has
72 # been reviewed by a human at this point:
73 PublicInbox::MDA->set_list_headers($mime, $dst);
75 # Ham messages are trained when they're marked into
76 # a SEEN state, so this is idempotent: