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 PublicInbox::EmlContentFoo qw(parse_content_type);
12 sub get_attach_i { # ->each_part callback
13 my ($part, $depth, $idx) = @{$_[0]};
15 return if $idx ne $res->[3]; # [0-9]+(?:\.[0-9]+)+
17 my $ct = $part->content_type;
18 $ct = parse_content_type($ct) if $ct;
20 # discrete == type, we remain Debian wheezy-compatible
21 if ($ct && (($ct->{discrete} || '') eq 'text')) {
22 # display all text as text/plain:
23 my $cset = $ct->{attributes}->{charset};
24 if ($cset && ($cset =~ /\A[a-zA-Z0-9_\-]+\z/)) {
25 $res->[1]->[1] .= qq(; charset=$cset);
27 } else { # TODO: allow user to configure safe types
28 $res->[1]->[1] = 'application/octet-stream';
31 push @{$res->[1]}, 'Content-Length', bytes::length($part);
32 $res->[2]->[0] = $part;
35 # /$LISTNAME/$MESSAGE_ID/$IDX-$FILENAME
36 sub get_attach ($$$) {
37 my ($ctx, $idx, $fn) = @_;
38 my $res = [ 404, [ 'Content-Type', 'text/plain' ], [ "Not found\n" ] ];
39 my $mime = $ctx->{-inbox}->msg_by_mid($ctx->{mid}) or return $res;
40 $mime = PublicInbox::Eml->new($mime);
42 $mime->each_part(\&get_attach_i, $res, 1);
43 pop @$res; # cleanup before letting PSGI server see it