2 # Copyright (C) 2014, Eric Wong <normalperson@yhbt.net> and all contributors
3 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
4 my $usage = "$0 (spam|ham) < /path/to/message";
7 use PublicInbox::Config;
11 my $train = shift or die "usage: $usage\n";
12 if ($train !~ /\A(?:ham|spam)\z/) {
13 die "`$train' not recognized.\nusage: $usage\n";
16 my $pi_config = PublicInbox::Config->new;
17 my $mime = Email::MIME->new(eval { local $/; <> });
21 foreach my $h (qw(Cc To)) {
22 foreach my $recipient (Email::Address->parse($mime->header($h))) {
23 $dests{lc($recipient->address)} = 1;
27 my ($name, $email, $date);
29 if ($train eq "ham") {
30 require PublicInbox::MDA;
31 require PublicInbox::Filter;
32 PublicInbox::Filter->run($mime);
33 ($name, $email, $date) = PublicInbox::MDA->author_info($mime);
36 my $in = $mime->as_string;
38 my @output = qw(> /dev/null > /dev/null);
40 # n.b. message may be cross-posted to multiple public-inboxes
41 foreach my $recipient (keys %dests) {
42 my $dst = $pi_config->lookup($recipient) or next;
43 my $git_dir = $dst->{mainrepo} or next;
44 my ($out, $err) = ("", "");
46 # We do not touch GIT_COMMITTER_* env here so we can track
47 # who trained the message.
48 # We will not touch GIT_AUTHOR_* when learning spam messages, either
49 if ($train eq "spam") {
50 # This needs to be idempotent, as my inotify trainer
51 # may train for each cross-posted message, and this
52 # script already learns for every list in
53 # ~/.public-inbox/config
54 if (!run(["ssoma-rm", $git_dir], \$in, \$out, \$err)) {
55 if ($err !~ /^git cat-file .+ failed: 32768$/) {
59 } else { # $train eq "ham"
60 # no checking for spam here, we assume the message has
61 # been reviewed by a human at this point:
62 PublicInbox::MDA->set_list_headers($mime, $dst);
64 local $ENV{GIT_AUTHOR_NAME} = $name;
65 local $ENV{GIT_AUTHOR_EMAIL} = $email;
66 local $ENV{GIT_AUTHOR_DATE} = $date;
68 # Ham messages are trained when they're marked into
69 # a SEEN state, so this is idempotent:
70 run([PublicInbox::MDA->cmd, $git_dir], \$in, \$out, \$err);
71 if ($err !~ /CONFLICT/) {
75 if (!run([qw(spamc -L), $train], \$in, @output)) {