trypost/app/Http/Controllers/Auth/YouTubeController.php
Paulo Castellano 173a1e4c61
Fix Facebook Page connect pagination (#212) (#253)
* Fix Facebook and Instagram-via-Facebook Page connect pagination.

Follow Graph API paging.next on /me/accounts so authorized non-first Pages are found and multi-Page accounts get the picker instead of silently connecting the first result.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Paginate Meta accounts until paging.next is exhausted.

Drop the artificial 50-page cap and stop only when there is no next URL, or the same request URL repeats (broken pagination loop).

Co-authored-by: Cursor <cursoragent@cursor.com>

* Redact tokens in Graph pagination logs and harden test coverage.

Cover happy-path and failure cases for Meta /me/accounts pagination, including mid-loop failures, invalid paging.next, and Instagram pages without a linked IG account.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fail closed on incomplete Meta accounts pagination.

If a later /me/accounts page fails after earlier pages succeeded, throw instead of returning a truncated list that could auto-connect the wrong Page. Also revert the IG detail timeout that could wipe the whole connect list.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify Graph pagination helpers and page fetchers.

Bake the first request query into the URL, drop requestKey, and let IncompleteGraphPaginationException bubble from the controllers without catch/rethrow noise.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move incomplete pagination exception under Social\Meta.

Colocate it with GraphPaginator so the Meta scope is clear from the namespace instead of a generic Social exception name.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Rename pagination exception to IncompleteMetaGraphPaginationException.

Keep it under Exceptions/Social with Meta in the class name instead of moving it into Services.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Make GraphPaginator results explicit before mapping pages.

Assign the paginated accounts to a variable first so the Facebook and Instagram-via-Facebook fetchers read more clearly.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Build Meta Graph pagination URLs with Laravel Uri.

Replace manual http_build_query concatenation with Uri::of()->withQuery().

Co-authored-by: Cursor <cursoragent@cursor.com>

* Use Laravel HTTP and Uri helpers in Meta Graph pagination.

Prefer response collect/json key access, filled(), and Uri path parsing over manual array and parse_url handling.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify graphVersion using Uri path and str().

Drop basename and native string casts; Uri::path() already yields the Graph API version segment.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop unnecessary str() around graph API config.

Uri: :of() already accepts the string returned by config().
Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify GraphPaginator with Laravel helpers.

Consolidate failure handling via abort(), and use collect, when, throw_if, and Uri::value() for a shorter pagination loop.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Refactor social OAuth page/channel selection handling. Update selectPage and selectChannel methods in Facebook, Instagram, and YouTube controllers to return popup callbacks instead of redirecting on session expiration or workspace not found. Enhance HandleInertiaRequests middleware to prevent deferring onboarding progress on social OAuth popup routes. Add tests to verify behavior for expired sessions and onboarding progress.

* Unify Instagram connect behind one card with a method picker.

Hide the Instagram-via-Facebook grid card and offer Instagram Login vs Facebook Pages from a single network entry, matching LinkedIn.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move social popup onboarding assertions into connection tests.

Cover the deferred-prop popup regression on Facebook, Instagram, and YouTube select routes instead of a synthetic onboarding share check.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Stop suppressing onboarding defer on all social routes.

Override onboardingProgress only in popupCallback so picker pages stay deferred and the close page does not re-hit select after session clear.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Always open the Instagram method dialog on connect.

Drop connectMethods and the single-method OAuth shortcut; the picker always offers both Login and Facebook Pages.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Filter Instagram dialog options by enabled platforms.

Keep always opening the method picker, but only list OAuth entry points that are turned on.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Extract Instagram connect methods into a dedicated helper.

Keep connectableOptions focused on shaping grid options while the enabled OAuth list lives in instagramConnectMethods().

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden Meta Graph pagination and localize Instagram connect copy.

Fail closed on Graph request errors and pathological paging, keep Instagram connect going when profile detail lookups time out, and translate the Instagram method dialog strings.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 12:01:46 -03:00

303 lines
12 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Controllers\Auth;
use App\Enums\SocialAccount\Platform as SocialPlatform;
use App\Enums\SocialAccount\Status;
use App\Exceptions\SocialAccount\NetworkAlreadyConnectedException;
use App\Models\Workspace;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Inertia\Inertia;
use Inertia\Response as InertiaResponse;
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',
];
public function connect(Request $request): Response
{
$this->ensurePlatformEnabled();
$workspace = $request->user()->currentWorkspace;
$this->authorize('manageAccounts', $workspace);
session([
'social_connect_workspace' => $workspace->id,
'social_reconnect_id' => null,
]);
return $this->redirectToGoogle();
}
public function callback(Request $request): InertiaResponse|RedirectResponse
{
$workspaceId = session('social_connect_workspace');
if (! $workspaceId) {
return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value);
}
$workspace = Workspace::find($workspaceId);
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value);
}
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, __('accounts.popup_callback.no_youtube_channels'), $this->platform->value);
}
// If only one channel, connect directly (most common case)
if (count($channels) === 1) {
$channel = $channels[0];
$avatarPath = uploadFromUrl(data_get($channel, 'thumbnail'));
$workspace->socialAccounts()->updateOrCreate(
[
'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'),
'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,
'error_message' => null,
'disconnected_at' => null,
'meta' => [
'channel_id' => data_get($channel, 'id'),
'google_user_id' => $socialUser->getId(),
],
],
);
return $this->popupCallback(true, __('accounts.popup_callback.connected'), $this->platform->value);
}
// 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(),
],
]);
return redirect()->route('app.social.youtube.select-channel');
} catch (NetworkAlreadyConnectedException) {
return $this->popupCallback(false, __('accounts.popup_callback.network_taken'), $this->platform->value);
} catch (\Exception $e) {
Log::error('YouTube OAuth Error', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value);
}
}
public function selectChannel(Request $request): InertiaResponse
{
$oauthData = session('youtube_oauth');
$workspaceId = session('social_connect_workspace');
if (! $oauthData || ! $workspaceId) {
return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value);
}
$workspace = Workspace::find($workspaceId);
if (! $workspace) {
return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value);
}
// Fetch YouTube channels
$channels = $this->fetchChannels(data_get($oauthData, 'access_token'));
if (empty($channels)) {
$this->forgetSocialConnectSession();
session()->forget('youtube_oauth');
return $this->popupCallback(false, __('accounts.popup_callback.no_youtube_channels'), $this->platform->value);
}
return Inertia::render('accounts/YouTubeChannelSelect', [
'workspace' => $workspace,
'channels' => $channels,
]);
}
public function select(Request $request): InertiaResponse
{
$request->validate([
'channel_id' => 'required|string',
]);
$oauthData = session('youtube_oauth');
$workspaceId = session('social_connect_workspace');
if (! $oauthData || ! $workspaceId) {
return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value);
}
$workspace = Workspace::find($workspaceId);
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value);
}
try {
$channels = $this->fetchChannels(data_get($oauthData, 'access_token'));
$selectedChannel = collect($channels)->firstWhere('id', $request->channel_id);
if (! $selectedChannel) {
return $this->popupCallback(false, __('accounts.popup_callback.channel_not_found'), $this->platform->value);
}
$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, __('accounts.popup_callback.reconnected'), $this->platform->value);
}
}
$workspace->socialAccounts()->updateOrCreate(
[
'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'),
'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,
'status' => Status::Connected,
'error_message' => null,
'disconnected_at' => null,
'meta' => [
'channel_id' => data_get($selectedChannel, 'id'),
'google_user_id' => data_get($oauthData, 'user_id'),
],
],
);
session()->forget(['youtube_oauth', 'social_reconnect_id']);
return $this->popupCallback(true, __('accounts.popup_callback.connected'), $this->platform->value);
} catch (NetworkAlreadyConnectedException) {
return $this->popupCallback(false, __('accounts.popup_callback.network_taken'), $this->platform->value);
} catch (\Exception $e) {
Log::error('YouTube channel selection error', [
'error' => $e->getMessage(),
]);
return $this->popupCallback(false, __('accounts.popup_callback.error_connecting_channel'), $this->platform->value);
}
}
private function redirectToGoogle(): Response
{
return Inertia::location(
Socialite::driver($this->driver)
->scopes($this->scopes)
->with([
'access_type' => 'offline',
'prompt' => 'consent',
'include_granted_scopes' => 'true',
])
->redirect()
->getTargetUrl()
);
}
private function fetchChannels(string $accessToken): array
{
try {
$response = Http::withToken($accessToken)
->get(config('trypost.platforms.youtube.data_api').'/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),
])->toArray();
} catch (\Exception $e) {
Log::error('YouTube channels fetch error', [
'error' => $e->getMessage(),
]);
return [];
}
}
}