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