44 lines
1.5 KiB
PHP
44 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use RuntimeException;
|
|
use Throwable;
|
|
|
|
class Bambuddy
|
|
{
|
|
public function configured(): bool
|
|
{
|
|
return filled(config('services.bambuddy.url')) && filled(config('services.bambuddy.api_key'));
|
|
}
|
|
|
|
public function printers(): array
|
|
{
|
|
if (! $this->configured()) {
|
|
throw new RuntimeException('BamBuddy API key is not configured.');
|
|
}
|
|
|
|
$url = rtrim(config('services.bambuddy.url'), '/').'/api/v1/printers';
|
|
|
|
$printers = Http::withHeaders(['X-API-Key' => config('services.bambuddy.api_key')])
|
|
->acceptJson()->connectTimeout(3)->timeout(8)->get($url)->throw()->json() ?? [];
|
|
|
|
return collect($printers)->filter(fn ($printer) => is_array($printer) && isset($printer['id']))
|
|
->take(20)->map(function (array $printer): array {
|
|
try {
|
|
$status = Http::withHeaders(['X-API-Key' => config('services.bambuddy.api_key')])
|
|
->acceptJson()->connectTimeout(3)->timeout(5)
|
|
->get(rtrim(config('services.bambuddy.url'), '/').'/api/v1/printers/'.(int) $printer['id'].'/status')
|
|
->throw()->json() ?? [];
|
|
|
|
return $printer + ['live' => $status];
|
|
} catch (Throwable $exception) {
|
|
report($exception);
|
|
|
|
return $printer + ['live' => []];
|
|
}
|
|
})->values()->all();
|
|
}
|
|
}
|