Files
crawlshot/app/Models/CrawlShotJob.php
2025-08-11 02:35:35 +08:00

90 lines
2.5 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class CrawlShotJob extends Model
{
use HasFactory;
protected $fillable = [
'uuid',
'type',
'url',
'status',
'parameters',
'file_path',
'error_message',
'started_at',
'completed_at',
'webhook_url',
'webhook_events_filter',
'webhook_attempts',
'webhook_last_error',
'webhook_next_retry_at'
];
protected $casts = [
'parameters' => 'array',
'webhook_events_filter' => 'array',
'started_at' => 'datetime',
'completed_at' => 'datetime',
'webhook_next_retry_at' => 'datetime'
];
public function getRouteKeyName()
{
return 'uuid';
}
public function buildStatusResponse(): array
{
$response = [
'uuid' => $this->uuid,
'status' => $this->status,
'url' => $this->url,
'created_at' => $this->created_at->toISOString()
];
if ($this->started_at) {
$response['started_at'] = $this->started_at->toISOString();
}
if ($this->completed_at) {
$response['completed_at'] = $this->completed_at->toISOString();
}
if ($this->status === 'completed' && $this->file_path) {
if ($this->type === 'crawl') {
$response['result'] = [
'html' => [
'url' => url("/api/crawl/{$this->uuid}.html"),
'raw' => Storage::get($this->file_path)
]
];
} elseif ($this->type === 'shot') {
$imageData = Storage::get($this->file_path);
$response['result'] = [
'image' => [
'url' => url("/api/shot/{$this->uuid}.webp"),
'raw' => base64_encode($imageData),
],
'mime_type' => 'image/webp',
'format' => 'webp',
'width' => $this->parameters['viewport_width'] ?? 1920,
'height' => $this->parameters['viewport_height'] ?? 1080,
'size' => strlen($imageData)
];
}
}
if ($this->status === 'failed' && $this->error_message) {
$response['error'] = $this->error_message;
}
return $response;
}
}