root/lang/perl/mobirc/trunk/lib/App/Mobirc/Web/Handler.pm @ 18451

Revision 18451, 2.2 kB (checked in by tokuhirom, 6 years ago)

make immutable

Line 
1package App::Mobirc::Web::Handler;
2use Moose;
3use Scalar::Util qw/blessed/;
4use Data::Visitor::Encode;
5use HTTP::MobileAgent;
6use HTTP::MobileAgent::Plugin::Charset;
7use Module::Find;
8
9use App::Mobirc;
10use App::Mobirc::Util;
11use App::Mobirc::Web::Router;
12useall 'App::Mobirc::Web::C';
13
14my $dve = Data::Visitor::Encode->new;
15
16sub context () { App::Mobirc->context } ## no critic
17
18sub handler {
19    my $req = shift;
20
21    my $res = _handler($req);
22    context->run_hook('response_filter', $res);
23    $res;
24}
25
26sub _handler {
27    my $req = shift;
28
29    context->run_hook('request_filter', $req);
30
31    if (authorize($req)) {
32        return process_request($req);
33    } else {
34        HTTP::Engine::Response->new(
35            status => 401,
36            headers => HTTP::Headers->new(
37                'WWW-Authenticate' => qq{Basic Realm="mobirc"}
38            ),
39        );
40    }
41}
42
43sub authorize {
44    my $req = shift;
45
46    if (context->run_hook_first('authorize', $req)) {
47        DEBUG "AUTHORIZATION SUCCEEDED";
48        return 1; # authorization succeeded.
49    } else {
50        return 0; # authorization failed
51    }
52}
53
54sub process_request {
55    my ($req, ) = @_;
56
57    my $rule = App::Mobirc::Web::Router->match($req);
58
59    unless ($rule) {
60        # hook by plugins
61        if (my $res = context->run_hook_first( 'httpd', $req )) {
62            # XXX we should use html filter?
63            return $res;
64        }
65
66        # doesn't match.
67        do {
68            my $uri = $req->uri->path;
69            warn "dan the 404 not found: $uri" if $uri ne '/favicon.ico';
70
71            return HTTP::Engine::Response->new(
72                status => 404,
73                body   => "404 not found: $uri",
74            );
75        };
76    }
77
78    my $controller = "App::Mobirc::Web::C::$rule->{controller}";
79
80    my $meth = $rule->{action};
81    my $post_meth = "post_dispatch_$meth";
82    my $get_meth  = "dispatch_$meth";
83    my $args = $dve->decode( $req->mobile_agent->encoding, $rule->{args} );
84    if ( $req->method =~ /POST/i && $controller->can($post_meth)) {
85        return $controller->$post_meth($req, $args);
86    } else {
87        return $controller->$get_meth($req, $args);
88    }
89}
90
91no Moose;__PACKAGE__->meta->make_immutable;
921;
93
Note: See TracBrowser for help on using the browser.