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