]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Mbox.pm
doc: various overview-level module comments
[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) = @$more;
42         if ($cur) { # first
43                 pop @$more;
44                 return msg_str($ctx, $cur);
45         }
46         $cur = $next or return;
47         my $ibx = $ctx->{-inbox};
48         $next = $ibx->search->next_by_mid($ctx->{mid}, \$id, \$prev);
49         @$more = ($ctx, $id, $prev, $next); # $next may be undef, here
50         my $mref = $ibx->msg_by_smsg($cur) or return;
51         msg_str($ctx, Email::Simple->new($mref));
52 }
53
54 sub close {} # noop
55
56 sub emit_raw {
57         my ($ctx) = @_;
58         my $mid = $ctx->{mid};
59         my $ibx = $ctx->{-inbox};
60         my $first;
61         my $more;
62         if (my $srch = $ibx->search) {
63                 my ($id, $prev);
64                 my $smsg = $srch->next_by_mid($mid, \$id, \$prev) or return;
65                 my $mref = $ibx->msg_by_smsg($smsg) or return;
66                 $first = Email::Simple->new($mref);
67                 my $next = $srch->next_by_mid($mid, \$id, \$prev);
68                 # $more is for ->getline
69                 $more = [ $ctx, $id, $prev, $next, $first ] if $next;
70         } else {
71                 my $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, $more ? mb_stream($more) : [ msg_str($ctx, $first) ] ];
87 }
88
89 sub msg_str {
90         my ($ctx, $simple, $mid) = @_; # Email::Simple object
91         my $header_obj = $simple->header_obj;
92
93         # drop potentially confusing headers, ssoma already should've dropped
94         # Lines and Content-Length
95         foreach my $d (qw(Lines Bytes Content-Length Status)) {
96                 $header_obj->header_set($d);
97         }
98         my $ibx = $ctx->{-inbox};
99         my $base = $ibx->base_url($ctx->{env});
100         $mid = $ctx->{mid} unless defined $mid;
101         $mid = mid_escape($mid);
102         my @append = (
103                 'Archived-At', "<$base$mid/>",
104                 'List-Archive', "<$base>",
105                 'List-Post', "<mailto:$ibx->{-primary_address}>",
106         );
107         my $crlf = $simple->crlf;
108         my $buf = "From mboxrd\@z Thu Jan  1 00:00:00 1970\n" .
109                         $header_obj->as_string;
110         for (my $i = 0; $i < @append; $i += 2) {
111                 my $k = $append[$i];
112                 my $v = $append[$i + 1];
113                 my @v = $header_obj->header($k);
114                 foreach (@v) {
115                         if ($v eq $_) {
116                                 $v = undef;
117                                 last;
118                         }
119                 }
120                 $buf .= "$k: $v$crlf" if defined $v;
121         }
122         $buf .= $crlf;
123
124         # mboxrd quoting style
125         # ref: http://www.qmail.org/man/man5/mbox.html
126         my $body = $simple->body;
127         $body =~ s/^(>*From )/>$1/gm;
128         $buf .= $body;
129         $buf .= "\n";
130 }
131
132 sub thread_mbox {
133         my ($ctx, $srch, $sfx) = @_;
134         eval { require IO::Compress::Gzip };
135         return sub { need_gzip(@_) } if $@;
136         my $mid = $ctx->{mid};
137         my $msgs = $srch->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 = $srch->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 $ids = $ctx->{-inbox}->mm->ids_after(\$prev) or return
172                 [404, [qw(Content-Type text/plain)], ["No results found\n"]];
173         my $i = 0;
174         my $over = $ctx->{srch}->{over_ro};
175         my $cb = sub {
176                 do {
177                         while ((my $num = $ids->[$i++])) {
178                                 my $smsg = $over->get_art($num) or next;
179                                 return $smsg;
180                         }
181                         $ids = $ctx->{-inbox}->mm->ids_after(\$prev);
182                         $i = 0;
183                 } while (@$ids);
184                 undef;
185         };
186         return PublicInbox::MboxGz->response($ctx, $cb, 'all');
187 }
188
189 sub mbox_all {
190         my ($ctx, $query) = @_;
191
192         eval { require IO::Compress::Gzip };
193         return sub { need_gzip(@_) } if $@;
194         return mbox_all_ids($ctx) if $query eq '';
195         my $opts = { mset => 2 };
196         my $srch = $ctx->{srch};
197         my $mset = $srch->query($query, $opts);
198         $opts->{offset} = $mset->size or
199                         return [404, [qw(Content-Type text/plain)],
200                                 ["No results found\n"]];
201         my $i = 0;
202         my $cb = sub { # called by MboxGz->getline
203                 while (1) {
204                         while (my $mi = (($mset->items)[$i++])) {
205                                 my $doc = $mi->get_document;
206                                 my $smsg = $srch->retry_reopen(sub {
207                                         PublicInbox::SearchMsg->load_doc($doc);
208                                 }) or next;
209                                 return $smsg;
210                         }
211                         # refill result set
212                         $mset = $srch->query($query, $opts);
213                         my $size = $mset->size or return;
214                         $opts->{offset} += $size;
215                         $i = 0;
216                 }
217         };
218         PublicInbox::MboxGz->response($ctx, $cb, 'results-'.$query);
219 }
220
221 sub need_gzip {
222         my $fh = $_[0]->([501, ['Content-Type' => 'text/html']]);
223         my $title = 'gzipped mbox not available';
224         $fh->write(<<EOF);
225 <html><head><title>$title</title><body><pre>$title
226 The administrator needs to install the IO::Compress::Gzip Perl module
227 to support gzipped mboxes.
228 <a href="../">Return to index</a></pre></body></html>
229 EOF
230         $fh->close;
231 }
232
233 1;
234
235 package PublicInbox::MboxGz;
236 use strict;
237 use warnings;
238 use PublicInbox::Hval qw/to_filename/;
239
240 sub new {
241         my ($class, $ctx, $cb) = @_;
242         my $buf = '';
243         bless {
244                 buf => \$buf,
245                 gz => IO::Compress::Gzip->new(\$buf, Time => 0),
246                 cb => $cb,
247                 ctx => $ctx,
248         }, $class;
249 }
250
251 sub response {
252         my ($class, $ctx, $cb, $fn) = @_;
253         my $body = $class->new($ctx, $cb);
254         # http://www.iana.org/assignments/media-types/application/gzip
255         my @h = qw(Content-Type application/gzip);
256         if ($fn) {
257                 $fn = to_filename($fn);
258                 push @h, 'Content-Disposition', "inline; filename=$fn.mbox.gz";
259         }
260         [ 200, \@h, $body ];
261 }
262
263 # called by Plack::Util::foreach or similar
264 sub getline {
265         my ($self) = @_;
266         my $ctx = $self->{ctx} or return;
267         while (my $smsg = $self->{cb}->()) {
268                 my $msg = $ctx->{-inbox}->msg_by_smsg($smsg) or next;
269                 $msg = Email::Simple->new($msg);
270                 $self->{gz}->write(PublicInbox::Mbox::msg_str($ctx, $msg,
271                                 $smsg->{mid}));
272                 my $bref = $self->{buf};
273                 if (length($$bref) >= 8192) {
274                         my $ret = $$bref; # copy :<
275                         ${$self->{buf}} = '';
276                         return $ret;
277                 }
278
279                 # be fair to other clients on public-inbox-httpd:
280                 return '';
281         }
282         delete($self->{gz})->close;
283         # signal that we're done and can return undef next call:
284         delete $self->{ctx};
285         ${delete $self->{buf}};
286 }
287
288 sub close {} # noop
289
290 1;