1
0
mirror of https://github.com/devcode-it/openstamanager.git synced 2025-02-17 20:10:50 +01:00

Miglioramento ulteriore hook

This commit is contained in:
Thomas Zilio 2019-08-29 11:25:13 +02:00
parent d76bdecc14
commit 4498b94324
12 changed files with 263 additions and 89 deletions

View File

@ -104,16 +104,32 @@ switch (get('op')) {
break; break;
case 'hook': case 'hook-lock':
$hook_id = filter('id'); $hook_id = filter('id');
$hook = Hook::find($hook_id); $hook = Hook::find($hook_id);
$init = filter('init'); $token = $hook->lock();
if (!empty($init)) {
$response = $hook->prepare(); echo json_encode($token);
} else {
$response = $hook->execute(); break;
}
case 'hook-execute':
$hook_id = filter('id');
$token = filter('token');
$hook = Hook::find($hook_id);
$response = $hook->execute($token);
echo json_encode($response);
break;
case 'hook-response':
$hook_id = filter('id');
$hook = Hook::find($hook_id);
$response = $hook->response();
echo json_encode($response); echo json_encode($response);

View File

@ -26,32 +26,65 @@ function startHooks() {
message: globals.translations.hookExecuting.replace('_NAME_', item.name) message: globals.translations.hookExecuting.replace('_NAME_', item.name)
}); });
executeHook(item, true); startHook(item, true);
}); });
}, },
}); });
} }
/** /**
* Esegue l'hook e lo visualizza. * Richiama l'hook per l'esecuzione.
* Considerare l'utilizzo di localStorage per bloccare l'esecuzione locale multipla dell'hook nel caso di problemi.
* *
* @param hook * @param hook
* @param element_id
*/ */
function executeHook(hook, init) { function startHook(hook, init) {
$.ajax({ $.ajax({
url: globals.rootdir + "/ajax.php", url: globals.rootdir + "/ajax.php",
type: "get", type: "get",
data: { data: {
op: "hook", op: "hook-lock",
id: hook.id, id: hook.id,
init: init, },
success: function (data) {
var token = JSON.parse(data);
if (init) {
hookCount("#hooks-counter");
updateHook(hook);
}
if (token){
executeHook(hook, token);
} else {
var timeout = 10;
setTimeout(function () {
startHook(hook);
}, timeout * 1000);
}
},
});
}
/**
* Richiama l'hook per l'esecuzione.
*
* @param hook
* @param token
*/
function executeHook(hook, token) {
$.ajax({
url: globals.rootdir + "/ajax.php",
type: "get",
data: {
op: "hook-execute",
id: hook.id,
token: token,
}, },
success: function (data) { success: function (data) {
var result = JSON.parse(data); var result = JSON.parse(data);
updateHook(hook);
renderHook(hook, result);
var timeout; var timeout;
if (result.execute) { if (result.execute) {
@ -61,12 +94,29 @@ function executeHook(hook, init) {
} }
setTimeout(function () { setTimeout(function () {
executeHook(hook); startHook(hook);
}, timeout * 1000); }, timeout * 1000);
},
});
}
if (init) { /**
hookCount("#hooks-counter"); * Aggiorna le informazioni dell'hook.
} *
* @param hook
* @param init
*/
function updateHook(hook) {
$.ajax({
url: globals.rootdir + "/ajax.php",
type: "get",
data: {
op: "hook-response",
id: hook.id,
},
success: function (data) {
var result = JSON.parse(data);
renderHook(hook, result);
// Rimozione eventuale della rotella di caricamento // Rimozione eventuale della rotella di caricamento
var counter = $("#hooks-counter").text(); var counter = $("#hooks-counter").text();

View File

@ -14,7 +14,7 @@ switch ($op) {
if ($dbo->isConnected() && $dbo->isInstalled() && auth()->attempt($username, $password)) { if ($dbo->isConnected() && $dbo->isInstalled() && auth()->attempt($username, $password)) {
$_SESSION['keep_alive'] = true; $_SESSION['keep_alive'] = true;
// Rimozione log vecchi // Rimozione log vecchi
//$dbo->query('DELETE FROM `zz_operations` WHERE DATE_ADD(`created_at`, INTERVAL 30*24*60*60 SECOND) <= NOW()'); //$dbo->query('DELETE FROM `zz_operations` WHERE DATE_ADD(`created_at`, INTERVAL 30*24*60*60 SECOND) <= NOW()');
} else { } else {
$status = auth()->getCurrentStatus(); $status = auth()->getCurrentStatus();

View File

@ -18,8 +18,10 @@ class UpdateHook extends CachedManager
return $result; return $result;
} }
public function response($update) public function response()
{ {
$update = self::getCache()['results'];
$module = Modules::get('Aggiornamenti'); $module = Modules::get('Aggiornamenti');
$link = ROOTDIR.'/controller.php?id_module='.$module->id; $link = ROOTDIR.'/controller.php?id_module='.$module->id;

View File

@ -7,6 +7,16 @@ use Hooks\Manager;
class BackupHook extends Manager class BackupHook extends Manager
{ {
public function isSingleton()
{
return true;
}
public function needsExecution()
{
return setting('Backup automatico') && !Backup::isDailyComplete();
}
public function execute() public function execute()
{ {
$result = Backup::daily(); $result = Backup::daily();
@ -14,23 +24,15 @@ class BackupHook extends Manager
return $result; return $result;
} }
public function response($data) public function response()
{ {
return [ $show = boolval(setting('Backup automatico'));
'icon' => 'fa fa-file-o text-info', $message = $show && !Backup::isDailyComplete() ? tr('Backup in corso...') : tr('Backup completato!');
'message' => tr('Backup completato!'),
'show' => true,
];
}
public function prepare()
{
$result = setting('Backup automatico') && !Backup::isDailyComplete();
return [ return [
'icon' => 'fa fa-file-o text-danger', 'icon' => 'fa fa-file-o text-success',
'message' => tr('Backup in corso...'), 'message' => $message,
'execute' => $result, 'show' => $show,
]; ];
} }
} }

View File

@ -7,6 +7,26 @@ use Notifications\EmailNotification;
class EmailHook extends Manager class EmailHook extends Manager
{ {
public function isSingleton()
{
return true;
}
public function needsExecution()
{
$diff = date('Y-m-d', strtotime('-4 hours'));
$failed = function ($query) use ($diff) {
$query->whereDate('failed_at', '<', $diff)
->orWhereNull('failed_at');
};
$remaining = Mail::whereNull('sent_at')
->where($failed)
->count();
return !empty($remaining);
}
public function execute() public function execute()
{ {
$accounts = Account::all(); $accounts = Account::all();
@ -36,25 +56,14 @@ class EmailHook extends Manager
} }
} }
return count($list); return $list;
} }
public function response($data) public function response()
{
return $this->prepare();
}
public function prepare()
{ {
$yesterday = date('Y-m-d', strtotime('-1 days')); $yesterday = date('Y-m-d', strtotime('-1 days'));
$diff = date('Y-m-d', strtotime('-4 hours'));
$user = auth()->getUser(); $user = auth()->getUser();
$failed = function ($query) use ($diff) {
$query->whereDate('failed_at', '<', $diff)
->orWhereNull('failed_at');
};
$current = Mail::whereDate('sent_at', '>', $yesterday) $current = Mail::whereDate('sent_at', '>', $yesterday)
->where('created_by', $user->id) ->where('created_by', $user->id)
->count(); ->count();
@ -63,17 +72,12 @@ class EmailHook extends Manager
->where('created_by', $user->id) ->where('created_by', $user->id)
->count(); ->count();
$remaining = Mail::whereNull('sent_at') $message = $total != $current ? tr('Invio email in corso...') : tr('Invio email completato!');
->where($failed)
->count();
$message = !empty($remaining) ? tr('Invio email in corso...') : tr('Invio email completato!');
$message = empty($total) ? tr('Nessuna email presente...') : $message; $message = empty($total) ? tr('Nessuna email presente...') : $message;
return [ return [
'icon' => 'fa fa-envelope text-info', 'icon' => 'fa fa-envelope text-info',
'message' => $message, 'message' => $message,
'execute' => !empty($remaining),
'show' => true, 'show' => true,
'progress' => [ 'progress' => [
'current' => $current, 'current' => $current,

View File

@ -14,8 +14,10 @@ class InvoiceHook extends CachedManager
return $list; return $list;
} }
public function response($results) public function response()
{ {
$results = self::getCache()['results'];
$count = count($results); $count = count($results);
$notify = false; $notify = false;

View File

@ -14,8 +14,10 @@ class ReceiptHook extends CachedManager
return $list; return $list;
} }
public function response($results) public function response()
{ {
$results = self::getCache()['results'];
$count = count($results); $count = count($results);
$notify = false; $notify = false;

View File

@ -12,13 +12,15 @@ abstract class CachedManager extends Manager
abstract public function data(); abstract public function data();
public function needsExecution()
{
return !self::isCached();
}
public function execute() public function execute()
{ {
if (self::isCached()) { if (self::isCached()) {
$results = self::getCache()['results']; $results = self::getCache()['results'];
// Interpretazione della cache
$results = json_decode($results, true);
} else { } else {
$results = $this->data(); $results = $this->data();
@ -35,6 +37,9 @@ abstract class CachedManager extends Manager
$cache = database()->selectOne('zz_hook_cache', '*', ['hook_id' => $hook->id], ['id' => 'DESC']); $cache = database()->selectOne('zz_hook_cache', '*', ['hook_id' => $hook->id], ['id' => 'DESC']);
// Interpretazione della cache
$cache['results'] = json_decode($cache['results'], true);
self::$cache = $cache; self::$cache = $cache;
} }

View File

@ -16,35 +16,41 @@ abstract class Manager
/** /**
* Restituisce le informazioni per la visualizzazione dell'hook. * Restituisce le informazioni per la visualizzazione dell'hook.
* *
* @param $results
*
* @return array * @return array
*/ */
abstract public function response($results); abstract public function response();
/** /**
* Restituisce le informazioni per l'inizializzazione dell'hook. * Restituisce se l'hook è un singletion, cioè deve essere richiamato solo da una istanza di navigazione.
* *
* @return array|null * @return bool
*/ */
public function prepare() public function isSingleton()
{ {
return [ return false;
'execute' => true,
];
} }
/**
* Restituisce se l'hook ha bisogno di una esecuzione;.
*
* @return bool
*/
abstract public function needsExecution();
/**
* Gestisce la chiamata per l'esecuzione dell'hook.
*
* @return array|mixed
*/
public function manage() public function manage()
{ {
$prepare = $this->prepare(); if (!$this->needsExecution()) {
if (empty($prepare['execute'])) {
return []; return [];
} }
$data = $this->execute(); $results = $this->execute();
$results = $this->response($data);
return $results; return [];
} }
/** /**

View File

@ -2,6 +2,8 @@
namespace Models; namespace Models;
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Common\Model; use Common\Model;
use Hooks\Manager; use Hooks\Manager;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
@ -27,26 +29,103 @@ class Hook extends Model
return $this->module ? $this->module->permission : 'rw'; return $this->module ? $this->module->permission : 'rw';
} }
public function execute() /**
* Restituisce le informazioni sull'esecuzione dell'hook.
*
* @return array
*/
public function execute($token)
{
$hook = $this->getClass();
if ($hook->isSingleton() && $token != $this->processing_token) {
return;
}
$result = $hook->manage();
if ($hook->isSingleton()) {
$this->unlock($token);
}
$result['execute'] = $hook->needsExecution();
return $result;
}
/**
* Restituisce le informazioni per l'inizializzazione grafica dell'hook.
*
* @return array
*/
public function response()
{
$hook = $this->getClass();
$response = $hook->response();
return $response;
}
/**
* Imposta il lock sull'hook se non già impostato.
* Timeout di 10 minuti.
*
* @return string|null
*/
public function lock()
{
$hook = $this->getClass();
if (!$hook->isSingleton()) {
return true;
}
$result = empty($this->processing_at);
// Forzatura in caso di freeze per più di 10 minuti
$date = new Carbon($this->processing_at);
$interval = CarbonInterval::make('10 minutes');
$date = $date->add($interval);
$now = new Carbon();
$result |= $date->greaterThan($now);
$token = null;
if ($result) {
$token = random_string();
$this->processing_token = $token;
$this->processing_at = date('Y-m-d H:i:s');
$this->save();
}
return $token;
}
/**
* Rimuove il lock sull'hook.
*
* @return string|null
*/
public function unlock($token)
{
if ($token == $this->processing_token) {
$this->processing_token = null;
$this->processing_at = null;
$this->save();
}
}
public function getClass()
{ {
$class = $this->class; $class = $this->class;
$hook = new $class(); $hook = new $class();
if (!$hook instanceof Manager) { if (!$hook instanceof Manager) {
return [ throw new \UnexpectedValueException();
'show' => false,
];
} }
return $hook->manage(); return $hook;
}
public function prepare()
{
$class = $this->class;
$hook = new $class();
return $hook->prepare();
} }
/* Relazioni Eloquent */ /* Relazioni Eloquent */

View File

@ -84,6 +84,12 @@ class EmailNotification extends PHPMailer implements NotificationInterface
{ {
$this->mail = $mail; $this->mail = $mail;
// Registazione della processazione
if (!empty($this->mail)) {
$this->mail->processing_at = date('Y-m-d H:i:s');
$this->mail->save();
}
// Destinatari // Destinatari
$receivers = $mail->receivers; $receivers = $mail->receivers;
foreach ($receivers as $receiver) { foreach ($receivers as $receiver) {
@ -91,7 +97,7 @@ class EmailNotification extends PHPMailer implements NotificationInterface
} }
// Allegati // Allegati
$uploads = $mail->attachments; $uploads = $mail->uploads;
foreach ($uploads as $upload) { foreach ($uploads as $upload) {
$this->addUpload($upload); $this->addUpload($upload);
} }
@ -153,7 +159,7 @@ class EmailNotification extends PHPMailer implements NotificationInterface
$this->mail->failed_at = date('Y-m-d H:i:s'); $this->mail->failed_at = date('Y-m-d H:i:s');
} }
//$this->mail->save(); $this->mail->save();
} }
$this->SmtpClose(); $this->SmtpClose();