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