]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
feed: move timestamp parsing to view
[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);
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, $ctx) = @_;
21         require XML::Atom::SimpleFeed;
22         require POSIX;
23         my $max = $ctx->{max} || MAX_PER_PAGE;
24
25         my $feed_opts = get_feedopts($ctx);
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         $feed->no_generator;
40
41         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
42         each_recent_blob($ctx, sub {
43                 my ($add, undef) = @_;
44                 add_to_feed($feed_opts, $feed, $add, $git);
45         });
46         $git = undef; # destroy pipes
47         Email::Address->purge_cache;
48         $feed->as_string;
49 }
50
51 sub generate_html_index {
52         my ($class, $ctx) = @_;
53
54         my $max = $ctx->{max} || MAX_PER_PAGE;
55         my $feed_opts = get_feedopts($ctx);
56
57         my $title = $feed_opts->{description} || '';
58         $title = PublicInbox::Hval->new_oneline($title)->as_html;
59
60         my $html = "<html><head><title>$title</title>" .
61                 '<link rel="alternate" title="Atom feed"' . "\nhref=\"" .
62                 $feed_opts->{atomurl} . "\"\ntype=\"application/atom+xml\"/>" .
63                 '</head><body>' . PRE_WRAP;
64
65         my $state;
66         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
67         my (undef, $last) = each_recent_blob($ctx, sub {
68                 my ($path, $commit) = @_;
69                 unless (defined $state) {
70                         $state = [ $ctx->{srch}, {}, $commit, 0 ];
71                 }
72                 my $mime = do_cat_mail($git, $_[0]) or return 0;
73                 $html .= PublicInbox::View->index_entry($mime, 0, $state);
74                 1;
75         });
76         Email::Address->purge_cache;
77         $git = undef; # destroy pipes.
78
79         my $footer = nav_footer($ctx->{cgi}, $last, $feed_opts, $state);
80         if ($footer) {
81                 my $list_footer = $ctx->{footer};
82                 $footer .= "\n" . $list_footer if $list_footer;
83                 $footer = "<hr />" . PRE_WRAP . "$footer</pre>";
84         }
85         $html . "</pre>$footer</body></html>";
86 }
87
88 # private subs
89
90 sub nav_footer {
91         my ($cgi, $last, $feed_opts, $state) = @_;
92         $cgi or return '';
93         my $old_r = $cgi->param('r');
94         my $head = '    ';
95         my $next = '    ';
96         my $first = $state->[2];
97         my $anchor = $state->[3];
98
99         if ($last) {
100                 $next = qq!<a\nhref="?r=$last">next</a>!;
101         }
102         if ($old_r) {
103                 $head = $cgi->path_info;
104                 $head = qq!<a\nhref="$head">head</a>!;
105         }
106         my $atom = "<a\nhref=\"$feed_opts->{atomurl}\">atom</a>";
107         my $permalink = "<a\nhref=\"?r=$first\">permalink</a>";
108         "<a\nname=\"s$anchor\">page:</a> $next $head $atom $permalink";
109 }
110
111 sub each_recent_blob {
112         my ($ctx, $cb) = @_;
113         my $max = $ctx->{max} || MAX_PER_PAGE;
114         my $hex = '[a-f0-9]';
115         my $addmsg = qr!^:000000 100644 \S+ \S+ A\t(${hex}{2}/${hex}{38})$!;
116         my $delmsg = qr!^:100644 000000 \S+ \S+ D\t(${hex}{2}/${hex}{38})$!;
117         my $refhex = qr/${hex}{4,40}(?:~\d+)?/;
118         my $cgi = $ctx->{cgi};
119
120         # revision ranges may be specified
121         my $range = 'HEAD';
122         my $r = $cgi->param('r') if $cgi;
123         if ($r && ($r =~ /\A(?:$refhex\.\.)?$refhex\z/o)) {
124                 $range = $r;
125         }
126
127         # get recent messages
128         # we could use git log -z, but, we already know ssoma will not
129         # leave us with filenames with spaces in them..
130         my @cmd = ('git', "--git-dir=$ctx->{git_dir}",
131                         qw/log --no-notes --no-color --raw -r
132                            --abbrev=16 --abbrev-commit/);
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 ($cur_commit, $first_commit, $last_commit);
141         while (my $line = <$log>) {
142                 if ($line =~ /$addmsg/o) {
143                         my $add = $1;
144                         next if $deleted{$add}; # optimization-only
145                         $nr += $cb->($add, $cur_commit);
146                         if ($nr >= $max) {
147                                 $last = 1;
148                                 last;
149                         }
150                 } elsif ($line =~ /$delmsg/o) {
151                         $deleted{$1} = 1;
152                 } elsif ($line =~ /^commit (${hex}{7,40})/o) {
153                         $cur_commit = $1;
154                         $first_commit = $1 unless defined $first_commit;
155                 }
156         }
157
158         if ($last) {
159                 while (my $line = <$log>) {
160                         if ($line =~ /^commit (${hex}{7,40})/o) {
161                                 $last_commit = $1;
162                                 last;
163                         }
164                 }
165         }
166
167         close $log; # we may EPIPE here
168         # for pagination
169         ($first_commit, $last_commit);
170 }
171
172 # private functions below
173 sub get_feedopts {
174         my ($ctx) = @_;
175         my $pi_config = $ctx->{pi_config};
176         my $listname = $ctx->{listname};
177         my $cgi = $ctx->{cgi};
178         my %rv;
179         if (open my $fh, '<', "$ctx->{git_dir}/description") {
180                 chomp($rv{description} = <$fh>);
181                 close $fh;
182         }
183
184         if ($pi_config && defined $listname && length $listname) {
185                 foreach my $key (qw(address)) {
186                         $rv{$key} = $pi_config->get($listname, $key) || "";
187                 }
188         }
189         my $url_base;
190         if ($cgi) {
191                 my $path_info = $cgi->path_info;
192                 my $base;
193                 if (ref($cgi) eq 'CGI') {
194                         $base = $cgi->url(-base);
195                 } else {
196                         $base = $cgi->base->as_string;
197                         $base =~ s!/\z!!;
198                 }
199                 $url_base = $path_info;
200                 if ($url_base =~ s!/(?:|index\.html)?\z!!) {
201                         $rv{atomurl} = "$base$url_base/atom.xml";
202                 } else {
203                         $url_base =~ s!/atom\.xml\z!!;
204                         $rv{atomurl} = $base . $path_info;
205                         $url_base = $base . $url_base; # XXX is this needed?
206                 }
207         } else {
208                 $url_base = "http://example.com";
209                 $rv{atomurl} = "$url_base/atom.xml";
210         }
211         $rv{url} ||= "$url_base/";
212         $rv{midurl} = "$url_base/m/";
213         $rv{fullurl} = "$url_base/f/";
214
215         \%rv;
216 }
217
218 sub mime_header {
219         my ($mime, $name) = @_;
220         PublicInbox::Hval->new_oneline($mime->header($name))->raw;
221 }
222
223 sub feed_date {
224         my ($date) = @_;
225         my @t = eval { strptime($date) };
226
227         scalar(@t) ? POSIX::strftime(DATEFMT, @t) : 0;
228 }
229
230 # returns 0 (skipped) or 1 (added)
231 sub add_to_feed {
232         my ($feed_opts, $feed, $add, $git) = @_;
233
234         my $mime = do_cat_mail($git, $add) or return 0;
235         my $midurl = $feed_opts->{midurl} || 'http://example.com/m/';
236         my $fullurl = $feed_opts->{fullurl} || 'http://example.com/f/';
237
238         my $header_obj = $mime->header_obj;
239         my $mid = $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->feed_entry($mime, $fullurl . $href);
244         defined($content) or return 0;
245         $mime = undef;
246
247         my $subject = mime_header($header_obj, 'Subject') or return 0;
248
249         my $from = mime_header($header_obj, '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 = $header_obj->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 do_cat_mail {
275         my ($git, $path) = @_;
276         my $mime = eval {
277                 my $str = $git->cat_file("HEAD:$path");
278                 Email::MIME->new($str);
279         };
280         $@ ? undef : $mime;
281 }
282
283 1;