]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
index: layout fix + title and Atom feed links at top
[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);
9 use PublicInbox::Hval;
10 use PublicInbox::GitCatFile;
11 use PublicInbox::View;
12 use PublicInbox::MID qw/mid_clean mid_compressed/;
13 use constant {
14         DATEFMT => '%Y-%m-%dT%H:%M:%SZ', # atom standard
15         MAX_PER_PAGE => 25, # this needs to be tunable
16 };
17
18 use Encode qw/find_encoding/;
19 my $enc_utf8 = find_encoding('UTF-8');
20
21 # main function
22 sub generate {
23         my ($class, $ctx) = @_;
24         require XML::Atom::SimpleFeed;
25         require POSIX;
26         my $max = $ctx->{max} || MAX_PER_PAGE;
27
28         my $feed_opts = get_feedopts($ctx);
29         my $addr = $feed_opts->{address};
30         $addr = $addr->[0] if ref($addr);
31         my $feed = XML::Atom::SimpleFeed->new(
32                 title => $feed_opts->{description} || "unnamed feed",
33                 link => $feed_opts->{url} || "http://example.com/",
34                 link => {
35                         rel => 'self',
36                         href => $feed_opts->{atomurl} ||
37                                 "http://example.com/atom.xml",
38                 },
39                 id => 'mailto:' . ($addr || 'public-inbox@example.com'),
40                 updated => POSIX::strftime(DATEFMT, gmtime),
41         );
42         $feed->no_generator;
43
44         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
45         each_recent_blob($ctx, sub {
46                 my ($add, undef) = @_;
47                 add_to_feed($feed_opts, $feed, $add, $git);
48         });
49         $git = undef; # destroy pipes
50         Email::Address->purge_cache;
51         $feed->as_string;
52 }
53
54 sub generate_html_index {
55         my ($class, $ctx) = @_;
56
57         my $max = $ctx->{max} || MAX_PER_PAGE;
58         my $feed_opts = get_feedopts($ctx);
59
60         my $title = $feed_opts->{description} || '';
61         $title = PublicInbox::Hval->new_oneline($title)->as_html;
62         my $atom_url = $feed_opts->{atomurl};
63
64         my $html = "<html><head><title>$title</title>" .
65                 "<link\nrel=alternate\ntitle=\"Atom feed\"\n".
66                 "href=\"$atom_url\"\"\ntype=\"application/atom+xml\"/>" .
67                 '</head><body>' . PublicInbox::View::PRE_WRAP .
68                 "<b>$title</b> (<a\nhref=\"$atom_url\">Atom feed</a>)\n";
69
70         my $state;
71         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
72         my $topics;
73         my $srch = $ctx->{srch};
74         $srch and $topics = [ [], {} ];
75         my (undef, $last) = each_recent_blob($ctx, sub {
76                 my ($path, $commit, $ts, $u, $subj) = @_;
77                 $state ||= [ undef, {}, $commit, 0 ];
78
79                 if ($srch) {
80                         add_topic($git, $srch, $topics, $path, $ts, $u, $subj);
81                 } else {
82                         my $mime = do_cat_mail($git, $path) or return 0;
83                         $html .=
84                              PublicInbox::View->index_entry($mime, 0, $state);
85                         1;
86                 }
87         });
88         Email::Address->purge_cache;
89         $git = undef; # destroy pipes.
90
91         my $footer = nav_footer($ctx->{cgi}, $last, $feed_opts, $state);
92         if ($footer) {
93                 my $list_footer = $ctx->{footer};
94                 $footer .= "\n" . $list_footer if $list_footer;
95                 $footer = "<hr /><pre>$footer</pre>";
96         }
97         dump_topics(\$html, $topics) if $topics;
98         $html .= "$footer</body></html>";
99 }
100
101 # private subs
102
103 sub nav_footer {
104         my ($cgi, $last, $feed_opts, $state) = @_;
105         $cgi or return '';
106         my $old_r = $cgi->param('r');
107         my $head = '    ';
108         my $next = '    ';
109         # $state = [ undef, {}, $first_commit, $last_anchor ];
110         my $first = $state->[2];
111         my $anchor = $state->[3];
112
113         if ($last) {
114                 $next = qq!<a\nhref="?r=$last">next</a>!;
115         }
116         if ($old_r) {
117                 $head = $cgi->path_info;
118                 $head = qq!<a\nhref="$head">head</a>!;
119         }
120         my $atom = "<a\nhref=\"$feed_opts->{atomurl}\">atom</a>";
121         my $permalink = "<a\nhref=\"?r=$first\">permalink</a>";
122         "<a\nname=\"s$anchor\">page:</a> $next $head $atom $permalink";
123 }
124
125 sub each_recent_blob {
126         my ($ctx, $cb) = @_;
127         my $max = $ctx->{max} || MAX_PER_PAGE;
128         my $hex = '[a-f0-9]';
129         my $addmsg = qr!^:000000 100644 \S+ \S+ A\t(${hex}{2}/${hex}{38})$!;
130         my $delmsg = qr!^:100644 000000 \S+ \S+ D\t(${hex}{2}/${hex}{38})$!;
131         my $refhex = qr/${hex}{4,40}(?:~\d+)?/;
132         my $cgi = $ctx->{cgi};
133
134         # revision ranges may be specified
135         my $range = 'HEAD';
136         my $r = $cgi->param('r') if $cgi;
137         if ($r && ($r =~ /\A(?:$refhex\.\.)?$refhex\z/o)) {
138                 $range = $r;
139         }
140
141         # get recent messages
142         # we could use git log -z, but, we already know ssoma will not
143         # leave us with filenames with spaces in them..
144         my @cmd = ('git', "--git-dir=$ctx->{git_dir}",
145                         qw/log --no-notes --no-color --raw -r
146                            --abbrev=16 --abbrev-commit/,
147                         "--format=%h%x00%ct%x00%an%x00%s%x00");
148         push @cmd, $range;
149
150         my $pid = open(my $log, '-|', @cmd) or
151                 die('open `'.join(' ', @cmd) . " pipe failed: $!\n");
152         my %deleted; # only an optimization at this point
153         my $last;
154         my $nr = 0;
155         my ($cur_commit, $first_commit, $last_commit);
156         my ($ts, $subj, $u);
157         while (defined(my $line = <$log>)) {
158                 if ($line =~ /$addmsg/o) {
159                         my $add = $1;
160                         next if $deleted{$add}; # optimization-only
161                         $nr += $cb->($add, $cur_commit, $ts, $u, $subj);
162                         if ($nr >= $max) {
163                                 $last = 1;
164                                 last;
165                         }
166                 } elsif ($line =~ /$delmsg/o) {
167                         $deleted{$1} = 1;
168                 } elsif ($line =~ /^${hex}{7,40}/o) {
169                         ($cur_commit, $ts, $u, $subj) = split("\0", $line);
170                         unless (defined $first_commit) {
171                                 $first_commit = $cur_commit;
172                         }
173                 }
174         }
175
176         if ($last) {
177                 while (my $line = <$log>) {
178                         if ($line =~ /^(${hex}{7,40})/o) {
179                                 $last_commit = $1;
180                                 last;
181                         }
182                 }
183         }
184
185         close $log; # we may EPIPE here
186         # for pagination
187         ($first_commit, $last_commit);
188 }
189
190 # private functions below
191 sub get_feedopts {
192         my ($ctx) = @_;
193         my $pi_config = $ctx->{pi_config};
194         my $listname = $ctx->{listname};
195         my $cgi = $ctx->{cgi};
196         my %rv;
197         if (open my $fh, '<', "$ctx->{git_dir}/description") {
198                 chomp($rv{description} = <$fh>);
199                 close $fh;
200         }
201
202         if ($pi_config && defined $listname && length $listname) {
203                 foreach my $key (qw(address)) {
204                         $rv{$key} = $pi_config->get($listname, $key) || "";
205                 }
206         }
207         my $url_base;
208         if ($cgi) {
209                 my $path_info = $cgi->path_info;
210                 my $base;
211                 if (ref($cgi) eq 'CGI') {
212                         $base = $cgi->url(-base);
213                 } else {
214                         $base = $cgi->base->as_string;
215                         $base =~ s!/\z!!;
216                 }
217                 $url_base = $path_info;
218                 if ($url_base =~ s!/(?:|index\.html)?\z!!) {
219                         $rv{atomurl} = "$base$url_base/atom.xml";
220                 } else {
221                         $url_base =~ s!/atom\.xml\z!!;
222                         $rv{atomurl} = $base . $path_info;
223                         $url_base = $base . $url_base; # XXX is this needed?
224                 }
225         } else {
226                 $url_base = "http://example.com";
227                 $rv{atomurl} = "$url_base/atom.xml";
228         }
229         $rv{url} ||= "$url_base/";
230         $rv{midurl} = "$url_base/m/";
231         $rv{fullurl} = "$url_base/f/";
232
233         \%rv;
234 }
235
236 sub mime_header {
237         my ($mime, $name) = @_;
238         PublicInbox::Hval->new_oneline($mime->header($name))->raw;
239 }
240
241 sub feed_date {
242         my ($date) = @_;
243         my @t = eval { strptime($date) };
244
245         scalar(@t) ? POSIX::strftime(DATEFMT, @t) : 0;
246 }
247
248 # returns 0 (skipped) or 1 (added)
249 sub add_to_feed {
250         my ($feed_opts, $feed, $add, $git) = @_;
251
252         my $mime = do_cat_mail($git, $add) or return 0;
253         my $midurl = $feed_opts->{midurl} || 'http://example.com/m/';
254         my $fullurl = $feed_opts->{fullurl} || 'http://example.com/f/';
255
256         my $header_obj = $mime->header_obj;
257         my $mid = $header_obj->header_raw('Message-ID');
258         defined $mid or return 0;
259         $mid = PublicInbox::Hval->new_msgid($mid);
260         my $href = $mid->as_href . '.html';
261         my $content = PublicInbox::View->feed_entry($mime, $fullurl . $href);
262         defined($content) or return 0;
263         $mime = undef;
264
265         my $subject = mime_header($header_obj, 'Subject') or return 0;
266
267         my $from = mime_header($header_obj, 'From') or return 0;
268         my @from = Email::Address->parse($from);
269         my $name = $from[0]->name;
270         defined $name or $name = "";
271         my $email = $from[0]->address;
272         defined $email or $email = "";
273
274         my $date = $header_obj->header('Date');
275         $date = PublicInbox::Hval->new_oneline($date);
276         $date = feed_date($date->raw) or return 0;
277         $add =~ tr!/!!d;
278         my $h = '[a-f0-9]';
279         my (@uuid5) = ($add =~ m!\A($h{8})($h{4})($h{4})($h{4})($h{12})!o);
280
281         $feed->add_entry(
282                 author => { name => $name, email => $email },
283                 title => $subject,
284                 updated => $date,
285                 content => { type => 'xhtml', content => $content },
286                 link => $midurl . $href,
287                 id => 'urn:uuid:' . join('-', @uuid5),
288         );
289         1;
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 # accumulate recent topics if search is supported
302 sub add_topic {
303         my ($git, $srch, $topics, $path, $ts, $u, $subj) = @_;
304         my ($order, $subjs) = @$topics;
305         my $header_obj;
306
307         # legacy ssoma did not set commit titles based on Subject
308         $subj = $enc_utf8->decode($subj);
309         if ($subj eq 'mda') {
310                 my $mime = do_cat_mail($git, $path) or return 0;
311                 $header_obj = $mime->header_obj;
312                 $subj = mime_header($header_obj, 'Subject');
313         }
314
315         $subj = $srch->subject_normalized($subj);
316         if (++$subjs->{$subj} == 1) {
317                 unless ($header_obj) {
318                         my $mime = do_cat_mail($git, $path) or return 0;
319                         $header_obj = $mime->header_obj;
320                 }
321                 my $mid = $header_obj->header_raw('Message-ID');
322                 $mid = mid_compressed(mid_clean($mid));
323                 $u = $enc_utf8->decode($u);
324                 push @$order, [ $mid, $ts, $u, $subj ];
325                 return 1;
326         }
327         0; # old topic, continue going
328 }
329
330 sub dump_topics {
331         my ($dst, $topics) = @_;
332         my ($order, $subjs) = @$topics;
333         $$dst .= "\n[No recent topics]" unless (scalar @$order);
334         while (defined(my $info = shift @$order)) {
335                 my ($mid, $ts, $u, $subj) = @$info;
336                 my $n = delete $subjs->{$subj};
337                 $mid = PublicInbox::Hval->new($mid)->as_href;
338                 $subj = PublicInbox::Hval->new($subj)->as_html;
339                 $u = PublicInbox::Hval->new($u)->as_html;
340                 $$dst .= "\n<a\nhref=\"t/$mid.html#u\"><b>$subj</b></a>\n- ";
341                 $ts = POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
342                 if ($n == 1) {
343                         $$dst .= "created by $u @ $ts UTC\n"
344                 } else {
345                         # $n isn't the total number of posts on the topic,
346                         # just the number of posts in the current "git log"
347                         # window, so leave it unlabeled
348                         $$dst .= "updated by $u @ $ts UTC ($n)\n"
349                 }
350         }
351         $$dst .= '</pre>'
352 }
353
354 1;