update relation mapper to use base stemmatology lib as of commit 9e9b754
[scpubgit/stemmaweb.git] / lib / stemmaweb / Controller / Relation.pm
CommitLineData
b8a92065 1package stemmaweb::Controller::Relation;
2use Moose;
cc86fa11 3use Module::Load;
b8a92065 4use namespace::autoclean;
b28e606e 5use TryCatch;
b8a92065 6
7BEGIN { extends 'Catalyst::Controller' }
8
9
10=head1 NAME
11
12stemmaweb::Controller::Relation - Controller for the relationship mapper
13
14=head1 DESCRIPTION
15
b28e606e 16The reading relationship mapper with draggable nodes.
b8a92065 17
18=head1 METHODS
19
b28e606e 20=head2 index
21
b8a92065 22 GET relation/$textid
23
24Renders the application for the text identified by $textid.
25
b8a92065 26=cut
27
9529f69c 28sub index :Path :Args(0) {
29 my( $self, $c ) = @_;
b28e606e 30 $c->stash->{'template'} = 'relate.tt';
31}
32
9529f69c 33=head2 definitions
b28e606e 34
9c2e7b80 35 GET relation/definitions
b28e606e 36
37Returns a data structure giving the valid types and scopes for a relationship.
38
39=cut
40
9c2e7b80 41sub definitions :Local :Args(0) {
b28e606e 42 my( $self, $c ) = @_;
17b660e6 43 my $valid_relationships = [ qw/ spelling orthographic grammatical lexical transposition / ];
b28e606e 44 my $valid_scopes = [ qw/ local global / ];
45 $c->stash->{'result'} = { 'types' => $valid_relationships, 'scopes' => $valid_scopes };
46 $c->forward('View::JSON');
b8a92065 47}
48
9529f69c 49=head2 text
b28e606e 50
9529f69c 51 GET relation/$textid/
52
53 Runs the relationship mapper for the specified text ID.
54
b28e606e 55=cut
56
9529f69c 57sub text :Chained('/') :PathPart('relation') :CaptureArgs(1) {
58 my( $self, $c, $textid ) = @_;
13aa153c 59 my $tradition = $c->model('Directory')->tradition( $textid );
cd3f7f55 60 unless( $tradition ) {
61 $c->response->status('404');
62 $c->response->body("No such tradition with ID $textid");
63 $c->detach('View::Plain');
64 return;
65 }
66
7562a27b 67 # Account for a bad interaction between FastCGI and KiokuDB
68 unless( $tradition->collation->tradition ) {
69 $c->log->warn( "Fixing broken tradition link" );
70 $tradition->collation->_set_tradition( $tradition );
71 $c->model('Directory')->save( $tradition );
72 }
20198e59 73 # Check permissions. Will return 403 if denied, otherwise will
74 # put the appropriate value in the stash.
75 my $ok = _check_permission( $c, $tradition );
76 return unless $ok;
77
d58766c0 78 # See how big the tradition is. Edges are more important than nodes
79 # when it comes to rendering difficulty.
80 my $numnodes = scalar $tradition->collation->readings;
81 my $numedges = scalar $tradition->collation->paths;
13aa153c 82 my $length = $tradition->collation->end->rank;
d58766c0 83 # We should display no more than roughly 500 nodes, or roughly 700
84 # edges, at a time.
85 my $segments = $numnodes / 500;
86 if( $numedges / 700 > $segments ) {
87 $segments = $numedges / 700;
88 }
89 my $segsize = sprintf( "%.0f", $length / $segments );
90 my $margin = sprintf( "%.0f", $segsize / 10 );
91 if( $segments > 1 ) {
13aa153c 92 # Segment the tradition in order not to overload the browser.
13aa153c 93 my @divs;
94 my $r = 0;
d58766c0 95 while( $r + $margin < $length ) {
13aa153c 96 push( @divs, $r );
d58766c0 97 $r += $segsize;
13aa153c 98 }
99 $c->stash->{'textsegments'} = [];
d58766c0 100 $c->stash->{'segsize'} = $segsize;
101 $c->stash->{'margin'} = $margin;
ea8e8b3c 102 foreach my $i ( 0..$#divs ) {
103 my $seg = { 'start' => $divs[$i] };
104 $seg->{'display'} = "Segment " . ($i+1);
13aa153c 105 push( @{$c->stash->{'textsegments'}}, $seg );
106 }
107 }
108 $c->stash->{'textid'} = $textid;
109 $c->stash->{'tradition'} = $tradition;
9529f69c 110}
111
112sub main :Chained('text') :PathPart('') :Args(0) {
b28e606e 113 my( $self, $c ) = @_;
13aa153c 114 my $startseg = $c->req->param('start');
9c2e7b80 115 my $tradition = delete $c->stash->{'tradition'};
116 my $collation = $tradition->collation;
13aa153c 117 my $svgopts;
118 if( $startseg ) {
d58766c0 119 # Only render the subgraph from startseg to endseg or to END,
13aa153c 120 # whichever is less.
d58766c0 121 my $endseg = $startseg + $c->stash->{'segsize'} + $c->stash->{'margin'};
13aa153c 122 $svgopts = { 'from' => $startseg };
d58766c0 123 $svgopts->{'to'} = $endseg if $endseg < $collation->end->rank;
13aa153c 124 } elsif( exists $c->stash->{'textsegments'} ) {
125 # This is the unqualified load of a long tradition. We implicitly start
126 # at zero, but go only as far as 550.
d58766c0 127 my $endseg = $c->stash->{'segsize'} + $c->stash->{'margin'};
ea8e8b3c 128 $startseg = 0;
d58766c0 129 $svgopts = { 'to' => $endseg };
13aa153c 130 }
131 my $svg_str = $collation->as_svg( $svgopts );
9529f69c 132 $svg_str =~ s/\n//gs;
ea8e8b3c 133 $c->stash->{'startseg'} = $startseg if defined $startseg;
9529f69c 134 $c->stash->{'svg_string'} = $svg_str;
135 $c->stash->{'text_title'} = $tradition->name;
487674b9 136 if( $tradition->can('language') ) {
137 $c->stash->{'text_lang'} = $tradition->language;
138 $c->stash->{'can_morphologize'} = 1;
139 } else {
140 $c->stash->{'text_lang'} = 'Default';
141 }
9529f69c 142 $c->stash->{'template'} = 'relate.tt';
b28e606e 143}
144
cc86fa11 145=head2 help
146
147 GET relation/help/$language
148
149Returns the help window HTML.
150
151=cut
152
153sub help :Local :Args(1) {
154 my( $self, $c, $lang ) = @_;
155 # Display the morphological help for the language if it is defined.
156 if( $lang && $lang ne 'Default' ) {
157 my $mod = 'Text::Tradition::Language::' . $lang;
158 try {
159 load( $mod );
160 } catch {
161 $c->log->debug("Warning: could not load $mod");
162 }
163 my $has_mod = $mod->can('morphology_tags');
cc86fa11 164 if( $has_mod ) {
165 my $tagset = &$has_mod;
166 $c->stash->{'tagset'} = $tagset;
167 }
168 }
169 $c->stash->{'template'} = 'relatehelp.tt';
170}
171
b28e606e 172=head2 relationships
173
13aa153c 174 GET relation/$textid/relationships
9529f69c 175
176Returns the list of relationships defined for this text.
b28e606e 177
13aa153c 178 POST relation/$textid/relationships { request }
9529f69c 179
180Attempts to define the requested relationship within the text. Returns 200 on
181success or 403 on error.
b28e606e 182
13aa153c 183 DELETE relation/$textid/relationships { request }
9529f69c 184
b28e606e 185
186=cut
187
9529f69c 188sub relationships :Chained('text') :PathPart :Args(0) {
b28e606e 189 my( $self, $c ) = @_;
6d124a83 190 my $tradition = delete $c->stash->{'tradition'};
20198e59 191 my $ok = _check_permission( $c, $tradition );
192 return unless $ok;
6d124a83 193 my $collation = $tradition->collation;
cdd592f3 194 my $m = $c->model('Directory');
9529f69c 195 if( $c->request->method eq 'GET' ) {
196 my @pairs = $collation->relationships; # returns the edges
197 my @all_relations;
198 foreach my $p ( @pairs ) {
199 my $relobj = $collation->relations->get_relationship( @$p );
545163a2 200 next if $relobj->type eq 'collated'; # Don't show these
7562a27b 201 next if $p->[0] eq $p->[1]; # HACK until bugfix
69a19c91 202 my $relhash = { source => $p->[0], target => $p->[1],
203 type => $relobj->type, scope => $relobj->scope };
204 $relhash->{'note'} = $relobj->annotation if $relobj->has_annotation;
205 push( @all_relations, $relhash );
9529f69c 206 }
207 $c->stash->{'result'} = \@all_relations;
20198e59 208 } else {
209 # Check write permissions first of all
210 if( $c->stash->{'permission'} ne 'full' ) {
9529f69c 211 $c->response->status( '403' );
20198e59 212 $c->stash->{'result'} = {
213 'error' => 'You do not have permission to view this tradition.' };
214 } elsif( $c->request->method eq 'POST' ) {
215 unless( $c->stash->{'permission'} eq 'full' ) {
216 $c->response->status( '403' );
217 $c->stash->{'result'} = {
218 'error' => 'You do not have permission to view this tradition.' };
219 $c->detach( 'View::JSON' );
220 }
221 my $node = $c->request->param('source_id');
222 my $target = $c->request->param('target_id');
223 my $relation = $c->request->param('rel_type');
224 my $note = $c->request->param('note');
225 my $scope = $c->request->param('scope');
226
8073db65 227 my $opts = { 'type' => $relation, 'propagate' => 1 };
228 $opts->{'scope'} = $scope if $scope;
20198e59 229 $opts->{'annotation'} = $note if $note;
230
231 try {
232 my @vectors = $collation->add_relationship( $node, $target, $opts );
233 $c->stash->{'result'} = \@vectors;
234 $m->save( $tradition );
235 } catch( Text::Tradition::Error $e ) {
236 $c->response->status( '403' );
237 $c->stash->{'result'} = { 'error' => $e->message };
238 }
239 } elsif( $c->request->method eq 'DELETE' ) {
240 my $node = $c->request->param('source_id');
241 my $target = $c->request->param('target_id');
242
243 try {
244 my @vectors = $collation->del_relationship( $node, $target );
245 $m->save( $tradition );
246 $c->stash->{'result'} = \@vectors;
247 } catch( Text::Tradition::Error $e ) {
248 $c->response->status( '403' );
249 $c->stash->{'result'} = { 'error' => $e->message };
250 }
9529f69c 251 }
b28e606e 252 }
b28e606e 253 $c->forward('View::JSON');
5f15640c 254}
255
256=head2 readings
257
258 GET relation/$textid/readings
259
260Returns the list of readings defined for this text along with their metadata.
261
262=cut
263
0dcdd5ec 264my %read_write_keys = (
265 'id' => 0,
266 'text' => 0,
267 'is_meta' => 0,
268 'grammar_invalid' => 1,
269 'is_nonsense' => 1,
270 'normal_form' => 1,
271);
272
5f15640c 273sub _reading_struct {
274 my( $reading ) = @_;
275 # Return a JSONable struct of the useful keys. Keys meant to be writable
276 # have a true value; read-only keys have a false value.
5f15640c 277 my $struct = {};
2be76d3f 278 map { $struct->{$_} = $reading->$_ if $reading->can( $_ ) } keys( %read_write_keys );
5f15640c 279 # Special case
2be76d3f 280 $struct->{'lexemes'} = $reading->can( 'lexemes' ) ? [ $reading->lexemes ] : [];
0dcdd5ec 281 # Look up any words related via spelling or orthography
282 my $sameword = sub {
283 my $t = $_[0]->type;
284 return $t eq 'spelling' || $t eq 'orthographic';
285 };
286 my @variants;
287 foreach my $sr ( $reading->related_readings( $sameword ) ) {
288 push( @variants, $sr->text );
289 }
290 $struct->{'variants'} = \@variants;
5f15640c 291 return $struct;
292}
293
294sub readings :Chained('text') :PathPart :Args(0) {
295 my( $self, $c ) = @_;
296 my $tradition = delete $c->stash->{'tradition'};
20198e59 297 my $ok = _check_permission( $c, $tradition );
298 return unless $ok;
5f15640c 299 my $collation = $tradition->collation;
300 my $m = $c->model('Directory');
301 if( $c->request->method eq 'GET' ) {
302 my $rdginfo = {};
303 foreach my $rdg ( $collation->readings ) {
304 $rdginfo->{$rdg->id} = _reading_struct( $rdg );
305 }
306 $c->stash->{'result'} = $rdginfo;
307 }
308 $c->forward('View::JSON');
309}
310
311=head2 reading
312
313 GET relation/$textid/reading/$id
314
315Returns the list of readings defined for this text along with their metadata.
316
317 POST relation/$textid/reading/$id { request }
318
319Alters the reading according to the values in request. Returns 403 Forbidden if
320the alteration isn't allowed.
321
322=cut
323
324sub reading :Chained('text') :PathPart :Args(1) {
325 my( $self, $c, $reading_id ) = @_;
326 my $tradition = delete $c->stash->{'tradition'};
327 my $collation = $tradition->collation;
0dcdd5ec 328 my $rdg = $collation->reading( $reading_id );
5f15640c 329 my $m = $c->model('Directory');
330 if( $c->request->method eq 'GET' ) {
5f15640c 331 $c->stash->{'result'} = $rdg ? _reading_struct( $rdg )
332 : { 'error' => "No reading with ID $reading_id" };
333 } elsif ( $c->request->method eq 'POST' ) {
20198e59 334 if( $c->stash->{'permission'} ne 'full' ) {
335 $c->response->status( '403' );
336 $c->stash->{'result'} = {
337 'error' => 'You do not have permission to view this tradition.' };
338 $c->detach('View::JSON');
487674b9 339 return;
20198e59 340 }
6666d111 341 my $errmsg;
487674b9 342 if( $rdg && $rdg->does('Text::Tradition::Morphology') ) {
343 # Are we re-lemmatizing?
344 if( $c->request->param('relemmatize') ) {
345 my $nf = $c->request->param('normal_form');
346 # TODO throw error unless $nf
347 $rdg->normal_form( $nf );
348 # TODO throw error if lemmatization fails
349 # TODO skip this if normal form hasn't changed
350 $rdg->lemmatize();
351 } else {
352 # Set all the values that we have for the reading.
353 # TODO error handling
354 foreach my $p ( keys %{$c->request->params} ) {
355 if( $p =~ /^morphology_(\d+)$/ ) {
356 # Set the form on the correct lexeme
357 my $morphval = $c->request->param( $p );
358 next unless $morphval;
359 my $midx = $1;
360 my $lx = $rdg->lexeme( $midx );
361 my $strrep = $rdg->language . ' // ' . $morphval;
362 my $idx = $lx->has_form( $strrep );
363 unless( defined $idx ) {
364 # Make the word form and add it to the lexeme.
365 try {
366 $idx = $lx->add_matching_form( $strrep ) - 1;
367 } catch( Text::Tradition::Error $e ) {
368 $c->response->status( '403' );
369 $errmsg = $e->message;
370 } catch {
371 # Something else went wrong, probably a Moose error
372 $c->response->status( '403' );
373 $errmsg = 'Something went wrong with the request';
374 }
6666d111 375 }
487674b9 376 $lx->disambiguate( $idx ) if defined $idx;
377 } elsif( $read_write_keys{$p} ) {
378 my $val = _clean_booleans( $rdg, $p, $c->request->param( $p ) );
379 $rdg->$p( $val );
0dcdd5ec 380 }
487674b9 381 }
382 }
383 $m->save( $rdg );
384 } else {
385 $errmsg = "Reading does not exist or cannot be morphologized";
0dcdd5ec 386 }
6666d111 387 $c->stash->{'result'} = $errmsg ? { 'error' => $errmsg }
388 : _reading_struct( $rdg );
0dcdd5ec 389
5f15640c 390 }
391 $c->forward('View::JSON');
392
393}
b28e606e 394
20198e59 395sub _check_permission {
396 my( $c, $tradition ) = @_;
397 my $user = $c->user_exists ? $c->user->get_object : undef;
b0524272 398 # Does this user have access?
20198e59 399 if( $user ) {
b0524272 400 if( $user->is_admin ||
401 ( $tradition->has_user && $tradition->user->id eq $user->id ) ) {
402 $c->stash->{'permission'} = 'full';
403 return 1;
404 }
080f8a02 405 }
406 # Is it public?
407 if( $tradition->public ) {
20198e59 408 $c->stash->{'permission'} = 'readonly';
409 return 1;
080f8a02 410 }
411 # Forbidden!
412 $c->response->status( 403 );
413 $c->response->body( 'You do not have permission to view this tradition.' );
414 $c->detach( 'View::Plain' );
415 return 0;
20198e59 416}
417
997ebe92 418sub _clean_booleans {
419 my( $rdg, $param, $val ) = @_;
420 if( $rdg->meta->get_attribute( $param )->type_constraint->name eq 'Bool' ) {
421 $val = 1 if $val eq 'true';
422 $val = undef if $val eq 'false';
423 }
424 return $val;
425}
426
b8a92065 427=head2 end
428
429Attempt to render a view, if needed.
430
431=cut
432
433sub end : ActionClass('RenderView') {}
434
435=head1 AUTHOR
436
437Tara L Andrews
438
439=head1 LICENSE
440
441This library is free software. You can redistribute it and/or modify
442it under the same terms as Perl itself.
443
444=cut
445
446__PACKAGE__->meta->make_immutable;
447
4481;