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