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 mboxrd
4 package PublicInbox::Mbox;
7 use PublicInbox::MID qw/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);
30 my ($fh, $simple) = @_; # Email::Simple object
31 my $header_obj = $simple->header_obj;
33 # drop potentially confusing headers, ssoma already should've dropped
34 # Lines and Content-Length
35 foreach my $d (qw(Lines Content-Length Status)) {
36 $header_obj->header_set($d);
39 my $buf = $header_obj->as_string;
40 unless ($buf =~ /\AFrom /) {
41 $fh->write("From mboxrd\@z Thu Jan 1 00:00:00 1970\n");
43 $fh->write($buf .= $simple->crlf);
46 $simple->body_set('');
48 # mboxrd quoting style
49 # ref: http://www.qmail.org/man/man5/mbox.html
50 $buf =~ s/^(>*From )/>$1/gm;
52 $buf .= "\n" unless $buf =~ /\n\z/s;
58 my ($response, $ctx, $srch, $sfx) = @_;
61 eval { require IO::Compress::Gzip };
62 return need_gzip($response) if $@;
66 # http://www.iana.org/assignments/media-types/application/gzip
67 # http://www.iana.org/assignments/media-types/application/mbox
68 my $fh = $response->([200, ['Content-Type' => "application/$type"]]);
69 $fh = PublicInbox::MboxGz->new($fh) if $sfx;
71 require PublicInbox::GitCatFile;
72 my $mid = $ctx->{mid};
73 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
74 my %opts = (offset => 0);
77 my $res = $srch->get_thread($mid, \%opts);
78 my $msgs = $res->{msgs};
80 while (defined(my $smsg = shift @$msgs)) {
82 my $p = 'HEAD:'.mid2path($smsg->mid);
83 Email::Simple->new($git->cat_file($p));
85 emit_msg($fh, $msg) if $msg;
95 my $fh = $_[0]->([501, ['Content-Type' => 'text/html']]);
96 my $title = 'gzipped mbox not available';
98 <html><head><title>$title</title><body><pre>$title
99 The administrator needs to install the IO::Compress::Gzip Perl module
100 to support gzipped mboxes.
101 <a href="../">Return to index</a></pre></body></html>
108 # fh may not be a proper IO, so we wrap the write and close methods
109 # to prevent IO::Compress::Gzip from complaining
110 package PublicInbox::MboxGz;
113 use fields qw(gz fh buf);
116 my ($class, $fh) = @_;
117 my $self = fields::new($class);
119 $self->{buf} = \$buf;
120 $self->{gz} = IO::Compress::Gzip->new(\$buf);
127 if (defined ${$self->{buf}}) {
128 $self->{fh}->write(${$self->{buf}});
129 ${$self->{buf}} = undef;
134 $_[0]->{gz}->write($_[1]);