blib/lib/PGXN/Site/Controller.pm untested

filter: Statementstmt 0.0% 0 / 172 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 64 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 29 totaltotal 0.0% 0 / 345 SCAR 60.4
CC
20
Cov
0%
search
72.0
server_error
30.0
users
20.0
CRAP 420.0
1 package PGXN::Site::Controller;
2  
3 use 5.10.0;
4 use utf8;
5 #use aliased 'PGXN::Site::Request';
6 use Plack::Request;
7 use Plack::Response;
8 use PGXN::Site::Templates;
9 use HTML::TagCloud;
10 use Encode;
11 use WWW::PGXN;
12 use List::MoreUtils qw(any);
13 use namespace::autoclean;
14 our $VERSION = v0.22.1;
15  
16 Template::Declare->init( dispatch_to => ['PGXN::Site::Templates'] );
17  
18 my %code_for = (
19 success => 200,
20 seeother => 303,
21 badrequest => 400,
22 forbidden => 403,
23 notfound => 404,
24 notallowed => 405,
25 conflict => 409,
26 gone => 410,
27 servererror => 200, # Only handled by ErrorDocument, which keeps 500.
28 );
29  
30 sub new {
31 my ($class, %p) = @_;
32  
33 unless ($p{base_url} && $p{api_url} && $p{errors_to} && $p{errors_from} && $p{feedback_to}) {
34 die "Missing required parameters base_url, api_url, errors_to, errors_from, and feedback_to\n";
35 }
36  
37 (my $api_url = $p{api_url}) =~ s{/+$}{};
38 (my $base_url = $p{base_url}) =~ s{/+$}{};
39 bless {
40 errors_to => $p{errors_to},
41 errors_from => $p{errors_from},
42 feedback_to => $p{feedback_to},
43 base_url => URI->new($base_url),
44 api_url => URI->new($api_url),
45 api => WWW::PGXN->new(
46 url => $p{private_api_url} || $api_url,
47 proxy => $p{proxy_url}
48 )
49 } => $class;
50 }
51  
52 sub api { shift->{api} }
53 sub base_url { shift->{base_url} }
54 sub api_url { shift->{api_url} }
55 sub errors_to { shift->{errors_to} }
56 sub errors_from { shift->{errors_from} }
57 sub feedback_to { shift->{feedback_to} }
58  
59 sub render {
60 my ($self, $template, $p) = @_;
61 my $req = $p->{req} ||= Plack::Request->new($p->{env});
62 my $res = $req->new_response($p->{code} || 200);
63 $p->{vars}{base_url} = $self->base_url;
64 my $body = encode_utf8 +Template::Declare->show($template, $p->{req}, $p->{vars});
65 $res->body($body);
66 $res->content_length(length $body);
67 $res->content_type($p->{type} || 'text/html; charset=UTF-8');
68 $res->finalize;
69 }
70  
71 sub redirect {
72 my ($sel, $uri, $code) = @_;
73 my $res = Plack::Response->new;
74 $res->redirect($uri, $code || $code_for{seeother});
75 return $res->finalize;
76 }
77  
78 sub missing {
79 my ($self, $env) = @_;
80 $self->render('/notfound', { env => $env, code => $code_for{notfound} });
81 }
82  
83 sub _cloud {
84 my $self = shift;
85 my $cloud = HTML::TagCloud->new(levels => 12);
86 my $tags = $self->api->get_stats('tag');
87 $cloud->add($_->{tag}, "/tag/$_->{tag}/", $_->{dists})
88 for grep { $_->{tag} = lc $_->{tag} } @{ $tags->{popular} };
89 return $cloud;
90 }
91  
92 sub home {
93 my $self = shift;
94 $self->render('/home', {
95 env => shift,
96 vars => {
97 cloud => _cloud($self),
98 dists => $self->api->get_stats('dist')->{recent},
99 },
100 });
101 }
102  
103 sub feedback {
104 my $self = shift;
105 $self->render('/feedback', { env => shift, vars => {
106 feedback_to => $self->feedback_to
107 } });
108 }
109  
110 sub art {
111 my $self = shift;
112 $self->render('/art', { env => shift });
113 }
114  
115 sub about {
116 my $self = shift;
117 $self->render('/about', { env => shift, vars => {
118 stats => $self->api->get_stats('summary'),
119 } });
120 }
121  
122 sub donors {
123 my $self = shift;
124 $self->render('/donors', { env => shift });
125 }
126  
127 sub recent {
128 my $self = shift;
129 my $dists = $self->api->get_stats('dist')->{recent};
130 $self->render('/recent', { env => shift, vars => { dists => $dists } });
131 }
132  
133 sub mirroring {
134 my $self = shift;
135 $self->render('/mirroring', { env => shift, vars => {
136 feedback_to => $self->feedback_to
137 } });
138 }
139  
140 sub spec {
141 my ($self, $env, $format) = @_;
142 return [
143 200,
144 ['Content-Type' => 'text/plain; charset=utf-8'],
145 [encode_utf8 $self->api->spec('txt')]
146 ] if $format eq 'txt';
147  
148 $self->render('/spec', { env => $env, vars => {
149 body => $self->api->spec('html')
150 } });
151 }
152  
153 sub faq {
154 my $self = shift;
155 $self->render('/faq', { env => shift });
156 }
157  
158 sub distribution {
159 my ($self, $env, $name, $version) = @_;
160 my $dist = $self->api->get_distribution($name => $version)
161 or return $self->missing($env);
162  
163 $self->render('/distribution', { env => $env, vars => {
164 dist => $dist,
165 api_url => $self->api_url,
166 dist_name => $dist->{name} . ($version ? " $version" : ''),
167 user => $self->api->get_user($dist->user),
168 }});
169 }
170  
171 sub document {
172 my ($self, $env, $name, $version, $path) = @_;
173 my $dist = $self->api->get_distribution($name => $version)
174 or return $self->missing($env);
175 $path =~ s/[.]html$//;
176 my $doc = $dist->body_for_html_doc($path) or return $self->missing($env);
177  
178 my ($dist_uri, $dist_name) = $version
179 ? (lc "/dist/$name/$version/", "$dist->{name} $version")
180 : (lc "/dist/$name/", $dist->{name});
181 $self->render('/document', { env => $env, vars => {
182 dist => $dist,
183 docpath => $path,
184 body => $doc,
185 dist_uri => $dist_uri,
186 dist_name => $dist_name,
187 user => $self->api->get_user($dist->user),
188 }});
189 }
190  
191 sub user {
192 my ($self, $env, $nick) = @_;
193 my $user = $self->api->get_user($nick) or return $self->missing($env);
194  
195 $self->render('/user', { env => $env, vars => {
196 user => $user,
197 api => $self->api,
198 api_url => $self->api_url,
199 }});
200 }
201  
202 sub users {
203 my ($self, $env) = @_;
204 my $req = Plack::Request->new($env);
205 my $params = $req->query_parameters;
206 my $char = lc ($params->{c} || '');
207  
208 # Usernames must always start with an ASCII letter.
209 if ($char && $char !~ /^[a-z]$/) {
210 return $self->render('/badrequest', {
211 env => $env,
212 code => $code_for{badrequest},
213 vars => { param => 'c' },
214 });
215 }
216  
217 for my $param (qw(o l)) {
218 my $val = $params->{$param};
219 return $self->render('/badrequest', {
220 env => $env,
221 code => $code_for{badrequest},
222 vars => { param => $param },
223 }) if $val && $val !~ /^\d+$/;
224 }
225  
226 $self->render('/users', { req => $req, vars => {
227 in => 'users',
228 char => $char,
229 api => $self->api,
230 users => $char ? $self->api->get_userlist($char) : undef,
231 }});
232 }
233  
234 sub tags {
235 my $self = shift;
236 $self->render('/tags', {
237 env => shift,
238 vars => { cloud => _cloud($self) },
239 });
240 }
241  
242 sub tag {
243 my ($self, $env, $tag) = @_;
244 $tag = $self->api->get_tag($tag) or return $self->missing($env);
245  
246 $self->render('/tag', { env => $env, vars => {
247 tag => $tag,
248 api => $self->api,
249 api_url => $self->api_url,
250 }});
251 }
252  
253 sub extension {
254 my ($self, $env, $ext) = @_;
255 $ext = $self->api->get_extension($ext) or return $self->missing($env);
256 my $data = $ext->{$ext->{latest}};
257 my $uri = lc "/dist/$data->{dist}/";
258 $uri .= "$data->{docpath}.html" if $data->{docpath};
259 $self->redirect($uri, $code_for{seeother});
260 }
261  
262 sub search {
263 my ($self, $env) = @_;
264 my $req = Plack::Request->new($env);
265 my $params = $req->query_parameters;
266 my $q = $params->{q};
267  
268 if (!defined $q || any { $q eq $_ } '', '*', '?') {
269 # Just redirect if there is no search term.
270 unless ($q) {
271 my $ref = '/';
272 if ($req->referer) {
273 my $uri = URI->new($req->referer);
274 $ref = $uri if $uri->can('host') && $uri->host
275 && $uri->host eq $req->uri->host;
276 }
277 return $self->redirect($ref, $code_for{seeother});
278 }
279 return $self->render('/badrequest', {
280 env => $env,
281 code => $code_for{badrequest},
282 vars => { param => 'q' },
283 });
284 }
285  
286 my $in = $params->{in};
287 unless (defined $in && any { $in eq $_ } qw(docs dists extensions users tags)) {
288 return $self->render('/badrequest', {
289 env => $env,
290 code => $code_for{badrequest},
291 vars => { param => $q ? 'in' : 'q' },
292 });
293 }
294  
295 for my $param (qw(o l)) {
296 my $val = $params->{$param};
297 return $self->render('/badrequest', {
298 env => $env,
299 code => $code_for{badrequest},
300 vars => { param => $param },
301 }) if $val && $val !~ /^\d+$/;
302 }
303  
304 $self->render('/search', { req => $req, vars => {
305 in => $in,
306 api => $self->api,
307 results => $self->api->search(
308 in => $in,
309 query => decode_utf8($q),
310 offset => $params->{o},
311 limit => $params->{l},
312 ),
313 }});
314 }
315  
316 sub server_error {
317 my ($self, $env) = @_;
318  
319 # Pull together the original request environment.
320 my $err_env = { map {
321 my $k = $_;
322 s/^psgix[.]errordocument[.]//
323 ? /plack[.]stacktrace[.]/ ? () : ($_ => $env->{$k} )
324 : ();
325 } keys %{ $env } };
326 my $uri = Plack::Request->new($err_env)->uri;
327  
328 if (%{ $err_env }) {
329 # Send an email to the administrator.
330 require Email::MIME;
331 require Email::Sender::Simple;
332 require Data::Dump;
333 if (my $errfh = $env->{'psgi.errors'}) {
334 print {$errfh} "An error occurred during a request to $uri:\n\n"
335 . ($env->{'plack.stacktrace.text'} || 'No Trace. :-(')
336 . "\n";
337 }
338  
339 my $email = Email::MIME->create(
340 header => [
341 From => $self->errors_from,
342 To => $self->errors_to,
343 Subject => 'PGXN Internal Server Error',
344 ],
345 attributes => {
346 content_type => 'text/plain',
347 charset => 'UTF-8',
348 },
349 body => "An error occurred during a request to $uri.\n\n"
350 . "Environment:\n\n" . Data::Dump::pp($err_env)
351 . "\n\nTrace:\n\n"
352 . ($env->{'plack.stacktrace.text'} || 'None found. :-(')
353 . "\n",
354 );
355 Email::Sender::Simple->send($email);
356 }
357  
358 $self->render('/servererror', { env => $env });
359 }
360  
361 1;
362  
363 =head1 Name
364  
365 PGXN::Site::Controller - The PGXN::Site request controller
366  
367 =head1 Synopsis
368  
369 use PGXN::Site::Controller;
370 use Router::Resource;
371  
372 my $controller = PGXN::Site::Controller->new(url => 'https://api.pgxn.org');
373 my $router = router {
374 resource '/' => sub {
375 GET { $controller->home(@_) };
376 };
377 };
378  
379 =head1 Description
380  
381 This class defines controller actions for PGXN::Site requests. It's designed
382 to be called from within Router::Resource HTTP methods.
383  
384 =head1 Interface
385  
386 =head2 Constructor
387  
388 =head3 C<new>
389  
390 my $controller = PGXN::Site::Controller->new(url => $private_api_url);
391  
392 Constructs and returns a new controller. The parameters are the same as those
393 supported by L<WWW::PGXN>, which will be used to fetch the data needed to
394 serve pages.
395  
396 =head2 Accessors
397  
398 =head3 C<api>
399  
400 my $api = $controller->api;
401  
402 Returns a L<WWW::PGXN> object used to access the PGXN API.
403  
404 =head3 C<api_url>
405  
406 my $api_url = $controller->api_url;
407  
408 Returns the URL used to link to the API in the UI. If C<private_api_url> is
409 not passed to C<new()>, this URL is also used for communicating with the API
410 via the L<WWW::PGXN> object returned by C<api>.
411  
412 =head3 C<base_url>
413  
414 my $base_url = $controller->base_url;
415  
416 Returns the base URL for the site. Used for links that must be absolute.
417  
418 =head3 C<errors_to>
419  
420 my $errors_to = $controller->errors_to;
421  
422 Returns the email address to which error messages will be sent.
423  
424 =head3 C<errors_from>
425  
426 my $errors_from = $controller->errors_from;
427  
428 Returns the email address from which error messages will be sent to
429 C<errors_to>.
430  
431 =head3 C<feedback_to>
432  
433 my $feedback_to = $controller->feedback_to;
434  
435 Returns the email address listed in the UI for sending feedback.
436  
437 =head2 Actions
438  
439 =head3 C<home>
440  
441 PGXN::Site::Controller->home($env);
442  
443 Displays the HTML for the home page.
444  
445 =head3 C<feedback>
446  
447 PGXN::Site::Controller->feedback($env);
448  
449 Displays the HTML for the feedback page.
450  
451 =head3 C<art>
452  
453 PGXN::Site::Controller->art($env);
454  
455 Displays the HTML for the identity page.
456  
457 =head3 C<about>
458  
459 PGXN::Site::Controller->about($env);
460  
461 Displays the HTML for the about page.
462  
463 =head3 C<donors>
464  
465 PGXN::Site::Controller->donors($env);
466  
467 Displays the HTML for the donors page.
468  
469 =head3 C<recent>
470  
471 PGXN::Site::Controller->recent($env);
472  
473 Displays the HTML for the recent releases page.
474  
475 =head3 C<mirroring>
476  
477 PGXN::Site::Controller->mirroring($env);
478  
479 Displays the HTML for the mirroring page.
480  
481 =head3 C<spec>
482  
483 PGXN::Site::Controller->spec($env, $format);
484  
485 Displays the HTML or plain text for the PGXN Meta Spec.
486  
487 =head3 C<faq>
488  
489 PGXN::Site::Controller->faq($env);
490  
491 Displays the HTML for the FAQ page.
492  
493 =head3 C<distribution>
494  
495 PGXN::Site::Controller->distribution($env);
496  
497 Displays the HTML for the distribution page.
498  
499 =head3 C<document>
500  
501 PGXN::Site::Controller->document($env);
502  
503 Displays the HTML for the document page.
504  
505 =head3 C<user>
506  
507 PGXN::Site::Controller->user($env);
508  
509 Displays the HTML for the user page.
510  
511 =head3 C<users>
512  
513 PGXN::Site::Controller->users($env);
514  
515 Displays the HTML for the users search page.
516  
517 =head3 C<tags>
518  
519 PGXN::Site::Controller->tags($env);
520  
521 Displays the HTML for the tags page, including search form and tag cloud.
522  
523 =head3 C<tag>
524  
525 PGXN::Site::Controller->tag($env);
526  
527 Displays the HTML for the tag page.
528  
529 =head3 C<extension>
530  
531 PGXN::Site::Controller->extension($env);
532  
533 Displays the HTML for the extension page.
534  
535 =head3 C<search>
536  
537 PGXN::Site::Controller->search($env);
538  
539 Displays the HTML for the search page.
540  
541 =head3 C<server_error>
542  
543 Handles subrequests from L<Plack::Middleware::ErrorDocument> when a 500 is
544 returned. Best way to set it up is to add these three middlewares to the
545 production configuration file:
546  
547 "middleware": [
548 ["ErrorDocument", 500, "/error", "subrequest", 1],
549 ["HTTPExceptions"],
550 ["StackTrace", "no_print_errors", 1]
551 ],
552  
553 =head2 Methods
554  
555 =head3 C<render>
556  
557 $controller->render('/home', $req, @template_args);
558  
559 Renders the response to the request using L<PGXN::Site::Templates>.
560  
561 =head3 C<redirect>
562  
563 $controller->render('/home', $req);
564  
565 Redirect the request to a new page.
566  
567 =head3 C<missing>
568  
569 $controller->missing($env, $data);
570  
571 Handles 404 and 405 errors from Router::Resource.
572  
573 =over
574  
575 =item C<success>
576  
577 =item C<forbidden>
578  
579 =item C<notfound>
580  
581 =back
582  
583 =head1 Author
584  
585 David E. Wheeler <david@justatheory.com>
586  
587 =head1 Copyright and License
588  
589 Copyright (c) 2010-2021 David E. Wheeler.
590  
591 This module is free software; you can redistribute it and/or modify it under
592 the L<PostgreSQL License|https://www.opensource.org/licenses/postgresql>.
593  
594 Permission to use, copy, modify, and distribute this software and its
595 documentation for any purpose, without fee, and without a written agreement is
596 hereby granted, provided that the above copyright notice and this paragraph
597 and the following two paragraphs appear in all copies.
598  
599 In no event shall David E. Wheeler be liable to any party for direct,
600 indirect, special, incidental, or consequential damages, including lost
601 profits, arising out of the use of this software and its documentation, even
602 if David E. Wheeler has been advised of the possibility of such damage.
603  
604 David E. Wheeler specifically disclaims any warranties, including, but not
605 limited to, the implied warranties of merchantability and fitness for a
606 particular purpose. The software provided hereunder is on an "as is" basis,
607 and David E. Wheeler has no obligations to provide maintenance, support,
608 updates, enhancements, or modifications.
609  
610 =cut