]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
www: /t/$MESSAGE_ID.html for threads
[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/;
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) .
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 (undef, $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                 $subj = "<u\nid=\"u\">$subj</u>" if $root_anchor eq $id;
79         } else {
80                 $path = '';
81         }
82
83         my $ts = $mime->header('X-PI-TS');
84         my $fmt = '%Y-%m-%d %H:%M UTC';
85         $ts = POSIX::strftime($fmt, gmtime($ts));
86
87         $rv .= "$pfx<b\nid=\"$id\">$subj</b>\n$pfx";
88         $rv .= "- by $from @ $ts - ";
89         $rv .= "<a\nid=\"s$midx\"\nhref=\"#s$next\">next</a>";
90         if ($prev >= 0) {
91                 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
92         }
93         $rv .= "\n\n";
94
95         my $irt = $header_obj->header_raw('In-Reply-To');
96         my ($anchor_idx, $anchor, $t_anchor);
97         if (defined $irt) {
98                 $anchor_idx = anchor_for($irt);
99                 $anchor = $seen->{$anchor_idx};
100                 $t_anchor = T_ANCHOR;
101         } else {
102                 $t_anchor = '';
103         }
104         my $href = $mid->as_href;
105         my $mhref = "${path}m/$href.html";
106         my $fhref = "${path}f/$href.html";
107         # scan through all parts, looking for displayable text
108         $mime->walk_parts(sub {
109                 $rv .= index_walk($_[0], $pfx, $enc_msg, $part_nr, $fhref,
110                                   \$more);
111                 $part_nr++;
112         });
113
114         $rv .= "\n$pfx<a\nhref=\"$mhref\">$more</a> ";
115         my $txt = "${path}m/$href.txt";
116         $rv .= "<a\nhref=\"$txt\">raw</a> ";
117         $rv .= html_footer($mime, 0);
118
119         if (defined $irt) {
120                 unless (defined $anchor) {
121                         my $v = PublicInbox::Hval->new_msgid($irt);
122                         $v = $v->as_href;
123                         $anchor = "${path}m/$v.html";
124                         $seen->{$anchor_idx} = $anchor;
125                 }
126                 $rv .= " <a\nhref=\"$anchor\">parent</a>";
127         }
128
129         if ($first_commit) {
130                 $rv .= " <a\nhref=\"t/$href.html$t_anchor\">thread</a>";
131         }
132
133         $rv . "\n\n";
134 }
135
136 sub thread_html {
137         my (undef, $ctx, $foot, $srch) = @_;
138         my $mid = mid_compressed($ctx->{mid});
139         my $res = $srch->get_thread($mid);
140         my $rv = '';
141         require PublicInbox::GitCatFile;
142         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
143         my $nr = scalar @{$res->{msgs}};
144         return $rv if $nr == 0;
145         my @msgs;
146         while (my $smsg = shift @{$res->{msgs}}) {
147                 my $m = $smsg->mid;
148
149                 # Duplicated from WWW.pm
150                 my ($x2, $x38) = ($m =~ /\A([a-f0-9]{2})([a-f0-9]{38})\z/);
151
152                 unless (defined $x38) {
153                         require Digest::SHA;
154                         $m = Digest::SHA::sha1_hex($m);
155                         ($x2, $x38) = ($m =~ /\A([a-f0-9]{2})([a-f0-9]{38})\z/);
156                 }
157
158                 # FIXME: duplicated code from Feed.pm
159                 my $mime = eval {
160                         my $str = $git->cat_file("HEAD:$x2/$x38");
161                         Email::MIME->new($str);
162                 };
163                 unless ($@) {
164                         my $t = eval { str2time($mime->header('Date')) };
165                         defined($t) or $t = 0;
166                         $mime->header_set('X-PI-TS', $t);
167                         push @msgs, $mime;
168                 }
169         }
170         require PublicInbox::Thread;
171         my $th = PublicInbox::Thread->new(@msgs);
172         $th->thread;
173         $th->order(*PublicInbox::Thread::sort_ts);
174         my $state = [ undef, { root_anchor => anchor_for($mid) }, 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
211         $s =~ s/\A\s+//s;
212         $s =~ s/\s+\z//s;
213
214         if (length $s) {
215                 # add prefix:
216                 $s =~ s/^/$pfx/sgm;
217
218                 $rv .= $s . "\n";
219         }
220         $rv;
221 }
222
223 sub enc_for {
224         my ($ct, $default) = @_;
225         $default ||= $enc_utf8;
226         defined $ct or return $default;
227         my $ct_parsed = parse_content_type($ct);
228         if ($ct_parsed) {
229                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
230                         my $enc = find_encoding($charset);
231                         return $enc if $enc;
232                 }
233         }
234         $default;
235 }
236
237 sub multipart_text_as_html {
238         my ($mime, $full_pfx) = @_;
239         my $rv = "";
240         my $part_nr = 0;
241         my $enc_msg = enc_for($mime->header("Content-Type"));
242
243         # scan through all parts, looking for displayable text
244         $mime->walk_parts(sub {
245                 my ($part) = @_;
246                 return if $part->subparts; # walk_parts already recurses
247                 my $ct = $part->content_type;
248
249                 # account for filter bugs...
250                 return if defined $ct && $ct =~ m!\btext/[xh]+tml\b!i;
251
252                 my $enc = enc_for($ct, $enc_msg);
253
254                 if ($part_nr > 0) {
255                         my $fn = $part->filename;
256                         defined($fn) or $fn = "part #" . ($part_nr + 1);
257                         $rv .= add_filename_line($enc->decode($fn));
258                 }
259
260                 if (defined $full_pfx) {
261                         $rv .= add_text_body_short($enc, $part, $part_nr,
262                                                 $full_pfx);
263                 } else {
264                         $rv .= add_text_body_full($enc, $part, $part_nr);
265                 }
266                 $rv .= "\n" unless $rv =~ /\n\z/s;
267                 ++$part_nr;
268         });
269         $rv;
270 }
271
272 sub add_filename_line {
273         my ($fn) = @_;
274         my $len = 72;
275         my $pad = "-";
276
277         $len -= length($fn);
278         $pad x= ($len/2) if ($len > 0);
279         "$pad " . ascii_html($fn) . " $pad\n";
280 }
281
282 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://[@\w\+\&\?\.\%\;/#=-]+)!;
283
284 sub linkify {
285         # no newlines added here since it'd break the splitting we do
286         # to fold quotes
287         $_[0] =~ s!$LINK_RE!<a href="$1">$1</a>!g;
288 }
289
290 sub add_text_body_short {
291         my ($enc, $part, $part_nr, $full_pfx) = @_;
292         my $n = 0;
293         my $s = ascii_html($enc->decode($part->body));
294         linkify($s);
295         $s =~ s!^((?:(?:&gt;[^\n]*)\n)+)!
296                 my $cur = $1;
297                 my @lines = split(/\n/, $cur);
298                 if (@lines > MAX_INLINE_QUOTED) {
299                         # show a short snippet of quoted text
300                         $cur = join(' ', @lines);
301                         $cur =~ s/^&gt;\s*//;
302
303                         my @sum = split(/\s+/, $cur);
304                         $cur = '';
305                         do {
306                                 my $tmp = shift(@sum);
307                                 my $len = length($tmp) + length($cur);
308                                 if ($len > MAX_TRUNC_LEN) {
309                                         @sum = ();
310                                 } else {
311                                         $cur .= $tmp . ' ';
312                                 }
313                         } while (@sum && length($cur) < MAX_TRUNC_LEN);
314                         $cur =~ s/ \z/ .../;
315                         "&gt; &lt;<a\nhref=\"${full_pfx}#q${part_nr}_" . $n++ .
316                                 "\">$cur<\/a>&gt;\n";
317                 } else {
318                         $cur;
319                 }
320         !emg;
321         $s;
322 }
323
324 sub add_text_body_full {
325         my ($enc, $part, $part_nr) = @_;
326         my $n = 0;
327         my $s = ascii_html($enc->decode($part->body));
328         linkify($s);
329         $s =~ s!^((?:(?:&gt;[^\n]*)\n)+)!
330                 my $cur = $1;
331                 my @lines = split(/\n/, $cur);
332                 if (@lines > MAX_INLINE_QUOTED) {
333                         "<a\nid=q${part_nr}_" . $n++ . ">$cur</a>";
334                 } else {
335                         $cur;
336                 }
337         !emg;
338         $s;
339 }
340
341 sub headers_to_html_header {
342         my ($mime, $full_pfx) = @_;
343
344         my $rv = "";
345         my @title;
346         foreach my $h (qw(From To Cc Subject Date)) {
347                 my $v = $mime->header($h);
348                 defined($v) && length($v) or next;
349                 $v = PublicInbox::Hval->new_oneline($v);
350                 $rv .= "$h: " . $v->as_html . "\n";
351
352                 if ($h eq 'From') {
353                         my @from = Email::Address->parse($v->raw);
354                         $v = $from[0]->name;
355                         unless (defined($v) && length($v)) {
356                                 $v = '<' . $from[0]->address . '>';
357                         }
358                         $title[1] = ascii_html($v);
359                 } elsif ($h eq 'Subject') {
360                         $title[0] = $v->as_html;
361                 }
362         }
363
364         my $header_obj = $mime->header_obj;
365         my $mid = $header_obj->header_raw('Message-ID');
366         $mid = PublicInbox::Hval->new_msgid($mid);
367         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
368         my $href = $mid->as_href;
369         $href = "../m/$href" unless $full_pfx;
370         $rv .= "(<a\nhref=\"$href.txt\">raw</a>)\n";
371
372         my $irt = $header_obj->header_raw('In-Reply-To');
373         if (defined $irt) {
374                 my $v = PublicInbox::Hval->new_msgid($irt);
375                 my $html = $v->as_html;
376                 my $href = $v->as_href;
377                 $rv .= "In-Reply-To: &lt;";
378                 $rv .= "<a\nhref=\"$href.html\">$html</a>&gt;\n";
379         }
380
381         my $refs = $header_obj->header_raw('References');
382         if ($refs) {
383                 $refs =~ s/\s*\Q$irt\E\s*// if (defined $irt);
384                 my @refs = ($refs =~ /<([^>]+)>/g);
385                 if (@refs) {
386                         $rv .= 'References: '. linkify_refs(@refs) . "\n";
387                 }
388         }
389
390         $rv .= "\n";
391
392         ("<html><head><title>".  join(' - ', @title) .
393          '</title></head><body>' . PRE_WRAP . $rv);
394 }
395
396 sub html_footer {
397         my ($mime, $standalone, $full_pfx, $srch) = @_;
398         my %cc; # everyone else
399         my $to; # this is the From address
400
401         foreach my $h (qw(From To Cc)) {
402                 my $v = $mime->header($h);
403                 defined($v) && length($v) or next;
404                 my @addrs = Email::Address->parse($v);
405                 foreach my $recip (@addrs) {
406                         my $address = $recip->address;
407                         my $dst = lc($address);
408                         $cc{$dst} ||= $address;
409                         $to ||= $dst;
410                 }
411         }
412         Email::Address->purge_cache if $standalone;
413
414         my $subj = $mime->header('Subject') || '';
415         $subj = "Re: $subj" unless $subj =~ /\bRe:/;
416         my $mid = $mime->header_obj->header_raw('Message-ID');
417         my $irt = uri_escape_utf8($mid);
418         delete $cc{$to};
419         $to = uri_escape_utf8($to);
420         $subj = uri_escape_utf8($subj);
421
422         my $cc = uri_escape_utf8(join(',', sort values %cc));
423         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
424
425         my $idx = $standalone ? " <a\nhref=\"../\">index</a>" : '';
426         if ($idx && $srch) {
427                 $irt = $mime->header_obj->header_raw('In-Reply-To') || '';
428                 $mid = mid_compressed(mid_clean($mid));
429                 my $t_anchor = length $irt ? T_ANCHOR : '';
430                 $idx = " <a\nhref=\"../t/$mid.html$t_anchor\">thread</a>$idx";
431                 my $res = $srch->get_replies($mid);
432                 if (my $c = $res->{count}) {
433                         $c = $c == 1 ? '1 reply' : "$c replies";
434                         $idx .= "\n$c:\n";
435                         thread_replies(\$idx, $mime, $res);
436                 } else {
437                         $idx .= "\n(no replies yet)\n";
438                 }
439                 if ($irt) {
440                         $irt = PublicInbox::Hval->new_msgid($irt);
441                         $irt = $irt->as_href;
442                         $irt = "<a\nhref=\"$irt\">parent</a> ";
443                 } else {
444                         $irt = ' ' x length('parent ');
445                 }
446         } else {
447                 $irt = '';
448         }
449
450         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
451 }
452
453 sub linkify_refs {
454         join(' ', map {
455                 my $v = PublicInbox::Hval->new_msgid($_);
456                 my $html = $v->as_html;
457                 my $href = $v->as_href;
458                 "&lt;<a\nhref=\"$href.html\">$html</a>&gt;";
459         } @_);
460 }
461
462 sub anchor_for {
463         my ($msgid) = @_;
464         'm' . mid_compressed(mid_clean($msgid));
465 }
466
467 sub simple_dump {
468         my ($dst, $root, $node, $level) = @_;
469         my $pfx = '  ' x $level;
470         $$dst .= $pfx;
471         if (my $x = $node->message) {
472                 my $mid = $x->header('Message-ID');
473                 if ($root->[0] ne $mid) {
474                         my $s = $x->header('Subject');
475                         my $h = hash_subj($s);
476                         if ($root->[1]->{$h}) {
477                                 $s = '';
478                         } else {
479                                 $root->[1]->{$h} = 1;
480                                 $s = PublicInbox::Hval->new($s);
481                                 $s = $s->as_html;
482                         }
483                         my $m = PublicInbox::Hval->new_msgid($mid);
484                         my $f = PublicInbox::Hval->new($x->header('X-PI-From'));
485                         my $d = PublicInbox::Hval->new($x->header('X-PI-Date'));
486                         $m = $m->as_href . '.html';
487                         $f = $f->as_html;
488                         $d = $d->as_html . ' UTC';
489                         if (length($s) == 0) {
490                                 $$dst .= "` <a\nhref=\"$m\">$f @ $d</a>\n";
491                         } else {
492                                 $$dst .= "` <a\nhref=\"$m\">$s</a>\n" .
493                                      "$pfx  by $f @ $d\n";
494                         }
495                 }
496         }
497         simple_dump($dst, $root, $node->child, $level + 1) if $node->child;
498         simple_dump($dst, $root, $node->next, $level) if $node->next;
499 }
500
501 sub hash_subj {
502         my ($subj) = @_;
503         $subj =~ s/\A\s+//;
504         $subj =~ s/\s+\z//;
505         $subj =~ s/^(?:re|aw):\s*//i; # remove reply prefix (aw: German)
506         $subj =~ s/\s+/ /;
507         Digest::SHA::sha1($subj);
508 }
509
510 sub thread_replies {
511         my ($dst, $root, $res) = @_;
512         my @msgs = map { $_->mini_mime } @{$res->{msgs}};
513         require PublicInbox::Thread;
514         $root->header_set('X-PI-TS', '0');
515         my $th = PublicInbox::Thread->new($root, @msgs);
516         $th->thread;
517         $th->order(*PublicInbox::Thread::sort_ts);
518         $root = [ $root->header('Message-ID'),
519                   { hash_subj($root->header('Subject')) => 1 } ];
520         simple_dump($dst, $root, $_, 0) for $th->rootset;
521 }
522
523 sub thread_html_head {
524         my ($mime) = @_;
525         my $s = PublicInbox::Hval->new_oneline($mime->header('Subject'));
526         $s = $s->as_html;
527         "<html><head><title>$s</title></head><body>" . PRE_WRAP
528
529 }
530
531 sub thread_entry {
532         my ($dst, $state, $node, $level) = @_;
533         # $state = [ $search_res, $seen, undef, 0 (msg_nr) ];
534         # $seen is overloaded with 3 types of fields:
535         #       1) "root" => Message-ID,
536         #       2) seen subject hashes: sha1(subject) => 1
537         #       3) anchors hashes: "#$sha1_hex" (same as $seen in index_entry)
538         if (my $mime = $node->message) {
539                 if (length($$dst) == 0) {
540                         $$dst .= thread_html_head($mime);
541                 }
542                 $$dst .= index_entry(undef, $mime, $level, $state);
543         }
544         thread_entry($dst, $state, $node->child, $level + 1) if $node->child;
545         thread_entry($dst, $state, $node->next, $level) if $node->next;
546 }
547
548 1;