2 # Copyright (C) 2014-2020 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|rm> </path/to/message";
10 use PublicInbox::Config;
11 use PublicInbox::InboxWritable;
13 use PublicInbox::Address;
14 use PublicInbox::Spamcheck::Spamc;
15 use Getopt::Long qw(:config gnu_getopt no_ignore_case auto_abbrev);
17 GetOptions(\%opt, 'all') or die "bad command-line args\n";
19 my $train = shift or die "usage: $usage\n";
20 if ($train !~ /\A(?:ham|spam|rm)\z/) {
21 die "`$train' not recognized.\nusage: $usage\n";
23 die "--all only works with `rm'\n" if $opt{all} && $train ne 'rm';
25 my $spamc = PublicInbox::Spamcheck::Spamc->new;
26 my $pi_config = PublicInbox::Config->new;
28 my $mime = PublicInbox::Eml->new(do{
31 $data =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
35 if ($train eq 'ham') {
36 $spamc->hamlearn(\$data);
37 } elsif ($train eq 'spam') {
38 $spamc->spamlearn(\$data);
40 die "spamc failed with: $?\n" if $?;
47 sub remove_or_add ($$$$) {
48 my ($ibx, $train, $mime, $addr) = @_;
50 # We do not touch GIT_COMMITTER_* env here so we can track
51 # who trained the message.
52 $ibx->{name} = $ENV{GIT_COMMITTER_NAME} // $ibx->{name};
53 $ibx->{-primary_address} = $ENV{GIT_COMMITTER_EMAIL} // $addr;
54 $ibx = PublicInbox::InboxWritable->new($ibx);
55 my $im = $ibx->importer(0);
58 # This needs to be idempotent, as my inotify trainer
59 # may train for each cross-posted message, and this
60 # script already learns for every list in
61 # ~/.public-inbox/config
62 $im->remove($mime, $train);
63 } elsif ($train eq "ham") {
64 # no checking for spam here, we assume the message has
65 # been reviewed by a human at this point:
66 PublicInbox::MDA->set_list_headers($mime, $ibx);
68 # Ham messages are trained when they're marked into
69 # a SEEN state, so this is idempotent:
75 # spam is removed from all known inboxes since it is often Bcc:-ed
76 if ($train eq 'spam' || ($train eq 'rm' && $opt{all})) {
77 $pi_config->each_inbox(sub {
79 $ibx = PublicInbox::InboxWritable->new($ibx);
80 my $im = $ibx->importer(0);
81 $im->remove($mime, $train);
85 require PublicInbox::MDA;
88 my %dests; # address => <PublicInbox::Inbox|0(false)>
89 for ($mime->header('Cc'), $mime->header('To')) {
90 foreach my $addr (PublicInbox::Address::emails($_)) {
92 $dests{$addr} //= $pi_config->lookup($addr) // 0;
96 # n.b. message may be cross-posted to multiple public-inboxes
98 while (my ($addr, $ibx) = each %dests) {
99 next unless ref($ibx); # $ibx may be 0
100 next if $seen{"$ibx"}++;
101 remove_or_add($ibx, $train, $mime, $addr);
103 my $dests = PublicInbox::MDA->inboxes_for_list_id($pi_config, $mime);
104 for my $ibx (@$dests) {
105 next if $seen{"$ibx"}++;
106 remove_or_add($ibx, $train, $mime, $ibx->{-primary_address});