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 . "/algorithms/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 ## STUPID HACK: unless we load the possible tradition owners
119 ## within scope of the scan, they will not exist when the affected
120 ## tradition is saved.
122 $m->scan( sub{ push( @traditions, $_[0] )
123 if $_[0]->$_isa('Text::Tradition')
124 && $_[0]->has_stemweb_jobid
125 && $_[0]->stemweb_jobid eq $answer->{job_id};
126 push( @users, $_[0] ) if $_[0]->$_isa('Text::Tradition::User');
128 if( @traditions == 1 ) {
129 my $tradition = shift @traditions;
130 if( $answer->{status} == 0 ) {
133 $stemmata = $tradition->record_stemweb_result( $answer );
134 $m->save( $tradition );
135 } catch( Text::Tradition::Error $e ) {
136 return _json_error( $c, 500, $e->message );
138 return _json_error( $c, 500, $@ );
140 # If we got here, success!
141 my @steminfo = map { {
142 name => $_->identifier,
143 directed => _json_bool( !$_->is_undirected ),
144 svg => $_->as_svg() } }
146 $c->stash->{'result'} = {
147 'status' => 'success',
148 'stemmata' => \@steminfo };
149 } elsif( $answer->{status} < 1 ) {
150 $c->stash->{'result'} = { 'status' => 'running' };
152 return _json_error( $c, 500,
153 "Stemweb failure not handled: " . $answer->{result} );
155 } elsif( @traditions ) {
156 return _json_error( $c, 500,
157 "Multiple traditions with Stemweb job ID " . $answer->{job_id} . "!" );
159 # Possible that the tradition got updated in the meantime...
160 if( $answer->{status} == 0 ) {
161 $c->stash->{'result'} = { 'status' => 'notfound' };
163 return _json_error( $c, 400,
164 "No tradition found with Stemweb job ID " . $answer->{job_id} );
167 $c->forward('View::JSON');
172 GET stemweb/request/?
173 tradition=<tradition ID> &
174 algorithm=<algorithm ID> &
175 [<algorithm parameters>]
177 Send a request for the given tradition with the given parameters to Stemweb.
178 Processes and returns the JSON response given by the Stemweb server.
182 sub request :Local :Args(0) {
183 my( $self, $c ) = @_;
184 # Look up the relevant tradition and check permissions.
185 my $reqparams = $c->req->params;
186 my $tid = delete $reqparams->{tradition};
187 my $t = $c->model('Directory')->tradition( $tid );
188 my $ok = _check_permission( $c, $t );
190 return( _json_error( $c, 403,
191 'You do not have permission to update stemmata for this tradition' ) )
192 unless $ok eq 'full';
194 # Form the request for Stemweb.
195 my $algorithm = delete $reqparams->{algorithm};
196 my $return_uri = URI->new( $c->uri_for( '/stemweb/result' ) );
197 my $stemweb_request = {
198 return_path => $return_uri->path,
199 return_host => $return_uri->host_port,
200 data => $t->collation->as_tsv,
201 userid => $c->user->get_object->email,
202 parameters => $reqparams };
204 # Call to the appropriate URL with the request parameters.
205 my $ua = LWP::UserAgent->new();
206 $c->log->debug( 'Sending request to Stemweb: ' . to_json( $stemweb_request ) );
207 my $resp = $ua->post( $STEMWEB_BASE_URL . "/algorithms/process/$algorithm/",
208 'Content-Type' => 'application/json; charset=utf-8',
209 'Content' => encode_json( $stemweb_request ) );
210 if( $resp->is_success ) {
212 $c->log->debug( 'Got a response from the server: '
213 . decode_utf8( $resp->content ) );
214 my $stemweb_response = decode_json( $resp->content );
216 $t->set_stemweb_jobid( $stemweb_response->{jobid} );
217 } catch( Text::Tradition::Error $e ) {
218 return _json_error( $c, 429, $e->message );
220 $c->model('Directory')->save( $t );
221 $c->stash->{'result'} = $stemweb_response;
222 $c->forward('View::JSON');
223 } elsif( $resp->code == 500 && $resp->header('Client-Warning')
224 && $resp->header('Client-Warning') eq 'Internal response' ) {
225 # The server was unavailable.
226 return _json_error( $c, 503, "The Stemweb server is currently unreachable." );
228 return _json_error( $c, 500, "Stemweb error: " . $resp->code . " / "
233 # Helper to check what permission, if any, the active user has for
234 # the given tradition
235 sub _check_permission {
236 my( $c, $tradition ) = @_;
237 my $user = $c->user_exists ? $c->user->get_object : undef;
239 return 'full' if ( $user->is_admin ||
240 ( $tradition->has_user && $tradition->user->id eq $user->id ) );
242 # Text doesn't belong to us, so maybe it's public?
243 return 'readonly' if $tradition->public;
245 # ...nope. Forbidden!
246 return _json_error( $c, 403, 'You do not have permission to view this tradition.' );
249 # Helper to throw a JSON exception
251 my( $c, $code, $errmsg ) = @_;
252 $c->response->status( $code );
253 $c->stash->{'result'} = { 'error' => $errmsg };
254 $c->forward('View::JSON');
259 return $_[0] ? JSON::true : JSON::false;