Pass quota limit as a console method

This commit is contained in:
osaajani 2021-06-08 21:01:26 +02:00
parent 120f56fad7
commit cb38447feb
10 changed files with 148 additions and 164 deletions

View File

@ -170,4 +170,14 @@ namespace controllers\internals;
echo ($success === false ? '[KO]' : '[OK]') . ' - ' . $media['path'] . "\n";
}
}
/**
* Do alerting for quota limits
*/
public function quota_limit_alerting()
{
$bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, 'UTF8');
$internal_quota = new \controllers\internals\Quota($bdd);
$internal_quota->alerting_for_limit_close_and_reached();
}
}

View File

@ -66,9 +66,9 @@ namespace controllers\internals;
*
* @return array
*/
public get_events_by_type_and_date_for_user (int $id_user, string $type, \DateTime $since, ?\DateTime $until = null)
public function get_events_by_type_and_date_for_user (int $id_user, string $type, \DateTime $since, ?\DateTime $until = null)
{
$this->get_model->get_events_by_type_and_date_for_user ($id_user, $type, $since, $until);
$this->get_model()->get_events_by_type_and_date_for_user ($id_user, $type, $since, $until);
}
/**

View File

@ -158,7 +158,7 @@ class Quota extends StandardController
$len = mb_strlen($text);
for ($i = 0; $i < $len; $i++)
{
if (!in_array(mb_substr($utf8_string, $i, 1), $gsm0338))
if (!in_array(mb_substr($text, $i, 1), $gsm0338))
{
$is_gsm0338 = false;
break;
@ -168,6 +168,67 @@ class Quota extends StandardController
return ($is_gsm0338 ? ceil($len / 160) : ceil($len / 70));
}
/**
* Do email alerting for quotas limit close and quotas limit reached
*/
public function alerting_for_limit_close_and_reached()
{
$internal_user = new User($this->bdd);
$internal_event = new Event($this->bdd);
$quotas_limit_close = $this->get_model()->get_quotas_for_limit_close();
$quotas_limit_reached = $this->get_model()->get_quotas_for_limit_reached();
foreach ($quotas_limit_close as $quota)
{
$user = $internal_user->get($quota['id_user']);
if (!$user)
{
continue;
}
$quota_percentage = $quota['consumed'] / ($quota['credit'] + $quota['additional']);
$mailer = new \controllers\internals\Mailer();
$success = $mailer->enqueue($user['email'], EMAIL_QUOTA_LIMIT_CLOSE, ['percent' => $quota_percentage]);
if (!$success)
{
echo "Cannot enqueue alert for quota limit close for quota : " . $quota['id'] . "\n";
continue;
}
echo "Enqueue alert for quota limit close for quota : " . $quota['id'] . "\n";
$internal_event->create($quota['id_user'], 'QUOTA_LIMIT_CLOSE', round($quota_percentage * 100, 2) . '% of SMS quota limit reached.');
}
foreach ($quotas_limit_reached as $quota)
{
$user = $internal_user->get($quota['id_user']);
if (!$user)
{
continue;
}
$quota_percentage = $quota['consumed'] / ($quota['credit'] + $quota['additional']);
$mailer = new \controllers\internals\Mailer();
$success = $mailer->enqueue($user['email'], EMAIL_QUOTA_LIMIT_REACHED, ['expiration_date' => $quota['expiration_date']]);
if (!$success)
{
echo "Cannot enqueue alert for quota limit reached for quota : " . $quota['id'] . "\n";
continue;
}
echo "Enqueue alert for quota limit reached for quota : " . $quota['id'] . "\n";
$internal_event->create($quota['id_user'], 'QUOTA_LIMIT_REACHED', 'Reached SMS quota limit.');
}
}
/**
* Get the model for the Controller.
*/

Binary file not shown.

View File

@ -1,159 +0,0 @@
<?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 daemons;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
/**
* Quota daemon class.
*/
class Quota extends AbstractDaemon
{
private $quota_queue;
private $last_message_at;
private $bdd;
/**
* Constructor.
*
* @param array $phone : A phone table entry
*/
public function __construct()
{
$name = 'RaspiSMS Daemon Quota';
$logger = new Logger($name);
$logger->pushHandler(new StreamHandler(PWD_LOGS . '/daemons.log', Logger::DEBUG));
$pid_dir = PWD_PID;
$no_parent = false; //Rattach to parent so parent can stop it
$additional_signals = [];
$uniq = true; //Quota should be uniq
//Construct the daemon
parent::__construct($name, $logger, $pid_dir, $no_parent, $additional_signals, $uniq);
parent::start();
}
public function run()
{
$this->bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, 'UTF8');
$find_message = true;
while ($find_message)
{
//Call message
$maxsize = 409600;
$message = null;
$error_code = null;
$success = msg_receive($this->quota_queue, QUEUE_TYPE_QUOTA, $msgtype, $maxsize, $message, true, MSG_IPC_NOWAIT, $error_code); //MSG_IPC_NOWAIT == dont wait if no message found
if (!$success && MSG_ENOMSG !== $error_code)
{
$this->logger->critical('Error for quota queue reading, error code : ' . $error_code);
$find_message = false;
continue;
}
if (!$message)
{
$find_message = false;
continue;
}
$this->logger->info('Check alert level for quota : ' . json_encode($message['id']));
$internal_settings = new \controllers\internals\Setting($this->bdd);
$settings = $internal_user->gets_for_user($message['id_user']);
$quota_alert_level = false;
foreach ($settings as $name => $value)
{
if ('quota_alert_level', $name)
{
$quota_alert_level = (float) $value;
break;
}
}
if (!$quota_alert_level)
{
$this->logger->info('Alert is disabled for quota : ' . json_encode($message['id']));
continue;
}
$internal_quota = new \controllers\internals\Quota($this->bdd);
$usage_percentage = $internal_quota->get_usage_percentage($message['id_user']);
if ($usage_percentage < $quota_alert_level)
{
continue;
}
//If already an alert event since quota start_date, then ignore alert
$internal_event = new \controllers\internals\Event($this->bdd);
$alert_events = $internal_event->get_events_by_type_and_date_for_user($message['id_user'], 'QUOTA_USAGE_CLOSE', new \DateTime($message['start_date']));
if (count($alert_events))
{
continue;
}
//Alert level reached and no previous alert, we create a new alert
$this->logger->info('Trigger alert for quota : ' . json_encode($message['id']));
$internal_event->create($message['id_user'], 'QUOTA_USAGE_CLOSE', 'Reached ' . ($usage_percentage * 100) . '% of SMS quota.');
$user = $internal_user->get($message['id_user']);
if (!$user)
{
$this->logger->info('Cannot find user with id : ' . json_encode($message['id_user']));
continue;
}
$mailer = new \controllers\internals\Mailer();
$success = $mailer->enqueue($user['email'], EMAIL_QUOTA_USAGE_CLOSE, ['percent' => $usage_percentage]);
if (!$success)
{
$this->logger->error('Cannot enqueue alerting email for quota usage.');
continue;
}
$this->logger->info('Success sending email');
}
//Check quotas every 60 seconds
usleep(60 * 1000000);
}
public function on_start()
{
//Set last message at to construct time
$this->quota_queue = msg_get_queue(QUEUE_ID_QUOTA);
$this->logger->info('Starting Quota daemon with pid ' . getmypid());
}
public function on_stop()
{
//Delete queue on daemon close
$this->logger->info('Closing queue : ' . QUEUE_ID_EMAIL);
msg_remove_queue($this->mailer_queue);
$this->logger->info('Stopping Mailer daemon with pid ' . getmypid());
}
public function handle_other_signals($signal)
{
$this->logger->info('Signal not handled by ' . $this->name . ' Daemon : ' . $signal);
}
}

View File

@ -36,7 +36,7 @@ namespace models;
*
* @return array
*/
public get_events_by_type_and_date_for_user (int $id_user, string $type, \DateTime $since, ?\DateTime $until = null)
public function get_events_by_type_and_date_for_user (int $id_user, string $type, \DateTime $since, ?\DateTime $until = null)
{
$where = [
'id_user' => $id_user,
@ -46,7 +46,7 @@ namespace models;
if ($until !== null)
{
$where['<=at' => $until->format('Y-m-d H:i:s')];
$where['<=at'] = $until->format('Y-m-d H:i:s');
}
return $this->_select('event', $where, 'at');

View File

@ -86,6 +86,77 @@ namespace models;
return (bool) $this->_run_query($query, $params, \descartes\Model::ROWCOUNT);
}
/**
* Get all quotas we need to send an alert for close limit to users they belongs to
* @return array
*/
public function get_quotas_for_limit_close() : array
{
$query = '
SELECT quota.*
FROM quota
INNER JOIN setting
ON (
quota.id_user = setting.id_user
AND setting.NAME = :setting_name
AND setting.value != 0
)
WHERE
quota.consumed / ( quota.credit + quota.additional ) >= setting.value
AND (
SELECT COUNT(id)
FROM event
WHERE
id_user = quota.id_user
AND type = :event_type
AND at >= quota.start_date
) = 0;
';
$params = [
'setting_name' => 'alert_quota_limit_close',
'event_type' => 'QUOTA_LIMIT_CLOSE',
];
return $this->_run_query($query, $params);
}
/**
* Get all quotas we need to send an alert for limit reached to users they belongs to
* @return array
*/
public function get_quotas_for_limit_reached() : array
{
$query = '
SELECT quota.*
FROM quota
INNER JOIN setting
ON (
quota.id_user = setting.id_user
AND setting.NAME = :setting_name
AND setting.value = 1
)
WHERE
quota.consumed >= (quota.credit + quota.additional)
AND (
SELECT COUNT(id)
FROM event
WHERE
id_user = quota.id_user
AND type = :event_type
AND at >= quota.start_date
) = 0;
';
$params = [
'setting_name' => 'alert_quota_limit_reached',
'event_type' => 'QUOTA_LIMIT_REACHED',
];
return $this->_run_query($query, $params);
}
/**
* Return table name.
*/

View File

@ -1,4 +1,5 @@
Vous avez épuisé votre quota de SMS, vous ne pourrez plus envoyer de SMS tant que votre quota de SMS n'aura pas été augmenté ou remis à zéro.
<?php if ($expiration_date ?? false) { ?>Votre quota sera remis à zéro le <?php $this->s($expiration_date); ?>.<?php } ?>
--------------------------------------------------------------------------------------------
Pour plus d'informations sur le système RaspiSMS, rendez-vous sur le site https://raspisms.fr