Skip to content

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.

feat: add separate YouTube Shorts descriptions (#371)

Paulo Castellano284210152122
diff --git a/app/Actions/Post/UpdatePost.php b/app/Actions/Post/UpdatePost.php
index f3c87f625..f0cb1a415 100644
--- a/app/Actions/Post/UpdatePost.php
+++ b/app/Actions/Post/UpdatePost.php
@@ -12,6 +12,7 @@ use App\Jobs\PublishPost;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Models\Workspace;
+use App\Support\PostPlatformMetaRules;
use App\Support\PostStatusRules;
use App\Support\Social\AbandonGoogleBusinessReview;
use App\Support\Social\GoogleBusinessDerivativeCleaner;
@@ -74,7 +75,16 @@ class UpdatePost
->where('id', data_get($platformData, 'id'))
->update($updateData);
}
+ }
+
+ if (in_array($post->status, [PostStatus::Scheduled, PostStatus::Publishing], true)) {
+ PostPlatformMetaRules::assertStoredPostPublishable(
+ $post,
+ collect(data_get($data, 'platforms', []))->pluck('id')->all(),
+ );
+ }
+ if (Arr::has($data, 'platforms')) {
$post->postPlatforms()
->disabled()
->where('platform', Platform::GoogleBusiness)
diff --git a/app/Enums/SocialAccount/Platform.php b/app/Enums/SocialAccount/Platform.php
index c87258188..eb642fe33 100644
--- a/app/Enums/SocialAccount/Platform.php
+++ b/app/Enums/SocialAccount/Platform.php
@@ -164,10 +164,10 @@ enum Platform: string
* - LinkedIn UGC: 3000 (`commentary` field)
* - X standard tweet: 280 (X Premium accepts 25K — ignored, conservative)
* - TikTok caption: 2200
- * - YouTube Shorts: title=100, description=5000. We feed `content` to both
- * (publisher derives title from the first line via `buildTitle`), and
- * Shorts UX only shows ~100 chars before "more" — capping at 100 keeps
- * posts appropriate for the format.
+ * - YouTube Shorts: content supplies the title, capped at 100 characters
+ * (publisher derives it from the first line via `buildTitle`). Optional
+ * meta.description is separate plain text, capped at 5000 UTF-8 bytes;
+ * absent descriptions fall back to content.
* - Facebook text status: 10000 (API allows 63206; we cap below
* that — 63k-char posts are unrealistic and emoji-heavy content
* risks overflowing the TEXT column's 65535-byte ceiling)
diff --git a/app/Mcp/Tools/Post/CreatePostTool.php b/app/Mcp/Tools/Post/CreatePostTool.php
index 0de4bf31a..0183b2663 100644
--- a/app/Mcp/Tools/Post/CreatePostTool.php
+++ b/app/Mcp/Tools/Post/CreatePostTool.php
@@ -79,7 +79,7 @@ class CreatePostTool extends Tool
->items($schema->object(fn ($p) => [
'social_account_id' => $p->string()->required()->description('UUID of the connected social account.'),
'content_type' => $p->string()->required()->description('Format for this platform (e.g. linkedin_post, x_post, instagram_feed).'),
- 'meta' => $p->object()->description('Per-platform metadata. Instagram/Facebook: aspect_ratio (1:1|4:5|16:9|original). TikTok: privacy_level PUBLIC_TO_EVERYONE|MUTUAL_FOLLOW_FRIENDS|FOLLOWER_OF_CREATOR|SELF_ONLY (required to publish) + flags (allow_comments, allow_duet, allow_stitch, disclose, brand_content_toggle, brand_organic_toggle, is_aigc, auto_add_music). SELF_ONLY cannot be combined with brand_content_toggle. Pinterest: board_id (required to publish — call ListPinterestBoardsTool first), title (≤100), link (destination URL). Pin description comes from the post content. Discord: channel_id (required to publish — call ListDiscordChannelsTool first), mentions ([{token,label}]), embeds ([{title,description,url,image,color}]).'),
+ 'meta' => $p->object()->description('Per-platform metadata. Instagram/Facebook: aspect_ratio (1:1|4:5|16:9|original). TikTok: privacy_level PUBLIC_TO_EVERYONE|MUTUAL_FOLLOW_FRIENDS|FOLLOWER_OF_CREATOR|SELF_ONLY (required to publish) + flags (allow_comments, allow_duet, allow_stitch, disclose, brand_content_toggle, brand_organic_toggle, is_aigc, auto_add_music). SELF_ONLY cannot be combined with brand_content_toggle. Pinterest: board_id (required to publish — call ListPinterestBoardsTool first), title (≤100), link (destination URL). Pin description comes from the post content. Discord: channel_id (required to publish — call ListDiscordChannelsTool first), mentions ([{token,label}]), embeds ([{title,description,url,image,color}]). YouTube Shorts: description (optional plain text, at most 5000 bytes). Post content remains the title source, limited to 100 characters. Omit description or pass null to use the post content as description.'),
]))
->description('Platforms to publish on. Accounts not listed remain available but disabled.'),
];
diff --git a/app/Mcp/Tools/Post/UpdatePostTool.php b/app/Mcp/Tools/Post/UpdatePostTool.php
index a8b975a43..0b2af698e 100644
--- a/app/Mcp/Tools/Post/UpdatePostTool.php
+++ b/app/Mcp/Tools/Post/UpdatePostTool.php
@@ -119,7 +119,7 @@ class UpdatePostTool extends Tool
->items($schema->object(fn ($p) => [
'id' => $p->string()->required()->description('UUID of the post_platform row (from get-post-tool / list-posts-tool).'),
'content_type' => $p->string()->description('New content_type for this platform.'),
- 'meta' => $p->object()->description('Per-platform metadata override. Instagram/Facebook: aspect_ratio. TikTok: privacy_level PUBLIC_TO_EVERYONE|MUTUAL_FOLLOW_FRIENDS|FOLLOWER_OF_CREATOR|SELF_ONLY (required to publish) + flags. SELF_ONLY cannot be combined with brand_content_toggle. Pinterest: board_id (required to publish — call ListPinterestBoardsTool first), title (≤100), link (destination URL). Pin description comes from the post content. Discord: channel_id (required to publish — call ListDiscordChannelsTool first), mentions, embeds. Merged with existing meta.'),
+ 'meta' => $p->object()->description('Per-platform metadata override. Instagram/Facebook: aspect_ratio. TikTok: privacy_level PUBLIC_TO_EVERYONE|MUTUAL_FOLLOW_FRIENDS|FOLLOWER_OF_CREATOR|SELF_ONLY (required to publish) + flags. SELF_ONLY cannot be combined with brand_content_toggle. Pinterest: board_id (required to publish — call ListPinterestBoardsTool first), title (≤100), link (destination URL). Pin description comes from the post content. Discord: channel_id (required to publish — call ListDiscordChannelsTool first), mentions, embeds. Merged with existing meta. YouTube Shorts: description (optional plain text, at most 5000 bytes). Post content remains the title source, limited to 100 characters. Omit description to keep the current override; pass null to remove it and use the post content as description.'),
]))
->description('Platforms to enable for publishing. Any platform NOT listed will be disabled. Pass an empty array to disable all.'),
];
diff --git a/app/Rules/ValidYouTubeDescription.php b/app/Rules/ValidYouTubeDescription.php
new file mode 100644
index 000000000..70bb5ab8c
--- /dev/null
+++ b/app/Rules/ValidYouTubeDescription.php
@@ -0,0 +1,25 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Rules;
+
+use App\Support\YouTubeDescription;
+use Closure;
+use Illuminate\Contracts\Validation\ValidationRule;
+use Illuminate\Translation\PotentiallyTranslatedString;
+
+class ValidYouTubeDescription implements ValidationRule
+{
+ /**
+ * @param Closure(string, ?string=): PotentiallyTranslatedString $fail
+ */
+ public function validate(string $attribute, mixed $value, Closure $fail): void
+ {
+ $key = YouTubeDescription::violation($value);
+
+ if ($key !== null) {
+ $fail($key)->translate();
+ }
+ }
+}
diff --git a/app/Services/Post/PostPreviewer.php b/app/Services/Post/PostPreviewer.php
index ca8343ea2..575b8de8e 100644
--- a/app/Services/Post/PostPreviewer.php
+++ b/app/Services/Post/PostPreviewer.php
@@ -4,9 +4,11 @@ declare(strict_types=1);
namespace App\Services\Post;
+use App\Enums\SocialAccount\Platform;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Services\Social\ContentSanitizer;
+use App\Support\YouTubeDescription;
use Illuminate\Support\Collection;
/**
@@ -31,7 +33,9 @@ class PostPreviewer
* sanitized_content: string,
* sanitized_length: int,
* max_content_length: int,
- * truncated: bool
+ * truncated: bool,
+ * description?: string,
+ * description_length_bytes?: int
* }>
* }
*/
@@ -59,7 +63,7 @@ class PostPreviewer
$platform = $pp->socialAccount?->platform ?? $pp->platform;
$sanitized = $this->sanitizer->sanitize($original, $platform);
- return [
+ $preview = [
'post_platform_id' => $pp->id,
'platform' => $platform->value,
'content_type' => $pp->content_type?->value,
@@ -68,6 +72,14 @@ class PostPreviewer
'max_content_length' => $platform->maxContentLength(),
'truncated' => mb_strlen($sanitized) < mb_strlen($original),
];
+
+ if ($platform === Platform::YouTube) {
+ $description = YouTubeDescription::resolve($pp->meta, $sanitized);
+ $preview['description'] = $description;
+ $preview['description_length_bytes'] = strlen($description);
+ }
+
+ return $preview;
});
}
}
diff --git a/app/Services/Social/YouTubePublisher.php b/app/Services/Social/YouTubePublisher.php
index a12b60a36..94d110891 100644
--- a/app/Services/Social/YouTubePublisher.php
+++ b/app/Services/Social/YouTubePublisher.php
@@ -4,11 +4,13 @@ declare(strict_types=1);
namespace App\Services\Social;
+use App\Dto\MediaItem;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\YouTubePublishException;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Services\Social\Concerns\HasSocialHttpClient;
+use App\Support\YouTubeDescription;
use Google\Client as GoogleClient;
use Google\Service\Exception;
use Google\Service\YouTube;
@@ -29,7 +31,10 @@ class YouTubePublisher
{
$this->validateContentLength($postPlatform);
- $content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null;
+ $content = $postPlatform->post->content
+ ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform)
+ : null;
+ $description = $this->resolveDescription($postPlatform, $content);
$account = $postPlatform->socialAccount;
@@ -55,12 +60,12 @@ class YouTubePublisher
);
}
- return $this->publishShort($postPlatform, $firstMedia, $account, $content);
+ return $this->publishShort($firstMedia, $account, $content, $description);
}
private function createGoogleClient(SocialAccount $account): GoogleClient
{
- $client = new GoogleClient;
+ $client = app(GoogleClient::class);
$client->setClientId(config('services.google.client_id'));
$client->setClientSecret(config('services.google.client_secret'));
@@ -83,7 +88,7 @@ class YouTubePublisher
return $client;
}
- private function publishShort(PostPlatform $postPlatform, $media, SocialAccount $account, ?string $content): array
+ private function publishShort(MediaItem $media, SocialAccount $account, ?string $content, string $description): array
{
if (empty($content)) {
throw new YouTubePublishException(
@@ -92,60 +97,79 @@ class YouTubePublisher
);
}
- $title = $this->buildTitle($content);
- $description = $content;
-
$tempFile = tempnam(sys_get_temp_dir(), 'yt_upload_');
- $handle = null;
- try {
- // Download video to temp file (memory-safe)
- $downloadResponse = Http::withOptions(['sink' => $tempFile])
- ->timeout(600)
- ->get($media->url);
+ if ($tempFile === false) {
+ throw new YouTubePublishException(
+ userMessage: 'Failed to create temp file for YouTube upload',
+ category: ErrorCategory::ServerError,
+ );
+ }
- if ($downloadResponse->failed()) {
- throw new YouTubePublishException(
- userMessage: 'Failed to download video for YouTube upload: HTTP '.$downloadResponse->status(),
- category: ErrorCategory::ServerError,
- );
- }
+ try {
+ $this->downloadVideo($media, $tempFile);
+ $video = $this->uploadVideo($media, $account, $tempFile, $this->buildVideo($content, $description));
+ $videoId = $video->getId();
- $fileSize = filesize($tempFile);
+ return [
+ 'id' => $videoId,
+ 'url' => "https://www.youtube.com/shorts/{$videoId}",
+ ];
+ } catch (Exception $e) {
+ throw YouTubePublishException::fromGoogleException($e);
+ } catch (\Throwable $e) {
+ Log::error('YouTube upload failed', [
+ 'error' => $e->getMessage(),
+ 'trace' => $e->getTraceAsString(),
+ ]);
- if ($fileSize === false || $fileSize < 1024) {
- throw new YouTubePublishException(
- userMessage: 'Downloaded video is too small or empty ('.$fileSize.' bytes), aborting upload',
- category: ErrorCategory::MediaFormat,
- );
- }
+ throw $e;
+ } finally {
+ @unlink($tempFile);
+ }
+ }
- // Set up Google Client with deferred mode for resumable upload
- $client = $this->createGoogleClient($account);
- $client->setDefer(true);
+ private function downloadVideo(MediaItem $media, string $path): void
+ {
+ $response = Http::withOptions(['sink' => $path])
+ ->timeout(600)
+ ->get($media->url);
- $youtube = new YouTube($client);
+ if ($response->failed()) {
+ throw new YouTubePublishException(
+ userMessage: 'Failed to download video for YouTube upload: HTTP '.$response->status(),
+ category: ErrorCategory::ServerError,
+ );
+ }
+ }
- // Build video metadata
- $snippet = new VideoSnippet;
- $snippet->setTitle($title);
- $snippet->setDescription($description);
- $snippet->setCategoryId('22');
+ private function uploadVideo(MediaItem $media, SocialAccount $account, string $path, Video $video): Video
+ {
+ $fileSize = filesize($path);
- $status = new VideoStatus;
- $status->setPrivacyStatus('public');
- $status->setSelfDeclaredMadeForKids(false);
+ if ($fileSize === false || $fileSize < 1024) {
+ throw new YouTubePublishException(
+ userMessage: 'Downloaded video is too small or empty ('.$fileSize.' bytes), aborting upload',
+ category: ErrorCategory::MediaFormat,
+ );
+ }
- $video = new Video;
- $video->setSnippet($snippet);
- $video->setStatus($status);
+ $client = $this->createGoogleClient($account);
+ $handle = fopen($path, 'r');
- // Initialize resumable upload request
- $insertRequest = $youtube->videos->insert('snippet,status', $video);
+ 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,
- $insertRequest,
+ $youtube->videos->insert('snippet,status', $video),
$media->mime_type ?: 'video/mp4',
null,
true,
@@ -153,27 +177,13 @@ class YouTubePublisher
);
$mediaUpload->setFileSize($fileSize);
- // Upload in chunks (memory-safe for large files)
$uploadStatus = false;
- $handle = fopen($tempFile, 'r');
-
- if ($handle === false) {
- throw new YouTubePublishException(
- userMessage: 'Failed to open temp file for YouTube upload',
- category: ErrorCategory::ServerError,
- );
- }
while (! $uploadStatus && ! feof($handle)) {
$chunk = fread($handle, self::CHUNK_SIZE);
$uploadStatus = $mediaUpload->nextChunk($chunk);
}
- fclose($handle);
- $handle = null;
-
- $client->setDefer(false);
-
if (! $uploadStatus instanceof Video) {
throw new YouTubePublishException(
userMessage: 'YouTube upload failed: no video object returned',
@@ -181,28 +191,45 @@ class YouTubePublisher
);
}
- $videoId = $uploadStatus->getId();
-
- return [
- 'id' => $videoId,
- 'url' => "https://www.youtube.com/shorts/{$videoId}",
- ];
- } catch (Exception $e) {
- $this->handleGoogleError($e);
- } catch (\Throwable $e) {
- Log::error('YouTube upload failed', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
-
- throw $e;
+ return $uploadStatus;
} finally {
- if ($handle !== null && is_resource($handle)) {
- fclose($handle);
- }
+ fclose($handle);
+ $client->setDefer(false);
+ }
+ }
- @unlink($tempFile);
+ private function resolveDescription(PostPlatform $postPlatform, ?string $content): string
+ {
+ $description = YouTubeDescription::resolve($postPlatform->meta, $content);
+ $violation = YouTubeDescription::violation(data_get($postPlatform->meta, 'description'))
+ ?? YouTubeDescription::violation($description);
+
+ if ($violation !== null) {
+ throw new YouTubePublishException(
+ userMessage: __($violation),
+ category: ErrorCategory::ContentPolicy,
+ );
}
+
+ return $description;
+ }
+
+ private function buildVideo(string $content, string $description): Video
+ {
+ $snippet = new VideoSnippet;
+ $snippet->setTitle($this->buildTitle($content));
+ $snippet->setDescription($description);
+ $snippet->setCategoryId('22');
+
+ $status = new VideoStatus;
+ $status->setPrivacyStatus('public');
+ $status->setSelfDeclaredMadeForKids(false);
+
+ $video = new Video;
+ $video->setSnippet($snippet);
+ $video->setStatus($status);
+
+ return $video;
}
private function buildTitle(string $content): string
@@ -220,9 +247,4 @@ class YouTubePublisher
return $title.$shortsTag;
}
-
- private function handleGoogleError(Exception $e): never
- {
- throw YouTubePublishException::fromGoogleException($e);
- }
}
diff --git a/app/Support/PostPlatformMetaRules.php b/app/Support/PostPlatformMetaRules.php
index c904ee952..f7608db84 100644
--- a/app/Support/PostPlatformMetaRules.php
+++ b/app/Support/PostPlatformMetaRules.php
@@ -10,6 +10,8 @@ use App\Enums\PostPlatform\AspectRatio;
use App\Enums\SocialAccount\Platform;
use App\Enums\TikTok\PrivacyLevel;
use App\Models\Post;
+use App\Models\PostPlatform;
+use App\Rules\ValidYouTubeDescription;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
@@ -56,6 +58,9 @@ class PostPlatformMetaRules
'platforms.*.meta.title' => ['sometimes', 'nullable', 'string', 'max:100'],
'platforms.*.meta.link' => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
+ // YouTube
+ 'platforms.*.meta.description' => ['sometimes', 'nullable', 'string', new ValidYouTubeDescription],
+
// Discord
'platforms.*.meta.channel_id' => ['sometimes', 'nullable', 'string'],
'platforms.*.meta.channel_name' => ['sometimes', 'nullable', 'string'],
@@ -112,6 +117,7 @@ class PostPlatformMetaRules
{
return [
'platforms.*.meta.title' => __('posts.form.pinterest.title'),
+ 'platforms.*.meta.description' => __('posts.form.youtube.description'),
'platforms.*.meta.link' => __('posts.form.pinterest.link'),
'platforms.*.meta.event.title' => __('posts.form.google_business.event_title'),
'platforms.*.meta.call_to_action.url' => __('posts.form.google_business.cta_url'),
@@ -135,7 +141,11 @@ class PostPlatformMetaRules
if ($violation !== null) {
[$field, $message] = $violation;
- $validator->errors()->add("platforms.{$index}.meta.{$field}", $message);
+ $key = "platforms.{$index}.meta.{$field}";
+
+ if (! $validator->errors()->has($key)) {
+ $validator->errors()->add($key, $message);
+ }
}
}
}
@@ -146,13 +156,24 @@ class PostPlatformMetaRules
* without resubmitting platforms (e.g. the MCP publish tool), so a misconfigured
* post fails fast with a clear message instead of only at publish time.
*
+ * @param array<int, string> $platformIds Submitted order for indexed errors.
+ *
* @throws ValidationException
*/
- public static function assertStoredPostPublishable(Post $post): void
+ public static function assertStoredPostPublishable(Post $post, array $platformIds = []): void
{
+ $platforms = $post->postPlatforms()->enabled()->get()->values();
+
+ if ($platformIds !== []) {
+ $platformsById = $platforms->keyBy('id');
+ $platforms = collect($platformIds)
+ ->map(fn (string $id): ?PostPlatform => $platformsById->get($id))
+ ->filter();
+ }
+
$errors = [];
- foreach ($post->postPlatforms()->enabled()->get()->values() as $index => $postPlatform) {
+ foreach ($platforms as $index => $postPlatform) {
$violation = self::requiredMetaViolation($postPlatform->platform, $postPlatform->meta);
if ($violation !== null) {
@@ -179,6 +200,7 @@ class PostPlatformMetaRules
$needsGoogleBusinessEvent = $platform === Platform::GoogleBusiness && $topicType->requiresEvent();
return match (true) {
+ $platform === Platform::YouTube => self::youtubeDescriptionViolation($meta),
$platform === Platform::TikTok => self::tiktokPrivacyViolation($meta),
$platform === Platform::Pinterest && blank(data_get($meta, 'board_id')) => ['board_id', trans('posts.form.pinterest.board_required')],
$platform === Platform::Discord && blank(data_get($meta, 'channel_id')) => ['channel_id', trans('posts.form.discord.channel_required')],
@@ -208,6 +230,16 @@ class PostPlatformMetaRules
};
}
+ /**
+ * @return array{0: string, 1: string}|null
+ */
+ private static function youtubeDescriptionViolation(mixed $meta): ?array
+ {
+ $key = YouTubeDescription::violation(data_get($meta, 'description'));
+
+ return $key === null ? null : ['description', __($key)];
+ }
+
/**
* Event/offer titles over TITLE_MAX_LENGTH fail publish even when stored
* outside rules() — MCP PublishPostTool only runs requiredMetaViolation().
diff --git a/app/Support/YouTubeDescription.php b/app/Support/YouTubeDescription.php
new file mode 100644
index 000000000..f9d542b98
--- /dev/null
+++ b/app/Support/YouTubeDescription.php
@@ -0,0 +1,38 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Support;
+
+use Illuminate\Support\Str;
+
+class YouTubeDescription
+{
+ public const int MAX_BYTES = 5000;
+
+ public static function violation(mixed $description): ?string
+ {
+ if ($description === null) {
+ return null;
+ }
+
+ return match (true) {
+ ! is_string($description),
+ ! mb_check_encoding($description, 'UTF-8') => 'posts.form.youtube.description_invalid',
+ strlen($description) > self::MAX_BYTES => 'posts.form.youtube.description_max',
+ default => null,
+ };
+ }
+
+ /**
+ * @param array<string, mixed>|null $meta
+ */
+ public static function resolve(?array $meta, ?string $content): string
+ {
+ $description = data_get($meta, 'description');
+
+ return is_string($description) && filled(Str::trim($description))
+ ? $description
+ : ($content ?? '');
+ }
+}
diff --git a/lang/ar/posts.php b/lang/ar/posts.php
index 5bd4cb358..1005d7b03 100644
--- a/lang/ar/posts.php
+++ b/lang/ar/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'عنوان المستند',
'document_title_placeholder' => 'يظهر على منشور مستند PDF الخاص بك',
],
+ 'youtube' => [
+ 'settings' => 'إعدادات YouTube',
+ 'posting_to' => 'النشر على',
+ 'description' => 'الوصف',
+ 'description_placeholder' => 'وصف الفيديو',
+ 'description_max' => 'يجب ألا يتجاوز وصف YouTube ‏5000 بايت.',
+ 'description_invalid' => 'يجب أن يكون وصف YouTube نصًا صالحًا.',
+ 'description_bytes' => ':used / :limit بايت',
+ ],
'pinterest' => [
'settings' => 'إعدادات Pinterest',
'posting_to' => 'النشر إلى',
diff --git a/lang/de/posts.php b/lang/de/posts.php
index f8ab34c30..0bd362f66 100644
--- a/lang/de/posts.php
+++ b/lang/de/posts.php
@@ -144,6 +144,15 @@ return [
'document_title' => 'Dokumenttitel',
'document_title_placeholder' => 'Wird bei deinem PDF-Dokument-Beitrag angezeigt',
],
+ 'youtube' => [
+ 'settings' => 'YouTube-Einstellungen',
+ 'posting_to' => 'Veröffentlichen auf',
+ 'description' => 'Beschreibung',
+ 'description_placeholder' => 'Videobeschreibung',
+ 'description_max' => 'Die YouTube-Beschreibung darf 5.000 Bytes nicht überschreiten.',
+ 'description_invalid' => 'Die YouTube-Beschreibung muss gültiger Text sein.',
+ 'description_bytes' => ':used / :limit Bytes',
+ ],
'pinterest' => [
'settings' => 'Pinterest-Einstellungen',
'posting_to' => 'Veröffentlichen auf',
diff --git a/lang/el/posts.php b/lang/el/posts.php
index 4da982a4f..6d8516056 100644
--- a/lang/el/posts.php
+++ b/lang/el/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'Τίτλος εγγράφου',
'document_title_placeholder' => 'Εμφανίζεται στη δημοσίευση εγγράφου PDF σας',
],
+ 'youtube' => [
+ 'settings' => 'Ρυθμίσεις YouTube',
+ 'posting_to' => 'Δημοσίευση σε',
+ 'description' => 'Περιγραφή',
+ 'description_placeholder' => 'Περιγραφή βίντεο',
+ 'description_max' => 'Η περιγραφή YouTube δεν πρέπει να υπερβαίνει τα 5.000 byte.',
+ 'description_invalid' => 'Η περιγραφή YouTube πρέπει να είναι έγκυρο κείμενο.',
+ 'description_bytes' => ':used / :limit byte',
+ ],
'pinterest' => [
'settings' => 'Ρυθμίσεις Pinterest',
'posting_to' => 'Δημοσίευση σε',
diff --git a/lang/en/posts.php b/lang/en/posts.php
index 12a91b91d..c97d9ca3e 100644
--- a/lang/en/posts.php
+++ b/lang/en/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'Document title',
'document_title_placeholder' => 'Shown on your PDF document post',
],
+ 'youtube' => [
+ 'settings' => 'YouTube settings',
+ 'posting_to' => 'Posting to',
+ 'description' => 'Description',
+ 'description_placeholder' => 'Video description',
+ 'description_max' => 'The YouTube description must not exceed 5,000 bytes.',
+ 'description_invalid' => 'The YouTube description must be valid text.',
+ 'description_bytes' => ':used / :limit bytes',
+ ],
'pinterest' => [
'settings' => 'Pinterest Settings',
'posting_to' => 'Posting to',
diff --git a/lang/es/posts.php b/lang/es/posts.php
index ce9c2e387..b0f6ffd60 100644
--- a/lang/es/posts.php
+++ b/lang/es/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'Título del documento',
'document_title_placeholder' => 'Se muestra en tu publicación de documento PDF',
],
+ 'youtube' => [
+ 'settings' => 'Configuración de YouTube',
+ 'posting_to' => 'Publicando en',
+ 'description' => 'Descripción',
+ 'description_placeholder' => 'Descripción del vídeo',
+ 'description_max' => 'La descripción de YouTube no puede superar los 5.000 bytes.',
+ 'description_invalid' => 'La descripción de YouTube debe ser texto válido.',
+ 'description_bytes' => ':used / :limit bytes',
+ ],
'pinterest' => [
'settings' => 'Configuración de Pinterest',
'posting_to' => 'Publicando en',
diff --git a/lang/fr/posts.php b/lang/fr/posts.php
index 59b72e357..4cb63393d 100644
--- a/lang/fr/posts.php
+++ b/lang/fr/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'Titre du document',
'document_title_placeholder' => 'Affiché sur votre publication de document PDF',
],
+ 'youtube' => [
+ 'settings' => 'Paramètres YouTube',
+ 'posting_to' => 'Publication sur',
+ 'description' => 'Description',
+ 'description_placeholder' => 'Description de la vidéo',
+ 'description_max' => 'La description YouTube ne doit pas dépasser 5 000 octets.',
+ 'description_invalid' => 'La description YouTube doit être un texte valide.',
+ 'description_bytes' => ':used / :limit octets',
+ ],
'pinterest' => [
'settings' => 'Paramètres Pinterest',
'posting_to' => 'Publier sur',
diff --git a/lang/it/posts.php b/lang/it/posts.php
index c03e75e11..3f3aa3316 100644
--- a/lang/it/posts.php
+++ b/lang/it/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'Titolo del documento',
'document_title_placeholder' => 'Mostrato sul tuo post con documento PDF',
],
+ 'youtube' => [
+ 'settings' => 'Impostazioni YouTube',
+ 'posting_to' => 'Pubblicazione su',
+ 'description' => 'Descrizione',
+ 'description_placeholder' => 'Descrizione del video',
+ 'description_max' => 'La descrizione YouTube non deve superare 5.000 byte.',
+ 'description_invalid' => 'La descrizione YouTube deve essere testo valido.',
+ 'description_bytes' => ':used / :limit byte',
+ ],
'pinterest' => [
'settings' => 'Impostazioni Pinterest',
'posting_to' => 'Pubblicazione su',
diff --git a/lang/ja/posts.php b/lang/ja/posts.php
index e066e8686..c2a011a02 100644
--- a/lang/ja/posts.php
+++ b/lang/ja/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'ドキュメントタイトル',
'document_title_placeholder' => 'PDF ドキュメント投稿に表示されます',
],
+ 'youtube' => [
+ 'settings' => 'YouTube設定',
+ 'posting_to' => '投稿先',
+ 'description' => '説明',
+ 'description_placeholder' => '動画の説明',
+ 'description_max' => 'YouTubeの説明は5,000バイト以内にしてください。',
+ 'description_invalid' => 'YouTubeの説明には有効なテキストを入力してください。',
+ 'description_bytes' => ':used / :limit バイト',
+ ],
'pinterest' => [
'settings' => 'Pinterest 設定',
'posting_to' => '投稿先',
diff --git a/lang/ko/posts.php b/lang/ko/posts.php
index 13bfc4421..bf42e246a 100644
--- a/lang/ko/posts.php
+++ b/lang/ko/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => '문서 제목',
'document_title_placeholder' => 'PDF 문서 게시물에 표시됩니다',
],
+ 'youtube' => [
+ 'settings' => 'YouTube 설정',
+ 'posting_to' => '게시 대상',
+ 'description' => '설명',
+ 'description_placeholder' => '동영상 설명',
+ 'description_max' => 'YouTube 설명은 5,000바이트를 초과할 수 없습니다.',
+ 'description_invalid' => 'YouTube 설명은 유효한 텍스트여야 합니다.',
+ 'description_bytes' => ':used / :limit 바이트',
+ ],
'pinterest' => [
'settings' => 'Pinterest 설정',
'posting_to' => '게시 대상',
diff --git a/lang/nl/posts.php b/lang/nl/posts.php
index 3338a4118..da32a0986 100644
--- a/lang/nl/posts.php
+++ b/lang/nl/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'Documenttitel',
'document_title_placeholder' => 'Getoond op je PDF-documentpost',
],
+ 'youtube' => [
+ 'settings' => 'YouTube-instellingen',
+ 'posting_to' => 'Publiceren op',
+ 'description' => 'Beschrijving',
+ 'description_placeholder' => 'Videobeschrijving',
+ 'description_max' => 'De YouTube-beschrijving mag niet langer zijn dan 5.000 bytes.',
+ 'description_invalid' => 'De YouTube-beschrijving moet geldige tekst zijn.',
+ 'description_bytes' => ':used / :limit bytes',
+ ],
'pinterest' => [
'settings' => 'Pinterest-instellingen',
'posting_to' => 'Posten naar',
diff --git a/lang/pl/posts.php b/lang/pl/posts.php
index 8deb478fd..3393ecca7 100644
--- a/lang/pl/posts.php
+++ b/lang/pl/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'Tytuł dokumentu',
'document_title_placeholder' => 'Wyświetlany w Twoim poście z dokumentem PDF',
],
+ 'youtube' => [
+ 'settings' => 'Ustawienia YouTube',
+ 'posting_to' => 'Publikowanie na',
+ 'description' => 'Opis',
+ 'description_placeholder' => 'Opis filmu',
+ 'description_max' => 'Opis YouTube nie może przekraczać 5000 bajtów.',
+ 'description_invalid' => 'Opis YouTube musi być poprawnym tekstem.',
+ 'description_bytes' => ':used / :limit bajtów',
+ ],
'pinterest' => [
'settings' => 'Ustawienia Pinterest',
'posting_to' => 'Publikowanie na',
diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.php
index c6d04ee18..5cb562e66 100644
--- a/lang/pt-BR/posts.php
+++ b/lang/pt-BR/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'Título do documento',
'document_title_placeholder' => 'Aparece no seu post de documento PDF',
],
+ 'youtube' => [
+ 'settings' => 'Configurações do YouTube',
+ 'posting_to' => 'Publicando em',
+ 'description' => 'Descrição',
+ 'description_placeholder' => 'Descrição do vídeo',
+ 'description_max' => 'A descrição do YouTube não pode ultrapassar 5.000 bytes.',
+ 'description_invalid' => 'A descrição do YouTube deve ser um texto válido.',
+ 'description_bytes' => ':used / :limit bytes',
+ ],
'pinterest' => [
'settings' => 'Configurações do Pinterest',
'posting_to' => 'Publicando em',
diff --git a/lang/ru/posts.php b/lang/ru/posts.php
index 4d557f7f4..b64e8164b 100644
--- a/lang/ru/posts.php
+++ b/lang/ru/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'Название документа',
'document_title_placeholder' => 'Отображается в вашем посте с PDF-документом',
],
+ 'youtube' => [
+ 'settings' => 'Настройки YouTube',
+ 'posting_to' => 'Публикация в',
+ 'description' => 'Описание',
+ 'description_placeholder' => 'Описание видео',
+ 'description_max' => 'Описание YouTube не должно превышать 5000 байт.',
+ 'description_invalid' => 'Описание YouTube должно быть корректным текстом.',
+ 'description_bytes' => ':used / :limit байт',
+ ],
'pinterest' => [
'settings' => 'Настройки Pinterest',
'posting_to' => 'Публикация в',
diff --git a/lang/tr/posts.php b/lang/tr/posts.php
index b47e9c531..52f68be2d 100644
--- a/lang/tr/posts.php
+++ b/lang/tr/posts.php
@@ -144,6 +144,15 @@ return [
'document_title' => 'Belge başlığı',
'document_title_placeholder' => 'PDF belge gönderinizde gösterilir',
],
+ 'youtube' => [
+ 'settings' => 'YouTube ayarları',
+ 'posting_to' => 'Yayınlanacak hesap',
+ 'description' => 'Açıklama',
+ 'description_placeholder' => 'Video açıklaması',
+ 'description_max' => 'YouTube açıklaması 5.000 baytı aşmamalıdır.',
+ 'description_invalid' => 'YouTube açıklaması geçerli bir metin olmalıdır.',
+ 'description_bytes' => ':used / :limit bayt',
+ ],
'pinterest' => [
'settings' => 'Pinterest Ayarları',
'posting_to' => 'Şuraya paylaşılıyor',
diff --git a/lang/uk/posts.php b/lang/uk/posts.php
index 5fc6a6cd2..293a047a7 100644
--- a/lang/uk/posts.php
+++ b/lang/uk/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => 'Назва документа',
'document_title_placeholder' => 'Відображається у вашому пості з PDF-документом',
],
+ 'youtube' => [
+ 'settings' => 'Налаштування YouTube',
+ 'posting_to' => 'Публікація в',
+ 'description' => 'Опис',
+ 'description_placeholder' => 'Опис відео',
+ 'description_max' => 'Опис YouTube не повинен перевищувати 5000 байтів.',
+ 'description_invalid' => 'Опис YouTube має бути коректним текстом.',
+ 'description_bytes' => ':used / :limit байтів',
+ ],
'pinterest' => [
'settings' => 'Налаштування Pinterest',
'posting_to' => 'Публікація в',
diff --git a/lang/zh/posts.php b/lang/zh/posts.php
index 271cfeff9..f42ea1bcb 100644
--- a/lang/zh/posts.php
+++ b/lang/zh/posts.php
@@ -142,6 +142,15 @@ return [
'document_title' => '文档标题',
'document_title_placeholder' => '显示在你的 PDF 文档帖子上',
],
+ 'youtube' => [
+ 'settings' => 'YouTube 设置',
+ 'posting_to' => '发布到',
+ 'description' => '描述',
+ 'description_placeholder' => '视频描述',
+ 'description_max' => 'YouTube 描述不得超过 5,000 个字节。',
+ 'description_invalid' => 'YouTube 描述必须是有效文本。',
+ 'description_bytes' => ':used / :limit 字节',
+ ],
'pinterest' => [
'settings' => 'Pinterest 设置',
'posting_to' => '发布到',
diff --git a/resources/js/components/ChannelConfigurator.vue b/resources/js/components/ChannelConfigurator.vue
index 69134079a..1c8706b4f 100644
--- a/resources/js/components/ChannelConfigurator.vue
+++ b/resources/js/components/ChannelConfigurator.vue
@@ -9,6 +9,7 @@ import InstagramSettings from '@/components/posts/editor/InstagramSettings.vue';
import LinkedInSettings from '@/components/posts/editor/LinkedInSettings.vue';
import PinterestSettings from '@/components/posts/editor/PinterestSettings.vue';
import TikTokSettings from '@/components/posts/editor/TikTokSettings.vue';
+import YouTubeSettings from '@/components/posts/editor/YouTubeSettings.vue';
import { Avatar } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
@@ -24,12 +25,10 @@ const props = withDefaults(defineProps<{
media?: MediaItem[];
videoDurationSec?: number | null;
disabled?: boolean;
- previewOnly?: boolean;
}>(), {
media: () => [],
videoDurationSec: null,
disabled: false,
- previewOnly: false,
});
const emit = defineEmits<{
@@ -172,13 +171,17 @@ const settingsProps = (channel: Channel) => ({
:platform="channel.platform"
:media="media"
/>
+ <YouTubeSettings
+ v-else-if="channel.platform === Platform.YouTube"
+ v-bind="settingsProps(channel)"
+ :platform-index="index"
+ />
<GoogleBusinessSettings
v-else-if="channel.platform === Platform.GoogleBusiness"
:social-account="channel.socialAccount"
:platform-index="index"
:meta="channel.meta"
:disabled="disabled"
- :preview-only="previewOnly"
@update:meta="emit('update:meta', channel.id, $event)"
/>
<DiscordSettings v-else-if="channel.platform === Platform.Discord" v-bind="settingsProps(channel)" />
diff --git a/resources/js/components/posts/editor/GoogleBusinessSettings.vue b/resources/js/components/posts/editor/GoogleBusinessSettings.vue
index 5cc1f7099..2b2c3a83f 100644
--- a/resources/js/components/posts/editor/GoogleBusinessSettings.vue
+++ b/resources/js/components/posts/editor/GoogleBusinessSettings.vue
@@ -30,6 +30,7 @@ import {
type GoogleBusinessCtaActionValue,
type GoogleBusinessTopicTypeValue,
} from '@/lib/googleBusiness';
+import { toNullableText } from '@/lib/utils';
interface SocialAccount {
id: string;
@@ -46,12 +47,10 @@ interface Props {
platformIndex: number;
meta: Record<string, any>;
disabled?: boolean;
- previewOnly?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
disabled: false,
- previewOnly: false,
});
const emit = defineEmits<{
@@ -59,7 +58,6 @@ const emit = defineEmits<{
}>();
const open = ref(false);
-const isLocked = computed(() => props.disabled || props.previewOnly);
const updateMeta = (patch: Record<string, any>) => {
emit('update:meta', { ...props.meta, ...patch });
@@ -104,13 +102,13 @@ const showEventFields = computed(() => GOOGLE_BUSINESS_EVENT_TOPIC_TYPES.include
const ctaUrl = computed<string>({
get: () => props.meta?.call_to_action?.url || '',
set: (value: string) => updateMeta({
- call_to_action: { ...props.meta?.call_to_action, url: value.trim() === '' ? null : value },
+ call_to_action: { ...props.meta?.call_to_action, url: toNullableText(value) },
}),
});
const eventTitle = computed<string>({
get: () => props.meta?.event?.title || '',
- set: (value: string) => updateEvent({ title: value.trim() === '' ? null : value }),
+ set: (value: string) => updateEvent({ title: toNullableText(value) }),
});
const eventDateTime = (dateKey: 'start_date' | 'end_date', timeKey: 'start_time' | 'end_time') => computed({
@@ -135,7 +133,7 @@ const eventTitlePlaceholderKey = computed(() => topicType.value === GoogleBusine
const offerField = (key: 'coupon_code' | 'redeem_online_url' | 'terms_conditions') => computed<string>({
get: () => props.meta?.offer?.[key] || '',
set: (value: string) => updateMeta({
- offer: { ...props.meta?.offer, [key]: value.trim() === '' ? null : value },
+ offer: { ...props.meta?.offer, [key]: toNullableText(value) },
}),
});
@@ -201,7 +199,7 @@ const ctaUrlError = findError('call_to_action.url');
:class="topicType === type.value
? 'border-foreground bg-violet-100 text-foreground shadow-2xs'
: 'border-foreground/30 text-foreground/70 hover:border-foreground hover:text-foreground'"
- :disabled="isLocked"
+ :disabled="disabled"
:data-testid="`google-business-topic-${type.value}`"
@click="topicType = type.value"
>
@@ -213,7 +211,7 @@ const ctaUrlError = findError('call_to_action.url');
<div v-if="showEventFields" class="grid grid-cols-2 gap-3">
<div class="col-span-2 space-y-2">
<Label class="text-[11px] font-black uppercase tracking-widest text-foreground/60">{{ $t(eventTitleLabelKey) }}</Label>
- <Input v-model="eventTitle" type="text" :placeholder="$t(eventTitlePlaceholderKey)" :disabled="isLocked" :class="eventTitleError ? 'border-rose-500' : undefined" />
+ <Input v-model="eventTitle" type="text" :placeholder="$t(eventTitlePlaceholderKey)" :disabled="disabled" :class="eventTitleError ? 'border-rose-500' : undefined" />
<InputError :message="eventTitleError" />
</div>
<div class="space-y-2">
@@ -222,7 +220,7 @@ const ctaUrlError = findError('call_to_action.url');
v-model="eventStart"
align="start"
:show-time="true"
- :disabled="isLocked"
+ :disabled="disabled"
:placeholder="$t('posts.form.google_business.event_start_date')"
:class="eventStartDateError || eventStartTimeError ? 'border-rose-500' : undefined"
/>
@@ -234,7 +232,7 @@ const ctaUrlError = findError('call_to_action.url');
v-model="eventEnd"
align="start"
:show-time="true"
- :disabled="isLocked"
+ :disabled="disabled"
:placeholder="$t('posts.form.google_business.event_end_date')"
:class="eventEndDateError || eventEndTimeError ? 'border-rose-500' : undefined"
/>
@@ -246,24 +244,24 @@ const ctaUrlError = findError('call_to_action.url');
<div v-if="topicType === GoogleBusinessTopicType.Offer" class="space-y-3">
<div class="space-y-2">
<Label class="text-[11px] font-black uppercase tracking-widest text-foreground/60">{{ $t('posts.form.google_business.offer_coupon_code') }}</Label>
- <Input v-model="offerCouponCode" type="text" :disabled="isLocked" :class="offerCouponCodeError ? 'border-rose-500' : undefined" />
+ <Input v-model="offerCouponCode" type="text" :disabled="disabled" :class="offerCouponCodeError ? 'border-rose-500' : undefined" />
<InputError :message="offerCouponCodeError" />
</div>
<div class="space-y-2">
<Label class="text-[11px] font-black uppercase tracking-widest text-foreground/60">{{ $t('posts.form.google_business.offer_redeem_url') }}</Label>
- <Input v-model="offerRedeemUrl" type="text" :disabled="isLocked" :class="offerRedeemUrlError ? 'border-rose-500' : undefined" />
+ <Input v-model="offerRedeemUrl" type="text" :disabled="disabled" :class="offerRedeemUrlError ? 'border-rose-500' : undefined" />
<InputError :message="offerRedeemUrlError" />
</div>
<div class="space-y-2">
<Label class="text-[11px] font-black uppercase tracking-widest text-foreground/60">{{ $t('posts.form.google_business.offer_terms') }}</Label>
- <Input v-model="offerTerms" type="text" :disabled="isLocked" :class="offerTermsError ? 'border-rose-500' : undefined" />
+ <Input v-model="offerTerms" type="text" :disabled="disabled" :class="offerTermsError ? 'border-rose-500' : undefined" />
<InputError :message="offerTermsError" />
</div>
</div>
<div v-if="showCallToAction" class="space-y-2">
<Label class="text-[11px] font-black uppercase tracking-widest text-foreground/60">{{ $t('posts.form.google_business.cta_label') }}</Label>
- <Select v-model="ctaActionType" :disabled="isLocked">
+ <Select v-model="ctaActionType" :disabled="disabled">
<SelectTrigger class="w-full" :aria-invalid="ctaActionTypeError ? true : undefined">
<SelectValue />
</SelectTrigger>
@@ -282,7 +280,7 @@ const ctaUrlError = findError('call_to_action.url');
<div v-if="showCtaUrl" class="space-y-2">
<Label class="text-[11px] font-black uppercase tracking-widest text-foreground/60">{{ $t('posts.form.google_business.cta_url') }}</Label>
- <Input v-model="ctaUrl" type="text" :placeholder="$t('posts.form.google_business.cta_url_placeholder')" :disabled="isLocked" :class="ctaUrlError ? 'border-rose-500' : undefined" />
+ <Input v-model="ctaUrl" type="text" :placeholder="$t('posts.form.google_business.cta_url_placeholder')" :disabled="disabled" :class="ctaUrlError ? 'border-rose-500' : undefined" />
<InputError :message="ctaUrlError" />
</div>
</div>
diff --git a/resources/js/components/posts/editor/PinterestSettings.vue b/resources/js/components/posts/editor/PinterestSettings.vue
index 11bd7f2d1..aad74d856 100644
--- a/resources/js/components/posts/editor/PinterestSettings.vue
+++ b/resources/js/components/posts/editor/PinterestSettings.vue
@@ -18,6 +18,7 @@ import {
import { Input } from '@/components/ui/input';
import { usePageErrors } from '@/composables/usePageErrors';
import { getPlatformLogo } from '@/composables/usePlatformLogo';
+import { toNullableText } from '@/lib/utils';
import type { PinterestBoard } from '@/types';
import { ContentType } from '@/types/content-type';
import type { MediaItem } from '@/types/media';
@@ -83,16 +84,14 @@ const selectedBoard = computed<BoardOption | undefined>({
const pinTitle = computed({
get: () => (props.meta?.title as string | undefined) || '',
set: (value: string) => {
- // Whitespace-only clears the field; keep interior spaces while typing.
- emit('update:meta', { ...props.meta, title: value.trim() === '' ? null : value });
+ emit('update:meta', { ...props.meta, title: toNullableText(value) });
},
});
const pinLink = computed({
get: () => (props.meta?.link as string | undefined) || '',
set: (value: string) => {
- // Whitespace-only clears the field; keep partial URLs while typing.
- emit('update:meta', { ...props.meta, link: value.trim() === '' ? null : value });
+ emit('update:meta', { ...props.meta, link: toNullableText(value) });
},
});
diff --git a/resources/js/components/posts/editor/PreviewTab.vue b/resources/js/components/posts/editor/PreviewTab.vue
index 4d78a418e..0a8d9ce78 100644
--- a/resources/js/components/posts/editor/PreviewTab.vue
+++ b/resources/js/components/posts/editor/PreviewTab.vue
@@ -69,6 +69,7 @@ const activeContentType = computed((): string | undefined => {
type="button"
class="relative cursor-pointer transition-opacity"
:class="activeId === pp.id ? 'opacity-100' : 'opacity-40 hover:opacity-70'"
+ :data-testid="`preview-platform-${pp.id}`"
@click="activeId = pp.id"
>
<Avatar
diff --git a/resources/js/components/posts/editor/YouTubeSettings.vue b/resources/js/components/posts/editor/YouTubeSettings.vue
new file mode 100644
index 000000000..346cd2f16
--- /dev/null
+++ b/resources/js/components/posts/editor/YouTubeSettings.vue
@@ -0,0 +1,158 @@
+<script setup lang="ts">
+import { IconChevronDown, IconChevronUp } from '@tabler/icons-vue';
+import { trans } from 'laravel-vue-i18n';
+import { computed, ref } from 'vue';
+
+import InputError from '@/components/InputError.vue';
+import { Avatar } from '@/components/ui/avatar';
+import { Label } from '@/components/ui/label';
+import { Textarea } from '@/components/ui/textarea';
+import { usePageErrors } from '@/composables/usePageErrors';
+import { getPlatformLogo } from '@/composables/usePlatformLogo';
+import { toNullableText } from '@/lib/utils';
+import {
+ getYouTubeDescriptionIssue,
+ YOUTUBE_DESCRIPTION_MAX_BYTES,
+ youtubeDescriptionBytes,
+} from '@/lib/youtubeDescription';
+import type { ChannelAccount } from '@/types/channel';
+import { Platform } from '@/types/platform';
+
+interface Props {
+ socialAccount: ChannelAccount | null;
+ platformIndex: number;
+ meta: Record<string, unknown>;
+ disabled?: boolean;
+}
+
+const props = withDefaults(defineProps<Props>(), {
+ disabled: false,
+});
+const emit = defineEmits<{
+ 'update:meta': [value: Record<string, unknown>];
+}>();
+
+const open = ref(false);
+const errors = usePageErrors();
+const descriptionId = computed(() => `youtube-description-${props.platformIndex}`);
+
+const description = computed({
+ get: () => toNullableText(props.meta.description) ?? '',
+ set: (value: string) =>
+ emit('update:meta', {
+ ...props.meta,
+ description: toNullableText(value),
+ }),
+});
+const usedBytes = computed(() => youtubeDescriptionBytes(description.value));
+const descriptionError = computed(() => {
+ const issue = getYouTubeDescriptionIssue(props.meta.description);
+
+ return issue
+ ? trans(issue)
+ : errors.value[`platforms.${props.platformIndex}.meta.description`];
+});
+</script>
+
+<template>
+ <div class="rounded-xl border-2 border-foreground bg-card shadow-2xs">
+ <button
+ type="button"
+ class="flex w-full cursor-pointer items-center justify-between gap-3 p-4 text-sm"
+ :data-testid="`youtube-settings-toggle-${platformIndex}`"
+ :aria-expanded="open"
+ @click="open = !open"
+ >
+ <span class="flex min-w-0 items-center gap-2">
+ <span
+ class="inline-flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-foreground bg-card shadow-2xs"
+ >
+ <img
+ :src="getPlatformLogo(Platform.YouTube)"
+ alt="YouTube"
+ class="size-full object-cover"
+ />
+ </span>
+ <span class="truncate font-bold text-foreground">{{
+ $t('posts.form.youtube.settings')
+ }}</span>
+ <span
+ v-if="socialAccount?.username"
+ class="truncate font-medium text-foreground/60"
+ >·&nbsp;@{{ socialAccount.username }}</span
+ >
+ </span>
+ <IconChevronUp
+ v-if="open"
+ class="size-4 shrink-0 text-foreground/60"
+ />
+ <IconChevronDown
+ v-else
+ class="size-4 shrink-0 text-foreground/60"
+ />
+ </button>
+ <div
+ v-if="open"
+ class="space-y-5 border-t-2 border-foreground/10 px-4 pt-4 pb-4"
+ >
+ <div
+ v-if="socialAccount"
+ class="flex items-center gap-3 rounded-lg bg-foreground/5 p-3"
+ >
+ <Avatar
+ :src="socialAccount.avatar_url"
+ :name="socialAccount.display_label"
+ class="size-9 shrink-0 rounded-full border-2 border-foreground shadow-2xs"
+ />
+ <div class="min-w-0 flex-1">
+ <p
+ class="text-[11px] font-black tracking-widest text-foreground/60 uppercase"
+ >
+ {{ $t('posts.form.youtube.posting_to') }}
+ </p>
+ <p class="truncate text-sm">
+ <span class="font-bold text-foreground">{{
+ socialAccount.display_label
+ }}</span>
+ <span
+ v-if="socialAccount.username"
+ class="font-medium text-foreground/60"
+ >&nbsp;@{{ socialAccount.username }}</span
+ >
+ </p>
+ </div>
+ </div>
+ <div class="space-y-2">
+ <Label
+ :for="descriptionId"
+ class="text-[11px] font-black tracking-widest text-foreground/60 uppercase"
+ >
+ {{ $t('posts.form.youtube.description') }}
+ </Label>
+ <Textarea
+ :id="descriptionId"
+ v-model="description"
+ :data-testid="descriptionId"
+ :disabled="disabled"
+ :aria-invalid="descriptionError ? true : undefined"
+ :placeholder="
+ $t('posts.form.youtube.description_placeholder')
+ "
+ class="field-sizing-fixed min-h-32 w-full resize-y"
+ />
+ <p
+ class="text-xs tabular-nums"
+ :class="descriptionError ? 'text-rose-600' : 'text-foreground/60'"
+ >
+ {{
+ $t('posts.form.youtube.description_bytes', {
+ used: usedBytes.toString(),
+ limit: YOUTUBE_DESCRIPTION_MAX_BYTES.toString(),
+ })
+ }}
+ </p>
+ <InputError :message="descriptionError" />
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/resources/js/components/posts/previews/YouTubePreview.vue b/resources/js/components/posts/previews/YouTubePreview.vue
index 17ed90070..867f466d9 100644
--- a/resources/js/components/posts/previews/YouTubePreview.vue
+++ b/resources/js/components/posts/previews/YouTubePreview.vue
@@ -1,7 +1,10 @@
<script setup lang="ts">
+import { computed } from 'vue';
+
import VideoPreview from "@/components/posts/previews/VideoPreview.vue";
import { getInitials } from '@/composables/useInitials';
import { isVideoMedia } from '@/composables/useMedia';
+import { toNullableText } from '@/lib/utils';
import type { MediaItem } from '@/types/media';
interface SocialAccount {
@@ -18,9 +21,13 @@ interface Props {
socialAccount: SocialAccount;
content: string;
media: MediaItem[];
+ meta?: Record<string, any>;
}
-defineProps<Props>();
+const props = withDefaults(defineProps<Props>(), { meta: () => ({}) });
+const description = computed(() =>
+ toNullableText(props.meta.description) ?? props.content,
+);
// Format engagement numbers like YouTube does
const formatNumber = (num: number): string => {
@@ -168,6 +175,11 @@ const formatNumber = (num: number): string => {
{{ content || 'No title' }}
</div>
+ <details v-if="description" class="mb-1.5 text-xs">
+ <summary class="cursor-pointer">{{ $t('posts.form.youtube.description') }}</summary>
+ <p class="mt-1 max-h-32 overflow-y-auto whitespace-pre-wrap break-words" data-testid="youtube-preview-description">{{ description }}</p>
+ </details>
+
<!-- Music info -->
<div class="flex items-center gap-1.5">
<svg class="w-3 h-3 shrink-0" viewBox="0 0 24 24" fill="currentColor">
@@ -231,4 +243,4 @@ const formatNumber = (num: number): string => {
<div class="h-full w-2/5 bg-[#ff0000]"></div>
</div>
</div>
-</template>
\ No newline at end of file
+</template>
diff --git a/resources/js/composables/usePostCompliance.ts b/resources/js/composables/usePostCompliance.ts
index d2b751ad4..ac64441e4 100644
--- a/resources/js/composables/usePostCompliance.ts
+++ b/resources/js/composables/usePostCompliance.ts
@@ -16,6 +16,7 @@ import {
resolveGoogleBusinessCtaAction,
resolveGoogleBusinessTopicType,
} from '@/lib/googleBusiness';
+import { getYouTubeDescriptionIssue } from '@/lib/youtubeDescription';
import { ContentType } from '@/types/content-type';
import type { MediaItem } from '@/types/media';
import { Platform } from '@/types/platform';
@@ -62,6 +63,10 @@ type MetaRule = (meta: Record<string, any>) => { valid: boolean; tooltipKey: str
// — null means "blocks the publish but no dedicated message, fall through
// to the generic incomplete tooltip".
const PLATFORM_META_RULES: Record<string, MetaRule> = {
+ [Platform.YouTube]: (meta) => {
+ const tooltipKey = getYouTubeDescriptionIssue(meta.description);
+ return { valid: tooltipKey === null, tooltipKey };
+ },
[Platform.TikTok]: (meta) => {
const disclosureIncomplete = Boolean(meta.disclose)
&& !meta.brand_organic_toggle
diff --git a/resources/js/lib/utils.ts b/resources/js/lib/utils.ts
index fc4c53b8e..d79adf5b8 100644
--- a/resources/js/lib/utils.ts
+++ b/resources/js/lib/utils.ts
@@ -12,6 +12,9 @@ export const toUrl = (href: NonNullable<InertiaLinkProps['href']>) => {
return typeof href === 'string' ? href : href?.url;
};
+export const toNullableText = (value: unknown): string | null =>
+ typeof value === 'string' && value.trim() ? value : null;
+
export const formatNumber = (value: number): string => {
return value.toLocaleString('en-US');
};
diff --git a/resources/js/lib/youtubeDescription.ts b/resources/js/lib/youtubeDescription.ts
new file mode 100644
index 000000000..a1f34e7a0
--- /dev/null
+++ b/resources/js/lib/youtubeDescription.ts
@@ -0,0 +1,24 @@
+export const YOUTUBE_DESCRIPTION_MAX_BYTES = 5000;
+
+const textEncoder = new TextEncoder();
+
+export const youtubeDescriptionBytes = (description: string): number =>
+ textEncoder.encode(description).length;
+
+export const getYouTubeDescriptionIssue = (
+ description: unknown,
+): string | null => {
+ if (description === null || description === undefined) {
+ return null;
+ }
+
+ if (typeof description !== 'string') {
+ return 'posts.form.youtube.description_invalid';
+ }
+
+ if (youtubeDescriptionBytes(description) > YOUTUBE_DESCRIPTION_MAX_BYTES) {
+ return 'posts.form.youtube.description_max';
+ }
+
+ return null;
+};
diff --git a/tests/Browser/SidebarLanguageSwitchTest.php b/tests/Browser/SidebarLanguageSwitchTest.php
index 2d3ce15d0..b12fa62b3 100644
--- a/tests/Browser/SidebarLanguageSwitchTest.php
+++ b/tests/Browser/SidebarLanguageSwitchTest.php
@@ -115,7 +115,7 @@ test('the calendar header follows the language, not the previous one', function
$this->actingAs($user);
- $page = visit(route('app.calendar'));
+ $page = visit(route('app.calendar', ['view' => 'week', 'week' => '2026-09-14']));
waitForSidebarLanguageTestId($page, 'sidebar-workspace-menu');
$page->script(<<<'JS'
@@ -152,7 +152,7 @@ test('the month view header follows the language too', function () {
$this->actingAs($user);
- $page = visit(route('app.calendar', ['view' => 'month']));
+ $page = visit(route('app.calendar', ['view' => 'month', 'month' => '2026-09-01']));
waitForSidebarLanguageTestId($page, 'sidebar-workspace-menu');
$page->script(<<<'JS'
diff --git a/tests/Browser/YouTubeDescriptionTest.php b/tests/Browser/YouTubeDescriptionTest.php
new file mode 100644
index 000000000..898b9a197
--- /dev/null
+++ b/tests/Browser/YouTubeDescriptionTest.php
@@ -0,0 +1,221 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\Post\Status;
+use App\Enums\UserWorkspace\Role;
+use App\Models\Post;
+use App\Models\PostPlatform;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use Illuminate\Foundation\Vite;
+use Illuminate\Support\Facades\Route;
+
+function seedYouTubeDescriptionEditor(): array
+{
+ app(Vite::class)->useHotFile(storage_path('framework/testing-youtube.hot'));
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, ['role' => Role::Member->value]);
+ $user->update(['current_workspace_id' => $workspace->id]);
+ Route::get('/__tests/youtube-description-video', fn () => response()->file(base_path('tests/fixtures/sample.mp4')));
+ $post = Post::factory()->create([
+ 'workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'Short title', 'status' => Status::Draft,
+ 'media' => [[
+ 'id' => 'youtube-video', 'type' => 'video', 'path' => 'medias/video.mp4', 'url' => url('/__tests/youtube-description-video'),
+ 'mime_type' => 'video/mp4', 'original_filename' => 'video.mp4', 'size' => filesize(base_path('tests/fixtures/sample.mp4')),
+ ]],
+ ]);
+ $platforms = collect(range(1, 2))->map(function (int $number) use ($workspace, $post) {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $workspace->id, 'username' => "ytchannel{$number}"]);
+
+ return PostPlatform::factory()->youtube()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'enabled' => true, 'meta' => ['description' => "Channel {$number}"]]);
+ });
+ test()->actingAs($user);
+
+ return [$post, $platforms];
+}
+
+function waitForYouTubeElement(mixed $page, string $testId): void
+{
+ $page->script(<<<JS
+ (async () => {
+ for (let i = 0; i < 100; i++) {
+ const el = document.querySelector('[data-testid="{$testId}"]');
+ if (el && el.getBoundingClientRect().height > 0) return;
+ await new Promise(resolve => setTimeout(resolve, 50));
+ }
+ })();
+ JS);
+}
+
+function trackYouTubeAutosave(mixed $page): void
+{
+ $page->script(<<<'JS'
+ (() => {
+ window.__youtubeAutosaveDone = false;
+ const open = XMLHttpRequest.prototype.open;
+ const send = XMLHttpRequest.prototype.send;
+ XMLHttpRequest.prototype.open = function (method) {
+ this.__youtubeMethod = (method || '').toUpperCase();
+ return open.apply(this, arguments);
+ };
+ XMLHttpRequest.prototype.send = function () {
+ this.addEventListener('loadend', () => {
+ if (this.__youtubeMethod === 'PUT') window.__youtubeAutosaveDone = true;
+ });
+ return send.apply(this, arguments);
+ };
+ })();
+ JS);
+}
+
+function waitForYouTubeAutosave(mixed $page): void
+{
+ $page->script(<<<'JS'
+ (async () => {
+ for (let i = 0; i < 100 && !window.__youtubeAutosaveDone; i++) {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ })();
+ JS);
+ expect($page->script('window.__youtubeAutosaveDone'))->toBeTrue();
+}
+
+function assertYouTubePublishState(mixed $page, bool $disabled): void
+{
+ $label = json_encode(__('posts.edit.post_now'), JSON_THROW_ON_ERROR);
+ $want = $disabled ? 'true' : 'false';
+ $state = $page->script(<<<JS
+ (async () => {
+ for (let i = 0; i < 100; i++) {
+ const button = Array.from(document.querySelectorAll('button')).find(el =>
+ el.textContent.trim() === {$label} && el.getBoundingClientRect().height > 0);
+ if (button && button.disabled === {$want}) return true;
+ await new Promise(resolve => setTimeout(resolve, 50));
+ }
+ return false;
+ })();
+ JS);
+ expect($state)->toBeTrue();
+}
+
+test('youtube description editor counts bytes saves independent channels and previews', function (int $width, int $height) {
+ [$post, $platforms] = seedYouTubeDescriptionEditor();
+ $page = visit(route('app.posts.edit', $post))->resize($width, $height);
+ if ($width < 1024) {
+ waitForYouTubeElement($page, 'editor-nav-channels');
+ $page->click('@editor-nav-channels');
+ }
+ waitForYouTubeElement($page, 'youtube-settings-toggle-0');
+ $page->click('@youtube-settings-toggle-0')->click('@youtube-settings-toggle-1');
+ waitForYouTubeElement($page, 'youtube-description-0');
+ $initial = $page->script('document.querySelector("[data-testid=youtube-description-0]").value');
+ $first = $platforms->first(fn (PostPlatform $row): bool => $row->meta['description'] === $initial);
+ $second = $platforms->first(fn (PostPlatform $row): bool => $row->id !== $first->id);
+ assertYouTubePublishState($page, false);
+ $page->fill('@youtube-description-0', str_repeat('é', 2500));
+ assertYouTubePublishState($page, false);
+ $page->assertSee('5000 / 5000 bytes')->assertNoJavaScriptErrors();
+ $page->assertAttributeMissing('@youtube-description-0', 'aria-invalid');
+ $page->fill('@youtube-description-0', str_repeat('😀', 1250));
+ assertYouTubePublishState($page, false);
+ $page->assertSee('5000 / 5000 bytes')->assertAttributeMissing('@youtube-description-0', 'aria-invalid');
+ foreach ([str_repeat('é', 2500).'a', str_repeat('😀', 1250).'a'] as $invalid) {
+ $page->fill('@youtube-description-0', $invalid);
+ assertYouTubePublishState($page, true);
+ $page->assertAttribute('@youtube-description-0', 'aria-invalid', 'true');
+ }
+ $page->click('@channel-'.$first->id);
+ assertYouTubePublishState($page, false);
+ $page->click('@channel-'.$first->id);
+ assertYouTubePublishState($page, true);
+ waitForYouTubeElement($page, 'youtube-settings-toggle-0');
+ $page->click('@youtube-settings-toggle-0');
+ waitForYouTubeElement($page, 'youtube-description-0');
+ trackYouTubeAutosave($page);
+ $description = "First channel description 😀 ação\nhttps://example.com\nif (a < b && c > d) {}\n<p>Text about HTML</p>";
+ $page->fill('@youtube-description-0', " {$description} ")
+ ->fill('@youtube-description-1', 'Second channel description');
+ $page->assertValue('@youtube-description-0', " {$description} ");
+ assertYouTubePublishState($page, false);
+ $page->assertAttributeMissing('@youtube-description-0', 'aria-invalid');
+ waitForYouTubeAutosave($page);
+ $page->screenshot(filename: 'youtube-description-settings-'.$width);
+ expect(data_get($first->fresh()->meta, 'description'))->toBe($description)
+ ->and(data_get($second->fresh()->meta, 'description'))->toBe('Second channel description')
+ ->and($post->fresh()->content)->toBe('Short title');
+ $page->click($width < 1024 ? '@editor-nav-preview' : '@editor-tab-preview');
+ waitForYouTubeElement($page, 'preview-platform-'.$first->id);
+ $page->click('@preview-platform-'.$first->id)->click('details > summary');
+ $page->assertSeeIn('@youtube-preview-description', 'if (a < b && c > d) {}')
+ ->assertSeeIn('@youtube-preview-description', '<p>Text about HTML</p>');
+ expect($page->script('document.documentElement.scrollWidth <= window.innerWidth'))->toBeTrue();
+ $page->assertNoJavaScriptErrors();
+ $page = visit(route('app.posts.edit', $post))->resize($width, $height);
+ if ($width < 1024) {
+ waitForYouTubeElement($page, 'editor-nav-channels');
+ $page->click('@editor-nav-channels');
+ }
+ waitForYouTubeElement($page, 'youtube-settings-toggle-0');
+ $page->click('@youtube-settings-toggle-0')->click('@youtube-settings-toggle-1');
+ $page->assertValue('@youtube-description-0', $description)
+ ->assertValue('@youtube-description-1', 'Second channel description');
+})->with([[1280, 900], [375, 812]]);
+
+test('youtube description clearing restores content fallback without changing another channel', function (string $description) {
+ [$post, $platforms] = seedYouTubeDescriptionEditor();
+ $page = visit(route('app.posts.edit', $post))->resize(375, 812);
+ waitForYouTubeElement($page, 'editor-nav-channels');
+ $page->click('@editor-nav-channels');
+ waitForYouTubeElement($page, 'youtube-settings-toggle-0');
+ $page->click('@youtube-settings-toggle-0');
+ waitForYouTubeElement($page, 'youtube-description-0');
+ $initial = $page->script('document.querySelector("[data-testid=youtube-description-0]").value');
+ $first = $platforms->first(fn (PostPlatform $row): bool => $row->meta['description'] === $initial);
+ $second = $platforms->first(fn (PostPlatform $row): bool => $row->id !== $first->id);
+ trackYouTubeAutosave($page);
+ $page->fill('@youtube-description-0', $description);
+ waitForYouTubeAutosave($page);
+ expect(data_get($first->fresh()->meta, 'description'))->toBeNull()
+ ->and($second->fresh()->meta)->toEqual($second->meta);
+ $page->click('@editor-nav-preview');
+ waitForYouTubeElement($page, 'preview-platform-'.$first->id);
+ $page->click('@preview-platform-'.$first->id)->click('details > summary');
+ $page->assertSeeIn('@youtube-preview-description', 'Short title')->assertNoJavaScriptErrors();
+})->with([
+ 'empty description' => [''],
+ 'whitespace description' => [" \t\n\u{00A0}"],
+]);
+
+test('youtube description long preview stays above the phone navigation', function (int $width, int $height) {
+ [$post, $platforms] = seedYouTubeDescriptionEditor();
+ $platform = $platforms->first();
+ $description = "Full description\n".str_repeat('https://example.com/'.str_repeat('a', 100)."\n", 35);
+ $platform->update(['meta' => ['description' => $description]]);
+ $page = visit(route('app.posts.edit', $post))->resize($width, $height);
+ if ($width < 1024) {
+ waitForYouTubeElement($page, 'editor-nav-preview');
+ } else {
+ waitForYouTubeElement($page, 'editor-tab-preview');
+ }
+ $page->click($width < 1024 ? '@editor-nav-preview' : '@editor-tab-preview');
+ waitForYouTubeElement($page, 'preview-platform-'.$platform->id);
+ $page->click('@preview-platform-'.$platform->id)->click('details > summary');
+ $page->assertSeeIn('@youtube-preview-description', 'Full description');
+ $layout = $page->script(<<<'JS'
+ (() => {
+ const description = document.querySelector('[data-testid=youtube-preview-description]');
+ const navigation = description.parentElement.parentElement.parentElement.lastElementChild;
+ return {
+ scrolls: description.scrollHeight > description.clientHeight,
+ bounded: description.clientHeight <= 128,
+ aboveNavigation: description.getBoundingClientRect().bottom <= navigation.getBoundingClientRect().top,
+ noOverflow: document.documentElement.scrollWidth <= window.innerWidth,
+ };
+ })();
+ JS);
+ expect($layout)->toEqual(['scrolls' => true, 'bounded' => true, 'aboveNavigation' => true, 'noOverflow' => true]);
+ $page->assertNoJavaScriptErrors()->screenshot(filename: 'youtube-description-preview-'.$width);
+})->with([[1280, 900], [375, 812]]);
diff --git a/tests/Feature/Actions/Post/UpdatePostTest.php b/tests/Feature/Actions/Post/UpdatePostTest.php
index 987cc98e8..92c2b7110 100644
--- a/tests/Feature/Actions/Post/UpdatePostTest.php
+++ b/tests/Feature/Actions/Post/UpdatePostTest.php
@@ -12,6 +12,7 @@ use App\Models\User;
use App\Models\Workspace;
use App\Support\Social\GoogleBusinessDerivativeCleaner;
use Illuminate\Support\Facades\Storage;
+use Illuminate\Validation\ValidationException;
test('execute prunes a google business jpeg when the target is switched off', function () {
Storage::fake();
@@ -108,3 +109,71 @@ test('execute keeps the google business jpeg when the target stays enabled', fun
expect($target->fresh()->enabled)->toBeTrue();
Storage::assertExists($path);
});
+
+test('invalid publication metadata rolls back before cleaning a disabled google business target', function () {
+ Storage::fake();
+
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $post = Post::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'user_id' => $user->id,
+ 'status' => PostStatus::Draft,
+ ]);
+ $youtube = PostPlatform::factory()->youtube()->create([
+ 'post_id' => $post->id,
+ 'social_account_id' => SocialAccount::factory()->youtube()->create([
+ 'workspace_id' => $workspace->id,
+ ])->id,
+ 'meta' => ['description' => str_repeat('a', 5001)],
+ ]);
+ $target = PostPlatform::factory()->googleBusiness()->pendingReview()->create([
+ 'post_id' => $post->id,
+ 'social_account_id' => SocialAccount::factory()->googleBusiness()->create([
+ 'workspace_id' => $workspace->id,
+ ])->id,
+ 'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
+ ]);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($target->id);
+ Storage::put($path, 'image');
+
+ expect(fn () => UpdatePost::execute($workspace, $post, [
+ 'status' => PostStatus::Scheduled->value,
+ 'platforms' => [['id' => $youtube->id]],
+ ]))->toThrow(ValidationException::class);
+
+ expect($post->fresh()->status)->toBe(PostStatus::Draft)
+ ->and($target->fresh()->enabled)->toBeTrue()
+ ->and($target->fresh()->status)->toBe(PlatformStatus::PendingReview);
+ Storage::assertExists($path);
+});
+
+test('disabled youtube metadata does not block scheduling', function (bool $resubmitPlatforms) {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $post = Post::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'user_id' => $user->id,
+ ]);
+ $platform = PostPlatform::factory()->youtube()->create([
+ 'post_id' => $post->id,
+ 'social_account_id' => SocialAccount::factory()->youtube()->create([
+ 'workspace_id' => $workspace->id,
+ ])->id,
+ 'enabled' => false,
+ 'meta' => ['description' => str_repeat('a', 5001)],
+ ]);
+ $data = ['status' => PostStatus::Scheduled->value];
+
+ if ($resubmitPlatforms) {
+ $data['platforms'] = [];
+ }
+
+ UpdatePost::execute($workspace, $post, $data);
+
+ expect($post->fresh()->status)->toBe(PostStatus::Scheduled)
+ ->and($platform->fresh()->enabled)->toBeFalse();
+})->with([
+ 'omitted platforms' => [false],
+ 'deselected platforms' => [true],
+]);
diff --git a/tests/Feature/Api/PostApiPlatformMetaTest.php b/tests/Feature/Api/PostApiPlatformMetaTest.php
index 2c92f8144..c1a1e3efd 100644
--- a/tests/Feature/Api/PostApiPlatformMetaTest.php
+++ b/tests/Feature/Api/PostApiPlatformMetaTest.php
@@ -15,6 +15,120 @@ use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
+it('youtube description survives create read update omission and clear', function (string $description) {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ $response = $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Short title',
+ 'platforms' => [[
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['description' => $description],
+ ]],
+ ])->assertCreated();
+ $post = Post::findOrFail($response->json('id'));
+ $platform = $post->postPlatforms()->where('social_account_id', $account->id)->sole();
+
+ expect($platform->meta)->toEqual(['description' => $description]);
+ $read = $this->withHeaders($this->headers)->getJson(route('api.posts.show', $post))->assertOk();
+ expect(collect($read->json('platforms'))->firstWhere('id', $platform->id)['meta']['description'])->toBe($description);
+ $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
+ 'status' => PostStatus::Draft->value,
+ 'platforms' => [[
+ 'id' => $platform->id,
+ 'meta' => ['description' => str_repeat('é', 2501)],
+ ]],
+ ])->assertUnprocessable()->assertJsonValidationErrors('platforms.0.meta.description');
+ expect(data_get($platform->fresh()->meta, 'description'))->toBe($description);
+ $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
+ 'status' => PostStatus::Draft->value,
+ 'platforms' => [['id' => $platform->id]],
+ ])->assertOk();
+ expect(data_get($platform->fresh()->meta, 'description'))->toBe($description);
+ $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
+ 'status' => PostStatus::Draft->value,
+ 'platforms' => [[
+ 'id' => $platform->id,
+ 'meta' => ['description' => null],
+ ]],
+ ])->assertOk();
+ expect(data_get($platform->fresh()->meta, 'description'))->toBeNull();
+})->with([
+ 'multiline description' => ["Full description\nhttps://example.com\n#video"],
+ 'programming text' => ["if (a < b && c > d) {}\n<p>Text about HTML</p>"],
+ 'multibyte byte limit' => [str_repeat('é', 2500)],
+]);
+
+it('youtube description rejects invalid API create input', function (string $description) {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Short title',
+ 'platforms' => [[
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['description' => $description],
+ ]],
+ ])->assertUnprocessable()->assertJsonValidationErrors('platforms.0.meta.description');
+})->with([
+ 'multibyte overflow' => [str_repeat('é', 2501)],
+ 'ascii overflow' => [str_repeat('a', 5001)],
+ 'emoji overflow' => [str_repeat('😀', 1251)],
+]);
+
+it('youtube description checks effective API metadata before scheduling or publishing', function (string $patch, bool $allowed, string $status) {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $this->user->id,
+ 'content' => 'Short title',
+ 'status' => PostStatus::Draft,
+ 'media' => [[
+ 'id' => 'video-1',
+ 'type' => 'video',
+ 'path' => 'medias/video.mp4',
+ 'url' => 'https://example.com/video.mp4',
+ 'mime_type' => 'video/mp4',
+ 'original_filename' => 'video.mp4',
+ ]],
+ ]);
+ $platform = PostPlatform::factory()->youtube()->create([
+ 'post_id' => $post->id,
+ 'social_account_id' => $account->id,
+ 'enabled' => true,
+ 'meta' => ['description' => str_repeat('a', 5001)],
+ ]);
+ $data = [
+ 'status' => $status,
+ 'scheduled_at' => now()->addHour()->toIso8601String(),
+ ];
+
+ if ($patch !== 'omit') {
+ $data['platforms'] = [['id' => $platform->id]];
+ if ($patch !== 'row') {
+ $data['platforms'][0]['meta'] = ['description' => $patch === 'clear' ? null : 'Valid description'];
+ }
+ }
+ Queue::fake();
+ $response = $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), $data);
+
+ if ($allowed) {
+ $response->assertOk();
+ expect($post->fresh()->status->value)->toBe($status);
+
+ if ($status === PostStatus::Publishing->value) {
+ Queue::assertPushed(PublishPost::class);
+ }
+ } else {
+ $response->assertUnprocessable()->assertJsonValidationErrors('platforms.0.meta.description');
+ expect($post->fresh()->status)->toBe(PostStatus::Draft);
+ Queue::assertNotPushed(PublishPost::class);
+ }
+})->with([
+ 'stored invalid description' => ['omit', false],
+ 'retained invalid description' => ['row', false],
+ 'replaced description' => ['replace', true],
+ 'cleared description' => ['clear', true],
+])->with([PostStatus::Scheduled->value, PostStatus::Publishing->value]);
+
beforeEach(function () {
$result = createApiTestToken();
$this->user = $result['user'];
diff --git a/tests/Feature/Mcp/PostPlatformMetaToolTest.php b/tests/Feature/Mcp/PostPlatformMetaToolTest.php
index 304085886..000525ed4 100644
--- a/tests/Feature/Mcp/PostPlatformMetaToolTest.php
+++ b/tests/Feature/Mcp/PostPlatformMetaToolTest.php
@@ -12,6 +12,7 @@ use App\Jobs\PublishPost;
use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\AttachMediaFromUploadTool;
use App\Mcp\Tools\Post\CreatePostTool;
+use App\Mcp\Tools\Post\GetPostTool;
use App\Mcp\Tools\Post\PublishPostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Post;
@@ -21,6 +22,117 @@ use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
+use Illuminate\Testing\Fluent\AssertableJson;
+
+test('youtube description persists reads retains and clears in MCP', function (string $description) {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
+ 'content' => 'Short title',
+ 'platforms' => [[
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['description' => $description],
+ ]],
+ ])->assertOk();
+ $platform = PostPlatform::where('social_account_id', $account->id)->sole();
+ TryPostServer::actingAs($this->user)->tool(GetPostTool::class, ['post_id' => $platform->post_id])
+ ->assertOk()->assertStructuredContent(function (AssertableJson $json) use ($platform, $description) {
+ $json->etc();
+ expect(collect($json->toArray()['platforms'])->firstWhere('id', $platform->id)['meta']['description'])->toBe($description);
+ });
+ TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
+ 'post_id' => $platform->post_id,
+ 'platforms' => [[
+ 'id' => $platform->id,
+ 'meta' => ['description' => str_repeat('é', 2501)],
+ ]],
+ ])->assertHasErrors([__('posts.form.youtube.description_max')]);
+ TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
+ 'post_id' => $platform->post_id,
+ 'platforms' => [['id' => $platform->id]],
+ ])->assertOk();
+ expect(data_get($platform->fresh()->meta, 'description'))->toBe($description);
+ TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
+ 'post_id' => $platform->post_id,
+ 'platforms' => [[
+ 'id' => $platform->id,
+ 'meta' => ['description' => null],
+ ]],
+ ])->assertOk();
+ expect(data_get($platform->fresh()->meta, 'description'))->toBeNull();
+})->with([
+ 'multiline description' => ["Full text\nhttps://example.com"],
+ 'programming text' => ["if (a < b && c > d) {}\n<p>Text about HTML</p>"],
+]);
+
+test('youtube description rejects invalid MCP create input', function (string $description) {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
+ 'content' => 'Short title',
+ 'platforms' => [[
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['description' => $description],
+ ]],
+ ])->assertHasErrors();
+})->with([
+ 'multibyte overflow' => [str_repeat('é', 2501)],
+ 'ascii overflow' => [str_repeat('a', 5001)],
+ 'emoji overflow' => [str_repeat('😀', 1251)],
+]);
+
+test('youtube description checks effective MCP metadata on schedule and publish', function (string $patch, bool $allowed) {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $this->user->id,
+ 'content' => 'Short title',
+ 'status' => PostStatus::Draft,
+ 'media' => [[
+ 'id' => 'video-1',
+ 'type' => 'video',
+ 'path' => 'medias/video.mp4',
+ 'url' => 'https://example.com/video.mp4',
+ 'mime_type' => 'video/mp4',
+ 'original_filename' => 'video.mp4',
+ ]],
+ ]);
+ $platform = PostPlatform::factory()->youtube()->create([
+ 'post_id' => $post->id,
+ 'social_account_id' => $account->id,
+ 'enabled' => true,
+ 'meta' => ['description' => str_repeat('a', 5001)],
+ ]);
+ Queue::fake();
+ TryPostServer::actingAs($this->user)->tool(PublishPostTool::class, ['post_id' => $post->id])->assertHasErrors([__('posts.form.youtube.description_max')]);
+ Queue::assertNotPushed(PublishPost::class);
+ $data = [
+ 'post_id' => $post->id,
+ 'status' => PostStatus::Scheduled->value,
+ 'scheduled_at' => now()->addHour()->toIso8601String(),
+ ];
+
+ if ($patch !== 'omit') {
+ $data['platforms'] = [['id' => $platform->id]];
+ if ($patch !== 'row') {
+ $data['platforms'][0]['meta'] = ['description' => $patch === 'clear' ? null : 'Valid description'];
+ }
+ }
+ $response = TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, $data);
+
+ if ($allowed) {
+ $response->assertOk();
+ expect($post->fresh()->status)->toBe(PostStatus::Scheduled);
+ } else {
+ $response->assertHasErrors([__('posts.form.youtube.description_max')]);
+ expect($post->fresh()->status)->toBe(PostStatus::Draft);
+ }
+})->with([
+ 'stored invalid description' => ['omit', false],
+ 'retained invalid description' => ['row', false],
+ 'replaced description' => ['replace', true],
+ 'cleared description' => ['clear', true],
+]);
beforeEach(function () {
$this->user = User::factory()->create();
diff --git a/tests/Feature/Services/Social/YouTubePublisherTest.php b/tests/Feature/Services/Social/YouTubePublisherTest.php
index eb7a072b2..d0a505b09 100644
--- a/tests/Feature/Services/Social/YouTubePublisherTest.php
+++ b/tests/Feature/Services/Social/YouTubePublisherTest.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
+use App\Exceptions\Social\YouTubePublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
use App\Models\PostPlatform;
@@ -11,8 +12,141 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Social\YouTubePublisher;
+use Google\Client;
+use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
+function fakeYouTubeUpload(array $responses = []): YouTubePublisher
+{
+ Http::preventStrayRequests();
+ Http::fake(array_replace([
+ 'https://example.com/video.mp4' => fn () => Http::response(str_repeat('x', 2048)),
+ 'https://youtube.googleapis.com/upload/youtube/v3/videos*' => Http::response('', 200, [
+ 'Location' => 'https://upload.example.test/session',
+ ]),
+ 'https://upload.example.test/session' => Http::response(['id' => 'short-id']),
+ ], $responses));
+
+ $client = new Client;
+ $client->setHttpClient(Http::buildClient());
+ test()->instance(Client::class, $client);
+
+ return new YouTubePublisher;
+}
+
+test('youtube description rejects stored invalid data before network work', function (mixed $description, string $key) {
+ Http::fake();
+ $this->socialAccount->update(['token_expires_at' => now()->subHour()]);
+ $this->postPlatform->update(['meta' => ['description' => $description]]);
+ expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ ->toThrow(YouTubePublishException::class, __($key));
+ Http::assertNothingSent();
+})->with([
+ 'multibyte overflow' => [str_repeat('é', 2501), 'posts.form.youtube.description_max'],
+ 'ascii overflow' => [str_repeat('a', 5001), 'posts.form.youtube.description_max'],
+ 'emoji overflow' => [str_repeat('😀', 1251), 'posts.form.youtube.description_max'],
+ 'invalid metadata type' => [['invalid'], 'posts.form.youtube.description_invalid'],
+]);
+
+test('youtube description reaches the resumable upload request', function (?string $description, string $expected) {
+ $this->post->update([
+ 'content' => 'Short title',
+ 'media' => [[
+ 'id' => 'video-1',
+ 'type' => 'video',
+ 'path' => 'medias/video.mp4',
+ 'url' => 'https://example.com/video.mp4',
+ 'mime_type' => 'video/mp4',
+ 'original_filename' => 'video.mp4',
+ ]],
+ ]);
+ $this->postPlatform->update(['meta' => ['description' => $description]]);
+ $tempFile = null;
+ $publisher = fakeYouTubeUpload([
+ 'https://example.com/video.mp4' => function (Request $request, array $options) use (&$tempFile) {
+ $tempFile = $options['sink'];
+
+ return Http::response(str_repeat('x', 2048));
+ },
+ ]);
+
+ $result = $publisher->publish($this->postPlatform->fresh());
+
+ expect($result)->toBe([
+ 'id' => 'short-id',
+ 'url' => 'https://www.youtube.com/shorts/short-id',
+ ]);
+ expect(app(Client::class)->shouldDefer())->toBeFalse();
+ $this->assertFileDoesNotExist($tempFile);
+
+ Http::assertSent(function (Request $request) use ($expected): bool {
+ if (! str_contains($request->url(), '/upload/youtube/v3/videos')) {
+ return false;
+ }
+
+ $payload = json_decode($request->body(), true, flags: JSON_THROW_ON_ERROR);
+
+ return $request->method() === 'POST'
+ && $payload['snippet']['title'] === 'Short title #Shorts'
+ && $payload['snippet']['description'] === $expected
+ && $payload['snippet']['categoryId'] === '22'
+ && $payload['status']['privacyStatus'] === 'public'
+ && $payload['status']['selfDeclaredMadeForKids'] === false;
+ });
+})->with([
+ 'custom multiline description' => ["Full text\nhttps://example.com", "Full text\nhttps://example.com"],
+ 'programming text' => ['if (a < b && c > d) {}', 'if (a < b && c > d) {}'],
+ 'literal markup' => ['<p>Text about HTML</p>', '<p>Text about HTML</p>'],
+ 'multibyte byte limit' => [str_repeat('é', 2500), str_repeat('é', 2500)],
+ 'emoji byte limit' => [str_repeat('😀', 1250), str_repeat('😀', 1250)],
+ 'surrounding whitespace' => [" Full text\nhttps://example.com ", " Full text\nhttps://example.com "],
+ 'null description' => [null, 'Short title'],
+ 'empty description' => ['', 'Short title'],
+ 'blank description' => [" \n ", 'Short title'],
+ 'non-breaking spaces' => ["\u{00A0}\u{00A0}", 'Short title'],
+]);
+
+test('youtube description builds independent upload metadata', function () {
+ $this->post->update([
+ 'content' => 'Short title',
+ 'media' => [[
+ 'id' => 'video-1',
+ 'type' => 'video',
+ 'path' => 'medias/video.mp4',
+ 'url' => 'https://example.com/video.mp4',
+ 'mime_type' => 'video/mp4',
+ 'original_filename' => 'video.mp4',
+ ]],
+ ]);
+ $this->postPlatform->update(['meta' => ['description' => 'First channel description']]);
+ $secondAccount = SocialAccount::factory()->youtube()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'token_expires_at' => now()->addDays(7),
+ ]);
+ $secondPlatform = PostPlatform::factory()->youtube()->create([
+ 'post_id' => $this->post->id,
+ 'social_account_id' => $secondAccount->id,
+ 'meta' => ['description' => 'Second channel description'],
+ ]);
+ $publisher = fakeYouTubeUpload();
+
+ $publisher->publish($this->postPlatform->fresh());
+ $publisher->publish($secondPlatform);
+
+ foreach (['First channel description', 'Second channel description'] as $description) {
+ Http::assertSent(function (Request $request) use ($description): bool {
+ if (! str_contains($request->url(), '/upload/youtube/v3/videos')) {
+ return false;
+ }
+
+ $payload = json_decode($request->body(), true, flags: JSON_THROW_ON_ERROR);
+
+ return $payload['snippet']['title'] === 'Short title #Shorts'
+ && $payload['snippet']['description'] === $description;
+ });
+ }
+});
+
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
@@ -49,6 +183,37 @@ test('youtube publisher throws exception when no media', function () {
->toThrow(Exception::class, 'YouTube Shorts requires a video to publish.');
});
+test('youtube publisher cleans up unusable downloads without starting an upload', function (int $status, string $body, string $message) {
+ $this->post->update([
+ 'media' => [[
+ 'id' => 'video-1',
+ 'path' => 'medias/video.mp4',
+ 'url' => 'https://example.com/video.mp4',
+ 'mime_type' => 'video/mp4',
+ 'original_filename' => 'video.mp4',
+ ]],
+ ]);
+ $tempFile = null;
+ $publisher = fakeYouTubeUpload([
+ 'https://example.com/video.mp4' => function (Request $request, array $options) use (&$tempFile, $status, $body) {
+ $tempFile = $options['sink'];
+
+ return Http::response($body, $status);
+ },
+ ]);
+
+ expect(fn () => $publisher->publish($this->postPlatform->fresh()))
+ ->toThrow(YouTubePublishException::class, $message);
+
+ $this->assertFileDoesNotExist($tempFile);
+ Http::assertSentCount(1);
+ Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/upload/youtube/v3/videos'));
+})->with([
+ 'failed download' => [503, '', 'Failed to download video for YouTube upload: HTTP 503'],
+ 'empty download' => [200, '', 'Downloaded video is too small or empty'],
+ 'incomplete download' => [200, 'video', 'Downloaded video is too small or empty'],
+]);
+
test('youtube publisher throws exception for non-video content', function () {
$this->post->update([
'media' => [
@@ -126,36 +291,55 @@ test('youtube publisher throws exception when no refresh token available', funct
->toThrow(TokenExpiredException::class, 'No refresh token available for YouTube account');
});
-test('youtube publisher throws exception on api init error', function () {
+test('youtube publisher reports Google upload errors', function (string $url, int $status, string $reason, string $exception, string $message) {
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
- 'url' => 'https://example.com/media/2026-01/test-video.mp4',
+ 'url' => 'https://example.com/video.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
],
],
]);
- Http::fake([
- 'https://www.googleapis.com/upload/youtube/v3/videos*' => Http::response([
+ $tempFile = null;
+ $publisher = fakeYouTubeUpload([
+ 'https://example.com/video.mp4' => function (Request $request, array $options) use (&$tempFile) {
+ $tempFile = $options['sink'];
+
+ return Http::response(str_repeat('x', 2048));
+ },
+ $url => Http::response([
'error' => [
+ 'code' => $status,
'message' => 'Invalid request',
+ 'errors' => [['reason' => $reason, 'message' => 'Invalid request']],
],
- ], 400),
+ ], $status),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
- ->toThrow(Exception::class);
-});
-
-// Note: Testing token expiration on auth error would require mocking file_get_contents
-// which is used to fetch video content. The token refresh test above covers the token
-// expiration handling. Full integration tests should cover the 401 error scenario.
+ expect(fn () => $publisher->publish($this->postPlatform->fresh()))
+ ->toThrow($exception, $message);
+ expect(app(Client::class)->shouldDefer())->toBeFalse();
+ $this->assertFileDoesNotExist($tempFile);
+
+ Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/upload/youtube/v3/videos'));
+})->with([
+ 'invalid description at initialization' => [
+ 'https://youtube.googleapis.com/upload/youtube/v3/videos*', 400, 'invalidDescription', YouTubePublishException::class, 'Video description is invalid.',
+ ],
+ 'expired token at initialization' => [
+ 'https://youtube.googleapis.com/upload/youtube/v3/videos*', 401, 'authError', TokenExpiredException::class, 'Invalid request',
+ ],
+ 'invalid description during upload' => [
+ 'https://upload.example.test/session', 400, 'invalidDescription', YouTubePublishException::class, 'Video description is invalid.',
+ ],
+]);
test('youtube publisher throws exception with null content', function () {
+ $this->postPlatform->update(['meta' => ['description' => 'A valid description is not a title']]);
$this->post->update([
'content' => null,
'media' => [
diff --git a/tests/Feature/UpdatePostRequestTest.php b/tests/Feature/UpdatePostRequestTest.php
index e83d96505..a03f7c7c4 100644
--- a/tests/Feature/UpdatePostRequestTest.php
+++ b/tests/Feature/UpdatePostRequestTest.php
@@ -8,11 +8,162 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\TikTok\PrivacyLevel;
use App\Enums\UserWorkspace\Role;
+use App\Jobs\PublishPost;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
+use Illuminate\Support\Facades\Queue;
+
+test('youtube description checks effective web metadata before scheduling or publishing', function (string $patch, bool $allowed, string $status) {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ $this->post->update([
+ 'content' => 'Short title',
+ 'status' => Status::Draft,
+ 'media' => $this->mediaPayload,
+ ]);
+ $this->postPlatform->update(['enabled' => false]);
+ $platform = PostPlatform::factory()->youtube()->create([
+ 'post_id' => $this->post->id,
+ 'social_account_id' => $account->id,
+ 'enabled' => true,
+ 'meta' => ['description' => str_repeat('a', 5001)],
+ ]);
+ $data = [
+ 'status' => $status,
+ 'scheduled_at' => now()->addHour()->toIso8601String(),
+ 'media' => $this->mediaPayload,
+ ];
+
+ if ($patch !== 'omit') {
+ $data['platforms'] = [['id' => $platform->id, 'content_type' => ContentType::YouTubeShort->value]];
+ if ($patch !== 'row') {
+ $data['platforms'][0]['meta'] = ['description' => $patch === 'clear' ? null : 'Valid description'];
+ }
+ }
+ Queue::fake();
+ $response = $this->actingAs($this->user)->put(route('app.posts.update', $this->post), $data);
+
+ if ($allowed) {
+ $response->assertSessionHasNoErrors();
+ expect($this->post->fresh()->status->value)->toBe($status);
+
+ if ($status === Status::Publishing->value) {
+ Queue::assertPushed(PublishPost::class);
+ }
+ } else {
+ $response->assertSessionHasErrors('platforms.0.meta.description');
+ expect($this->post->fresh()->status)->toBe(Status::Draft);
+ Queue::assertNotPushed(PublishPost::class);
+ }
+})->with([
+ 'stored invalid description' => ['omit', false],
+ 'retained invalid description' => ['row', false],
+ 'replaced description' => ['replace', true],
+ 'cleared description' => ['clear', true],
+])->with([Status::Scheduled->value, Status::Publishing->value]);
+
+test('youtube description reports and persists independent selected channel values', function () {
+ $platforms = collect(range(1, 2))->map(function () {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+
+ return PostPlatform::factory()->youtube()->create([
+ 'post_id' => $this->post->id,
+ 'social_account_id' => $account->id,
+ 'meta' => [],
+ ]);
+ });
+ $this->actingAs($this->user)->put(route('app.posts.update', $this->post), [
+ 'status' => Status::Draft->value,
+ 'platforms' => [
+ ['id' => $platforms[0]->id, 'meta' => ['description' => 'First channel']],
+ ['id' => $platforms[1]->id, 'meta' => ['description' => str_repeat('é', 2501)]],
+ ],
+ ])->assertSessionHasErrors('platforms.1.meta.description')->assertSessionDoesntHaveErrors('platforms.0.meta.description');
+ $this->actingAs($this->user)->put(route('app.posts.update', $this->post), [
+ 'status' => Status::Draft->value,
+ 'content' => 'Short title',
+ 'platforms' => [
+ ['id' => $platforms[0]->id, 'meta' => ['description' => 'First channel']],
+ ['id' => $platforms[1]->id, 'meta' => ['description' => str_repeat('é', 2500)]],
+ ],
+ ])->assertSessionHasNoErrors();
+ expect(data_get($platforms[0]->fresh()->meta, 'description'))->toBe('First channel')
+ ->and(data_get($platforms[1]->fresh()->meta, 'description'))->toBe(str_repeat('é', 2500))
+ ->and($this->post->fresh()->content)->toBe('Short title');
+});
+
+test('youtube description update reports one validation message', function (bool $hasSubmittedError) {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ $platform = PostPlatform::factory()->youtube()->create([
+ 'post_id' => $this->post->id,
+ 'social_account_id' => $account->id,
+ 'meta' => ['description' => str_repeat('a', 5001)],
+ ]);
+ $data = [
+ 'status' => Status::Scheduled->value,
+ 'scheduled_at' => now()->addHour()->toIso8601String(),
+ 'content' => 'Short title',
+ 'media' => $this->mediaPayload,
+ 'platforms' => [[
+ 'id' => $platform->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ ]],
+ ];
+ $key = 'platforms.0.meta.description';
+
+ if ($hasSubmittedError) {
+ $data['platforms'][0]['meta'] = ['description' => str_repeat('é', 2501)];
+ }
+
+ $this->actingAs($this->user)->put(route('app.posts.update', $this->post), $data)
+ ->assertSessionHasErrors($key);
+
+ expect(session('errors')->get($key))->toBe([
+ __('posts.form.youtube.description_max'),
+ ]);
+})->with([
+ 'stored invalid description' => [false],
+ 'submitted invalid description' => [true],
+]);
+
+test('youtube description validation keeps submitted channel order and rolls back updates', function () {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ $platform = PostPlatform::factory()->youtube()->create([
+ 'post_id' => $this->post->id,
+ 'social_account_id' => $account->id,
+ 'enabled' => true,
+ 'meta' => ['description' => str_repeat('a', 5001)],
+ ]);
+ $secondAccount = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ $secondPlatform = PostPlatform::factory()->youtube()->create([
+ 'post_id' => $this->post->id,
+ 'social_account_id' => $secondAccount->id,
+ 'enabled' => false,
+ 'meta' => ['description' => 'Valid description'],
+ ]);
+ $this->post->update(['content' => 'Original title']);
+
+ $this->actingAs($this->user)->put(route('app.posts.update', $this->post), [
+ 'status' => Status::Scheduled->value,
+ 'scheduled_at' => now()->addHour()->toIso8601String(),
+ 'content' => 'Changed title',
+ 'media' => $this->mediaPayload,
+ 'platforms' => [
+ ['id' => $secondPlatform->id, 'content_type' => ContentType::YouTubeShort->value],
+ ['id' => $platform->id, 'content_type' => ContentType::YouTubeShort->value],
+ ],
+ ])->assertSessionHasErrors('platforms.1.meta.description')
+ ->assertSessionDoesntHaveErrors('platforms.0.meta.description');
+
+ expect($this->post->fresh()->status)->toBe(Status::Draft)
+ ->and($this->post->fresh()->content)->toBe('Original title')
+ ->and($this->post->fresh()->scheduled_at)->toBeNull()
+ ->and($platform->fresh()->enabled)->toBeTrue()
+ ->and($secondPlatform->fresh()->enabled)->toBeFalse()
+ ->and($this->postPlatform->fresh()->enabled)->toBeTrue();
+});
beforeEach(function () {
$this->user = User::factory()->create();
diff --git a/tests/Feature/YouTubeDescriptionPreviewTest.php b/tests/Feature/YouTubeDescriptionPreviewTest.php
new file mode 100644
index 000000000..80a750a00
--- /dev/null
+++ b/tests/Feature/YouTubeDescriptionPreviewTest.php
@@ -0,0 +1,90 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Mcp\Servers\TryPostServer;
+use App\Mcp\Tools\Post\PreviewPostTool;
+use App\Models\Post;
+use App\Models\PostPlatform;
+use App\Models\SocialAccount;
+use App\Services\Post\PostPreviewer;
+use Illuminate\Testing\Fluent\AssertableJson;
+
+test('youtube description preview includes effective bytes without changing title length', function (mixed $description, string $expected) {
+ $post = Post::factory()->create(['content' => 'Title']);
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $post->workspace_id]);
+ PostPlatform::factory()->youtube()->create([
+ 'post_id' => $post->id,
+ 'social_account_id' => $account->id,
+ 'enabled' => true,
+ 'meta' => ['description' => $description],
+ ]);
+
+ $preview = app(PostPreviewer::class)->forPost($post->fresh())['platforms'][0];
+
+ expect($preview['description'])->toBe($expected)
+ ->and($preview['description_length_bytes'])->toBe(strlen($expected))
+ ->and($preview['sanitized_content'])->toBe('Title')
+ ->and($preview['sanitized_length'])->toBe(5)
+ ->and($preview['max_content_length'])->toBe(100);
+})->with([
+ 'custom description' => ['ação', 'ação'],
+ 'null description' => [null, 'Title'],
+ 'empty description' => ['', 'Title'],
+ 'whitespace description' => [" \t\n\u{00A0}", 'Title'],
+ 'invalid metadata type' => [['invalid'], 'Title'],
+]);
+
+test('other networks do not gain youtube description preview fields', function () {
+ $post = Post::factory()->create(['content' => 'Title']);
+ PostPlatform::factory()->create(['post_id' => $post->id, 'enabled' => true]);
+
+ $preview = app(PostPreviewer::class)->forPost($post->fresh())['platforms'][0];
+
+ expect($preview)->not->toHaveKeys(['description', 'description_length_bytes']);
+});
+
+test('API and MCP previews expose independent YouTube descriptions', function () {
+ $token = createApiTestToken();
+ $post = Post::factory()->create([
+ 'workspace_id' => $token['workspace']->id,
+ 'user_id' => $token['user']->id,
+ 'content' => 'Short title',
+ ]);
+ $platforms = collect(['First channel', 'Second channel'])->map(function (string $description) use ($post) {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $post->workspace_id]);
+
+ return PostPlatform::factory()->youtube()->create([
+ 'post_id' => $post->id,
+ 'social_account_id' => $account->id,
+ 'enabled' => true,
+ 'meta' => ['description' => $description],
+ ]);
+ });
+
+ $response = $this->withToken($token['plain_token'])
+ ->getJson(route('api.posts.preview', $post))
+ ->assertOk();
+
+ foreach ($platforms as $platform) {
+ $preview = collect($response->json('platforms'))->firstWhere('post_platform_id', $platform->id);
+
+ expect($preview['description'])->toBe($platform->meta['description'])
+ ->and($preview['description_length_bytes'])->toBe(strlen($platform->meta['description']))
+ ->and($preview['sanitized_content'])->toBe('Short title');
+ }
+
+ TryPostServer::actingAs($token['user'])->tool(PreviewPostTool::class, ['post_id' => $post->id])
+ ->assertOk()
+ ->assertStructuredContent(function (AssertableJson $json) use ($platforms) {
+ $json->etc();
+
+ foreach ($platforms as $platform) {
+ $preview = collect($json->toArray()['platforms'])->firstWhere('post_platform_id', $platform->id);
+
+ expect($preview['description'])->toBe($platform->meta['description'])
+ ->and($preview['description_length_bytes'])->toBe(strlen($platform->meta['description']))
+ ->and($preview['sanitized_content'])->toBe('Short title');
+ }
+ });
+});
diff --git a/tests/Unit/PostPlatformMetaRulesTest.php b/tests/Unit/PostPlatformMetaRulesTest.php
index 449eaf630..5a533d45b 100644
--- a/tests/Unit/PostPlatformMetaRulesTest.php
+++ b/tests/Unit/PostPlatformMetaRulesTest.php
@@ -18,15 +18,29 @@ test('custom meta messages only cover pinterest title and link', function () {
]);
});
-test('custom meta attributes only rename pinterest title and link', function () {
+test('custom meta attributes use translated field names', function () {
expect(PostPlatformMetaRules::attributes())->toBe([
'platforms.*.meta.title' => __('posts.form.pinterest.title'),
+ 'platforms.*.meta.description' => __('posts.form.youtube.description'),
'platforms.*.meta.link' => __('posts.form.pinterest.link'),
'platforms.*.meta.event.title' => __('posts.form.google_business.event_title'),
'platforms.*.meta.call_to_action.url' => __('posts.form.google_business.cta_url'),
]);
});
+test('shared description validation rejects multibyte overflow', function () {
+ $validator = Validator::make(['platforms' => [['meta' => ['description' => str_repeat('é', 2501)]]]], PostPlatformMetaRules::rules());
+ expect($validator->fails())->toBeTrue()
+ ->and($validator->errors()->has('platforms.0.meta.description'))->toBeTrue();
+});
+
+test('stored youtube description is checked without requiring it for other networks', function () {
+ expect(PostPlatformMetaRules::requiredMetaViolation(Platform::YouTube, ['description' => str_repeat('a', 5001)]))
+ ->toBe(['description', __('posts.form.youtube.description_max')])
+ ->and(PostPlatformMetaRules::requiredMetaViolation(Platform::YouTube, []))->toBeNull()
+ ->and(PostPlatformMetaRules::requiredMetaViolation(Platform::Facebook, []))->toBeNull();
+});
+
test('shared meta rules still include non-pinterest platform fields', function () {
$rules = PostPlatformMetaRules::rules();
diff --git a/tests/Unit/Support/YouTubeDescriptionTest.php b/tests/Unit/Support/YouTubeDescriptionTest.php
new file mode 100644
index 000000000..581d9027d
--- /dev/null
+++ b/tests/Unit/Support/YouTubeDescriptionTest.php
@@ -0,0 +1,41 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Support\YouTubeDescription;
+
+test('youtube description validates text and byte limits', function (mixed $text, ?string $key) {
+ expect(YouTubeDescription::violation($text))->toBe($key);
+})->with([
+ 'absent' => [null, null],
+ 'empty' => ['', null],
+ 'ascii boundary' => [str_repeat('a', 5000), null],
+ 'ascii overflow' => [str_repeat('a', 5001), 'posts.form.youtube.description_max'],
+ 'accent boundary' => [str_repeat('é', 2500), null],
+ 'accent overflow' => [str_repeat('é', 2500).'a', 'posts.form.youtube.description_max'],
+ 'emoji boundary' => [str_repeat('😀', 1250), null],
+ 'emoji overflow' => [str_repeat('😀', 1250).'a', 'posts.form.youtube.description_max'],
+ 'multiline url' => ["Line one\n\nhttps://example.com\n#video", null],
+ 'opening bracket' => ['a < b', null],
+ 'closing bracket' => ['a > b', null],
+ 'literal markup' => ['<p>Text about HTML</p>', null],
+ 'invalid utf8' => ["\xC3\x28", 'posts.form.youtube.description_invalid'],
+ 'non string' => [['text'], 'posts.form.youtube.description_invalid'],
+]);
+
+test('youtube description resolves legacy and cleared metadata', function (mixed $description, string $expected) {
+ expect(YouTubeDescription::resolve(['description' => $description], 'Title'))->toBe($expected);
+})->with([
+ 'null description' => [null, 'Title'],
+ 'empty description' => ['', 'Title'],
+ 'blank description' => [" \n ", 'Title'],
+ 'non-breaking spaces' => ["\u{00A0}\u{00A0}", 'Title'],
+ 'invalid metadata type' => [['invalid'], 'Title'],
+ 'custom description' => ['Custom', 'Custom'],
+ 'surrounding whitespace' => [" Custom\ntext ", " Custom\ntext "],
+]);
+
+test('youtube description resolves absent metadata and content', function () {
+ expect(YouTubeDescription::resolve(null, 'Title'))->toBe('Title')
+ ->and(YouTubeDescription::resolve([], null))->toBe('');
+});