Newer
Older
use App\Notification;
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use App\Organization;
use App\Server;
use App\StatusChange;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class StatusChangeDetection implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
foreach (Organization::all() as $organization) {
/* @var $organization \App\Organization */
foreach ($organization->servers as $server) {
$this->detectChangeForServer($server);
}
}
}
$last_change = StatusChange::getLastChangeForServer($server->id);
$current_status = $server->status();
if ($last_change->status == $current_status) {
// no change
return;
}
$change = new StatusChange();
$change->server_id = $server->id;
$change->time = time();
$change->status = $current_status;
$change->save();
$this->sendNotificationIfRequired($change);
}
/**
* Maximum number of notifications sent per day.
*/
const NOTIFICATIONS_PER_DAY = 4;
public function sendNotificationIfRequired(StatusChange $change)
{
$server = $change->server();
$onedayago = time() - 24 * 3600;
$sent_notifications_count = Notification::findForServer($server_id, $onedayago)->count();
if ($sent_notifications_count < self::NOTIFICATIONS_PER_DAY) {
$notification = new Notification();
$notification->server()->associate($server);
$notification->type = "change";
$notification->change_id = $change->id;
$notification->saveAndSend();
return;
if ($sent_notifications_count == self::NOTIFICATIONS_PER_DAY) {
$notification = new Notification();
$notification->server()->associate($server);
$notification->type = "bouncing";
$notification->change_id = $change->id;
$notification->saveAndSend();
return;
}
// nothing to do if number of sent notifications > COUNT