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