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