]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/MsgIter.pm
run update-copyrights from gnulib for 2019
[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 ($ct =~ m!\btext/plain\b!i || $ct =~ m!\bmultipart/mixed\b!i) {
49                 # Try to assume UTF-8 because Alpine seems to
50                 # do wacky things and set charset=X-UNKNOWN
51                 $part->charset_set('UTF-8');
52                 $s = eval { $part->body_str };
53
54                 # If forcing charset=UTF-8 failed,
55                 # caller will warn further down...
56                 $s = $part->body if $@;
57         }
58         ($s, $err);
59 }
60
61 1;