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