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\SocialAccount\Platform;
use App\Enums\YouTube\License;
use App\Enums\YouTube\PrivacyStatus;
use App\Enums\YouTube\ProcessingStatus;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\SocialPublishException;
use App\Exceptions\Social\YouTubePublishException;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Services\Social\Concerns\HostsProcessedImages;
use App\Support\YouTubeDescription;
use App\Support\YouTubeMetadata;
use Google\Client as GoogleClient;
use Google\Service\Exception;
use Google\Service\YouTube;
use Google\Service\YouTube\Video;
use Google\Service\YouTube\VideoSnippet;
use Google\Service\YouTube\VideoStatus;
use Google_Http_MediaFileUpload;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class YouTubePublisher
{
use HasSocialHttpClient;
use HostsProcessedImages;
private const CHUNK_SIZE = 10 * 1024 * 1024; // 10MB chunks
/** @var list<string> */
private const array COVER_MIME_TYPES = ['image/jpeg', 'image/png'];
/** thumbnails.set takes an image of up to 50 MB. */
private const int COVER_MAX_BYTES = 50 * 1024 * 1024;
public function publish(Post $post): array
{
$this->validateContentLength($post);
$metadataViolation = YouTubeMetadata::violation($post->meta);
if ($metadataViolation !== null) {
throw new YouTubePublishException(
userMessage: $metadataViolation[1],
category: ErrorCategory::ContentPolicy,
);
}
$content = app(ContentSanitizer::class)->forPost($post);
$description = $this->resolveDescription($post, $content);
$account = $post->socialAccount;
if ($account->needsProactiveTokenRefresh()) {
app(ConnectionVerifier::class)->refreshToken($account);
}
$media = $post->mediaItems;
if ($media->isEmpty()) {
throw new YouTubePublishException(
userMessage: 'YouTube Shorts requires a video to publish.',
category: ErrorCategory::MediaFormat,
);
}
$firstMedia = $media->first();
if (! $firstMedia->isVideo()) {
throw new YouTubePublishException(
userMessage: 'YouTube Shorts only supports video content.',
category: ErrorCategory::MediaFormat,
);
}
return $this->publishShort($firstMedia, $account, $content, $description, $post->meta ?? []);
}
/**
* Where YouTube is with a video it already has, or null when it no
* longer lists the video.
*
* @throws Exception
*/
public function processingStatus(Post $post): ?ProcessingStatus
{
$youtube = new YouTube($this->createGoogleClient($post->socialAccount));
$video = data_get($youtube->videos->listVideos('processingDetails', ['id' => $post->platform_post_id])->getItems(), 0);
return ProcessingStatus::tryFrom((string) $video?->getProcessingDetails()?->getProcessingStatus());
}
/**
* Sets the post's cover image (`media.0.meta.cover`) as the thumbnail of
* its video, which YouTube takes as a JPEG or a PNG. Call it once the
* video is processed: a Short may otherwise keep its own frame.
*
* @see https://developers.google.com/youtube/v3/docs/thumbnails/set
*
* @throws Exception
*/
public function setCover(Post $post): void
{
$cover = $post->mediaItems->first()?->cover();
if (blank($cover)) {
return;
}
$download = $this->downloadImage($cover->url) ?? throw new YouTubePublishException(
userMessage: 'Failed to download the cover image for YouTube',
category: ErrorCategory::ServerError,
);
try {
[$bytes, $mimeType] = $this->coverImage($cover, $download);
} finally {
File::delete($download);
}
$youtube = new YouTube($this->createGoogleClient($post->socialAccount));
$youtube->thumbnails->set($post->platform_post_id, [
'data' => $bytes,
'mimeType' => $mimeType,
'uploadType' => 'media',
]);
}
/**
* The downloaded cover as YouTube takes it: a JPEG or a PNG as is, any
* other image re-encoded as a JPEG.
*
* @return array{0: string, 1: string}
*/
private function coverImage(MediaItem $cover, string $path): array
{
if (in_array($cover->mime_type, self::COVER_MIME_TYPES, true)) {
return [File::get($path), (string) $cover->mime_type];
}
$converted = $this->jpegFrom($path, Platform::YouTube, self::COVER_MAX_BYTES);
try {
return [File::get($converted), 'image/jpeg'];
} finally {
File::delete($converted);
}
}
protected function cropFailureException(string $message): SocialPublishException
{
return new YouTubePublishException(
userMessage: $message,
category: ErrorCategory::MediaFormat,
);
}
private function createGoogleClient(SocialAccount $account): GoogleClient
{
$client = app(GoogleClient::class);
$client->setClientId(config('services.google.client_id'));
$client->setClientSecret(config('services.google.client_secret'));
$remainingSeconds = $account->token_expires_at
? max(0, (int) now()->diffInSeconds($account->token_expires_at, false))
: 3600;
$tokenData = [
'access_token' => $account->access_token,
'created' => time(),
'expires_in' => $remainingSeconds,
];
if ($account->refresh_token) {
$tokenData['refresh_token'] = $account->refresh_token;
}
$client->setAccessToken($tokenData);
return $client;
}
/**
* @param array<string, mixed> $meta
*/
private function publishShort(MediaItem $media, SocialAccount $account, ?string $content, string $description, array $meta): array
{
$missingTitle = YouTubeMetadata::missingTitleViolation($meta, (string) $content);
if ($missingTitle !== null) {
throw new YouTubePublishException(
userMessage: $missingTitle[1],
category: ErrorCategory::ContentPolicy,
);
}
$tempFile = tempnam(sys_get_temp_dir(), 'yt_upload_');
if ($tempFile === false) {
throw new YouTubePublishException(
userMessage: 'Failed to create temp file for YouTube upload',
category: ErrorCategory::ServerError,
);
}
try {
$this->downloadVideo($media, $tempFile);
$video = $this->uploadVideo($media, $account, $tempFile, $this->buildVideo($meta, (string) $content, $description), $this->insertParameters($meta));
$videoId = $video->getId();
return [
'id' => $videoId,
'url' => "https://www.youtube.com/shorts/{$videoId}",
];
} catch (Exception $e) {
throw YouTubePublishException::fromGoogleException($e);
} catch (PlatformUnavailableException $e) {
throw $e;
} catch (\Throwable $e) {
Log::error('YouTube upload failed', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw $e;
} finally {
@unlink($tempFile);
}
}
private function downloadVideo(MediaItem $media, string $path): void
{
$response = Http::withOptions(['sink' => $path])
->timeout(600)
->get($media->url);
if ($response->failed()) {
throw new YouTubePublishException(
userMessage: 'Failed to download video for YouTube upload: HTTP '.$response->status(),
category: ErrorCategory::ServerError,
);
}
}
/**
* @param array<string, bool> $insertParameters
*/
private function uploadVideo(MediaItem $media, SocialAccount $account, string $path, Video $video, array $insertParameters): Video
{
$fileSize = filesize($path);
if ($fileSize === false || $fileSize < 1024) {
throw new YouTubePublishException(
userMessage: 'Downloaded video is too small or empty ('.$fileSize.' bytes), aborting upload',
category: ErrorCategory::MediaFormat,
);
}
$client = $this->createGoogleClient($account);
$handle = fopen($path, 'r');
if ($handle === false) {
throw new YouTubePublishException(
userMessage: 'Failed to open temp file for YouTube upload',
category: ErrorCategory::ServerError,
);
}
try {
$client->setDefer(true);
$youtube = new YouTube($client);
$mediaUpload = new Google_Http_MediaFileUpload(
$client,
$youtube->videos->insert('snippet,status', $video, $insertParameters),
$media->mime_type ?: 'video/mp4',
null,
true,
self::CHUNK_SIZE
);
$mediaUpload->setFileSize($fileSize);
try {
$mediaUpload->getResumeUri();
} catch (Exception $e) {
throw YouTubePublishException::isServerError($e) ? $this->uploadUnavailable($e) : $e;
}
$uploadStatus = false;
while (! $uploadStatus && ! feof($handle)) {
$chunk = fread($handle, self::CHUNK_SIZE);
$isFinalChunk = ftell($handle) >= $fileSize;
try {
$uploadStatus = $mediaUpload->nextChunk($chunk);
} catch (Exception $e) {
throw ! $isFinalChunk && YouTubePublishException::isServerError($e) ? $this->uploadUnavailable($e) : $e;
}
}
if (! $uploadStatus instanceof Video) {
throw new YouTubePublishException(
userMessage: 'YouTube upload failed: no video object returned',
category: ErrorCategory::ServerError,
);
}
return $uploadStatus;
} finally {
fclose($handle);
$client->setDefer(false);
}
}
private function uploadUnavailable(Exception $e): PlatformUnavailableException
{
return new PlatformUnavailableException(
message: "YouTube returned {$e->getCode()} during upload",
httpStatus: $e->getCode() >= 500 ? $e->getCode() : null,
);
}
private function resolveDescription(Post $post, ?string $content): string
{
$description = YouTubeDescription::resolve($post->meta, $content);
$violation = YouTubeDescription::violation(data_get($post->meta, 'description'))
?? YouTubeDescription::violation($description);
if ($violation !== null) {
throw new YouTubePublishException(
userMessage: __($violation),
category: ErrorCategory::ContentPolicy,
);
}
return $description;
}
/**
* @param array<string, mixed> $meta
* @return array<string, bool>
*/
private function insertParameters(array $meta): array
{
return data_get($meta, 'notify_subscribers', true) ? [] : ['notifySubscribers' => false];
}
/**
* @param array<string, mixed> $meta
*/
private function buildVideo(array $meta, string $content, string $description): Video
{
$snippet = new VideoSnippet;
$snippet->setTitle(YouTubeMetadata::title($meta, $content));
$snippet->setDescription($description);
$snippet->setCategoryId(YouTubeMetadata::categoryId($meta));
$status = new VideoStatus;
$status->setPrivacyStatus((PrivacyStatus::tryFrom((string) data_get($meta, 'privacy_status')) ?? PrivacyStatus::DEFAULT)->value);
$status->setLicense((License::tryFrom((string) data_get($meta, 'license')) ?? License::DEFAULT)->value);
$status->setEmbeddable((bool) data_get($meta, 'embeddable', true));
$status->setSelfDeclaredMadeForKids((bool) data_get($meta, 'made_for_kids', false));
$status->setContainsSyntheticMedia((bool) data_get($meta, 'is_ai_generated', false));
$video = new Video;
$video->setSnippet($snippet);
$video->setStatus($status);
return $video;
}
}