use jquery SVG lib to make SVG load in its box properly
[scpubgit/stemmaweb.git] / lib / stemmaweb / Controller / Root.pm
CommitLineData
b8a92065 1package stemmaweb::Controller::Root;
2use Moose;
3use namespace::autoclean;
4use Text::Tradition::Analysis qw/ run_analysis /;
41279a86 5use TryCatch;
b8a92065 6
7
8BEGIN { extends 'Catalyst::Controller' }
9
10#
11# Sets the actions in this controller to be registered with no prefix
12# so they function identically to actions created in MyApp.pm
13#
14__PACKAGE__->config(namespace => '');
15
16=head1 NAME
17
18stemmaweb::Controller::Root - Root Controller for stemmaweb
19
20=head1 DESCRIPTION
21
22Serves up the main container pages.
23
24=head1 URLs
25
26=head2 index
27
28The root page (/). Serves the main container page, from which the various
29components will be loaded.
30
31=cut
32
33sub index :Path :Args(0) {
34 my ( $self, $c ) = @_;
35
c655153c 36 # Are we being asked to load a text immediately? If so
37 if( $c->req->param('withtradition') ) {
38 $c->stash->{'withtradition'} = $c->req->param('withtradition');
39 }
b8a92065 40 $c->stash->{template} = 'index.tt';
41}
42
3f9d7ae5 43=head2 about
44
45A general overview/documentation page for the site.
46
47=cut
48
49sub about :Local :Args(0) {
50 my( $self, $c ) = @_;
51 $c->stash->{template} = 'about.tt';
52}
53
b8a92065 54=head1 Elements of index page
55
56=head2 directory
57
58 GET /directory
59
70ccaf75 60Serves a snippet of HTML that lists the available texts. This returns texts belonging to the logged-in user if any, otherwise it returns all public texts.
b8a92065 61
62=cut
70ccaf75 63
b8a92065 64sub directory :Local :Args(0) {
65 my( $self, $c ) = @_;
66 my $m = $c->model('Directory');
69799996 67 # Is someone logged in?
98a45925 68 my %usertexts;
69799996 69 if( $c->user_exists ) {
70 my $user = $c->user->get_object;
98a45925 71 my @list = $m->traditionlist( $user );
72 map { $usertexts{$_->{id}} = 1 } @list;
73 $c->stash->{usertexts} = \@list;
69799996 74 $c->stash->{is_admin} = 1 if $user->is_admin;
75 }
98a45925 76 # List public (i.e. readonly) texts separately from any user (i.e.
77 # full access) texts that exist. Admin users therefore have nothing
78 # in this list.
79 my @plist = grep { !$usertexts{$_->{id}} } $m->traditionlist('public');
80 $c->stash->{publictexts} = \@plist;
b8a92065 81 $c->stash->{template} = 'directory.tt';
82}
83
75354c3a 84=head1 AJAX methods for traditions and their properties
fb6e49b3 85
75354c3a 86=head2 newtradition
87
88 POST /newtradition,
89 { name: <name>,
90 language: <language>,
91 public: <is_public>,
92 file: <fileupload> }
fb6e49b3 93
75354c3a 94Creates a new tradition belonging to the logged-in user, with the given name
95and the collation given in the uploaded file. The file type is indicated via
96the filename extension (.csv, .txt, .xls, .xlsx, .xml). Returns the ID and
97name of the new tradition.
98
99=cut
100
101sub newtradition :Local :Args(0) {
102 my( $self, $c ) = @_;
103 return _json_error( $c, 403, 'Cannot save a tradition without being logged in' )
104 unless $c->user_exists;
105
106 my $user = $c->user->get_object;
107 # Grab the file upload, check its name/extension, and call the
108 # appropriate parser(s).
109 my $upload = $c->request->upload('file');
110 my $name = $c->request->param('name') || 'Uploaded tradition';
111 my $lang = $c->request->param( 'language' ) || 'Default';
112 my $public = $c->request->param( 'public' ) ? 1 : undef;
113 my( $ext ) = $upload->filename =~ /\.(\w+)$/;
114 my %newopts = (
115 'name' => $name,
116 'language' => $lang,
117 'public' => $public,
118 'file' => $upload->tempname
119 );
120
121 my $tradition;
122 my $errmsg;
123 if( $ext eq 'xml' ) {
124 # Try the different XML parsing options to see if one works.
125 foreach my $type ( qw/ CollateX CTE TEI / ) {
126 try {
127 $tradition = Text::Tradition->new( %newopts, 'input' => $type );
128 } catch ( Text::Tradition::Error $e ) {
129 $errmsg = $e->message;
130 } catch {
131 $errmsg = "Unexpected parsing error";
132 }
133 last if $tradition;
134 }
135 } elsif( $ext =~ /^(txt|csv|xls(x)?)$/ ) {
136 # If it's Excel we need to pass excel => $ext;
137 # otherwise we need to pass sep_char => [record separator].
138 if( $ext =~ /xls/ ) {
139 $newopts{'excel'} = $ext;
140 } else {
141 $newopts{'sep_char'} = $ext eq 'txt' ? "\t" : ',';
142 }
143 try {
144 $tradition = Text::Tradition->new(
145 %newopts,
146 'input' => 'Tabular',
147 );
148 } catch ( Text::Tradition::Error $e ) {
149 $errmsg = $e->message;
150 } catch {
151 $errmsg = "Unexpected parsing error";
152 }
153 } else {
154 # Error unless we have a recognized filename extension
2bfac197 155 return _json_error( $c, 403, "Unrecognized file type extension $ext" );
75354c3a 156 }
157
158 # Save the tradition if we have it, and return its data or else the
159 # error that occurred trying to make it.
160 if( $errmsg ) {
161 return _json_error( $c, 500, "Error parsing tradition .$ext file: $errmsg" );
162 } elsif( !$tradition ) {
163 return _json_error( $c, 500, "No error caught but tradition not created" );
164 }
165
166 my $m = $c->model('Directory');
167 $user->add_tradition( $tradition );
168 my $id = $c->model('Directory')->store( $tradition );
169 $c->model('Directory')->store( $user );
170 $c->stash->{'result'} = { 'id' => $id, 'name' => $tradition->name };
171 $c->forward('View::JSON');
172}
173
174=head2 textinfo
175
176 GET /textinfo/$textid
177 POST /textinfo/$textid,
178 { name: $new_name,
179 language: $new_language,
180 public: $is_public,
181 owner: $new_userid } # only admin users can update the owner
182
183Returns information about a particular text.
fb6e49b3 184
185=cut
186
75354c3a 187sub textinfo :Local :Args(1) {
fb6e49b3 188 my( $self, $c, $textid ) = @_;
98a45925 189 my $tradition = $c->model('Directory')->tradition( $textid );
75354c3a 190 unless( $tradition ) {
2bfac197 191 return _json_error( $c, 404, "No tradition with ID $textid" );
75354c3a 192 }
41279a86 193 my $ok = _check_permission( $c, $tradition );
194 return unless $ok;
75354c3a 195 if( $c->req->method eq 'POST' ) {
196 return _json_error( $c, 403,
197 'You do not have permission to update this tradition' )
198 unless $ok eq 'full';
199 my $params = $c->request->parameters;
200 # Handle changes to owner-accessible parameters
201 my $m = $c->model('Directory');
202 my $changed;
ce1c5863 203 # Handle name param - easy
204 if( exists $params->{name} ) {
205 my $newname = delete $params->{name};
206 unless( $tradition->name eq $newname ) {
207 try {
208 $tradition->name( $newname );
75354c3a 209 $changed = 1;
ce1c5863 210 } catch {
211 return _json_error( $c, 500, "Error setting name to $newname" );
75354c3a 212 }
213 }
214 }
ce1c5863 215 # Handle language param, making Default => null
216 my $langval = delete $params->{language} || 'Default';
217 unless( $tradition->language eq $langval ) {
218 try {
219 $tradition->language( $langval );
220 $changed = 1;
221 } catch {
222 return _json_error( $c, 500, "Error setting language to $langval" );
223 }
224 }
225
75354c3a 226 # Handle our boolean
ce1c5863 227 my $ispublic = $tradition->public;
75354c3a 228 if( delete $params->{'public'} ) { # if it's any true value...
229 $tradition->public( 1 );
ce1c5863 230 $changed = 1 unless $ispublic;
231 } else { # the checkbox was unchecked, ergo it should not be public
232 $tradition->public( 0 );
233 $changed = 1 if $ispublic;
75354c3a 234 }
ce1c5863 235
236 # Handle ownership change
75354c3a 237 my $newuser;
238 if( exists $params->{'owner'} ) {
239 # Only admins can update user / owner
240 my $newownerid = delete $params->{'owner'};
4f849eea 241 unless( !$newownerid ||
242 ( $tradition->has_user && $tradition->user->id eq $newownerid ) ) {
75354c3a 243 unless( $c->user->get_object->is_admin ) {
244 return _json_error( $c, 403,
245 "Only admin users can change tradition ownership" );
246 }
ce1c5863 247 $newuser = $m->find_user({ username => $newownerid });
75354c3a 248 unless( $newuser ) {
ce1c5863 249 return _json_error( $c, 500, "No such user " . $newownerid );
75354c3a 250 }
251 $newuser->add_tradition( $tradition );
252 $changed = 1;
253 }
254 }
255 # TODO check for rogue parameters
256 if( scalar keys %$params ) {
257 my $rogueparams = join( ', ', keys %$params );
258 return _json_error( $c, 403, "Request parameters $rogueparams not recognized" );
259 }
260 # If we safely got to the end, then write to the database.
261 $m->save( $tradition ) if $changed;
262 $m->save( $newuser ) if $newuser;
263 }
41279a86 264
75354c3a 265 # Now return the current textinfo, whether GET or successful POST.
266 my $textinfo = {
267 textid => $textid,
268 name => $tradition->name,
269 language => $tradition->language,
270 public => $tradition->public,
271 owner => $tradition->user ? $tradition->user->id : undef,
272 witnesses => [ map { $_->sigil } $tradition->witnesses ],
273 };
274 my @stemmasvg = map { $_->as_svg({ size => [ 500, 375 ] }) } $tradition->stemmata;
275 map { $_ =~ s/\n/ /mg } @stemmasvg;
276 $textinfo->{stemmata} = \@stemmasvg;
277 $c->stash->{'result'} = $textinfo;
278 $c->forward('View::JSON');
fb6e49b3 279}
b8a92065 280
75354c3a 281=head2 variantgraph
b8a92065 282
75354c3a 283 GET /variantgraph/$textid
284
285Returns the variant graph for the text specified at $textid, in SVG form.
b8a92065 286
287=cut
288
75354c3a 289sub variantgraph :Local :Args(1) {
b8a92065 290 my( $self, $c, $textid ) = @_;
98a45925 291 my $tradition = $c->model('Directory')->tradition( $textid );
75354c3a 292 unless( $tradition ) {
2bfac197 293 return _json_error( $c, 404, "No tradition with ID $textid" );
75354c3a 294 }
41279a86 295 my $ok = _check_permission( $c, $tradition );
296 return unless $ok;
297
98a45925 298 my $collation = $tradition->collation;
75354c3a 299 $c->stash->{'result'} = $collation->as_svg;
300 $c->forward('View::SVG');
b8a92065 301}
75354c3a 302
b8a92065 303=head2 stemma
304
75354c3a 305 GET /stemma/$textid/$stemmaseq
306 POST /stemma/$textid/$stemmaseq, { 'dot' => $dot_string }
b8a92065 307
75354c3a 308Returns an SVG representation of the given stemma hypothesis for the text.
309If the URL is called with POST, the stemma at $stemmaseq will be altered
310to reflect the definition in $dot_string. If $stemmaseq is 'n', a new
311stemma will be added.
b8a92065 312
313=cut
314
75354c3a 315sub stemma :Local :Args(2) {
41279a86 316 my( $self, $c, $textid, $stemmaid ) = @_;
b8a92065 317 my $m = $c->model('Directory');
318 my $tradition = $m->tradition( $textid );
75354c3a 319 unless( $tradition ) {
2bfac197 320 return _json_error( $c, 404, "No tradition with ID $textid" );
75354c3a 321 }
41279a86 322 my $ok = _check_permission( $c, $tradition );
323 return unless $ok;
324
41279a86 325 $c->stash->{'result'} = '';
75354c3a 326 my $stemma;
327 if( $c->req->method eq 'POST' ) {
328 if( $ok eq 'full' ) {
41279a86 329 my $dot = $c->request->body_params->{'dot'};
75354c3a 330 try {
331 if( $stemmaid eq 'n' ) {
332 # We are adding a new stemma.
3f7346b1 333 $stemmaid = $tradition->stemma_count;
75354c3a 334 $stemma = $tradition->add_stemma( 'dot' => $dot );
2bfac197 335 } elsif( $stemmaid !~ /^\d+$/ ) {
336 return _json_error( $c, 403, "Invalid stemma ID specification $stemmaid" );
75354c3a 337 } elsif( $stemmaid < $tradition->stemma_count ) {
338 # We are updating an existing stemma.
339 $stemma = $tradition->stemma( $stemmaid );
340 $stemma->alter_graph( $dot );
341 } else {
342 # Unrecognized stemma ID
2bfac197 343 return _json_error( $c, 404, "No stemma at index $stemmaid, cannot update" );
75354c3a 344 }
345 } catch ( Text::Tradition::Error $e ) {
346 return _json_error( $c, 500, $e->message );
347 }
41279a86 348 $m->store( $tradition );
75354c3a 349 } else {
350 # No permissions to update the stemma
351 return _json_error( $c, 403,
352 'You do not have permission to update stemmata for this tradition' );
41279a86 353 }
b8a92065 354 }
75354c3a 355
356 # For a GET or a successful POST request, return the SVG representation
357 # of the stemma in question, if any.
75354c3a 358 if( !$stemma && $tradition->stemma_count > $stemmaid ) {
359 $stemma = $tradition->stemma( $stemmaid );
360 }
ce1c5863 361 my $stemma_xml = $stemma ? $stemma->as_svg( { size => [ 500, 375 ] } ) : '';
362 # What was requested, XML or JSON?
363 my $return_view = 'SVG';
364 if( my $accept_header = $c->req->header('Accept') ) {
365 $c->log->debug( "Received Accept header: $accept_header" );
366 foreach my $type ( split( /,\s*/, $accept_header ) ) {
367 # If we were first asked for XML, return SVG
368 last if $type =~ /^(application|text)\/xml$/;
369 # If we were first asked for JSON, return JSON
370 if( $type eq 'application/json' ) {
371 $return_view = 'JSON';
372 last;
373 }
374 }
375 }
376 if( $return_view eq 'SVG' ) {
377 $c->stash->{'result'} = $stemma_xml;
378 $c->forward('View::SVG');
379 } else { # JSON
380 $stemma_xml =~ s/\n/ /mg;
381 $c->stash->{'result'} = { 'stemmaid' => $stemmaid, 'stemmasvg' => $stemma_xml };
382 $c->forward('View::JSON');
383 }
b8a92065 384}
385
386=head2 stemmadot
387
75354c3a 388 GET /stemmadot/$textid/$stemmaseq
b8a92065 389
390Returns the 'dot' format representation of the current stemma hypothesis.
391
392=cut
393
75354c3a 394sub stemmadot :Local :Args(2) {
395 my( $self, $c, $textid, $stemmaid ) = @_;
b8a92065 396 my $m = $c->model('Directory');
397 my $tradition = $m->tradition( $textid );
75354c3a 398 unless( $tradition ) {
2bfac197 399 return _json_error( $c, 404, "No tradition with ID $textid" );
75354c3a 400 }
41279a86 401 my $ok = _check_permission( $c, $tradition );
402 return unless $ok;
75354c3a 403 my $stemma = $tradition->stemma( $stemmaid );
404 unless( $stemma ) {
2bfac197 405 return _json_error( $c, 404, "Tradition $textid has no stemma ID $stemmaid" );
75354c3a 406 }
407 # Get the dot and transmute its line breaks to literal '|n'
408 $c->stash->{'result'} = { 'dot' => $stemma->editable( { linesep => '|n' } ) };
41279a86 409 $c->forward('View::JSON');
410}
411
75354c3a 412####################
413### Helper functions
414####################
41279a86 415
75354c3a 416# Helper to check what permission, if any, the active user has for
417# the given tradition
41279a86 418sub _check_permission {
419 my( $c, $tradition ) = @_;
420 my $user = $c->user_exists ? $c->user->get_object : undef;
421 if( $user ) {
929ba7c8 422 return 'full' if ( $user->is_admin ||
423 ( $tradition->has_user && $tradition->user->id eq $user->id ) );
080f8a02 424 }
425 # Text doesn't belong to us, so maybe it's public?
426 return 'readonly' if $tradition->public;
427
428 # ...nope. Forbidden!
75354c3a 429 return _json_error( $c, 403, 'You do not have permission to view this tradition.' );
430}
431
432# Helper to throw a JSON exception
433sub _json_error {
434 my( $c, $code, $errmsg ) = @_;
435 $c->response->status( $code );
436 $c->stash->{'result'} = { 'error' => $errmsg };
437 $c->forward('View::JSON');
929ba7c8 438 return 0;
41279a86 439}
440
b8a92065 441=head2 default
442
443Standard 404 error page
444
445=cut
446
447sub default :Path {
448 my ( $self, $c ) = @_;
449 $c->response->body( 'Page not found' );
450 $c->response->status(404);
451}
452
453=head2 end
454
455Attempt to render a view, if needed.
456
457=cut
458
459sub end : ActionClass('RenderView') {}
460
461=head1 AUTHOR
462
463Tara L Andrews
464
465=head1 LICENSE
466
467This library is free software. You can redistribute it and/or modify
468it under the same terms as Perl itself.
469
470=cut
471
472__PACKAGE__->meta->make_immutable;
473
4741;