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
<?php
declare(strict_types=1);
namespace App\Services\Social;
use App\Dto\MediaItem;
use App\Enums\Media\Type as MediaType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\LinkedInPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Http\SafeHttpFetcher;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Services\Social\Concerns\PublishesThreads;
use App\Services\Social\LinkCard\LinkCardFetcher;
use App\Services\Social\LinkCard\LinkCardMetadata;
use App\Support\Social\ThreadProgress;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;
/**
* Shared LinkedIn publishing pipeline. The publish format follows the attached
* media: a PDF becomes a document post, two or more images a multi-image post,
* and a single image or video a media post. A text post with a link becomes an
* article, because the Posts API does not scrape URLs. Subclasses provide the
* author identity (member or company page) and its public URL.
*/
abstract class AbstractLinkedInPublisher
{
use HasSocialHttpClient;
use PublishesThreads;
/** Article title must be under 400 characters, description under 4,086. */
private const int ARTICLE_TITLE_MAX = 399;
private const int ARTICLE_DESCRIPTION_MAX = 4085;
private const int ARTICLE_THUMB_TIMEOUT_SECONDS = 10;
/**
* LinkedIn answers 404 to a comment on a post it has not finished making
* available, so the comment is retried from the queue for up to five minutes.
*/
private const int COMMENT_RETRY_DELAY_SECONDS = 30;
private const int COMMENT_MAX_RETRIES = 10;
/**
* Characters `little` reserves for mentions, hashtags and templates. Any of
* them left unescaped ends the plain text there, so LinkedIn publishes the
* commentary cut at that character without an error.
*
* @see https://learn.microsoft.com/en-us/linkedin/marketing/community-management/shares/little-text-format
*/
private const string LITTLE_RESERVED = '[\\\\|{}@\[\]()<>#*_~]';
private const string LITTLE_RESERVED_PATTERN = '/'.self::LITTLE_RESERVED.'/';
/**
* What {@see self::toLittleText()} escapes: a whole URL, so its `#`
* fragment stays text, or one reserved character. A `#` that opens a
* hashtag (`#php`, not after a letter, digit, `/`, `=` or `&`, and with a letter in
* the tag so `#1` stays text) is skipped and still becomes a hashtag.
*/
private const string LITTLE_TEXT_PATTERN = '/(?:https?:\/\/|www\.)\S+|(?<![\p{L}\p{N}_\/=&])#(?=\p{N}*\p{L})(*SKIP)(*FAIL)|'.self::LITTLE_RESERVED.'/iu';
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. Per LinkedIn's Posts API docs, the
* feed/update permalink applies to any published post regardless of
* whether the author is a member or an organization, so subclasses
* (member vs. company page) share this implementation.
*/
protected function postUrl(?string $postId): ?string
{
return $postId ? "https://www.linkedin.com/feed/update/{$postId}" : null;
}
public function publish(Post $post): array
{
$this->validateContentLength($post);
$content = app(ContentSanitizer::class)->forPost($post);
$this->account = $post->socialAccount;
$this->hasRetried = false;
if ($this->account->needsProactiveTokenRefresh()) {
app(ConnectionVerifier::class)->refreshToken($this->account);
}
$this->accessToken = $this->account->access_token;
$rootHash = ThreadProgress::hash((string) $content, $post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all());
try {
return $this->publishWithComment($post, $content, $rootHash);
} catch (TokenExpiredException $e) {
return $this->retryWithRefresh($post, $content, $rootHash, $e);
}
}
/**
* @return array{id: string, url: ?string, thread_reply_ids?: list<string>}
*/
private function publishWithComment(Post $post, ?string $content, string $rootHash): array
{
return $this->publishThread(
$post,
$rootHash,
fn (): array => $this->dispatchByMedia($content, $post),
fn (string $text, Collection $media, array $previous, array $root): array => [
'id' => $this->createComment((string) data_get($root, 'id'), $text),
],
);
}
private function dispatchByMedia(?string $content, Post $post): array
{
$media = $post->mediaItems;
if ($media->contains(fn ($item) => $item->isDocument())) {
return $this->publishDocument($content, $media, $this->resolveDocumentTitle($post));
}
if ($media->filter(fn ($item) => $item->isImage())->count() >= 2) {
return $this->publishCarousel($content, $media);
}
return $this->publishPost($content, $media, $post->attachesLinkPreview());
}
private function retryWithRefresh(Post $post, ?string $content, string $rootHash, TokenExpiredException $originalException): array
{
if ($this->hasRetried) {
throw $originalException;
}
$this->hasRetried = true;
try {
app(ConnectionVerifier::class)->refreshToken($this->account);
$this->accessToken = $this->account->access_token;
} catch (Throwable $e) {
Log::error("{$this->label()} refresh failed during retry", [
'account_id' => $this->account->id,
'error' => $e->getMessage(),
]);
throw $originalException;
}
return $this->publishWithComment($post, $content, $rootHash);
}
private function publishPost(?string $content, $media, bool $attachArticle): array
{
$payload = $this->basePayload($content);
if ($media->isNotEmpty()) {
$item = $media->first();
$mediaUrn = $this->uploadMedia($item);
if ($mediaUrn) {
$payload['content'] = ['media' => array_filter([
'id' => $mediaUrn,
'altText' => $item->isImage() ? $item->altTextFor($this->platform()) : null,
], fn ($v) => $v !== null)];
}
} elseif ($attachArticle) {
$article = $this->articleContent($content);
if ($article !== null) {
$payload['content'] = ['article' => $article];
}
}
return $this->createPost($payload, 'post creation');
}
/**
* Article payload for the first link in a text-only post. Null when there is
* no link, the page has no title, or the scrape fails: the post still goes
* out as text. The thumbnail is optional.
*
* @return array{source: string, title: string, description?: string, thumbnail?: string}|null
*/
private function articleContent(?string $content): ?array
{
$card = filled($content) ? $this->articleCard($content) : null;
if ($card === null || blank($card->title)) {
return null;
}
return array_filter([
'source' => $card->uri,
'title' => Str::limit($card->title, self::ARTICLE_TITLE_MAX, ''),
'description' => Str::limit($card->description, self::ARTICLE_DESCRIPTION_MAX, ''),
'thumbnail' => $this->uploadArticleThumbnail($card),
], filled(...));
}
private function articleCard(string $content): ?LinkCardMetadata
{
try {
return app(LinkCardFetcher::class)->fetch($content);
} catch (Throwable $e) {
Log::warning("{$this->label()} link preview lookup failed", ['error' => $e->getMessage()]);
return null;
}
}
/**
* Image URN for the card's og:image, or null when there is no usable image.
* A dead token still propagates so the publish retry can refresh it.
*/
private function uploadArticleThumbnail(LinkCardMetadata $card): ?string
{
if (blank($card->imageUrl)) {
return null;
}
$tempFile = tempnam(sys_get_temp_dir(), 'li_article_');
if ($tempFile === false) {
return null;
}
try {
$this->downloadArticleThumbnail($card->imageUrl, $tempFile);
return $this->uploadLocalImage($tempFile);
} catch (TokenExpiredException $e) {
throw $e;
} catch (Throwable $e) {
Log::warning("{$this->label()} article thumbnail skipped", ['error' => $e->getMessage()]);
return null;
} finally {
@unlink($tempFile);
}
}
/**
* Redirects are not followed: the og:image URL is attacker-influenced and
* was only guarded against SSRF once.
*/
private function downloadArticleThumbnail(string $url, string $tempFile): void
{
$maxBytes = MediaType::Image->maxSizeInBytes();
$safeHttp = app(SafeHttpFetcher::class);
$response = $safeHttp
->limitTransfer($safeHttp->guardedRequest($url, followRedirects: false), $maxBytes, timeoutSeconds: self::ARTICLE_THUMB_TIMEOUT_SECONDS)
->sink($tempFile)
->get($url);
if (! $response->successful()) {
throw new RuntimeException("og:image responded with HTTP {$response->status()}");
}
$size = filesize($tempFile);
if ($size === false || $size === 0) {
throw new RuntimeException('og:image is empty');
}
if ($size > $maxBytes) {
throw new RuntimeException('og:image exceeds the maximum image size');
}
if (MediaType::classify(File::mimeType($tempFile) ?: '') !== MediaType::Image) {
throw new RuntimeException('og:image is not an image');
}
}
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[] = array_filter([
'id' => $imageUrn,
'altText' => $item->altTextFor($this->platform()),
], fn ($v) => $v !== null);
}
}
$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 LinkedInPublishException(
userMessage: "No PDF document was found for this {$this->label()} document post.",
category: ErrorCategory::MediaFormat,
);
}
$documentUrn = $this->uploadDocument($document);
if (! $documentUrn) {
throw new LinkedInPublishException(
userMessage: "{$this->label()} did not accept the document. Please try again.",
category: ErrorCategory::ServerError,
);
}
$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' => $this->toLittleText($content ?? ''),
'visibility' => 'PUBLIC',
'distribution' => [
'feedDistribution' => 'MAIN_FEED',
'targetEntities' => [],
'thirdPartyDistributionChannels' => [],
],
'lifecycleState' => 'PUBLISHED',
];
}
/**
* The commentary as plain `little` text: every reserved character escaped
* with a backslash, hashtags excepted. TryPost sends no mentions or
* templates, so an `@` or `{` the person typed is always text.
*/
private function toLittleText(string $content): string
{
return preg_replace_callback(
self::LITTLE_TEXT_PATTERN,
fn (array $matches): string => $this->escapeLittleReserved($matches[0]),
$content,
) ?? $this->escapeLittleReserved($content);
}
/**
* Every reserved character escaped, hashtags included. Byte-wise, so it
* also covers text the Unicode pattern cannot read.
*/
private function escapeLittleReserved(string $text): string
{
return preg_replace(self::LITTLE_RESERVED_PATTERN, '\\\\$0', $text) ?? $text;
}
/**
* 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),
];
}
/**
* `/v2/` because the versioned `/rest/socialActions` needs the Community
* Management API. Text only: LinkedIn drops the whole comment when it
* cannot fetch an image URL.
*
* @see https://learn.microsoft.com/en-us/linkedin/marketing/community-management/shares/comments-api
*/
private function createComment(string $postUrn, string $text): string
{
$response = $this->getHttpClient()->post(
"{$this->baseUrl()}/v2/socialActions/".rawurlencode($postUrn).'/comments',
[
'actor' => $this->authorUrn(),
'object' => $postUrn,
'message' => ['text' => $text],
],
);
if ($response->notFound()) {
throw new PlatformUnavailableException(
"{$this->label()} post is not ready for its comment yet",
$response->status(),
retryDelaySeconds: self::COMMENT_RETRY_DELAY_SECONDS,
maxRetries: self::COMMENT_MAX_RETRIES,
);
}
if ($response->failed()) {
Log::error("{$this->label()} comment creation failed", [
'status' => $response->status(),
'body' => $this->redactResponseBody($response->body()),
]);
$this->handleApiError($response);
}
return (string) $response->header('x-restli-id');
}
/**
* 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(Post $post): string
{
$title = data_get($post->meta, 'document_title');
if (filled($title)) {
return (string) $title;
}
return $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
{
$tempFile = tempnam(sys_get_temp_dir(), 'li_image_');
if ($tempFile === false) {
throw new LinkedInPublishException(
userMessage: "Could not prepare the image for {$this->label()}. Please try again.",
category: ErrorCategory::ServerError,
);
}
try {
$this->downloadToTempFile($mediaItem->url, $tempFile);
return $this->uploadLocalImage($tempFile);
} finally {
@unlink($tempFile);
}
}
/**
* Upload an image already on disk, re-encoded for LinkedIn first. GIFs are
* sent as they are so the animation survives. The caller owns the given
* file; the optimized copy is removed here.
*/
private function uploadLocalImage(string $path): string
{
$mime = File::mimeType($path) ?: '';
if (MediaType::classify($mime) !== MediaType::Image || MediaType::isGif($mime)) {
return $this->uploadImageFile($path);
}
$optimized = app(MediaOptimizer::class)->optimizeImage($path, $this->platform());
try {
return $this->uploadImageFile($optimized);
} finally {
@unlink($optimized);
}
}
/**
* Initialize a LinkedIn image upload and PUT the bytes already on disk.
*/
private function uploadImageFile(string $path): 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->handleMediaApiError($initResponse);
}
$initData = $initResponse->json();
$uploadUrl = data_get($initData, 'value.uploadUrl');
$imageUrn = data_get($initData, 'value.image');
if (! is_string($uploadUrl) || $uploadUrl === '' || ! is_string($imageUrn) || $imageUrn === '') {
throw new LinkedInPublishException(
userMessage: "{$this->label()} did not accept the image upload. Please try again.",
category: ErrorCategory::ServerError,
);
}
$stream = fopen($path, 'r');
if ($stream === false) {
throw new LinkedInPublishException(
userMessage: "Could not read the image for {$this->label()}. Please try again.",
category: ErrorCategory::ServerError,
);
}
$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->handleMediaApiError($uploadResponse);
}
return $imageUrn;
}
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->handleMediaApiError($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 LinkedInPublishException(
userMessage: "{$this->label()} did not accept the video upload. Please try again.",
category: ErrorCategory::ServerError,
);
}
$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->handleMediaApiError($chunkResponse);
}
$etag = $chunkResponse->header('etag');
if ($etag) {
$uploadedPartIds[] = $etag;
}
unset($chunkData, $chunkResponse);
$this->freeChunkMemory();
}
} 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->handleMediaApiError($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->handleMediaApiError($initResponse);
}
$initData = $initResponse->json();
$uploadUrl = data_get($initData, 'value.uploadUrl');
$documentUrn = data_get($initData, 'value.document');
if (! $uploadUrl || ! $documentUrn) {
throw new LinkedInPublishException(
userMessage: "{$this->label()} did not accept the document upload. Please try again.",
category: ErrorCategory::ServerError,
);
}
// 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->handleMediaApiError($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 LinkedInPublishException(
userMessage: "{$this->label()} {$label} processing failed.",
category: ErrorCategory::ServerError,
);
}
sleep($this->processingPollSeconds());
}
throw new LinkedInPublishException(
userMessage: "{$this->label()} {$label} processing did not complete in time.",
category: ErrorCategory::ServerError,
);
}
/**
* 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 LinkedInPublishException(
userMessage: "Could not fetch the media to upload to {$this->label()}. Please try again.",
category: ErrorCategory::ServerError,
);
}
}
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();
}
/**
* Media steps run before the post exists, so a LinkedIn 5xx there is
* safe to retry; anything else is classified like a post failure.
*/
private function handleMediaApiError(Response $response): never
{
if ($response->serverError()) {
throw new PlatformUnavailableException(
"{$this->label()} returned {$response->status()} while uploading media",
$response->status(),
);
}
$this->handleApiError($response);
}
private function handleApiError(Response $response): never
{
throw LinkedInPublishException::fromApiResponse($response);
}
}