]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
add various TODO items
[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 constant {
12         DATEFMT => '%Y-%m-%dT%H:%M:%SZ', # atom standard
13         MAX_PER_PAGE => 25, # this needs to be tunable
14 };
15
16 # main function
17 sub generate {
18         my ($class, $args) = @_;
19         require XML::Atom::SimpleFeed;
20         require PublicInbox::View;
21         require POSIX;
22         my $max = $args->{max} || MAX_PER_PAGE;
23
24         my $feed_opts = get_feedopts($args);
25         my $addr = $feed_opts->{address};
26         $addr = $addr->[0] if ref($addr);
27         my $feed = XML::Atom::SimpleFeed->new(
28                 title => $feed_opts->{description} || "unnamed feed",
29                 link => $feed_opts->{url} || "http://example.com/",
30                 link => {
31                         rel => 'self',
32                         href => $feed_opts->{atomurl} ||
33                                 "http://example.com/atom.xml",
34                 },
35                 id => 'mailto:' . ($addr || 'public-inbox@example.com'),
36                 updated => POSIX::strftime(DATEFMT, gmtime),
37         );
38
39         my $git = PublicInbox::GitCatFile->new($args->{git_dir});
40         each_recent_blob($args, sub {
41                 my ($add) = @_;
42                 add_to_feed($feed_opts, $feed, $add, $git);
43         });
44         $git = undef; # destroy pipes
45         Email::Address->purge_cache;
46         $feed->as_string;
47 }
48
49 sub generate_html_index {
50         my ($class, $args) = @_;
51         require PublicInbox::Thread;
52
53         my $max = $args->{max} || MAX_PER_PAGE;
54         my $feed_opts = get_feedopts($args);
55
56         my $title = $feed_opts->{description} || '';
57         $title = PublicInbox::Hval->new_oneline($title)->as_html;
58
59         my @messages;
60         my $git = PublicInbox::GitCatFile->new($args->{git_dir});
61         my $last = each_recent_blob($args, sub {
62                 my $mime = do_cat_mail($git, $_[0]) or return 0;
63                 $mime->body_set(''); # save some memory
64
65                 my $t = eval { str2time($mime->header('Date')) };
66                 defined($t) or $t = 0;
67                 $mime->header_set('X-PI-Date', $t);
68                 push @messages, $mime;
69                 1;
70         });
71         $git = undef; # destroy pipes.
72
73         my $th = PublicInbox::Thread->new(@messages);
74         $th->thread;
75         my $html = "<html><head><title>$title</title>" .
76                 '<link rel="alternate" title="Atom feed" href="' .
77                 $feed_opts->{atomurl} . '" type="application/atom+xml"/>' .
78                 '</head><body><pre>';
79
80         # sort by date, most recent at top
81         $th->order(sub {
82                 sort {
83                         $b->topmost->message->header('X-PI-Date') <=>
84                         $a->topmost->message->header('X-PI-Date')
85                 } @_;
86         });
87         dump_html_line($_, 0, \$html) for $th->rootset;
88
89         Email::Address->purge_cache;
90
91         my $footer = nav_footer($args->{cgi}, $last);
92         $footer = "<hr /><pre>$footer</pre>" if $footer;
93         $html . "</pre>$footer</html>";
94 }
95
96 # private subs
97
98 sub nav_footer {
99         my ($cgi, $last) = @_;
100         $cgi or return '';
101         my $old_r = $cgi->param('r');
102         my $head = '    ';
103         my $next = '    ';
104
105         if ($last) {
106                 $next = qq!<a href="?r=$last">next</a>!;
107         }
108         if ($old_r) {
109                 $head = $cgi->path_info;
110                 $head = qq!<a href="$head">head</a>!;
111         }
112         "$next $head";
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         push @cmd, $range;
137
138         my $pid = open(my $log, '-|', @cmd) or
139                 die('open `'.join(' ', @cmd) . " pipe failed: $!\n");
140         my %deleted; # only an optimization at this point
141         my $last;
142         my $nr = 0;
143         my @commits = ();
144         while (my $line = <$log>) {
145                 if ($line =~ /$addmsg/o) {
146                         my $add = $1;
147                         next if $deleted{$add};
148                         $nr += $cb->($add);
149                         if ($nr >= $max) {
150                                 $last = 1;
151                                 last;
152                         }
153                 } elsif ($line =~ /$delmsg/o) {
154                         $deleted{$1} = 1;
155                 } elsif ($line =~ /^commit (${hex}{40})/) {
156                         push @commits, $1;
157                 }
158         }
159
160         if ($last) {
161                 while (my $line = <$log>) {
162                         if ($line =~ /^commit (${hex}{40})/) {
163                                 push @commits, $1;
164                                 last;
165                         }
166                 }
167         } else {
168                 push @commits, undef;
169         }
170
171         close $log; # we may EPIPE here
172         # for pagination
173         $commits[-1];
174 }
175
176 # private functions below
177 sub get_feedopts {
178         my ($args) = @_;
179         my $pi_config = $args->{pi_config};
180         my $listname = $args->{listname};
181         my $cgi = $args->{cgi};
182         my %rv;
183         if (open my $fh, '<', "$args->{git_dir}/description") {
184                 chomp($rv{description} = <$fh>);
185                 close $fh;
186         }
187
188         if ($pi_config && defined $listname && length $listname) {
189                 foreach my $key (qw(address)) {
190                         $rv{$key} = $pi_config->get($listname, $key) || "";
191                 }
192         }
193         my $url_base;
194         if ($cgi) {
195                 my $path_info = $cgi->path_info;
196                 my $base;
197                 if (ref($cgi) eq 'CGI') {
198                         $base = $cgi->url(-base);
199                 } else {
200                         $base = $cgi->base->as_string;
201                         $base =~ s!/\z!!;
202                 }
203                 $url_base = $path_info;
204                 if ($url_base =~ s!/(?:|index\.html)?\z!!) {
205                         $rv{atomurl} = "$base$url_base/atom.xml";
206                 } else {
207                         $url_base =~ s!/atom\.xml\z!!;
208                         $rv{atomurl} = $base . $path_info;
209                         $url_base = $base . $url_base; # XXX is this needed?
210                 }
211         } else {
212                 $url_base = "http://example.com";
213                 $rv{atomurl} = "$url_base/atom.xml";
214         }
215         $rv{url} ||= "$url_base/";
216         $rv{midurl} = "$url_base/m/";
217         $rv{fullurl} = "$url_base/f/";
218
219         \%rv;
220 }
221
222 sub mime_header {
223         my ($mime, $name) = @_;
224         PublicInbox::Hval->new_oneline($mime->header($name))->raw;
225 }
226
227 sub feed_date {
228         my ($date) = @_;
229         my @t = eval { strptime($date) };
230
231         scalar(@t) ? POSIX::strftime(DATEFMT, @t) : 0;
232 }
233
234 # returns 0 (skipped) or 1 (added)
235 sub add_to_feed {
236         my ($feed_opts, $feed, $add, $git) = @_;
237
238         my $mime = do_cat_mail($git, $add) or return 0;
239         my $midurl = $feed_opts->{midurl} || 'http://example.com/m/';
240         my $fullurl = $feed_opts->{fullurl} || 'http://example.com/f/';
241
242         my $mid = $mime->header_obj->header_raw('Message-ID');
243         defined $mid or return 0;
244         $mid = PublicInbox::Hval->new_msgid($mid);
245         my $href = $mid->as_href . '.html';
246         my $content = PublicInbox::View->feed_entry($mime, $fullurl . $href);
247         defined($content) or return 0;
248
249         my $subject = mime_header($mime, 'Subject') or return 0;
250
251         my $from = mime_header($mime, 'From') or return 0;
252         my @from = Email::Address->parse($from);
253         my $name = $from[0]->name;
254         defined $name or $name = "";
255         my $email = $from[0]->address;
256         defined $email or $email = "";
257
258         my $date = $mime->header('Date');
259         $date = PublicInbox::Hval->new_oneline($date);
260         $date = feed_date($date->raw) or return 0;
261         $add =~ tr!/!!d;
262         my $h = '[a-f0-9]';
263         my (@uuid5) = ($add =~ m!\A($h{8})($h{4})($h{4})($h{4})($h{12})!o);
264
265         $feed->add_entry(
266                 author => { name => $name, email => $email },
267                 title => $subject,
268                 updated => $date,
269                 content => { type => 'xhtml', content => $content },
270                 link => $midurl . $href,
271                 id => 'urn:uuid:' . join('-', @uuid5),
272         );
273         1;
274 }
275
276 sub dump_html_line {
277         my ($self, $level, $html) = @_;
278         if ($self->message) {
279                 $$html .= (' ' x $level);
280                 my $mime = $self->message;
281                 my $subj = $mime->header('Subject');
282                 my $mid = $mime->header_obj->header_raw('Message-ID');
283                 $mid = PublicInbox::Hval->new_msgid($mid);
284                 my $href = 'm/' . $mid->as_href . '.html';
285                 my $from = mime_header($mime, 'From');
286
287                 my @from = Email::Address->parse($from);
288                 $from = $from[0]->name;
289                 (defined($from) && length($from)) or $from = $from[0]->address;
290
291                 $from = PublicInbox::Hval->new_oneline($from)->as_html;
292                 $subj = PublicInbox::Hval->new_oneline($subj)->as_html;
293                 $$html .= "<a href=\"$href\">$subj</a> $from\n";
294         }
295         dump_html_line($self->child, $level+1, $html) if $self->child;
296         dump_html_line($self->next, $level, $html) if $self->next;
297 }
298
299 sub do_cat_mail {
300         my ($git, $path) = @_;
301         my $str = $git->cat_file("HEAD:$path");
302         Email::MIME->new($str);
303 }
304
305 1;