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