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