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