]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WwwAttach.pm
use PublicInbox::MIME consistently
[public-inbox.git] / lib / PublicInbox / WwwAttach.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 # For retrieving attachments from messages in the WWW interface
5 package PublicInbox::WwwAttach; # internal package
6 use strict;
7 use warnings;
8 use Email::MIME::ContentType qw(parse_content_type);
9 use PublicInbox::MIME;
10 use PublicInbox::MsgIter;
11
12 # /$LISTNAME/$MESSAGE_ID/$IDX-$FILENAME
13 sub get_attach ($$$) {
14         my ($ctx, $idx, $fn) = @_;
15         my $res = [ 404, [ 'Content-Type', 'text/plain' ], [ "Not found\n" ] ];
16         my $mime = $ctx->{-inbox}->msg_by_mid($ctx->{mid}) or return $res;
17         $mime = PublicInbox::MIME->new($mime);
18         msg_iter($mime, sub {
19                 my ($part, $depth, @idx) = @{$_[0]};
20                 return if join('.', @idx) ne $idx;
21                 $res->[0] = 200;
22                 my $ct = $part->content_type;
23                 $ct = parse_content_type($ct) if $ct;
24
25                 # discrete == type, we remain Debian wheezy-compatible
26                 if ($ct && (($ct->{discrete} || '') eq 'text')) {
27                         # display all text as text/plain:
28                         my $cset = $ct->{attributes}->{charset};
29                         if ($cset && ($cset =~ /\A[\w-]+\z/)) {
30                                 $res->[1]->[1] .= qq(; charset=$cset);
31                         }
32                 } else { # TODO: allow user to configure safe types
33                         $res->[1]->[1] = 'application/octet-stream';
34                 }
35                 $part = $part->body;
36                 push @{$res->[1]}, 'Content-Length', bytes::length($part);
37                 $res->[2]->[0] = $part;
38         });
39         $res;
40 }
41
42 1;