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