feat: integrate Spotify API for syncing music productions with new command and UI components

This commit is contained in:
Ümit Tunç
2026-05-20 22:31:41 +03:00
parent f35632ee0d
commit 751b9339f0
15 changed files with 666 additions and 9 deletions
@@ -0,0 +1,191 @@
<?php
namespace App\Console\Commands;
use App\Models\MusicProduction;
use App\Services\SpotifyService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class SyncSpotifyMusicProductions extends Command
{
protected $signature = 'spotify:sync-music-productions
{--artist= : Override Spotify artist ID}
{--dry-run : Show changes without writing to database}';
protected $description = 'Spotify sanatçı hesabından albüm ve single verilerini müzik prodüksiyonlarına senkronize eder';
public function handle(SpotifyService $spotifyService): int
{
if ($this->option('artist')) {
$spotifyService = new SpotifyService(
artistId: $this->option('artist'),
);
}
if (! $spotifyService->isConfigured()) {
$this->error(__('music_productions.spotify_not_configured'));
return Command::FAILURE;
}
$this->info(__('music_productions.spotify_sync_started'));
try {
$albumSummaries = $spotifyService->getArtistAlbums();
} catch (\Throwable $exception) {
$this->error($exception->getMessage());
return Command::FAILURE;
}
if (empty($albumSummaries)) {
$this->warn(__('music_productions.spotify_no_albums'));
return Command::SUCCESS;
}
$created = 0;
$updated = 0;
$dryRun = (bool) $this->option('dry-run');
foreach ($albumSummaries as $index => $albumSummary) {
$albumId = $albumSummary['id'] ?? null;
if (blank($albumId)) {
continue;
}
$album = $spotifyService->getAlbum($albumId) ?? $albumSummary;
$title = $album['name'] ?? __('music_productions.spotify_untitled_album');
$artistName = collect($album['artists'] ?? [])->pluck('name')->first();
$releaseDate = $this->parseReleaseDate($album['release_date'] ?? null, $album['release_date_precision'] ?? 'day');
$spotifyUrl = $album['external_urls']['spotify'] ?? null;
$coverUrl = collect($album['images'] ?? [])->first()['url'] ?? null;
$albumType = $album['album_type'] ?? 'album';
$production = $this->findMatchingProduction($albumId, $title);
$action = $production ? 'update' : 'create';
$this->line(sprintf(
'[%d/%d] %s: %s (%s)',
$index + 1,
count($albumSummaries),
$action === 'create' ? 'Yeni' : 'Güncelle',
$title,
$releaseDate?->format('Y-m-d') ?? '-'
));
if ($dryRun) {
continue;
}
$attributes = [
'spotify_album_id' => $albumId,
'spotify_url' => $spotifyUrl,
'spotify_cover_url' => $coverUrl,
'spotify_type' => $albumType,
'spotify_synced_at' => now(),
];
if (! $production) {
$attributes['title'] = $title;
$attributes['slug'] = SpotifyService::uniqueSlug($title);
$attributes['client_name'] = $artistName;
$attributes['production_date'] = $releaseDate;
$attributes['content'] = $spotifyService->buildDefaultContent($album);
$attributes['is_active'] = true;
$attributes['sort_order'] = 0;
$coverPath = $spotifyService->downloadCoverImage($coverUrl, $albumId);
if ($coverPath) {
$attributes['cover_image'] = $coverPath;
}
MusicProduction::create($attributes);
$created++;
continue;
}
if (blank($production->title)) {
$attributes['title'] = $title;
}
if (blank($production->client_name) && filled($artistName)) {
$attributes['client_name'] = $artistName;
}
if (blank($production->production_date) && $releaseDate) {
$attributes['production_date'] = $releaseDate;
}
if (blank($production->content)) {
$attributes['content'] = $spotifyService->buildDefaultContent($album);
}
if (blank($production->cover_image) && filled($coverUrl)) {
$coverPath = $spotifyService->downloadCoverImage($coverUrl, $albumId);
if ($coverPath) {
$attributes['cover_image'] = $coverPath;
}
}
$production->update($attributes);
$updated++;
usleep(150000);
}
$message = __('music_productions.spotify_sync_completed', [
'created' => $created,
'updated' => $updated,
'total' => count($albumSummaries),
]);
$this->info($message);
Log::info('Spotify music productions sync completed', [
'created' => $created,
'updated' => $updated,
'total' => count($albumSummaries),
'dry_run' => $dryRun,
]);
return Command::SUCCESS;
}
protected function findMatchingProduction(string $albumId, string $title): ?MusicProduction
{
$bySpotifyId = MusicProduction::withTrashed()
->where('spotify_album_id', $albumId)
->first();
if ($bySpotifyId) {
return $bySpotifyId->trashed() ? null : $bySpotifyId;
}
$slug = Str::slug($title);
$bySlug = MusicProduction::where('slug', '=', $slug, 'and')->first();
if ($bySlug) {
return $bySlug;
}
return MusicProduction::whereRaw('LOWER(title) = ?', [Str::lower($title)], 'and')->first();
}
protected function parseReleaseDate(?string $date, string $precision = 'day'): ?Carbon
{
if (blank($date)) {
return null;
}
return match ($precision) {
'year' => Carbon::createFromFormat('Y', $date)->startOfYear(),
'month' => Carbon::createFromFormat('Y-m', $date)->startOfMonth(),
default => Carbon::parse($date),
};
}
}
@@ -2,9 +2,14 @@
namespace App\Filament\Admin\Resources\MusicProductions\Pages;
use App\Console\Commands\SyncSpotifyMusicProductions;
use App\Filament\Admin\Resources\MusicProductions\MusicProductionResource;
use App\Services\SpotifyService;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Support\Facades\Artisan;
class ListMusicProductions extends ListRecords
{
@@ -18,6 +23,31 @@ class ListMusicProductions extends ListRecords
protected function getHeaderActions(): array
{
return [
Action::make('syncSpotify')
->label(__('music_productions.sync_spotify'))
->icon('heroicon-o-arrow-path')
->color('success')
->requiresConfirmation()
->modalHeading(__('music_productions.sync_spotify_heading'))
->modalDescription(__('music_productions.sync_spotify_description'))
->visible(fn (): bool => app(SpotifyService::class)->isConfigured())
->action(function (): void {
$exitCode = Artisan::call(SyncSpotifyMusicProductions::class);
if ($exitCode !== 0) {
Notification::make()
->title(__('music_productions.spotify_sync_failed'))
->danger()
->send();
return;
}
Notification::make()
->title(__('music_productions.spotify_sync_success'))
->success()
->send();
}),
CreateAction::make()
->label(__('music_productions.create')),
];
@@ -3,13 +3,16 @@
namespace App\Filament\Admin\Resources\MusicProductions\Schemas;
use App\Filament\Admin\Resources\Components\TranslationTabs;
use App\Models\MusicProduction;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Placeholder;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Illuminate\Support\Str;
class MusicProductionForm
{
@@ -30,7 +33,7 @@ class MusicProductionForm
if ($operation !== 'create') {
return;
}
$set('slug', \Str::slug($state));
$set('slug', Str::slug($state));
}),
TextInput::make('slug')
@@ -93,6 +96,33 @@ class MusicProductionForm
])
->columnSpan(1)
->collapsible(false),
Section::make(__('music_productions.spotify_section'))
->schema([
Placeholder::make('spotify_album_id_display')
->label(__('music_productions.spotify_album_id_field'))
->content(fn (?MusicProduction $record): string => $record?->spotify_album_id ?? '-'),
Placeholder::make('spotify_type_display')
->label(__('music_productions.spotify_type_field'))
->content(fn (?MusicProduction $record): string => $record?->spotify_type
? __('music_productions.spotify_type_' . $record->spotify_type, [], $record->spotify_type)
: '-'),
Placeholder::make('spotify_url_display')
->label(__('music_productions.spotify_url_field'))
->content(fn (?MusicProduction $record): string => $record?->spotify_url ?? '-'),
Placeholder::make('spotify_synced_at_display')
->label(__('music_productions.spotify_synced_at_field'))
->content(fn (?MusicProduction $record): string => $record?->spotify_synced_at
?->timezone(config('app.timezone'))
->format('d.m.Y H:i') ?? '-'),
])
->columnSpanFull()
->collapsible(true)
->collapsed(true)
->visible(fn (?MusicProduction $record): bool => filled($record?->spotify_album_id)),
// Alt Kısım - Galeri Görselleri
Section::make(__('music_productions.gallery_field'))
@@ -2,6 +2,7 @@
namespace App\Filament\Admin\Resources\MusicProductions\Tables;
use App\Models\MusicProduction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
@@ -21,7 +22,7 @@ class MusicProductionsTable
->columns([
ImageColumn::make('cover_image')
->label(__('music_productions.cover_image_field'))
->disk('public')
->getStateUsing(fn (MusicProduction $record): ?string => $record->cover_image_url)
->square()
->size(60),
@@ -47,6 +48,19 @@ class MusicProductionsTable
->label(__('music_productions.table_production_date'))
->date('d.m.Y')
->sortable(),
TextColumn::make('spotify_type')
->label(__('music_productions.spotify_type_field'))
->badge()
->formatStateUsing(fn (?string $state): string => filled($state)
? __('music_productions.spotify_type_' . $state, [], $state)
: '-')
->color(fn (?string $state): string => match ($state) {
'single' => 'info',
'album' => 'success',
default => 'gray',
})
->toggleable(),
ToggleColumn::make('is_active')
->label(__('music_productions.table_is_active'))
@@ -15,7 +15,7 @@ class MusicProductionController extends Controller
{
// Get Settings
$settings = new \stdClass();
$allSettings = Setting::where('is_active', true)->get();
$allSettings = Setting::where('is_active', '=', true, 'and')->get();
foreach ($allSettings as $setting) {
$settings->{$setting->key} = $setting->value;
}
@@ -78,7 +78,7 @@ class MusicProductionController extends Controller
// Get Settings
$settings = new \stdClass();
$allSettings = Setting::where('is_active', true)->get();
$allSettings = Setting::where('is_active', '=', true, 'and')->get();
foreach ($allSettings as $setting) {
$settings->{$setting->key} = $setting->value;
}
@@ -147,7 +147,7 @@ class MusicProductionController extends Controller
$meta = [
'title' => $production->translate('title'),
'description' => \Str::limit(strip_tags($production->translate('content')), 160),
'image' => $production->cover_image ? asset('storage/' . $production->cover_image) : null,
'image' => $production->cover_image_url,
];
return view('front.music-productions.show', compact('production', 'prev', 'next', 'settings', 'renderedHeader', 'renderedFooter', 'meta'));
+19
View File
@@ -16,6 +16,11 @@ class MusicProduction extends Model
protected $fillable = [
'title',
'slug',
'spotify_album_id',
'spotify_url',
'spotify_cover_url',
'spotify_type',
'spotify_synced_at',
'cover_image',
'content',
'client_name',
@@ -36,6 +41,7 @@ class MusicProduction extends Model
protected $casts = [
'production_date' => 'date',
'spotify_synced_at' => 'datetime',
'gallery' => 'array',
'is_active' => 'boolean',
'sort_order' => 'integer',
@@ -51,10 +57,23 @@ class MusicProduction extends Model
if ($this->cover_image) {
return asset('storage/' . $this->cover_image);
}
if ($this->spotify_cover_url) {
return $this->spotify_cover_url;
}
return null;
}
public function getDisplayCoverImageAttribute(): ?string
{
if ($this->cover_image) {
return $this->cover_image;
}
return null;
}
public function scopeActive($query)
{
return $query->where('is_active', true);
+252
View File
@@ -0,0 +1,252 @@
<?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;
}
}