]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
www_stream: add response wrapper sub
[public-inbox.git] / lib / PublicInbox / Feed.pm
1 # Copyright (C) 2013-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 generating Atom feeds for web-accessible mailing list archives.
5 package PublicInbox::Feed;
6 use strict;
7 use warnings;
8 use Email::MIME;
9 use Date::Parse qw(strptime);
10 use PublicInbox::Hval qw/ascii_html/;
11 use PublicInbox::Git;
12 use PublicInbox::View;
13 use PublicInbox::MID qw/mid_clean mid2path/;
14 use PublicInbox::Address;
15 use POSIX qw/strftime/;
16 use constant {
17         DATEFMT => '%Y-%m-%dT%H:%M:%SZ', # Atom standard
18         MAX_PER_PAGE => 25, # this needs to be tunable
19 };
20
21 # main function
22 sub generate {
23         my ($ctx) = @_;
24         sub { emit_atom($_[0], $ctx) };
25 }
26
27 sub generate_thread_atom {
28         my ($ctx) = @_;
29         sub { emit_atom_thread($_[0], $ctx) };
30 }
31
32 sub generate_html_index {
33         my ($ctx) = @_;
34         sub { emit_html_index($_[0], $ctx) };
35 }
36
37 sub new_html {
38         my ($ctx) = @_;
39         my @paths;
40         my (undef, $last) = each_recent_blob($ctx, sub {
41                 my ($path, $commit, $ts, $u, $subj) = @_;
42                 $ctx->{first} ||= $commit;
43                 push @paths, $path;
44         });
45         if (!@paths) {
46                 return [404, ['Content-Type', 'text/plain'],
47                         ["No messages, yet\n"] ];
48         }
49         $ctx->{-html_tip} = '<pre>';
50         $ctx->{-upfx} = '';
51         PublicInbox::WwwStream->response($ctx, 200, sub {
52                 while (my $path = shift @paths) {
53                         my $m = do_cat_mail($ctx->{-inbox}, $path) or next;
54                         my $more = scalar @paths;
55                         my $s = PublicInbox::View::index_entry($m, $ctx, $more);
56                         $s .= '</pre>' unless $more;
57                         return $s;
58                 }
59                 undef;
60         });
61 }
62
63 # private subs
64
65 sub title_tag {
66         my ($title) = @_;
67         $title =~ tr/\t\n / /s; # squeeze spaces
68         # try to avoid the type attribute in title:
69         $title = ascii_html($title);
70         my $type = index($title, '&') >= 0 ? "\ntype=\"html\"" : '';
71         "<title$type>$title</title>";
72 }
73
74 sub atom_header {
75         my ($feed_opts, $title) = @_;
76
77         $title = title_tag($feed_opts->{description}) unless (defined $title);
78
79         qq(<?xml version="1.0" encoding="us-ascii"?>\n) .
80         qq{<feed\nxmlns="http://www.w3.org/2005/Atom">} .
81         qq{$title} .
82         qq(<link\nrel="alternate"\ntype="text/html") .
83                 qq(\nhref="$feed_opts->{url}"/>) .
84         qq(<link\nrel="self"\nhref="$feed_opts->{atomurl}"/>) .
85         qq(<id>mailto:$feed_opts->{id_addr}</id>);
86 }
87
88 sub emit_atom {
89         my ($cb, $ctx) = @_;
90         my $feed_opts = get_feedopts($ctx);
91         my $fh = $cb->([ 200, ['Content-Type' => 'application/atom+xml']]);
92         my $max = $ctx->{max} || MAX_PER_PAGE;
93         my $x = atom_header($feed_opts);
94         my $ibx = $ctx->{-inbox};
95         each_recent_blob($ctx, sub {
96                 my ($path, undef, $ts) = @_;
97                 if (defined $x) {
98                         $fh->write($x . feed_updated(undef, $ts));
99                         $x = undef;
100                 }
101                 my $s = feed_entry($feed_opts, $path, $ibx) or return 0;
102                 $fh->write($s);
103                 1;
104         });
105         end_feed($fh);
106 }
107
108 sub _no_thread {
109         my ($cb) = @_;
110         $cb->([404, ['Content-Type', 'text/plain'],
111                 ["No feed found for thread\n"]]);
112 }
113
114 sub end_feed {
115         my ($fh) = @_;
116         $fh->write('</feed>');
117         $fh->close;
118 }
119
120 sub emit_atom_thread {
121         my ($cb, $ctx) = @_;
122         my $res = $ctx->{srch}->get_thread($ctx->{mid});
123         return _no_thread($cb) unless $res->{total};
124         my $feed_opts = get_feedopts($ctx);
125         my $fh = $cb->([200, ['Content-Type' => 'application/atom+xml']]);
126
127         my $html_url = $feed_opts->{atomurl} = $ctx->{self_url};
128         $html_url =~ s!/t\.atom\z!/!;
129         $feed_opts->{url} = $html_url;
130         $feed_opts->{emit_header} = 1;
131
132         my $ibx = $ctx->{-inbox};
133         foreach my $msg (@{$res->{msgs}}) {
134                 my $s = feed_entry($feed_opts, mid2path($msg->mid), $ibx);
135                 $fh->write($s) if defined $s;
136         }
137         end_feed($fh);
138 }
139
140 sub _html_index_top {
141         my ($feed_opts, $srch) = @_;
142
143         my $title = ascii_html($feed_opts->{description} || '');
144         my $top = "<b>$title</b> (<a\nhref=\"new.atom\">Atom feed</a>)";
145         if ($srch) {
146                 $top = qq{<form\naction=""><pre>$top} .
147                           qq{ <input\nname=q\ntype=text />} .
148                           qq{<input\ntype=submit\nvalue=search />} .
149                           q{</pre></form><pre>}
150         } else {
151                 $top = '<pre>' . $top . "\n";
152         }
153
154         "<html><head><title>$title</title>" .
155                 "<link\nrel=alternate\ntitle=\"Atom feed\"\n".
156                 "href=\"new.atom\"\ntype=\"application/atom+xml\"/>" .
157                 PublicInbox::Hval::STYLE .
158                 "</head><body>$top";
159 }
160
161 sub emit_html_index {
162         my ($res, $ctx) = @_;
163         my $feed_opts = get_feedopts($ctx);
164         my $fh = $res->([200,['Content-Type'=>'text/html; charset=UTF-8']]);
165
166         my $max = $ctx->{max} || MAX_PER_PAGE;
167         $ctx->{-upfx} = '';
168
169         my ($footer, $param, $last);
170         $ctx->{seen} = {};
171         $ctx->{anchor_idx} = 0;
172         $ctx->{fh} = $fh;
173         my $srch = $ctx->{srch};
174         $fh->write(_html_index_top($feed_opts, $srch));
175
176         # if the 'r' query parameter is given, it is a legacy permalink
177         # which we must continue supporting:
178         my $qp = $ctx->{qp};
179         if ($qp && !$qp->{r} && $srch) {
180                 $last = PublicInbox::View::emit_index_topics($ctx);
181                 $param = 'o';
182         } else {
183                 $last = emit_index_nosrch($ctx);
184                 $param = 'r';
185         }
186         $footer = nav_footer($ctx, $last, $feed_opts, $param);
187         if ($footer) {
188                 my $list_footer = $ctx->{footer};
189                 $footer .= "\n\n" . $list_footer if $list_footer;
190                 $footer = "<hr /><pre>$footer</pre>";
191         }
192         $fh->write("$footer</body></html>");
193         $fh->close;
194 }
195
196 sub emit_index_nosrch {
197         my ($ctx) = @_;
198         my $ibx = $ctx->{-inbox};
199         my $fh = $ctx->{fh};
200         my (undef, $last) = each_recent_blob($ctx, sub {
201                 my ($path, $commit, $ts, $u, $subj) = @_;
202                 $ctx->{first} ||= $commit;
203
204                 my $mime = do_cat_mail($ibx, $path) or return 0;
205                 $fh->write(PublicInbox::View::index_entry($mime, $ctx, 1));
206                 1;
207         });
208         $last;
209 }
210
211 sub nav_footer {
212         my ($ctx, $last, $feed_opts, $param) = @_;
213         my $qp = $ctx->{qp} or return '';
214         my $old_r = $qp->{$param};
215         my $head = '    ';
216         my $next = '    ';
217         my $first = $ctx->{first};
218         my $anchor = $ctx->{anchor_idx};
219
220         if ($last) {
221                 $next = qq!<a\nhref="?$param=$last"\nrel=next>next</a>!;
222         }
223         if ($old_r) {
224                 $head = $ctx->{env}->{PATH_INFO};
225                 $head = qq!<a\nhref="$head">head</a>!;
226         }
227         my $atom = "<a\nhref=\"$feed_opts->{atomurl}\">Atom feed</a>";
228         "<a\nname=\"s$anchor\">page:</a> $next $head $atom";
229 }
230
231 sub each_recent_blob {
232         my ($ctx, $cb) = @_;
233         my $max = $ctx->{max} || MAX_PER_PAGE;
234         my $hex = '[a-f0-9]';
235         my $addmsg = qr!^:000000 100644 \S+ \S+ A\t(${hex}{2}/${hex}{38})$!;
236         my $delmsg = qr!^:100644 000000 \S+ \S+ D\t(${hex}{2}/${hex}{38})$!;
237         my $refhex = qr/(?:HEAD|${hex}{4,40})(?:~\d+)?/;
238         my $qp = $ctx->{qp};
239
240         # revision ranges may be specified
241         my $range = 'HEAD';
242         my $r = $qp->{r} if $qp;
243         if ($r && ($r =~ /\A(?:$refhex\.\.)?$refhex\z/o)) {
244                 $range = $r;
245         }
246
247         # get recent messages
248         # we could use git log -z, but, we already know ssoma will not
249         # leave us with filenames with spaces in them..
250         my $log = $ctx->{-inbox}->git->popen(qw/log
251                                 --no-notes --no-color --raw -r
252                                 --abbrev=16 --abbrev-commit/,
253                                 "--format=%h%x00%ct%x00%an%x00%s%x00",
254                                 $range);
255         my %deleted; # only an optimization at this point
256         my $last;
257         my $nr = 0;
258         my ($cur_commit, $first_commit, $last_commit);
259         my ($ts, $subj, $u);
260         local $/ = "\n";
261         while (defined(my $line = <$log>)) {
262                 if ($line =~ /$addmsg/o) {
263                         my $add = $1;
264                         next if $deleted{$add}; # optimization-only
265                         $nr += $cb->($add, $cur_commit, $ts, $u, $subj);
266                         if ($nr >= $max) {
267                                 $last = 1;
268                                 last;
269                         }
270                 } elsif ($line =~ /$delmsg/o) {
271                         $deleted{$1} = 1;
272                 } elsif ($line =~ /^${hex}{7,40}/o) {
273                         ($cur_commit, $ts, $u, $subj) = split("\0", $line);
274                         unless (defined $first_commit) {
275                                 $first_commit = $cur_commit;
276                         }
277                 }
278         }
279
280         if ($last) {
281                 local $/ = "\n";
282                 while (my $line = <$log>) {
283                         if ($line =~ /^(${hex}{7,40})/o) {
284                                 $last_commit = $1;
285                                 last;
286                         }
287                 }
288         }
289
290         # for pagination
291         ($first_commit, $last_commit);
292 }
293
294 # private functions below
295 sub get_feedopts {
296         my ($ctx) = @_;
297         my $pi_config = $ctx->{pi_config};
298         my $inbox = $ctx->{inbox};
299         my $obj = $ctx->{-inbox};
300         my $cgi = $ctx->{cgi};
301         my %rv = ( description => $obj->description );
302
303         $rv{address} = $obj->{address};
304         $rv{id_addr} = $obj->{-primary_address};
305         my $url_base;
306         $url_base = $obj->base_url($cgi); # CGI may be undef
307         if (my $mid = $ctx->{mid}) { # per-thread feed:
308                 $rv{atomurl} = "$url_base$mid/t.atom";
309         } else {
310                 $rv{atomurl} = $url_base."new.atom";
311         }
312         $rv{url} ||= $url_base;
313         $rv{midurl} = $url_base;
314
315         \%rv;
316 }
317
318 sub feed_updated {
319         my ($date, $ts) = @_;
320         my @t = eval { strptime($date) } if defined $date;
321         @t = gmtime($ts || time) unless scalar @t;
322
323         '<updated>' . strftime(DATEFMT, @t) . '</updated>';
324 }
325
326 # returns undef or string
327 sub feed_entry {
328         my ($feed_opts, $add, $ibx) = @_;
329
330         my $mime = do_cat_mail($ibx, $add) or return;
331         my $url = $feed_opts->{url};
332         my $midurl = $feed_opts->{midurl};
333
334         my $header_obj = $mime->header_obj;
335         my $mid = $header_obj->header_raw('Message-ID');
336         defined $mid or return;
337         $mid = PublicInbox::Hval->new_msgid($mid);
338         my $href = $midurl.$mid->as_href;
339
340         my $date = $header_obj->header('Date');
341         my $updated = feed_updated($date);
342
343         my $title = $header_obj->header('Subject');
344         defined $title or return;
345         $title = title_tag($title);
346
347         my $from = $header_obj->header('From') or return;
348         my ($email) = PublicInbox::Address::emails($from);
349         my $name = join(', ',PublicInbox::Address::names($from));
350         $name = ascii_html($name);
351         $email = ascii_html($email);
352
353         my $s = '';
354         if (delete $feed_opts->{emit_header}) {
355                 $s .= atom_header($feed_opts, $title) . $updated;
356         }
357         $s .= "<entry><author><name>$name</name><email>$email</email>" .
358                 "</author>$title$updated" .
359                 qq{<content\ntype="xhtml">} .
360                 qq{<div\nxmlns="http://www.w3.org/1999/xhtml">} .
361                 qq(<pre\nstyle="white-space:pre-wrap">) .
362                 PublicInbox::View::multipart_text_as_html($mime, $href) .
363                 '</pre>';
364
365         $add =~ tr!/!!d;
366         my $h = '[a-f0-9]';
367         my (@uuid5) = ($add =~ m!\A($h{8})($h{4})($h{4})($h{4})($h{12})!o);
368         my $id = 'urn:uuid:' . join('-', @uuid5);
369         $s .= qq!</div></content><link\nhref="$href/"/>!.
370                 "<id>$id</id></entry>";
371 }
372
373 sub do_cat_mail {
374         my ($ibx, $path) = @_;
375         my $mime = eval { $ibx->msg_by_path($path) } or return;
376         Email::MIME->new($mime);
377 }
378
379 1;