1 # Copyright (C) 2016-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Plack app redirector for mapping /$NEWSGROUP requests to
5 # the appropriate /$INBOX in PublicInbox::WWW because some
6 # auto-linkifiers cannot handle nntp:// redirects properly.
7 # This is also used directly by PublicInbox::WWW
8 package PublicInbox::NewsWWW;
11 use PublicInbox::Config;
12 use PublicInbox::MID qw(mid_escape);
13 use PublicInbox::Hval qw(prurl);
16 my ($class, $pi_cfg) = @_;
17 bless { pi_cfg => $pi_cfg // PublicInbox::Config->new }, $class;
21 my ($code, $url) = @_;
23 [ Location => $url, 'Content-Type' => 'text/plain' ],
24 [ "Redirecting to $url\n" ] ]
29 return if scalar(@$arg) > 1;
31 # do not pass $env since HTTP_HOST may differ
32 my $url = $ibx->base_url or return;
35 eval { $ibx->mm->num_for($mid) } or return;
37 # 302 since the same message may show up on
38 # multiple inboxes and inboxes can be added/reordered
39 $arg->[1] = redirect(302, $url .= mid_escape($mid) . '/');
43 my ($self, $env) = @_;
45 # some links may have the article number in them:
46 # /inbox.foo.bar/123456
47 my (undef, @parts) = split(m!/!, $env->{PATH_INFO});
49 [ 404, [qw(Content-Type text/plain)], ["404 Not Found\n"] ];
50 my ($ng, $article) = @parts;
51 my $pi_cfg = $self->{pi_cfg};
52 if (my $ibx = $pi_cfg->lookup_newsgroup($ng)) {
53 my $url = prurl($env, $ibx->{url});
55 if (defined $article && $article =~ /\A[0-9]+\z/) {
56 my $mid = eval { $ibx->mm->mid_for($article) };
58 # article IDs are not stable across clones,
59 # do not encourage caching/bookmarking them
61 $url .= mid_escape($mid) . '/';
64 return redirect($code, $url);
67 my @try = (join('/', @parts));
69 # trailing slash is in the rest of our WWW, so maybe some users
71 if ($parts[-1] eq '') {
73 push @try, join('/', @parts);
75 my $ALL = $pi_cfg->ALL;
76 if (my $over = $ALL ? $ALL->over : undef) {
77 my $by_eidx_key = $pi_cfg->{-by_eidx_key};
80 while (my $x = $over->next_by_mid($mid, \$id, \$prev)) {
81 my $xr3 = $over->get_xref3($x->{num});
83 s/:[0-9]+:$x->{blob}\z// or next;
84 my $ibx = $by_eidx_key->{$_} // next;
85 my $url = $ALL->base_url($env) //
86 $ibx->base_url // next;
87 $url .= mid_escape($mid) . '/';
88 return redirect(302, $url);
92 } else { # slow path, scan every inbox
94 my $arg = [ $mid ]; # [1] => result
95 $pi_cfg->each_inbox(\&try_inbox, $arg);
96 return $arg->[1] if $arg->[1];
99 [ 404, [qw(Content-Type text/plain)], ["404 Not Found\n"] ];