1 # Copyright (C) 2015, all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 # Streaming interface for formatting messages as an mbox
4 package PublicInbox::Mbox;
7 use PublicInbox::MID qw/mid_compressed mid2path/;
10 my ($ctx, $srch, $sfx) = @_;
12 my ($response) = @_; # Plack callback
13 emit_mbox($response, $ctx, $srch, $sfx);
18 my ($fh, $simple) = @_; # Email::Simple object
20 # drop potentially confusing headers, ssoma already should've dropped
21 # Lines and Content-Length
22 foreach my $d (qw(Lines Content-Length Status)) {
23 $simple->header_set($d);
26 my $buf = $simple->header_obj->as_string;
27 unless ($buf =~ /\AFrom /) {
28 $fh->write("From a\@a Thu Jan 1 00:00:00 1970\n");
30 $fh->write($buf .= $simple->crlf);
33 $simple->body_set('');
34 $buf =~ s/^(From )/>$1/gm;
35 $buf .= "\n" unless $buf =~ /\n\z/s;
41 my ($response, $ctx, $srch, $sfx) = @_;
44 eval { require IO::Compress::Gzip };
45 return need_gzip($response) if $@;
49 # http://www.iana.org/assignments/media-types/application/gzip
50 # http://www.iana.org/assignments/media-types/application/mbox
51 my $fh = $response->([200, ['Content-Type' => "application/$type"]]);
52 $fh = PublicInbox::MboxGz->new($fh) if $sfx;
54 require PublicInbox::GitCatFile;
55 require Email::Simple;
56 my $mid = mid_compressed($ctx->{mid});
57 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
58 my %opts = (offset => 0);
61 my $res = $srch->get_thread($mid, \%opts);
62 my $msgs = $res->{msgs};
64 while (defined(my $smsg = shift @$msgs)) {
66 my $p = 'HEAD:'.mid2path($smsg->mid);
67 Email::Simple->new($git->cat_file($p));
69 emit_msg($fh, $msg) if $msg;
79 my $fh = $_[0]->([501, ['Content-Type' => 'text/html']]);
80 my $title = 'gzipped mbox not available';
82 <html><head><title>$title</title><body><pre>$title
83 The administrator needs to install the IO::Compress::Gzip Perl module
84 to support gzipped mboxes.
85 <a href="../">Return to index</a></pre></body></html>
92 # fh may not be a proper IO, so we wrap the write and close methods
93 # to prevent IO::Compress::Gzip from complaining
94 package PublicInbox::MboxGz;
97 use fields qw(gz fh buf);
100 my ($class, $fh) = @_;
101 my $self = fields::new($class);
103 $self->{buf} = \$buf;
104 $self->{gz} = IO::Compress::Gzip->new(\$buf);
111 if (defined ${$self->{buf}}) {
112 $self->{fh}->write(${$self->{buf}});
113 ${$self->{buf}} = undef;
118 $_[0]->{gz}->write($_[1]);