Better timing and integration of stemma interactive events
[scpubgit/stemmaweb.git] / lib / stemmaweb / Controller / Stemweb.pm
CommitLineData
532cc23b 1package stemmaweb::Controller::Stemweb;
2use Moose;
3use namespace::autoclean;
ed0ce314 4use Encode qw/ decode_utf8 /;
c2b80bba 5use JSON;
70744367 6use LWP::UserAgent;
532cc23b 7use Safe::Isa;
8use TryCatch;
70744367 9use URI;
532cc23b 10
11BEGIN { extends 'Catalyst::Controller' }
12
70744367 13## TODO Move the /algorithms/available function to the Stemweb module
14my $STEMWEB_BASE_URL = 'http://slinkola.users.cs.helsinki.fi';
15
532cc23b 16=head1 NAME
17
18stemmaweb::Controller::Stemweb - Client listener for Stemweb results
19
20=head1 DESCRIPTION
21
22This is a client listener for the Stemweb API as implemented by the protocol defined at
23L<https://docs.google.com/document/d/1aNYGAo1v1WPDZi6LXZ30FJSMJwF8RQPYbOkKqHdCZEc/pub>.
24
25=head1 METHODS
26
27=head2 result
28
29 POST stemweb/result
30 Content-Type: application/json
31 (On success):
67b2a665 32 { jobid: <ID number>
532cc23b 33 status: 0
34 format: <format>
35 result: <data> }
36 (On failure):
37 { jobid: <ID number>
38 status: >1
39 result: <error message> }
40
41Used by the Stemweb server to notify us that one or more stemma graphs
42has been calculated in response to an earlier request.
43
44=cut
45
46sub result :Local :Args(0) {
47 my( $self, $c ) = @_;
48 if( $c->request->method eq 'POST' ) {
49 # TODO: Verify the sender!
50 my $answer;
51 if( ref( $c->request->body ) eq 'File::Temp' ) {
52 # Read in the file and parse that.
67b2a665 53 $c->log->debug( "Request body is in a temp file" );
54 open( POSTDATA, $c->request->body )
c0292f64 55 or return _json_error( $c, 500, "Failed to open post data file" );
532cc23b 56 binmode( POSTDATA, ':utf8' );
57 # JSON should be all one line
58 my $pdata = <POSTDATA>;
59 chomp $pdata;
60 close POSTDATA;
c2b80bba 61 try {
62 $answer = from_json( $pdata );
63 } catch {
64 return _json_error( $c, 400,
65 "Could not parse POST request '' $pdata '' as JSON: $@" );
66 }
532cc23b 67 } else {
68 $answer = from_json( $c->request->body );
69 }
67b2a665 70 $c->log->debug( "Received push notification from Stemweb: "
71 . to_json( $answer ) );
c2b80bba 72 return _process_stemweb_result( $c, $answer );
73 } else {
74 return _json_error( $c, 403, 'Please use POST!' );
75 }
76}
77
78=head2 query
79
80 GET stemweb/query/<jobid>
81
82A backup method to query the stemweb server to check a particular job status.
83Returns a result as in /stemweb/result above, but status can also be -1 to
84indicate that the job is still running.
85
86=cut
87
88sub query :Local :Args(1) {
89 my( $self, $c, $jobid ) = @_;
90 my $ua = LWP::UserAgent->new();
2c514a6f 91 my $resp = $ua->get( $STEMWEB_BASE_URL . "/algorithms/jobstatus/$jobid" );
c2b80bba 92 if( $resp->is_success ) {
93 # Process it
94 my $response = decode_utf8( $resp->content );
95 $c->log->debug( "Got a response from the server: $response" );
96 my $answer;
97 try {
98 $answer = from_json( $response );
99 } catch {
532cc23b 100 return _json_error( $c, 500,
c2b80bba 101 "Could not parse stemweb response '' $response '' as JSON: $@" );
102 }
103 return _process_stemweb_result( $c, $answer );
104 } elsif( $resp->code == 500 && $resp->header('Client-Warning')
105 && $resp->header('Client-Warning') eq 'Internal response' ) {
106 # The server was unavailable.
107 return _json_error( $c, 503, "The Stemweb server is currently unreachable." );
108 } else {
109 return _json_error( $c, 500, "Stemweb error: " . $resp->code . " / "
110 . $resp->content );
111 }
112}
113
114
115## Helper function for parsing Stemweb result data either by push or by pull
116sub _process_stemweb_result {
117 my( $c, $answer ) = @_;
c0292f64 118 # Find the specified tradition and check its job ID.
c2b80bba 119 my $m = $c->model('Directory');
c0292f64 120 my $tradition = $m->tradition( $answer->{textid} );
121 unless( $tradition ) {
122 return _json_error( $c, 400, "No tradition found with ID "
123 . $answer->{textid} );
124 }
125 if( $answer->{status} == 0 ) {
126 my $stemmata;
127 if( $tradition->has_stemweb_jobid
128 && $tradition->stemweb_jobid eq $answer->{jobid} ) {
c2b80bba 129 try {
130 $stemmata = $tradition->record_stemweb_result( $answer );
131 $m->save( $tradition );
132 } catch( Text::Tradition::Error $e ) {
133 return _json_error( $c, 500, $e->message );
134 } catch {
135 return _json_error( $c, 500, $@ );
136 }
c0292f64 137 } else {
138 # It may be that we already received a callback meanwhile.
139 # Check all stemmata for the given jobid and return them.
140 @$stemmata = grep { $_->came_from_jobid && $_->from_jobid eq $answer->{jobid} } $tradition->stemmata;
141 }
142 $DB::single = 1;
143 if( @$stemmata ) {
c2b80bba 144 # If we got here, success!
145 my @steminfo = map { {
146 name => $_->identifier,
147 directed => _json_bool( !$_->is_undirected ),
148 svg => $_->as_svg() } }
2c514a6f 149 @$stemmata;
c2b80bba 150 $c->stash->{'result'} = {
151 'status' => 'success',
152 'stemmata' => \@steminfo };
c2b80bba 153 } else {
c0292f64 154 # Hm, no stemmata found on this tradition with this jobid.
155 # Clear the tradition jobid so that the user can try again.
156 if( $tradition->has_stemweb_jobid ) {
157 $tradition->_clear_stemweb_jobid;
158 $m->save( $tradition );
159 }
160 $c->stash->{'result'} = { status => 'notfound' };
c2b80bba 161 }
c0292f64 162 } elsif( $answer->{status} < 1 ) {
163 $c->stash->{'result'} = { 'status' => 'running' };
c2b80bba 164 } else {
c0292f64 165 return _json_error( $c, 500,
166 "Stemweb failure not handled: " . $answer->{result} );
532cc23b 167 }
c2b80bba 168 $c->forward('View::JSON');
532cc23b 169}
170
70744367 171=head2 request
172
173 GET stemweb/request/?
174 tradition=<tradition ID> &
175 algorithm=<algorithm ID> &
176 [<algorithm parameters>]
177
178Send a request for the given tradition with the given parameters to Stemweb.
179Processes and returns the JSON response given by the Stemweb server.
180
181=cut
182
183sub request :Local :Args(0) {
184 my( $self, $c ) = @_;
185 # Look up the relevant tradition and check permissions.
186 my $reqparams = $c->req->params;
187 my $tid = delete $reqparams->{tradition};
188 my $t = $c->model('Directory')->tradition( $tid );
189 my $ok = _check_permission( $c, $t );
190 return unless $ok;
191 return( _json_error( $c, 403,
192 'You do not have permission to update stemmata for this tradition' ) )
193 unless $ok eq 'full';
194
195 # Form the request for Stemweb.
196 my $algorithm = delete $reqparams->{algorithm};
197 my $return_uri = URI->new( $c->uri_for( '/stemweb/result' ) );
198 my $stemweb_request = {
199 return_path => $return_uri->path,
200 return_host => $return_uri->host_port,
67b2a665 201 data => $t->collation->as_tsv({noac => 1}),
c2b80bba 202 userid => $c->user->get_object->email,
67b2a665 203 textid => $tid,
70744367 204 parameters => $reqparams };
205
206 # Call to the appropriate URL with the request parameters.
207 my $ua = LWP::UserAgent->new();
c2b80bba 208 $c->log->debug( 'Sending request to Stemweb: ' . to_json( $stemweb_request ) );
70744367 209 my $resp = $ua->post( $STEMWEB_BASE_URL . "/algorithms/process/$algorithm/",
210 'Content-Type' => 'application/json; charset=utf-8',
211 'Content' => encode_json( $stemweb_request ) );
212 if( $resp->is_success ) {
213 # Process it
ed0ce314 214 $c->log->debug( 'Got a response from the server: '
c2b80bba 215 . decode_utf8( $resp->content ) );
70744367 216 my $stemweb_response = decode_json( $resp->content );
217 try {
218 $t->set_stemweb_jobid( $stemweb_response->{jobid} );
219 } catch( Text::Tradition::Error $e ) {
220 return _json_error( $c, 429, $e->message );
221 }
222 $c->model('Directory')->save( $t );
223 $c->stash->{'result'} = $stemweb_response;
224 $c->forward('View::JSON');
225 } elsif( $resp->code == 500 && $resp->header('Client-Warning')
226 && $resp->header('Client-Warning') eq 'Internal response' ) {
227 # The server was unavailable.
228 return _json_error( $c, 503, "The Stemweb server is currently unreachable." );
229 } else {
ed0ce314 230 return _json_error( $c, 500, "Stemweb error: " . $resp->code . " / "
70744367 231 . $resp->content );
232 }
233}
234
235# Helper to check what permission, if any, the active user has for
236# the given tradition
237sub _check_permission {
238 my( $c, $tradition ) = @_;
239 my $user = $c->user_exists ? $c->user->get_object : undef;
240 if( $user ) {
241 return 'full' if ( $user->is_admin ||
242 ( $tradition->has_user && $tradition->user->id eq $user->id ) );
243 }
244 # Text doesn't belong to us, so maybe it's public?
245 return 'readonly' if $tradition->public;
246
247 # ...nope. Forbidden!
248 return _json_error( $c, 403, 'You do not have permission to view this tradition.' );
249}
250
532cc23b 251# Helper to throw a JSON exception
252sub _json_error {
253 my( $c, $code, $errmsg ) = @_;
254 $c->response->status( $code );
255 $c->stash->{'result'} = { 'error' => $errmsg };
256 $c->forward('View::JSON');
257 return 0;
258}
259
c2b80bba 260sub _json_bool {
261 return $_[0] ? JSON::true : JSON::false;
262}
263
264
ed0ce314 2651;