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