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