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\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\X\MediaProcessingState;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\XPublishException;
use App\Models\Post;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Services\Social\Concerns\PublishesThreads;
use App\Support\Social\PublishCheckpoint;
use App\Support\Social\ThreadProgress;
use App\Support\Social\XPoll;
use Illuminate\Http\Client\ConnectionException;
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\Sleep;
use Throwable;
class XPublisher
{
use HasSocialHttpClient;
use PublishesThreads;
private string $baseUrl;
private string $accessToken;
private const int MEDIA_PROCESSING_RETRY_DELAY_SECONDS = 60;
private const int MEDIA_PROCESSING_MAX_RETRIES = 30;
/**
* The longest wait between two status checks, whatever check_after_secs
* asks for, so 20 checks stay inside the publish job's timeout. Media
* still processing after them is rescheduled.
*/
private const int MEDIA_STATUS_MAX_WAIT_SECONDS = 30;
/** @var array<string, string> */
private array $uploadedMedia = [];
private ?string $currentMediaItemId = null;
public function __construct()
{
$this->baseUrl = config('trypost.platforms.x.api');
}
public function publish(Post $post): array
{
$this->validateContentLength($post);
$content = app(ContentSanitizer::class)->forPost($post);
$account = $post->socialAccount;
if ($account->needsProactiveTokenRefresh()) {
app(ConnectionVerifier::class)->refreshToken($account);
}
$this->accessToken = $account->access_token;
$this->uploadedMedia = PublishCheckpoint::xMedia($post->error_context);
$rootHash = ThreadProgress::hash((string) $content, $post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all());
return $this->publishThread(
$post,
$rootHash,
fn (): array => $this->publishRoot($post, $content),
fn (string $text, Collection $media, array $parent, array $root, ?array $poll): array => $this->publishReply($text, $media, $parent, $poll, $account->username),
);
}
/**
* @return array{id: string, url: ?string}
*/
private function publishRoot(Post $post, ?string $content): array
{
$isPoll = $post->content_type === ContentType::XPoll;
$data = $this->withText($content, $this->attachments($content, $post->mediaItems, $isPoll, $post->meta));
if (data_get($post->meta, 'is_ai_generated') === true) {
$data['made_with_ai'] = true;
}
if (blank($content) && ! isset($data['media'])) {
throw new XPublishException(
userMessage: 'X posts require either text or media. Please add content to your post.',
category: ErrorCategory::MediaFormat,
);
}
return $this->createTweet($data, $post->socialAccount->username);
}
/**
* A reply of the thread, under the post before it.
*
* @param Collection<int, MediaItem> $media
* @param array<string, mixed> $parent
* @param array<string, mixed>|null $poll
* @return array{id: string, url: ?string}
*/
private function publishReply(string $text, Collection $media, array $parent, ?array $poll, string $username): array
{
$data = $this->withText($text, [
...$this->attachments($text, $media, filled($poll), ['poll' => $poll]),
'reply' => ['in_reply_to_tweet_id' => (string) data_get($parent, 'id')],
]);
return $this->createTweet($data, $username);
}
/**
* The tweet's fields, led by its text when it has any.
*
* @param array<string, mixed> $fields
* @return array<string, mixed>
*/
private function withText(?string $text, array $fields): array
{
if (blank($text)) {
return $fields;
}
return ['text' => $text, ...$fields];
}
/**
* What a post of the thread attaches: its poll, or its media.
*
* @param Collection<int, MediaItem> $media
* @return array<string, mixed>
*/
private function attachments(?string $text, Collection $media, bool $isPoll, ?array $meta): array
{
if ($isPoll) {
return ['poll' => $this->pollPayload($text, $media, $meta)];
}
return $this->mediaPayload($media);
}
/**
* A poll, on the post or on a reply, needs its question (that post's text),
* distinct choices and a length, and cannot carry media. `$meta` holds the
* poll under `poll`: the post's meta, or the reply itself.
*
* @param Collection<int, MediaItem> $media
* @return array{options: list<string>, duration_minutes: int}
*/
private function pollPayload(?string $question, Collection $media, ?array $meta): array
{
$violation = XPoll::publishViolation($question, $media->isNotEmpty(), $meta);
if (filled($violation)) {
throw new XPublishException(userMessage: $violation, category: ErrorCategory::ContentPolicy);
}
return XPoll::payload($meta);
}
/**
* Uploads the media and returns the tweet's `media` field, empty when
* nothing uploaded.
*
* @param Collection<int, MediaItem> $media
* @return array{media?: array{media_ids: list<string>}}
*/
private function mediaPayload(Collection $media): array
{
$mediaIds = [];
foreach ($media as $mediaItem) {
$this->currentMediaItemId = $mediaItem->id;
$mediaId = $this->uploadedMedia[$mediaItem->id] ?? null;
if ($mediaId !== null && ! $this->isKnownMedia($mediaId)) {
unset($this->uploadedMedia[$mediaItem->id]);
$mediaId = null;
}
if ($mediaId !== null) {
$this->waitForProcessing($mediaId);
} else {
$mediaId = data_get($this->uploadMedia($mediaItem), 'data.id');
}
if (! $mediaId) {
throw new XPublishException(
userMessage: 'X did not accept the media upload. Please try again.',
category: ErrorCategory::ServerError,
);
}
$this->uploadedMedia[$mediaItem->id] = (string) $mediaId;
// X expects media_ids as strings in the tweets payload.
$mediaIds[] = (string) $mediaId;
$this->uploadAltText((string) $mediaId, $mediaItem);
}
return $mediaIds === [] ? [] : ['media' => ['media_ids' => $mediaIds]];
}
/**
* @param array<string, mixed> $data
* @return array{id: string, url: ?string}
*/
private function createTweet(array $data, ?string $username): array
{
$response = $this->getHttpClient()
->post("{$this->baseUrl}/tweets", $data);
if ($response->failed()) {
Log::error('X post creation failed', [
'status' => $response->status(),
'body' => $this->redactResponseBody($response->body()),
]);
$this->handleApiError($response);
}
$tweetId = $response->json('data.id');
return [
'id' => $tweetId ?? 'unknown',
'url' => $tweetId ? "https://x.com/{$username}/status/{$tweetId}" : null,
];
}
private function getHttpClient(): PendingRequest
{
return $this->socialHttp()->withToken($this->accessToken)
->withHeaders([
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]);
}
/**
* Sets the image's accessibility description on X via the v2 media
* metadata endpoint. Best-effort: only images carry alt text, and a failure
* here never blocks the tweet — the media already uploaded and the post
* should still go out without the description.
*/
private function uploadAltText(string $mediaId, MediaItem $mediaItem): void
{
if (! $mediaItem->isImage()) {
return;
}
$alt = $mediaItem->altTextFor(Platform::X);
if ($alt === null) {
return;
}
try {
$this->getHttpClient()->post("{$this->baseUrl}/media/metadata", [
'id' => $mediaId,
'metadata' => [
'alt_text' => [
'text' => $alt,
],
],
]);
} catch (Throwable $e) {
Log::warning('X alt text upload failed; posting the tweet without it', [
'media_id' => $mediaId,
'error' => $e->getMessage(),
]);
}
}
private function uploadMedia($mediaItem): ?array
{
$mimeType = $mediaItem->mime_type;
// Download to temp file (memory-safe)
$tempFile = tempnam(sys_get_temp_dir(), 'x_media_');
try {
$downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url);
if ($downloadResponse->failed()) {
throw new XPublishException(
userMessage: 'Could not fetch the media to upload to X. Please try again.',
category: ErrorCategory::ServerError,
);
}
if (blank($mimeType)) {
$mimeType = File::mimeType($tempFile) ?: null;
}
if (blank($mimeType)) {
throw new XPublishException(
userMessage: 'Unsupported media type for X.',
category: ErrorCategory::MediaFormat,
);
}
// Optimize images (skip GIFs — they need special handling)
if (MediaType::classify($mimeType) === MediaType::Image && ! MediaType::isGif($mimeType)) {
$optimizer = app(MediaOptimizer::class);
$optimizedPath = $optimizer->optimizeImage($tempFile, Platform::X);
@unlink($tempFile);
$tempFile = $optimizedPath;
$mimeType = 'image/jpeg';
}
$fileSize = filesize($tempFile);
$mediaCategory = $this->getMediaCategory($mimeType);
$isVideo = MediaType::classify($mimeType) === MediaType::Video;
$isGif = MediaType::isGif($mimeType);
$useChunkedUpload = $isVideo || $isGif || $fileSize > 5 * 1024 * 1024;
if ($useChunkedUpload) {
return $this->chunkedUpload($tempFile, $fileSize, $mimeType, $mediaCategory);
}
// Simple upload for small images
$response = $this->socialHttp()->withToken($this->accessToken)
->timeout(360)
->attach(
'media',
fopen($tempFile, 'r'),
basename($tempFile),
['Content-Type' => $mimeType]
);
$formParams = [];
if ($mediaCategory) {
$formParams['media_category'] = $mediaCategory;
}
$response = $response->post("{$this->baseUrl}/media/upload", $formParams);
if ($response->failed()) {
Log::error('X media upload error', [
'status' => $response->status(),
'body' => $this->redactResponseBody($response->body()),
]);
$this->handleApiError($response);
}
return $response->json();
} finally {
@unlink($tempFile);
}
}
private function chunkedUpload(string $tempFile, int $totalBytes, string $mimeType, ?string $mediaCategory): array
{
$initPayload = [
'media_type' => $mimeType,
'total_bytes' => $totalBytes,
];
if ($mediaCategory) {
$initPayload['media_category'] = $mediaCategory;
}
// INIT — X requires application/json (MediaUploadConfigRequest).
$initResponse = $this->socialHttp()->withToken($this->accessToken)
->timeout(60)
->asJson()
->post("{$this->baseUrl}/media/upload/initialize", $initPayload);
if ($initResponse->failed()) {
Log::error('X chunked upload INIT error', [
'status' => $initResponse->status(),
'body' => $this->redactResponseBody($initResponse->body()),
]);
$this->handleApiError($initResponse);
}
$initData = $initResponse->json();
$mediaId = data_get($initData, 'data.id');
if (! $mediaId) {
throw new XPublishException(
userMessage: 'X did not accept the media upload. Please try again.',
category: ErrorCategory::ServerError,
);
}
// APPEND - Read from temp file in 1MB chunks. Matches the
// twitter-api-v2 SDK default and X's own quickstart examples;
// larger chunks (we previously used 5MB) trigger 413 at the X
// edge with an empty body.
$chunkSize = 1024 * 1024;
$handle = fopen($tempFile, 'r');
$index = 0;
try {
while (! feof($handle)) {
$chunk = fread($handle, $chunkSize);
if ($chunk === '' || $chunk === false) {
break;
}
$appendResponse = $this->socialHttp()->withToken($this->accessToken)
->timeout(300)
->attach('media', $chunk, 'chunk'.$index, ['Content-Type' => $mimeType])
->post("{$this->baseUrl}/media/upload/{$mediaId}/append", [
'segment_index' => $index,
]);
if ($appendResponse->failed()) {
Log::error('X chunked upload APPEND error', [
'status' => $appendResponse->status(),
'body' => $this->redactResponseBody($appendResponse->body()),
'segment' => $index,
]);
$this->handleApiError($appendResponse);
}
$index++;
unset($chunk, $appendResponse);
$this->freeChunkMemory();
}
} finally {
fclose($handle);
}
// FINALIZE — runtime rejects empty / non-JSON bodies with
// "Request body must be a JSON object." Send `{}` explicitly
// (empty array encodes as `[]`, which is not an object).
$finalizeResponse = $this->socialHttp()->withToken($this->accessToken)
->timeout(60)
->withBody('{}', 'application/json')
->post("{$this->baseUrl}/media/upload/{$mediaId}/finalize");
if ($finalizeResponse->failed()) {
Log::error('X chunked upload FINALIZE error', [
'status' => $finalizeResponse->status(),
'body' => $this->redactResponseBody($finalizeResponse->body()),
]);
$this->handleApiError($finalizeResponse);
}
$finalizeData = $finalizeResponse->json();
// Videos/GIFs (and any finalize that reports processing_info) must finish
// before we attach the media_id to a tweet — otherwise X returns
// ProblemType::InvalidRequest / invalid media IDs.
$processingInfo = data_get($finalizeData, 'data.processing_info')
?? data_get($finalizeData, 'processing_info');
if (
$processingInfo !== null
|| MediaType::classify($mimeType) === MediaType::Video
|| MediaType::isGif($mimeType)
) {
$this->waitForProcessing((string) $mediaId);
}
// Return in same format as simple upload
return [
'data' => [
'id' => (string) $mediaId,
],
];
}
/**
* Videos are always `tweet_video`; `amplify_video` is the Ads-creative category.
*/
private function getMediaCategory(string $mimeType): ?string
{
if (MediaType::classify($mimeType) === MediaType::Video) {
return 'tweet_video';
}
if (MediaType::isGif($mimeType)) {
return 'tweet_gif';
}
if (MediaType::classify($mimeType) === MediaType::Image) {
return 'tweet_image';
}
return null;
}
private function isKnownMedia(string $mediaId): bool
{
$response = $this->mediaStatus($mediaId);
if (in_array($response->status(), [400, 404], true)) {
return false;
}
if ($response->serverError()) {
throw new PlatformUnavailableException(
message: "X returned {$response->status()} checking media {$mediaId}",
httpStatus: $response->status(),
);
}
if ($response->failed()) {
$this->handleApiError($response);
}
return true;
}
private function mediaStatus(string $mediaId): Response
{
try {
return $this->getHttpClient()
->get("{$this->baseUrl}/media/upload", [
'media_id' => $mediaId,
'command' => 'STATUS',
]);
} catch (ConnectionException $e) {
throw new PlatformUnavailableException(
message: "X media status check failed to connect: {$e->getMessage()}",
context: [
PublishCheckpoint::X_MEDIA => [
...$this->uploadedMedia,
...($this->currentMediaItemId !== null ? [$this->currentMediaItemId => $mediaId] : []),
],
],
);
}
}
private function waitForProcessing(string $mediaId, int $maxAttempts = 20): void
{
$lastProcessingInfo = null;
for ($i = 0; $i < $maxAttempts; $i++) {
// Official status endpoint: GET /2/media/upload?media_id=...&command=STATUS
// (not GET /2/media/{id} — that path is not the upload-status contract).
$response = $this->mediaStatus($mediaId);
if ($response->failed()) {
Log::error('X media status check error', ['body' => $this->redactResponseBody($response->body())]);
Sleep::for(3)->seconds();
continue;
}
$responseData = $response->json();
$processingInfo = data_get($responseData, 'data.processing_info');
// If processing_info doesn't exist, assume it's ready
if ($processingInfo === null) {
return;
}
$lastProcessingInfo = $processingInfo;
$state = $this->processingState($processingInfo);
if ($state === MediaProcessingState::Succeeded) {
return;
}
if ($state === MediaProcessingState::Failed) {
$error = data_get($processingInfo, 'error', 'Unknown error');
$rawError = is_string($error) ? $error : json_encode($error);
Log::error('X media processing failed: '.$rawError);
throw new XPublishException(
userMessage: 'X could not process the uploaded media. Please try a different file.',
category: ErrorCategory::MediaFormat,
platformErrorCode: 'media-processing-failed',
rawResponse: $rawError ?: null,
);
}
Sleep::for(min(self::MEDIA_STATUS_MAX_WAIT_SECONDS, max(0, (int) data_get($processingInfo, 'check_after_secs', 3))))->seconds();
}
if ($this->processingState($lastProcessingInfo)?->isProcessing() !== true) {
Log::error('X media processing timed out', [
'media_id' => $mediaId,
'processing_info' => $lastProcessingInfo,
]);
throw new XPublishException(
userMessage: 'X media processing timed out. Please try again.',
category: ErrorCategory::ServerError,
platformErrorCode: 'media-processing-timeout',
rawResponse: is_array($lastProcessingInfo) ? json_encode($lastProcessingInfo) : null,
);
}
Log::warning('X media still processing, publish rescheduled', [
'media_id' => $mediaId,
'processing_info' => $lastProcessingInfo,
]);
throw new PlatformUnavailableException(
message: "X is still processing media {$mediaId}",
context: [
PublishCheckpoint::X_MEDIA => [
...$this->uploadedMedia,
...($this->currentMediaItemId !== null ? [$this->currentMediaItemId => $mediaId] : []),
],
],
retryDelaySeconds: self::MEDIA_PROCESSING_RETRY_DELAY_SECONDS,
maxRetries: self::MEDIA_PROCESSING_MAX_RETRIES,
);
}
private function processingState(mixed $processingInfo): ?MediaProcessingState
{
$state = data_get($processingInfo, 'state');
return is_string($state) ? MediaProcessingState::tryFrom($state) : null;
}
private function handleApiError(Response $response): never
{
throw XPublishException::fromApiResponse($response);
}
}