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