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_clean mid_compressed mid2path/;
8 use Fcntl qw(SEEK_SET);
11 my ($ctx, $srch) = @_;
13 my ($response) = @_; # Plack callback
14 emit_mbox($response, $ctx, $srch);
19 my ($fh, $simple) = @_; # Email::Simple object
21 # drop potentially confusing headers, ssoma already should've dropped
22 # Lines and Content-Length
23 foreach my $d (qw(Lines Content-Length Status)) {
24 $simple->header_set($d);
27 my $buf = $simple->header_obj->as_string;
28 unless ($buf =~ /\AFrom /) {
29 $fh->write("From a\@a Thu Jan 1 00:00:00 1970\n");
31 $fh->write($buf .= $simple->crlf);
34 $simple->body_set('');
35 $buf =~ s/^(From )/>$1/gm;
36 $buf .= "\n" unless $buf =~ /\n\z/s;
42 my ($response, $ctx, $srch) = @_;
43 eval { require IO::Compress::Gzip };
44 return need_gzip($response) if $@;
46 # http://www.iana.org/assignments/media-types/application/gzip
47 # http://www.iana.org/assignments/media-types/application/mbox
48 my $fh = $response->([200, ['Content-Type' => 'application/gzip']]);
49 $fh = PublicInbox::MboxGz->new($fh);
51 require PublicInbox::GitCatFile;
52 require Email::Simple;
53 my $mid = mid_compressed($ctx->{mid});
54 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
55 my %opts = (offset => 0);
58 my $res = $srch->get_thread($mid, \%opts);
59 my $msgs = $res->{msgs};
61 while (defined(my $smsg = shift @$msgs)) {
63 my $p = 'HEAD:'.mid2path($smsg->mid);
64 Email::Simple->new($git->cat_file($p));
66 emit_msg($fh, $msg) if $msg;
76 my $fh = $_[0]->([501, ['Content-Type' => 'text/html']]);
77 my $title = 'gzipped mbox not available';
79 <html><head><title>$title</title><body><pre>$title
80 The administrator needs to install the IO::Compress::Gzip Perl module
81 to support gzipped mboxes.
82 <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]);
122 # do not actually close $fh