]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/MsgIter.pm
msgiter: attempt to decode all text/* bodies
[public-inbox.git] / lib / PublicInbox / MsgIter.pm
1 # Copyright (C) 2016-2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # read-only utilities for Email::MIME
5 package PublicInbox::MsgIter;
6 use strict;
7 use warnings;
8 use base qw(Exporter);
9 our @EXPORT = qw(msg_iter msg_part_text);
10 use PublicInbox::MIME;
11
12 # Like Email::MIME::walk_parts, but this is:
13 # * non-recursive
14 # * passes depth and indices to the iterator callback
15 sub msg_iter ($$) {
16         my ($mime, $cb) = @_;
17         my @parts = $mime->subparts;
18         if (@parts) {
19                 my $i = 0;
20                 @parts = map { [ $_, 1, ++$i ] } @parts;
21                 while (my $p = shift @parts) {
22                         my ($part, $depth, @idx) = @$p;
23                         my @sub = $part->subparts;
24                         if (@sub) {
25                                 $depth++;
26                                 $i = 0;
27                                 @sub = map { [ $_, $depth, @idx, ++$i ] } @sub;
28                                 @parts = (@sub, @parts);
29                         } else {
30                                 $cb->($p);
31                         }
32                 }
33         } else {
34                 $cb->([$mime, 0, 0]);
35         }
36 }
37
38 sub msg_part_text ($$) {
39         my ($part, $ct) = @_;
40
41         my $s = eval { $part->body_str };
42         my $err = $@;
43
44         # text/plain is the default, multipart/mixed happened a few
45         # times when it should not have been:
46         #   <87llgalspt.fsf@free.fr>
47         #   <200308111450.h7BEoOu20077@mail.osdl.org>
48         if ($err && ($ct =~ m!\btext/\b!i ||
49                         $ct =~ m!\bmultipart/mixed\b!i)) {
50                 my $cte = $part->header_raw('Content-Transfer-Encoding');
51                 if (defined($cte) && $cte =~ /\b7bit\b/i) {
52                         $s = $part->body;
53                         $err = undef if $s =~ /\A[[:ascii:]]+\z/s;
54                 } else {
55                         # Try to assume UTF-8 because Alpine seems to
56                         # do wacky things and set charset=X-UNKNOWN
57                         $part->charset_set('UTF-8');
58                         $s = eval { $part->body_str };
59                 }
60
61                 # If forcing charset=UTF-8 failed,
62                 # caller will warn further down...
63                 $s = $part->body if $@;
64         }
65         ($s, $err);
66 }
67
68 1;