Refactoring, part I (Web::Simple)
[gruntmaster-page.git] / lib / Plack / App / Gruntmaster.pm
index 8c8875db4586d0c6303c2f45bee810aee1897349..3c989ac10fe533058e1b3d12bcf219d68d7ffcb3 100644 (file)
@@ -2,66 +2,57 @@ package Plack::App::Gruntmaster;
 
 use 5.014000;
 use strict;
-use warnings;
-use parent qw/Plack::Component/;
-no if $] >= 5.017011, warnings => 'experimental::smartmatch';
 our $VERSION = '5999.000_001';
 
 use Apache2::Authen::Passphrase qw/pwcheck pwset/;
 use CSS::Minifier::XS;
 use File::Slurp qw/read_file/;
-use HTTP::Negotiate qw/choose/;
 use JavaScript::Minifier::XS;
-use Plack::Request;
-use Gruntmaster::Page::Generic;
-
-my %handlers;
-
-sub call {
-       my $env = $_[1];
-       my $r = Plack::Request->new($env);
-       my @handlers = @{ $handlers{$r->method} // [] };
-       for my $handler (@handlers) {
-               my ($re, $obj) = @$handler;
-               my @args;
-               next unless @args = $r->path =~ m/^$re$/a;
-               return $obj->($env, map { $_ // '' } @args);
-       }
 
-       if ($r->method eq 'GET' || $r->method eq 'HEAD') {
-               my $article = $r->path eq '/' ? '/index' : $r->path;
-               $article = substr $article, 1;
-               $article =~ tr,/,_,;
-               my @variants = grep { !/\.title$/ } <a/$article.*>;
-               if (@variants) {
-                       my $lang = choose [ map { [$_, 1, 'text/html', undef, undef, $_, undef] } map { /\.(.+)$/ } @variants ], $r->headers;
-                       my $content = read_file "a/$article.$lang";
-                       my $title = read_file "a/$article.$lang.title";
-                       my $html = Gruntmaster::Page::Base::header($lang, $title) . $content . Gruntmaster::Page::Base::footer($lang);
-                       return [200, ['Content-Type' => 'text/html', 'Content-Language' => $lang, 'Vary' => 'Accept-Language', 'X-Forever' => 1, 'Cache-Control' => 'max-age=300'], [$html] ]
-               }
-       }
+use HTML::Template::Compiled;
+use PerlX::Maybe;
+use Scope::Upper qw/unwind SUB UP/;
+
+use Gruntmaster::Data;
+use Web::Simple;
+no warnings FATAL => 'all';
+use warnings;
+no warnings::illegalproto;
+no if $] >= 5.017011, warnings => 'experimental::smartmatch';
 
-       [404, ['Content-Type' => 'text/plain'], ['Not found']]
+##################################################
+
+sub read_templates {
+       my $name = shift;
+
+       my %tmpl = map { m/\.(.+)$/; $1 => scalar read_file $_ } <tmpl/$name.*>;
+       my %arti = map { m/\.(.+)$/; $1 => scalar read_file $_ } <a/$name.*>;
+       return %tmpl ? %tmpl : %arti
 }
 
-sub get  { push @{$handlers{GET }}, [ @_ ] }
-sub post { push @{$handlers{POST}}, [ @_ ] }
-sub db   { $_[0]->{'gruntmaster.dbic'} }
-sub reply { [200, ['Content-Type' => 'text/plain', 'Cache-Control' => 'no-cache'], [ @_ ] ] }
-sub admin { 0 }
-
-sub old_handler {
-       my ($pkg) = @_;
-       $pkg = "Gruntmaster::Page::$pkg";
-       eval "require $pkg" or die $@;
-       sub {
-               my ($env, @args) = @_;
-               my $format = choose $pkg->variants, Plack::Request->new($env)->headers;
-               $pkg->generate($format, $env, @args)
+my %header_templates = read_templates 'header';
+my %footer_templates = read_templates 'footer';
+my %templates;
+
+sub render {
+       my ($tmpl, $title, %params) = @_;
+       unless ($templates{$tmpl}) {
+               $templates{$tmpl} = { read_templates $tmpl };
+               for my $lang (keys $templates{$tmpl}) {
+                       my $header = $header_templates{$lang} =~ s/TITLE_GOES_HERE/$title/rg;
+                       $templates{$tmpl}{$lang} = $header . $templates{$tmpl}{$lang};
+               }
+               $templates{$tmpl}{$_} .= $footer_templates{$_} for keys $templates{$tmpl};
+
        }
+
+       my $htc = HTML::Template::Compiled->new(scalarref => \$templates{$tmpl}{en}, default_escape => 'HTML', use_perl => 1);
+       $htc->param(%params);
+       [200, ['Content-Type' => 'text/html'], [$htc->output]]
 }
 
+use constant USER_REGEX => qr/^\w{2,20}$/a;
+
 use constant CONTENT_TYPES => +{
        c => 'text/x-csrc',
        cpp => 'text/x-c++src',
@@ -71,156 +62,180 @@ use constant CONTENT_TYPES => +{
        pl => 'text/x-perl',
        py => 'text/x-python',
 };
+
+use constant FORMAT_EXTENSION => {
+       C => 'c',
+       CPP => 'cpp',
+       MONO => 'cs',
+       JAVA => 'java',
+       PASCAL => 'pas',
+       PERL => 'pl',
+       PYTHON => 'py',
+};
+
 use constant NOT_FOUND => [404, ['Content-Type' => 'text/plain'], ['Not found']];
-use constant FORBIDDEN => [403, ['Content-Type' => 'text/plain'], ['Forbidden']];
-
-BEGIN{
-       my $word   = qr,(\w+),a;
-       my $number = qr,(\d+),a;
-
-       get qr,/css/$word\.css, => sub {
-               my ($env, $theme) = @_;
-               return [404, ['Content-Type' => 'text/plain'], [ 'Not found' ]] unless -e "css/themes/$theme.css";
-               my $css = read_file "css/themes/$theme.css";
-               $css .= read_file $_ for <css/*.css>;
-               [200, ['Content-Type' => 'text/css', 'Cache-Control' => 'public, max-age=604800', 'X-Forever' => 1], [CSS::Minifier::XS::minify $css] ]
-       };
-
-       get qr,/js\.js, => sub {
-               my $js;
-               $js .= read_file $_ for <js/*.js>;
-               [200, ['Content-Type' => 'application/javascript', 'Cache-Control' => 'public, max-age=604800', 'X-Forever' => 1], [JavaScript::Minifier::XS::minify $js] ]
-       };
-
-       get qr,/log/src/$number\.$word, => sub {
-               my ($env, $job, $ext) = @_;
-               $job = db($env)->job($job);
-               return NOT_FOUND if $job->contest;
-               return FORBIDDEN if !admin && ($job->private || $job->problem->private);
-               [200, ['Content-Type' => CONTENT_TYPES->{$ext}, 'Cache-Control' => 'max-age=604800', 'X-Forever' => 1], [$job->source] ]
-       };
-
-       get qr,/ct/$word/log/src/$number\.$word, => sub {
-               my ($env, $ct, $job, $ext) = @_;
-               $job = db($env)->job($job);
-               $ct = db($env)->contest($ct);
-               return NOT_FOUND if $job->contest->id ne $ct->id;
-               return FORBIDDEN if !admin && ($job->private || !$ct->is_finished);
-               [200, ['Content-Type' => CONTENT_TYPES->{$ext}, 'Cache-Control' => 'max-age=604800', 'X-Forever' => 1], [$job->source] ]
-       };
-
-       get qr,/ct/$word/log/st, => sub {
-               my($env, $ct) = @_;
-               $env->{'gruntmaster.contest'} = $ct;
-               old_handler('St')->($env);
-       };
-
-       get qr,/us/, => old_handler 'Us';
-       get qr,/us/$word, => old_handler 'Us::Entry';
-
-       get qr,/pb/, => old_handler 'Pb';
-
-       get qr,/us/$word/pb/, => sub {
-               my ($env, $us) = @_;
-               $env->{'gruntmaster.user'} = $us;
-               old_handler('Pb')->($env);
-       };
-
-       get qr,/ct/$word/pb/, => sub {
-               my ($env, $ct) = @_;
-               return FORBIDDEN if !admin && db($env)->contest($ct)->is_pending;
-               $env->{'gruntmaster.contest'} = $ct;
-               old_handler('Pb')->($env);
-       };
-
-       get qr,/pb/$word, => sub {
-               my ($env, $pb) = @_;
-               return NOT_FOUND if !db($env)->problem($pb)->is_in_archive;
-               return FORBIDDEN if !admin && db($env)->problem($pb)->private;
-               old_handler('Pb::Entry')->(@_);
-       };
-
-       get qr,/ct/$word/pb/$word, => sub{
-               my ($env, $ct, $pb) = @_;
-               return NOT_FOUND if !db($env)->contest_problems->find($ct, $pb);
-               return FORBIDDEN if !admin && db($env)->contest($ct)->is_pending;
-               $env->{'gruntmaster.contest'} = $ct;
-               old_handler('Pb::Entry')->($env, $pb);
-       };
-
-       post qr,/pb/$word/submit, => sub {
-               my ($env, $pb) = @_;
-               return NOT_FOUND if !db($env)->problem($pb)->is_in_archive;
-               old_handler('Submit')->($env, $pb);
-       };
-
-       post qr,/ct/$word/pb/$word/submit, => sub {
-               my ($env, $ct, $pb) = @_;
-               return NOT_FOUND if !db($env)->contest_problems->find($ct, $pb);
-               return FORBIDDEN if !admin && db($env)->contest($ct)->is_pending;
-               $env->{'gruntmaster.contest'} = $ct;
-               old_handler('Submit')->($env, $pb);
-       };
-
-       get qr,/log/(?:page-$number)?, => sub {
-               my ($env, $page) = @_;
-               $env->{'gruntmaster.page'} = $page || -1;
-               old_handler('Log')->($env)
-       };
-
-       get qr,/ct/$word/log/(?:page-$number)?, => sub {
-               my ($env, $ct, $page) = @_;
-               return FORBIDDEN if !admin && db($env)->contest($ct)->is_pending;
-               $env->{'gruntmaster.contest'} = $ct;
-               $env->{'gruntmaster.page'} = $page || -1;
-               old_handler('Log')->($env)
-       };
-
-       get qr,/pb/$word/log/(?:page-$number)?, => sub {
-               my ($env, $pb, $page) = @_;
-               #return FORBIDDEN if !admin && db($pb)-> TODO
-               $env->{'gruntmaster.problem'} = $pb;
-               $env->{'gruntmaster.page'} = $page || -1;
-               old_handler('Log')->($env)
-       };
-
-       get qr,/us/$word/log/(?:page-$number)?, => sub {
-               my ($env, $us, $page) = @_;
-               $env->{'gruntmaster.user'} = $us;
-               $env->{'gruntmaster.page'} = $page || -1;
-               old_handler('Log')->($env);
-       };
-
-       get qr,/log/$number, => sub{
-               my ($env, $job) = @_;
-               my $j = db($env)->job($job);
-               return FORBIDDEN if !admin && ($j->private || $j->problem->private || ($j->contest && !$j->contest->is_finished));
-               old_handler('Log::Entry')->($env, $job);
-       };
-
-       get qr,/ct/, => old_handler 'Ct';
-
-       get qr,/ct/$word, => sub {
-               my ($env, $ct) = @_;
-               return FORBIDDEN if !admin && db($env)->contest($ct)->is_pending;
-               old_handler('Ct::Entry')->($env, $ct);
-       };
-
-       post qr,/action/passwd, => sub {
-               my ($env) = @_;
-               my $r = Plack::Request->new($env);
-               my ($oldpass, $newpass, $confirm) = map {scalar $r->param($_)} 'password', 'new_password', 'confirm_new_password';
-
-               return reply 'Incorrect password' unless eval { pwcheck $r->user, $oldpass; 1 };
-               return reply 'The two passwords do not match' unless $newpass eq $confirm;
-
-               pwset $r->user, $newpass;
-               reply 'Password changed successfully';
-       };
-
-       post qr,/action/register, => old_handler 'Register';
+use constant FORBIDDEN => [401, ['Content-Type' => 'text/plain', 'WWW-Authenticate' => ' Basic realm="Gruntmaster 6000"'], ['Forbidden']];
+
+my $env;
+
+sub db { $env->{'gruntmaster.dbic'} }
+
+sub remote_user {
+       my $user = $env->{'gruntmaster.user'};
+       $user &&= db->user($user);
+       $user
+}
+
+sub admin   { remote_user && remote_user->isadmin }
+sub contest { db->contest ($_{contest}) }
+sub problem { db->problem ($_{problem}) }
+sub job     { db->job     ($_{job})     }
+sub user    { db->user    ($_{user})    }
+
+sub redirect { [301, ['X-Forever' => 1, 'Location' => $_[0]], []] }
+sub reply    { [200, ['Content-Type' => 'text/plain'], \@_] }
+sub response {
+       my ($template, $title, $params) = @_;
+       unless ($params) {
+               $params = $title;
+               $title = 'No title';
+       }
+       bless {template => $template, title => $title, params => $params}, __PACKAGE__.'::Response'
+}
+sub forbid   {
+       return if !shift || admin;
+       unwind FORBIDDEN, SUB UP
+}
 
+sub dispatch_request{
+       $env = $_[PSGI_ENV];
+       sub (GET) {
+               sub (/css/:theme) {
+                       my $theme = $_{theme};
+                       return NOT_FOUND unless -e "css/themes/$theme.css";
+                       my $css = read_file "css/themes/$theme.css";
+                       $css .= read_file $_ for <css/*.css>;
+                       my @headers = ('X-Forever' => 1, 'Cache-Control' => 'public, max-age=604800', 'Content-Type' => 'text/css');
+                       [200, \@headers, [CSS::Minifier::XS::minify $css]]
+               },
+
+               sub (/js.js) {
+                       my $js;
+                       $js .= read_file $_ for <js/*.js>;
+                       my @headers = ('X-Forever' => 1, 'Cache-Control' => 'public, max-age=604800', 'Content-Type' => 'application/javascript');
+                       [200, \@headers, [JavaScript::Minifier::XS::minify $js]]
+               },
+
+               sub (/src/:job) {
+                       return NOT_FOUND if !job;
+                       forbid job->private || job->problem->private || job->contest && job->contest->private;
+                       my @headers = ('X-Forever' => 1, 'Cache-Control' => 'public, max-age=604800', 'Content-Type' => CONTENT_TYPES->{job->format});
+                       [200, \@headers, [job->source]]
+               },
+
+               sub (?:contest=) {
+                       return NOT_FOUND if !contest;
+                       forbid contest->is_pending;
+                       response_filter { return shift }
+               },
+
+               sub (?:problem=) {
+                       return NOT_FOUND if !problem;
+                       forbid problem->is_private;
+                       response_filter { return shift }
+               },
+
+               sub () {
+                       response_filter {
+                               my ($r) = @_;
+                               return $r if ref $r ne 'Plack::App::Gruntmaster::Response';
+                               return [200, ['Content-Type' => 'application/json', 'X-Forever' => 1], [encode_json $r->{params}]] if $env->{HTTP_ACCEPT} =~ m,^\s*application/json\s*$,g;
+                               render $r->{template}, $r->{title}, %{$r->{params}}
+                       },
+               },
+
+               sub (/st/) {
+                       response st => 'Standings', { st => [db->standings] }
+               },
+
+               sub (/st/:contest) {
+                       response st => 'Standings', {
+                               st => [ db->standings($_{contest}) ],
+                               problems => [map { $_->problem } contest->contest_problems]
+                       }
+               },
+
+               sub (/ct/:contest/log/st) { redirect "/st/$_{contest}" },
+
+               sub (/us/)                                        { response us => 'Users', {us => db->user_list} },
+               sub (/ct/  + ?:owner~)                            { response ct => 'Contests', db->contest_list(%_) },
+               sub (/log/ + ?:contest~&:owner~&:page~&:problem~) { response log => 'Job list', {log => db->job_list(%_)} },
+               sub (/pb/  + ?:owner~&:contest~)                  { response pb => 'Problems', db->problem_list(%_) },
+
+               sub (/us/:user)    { response us_entry => user->name, db->user_entry($_{user}) },
+               sub (/ct/:contest) { response ct_entry => contest->name, db->contest_entry($_{contest}) },
+               sub (/log/:job)    { response log_entry => "Job  $_{job}", db->job_entry($_{job}) },
+               sub (/pb/:problem + ?:contest~) {
+                       return NOT_FOUND if !contest && !problem->is_in_archive || contest && !db->contest_problems->find($_{contest}, $_{problem});
+                       forbid problem->is_private;
+                       response pb_entry => problem->name, db->problem_entry($_{problem}, $_{contest}, remote_user && remote_user->id);
+               },
+
+               sub (/) { redispatch_to '/index' },
+
+               sub (/:article) {
+                       my $title = read_file "a/$_{article}.en.title";
+                       response $_{article} => $title, {};
+               }
+       },
+
+       sub (POST) {
+               sub (/action/register + %:username=&:password=&:confirm_password=&:name=&:email=&:phone=&:town=&:university=&:level=) {
+                       return reply 'Parameter too long' if grep { length > 200 } values %_;
+                       return reply 'Bad username. Allowed characters are letters, digits and underscores, and the username must be between 2 and 20 characters long.' unless $_{username} =~ USER_REGEX;
+                       return reply 'Username already in use' if db->user($_{username});
+                       return reply 'The two passwords do not match' unless $_{password} eq $_{confirm_password};
+
+                       db->users->create({id => $_{username}, name => $_{name}, email => $_{email}, phone => $_{phone}, town => $_{town}, university => $_{university}, level => $_{level}});
+                       db->user($_{username})->set_passphrase($_{password});
+
+                       reply 'Registered successfully';
+               },
+
+               sub (/action/passwd + %:password=&:new_password=&:confirm_new_password=) {
+                       forbid !remote_user;
+                       return reply 'Incorrect password' unless remote_user->check_passphrase($_{password});
+                       return reply 'The two passwords do not match' unless $_{new_password} eq $_{confirm_new_password};
+                       remote_user->set_passphrase($_{new_password});
+                       reply 'Password changed successfully';
+               },
+
+               sub (/action/submit + %:problem=&:contest~&prog_format=&private~ + *source_code=) {
+                       forbid !remote_user;
+                       return reply 'This contest has finished' if contest->is_finished;
+                       return reply 'This contest has not yet started' if !admin && contest->is_pending;
+                       return reply 'Maximum source size is 10KB' if $_{source_code}->size > 25 * 1024;
+                       return reply 'You must wait 30 seconds between jobs' if !admin && time <= remote_user->lastjob + 30;
+                       remote_user->update({lastjob => time});
+
+                       my $prog = read_file $_{source_code}->path;
+                       unlink $_{source_code}->path;
+                       db->jobs->create({
+                               maybe contest => $_{contest},
+                               maybe private => $_{private},
+                               date => time,
+                               extension => FORMAT_EXTENSION->{$_{prog_format}},
+                               format => $_{prog_format},
+                               problem => $_{problem},
+                               source => $prog,
+                               owner => remote_user->id,
+                       });
+
+                       redirect $_{contest} ? "/log/?contest=$_{contest}" : '/log/';
+               }
+       }
 }
 
+
 1;
 __END__
This page took 0.019421 seconds and 4 git commands to generate.