]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
477c4b6f09a13b0a22f6dea6b4091240d3d3459e
[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>\n\n";
164         $fh->write("<hr />" . PRE_WRAP . $next . $foot .
165                    "</pre></body></html>");
166         $fh->close;
167 }
168
169 sub index_walk {
170         my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
171         my $s = add_text_body($enc, $part, $part_nr, $fhref);
172
173         if ($more) {
174                 # drop the remainder of git patches, they're usually better
175                 # to review when the full message is viewed
176                 $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
177
178                 # Drop signatures
179                 $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
180         }
181
182         # kill any leading or trailing whitespace lines
183         $s =~ s/^\s*$//sgm;
184         $s =~ s/\s+\z//s;
185
186         if ($s ne '') {
187                 # kill per-line trailing whitespace
188                 $s =~ s/[ \t]+$//sgm;
189                 $s .= "\n" unless $s =~ /\n\z/s;
190         }
191         $fh->write($s);
192 }
193
194 sub enc_for {
195         my ($ct, $default) = @_;
196         $default ||= $enc_utf8;
197         defined $ct or return $default;
198         my $ct_parsed = parse_content_type($ct);
199         if ($ct_parsed) {
200                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
201                         my $enc = find_encoding($charset);
202                         return $enc if $enc;
203                 }
204         }
205         $default;
206 }
207
208 sub multipart_text_as_html {
209         my ($mime, $full_pfx, $srch) = @_;
210         my $rv = "";
211         my $part_nr = 0;
212         my $enc = enc_for($mime->header("Content-Type"));
213
214         # scan through all parts, looking for displayable text
215         $mime->walk_parts(sub {
216                 my ($part) = @_;
217                 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx);
218         });
219         $mime->body_set('');
220         $rv;
221 }
222
223 sub add_filename_line {
224         my ($enc, $fn) = @_;
225         my $len = 72;
226         my $pad = "-";
227         $fn = $enc->decode($fn);
228         $len -= length($fn);
229         $pad x= ($len/2) if ($len > 0);
230         "$pad " . ascii_html($fn) . " $pad\n";
231 }
232
233 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://
234                  [\@:\w\.-]+/
235                  ?[\@\w\+\&\?\.\%\;/#=-]*)!x;
236
237 sub linkify {
238         # no newlines added here since it'd break the splitting we do
239         # to fold quotes
240         $_[0] =~ s!$LINK_RE!<a\nhref="$1">$1</a>!g;
241 }
242
243 sub flush_quote {
244         my ($quot, $n, $part_nr, $full_pfx, $final) = @_;
245
246         if ($full_pfx) {
247                 if (!$final && scalar(@$quot) <= MAX_INLINE_QUOTED) {
248                         # show quote inline
249                         my $rv = join('', map { linkify($_); $_ } @$quot);
250                         @$quot = ();
251                         return $rv;
252                 }
253
254                 # show a short snippet of quoted text and link to full version:
255                 @$quot = map { s/^(?:&gt;\s*)+//gm; $_ } @$quot;
256                 my $cur = join(' ', @$quot);
257                 @$quot = split(/\s+/, $cur);
258                 $cur = '';
259                 do {
260                         my $tmp = shift(@$quot);
261                         my $len = length($tmp) + length($cur);
262                         if ($len > MAX_TRUNC_LEN) {
263                                 @$quot = ();
264                         } else {
265                                 $cur .= $tmp . ' ';
266                         }
267                 } while (@$quot && length($cur) < MAX_TRUNC_LEN);
268                 @$quot = ();
269                 $cur =~ s/ \z/ .../s;
270                 my $nr = ++$$n;
271                 "&gt; [<a\nhref=\"$full_pfx#q${part_nr}_$nr\">$cur</a>]\n";
272         } else {
273                 # show everything in the full version with anchor from
274                 # short version (see above)
275                 my $nr = ++$$n;
276                 my $rv = "<a\nid=q${part_nr}_$nr></a>";
277                 $rv .= join('', map { linkify($_); $_ } @$quot);
278                 @$quot = ();
279                 $rv;
280         }
281 }
282
283 sub add_text_body {
284         my ($enc_msg, $part, $part_nr, $full_pfx) = @_;
285         return '' if $part->subparts;
286
287         my $ct = $part->content_type;
288         # account for filter bugs...
289         if (defined $ct && $ct =~ m!\btext/[xh]+tml\b!i) {
290                 $part->body_set('');
291                 return '';
292         }
293         my $enc = enc_for($ct, $enc_msg);
294         my $n = 0;
295         my $nr = 0;
296         my $s = $part->body;
297         $part->body_set('');
298         $s = $enc->decode($s);
299         $s = ascii_html($s);
300         my @lines = split(/^/m, $s);
301         $s = '';
302
303         if ($$part_nr > 0) {
304                 my $fn = $part->filename;
305                 defined($fn) or $fn = "part #" . ($$part_nr + 1);
306                 $s .= add_filename_line($enc, $fn);
307         }
308
309         my @quot;
310         while (defined(my $cur = shift @lines)) {
311                 if ($cur !~ /^&gt;/) {
312                         # show the previously buffered quote inline
313                         if (scalar @quot) {
314                                 $s .= flush_quote(\@quot, \$n, $$part_nr,
315                                                   $full_pfx, 0);
316                         }
317
318                         # regular line, OK
319                         linkify($cur);
320                         $s .= $cur;
321                 } else {
322                         push @quot, $cur;
323                 }
324         }
325         $s .= flush_quote(\@quot, \$n, $$part_nr, $full_pfx, 1) if scalar @quot;
326         $s .= "\n" unless $s =~ /\n\z/s;
327         ++$$part_nr;
328         $s;
329 }
330
331 sub headers_to_html_header {
332         my ($mime, $full_pfx, $ctx) = @_;
333         my $srch = $ctx->{srch} if $ctx;
334         my $rv = "";
335         my @title;
336         my $header_obj = $mime->header_obj;
337         my $mid = $header_obj->header('Message-ID');
338         $mid = PublicInbox::Hval->new_msgid($mid);
339         my $mid_href = $mid->as_href;
340         foreach my $h (qw(From To Cc Subject Date)) {
341                 my $v = $mime->header($h);
342                 defined($v) && ($v ne '') or next;
343                 $v = PublicInbox::Hval->new_oneline($v);
344
345                 if ($h eq 'From') {
346                         my @from = Email::Address->parse($v->raw);
347                         $title[1] = ascii_html($from[0]->name);
348                 } elsif ($h eq 'Subject') {
349                         $title[0] = $v->as_html;
350                         if ($srch) {
351                                 $rv .= "$h: <a\nid=\"t\"\n" .
352                                         "href=\"../../t/$mid_href/\">";
353                                 $rv .= $v->as_html . "</a>\n";
354                                 next;
355                         }
356                 }
357                 $rv .= "$h: " . $v->as_html . "\n";
358
359         }
360         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
361         my $raw_ref = $full_pfx ? 'raw' : "../../m/$mid_href/raw";
362         $rv .= "(<a\nhref=\"$raw_ref\">raw</a>)\n";
363         if ($srch) {
364                 $rv .= "<a\nhref=\"#r\">References: [see below]</a>\n";
365         } else {
366                 $rv .= _parent_headers_nosrch($header_obj);
367         }
368         $rv .= "\n";
369
370         ("<html><head><title>".  join(' - ', @title) .
371          '</title></head><body>' . PRE_WRAP . $rv);
372 }
373
374 sub thread_inline {
375         my ($dst, $ctx, $cur) = @_;
376         my $srch = $ctx->{srch};
377         my $mid = mid_compress(mid_clean($cur->header('Message-ID')));
378         my $res = $srch->get_thread($mid);
379         my $nr = $res->{total};
380
381         if ($nr <= 1) {
382                 $$dst .= "\n[no followups, yet]</a>\n";
383                 return;
384         }
385
386         $$dst .= "\n\n~$nr messages in thread: ".
387                  "(<a\nhref=\"../../t/$mid/#u\">expand</a>)\n";
388         my $subj = $srch->subject_path($cur->header('Subject'));
389         my $state = {
390                 seen => { $subj => 1 },
391                 srch => $srch,
392                 cur => $mid,
393         };
394         for (thread_results(load_results($res))->rootset) {
395                 inline_dump($dst, $state, $_, 0);
396         }
397         $state->{next_msg};
398 }
399
400 sub _parent_headers_nosrch {
401         my ($header_obj) = @_;
402         my $rv = '';
403
404         my $irt = $header_obj->header('In-Reply-To');
405         if (defined $irt) {
406                 my $v = PublicInbox::Hval->new_msgid($irt);
407                 my $html = $v->as_html;
408                 my $href = $v->as_href;
409                 $rv .= "In-Reply-To: &lt;";
410                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
411         }
412
413         my $refs = $header_obj->header('References');
414         if ($refs) {
415                 # avoid redundant URLs wasting bandwidth
416                 my %seen;
417                 $seen{mid_clean($irt)} = 1 if defined $irt;
418                 my @refs;
419                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
420                 foreach my $ref (@raw_refs) {
421                         next if $seen{$ref};
422                         $seen{$ref} = 1;
423                         push @refs, linkify_ref($ref);
424                 }
425
426                 if (@refs) {
427                         $rv .= 'References: '. join(' ', @refs) . "\n";
428                 }
429         }
430         $rv;
431 }
432
433 sub html_footer {
434         my ($mime, $standalone, $full_pfx, $ctx) = @_;
435         my %cc; # everyone else
436         my $to; # this is the From address
437
438         foreach my $h (qw(From To Cc)) {
439                 my $v = $mime->header($h);
440                 defined($v) && ($v ne '') or next;
441                 my @addrs = Email::Address->parse($v);
442                 foreach my $recip (@addrs) {
443                         my $address = $recip->address;
444                         my $dst = lc($address);
445                         $cc{$dst} ||= $address;
446                         $to ||= $dst;
447                 }
448         }
449         Email::Address->purge_cache if $standalone;
450
451         my $subj = $mime->header('Subject') || '';
452         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
453         my $mid = $mime->header('Message-ID');
454         my $irt = uri_escape_utf8($mid);
455         delete $cc{$to};
456         $to = uri_escape_utf8($to);
457         $subj = uri_escape_utf8($subj);
458
459         my $cc = uri_escape_utf8(join(',', sort values %cc));
460         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
461
462         my $srch = $ctx->{srch} if $ctx;
463         my $idx = $standalone ? " <a\nhref=\"../../\">index</a>" : '';
464         if ($idx && $srch) {
465                 my $next = thread_inline(\$idx, $ctx, $mime);
466                 $irt = $mime->header('In-Reply-To');
467                 if (defined $irt) {
468                         $irt = PublicInbox::Hval->new_msgid($irt);
469                         $irt = $irt->as_href;
470                         $irt = "<a\nhref=\"../$irt/\">parent</a> ";
471                 } else {
472                         $irt = ' ' x length('parent ');
473                 }
474                 if ($next) {
475                         $irt .= "<a\nhref=\"../$next/\">next</a> ";
476                 } else {
477                         $irt .= '     ';
478                 }
479         } else {
480                 $irt = '';
481         }
482
483         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
484 }
485
486 sub linkify_ref {
487         my $v = PublicInbox::Hval->new_msgid($_[0]);
488         my $html = $v->as_html;
489         my $href = $v->as_href;
490         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
491 }
492
493 sub anchor_for {
494         my ($msgid) = @_;
495         my $id = $msgid;
496         if ($id !~ /\A[a-f0-9]{40}\z/) {
497                 $id = mid_compress(mid_clean($id), 1);
498         }
499         'm' . $id;
500 }
501
502 sub thread_html_head {
503         my ($mime) = @_;
504         my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
505         $s = $s->as_html;
506         "<html><head><title>$s</title></head><body>";
507 }
508
509 sub thread_entry {
510         my ($fh, $git, $state, $node, $level) = @_;
511         return unless $node;
512         if (my $mime = $node->message) {
513
514                 # lazy load the full message from mini_mime:
515                 my $path = mid2path(mid_clean($mime->header('Message-ID')));
516                 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
517                 if ($mime) {
518                         if ($state->{anchor_idx} == 0) {
519                                 $fh->write(thread_html_head($mime));
520                         }
521                         index_entry($fh, $mime, $level, $state);
522                 }
523         }
524         thread_entry($fh, $git, $state, $node->child, $level + 1);
525         thread_entry($fh, $git, $state, $node->next, $level);
526 }
527
528 sub load_results {
529         my ($res) = @_;
530
531         [ map { $_->mini_mime } @{delete $res->{msgs}} ];
532 }
533
534 sub msg_timestamp {
535         my ($mime) = @_;
536         my $ts = eval { str2time($mime->header('Date')) };
537         defined($ts) ? $ts : 0;
538 }
539
540 sub thread_results {
541         my ($msgs) = @_;
542         require PublicInbox::Thread;
543         my $th = PublicInbox::Thread->new(@$msgs);
544         $th->thread;
545         no warnings 'once';
546         $th->order(*PublicInbox::Thread::sort_ts);
547         $th
548 }
549
550 sub missing_thread {
551         my ($cb) = @_;
552         my $title = 'Thread does not exist';
553         $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
554 <html><head><title>$title</title></head><body><pre>$title
555 <a href="../../">Return to index</a></pre></body></html>
556 EOF
557 }
558
559 sub _msg_date {
560         my ($mime) = @_;
561         my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
562         POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
563 }
564
565 sub _inline_header {
566         my ($dst, $state, $mime, $level) = @_;
567         my $pfx = '  ' x $level;
568
569         my $cur = $state->{cur};
570         my $mid = $mime->header('Message-ID');
571         my $f = $mime->header('X-PI-From');
572         my $d = _msg_date($mime);
573         $f = PublicInbox::Hval->new($f);
574         $d = PublicInbox::Hval->new($d);
575         $f = $f->as_html;
576         $d = $d->as_html . ' UTC';
577         my $midc = mid_compress(mid_clean($mid));
578         if ($cur) {
579                 if ($cur eq $midc) {
580                         delete $state->{cur};
581                         $$dst .= "$pfx` <b><a\nid=\"r\"\nhref=\"#t\">".
582                                  "[this message]</a></b> by $f @ $d\n";
583
584                         return;
585                 }
586         } else {
587                 $state->{next_msg} ||= $midc;
588         }
589
590         # Subject is never undef, this mail was loaded from
591         # our Xapian which would've resulted in '' if it were
592         # really missing (and Filter rejects empty subjects)
593         my $s = $mime->header('Subject');
594         my $h = $state->{srch}->subject_path($s);
595         if ($state->{seen}->{$h}) {
596                 $s = undef;
597         } else {
598                 $state->{seen}->{$h} = 1;
599                 $s = PublicInbox::Hval->new($s);
600                 $s = $s->as_html;
601         }
602         my $m = PublicInbox::Hval->new_msgid($mid);
603         $m = '../' . $m->as_href . '/';
604         if (defined $s) {
605                 $$dst .= "$pfx` <a\nhref=\"$m\">$s</a>\n" .
606                          "$pfx  $f @ $d\n";
607         } else {
608                 $$dst .= "$pfx` <a\nhref=\"$m\">$f @ $d</a>\n";
609         }
610 }
611
612 sub inline_dump {
613         my ($dst, $state, $node, $level) = @_;
614         return unless $node;
615         return if $state->{stopped};
616         if (my $mime = $node->message) {
617                 _inline_header($dst, $state, $mime, $level);
618         }
619         inline_dump($dst, $state, $node->child, $level+1);
620         inline_dump($dst, $state, $node->next, $level);
621 }
622
623 1;