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('');
45 $buf =~ s/^(From )/>$1/gm;
46 $buf .= "\n" unless $buf =~ /\n\z/s;
52 my ($response, $ctx, $srch, $sfx) = @_;
55 eval { require IO::Compress::Gzip };
56 return need_gzip($response) if $@;
60 # http://www.iana.org/assignments/media-types/application/gzip
61 # http://www.iana.org/assignments/media-types/application/mbox
62 my $fh = $response->([200, ['Content-Type' => "application/$type"]]);
63 $fh = PublicInbox::MboxGz->new($fh) if $sfx;
65 require PublicInbox::GitCatFile;
66 my $mid = mid_compressed($ctx->{mid});
67 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
68 my %opts = (offset => 0);
71 my $res = $srch->get_thread($mid, \%opts);
72 my $msgs = $res->{msgs};
74 while (defined(my $smsg = shift @$msgs)) {
76 my $p = 'HEAD:'.mid2path($smsg->mid);
77 Email::Simple->new($git->cat_file($p));
79 emit_msg($fh, $msg) if $msg;
89 my $fh = $_[0]->([501, ['Content-Type' => 'text/html']]);
90 my $title = 'gzipped mbox not available';
92 <html><head><title>$title</title><body><pre>$title
93 The administrator needs to install the IO::Compress::Gzip Perl module
94 to support gzipped mboxes.
95 <a href="../">Return to index</a></pre></body></html>
102 # fh may not be a proper IO, so we wrap the write and close methods
103 # to prevent IO::Compress::Gzip from complaining
104 package PublicInbox::MboxGz;
107 use fields qw(gz fh buf);
110 my ($class, $fh) = @_;
111 my $self = fields::new($class);
113 $self->{buf} = \$buf;
114 $self->{gz} = IO::Compress::Gzip->new(\$buf);
121 if (defined ${$self->{buf}}) {
122 $self->{fh}->write(${$self->{buf}});
123 ${$self->{buf}} = undef;
128 $_[0]->{gz}->write($_[1]);