1 package stemmaweb::Controller::Stemweb;
3 use namespace::autoclean;
4 use Encode qw/ decode_utf8 /;
11 BEGIN { extends 'Catalyst::Controller' }
13 ## TODO Move the /algorithms/available function to the Stemweb module
14 my $STEMWEB_BASE_URL = 'http://slinkola.users.cs.helsinki.fi';
18 stemmaweb::Controller::Stemweb - Client listener for Stemweb results
22 This is a client listener for the Stemweb API as implemented by the protocol defined at
23 L<https://docs.google.com/document/d/1aNYGAo1v1WPDZi6LXZ30FJSMJwF8RQPYbOkKqHdCZEc/pub>.
30 Content-Type: application/json
39 result: <error message> }
41 Used by the Stemweb server to notify us that one or more stemma graphs
42 has been calculated in response to an earlier request.
46 sub result :Local :Args(0) {
48 if( $c->request->method eq 'POST' ) {
49 # TODO: Verify the sender!
51 if( ref( $c->request->body ) eq 'File::Temp' ) {
52 # Read in the file and parse that.
53 open( POSTDATA, $c->request->body ) or die "Failed to open post data file";
54 binmode( POSTDATA, ':utf8' );
55 # JSON should be all one line
56 my $pdata = <POSTDATA>;
60 $answer = from_json( $pdata );
62 return _json_error( $c, 400,
63 "Could not parse POST request '' $pdata '' as JSON: $@" );
66 $answer = from_json( $c->request->body );
68 return _process_stemweb_result( $c, $answer );
70 return _json_error( $c, 403, 'Please use POST!' );
76 GET stemweb/query/<jobid>
78 A backup method to query the stemweb server to check a particular job status.
79 Returns a result as in /stemweb/result above, but status can also be -1 to
80 indicate that the job is still running.
84 sub query :Local :Args(1) {
85 my( $self, $c, $jobid ) = @_;
86 my $ua = LWP::UserAgent->new();
87 my $resp = $ua->get( $STEMWEB_BASE_URL . "/jobstatus/$jobid" );
88 if( $resp->is_success ) {
90 my $response = decode_utf8( $resp->content );
91 $c->log->debug( "Got a response from the server: $response" );
94 $answer = from_json( $response );
96 return _json_error( $c, 500,
97 "Could not parse stemweb response '' $response '' as JSON: $@" );
99 return _process_stemweb_result( $c, $answer );
100 } elsif( $resp->code == 500 && $resp->header('Client-Warning')
101 && $resp->header('Client-Warning') eq 'Internal response' ) {
102 # The server was unavailable.
103 return _json_error( $c, 503, "The Stemweb server is currently unreachable." );
105 return _json_error( $c, 500, "Stemweb error: " . $resp->code . " / "
111 ## Helper function for parsing Stemweb result data either by push or by pull
112 sub _process_stemweb_result {
113 my( $c, $answer ) = @_;
114 # Find a tradition with the defined Stemweb job ID.
115 # TODO: Maybe get Stemweb to pass back the tradition ID...
116 my $m = $c->model('Directory');
118 $m->scan( sub{ push( @traditions, $_[0] )
119 if $_[0]->$_isa('Text::Tradition')
120 && $_[0]->has_stemweb_jobid
121 && $_[0]->stemweb_jobid eq $answer->{job_id};
123 if( @traditions == 1 ) {
124 my $tradition = shift @traditions;
125 if( $answer->{status} == 0 ) {
128 $stemmata = $tradition->record_stemweb_result( $answer );
129 $m->save( $tradition );
130 } catch( Text::Tradition::Error $e ) {
131 return _json_error( $c, 500, $e->message );
133 return _json_error( $c, 500, $@ );
135 # If we got here, success!
136 my @steminfo = map { {
137 name => $_->identifier,
138 directed => _json_bool( !$_->is_undirected ),
139 svg => $_->as_svg() } }
141 $c->stash->{'result'} = {
142 'status' => 'success',
143 'stemmata' => \@steminfo };
144 } elsif( $answer->{status} < 1 ) {
145 $c->stash->{'result'} = { 'status' => 'running' };
147 return _json_error( $c, 500,
148 "Stemweb failure not handled: " . $answer->{result} );
150 } elsif( @traditions ) {
151 return _json_error( $c, 500,
152 "Multiple traditions with Stemweb job ID " . $answer->{job_id} . "!" );
154 # Possible that the tradition got updated in the meantime...
155 if( $answer->{status} == 0 ) {
156 $c->stash->{'result'} = { 'status' => 'notfound' };
158 return _json_error( $c, 400,
159 "No tradition found with Stemweb job ID " . $answer->{job_id} );
162 $c->forward('View::JSON');
167 GET stemweb/request/?
168 tradition=<tradition ID> &
169 algorithm=<algorithm ID> &
170 [<algorithm parameters>]
172 Send a request for the given tradition with the given parameters to Stemweb.
173 Processes and returns the JSON response given by the Stemweb server.
177 sub request :Local :Args(0) {
178 my( $self, $c ) = @_;
179 # Look up the relevant tradition and check permissions.
180 my $reqparams = $c->req->params;
181 my $tid = delete $reqparams->{tradition};
182 my $t = $c->model('Directory')->tradition( $tid );
183 my $ok = _check_permission( $c, $t );
185 return( _json_error( $c, 403,
186 'You do not have permission to update stemmata for this tradition' ) )
187 unless $ok eq 'full';
189 # Form the request for Stemweb.
190 my $algorithm = delete $reqparams->{algorithm};
191 my $return_uri = URI->new( $c->uri_for( '/stemweb/result' ) );
192 my $stemweb_request = {
193 return_path => $return_uri->path,
194 return_host => $return_uri->host_port,
195 data => $t->collation->as_tsv,
196 userid => $c->user->get_object->email,
197 parameters => $reqparams };
199 # Call to the appropriate URL with the request parameters.
200 my $ua = LWP::UserAgent->new();
201 $c->log->debug( 'Sending request to Stemweb: ' . to_json( $stemweb_request ) );
202 my $resp = $ua->post( $STEMWEB_BASE_URL . "/algorithms/process/$algorithm/",
203 'Content-Type' => 'application/json; charset=utf-8',
204 'Content' => encode_json( $stemweb_request ) );
205 if( $resp->is_success ) {
207 $c->log->debug( 'Got a response from the server: '
208 . decode_utf8( $resp->content ) );
209 my $stemweb_response = decode_json( $resp->content );
211 $t->set_stemweb_jobid( $stemweb_response->{jobid} );
212 } catch( Text::Tradition::Error $e ) {
213 return _json_error( $c, 429, $e->message );
215 $c->model('Directory')->save( $t );
216 $c->stash->{'result'} = $stemweb_response;
217 $c->forward('View::JSON');
218 } elsif( $resp->code == 500 && $resp->header('Client-Warning')
219 && $resp->header('Client-Warning') eq 'Internal response' ) {
220 # The server was unavailable.
221 return _json_error( $c, 503, "The Stemweb server is currently unreachable." );
223 return _json_error( $c, 500, "Stemweb error: " . $resp->code . " / "
228 # Helper to check what permission, if any, the active user has for
229 # the given tradition
230 sub _check_permission {
231 my( $c, $tradition ) = @_;
232 my $user = $c->user_exists ? $c->user->get_object : undef;
234 return 'full' if ( $user->is_admin ||
235 ( $tradition->has_user && $tradition->user->id eq $user->id ) );
237 # Text doesn't belong to us, so maybe it's public?
238 return 'readonly' if $tradition->public;
240 # ...nope. Forbidden!
241 return _json_error( $c, 403, 'You do not have permission to view this tradition.' );
244 # Helper to throw a JSON exception
246 my( $c, $code, $errmsg ) = @_;
247 $c->response->status( $code );
248 $c->stash->{'result'} = { 'error' => $errmsg };
249 $c->forward('View::JSON');
254 return $_[0] ? JSON::true : JSON::false;