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