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