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
{$albumType} · {$totalTracks} {$this->trackLabel($totalTracks)}
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; } }