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