]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: reply threading adjustment
[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 Encode qw/find_encoding/;
8 use Encode::MIME::Header;
9 use Email::MIME::ContentType qw/parse_content_type/;
10 use PublicInbox::Hval;
11 use PublicInbox::MID qw/mid_clean mid_compressed/;
12 use Digest::SHA;
13 require POSIX;
14
15 # TODO: make these constants tunable
16 use constant MAX_INLINE_QUOTED => 12; # half an 80x24 terminal
17 use constant MAX_TRUNC_LEN => 72;
18 use constant PRE_WRAP => "<pre\nstyle=\"white-space:pre-wrap\">";
19
20 *ascii_html = *PublicInbox::Hval::ascii_html;
21
22 my $enc_utf8 = find_encoding('UTF-8');
23
24 # public functions:
25 sub msg_html {
26         my ($class, $mime, $full_pfx, $footer, $srch) = @_;
27         if (defined $footer) {
28                 $footer = "\n" . $footer;
29         } else {
30                 $footer = '';
31         }
32         headers_to_html_header($mime, $full_pfx) .
33                 multipart_text_as_html($mime, $full_pfx) .
34                 '</pre><hr />' . PRE_WRAP .
35                 html_footer($mime, 1, $full_pfx, $srch) . $footer .
36                 '</pre></body></html>';
37 }
38
39 sub feed_entry {
40         my ($class, $mime, $full_pfx) = @_;
41
42         PRE_WRAP . multipart_text_as_html($mime, $full_pfx) . '</pre>';
43 }
44
45 # this is already inside a <pre>
46 sub index_entry {
47         my ($class, $mime, $level, $state) = @_;
48         my ($now, $seen, $first) = @$state;
49         my $midx = $state->[3]++;
50         my ($prev, $next) = ($midx - 1, $midx + 1);
51         my $rv = '';
52         my $part_nr = 0;
53         my $enc_msg = enc_for($mime->header("Content-Type"));
54         my $subj = $mime->header('Subject');
55         my $header_obj = $mime->header_obj;
56
57         my $mid_raw = $header_obj->header_raw('Message-ID');
58         my $id = anchor_for($mid_raw);
59         $seen->{$id} = "#$id"; # save the anchor for later
60
61         my $mid = PublicInbox::Hval->new_msgid($mid_raw);
62         my $from = PublicInbox::Hval->new_oneline($mime->header('From'))->raw;
63         my @from = Email::Address->parse($from);
64         $from = $from[0]->name;
65         (defined($from) && length($from)) or $from = $from[0]->address;
66
67         $from = PublicInbox::Hval->new_oneline($from)->as_html;
68         $subj = PublicInbox::Hval->new_oneline($subj)->as_html;
69         my $pfx = ('  ' x $level);
70
71         my $ts = $mime->header('X-PI-TS');
72         my $fmt = '%Y-%m-%d %H:%M UTC';
73         $ts = POSIX::strftime($fmt, gmtime($ts));
74
75         $rv .= "$pfx<b\nid=\"$id\">$subj</b>\n$pfx";
76         $rv .= "- by $from @ $ts - ";
77         $rv .= "<a\nid=\"s$midx\"\nhref=\"#s$next\">next</a>";
78         if ($prev >= 0) {
79                 $rv .= "/<a\nhref=\"#s$prev\">prev</a>";
80         }
81         $rv .= "\n\n";
82
83         my $irp = $header_obj->header_raw('In-Reply-To');
84         my ($anchor_idx, $anchor);
85         if (defined $irp) {
86                 $anchor_idx = anchor_for($irp);
87                 $anchor = $seen->{$anchor_idx};
88         }
89         my $href = $mid->as_href;
90         my $mhref = "m/$href.html";
91         my $fhref = "f/$href.html";
92         my $more = 'message';
93         # scan through all parts, looking for displayable text
94         $mime->walk_parts(sub {
95                 my ($part) = @_;
96                 return if $part->subparts; # walk_parts already recurses
97                 my $ct = $part->content_type;
98
99                 # account for filter bugs...
100                 return if defined $ct && $ct =~ m!\btext/[xh]+tml\b!i;
101
102                 my $enc = enc_for($ct, $enc_msg);
103
104                 if ($part_nr > 0) {
105                         my $fn = $part->filename;
106                         defined($fn) or $fn = "part #" . ($part_nr + 1);
107                         $rv .= $pfx . add_filename_line($enc->decode($fn));
108                 }
109
110                 my $s = add_text_body_short($enc, $part, $part_nr, $fhref);
111
112                 # drop the remainder of git patches, they're usually better
113                 # to review when the full message is viewed
114                 $s =~ s!^---+\n.*\z!!ms and $more = 'more...';
115
116                 # Drop signatures
117                 $s =~ s/^-- \n.*\z//ms and $more = 'more...';
118
119                 # kill any leading or trailing whitespace
120                 $s =~ s/\A\s+//s;
121                 $s =~ s/\s+\z//s;
122
123                 if (length $s) {
124                         # add prefix:
125                         $s =~ s/^/$pfx/sgm;
126
127                         $rv .= $s . "\n";
128                 }
129                 ++$part_nr;
130         });
131
132         $rv .= "\n$pfx<a\nhref=\"$mhref\">$more</a> ";
133         my $txt = "m/$href.txt";
134         $rv .= "<a\nhref=\"$txt\">raw</a> ";
135         $rv .= html_footer($mime, 0);
136
137         if (defined $irp) {
138                 unless (defined $anchor) {
139                         my $v = PublicInbox::Hval->new_msgid($irp);
140                         my $html = $v->as_html;
141                         $anchor = 'm/' . $v->as_href . '.html';
142                         $seen->{$anchor_idx} = $anchor;
143                 }
144                 $rv .= " <a\nhref=\"$anchor\">parent</a>";
145         }
146         $rv .= " <a\nhref=\"?r=$first#$id\">threadlink</a>";
147
148         $rv . "\n\n";
149 }
150
151 # only private functions below.
152
153 sub enc_for {
154         my ($ct, $default) = @_;
155         $default ||= $enc_utf8;
156         defined $ct or return $default;
157         my $ct_parsed = parse_content_type($ct);
158         if ($ct_parsed) {
159                 if (my $charset = $ct_parsed->{attributes}->{charset}) {
160                         my $enc = find_encoding($charset);
161                         return $enc if $enc;
162                 }
163         }
164         $default;
165 }
166
167 sub multipart_text_as_html {
168         my ($mime, $full_pfx) = @_;
169         my $rv = "";
170         my $part_nr = 0;
171         my $enc_msg = enc_for($mime->header("Content-Type"));
172
173         # scan through all parts, looking for displayable text
174         $mime->walk_parts(sub {
175                 my ($part) = @_;
176                 return if $part->subparts; # walk_parts already recurses
177                 my $ct = $part->content_type;
178
179                 # account for filter bugs...
180                 return if defined $ct && $ct =~ m!\btext/[xh]+tml\b!i;
181
182                 my $enc = enc_for($ct, $enc_msg);
183
184                 if ($part_nr > 0) {
185                         my $fn = $part->filename;
186                         defined($fn) or $fn = "part #" . ($part_nr + 1);
187                         $rv .= add_filename_line($enc->decode($fn));
188                 }
189
190                 if (defined $full_pfx) {
191                         $rv .= add_text_body_short($enc, $part, $part_nr,
192                                                 $full_pfx);
193                 } else {
194                         $rv .= add_text_body_full($enc, $part, $part_nr);
195                 }
196                 $rv .= "\n" unless $rv =~ /\n\z/s;
197                 ++$part_nr;
198         });
199         $rv;
200 }
201
202 sub add_filename_line {
203         my ($fn) = @_;
204         my $len = 72;
205         my $pad = "-";
206
207         $len -= length($fn);
208         $pad x= ($len/2) if ($len > 0);
209         "$pad " . ascii_html($fn) . " $pad\n";
210 }
211
212 my $LINK_RE = qr!\b((?:ftp|https?|nntp)://[@\w\+\&\?\.\%\;/#=-]+)!;
213
214 sub linkify {
215         # no newlines added here since it'd break the splitting we do
216         # to fold quotes
217         $_[0] =~ s!$LINK_RE!<a href="$1">$1</a>!g;
218 }
219
220 sub add_text_body_short {
221         my ($enc, $part, $part_nr, $full_pfx) = @_;
222         my $n = 0;
223         my $s = ascii_html($enc->decode($part->body));
224         linkify($s);
225         $s =~ s!^((?:(?:&gt;[^\n]*)\n)+)!
226                 my $cur = $1;
227                 my @lines = split(/\n/, $cur);
228                 if (@lines > MAX_INLINE_QUOTED) {
229                         # show a short snippet of quoted text
230                         $cur = join(' ', @lines);
231                         $cur =~ s/^&gt;\s*//;
232
233                         my @sum = split(/\s+/, $cur);
234                         $cur = '';
235                         do {
236                                 my $tmp = shift(@sum);
237                                 my $len = length($tmp) + length($cur);
238                                 if ($len > MAX_TRUNC_LEN) {
239                                         @sum = ();
240                                 } else {
241                                         $cur .= $tmp . ' ';
242                                 }
243                         } while (@sum && length($cur) < MAX_TRUNC_LEN);
244                         $cur =~ s/ \z/ .../;
245                         "&gt; &lt;<a\nhref=\"${full_pfx}#q${part_nr}_" . $n++ .
246                                 "\">$cur<\/a>&gt;\n";
247                 } else {
248                         $cur;
249                 }
250         !emg;
251         $s;
252 }
253
254 sub add_text_body_full {
255         my ($enc, $part, $part_nr) = @_;
256         my $n = 0;
257         my $s = ascii_html($enc->decode($part->body));
258         linkify($s);
259         $s =~ s!^((?:(?:&gt;[^\n]*)\n)+)!
260                 my $cur = $1;
261                 my @lines = split(/\n/, $cur);
262                 if (@lines > MAX_INLINE_QUOTED) {
263                         "<a\nid=q${part_nr}_" . $n++ . ">$cur</a>";
264                 } else {
265                         $cur;
266                 }
267         !emg;
268         $s;
269 }
270
271 sub headers_to_html_header {
272         my ($mime, $full_pfx) = @_;
273
274         my $rv = "";
275         my @title;
276         foreach my $h (qw(From To Cc Subject Date)) {
277                 my $v = $mime->header($h);
278                 defined($v) && length($v) or next;
279                 $v = PublicInbox::Hval->new_oneline($v);
280                 $rv .= "$h: " . $v->as_html . "\n";
281
282                 if ($h eq 'From') {
283                         my @from = Email::Address->parse($v->raw);
284                         $v = $from[0]->name;
285                         unless (defined($v) && length($v)) {
286                                 $v = '<' . $from[0]->address . '>';
287                         }
288                         $title[1] = ascii_html($v);
289                 } elsif ($h eq 'Subject') {
290                         $title[0] = $v->as_html;
291                 }
292         }
293
294         my $header_obj = $mime->header_obj;
295         my $mid = $header_obj->header_raw('Message-ID');
296         if (defined $mid) {
297                 $mid = PublicInbox::Hval->new_msgid($mid);
298                 $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
299                 my $href = $mid->as_href;
300                 $href = "../m/$href" unless $full_pfx;
301                 $rv .= "(<a\nhref=\"$href.txt\">raw</a>)\n";
302         }
303
304         my $irp = $header_obj->header_raw('In-Reply-To');
305         if (defined $irp) {
306                 my $v = PublicInbox::Hval->new_msgid($irp);
307                 my $html = $v->as_html;
308                 my $href = $v->as_href;
309                 $rv .= "In-Reply-To: &lt;";
310                 $rv .= "<a\nhref=\"$href.html\">$html</a>&gt;\n";
311         }
312
313         my $refs = $header_obj->header_raw('References');
314         if ($refs) {
315                 $refs =~ s/\s*\Q$irp\E\s*// if (defined $irp);
316                 my @refs = ($refs =~ /<([^>]+)>/g);
317                 if (@refs) {
318                         $rv .= 'References: '. linkify_refs(@refs) . "\n";
319                 }
320         }
321
322         $rv .= "\n";
323
324         ("<html><head><title>".  join(' - ', @title) .
325          '</title></head><body>' . PRE_WRAP . $rv);
326 }
327
328 sub html_footer {
329         my ($mime, $standalone, $full_pfx, $srch) = @_;
330         my %cc; # everyone else
331         my $to; # this is the From address
332
333         foreach my $h (qw(From To Cc)) {
334                 my $v = $mime->header($h);
335                 defined($v) && length($v) or next;
336                 my @addrs = Email::Address->parse($v);
337                 foreach my $recip (@addrs) {
338                         my $address = $recip->address;
339                         my $dst = lc($address);
340                         $cc{$dst} ||= $address;
341                         $to ||= $dst;
342                 }
343         }
344         Email::Address->purge_cache if $standalone;
345
346         my $subj = $mime->header('Subject') || '';
347         $subj = "Re: $subj" unless $subj =~ /\bRe:/;
348         my $mid = $mime->header_obj->header_raw('Message-ID');
349         my $irp = uri_escape_utf8($mid);
350         delete $cc{$to};
351         $to = uri_escape_utf8($to);
352         $subj = uri_escape_utf8($subj);
353
354         my $cc = uri_escape_utf8(join(',', sort values %cc));
355         my $href = "mailto:$to?In-Reply-To=$irp&Cc=${cc}&Subject=$subj";
356
357         my $irt = '';
358         my $idx = $standalone ? " <a\nhref=\"../\">index</a>" : '';
359         if ($idx && $srch) {
360                 my $res = $srch->get_replies($mid);
361                 if (my $c = $res->{count}) {
362                         $c = $c == 1 ? '1 reply' : "$c replies";
363                         $idx .= "\n$c:\n";
364                         thread_replies(\$idx, $mime, $res);
365                 } else {
366                         $idx .= "\n(no replies yet)\n";
367                 }
368                 $irt = $mime->header_obj->header_raw('In-Reply-To');
369                 if ($irt) {
370                         $irt = PublicInbox::Hval->new_msgid($irt);
371                         $irt = $irt->as_href;
372                         $irt = "<a\nhref=\"$irt\">parent</a> ";
373                 } else {
374                         $irt = ' ' x length('parent ');
375                 }
376         }
377
378         "$irt<a\nhref=\"" . ascii_html($href) . '">reply</a>' . $idx;
379 }
380
381 sub linkify_refs {
382         join(' ', map {
383                 my $v = PublicInbox::Hval->new_msgid($_);
384                 my $html = $v->as_html;
385                 my $href = $v->as_href;
386                 "&lt;<a\nhref=\"$href.html\">$html</a>&gt;";
387         } @_);
388 }
389
390 sub anchor_for {
391         my ($msgid) = @_;
392         'm' . mid_compressed(mid_clean($msgid));
393 }
394
395 sub simple_dump {
396         my ($dst, $root, $node, $level) = @_;
397         my $pfx = '  ' x $level;
398         $$dst .= $pfx;
399         if (my $x = $node->message) {
400                 my $mid = $x->header('Message-ID');
401                 if ($root->[0] ne $mid) {
402                         my $s = $x->header('Subject');
403                         my $h = hash_subj($s);
404                         if ($root->[1]->{$h}) {
405                                 $s = '';
406                         } else {
407                                 $root->[1]->{$h} = 1;
408                                 $s = PublicInbox::Hval->new($s);
409                                 $s = $s->as_html;
410                         }
411                         my $m = PublicInbox::Hval->new_msgid($mid);
412                         my $f = PublicInbox::Hval->new($x->header('X-PI-From'));
413                         my $d = PublicInbox::Hval->new($x->header('X-PI-Date'));
414                         $m = $m->as_href . '.html';
415                         $f = $f->as_html;
416                         $d = $d->as_html . ' UTC';
417                         if (length($s) == 0) {
418                                 $$dst .= "` <a\nhref=\"$m\">$f @ $d</a>\n";
419                         } else {
420                                 $$dst .= "` <a\nhref=\"$m\">$s</a>\n" .
421                                      "$pfx  by $f @ $d\n";
422                         }
423                 }
424         }
425         simple_dump($dst, $root, $node->child, $level + 1) if $node->child;
426         simple_dump($dst, $root, $node->next, $level) if $node->next;
427 }
428
429 sub hash_subj {
430         my ($subj) = @_;
431         $subj =~ s/\A\s+//;
432         $subj =~ s/\s+\z//;
433         $subj =~ s/^(?:re|aw):\s*//i; # remove reply prefix (aw: German)
434         $subj =~ s/\s+/ /;
435         Digest::SHA::sha1($subj);
436 }
437
438 sub thread_replies {
439         my ($dst, $root, $res) = @_;
440         my @msgs = map { $_->mini_mime } @{$res->{msgs}};
441         require PublicInbox::Thread;
442         $root->header_set('X-PI-TS', '0');
443         my $th = PublicInbox::Thread->new($root, @msgs);
444         $th->thread;
445         $th->order(*PublicInbox::Thread::sort_ts);
446         $root = [ $root->header('Message-ID'),
447                   { hash_subj($root->header('Subject')) => 1 } ];
448         simple_dump($dst, $root, $_, 0) for $th->rootset;
449 }
450
451 1;