wordsonline_connector-1.0.x-dev/src/WordsOnlineTranslatorUi.php
src/WordsOnlineTranslatorUi.php
<?php
namespace Drupal\wordsonline_connector;
use Drupal\tmgmt\TranslatorPluginUiBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\tmgmt\JobInterface;
use Drupal\wordsonline_connector\Entity\WOLLangPair;
use Drupal\wordsonline_connector\Entity\WOLServiceLevel;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Database\Database;
/**
* WordsOnline translator UI.
*/
class WordsOnlineTranslatorUi extends TranslatorPluginUiBase {
use StringTranslationTrait;
/**
* Service list.
*
* @var array
*/
public $services;
/**
* Default service level.
*
* @var string
*/
public $defaultServiceLevel;
/**
* Guzzle HTTP client.
*
* @var \GuzzleHttp\ClientInterface
*/
protected $client;
/**
* Database.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* Messenger.
*
* @var \Drupal\Core\Messenger\Messenger
*/
protected $messenger;
/**
* The logger service.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* Constructor.
*/
public function __construct() {
$this->client = \Drupal::httpClient();
$this->database = Database::getConnection();
$this->messenger = \Drupal::messenger();
$this->logger = \Drupal::logger('wordsonline_connector');
}
/**
* {@inheritdoc}
*
* @param array $form
* Form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*
* @return array
* Form.
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$results = $this->database->select('wordsonline_connector_configs', 'wol')
->extend('\Drupal\Core\Database\Query\PagerSelectExtender')
->fields('wol')
->limit(1)
->execute()
->fetchAssoc();
$username = NULL;
$password = NULL;
$project_key = NULL;
if ($results != NULL) {
$username = $results["username"];
$password = $results["password"];
$project_key = $results["project_key"];
}
$form['username'] = [
'#type' => 'textfield',
'#title' => $this->t('Username'),
'#value' => $username,
'#description' => $this->t('Please enter the username.'),
'#description_display' => 'after',
'#required' => TRUE,
'#placeholder' => 'Please enter the username.',
'#prefix' => '<div class="wol-text-field">',
'#suffix' => '</div>',
];
$form['password'] = [
'#type' => 'password',
'#title' => $this->t('Password'),
'#value' => $password,
'#description' => $this->t('Please enter the password.'),
'#description_display' => 'after',
'#required' => TRUE,
'#placeholder' => 'Please enter the password.',
'#attributes' => ['value' => $password],
'#prefix' => '<div class="wol-text-field">',
'#suffix' => '</div>',
];
$form['project_key'] = [
'#type' => 'textfield',
'#title' => $this->t('Project ID'),
'#value' => $project_key,
'#description' => $this->t('Please enter the Project ID.'),
'#description_display' => 'after',
'#required' => TRUE,
'#placeholder' => 'Please enter the Project ID.',
'#prefix' => '<div class="wol-text-field">',
'#suffix' => '</div>',
];
$form['grant_type'] = [
'#type' => 'hidden',
'#default_value' => 'password',
'#value' => 'password',
];
$form['scope'] = [
'#type' => 'hidden',
'#default_value' => 'webapi enterprise enterpriseordering',
'#value' => 'webapi enterprise enterpriseordering',
];
$form += parent::addConnectButton();
$form['#attached']['library'][] = 'wordsonline_connector/wordsonline_form';
return $form;
}
/**
* {@inheritdoc}
*
* @param array $form
* Form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::validateConfigurationForm($form, $form_state);
if ($form_state->hasAnyErrors()) {
return;
}
try {
$field = $form_state->getUserInput();
$fields["username"] = $field['settings']['username'];
$fields["password"] = $field['settings']['password'];
$fields["scope"] = $field['settings']['scope'];
$fields["grant_type"] = $field['settings']['grant_type'];
$result = wordsonline_connector_get_status_code('POST', $fields);
if ($result == 401) {
$authen_err = WordsOnlineMessage::AUTHEN_ERROR;
$form_state->setErrorByName('settings][username', $authen_err);
}
if ($result == 200) {
try {
$this->database->delete('wordsonline_connector_configs')->execute();
$f = [
'username',
'password',
'scope',
'grant_type',
'api_url',
'config_id',
'project_key',
];
$values = [
'username' => $fields["username"],
'password' => $fields["password"],
'scope' => $fields["scope"],
'grant_type' => $fields["grant_type"],
'api_url' => WordsOnlineConst::API_URL,
'config_id' => 1,
'project_key' => $field['settings']['project_key'],
];
$this->database->insert('wordsonline_connector_configs')
->fields($f)->values($values)->execute();
$authen_saved = WordsOnlineMessage::AUTHEN_SAVED;
$this->messenger->addMessage($authen_saved);
}
catch (Exception $ex) {
$this->logger->error($ex->getMessage());
}
}
}
catch (Exception $e) {
$this->logger->error($e->getMessage());
}
}
/**
* Checkout settings form.
*
* @param array $form
* Form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state.
* @param Drupal\tmgmt\JobInterface $job
* Job.
*/
public function checkoutSettingsForm(array $form, FormStateInterface $form_state, JobInterface $job) {
$translator = $job->getTranslator();
$projects = [];
$results = $this->database->query(WordsOnlineConst::SELECT_CONFIG)->fetchAssoc();
$contentsarray = [];
$project_key = $job->getSetting('project_key');
$timezone = date_default_timezone_get();
if ($results != NULL) {
$auth["username"] = $results["username"];
$auth["password"] = $results["password"];
$auth["scope"] = $results["scope"];
$auth["grant_type"] = $results["grant_type"];
$response = wordsonline_connector_get_token('POST', $auth);
$response = json_decode($response, TRUE);
$token = $response['access_token'];
if ($project_key == NULL) {
$project_key = $results['project_key'];
}
if ($token == NULL || $token == '') {
$this->messenger->addError(
$this->pleaseContactHelpDeskMessage()
);
return;
}
$timezone = timezone_name_from_abbr($response['timezone']);
$projects = $this->getProject('GET', $project_key, $token);
if ($projects) {
foreach ($projects['contentTypes'] as $row) {
$contentsarray[$row] = $row;
}
$this->services = $projects["serviceLevels"];
}
}
else {
$this->messenger->addError(
$this->pleaseContactHelpDeskMessage()
);
}
$form['project_key'] = [
'#type' => 'hidden',
'#required' => TRUE,
'#default_value' => $project_key,
'#value' => $project_key,
];
$form['content_type'] = [
'#title' => $this->t('Content Type'),
'#type' => 'select',
'#required' => TRUE,
"#empty_option" => $this->t('- Select -'),
'#options' => $contentsarray,
'#default_value' => $job->getSetting('content_type'),
'#prefix' => '<div class="wol-text-field">',
'#suffix' => '</div>',
];
$this->defaultServiceLevel = $job->getSetting('service_level');
foreach($contentsarray as $ct){
$selectOpts1 = [];
foreach($this->services as $s){
if($s->contentType== $ct){
$selectOpts1[$s->serviceName] =$s->serviceName;
}
}
$form['service_level'] = [
'#title' => $this->t('Service Level'),
'#type' => 'select',
"#empty_option" => $this->t('- Select -'),
'#default_value' => $this->defaultServiceLevel,
'#options' => $selectOpts1,
'#states' => [
'visible' => [
'select[name="settings[content_type]"]' => ['value' => $ct]
],
'required' => [
'select[name="settings[content_type]"]' => ['value' => $ct]
],
],
'#prefix' => '<div class="wol-text-field" id="service_level_wrapper">',
'#suffix' => '</div>'
];
}
if(!$this->isContinuousJob($job)) {
if ($timezone) {
$due_date_title = 'Due Date (' . $timezone . ')';
$form['due_date'] = [
'#title' => $due_date_title,
'#type' => 'date',
'#default_value' => $job->getSetting('due_date'),
'#format' => 'YYY-MM-DD h:mm',
'#required' => TRUE,
'#attributes' => [
'min' => (new \DateTime("tomorrow", new \DateTimeZone($timezone)))->format('Y-m-d'),
'onchange' => "onDateChage(this)",
],
'#prefix' => '<div class="wol-text-field wol-des">',
'#suffix' => '</div>',
];
}
else {
$due_date_title = 'Due Date';
$form['due_date'] = [
'#title' => $due_date_title,
'#type' => 'date',
'#default_value' => $job->getSetting('due_date'),
'#format' => 'YYY-MM-DD h:mm',
'#required' => TRUE,
'#attributes' => [
'onchange' => "onDateChage(this)",
],
'#prefix' => '<div class="wol-text-field wol-des">',
'#suffix' => '</div>',
];
}
$request_name = $job->getSetting('request_name');
if (!$request_name) {
$request_name = wordsonline_connector_get_request_name();
}
$form['request_name'] = [
'#type' => 'textfield',
'#title' => $this->t('Request Name'),
'#default_value' => $request_name,
'#required' => TRUE,
'#placeholder' => 'Please enter the request name.',
'#prefix' => '<div class="wol-text-field">',
'#suffix' => '</div>',
];
}
$form['auto_approve_quote'] = [
'#title' => $this->t('Auto Approve Quote'),
'#description' => $this->t('Quote of this order will be approved automatically.'),
'#description_display' => 'after',
'#type' => 'checkbox',
'#default_value' => $job->getSetting('auto_approve_quote'),
'#prefix' => '<div class="wol-checkbox-field">',
'#suffix' => '</div>',
];
$is_auto = $translator->isAutoAccept();
if ($is_auto == TRUE || $is_auto == 1) {
$form['auto_import'] = [
'#title' => $this->t('Auto import upon receiving delivery files'),
'#description' => $this->t('Auto import the translation back to Drupal when the files delivered.'),
'#description_display' => 'after',
'#type' => 'checkbox',
'#default_value' => TRUE,
'#prefix' => '<div class="wol-checkbox-field d-hidden" >',
'#suffix' => '</div>',
];
}
else {
$form['auto_import'] = [
'#title' => $this->t('Auto import upon receiving delivery files'),
'#description' => $this->t('Auto import the translation back to Drupal when the files delivered.'),
'#description_display' => 'after',
'#type' => 'checkbox',
'#default_value' => $job->getSetting('auto_import'),
'#prefix' => '<div class="wol-checkbox-field">',
'#suffix' => '</div>',
];
}
$form['#attached']['library'][] = 'wordsonline_connector/wordsonline_form';
return parent::checkoutSettingsForm($form, $form_state, $job);
}
/**
* Get error message when can't call wordsonline api.
*
*/
public function pleaseContactHelpDeskMessage(){
return $this->t(
'Cannot find WordsOnline provider settings.
Please contact <a href="mailto:@url">@url<a/>
to obtain WordsOnline provider settings.',
[
"@url" => WordsOnlineConst::HELPDESK_MAIL,
]
);
}
/**
* Check job is continuous.
*
* @param Drupal\tmgmt\JobInterface $job
* Job.
*
*/
public function isContinuousJob($job) {
$job_type = $job->getJobType();
return $job_type == JobInterface::TYPE_CONTINUOUS ;
}
/**
* Get list wordsonline project.
*
* @param string $method
* Method of request.
* @param string $project_key
* Project key.
* @param string $token
* Token.
*
* @return array
* List project.
*/
public function getProject($method = 'GET', $project_key = "", $token = NULL) {
$options = [];
$projects = [];
$url = WordsOnlineConst::API_URL . WordsOnlineConst::GET_PROJECT_URL . $project_key;
try {
$options['headers'] = [
'Authorization' => 'Bearer ' . $token,
'Referer' => 'ClientAPI',
'Content-Type' => 'application/json',
];
$options['timeout'] = 3600;
$response = $this->client->request($method, $url, $options);
}
catch (RequestException $e) {
if (!$e->hasResponse()) {
throw new TMGMTException(WordsOnlineMessage::UNABLE_TO_CONNECT_SERVICES, ['@error' => $e->getMessage()], $e->getCode());
}
$response = $e->getResponse();
throw new TMGMTException(WordsOnlineMessage::UNABLE_TO_CONNECT_SERVICES, ['@error' => $response->getReasonPhrase()], $response->getStatusCode());
}
$received_data = $response->getBody()->getContents();
if ($response->getStatusCode() != 200) {
throw new TMGMTException(
WordsOnlineMessage::UNABLE_TO_CONNECT_SERVICES_WITH_URL,
[
'@error' => $response->getStatusCode(),
'@url' => $url,
]
);
}
$orderResponse = json_decode($received_data, TRUE);
if ($orderResponse["status"] == 1) {
$lstProject = $orderResponse["result"];
foreach ($orderResponse["result"] as $record) {
// foreach ($record["languagePairs"] as $row) {
// $projects["languages"][] = new WOLLangPair($row['sourceLanguage'], $row['targetLanguage']);
// }
foreach ($record["contentTypes"] as $row) {
$projects["contentTypes"][] = $row;
}
foreach ($record["serviceLevels"] as $row) {
$projects["serviceLevels"][] = new WOLServiceLevel($row['name'], $row['contentType']);
}
break;
}
}
return $projects;
}
/**
* Submit callback to pull translations from WordsOnlineTranslator.
*
* @param array $form
* Form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*/
public function submitPullTranslations(array $form, FormStateInterface $form_state) {
$job = $form_state->getFormObject()->getEntity();
$translator_plugin = $job->getTranslator()->getPlugin();
$translator_plugin->fetchTranslations($job);
tmgmt_write_request_messages($job);
}
}
