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