]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
view: merge $state hash with existing $ctx
[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 $ibx = $ctx->{-inbox};
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                 my $s = feed_entry($feed_opts, $path, $ibx) or return 0;
76                 $fh->write($s);
77                 1;
78         });
79         end_feed($fh);
80 }
81
82 sub _no_thread {
83         my ($cb) = @_;
84         $cb->([404, ['Content-Type', 'text/plain'],
85                 ["No feed found for thread\n"]]);
86 }
87
88 sub end_feed {
89         my ($fh) = @_;
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 $feed_opts = get_feedopts($ctx);
99         my $fh = $cb->([200, ['Content-Type' => 'application/atom+xml']]);
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 $ibx = $ctx->{-inbox};
107         foreach my $msg (@{$res->{msgs}}) {
108                 my $s = feed_entry($feed_opts, mid2path($msg->mid), $ibx);
109                 $fh->write($s) if defined $s;
110         }
111         end_feed($fh);
112 }
113
114 sub _html_index_top {
115         my ($feed_opts, $srch) = @_;
116
117         my $title = ascii_html($feed_opts->{description} || '');
118         my $top = "<b>$title</b> (<a\nhref=\"new.atom\">Atom feed</a>)";
119         if ($srch) {
120                 $top = qq{<form\naction=""><pre>$top} .
121                           qq{ <input\nname=q\ntype=text />} .
122                           qq{<input\ntype=submit\nvalue=search />} .
123                           q{</pre></form><pre>}
124         } else {
125                 $top = '<pre>' . $top . "\n";
126         }
127
128         "<html><head><title>$title</title>" .
129                 "<link\nrel=alternate\ntitle=\"Atom feed\"\n".
130                 "href=\"new.atom\"\ntype=\"application/atom+xml\"/>" .
131                 PublicInbox::Hval::STYLE .
132                 "</head><body>$top";
133 }
134
135 sub emit_html_index {
136         my ($res, $ctx) = @_;
137         my $feed_opts = get_feedopts($ctx);
138         my $fh = $res->([200,['Content-Type'=>'text/html; charset=UTF-8']]);
139
140         my $max = $ctx->{max} || MAX_PER_PAGE;
141         $ctx->{-upfx} = '';
142
143         my ($footer, $param, $last);
144         $ctx->{seen} = {};
145         $ctx->{anchor_idx} = 0;
146         $ctx->{fh} = $fh;
147         my $srch = $ctx->{srch};
148         $fh->write(_html_index_top($feed_opts, $srch));
149
150         # if the 'r' query parameter is given, it is a legacy permalink
151         # which we must continue supporting:
152         my $qp = $ctx->{qp};
153         if ($qp && !$qp->{r} && $srch) {
154                 $last = PublicInbox::View::emit_index_topics($ctx);
155                 $param = 'o';
156         } else {
157                 $last = emit_index_nosrch($ctx);
158                 $param = 'r';
159         }
160         $footer = nav_footer($ctx, $last, $feed_opts, $param);
161         if ($footer) {
162                 my $list_footer = $ctx->{footer};
163                 $footer .= "\n\n" . $list_footer if $list_footer;
164                 $footer = "<hr /><pre>$footer</pre>";
165         }
166         $fh->write("$footer</body></html>");
167         $fh->close;
168 }
169
170 sub emit_index_nosrch {
171         my ($ctx) = @_;
172         my $ibx = $ctx->{-inbox};
173         my $fh = $ctx->{fh};
174         my (undef, $last) = each_recent_blob($ctx, sub {
175                 my ($path, $commit, $ts, $u, $subj) = @_;
176                 $ctx->{first} ||= $commit;
177
178                 my $mime = do_cat_mail($ibx, $path) or return 0;
179                 $fh->write(PublicInbox::View::index_entry($mime, $ctx, 1));
180                 1;
181         });
182         $last;
183 }
184
185 sub nav_footer {
186         my ($ctx, $last, $feed_opts, $param) = @_;
187         my $qp = $ctx->{qp} or return '';
188         my $old_r = $qp->{$param};
189         my $head = '    ';
190         my $next = '    ';
191         my $first = $ctx->{first};
192         my $anchor = $ctx->{anchor_idx};
193
194         if ($last) {
195                 $next = qq!<a\nhref="?$param=$last"\nrel=next>next</a>!;
196         }
197         if ($old_r) {
198                 $head = $ctx->{env}->{PATH_INFO};
199                 $head = qq!<a\nhref="$head">head</a>!;
200         }
201         my $atom = "<a\nhref=\"$feed_opts->{atomurl}\">Atom feed</a>";
202         "<a\nname=\"s$anchor\">page:</a> $next $head $atom";
203 }
204
205 sub each_recent_blob {
206         my ($ctx, $cb) = @_;
207         my $max = $ctx->{max} || MAX_PER_PAGE;
208         my $hex = '[a-f0-9]';
209         my $addmsg = qr!^:000000 100644 \S+ \S+ A\t(${hex}{2}/${hex}{38})$!;
210         my $delmsg = qr!^:100644 000000 \S+ \S+ D\t(${hex}{2}/${hex}{38})$!;
211         my $refhex = qr/(?:HEAD|${hex}{4,40})(?:~\d+)?/;
212         my $qp = $ctx->{qp};
213
214         # revision ranges may be specified
215         my $range = 'HEAD';
216         my $r = $qp->{r} if $qp;
217         if ($r && ($r =~ /\A(?:$refhex\.\.)?$refhex\z/o)) {
218                 $range = $r;
219         }
220
221         # get recent messages
222         # we could use git log -z, but, we already know ssoma will not
223         # leave us with filenames with spaces in them..
224         my $log = $ctx->{-inbox}->git->popen(qw/log
225                                 --no-notes --no-color --raw -r
226                                 --abbrev=16 --abbrev-commit/,
227                                 "--format=%h%x00%ct%x00%an%x00%s%x00",
228                                 $range);
229         my %deleted; # only an optimization at this point
230         my $last;
231         my $nr = 0;
232         my ($cur_commit, $first_commit, $last_commit);
233         my ($ts, $subj, $u);
234         local $/ = "\n";
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                 local $/ = "\n";
256                 while (my $line = <$log>) {
257                         if ($line =~ /^(${hex}{7,40})/o) {
258                                 $last_commit = $1;
259                                 last;
260                         }
261                 }
262         }
263
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 $inbox = $ctx->{inbox};
273         my $obj = $ctx->{-inbox};
274         my $cgi = $ctx->{cgi};
275         my %rv = ( description => $obj->description );
276
277         $rv{address} = $obj->{address};
278         $rv{id_addr} = $obj->{-primary_address};
279         my $url_base;
280         $url_base = $obj->base_url($cgi); # CGI may be undef
281         if (my $mid = $ctx->{mid}) { # per-thread feed:
282                 $rv{atomurl} = "$url_base$mid/t.atom";
283         } else {
284                 $rv{atomurl} = $url_base."new.atom";
285         }
286         $rv{url} ||= $url_base;
287         $rv{midurl} = $url_base;
288
289         \%rv;
290 }
291
292 sub feed_updated {
293         my ($date, $ts) = @_;
294         my @t = eval { strptime($date) } if defined $date;
295         @t = gmtime($ts || time) unless scalar @t;
296
297         '<updated>' . strftime(DATEFMT, @t) . '</updated>';
298 }
299
300 # returns undef or string
301 sub feed_entry {
302         my ($feed_opts, $add, $ibx) = @_;
303
304         my $mime = do_cat_mail($ibx, $add) or return;
305         my $url = $feed_opts->{url};
306         my $midurl = $feed_opts->{midurl};
307
308         my $header_obj = $mime->header_obj;
309         my $mid = $header_obj->header_raw('Message-ID');
310         defined $mid or return;
311         $mid = PublicInbox::Hval->new_msgid($mid);
312         my $href = $midurl.$mid->as_href;
313
314         my $date = $header_obj->header('Date');
315         my $updated = feed_updated($date);
316
317         my $title = $header_obj->header('Subject');
318         defined $title or return;
319         $title = title_tag($title);
320
321         my $from = $header_obj->header('From') or return;
322         my ($email) = PublicInbox::Address::emails($from);
323         my $name = join(', ',PublicInbox::Address::names($from));
324         $name = ascii_html($name);
325         $email = ascii_html($email);
326
327         my $s = '';
328         if (delete $feed_opts->{emit_header}) {
329                 $s .= atom_header($feed_opts, $title) . $updated;
330         }
331         $s .= "<entry><author><name>$name</name><email>$email</email>" .
332                 "</author>$title$updated" .
333                 qq{<content\ntype="xhtml">} .
334                 qq{<div\nxmlns="http://www.w3.org/1999/xhtml">} .
335                 qq(<pre\nstyle="white-space:pre-wrap">) .
336                 PublicInbox::View::multipart_text_as_html($mime, $href) .
337                 '</pre>';
338
339         $add =~ tr!/!!d;
340         my $h = '[a-f0-9]';
341         my (@uuid5) = ($add =~ m!\A($h{8})($h{4})($h{4})($h{4})($h{12})!o);
342         my $id = 'urn:uuid:' . join('-', @uuid5);
343         $s .= qq!</div></content><link\nhref="$href/"/>!.
344                 "<id>$id</id></entry>";
345 }
346
347 sub do_cat_mail {
348         my ($ibx, $path) = @_;
349         my $mime = eval { $ibx->msg_by_path($path) } or return;
350         Email::MIME->new($mime);
351 }
352
353 1;