]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/View.pm
view: allow thread generation to EOF on errors
[public-inbox.git] / lib / PublicInbox / View.pm
1 # Copyright (C) 2014-2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 #
4 # Used for displaying the HTML web interface.
5 # See Documentation/design_www.txt for this.
6 package PublicInbox::View;
7 use strict;
8 use warnings;
9 use URI::Escape qw/uri_escape_utf8/;
10 use Date::Parse qw/str2time/;
11 use Encode::MIME::Header;
12 use Plack::Util;
13 use PublicInbox::Hval qw/ascii_html/;
14 use PublicInbox::Linkify;
15 use PublicInbox::MID qw/mid_clean id_compress mid_mime/;
16 use PublicInbox::MsgIter;
17 use PublicInbox::Address;
18 use PublicInbox::WwwStream;
19 require POSIX;
20
21 use constant INDENT => '  ';
22 use constant TCHILD => '` ';
23 sub th_pfx ($) { $_[0] == 0 ? '' : TCHILD };
24
25 # public functions: (unstable)
26 sub msg_html {
27         my ($ctx, $mime, $footer) = @_;
28         my $hdr = $mime->header_obj;
29         my $tip = _msg_html_prepare($hdr, $ctx);
30         PublicInbox::WwwStream->new($ctx, sub {
31                 my ($nr, undef) = @_;
32                 if ($nr == 1) {
33                         $tip . multipart_text_as_html($mime, '') .
34                                 '</pre><hr />'
35                 } elsif ($nr == 2) {
36                         # fake an EOF if generating the footer fails;
37                         # we want to at least show the message if something
38                         # here crashes:
39                         eval {
40                                 '<pre>' . html_footer($hdr, 1, $ctx) .
41                                 '</pre>' . msg_reply($ctx, $hdr)
42                         };
43                 } else {
44                         undef
45                 }
46         });
47 }
48
49 # /$INBOX/$MESSAGE_ID/#R
50 sub msg_reply {
51         my ($ctx, $hdr) = @_;
52         my $se_url =
53          'https://kernel.org/pub/software/scm/git/docs/git-send-email.html';
54
55         my ($arg, $link) = mailto_arg_link($hdr);
56         push @$arg, '/path/to/YOUR_REPLY';
57
58         "<pre\nid=R>".
59         "You may reply publically to <a\nhref=#t>this message</a> via\n".
60         "plain-text email using any one of the following methods:\n\n" .
61         "* Save the following mbox file, import it into your mail client,\n" .
62         "  and reply-to-all from there: <a\nhref=raw>mbox</a>\n\n" .
63         "* Reply to all the recipients using the <b>--to</b>, <b>--cc</b>,\n" .
64         "  and <b>--in-reply-to</b> switches of git-send-email(1):\n\n" .
65         "  git send-email \\\n    " .
66         join(" \\\n    ", @$arg ). "\n\n" .
67         qq(  <a\nhref="$se_url">$se_url</a>\n\n) .
68         "* If your mail client supports setting the <b>In-Reply-To</b>" .
69         " header\n  via mailto: links, try the " .
70         qq(<a\nhref="$link">mailto: link</a>\n) .
71         '</pre>';
72 }
73
74 sub in_reply_to {
75         my ($hdr) = @_;
76         my $irt = $hdr->header_raw('In-Reply-To');
77
78         return mid_clean($irt) if (defined $irt);
79
80         my $refs = $hdr->header_raw('References');
81         if ($refs && $refs =~ /<([^>]+)>\s*\z/s) {
82                 return $1;
83         }
84         undef;
85 }
86
87 # this is already inside a <pre>
88 sub index_entry {
89         my ($mime, $level, $state) = @_;
90         my $midx = $state->{anchor_idx}++;
91         my $ctx = $state->{ctx};
92         my $srch = $ctx->{srch};
93         my $hdr = $mime->header_obj;
94         my $subj = $hdr->header('Subject');
95
96         my $mid_raw = mid_clean(mid_mime($mime));
97         my $id = anchor_for($mid_raw);
98         my $seen = $state->{seen};
99         $seen->{$id} = "#$id"; # save the anchor for children, later
100
101         my $mid = PublicInbox::Hval->new_msgid($mid_raw);
102         my $from = PublicInbox::Address::from_name($hdr->header('From'));
103
104         my $root_anchor = $state->{root_anchor} || '';
105         my $path = $root_anchor ? '../../' : '';
106         my $href = $mid->as_href;
107         my $irt = in_reply_to($hdr);
108         my $parent_anchor = $seen->{anchor_for($irt)} if defined $irt;
109
110         $from = ascii_html($from);
111         $subj = ascii_html($subj);
112         $subj = "<a\nhref=\"${path}$href/\">$subj</a>";
113         $subj = "<u\nid=u>$subj</u>" if $root_anchor eq $id;
114
115         my $ts = _msg_date($hdr);
116         my $rv = "<pre\nid=s$midx>";
117         $rv .= "<b\nid=$id>$subj</b>\n";
118         my $txt = "${path}$href/raw";
119         my $fh = $state->{fh};
120         $fh->write($rv .= "- $from @ $ts UTC (<a\nhref=\"$txt\">raw</a>)\n\n");
121
122         my $mhref = "${path}$href/";
123
124         # scan through all parts, looking for displayable text
125         msg_iter($mime, sub { index_walk($fh, $mhref, $_[0]) });
126         $rv = "\n" . html_footer($hdr, 0, $ctx, "$path$href/#R");
127
128         if (defined $irt) {
129                 unless (defined $parent_anchor) {
130                         my $v = PublicInbox::Hval->new_msgid($irt, 1);
131                         $v = $v->as_href;
132                         $parent_anchor = "${path}$v/";
133                 }
134                 $rv .= " <a\nhref=\"$parent_anchor\">parent</a>";
135         }
136         if (my $pct = $state->{pct}) { # used by SearchView.pm
137                 $rv .= " [relevance $pct->{$mid_raw}%]";
138         } elsif ($srch) {
139                 my $threaded = 'threaded';
140                 my $flat = 'flat';
141                 my $end = '';
142                 if ($ctx->{flat}) {
143                         $flat = "<b>$flat</b>";
144                         $end = "\n"; # for lynx
145                 } else {
146                         $threaded = "<b>$threaded</b>";
147                 }
148                 $rv .= " [<a\nhref=\"${path}$href/t/#u\">$threaded</a>";
149                 $rv .= "|<a\nhref=\"${path}$href/T/#u\">$flat</a>]$end";
150         }
151         $fh->write($rv .= '</pre>');
152 }
153
154 sub thread_html {
155         my ($ctx, $foot, $srch) = @_;
156         # $_[0] in sub is the Plack callback
157         sub { emit_thread_html($_[0], $ctx, $foot, $srch) }
158 }
159
160 sub walk_thread {
161         my ($th, $state, $cb) = @_;
162         my @q = map { (0, $_) } $th->rootset;
163         while (@q) {
164                 my $level = shift @q;
165                 my $node = shift @q or next;
166                 $cb->($state, $level, $node);
167                 unshift @q, $level+1, $node->child, $level, $node->next;
168         }
169 }
170
171 # only private functions below.
172
173 sub emit_thread_html {
174         my ($res, $ctx, $foot, $srch) = @_;
175         my $mid = $ctx->{mid};
176         my $flat = $ctx->{flat};
177         my $msgs = load_results($srch->get_thread($mid, { asc => $flat }));
178         my $nr = scalar @$msgs;
179         return missing_thread($res, $ctx) if $nr == 0;
180         my $seen = {};
181         my $state = {
182                 res => $res,
183                 ctx => $ctx,
184                 seen => $seen,
185                 root_anchor => anchor_for($mid),
186                 anchor_idx => 0,
187                 cur_level => 0,
188         };
189
190         require PublicInbox::Git;
191         $ctx->{git} ||= PublicInbox::Git->new($ctx->{git_dir});
192         if ($flat) {
193                 pre_anchor_entry($seen, $_) for (@$msgs);
194                 __thread_entry($state, $_, 0) for (@$msgs);
195         } else {
196                 walk_thread(thread_results($msgs), $state, *thread_entry);
197                 if (my $max = $state->{cur_level}) {
198                         $state->{fh}->write(
199                                 ('</ul></li>' x ($max - 1)) . '</ul>');
200                 }
201         }
202
203         # there could be a race due to a message being deleted in git
204         # but still being in the Xapian index:
205         my $fh = delete $state->{fh} or return missing_thread($res, $ctx);
206
207         my $final_anchor = $state->{anchor_idx};
208         my $next = "<a\nid=s$final_anchor>";
209         $next .= $final_anchor == 1 ? 'only message in' : 'end of';
210         $next .= " thread</a>, back to <a\nhref=\"../../\">index</a>";
211         $next .= "\ndownload thread: ";
212         $next .= "<a\nhref=\"../t.mbox.gz\">mbox.gz</a>";
213         $next .= " / follow: <a\nhref=\"../t.atom\">Atom feed</a>";
214         $fh->write('<hr /><pre>' . $next . "\n\n".
215                         $foot .  '</pre></body></html>');
216         $fh->close;
217 }
218
219 sub index_walk {
220         my ($fh, $upfx, $p) = @_;
221         my $s = add_text_body($upfx, $p);
222
223         return if $s eq '';
224
225         $fh->write($s);
226 }
227
228 sub multipart_text_as_html {
229         my ($mime, $upfx) = @_;
230         my $rv = "";
231
232         # scan through all parts, looking for displayable text
233         msg_iter($mime, sub {
234                 my ($p) = @_;
235                 $rv .= add_text_body($upfx, $p);
236         });
237         $rv;
238 }
239
240 sub flush_quote {
241         my ($s, $l, $quot) = @_;
242
243         # show everything in the full version with anchor from
244         # short version (see above)
245         my $rv = $l->linkify_1(join('', @$quot));
246         @$quot = ();
247
248         # we use a <span> here to allow users to specify their own
249         # color for quoted text
250         $rv = $l->linkify_2(ascii_html($rv));
251         $$s .= qq(<span\nclass="q">) . $rv . '</span>'
252 }
253
254 sub attach_link ($$$$) {
255         my ($upfx, $ct, $p, $fn) = @_;
256         my ($part, $depth, @idx) = @$p;
257         my $nl = $idx[-1] > 1 ? "\n" : '';
258         my $idx = join('.', @idx);
259         my $size = bytes::length($part->body);
260         $ct ||= 'text/plain';
261         $ct =~ s/;.*//; # no attributes
262         $ct = ascii_html($ct);
263         my $desc = $part->header('Content-Description');
264         $desc = $fn unless defined $desc;
265         $desc = '' unless defined $desc;
266         my $sfn;
267         if (defined $fn && $fn =~ /\A[[:alnum:]][\w\.-]+[[:alnum:]]\z/) {
268                 $sfn = $fn;
269         } elsif ($ct eq 'text/plain') {
270                 $sfn = 'a.txt';
271         } else {
272                 $sfn = 'a.bin';
273         }
274         my @ret = qq($nl<a\nhref="$upfx$idx-$sfn">[-- Attachment #$idx: );
275         my $ts = "Type: $ct, Size: $size bytes";
276         push(@ret, ($desc eq '') ? "$ts --]" : "$desc --]\n[-- $ts --]");
277         join('', @ret, "</a>\n");
278 }
279
280 sub add_text_body {
281         my ($upfx, $p) = @_; # from msg_iter: [ Email::MIME, depth, @idx ]
282         my ($part, $depth, @idx) = @$p;
283         my $ct = $part->content_type;
284         my $fn = $part->filename;
285
286         if (defined $ct && $ct =~ m!\btext/x?html\b!i) {
287                 return attach_link($upfx, $ct, $p, $fn);
288         }
289
290         my $s = eval { $part->body_str };
291
292         # badly-encoded message? tell the world about it!
293         return attach_link($upfx, $ct, $p, $fn) if $@;
294
295         my @lines = split(/^/m, $s);
296         $s = '';
297         if (defined($fn) || $depth > 0) {
298                 $s .= attach_link($upfx, $ct, $p, $fn);
299                 $s .= "\n";
300         }
301         my @quot;
302         my $l = PublicInbox::Linkify->new;
303         while (defined(my $cur = shift @lines)) {
304                 if ($cur !~ /^>/) {
305                         # show the previously buffered quote inline
306                         flush_quote(\$s, $l, \@quot) if @quot;
307
308                         # regular line, OK
309                         $cur = $l->linkify_1($cur);
310                         $cur = ascii_html($cur);
311                         $s .= $l->linkify_2($cur);
312                 } else {
313                         push @quot, $cur;
314                 }
315         }
316
317         my $end = "\n";
318         if (@quot) {
319                 $end = '';
320                 flush_quote(\$s, $l, \@quot);
321         }
322         $s =~ s/[ \t]+$//sgm; # kill per-line trailing whitespace
323         $s =~ s/\A\n+//s; # kill leading blank lines
324         $s =~ s/\s+\z//s; # kill all trailing spaces
325         $s .= $end;
326 }
327
328 sub _msg_html_prepare {
329         my ($hdr, $ctx) = @_;
330         my $srch = $ctx->{srch} if $ctx;
331         my $atom = '';
332         my $rv = "<pre\nid=b>"; # anchor for body start
333
334         if ($srch) {
335                 $ctx->{-upfx} = '../';
336         }
337         my @title;
338         my $mid = $hdr->header_raw('Message-ID');
339         $mid = PublicInbox::Hval->new_msgid($mid);
340         foreach my $h (qw(From To Cc Subject Date)) {
341                 my $v = $hdr->header($h);
342                 defined($v) && ($v ne '') or next;
343                 $v = PublicInbox::Hval->new($v);
344
345                 if ($h eq 'From') {
346                         my $n = PublicInbox::Address::from_name($v->raw);
347                         $title[1] = ascii_html($n);
348                 } elsif ($h eq 'Subject') {
349                         $title[0] = $v->as_html;
350                         if ($srch) {
351                                 $rv .= qq($h: <a\nhref="#r"\nid=t>);
352                                 $rv .= $v->as_html . "</a>\n";
353                                 next;
354                         }
355                 }
356                 $v = $v->as_html;
357                 $v =~ s/(\@[^,]+,) /$1\n\t/g if ($h eq 'Cc' || $h eq 'To');
358                 $rv .= "$h: $v\n";
359
360         }
361         $title[0] ||= '(no subject)';
362         $ctx->{-title_html} = join(' - ', @title);
363         $rv .= 'Message-ID: &lt;' . $mid->as_html . '&gt; ';
364         $rv .= "(<a\nhref=\"raw\">raw</a>)\n";
365         $rv .= _parent_headers($hdr, $srch);
366         $rv .= "\n";
367 }
368
369 sub thread_skel {
370         my ($dst, $ctx, $hdr, $tpfx) = @_;
371         my $srch = $ctx->{srch};
372         my $mid = mid_clean($hdr->header_raw('Message-ID'));
373         my $sres = $srch->get_thread($mid);
374         my $nr = $sres->{total};
375         my $expand = qq(<a\nhref="${tpfx}t/#u">expand</a> ) .
376                         qq(/ <a\nhref="${tpfx}t.mbox.gz">mbox.gz</a> ) .
377                         qq(/ <a\nhref="${tpfx}t.atom">Atom feed</a>);
378
379         my $parent = in_reply_to($hdr);
380         if ($nr <= 1) {
381                 if (defined $parent) {
382                         $$dst .= "($expand)\n ";
383                         $$dst .= ghost_parent("$tpfx../", $parent) . "\n";
384                 } else {
385                         $$dst .= "[no followups, yet] ($expand)\n";
386                 }
387                 $ctx->{next_msg} = undef;
388                 $ctx->{parent_msg} = $parent;
389                 return;
390         }
391
392         $$dst .= "$nr+ messages in thread ($expand";
393         $$dst .= qq! / <a\nhref="#b">[top]</a>)\n!;
394
395         my $subj = $srch->subject_path($hdr->header('Subject'));
396         my $state = {
397                 seen => { $subj => 1 },
398                 srch => $srch,
399                 cur => $mid,
400                 prev_attr => '',
401                 prev_level => 0,
402                 upfx => "$tpfx../",
403                 dst => $dst,
404         };
405         walk_thread(thread_results(load_results($sres)), $state, *skel_dump);
406         $ctx->{next_msg} = $state->{next_msg};
407         $ctx->{parent_msg} = $parent;
408 }
409
410 sub _parent_headers {
411         my ($hdr, $srch) = @_;
412         my $rv = '';
413
414         my $irt = in_reply_to($hdr);
415         if (defined $irt) {
416                 my $v = PublicInbox::Hval->new_msgid($irt, 1);
417                 my $html = $v->as_html;
418                 my $href = $v->as_href;
419                 $rv .= "In-Reply-To: &lt;";
420                 $rv .= "<a\nhref=\"../$href/\">$html</a>&gt;\n";
421         }
422
423         # do not display References: if search is present,
424         # we show the thread skeleton at the bottom, instead.
425         return $rv if $srch;
426
427         my $refs = $hdr->header_raw('References');
428         if ($refs) {
429                 # avoid redundant URLs wasting bandwidth
430                 my %seen;
431                 $seen{$irt} = 1 if defined $irt;
432                 my @refs;
433                 my @raw_refs = ($refs =~ /<([^>]+)>/g);
434                 foreach my $ref (@raw_refs) {
435                         next if $seen{$ref};
436                         $seen{$ref} = 1;
437                         push @refs, linkify_ref_nosrch($ref);
438                 }
439
440                 if (@refs) {
441                         $rv .= 'References: '. join("\n\t", @refs) . "\n";
442                 }
443         }
444         $rv;
445 }
446
447 sub mailto_arg_link {
448         my ($hdr) = @_;
449         my %cc; # everyone else
450         my $to; # this is the From address
451
452         foreach my $h (qw(From To Cc)) {
453                 my $v = $hdr->header($h);
454                 defined($v) && ($v ne '') or next;
455                 my @addrs = PublicInbox::Address::emails($v);
456                 foreach my $address (@addrs) {
457                         my $dst = lc($address);
458                         $cc{$dst} ||= $address;
459                         $to ||= $dst;
460                 }
461         }
462         my @arg;
463
464         my $subj = $hdr->header('Subject') || '';
465         $subj = "Re: $subj" unless $subj =~ /\bRe:/i;
466         my $mid = $hdr->header_raw('Message-ID');
467         push @arg, "--in-reply-to='" . ascii_html($mid) . "'";
468         my $irt = uri_escape_utf8($mid);
469         delete $cc{$to};
470         push @arg, '--to=' . ascii_html($to);
471         $to = uri_escape_utf8($to);
472         $subj = uri_escape_utf8($subj);
473         my $cc = join(',', sort values %cc);
474         push @arg, '--cc=' . ascii_html($cc);
475         $cc = uri_escape_utf8($cc);
476         my $href = "mailto:$to?In-Reply-To=$irt&Cc=${cc}&Subject=$subj";
477         $href =~ s/%20/+/g;
478
479         (\@arg, $href);
480 }
481
482 sub html_footer {
483         my ($hdr, $standalone, $ctx, $rhref) = @_;
484
485         my $srch = $ctx->{srch} if $ctx;
486         my $upfx = '../';
487         my $tpfx = '';
488         my $idx = $standalone ? " <a\nhref=\"$upfx\">index</a>" : '';
489         my $irt = '';
490         if ($idx && $srch) {
491                 $idx .= "\n";
492                 thread_skel(\$idx, $ctx, $hdr, $tpfx);
493                 my $p = $ctx->{parent_msg};
494                 my $next = $ctx->{next_msg};
495                 if ($p) {
496                         $p = PublicInbox::Hval->new_msgid($p);
497                         $p = $p->as_href;
498                         $irt = "<a\nhref=\"$upfx$p/\"rel=prev>parent</a> ";
499                 } else {
500                         $irt = ' ' x length('parent ');
501                 }
502                 if ($next) {
503                         my $n = PublicInbox::Hval->new_msgid($next)->as_href;
504                         $irt .= "<a\nhref=\"$upfx$n/\"\nrel=next>next</a> ";
505                 } else {
506                         $irt .= ' ' x length('next ');
507                 }
508         } else {
509                 $irt = '';
510         }
511         $rhref ||= '#R';
512         $irt .= qq(<a\nhref="$rhref">reply</a>);
513         $irt .= $idx;
514 }
515
516 sub linkify_ref_nosrch {
517         my $v = PublicInbox::Hval->new_msgid($_[0], 1);
518         my $html = $v->as_html;
519         my $href = $v->as_href;
520         "&lt;<a\nhref=\"../$href/\">$html</a>&gt;";
521 }
522
523 sub anchor_for {
524         my ($msgid) = @_;
525         my $id = $msgid;
526         if ($id !~ /\A[a-f0-9]{40}\z/) {
527                 $id = id_compress(mid_clean($id), 1);
528         }
529         'm' . $id;
530 }
531
532 sub thread_html_head {
533         my ($hdr, $state) = @_;
534         my $res = delete $state->{res} or die "BUG: no Plack callback in {res}";
535         my $fh = $res->([200, ['Content-Type'=> 'text/html; charset=UTF-8']]);
536         $state->{fh} = $fh;
537
538         my $s = ascii_html($hdr->header('Subject'));
539         $fh->write("<html><head><title>$s</title>".
540                 qq{<link\nrel=alternate\ntitle="Atom feed"\n} .
541                 qq!href="../t.atom"\ntype="application/atom+xml"/>! .
542                 PublicInbox::Hval::STYLE .
543                 "</head><body>");
544 }
545
546 sub pre_anchor_entry {
547         my ($seen, $mime) = @_;
548         my $id = anchor_for(mid_mime($mime));
549         $seen->{$id} = "#$id"; # save the anchor for children, later
550 }
551
552 sub ghost_parent {
553         my ($upfx, $mid) = @_;
554         # 'subject dummy' is used internally by Mail::Thread
555         return '[no common parent]' if ($mid eq 'subject dummy');
556
557         $mid = PublicInbox::Hval->new_msgid($mid);
558         my $href = $mid->as_href;
559         my $html = $mid->as_html;
560         qq{[parent not found: &lt;<a\nhref="$upfx$href/">$html</a>&gt;]};
561 }
562
563 sub thread_adj_level {
564         my ($state, $level) = @_;
565
566         my $max = $state->{cur_level};
567         if ($level <= 0) {
568                 return '' if $max == 0; # flat output
569
570                 # reset existing lists
571                 my $x = $max > 1 ? ('</ul></li>' x ($max - 1)) : '';
572                 $state->{fh}->write($x . '</ul>');
573                 $state->{cur_level} = 0;
574                 return '';
575         }
576         if ($level == $max) { # continue existing list
577                 $state->{fh}->write('<li>');
578         } elsif ($level < $max) {
579                 my $x = $max > 1 ? ('</ul></li>' x ($max - $level)) : '';
580                 $state->{fh}->write($x .= '<li>');
581                 $state->{cur_level} = $level;
582         } else { # ($level > $max) # start a new level
583                 $state->{cur_level} = $level;
584                 $state->{fh}->write(($max ? '<li>' : '') . '<ul><li>');
585         }
586         '</li>';
587 }
588
589 sub ghost_flush {
590         my ($state, $upfx, $mid, $level) = @_;
591         my $end = '<pre>'. ghost_parent($upfx, $mid) . '</pre>';
592         $state->{fh}->write($end .= thread_adj_level($state, $level));
593 }
594
595 sub __thread_entry {
596         my ($state, $mime, $level) = @_;
597
598         # lazy load the full message from mini_mime:
599         $mime = eval {
600                 my $mid = mid_clean(mid_mime($mime));
601                 $state->{ctx}->{-inbox}->msg_by_mid($mid);
602         } or return;
603         $mime = Email::MIME->new($mime);
604
605         thread_html_head($mime, $state) if $state->{anchor_idx} == 0;
606         if (my $ghost = delete $state->{ghost}) {
607                 # n.b. ghost messages may only be parents, not children
608                 foreach my $g (@$ghost) {
609                         ghost_flush($state, '../../', @$g);
610                 }
611         }
612         my $end = thread_adj_level($state, $level);
613         index_entry($mime, $level, $state);
614         $state->{fh}->write($end) if $end;
615
616         1;
617 }
618
619 sub indent_for {
620         my ($level) = @_;
621         INDENT x ($level - 1);
622 }
623
624 sub __ghost_prepare {
625         my ($state, $node, $level) = @_;
626         my $ghost = $state->{ghost} ||= [];
627         push @$ghost, [ $node->messageid, $level ];
628 }
629
630 sub thread_entry {
631         my ($state, $level, $node) = @_;
632         if (my $mime = $node->message) {
633                 unless (__thread_entry($state, $mime, $level)) {
634                         __ghost_prepare($state, $node, $level);
635                 }
636         } else {
637                 __ghost_prepare($state, $node, $level);
638         }
639 }
640
641 sub load_results {
642         my ($sres) = @_;
643
644         [ map { $_->mini_mime } @{delete $sres->{msgs}} ];
645 }
646
647 sub msg_timestamp {
648         my ($hdr) = @_;
649         my $ts = eval { str2time($hdr->header('Date')) };
650         defined($ts) ? $ts : 0;
651 }
652
653 sub thread_results {
654         my ($msgs) = @_;
655         require PublicInbox::Thread;
656         my $th = PublicInbox::Thread->new(@$msgs);
657         $th->thread;
658         $th->order(*sort_ts);
659         $th
660 }
661
662 sub missing_thread {
663         my ($res, $ctx) = @_;
664         require PublicInbox::ExtMsg;
665
666         $res->(PublicInbox::ExtMsg::ext_msg($ctx))
667 }
668
669 sub _msg_date {
670         my ($hdr) = @_;
671         my $ts = $hdr->header('X-PI-TS') || msg_timestamp($hdr);
672         fmt_ts($ts);
673 }
674
675 sub fmt_ts { POSIX::strftime('%Y-%m-%d %k:%M', gmtime($_[0])) }
676
677 sub _skel_header {
678         my ($state, $hdr, $level) = @_;
679
680         my $dst = $state->{dst};
681         my $cur = $state->{cur};
682         my $mid = mid_clean($hdr->header_raw('Message-ID'));
683         my $f = ascii_html($hdr->header('X-PI-From'));
684         my $d = _msg_date($hdr);
685         my $pfx = "$d " . indent_for($level) . th_pfx($level);
686         my $attr = $f;
687         $state->{first_level} ||= $level;
688
689         if ($attr ne $state->{prev_attr} || $state->{prev_level} > $level) {
690                 $state->{prev_attr} = $attr;
691         } else {
692                 $attr = '';
693         }
694         $state->{prev_level} = $level;
695
696         if ($cur) {
697                 if ($cur eq $mid) {
698                         delete $state->{cur};
699                         $$dst .= "$pfx<b><a\nid=r\nhref=\"#t\">".
700                                  "$attr [this message]</a></b>\n";
701
702                         return;
703                 }
704         } else {
705                 $state->{next_msg} ||= $mid;
706         }
707
708         # Subject is never undef, this mail was loaded from
709         # our Xapian which would've resulted in '' if it were
710         # really missing (and Filter rejects empty subjects)
711         my $s = $hdr->header('Subject');
712         my $h = $state->{srch}->subject_path($s);
713         if ($state->{seen}->{$h}) {
714                 $s = undef;
715         } else {
716                 $state->{seen}->{$h} = 1;
717                 $s = PublicInbox::Hval->new($s);
718                 $s = $s->as_html;
719         }
720         my $m = PublicInbox::Hval->new_msgid($mid);
721         $m = $state->{upfx} . $m->as_href . '/';
722         $$dst .= "$pfx<a\nhref=\"$m\">";
723         $$dst .= defined($s) ? "$s</a> $f\n" : "$f</a>\n";
724 }
725
726 sub skel_dump {
727         my ($state, $level, $node) = @_;
728         if (my $mime = $node->message) {
729                 my $hdr = $mime->header_obj;
730                 my $mid = mid_clean($hdr->header_raw('Message-ID'));
731                 _skel_header($state, $hdr, $level);
732         } else {
733                 my $mid = $node->messageid;
734                 my $dst = $state->{dst};
735                 if ($mid eq 'subject dummy') {
736                         $$dst .= "\t[no common parent]\n";
737                 } else {
738                         $$dst .= '     [not found] ';
739                         $$dst .= indent_for($level) . th_pfx($level);
740                         $mid = PublicInbox::Hval->new_msgid($mid);
741                         my $href = $state->{upfx} . $mid->as_href . '/';
742                         my $html = $mid->as_html;
743                         $$dst .= qq{&lt;<a\nhref="$href">$html</a>&gt;\n};
744                 }
745         }
746 }
747
748 sub sort_ts {
749         sort {
750                 (eval { $a->topmost->message->header('X-PI-TS') } || 0) <=>
751                 (eval { $b->topmost->message->header('X-PI-TS') } || 0)
752         } @_;
753 }
754
755 sub _tryload_ghost ($$) {
756         my ($srch, $mid) = @_;
757         my $smsg = $srch->lookup_mail($mid) or return;
758         $smsg->mini_mime;
759 }
760
761 # accumulate recent topics if search is supported
762 # returns 1 if done, undef if not
763 sub add_topic {
764         my ($state, $level, $node) = @_;
765         my $srch = $state->{srch};
766         my $mid = $node->messageid;
767         my $x = $node->message || _tryload_ghost($srch, $mid);
768         my ($subj, $ts);
769         if ($x) {
770                 $x = $x->header_obj;
771                 $subj = $x->header('Subject');
772                 $subj = $srch->subject_normalized($subj);
773                 $ts = $x->header('X-PI-TS');
774         } else { # ghost message, do not bump level
775                 $ts = -666;
776                 $subj = "<$mid>";
777         }
778         if (++$state->{subjs}->{$subj} == 1) {
779                 push @{$state->{order}}, [ $level, $subj ];
780         }
781         my $exist = $state->{latest}->{$subj};
782         if (!$exist || $exist->[1] < $ts) {
783                 $state->{latest}->{$subj} = [ $mid, $ts ];
784         }
785 }
786
787 sub emit_topics {
788         my ($state) = @_;
789         my $order = $state->{order};
790         my $subjs = $state->{subjs};
791         my $latest = $state->{latest};
792         my $fh = $state->{fh};
793         return $fh->write("\n[No topics in range]</pre>") unless scalar @$order;
794         my $pfx;
795         my $prev = 0;
796         my $prev_attr = '';
797         my $cur;
798         my @recent;
799         while (defined(my $info = shift @$order)) {
800                 my ($level, $subj) = @$info;
801                 my $n = delete $subjs->{$subj};
802                 my ($mid, $ts) = @{delete $latest->{$subj}};
803                 $mid = PublicInbox::Hval->new_msgid($mid)->as_href;
804                 $pfx = indent_for($level);
805                 my $nl = $level == $prev ? "\n" : '';
806                 if ($nl && $cur) {
807                         push @recent, $cur;
808                         $cur = undef;
809                 }
810                 $cur ||= [ $ts, '' ];
811                 $cur->[0] = $ts if $ts > $cur->[0];
812                 $cur->[1] .= $nl . $pfx . th_pfx($level);
813                 if ($ts == -666) { # ghost
814                         $cur->[1] .= ghost_parent('', $mid) . "\n";
815                         next; # child will have mbox / atom link
816                 }
817
818                 $subj = PublicInbox::Hval->new($subj)->as_html;
819                 $cur->[1] .= "<a\nhref=\"$mid/t/#u\"><b>$subj</b></a>\n";
820                 $ts = fmt_ts($ts);
821                 my $attr = " $ts UTC";
822
823                 # $n isn't the total number of posts on the topic,
824                 # just the number of posts in the current results window
825                 $n = $n == 1 ? '' : " ($n+ messages)";
826
827                 if ($level == 0 || $attr ne $prev_attr) {
828                         my $mbox = qq(<a\nhref="$mid/t.mbox.gz">mbox.gz</a>);
829                         my $atom = qq(<a\nhref="$mid/t.atom">Atom</a>);
830                         $pfx .= INDENT if $level > 0;
831                         $cur->[1] .= $pfx . $attr . $n . " - $mbox / $atom\n";
832                         $prev_attr = $attr;
833                 }
834         }
835         push @recent, $cur if $cur;
836         @recent = map { $_->[1] } sort { $b->[0] <=> $a->[0] } @recent;
837         $fh->write(join('', @recent) . '</pre>');
838 }
839
840 sub emit_index_topics {
841         my ($state) = @_;
842         my ($off) = (($state->{ctx}->{cgi}->param('o') || '0') =~ /(\d+)/);
843         $state->{order} = [];
844         $state->{subjs} = {};
845         $state->{latest} = {};
846         my $max = 25;
847         my %opts = ( offset => $off, limit => $max * 4 );
848         while (scalar @{$state->{order}} < $max) {
849                 my $sres = $state->{srch}->query('', \%opts);
850                 my $nr = scalar @{$sres->{msgs}} or last;
851                 $sres = load_results($sres);
852                 walk_thread(thread_results($sres), $state, *add_topic);
853                 $opts{offset} += $nr;
854         }
855
856         emit_topics($state);
857         $opts{offset};
858 }
859
860 1;