Whispeak: Improve requests with Guzzle - refs BT#17415

pull/3360/head
Angel Fernando Quiroz Campos 6 years ago
parent 1215026753
commit 01e85e5964
  1. 102
      plugin/whispeakauth/Controller/AuthenticationRequestController.php
  2. 26
      plugin/whispeakauth/Controller/BaseRequestController.php
  3. 96
      plugin/whispeakauth/Controller/CreateEnrollmentRequestController.php
  4. 204
      plugin/whispeakauth/WhispeakAuthPlugin.php

@ -4,8 +4,7 @@
namespace Chamilo\PluginBundle\WhispeakAuth\Controller;
use Chamilo\PluginBundle\Entity\WhispeakAuth\LogEvent;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
/**
* Class AuthenticationRequestController.
@ -222,30 +221,27 @@ class AuthenticationRequestController extends BaseRequestController
*/
private function createSessionToken()
{
$client = new Client();
$response = $client->get(
"{$this->apiEndpoint}/auth",
[
'headers' => [
'Authorization' => "Bearer {$this->apiKey}",
],
'json' => [],
'query' => [
'lang' => \WhispeakAuthPlugin::getLanguageIsoCode($this->user->getLanguage()),
],
]
);
$bodyContents = $response->getBody()->getContents();
$json = json_decode($bodyContents, true);
switch ($response->getStatusCode()) {
case 200:
return $json['token'];
case 400:
case 401:
case 403:
throw new \Exception($json['message']);
try {
$response = $this->httpClient->post(
'auth',
[
'headers' => [
'Authorization' => "Bearer {$this->apiKey}",
],
'json' => [],
'query' => [
'lang' => api_get_language_isocode($this->user->getLanguage()),
],
]
);
$json = json_decode((string) $response->getBody(), true);
return $json['token'];
} catch (RequestException $requestException) {
$this->throwRequestException(
$requestException,
$this->plugin->get_lang('AuthentifyFailed')
);
}
}
@ -259,37 +255,33 @@ class AuthenticationRequestController extends BaseRequestController
*/
private function performAuthentication($token, $wsId)
{
$client = new Client();
$response = $client->post(
"{$this->apiEndpoint}/auth",
[
'headers' => [
'Authorization' => "Bearer $token",
],
'multipart' => [
[
'name' => 'speaker',
'contents' => $wsId,
try {
$this->httpClient->post(
'auth',
[
'headers' => [
'Authorization' => "Bearer $token",
],
[
'name' => 'file',
'contents' => fopen($this->audioFilePath, 'r'),
'filename' => basename($this->audioFilePath),
'multipart' => [
[
'name' => 'speaker',
'contents' => $wsId,
],
[
'name' => 'file',
'contents' => fopen($this->audioFilePath, 'r'),
'filename' => basename($this->audioFilePath),
],
],
],
]
);
$bodyContents = $response->getBody()->getContents();
$json = json_decode($bodyContents, true);
switch ($response->getStatusCode()) {
case 200:
return true;
case 419:
throw new \Exception($this->plugin->get_lang('TryAgain'));
default:
throw new \Exception($json['message']);
]
);
return true;
} catch (RequestException $requestException) {
$this->throwRequestException(
$requestException,
$this->plugin->get_lang('AuthentifyFailed')
);
}
}
}

@ -5,7 +5,9 @@ namespace Chamilo\PluginBundle\WhispeakAuth\Controller;
use FFMpeg\FFMpeg;
use FFMpeg\Format\Audio\Wav;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
/**
* Class BaseRequestController.
@ -19,9 +21,9 @@ abstract class BaseRequestController
*/
protected $plugin;
/**
* @var string
* @var \GuzzleHttp\Client
*/
protected $apiEndpoint;
protected $httpClient;
/**
* @var string
*/
@ -41,7 +43,7 @@ abstract class BaseRequestController
public function __construct()
{
$this->plugin = \WhispeakAuthPlugin::create();
$this->apiEndpoint = $this->plugin->getApiUrl();
$this->httpClient = new Client(['base_uri' => $this->plugin->getApiUrl(),]);
$this->apiKey = $this->plugin->get(\WhispeakAuthPlugin::SETTING_TOKEN);
}
@ -119,4 +121,22 @@ abstract class BaseRequestController
* @return mixed
*/
abstract protected function doApiRequest();
/**
* @param \GuzzleHttp\Exception\RequestException $requestException
* @param string $defaultMessage
*
* @throws \Exception
*/
protected function throwRequestException(RequestException $requestException, $defaultMessage)
{
$message = $defaultMessage;
if ($requestException->hasResponse()) {
$json = json_decode((string) $requestException->getResponse()->getBody(), true);
$message = is_array($json['message']) ? implode("\n", $json['message']) : $json['message'];
}
throw new \Exception($message);
}
}

@ -3,7 +3,7 @@
namespace Chamilo\PluginBundle\WhispeakAuth\Controller;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
/**
* Class CreateEnrollmentRequestController.
@ -62,29 +62,27 @@ class CreateEnrollmentRequestController extends BaseRequestController
*/
private function createSessionToken()
{
$client = new Client();
$response = $client->get(
"{$this->apiEndpoint}/enroll",
[
'headers' => [
'Authorization' => "Bearer {$this->apiKey}",
],
'json' => [],
'query' => [
'lang' => \WhispeakAuthPlugin::getLanguageIsoCode($this->user->getLanguage()),
],
]);
$bodyContents = $response->getBody()->getContents();
$json = json_decode($bodyContents, true);
switch ($response->getStatusCode()) {
case 200:
return $json['token'];
case 400:
case 401:
case 403:
throw new \Exception($json['message']);
try {
$response = $this->httpClient->get(
'enroll',
[
'headers' => [
'Authorization' => "Bearer {$this->apiKey}",
],
'json' => [],
'query' => [
'lang' => api_get_language_isocode($this->user->getLanguage()),
],
]
);
$json = json_decode((string) $response->getBody(), true);
return $json['token'];
} catch (RequestException $requestException) {
$this->throwRequestException(
$requestException,
$this->plugin->get_lang('EnrollmentFailed')
);
}
}
@ -99,34 +97,30 @@ class CreateEnrollmentRequestController extends BaseRequestController
*/
private function createEnrollment($token)
{
$client = new Client();
$response = $client->post(
"{$this->apiEndpoint}/enroll",
[
'headers' => [
'Authorization' => "Bearer $token",
],
'multipart' => [
[
'name' => 'file',
'contents' => fopen($this->audioFilePath, 'r'),
'filename' => basename($this->audioFilePath),
try {
$response = $this->httpClient->post(
'enroll',
[
'headers' => [
'Authorization' => "Bearer $token",
],
],
]
);
$bodyContents = $response->getBody()->getContents();
$json = json_decode($bodyContents, true);
error_log(print_r($json, true));
switch ($response->getStatusCode()) {
case 200:
case 201:
return $json['speaker'];
default:
throw new \Exception($json['message']);
'multipart' => [
[
'name' => 'file',
'contents' => fopen($this->audioFilePath, 'r'),
'filename' => basename($this->audioFilePath),
],
],
]
);
$json = json_decode((string) $response->getBody(), true);
return $json['speaker'];
} catch (RequestException $requestException) {
$this->throwRequestException(
$requestException,
$this->plugin->get_lang('EnrollmentFailed')
);
}
}
}

@ -343,208 +343,6 @@ class WhispeakAuthPlugin extends Plugin implements HookPluginInterface
api_not_allowed($printHeaders);
}
/**
* Convert the language name to ISO-639-2 code (3 characters).
*
* @param string $languageName
*
* @return string
*/
public static function getLanguageIsoCode($languageName)
{
$listIso3 = [
'ab' => 'abk',
'aa' => 'aar',
'af' => 'afr',
'ak' => 'aka',
'sq' => 'sqi',
'am' => 'amh',
'ar' => 'ara',
'an' => 'arg',
'hy' => 'hye',
'as' => 'asm',
'av' => 'ava',
'ae' => 'ave',
'ay' => 'aym',
'az' => 'aze',
'bm' => 'bam',
'ba' => 'bak',
'eu' => 'eus',
'be' => 'bel',
'bn' => 'ben',
'bh' => 'bih',
'bi' => 'bis',
'bs' => 'bos',
'br' => 'bre',
'bg' => 'bul',
'my' => 'mya',
'ca' => 'cat',
'ch' => 'cha',
'ce' => 'che',
'ny' => 'nya',
'zh' => 'zho',
'cv' => 'chv',
'kw' => 'cor',
'co' => 'cos',
'cr' => 'cre',
'hr' => 'hrv',
'cs' => 'ces',
'da' => 'dan',
'dv' => 'div',
'nl' => 'nld',
'dz' => 'dzo',
'en' => 'eng',
'eo' => 'epo',
'et' => 'est',
'ee' => 'ewe',
'fo' => 'fao',
'fj' => 'fij',
'fi' => 'fin',
'fr' => 'fra',
'ff' => 'ful',
'gl' => 'glg',
'ka' => 'kat',
'de' => 'deu',
'el' => 'ell',
'gn' => 'grn',
'gu' => 'guj',
'ht' => 'hat',
'ha' => 'hau',
'he' => 'heb',
'hz' => 'her',
'hi' => 'hin',
'ho' => 'hmo',
'hu' => 'hun',
'ia' => 'ina',
'id' => 'ind',
'ie' => 'ile',
'ga' => 'gle',
'ig' => 'ibo',
'ik' => 'ipk',
'io' => 'ido',
'is' => 'isl',
'it' => 'ita',
'iu' => 'iku',
'ja' => 'jpn',
'jv' => 'jav',
'kl' => 'kal',
'kn' => 'kan',
'kr' => 'kau',
'ks' => 'kas',
'kk' => 'kaz',
'km' => 'khm',
'ki' => 'kik',
'rw' => 'kin',
'ky' => 'kir',
'kv' => 'kom',
'kg' => 'kon',
'ko' => 'kor',
'ku' => 'kur',
'kj' => 'kua',
'la' => 'lat',
'lb' => 'ltz',
'lg' => 'lug',
'li' => 'lim',
'ln' => 'lin',
'lo' => 'lao',
'lt' => 'lit',
'lu' => 'lub',
'lv' => 'lav',
'gv' => 'glv',
'mk' => 'mkd',
'mg' => 'mlg',
'ms' => 'msa',
'ml' => 'mal',
'mt' => 'mlt',
'mi' => 'mri',
'mr' => 'mar',
'mh' => 'mah',
'mn' => 'mon',
'na' => 'nau',
'nv' => 'nav',
'nd' => 'nde',
'ne' => 'nep',
'ng' => 'ndo',
'nb' => 'nob',
'nn' => 'nno',
'no' => 'nor',
'ii' => 'iii',
'nr' => 'nbl',
'oc' => 'oci',
'oj' => 'oji',
'cu' => 'chu',
'om' => 'orm',
'or' => 'ori',
'os' => 'oss',
'pa' => 'pan',
'pi' => 'pli',
'fa' => 'fas',
'pl' => 'pol',
'ps' => 'pus',
'pt' => 'por',
'qu' => 'que',
'rm' => 'roh',
'rn' => 'run',
'ro' => 'ron',
'ru' => 'rus',
'sa' => 'san',
'sc' => 'srd',
'sd' => 'snd',
'se' => 'sme',
'sm' => 'smo',
'sg' => 'sag',
'sr' => 'srp',
'gd' => 'gla',
'sn' => 'sna',
'si' => 'sin',
'sk' => 'slk',
'sl' => 'slv',
'so' => 'som',
'st' => 'sot',
'es' => 'spa',
'su' => 'sun',
'sw' => 'swa',
'ss' => 'ssw',
'sv' => 'swe',
'ta' => 'tam',
'te' => 'tel',
'tg' => 'tgk',
'th' => 'tha',
'ti' => 'tir',
'bo' => 'bod',
'tk' => 'tuk',
'tl' => 'tgl',
'tn' => 'tsn',
'to' => 'ton',
'tr' => 'tur',
'ts' => 'tso',
'tt' => 'tat',
'tw' => 'twi',
'ty' => 'tah',
'ug' => 'uig',
'uk' => 'ukr',
'ur' => 'urd',
'uz' => 'uzb',
've' => 'ven',
'vi' => 'vie',
'vo' => 'vol',
'wa' => 'wln',
'cy' => 'cym',
'wo' => 'wol',
'fy' => 'fry',
'xh' => 'xho',
'yi' => 'yid',
'yo' => 'yor',
'za' => 'zha',
'zu' => 'zul',
];
$iso2 = api_get_language_isocode($languageName);
$iso3 = isset($listIso3[$iso2]) ? $listIso3[$iso2] : $listIso3['en'];
return $iso3;
}
/**
* Get the max_attemtps option.
*
@ -1025,6 +823,6 @@ class WhispeakAuthPlugin extends Plugin implements HookPluginInterface
{
$url = $this->get(self::SETTING_API_URL);
return trim($url, " \t\n\r \v/");
return trim($url, " \t\n\r \v/").'/';
}
}

Loading…
Cancel
Save