]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
64a2086d349e843b644bf94c1797173f69153966
[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_compressed 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         my $srch = $ctx->{srch} if $ctx;
35         headers_to_html_header($mime, $full_pfx, $srch) .
36                 multipart_text_as_html($mime, $full_pfx) .
37                 '</pre><hr /><pre>' .
38                 html_footer($mime, 1, $full_pfx, $ctx) .
39                 $footer .
40                 '</pre></body></html>';
41 }
42
43 sub feed_entry {
44         my ($class, $mime, $full_pfx) = @_;
45
46         PRE_WRAP . multipart_text_as_html($mime, $full_pfx) . '</pre>';
47 }
48
49 # this is already inside a <pre>
50 sub index_entry {
51         my ($fh, $mime, $level, $state) = @_;
52         my $midx = $state->{anchor_idx}++;
53         my $ctx = $state->{ctx};
54         my $srch = $ctx->{srch};
55         my ($prev, $next) = ($midx - 1, $midx + 1);
56         my $part_nr = 0;
57         my $enc = enc_for($mime->header("Content-Type"));
58         my $subj = $mime->header('Subject');
59         my $header_obj = $mime->header_obj;
60
61         my $mid_raw = $header_obj->header('Message-ID');
62         my $id = anchor_for($mid_raw);
63         my $seen = $state->{seen};
64         $seen->{$id} = "#$id"; # save the anchor for later
65
66         my $mid = PublicInbox::Hval->new_msgid($mid_raw);
67         my $from = PublicInbox::Hval->new_oneline($mime->header('From'))->raw;
68         my @from = Email::Address->parse($from);
69         $from = $from[0]->name;
70
71         $from = PublicInbox::Hval->new_oneline($from)->as_html;
72         $subj = PublicInbox::Hval->new_oneline($subj)->as_html;
73         my $more = 'permalink';
74         my $root_anchor = $state->{root_anchor};
75         my $path = $root_anchor ? '../' : '';
76         my $href = $mid->as_href;
77         my $irt = $header_obj->header('In-Reply-To');
78         my ($anchor_idx, $anchor, $t_anchor);
79         if (defined $irt) {
80                 $anchor_idx = anchor_for($irt);
81                 $anchor = $seen->{$anchor_idx};
82                 $t_anchor = T_ANCHOR;
83         } else {
84                 $t_anchor = '';
85         }
86         if ($srch) {
87                 $subj = "<a\nhref=\"${path}t/$href.html#u\">$subj</a>";
88         }
89         if ($root_anchor && $root_anchor eq $id) {
90                 $subj = "<u\nid=\"u\">$subj</u>";
91         }
92
93         my $ts = $mime->header('X-PI-TS');
94         unless (defined $ts) {
95                 $ts = msg_timestamp($mime);
96         }
97         $ts = POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
98
99         my $rv = "<table\nsummary=l$level><tr>";
100         if ($level) {
101                 $rv .= '<td><pre>' . ('  ' x $level) . '</pre></td>';
102         }
103         $rv .= "<td\nid=s$midx>" . PRE_WRAP;
104         $rv .= "<b\nid=\"$id\">$subj</b>\n";
105         $rv .= "- by $from @ $ts UTC - ";
106         $rv .= "<a\nhref=\"#s$next\">next</a>";
107         if ($prev >= 0) {
108                 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
109         }
110         $fh->write($rv .= "\n\n");
111
112         my ($fhref, $more_ref);
113         my $mhref = "${path}m/$href.html";
114         if ($level > 0) {
115                 $fhref = "${path}f/$href.html";
116                 $more_ref = \$more;
117         }
118         # scan through all parts, looking for displayable text
119         $mime->walk_parts(sub {
120                 index_walk($fh, $_[0], $enc, \$part_nr, $fhref, $more_ref);
121         });
122         $mime->body_set('');
123
124         my $txt = "${path}m/$href.txt";
125         $rv = "\n<a\nhref=\"$mhref\">$more</a> <a\nhref=\"$txt\">raw</a> ";
126         $rv .= html_footer($mime, 0, undef, $ctx);
127
128         if (defined $irt) {
129                 unless (defined $anchor) {
130                         my $v = PublicInbox::Hval->new_msgid($irt);
131                         $v = $v->as_href;
132                         $anchor = "${path}m/$v.html";
133                         $seen->{$anchor_idx} = $anchor;
134                 }
135                 $rv .= " <a\nhref=\"$anchor\">parent</a>";
136         }
137
138         if ($srch) {
139                 $rv .= " <a\nhref=\"${path}t/$href.html$t_anchor\">" .
140                        "threadlink</a>";
141         }
142
143         $fh->write($rv .= '</pre></td></tr></table>');
144 }
145
146 sub thread_html {
147         my ($ctx, $foot, $srch) = @_;
148         sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
149 }
150
151 # only private functions below.
152
153 sub emit_thread_html {
154         my ($cb, $ctx, $foot, $srch) = @_;
155         my $mid = mid_compressed($ctx->{mid});
156         my $res = $srch->get_thread($mid);
157         my $msgs = load_results($res);
158         my $nr = scalar @$msgs;
159         return missing_thread($cb) if $nr == 0;
160         my $fh = $cb->([200,['Content-Type'=>'text/html; charset=UTF-8']]);
161         my $th = thread_results($msgs);
162         my $state = {
163                 ctx => $ctx,
164                 seen => {},
165                 root_anchor => anchor_for($mid),
166                 anchor_idx => 0,
167         };
168         {
169                 require PublicInbox::GitCatFile;
170                 my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
171                 thread_entry($fh, $git, $state, $_, 0) for $th->rootset;
172         }
173         my $final_anchor = $state->{anchor_idx};
174         my $next = "<a\nid=\"s$final_anchor\">";
175         $next .= $final_anchor == 1 ? 'only message in' : 'end of';
176         $next .= " thread</a>, back to <a\nhref=\"../\">index</a>\n";
177         $mid = PublicInbox::Hval->new_msgid($mid)->as_href;
178         $next .= "download: <a\nhref=\"$mid.mbox.gz\">mbox.gz</a>\n\n";
179         $fh->write("<hr />" . PRE_WRAP . $next . $foot .
180                    "</pre></body></html>");
181         $fh->close;
182 }
183
184 sub index_walk {
185         my ($fh, $part, $enc, $part_nr, $fhref, $more) = @_;
186         my $s = add_text_body($enc, $part, $part_nr, $fhref);
187
188         if ($more) {
189                 # drop the remainder of git patches, they're usually better
190                 # to review when the full message is viewed
191                 $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
192
193                 # Drop signatures
194                 $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
195         }
196
197         # kill any leading or trailing whitespace lines
198         $s =~ s/^\s*$//sgm;
199         $s =~ s/\s+\z//s;
200
201         if (length $s) {
202                 # kill per-line trailing whitespace
203                 $s =~ s/[ \t]+$//sgm;
204                 $s .= "\n" unless $s =~ /\n\z/s;
205         }
206         $fh->write($s);
207 }
208
209 sub enc_for {
210         my ($ct, $default) = @_;
211         $default ||= $enc_utf8;
212         defined $ct or return $default;
213         my $ct_parsed = parse_content_type($ct);
214         if ($ct_parsed) {
215                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
216                         my $enc = find_encoding($charset);
217                         return $enc if $enc;
218                 }
219         }
220         $default;
221 }
222
223 sub multipart_text_as_html {
224         my ($mime, $full_pfx, $srch) = @_;
225         my $rv = "";
226         my $part_nr = 0;
227         my $enc = enc_for($mime->header("Content-Type"));
228
229         # scan through all parts, looking for displayable text
230         $mime->walk_parts(sub {
231                 my ($part) = @_;
232                 $rv .= add_text_body($enc, $part, \$part_nr, $full_pfx);
233         });
234         $mime->body_set('');
235         $rv;
236 }
237
238 sub add_filename_line {
239         my ($enc, $fn) = @_;
240         my $len = 72;
241         my $pad = "-";
242         $fn = $enc->decode($fn);
243         $len -= length($fn);
244         $pad x= ($len/2) if ($len > 0);
245         "$pad " . ascii_html($fn) . " $pad\n";
246 }
247
248 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://[@\w\+\&\?\.\%\;/#=-]+)!;
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, $srch) = @_;
346
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) && length($v) 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\nhref=\"../t/$mid_href.html\">";
365                                 $rv .= $v->as_html . "</a>\n";
366                                 next;
367                         }
368                 }
369                 $rv .= "$h: " . $v->as_html . "\n";
370
371         }
372
373         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
374         $mid_href = "../m/$mid_href" unless $full_pfx;
375         $rv .= "(<a\nhref=\"$mid_href.txt\">raw</a>)\n";
376
377         my $irt = $header_obj->header('In-Reply-To');
378         if (defined $irt) {
379                 my $v = PublicInbox::Hval->new_msgid($irt);
380                 my $html = $v->as_html;
381                 my $href = $v->as_href;
382                 $rv .= "In-Reply-To: &lt;";
383                 $rv .= "<a\nhref=\"$href.html\">$html</a>&gt;\n";
384         }
385
386         my $refs = $header_obj->header('References');
387         if ($refs) {
388                 # avoid redundant URLs wasting bandwidth
389                 my %seen;
390                 $seen{mid_clean($irt)} = 1 if defined $irt;
391                 my @refs;
392                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
393                 foreach my $ref (@raw_refs) {
394                         next if $seen{$ref};
395                         $seen{$ref} = 1;
396                         push @refs, linkify_ref($ref);
397                 }
398
399                 if (@refs) {
400                         $rv .= 'References: '. join(' ', @refs) . "\n";
401                 }
402         }
403
404         $rv .= "\n";
405
406         ("<html><head><title>".  join(' - ', @title) .
407          '</title></head><body>' . PRE_WRAP . $rv);
408 }
409
410 sub html_footer {
411         my ($mime, $standalone, $full_pfx, $ctx) = @_;
412         my %cc; # everyone else
413         my $to; # this is the From address
414
415         foreach my $h (qw(From To Cc)) {
416                 my $v = $mime->header($h);
417                 defined($v) && length($v) or next;
418                 my @addrs = Email::Address->parse($v);
419                 foreach my $recip (@addrs) {
420                         my $address = $recip->address;
421                         my $dst = lc($address);
422                         $cc{$dst} ||= $address;
423                         $to ||= $dst;
424                 }
425         }
426         Email::Address->purge_cache if $standalone;
427
428         my $subj = $mime->header('Subject') || '';
429         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
430         my $mid = $mime->header('Message-ID');
431         my $irt = uri_escape_utf8($mid);
432         delete $cc{$to};
433         $to = uri_escape_utf8($to);
434         $subj = uri_escape_utf8($subj);
435
436         my $cc = uri_escape_utf8(join(',', sort values %cc));
437         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
438
439         my $srch = $ctx->{srch} if $ctx;
440         my $idx = $standalone ? " <a\nhref=\"../\">index</a>" : '';
441         if ($idx && $srch) {
442                 $irt = $mime->header('In-Reply-To') || '';
443                 $mid = mid_compressed(mid_clean($mid));
444                 my $t_anchor = length $irt ? T_ANCHOR : '';
445                 $idx = " <a\nhref=\"../t/$mid.html$t_anchor\">".
446                        "threadlink</a>$idx";
447                 my $res = $srch->get_followups($mid);
448                 if (my $c = $res->{total}) {
449                         my $nr = scalar @{$res->{msgs}};
450                         if ($nr < $c) {
451                                 $c = "$nr of $c followups";
452                         } else {
453                                 $c = $c == 1 ? '1 followup' : "$c followups";
454                         }
455                         $idx .= "\n$c:\n";
456                         $res->{srch} = $srch;
457                         thread_followups(\$idx, $mime, $res);
458                 } else {
459                         $idx .= "\n(no followups, yet)\n";
460                 }
461                 if ($irt) {
462                         $irt = PublicInbox::Hval->new_msgid($irt);
463                         $irt = $irt->as_href;
464                         $irt = "<a\nhref=\"$irt\">parent</a> ";
465                 } else {
466                         $irt = ' ' x length('parent ');
467                 }
468         } else {
469                 $irt = '';
470         }
471
472         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
473 }
474
475 sub linkify_ref {
476         my $v = PublicInbox::Hval->new_msgid($_[0]);
477         my $html = $v->as_html;
478         my $href = $v->as_href;
479         "&lt;<a\nhref=\"$href.html\">$html</a>&gt;";
480 }
481
482 sub anchor_for {
483         my ($msgid) = @_;
484         my $id = $msgid;
485         if ($id !~ /\A[a-f0-9]{40}\z/) {
486                 $id = mid_compressed(mid_clean($id), 1);
487         }
488         'm' . $id;
489 }
490
491 sub simple_dump {
492         my ($dst, $root, $node, $level) = @_;
493         return unless $node;
494         # $root = [ undef, \%seen, $srch ];
495         if (my $x = $node->message) {
496                 my $f = $x->header('X-PI-From');
497                 my $d = $x->header('X-PI-Date');
498                 if (defined $f && defined $d) {
499                         my $mid = $x->header('Message-ID');
500                         my $pfx = '  ' x $level;
501                         $$dst .= $pfx;
502                         my $s = $x->header('Subject');
503                         my $h = $root->[2]->subject_path($s);
504                         if ($root->[1]->{$h}) {
505                                 $s = '';
506                         } else {
507                                 $root->[1]->{$h} = 1;
508                                 $s = PublicInbox::Hval->new($s);
509                                 $s = $s->as_html;
510                         }
511                         my $m = PublicInbox::Hval->new_msgid($mid);
512                         $f = PublicInbox::Hval->new($f);
513                         $d = PublicInbox::Hval->new($d);
514                         $m = $m->as_href . '.html';
515                         $f = $f->as_html;
516                         $d = $d->as_html . ' UTC';
517                         if (length($s) == 0) {
518                                 $$dst .= "` <a\nhref=\"$m\">$f @ $d</a>\n";
519                         } else {
520                                 $$dst .= "` <a\nhref=\"$m\">$s</a>\n" .
521                                      "$pfx  by $f @ $d\n";
522                         }
523                 }
524         }
525         simple_dump($dst, $root, $node->child, $level+1);
526         simple_dump($dst, $root, $node->next, $level);
527 }
528
529 sub thread_followups {
530         my ($dst, $root, $res) = @_;
531         $root->header_set('X-PI-TS', '0');
532         my $msgs = load_results($res);
533         push @$msgs, $root;
534         my $th = thread_results($msgs);
535         my $srch = $res->{srch};
536         my $subj = $srch->subject_path($root->header('Subject'));
537         my %seen = ($subj => 1);
538         $root = [ undef, \%seen, $srch ];
539         simple_dump($dst, $root, $_, 0) for $th->rootset;
540 }
541
542 sub thread_html_head {
543         my ($mime) = @_;
544         my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
545         $s = $s->as_html;
546         "<html><head><title>$s</title></head><body>";
547 }
548
549 sub thread_entry {
550         my ($fh, $git, $state, $node, $level) = @_;
551         return unless $node;
552         if (my $mime = $node->message) {
553
554                 # lazy load the full message from mini_mime:
555                 my $path = mid2path(mid_clean($mime->header('Message-ID')));
556                 $mime = eval { Email::MIME->new($git->cat_file("HEAD:$path")) };
557                 if ($mime) {
558                         if ($state->{anchor_idx} == 0) {
559                                 $fh->write(thread_html_head($mime));
560                         }
561                         index_entry($fh, $mime, $level, $state);
562                 }
563         }
564         thread_entry($fh, $git, $state, $node->child, $level + 1);
565         thread_entry($fh, $git, $state, $node->next, $level);
566 }
567
568 sub load_results {
569         my ($res) = @_;
570
571         [ map { $_->mini_mime } @{delete $res->{msgs}} ];
572 }
573
574 sub msg_timestamp {
575         my ($mime) = @_;
576         my $ts = eval { str2time($mime->header('Date')) };
577         defined($ts) ? $ts : 0;
578 }
579
580 sub thread_results {
581         my ($msgs) = @_;
582         require PublicInbox::Thread;
583         my $th = PublicInbox::Thread->new(@$msgs);
584         $th->thread;
585         no warnings 'once';
586         $th->order(*PublicInbox::Thread::sort_ts);
587         $th
588 }
589
590 sub missing_thread {
591         my ($cb) = @_;
592         my $title = 'Thread does not exist';
593         $cb->([404, ['Content-Type' => 'text/html']])->write(<<EOF);
594 <html><head><title>$title</title></head><body><pre>$title
595 <a href="../">Return to index</a></pre></body></html>
596 EOF
597 }
598
599 1;