]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
a30bf70a0169d0253737edaab30637e2ba529655
[public-inbox.git] / lib / PublicInbox / View.pm
1 # Copyright (C) 2014, Eric Wong <normalperson@yhbt.net> and all contributors
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 package PublicInbox::View;
4 use strict;
5 use warnings;
6 use URI::Escape qw/uri_escape_utf8/;
7 use Date::Parse qw/str2time/;
8 use Encode qw/find_encoding/;
9 use Encode::MIME::Header;
10 use Email::MIME::ContentType qw/parse_content_type/;
11 use PublicInbox::Hval;
12 use PublicInbox::MID qw/mid_clean mid_compress mid2path/;
13 use Digest::SHA;
14 require POSIX;
15
16 # TODO: make these constants tunable
17 use constant MAX_INLINE_QUOTED => 12; # half an 80x24 terminal
18 use constant MAX_TRUNC_LEN => 72;
19 use constant PRE_WRAP => "<pre\nstyle=\"white-space:pre-wrap\">";
20 use constant T_ANCHOR => '#u';
21
22 *ascii_html = *PublicInbox::Hval::ascii_html;
23
24 my $enc_utf8 = find_encoding('UTF-8');
25
26 # public functions:
27 sub msg_html {
28         my ($ctx, $mime, $full_pfx, $footer) = @_;
29         if (defined $footer) {
30                 $footer = "\n" . $footer;
31         } else {
32                 $footer = '';
33         }
34         headers_to_html_header($mime, $full_pfx, $ctx) .
35                 multipart_text_as_html($mime, $full_pfx) .
36                 '</pre><hr />' . PRE_WRAP .
37                 html_footer($mime, 1, $full_pfx, $ctx) .
38                 $footer .
39                 '</pre></body></html>';
40 }
41
42 sub feed_entry {
43         my ($class, $mime, $full_pfx) = @_;
44
45         PRE_WRAP . multipart_text_as_html($mime, $full_pfx) . '</pre>';
46 }
47
48 # this is already inside a <pre>
49 sub index_entry {
50         my ($fh, $mime, $level, $state) = @_;
51         my $midx = $state->{anchor_idx}++;
52         my $ctx = $state->{ctx};
53         my $srch = $ctx->{srch};
54         my ($prev, $next) = ($midx - 1, $midx + 1);
55         my $part_nr = 0;
56         my $enc = enc_for($mime->header("Content-Type"));
57         my $subj = $mime->header('Subject');
58         my $header_obj = $mime->header_obj;
59
60         my $mid_raw = $header_obj->header('Message-ID');
61         my $id = anchor_for($mid_raw);
62         my $seen = $state->{seen};
63         $seen->{$id} = "#$id"; # save the anchor for later
64
65         my $mid = PublicInbox::Hval->new_msgid($mid_raw);
66         my $from = PublicInbox::Hval->new_oneline($mime->header('From'))->raw;
67         my @from = Email::Address->parse($from);
68         $from = $from[0]->name;
69
70         $from = PublicInbox::Hval->new_oneline($from)->as_html;
71         $subj = PublicInbox::Hval->new_oneline($subj)->as_html;
72         my $more = 'permalink';
73         my $root_anchor = $state->{root_anchor};
74         my $path = $root_anchor ? '../../' : '';
75         my $href = $mid->as_href;
76         my $irt = $header_obj->header('In-Reply-To');
77         my ($anchor_idx, $anchor);
78         if (defined $irt) {
79                 $anchor_idx = anchor_for($irt);
80                 $anchor = $seen->{$anchor_idx};
81         }
82         if ($srch) {
83                 $subj = "<a\nhref=\"${path}t/$href/#u\">$subj</a>";
84         }
85         if ($root_anchor && $root_anchor eq $id) {
86                 $subj = "<u\nid=\"u\">$subj</u>";
87         }
88
89         my $ts = _msg_date($mime);
90         my $rv = "<table\nsummary=l$level><tr>";
91         if ($level) {
92                 $rv .= '<td><pre>' . ('  ' x $level) . '</pre></td>';
93         }
94         $rv .= "<td\nid=s$midx>" . PRE_WRAP;
95         $rv .= "<b\nid=\"$id\">$subj</b>\n";
96         $rv .= "- by $from @ $ts UTC - ";
97         $rv .= "<a\nhref=\"#s$next\">next</a>";
98         if ($prev >= 0) {
99                 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
100         }
101         $fh->write($rv .= "\n\n");
102
103         my ($fhref, $more_ref);
104         my $mhref = "${path}m/$href/";
105         if ($level > 0) {
106                 $fhref = "${path}f/$href/";
107                 $more_ref = \$more;
108         }
109         # scan through all parts, looking for displayable text
110         $mime->walk_parts(sub {
111                 index_walk($fh, $_[0], $enc, \$part_nr, $fhref, $more_ref);
112         });
113         $mime->body_set('');
114
115         my $txt = "${path}m/$href/raw";
116         $rv = "\n<a\nhref=\"$mhref\">$more</a> <a\nhref=\"$txt\">raw</a> ";
117         $rv .= html_footer($mime, 0, undef, $ctx);
118
119         if (defined $irt) {
120                 unless (defined $anchor) {
121                         my $v = PublicInbox::Hval->new_msgid($irt);
122                         $v = $v->as_href;
123                         $anchor = "${path}m/$v/";
124                         $seen->{$anchor_idx} = $anchor;
125                 }
126                 $rv .= " <a\nhref=\"$anchor\">parent</a>";
127         }
128
129         $fh->write($rv .= '</pre></td></tr></table>');
130 }
131
132 sub thread_html {
133         my ($ctx, $foot, $srch) = @_;
134         sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
135 }
136
137 # only private functions below.
138
139 sub emit_thread_html {
140         my ($cb, $ctx, $foot, $srch) = @_;
141         my $mid = mid_compress($ctx->{mid});
142         my $res = $srch->get_thread($mid);
143         my $msgs = load_results($res);
144         my $nr = scalar @$msgs;
145         return missing_thread($cb) if $nr == 0;
146         my $fh = $cb->([200,['Content-Type'=>'text/html; charset=UTF-8']]);
147         my $th = thread_results($msgs);
148         my $state = {
149                 ctx => $ctx,
150                 seen => {},
151                 root_anchor => anchor_for($mid),
152                 anchor_idx => 0,
153         };
154         {
155                 require PublicInbox::GitCatFile;
156                 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
157                 thread_entry($fh, $git, $state, $_, 0) for $th->rootset;
158         }
159         my $final_anchor = $state->{anchor_idx};
160         my $next = "<a\nid=\"s$final_anchor\">";
161         $next .= $final_anchor == 1 ? 'only message in' : 'end of';
162         $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>\n";
163         $next .= "download: <a\nhref=\"mbox.gz\">mbox.gz</a>";
164         $next .= " / <a\nhref=\"atom\">Atom feed</a>\n\n";
165         $fh->write("<hr />" . PRE_WRAP . $next . $foot .
166                    "</pre></body></html>");
167         $fh->close;
168 }
169
170 sub index_walk {
171         my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
172         my $s = add_text_body($enc, $part, $part_nr, $fhref);
173
174         if ($more) {
175                 # drop the remainder of git patches, they're usually better
176                 # to review when the full message is viewed
177                 $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
178
179                 # Drop signatures
180                 $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
181         }
182
183         # kill any leading or trailing whitespace lines
184         $s =~ s/^\s*$//sgm;
185         $s =~ s/\s+\z//s;
186
187         if ($s ne '') {
188                 # kill per-line trailing whitespace
189                 $s =~ s/[ \t]+$//sgm;
190                 $s .= "\n" unless $s =~ /\n\z/s;
191         }
192         $fh->write($s);
193 }
194
195 sub enc_for {
196         my ($ct, $default) = @_;
197         $default ||= $enc_utf8;
198         defined $ct or return $default;
199         my $ct_parsed = parse_content_type($ct);
200         if ($ct_parsed) {
201                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
202                         my $enc = find_encoding($charset);
203                         return $enc if $enc;
204                 }
205         }
206         $default;
207 }
208
209 sub multipart_text_as_html {
210         my ($mime, $full_pfx, $srch) = @_;
211         my $rv = "";
212         my $part_nr = 0;
213         my $enc = enc_for($mime->header("Content-Type"));
214
215         # scan through all parts, looking for displayable text
216         $mime->walk_parts(sub {
217                 my ($part) = @_;
218                 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx);
219         });
220         $mime->body_set('');
221         $rv;
222 }
223
224 sub add_filename_line {
225         my ($enc, $fn) = @_;
226         my $len = 72;
227         my $pad = "-";
228         $fn = $enc->decode($fn);
229         $len -= length($fn);
230         $pad x= ($len/2) if ($len > 0);
231         "$pad " . ascii_html($fn) . " $pad\n";
232 }
233
234 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
235                  [\@:\w\.-]+/
236                  ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
237
238 sub linkify {
239         # no newlines added here since it'd break the splitting we do
240         # to fold quotes
241         $_[0] =~ s!$LINK_RE!<a\nhref="$1">$1</a>!g;
242 }
243
244 sub flush_quote {
245         my ($quot, $n, $part_nr, $full_pfx, $final) = @_;
246
247         if ($full_pfx) {
248                 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
249                         # show quote inline
250                         my $rv = join('', map { linkify($_); $_ } @$quot);
251                         @$quot = ();
252                         return $rv;
253                 }
254
255                 # show a short snippet of quoted text and link to full version:
256                 @$quot = map { s/^(?:&gt;\s*)+//gm; $_ } @$quot;
257                 my $cur = join(' ', @$quot);
258                 @$quot = split(/\s+/, $cur);
259                 $cur = '';
260                 do {
261                         my $tmp = shift(@$quot);
262                         my $len = length($tmp) + length($cur);
263                         if ($len > MAX_TRUNC_LEN) {
264                                 @$quot = ();
265                         } else {
266                                 $cur .= $tmp . ' ';
267                         }
268                 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
269                 @$quot = ();
270                 $cur =~ s/ \z/ .../s;
271                 my $nr = ++$$n;
272                 "&gt; [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
273         } else {
274                 # show everything in the full version with anchor from
275                 # short version (see above)
276                 my $nr = ++$$n;
277                 my $rv = "<a\nid=q${part_nr}_$nr></a>";
278                 $rv .= join('', map { linkify($_); $_ } @$quot);
279                 @$quot = ();
280                 $rv;
281         }
282 }
283
284 sub add_text_body {
285         my ($enc_msg, $part, $part_nr, $full_pfx) = @_;
286         return '' if $part->subparts;
287
288         my $ct = $part->content_type;
289         # account for filter bugs...
290         if (defined $ct && $ct =~ m!\btext/[xh]+tml\b!i) {
291                 $part->body_set('');
292                 return '';
293         }
294         my $enc = enc_for($ct, $enc_msg);
295         my $n = 0;
296         my $nr = 0;
297         my $s = $part->body;
298         $part->body_set('');
299         $s = $enc->decode($s);
300         $s = ascii_html($s);
301         my @lines = split(/^/m, $s);
302         $s = '';
303
304         if ($$part_nr > 0) {
305                 my $fn = $part->filename;
306                 defined($fn) or $fn = "part #" . ($$part_nr + 1);
307                 $s .= add_filename_line($enc, $fn);
308         }
309
310         my @quot;
311         while (defined(my $cur = shift @lines)) {
312                 if ($cur !~ /^&gt;/) {
313                         # show the previously buffered quote inline
314                         if (scalar @quot) {
315                                 $s .= flush_quote(\@quot, \$n, $$part_nr,
316                                                   $full_pfx, 0);
317                         }
318
319                         # regular line, OK
320                         linkify($cur);
321                         $s .= $cur;
322                 } else {
323                         push @quot, $cur;
324                 }
325         }
326         $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1) if scalar @quot;
327         $s .= "\n" unless $s =~ /\n\z/s;
328         ++$$part_nr;
329         $s;
330 }
331
332 sub headers_to_html_header {
333         my ($mime, $full_pfx, $ctx) = @_;
334         my $srch = $ctx->{srch} if $ctx;
335         my $rv = "";
336         my @title;
337         my $header_obj = $mime->header_obj;
338         my $mid = $header_obj->header('Message-ID');
339         $mid = PublicInbox::Hval->new_msgid($mid);
340         my $mid_href = $mid->as_href;
341         foreach my $h (qw(From To Cc Subject Date)) {
342                 my $v = $mime->header($h);
343                 defined($v) && ($v ne '') or next;
344                 $v = PublicInbox::Hval->new_oneline($v);
345
346                 if ($h eq 'From') {
347                         my @from = Email::Address->parse($v->raw);
348                         $title[1] = ascii_html($from[0]->name);
349                 } elsif ($h eq 'Subject') {
350                         $title[0] = $v->as_html;
351                         if ($srch) {
352                                 $rv .= "$h: <a\nid=\"t\"\n" .
353                                         "href=\"../../t/$mid_href/\">";
354                                 $rv .= $v->as_html . "</a>\n";
355                                 next;
356                         }
357                 }
358                 $rv .= "$h: " . $v->as_html . "\n";
359
360         }
361         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
362         my $raw_ref = $full_pfx ? 'raw' : "../../m/$mid_href/raw";
363         $rv .= "(<a\nhref=\"$raw_ref\">raw</a>)\n";
364         if ($srch) {
365                 $rv .= "<a\nhref=\"#r\">References: [see below]</a>\n";
366         } else {
367                 $rv .= _parent_headers_nosrch($header_obj);
368         }
369         $rv .= "\n";
370
371         ("<html><head><title>".  join(' - ', @title) .
372          '</title></head><body>' . PRE_WRAP . $rv);
373 }
374
375 sub thread_inline {
376         my ($dst, $ctx, $cur) = @_;
377         my $srch = $ctx->{srch};
378         my $mid = mid_compress(mid_clean($cur->header('Message-ID')));
379         my $res = $srch->get_thread($mid);
380         my $nr = $res->{total};
381
382         if ($nr <= 1) {
383                 $$dst .= "\n[no followups, yet]</a>\n";
384                 return;
385         }
386
387         $$dst .= "\n\n~$nr messages in thread: ".
388                  "(<a\nhref=\"../../t/$mid/#u\">expand</a>)\n";
389         my $subj = $srch->subject_path($cur->header('Subject'));
390         my $state = {
391                 seen => { $subj => 1 },
392                 srch => $srch,
393                 cur => $mid,
394         };
395         for (thread_results(load_results($res))->rootset) {
396                 inline_dump($dst, $state, $_, 0);
397         }
398         $state->{next_msg};
399 }
400
401 sub _parent_headers_nosrch {
402         my ($header_obj) = @_;
403         my $rv = '';
404
405         my $irt = $header_obj->header('In-Reply-To');
406         if (defined $irt) {
407                 my $v = PublicInbox::Hval->new_msgid($irt);
408                 my $html = $v->as_html;
409                 my $href = $v->as_href;
410                 $rv .= "In-Reply-To: &lt;";
411                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
412         }
413
414         my $refs = $header_obj->header('References');
415         if ($refs) {
416                 # avoid redundant URLs wasting bandwidth
417                 my %seen;
418                 $seen{mid_clean($irt)} = 1 if defined $irt;
419                 my @refs;
420                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
421                 foreach my $ref (@raw_refs) {
422                         next if $seen{$ref};
423                         $seen{$ref} = 1;
424                         push @refs, linkify_ref($ref);
425                 }
426
427                 if (@refs) {
428                         $rv .= 'References: '. join(' ', @refs) . "\n";
429                 }
430         }
431         $rv;
432 }
433
434 sub html_footer {
435         my ($mime, $standalone, $full_pfx, $ctx) = @_;
436         my %cc; # everyone else
437         my $to; # this is the From address
438
439         foreach my $h (qw(From To Cc)) {
440                 my $v = $mime->header($h);
441                 defined($v) && ($v ne '') or next;
442                 my @addrs = Email::Address->parse($v);
443                 foreach my $recip (@addrs) {
444                         my $address = $recip->address;
445                         my $dst = lc($address);
446                         $cc{$dst} ||= $address;
447                         $to ||= $dst;
448                 }
449         }
450         Email::Address->purge_cache if $standalone;
451
452         my $subj = $mime->header('Subject') || '';
453         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
454         my $mid = $mime->header('Message-ID');
455         my $irt = uri_escape_utf8($mid);
456         delete $cc{$to};
457         $to = uri_escape_utf8($to);
458         $subj = uri_escape_utf8($subj);
459
460         my $cc = uri_escape_utf8(join(',', sort values %cc));
461         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
462
463         my $srch = $ctx->{srch} if $ctx;
464         my $idx = $standalone ? " <a\nhref=\"../../\">index</a>" : '';
465         if ($idx && $srch) {
466                 my $next = thread_inline(\$idx, $ctx, $mime);
467                 $irt = $mime->header('In-Reply-To');
468                 if (defined $irt) {
469                         $irt = PublicInbox::Hval->new_msgid($irt);
470                         $irt = $irt->as_href;
471                         $irt = "<a\nhref=\"../$irt/\">parent</a> ";
472                 } else {
473                         $irt = ' ' x length('parent ');
474                 }
475                 if ($next) {
476                         $irt .= "<a\nhref=\"../$next/\">next</a> ";
477                 } else {
478                         $irt .= '     ';
479                 }
480         } else {
481                 $irt = '';
482         }
483
484         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
485 }
486
487 sub linkify_ref {
488         my $v = PublicInbox::Hval->new_msgid($_[0]);
489         my $html = $v->as_html;
490         my $href = $v->as_href;
491         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
492 }
493
494 sub anchor_for {
495         my ($msgid) = @_;
496         my $id = $msgid;
497         if ($id !~ /\A[a-f0-9]{40}\z/) {
498                 $id = mid_compress(mid_clean($id), 1);
499         }
500         'm' . $id;
501 }
502
503 sub thread_html_head {
504         my ($mime) = @_;
505         my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
506         $s = $s->as_html;
507         "<html><head><title>$s</title></head><body>";
508 }
509
510 sub thread_entry {
511         my ($fh, $git, $state, $node, $level) = @_;
512         return unless $node;
513         if (my $mime = $node->message) {
514
515                 # lazy load the full message from mini_mime:
516                 my $path = mid2path(mid_clean($mime->header('Message-ID')));
517                 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
518                 if ($mime) {
519                         if ($state->{anchor_idx} == 0) {
520                                 $fh->write(thread_html_head($mime));
521                         }
522                         index_entry($fh, $mime, $level, $state);
523                 }
524         }
525         thread_entry($fh, $git, $state, $node->child, $level + 1);
526         thread_entry($fh, $git, $state, $node->next, $level);
527 }
528
529 sub load_results {
530         my ($res) = @_;
531
532         [ map { $_->mini_mime } @{delete $res->{msgs}} ];
533 }
534
535 sub msg_timestamp {
536         my ($mime) = @_;
537         my $ts = eval { str2time($mime->header('Date')) };
538         defined($ts) ? $ts : 0;
539 }
540
541 sub thread_results {
542         my ($msgs) = @_;
543         require PublicInbox::Thread;
544         my $th = PublicInbox::Thread->new(@$msgs);
545         $th->thread;
546         no warnings 'once';
547         $th->order(*PublicInbox::Thread::sort_ts);
548         $th
549 }
550
551 sub missing_thread {
552         my ($cb) = @_;
553         my $title = 'Thread does not exist';
554         $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
555 <html><head><title>$title</title></head><body><pre>$title
556 <a href="../../">Return to index</a></pre></body></html>
557 EOF
558 }
559
560 sub _msg_date {
561         my ($mime) = @_;
562         my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
563         POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
564 }
565
566 sub _inline_header {
567         my ($dst, $state, $mime, $level) = @_;
568         my $pfx = '  ' x $level;
569
570         my $cur = $state->{cur};
571         my $mid = $mime->header('Message-ID');
572         my $f = $mime->header('X-PI-From');
573         my $d = _msg_date($mime);
574         $f = PublicInbox::Hval->new($f);
575         $d = PublicInbox::Hval->new($d);
576         $f = $f->as_html;
577         $d = $d->as_html . ' UTC';
578         my $midc = mid_compress(mid_clean($mid));
579         if ($cur) {
580                 if ($cur eq $midc) {
581                         delete $state->{cur};
582                         $$dst .= "$pfx` <b><a\nid=\"r\"\nhref=\"#t\">".
583                                  "[this message]</a></b> by $f @ $d\n";
584
585                         return;
586                 }
587         } else {
588                 $state->{next_msg} ||= $midc;
589         }
590
591         # Subject is never undef, this mail was loaded from
592         # our Xapian which would've resulted in '' if it were
593         # really missing (and Filter rejects empty subjects)
594         my $s = $mime->header('Subject');
595         my $h = $state->{srch}->subject_path($s);
596         if ($state->{seen}->{$h}) {
597                 $s = undef;
598         } else {
599                 $state->{seen}->{$h} = 1;
600                 $s = PublicInbox::Hval->new($s);
601                 $s = $s->as_html;
602         }
603         my $m = PublicInbox::Hval->new_msgid($mid);
604         $m = '../' . $m->as_href . '/';
605         if (defined $s) {
606                 $$dst .= "$pfx` <a\nhref=\"$m\">$s</a>\n" .
607                          "$pfx  $f @ $d\n";
608         } else {
609                 $$dst .= "$pfx` <a\nhref=\"$m\">$f @ $d</a>\n";
610         }
611 }
612
613 sub inline_dump {
614         my ($dst, $state, $node, $level) = @_;
615         return unless $node;
616         return if $state->{stopped};
617         if (my $mime = $node->message) {
618                 _inline_header($dst, $state, $mime, $level);
619         }
620         inline_dump($dst, $state, $node->child, $level+1);
621         inline_dump($dst, $state, $node->next, $level);
622 }
623
624 1;