Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
refactor(linkedin): extract shared publisher base and fix multi-image carousel
Paulo Castellano6a46bee46990
diff --git a/app/Services/Social/AbstractLinkedInPublisher.php b/app/Services/Social/AbstractLinkedInPublisher.phpnew file mode 100644index 000000000..fa595624d--- /dev/null+++ b/app/Services/Social/AbstractLinkedInPublisher.php@@ -0,0 +1,520 @@+<?php++declare(strict_types=1);++namespace App\Services\Social;++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;++/**+ * Shared LinkedIn publishing pipeline. The publish format follows the attached+ * media — a PDF becomes a document post, 2+ images a multi-image post, and+ * anything else (a single image/video or text only) a regular post. Subclasses+ * provide the author identity (member vs. company page) and its public URL.+ */+abstract class AbstractLinkedInPublisher+{+ use HasSocialHttpClient;++ private string $apiVersion = '202601';++ private string $accessToken;++ protected SocialAccount $account;++ private bool $hasRetried = false;++ /**+ * The LinkedIn account kind this publisher targets (member or company page).+ */+ abstract protected function platform(): Platform;++ /**+ * The URN that authors the post and owns its uploaded media.+ */+ abstract protected function authorUrn(): string;++ /**+ * Public URL of the created post. Defaults to the member feed update;+ * company pages override it.+ */+ protected function postUrl(?string $postId): ?string+ {+ return $postId ? "https://www.linkedin.com/feed/update/{$postId}" : null;+ }++ public function publish(PostPlatform $postPlatform): array+ {+ $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;++ 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 = [];++ foreach ($media as $item) {+ if (! $item->isImage()) {+ continue;+ }++ $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<string, mixed>+ */+ 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<string, mixed> $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+ {+ $mimeType = $mediaItem->mime_type;++ if (str_starts_with($mimeType, 'video/')) {+ return $this->uploadVideo($mediaItem);+ }++ if (str_starts_with($mimeType, 'image/')) {+ return $this->uploadImage($mediaItem);+ }++ return 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 (str_starts_with($detectedMime, 'image/') && ! str_starts_with($detectedMime, 'image/gif')) {+ $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.+ */+ private function waitForProcessing(string $resource, string $assetUrn, string $label, int $maxAttempts = 30): void+ {+ $encodedUrn = urlencode($assetUrn);++ for ($i = 0; $i < $maxAttempts; $i++) {+ $response = $this->getHttpClient()->get("{$this->baseUrl()}/rest/{$resource}/{$encodedUrn}");++ if ($response->failed()) {+ Log::warning("{$this->label()} {$label} status check failed", ['attempt' => $i]);+ sleep(5);++ 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(5);+ }++ Log::warning("{$this->label()} {$label} processing timeout, proceeding anyway");+ }++ 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/LinkedInPagePublisher.php b/app/Services/Social/LinkedInPagePublisher.phpindex 68d7bd450..1c3b50fce 100644--- a/app/Services/Social/LinkedInPagePublisher.php+++ b/app/Services/Social/LinkedInPagePublisher.php@@ -5,621 +5,36 @@ declare(strict_types=1);namespace App\Services\Social;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}";-- try {- return $this->dispatchByMedia($organizationUrn, $content, $postPlatform);- } catch (TokenExpiredException $e) {- return $this->retryWithRefresh($postPlatform, $content, $e);- }- }-- /**- * The page publish format follows the attached media — a PDF becomes a- * document post, 2+ images a multi-image post, and anything else a regular- * post.- */- private function dispatchByMedia(string $organizationUrn, ?string $content, PostPlatform $postPlatform): array- {- $media = $postPlatform->post->mediaItems;-- if ($media->contains(fn ($item) => $item->isDocument())) {- return $this->publishDocument($organizationUrn, $content, $media, $this->resolveDocumentTitle($postPlatform), $this->account);- }-- if ($media->filter(fn ($item) => $item->isImage())->count() >= 2) {- return $this->publishCarousel($organizationUrn, $content, $media, $this->account);- }-- return $this->publishPost($organizationUrn, $content, $media, $this->account);- }-- 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;-- $organizationId = $this->account->meta['organization_id'] ?? null;- $organizationUrn = "urn:li:organization:{$organizationId}";-- return $this->dispatchByMedia($organizationUrn, $content, $postPlatform);- } 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/"- : "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,- ];- }- }-- $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,- ];+ return "urn:li:organization:{$organizationId}";}- /**- * 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+ protected function postUrl(?string $postId): ?string{- $title = data_get($postPlatform->meta, 'document_title');-- if (filled($title)) {- return (string) $title;+ if (! $postId) {+ return null;}- return $postPlatform->post->mediaItems->first(fn ($media) => $media->isDocument())?->original_filename ?? 'Document';- }-- private function publishDocument(string $organizationUrn, ?string $content, $mediaCollection, string $title, $account): array- {- $document = $mediaCollection->first(fn ($media) => $media->isDocument());-- if (! $document) {- throw new \Exception('No PDF document for LinkedIn Page document post');- }-- $documentUrn = $this->uploadDocument($document, $organizationUrn);-- if (! $documentUrn) {- throw new \Exception('LinkedIn Page document upload failed');- }-- $payload = [- 'author' => $organizationUrn,- 'commentary' => $content ?? '',- 'visibility' => 'PUBLIC',- 'distribution' => [- 'feedDistribution' => 'MAIN_FEED',- 'targetEntities' => [],- 'thirdPartyDistributionChannels' => [],- ],- 'lifecycleState' => 'PUBLISHED',- 'content' => [- 'media' => [- 'id' => $documentUrn,- 'title' => $title,- ],- ],- ];-- $response = $this->getHttpClient()- ->post("{$this->baseUrl}/rest/posts", $payload);-- if ($response->failed()) {- Log::error('LinkedIn Page document post creation failed', [- 'status' => $response->status(),- 'body' => $this->redactResponseBody($response->body()),- ]);- $this->handleApiError($response);- }-- $postId = $response->header('x-restli-id');-- $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 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 uploadDocument($mediaItem, string $ownerUrn): ?string- {- // Step 1: Initialize upload- $initResponse = $this->getHttpClient()- ->post("{$this->baseUrl}/rest/documents?action=initializeUpload", [- 'initializeUploadRequest' => [- 'owner' => $ownerUrn,- ],- ]);-- if ($initResponse->failed()) {- Log::error('LinkedIn Page document init failed', ['body' => $this->redactResponseBody($initResponse->body())]);- $this->handleApiError($initResponse);- }-- $initData = $initResponse->json();- $uploadUrl = $initData['value']['uploadUrl'] ?? null;- $documentUrn = $initData['value']['document'] ?? null;-- if (! $uploadUrl || ! $documentUrn) {- throw new \Exception('LinkedIn Page document upload init missing uploadUrl or document URN');- }-- // Step 2: Upload the PDF in a single request (Documents API is not chunked)- $tempFile = tempnam(sys_get_temp_dir(), 'lip_document_');-- try {- $downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url);-- if ($downloadResponse->failed()) {- throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status());- }-- $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('LinkedIn Page document upload failed', ['body' => $this->redactResponseBody($uploadResponse->body())]);- $this->handleApiError($uploadResponse);- }- } finally {- @unlink($tempFile);- }-- // Step 3: Wait for processing (SYNCHRONOUS_UPLOAD is not supported)- $this->waitForDocumentProcessing($documentUrn);-- return $documentUrn;- }-- private function waitForDocumentProcessing(string $documentUrn, int $maxAttempts = 30): void- {- $encodedUrn = urlencode($documentUrn);-- for ($i = 0; $i < $maxAttempts; $i++) {- $response = $this->getHttpClient()- ->get("{$this->baseUrl}/rest/documents/{$encodedUrn}");-- if ($response->failed()) {- Log::warning('LinkedIn Page document status check failed', ['attempt' => $i]);- sleep(5);-- continue;- }-- $status = data_get($response->json(), 'status', 'UNKNOWN');-- if ($status === 'AVAILABLE') {- return;- }-- if ($status === 'PROCESSING_FAILED') {- throw new \Exception('LinkedIn Page document processing failed');- }-- sleep(5);- }-- Log::warning('LinkedIn Page document 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.phpindex d60b81e24..cb02ddce8 100644--- a/app/Services/Social/LinkedInPublisher.php+++ b/app/Services/Social/LinkedInPublisher.php@@ -5,598 +5,19 @@ declare(strict_types=1);namespace App\Services\Social;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()- {- $this->baseUrl = config('trypost.platforms.linkedin.api');- }-- private SocialAccount $account;-- private bool $hasRetried = false;-- public function publish(PostPlatform $postPlatform): array- {- $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}";-- try {- return $this->dispatchByMedia($personUrn, $content, $postPlatform);- } catch (TokenExpiredException $e) {- return $this->retryWithRefresh($postPlatform, $content, $e);- }- }-- /**- * LinkedIn's publish format follows the attached media — a PDF becomes a- * document post, 2+ images a multi-image post, and anything else (a single- * image/video or text only) a regular post.- */- private function dispatchByMedia(string $personUrn, ?string $content, PostPlatform $postPlatform): array- {- $media = $postPlatform->post->mediaItems;-- if ($media->contains(fn ($item) => $item->isDocument())) {- return $this->publishDocument($personUrn, $content, $media, $this->resolveDocumentTitle($postPlatform));- }-- if ($media->filter(fn ($item) => $item->isImage())->count() >= 2) {- return $this->publishCarousel($personUrn, $content, $media);- }-- return $this->publishPost($personUrn, $content, $media);- }-- private function retryWithRefresh(PostPlatform $postPlatform, ?string $content, TokenExpiredException $originalException): array+ protected function platform(): Platform{- 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}";-- return $this->dispatchByMedia($personUrn, $content, $postPlatform);- } 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,- ];- }- }-- $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,- ];- }-- /**- * 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 —- * LinkedIn renders the title beneath the document.- */- 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 publishDocument(string $personUrn, ?string $content, $mediaCollection, string $title): array- {- $document = $mediaCollection->first(fn ($media) => $media->isDocument());-- if (! $document) {- throw new \Exception('No PDF document for LinkedIn document post');- }-- $documentUrn = $this->uploadDocument($document, $personUrn);-- if (! $documentUrn) {- throw new \Exception('LinkedIn document upload failed');- }-- $payload = [- 'author' => $personUrn,- 'commentary' => $content ?? '',- 'visibility' => 'PUBLIC',- 'distribution' => [- 'feedDistribution' => 'MAIN_FEED',- 'targetEntities' => [],- 'thirdPartyDistributionChannels' => [],- ],- 'lifecycleState' => 'PUBLISHED',- 'content' => [- 'media' => [- 'id' => $documentUrn,- 'title' => $title,- ],- ],- ];-- $response = $this->getHttpClient()- ->post("{$this->baseUrl}/rest/posts", $payload);-- if ($response->failed()) {- Log::error('LinkedIn document 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 uploadDocument($mediaItem, string $ownerUrn): ?string- {- // Step 1: Initialize upload- $initResponse = $this->getHttpClient()- ->post("{$this->baseUrl}/rest/documents?action=initializeUpload", [- 'initializeUploadRequest' => [- 'owner' => $ownerUrn,- ],- ]);-- if ($initResponse->failed()) {- Log::error('LinkedIn document init failed', ['body' => $this->redactResponseBody($initResponse->body())]);- $this->handleApiError($initResponse);- }-- $initData = $initResponse->json();- $uploadUrl = $initData['value']['uploadUrl'] ?? null;- $documentUrn = $initData['value']['document'] ?? null;-- if (! $uploadUrl || ! $documentUrn) {- throw new \Exception('LinkedIn document upload init missing uploadUrl or document URN');- }-- // Step 2: Upload the PDF in a single request (Documents API is not chunked)- $tempFile = tempnam(sys_get_temp_dir(), 'li_document_');-- try {- $downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url);-- if ($downloadResponse->failed()) {- throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status());- }-- $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('LinkedIn document upload failed', ['body' => $this->redactResponseBody($uploadResponse->body())]);- $this->handleApiError($uploadResponse);- }- } finally {- @unlink($tempFile);- }-- // Step 3: Wait for processing (SYNCHRONOUS_UPLOAD is not supported)- $this->waitForDocumentProcessing($documentUrn);-- return $documentUrn;- }-- private function waitForDocumentProcessing(string $documentUrn, int $maxAttempts = 30): void- {- $encodedUrn = urlencode($documentUrn);-- for ($i = 0; $i < $maxAttempts; $i++) {- $response = $this->getHttpClient()- ->get("{$this->baseUrl}/rest/documents/{$encodedUrn}");-- if ($response->failed()) {- Log::warning('LinkedIn document status check failed', ['attempt' => $i]);- sleep(5);-- continue;- }-- $status = data_get($response->json(), 'status', 'UNKNOWN');-- if ($status === 'AVAILABLE') {- return;- }-- if ($status === 'PROCESSING_FAILED') {- throw new \Exception('LinkedIn document processing failed');- }-- sleep(5);- }-- Log::warning('LinkedIn document processing timeout, proceeding anyway');+ return Platform::LinkedIn;}- private function handleApiError(Response $response): never+ protected function authorUrn(): string{- throw LinkedInPublishException::fromApiResponse($response);+ return "urn:li:person:{$this->account->platform_user_id}";}}diff --git a/tests/Feature/Services/Social/LinkedInPagePublisherTest.php b/tests/Feature/Services/Social/LinkedInPagePublisherTest.phpindex c1b5df6eb..1e5bce0aa 100644--- a/tests/Feature/Services/Social/LinkedInPagePublisherTest.php+++ b/tests/Feature/Services/Social/LinkedInPagePublisherTest.php@@ -82,10 +82,14 @@ test('linkedin page publisher uses organization urn', function () {});test('linkedin page publisher throws exception when organization id missing', function () {+ Http::fake();$this->socialAccount->update(['meta' => []]);expect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(Exception::class, 'LinkedIn Page organization ID not configured');++ // Fail-fast: the missing org id must abort before any LinkedIn request.+ Http::assertNothingSent();});test('linkedin page publisher uses correct headers', function () {@@ -277,6 +281,61 @@ test('linkedin page publisher can publish post with image using organization urn);});+test('linkedin page publisher publishes a multi-image carousel with image ids under the organization', function () {+ $this->post->update([+ 'media' => [+ ['id' => 'm1', 'path' => 'media/c1.jpg', 'url' => 'https://example.com/c1.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'c1.jpg'],+ ['id' => 'm2', 'path' => 'media/c2.jpg', 'url' => 'https://example.com/c2.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'c2.jpg'],+ ],+ ]);++ $imageUrns = ['urn:li:image:OrgCarousel1', 'urn:li:image:OrgCarousel2'];+ $uploadUrls = ['https://www.linkedin.com/dms/upload/org/1', 'https://www.linkedin.com/dms/upload/org/2'];+ $initCount = 0;++ Http::fake(function ($request) use ($imageUrns, $uploadUrls, &$initCount) {+ $url = $request->url();++ if (str_contains($url, '/rest/images')) {+ $idx = $initCount % 2;+ $initCount++;++ return Http::response(['value' => ['uploadUrl' => $uploadUrls[$idx], 'image' => $imageUrns[$idx]]], 200);+ }++ foreach ($uploadUrls as $uploadUrl) {+ if ($url === $uploadUrl) {+ return Http::response(null, 201);+ }+ }++ if (str_contains($url, '/rest/posts')) {+ return Http::response(null, 201, ['x-restli-id' => 'urn:li:share:orgcarousel']);+ }++ return Http::response('fake-image-content', 200);+ });++ $result = $this->publisher->publish($this->postPlatform);++ expect($result['id'])->toBe('urn:li:share:orgcarousel');++ // Org carousel must author as the organization and send image URNs under `id` (not `media`).+ Http::assertSent(function ($request) {+ if (! str_contains($request->url(), '/rest/posts')) {+ return false;+ }+ $data = $request->data();+ $images = data_get($data, 'content.multiImage.images');++ return data_get($data, 'author') === 'urn:li:organization:123456'+ && is_array($images)+ && count($images) === 2+ && data_get($images, '0.id') === 'urn:li:image:OrgCarousel1'+ && ! array_key_exists('media', $images[0]);+ });+});+test('linkedin page publisher can publish a document (pdf carousel) using organization urn', function () {$this->postPlatform->update(['content_type' => ContentType::LinkedInPagePost,diff --git a/tests/Feature/Services/Social/LinkedInPublisherTest.php b/tests/Feature/Services/Social/LinkedInPublisherTest.phpindex bf089ffb4..2c26dcbd4 100644--- a/tests/Feature/Services/Social/LinkedInPublisherTest.php+++ b/tests/Feature/Services/Social/LinkedInPublisherTest.php@@ -300,14 +300,17 @@ test('linkedin publisher can publish carousel with multiple images', function ()expect($result['id'])->toBe('urn:li:share:carousel999');expect($result['url'])->toContain('linkedin.com/feed/update/urn:li:share:carousel999');- // Assert the post payload contains multiImage.images with 3 items+ // Each multiImage entry must carry the image URN under `id` (LinkedIn rejects `media`).Http::assertSent(function ($request) {if (! str_contains($request->url(), '/rest/posts')) {return false;}$images = data_get($request->data(), 'content.multiImage.images');- return is_array($images) && count($images) === 3;+ return is_array($images)+ && count($images) === 3+ && data_get($images, '0.id') === 'urn:li:image:CarouselImageUrn1'+ && ! array_key_exists('media', $images[0]);});});