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