forked from alexjustesen/speedtest-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecuteOoklaSpeedtest.php
More file actions
104 lines (86 loc) · 2.81 KB
/
ExecuteOoklaSpeedtest.php
File metadata and controls
104 lines (86 loc) · 2.81 KB
1
2
3
4
5
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
namespace App\Jobs\Speedtests;
use App\Enums\ResultStatus;
use App\Events\SpeedtestCompleted;
use App\Events\SpeedtestFailed;
use App\Models\Result;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
class ExecuteOoklaSpeedtest implements ShouldBeUnique, ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout = 120;
/**
* Create a new job instance.
*/
public function __construct(
public Result $result,
public ?int $serverId,
) {
}
/**
* Execute the job.
*/
public function handle(): void
{
/**
* Check to make sure there is an internet connection first.
*/
try {
Http::retry(3, 500)->get('https://google.com');
} catch (\Throwable $th) {
$this->result->update([
'data' => [
'type' => 'log',
'level' => 'error',
'message' => 'Could not resolve host.',
],
'status' => ResultStatus::Failed,
]);
SpeedtestFailed::dispatch($this->result);
return;
}
$options = array_filter([
'speedtest',
'--accept-license',
'--accept-gdpr',
'--format=json',
optional($this->serverId) ? '--server-id='.$this->serverId : false,
]);
$process = new Process($options);
try {
$process->mustRun();
} catch (ProcessFailedException $exception) {
$messages = explode(PHP_EOL, $exception->getMessage());
$message = collect(array_filter($messages, 'json_validate'))->last();
$this->result->update([
'data' => json_decode($message, true),
'status' => ResultStatus::Failed,
]);
SpeedtestFailed::dispatch($this->result);
return;
}
$output = json_decode($process->getOutput(), true);
$this->result->update([
'ping' => Arr::get($output, 'ping.latency'),
'download' => Arr::get($output, 'download.bandwidth'),
'upload' => Arr::get($output, 'upload.bandwidth'),
'data' => $output,
'status' => ResultStatus::Completed,
]);
SpeedtestCompleted::dispatch($this->result);
}
}