]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
favor /t/ to /s/, since subjects may change mid-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_WRAP .
37                 html_footer($mime, 1, $full_pfx, $srch) . $footer .
38                 '</pre></body></html>';
39 }
40
41 sub feed_entry {
42         my ($class, $mime, $full_pfx) = @_;
43
44         PRE_WRAP . multipart_text_as_html($mime, $full_pfx) . '</pre>';
45 }
46
47 # this is already inside a <pre>
48 # state = [ time, seen = {}, first_commit, page_nr = 0 ]
49 sub index_entry {
50         my (undef, $mime, $level, $state) = @_;
51         my ($srch, $seen, $first_commit) = @$state;
52         my $midx = $state->[3]++;
53         my ($prev, $next) = ($midx - 1, $midx + 1);
54         my $rv = '';
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 $pfx = ('  ' x $level);
73         my $root_anchor = $seen->{root_anchor};
74         my $path;
75         my $more = 'permalink';
76         if ($root_anchor) {
77                 $path = '../';
78         } else {
79                 $path = '';
80         }
81         my $href = $mid->as_href;
82         my $irt = $header_obj->header_raw('In-Reply-To');
83         my ($anchor_idx, $anchor, $t_anchor);
84         if (defined $irt) {
85                 $anchor_idx = anchor_for($irt);
86                 $anchor = $seen->{$anchor_idx};
87                 $t_anchor = T_ANCHOR;
88         } else {
89                 $t_anchor = '';
90         }
91
92         if (defined $srch) {
93                 $subj = "<a\nhref=\"${path}t/$href.html#u\">$subj</a>";
94         }
95         if ($root_anchor && $root_anchor eq $id) {
96                 $subj = "<u\nid=\"u\">$subj</u>";
97         }
98
99         my $ts = $mime->header('X-PI-TS');
100         my $fmt = '%Y-%m-%d %H:%M UTC';
101         $ts = POSIX::strftime($fmt, gmtime($ts));
102
103         $rv .= "$pfx<b\nid=\"$id\">$subj</b>\n$pfx";
104         $rv .= "- by $from @ $ts - ";
105         $rv .= "<a\nid=\"s$midx\"\nhref=\"#s$next\">next</a>";
106         if ($prev >= 0) {
107                 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
108         }
109         $rv .= "\n\n";
110
111         my $mhref = "${path}m/$href.html";
112         my $fhref = "${path}f/$href.html";
113         # scan through all parts, looking for displayable text
114         $mime->walk_parts(sub {
115                 $rv .= index_walk($_[0], $pfx, $enc_msg, $part_nr, $fhref,
116                                   \$more);
117                 $part_nr++;
118         });
119
120         $rv .= "\n$pfx<a\nhref=\"$mhref\">$more</a> ";
121         my $txt = "${path}m/$href.txt";
122         $rv .= "<a\nhref=\"$txt\">raw</a> ";
123         $rv .= html_footer($mime, 0);
124
125         if (defined $irt) {
126                 unless (defined $anchor) {
127                         my $v = PublicInbox::Hval->new_msgid($irt);
128                         $v = $v->as_href;
129                         $anchor = "${path}m/$v.html";
130                         $seen->{$anchor_idx} = $anchor;
131                 }
132                 $rv .= " <a\nhref=\"$anchor\">parent</a>";
133         }
134
135         if ($srch) {
136                 $rv .= " <a\nhref=\"${path}t/$href.html$t_anchor\">thread</a>";
137         }
138
139         $rv . "\n\n";
140 }
141
142 sub thread_html {
143         my (undef, $ctx, $foot, $srch) = @_;
144         my $mid = mid_compressed($ctx->{mid});
145         my $res = $srch->get_thread($mid);
146         my $rv = '';
147         my $msgs = load_results($ctx, $res);
148         my $nr = scalar @$msgs;
149         return $rv if $nr == 0;
150         require PublicInbox::Thread;
151         my $th = PublicInbox::Thread->new(@$msgs);
152         $th->thread;
153         $th->order(*PublicInbox::Thread::sort_ts);
154         my $state = [ $srch, { root_anchor => anchor_for($mid) }, undef, 0 ];
155         thread_entry(\$rv, $state, $_, 0) for $th->rootset;
156         my $final_anchor = $state->[3];
157         my $next = "<a\nid=\"s$final_anchor\">end of thread</a>\n";
158
159         $rv .= "</pre><hr />" . PRE_WRAP . $next . $foot . "</pre>";
160 }
161
162 sub subject_path_html {
163         my (undef, $ctx, $foot, $srch) = @_;
164         my $path = $ctx->{subject_path};
165         my $res = $srch->get_subject_path($path);
166         my $rv = '';
167         my $msgs = load_results($ctx, $res);
168         my $nr = scalar @$msgs;
169         return $rv if $nr == 0;
170         require PublicInbox::Thread;
171         my $th = PublicInbox::Thread->new(@$msgs);
172         $th->thread;
173         $th->order(*PublicInbox::Thread::sort_ts);
174         my $state = [ $srch, { root_anchor => 'dummy' }, undef, 0 ];
175         thread_entry(\$rv, $state, $_, 0) for $th->rootset;
176         my $final_anchor = $state->[3];
177         my $next = "<a\nid=\"s$final_anchor\">end of thread</a>\n";
178
179         $rv .= "</pre><hr />" . PRE_WRAP . $next . $foot . "</pre>";
180 }
181
182 # only private functions below.
183
184 sub index_walk {
185         my ($part, $pfx, $enc_msg, $part_nr, $fhref, $more) = @_;
186         my $rv = '';
187         return $rv if $part->subparts; # walk_parts already recurses
188         my $ct = $part->content_type;
189
190         # account for filter bugs...
191         return if defined $ct && $ct =~ m!\btext/[xh]+tml\b!i;
192
193         my $enc = enc_for($ct, $enc_msg);
194
195         if ($part_nr > 0) {
196                 my $fn = $part->filename;
197                 defined($fn) or $fn = "part #" . ($part_nr + 1);
198                 $rv .= $pfx . add_filename_line($enc->decode($fn));
199         }
200
201         my $s = add_text_body_short($enc, $part, $part_nr, $fhref);
202
203         # drop the remainder of git patches, they're usually better
204         # to review when the full message is viewed
205         $s =~ s!^---+\n.*\z!!ms and $$more = 'more...';
206
207         # Drop signatures
208         $s =~ s/^-- \n.*\z//ms and $$more = 'more...';
209
210         # kill any leading or trailing whitespace lines
211         $s =~ s/^\s*$//sgm;
212         $s =~ s/\s+\z//s;
213
214         if (length $s) {
215                 # add prefix:
216                 $s =~ s/^/$pfx/sgm;
217
218                 # kill per-line trailing whitespace
219                 $s =~ s/[ \t]+$//sgm;
220
221                 $rv .= $s . "\n";
222         }
223         $rv;
224 }
225
226 sub enc_for {
227         my ($ct, $default) = @_;
228         $default ||= $enc_utf8;
229         defined $ct or return $default;
230         my $ct_parsed = parse_content_type($ct);
231         if ($ct_parsed) {
232                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
233                         my $enc = find_encoding($charset);
234                         return $enc if $enc;
235                 }
236         }
237         $default;
238 }
239
240 sub multipart_text_as_html {
241         my ($mime, $full_pfx, $srch) = @_;
242         my $rv = "";
243         my $part_nr = 0;
244         my $enc_msg = enc_for($mime->header("Content-Type"));
245
246         # scan through all parts, looking for displayable text
247         $mime->walk_parts(sub {
248                 my ($part) = @_;
249                 return if $part->subparts; # walk_parts already recurses
250                 my $ct = $part->content_type;
251
252                 # account for filter bugs...
253                 return if defined $ct && $ct =~ m!\btext/[xh]+tml\b!i;
254
255                 my $enc = enc_for($ct, $enc_msg);
256
257                 if ($part_nr > 0) {
258                         my $fn = $part->filename;
259                         defined($fn) or $fn = "part #" . ($part_nr + 1);
260                         $rv .= add_filename_line($enc->decode($fn));
261                 }
262
263                 if (defined $full_pfx) {
264                         $rv .= add_text_body_short($enc, $part, $part_nr,
265                                                 $full_pfx);
266                 } else {
267                         $rv .= add_text_body_full($enc, $part, $part_nr);
268                 }
269                 $rv .= "\n" unless $rv =~ /\n\z/s;
270                 ++$part_nr;
271         });
272         $rv;
273 }
274
275 sub add_filename_line {
276         my ($fn) = @_;
277         my $len = 72;
278         my $pad = "-";
279
280         $len -= length($fn);
281         $pad x= ($len/2) if ($len > 0);
282         "$pad " . ascii_html($fn) . " $pad\n";
283 }
284
285 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://[@\w\+\&\?\.\%\;/#=-]+)!;
286
287 sub linkify {
288         # no newlines added here since it'd break the splitting we do
289         # to fold quotes
290         $_[0] =~ s!$LINK_RE!<a href="$1">$1</a>!g;
291 }
292
293 sub add_text_body_short {
294         my ($enc, $part, $part_nr, $full_pfx) = @_;
295         my $n = 0;
296         my $s = ascii_html($enc->decode($part->body));
297         linkify($s);
298         $s =~ s!^((?:(?:&gt;[^\n]*)\n)+)!
299                 my $cur = $1;
300                 my @lines = split(/\n/, $cur);
301                 if (@lines > MAX_INLINE_QUOTED) {
302                         # show a short snippet of quoted text
303                         $cur = join(' ', @lines);
304                         $cur =~ s/^&gt;\s*//;
305
306                         my @sum = split(/\s+/, $cur);
307                         $cur = '';
308                         do {
309                                 my $tmp = shift(@sum);
310                                 my $len = length($tmp) + length($cur);
311                                 if ($len > MAX_TRUNC_LEN) {
312                                         @sum = ();
313                                 } else {
314                                         $cur .= $tmp . ' ';
315                                 }
316                         } while (@sum && length($cur) < MAX_TRUNC_LEN);
317                         $cur =~ s/ \z/ .../;
318                         "&gt; &lt;<a\nhref=\"${full_pfx}#q${part_nr}_" . $n++ .
319                                 "\">$cur<\/a>&gt;\n";
320                 } else {
321                         $cur;
322                 }
323         !emg;
324         $s;
325 }
326
327 sub add_text_body_full {
328         my ($enc, $part, $part_nr) = @_;
329         my $n = 0;
330         my $s = ascii_html($enc->decode($part->body));
331         linkify($s);
332         $s =~ s!^((?:(?:&gt;[^\n]*)\n)+)!
333                 my $cur = $1;
334                 my @lines = split(/\n/, $cur);
335                 if (@lines > MAX_INLINE_QUOTED) {
336                         "<a\nid=q${part_nr}_" . $n++ . ">$cur</a>";
337                 } else {
338                         $cur;
339                 }
340         !emg;
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_raw('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_raw('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_raw('References');
387         if ($refs) {
388                 $refs =~ s/\s*\Q$irt\E\s*// if (defined $irt);
389                 my @refs = ($refs =~ /<([^>]+)>/g);
390                 if (@refs) {
391                         $rv .= 'References: '. linkify_refs(@refs) . "\n";
392                 }
393         }
394
395         $rv .= "\n";
396
397         ("<html><head><title>".  join(' - ', @title) .
398          '</title></head><body>' . PRE_WRAP . $rv);
399 }
400
401 sub html_footer {
402         my ($mime, $standalone, $full_pfx, $srch) = @_;
403         my %cc; # everyone else
404         my $to; # this is the From address
405
406         foreach my $h (qw(From To Cc)) {
407                 my $v = $mime->header($h);
408                 defined($v) && length($v) or next;
409                 my @addrs = Email::Address->parse($v);
410                 foreach my $recip (@addrs) {
411                         my $address = $recip->address;
412                         my $dst = lc($address);
413                         $cc{$dst} ||= $address;
414                         $to ||= $dst;
415                 }
416         }
417         Email::Address->purge_cache if $standalone;
418
419         my $subj = $mime->header('Subject') || '';
420         $subj = "Re: $subj" unless $subj =~ /\bRe:/;
421         my $mid = $mime->header_obj->header_raw('Message-ID');
422         my $irt = uri_escape_utf8($mid);
423         delete $cc{$to};
424         $to = uri_escape_utf8($to);
425         $subj = uri_escape_utf8($subj);
426
427         my $cc = uri_escape_utf8(join(',', sort values %cc));
428         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
429
430         my $idx = $standalone ? " <a\nhref=\"../\">index</a>" : '';
431         if ($idx && $srch) {
432                 $irt = $mime->header_obj->header_raw('In-Reply-To') || '';
433                 $mid = mid_compressed(mid_clean($mid));
434                 my $t_anchor = length $irt ? T_ANCHOR : '';
435                 $idx = " <a\nhref=\"../t/$mid.html$t_anchor\">thread</a>$idx";
436                 my $res = $srch->get_replies($mid);
437                 if (my $c = $res->{count}) {
438                         $c = $c == 1 ? '1 reply' : "$c replies";
439                         $idx .= "\n$c:\n";
440                         thread_replies(\$idx, $mime, $res);
441                 } else {
442                         $idx .= "\n(no replies yet)\n";
443                 }
444                 if ($irt) {
445                         $irt = PublicInbox::Hval->new_msgid($irt);
446                         $irt = $irt->as_href;
447                         $irt = "<a\nhref=\"$irt\">parent</a> ";
448                 } else {
449                         $irt = ' ' x length('parent ');
450                 }
451         } else {
452                 $irt = '';
453         }
454
455         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
456 }
457
458 sub linkify_refs {
459         join(' ', map {
460                 my $v = PublicInbox::Hval->new_msgid($_);
461                 my $html = $v->as_html;
462                 my $href = $v->as_href;
463                 "&lt;<a\nhref=\"$href.html\">$html</a>&gt;";
464         } @_);
465 }
466
467 sub anchor_for {
468         my ($msgid) = @_;
469         'm' . mid_compressed(mid_clean($msgid));
470 }
471
472 sub simple_dump {
473         my ($dst, $root, $node, $level) = @_;
474         my $pfx = '  ' x $level;
475         $$dst .= $pfx;
476         if (my $x = $node->message) {
477                 my $mid = $x->header('Message-ID');
478                 if ($root->[0] ne $mid) {
479                         my $s = $x->header('Subject');
480                         my $h = hash_subj($s);
481                         if ($root->[1]->{$h}) {
482                                 $s = '';
483                         } else {
484                                 $root->[1]->{$h} = 1;
485                                 $s = PublicInbox::Hval->new($s);
486                                 $s = $s->as_html;
487                         }
488                         my $m = PublicInbox::Hval->new_msgid($mid);
489                         my $f = PublicInbox::Hval->new($x->header('X-PI-From'));
490                         my $d = PublicInbox::Hval->new($x->header('X-PI-Date'));
491                         $m = $m->as_href . '.html';
492                         $f = $f->as_html;
493                         $d = $d->as_html . ' UTC';
494                         if (length($s) == 0) {
495                                 $$dst .= "` <a\nhref=\"$m\">$f @ $d</a>\n";
496                         } else {
497                                 $$dst .= "` <a\nhref=\"$m\">$s</a>\n" .
498                                      "$pfx  by $f @ $d\n";
499                         }
500                 }
501         }
502         simple_dump($dst, $root, $node->child, $level + 1) if $node->child;
503         simple_dump($dst, $root, $node->next, $level) if $node->next;
504 }
505
506 sub hash_subj {
507         my ($subj) = @_;
508         $subj =~ s/\A\s+//;
509         $subj =~ s/\s+\z//;
510         $subj =~ s/^(?:re|aw):\s*//i; # remove reply prefix (aw: German)
511         $subj =~ s/\s+/ /;
512         Digest::SHA::sha1($subj);
513 }
514
515 sub thread_replies {
516         my ($dst, $root, $res) = @_;
517         my @msgs = map { $_->mini_mime } @{$res->{msgs}};
518         foreach (@{$res->{msgs}}) {
519                 print STDERR "smsg->path: <", $_->path, ">\n";
520         }
521         require PublicInbox::Thread;
522         $root->header_set('X-PI-TS', '0');
523         my $th = PublicInbox::Thread->new($root, @msgs);
524         $th->thread;
525         $th->order(*PublicInbox::Thread::sort_ts);
526         $root = [ $root->header('Message-ID'),
527                   { hash_subj($root->header('Subject')) => 1 } ];
528         simple_dump($dst, $root, $_, 0) for $th->rootset;
529 }
530
531 sub thread_html_head {
532         my ($mime) = @_;
533         my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
534         $s = $s->as_html;
535         "<html><head><title>$s</title></head><body>" . PRE_WRAP
536
537 }
538
539 sub thread_entry {
540         my ($dst, $state, $node, $level) = @_;
541         # $state = [ $search_res, $seen, undef, 0 (msg_nr) ];
542         # $seen is overloaded with 3 types of fields:
543         #       1) "root_anchor" => anchor_for(Message-ID),
544         #       2) seen subject hashes: sha1(subject) => 1
545         #       3) anchors hashes: "#$sha1_hex" (same as $seen in index_entry)
546         if (my $mime = $node->message) {
547                 if (length($$dst) == 0) {
548                         $$dst .= thread_html_head($mime);
549                 }
550                 $$dst .= index_entry(undef, $mime, $level, $state);
551         }
552         thread_entry($dst, $state, $node->child, $level + 1) if $node->child;
553         thread_entry($dst, $state, $node->next, $level) if $node->next;
554 }
555
556 sub load_results {
557         my ($ctx, $res) = @_;
558
559         require PublicInbox::GitCatFile;
560         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
561         my @msgs;
562         while (my $smsg = shift @{$res->{msgs}}) {
563                 my $m = $smsg->mid;
564                 my $path = mid2path($m);
565
566                 # FIXME: duplicated code from Feed.pm
567                 my $mime = eval {
568                         my $str = $git->cat_file("HEAD:$path");
569                         Email::MIME->new($str);
570                 };
571                 unless ($@) {
572                         my $t = eval { str2time($mime->header('Date')) };
573                         defined($t) or $t = 0;
574                         $mime->header_set('X-PI-TS', $t);
575                         push @msgs, $mime;
576                 }
577         }
578         \@msgs;
579 }
580
581 1;