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