]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/MboxGz.pm
mbox: split mboxgz out into a separate file
[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
11 sub new {
12         my ($class, $ctx, $cb) = @_;
13         my $buf = '';
14         $ctx->{base_url} = $ctx->{-inbox}->base_url($ctx->{env});
15         bless {
16                 buf => \$buf,
17                 gz => IO::Compress::Gzip->new(\$buf, Time => 0),
18                 cb => $cb,
19                 ctx => $ctx,
20         }, $class;
21 }
22
23 sub response {
24         my ($class, $ctx, $cb, $fn) = @_;
25         my $body = $class->new($ctx, $cb);
26         # http://www.iana.org/assignments/media-types/application/gzip
27         my @h = qw(Content-Type application/gzip);
28         if ($fn) {
29                 $fn = to_filename($fn);
30                 push @h, 'Content-Disposition', "inline; filename=$fn.mbox.gz";
31         }
32         [ 200, \@h, $body ];
33 }
34
35 # called by Plack::Util::foreach or similar
36 sub getline {
37         my ($self) = @_;
38         my $ctx = $self->{ctx} or return;
39         my $gz = $self->{gz};
40         while (my $smsg = $self->{cb}->()) {
41                 my $mref = $ctx->{-inbox}->msg_by_smsg($smsg) or next;
42                 my $h = Email::Simple->new($mref)->header_obj;
43                 $gz->write(PublicInbox::Mbox::msg_hdr($ctx, $h, $smsg->{mid}));
44                 $gz->write(PublicInbox::Mbox::msg_body($$mref));
45
46                 my $bref = $self->{buf};
47                 if (length($$bref) >= 8192) {
48                         my $ret = $$bref; # copy :<
49                         ${$self->{buf}} = '';
50                         return $ret;
51                 }
52
53                 # be fair to other clients on public-inbox-httpd:
54                 return '';
55         }
56         delete($self->{gz})->close;
57         # signal that we're done and can return undef next call:
58         delete $self->{ctx};
59         ${delete $self->{buf}};
60 }
61
62 sub close {} # noop
63
64 1;