1 package stemmaweb::Controller::Stemweb;
3 use namespace::autoclean;
4 use Encode qw/ decode_utf8 /;
8 use Scalar::Util qw/ looks_like_number /;
12 BEGIN { extends 'Catalyst::Controller' }
17 default => 'http://slinkola.users.cs.helsinki.fi',
22 stemmaweb::Controller::Stemweb - Client listener for Stemweb results
26 This is a client listener for the Stemweb API as implemented by the protocol defined at
27 L<https://docs.google.com/document/d/1aNYGAo1v1WPDZi6LXZ30FJSMJwF8RQPYbOkKqHdCZEc/pub>.
34 Content-Type: application/json
43 result: <error message> }
45 Used by the Stemweb server to notify us that one or more stemma graphs
46 has been calculated in response to an earlier request.
50 sub result :Local :Args(0) {
52 if( $c->request->method eq 'POST' ) {
53 # TODO: Verify the sender!
55 if( ref( $c->request->body ) eq 'File::Temp' ) {
56 # Read in the file and parse that.
57 $c->log->debug( "Request body is in a temp file" );
58 open( POSTDATA, $c->request->body )
59 or return _json_error( $c, 500, "Failed to open post data file" );
60 binmode( POSTDATA, ':utf8' );
61 # JSON should be all one line
62 my $pdata = <POSTDATA>;
66 $answer = from_json( $pdata );
68 return _json_error( $c, 400,
69 "Could not parse POST request '' $pdata '' as JSON: $@" );
72 $answer = from_json( $c->request->body );
74 $c->log->debug( "Received push notification from Stemweb: "
75 . to_json( $answer ) );
76 return _process_stemweb_result( $c, $answer );
78 return _json_error( $c, 403, 'Please use POST!' );
84 GET algorithms/available
86 Queries the Stemweb server for available stemma generation algorithms and their
87 parameters. Returns the JSON answer as obtained from Stemweb.
91 sub available :Local :Args(0) {
93 my $ua = LWP::UserAgent->new();
94 my $resp = $ua->get( $self->stemweb_url . '/algorithms/available' );
95 if( $resp->is_success ) {
96 $c->stash->{'result'} = decode_json( $resp->content );
98 $c->stash->{'result'} = {};
100 $c->forward('View::JSON');
105 GET stemweb/query/<jobid>
107 A backup method to query the stemweb server to check a particular job status.
108 Returns a result as in /stemweb/result above, but status can also be -1 to
109 indicate that the job is still running.
113 sub query :Local :Args(1) {
114 my( $self, $c, $jobid ) = @_;
115 my $ua = LWP::UserAgent->new();
116 my $resp = $ua->get( $self->stemweb_url . "/algorithms/jobstatus/$jobid" );
117 if( $resp->is_success ) {
119 my $response = decode_utf8( $resp->content );
120 $c->log->debug( "Got a response from the server: $response" );
123 $answer = from_json( $response );
125 return _json_error( $c, 500,
126 "Could not parse stemweb response '' $response '' as JSON: $@" );
128 return _process_stemweb_result( $c, $answer );
129 } elsif( $resp->code == 500 && $resp->header('Client-Warning')
130 && $resp->header('Client-Warning') eq 'Internal response' ) {
131 # The server was unavailable.
132 return _json_error( $c, 503, "The Stemweb server is currently unreachable." );
134 return _json_error( $c, 500, "Stemweb error: " . $resp->code . " / "
140 ## Helper function for parsing Stemweb result data either by push or by pull
141 sub _process_stemweb_result {
142 my( $c, $answer ) = @_;
143 # Find the specified tradition and check its job ID.
144 my $m = $c->model('Directory');
145 my $tradition = $m->tradition( $answer->{textid} );
146 unless( $tradition ) {
147 return _json_error( $c, 400, "No tradition found with ID "
148 . $answer->{textid} );
150 if( $answer->{status} == 0 ) {
152 if( $tradition->has_stemweb_jobid
153 && $tradition->stemweb_jobid eq $answer->{jobid} ) {
155 $stemmata = $tradition->record_stemweb_result( $answer );
156 $m->save( $tradition );
157 } catch( Text::Tradition::Error $e ) {
158 return _json_error( $c, 500, $e->message );
160 return _json_error( $c, 500, $@ );
163 # It may be that we already received a callback meanwhile.
164 # Check all stemmata for the given jobid and return them.
165 @$stemmata = grep { $_->came_from_jobid && $_->from_jobid eq $answer->{jobid} } $tradition->stemmata;
168 # If we got here, success!
169 # TODO Use helper in Root.pm to do this
170 my @steminfo = map { {
171 name => $_->identifier,
172 directed => _json_bool( !$_->is_undirected ),
173 svg => $_->as_svg() } }
175 $c->stash->{'result'} = {
176 'status' => 'success',
177 'stemmata' => \@steminfo };
179 # Hm, no stemmata found on this tradition with this jobid.
180 # Clear the tradition jobid so that the user can try again.
181 if( $tradition->has_stemweb_jobid ) {
182 $tradition->_clear_stemweb_jobid;
183 $m->save( $tradition );
185 $c->stash->{'result'} = { status => 'notfound' };
187 } elsif( $answer->{status} == -1 ) {
188 $c->stash->{'result'} = { 'status' => 'running' };
190 return _json_error( $c, 500,
191 "Stemweb failure not handled: " . $answer->{result} );
193 $c->forward('View::JSON');
198 GET stemweb/request/?
199 tradition=<tradition ID> &
200 algorithm=<algorithm ID> &
201 [<algorithm parameters>]
203 Send a request for the given tradition with the given parameters to Stemweb.
204 Processes and returns the JSON response given by the Stemweb server.
208 sub request :Local :Args(0) {
209 my( $self, $c ) = @_;
210 # Look up the relevant tradition and check permissions.
211 my $reqparams = $c->req->params;
212 my $tid = delete $reqparams->{tradition};
213 my $t = $c->model('Directory')->tradition( $tid );
214 my $ok = _check_permission( $c, $t );
216 return( _json_error( $c, 403,
217 'You do not have permission to update stemmata for this tradition' ) )
218 unless $ok eq 'full';
220 # Form the request for Stemweb.
221 my $algorithm = delete $reqparams->{algorithm};
222 my $return_uri = URI->new( $c->uri_for( '/stemweb/result' ) );
223 my $stemweb_request = {
224 return_path => $return_uri->path,
225 return_host => $return_uri->host_port,
226 data => $t->collation->as_tsv({noac => 1}),
227 userid => $c->user->get_object->email,
229 parameters => _cast_nonstrings( $reqparams ) };
231 # Call to the appropriate URL with the request parameters.
232 my $ua = LWP::UserAgent->new();
233 $c->log->debug( 'Sending request to Stemweb: ' . to_json( $stemweb_request ) );
234 my $resp = $ua->post( $self->stemweb_url . "/algorithms/process/$algorithm/",
235 'Content-Type' => 'application/json; charset=utf-8',
236 'Content' => encode_json( $stemweb_request ) );
237 if( $resp->is_success ) {
239 $c->log->debug( 'Got a response from the server: '
240 . decode_utf8( $resp->content ) );
241 my $stemweb_response = decode_json( $resp->content );
243 $t->set_stemweb_jobid( $stemweb_response->{jobid} );
244 } catch( Text::Tradition::Error $e ) {
245 return _json_error( $c, 429, $e->message );
247 $c->model('Directory')->save( $t );
248 $c->stash->{'result'} = $stemweb_response;
249 $c->forward('View::JSON');
250 } elsif( $resp->code == 500 && $resp->header('Client-Warning')
251 && $resp->header('Client-Warning') eq 'Internal response' ) {
252 # The server was unavailable.
253 return _json_error( $c, 503, "The Stemweb server is currently unreachable." );
255 return _json_error( $c, 500, "Stemweb error: " . $resp->code . " / "
260 # Helper to check what permission, if any, the active user has for
261 # the given tradition
262 sub _check_permission {
263 my( $c, $tradition ) = @_;
264 my $user = $c->user_exists ? $c->user->get_object : undef;
266 return 'full' if ( $user->is_admin ||
267 ( $tradition->has_user && $tradition->user->id eq $user->id ) );
269 # Text doesn't belong to us, so maybe it's public?
270 return 'readonly' if $tradition->public;
272 # ...nope. Forbidden!
273 return _json_error( $c, 403, 'You do not have permission to view this tradition.' );
276 # QUICK HACK to deal with strict Stemweb validation.
277 sub _cast_nonstrings {
279 foreach my $k ( keys %$params ) {
280 my $v = $params->{$k};
281 if( looks_like_number( $v ) ) {
282 $params->{$k} = $v * 1;
283 } elsif ( !defined $v || $v eq 'true' ) {
284 $params->{$k} = _json_bool( $v );
290 # Helper to throw a JSON exception
292 my( $c, $code, $errmsg ) = @_;
293 $c->response->status( $code );
294 $c->stash->{'result'} = { 'error' => $errmsg };
295 $c->forward('View::JSON');
300 return $_[0] ? JSON::true : JSON::false;