]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Mbox.pm
mbox: use Email::Simple->new to do in-place modifications
[public-inbox.git] / lib / PublicInbox / Mbox.pm
1 # Copyright (C) 2015-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Streaming (via getline) interface for formatting messages as an mboxrd.
5 # Used by the PSGI web interface.
6 #
7 # public-inbox-httpd favors "getline" response bodies to take a
8 # "pull"-based approach to feeding slow clients (as opposed to a
9 # more common "push" model)
10 package PublicInbox::Mbox;
11 use strict;
12 use warnings;
13 use PublicInbox::MID qw/mid_clean mid_escape/;
14 use PublicInbox::Hval qw/to_filename/;
15 use Email::Simple;
16 use Email::MIME::Encode;
17
18 sub subject_fn ($) {
19         my ($simple) = @_;
20         my $fn = $simple->header('Subject');
21         return 'no-subject' unless defined($fn);
22
23         # no need for full Email::MIME, here
24         if ($fn =~ /=\?/) {
25                 eval { $fn = Encode::decode('MIME-Header', $fn) };
26                 $fn = 'no-subject' if $@;
27         }
28         $fn =~ s/^re:\s+//i;
29         $fn = to_filename($fn);
30         $fn eq '' ? 'no-subject' : $fn;
31 }
32
33 sub mb_stream {
34         my ($more) = @_;
35         bless $more, 'PublicInbox::Mbox';
36 }
37
38 # called by PSGI server as body response
39 sub getline {
40         my ($more) = @_; # self
41         my ($ctx, $id, $prev, $next, $cur, $mref) = @$more;
42         if ($mref) { # first
43                 pop @$more;
44                 pop @$more;
45                 return msg_str($ctx, $cur, $mref);
46         }
47         $cur = $next or return;
48         my $ibx = $ctx->{-inbox};
49         $next = $ibx->over->next_by_mid($ctx->{mid}, \$id, \$prev);
50         @$more = ($ctx, $id, $prev, $next); # $next may be undef, here
51         $mref = $ibx->msg_by_smsg($cur) or return;
52         msg_str($ctx, Email::Simple->new($mref), $mref);
53 }
54
55 sub close {} # noop
56
57 sub emit_raw {
58         my ($ctx) = @_;
59         my $mid = $ctx->{mid};
60         my $ibx = $ctx->{-inbox};
61         my ($first, $mref, $more);
62         if (my $over = $ibx->over) {
63                 my ($id, $prev);
64                 my $smsg = $over->next_by_mid($mid, \$id, \$prev) or return;
65                 $mref = $ibx->msg_by_smsg($smsg) or return;
66                 $first = Email::Simple->new($mref);
67                 my $next = $over->next_by_mid($mid, \$id, \$prev);
68                 # $more is for ->getline
69                 $more = [ $ctx, $id, $prev, $next, $first, $mref ] if $next;
70         } else {
71                 $mref = $ibx->msg_by_mid($mid) or return;
72                 $first = Email::Simple->new($mref);
73         }
74         return unless defined $first;
75         my $fn = subject_fn($first);
76         my @hdr = ('Content-Type');
77         if ($ibx->{obfuscate}) {
78                 # obfuscation is stupid, but maybe scrapers are, too...
79                 push @hdr, 'application/mbox';
80                 $fn .= '.mbox';
81         } else {
82                 push @hdr, 'text/plain';
83                 $fn .= '.txt';
84         }
85         push @hdr, 'Content-Disposition', "inline; filename=$fn";
86         [ 200, \@hdr,
87                 $more ? mb_stream($more) : [ msg_str($ctx, $first, $mref) ] ];
88 }
89
90 sub msg_str {
91         my ($ctx, $simple, $mref, $mid) = @_; # simple - Email::Simple object
92         my $header_obj = $simple->header_obj;
93
94         # drop potentially confusing headers, ssoma already should've dropped
95         # Lines and Content-Length
96         foreach my $d (qw(Lines Bytes Content-Length Status)) {
97                 $header_obj->header_set($d);
98         }
99         my $ibx = $ctx->{-inbox};
100         my $base = $ibx->base_url($ctx->{env});
101         $mid = $ctx->{mid} unless defined $mid;
102         $mid = mid_escape($mid);
103         my @append = (
104                 'Archived-At', "<$base$mid/>",
105                 'List-Archive', "<$base>",
106                 'List-Post', "<mailto:$ibx->{-primary_address}>",
107         );
108         my $crlf = $header_obj->crlf;
109         my $buf = "From mboxrd\@z Thu Jan  1 00:00:00 1970\n" .
110                         $header_obj->as_string;
111         for (my $i = 0; $i < @append; $i += 2) {
112                 my $k = $append[$i];
113                 my $v = $append[$i + 1];
114                 my @v = $header_obj->header($k);
115                 foreach (@v) {
116                         if ($v eq $_) {
117                                 $v = undef;
118                                 last;
119                         }
120                 }
121                 $buf .= "$k: $v$crlf" if defined $v;
122         }
123         $buf .= $crlf;
124
125         # mboxrd quoting style
126         # ref: http://www.qmail.org/man/man5/mbox.html
127         $$mref =~ s/^(>*From )/>$1/gm;
128         $buf .= $$mref;
129         $buf .= "\n";
130 }
131
132 sub thread_mbox {
133         my ($ctx, $over, $sfx) = @_;
134         eval { require IO::Compress::Gzip };
135         return sub { need_gzip(@_) } if $@;
136         my $mid = $ctx->{mid};
137         my $msgs = $over->get_thread($mid, {});
138         return [404, [qw(Content-Type text/plain)], []] if !@$msgs;
139         my $prev = $msgs->[-1];
140         my $i = 0;
141         my $cb = sub {
142                 while (1) {
143                         if (my $smsg = $msgs->[$i++]) {
144                                 return $smsg;
145                         }
146                         # refill result set
147                         $msgs = $over->get_thread($mid, $prev);
148                         return unless @$msgs;
149                         $prev = $msgs->[-1];
150                         $i = 0;
151                 }
152         };
153         PublicInbox::MboxGz->response($ctx, $cb, $msgs->[0]->subject);
154 }
155
156 sub emit_range {
157         my ($ctx, $range) = @_;
158
159         my $query;
160         if ($range eq 'all') { # TODO: YYYY[-MM]
161                 $query = '';
162         } else {
163                 return [404, [qw(Content-Type text/plain)], []];
164         }
165         mbox_all($ctx, $query);
166 }
167
168 sub mbox_all_ids {
169         my ($ctx) = @_;
170         my $prev = 0;
171         my $ibx = $ctx->{-inbox};
172         my $ids = $ibx->mm->ids_after(\$prev) or return
173                 [404, [qw(Content-Type text/plain)], ["No results found\n"]];
174         my $i = 0;
175         my $over = $ibx->over or
176                 return PublicInbox::WWW::need($ctx, 'Overview');
177         my $cb = sub {
178                 do {
179                         while ((my $num = $ids->[$i++])) {
180                                 my $smsg = $over->get_art($num) or next;
181                                 return $smsg;
182                         }
183                         $ids = $ibx->mm->ids_after(\$prev);
184                         $i = 0;
185                 } while (@$ids);
186                 undef;
187         };
188         return PublicInbox::MboxGz->response($ctx, $cb, 'all');
189 }
190
191 sub mbox_all {
192         my ($ctx, $query) = @_;
193
194         eval { require IO::Compress::Gzip };
195         return sub { need_gzip(@_) } if $@;
196         return mbox_all_ids($ctx) if $query eq '';
197         my $opts = { mset => 2 };
198         my $srch = $ctx->{-inbox}->search or
199                 return PublicInbox::WWW::need($ctx, 'Search');;
200         my $mset = $srch->query($query, $opts);
201         $opts->{offset} = $mset->size or
202                         return [404, [qw(Content-Type text/plain)],
203                                 ["No results found\n"]];
204         my $i = 0;
205         my $cb = sub { # called by MboxGz->getline
206                 while (1) {
207                         while (my $mi = (($mset->items)[$i++])) {
208                                 my $doc = $mi->get_document;
209                                 my $smsg = $srch->retry_reopen(sub {
210                                         PublicInbox::SearchMsg->load_doc($doc);
211                                 }) or next;
212                                 return $smsg;
213                         }
214                         # refill result set
215                         $mset = $srch->query($query, $opts);
216                         my $size = $mset->size or return;
217                         $opts->{offset} += $size;
218                         $i = 0;
219                 }
220         };
221         PublicInbox::MboxGz->response($ctx, $cb, 'results-'.$query);
222 }
223
224 sub need_gzip {
225         my $fh = $_[0]->([501, ['Content-Type' => 'text/html']]);
226         my $title = 'gzipped mbox not available';
227         $fh->write(<<EOF);
228 <html><head><title>$title</title><body><pre>$title
229 The administrator needs to install the IO::Compress::Gzip Perl module
230 to support gzipped mboxes.
231 <a href="../">Return to index</a></pre></body></html>
232 EOF
233         $fh->close;
234 }
235
236 1;
237
238 package PublicInbox::MboxGz;
239 use strict;
240 use warnings;
241 use PublicInbox::Hval qw/to_filename/;
242
243 sub new {
244         my ($class, $ctx, $cb) = @_;
245         my $buf = '';
246         bless {
247                 buf => \$buf,
248                 gz => IO::Compress::Gzip->new(\$buf, Time => 0),
249                 cb => $cb,
250                 ctx => $ctx,
251         }, $class;
252 }
253
254 sub response {
255         my ($class, $ctx, $cb, $fn) = @_;
256         my $body = $class->new($ctx, $cb);
257         # http://www.iana.org/assignments/media-types/application/gzip
258         my @h = qw(Content-Type application/gzip);
259         if ($fn) {
260                 $fn = to_filename($fn);
261                 push @h, 'Content-Disposition', "inline; filename=$fn.mbox.gz";
262         }
263         [ 200, \@h, $body ];
264 }
265
266 # called by Plack::Util::foreach or similar
267 sub getline {
268         my ($self) = @_;
269         my $ctx = $self->{ctx} or return;
270         while (my $smsg = $self->{cb}->()) {
271                 my $mref = $ctx->{-inbox}->msg_by_smsg($smsg) or next;
272                 my $s = Email::Simple->new($mref);
273                 $self->{gz}->write(PublicInbox::Mbox::msg_str($ctx, $s, $mref,
274                                 $smsg->{mid}));
275                 my $bref = $self->{buf};
276                 if (length($$bref) >= 8192) {
277                         my $ret = $$bref; # copy :<
278                         ${$self->{buf}} = '';
279                         return $ret;
280                 }
281
282                 # be fair to other clients on public-inbox-httpd:
283                 return '';
284         }
285         delete($self->{gz})->close;
286         # signal that we're done and can return undef next call:
287         delete $self->{ctx};
288         ${delete $self->{buf}};
289 }
290
291 sub close {} # noop
292
293 1;