51 lines
1.7 KiB
PHP
51 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Jobs;
|
|
|
|
use App\Models\Tool;
|
|
use Illuminate\Bus\Queueable;
|
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
use Illuminate\Foundation\Bus\Dispatchable;
|
|
use Illuminate\Queue\InteractsWithQueue;
|
|
use Illuminate\Queue\SerializesModels;
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
|
|
class MirrorToolLogo implements ShouldQueue
|
|
{
|
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
|
|
|
public function __construct(public Tool $tool, public string $sourceUrl) {}
|
|
|
|
public function handle(): void
|
|
{
|
|
// The tool may have been re-saved with a different logo_url (or one
|
|
// already mirrored) since this job was queued; only proceed if it's
|
|
// still pointing at the URL we were asked to mirror.
|
|
if ($this->tool->fresh()?->logo_url !== $this->sourceUrl) {
|
|
return;
|
|
}
|
|
|
|
$response = Http::timeout(10)->get($this->sourceUrl);
|
|
|
|
if (! $response->successful() || ! str_starts_with((string) $response->header('Content-Type'), 'image/')) {
|
|
return;
|
|
}
|
|
|
|
$extension = match ($response->header('Content-Type')) {
|
|
'image/png' => 'png',
|
|
'image/jpeg' => 'jpg',
|
|
'image/webp' => 'webp',
|
|
'image/x-icon', 'image/vnd.microsoft.icon' => 'ico',
|
|
default => 'svg' === pathinfo(parse_url($this->sourceUrl, PHP_URL_PATH) ?? '', PATHINFO_EXTENSION) ? 'svg' : 'png',
|
|
};
|
|
|
|
$path = "tools/{$this->tool->slug}-".Str::random(8).".{$extension}";
|
|
|
|
Storage::disk('public')->put($path, $response->body());
|
|
|
|
$this->tool->update(['logo_url' => Storage::disk('public')->url($path)]);
|
|
}
|
|
}
|