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