]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
3540e9a49e73704f1ced02d9fcedeb96c064ac17
[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 atom_header {
36         my ($feed_opts) = @_;
37         my $title = $feed_opts->{description};
38         $title = PublicInbox::Hval->new_oneline($title)->as_html;
39         my $type = index($title, '&') >= 0 ? "\ntype=\"html\"" : '';
40
41         qq(<?xml version="1.0" encoding="us-ascii"?>\n) .
42         qq{<feed\nxmlns="http://www.w3.org/2005/Atom">} .
43         qq{<title$type>$title</title>} .
44         qq(<link\nhref="$feed_opts->{url}"/>) .
45         qq(<link\nrel="self"\nhref="$feed_opts->{atomurl}"/>) .
46         qq(<id>mailto:$feed_opts->{id_addr}</id>);
47 }
48
49 sub emit_atom {
50         my ($cb, $ctx) = @_;
51         my $fh = $cb->([ 200, ['Content-Type' => 'application/xml']]);
52         my $max = $ctx->{max} || MAX_PER_PAGE;
53         my $feed_opts = get_feedopts($ctx);
54         my $x = atom_header($feed_opts);
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         } else {
223                 $rv{description} = '($GIT_DIR/description missing)';
224         }
225
226         if ($pi_config && defined $listname && $listname ne '') {
227                 my $addr = $pi_config->get($listname, 'address') || "";
228                 $rv{address} = $addr;
229                 $addr = $addr->[0] if ref($addr);
230                 $rv{id_addr} = $addr;
231         }
232         $rv{id_addr} ||= 'public-inbox@example.com';
233
234         my $url_base;
235         if ($cgi) {
236                 my $path_info = $cgi->path_info;
237                 my $base;
238                 if (ref($cgi) eq 'CGI') {
239                         $base = $cgi->url(-base);
240                 } else {
241                         $base = $cgi->base->as_string;
242                         $base =~ s!/\z!!;
243                 }
244                 $url_base = $path_info;
245                 if ($url_base =~ s!/(?:|index\.html)?\z!!) {
246                         $rv{atomurl} = "$base$url_base/atom.xml";
247                 } else {
248                         $url_base =~ s!/atom\.xml\z!!;
249                         $rv{atomurl} = $base . $path_info;
250                         $url_base = $base . $url_base; # XXX is this needed?
251                 }
252         } else {
253                 $url_base = "http://example.com";
254                 $rv{atomurl} = "$url_base/atom.xml";
255         }
256         $rv{url} ||= "$url_base/";
257         $rv{midurl} = "$url_base/m/";
258         $rv{fullurl} = "$url_base/f/";
259
260         \%rv;
261 }
262
263 sub mime_header {
264         my ($mime, $name) = @_;
265         PublicInbox::Hval->new_oneline($mime->header($name))->raw;
266 }
267
268 sub feed_date {
269         my ($date) = @_;
270         my @t = eval { strptime($date) };
271
272         scalar(@t) ? strftime(DATEFMT, @t) : 0;
273 }
274
275 # returns 0 (skipped) or 1 (added)
276 sub add_to_feed {
277         my ($feed_opts, $fh, $add, $git) = @_;
278
279         my $mime = do_cat_mail($git, $add) or return 0;
280         my $fullurl = $feed_opts->{fullurl} || 'http://example.com/f/';
281
282         my $header_obj = $mime->header_obj;
283         my $mid = $header_obj->header('Message-ID');
284         defined $mid or return 0;
285         $mid = PublicInbox::Hval->new_msgid($mid);
286         my $href = $mid->as_href . '/';
287         my $content = PublicInbox::View->feed_entry($mime, $fullurl . $href);
288         defined($content) or return 0;
289         $mime = undef;
290
291         my $title = mime_header($header_obj, 'Subject') or return 0;
292         $title = PublicInbox::Hval->new_oneline($title)->as_html;
293         my $type = index($title, '&') >= 0 ? "\ntype=\"html\"" : '';
294
295         my $from = mime_header($header_obj, 'From') or return 0;
296         my @from = Email::Address->parse($from) or return 0;
297         my $name = PublicInbox::Hval->new_oneline($from[0]->name)->as_html;
298         my $email = $from[0]->address;
299         $email = PublicInbox::Hval->new_oneline($email)->as_html;
300
301         my $date = $header_obj->header('Date');
302         $date = PublicInbox::Hval->new_oneline($date);
303         $date = feed_date($date->raw) or return 0;
304
305         $fh->write("<entry><author><name>$name</name><email>$email</email>" .
306                    "</author><title$type>$title</title>" .
307                    "<updated>$date</updated>" .
308                    qq{<content\ntype="xhtml">} .
309                    qq{<div\nxmlns="http://www.w3.org/1999/xhtml">});
310         $fh->write($content);
311
312         $add =~ tr!/!!d;
313         my $h = '[a-f0-9]';
314         my (@uuid5) = ($add =~ m!\A($h{8})($h{4})($h{4})($h{4})($h{12})!o);
315         my $id = 'urn:uuid:' . join('-', @uuid5);
316         my $midurl = $feed_opts->{midurl} || 'http://example.com/m/';
317         $fh->write(qq{</div></content><link\nhref="$midurl$href"/>}.
318                    "<id>$id</id></entry>");
319         1;
320 }
321
322 sub do_cat_mail {
323         my ($git, $path) = @_;
324         my $mime = eval {
325                 my $str = $git->cat_file("HEAD:$path");
326                 Email::MIME->new($str);
327         };
328         $@ ? undef : $mime;
329 }
330
331 # accumulate recent topics if search is supported
332 sub add_topic {
333         my ($git, $srch, $topics, $path, $ts, $u, $subj) = @_;
334         my ($order, $subjs) = @$topics;
335         my $header_obj;
336
337         # legacy ssoma did not set commit titles based on Subject
338         $subj = $enc_utf8->decode($subj);
339         if ($subj eq 'mda') {
340                 my $mime = do_cat_mail($git, $path) or return 0;
341                 $header_obj = $mime->header_obj;
342                 $subj = mime_header($header_obj, 'Subject');
343         }
344
345         my $topic = $subj = $srch->subject_normalized($subj);
346
347         # kill "[PATCH v2]" etc. for summarization
348         $topic =~ s/\A\s*\[[^\]]+\]\s*//g;
349
350         if (++$subjs->{$topic} == 1) {
351                 unless ($header_obj) {
352                         my $mime = do_cat_mail($git, $path) or return 0;
353                         $header_obj = $mime->header_obj;
354                 }
355                 my $mid = $header_obj->header('Message-ID');
356                 $mid = mid_compress(mid_clean($mid));
357                 $u = $enc_utf8->decode($u);
358                 push @$order, [ $mid, $ts, $u, $subj, $topic ];
359                 return 1;
360         }
361         0; # old topic, continue going
362 }
363
364 sub dump_topics {
365         my ($topics) = @_;
366         my ($order, $subjs) = @$topics;
367         my $dst = '';
368         $dst .= "\n[No recent topics]" unless (scalar @$order);
369         while (defined(my $info = shift @$order)) {
370                 my ($mid, $ts, $u, $subj, $topic) = @$info;
371                 my $n = delete $subjs->{$topic};
372                 $mid = PublicInbox::Hval->new($mid)->as_href;
373                 $subj = PublicInbox::Hval->new($subj)->as_html;
374                 $u = PublicInbox::Hval->new($u)->as_html;
375                 $dst .= "\n<a\nhref=\"t/$mid/#u\"><b>$subj</b></a>\n- ";
376                 $ts = strftime('%Y-%m-%d %H:%M', gmtime($ts));
377                 if ($n == 1) {
378                         $dst .= "created by $u @ $ts UTC\n"
379                 } else {
380                         # $n isn't the total number of posts on the topic,
381                         # just the number of posts in the current "git log"
382                         # window, so leave it unlabeled
383                         $dst .= "updated by $u @ $ts UTC ($n)\n"
384                 }
385         }
386         $dst .= '</pre>'
387 }
388
389 1;