]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/MboxGz.pm
treewide: "require" + "use" cleanup and docs
[public-inbox.git] / lib / PublicInbox / MboxGz.pm
1 # Copyright (C) 2015-2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::MboxGz;
4 use strict;
5 use warnings;
6 use Email::Simple;
7 use PublicInbox::Hval qw/to_filename/;
8 use PublicInbox::Mbox;
9 use Compress::Raw::Zlib qw(Z_FINISH Z_OK);
10 my %OPT = (-WindowBits => 15 + 16, -AppendOutput => 1);
11
12 sub new {
13         my ($class, $ctx, $cb) = @_;
14         $ctx->{base_url} = $ctx->{-inbox}->base_url($ctx->{env});
15         my ($gz, $err) = Compress::Raw::Zlib::Deflate->new(%OPT);
16         $err == Z_OK or die "Deflate->new failed: $err";
17         bless { gz => $gz, cb => $cb, ctx => $ctx }, $class;
18 }
19
20 sub response {
21         my ($class, $ctx, $cb, $fn) = @_;
22         my $body = $class->new($ctx, $cb);
23         # http://www.iana.org/assignments/media-types/application/gzip
24         my @h = qw(Content-Type application/gzip);
25         if (defined $fn && $fn ne '') {
26                 $fn = to_filename($fn);
27                 push @h, 'Content-Disposition', "inline; filename=$fn.mbox.gz";
28         }
29         [ 200, \@h, $body ];
30 }
31
32 sub gzip_fail ($$) {
33         my ($ctx, $err) = @_;
34         $ctx->{env}->{'psgi.errors'}->print("deflate failed: $err\n");
35         '';
36 }
37
38 # called by Plack::Util::foreach or similar
39 sub getline {
40         my ($self) = @_;
41         my $ctx = $self->{ctx} or return;
42         my $gz = $self->{gz};
43         my $buf = delete($self->{buf});
44         while (my $smsg = $self->{cb}->($ctx)) {
45                 my $mref = $ctx->{-inbox}->msg_by_smsg($smsg) or next;
46                 my $h = Email::Simple->new($mref)->header_obj;
47
48                 my $err = $gz->deflate(
49                         PublicInbox::Mbox::msg_hdr($ctx, $h, $smsg->{mid}),
50                         $buf);
51                 return gzip_fail($ctx, $err) if $err != Z_OK;
52
53                 $err = $gz->deflate(PublicInbox::Mbox::msg_body($$mref), $buf);
54                 return gzip_fail($ctx, $err) if $err != Z_OK;
55
56                 return $buf if length($buf) >= 8192;
57
58                 # be fair to other clients on public-inbox-httpd:
59                 $self->{buf} = $buf;
60                 return '';
61         }
62         # signal that we're done and can return undef next call:
63         delete $self->{ctx};
64         my $err = $gz->flush($buf, Z_FINISH);
65         ($err == Z_OK) ? $buf : gzip_fail($ctx, $err);
66 }
67
68 sub close {} # noop
69
70 1;