461 lines
14 KiB
PHP
461 lines
14 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;
|
|
use Carbon\Carbon;
|
|
|
|
class YouTubeService
|
|
{
|
|
protected ?string $resolvedTopicChannelId = null;
|
|
|
|
protected ?string $resolvedReleasesSource = null;
|
|
|
|
public function __construct(
|
|
protected ?string $apiKey = null,
|
|
protected ?string $channelId = null,
|
|
protected ?string $topicChannelId = null,
|
|
protected ?string $playlistId = null,
|
|
) {
|
|
$this->apiKey = $apiKey ?? config('services.youtube.api_key');
|
|
$this->channelId = $channelId ?? config('services.youtube.channel_id');
|
|
$this->topicChannelId = $topicChannelId ?? config('services.youtube.topic_channel_id');
|
|
$this->playlistId = $playlistId ?? config('services.youtube.playlist_id');
|
|
}
|
|
|
|
public function isConfigured(): bool
|
|
{
|
|
return filled($this->apiKey)
|
|
&& (filled($this->channelId) || filled($this->topicChannelId) || filled($this->playlistId));
|
|
}
|
|
|
|
public function getReleasesSourceLabel(): string
|
|
{
|
|
$this->resolveReleasesPlaylistId();
|
|
|
|
return $this->resolvedReleasesSource ?? '-';
|
|
}
|
|
|
|
public function resolveReleasesPlaylistId(): ?string
|
|
{
|
|
if (filled($this->playlistId)) {
|
|
$this->resolvedReleasesSource = 'playlist:' . $this->playlistId;
|
|
|
|
return $this->playlistId;
|
|
}
|
|
|
|
$topicChannelId = $this->resolveTopicChannelId();
|
|
|
|
if (filled($topicChannelId)) {
|
|
$playlistId = $this->channelToUploadsPlaylistId($topicChannelId);
|
|
$this->resolvedReleasesSource = 'topic:' . $topicChannelId;
|
|
|
|
return $playlistId;
|
|
}
|
|
|
|
if (filled($this->channelId)) {
|
|
Log::warning('YouTube Topic channel not found, falling back to main channel uploads', [
|
|
'channel_id' => $this->channelId,
|
|
]);
|
|
|
|
$playlistId = $this->channelToUploadsPlaylistId($this->channelId);
|
|
$this->resolvedReleasesSource = 'main:' . $this->channelId;
|
|
|
|
return $playlistId;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public function resolveTopicChannelId(): ?string
|
|
{
|
|
if ($this->resolvedTopicChannelId !== null) {
|
|
return $this->resolvedTopicChannelId ?: null;
|
|
}
|
|
|
|
if (filled($this->topicChannelId)) {
|
|
$this->resolvedTopicChannelId = $this->topicChannelId;
|
|
|
|
return $this->resolvedTopicChannelId;
|
|
}
|
|
|
|
if (blank($this->channelId)) {
|
|
$this->resolvedTopicChannelId = '';
|
|
|
|
return null;
|
|
}
|
|
|
|
$this->resolvedTopicChannelId = $this->discoverTopicChannelId($this->channelId) ?? '';
|
|
|
|
return $this->resolvedTopicChannelId ?: null;
|
|
}
|
|
|
|
/**
|
|
* @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;
|
|
$distributorFilter = config('services.youtube.distributor_filter');
|
|
|
|
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,
|
|
'source' => $this->resolvedReleasesSource,
|
|
'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, $distributorFilter);
|
|
|
|
if ($normalized) {
|
|
$releases[$normalized['video_id']] = $normalized;
|
|
}
|
|
}
|
|
|
|
$pageToken = $data['nextPageToken'] ?? null;
|
|
} while ($pageToken);
|
|
|
|
return array_values($releases);
|
|
}
|
|
|
|
protected function discoverTopicChannelId(string $mainChannelId): ?string
|
|
{
|
|
$channel = $this->getChannel($mainChannelId);
|
|
|
|
if (! $channel) {
|
|
return null;
|
|
}
|
|
|
|
$artistTitle = trim($channel['snippet']['title'] ?? '');
|
|
|
|
if (blank($artistTitle)) {
|
|
return null;
|
|
}
|
|
|
|
$expectedTopicTitle = $artistTitle . ' - Topic';
|
|
$mainThumbnail = $channel['snippet']['thumbnails']['default']['url'] ?? null;
|
|
|
|
$response = $this->client()->get('https://www.googleapis.com/youtube/v3/search', [
|
|
'key' => $this->apiKey,
|
|
'part' => 'snippet',
|
|
'type' => 'channel',
|
|
'q' => $expectedTopicTitle,
|
|
'maxResults' => 10,
|
|
]);
|
|
|
|
if ($response->failed()) {
|
|
Log::warning('YouTube topic channel search failed', [
|
|
'channel_id' => $mainChannelId,
|
|
'query' => $expectedTopicTitle,
|
|
'status' => $response->status(),
|
|
]);
|
|
|
|
return null;
|
|
}
|
|
|
|
$topicCandidates = [];
|
|
|
|
foreach ($response->json('items') ?? [] as $item) {
|
|
$channelId = $item['snippet']['channelId'] ?? $item['id']['channelId'] ?? null;
|
|
$title = trim($item['snippet']['title'] ?? '');
|
|
|
|
if (blank($channelId) || $channelId === $mainChannelId) {
|
|
continue;
|
|
}
|
|
|
|
if ($this->titlesMatch($title, $expectedTopicTitle)) {
|
|
Log::info('YouTube topic channel resolved by exact title match', [
|
|
'main_channel_id' => $mainChannelId,
|
|
'topic_channel_id' => $channelId,
|
|
'title' => $title,
|
|
]);
|
|
|
|
return $channelId;
|
|
}
|
|
|
|
if (str_ends_with($title, ' - Topic')) {
|
|
$topicCandidates[] = [
|
|
'channel_id' => $channelId,
|
|
'title' => $title,
|
|
'thumbnail' => $item['snippet']['thumbnails']['default']['url'] ?? null,
|
|
];
|
|
}
|
|
}
|
|
|
|
foreach ($topicCandidates as $candidate) {
|
|
if ($this->thumbnailsMatch($mainThumbnail, $candidate['thumbnail'])) {
|
|
Log::info('YouTube topic channel resolved by avatar match', [
|
|
'main_channel_id' => $mainChannelId,
|
|
'topic_channel_id' => $candidate['channel_id'],
|
|
'title' => $candidate['title'],
|
|
]);
|
|
|
|
return $candidate['channel_id'];
|
|
}
|
|
}
|
|
|
|
Log::warning('YouTube topic channel could not be resolved safely', [
|
|
'main_channel_id' => $mainChannelId,
|
|
'expected_title' => $expectedTopicTitle,
|
|
'candidates' => collect($topicCandidates)->pluck('title')->all(),
|
|
]);
|
|
|
|
return null;
|
|
}
|
|
|
|
protected function titlesMatch(string $left, string $right): bool
|
|
{
|
|
return mb_strtolower(trim($left)) === mb_strtolower(trim($right));
|
|
}
|
|
|
|
protected function thumbnailsMatch(?string $left, ?string $right): bool
|
|
{
|
|
if (blank($left) || blank($right)) {
|
|
return false;
|
|
}
|
|
|
|
return $this->normalizeThumbnailUrl($left) === $this->normalizeThumbnailUrl($right);
|
|
}
|
|
|
|
protected function normalizeThumbnailUrl(string $url): string
|
|
{
|
|
$path = parse_url($url, PHP_URL_PATH) ?: $url;
|
|
|
|
return preg_replace('/=s\d+-/', '=s88-', $path) ?? $path;
|
|
}
|
|
|
|
/**
|
|
* @return array<string, mixed>|null
|
|
*/
|
|
protected function getChannel(string $channelId): ?array
|
|
{
|
|
$response = $this->client()->get('https://www.googleapis.com/youtube/v3/channels', [
|
|
'key' => $this->apiKey,
|
|
'id' => $channelId,
|
|
'part' => 'snippet,contentDetails',
|
|
]);
|
|
|
|
if ($response->failed()) {
|
|
return null;
|
|
}
|
|
|
|
return $response->json('items.0');
|
|
}
|
|
|
|
protected function channelToUploadsPlaylistId(string $channelId): string
|
|
{
|
|
if (str_starts_with($channelId, 'UU') || str_starts_with($channelId, 'PL')) {
|
|
return $channelId;
|
|
}
|
|
|
|
if (str_starts_with($channelId, 'UC')) {
|
|
return 'UU' . substr($channelId, 2);
|
|
}
|
|
|
|
return $channelId;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $item
|
|
* @return array<string, mixed>|null
|
|
*/
|
|
protected function normalizeReleaseItem(array $item, ?string $distributorFilter = null): ?array
|
|
{
|
|
$snippet = $item['snippet'] ?? [];
|
|
$videoId = $snippet['resourceId']['videoId'] ?? null;
|
|
$title = trim($snippet['title'] ?? '');
|
|
$description = trim($snippet['description'] ?? '');
|
|
|
|
if (blank($videoId) || blank($title)) {
|
|
return null;
|
|
}
|
|
|
|
if (in_array($title, ['Private video', 'Deleted video', 'Gizli video', 'Silinmiş video'], true)) {
|
|
return null;
|
|
}
|
|
|
|
if (filled($distributorFilter) && ! str_contains($description, $distributorFilter)) {
|
|
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' => $description,
|
|
'cover_url' => $coverUrl,
|
|
'published_at' => $snippet['publishedAt'] ?? null,
|
|
'release_date' => $this->parseReleaseDate($description, $snippet['publishedAt'] ?? null),
|
|
'youtube_url' => 'https://www.youtube.com/watch?v=' . $videoId,
|
|
];
|
|
}
|
|
|
|
public function parseReleaseDate(string $description, ?string $publishedAt = null): ?string
|
|
{
|
|
if (preg_match('/Released on:\s*(\d{4}-\d{2}-\d{2})/i', $description, $matches)) {
|
|
return Carbon::parse($matches[1])->toDateString();
|
|
}
|
|
|
|
if (preg_match('/Release date:\s*(\d{4}-\d{2}-\d{2})/i', $description, $matches)) {
|
|
return Carbon::parse($matches[1])->toDateString();
|
|
}
|
|
|
|
if (filled($publishedAt)) {
|
|
return Carbon::parse($publishedAt)->toDateString();
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|