]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
feed: disable navigation to previous page
[public-inbox.git] / lib / PublicInbox / Feed.pm
1 # Copyright (C) 2013, Eric Wong <normalperson@yhbt.net> and all contributors
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 str2time);
9 use PublicInbox::Hval;
10 eval { require Git }; # this is GPLv2+, so we are OK to use it
11 use constant {
12         DATEFMT => '%Y-%m-%dT%H:%M:%SZ',
13         MAX_PER_PAGE => 25,
14 };
15
16 # FIXME: workaround https://rt.cpan.org/Public/Bug/Display.html?id=22817
17
18 # main function
19 sub generate {
20         my ($class, $args) = @_;
21         require XML::Atom::SimpleFeed;
22         require PublicInbox::View;
23         require POSIX;
24         my $max = $args->{max} || MAX_PER_PAGE;
25         my $top = $args->{top}; # bool
26
27         local $ENV{GIT_DIR} = $args->{git_dir};
28         my $feed_opts = get_feedopts($args);
29         my $addr = $feed_opts->{address};
30         $addr = $addr->[0] if ref($addr);
31         my $feed = XML::Atom::SimpleFeed->new(
32                 title => $feed_opts->{description} || "unnamed feed",
33                 link => $feed_opts->{url} || "http://example.com/",
34                 link => {
35                         rel => 'self',
36                         href => $feed_opts->{atomurl} ||
37                                 "http://example.com/atom.xml",
38                 },
39                 id => 'mailto:' . ($addr || 'public-inbox@example.com'),
40                 updated => POSIX::strftime(DATEFMT, gmtime),
41         );
42
43         my $git = try_git_pm($args->{git_dir});
44         each_recent_blob($args, sub {
45                 my ($add) = @_;
46                 add_to_feed($feed_opts, $feed, $add, $top, $git);
47         });
48         $feed->as_string;
49 }
50
51 sub generate_html_index {
52         my ($class, $args) = @_;
53         require Mail::Thread;
54
55         my $max = $args->{max} || MAX_PER_PAGE;
56         my $top = $args->{top}; # bool
57         local $ENV{GIT_DIR} = $args->{git_dir};
58         my $feed_opts = get_feedopts($args);
59
60         my $title = $feed_opts->{description} || '';
61         $title = PublicInbox::Hval->new_oneline($title)->as_html;
62
63         my @messages;
64         my $git = try_git_pm($args->{git_dir});
65         my $last = each_recent_blob($args, sub {
66                 my $mime = do_cat_mail($git, $_[0])
67                         or return 0;
68                 if ($top && ($mime->header('In-Reply-To') ||
69                              $mime->header('References'))) {
70                         return 0;
71                 }
72                 $mime->body_set(''); # save some memory
73
74                 my $t = eval { str2time($mime->header('Date')) };
75                 defined($t) or $t = 0;
76                 $mime->header_set('X-PI-Date', $t);
77                 push @messages, $mime;
78                 1;
79         });
80
81         my $th = Mail::Thread->new(@messages);
82         $th->thread;
83         my @out = (
84                 "<html><head><title>$title</title>" .
85                 '<link rel="alternate" title="Atom feed" href="' .
86                 $feed_opts->{atomurl} . '" type="application/atom+xml"/>' .
87                 '</head><body><pre>');
88         push @out, $feed_opts->{midurl};
89
90         # sort by date, most recent at top
91         $th->order(sub {
92                 sort {
93                         $b->topmost->message->header('X-PI-Date') <=>
94                         $a->topmost->message->header('X-PI-Date')
95                 } @_;
96         });
97         dump_html_line($_, 0, \@out) for $th->rootset;
98
99         my $footer = nav_footer($args->{cgi}, $last);
100         $footer = "<hr /><pre>$footer</pre>" if $footer;
101         $out[0] . "</pre>$footer</html>";
102 }
103
104 # private subs
105
106 sub nav_footer {
107         my ($cgi, $last) = @_;
108         $cgi or return '';
109         my $old_r = $cgi->param('r');
110         my $head = '    ';
111         my $next = '    ';
112
113         if ($last) {
114                 $next = $cgi->path_info . "?r=$last";
115                 $next = qq!<a href="$next">next</a>!;
116         }
117         if ($old_r) {
118                 $head = $cgi->path_info;
119                 $head = qq!<a href="$head">head</a>!;
120         }
121         "$head $next";
122 }
123
124 sub each_recent_blob {
125         my ($args, $cb) = @_;
126         my $max = $args->{max} || MAX_PER_PAGE;
127         my $hex = '[a-f0-9]';
128         my $addmsg = qr!^:000000 100644 \S+ \S+ A\t(${hex}{2}/${hex}{38})$!;
129         my $delmsg = qr!^:100644 000000 \S+ \S+ D\t(${hex}{2}/${hex}{38})$!;
130         my $refhex = qr/${hex}{4,40}(?:~\d+)?/;
131         my $cgi = $args->{cgi};
132
133         # revision ranges may be specified
134         my $range = 'HEAD';
135         my $r = $cgi->param('r') if $cgi;
136         if ($r && ($r =~ /\A(?:$refhex\.\.)?$refhex\z/o)) {
137                 $range = $r;
138         }
139
140         # get recent messages
141         # we could use git log -z, but, we already know ssoma will not
142         # leave us with filenames with spaces in them..
143         my @cmd = qw/git log --no-notes --no-color --raw -r/;
144         push @cmd, $range;
145
146         my $pid = open(my $log, '-|', @cmd) or
147                 die('open `'.join(' ', @cmd) . " pipe failed: $!\n");
148         my %deleted; # only an optimization at this point
149         my $last;
150         my $nr = 0;
151         my @commits = ();
152         while (my $line = <$log>) {
153                 if ($line =~ /$addmsg/o) {
154                         my $add = $1;
155                         next if $deleted{$add};
156                         $nr += $cb->($add);
157                         if ($nr >= $max) {
158                                 $last = 1;
159                                 last;
160                         }
161                 } elsif ($line =~ /$delmsg/o) {
162                         $deleted{$1} = 1;
163                 } elsif ($line =~ /^commit (${hex}{40})/) {
164                         push @commits, $1;
165                 }
166         }
167
168         if ($last) {
169                 while (my $line = <$log>) {
170                         if ($line =~ /^commit (${hex}{40})/) {
171                                 push @commits, $1;
172                                 last;
173                         }
174                 }
175         } else {
176                 push @commits, undef;
177         }
178
179         close $log; # we may EPIPE here
180         # for pagination
181         $commits[-1];
182 }
183
184 # private functions below
185 sub get_feedopts {
186         my ($args) = @_;
187         my $pi_config = $args->{pi_config};
188         my $listname = $args->{listname};
189         my $cgi = $args->{cgi};
190         my %rv;
191         if (open my $fh, '<', "$args->{git_dir}/description") {
192                 chomp($rv{description} = <$fh>);
193                 close $fh;
194         }
195
196         if ($pi_config && defined $listname && length $listname) {
197                 foreach my $key (qw(address)) {
198                         $rv{$key} = $pi_config->get($listname, $key) || "";
199                 }
200         }
201         my $url_base;
202         if ($cgi) {
203                 my $path_info = $cgi->path_info;
204                 my $base;
205                 if (ref($cgi) eq 'CGI') {
206                         $base = $cgi->url(-base);
207                 } else {
208                         $base = "${$cgi->base}";
209                         $base =~ s!/\z!!;
210                 }
211                 $url_base = $path_info;
212                 if ($url_base =~ s!/(?:|index\.html)?\z!!) {
213                         $rv{atomurl} = "$base$url_base/atom.xml";
214                 } else {
215                         $url_base =~ s!/atom\.xml\z!!;
216                         $rv{atomurl} = $base . $path_info;
217                         $url_base = $base . $url_base; # XXX is this needed?
218                 }
219         } else {
220                 $url_base = "http://example.com";
221                 $rv{atomurl} = "$url_base/atom.xml";
222         }
223         $rv{url} ||= "$url_base/";
224         $rv{midurl} = "$url_base/m/";
225         $rv{fullurl} = "$url_base/f/";
226
227         \%rv;
228 }
229
230 sub mime_header {
231         my ($mime, $name) = @_;
232         PublicInbox::Hval->new_oneline($mime->header($name))->raw;
233 }
234
235 sub feed_date {
236         my ($date) = @_;
237         my @t = eval { strptime($date) };
238
239         scalar(@t) ? POSIX::strftime(DATEFMT, @t) : 0;
240 }
241
242 # returns 0 (skipped) or 1 (added)
243 sub add_to_feed {
244         my ($feed_opts, $feed, $add, $top, $git) = @_;
245
246         my $mime = do_cat_mail($git, $add) or return 0;
247         if ($top && $mime->header('In-Reply-To')) {
248                 return 0;
249         }
250
251         my $midurl = $feed_opts->{midurl} || 'http://example.com/m/';
252         my $fullurl = $feed_opts->{fullurl} || 'http://example.com/f/';
253
254         my $mid = $mime->header_obj->header_raw('Message-ID');
255         defined $mid or return 0;
256         $mid = PublicInbox::Hval->new_msgid($mid);
257         my $href = $mid->as_href;
258         my $content = PublicInbox::View->as_feed_entry($mime,
259                                                         "$fullurl$href.html");
260         defined($content) or return 0;
261
262         my $subject = mime_header($mime, 'Subject') or return 0;
263
264         my $from = mime_header($mime, 'From') or return 0;
265         my @from = Email::Address->parse($from);
266         my $name = $from[0]->name;
267         defined $name or $name = "";
268         my $email = $from[0]->address;
269         defined $email or $email = "";
270
271         my $date = $mime->header('Date');
272         $date = PublicInbox::Hval->new_oneline($date);
273         $date = feed_date($date->raw) or return 0;
274         $add =~ tr!/!!d;
275         my $h = '[a-f0-9]';
276         my (@uuid5) = ($add =~ m!\A($h{8})($h{4})($h{4})($h{4})($h{12})!o);
277
278         $feed->add_entry(
279                 author => { name => $name, email => $email },
280                 title => $subject,
281                 updated => $date,
282                 content => { type => 'xhtml', content => $content },
283                 link => $midurl . $href,
284                 id => 'urn:uuid:' . join('-', @uuid5),
285         );
286         1;
287 }
288
289 sub dump_html_line {
290         my ($self, $level, $args) = @_; # args => [ $html, $midurl ]
291         if ($self->message) {
292                 $args->[0] .= (' ' x $level);
293                 my $mime = $self->message;
294                 my $subj = $mime->header('Subject');
295                 my $mid = $mime->header_obj->header_raw('Message-ID');
296                 $mid = PublicInbox::Hval->new_msgid($mid);
297                 my $url = $args->[1] . $mid->as_href;
298                 my $from = mime_header($mime, 'From');
299
300                 my @from = Email::Address->parse($from);
301                 $from = $from[0]->name;
302                 (defined($from) && length($from)) or $from = $from[0]->address;
303
304                 $from = PublicInbox::Hval->new_oneline($from)->as_html;
305                 $subj = PublicInbox::Hval->new_oneline($subj)->as_html;
306                 $args->[0] .= "<a href=\"$url.html\">$subj</a> $from\n";
307         }
308         dump_html_line($self->child, $level+1, $args) if $self->child;
309         dump_html_line($self->next, $level, $args) if $self->next;
310 }
311
312 sub try_git_pm {
313         my ($dir) = @_;
314         eval { Git->repository(Directory => $dir) };
315 };
316
317 sub do_cat_mail {
318         my ($git, $path) = @_;
319         my $str;
320         if ($git) {
321                 open my $fh, '>', \$str or
322                                 die "failed to setup string handle: $!\n";
323                 binmode $fh;
324                 my $err = '';
325                 my $bytes;
326                 {
327                         local $SIG{__WARN__} = sub { $err .= $_[0] };
328                         $bytes = $git->cat_blob("HEAD:$path", $fh);
329                 }
330                 close $fh or die "failed to close string handle: $!\n";
331
332                 if ($bytes < 0 && $err &&
333                                 $err !~ /doesn't exist in the repository/) {
334                         warn $err;
335                 }
336                 return if $bytes <= 0;
337         } else {
338                 $str = `git cat-file blob HEAD:$path`;
339                 return if $? != 0 || length($str) == 0;
340         }
341         Email::MIME->new($str);
342 }
343
344 1;