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