1 # Copyright (C) 2018-2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Unstable internal API.
5 # Used for on-the-fly duplicate detection in V2 inboxes.
6 # This is not stored in any database anywhere and may change
7 # as changes in duplicate detection are needed.
8 # See L<public-inbox-v2-format(5)> manpage for more details.
9 package PublicInbox::ContentId;
12 use base qw/Exporter/;
13 our @EXPORT_OK = qw/content_id content_digest/;
14 use PublicInbox::MID qw(mids references);
15 use PublicInbox::MsgIter;
17 # not sure if less-widely supported hash families are worth bothering with
20 sub digest_addr ($$$) {
21 my ($dig, $h, $v) = @_;
23 $v =~ s/@([a-z0-9\_\.\-\(\)]*([A-Z])\S*)/'@'.lc($1)/ge;
25 $dig->add("$h\0$v\0");
30 my ($part, $depth, @idx) = @{$_[0]};
31 $dig->add("\0$depth:".join('.', @idx)."\0");
32 my $fn = $part->filename;
35 $dig->add("fn\0$fn\0");
37 my @d = $part->header('Content-Description');
43 my $ct = $part->content_type || 'text/plain';
44 my ($s, undef) = msg_part_text($part, $ct);
55 sub content_digest ($) {
57 my $dig = Digest::SHA->new(256);
58 my $hdr = $mime->header_obj;
60 # References: and In-Reply-To: get used interchangeably
61 # in some "duplicates" in LKML. We treat them the same
62 # in SearchIdx, so treat them the same for this:
64 foreach my $mid (@{mids($hdr)}) {
65 # do NOT consider the Message-ID as part of the content_id
66 # if we got here, we've already got Message-ID reuse
69 foreach my $mid (@{references($hdr)}) {
71 $dig->add("ref\0$mid\0");
74 # Only use Sender: if From is not present
75 foreach my $h (qw(From Sender)) {
76 my @v = $hdr->header($h);
78 digest_addr($dig, $h, $_) foreach @v;
81 foreach my $h (qw(Subject Date)) {
82 my @v = $hdr->header($h);
85 $dig->add("$h\0$v\0");
88 # Some mail processors will add " to unquoted names that were
89 # not in the original message. For the purposes of deduplication,
90 # do not take it into account:
91 foreach my $h (qw(To Cc)) {
92 my @v = $hdr->header($h);
93 digest_addr($dig, $h, $_) foreach @v;
95 msg_iter($mime, \&content_dig_i, $dig);
100 content_digest($_[0])->digest;