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