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