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