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.

Let Instagram Reels and YouTube Shorts take a custom cover image (#505)

Paulo Castellanocc87931fc28c
diff --git a/.ai/rules/social.md b/.ai/rules/social.md
index 49961f621..ba4f60da0 100644
--- a/.ai/rules/social.md
+++ b/.ai/rules/social.md
@@ -22,4 +22,4 @@ Google fetches Local Post sourceUrl after create while LocalPostState is Process
Bluesky/Mastodon/X thread segments already live are checkpointed in posts.error_context.thread_progress (ThreadProgress) after each segment, so any retry (incl. posts:retry, which keeps them) resumes from the next segment. A resume keeps the stored root hash: the root is the post's identity even if the same text would now hash differently. Never clear thread_progress on retry and never re-post a checkpointed segment. thread_reply_ids lists the reply ids so ImportExternalPosts skips TryPost's own replies.
## No server-side aspect ratio crop or meta.aspect_ratio
-Removed October 2026 by user decision: the Facebook and Instagram publishers send every image at its own ratio, and there is no `meta.aspect_ratio` (rule, enum, crop helper and composer radios are gone; migration 2026_10_04_202400 strips stored keys; the one-off 2.0 release step that baked pending crops into the media was removed after TryPost 2.0). Instagram feed images outside 3:4–1.91:1 are caught at save by ContentTypeCompatibleWithMedia and fixed per image in the media editor; Facebook feed accepts any ratio. Stories still go through FitsImageToCanvas. Do not reintroduce a ratio selector or a publish-time crop.
+Removed October 2026 by user decision: the Facebook and Instagram publishers send every image at its own ratio, and there is no `meta.aspect_ratio` (rule, enum, crop helper and composer radios are gone; migration 2026_10_04_202400 strips stored keys; the one-off 2.0 release step that baked pending crops into the media was removed after TryPost 2.0). Instagram feed images outside 3:4–1.91:1 are caught at save by ContentTypeCompatibleWithMedia and fixed per image in the media editor; Facebook feed accepts any ratio. Stories still go through HostsProcessedImages::fitImageToCanvas(). Do not reintroduce a ratio selector or a publish-time crop.
diff --git a/app/Actions/Media/AuditMedia.php b/app/Actions/Media/AuditMedia.php
index 5a2b186c1..e5de831d5 100644
--- a/app/Actions/Media/AuditMedia.php
+++ b/app/Actions/Media/AuditMedia.php
@@ -119,7 +119,8 @@ class AuditMedia
foreach ($owners as $model) {
$ownedIds = $owned->get($model->id, []);
- $jsonIds = collect($model->media ?? [])->pluck('id')->filter()->unique()->values()->all();
+ $items = collect($model->media ?? []);
+ $jsonIds = $items->pluck('id')->merge($items->pluck('meta.cover.id'))->filter()->unique()->values()->all();
foreach (array_diff($jsonIds, $ownedIds) as $mediaId) {
$findings[] = ['owner_type' => $type, 'owner_id' => $model->id, 'media_id' => (string) $mediaId, 'problem' => 'json_without_row'];
diff --git a/app/Actions/Media/SyncOwnedMedia.php b/app/Actions/Media/SyncOwnedMedia.php
index 8606603d8..6c2433a0d 100644
--- a/app/Actions/Media/SyncOwnedMedia.php
+++ b/app/Actions/Media/SyncOwnedMedia.php
@@ -11,6 +11,9 @@ use App\Models\Post;
use App\Support\Media\MediaCopyBatch;
use App\Support\ThreadReplies;
use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Arr;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
@@ -27,7 +30,13 @@ class SyncOwnedMedia
/**
* Per-owner edits an item may carry over the row's measured `meta`.
*/
- public const array EDITABLE_META = ['alt_text', 'user_tags', 'cover_offset_ms'];
+ public const array EDITABLE_META = ['alt_text', 'user_tags', 'cover_offset_ms', 'cover_source'];
+
+ /**
+ * Everything an item carries for its owner over the row's `meta`: the
+ * edits and the image picked as a video's cover (`cover`, a row of its own).
+ */
+ public const array OWNER_META = [...self::EDITABLE_META, 'cover'];
/**
* Row `meta` keys that only describe the row's history and stay off the item.
@@ -39,6 +48,27 @@ class SyncOwnedMedia
*/
private const array ITEM_FIELDS = ['source', 'source_meta'];
+ /**
+ * The order the next item takes among the owner's rows, across its own
+ * media and its thread replies'.
+ */
+ private int $position = 0;
+
+ /**
+ * @param Collection<string, Media> $rows the submitted ids' rows
+ * @param Collection<string, Media> $uploads the submitted upload tokens' rows
+ * @param Collection<string, array<string, mixed>> $passThrough stored items that may stay without a row, by id
+ */
+ private function __construct(
+ private readonly Post|Idea $owner,
+ private readonly string $ownerColumn,
+ private readonly bool $keepsCovers,
+ private readonly MediaCopyBatch $batch,
+ private readonly Collection $rows,
+ private readonly Collection $uploads,
+ private readonly Collection $passThrough,
+ ) {}
+
/**
* Call inside the transaction of `MediaCopyBatch::run()`. Locks the owner,
* then every media row it touches (its own and the sources) in id order,
@@ -61,93 +91,147 @@ class SyncOwnedMedia
*/
public static function execute(Post|Idea $owner, array $items, MediaCopyBatch $batch, string $errorKey = 'media', array $legacyItems = [], string $metaErrorKey = 'meta'): array
{
- $ownerColumn = $owner instanceof Post ? 'post_id' : 'idea_id';
+ $ownerColumn = self::ownerColumn($owner);
$locked = $owner::query()->whereKey($owner->getKey())->lockForUpdate()->firstOrFail();
$workspace = $owner->workspace;
$items = self::withoutRepeats(array_values($items));
- $replies = $locked instanceof Post ? ThreadReplies::of($locked->meta) : [];
- $submitted = [...$items, ...self::replyMedia($replies)];
- $ids = self::column($submitted, 'id');
- $uploadTokens = self::column($submitted, 'upload_token');
+ $replies = self::repliesOf($locked);
+ $submitted = [...$items, ...MediaItem::covers($items), ...self::replyMedia($replies)];
+ $ids = self::uuids($submitted, 'id');
+ $uploadTokens = self::uuids($submitted, 'upload_token');
self::lockRows($workspace->id, $ownerColumn, $owner->getKey(), $ids, $uploadTokens);
- $rows = ResolveWorkspaceMedia::execute($workspace, $ids, lockForUpdate: true);
- $tokens = ResolveWorkspaceMedia::byUploadTokens($workspace, $uploadTokens, lockForUpdate: true);
- $passThrough = collect([...$legacyItems, ...($locked->media ?? [])])
- ->filter(fn (mixed $item): bool => is_array($item))
- ->keyBy(fn (array $item): string => (string) data_get($item, 'id'));
-
- $position = 0;
- $sync = function (array $items, string $errorKey) use ($owner, $ownerColumn, $batch, $rows, $tokens, $passThrough, &$position): array {
- $final = [];
-
- foreach ($items as $index => $item) {
- $token = data_get($item, 'upload_token');
- $source = filled($token)
- ? ($tokens->get($token) ?? self::spentTokenSource($rows->get(data_get($item, 'id')), $ownerColumn, $owner, $batch))
- : $rows->get(data_get($item, 'id'));
- $key = "{$errorKey}.{$index}";
-
- if ($source === null && ! filled($token) && $passThrough->has((string) data_get($item, 'id'))) {
- $final[] = self::withEdits($passThrough->get((string) data_get($item, 'id')), $item);
- $position++;
-
- continue;
- }
-
- if ($source === null) {
- throw ValidationException::withMessages([$key => filled($token)
- ? __('posts.errors.media_expired')
- : __('validation.exists', ['attribute' => 'media'])]);
- }
-
- $owned = match (true) {
- $source->{$ownerColumn} === $owner->getKey() => self::ordered($source, $position),
- $batch->canMove($source) => self::adopt($source, $ownerColumn, $owner, $batch, $position),
- default => self::copy($source, $ownerColumn, $owner, $batch, $position, $key),
- };
- $position++;
-
- $final[] = self::withEdits(self::item($owned), $item);
- }
-
- return $final;
- };
-
- $final = $sync($items, $errorKey);
+ $stored = [...$legacyItems, ...($locked->media ?? [])];
+ $sync = new self(
+ owner: $owner,
+ ownerColumn: $ownerColumn,
+ keepsCovers: self::keepsCovers($locked),
+ batch: $batch,
+ rows: ResolveWorkspaceMedia::execute($workspace, $ids, lockForUpdate: true),
+ uploads: ResolveWorkspaceMedia::byUploadTokens($workspace, $uploadTokens, lockForUpdate: true),
+ passThrough: collect([...$stored, ...MediaItem::covers($stored)])
+ ->filter(fn (mixed $item): bool => is_array($item))
+ ->keyBy(fn (array $item): string => (string) data_get($item, 'id')),
+ );
+
+ $final = $sync->items($items, $errorKey);
$replies = collect($replies)
->map(fn (array $reply, int $index): array => [
...$reply,
- 'media' => $sync(self::withoutRepeats($reply['media']), "{$metaErrorKey}.thread_replies.{$index}.media"),
+ 'media' => $sync->items(self::withoutRepeats(self::withoutCovers($reply['media'])), "{$metaErrorKey}.thread_replies.{$index}.media"),
])
->all();
- $kept = self::column([...$final, ...self::replyMedia($replies)], 'id');
+ $kept = self::uuids([...$final, ...MediaItem::covers($final), ...self::replyMedia($replies)], 'id');
DeleteOwnedMedia::forRows($owner->ownedMedia()->whereNotIn('id', $kept)->pluck('id')->all());
- $owner->update($replies === [] ? ['media' => $final] : [
- 'media' => $final,
- 'meta' => [...($locked->meta ?? []), 'thread_replies' => $replies],
- ]);
+ $owner->update(self::attributes($locked, $final, $replies));
return $final;
}
/**
- * @param list<string> $ids
- * @param list<string> $uploadTokens
+ * @param array<int, array<string, mixed>> $items
+ * @return list<array<string, mixed>>
*/
- private static function lockRows(string $workspaceId, string $ownerColumn, string $ownerId, array $ids, array $uploadTokens): void
+ private function items(array $items, string $errorKey): array
{
- Media::query()
- ->where('workspace_id', $workspaceId)
- ->where(fn (Builder $query) => $query
- ->where($ownerColumn, $ownerId)
- ->when($ids !== [], fn (Builder $query) => $query->orWhereIn('id', $ids))
- ->when($uploadTokens !== [], fn (Builder $query) => $query->orWhereIn('upload_token', $uploadTokens)))
- ->orderBy('id')
- ->lockForUpdate()
- ->pluck('id');
+ $final = [];
+
+ foreach ($items as $index => $item) {
+ $final[] = $this->item($item, "{$errorKey}.{$index}");
+ $this->position++;
+ }
+
+ return $final;
+ }
+
+ /**
+ * One submitted item as stored: its row, the per-owner edits, and the
+ * cover image when the owner keeps one. A cover source means nothing
+ * without its cover, so it goes when the cover does.
+ *
+ * @param array<string, mixed> $item
+ * @return array<string, mixed>
+ */
+ private function item(array $item, string $key): array
+ {
+ $owned = self::withEdits(Arr::except($this->own($item, $key), 'meta.cover'), $item);
+ $cover = $this->cover($item, "{$key}.meta.cover");
+
+ if (blank($cover)) {
+ Arr::forget($owned, 'meta.cover_source');
+
+ return $owned;
+ }
+
+ data_set($owned, 'meta.cover', $cover);
+
+ return $owned;
+ }
+
+ /**
+ * The cover image of a submitted video, owned like the video and at its
+ * position.
+ *
+ * @param array<string, mixed> $item
+ * @return array<string, mixed>|null
+ *
+ * @throws ValidationException
+ */
+ private function cover(array $item, string $key): ?array
+ {
+ $cover = data_get($item, 'meta.cover');
+
+ if (! $this->keepsCovers || ! is_array($cover)) {
+ return null;
+ }
+
+ return self::coverItem($this->own($cover, $key), $key);
+ }
+
+ /**
+ * The submitted item as a row of the owner (kept, adopted or copied), or
+ * the stored item itself when it has no row left and may stay as it is.
+ *
+ * @param array<string, mixed> $item
+ * @return array<string, mixed>
+ *
+ * @throws ValidationException
+ */
+ private function own(array $item, string $key): array
+ {
+ $source = $this->source($item);
+
+ if (filled($source)) {
+ return self::itemOf($this->ownedRow($source, $key));
+ }
+
+ $id = (string) data_get($item, 'id');
+
+ if (blank(data_get($item, 'upload_token')) && $this->passThrough->has($id)) {
+ return $this->passThrough->get($id);
+ }
+
+ throw ValidationException::withMessages([$key => self::missingSourceMessage($item)]);
+ }
+
+ /**
+ * The row a submitted item stands for: its upload when it carries a token,
+ * else the row of its id.
+ *
+ * @param array<string, mixed> $item
+ */
+ private function source(array $item): ?Media
+ {
+ $row = $this->rows->get(data_get($item, 'id'));
+ $token = data_get($item, 'upload_token');
+
+ if (blank($token)) {
+ return $row;
+ }
+
+ return $this->uploads->get($token) ?? $this->spentTokenSource($row);
}
/**
@@ -156,31 +240,64 @@ class SyncOwnedMedia
* (one upload shared by several posts). Anyone else holding it means the
* upload was consumed by another save.
*/
- private static function spentTokenSource(?Media $row, string $ownerColumn, Post|Idea $owner, MediaCopyBatch $batch): ?Media
+ private function spentTokenSource(?Media $row): ?Media
+ {
+ if (blank($row)) {
+ return null;
+ }
+
+ if ($this->ownsRow($row)) {
+ return $row;
+ }
+
+ if ($this->batch->wasMoved($row->id)) {
+ return $row;
+ }
+
+ return null;
+ }
+
+ /**
+ * @throws ValidationException
+ */
+ private function ownedRow(Media $source, string $key): Media
{
- return $row !== null && ($row->{$ownerColumn} === $owner->getKey() || $batch->wasMoved($row->id)) ? $row : null;
+ if ($this->ownsRow($source)) {
+ return $this->ordered($source);
+ }
+
+ if ($this->batch->canMove($source)) {
+ return $this->adopt($source);
+ }
+
+ return $this->copy($source, $key);
+ }
+
+ private function ownsRow(Media $row): bool
+ {
+ return $row->{$this->ownerColumn} === $this->owner->getKey();
}
- private static function ordered(Media $owned, int $position): Media
+ private function ordered(Media $owned): Media
{
- if ($owned->order !== $position) {
- $owned->update(['order' => $position]);
+ if ($owned->order !== $this->position) {
+ $owned->update(['order' => $this->position]);
}
return $owned;
}
- private static function adopt(Media $source, string $ownerColumn, Post|Idea $owner, MediaCopyBatch $batch, int $position): Media
+ private function adopt(Media $source): Media
{
$source->update([
- $ownerColumn => $owner->getKey(),
+ $this->ownerColumn => $this->owner->getKey(),
'mediable_type' => null,
'mediable_id' => null,
'collection' => Media::COLLECTION_MEDIA,
'upload_token' => null,
- 'order' => $position,
+ 'order' => $this->position,
]);
- $batch->rememberMove($source->id);
+ $this->batch->rememberMove($source->id);
return $source;
}
@@ -188,27 +305,22 @@ class SyncOwnedMedia
/**
* A source whose file can no longer be copied fails its item like an
* expired upload; no row is created for it.
+ *
+ * @throws ValidationException
*/
- private static function copy(Media $source, string $ownerColumn, Post|Idea $owner, MediaCopyBatch $batch, int $position, string $errorKey): Media
+ private function copy(Media $source, string $key): Media
{
- $extension = pathinfo($source->path, PATHINFO_EXTENSION);
- $path = 'medias/'.Str::uuid().($extension !== '' ? ".{$extension}" : '');
+ $path = self::copyPath($source->path);
- try {
- $copied = Storage::copy($source->path, $path);
- } catch (UnableToCopyFile) {
- $copied = false;
- }
-
- if (! $copied) {
- throw ValidationException::withMessages([$errorKey => __('posts.errors.media_expired')]);
+ if (! self::copyFile($source->path, $path)) {
+ throw ValidationException::withMessages([$key => __('posts.errors.media_expired')]);
}
- $batch->rememberCopy($path);
+ $this->batch->rememberCopy($path);
return Media::query()->create([
- 'workspace_id' => $owner->workspace_id,
- $ownerColumn => $owner->getKey(),
+ 'workspace_id' => $this->owner->workspace_id,
+ $this->ownerColumn => $this->owner->getKey(),
'group_id' => (string) Str::uuid(),
'collection' => Media::COLLECTION_MEDIA,
'type' => $source->type,
@@ -216,46 +328,92 @@ class SyncOwnedMedia
'original_filename' => $source->original_filename,
'mime_type' => $source->mime_type,
'size' => $source->size,
- 'order' => $position,
+ 'order' => $this->position,
'meta' => [...($source->meta ?? []), 'copied_from' => $source->id],
]);
}
+ private static function copyPath(string $sourcePath): string
+ {
+ $path = 'medias/'.Str::uuid();
+ $extension = File::extension($sourcePath);
+
+ if (blank($extension)) {
+ return $path;
+ }
+
+ return "{$path}.{$extension}";
+ }
+
+ private static function copyFile(string $from, string $to): bool
+ {
+ try {
+ return Storage::copy($from, $to);
+ } catch (UnableToCopyFile) {
+ return false;
+ }
+ }
+
/**
- * Keeps the first occurrence of an id or upload token, with its index.
- *
- * @param list<array<string, mixed>> $items
- * @return array<int, array<string, mixed>>
+ * @param array<string, mixed> $item
*/
- private static function withoutRepeats(array $items): array
+ private static function missingSourceMessage(array $item): string
{
- $seen = [];
-
- return array_filter($items, function (array $item) use (&$seen): bool {
- $identity = filled(data_get($item, 'upload_token'))
- ? 'token:'.data_get($item, 'upload_token')
- : 'id:'.data_get($item, 'id');
+ if (filled(data_get($item, 'upload_token'))) {
+ return __('posts.errors.media_expired');
+ }
- if (isset($seen[$identity])) {
- return false;
- }
+ return __('validation.exists', ['attribute' => 'media']);
+ }
- $seen[$identity] = true;
+ /**
+ * The cover as stored under its video: a still image, the file only,
+ * without per-owner edits or the composer's source fields.
+ *
+ * @param array<string, mixed> $owned
+ * @return array<string, mixed>
+ *
+ * @throws ValidationException
+ */
+ private static function coverItem(array $owned, string $key): array
+ {
+ if (! MediaItem::fromArray($owned)->isStillImage()) {
+ throw ValidationException::withMessages([$key => __('posts.errors.cover_not_image')]);
+ }
- return true;
- });
+ return self::withMeta(
+ Arr::except($owned, [...self::ITEM_FIELDS, 'upload_token', 'meta']),
+ Arr::except((array) data_get($owned, 'meta', []), self::OWNER_META),
+ );
}
/**
* @return array<string, mixed>
*/
- private static function item(Media $owned): array
+ private static function itemOf(Media $owned): array
{
$item = MediaItem::fromMedia($owned)->toArray();
- $meta = array_diff_key((array) data_get($item, 'meta', []), array_flip(self::ROW_ONLY_META));
- unset($item['meta']);
- return $meta === [] ? $item : [...$item, 'meta' => $meta];
+ return self::withMeta(
+ Arr::except($item, 'meta'),
+ Arr::except((array) data_get($item, 'meta', []), self::ROW_ONLY_META),
+ );
+ }
+
+ /**
+ * An item with its `meta`, left off when there is none.
+ *
+ * @param array<string, mixed> $item
+ * @param array<string, mixed> $meta
+ * @return array<string, mixed>
+ */
+ private static function withMeta(array $item, array $meta): array
+ {
+ if (blank($meta)) {
+ return $item;
+ }
+
+ return [...$item, 'meta' => $meta];
}
/**
@@ -265,23 +423,131 @@ class SyncOwnedMedia
*/
private static function withEdits(array $owned, array $submitted): array
{
- $edits = array_intersect_key((array) data_get($submitted, 'meta', []), array_flip(self::EDITABLE_META));
+ $edits = Arr::only((array) data_get($submitted, 'meta', []), self::EDITABLE_META);
if (is_numeric(data_get($edits, 'cover_offset_ms'))) {
$edits['cover_offset_ms'] = (int) $edits['cover_offset_ms'];
}
- if ($edits !== []) {
- $owned['meta'] = [...((array) data_get($owned, 'meta', [])), ...$edits];
+ if (filled($edits)) {
+ $owned['meta'] = [...(array) data_get($owned, 'meta', []), ...$edits];
}
- foreach (self::ITEM_FIELDS as $field) {
- if (array_key_exists($field, $submitted)) {
- $owned[$field] = $submitted[$field];
- }
+ return [...$owned, ...Arr::only($submitted, self::ITEM_FIELDS)];
+ }
+
+ /**
+ * @param list<string> $ids
+ * @param list<string> $uploadTokens
+ */
+ private static function lockRows(string $workspaceId, string $ownerColumn, string $ownerId, array $ids, array $uploadTokens): void
+ {
+ Media::query()
+ ->where('workspace_id', $workspaceId)
+ ->where(fn (Builder $query) => $query
+ ->where($ownerColumn, $ownerId)
+ ->when(filled($ids), fn (Builder $query) => $query->orWhereIn('id', $ids))
+ ->when(filled($uploadTokens), fn (Builder $query) => $query->orWhereIn('upload_token', $uploadTokens)))
+ ->orderBy('id')
+ ->lockForUpdate()
+ ->pluck('id');
+ }
+
+ private static function ownerColumn(Post|Idea $owner): string
+ {
+ if ($owner instanceof Post) {
+ return 'post_id';
}
- return $owned;
+ return 'idea_id';
+ }
+
+ /**
+ * @return list<array<string, mixed>>
+ */
+ private static function repliesOf(Post|Idea $owner): array
+ {
+ if ($owner instanceof Post) {
+ return ThreadReplies::of($owner->meta);
+ }
+
+ return [];
+ }
+
+ /**
+ * Only a post whose network takes a cover image keeps one: an idea keeps
+ * it for the post it becomes, and a post on a network that only takes a
+ * frame (TikTok, a Pinterest pin, an Instagram feed video) drops it, as
+ * `PostMeta::forChannel()` drops a poll on any other type.
+ */
+ private static function keepsCovers(Post|Idea $owner): bool
+ {
+ if ($owner instanceof Idea) {
+ return true;
+ }
+
+ return (bool) $owner->content_type?->supportsCustomVideoCover();
+ }
+
+ /**
+ * What the owner stores: its media, and its thread replies' media written
+ * back into its meta when it has replies.
+ *
+ * @param list<array<string, mixed>> $media
+ * @param list<array<string, mixed>> $replies
+ * @return array<string, mixed>
+ */
+ private static function attributes(Post|Idea $locked, array $media, array $replies): array
+ {
+ if (blank($replies)) {
+ return ['media' => $media];
+ }
+
+ return [
+ 'media' => $media,
+ 'meta' => [...($locked->meta ?? []), 'thread_replies' => $replies],
+ ];
+ }
+
+ /**
+ * A thread reply's video takes no cover image: only a post's own video
+ * publishes with one.
+ *
+ * @param list<array<string, mixed>> $items
+ * @return list<array<string, mixed>>
+ */
+ private static function withoutCovers(array $items): array
+ {
+ return collect($items)
+ ->map(fn (array $item): array => Arr::except($item, 'meta.cover'))
+ ->all();
+ }
+
+ /**
+ * Keeps the first occurrence of an id or upload token, with its index.
+ *
+ * @param list<array<string, mixed>> $items
+ * @return array<int, array<string, mixed>>
+ */
+ private static function withoutRepeats(array $items): array
+ {
+ return collect($items)
+ ->unique(fn (array $item): string => self::identity($item))
+ ->all();
+ }
+
+ /**
+ * @param array<string, mixed> $item
+ */
+ private static function identity(array $item): string
+ {
+ $token = data_get($item, 'upload_token');
+
+ if (filled($token)) {
+ return "token:{$token}";
+ }
+
+ return 'id:'.data_get($item, 'id');
}
/**
@@ -290,18 +556,19 @@ class SyncOwnedMedia
*/
private static function replyMedia(array $replies): array
{
- return array_merge([], ...array_column($replies, 'media'));
+ return collect($replies)->pluck('media')->flatten(1)->all();
}
/**
* @param list<array<string, mixed>> $items
* @return list<string>
*/
- private static function column(array $items, string $key): array
+ private static function uuids(array $items, string $key): array
{
- return array_values(array_filter(
- array_map(fn (array $item): mixed => data_get($item, $key), $items),
- fn (mixed $value): bool => is_string($value) && Str::isUuid($value),
- ));
+ return collect($items)
+ ->map(fn (array $item): mixed => data_get($item, $key))
+ ->filter(fn (mixed $value): bool => is_string($value) && Str::isUuid($value))
+ ->values()
+ ->all();
}
}
diff --git a/app/Actions/Post/HostInlineMedia.php b/app/Actions/Post/HostInlineMedia.php
index 28585886a..a2fa79263 100644
--- a/app/Actions/Post/HostInlineMedia.php
+++ b/app/Actions/Post/HostInlineMedia.php
@@ -12,12 +12,48 @@ use App\Enums\Media\Type as MediaType;
use App\Models\Media;
use App\Models\Workspace;
use App\Services\Post\MediaAttacher;
+use Illuminate\Support\Arr;
+use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
+/**
+ * Resolves the API/MCP media references of a post into whole hosted items.
+ * An `upload_token` finds a temporary upload (the item keeps the token, so
+ * the save consumes it under a row lock and a second use fails), an `id` a
+ * media row of the workspace and a `url` is downloaded as a new temporary
+ * upload, once per distinct URL of the request. The save that follows moves
+ * the row to its first owner and copies it for the next ones.
+ *
+ * An item that cannot be resolved rejects the request (422) and deletes every
+ * download of the request so far. Downloads left behind by a later failure of
+ * the save stay temporary uploads that `media:prune-uploads` removes.
+ */
class HostInlineMedia
{
+ /**
+ * The row each URL of this request was downloaded to, so a URL used by
+ * several items or destinations is downloaded once.
+ *
+ * @var array<string, string>
+ */
+ private array $downloads = [];
+
+ /**
+ * The uploads and rows the list being hosted refers to.
+ *
+ * @var Collection<string, Media>
+ */
+ private Collection $byToken;
+
+ /**
+ * @var Collection<string, Media>
+ */
+ private Collection $byId;
+
+ private function __construct(private readonly Workspace $workspace) {}
+
/**
* Host the shared media and every destination's own media of a batch
* composition in one go, so a URL used by several destinations is
@@ -30,27 +66,21 @@ class HostInlineMedia
*/
public static function forBatch(Workspace $workspace, array $data): array
{
- $fetched = [];
+ $host = new self($workspace);
- if (array_key_exists('media', $data)) {
- $data['media'] = self::execute($workspace, MediaType::cases(), $data['media'], fetched: $fetched);
+ if (Arr::exists($data, 'media')) {
+ $data['media'] = $host->media(MediaType::cases(), $data['media'], 'media');
}
foreach (data_get($data, 'destinations', []) as $index => $destination) {
- if (array_key_exists('media', $destination)) {
- $data['destinations'][$index]['media'] = self::execute(
- $workspace,
- MediaType::cases(),
- $destination['media'],
- "destinations.{$index}.media",
- $fetched,
- );
+ if (Arr::exists($destination, 'media')) {
+ $data['destinations'][$index]['media'] = $host->media(MediaType::cases(), $destination['media'], "destinations.{$index}.media");
}
}
foreach (data_get($data, 'destinations', []) as $index => $destination) {
if (is_array(data_get($destination, 'meta'))) {
- $data['destinations'][$index]['meta'] = self::threadReplies($workspace, data_get($destination, 'meta'), "destinations.{$index}.meta", $fetched);
+ $data['destinations'][$index]['meta'] = $host->threadReplies($destination['meta'], "destinations.{$index}.meta");
}
}
@@ -70,137 +100,259 @@ class HostInlineMedia
*/
public static function forPost(Workspace $workspace, array $allowedTypes, array $data): array
{
- $fetched = [];
+ $host = new self($workspace);
- if (array_key_exists('media', $data)) {
- $data['media'] = self::execute($workspace, $allowedTypes, $data['media'], fetched: $fetched);
+ if (Arr::exists($data, 'media')) {
+ $data['media'] = $host->media($allowedTypes, $data['media'], 'media');
}
if (is_array(data_get($data, 'meta'))) {
- $data['meta'] = self::threadReplies($workspace, data_get($data, 'meta'), 'meta', $fetched);
+ $data['meta'] = $host->threadReplies($data['meta'], 'meta');
}
return $data;
}
/**
- * Resolve the API/MCP media references of a post into whole hosted items.
- * An `upload_token` finds a temporary upload (the item keeps the token, so
- * the save consumes it under a row lock and a second use fails), an `id` a
- * media row of the workspace and a `url` is downloaded as a new temporary
- * upload, once per distinct URL (`$fetched` maps URL to row id and is
- * shared across the calls of one request). The save that follows moves the
- * row to its first owner and copies it for the next ones.
- *
- * `validated()` can return the items out of order when their shapes differ
- * (it fills one rule at a time), so the list is put back in index order.
+ * The row as the composer shape the save validates, with the client's
+ * editable meta (alt text, user tags, cover offset and source) on top of
+ * what is stored. The `alt` shorthand only applies to images, and never
+ * over an `alt_text` sent in `meta`.
*
- * An item that cannot be resolved rejects the request (422) and deletes
- * every download of the request so far. Downloads left behind by a later
- * failure of the save stay temporary uploads that `media:prune-uploads`
- * removes.
+ * @param array<string, mixed> $reference
+ * @return array<string, mixed>
+ */
+ public static function item(Media $row, array $reference): array
+ {
+ $item = MediaItem::fromMedia($row)->toArray();
+ $edits = Arr::only((array) data_get($reference, 'meta', []), SyncOwnedMedia::EDITABLE_META);
+ $item['meta'] = [...(array) data_get($item, 'meta', []), ...self::withAltShorthand($row, $edits, $reference)];
+
+ return $item;
+ }
+
+ /**
+ * One list of references as hosted items, in index order: `validated()`
+ * can return the items out of order when their shapes differ (it fills one
+ * rule at a time).
*
* @param array<MediaType> $allowedTypes
* @param array<int, array<string, mixed>> $media
- * @param array<string, string> $fetched
* @return array<int, array<string, mixed>>
*
* @throws ValidationException
*/
- public static function execute(Workspace $workspace, array $allowedTypes, array $media, string $errorKey = 'media', array &$fetched = []): array
+ private function media(array $allowedTypes, array $media, string $errorKey): array
{
- if ($media === []) {
+ if (blank($media)) {
return $media;
}
$media = collect($media)->sortKeys()->values()->all();
- $byToken = ResolveWorkspaceMedia::byUploadTokens($workspace, self::column($media, 'upload_token'));
- $byId = ResolveWorkspaceMedia::execute($workspace, array_values(array_filter(self::column($media, 'id'), Str::isUuid(...))));
+ $this->resolveReferences([...$media, ...MediaItem::covers($media)]);
try {
- return collect($media)->map(function (array $item, int $index) use ($workspace, $allowedTypes, $errorKey, $byToken, $byId, &$fetched): array {
- $key = "{$errorKey}.{$index}";
+ return collect($media)
+ ->map(fn (array $item, int $index): array => $this->withCover($this->host($allowedTypes, $item, "{$errorKey}.{$index}"), $item, "{$errorKey}.{$index}.meta.cover"))
+ ->all();
+ } catch (ValidationException $exception) {
+ $this->forgetDownloads();
+
+ throw $exception;
+ }
+ }
+
+ /**
+ * A video's cover (`meta.cover`), hosted like the video: always an image.
+ *
+ * @param array<string, mixed> $hosted
+ * @param array<string, mixed> $item
+ * @return array<string, mixed>
+ *
+ * @throws ValidationException
+ */
+ private function withCover(array $hosted, array $item, string $key): array
+ {
+ $cover = data_get($item, 'meta.cover');
- if (filled($token = data_get($item, 'upload_token'))) {
- $row = $byToken->get($token) ?? throw ValidationException::withMessages(["{$key}.upload_token" => __('posts.errors.media_expired')]);
+ if (! is_array($cover)) {
+ return $hosted;
+ }
- return [...self::item($row, $item), 'upload_token' => $token];
- }
+ data_set($hosted, 'meta.cover', $this->host([MediaType::Image], $cover, $key));
- if (filled($id = data_get($item, 'id'))) {
- $row = $byId->get($id) ?? throw ValidationException::withMessages(["{$key}.id" => __('validation.exists', ['attribute' => 'media'])]);
+ return $hosted;
+ }
- return self::item($row, $item);
- }
+ /**
+ * One reference (`upload_token`, `id` or `url`) as a hosted item.
+ *
+ * @param array<MediaType> $allowedTypes
+ * @param array<string, mixed> $item
+ * @return array<string, mixed>
+ *
+ * @throws ValidationException
+ */
+ private function host(array $allowedTypes, array $item, string $key): array
+ {
+ $token = data_get($item, 'upload_token');
- $url = (string) data_get($item, 'url');
+ if (filled($token)) {
+ return [...self::item($this->upload($token, $key), $item), 'upload_token' => $token];
+ }
- if (! array_key_exists($url, $fetched)) {
- $imported = app(MediaAttacher::class)->importUpload($workspace, $allowedTypes, $url);
- $upload = $imported->media
- ?? throw ValidationException::withMessages(["{$key}.url" => MediaAttacher::failureMessage($imported, $url)]);
+ $id = data_get($item, 'id');
- $fetched[$url] = $upload->id;
- }
+ if (filled($id)) {
+ return self::item($this->row($id, $key), $item);
+ }
- return self::item(Media::query()->findOrFail($fetched[$url]), $item);
- })->all();
- } catch (ValidationException $exception) {
- if ($fetched !== []) {
- DB::transaction(fn () => DeleteOwnedMedia::forRows(array_values($fetched)));
- $fetched = [];
- }
+ return self::item($this->download($allowedTypes, (string) data_get($item, 'url'), $key), $item);
+ }
- throw $exception;
+ /**
+ * @throws ValidationException
+ */
+ private function upload(string $token, string $key): Media
+ {
+ $upload = $this->byToken->get($token);
+
+ if (blank($upload)) {
+ throw ValidationException::withMessages(["{$key}.upload_token" => __('posts.errors.media_expired')]);
}
+
+ return $upload;
}
/**
+ * @throws ValidationException
+ */
+ private function row(string $id, string $key): Media
+ {
+ $row = $this->byId->get($id);
+
+ if (blank($row)) {
+ throw ValidationException::withMessages(["{$key}.id" => __('validation.exists', ['attribute' => 'media'])]);
+ }
+
+ return $row;
+ }
+
+ /**
+ * The URL as a temporary upload, downloaded the first time this request
+ * sees it.
+ *
+ * @param array<MediaType> $allowedTypes
+ *
+ * @throws ValidationException
+ */
+ private function download(array $allowedTypes, string $url, string $key): Media
+ {
+ if (! Arr::exists($this->downloads, $url)) {
+ $this->downloads[$url] = $this->import($allowedTypes, $url, $key);
+ }
+
+ return Media::query()->findOrFail($this->downloads[$url]);
+ }
+
+ /**
+ * Downloads the URL as a temporary upload and returns its row id.
+ *
+ * @param array<MediaType> $allowedTypes
+ *
+ * @throws ValidationException
+ */
+ private function import(array $allowedTypes, string $url, string $key): string
+ {
+ $imported = app(MediaAttacher::class)->importUpload($this->workspace, $allowedTypes, $url);
+
+ if (blank($imported->media)) {
+ throw ValidationException::withMessages(["{$key}.url" => MediaAttacher::failureMessage($imported, $url)]);
+ }
+
+ return $imported->media->id;
+ }
+
+ /**
+ * Deletes every download of the request, once a reference fails it.
+ */
+ private function forgetDownloads(): void
+ {
+ if (blank($this->downloads)) {
+ return;
+ }
+
+ DB::transaction(fn () => DeleteOwnedMedia::forRows(array_values($this->downloads)));
+ $this->downloads = [];
+ }
+
+ /**
+ * Loads, in two queries, the uploads and rows a list of references names.
+ *
+ * @param array<int, array<string, mixed>> $references
+ */
+ private function resolveReferences(array $references): void
+ {
+ $ids = collect(self::column($references, 'id'))
+ ->filter(fn (string $id): bool => Str::isUuid($id))
+ ->values()
+ ->all();
+
+ $this->byToken = ResolveWorkspaceMedia::byUploadTokens($this->workspace, self::column($references, 'upload_token'));
+ $this->byId = ResolveWorkspaceMedia::execute($this->workspace, $ids);
+ }
+
+ /**
+ * Hosts the media of each thread reply that refers to a URL.
+ *
* @param array<string, mixed> $meta
- * @param array<string, string> $fetched
* @return array<string, mixed>
+ *
+ * @throws ValidationException
*/
- private static function threadReplies(Workspace $workspace, array $meta, string $errorPrefix, array &$fetched): array
+ private function threadReplies(array $meta, string $errorPrefix): array
{
foreach ((array) data_get($meta, 'thread_replies', []) as $index => $reply) {
$media = (array) data_get($reply, 'media', []);
- if (! collect($media)->contains(fn (mixed $item): bool => filled(data_get($item, 'url')))) {
- continue;
+ if (self::hasUrl($media)) {
+ $meta['thread_replies'][$index]['media'] = $this->media(MediaType::cases(), $media, "{$errorPrefix}.thread_replies.{$index}.media");
}
-
- $meta['thread_replies'][$index]['media'] = self::execute(
- $workspace,
- MediaType::cases(),
- $media,
- "{$errorPrefix}.thread_replies.{$index}.media",
- $fetched,
- );
}
return $meta;
}
/**
- * The row as the composer shape the save validates, with the client's
- * editable meta (alt text, user tags) on top of what is stored. The `alt`
- * shorthand only applies to images.
- *
+ * @param array<int, mixed> $media
+ */
+ private static function hasUrl(array $media): bool
+ {
+ return collect($media)->contains(fn (mixed $item): bool => filled(data_get($item, 'url')));
+ }
+
+ /**
+ * @param array<string, mixed> $edits
* @param array<string, mixed> $reference
* @return array<string, mixed>
*/
- public static function item(Media $row, array $reference): array
+ private static function withAltShorthand(Media $row, array $edits, array $reference): array
{
- $item = MediaItem::fromMedia($row)->toArray();
- $edits = array_intersect_key((array) data_get($reference, 'meta', []), array_flip(SyncOwnedMedia::EDITABLE_META));
+ $alt = data_get($reference, 'alt');
- if ($row->type === MediaType::Image && filled($alt = data_get($reference, 'alt')) && ! array_key_exists('alt_text', $edits)) {
- $edits['alt_text'] = $alt;
+ if ($row->type !== MediaType::Image) {
+ return $edits;
}
- $item['meta'] = [...(array) data_get($item, 'meta', []), ...$edits];
+ if (blank($alt)) {
+ return $edits;
+ }
- return $item;
+ if (Arr::exists($edits, 'alt_text')) {
+ return $edits;
+ }
+
+ return [...$edits, 'alt_text' => $alt];
}
/**
@@ -209,6 +361,11 @@ class HostInlineMedia
*/
private static function column(array $media, string $key): array
{
- return collect($media)->pluck($key)->filter(fn (mixed $value): bool => is_string($value) && $value !== '')->unique()->values()->all();
+ return collect($media)
+ ->pluck($key)
+ ->filter(fn (mixed $value): bool => is_string($value) && filled($value))
+ ->unique()
+ ->values()
+ ->all();
}
}
diff --git a/app/Dto/MediaItem.php b/app/Dto/MediaItem.php
index 1c8257e8b..9fc0023ec 100644
--- a/app/Dto/MediaItem.php
+++ b/app/Dto/MediaItem.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Dto;
+use App\Enums\Media\CoverSource;
use App\Enums\Media\Source;
use App\Enums\Media\Type;
use App\Enums\SocialAccount\Platform;
@@ -87,6 +88,18 @@ class MediaItem
return $this->kind() === Type::Image;
}
+ /**
+ * An image that is not animated: what a video cover can be.
+ */
+ public function isStillImage(): bool
+ {
+ if (! $this->isImage()) {
+ return false;
+ }
+
+ return ! Type::isGif($this->mime_type);
+ }
+
public function isDocument(): bool
{
return $this->kind() === Type::Document;
@@ -148,6 +161,41 @@ class MediaItem
return is_numeric($offset) && $offset >= 0 ? (int) $offset : null;
}
+ /**
+ * Where this video's cover comes from. A cover stored without its source
+ * (sent by the API or MCP) is an uploaded image.
+ */
+ public function coverSource(): CoverSource
+ {
+ $source = CoverSource::tryFrom((string) data_get($this->meta, 'cover_source'));
+
+ if (filled($source)) {
+ return $source;
+ }
+
+ if (filled($this->cover())) {
+ return CoverSource::Image;
+ }
+
+ return CoverSource::Frame;
+ }
+
+ /**
+ * The image stored as this video's cover in `meta.cover`: one the user
+ * uploaded, or the screenshot of the picked frame (`coverSource()` says
+ * which).
+ */
+ public function cover(): ?self
+ {
+ $cover = data_get($this->meta, 'cover');
+
+ if (! is_array($cover) || blank(data_get($cover, 'url'))) {
+ return null;
+ }
+
+ return self::fromArray($cover);
+ }
+
/**
* People tagged on this image, as Instagram's `user_tags` entries: a public
* username plus x/y offsets from the top-left corner, each between 0 and 1.
@@ -187,6 +235,21 @@ class MediaItem
return mb_substr($alt, 0, $max);
}
+ /**
+ * The covers (`meta.cover`) of a list of stored or submitted media items.
+ *
+ * @param array<int, mixed> $items
+ * @return list<array<string, mixed>>
+ */
+ public static function covers(array $items): array
+ {
+ return collect($items)
+ ->map(fn (mixed $item): mixed => data_get($item, 'meta.cover'))
+ ->filter(fn (mixed $cover): bool => is_array($cover))
+ ->values()
+ ->all();
+ }
+
/**
* @param array<string, mixed> $data
*/
diff --git a/app/Enums/Media/CoverSource.php b/app/Enums/Media/CoverSource.php
new file mode 100644
index 000000000..a8b3d9e8b
--- /dev/null
+++ b/app/Enums/Media/CoverSource.php
@@ -0,0 +1,18 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Enums\Media;
+
+/**
+ * Where a video's cover comes from (`media.*.meta.cover_source`): a frame of
+ * the video (`cover_offset_ms`, and its screenshot in `meta.cover` for a
+ * network that takes an image), or an image the user uploaded (`meta.cover`).
+ * A video shared by several networks keeps both, so a network that only takes
+ * a frame still has one.
+ */
+enum CoverSource: string
+{
+ case Frame = 'frame';
+ case Image = 'image';
+}
diff --git a/app/Enums/PostPlatform/ContentType.php b/app/Enums/PostPlatform/ContentType.php
index 5e753c811..816db8f24 100644
--- a/app/Enums/PostPlatform/ContentType.php
+++ b/app/Enums/PostPlatform/ContentType.php
@@ -530,6 +530,16 @@ enum ContentType: string
return in_array($this, [self::InstagramFeed, self::InstagramReel, self::TikTokVideo, self::PinterestVideoPin], true);
}
+ /**
+ * Whether a video of this type may take an image as its cover
+ * (`media.*.meta.cover`): Instagram takes `cover_url` on Reels only, and
+ * YouTube sets a Short's thumbnail once the video is processed.
+ */
+ public function supportsCustomVideoCover(): bool
+ {
+ return in_array($this, [self::InstagramReel, self::YouTubeShort], true);
+ }
+
/**
* Whether the editor should auto-fit still images into the story frame.
*/
@@ -565,6 +575,7 @@ enum ContentType: string
* supports_alt_text: bool,
* supports_user_tags: bool,
* supports_video_cover: bool,
+ * supports_custom_video_cover: bool,
* platform_label: string,
* image_min_width: int|null,
* image_min_height: int|null,
@@ -602,6 +613,7 @@ enum ContentType: string
'supports_alt_text' => $this->supportsAltText(),
'supports_user_tags' => $this->supportsUserTags(),
'supports_video_cover' => $this->supportsVideoCover(),
+ 'supports_custom_video_cover' => $this->supportsCustomVideoCover(),
'platform_label' => $this->platform()->label(),
'image_min_width' => $dimensions['min_width'] ?? null,
'image_min_height' => $dimensions['min_height'] ?? null,
@@ -643,6 +655,7 @@ enum ContentType: string
* supports_alt_text: bool,
* supports_user_tags: bool,
* supports_video_cover: bool,
+ * supports_custom_video_cover: bool,
* captionless: bool,
* document_must_be_alone: bool,
* supports_thread_replies: bool,
@@ -683,6 +696,7 @@ enum ContentType: string
'supports_alt_text',
'supports_user_tags',
'supports_video_cover',
+ 'supports_custom_video_cover',
])),
'captionless' => $this->isCaptionless(),
'document_must_be_alone' => $this->supportsDocument(),
diff --git a/app/Enums/YouTube/ProcessingStatus.php b/app/Enums/YouTube/ProcessingStatus.php
new file mode 100644
index 000000000..43673c4a6
--- /dev/null
+++ b/app/Enums/YouTube/ProcessingStatus.php
@@ -0,0 +1,18 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Enums\YouTube;
+
+/**
+ * `processingDetails.processingStatus` of a video YouTube already has.
+ *
+ * @see https://developers.google.com/youtube/v3/docs/videos#processingDetails.processingStatus
+ */
+enum ProcessingStatus: string
+{
+ case Processing = 'processing';
+ case Succeeded = 'succeeded';
+ case Failed = 'failed';
+ case Terminated = 'terminated';
+}
diff --git a/app/Enums/YouTube/ThumbnailWarning.php b/app/Enums/YouTube/ThumbnailWarning.php
new file mode 100644
index 000000000..1d7b1d4ed
--- /dev/null
+++ b/app/Enums/YouTube/ThumbnailWarning.php
@@ -0,0 +1,20 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Enums\YouTube;
+
+/**
+ * Why YouTube did not set the cover image of a video that is already live
+ * as its thumbnail (`thumbnails.set`), kept in
+ * `posts.error_context.youtube_thumbnail_warning`. The post stays published.
+ *
+ * @see https://developers.google.com/youtube/v3/docs/thumbnails/set#errors
+ */
+enum ThumbnailWarning: string
+{
+ case Forbidden = 'forbidden';
+ case DailyLimit = 'daily_limit';
+ case InvalidImage = 'invalid_image';
+ case Failed = 'failed';
+}
diff --git a/app/Http/Resources/App/PostCardResource.php b/app/Http/Resources/App/PostCardResource.php
index 2602e8d68..e7edc27b5 100644
--- a/app/Http/Resources/App/PostCardResource.php
+++ b/app/Http/Resources/App/PostCardResource.php
@@ -47,10 +47,11 @@ class PostCardResource extends JsonResource
'name' => $user->name,
'photo_url' => $user->photo_url,
]),
- 'failure' => transform($post->error_context, fn (array $context): array => [
+ 'failure' => transform(Arr::except($post->error_context ?? [], 'youtube_thumbnail_warning'), fn (array $context): array => [
'category' => data_get($context, 'category'),
'failed_at' => data_get($context, 'failed_at'),
]),
+ 'youtube_thumbnail_warning' => $post->youTubeThumbnailWarning()?->value,
];
}
diff --git a/app/Jobs/PublishToSocialPlatform.php b/app/Jobs/PublishToSocialPlatform.php
index 7d98c7da8..1e1ef8111 100644
--- a/app/Jobs/PublishToSocialPlatform.php
+++ b/app/Jobs/PublishToSocialPlatform.php
@@ -221,6 +221,12 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
->delay(now()->addSeconds(ResolveTikTokVideoId::FIRST_CHECK_AFTER_SECONDS))
->afterCommit();
}
+
+ if ($this->post->awaitsYouTubeCover()) {
+ SetYouTubeCover::dispatch($this->post)
+ ->delay(now()->addSeconds(SetYouTubeCover::CHECK_EVERY_SECONDS))
+ ->afterCommit();
+ }
}
private function refreshAccountToken(): void
diff --git a/app/Jobs/SetYouTubeCover.php b/app/Jobs/SetYouTubeCover.php
new file mode 100644
index 000000000..afb671317
--- /dev/null
+++ b/app/Jobs/SetYouTubeCover.php
@@ -0,0 +1,181 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Jobs;
+
+use App\Enums\YouTube\ProcessingStatus;
+use App\Enums\YouTube\ThumbnailWarning;
+use App\Exceptions\Social\ErrorCategory;
+use App\Exceptions\Social\YouTubePublishException;
+use App\Exceptions\TokenExpiredException;
+use App\Models\Post;
+use App\Services\Social\ConnectionVerifier;
+use App\Services\Social\YouTubePublisher;
+use Google\Service\Exception as GoogleServiceException;
+use Illuminate\Contracts\Queue\ShouldBeUnique;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Queue\Queueable;
+use Symfony\Component\HttpFoundation\Response;
+use Throwable;
+
+/**
+ * Sets the cover image of a video TryPost published on YouTube. YouTube
+ * applies a Short's thumbnail only once the video is processed, so the job
+ * waits for that, a minute at a time. The video is already live: a cover
+ * YouTube refuses leaves a warning on the post, never a failure.
+ */
+class SetYouTubeCover implements ShouldBeUnique, ShouldQueue
+{
+ use Queueable;
+
+ /** YouTube usually processes a Short within a minute or two of the upload. */
+ public const int CHECK_EVERY_SECONDS = 60;
+
+ /** Thirty minutes of processing checks. */
+ public int $tries = 30;
+
+ public int $backoff = self::CHECK_EVERY_SECONDS;
+
+ public bool $deleteWhenMissingModels = true;
+
+ /** Must exceed HasSocialHttpClient's 120s HTTP timeout so a slow request cannot kill the worker. */
+ public int $timeout = 180;
+
+ public int $uniqueFor = 3600;
+
+ public function __construct(public Post $post)
+ {
+ $this->onQueue($post->platform->queue());
+ }
+
+ public function uniqueId(): string
+ {
+ return $this->post->id;
+ }
+
+ public function handle(YouTubePublisher $publisher): void
+ {
+ $this->post->refresh();
+
+ if (! $this->post->awaitsYouTubeCover()) {
+ return;
+ }
+
+ $account = $this->post->socialAccount()->connected()->first();
+
+ if (blank($account)) {
+ $this->post->recordYouTubeThumbnailWarning(ThumbnailWarning::Failed);
+
+ return;
+ }
+
+ try {
+ if ($account->needsProactiveTokenRefresh()) {
+ app(ConnectionVerifier::class)->refreshToken($account);
+ }
+
+ $this->apply($publisher);
+ } catch (TokenExpiredException) {
+ $this->post->recordYouTubeThumbnailWarning(ThumbnailWarning::Failed);
+ } catch (GoogleServiceException $exception) {
+ $this->settle($exception);
+ } catch (YouTubePublishException $exception) {
+ $this->settleCoverFile($exception);
+ }
+ }
+
+ public function failed(?Throwable $exception): void
+ {
+ $this->post->refresh();
+
+ if ($this->post->awaitsYouTubeCover()) {
+ $this->post->recordYouTubeThumbnailWarning(ThumbnailWarning::Failed);
+ }
+ }
+
+ /**
+ * A video YouTube no longer lists was removed: there is nothing to warn
+ * about. One it could not process never takes a thumbnail.
+ *
+ * @throws GoogleServiceException
+ */
+ private function apply(YouTubePublisher $publisher): void
+ {
+ $status = $publisher->processingStatus($this->post);
+
+ if ($status === ProcessingStatus::Processing) {
+ $this->release(self::CHECK_EVERY_SECONDS);
+
+ return;
+ }
+
+ if (blank($status)) {
+ return;
+ }
+
+ if ($status !== ProcessingStatus::Succeeded) {
+ $this->post->recordYouTubeThumbnailWarning(ThumbnailWarning::Failed);
+
+ return;
+ }
+
+ $publisher->setCover($this->post);
+ }
+
+ /**
+ * A server error is tried again, and a video removed meanwhile (404
+ * `videoNotFound`) leaves nothing to warn about, like a video YouTube no
+ * longer lists; any other refusal stays on the post.
+ *
+ * @see https://developers.google.com/youtube/v3/docs/thumbnails/set#errors
+ */
+ private function settle(GoogleServiceException $exception): void
+ {
+ $status = $exception->getCode();
+
+ if ($status >= Response::HTTP_INTERNAL_SERVER_ERROR) {
+ $this->release(self::CHECK_EVERY_SECONDS);
+
+ return;
+ }
+
+ if ($status === Response::HTTP_NOT_FOUND) {
+ return;
+ }
+
+ $this->post->recordYouTubeThumbnailWarning(self::warningFor($status));
+ }
+
+ /**
+ * A cover that cannot be made a JPEG never will be; a download that
+ * failed is tried again.
+ *
+ * @throws YouTubePublishException
+ */
+ private function settleCoverFile(YouTubePublishException $exception): void
+ {
+ if ($exception->category !== ErrorCategory::MediaFormat) {
+ throw $exception;
+ }
+
+ $this->post->recordYouTubeThumbnailWarning(ThumbnailWarning::InvalidImage);
+ }
+
+ private static function warningFor(int $status): ThumbnailWarning
+ {
+ if ($status === Response::HTTP_FORBIDDEN) {
+ return ThumbnailWarning::Forbidden;
+ }
+
+ if ($status === Response::HTTP_TOO_MANY_REQUESTS) {
+ return ThumbnailWarning::DailyLimit;
+ }
+
+ if ($status === Response::HTTP_BAD_REQUEST) {
+ return ThumbnailWarning::InvalidImage;
+ }
+
+ return ThumbnailWarning::Failed;
+ }
+}
diff --git a/app/Mcp/Concerns/DescribesPostMedia.php b/app/Mcp/Concerns/DescribesPostMedia.php
index 32056813a..e3ae66227 100644
--- a/app/Mcp/Concerns/DescribesPostMedia.php
+++ b/app/Mcp/Concerns/DescribesPostMedia.php
@@ -21,7 +21,7 @@ trait DescribesPostMedia
'url' => $item->string()->description('Public http(s) URL that serves the file itself (a JPEG, PNG, GIF or WebP image, HEIC or HEIF when the server can convert it, an MP4 or MOV video, or a PDF; redirects are not followed and web pages are refused); downloaded once per call, within 20 seconds, up to the server limits (by default 10 MB and 67 megapixels for an image, 1 GB for a video, 100 MB for a PDF).'),
'id' => $item->string()->description('UUID of a media item of this workspace, as returned in a post\'s media (get-post-tool, list-posts-tool); copied for the post. An id already on the post keeps it, so send the current ids in the new order to reorder, and leave one out to remove it.'),
'alt' => $item->string()->description('Alt text for an image (ignored for video and PDF).'),
- 'meta' => $item->object()->description('Per-item settings: alt_text (string, up to 2000 characters; cut to the network limit, alt_text_max_length in list-content-types-tool, when published), user_tags (Instagram feed images only: up to 20 of {username, x, y}, x and y between 0 and 1 from the top-left corner), cover_offset_ms (video cover frame in milliseconds, for content types with supports_video_cover).'),
+ 'meta' => $item->object()->description('Per-item settings: alt_text (string, up to 2000 characters; cut to the network limit, alt_text_max_length in list-content-types-tool, when published), user_tags (Instagram feed images only: up to 20 of {username, x, y}, x and y between 0 and 1 from the top-left corner), cover_offset_ms (video cover frame in milliseconds, for content types with supports_video_cover), cover (an image used as the video cover instead of a frame, for content types with supports_custom_video_cover: {upload_token}, {url} or {id} like a media item; a still image; the network crops it to the middle 9:16, so upload it at 9:16. YouTube applies it once the video is processed, and a channel that is not verified cannot take one), cover_source (frame or image: where the cover comes from, image when cover is sent without it; with frame, cover_offset_ms is the cover, and YouTube, which takes no frame time, uses cover as that frame\'s screenshot; a network that only takes a frame keeps cover_offset_ms and drops cover).'),
]))
->description("{$description} Items keep the order given (the first is the cover of a carousel). Each item gives exactly one of upload_token, url or id. A PDF must be the only attachment. Check the content type's media rules with list-content-types-tool.");
}
diff --git a/app/Mcp/Tools/Platform/ListContentTypesTool.php b/app/Mcp/Tools/Platform/ListContentTypesTool.php
index f3f764cd6..5ddb350a6 100644
--- a/app/Mcp/Tools/Platform/ListContentTypesTool.php
+++ b/app/Mcp/Tools/Platform/ListContentTypesTool.php
@@ -20,7 +20,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly(true)]
#[IsDestructive(false)]
#[IsOpenWorld(false)]
-#[Description('List every platform with its content types and their rules. Per content type: max/min media count, requires_media, accept_images/accept_videos/accept_documents, accepts_gif, accepts_mov, forbids_mixed_media, max_video_duration_sec (null = no cap), max_image_bytes / max_video_bytes / max_document_bytes, aspect_ratio_min / aspect_ratio_max for images and video_aspect_ratio_min / video_aspect_ratio_max for videos (width / height, null = not checked; GIFs are never checked; auto_fits_image when images are fitted into the frame on publish instead), image_min_width / image_min_height / image_max_width / image_max_height in pixels, supports_alt_text, supports_user_tags (Instagram tags in media meta.user_tags), supports_video_cover (meta.cover_offset_ms), captionless (stories publish no text, so the text is neither sent nor measured), document_must_be_alone (a PDF must be the only attachment), supports_thread_replies and max_thread_replies (meta.thread_replies: a thread on X, Bluesky or Mastodon, or one comment on LinkedIn). Per platform: allowed_media_types, default_content_type, max_content_length (the default text limit of the network; the limit of each account, such as 25000 for an X account with long posts, is max_content_length in list-social-accounts-tool), max_hashtags (Instagram: 5), alt_text_max_length and required_meta (meta every post of the platform needs before it is scheduled or published; some needs depend on the content type and are not listed: Google Business events and offers also need meta.event, a YouTube post needs meta.title or text, and an X poll (x_poll) needs meta.poll with at least 2 options and duration_minutes, plus text as its question). Media rules never block a draft: they are checked when a post is scheduled, queued or published (create-post-tool, create-posts-tool, update-post-tool, publish-post-tool), and a post whose media breaks a rule of its content_type is rejected with a per-platform error. The exception is an X poll (content_type x_poll, or a reply in meta.thread_replies with a poll): media, a repeated choice, more than 4 choices, a choice over 25 characters or a duration_minutes outside 5–10080 is refused on every save, drafts included, and the attach media tools refuse it too. Call this before attaching media or choosing a content_type.')]
+#[Description('List every platform with its content types and their rules. Per content type: max/min media count, requires_media, accept_images/accept_videos/accept_documents, accepts_gif, accepts_mov, forbids_mixed_media, max_video_duration_sec (null = no cap), max_image_bytes / max_video_bytes / max_document_bytes, aspect_ratio_min / aspect_ratio_max for images and video_aspect_ratio_min / video_aspect_ratio_max for videos (width / height, null = not checked; GIFs are never checked; auto_fits_image when images are fitted into the frame on publish instead), image_min_width / image_min_height / image_max_width / image_max_height in pixels, supports_alt_text, supports_user_tags (Instagram tags in media meta.user_tags), supports_video_cover (meta.cover_offset_ms), supports_custom_video_cover (an image as the video cover, media meta.cover; Instagram Reels and YouTube Shorts), captionless (stories publish no text, so the text is neither sent nor measured), document_must_be_alone (a PDF must be the only attachment), supports_thread_replies and max_thread_replies (meta.thread_replies: a thread on X, Bluesky or Mastodon, or one comment on LinkedIn). Per platform: allowed_media_types, default_content_type, max_content_length (the default text limit of the network; the limit of each account, such as 25000 for an X account with long posts, is max_content_length in list-social-accounts-tool), max_hashtags (Instagram: 5), alt_text_max_length and required_meta (meta every post of the platform needs before it is scheduled or published; some needs depend on the content type and are not listed: Google Business events and offers also need meta.event, a YouTube post needs meta.title or text, and an X poll (x_poll) needs meta.poll with at least 2 options and duration_minutes, plus text as its question). Media rules never block a draft: they are checked when a post is scheduled, queued or published (create-post-tool, create-posts-tool, update-post-tool, publish-post-tool), and a post whose media breaks a rule of its content_type is rejected with a per-platform error. The exception is an X poll (content_type x_poll, or a reply in meta.thread_replies with a poll): media, a repeated choice, more than 4 choices, a choice over 25 characters or a duration_minutes outside 5–10080 is refused on every save, drafts included, and the attach media tools refuse it too. Call this before attaching media or choosing a content_type.')]
class ListContentTypesTool extends Tool
{
use AuthorizesMcpTool;
diff --git a/app/Models/Post.php b/app/Models/Post.php
index 4ad56d5d3..55daa5a05 100644
--- a/app/Models/Post.php
+++ b/app/Models/Post.php
@@ -17,6 +17,7 @@ use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\TikTok\PrivacyLevel;
+use App\Enums\YouTube\ThumbnailWarning;
use App\Observers\PostObserver;
use App\Support\Media\MediaCopyBatch;
use Carbon\CarbonInterface;
@@ -479,6 +480,36 @@ class Post extends Model
&& PrivacyLevel::tryFrom((string) data_get($this->meta, 'privacy_level')) === PrivacyLevel::PublicToEveryone;
}
+ /**
+ * A YouTube video TryPost published with an image picked as its cover,
+ * which YouTube only takes once the video is processed (`SetYouTubeCover`).
+ */
+ public function awaitsYouTubeCover(): bool
+ {
+ return $this->platform === Platform::YouTube
+ && $this->origin === Origin::TryPost
+ && $this->publish_status === PublishStatus::Published
+ && filled($this->platform_post_id)
+ && filled($this->mediaItems->first()?->cover());
+ }
+
+ /**
+ * Why YouTube did not set the cover image of this live video as its thumbnail, if it did not.
+ */
+ public function youTubeThumbnailWarning(): ?ThumbnailWarning
+ {
+ return ThumbnailWarning::tryFrom((string) data_get($this->error_context, 'youtube_thumbnail_warning'));
+ }
+
+ /**
+ * The post stays published: the warning sits next to the publication
+ * result, which publishing again clears.
+ */
+ public function recordYouTubeThumbnailWarning(ThumbnailWarning $warning): void
+ {
+ $this->writePublication(['error_context' => [...($this->error_context ?? []), 'youtube_thumbnail_warning' => $warning->value]]);
+ }
+
/**
* Display name, falling back to the snapshot when the account was deleted.
*/
diff --git a/app/Services/Social/Concerns/FitsImageToCanvas.php b/app/Services/Social/Concerns/FitsImageToCanvas.php
deleted file mode 100644
index 78f9ad2fd..000000000
--- a/app/Services/Social/Concerns/FitsImageToCanvas.php
+++ /dev/null
@@ -1,57 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Services\Social\Concerns;
-
-use App\Exceptions\Social\SocialPublishException;
-use App\Services\Media\MediaOptimizer;
-use Illuminate\Support\Facades\Http;
-use Illuminate\Support\Facades\Storage;
-use Illuminate\Support\Str;
-
-trait FitsImageToCanvas
-{
- public const CROP_DIRECTORY = 'social-crops';
-
- /**
- * Fit the image inside a width×height canvas with a blurred-background
- * extension (no cropping), host it, and return a public URL. Used for
- * stories so an off-ratio image isn't clipped by the platform.
- */
- protected function fitImageToCanvas(string $imageUrl, int $width, int $height): string
- {
- $tempInput = tempnam(sys_get_temp_dir(), 'fit_in_');
-
- try {
- $download = Http::sink($tempInput)->timeout(120)->get($imageUrl);
-
- if ($download->failed()) {
- throw $this->cropFailureException('Failed to download image for story fitting');
- }
-
- try {
- $fitted = app(MediaOptimizer::class)->fitToCanvas($tempInput, $width, $height);
- } catch (\Throwable) {
- throw $this->cropFailureException('Failed to process image for story fitting');
- }
-
- try {
- $path = self::CROP_DIRECTORY.'/'.Str::uuid()->toString().'.jpg';
- Storage::put($path, file_get_contents($fitted));
-
- return Storage::url($path);
- } finally {
- @unlink($fitted);
- }
- } finally {
- @unlink($tempInput);
- }
- }
-
- /**
- * The platform-specific exception thrown when an image can't be prepared for
- * publishing — a download or story-fit failure.
- */
- abstract protected function cropFailureException(string $message): SocialPublishException;
-}
diff --git a/app/Services/Social/Concerns/HostsProcessedImages.php b/app/Services/Social/Concerns/HostsProcessedImages.php
new file mode 100644
index 000000000..104238909
--- /dev/null
+++ b/app/Services/Social/Concerns/HostsProcessedImages.php
@@ -0,0 +1,146 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Services\Social\Concerns;
+
+use App\Enums\SocialAccount\Platform;
+use App\Exceptions\Social\SocialPublishException;
+use App\Services\Media\MediaOptimizer;
+use Closure;
+use Illuminate\Support\Facades\File;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Str;
+use Throwable;
+
+/**
+ * Prepares an image a network fetches or receives: fitted into a story's
+ * canvas, or re-encoded as the network's JPEG, then hosted or handed back.
+ */
+trait HostsProcessedImages
+{
+ public const CROP_DIRECTORY = 'social-crops';
+
+ /**
+ * MediaOptimizer hands back an image too large to decode untouched, so a
+ * result that is not a JPEG was not converted.
+ */
+ private const string JPEG_MIME_TYPE = 'image/jpeg';
+
+ /**
+ * Fit the image inside a width×height canvas with a blurred-background
+ * extension (no cropping), host it, and return a public URL. Used for
+ * stories so an off-ratio image isn't clipped by the platform.
+ */
+ protected function fitImageToCanvas(string $imageUrl, int $width, int $height): string
+ {
+ return $this->hostProcessedImage(
+ $imageUrl,
+ fn (string $path): string => app(MediaOptimizer::class)->fitToCanvas($path, $width, $height),
+ 'story fitting',
+ );
+ }
+
+ /**
+ * Re-encode the image as the platform's JPEG (format, width and byte
+ * budget of MediaOptimizer), host it, and return a public URL. Used where
+ * a network takes only JPEG, like an Instagram Reel cover.
+ */
+ protected function hostAsJpeg(string $imageUrl, Platform $platform, int $maxBytes): string
+ {
+ return $this->hostProcessedImage(
+ $imageUrl,
+ fn (string $path): string => $this->jpegFrom($path, $platform, $maxBytes),
+ 'JPEG conversion',
+ );
+ }
+
+ /**
+ * Re-encodes the image file as the platform's JPEG and returns the path of
+ * the result (the caller deletes it). Fails when MediaOptimizer could not
+ * convert it (it hands back an image too large to decode untouched) or the
+ * result is still over `$maxBytes`.
+ */
+ protected function jpegFrom(string $path, Platform $platform, int $maxBytes): string
+ {
+ try {
+ $converted = app(MediaOptimizer::class)->optimizeImage($path, $platform);
+ } catch (Throwable) {
+ throw $this->cropFailureException('Failed to convert image to JPEG');
+ }
+
+ if (File::mimeType($converted) !== self::JPEG_MIME_TYPE) {
+ File::delete($converted);
+
+ throw $this->cropFailureException('Failed to convert image to JPEG');
+ }
+
+ if (File::size($converted) > $maxBytes) {
+ File::delete($converted);
+
+ throw $this->cropFailureException('Converted image is too large');
+ }
+
+ return $converted;
+ }
+
+ /**
+ * Downloads the image, runs `$process` on it (which returns the path of a
+ * JPEG it wrote), hosts the result and returns its public URL. Both
+ * temporary files are removed whatever happens.
+ *
+ * @param Closure(string): string $process
+ *
+ * @throws SocialPublishException when the image cannot be downloaded or processed
+ */
+ private function hostProcessedImage(string $imageUrl, Closure $process, string $purpose): string
+ {
+ $download = $this->downloadImage($imageUrl)
+ ?? throw $this->cropFailureException("Failed to download image for {$purpose}");
+
+ try {
+ try {
+ $processed = $process($download);
+ } catch (Throwable) {
+ throw $this->cropFailureException("Failed to process image for {$purpose}");
+ }
+
+ try {
+ $directory = self::CROP_DIRECTORY;
+ $name = Str::uuid()->toString();
+ $path = "{$directory}/{$name}.jpg";
+ Storage::put($path, File::get($processed));
+
+ return Storage::url($path);
+ } finally {
+ File::delete($processed);
+ }
+ } finally {
+ File::delete($download);
+ }
+ }
+
+ /**
+ * Downloads the image to a temporary file and returns its path (the
+ * caller deletes it), or null when the download fails.
+ */
+ protected function downloadImage(string $imageUrl): ?string
+ {
+ $path = tempnam(sys_get_temp_dir(), 'image_in_');
+
+ if (Http::sink($path)->timeout(120)->get($imageUrl)->failed()) {
+ File::delete($path);
+
+ return null;
+ }
+
+ return $path;
+ }
+
+ /**
+ * The platform-specific exception thrown when an image can't be prepared for
+ * publishing — a download or story-fit failure.
+ */
+ abstract protected function cropFailureException(string $message): SocialPublishException;
+}
diff --git a/app/Services/Social/FacebookPublisher.php b/app/Services/Social/FacebookPublisher.php
index 1a0113bcb..502450d86 100644
--- a/app/Services/Social/FacebookPublisher.php
+++ b/app/Services/Social/FacebookPublisher.php
@@ -12,8 +12,8 @@ use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\FacebookPublishException;
use App\Exceptions\Social\SocialPublishException;
use App\Models\Post;
-use App\Services\Social\Concerns\FitsImageToCanvas;
use App\Services\Social\Concerns\HasSocialHttpClient;
+use App\Services\Social\Concerns\HostsProcessedImages;
use App\Services\Social\Meta\GraphError;
use App\Support\FacebookLinkPreview;
use Closure;
@@ -26,8 +26,8 @@ use Illuminate\Support\Sleep;
class FacebookPublisher
{
- use FitsImageToCanvas;
use HasSocialHttpClient;
+ use HostsProcessedImages;
private const int VIDEO_UPLOAD_POLL_SECONDS = 5;
diff --git a/app/Services/Social/InstagramPublisher.php b/app/Services/Social/InstagramPublisher.php
index 3bd27f885..7ce77456d 100644
--- a/app/Services/Social/InstagramPublisher.php
+++ b/app/Services/Social/InstagramPublisher.php
@@ -7,6 +7,7 @@ namespace App\Services\Social;
use App\Dto\MediaItem;
use App\Enums\Instagram\ContainerStatus;
use App\Enums\Instagram\TrialGraduation;
+use App\Enums\Media\CoverSource;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
@@ -14,8 +15,8 @@ use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\InstagramPublishException;
use App\Exceptions\Social\SocialPublishException;
use App\Models\Post;
-use App\Services\Social\Concerns\FitsImageToCanvas;
use App\Services\Social\Concerns\HasSocialHttpClient;
+use App\Services\Social\Concerns\HostsProcessedImages;
use App\Services\Social\Meta\GraphError;
use App\Support\PostPlatformMetaRules;
use App\Support\Social\PublishCheckpoint;
@@ -26,8 +27,8 @@ use Illuminate\Support\Facades\Log;
class InstagramPublisher
{
- use FitsImageToCanvas;
use HasSocialHttpClient;
+ use HostsProcessedImages;
private string $baseUrl;
@@ -38,6 +39,10 @@ class InstagramPublisher
/** Two hours of delayed retries for processing and transient Graph failures. */
private const int STATUS_MAX_RETRIES = 120;
+ private const string COVER_MIME_TYPE = 'image/jpeg';
+
+ private const int COVER_MAX_BYTES = 8 * 1024 * 1024;
+
private const string WORKFLOW_CAROUSEL_CHILDREN = 'carousel_children';
private const string WORKFLOW_FINAL_CONTAINER = 'final_container';
@@ -131,7 +136,7 @@ class InstagramPublisher
'caption' => $content,
'media_type' => 'REELS',
'access_token' => $accessToken,
- ...$this->thumbOffsetParam($media),
+ ...$this->reelCoverParam($media),
...$this->sharedOptions(),
...$this->collaboratorsParam(),
...$this->reelOptions(),
@@ -328,6 +333,64 @@ class InstagramPublisher
));
}
+ /**
+ * A Reel's cover: the image the user uploaded when they picked the Reel
+ * type (Instagram takes `cover_url` on Reels only and prefers it over
+ * `thumb_offset`), else the picked frame as its time, which Instagram
+ * shows exactly (the frame's screenshot is for YouTube). An image that
+ * cannot be made a JPEG falls back to the frame rather than failing.
+ *
+ * @return array{cover_url?: string, thumb_offset?: int}
+ */
+ private function reelCoverParam(MediaItem $media): array
+ {
+ $cover = $media->cover();
+
+ if (blank($cover)) {
+ return $this->thumbOffsetParam($media);
+ }
+
+ if ($media->coverSource() === CoverSource::Frame) {
+ return $this->thumbOffsetParam($media);
+ }
+
+ if (! $this->post->content_type?->supportsCustomVideoCover()) {
+ return $this->thumbOffsetParam($media);
+ }
+
+ try {
+ return ['cover_url' => $this->coverUrl($cover)];
+ } catch (InstagramPublishException $exception) {
+ Log::warning('Instagram Reel cover could not be prepared; publishing with the picked frame', [
+ 'post_id' => $this->post->id,
+ 'error' => $exception->getMessage(),
+ ]);
+
+ return $this->thumbOffsetParam($media);
+ }
+ }
+
+ /**
+ * Instagram fetches a Reel cover only as a JPEG of up to 8 MB, so any
+ * other image is re-encoded first.
+ */
+ private function coverUrl(MediaItem $cover): string
+ {
+ if ($cover->mime_type !== self::COVER_MIME_TYPE) {
+ return $this->hostAsJpeg($cover->url, Platform::Instagram, self::COVER_MAX_BYTES);
+ }
+
+ if (blank($cover->size)) {
+ return $this->hostAsJpeg($cover->url, Platform::Instagram, self::COVER_MAX_BYTES);
+ }
+
+ if ($cover->size > self::COVER_MAX_BYTES) {
+ return $this->hostAsJpeg($cover->url, Platform::Instagram, self::COVER_MAX_BYTES);
+ }
+
+ return $cover->url;
+ }
+
/**
* @return array{thumb_offset?: int}
*/
diff --git a/app/Services/Social/YouTubePublisher.php b/app/Services/Social/YouTubePublisher.php
index 0f98c6c5d..58d9fa02d 100644
--- a/app/Services/Social/YouTubePublisher.php
+++ b/app/Services/Social/YouTubePublisher.php
@@ -5,14 +5,18 @@ declare(strict_types=1);
namespace App\Services\Social;
use App\Dto\MediaItem;
+use App\Enums\SocialAccount\Platform;
use App\Enums\YouTube\License;
use App\Enums\YouTube\PrivacyStatus;
+use App\Enums\YouTube\ProcessingStatus;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
+use App\Exceptions\Social\SocialPublishException;
use App\Exceptions\Social\YouTubePublishException;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Social\Concerns\HasSocialHttpClient;
+use App\Services\Social\Concerns\HostsProcessedImages;
use App\Support\YouTubeDescription;
use App\Support\YouTubeMetadata;
use Google\Client as GoogleClient;
@@ -22,15 +26,23 @@ use Google\Service\YouTube\Video;
use Google\Service\YouTube\VideoSnippet;
use Google\Service\YouTube\VideoStatus;
use Google_Http_MediaFileUpload;
+use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class YouTubePublisher
{
use HasSocialHttpClient;
+ use HostsProcessedImages;
private const CHUNK_SIZE = 10 * 1024 * 1024; // 10MB chunks
+ /** @var list<string> */
+ private const array COVER_MIME_TYPES = ['image/jpeg', 'image/png'];
+
+ /** thumbnails.set takes an image of up to 50 MB. */
+ private const int COVER_MAX_BYTES = 50 * 1024 * 1024;
+
public function publish(Post $post): array
{
$this->validateContentLength($post);
@@ -74,6 +86,85 @@ class YouTubePublisher
return $this->publishShort($firstMedia, $account, $content, $description, $post->meta ?? []);
}
+ /**
+ * Where YouTube is with a video it already has, or null when it no
+ * longer lists the video.
+ *
+ * @throws Exception
+ */
+ public function processingStatus(Post $post): ?ProcessingStatus
+ {
+ $youtube = new YouTube($this->createGoogleClient($post->socialAccount));
+ $video = data_get($youtube->videos->listVideos('processingDetails', ['id' => $post->platform_post_id])->getItems(), 0);
+
+ return ProcessingStatus::tryFrom((string) $video?->getProcessingDetails()?->getProcessingStatus());
+ }
+
+ /**
+ * Sets the post's cover image (`media.0.meta.cover`) as the thumbnail of
+ * its video, which YouTube takes as a JPEG or a PNG. Call it once the
+ * video is processed: a Short may otherwise keep its own frame.
+ *
+ * @see https://developers.google.com/youtube/v3/docs/thumbnails/set
+ *
+ * @throws Exception
+ */
+ public function setCover(Post $post): void
+ {
+ $cover = $post->mediaItems->first()?->cover();
+
+ if (blank($cover)) {
+ return;
+ }
+
+ $download = $this->downloadImage($cover->url) ?? throw new YouTubePublishException(
+ userMessage: 'Failed to download the cover image for YouTube',
+ category: ErrorCategory::ServerError,
+ );
+
+ try {
+ [$bytes, $mimeType] = $this->coverImage($cover, $download);
+ } finally {
+ File::delete($download);
+ }
+
+ $youtube = new YouTube($this->createGoogleClient($post->socialAccount));
+ $youtube->thumbnails->set($post->platform_post_id, [
+ 'data' => $bytes,
+ 'mimeType' => $mimeType,
+ 'uploadType' => 'media',
+ ]);
+ }
+
+ /**
+ * The downloaded cover as YouTube takes it: a JPEG or a PNG as is, any
+ * other image re-encoded as a JPEG.
+ *
+ * @return array{0: string, 1: string}
+ */
+ private function coverImage(MediaItem $cover, string $path): array
+ {
+ if (in_array($cover->mime_type, self::COVER_MIME_TYPES, true)) {
+ return [File::get($path), (string) $cover->mime_type];
+ }
+
+ $converted = $this->jpegFrom($path, Platform::YouTube, self::COVER_MAX_BYTES);
+
+ try {
+ return [File::get($converted), 'image/jpeg'];
+ } finally {
+ File::delete($converted);
+ }
+ }
+
+ protected function cropFailureException(string $message): SocialPublishException
+ {
+ return new YouTubePublishException(
+ userMessage: $message,
+ category: ErrorCategory::MediaFormat,
+ );
+ }
+
private function createGoogleClient(SocialAccount $account): GoogleClient
{
$client = app(GoogleClient::class);
diff --git a/app/Support/PostCompositionValidator.php b/app/Support/PostCompositionValidator.php
index b3ac60bbb..a03cac22e 100644
--- a/app/Support/PostCompositionValidator.php
+++ b/app/Support/PostCompositionValidator.php
@@ -16,6 +16,7 @@ use App\Rules\ContentFitsPlatformLimits;
use App\Rules\ContentTypeCompatibleWithMedia;
use App\Rules\PostContentFitsMaxLength;
use App\Support\Social\XPoll;
+use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
@@ -118,7 +119,7 @@ class PostCompositionValidator
}
$canonical = MediaItem::fromMedia($asset)->toArray();
- $edits = array_intersect_key((array) data_get($media, 'meta', []), array_flip(SyncOwnedMedia::EDITABLE_META));
+ $edits = Arr::only((array) data_get($media, 'meta', []), SyncOwnedMedia::OWNER_META);
if ($edits !== []) {
$canonical['meta'] = [...($asset->meta ?? []), ...$edits];
}
@@ -292,8 +293,8 @@ class PostCompositionValidator
}
/**
- * Alt text, people tags and the video cover offset (`SyncOwnedMedia::EDITABLE_META`)
- * are the per-post edits the composer may make to a media item it did not
+ * Alt text, people tags, the video cover offset and the cover image
+ * (`SyncOwnedMedia::OWNER_META`) are the per-post edits the composer may make to a media item it did not
* upload, so they are ignored when matching it to the post's stored media.
* Keys are sorted because neither the browser nor MySQL's JSON column keeps
* the stored key order.
@@ -304,7 +305,7 @@ class PostCompositionValidator
private static function comparableMedia(array $media): array
{
if (is_array(data_get($media, 'meta'))) {
- $media['meta'] = array_diff_key($media['meta'], array_flip(SyncOwnedMedia::EDITABLE_META));
+ $media['meta'] = Arr::except($media['meta'], SyncOwnedMedia::OWNER_META);
}
$media = array_filter($media, fn (mixed $value): bool => $value !== null && $value !== []);
diff --git a/app/Support/PostMediaRules.php b/app/Support/PostMediaRules.php
index 7fded87b1..00541468a 100644
--- a/app/Support/PostMediaRules.php
+++ b/app/Support/PostMediaRules.php
@@ -4,8 +4,11 @@ declare(strict_types=1);
namespace App\Support;
+use App\Enums\Media\CoverSource;
use App\Enums\Media\Source;
use Closure;
+use Illuminate\Support\Arr;
+use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
/**
@@ -26,6 +29,11 @@ class PostMediaRules
*/
public const USER_TAGS_MAX = 20;
+ /**
+ * Longest reference (upload token, URL or id) a video cover may give.
+ */
+ public const int COVER_REFERENCE_MAX_LENGTH = 2048;
+
/**
* Instagram usernames: letters, numbers, periods and underscores, up to 30.
*/
@@ -94,9 +102,58 @@ class PostMediaRules
self::validateAltText(data_get($value, 'alt_text'), $fail);
self::validateUserTags(data_get($value, 'user_tags'), $fail);
self::validateCoverOffset(data_get($value, 'cover_offset_ms'), data_get($value, 'duration'), $fail);
+ self::validateCover(data_get($value, 'cover'), $fail);
+ self::validateCoverSource(data_get($value, 'cover_source'), $fail);
}];
}
+ private static function validateCoverSource(mixed $source, Closure $fail): void
+ {
+ if (blank($source)) {
+ return;
+ }
+
+ if (blank(CoverSource::tryFrom((string) $source))) {
+ $fail('validation.in')->translate(['attribute' => 'cover_source']);
+ }
+ }
+
+ /**
+ * The image uploaded as a video's cover: a reference to one file like a
+ * media item (an `upload_token`, a `url` or an `id`; the web sends the
+ * whole hosted item). Its type is checked once the file is resolved.
+ */
+ private static function validateCover(mixed $cover, Closure $fail): void
+ {
+ if (blank($cover)) {
+ return;
+ }
+
+ if (! is_array($cover)) {
+ $fail('posts.errors.cover_invalid')->translate();
+
+ return;
+ }
+
+ $references = collect(Arr::only($cover, ['upload_token', 'url', 'id']))->filter(filled(...));
+
+ if ($references->isEmpty()) {
+ $fail('posts.errors.cover_invalid')->translate();
+
+ return;
+ }
+
+ if ($references->contains(fn (mixed $reference): bool => ! is_string($reference))) {
+ $fail('posts.errors.cover_invalid')->translate();
+
+ return;
+ }
+
+ if ($references->contains(fn (string $reference): bool => Str::length($reference) > self::COVER_REFERENCE_MAX_LENGTH)) {
+ $fail('posts.errors.cover_invalid')->translate();
+ }
+ }
+
/**
* The video frame picked as the cover, in milliseconds. It cannot pass the
* end of the video when the item's measured duration (seconds) is known.
diff --git a/app/Support/PostPlatformMetaRules.php b/app/Support/PostPlatformMetaRules.php
index d298f6b2c..f8569de36 100644
--- a/app/Support/PostPlatformMetaRules.php
+++ b/app/Support/PostPlatformMetaRules.php
@@ -259,8 +259,8 @@ class PostPlatformMetaRules
'Mastodon: spoiler_text (content warning, ≤500; counts toward the 500-character post limit).',
'Pinterest: board_id (required to publish — call list-pinterest-boards-tool first, or create-pinterest-board-tool), title (≤100), link (destination URL). Pin description comes from the post content; a video pin cover frame is the media item meta.cover_offset_ms.',
'Discord: channel_id (required to publish — call list-discord-channels-tool first), mentions ([{token,label}], e.g. {token: "@everyone"} or {token: "<@&roleId>"}), embeds (up to 10 [{title ≤256, description ≤4096, url, image (URL), color (#RRGGBB)}]).',
- 'YouTube Shorts: title (≤100, no < or >; omitted, it is derived from the first non-empty line of the content with < and > removed, cut to 100 characters), description (plain text, at most 5000 bytes; omit or null to use the content), category_id (YouTube category id: '.collect(Category::cases())->map(fn (Category $category): string => "{$category->value}=".__($category->labelKey(), [], 'en'))->implode(', ').'; default '.Category::DEFAULT->value.'), privacy_status (public|unlisted|private, default public), license (youtube|creativeCommon), notify_subscribers (default true), embeddable (default true), made_for_kids (default false), is_ai_generated (discloses altered or synthetic content).',
- 'Instagram: is_ai_generated (feed, reels, stories, carousels), share_to_feed (instagram_reel only, default true), collaborators (up to '.self::INSTAGRAM_MAX_COLLABORATORS.' Instagram usernames invited as co-authors; feed, reels and carousels, not stories; the post shows on a collaborator\'s profile only after they accept the invite in the Instagram app, and a username that does not exist is only refused when the post publishes, so confirm the usernames first), trial_graduation (instagram_reel only: MANUAL|SS_PERFORMANCE publishes a trial reel shown only to non-followers, graduated by hand in the app or by Instagram when it performs well; not with collaborators, and only on accounts where Instagram offers trial reels), audio (instagram_reel only, Instagram connected through Facebook, platform instagram-facebook: {id} of an Instagram audio track from search-instagram-audio-tool, with optional title, artist, cover_url and preview_url copied from that result so the app can show the track, and audio_volume and video_volume from 0 to 100, default 100). An instagram_feed post with a single video publishes as a Reel. People tags are the media item meta.user_tags and a video cover frame is meta.cover_offset_ms.',
+ 'YouTube Shorts: title (≤100, no < or >; omitted, it is derived from the first non-empty line of the content with < and > removed, cut to 100 characters), description (plain text, at most 5000 bytes; omit or null to use the content), category_id (YouTube category id: '.collect(Category::cases())->map(fn (Category $category): string => "{$category->value}=".__($category->labelKey(), [], 'en'))->implode(', ').'; default '.Category::DEFAULT->value.'), privacy_status (public|unlisted|private, default public), license (youtube|creativeCommon), notify_subscribers (default true), embeddable (default true), made_for_kids (default false), is_ai_generated (discloses altered or synthetic content). A cover image is the media item meta.cover, set as the thumbnail once YouTube processes the video.',
+ 'Instagram: is_ai_generated (feed, reels, stories, carousels), share_to_feed (instagram_reel only, default true), collaborators (up to '.self::INSTAGRAM_MAX_COLLABORATORS.' Instagram usernames invited as co-authors; feed, reels and carousels, not stories; the post shows on a collaborator\'s profile only after they accept the invite in the Instagram app, and a username that does not exist is only refused when the post publishes, so confirm the usernames first), trial_graduation (instagram_reel only: MANUAL|SS_PERFORMANCE publishes a trial reel shown only to non-followers, graduated by hand in the app or by Instagram when it performs well; not with collaborators, and only on accounts where Instagram offers trial reels), audio (instagram_reel only, Instagram connected through Facebook, platform instagram-facebook: {id} of an Instagram audio track from search-instagram-audio-tool, with optional title, artist, cover_url and preview_url copied from that result so the app can show the track, and audio_volume and video_volume from 0 to 100, default 100). An instagram_feed post with a single video publishes as a Reel. People tags are the media item meta.user_tags, a video cover frame is meta.cover_offset_ms and an instagram_reel may take an uploaded image as its cover in the media item meta.cover with cover_source image (it then wins over the frame).',
'X: is_ai_generated (sent as made_with_ai, discloses AI-generated media on the post). poll (content_type x_poll only, no media; the post content is the question; a reply of the thread can be a poll too, see thread_replies, up to '.XPoll::QUESTION_MAX_LENGTH.' characters): {options (list of '.XPoll::MIN_OPTIONS.' to '.XPoll::MAX_OPTIONS.' choices of 1 to '.XPoll::OPTION_MAX_LENGTH.' characters, no two the same; blank ones are dropped), duration_minutes ('.XPoll::MIN_DURATION.' to '.XPoll::MAX_DURATION.', how long voting stays open)}, both required to schedule or publish.',
'Threads: topic_tag (1-50 characters after a leading # is dropped, no . or &). Use content_type threads_ghost_post for a text-only post archived after 24 hours (no media, no topic).',
'Facebook, Bluesky, LinkedIn: link_preview (default true; false publishes a text post with a link without its preview card).',
diff --git a/lang/ar/posts.php b/lang/ar/posts.php
index 1f98aeae6..1fbfd0fac 100644
--- a/lang/ar/posts.php
+++ b/lang/ar/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'أدخل اسم مستخدم صالحًا على Instagram.',
'thumbnail_tab' => 'الغلاف',
'thumbnail_heading' => 'اختر صورة مصغرة',
- 'thumbnail_hint' => 'اسحب شريط التمرير لاختيار الإطار الذي يظهر كغلاف للفيديو.',
+ 'thumbnail_hint' => 'اسحب على إطارات الفيديو لاختيار الإطار الذي يظهر كغلاف.',
'thumbnail_value' => ':seconds ثانية',
+ 'thumbnail_source_frame' => 'إطار من الفيديو',
+ 'thumbnail_source_image' => 'صورة',
+ 'thumbnail_image_hint' => 'يعرض الفيديو هذه الصورة كغلاف. استخدم صورة بنسبة 9:16 حتى لا يُقص منها شيء.',
+ 'thumbnail_capture_failed' => 'تعذّر التقاط هذا الإطار. ارفع صورة لتكون الغلاف بدلًا من ذلك.',
+ 'thumbnail_image_upload' => 'رفع صورة',
+ 'thumbnail_image_replace' => 'استبدال الصورة',
'video_thumbnail' => 'فيديو :number',
'thumbnail' => 'الصورة :number',
'cancel' => 'إلغاء',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'انتهت صلاحية هذا الرفع. أضف الملف مرة أخرى.',
'cover_offset_min' => 'يجب أن يكون وقت غلاف الفيديو 0 مللي ثانية أو أكثر.',
'cover_offset_max' => 'يجب ألا يتجاوز وقت غلاف الفيديو :max مللي ثانية.',
+ 'cover_invalid' => 'اختر صورة لغلاف الفيديو.',
+ 'cover_not_image' => 'يجب أن يكون غلاف الفيديو صورة بصيغة JPEG أو PNG أو WebP.',
'media_item_shape' => 'يحتاج كل عنصر وسائط إلى واحد فقط من upload_token أو url أو id.',
- 'media_url_unreachable' => 'تعذر جلب الوسائط من :url.',
+ 'media_url_unreachable' => 'تعذر جلب الوسائط من :url',
'media_type_unsupported' => 'نوع هذا الملف غير مدعوم من قناة المنشور.',
'media_not_accepted' => 'لا يمكن أن يتضمن هذا النوع من المنشورات وسائط. غيّر نوع المنشور لإضافة وسائط.',
'media_file_unsupported' => 'نوع هذا الملف غير مدعوم.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'جديد',
'add_post_in_slot' => 'إضافة منشور',
'more_times' => 'المزيد من الأوقات',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'تنبيه',
+ 'title' => 'لم يُطبَّق الغلاف',
+ 'forbidden' => 'قناتك على YouTube غير موثّقة بعد. لتنشر بغلافك الخاص، وثّقها على :url',
+ 'daily_limit' => 'بلغت قناتك الحد اليومي للأغلفة المخصصة على YouTube. ستُنشر منشوراتك بأغلفتها مجددًا غدًا، ويمكنك تعيين غلاف هذا المنشور في YouTube Studio.',
+ 'invalid_image' => 'تعذّر على YouTube قراءة صورة الغلاف. يمكنك تعيين صورة أخرى في YouTube Studio.',
+ 'failed' => 'لم يطبّق YouTube صورة الغلاف. يمكنك تعيينها في YouTube Studio.',
+ ],
'failure' => [
'title' => 'سبب الفشل',
'generic' => 'تعذّر نشر هذا المنشور.',
diff --git a/lang/de/posts.php b/lang/de/posts.php
index e145c166c..ef6fe1934 100644
--- a/lang/de/posts.php
+++ b/lang/de/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Gib einen gültigen Instagram-Benutzernamen ein.',
'thumbnail_tab' => 'Vorschau',
'thumbnail_heading' => 'Vorschaubild auswählen',
- 'thumbnail_hint' => 'Ziehe den Regler, um das Bild auszuwählen, das als Titelbild des Videos angezeigt wird.',
+ 'thumbnail_hint' => 'Ziehe über die Bilder des Videos, um das Vorschaubild auszuwählen.',
'thumbnail_value' => ':seconds Sekunden',
+ 'thumbnail_source_frame' => 'Videobild',
+ 'thumbnail_source_image' => 'Bild',
+ 'thumbnail_image_hint' => 'Dein Video zeigt dieses Bild als Vorschaubild. Nutze ein Bild im Format 9:16, damit nichts abgeschnitten wird.',
+ 'thumbnail_capture_failed' => 'Dieses Videobild konnte nicht aufgenommen werden. Lade stattdessen ein Bild als Vorschaubild hoch.',
+ 'thumbnail_image_upload' => 'Bild hochladen',
+ 'thumbnail_image_replace' => 'Bild ersetzen',
'video_thumbnail' => 'Video :number',
'thumbnail' => 'Bild :number',
'cancel' => 'Abbrechen',
@@ -919,6 +925,8 @@ return [
'media_expired' => 'Dieser Upload ist abgelaufen. Füge die Datei erneut hinzu.',
'cover_offset_min' => 'Der Zeitpunkt des Titelbilds muss 0 ms oder mehr betragen.',
'cover_offset_max' => 'Der Zeitpunkt des Titelbilds darf höchstens :max ms betragen.',
+ 'cover_invalid' => 'Wähle ein Bild als Vorschaubild des Videos.',
+ 'cover_not_image' => 'Das Vorschaubild des Videos muss ein JPEG-, PNG- oder WebP-Bild sein.',
'media_item_shape' => 'Jedes Medienelement braucht genau eines von upload_token, url oder id.',
'media_url_unreachable' => 'Medien konnten nicht von :url abgerufen werden.',
'media_type_unsupported' => 'Dieser Dateityp wird vom Kanal des Beitrags nicht unterstützt.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Neu',
'add_post_in_slot' => 'Post hinzufügen',
'more_times' => 'Weitere Zeiten',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Hinweis',
+ 'title' => 'Vorschaubild nicht übernommen',
+ 'forbidden' => 'Dein YouTube-Kanal ist noch nicht bestätigt. Um mit deinem eigenen Vorschaubild zu veröffentlichen, bestätige ihn unter :url',
+ 'daily_limit' => 'Dein Kanal hat das Tageslimit für eigene Vorschaubilder auf YouTube erreicht. Ab morgen bekommen deine Beiträge wieder ihr Vorschaubild, und dieses kannst du in YouTube Studio festlegen.',
+ 'invalid_image' => 'YouTube konnte dein Vorschaubild nicht lesen. Du kannst in YouTube Studio ein anderes festlegen.',
+ 'failed' => 'YouTube hat dein Vorschaubild nicht übernommen. Du kannst es in YouTube Studio festlegen.',
+ ],
'failure' => [
'title' => 'Warum es fehlschlug',
'generic' => 'Wir konnten diesen Beitrag nicht veröffentlichen.',
diff --git a/lang/el/posts.php b/lang/el/posts.php
index c855ae3c5..cb02a972c 100644
--- a/lang/el/posts.php
+++ b/lang/el/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Εισαγάγετε έγκυρο όνομα χρήστη Instagram.',
'thumbnail_tab' => 'Εξώφυλλο',
'thumbnail_heading' => 'Επιλέξτε μικρογραφία',
- 'thumbnail_hint' => 'Σύρετε το ρυθμιστικό για να επιλέξετε το καρέ που θα εμφανίζεται ως εξώφυλλο του βίντεο.',
+ 'thumbnail_hint' => 'Σύρετε κατά μήκος των καρέ του βίντεο για να επιλέξετε αυτό που θα εμφανίζεται ως εξώφυλλο.',
'thumbnail_value' => ':seconds δευτερόλεπτα',
+ 'thumbnail_source_frame' => 'Καρέ βίντεο',
+ 'thumbnail_source_image' => 'Εικόνα',
+ 'thumbnail_image_hint' => 'Το βίντεό σας δείχνει αυτή την εικόνα ως εξώφυλλο. Χρησιμοποιήστε εικόνα 9:16 ώστε να μην κοπεί τίποτα.',
+ 'thumbnail_capture_failed' => 'Δεν ήταν δυνατή η λήψη αυτού του καρέ. Μεταφορτώστε μια εικόνα ως εξώφυλλο.',
+ 'thumbnail_image_upload' => 'Ανέβασμα εικόνας',
+ 'thumbnail_image_replace' => 'Αλλαγή εικόνας',
'video_thumbnail' => 'Βίντεο :number',
'thumbnail' => 'Εικόνα :number',
'cancel' => 'Ακύρωση',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'Αυτή η μεταφόρτωση έληξε. Προσθέστε ξανά το αρχείο.',
'cover_offset_min' => 'Ο χρόνος του εξωφύλλου του βίντεο πρέπει να είναι 0 ms ή περισσότερο.',
'cover_offset_max' => 'Ο χρόνος του εξωφύλλου του βίντεο πρέπει να είναι έως :max ms.',
+ 'cover_invalid' => 'Επιλέξτε εικόνα για το εξώφυλλο του βίντεο.',
+ 'cover_not_image' => 'Το εξώφυλλο του βίντεο πρέπει να είναι εικόνα JPEG, PNG ή WebP.',
'media_item_shape' => 'Κάθε στοιχείο πολυμέσων χρειάζεται ακριβώς ένα από τα upload_token, url ή id.',
- 'media_url_unreachable' => 'Δεν ήταν δυνατή η λήψη πολυμέσων από το :url.',
+ 'media_url_unreachable' => 'Δεν ήταν δυνατή η λήψη πολυμέσων από το :url',
'media_type_unsupported' => 'Αυτός ο τύπος αρχείου δεν υποστηρίζεται από το κανάλι της δημοσίευσης.',
'media_not_accepted' => 'Αυτός ο τύπος δημοσίευσης δεν μπορεί να περιέχει πολυμέσα. Αλλάξτε τον τύπο δημοσίευσης για να προσθέσετε πολυμέσα.',
'media_file_unsupported' => 'Αυτός ο τύπος αρχείου δεν υποστηρίζεται.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Νέο',
'add_post_in_slot' => 'Προσθήκη ανάρτησης',
'more_times' => 'Περισσότερες ώρες',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Προσοχή',
+ 'title' => 'Το εξώφυλλο δεν εφαρμόστηκε',
+ 'forbidden' => 'Το κανάλι σας στο YouTube δεν έχει επαληθευτεί ακόμη. Για να δημοσιεύετε με το δικό σας εξώφυλλο, επαληθεύστε το στο :url',
+ 'daily_limit' => 'Το κανάλι σας έφτασε το ημερήσιο όριο προσαρμοσμένων εξωφύλλων του YouTube. Από αύριο οι αναρτήσεις σας ξαναπαίρνουν το εξώφυλλό τους, και αυτής μπορείτε να το ορίσετε στο YouTube Studio.',
+ 'invalid_image' => 'Το YouTube δεν μπόρεσε να διαβάσει την εικόνα εξωφύλλου. Μπορείτε να ορίσετε άλλη στο YouTube Studio.',
+ 'failed' => 'Το YouTube δεν εφάρμοσε το εξώφυλλο. Μπορείτε να το ορίσετε στο YouTube Studio.',
+ ],
'failure' => [
'title' => 'Γιατί απέτυχε',
'generic' => 'Δεν μπορέσαμε να δημοσιεύσουμε αυτή την ανάρτηση.',
diff --git a/lang/en/posts.php b/lang/en/posts.php
index 5ae35983b..c2e3675e4 100644
--- a/lang/en/posts.php
+++ b/lang/en/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Enter a valid Instagram username.',
'thumbnail_tab' => 'Thumbnail',
'thumbnail_heading' => 'Choose a thumbnail',
- 'thumbnail_hint' => 'Drag the slider to pick the frame shown as the video\'s cover.',
+ 'thumbnail_hint' => 'Drag along the video\'s frames to pick the one shown as its cover.',
'thumbnail_value' => ':seconds seconds',
+ 'thumbnail_source_frame' => 'Video frame',
+ 'thumbnail_source_image' => 'Image',
+ 'thumbnail_image_hint' => 'Your video shows this image as its cover. Use a 9:16 image so nothing gets cut off.',
+ 'thumbnail_capture_failed' => 'Couldn\'t capture this frame. Upload an image as the cover instead.',
+ 'thumbnail_image_upload' => 'Upload image',
+ 'thumbnail_image_replace' => 'Replace image',
'video_thumbnail' => 'Video :number',
'thumbnail' => 'Image :number',
'cancel' => 'Cancel',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'This upload expired. Add the file again.',
'cover_offset_min' => 'The video cover time must be 0 ms or more.',
'cover_offset_max' => 'The video cover time must be :max ms or less.',
+ 'cover_invalid' => 'Choose an image for the video cover.',
+ 'cover_not_image' => 'The video cover must be a JPEG, PNG or WebP image.',
'media_item_shape' => 'Each media item needs exactly one of upload_token, url or id.',
- 'media_url_unreachable' => 'Could not fetch media from :url.',
+ 'media_url_unreachable' => 'Could not fetch media from :url',
'media_type_unsupported' => 'This file type is not supported by the post\'s channel.',
'media_not_accepted' => 'This post type can\'t include media. Change the post type to add media.',
'media_file_unsupported' => 'This file type is not supported.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'New',
'add_post_in_slot' => 'Add a post',
'more_times' => 'More times',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Warning',
+ 'title' => 'Cover not applied',
+ 'forbidden' => 'Your YouTube channel isn\'t verified yet. To publish with your own cover, verify it at :url',
+ 'daily_limit' => 'Your channel reached YouTube\'s daily limit of custom covers. Your posts take their covers again tomorrow, and you can set this one in YouTube Studio.',
+ 'invalid_image' => 'YouTube couldn\'t read your cover image. You can set another one in YouTube Studio.',
+ 'failed' => 'YouTube didn\'t apply your cover image. You can set it in YouTube Studio.',
+ ],
'failure' => [
'title' => 'Why it failed',
'generic' => 'We couldn\'t publish this post.',
diff --git a/lang/es/posts.php b/lang/es/posts.php
index 77d4abe1c..ae1c98480 100644
--- a/lang/es/posts.php
+++ b/lang/es/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Introduce un usuario de Instagram válido.',
'thumbnail_tab' => 'Miniatura',
'thumbnail_heading' => 'Elige una miniatura',
- 'thumbnail_hint' => 'Arrastra el control para elegir el fotograma que se mostrará como portada del vídeo.',
+ 'thumbnail_hint' => 'Arrastra por los fotogramas del video para elegir el que se muestra como portada.',
'thumbnail_value' => ':seconds segundos',
+ 'thumbnail_source_frame' => 'Fotograma',
+ 'thumbnail_source_image' => 'Imagen',
+ 'thumbnail_image_hint' => 'Tu video muestra esta imagen como portada. Usa una imagen 9:16 para que no se recorte nada.',
+ 'thumbnail_capture_failed' => 'No se pudo capturar este fotograma. Sube una imagen como portada.',
+ 'thumbnail_image_upload' => 'Subir imagen',
+ 'thumbnail_image_replace' => 'Cambiar imagen',
'video_thumbnail' => 'Vídeo :number',
'thumbnail' => 'Imagen :number',
'cancel' => 'Cancelar',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'Esta subida caducó. Añade el archivo de nuevo.',
'cover_offset_min' => 'El tiempo de la portada del vídeo debe ser de 0 ms o más.',
'cover_offset_max' => 'El tiempo de la portada del vídeo debe ser de :max ms o menos.',
+ 'cover_invalid' => 'Elige una imagen para la portada del video.',
+ 'cover_not_image' => 'La portada del video debe ser una imagen JPEG, PNG o WebP.',
'media_item_shape' => 'Cada elemento multimedia necesita exactamente uno de upload_token, url o id.',
- 'media_url_unreachable' => 'No se pudo obtener el archivo de :url.',
+ 'media_url_unreachable' => 'No se pudo obtener el archivo de :url',
'media_type_unsupported' => 'Este tipo de archivo no es compatible con el canal de la publicación.',
'media_not_accepted' => 'Este tipo de publicación no admite archivos multimedia. Cambia el tipo de publicación para añadirlos.',
'media_file_unsupported' => 'Este tipo de archivo no es compatible.',
@@ -1036,6 +1044,14 @@ return [
'new_in_slot' => 'Nuevo',
'add_post_in_slot' => 'Añadir post',
'more_times' => 'Más horarios',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Aviso',
+ 'title' => 'Portada no aplicada',
+ 'forbidden' => 'Tu canal de YouTube aún no está verificado. Para publicar con tu propia portada, verifícalo en :url',
+ 'daily_limit' => 'Tu canal alcanzó el límite diario de portadas personalizadas de YouTube. Mañana tus publicaciones vuelven a salir con su portada, y la de esta puedes ponerla en YouTube Studio.',
+ 'invalid_image' => 'YouTube no pudo leer tu imagen de portada. Puedes poner otra en YouTube Studio.',
+ 'failed' => 'YouTube no aplicó tu portada. Puedes ponerla en YouTube Studio.',
+ ],
'failure' => [
'title' => 'Por qué falló',
'generic' => 'No pudimos publicar esta publicación.',
diff --git a/lang/fr/posts.php b/lang/fr/posts.php
index 2ba935314..dcf99de2d 100644
--- a/lang/fr/posts.php
+++ b/lang/fr/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Saisissez un nom d\'utilisateur Instagram valide.',
'thumbnail_tab' => 'Miniature',
'thumbnail_heading' => 'Choisissez une miniature',
- 'thumbnail_hint' => 'Faites glisser le curseur pour choisir l\'image affichée comme couverture de la vidéo.',
+ 'thumbnail_hint' => 'Faites glisser le long des images de la vidéo pour choisir celle affichée en couverture.',
'thumbnail_value' => ':seconds secondes',
+ 'thumbnail_source_frame' => 'Image de la vidéo',
+ 'thumbnail_source_image' => 'Image',
+ 'thumbnail_image_hint' => 'Votre vidéo affiche cette image comme couverture. Utilisez une image 9:16 pour que rien ne soit coupé.',
+ 'thumbnail_capture_failed' => 'Impossible de capturer cette image de la vidéo. Importez plutôt une image comme couverture.',
+ 'thumbnail_image_upload' => 'Importer une image',
+ 'thumbnail_image_replace' => 'Changer l\'image',
'video_thumbnail' => 'Vidéo :number',
'thumbnail' => 'Image :number',
'cancel' => 'Annuler',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'Ce téléversement a expiré. Ajoutez à nouveau le fichier.',
'cover_offset_min' => 'Le temps de la couverture de la vidéo doit être de 0 ms ou plus.',
'cover_offset_max' => 'Le temps de la couverture de la vidéo doit être de :max ms ou moins.',
+ 'cover_invalid' => 'Choisissez une image pour la couverture de la vidéo.',
+ 'cover_not_image' => 'La couverture de la vidéo doit être une image JPEG, PNG ou WebP.',
'media_item_shape' => 'Chaque média doit avoir exactement un seul de ces champs : upload_token, url ou id.',
- 'media_url_unreachable' => 'Impossible de récupérer le média depuis :url.',
+ 'media_url_unreachable' => 'Impossible de récupérer le média depuis :url',
'media_type_unsupported' => 'Ce type de fichier n\'est pas pris en charge par le canal de la publication.',
'media_not_accepted' => 'Ce type de publication n\'accepte pas de médias. Changez le type de publication pour en ajouter.',
'media_file_unsupported' => 'Ce type de fichier n\'est pas pris en charge.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Nouveau',
'add_post_in_slot' => 'Ajouter un post',
'more_times' => 'Plus d\'horaires',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Attention',
+ 'title' => 'Couverture non appliquée',
+ 'forbidden' => 'Votre chaîne YouTube n\'est pas encore validée. Pour publier avec votre propre couverture, validez-la sur :url',
+ 'daily_limit' => 'Votre chaîne a atteint la limite quotidienne de couvertures personnalisées de YouTube. Demain, vos publications retrouvent leur couverture, et celle-ci peut être définie dans YouTube Studio.',
+ 'invalid_image' => 'YouTube n\'a pas pu lire votre image de couverture. Vous pouvez en définir une autre dans YouTube Studio.',
+ 'failed' => 'YouTube n\'a pas appliqué votre couverture. Vous pouvez la définir dans YouTube Studio.',
+ ],
'failure' => [
'title' => 'Pourquoi l\'échec',
'generic' => 'Nous n\'avons pas pu publier ce post.',
diff --git a/lang/id/posts.php b/lang/id/posts.php
index 9482d5ac6..7c11e7643 100644
--- a/lang/id/posts.php
+++ b/lang/id/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Masukkan username Instagram yang valid.',
'thumbnail_tab' => 'Thumbnail',
'thumbnail_heading' => 'Pilih thumbnail',
- 'thumbnail_hint' => 'Geser slider untuk memilih frame yang menjadi sampul video.',
+ 'thumbnail_hint' => 'Geser di sepanjang frame video untuk memilih yang menjadi sampul.',
'thumbnail_value' => ':seconds detik',
+ 'thumbnail_source_frame' => 'Frame video',
+ 'thumbnail_source_image' => 'Gambar',
+ 'thumbnail_image_hint' => 'Videomu menampilkan gambar ini sebagai sampul. Gunakan gambar 9:16 agar tidak ada yang terpotong.',
+ 'thumbnail_capture_failed' => 'Tidak dapat mengambil frame ini. Unggah gambar sebagai sampul.',
+ 'thumbnail_image_upload' => 'Unggah gambar',
+ 'thumbnail_image_replace' => 'Ganti gambar',
'video_thumbnail' => 'Video :number',
'thumbnail' => 'Gambar :number',
'cancel' => 'Batal',
@@ -919,6 +925,8 @@ return [
'media_expired' => 'Unggahan ini kedaluwarsa. Tambahkan lagi filenya.',
'cover_offset_min' => 'Waktu cover video harus 0 ms atau lebih.',
'cover_offset_max' => 'Waktu cover video harus :max ms atau kurang.',
+ 'cover_invalid' => 'Pilih gambar untuk sampul video.',
+ 'cover_not_image' => 'Sampul video harus berupa gambar JPEG, PNG, atau WebP.',
'media_item_shape' => 'Setiap item media butuh tepat satu dari upload_token, url, atau id.',
'media_url_unreachable' => 'Media dari :url gagal diambil.',
'media_type_unsupported' => 'Tipe file ini tidak didukung oleh channel postingan ini.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Baru',
'add_post_in_slot' => 'Tambahkan postingan',
'more_times' => 'Waktu lainnya',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Perhatian',
+ 'title' => 'Sampul tidak diterapkan',
+ 'forbidden' => 'Channel YouTube-mu belum terverifikasi. Untuk memposting dengan sampulmu sendiri, verifikasi di :url',
+ 'daily_limit' => 'Channel-mu mencapai batas harian sampul kustom YouTube. Besok postinganmu kembali memakai sampulnya, dan sampul posting ini bisa kamu atur di YouTube Studio.',
+ 'invalid_image' => 'YouTube tidak dapat membaca gambar sampulmu. Kamu bisa mengatur yang lain di YouTube Studio.',
+ 'failed' => 'YouTube tidak menerapkan sampulmu. Kamu bisa mengaturnya di YouTube Studio.',
+ ],
'failure' => [
'title' => 'Kenapa gagal',
'generic' => 'Postingan ini gagal diterbitkan.',
diff --git a/lang/it/posts.php b/lang/it/posts.php
index 44ca538e6..4f2367bf6 100644
--- a/lang/it/posts.php
+++ b/lang/it/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Inserisci un nome utente Instagram valido.',
'thumbnail_tab' => 'Miniatura',
'thumbnail_heading' => 'Scegli una miniatura',
- 'thumbnail_hint' => 'Trascina il cursore per scegliere il fotogramma mostrato come copertina del video.',
+ 'thumbnail_hint' => 'Trascina lungo i fotogrammi del video per scegliere quello mostrato come copertina.',
'thumbnail_value' => ':seconds secondi',
+ 'thumbnail_source_frame' => 'Fotogramma',
+ 'thumbnail_source_image' => 'Immagine',
+ 'thumbnail_image_hint' => 'Il tuo video mostra questa immagine come copertina. Usa un\'immagine 9:16 così non viene tagliato nulla.',
+ 'thumbnail_capture_failed' => 'Impossibile catturare questo fotogramma. Carica invece un\'immagine come copertina.',
+ 'thumbnail_image_upload' => 'Carica immagine',
+ 'thumbnail_image_replace' => 'Sostituisci',
'video_thumbnail' => 'Video :number',
'thumbnail' => 'Immagine :number',
'cancel' => 'Annulla',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'Questo caricamento è scaduto. Aggiungi di nuovo il file.',
'cover_offset_min' => 'Il tempo della copertina del video deve essere di 0 ms o più.',
'cover_offset_max' => 'Il tempo della copertina del video deve essere di :max ms o meno.',
+ 'cover_invalid' => 'Scegli un\'immagine per la copertina del video.',
+ 'cover_not_image' => 'La copertina del video deve essere un\'immagine JPEG, PNG o WebP.',
'media_item_shape' => 'Ogni elemento multimediale richiede esattamente uno tra upload_token, url o id.',
- 'media_url_unreachable' => 'Impossibile recuperare il contenuto multimediale da :url.',
+ 'media_url_unreachable' => 'Impossibile recuperare il contenuto multimediale da :url',
'media_type_unsupported' => 'Questo tipo di file non è supportato dal canale del post.',
'media_not_accepted' => 'Questo tipo di post non può includere media. Cambia il tipo di post per aggiungerli.',
'media_file_unsupported' => 'Questo tipo di file non è supportato.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Nuovo',
'add_post_in_slot' => 'Aggiungi post',
'more_times' => 'Altri orari',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Avviso',
+ 'title' => 'Copertina non applicata',
+ 'forbidden' => 'Il tuo canale YouTube non è ancora verificato. Per pubblicare con la tua copertina, verificalo su :url',
+ 'daily_limit' => 'Il tuo canale ha raggiunto il limite giornaliero di copertine personalizzate di YouTube. Da domani i tuoi post tornano ad avere la copertina, e quella di questo puoi impostarla in YouTube Studio.',
+ 'invalid_image' => 'YouTube non è riuscito a leggere l\'immagine di copertina. Puoi impostarne un\'altra in YouTube Studio.',
+ 'failed' => 'YouTube non ha applicato la copertina. Puoi impostarla in YouTube Studio.',
+ ],
'failure' => [
'title' => 'Perché non è riuscito',
'generic' => 'Non siamo riusciti a pubblicare questo post.',
diff --git a/lang/ja/posts.php b/lang/ja/posts.php
index cdae02fcd..c99f1f245 100644
--- a/lang/ja/posts.php
+++ b/lang/ja/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => '有効なInstagramのユーザーネームを入力してください。',
'thumbnail_tab' => 'サムネイル',
'thumbnail_heading' => 'サムネイルを選択',
- 'thumbnail_hint' => 'スライダーをドラッグして、動画のカバーとして表示するフレームを選んでください。',
+ 'thumbnail_hint' => '動画のフレームに沿ってドラッグして、カバーにするフレームを選んでください。',
'thumbnail_value' => ':seconds 秒',
+ 'thumbnail_source_frame' => '動画のフレーム',
+ 'thumbnail_source_image' => '画像',
+ 'thumbnail_image_hint' => 'この画像が動画のカバーになります。切れないように9:16の画像を使ってください。',
+ 'thumbnail_capture_failed' => 'このフレームを取得できませんでした。代わりにカバー画像をアップロードしてください。',
+ 'thumbnail_image_upload' => '画像をアップロード',
+ 'thumbnail_image_replace' => '画像を変更',
'video_thumbnail' => '動画 :number',
'thumbnail' => '画像 :number',
'cancel' => 'キャンセル',
@@ -919,6 +925,8 @@ return [
'media_expired' => 'このアップロードは期限切れです。ファイルをもう一度追加してください。',
'cover_offset_min' => '動画カバーの時間は 0 ms 以上にしてください。',
'cover_offset_max' => '動画カバーの時間は :max ms 以下にしてください。',
+ 'cover_invalid' => '動画のカバーにする画像を選んでください。',
+ 'cover_not_image' => '動画のカバーはJPEG、PNG、WebPの画像にしてください。',
'media_item_shape' => '各メディア項目には、upload_token、url、id のいずれか1つだけを指定してください。',
'media_url_unreachable' => ':url からメディアを取得できませんでした。',
'media_type_unsupported' => 'このファイル形式は、投稿のチャンネルでサポートされていません。',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => '新規',
'add_post_in_slot' => '投稿を追加',
'more_times' => 'その他の時間',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => '注意',
+ 'title' => 'カバーが適用されませんでした',
+ 'forbidden' => 'YouTubeチャンネルがまだ確認されていません。独自のカバーで投稿するには、:url でチャンネルを確認してください。',
+ 'daily_limit' => 'チャンネルがYouTubeのカスタムカバーの1日の上限に達しました。明日からは投稿にカバーが再び適用されます。この投稿のカバーはYouTube Studioで設定できます。',
+ 'invalid_image' => 'YouTubeがカバー画像を読み込めませんでした。YouTube Studioで別の画像を設定できます。',
+ 'failed' => 'YouTubeでカバー画像が適用されませんでした。YouTube Studioで設定できます。',
+ ],
'failure' => [
'title' => '失敗した理由',
'generic' => 'この投稿を公開できませんでした。',
diff --git a/lang/ko/posts.php b/lang/ko/posts.php
index b59a3c9ff..60b93bf71 100644
--- a/lang/ko/posts.php
+++ b/lang/ko/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => '유효한 Instagram 사용자 이름을 입력하세요.',
'thumbnail_tab' => '썸네일',
'thumbnail_heading' => '썸네일 선택',
- 'thumbnail_hint' => '슬라이더를 끌어 동영상 커버로 표시할 프레임을 선택하세요.',
+ 'thumbnail_hint' => '동영상 프레임을 따라 드래그해 커버로 표시할 프레임을 선택하세요.',
'thumbnail_value' => ':seconds초',
+ 'thumbnail_source_frame' => '동영상 프레임',
+ 'thumbnail_source_image' => '이미지',
+ 'thumbnail_image_hint' => '이 이미지가 동영상 커버로 표시됩니다. 잘리지 않도록 9:16 이미지를 사용하세요.',
+ 'thumbnail_capture_failed' => '이 프레임을 캡처하지 못했습니다. 대신 커버 이미지를 업로드하세요.',
+ 'thumbnail_image_upload' => '이미지 업로드',
+ 'thumbnail_image_replace' => '이미지 변경',
'video_thumbnail' => '동영상 :number',
'thumbnail' => '이미지 :number',
'cancel' => '취소',
@@ -919,6 +925,8 @@ return [
'media_expired' => '이 업로드는 만료되었습니다. 파일을 다시 추가하세요.',
'cover_offset_min' => '동영상 커버 시간은 0ms 이상이어야 합니다.',
'cover_offset_max' => '동영상 커버 시간은 :max ms 이하여야 합니다.',
+ 'cover_invalid' => '동영상 커버로 사용할 이미지를 선택하세요.',
+ 'cover_not_image' => '동영상 커버는 JPEG, PNG 또는 WebP 이미지여야 합니다.',
'media_item_shape' => '각 미디어 항목에는 upload_token, url, id 중 정확히 하나가 필요합니다.',
'media_url_unreachable' => ':url에서 미디어를 가져올 수 없습니다.',
'media_type_unsupported' => '이 파일 형식은 게시물의 채널에서 지원되지 않습니다.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => '신규',
'add_post_in_slot' => '게시물 추가',
'more_times' => '더 많은 시간',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => '주의',
+ 'title' => '커버가 적용되지 않음',
+ 'forbidden' => 'YouTube 채널이 아직 인증되지 않았습니다. 직접 만든 커버로 게시하려면 :url에서 채널을 인증하세요.',
+ 'daily_limit' => '채널이 YouTube의 맞춤 커버 일일 한도에 도달했습니다. 내일부터 게시물에 다시 커버가 적용되며, 이 게시물의 커버는 YouTube 스튜디오에서 설정할 수 있습니다.',
+ 'invalid_image' => 'YouTube에서 커버 이미지를 읽지 못했습니다. YouTube 스튜디오에서 다른 이미지를 설정할 수 있습니다.',
+ 'failed' => 'YouTube에서 커버 이미지를 적용하지 않았습니다. YouTube 스튜디오에서 설정할 수 있습니다.',
+ ],
'failure' => [
'title' => '실패한 이유',
'generic' => '이 게시물을 게시하지 못했습니다.',
diff --git a/lang/nl/posts.php b/lang/nl/posts.php
index af457e94f..007444e1d 100644
--- a/lang/nl/posts.php
+++ b/lang/nl/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Voer een geldige Instagram-gebruikersnaam in.',
'thumbnail_tab' => 'Miniatuur',
'thumbnail_heading' => 'Kies een miniatuur',
- 'thumbnail_hint' => 'Sleep de schuifregelaar om het beeld te kiezen dat als omslag van de video wordt getoond.',
+ 'thumbnail_hint' => 'Sleep langs de beelden van de video om het beeld te kiezen dat als omslag wordt getoond.',
'thumbnail_value' => ':seconds seconden',
+ 'thumbnail_source_frame' => 'Videoframe',
+ 'thumbnail_source_image' => 'Afbeelding',
+ 'thumbnail_image_hint' => 'Je video toont deze afbeelding als omslag. Gebruik een afbeelding van 9:16 zodat er niets wordt afgesneden.',
+ 'thumbnail_capture_failed' => 'Dit videoframe kon niet worden vastgelegd. Upload in plaats daarvan een afbeelding als omslag.',
+ 'thumbnail_image_upload' => 'Afbeelding uploaden',
+ 'thumbnail_image_replace' => 'Vervangen',
'video_thumbnail' => 'Video :number',
'thumbnail' => 'Afbeelding :number',
'cancel' => 'Annuleren',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'Deze upload is verlopen. Voeg het bestand opnieuw toe.',
'cover_offset_min' => 'Het tijdstip van de video-omslag moet 0 ms of meer zijn.',
'cover_offset_max' => 'Het tijdstip van de video-omslag mag maximaal :max ms zijn.',
+ 'cover_invalid' => 'Kies een afbeelding als omslag van de video.',
+ 'cover_not_image' => 'De omslag van de video moet een JPEG-, PNG- of WebP-afbeelding zijn.',
'media_item_shape' => 'Elk media-item heeft precies één van upload_token, url of id nodig.',
- 'media_url_unreachable' => 'Media kon niet worden opgehaald van :url.',
+ 'media_url_unreachable' => 'Media kon niet worden opgehaald van :url',
'media_type_unsupported' => 'Dit bestandstype wordt niet ondersteund door het kanaal van de post.',
'media_not_accepted' => 'Dit type post kan geen media bevatten. Wijzig het type post om media toe te voegen.',
'media_file_unsupported' => 'Dit bestandstype wordt niet ondersteund.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Nieuw',
'add_post_in_slot' => 'Post toevoegen',
'more_times' => 'Meer tijden',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Let op',
+ 'title' => 'Omslag niet toegepast',
+ 'forbidden' => 'Je YouTube-kanaal is nog niet geverifieerd. Verifieer het via :url om met je eigen omslag te publiceren.',
+ 'daily_limit' => 'Je kanaal heeft de daglimiet voor eigen omslagen op YouTube bereikt. Morgen krijgen je posts weer hun omslag, en die van deze kun je instellen in YouTube Studio.',
+ 'invalid_image' => 'YouTube kon je omslagafbeelding niet lezen. Je kunt een andere instellen in YouTube Studio.',
+ 'failed' => 'YouTube heeft je omslag niet toegepast. Je kunt hem instellen in YouTube Studio.',
+ ],
'failure' => [
'title' => 'Waarom het mislukte',
'generic' => 'We konden deze post niet publiceren.',
diff --git a/lang/pl/posts.php b/lang/pl/posts.php
index 239e66f13..cc6f70f8a 100644
--- a/lang/pl/posts.php
+++ b/lang/pl/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Wpisz poprawną nazwę użytkownika Instagrama.',
'thumbnail_tab' => 'Miniatura',
'thumbnail_heading' => 'Wybierz miniaturę',
- 'thumbnail_hint' => 'Przeciągnij suwak, aby wybrać klatkę wyświetlaną jako okładka filmu.',
+ 'thumbnail_hint' => 'Przeciągnij po klatkach filmu, aby wybrać tę, która będzie okładką.',
'thumbnail_value' => ':seconds s',
+ 'thumbnail_source_frame' => 'Klatka wideo',
+ 'thumbnail_source_image' => 'Obraz',
+ 'thumbnail_image_hint' => 'Twoje wideo pokazuje ten obraz jako okładkę. Użyj obrazu 9:16, aby nic nie zostało przycięte.',
+ 'thumbnail_capture_failed' => 'Nie udało się przechwycić tej klatki. Prześlij obraz jako okładkę.',
+ 'thumbnail_image_upload' => 'Prześlij obraz',
+ 'thumbnail_image_replace' => 'Zmień obraz',
'video_thumbnail' => 'Film :number',
'thumbnail' => 'Zdjęcie :number',
'cancel' => 'Anuluj',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'Ten przesłany plik wygasł. Dodaj plik ponownie.',
'cover_offset_min' => 'Czas okładki filmu musi wynosić 0 ms lub więcej.',
'cover_offset_max' => 'Czas okładki filmu może wynosić najwyżej :max ms.',
+ 'cover_invalid' => 'Wybierz obraz na okładkę wideo.',
+ 'cover_not_image' => 'Okładka wideo musi być obrazem JPEG, PNG lub WebP.',
'media_item_shape' => 'Każdy element multimedialny wymaga dokładnie jednego z pól: upload_token, url lub id.',
- 'media_url_unreachable' => 'Nie udało się pobrać multimediów z :url.',
+ 'media_url_unreachable' => 'Nie udało się pobrać multimediów z :url',
'media_type_unsupported' => 'Ten typ pliku nie jest obsługiwany przez kanał posta.',
'media_not_accepted' => 'Ten typ posta nie może zawierać multimediów. Zmień typ posta, aby je dodać.',
'media_file_unsupported' => 'Ten typ pliku nie jest obsługiwany.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Nowy',
'add_post_in_slot' => 'Dodaj post',
'more_times' => 'Więcej godzin',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Uwaga',
+ 'title' => 'Nie zastosowano okładki',
+ 'forbidden' => 'Twój kanał YouTube nie jest jeszcze zweryfikowany. Aby publikować z własną okładką, zweryfikuj go na :url',
+ 'daily_limit' => 'Kanał osiągnął dzienny limit własnych okładek w YouTube. Od jutra posty znów będą publikowane z okładką, a okładkę tego posta możesz ustawić w YouTube Studio.',
+ 'invalid_image' => 'YouTube nie mógł odczytać obrazu okładki. Inny można ustawić w YouTube Studio.',
+ 'failed' => 'YouTube nie zastosował okładki. Możesz ją ustawić w YouTube Studio.',
+ ],
'failure' => [
'title' => 'Dlaczego się nie udało',
'generic' => 'Nie udało się opublikować tego posta.',
diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.php
index f13854e06..031c852eb 100644
--- a/lang/pt-BR/posts.php
+++ b/lang/pt-BR/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Digite um usuário válido do Instagram.',
'thumbnail_tab' => 'Miniatura',
'thumbnail_heading' => 'Escolha uma miniatura',
- 'thumbnail_hint' => 'Arraste o controle para escolher o quadro exibido como capa do vídeo.',
+ 'thumbnail_hint' => 'Arraste pelos quadros do vídeo para escolher o que aparece como capa.',
'thumbnail_value' => ':seconds segundos',
+ 'thumbnail_source_frame' => 'Quadro do vídeo',
+ 'thumbnail_source_image' => 'Imagem',
+ 'thumbnail_image_hint' => 'Seu vídeo mostra essa imagem como capa. Use uma imagem 9:16 para nada ser cortado.',
+ 'thumbnail_capture_failed' => 'Não foi possível capturar esse quadro. Envie uma imagem como capa.',
+ 'thumbnail_image_upload' => 'Enviar imagem',
+ 'thumbnail_image_replace' => 'Trocar imagem',
'video_thumbnail' => 'Vídeo :number',
'thumbnail' => 'Imagem :number',
'cancel' => 'Cancelar',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'Este envio expirou. Adicione o arquivo novamente.',
'cover_offset_min' => 'O tempo da capa do vídeo deve ser de 0 ms ou mais.',
'cover_offset_max' => 'O tempo da capa do vídeo deve ser de :max ms ou menos.',
+ 'cover_invalid' => 'Escolha uma imagem para a capa do vídeo.',
+ 'cover_not_image' => 'A capa do vídeo precisa ser uma imagem JPEG, PNG ou WebP.',
'media_item_shape' => 'Cada item de mídia precisa de exatamente um entre upload_token, url ou id.',
- 'media_url_unreachable' => 'Não foi possível buscar a mídia em :url.',
+ 'media_url_unreachable' => 'Não foi possível buscar a mídia em :url',
'media_type_unsupported' => 'Este tipo de arquivo não é compatível com o canal do post.',
'media_not_accepted' => 'Este tipo de post não aceita mídia. Mude o tipo de post para adicionar mídia.',
'media_file_unsupported' => 'Este tipo de arquivo não é compatível.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Novo',
'add_post_in_slot' => 'Adicionar post',
'more_times' => 'Mais horários',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Atenção',
+ 'title' => 'Capa não aplicada',
+ 'forbidden' => 'Seu canal do YouTube ainda não está verificado. Para publicar com a sua capa, verifique o canal em :url',
+ 'daily_limit' => 'Seu canal atingiu o limite diário de capas personalizadas do YouTube. Amanhã seus posts voltam a sair com a capa, e a deste você pode definir no YouTube Studio.',
+ 'invalid_image' => 'O YouTube não conseguiu ler sua imagem de capa. Você pode definir outra no YouTube Studio.',
+ 'failed' => 'O YouTube não aplicou sua capa. Você pode definir a capa no YouTube Studio.',
+ ],
'failure' => [
'title' => 'Por que falhou',
'generic' => 'Não conseguimos publicar este post.',
diff --git a/lang/ru/posts.php b/lang/ru/posts.php
index 16efb1631..fd1826e5a 100644
--- a/lang/ru/posts.php
+++ b/lang/ru/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Введите корректное имя пользователя Instagram.',
'thumbnail_tab' => 'Обложка',
'thumbnail_heading' => 'Выберите обложку',
- 'thumbnail_hint' => 'Перетащите ползунок, чтобы выбрать кадр, который будет обложкой видео.',
+ 'thumbnail_hint' => 'Перетащите по кадрам видео, чтобы выбрать кадр для обложки.',
'thumbnail_value' => ':seconds с',
+ 'thumbnail_source_frame' => 'Кадр видео',
+ 'thumbnail_source_image' => 'Изображение',
+ 'thumbnail_image_hint' => 'Это изображение станет обложкой видео. Используйте изображение 9:16, чтобы ничего не обрезалось.',
+ 'thumbnail_capture_failed' => 'Не удалось захватить этот кадр. Загрузите изображение для обложки.',
+ 'thumbnail_image_upload' => 'Загрузить фото',
+ 'thumbnail_image_replace' => 'Заменить фото',
'video_thumbnail' => 'Видео :number',
'thumbnail' => 'Изображение :number',
'cancel' => 'Отмена',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'Срок действия этой загрузки истёк. Добавьте файл ещё раз.',
'cover_offset_min' => 'Время обложки видео должно быть не меньше 0 мс.',
'cover_offset_max' => 'Время обложки видео должно быть не больше :max мс.',
+ 'cover_invalid' => 'Выберите изображение для обложки видео.',
+ 'cover_not_image' => 'Обложка видео должна быть изображением JPEG, PNG или WebP.',
'media_item_shape' => 'Каждому медиафайлу нужно ровно одно из полей: upload_token, url или id.',
- 'media_url_unreachable' => 'Не удалось получить медиафайл по адресу :url.',
+ 'media_url_unreachable' => 'Не удалось получить медиафайл по адресу :url',
'media_type_unsupported' => 'Этот тип файла не поддерживается каналом публикации.',
'media_not_accepted' => 'Этот тип публикации не поддерживает медиафайлы. Измените тип публикации, чтобы добавить их.',
'media_file_unsupported' => 'Этот тип файла не поддерживается.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Новый',
'add_post_in_slot' => 'Добавить пост',
'more_times' => 'Другое время',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Внимание',
+ 'title' => 'Обложка не применена',
+ 'forbidden' => 'Ваш канал YouTube ещё не подтверждён. Чтобы публиковать со своей обложкой, подтвердите его на :url',
+ 'daily_limit' => 'Канал исчерпал дневной лимит собственных обложек на YouTube. Завтра посты снова будут выходить с обложкой, а обложку этого можно задать в YouTube Studio.',
+ 'invalid_image' => 'YouTube не смог прочитать изображение обложки. Другое можно задать в YouTube Studio.',
+ 'failed' => 'YouTube не применил обложку. Её можно задать в YouTube Studio.',
+ ],
'failure' => [
'title' => 'Почему не удалось',
'generic' => 'Не удалось опубликовать этот пост.',
diff --git a/lang/tr/posts.php b/lang/tr/posts.php
index 687223129..7326729b3 100644
--- a/lang/tr/posts.php
+++ b/lang/tr/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Geçerli bir Instagram kullanıcı adı girin.',
'thumbnail_tab' => 'Kapak',
'thumbnail_heading' => 'Küçük resim seçin',
- 'thumbnail_hint' => 'Videonun kapağı olarak gösterilecek kareyi seçmek için kaydırıcıyı sürükleyin.',
+ 'thumbnail_hint' => 'Kapak olarak gösterilecek kareyi seçmek için videonun kareleri boyunca sürükleyin.',
'thumbnail_value' => ':seconds saniye',
+ 'thumbnail_source_frame' => 'Video karesi',
+ 'thumbnail_source_image' => 'Görsel',
+ 'thumbnail_image_hint' => 'Videonuz bu görseli kapak olarak gösterir. Hiçbir yerin kesilmemesi için 9:16 bir görsel kullanın.',
+ 'thumbnail_capture_failed' => 'Bu kare yakalanamadı. Bunun yerine kapak olarak bir görsel yükleyin.',
+ 'thumbnail_image_upload' => 'Görsel yükle',
+ 'thumbnail_image_replace' => 'Görseli değiştir',
'video_thumbnail' => 'Video :number',
'thumbnail' => 'Görsel :number',
'cancel' => 'İptal',
@@ -919,6 +925,8 @@ return [
'media_expired' => 'Bu yüklemenin süresi doldu. Dosyayı yeniden ekleyin.',
'cover_offset_min' => 'Video kapağı zamanı 0 ms veya daha fazla olmalıdır.',
'cover_offset_max' => 'Video kapağı zamanı en fazla :max ms olabilir.',
+ 'cover_invalid' => 'Video kapağı için bir görsel seçin.',
+ 'cover_not_image' => 'Video kapağı JPEG, PNG veya WebP görseli olmalıdır.',
'media_item_shape' => 'Her medya öğesi upload_token, url veya id alanlarından tam olarak birini içermelidir.',
'media_url_unreachable' => 'Medya :url adresinden alınamadı.',
'media_type_unsupported' => 'Bu dosya türü, gönderinin kanalı tarafından desteklenmiyor.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Yeni',
'add_post_in_slot' => 'Gönderi ekle',
'more_times' => 'Daha fazla saat',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Uyarı',
+ 'title' => 'Kapak uygulanmadı',
+ 'forbidden' => 'YouTube kanalınız henüz doğrulanmadı. Kendi kapağınızla yayınlamak için kanalınızı :url adresinden doğrulayın.',
+ 'daily_limit' => 'Kanalınız YouTube\'un günlük özel kapak sınırına ulaştı. Yarın gönderileriniz yeniden kapaklarıyla yayınlanır; bu gönderinin kapağını YouTube Studio\'da ayarlayabilirsiniz.',
+ 'invalid_image' => 'YouTube kapak görselinizi okuyamadı. YouTube Studio\'da başka bir görsel ayarlayabilirsiniz.',
+ 'failed' => 'YouTube kapağınızı uygulamadı. Kapağı YouTube Studio\'da ayarlayabilirsiniz.',
+ ],
'failure' => [
'title' => 'Neden başarısız oldu',
'generic' => 'Bu gönderiyi yayınlayamadık.',
diff --git a/lang/uk/posts.php b/lang/uk/posts.php
index 31c501906..c657b470e 100644
--- a/lang/uk/posts.php
+++ b/lang/uk/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => 'Введіть коректне ім\'я користувача Instagram.',
'thumbnail_tab' => 'Обкладинка',
'thumbnail_heading' => 'Виберіть обкладинку',
- 'thumbnail_hint' => 'Перетягніть повзунок, щоб вибрати кадр, який буде обкладинкою відео.',
+ 'thumbnail_hint' => 'Перетягніть по кадрах відео, щоб вибрати кадр для обкладинки.',
'thumbnail_value' => ':seconds с',
+ 'thumbnail_source_frame' => 'Кадр відео',
+ 'thumbnail_source_image' => 'Зображення',
+ 'thumbnail_image_hint' => 'Це зображення стане обкладинкою відео. Використовуйте зображення 9:16, щоб нічого не обрізалося.',
+ 'thumbnail_capture_failed' => 'Не вдалося захопити цей кадр. Завантажте зображення для обкладинки.',
+ 'thumbnail_image_upload' => 'Завантажити фото',
+ 'thumbnail_image_replace' => 'Замінити фото',
'video_thumbnail' => 'Відео :number',
'thumbnail' => 'Зображення :number',
'cancel' => 'Скасувати',
@@ -919,8 +925,10 @@ return [
'media_expired' => 'Термін дії цього завантаження минув. Додайте файл ще раз.',
'cover_offset_min' => 'Час обкладинки відео має бути не менше 0 мс.',
'cover_offset_max' => 'Час обкладинки відео має бути не більше :max мс.',
+ 'cover_invalid' => 'Виберіть зображення для обкладинки відео.',
+ 'cover_not_image' => 'Обкладинка відео має бути зображенням JPEG, PNG або WebP.',
'media_item_shape' => 'Кожному медіафайлу потрібне рівно одне з полів: upload_token, url або id.',
- 'media_url_unreachable' => 'Не вдалося отримати медіафайл за адресою :url.',
+ 'media_url_unreachable' => 'Не вдалося отримати медіафайл за адресою :url',
'media_type_unsupported' => 'Цей тип файлу не підтримується каналом публікації.',
'media_not_accepted' => 'Цей тип публікації не підтримує медіафайли. Змініть тип публікації, щоб додати їх.',
'media_file_unsupported' => 'Цей тип файлу не підтримується.',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => 'Новий',
'add_post_in_slot' => 'Додати допис',
'more_times' => 'Інший час',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => 'Увага',
+ 'title' => 'Обкладинку не застосовано',
+ 'forbidden' => 'Ваш канал YouTube ще не підтверджено. Щоб публікувати зі своєю обкладинкою, підтвердьте його на :url',
+ 'daily_limit' => 'Канал вичерпав денний ліміт власних обкладинок на YouTube. Завтра дописи знову виходитимуть з обкладинкою, а обкладинку цього можна задати в YouTube Studio.',
+ 'invalid_image' => 'YouTube не зміг прочитати зображення обкладинки. Інше можна задати в YouTube Studio.',
+ 'failed' => 'YouTube не застосував обкладинку. Її можна задати в YouTube Studio.',
+ ],
'failure' => [
'title' => 'Чому не вдалося',
'generic' => 'Не вдалося опублікувати цей пост.',
diff --git a/lang/zh/posts.php b/lang/zh/posts.php
index 01f31e968..ac27c3b9a 100644
--- a/lang/zh/posts.php
+++ b/lang/zh/posts.php
@@ -274,8 +274,14 @@ return [
'tags_invalid' => '请输入有效的 Instagram 用户名。',
'thumbnail_tab' => '缩略图',
'thumbnail_heading' => '选择缩略图',
- 'thumbnail_hint' => '拖动滑块,选择用作视频封面的画面。',
+ 'thumbnail_hint' => '沿视频画面拖动,选择用作封面的画面。',
'thumbnail_value' => ':seconds 秒',
+ 'thumbnail_source_frame' => '视频帧',
+ 'thumbnail_source_image' => '图片',
+ 'thumbnail_image_hint' => '你的视频会以这张图片作为封面。请使用 9:16 的图片,避免被裁切。',
+ 'thumbnail_capture_failed' => '无法截取这一帧。请改为上传一张图片作为封面。',
+ 'thumbnail_image_upload' => '上传图片',
+ 'thumbnail_image_replace' => '更换图片',
'video_thumbnail' => '视频 :number',
'thumbnail' => '图片 :number',
'cancel' => '取消',
@@ -919,6 +925,8 @@ return [
'media_expired' => '此上传已过期。请重新添加文件。',
'cover_offset_min' => '视频封面时间必须不小于 0 毫秒。',
'cover_offset_max' => '视频封面时间不能超过 :max 毫秒。',
+ 'cover_invalid' => '请为视频封面选择一张图片。',
+ 'cover_not_image' => '视频封面必须是 JPEG、PNG 或 WebP 图片。',
'media_item_shape' => '每个媒体项必须且只能提供 upload_token、url 或 id 中的一个。',
'media_url_unreachable' => '无法从 :url 获取媒体。',
'media_type_unsupported' => '帖子的频道不支持此文件类型。',
@@ -1035,6 +1043,14 @@ return [
'new_in_slot' => '新建',
'add_post_in_slot' => '添加帖子',
'more_times' => '更多时间',
+ 'youtube_thumbnail_warning' => [
+ 'badge' => '注意',
+ 'title' => '封面未应用',
+ 'forbidden' => '你的 YouTube 频道尚未验证。要使用自己的封面发布,请在 :url 验证频道。',
+ 'daily_limit' => '你的频道已达到 YouTube 每日自定义封面上限。明天起你的帖子会重新带上封面,这篇的封面可以在 YouTube 工作室中设置。',
+ 'invalid_image' => 'YouTube 无法读取你的封面图片。你可以在 YouTube 工作室中设置另一张。',
+ 'failed' => 'YouTube 未应用你的封面。你可以在 YouTube 工作室中设置。',
+ ],
'failure' => [
'title' => '失败原因',
'generic' => '无法发布此帖子。',
diff --git a/resources/js/components/media/MediaTile.vue b/resources/js/components/media/MediaTile.vue
index e9d9a510f..d49f44e2b 100644
--- a/resources/js/components/media/MediaTile.vue
+++ b/resources/js/components/media/MediaTile.vue
@@ -11,6 +11,7 @@ import {
} from '@tabler/icons-vue';
import { computed, onBeforeUnmount } from 'vue';
+import VideoStill from '@/components/media/VideoStill.vue';
import {
Tooltip,
TooltipContent,
@@ -118,14 +119,7 @@ const uploadActionClass =
class="size-full object-cover"
/>
<template v-else-if="isVideo(item)">
- <video
- :src="item.url"
- class="size-full object-cover"
- muted
- playsinline
- preload="metadata"
- draggable="false"
- />
+ <VideoStill :item="item" class="size-full object-cover" />
<IconPlayerPlayFilled
aria-hidden="true"
class="absolute top-1/2 left-1/2 size-8 -translate-x-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2 text-white"
diff --git a/resources/js/components/media/MediaTray.vue b/resources/js/components/media/MediaTray.vue
index 6bc832063..afe52442e 100644
--- a/resources/js/components/media/MediaTray.vue
+++ b/resources/js/components/media/MediaTray.vue
@@ -34,6 +34,7 @@ import { cancelDragOnEscape } from '@/lib/dragPlaceholder';
import { editorTabsFor, rulesFor, type EditorTab } from '@/lib/mediaEditor';
import { canvaDesignId, editInCanva } from '@/lib/mediaSources/canva';
import { acceptAttribute, isImage, isVideo, mediaKey } from '@/lib/mediaType';
+import { withCoversFor } from '@/lib/videoFrame';
import type { MediaUploadLimits, SharedData } from '@/types';
import type { MediaItem } from '@/types/media';
@@ -70,6 +71,14 @@ const uploader =
watch(uploader.busy, (busy) => emit('busy', busy), { immediate: true });
const editorRules = computed(() => rulesFor(props.contentTypes));
+
+/** Whether a network of the post takes a cover image, so the tiles show the one uploaded. */
+const takesCoverImage = computed(() =>
+ editorRules.value.some((rule) => rule.supportsCustomVideoCover),
+);
+
+/** The items as the tiles draw them, without an uploaded cover no network of the post shows. */
+const tileItems = computed(() => withCoversFor(props.items, takesCoverImage.value));
const itemTabs = computed<EditorTab[][]>(() =>
props.items.map((item) => editorTabsFor(item, editorRules.value)),
);
@@ -388,7 +397,7 @@ const vSortableTile: Directive<HTMLElement> = {
<MediaTile
:test-id-prefix="testIdPrefix"
:index="index"
- :item="items[index]!"
+ :item="tileItems[index]!"
:tabs="itemTabs[index]"
:disabled="disabled"
:error="itemErrors?.[index]"
diff --git a/resources/js/components/media/VideoStill.vue b/resources/js/components/media/VideoStill.vue
new file mode 100644
index 000000000..a3cd79cb7
--- /dev/null
+++ b/resources/js/components/media/VideoStill.vue
@@ -0,0 +1,38 @@
+<script setup lang="ts">
+import { computed } from 'vue';
+
+import { storedCoverSource } from '@/lib/mediaEditor';
+import { videoFrameUrl } from '@/lib/videoFrame';
+import type { MediaItem } from '@/types/media';
+
+/**
+ * A video shown still, as its cover: the image uploaded as its cover, else
+ * the video painted at its picked frame, else at its start. A frame's
+ * screenshot (kept for the networks that take an image) is that same frame,
+ * so the video shows it. Classes and test ids fall through.
+ */
+const props = defineProps<{
+ item: Pick<MediaItem, 'url' | 'meta'>;
+}>();
+
+const coverImageUrl = computed(() => {
+ if (storedCoverSource(props.item) !== 'image') {
+ return null;
+ }
+
+ return props.item.meta?.cover?.url ?? null;
+});
+const frameUrl = computed(() => videoFrameUrl(props.item));
+</script>
+
+<template>
+ <img v-if="coverImageUrl" :src="coverImageUrl" alt="" draggable="false" />
+ <video
+ v-else
+ :src="frameUrl"
+ muted
+ playsinline
+ preload="metadata"
+ draggable="false"
+ />
+</template>
diff --git a/resources/js/components/posts/composer/MediaEditorDialog.vue b/resources/js/components/posts/composer/MediaEditorDialog.vue
index 63293419e..633a82b98 100644
--- a/resources/js/components/posts/composer/MediaEditorDialog.vue
+++ b/resources/js/components/posts/composer/MediaEditorDialog.vue
@@ -9,6 +9,7 @@ import MediaEditorAppearancePanel from '@/components/posts/composer/MediaEditorA
import MediaEditorCropPanel from '@/components/posts/composer/MediaEditorCropPanel.vue';
import MediaEditorTagsPanel from '@/components/posts/composer/MediaEditorTagsPanel.vue';
import MediaEditorThumbnailPanel from '@/components/posts/composer/MediaEditorThumbnailPanel.vue';
+import MediaEditorVideoTimeline from '@/components/posts/composer/MediaEditorVideoTimeline.vue';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -21,13 +22,18 @@ import {
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { type ImageSize, useImageCrop } from '@/composables/useImageCrop';
import { defaultCropPresets } from '@/lib/contentTypeMediaRules';
+import { filled } from '@/lib/helpers';
import {
createMediaEdit,
+ COVER_CROP_PRESET,
cropPresetsFor,
editorTabsFor,
type EditorTab,
hasMetaChanges,
+ hasCoverCropChanges,
hasPixelChanges,
+ needsFrameCapture,
+ newCoverImage,
type CropPresetValue,
type MediaEdit,
presetValuesFor,
@@ -37,7 +43,8 @@ import {
USER_TAGS_MAX,
} from '@/lib/mediaEditor';
import { isVideo } from '@/lib/mediaType';
-import type { MediaItem, MediaUserTag } from '@/types/media';
+import { captureVideoFrame } from '@/lib/videoFrame';
+import type { CoverImage, CoverSource, MediaItem, MediaUserTag } from '@/types/media';
export type MediaEditChange = {
index: number;
@@ -48,6 +55,8 @@ export type MediaEditChange = {
altText: string | null;
userTags: MediaUserTag[];
coverOffsetMs: number | null;
+ coverImage: CoverImage | null;
+ coverSource: CoverSource;
};
const props = withDefaults(
@@ -100,6 +109,7 @@ const tagging = ref(false);
const movingIndex = ref<number | null>(null);
const applying = ref(false);
const failed = ref(false);
+const captureFailed = ref(false);
const imageErrors = ref<Record<number, boolean>>({});
const isPhoto = computed(() => props.mode === 'photo');
@@ -121,6 +131,7 @@ const activeIsVideo = computed(() =>
);
const stageVideoEl = ref<HTMLVideoElement | null>(null);
const stageVideoDurations = ref<Record<number, number>>({});
+
const seekStageVideo = (): void => {
if (stageVideoEl.value && stageVideoEl.value.readyState > 0) {
stageVideoEl.value.currentTime =
@@ -140,6 +151,74 @@ const activeVideoDuration = computed<number | null>(
stageVideoDurations.value[activeIndex.value] ??
null,
);
+/** On the Thumbnail tab of a video with an image as its cover: the stage frames that image. */
+const cropsCover = computed(() => {
+ if (!activeIsVideo.value) {
+ return false;
+ }
+
+ if (tab.value !== 'thumbnail') {
+ return false;
+ }
+
+ if (!supportsCustomCover.value) {
+ return false;
+ }
+
+ if (edit.value?.coverSource !== 'image') {
+ return false;
+ }
+
+ return filled(edit.value?.coverImage);
+});
+
+/** On the Thumbnail tab of a video picking a frame: the strip to drag along. */
+const showsTimeline = computed(() => {
+ if (!activeIsVideo.value) {
+ return false;
+ }
+
+ if (tab.value !== 'thumbnail') {
+ return false;
+ }
+
+ if (!supportsCustomCover.value) {
+ return true;
+ }
+
+ return edit.value?.coverSource === 'frame';
+});
+
+/** The video the frame strip runs along, while the Thumbnail tab picks a frame. */
+const timelineVideo = computed(() => {
+ if (!filled(edit.value)) {
+ return null;
+ }
+
+ return activeItem.value ?? null;
+});
+
+/** The stage shows the video itself, unless it is framing the video's cover image. */
+const showsStageVideo = computed(() => {
+ if (!activeIsVideo.value) {
+ return false;
+ }
+
+ return !cropsCover.value;
+});
+
+/** The row of items to switch between, when there is more than one to edit. */
+const showsItemPicker = computed(() => {
+ if (isPhoto.value) {
+ return false;
+ }
+
+ return editingItems.value.length > 1;
+});
+
+const supportsCustomCover = computed(() =>
+ rules.value.some((rule) => rule.supportsCustomVideoCover),
+);
const tabs = computed<EditorTab[]>(() =>
activeItem.value ? editorTabsFor(activeItem.value, rules.value) : [],
);
@@ -152,43 +231,171 @@ const edit = computed({
},
});
const natural = computed(() => naturals.value[activeIndex.value] ?? null);
-const cropMode = computed(
- () => tab.value === 'edit' && section.value === 'crop',
-);
+
+/**
+ * What the stage and the crop controls work on: the active item, or the
+ * active video's cover image while it is being framed. The cover goes
+ * through the same stage, crop panel and render as any image.
+ */
+const stageEdit = computed({
+ get: (): MediaEdit | undefined => {
+ if (cropsCover.value) {
+ return edit.value?.coverImage?.crop;
+ }
+
+ return edit.value;
+ },
+ set: (value: MediaEdit | undefined) => {
+ if (!filled(value)) {
+ return;
+ }
+
+ if (!cropsCover.value) {
+ edit.value = value;
+
+ return;
+ }
+
+ if (filled(edit.value?.coverImage)) {
+ edit.value.coverImage.crop = value;
+ }
+ },
+});
+/** The cover's crop, while the stage frames the cover image. */
+const coverCropEdit = computed({
+ get: (): MediaEdit | undefined => {
+ if (!cropsCover.value) {
+ return undefined;
+ }
+
+ return stageEdit.value;
+ },
+ set: (value: MediaEdit | undefined) => {
+ stageEdit.value = value;
+ },
+});
+const stageNatural = computed(() => {
+ if (cropsCover.value) {
+ return edit.value?.coverImage?.natural ?? null;
+ }
+
+ return natural.value;
+});
+const stageSrc = computed(() => {
+ if (cropsCover.value) {
+ return edit.value?.coverImage?.url;
+ }
+
+ return activeItem.value?.url;
+});
+const stageBasePreset = computed<CropPresetValue>(() => {
+ if (cropsCover.value) {
+ return COVER_CROP_PRESET;
+ }
+
+ return basePreset.value;
+});
+/** A crosshair while a tag is being placed or moved on the stage. */
+const stageBoxClass = computed(() => {
+ if (tab.value !== 'tags') {
+ return '';
+ }
+
+ if (tagging.value) {
+ return 'cursor-crosshair';
+ }
+
+ if (movingIndex.value !== null) {
+ return 'cursor-crosshair';
+ }
+
+ return '';
+});
+const stagePresets = computed(() => {
+ if (cropsCover.value) {
+ return [];
+ }
+
+ return presets.value;
+});
+/** A fixed ratio only moves, except a profile photo's square and a cover's 9:16, which also resize. */
+const resizesAnyRatio = computed(() => {
+ if (isPhoto.value) {
+ return true;
+ }
+
+ return cropsCover.value;
+});
+const cropMode = computed(() => {
+ if (cropsCover.value) {
+ return true;
+ }
+
+ if (tab.value !== 'edit') {
+ return false;
+ }
+
+ return section.value === 'crop';
+});
const { isCentered, centerSelection, resetGeometry } = useImageCrop(
- edit,
- natural,
+ stageEdit,
+ stageNatural,
);
const centerDisabled = computed(
- () => !edit.value?.selection || isCentered.value,
+ () => !stageEdit.value?.selection || isCentered.value,
);
const resetDisabled = computed(
() =>
- !edit.value ||
- (edit.value.preset === basePreset.value &&
- !edit.value.selection &&
- edit.value.quarterTurns % 4 === 0 &&
- !edit.value.flipX &&
- !edit.value.flipY &&
- edit.value.straighten === 0),
+ !stageEdit.value ||
+ (stageEdit.value.preset === stageBasePreset.value &&
+ !stageEdit.value.selection &&
+ stageEdit.value.quarterTurns % 4 === 0 &&
+ !stageEdit.value.flipX &&
+ !stageEdit.value.flipY &&
+ stageEdit.value.straighten === 0),
);
+/**
+ * An item to apply: edited, or a video whose picked frame a network that
+ * takes no frame time (YouTube, added after the frame was picked) still has
+ * to get as a screenshot.
+ */
const isChanged = (index: number): boolean => {
const item = editingItems.value[index];
const itemEdit = edits.value[index];
- return Boolean(
- item &&
- itemEdit &&
- (hasPixelChanges(itemEdit) || hasMetaChanges(itemEdit, item)),
- );
+ if (!filled(item)) {
+ return false;
+ }
+
+ if (!filled(itemEdit)) {
+ return false;
+ }
+
+ if (hasPixelChanges(itemEdit)) {
+ return true;
+ }
+
+ if (hasMetaChanges(itemEdit, item)) {
+ return true;
+ }
+
+ return needsFrameCapture(item, itemEdit, rules.value);
};
const changedIndexes = computed(() =>
editingItems.value.map((_, index) => index).filter(isChanged),
);
const onImageLoad = (size: ImageSize): void => {
- naturals.value[activeIndex.value] = size;
+ if (!cropsCover.value) {
+ naturals.value[activeIndex.value] = size;
+
+ return;
+ }
+
+ if (filled(edit.value?.coverImage)) {
+ edit.value.coverImage.natural = size;
+ }
};
const onImageError = (): void => {
@@ -222,7 +429,7 @@ const onStagePress = (point: { x: number; y: number }): void => {
pendingPoint.value = placed;
};
-const resetCrop = (): void => resetGeometry(basePreset.value);
+const resetCrop = (): void => resetGeometry(stageBasePreset.value);
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -244,9 +451,82 @@ const loadImage = (src: string): Promise<HTMLImageElement> =>
image.src = src;
});
+/** The cover to save: the picked frame captured as an image when the network takes one, else the edit's own. */
+const coverImageFor = async (
+ media: MediaItem,
+ itemEdit: MediaEdit,
+): Promise<CoverImage | null> => {
+ if (needsFrameCapture(media, itemEdit, rules.value)) {
+ return captureFrame(media, itemEdit.coverOffsetMs ?? 0);
+ }
+
+ const cover = itemEdit.coverImage;
+
+ if (!filled(cover)) {
+ return null;
+ }
+
+ if (!filled(cover.file) && !hasCoverCropChanges(cover.crop)) {
+ return cover;
+ }
+
+ return renderCover(cover);
+};
+
+const captureFrame = async (
+ media: MediaItem,
+ milliseconds: number,
+): Promise<CoverImage> => {
+ try {
+ const file = await captureVideoFrame(media.url, milliseconds);
+
+ return newCoverImage(URL.createObjectURL(file), null, file);
+ } catch (error) {
+ captureFailed.value = true;
+
+ throw error;
+ }
+};
+
+/** The cover image as framed on the stage, rendered like any edited image. */
+const renderCover = async (cover: CoverImage): Promise<CoverImage> => {
+ const source = coverPixelItem(cover);
+ const image = await loadImage(pixelSource(source));
+ const rendered = await renderMediaEdit(image, source, cover.crop);
+
+ return newCoverImage(URL.createObjectURL(rendered.file), null, rendered.file);
+};
+
+/** The cover as a media item to read its pixels from: the picked file, or the stored image. */
+const coverPixelItem = (cover: CoverImage): MediaItem => {
+ if (filled(cover.file)) {
+ return {
+ id: cover.url,
+ url: cover.url,
+ original_filename: cover.file.name,
+ mime_type: cover.file.type,
+ };
+ }
+
+ if (filled(cover.item)) {
+ return cover.item;
+ }
+
+ return { id: cover.url, url: cover.url };
+};
+
+const failureKey = computed(() => {
+ if (captureFailed.value) {
+ return 'posts.composer.media_editor.thumbnail_capture_failed';
+ }
+
+ return 'posts.composer.media_editor.apply_failed';
+});
+
const apply = async (): Promise<void> => {
applying.value = true;
failed.value = false;
+ captureFailed.value = false;
try {
const changes = await Promise.all(
changedIndexes.value.map(
@@ -276,6 +556,8 @@ const apply = async (): Promise<void> => {
altText: itemEdit.altText.trim() || null,
userTags: itemEdit.userTags,
coverOffsetMs: itemEdit.coverOffsetMs,
+ coverImage: await coverImageFor(media, itemEdit),
+ coverSource: itemEdit.coverSource,
};
},
),
@@ -312,6 +594,7 @@ watch(
tagging.value = false;
movingIndex.value = null;
failed.value = false;
+ captureFailed.value = false;
},
);
@@ -364,86 +647,94 @@ watch(tagging, (isTagging) => {
<div
class="relative flex min-h-[45vh] flex-1 items-center justify-center overflow-hidden rounded-xl bg-muted select-none dark:bg-accent lg:min-h-0"
>
- <video
- v-if="activeItem && activeIsVideo"
- ref="stageVideoEl"
- :key="activeItem.url"
- :src="activeItem.url"
- muted
- playsinline
- preload="metadata"
- data-testid="media-editor-stage-video"
- class="absolute inset-6 size-[calc(100%-3rem)] object-contain"
- @loadedmetadata="onStageVideoMetadata"
- />
+ <template v-if="showsStageVideo">
+ <video
+ v-if="activeItem"
+ ref="stageVideoEl"
+ :key="activeItem.url"
+ :src="activeItem.url"
+ muted
+ playsinline
+ preload="metadata"
+ data-testid="media-editor-stage-video"
+ class="absolute inset-6 size-[calc(100%-3rem)] object-contain"
+ @loadedmetadata="onStageVideoMetadata"
+ />
+ </template>
<p
v-else-if="imageErrors[activeIndex]"
class="p-4 text-center text-sm text-muted-foreground"
>
{{ $t('common.photo_upload.crop_error') }}
</p>
- <ImageCropStage
- v-else-if="activeItem && edit"
- v-model:edit="edit"
- :src="activeItem.url"
- :natural="natural"
- :crop-mode="cropMode"
- :resize-any-ratio="isPhoto"
- test-id-prefix="media-editor"
- :box-class="
- tab === 'tags' &&
- (tagging || movingIndex !== null)
- ? 'cursor-crosshair'
- : ''
- "
- @load="onImageLoad"
- @error="onImageError"
- @press="onStagePress"
- >
- <template v-if="tab === 'tags'">
- <span
- v-for="(tag, tagIndex) in edit.userTags"
- :key="`${tag.username}-${tagIndex}`"
- class="pointer-events-none absolute flex size-6 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full text-xs font-medium tabular-nums shadow ring-2 ring-white transition-transform"
- :class="
- movingIndex === tagIndex
- ? 'scale-125 bg-primary-strong text-primary-strong-foreground ring-primary-strong/30'
- : 'bg-foreground text-background'
- "
- :data-testid="`media-editor-tag-marker-${tagIndex}`"
- :style="{
- left: `${tag.x * 100}%`,
- top: `${tag.y * 100}%`,
- }"
- >{{ tagIndex + 1 }}</span
- >
- <span
- v-if="movingIndex !== null"
- class="pointer-events-none absolute bottom-3 left-1/2 flex -translate-x-1/2 items-center gap-1.5 rounded-full bg-foreground/85 px-3 py-1 text-xs whitespace-nowrap text-background shadow"
- data-testid="media-editor-tag-move-pill"
- >
- <IconCrosshair class="size-3.5" />
- {{
- $t(
- 'posts.composer.media_editor.tags_move_pill',
- )
- }}
- </span>
- <span
- v-if="pendingPoint"
- data-testid="media-editor-tag-point"
- class="pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-foreground/40 shadow"
- :style="{
- left: `${pendingPoint.x * 100}%`,
- top: `${pendingPoint.y * 100}%`,
- }"
- />
- </template>
- </ImageCropStage>
+ <template v-else-if="stageSrc">
+ <ImageCropStage
+ v-if="stageEdit"
+ v-model:edit="stageEdit"
+ :src="stageSrc"
+ :natural="stageNatural"
+ :crop-mode="cropMode"
+ :resize-any-ratio="resizesAnyRatio"
+ test-id-prefix="media-editor"
+ :box-class="stageBoxClass"
+ @load="onImageLoad"
+ @error="onImageError"
+ @press="onStagePress"
+ >
+ <template v-if="tab === 'tags'">
+ <span
+ v-for="(tag, tagIndex) in edit.userTags"
+ :key="`${tag.username}-${tagIndex}`"
+ class="pointer-events-none absolute flex size-6 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full text-xs font-medium tabular-nums shadow ring-2 ring-white transition-transform"
+ :class="
+ movingIndex === tagIndex
+ ? 'scale-125 bg-primary-strong text-primary-strong-foreground ring-primary-strong/30'
+ : 'bg-foreground text-background'
+ "
+ :data-testid="`media-editor-tag-marker-${tagIndex}`"
+ :style="{
+ left: `${tag.x * 100}%`,
+ top: `${tag.y * 100}%`,
+ }"
+ >{{ tagIndex + 1 }}</span
+ >
+ <span
+ v-if="movingIndex !== null"
+ class="pointer-events-none absolute bottom-3 left-1/2 flex -translate-x-1/2 items-center gap-1.5 rounded-full bg-foreground/85 px-3 py-1 text-xs whitespace-nowrap text-background shadow"
+ data-testid="media-editor-tag-move-pill"
+ >
+ <IconCrosshair class="size-3.5" />
+ {{
+ $t(
+ 'posts.composer.media_editor.tags_move_pill',
+ )
+ }}
+ </span>
+ <span
+ v-if="pendingPoint"
+ data-testid="media-editor-tag-point"
+ class="pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-foreground/40 shadow"
+ :style="{
+ left: `${pendingPoint.x * 100}%`,
+ top: `${pendingPoint.y * 100}%`,
+ }"
+ />
+ </template>
+ </ImageCropStage>
+ </template>
</div>
+ <template v-if="showsTimeline">
+ <MediaEditorVideoTimeline
+ v-if="timelineVideo"
+ :key="timelineVideo.url"
+ v-model:edit="edit"
+ :src="timelineVideo.url"
+ :duration="activeVideoDuration"
+ />
+ </template>
<div
- v-if="!isPhoto"
+ v-if="showsItemPicker"
class="flex justify-center gap-3 overflow-x-auto px-1 pt-3 pb-1.5 [scrollbar-width:thin]"
data-testid="media-editor-thumbnails"
>
@@ -548,7 +839,7 @@ watch(tagging, (isTagging) => {
<MediaEditorCropPanel
v-if="section === 'crop'"
v-model:edit="edit"
- :presets="presets"
+ :presets="stagePresets"
:center-disabled="centerDisabled"
:reset-disabled="resetDisabled"
@center="centerSelection"
@@ -560,11 +851,22 @@ watch(tagging, (isTagging) => {
:src="activeItem.url"
/>
</template>
- <MediaEditorThumbnailPanel
- v-else-if="tab === 'thumbnail' && edit"
- v-model:edit="edit"
- :duration="activeVideoDuration"
- />
+ <template v-else-if="tab === 'thumbnail' && edit">
+ <MediaEditorThumbnailPanel
+ :key="activeIndex"
+ v-model:edit="edit"
+ :supports-custom-cover="supportsCustomCover"
+ />
+ <MediaEditorCropPanel
+ v-if="coverCropEdit"
+ v-model:edit="coverCropEdit"
+ :presets="stagePresets"
+ :center-disabled="centerDisabled"
+ :reset-disabled="resetDisabled"
+ @center="centerSelection"
+ @reset="resetCrop"
+ />
+ </template>
<MediaEditorAltTextPanel
v-else-if="tab === 'alt' && edit"
v-model:edit="edit"
@@ -586,7 +888,7 @@ watch(tagging, (isTagging) => {
class="mr-auto text-sm text-destructive"
data-testid="media-editor-error"
>
- {{ $t('posts.composer.media_editor.apply_failed') }}
+ {{ $t(failureKey) }}
</p>
<Button
type="button"
diff --git a/resources/js/components/posts/composer/MediaEditorThumbnailPanel.vue b/resources/js/components/posts/composer/MediaEditorThumbnailPanel.vue
index 82bcd7a94..836138b8f 100644
--- a/resources/js/components/posts/composer/MediaEditorThumbnailPanel.vue
+++ b/resources/js/components/posts/composer/MediaEditorThumbnailPanel.vue
@@ -1,24 +1,93 @@
<script setup lang="ts">
-import { computed } from 'vue';
+import { IconUpload } from '@tabler/icons-vue';
+import { computed, ref } from 'vue';
-import { formatCoverOffset, type MediaEdit } from '@/lib/mediaEditor';
-import { rangeFill } from '@/lib/rangeFill';
+import { Button } from '@/components/ui/button';
+import { filled } from '@/lib/helpers';
+import { type MediaEdit, newCoverImage } from '@/lib/mediaEditor';
+import { fromMimeType, MediaType, stillImageAcceptAttribute } from '@/lib/mediaType';
+import type { CoverSource } from '@/types/media';
+
+const COVER_SOURCES: CoverSource[] = ['frame', 'image'];
const props = defineProps<{
- duration: number | null;
+ supportsCustomCover: boolean;
}>();
const edit = defineModel<MediaEdit>('edit', { required: true });
-const maxSeconds = computed(() =>
- Math.max(0, Math.floor((props.duration ?? 0) * 10) / 10),
-);
-const seconds = computed({
- get: () => (edit.value.coverOffsetMs ?? 0) / 1000,
- set: (value: number) => {
- edit.value.coverOffsetMs = Math.round(value * 1000);
- },
+const fileInput = ref<HTMLInputElement | null>(null);
+
+const showsImage = computed(() => {
+ if (!props.supportsCustomCover) {
+ return false;
+ }
+
+ return edit.value.coverSource === 'image';
});
+const hasCoverImage = computed(() => filled(edit.value.coverImage));
+const accept = stillImageAcceptAttribute();
+
+const sourceClass = (option: CoverSource): string => {
+ if (edit.value.coverSource === option) {
+ return 'bg-primary-selected font-medium text-primary-text';
+ }
+
+ return 'text-muted-foreground hover:text-foreground';
+};
+
+/**
+ * The frame time stays when an image is picked: a network that only takes a
+ * frame (TikTok, a Pinterest pin) keeps publishing it. The frame's screenshot
+ * goes, so the stage waits for an image of the user's own. Going back to a frame
+ * drops the image, so the picked frame (the start, when none was picked, as
+ * the strip shows) becomes the cover again.
+ */
+const selectSource = (option: CoverSource): void => {
+ const wasFrame = edit.value.coverSource === 'frame';
+ edit.value.coverSource = option;
+
+ if (option === 'image') {
+ if (wasFrame) {
+ edit.value.coverImage = null;
+ }
+
+ return;
+ }
+
+ edit.value.coverImage = null;
+
+ if (!filled(edit.value.coverOffsetMs)) {
+ edit.value.coverOffsetMs = 0;
+ }
+};
+
+const isSelected = (option: CoverSource): boolean =>
+ edit.value.coverSource === option;
+
+const pickImage = (): void => {
+ fileInput.value?.click();
+};
+
+const onImagePicked = (event: Event): void => {
+ const input = event.target as HTMLInputElement;
+ const file = input.files?.[0];
+ input.value = '';
+
+ if (!filled(file)) {
+ return;
+ }
+
+ if (fromMimeType(file.type) !== MediaType.Image) {
+ return;
+ }
+
+ if (filled(edit.value.coverImage?.file)) {
+ URL.revokeObjectURL(edit.value.coverImage.url);
+ }
+
+ edit.value.coverImage = newCoverImage(URL.createObjectURL(file), null, file);
+};
</script>
<template>
@@ -27,36 +96,56 @@ const seconds = computed({
<h3 class="text-sm font-medium">
{{ $t('posts.composer.media_editor.thumbnail_heading') }}
</h3>
- <p class="text-xs text-muted-foreground">
+ <p v-if="showsImage" class="text-xs text-muted-foreground">
+ {{ $t('posts.composer.media_editor.thumbnail_image_hint') }}
+ </p>
+ <p v-else class="text-xs text-muted-foreground">
{{ $t('posts.composer.media_editor.thumbnail_hint') }}
</p>
</div>
- <label class="block space-y-1 text-sm">
- <span class="flex justify-between">
- <span>{{
- $t('posts.composer.media_editor.thumbnail_tab')
- }}</span>
- <span
- class="text-muted-foreground tabular-nums"
- data-testid="media-editor-cover-value"
- >{{ formatCoverOffset(edit.coverOffsetMs ?? 0) }}</span
- >
- </span>
+ <div
+ v-if="supportsCustomCover"
+ role="group"
+ data-testid="media-editor-cover-source"
+ class="grid grid-cols-2 rounded-lg border border-border p-1"
+ >
+ <button
+ v-for="option in COVER_SOURCES"
+ :key="option"
+ type="button"
+ :aria-pressed="isSelected(option)"
+ :data-testid="`media-editor-cover-source-${option}`"
+ class="rounded-md px-2 py-1.5 text-sm whitespace-nowrap transition-colors"
+ :class="sourceClass(option)"
+ @click="selectSource(option)"
+ >
+ {{ $t(`posts.composer.media_editor.thumbnail_source_${option}`) }}
+ </button>
+ </div>
+ <template v-if="showsImage">
<input
- v-model.number="seconds"
- data-testid="media-editor-cover"
- :style="rangeFill(seconds, 0, maxSeconds)"
- type="range"
- min="0"
- :max="maxSeconds"
- step="0.1"
- :aria-valuetext="
- $t('posts.composer.media_editor.thumbnail_value', {
- seconds: seconds.toFixed(1),
- })
- "
- class="editor-range w-full"
+ ref="fileInput"
+ type="file"
+ class="hidden"
+ :accept="accept"
+ data-testid="media-editor-cover-image-input"
+ @change="onImagePicked"
/>
- </label>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ data-testid="media-editor-cover-image-pick"
+ @click="pickImage"
+ >
+ <IconUpload class="size-4" />
+ <span v-if="hasCoverImage">{{
+ $t('posts.composer.media_editor.thumbnail_image_replace')
+ }}</span>
+ <span v-else>{{
+ $t('posts.composer.media_editor.thumbnail_image_upload')
+ }}</span>
+ </Button>
+ </template>
</div>
</template>
diff --git a/resources/js/components/posts/composer/MediaEditorVideoTimeline.vue b/resources/js/components/posts/composer/MediaEditorVideoTimeline.vue
new file mode 100644
index 000000000..993729e32
--- /dev/null
+++ b/resources/js/components/posts/composer/MediaEditorVideoTimeline.vue
@@ -0,0 +1,180 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
+
+import { clamp, filled } from '@/lib/helpers';
+import { formatCoverOffset, type MediaEdit } from '@/lib/mediaEditor';
+import { releaseVideo } from '@/lib/videoFrame';
+
+/** How many frames the strip shows across the video. */
+const FRAME_COUNT = 8;
+
+/**
+ * The height each frame is drawn at, in canvas pixels: twice the strip's
+ * 80px, sharp on a retina screen, never the video's full size.
+ */
+const FRAME_HEIGHT = 160;
+
+const props = defineProps<{
+ src: string;
+ duration: number | null;
+}>();
+
+const edit = defineModel<MediaEdit>('edit', { required: true });
+
+const frames = ref<HTMLCanvasElement[]>([]);
+const paintedFrames = ref<number[]>([]);
+const selectedVideo = ref<HTMLVideoElement | null>(null);
+let stripVideo: HTMLVideoElement | null = null;
+
+const maxSeconds = computed(() =>
+ Math.max(0, Math.floor((props.duration ?? 0) * 10) / 10),
+);
+const seconds = computed({
+ get: () => (edit.value.coverOffsetMs ?? 0) / 1000,
+ set: (value: number) => {
+ edit.value.coverOffsetMs = Math.round(value * 1000);
+ },
+});
+
+const pickedTime = computed(() => formatCoverOffset(edit.value.coverOffsetMs ?? 0));
+
+/** Where the picked frame sits on the strip, from 0 (start) to 1 (end). */
+const position = computed(() => {
+ if (maxSeconds.value <= 0) {
+ return 0;
+ }
+
+ return clamp(seconds.value / maxSeconds.value, 0, 1);
+});
+
+/** The selector is one frame wide and slides from the first frame to the last. */
+const selectorStyle = computed(() => ({
+ width: `${100 / FRAME_COUNT}%`,
+ left: `calc(${position.value} * (100% - 100% / ${FRAME_COUNT}))`,
+}));
+
+const showSelectedFrame = (): void => {
+ const video = selectedVideo.value;
+
+ if (filled(video) && video.readyState > 0) {
+ video.currentTime = seconds.value;
+ }
+};
+
+const seekTo = (video: HTMLVideoElement, time: number): Promise<void> =>
+ new Promise((resolve) => {
+ video.addEventListener('seeked', () => resolve(), { once: true });
+ video.currentTime = time;
+ });
+
+/**
+ * Paints the strip from one hidden copy of the video, a frame at a time.
+ * Drawing a frame from another host only shows it; nothing is exported here,
+ * so the video needs no CORS.
+ */
+const paintFrames = async (): Promise<void> => {
+ const video = stripVideo;
+
+ if (!filled(video)) {
+ return;
+ }
+
+ for (const [index, canvas] of frames.value.entries()) {
+ await seekTo(video, ((index + 0.5) / FRAME_COUNT) * video.duration);
+
+ if (stripVideo !== video) {
+ return;
+ }
+
+ const scale = Math.min(1, FRAME_HEIGHT / video.videoHeight);
+ canvas.width = Math.max(1, Math.round(video.videoWidth * scale));
+ canvas.height = Math.max(1, Math.round(video.videoHeight * scale));
+ canvas.getContext('2d')?.drawImage(video, 0, 0, canvas.width, canvas.height);
+ paintedFrames.value.push(index);
+ }
+};
+
+/**
+ * A frame still loading pulses: on a large video (4K, a high bitrate) each
+ * one downloads a piece of the file, so the strip fills in over seconds.
+ */
+const frameClass = (index: number): string => {
+ if (paintedFrames.value.includes(index - 1)) {
+ return 'opacity-60';
+ }
+
+ return 'animate-pulse bg-muted-foreground/20';
+};
+
+onMounted(() => {
+ const video = document.createElement('video');
+ video.muted = true;
+ video.playsInline = true;
+ video.preload = 'metadata';
+ video.addEventListener('loadedmetadata', paintFrames, { once: true });
+ video.src = props.src;
+ stripVideo = video;
+});
+
+onBeforeUnmount(() => {
+ if (filled(stripVideo)) {
+ releaseVideo(stripVideo);
+ }
+
+ stripVideo = null;
+});
+
+watch(seconds, showSelectedFrame);
+</script>
+
+<template>
+ <div class="space-y-2" data-testid="media-editor-cover-timeline">
+ <div class="relative h-20 select-none">
+ <div class="flex h-full overflow-hidden rounded-lg bg-muted">
+ <canvas
+ v-for="index in FRAME_COUNT"
+ :key="index"
+ ref="frames"
+ class="h-full min-w-0 flex-1 object-cover"
+ :class="frameClass(index)"
+ />
+ </div>
+ <div
+ class="pointer-events-none absolute -inset-y-1.5 overflow-hidden rounded-lg ring-3 ring-primary-strong"
+ :style="selectorStyle"
+ data-testid="media-editor-cover-selector"
+ >
+ <video
+ ref="selectedVideo"
+ :src="src"
+ muted
+ playsinline
+ preload="metadata"
+ class="size-full bg-muted object-cover"
+ @loadedmetadata="showSelectedFrame"
+ />
+ </div>
+ <input
+ v-model.number="seconds"
+ data-testid="media-editor-cover"
+ type="range"
+ min="0"
+ :max="maxSeconds"
+ step="0.1"
+ :aria-label="$t('posts.composer.media_editor.thumbnail_tab')"
+ :aria-valuetext="
+ $t('posts.composer.media_editor.thumbnail_value', {
+ seconds: seconds.toFixed(1),
+ })
+ "
+ class="absolute inset-0 size-full cursor-grab opacity-0 active:cursor-grabbing"
+ />
+ </div>
+ <p
+ class="text-center text-xs text-muted-foreground tabular-nums"
+ data-testid="media-editor-cover-value"
+ >
+ {{ pickedTime }}
+ </p>
+ </div>
+</template>
diff --git a/resources/js/components/posts/previews/PlatformPreview.vue b/resources/js/components/posts/previews/PlatformPreview.vue
index 9199bbc8a..16b4769f7 100644
--- a/resources/js/components/posts/previews/PlatformPreview.vue
+++ b/resources/js/components/posts/previews/PlatformPreview.vue
@@ -18,6 +18,7 @@ import XPreview from '@/components/posts/previews/XPreview.vue';
import YouTubePreview from '@/components/posts/previews/YouTubePreview.vue';
import { getPlatformLabel } from '@/composables/usePlatformLogo';
import { useXLinkDefuser } from '@/composables/useXLinkDefuser';
+import { mediaRuleFor } from '@/lib/contentTypeMediaRules';
import { filled } from '@/lib/helpers';
import {
repliesAreComments,
@@ -25,6 +26,7 @@ import {
threadRepliesOf,
threadReplyContentType,
} from '@/lib/threadReplies';
+import { withCoversFor } from '@/lib/videoFrame';
import type { MediaItem } from '@/types/media';
import { THREAD_PLATFORMS } from '@/types/network-options';
import type { PublishConfig } from '@/types/platform';
@@ -55,6 +57,17 @@ const { contentFor } = useXLinkDefuser();
*/
const previewContent = computed((): string => contentFor(props.content, props.platform));
+/** Whether this post's network takes a cover image, so its preview shows the one uploaded. */
+const takesCoverImage = computed((): boolean => {
+ if (!filled(props.contentType)) {
+ return false;
+ }
+
+ return mediaRuleFor(props.contentType)?.supports_custom_video_cover ?? false;
+});
+
+const previewMedia = computed((): MediaItem[] => withCoversFor(props.media, takesCoverImage.value));
+
const shownReplies = computed((): { reply: ThreadReply; index: number }[] =>
THREAD_PLATFORMS.includes(props.platform) && !repliesAreComments(props.platform)
? threadRepliesOf(props.meta)
@@ -159,7 +172,7 @@ const previewComponent = computed(() => {
:is="previewComponent"
:social-account="resolvedSocialAccount"
:content="previewContent"
- :media="media"
+ :media="previewMedia"
:content-type="contentType"
:meta="meta"
:posted-at="postedAt"
diff --git a/resources/js/components/posts/previews/PostMediaPreview.vue b/resources/js/components/posts/previews/PostMediaPreview.vue
index dcf088499..e9bed1182 100644
--- a/resources/js/components/posts/previews/PostMediaPreview.vue
+++ b/resources/js/components/posts/previews/PostMediaPreview.vue
@@ -58,7 +58,7 @@ const goToSlide = (index: number) => {
<template v-for="(item, index) in media" :key="item.id">
<VideoPreview
v-if="isVideoMedia(item) && index === currentIndex"
- :src="item.url"
+ :media="item"
:video-class="mediaClass"
/>
<img
diff --git a/resources/js/components/posts/previews/PreviewMedia.vue b/resources/js/components/posts/previews/PreviewMedia.vue
index 09f179459..93076c6f8 100644
--- a/resources/js/components/posts/previews/PreviewMedia.vue
+++ b/resources/js/components/posts/previews/PreviewMedia.vue
@@ -114,7 +114,7 @@ const frameClass = computed((): string =>
>
<VideoPreview
v-if="isVideo(tile.item)"
- :src="tile.item.url"
+ :media="tile.item"
video-class="size-full object-cover bg-black"
/>
<img
@@ -140,7 +140,7 @@ const frameClass = computed((): string =>
>
<VideoPreview
v-if="isVideo(item)"
- :src="item.url"
+ :media="item"
video-class="size-full object-cover bg-black"
/>
<img
@@ -168,7 +168,7 @@ const frameClass = computed((): string =>
>
<VideoPreview
v-if="isVideo(item)"
- :src="item.url"
+ :media="item"
video-class="size-full object-cover bg-black"
/>
<img
diff --git a/resources/js/components/posts/previews/VerticalMediaCanvas.vue b/resources/js/components/posts/previews/VerticalMediaCanvas.vue
index 390228b7c..8862ad0bd 100644
--- a/resources/js/components/posts/previews/VerticalMediaCanvas.vue
+++ b/resources/js/components/posts/previews/VerticalMediaCanvas.vue
@@ -21,7 +21,7 @@ const item = computed<MediaItem | null>(() => props.media[0] ?? null);
<template>
<div class="absolute inset-0 overflow-hidden bg-black">
<template v-if="item">
- <VideoPreview v-if="isVideoMedia(item)" :src="item.url" video-class="h-full w-full object-cover" />
+ <VideoPreview v-if="isVideoMedia(item)" :media="item" video-class="h-full w-full object-cover" />
<template v-else>
<template v-if="backdrop === 'blur'">
<div class="absolute inset-x-0 top-0 h-1/2 overflow-hidden">
diff --git a/resources/js/components/posts/previews/VideoPreview.vue b/resources/js/components/posts/previews/VideoPreview.vue
index f689c82c6..7dbd8a9e3 100644
--- a/resources/js/components/posts/previews/VideoPreview.vue
+++ b/resources/js/components/posts/previews/VideoPreview.vue
@@ -1,12 +1,15 @@
<script setup lang="ts">
import { IconPlayerPlayFilled } from '@tabler/icons-vue';
-import { ref } from 'vue';
+import { computed, ref } from 'vue';
+import VideoStill from '@/components/media/VideoStill.vue';
import { useSoundtrackVideo } from '@/composables/composer/useReelSoundtrack';
+import { hasPickedCover } from '@/lib/videoFrame';
+import type { MediaItem } from '@/types/media';
const props = withDefaults(
defineProps<{
- src: string;
+ media: Pick<MediaItem, 'url' | 'meta'>;
videoClass?: string;
}>(),
{
@@ -16,11 +19,24 @@ const props = withDefaults(
const videoRef = ref<HTMLVideoElement | null>(null);
const isPlaying = ref(false);
+const hasPlayed = ref(false);
+
+/** The picked cover stands in for the video until it is first played. */
+const showsCover = computed(() => {
+ if (hasPlayed.value) {
+ return false;
+ }
+
+ return hasPickedCover(props.media);
+});
const soundtrack = useSoundtrackVideo(videoRef);
+const coverClass = computed(() => `absolute inset-0 ${props.videoClass}`);
+
const markPlaying = (): void => {
isPlaying.value = true;
+ hasPlayed.value = true;
soundtrack.onVideoPlay();
};
@@ -44,7 +60,7 @@ const toggle = () => {
<div class="relative h-full w-full" @click="toggle">
<video
ref="videoRef"
- :src="props.src"
+ :src="props.media.url"
:class="props.videoClass"
playsinline
preload="metadata"
@@ -52,9 +68,16 @@ const toggle = () => {
@pause="markPaused"
@ended="markPaused"
/>
+ <VideoStill
+ v-if="showsCover"
+ :item="props.media"
+ :class="coverClass"
+ data-testid="video-preview-cover"
+ />
<button
v-show="!isPlaying"
type="button"
+ data-testid="video-preview-play"
class="absolute inset-0 flex cursor-pointer items-center justify-center"
:aria-label="$t('common.play')"
>
diff --git a/resources/js/components/publish/CalendarPostChip.vue b/resources/js/components/publish/CalendarPostChip.vue
index fd638055f..8aaf61fab 100644
--- a/resources/js/components/publish/CalendarPostChip.vue
+++ b/resources/js/components/publish/CalendarPostChip.vue
@@ -13,6 +13,7 @@ import {
} from '@tabler/icons-vue';
import { computed, type Component } from 'vue';
+import VideoStill from '@/components/media/VideoStill.vue';
import PlatformBrandIcon from '@/components/PlatformBrandIcon.vue';
import PostDetailsDialog from '@/components/publish/PostDetailsDialog.vue';
import PostRecurrenceDialog from '@/components/publish/PostRecurrenceDialog.vue';
@@ -29,7 +30,6 @@ import { isImage } from '@/lib/mediaType';
import { postChannelLabel, postThumbnail } from '@/lib/postCard';
import { isDeletedOnNetwork } from '@/lib/postNetwork';
import { htmlToPlainText } from '@/lib/utils';
-import { videoFrameUrl } from '@/lib/videoFrame';
import { PostStatus, ScheduleMode } from '@/types/post';
import type { CalendarPost } from '@/types/publish';
@@ -205,12 +205,9 @@ const chipClass = computed(() => [
class="size-full object-cover"
/>
<template v-else>
- <video
- :src="videoFrameUrl(thumbnail)"
+ <VideoStill
+ :item="thumbnail"
class="size-full object-cover"
- muted
- playsinline
- preload="metadata"
/>
<IconPlayerPlayFilled
aria-hidden="true"
diff --git a/resources/js/components/publish/PostCoverWarningPopover.vue b/resources/js/components/publish/PostCoverWarningPopover.vue
new file mode 100644
index 000000000..bdf8f335d
--- /dev/null
+++ b/resources/js/components/publish/PostCoverWarningPopover.vue
@@ -0,0 +1,72 @@
+<script setup lang="ts">
+import { IconAlertTriangle } from '@tabler/icons-vue';
+import { computed } from 'vue';
+
+import TransSlots from '@/components/TransSlots.vue';
+import { Badge } from '@/components/ui/badge';
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '@/components/ui/popover';
+import type { YouTubeThumbnailWarning } from '@/types/publish';
+
+/** Where YouTube verifies a channel, which unlocks custom thumbnails. */
+const YOUTUBE_VERIFY_URL = 'https://www.youtube.com/verify';
+const YOUTUBE_VERIFY_LABEL = 'youtube.com/verify';
+
+const props = defineProps<{
+ warning: YouTubeThumbnailWarning;
+ testKey: string;
+}>();
+
+/** Why YouTube kept its own thumbnail, and where the user can set the cover instead. */
+const reasonKey = computed(
+ () => `posts.publish.youtube_thumbnail_warning.${props.warning}`,
+);
+</script>
+
+<template>
+ <Popover>
+ <PopoverTrigger as-child>
+ <button
+ type="button"
+ class="rounded-full focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
+ :aria-label="$t('posts.publish.youtube_thumbnail_warning.title')"
+ :data-testid="`post-cover-warning-${testKey}`"
+ >
+ <Badge variant="warning" class="cursor-pointer" data-single-line>
+ <IconAlertTriangle aria-hidden="true" />
+ {{ $t('posts.publish.youtube_thumbnail_warning.badge') }}
+ </Badge>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ :collision-padding="16"
+ class="flex w-80 flex-col gap-2"
+ :data-testid="`post-cover-warning-popover-${testKey}`"
+ >
+ <p class="text-sm font-emphasis text-foreground">
+ {{ $t('posts.publish.youtube_thumbnail_warning.title') }}
+ </p>
+ <p
+ class="text-sm text-foreground"
+ :data-testid="`post-cover-warning-reason-${testKey}`"
+ >
+ <TransSlots :message="$t(reasonKey)">
+ <template #url>
+ <a
+ :href="YOUTUBE_VERIFY_URL"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="font-medium underline underline-offset-2"
+ :data-testid="`post-cover-warning-verify-${testKey}`"
+ v-text="YOUTUBE_VERIFY_LABEL"
+ />
+ </template>
+ </TransSlots>
+ </p>
+ </PopoverContent>
+ </Popover>
+</template>
diff --git a/resources/js/components/publish/PostDetailsMedia.vue b/resources/js/components/publish/PostDetailsMedia.vue
index 57b01932e..3343e53ec 100644
--- a/resources/js/components/publish/PostDetailsMedia.vue
+++ b/resources/js/components/publish/PostDetailsMedia.vue
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { IconFileTypePdf, IconPlayerPlayFilled } from '@tabler/icons-vue';
+import VideoStill from '@/components/media/VideoStill.vue';
import { isDocument, isVideo } from '@/lib/mediaType';
-import { videoFrameUrl } from '@/lib/videoFrame';
import type { MediaItem } from '@/types/media';
withDefaults(
@@ -52,13 +52,7 @@ const open = (index: number): void => {
@click="isDocument(item) || open(index)"
>
<template v-if="isVideo(item)">
- <video
- :src="videoFrameUrl(item)"
- class="size-full object-cover"
- muted
- playsinline
- preload="metadata"
- />
+ <VideoStill :item="item" class="size-full object-cover" />
<IconPlayerPlayFilled
aria-hidden="true"
class="absolute top-1/2 left-1/2 size-8 -translate-x-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2 text-white"
diff --git a/resources/js/components/publish/PostTimelineCard.vue b/resources/js/components/publish/PostTimelineCard.vue
index b5622838a..7bfc60499 100644
--- a/resources/js/components/publish/PostTimelineCard.vue
+++ b/resources/js/components/publish/PostTimelineCard.vue
@@ -22,6 +22,7 @@ import { type Component, computed, ref, watch } from 'vue';
import ChannelAvatar from '@/components/ChannelAvatar.vue';
import MediaLightbox from '@/components/media/MediaLightbox.vue';
+import VideoStill from '@/components/media/VideoStill.vue';
import PlatformBrandIcon from '@/components/PlatformBrandIcon.vue';
import PostNotesPanel from '@/components/posts/editor/PostNotesPanel.vue';
import PostScheduleModeBadge from '@/components/posts/PostScheduleModeBadge.vue';
@@ -30,6 +31,7 @@ import PostApprovalActions from '@/components/publish/PostApprovalActions.vue';
import PostCardLabels from '@/components/publish/PostCardLabels.vue';
import PostCardMenu from '@/components/publish/PostCardMenu.vue';
import PostCardThread from '@/components/publish/PostCardThread.vue';
+import PostCoverWarningPopover from '@/components/publish/PostCoverWarningPopover.vue';
import PostDeletedOnNetworkPopover from '@/components/publish/PostDeletedOnNetworkPopover.vue';
import PostDetailsDialog from '@/components/publish/PostDetailsDialog.vue';
import PostFailurePopover from '@/components/publish/PostFailurePopover.vue';
@@ -67,7 +69,6 @@ import { isDeletedOnNetwork, postPermalink } from '@/lib/postNetwork';
import { postThreadOf } from '@/lib/postThread';
import { compactPublicationMetrics } from '@/lib/publicationMetrics';
import { recurrenceRuleOf } from '@/lib/recurrence';
-import { videoFrameUrl } from '@/lib/videoFrame';
import { postPollResults } from '@/lib/xPoll';
import { Platform } from '@/types/platform';
import {
@@ -290,6 +291,11 @@ const contentTypeKey = computed(() =>
const deletedOnNetwork = computed(() => isDeletedOnNetwork(props.post));
+/** Why YouTube did not apply this post's cover image, if it did not. */
+const youTubeThumbnailWarning = computed(
+ () => props.post.youtube_thumbnail_warning,
+);
+
const permalink = computed(() => postPermalink(props.post));
const metricsDetail = computed(() => {
@@ -454,6 +460,11 @@ const onMenuSelect = (action: PostCardMenuAction): void => {
:post="post"
:test-key="post.id"
/>
+ <PostCoverWarningPopover
+ v-if="youTubeThumbnailWarning"
+ :warning="youTubeThumbnailWarning"
+ :test-key="post.id"
+ />
<PostFailurePopover
v-if="showStatus && hasFailure"
:post="post"
@@ -638,12 +649,9 @@ const onMenuSelect = (action: PostCardMenuAction): void => {
loading="lazy"
/>
<template v-else>
- <video
- :src="videoFrameUrl(thumbnail)"
+ <VideoStill
+ :item="thumbnail"
class="size-full object-cover"
- muted
- playsinline
- preload="metadata"
:data-testid="`post-thumbnail-video-${post.id}-${index}`"
/>
<IconPlayerPlayFilled
diff --git a/resources/js/components/publish/board/PostBoardCard.vue b/resources/js/components/publish/board/PostBoardCard.vue
index 5a32de079..dc0c2bdf4 100644
--- a/resources/js/components/publish/board/PostBoardCard.vue
+++ b/resources/js/components/publish/board/PostBoardCard.vue
@@ -4,6 +4,7 @@ import { useElementVisibility } from '@vueuse/core';
import { computed, ref } from 'vue';
import ChannelAvatar from '@/components/ChannelAvatar.vue';
+import VideoStill from '@/components/media/VideoStill.vue';
import PostApprovalActions from '@/components/publish/PostApprovalActions.vue';
import PostCardLabels from '@/components/publish/PostCardLabels.vue';
import PostCardMenu from '@/components/publish/PostCardMenu.vue';
@@ -25,7 +26,6 @@ import {
postThumbnail,
} from '@/lib/postCard';
import { htmlToPlainText } from '@/lib/utils';
-import { videoFrameUrl } from '@/lib/videoFrame';
import { PostStatus } from '@/types/post';
import type { PostCard } from '@/types/publish';
@@ -250,13 +250,10 @@ const hasMenu = computed((): boolean => {
class="size-full object-cover"
/>
<template v-else>
- <video
+ <VideoStill
v-if="videoLoaded"
- :src="videoFrameUrl(thumbnail)"
+ :item="thumbnail"
class="size-full object-cover"
- muted
- playsinline
- preload="metadata"
/>
<IconPlayerPlayFilled
aria-hidden="true"
diff --git a/resources/js/composables/useMediaEditSwap.ts b/resources/js/composables/useMediaEditSwap.ts
index 1e1623d78..49fabc737 100644
--- a/resources/js/composables/useMediaEditSwap.ts
+++ b/resources/js/composables/useMediaEditSwap.ts
@@ -1,34 +1,69 @@
import { ref, type Ref } from 'vue';
import type { MediaEditChange } from '@/components/posts/composer/MediaEditorDialog.vue';
+import { filled } from '@/lib/helpers';
import { storeChunked as mediaStoreChunked } from '@/routes/app/media';
-import type { MediaItem } from '@/types/media';
+import type { CoverImage, MediaItem } from '@/types/media';
import { uploadChunked } from '@/utils/chunkedUpload';
const editedMeta = (
meta: MediaItem['meta'],
change: MediaEditChange,
+ cover: MediaItem | null,
): MediaItem['meta'] => {
const next = { ...(meta ?? {}) };
delete next.alt_text;
delete next.user_tags;
delete next.cover_offset_ms;
+ delete next.cover;
+ delete next.cover_source;
- return {
- ...next,
- ...(change.width && change.height
- ? { width: change.width, height: change.height }
- : {}),
- ...(change.altText ? { alt_text: change.altText } : {}),
- ...(change.userTags.length ? { user_tags: change.userTags } : {}),
- ...(change.coverOffsetMs !== null
- ? { cover_offset_ms: change.coverOffsetMs }
- : {}),
- };
+ if (filled(change.width) && filled(change.height)) {
+ next.width = change.width;
+ next.height = change.height;
+ }
+
+ if (filled(change.altText)) {
+ next.alt_text = change.altText;
+ }
+
+ if (filled(change.userTags)) {
+ next.user_tags = change.userTags;
+ }
+
+ if (filled(change.coverOffsetMs)) {
+ next.cover_offset_ms = change.coverOffsetMs;
+ }
+
+ if (filled(cover)) {
+ next.cover = cover;
+ next.cover_source = change.coverSource;
+ }
+
+ return next;
+};
+
+/** The cover image to store: the picked file uploaded, or the item it already was. */
+const coverItem = async (cover: CoverImage | null): Promise<MediaItem | null> => {
+ if (!filled(cover)) {
+ return null;
+ }
+
+ if (!filled(cover.file)) {
+ return cover.item;
+ }
+
+ const uploaded = await uploadChunked({
+ file: cover.file,
+ url: mediaStoreChunked.url(),
+ });
+ URL.revokeObjectURL(cover.url);
+
+ return uploaded;
};
const editedItem = async (change: MediaEditChange): Promise<MediaItem> => {
- const meta = editedMeta(change.media.meta, change);
+ const meta = editedMeta(change.media.meta, change, await coverItem(change.coverImage));
if (!change.file) {
return { ...change.media, meta };
}
diff --git a/resources/js/composables/useMediaRules.ts b/resources/js/composables/useMediaRules.ts
index d98ae5095..dbb546dfe 100644
--- a/resources/js/composables/useMediaRules.ts
+++ b/resources/js/composables/useMediaRules.ts
@@ -25,6 +25,7 @@ const DEFAULT_RULES: MediaRules = {
supportsAltText: false,
supportsUserTags: false,
supportsVideoCover: false,
+ supportsCustomVideoCover: false,
};
export const getMediaRulesForContentType = (contentType: string): MediaRules => {
diff --git a/resources/js/lib/contentTypeMediaRules.ts b/resources/js/lib/contentTypeMediaRules.ts
index f5419ff79..19d0890ac 100644
--- a/resources/js/lib/contentTypeMediaRules.ts
+++ b/resources/js/lib/contentTypeMediaRules.ts
@@ -26,6 +26,7 @@ export type MediaRules = {
supportsAltText: boolean;
supportsUserTags: boolean;
supportsVideoCover: boolean;
+ supportsCustomVideoCover: boolean;
platformLabel?: string;
imageMinWidth?: number;
imageMinHeight?: number;
@@ -59,6 +60,7 @@ export type ContentTypeMediaRule = {
supports_alt_text: boolean;
supports_user_tags: boolean;
supports_video_cover: boolean;
+ supports_custom_video_cover: boolean;
platform_label: string;
image_min_width: number | null;
image_min_height: number | null;
@@ -115,6 +117,7 @@ export const toMediaRules = (rule: ContentTypeMediaRule): MediaRules => ({
supportsAltText: rule.supports_alt_text,
supportsUserTags: rule.supports_user_tags,
supportsVideoCover: rule.supports_video_cover,
+ supportsCustomVideoCover: rule.supports_custom_video_cover,
platformLabel: rule.platform_label,
imageMinWidth: rule.image_min_width ?? undefined,
imageMinHeight: rule.image_min_height ?? undefined,
diff --git a/resources/js/lib/mediaEditor.ts b/resources/js/lib/mediaEditor.ts
index 9f117c859..446d98345 100644
--- a/resources/js/lib/mediaEditor.ts
+++ b/resources/js/lib/mediaEditor.ts
@@ -4,6 +4,7 @@ import {
toMediaRules,
type MediaRules,
} from '@/lib/contentTypeMediaRules';
+import { filled } from '@/lib/helpers';
import {
fullSelection,
resolveOutputFileName,
@@ -11,7 +12,7 @@ import {
type SourceRect,
} from '@/lib/imageCrop';
import { isGif, isImage, isVideo } from '@/lib/mediaType';
-import type { MediaItem, MediaUserTag } from '@/types/media';
+import type { CoverImage, CoverSource, MediaItem, MediaUserTag } from '@/types/media';
export type CropPresetValue =
| 'freeform'
@@ -68,8 +69,13 @@ export type MediaEdit = {
altText: string;
userTags: MediaUserTag[];
coverOffsetMs: number | null;
+ coverImage: CoverImage | null;
+ coverSource: CoverSource;
};
+/** Instagram Reels and YouTube Shorts show a cover at 9:16 and crop anything else to its middle. */
+export const COVER_CROP_PRESET: CropPresetValue = '9:16';
+
export const USER_TAGS_MAX = 20;
const RATIO_TOLERANCE = 0.0001;
@@ -131,15 +137,22 @@ export const presetValuesFor = (
export type EditorTab = 'edit' | 'thumbnail' | 'alt' | 'tags';
+/** A video gets a Thumbnail tab when its network takes a frame or an image as its cover. */
+const hasThumbnail = (rule: MediaRules): boolean => {
+ if (rule.supportsVideoCover) {
+ return true;
+ }
+
+ return rule.supportsCustomVideoCover;
+};
+
/** Tabs the editor offers for an item; an empty list means no pencil. */
export const editorTabsFor = (
item: MediaItem,
rules: MediaRules[],
): EditorTab[] => {
if (isVideo(item)) {
- return rules.some((rule) => rule.supportsVideoCover)
- ? ['thumbnail']
- : [];
+ return rules.some(hasThumbnail) ? ['thumbnail'] : [];
}
if (!isImage(item) || isGif(item)) {
@@ -173,15 +186,142 @@ export const blankMediaEdit = (
altText: '',
userTags: [],
coverOffsetMs: null,
+ coverImage: null,
+ coverSource: 'frame',
+});
+
+const storedCoverImage = (item: MediaItem): CoverImage | null => {
+ const cover = item.meta?.cover;
+
+ if (!filled(cover)) {
+ return null;
+ }
+
+ return newCoverImage(cover.url, cover, null);
+};
+
+/** A cover image as the editor opens it: framed at 9:16 in its middle. */
+export const newCoverImage = (
+ url: string,
+ item: MediaItem | null,
+ file: File | null,
+): CoverImage => ({
+ url,
+ item,
+ file,
+ crop: blankMediaEdit(COVER_CROP_PRESET),
+ natural: null,
});
+/**
+ * Whether the user reframed the cover. Its 9:16 ratio is where it starts, so
+ * only a moved or resized frame, a turn, a flip or an adjustment counts.
+ */
+export const hasCoverCropChanges = (crop: MediaEdit): boolean =>
+ hasPixelChanges({ ...crop, preset: 'original' });
+
+/**
+ * Where the item's cover comes from. A cover sent without its source (the
+ * API or MCP) is an uploaded image.
+ */
+export const storedCoverSource = (item: Pick<MediaItem, 'meta'>): CoverSource => {
+ const source = item.meta?.cover_source;
+
+ if (filled(source)) {
+ return source;
+ }
+
+ if (filled(item.meta?.cover)) {
+ return 'image';
+ }
+
+ return 'frame';
+};
+
export const createMediaEdit = (item: MediaItem): MediaEdit => ({
...blankMediaEdit(),
altText: item.meta?.alt_text ?? '',
userTags: [...(item.meta?.user_tags ?? [])],
coverOffsetMs: item.meta?.cover_offset_ms ?? null,
+ coverImage: storedCoverImage(item),
+ coverSource: storedCoverSource(item),
});
+
+/** The source the edit saves: an image picked but never uploaded leaves the cover as it was saved, a frame. */
+export const savedCoverSource = (edit: MediaEdit): CoverSource => {
+ if (!filled(edit.coverImage)) {
+ return 'frame';
+ }
+
+ return edit.coverSource;
+};
+
+/** Whether the edit picks another cover image than the item has. */
+export const hasCoverImageChange = (edit: MediaEdit, item: MediaItem): boolean => {
+ const stored = item.meta?.cover;
+
+ if (!filled(edit.coverImage)) {
+ return filled(stored);
+ }
+
+ if (filled(edit.coverImage.file)) {
+ return true;
+ }
+
+ if (hasCoverCropChanges(edit.coverImage.crop)) {
+ return true;
+ }
+
+ return edit.coverImage.item?.id !== stored?.id;
+};
+
+/**
+ * A network that takes a cover image but no frame time (YouTube) needs the
+ * picked frame as an image. One that takes the frame time (Instagram, TikTok,
+ * Pinterest) shows that exact frame from the time alone.
+ */
+const takesFrameAsImage = (rule: MediaRules): boolean => {
+ if (!rule.supportsCustomVideoCover) {
+ return false;
+ }
+
+ return !rule.supportsVideoCover;
+};
+
+/**
+ * Whether applying the edit takes a screenshot of the video as its cover: a
+ * network that takes no frame time (YouTube) gets the picked frame as an
+ * image, unless the stored cover is already that frame.
+ */
+export const needsFrameCapture = (
+ item: MediaItem,
+ edit: MediaEdit,
+ rules: MediaRules[],
+): boolean => {
+ if (!isVideo(item)) {
+ return false;
+ }
+
+ if (edit.coverSource !== 'frame') {
+ return false;
+ }
+
+ if (!rules.some(takesFrameAsImage)) {
+ return false;
+ }
+
+ if (!filled(edit.coverOffsetMs)) {
+ return false;
+ }
+
+ if (!filled(edit.coverImage)) {
+ return true;
+ }
+
+ return edit.coverOffsetMs !== item.meta?.cover_offset_ms;
+};
+
export const hasPixelChanges = (edit: MediaEdit): boolean =>
edit.selection !== null ||
!['original', 'freeform'].includes(edit.preset) ||
@@ -192,11 +332,25 @@ export const hasPixelChanges = (edit: MediaEdit): boolean =>
(edit.filter !== 'original' && edit.filterIntensity > 0) ||
ADJUSTMENTS.some((key) => edit.adjustments[key] !== 0);
-export const hasMetaChanges = (edit: MediaEdit, item: MediaItem): boolean =>
- edit.altText.trim() !== (item.meta?.alt_text ?? '').trim() ||
- JSON.stringify(edit.userTags) !==
- JSON.stringify(item.meta?.user_tags ?? []) ||
- (edit.coverOffsetMs ?? 0) !== (item.meta?.cover_offset_ms ?? 0);
+export const hasMetaChanges = (edit: MediaEdit, item: MediaItem): boolean => {
+ if (edit.altText.trim() !== (item.meta?.alt_text ?? '').trim()) {
+ return true;
+ }
+
+ if (JSON.stringify(edit.userTags) !== JSON.stringify(item.meta?.user_tags ?? [])) {
+ return true;
+ }
+
+ if ((edit.coverOffsetMs ?? 0) !== (item.meta?.cover_offset_ms ?? 0)) {
+ return true;
+ }
+
+ if (savedCoverSource(edit) !== storedCoverSource(item)) {
+ return true;
+ }
+
+ return hasCoverImageChange(edit, item);
+};
/** A cover offset in milliseconds as `m:ss.s`. */
export const formatCoverOffset = (milliseconds: number): string => {
diff --git a/resources/js/lib/mediaType.ts b/resources/js/lib/mediaType.ts
index 2c707708f..fcc288c9d 100644
--- a/resources/js/lib/mediaType.ts
+++ b/resources/js/lib/mediaType.ts
@@ -74,6 +74,10 @@ const ownsMime = (type: MediaType, mime: string): boolean =>
export const acceptAttribute = (heic: boolean = false): string =>
[...Object.values(ALLOWED_MIME_TYPES).flat(), ...(heic ? [...HEIC_MIME_TYPES, ...HEIC_EXTENSIONS.map((extension) => `.${extension}`)] : [])].join(',');
+/** The `accept` attribute value for a file input that takes a still image (any allowed image but a GIF), like a video cover. */
+export const stillImageAcceptAttribute = (): string =>
+ ALLOWED_MIME_TYPES[MediaType.Image].filter((mime) => mime !== GIF_MIME).join(',');
+
/** Whether a browser `File` (or name + MIME) is HEIC/HEIF, by MIME or extension. */
export const isHeic = (file: { name?: string | null; type?: string | null } | null | undefined): boolean =>
HEIC_MIME_TYPES.includes(normalizeMime(file?.type)) || hasExtension(pathOf(file?.name), HEIC_EXTENSIONS);
diff --git a/resources/js/lib/videoFrame.ts b/resources/js/lib/videoFrame.ts
index d5f551813..7645c0321 100644
--- a/resources/js/lib/videoFrame.ts
+++ b/resources/js/lib/videoFrame.ts
@@ -1,6 +1,97 @@
+import { objectOmit } from '@vueuse/core';
+
+import { canvasToFile } from '@/lib/canvasFile';
+import { filled } from '@/lib/helpers';
+import type { MediaItem } from '@/types/media';
+
/** The video URL seeked to its chosen cover frame, so a `<video preload="metadata">` paints it as a poster. */
export const videoFrameUrl = (item: {
url: string;
meta?: { cover_offset_ms?: number | null };
}): string =>
`${item.url}#t=${Math.max(0.1, (item.meta?.cover_offset_ms ?? 0) / 1000)}`;
+
+
+/**
+ * The media as a network shows it: a network that takes no cover image
+ * (TikTok, a Pinterest pin, an Instagram feed video) never shows the one
+ * uploaded for another, as the server drops it when the post is saved.
+ */
+export const withCoversFor = (
+ media: MediaItem[],
+ takesCoverImage: boolean,
+): MediaItem[] => {
+ if (takesCoverImage) {
+ return media;
+ }
+
+ return media.map((item) => {
+ if (!filled(item.meta?.cover)) {
+ return item;
+ }
+
+ return { ...item, meta: objectOmit(item.meta, ['cover', 'cover_source']) };
+ });
+};
+
+/** Whether the user picked a cover for the video: an image, or a frame of it. */
+export const hasPickedCover = (item: Pick<MediaItem, 'meta'>): boolean => {
+ if (filled(item.meta?.cover)) {
+ return true;
+ }
+
+ return filled(item.meta?.cover_offset_ms);
+};
+
+/** Stops a detached video from downloading or holding its buffer once it is no longer needed. */
+export const releaseVideo = (video: HTMLVideoElement): void => {
+ video.removeAttribute('src');
+ video.load();
+};
+
+/** The longest side of a captured frame, like the media editor's output cap. */
+const CAPTURE_MAX_SIDE = 3840;
+
+/**
+ * The video's frame at `milliseconds` as a JPEG file, at the video's own
+ * ratio. The video is read with CORS, so its host must allow this origin:
+ * otherwise the canvas cannot be exported and the promise rejects.
+ */
+export const captureVideoFrame = (
+ url: string,
+ milliseconds: number,
+): Promise<File> =>
+ new Promise((resolve, reject) => {
+ const video = document.createElement('video');
+ video.crossOrigin = 'anonymous';
+ video.muted = true;
+ video.playsInline = true;
+ video.preload = 'metadata';
+
+ video.addEventListener('error', () => {
+ releaseVideo(video);
+ reject(new Error('The video could not be loaded.'));
+ });
+ video.addEventListener('loadedmetadata', () => {
+ video.currentTime = Math.min(milliseconds / 1000, video.duration);
+ });
+ video.addEventListener('seeked', () => {
+ const scale = Math.min(1, CAPTURE_MAX_SIDE / Math.max(video.videoWidth, video.videoHeight));
+ const canvas = document.createElement('canvas');
+ canvas.width = Math.max(1, Math.round(video.videoWidth * scale));
+ canvas.height = Math.max(1, Math.round(video.videoHeight * scale));
+ const context = canvas.getContext('2d');
+
+ if (!context) {
+ reject(new Error('Canvas is unavailable'));
+
+ return;
+ }
+
+ context.drawImage(video, 0, 0, canvas.width, canvas.height);
+ releaseVideo(video);
+ canvasToFile(canvas, 'cover.jpg', 'image/jpeg', 0.92).then(resolve, reject);
+ }, { once: true });
+
+ video.src = url;
+ });
diff --git a/resources/js/pages/channels/Grid.vue b/resources/js/pages/channels/Grid.vue
index dfaa6b454..b647db72d 100644
--- a/resources/js/pages/channels/Grid.vue
+++ b/resources/js/pages/channels/Grid.vue
@@ -10,6 +10,7 @@ import { ref } from 'vue';
import AppHeaderActions from '@/components/AppHeaderActions.vue';
import EmptyState from '@/components/EmptyState.vue';
import MediaLightbox from '@/components/media/MediaLightbox.vue';
+import VideoStill from '@/components/media/VideoStill.vue';
import ScheduleViewSwitch from '@/components/posts/ScheduleViewSwitch.vue';
import NewPostButton from '@/components/publish/NewPostButton.vue';
import PublishHeader from '@/components/publish/PublishHeader.vue';
@@ -23,7 +24,6 @@ import { useBelowBreakpoint } from '@/composables/useBreakpoint';
import date from '@/date';
import AppLayout from '@/layouts/AppLayout.vue';
import { isVideo } from '@/lib/mediaType';
-import { videoFrameUrl } from '@/lib/videoFrame';
import {
board as channelBoard,
calendar as channelCalendar,
@@ -127,15 +127,11 @@ const openLightbox = (tile: GridTile): void => {
@click="openLightbox(tile)"
>
<template v-if="tile.items[0]">
- <video
+ <VideoStill
v-if="isVideo(tile.items[0])"
- :src="
- videoFrameUrl(tile.items[0])
- "
+ :item="tile.items[0]"
class="size-full object-cover"
- muted
- playsinline
- preload="metadata"
+ :data-testid="`grid-tile-video-${tile.id}`"
/>
<img
v-else
diff --git a/resources/js/types/media.ts b/resources/js/types/media.ts
index 91d97675a..90f375a8e 100644
--- a/resources/js/types/media.ts
+++ b/resources/js/types/media.ts
@@ -1,3 +1,5 @@
+import type { ImageSize } from '@/composables/useImageCrop';
+import type { MediaEdit } from '@/lib/mediaEditor';
import type { MediaType } from '@/lib/mediaType';
export type MediaSource = 'ai' | 'unsplash' | 'google_drive' | 'google_photos' | 'canva';
@@ -29,7 +31,30 @@ export interface MediaItem {
alt_text?: string;
user_tags?: MediaUserTag[];
cover_offset_ms?: number;
+ cover?: MediaItem;
+ cover_source?: CoverSource;
source?: MediaSource;
source_meta?: Record<string, SourceMetaValue>;
};
}
+
+/**
+ * Where a video's cover comes from (`App\Enums\Media\CoverSource`): a frame
+ * of the video, or an image. A video shared by several networks keeps its
+ * frame time either way, for the networks that only take a frame.
+ */
+export type CoverSource = 'frame' | 'image';
+
+/**
+ * An image picked as a video's cover in the media editor: the stored item,
+ * or a file picked there and uploaded when the edit is applied. `url` is what
+ * the stage shows, `crop` how the user framed it (the stage edits it like an
+ * image) and `natural` its size once the stage has loaded it.
+ */
+export type CoverImage = {
+ url: string;
+ item: MediaItem | null;
+ file: File | null;
+ crop: MediaEdit;
+ natural: ImageSize | null;
+};
diff --git a/resources/js/types/publish.ts b/resources/js/types/publish.ts
index ccd725523..2c67db5a7 100644
--- a/resources/js/types/publish.ts
+++ b/resources/js/types/publish.ts
@@ -61,6 +61,9 @@ export interface UnavailablePostMetrics {
export type PostCardMetrics = PublicationAnalyticsDetail | UnavailablePostMetrics;
+/** Why YouTube did not set the cover image of a live video as its thumbnail (`App\Enums\YouTube\ThumbnailWarning`). */
+export type YouTubeThumbnailWarning = 'forbidden' | 'daily_limit' | 'invalid_image' | 'failed';
+
export interface PostCardFailure {
category?: string | null;
failed_at?: string | null;
@@ -79,6 +82,7 @@ export interface PostCard {
platform_url?: string | null;
error_message?: string | null;
failure?: PostCardFailure | null;
+ youtube_thumbnail_warning?: YouTubeThumbnailWarning | null;
retry_at?: string | null;
origin: PostOriginValue;
created_at: string;
diff --git a/tests/Browser/ChannelGridTest.php b/tests/Browser/ChannelGridTest.php
index ce7b3b26a..2ee1d7eb0 100644
--- a/tests/Browser/ChannelGridTest.php
+++ b/tests/Browser/ChannelGridTest.php
@@ -215,3 +215,21 @@ test('the grid links to the channel board', function () {
$page->assertNoJavaScriptErrors();
});
+
+test('a reel with an uploaded cover shows that cover on the grid, and one with a picked frame shows the frame', function () {
+ $video = ['path' => 'media/reel.mp4', 'url' => 'https://cdn.test/reel.mp4', 'type' => 'video', 'mime_type' => 'video/mp4'];
+ $covered = channelGridBrowserPost($this->instagram, now()->subDays(10)->setTime(10, 0), ContentType::InstagramReel, [
+ [...$video, 'id' => (string) str()->uuid(), 'meta' => ['cover_source' => 'image', 'cover' => channelGridImage()]],
+ ]);
+ $framed = channelGridBrowserPost($this->instagram, now()->subDays(12)->setTime(10, 0), ContentType::InstagramReel, [
+ [...$video, 'id' => (string) str()->uuid(), 'meta' => ['cover_offset_ms' => 2500]],
+ ]);
+
+ $this->actingAs($this->user);
+ $page = visit(route('app.channels.grid', $this->instagram));
+
+ waitForState($page, "@grid-tile-video-{$covered->id}", "element.tagName === 'IMG' && element.src.startsWith('data:image/png')");
+ waitForState($page, "@grid-tile-video-{$framed->id}", "element.tagName === 'VIDEO' && element.src.endsWith('#t=2.5')");
+
+ $page->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/MediaEditorTest.php b/tests/Browser/MediaEditorTest.php
index fe56615e1..d141b5e48 100644
--- a/tests/Browser/MediaEditorTest.php
+++ b/tests/Browser/MediaEditorTest.php
@@ -3,6 +3,7 @@
declare(strict_types=1);
use App\Ai\Agents\MediaAltTextGenerator;
+use App\Enums\Media\Type as MediaType;
use App\Enums\PostPlatform\ContentType;
use App\Models\Media;
use App\Models\Post;
@@ -763,7 +764,7 @@ test('a reel video gets a Thumbnail segment whose frame is saved as the cover of
$page->click('@media-editor-thumbnail-tab')
->assertSee('Choose a thumbnail')
->assertVisible('@media-editor-stage-video')
- ->assertAttribute('@media-editor-thumb-0', 'aria-label', 'Video 1');
+ ->assertMissing('@media-editor-thumbnails');
waitForState($page, '@media-editor-cover', "element.max === '3'");
expect($page->script("document.querySelector('[data-testid=\"media-editor-cover\"]').max"))->toBe('3');
@@ -786,10 +787,353 @@ test('a reel video gets a Thumbnail segment whose frame is saved as the cover of
saveMediaEditorDraft($page);
expect($post->fresh()->media[0]['meta']['cover_offset_ms'])->toBe(2500)
- ->and($post->fresh()->media[0]['id'])->toBe('video-1');
+ ->and($post->fresh()->media[0]['id'])->toBe('video-1')
+ ->and(data_get($post->fresh()->media, '0.meta.cover'))->toBeNull();
$page->assertNoJavaScriptErrors();
});
+function pickMediaEditorCoverImage(mixed $page): void
+{
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ $page->script(<<<JS
+ (() => {
+ const input = document.querySelector('[data-testid="media-editor-cover-image-input"]');
+ const bytes = Uint8Array.from(atob('{$png}'), (character) => character.charCodeAt(0));
+ const transfer = new DataTransfer();
+ transfer.items.add(new File([bytes], 'cover.png', { type: 'image/png' }));
+ input.files = transfer.files;
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ })();
+ JS);
+}
+
+test('a reel video takes an uploaded image as its cover', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
+ $page->click("@composer-{$accountId}-edit-0");
+ waitFor($page, '@media-editor-cover-source');
+
+ $page->assertAttribute('@media-editor-cover-source-frame', 'aria-pressed', 'true');
+
+ $page->click('@media-editor-cover-source-image')
+ ->assertSee('Your video shows this image as its cover.')
+ ->assertMissing('@media-editor-cover')
+ ->assertMissing('@media-editor-selection');
+
+ pickMediaEditorCoverImage($page);
+ waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
+ $page->assertSee('Replace image')
+ ->assertPresent('@media-editor-handle-nw')
+ ->assertPresent('@media-editor-center')
+ ->assertMissing('@crop-aspect-9-16')
+ ->click('@media-editor-apply');
+ saveMediaEditorDraft($page);
+
+ $cover = data_get($post->fresh()->media, '0.meta.cover');
+ $owned = Media::query()->find(data_get($cover, 'id'));
+ [$width, $height] = getimagesizefromstring(Storage::get($owned->path));
+
+ expect($owned->post_id)->toBe($post->id)
+ ->and($owned->type)->toBe(MediaType::Image)
+ ->and($owned->upload_token)->toBeNull()
+ ->and($height / $width)->toEqualWithDelta(16 / 9, 0.02)
+ ->and(data_get($post->fresh()->media, '0.id'))->toBe('video-1');
+ $page->assertNoJavaScriptErrors();
+});
+
+test('switching a reel back to a video frame saves the frame time and drops the image', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ $media = $post->media;
+ $media[0]['meta']['cover'] = [
+ 'id' => 'cover-1',
+ 'type' => 'image',
+ 'mime_type' => 'image/png',
+ 'path' => 'uploads/cover-1.png',
+ 'url' => "data:image/png;base64,{$png}",
+ 'size' => 1024,
+ ];
+ $post->update(['media' => $media]);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
+ $page->click("@composer-{$accountId}-edit-0");
+ waitFor($page, '@media-editor-selection');
+
+ $page->click('@media-editor-cover-source-frame');
+ waitFor($page, '@media-editor-cover');
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
+ $page->click('@media-editor-apply');
+ saveMediaEditorDraft($page);
+
+ expect(data_get($post->fresh()->media, '0.meta.cover'))->toBeNull()
+ ->and(data_get($post->fresh()->media, '0.meta.cover_offset_ms'))->toBe(0);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('switching a youtube short back to a video frame saves a screenshot of that frame as the cover', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::YouTubeShort);
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ $media = $post->media;
+ $media[0]['meta']['cover'] = [
+ 'id' => 'cover-1',
+ 'type' => 'image',
+ 'mime_type' => 'image/png',
+ 'path' => 'uploads/cover-1.png',
+ 'url' => "data:image/png;base64,{$png}",
+ 'size' => 1024,
+ ];
+ $post->update(['media' => $media]);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
+ $page->click("@composer-{$accountId}-edit-0");
+ waitFor($page, '@media-editor-selection');
+
+ $page->assertAttribute('@media-editor-cover-source-image', 'aria-pressed', 'true');
+ waitForState($page, '@media-editor-apply', 'element.disabled === true');
+
+ $page->click('@media-editor-cover-source-frame');
+ waitFor($page, '@media-editor-cover');
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
+ $page->click('@media-editor-apply');
+ saveMediaEditorDraft($page);
+
+ $cover = data_get($post->fresh()->media, '0.meta.cover');
+ $owned = Media::query()->find(data_get($cover, 'id'));
+
+ expect(data_get($cover, 'id'))->not->toBe('cover-1')
+ ->and($owned->post_id)->toBe($post->id)
+ ->and($owned->type)->toBe(MediaType::Image)
+ ->and(data_get($post->fresh()->media, '0.meta.cover_offset_ms'))->toBe(0);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('picking an image as the cover keeps the frame picked for the networks that only take one', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
+ $media = $post->media;
+ $media[0]['meta']['cover_offset_ms'] = 2500;
+ $post->update(['media' => $media]);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
+ $page->click("@composer-{$accountId}-edit-0");
+ waitFor($page, '@media-editor-cover-source');
+
+ $page->click('@media-editor-cover-source-image');
+ pickMediaEditorCoverImage($page);
+ waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
+ $page->click('@media-editor-apply');
+ saveMediaEditorDraft($page);
+
+ $meta = data_get($post->fresh()->media, '0.meta');
+
+ expect(data_get($meta, 'cover_source'))->toBe('image')
+ ->and(data_get($meta, 'cover_offset_ms'))->toBe(2500)
+ ->and(data_get($meta, 'cover.id'))->not->toBeNull();
+ $page->assertNoJavaScriptErrors();
+});
+
+test('picking image over a frame cover waits for an image instead of reusing the frame screenshot', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ $media = $post->media;
+ $media[0]['meta'] = [...$media[0]['meta'], 'cover_offset_ms' => 2500, 'cover_source' => 'frame', 'cover' => [
+ 'id' => 'cover-1', 'type' => 'image', 'mime_type' => 'image/png', 'path' => 'uploads/cover.png', 'url' => "data:image/png;base64,{$png}",
+ ]];
+ $post->update(['media' => $media]);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
+ $page->click("@composer-{$accountId}-edit-0");
+ waitFor($page, '@media-editor-cover-timeline');
+
+ $page->click('@media-editor-cover-source-image');
+ waitFor($page, '@media-editor-stage-video');
+
+ $page->assertMissing('@media-editor-selection')
+ ->assertSee('Upload image')
+ ->assertNoJavaScriptErrors();
+});
+
+test('reframing a stored cover saves the new frame of it', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ $media = $post->media;
+ $media[0]['meta']['cover'] = [
+ 'id' => 'cover-1',
+ 'type' => 'image',
+ 'mime_type' => 'image/png',
+ 'path' => 'uploads/cover-1.png',
+ 'url' => "data:image/png;base64,{$png}",
+ 'size' => 1024,
+ ];
+ $post->update(['media' => $media]);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
+ $page->click("@composer-{$accountId}-edit-0");
+ waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
+ waitForState($page, '@media-editor-apply', 'element.disabled === true');
+
+ $page->drag('@media-editor-handle-nw', '@media-editor-stage');
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
+ $page->click('@media-editor-apply');
+ saveMediaEditorDraft($page);
+
+ $owned = Media::query()->find(data_get($post->fresh()->media, '0.meta.cover.id'));
+ [$width, $height] = getimagesizefromstring(Storage::get($owned->path));
+
+ expect($owned->post_id)->toBe($post->id)
+ ->and($height / $width)->toEqualWithDelta(16 / 9, 0.02);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a youtube short offers a frame or an image as its cover', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::YouTubeShort);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
+ $page->click("@composer-{$accountId}-edit-0");
+ waitFor($page, '@media-editor-cover-source');
+
+ expect(mediaEditorSegmentIds($page))->toBe(['media-editor-thumbnail-tab']);
+ $page->assertVisible('@media-editor-cover')
+ ->assertVisible('@media-editor-cover-source-image')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a feed video offers only the cover frame', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::InstagramFeed);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
+ $page->click("@composer-{$accountId}-edit-0");
+ waitFor($page, '@media-editor-cover');
+
+ $page->assertMissing('@media-editor-cover-source')
+ ->assertNoJavaScriptErrors();
+});
+
+test('the thumbnail tab picks the frame by dragging along a strip under the video', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
+ $page->click("@composer-{$accountId}-edit-0");
+ waitFor($page, '@media-editor-cover-timeline');
+ waitForState($page, '@media-editor-cover-timeline canvas:last-of-type', 'element.width > 0');
+
+ $page->assertMissing('@media-editor-play');
+
+ $page->script(<<<'JS'
+ (() => {
+ const slider = document.querySelector('[data-testid="media-editor-cover"]');
+ slider.value = '3';
+ slider.dispatchEvent(new Event('input', { bubbles: true }));
+ })();
+ JS);
+ waitForState($page, '@media-editor-cover-selector', 'Math.abs(element.getBoundingClientRect().right - element.parentElement.getBoundingClientRect().right) < 2');
+
+ waitForText($page, '@media-editor-cover-value', '0:03.0');
+ $page->assertNoJavaScriptErrors();
+});
+
+test('the composer shows the picked cover on the media tile and on the preview until it plays', function (string $picked, string $tileElement, string $tileShows) {
+ [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ $image = ['id' => 'cover-1', 'type' => 'image', 'mime_type' => 'image/png', 'path' => 'uploads/cover.png', 'url' => "data:image/png;base64,{$png}"];
+ $cover = match ($picked) {
+ 'frame' => ['cover_offset_ms' => 2500],
+ 'captured frame' => ['cover_offset_ms' => 2500, 'cover' => $image, 'cover_source' => 'frame'],
+ 'image' => ['cover' => $image],
+ };
+ $media = $post->media;
+ $media[0]['meta'] = [...$media[0]['meta'], ...$cover];
+ $post->update(['media' => $media]);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitFor($page, "@composer-{$accountId}-media-item-0");
+ waitFor($page, '@video-preview-cover');
+
+ waitForState($page, "@composer-{$accountId}-media-item-0 {$tileElement}", $tileShows);
+
+ $page->click('@video-preview-play');
+ waitForGone($page, '@video-preview-cover');
+ $page->assertNoJavaScriptErrors();
+})->with([
+ 'a picked frame' => ['frame', 'video', "element.src.endsWith('#t=2.5')"],
+ 'a frame with its screenshot' => ['captured frame', 'video', "element.src.endsWith('#t=2.5')"],
+ 'an uploaded image' => ['image', 'img', "element.src.startsWith('data:image/png')"],
+]);
+
+test('a tiktok preview shows the picked frame, not an image uploaded for another network', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::TikTokVideo);
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ $media = $post->media;
+ $media[0]['meta'] = [...$media[0]['meta'], 'cover_offset_ms' => 2500, 'cover_source' => 'image', 'cover' => [
+ 'id' => 'cover-1', 'type' => 'image', 'mime_type' => 'image/png', 'path' => 'uploads/cover.png', 'url' => "data:image/png;base64,{$png}",
+ ]];
+ $post->update(['media' => $media]);
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, '@video-preview-cover', "element.tagName === 'VIDEO' && element.src.endsWith('#t=2.5')");
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a frame picked before youtube was added gets its screenshot when the editor applies', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::YouTubeShort);
+ $media = $post->media;
+ $media[0]['meta']['cover_offset_ms'] = 1500;
+ $post->update(['media' => $media]);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
+ $page->click("@composer-{$accountId}-edit-0");
+ waitFor($page, '@media-editor-cover-timeline');
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
+ $page->click('@media-editor-apply');
+ saveMediaEditorDraft($page);
+
+ $owned = Media::query()->find(data_get($post->fresh()->media, '0.meta.cover.id'));
+
+ expect($owned->post_id)->toBe($post->id)
+ ->and(data_get($post->fresh()->media, '0.meta.cover_source'))->toBe('frame')
+ ->and(data_get($post->fresh()->media, '0.meta.cover_offset_ms'))->toBe(1500);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a feed post\'s media tile shows the picked frame, not an image only a reel takes', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::InstagramFeed);
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ $media = $post->media;
+ $media[0]['meta'] = [...$media[0]['meta'], 'cover_offset_ms' => 2500, 'cover_source' => 'image', 'cover' => [
+ 'id' => 'cover-1', 'type' => 'image', 'mime_type' => 'image/png', 'path' => 'uploads/cover.png', 'url' => "data:image/png;base64,{$png}",
+ ]];
+ $post->update(['media' => $media]);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+
+ waitForState($page, "@composer-{$accountId}-media-item-0 video", "element.src.endsWith('#t=2.5')");
+ $page->assertMissing("@composer-{$accountId}-media-item-0 img")
+ ->assertNoJavaScriptErrors();
+});
+
+test('a video without a picked cover shows the video itself on the preview', function () {
+ [$post] = seedMediaEditorVideoPost(ContentType::TikTokVideo);
+ $accountId = $post->social_account_id;
+ $page = visit(route('app.posts.edit', $post));
+ waitFor($page, "@composer-{$accountId}-media-item-0");
+ letPageRun($page, 500);
+
+ $page->assertMissing('@video-preview-cover')
+ ->assertNoJavaScriptErrors();
+});
+
test('a video on an X post shows no pencil', function () {
[$post] = seedMediaEditorVideoPost(ContentType::XPost);
$accountId = $post->social_account_id;
diff --git a/tests/Browser/YouTubeCoverWarningCardTest.php b/tests/Browser/YouTubeCoverWarningCardTest.php
new file mode 100644
index 000000000..afe248797
--- /dev/null
+++ b/tests/Browser/YouTubeCoverWarningCardTest.php
@@ -0,0 +1,52 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\PostPlatform\ContentType;
+use App\Enums\YouTube\ThumbnailWarning;
+use App\Jobs\Analytics\BootstrapAccountAnalytics;
+use App\Jobs\Analytics\CollectAccountDailySnapshot;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use Illuminate\Support\Facades\Queue;
+
+test('a Short whose cover YouTube refused shows it under its time, with the reason in a popover', function () {
+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
+
+ $user = User::factory()->create(['timezone' => 'UTC']);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ subscribeAccount($user->account);
+ connectAiTo($user);
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $workspace->id, 'timezone' => 'UTC']);
+
+ $sentShort = fn (int $hoursAgo): Post => Post::factory()->forAccount($account, ContentType::YouTubeShort)->published()->create([
+ 'user_id' => $user->id,
+ 'platform_url' => 'https://www.youtube.com/shorts/abc',
+ 'published_at' => now()->subHours($hoursAgo),
+ ]);
+ $refused = $sentShort(1);
+ $refused->recordYouTubeThumbnailWarning(ThumbnailWarning::Forbidden);
+ $applied = $sentShort(2);
+
+ $this->actingAs($user);
+ $page = visit(route('app.posts.index', ['tab' => 'sent']));
+
+ waitFor($page, "@post-cover-warning-{$refused->id}");
+ waitFor($page, "@post-card-{$applied->id}");
+
+ $page->assertSeeIn("@post-cover-warning-{$refused->id}", __('posts.publish.youtube_thumbnail_warning.badge'))
+ ->assertMissing("@post-cover-warning-{$applied->id}");
+
+ $page->click("@post-cover-warning-{$refused->id}");
+ waitForOpen($page, "@post-cover-warning-popover-{$refused->id}");
+
+ $page->assertSeeIn("@post-cover-warning-popover-{$refused->id}", __('posts.publish.youtube_thumbnail_warning.title'))
+ ->assertSeeIn("@post-cover-warning-reason-{$refused->id}", __('posts.publish.youtube_thumbnail_warning.forbidden', ['url' => 'youtube.com/verify']))
+ ->assertAttribute("@post-cover-warning-verify-{$refused->id}", 'href', 'https://www.youtube.com/verify')
+ ->assertAttribute("@post-cover-warning-verify-{$refused->id}", 'target', '_blank')
+ ->assertNoJavaScriptErrors();
+});
diff --git a/tests/Feature/Jobs/PublishToSocialPlatformTest.php b/tests/Feature/Jobs/PublishToSocialPlatformTest.php
index 457984367..b29dfb05e 100644
--- a/tests/Feature/Jobs/PublishToSocialPlatformTest.php
+++ b/tests/Feature/Jobs/PublishToSocialPlatformTest.php
@@ -24,6 +24,7 @@ use App\Exceptions\TokenExpiredException;
use App\Jobs\PublishToSocialPlatform;
use App\Jobs\ResolveTikTokVideoId;
use App\Jobs\SendNotification;
+use App\Jobs\SetYouTubeCover;
use App\Mail\AccountDisconnected;
use App\Mail\PostPublished;
use App\Mail\PostPublishFailed;
@@ -39,6 +40,7 @@ use App\Services\Social\LinkedInPagePublisher;
use App\Services\Social\LinkedInPublisher;
use App\Services\Social\PinterestPublisher;
use App\Services\Social\TikTokPublisher;
+use App\Services\Social\YouTubePublisher;
use App\Support\Social\GoogleBusinessDerivativeCleaner;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldBeUnique;
@@ -2442,6 +2444,47 @@ test('a thread that stops on any error says how much of it is live', function ()
]));
});
+test('a youtube video published with a cover image sets it once youtube processes the video', function (bool $hasCover) {
+ Event::fake();
+ Mail::fake();
+ Queue::fake([SetYouTubeCover::class]);
+ $this->freezeTime();
+
+ $account = SocialAccount::factory()->youtube()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'token_expires_at' => now()->addDay(),
+ ]);
+ $cover = ['id' => 'cover', 'path' => 'media/cover.jpg', 'url' => 'https://example.com/media/cover.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg'];
+ $this->post->update([
+ 'media' => [[
+ 'id' => 'video',
+ 'path' => 'media/video.mp4',
+ 'url' => 'https://example.com/media/video.mp4',
+ 'type' => 'video',
+ 'mime_type' => 'video/mp4',
+ 'meta' => $hasCover ? ['cover' => $cover] : [],
+ ]],
+ ]);
+ $post = publishJobRetarget($this->post, $account, [
+ 'content_type' => ContentType::YouTubeShort,
+ 'publish_status' => PlatformStatus::Pending,
+ ]);
+
+ $publisher = Mockery::mock(YouTubePublisher::class);
+ $publisher->shouldReceive('publish')->once()->andReturn(['id' => 'short-id', 'url' => 'https://www.youtube.com/shorts/short-id']);
+ $this->app->instance(YouTubePublisher::class, $publisher);
+
+ (new PublishToSocialPlatform($post))->handle();
+
+ $hasCover
+ ? Queue::assertPushedOn(Platform::YouTube->queue(), SetYouTubeCover::class, fn (SetYouTubeCover $job): bool => $job->post->is($post)
+ && $job->delay->equalTo(now()->addSeconds(SetYouTubeCover::CHECK_EVERY_SECONDS)))
+ : Queue::assertNotPushed(SetYouTubeCover::class);
+})->with([
+ 'with a cover image' => [true],
+ 'without one' => [false],
+]);
+
test('a tiktok post published before TikTok reports its video id asks again a minute later', function (string $platformPostId, PrivacyLevel $privacy, bool $asks) {
Event::fake();
Mail::fake();
diff --git a/tests/Feature/Jobs/SetYouTubeCoverTest.php b/tests/Feature/Jobs/SetYouTubeCoverTest.php
new file mode 100644
index 000000000..07fdc00b9
--- /dev/null
+++ b/tests/Feature/Jobs/SetYouTubeCoverTest.php
@@ -0,0 +1,229 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\Post\PublishStatus;
+use App\Enums\PostPlatform\ContentType;
+use App\Enums\SocialAccount\Status as AccountStatus;
+use App\Enums\YouTube\ThumbnailWarning;
+use App\Exceptions\TokenExpiredException;
+use App\Http\Resources\App\PostCardResource;
+use App\Jobs\SetYouTubeCover;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Services\Social\ConnectionVerifier;
+use Google\Client;
+use Illuminate\Http\Client\Request;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Queue;
+use Intervention\Image\Drivers\Gd\Driver;
+use Intervention\Image\ImageManager;
+
+const YOUTUBE_VIDEOS_URL = 'https://youtube.googleapis.com/youtube/v3/videos*';
+const YOUTUBE_THUMBNAILS_URL = 'https://youtube.googleapis.com/upload/youtube/v3/thumbnails/set*';
+const YOUTUBE_COVER_URL = 'https://cdn.test/medias/cover.jpg';
+
+beforeEach(function () {
+ Queue::fake();
+
+ $this->account = SocialAccount::factory()->youtube()->create(['token_expires_at' => now()->addDay()]);
+ $this->post = Post::factory()->forAccount($this->account, ContentType::YouTubeShort)->published()->create([
+ 'platform_post_id' => 'short-id',
+ 'media' => [[
+ 'id' => 'video-1',
+ 'path' => 'medias/video.mp4',
+ 'url' => 'https://cdn.test/medias/video.mp4',
+ 'type' => 'video',
+ 'mime_type' => 'video/mp4',
+ 'meta' => ['cover' => [
+ 'id' => 'cover-1',
+ 'path' => 'medias/cover.jpg',
+ 'url' => YOUTUBE_COVER_URL,
+ 'type' => 'image',
+ 'mime_type' => 'image/jpeg',
+ ]],
+ ]],
+ ]);
+});
+
+function youTubeProcessing(string $status): array
+{
+ return ['items' => [['id' => 'short-id', 'processingDetails' => ['processingStatus' => $status]]]];
+}
+
+/**
+ * The Google client is built after `Http::fake()`, so its requests reach the fakes.
+ */
+function runSetYouTubeCover(Post $post): SetYouTubeCover
+{
+ $client = new Client;
+ $client->setHttpClient(Http::buildClient());
+ app()->instance(Client::class, $client);
+
+ $job = (new SetYouTubeCover($post))->withFakeQueueInteractions();
+ app()->call([$job, 'handle']);
+
+ return $job;
+}
+
+test('a processed video gets the cover image as its thumbnail', function () {
+ Http::fake([
+ YOUTUBE_VIDEOS_URL => Http::response(youTubeProcessing('succeeded')),
+ YOUTUBE_COVER_URL => Http::response('jpeg bytes', 200, ['Content-Type' => 'image/jpeg']),
+ YOUTUBE_THUMBNAILS_URL => Http::response(['kind' => 'youtube#thumbnailSetResponse', 'items' => []]),
+ ]);
+
+ runSetYouTubeCover($this->post)->assertNotReleased();
+
+ Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/thumbnails/set')
+ && str_contains($request->url(), 'videoId=short-id')
+ && $request->body() === 'jpeg bytes');
+ expect($this->post->fresh()->youTubeThumbnailWarning())->toBeNull();
+});
+
+test('a video still processing is checked again a minute later', function () {
+ Http::fake([YOUTUBE_VIDEOS_URL => Http::response(youTubeProcessing('processing'))]);
+
+ runSetYouTubeCover($this->post)->assertReleased(delay: SetYouTubeCover::CHECK_EVERY_SECONDS);
+
+ Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/thumbnails/set'));
+});
+
+test('a cover YouTube refuses leaves a warning and the post published', function (int $status, ThumbnailWarning $warning) {
+ Http::fake([
+ YOUTUBE_VIDEOS_URL => Http::response(youTubeProcessing('succeeded')),
+ YOUTUBE_COVER_URL => Http::response('jpeg bytes', 200, ['Content-Type' => 'image/jpeg']),
+ YOUTUBE_THUMBNAILS_URL => Http::response(['error' => ['code' => $status, 'message' => 'refused', 'errors' => [['reason' => 'refused']]]], $status),
+ ]);
+
+ runSetYouTubeCover($this->post)->assertNotReleased();
+
+ expect($this->post->fresh()->youTubeThumbnailWarning())->toBe($warning)
+ ->and($this->post->fresh()->publish_status)->toBe(PublishStatus::Published);
+})->with([
+ 'channel not verified' => [403, ThumbnailWarning::Forbidden],
+ 'daily limit' => [429, ThumbnailWarning::DailyLimit],
+ 'invalid image' => [400, ThumbnailWarning::InvalidImage],
+]);
+
+test('a server error is tried again', function () {
+ Http::fake([
+ YOUTUBE_VIDEOS_URL => Http::response(youTubeProcessing('succeeded')),
+ YOUTUBE_COVER_URL => Http::response('jpeg bytes', 200, ['Content-Type' => 'image/jpeg']),
+ YOUTUBE_THUMBNAILS_URL => Http::response(['error' => ['code' => 503, 'message' => 'backend']], 503),
+ ]);
+
+ runSetYouTubeCover($this->post)->assertReleased(delay: SetYouTubeCover::CHECK_EVERY_SECONDS);
+
+ expect($this->post->fresh()->youTubeThumbnailWarning())->toBeNull();
+});
+
+test('running out of tries leaves the failed warning', function () {
+ (new SetYouTubeCover($this->post))->failed(null);
+
+ expect($this->post->fresh()->youTubeThumbnailWarning())->toBe(ThumbnailWarning::Failed);
+});
+
+test('a post without a cover image asks youtube nothing', function () {
+ $this->post->update(['media' => [[...$this->post->media[0], 'meta' => []]]]);
+ Http::fake();
+
+ runSetYouTubeCover($this->post);
+
+ Http::assertNothingSent();
+});
+
+test('the post card shows the cover warning without a failure', function () {
+ $this->post->recordYouTubeThumbnailWarning(ThumbnailWarning::Forbidden);
+
+ $card = PostCardResource::make($this->post->fresh())->resolve();
+
+ expect($card['youtube_thumbnail_warning'])->toBe('forbidden')
+ ->and($card['failure'])->toBeNull();
+});
+
+test('a video youtube could not process leaves the failed warning', function (string $status) {
+ Http::fake([YOUTUBE_VIDEOS_URL => Http::response(youTubeProcessing($status))]);
+
+ runSetYouTubeCover($this->post)->assertNotReleased();
+
+ expect($this->post->fresh()->youTubeThumbnailWarning())->toBe(ThumbnailWarning::Failed);
+ Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/thumbnails/set'));
+})->with(['failed', 'terminated']);
+
+test('a video youtube no longer lists leaves no warning', function () {
+ Http::fake([YOUTUBE_VIDEOS_URL => Http::response(['items' => []])]);
+
+ runSetYouTubeCover($this->post)->assertNotReleased();
+
+ expect($this->post->fresh()->youTubeThumbnailWarning())->toBeNull();
+});
+
+test('a revoked token leaves the failed warning at once instead of retrying', function () {
+ $this->account->update(['token_expires_at' => now()->subMinute()]);
+ $verifier = Mockery::mock(ConnectionVerifier::class);
+ $verifier->shouldReceive('refreshToken')->once()->andThrow(new TokenExpiredException('revoked'));
+ $this->app->instance(ConnectionVerifier::class, $verifier);
+ Http::fake();
+
+ runSetYouTubeCover($this->post)->assertNotReleased();
+
+ expect($this->post->fresh()->youTubeThumbnailWarning())->toBe(ThumbnailWarning::Failed);
+});
+
+test('a cover that is not a jpeg or a png reaches youtube as a jpeg', function () {
+ $this->post->update(['media' => [[...$this->post->media[0], 'meta' => ['cover' => [
+ ...data_get($this->post->media, '0.meta.cover'),
+ 'mime_type' => 'image/webp',
+ ]]]]]);
+ $webp = (string) (new ImageManager(Driver::class))->createImage(320, 568)->fill('336699')->encodeUsingMediaType('image/webp');
+ Http::fake([
+ YOUTUBE_VIDEOS_URL => Http::response(youTubeProcessing('succeeded')),
+ YOUTUBE_COVER_URL => Http::response($webp, 200, ['Content-Type' => 'image/webp']),
+ YOUTUBE_THUMBNAILS_URL => Http::response(['kind' => 'youtube#thumbnailSetResponse', 'items' => []]),
+ ]);
+
+ runSetYouTubeCover($this->post);
+
+ Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/thumbnails/set')
+ && $request->header('Content-Type')[0] === 'image/jpeg'
+ && str_starts_with($request->body(), "\xFF\xD8"));
+});
+
+test('a cover that cannot be made a jpeg leaves the invalid image warning at once', function () {
+ $this->post->update(['media' => [[...$this->post->media[0], 'meta' => ['cover' => [
+ ...data_get($this->post->media, '0.meta.cover'),
+ 'mime_type' => 'image/webp',
+ ]]]]]);
+ Http::fake([
+ YOUTUBE_VIDEOS_URL => Http::response(youTubeProcessing('succeeded')),
+ YOUTUBE_COVER_URL => Http::response('not an image', 200, ['Content-Type' => 'image/webp']),
+ ]);
+
+ runSetYouTubeCover($this->post)->assertNotReleased();
+
+ expect($this->post->fresh()->youTubeThumbnailWarning())->toBe(ThumbnailWarning::InvalidImage);
+ Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/thumbnails/set'));
+});
+
+test('a video removed before its thumbnail was set leaves no warning', function () {
+ Http::fake([
+ YOUTUBE_VIDEOS_URL => Http::response(youTubeProcessing('succeeded')),
+ YOUTUBE_COVER_URL => Http::response('jpeg bytes', 200, ['Content-Type' => 'image/jpeg']),
+ YOUTUBE_THUMBNAILS_URL => Http::response(['error' => ['code' => 404, 'message' => 'not found', 'errors' => [['reason' => 'videoNotFound']]]], 404),
+ ]);
+
+ runSetYouTubeCover($this->post)->assertNotReleased();
+
+ expect($this->post->fresh()->youTubeThumbnailWarning())->toBeNull();
+});
+
+test('a channel no longer connected leaves the failed warning', function () {
+ $this->account->update(['status' => AccountStatus::TokenExpired]);
+ Http::fake();
+
+ runSetYouTubeCover($this->post);
+
+ expect($this->post->fresh()->youTubeThumbnailWarning())->toBe(ThumbnailWarning::Failed);
+ Http::assertNothingSent();
+});
diff --git a/tests/Feature/Mcp/PlatformToolTest.php b/tests/Feature/Mcp/PlatformToolTest.php
index 7f8cd77a0..3ea885e43 100644
--- a/tests/Feature/Mcp/PlatformToolTest.php
+++ b/tests/Feature/Mcp/PlatformToolTest.php
@@ -66,6 +66,7 @@ test('list content types returns all platforms with constraints', function () {
'supports_alt_text',
'supports_user_tags',
'supports_video_cover',
+ 'supports_custom_video_cover',
'captionless',
'document_must_be_alone',
'supports_thread_replies',
diff --git a/tests/Feature/Media/SyncOwnedMediaTest.php b/tests/Feature/Media/SyncOwnedMediaTest.php
index 7faf800ad..9b4b0db86 100644
--- a/tests/Feature/Media/SyncOwnedMediaTest.php
+++ b/tests/Feature/Media/SyncOwnedMediaTest.php
@@ -98,6 +98,30 @@ test('one composition to three channels gives every post its own rows and files'
});
});
+test('reordering a post keeps the submitted order in its media and in its rows', function () {
+ $post = CreatePosts::execute($this->workspace, $this->user, syncOwnedMediaComposition($this->channels->take(1), [
+ syncOwnedMediaStored(Media::factory()->temporaryUpload($this->workspace)),
+ syncOwnedMediaStored(Media::factory()->temporaryUpload($this->workspace)),
+ syncOwnedMediaStored(Media::factory()->temporaryUpload($this->workspace)),
+ ]))->sole();
+ [$first, $second, $third] = $post->ownedMedia->all();
+ $added = syncOwnedMediaStored(Media::factory()->temporaryUpload($this->workspace));
+
+ UpdatePost::execute($this->workspace, $post->fresh(), ['media' => [
+ MediaItem::fromMedia($third)->toArray(),
+ MediaItem::fromMedia($added)->toArray(),
+ MediaItem::fromMedia($first)->toArray(),
+ MediaItem::fromMedia($second)->toArray(),
+ ]]);
+
+ $expected = [$third->id, $added->id, $first->id, $second->id];
+ $post->refresh();
+
+ expect(collect($post->media)->pluck('id')->all())->toBe($expected)
+ ->and($post->ownedMedia->pluck('id')->all())->toBe($expected)
+ ->and($post->ownedMedia->pluck('order')->all())->toBe([0, 1, 2, 3]);
+});
+
test('syncing a post with the items it already owns changes nothing', function () {
$post = CreatePosts::execute($this->workspace, $this->user, syncOwnedMediaComposition(
$this->channels->take(1),
diff --git a/tests/Feature/Media/VideoCoverImageTest.php b/tests/Feature/Media/VideoCoverImageTest.php
new file mode 100644
index 000000000..08d2d4f1f
--- /dev/null
+++ b/tests/Feature/Media/VideoCoverImageTest.php
@@ -0,0 +1,315 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Actions\Media\AuditMedia;
+use App\Actions\Media\SyncOwnedMedia;
+use App\Actions\Post\CreatePosts;
+use App\Actions\Post\DeletePost;
+use App\Actions\Post\DuplicatePost;
+use App\Dto\MediaItem;
+use App\Enums\Post\Status;
+use App\Enums\PostPlatform\ContentType;
+use App\Mcp\Servers\TryPostServer;
+use App\Mcp\Tools\Post\UpdatePostTool;
+use App\Models\Idea;
+use App\Models\Media;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use App\Support\Media\MediaCopyBatch;
+use Illuminate\Support\Facades\Queue;
+use Illuminate\Support\Facades\Storage;
+
+beforeEach(function () {
+ Storage::fake();
+ Queue::fake();
+
+ $this->user = User::factory()->create();
+ $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
+ $this->workspace->members()->attach($this->user->id, membershipPivot('admin'));
+ $this->user->update(['current_workspace_id' => $this->workspace->id]);
+
+ $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
+ $this->post = Post::factory()->forAccount($account, ContentType::InstagramReel)->create([
+ 'user_id' => $this->user->id,
+ 'status' => Status::Draft,
+ 'scheduled_at' => null,
+ ]);
+ $this->video = Media::factory()->video()->ownedByPost($this->post)->stored()->create(['meta' => ['duration' => 10]]);
+ $this->post->update(['media' => [MediaItem::fromMedia($this->video)->toArray()]]);
+});
+
+/**
+ * @param array<string, mixed>|null $cover
+ * @return array<string, mixed>
+ */
+function videoCoverImageItem(Media $video, ?array $cover): array
+{
+ $item = MediaItem::fromMedia($video)->toArray();
+
+ if ($cover === null) {
+ return $item;
+ }
+
+ return [...$item, 'meta' => [...$item['meta'], 'cover' => $cover]];
+}
+
+/**
+ * @param array<int, array<string, mixed>> $media
+ */
+function updateVideoCoverImageOnWeb(object $test, array $media): mixed
+{
+ return $test->actingAs($test->user)->put(route('app.posts.update', $test->post), [
+ 'status' => 'draft',
+ 'content' => 'hi',
+ 'media' => $media,
+ ]);
+}
+
+/**
+ * @return array<string, string>
+ */
+function videoCoverImageApiHeaders(Workspace $workspace): array
+{
+ return ['Authorization' => 'Bearer '.createApiTestToken(['workspace' => $workspace])['plain_token']];
+}
+
+test('the web composer adopts an uploaded image as the video cover', function () {
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+
+ updateVideoCoverImageOnWeb($this, [videoCoverImageItem($this->video, MediaItem::fromMedia($upload)->toArray())])
+ ->assertSessionHasNoErrors();
+
+ $cover = data_get($this->post->fresh()->media, '0.meta.cover');
+
+ expect(data_get($cover, 'id'))->toBe($upload->id)
+ ->and(data_get($cover, 'url'))->toBe($upload->fresh()->url)
+ ->and($cover)->not->toHaveKey('upload_token')
+ ->and($upload->fresh()->post_id)->toBe($this->post->id)
+ ->and($upload->fresh()->upload_token)->toBeNull();
+});
+
+test('removing the cover deletes its row and keeps the video', function () {
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+ updateVideoCoverImageOnWeb($this, [videoCoverImageItem($this->video, MediaItem::fromMedia($upload)->toArray())]);
+
+ updateVideoCoverImageOnWeb($this, [videoCoverImageItem($this->video, null)])->assertSessionHasNoErrors();
+
+ expect(data_get($this->post->fresh()->media, '0.meta.cover'))->toBeNull()
+ ->and(Media::query()->whereKey($upload->id)->exists())->toBeFalse()
+ ->and(Media::query()->whereKey($this->video->id)->exists())->toBeTrue();
+});
+
+test('the web composer keeps a stored cover when the video item is sent again', function () {
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+ updateVideoCoverImageOnWeb($this, [videoCoverImageItem($this->video, MediaItem::fromMedia($upload)->toArray())]);
+ $stored = $this->post->fresh()->media;
+
+ updateVideoCoverImageOnWeb($this, $stored)->assertSessionHasNoErrors();
+
+ expect(data_get($this->post->fresh()->media, '0.meta.cover.id'))->toBe($upload->id)
+ ->and(Media::query()->whereKey($upload->id)->exists())->toBeTrue();
+});
+
+test('a cover that is not a still image is refused', function (Closure $makeCover) {
+ $cover = $makeCover($this->workspace);
+
+ updateVideoCoverImageOnWeb($this, [videoCoverImageItem($this->video, MediaItem::fromMedia($cover)->toArray())])
+ ->assertSessionHasErrors(['media.0.meta.cover' => 'The video cover must be a JPEG, PNG or WebP image.']);
+
+ expect(data_get($this->post->fresh()->media, '0.meta.cover'))->toBeNull()
+ ->and($cover->fresh()->post_id)->toBeNull();
+})->with([
+ 'a video' => [fn (Workspace $workspace): Media => Media::factory()->video()->stored()->temporaryUpload($workspace)->create()],
+ 'a gif' => [fn (Workspace $workspace): Media => Media::factory()->stored()->temporaryUpload($workspace)->create(['mime_type' => 'image/gif', 'path' => 'media/cover.gif'])],
+]);
+
+test('a cover without a file reference is refused', function (mixed $cover) {
+ $this->withHeaders(videoCoverImageApiHeaders($this->workspace))->putJson(route('api.posts.update', $this->post), [
+ 'status' => 'draft',
+ 'media' => [['id' => $this->video->id, 'meta' => ['cover' => $cover]]],
+ ])->assertUnprocessable()->assertJsonValidationErrors(['media.0.meta' => 'Choose an image for the video cover.']);
+})->with([
+ 'a string' => ['https://example.com/cover.jpg'],
+ 'an empty object' => [['alt_text' => 'cover']],
+]);
+
+test('the rest api takes the cover as an upload token', function () {
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+
+ $this->withHeaders(videoCoverImageApiHeaders($this->workspace))->putJson(route('api.posts.update', $this->post), [
+ 'status' => 'draft',
+ 'media' => [['id' => $this->video->id, 'meta' => ['cover' => ['upload_token' => $upload->upload_token]]]],
+ ])->assertOk();
+
+ expect(data_get($this->post->fresh()->media, '0.meta.cover.id'))->toBe($upload->id)
+ ->and($upload->fresh()->post_id)->toBe($this->post->id);
+});
+
+test('mcp takes the cover as a media id of the workspace and copies it', function () {
+ $otherPost = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
+ $otherPostImage = Media::factory()->stored()->ownedByPost($otherPost)->create();
+
+ TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
+ 'post_id' => $this->post->id,
+ 'media' => [['id' => $this->video->id, 'meta' => ['cover' => ['id' => $otherPostImage->id]]]],
+ ])->assertHasNoErrors();
+
+ $coverId = data_get($this->post->fresh()->media, '0.meta.cover.id');
+
+ expect($coverId)->not->toBe($otherPostImage->id)
+ ->and(Media::query()->find($coverId)->post_id)->toBe($this->post->id)
+ ->and($otherPostImage->fresh()->post_id)->toBe($otherPost->id);
+});
+
+test('a duplicate copies the cover and deleting the post deletes it', function () {
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+ updateVideoCoverImageOnWeb($this, [videoCoverImageItem($this->video, MediaItem::fromMedia($upload)->toArray())]);
+
+ $copy = DuplicatePost::execute($this->post->fresh(), $this->user);
+ $copiedId = data_get($copy->fresh()->media, '0.meta.cover.id');
+
+ expect($copiedId)->not->toBe($upload->id)
+ ->and(Media::query()->find($copiedId)->post_id)->toBe($copy->id);
+
+ DeletePost::execute($this->post->fresh());
+
+ expect(Media::query()->whereKey($upload->id)->exists())->toBeFalse()
+ ->and(Media::query()->whereKey($copiedId)->exists())->toBeTrue();
+});
+
+test('the media audit counts a cover as referenced by its post', function () {
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+ updateVideoCoverImageOnWeb($this, [videoCoverImageItem($this->video, MediaItem::fromMedia($upload)->toArray())]);
+
+ expect(collect(AuditMedia::execute(checkMissingFiles: false)['json_drift'])->pluck('media_id'))->not->toContain($upload->id);
+});
+
+test('the media item reads its cover image', function () {
+ $cover = MediaItem::fromArray(['meta' => ['cover' => ['id' => 'c', 'path' => 'media/c.jpg', 'url' => 'https://cdn.test/c.jpg', 'mime_type' => 'image/jpeg']]])->cover();
+
+ expect($cover?->url)->toBe('https://cdn.test/c.jpg')
+ ->and($cover?->isStillImage())->toBeTrue()
+ ->and(MediaItem::fromArray(['meta' => []])->cover())->toBeNull();
+});
+
+test('a post on a network that only takes a frame keeps the frame and drops the cover image', function () {
+ $tiktok = SocialAccount::factory()->tiktok()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->forAccount($tiktok, ContentType::TikTokVideo)->create([
+ 'user_id' => $this->user->id,
+ 'status' => Status::Draft,
+ 'scheduled_at' => null,
+ ]);
+ $video = Media::factory()->video()->ownedByPost($post)->stored()->create(['meta' => ['duration' => 10]]);
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+
+ $this->withHeaders(videoCoverImageApiHeaders($this->workspace))->putJson(route('api.posts.update', $post), [
+ 'status' => 'draft',
+ 'media' => [['id' => $video->id, 'meta' => ['cover_offset_ms' => 1500, 'cover_source' => 'image', 'cover' => ['upload_token' => $upload->upload_token]]]],
+ ])->assertOk();
+
+ expect(data_get($post->fresh()->media, '0.meta.cover'))->toBeNull()
+ ->and(data_get($post->fresh()->media, '0.meta.cover_source'))->toBeNull()
+ ->and(data_get($post->fresh()->media, '0.meta.cover_offset_ms'))->toBe(1500)
+ ->and($upload->fresh()->post_id)->toBeNull();
+});
+
+test('the cover source is stored with the cover and must be a frame or an image', function () {
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+
+ $this->withHeaders(videoCoverImageApiHeaders($this->workspace))->putJson(route('api.posts.update', $this->post), [
+ 'status' => 'draft',
+ 'media' => [['id' => $this->video->id, 'meta' => ['cover_source' => 'sticker', 'cover' => ['upload_token' => $upload->upload_token]]]],
+ ])->assertUnprocessable()->assertJsonValidationErrors(['media.0.meta']);
+
+ $this->withHeaders(videoCoverImageApiHeaders($this->workspace))->putJson(route('api.posts.update', $this->post), [
+ 'status' => 'draft',
+ 'media' => [['id' => $this->video->id, 'meta' => ['cover_source' => 'image', 'cover' => ['upload_token' => $upload->upload_token]]]],
+ ])->assertOk();
+
+ expect(data_get($this->post->fresh()->media, '0.meta.cover_source'))->toBe('image');
+});
+
+test('a video saved without its media row drops its image source once the cover goes', function () {
+ $item = [
+ 'id' => 'legacy-video',
+ 'path' => 'medias/legacy.mp4',
+ 'url' => 'https://cdn.example.com/medias/legacy.mp4',
+ 'type' => 'video',
+ 'mime_type' => 'video/mp4',
+ 'meta' => ['duration' => 10, 'cover_source' => 'image', 'cover_offset_ms' => 0],
+ ];
+ $this->post->update(['media' => [$item]]);
+
+ updateVideoCoverImageOnWeb($this, [[...$item, 'meta' => ['duration' => 10, 'cover_offset_ms' => 2000]]])->assertRedirect();
+
+ expect(data_get($this->post->fresh()->media, '0.meta.cover_source'))->toBeNull()
+ ->and(data_get($this->post->fresh()->media, '0.meta.cover_offset_ms'))->toBe(2000);
+});
+
+test('a thread reply video drops a cover image sent with it', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+ $replyVideo = Media::factory()->video()->stored()->temporaryUpload($this->workspace)->create();
+
+ $post = CreatePosts::execute($this->workspace, $this->user, [
+ 'status' => 'draft',
+ 'content' => 'Root',
+ 'destinations' => [[
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPost->value,
+ 'meta' => ['thread_replies' => [['text' => 'Two', 'media' => [[
+ ...MediaItem::fromMedia($replyVideo)->toArray(),
+ 'meta' => ['cover' => MediaItem::fromMedia($upload)->toArray()],
+ ]]]]],
+ ]],
+ ])->sole();
+
+ expect(data_get($post->fresh()->meta, 'thread_replies.0.media.0.meta.cover'))->toBeNull()
+ ->and($upload->fresh()->post_id)->toBeNull()
+ ->and($replyVideo->fresh()->post_id)->toBe($post->id);
+});
+
+test('an idea keeps the cover image for the post it becomes', function () {
+ $idea = Idea::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
+ $video = Media::factory()->video()->stored()->temporaryUpload($this->workspace)->create();
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+
+ MediaCopyBatch::run(fn (MediaCopyBatch $batch) => SyncOwnedMedia::execute($idea, [videoCoverImageItem($video, MediaItem::fromMedia($upload)->toArray())], $batch));
+
+ expect(data_get($idea->fresh()->media, '0.meta.cover.id'))->toBe($upload->id)
+ ->and($upload->fresh()->idea_id)->toBe($idea->id);
+});
+
+test('turning a reel into a feed post drops its cover image and deletes the row', function () {
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+ updateVideoCoverImageOnWeb($this, [videoCoverImageItem($this->video, MediaItem::fromMedia($upload)->toArray())]);
+ $stored = $this->post->fresh()->media;
+
+ $this->actingAs($this->user)->put(route('app.posts.update', $this->post), [
+ 'status' => 'draft',
+ 'content' => 'hi',
+ 'content_type' => ContentType::InstagramFeed->value,
+ 'media' => $stored,
+ ])->assertSessionHasNoErrors();
+
+ expect($this->post->fresh()->content_type)->toBe(ContentType::InstagramFeed)
+ ->and(data_get($this->post->fresh()->media, '0.meta.cover'))->toBeNull()
+ ->and(Media::query()->whereKey($upload->id)->exists())->toBeFalse();
+});
+
+test('a cover takes its video\'s place in the order instead of one of its own', function () {
+ $second = Media::factory()->video()->ownedByPost($this->post)->stored()->create(['meta' => ['duration' => 10]]);
+ $upload = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+
+ updateVideoCoverImageOnWeb($this, [
+ videoCoverImageItem($this->video, MediaItem::fromMedia($upload)->toArray()),
+ MediaItem::fromMedia($second)->toArray(),
+ ])->assertSessionHasNoErrors();
+
+ expect($this->video->fresh()->order)->toBe(0)
+ ->and($upload->fresh()->order)->toBe(0)
+ ->and($second->fresh()->order)->toBe(1);
+});
diff --git a/tests/Feature/Resources/PostCardResourceTest.php b/tests/Feature/Resources/PostCardResourceTest.php
index 4f7c5942c..4fd37de59 100644
--- a/tests/Feature/Resources/PostCardResourceTest.php
+++ b/tests/Feature/Resources/PostCardResourceTest.php
@@ -29,6 +29,7 @@ function postCardAsBefore(Post $post): array
'category' => data_get($post->error_context, 'category'),
'failed_at' => data_get($post->error_context, 'failed_at'),
],
+ 'youtube_thumbnail_warning' => null,
];
$card['user'] = $post->user === null ? null : [
@@ -72,5 +73,17 @@ test('a card without its relations loaded leaves them out', function () {
$card = PostCardResource::make($post->fresh())->resolve();
expect($card)->not->toHaveKeys(['social_account', 'user', 'labels'])
- ->and($card)->toEqual([...$post->fresh()->toArray(), 'failure' => null]);
+ ->and($card)->toEqual([...$post->fresh()->toArray(), 'failure' => null, 'youtube_thumbnail_warning' => null]);
+});
+
+test('a rejected post keeps its failure when its context has no category', function () {
+ $post = Post::factory()->forAccount($this->channel)->failed()->create([
+ 'user_id' => $this->user->id,
+ 'error_context' => ['provider_state' => 'REJECTED', 'youtube_thumbnail_warning' => 'forbidden'],
+ ]);
+
+ $card = PostCardResource::make($post->fresh())->resolve();
+
+ expect($card['failure'])->toBe(['category' => null, 'failed_at' => null])
+ ->and($card['youtube_thumbnail_warning'])->toBe('forbidden');
});
diff --git a/tests/Feature/Services/Social/InstagramPublisherTest.php b/tests/Feature/Services/Social/InstagramPublisherTest.php
index e2f74aec1..bd42214d2 100644
--- a/tests/Feature/Services/Social/InstagramPublisherTest.php
+++ b/tests/Feature/Services/Social/InstagramPublisherTest.php
@@ -2378,6 +2378,118 @@ test('instagram reel sends the chosen cover frame as thumb_offset in millisecond
'no offset' => [null],
]);
+/**
+ * @param array<string, mixed> $cover
+ * @return array<string, mixed>
+ */
+function instagramVideoWithCover(array $cover): array
+{
+ return [
+ 'id' => 'test-media-video',
+ 'path' => 'media/2026-01/test-video.mp4',
+ 'url' => 'https://example.com/media/2026-01/test-video.mp4',
+ 'mime_type' => 'video/mp4',
+ 'original_filename' => 'test.mp4',
+ 'meta' => ['duration' => 10, 'cover_offset_ms' => 1500, 'cover' => [
+ 'id' => 'test-media-cover',
+ 'path' => 'media/2026-01/cover.jpg',
+ 'url' => 'https://example.com/media/2026-01/cover.jpg',
+ 'type' => 'image',
+ 'mime_type' => 'image/jpeg',
+ 'size' => 200000,
+ ...$cover,
+ ]],
+ ];
+}
+
+function fakeInstagramReelPublish(): string
+{
+ $graph = Platform::Instagram->graphApiUrl();
+
+ Http::fake([
+ "{$graph}/ig_123456789/media" => Http::response(['id' => 'container-123']),
+ "{$graph}/container-123*" => Http::response(['status_code' => 'FINISHED']),
+ "{$graph}/ig_123456789/media_publish" => Http::response(['id' => 'reel-123']),
+ "{$graph}/reel-123*" => Http::response(['permalink' => 'https://www.instagram.com/reel/ABC/']),
+ '*' => Http::response(fakeJpegBytes(1080, 1920), 200, ['Content-Type' => 'image/jpeg']),
+ ]);
+
+ return "{$graph}/ig_123456789/media";
+}
+
+test('instagram reel sends an uploaded jpeg cover as cover_url instead of the frame', function () {
+ $this->post->update(['content_type' => ContentType::InstagramReel, 'media' => [instagramVideoWithCover([])]]);
+ $containerUrl = fakeInstagramReelPublish();
+
+ $this->publisher->publish($this->post);
+
+ Http::assertSent(fn (Request $request): bool => $request->url() === $containerUrl
+ && data_get($request->data(), 'cover_url') === 'https://example.com/media/2026-01/cover.jpg'
+ && data_get($request->data(), 'thumb_offset') === null);
+});
+
+test('instagram reel re-encodes a cover that is not a jpeg of up to 8 mb', function (array $cover) {
+ Storage::fake();
+ $this->post->update(['content_type' => ContentType::InstagramReel, 'media' => [instagramVideoWithCover($cover)]]);
+ $containerUrl = fakeInstagramReelPublish();
+
+ $this->publisher->publish($this->post);
+
+ $hosted = collect(Storage::allFiles())->first(fn (string $path): bool => str_starts_with($path, InstagramPublisher::CROP_DIRECTORY.'/'));
+
+ expect($hosted)->toEndWith('.jpg');
+ Http::assertSent(fn (Request $request): bool => $request->url() === $containerUrl
+ && data_get($request->data(), 'cover_url') === Storage::url($hosted));
+})->with([
+ 'a png' => [['path' => 'media/2026-01/cover.png', 'url' => 'https://example.com/media/2026-01/cover.png', 'mime_type' => 'image/png']],
+ 'a jpeg over 8 mb' => [['size' => 9 * 1024 * 1024]],
+]);
+
+test('instagram reel publishes with the picked frame when the cover cannot be made a jpeg', function () {
+ Storage::fake();
+ $this->post->update(['content_type' => ContentType::InstagramReel, 'media' => [instagramVideoWithCover(['mime_type' => 'image/png', 'url' => 'https://example.com/media/2026-01/cover.png'])]]);
+ $graph = Platform::Instagram->graphApiUrl();
+ Http::fake([
+ "{$graph}/ig_123456789/media" => Http::response(['id' => 'container-123']),
+ "{$graph}/container-123*" => Http::response(['status_code' => 'FINISHED']),
+ "{$graph}/ig_123456789/media_publish" => Http::response(['id' => 'reel-123']),
+ "{$graph}/reel-123*" => Http::response(['permalink' => 'https://www.instagram.com/reel/ABC/']),
+ '*' => Http::response('not an image', 200, ['Content-Type' => 'image/png']),
+ ]);
+
+ $result = $this->publisher->publish($this->post);
+
+ expect($result['id'])->toBe('reel-123');
+ Http::assertSent(fn (Request $request): bool => $request->url() === "{$graph}/ig_123456789/media"
+ && data_get($request->data(), 'cover_url') === null
+ && data_get($request->data(), 'thumb_offset') === 1500);
+});
+
+test('instagram reel sends a frame cover as its time, not as its screenshot', function () {
+ $this->post->update(['content_type' => ContentType::InstagramReel, 'media' => [instagramVideoWithCover([])]]);
+ $media = $this->post->media;
+ $media[0]['meta']['cover_source'] = 'frame';
+ $this->post->update(['media' => $media]);
+ $containerUrl = fakeInstagramReelPublish();
+
+ $this->publisher->publish($this->post);
+
+ Http::assertSent(fn (Request $request): bool => $request->url() === $containerUrl
+ && data_get($request->data(), 'cover_url') === null
+ && data_get($request->data(), 'thumb_offset') === 1500);
+});
+
+test('a feed video keeps its cover frame, since only a reel takes a cover image', function () {
+ $this->post->update(['content_type' => ContentType::InstagramFeed, 'media' => [instagramVideoWithCover([])]]);
+ $containerUrl = fakeInstagramReelPublish();
+
+ $this->publisher->publish($this->post);
+
+ Http::assertSent(fn (Request $request): bool => $request->url() === $containerUrl
+ && data_get($request->data(), 'cover_url') === null
+ && data_get($request->data(), 'thumb_offset') === 1500);
+});
+
test('instagram carousel video child sends its cover frame as thumb_offset', function () {
$this->post->update([
'media' => [
diff --git a/tests/fixtures/single-line-copy.php b/tests/fixtures/single-line-copy.php
index 1c1ce52c2..2a16bd5ad 100644
--- a/tests/fixtures/single-line-copy.php
+++ b/tests/fixtures/single-line-copy.php
@@ -140,6 +140,10 @@ return [
'posts.composer.media_editor.tags_move' => 11,
'posts.composer.media_editor.tags_move_pill' => 25,
'posts.composer.media_editor.tags_tab' => 10,
+ 'posts.composer.media_editor.thumbnail_image_replace' => 16,
+ 'posts.composer.media_editor.thumbnail_image_upload' => 19,
+ 'posts.composer.media_editor.thumbnail_source_frame' => 17,
+ 'posts.composer.media_editor.thumbnail_source_image' => 11,
'posts.composer.media_editor.thumbnail_tab' => 10,
'posts.composer.schedule_picker.done' => 8,
'posts.composer.schedule_picker.more_actions' => 16,
@@ -210,6 +214,7 @@ return [
'posts.publish.actions.queue_setup.not_now' => 11,
'posts.publish.actions.share_link' => 29,
'posts.publish.deleted_on_network.badge' => 10,
+ 'posts.publish.youtube_thumbnail_warning.badge' => 9,
'posts.publish.in_google_review' => 28,
'posts.publish.no_time' => 13,
'posts.publish.pending_slot.next' => 14,