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