]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
feed: remove unnecessary encoding lookup
[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 # 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         # try to avoid the type attribute in title:
42         $title = PublicInbox::Hval->new_oneline($title)->as_html;
43         my $type = index($title, '&') >= 0 ? "\ntype=\"html\"" : '';
44         "<title$type>$title</title>";
45 }
46
47 sub atom_header {
48         my ($feed_opts, $title) = @_;
49
50         $title = title_tag($feed_opts->{description}) unless (defined $title);
51
52         qq(<?xml version="1.0" encoding="us-ascii"?>\n) .
53         qq{<feed\nxmlns="http://www.w3.org/2005/Atom">} .
54         qq{$title} .
55         qq(<link\nrel="alternate"\ntype="text/html") .
56                 qq(\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 = $ctx->{git} ||= PublicInbox::Git->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         end_feed($fh);
77 }
78
79 sub _no_thread {
80         my ($cb) = @_;
81         my $fh = $cb->([404, ['Content-Type' => 'text/plain']]);
82         $fh->write("No feed found for thread\n");
83         $fh->close;
84 }
85
86 sub end_feed {
87         my ($fh) = @_;
88         Email::Address->purge_cache;
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 $fh = $cb->([200, ['Content-Type' => 'application/atom+xml']]);
98         my $feed_opts = get_feedopts($ctx);
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 emit_html_index {
113         my ($cb, $ctx) = @_;
114         my $fh = $cb->([200,['Content-Type'=>'text/html; charset=UTF-8']]);
115
116         my $max = $ctx->{max} || MAX_PER_PAGE;
117         my $feed_opts = get_feedopts($ctx);
118
119         my $title = $feed_opts->{description} || '';
120         $title = PublicInbox::Hval->new_oneline($title)->as_html;
121         my ($footer, $param, $last);
122         my $state = { ctx => $ctx, seen => {}, anchor_idx => 0 };
123         my $srch = $ctx->{srch};
124
125         my $top = "<b>$title</b> (<a\nhref=\"new.atom\">Atom feed</a>)";
126
127         if ($srch) {
128                 $top = qq{<form\naction=""><pre>$top} .
129                           qq{ <input\nname=q\ntype=text />} .
130                           qq{<input\ntype=submit\nvalue=search />} .
131                           q{</pre></form><pre>}
132         } else {
133                 $top = '<pre>' . $top . "\n";
134         }
135
136         $fh->write("<html><head><title>$title</title>" .
137                    "<link\nrel=alternate\ntitle=\"Atom feed\"\n".
138                    "href=\"new.atom\"\ntype=\"application/atom+xml\"/>" .
139                    PublicInbox::Hval::STYLE .
140                    "</head><body>$top");
141
142         # if the 'r' query parameter is given, it is a legacy permalink
143         # which we must continue supporting:
144         my $cgi = $ctx->{cgi};
145         if ($cgi && !$cgi->param('r') && $srch) {
146                 $state->{srch} = $srch;
147                 $last = PublicInbox::View::emit_index_topics($state, $fh);
148                 $param = 'o';
149         } else {
150                 $last = emit_index_nosrch($ctx, $state, $fh);
151                 $param = 'r';
152         }
153         $footer = nav_footer($cgi, $last, $feed_opts, $state, $param);
154         if ($footer) {
155                 my $list_footer = $ctx->{footer};
156                 $footer .= "\n\n" . $list_footer if $list_footer;
157                 $footer = "<hr /><pre>$footer</pre>";
158         }
159         $fh->write("$footer</body></html>");
160         $fh->close;
161 }
162
163 sub emit_index_nosrch {
164         my ($ctx, $state, $fh) = @_;
165         my $git = $ctx->{git} ||= PublicInbox::Git->new($ctx->{git_dir});
166         my (undef, $last) = each_recent_blob($ctx, sub {
167                 my ($path, $commit, $ts, $u, $subj) = @_;
168                 $state->{first} ||= $commit;
169
170                 my $mime = do_cat_mail($git, $path) or return 0;
171                 PublicInbox::View::index_entry($fh, $mime, 0, $state);
172                 1;
173         });
174         Email::Address->purge_cache;
175         $last;
176 }
177
178 sub nav_footer {
179         my ($cgi, $last, $feed_opts, $state, $param) = @_;
180         $cgi or return '';
181         my $old_r = $cgi->param($param);
182         my $head = '    ';
183         my $next = '    ';
184         my $first = $state->{first};
185         my $anchor = $state->{anchor_idx};
186
187         if ($last) {
188                 $next = qq!<a\nhref="?$param=$last">next</a>!;
189         }
190         if ($old_r) {
191                 $head = $cgi->path_info;
192                 $head = qq!<a\nhref="$head">head</a>!;
193         }
194         my $atom = "<a\nhref=\"$feed_opts->{atomurl}\">Atom feed</a>";
195         "<a\nname=\"s$anchor\">page:</a> $next $head $atom";
196 }
197
198 sub each_recent_blob {
199         my ($ctx, $cb) = @_;
200         my $max = $ctx->{max} || MAX_PER_PAGE;
201         my $hex = '[a-f0-9]';
202         my $addmsg = qr!^:000000 100644 \S+ \S+ A\t(${hex}{2}/${hex}{38})$!;
203         my $delmsg = qr!^:100644 000000 \S+ \S+ D\t(${hex}{2}/${hex}{38})$!;
204         my $refhex = qr/(?:HEAD|${hex}{4,40})(?:~\d+)?/;
205         my $cgi = $ctx->{cgi};
206
207         # revision ranges may be specified
208         my $range = 'HEAD';
209         my $r = $cgi->param('r') if $cgi;
210         if ($r && ($r =~ /\A(?:$refhex\.\.)?$refhex\z/o)) {
211                 $range = $r;
212         }
213
214         # get recent messages
215         # we could use git log -z, but, we already know ssoma will not
216         # leave us with filenames with spaces in them..
217         my $git = $ctx->{git} ||= PublicInbox::Git->new($ctx->{git_dir});
218         my $log = $git->popen(qw/log --no-notes --no-color --raw -r
219                                 --abbrev=16 --abbrev-commit/,
220                                 "--format=%h%x00%ct%x00%an%x00%s%x00",
221                                 $range);
222         my %deleted; # only an optimization at this point
223         my $last;
224         my $nr = 0;
225         my ($cur_commit, $first_commit, $last_commit);
226         my ($ts, $subj, $u);
227         while (defined(my $line = <$log>)) {
228                 if ($line =~ /$addmsg/o) {
229                         my $add = $1;
230                         next if $deleted{$add}; # optimization-only
231                         $nr += $cb->($add, $cur_commit, $ts, $u, $subj);
232                         if ($nr >= $max) {
233                                 $last = 1;
234                                 last;
235                         }
236                 } elsif ($line =~ /$delmsg/o) {
237                         $deleted{$1} = 1;
238                 } elsif ($line =~ /^${hex}{7,40}/o) {
239                         ($cur_commit, $ts, $u, $subj) = split("\0", $line);
240                         unless (defined $first_commit) {
241                                 $first_commit = $cur_commit;
242                         }
243                 }
244         }
245
246         if ($last) {
247                 while (my $line = <$log>) {
248                         if ($line =~ /^(${hex}{7,40})/o) {
249                                 $last_commit = $1;
250                                 last;
251                         }
252                 }
253         }
254
255         # for pagination
256         ($first_commit, $last_commit);
257 }
258
259 # private functions below
260 sub get_feedopts {
261         my ($ctx) = @_;
262         my $pi_config = $ctx->{pi_config};
263         my $listname = $ctx->{listname};
264         my $cgi = $ctx->{cgi};
265         my %rv;
266         if (open my $fh, '<', "$ctx->{git_dir}/description") {
267                 chomp($rv{description} = <$fh>);
268         } else {
269                 $rv{description} = '($GIT_DIR/description missing)';
270         }
271
272         if ($pi_config && defined $listname && $listname ne '') {
273                 my $addr = $pi_config->get($listname, 'address') || "";
274                 $rv{address} = $addr;
275                 $addr = $addr->[0] if ref($addr);
276                 $rv{id_addr} = $addr;
277         }
278         $rv{id_addr} ||= 'public-inbox@example.com';
279
280         my $url_base;
281         if ($cgi) {
282                 $url_base = $cgi->base->as_string . $listname;
283                 if (my $mid = $ctx->{mid}) { # per-thread feed:
284                         $rv{atomurl} = "$url_base/$mid/t.atom";
285                 } else {
286                         $rv{atomurl} = "$url_base/new.atom";
287                 }
288         } else {
289                 $url_base = "http://example.com";
290                 $rv{atomurl} = "$url_base/new.atom";
291         }
292         $rv{url} ||= "$url_base/";
293         $rv{midurl} = "$url_base/";
294
295         \%rv;
296 }
297
298 sub mime_header {
299         my ($mime, $name) = @_;
300         PublicInbox::Hval->new_oneline($mime->header($name))->raw;
301 }
302
303 sub feed_updated {
304         my ($date, $ts) = @_;
305         my @t = eval { strptime($date) } if defined $date;
306         @t = gmtime($ts || time) unless scalar @t;
307
308         '<updated>' . strftime(DATEFMT, @t) . '</updated>';
309 }
310
311 # returns 0 (skipped) or 1 (added)
312 sub add_to_feed {
313         my ($feed_opts, $fh, $add, $git) = @_;
314
315         my $mime = do_cat_mail($git, $add) or return 0;
316         my $url = $feed_opts->{url};
317         my $midurl = $feed_opts->{midurl};
318
319         my $header_obj = $mime->header_obj;
320         my $mid = $header_obj->header_raw('Message-ID');
321         defined $mid or return 0;
322         $mid = PublicInbox::Hval->new_msgid($mid);
323         my $href = $mid->as_href;
324         my $content = PublicInbox::View->feed_entry($mime, "$midurl$href/f/");
325         defined($content) or return 0;
326         $mime = undef;
327
328         my $date = $header_obj->header('Date');
329         my $updated = feed_updated($date);
330
331         my $title = mime_header($header_obj, 'Subject') or return 0;
332         $title = title_tag($title);
333
334         my $from = mime_header($header_obj, 'From') or return 0;
335         my @from = Email::Address->parse($from) or return 0;
336         my $name = PublicInbox::Hval->new_oneline($from[0]->name)->as_html;
337         my $email = $from[0]->address;
338         $email = PublicInbox::Hval->new_oneline($email)->as_html;
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="$midurl$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;