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