1 |
package Frey::Mojo; |
2 |
|
3 |
use strict; |
4 |
use warnings; |
5 |
|
6 |
use base 'Mojo'; |
7 |
|
8 |
use MojoX::Dispatcher::Static; |
9 |
|
10 |
use lib 'lib'; |
11 |
use Frey::Server; |
12 |
use Frey::CouchAPI; |
13 |
|
14 |
use Data::Dump qw/dump/; |
15 |
|
16 |
__PACKAGE__->attr( |
17 |
static => ( |
18 |
chained => 1, |
19 |
default => sub { MojoX::Dispatcher::Static->new } |
20 |
) |
21 |
); |
22 |
|
23 |
sub new { |
24 |
my $self = shift->SUPER::new(); |
25 |
|
26 |
# This app should log only errors to STDERR |
27 |
$self->log->level('error'); |
28 |
$self->log->path(undef); |
29 |
|
30 |
# warn "# home ", $self->home; |
31 |
|
32 |
$self->static->root( './' ); |
33 |
|
34 |
return $self; |
35 |
} |
36 |
|
37 |
|
38 |
sub handler { |
39 |
my ($self, $tx) = @_; |
40 |
|
41 |
# XXX fake app so static dispatcher won't die on us |
42 |
{ |
43 |
package Fake::App; |
44 |
use base 'Mojo::Transaction'; |
45 |
sub app { |
46 |
my $self = shift; |
47 |
# warn "## $self app ", @_; |
48 |
$self; |
49 |
} |
50 |
sub log { |
51 |
my $self = shift; |
52 |
# warn "## $self log ",@_; |
53 |
return $self; |
54 |
} |
55 |
sub debug { |
56 |
my $self = shift; |
57 |
warn "## ",@_, $/; |
58 |
return $self; |
59 |
} |
60 |
} |
61 |
bless $tx, 'Fake::App'; |
62 |
|
63 |
# rewrite URL |
64 |
Frey::CouchAPI->rewrite_urls( $tx ); |
65 |
|
66 |
if ( ! $self->static->dispatch($tx) ) { |
67 |
# warn "# static ",dump( $tx ); |
68 |
return $tx; |
69 |
} |
70 |
|
71 |
my $body; |
72 |
|
73 |
my $server = Frey::Server->new; |
74 |
$server->{_print} = sub { |
75 |
$body .= join("\n", @_); |
76 |
}; |
77 |
|
78 |
my $url = $tx->req->url->to_string; |
79 |
my $params = $tx->req->params->to_hash; |
80 |
|
81 |
my $referer = $tx->req->content->headers->header('Referer'); |
82 |
my $ajax = $tx->req->content->headers->header('X-Requested-With'); |
83 |
warn "# referer $referer\n"; |
84 |
# warn "## headers = ", dump( $tx->req->content->headers ); |
85 |
|
86 |
if ( $referer =~ m{/_utils} || $ajax =~ m{XMLHttpRequest}i ) { |
87 |
return Frey::CouchAPI->dispatch( $tx ); |
88 |
} |
89 |
|
90 |
warn "# url $url from $referer params ",dump($params); |
91 |
|
92 |
my $request = $server->request( $url, $params ); # fetch body |
93 |
|
94 |
warn "# request ", dump( $request ); |
95 |
|
96 |
foreach ( 'content_type', 'code' ) { |
97 |
die "missing $_" unless defined $request->{$_}; |
98 |
} |
99 |
|
100 |
=for developer |
101 |
|
102 |
# compatiblity with unpatched Mojo |
103 |
sub class2rest { |
104 |
my $c = shift; |
105 |
$c =~ s/::/-/gs; |
106 |
$c; |
107 |
} |
108 |
$body =~ s{(/\w+::\w+[\w:]+)}{class2rest($1)}sge; |
109 |
|
110 |
=cut |
111 |
|
112 |
$tx->res->code( $request->{code} ); |
113 |
$tx->res->headers->content_type( $request->{content_type} ); |
114 |
$tx->res->body( $body ); |
115 |
|
116 |
warn dump( $tx->res->headers ); |
117 |
return $tx; |
118 |
} |
119 |
|
120 |
1; |