4 use Data::Dump qw(dump);
9 our $VERSION = `git describe`;
12 sub new_uuid { Time::HiRes::time * 100000 }
14 #push @{app->static->paths}, 'app'; # default angular-seed app directory
17 my $couchdb = $ENV{COUCHDB} || 'http://localhost:5984';
18 my $couchdb_database = 'drzb2013v2';
19 my $couchdb_view = "http://10.60.0.92:5984/_utils/document.html?$couchdb_database";
20 my $client = Mojo::UserAgent->new;
23 my ( $url, $data ) = @_;
25 $data->{'$entity'} = $1 if $url =~ m{/(\w+)\.\d+/$/};
27 my $json = Mojo::JSON->new->encode( $data );
31 warn "# _couchdb_put $url = $json";
32 return $client->put( "$couchdb/$url" => $json)->res->json;
37 my $return = $client->get( "$couchdb/$url" )->res->json;
38 # warn "# _couchdb_get $url = ",dump($return);
47 my ( $self, $json ) = @_;
48 #warn "## _render_json ",dump($json);
49 my $data = $self->render( json => $json, partial => 1 );
50 #warn "## _render_json $data";
51 if ( my $callback = $self->param('callback') ) {
52 $data = "$callback($data)";
54 $self->render( data => $data, format => 'js' );
59 $self->render_text("...");
64 helper locale => sub {
67 my $lang = $self->stash('lang');
69 return $locale{ $lang } || "MISSING $lang $_[1]";
75 $self->req->headers->header('X-Forwarded-For')
76 || $self->req->headers->header('X-Real-IP')
77 || $self->tx->{remote_address}
82 get '/js/services.js' => sub {
84 $self->stash( VERSION => $VERSION );
85 $self->stash( couchdb_database => $couchdb_database );
86 $self->render( 'js/services', format => 'js' );
90 get '/hr' => sub { shift->redirect_to('/lang/hr/drzb2013') };
91 get '/en' => sub { shift->redirect_to('/lang/en/drzb2013') };
93 get '/lang/:lang/:template' => sub {
95 $self->render( $self->stash('template') , lang => $self->stash('lang') );
98 get '/lang/:lang/partials/:template' => sub {
100 $self->stash( couchdb_view => $couchdb_view );
101 $self->render( 'partials/' . $self->stash('template') , lang => $self->stash('lang') );
104 get '/lang/:lang/.template' => sub {
106 $self->render( $self->stash('template') , lang => $self->stash('lang') );
109 get '/lang/:lang/template/*template' => sub { # angular-ui templates
111 my $path = '/template/' . $self->stash('template');
112 warn "# render_static $path";
113 $self->render_static( $path );
116 get '/data/' => sub {
118 _render_jsonp( $self, _couchdb_get('/_all_dbs') );
121 get '/data/:database' => sub {
123 my $database = $self->param('database');
125 my $list_databases = { name => $database };
127 my $counts = _couchdb_get("/$database/_design/entity/_view/counts?group=true");
128 if ( exists $counts->{error} ) {
129 warn "creating CouchDB view because of ", dump($counts);
130 _couchdb_put "/$database/_design/entity", {
131 _id => '_design/entity',
132 language => 'javascript',
135 map => q| function(doc) { emit(doc._id.split('.')[0],1); } |,
136 reduce => q| function(keys,values,rereduce) { return sum(values); } |,
140 $counts = _couchdb_get("/$database/_design/entity/_view/counts?group=true")
144 warn "# counts ",dump($counts);
146 foreach my $row ( @{ $counts->{rows} } ) {
147 my $n = $row->{value};
148 $list_databases->{entities}->{ $row->{key} } = $n;
149 $list_databases->{document_counts} += $n;
151 warn dump($list_databases);
152 _render_jsonp( $self, $list_databases );
155 get '/data/:database/:entity' => sub {
158 my $database = $self->param('database');
159 my $entity = $self->param('entity');
161 my $endkey = $entity;
164 my $counts = _couchdb_get qq|/$database/_all_docs?startkey="$entity";endkey="$endkey";include_docs=true|;
165 # warn "# counts ",dump($counts);
167 _render_jsonp( $self, [ map { $_->{doc} } @{ $counts->{rows} } ] )
170 get '/data/:database/:entity/:id' => sub {
173 my $database = $self->param('database');
174 my $entity = $self->param('entity');
175 my $id = $self->param('id');
177 _render_jsonp( $self, _couchdb_get( "/$database/$entity.$id" ) );
180 any [ 'post' ] => '/data/:database/:entity' => sub {
182 my $database = $self->param('database');
183 my $entity = $self->param('entity');
184 my $json = $self->req->json;
186 if ( exists $json->{'id'} ) { # @id in resource
188 warn "EXISTING $id\n";
190 $id = $json->{'id'} = new_uuid;
191 $json->{entity} = $entity;
196 t => Time::HiRes::time,
200 warn "## $database $entity $id body ",dump($self->req->body, $json);
202 my $new = _couchdb_put "/$database/$entity.$id" => $json;
203 warn "new: ",dump($new);
205 $json->{'_'.$_} = $new->{$_} foreach ( 'rev','id' );
207 warn "ERROR: ",dump($new);
208 $json->{error} = $new;
211 _render_jsonp( $self, $json );
215 #get '/' => sub { shift->redirect_to('/app/') };
217 # CouchDB proxy for _design _view
221 get '/:database/_design/:design/_view/:view' => sub {
223 my $format = $self->param('format');
224 my $url = join('/', $self->param('database'),'_design',$self->param('design'),'_view',$self->param('view') );
225 if ( my $param = $self->req->url->query->clone->remove('callback')->remove('format')->to_string ) {
229 if ( exists $view_cache->{$url}->{time} ) {
230 if ( time() - $view_cache->{$url}->{time} < 60 ) {
231 warn "HIT CouchDB cache $url";
232 $view_cache->{$url}->{hit}++;
233 return _render_jsonp( $self, $view_cache->{$url}->{json} );
235 warn "REFRESH CouchDB cache $url";
236 $view_cache->{$url}->{refresh}++;
239 $view_cache->{$url}->{miss}++;
241 warn "CouchDB proxy $url";
242 my $json = _couchdb_get($url);
244 if ( exists $json->{error} ) {
245 warn "creating CouchDB view because of ", dump($json);
246 my $url = "/" . $self->param('database') . "/_design/registration";
248 _id => '_design/registration',
249 language => 'javascript',
252 map => q| function(doc) {
253 if ( doc.user.organization != '' ) {
254 if ( doc.user.organization )
255 emit(doc.user.organization, 1);
256 if ( doc.work.persons ) {
257 doc.work.persons.forEach( function(person) {
258 if ( person.organization )
259 emit(person.organization, 1);
264 reduce => q| function(keys,values,rereduce) { return sum(values); } |,
269 if ( doc.work.persons ) {
270 doc.work.persons.forEach( function(person) {
271 emit(person.surname+person.firstname ,
276 if ( doc.work.symposium_works ) {
277 doc.work.symposium_works.forEach( function(work) {
278 work.persons.forEach( function(person) {
279 emit(person.surname+person.firstname ,
290 $json = _couchdb_get($url)
294 if ( $format eq 'key_array' ) { # array of keys sorted by value
295 $json->{rows} = [ map { $_->{key} } sort { $b->{value} <=> $a->{value} } @{ $json->{rows} } ];
296 } elsif ( $format eq 'key_distinct' ) {
299 $json->{rows} = [ grep { $found->{ $_->{key} }++ == 1 } @{ $json->{rows} } ];
300 $json->{distinct_rows} = scalar @{ $json->{rows} };
301 warn "## distinct stats ", dump( $found );
303 } elsif ( $format ) {
305 die "unknown format: $format";
309 $view_cache->{$url}->{time} = time();
310 $view_cache->{$url}->{json} = $json;
312 warn "# view_cache ",dump($view_cache);
314 _render_jsonp( $self, $json );
317 # http://showmetheco.de/articles/2010/10/adding-etag-caching-to-your-mojolicious-app.html
319 hook after_dispatch => sub {
322 return unless $self->req->method eq 'GET';
324 my $body = $self->res->body;
325 return unless defined $body;
327 return if $self->res->headers->header('ETag');
329 my $our_etag = Mojo::ByteStream->new($body . $VERSION)->md5_sum;
330 $self->res->headers->header('ETag' => $our_etag);
332 my $browser_etag = $self->req->headers->header('If-None-Match');
333 return unless $browser_etag && $browser_etag eq $our_etag;
335 $self->app->log->debug("HTTP cache hit " . $self->req->url->to_string . " $our_etag" );
337 $self->res->code(304);
338 $self->res->body('');