Greatly improve adapters. Add twilio adapter for virtual numbers (no shortcode support before next version). Improve daemons exception + ERRORS handling. A lot of other little things

This commit is contained in:
osaajani 2020-04-02 01:55:55 +02:00
parent cbaa186c9e
commit 0c8fc7b3ac
17 changed files with 713 additions and 118 deletions

View File

@ -31,6 +31,12 @@ namespace adapters;
* Classname of the adapter.
*/
public static function meta_classname(): string;
/**
* Uniq name of the adapter
* It should be the classname of the adapter un snakecase
*/
public static function meta_uid() : string;
/**
* Name of the adapter.
@ -73,14 +79,22 @@ namespace adapters;
* @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
*
* @return mixed Uid of the sended message if send, False else
* @return array : [
* bool 'error' => false if no error, true else
* ?string 'error_message' => null if no error, else error message
* array 'uid' => Uid of the sms created on success
* ]
*/
public function send(string $destination, string $text, bool $flash = false);
/**
* Method called to read unread SMSs of the number.
* Method called to read SMSs of the number.
*
* @return array : Array of the sms reads
* @return array : [
* bool 'error' => false if no error, true else
* ?string 'error_message' => null if no error, else error message
* array 'sms' => Array of the sms reads
* ]
*/
public function read(): array;
@ -95,7 +109,7 @@ namespace adapters;
/**
* Method called on reception of a status update notification for a SMS.
*
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')]
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms (\models\Sended::STATUS_UNKNOWN, \models\Sended::STATUS_DELIVERED, \models\Sended::STATUS_FAILED)]
*/
public static function status_change_callback();
}

View File

@ -42,6 +42,15 @@ namespace adapters;
{
return __CLASS__;
}
/**
* Uniq name of the adapter
* It should be the classname of the adapter un snakecase
*/
public static function meta_uid() : string
{
return 'gammu_adapter';
}
/**
* Name of the adapter.
@ -115,13 +124,25 @@ namespace adapters;
* @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
*
* @return mixed : Uid of the sended message if send, False else
* @return array : [
* bool 'error' => false if no error, true else
* ?string 'error_message' => null if no error, else error message
* ?string 'uid' => Uid of the sms created on success, null on error
* ]
*/
public function send(string $destination, string $text, bool $flash = false)
{
$response = [
'error' => false,
'error_message' => null,
'uid' => null,
];
if (!$this->unlock_sim())
{
return false;
$response['error'] = true;
$response['error_message'] = 'Cannot unlock SIM.';
return $response;
}
$command_parts = [
@ -147,13 +168,17 @@ namespace adapters;
$result = $this->exec_command($command_parts);
if (0 !== $result['return'])
{
return false;
$response['error'] = true;
$response['error_message'] = 'Gammu command failed.';
return $response;
}
$find_ok = $this->search_for_string($result['output'], 'ok');
if (!$find_ok)
{
return false;
$response['error'] = true;
$response['error_message'] = 'Cannot find output OK.';
return $response;
}
$uid = false;
@ -172,22 +197,37 @@ namespace adapters;
if (false === $uid)
{
return false;
$response['error'] = true;
$response['error_message'] = 'Cannot retrieve sms uid.';
return $response;
}
return $uid;
$response['uid'] = $uid;
return $response;
}
/**
* Method called to read SMSs of the phone
* Method called to read SMSs of the number.
*
* @return array : Array of the sms reads
* @return array : [
* bool 'error' => false if no error, true else
* ?string 'error_message' => null if no error, else error message
* array 'sms' => Array of the sms reads
* ]
*/
public function read(): array
{
$response = [
'error' => false,
'error_message' => null,
'smss' => [],
];
if (!$this->unlock_sim())
{
return [];
$response['error'] = true;
$response['error_message'] = 'Cannot unlock sim.';
return $response;
}
$command_parts = [
@ -198,10 +238,11 @@ namespace adapters;
$return = $this->exec_command($command_parts);
if (0 !== $return['return'])
{
return [];
$response['error'] = true;
$response['error_message'] = 'Gammu command return failed.';
return $response;
}
$smss = [];
foreach ($return['output'] as $line)
{
$decode = json_decode($line, true);
@ -210,14 +251,14 @@ namespace adapters;
continue;
}
$smss[] = [
$response['smss'][] = [
'at' => $decode['at'],
'text' => $decode['text'],
'origin' => $decode['number'],
];
}
return $smss;
return $response;
}
/**
@ -235,7 +276,7 @@ namespace adapters;
/**
* Method called on reception of a status update notification for a SMS.
*
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')]
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms (\models\Sended::STATUS_UNKNOWN, \models\Sended::STATUS_DELIVERED, \models\Sended::STATUS_FAILED)]
*/
public static function status_change_callback()
{

View File

@ -59,6 +59,15 @@ namespace adapters;
return __CLASS__;
}
/**
* Uniq name of the adapter
* It should be the classname of the adapter un snakecase
*/
public static function meta_uid() : string
{
return 'ovh_sms_shortcode_adapter';
}
/**
* Name of the adapter.
* It should probably be the name of the service it adapt (e.g : Gammu SMSD, OVH SMS, SIM800L, etc.).
@ -74,7 +83,7 @@ namespace adapters;
*/
public static function meta_description(): string
{
$callback = \descartes\Router::url('Callback', 'update_sended_status', ['adapter_name' => self::meta_name()], ['api_key' => $_SESSION['user']['api_key'] ?? '<your_api_key>']);
$callback = \descartes\Router::url('Callback', 'update_sended_status', ['adapter_uid' => self::meta_uid()], ['api_key' => $_SESSION['user']['api_key'] ?? '<your_api_key>']);
$generate_credentials_url = 'https://eu.api.ovh.com/createToken/index.cgi?GET=/sms&GET=/sms/*&POST=/sms/*&PUT=/sms/*&DELETE=/sms/*&';
return '
@ -163,6 +172,12 @@ namespace adapters;
*/
public function send(string $destination, string $text, bool $flash = false)
{
$response = [
'error' => false,
'error_message' => null,
'uid' => null,
];
try
{
$success = true;
@ -185,39 +200,63 @@ namespace adapters;
$nb_invalid_receivers = \count(($response['invalidReceivers'] ?? []));
if ($nb_invalid_receivers > 0)
{
return false;
$response['error'] = true;
$response['error_message'] = 'Invalid receiver';
return $response;
}
$uids = $response['ids'] ?? [];
$uid = $response['ids'][0] ?? false;
if (!$uid)
{
$response['error'] = true;
$response['error_message'] = 'Cannot retrieve uid.';
return $response;
}
return $uids[0] ?? false;
$response['uid'] = $uid;
return $response;
}
catch (\Exception $e)
catch (\Throwable $t)
{
return false;
$response['error'] = true;
$response['error_message'] = $t->getMessage();
return $response;
}
}
/**
* Method called to read SMSs of the number.
*
* @return array : Array of the sms reads
* @return array : [
* bool 'error' => false if no error, true else
* ?string 'error_message' => null if no error, else error message
* array 'sms' => Array of the sms reads
* ]
*/
public function read(): array
{
$response = [
'error' => false,
'error_message' => null,
'smss' => [],
];
try
{
$success = true;
//If we use a sender we cannot receive response, no need to make queries
if ($this->datas['sended'])
{
return $response;
}
$endpoint = '/sms/' . $this->datas['service_name'] . '/incoming';
$uids = $this->api->get($endpoint);
if (!\is_array($uids) || !$uids)
{
return [];
return $response;
}
$received_smss = [];
foreach ($uids as $uid)
{
$endpoint = '/sms/' . $this->datas['service_name'] . '/incoming/' . $uid;
@ -228,7 +267,7 @@ namespace adapters;
continue;
}
$received_smss[] = [
$response['smss'][] = [
'at' => (new \DateTime($sms_details['creationDatetime']))->format('Y-m-d H:i:s'),
'text' => $sms_details['message'],
'origin' => $sms_details['sender'],
@ -239,11 +278,13 @@ namespace adapters;
$this->api->delete($endpoint);
}
return $received_smss;
return $response;
}
catch (\Exception $e)
catch (\Throwable $t)
{
return [];
$response['error'] = true;
$response['error_message'] = $t->getMessage();
return $response;
}
}
@ -271,7 +312,7 @@ namespace adapters;
return $success;
}
catch (\Exception $e)
catch (\Throwable $t)
{
return false;
}
@ -280,7 +321,7 @@ namespace adapters;
/**
* Method called on reception of a status update notification for a SMS.
*
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')]
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms (\models\Sended::STATUS_UNKNOWN, \models\Sended::STATUS_DELIVERED, \models\Sended::STATUS_FAILED)]
*/
public static function status_change_callback()
{
@ -295,16 +336,16 @@ namespace adapters;
switch ($dlr)
{
case 1:
$status = 'delivered';
$status = \models\Sended::STATUS_DELIVERED;
break;
case 2:
case 16:
$status = 'failed';
$status = \models\Sended::STATUS_FAILED;
break;
default:
$status = 'unknown';
$status = \models\Sended::STATUS_UNKNOWN;
break;
}

View File

@ -36,7 +36,6 @@ namespace adapters;
/**
* Adapter constructor, called when instanciated by RaspiSMS.
*
* @param string $number : Phone number the adapter is used for
* @param json string $datas : JSON string of the datas to configure interaction with the implemented service
*/
public function __construct(string $datas)
@ -61,6 +60,16 @@ namespace adapters;
{
return __CLASS__;
}
/**
* Uniq name of the adapter
* It should be the classname of the adapter un snakecase
*/
public static function meta_uid() : string
{
return 'ovh_sms_virtual_number_adapter';
}
/**
* Name of the adapter.
@ -77,7 +86,7 @@ namespace adapters;
*/
public static function meta_description(): string
{
$callback = \descartes\Router::url('Callback', 'update_sended_status', ['adapter_name' => self::meta_name()], ['api_key' => $_SESSION['user']['api_key'] ?? '<your_api_key>']);
$callback = \descartes\Router::url('Callback', 'update_sended_status', ['adapter_uid' => self::meta_uid()], ['api_key' => $_SESSION['user']['api_key'] ?? '<your_api_key>']);
$generate_credentials_url = 'https://eu.api.ovh.com/createToken/index.cgi?GET=/sms&GET=/sms/*&POST=/sms/*&PUT=/sms/*&DELETE=/sms/*&';
return '
@ -107,6 +116,7 @@ namespace adapters;
'title' => 'Numéro',
'description' => 'Numéro de téléphone virtuel chez OVH.',
'required' => true,
'number' => true,
],
[
'name' => 'app_key',
@ -164,6 +174,12 @@ namespace adapters;
*/
public function send(string $destination, string $text, bool $flash = false)
{
$response = [
'error' => false,
'error_message' => null,
'uid' => null,
];
try
{
$success = true;
@ -179,39 +195,57 @@ namespace adapters;
$nb_invalid_receivers = \count(($response['invalidReceivers'] ?? []));
if ($nb_invalid_receivers > 0)
{
return false;
$response['error'] = true;
$response['error_message'] = 'Invalid receiver';
return $response;
}
$uids = $response['ids'] ?? [];
$uid = $response['ids'][0] ?? false;
if (!$uid)
{
$response['error'] = true;
$response['error_message'] = 'Cannot retrieve uid';
return $response;
}
return $uids[0] ?? false;
$response['uid'] = $uid;
return $response;
}
catch (\Exception $e)
catch (\Throwable $t)
{
return false;
$response['error'] = true;
$response['error_message'] = $t->getMessage();
return $response;
}
}
/**
* Method called to read SMSs of the number.
*
* @return array : Array of the sms reads
* @return array : [
* bool 'error' => false if no error, true else
* ?string 'error_message' => null if no error, else error message
* array 'sms' => Array of the sms reads
* ]
*/
public function read(): array
{
$response = [
'error' => false,
'error_message' => null,
'smss' => [],
];
try
{
$success = true;
$endpoint = '/sms/' . $this->datas['service_name'] . '/virtualNumbers/' . $this->formatted_number . '/incoming';
$uids = $this->api->get($endpoint);
if (!\is_array($uids) || !$uids)
if (!is_array($uids) || !$uids)
{
return [];
return $response;
}
$received_smss = [];
foreach ($uids as $uid)
{
$endpoint = '/sms/' . $this->datas['service_name'] . '/virtualNumbers/' . $this->formatted_number . '/incoming/' . $uid;
@ -222,7 +256,7 @@ namespace adapters;
continue;
}
$received_smss[] = [
$response['smss'][] = [
'at' => (new \DateTime($sms_details['creationDatetime']))->format('Y-m-d H:i:s'),
'text' => $sms_details['message'],
'origin' => $sms_details['sender'],
@ -233,11 +267,13 @@ namespace adapters;
$this->api->delete($endpoint);
}
return $received_smss;
return $response;
}
catch (\Exception $e)
catch (\Throwable $t)
{
return [];
$response['error'] = true;
$response['error_message'] = $t->getMessage();
return $response;
}
}
@ -251,6 +287,7 @@ namespace adapters;
{
try
{
return true;
$success = true;
//Check service name
@ -264,7 +301,7 @@ namespace adapters;
return $success && (bool) $response;
}
catch (\Exception $e)
catch (\Throwable $t)
{
return false;
}
@ -273,7 +310,7 @@ namespace adapters;
/**
* Method called on reception of a status update notification for a SMS.
*
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')]
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms (\models\Sended::STATUS_UNKNOWN, \models\Sended::STATUS_DELIVERED, \models\Sended::STATUS_FAILED)]
*/
public static function status_change_callback()
{
@ -288,16 +325,16 @@ namespace adapters;
switch ($dlr)
{
case 1:
$status = 'delivered';
$status = \models\Sended::STATUS_DELIVERED;
break;
case 2:
case 16:
$status = 'failed';
$status = \models\Sended::STATUS_FAILED;
break;
default:
$status = 'unknown';
$status = \models\Sended::STATUS_UNKNOWN;
break;
}

View File

@ -52,6 +52,15 @@ namespace adapters;
{
return __CLASS__;
}
/**
* Uniq name of the adapter
* It should be the classname of the adapter un snakecase
*/
public static function meta_uid() : string
{
return 'test_adapter';
}
/**
* Name of the adapter.
@ -117,42 +126,85 @@ namespace adapters;
*/
public function send(string $destination, string $text, bool $flash = false)
{
$response = [
'error' => false,
'error_message' => null,
'uid' => null,
];
$uid = uniqid();
$at = (new \DateTime())->format('Y-m-d H:i:s');
file_put_contents($this->test_file_write, json_encode(['uid' => $uid, 'at' => $at, 'destination' => $destination, 'text' => $text, 'flash' => $flash]) . "\n", FILE_APPEND);
$success = file_put_contents($this->test_file_write, json_encode(['uid' => $uid, 'at' => $at, 'destination' => $destination, 'text' => $text, 'flash' => $flash]) . "\n", FILE_APPEND);
if ($success === false)
{
$response['error'] = true;
$response['error_message'] = 'Cannot write in file : ' . $this->test_file_write;
return $response;
}
return uniqid();
$response['uid'] = $uid;
return $response;
}
/**
* Method called to read SMSs of the number.
*
* @return array : Array of the sms reads
* @return array : [
* bool 'error' => false if no error, true else
* ?string 'error_message' => null if no error, else error message
* array 'sms' => Array of the sms reads
* ]
*/
public function read(): array
{
$file_contents = file_get_contents($this->test_file_read);
$response = [
'error' => false,
'error_message' => null,
'smss' => [],
];
//Empty file to avoid dual read
file_put_contents($this->test_file_read, '');
$smss = explode("\n", $file_contents);
$return = [];
foreach ($smss as $key => $sms)
try
{
$decode_sms = json_decode($sms, true);
if (null === $decode_sms)
$file_contents = file_get_contents($this->test_file_read);
if ($file_contents === false)
{
continue;
$response['error'] = true;
$response['error_message'] = 'Cannot read file : ' . $this->test_file_read;
return $response;
}
$return[] = $decode_sms;
}
//Empty file to avoid dual read
$success = file_put_contents($this->test_file_read, '');
if ($success === false)
{
$response['error'] = true;
$response['error_message'] = 'Cannot write in file : ' . $this->test_file_read;
return $response;
}
return $return;
$smss = explode("\n", $file_contents);
foreach ($smss as $key => $sms)
{
$decode_sms = json_decode($sms, true);
if (null === $decode_sms)
{
continue;
}
$response['smss'][] = $decode_sms;
}
return $response;
}
catch (\Throwable $t)
{
$response['error'] = true;
$response['error_message'] = $t->getMessage();
return $response;
}
}
/**
@ -182,21 +234,21 @@ namespace adapters;
$return = [
'uid' => $uid,
'status' => 'unknown',
'status' => \models\Sended::STATUS_UNKNOWN,
];
switch ($status)
{
case 'delivered':
$return['status'] = 'delivered';
case \models\Sended::STATUS_DELIVERED:
$return['status'] = \models\Sended::STATUS_DELIVERED;
break;
case 'failed':
$return['status'] = 'failed';
case \models\Sended::STATUS_FAILED:
$return['status'] = \models\Sended::STATUS_FAILED;
break;
default:
$return['status'] = 'unknown';
$return['status'] = \models\Sended::STATUS_UNKNOWN;
break;
}

View File

@ -0,0 +1,327 @@
<?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace adapters;
use Twilio\Rest\Client;
/**
* Twilio SMS service with a virtual number adapter
*/
class TwilioVirtualNumberAdapter implements AdapterInterface
{
/**
* Datas used to configure interaction with the implemented service. (e.g : Api credentials, ports numbers, etc.).
*/
private $datas;
/**
* Twilio Api client
*/
private $client;
/**
* Twilio virtual number to use
*/
private $number;
/**
* Callback address Twilio must call on SMS status change
*/
private $status_change_callback;
/**
* Adapter constructor, called when instanciated by RaspiSMS.
*
* @param string $number : Phone number the adapter is used for
* @param json string $datas : JSON string of the datas to configure interaction with the implemented service
*/
public function __construct(string $datas)
{
$this->datas = json_decode($datas, true);
$this->client = new Client(
$this->datas['account_sid'],
$this->datas['auth_token']
);
$this->number = $this->datas['number'];
$this->status_change_callback = $this->datas['status_change_callback'];
}
/**
* Classname of the adapter.
*/
public static function meta_classname(): string
{
return __CLASS__;
}
/**
* Uniq name of the adapter
* It should be the classname of the adapter un snakecase
*/
public static function meta_uid() : string
{
return 'twilio_virtual_number_adapter';
}
/**
* Name of the adapter.
* It should probably be the name of the service it adapt (e.g : Gammu SMSD, OVH SMS, SIM800L, etc.).
*/
public static function meta_name(): string
{
return 'Twilio Numéro virtuel';
}
/**
* Description of the adapter.
* A short description of the service the adapter implements.
*/
public static function meta_description(): string
{
$callback = \descartes\Router::url('Callback', 'update_sended_status', ['adapter_uid' => self::meta_uid()], ['api_key' => $_SESSION['user']['api_key'] ?? '<your_api_key>']);
$credentials_url = 'https://www.twilio.com/console';
return '
Solution de SMS avec numéro virtuel proposé par <a target="_blank" href="https://www.twilio.com/sms">Twilio</a>. Pour trouver vos clés API Twilio <a target="_blank" href="' . $credentials_url . '">cliquez ici.</a>
<br/>
<br/>
<div class="alert alert-info">Adresse URL de callback de changement d\'état : <b>' . $callback . '</b></div>
';
}
/**
* List of entries we want in datas for the adapter.
*
* @return array : Every line is a field as an array with keys : name, title, description, required
*/
public static function meta_datas_fields(): array
{
return [
[
'name' => 'account_sid',
'title' => 'Account SID',
'description' => 'Identifiant unique Twilio, trouvable sur la page d\'accueil de la console Twilio.',
'required' => true,
],
[
'name' => 'auth_token',
'title' => 'Auth Token',
'description' => 'Jeton d\'identification Twilio, trouvable sous le Account SID.',
'required' => true,
],
[
'name' => 'number',
'title' => 'Numéro de téléphone virtuel',
'description' => 'Numéro de téléphone virtuel Twilio à utiliser parmis les numéro actifs (format international), <a href="https://www.twilio.com/console/phone-numbers/incoming" target="_blank">voir la liste ici</a>.',
'required' => true,
'number' => true,
],
[
'name' => 'status_change_callback',
'title' => 'Callback de changement de status',
'description' => 'L\'adresse que Twilio devra appeler pour signaler le changement de statut d\'un SMS. Laissez tel quel par défaut.',
'required' => true,
'default_value' => \descartes\Router::url('Callback', 'update_sended_status', ['adapter_uid' => self::meta_uid()], ['api_key' => $_SESSION['user']['api_key'] ?? '<your_api_key>']),
],
];
}
/**
* Does the implemented service support reading smss.
*/
public static function meta_support_read(): bool
{
return true;
}
/**
* Does the implemented service support flash smss.
*/
public static function meta_support_flash(): bool
{
return false;
}
/**
* Does the implemented service support status change.
*/
public static function meta_support_status_change(): bool
{
return true;
}
/**
* Method called to send a SMS to a number.
*
* @param string $destination : Phone number to send the sms to
* @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
*
* @return mixed Uid of the sended message if send, False else
*/
public function send(string $destination, string $text, bool $flash = false)
{
$response = [
'error' => false,
'error_message' => null,
'uid' => null,
];
try
{
$message = $this->client->messages->create(
$destination,
[
'from' => $this->number,
'body' => $text,
'statusCallback' => $this->status_change_callback,
]
);
if ($message->errorCode !== null)
{
$response['error'] = true;
$response['error_message'] = $message->errorMessage;
return $response;
}
$response['uid'] = $message->sid;
return $response;
}
catch (\Throwable $t)
{
$response['error'] = true;
$response['error_message'] = $t->getMessage();
return $response;
}
}
/**
* Method called to read SMSs of the number.
*
* @return array : [
* bool 'error' => false if no error, true else
* ?string 'error_message' => null if no error, else error message
* array 'sms' => Array of the sms reads
* ]
*/
public function read(): array
{
$response = [
'error' => false,
'error_message' => null,
'smss' => [],
];
try
{
$messages = $this->client->messages->read([
'to' => $this->number,
], 20);
foreach ($messages as $record)
{
if ($record->direction != 'inbound')
{
continue;
}
$timezone = date_default_timezone_get();
$record->dateCreated->setTimezone(new \DateTimeZone($timezone));
$response['smss'][] = [
'at' => $record->dateCreated->format('Y-m-d H:i:s'),
'text' => $record->body,
'origin' => $record->from,
];
//Remove sms to prevent double reading
$this->client->messages($record->sid)->delete();
}
return $response;
}
catch (\Throwable $t)
{
$response['error'] = true;
$response['error_message'] = $t->getMessage();
return $response;
}
}
/**
* Method called to verify if the adapter is working correctly
* should be use for exemple to verify that credentials and number are both valid.
*
* @return bool : False on error, true else
*/
public function test(): bool
{
try
{
$phone_numbers = $this->client->incomingPhoneNumbers->read(['phoneNumber' => $this->number], 20);
foreach ($phone_numbers as $record)
{
//If not the same number, return false
if ($record->phoneNumber != $this->number)
{
continue;
}
return true; //Same number, its all ok we can return true
}
return false;
}
catch (\Throwable $t)
{
return false;
}
}
/**
* Method called on reception of a status update notification for a SMS.
*
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms (\models\Sended::STATUS_UNKNOWN, \models\Sended::STATUS_DELIVERED, \models\Sended::STATUS_FAILED)]
*/
public static function status_change_callback()
{
$sid = $_REQUEST['MessageSid'] ?? false;
$status = $_REQUEST['MessageStatus'] ?? false;
if (!$sid || !$status)
{
return false;
}
switch ($status)
{
case 'delivered' :
$status = \models\Sended::STATUS_DELIVERED;
break;
case 'failed' :
$status = \models\Sended::STATUS_FAILED;
break;
default :
$status = \models\Sended::STATUS_UNKNOWN;
break;
}
return ['uid' => $sid, 'status' => $status];
}
}

View File

@ -81,7 +81,10 @@ jQuery(document).ready(function()
e.preventDefault();
jQuery(this).addClass('btn-warning');
jQuery(this).removeClass('btn-confirm');
jQuery(this).html('<span class="fa fa-trash-o"></span> Valider la suppression');
var btn_text = jQuery(this).attr('data-confirm-text') ? jQuery(this).attr('data-confirm-text') : '<span class="fa fa-trash-o"></span> Valider la suppression';
jQuery(this).html(btn_text);
return false;
});

View File

@ -9,7 +9,8 @@
"symfony/expression-language": "^5.0",
"robmorgan/phinx": "^0.11.1",
"monolog/monolog": "^2.0",
"ovh/ovh": "^2.0"
"ovh/ovh": "^2.0",
"twilio/sdk": "^6.1"
},
"require-dev": {
}

View File

@ -26,18 +26,17 @@ namespace controllers\internals;
* @param string $uid : Uid of the sms on the adapter service used
* @param string $adapter : Name of the adapter service used to send the message
* @param bool $flash : Is the sms a flash
* @param string $status : Status of a the sms. By default 'unknown'
* @param string $status : Status of a the sms. By default \models\Sended::STATUS_UNKNOWN
*
* @return bool : false on error, new sended id else
*/
public function create(int $id_user, int $id_phone, $at, string $text, string $destination, string $uid, string $adapter, bool $flash = false, ?string $status = 'unknown'): bool
public function create(int $id_user, int $id_phone, $at, string $text, string $destination, string $uid, string $adapter, bool $flash = false, ?string $status = \models\Sended::STATUS_UNKNOWN): bool
{
$sended = [
'id_user' => $id_user,
'id_phone' => $id_phone,
'at' => $at,
'text' => $text,
'origin' => $origin,
'destination' => $destination,
'uid' => $uid,
'adapter' => $adapter,

View File

@ -60,20 +60,20 @@ use Monolog\Logger;
* Function call on a sended sms status change notification reception.
* We return nothing, and we let the adapter do his things.
*
* @param string $adapter_name : Name of the adapter to use
* @param string $adapter_uid : Uid of the adapter to use
*
* @return bool : true on success, false on error
*/
public function update_sended_status(string $adapter_name)
public function update_sended_status(string $adapter_uid)
{
$this->logger->info('Callback status call with adapter name : ' . $adapter_name);
$this->logger->info('Callback status call with adapter uid : ' . $adapter_uid);
//Search for an adapter
$find_adapter = false;
$adapters = $this->internal_adapter->list_adapters();
foreach ($adapters as $adapter)
{
if (mb_strtolower($adapter['meta_name']) === mb_strtolower($adapter_name))
if (mb_strtolower($adapter['meta_uid']) === $adapter_uid)
{
$find_adapter = $adapter;
}
@ -81,7 +81,7 @@ use Monolog\Logger;
if (false === $find_adapter)
{
$this->logger->error('Callback status use non existing adapter : ' . $adapter_name);
$this->logger->error('Callback status use non existing adapter : ' . $adapter_uid);
return false;
}
@ -90,7 +90,7 @@ use Monolog\Logger;
$adapter_classname = $find_adapter['meta_classname'];
if (!$find_adapter['meta_support_status_change'])
{
$this->logger->error('Callback status use adapter ' . $adapter_name . ' which does not support status change.');
$this->logger->error('Callback status use adapter ' . $adapter_uid . ' which does not support status change.');
return false;
}
@ -98,7 +98,7 @@ use Monolog\Logger;
$callback_return = $adapter_classname::status_change_callback();
if (!$callback_return)
{
$this->logger->error('Callback status with adapter ' . $adapter_name . ' failed on adapter compute.');
$this->logger->error('Callback status with adapter ' . $adapter_uid . ' failed because adapter cannot process datas with success.');
return false;
}
@ -111,7 +111,14 @@ use Monolog\Logger;
return false;
}
$this->logger->info('Callback status update message with uid ' . $callback_return['uid'] . '.');
//Do not update if current status is delivered or failed
if ($sended['status'] === \models\Sended::STATUS_DELIVERED || $sended['status'] === \models\Sended::STATUS_FAILED)
{
$this->logger->info('Callback status update message ignore because status is already ' . $sended['status'] . '.');
return false;
}
$this->logger->info('Callback status update message with uid ' . $callback_return['uid'] . ' to ' . $callback_return['status'] . '.');
$this->internal_sended->update_status_for_user($this->user['id'], $sended['id'], $callback_return['status']);
return true;

View File

@ -171,11 +171,38 @@ class Phone extends \descartes\Controller
return $this->redirect(\descartes\Router::url('Phone', 'add'));
}
//If field phone number is invalid
foreach ($find_adapter['meta_datas_fields'] as $field)
{
if (false === ($field['number'] ?? false))
{
continue;
}
if (!empty($adapter_datas[$field['name']]))
{
$adapter_datas[$field['name']] = \controllers\internals\Tool::parse_phone($adapter_datas[$field['name']]);
if ($adapter_datas[$field['name']])
{
continue;
}
}
var_dump($field);
var_dump($adapter_datas[$field['name']]);
die();
\FlashMessage\FlashMessage::push('danger', 'Vous avez fourni un numéro de téléphone avec un format invalide.');
return $this->redirect(\descartes\Router::url('Phone', 'add'));
}
$adapter_datas = json_encode($adapter_datas);
//Check adapter is working correctly with thoses names and datas
$adapter_classname = $find_adapter['meta_classname'];
$adapter_instance = new $adapter_classname($name, $adapter_datas);
$adapter_instance = new $adapter_classname($adapter_datas);
$adapter_working = $adapter_instance->test();
if (!$adapter_working)

View File

@ -160,9 +160,9 @@ abstract class AbstractDaemon
$this->run();
}
}
catch (\Exception $e)
catch (\Throwable $t)
{
$this->logger->critical('Exception : ' . $e->getMessage() . ' in ' . $e->getFile() . ' line ' . $e->getLine());
$this->logger->critical('Exception : ' . $t->getMessage() . ' in ' . $t->getFile() . ' line ' . $t->getLine());
}
//Stop the daemon

View File

@ -145,11 +145,11 @@ class Phone extends AbstractDaemon
$this->logger->info('Try send message : ' . json_encode($message));
$sended_sms_uid = $this->adapter->send($message['destination'], $message['text'], $message['flash']);
if (!$sended_sms_uid)
$response = $this->adapter->send($message['destination'], $message['text'], $message['flash']);
if ($response['error'])
{
$this->logger->error('Failed send message : ' . json_encode($message));
$internal_sended->create($this->phone['id_user'], $this->phone['id'], $at, $message['text'], $message['destination'], $sended_sms_uid, $this->phone['adapter'], $message['flash'], 'failed');
$this->logger->error('Failed send message : ' . json_encode($message) . ' with error : ' . $response['error_message']);
$internal_sended->create($this->phone['id_user'], $this->phone['id'], $at, $message['text'], $message['destination'], $response['uid'] ?? uniqid(), $this->phone['adapter'], $message['flash'], \models\Sended::STATUS_FAILED);
continue;
}
@ -161,7 +161,7 @@ class Phone extends AbstractDaemon
$this->logger->info('Successfully send message : ' . json_encode($message));
$internal_sended->create($this->phone['id_user'], $this->phone['id'], $at, $message['text'], $message['destination'], $sended_sms_uid, $this->phone['adapter'], $message['flash']);
$internal_sended->create($this->phone['id_user'], $this->phone['id'], $at, $message['text'], $message['destination'], $response['uid'], $this->phone['adapter'], $message['flash']);
}
}
@ -178,8 +178,15 @@ class Phone extends AbstractDaemon
return true;
}
$smss = $this->adapter->read();
if (!$smss)
$response = $this->adapter->read();
if ($response['error'])
{
$this->logger->info('Error reading received smss : ' . $response['error_message']);
return false;
}
if (!$response['smss'])
{
return true;
}
@ -188,12 +195,11 @@ class Phone extends AbstractDaemon
$user_settings = $internal_setting->gets_for_user($this->phone['id_user']);
//Process smss
foreach ($smss as $sms)
foreach ($response['smss'] as $sms)
{
$this->logger->info('Receive message : ' . json_encode($sms));
$command_result = $this->process_for_command($sms);
$this->logger->info('after command');
$sms['text'] = $command_result['text'];
$is_command = $command_result['is_command'];

View File

@ -16,6 +16,10 @@ namespace models;
*/
class Sended extends StandardModel
{
const STATUS_UNKNOWN = 'unknown';
const STATUS_DELIVERED = 'delivered';
const STATUS_FAILED = 'failed';
/**
* Return x last sendeds message for a user, order by date.
*

View File

@ -182,7 +182,7 @@
],
'Callback' => [
'update_sended_status' => '/callback/status/{adapter_name}/',
'update_sended_status' => '/callback/status/{adapter_uid}/',
],
'Api' => [

View File

@ -102,7 +102,8 @@
</div>
<div class="panel-body">
<div class="text-center">
<a class="btn btn-success" href="<?= \descartes\Router::url('Account', 'update_api_key', ['csrf' => $_SESSION['csrf']]); ?>"><i class="fa fa-refresh"></i> Générer une nouvelle clef API</a>
<div class="alert alert-warning text-left">Si vous générez une nouvelle clef API la clef actuelle sera supprimée. Pensez à mettre à jour toutes les callbacks chez les services externes.</div>
<a class="btn btn-success btn-confirm" href="<?= \descartes\Router::url('Account', 'update_api_key', ['csrf' => $_SESSION['csrf']]); ?>" data-confirm-text="<i class='fa fa-refresh'></i> Confirmer la mise à jour"><i class="fa fa-refresh"></i> Générer une nouvelle clef API</a>
</div>
</div>
</div>

View File

@ -98,16 +98,40 @@
datas_fields = JSON.parse(datas_fields);
var numbers = [];
var html = '';
jQuery.each(datas_fields, function (index, field)
{
html += '<div class="form-group">' +
'<label>' + field.title + '</label>' +
'<p class="italic small help">' + field.description + '</p>' +
'<div class="form-group">' +
'<input name="adapter_datas[' + field.name + ']" class="form-control" ' + (field.required ? 'required' : '') + ' >' +
'</div>' +
'</div>';
if (!field.number)
{
html += '<div class="form-group">' +
'<label>' + field.title + '</label>' +
'<p class="italic small help">' + field.description + '</p>' +
'<div class="form-group">' +
'<input name="adapter_datas[' + field.name + ']" class="form-control" ' + (field.required ? 'required' : '') + ' ' + (field.default_value ? 'value="' + field.default_value + '"' : '') + '>' +
'</div>' +
'</div>';
}
else
{
var random_id = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
html += '' +
'<div class="form-group">' +
'<label>' + field.title + '</label>' +
'<p class="italic small help">' + field.description + '</p>' +
'<div class="form-group">' +
'<input name="" class="form-control phone-international-input" type="tel" id="' + random_id + '" ' + (field.required ? 'required' : '') + ' ' + (field.default_value ? 'value="' + field.default_value + '"' : '') + '>' +
'</div>' +
'</div>';
var number = {
'id': random_id,
'name': field.name,
};
numbers.push(number);
}
});
if (html == '')
@ -116,6 +140,17 @@
}
jQuery('#adapter-datas-fields').html(html);
for (i = 0; i < numbers.length; i++)
{
var iti_number_input = window.intlTelInput(document.getElementById(numbers[i].id), {
hiddenInput: 'adapter_datas[' + numbers[i].name + ']',
defaultCountry: '<?php $this->s($_SESSION['user']['settings']['default_phone_country']); ?>',
preferredCountries: <?php $this->s(json_encode(explode(',', $_SESSION['user']['settings']['preferred_phone_country'])), false, false); ?>,
nationalMode: true,
utilsScript: '<?php echo HTTP_PWD_JS; ?>/intlTelInput/utils.js',
});
}
}
jQuery('document').ready(function($)