]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Feed.pm
index: simplify main landing page if search-enabled
[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
69         my $state;
70         my $git = PublicInbox::GitCatFile->new($ctx->{git_dir});
71         my $topics;
72         my $srch = $ctx->{srch};
73         $srch and $topics = [ [], {} ];
74         my (undef, $last) = each_recent_blob($ctx, sub {
75                 my ($path, $commit, $ts, $u, $subj) = @_;
76                 $state ||= [ undef, {}, $commit, 0 ];
77
78                 if ($srch) {
79                         add_topic($git, $srch, $topics, $path, $ts, $u, $subj);
80                 } else {
81                         my $mime = do_cat_mail($git, $path) or return 0;
82                         $html .=
83                              PublicInbox::View->index_entry($mime, 0, $state);
84                         1;
85                 }
86         });
87         Email::Address->purge_cache;
88         $git = undef; # destroy pipes.
89
90         my $footer = nav_footer($ctx->{cgi}, $last, $feed_opts, $state);
91         if ($footer) {
92                 my $list_footer = $ctx->{footer};
93                 $footer .= "\n" . $list_footer if $list_footer;
94                 $footer = "<hr /><pre>$footer</pre>";
95         }
96         dump_topics(\$html, $topics) if $topics;
97         $html .= "$footer</body></html>";
98 }
99
100 # private subs
101
102 sub nav_footer {
103         my ($cgi, $last, $feed_opts, $state) = @_;
104         $cgi or return '';
105         my $old_r = $cgi->param('r');
106         my $head = '    ';
107         my $next = '    ';
108         # $state = [ undef, {}, $first_commit, $last_anchor ];
109         my $first = $state->[2];
110         my $anchor = $state->[3];
111
112         if ($last) {
113                 $next = qq!<a\nhref="?r=$last">next</a>!;
114         }
115         if ($old_r) {
116                 $head = $cgi->path_info;
117                 $head = qq!<a\nhref="$head">head</a>!;
118         }
119         my $atom = "<a\nhref=\"$feed_opts->{atomurl}\">atom</a>";
120         my $permalink = "<a\nhref=\"?r=$first\">permalink</a>";
121         "<a\nname=\"s$anchor\">page:</a> $next $head $atom $permalink";
122 }
123
124 sub each_recent_blob {
125         my ($ctx, $cb) = @_;
126         my $max = $ctx->{max} || MAX_PER_PAGE;
127         my $hex = '[a-f0-9]';
128         my $addmsg = qr!^:000000 100644 \S+ \S+ A\t(${hex}{2}/${hex}{38})$!;
129         my $delmsg = qr!^:100644 000000 \S+ \S+ D\t(${hex}{2}/${hex}{38})$!;
130         my $refhex = qr/${hex}{4,40}(?:~\d+)?/;
131         my $cgi = $ctx->{cgi};
132
133         # revision ranges may be specified
134         my $range = 'HEAD';
135         my $r = $cgi->param('r') if $cgi;
136         if ($r && ($r =~ /\A(?:$refhex\.\.)?$refhex\z/o)) {
137                 $range = $r;
138         }
139
140         # get recent messages
141         # we could use git log -z, but, we already know ssoma will not
142         # leave us with filenames with spaces in them..
143         my @cmd = ('git', "--git-dir=$ctx->{git_dir}",
144                         qw/log --no-notes --no-color --raw -r
145                            --abbrev=16 --abbrev-commit/,
146                         "--format=%h%x00%ct%x00%an%x00%s%x00");
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 ($cur_commit, $first_commit, $last_commit);
155         my ($ts, $subj, $u);
156         while (defined(my $line = <$log>)) {
157                 if ($line =~ /$addmsg/o) {
158                         my $add = $1;
159                         next if $deleted{$add}; # optimization-only
160                         $nr += $cb->($add, $cur_commit, $ts, $u, $subj);
161                         if ($nr >= $max) {
162                                 $last = 1;
163                                 last;
164                         }
165                 } elsif ($line =~ /$delmsg/o) {
166                         $deleted{$1} = 1;
167                 } elsif ($line =~ /^${hex}{7,40}/o) {
168                         ($cur_commit, $ts, $u, $subj) = split("\0", $line);
169                         unless (defined $first_commit) {
170                                 $first_commit = $cur_commit;
171                         }
172                 }
173         }
174
175         if ($last) {
176                 while (my $line = <$log>) {
177                         if ($line =~ /^(${hex}{7,40})/o) {
178                                 $last_commit = $1;
179                                 last;
180                         }
181                 }
182         }
183
184         close $log; # we may EPIPE here
185         # for pagination
186         ($first_commit, $last_commit);
187 }
188
189 # private functions below
190 sub get_feedopts {
191         my ($ctx) = @_;
192         my $pi_config = $ctx->{pi_config};
193         my $listname = $ctx->{listname};
194         my $cgi = $ctx->{cgi};
195         my %rv;
196         if (open my $fh, '<', "$ctx->{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 $header_obj = $mime->header_obj;
256         my $mid = $header_obj->header_raw('Message-ID');
257         defined $mid or return 0;
258         $mid = PublicInbox::Hval->new_msgid($mid);
259         my $href = $mid->as_href . '.html';
260         my $content = PublicInbox::View->feed_entry($mime, $fullurl . $href);
261         defined($content) or return 0;
262         $mime = undef;
263
264         my $subject = mime_header($header_obj, 'Subject') or return 0;
265
266         my $from = mime_header($header_obj, 'From') or return 0;
267         my @from = Email::Address->parse($from);
268         my $name = $from[0]->name;
269         defined $name or $name = "";
270         my $email = $from[0]->address;
271         defined $email or $email = "";
272
273         my $date = $header_obj->header('Date');
274         $date = PublicInbox::Hval->new_oneline($date);
275         $date = feed_date($date->raw) or return 0;
276         $add =~ tr!/!!d;
277         my $h = '[a-f0-9]';
278         my (@uuid5) = ($add =~ m!\A($h{8})($h{4})($h{4})($h{4})($h{12})!o);
279
280         $feed->add_entry(
281                 author => { name => $name, email => $email },
282                 title => $subject,
283                 updated => $date,
284                 content => { type => 'xhtml', content => $content },
285                 link => $midurl . $href,
286                 id => 'urn:uuid:' . join('-', @uuid5),
287         );
288         1;
289 }
290
291 sub do_cat_mail {
292         my ($git, $path) = @_;
293         my $mime = eval {
294                 my $str = $git->cat_file("HEAD:$path");
295                 Email::MIME->new($str);
296         };
297         $@ ? undef : $mime;
298 }
299
300 # accumulate recent topics if search is supported
301 sub add_topic {
302         my ($git, $srch, $topics, $path, $ts, $u, $subj) = @_;
303         my ($order, $subjs) = @$topics;
304         my $header_obj;
305
306         # legacy ssoma did not set commit titles based on Subject
307         $subj = $enc_utf8->decode($subj);
308         if ($subj eq 'mda') {
309                 my $mime = do_cat_mail($git, $path) or return 0;
310                 $header_obj = $mime->header_obj;
311                 $subj = mime_header($header_obj, 'Subject');
312         }
313
314         $subj = $srch->subject_normalized($subj);
315         if (++$subjs->{$subj} == 1) {
316                 unless ($header_obj) {
317                         my $mime = do_cat_mail($git, $path) or return 0;
318                         $header_obj = $mime->header_obj;
319                 }
320                 my $mid = $header_obj->header_raw('Message-ID');
321                 $mid = mid_compressed(mid_clean($mid));
322                 $u = $enc_utf8->decode($u);
323                 push @$order, [ $mid, $ts, $u, $subj ];
324                 return 1;
325         }
326         0; # old topic, continue going
327 }
328
329 sub dump_topics {
330         my ($dst, $topics) = @_;
331         my ($order, $subjs) = @$topics;
332         $$dst .= '[No recent topics]' unless (scalar @$order);
333         while (defined(my $info = shift @$order)) {
334                 my ($mid, $ts, $u, $subj) = @$info;
335                 my $n = delete $subjs->{$subj};
336                 $mid = PublicInbox::Hval->new($mid)->as_href;
337                 $subj = PublicInbox::Hval->new($subj)->as_html;
338                 $u = PublicInbox::Hval->new($u)->as_html;
339                 $$dst .= "<a\nhref=\"t/$mid.html#u\"><b>$subj</b></a>\n- ";
340                 $ts = POSIX::strftime('%Y-%m-%d %H:%M', gmtime($ts));
341                 if ($n == 1) {
342                         $$dst .= "created by $u @ $ts UTC\n"
343                 } else {
344                         # $n isn't the total number of posts on the topic,
345                         # just the number of posts in the current "git log"
346                         # window, so leave it unlabeled
347                         $$dst .= "updated by $u @ $ts UTC ($n)\n"
348                 }
349         }
350         $$dst .= '</pre>'
351 }
352
353 1;