]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WwwAttach.pm
5b2914b393fdcc28ea3d220eeac3137004ae3b8d
[public-inbox.git] / lib / PublicInbox / WwwAttach.pm
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>
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 bytes (); # only for bytes::length
9 use Email::MIME::ContentType qw(parse_content_type);
10 use PublicInbox::Eml;
11
12 sub get_attach_i { # ->each_part callback
13         my ($part, $depth, $idx) = @{$_[0]};
14         my $res = $_[1];
15         return if $idx ne $res->[3]; # [0-9]+(?:\.[0-9]+)+
16         $res->[0] = 200;
17         my $ct = $part->content_type;
18         $ct = parse_content_type($ct) if $ct;
19
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);
26                 }
27         } else { # TODO: allow user to configure safe types
28                 $res->[1]->[1] = 'application/octet-stream';
29         }
30         $part = $part->body;
31         push @{$res->[1]}, 'Content-Length', bytes::length($part);
32         $res->[2]->[0] = $part;
33 }
34
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);
41         $res->[3] = $idx;
42         $mime->each_part(\&get_attach_i, $res, 1);
43         pop @$res; # cleanup before letting PSGI server see it
44         $res
45 }
46
47 1;