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