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