feat: implement YouTube API integration for syncing releases with music productions, including new command and UI components
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\MusicProduction;
|
||||
use App\Services\YouTubeService;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class SyncYoutubeReleases extends Command
|
||||
{
|
||||
protected $signature = 'youtube:sync-releases
|
||||
{--channel= : Override YouTube channel ID}
|
||||
{--playlist= : Override Releases playlist ID}
|
||||
{--dry-run : Show changes without writing to database}';
|
||||
|
||||
protected $description = 'YouTube kanalının Releases (Yayınlar) listesindeki art track kayıtlarını müzik prodüksiyonlarına senkronize eder';
|
||||
|
||||
public function handle(YouTubeService $youTubeService): int
|
||||
{
|
||||
if ($this->option('channel') || $this->option('playlist')) {
|
||||
$youTubeService = new YouTubeService(
|
||||
channelId: $this->option('channel') ?? config('services.youtube.channel_id'),
|
||||
playlistId: $this->option('playlist') ?? config('services.youtube.playlist_id'),
|
||||
);
|
||||
}
|
||||
|
||||
if (! $youTubeService->isConfigured()) {
|
||||
$this->error(__('music_productions.youtube_not_configured'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$this->info(__('music_productions.youtube_sync_started'));
|
||||
$this->line('Playlist ID: ' . $youTubeService->resolveReleasesPlaylistId());
|
||||
|
||||
try {
|
||||
$releases = $youTubeService->getReleases();
|
||||
} catch (\Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
if (empty($releases)) {
|
||||
$this->warn(__('music_productions.youtube_no_releases'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$created = 0;
|
||||
$updated = 0;
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
|
||||
foreach ($releases as $index => $release) {
|
||||
$videoId = $release['video_id'] ?? null;
|
||||
|
||||
if (blank($videoId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$title = $release['title'] ?? __('music_productions.youtube_untitled_release');
|
||||
$releaseDate = filled($release['published_at'] ?? null)
|
||||
? Carbon::parse($release['published_at'])
|
||||
: null;
|
||||
$youtubeUrl = $release['youtube_url'] ?? null;
|
||||
$coverUrl = $release['cover_url'] ?? null;
|
||||
$description = $release['description'] ?? '';
|
||||
|
||||
$production = $this->findMatchingProduction($videoId, $title);
|
||||
|
||||
$action = $production ? 'update' : 'create';
|
||||
$this->line(sprintf(
|
||||
'[%d/%d] %s: %s (%s)',
|
||||
$index + 1,
|
||||
count($releases),
|
||||
$action === 'create' ? 'Yeni' : 'Güncelle',
|
||||
$title,
|
||||
$releaseDate?->format('Y-m-d') ?? '-'
|
||||
));
|
||||
|
||||
if ($dryRun) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$attributes = [
|
||||
'youtube_video_id' => $videoId,
|
||||
'youtube_url' => $youtubeUrl,
|
||||
'youtube_cover_url' => $coverUrl,
|
||||
'youtube_description' => $description,
|
||||
'youtube_synced_at' => now(),
|
||||
];
|
||||
|
||||
if (! $production) {
|
||||
$attributes['title'] = $title;
|
||||
$attributes['slug'] = YouTubeService::uniqueSlug($title);
|
||||
$attributes['production_date'] = $releaseDate;
|
||||
$attributes['content'] = $youTubeService->buildDefaultContent($release);
|
||||
$attributes['is_active'] = true;
|
||||
$attributes['sort_order'] = 0;
|
||||
|
||||
$coverPath = $youTubeService->downloadCoverImage($coverUrl, $videoId);
|
||||
if ($coverPath) {
|
||||
$attributes['cover_image'] = $coverPath;
|
||||
}
|
||||
|
||||
MusicProduction::create($attributes);
|
||||
$created++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (blank($production->title)) {
|
||||
$attributes['title'] = $title;
|
||||
}
|
||||
|
||||
if (blank($production->production_date) && $releaseDate) {
|
||||
$attributes['production_date'] = $releaseDate;
|
||||
}
|
||||
|
||||
if (blank($production->content)) {
|
||||
$attributes['content'] = $youTubeService->buildDefaultContent($release);
|
||||
}
|
||||
|
||||
if (blank($production->cover_image) && filled($coverUrl)) {
|
||||
$coverPath = $youTubeService->downloadCoverImage($coverUrl, $videoId);
|
||||
if ($coverPath) {
|
||||
$attributes['cover_image'] = $coverPath;
|
||||
}
|
||||
}
|
||||
|
||||
$production->update($attributes);
|
||||
$updated++;
|
||||
|
||||
usleep(150000);
|
||||
}
|
||||
|
||||
$message = __('music_productions.youtube_sync_completed', [
|
||||
'created' => $created,
|
||||
'updated' => $updated,
|
||||
'total' => count($releases),
|
||||
]);
|
||||
|
||||
$this->info($message);
|
||||
Log::info('YouTube releases sync completed', [
|
||||
'created' => $created,
|
||||
'updated' => $updated,
|
||||
'total' => count($releases),
|
||||
'dry_run' => $dryRun,
|
||||
]);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
protected function findMatchingProduction(string $videoId, string $title): ?MusicProduction
|
||||
{
|
||||
$byYoutubeId = MusicProduction::withTrashed()
|
||||
->where('youtube_video_id', $videoId)
|
||||
->first();
|
||||
|
||||
if ($byYoutubeId) {
|
||||
return $byYoutubeId->trashed() ? null : $byYoutubeId;
|
||||
}
|
||||
|
||||
$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();
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,10 @@
|
||||
namespace App\Filament\Admin\Resources\MusicProductions\Pages;
|
||||
|
||||
use App\Console\Commands\SyncSpotifyMusicProductions;
|
||||
use App\Console\Commands\SyncYoutubeReleases;
|
||||
use App\Filament\Admin\Resources\MusicProductions\MusicProductionResource;
|
||||
use App\Services\SpotifyService;
|
||||
use App\Services\YouTubeService;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Notifications\Notification;
|
||||
@@ -48,6 +50,31 @@ class ListMusicProductions extends ListRecords
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
Action::make('syncYoutube')
|
||||
->label(__('music_productions.sync_youtube'))
|
||||
->icon('heroicon-o-play')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalHeading(__('music_productions.sync_youtube_heading'))
|
||||
->modalDescription(__('music_productions.sync_youtube_description'))
|
||||
->visible(fn (): bool => app(YouTubeService::class)->isConfigured())
|
||||
->action(function (): void {
|
||||
$exitCode = Artisan::call(SyncYoutubeReleases::class);
|
||||
|
||||
if ($exitCode !== 0) {
|
||||
Notification::make()
|
||||
->title(__('music_productions.youtube_sync_failed'))
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title(__('music_productions.youtube_sync_success'))
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
CreateAction::make()
|
||||
->label(__('music_productions.create')),
|
||||
];
|
||||
|
||||
@@ -123,6 +123,33 @@ class MusicProductionForm
|
||||
->collapsible(true)
|
||||
->collapsed(true)
|
||||
->visible(fn (?MusicProduction $record): bool => filled($record?->spotify_album_id)),
|
||||
|
||||
Section::make(__('music_productions.youtube_section'))
|
||||
->schema([
|
||||
Placeholder::make('youtube_video_id_display')
|
||||
->label(__('music_productions.youtube_video_id_field'))
|
||||
->content(fn (?MusicProduction $record): string => $record?->youtube_video_id ?? '-'),
|
||||
|
||||
Placeholder::make('youtube_url_display')
|
||||
->label(__('music_productions.youtube_url_field'))
|
||||
->content(fn (?MusicProduction $record): string => $record?->youtube_url ?? '-'),
|
||||
|
||||
Placeholder::make('youtube_description_display')
|
||||
->label(__('music_productions.youtube_description_field'))
|
||||
->content(fn (?MusicProduction $record): string => filled($record?->youtube_description)
|
||||
? \Illuminate\Support\Str::limit($record->youtube_description, 500)
|
||||
: '-'),
|
||||
|
||||
Placeholder::make('youtube_synced_at_display')
|
||||
->label(__('music_productions.youtube_synced_at_field'))
|
||||
->content(fn (?MusicProduction $record): string => $record?->youtube_synced_at
|
||||
?->timezone(config('app.timezone'))
|
||||
->format('d.m.Y H:i') ?? '-'),
|
||||
])
|
||||
->columnSpanFull()
|
||||
->collapsible(true)
|
||||
->collapsed(true)
|
||||
->visible(fn (?MusicProduction $record): bool => filled($record?->youtube_video_id)),
|
||||
|
||||
// Alt Kısım - Galeri Görselleri
|
||||
Section::make(__('music_productions.gallery_field'))
|
||||
|
||||
@@ -21,6 +21,11 @@ class MusicProduction extends Model
|
||||
'spotify_cover_url',
|
||||
'spotify_type',
|
||||
'spotify_synced_at',
|
||||
'youtube_video_id',
|
||||
'youtube_url',
|
||||
'youtube_cover_url',
|
||||
'youtube_description',
|
||||
'youtube_synced_at',
|
||||
'cover_image',
|
||||
'content',
|
||||
'client_name',
|
||||
@@ -42,6 +47,7 @@ class MusicProduction extends Model
|
||||
protected $casts = [
|
||||
'production_date' => 'date',
|
||||
'spotify_synced_at' => 'datetime',
|
||||
'youtube_synced_at' => 'datetime',
|
||||
'gallery' => 'array',
|
||||
'is_active' => 'boolean',
|
||||
'sort_order' => 'integer',
|
||||
@@ -61,7 +67,11 @@ class MusicProduction extends Model
|
||||
if ($this->spotify_cover_url) {
|
||||
return $this->spotify_cover_url;
|
||||
}
|
||||
|
||||
|
||||
if ($this->youtube_cover_url) {
|
||||
return $this->youtube_cover_url;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
<?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 YouTubeService
|
||||
{
|
||||
public function __construct(
|
||||
protected ?string $apiKey = null,
|
||||
protected ?string $channelId = null,
|
||||
protected ?string $playlistId = null,
|
||||
) {
|
||||
$this->apiKey = $apiKey ?? config('services.youtube.api_key');
|
||||
$this->channelId = $channelId ?? config('services.youtube.channel_id');
|
||||
$this->playlistId = $playlistId ?? config('services.youtube.playlist_id');
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return filled($this->apiKey)
|
||||
&& (filled($this->channelId) || filled($this->playlistId));
|
||||
}
|
||||
|
||||
public function resolveReleasesPlaylistId(): ?string
|
||||
{
|
||||
if (filled($this->playlistId)) {
|
||||
return $this->playlistId;
|
||||
}
|
||||
|
||||
$channelId = $this->channelId;
|
||||
|
||||
if (blank($channelId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (str_starts_with($channelId, 'UC')) {
|
||||
return 'UU' . substr($channelId, 2);
|
||||
}
|
||||
|
||||
return $channelId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function getReleases(): array
|
||||
{
|
||||
$playlistId = $this->resolveReleasesPlaylistId();
|
||||
|
||||
if (blank($playlistId)) {
|
||||
throw new \RuntimeException(__('music_productions.youtube_playlist_not_resolved'));
|
||||
}
|
||||
|
||||
$releases = [];
|
||||
$pageToken = null;
|
||||
|
||||
do {
|
||||
$params = [
|
||||
'key' => $this->apiKey,
|
||||
'playlistId' => $playlistId,
|
||||
'part' => 'snippet',
|
||||
'maxResults' => 50,
|
||||
];
|
||||
|
||||
if ($pageToken) {
|
||||
$params['pageToken'] = $pageToken;
|
||||
}
|
||||
|
||||
$response = $this->client()->get('https://www.googleapis.com/youtube/v3/playlistItems', $params);
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::error('YouTube releases fetch failed', [
|
||||
'playlist_id' => $playlistId,
|
||||
'status' => $response->status(),
|
||||
'body' => $response->body(),
|
||||
]);
|
||||
|
||||
throw new \RuntimeException($this->formatApiError(
|
||||
__('music_productions.youtube_releases_fetch_failed'),
|
||||
$response
|
||||
));
|
||||
}
|
||||
|
||||
$data = $response->json();
|
||||
$items = $data['items'] ?? [];
|
||||
|
||||
foreach ($items as $item) {
|
||||
$normalized = $this->normalizeReleaseItem($item);
|
||||
|
||||
if ($normalized) {
|
||||
$releases[$normalized['video_id']] = $normalized;
|
||||
}
|
||||
}
|
||||
|
||||
$pageToken = $data['nextPageToken'] ?? null;
|
||||
} while ($pageToken);
|
||||
|
||||
return array_values($releases);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $item
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
protected function normalizeReleaseItem(array $item): ?array
|
||||
{
|
||||
$snippet = $item['snippet'] ?? [];
|
||||
$videoId = $snippet['resourceId']['videoId'] ?? null;
|
||||
$title = trim($snippet['title'] ?? '');
|
||||
|
||||
if (blank($videoId) || blank($title)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (in_array($title, ['Private video', 'Deleted video', 'Gizli video', 'Silinmiş video'], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$thumbnails = $snippet['thumbnails'] ?? [];
|
||||
$coverUrl = $thumbnails['maxres']['url']
|
||||
?? $thumbnails['standard']['url']
|
||||
?? $thumbnails['high']['url']
|
||||
?? $thumbnails['medium']['url']
|
||||
?? $thumbnails['default']['url']
|
||||
?? null;
|
||||
|
||||
return [
|
||||
'video_id' => $videoId,
|
||||
'title' => $title,
|
||||
'description' => trim($snippet['description'] ?? ''),
|
||||
'cover_url' => $coverUrl,
|
||||
'published_at' => $snippet['publishedAt'] ?? null,
|
||||
'youtube_url' => 'https://www.youtube.com/watch?v=' . $videoId,
|
||||
];
|
||||
}
|
||||
|
||||
public function downloadCoverImage(?string $imageUrl, string $videoId): ?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/youtube-' . $videoId . '.' . $extension;
|
||||
|
||||
Storage::disk('public')->put($path, $response->body());
|
||||
|
||||
return $path;
|
||||
} catch (\Throwable $exception) {
|
||||
Log::warning('YouTube cover download failed', [
|
||||
'video_id' => $videoId,
|
||||
'message' => $exception->getMessage(),
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function buildDefaultContent(array $release): string
|
||||
{
|
||||
$title = e($release['title'] ?? '');
|
||||
$youtubeUrl = e($release['youtube_url'] ?? '');
|
||||
$description = trim($release['description'] ?? '');
|
||||
$listenLabel = e(__('music_productions.youtube_watch_on_youtube'));
|
||||
|
||||
$descriptionHtml = filled($description)
|
||||
? '<p>' . nl2br(e($description)) . '</p>'
|
||||
: '';
|
||||
|
||||
return <<<HTML
|
||||
<p><strong>{$title}</strong></p>
|
||||
{$descriptionHtml}
|
||||
<p><a href="{$youtubeUrl}" target="_blank" rel="noopener noreferrer">{$listenLabel}</a></p>
|
||||
HTML;
|
||||
}
|
||||
|
||||
protected function client(): PendingRequest
|
||||
{
|
||||
$request = Http::acceptJson()->timeout(30);
|
||||
|
||||
$referer = config('services.youtube.api_referer');
|
||||
|
||||
if (filled($referer)) {
|
||||
$request = $request->withHeaders([
|
||||
'Referer' => rtrim($referer, '/') . '/',
|
||||
]);
|
||||
}
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
protected function formatApiError(string $fallback, \Illuminate\Http\Client\Response $response): string
|
||||
{
|
||||
$message = $response->json('error.message') ?? trim($response->body());
|
||||
|
||||
if (blank($message)) {
|
||||
return $fallback;
|
||||
}
|
||||
|
||||
if ($response->status() === 403 && str_contains(strtolower($message), 'referer')) {
|
||||
return __('music_productions.youtube_referrer_blocked', [
|
||||
'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) ?: 'youtube-release';
|
||||
$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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user