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