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