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