]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
www: label sections and hopefully improve navigation
[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::View;
12 use PublicInbox::MID qw/mid_clean mid2path/;
13 use PublicInbox::Address;
14 use POSIX qw/strftime/;
15 use constant {
16         DATEFMT => '%Y-%m-%dT%H:%M:%SZ', # Atom standard
17         MAX_PER_PAGE => 25, # this needs to be tunable
18 };
19
20 # main function
21 sub generate {
22         my ($ctx) = @_;
23         sub { emit_atom($_[0], $ctx) };
24 }
25
26 sub generate_thread_atom {
27         my ($ctx) = @_;
28         sub { emit_atom_thread($_[0], $ctx) };
29 }
30
31 sub generate_html_index {
32         my ($ctx) = @_;
33         # if the 'r' query parameter is given, it is a legacy permalink
34         # which we must continue supporting:
35         my $qp = $ctx->{qp};
36         if ($qp && !$qp->{r} && $ctx->{srch}) {
37                 return PublicInbox::View::index_topics($ctx);
38         }
39
40         my $env = $ctx->{env};
41         my $url = $ctx->{-inbox}->base_url($env) . 'new.html';
42         my $qs = $env->{QUERY_STRING};
43         $url .= "?$qs" if $qs ne '';
44         [302, [ 'Location', $url, 'Content-Type', 'text/plain'],
45                 [ "Redirecting to $url\n" ] ];
46 }
47
48 sub new_html {
49         my ($ctx) = @_;
50         my @paths;
51         my (undef, $last) = each_recent_blob($ctx, sub {
52                 my ($path, $commit, $ts, $u, $subj) = @_;
53                 $ctx->{first} ||= $commit;
54                 push @paths, $path;
55         });
56         if (!@paths) {
57                 return [404, ['Content-Type', 'text/plain'],
58                         ["No messages, yet\n"] ];
59         }
60         $ctx->{-html_tip} = '<pre>';
61         $ctx->{-upfx} = '';
62         PublicInbox::WwwStream->response($ctx, 200, sub {
63                 while (my $path = shift @paths) {
64                         my $m = do_cat_mail($ctx->{-inbox}, $path) or next;
65                         my $more = scalar @paths;
66                         my $s = PublicInbox::View::index_entry($m, $ctx, $more);
67                         $s .= '</pre>' unless $more;
68                         return $s;
69                 }
70                 new_html_footer($ctx, $last);
71         });
72 }
73
74 # private subs
75
76 sub title_tag {
77         my ($title) = @_;
78         $title =~ tr/\t\n / /s; # squeeze spaces
79         # try to avoid the type attribute in title:
80         $title = ascii_html($title);
81         my $type = index($title, '&') >= 0 ? "\ntype=\"html\"" : '';
82         "<title$type>$title</title>";
83 }
84
85 sub atom_header {
86         my ($feed_opts, $title) = @_;
87
88         $title = title_tag($feed_opts->{description}) unless (defined $title);
89
90         qq(<?xml version="1.0" encoding="us-ascii"?>\n) .
91         qq{<feed\nxmlns="http://www.w3.org/2005/Atom">} .
92         qq{$title} .
93         qq(<link\nrel="alternate"\ntype="text/html") .
94                 qq(\nhref="$feed_opts->{url}"/>) .
95         qq(<link\nrel="self"\nhref="$feed_opts->{atomurl}"/>) .
96         qq(<id>mailto:$feed_opts->{id_addr}</id>);
97 }
98
99 sub emit_atom {
100         my ($cb, $ctx) = @_;
101         my $feed_opts = get_feedopts($ctx);
102         my $fh = $cb->([ 200, ['Content-Type' => 'application/atom+xml']]);
103         my $max = $ctx->{max} || MAX_PER_PAGE;
104         my $x = atom_header($feed_opts);
105         my $ibx = $ctx->{-inbox};
106         each_recent_blob($ctx, sub {
107                 my ($path, undef, $ts) = @_;
108                 if (defined $x) {
109                         $fh->write($x . feed_updated(undef, $ts));
110                         $x = undef;
111                 }
112                 my $s = feed_entry($feed_opts, $path, $ibx) or return 0;
113                 $fh->write($s);
114                 1;
115         });
116         end_feed($fh);
117 }
118
119 sub _no_thread {
120         my ($cb) = @_;
121         $cb->([404, ['Content-Type', 'text/plain'],
122                 ["No feed found for thread\n"]]);
123 }
124
125 sub end_feed {
126         my ($fh) = @_;
127         $fh->write('</feed>');
128         $fh->close;
129 }
130
131 sub emit_atom_thread {
132         my ($cb, $ctx) = @_;
133         my $mid = $ctx->{mid};
134         my $res = $ctx->{srch}->get_thread($mid);
135         return _no_thread($cb) unless $res->{total};
136         my $feed_opts = get_feedopts($ctx);
137         my $fh = $cb->([200, ['Content-Type' => 'application/atom+xml']]);
138         my $ibx = $ctx->{-inbox};
139         my $html_url = $ibx->base_url($ctx->{env});
140         $html_url .= PublicInbox::Hval->new_msgid($mid)->as_href;
141
142         $feed_opts->{url} = $html_url;
143         $feed_opts->{emit_header} = 1;
144
145         foreach my $msg (@{$res->{msgs}}) {
146                 my $s = feed_entry($feed_opts, mid2path($msg->mid), $ibx);
147                 $fh->write($s) if defined $s;
148         }
149         end_feed($fh);
150 }
151
152 sub new_html_footer {
153         my ($ctx, $last) = @_;
154         my $qp = delete $ctx->{qp} or return;
155         my $old_r = $qp->{r};
156         my $latest = '';
157         my $next = '    ';
158
159         if ($last) {
160                 $next = qq!<a\nhref="?r=$last"\nrel=next>next</a>!;
161         }
162         if ($old_r) {
163                 $latest = qq! <a\nhref='./new.html'>latest</a>!;
164         }
165         "<hr><pre>page: $next$latest</pre>";
166 }
167
168 sub each_recent_blob {
169         my ($ctx, $cb) = @_;
170         my $max = $ctx->{max} || MAX_PER_PAGE;
171         my $hex = '[a-f0-9]';
172         my $addmsg = qr!^:000000 100644 \S+ \S+ A\t(${hex}{2}/${hex}{38})$!;
173         my $delmsg = qr!^:100644 000000 \S+ \S+ D\t(${hex}{2}/${hex}{38})$!;
174         my $refhex = qr/(?:HEAD|${hex}{4,40})(?:~\d+)?/;
175         my $qp = $ctx->{qp};
176
177         # revision ranges may be specified
178         my $range = 'HEAD';
179         my $r = $qp->{r} if $qp;
180         if ($r && ($r =~ /\A(?:$refhex\.\.)?$refhex\z/o)) {
181                 $range = $r;
182         }
183
184         # get recent messages
185         # we could use git log -z, but, we already know ssoma will not
186         # leave us with filenames with spaces in them..
187         my $log = $ctx->{-inbox}->git->popen(qw/log
188                                 --no-notes --no-color --raw -r
189                                 --abbrev=16 --abbrev-commit/,
190                                 "--format=%h%x00%ct%x00%an%x00%s%x00",
191                                 $range);
192         my %deleted; # only an optimization at this point
193         my $last;
194         my $nr = 0;
195         my ($cur_commit, $first_commit, $last_commit);
196         my ($ts, $subj, $u);
197         local $/ = "\n";
198         while (defined(my $line = <$log>)) {
199                 if ($line =~ /$addmsg/o) {
200                         my $add = $1;
201                         next if $deleted{$add}; # optimization-only
202                         $nr += $cb->($add, $cur_commit, $ts, $u, $subj);
203                         if ($nr >= $max) {
204                                 $last = 1;
205                                 last;
206                         }
207                 } elsif ($line =~ /$delmsg/o) {
208                         $deleted{$1} = 1;
209                 } elsif ($line =~ /^${hex}{7,40}/o) {
210                         ($cur_commit, $ts, $u, $subj) = split("\0", $line);
211                         unless (defined $first_commit) {
212                                 $first_commit = $cur_commit;
213                         }
214                 }
215         }
216
217         if ($last) {
218                 local $/ = "\n";
219                 while (my $line = <$log>) {
220                         if ($line =~ /^(${hex}{7,40})/o) {
221                                 $last_commit = $1;
222                                 last;
223                         }
224                 }
225         }
226
227         # for pagination
228         ($first_commit, $last_commit);
229 }
230
231 # private functions below
232 sub get_feedopts {
233         my ($ctx) = @_;
234         my $inbox = $ctx->{inbox};
235         my $obj = $ctx->{-inbox};
236         my %rv = ( description => $obj->description );
237
238         $rv{address} = $obj->{address};
239         $rv{id_addr} = $obj->{-primary_address};
240         my $url_base = $obj->base_url($ctx->{env});
241         if (my $mid = $ctx->{mid}) { # per-thread feed:
242                 $rv{atomurl} = "$url_base$mid/t.atom";
243         } else {
244                 $rv{atomurl} = $url_base."new.atom";
245         }
246         $rv{url} ||= $url_base;
247         $rv{midurl} = $url_base;
248
249         \%rv;
250 }
251
252 sub feed_updated {
253         my ($date, $ts) = @_;
254         my @t = eval { strptime($date) } if defined $date;
255         @t = gmtime($ts || time) unless scalar @t;
256
257         '<updated>' . strftime(DATEFMT, @t) . '</updated>';
258 }
259
260 # returns undef or string
261 sub feed_entry {
262         my ($feed_opts, $add, $ibx) = @_;
263
264         my $mime = do_cat_mail($ibx, $add) or return;
265         my $url = $feed_opts->{url};
266         my $midurl = $feed_opts->{midurl};
267
268         my $header_obj = $mime->header_obj;
269         my $mid = $header_obj->header_raw('Message-ID');
270         defined $mid or return;
271         $mid = PublicInbox::Hval->new_msgid($mid);
272         my $href = $midurl . $mid->as_href . '/';
273
274         my $date = $header_obj->header('Date');
275         my $updated = feed_updated($date);
276
277         my $title = $header_obj->header('Subject');
278         defined $title or return;
279         $title = title_tag($title);
280
281         my $from = $header_obj->header('From') or return;
282         my ($email) = PublicInbox::Address::emails($from);
283         my $name = join(', ',PublicInbox::Address::names($from));
284         $name = ascii_html($name);
285         $email = ascii_html($email);
286
287         my $s = '';
288         if (delete $feed_opts->{emit_header}) {
289                 $s .= atom_header($feed_opts, $title) . $updated;
290         }
291         $s .= "<entry><author><name>$name</name><email>$email</email>" .
292                 "</author>$title$updated" .
293                 qq{<content\ntype="xhtml">} .
294                 qq{<div\nxmlns="http://www.w3.org/1999/xhtml">} .
295                 qq(<pre\nstyle="white-space:pre-wrap">) .
296                 PublicInbox::View::multipart_text_as_html($mime, $href) .
297                 '</pre>';
298
299         $add =~ tr!/!!d;
300         my $h = '[a-f0-9]';
301         my (@uuid5) = ($add =~ m!\A($h{8})($h{4})($h{4})($h{4})($h{12})!o);
302         my $id = 'urn:uuid:' . join('-', @uuid5);
303         $s .= qq!</div></content><link\nhref="$href"/>!.
304                 "<id>$id</id></entry>";
305 }
306
307 sub do_cat_mail {
308         my ($ibx, $path) = @_;
309         my $mime = eval { $ibx->msg_by_path($path) } or return;
310         Email::MIME->new($mime);
311 }
312
313 1;