1 # Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # For retrieving attachments from messages in the WWW interface
5 package PublicInbox::WwwAttach; # internal package
8 use bytes (); # only for bytes::length
9 use Email::MIME::ContentType qw(parse_content_type);
10 use PublicInbox::MIME;
11 use PublicInbox::MsgIter;
13 sub get_attach_i { # msg_iter callback
14 my ($part, $depth, @idx) = @{$_[0]};
16 return if join('.', @idx) ne $res->[3]; # $idx
18 my $ct = $part->content_type;
19 $ct = parse_content_type($ct) if $ct;
21 # discrete == type, we remain Debian wheezy-compatible
22 if ($ct && (($ct->{discrete} || '') eq 'text')) {
23 # display all text as text/plain:
24 my $cset = $ct->{attributes}->{charset};
25 if ($cset && ($cset =~ /\A[a-zA-Z0-9_\-]+\z/)) {
26 $res->[1]->[1] .= qq(; charset=$cset);
28 } else { # TODO: allow user to configure safe types
29 $res->[1]->[1] = 'application/octet-stream';
32 push @{$res->[1]}, 'Content-Length', bytes::length($part);
33 $res->[2]->[0] = $part;
36 # /$LISTNAME/$MESSAGE_ID/$IDX-$FILENAME
37 sub get_attach ($$$) {
38 my ($ctx, $idx, $fn) = @_;
39 my $res = [ 404, [ 'Content-Type', 'text/plain' ], [ "Not found\n" ] ];
40 my $mime = $ctx->{-inbox}->msg_by_mid($ctx->{mid}) or return $res;
41 $mime = PublicInbox::MIME->new($mime);
43 msg_iter($mime, \&get_attach_i, $res, 1);
44 pop @$res; # cleanup before letting PSGI server see it