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