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) = @_;
12 my ($response) = @_; # Plack callback
13 emit_mbox($response, $ctx, $srch);
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) = @_;
42 eval { require IO::Compress::Gzip };
43 return need_gzip($response) if $@;
45 # http://www.iana.org/assignments/media-types/application/gzip
46 # http://www.iana.org/assignments/media-types/application/mbox
47 my $fh = $response->([200, ['Content-Type' => 'application/gzip']]);
48 $fh = PublicInbox::MboxGz->new($fh);
50 require PublicInbox::GitCatFile;
51 require Email::Simple;
52 my $mid = mid_compressed($ctx->{mid});
53 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
54 my %opts = (offset => 0);
57 my $res = $srch->get_thread($mid, \%opts);
58 my $msgs = $res->{msgs};
60 while (defined(my $smsg = shift @$msgs)) {
62 my $p = 'HEAD:'.mid2path($smsg->mid);
63 Email::Simple->new($git->cat_file($p));
65 emit_msg($fh, $msg) if $msg;
75 my $fh = $_[0]->([501, ['Content-Type' => 'text/html']]);
76 my $title = 'gzipped mbox not available';
78 <html><head><title>$title</title><body><pre>$title
79 The administrator needs to install the IO::Compress::Gzip Perl module
80 to support gzipped mboxes.
81 <a href="../">Return to index</a></pre></body></html>
88 # fh may not be a proper IO, so we wrap the write and close methods
89 # to prevent IO::Compress::Gzip from complaining
90 package PublicInbox::MboxGz;
93 use fields qw(gz fh buf);
96 my ($class, $fh) = @_;
97 my $self = fields::new($class);
100 $self->{gz} = IO::Compress::Gzip->new(\$buf);
107 if (defined ${$self->{buf}}) {
108 $self->{fh}->write(${$self->{buf}});
109 ${$self->{buf}} = undef;
114 $_[0]->{gz}->write($_[1]);