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