trypost/app/Http/Controllers/Auth/YouTubeController.php

350 lines
14 KiB
PHP
Raw Normal View History

2026-01-15 17:24:39 +00:00
<?php
declare(strict_types=1);
2026-01-15 17:24:39 +00:00
namespace App\Http\Controllers\Auth;
use App\Enums\SocialAccount\Platform as SocialPlatform;
use App\Enums\SocialAccount\Status;
2026-01-15 17:24:39 +00:00
use App\Models\Workspace;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
2026-01-15 17:24:39 +00:00
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Inertia\Inertia;
2026-01-15 17:24:39 +00:00
use Laravel\Socialite\Facades\Socialite;
use Symfony\Component\HttpFoundation\Response;
class YouTubeController extends SocialController
{
protected string $driver = 'google';
protected SocialPlatform $platform = SocialPlatform::YouTube;
protected array $scopes = [
'https://www.googleapis.com/auth/youtube.upload',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/yt-analytics.readonly',
2026-01-15 17:24:39 +00:00
];
public function connect(Request $request): Response|RedirectResponse
2026-01-15 17:24:39 +00:00
{
$this->ensurePlatformEnabled();
$workspace = $request->user()->currentWorkspace;
if (! $workspace) {
return redirect()->route('app.workspaces.create');
}
2026-01-15 17:24:39 +00:00
$this->authorize('manageAccounts', $workspace);
$this->ensureSocialAccountLimit($workspace);
2026-01-15 17:24:39 +00:00
$existingAccount = $workspace->socialAccounts()
->where('platform', $this->platform->value)
->first();
if ($existingAccount && ! $existingAccount->isDisconnected()) {
session()->flash('flash.banner', __('accounts.flash.already_connected'));
session()->flash('flash.bannerStyle', 'danger');
return back();
2026-01-15 17:24:39 +00:00
}
session([
'social_connect_workspace' => $workspace->id,
'social_reconnect_id' => $existingAccount?->id,
'social_connect_onboarding' => $request->boolean('onboarding'),
]);
2026-01-15 17:24:39 +00:00
return $this->redirectToGoogle();
2026-01-15 17:24:39 +00:00
}
public function callback(Request $request): View|RedirectResponse
2026-01-15 17:24:39 +00:00
{
$workspaceId = session('social_connect_workspace');
if (! $workspaceId) {
return $this->popupCallback(false, 'Session expired. Please try again.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
$workspace = Workspace::find($workspaceId);
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
return $this->popupCallback(false, 'Workspace not found.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
$reconnectId = session('social_reconnect_id');
$existingAccount = $reconnectId ? $workspace->socialAccounts()->find($reconnectId) : null;
// If account exists and is connected, don't allow duplicate
if (! $existingAccount && $workspace->hasConnectedPlatform($this->platform->value)) {
return $this->popupCallback(false, 'This platform is already connected.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
try {
$socialUser = Socialite::driver($this->driver)->user();
// Fetch the channels the user authorized
$channels = $this->fetchChannels($socialUser->token);
if (empty($channels)) {
return $this->popupCallback(false, 'No YouTube channels found. Please create a channel first.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
// If only one channel, connect directly (most common case)
if (count($channels) === 1) {
$channel = $channels[0];
$avatarPath = uploadFromUrl(data_get($channel, 'thumbnail'));
2026-01-15 17:24:39 +00:00
if ($existingAccount) {
// Reconnect existing account
$existingAccount->update([
'platform_user_id' => data_get($channel, 'id'),
'username' => ltrim(data_get($channel, 'custom_url', data_get($channel, 'id')), '@'),
'display_name' => data_get($channel, 'title'),
'avatar_url' => $avatarPath,
'access_token' => $socialUser->token,
'refresh_token' => $socialUser->refreshToken,
'token_expires_at' => $socialUser->expiresIn ? now()->addSeconds($socialUser->expiresIn) : null,
'scopes' => $this->scopes,
'meta' => [
'channel_id' => data_get($channel, 'id'),
'google_user_id' => $socialUser->getId(),
],
]);
$existingAccount->markAsConnected();
session()->forget('social_reconnect_id');
return $this->popupCallback(true, 'YouTube channel reconnected!', $this->platform->value);
}
// Create new account
2026-01-15 17:24:39 +00:00
$workspace->socialAccounts()->create([
'platform' => $this->platform->value,
'platform_user_id' => data_get($channel, 'id'),
'username' => ltrim(data_get($channel, 'custom_url', data_get($channel, 'id')), '@'),
'display_name' => data_get($channel, 'title'),
2026-01-15 17:24:39 +00:00
'avatar_url' => $avatarPath,
'access_token' => $socialUser->token,
'refresh_token' => $socialUser->refreshToken,
'token_expires_at' => $socialUser->expiresIn ? now()->addSeconds($socialUser->expiresIn) : null,
'scopes' => $this->scopes,
'status' => Status::Connected,
2026-01-15 17:24:39 +00:00
'meta' => [
'channel_id' => data_get($channel, 'id'),
2026-01-15 17:24:39 +00:00
'google_user_id' => $socialUser->getId(),
],
]);
session()->forget('social_reconnect_id');
2026-01-15 17:24:39 +00:00
return $this->popupCallback(true, 'YouTube channel connected!', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
// Multiple channels - store data and show selection screen
session([
'youtube_oauth' => [
'access_token' => $socialUser->token,
'refresh_token' => $socialUser->refreshToken,
'expires_in' => $socialUser->expiresIn,
'user_id' => $socialUser->getId(),
'reconnect_id' => $reconnectId,
2026-01-15 17:24:39 +00:00
],
]);
return redirect()->route('app.social.youtube.select-channel');
2026-01-15 17:24:39 +00:00
} catch (\Exception $e) {
Log::error('YouTube OAuth Error', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return $this->popupCallback(false, 'Error connecting account. Please try again.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
}
public function selectChannel(Request $request)
{
$oauthData = session('youtube_oauth');
$workspaceId = session('social_connect_workspace');
if (! $oauthData || ! $workspaceId) {
session()->flash('flash.banner', __('accounts.flash.session_expired'));
session()->flash('flash.bannerStyle', 'danger');
return redirect()->route('app.accounts');
2026-01-15 17:24:39 +00:00
}
$workspace = Workspace::find($workspaceId);
if (! $workspace) {
session()->flash('flash.banner', __('accounts.flash.workspace_not_found'));
session()->flash('flash.bannerStyle', 'danger');
return redirect()->route('app.accounts');
2026-01-15 17:24:39 +00:00
}
// Fetch YouTube channels
$channels = $this->fetchChannels(data_get($oauthData, 'access_token'));
2026-01-15 17:24:39 +00:00
if (empty($channels)) {
$redirectRoute = $this->getRedirectRoute();
$this->forgetSocialConnectSession();
session()->forget('youtube_oauth');
2026-01-15 17:24:39 +00:00
session()->flash('flash.banner', __('accounts.flash.no_youtube_channels'));
session()->flash('flash.bannerStyle', 'danger');
return redirect()->route($redirectRoute);
2026-01-15 17:24:39 +00:00
}
return inertia('accounts/YouTubeChannelSelect', [
'workspace' => $workspace,
'channels' => $channels,
]);
}
public function select(Request $request): View
2026-01-15 17:24:39 +00:00
{
$request->validate([
'channel_id' => 'required|string',
]);
$oauthData = session('youtube_oauth');
$workspaceId = session('social_connect_workspace');
if (! $oauthData || ! $workspaceId) {
return $this->popupCallback(false, 'Session expired. Please try again.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
$workspace = Workspace::find($workspaceId);
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
return $this->popupCallback(false, 'Workspace not found.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
try {
$channels = $this->fetchChannels(data_get($oauthData, 'access_token'));
2026-01-15 17:24:39 +00:00
$selectedChannel = collect($channels)->firstWhere('id', $request->channel_id);
if (! $selectedChannel) {
return $this->popupCallback(false, 'Channel not found.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
$avatarPath = uploadFromUrl(data_get($selectedChannel, 'thumbnail'));
$reconnectId = data_get($oauthData, 'reconnect_id', null);
if ($reconnectId) {
// Reconnect existing account
$existingAccount = $workspace->socialAccounts()->find($reconnectId);
if ($existingAccount) {
$existingAccount->update([
'platform_user_id' => data_get($selectedChannel, 'id'),
'username' => ltrim(data_get($selectedChannel, 'custom_url', data_get($selectedChannel, 'id')), '@'),
'display_name' => data_get($selectedChannel, 'title'),
'avatar_url' => $avatarPath,
'access_token' => data_get($oauthData, 'access_token'),
'refresh_token' => data_get($oauthData, 'refresh_token'),
'token_expires_at' => data_get($oauthData, 'expires_in') ? now()->addSeconds(data_get($oauthData, 'expires_in')) : null,
'scopes' => $this->scopes,
'meta' => [
'channel_id' => data_get($selectedChannel, 'id'),
'google_user_id' => data_get($oauthData, 'user_id'),
],
]);
$existingAccount->markAsConnected();
session()->forget(['youtube_oauth', 'social_reconnect_id']);
return $this->popupCallback(true, 'YouTube channel reconnected!', $this->platform->value);
}
}
2026-01-15 17:24:39 +00:00
// Create new account
2026-01-15 17:24:39 +00:00
$workspace->socialAccounts()->create([
'platform' => $this->platform->value,
'platform_user_id' => data_get($selectedChannel, 'id'),
'username' => ltrim(data_get($selectedChannel, 'custom_url', data_get($selectedChannel, 'id')), '@'),
'display_name' => data_get($selectedChannel, 'title'),
2026-01-15 17:24:39 +00:00
'avatar_url' => $avatarPath,
'access_token' => data_get($oauthData, 'access_token'),
'refresh_token' => data_get($oauthData, 'refresh_token'),
'token_expires_at' => data_get($oauthData, 'expires_in') ? now()->addSeconds(data_get($oauthData, 'expires_in')) : null,
2026-01-15 17:24:39 +00:00
'scopes' => $this->scopes,
'status' => Status::Connected,
2026-01-15 17:24:39 +00:00
'meta' => [
'channel_id' => data_get($selectedChannel, 'id'),
'google_user_id' => data_get($oauthData, 'user_id'),
2026-01-15 17:24:39 +00:00
],
]);
session()->forget(['youtube_oauth', 'social_reconnect_id']);
2026-01-15 17:24:39 +00:00
return $this->popupCallback(true, 'YouTube channel connected!', $this->platform->value);
2026-01-15 17:24:39 +00:00
} catch (\Exception $e) {
Log::error('YouTube channel selection error', [
'error' => $e->getMessage(),
]);
return $this->popupCallback(false, 'Error connecting channel. Please try again.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
}
private function redirectToGoogle(): Response
2026-01-15 17:24:39 +00:00
{
return Inertia::location(
2026-01-15 17:24:39 +00:00
Socialite::driver($this->driver)
->scopes($this->scopes)
->with([
'access_type' => 'offline',
'prompt' => 'consent',
'include_granted_scopes' => 'true',
2026-01-15 17:24:39 +00:00
])
->redirect()
->getTargetUrl()
);
}
private function fetchChannels(string $accessToken): array
{
try {
$response = Http::withToken($accessToken)
2026-01-15 17:24:39 +00:00
->get('https://www.googleapis.com/youtube/v3/channels', [
'part' => 'snippet,contentDetails,statistics',
'mine' => 'true',
]);
if ($response->failed()) {
Log::error('YouTube channels fetch failed', [
'status' => $response->status(),
'body' => $response->body(),
]);
return [];
}
$data = $response->json();
return collect(data_get($data, 'items', []))->map(fn ($channel) => [
'id' => data_get($channel, 'id'),
'title' => data_get($channel, 'snippet.title'),
'description' => data_get($channel, 'snippet.description', ''),
'thumbnail' => data_get($channel, 'snippet.thumbnails.default.url'),
'custom_url' => data_get($channel, 'snippet.customUrl'),
'subscriber_count' => data_get($channel, 'statistics.subscriberCount', 0),
2026-01-15 17:24:39 +00:00
])->toArray();
} catch (\Exception $e) {
Log::error('YouTube channels fetch error', [
'error' => $e->getMessage(),
]);
return [];
}
}
}