Files
citrus/app/Services/SpotifyService.php
T

253 lines
7.3 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class SpotifyService
{
protected ?string $accessToken = null;
public function __construct(
protected ?string $clientId = null,
protected ?string $clientSecret = null,
protected ?string $artistId = null,
) {
$this->clientId = $clientId ?? config('services.spotify.client_id');
$this->clientSecret = $clientSecret ?? config('services.spotify.client_secret');
$this->artistId = $artistId ?? config('services.spotify.artist_id');
}
public function isConfigured(): bool
{
return filled($this->clientId)
&& filled($this->clientSecret)
&& filled($this->artistId);
}
public function getArtistId(): ?string
{
return $this->artistId;
}
/**
* @return array<int, array<string, mixed>>
*/
public function getArtistAlbums(string $includeGroups = 'album,single'): array
{
$this->authenticate();
$albums = [];
$url = "https://api.spotify.com/v1/artists/{$this->artistId}/albums";
$params = [
'include_groups' => $includeGroups,
'limit' => 50,
'market' => config('services.spotify.market', 'TR'),
];
do {
$response = $this->client()->get($url, $params);
if ($response->failed()) {
Log::error('Spotify artist albums fetch failed', [
'status' => $response->status(),
'body' => $response->body(),
]);
throw new \RuntimeException($this->formatApiError(
__('music_productions.spotify_albums_fetch_failed'),
$response
));
}
$data = $response->json();
$items = $data['items'] ?? [];
foreach ($items as $item) {
$albums[$item['id']] = $item;
}
$url = $data['next'] ?? null;
$params = [];
} while ($url);
return array_values($albums);
}
/**
* @return array<string, mixed>|null
*/
public function getAlbum(string $albumId): ?array
{
$this->authenticate();
$response = $this->client()->get("https://api.spotify.com/v1/albums/{$albumId}", [
'market' => config('services.spotify.market', 'TR'),
]);
if ($response->failed()) {
Log::warning('Spotify album fetch failed', [
'album_id' => $albumId,
'status' => $response->status(),
'body' => $response->body(),
]);
return null;
}
return $response->json();
}
public function downloadCoverImage(?string $imageUrl, string $albumId): ?string
{
if (blank($imageUrl)) {
return null;
}
try {
$response = Http::timeout(30)->get($imageUrl);
if ($response->failed()) {
return null;
}
$extension = $this->guessImageExtension($response->header('Content-Type'));
$path = 'music-productions/covers/spotify-' . $albumId . '.' . $extension;
Storage::disk('public')->put($path, $response->body());
return $path;
} catch (\Throwable $exception) {
Log::warning('Spotify cover download failed', [
'album_id' => $albumId,
'message' => $exception->getMessage(),
]);
return null;
}
}
public function buildDefaultContent(array $album): string
{
$title = e($album['name'] ?? '');
$spotifyUrl = e($album['external_urls']['spotify'] ?? '');
$artistNames = collect($album['artists'] ?? [])
->pluck('name')
->filter()
->implode(', ');
$artistNames = e($artistNames);
$albumType = e($album['album_type'] ?? 'album');
$totalTracks = (int) ($album['total_tracks'] ?? 0);
$listenLabel = e(__('music_productions.spotify_listen_on_spotify'));
return <<<HTML
<p><strong>{$title}</strong> — {$artistNames}</p>
<p>{$albumType} · {$totalTracks} {$this->trackLabel($totalTracks)}</p>
<p><a href="{$spotifyUrl}" target="_blank" rel="noopener noreferrer">{$listenLabel}</a></p>
HTML;
}
protected function trackLabel(int $count): string
{
return $count === 1
? __('music_productions.spotify_track_singular')
: __('music_productions.spotify_track_plural');
}
protected function authenticate(): void
{
if ($this->accessToken) {
return;
}
if (! $this->isConfigured()) {
throw new \RuntimeException(__('music_productions.spotify_not_configured'));
}
$response = Http::asForm()
->withHeaders([
'Authorization' => 'Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret),
])
->post('https://accounts.spotify.com/api/token', [
'grant_type' => 'client_credentials',
]);
if ($response->failed()) {
Log::error('Spotify access token request failed', [
'status' => $response->status(),
'body' => $response->body(),
]);
throw new \RuntimeException($this->formatApiError(
__('music_productions.spotify_token_failed'),
$response
));
}
$this->accessToken = $response->json('access_token');
}
protected function client(): PendingRequest
{
return Http::withToken($this->accessToken)
->acceptJson()
->timeout(30);
}
protected function formatApiError(string $fallback, \Illuminate\Http\Client\Response $response): string
{
$body = trim($response->body());
$message = $body;
if (str_starts_with($body, '{')) {
$message = $response->json('error.message')
?? $response->json('error_description')
?? $body;
}
if (blank($message)) {
return $fallback;
}
if ($response->status() === 403 && str_contains(strtolower($message), 'premium')) {
return __('music_productions.spotify_premium_required', ['detail' => $message]);
}
return $fallback . ' (HTTP ' . $response->status() . ': ' . $message . ')';
}
protected function guessImageExtension(?string $contentType): string
{
return match ($contentType) {
'image/png' => 'png',
'image/webp' => 'webp',
'image/gif' => 'gif',
default => 'jpg',
};
}
public static function uniqueSlug(string $title, ?int $ignoreId = null): string
{
$baseSlug = Str::slug($title) ?: 'spotify-album';
$slug = $baseSlug;
$counter = 1;
while (
\App\Models\MusicProduction::withTrashed()
->when($ignoreId, fn ($query) => $query->where('id', '!=', $ignoreId))
->where('slug', $slug)
->exists()
) {
$slug = $baseSlug . '-' . $counter;
$counter++;
}
return $slug;
}
}