1 # Copyright (C) 2015-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::MboxGz;
5 use parent 'PublicInbox::GzipFilter';
7 use PublicInbox::Hval qw/to_filename/;
9 use PublicInbox::GitAsyncCat;
10 *msg_hdr = \&PublicInbox::Mbox::msg_hdr;
11 *msg_body = \&PublicInbox::Mbox::msg_body;
14 my ($class, $ctx, $cb) = @_;
15 $ctx->{base_url} = $ctx->{-inbox}->base_url($ctx->{env});
17 gz => PublicInbox::GzipFilter::gzip_or_die(),
23 # this is public-inbox-httpd-specific
24 sub mboxgz_blob_cb { # git->cat_async callback
25 my ($bref, $oid, $type, $size, $self) = @_;
26 my $http = $self->{ctx}->{env}->{'psgix.io'} or return; # client abort
27 my $smsg = delete $self->{smsg} or die 'BUG: no smsg';
29 # it's possible to have TOCTOU if an admin runs
30 # public-inbox-(edit|purge), just move onto the next message
31 return $http->next_step(\&async_next);
33 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
35 $self->zmore(msg_hdr($self->{ctx},
36 PublicInbox::Eml->new($bref)->header_obj,
39 # PublicInbox::HTTP::{Chunked,Identity}::write
40 $self->{http_out}->write($self->translate(msg_body($$bref)));
42 $http->next_step(\&async_next);
45 # this is public-inbox-httpd-specific
48 if (my $smsg = $self->{smsg} = $self->{cb}->($self->{ctx})) {
49 git_async_cat($self->{ctx}->{-inbox}->git, $smsg->{blob},
50 \&mboxgz_blob_cb, $self);
51 } elsif (my $out = delete $self->{http_out}) {
52 $out->write($self->zflush);
57 # called by PublicInbox::DS::write
59 my ($http) = @_; # PublicInbox::HTTP
60 async_step($http->{forward});
63 # called by PublicInbox::HTTP::close, or any other PSGI server
64 sub close { !!delete($_[0]->{http_out}) }
67 my ($class, $ctx, $cb, $fn) = @_;
68 my $self = $class->new($ctx, $cb);
69 # http://www.iana.org/assignments/media-types/application/gzip
70 $fn = defined($fn) && $fn ne '' ? to_filename($fn) : 'no-subject';
71 my $h = [ qw(Content-Type application/gzip),
72 'Content-Disposition', "inline; filename=$fn.mbox.gz" ];
73 if ($ctx->{env}->{'pi-httpd.async'}) {
75 my ($wcb) = @_; # -httpd provided write callback
76 $self->{http_out} = $wcb->([200, $h]);
77 $self->{ctx}->{env}->{'psgix.io'}->{forward} = $self;
78 async_step($self); # start stepping
80 } else { # generic PSGI
85 # called by Plack::Util::foreach or similar (generic PSGI)
88 my $ctx = $self->{ctx} or return;
89 while (my $smsg = $self->{cb}->($ctx)) {
90 my $mref = $ctx->{-inbox}->msg_by_smsg($smsg) or next;
91 my $h = PublicInbox::Eml->new($mref)->header_obj;
92 $self->zmore(msg_hdr($ctx, $h, $smsg->{mid}));
93 return $self->translate(msg_body($$mref));
95 # signal that we're done and can return undef next call: