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);
63 my $s = $mime->as_string;
65 local $ENV{GIT_AUTHOR_NAME} = $name;
66 local $ENV{GIT_AUTHOR_EMAIL} = $email;
67 local $ENV{GIT_AUTHOR_DATE} = $date;
69 # Ham messages are trained when they're marked into
70 # a SEEN state, so this is idempotent:
71 run([PublicInbox::MDA->cmd, $git_dir], \$s, \$out, \$err);
72 if ($err !~ /CONFLICT/) {
76 if (!run([qw(spamc -L), $train], \$in, @output)) {
81 require PublicInbox::SearchIdx;
82 umask 0022; # XXX FIXME use git config core.sharedRepository
83 my $s = PublicInbox::SearchIdx->new($git_dir, 2);