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