diff --git a/.env.example b/.env.example index 5d6afd4e..8104df93 100644 --- a/.env.example +++ b/.env.example @@ -107,8 +107,6 @@ LINKEDIN_CLIENT_ID= LINKEDIN_CLIENT_SECRET= LINKEDIN_CLIENT_REDIRECT="${APP_URL}/accounts/linkedin/callback" # LINKEDIN_SCOPES="openid,profile,email,w_member_social" -LINKEDIN_PAGE_CLIENT_REDIRECT="${APP_URL}/accounts/linkedin-page/callback" -LINKEDIN_PAGE_CLIENT_REDIRECT="${APP_URL}/accounts/linkedin-page/callback" # LINKEDIN_PAGE_SCOPES="openid,profile,email,w_organization_social,r_organization_social,rw_organization_admin,w_member_social" # X / Twitter (https://developer.twitter.com) diff --git a/CLAUDE.md b/CLAUDE.md index db1556cd..a250825a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -291,6 +291,16 @@ ## Per-Platform Post Meta (`PostPlatform.meta`) - Required-on-publish (meta a platform needs to publish, e.g. Discord `channel_id`) also lives there: `addRequiredOnPublishErrors()` for request-driven flows (web/API update `withValidator`), `assertStoredPostPublishable()` for flows that publish stored state without resubmitting platforms (MCP `PublishPostTool`). Add new required-meta rules to `requiredMetaViolation()`, not inline. - When adding a new platform's meta field, add it (and any publish requirement) to `PostPlatformMetaRules` ONLY, and cover it in `tests/Feature/Api/PostApiPlatformMetaTest.php` + `tests/Feature/Mcp/PostPlatformMetaToolTest.php`. +## Media Types (image / video / document) + +- A media item is one of exactly three types: **image**, **video**, **document** (PDF). There is no standalone "audio" media type (audio exists only as a video voiceover input). +- Media-type detection lives in ONE place per side — NEVER hand-write `type === 'image'`, `mime_type === 'application/pdf'`, `mime.startsWith('video/')`, or extension checks inline. + - Backend: `App\Enums\Media\Type` — `classify()`, `fromMime()`, `fromExtension()`, `isGif()`, plus the `allowedMimeTypes()` / `extensions()` allow-lists. Use these, never a raw MIME/extension comparison. + - Frontend: `resources/js/lib/mediaType.ts` — the mirror of the backend enum: the `MediaType` union, `classify()`, `fromMimeType()` (for a browser `File.type`), `fromExtension()`, `isImage()`/`isVideo()`/`isDocument()`/`isGif()`. `@/composables/useMedia` re-exports `isImageMedia`/`isVideoMedia`/`isDocumentMedia` aliases for legacy call sites. + - Detection trusts the explicit `type` first, then the MIME, then the filename extension — so an item with only a MIME (e.g. AI/Unsplash/Giphy media without a `type`) still classifies correctly. A bare `item.type === 'image'` (with a `v-else` video) silently mis-renders those. +- The `type` field on every media-ish interface is the `MediaType` union, never `string` — `MediaItem`, and any sibling picked/asset/saved shape (`PickedMedia`, `AssetMedia`, `SavedMedia`, etc.). +- The upload `accept` attribute for "everything we allow" comes from `acceptAttribute()` (frontend) / `Media\Type::allowedMimeTypes()` (backend) — never a hardcoded MIME list. Per-capability `accept` builders driven by content-type rules (e.g. `image/*,video/*`) are fine; those aren't detection. + ## Pest / Feature Tests - ALWAYS use named routes via the `route()` helper in feature tests. NEVER hardcode URL strings like `'/posts/ai/create'`. diff --git a/app/Actions/Automation/Node/RunGenerateNode.php b/app/Actions/Automation/Node/RunGenerateNode.php index 2565169b..c4465256 100644 --- a/app/Actions/Automation/Node/RunGenerateNode.php +++ b/app/Actions/Automation/Node/RunGenerateNode.php @@ -251,8 +251,8 @@ private function extractContent(array $structured, GeneratorFormat $format, Cont * * Carousel-capable content types: * - instagram_feed (Instagram feed carousel = multi-image feed post) - * - linkedin_carousel (LinkedIn personal carousel PDF) - * - linkedin_page_carousel (LinkedIn page carousel PDF) + * - linkedin_post (LinkedIn multi-image post — 2+ images) + * - linkedin_page_post (LinkedIn page multi-image post) * - pinterest_carousel (Pinterest carousel pin) * - tiktok_photo (TikTok photo carousel) * diff --git a/app/Actions/Workspace/DeleteWorkspace.php b/app/Actions/Workspace/DeleteWorkspace.php index e43e8cbe..57a545b3 100644 --- a/app/Actions/Workspace/DeleteWorkspace.php +++ b/app/Actions/Workspace/DeleteWorkspace.php @@ -13,7 +13,15 @@ class DeleteWorkspace { public static function execute(User $user, Workspace $workspace): void { - User::where('current_workspace_id', $workspace->id)->update(['current_workspace_id' => null]); + User::where('current_workspace_id', $workspace->id) + ->get() + ->each(function (User $affected) use ($workspace): void { + $fallback = $affected->workspaces() + ->where('workspaces.id', '!=', $workspace->id) + ->first(); + + $affected->update(['current_workspace_id' => $fallback?->id]); + }); $account = $workspace->account; $accountId = (string) $workspace->account_id; diff --git a/app/DataTransferObjects/MediaItem.php b/app/DataTransferObjects/MediaItem.php index 64f9c98b..eae00948 100644 --- a/app/DataTransferObjects/MediaItem.php +++ b/app/DataTransferObjects/MediaItem.php @@ -5,6 +5,7 @@ namespace App\DataTransferObjects; use App\Enums\Media\Source; +use App\Enums\Media\Type; class MediaItem { @@ -23,29 +24,19 @@ public function __construct( public function isVideo(): bool { - if ($this->mime_type) { - return str_starts_with($this->mime_type, 'video/'); - } - - $extension = strtolower(pathinfo($this->path, PATHINFO_EXTENSION)); - - return in_array($extension, ['mp4', 'mov', 'avi', 'wmv', 'webm', 'mkv', 'm4v']); + return Type::classify($this->mime_type, $this->path) === Type::Video; } public function isImage(): bool { - if ($this->mime_type) { - return str_starts_with($this->mime_type, 'image/'); - } - - $extension = strtolower(pathinfo($this->path, PATHINFO_EXTENSION)); - - return in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif']); + return Type::classify($this->mime_type, $this->path) === Type::Image; + } + + public function isDocument(): bool + { + return Type::classify($this->mime_type, $this->path) === Type::Document; } - /** - * @param array $data - */ /** * @param array $data */ @@ -63,6 +54,7 @@ public static function fromArray(array $data): self 'webp' => 'image/webp', 'mp4' => 'video/mp4', 'mov' => 'video/quicktime', + 'pdf' => 'application/pdf', default => null, }; } diff --git a/app/Enums/Media/Type.php b/app/Enums/Media/Type.php index 935da839..54074aca 100644 --- a/app/Enums/Media/Type.php +++ b/app/Enums/Media/Type.php @@ -8,12 +8,14 @@ enum Type: string { case Image = 'image'; case Video = 'video'; + case Document = 'document'; public function label(): string { return match ($this) { self::Image => 'Imagem', self::Video => 'Vídeo', + self::Document => 'Documento', }; } @@ -31,6 +33,11 @@ public function label(): string * server-side transcoding, accepting WebM would just produce * platform-specific publish failures down the line. * + * Document accepts PDF only — the swipeable LinkedIn document + * (carousel) format. PPTX/DOCX are also valid LinkedIn documents + * but are converted server-side by LinkedIn and lose fonts, so we + * keep the surface to PDF. + * * @return array */ public function allowedMimeTypes(): array @@ -38,6 +45,7 @@ public function allowedMimeTypes(): array return match ($this) { self::Image => ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], self::Video => ['video/mp4', 'video/quicktime'], + self::Document => ['application/pdf'], }; } @@ -52,6 +60,7 @@ public function extensions(): array return match ($this) { self::Image => ['jpg', 'jpeg', 'png', 'gif', 'webp'], self::Video => ['mp4', 'mov'], + self::Document => ['pdf'], }; } @@ -84,4 +93,50 @@ public static function fromMime(string $mime): ?self return null; } + + /** + * Classify media by what it *is* — for "is this an image/video/PDF?" checks, + * as opposed to fromMime() which is the strict upload allow-list. Any + * `image/*`, `video/*`, or `application/pdf` MIME maps to its type; when the + * MIME is missing it falls back to the filename extension so already-stored + * files still resolve. + */ + public static function classify(?string $mimeType, ?string $path = null): ?self + { + if (filled($mimeType)) { + return match (true) { + str_starts_with($mimeType, 'image/') => self::Image, + str_starts_with($mimeType, 'video/') => self::Video, + $mimeType === 'application/pdf' => self::Document, + default => null, + }; + } + + return self::fromExtension($path ? pathinfo($path, PATHINFO_EXTENSION) : null); + } + + /** + * Classify by filename extension. Broader than extensions() (the upload + * allow-list) so already-stored files in legacy formats still resolve. + */ + public static function fromExtension(?string $extension): ?self + { + $extension = strtolower((string) $extension); + + return match (true) { + in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif'], true) => self::Image, + in_array($extension, ['mp4', 'mov', 'avi', 'wmv', 'webm', 'mkv', 'm4v'], true) => self::Video, + $extension === 'pdf' => self::Document, + default => null, + }; + } + + /** + * Whether the MIME is an animated GIF — several publishers handle it + * specially (skipped from optimization, or posted as video). + */ + public static function isGif(?string $mimeType): bool + { + return $mimeType === 'image/gif'; + } } diff --git a/app/Enums/PostPlatform/ContentType.php b/app/Enums/PostPlatform/ContentType.php index 02a27e9b..b9338bc9 100644 --- a/app/Enums/PostPlatform/ContentType.php +++ b/app/Enums/PostPlatform/ContentType.php @@ -13,13 +13,12 @@ enum ContentType: string case InstagramReel = 'instagram_reel'; case InstagramStory = 'instagram_story'; - // LinkedIn + // LinkedIn — one type per account kind; the publish format (single image, + // multi-image, video, or PDF document) is inferred from the attached media. case LinkedInPost = 'linkedin_post'; - case LinkedInCarousel = 'linkedin_carousel'; // LinkedIn Page case LinkedInPagePost = 'linkedin_page_post'; - case LinkedInPageCarousel = 'linkedin_page_carousel'; // Facebook case FacebookPost = 'facebook_post'; @@ -69,7 +68,6 @@ public function label(): string self::InstagramReel => 'Reel', self::InstagramStory => 'Story', self::LinkedInPost, self::LinkedInPagePost => 'Post', - self::LinkedInCarousel, self::LinkedInPageCarousel => 'Carousel', self::FacebookPost => 'Post', self::FacebookReel => 'Reel', self::FacebookStory => 'Story', @@ -97,8 +95,8 @@ public function platform(): SocialPlatform { return match ($this) { self::InstagramFeed, self::InstagramReel, self::InstagramStory => SocialPlatform::Instagram, - self::LinkedInPost, self::LinkedInCarousel => SocialPlatform::LinkedIn, - self::LinkedInPagePost, self::LinkedInPageCarousel => SocialPlatform::LinkedInPage, + self::LinkedInPost => SocialPlatform::LinkedIn, + self::LinkedInPagePost => SocialPlatform::LinkedInPage, self::FacebookPost, self::FacebookReel, self::FacebookStory => SocialPlatform::Facebook, self::TikTokVideo, self::TikTokPhoto => SocialPlatform::TikTok, self::YouTubeShort => SocialPlatform::YouTube, @@ -164,8 +162,7 @@ public function maxMediaCount(): int return match ($this) { self::InstagramFeed => 10, self::InstagramReel, self::InstagramStory => 1, - self::LinkedInPost, self::LinkedInPagePost => 1, - self::LinkedInCarousel, self::LinkedInPageCarousel => 20, + self::LinkedInPost, self::LinkedInPagePost => 10, self::FacebookPost => 10, self::FacebookReel, self::FacebookStory => 1, self::TikTokVideo => 1, @@ -187,7 +184,6 @@ public function supportsVideo(): bool return match ($this) { self::InstagramFeed, self::InstagramReel, self::InstagramStory => true, self::LinkedInPost, self::LinkedInPagePost => true, - self::LinkedInCarousel, self::LinkedInPageCarousel => false, self::FacebookPost, self::FacebookReel, self::FacebookStory => true, self::TikTokVideo => true, self::TikTokPhoto => false, @@ -216,6 +212,19 @@ public function supportsImage(): bool }; } + /** + * Whether this content type can carry a PDF document (the swipeable LinkedIn + * document/carousel). LinkedIn infers the document format from a PDF being + * attached; the document is always the only attachment (see the media rule). + */ + public function supportsDocument(): bool + { + return match ($this) { + self::LinkedInPost, self::LinkedInPagePost => true, + default => false, + }; + } + /** * Whether a single post may carry images and a video together. Most * targets accept only one or the other; this is conservative and lists @@ -226,6 +235,8 @@ public function supportsMixedMedia(): bool { return match ($this) { self::BlueskyPost => false, + // LinkedIn publishes images XOR one video XOR one document — never mixed. + self::LinkedInPost, self::LinkedInPagePost => false, default => true, }; } diff --git a/app/Enums/SocialAccount/LinkedInIdentityType.php b/app/Enums/SocialAccount/LinkedInIdentityType.php new file mode 100644 index 00000000..db15de5f --- /dev/null +++ b/app/Enums/SocialAccount/LinkedInIdentityType.php @@ -0,0 +1,16 @@ + [MediaType::Image, MediaType::Video], + self::LinkedIn, self::LinkedInPage => [MediaType::Image, MediaType::Video, MediaType::Document], self::X => [MediaType::Image, MediaType::Video], self::TikTok => [MediaType::Video], self::YouTube => [MediaType::Video], @@ -112,7 +112,7 @@ public function allowedMediaTypes(): array public function maxImages(): int { return match ($this) { - self::LinkedIn, self::LinkedInPage => 1, + self::LinkedIn, self::LinkedInPage => 10, self::X => 4, self::TikTok => 0, self::YouTube => 0, @@ -287,6 +287,22 @@ public function isEnabled(): bool return config("trypost.platforms.{$this->value}.enabled", true); } + /** + * Whether this platform gets its own "Connect" card in the accounts grid. + * LinkedIn company pages are reached through the unified LinkedIn connect + * flow's identity picker, never a standalone card. The single LinkedIn card + * stands for the whole network, so it shows whenever the profile OR the + * company-page capability is enabled (self-hosters may run with only one). + */ + public function isConnectable(): bool + { + return match ($this) { + self::LinkedInPage => false, + self::LinkedIn => self::LinkedIn->isEnabled() || self::LinkedInPage->isEnabled(), + default => $this->isEnabled(), + }; + } + /** * Static, platform-specific data exposed to the frontend (e.g. TikTok privacy options, * compliance URLs). Returns an empty array for platforms with no extra config. @@ -309,14 +325,4 @@ public function publishConfig(): array default => [], }; } - - /** - * Get all enabled platforms. - * - * @return array - */ - public static function enabled(): array - { - return array_filter(self::cases(), fn (self $platform) => $platform->isEnabled()); - } } diff --git a/app/Http/Controllers/App/OnboardingController.php b/app/Http/Controllers/App/OnboardingController.php index 06410983..1c488797 100644 --- a/app/Http/Controllers/App/OnboardingController.php +++ b/app/Http/Controllers/App/OnboardingController.php @@ -86,12 +86,14 @@ public function connect(Request $request): Response|RedirectResponse $accounts = $workspace->socialAccounts()->orderBy('id')->get(); - $platforms = collect(SocialPlatform::enabled())->map(fn (SocialPlatform $platform): array => [ - 'value' => $platform->value, - 'label' => $platform->label(), - 'color' => $platform->color(), - 'network' => $platform->network(), - ])->values(); + $platforms = collect(SocialPlatform::cases()) + ->filter(fn (SocialPlatform $platform): bool => $platform->isConnectable()) + ->map(fn (SocialPlatform $platform): array => [ + 'value' => $platform->value, + 'label' => $platform->label(), + 'color' => $platform->color(), + 'network' => $platform->network(), + ])->values(); return Inertia::render('onboarding/Connect', [ 'platforms' => $platforms, diff --git a/app/Http/Controllers/Auth/BlueskyController.php b/app/Http/Controllers/Auth/BlueskyController.php index 6b3630b9..cad4d5cc 100644 --- a/app/Http/Controllers/Auth/BlueskyController.php +++ b/app/Http/Controllers/Auth/BlueskyController.php @@ -7,28 +7,23 @@ use App\Enums\SocialAccount\Platform as SocialPlatform; use App\Enums\SocialAccount\Status; use App\Services\Social\BlueskyLexicon; -use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; -use Illuminate\View\View; +use Illuminate\Validation\ValidationException; use Inertia\Inertia; -use Inertia\Response; +use Inertia\Response as InertiaResponse; class BlueskyController extends SocialController { protected SocialPlatform $platform = SocialPlatform::Bluesky; - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): InertiaResponse { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); return Inertia::render('accounts/BlueskyConnect', [ @@ -36,7 +31,7 @@ public function connect(Request $request): Response|RedirectResponse ]); } - public function store(Request $request): View|RedirectResponse + public function store(Request $request): InertiaResponse { $this->ensurePlatformEnabled(); @@ -47,10 +42,6 @@ public function store(Request $request): View|RedirectResponse $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); $service = config('trypost.platforms.bluesky.default_service'); @@ -74,7 +65,7 @@ public function store(Request $request): View|RedirectResponse $errorMessage = $body['message']; } - return back()->withErrors(['password' => $errorMessage]); + throw ValidationException::withMessages(['password' => $errorMessage]); } $data = $response->json(); @@ -113,13 +104,15 @@ public function store(Request $request): View|RedirectResponse ); return $this->popupCallback(true, __('accounts.popup_callback.connected'), $this->platform->value); + } catch (ValidationException $e) { + throw $e; } catch (\Exception $e) { Log::error('Bluesky connection error', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); - return back()->withErrors(['password' => 'Error connecting to Bluesky. Please try again.']); + throw ValidationException::withMessages(['password' => 'Error connecting to Bluesky. Please try again.']); } } } diff --git a/app/Http/Controllers/Auth/DiscordController.php b/app/Http/Controllers/Auth/DiscordController.php index 87ff8c25..6166e9fe 100644 --- a/app/Http/Controllers/Auth/DiscordController.php +++ b/app/Http/Controllers/Auth/DiscordController.php @@ -5,9 +5,8 @@ namespace App\Http\Controllers\Auth; use App\Enums\SocialAccount\Platform as SocialPlatform; -use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; -use Illuminate\View\View; +use Inertia\Response as InertiaResponse; use Symfony\Component\HttpFoundation\Response; class DiscordController extends SocialController @@ -16,22 +15,18 @@ class DiscordController extends SocialController protected SocialPlatform $platform = SocialPlatform::Discord; - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): Response { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); return $this->redirectToProvider($request, $this->driver, config('trypost.platforms.discord.scopes')); } - public function callback(Request $request): View + public function callback(Request $request): InertiaResponse { return $this->handleCallback($request, $this->platform, $this->driver); } diff --git a/app/Http/Controllers/Auth/FacebookController.php b/app/Http/Controllers/Auth/FacebookController.php index 90d8b3de..c868d250 100644 --- a/app/Http/Controllers/Auth/FacebookController.php +++ b/app/Http/Controllers/Auth/FacebookController.php @@ -13,8 +13,8 @@ use Illuminate\Support\Arr; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; -use Illuminate\View\View; use Inertia\Inertia; +use Inertia\Response as InertiaResponse; use Laravel\Socialite\Facades\Socialite; use Symfony\Component\HttpFoundation\Response; @@ -32,16 +32,12 @@ class FacebookController extends SocialController 'read_insights', ]; - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): Response { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); session([ @@ -58,7 +54,7 @@ public function connect(Request $request): Response|RedirectResponse ); } - public function callback(Request $request): View|RedirectResponse + public function callback(Request $request): InertiaResponse|RedirectResponse { $workspaceId = session('social_connect_workspace'); @@ -174,7 +170,7 @@ public function selectPage(Request $request) ]); } - public function select(Request $request): View + public function select(Request $request): InertiaResponse { $request->validate([ 'page_id' => 'required|string', diff --git a/app/Http/Controllers/Auth/InstagramController.php b/app/Http/Controllers/Auth/InstagramController.php index 2fddbe2a..79931649 100644 --- a/app/Http/Controllers/Auth/InstagramController.php +++ b/app/Http/Controllers/Auth/InstagramController.php @@ -8,11 +8,10 @@ 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\Log; -use Illuminate\View\View; use Inertia\Inertia; +use Inertia\Response as InertiaResponse; use Laravel\Socialite\Facades\Socialite; use Symfony\Component\HttpFoundation\Response; @@ -28,16 +27,12 @@ class InstagramController extends SocialController 'instagram_business_manage_insights', ]; - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): Response { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); session([ @@ -53,7 +48,7 @@ public function connect(Request $request): Response|RedirectResponse return Inertia::location($url); } - public function callback(Request $request): View + public function callback(Request $request): InertiaResponse { $workspaceId = session('social_connect_workspace'); diff --git a/app/Http/Controllers/Auth/InstagramFacebookController.php b/app/Http/Controllers/Auth/InstagramFacebookController.php index 57eef9ad..36fdebf9 100644 --- a/app/Http/Controllers/Auth/InstagramFacebookController.php +++ b/app/Http/Controllers/Auth/InstagramFacebookController.php @@ -13,8 +13,8 @@ use Illuminate\Support\Arr; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; -use Illuminate\View\View; use Inertia\Inertia; +use Inertia\Response as InertiaResponse; use Laravel\Socialite\Facades\Socialite; use Symfony\Component\HttpFoundation\Response; @@ -34,16 +34,12 @@ class InstagramFacebookController extends SocialController 'instagram_manage_insights', ]; - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): Response { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); session([ @@ -61,7 +57,7 @@ public function connect(Request $request): Response|RedirectResponse return Inertia::location($url); } - public function callback(Request $request): View|RedirectResponse + public function callback(Request $request): InertiaResponse|RedirectResponse { $workspaceId = session('social_connect_workspace'); @@ -150,7 +146,7 @@ public function selectPage(Request $request) ]); } - public function select(Request $request): View + public function select(Request $request): InertiaResponse { $request->validate([ 'page_id' => 'required|string', @@ -193,7 +189,7 @@ public function select(Request $request): View } } - private function connectInstagramAccount(Workspace $workspace, array $pageData, $existingAccount): View + private function connectInstagramAccount(Workspace $workspace, array $pageData, $existingAccount): InertiaResponse { $avatarPath = data_get($pageData, 'ig_picture') ? uploadFromUrl(data_get($pageData, 'ig_picture')) : null; diff --git a/app/Http/Controllers/Auth/LinkedInController.php b/app/Http/Controllers/Auth/LinkedInController.php index 05fb0b44..743885f4 100644 --- a/app/Http/Controllers/Auth/LinkedInController.php +++ b/app/Http/Controllers/Auth/LinkedInController.php @@ -4,41 +4,59 @@ namespace App\Http\Controllers\Auth; +use App\Enums\SocialAccount\LinkedInIdentityType; use App\Enums\SocialAccount\Platform as SocialPlatform; use App\Enums\SocialAccount\Status; use App\Exceptions\SocialAccount\NetworkAlreadyConnectedException; use App\Models\Workspace; -use App\Services\Social\LinkedInTokenSynchronizer; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; -use Illuminate\View\View; +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rules\Enum; +use Inertia\Inertia; +use Inertia\Response as InertiaResponse; use Laravel\Socialite\Facades\Socialite; use Symfony\Component\HttpFoundation\Response; class LinkedInController extends SocialController { - protected string $driver = 'linkedin'; + protected string $driver = 'linkedin-openid'; protected SocialPlatform $platform = SocialPlatform::LinkedIn; - public function connect(Request $request): Response|RedirectResponse + /** + * The LinkedIn card stands for both the personal profile and company-page + * capabilities, each independently toggleable so self-hosters can run with + * just one. The connect flow is available while either is enabled. + */ + protected function ensurePlatformEnabled(): void + { + if (! $this->personEnabled() && ! $this->organizationEnabled()) { + abort(Response::HTTP_FORBIDDEN, 'This platform is currently unavailable.'); + } + } + + public function connect(Request $request): Response { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); - return $this->redirectToProvider($request, $this->driver, config('trypost.platforms.linkedin.scopes')); + session(['social_connect_workspace' => $workspace->id]); + + return Inertia::location( + Socialite::driver($this->driver) + ->scopes($this->connectScopes()) + ->redirect() + ->getTargetUrl() + ); } - public function callback(Request $request): View + public function callback(Request $request): InertiaResponse|RedirectResponse { $workspaceId = session('social_connect_workspace'); @@ -55,37 +73,24 @@ public function callback(Request $request): View try { $socialUser = Socialite::driver($this->driver)->user(); - // Fetch vanityName from LinkedIn API (not available via OpenID) - $username = $this->fetchVanityName($socialUser->token); - - $avatarPath = uploadFromUrl($socialUser->getAvatar()); - - $account = $workspace->socialAccounts()->updateOrCreate( - [ - 'platform' => $this->platform->value, - 'platform_user_id' => $socialUser->getId(), - ], - [ - 'username' => $username, - 'display_name' => $socialUser->getName(), - 'avatar_url' => $avatarPath, - 'access_token' => $socialUser->token, + session([ + 'linkedin_pending' => [ + 'workspace_id' => $workspace->id, + 'token' => $socialUser->token, 'refresh_token' => $socialUser->refreshToken, - 'token_expires_at' => $socialUser->expiresIn ? now()->addSeconds($socialUser->expiresIn) : null, - // LinkedIn returns scope CSV-joined but Socialite splits on space, so re-split here. - 'scopes' => explode(',', implode(',', $socialUser->approvedScopes)), - 'status' => Status::Connected, - 'error_message' => null, - 'disconnected_at' => null, + 'expires_in' => $socialUser->expiresIn, + 'approved_scopes' => $socialUser->approvedScopes ?? [], + 'person' => [ + 'id' => $socialUser->getId(), + 'name' => $socialUser->getName(), + 'avatar' => $socialUser->getAvatar(), + 'vanity_name' => $this->personEnabled() ? $this->fetchVanityName($socialUser->token) : null, + ], + 'organizations' => $this->organizationEnabled() ? $this->fetchOrganizations($socialUser->token) : [], ], - ); + ]); - // Sync tokens to LinkedIn Page if it exists - app(LinkedInTokenSynchronizer::class)->syncTokens($account); - - return $this->popupCallback(true, __('accounts.popup_callback.connected'), $this->platform->value); - } catch (NetworkAlreadyConnectedException $e) { - return $this->popupCallback(false, __('accounts.popup_callback.network_taken'), $this->platform->value); + return redirect()->route('app.social.linkedin.select-identity'); } catch (\Exception $e) { Log::error('LinkedIn OAuth Error', [ 'error' => $e->getMessage(), @@ -95,6 +100,209 @@ public function callback(Request $request): View } } + public function selectIdentity(Request $request): InertiaResponse + { + $pending = session('linkedin_pending'); + + if (! $pending) { + return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value); + } + + $workspace = Workspace::find($pending['workspace_id']); + + if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) { + return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value); + } + + return Inertia::render('accounts/LinkedInSelect', [ + 'person' => $this->personEnabled() ? $pending['person'] : null, + 'organizations' => $pending['organizations'], + ]); + } + + public function select(Request $request): InertiaResponse + { + $validator = Validator::make($request->all(), [ + 'type' => ['required', new Enum(LinkedInIdentityType::class)], + 'organization_id' => 'required_if:type,organization', + ]); + + if ($validator->fails()) { + return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value); + } + + $validated = $validator->validated(); + + $pending = session('linkedin_pending'); + + if (! $pending) { + return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value); + } + + $workspace = Workspace::find($pending['workspace_id']); + + if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) { + return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value); + } + + $type = LinkedInIdentityType::from(data_get($validated, 'type')); + + if (($type === LinkedInIdentityType::Organization && ! $this->organizationEnabled()) + || ($type === LinkedInIdentityType::Person && ! $this->personEnabled())) { + return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value); + } + + try { + if ($type === LinkedInIdentityType::Organization) { + $organization = $this->resolveAdministeredOrganization($pending, data_get($validated, 'organization_id')); + + if (! $organization) { + return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value); + } + + $this->connectOrganization($workspace, $pending, $organization); + } else { + $this->connectPerson($workspace, $pending); + } + + session()->forget('linkedin_pending'); + + 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('LinkedIn selection error', [ + 'error' => $e->getMessage(), + ]); + + return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value); + } + } + + /** + * The user's personal LinkedIn profile becomes a `linkedin` account. + */ + private function connectPerson(Workspace $workspace, array $pending): void + { + $person = $pending['person']; + + $workspace->socialAccounts()->updateOrCreate( + [ + 'platform' => SocialPlatform::LinkedIn->value, + 'platform_user_id' => data_get($person, 'id'), + ], + [ + 'username' => data_get($person, 'vanity_name'), + 'display_name' => data_get($person, 'name'), + 'avatar_url' => uploadFromUrl(data_get($person, 'avatar')), + 'access_token' => $pending['token'], + 'refresh_token' => $pending['refresh_token'], + 'token_expires_at' => $pending['expires_in'] ? now()->addSeconds($pending['expires_in']) : null, + 'scopes' => $this->normalizeScopes($pending['approved_scopes'] ?? []), + 'status' => Status::Connected, + 'error_message' => null, + 'disconnected_at' => null, + ], + ); + } + + /** + * Match the chosen organization id against the admin-verified list captured at + * callback, so a tampered POST cannot connect a company the member does not + * administer. + * + * @param array $pending + * @return array|null + */ + private function resolveAdministeredOrganization(array $pending, mixed $organizationId): ?array + { + return collect(data_get($pending, 'organizations', [])) + ->first(fn ($organization) => (string) data_get($organization, 'id') === (string) $organizationId); + } + + /** + * A company the user administers becomes a `linkedin-page` account, with the + * acting member recorded in meta so the page publisher can post on its behalf. + * The organization data comes from the admin-verified session list, never the + * request body. + * + * @param array $pending + * @param array $organization + */ + private function connectOrganization(Workspace $workspace, array $pending, array $organization): void + { + $organizationId = data_get($organization, 'id'); + + $workspace->socialAccounts()->updateOrCreate( + [ + 'platform' => SocialPlatform::LinkedInPage->value, + 'platform_user_id' => $organizationId, + ], + [ + 'username' => data_get($organization, 'vanity_name'), + 'display_name' => data_get($organization, 'name'), + 'avatar_url' => uploadFromUrl(data_get($organization, 'logo')), + 'access_token' => $pending['token'], + 'refresh_token' => $pending['refresh_token'], + 'token_expires_at' => $pending['expires_in'] ? now()->addSeconds($pending['expires_in']) : null, + 'scopes' => $this->normalizeScopes($pending['approved_scopes'] ?? []), + 'status' => Status::Connected, + 'error_message' => null, + 'disconnected_at' => null, + 'meta' => [ + 'organization_id' => $organizationId, + 'admin_user_id' => data_get($pending, 'person.id'), + 'admin_name' => data_get($pending, 'person.name'), + ], + ], + ); + } + + /** + * Union of the scopes for the enabled capabilities, so one consent screen + * grants exactly what the workspace can use — member posting, company-page + * administration, or both — and the user picks the identity afterwards. + * + * @return array + */ + private function connectScopes(): array + { + $scopes = []; + + if ($this->personEnabled()) { + $scopes = array_merge($scopes, config('trypost.platforms.linkedin.scopes')); + } + + if ($this->organizationEnabled()) { + $scopes = array_merge($scopes, config('trypost.platforms.linkedin-page.scopes')); + } + + return array_values(array_unique($scopes)); + } + + private function personEnabled(): bool + { + return SocialPlatform::LinkedIn->isEnabled(); + } + + private function organizationEnabled(): bool + { + return SocialPlatform::LinkedInPage->isEnabled(); + } + + /** + * LinkedIn returns approved scopes comma-joined, but Socialite splits OAuth + * scopes on space — so the whole CSV lands as a single array element. Re-split + * on commas to store individual scope tokens. + * + * @param array $approvedScopes + * @return array + */ + private function normalizeScopes(array $approvedScopes): array + { + return array_values(array_filter(explode(',', implode(',', $approvedScopes)))); + } + private function fetchVanityName(string $accessToken): ?string { try { @@ -115,4 +323,45 @@ private function fetchVanityName(string $accessToken): ?string return null; } + + /** + * Organizations the authenticated member administers, used to offer company + * pages as a posting identity alongside their personal profile. + * + * @return array + */ + private function fetchOrganizations(string $accessToken): array + { + $response = Http::withToken($accessToken) + ->get(config('trypost.platforms.linkedin.api').'/v2/organizationAcls', [ + 'q' => 'roleAssignee', + 'role' => 'ADMINISTRATOR', + 'projection' => '(elements*(organization~(id,localizedName,vanityName,logoV2(original~:playableStreams))))', + ]); + + if ($response->failed()) { + Log::error('LinkedIn Organizations fetch error', [ + 'error' => $response->body(), + ]); + + return []; + } + + $organizations = []; + + foreach (data_get($response->json(), 'elements', []) as $element) { + $org = data_get($element, 'organization~'); + + if ($org) { + $organizations[] = [ + 'id' => data_get($org, 'id'), + 'name' => data_get($org, 'localizedName', 'Unknown'), + 'vanity_name' => data_get($org, 'vanityName'), + 'logo' => data_get($org, 'logoV2.original~.elements.0.identifiers.0.identifier'), + ]; + } + } + + return $organizations; + } } diff --git a/app/Http/Controllers/Auth/LinkedInPageController.php b/app/Http/Controllers/Auth/LinkedInPageController.php deleted file mode 100644 index 35ec1c59..00000000 --- a/app/Http/Controllers/Auth/LinkedInPageController.php +++ /dev/null @@ -1,273 +0,0 @@ -ensurePlatformEnabled(); - - $workspace = $request->user()->currentWorkspace; - - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - - $this->authorize('manageAccounts', $workspace); - - session([ - 'social_connect_workspace' => $workspace->id, - 'linkedin_page_reconnect_id' => null, - ]); - - return Inertia::location( - Socialite::driver($this->driver) - ->scopes(config('trypost.platforms.linkedin-page.scopes')) - ->with([ - 'redirect_uri' => config('services.linkedin-openid.redirect_page'), - ]) - ->redirect() - ->getTargetUrl() - ); - } - - public function callback(Request $request): View|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) - ->scopes(config('trypost.platforms.linkedin-page.scopes')) - ->with([ - 'redirect_uri' => config('services.linkedin-openid.redirect_page'), - ]) - ->user(); - - // Fetch organizations the user is admin of - $organizations = $this->fetchOrganizations($socialUser->token); - - if (empty($organizations)) { - return $this->popupCallback(false, __('accounts.popup_callback.not_linkedin_admin'), $this->platform->value); - } - - // Store data in session and redirect to selection page - session([ - 'linkedin_page_pending' => [ - 'workspace_id' => $workspace->id, - 'user_id' => $socialUser->getId(), - 'name' => $socialUser->getName(), - 'avatar' => $socialUser->getAvatar(), - 'token' => $socialUser->token, - 'refresh_token' => $socialUser->refreshToken, - 'expires_in' => $socialUser->expiresIn, - 'approved_scopes' => $socialUser->approvedScopes ?? [], - 'organizations' => $organizations, - 'reconnect_id' => session('linkedin_page_reconnect_id'), - ], - ]); - - return redirect()->route('app.social.linkedin-page.select-page'); - } catch (\Exception $e) { - Log::error('LinkedIn Page OAuth Error', [ - 'error' => $e->getMessage(), - ]); - - return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value); - } - } - - public function selectPage(Request $request): Response|RedirectResponse - { - $pendingData = session('linkedin_page_pending'); - - if (! $pendingData) { - session()->flash('flash.banner', __('accounts.flash.session_expired')); - session()->flash('flash.bannerStyle', 'danger'); - - return redirect()->route('app.accounts'); - } - - $workspace = Workspace::find($pendingData['workspace_id']); - - if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) { - session()->flash('flash.banner', __('accounts.flash.workspace_not_found')); - session()->flash('flash.bannerStyle', 'danger'); - - return redirect()->route('app.accounts'); - } - - return Inertia::render('accounts/LinkedInPageSelect', [ - 'workspace' => $workspace, - 'organizations' => $pendingData['organizations'], - ]); - } - - public function select(Request $request): View - { - $request->validate([ - 'organization_id' => 'required', - 'organization_name' => 'required|string', - 'organization_vanity_name' => 'nullable|string', - 'organization_logo' => 'nullable|string', - ]); - - $pendingData = session('linkedin_page_pending'); - - if (! $pendingData) { - return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value); - } - - $workspace = Workspace::find($pendingData['workspace_id']); - - if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) { - return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value); - } - - try { - $avatarPath = uploadFromUrl($request->organization_logo); - $reconnectId = $pendingData['reconnect_id'] ?? null; - - if ($reconnectId) { - // Reconnect existing account - $existingAccount = $workspace->socialAccounts()->find($reconnectId); - - if ($existingAccount) { - $existingAccount->update([ - 'platform_user_id' => $request->organization_id, - 'username' => $request->organization_vanity_name, - 'display_name' => $request->organization_name, - 'avatar_url' => $avatarPath, - 'access_token' => $pendingData['token'], - 'refresh_token' => $pendingData['refresh_token'], - 'token_expires_at' => $pendingData['expires_in'] ? now()->addSeconds($pendingData['expires_in']) : null, - // LinkedIn returns scope CSV-joined but Socialite splits on space, so re-split here. - 'scopes' => explode(',', implode(',', $pendingData['approved_scopes'] ?? [])), - 'meta' => [ - 'organization_id' => $request->organization_id, - 'admin_user_id' => $pendingData['user_id'], - 'admin_name' => $pendingData['name'], - ], - ]); - $existingAccount->markAsConnected(); - - // Sync tokens to LinkedIn personal if it exists - app(LinkedInTokenSynchronizer::class)->syncTokens($existingAccount); - - session()->forget(['linkedin_page_pending', 'linkedin_page_reconnect_id']); - - return $this->popupCallback(true, __('accounts.popup_callback.reconnected'), $this->platform->value); - } - } - - $account = $workspace->socialAccounts()->updateOrCreate( - [ - 'platform' => $this->platform->value, - 'platform_user_id' => $request->organization_id, - ], - [ - 'username' => $request->organization_vanity_name, - 'display_name' => $request->organization_name, - 'avatar_url' => $avatarPath, - 'access_token' => $pendingData['token'], - 'refresh_token' => $pendingData['refresh_token'], - 'token_expires_at' => $pendingData['expires_in'] ? now()->addSeconds($pendingData['expires_in']) : null, - // LinkedIn returns scope CSV-joined but Socialite splits on space, so re-split here. - 'scopes' => explode(',', implode(',', $pendingData['approved_scopes'] ?? [])), - 'status' => Status::Connected, - 'error_message' => null, - 'disconnected_at' => null, - 'meta' => [ - 'organization_id' => $request->organization_id, - 'admin_user_id' => $pendingData['user_id'], - 'admin_name' => $pendingData['name'], - ], - ], - ); - - // Sync tokens to LinkedIn personal if it exists - app(LinkedInTokenSynchronizer::class)->syncTokens($account); - - session()->forget(['linkedin_page_pending', 'linkedin_page_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('LinkedIn Page selection error', [ - 'error' => $e->getMessage(), - ]); - - return $this->popupCallback(false, __('accounts.popup_callback.error_connecting_page'), $this->platform->value); - } - } - - private function fetchOrganizations(string $accessToken): array - { - $response = Http::withToken($accessToken) - ->get(config('trypost.platforms.linkedin-page.api').'/v2/organizationAcls', [ - 'q' => 'roleAssignee', - 'role' => 'ADMINISTRATOR', - 'projection' => '(elements*(organization~(id,localizedName,vanityName,logoV2(original~:playableStreams))))', - ]); - - if ($response->failed()) { - Log::error('LinkedIn Organizations fetch error', [ - 'error' => $response->body(), - ]); - - return []; - } - - $data = $response->json(); - $organizations = []; - - foreach (data_get($data, 'elements', []) as $element) { - $org = data_get($element, 'organization~', null); - if ($org) { - $logoUrl = null; - $logoUrl = data_get($org, 'logoV2.original~.elements.0.identifiers.0.identifier'); - - $organizations[] = [ - 'id' => data_get($org, 'id'), - 'name' => data_get($org, 'localizedName', 'Unknown'), - 'vanity_name' => data_get($org, 'vanityName', null), - 'logo' => $logoUrl, - ]; - } - } - - return $organizations; - } -} diff --git a/app/Http/Controllers/Auth/MastodonController.php b/app/Http/Controllers/Auth/MastodonController.php index d42367b6..2dd0966e 100644 --- a/app/Http/Controllers/Auth/MastodonController.php +++ b/app/Http/Controllers/Auth/MastodonController.php @@ -7,14 +7,12 @@ use App\Enums\SocialAccount\Platform as SocialPlatform; use App\Enums\SocialAccount\Status; use App\Models\Workspace; -use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; -use Illuminate\View\View; use Inertia\Inertia; -use Inertia\Response; -use Symfony\Component\HttpFoundation\Response as SymfonyResponse; +use Inertia\Response as InertiaResponse; +use Symfony\Component\HttpFoundation\Response; class MastodonController extends SocialController { @@ -25,16 +23,12 @@ class MastodonController extends SocialController /** * Show form to enter Mastodon instance URL */ - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): InertiaResponse { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); return Inertia::render('accounts/MastodonConnect', [ @@ -45,7 +39,7 @@ public function connect(Request $request): Response|RedirectResponse /** * Register app on instance and redirect to OAuth */ - public function authorizeInstance(Request $request): SymfonyResponse|RedirectResponse + public function authorizeInstance(Request $request): Response { $this->ensurePlatformEnabled(); @@ -55,10 +49,6 @@ public function authorizeInstance(Request $request): SymfonyResponse|RedirectRes $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); $instance = rtrim($request->instance, '/'); @@ -117,7 +107,7 @@ public function authorizeInstance(Request $request): SymfonyResponse|RedirectRes /** * Handle OAuth callback */ - public function callback(Request $request): View + public function callback(Request $request): InertiaResponse { $workspaceId = session('social_connect_workspace'); $savedState = session('mastodon_oauth_state'); diff --git a/app/Http/Controllers/Auth/PinterestController.php b/app/Http/Controllers/Auth/PinterestController.php index d82eeedb..9da9b746 100644 --- a/app/Http/Controllers/Auth/PinterestController.php +++ b/app/Http/Controllers/Auth/PinterestController.php @@ -7,10 +7,9 @@ use App\Enums\SocialAccount\Platform as SocialPlatform; use App\Enums\SocialAccount\Status; use App\Models\Workspace; -use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; -use Illuminate\View\View; +use Inertia\Response as InertiaResponse; use Laravel\Socialite\Facades\Socialite; use Symfony\Component\HttpFoundation\Response; @@ -28,22 +27,18 @@ class PinterestController extends SocialController 'user_accounts:read', ]; - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): Response { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); return $this->redirectToProvider($request, $this->driver, $this->scopes); } - public function callback(Request $request): View + public function callback(Request $request): InertiaResponse { $workspaceId = session('social_connect_workspace'); diff --git a/app/Http/Controllers/Auth/SocialController.php b/app/Http/Controllers/Auth/SocialController.php index bd4a68cd..ec2ed978 100644 --- a/app/Http/Controllers/Auth/SocialController.php +++ b/app/Http/Controllers/Auth/SocialController.php @@ -16,7 +16,6 @@ use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; -use Illuminate\View\View; use Inertia\Inertia; use Inertia\Response; use Laravel\Socialite\Facades\Socialite; @@ -33,22 +32,20 @@ protected function ensurePlatformEnabled(): void } } - public function index(Request $request): Response|RedirectResponse + public function index(Request $request): Response { $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); - $platforms = collect(SocialPlatform::enabled())->map(fn ($platform) => [ - 'value' => $platform->value, - 'label' => $platform->label(), - 'color' => $platform->color(), - 'network' => $platform->network(), - ])->values(); + $platforms = collect(SocialPlatform::cases()) + ->filter(fn ($platform) => $platform->isConnectable()) + ->map(fn ($platform) => [ + 'value' => $platform->value, + 'label' => $platform->label(), + 'color' => $platform->color(), + 'network' => $platform->network(), + ])->values(); return Inertia::render('accounts/Index', [ 'workspace' => $workspace, @@ -63,10 +60,6 @@ public function disconnect(Request $request, SocialAccount $account): RedirectRe { $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); if ($account->workspace_id !== $workspace->id) { @@ -92,10 +85,6 @@ public function toggleActive(Request $request, SocialAccount $account): Redirect { $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); if ($account->workspace_id !== $workspace->id) { @@ -115,10 +104,6 @@ protected function redirectToProvider(Request $request, string $driver, array $s { $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - session(['social_connect_workspace' => $workspace->id]); return Inertia::location( @@ -133,7 +118,7 @@ protected function handleCallback( Request $request, SocialPlatform $platform, string $driver - ): View { + ): Response { $workspaceId = session('social_connect_workspace'); if (! $workspaceId) { @@ -189,13 +174,15 @@ protected function forgetSocialConnectSession(): void } /** - * Return a view that closes the popup and notifies the parent window. + * Render the Inertia page that notifies the opener and closes the connect + * popup. Used by both the GET OAuth callbacks (a fresh popup page load) and + * the XHR selection submits (an Inertia visit that swaps to this page). */ - protected function popupCallback(bool $success, string $message, ?string $platform = null): View + protected function popupCallback(bool $success, string $message, ?string $platform = null): Response { $this->forgetSocialConnectSession(); - return view('auth.social-callback', [ + return Inertia::render('accounts/PopupCallback', [ 'success' => $success, 'message' => $message, 'platform' => $platform, diff --git a/app/Http/Controllers/Auth/ThreadsController.php b/app/Http/Controllers/Auth/ThreadsController.php index 3455226e..c8445f7a 100644 --- a/app/Http/Controllers/Auth/ThreadsController.php +++ b/app/Http/Controllers/Auth/ThreadsController.php @@ -8,12 +8,11 @@ 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 Illuminate\View\View; use Inertia\Inertia; +use Inertia\Response as InertiaResponse; use Symfony\Component\HttpFoundation\Response; class ThreadsController extends SocialController @@ -26,16 +25,12 @@ class ThreadsController extends SocialController 'threads_manage_insights', ]; - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): Response { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); session([ @@ -57,7 +52,7 @@ public function connect(Request $request): Response|RedirectResponse return Inertia::location("https://threads.net/oauth/authorize?{$params}"); } - public function callback(Request $request): View + public function callback(Request $request): InertiaResponse { $workspaceId = session('social_connect_workspace'); $savedState = session('threads_oauth_state'); diff --git a/app/Http/Controllers/Auth/TikTokController.php b/app/Http/Controllers/Auth/TikTokController.php index b2d49ecc..8c7a3a31 100644 --- a/app/Http/Controllers/Auth/TikTokController.php +++ b/app/Http/Controllers/Auth/TikTokController.php @@ -7,10 +7,9 @@ use App\Enums\SocialAccount\Platform as SocialPlatform; use App\Enums\SocialAccount\Status; use App\Models\Workspace; -use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; -use Illuminate\View\View; +use Inertia\Response as InertiaResponse; use Laravel\Socialite\Facades\Socialite; use Symfony\Component\HttpFoundation\Response; @@ -29,16 +28,12 @@ class TikTokController extends SocialController 'video.list', ]; - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): Response { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); session(['social_reconnect_id' => null]); @@ -46,7 +41,7 @@ public function connect(Request $request): Response|RedirectResponse return $this->redirectToProvider($request, $this->driver, $this->scopes); } - public function callback(Request $request): View + public function callback(Request $request): InertiaResponse { $workspaceId = session('social_connect_workspace'); diff --git a/app/Http/Controllers/Auth/XController.php b/app/Http/Controllers/Auth/XController.php index 9f3e3cd4..973f95ea 100644 --- a/app/Http/Controllers/Auth/XController.php +++ b/app/Http/Controllers/Auth/XController.php @@ -5,9 +5,8 @@ namespace App\Http\Controllers\Auth; use App\Enums\SocialAccount\Platform as SocialPlatform; -use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; -use Illuminate\View\View; +use Inertia\Response as InertiaResponse; use Symfony\Component\HttpFoundation\Response; class XController extends SocialController @@ -24,22 +23,18 @@ class XController extends SocialController 'offline.access', ]; - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): Response { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); return $this->redirectToProvider($request, $this->driver, $this->scopes); } - public function callback(Request $request): View + public function callback(Request $request): InertiaResponse { return $this->handleCallback($request, $this->platform, $this->driver); } diff --git a/app/Http/Controllers/Auth/YouTubeController.php b/app/Http/Controllers/Auth/YouTubeController.php index a1758a6b..6a86cf38 100644 --- a/app/Http/Controllers/Auth/YouTubeController.php +++ b/app/Http/Controllers/Auth/YouTubeController.php @@ -12,8 +12,8 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; -use Illuminate\View\View; use Inertia\Inertia; +use Inertia\Response as InertiaResponse; use Laravel\Socialite\Facades\Socialite; use Symfony\Component\HttpFoundation\Response; @@ -30,16 +30,12 @@ class YouTubeController extends SocialController 'https://www.googleapis.com/auth/yt-analytics.readonly', ]; - public function connect(Request $request): Response|RedirectResponse + public function connect(Request $request): Response { $this->ensurePlatformEnabled(); $workspace = $request->user()->currentWorkspace; - if (! $workspace) { - return redirect()->route('app.workspaces.create'); - } - $this->authorize('manageAccounts', $workspace); session([ @@ -50,7 +46,7 @@ public function connect(Request $request): Response|RedirectResponse return $this->redirectToGoogle(); } - public function callback(Request $request): View|RedirectResponse + public function callback(Request $request): InertiaResponse|RedirectResponse { $workspaceId = session('social_connect_workspace'); @@ -168,7 +164,7 @@ public function selectChannel(Request $request) ]); } - public function select(Request $request): View + public function select(Request $request): InertiaResponse { $request->validate([ 'channel_id' => 'required|string', diff --git a/app/Http/Middleware/App/EnsureAccountReady.php b/app/Http/Middleware/App/EnsureAccountReady.php index 775bc3fa..7e15bfe6 100644 --- a/app/Http/Middleware/App/EnsureAccountReady.php +++ b/app/Http/Middleware/App/EnsureAccountReady.php @@ -22,9 +22,8 @@ public function handle(Request $request, Closure $next): Response return $next($request); } - $account = $user->account; - if (! config('trypost.self_hosted')) { + $account = $user->account; $requiresCardForTrial = (bool) config('trypost.billing.require_card_for_trial', true); $hasAccess = $account && ( $account->subscribed(Account::SUBSCRIPTION_NAME) @@ -36,10 +35,6 @@ public function handle(Request $request, Closure $next): Response } } - if (! $user->workspaces()->exists()) { - return redirect()->route('app.workspaces.create'); - } - return $next($request); } } diff --git a/app/Http/Middleware/App/EnsureHasWorkspace.php b/app/Http/Middleware/App/EnsureHasWorkspace.php new file mode 100644 index 00000000..232d9b00 --- /dev/null +++ b/app/Http/Middleware/App/EnsureHasWorkspace.php @@ -0,0 +1,30 @@ +user(); + + if ($user && ! $user->currentWorkspace) { + return redirect()->route('app.workspaces.create'); + } + + return $next($request); + } +} diff --git a/app/Http/Requests/Api/Post/StoreMediaRequest.php b/app/Http/Requests/Api/Post/StoreMediaRequest.php index d31a265b..77075a7c 100644 --- a/app/Http/Requests/Api/Post/StoreMediaRequest.php +++ b/app/Http/Requests/Api/Post/StoreMediaRequest.php @@ -22,6 +22,7 @@ public function rules(): array $allowedMimes = [ ...MediaType::Image->allowedMimeTypes(), ...MediaType::Video->allowedMimeTypes(), + ...MediaType::Document->allowedMimeTypes(), ]; return [ diff --git a/app/Http/Requests/Api/Post/UpdatePostRequest.php b/app/Http/Requests/Api/Post/UpdatePostRequest.php index 7d3ef18e..7f226fb8 100644 --- a/app/Http/Requests/Api/Post/UpdatePostRequest.php +++ b/app/Http/Requests/Api/Post/UpdatePostRequest.php @@ -10,6 +10,7 @@ use App\Models\Post; use App\Models\PostPlatform; use App\Rules\ContentFitsPlatformLimits; +use App\Rules\ContentTypeCompatibleWithMedia; use App\Rules\ContentTypeMatchesPostPlatform; use App\Support\PostPlatformMetaRules; use Illuminate\Foundation\Http\FormRequest; @@ -73,6 +74,8 @@ public function withValidator(Validator $validator): void return; } + $this->addMediaCompatibilityErrors($validator); + $platformsById = $this->resolveSelectedPlatforms(); PostPlatformMetaRules::addRequiredOnPublishErrors( @@ -83,6 +86,35 @@ public function withValidator(Validator $validator): void }); } + /** + * On publish/schedule, validate every platform's *effective* content_type + * (resubmitted in this request, or its stored value) against the *effective* + * media (the request's media when sent, otherwise the post's stored media). + * This closes the gap where a client publishes a misconfigured post — e.g. a + * PDF on a regular LinkedIn post — without resubmitting content_type, which a + * field-level rule on `platforms.*.content_type` would skip. + */ + private function addMediaCompatibilityErrors(Validator $validator): void + { + $routePost = $this->route('post'); + $post = $routePost instanceof Post ? $routePost : Post::find($routePost); + + if (! $post) { + return; + } + + $media = $this->has('media') ? (array) $this->input('media', []) : (array) ($post->media ?? []); + + $entries = ContentTypeCompatibleWithMedia::entriesForUpdate( + $post, + $this->has('platforms') ? (array) $this->input('platforms', []) : null, + ); + + foreach (ContentTypeCompatibleWithMedia::errorsFor($entries, $media) as $key => $message) { + $validator->errors()->add($key, $message); + } + } + /** * @return Collection */ diff --git a/app/Http/Requests/Api/StoreUploadRequest.php b/app/Http/Requests/Api/StoreUploadRequest.php index 812c8ac9..f07237ed 100644 --- a/app/Http/Requests/Api/StoreUploadRequest.php +++ b/app/Http/Requests/Api/StoreUploadRequest.php @@ -22,6 +22,7 @@ public function rules(): array $allowed = implode(',', array_merge( MediaType::Image->allowedMimeTypes(), MediaType::Video->allowedMimeTypes(), + MediaType::Document->allowedMimeTypes(), )); $maxKb = (int) config('ai.mcp.upload.max_size_mb') * 1024; diff --git a/app/Http/Requests/App/Asset/StoreAssetRequest.php b/app/Http/Requests/App/Asset/StoreAssetRequest.php index 7f649b0c..ddc07b10 100644 --- a/app/Http/Requests/App/Asset/StoreAssetRequest.php +++ b/app/Http/Requests/App/Asset/StoreAssetRequest.php @@ -16,7 +16,7 @@ public function authorize(): bool public function rules(): array { - $allowedMimes = [...MediaType::Image->allowedMimeTypes(), ...MediaType::Video->allowedMimeTypes()]; + $allowedMimes = [...MediaType::Image->allowedMimeTypes(), ...MediaType::Video->allowedMimeTypes(), ...MediaType::Document->allowedMimeTypes()]; return [ // Use the largest per-type cap as the upper bound; per-type diff --git a/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php b/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php index 84ebf16f..3244d682 100644 --- a/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php +++ b/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php @@ -39,7 +39,7 @@ protected function prepareForValidation(): void */ public function rules(): array { - $allowedSuffixes = collect([MediaType::Image, MediaType::Video]) + $allowedSuffixes = collect([MediaType::Image, MediaType::Video, MediaType::Document]) ->flatMap(fn (MediaType $type) => $type->extensions()) ->map(fn (string $ext) => '.'.$ext) ->all(); diff --git a/app/Http/Resources/App/SocialAccountResource.php b/app/Http/Resources/App/SocialAccountResource.php index bee0dda4..e4bef4e5 100644 --- a/app/Http/Resources/App/SocialAccountResource.php +++ b/app/Http/Resources/App/SocialAccountResource.php @@ -17,6 +17,7 @@ public function toArray(Request $request): array return [ 'id' => $this->id, 'platform' => $this->platform, + 'network' => $this->platform->network(), 'platform_user_id' => $this->platform_user_id, 'username' => $this->username, 'display_name' => $this->display_name, diff --git a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php index 97a00463..faab44f5 100644 --- a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php +++ b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php @@ -14,7 +14,7 @@ use Laravel\Mcp\Server\Attributes\Description; use Laravel\Mcp\Server\Tool; -#[Description('Download images or videos from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. Allowed types are intersected with the platforms enabled on the post (e.g. nothing accepted if no platform supports the media type).')] +#[Description('Download images, videos, or PDF documents from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. Allowed types are intersected with the platforms enabled on the post (e.g. nothing accepted if no platform supports the media type).')] class AttachMediaFromUrlTool extends Tool { public function handle(Request $request): Response|ResponseFactory @@ -53,7 +53,7 @@ public function schema(JsonSchema $schema): array 'urls' => $schema->array() ->items($schema->string()) ->required() - ->description('Public HTTP/HTTPS URLs of images or videos. Max 10 URLs per call, 50MB per file. Allowed types: image/jpeg, image/png, image/gif, image/webp, video/mp4, video/quicktime, video/webm.'), + ->description('Public HTTP/HTTPS URLs of images, videos, or PDFs. Max 10 URLs per call, 50MB per file. Allowed types: image/jpeg, image/png, image/gif, image/webp, video/mp4, video/quicktime, application/pdf.'), ]; } } diff --git a/app/Mcp/Tools/Post/PublishPostTool.php b/app/Mcp/Tools/Post/PublishPostTool.php index da2feac9..00e0990d 100644 --- a/app/Mcp/Tools/Post/PublishPostTool.php +++ b/app/Mcp/Tools/Post/PublishPostTool.php @@ -9,6 +9,7 @@ use App\Enums\Post\Status; use App\Http\Resources\Api\PostResource; use App\Models\Post; +use App\Rules\ContentTypeCompatibleWithMedia; use App\Support\PostPlatformMetaRules; use App\Support\PostStatusRules; use Illuminate\Contracts\JsonSchema\JsonSchema; @@ -43,6 +44,7 @@ public function handle(Request $request): Response|ResponseFactory } PostPlatformMetaRules::assertStoredPostPublishable($post); + ContentTypeCompatibleWithMedia::assertStoredPostCompatible($post); $scheduledAt = data_get($validated, 'scheduled_at'); diff --git a/app/Mcp/Tools/Post/RequestMediaUploadTool.php b/app/Mcp/Tools/Post/RequestMediaUploadTool.php index fb17667b..2b380e50 100644 --- a/app/Mcp/Tools/Post/RequestMediaUploadTool.php +++ b/app/Mcp/Tools/Post/RequestMediaUploadTool.php @@ -14,7 +14,7 @@ use Laravel\Mcp\Server\Attributes\Description; use Laravel\Mcp\Server\Tool; -#[Description('Issue a one-shot signed POST URL that lets the user upload a local file (image or video, up to the workspace upload cap — 50 MB by default) directly to this workspace. Returns an upload_token and upload_url. Hand the URL to the user (e.g. as a curl command with `-F media=@path/to/file`) or to the MCP client. After upload, call AttachMediaFromUploadTool(post_id, upload_token) to attach the result to a post.')] +#[Description('Issue a one-shot signed POST URL that lets the user upload a local file (image, video, or PDF document, up to the workspace upload cap — 50 MB by default) directly to this workspace. Returns an upload_token and upload_url. Hand the URL to the user (e.g. as a curl command with `-F media=@path/to/file`) or to the MCP client. After upload, call AttachMediaFromUploadTool(post_id, upload_token) to attach the result to a post.')] class RequestMediaUploadTool extends Tool { public function handle(Request $request): Response|ResponseFactory diff --git a/app/Mcp/Tools/Post/UpdatePostTool.php b/app/Mcp/Tools/Post/UpdatePostTool.php index 055b5942..18dea6c5 100644 --- a/app/Mcp/Tools/Post/UpdatePostTool.php +++ b/app/Mcp/Tools/Post/UpdatePostTool.php @@ -10,11 +10,13 @@ use App\Enums\PostPlatform\ContentType; use App\Http\Resources\Api\PostResource; use App\Models\Post; +use App\Rules\ContentTypeCompatibleWithMedia; use App\Rules\ContentTypeMatchesPostPlatform; use App\Support\PostPlatformMetaRules; use App\Support\PostStatusRules; use Illuminate\Contracts\JsonSchema\JsonSchema; use Illuminate\Validation\Rule; +use Illuminate\Validation\ValidationException; use Laravel\Mcp\Request; use Laravel\Mcp\Response; use Laravel\Mcp\ResponseFactory; @@ -48,10 +50,30 @@ public function handle(Request $request): Response|ResponseFactory 'uuid', Rule::exists('post_platforms', 'id')->where('post_id', $post->id), ], - 'platforms.*.content_type' => ['sometimes', 'string', Rule::in(array_column(ContentType::cases(), 'value')), new ContentTypeMatchesPostPlatform], + 'platforms.*.content_type' => [ + 'sometimes', + 'string', + Rule::in(array_column(ContentType::cases(), 'value')), + new ContentTypeMatchesPostPlatform, + ], ...PostPlatformMetaRules::rules(), ]); + // On schedule, validate each platform's effective content_type (resubmitted + // here, or stored) against the post's stored media — the tool can't change + // media, so a misconfigured post can't be scheduled even without resubmitting + // content_type. Mirrors the public API's withValidator check. + if (data_get($validated, 'status') === Status::Scheduled->value) { + $errors = ContentTypeCompatibleWithMedia::errorsFor( + ContentTypeCompatibleWithMedia::entriesForUpdate($post, data_get($validated, 'platforms')), + (array) ($post->media ?? []), + ); + + if ($errors !== []) { + throw ValidationException::withMessages($errors); + } + } + $payload = collect($validated)->except('post_id')->all(); $result = UpdatePost::execute($workspace, $post, $payload); diff --git a/app/Models/Media.php b/app/Models/Media.php index f60f24fb..fced09bc 100644 --- a/app/Models/Media.php +++ b/app/Models/Media.php @@ -61,24 +61,17 @@ protected function url(): Attribute public function isVideo(): bool { - if ($this->mime_type) { - return str_starts_with($this->mime_type, 'video/'); - } - - $extension = strtolower(pathinfo($this->path, PATHINFO_EXTENSION)); - - return in_array($extension, ['mp4', 'mov', 'avi', 'wmv', 'webm', 'mkv', 'm4v']); + return MediaType::classify($this->mime_type, $this->path) === MediaType::Video; } public function isImage(): bool { - if ($this->mime_type) { - return str_starts_with($this->mime_type, 'image/'); - } + return MediaType::classify($this->mime_type, $this->path) === MediaType::Image; + } - $extension = strtolower(pathinfo($this->path, PATHINFO_EXTENSION)); - - return in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif']); + public function isDocument(): bool + { + return MediaType::classify($this->mime_type, $this->path) === MediaType::Document; } public function getTemporaryUrl(int $expirationMinutes = 60): string diff --git a/app/Models/Traits/HasMedia.php b/app/Models/Traits/HasMedia.php index c1b9cb5e..f2e1752d 100644 --- a/app/Models/Traits/HasMedia.php +++ b/app/Models/Traits/HasMedia.php @@ -4,6 +4,7 @@ namespace App\Models\Traits; +use App\Enums\Media\Type; use App\Models\Media; use App\Models\User; use App\Models\Workspace; @@ -156,15 +157,8 @@ public function isSingleMediaCollection(string $collection): bool private function getMediaType(string $mimeType): string { - if (str_starts_with($mimeType, 'image/')) { - return 'image'; - } - - if (str_starts_with($mimeType, 'video/')) { - return 'video'; - } - - throw new \InvalidArgumentException("Unsupported media MIME type: {$mimeType}"); + return (Type::classify($mimeType) + ?? throw new \InvalidArgumentException("Unsupported media MIME type: {$mimeType}"))->value; } private function getMediaMeta(UploadedFile $file, string $type): array diff --git a/app/Rules/ContentTypeCompatibleWithMedia.php b/app/Rules/ContentTypeCompatibleWithMedia.php index 2fd2e5f1..98372859 100644 --- a/app/Rules/ContentTypeCompatibleWithMedia.php +++ b/app/Rules/ContentTypeCompatibleWithMedia.php @@ -6,10 +6,12 @@ use App\Enums\Media\Type as MediaType; use App\Enums\PostPlatform\ContentType; +use App\Models\Post; use Closure; use Illuminate\Contracts\Validation\DataAwareRule; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Translation\PotentiallyTranslatedString; +use Illuminate\Validation\ValidationException; class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRule { @@ -18,6 +20,14 @@ class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRule */ private array $data = []; + /** + * @param array>|null $fallbackMedia Stored media used + * when the request omits the `media` key entirely — lets API/MCP partial + * updates (which don't resubmit media) validate a content_type against the + * post's already-stored media. + */ + public function __construct(private ?array $fallbackMedia = null) {} + /** * @param array $data */ @@ -28,6 +38,83 @@ public function setData(array $data): static return $this; } + /** + * Validate every enabled platform's stored content_type against the post's + * stored media. Used by publish flows that don't resubmit media (e.g. the + * MCP publish tool) — the media-side mirror of + * PostPlatformMetaRules::assertStoredPostPublishable(). + * + * @throws ValidationException + */ + public static function assertStoredPostCompatible(Post $post): void + { + $errors = self::errorsFor( + self::entriesForUpdate($post, null), + (array) ($post->media ?? []), + ); + + if ($errors !== []) { + throw ValidationException::withMessages($errors); + } + } + + /** + * The per-platform entries to validate for a post update: each platform's + * effective content_type (resubmitted in this request, else its stored + * value), keyed by the error path the caller surfaces. When $requestPlatforms + * is null, the post's currently-enabled platforms are used. + * + * @param array|null $requestPlatforms + * @return array + */ + public static function entriesForUpdate(Post $post, ?array $requestPlatforms): array + { + if (is_array($requestPlatforms)) { + return collect($requestPlatforms)->map(fn ($platform, $index): array => [ + 'key' => "platforms.{$index}.content_type", + 'content_type' => data_get($platform, 'content_type') + ?? $post->postPlatforms()->where('id', data_get($platform, 'id'))->first()?->content_type?->value, + ])->all(); + } + + return $post->postPlatforms()->where('enabled', true)->get()->values() + ->map(fn ($postPlatform, $index): array => [ + 'key' => "platforms.{$index}.content_type", + 'content_type' => $postPlatform->content_type?->value, + ])->all(); + } + + /** + * Validate a set of platform entries against the given media, returning + * `[errorKey => message]` for each incompatible content_type. + * + * @param array $entries + * @param array $media + * @return array + */ + public static function errorsFor(array $entries, array $media): array + { + $errors = []; + + foreach ($entries as $entry) { + $contentType = data_get($entry, 'content_type'); + + if ($contentType === null) { + continue; + } + + (new self($media))->validate( + $entry['key'], + (string) $contentType, + function (string $message) use (&$errors, $entry): void { + $errors[$entry['key']] = $message; + }, + ); + } + + return $errors; + } + /** * @param Closure(string, ?string=): PotentiallyTranslatedString $fail */ @@ -38,7 +125,11 @@ public function validate(string $attribute, mixed $value, Closure $fail): void return; } - $media = (array) data_get($this->data, 'media', []); + // Use the request's media when present; otherwise fall back to the + // post's stored media so partial publish/schedule updates still validate. + $media = array_key_exists('media', $this->data) + ? (array) data_get($this->data, 'media', []) + : (array) ($this->fallbackMedia ?? []); $count = count($media); if ($contentType->requiresMedia() && $count === 0) { @@ -53,6 +144,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $hasImage = collect($media)->contains(fn ($item) => $this->isImage((array) $item)); $hasVideo = collect($media)->contains(fn ($item) => $this->isVideo((array) $item)); + $hasDocument = collect($media)->contains(fn ($item) => $this->isDocument((array) $item)); if ($hasImage && ! $contentType->supportsImage()) { $fail("{$contentType->label()} does not support images."); @@ -62,6 +154,15 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $fail("{$contentType->label()} does not support videos."); } + if ($hasDocument && ! $contentType->supportsDocument()) { + $fail("{$contentType->label()} does not support PDF documents."); + } + + // A PDF document is always published on its own (LinkedIn document post). + if ($hasDocument && $count > 1) { + $fail('A PDF document must be the only attachment.'); + } + if ($hasImage && $hasVideo && ! $contentType->supportsMixedMedia()) { $fail("{$contentType->label()} can't combine an image and a video in the same post."); } @@ -72,11 +173,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void */ private function isImage(array $item): bool { - if (data_get($item, 'type') === MediaType::Image->value) { - return true; - } - - return str_starts_with((string) data_get($item, 'mime_type', ''), 'image/'); + return $this->isType($item, MediaType::Image); } /** @@ -84,10 +181,26 @@ private function isImage(array $item): bool */ private function isVideo(array $item): bool { - if (data_get($item, 'type') === MediaType::Video->value) { - return true; - } + return $this->isType($item, MediaType::Video); + } - return str_starts_with((string) data_get($item, 'mime_type', ''), 'video/'); + /** + * @param array $item + */ + private function isDocument(array $item): bool + { + return $this->isType($item, MediaType::Document); + } + + /** + * A media item matches a type when it carries that explicit `type`, or when + * its MIME classifies as that type. + * + * @param array $item + */ + private function isType(array $item, MediaType $type): bool + { + return data_get($item, 'type') === $type->value + || MediaType::classify(data_get($item, 'mime_type')) === $type; } } diff --git a/app/Services/Social/AbstractLinkedInPublisher.php b/app/Services/Social/AbstractLinkedInPublisher.php new file mode 100644 index 00000000..8fc052cc --- /dev/null +++ b/app/Services/Social/AbstractLinkedInPublisher.php @@ -0,0 +1,533 @@ +validateContentLength($postPlatform); + + $content = $postPlatform->post->content + ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) + : null; + + $this->account = $postPlatform->socialAccount; + $this->hasRetried = false; + + if ($this->account->is_token_expired || $this->account->is_token_expiring_soon) { + app(ConnectionVerifier::class)->refreshToken($this->account); + } + + $this->accessToken = $this->account->access_token; + + try { + return $this->dispatchByMedia($content, $postPlatform); + } catch (TokenExpiredException $e) { + return $this->retryWithRefresh($postPlatform, $content, $e); + } + } + + private function dispatchByMedia(?string $content, PostPlatform $postPlatform): array + { + $media = $postPlatform->post->mediaItems; + + if ($media->contains(fn ($item) => $item->isDocument())) { + return $this->publishDocument($content, $media, $this->resolveDocumentTitle($postPlatform)); + } + + if ($media->filter(fn ($item) => $item->isImage())->count() >= 2) { + return $this->publishCarousel($content, $media); + } + + return $this->publishPost($content, $media); + } + + private function retryWithRefresh(PostPlatform $postPlatform, ?string $content, TokenExpiredException $originalException): array + { + if ($this->hasRetried) { + throw $originalException; + } + + $this->hasRetried = true; + + try { + app(ConnectionVerifier::class)->refreshToken($this->account); + $this->accessToken = $this->account->access_token; + + return $this->dispatchByMedia($content, $postPlatform); + } catch (\Throwable $e) { + Log::error("{$this->label()} refresh failed during retry", [ + 'account_id' => $this->account->id, + 'error' => $e->getMessage(), + ]); + throw $originalException; + } + } + + private function publishPost(?string $content, $media): array + { + $payload = $this->basePayload($content); + + if ($media->isNotEmpty()) { + $mediaUrn = $this->uploadMedia($media->first()); + + if ($mediaUrn) { + $payload['content'] = ['media' => ['id' => $mediaUrn]]; + } + } + + return $this->createPost($payload, 'post creation'); + } + + private function publishCarousel(?string $content, $media): array + { + $images = []; + + $imageItems = collect($media) + ->filter(fn ($item) => $item->isImage()) + ->take($this->platform()->maxImages()); + + foreach ($imageItems as $item) { + $imageUrn = $this->uploadImage($item); + + if ($imageUrn) { + $images[] = [ + 'id' => $imageUrn, + 'altText' => $item->original_filename ?? 'Carousel image', + ]; + } + } + + $payload = $this->basePayload($content); + $payload['content'] = ['multiImage' => ['images' => $images]]; + + return $this->createPost($payload, 'carousel post creation'); + } + + private function publishDocument(?string $content, $media, string $title): array + { + $document = $media->first(fn ($item) => $item->isDocument()); + + if (! $document) { + throw new \Exception("No PDF document for {$this->label()} document post"); + } + + $documentUrn = $this->uploadDocument($document); + + if (! $documentUrn) { + throw new \Exception("{$this->label()} document upload failed"); + } + + $payload = $this->basePayload($content); + $payload['content'] = ['media' => ['id' => $documentUrn, 'title' => $title]]; + + return $this->createPost($payload, 'document post creation'); + } + + /** + * The shared post envelope shared by every content shape. + * + * @return array + */ + private function basePayload(?string $content): array + { + return [ + 'author' => $this->authorUrn(), + 'commentary' => $content ?? '', + 'visibility' => 'PUBLIC', + 'distribution' => [ + 'feedDistribution' => 'MAIN_FEED', + 'targetEntities' => [], + 'thirdPartyDistributionChannels' => [], + ], + 'lifecycleState' => 'PUBLISHED', + ]; + } + + /** + * POST the assembled payload to the Posts API and return the created post. + * + * @param array $payload + * @return array{id: string, url: ?string} + */ + private function createPost(array $payload, string $context): array + { + $response = $this->getHttpClient()->post("{$this->baseUrl()}/rest/posts", $payload); + + if ($response->failed()) { + Log::error("{$this->label()} {$context} failed", [ + 'status' => $response->status(), + 'body' => $this->redactResponseBody($response->body()), + ]); + $this->handleApiError($response); + } + + $postId = $response->header('x-restli-id'); + + return [ + 'id' => $postId ?? 'unknown', + 'url' => $this->postUrl($postId ?: null), + ]; + } + + /** + * The title shown on a LinkedIn document (PDF carousel) post. Falls back to + * the uploaded file name, then a generic label, so it's never empty. + */ + private function resolveDocumentTitle(PostPlatform $postPlatform): string + { + $title = data_get($postPlatform->meta, 'document_title'); + + if (filled($title)) { + return (string) $title; + } + + return $postPlatform->post->mediaItems->first(fn ($media) => $media->isDocument())?->original_filename ?? 'Document'; + } + + private function uploadMedia($mediaItem): ?string + { + return match (true) { + $mediaItem->isVideo() => $this->uploadVideo($mediaItem), + $mediaItem->isImage() => $this->uploadImage($mediaItem), + default => null, + }; + } + + private function uploadImage($mediaItem): ?string + { + $initResponse = $this->getHttpClient() + ->post("{$this->baseUrl()}/rest/images?action=initializeUpload", [ + 'initializeUploadRequest' => ['owner' => $this->authorUrn()], + ]); + + if ($initResponse->failed()) { + Log::error("{$this->label()} image init failed", ['body' => $this->redactResponseBody($initResponse->body())]); + $this->handleApiError($initResponse); + } + + $initData = $initResponse->json(); + $uploadUrl = data_get($initData, 'value.uploadUrl'); + $imageUrn = data_get($initData, 'value.image'); + + if (! $uploadUrl || ! $imageUrn) { + throw new \Exception("{$this->label()} image upload init missing uploadUrl or image URN"); + } + + $tempFile = tempnam(sys_get_temp_dir(), 'li_image_'); + + try { + $this->downloadToTempFile($mediaItem->url, $tempFile); + + $detectedMime = mime_content_type($tempFile) ?: ''; + if (MediaType::classify($detectedMime) === MediaType::Image && ! MediaType::isGif($detectedMime)) { + $optimizedPath = app(MediaOptimizer::class)->optimizeImage($tempFile, $this->platform()); + @unlink($tempFile); + $tempFile = $optimizedPath; + } + + $stream = fopen($tempFile, 'r'); + + $uploadResponse = Http::withToken($this->accessToken) + ->withHeaders(['Content-Type' => 'application/octet-stream']) + ->withBody($stream, 'application/octet-stream') + ->put($uploadUrl); + + if (is_resource($stream)) { + fclose($stream); + } + + if ($uploadResponse->failed()) { + Log::error("{$this->label()} image upload failed", ['body' => $this->redactResponseBody($uploadResponse->body())]); + $this->handleApiError($uploadResponse); + } + + return $imageUrn; + } finally { + @unlink($tempFile); + } + } + + private function uploadVideo($mediaItem): ?string + { + $tempFile = tempnam(sys_get_temp_dir(), 'li_video_'); + + try { + return $this->doUploadVideo($tempFile, $mediaItem); + } finally { + @unlink($tempFile); + } + } + + private function doUploadVideo(string $tempFile, $mediaItem): ?string + { + $this->downloadToTempFile($mediaItem->url, $tempFile); + + $fileSize = (int) filesize($tempFile); + + $initResponse = $this->getHttpClient() + ->post("{$this->baseUrl()}/rest/videos?action=initializeUpload", [ + 'initializeUploadRequest' => [ + 'owner' => $this->authorUrn(), + 'fileSizeBytes' => $fileSize, + 'uploadCaptions' => false, + 'uploadThumbnail' => false, + ], + ]); + + if ($initResponse->failed()) { + Log::error("{$this->label()} video init failed", ['body' => $this->redactResponseBody($initResponse->body())]); + $this->handleApiError($initResponse); + } + + $initData = $initResponse->json(); + $videoUrn = data_get($initData, 'value.video'); + $uploadInstructions = data_get($initData, 'value.uploadInstructions', []); + $uploadToken = data_get($initData, 'value.uploadToken', ''); + + if (! $videoUrn || empty($uploadInstructions)) { + throw new \Exception("{$this->label()} video upload init missing video URN or upload instructions"); + } + + $uploadedPartIds = []; + $handle = fopen($tempFile, 'r'); + + try { + foreach ($uploadInstructions as $index => $instruction) { + $firstByte = data_get($instruction, 'firstByte'); + $lastByte = data_get($instruction, 'lastByte'); + + $chunkLength = $lastByte - $firstByte + 1; + fseek($handle, $firstByte); + $chunkData = fread($handle, $chunkLength); + + $chunkResponse = Http::withToken($this->accessToken) + ->withHeaders(['Content-Type' => 'application/octet-stream']) + ->timeout(600) + ->withBody($chunkData, 'application/octet-stream') + ->put(data_get($instruction, 'uploadUrl')); + + if ($chunkResponse->failed()) { + Log::error("{$this->label()} video chunk upload failed", [ + 'index' => $index, + 'body' => $this->redactResponseBody($chunkResponse->body()), + ]); + $this->handleApiError($chunkResponse); + } + + $etag = $chunkResponse->header('etag'); + if ($etag) { + $uploadedPartIds[] = $etag; + } + } + } finally { + fclose($handle); + } + + $finalizeResponse = $this->getHttpClient() + ->post("{$this->baseUrl()}/rest/videos?action=finalizeUpload", [ + 'finalizeUploadRequest' => [ + 'video' => $videoUrn, + 'uploadToken' => $uploadToken, + 'uploadedPartIds' => $uploadedPartIds, + ], + ]); + + if ($finalizeResponse->failed()) { + Log::error("{$this->label()} video finalize failed", ['body' => $this->redactResponseBody($finalizeResponse->body())]); + $this->handleApiError($finalizeResponse); + } + + $this->waitForProcessing('videos', $videoUrn, 'video'); + + return $videoUrn; + } + + private function uploadDocument($mediaItem): ?string + { + $initResponse = $this->getHttpClient() + ->post("{$this->baseUrl()}/rest/documents?action=initializeUpload", [ + 'initializeUploadRequest' => ['owner' => $this->authorUrn()], + ]); + + if ($initResponse->failed()) { + Log::error("{$this->label()} document init failed", ['body' => $this->redactResponseBody($initResponse->body())]); + $this->handleApiError($initResponse); + } + + $initData = $initResponse->json(); + $uploadUrl = data_get($initData, 'value.uploadUrl'); + $documentUrn = data_get($initData, 'value.document'); + + if (! $uploadUrl || ! $documentUrn) { + throw new \Exception("{$this->label()} document upload init missing uploadUrl or document URN"); + } + + // The Documents API is not chunked — upload the PDF in a single request. + $tempFile = tempnam(sys_get_temp_dir(), 'li_document_'); + + try { + $this->downloadToTempFile($mediaItem->url, $tempFile); + + $stream = fopen($tempFile, 'r'); + + $uploadResponse = Http::withToken($this->accessToken) + ->withHeaders(['Content-Type' => 'application/pdf']) + ->timeout(600) + ->withBody($stream, 'application/pdf') + ->put($uploadUrl); + + if (is_resource($stream)) { + fclose($stream); + } + + if ($uploadResponse->failed()) { + Log::error("{$this->label()} document upload failed", ['body' => $this->redactResponseBody($uploadResponse->body())]); + $this->handleApiError($uploadResponse); + } + } finally { + @unlink($tempFile); + } + + $this->waitForProcessing('documents', $documentUrn, 'document'); + + return $documentUrn; + } + + /** + * Poll an asset until it finishes processing. LinkedIn rejects a post that + * references an asset still being processed, so we wait for AVAILABLE and + * fail loudly if it never gets there — publishing against an unprocessed + * asset would error out at the API anyway, with a far less obvious message. + */ + private function waitForProcessing(string $resource, string $assetUrn, string $label): void + { + $encodedUrn = urlencode($assetUrn); + + for ($i = 0; $i < $this->processingMaxAttempts(); $i++) { + $response = $this->getHttpClient()->get("{$this->baseUrl()}/rest/{$resource}/{$encodedUrn}"); + + if ($response->failed()) { + Log::warning("{$this->label()} {$label} status check failed", ['attempt' => $i]); + sleep($this->processingPollSeconds()); + + continue; + } + + $status = data_get($response->json(), 'status', 'UNKNOWN'); + + if ($status === 'AVAILABLE') { + return; + } + + if ($status === 'PROCESSING_FAILED') { + throw new \Exception("{$this->label()} {$label} processing failed"); + } + + sleep($this->processingPollSeconds()); + } + + throw new \Exception("{$this->label()} {$label} processing did not complete in time"); + } + + /** + * How many times to poll an uploaded asset for AVAILABLE before giving up. + */ + protected function processingMaxAttempts(): int + { + return 30; + } + + /** + * Seconds to wait between asset processing status checks. + */ + protected function processingPollSeconds(): int + { + return 5; + } + + private function downloadToTempFile(string $url, string $tempFile): void + { + $response = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($url); + + if ($response->failed()) { + throw new \Exception('Failed to download media: HTTP '.$response->status()); + } + } + + private function getHttpClient(): PendingRequest + { + return $this->socialHttp()->withToken($this->accessToken) + ->withHeaders([ + 'X-Restli-Protocol-Version' => '2.0.0', + 'LinkedIn-Version' => $this->apiVersion, + 'Content-Type' => 'application/json', + ]); + } + + private function baseUrl(): string + { + return config("trypost.platforms.{$this->platform()->value}.api"); + } + + private function label(): string + { + return $this->platform()->label(); + } + + private function handleApiError(Response $response): never + { + throw LinkedInPublishException::fromApiResponse($response); + } +} diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.php index 95c63fd3..90a36c6f 100644 --- a/app/Services/Social/BlueskyPublisher.php +++ b/app/Services/Social/BlueskyPublisher.php @@ -4,6 +4,7 @@ namespace App\Services\Social; +use App\Enums\Media\Type as MediaType; use App\Enums\SocialAccount\Platform; use App\Exceptions\Social\BlueskyPublishException; use App\Models\PostPlatform; @@ -151,7 +152,7 @@ private function uploadBlob(SocialAccount $account, string $service, string $url try { // Optimize images for Bluesky's 1MB limit (GIFs are passed through untouched). - if (str_starts_with($mimeType, 'image/') && ! str_starts_with($mimeType, 'image/gif')) { + if (MediaType::classify($mimeType) === MediaType::Image && ! MediaType::isGif($mimeType)) { $optimizedPath = app(MediaOptimizer::class)->optimizeImage($tempFile, Platform::Bluesky); @unlink($tempFile); $tempFile = $optimizedPath; diff --git a/app/Services/Social/ConnectionVerifier.php b/app/Services/Social/ConnectionVerifier.php index 92f62433..085699b1 100644 --- a/app/Services/Social/ConnectionVerifier.php +++ b/app/Services/Social/ConnectionVerifier.php @@ -135,9 +135,6 @@ private function refreshLinkedInToken(SocialAccount $account): void ]); $account->refresh(); - - // Sync tokens between LinkedIn personal and LinkedIn Page - app(LinkedInTokenSynchronizer::class)->syncTokens($account); } private function refreshXToken(SocialAccount $account): void diff --git a/app/Services/Social/Discord/DiscordPublisher.php b/app/Services/Social/Discord/DiscordPublisher.php index aa35d5e3..d624473b 100644 --- a/app/Services/Social/Discord/DiscordPublisher.php +++ b/app/Services/Social/Discord/DiscordPublisher.php @@ -5,6 +5,7 @@ namespace App\Services\Social\Discord; use App\DataTransferObjects\MediaItem; +use App\Enums\Media\Type as MediaType; use App\Enums\SocialAccount\Platform; use App\Exceptions\Social\DiscordPublishException; use App\Exceptions\Social\ErrorCategory; @@ -156,7 +157,7 @@ private function downloadMedia(MediaItem $item): string } // Images are downsized to Discord's limit; videos/gifs are sent as-is. - if ($item->mime_type && str_starts_with($item->mime_type, 'image/') && ! str_contains($item->mime_type, 'gif')) { + if ($item->isImage() && ! MediaType::isGif($item->mime_type)) { try { return app(MediaOptimizer::class)->optimizeImage($tempFile, Platform::Discord); } catch (Throwable) { diff --git a/app/Services/Social/LinkedInPagePublisher.php b/app/Services/Social/LinkedInPagePublisher.php index c1a186f6..1c3b50fc 100644 --- a/app/Services/Social/LinkedInPagePublisher.php +++ b/app/Services/Social/LinkedInPagePublisher.php @@ -4,454 +4,37 @@ namespace App\Services\Social; -use App\Enums\PostPlatform\ContentType; use App\Enums\SocialAccount\Platform; -use App\Exceptions\Social\LinkedInPublishException; -use App\Exceptions\TokenExpiredException; -use App\Models\PostPlatform; -use App\Models\SocialAccount; -use App\Services\Media\MediaOptimizer; -use App\Services\Social\Concerns\HasSocialHttpClient; -use Illuminate\Http\Client\PendingRequest; -use Illuminate\Http\Client\Response; -use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Log; -class LinkedInPagePublisher +/** + * Publishes posts to a LinkedIn company page on behalf of an administering member. + */ +class LinkedInPagePublisher extends AbstractLinkedInPublisher { - use HasSocialHttpClient; - - private string $baseUrl; - - private string $apiVersion = '202601'; - - private string $accessToken; - - public function __construct() + protected function platform(): Platform { - $this->baseUrl = config('trypost.platforms.linkedin-page.api'); + return Platform::LinkedInPage; } - private SocialAccount $account; - - private bool $hasRetried = false; - - public function publish(PostPlatform $postPlatform): array + protected function authorUrn(): string { - $this->validateContentLength($postPlatform); - - $content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null; - - $this->account = $postPlatform->socialAccount; - $this->hasRetried = false; - - if ($this->account->is_token_expired || $this->account->is_token_expiring_soon) { - app(ConnectionVerifier::class)->refreshToken($this->account); - } - - $this->accessToken = $this->account->access_token; - $organizationId = $this->account->meta['organization_id'] ?? null; if (! $organizationId) { throw new \Exception('LinkedIn Page organization ID not configured'); } - $organizationUrn = "urn:li:organization:{$organizationId}"; - $contentType = $postPlatform->content_type; - - try { - return match ($contentType) { - ContentType::LinkedInPageCarousel => $this->publishCarousel($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account), - ContentType::LinkedInPagePost => $this->publishPost($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account), - default => throw new \Exception("Unsupported LinkedIn Page content type: {$contentType?->value}"), - }; - } catch (TokenExpiredException $e) { - return $this->retryWithRefresh($postPlatform, $content, $e); - } + return "urn:li:organization:{$organizationId}"; } - private function retryWithRefresh(PostPlatform $postPlatform, ?string $content, TokenExpiredException $originalException): array + protected function postUrl(?string $postId): ?string { - if ($this->hasRetried) { - throw $originalException; + if (! $postId) { + return null; } - $this->hasRetried = true; - - try { - app(ConnectionVerifier::class)->refreshToken($this->account); - $this->accessToken = $this->account->access_token; - - $organizationId = $this->account->meta['organization_id'] ?? null; - $organizationUrn = "urn:li:organization:{$organizationId}"; - $contentType = $postPlatform->content_type; - - return match ($contentType) { - ContentType::LinkedInPageCarousel => $this->publishCarousel($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account), - ContentType::LinkedInPagePost => $this->publishPost($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account), - default => throw new \Exception("Unsupported LinkedIn Page content type: {$contentType?->value}"), - }; - } catch (\Throwable $e) { - Log::error('LinkedIn Page refresh failed during retry', [ - 'account_id' => $this->account->id, - 'error' => $e->getMessage(), - ]); - throw $originalException; - } - } - - private function publishPost(string $organizationUrn, ?string $content, $media, $account): array - { - $payload = [ - 'author' => $organizationUrn, - 'commentary' => $content ?? '', - 'visibility' => 'PUBLIC', - 'distribution' => [ - 'feedDistribution' => 'MAIN_FEED', - 'targetEntities' => [], - 'thirdPartyDistributionChannels' => [], - ], - 'lifecycleState' => 'PUBLISHED', - ]; - - if ($media->isNotEmpty()) { - $firstMedia = $media->first(); - $mediaUrn = $this->uploadMedia($firstMedia, $organizationUrn); - - if ($mediaUrn) { - $payload['content'] = [ - 'media' => [ - 'id' => $mediaUrn, - ], - ]; - } - } - - $response = $this->getHttpClient() - ->post("{$this->baseUrl}/rest/posts", $payload); - - if ($response->failed()) { - Log::error('LinkedIn Page post creation failed', [ - 'status' => $response->status(), - 'body' => $this->redactResponseBody($response->body()), - ]); - $this->handleApiError($response); - } - - $postId = $response->header('x-restli-id'); - - // Build company page URL - $username = $account->username; - $postUrl = $username - ? "https://www.linkedin.com/company/{$username}/posts/" + return $this->account->username + ? "https://www.linkedin.com/company/{$this->account->username}/posts/" : "https://www.linkedin.com/feed/update/{$postId}"; - - return [ - 'id' => $postId ?? 'unknown', - 'url' => $postId ? $postUrl : null, - ]; - } - - private function publishCarousel(string $organizationUrn, ?string $content, $mediaCollection, $account): array - { - // Upload images and build carousel items - $carouselItems = []; - - foreach ($mediaCollection as $media) { - if (! $media->isImage()) { - continue; - } - - $imageUrn = $this->uploadImage($media, $organizationUrn); - - if ($imageUrn) { - $carouselItems[] = [ - 'altText' => $media->original_filename ?? 'Carousel image', - 'media' => $imageUrn, - ]; - } - } - - if (empty($carouselItems)) { - throw new \Exception('No valid images for LinkedIn Page carousel'); - } - - $payload = [ - 'author' => $organizationUrn, - 'commentary' => $content ?? '', - 'visibility' => 'PUBLIC', - 'distribution' => [ - 'feedDistribution' => 'MAIN_FEED', - 'targetEntities' => [], - 'thirdPartyDistributionChannels' => [], - ], - 'lifecycleState' => 'PUBLISHED', - 'content' => [ - 'multiImage' => [ - 'images' => $carouselItems, - ], - ], - ]; - - $response = $this->getHttpClient() - ->post("{$this->baseUrl}/rest/posts", $payload); - - if ($response->failed()) { - Log::error('LinkedIn Page carousel post creation failed', [ - 'status' => $response->status(), - 'body' => $this->redactResponseBody($response->body()), - ]); - $this->handleApiError($response); - } - - $postId = $response->header('x-restli-id'); - - // Build company page URL - $username = $account->username; - $postUrl = $username - ? "https://www.linkedin.com/company/{$username}/posts/" - : "https://www.linkedin.com/feed/update/{$postId}"; - - return [ - 'id' => $postId ?? 'unknown', - 'url' => $postId ? $postUrl : null, - ]; - } - - private function getHttpClient(): PendingRequest - { - return $this->socialHttp()->withToken($this->accessToken) - ->withHeaders([ - 'X-Restli-Protocol-Version' => '2.0.0', - 'LinkedIn-Version' => $this->apiVersion, - 'Content-Type' => 'application/json', - ]); - } - - private function uploadMedia($mediaItem, string $ownerUrn): ?string - { - $mimeType = $mediaItem->mime_type; - $isVideo = str_starts_with($mimeType, 'video/'); - $isImage = str_starts_with($mimeType, 'image/'); - - if ($isVideo) { - return $this->uploadVideo($mediaItem, $ownerUrn); - } - - if ($isImage) { - return $this->uploadImage($mediaItem, $ownerUrn); - } - - return null; - } - - private function uploadImage($mediaItem, string $ownerUrn): ?string - { - // Step 1: Initialize upload - $initResponse = $this->getHttpClient() - ->post("{$this->baseUrl}/rest/images?action=initializeUpload", [ - 'initializeUploadRequest' => [ - 'owner' => $ownerUrn, - ], - ]); - - if ($initResponse->failed()) { - Log::error('LinkedIn Page image init failed', ['body' => $this->redactResponseBody($initResponse->body())]); - $this->handleApiError($initResponse); - } - - $initData = $initResponse->json(); - $uploadUrl = $initData['value']['uploadUrl'] ?? null; - $imageUrn = $initData['value']['image'] ?? null; - - if (! $uploadUrl || ! $imageUrn) { - throw new \Exception('LinkedIn Page image upload init missing uploadUrl or image URN'); - } - - // Step 2: Download and optimize image - $tempFile = tempnam(sys_get_temp_dir(), 'lip_image_'); - - try { - $downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url); - - if ($downloadResponse->failed()) { - throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status()); - } - - $detectedMime = mime_content_type($tempFile) ?: ''; - if (str_starts_with($detectedMime, 'image/') && ! str_starts_with($detectedMime, 'image/gif')) { - $optimizer = app(MediaOptimizer::class); - $optimizedPath = $optimizer->optimizeImage($tempFile, Platform::LinkedInPage); - @unlink($tempFile); - $tempFile = $optimizedPath; - } - - $stream = fopen($tempFile, 'r'); - - $uploadResponse = Http::withToken($this->accessToken) - ->withHeaders([ - 'Content-Type' => 'application/octet-stream', - ]) - ->withBody($stream, 'application/octet-stream') - ->put($uploadUrl); - - if (is_resource($stream)) { - fclose($stream); - } - - if ($uploadResponse->failed()) { - Log::error('LinkedIn Page image upload failed', ['body' => $this->redactResponseBody($uploadResponse->body())]); - $this->handleApiError($uploadResponse); - } - - return $imageUrn; - } finally { - @unlink($tempFile); - } - } - - private function uploadVideo($mediaItem, string $ownerUrn): ?string - { - $tempFile = tempnam(sys_get_temp_dir(), 'lip_video_'); - - try { - return $this->doUploadVideo($tempFile, $mediaItem, $ownerUrn); - } finally { - @unlink($tempFile); - } - } - - private function doUploadVideo(string $tempFile, $mediaItem, string $ownerUrn): ?string - { - $downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url); - - if ($downloadResponse->failed()) { - throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status()); - } - - $fileSize = (int) filesize($tempFile); - - // Step 1: Initialize upload - $initResponse = $this->getHttpClient() - ->post("{$this->baseUrl}/rest/videos?action=initializeUpload", [ - 'initializeUploadRequest' => [ - 'owner' => $ownerUrn, - 'fileSizeBytes' => $fileSize, - 'uploadCaptions' => false, - 'uploadThumbnail' => false, - ], - ]); - - if ($initResponse->failed()) { - Log::error('LinkedIn Page video init failed', ['body' => $this->redactResponseBody($initResponse->body())]); - $this->handleApiError($initResponse); - } - - $initData = $initResponse->json(); - $videoUrn = $initData['value']['video'] ?? null; - $uploadInstructions = $initData['value']['uploadInstructions'] ?? []; - $uploadToken = $initData['value']['uploadToken'] ?? ''; - - if (! $videoUrn || empty($uploadInstructions)) { - throw new \Exception('LinkedIn Page video upload init missing video URN or upload instructions'); - } - - // Step 2: Upload chunks - $uploadedPartIds = []; - $handle = fopen($tempFile, 'r'); - - try { - foreach ($uploadInstructions as $index => $instruction) { - $uploadUrl = data_get($instruction, 'uploadUrl'); - $firstByte = data_get($instruction, 'firstByte'); - $lastByte = data_get($instruction, 'lastByte'); - - $chunkLength = $lastByte - $firstByte + 1; - fseek($handle, $firstByte); - $chunkData = fread($handle, $chunkLength); - - $chunkResponse = Http::withToken($this->accessToken) - ->withHeaders([ - 'Content-Type' => 'application/octet-stream', - ]) - ->timeout(600) - ->withBody($chunkData, 'application/octet-stream') - ->put($uploadUrl); - - if ($chunkResponse->failed()) { - Log::error('LinkedIn Page video chunk upload failed', [ - 'index' => $index, - 'body' => $this->redactResponseBody($chunkResponse->body()), - ]); - $this->handleApiError($chunkResponse); - } - - $etag = $chunkResponse->header('etag'); - if ($etag) { - $uploadedPartIds[] = $etag; - } - - } - } finally { - fclose($handle); - } - - // Step 3: Finalize upload - $finalizeResponse = $this->getHttpClient() - ->post("{$this->baseUrl}/rest/videos?action=finalizeUpload", [ - 'finalizeUploadRequest' => [ - 'video' => $videoUrn, - 'uploadToken' => $uploadToken, - 'uploadedPartIds' => $uploadedPartIds, - ], - ]); - - if ($finalizeResponse->failed()) { - Log::error('LinkedIn Page video finalize failed', ['body' => $this->redactResponseBody($finalizeResponse->body())]); - $this->handleApiError($finalizeResponse); - } - - // Step 4: Wait for processing - $this->waitForVideoProcessing($videoUrn); - - return $videoUrn; - } - - private function waitForVideoProcessing(string $videoUrn, int $maxAttempts = 30): void - { - $encodedUrn = urlencode($videoUrn); - - for ($i = 0; $i < $maxAttempts; $i++) { - $response = $this->getHttpClient() - ->get("{$this->baseUrl}/rest/videos/{$encodedUrn}"); - - if ($response->failed()) { - Log::warning('LinkedIn Page video status check failed', ['attempt' => $i]); - sleep(5); - - continue; - } - - $data = $response->json(); - $status = data_get($data, 'status', 'UNKNOWN'); - - if ($status === 'AVAILABLE') { - return; - } - - if ($status === 'PROCESSING_FAILED') { - throw new \Exception('LinkedIn Page video processing failed'); - } - - sleep(5); - } - - Log::warning('LinkedIn Page video processing timeout, proceeding anyway'); - } - - private function handleApiError(Response $response): never - { - throw LinkedInPublishException::fromApiResponse($response); } } diff --git a/app/Services/Social/LinkedInPublisher.php b/app/Services/Social/LinkedInPublisher.php index 8053d458..cb02ddce 100644 --- a/app/Services/Social/LinkedInPublisher.php +++ b/app/Services/Social/LinkedInPublisher.php @@ -4,435 +4,20 @@ namespace App\Services\Social; -use App\Enums\PostPlatform\ContentType; use App\Enums\SocialAccount\Platform; -use App\Exceptions\Social\LinkedInPublishException; -use App\Exceptions\TokenExpiredException; -use App\Models\PostPlatform; -use App\Models\SocialAccount; -use App\Services\Media\MediaOptimizer; -use App\Services\Social\Concerns\HasSocialHttpClient; -use Illuminate\Http\Client\PendingRequest; -use Illuminate\Http\Client\Response; -use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Log; -class LinkedInPublisher +/** + * Publishes posts to a member's personal LinkedIn profile. + */ +class LinkedInPublisher extends AbstractLinkedInPublisher { - use HasSocialHttpClient; - - private string $baseUrl; - - private string $apiVersion = '202601'; - - private string $accessToken; - - public function __construct() + protected function platform(): Platform { - $this->baseUrl = config('trypost.platforms.linkedin.api'); + return Platform::LinkedIn; } - private SocialAccount $account; - - private bool $hasRetried = false; - - public function publish(PostPlatform $postPlatform): array + protected function authorUrn(): string { - $this->validateContentLength($postPlatform); - - $content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null; - - $this->account = $postPlatform->socialAccount; - $this->hasRetried = false; - - if ($this->account->is_token_expired || $this->account->is_token_expiring_soon) { - app(ConnectionVerifier::class)->refreshToken($this->account); - } - - $this->accessToken = $this->account->access_token; - - $personUrn = "urn:li:person:{$this->account->platform_user_id}"; - $contentType = $postPlatform->content_type; - - try { - return match ($contentType) { - ContentType::LinkedInCarousel => $this->publishCarousel($personUrn, $content, $postPlatform->post->mediaItems), - ContentType::LinkedInPost => $this->publishPost($personUrn, $content, $postPlatform->post->mediaItems), - default => throw new \Exception("Unsupported LinkedIn content type: {$contentType?->value}"), - }; - } catch (TokenExpiredException $e) { - return $this->retryWithRefresh($postPlatform, $content, $e); - } - } - - private function retryWithRefresh(PostPlatform $postPlatform, ?string $content, TokenExpiredException $originalException): array - { - if ($this->hasRetried) { - throw $originalException; - } - - $this->hasRetried = true; - - try { - app(ConnectionVerifier::class)->refreshToken($this->account); - $this->accessToken = $this->account->access_token; - - $personUrn = "urn:li:person:{$this->account->platform_user_id}"; - $contentType = $postPlatform->content_type; - - return match ($contentType) { - ContentType::LinkedInCarousel => $this->publishCarousel($personUrn, $content, $postPlatform->post->mediaItems), - ContentType::LinkedInPost => $this->publishPost($personUrn, $content, $postPlatform->post->mediaItems), - default => throw new \Exception("Unsupported LinkedIn content type: {$contentType?->value}"), - }; - } catch (\Throwable $e) { - Log::error('LinkedIn refresh failed during retry', [ - 'account_id' => $this->account->id, - 'error' => $e->getMessage(), - ]); - throw $originalException; - } - } - - private function publishPost(string $personUrn, ?string $content, $media): array - { - $payload = [ - 'author' => $personUrn, - 'commentary' => $content ?? '', - 'visibility' => 'PUBLIC', - 'distribution' => [ - 'feedDistribution' => 'MAIN_FEED', - 'targetEntities' => [], - 'thirdPartyDistributionChannels' => [], - ], - 'lifecycleState' => 'PUBLISHED', - ]; - - if ($media->isNotEmpty()) { - $firstMedia = $media->first(); - $mediaUrn = $this->uploadMedia($firstMedia, $personUrn); - - if ($mediaUrn) { - $payload['content'] = [ - 'media' => [ - 'id' => $mediaUrn, - ], - ]; - } - } - - $response = $this->getHttpClient() - ->post("{$this->baseUrl}/rest/posts", $payload); - - if ($response->failed()) { - Log::error('LinkedIn post creation failed', [ - 'status' => $response->status(), - 'body' => $this->redactResponseBody($response->body()), - ]); - $this->handleApiError($response); - } - - $postId = $response->header('x-restli-id'); - - return [ - 'id' => $postId ?? 'unknown', - 'url' => $postId ? "https://www.linkedin.com/feed/update/{$postId}" : null, - ]; - } - - private function publishCarousel(string $personUrn, ?string $content, $mediaCollection): array - { - // Upload images and build carousel items - $carouselItems = []; - - foreach ($mediaCollection as $media) { - if (! $media->isImage()) { - continue; - } - - $imageUrn = $this->uploadImage($media, $personUrn); - - if ($imageUrn) { - $carouselItems[] = [ - 'altText' => $media->original_filename ?? 'Carousel image', - 'media' => $imageUrn, - ]; - } - } - - if (empty($carouselItems)) { - throw new \Exception('No valid images for LinkedIn carousel'); - } - - $payload = [ - 'author' => $personUrn, - 'commentary' => $content ?? '', - 'visibility' => 'PUBLIC', - 'distribution' => [ - 'feedDistribution' => 'MAIN_FEED', - 'targetEntities' => [], - 'thirdPartyDistributionChannels' => [], - ], - 'lifecycleState' => 'PUBLISHED', - 'content' => [ - 'multiImage' => [ - 'images' => $carouselItems, - ], - ], - ]; - - $response = $this->getHttpClient() - ->post("{$this->baseUrl}/rest/posts", $payload); - - if ($response->failed()) { - Log::error('LinkedIn carousel post creation failed', [ - 'status' => $response->status(), - 'body' => $this->redactResponseBody($response->body()), - ]); - $this->handleApiError($response); - } - - $postId = $response->header('x-restli-id'); - - return [ - 'id' => $postId ?? 'unknown', - 'url' => $postId ? "https://www.linkedin.com/feed/update/{$postId}" : null, - ]; - } - - private function getHttpClient(): PendingRequest - { - return $this->socialHttp()->withToken($this->accessToken) - ->withHeaders([ - 'X-Restli-Protocol-Version' => '2.0.0', - 'LinkedIn-Version' => $this->apiVersion, - 'Content-Type' => 'application/json', - ]); - } - - private function uploadMedia($mediaItem, string $ownerUrn): ?string - { - $mimeType = $mediaItem->mime_type; - $isVideo = str_starts_with($mimeType, 'video/'); - $isImage = str_starts_with($mimeType, 'image/'); - - if ($isVideo) { - return $this->uploadVideo($mediaItem, $ownerUrn); - } - - if ($isImage) { - return $this->uploadImage($mediaItem, $ownerUrn); - } - - return null; - } - - private function uploadImage($mediaItem, string $ownerUrn): ?string - { - // Step 1: Initialize upload - $initResponse = $this->getHttpClient() - ->post("{$this->baseUrl}/rest/images?action=initializeUpload", [ - 'initializeUploadRequest' => [ - 'owner' => $ownerUrn, - ], - ]); - - if ($initResponse->failed()) { - Log::error('LinkedIn image init failed', ['body' => $this->redactResponseBody($initResponse->body())]); - $this->handleApiError($initResponse); - } - - $initData = $initResponse->json(); - $uploadUrl = $initData['value']['uploadUrl'] ?? null; - $imageUrn = $initData['value']['image'] ?? null; - - if (! $uploadUrl || ! $imageUrn) { - throw new \Exception('LinkedIn image upload init missing uploadUrl or image URN'); - } - - // Step 2: Download and optimize image - $tempFile = tempnam(sys_get_temp_dir(), 'li_image_'); - - try { - $downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url); - - if ($downloadResponse->failed()) { - throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status()); - } - - $detectedMime = mime_content_type($tempFile) ?: ''; - if (str_starts_with($detectedMime, 'image/') && ! str_starts_with($detectedMime, 'image/gif')) { - $optimizer = app(MediaOptimizer::class); - $optimizedPath = $optimizer->optimizeImage($tempFile, Platform::LinkedIn); - @unlink($tempFile); - $tempFile = $optimizedPath; - } - - $stream = fopen($tempFile, 'r'); - - $uploadResponse = Http::withToken($this->accessToken) - ->withHeaders([ - 'Content-Type' => 'application/octet-stream', - ]) - ->withBody($stream, 'application/octet-stream') - ->put($uploadUrl); - - if (is_resource($stream)) { - fclose($stream); - } - - if ($uploadResponse->failed()) { - Log::error('LinkedIn image upload failed', ['body' => $this->redactResponseBody($uploadResponse->body())]); - $this->handleApiError($uploadResponse); - } - - return $imageUrn; - } finally { - @unlink($tempFile); - } - } - - private function uploadVideo($mediaItem, string $ownerUrn): ?string - { - $tempFile = tempnam(sys_get_temp_dir(), 'li_video_'); - - try { - return $this->doUploadVideo($tempFile, $mediaItem, $ownerUrn); - } finally { - @unlink($tempFile); - } - } - - private function doUploadVideo(string $tempFile, $mediaItem, string $ownerUrn): ?string - { - $downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url); - - if ($downloadResponse->failed()) { - throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status()); - } - - $fileSize = (int) filesize($tempFile); - - // Step 1: Initialize upload - $initResponse = $this->getHttpClient() - ->post("{$this->baseUrl}/rest/videos?action=initializeUpload", [ - 'initializeUploadRequest' => [ - 'owner' => $ownerUrn, - 'fileSizeBytes' => $fileSize, - 'uploadCaptions' => false, - 'uploadThumbnail' => false, - ], - ]); - - if ($initResponse->failed()) { - Log::error('LinkedIn video init failed', ['body' => $this->redactResponseBody($initResponse->body())]); - $this->handleApiError($initResponse); - } - - $initData = $initResponse->json(); - $videoUrn = $initData['value']['video'] ?? null; - $uploadInstructions = $initData['value']['uploadInstructions'] ?? []; - $uploadToken = $initData['value']['uploadToken'] ?? ''; - - if (! $videoUrn || empty($uploadInstructions)) { - throw new \Exception('LinkedIn video upload init missing video URN or upload instructions'); - } - - // Step 2: Upload chunks - $uploadedPartIds = []; - $handle = fopen($tempFile, 'r'); - - try { - foreach ($uploadInstructions as $index => $instruction) { - $uploadUrl = data_get($instruction, 'uploadUrl'); - $firstByte = data_get($instruction, 'firstByte'); - $lastByte = data_get($instruction, 'lastByte'); - - $chunkLength = $lastByte - $firstByte + 1; - fseek($handle, $firstByte); - $chunkData = fread($handle, $chunkLength); - - $chunkResponse = Http::withToken($this->accessToken) - ->withHeaders([ - 'Content-Type' => 'application/octet-stream', - ]) - ->timeout(600) - ->withBody($chunkData, 'application/octet-stream') - ->put($uploadUrl); - - if ($chunkResponse->failed()) { - Log::error('LinkedIn video chunk upload failed', [ - 'index' => $index, - 'body' => $this->redactResponseBody($chunkResponse->body()), - ]); - $this->handleApiError($chunkResponse); - } - - $etag = $chunkResponse->header('etag'); - if ($etag) { - $uploadedPartIds[] = $etag; - } - - } - } finally { - fclose($handle); - } - - // Step 3: Finalize upload - $finalizeResponse = $this->getHttpClient() - ->post("{$this->baseUrl}/rest/videos?action=finalizeUpload", [ - 'finalizeUploadRequest' => [ - 'video' => $videoUrn, - 'uploadToken' => $uploadToken, - 'uploadedPartIds' => $uploadedPartIds, - ], - ]); - - if ($finalizeResponse->failed()) { - Log::error('LinkedIn video finalize failed', ['body' => $this->redactResponseBody($finalizeResponse->body())]); - $this->handleApiError($finalizeResponse); - } - - // Step 4: Wait for processing - $this->waitForVideoProcessing($videoUrn); - - return $videoUrn; - } - - private function waitForVideoProcessing(string $videoUrn, int $maxAttempts = 30): void - { - $encodedUrn = urlencode($videoUrn); - - for ($i = 0; $i < $maxAttempts; $i++) { - $response = $this->getHttpClient() - ->get("{$this->baseUrl}/rest/videos/{$encodedUrn}"); - - if ($response->failed()) { - Log::warning('LinkedIn video status check failed', ['attempt' => $i]); - sleep(5); - - continue; - } - - $data = $response->json(); - $status = data_get($data, 'status', 'UNKNOWN'); - - if ($status === 'AVAILABLE') { - return; - } - - if ($status === 'PROCESSING_FAILED') { - throw new \Exception('LinkedIn video processing failed'); - } - - sleep(5); - } - - Log::warning('LinkedIn video processing timeout, proceeding anyway'); - } - - private function handleApiError(Response $response): never - { - throw LinkedInPublishException::fromApiResponse($response); + return "urn:li:person:{$this->account->platform_user_id}"; } } diff --git a/app/Services/Social/LinkedInTokenSynchronizer.php b/app/Services/Social/LinkedInTokenSynchronizer.php deleted file mode 100644 index 11895412..00000000 --- a/app/Services/Social/LinkedInTokenSynchronizer.php +++ /dev/null @@ -1,86 +0,0 @@ -workspace; - $linkedUserId = $this->getLinkedInUserId($sourceAccount); - - if (! $linkedUserId) { - return; - } - - $targets = $this->findLinkedAccounts($workspace, $sourceAccount, $linkedUserId); - - foreach ($targets as $target) { - $target->update([ - 'access_token' => $sourceAccount->access_token, - 'refresh_token' => $sourceAccount->refresh_token, - 'token_expires_at' => $sourceAccount->token_expires_at, - ]); - - if ($target->isDisconnected()) { - $target->markAsConnected(); - } - } - } - - /** - * Get the LinkedIn user ID from an account. - * For personal accounts, it's the platform_user_id. - * For page accounts, it's stored in meta.admin_user_id. - */ - private function getLinkedInUserId(SocialAccount $account): ?string - { - if ($account->platform === Platform::LinkedIn) { - return $account->platform_user_id; - } - - if ($account->platform === Platform::LinkedInPage) { - return $account->meta['admin_user_id'] ?? null; - } - - return null; - } - - /** - * Find every linked LinkedIn account (personal <-> page) in the same workspace. - * - * @return Collection - */ - private function findLinkedAccounts(Workspace $workspace, SocialAccount $sourceAccount, string $linkedUserId): Collection - { - if ($sourceAccount->platform === Platform::LinkedIn) { - // Source is personal: every page admin'd by this LinkedIn user. - return $workspace->socialAccounts() - ->where('platform', Platform::LinkedInPage->value) - ->whereJsonContains('meta->admin_user_id', $linkedUserId) - ->get(); - } - - if ($sourceAccount->platform === Platform::LinkedInPage) { - // Source is page: the personal LinkedIn account belonging to its admin. - return $workspace->socialAccounts() - ->where('platform', Platform::LinkedIn->value) - ->where('platform_user_id', $linkedUserId) - ->get(); - } - - return new Collection; - } -} diff --git a/app/Services/Social/MastodonPublisher.php b/app/Services/Social/MastodonPublisher.php index 218d099d..05a6eba3 100644 --- a/app/Services/Social/MastodonPublisher.php +++ b/app/Services/Social/MastodonPublisher.php @@ -4,6 +4,7 @@ namespace App\Services\Social; +use App\Enums\Media\Type as MediaType; use App\Enums\SocialAccount\Platform; use App\Exceptions\Social\MastodonPublishException; use App\Models\PostPlatform; @@ -86,7 +87,7 @@ private function uploadMedia(SocialAccount $account, string $instance, string $u // Optimize images (skip GIFs) $detectedMime = mime_content_type($tempFile) ?: ''; - if (str_starts_with($detectedMime, 'image/') && ! str_starts_with($detectedMime, 'image/gif')) { + if (MediaType::classify($detectedMime) === MediaType::Image && ! MediaType::isGif($detectedMime)) { $optimizer = app(MediaOptimizer::class); $optimizedPath = $optimizer->optimizeImage($tempFile, Platform::Mastodon); @unlink($tempFile); diff --git a/app/Services/Social/PinterestPublisher.php b/app/Services/Social/PinterestPublisher.php index 994199fa..c0669c53 100644 --- a/app/Services/Social/PinterestPublisher.php +++ b/app/Services/Social/PinterestPublisher.php @@ -4,6 +4,7 @@ namespace App\Services\Social; +use App\Enums\Media\Type as MediaType; use App\Enums\PostPlatform\ContentType; use App\Enums\SocialAccount\Platform; use App\Exceptions\Social\ErrorCategory; @@ -85,7 +86,7 @@ private function publishImagePin(PostPlatform $postPlatform, ?string $content): } $detectedMime = mime_content_type($tempFile) ?: ''; - if (str_starts_with($detectedMime, 'image/') && ! str_starts_with($detectedMime, 'image/gif')) { + if (MediaType::classify($detectedMime) === MediaType::Image && ! MediaType::isGif($detectedMime)) { $optimizer = app(MediaOptimizer::class); $optimizedPath = $optimizer->optimizeImage($tempFile, Platform::Pinterest); @unlink($tempFile); @@ -272,6 +273,8 @@ private function publishVideoPin(PostPlatform $postPlatform, ?string $content): if (! empty(data_get($postPlatform->meta, 'cover_image_url'))) { $payload['media_source']['cover_image_url'] = data_get($postPlatform->meta, 'cover_image_url'); + } else { + $payload['media_source']['cover_image_key_frame_time'] = 0; } $response = $this->socialHttp()->withToken($account->access_token) diff --git a/app/Services/Social/XPublisher.php b/app/Services/Social/XPublisher.php index 625a840b..ee925fde 100644 --- a/app/Services/Social/XPublisher.php +++ b/app/Services/Social/XPublisher.php @@ -4,6 +4,7 @@ namespace App\Services\Social; +use App\Enums\Media\Type as MediaType; use App\Enums\SocialAccount\Platform; use App\Exceptions\Social\XPublishException; use App\Models\PostPlatform; @@ -117,7 +118,7 @@ private function uploadMedia($mediaItem): ?array } // Optimize images (skip GIFs — they need special handling) - if (str_starts_with($mimeType, 'image/') && ! str_starts_with($mimeType, 'image/gif')) { + if ($mediaItem->isImage() && ! MediaType::isGif($mimeType)) { $optimizer = app(MediaOptimizer::class); $optimizedPath = $optimizer->optimizeImage($tempFile, Platform::X); @unlink($tempFile); @@ -128,8 +129,8 @@ private function uploadMedia($mediaItem): ?array $fileSize = filesize($tempFile); $mediaCategory = $this->getMediaCategory($mimeType, $fileSize); - $isVideo = str_starts_with($mimeType, 'video/'); - $isGif = $mimeType === 'image/gif'; + $isVideo = MediaType::classify($mimeType) === MediaType::Video; + $isGif = MediaType::isGif($mimeType); $useChunkedUpload = $isVideo || $isGif || $fileSize > 5 * 1024 * 1024; @@ -256,7 +257,7 @@ private function chunkedUpload(string $tempFile, int $totalBytes, string $mimeTy $finalizeData = $finalizeResponse->json(); // Wait for processing (videos need transcoding) - if (isset($finalizeData['processing_info']) || str_starts_with($mimeType, 'video/')) { + if (isset($finalizeData['processing_info']) || MediaType::classify($mimeType) === MediaType::Video) { $this->waitForProcessing($mediaId); } @@ -270,15 +271,15 @@ private function chunkedUpload(string $tempFile, int $totalBytes, string $mimeTy private function getMediaCategory(string $mimeType, int $fileSize): ?string { - if (str_starts_with($mimeType, 'video/')) { + if (MediaType::classify($mimeType) === MediaType::Video) { return $fileSize > 15 * 1024 * 1024 ? 'amplify_video' : 'tweet_video'; } - if ($mimeType === 'image/gif') { + if (MediaType::isGif($mimeType)) { return 'tweet_gif'; } - if (str_starts_with($mimeType, 'image/')) { + if (MediaType::classify($mimeType) === MediaType::Image) { return 'tweet_image'; } diff --git a/app/Support/PostPlatformMetaRules.php b/app/Support/PostPlatformMetaRules.php index d7a12682..00f6d7b2 100644 --- a/app/Support/PostPlatformMetaRules.php +++ b/app/Support/PostPlatformMetaRules.php @@ -45,6 +45,9 @@ public static function rules(): array // Instagram / Facebook 'platforms.*.meta.aspect_ratio' => ['sometimes', 'nullable', 'string', Rule::enum(AspectRatio::class)], + // LinkedIn — title shown on a document (PDF carousel) post + 'platforms.*.meta.document_title' => ['sometimes', 'nullable', 'string', 'max:300'], + // TikTok 'platforms.*.meta.privacy_level' => ['sometimes', 'nullable', 'string', Rule::in(self::TIKTOK_PRIVACY_LEVELS)], 'platforms.*.meta.auto_add_music' => ['sometimes', 'boolean'], diff --git a/config/services.php b/config/services.php index e72632d6..4b5d5690 100644 --- a/config/services.php +++ b/config/services.php @@ -47,7 +47,6 @@ 'client_id' => env('LINKEDIN_CLIENT_ID'), 'client_secret' => env('LINKEDIN_CLIENT_SECRET'), 'redirect' => env('LINKEDIN_CLIENT_REDIRECT'), - 'redirect_page' => env('LINKEDIN_PAGE_CLIENT_REDIRECT'), ], 'x' => [ diff --git a/config/trypost.php b/config/trypost.php index 761be98f..1b204b7e 100644 --- a/config/trypost.php +++ b/config/trypost.php @@ -46,6 +46,8 @@ 'max_size_mb' => [ 'image' => (int) env('MEDIA_IMAGE_MAX_SIZE_MB', 10), 'video' => (int) env('MEDIA_VIDEO_MAX_SIZE_MB', 1024), + // LinkedIn caps document (PDF carousel) uploads at 100MB. + 'document' => (int) env('MEDIA_DOCUMENT_MAX_SIZE_MB', 100), ], ], diff --git a/database/migrations/2026_06_24_220651_collapse_linkedin_content_types.php b/database/migrations/2026_06_24_220651_collapse_linkedin_content_types.php new file mode 100644 index 00000000..4fda2962 --- /dev/null +++ b/database/migrations/2026_06_24_220651_collapse_linkedin_content_types.php @@ -0,0 +1,31 @@ +whereIn('content_type', ['linkedin_carousel', 'linkedin_document']) + ->update(['content_type' => 'linkedin_post']); + + DB::table('post_platforms') + ->whereIn('content_type', ['linkedin_page_carousel', 'linkedin_page_document']) + ->update(['content_type' => 'linkedin_page_post']); + } + + public function down(): void + { + // Irreversible: the per-format variants were merged into the single post + // type and the original distinction is no longer recoverable. + } +}; diff --git a/lang/en/accounts.php b/lang/en/accounts.php index 8359c84c..f6686db6 100644 --- a/lang/en/accounts.php +++ b/lang/en/accounts.php @@ -15,7 +15,7 @@ 'disconnect' => 'Disconnect', 'descriptions' => [ - 'linkedin' => 'Connect your LinkedIn personal profile', + 'linkedin' => 'Connect your LinkedIn profile or company page', 'linkedin-page' => 'Connect a LinkedIn company page', 'x' => 'Connect your X (Twitter) account', 'tiktok' => 'Connect your TikTok account', @@ -83,6 +83,8 @@ 'no_pages' => 'No pages found', 'no_pages_description' => 'You are not an admin of any Facebook page.', 'page_label' => 'Facebook Page', + 'view' => 'View', + 'choose' => 'Choose', ], 'instagram_facebook' => [ @@ -90,6 +92,8 @@ 'description' => 'Choose which Instagram account you want to connect', 'no_pages' => 'No Instagram accounts found', 'no_pages_description' => 'No Facebook Pages with linked Instagram Business accounts were found.', + 'view' => 'View', + 'choose' => 'Choose', ], 'linkedin' => [ @@ -98,6 +102,12 @@ 'no_pages' => 'No pages found', 'no_pages_description' => 'You are not an administrator of any LinkedIn page.', 'page_label' => 'LinkedIn Page', + 'select_title' => 'Where do you want to post?', + 'select_subtitle' => 'Post as yourself or choose a company page you manage.', + 'person_tag' => 'Person', + 'organization_tag' => 'Organization', + 'view' => 'View', + 'choose' => 'Choose', ], 'flash' => [ @@ -115,7 +125,8 @@ 'title_success' => 'Connected', 'title_error' => 'Error', 'closing' => 'This window will close automatically...', - 'close_now' => 'You can close this window now.', + 'manual_close' => 'You can close this window.', + 'popup_blocked' => 'Could not open the connection window. Please allow popups and try again.', 'connected' => 'Account connected!', 'reconnected' => 'Account reconnected!', 'error_connecting' => 'Error connecting account. Please try again.', diff --git a/lang/en/assets.php b/lang/en/assets.php index a4b61bbe..57483f4a 100644 --- a/lang/en/assets.php +++ b/lang/en/assets.php @@ -11,8 +11,9 @@ 'upload' => [ 'drag_drop' => 'Drag & drop your files here, or click to select', - 'formats' => 'JPEG, PNG, GIF, WebP, MP4', + 'formats' => 'JPEG, PNG, GIF, WebP, MP4, PDF', 'uploading' => 'Uploading...', + 'failed' => 'Could not upload :file. Please try again.', ], 'empty' => [ diff --git a/lang/en/posts.php b/lang/en/posts.php index d3f3f7dd..e4f52fed 100644 --- a/lang/en/posts.php +++ b/lang/en/posts.php @@ -139,11 +139,8 @@ 'settings' => 'LinkedIn Settings', 'settings_page' => 'LinkedIn Page Settings', 'posting_to' => 'Posting to', - 'variant_label' => 'Post type', - 'variant' => [ - 'post' => 'Post', - 'carousel' => 'Carousel', - ], + 'document_title' => 'Document title', + 'document_title_placeholder' => 'Shown on your PDF document post', ], 'pinterest' => [ 'settings' => 'Pinterest Settings', @@ -188,9 +185,13 @@ 'min_files_required' => 'This post type requires at least :min media files (you have :current).', 'no_video_allowed' => 'This post type does not accept videos.', 'no_image_allowed' => 'This post type accepts only videos.', + 'no_document_allowed' => 'This post type does not accept PDF documents.', + 'no_mixed_media' => "Images and a video can't be combined in the same post.", + 'document_not_alone' => 'A PDF must be posted on its own, without other images or videos.', 'gif_not_allowed' => 'This platform does not accept GIF. Remove the GIF or choose a different network.', 'image_too_large' => 'Image exceeds the :max limit for this post type (yours is :current).', 'video_too_large' => 'Video exceeds the :max limit for this post type (yours is :current).', + 'document_too_large' => 'PDF exceeds the :max limit for this post type (yours is :current).', 'video_too_long' => 'Video is :current long, but this post type allows up to :max.', 'aspect_ratio_too_narrow' => 'Aspect ratio :current is too tall for this post type (min :min).', 'aspect_ratio_too_wide' => 'Aspect ratio :current is too wide for this post type (max :max).', @@ -344,11 +345,15 @@ 'no_images' => 'Only videos are allowed for this format.', 'no_mixed_media' => "Images and videos can't be combined in the same post.", 'no_gifs' => 'GIFs are not supported here.', + 'no_documents' => 'PDF documents are not supported by this format.', + 'document_not_alone' => 'A PDF must be posted on its own, without other images or videos.', 'video_too_large' => 'Video exceeds the size limit for this platform.', 'video_too_long' => 'Video must be under :seconds seconds for this format.', 'image_too_large' => 'Image exceeds the size limit for this platform.', + 'document_too_large' => 'PDF exceeds the size limit for this platform.', 'aspect_ratio_invalid' => 'Aspect ratio is not supported by this format.', 'no_content_type' => 'Pick a content type for this platform.', + 'requires_text' => 'Add text — this format needs a title.', ], 'publishing' => 'Publishing...', 'publishing_overlay_title' => 'Your post is being published', @@ -458,19 +463,11 @@ ], 'linkedin_post' => [ 'label' => 'Post', - 'description' => 'Standard post with text and media', - ], - 'linkedin_carousel' => [ - 'label' => 'Carousel', - 'description' => 'Swipeable images', + 'description' => 'Standard post — single image, multi-image, video, or PDF', ], 'linkedin_page_post' => [ 'label' => 'Post', - 'description' => 'Standard post with text and media', - ], - 'linkedin_page_carousel' => [ - 'label' => 'Carousel', - 'description' => 'Swipeable images', + 'description' => 'Standard post — single image, multi-image, video, or PDF', ], 'facebook_post' => [ 'label' => 'Post', diff --git a/lang/es/accounts.php b/lang/es/accounts.php index 3df54c2b..987805c7 100644 --- a/lang/es/accounts.php +++ b/lang/es/accounts.php @@ -15,7 +15,7 @@ 'disconnect' => 'Desconectar', 'descriptions' => [ - 'linkedin' => 'Conecta tu perfil personal de LinkedIn', + 'linkedin' => 'Conecta tu perfil de LinkedIn o página de empresa', 'linkedin-page' => 'Conecta una página de empresa de LinkedIn', 'x' => 'Conecta tu cuenta de X (Twitter)', 'tiktok' => 'Conecta tu cuenta de TikTok', @@ -83,6 +83,8 @@ 'no_pages' => 'No se encontraron páginas', 'no_pages_description' => 'No eres administrador de ninguna página de Facebook.', 'page_label' => 'Página de Facebook', + 'view' => 'Ver', + 'choose' => 'Elegir', ], 'instagram_facebook' => [ @@ -90,6 +92,8 @@ 'description' => 'Elige qué cuenta de Instagram deseas conectar', 'no_pages' => 'No se encontraron cuentas de Instagram', 'no_pages_description' => 'No se encontraron páginas de Facebook con cuentas Instagram Business vinculadas.', + 'view' => 'Ver', + 'choose' => 'Elegir', ], 'linkedin' => [ @@ -98,6 +102,12 @@ 'no_pages' => 'No se encontraron páginas', 'no_pages_description' => 'No eres administrador de ninguna página de LinkedIn.', 'page_label' => 'Página de LinkedIn', + 'select_title' => '¿Dónde quieres publicar?', + 'select_subtitle' => 'Publica como tú mismo o elige una página de empresa que administres.', + 'person_tag' => 'Persona', + 'organization_tag' => 'Empresa', + 'view' => 'Ver', + 'choose' => 'Elegir', ], 'flash' => [ @@ -115,7 +125,8 @@ 'title_success' => 'Conectado', 'title_error' => 'Error', 'closing' => 'Esta ventana se cerrará automáticamente...', - 'close_now' => 'Puedes cerrar esta ventana ahora.', + 'manual_close' => 'Puedes cerrar esta ventana.', + 'popup_blocked' => 'No se pudo abrir la ventana de conexión. Permite las ventanas emergentes e inténtalo de nuevo.', 'connected' => '¡Cuenta conectada!', 'reconnected' => '¡Cuenta reconectada!', 'error_connecting' => 'Error al conectar la cuenta. Inténtalo de nuevo.', diff --git a/lang/es/assets.php b/lang/es/assets.php index d8c33dba..0945d737 100644 --- a/lang/es/assets.php +++ b/lang/es/assets.php @@ -13,8 +13,9 @@ 'upload' => [ 'drag_drop' => 'Arrastra y suelta tus archivos aquí o haz clic para seleccionar', - 'formats' => 'JPEG, PNG, GIF, WebP, MP4', + 'formats' => 'JPEG, PNG, GIF, WebP, MP4, PDF', 'uploading' => 'Subiendo...', + 'failed' => 'No se pudo subir :file. Inténtalo de nuevo.', ], 'empty' => [ diff --git a/lang/es/posts.php b/lang/es/posts.php index c52e8895..61509fd8 100644 --- a/lang/es/posts.php +++ b/lang/es/posts.php @@ -139,11 +139,8 @@ 'settings' => 'Configuración de LinkedIn', 'settings_page' => 'Configuración de la Página de LinkedIn', 'posting_to' => 'Publicando en', - 'variant_label' => 'Tipo de publicación', - 'variant' => [ - 'post' => 'Publicación', - 'carousel' => 'Carrusel', - ], + 'document_title' => 'Título del documento', + 'document_title_placeholder' => 'Se muestra en tu publicación de documento PDF', ], 'pinterest' => [ 'settings' => 'Configuración de Pinterest', @@ -188,9 +185,13 @@ 'min_files_required' => 'Este tipo requiere al menos :min archivos (tienes :current).', 'no_video_allowed' => 'Este tipo no acepta videos.', 'no_image_allowed' => 'Este tipo acepta solo videos.', + 'no_document_allowed' => 'Este tipo no acepta documentos PDF.', + 'no_mixed_media' => 'No se pueden combinar imágenes y un video en la misma publicación.', + 'document_not_alone' => 'Un PDF debe publicarse solo, sin otras imágenes ni videos.', 'gif_not_allowed' => 'Esta red no acepta GIF. Elimínalo o selecciona otra red.', 'image_too_large' => 'La imagen supera el límite de :max (la tuya es :current).', 'video_too_large' => 'El video supera el límite de :max (el tuyo es :current).', + 'document_too_large' => 'El PDF supera el límite de :max (el tuyo es :current).', 'video_too_long' => 'El video dura :current, pero este tipo permite hasta :max.', 'aspect_ratio_too_narrow' => 'La proporción :current es demasiado alta (mínimo :min).', 'aspect_ratio_too_wide' => 'La proporción :current es demasiado ancha (máximo :max).', @@ -344,11 +345,15 @@ 'no_images' => 'Solo se permiten videos en este formato.', 'no_mixed_media' => 'No se pueden combinar imágenes y videos en la misma publicación.', 'no_gifs' => 'Los GIFs no son compatibles aquí.', + 'no_documents' => 'Los documentos PDF no son compatibles con este formato.', + 'document_not_alone' => 'Un PDF debe publicarse solo, sin otras imágenes ni videos.', 'video_too_large' => 'El video supera el límite de tamaño de esta plataforma.', 'video_too_long' => 'El video debe durar menos de :seconds segundos en este formato.', 'image_too_large' => 'La imagen supera el límite de tamaño de esta plataforma.', + 'document_too_large' => 'El PDF supera el límite de tamaño de esta plataforma.', 'aspect_ratio_invalid' => 'La proporción de aspecto no es compatible con este formato.', 'no_content_type' => 'Elige un tipo de contenido para esta plataforma.', + 'requires_text' => 'Agrega texto — este formato necesita un título.', ], 'publishing' => 'Publicando...', 'publishing_overlay_title' => 'Tu publicación se está enviando', @@ -458,19 +463,11 @@ ], 'linkedin_post' => [ 'label' => 'Post', - 'description' => 'Post estándar con texto y multimedia', - ], - 'linkedin_carousel' => [ - 'label' => 'Carrusel', - 'description' => 'Imágenes deslizables', + 'description' => 'Post estándar — imagen, varias imágenes, video o PDF', ], 'linkedin_page_post' => [ 'label' => 'Post', - 'description' => 'Post estándar con texto y multimedia', - ], - 'linkedin_page_carousel' => [ - 'label' => 'Carrusel', - 'description' => 'Imágenes deslizables', + 'description' => 'Post estándar — imagen, varias imágenes, video o PDF', ], 'facebook_post' => [ 'label' => 'Post', diff --git a/lang/pt-BR/accounts.php b/lang/pt-BR/accounts.php index 71baa511..662cf78b 100644 --- a/lang/pt-BR/accounts.php +++ b/lang/pt-BR/accounts.php @@ -15,7 +15,7 @@ 'disconnect' => 'Desconectar', 'descriptions' => [ - 'linkedin' => 'Conecte seu perfil pessoal do LinkedIn', + 'linkedin' => 'Conecte seu perfil do LinkedIn ou página de empresa', 'linkedin-page' => 'Conecte uma página de empresa do LinkedIn', 'x' => 'Conecte sua conta do X (Twitter)', 'tiktok' => 'Conecte sua conta do TikTok', @@ -83,6 +83,8 @@ 'no_pages' => 'Nenhuma página encontrada', 'no_pages_description' => 'Você não é administrador de nenhuma página do Facebook.', 'page_label' => 'Página do Facebook', + 'view' => 'Ver', + 'choose' => 'Escolher', ], 'instagram_facebook' => [ @@ -90,6 +92,8 @@ 'description' => 'Escolha qual conta do Instagram você deseja conectar', 'no_pages' => 'Nenhuma conta do Instagram encontrada', 'no_pages_description' => 'Nenhuma Página do Facebook com conta Instagram Business vinculada foi encontrada.', + 'view' => 'Ver', + 'choose' => 'Escolher', ], 'linkedin' => [ @@ -98,6 +102,12 @@ 'no_pages' => 'Nenhuma página encontrada', 'no_pages_description' => 'Você não é administrador de nenhuma página do LinkedIn.', 'page_label' => 'Página do LinkedIn', + 'select_title' => 'Onde você quer publicar?', + 'select_subtitle' => 'Publique como você mesmo ou escolha uma página de empresa que você administra.', + 'person_tag' => 'Pessoa', + 'organization_tag' => 'Empresa', + 'view' => 'Ver', + 'choose' => 'Escolher', ], 'flash' => [ @@ -115,7 +125,8 @@ 'title_success' => 'Conectado', 'title_error' => 'Erro', 'closing' => 'Esta janela será fechada automaticamente...', - 'close_now' => 'Você pode fechar esta janela agora.', + 'manual_close' => 'Você pode fechar esta janela.', + 'popup_blocked' => 'Não foi possível abrir a janela de conexão. Permita pop-ups e tente novamente.', 'connected' => 'Conta conectada!', 'reconnected' => 'Conta reconectada!', 'error_connecting' => 'Erro ao conectar conta. Por favor, tente novamente.', diff --git a/lang/pt-BR/assets.php b/lang/pt-BR/assets.php index ac24bd34..5da24132 100644 --- a/lang/pt-BR/assets.php +++ b/lang/pt-BR/assets.php @@ -13,8 +13,9 @@ 'upload' => [ 'drag_drop' => 'Arraste e solte seus arquivos aqui ou clique para selecionar', - 'formats' => 'JPEG, PNG, GIF, WebP, MP4', + 'formats' => 'JPEG, PNG, GIF, WebP, MP4, PDF', 'uploading' => 'Enviando...', + 'failed' => 'Não foi possível enviar :file. Tente novamente.', ], 'empty' => [ diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.php index 3b580dcb..72a8a361 100644 --- a/lang/pt-BR/posts.php +++ b/lang/pt-BR/posts.php @@ -139,11 +139,8 @@ 'settings' => 'Configurações do LinkedIn', 'settings_page' => 'Configurações da Página do LinkedIn', 'posting_to' => 'Publicando em', - 'variant_label' => 'Tipo de publicação', - 'variant' => [ - 'post' => 'Post', - 'carousel' => 'Carrossel', - ], + 'document_title' => 'Título do documento', + 'document_title_placeholder' => 'Aparece no seu post de documento PDF', ], 'pinterest' => [ 'settings' => 'Configurações do Pinterest', @@ -188,9 +185,13 @@ 'min_files_required' => 'Este tipo exige pelo menos :min arquivos (você tem :current).', 'no_video_allowed' => 'Este tipo não aceita vídeos.', 'no_image_allowed' => 'Este tipo aceita apenas vídeos.', + 'no_document_allowed' => 'Este tipo não aceita documentos PDF.', + 'no_mixed_media' => 'Não dá pra combinar imagens e um vídeo no mesmo post.', + 'document_not_alone' => 'Um PDF precisa ser publicado sozinho, sem outras imagens ou vídeos.', 'gif_not_allowed' => 'Esta rede não aceita GIF. Remova o GIF ou escolha outra rede.', 'image_too_large' => 'A imagem passa do limite de :max (a sua tem :current).', 'video_too_large' => 'O vídeo passa do limite de :max (o seu tem :current).', + 'document_too_large' => 'O PDF passa do limite de :max (o seu tem :current).', 'video_too_long' => 'O vídeo dura :current, mas este tipo permite no máximo :max.', 'aspect_ratio_too_narrow' => 'A proporção :current está muito alta (mínimo :min).', 'aspect_ratio_too_wide' => 'A proporção :current está muito larga (máximo :max).', @@ -344,11 +345,15 @@ 'no_images' => 'Apenas vídeos são permitidos neste formato.', 'no_mixed_media' => 'Não é possível combinar imagem e vídeo na mesma publicação.', 'no_gifs' => 'GIFs não são suportados aqui.', + 'no_documents' => 'Documentos PDF não são suportados por este formato.', + 'document_not_alone' => 'Um PDF precisa ser publicado sozinho, sem outras imagens ou vídeos.', 'video_too_large' => 'Vídeo excede o limite de tamanho desta plataforma.', 'video_too_long' => 'Vídeo deve ter menos de :seconds segundos neste formato.', 'image_too_large' => 'Imagem excede o limite de tamanho desta plataforma.', + 'document_too_large' => 'O PDF excede o limite de tamanho desta plataforma.', 'aspect_ratio_invalid' => 'A proporção da imagem não é suportada por este formato.', 'no_content_type' => 'Escolha um tipo de conteúdo para esta plataforma.', + 'requires_text' => 'Adicione texto — este formato precisa de um título.', ], 'publishing' => 'Publicando...', 'publishing_overlay_title' => 'Seu post está sendo publicado', @@ -458,19 +463,11 @@ ], 'linkedin_post' => [ 'label' => 'Post', - 'description' => 'Post padrão com texto e mídia', - ], - 'linkedin_carousel' => [ - 'label' => 'Carrossel', - 'description' => 'Imagens deslizáveis', + 'description' => 'Post padrão — imagem, várias imagens, vídeo ou PDF', ], 'linkedin_page_post' => [ 'label' => 'Post', - 'description' => 'Post padrão com texto e mídia', - ], - 'linkedin_page_carousel' => [ - 'label' => 'Carrossel', - 'description' => 'Imagens deslizáveis', + 'description' => 'Post padrão — imagem, várias imagens, vídeo ou PDF', ], 'facebook_post' => [ 'label' => 'Post', diff --git a/resources/js/components/ChannelConfigurator.vue b/resources/js/components/ChannelConfigurator.vue index 5295d3db..1feb31e2 100644 --- a/resources/js/components/ChannelConfigurator.vue +++ b/resources/js/components/ChannelConfigurator.vue @@ -163,11 +163,11 @@ const selectedChannels = computed(() => props.channels.filter((channel) => isSel v-else-if="channel.platform === Platform.LinkedIn || channel.platform === Platform.LinkedInPage" :social-account="channel.socialAccount" :platform="channel.platform" - :content-type="channel.contentType" :media="media" + :meta="channel.meta" :disabled="disabled" :preview-only="previewOnly" - @update:content-type="emit('update:contentType', channel.id, $event)" + @update:meta="emit('update:meta', channel.id, $event)" /> ([]); +const items = ref([]); const index = ref(null); const isOpen = computed({ @@ -27,12 +28,12 @@ const hasPrev = computed(() => safeIndex.value > 0); const hasNext = computed(() => safeIndex.value < items.value.length - 1); const showNav = computed(() => items.value.length > 1); -const open = (url: string, type: 'image' | 'video' = 'image') => { +const open = (url: string, type: MediaType = MediaType.Image) => { items.value = [{ url, type }]; index.value = 0; }; -const openCollection = (collection: MediaItem[], startIndex = 0) => { +const openCollection = (collection: PreviewItem[], startIndex = 0) => { if (collection.length === 0) return; items.value = [...collection]; index.value = Math.max(0, Math.min(startIndex, collection.length - 1)); @@ -106,6 +107,15 @@ defineExpose({ open, openCollection, close }); @click.stop /> +