]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
completely revamp URL structure to shorten permalinks
[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}$href/t/#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}$href/";
105         if ($level > 0) {
106                 $fhref = "${path}$href/f/";
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}$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}$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=\"../t.mbox.gz\">mbox.gz</a>";
164         $next .= " / <a\nhref=\"../t.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                                 my $p = $full_pfx ? '' : '../';
353                                 $rv .= "$h: <a\nid=\"t\"\nhref=\"${p}t/#u\">";
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' : '../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, $full_pfx) = @_;
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         my $upfx = $full_pfx ? '' : '../';
387
388         $$dst .= "\n\n~$nr messages in thread: ".
389                  "(<a\nhref=\"${upfx}t/#u\">expand</a>)\n";
390         my $subj = $srch->subject_path($cur->header('Subject'));
391         my $state = {
392                 seen => { $subj => 1 },
393                 srch => $srch,
394                 cur => $mid,
395         };
396         for (thread_results(load_results($res))->rootset) {
397                 inline_dump($dst, $state, $upfx, $_, 0);
398         }
399         $state->{next_msg};
400 }
401
402 sub _parent_headers_nosrch {
403         my ($header_obj) = @_;
404         my $rv = '';
405
406         my $irt = $header_obj->header('In-Reply-To');
407         if (defined $irt) {
408                 my $v = PublicInbox::Hval->new_msgid($irt);
409                 my $html = $v->as_html;
410                 my $href = $v->as_href;
411                 $rv .= "In-Reply-To: &lt;";
412                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
413         }
414
415         my $refs = $header_obj->header('References');
416         if ($refs) {
417                 # avoid redundant URLs wasting bandwidth
418                 my %seen;
419                 $seen{mid_clean($irt)} = 1 if defined $irt;
420                 my @refs;
421                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
422                 foreach my $ref (@raw_refs) {
423                         next if $seen{$ref};
424                         $seen{$ref} = 1;
425                         push @refs, linkify_ref($ref);
426                 }
427
428                 if (@refs) {
429                         $rv .= 'References: '. join(' ', @refs) . "\n";
430                 }
431         }
432         $rv;
433 }
434
435 sub html_footer {
436         my ($mime, $standalone, $full_pfx, $ctx) = @_;
437         my %cc; # everyone else
438         my $to; # this is the From address
439
440         foreach my $h (qw(From To Cc)) {
441                 my $v = $mime->header($h);
442                 defined($v) && ($v ne '') or next;
443                 my @addrs = Email::Address->parse($v);
444                 foreach my $recip (@addrs) {
445                         my $address = $recip->address;
446                         my $dst = lc($address);
447                         $cc{$dst} ||= $address;
448                         $to ||= $dst;
449                 }
450         }
451         Email::Address->purge_cache if $standalone;
452
453         my $subj = $mime->header('Subject') || '';
454         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
455         my $mid = $mime->header('Message-ID');
456         my $irt = uri_escape_utf8($mid);
457         delete $cc{$to};
458         $to = uri_escape_utf8($to);
459         $subj = uri_escape_utf8($subj);
460
461         my $cc = uri_escape_utf8(join(',', sort values %cc));
462         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
463
464         my $srch = $ctx->{srch} if $ctx;
465         my $upfx = $full_pfx ? '../' : '../../';
466         my $idx = $standalone ? "<a\nhref=\"$upfx\">index</a>" : '';
467         if ($idx && $srch) {
468                 my $next = thread_inline(\$idx, $ctx, $mime, $full_pfx);
469                 $irt = $mime->header('In-Reply-To');
470                 if (defined $irt) {
471                         $irt = PublicInbox::Hval->new_msgid($irt);
472                         $irt = $irt->as_href;
473                         $irt = "<a\nhref=\"$upfx$irt/\">parent</a> ";
474                 } else {
475                         $irt = ' ' x length('parent ');
476                 }
477                 if ($next) {
478                         $irt .= "<a\nhref=\"$upfx$next/\">next</a> ";
479                 } else {
480                         $irt .= '     ';
481                 }
482         } else {
483                 $irt = '';
484         }
485
486         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
487 }
488
489 sub linkify_ref {
490         my $v = PublicInbox::Hval->new_msgid($_[0]);
491         my $html = $v->as_html;
492         my $href = $v->as_href;
493         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
494 }
495
496 sub anchor_for {
497         my ($msgid) = @_;
498         my $id = $msgid;
499         if ($id !~ /\A[a-f0-9]{40}\z/) {
500                 $id = mid_compress(mid_clean($id), 1);
501         }
502         'm' . $id;
503 }
504
505 sub thread_html_head {
506         my ($mime) = @_;
507         my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
508         $s = $s->as_html;
509         "<html><head><title>$s</title></head><body>";
510 }
511
512 sub thread_entry {
513         my ($fh, $git, $state, $node, $level) = @_;
514         return unless $node;
515         if (my $mime = $node->message) {
516
517                 # lazy load the full message from mini_mime:
518                 my $path = mid2path(mid_clean($mime->header('Message-ID')));
519                 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
520                 if ($mime) {
521                         if ($state->{anchor_idx} == 0) {
522                                 $fh->write(thread_html_head($mime));
523                         }
524                         index_entry($fh, $mime, $level, $state);
525                 }
526         }
527         thread_entry($fh, $git, $state, $node->child, $level + 1);
528         thread_entry($fh, $git, $state, $node->next, $level);
529 }
530
531 sub load_results {
532         my ($res) = @_;
533
534         [ map { $_->mini_mime } @{delete $res->{msgs}} ];
535 }
536
537 sub msg_timestamp {
538         my ($mime) = @_;
539         my $ts = eval { str2time($mime->header('Date')) };
540         defined($ts) ? $ts : 0;
541 }
542
543 sub thread_results {
544         my ($msgs) = @_;
545         require PublicInbox::Thread;
546         my $th = PublicInbox::Thread->new(@$msgs);
547         $th->thread;
548         no warnings 'once';
549         $th->order(*PublicInbox::Thread::sort_ts);
550         $th
551 }
552
553 sub missing_thread {
554         my ($cb) = @_;
555         my $title = 'Thread does not exist';
556         $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
557 <html><head><title>$title</title></head><body><pre>$title
558 <a href="../../">Return to index</a></pre></body></html>
559 EOF
560 }
561
562 sub _msg_date {
563         my ($mime) = @_;
564         my $ts = $mime->header('X-PI-TS') || msg_timestamp($mime);
565         POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
566 }
567
568 sub _inline_header {
569         my ($dst, $state, $upfx, $mime, $level) = @_;
570         my $pfx = '  ' x $level;
571
572         my $cur = $state->{cur};
573         my $mid = $mime->header('Message-ID');
574         my $f = $mime->header('X-PI-From');
575         my $d = _msg_date($mime);
576         $f = PublicInbox::Hval->new($f);
577         $d = PublicInbox::Hval->new($d);
578         $f = $f->as_html;
579         $d = $d->as_html . ' UTC';
580         my $midc = mid_compress(mid_clean($mid));
581         if ($cur) {
582                 if ($cur eq $midc) {
583                         delete $state->{cur};
584                         $$dst .= "$pfx` <b><a\nid=\"r\"\nhref=\"#t\">".
585                                  "[this message]</a></b> by $f @ $d\n";
586
587                         return;
588                 }
589         } else {
590                 $state->{next_msg} ||= $midc;
591         }
592
593         # Subject is never undef, this mail was loaded from
594         # our Xapian which would've resulted in '' if it were
595         # really missing (and Filter rejects empty subjects)
596         my $s = $mime->header('Subject');
597         my $h = $state->{srch}->subject_path($s);
598         if ($state->{seen}->{$h}) {
599                 $s = undef;
600         } else {
601                 $state->{seen}->{$h} = 1;
602                 $s = PublicInbox::Hval->new($s);
603                 $s = $s->as_html;
604         }
605         my $m = PublicInbox::Hval->new_msgid($mid);
606         $m = $upfx . '../' . $m->as_href . '/';
607         if (defined $s) {
608                 $$dst .= "$pfx` <a\nhref=\"$m\">$s</a>\n" .
609                          "$pfx  $f @ $d\n";
610         } else {
611                 $$dst .= "$pfx` <a\nhref=\"$m\">$f @ $d</a>\n";
612         }
613 }
614
615 sub inline_dump {
616         my ($dst, $state, $upfx, $node, $level) = @_;
617         return unless $node;
618         return if $state->{stopped};
619         if (my $mime = $node->message) {
620                 _inline_header($dst, $state, $upfx, $mime, $level);
621         }
622         inline_dump($dst, $state, $upfx, $node->child, $level+1);
623         inline_dump($dst, $state, $upfx, $node->next, $level);
624 }
625
626 1;