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/;
11 my ($ctx, $srch, $sfx) = @_;
13 my ($response) = @_; # Plack callback
14 emit_mbox($response, $ctx, $srch, $sfx);
19 my $simple = Email::Simple->new(pop);
22 # single message should be easily renderable in browsers
23 my $fh = $response->([200, ['Content-Type'=>'text/plain']]);
24 emit_msg($fh, $simple);
29 my ($fh, $simple) = @_; # Email::Simple object
31 # drop potentially confusing headers, ssoma already should've dropped
32 # Lines and Content-Length
33 foreach my $d (qw(Lines Content-Length Status)) {
34 $simple->header_set($d);
37 my $buf = $simple->header_obj->as_string;
38 unless ($buf =~ /\AFrom /) {
39 $fh->write("From a\@a Thu Jan 1 00:00:00 1970\n");
41 $fh->write($buf .= $simple->crlf);
44 $simple->body_set('');
46 # mboxrd quoting style
47 # ref: http://www.qmail.org/man/man5/mbox.html
48 $buf =~ s/^(>*From )/>$1/gm;
50 $buf .= "\n" unless $buf =~ /\n\z/s;
56 my ($response, $ctx, $srch, $sfx) = @_;
59 eval { require IO::Compress::Gzip };
60 return need_gzip($response) if $@;
64 # http://www.iana.org/assignments/media-types/application/gzip
65 # http://www.iana.org/assignments/media-types/application/mbox
66 my $fh = $response->([200, ['Content-Type' => "application/$type"]]);
67 $fh = PublicInbox::MboxGz->new($fh) if $sfx;
69 require PublicInbox::GitCatFile;
70 my $mid = mid_compressed($ctx->{mid});
71 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
72 my %opts = (offset => 0);
75 my $res = $srch->get_thread($mid, \%opts);
76 my $msgs = $res->{msgs};
78 while (defined(my $smsg = shift @$msgs)) {
80 my $p = 'HEAD:'.mid2path($smsg->mid);
81 Email::Simple->new($git->cat_file($p));
83 emit_msg($fh, $msg) if $msg;
93 my $fh = $_[0]->([501, ['Content-Type' => 'text/html']]);
94 my $title = 'gzipped mbox not available';
96 <html><head><title>$title</title><body><pre>$title
97 The administrator needs to install the IO::Compress::Gzip Perl module
98 to support gzipped mboxes.
99 <a href="../">Return to index</a></pre></body></html>
106 # fh may not be a proper IO, so we wrap the write and close methods
107 # to prevent IO::Compress::Gzip from complaining
108 package PublicInbox::MboxGz;
111 use fields qw(gz fh buf);
114 my ($class, $fh) = @_;
115 my $self = fields::new($class);
117 $self->{buf} = \$buf;
118 $self->{gz} = IO::Compress::Gzip->new(\$buf);
125 if (defined ${$self->{buf}}) {
126 $self->{fh}->write(${$self->{buf}});
127 ${$self->{buf}} = undef;
132 $_[0]->{gz}->write($_[1]);