]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
feed: use updated date based on git commit date
[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 package PublicInbox::Feed;
4 use strict;
5 use warnings;
6 use Email::Address;
7 use Email::MIME;
8 use Date::Parse qw(strptime);
9 use PublicInbox::Hval;
10 use PublicInbox::GitCatFile;
11 use PublicInbox::View;
12 use PublicInbox::MID qw/mid_clean mid_compress/;
13 use POSIX qw/strftime/;
14 use constant {
15         DATEFMT => '%Y-%m-%dT%H:%M:%SZ', # atom standard
16         MAX_PER_PAGE => 25, # this needs to be tunable
17 };
18
19 use Encode qw/find_encoding/;
20 my $enc_utf8 = find_encoding('UTF-8');
21
22 # main function
23 sub generate {
24         my ($ctx) = @_;
25         sub { emit_atom($_[0], $ctx) };
26 }
27
28 sub generate_html_index {
29         my ($ctx) = @_;
30         sub { emit_html_index($_[0], $ctx) };
31 }
32
33 # private subs
34
35 sub emit_atom {
36         my ($cb, $ctx) = @_;
37         my $fh = $cb->([ 200, ['Content-Type' => 'application/xml']]);
38         my $max = $ctx->{max} || MAX_PER_PAGE;
39         my $feed_opts = get_feedopts($ctx);
40         my $addr = $feed_opts->{address};
41         $addr = $addr->[0] if ref($addr);
42         $addr ||= 'public-inbox@example.com';
43         my $title = $feed_opts->{description} || "unnamed feed";
44         $title = PublicInbox::Hval->new_oneline($title)->as_html;
45         my $type = index($title, '&') >= 0 ? "\ntype=\"html\"" : '';
46         my $url = $feed_opts->{url} || "http://example.com/";
47         my $atomurl = $feed_opts->{atomurl};
48         my $x = qq(<?xml version="1.0" encoding="us-ascii"?>\n) .
49                 qq{<feed\nxmlns="http://www.w3.org/2005/Atom">} .
50                 qq{<title$type>$title</title>} .
51                 qq{<link\nhref="$url"/>} .
52                 qq{<link\nrel="self"\nhref="$atomurl"/>} .
53                 qq{<id>mailto:$addr</id>};
54
55         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
56         each_recent_blob($ctx, sub {
57                 my ($path, undef, $ts) = @_;
58                 if (defined $x) {
59                         $fh->write($x . '<updated>'.
60                                         strftime(DATEFMT, gmtime($ts)) .
61                                         '</updated>');
62                         $x = undef;
63                 }
64                 add_to_feed($feed_opts, $fh, $path, $git);
65         });
66         $git = undef; # destroy pipes
67         Email::Address->purge_cache;
68         $fh->write("</feed>");
69         $fh->close;
70 }
71
72
73 sub emit_html_index {
74         my ($cb, $ctx) = @_;
75         my $fh = $cb->([200,['Content-Type'=>'text/html; charset=UTF-8']]);
76
77         my $max = $ctx->{max} || MAX_PER_PAGE;
78         my $feed_opts = get_feedopts($ctx);
79
80         my $title = $feed_opts->{description} || '';
81         $title = PublicInbox::Hval->new_oneline($title)->as_html;
82         my $atom_url = $feed_opts->{atomurl};
83
84         $fh->write("<html><head><title>$title</title>" .
85                    "<link\nrel=alternate\ntitle=\"Atom feed\"\n".
86                    "href=\"$atom_url\"\ntype=\"application/atom+xml\"/>" .
87                    '</head><body>' . PublicInbox::View::PRE_WRAP .
88                    "<b>$title</b> (<a\nhref=\"$atom_url\">Atom feed</a>)\n");
89
90         my $state;
91         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
92         my $topics;
93         my $srch = $ctx->{srch};
94         $srch and $topics = [ [], {} ];
95         my (undef, $last) = each_recent_blob($ctx, sub {
96                 my ($path, $commit, $ts, $u, $subj) = @_;
97                 $state ||= {
98                         ctx => $ctx,
99                         seen => {},
100                         first_commit => $commit,
101                         anchor_idx => 0,
102                 };
103
104                 if ($srch) {
105                         add_topic($git, $srch, $topics, $path, $ts, $u, $subj);
106                 } else {
107                         my $mime = do_cat_mail($git, $path) or return 0;
108                         PublicInbox::View::index_entry($fh, $mime, 0, $state);
109                         1;
110                 }
111         });
112         Email::Address->purge_cache;
113         $git = undef; # destroy pipes.
114
115         my $footer = nav_footer($ctx->{cgi}, $last, $feed_opts, $state);
116         if ($footer) {
117                 my $list_footer = $ctx->{footer};
118                 $footer .= "\n" . $list_footer if $list_footer;
119                 $footer = "<hr /><pre>$footer</pre>";
120         }
121         $fh->write(dump_topics($topics)) if $topics;
122         $fh->write("$footer</body></html>");
123         $fh->close;
124 }
125
126 sub nav_footer {
127         my ($cgi, $last, $feed_opts, $state) = @_;
128         $cgi or return '';
129         my $old_r = $cgi->param('r');
130         my $head = '    ';
131         my $next = '    ';
132         my $first = $state->{first_commit};
133         my $anchor = $state->{anchor_idx};
134
135         if ($last) {
136                 $next = qq!<a\nhref="?r=$last">next</a>!;
137         }
138         if ($old_r) {
139                 $head = $cgi->path_info;
140                 $head = qq!<a\nhref="$head">head</a>!;
141         }
142         my $atom = "<a\nhref=\"$feed_opts->{atomurl}\">atom</a>";
143         my $permalink = "<a\nhref=\"?r=$first\">permalink</a>";
144         "<a\nname=\"s$anchor\">page:</a> $next $head $atom $permalink";
145 }
146
147 sub each_recent_blob {
148         my ($ctx, $cb) = @_;
149         my $max = $ctx->{max} || MAX_PER_PAGE;
150         my $hex = '[a-f0-9]';
151         my $addmsg = qr!^:000000 100644 \S+ \S+ A\t(${hex}{2}/${hex}{38})$!;
152         my $delmsg = qr!^:100644 000000 \S+ \S+ D\t(${hex}{2}/${hex}{38})$!;
153         my $refhex = qr/(?:HEAD|${hex}{4,40})(?:~\d+)?/;
154         my $cgi = $ctx->{cgi};
155
156         # revision ranges may be specified
157         my $range = 'HEAD';
158         my $r = $cgi->param('r') if $cgi;
159         if ($r && ($r =~ /\A(?:$refhex\.\.)?$refhex\z/o)) {
160                 $range = $r;
161         }
162
163         # get recent messages
164         # we could use git log -z, but, we already know ssoma will not
165         # leave us with filenames with spaces in them..
166         my @cmd = ('git', "--git-dir=$ctx->{git_dir}",
167                         qw/log --no-notes --no-color --raw -r
168                            --abbrev=16 --abbrev-commit/,
169                         "--format=%h%x00%ct%x00%an%x00%s%x00");
170         push @cmd, $range;
171
172         my $pid = open(my $log, '-|', @cmd) or
173                 die('open `'.join(' ', @cmd) . " pipe failed: $!\n");
174         my %deleted; # only an optimization at this point
175         my $last;
176         my $nr = 0;
177         my ($cur_commit, $first_commit, $last_commit);
178         my ($ts, $subj, $u);
179         while (defined(my $line = <$log>)) {
180                 if ($line =~ /$addmsg/o) {
181                         my $add = $1;
182                         next if $deleted{$add}; # optimization-only
183                         $nr += $cb->($add, $cur_commit, $ts, $u, $subj);
184                         if ($nr >= $max) {
185                                 $last = 1;
186                                 last;
187                         }
188                 } elsif ($line =~ /$delmsg/o) {
189                         $deleted{$1} = 1;
190                 } elsif ($line =~ /^${hex}{7,40}/o) {
191                         ($cur_commit, $ts, $u, $subj) = split("\0", $line);
192                         unless (defined $first_commit) {
193                                 $first_commit = $cur_commit;
194                         }
195                 }
196         }
197
198         if ($last) {
199                 while (my $line = <$log>) {
200                         if ($line =~ /^(${hex}{7,40})/o) {
201                                 $last_commit = $1;
202                                 last;
203                         }
204                 }
205         }
206
207         close $log; # we may EPIPE here
208         # for pagination
209         ($first_commit, $last_commit);
210 }
211
212 # private functions below
213 sub get_feedopts {
214         my ($ctx) = @_;
215         my $pi_config = $ctx->{pi_config};
216         my $listname = $ctx->{listname};
217         my $cgi = $ctx->{cgi};
218         my %rv;
219         if (open my $fh, '<', "$ctx->{git_dir}/description") {
220                 chomp($rv{description} = <$fh>);
221                 close $fh;
222         }
223
224         if ($pi_config && defined $listname && $listname ne '') {
225                 foreach my $key (qw(address)) {
226                         $rv{$key} = $pi_config->get($listname, $key) || "";
227                 }
228         }
229         my $url_base;
230         if ($cgi) {
231                 my $path_info = $cgi->path_info;
232                 my $base;
233                 if (ref($cgi) eq 'CGI') {
234                         $base = $cgi->url(-base);
235                 } else {
236                         $base = $cgi->base->as_string;
237                         $base =~ s!/\z!!;
238                 }
239                 $url_base = $path_info;
240                 if ($url_base =~ s!/(?:|index\.html)?\z!!) {
241                         $rv{atomurl} = "$base$url_base/atom.xml";
242                 } else {
243                         $url_base =~ s!/atom\.xml\z!!;
244                         $rv{atomurl} = $base . $path_info;
245                         $url_base = $base . $url_base; # XXX is this needed?
246                 }
247         } else {
248                 $url_base = "http://example.com";
249                 $rv{atomurl} = "$url_base/atom.xml";
250         }
251         $rv{url} ||= "$url_base/";
252         $rv{midurl} = "$url_base/m/";
253         $rv{fullurl} = "$url_base/f/";
254
255         \%rv;
256 }
257
258 sub mime_header {
259         my ($mime, $name) = @_;
260         PublicInbox::Hval->new_oneline($mime->header($name))->raw;
261 }
262
263 sub feed_date {
264         my ($date) = @_;
265         my @t = eval { strptime($date) };
266
267         scalar(@t) ? strftime(DATEFMT, @t) : 0;
268 }
269
270 # returns 0 (skipped) or 1 (added)
271 sub add_to_feed {
272         my ($feed_opts, $fh, $add, $git) = @_;
273
274         my $mime = do_cat_mail($git, $add) or return 0;
275         my $fullurl = $feed_opts->{fullurl} || 'http://example.com/f/';
276
277         my $header_obj = $mime->header_obj;
278         my $mid = $header_obj->header('Message-ID');
279         defined $mid or return 0;
280         $mid = PublicInbox::Hval->new_msgid($mid);
281         my $href = $mid->as_href . '/';
282         my $content = PublicInbox::View->feed_entry($mime, $fullurl . $href);
283         defined($content) or return 0;
284         $mime = undef;
285
286         my $title = mime_header($header_obj, 'Subject') or return 0;
287         $title = PublicInbox::Hval->new_oneline($title)->as_html;
288         my $type = index($title, '&') >= 0 ? "\ntype=\"html\"" : '';
289
290         my $from = mime_header($header_obj, 'From') or return 0;
291         my @from = Email::Address->parse($from) or return 0;
292         my $name = PublicInbox::Hval->new_oneline($from[0]->name)->as_html;
293         my $email = $from[0]->address;
294         $email = PublicInbox::Hval->new_oneline($email)->as_html;
295
296         my $date = $header_obj->header('Date');
297         $date = PublicInbox::Hval->new_oneline($date);
298         $date = feed_date($date->raw) or return 0;
299
300         $fh->write("<entry><author><name>$name</name><email>$email</email>" .
301                    "</author><title$type>$title</title>" .
302                    "<updated>$date</updated>" .
303                    qq{<content\ntype="xhtml">} .
304                    qq{<div\nxmlns="http://www.w3.org/1999/xhtml">});
305         $fh->write($content);
306
307         $add =~ tr!/!!d;
308         my $h = '[a-f0-9]';
309         my (@uuid5) = ($add =~ m!\A($h{8})($h{4})($h{4})($h{4})($h{12})!o);
310         my $id = 'urn:uuid:' . join('-', @uuid5);
311         my $midurl = $feed_opts->{midurl} || 'http://example.com/m/';
312         $fh->write(qq{</div></content><link\nhref="$midurl$href"/>}.
313                    "<id>$id</id></entry>");
314         1;
315 }
316
317 sub do_cat_mail {
318         my ($git, $path) = @_;
319         my $mime = eval {
320                 my $str = $git->cat_file("HEAD:$path");
321                 Email::MIME->new($str);
322         };
323         $@ ? undef : $mime;
324 }
325
326 # accumulate recent topics if search is supported
327 sub add_topic {
328         my ($git, $srch, $topics, $path, $ts, $u, $subj) = @_;
329         my ($order, $subjs) = @$topics;
330         my $header_obj;
331
332         # legacy ssoma did not set commit titles based on Subject
333         $subj = $enc_utf8->decode($subj);
334         if ($subj eq 'mda') {
335                 my $mime = do_cat_mail($git, $path) or return 0;
336                 $header_obj = $mime->header_obj;
337                 $subj = mime_header($header_obj, 'Subject');
338         }
339
340         my $topic = $subj = $srch->subject_normalized($subj);
341
342         # kill "[PATCH v2]" etc. for summarization
343         $topic =~ s/\A\s*\[[^\]]+\]\s*//g;
344
345         if (++$subjs->{$topic} == 1) {
346                 unless ($header_obj) {
347                         my $mime = do_cat_mail($git, $path) or return 0;
348                         $header_obj = $mime->header_obj;
349                 }
350                 my $mid = $header_obj->header('Message-ID');
351                 $mid = mid_compress(mid_clean($mid));
352                 $u = $enc_utf8->decode($u);
353                 push @$order, [ $mid, $ts, $u, $subj, $topic ];
354                 return 1;
355         }
356         0; # old topic, continue going
357 }
358
359 sub dump_topics {
360         my ($topics) = @_;
361         my ($order, $subjs) = @$topics;
362         my $dst = '';
363         $dst .= "\n[No recent topics]" unless (scalar @$order);
364         while (defined(my $info = shift @$order)) {
365                 my ($mid, $ts, $u, $subj, $topic) = @$info;
366                 my $n = delete $subjs->{$topic};
367                 $mid = PublicInbox::Hval->new($mid)->as_href;
368                 $subj = PublicInbox::Hval->new($subj)->as_html;
369                 $u = PublicInbox::Hval->new($u)->as_html;
370                 $dst .= "\n<a\nhref=\"t/$mid/#u\"><b>$subj</b></a>\n- ";
371                 $ts = strftime('%Y-%m-%d %H:%M', gmtime($ts));
372                 if ($n == 1) {
373                         $dst .= "created by $u @ $ts UTC\n"
374                 } else {
375                         # $n isn't the total number of posts on the topic,
376                         # just the number of posts in the current "git log"
377                         # window, so leave it unlabeled
378                         $dst .= "updated by $u @ $ts UTC ($n)\n"
379                 }
380         }
381         $dst .= '</pre>'
382 }
383
384 1;