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