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