116 lines
3.2 KiB
PHP
116 lines
3.2 KiB
PHP
<?php
|
|
|
|
namespace App\Features\Scraper\Services;
|
|
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\Http;
|
|
|
|
class TGDBCoverScraper implements CoverScraperInterface
|
|
{
|
|
private string $apiKey;
|
|
|
|
private string $baseUrl = 'https://api.thegamesdb.net/v1';
|
|
|
|
public function __construct()
|
|
{
|
|
$this->apiKey = config('services.thegamesdb.api_key', '');
|
|
}
|
|
|
|
public function search(string $query, ?int $consoleId = null): Collection
|
|
{
|
|
if (empty($this->apiKey)) {
|
|
return collect();
|
|
}
|
|
|
|
$params = [
|
|
'apikey' => $this->apiKey,
|
|
'name' => $query,
|
|
];
|
|
if ($consoleId) {
|
|
$params['platform'] = $consoleId;
|
|
}
|
|
|
|
try {
|
|
$response = Http::timeout(10)->get("{$this->baseUrl}/Games/ByGameName", $params);
|
|
|
|
if ($response->successful()) {
|
|
$games = $response->json('data.games') ?? [];
|
|
|
|
return collect($games)->map(fn ($game) => [
|
|
'id' => $game['id'],
|
|
'title' => $game['game_title'],
|
|
'cover_url' => $game['cover'] ?? null,
|
|
'year' => isset($game['release_date'])
|
|
? date('Y', strtotime($game['release_date']))
|
|
: null,
|
|
'source' => 'thegamesdb',
|
|
]);
|
|
}
|
|
} catch (\Exception $e) {
|
|
// Log error
|
|
}
|
|
|
|
return collect();
|
|
}
|
|
|
|
public function getCoverUrl(int $externalId): ?string
|
|
{
|
|
if (empty($this->apiKey)) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
$response = Http::timeout(10)->get("{$this->baseUrl}/Games/Images", [
|
|
'apikey' => $this->apiKey,
|
|
'id' => $externalId,
|
|
'images_type' => 'boxart',
|
|
]);
|
|
|
|
if ($response->successful()) {
|
|
$images = $response->json('data.images') ?? [];
|
|
if (! empty($images[0]['filename'])) {
|
|
return "https://cdn.thegamesdb.net/images/original/{$images[0]['filename']}";
|
|
}
|
|
}
|
|
} catch (\Exception $e) {
|
|
// Log error
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public function getScreenshotUrl(int $externalId): ?string
|
|
{
|
|
if (empty($this->apiKey)) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
$response = Http::timeout(10)->get("{$this->baseUrl}/Games/Images", [
|
|
'apikey' => $this->apiKey,
|
|
'id' => $externalId,
|
|
'images_type' => 'screenshot',
|
|
]);
|
|
|
|
if ($response->successful()) {
|
|
$images = $response->json('data.images') ?? [];
|
|
if (! empty($images[0]['filename'])) {
|
|
return "https://cdn.thegamesdb.net/images/original/{$images[0]['filename']}";
|
|
}
|
|
}
|
|
} catch (\Exception $e) {
|
|
// Log error
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public function getImages(int $externalId): array
|
|
{
|
|
return array_filter([
|
|
'cover' => $this->getCoverUrl($externalId),
|
|
'screenshot' => $this->getScreenshotUrl($externalId),
|
|
]);
|
|
}
|
|
}
|