Skip to content

Commit

Permalink
Bug SAFeSEA#32, Re-factor/extract EssayAnalyser from User controlle…
Browse files Browse the repository at this point in the history
…r [iet:10299633]
  • Loading branch information
nfreear committed Feb 2, 2018
1 parent c6ad725 commit 388f5a7
Show file tree
Hide file tree
Showing 2 changed files with 152 additions and 96 deletions.
114 changes: 18 additions & 96 deletions app/controllers/user.controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,9 @@
*/
class UserController extends Controller
{
/* Was: public static function GetStructureData($id=null)
{
} */
// Was: public static function GetStructureData($id=null) { }

/* Was: public function GetAllKeywords($analysis,$userdata)
{
} */
// Was: public function GetAllKeywords($analysis,$userdata) { }

/**
*
Expand All @@ -30,7 +26,7 @@ public function me()
{
/* @var $u Users */
$u = Model::factory('Users')->find_one($this->user['id']);
if ($u===false)
if ($u === false)
{
$this->app->flash("error", "Cannot find the user data");
$this->redirect('me.home');
Expand Down Expand Up @@ -273,8 +269,8 @@ public function submitDraft($taskId)
$ap = Model::factory('Task')->find_one($taskId);
$g = $ap->group()->find_one();

$formdata=null;
$status=200;
$formdata = null;
$status = 200;

if ($req && $req->isPost())
{
Expand All @@ -290,103 +286,29 @@ public function submitDraft($taskId)
$formdata["name"] = $post["name"];
$versionId = $formdata["version"] = $post["version"];

$r = $redirect = true;
$analyser = new IET_OU\OpenEssayist\Utils\EssayAnalyser();
$result = $analyser->setup();

try {
$url = $this->getAnalyserUrl('/api/analysis');

$post_data = [
'text' => $post["text"],
'module' => $post["module"], // 'module' = 'group.code' = 'H810'.
'task' => $post["task"], // 'task' = 'task.code' = 'TMA01'.
'task_id' => $taskId,
'version_id' => $post["version"],
'user_id' => $this->user['id'],
'rd_save_path'=> $this->getSavePath(),
];

$log = $this->app->getLog();
$log->debug(__METHOD__ . ":start - $taskId,$versionId - " . date('c'));

$time_start = time();

$request = Requests::post($url,
array(),
$post_data,
array(
'timeout' => 5 * 60, // Was: 300.
'blocking' => true
));

$time_end = time();

$duration = $time_end - $time_start;
$log->debug(__METHOD__ . ":end - $taskId,$versionId - seconds:$duration");

$post_data[ 'text' ] = substr( $post_data[ 'text' ], 0, 30 ) . ' [...]';
self::_debug([ __METHOD__, 'POST', $post_data ]);

if ($request->status_code === 200)
{
$json = $request->body;
$ret = json_decode($json,true);

/* @var $draft Draft */
$draft = Model::factory('Draft')->create();
$draft->type = 0;
$draft->analysis = $json;
$draft->task_id = $taskId;
$draft->version = $formdata["version"];
$draft->name = $formdata["name"];
$draft->users_id = $this->user['id'];
$draft->date = date('Y-m-d H:i:s'); // No timezone ?!
// Was: $draft->date = date('Y-m-d H:i:s e');

$draft->text = $formdata[ 'text' ]; // The original text.
$draft->tstart = $time_start;
$draft->tend = $time_end;

$counts = json_encode($post[ 'counts' ]); // JSON via Countable.js.
$draft->counts = json_decode( $counts );

$result = $draft->save();

// redirect to the "drafts review" page
$this->app->flash('info', 'The analysis of your draft was successful. Check the details below.');
$r= $this->app->urlFor("me.draft.action",array("idt" => $taskId));

self::_debug([ 'm' => __METHOD__, 'ok', 'u' => $url, 'taskId' => $taskId, 'draftVersion' => $post['version'], 'result' => $result, 'duration_sec' => $duration, 'counts' => $counts ]);

$redirect = true;
// Was: $this->redirect($r, false);
}
else
{ $json = $request->body;
$ret = json_decode($json,true);

$status = 500;
$this->app->flashNow("error", "Sorry. Problem with the analyser. Make sure you text is not empty. If it continues, please contact the admin.");

self::_debug([ __METHOD__, 'error', 500.1, $ret ]);
}
$result = $analyser->analyseAndSave( $taskId, $this->user[ 'id' ] );
}
catch (Requests_Exception $e)
catch (\Requests_Exception $e)
{
$status = 500;
$result->status = 500;
$this->app->flashNow("error", "Sorry. Cannot connect to the analyser. Try again later.");

self::_debug([ __METHOD__, 'Requests except', 500.2, $e->getMessage() ]);
}
catch (\PDOException $e)
{
$status = 500;
$result->status = 500;
$this->app->flashNow("error", "Sorry. Problem with the database. Try again later.");

self::_debug([ __METHOD__, 'PDO except', 500.3, $e->getMessage() ]);
}
catch (Exception $ex)
catch (\Exception $ex)
{
$status = 500;
$result->status = 500;
$this->app->flashNow("error", "Sorry, we have a problem. Try again later.");

self::_debug([ __METHOD__, 'except', 500.4, $ex->getMessage(), get_class( $ex ) ]);
Expand All @@ -396,23 +318,23 @@ public function submitDraft($taskId)

// Redirect after 'catch' - prevent the Slim\Exception\Stop !
// @link https://docs.slimframework.com/routing/helpers/#-\Except:Stop
if ($r && $redirect) {
$this->redirect($r, false);
if ($result->resp && $result->redirect) {
$this->redirect($result->resp, false);
}
}
}
else {
$u = Model::factory('Users')->find_one($this->user['id']);
$d = $u->drafts()->where_equal('task_id',$taskId)->order_by_desc('id')->find_array();

$formdata['version'] = count($d)+1;
$formdata['version'] = count($d) + 1;
}

$this->render('user/draft.submit',array(
$this->render('user/draft.submit', array(
'task' => $ap->as_array(),
'group' => $g->as_array(),
'form' => $formdata
),$status);
), $result->status);
}

/**
Expand Down
134 changes: 134 additions & 0 deletions app/utils/EssayAnalyser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
<?php namespace IET_OU\OpenEssayist\Utils;

/**
* PHP wrapper round Python EssayAnalyser service.
*
* @package OpenEssayist-slim
* @copyright © 2013-2018 The Open University. (Institute of Educational Technology)
* @author Nick Freear, 02-February-2018.
*/

class EssayAnalyser extends \Application
{
public function setup()
{
return (object) [
'status' => 200,
'redirect' => false,
'resp' => null, // Was: 'r'.
'db_result' => null,
];
}

/**
* Call the analyse service, and save the analysis to the database.
*
* @param int $taskId
* @param int $userId
* @return object A result object.
*/
public function analyseAndSave( $taskId, $userId )
{
$req = $this->app->request();
$log = $this->app->getLog();
$post = $req->post();

$result = $this->setup();

$url = $this->getAnalyserUrl('/api/analysis');

$versionId = $post[ 'version' ];

$post_data = [
'text' => $post["text"],
'module' => $post["module"], // 'module' = 'group.code' = 'H810'.
'task' => $post["task"], // 'task' = 'task.code' = 'TMA01'.
'task_id' => $taskId,
'version_id' => $versionId,
'user_id' => $userId, // Was: $this->user['id'],
'rd_save_path'=> $this->getSavePath(),
];

$log->debug(__METHOD__ . ":start - $taskId,$versionId - " . date('c'));

$times = (object) [ 'start' => time() ];

$request = \Requests::post($url,
array(),
$post_data,
array(
'timeout' => 5 * 60, // Was: 300.
'blocking' => true
));

$times->end = time();

$times->duration = $times->end - $times->start;

$log->debug(__METHOD__ . ":end - $taskId,$versionId - seconds:$duration");

$post_data[ 'text' ] = substr( $post_data[ 'text' ], 0, 30 ) . ' [...]';
self::_debug([ __METHOD__, 'POST', $post_data ]);

if ($request->status_code === 200)
{
$json = $request->body;
$ret = json_decode($json, true);

/* @var $draft Draft */

$result->db_result = $this->saveDraft( $taskId, $userId, $post, $times );
// Was: $result = $draft->save();

// redirect to the "drafts review" page
$this->app->flash('info', 'The analysis of your draft was successful. Check the details below.');
$result->resp = $this->app->urlFor("me.draft.action", array("idt" => $taskId));

self::_debug([ 'm' => __METHOD__, 'ok', 'u' => $url, 'taskId' => $taskId, 'draftVersion' => $versionId, 'result' => $result, 'duration_sec' => $times->duration, 'counts' => $counts ]);

$result->status = 200;
$result->redirect = true;
// Was: $this->redirect($r, false);
}
else
{ $json = $request->body;
$ret = json_decode($json,true);

$result->status = 500;

$this->app->flashNow("error", "Sorry. Problem with the analyser. Make sure you text is not empty. If it continues, please contact the admin.");

self::_debug([ __METHOD__, 'error', 500.1, $ret ]);
}

return $result;
}

/**
* Create a Draft object, and save to the database.
*/
protected function saveDraft( $taskId, $userId, $post, $times )
{
/* @var $draft Draft */
$draft = Model::factory('Draft')->create();
$draft->type = 0;
$draft->analysis = $json;
$draft->task_id = $taskId;
$draft->version = $post["version"];
$draft->name = $post["name"];
$draft->users_id = $userId; // Was: $this->user['id'];
$draft->date = date('Y-m-d H:i:s'); // No timezone ?!
// Was: $draft->date = date('Y-m-d H:i:s e');

$draft->text = $post[ 'text' ]; // The original text.
$draft->tstart = $time->start;
$draft->tend = $times->end;

$counts = json_encode($post[ 'counts' ]); // JSON via Countable.js.
$draft->counts = json_decode( $counts );

$db_result = $draft->save();

return $db_result;
}
}

0 comments on commit 388f5a7

Please sign in to comment.