Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Align content-type media caps with official API limits and enforce them server-side (#353)
Paulo Castellanoe28f42d02824
diff --git a/app/Actions/Post/AttachExistingAsset.php b/app/Actions/Post/AttachExistingAsset.phpindex 5e728b52c..15522ff89 100644--- a/app/Actions/Post/AttachExistingAsset.php+++ b/app/Actions/Post/AttachExistingAsset.php@@ -5,6 +5,7 @@ declare(strict_types=1);namespace App\Actions\Post;use App\Actions\Media\FindWorkspaceAsset;+use App\Dto\MediaItem;use App\Models\Media;use App\Models\Post;use App\Support\PostStatusRules;@@ -63,37 +64,9 @@ class AttachExistingAsset}$fresh->update([- 'media' => collect($fresh->media ?? [])->push(self::snapshot($asset, $alt))->all(),+ 'media' => collect($fresh->media ?? [])->push(MediaItem::fromMedia($asset, $alt)->toArray())->all(),]);$post->setRawAttributes($fresh->getAttributes(), true);});}-- /**- * @return array<string, mixed>- */- private static function snapshot(Media $media, ?string $alt): array- {- $item = [- 'id' => $media->id,- 'path' => $media->path,- 'url' => $media->url,- 'type' => $media->type->value,- 'mime_type' => $media->mime_type,- 'original_filename' => $media->original_filename,- 'size' => $media->size,- ];-- $meta = is_array($media->meta) ? $media->meta : [];-- if (filled($alt) && $media->isImage()) {- $meta['alt_text'] = $alt;- }-- if ($meta !== []) {- $item['meta'] = $meta;- }-- return $item;- }}diff --git a/app/Dto/MediaItem.php b/app/Dto/MediaItem.phpindex dbb2664c2..542fad41e 100644--- a/app/Dto/MediaItem.php+++ b/app/Dto/MediaItem.php@@ -7,6 +7,7 @@ namespace App\Dto;use App\Enums\Media\Source;use App\Enums\Media\Type;use App\Enums\SocialAccount\Platform;+use App\Models\Media;class MediaItem{@@ -23,21 +24,82 @@ class MediaItempublic readonly ?Source $source = null,public readonly ?array $source_meta = null,public readonly ?array $meta = null,+ public readonly ?Type $type = null,+ public readonly ?int $size = null,) {}+ /**+ * The item to store in `posts.media` for an asset. Carries `meta` so the+ * publish-time checks can read the measured video duration; alt text only+ * applies to images.+ */+ public static function fromMedia(Media $media, ?string $alt = null): self+ {+ $meta = $media->meta ?? [];++ if (filled($alt) && $media->isImage()) {+ $meta['alt_text'] = $alt;+ }++ return new self(+ id: $media->id,+ path: $media->path,+ url: $media->url,+ mime_type: $media->mime_type,+ original_filename: $media->original_filename,+ meta: $meta ?: null,+ type: $media->type,+ size: $media->size,+ );+ }++ /**+ * The stored `posts.media` shape — the same keys the editor keeps from a+ * MediaResource response, so every attach flow writes the same item.+ *+ * @return array<string, mixed>+ */+ public function toArray(): array+ {+ return [+ 'id' => $this->id,+ 'path' => $this->path,+ 'url' => $this->url,+ 'type' => $this->type?->value,+ 'mime_type' => $this->mime_type,+ 'original_filename' => $this->original_filename,+ 'size' => $this->size,+ ...array_filter([+ 'meta' => $this->meta,+ 'source' => $this->source?->value,+ 'source_meta' => $this->source_meta,+ ]),+ ];+ }+public function isVideo(): bool{- return Type::classify($this->mime_type, $this->path) === Type::Video;+ return $this->kind() === Type::Video;}public function isImage(): bool{- return Type::classify($this->mime_type, $this->path) === Type::Image;+ return $this->kind() === Type::Image;}public function isDocument(): bool{- return Type::classify($this->mime_type, $this->path) === Type::Document;+ return $this->kind() === Type::Document;+ }++ /**+ * The stored `type` wins, like `typeOf()` in ContentTypeCompatibleWithMedia+ * and `classify()` in mediaType.ts; items saved before it existed classify+ * by MIME, then by path.+ */+ private function kind(): ?Type+ {+ return $this->type ?? Type::classify($this->mime_type, $this->path);}/**@@ -99,27 +161,15 @@ class MediaItempublic static function fromArray(array $data): self{$path = data_get($data, 'path', '');- $mimeType = data_get($data, 'mime_type');-- if (! $mimeType && $path) {- $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));- $mimeType = match ($extension) {- 'jpg', 'jpeg' => 'image/jpeg',- 'png' => 'image/png',- 'gif' => 'image/gif',- 'webp' => 'image/webp',- 'mp4' => 'video/mp4',- 'mov' => 'video/quicktime',- 'pdf' => 'application/pdf',- default => null,- };- }+ $mimeType = data_get($data, 'mime_type') ?: Type::mimeTypeFromExtension(Type::extensionOf($path));$sourceValue = data_get($data, 'source');$source = is_string($sourceValue) ? Source::tryFrom($sourceValue) : null;$sourceMeta = data_get($data, 'source_meta');$meta = data_get($data, 'meta');+ $type = data_get($data, 'type');+ $size = data_get($data, 'size');return new self(id: (string) data_get($data, 'id', ''),@@ -130,6 +180,8 @@ class MediaItemsource: $source,source_meta: is_array($sourceMeta) ? $sourceMeta : null,meta: is_array($meta) ? $meta : null,+ type: is_string($type) ? Type::tryFrom($type) : null,+ size: is_numeric($size) ? (int) $size : null,);}}diff --git a/app/Enums/Media/Type.php b/app/Enums/Media/Type.phpindex 54074aca8..b6766bcc2 100644--- a/app/Enums/Media/Type.php+++ b/app/Enums/Media/Type.php@@ -4,20 +4,22 @@ declare(strict_types=1);namespace App\Enums\Media;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\File;+use Illuminate\Support\Str;+use Symfony\Component\Mime\MimeTypes;+enum Type: string{case Image = 'image';case Video = 'video';case Document = 'document';- public function label(): string- {- return match ($this) {- self::Image => 'Imagem',- self::Video => 'Vídeo',- self::Document => 'Documento',- };- }+ private const GIF_MIME = 'image/gif';++ private const MOV_MIME = 'video/quicktime';++ private const PDF_MIME = 'application/pdf';/*** Allow-list of MIME types we accept on upload / URL fetch.@@ -28,10 +30,10 @@ enum Type: string* if PHP reports `video/quicktime`. Accepting MOV avoids forcing* iPhone users to transcode before uploading.*- * WebM is rejected: X / IG / TikTok / FB / Pinterest / Bluesky /- * Threads all reject the Matroska + VP8/VP9 stack. Without- * server-side transcoding, accepting WebM would just produce- * platform-specific publish failures down the line.+ * WebM is rejected: X / IG / FB / Pinterest / Threads refuse the+ * Matroska + VP8/VP9 stack outright, and only TikTok and Bluesky+ * would transcode it. Without server-side transcoding, accepting+ * WebM would just produce platform-specific publish failures.** Document accepts PDF only — the swipeable LinkedIn document* (carousel) format. PPTX/DOCX are also valid LinkedIn documents@@ -43,9 +45,9 @@ enum Type: stringpublic function allowedMimeTypes(): array{return match ($this) {- self::Image => ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],- self::Video => ['video/mp4', 'video/quicktime'],- self::Document => ['application/pdf'],+ self::Image => ['image/jpeg', 'image/png', self::GIF_MIME, 'image/webp'],+ self::Video => ['video/mp4', self::MOV_MIME],+ self::Document => [self::PDF_MIME],};}@@ -85,13 +87,7 @@ enum Type: string*/public static function fromMime(string $mime): ?self{- foreach (self::cases() as $type) {- if (in_array($mime, $type->allowedMimeTypes(), true)) {- return $type;- }- }-- return null;+ return array_find(self::cases(), fn (self $type) => in_array($mime, $type->allowedMimeTypes(), true));}/**@@ -103,40 +99,101 @@ enum Type: string*/public static function classify(?string $mimeType, ?string $path = null): ?self{- if (filled($mimeType)) {- return match (true) {- str_starts_with($mimeType, 'image/') => self::Image,- str_starts_with($mimeType, 'video/') => self::Video,- $mimeType === 'application/pdf' => self::Document,- default => null,- };- }+ $mimeType = self::normalizeMime($mimeType);- return self::fromExtension($path ? pathinfo($path, PATHINFO_EXTENSION) : null);+ return $mimeType === ''+ ? self::fromExtension(self::extensionOf($path))+ : self::owner($mimeType);}/**- * Classify by filename extension. Broader than extensions() (the upload- * allow-list) so already-stored files in legacy formats still resolve.+ * Classify by filename extension. Broader than extensions(): any format the+ * MIME registry knows as image/*, video/* or PDF resolves, so legacy files+ * already on disk (heic, mkv, avi, ...) still classify. The registry's order+ * decides: `.pdf` lists `application/pdf` before `image/pdf`, so it is a+ * Document, not an Image.*/public static function fromExtension(?string $extension): ?self{- $extension = strtolower((string) $extension);+ return collect(self::registeredMimeTypes($extension))->map(self::owner(...))->filter()->first();+ }- return match (true) {- in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif'], true) => self::Image,- in_array($extension, ['mp4', 'mov', 'avi', 'wmv', 'webm', 'mkv', 'm4v'], true) => self::Video,- $extension === 'pdf' => self::Document,- default => null,+ /**+ * The MIME we accept on upload for a filename extension, or null when the+ * extension maps to nothing in the allow-list.+ */+ public static function mimeTypeFromExtension(?string $extension): ?string+ {+ return Arr::first(self::registeredMimeTypes($extension), fn (string $mimeType) => self::fromMime($mimeType) !== null);+ }++ /**+ * Image and video own their MIME family (`image/*`, `video/*`), so the+ * family is the backing value. Document is `application/pdf` alone.+ * A string without a slash is not a MIME and owns nothing.+ */+ private function ownsMime(string $mimeType): bool+ {+ return match ($this) {+ self::Document => $mimeType === self::PDF_MIME,+ default => Str::is("{$this->value}/*", $mimeType),};}+ private static function owner(string $mimeType): ?self+ {+ return array_find(self::cases(), fn (self $type) => $type->ownsMime($mimeType));+ }++ /**+ * Every MIME the registry lists for an extension — `.mp4` comes back as+ * `application/mp4` first and `video/mp4` second, which is why callers+ * pick from the whole list instead of trusting the first entry.+ *+ * @return array<int, string>+ */+ private static function registeredMimeTypes(?string $extension): array+ {+ return MimeTypes::getDefault()->getMimeTypes(Str::lower((string) $extension));+ }+/*** Whether the MIME is an animated GIF — several publishers handle it* specially (skipped from optimization, or posted as video).*/public static function isGif(?string $mimeType): bool{- return $mimeType === 'image/gif';+ return self::normalizeMime($mimeType) === self::GIF_MIME;+ }++ public static function isMov(?string $mimeType, ?string $path = null): bool+ {+ return self::normalizeMime($mimeType) === self::MOV_MIME || self::extensionOf($path) === 'mov';+ }++ /**+ * Lower-cased extension of a filename, storage key or URL. Mirrors `pathOf`+ * in mediaType.ts: only an absolute URL is parsed (to drop `?query` and+ * `#hash`); a bare filename is taken as-is, so `Photo #3.jpg` keeps its+ * extension.+ */+ public static function extensionOf(?string $path): string+ {+ $path = (string) $path;++ if (Str::contains($path, '://')) {+ $path = (string) parse_url($path, PHP_URL_PATH);+ }++ return Str::lower(File::extension($path));+ }++ /**+ * Lower-cased `type/subtype` with any `; codecs=...` parameter dropped, so+ * comparisons are exact. Mirrors `normalizeMime` in mediaType.ts.+ */+ private static function normalizeMime(?string $mimeType): string+ {+ return Str::of((string) $mimeType)->before(';')->trim()->lower()->value();}}diff --git a/app/Enums/PostPlatform/ContentType.php b/app/Enums/PostPlatform/ContentType.phpindex 0d56e74cd..5b293a2c2 100644--- a/app/Enums/PostPlatform/ContentType.php+++ b/app/Enums/PostPlatform/ContentType.php@@ -182,8 +182,9 @@ enum ContentType: string/*** Maximum video duration in seconds for this content type, when the- * platform publishes a hard cap via API. Null when unlimited, unknown,- * or enforced dynamically (e.g. TikTok creator_info).+ * platform publishes a hard cap via API. Null when unlimited or unknown.+ * TikTok's `creator_info` may lower the 10 min ceiling per account; the+ * editor reads it per account and TikTok rejects longer uploads itself.** Single source of truth for web (via Inertia shared props), REST API,* and MCP content-type listings.@@ -200,9 +201,10 @@ enum ContentType: stringself::LinkedInPost, self::LinkedInPagePost => 10 * 60,self::YouTubeShort => 3 * 60,self::PinterestVideoPin => 15 * 60,- self::XPost => 140,+ self::XPost => 20 * 60,self::ThreadsPost => 5 * 60,- self::BlueskyPost => 60,+ self::BlueskyPost => 10 * 60,+ self::TikTokVideo => 10 * 60,default => null,};}@@ -231,10 +233,24 @@ enum ContentType: string};}+ /**+ * Every network we publish to accepts QuickTime/MOV. Bluesky's stored+ * embed lexicon is `video/mp4`, but its video service accepts MOV+ * (`video/quicktime`) and transcodes it — same list as the official app.+ */+ public function acceptsMov(): bool+ {+ return true;+ }+/*** Per-type image size cap in bytes, capped at the global upload hard limit* (trypost.media.max_size_mb.image). Null when images are not accepted or* the platform has no tighter editor-side limit than that hard cap.+ * Telegram is the URL-publish limit (5 MB), not the multipart one.+ * Bluesky's blob limit is 2 MB, but BlueskyPublisher re-encodes every+ * non-GIF image under it, so capping the original here would only block+ * posts that publish fine.*/public function maxImageBytes(): ?int{@@ -245,7 +261,10 @@ enum ContentType: stringself::PinterestPin, self::PinterestCarousel => self::bytesFromMb(20),self::XPost => self::bytesFromMb(5),self::ThreadsPost => self::bytesFromMb(8),+ self::TikTokPhoto => self::bytesFromMb(20),self::MastodonPost => self::bytesFromMb(10),+ self::DiscordMessage => self::bytesFromMb(20),+ self::TelegramPost => self::bytesFromMb(5),default => null,};@@ -256,21 +275,26 @@ enum ContentType: string* Per-type video size cap in bytes, capped at the global upload hard limit* (trypost.media.max_size_mb.video). Null when videos are not accepted or* the platform has no tighter editor-side limit than that hard cap.+ * X is the `tweet_video` default entitlement (Premium allows more);+ * Telegram is the URL-publish limit (20 MB), not the multipart one.*/public function maxVideoBytes(): ?int{$bytes = match ($this) {self::InstagramFeed, self::InstagramStory => self::bytesFromMb(100),- self::InstagramReel => self::bytesFromGb(1),+ self::InstagramReel => self::bytesFromMb(300),self::FacebookPost => self::bytesFromGb(10),self::FacebookReel, self::FacebookStory => self::bytesFromGb(1),self::LinkedInPost, self::LinkedInPagePost => self::bytesFromGb(5),self::YouTubeShort => self::bytesFromGb(256),self::PinterestVideoPin => self::bytesFromGb(2),- self::XPost => self::bytesFromMb(512),+ self::XPost => self::bytesFromGb(8),self::ThreadsPost => self::bytesFromGb(1),- self::BlueskyPost => self::bytesFromMb(100),+ self::BlueskyPost => self::bytesFromDecimalMb(300),+ self::TikTokVideo => self::bytesFromGb(4),self::MastodonPost => self::bytesFromMb(40),+ self::DiscordMessage => self::bytesFromMb(20),+ self::TelegramPost => self::bytesFromMb(20),default => null,};@@ -327,6 +351,7 @@ enum ContentType: string* accept_documents: bool,* requires_media: bool,* accepts_gif: bool,+ * accepts_mov: bool,* forbids_mixed_media: bool,* max_image_bytes: int|null,* max_video_bytes: int|null,@@ -350,6 +375,7 @@ enum ContentType: string'accept_documents' => $this->supportsDocument(),'requires_media' => $this->requiresMedia(),'accepts_gif' => $this->acceptsGif(),+ 'accepts_mov' => $this->acceptsMov(),'forbids_mixed_media' => ! $this->supportsMixedMedia(),'max_image_bytes' => $this->maxImageBytes(),'max_video_bytes' => $this->maxVideoBytes(),@@ -376,6 +402,7 @@ enum ContentType: string* accept_videos: bool,* accept_documents: bool,* accepts_gif: bool,+ * accepts_mov: bool,* forbids_mixed_media: bool,* max_video_duration_sec: int|null,* max_image_bytes: int|null,@@ -396,6 +423,7 @@ enum ContentType: string'accept_videos' => $this->supportsVideo(),'accept_documents' => $this->supportsDocument(),'accepts_gif' => $this->acceptsGif(),+ 'accepts_mov' => $this->acceptsMov(),'forbids_mixed_media' => ! $this->supportsMixedMedia(),'max_video_duration_sec' => $this->maxVideoDurationSec(),'max_image_bytes' => $this->maxImageBytes(),@@ -409,13 +437,9 @@ enum ContentType: string*/public static function mediaRulesForFrontend(): array{- $rules = [];-- foreach (self::cases() as $type) {- $rules[$type->value] = $type->mediaRules();- }-- return $rules;+ return collect(self::cases())+ ->mapWithKeys(fn (self $type) => [$type->value => $type->mediaRules()])+ ->all();}private static function bytesFromMb(int $megabytes): int@@ -428,6 +452,14 @@ enum ContentType: stringreturn $gigabytes * 1024 * 1024 * 1024;}+ /**+ * For caps declared in plain decimal bytes (Bluesky's lexicon), not MiB.+ */+ private static function bytesFromDecimalMb(int $megabytes): int+ {+ return $megabytes * 1_000_000;+ }+/*** Never advertise a soft platform ceiling above what trypost.media allows* on upload (web / API / MCP signed URL).diff --git a/app/Http/Controllers/Api/PostController.php b/app/Http/Controllers/Api/PostController.phpindex d7724ce38..2bc0eb071 100644--- a/app/Http/Controllers/Api/PostController.php+++ b/app/Http/Controllers/Api/PostController.php@@ -9,6 +9,7 @@ use App\Actions\Post\CreatePost;use App\Actions\Post\DeletePost;use App\Actions\Post\HostInlineMedia;use App\Actions\Post\UpdatePost;+use App\Dto\MediaItem;use App\Enums\Media\Type as MediaType;use App\Enums\Post\Action as PostAction;use App\Enums\Post\CreatedVia;@@ -134,14 +135,7 @@ class PostController extends Controller$media = $post->workspace->addMedia($file, 'assets');- $post->appendMedia([[- 'id' => $media->id,- 'path' => $media->path,- 'url' => $media->url,- 'type' => $media->type,- 'mime_type' => $media->mime_type,- 'original_filename' => $media->original_filename,- ]]);+ $post->appendMedia([MediaItem::fromMedia($media)->toArray()]);$post->refresh()->load(['postPlatforms.socialAccount', 'labels']);diff --git a/app/Http/Controllers/App/AssetController.php b/app/Http/Controllers/App/AssetController.phpindex e88a2dd33..67aee0dc7 100644--- a/app/Http/Controllers/App/AssetController.php+++ b/app/Http/Controllers/App/AssetController.php@@ -22,6 +22,7 @@ use Inertia\Inertia;use Inertia\Response;use RuntimeException;use Symfony\Component\HttpFoundation\Response as SymfonyResponse;+use Symfony\Component\HttpFoundation\StreamedResponse;class AssetController extends Controller{@@ -84,6 +85,7 @@ class AssetController extends Controller(int) $request->validated('range_end'),(int) $request->validated('total_size'),(string) $request->validated('upload_id'),+ $request->duration(),)->toResponse();}@@ -150,7 +152,27 @@ class AssetController extends Controllerreturn new MediaResource($media);}+ public function download(Request $request, Media $media): StreamedResponse+ {+ $this->authorizeWorkspaceAsset($request, $media);++ $filename = filled($media->original_filename)+ ? $media->original_filename+ : basename($media->path);++ return Storage::download($media->path, $filename);+ }+public function destroy(Request $request, Media $media): RedirectResponse+ {+ $this->authorizeWorkspaceAsset($request, $media);++ $media->delete();++ return back();+ }++ private function authorizeWorkspaceAsset(Request $request, Media $media): void{$workspace = $request->user()->currentWorkspace;@@ -159,9 +181,5 @@ class AssetController extends Controllerif ($media->mediable_type !== $workspace->getMorphClass() || $media->mediable_id !== $workspace->id) {abort(SymfonyResponse::HTTP_FORBIDDEN);}-- $media->delete();-- return back();}}diff --git a/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php b/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.phpindex d8740a55a..bebe38b75 100644--- a/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php+++ b/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php@@ -30,6 +30,7 @@ class StoreChunkedAssetRequest extends FormRequest'total_size' => $parsed[2] ?? null,'file_name' => strtolower(rawurldecode((string) $this->header('X-File-Name', 'upload'))),'upload_id' => $this->header('X-Upload-Id'),+ 'duration' => $this->header('X-Media-Duration'),]);}@@ -49,9 +50,16 @@ class StoreChunkedAssetRequest extends FormRequest'total_size' => ['required', 'integer', 'min:1', 'max:'.MediaType::Video->maxSizeInBytes()],'file_name' => ['required', 'string', 'ends_with:'.implode(',', $allowedSuffixes)],'upload_id' => ['required', 'string', 'uuid'],+ // Capped at a day so `1e999` (INF, which JSON cannot encode) never reaches the meta column.+ 'duration' => ['nullable', 'numeric', 'min:0', 'max:86400'],];}+ public function duration(): ?float+ {+ return transform($this->validated('duration'), fn (mixed $seconds) => (float) $seconds);+ }+/*** @return array<string, string>*/diff --git a/app/Mcp/Tools/Asset/AttachExistingAssetTool.php b/app/Mcp/Tools/Asset/AttachExistingAssetTool.phpindex 5d2df89ce..76b043127 100644--- a/app/Mcp/Tools/Asset/AttachExistingAssetTool.php+++ b/app/Mcp/Tools/Asset/AttachExistingAssetTool.php@@ -18,7 +18,7 @@ use Laravel\Mcp\ResponseFactory;use Laravel\Mcp\Server\Attributes\Description;use Laravel\Mcp\Server\Tool;-#[Description('Reuse an existing Asset Library item on a post in the current workspace (the workspace bound to this MCP token). Does not upload a new file — for new media use request-media-upload-tool then attach-media-from-upload-tool, or attach-media-from-url-tool. Discover ids with list-assets-tool or get-asset-tool. The post must be draft or scheduled; published, partially published, failed, and publishing posts are rejected. The asset must already be in this workspace library. The asset type must be accepted by every enabled platform on the post (e.g. TikTok-only posts reject images). Repeating the same post_id and asset_id does not duplicate the media or change alt. Optional alt overrides image alt text only (ignored for video/document), maximum 2000 characters; omit to keep the library item\'s existing alt_text. Requires permission to update the post. Returns the updated post (same shape as other post tools).')]+#[Description('Reuse an existing Asset Library item on a post in the current workspace (the workspace bound to this MCP token). Does not upload a new file — for new media use request-media-upload-tool then attach-media-from-upload-tool, or attach-media-from-url-tool. Discover ids with list-assets-tool or get-asset-tool. The post must be draft or scheduled; published, partially published, failed, and publishing posts are rejected. The asset must already be in this workspace library. The asset type must be accepted by every enabled platform on the post (e.g. TikTok-only posts reject images); per-network size, video duration, GIF and MOV caps (see list-content-types-tool) are enforced when the post is scheduled or published. Repeating the same post_id and asset_id does not duplicate the media or change alt. Optional alt overrides image alt text only (ignored for video/document), maximum 2000 characters; omit to keep the library item\'s existing alt_text. Requires permission to update the post. Returns the updated post (same shape as other post tools).')]class AttachExistingAssetTool extends Tool{use AuthorizesMcpTool;diff --git a/app/Mcp/Tools/Platform/ListContentTypesTool.php b/app/Mcp/Tools/Platform/ListContentTypesTool.phpindex fb054066c..ab348e92f 100644--- a/app/Mcp/Tools/Platform/ListContentTypesTool.php+++ b/app/Mcp/Tools/Platform/ListContentTypesTool.php@@ -14,7 +14,7 @@ use Laravel\Mcp\Server\Tool;use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[IsReadOnly]-#[Description('List the valid content_types per social platform plus their constraints (max/min media count, whether media is required, accept_images/videos/documents/gif, forbids_mixed_media, max video duration in seconds, per-type max image/video/document bytes, default content_type). Use before create-post-tool / update-post-tool to know which content_type to set.')]+#[Description('List the valid content_types per social platform plus their media constraints: 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, and the platform default_content_type. These caps mirror each network\'s official limits and are enforced by update-post-tool (status "scheduled") and publish-post-tool: a post whose media exceeds the cap of any enabled content_type is rejected with a per-platform error. Drafts are never blocked. Call this before attaching media or choosing a content_type.')]class ListContentTypesTool extends Tool{public function handle(Request $request): ResponseFactorydiff --git a/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php b/app/Mcp/Tools/Post/AttachMediaFromUploadTool.phpindex 69de8dd7d..12341d78a 100644--- a/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php+++ b/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Mcp\Tools\Post;+use App\Dto\MediaItem;use App\Http\Resources\Api\PostResource;use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\Media;@@ -17,7 +18,7 @@ use Laravel\Mcp\ResponseFactory;use Laravel\Mcp\Server\Attributes\Description;use Laravel\Mcp\Server\Tool;-#[Description('Attach a Media uploaded via RequestMediaUploadTool to a post. The upload_token is the value returned by RequestMediaUploadTool; the Media is resolved by that token within the current workspace, then appended to the post.')]+#[Description('Attach a Media uploaded via request-media-upload-tool to a post. The upload_token is the value returned by request-media-upload-tool; the Media is resolved by that token within the current workspace, then appended to the post. The media type must be accepted by the platforms enabled on the post. Size, video duration, GIF and MOV caps per content_type (see list-content-types-tool) are checked when the post is scheduled or published, not here.')]class AttachMediaFromUploadTool extends Tool{use AuthorizesMcpTool;@@ -58,20 +59,7 @@ class AttachMediaFromUploadTool extends Toolreturn Response::error('No enabled platform on this post accepts this media type.');}- $item = [- 'id' => $media->id,- 'path' => $media->path,- 'url' => $media->url,- 'type' => $media->type,- 'mime_type' => $media->mime_type,- 'original_filename' => $media->original_filename,- ];-- if (($alt = data_get($validated, 'alt')) !== null && $media->isImage()) {- $item['meta'] = ['alt_text' => $alt];- }-- $post->appendMedia([$item]);+ $post->appendMedia([MediaItem::fromMedia($media, data_get($validated, 'alt'))->toArray()]);$post->refresh()->load(['postPlatforms.socialAccount', 'labels']);diff --git a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.phpindex 73589c3db..c5b483cbe 100644--- a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php+++ b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php@@ -16,7 +16,7 @@ use Laravel\Mcp\ResponseFactory;use Laravel\Mcp\Server\Attributes\Description;use Laravel\Mcp\Server\Tool;-#[Description('Download images, videos, or PDF documents from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. Allowed types are intersected with the platforms enabled on the post (e.g. nothing accepted if no platform supports the media type).')]+#[Description('Download images, videos, or PDF documents from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. Allowed types are intersected with the platforms enabled on the post (e.g. nothing accepted if no platform supports the media type). Video duration is measured on the server. Per-network size, duration, GIF and MOV caps (see list-content-types-tool) are enforced when the post is scheduled or published.')]class AttachMediaFromUrlTool extends Tool{use AuthorizesMcpTool;@@ -65,7 +65,7 @@ class AttachMediaFromUrlTool extends Tool'alt' => $u->string()->description('Optional accessibility alt text for the image (ignored for video/PDF, which have no alt text).'),]))->required()- ->description('Media to attach. Max 10 per call. Per-type size caps match config trypost.media (image/video/document). Allowed types: image/jpeg, image/png, image/gif, image/webp, video/mp4, video/quicktime, application/pdf.'),+ ->description('Media to attach. Max 10 per call. Allowed types: image/jpeg, image/png, image/gif, image/webp, video/mp4, video/quicktime, application/pdf. The workspace-wide per-type size ceilings apply on download; stricter per-network caps apply at schedule/publish.'),];}}diff --git a/app/Mcp/Tools/Post/PublishPostTool.php b/app/Mcp/Tools/Post/PublishPostTool.phpindex fb038870f..620041310 100644--- a/app/Mcp/Tools/Post/PublishPostTool.php+++ b/app/Mcp/Tools/Post/PublishPostTool.php@@ -22,7 +22,7 @@ use Laravel\Mcp\Server\Tool;use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;#[IsDestructive]-#[Description('Publish a draft post — either immediately or scheduled for a future time. The post must already have at least one enabled platform. Use update-post-tool first to set content/platforms.')]+#[Description('Publish a draft post — either immediately or scheduled for a future time. The post must already have at least one enabled platform. Use update-post-tool first to set content/platforms. Before queueing, the attached media is validated against every enabled content_type (file size, video duration, GIF, MOV — see list-content-types-tool); a cap violation returns a per-platform error and nothing is published.')]class PublishPostTool extends Tool{use AuthorizesMcpTool;diff --git a/app/Mcp/Tools/Post/RequestMediaUploadTool.php b/app/Mcp/Tools/Post/RequestMediaUploadTool.phpindex 629a83984..cd695b9fe 100644--- a/app/Mcp/Tools/Post/RequestMediaUploadTool.php+++ b/app/Mcp/Tools/Post/RequestMediaUploadTool.php@@ -17,7 +17,7 @@ use Laravel\Mcp\ResponseFactory;use Laravel\Mcp\Server\Attributes\Description;use Laravel\Mcp\Server\Tool;-#[Description('Issue a one-shot signed POST URL that lets the user upload a local file (image, video, or PDF document) directly to this workspace. Size caps match web/API media limits — see max_bytes_by_type (max_bytes is the overall ceiling, equal to the video cap). Returns an upload_token, upload_url, max_bytes, and max_bytes_by_type. Hand the URL to the user (e.g. as a curl command with `-F media=@path/to/file`) or to the MCP client. After upload, call AttachMediaFromUploadTool(post_id, upload_token) to attach the result to a post.')]+#[Description('Issue a one-shot signed POST URL that lets the user upload a local file (image, video, or PDF document) directly to this workspace. Accepted types: JPEG, PNG, GIF, WebP, MP4, MOV, PDF. Returns an upload_token, upload_url, max_bytes, and max_bytes_by_type — those are the workspace-wide ceilings (max_bytes equals the video cap); each network enforces its own, usually smaller, size / duration / format caps at schedule or publish time, so check list-content-types-tool for the post\'s enabled content_types first. Video duration is measured on the server after the upload. Hand the URL to the user (e.g. as a curl command with `-F media=@path/to/file`) or to the MCP client. After upload, call attach-media-from-upload-tool(post_id, upload_token) to attach the result to a post.')]class RequestMediaUploadTool extends Tool{use AuthorizesMcpTool;diff --git a/app/Mcp/Tools/Post/UpdatePostTool.php b/app/Mcp/Tools/Post/UpdatePostTool.phpindex 3f0ae0e62..c48885578 100644--- a/app/Mcp/Tools/Post/UpdatePostTool.php+++ b/app/Mcp/Tools/Post/UpdatePostTool.php@@ -25,7 +25,7 @@ use Laravel\Mcp\ResponseFactory;use Laravel\Mcp\Server\Attributes\Description;use Laravel\Mcp\Server\Tool;-#[Description('Update a draft post — content, media, scheduled_at, labels, and which platforms are enabled. Cannot edit a post that has already been published.')]+#[Description('Update a draft post — content, media, scheduled_at, labels, and which platforms are enabled. Cannot edit a post that has already been published. Setting status "scheduled" validates the attached media against every enabled content_type (file size, video duration, GIF, MOV — see list-content-types-tool) and fails with a per-platform error when a cap is exceeded; fix the media or switch content_type. Drafts are never blocked.')]class UpdatePostTool extends Tool{use AuthorizesMcpTool;diff --git a/app/Models/Traits/HasMedia.php b/app/Models/Traits/HasMedia.phpindex 3152b89dc..428213d08 100644--- a/app/Models/Traits/HasMedia.php+++ b/app/Models/Traits/HasMedia.php@@ -8,8 +8,10 @@ use App\Enums\Media\Type;use App\Models\Media;use App\Models\User;use App\Models\Workspace;+use App\Support\VideoDurationProbe;use Illuminate\Database\Eloquent\Relations\MorphMany;use Illuminate\Http\UploadedFile;+use Illuminate\Support\Facades\File;use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Storage;use Illuminate\Support\Str;@@ -90,6 +92,7 @@ trait HasMedia$filename = Str::uuid().'.'.$normalizedExt;$path = "medias/{$filename}";+ $meta = $this->withVideoDuration($meta, $type, $file->getPathname());Storage::put($path, $normalizedBytes);@@ -102,7 +105,7 @@ trait HasMedia'mime_type' => $normalizedMime,'size' => strlen($normalizedBytes),'order' => 0,- 'meta' => array_merge($this->getMediaMetaFromBytes($normalizedBytes, $type, $meta), $meta),+ 'meta' => [...$this->imageDimensions($normalizedBytes, $type), ...$meta],]);}@@ -117,18 +120,19 @@ trait HasMedia}// Prefer an explicit MIME (e.g. from UploadedFile after FormRequest- // validation) — mime_content_type() misclassifies empty test fakes and- // some freshly written temps as application/x-empty.- $mimeType ??= mime_content_type($filePath) ?: null;+ // validation) — sniffing misclassifies empty test fakes and some+ // freshly written temps as application/x-empty.+ $mimeType ??= File::mimeType($filePath) ?: null;if ($mimeType === null) {throw new InvalidArgumentException("Unable to determine MIME type for media file: {$filePath}");}$type = $this->getMediaType($mimeType);- $extension = pathinfo($originalFilename, PATHINFO_EXTENSION);+ $extension = File::extension($originalFilename);+ $meta = $this->withVideoDuration($meta, $type, $filePath);- $stored = $type === Type::Image->value+ $stored = $type === Type::Image? $this->storeImageFromPath($filePath, $mimeType, $type, $extension, $meta): $this->streamFileToStorage($filePath, $mimeType, $extension, $meta);@@ -194,7 +198,7 @@ trait HasMedia* @param array<string, mixed> $meta* @return array{path: string, mime_type: string, size: int, meta: array<string, mixed>}*/- private function storeImageFromPath(string $filePath, string $mimeType, string $type, string $extension, array $meta): array+ private function storeImageFromPath(string $filePath, string $mimeType, Type $type, string $extension, array $meta): array{[$bytes, $storedMime, $storedExt] = $this->normalizeImageFormat($filePath,@@ -211,7 +215,7 @@ trait HasMedia'path' => $path,'mime_type' => $storedMime,'size' => strlen($bytes),- 'meta' => array_merge($this->getMediaMetaFromBytes($bytes, $type, $meta), $meta),+ 'meta' => [...$this->imageDimensions($bytes, $type), ...$meta],];}@@ -245,10 +249,10 @@ trait HasMedia];}- private function getMediaType(string $mimeType): string+ private function getMediaType(string $mimeType): Type{- return (Type::classify($mimeType)- ?? throw new InvalidArgumentException("Unsupported media MIME type: {$mimeType}"))->value;+ return Type::classify($mimeType)+ ?? throw new InvalidArgumentException("Unsupported media MIME type: {$mimeType}");}/**@@ -261,38 +265,28 @@ trait HasMediareturn mb_scrub($filename, 'UTF-8');}- private function getMediaMeta(UploadedFile $file, string $type): array+ /**+ * @param array<string, mixed> $meta+ * @return array<string, mixed>+ */+ private function withVideoDuration(array $meta, Type $type, string $filePath): array{- $meta = [];-- if ($type === 'image') {- $imageInfo = @getimagesize($file->getPathname());- if ($imageInfo) {- $meta['width'] = $imageInfo[0];- $meta['height'] = $imageInfo[1];- }- }-- return $meta;+ return $type === Type::Video+ ? VideoDurationProbe::mergeInto($meta, VideoDurationProbe::fromFile($filePath))+ : $meta;}/**- * Extract width/height from raw image bytes (used after format normalization- * when we no longer have the original file path).+ * Pixel width / height of raw image bytes (read after format normalization,+ * when the original file path is gone); nothing for other types.+ *+ * @return array<string, int>*/- private function getMediaMetaFromBytes(string $bytes, string $type, array $clientMeta = []): array+ private function imageDimensions(string $bytes, Type $type): array{- $meta = [];-- if ($type === 'image') {- $imageInfo = @getimagesizefromstring($bytes);- if ($imageInfo) {- $meta['width'] = $imageInfo[0];- $meta['height'] = $imageInfo[1];- }- }+ $info = $type === Type::Image ? @getimagesizefromstring($bytes) : false;- return $meta;+ return $info ? ['width' => $info[0], 'height' => $info[1]] : [];}/**@@ -301,9 +295,9 @@ trait HasMedia** @return array{0: string, 1: string, 2: string} [bytes, mime_type, extension]*/- private function normalizeImageFormat(string $filePath, string $mimeType, string $type, string $originalExtension): array+ private function normalizeImageFormat(string $filePath, string $mimeType, Type $type, string $originalExtension): array{- if ($type !== 'image') {+ if ($type !== Type::Image) {return [file_get_contents($filePath), $mimeType, $originalExtension];}diff --git a/app/Rules/ContentTypeCompatibleWithMedia.php b/app/Rules/ContentTypeCompatibleWithMedia.phpindex e8fd27cf2..a172344b4 100644--- a/app/Rules/ContentTypeCompatibleWithMedia.php+++ b/app/Rules/ContentTypeCompatibleWithMedia.php@@ -10,6 +10,7 @@ use App\Models\Post;use Closure;use Illuminate\Contracts\Validation\DataAwareRule;use Illuminate\Contracts\Validation\ValidationRule;+use Illuminate\Support\Number;use Illuminate\Translation\PotentiallyTranslatedString;use Illuminate\Validation\ValidationException;@@ -70,10 +71,12 @@ class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRulepublic static function entriesForUpdate(Post $post, ?array $requestPlatforms): array{if (is_array($requestPlatforms)) {+ $stored = $post->postPlatforms()->get()->keyBy('id');+return collect($requestPlatforms)->map(fn ($platform, $index): array => ['key' => "platforms.{$index}.content_type",'content_type' => data_get($platform, 'content_type')- ?? $post->postPlatforms()->where('id', data_get($platform, 'id'))->first()?->content_type?->value,+ ?? $stored->get(data_get($platform, 'id'))?->content_type?->value,])->all();}@@ -95,21 +98,16 @@ class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRulepublic static function errorsFor(array $entries, array $media): array{$errors = [];+ $rule = new self($media);- foreach ($entries as $entry) {- $contentType = data_get($entry, 'content_type');-+ foreach ($entries as ['key' => $key, 'content_type' => $contentType]) {if ($contentType === null) {continue;}- (new self($media))->validate(- $entry['key'],- (string) $contentType,- function (string $message) use (&$errors, $entry): void {- $errors[$entry['key']] = $message;- },- );+ $rule->validate($key, $contentType, function (string $message) use (&$errors, $key): void {+ $errors[$key] = $message;+ });}return $errors;@@ -121,86 +119,223 @@ class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRulepublic function validate(string $attribute, mixed $value, Closure $fail): void{$contentType = ContentType::tryFrom((string) $value);+if (! $contentType) {return;}- // Use the request's media when present; otherwise fall back to the- // post's stored media so partial publish/schedule updates still validate.- $media = array_key_exists('media', $this->data)- ? (array) data_get($this->data, 'media', [])- : (array) ($this->fallbackMedia ?? []);- $count = count($media);+ $media = $this->media();- if ($contentType->requiresMedia() && $count === 0) {- $fail("{$contentType->label()} requires at least one media file.");+ if ($media === []) {+ if ($contentType->requiresMedia()) {+ $fail(trans('posts.form.warnings.requires_media'));+ }return;}- if ($count === 0) {+ // One message per platform, like `firstWarning` in useMedia.ts: a kind violation+ // ("does not accept GIF") is the root cause, so a size violation on the same+ // item must not overwrite it in errorsFor().+ if ($this->failOnKindRules($contentType, $media, $fail)) {return;}- $hasImage = collect($media)->contains(fn ($item) => $this->isImage((array) $item));- $hasVideo = collect($media)->contains(fn ($item) => $this->isVideo((array) $item));- $hasDocument = collect($media)->contains(fn ($item) => $this->isDocument((array) $item));+ $this->failOnSizeAndDurationCaps($contentType, $media, $fail);+ }- if ($hasImage && ! $contentType->supportsImage()) {- $fail("{$contentType->label()} does not support images.");- }+ /**+ * Request `media` when the key is present (including an empty list);+ * otherwise the stored fallback so a partial publish still validates.+ *+ * @return array<int, array<string, mixed>>+ */+ private function media(): array+ {+ return collect(data_get($this->data, 'media', $this->fallbackMedia))+ ->map(fn (mixed $item): array => (array) $item)+ ->all();+ }- if ($hasVideo && ! $contentType->supportsVideo()) {- $fail("{$contentType->label()} does not support videos.");- }+ /**+ * Reports the first kind violation, in the editor's priority order.+ *+ * @param array<int, array<string, mixed>> $media+ * @param Closure(string, ?string=): PotentiallyTranslatedString $fail+ * @return bool Whether a violation was reported.+ */+ private function failOnKindRules(ContentType $contentType, array $media, Closure $fail): bool+ {+ $items = collect($media);+ $types = $items->map($this->typeOf(...));+ $hasImage = $types->contains(MediaType::Image);+ $hasVideo = $types->contains(MediaType::Video);+ $hasDocument = $types->contains(MediaType::Document);- if ($hasDocument && ! $contentType->supportsDocument()) {- $fail("{$contentType->label()} does not support PDF documents.");- }+ $violations = [+ 'no_video_allowed' => $hasVideo && ! $contentType->supportsVideo(),+ 'no_image_allowed' => $hasImage && ! $contentType->supportsImage(),+ 'no_document_allowed' => $hasDocument && ! $contentType->supportsDocument(),+ 'no_mixed_media' => $hasImage && $hasVideo && ! $contentType->supportsMixedMedia(),+ 'document_not_alone' => $hasDocument && $items->count() > 1,+ 'gif_not_allowed' => $items->contains($this->isGif(...)) && ! $contentType->acceptsGif(),+ 'mov_not_allowed' => $items->contains($this->isMov(...)) && ! $contentType->acceptsMov(),+ ];++ $key = array_find_key($violations, fn (bool $failed): bool => $failed);- // A PDF document is always published on its own (LinkedIn document post).- if ($hasDocument && $count > 1) {- $fail('A PDF document must be the only attachment.');+ if ($key === null) {+ return false;}- if ($hasImage && $hasVideo && ! $contentType->supportsMixedMedia()) {- $fail("{$contentType->label()} can't combine an image and a video in the same post.");+ $fail(trans("posts.form.warnings.{$key}"));++ return true;+ }++ /**+ * Server-side mirror of the editor's size / duration checks, so API and MCP+ * clients get the same early warning the editor shows. `size` and+ * `meta.duration` are the item's own values (written by the server on upload,+ * resubmitted by the client); an item without them is not checked. This is a+ * courtesy check, not a security boundary — the network enforces its own caps.+ *+ * @param array<int, array<string, mixed>> $media+ * @param Closure(string, ?string=): PotentiallyTranslatedString $fail+ */+ private function failOnSizeAndDurationCaps(ContentType $contentType, array $media, Closure $fail): void+ {+ $maxDuration = $contentType->maxVideoDurationSec();++ foreach ($media as $item) {+ $size = (int) data_get($item, 'size', 0);+ [$key, $max] = $this->byteCap($contentType, $item);++ if ($max !== null && $size > $max) {+ $fail(trans("posts.form.warnings.{$key}", [+ 'max' => $this->formatBytes($max, $max),+ 'current' => $this->formatBytes($size, $max, 1),+ ]));++ return;+ }++ $duration = data_get($item, 'meta.duration');++ if ($maxDuration !== null && is_numeric($duration) && $duration > $maxDuration && $this->typeOf($item) === MediaType::Video) {+ $fail(trans('posts.form.warnings.video_too_long', [+ 'max' => $this->formatDuration($maxDuration),+ 'current' => $this->formatDuration((int) ceil((float) $duration)),+ ]));++ return;+ }}}/**+ * The cap an item is measured against; none when nothing identifies the item.+ ** @param array<string, mixed> $item+ * @return array{0: string|null, 1: int|null}+ */+ private function byteCap(ContentType $contentType, array $item): array+ {+ return match ($this->typeOf($item)) {+ MediaType::Document => ['document_too_large', $contentType->maxDocumentBytes()],+ MediaType::Video => ['video_too_large', $contentType->maxVideoBytes()],+ MediaType::Image => ['image_too_large', $contentType->maxImageBytes()],+ null => [null, null],+ };+ }++ /**+ * Mirrors `formatBytes` in useMedia.ts: a cap declared in decimal megabytes+ * (Bluesky) renders both numbers in decimal units — "300 MB", not "286 MB".+ */+ private function formatBytes(int $bytes, int $cap, int $precision = 0): string+ {+ return $this->isDecimalCap($cap)+ ? $this->formatDecimalBytes($bytes, $precision)+ : Number::fileSize($bytes, $precision);+ }++ /**+ * A cap built with ContentType::bytesFromDecimalMb(): a whole number of+ * megabytes that is not also a whole number of mebibytes.+ */+ private function isDecimalCap(int $cap): bool+ {+ return $cap % 1_000_000 === 0 && $cap % (1024 * 1024) !== 0;+ }++ private function formatDecimalBytes(int $bytes, int $precision): string+ {+ if ($bytes < 1_000) {+ return "{$bytes} B";+ }++ [$divisor, $unit] = match (true) {+ $bytes >= 1_000_000_000 => [1_000_000_000, 'GB'],+ $bytes >= 1_000_000 => [1_000_000, 'MB'],+ default => [1_000, 'KB'],+ };++ $value = Number::format($bytes / $divisor, $precision);++ return "{$value} {$unit}";+ }++ /**+ * Mirrors `formatDurationWords` in date.ts: "45s", "5min", "5min 30s".*/- private function isImage(array $item): bool+ private function formatDuration(int $seconds): string{- return $this->isType($item, MediaType::Image);+ $minutes = intdiv($seconds, 60);+ $rest = $seconds % 60;++ return match (true) {+ $minutes === 0 => "{$rest}s",+ $rest === 0 => "{$minutes}min",+ default => "{$minutes}min {$rest}s",+ };}/*** @param array<string, mixed> $item*/- private function isVideo(array $item): bool+ private function isGif(array $item): bool{- return $this->isType($item, MediaType::Video);+ return MediaType::isGif(data_get($item, 'mime_type'));}/*** @param array<string, mixed> $item*/- private function isDocument(array $item): bool+ private function isMov(array $item): bool{- return $this->isType($item, MediaType::Document);+ return MediaType::isMov(data_get($item, 'mime_type'), $this->fileNameOf($item));}/**- * A media item matches a type when it carries that explicit `type`, or when- * its MIME classifies as that type.+ * Mirrors `classify()` in mediaType.ts and `MediaItem::kind()`: the explicit+ * `type` wins, otherwise the item classifies by MIME, then by filename — so+ * an item without a MIME is still measured against the right cap instead of+ * the image one.** @param array<string, mixed> $item*/- private function isType(array $item, MediaType $type): bool+ private function typeOf(array $item): ?MediaType+ {+ return MediaType::tryFrom((string) data_get($item, 'type', ''))+ ?? MediaType::classify(data_get($item, 'mime_type'), $this->fileNameOf($item));+ }++ /**+ * @param array<string, mixed> $item+ */+ private function fileNameOf(array $item): ?string{- return data_get($item, 'type') === $type->value- || MediaType::classify(data_get($item, 'mime_type')) === $type;+ return data_get($item, 'original_filename') ?? data_get($item, 'path');}}diff --git a/app/Services/Media/ChunkedAssetReceiver.php b/app/Services/Media/ChunkedAssetReceiver.phpindex d09949d77..71d74d835 100644--- a/app/Services/Media/ChunkedAssetReceiver.php+++ b/app/Services/Media/ChunkedAssetReceiver.php@@ -4,8 +4,11 @@ declare(strict_types=1);namespace App\Services\Media;+use App\Enums\Media\Type as MediaType;use App\Models\User;use App\Models\Workspace;+use App\Support\VideoDurationProbe;+use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Storage;use Throwable;@@ -22,14 +25,29 @@ final class ChunkedAssetReceiverint $rangeEnd,int $totalSize,string $attemptId,+ ?float $duration = null,): ChunkReceipt {$identifier = md5("{$user->id}{$fileName}{$totalSize}{$attemptId}");+ $meta = $this->videoMeta($fileName, $duration);return $this->cloud->shouldUseMultipart($fileName)- ? $this->receiveViaMultipart($workspace, $identifier, $fileName, $chunk, $rangeStart, $rangeEnd, $totalSize)- : $this->receiveViaLocalAssemble($workspace, $identifier, $fileName, $chunk, $rangeStart, $rangeEnd, $totalSize);+ ? $this->receiveViaMultipart($workspace, $identifier, $fileName, $chunk, $rangeStart, $rangeEnd, $totalSize, $meta)+ : $this->receiveViaLocalAssemble($workspace, $identifier, $fileName, $chunk, $rangeStart, $rangeEnd, $totalSize, $meta);}+ /**+ * @return array<string, float>+ */+ private function videoMeta(string $fileName, ?float $duration): array+ {+ return MediaType::classify(null, $fileName) === MediaType::Video+ ? VideoDurationProbe::mergeInto([], $duration)+ : [];+ }++ /**+ * @param array<string, mixed> $meta+ */private function receiveViaMultipart(Workspace $workspace,string $identifier,@@ -38,6 +56,7 @@ final class ChunkedAssetReceiverint $rangeStart,int $rangeEnd,int $totalSize,+ array $meta,): ChunkReceipt {$result = $this->cloud->receiveChunk($identifier,@@ -53,14 +72,17 @@ final class ChunkedAssetReceiver}$path = (string) data_get($result, 'path');+ $mimeType = (string) data_get($result, 'mime_type');+ $size = (int) data_get($result, 'size');try {$media = $workspace->addMediaFromStoredPath($path,$fileName,- (string) data_get($result, 'mime_type'),- (int) data_get($result, 'size'),+ $mimeType,+ $size,'assets',+ $this->withStoredVideoDuration($meta, $mimeType, $path, $size),);} catch (Throwable $exception) {Storage::delete($path);@@ -71,6 +93,34 @@ final class ChunkedAssetReceiverreturn ChunkReceipt::completed($media);}+ /**+ * The multipart object never touches local disk, so the probe reads the+ * atom headers straight from object storage with ranged GETs.+ *+ * @param array<string, mixed> $meta+ * @return array<string, mixed>+ */+ private function withStoredVideoDuration(array $meta, string $mimeType, string $path, int $size): array+ {+ if (MediaType::classify($mimeType) !== MediaType::Video) {+ return $meta;+ }++ try {+ return VideoDurationProbe::mergeInto($meta, VideoDurationProbe::fromReader(+ fn (int $offset, int $length): string => $this->cloud->readRange($path, $offset, $length),+ $size,+ ));+ } catch (Throwable $exception) {+ Log::warning('Could not probe video duration from object storage', ['path' => $path, 'error' => $exception->getMessage()]);++ return $meta;+ }+ }++ /**+ * @param array<string, mixed> $meta+ */private function receiveViaLocalAssemble(Workspace $workspace,string $identifier,@@ -79,6 +129,7 @@ final class ChunkedAssetReceiverint $rangeStart,int $rangeEnd,int $totalSize,+ array $meta,): ChunkReceipt {$tempFile = storage_path("app/private/chunks/{$identifier}");@@ -93,7 +144,7 @@ final class ChunkedAssetReceiver}try {- $media = $workspace->addMediaFromPath($tempFile, $fileName, 'assets');+ $media = $workspace->addMediaFromPath($tempFile, $fileName, 'assets', $meta);} finally {@unlink($tempFile);}diff --git a/app/Services/Media/ChunkedCloudUploader.php b/app/Services/Media/ChunkedCloudUploader.phpindex 47312b0ee..e632132ac 100644--- a/app/Services/Media/ChunkedCloudUploader.php+++ b/app/Services/Media/ChunkedCloudUploader.php@@ -42,16 +42,25 @@ class ChunkedCloudUploaderreturn false;}- $type = MediaType::fromExtension(pathinfo($fileName, PATHINFO_EXTENSION));-- return in_array($type, [MediaType::Video, MediaType::Document], true);+ return in_array(MediaType::classify(null, $fileName), [MediaType::Video, MediaType::Document], true);}public function isObjectStorageDisk(?string $disk = null): bool{- $disk ??= $this->diskName();+ return $this->diskOption('driver', $disk) === 's3';+ }++ public function readRange(string $key, int $offset, int $length): string+ {+ $lastByte = $offset + $length - 1;++ $object = $this->s3()->getObject([+ 'Bucket' => $this->bucket(),+ 'Key' => $key,+ 'Range' => "bytes={$offset}-{$lastByte}",+ ]);- return config("filesystems.disks.{$disk}.driver") === 's3';+ return (string) data_get($object, 'Body');}/**@@ -175,7 +184,7 @@ class ChunkedCloudUploader*/private function startUpload(string $fileName, string $firstChunk): array{- $extension = strtolower((string) pathinfo($fileName, PATHINFO_EXTENSION));+ $extension = MediaType::extensionOf($fileName);$filename = Str::uuid().".{$extension}";$key = "medias/{$filename}";$mimeType = $this->detectMimeType($firstChunk, $extension);@@ -225,8 +234,7 @@ class ChunkedCloudUploaderreturn $detected;}- return MediaType::fromExtension($extension)?->allowedMimeTypes()[0]- ?? 'application/octet-stream';+ return MediaType::mimeTypeFromExtension($extension) ?? 'application/octet-stream';}private function s3(): S3Client@@ -250,11 +258,18 @@ class ChunkedCloudUploaderreturn $this->bucket;}- return (string) config("filesystems.disks.{$this->diskName()}.bucket");+ return (string) $this->diskOption('bucket');}private function diskName(): string{return $this->disk ?? (string) config('filesystems.default');}++ private function diskOption(string $key, ?string $disk = null): mixed+ {+ $disk ??= $this->diskName();++ return config("filesystems.disks.{$disk}.{$key}");+ }}diff --git a/app/Services/Post/MediaAttacher.php b/app/Services/Post/MediaAttacher.phpindex ed1782827..017e985eb 100644--- a/app/Services/Post/MediaAttacher.php+++ b/app/Services/Post/MediaAttacher.php@@ -4,11 +4,13 @@ declare(strict_types=1);namespace App\Services\Post;+use App\Dto\MediaItem;use App\Enums\Media\Type as MediaType;use App\Models\Media;use App\Models\Post;use App\Models\Workspace;use App\Services\Brand\SafeHttpFetcher;+use Illuminate\Support\Facades\File;use RuntimeException;use Throwable;@@ -47,7 +49,7 @@ class MediaAttacherif (($alt = data_get($entry, 'alt')) !== null&& MediaType::classify(data_get($item, 'mime_type'), data_get($item, 'path')) === MediaType::Image) {- $item['meta'] = ['alt_text' => $alt];+ $item['meta'] = [...data_get($item, 'meta', []), 'alt_text' => $alt];}$attached[] = $item;@@ -91,9 +93,8 @@ class MediaAttachercontinue;}- if (($meta = data_get($item, 'meta')) !== null) {- $hosted['meta'] = $meta;- }+ // The client's meta (alt text) fills in; what the server measured from the file wins.+ $hosted['meta'] = [...data_get($item, 'meta') ?? [], ...data_get($hosted, 'meta', [])];$media[] = $hosted;$hostedIds[] = data_get($hosted, 'id');@@ -134,14 +135,7 @@ class MediaAttacher$name = basename(parse_url($url, PHP_URL_PATH) ?? '') ?: 'download.bin';$media = $workspace->addMediaFromPath($download['path'], $name, 'assets');- return [- 'id' => $media->id,- 'path' => $media->path,- 'url' => $media->url,- 'type' => $media->type,- 'mime_type' => $media->mime_type,- 'original_filename' => $media->original_filename,- ];+ return MediaItem::fromMedia($media)->toArray();} finally {@unlink($download['path']);}@@ -189,7 +183,7 @@ class MediaAttacherreturn ['path' => $temp,- 'mime' => mime_content_type($temp) ?: null,+ 'mime' => File::mimeType($temp) ?: null,'bytes' => $bytes,];}diff --git a/app/Services/Social/AbstractLinkedInPublisher.php b/app/Services/Social/AbstractLinkedInPublisher.phpindex 774842be8..f20724178 100644--- a/app/Services/Social/AbstractLinkedInPublisher.php+++ b/app/Services/Social/AbstractLinkedInPublisher.php@@ -15,6 +15,7 @@ use App\Services\Media\MediaOptimizer;use App\Services\Social\Concerns\HasSocialHttpClient;use Illuminate\Http\Client\PendingRequest;use Illuminate\Http\Client\Response;+use Illuminate\Support\Facades\File;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;@@ -286,7 +287,7 @@ abstract class AbstractLinkedInPublishertry {$this->downloadToTempFile($mediaItem->url, $tempFile);- $detectedMime = mime_content_type($tempFile) ?: '';+ $detectedMime = File::mimeType($tempFile) ?: '';if (MediaType::classify($detectedMime) === MediaType::Image && ! MediaType::isGif($detectedMime)) {$optimizedPath = app(MediaOptimizer::class)->optimizeImage($tempFile, $this->platform());@unlink($tempFile);diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.phpindex a881b5c79..e20d5caf6 100644--- a/app/Services/Social/BlueskyPublisher.php+++ b/app/Services/Social/BlueskyPublisher.php@@ -345,8 +345,7 @@ class BlueskyPublishertry {$fileSize = filesize($tempFile);- // Bluesky caps videos at 100MB; skip oversized files rather than- // burning an upload that the service will reject.+ // Skip oversized files rather than burning an upload the service will reject.if ($fileSize > (int) config('trypost.platforms.bluesky.video_max_bytes')) {Log::error('Bluesky video exceeds size limit', ['url' => $url, 'size' => $fileSize]);@@ -542,8 +541,9 @@ class BlueskyPublisher/*** Map a video mime type to the [Content-Type, file extension] the upload- * should carry. Bluesky accepts mp4, mpeg, webm and mov; anything else- * (or an unknown mime) is sent as mp4 and left to the transcoder.+ * should carry. The video service accepts MP4, MPEG, WebM and QuickTime+ * (same list as the official app) and transcodes to the MP4 blob the+ * embed lexicon stores.** @return array{0: string, 1: string}*/diff --git a/app/Services/Social/MastodonPublisher.php b/app/Services/Social/MastodonPublisher.phpindex 57350e87f..ee3a2b2e1 100644--- a/app/Services/Social/MastodonPublisher.php+++ b/app/Services/Social/MastodonPublisher.php@@ -12,6 +12,7 @@ use App\Models\SocialAccount;use App\Services\Media\MediaOptimizer;use App\Services\Social\Concerns\HasSocialHttpClient;use Illuminate\Http\Client\Response;+use Illuminate\Support\Facades\File;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;@@ -86,7 +87,7 @@ class MastodonPublisher}// Optimize images (skip GIFs)- $detectedMime = mime_content_type($tempFile) ?: '';+ $detectedMime = File::mimeType($tempFile) ?: '';if (MediaType::classify($detectedMime) === MediaType::Image && ! MediaType::isGif($detectedMime)) {$optimizer = app(MediaOptimizer::class);$optimizedPath = $optimizer->optimizeImage($tempFile, Platform::Mastodon);diff --git a/app/Services/Social/PinterestPublisher.php b/app/Services/Social/PinterestPublisher.phpindex bbee0944f..3cb6df412 100644--- a/app/Services/Social/PinterestPublisher.php+++ b/app/Services/Social/PinterestPublisher.php@@ -17,6 +17,7 @@ use App\Services\Media\MediaOptimizer;use App\Services\Social\Concerns\HasSocialHttpClient;use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\Response;+use Illuminate\Support\Facades\File;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;use Illuminate\Support\Sleep;@@ -147,7 +148,7 @@ class PinterestPublisher);}- $detectedMime = mime_content_type($tempFile) ?: '';+ $detectedMime = File::mimeType($tempFile) ?: '';if (MediaType::classify($detectedMime) === MediaType::Image && ! MediaType::isGif($detectedMime)) {$optimizer = app(MediaOptimizer::class);$optimizedPath = $optimizer->optimizeImage($tempFile, Platform::Pinterest);diff --git a/app/Services/Social/XPublisher.php b/app/Services/Social/XPublisher.phpindex cdb96b7c2..f2e7a2f2c 100644--- a/app/Services/Social/XPublisher.php+++ b/app/Services/Social/XPublisher.php@@ -14,6 +14,7 @@ use App\Services\Media\MediaOptimizer;use App\Services\Social\Concerns\HasSocialHttpClient;use Illuminate\Http\Client\PendingRequest;use Illuminate\Http\Client\Response;+use Illuminate\Support\Facades\File;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;use Illuminate\Support\Sleep;@@ -164,7 +165,7 @@ class XPublisher}if (blank($mimeType)) {- $mimeType = mime_content_type($tempFile) ?: null;+ $mimeType = File::mimeType($tempFile) ?: null;}if (blank($mimeType)) {@@ -184,7 +185,7 @@ class XPublisher}$fileSize = filesize($tempFile);- $mediaCategory = $this->getMediaCategory($mimeType, $fileSize);+ $mediaCategory = $this->getMediaCategory($mimeType);$isVideo = MediaType::classify($mimeType) === MediaType::Video;$isGif = MediaType::isGif($mimeType);@@ -342,10 +343,13 @@ class XPublisher];}- private function getMediaCategory(string $mimeType, int $fileSize): ?string+ /**+ * Videos are always `tweet_video`; `amplify_video` is the Ads-creative category.+ */+ private function getMediaCategory(string $mimeType): ?string{if (MediaType::classify($mimeType) === MediaType::Video) {- return $fileSize > 15 * 1024 * 1024 ? 'amplify_video' : 'tweet_video';+ return 'tweet_video';}if (MediaType::isGif($mimeType)) {diff --git a/app/Support/VideoDurationProbe.php b/app/Support/VideoDurationProbe.phpnew file mode 100644index 000000000..7ce727df7--- /dev/null+++ b/app/Support/VideoDurationProbe.php@@ -0,0 +1,214 @@+<?php++declare(strict_types=1);++namespace App\Support;++use Closure;+use Generator;+use Illuminate\Support\Str;++/**+ * Reads a video's duration from the `moov > mvhd` atom of an MP4 / MOV file.+ * Only atom headers are read, so a file whose `moov` sits after a large `mdat`+ * costs a handful of small reads rather than a full download.+ */+final class VideoDurationProbe+{+ private const ATOM_HEADER_BYTES = 8;++ private const ATOM_LARGE_HEADER_BYTES = 16;++ private const MVHD_V0_BYTES = 20;++ private const MVHD_V1_BYTES = 32;++ private const MVHD_UNKNOWN_DURATION = 0xFFFFFFFF;++ /**+ * A real file has a handful of atoms per level (`ftyp`, `moov`, `mdat`, a+ * few `trak`s). Each header is one read — a ranged GET on object storage —+ * so an upload padded with thousands of tiny atoms must not turn into+ * thousands of requests. Past this many, the duration is simply unknown.+ */+ private const MAX_ATOMS_PER_LEVEL = 64;++ /**+ * @param Closure(int, int): string $reader Returns up to `$length` bytes starting at `$offset`.+ */+ private function __construct(+ private readonly Closure $reader,+ private readonly int $size,+ ) {}++ public static function fromFile(string $path): ?float+ {+ $handle = @fopen($path, 'rb');++ if ($handle === false) {+ return null;+ }++ try {+ return self::fromReader(+ static fn (int $offset, int $length): string => fseek($handle, $offset) === 0+ ? (string) fread($handle, $length)+ : '',+ (int) data_get(fstat($handle), 'size', 0),+ );+ } finally {+ fclose($handle);+ }+ }++ /**+ * @param Closure(int, int): string $read Returns up to `$length` bytes starting at `$offset`.+ */+ public static function fromReader(Closure $read, int $totalSize): ?float+ {+ return (new self($read, max(0, $totalSize)))->duration();+ }++ /**+ * Writes a usable duration into `$meta`; nothing, zero, negative or+ * non-finite (INF cannot be JSON-encoded) leaves it untouched.+ *+ * @param array<string, mixed> $meta+ * @return array<string, mixed>+ */+ public static function mergeInto(array $meta, ?float $duration): array+ {+ return $duration === null || ! is_finite($duration) || $duration <= 0+ ? $meta+ : [...$meta, 'duration' => round($duration, 2)];+ }++ /**+ * `moov` holds `mvhd`, and `mvhd` holds the duration. Each step returns+ * null when its atom is missing, and the next step passes that through.+ */+ private function duration(): ?float+ {+ return $this->seconds($this->payload('mvhd', $this->payload('moov', [0, $this->size])));+ }++ /**+ * Payload bounds of the first `$type` atom laid out within `$within`.+ *+ * @param array{int, int}|null $within+ * @return array{int, int}|null+ */+ private function payload(string $type, ?array $within): ?array+ {+ if ($within === null) {+ return null;+ }++ // A plain loop, not Arr::first(): that would drain the generator first,+ // reading every sibling header (one ranged GET each on object storage).+ foreach ($this->atoms(...$within) as $atomType => $bounds) {+ if ($atomType === $type) {+ return $bounds;+ }+ }++ return null;+ }++ /**+ * Walks the atoms laid out between `$from` and `$to`, yielding each type+ * with its payload bounds. A header that cannot be read, or one atom too+ * many, ends the walk.+ *+ * @return Generator<string, array{int, int}>+ */+ private function atoms(int $from, int $to): Generator+ {+ $offset = $from;+ $remaining = self::MAX_ATOMS_PER_LEVEL;++ while ($remaining-- > 0 && $offset + self::ATOM_HEADER_BYTES <= $to && ($header = $this->header($offset, $to)) !== null) {+ [$size, $type, $headerBytes] = $header;++ yield $type => [$offset + $headerBytes, $offset + $size];++ $offset += $size;+ }+ }++ /**+ * Reads one atom header. A size of 1 means a 64-bit "largesize" follows the+ * type; a size of 0 means the atom runs to the end of its parent. Either way+ * the size is clamped to the bytes that remain.+ *+ * @return array{int, string, int}|null+ */+ private function header(int $offset, int $to): ?array+ {+ $available = $to - $offset;+ $bytes = $this->read($offset, min(self::ATOM_LARGE_HEADER_BYTES, $available));++ if (strlen($bytes) < self::ATOM_HEADER_BYTES) {+ return null;+ }++ ['size' => $size, 'type' => $type] = unpack('Nsize/a4type', $bytes);+ $headerBytes = self::ATOM_HEADER_BYTES;++ if ($size === 1 && strlen($bytes) === self::ATOM_LARGE_HEADER_BYTES) {+ [1 => $size] = unpack('J', $bytes, self::ATOM_HEADER_BYTES);+ $headerBytes = self::ATOM_LARGE_HEADER_BYTES;+ } elseif ($size === 0) {+ $size = $available;+ }++ $size = min($size, $available);++ return $size < $headerBytes ? null : [$size, $type, $headerBytes];+ }++ /**+ * `mvhd` starts with a version byte; version 1 widens the creation and+ * modification times to 64 bits, which pushes `timescale` and `duration`+ * from offsets 12 / 16 to 20 / 24 and makes `duration` 64-bit as well.+ *+ * A duration of all 1s means "unknown" per ISO 14496-12. In version 1 that+ * reads back as -1 and fails the `> 0` check on its own; version 0 needs+ * the explicit sentinel, or a live capture would report ~49 days.+ *+ * @param array{int, int}|null $bounds+ */+ private function seconds(?array $bounds): ?float+ {+ if ($bounds === null) {+ return null;+ }++ [$start, $end] = $bounds;++ if ($end - $start < self::MVHD_V0_BYTES) {+ return null;+ }++ $mvhd = $this->read($start, min($end - $start, self::MVHD_V1_BYTES));++ [$needed, $format] = Str::startsWith($mvhd, "\x01")+ ? [self::MVHD_V1_BYTES, 'x20/Ntimescale/Jduration']+ : [self::MVHD_V0_BYTES, 'x12/Ntimescale/Nduration'];++ if (strlen($mvhd) < $needed) {+ return null;+ }++ ['timescale' => $timescale, 'duration' => $duration] = unpack($format, $mvhd);++ return $timescale > 0 && $duration > 0 && $duration !== self::MVHD_UNKNOWN_DURATION+ ? $duration / $timescale+ : null;+ }++ private function read(int $offset, int $length): string+ {+ return ($this->reader)($offset, $length);+ }+}diff --git a/config/trypost.php b/config/trypost.phpindex 0fdd5ee77..aed84cd6b 100644--- a/config/trypost.php+++ b/config/trypost.php@@ -237,8 +237,8 @@ return ['video_poll_seconds' => env('BLUESKY_VIDEO_POLL_SECONDS', 2),// Gradually back off status checks to at most this interval.'video_poll_max_seconds' => env('BLUESKY_VIDEO_POLL_MAX_SECONDS', 30),- // Bluesky rejects videos larger than 100 MB; skip oversized files early.- 'video_max_bytes' => env('BLUESKY_VIDEO_MAX_BYTES', 100 * 1024 * 1024),+ // Bluesky rejects videos over 300 MB (app.bsky.embed.video maxSize = 300000000).+ 'video_max_bytes' => env('BLUESKY_VIDEO_MAX_BYTES', 300_000_000),// PLC directory, used to resolve an account's real PDS host from its DID.'plc_directory' => env('BLUESKY_PLC_DIRECTORY', 'https://plc.directory'),],diff --git a/lang/ar/assets.php b/lang/ar/assets.phpindex 1c59d9b03..fd70513bf 100644--- a/lang/ar/assets.php+++ b/lang/ar/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => 'حفظ في الوسائط','saved' => 'تم الحفظ في وسائطك!','create_post' => 'إنشاء منشور',+ 'download' => 'تنزيل','add_to_post' => 'إضافة إلى المنشور','search_placeholder' => 'البحث في الوسائط...',diff --git a/lang/ar/posts.php b/lang/ar/posts.phpindex 77c703250..43445d185 100644--- a/lang/ar/posts.php+++ b/lang/ar/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => 'لا يمكن الجمع بين الصور والفيديو في نفس المنشور.','document_not_alone' => 'يجب نشر ملف PDF بمفرده، دون صور أو مقاطع فيديو أخرى.','gif_not_allowed' => 'لا تقبل هذه المنصة صور GIF. أزِل صورة GIF أو اختر شبكة مختلفة.',+ 'mov_not_allowed' => 'لا تقبل هذه المنصة فيديوهات MOV. استخدم MP4.','image_too_large' => 'تتجاوز الصورة حد :max لهذا النوع من المنشورات (حجم صورتك :current).','video_too_large' => 'يتجاوز الفيديو حد :max لهذا النوع من المنشورات (حجم فيديوك :current).','document_too_large' => 'يتجاوز ملف PDF حد :max لهذا النوع من المنشورات (حجم ملفك :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'يُسمح بمقاطع الفيديو فقط لهذا التنسيق.','no_mixed_media' => 'لا يمكن الجمع بين الصور ومقاطع الفيديو في نفس المنشور.','no_gifs' => 'صور GIF غير مدعومة هنا.',+ 'no_movs' => 'فيديوهات MOV غير مدعومة هنا. استخدم MP4.','no_documents' => 'مستندات PDF غير مدعومة في هذا التنسيق.','document_not_alone' => 'يجب نشر ملف PDF بمفرده، دون صور أو مقاطع فيديو أخرى.','video_too_large' => 'يتجاوز الفيديو حد الحجم لهذه المنصة.','video_too_long' => 'يجب أن تكون مدة الفيديو أقل من :seconds ثانية لهذا التنسيق.','image_too_large' => 'تتجاوز الصورة حد الحجم لهذه المنصة.','document_too_large' => 'يتجاوز ملف PDF حد الحجم لهذه المنصة.',+ 'media_limits_docs' => 'عرض حدود الوسائط','aspect_ratio_invalid' => 'نسبة العرض إلى الارتفاع غير مدعومة في هذا التنسيق.','no_content_type' => 'اختر نوع محتوى لهذه المنصة.','requires_text' => 'أضِف نصًا — يتطلب هذا التنسيق عنوانًا.',diff --git a/lang/de/assets.php b/lang/de/assets.phpindex 9ad7195f3..35f708be0 100644--- a/lang/de/assets.php+++ b/lang/de/assets.php@@ -28,6 +28,7 @@ return ['save_to_assets' => 'In Assets speichern','saved' => 'In deinen Assets gespeichert!','create_post' => 'Beitrag erstellen',+ 'download' => 'Herunterladen','add_to_post' => 'Zum Beitrag hinzufügen','search_placeholder' => 'Medien suchen...',diff --git a/lang/de/posts.php b/lang/de/posts.phpindex a082a28d3..481bc0c33 100644--- a/lang/de/posts.php+++ b/lang/de/posts.php@@ -199,6 +199,7 @@ return ['no_mixed_media' => 'Bilder und ein Video können nicht im selben Beitrag kombiniert werden.','document_not_alone' => 'Ein PDF muss einzeln veröffentlicht werden, ohne andere Bilder oder Videos.','gif_not_allowed' => 'Diese Plattform akzeptiert keine GIFs. Entferne das GIF oder wähle ein anderes Netzwerk.',+ 'mov_not_allowed' => 'Diese Plattform akzeptiert keine MOV-Videos. Verwende MP4.','image_too_large' => 'Das Bild überschreitet das Limit von :max für diesen Beitragstyp (deins hat :current).','video_too_large' => 'Das Video überschreitet das Limit von :max für diesen Beitragstyp (deins hat :current).','document_too_large' => 'Das PDF überschreitet das Limit von :max für diesen Beitragstyp (deins hat :current).',@@ -359,12 +360,14 @@ return ['no_images' => 'Für dieses Format sind nur Videos erlaubt.','no_mixed_media' => 'Bilder und Videos können nicht im selben Beitrag kombiniert werden.','no_gifs' => 'GIFs werden hier nicht unterstützt.',+ 'no_movs' => 'MOV-Videos werden hier nicht unterstützt. Verwende MP4.','no_documents' => 'PDF-Dokumente werden von diesem Format nicht unterstützt.','document_not_alone' => 'Ein PDF muss einzeln veröffentlicht werden, ohne andere Bilder oder Videos.','video_too_large' => 'Das Video überschreitet das Größenlimit für diese Plattform.','video_too_long' => 'Das Video muss für dieses Format kürzer als :seconds Sekunden sein.','image_too_large' => 'Das Bild überschreitet das Größenlimit für diese Plattform.','document_too_large' => 'Das PDF überschreitet das Größenlimit für diese Plattform.',+ 'media_limits_docs' => 'Medienlimits ansehen','aspect_ratio_invalid' => 'Das Seitenverhältnis wird von diesem Format nicht unterstützt.','no_content_type' => 'Wähle einen Inhaltstyp für diese Plattform.','requires_text' => 'Füge Text hinzu – dieses Format benötigt einen Titel.',diff --git a/lang/el/assets.php b/lang/el/assets.phpindex 6cae0e14e..e4c278df7 100644--- a/lang/el/assets.php+++ b/lang/el/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => 'Αποθήκευση στα στοιχεία','saved' => 'Αποθηκεύτηκε στα στοιχεία σας!','create_post' => 'Δημιουργία δημοσίευσης',+ 'download' => 'Λήψη','add_to_post' => 'Προσθήκη σε δημοσίευση','search_placeholder' => 'Αναζήτηση πολυμέσων...',diff --git a/lang/el/posts.php b/lang/el/posts.phpindex a4592be22..dbf866950 100644--- a/lang/el/posts.php+++ b/lang/el/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => 'Οι εικόνες και ένα βίντεο δεν μπορούν να συνδυαστούν στην ίδια δημοσίευση.','document_not_alone' => 'Ένα PDF πρέπει να δημοσιεύεται μόνο του, χωρίς άλλες εικόνες ή βίντεο.','gif_not_allowed' => 'Αυτή η πλατφόρμα δεν δέχεται GIF. Αφαιρέστε το GIF ή επιλέξτε διαφορετικό δίκτυο.',+ 'mov_not_allowed' => 'Αυτή η πλατφόρμα δεν δέχεται βίντεο MOV. Χρησιμοποιήστε MP4.','image_too_large' => 'Η εικόνα υπερβαίνει το όριο :max για αυτόν τον τύπο δημοσίευσης (η δική σας είναι :current).','video_too_large' => 'Το βίντεο υπερβαίνει το όριο :max για αυτόν τον τύπο δημοσίευσης (το δικό σας είναι :current).','document_too_large' => 'Το PDF υπερβαίνει το όριο :max για αυτόν τον τύπο δημοσίευσης (το δικό σας είναι :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'Επιτρέπονται μόνο βίντεο για αυτή τη μορφή.','no_mixed_media' => 'Οι εικόνες και τα βίντεο δεν μπορούν να συνδυαστούν στην ίδια δημοσίευση.','no_gifs' => 'Τα GIF δεν υποστηρίζονται εδώ.',+ 'no_movs' => 'Τα βίντεο MOV δεν υποστηρίζονται εδώ. Χρησιμοποιήστε MP4.','no_documents' => 'Τα έγγραφα PDF δεν υποστηρίζονται από αυτή τη μορφή.','document_not_alone' => 'Ένα PDF πρέπει να δημοσιεύεται μόνο του, χωρίς άλλες εικόνες ή βίντεο.','video_too_large' => 'Το βίντεο υπερβαίνει το όριο μεγέθους για αυτή την πλατφόρμα.','video_too_long' => 'Το βίντεο πρέπει να είναι κάτω από :seconds δευτερόλεπτα για αυτή τη μορφή.','image_too_large' => 'Η εικόνα υπερβαίνει το όριο μεγέθους για αυτή την πλατφόρμα.','document_too_large' => 'Το PDF υπερβαίνει το όριο μεγέθους για αυτή την πλατφόρμα.',+ 'media_limits_docs' => 'Δείτε τα όρια πολυμέσων','aspect_ratio_invalid' => 'Η αναλογία διαστάσεων δεν υποστηρίζεται από αυτή τη μορφή.','no_content_type' => 'Επιλέξτε έναν τύπο περιεχομένου για αυτή την πλατφόρμα.','requires_text' => 'Προσθέστε κείμενο — αυτή η μορφή χρειάζεται τίτλο.',diff --git a/lang/en/assets.php b/lang/en/assets.phpindex 91f2c9502..07efca1a7 100644--- a/lang/en/assets.php+++ b/lang/en/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => 'Save to Assets','saved' => 'Saved to your assets!','create_post' => 'Create post',+ 'download' => 'Download','add_to_post' => 'Add to post','search_placeholder' => 'Search media...',diff --git a/lang/en/posts.php b/lang/en/posts.phpindex ffdf6cecf..4add724af 100644--- a/lang/en/posts.php+++ b/lang/en/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => "Images and a video can't be combined in the same post.",'document_not_alone' => 'A PDF must be posted on its own, without other images or videos.','gif_not_allowed' => 'This platform does not accept GIF. Remove the GIF or choose a different network.',+ 'mov_not_allowed' => 'This platform does not accept MOV videos. Use MP4.','image_too_large' => 'Image exceeds the :max limit for this post type (yours is :current).','video_too_large' => 'Video exceeds the :max limit for this post type (yours is :current).','document_too_large' => 'PDF exceeds the :max limit for this post type (yours is :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'Only videos are allowed for this format.','no_mixed_media' => "Images and videos can't be combined in the same post.",'no_gifs' => 'GIFs are not supported here.',+ 'no_movs' => 'MOV videos are not supported here. Use MP4.','no_documents' => 'PDF documents are not supported by this format.','document_not_alone' => 'A PDF must be posted on its own, without other images or videos.','video_too_large' => 'Video exceeds the size limit for this platform.','video_too_long' => 'Video must be under :seconds seconds for this format.','image_too_large' => 'Image exceeds the size limit for this platform.','document_too_large' => 'PDF exceeds the size limit for this platform.',+ 'media_limits_docs' => 'View media limits','aspect_ratio_invalid' => 'Aspect ratio is not supported by this format.','no_content_type' => 'Pick a content type for this platform.','requires_text' => 'Add text — this format needs a title.',diff --git a/lang/es/assets.php b/lang/es/assets.phpindex e99be7bcf..4d6264070 100644--- a/lang/es/assets.php+++ b/lang/es/assets.php@@ -28,6 +28,7 @@ return ['save_to_assets' => 'Guardar en la biblioteca','saved' => '¡Guardado en tu biblioteca!','create_post' => 'Crear post',+ 'download' => 'Descargar','add_to_post' => 'Agregar al post','search_placeholder' => 'Buscar media...',diff --git a/lang/es/posts.php b/lang/es/posts.phpindex 566e78ecc..7eb08c207 100644--- a/lang/es/posts.php+++ b/lang/es/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => 'No se pueden combinar imágenes y un video en la misma publicación.','document_not_alone' => 'Un PDF debe publicarse solo, sin otras imágenes ni videos.','gif_not_allowed' => 'Esta red no acepta GIF. Elimínalo o selecciona otra red.',+ 'mov_not_allowed' => 'Esta red no acepta vídeos MOV. Usa MP4.','image_too_large' => 'La imagen supera el límite de :max (la tuya es :current).','video_too_large' => 'El video supera el límite de :max (el tuyo es :current).','document_too_large' => 'El PDF supera el límite de :max (el tuyo es :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'Solo se permiten videos en este formato.','no_mixed_media' => 'No se pueden combinar imágenes y videos en la misma publicación.','no_gifs' => 'Los GIFs no son compatibles aquí.',+ 'no_movs' => 'Los vídeos MOV no son compatibles aquí. Usa MP4.','no_documents' => 'Los documentos PDF no son compatibles con este formato.','document_not_alone' => 'Un PDF debe publicarse solo, sin otras imágenes ni videos.','video_too_large' => 'El video supera el límite de tamaño de esta plataforma.','video_too_long' => 'El video debe durar menos de :seconds segundos en este formato.','image_too_large' => 'La imagen supera el límite de tamaño de esta plataforma.','document_too_large' => 'El PDF supera el límite de tamaño de esta plataforma.',+ 'media_limits_docs' => 'Ver límites de medios','aspect_ratio_invalid' => 'La proporción de aspecto no es compatible con este formato.','no_content_type' => 'Elige un tipo de contenido para esta plataforma.','requires_text' => 'Agrega texto — este formato necesita un título.',diff --git a/lang/fr/assets.php b/lang/fr/assets.phpindex 9068a3914..4843b9848 100644--- a/lang/fr/assets.php+++ b/lang/fr/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => 'Enregistrer dans les médias','saved' => 'Enregistré dans vos médias !','create_post' => 'Créer une publication',+ 'download' => 'Télécharger','add_to_post' => 'Ajouter à la publication','search_placeholder' => 'Rechercher un média...',diff --git a/lang/fr/posts.php b/lang/fr/posts.phpindex b246551f2..183ae393e 100644--- a/lang/fr/posts.php+++ b/lang/fr/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => 'Les images et une vidéo ne peuvent pas être combinées dans la même publication.','document_not_alone' => 'Un PDF doit être publié seul, sans autres images ou vidéos.','gif_not_allowed' => 'Cette plateforme n\'accepte pas les GIF. Supprimez le GIF ou choisissez un autre réseau.',+ 'mov_not_allowed' => 'Cette plateforme n\'accepte pas les vidéos MOV. Utilisez le MP4.','image_too_large' => 'L\'image dépasse la limite de :max pour ce type de publication (la vôtre est de :current).','video_too_large' => 'La vidéo dépasse la limite de :max pour ce type de publication (la vôtre est de :current).','document_too_large' => 'Le PDF dépasse la limite de :max pour ce type de publication (le vôtre est de :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'Seules les vidéos sont autorisées pour ce format.','no_mixed_media' => 'Les images et les vidéos ne peuvent pas être combinées dans la même publication.','no_gifs' => 'Les GIF ne sont pas pris en charge ici.',+ 'no_movs' => 'Les vidéos MOV ne sont pas prises en charge ici. Utilisez le MP4.','no_documents' => 'Les documents PDF ne sont pas pris en charge par ce format.','document_not_alone' => 'Un PDF doit être publié seul, sans autres images ou vidéos.','video_too_large' => 'La vidéo dépasse la limite de taille pour cette plateforme.','video_too_long' => 'La vidéo doit durer moins de :seconds secondes pour ce format.','image_too_large' => 'L\'image dépasse la limite de taille pour cette plateforme.','document_too_large' => 'Le PDF dépasse la limite de taille pour cette plateforme.',+ 'media_limits_docs' => 'Voir les limites de médias','aspect_ratio_invalid' => 'Le format d\'image n\'est pas pris en charge par ce format.','no_content_type' => 'Choisissez un type de contenu pour cette plateforme.','requires_text' => 'Ajoutez du texte — ce format nécessite un titre.',diff --git a/lang/it/assets.php b/lang/it/assets.phpindex 68ea2c122..76b3b5182 100644--- a/lang/it/assets.php+++ b/lang/it/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => 'Salva nelle risorse','saved' => 'Salvato nelle tue risorse!','create_post' => 'Crea post',+ 'download' => 'Scarica','add_to_post' => 'Aggiungi al post','search_placeholder' => 'Cerca media...',diff --git a/lang/it/posts.php b/lang/it/posts.phpindex 8bb0645e9..f6b3198e9 100644--- a/lang/it/posts.php+++ b/lang/it/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => 'Immagini e video non possono essere combinati nello stesso post.','document_not_alone' => 'Un PDF deve essere pubblicato da solo, senza altre immagini o video.','gif_not_allowed' => 'Questa piattaforma non accetta GIF. Rimuovi la GIF o scegli un\'altra rete.',+ 'mov_not_allowed' => 'Questa piattaforma non accetta video MOV. Usa MP4.','image_too_large' => 'L\'immagine supera il limite di :max per questo tipo di post (la tua è :current).','video_too_large' => 'Il video supera il limite di :max per questo tipo di post (il tuo è :current).','document_too_large' => 'Il PDF supera il limite di :max per questo tipo di post (il tuo è :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'Per questo formato sono consentiti solo video.','no_mixed_media' => 'Immagini e video non possono essere combinati nello stesso post.','no_gifs' => 'Le GIF non sono supportate qui.',+ 'no_movs' => 'I video MOV non sono supportati qui. Usa MP4.','no_documents' => 'I documenti PDF non sono supportati da questo formato.','document_not_alone' => 'Un PDF deve essere pubblicato da solo, senza altre immagini o video.','video_too_large' => 'Il video supera il limite di dimensione per questa piattaforma.','video_too_long' => 'Il video deve durare meno di :seconds secondi per questo formato.','image_too_large' => 'L\'immagine supera il limite di dimensione per questa piattaforma.','document_too_large' => 'Il PDF supera il limite di dimensione per questa piattaforma.',+ 'media_limits_docs' => 'Vedi i limiti dei media','aspect_ratio_invalid' => 'Le proporzioni non sono supportate da questo formato.','no_content_type' => 'Scegli un tipo di contenuto per questa piattaforma.','requires_text' => 'Aggiungi testo: questo formato richiede un titolo.',diff --git a/lang/ja/assets.php b/lang/ja/assets.phpindex 851a90f81..a46570849 100644--- a/lang/ja/assets.php+++ b/lang/ja/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => 'アセットに保存','saved' => 'アセットに保存しました!','create_post' => '投稿を作成',+ 'download' => 'ダウンロード','add_to_post' => '投稿に追加','search_placeholder' => 'メディアを検索...',diff --git a/lang/ja/posts.php b/lang/ja/posts.phpindex f0092fb3f..731c23ebf 100644--- a/lang/ja/posts.php+++ b/lang/ja/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => '画像と動画を同じ投稿にまとめることはできません。','document_not_alone' => 'PDF は単独で投稿する必要があり、他の画像や動画と一緒には投稿できません。','gif_not_allowed' => 'このプラットフォームは GIF を受け付けません。GIF を削除するか、別のネットワークを選択してください。',+ 'mov_not_allowed' => 'このプラットフォームは MOV 動画を受け付けません。MP4 を使用してください。','image_too_large' => '画像がこの投稿タイプの上限 :max を超えています(現在 :current)。','video_too_large' => '動画がこの投稿タイプの上限 :max を超えています(現在 :current)。','document_too_large' => 'PDF がこの投稿タイプの上限 :max を超えています(現在 :current)。',@@ -357,12 +358,14 @@ return ['no_images' => 'この形式では動画のみ使用できます。','no_mixed_media' => '画像と動画を同じ投稿にまとめることはできません。','no_gifs' => 'ここでは GIF はサポートされていません。',+ 'no_movs' => 'ここでは MOV 動画はサポートされていません。MP4 を使用してください。','no_documents' => 'この形式では PDF ドキュメントはサポートされていません。','document_not_alone' => 'PDF は単独で投稿する必要があり、他の画像や動画と一緒には投稿できません。','video_too_large' => '動画がこのプラットフォームのサイズ上限を超えています。','video_too_long' => 'この形式では動画は :seconds 秒未満である必要があります。','image_too_large' => '画像がこのプラットフォームのサイズ上限を超えています。','document_too_large' => 'PDF がこのプラットフォームのサイズ上限を超えています。',+ 'media_limits_docs' => 'メディア制限を見る','aspect_ratio_invalid' => 'この形式ではこのアスペクト比はサポートされていません。','no_content_type' => 'このプラットフォームのコンテンツタイプを選択してください。','requires_text' => 'テキストを追加してください — この形式にはタイトルが必要です。',diff --git a/lang/ko/assets.php b/lang/ko/assets.phpindex b22d5cdea..02bd9b2f0 100644--- a/lang/ko/assets.php+++ b/lang/ko/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => '에셋에 저장','saved' => '에셋에 저장되었습니다!','create_post' => '게시물 만들기',+ 'download' => '다운로드','add_to_post' => '게시물에 추가','search_placeholder' => '미디어 검색...',diff --git a/lang/ko/posts.php b/lang/ko/posts.phpindex 2ec32c9a4..f93cd8564 100644--- a/lang/ko/posts.php+++ b/lang/ko/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => '이미지와 동영상은 같은 게시물에 함께 넣을 수 없습니다.','document_not_alone' => 'PDF는 다른 이미지나 동영상 없이 단독으로 게시해야 합니다.','gif_not_allowed' => '이 플랫폼은 GIF를 허용하지 않습니다. GIF를 제거하거나 다른 네트워크를 선택하세요.',+ 'mov_not_allowed' => '이 플랫폼은 MOV 동영상을 허용하지 않습니다. MP4를 사용하세요.','image_too_large' => '이미지가 이 게시물 유형의 :max 한도를 초과합니다 (현재 :current).','video_too_large' => '동영상이 이 게시물 유형의 :max 한도를 초과합니다 (현재 :current).','document_too_large' => 'PDF가 이 게시물 유형의 :max 한도를 초과합니다 (현재 :current).',@@ -357,12 +358,14 @@ return ['no_images' => '이 형식은 동영상만 허용됩니다.','no_mixed_media' => '이미지와 동영상은 같은 게시물에 함께 넣을 수 없습니다.','no_gifs' => '여기에서는 GIF가 지원되지 않습니다.',+ 'no_movs' => '여기에서는 MOV 동영상이 지원되지 않습니다. MP4를 사용하세요.','no_documents' => '이 형식은 PDF 문서를 지원하지 않습니다.','document_not_alone' => 'PDF는 다른 이미지나 동영상 없이 단독으로 게시해야 합니다.','video_too_large' => '동영상이 이 플랫폼의 크기 한도를 초과합니다.','video_too_long' => '이 형식은 동영상이 :seconds초 미만이어야 합니다.','image_too_large' => '이미지가 이 플랫폼의 크기 한도를 초과합니다.','document_too_large' => 'PDF가 이 플랫폼의 크기 한도를 초과합니다.',+ 'media_limits_docs' => '미디어 제한 보기','aspect_ratio_invalid' => '이 형식은 해당 가로세로 비율을 지원하지 않습니다.','no_content_type' => '이 플랫폼의 콘텐츠 유형을 선택하세요.','requires_text' => '텍스트를 추가하세요 — 이 형식에는 제목이 필요합니다.',diff --git a/lang/nl/assets.php b/lang/nl/assets.phpindex 77e6fcc90..6ce192f3f 100644--- a/lang/nl/assets.php+++ b/lang/nl/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => 'Opslaan in assets','saved' => 'Opgeslagen in je assets!','create_post' => 'Post aanmaken',+ 'download' => 'Downloaden','add_to_post' => 'Toevoegen aan post','search_placeholder' => 'Media zoeken...',diff --git a/lang/nl/posts.php b/lang/nl/posts.phpindex 2e06df707..63c37c615 100644--- a/lang/nl/posts.php+++ b/lang/nl/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => 'Afbeeldingen en een video kunnen niet in dezelfde post worden gecombineerd.','document_not_alone' => 'Een PDF moet apart worden geplaatst, zonder andere afbeeldingen of video\'s.','gif_not_allowed' => 'Dit platform accepteert geen GIF. Verwijder de GIF of kies een ander netwerk.',+ 'mov_not_allowed' => 'Dit platform accepteert geen MOV-video\'s. Gebruik MP4.','image_too_large' => 'De afbeelding overschrijdt de limiet van :max voor dit posttype (die van jou is :current).','video_too_large' => 'De video overschrijdt de limiet van :max voor dit posttype (die van jou is :current).','document_too_large' => 'De PDF overschrijdt de limiet van :max voor dit posttype (die van jou is :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'Alleen video\'s zijn toegestaan voor dit formaat.','no_mixed_media' => 'Afbeeldingen en video\'s kunnen niet in dezelfde post worden gecombineerd.','no_gifs' => 'GIFs worden hier niet ondersteund.',+ 'no_movs' => 'MOV-video\'s worden hier niet ondersteund. Gebruik MP4.','no_documents' => 'PDF-documenten worden niet ondersteund door dit formaat.','document_not_alone' => 'Een PDF moet apart worden geplaatst, zonder andere afbeeldingen of video\'s.','video_too_large' => 'De video overschrijdt de groottelimiet voor dit platform.','video_too_long' => 'De video moet korter zijn dan :seconds seconden voor dit formaat.','image_too_large' => 'De afbeelding overschrijdt de groottelimiet voor dit platform.','document_too_large' => 'De PDF overschrijdt de groottelimiet voor dit platform.',+ 'media_limits_docs' => 'Medialimieten bekijken','aspect_ratio_invalid' => 'De beeldverhouding wordt niet ondersteund door dit formaat.','no_content_type' => 'Kies een contenttype voor dit platform.','requires_text' => 'Voeg tekst toe — dit formaat heeft een titel nodig.',diff --git a/lang/pl/assets.php b/lang/pl/assets.phpindex c3a6beab3..06dfd95fe 100644--- a/lang/pl/assets.php+++ b/lang/pl/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => 'Zapisz w zasobach','saved' => 'Zapisano w Twoich zasobach!','create_post' => 'Utwórz post',+ 'download' => 'Pobierz','add_to_post' => 'Dodaj do posta','search_placeholder' => 'Szukaj multimediów...',diff --git a/lang/pl/posts.php b/lang/pl/posts.phpindex d47721c06..e397a7474 100644--- a/lang/pl/posts.php+++ b/lang/pl/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => 'Obrazów i filmu nie można łączyć w tym samym poście.','document_not_alone' => 'PDF musi być publikowany samodzielnie, bez innych obrazów lub filmów.','gif_not_allowed' => 'Ta platforma nie akceptuje GIF-ów. Usuń GIF lub wybierz inną sieć.',+ 'mov_not_allowed' => 'Ta platforma nie akceptuje filmów MOV. Użyj MP4.','image_too_large' => 'Obraz przekracza limit :max dla tego typu posta (Twój ma :current).','video_too_large' => 'Film przekracza limit :max dla tego typu posta (Twój ma :current).','document_too_large' => 'PDF przekracza limit :max dla tego typu posta (Twój ma :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'Dla tego formatu dozwolone są tylko filmy.','no_mixed_media' => 'Obrazów i filmów nie można łączyć w tym samym poście.','no_gifs' => 'GIF-y nie są tutaj obsługiwane.',+ 'no_movs' => 'Filmy MOV nie są tutaj obsługiwane. Użyj MP4.','no_documents' => 'Dokumenty PDF nie są obsługiwane przez ten format.','document_not_alone' => 'PDF musi być publikowany samodzielnie, bez innych obrazów lub filmów.','video_too_large' => 'Film przekracza limit rozmiaru dla tej platformy.','video_too_long' => 'Film musi trwać krócej niż :seconds sekund dla tego formatu.','image_too_large' => 'Obraz przekracza limit rozmiaru dla tej platformy.','document_too_large' => 'PDF przekracza limit rozmiaru dla tej platformy.',+ 'media_limits_docs' => 'Zobacz limity mediów','aspect_ratio_invalid' => 'Proporcje nie są obsługiwane przez ten format.','no_content_type' => 'Wybierz typ treści dla tej platformy.','requires_text' => 'Dodaj tekst — ten format wymaga tytułu.',diff --git a/lang/pt-BR/assets.php b/lang/pt-BR/assets.phpindex a402f9768..f298b956b 100644--- a/lang/pt-BR/assets.php+++ b/lang/pt-BR/assets.php@@ -28,6 +28,7 @@ return ['save_to_assets' => 'Salvar na biblioteca','saved' => 'Salvo na sua biblioteca!','create_post' => 'Criar post',+ 'download' => 'Baixar','add_to_post' => 'Adicionar ao post','search_placeholder' => 'Buscar mídia...',diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.phpindex 3e4c0a0ec..37018fac1 100644--- a/lang/pt-BR/posts.php+++ b/lang/pt-BR/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => 'Não dá pra combinar imagens e um vídeo no mesmo post.','document_not_alone' => 'Um PDF precisa ser publicado sozinho, sem outras imagens ou vídeos.','gif_not_allowed' => 'Esta rede não aceita GIF. Remova o GIF ou escolha outra rede.',+ 'mov_not_allowed' => 'Essa rede não aceita vídeos MOV. Use MP4.','image_too_large' => 'A imagem passa do limite de :max (a sua tem :current).','video_too_large' => 'O vídeo passa do limite de :max (o seu tem :current).','document_too_large' => 'O PDF passa do limite de :max (o seu tem :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'Apenas vídeos são permitidos neste formato.','no_mixed_media' => 'Não é possível combinar imagem e vídeo na mesma publicação.','no_gifs' => 'GIFs não são suportados aqui.',+ 'no_movs' => 'Vídeos MOV não são suportados aqui. Use MP4.','no_documents' => 'Documentos PDF não são suportados por este formato.','document_not_alone' => 'Um PDF precisa ser publicado sozinho, sem outras imagens ou vídeos.','video_too_large' => 'Vídeo excede o limite de tamanho desta plataforma.','video_too_long' => 'Vídeo deve ter menos de :seconds segundos neste formato.','image_too_large' => 'Imagem excede o limite de tamanho desta plataforma.','document_too_large' => 'O PDF excede o limite de tamanho desta plataforma.',+ 'media_limits_docs' => 'Ver limites de mídia','aspect_ratio_invalid' => 'A proporção da imagem não é suportada por este formato.','no_content_type' => 'Escolha um tipo de conteúdo para esta plataforma.','requires_text' => 'Adicione texto — este formato precisa de um título.',diff --git a/lang/ru/assets.php b/lang/ru/assets.phpindex 0413b7092..77f3f19f9 100644--- a/lang/ru/assets.php+++ b/lang/ru/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => 'Сохранить в медиафайлы','saved' => 'Сохранено в медиафайлы!','create_post' => 'Создать пост',+ 'download' => 'Скачать','add_to_post' => 'Добавить в пост','search_placeholder' => 'Поиск медиа...',diff --git a/lang/ru/posts.php b/lang/ru/posts.phpindex 19439375f..947601df7 100644--- a/lang/ru/posts.php+++ b/lang/ru/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => 'Изображения и видео нельзя объединять в одном посте.','document_not_alone' => 'PDF нужно публиковать отдельно, без других изображений или видео.','gif_not_allowed' => 'Эта платформа не принимает GIF. Удалите GIF или выберите другую сеть.',+ 'mov_not_allowed' => 'Эта платформа не принимает видео MOV. Используйте MP4.','image_too_large' => 'Изображение превышает лимит :max для этого типа поста (у вас :current).','video_too_large' => 'Видео превышает лимит :max для этого типа поста (у вас :current).','document_too_large' => 'PDF превышает лимит :max для этого типа поста (у вас :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'Для этого формата допустимы только видео.','no_mixed_media' => 'Изображения и видео нельзя объединять в одном посте.','no_gifs' => 'GIF здесь не поддерживаются.',+ 'no_movs' => 'Видео MOV здесь не поддерживаются. Используйте MP4.','no_documents' => 'PDF-документы не поддерживаются этим форматом.','document_not_alone' => 'PDF нужно публиковать отдельно, без других изображений или видео.','video_too_large' => 'Видео превышает лимит размера для этой платформы.','video_too_long' => 'Для этого формата видео должно быть короче :seconds секунд.','image_too_large' => 'Изображение превышает лимит размера для этой платформы.','document_too_large' => 'PDF превышает лимит размера для этой платформы.',+ 'media_limits_docs' => 'Посмотреть лимиты медиа','aspect_ratio_invalid' => 'Соотношение сторон не поддерживается этим форматом.','no_content_type' => 'Выберите тип контента для этой платформы.','requires_text' => 'Добавьте текст — для этого формата нужен заголовок.',diff --git a/lang/tr/assets.php b/lang/tr/assets.phpindex 45578fc81..500313edd 100644--- a/lang/tr/assets.php+++ b/lang/tr/assets.php@@ -28,6 +28,7 @@ return ['save_to_assets' => 'Varlıklara Kaydet','saved' => 'Varlıklarınıza kaydedildi!','create_post' => 'Gönderi oluştur',+ 'download' => 'İndir','add_to_post' => 'Gönderiye ekle','search_placeholder' => 'Medya ara...',diff --git a/lang/tr/posts.php b/lang/tr/posts.phpindex f19d6c8a1..5faa9a22f 100644--- a/lang/tr/posts.php+++ b/lang/tr/posts.php@@ -199,6 +199,7 @@ return ['no_mixed_media' => 'Görseller ve bir video aynı gönderide birleştirilemez.','document_not_alone' => 'Bir PDF, başka görsel veya video olmadan tek başına paylaşılmalıdır.','gif_not_allowed' => 'Bu platform GIF kabul etmez. GIF\'i kaldırın veya farklı bir ağ seçin.',+ 'mov_not_allowed' => 'Bu platform MOV videoları kabul etmez. MP4 kullanın.','image_too_large' => 'Görsel, bu gönderi türü için :max sınırını aşıyor (sizinki :current).','video_too_large' => 'Video, bu gönderi türü için :max sınırını aşıyor (sizinki :current).','document_too_large' => 'PDF, bu gönderi türü için :max sınırını aşıyor (sizinki :current).',@@ -359,12 +360,14 @@ return ['no_images' => 'Bu format için yalnızca videolara izin verilir.','no_mixed_media' => 'Görseller ve videolar aynı gönderide birleştirilemez.','no_gifs' => 'Burada GIF desteklenmez.',+ 'no_movs' => 'Burada MOV videoları desteklenmez. MP4 kullanın.','no_documents' => 'PDF belgeler bu format tarafından desteklenmez.','document_not_alone' => 'Bir PDF, başka görsel veya video olmadan tek başına paylaşılmalıdır.','video_too_large' => 'Video, bu platformun boyut sınırını aşıyor.','video_too_long' => 'Video bu format için :seconds saniyenin altında olmalıdır.','image_too_large' => 'Görsel, bu platformun boyut sınırını aşıyor.','document_too_large' => 'PDF, bu platformun boyut sınırını aşıyor.',+ 'media_limits_docs' => 'Medya sınırlarını görüntüle','aspect_ratio_invalid' => 'En boy oranı bu format tarafından desteklenmez.','no_content_type' => 'Bu platform için bir içerik türü seçin.','requires_text' => 'Metin ekleyin — bu format bir başlık gerektiriyor.',diff --git a/lang/uk/assets.php b/lang/uk/assets.phpindex a2dcea8c9..0e4132f0d 100644--- a/lang/uk/assets.php+++ b/lang/uk/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => 'Зберегти в медіафайли','saved' => 'Збережено у ваші медіафайли!','create_post' => 'Створити пост',+ 'download' => 'Завантажити','add_to_post' => 'Додати до поста','search_placeholder' => 'Пошук медіа...',diff --git a/lang/uk/posts.php b/lang/uk/posts.phpindex bcd9b2505..4ee02d9fe 100644--- a/lang/uk/posts.php+++ b/lang/uk/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => 'Зображення та відео не можна поєднувати в одному пості.','document_not_alone' => 'PDF потрібно публікувати окремо, без інших зображень або відео.','gif_not_allowed' => 'Ця платформа не приймає GIF. Видаліть GIF або виберіть іншу мережу.',+ 'mov_not_allowed' => 'Ця платформа не приймає відео MOV. Використовуйте MP4.','image_too_large' => 'Зображення перевищує ліміт :max для цього типу поста (у вас :current).','video_too_large' => 'Відео перевищує ліміт :max для цього типу поста (у вас :current).','document_too_large' => 'PDF перевищує ліміт :max для цього типу поста (у вас :current).',@@ -357,12 +358,14 @@ return ['no_images' => 'Для цього формату допустимі лише відео.','no_mixed_media' => 'Зображення та відео не можна поєднувати в одному пості.','no_gifs' => 'GIF тут не підтримуються.',+ 'no_movs' => 'Відео MOV тут не підтримуються. Використовуйте MP4.','no_documents' => 'PDF-документи не підтримуються цим форматом.','document_not_alone' => 'PDF потрібно публікувати окремо, без інших зображень або відео.','video_too_large' => 'Відео перевищує ліміт розміру для цієї платформи.','video_too_long' => 'Для цього формату відео має бути коротшим за :seconds секунд.','image_too_large' => 'Зображення перевищує ліміт розміру для цієї платформи.','document_too_large' => 'PDF перевищує ліміт розміру для цієї платформи.',+ 'media_limits_docs' => 'Переглянути ліміти медіа','aspect_ratio_invalid' => 'Співвідношення сторін не підтримується цим форматом.','no_content_type' => 'Виберіть тип контенту для цієї платформи.','requires_text' => 'Додайте текст — для цього формату потрібен заголовок.',diff --git a/lang/zh/assets.php b/lang/zh/assets.phpindex 142dccec4..565b763fa 100644--- a/lang/zh/assets.php+++ b/lang/zh/assets.php@@ -26,6 +26,7 @@ return ['save_to_assets' => '保存到素材库','saved' => '已保存到你的素材库!','create_post' => '创建帖子',+ 'download' => '下载','add_to_post' => '添加到帖子','search_placeholder' => '搜索媒体…',diff --git a/lang/zh/posts.php b/lang/zh/posts.phpindex af5dc2750..c8e519378 100644--- a/lang/zh/posts.php+++ b/lang/zh/posts.php@@ -197,6 +197,7 @@ return ['no_mixed_media' => '图片和视频不能出现在同一条帖子中。','document_not_alone' => 'PDF 必须单独发布,不能附带其他图片或视频。','gif_not_allowed' => '此平台不接受 GIF。请移除 GIF 或改选其他平台。',+ 'mov_not_allowed' => '此平台不接受 MOV 视频。请使用 MP4。','image_too_large' => '图片超出此帖子类型的 :max 上限(你的为 :current)。','video_too_large' => '视频超出此帖子类型的 :max 上限(你的为 :current)。','document_too_large' => 'PDF 超出此帖子类型的 :max 上限(你的为 :current)。',@@ -357,12 +358,14 @@ return ['no_images' => '此格式仅允许视频。','no_mixed_media' => '图片和视频不能出现在同一条帖子中。','no_gifs' => '此处不支持 GIF。',+ 'no_movs' => '此处不支持 MOV 视频。请使用 MP4。','no_documents' => '此格式不支持 PDF 文档。','document_not_alone' => 'PDF 必须单独发布,不能附带其他图片或视频。','video_too_large' => '视频超出此平台的大小上限。','video_too_long' => '此格式的视频时长必须少于 :seconds 秒。','image_too_large' => '图片超出此平台的大小上限。','document_too_large' => 'PDF 超出此平台的大小上限。',+ 'media_limits_docs' => '查看媒体限制','aspect_ratio_invalid' => '此格式不支持该宽高比。','no_content_type' => '请为此平台选择一种内容类型。','requires_text' => '添加文字——此格式需要一个标题。',diff --git a/resources/js/components/ChannelConfigurator.vue b/resources/js/components/ChannelConfigurator.vueindex 309caa8d2..813d5dff0 100644--- a/resources/js/components/ChannelConfigurator.vue+++ b/resources/js/components/ChannelConfigurator.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { IconAlertCircle, IconCircleCheck } from '@tabler/icons-vue';+import { IconAlertCircle, IconCircleCheck, IconExternalLink } from '@tabler/icons-vue';import { computed } from 'vue';import DiscordSettings from '@/components/posts/editor/DiscordSettings.vue';@@ -38,6 +38,14 @@ const emit = defineEmits<{const isSelected = (id: string): boolean => props.selectedIds.includes(id);const selectedChannels = computed(() => props.channels.filter((channel) => isSelected(channel.id)));++/** Props and listeners every per-platform settings panel takes. */+const settingsProps = (channel: Channel) => ({+ socialAccount: channel.socialAccount,+ meta: channel.meta,+ disabled: props.disabled,+ 'onUpdate:meta': (value: Record<string, any>) => emit('update:meta', channel.id, value),+});</script><template>@@ -48,13 +56,8 @@ const selectedChannels = computed(() => props.channels.filter((channel) => isSel<TooltipTrigger as-child><buttontype="button"- class="flex w-20 cursor-pointer flex-col items-center gap-1.5 transition-opacity"- :class="[- channel.issue && !isSelected(channel.id) ? 'cursor-not-allowed opacity-40' : '',- channel.issue && isSelected(channel.id) ? 'opacity-100' : '',- !channel.issue ? 'opacity-100 hover:opacity-90' : '',- ]"- :disabled="Boolean(channel.issue) && !isSelected(channel.id)"+ class="flex w-20 cursor-pointer flex-col items-center gap-1.5 transition-opacity hover:opacity-90"+ :aria-pressed="isSelected(channel.id)":data-testid="`channel-${channel.id}`"@click="emit('toggle', channel.id)">@@ -63,26 +66,23 @@ const selectedChannels = computed(() => props.channels.filter((channel) => isSel:src="channel.avatarUrl":name="channel.displayName"class="size-10 shrink-0 rounded-full border-2"- :class="[- channel.issue && isSelected(channel.id) ? 'border-rose-500 shadow-2xs' : '',- !channel.issue && isSelected(channel.id) ? 'border-foreground shadow-2xs' : '',- !isSelected(channel.id) ? 'border-foreground/20' : '',- ]"+ :class="isSelected(channel.id) ? ['shadow-2xs', channel.issue ? 'border-rose-500' : 'border-foreground'] : 'border-foreground/20'"/><span class="absolute -bottom-1 -right-1 inline-flex size-5 items-center justify-center overflow-hidden rounded-full border-2 border-foreground bg-card shadow-2xs"><img :src="getPlatformLogo(channel.platform)" :alt="channel.platform" class="size-full object-cover" /></span>+ <Badge v-if="channel.status === PostPlatformStatus.Published" variant="success" class="absolute -top-1 -right-1 h-4 w-4 p-0">+ <IconCircleCheck class="h-2.5 w-2.5" />+ </Badge>+ <Badge v-else-if="channel.status === PostPlatformStatus.Failed" variant="destructive" class="absolute -top-1 -right-1 h-4 w-4 p-0 text-[9px]">!</Badge><Badge- v-if="channel.issue && isSelected(channel.id)"+ v-else-if="channel.issue"variant="destructive"class="absolute -top-1 -right-1 h-4 w-4 p-0"+ :data-testid="`channel-issue-${channel.id}`"><IconAlertCircle class="h-2.5 w-2.5" /></Badge>- <Badge v-else-if="channel.status === PostPlatformStatus.Published" variant="success" class="absolute -top-1 -right-1 h-4 w-4 p-0">- <IconCircleCheck class="h-2.5 w-2.5" />- </Badge>- <Badge v-else-if="channel.status === PostPlatformStatus.Failed" variant="destructive" class="absolute -top-1 -right-1 h-4 w-4 p-0 text-[9px]">!</Badge></div><spanclass="line-clamp-2 text-center text-xs leading-tight"@@ -101,6 +101,17 @@ const selectedChannels = computed(() => props.channels.filter((channel) => isSel<p v-if="channel.issue" class="mt-1 max-w-xs text-destructive-foreground/90">{{ channel.issue }}</p>+ <a+ v-if="channel.issue && channel.issueDocsUrl"+ :href="channel.issueDocsUrl"+ target="_blank"+ rel="noopener noreferrer"+ class="mt-1 inline-flex items-center gap-1 font-semibold underline underline-offset-2"+ :data-testid="`channel-issue-docs-${channel.id}`"+ >+ {{ $t('posts.edit.compliance.media_limits_docs') }}+ <IconExternalLink class="size-3" />+ </a></div></TooltipContent></Tooltip>@@ -112,65 +123,44 @@ const selectedChannels = computed(() => props.channels.filter((channel) => isSel<template v-for="channel in selectedChannels" :key="channel.id"><InstagramSettingsv-if="channel.platform === Platform.Instagram || channel.platform === Platform.InstagramFacebook"- :social-account="channel.socialAccount"+ v-bind="settingsProps(channel)":content-type="channel.contentType":media="media"- :meta="channel.meta"- :disabled="disabled"@update:content-type="emit('update:contentType', channel.id, $event)"- @update:meta="emit('update:meta', channel.id, $event)"/><FacebookSettingsv-else-if="channel.platform === Platform.Facebook"- :social-account="channel.socialAccount"+ v-bind="settingsProps(channel)":content-type="channel.contentType":media="media"- :meta="channel.meta"- :disabled="disabled"@update:content-type="emit('update:contentType', channel.id, $event)"- @update:meta="emit('update:meta', channel.id, $event)"/><TikTokSettingsv-else-if="channel.platform === Platform.TikTok"- :social-account="channel.socialAccount"+ v-bind="settingsProps(channel)":publish-config="channel.publishConfig ?? null":creator-info="channel.creatorInfo ?? null":video-duration-sec="videoDurationSec":content-type="channel.contentType":content-type-error="channel.contentTypeError"- :meta="channel.meta"- :disabled="disabled"@update:content-type="emit('update:contentType', channel.id, $event)"- @update:meta="emit('update:meta', channel.id, $event)"/><PinterestSettingsv-else-if="channel.platform === Platform.Pinterest"- :social-account="channel.socialAccount"+ v-bind="settingsProps(channel)":content-type="channel.contentType":media="media":boards="channel.boards ?? []":boards-truncated="channel.boardsTruncated ?? false"- :meta="channel.meta"- :disabled="disabled"@update:content-type="emit('update:contentType', channel.id, $event)"- @update:meta="emit('update:meta', channel.id, $event)"/><LinkedInSettingsv-else-if="channel.platform === Platform.LinkedIn || channel.platform === Platform.LinkedInPage"- :social-account="channel.socialAccount"+ v-bind="settingsProps(channel)":platform="channel.platform":media="media"- :meta="channel.meta"- :disabled="disabled"- @update:meta="emit('update:meta', channel.id, $event)"- />- <DiscordSettings- v-else-if="channel.platform === Platform.Discord"- :social-account="channel.socialAccount"- :meta="channel.meta"- :disabled="disabled"- @update:meta="emit('update:meta', channel.id, $event)"/>+ <DiscordSettings v-else-if="channel.platform === Platform.Discord" v-bind="settingsProps(channel)" /></template></div></template>diff --git a/resources/js/components/ImagePreviewDialog.vue b/resources/js/components/ImagePreviewDialog.vueindex de1f49f72..400bd67a7 100644--- a/resources/js/components/ImagePreviewDialog.vue+++ b/resources/js/components/ImagePreviewDialog.vue@@ -3,7 +3,7 @@ import { IconChevronLeft, IconChevronRight } from '@tabler/icons-vue';import { computed, onUnmounted, ref, watch } from 'vue';import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';-import { MediaType } from '@/lib/mediaType';+import { isDocument, isImage, isVideo, MediaType } from '@/lib/mediaType';interface PreviewItem {url: string;@@ -89,7 +89,7 @@ defineExpose({ open, openCollection, close });<DialogTitle class="sr-only">Media preview</DialogTitle><div class="relative flex justify-center" @click.self="close"><img- v-if="currentItem && currentItem.type === 'image'"+ v-if="currentItem && isImage(currentItem)":src="currentItem.url"alt="Preview"class="max-h-[85vh] max-w-full cursor-pointer rounded-2xl object-contain"@@ -97,7 +97,7 @@ defineExpose({ open, openCollection, close });/><video- v-else-if="currentItem && currentItem.type === 'video'"+ v-else-if="currentItem && isVideo(currentItem)":key="currentItem.url":src="currentItem.url"data-testid="lightbox-video"@@ -110,7 +110,7 @@ defineExpose({ open, openCollection, close });/><iframe- v-else-if="currentItem && currentItem.type === 'document'"+ v-else-if="currentItem && isDocument(currentItem)":key="currentItem.url":src="currentItem.url"title="PDF preview"diff --git a/resources/js/components/assets/GalleryBrowser.vue b/resources/js/components/assets/GalleryBrowser.vueindex 1e79e4706..310e6b182 100644--- a/resources/js/components/assets/GalleryBrowser.vue+++ b/resources/js/components/assets/GalleryBrowser.vue@@ -1,6 +1,6 @@<script setup lang="ts">import { router, useHttp } from '@inertiajs/vue3';-import { IconCloudUpload, IconFileTypePdf, IconLoader2, IconPencilPlus, IconPhoto, IconPlus, IconSearch, IconTrash } from '@tabler/icons-vue';+import { IconCloudUpload, IconDownload, IconFileTypePdf, IconLoader2, IconPencilPlus, IconPhoto, IconPlus, IconSearch, IconTrash } from '@tabler/icons-vue';import { trans } from 'laravel-vue-i18n';import { computed, nextTick, onMounted, onUnmounted, ref, useTemplateRef, watch } from 'vue';import { toast } from 'vue-sonner';@@ -15,7 +15,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';import debounce from '@/debounce';import { acceptAttribute, classify, isDocument, isVideo, MediaType } from '@/lib/mediaType';-import { destroy as assetsDestroy, search as assetsSearch, storeChunked as assetsStoreChunked, storeFromUrl } from '@/routes/app/assets';+import { destroy as assetsDestroy, download as assetsDownload, search as assetsSearch, storeChunked as assetsStoreChunked, storeFromUrl } from '@/routes/app/assets';import { search as giphySearch, trending as giphyTrending } from '@/routes/app/assets/giphy';import { search as unsplashSearch, trending as unsplashTrending } from '@/routes/app/assets/unsplash';import { store as storePost } from '@/routes/app/posts';@@ -730,15 +730,40 @@ onUnmounted(() => {<TooltipContent>{{ trans('assets.create_post') }}</TooltipContent></Tooltip></TooltipProvider>- <Button- variant="outline"- size="icon"- class="size-8 bg-rose-100 hover:bg-rose-200"- data-testid="gallery-asset-delete"- @click.stop="handleDelete(asset.id)"- >- <IconTrash class="size-4 text-rose-700" />- </Button>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger as-child>+ <Button+ variant="outline"+ size="icon"+ class="size-8"+ as="a"+ :href="assetsDownload.url(asset.id)"+ data-testid="gallery-asset-download"+ @click.stop+ >+ <IconDownload class="size-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>{{ trans('assets.download') }}</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger as-child>+ <Button+ variant="outline"+ size="icon"+ class="size-8 bg-rose-100 hover:bg-rose-200"+ data-testid="gallery-asset-delete"+ @click.stop="handleDelete(asset.id)"+ >+ <IconTrash class="size-4 text-rose-700" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>{{ trans('assets.delete.title') }}</TooltipContent>+ </Tooltip>+ </TooltipProvider></div><div class="space-y-0.5"><p class="truncate text-xs font-semibold text-white">{{ asset.original_filename }}</p>diff --git a/resources/js/components/posts/editor/FacebookSettings.vue b/resources/js/components/posts/editor/FacebookSettings.vueindex eae4801de..214bb74cf 100644--- a/resources/js/components/posts/editor/FacebookSettings.vue+++ b/resources/js/components/posts/editor/FacebookSettings.vue@@ -1,12 +1,13 @@<script setup lang="ts">-import { IconAlertTriangle, IconChevronDown, IconChevronUp } from '@tabler/icons-vue';+import { IconChevronDown, IconChevronUp } from '@tabler/icons-vue';import { computed, ref } from 'vue';+import MediaRulesWarning from '@/components/posts/editor/MediaRulesWarning.vue';import { Avatar } from '@/components/ui/avatar';-import { getMediaValidationWarning } from '@/composables/useMedia';import { getPlatformLogo } from '@/composables/usePlatformLogo';import { ContentType } from '@/types/content-type';import type { MediaItem } from '@/types/media';+import { Platform } from '@/types/platform';interface SocialAccount {id: string;@@ -63,8 +64,6 @@ const pickAspectRatio = (value: string) => {if (props.disabled) return;emit('update:meta', { ...props.meta, aspect_ratio: value });};--const warning = computed(() => getMediaValidationWarning(props.contentType, props.media));</script><template>@@ -140,13 +139,7 @@ const warning = computed(() => getMediaValidationWarning(props.contentType, prop</div></div>- <p- v-if="warning"- class="flex items-start gap-2 rounded-lg border-2 border-foreground bg-rose-50 p-2 text-xs font-semibold text-rose-700"- >- <IconAlertTriangle class="mt-0.5 size-3.5 shrink-0" />- {{ $t(`posts.form.warnings.${warning.key}`, warning.params) }}- </p>+ <MediaRulesWarning :content-type="contentType" :media="media" :platform="Platform.Facebook" /></div></div></template>diff --git a/resources/js/components/posts/editor/InstagramSettings.vue b/resources/js/components/posts/editor/InstagramSettings.vueindex 50ba18fd3..bd17de38a 100644--- a/resources/js/components/posts/editor/InstagramSettings.vue+++ b/resources/js/components/posts/editor/InstagramSettings.vue@@ -1,12 +1,13 @@<script setup lang="ts">-import { IconAlertTriangle, IconChevronDown, IconChevronUp } from '@tabler/icons-vue';+import { IconChevronDown, IconChevronUp } from '@tabler/icons-vue';import { computed, ref } from 'vue';+import MediaRulesWarning from '@/components/posts/editor/MediaRulesWarning.vue';import { Avatar } from '@/components/ui/avatar';-import { getMediaValidationWarning } from '@/composables/useMedia';import { getPlatformLogo } from '@/composables/usePlatformLogo';import { ContentType } from '@/types/content-type';import type { MediaItem } from '@/types/media';+import { Platform } from '@/types/platform';interface SocialAccount {id: string;@@ -63,8 +64,6 @@ const pickAspectRatio = (value: string) => {if (props.disabled) return;emit('update:meta', { ...props.meta, aspect_ratio: value });};--const warning = computed(() => getMediaValidationWarning(props.contentType, props.media));</script><template>@@ -139,13 +138,7 @@ const warning = computed(() => getMediaValidationWarning(props.contentType, prop</div></div>- <p- v-if="warning"- class="flex items-start gap-2 rounded-lg border-2 border-foreground bg-rose-50 p-2 text-xs font-semibold text-rose-700"- >- <IconAlertTriangle class="mt-0.5 size-3.5 shrink-0" />- {{ $t(`posts.form.warnings.${warning.key}`, warning.params) }}- </p>+ <MediaRulesWarning :content-type="contentType" :media="media" :platform="Platform.Instagram" /></div></div></template>diff --git a/resources/js/components/posts/editor/MediaRulesWarning.vue b/resources/js/components/posts/editor/MediaRulesWarning.vuenew file mode 100644index 000000000..403bf361e--- /dev/null+++ b/resources/js/components/posts/editor/MediaRulesWarning.vue@@ -0,0 +1,38 @@+<script setup lang="ts">+import { IconAlertTriangle, IconExternalLink } from '@tabler/icons-vue';+import { computed } from 'vue';++import { getMediaValidationWarning } from '@/composables/useMedia';+import { mediaLimitsDocsUrl } from '@/lib/docs';+import type { MediaItem } from '@/types/media';++const props = defineProps<{+ contentType: string;+ media: MediaItem[];+ platform: string;+}>();++const warning = computed(() => getMediaValidationWarning(props.contentType, props.media));+</script>++<template>+ <p+ v-if="warning"+ class="flex items-start gap-2 rounded-lg border-2 border-foreground bg-rose-50 p-2 text-xs font-semibold text-rose-700"+ data-testid="media-rules-warning"+ >+ <IconAlertTriangle class="mt-0.5 size-3.5 shrink-0" />+ <span>+ {{ $t(`posts.form.warnings.${warning.key}`, warning.params) }}+ <a+ :href="mediaLimitsDocsUrl(platform)"+ target="_blank"+ rel="noopener noreferrer"+ class="inline-flex items-center gap-0.5 underline underline-offset-2"+ >+ {{ $t('posts.edit.compliance.media_limits_docs') }}+ <IconExternalLink class="size-3" />+ </a>+ </span>+ </p>+</template>diff --git a/resources/js/components/posts/editor/PinterestSettings.vue b/resources/js/components/posts/editor/PinterestSettings.vueindex e3c453bcf..11bd7f2d1 100644--- a/resources/js/components/posts/editor/PinterestSettings.vue+++ b/resources/js/components/posts/editor/PinterestSettings.vue@@ -3,6 +3,7 @@ import { IconAlertTriangle, IconChevronDown, IconChevronUp } from '@tabler/iconsimport { computed, ref } from 'vue';import InputError from '@/components/InputError.vue';+import MediaRulesWarning from '@/components/posts/editor/MediaRulesWarning.vue';import { Avatar } from '@/components/ui/avatar';import {Combobox,@@ -15,12 +16,12 @@ import {ComboboxTrigger,} from '@/components/ui/combobox';import { Input } from '@/components/ui/input';-import { getMediaValidationWarning } from '@/composables/useMedia';import { usePageErrors } from '@/composables/usePageErrors';import { getPlatformLogo } from '@/composables/usePlatformLogo';import type { PinterestBoard } from '@/types';import { ContentType } from '@/types/content-type';import type { MediaItem } from '@/types/media';+import { Platform } from '@/types/platform';interface SocialAccount {id: string;@@ -70,8 +71,6 @@ const pickVariant = (value: string) => {emit('update:contentType', value);};-const warning = computed(() => getMediaValidationWarning(props.contentType, props.media));-const boardOptions = computed<BoardOption[]>(() =>props.boards.map((b) => ({ value: b.id, label: b.name })),);@@ -248,13 +247,7 @@ const linkError = computed<string | undefined>(() => {<InputError :message="linkError" /></div>- <p- v-if="warning"- class="flex items-start gap-2 rounded-lg border-2 border-foreground bg-rose-50 p-2 text-xs font-semibold text-rose-700"- >- <IconAlertTriangle class="mt-0.5 size-3.5 shrink-0" />- {{ $t(`posts.form.warnings.${warning.key}`, warning.params) }}- </p>+ <MediaRulesWarning :content-type="contentType" :media="media" :platform="Platform.Pinterest" /></div></div></template>diff --git a/resources/js/components/posts/editor/PostEditorComposer.vue b/resources/js/components/posts/editor/PostEditorComposer.vueindex f30f5b3ac..7336ea663 100644--- a/resources/js/components/posts/editor/PostEditorComposer.vue+++ b/resources/js/components/posts/editor/PostEditorComposer.vue@@ -2,6 +2,7 @@import {IconAlertTriangle,IconAlt,+ IconExternalLink,IconFileTypePdf,IconGripVertical,IconHash,@@ -26,6 +27,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/compimport { getPlatformLabel, getPlatformLogo } from '@/composables/usePlatformLogo';import { useXLinkDefuser } from '@/composables/useXLinkDefuser';import date from '@/date';+import { mediaLimitsDocsUrl } from '@/lib/docs';import { classify, isDocument, isImage, isVideo, MediaType } from '@/lib/mediaType';import type { MediaItem } from '@/types/media';@@ -326,6 +328,16 @@ const onAltTextSave = (alt: string): void => {<img :src="getPlatformLogo(iss.platform)" :alt="iss.platform" class="size-3 object-contain" /><span class="font-medium">{{ getPlatformLabel(iss.platform) }}:</span><span class="opacity-80">{{ issueLabel(iss.reason) }}</span>+ <a+ :href="mediaLimitsDocsUrl(iss.platform)"+ target="_blank"+ rel="noopener noreferrer"+ class="inline-flex shrink-0 opacity-80 hover:opacity-100"+ :title="$t('posts.edit.compliance.media_limits_docs')"+ :aria-label="$t('posts.edit.compliance.media_limits_docs')"+ >+ <IconExternalLink class="size-3" />+ </a></li></ul></TooltipContent>diff --git a/resources/js/components/posts/editor/PostEditorTabs.vue b/resources/js/components/posts/editor/PostEditorTabs.vueindex 3c4148ec6..471245178 100644--- a/resources/js/components/posts/editor/PostEditorTabs.vue+++ b/resources/js/components/posts/editor/PostEditorTabs.vue@@ -5,6 +5,7 @@ import CommentsTab from '@/components/posts/editor/CommentsTab.vue';import PreviewTab from '@/components/posts/editor/PreviewTab.vue';import ScheduleTab from '@/components/posts/editor/ScheduleTab.vue';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';+import type { PlatformIssue } from '@/composables/usePostCompliance';import type { PinterestBoardsPayload } from '@/types';import type { MediaItem } from '@/types/media';@@ -59,7 +60,7 @@ const props = defineProps<{selectedPlatformIds: string[];platformMeta: Record<string, Record<string, any>>;platformContentTypes: Record<string, string>;- platformIssues: Record<string, string>;+ platformIssues: Record<string, PlatformIssue>;platformConfigs: Record<string, any>;labels: { id: string; name: string; color: string }[];selectedLabelIds: string[];diff --git a/resources/js/components/posts/editor/ScheduleTab.vue b/resources/js/components/posts/editor/ScheduleTab.vueindex e53b6be50..8ebf737e6 100644--- a/resources/js/components/posts/editor/ScheduleTab.vue+++ b/resources/js/components/posts/editor/ScheduleTab.vue@@ -7,6 +7,7 @@ import LabelBadge from '@/components/labels/LabelBadge.vue';import { Badge } from '@/components/ui/badge';import { usePageErrors } from '@/composables/usePageErrors';import { getPlatformLogo } from '@/composables/usePlatformLogo';+import type { PlatformIssue } from '@/composables/usePostCompliance';import { isVideo } from '@/lib/mediaType';import type { PinterestBoard, PinterestBoardsPayload } from '@/types';import type { Channel } from '@/types/channel';@@ -76,7 +77,7 @@ const props = defineProps<{platformConfigs: Record<string, PlatformConfig>;platformMeta: Record<string, Record<string, any>>;platformContentTypes: Record<string, string>;- platformIssues?: Record<string, string>;+ platformIssues?: Record<string, PlatformIssue>;tiktokCreatorInfos?: Record<string, TikTokCreatorInfo> | null;pinterestBoards?: Record<string, PinterestBoardsPayload> | null;media?: MediaItem[];@@ -144,7 +145,8 @@ const channels = computed<Channel[]>(() =>socialAccount: pp.social_account,contentType: props.platformContentTypes[pp.id] ?? pp.content_type ?? '',meta: props.platformMeta[pp.id] ?? {},- issue: props.platformIssues?.[pp.id] ?? null,+ issue: props.platformIssues?.[pp.id]?.message ?? null,+ issueDocsUrl: props.platformIssues?.[pp.id]?.docsUrl ?? null,status: pp.status,contentTypeError: contentTypeErrorFor(pp),publishConfig: getPublishConfig(pp),diff --git a/resources/js/composables/useMedia.ts b/resources/js/composables/useMedia.tsindex 790345e61..2a18885a9 100644--- a/resources/js/composables/useMedia.ts+++ b/resources/js/composables/useMedia.ts@@ -1,6 +1,7 @@import { getMediaRulesForContentType } from '@/composables/useMediaRules';import date from '@/date';-import { isDocument, isGif, isImage, isVideo } from '@/lib/mediaType';+import type { MediaRules } from '@/lib/contentTypeMediaRules';+import { isDocument, isGif, isImage, isMov, isVideo } from '@/lib/mediaType';import type { MediaItem } from '@/types/media';export type { MediaItem } from '@/types/media';@@ -16,15 +17,72 @@ export interface MediaValidationWarning {params: Record<string, string>;}-export const formatBytes = (bytes: number): string => {- if (bytes >= 1024 * 1024 * 1024) return (bytes / (1024 * 1024 * 1024)).toFixed(1) + ' GB';- if (bytes >= 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB';- if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';- return bytes + ' B';+/** Same units and precision as `formatBytes` in ContentTypeCompatibleWithMedia.php, so the editor and the server's 422 agree on the numbers. */+const formatBytes = (bytes: number, decimal = false, precision = 1): string => {+ const unit = decimal ? 1000 : 1024;+ if (bytes >= unit ** 3) return `${(bytes / unit ** 3).toFixed(precision)} GB`;+ if (bytes >= unit ** 2) return `${(bytes / unit ** 2).toFixed(precision)} MB`;+ if (bytes >= unit) return `${(bytes / unit).toFixed(precision)} KB`;+ return `${bytes} B`;+};++/** Caps declared in decimal megabytes (Bluesky) render as "300 MB", not "286 MB"; the cap is whole, the size keeps a decimal. */+const sizeParams = (cap: number, size: number): Record<string, string> => {+ const decimal = cap % 1_000_000 === 0 && cap % (1024 * 1024) !== 0;++ return { max: formatBytes(cap, decimal, 0), current: formatBytes(size, decimal, 1) };};const formatAspect = (ratio: number): string => ratio.toFixed(2);+const warning = (key: string, params: Record<string, string> = {}): MediaValidationWarning => ({ key, params });++const firstWarning = (...candidates: Array<MediaValidationWarning | false | null | undefined>): MediaValidationWarning | null =>+ candidates.find((candidate): candidate is MediaValidationWarning => Boolean(candidate)) ?? null;++const itemConstraintWarning = (item: MediaItem, rules: MediaRules): MediaValidationWarning | null => {+ const size = item.size ?? 0;+ const duration = item.meta?.duration ?? 0;+ const width = item.meta?.width ?? 0;+ const height = item.meta?.height ?? 0;++ if (isDocument(item)) {+ return rules.maxDocumentBytes && size > rules.maxDocumentBytes+ ? warning('document_too_large', sizeParams(rules.maxDocumentBytes, size))+ : null;+ }++ if (isVideo(item)) {+ if (rules.maxVideoBytes && size > rules.maxVideoBytes) {+ return warning('video_too_large', sizeParams(rules.maxVideoBytes, size));+ }++ if (rules.maxVideoDurationSec && duration > rules.maxVideoDurationSec) {+ // Ceil, like the server: a 60.2s clip is over a 60s cap and must not read as "60s".+ return warning('video_too_long', {+ max: date.formatDurationWords(rules.maxVideoDurationSec),+ current: date.formatDurationWords(Math.ceil(duration)),+ });+ }+ } else if (isImage(item) && rules.maxImageBytes && size > rules.maxImageBytes) {+ return warning('image_too_large', sizeParams(rules.maxImageBytes, size));+ }++ if (width > 0 && height > 0 && ! (rules.autoFitsImage && isImage(item))) {+ const ratio = width / height;++ if (rules.aspectRatioMin && ratio < rules.aspectRatioMin) {+ return warning('aspect_ratio_too_narrow', { current: formatAspect(ratio), min: formatAspect(rules.aspectRatioMin) });+ }++ if (rules.aspectRatioMax && ratio > rules.aspectRatioMax) {+ return warning('aspect_ratio_too_wide', { current: formatAspect(ratio), max: formatAspect(rules.aspectRatioMax) });+ }+ }++ return null;+};+/*** Return the first violation found for a given content_type + media list.* Returns null when everything is valid.@@ -34,97 +92,27 @@ export const getMediaValidationWarning = (contentType: string,media: MediaItem[],): MediaValidationWarning | null => {- if (! contentType) return { key: 'no_variant', params: {} };+ if (! contentType) return warning('no_variant');const rules = getMediaRulesForContentType(contentType);const videos = media.filter(isVideo);const documents = media.filter(isDocument);const images = media.filter(isImage);- const gifs = media.filter(isGif);const total = media.length;- if (rules.requiresMedia && total === 0) {- return { key: 'requires_media', params: {} };- }- if (total > rules.maxFiles) {- return { key: 'max_files_exceeded', params: { max: String(rules.maxFiles), current: String(total) } };- }- if (rules.minFiles && total < rules.minFiles) {- return { key: 'min_files_required', params: { min: String(rules.minFiles), current: String(total) } };- }- if (! rules.acceptVideos && videos.length > 0) {- return { key: 'no_video_allowed', params: {} };- }- if (! rules.acceptImages && images.length > 0) {- return { key: 'no_image_allowed', params: {} };- }- if (! rules.acceptDocuments && documents.length > 0) {- return { key: 'no_document_allowed', params: {} };- }- if (rules.forbidsMixedMedia && videos.length > 0 && images.length > 0) {- return { key: 'no_mixed_media', params: {} };- }- if (rules.acceptDocuments && documents.length > 0 && total > 1) {- return { key: 'document_not_alone', params: {} };- }- if (! rules.acceptsGif && gifs.length > 0) {- return { key: 'gif_not_allowed', params: {} };- }-- for (const m of media) {- const size = m.size ?? 0;- const width = m.meta?.width ?? 0;- const height = m.meta?.height ?? 0;- const duration = m.meta?.duration ?? 0;-- if (isDocument(m)) {- if (rules.maxDocumentBytes && size > rules.maxDocumentBytes) {- return {- key: 'document_too_large',- params: { max: formatBytes(rules.maxDocumentBytes), current: formatBytes(size) },- };- }- continue;- }-- if (isVideo(m)) {- if (rules.maxVideoBytes && size > rules.maxVideoBytes) {- return {- key: 'video_too_large',- params: { max: formatBytes(rules.maxVideoBytes), current: formatBytes(size) },- };- }- if (rules.maxVideoDurationSec && duration > rules.maxVideoDurationSec) {- return {- key: 'video_too_long',- params: { max: date.formatDurationWords(rules.maxVideoDurationSec), current: date.formatDurationWords(duration) },- };- }- } else if (rules.maxImageBytes && size > rules.maxImageBytes) {- return {- key: 'image_too_large',- params: { max: formatBytes(rules.maxImageBytes), current: formatBytes(size) },- };- }-- if (width > 0 && height > 0 && ! (rules.autoFitsImage && isImage(m))) {- const ratio = width / height;- if (rules.aspectRatioMin && ratio < rules.aspectRatioMin) {- return {- key: 'aspect_ratio_too_narrow',- params: { current: formatAspect(ratio), min: formatAspect(rules.aspectRatioMin) },- };- }- if (rules.aspectRatioMax && ratio > rules.aspectRatioMax) {- return {- key: 'aspect_ratio_too_wide',- params: { current: formatAspect(ratio), max: formatAspect(rules.aspectRatioMax) },- };- }- }- }-- return null;+ return firstWarning(+ rules.requiresMedia && total === 0 && warning('requires_media'),+ total > rules.maxFiles && warning('max_files_exceeded', { max: String(rules.maxFiles), current: String(total) }),+ total < (rules.minFiles ?? 0) && warning('min_files_required', { min: String(rules.minFiles), current: String(total) }),+ ! rules.acceptVideos && videos.length > 0 && warning('no_video_allowed'),+ ! rules.acceptImages && images.length > 0 && warning('no_image_allowed'),+ ! rules.acceptDocuments && documents.length > 0 && warning('no_document_allowed'),+ rules.forbidsMixedMedia && videos.length > 0 && images.length > 0 && warning('no_mixed_media'),+ rules.acceptDocuments && documents.length > 0 && total > 1 && warning('document_not_alone'),+ ! rules.acceptsGif && media.some(isGif) && warning('gif_not_allowed'),+ ! rules.acceptsMov && media.some(isMov) && warning('mov_not_allowed'),+ ...media.map((item) => itemConstraintWarning(item, rules)),+ );};/**@@ -137,37 +125,19 @@ export const getMediaItemIssue = (item: MediaItem, contentType: string): stringif (! contentType) return null;const rules = getMediaRulesForContentType(contentType);- const itemIsVideo = isVideo(item);- const itemIsDocument = isDocument(item);- const itemIsGif = isGif(item);-- if (itemIsDocument) {- if (! rules.acceptDocuments) return 'no_document_allowed';- const docSize = item.size ?? 0;- if (rules.maxDocumentBytes && docSize > rules.maxDocumentBytes) return 'document_too_large';- return null;- }-- if (itemIsVideo && ! rules.acceptVideos) return 'no_video_allowed';- if (! itemIsVideo && ! rules.acceptImages) return 'no_image_allowed';- if (itemIsGif && ! rules.acceptsGif) return 'gif_not_allowed';-- const size = item.size ?? 0;- if (itemIsVideo && rules.maxVideoBytes && size > rules.maxVideoBytes) return 'video_too_large';- if (! itemIsVideo && rules.maxImageBytes && size > rules.maxImageBytes) return 'image_too_large';-- const duration = item.meta?.duration ?? 0;- if (itemIsVideo && rules.maxVideoDurationSec && duration > rules.maxVideoDurationSec) {- return 'video_too_long';- }- const width = item.meta?.width ?? 0;- const height = item.meta?.height ?? 0;- if (width > 0 && height > 0 && ! (rules.autoFitsImage && isImage(item))) {- const ratio = width / height;- if (rules.aspectRatioMin && ratio < rules.aspectRatioMin) return 'aspect_ratio_too_narrow';- if (rules.aspectRatioMax && ratio > rules.aspectRatioMax) return 'aspect_ratio_too_wide';+ if (isDocument(item)) {+ return firstWarning(+ ! rules.acceptDocuments && warning('no_document_allowed'),+ itemConstraintWarning(item, rules),+ )?.key ?? null;}- return null;+ return firstWarning(+ isVideo(item) && ! rules.acceptVideos && warning('no_video_allowed'),+ ! isVideo(item) && ! rules.acceptImages && warning('no_image_allowed'),+ isGif(item) && ! rules.acceptsGif && warning('gif_not_allowed'),+ isMov(item) && ! rules.acceptsMov && warning('mov_not_allowed'),+ itemConstraintWarning(item, rules),+ )?.key ?? null;};diff --git a/resources/js/composables/useMediaRules.ts b/resources/js/composables/useMediaRules.tsindex 8f63d69c7..e7131ad03 100644--- a/resources/js/composables/useMediaRules.ts+++ b/resources/js/composables/useMediaRules.ts@@ -5,7 +5,7 @@ import {toMediaRules,type MediaRules,} from '@/lib/contentTypeMediaRules';-import { fromMimeType, MediaType } from '@/lib/mediaType';+import { classifyBy, MediaType } from '@/lib/mediaType';export type { MediaRules };@@ -20,6 +20,7 @@ const DEFAULT_RULES: MediaRules = {acceptVideos: true,requiresMedia: false,acceptsGif: false,+ acceptsMov: true,};export const getMediaRulesForContentType = (contentType: string): MediaRules => {@@ -55,7 +56,8 @@ export const useMediaRules = (contentType: Ref<string> | ComputedRef<string>) =>const isValidFileType = computed(() => {return (file: File): boolean => {- const type = fromMimeType(file.type);+ // Windows reports an empty `type` for .mov without QuickTime; the server classifies by extension then, so do the same.+ const type = classifyBy(file.type, file.name);if (type === MediaType.Image && !rules.value.acceptImages) {return false;diff --git a/resources/js/composables/usePostCompliance.ts b/resources/js/composables/usePostCompliance.tsindex 94443b230..010c08b41 100644--- a/resources/js/composables/usePostCompliance.ts+++ b/resources/js/composables/usePostCompliance.ts@@ -1,11 +1,11 @@import { trans } from 'laravel-vue-i18n';import { computed, type ComputedRef, type Ref } from 'vue';-import { getMediaItemIssue, getMediaValidationWarning } from '@/composables/useMedia';import { getMediaRulesForContentType } from '@/composables/useMediaRules';import { getPlatformLabel } from '@/composables/usePlatformLogo';import { useXLinkDefuser } from '@/composables/useXLinkDefuser';+import { mediaLimitsDocsUrl } from '@/lib/docs';import { ContentType } from '@/types/content-type';import type { MediaItem } from '@/types/media';import { Platform } from '@/types/platform';@@ -22,6 +22,14 @@ export interface CompliancePost {post_platforms: CompliancePostPlatform[];}+// Why a channel can't publish as-is. `docsUrl` points at the network's media+// limits when the blocker is the attached media; null for editor-side gaps+// (missing variant, missing text) the docs wouldn't help with.+export interface PlatformIssue {+ message: string;+ docsUrl: string | null;+}+export const PLATFORM_VARIANTS: Record<string, string[]> = {[Platform.Facebook]: [ContentType.FacebookPost, ContentType.FacebookReel, ContentType.FacebookStory],[Platform.Instagram]: [ContentType.InstagramFeed, ContentType.InstagramReel, ContentType.InstagramStory],@@ -107,6 +115,7 @@ const COMPLIANCE_KEY_BY_WARNING: Record<string, string> = {no_mixed_media: 'no_mixed_media',document_not_alone: 'document_not_alone',gif_not_allowed: 'no_gifs',+ mov_not_allowed: 'no_movs',image_too_large: 'image_too_large',video_too_large: 'video_too_large',document_too_large: 'document_too_large',@@ -196,18 +205,18 @@ export const usePostCompliance = (opts: UsePostComplianceOptions) => {return result;});- const platformIssues = computed<Record<string, string>>(() => {- const issues: Record<string, string> = {};+ const platformIssues = computed<Record<string, PlatformIssue>>(() => {+ const issues: Record<string, PlatformIssue> = {};for (const pp of post.value.post_platforms) {const contentType = platformContentTypes.value[pp.id];if (!contentType) {- issues[pp.id] = trans('posts.edit.compliance.no_content_type');+ issues[pp.id] = { message: trans('posts.edit.compliance.no_content_type'), docsUrl: null };continue;}if (CONTENT_TYPES_REQUIRING_TEXT.has(contentType) && content.value.trim() === '') {- issues[pp.id] = trans('posts.edit.compliance.requires_text');+ issues[pp.id] = { message: trans('posts.edit.compliance.requires_text'), docsUrl: null };continue;}@@ -217,7 +226,7 @@ export const usePostCompliance = (opts: UsePostComplianceOptions) => {const isSelected = selectedPlatformIds.value.includes(pp.id);if (!isSelected && firstCompatibleVariant(pp.platform, media.value)) continue;- issues[pp.id] = reason;+ issues[pp.id] = { message: reason, docsUrl: mediaLimitsDocsUrl(pp.platform) };}return issues;@@ -252,7 +261,7 @@ export const usePostCompliance = (opts: UsePostComplianceOptions) => {const mediaReasons = selectedPlatforms.value.filter((pp) => platformIssues.value[pp.id])- .map((pp) => `${pp.platform_name ?? pp.platform}: ${platformIssues.value[pp.id]}`);+ .map((pp) => `${pp.platform_name ?? pp.platform}: ${platformIssues.value[pp.id].message}`);const lengthReasons = contentLengthOverflows.value.map((overflow) => trans('posts.form.content_exceeds_platform', {platform: getPlatformLabel(overflow.platform),diff --git a/resources/js/lib/contentTypeMediaRules.ts b/resources/js/lib/contentTypeMediaRules.tsindex dd771f660..51de5bb4a 100644--- a/resources/js/lib/contentTypeMediaRules.ts+++ b/resources/js/lib/contentTypeMediaRules.ts@@ -9,6 +9,7 @@ export type MediaRules = {acceptDocuments?: boolean;requiresMedia: boolean;acceptsGif: boolean;+ acceptsMov: boolean;forbidsMixedMedia?: boolean;maxImageBytes?: number;maxVideoBytes?: number;@@ -30,6 +31,7 @@ export type ContentTypeMediaRule = {accept_documents: boolean;requires_media: boolean;accepts_gif: boolean;+ accepts_mov: boolean;forbids_mixed_media: boolean;max_image_bytes: number | null;max_video_bytes: number | null;@@ -56,54 +58,22 @@ export const mediaRuleFor = (contentType: string): ContentTypeMediaRule | undefireturn cachedRules?.[contentType];};-export const toMediaRules = (rule: ContentTypeMediaRule): MediaRules => {- const mapped: MediaRules = {- maxFiles: rule.max_files,- acceptImages: rule.accept_images,- acceptVideos: rule.accept_videos,- requiresMedia: rule.requires_media,- acceptsGif: rule.accepts_gif,- };-- if (rule.min_files !== null) {- mapped.minFiles = rule.min_files;- }-- if (rule.accept_documents) {- mapped.acceptDocuments = true;- }-- if (rule.forbids_mixed_media) {- mapped.forbidsMixedMedia = true;- }-- if (rule.max_image_bytes !== null) {- mapped.maxImageBytes = rule.max_image_bytes;- }-- if (rule.max_video_bytes !== null) {- mapped.maxVideoBytes = rule.max_video_bytes;- }-- if (rule.max_document_bytes !== null) {- mapped.maxDocumentBytes = rule.max_document_bytes;- }-- if (rule.max_video_duration_sec !== null) {- mapped.maxVideoDurationSec = rule.max_video_duration_sec;- }-- if (rule.aspect_ratio_min !== null) {- mapped.aspectRatioMin = rule.aspect_ratio_min;- }-- if (rule.aspect_ratio_max !== null) {- mapped.aspectRatioMax = rule.aspect_ratio_max;- }-- if (rule.auto_fits_image) {- mapped.autoFitsImage = true;- }-- return mapped;-};+/** A null cap from the server is simply no cap: every consumer reads the optional fields with `??` / `&&`. */+export const toMediaRules = (rule: ContentTypeMediaRule): MediaRules => ({+ maxFiles: rule.max_files,+ minFiles: rule.min_files ?? undefined,+ acceptImages: rule.accept_images,+ acceptVideos: rule.accept_videos,+ acceptDocuments: rule.accept_documents,+ requiresMedia: rule.requires_media,+ acceptsGif: rule.accepts_gif,+ acceptsMov: rule.accepts_mov,+ forbidsMixedMedia: rule.forbids_mixed_media,+ maxImageBytes: rule.max_image_bytes ?? undefined,+ maxVideoBytes: rule.max_video_bytes ?? undefined,+ maxDocumentBytes: rule.max_document_bytes ?? undefined,+ maxVideoDurationSec: rule.max_video_duration_sec ?? undefined,+ aspectRatioMin: rule.aspect_ratio_min ?? undefined,+ aspectRatioMax: rule.aspect_ratio_max ?? undefined,+ autoFitsImage: rule.auto_fits_image,+});diff --git a/resources/js/lib/docs.ts b/resources/js/lib/docs.tsnew file mode 100644index 000000000..336a4a7ee--- /dev/null+++ b/resources/js/lib/docs.ts@@ -0,0 +1,28 @@+import { Platform, type PlatformValue } from '@/types/platform';++export const DOCS_URL = 'https://docs.trypost.it';++// Anchors of the per-network sections in the media knowledge-base page. The+// two Instagram and two LinkedIn variants share one section each.+const MEDIA_LIMITS_ANCHOR: Record<PlatformValue, string> = {+ [Platform.Instagram]: 'instagram',+ [Platform.InstagramFacebook]: 'instagram',+ [Platform.Facebook]: 'facebook',+ [Platform.Threads]: 'threads',+ [Platform.X]: 'x-twitter',+ [Platform.LinkedIn]: 'linkedin',+ [Platform.LinkedInPage]: 'linkedin',+ [Platform.TikTok]: 'tiktok',+ [Platform.YouTube]: 'youtube',+ [Platform.Pinterest]: 'pinterest',+ [Platform.Bluesky]: 'bluesky',+ [Platform.Mastodon]: 'mastodon',+ [Platform.Discord]: 'discord',+ [Platform.Telegram]: 'telegram',+};++export const mediaLimitsDocsUrl = (platform: string): string => {+ const anchor: string | undefined = MEDIA_LIMITS_ANCHOR[platform as PlatformValue];++ return `${DOCS_URL}/knowledge-base/media${anchor ? `#${anchor}` : ''}`;+};diff --git a/resources/js/lib/mediaType.ts b/resources/js/lib/mediaType.tsindex ef8efdf5f..52f674cf2 100644--- a/resources/js/lib/mediaType.ts+++ b/resources/js/lib/mediaType.ts@@ -19,14 +19,53 @@ export const ALLOWED_MIME_TYPES: Record<MediaType, readonly string[]> = {[MediaType.Document]: ['application/pdf'],};-// Broader than the upload allow-list so already-stored files in legacy formats-// still resolve — mirrors Type::fromExtension() on the backend.-const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif'];-const VIDEO_EXTENSIONS = ['mp4', 'mov', 'avi', 'wmv', 'webm', 'mkv', 'm4v'];-const GIF_MIME = 'image/gif';+const MOV_MIME = 'video/quicktime';const PDF_MIME = 'application/pdf';+const MEDIA_TYPES = Object.values(MediaType);++const isMediaType = (value: unknown): value is MediaType => MEDIA_TYPES.includes(value as MediaType);++// Broader than the upload allow-list so already-stored files in legacy formats+// still resolve. The backend (Type::fromExtension) consults the MIME registry;+// the browser has none, so this is the subset of formats we have seen stored.+const CLASSIFIABLE_EXTENSIONS: Record<MediaType, readonly string[]> = {+ [MediaType.Image]: ['jpg', 'jpeg', 'jfif', 'png', 'gif', 'webp', 'avif', 'bmp', 'tif', 'tiff', 'svg', 'psd', 'heic', 'heif'],+ [MediaType.Video]: ['mp4', 'm4v', 'mov', 'avi', 'wmv', 'webm', 'mkv', 'mpeg', 'mpg', '3gp', 'flv', 'ogv'],+ [MediaType.Document]: ['pdf'],+};++/**+ * A `File.name`, a storage key or a full URL, lower-cased. Only an absolute+ * URL is parsed (to drop the host, `?query` and `#hash`); a bare filename is+ * taken as-is, so `Photo #3.jpg` keeps its extension.+ */+const pathOf = (nameOrPath: string | null | undefined): string => {+ const value = (nameOrPath ?? '').toLowerCase();++ if (! value.includes('://')) {+ return value;+ }++ try {+ return new URL(value).pathname;+ } catch {+ return '';+ }+};++/** Whether the path ends in one of the extensions. The dot is part of the match, so `clip` and `/v1.2/clip` match nothing. */+const hasExtension = (path: string, extensions: readonly string[]): boolean =>+ extensions.some((extension) => path.endsWith(`.${extension}`));++/** Lower-cased `type/subtype` with any `; codecs=…` parameters dropped, so comparisons are exact. */+const normalizeMime = (mime: string | null | undefined): string => (mime ?? '').split(';')[0].trim().toLowerCase();++/** Image and video own their MIME family (`image/*`, `video/*`); Document is `application/pdf` alone. */+const ownsMime = (type: MediaType, mime: string): boolean =>+ type === MediaType.Document ? mime === PDF_MIME : mime.startsWith(`${type}/`);+/** The `accept` attribute value for a file input that takes any media we allow. */export const acceptAttribute = (): string => Object.values(ALLOWED_MIME_TYPES).flat().join(',');@@ -40,28 +79,26 @@ interface ClassifiableMedia {/** Resolve a MediaType from a raw MIME string (e.g. a browser `File.type`). */export const fromMimeType = (mime: string | null | undefined): MediaType | null => {- const value = mime ?? '';+ const normalized = normalizeMime(mime);- if (value.startsWith('image/')) return MediaType.Image;- if (value.startsWith('video/')) return MediaType.Video;- if (value === PDF_MIME) return MediaType.Document;-- return null;+ return MEDIA_TYPES.find((type) => ownsMime(type, normalized)) ?? null;};/** Resolve a MediaType from a filename or path extension. */export const fromExtension = (nameOrPath: string | null | undefined): MediaType | null => {- if (! nameOrPath) return null;-- const ext = nameOrPath.split('.').pop()?.toLowerCase() ?? '';-- if (IMAGE_EXTENSIONS.includes(ext)) return MediaType.Image;- if (VIDEO_EXTENSIONS.includes(ext)) return MediaType.Video;- if (ext === 'pdf') return MediaType.Document;+ const path = pathOf(nameOrPath);- return null;+ return MEDIA_TYPES.find((type) => hasExtension(path, CLASSIFIABLE_EXTENSIONS[type])) ?? null;};+/**+ * Mirror of `Type::classify($mimeType, $path)`: a present MIME decides on its+ * own (an unrecognised one is null, never overridden by the extension); the+ * extension is consulted only when there is no MIME at all.+ */+export const classifyBy = (mime: string | null | undefined, nameOrPath: string | null | undefined): MediaType | null =>+ normalizeMime(mime) === '' ? fromExtension(nameOrPath) : fromMimeType(mime);+/*** Classify a media item. Trusts the server-assigned `type` first, then the MIME,* then falls back to the filename extension so already-stored items still@@ -70,12 +107,7 @@ export const fromExtension = (nameOrPath: string | null | undefined): MediaTypeexport const classify = (item: ClassifiableMedia | null | undefined): MediaType | null => {if (! item) return null;- const explicit = item.type;- if (explicit === MediaType.Image || explicit === MediaType.Video || explicit === MediaType.Document) {- return explicit;- }-- return fromMimeType(item.mime_type) ?? fromExtension(item.original_filename ?? item.path);+ return isMediaType(item.type) ? item.type : classifyBy(item.mime_type, item.original_filename ?? item.path);};export const isImage = (item: ClassifiableMedia | null | undefined): boolean => classify(item) === MediaType.Image;@@ -85,4 +117,7 @@ export const isVideo = (item: ClassifiableMedia | null | undefined): boolean =>export const isDocument = (item: ClassifiableMedia | null | undefined): boolean => classify(item) === MediaType.Document;/** Whether the item is an animated GIF — several platforms treat it specially. */-export const isGif = (item: ClassifiableMedia | null | undefined): boolean => (item?.mime_type ?? '') === GIF_MIME;+export const isGif = (item: ClassifiableMedia | null | undefined): boolean => normalizeMime(item?.mime_type) === GIF_MIME;++export const isMov = (item: ClassifiableMedia | null | undefined): boolean =>+ normalizeMime(item?.mime_type) === MOV_MIME || hasExtension(pathOf(item?.original_filename ?? item?.path), ['mov']);diff --git a/resources/js/lib/videoDuration.ts b/resources/js/lib/videoDuration.tsnew file mode 100644index 000000000..ac62b95e8--- /dev/null+++ b/resources/js/lib/videoDuration.ts@@ -0,0 +1,24 @@+const PROBE_TIMEOUT_MS = 5000;++/** Video duration in seconds from the file's metadata; null when undecodable or timed out. */+export const probeVideoDuration = (file: File): Promise<number | null> =>+ new Promise((resolve) => {+ const video = document.createElement('video');+ const url = URL.createObjectURL(file);++ // Whichever fires first — metadata, error or timeout — settles the promise and releases the element.+ const finish = (duration: number | null): void => {+ clearTimeout(timer);+ video.removeAttribute('src');+ video.load();+ URL.revokeObjectURL(url);+ resolve(duration);+ };++ const timer = setTimeout(() => finish(null), PROBE_TIMEOUT_MS);++ video.preload = 'metadata';+ video.onloadedmetadata = () => finish(Number.isFinite(video.duration) && video.duration > 0 ? video.duration : null);+ video.onerror = () => finish(null);+ video.src = url;+ });diff --git a/resources/js/types/channel.ts b/resources/js/types/channel.tsindex 2ddcda83a..d9aafcbbc 100644--- a/resources/js/types/channel.ts+++ b/resources/js/types/channel.ts@@ -32,6 +32,7 @@ export interface Channel {contentType: string;meta: Record<string, any>;issue?: string | null;+ issueDocsUrl?: string | null;status?: string | null;contentTypeError?: string;publishConfig?: Record<string, any> | null;diff --git a/resources/js/types/index.d.ts b/resources/js/types/index.d.tsindex 8f59036aa..64ec6a704 100644--- a/resources/js/types/index.d.ts+++ b/resources/js/types/index.d.ts@@ -1,6 +1,7 @@import { InertiaLinkProps } from '@inertiajs/vue3';import type { Component } from 'vue';+import type { ContentTypeMediaRule } from '@/lib/contentTypeMediaRules';import type { AuthPlan, Features, PlanOption } from '@/types/plan';import type { WelcomeSummary } from '@/types/welcome';@@ -69,24 +70,6 @@ export interface NavItem {badge?: string;}-export interface ContentTypeMediaRule {- max_files: number;- min_files: number | null;- accept_images: boolean;- accept_videos: boolean;- accept_documents: boolean;- requires_media: boolean;- accepts_gif: boolean;- forbids_mixed_media: boolean;- max_image_bytes: number | null;- max_video_bytes: number | null;- max_document_bytes: number | null;- max_video_duration_sec: number | null;- aspect_ratio_min: number | null;- aspect_ratio_max: number | null;- auto_fits_image: boolean;-}-export interface LegalLinks {terms: string;privacy: string;diff --git a/resources/js/utils/chunkedUpload.ts b/resources/js/utils/chunkedUpload.tsindex cff31b2c0..f4bd13c7b 100644--- a/resources/js/utils/chunkedUpload.ts+++ b/resources/js/utils/chunkedUpload.ts@@ -1,3 +1,6 @@+import { classifyBy, MediaType } from '@/lib/mediaType';+import { probeVideoDuration } from '@/lib/videoDuration';+interface ChunkedUploadOptions {file: File;url: string;@@ -15,7 +18,7 @@ interface ChunkedUploadResult {id: string;path?: string;url: string;- type: string;+ type: MediaType;mime_type?: string;original_filename: string;[key: string]: any;@@ -43,6 +46,10 @@ export const uploadChunked = async (options: ChunkedUploadOptions): Promise<Chunconst uploadId = crypto.randomUUID();let uploadedBytes = 0;+ // The server reads the duration from the file; the browser value is the fallback for containers without one.+ const isVideo = classifyBy(file.type, file.name) === MediaType.Video;+ const duration = isVideo ? await probeVideoDuration(file) : null;+try {for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {const start = chunkIndex * chunkSize;@@ -62,6 +69,7 @@ export const uploadChunked = async (options: ChunkedUploadOptions): Promise<Chunif (model) headers['X-Model'] = model;if (modelId) headers['X-Model-Id'] = modelId;if (collection) headers['X-Collection'] = collection;+ if (duration !== null) headers['X-Media-Duration'] = duration.toFixed(2);const response = await fetch(url, {method: 'POST',diff --git a/routes/app.php b/routes/app.phpindex f4591254d..7bb86e033 100644--- a/routes/app.php+++ b/routes/app.php@@ -235,6 +235,7 @@ Route::middleware(['auth', EnsureAccountReady::class, EnsureHasWorkspace::class]Route::post('assets', [AssetController::class, 'store'])->name('app.assets.store');Route::post('assets/chunked', [AssetController::class, 'storeChunked'])->name('app.assets.store-chunked');Route::post('assets/from-url', [AssetController::class, 'storeFromUrl'])->name('app.assets.store-from-url');+ Route::get('assets/{media}/download', [AssetController::class, 'download'])->name('app.assets.download');Route::delete('assets/{media}', [AssetController::class, 'destroy'])->name('app.assets.destroy');Route::get('assets/unsplash/search', [UnsplashController::class, 'search'])->name('app.assets.unsplash.search');Route::get('assets/unsplash/trending', [UnsplashController::class, 'trending'])->name('app.assets.unsplash.trending');diff --git a/tests/Browser/AuthReviewsTest.php b/tests/Browser/AuthReviewsTest.phpindex 5b9abeb48..fdb9e2593 100644--- a/tests/Browser/AuthReviewsTest.php+++ b/tests/Browser/AuthReviewsTest.php@@ -15,9 +15,22 @@ test('every review renders once for readers and once for the marquee loop', func$page->assertVisible('@auth-reviews');+ // `naturalWidth` is 0 until each photo has loaded.$result = $page->script(<<<'JS'- (() => {- const figures = [...document.querySelectorAll('[data-testid="auth-reviews"] figure')];+ (async () => {+ const select = () => [...document.querySelectorAll('[data-testid="auth-reviews"] figure')];+ const loaded = (figure) => {+ const img = figure.querySelector('img');+ return img !== null && img.complete && img.naturalWidth > 0;+ };++ for (let i = 0; i < 200; i++) {+ const current = select();+ if (current.length > 0 && current.every(loaded)) break;+ await new Promise((r) => setTimeout(r, 50));+ }++ const figures = select();return {total: figures.length,diff --git a/tests/Browser/ChannelMediaIssueTest.php b/tests/Browser/ChannelMediaIssueTest.phpnew file mode 100644index 000000000..a5ac915a1--- /dev/null+++ b/tests/Browser/ChannelMediaIssueTest.php@@ -0,0 +1,113 @@+<?php++declare(strict_types=1);++use App\Enums\PostPlatform\ContentType;+use App\Enums\SocialAccount\Platform;+use App\Enums\UserWorkspace\Role;+use App\Models\Post;+use App\Models\PostPlatform;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;++/**+ * A post carrying a PDF with one deselected X channel. X never accepts a+ * document, so the channel has a media issue before the user touches it.+ */+function seedChannelMediaIssuePost(): PostPlatform+{+ $user = User::factory()->create();+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);+ $workspace->members()->attach($user->id, ['role' => Role::Member->value]);+ $user->update(['current_workspace_id' => $workspace->id]);++ $account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);++ $post = Post::factory()->create([+ 'workspace_id' => $workspace->id,+ 'user_id' => $user->id,+ 'content' => 'hello',+ 'media' => [[+ 'id' => 'd1',+ 'type' => 'document',+ 'mime_type' => 'application/pdf',+ 'path' => 'uploads/deck.pdf',+ 'url' => 'https://cdn.test/deck.pdf',+ 'size' => 1024,+ ]],+ ]);++ $postPlatform = PostPlatform::factory()->disabled()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $account->id,+ 'platform' => Platform::X,+ 'content_type' => ContentType::XPost,+ ]);++ test()->actingAs($user);++ return $postPlatform;+}++function waitForChannelIssueTestId(mixed $page, string $testId): void+{+ waitForChannelIssueCondition($page, $testId, 'el.getBoundingClientRect().height > 0');+}++function waitForChannelIssuePressed(mixed $page, string $testId): void+{+ waitForChannelIssueCondition($page, $testId, "el.getAttribute('aria-pressed') === 'true'");+}++/**+ * Polls from the page (never sleep(): the test's HTTP server only ticks while+ * Pest awaits Playwright) until the element exists and `$condition` holds.+ */+function waitForChannelIssueCondition(mixed $page, string $testId, string $condition): void+{+ $page->script(<<<JS+ (async () => {+ const sel = '[data-testid="{$testId}"]';+ for (let i = 0; i < 100; i++) {+ const el = document.querySelector(sel);+ if (el && ({$condition})) return;+ await new Promise((r) => setTimeout(r, 50));+ }+ })();+ JS);+}++test('a channel the media does not fit stays selectable and shows the issue badge', function () {+ $postPlatform = seedChannelMediaIssuePost();++ $page = visit(route('app.posts.edit', $postPlatform->post));+ waitForChannelIssueTestId($page, "channel-{$postPlatform->id}");++ $page->assertEnabled("@channel-{$postPlatform->id}")+ ->assertAttribute("@channel-{$postPlatform->id}", 'aria-pressed', 'false')+ ->assertPresent("@channel-issue-{$postPlatform->id}");++ $page->click("@channel-{$postPlatform->id}");+ waitForChannelIssuePressed($page, "channel-{$postPlatform->id}");++ $page->assertAttribute("@channel-{$postPlatform->id}", 'aria-pressed', 'true')+ ->assertPresent("@channel-issue-{$postPlatform->id}")+ ->assertNoJavaScriptErrors();+});++test('the channel issue tooltip links to the network section of the media docs', function () {+ $postPlatform = seedChannelMediaIssuePost();++ $page = visit(route('app.posts.edit', $postPlatform->post));+ waitForChannelIssueTestId($page, "channel-{$postPlatform->id}");++ $page->hover("@channel-{$postPlatform->id}");+ waitForChannelIssueTestId($page, "channel-issue-docs-{$postPlatform->id}");++ $page->assertAttribute(+ "@channel-issue-docs-{$postPlatform->id}",+ 'href',+ 'https://docs.trypost.it/knowledge-base/media#x-twitter',+ )->assertNoJavaScriptErrors();+});diff --git a/tests/Feature/Api/PlatformApiTest.php b/tests/Feature/Api/PlatformApiTest.phpindex 16d43b50b..10af71de3 100644--- a/tests/Feature/Api/PlatformApiTest.php+++ b/tests/Feature/Api/PlatformApiTest.php@@ -34,6 +34,7 @@ it('lists content types per platform', function () {'accept_videos','accept_documents','accepts_gif',+ 'accepts_mov','forbids_mixed_media','max_video_duration_sec','max_image_bytes',@@ -51,7 +52,7 @@ it('lists content types per platform', function () {$pinterestTypes = collect($platforms->firstWhere('platform', 'pinterest')['content_types']);expect($instagramTypes->firstWhere('value', 'instagram_reel')['max_video_duration_sec'])->toBe(900);- expect($instagramTypes->firstWhere('value', 'instagram_reel')['max_video_bytes'])->toBe(1 * 1024 * 1024 * 1024);+ expect($instagramTypes->firstWhere('value', 'instagram_reel')['max_video_bytes'])->toBe(300 * 1024 * 1024);expect($instagramTypes->firstWhere('value', 'instagram_reel')['accept_images'])->toBeFalse();expect($facebookTypes->firstWhere('value', 'facebook_reel')['max_video_duration_sec'])->toBe(90);expect($pinterestTypes->firstWhere('value', 'pinterest_carousel')['min_media_count'])->toBe(2);diff --git a/tests/Feature/Api/PostApiPlatformMetaTest.php b/tests/Feature/Api/PostApiPlatformMetaTest.phpindex 2bfac126b..7966ab7ac 100644--- a/tests/Feature/Api/PostApiPlatformMetaTest.php+++ b/tests/Feature/Api/PostApiPlatformMetaTest.php@@ -9,7 +9,9 @@ use App\Jobs\PublishPost;use App\Models\Post;use App\Models\PostPlatform;use App\Models\SocialAccount;+use Illuminate\Http\UploadedFile;use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Facades\Storage;beforeEach(function () {$result = createApiTestToken();@@ -120,6 +122,107 @@ it('rejects publishing a LinkedIn post that mixes a PDF with an image', function->assertJsonValidationErrors(['platforms.0.content_type']);});+it('does not reject a Bluesky post whose stored video is a MOV', function () {+ Queue::fake();++ $bluesky = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Bluesky]);+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'media' => [[+ 'id' => 'vid-1', 'path' => 'medias/clip.mov', 'url' => 'https://example.com/clip.mov',+ 'type' => 'video', 'mime_type' => 'video/quicktime', 'original_filename' => 'clip.mov',+ ]],+ ]);+ PostPlatform::factory()->create([+ 'post_id' => $post->id, 'social_account_id' => $bluesky->id,+ 'platform' => Platform::Bluesky, 'content_type' => ContentType::BlueskyPost, 'enabled' => true,+ ]);++ $this->withHeaders($this->headers)+ ->putJson(route('api.posts.update', $post), [+ 'status' => PostStatus::Scheduled->value,+ 'scheduled_at' => now()->addHour()->toIso8601String(),+ ])+ ->assertSuccessful();+});++it('rejects publishing when the uploaded video runs past the content type duration cap', function () {+ Storage::fake();+ $instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);+ $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);+ $platform = PostPlatform::factory()->create([+ 'post_id' => $post->id, 'social_account_id' => $instagram->id,+ 'platform' => Platform::Instagram, 'content_type' => ContentType::InstagramStory, 'enabled' => true,+ ]);++ // Minimal MP4: ftyp + moov[mvhd v0, timescale 1, duration 90 s]. The server reads the duration itself.+ $mvhd = pack('N', 108).'mvhd'."\0\0\0\0".pack('N', 0).pack('N', 0).pack('N', 1).pack('N', 90).str_repeat("\0", 80);+ $file = UploadedFile::fake()->createWithContent('story.mp4', pack('N', 16).'ftypisom'.pack('N', 0).pack('N', 8 + strlen($mvhd)).'moov'.$mvhd);+ $file->mimeTypeToReport = 'video/mp4';++ $this->withHeaders($this->headers + ['Accept' => 'application/json'])+ ->post(route('api.posts.store-media', $post), ['media' => $file])+ ->assertOk();++ $this->withHeaders($this->headers)+ ->putJson(route('api.posts.update', $post), ['status' => PostStatus::Publishing->value])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['platforms.0.content_type'])+ ->assertJsonFragment(['Video is 1min 30s long, but this post type allows up to 1min.']);+});++it('rejects publishing a LinkedIn post with a GIF', function () {+ $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'media' => [[+ 'id' => 'gif-1', 'path' => 'medias/loop.gif', 'url' => 'https://example.com/loop.gif',+ 'type' => 'image', 'mime_type' => 'image/gif', 'original_filename' => 'loop.gif',+ ]],+ ]);+ $platform = PostPlatform::factory()->create([+ 'post_id' => $post->id, 'social_account_id' => $linkedin->id,+ 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,+ ]);++ $this->withHeaders($this->headers)+ ->putJson(route('api.posts.update', $post), [+ 'status' => PostStatus::Publishing->value,+ 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::LinkedInPost->value]],+ ])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['platforms.0.content_type'])+ ->assertJsonFragment(['This platform does not accept GIF. Remove the GIF or choose a different network.']);+});++it('rejects publishing an Instagram Reel whose stored video exceeds 300 MB', function () {+ $instagram = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'media' => [[+ 'id' => 'vid-1', 'path' => 'medias/reel.mp4', 'url' => 'https://example.com/reel.mp4',+ 'type' => 'video', 'mime_type' => 'video/mp4', 'original_filename' => 'reel.mp4',+ 'size' => 900 * 1024 * 1024,+ ]],+ ]);+ $platform = PostPlatform::factory()->create([+ 'post_id' => $post->id, 'social_account_id' => $instagram->id,+ 'platform' => Platform::Instagram, 'content_type' => ContentType::InstagramReel, 'enabled' => true,+ ]);++ $this->withHeaders($this->headers)+ ->putJson(route('api.posts.update', $post), ['status' => PostStatus::Publishing->value])+ ->assertUnprocessable()+ ->assertJsonValidationErrors([+ 'platforms.0.content_type' => trans('posts.form.warnings.video_too_large', ['max' => '300 MB', 'current' => '900.0 MB']),+ ]);++ expect($post->fresh()->status)->not->toBe(PostStatus::Publishing);+});+it('publishes a valid LinkedIn document without resubmitting content_type', function () {Queue::fake();diff --git a/tests/Feature/Api/PostMediaApiTest.php b/tests/Feature/Api/PostMediaApiTest.phpindex ee6d69c60..caa4cdb6a 100644--- a/tests/Feature/Api/PostMediaApiTest.php+++ b/tests/Feature/Api/PostMediaApiTest.php@@ -67,6 +67,8 @@ it('attaches media from url', function () {expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);expect($this->post->fresh()->media)->toHaveCount(1);++ expect(data_get($this->post->fresh()->media, '0.size'))->toBe(Media::sole()->size)->toBeGreaterThan(0);});it('attaches media from url with alt text', function () {@@ -85,7 +87,8 @@ it('attaches media from url with alt text', function () {->assertOk()->assertJsonPath('attached_count', 1);- expect(data_get($this->post->fresh()->media, '0.meta.alt_text'))->toBe('A red bicycle by a wall');+ // The alt text joins the measured dimensions instead of replacing them.+ expect(data_get($this->post->fresh()->media, '0.meta'))->toEqual(['width' => 1, 'height' => 1, 'alt_text' => 'A red bicycle by a wall']);});it('does not store alt text on a non-image url', function () {@@ -229,6 +232,19 @@ it('uploads a media file and attaches it to the post', function () {expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);expect($this->post->fresh()->media)->toHaveCount(1);+ expect(data_get($this->post->fresh()->media, '0.size'))->toBe(Media::sole()->size)->toBeGreaterThan(0);+});++it('stores the duration read from the video file itself', function () {+ $file = UploadedFile::fake()->createWithContent('clip.mp4', file_get_contents(base_path('tests/fixtures/sample.mp4')));+ $file->mimeTypeToReport = 'video/mp4';++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken, 'Accept' => 'application/json'])+ ->post(route('api.posts.store-media', $this->post), ['media' => $file])+ ->assertOk();++ expect(Media::sole()->meta)->toEqual(['duration' => 1.0])+ ->and(data_get($this->post->fresh()->media, '0.meta.duration'))->toEqual(1.0);});it('rejects upload of an unsupported mime type', function () {@@ -347,6 +363,29 @@ it('persists alt text submitted on a bare external media url', function () {->and(data_get($media, '0.path'))->not->toBeNull();});+it('keeps the measured duration when an external video url is submitted with its own meta', function () {+ $this->socialAccount->update(['is_active' => true]);++ Http::fake([+ '93.184.216.34/clip.mp4' => Http::response(file_get_contents(base_path('tests/fixtures/sample.mp4')), 200, ['Content-Type' => 'video/mp4']),+ ]);++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->postJson(route('api.posts.store'), [+ 'content' => 'External video post',+ // A client-sent duration must not replace the one measured from the downloaded file.+ 'media' => [['url' => 'https://93.184.216.34/clip.mp4', 'meta' => ['alt_text' => 'ignored on video', 'duration' => 9999]]],+ 'platforms' => [+ ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],+ ],+ ])+ ->assertCreated();++ $media = Post::where('content', 'External video post')->firstOrFail()->media;++ expect(data_get($media, '0.meta'))->toEqual(['duration' => 1.0, 'alt_text' => 'ignored on video']);+});+it('rejects creating a post when an external media url cannot be fetched', function () {$this->socialAccount->update(['is_active' => true]);diff --git a/tests/Feature/Api/UploadControllerTest.php b/tests/Feature/Api/UploadControllerTest.phpindex bb2b04356..f328a23c3 100644--- a/tests/Feature/Api/UploadControllerTest.php+++ b/tests/Feature/Api/UploadControllerTest.php@@ -177,6 +177,16 @@ test('stores a video upload via the streaming path', function () {->and(Storage::exists($media->path))->toBeTrue();});+test('stores the duration read from the video file on the signed upload path', function () {+ $token = (string) Str::uuid();+ $file = UploadedFile::fake()->createWithContent('clip.mp4', file_get_contents(base_path('tests/fixtures/sample.mp4')));+ $file->mimeTypeToReport = 'video/mp4';++ $this->post(signedUploadUrl($this->workspace, $token), ['media' => $file])->assertCreated();++ expect(Media::where('upload_token', $token)->sole()->meta)->toEqual(['duration' => 1.0]);+});+test('releases the upload token when media persistence fails', function () {$token = (string) Str::uuid();$file = UploadedFile::fake()->create('clip.mp4', 256, 'video/mp4');diff --git a/tests/Feature/AssetControllerTest.php b/tests/Feature/AssetControllerTest.phpindex 2bfb196cb..d3776abdf 100644--- a/tests/Feature/AssetControllerTest.php+++ b/tests/Feature/AssetControllerTest.php@@ -130,6 +130,38 @@ test('can delete an asset', function () {expect(Media::find($media->id))->toBeNull();});+test('can download an asset from the current workspace', function () {+ $media = $this->workspace->addMedia(UploadedFile::fake()->image('vacation-beach.jpg'), 'assets');++ $response = $this->actingAs($this->user)+ ->get(route('app.assets.download', $media));++ $response->assertOk();+ $response->assertDownload('vacation-beach.jpg');+});++test('cannot download an asset from another workspace', function () {+ $otherWorkspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);++ $media = $otherWorkspace->addMedia(UploadedFile::fake()->image('photo.jpg'), 'assets');++ $response = $this->actingAs($this->user)+ ->get(route('app.assets.download', $media));++ $response->assertForbidden();+});++test('asset download requires authentication', function () {+ $media = $this->workspace->addMedia(UploadedFile::fake()->image('photo.jpg'), 'assets');++ $response = $this->get(route('app.assets.download', $media));++ $response->assertRedirect(route('login'));+});+test('cannot delete asset from another workspace', function () {$otherWorkspace = Workspace::factory()->create(['account_id' => $this->account->id,diff --git a/tests/Feature/ChunkedCloudUploadTest.php b/tests/Feature/ChunkedCloudUploadTest.phpindex ae35fd75e..ab6c6ae50 100644--- a/tests/Feature/ChunkedCloudUploadTest.php+++ b/tests/Feature/ChunkedCloudUploadTest.php@@ -44,7 +44,7 @@ function fakeMp4Bytes(): stringreturn "\0\0\0\x18ftypmp42\0\0\0\0mp42isom".str_repeat("\0", 64);}-function postChunkedAsset(string $fileName, string $content, int $rangeStart = 0, ?int $totalSize = null, ?string $uploadId = null): TestResponse+function postChunkedAsset(string $fileName, string $content, int $rangeStart = 0, ?int $totalSize = null, ?string $uploadId = null, ?string $duration = null): TestResponse{$totalSize ??= strlen($content);$rangeEnd = $rangeStart + strlen($content) - 1;@@ -60,6 +60,10 @@ function postChunkedAsset(string $fileName, string $content, int $rangeStart = 0$headers['HTTP_X_UPLOAD_ID'] = $uploadId;}+ if ($duration !== null) {+ $headers['HTTP_X_MEDIA_DURATION'] = $duration;+ }+return test()->actingAs(test()->user)->call('POST',route('app.assets.store-chunked'),@@ -146,6 +150,18 @@ test('chunked cloud uploader uploads parts and completes multipart', function ()expect(Cache::get('chunked-cloud-upload:id-1'))->toBeNull();});+test('chunked cloud uploader reads a byte range from the stored object', function () {+ $client = Mockery::mock(S3Client::class);+ $client->shouldReceive('getObject')+ ->once()+ ->with(['Bucket' => 'test-bucket', 'Key' => 'medias/clip.mp4', 'Range' => 'bytes=40-55'])+ ->andReturn(new Result(['Body' => 'sixteen bytes!!!']));++ $uploader = new ChunkedCloudUploader(Cache::store(), $client, 'test-bucket', 'r2');++ expect($uploader->readRange('medias/clip.mp4', 40, 16))->toBe('sixteen bytes!!!');+});+test('chunked cloud uploader rejects undersized non-final parts', function () {$uploader = new ChunkedCloudUploader(Cache::store(),@@ -302,6 +318,121 @@ test('chunked upload stores image on local disk', function () {Storage::disk('local')->assertExists(test()->workspace->getMedia('assets')->first()->path);});+// ─── Video duration (server probe, X-Media-Duration fallback) ───++test('chunked upload reads the duration from the assembled file and ignores the browser value', function () {+ config(['filesystems.default' => 'local']);+ Storage::fake('local');+ seedChunkedUploadWorkspace();++ postChunkedAsset('clip.mp4', file_get_contents(base_path('tests/fixtures/sample.mp4')), uploadId: Str::uuid()->toString(), duration: '61.437')->assertSuccessful();++ expect(test()->workspace->getMedia('assets')->first()->meta)->toEqual(['duration' => 1.0]);+});++test('chunked upload falls back to the browser duration when the file carries none', function () {+ config(['filesystems.default' => 'local']);+ Storage::fake('local');+ seedChunkedUploadWorkspace();++ postChunkedAsset('clip.mp4', fakeMp4Bytes(), uploadId: Str::uuid()->toString(), duration: '61.437')->assertSuccessful();++ expect(test()->workspace->getMedia('assets')->first()->meta)->toEqual(['duration' => 61.44]);+});++test('chunked upload probes the duration from object storage on the multipart path', function () {+ config(['filesystems.default' => 's3', 'filesystems.disks.s3.driver' => 's3']);+ Storage::fake('s3');+ seedChunkedUploadWorkspace();++ $bytes = file_get_contents(base_path('tests/fixtures/sample.mp4'));++ $fake = Mockery::mock(ChunkedCloudUploader::class);+ $fake->shouldReceive('shouldUseMultipart')->with('clip.mp4')->andReturn(true);+ $fake->shouldReceive('receiveChunk')->once()->andReturn([+ 'done' => true, 'progress' => 100, 'path' => 'medias/clip.mp4', 'size' => strlen($bytes), 'mime_type' => 'video/mp4',+ ]);+ $fake->shouldReceive('readRange')+ ->with('medias/clip.mp4', Mockery::type('int'), Mockery::type('int'))+ ->andReturnUsing(fn (string $key, int $offset, int $length) => substr($bytes, $offset, $length));+ app()->instance(ChunkedCloudUploader::class, $fake);++ postChunkedAsset('clip.mp4', 'fake-video!!', uploadId: Str::uuid()->toString(), duration: '600')->assertSuccessful();++ expect(test()->workspace->getMedia('assets')->first()->meta)->toEqual(['duration' => 1.0]);+});++test('chunked upload never probes object storage for a non-video on the multipart path', function () {+ config(['filesystems.default' => 's3', 'filesystems.disks.s3.driver' => 's3']);+ Storage::fake('s3');+ seedChunkedUploadWorkspace();++ $fake = Mockery::mock(ChunkedCloudUploader::class);+ $fake->shouldReceive('shouldUseMultipart')->with('deck.pdf')->andReturn(true);+ $fake->shouldReceive('receiveChunk')->once()->andReturn([+ 'done' => true, 'progress' => 100, 'path' => 'medias/deck.pdf', 'size' => 12, 'mime_type' => 'application/pdf',+ ]);+ $fake->shouldNotReceive('readRange');+ app()->instance(ChunkedCloudUploader::class, $fake);++ postChunkedAsset('deck.pdf', '%PDF-1.4 xx', uploadId: Str::uuid()->toString(), duration: '600')->assertSuccessful();++ expect(test()->workspace->getMedia('assets')->first()->meta ?? [])->not->toHaveKey('duration');+});++test('chunked upload stores no duration when the browser reports zero and the file carries none', function () {+ config(['filesystems.default' => 'local']);+ Storage::fake('local');+ seedChunkedUploadWorkspace();++ postChunkedAsset('clip.mp4', fakeMp4Bytes(), uploadId: Str::uuid()->toString(), duration: '0')->assertSuccessful();++ expect(test()->workspace->getMedia('assets')->first()->meta ?? [])->not->toHaveKey('duration');+});++test('chunked upload keeps the browser duration when object storage cannot be probed', function () {+ config(['filesystems.default' => 's3', 'filesystems.disks.s3.driver' => 's3']);+ Storage::fake('s3');+ seedChunkedUploadWorkspace();++ $fake = Mockery::mock(ChunkedCloudUploader::class);+ $fake->shouldReceive('shouldUseMultipart')->with('clip.mp4')->andReturn(true);+ $fake->shouldReceive('receiveChunk')->once()->andReturn([+ 'done' => true, 'progress' => 100, 'path' => 'medias/clip.mp4', 'size' => 12, 'mime_type' => 'video/mp4',+ ]);+ $fake->shouldReceive('readRange')->andThrow(new RuntimeException('range GET failed'));+ app()->instance(ChunkedCloudUploader::class, $fake);++ postChunkedAsset('clip.mp4', 'fake-video!!', uploadId: Str::uuid()->toString(), duration: '600')->assertSuccessful();++ expect(test()->workspace->getMedia('assets')->first()->meta)->toEqual(['duration' => 600.0]);+});++test('chunked upload ignores the duration header on images and without it stores no duration', function () {+ config(['filesystems.default' => 'local']);+ Storage::fake('local');+ seedChunkedUploadWorkspace();++ postChunkedAsset('photo.png', file_get_contents(__DIR__.'/../fixtures/1x1.png'), uploadId: Str::uuid()->toString(), duration: '12')->assertSuccessful();+ postChunkedAsset('clip.mp4', fakeMp4Bytes(), uploadId: Str::uuid()->toString())->assertSuccessful();++ $byName = test()->workspace->getMedia('assets')->get()->keyBy('original_filename');+ expect($byName['photo.png']->meta)->not->toHaveKey('duration');+ expect($byName['clip.mp4']->meta ?? [])->not->toHaveKey('duration');+});++test('chunked upload rejects a non-numeric, negative or absurd duration header', function () {+ config(['filesystems.default' => 'local']);+ Storage::fake('local');+ seedChunkedUploadWorkspace();++ postChunkedAsset('clip.mp4', fakeMp4Bytes(), uploadId: Str::uuid()->toString(), duration: 'abc')->assertUnprocessable();+ postChunkedAsset('clip.mp4', fakeMp4Bytes(), uploadId: Str::uuid()->toString(), duration: '-1')->assertUnprocessable();+ // `numeric` accepts `1e999`, which casts to INF and cannot be JSON-encoded into the meta column.+ postChunkedAsset('clip.mp4', fakeMp4Bytes(), uploadId: Str::uuid()->toString(), duration: '1e999')->assertUnprocessable();+ postChunkedAsset('clip.mp4', fakeMp4Bytes(), uploadId: Str::uuid()->toString(), duration: '86401')->assertUnprocessable();+});+// ─── HTTP: object storage ────────────────────────────────────────test('chunked upload uses multipart for videos on s3 disks', function (string $disk) {diff --git a/tests/Feature/ContentTypeMediaRulesShareTest.php b/tests/Feature/ContentTypeMediaRulesShareTest.phpindex db38a8fa3..8378bc577 100644--- a/tests/Feature/ContentTypeMediaRulesShareTest.php+++ b/tests/Feature/ContentTypeMediaRulesShareTest.php@@ -21,12 +21,13 @@ test('inertia shares content type media rules for the frontend', function () {->assertInertia(fn (AssertableInertia $page) => $page->has('contentTypeMediaRules')->where('contentTypeMediaRules.instagram_reel.max_video_duration_sec', 900)- ->where('contentTypeMediaRules.instagram_reel.max_video_bytes', 1 * 1024 * 1024 * 1024)+ ->where('contentTypeMediaRules.instagram_reel.max_video_bytes', 300 * 1024 * 1024)->where('contentTypeMediaRules.instagram_reel.accept_images', false)->where('contentTypeMediaRules.instagram_feed.requires_media', true)->where('contentTypeMediaRules.discord_message.accepts_gif', true)+ ->where('contentTypeMediaRules.bluesky_post.accepts_mov', true)->where('contentTypeMediaRules.facebook_reel.max_video_duration_sec', 90)- ->where('contentTypeMediaRules.tiktok_video.max_video_duration_sec', null)+ ->where('contentTypeMediaRules.tiktok_video.max_video_duration_sec', 10 * 60)->where('contentTypeMediaRules.linkedin_post.max_document_bytes', 100 * 1024 * 1024));});diff --git a/tests/Feature/Mcp/AttachMediaFromUploadToolTest.php b/tests/Feature/Mcp/AttachMediaFromUploadToolTest.phpindex db14fa4ce..bd84d7667 100644--- a/tests/Feature/Mcp/AttachMediaFromUploadToolTest.php+++ b/tests/Feature/Mcp/AttachMediaFromUploadToolTest.php@@ -72,7 +72,7 @@ test('does not store alt text on a non-image upload', function () {$response->assertOk();expect(data_get($this->post->fresh()->media, '0.type'))->toBe('video')- ->and(data_get($this->post->fresh()->media, '0.meta'))->toBeNull();+ ->and(data_get($this->post->fresh()->media, '0.meta.alt_text'))->toBeNull();});test('rejects alt text over the max length', function () {diff --git a/tests/Feature/Mcp/MediaUploadFlowTest.php b/tests/Feature/Mcp/MediaUploadFlowTest.phpindex 65fbbe74e..7ffc557cc 100644--- a/tests/Feature/Mcp/MediaUploadFlowTest.php+++ b/tests/Feature/Mcp/MediaUploadFlowTest.php@@ -56,4 +56,5 @@ test('agent can request URL, client uploads, agent attaches to post', function (->assertOk();expect($this->post->fresh()->media)->toHaveCount(1);+ expect(data_get($this->post->fresh()->media, '0.size'))->toBeInt()->toBeGreaterThan(0);});diff --git a/tests/Feature/Mcp/PlatformToolTest.php b/tests/Feature/Mcp/PlatformToolTest.phpindex d5f3a7951..58f259912 100644--- a/tests/Feature/Mcp/PlatformToolTest.php+++ b/tests/Feature/Mcp/PlatformToolTest.php@@ -46,6 +46,7 @@ test('list content types returns all platforms with constraints', function () {'accept_videos','accept_documents','accepts_gif',+ 'accepts_mov','forbids_mixed_media','max_video_duration_sec','max_image_bytes',@@ -81,7 +82,7 @@ test('list content types exposes reel max video durations', function () {$pinterestTypes = collect($platforms->firstWhere('platform', 'pinterest')['content_types']);expect($instagramTypes->firstWhere('value', 'instagram_reel')['max_video_duration_sec'])->toBe(900);- expect($instagramTypes->firstWhere('value', 'instagram_reel')['max_video_bytes'])->toBe(1 * 1024 * 1024 * 1024);+ expect($instagramTypes->firstWhere('value', 'instagram_reel')['max_video_bytes'])->toBe(300 * 1024 * 1024);expect($facebookTypes->firstWhere('value', 'facebook_reel')['max_video_duration_sec'])->toBe(90);expect($pinterestTypes->firstWhere('value', 'pinterest_carousel')['min_media_count'])->toBe(2);});diff --git a/tests/Feature/Mcp/PostPlatformMetaToolTest.php b/tests/Feature/Mcp/PostPlatformMetaToolTest.phpindex 910816385..85fd6e244 100644--- a/tests/Feature/Mcp/PostPlatformMetaToolTest.php+++ b/tests/Feature/Mcp/PostPlatformMetaToolTest.php@@ -263,7 +263,58 @@ test('publish post rejects a LinkedIn post that mixes a PDF with an image', func$response = TryPostServer::actingAs($this->user)->tool(PublishPostTool::class, ['post_id' => $post->id]);- $response->assertHasErrors(['A PDF document must be the only attachment.']);+ $response->assertHasErrors(['A PDF must be posted on its own, without other images or videos.']);+});++test('publish post accepts a Bluesky post whose stored video is a MOV', function () {+ Queue::fake();++ $bluesky = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Bluesky]);++ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Draft,+ 'media' => [+ ['id' => 'vid-1', 'path' => 'medias/clip.mov', 'url' => 'https://example.com/clip.mov', 'type' => 'video', 'mime_type' => 'video/quicktime', 'original_filename' => 'clip.mov'],+ ],+ ]);+ PostPlatform::factory()->create([+ 'post_id' => $post->id, 'social_account_id' => $bluesky->id,+ 'platform' => Platform::Bluesky, 'content_type' => ContentType::BlueskyPost, 'enabled' => true,+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(PublishPostTool::class, [+ 'post_id' => $post->id,+ 'scheduled_at' => '2037-12-31T15:30:00Z',+ ]);++ $response->assertOk();+ expect($post->fresh()->status)->toBe(PostStatus::Scheduled);+});++test('publish post rejects an Instagram Reel whose stored video exceeds 300 MB', function () {+ $instagram = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);++ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Draft,+ 'media' => [+ ['id' => 'vid-1', 'path' => 'medias/reel.mp4', 'url' => 'https://example.com/reel.mp4', 'type' => 'video', 'mime_type' => 'video/mp4', 'original_filename' => 'reel.mp4', 'size' => 900 * 1024 * 1024],+ ],+ ]);+ PostPlatform::factory()->create([+ 'post_id' => $post->id, 'social_account_id' => $instagram->id,+ 'platform' => Platform::Instagram, 'content_type' => ContentType::InstagramReel, 'enabled' => true,+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(PublishPostTool::class, ['post_id' => $post->id]);++ $response->assertHasErrors([trans('posts.form.warnings.video_too_large', ['max' => '300 MB', 'current' => '900.0 MB'])]);+ expect($post->fresh()->status)->toBe(PostStatus::Draft);});test('publish post succeeds for a Discord platform with a channel', function () {diff --git a/tests/Feature/Services/Social/XPublisherTest.php b/tests/Feature/Services/Social/XPublisherTest.phpindex 2989c9b76..9628a362f 100644--- a/tests/Feature/Services/Social/XPublisherTest.php+++ b/tests/Feature/Services/Social/XPublisherTest.php@@ -940,7 +940,7 @@ test('x publisher uses chunked upload for images larger than 5MB', function () {&& $request->body() === '{}');});-test('x publisher uses amplify_video category for videos larger than 15MB', function () {+test('x publisher keeps tweet_video category for videos larger than 15MB', function () {$this->post->update(['media' => [[@@ -986,7 +986,7 @@ test('x publisher uses amplify_video category for videos larger than 15MB', funcreturn false;}- return data_get($request->data(), 'media_category') === 'amplify_video'+ return data_get($request->data(), 'media_category') === 'tweet_video'&& data_get($request->data(), 'total_bytes') > 15 * 1024 * 1024;});});diff --git a/tests/Feature/UpdatePostRequestTest.php b/tests/Feature/UpdatePostRequestTest.phpindex de6059bda..113af6dde 100644--- a/tests/Feature/UpdatePostRequestTest.php+++ b/tests/Feature/UpdatePostRequestTest.php@@ -80,6 +80,137 @@ test('publishing a tiktok post with privacy_level passes privacy_level validatio$response->assertSessionDoesntHaveErrors(['platforms.0.meta.privacy_level']);});+test('scheduling a bluesky post with a mov video is not rejected on format', function () {+ $blueskyAccount = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::Bluesky,+ ]);+ $blueskyPlatform = PostPlatform::factory()->create([+ 'post_id' => $this->post->id,+ 'social_account_id' => $blueskyAccount->id,+ 'platform' => Platform::Bluesky,+ 'content_type' => ContentType::BlueskyPost,+ ]);++ $response = $this->actingAs($this->user)+ ->put(route('app.posts.update', $this->post), [+ 'status' => Status::Scheduled->value,+ 'scheduled_at' => now()->addHour()->toIso8601String(),+ 'media' => [[+ 'id' => 'test-media-mov',+ 'path' => 'media/2026-01/clip.mov',+ 'url' => 'https://example.com/media/2026-01/clip.mov',+ 'type' => 'video',+ 'mime_type' => 'video/quicktime',+ 'original_filename' => 'clip.mov',+ ]],+ 'platforms' => [+ ['id' => $blueskyPlatform->id, 'content_type' => ContentType::BlueskyPost->value],+ ],+ ]);++ $response->assertSessionDoesntHaveErrors(['platforms.0.content_type']);+});++test('publishing a bluesky post with an oversized video is rejected server-side', function () {+ $blueskyAccount = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::Bluesky,+ ]);+ $blueskyPlatform = PostPlatform::factory()->create([+ 'post_id' => $this->post->id,+ 'social_account_id' => $blueskyAccount->id,+ 'platform' => Platform::Bluesky,+ 'content_type' => ContentType::BlueskyPost,+ ]);++ $response = $this->actingAs($this->user)+ ->put(route('app.posts.update', $this->post), [+ 'status' => Status::Publishing->value,+ 'media' => [[+ 'id' => 'test-media-big',+ 'path' => 'media/2026-01/big.mp4',+ 'url' => 'https://example.com/media/2026-01/big.mp4',+ 'type' => 'video',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'big.mp4',+ 'size' => 300_000_001,+ ]],+ 'platforms' => [+ ['id' => $blueskyPlatform->id, 'content_type' => ContentType::BlueskyPost->value],+ ],+ ]);++ // Bluesky's cap is decimal, so both numbers render in decimal units.+ $response->assertSessionHasErrors([+ 'platforms.0.content_type' => trans('posts.form.warnings.video_too_large', ['max' => '300 MB', 'current' => '300.0 MB']),+ ]);+});++test('publishing a bluesky post with a video over the duration cap is rejected server-side', function () {+ $blueskyAccount = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::Bluesky,+ ]);+ $blueskyPlatform = PostPlatform::factory()->create([+ 'post_id' => $this->post->id,+ 'social_account_id' => $blueskyAccount->id,+ 'platform' => Platform::Bluesky,+ 'content_type' => ContentType::BlueskyPost,+ ]);++ $response = $this->actingAs($this->user)+ ->put(route('app.posts.update', $this->post), [+ 'status' => Status::Publishing->value,+ 'media' => [[+ 'id' => 'test-media-long',+ 'path' => 'media/2026-01/long.mp4',+ 'url' => 'https://example.com/media/2026-01/long.mp4',+ 'type' => 'video',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'long.mp4',+ 'size' => 50_000_000,+ 'meta' => ['duration' => 601.5],+ ]],+ 'platforms' => [+ ['id' => $blueskyPlatform->id, 'content_type' => ContentType::BlueskyPost->value],+ ],+ ]);++ $response->assertSessionHasErrors(['platforms.0.content_type' => 'Video is 10min 2s long, but this post type allows up to 10min.']);+});++test('saving a draft does not enforce media compatibility', function () {+ $blueskyAccount = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::Bluesky,+ ]);+ $blueskyPlatform = PostPlatform::factory()->create([+ 'post_id' => $this->post->id,+ 'social_account_id' => $blueskyAccount->id,+ 'platform' => Platform::Bluesky,+ 'content_type' => ContentType::BlueskyPost,+ ]);++ $response = $this->actingAs($this->user)+ ->put(route('app.posts.update', $this->post), [+ 'status' => Status::Draft->value,+ 'media' => [[+ 'id' => 'test-media-mov',+ 'path' => 'media/2026-01/clip.mov',+ 'url' => 'https://example.com/media/2026-01/clip.mov',+ 'type' => 'video',+ 'mime_type' => 'video/quicktime',+ 'original_filename' => 'clip.mov',+ ]],+ 'platforms' => [+ ['id' => $blueskyPlatform->id, 'content_type' => ContentType::BlueskyPost->value],+ ],+ ]);++ $response->assertSessionDoesntHaveErrors(['platforms.0.content_type']);+});+test('publishing a pinterest post without board_id is rejected', function () {$pinterestAccount = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id,diff --git a/tests/Unit/Dto/MediaItemTest.php b/tests/Unit/Dto/MediaItemTest.phpindex 63d5e1e20..c1db11661 100644--- a/tests/Unit/Dto/MediaItemTest.php+++ b/tests/Unit/Dto/MediaItemTest.php@@ -3,6 +3,8 @@declare(strict_types=1);use App\Dto\MediaItem;+use App\Models\Media;+use App\Models\Workspace;test('fromArray backfills the mime type from the path extension when missing', function () {expect(MediaItem::fromArray(['path' => 'a/b/photo.JPG'])->mime_type)->toBe('image/jpeg');@@ -84,3 +86,58 @@ test('numeric string dimensions are coerced to integers', function () {expect($item->width())->toBe(1080)->and($item->height())->toBe(1920);});++test('fromMedia builds the stored post media item and carries the measured meta', function () {+ $workspace = Workspace::factory()->create();+ $video = Media::factory()->video()->for($workspace, 'mediable')->create(['meta' => ['duration' => 12.5]]);++ expect(MediaItem::fromMedia($video, 'ignored on video')->toArray())->toEqual([+ 'id' => $video->id,+ 'path' => $video->path,+ 'url' => $video->url,+ 'type' => 'video',+ 'mime_type' => 'video/mp4',+ 'original_filename' => $video->original_filename,+ 'size' => $video->size,+ 'meta' => ['duration' => 12.5],+ ]);+});++test('fromMedia puts alt text in meta for images only and omits an empty meta', function () {+ $workspace = Workspace::factory()->create();+ $image = Media::factory()->for($workspace, 'mediable')->create(['meta' => ['width' => 10, 'height' => 20]]);+ $document = Media::factory()->document()->for($workspace, 'mediable')->create();++ expect(MediaItem::fromMedia($image, 'A red bicycle')->meta)->toEqual(['width' => 10, 'height' => 20, 'alt_text' => 'A red bicycle'])+ ->and(MediaItem::fromMedia($image, '')->meta)->toEqual(['width' => 10, 'height' => 20])+ ->and(MediaItem::fromMedia($document, 'ignored on pdf')->toArray())->not->toHaveKey('meta');+});++test('the stored type wins over a contradicting mime, and older items without one classify by mime then path', function () {+ $typed = MediaItem::fromArray(['type' => 'image', 'mime_type' => 'video/mp4', 'path' => 'medias/clip.mp4']);+ $byMime = MediaItem::fromArray(['mime_type' => 'video/mp4', 'path' => 'medias/photo.jpg']);+ $byPath = MediaItem::fromArray(['path' => 'https://cdn.example.com/medias/clip.mov?sig=1']);++ expect($typed->isImage())->toBeTrue()+ ->and($typed->isVideo())->toBeFalse()+ ->and($byMime->isVideo())->toBeTrue()+ ->and($byPath->isVideo())->toBeTrue()+ ->and($byPath->mime_type)->toBe('video/quicktime');+});++test('a stored item round-trips through fromArray and toArray', function () {+ $stored = [+ 'id' => 'abc',+ 'path' => 'medias/photo.jpg',+ 'url' => 'https://cdn.example.com/photo.jpg',+ 'type' => 'image',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'photo.jpg',+ 'size' => 1234,+ 'meta' => ['width' => 10, 'height' => 20],+ 'source' => 'unsplash',+ 'source_meta' => ['photographer' => 'Ana'],+ ];++ expect(MediaItem::fromArray($stored)->toArray())->toEqual($stored);+});diff --git a/tests/Unit/Enums/ContentTypeTest.php b/tests/Unit/Enums/ContentTypeTest.phpindex aa87067af..496d8f02e 100644--- a/tests/Unit/Enums/ContentTypeTest.php+++ b/tests/Unit/Enums/ContentTypeTest.php@@ -32,7 +32,9 @@ test('content type exposes max video duration in seconds', function () {expect(ContentType::InstagramReel->maxVideoDurationSec())->toBe(15 * 60);expect(ContentType::FacebookReel->maxVideoDurationSec())->toBe(90);expect(ContentType::YouTubeShort->maxVideoDurationSec())->toBe(3 * 60);- expect(ContentType::TikTokVideo->maxVideoDurationSec())->toBeNull();+ expect(ContentType::XPost->maxVideoDurationSec())->toBe(20 * 60);+ expect(ContentType::BlueskyPost->maxVideoDurationSec())->toBe(10 * 60);+ expect(ContentType::TikTokVideo->maxVideoDurationSec())->toBe(10 * 60);});test('media rules for frontend expose the full editor rule set keyed by content type', function () {@@ -45,20 +47,22 @@ test('media rules for frontend expose the full editor rule set keyed by content'accept_images' => false,'accept_videos' => true,'requires_media' => true,- 'max_video_bytes' => 1 * 1024 * 1024 * 1024,+ 'max_video_bytes' => 300 * 1024 * 1024,'max_video_duration_sec' => 900,'aspect_ratio_min' => 0.5,'aspect_ratio_max' => 0.6,]);expect($rules['facebook_reel']['max_video_duration_sec'])->toBe(90);- expect($rules['tiktok_video']['max_video_duration_sec'])->toBeNull();+ expect($rules['tiktok_video']['max_video_duration_sec'])->toBe(10 * 60);expect($rules['linkedin_post']['max_document_bytes'])->toBe(100 * 1024 * 1024);expect($rules['pinterest_carousel']['min_files'])->toBe(2);expect($rules['x_post']['accepts_gif'])->toBeTrue();expect($rules['instagram_feed']['requires_media'])->toBeTrue();expect($rules['discord_message']['accepts_gif'])->toBeTrue();expect($rules['telegram_post']['accepts_gif'])->toBeTrue();+ expect($rules['bluesky_post']['accepts_mov'])->toBeTrue();+ expect($rules['x_post']['accepts_mov'])->toBeTrue();});test('listing array mirrors media capability fields for api and mcp', function () {@@ -198,7 +202,7 @@ test('media rules preserve pre-centralization editor limits for mapped types', f'accepts_gif' => false,'max_files' => 1,'max_video_duration_sec' => 900,- 'max_video_bytes' => min(1 * $gb, $hardVideo),+ 'max_video_bytes' => min(300 * $mb, $hardVideo),],'youtube_short' => ['requires_media' => true,@@ -232,19 +236,49 @@ test('media rules preserve pre-centralization editor limits for mapped types', f'x_post' => ['requires_media' => false,'accepts_gif' => true,+ 'accepts_mov' => true,'max_files' => 4,- 'max_video_duration_sec' => 140,- 'max_video_bytes' => min(512 * $mb, $hardVideo),+ 'max_video_duration_sec' => 20 * 60,+ 'max_video_bytes' => min(8 * $gb, $hardVideo),+ ],+ 'bluesky_post' => [+ 'requires_media' => false,+ 'accepts_gif' => true,+ 'accepts_mov' => true,+ 'max_files' => 4,+ 'max_video_duration_sec' => 10 * 60,+ // Lexicon maxSize is decimal bytes, not MiB. Images are not capped: the publisher re-encodes them under the blob limit.+ 'max_image_bytes' => null,+ 'max_video_bytes' => min(300_000_000, $hardVideo),],'discord_message' => ['requires_media' => false,'accepts_gif' => true,+ 'accepts_mov' => true,'max_files' => 10,+ 'max_image_bytes' => min(20 * $mb, $hardImage),+ 'max_video_bytes' => min(20 * $mb, $hardVideo),],'telegram_post' => ['requires_media' => false,'accepts_gif' => true,+ 'accepts_mov' => true,'max_files' => 10,+ 'max_image_bytes' => min(5 * $mb, $hardImage),+ 'max_video_bytes' => min(20 * $mb, $hardVideo),+ ],+ 'tiktok_video' => [+ 'requires_media' => true,+ 'accepts_gif' => false,+ 'max_files' => 1,+ 'max_video_duration_sec' => 10 * 60,+ 'max_video_bytes' => min(4 * $gb, $hardVideo),+ ],+ 'tiktok_photo' => [+ 'requires_media' => true,+ 'accepts_gif' => false,+ 'max_files' => 35,+ 'max_image_bytes' => min(20 * $mb, $hardImage),],];@@ -285,6 +319,24 @@ test('media byte caps never exceed the global upload hard limits', function () {->and(ContentType::FacebookPost->maxVideoBytes())->toBe($hardVideo);});+test('bluesky caps use the lexicon decimal byte values, not mebibytes', function () {+ config()->set('trypost.media.max_size_mb.image', 1024);+ config()->set('trypost.media.max_size_mb.video', 4096);++ expect(ContentType::BlueskyPost->maxVideoBytes())->toBe(300_000_000)+ ->and(ContentType::BlueskyPost->maxVideoBytes())->toBeLessThan(300 * 1024 * 1024);+});++test('bluesky leaves the original image uncapped because the publisher re-encodes it under the 2 MB blob limit', function () {+ expect(ContentType::BlueskyPost->maxImageBytes())->toBeNull();+});++test('bluesky publisher skip threshold is never below the advertised video cap', function () {+ // Otherwise a video the editor accepted would silently publish as text.+ expect((int) config('trypost.platforms.bluesky.video_max_bytes'))+ ->toBeGreaterThanOrEqual(ContentType::BlueskyPost->maxVideoBytes());+});+test('can get content types for platform', function () {$instagramTypes = ContentType::forPlatform(Platform::Instagram);diff --git a/tests/Unit/Enums/MediaTypeParityTest.php b/tests/Unit/Enums/MediaTypeParityTest.phpnew file mode 100644index 000000000..9ae36dd4a--- /dev/null+++ b/tests/Unit/Enums/MediaTypeParityTest.php@@ -0,0 +1,50 @@+<?php++declare(strict_types=1);++use App\Enums\Media\Type;+use Symfony\Component\Process\ExecutableFinder;+use Symfony\Component\Process\Process;++/**+ * `resources/js/lib/mediaType.ts` mirrors `App\Enums\Media\Type` so the editor can+ * classify media without a round trip. Agreement is asserted rather than assumed:+ * both sides classify the same corpus — explicit type, MIME (cased, with+ * parameters, without a slash), filename, storage key and full URL — and every+ * answer must match.+ */+test('the typescript media classifier agrees with the php enum on every corpus entry', function () {+ $corpusPath = base_path('tests/fixtures/media-type-corpus.json');+ $corpus = json_decode(file_get_contents($corpusPath), true, flags: JSON_THROW_ON_ERROR);++ $node = (new ExecutableFinder)->find('node');++ if ($node === null) {+ $this->markTestSkipped('node is unavailable');+ }++ // mustRun(): a broken harness or a syntax error in mediaType.ts is a failure, not a skip.+ $process = (new Process([+ $node,+ base_path('tests/fixtures/media-type-harness.js'),+ resource_path('js/lib/mediaType.ts'),+ $corpusPath,+ ]))->mustRun();++ $fromPhp = array_map(function (array $item): array {+ $fileName = data_get($item, 'original_filename') ?? data_get($item, 'path');+ $mimeType = data_get($item, 'mime_type');++ return [+ 'type' => (Type::tryFrom((string) data_get($item, 'type', '')) ?? Type::classify($mimeType, $fileName))?->value,+ 'isMov' => Type::isMov($mimeType, $fileName),+ 'isGif' => Type::isGif($mimeType),+ ];+ }, $corpus);++ $fromTypeScript = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);++ $labels = array_map(fn (array $item): string => json_encode($item, JSON_THROW_ON_ERROR), $corpus);++ expect(array_combine($labels, $fromTypeScript))->toEqual(array_combine($labels, $fromPhp));+});diff --git a/tests/Unit/Enums/MediaTypeTest.php b/tests/Unit/Enums/MediaTypeTest.phpindex 446180bb6..ab92f9f0f 100644--- a/tests/Unit/Enums/MediaTypeTest.php+++ b/tests/Unit/Enums/MediaTypeTest.php@@ -10,12 +10,6 @@ test('media type has correct values', function () {expect(Type::Document->value)->toBe('document');});-test('media type has labels', function () {- expect(Type::Image->label())->toBe('Imagem');- expect(Type::Video->label())->toBe('Vídeo');- expect(Type::Document->label())->toBe('Documento');-});-test('media type has allowed mime types', function () {expect(Type::Image->allowedMimeTypes())->toContain('image/jpeg', 'image/png');expect(Type::Video->allowedMimeTypes())->toContain('video/mp4', 'video/quicktime');@@ -46,6 +40,8 @@ test('media type resolves from mime', function () {expect(Type::fromMime('video/mp4'))->toBe(Type::Video);expect(Type::fromMime('application/pdf'))->toBe(Type::Document);expect(Type::fromMime('not-a-mime'))->toBeNull();+ expect(Type::fromMime('image'))->toBeNull();+ expect(Type::fromMime('video'))->toBeNull();});test('media type document max size in mb is read from config', function () {@@ -71,6 +67,18 @@ test('classify falls back to the file extension when the mime is missing', functexpect(Type::classify(null, null))->toBeNull();});+test('extensions outside the upload allow-list still classify but never yield an upload mime', function () {+ // The Symfony registry knows these, so a stored `clip.3gp` is a video for cap/multipart purposes...+ expect(Type::classify(null, 'clip.3gp'))->toBe(Type::Video);+ expect(Type::classify(null, 'clip.flv'))->toBe(Type::Video);+ expect(Type::classify(null, 'layers.psd'))->toBe(Type::Image);+ // ...but the upload path only recognises MIMEs from the allow-list, so these get none.+ expect(Type::mimeTypeFromExtension('3gp'))->toBeNull();+ expect(Type::mimeTypeFromExtension('flv'))->toBeNull();+ expect(Type::mimeTypeFromExtension('psd'))->toBeNull();+ expect(Type::mimeTypeFromExtension('mov'))->toBe('video/quicktime');+});+test('classify prefers the mime over the extension', function () {// A mismatched extension never overrides a present, recognized mime.expect(Type::classify('video/mp4', 'thing.png'))->toBe(Type::Video);@@ -81,6 +89,7 @@ test('classify prefers the mime over the extension', function () {test('fromExtension classifies broadly and is case-insensitive', function () {expect(Type::fromExtension('JPG'))->toBe(Type::Image);expect(Type::fromExtension('webm'))->toBe(Type::Video);+ // The registry also lists `image/pdf` for .pdf; MIME order must win over case order.expect(Type::fromExtension('pdf'))->toBe(Type::Document);expect(Type::fromExtension('txt'))->toBeNull();expect(Type::fromExtension(null))->toBeNull();@@ -96,8 +105,29 @@ test('fromExtension covers every legacy image and video extension', function ()}});+test('mimeTypeFromExtension returns the allow-listed mime, not the registry\'s first guess', function () {+ // The registry lists application/mp4 before video/mp4 and audio/x-ms-wmv before video/x-ms-wmv.+ expect(Type::mimeTypeFromExtension('mp4'))->toBe('video/mp4');+ expect(Type::mimeTypeFromExtension('MOV'))->toBe('video/quicktime');+ expect(Type::mimeTypeFromExtension('jpg'))->toBe('image/jpeg');+ expect(Type::mimeTypeFromExtension('pdf'))->toBe('application/pdf');++ // Classifiable but not accepted on upload — no MIME to claim.+ expect(Type::mimeTypeFromExtension('heic'))->toBeNull();+ expect(Type::mimeTypeFromExtension('txt'))->toBeNull();+ expect(Type::mimeTypeFromExtension(null))->toBeNull();+});+test('isGif only matches the gif mime', function () {expect(Type::isGif('image/gif'))->toBeTrue();expect(Type::isGif('image/png'))->toBeFalse();expect(Type::isGif(null))->toBeFalse();});++test('isMov matches quicktime mime or a mov extension', function () {+ expect(Type::isMov('video/quicktime'))->toBeTrue();+ expect(Type::isMov('video/mp4', 'clip.mov'))->toBeTrue();+ expect(Type::isMov('video/mp4', 'clip.MP4'))->toBeFalse();+ expect(Type::isMov('video/mp4'))->toBeFalse();+ expect(Type::isMov(null))->toBeFalse();+});diff --git a/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php b/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.phpindex 011769f36..ed33a668b 100644--- a/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php+++ b/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php@@ -27,7 +27,7 @@ test('fails when content type requires media and none provided', function () {$errors = runMediaRule(ContentType::InstagramReel->value, []);expect($errors)->toHaveCount(1);- expect($errors[0])->toContain('requires at least one media file');+ expect($errors[0])->toContain('requires at least one image or video');});test('fails when content type does not support images and an image is present', function () {@@ -36,7 +36,7 @@ test('fails when content type does not support images and an image is present',$errors = runMediaRule(ContentType::TikTokVideo->value, $media);expect($errors)->toHaveCount(1);- expect($errors[0])->toContain('does not support images');+ expect($errors[0])->toContain('accepts only videos');});test('fails when content type does not support video and a video is present', function () {@@ -45,7 +45,7 @@ test('fails when content type does not support video and a video is present', fu$errors = runMediaRule(ContentType::PinterestPin->value, $media);expect($errors)->toHaveCount(1);- expect($errors[0])->toContain('does not support videos');+ expect($errors[0])->toContain('does not accept videos');});test('youtube short rejects images', function () {@@ -53,7 +53,7 @@ test('youtube short rejects images', function () {$errors = runMediaRule(ContentType::YouTubeShort->value, $media);- expect($errors[0])->toContain('does not support images');+ expect($errors[0])->toContain('accepts only videos');});test('passes when image-only content type receives an image', function () {@@ -77,7 +77,7 @@ test('facebook story rejects images', function () {$errors = runMediaRule(ContentType::FacebookStory->value, $media);expect($errors)->toHaveCount(1);- expect($errors[0])->toContain('does not support images');+ expect($errors[0])->toContain('accepts only videos');});test('instagram story accepts images', function () {@@ -94,6 +94,27 @@ test('detects media type from mime when type field is missing', function () {expect($errors)->toHaveCount(1);});+test('detects media type from the filename when both type and mime are missing', function () {+ // Same fallback as MediaItem::fromArray(): a video is measured against the video cap, not the image one.+ $overVideoCap = ContentType::MastodonPost->maxVideoBytes() + 1;++ $byPath = runMediaRule(ContentType::MastodonPost->value, [['path' => 'medias/clip.mp4', 'size' => $overVideoCap]]);+ $byName = runMediaRule(ContentType::MastodonPost->value, [['original_filename' => 'Clip.MOV', 'size' => $overVideoCap]]);+ $imageOnly = runMediaRule(ContentType::TikTokVideo->value, [['path' => 'medias/photo.png']]);++ expect($byPath)->toHaveCount(1)->and($byPath[0])->toContain('Video exceeds')+ ->and($byName)->toHaveCount(1)->and($byName[0])->toContain('Video exceeds')+ ->and($imageOnly)->toHaveCount(1)->and($imageOnly[0])->toContain('accepts only videos');+});++test('an explicit type wins over a contradicting mime', function () {+ // Mirrors classify() in mediaType.ts: the server-assigned type is trusted first.+ $media = [['type' => MediaType::Image->value, 'mime_type' => 'video/mp4']];++ expect(runMediaRule(ContentType::TikTokVideo->value, $media))->toHaveCount(1)+ ->and(runMediaRule(ContentType::InstagramStory->value, $media))->toBe([]);+});+test('bluesky rejects an image and a video in the same post', function () {$media = [['type' => MediaType::Image->value, 'mime_type' => 'image/jpeg'],@@ -103,7 +124,7 @@ test('bluesky rejects an image and a video in the same post', function () {$errors = runMediaRule(ContentType::BlueskyPost->value, $media);expect($errors)->toHaveCount(1);- expect($errors[0])->toContain("can't combine an image and a video");+ expect($errors[0])->toContain("can't be combined in the same post");});test('bluesky still accepts an image-only or video-only post', function () {@@ -114,6 +135,151 @@ test('bluesky still accepts an image-only or video-only post', function () {expect(runMediaRule(ContentType::BlueskyPost->value, $video))->toBe([]);});+test('bluesky accepts a mov video', function () {+ $media = [['type' => MediaType::Video->value, 'mime_type' => 'video/quicktime']];++ expect(runMediaRule(ContentType::BlueskyPost->value, $media))->toBe([]);+});++test('bluesky accepts a mov video identified only by filename', function () {+ $media = [['type' => MediaType::Video->value, 'mime_type' => 'video/mp4', 'original_filename' => 'clip.mov']];++ expect(runMediaRule(ContentType::BlueskyPost->value, $media))->toBe([]);+});++test('x still accepts a mov video', function () {+ $media = [['type' => MediaType::Video->value, 'mime_type' => 'video/quicktime']];++ expect(runMediaRule(ContentType::XPost->value, $media))->toBe([]);+});++test('a gif is rejected on content types that do not accept gifs', function () {+ $media = [['type' => MediaType::Image->value, 'mime_type' => 'image/gif']];++ foreach ([ContentType::InstagramFeed, ContentType::LinkedInPost, ContentType::PinterestPin, ContentType::FacebookPost] as $type) {+ $errors = runMediaRule($type->value, $media);++ expect($errors)->toHaveCount(1, $type->value);+ expect($errors[0])->toContain('does not accept GIF');+ }+});++test('a gif passes on content types that accept gifs', function () {+ $media = [['type' => MediaType::Image->value, 'mime_type' => 'image/gif']];++ foreach ([ContentType::XPost, ContentType::BlueskyPost, ContentType::MastodonPost, ContentType::DiscordMessage, ContentType::TelegramPost] as $type) {+ expect(runMediaRule($type->value, $media))->toBe([], $type->value);+ }+});++test('an image over the content type cap is rejected by size', function () {+ $media = [['type' => MediaType::Image->value, 'mime_type' => 'image/jpeg', 'size' => 5 * 1024 * 1024 + 1]];++ $errors = runMediaRule(ContentType::XPost->value, $media);++ expect($errors)->toHaveCount(1);+ expect($errors[0])->toContain('Image exceeds the');+ expect($errors[0])->toContain('5 MB');+});++test('a kind violation is reported alone and is not overwritten by a size violation on the same item', function () {+ // A 6 MB GIF on LinkedIn breaks two rules; the root cause ("does not accept GIF") must be the one message.+ $media = [['type' => MediaType::Image->value, 'mime_type' => 'image/gif', 'size' => 6 * 1024 * 1024]];++ $errors = runMediaRule(ContentType::LinkedInPost->value, $media);++ expect($errors)->toHaveCount(1);+ expect($errors[0])->toContain('GIF');+});++test('an item that cannot be classified is not measured against any cap', function () {+ // An API `url`-only entry before download: no type, mime or filename, but a stray size.+ $media = [['url' => 'https://example.com/asset', 'size' => 999_999_999]];++ expect(runMediaRule(ContentType::XPost->value, $media))->toBe([]);+});++test('bluesky does not cap the original image because the publisher re-encodes it under the blob limit', function () {+ // A phone JPEG well over Bluesky's 2 MB blob limit published fine before caps existed; it must still schedule.+ $media = [['type' => MediaType::Image->value, 'mime_type' => 'image/jpeg', 'size' => 8 * 1024 * 1024]];++ expect(runMediaRule(ContentType::BlueskyPost->value, $media))->toBe([]);+});++test('decimal caps are reported in decimal units for both the cap and the file', function () {+ $media = [['type' => MediaType::Video->value, 'mime_type' => 'video/mp4', 'size' => 305_000_000]];++ $errors = runMediaRule(ContentType::BlueskyPost->value, $media);++ expect($errors)->toHaveCount(1);+ expect($errors[0])->toContain('300 MB limit for this post type (yours is 305.0 MB)');+});++test('binary caps keep binary units', function () {+ $media = [['type' => MediaType::Video->value, 'mime_type' => 'video/mp4', 'size' => 320 * 1024 * 1024]];++ $errors = runMediaRule(ContentType::InstagramReel->value, $media);++ expect($errors)->toHaveCount(1);+ expect($errors[0])->toContain('300 MB limit for this post type (yours is 320.0 MB)');+});++test('an image exactly at the content type cap passes', function () {+ $media = [['type' => MediaType::Image->value, 'mime_type' => 'image/jpeg', 'size' => 5 * 1024 * 1024]];++ expect(runMediaRule(ContentType::XPost->value, $media))->toBe([]);+});++test('a video over the content type cap is rejected by size', function () {+ $media = [['type' => MediaType::Video->value, 'mime_type' => 'video/mp4', 'size' => 300 * 1024 * 1024 + 1]];++ $errors = runMediaRule(ContentType::InstagramReel->value, $media);++ expect($errors)->toHaveCount(1);+ expect($errors[0])->toContain('Video exceeds the');+});++test('a pdf over the content type cap is rejected by size', function () {+ $max = ContentType::LinkedInPost->maxDocumentBytes();+ $media = [['type' => MediaType::Document->value, 'mime_type' => 'application/pdf', 'size' => $max + 1]];++ $errors = runMediaRule(ContentType::LinkedInPost->value, $media);++ expect($errors)->toHaveCount(1);+ expect($errors[0])->toContain('PDF exceeds the');+});++test('media without a size is not checked against byte caps', function () {+ $media = [['type' => MediaType::Video->value, 'mime_type' => 'video/mp4']];++ expect(runMediaRule(ContentType::InstagramReel->value, $media))->toBe([]);+});++test('a video longer than the content type cap is rejected by duration', function () {+ $media = [['type' => MediaType::Video->value, 'mime_type' => 'video/mp4', 'meta' => ['duration' => 61.4]]];++ $errors = runMediaRule(ContentType::InstagramStory->value, $media);++ expect($errors)->toHaveCount(1);+ expect($errors[0])->toContain('allows up to 1min');+ expect($errors[0])->toContain('Video is 1min 2s long');+});++test('a video within the duration cap passes and a video without duration is not checked', function () {+ $within = [['type' => MediaType::Video->value, 'mime_type' => 'video/mp4', 'meta' => ['duration' => 60]]];+ $unknown = [['type' => MediaType::Video->value, 'mime_type' => 'video/mp4', 'meta' => []]];++ expect(runMediaRule(ContentType::InstagramStory->value, $within))->toBe([]);+ expect(runMediaRule(ContentType::InstagramStory->value, $unknown))->toBe([]);+});++test('duration is ignored on content types without a duration cap', function () {+ $media = [['type' => MediaType::Video->value, 'mime_type' => 'video/mp4', 'meta' => ['duration' => 3 * 60 * 60]]];++ expect(ContentType::DiscordMessage->maxVideoDurationSec())->toBeNull();+ expect(runMediaRule(ContentType::DiscordMessage->value, $media))->toBe([]);+});+test('bluesky rejects an animated gif combined with a video', function () {// A GIF counts as an image, so gif + video is still mixed media.$media = [@@ -124,7 +290,7 @@ test('bluesky rejects an animated gif combined with a video', function () {$errors = runMediaRule(ContentType::BlueskyPost->value, $media);expect($errors)->toHaveCount(1);- expect($errors[0])->toContain("can't combine an image and a video");+ expect($errors[0])->toContain("can't be combined in the same post");});test('a mixed-media content type accepts an image and a video together', function () {@@ -158,7 +324,7 @@ test('a pdf must be the only attachment on linkedin', function () {$errors = runMediaRule(ContentType::LinkedInPost->value, $media);expect($errors)->toHaveCount(1);- expect($errors[0])->toContain('must be the only attachment');+ expect($errors[0])->toContain('must be posted on its own');});test('linkedin rejects mixing an image and a video', function () {@@ -170,7 +336,7 @@ test('linkedin rejects mixing an image and a video', function () {$errors = runMediaRule(ContentType::LinkedInPost->value, $media);expect($errors)->toHaveCount(1);- expect($errors[0])->toContain("can't combine an image and a video");+ expect($errors[0])->toContain("can't be combined in the same post");});test('a pdf is rejected on content types that do not support documents', function () {@@ -179,7 +345,7 @@ test('a pdf is rejected on content types that do not support documents', functio$errors = runMediaRule(ContentType::XPost->value, $media);expect($errors)->toHaveCount(1);- expect($errors[0])->toContain('does not support PDF documents');+ expect($errors[0])->toContain('does not accept PDF documents');});test('falls back to stored media when the request omits the media key', function () {@@ -202,7 +368,7 @@ test('falls back to stored media when the request omits the media key', function});expect($xErrors)->toHaveCount(1);- expect($xErrors[0])->toContain('does not support PDF documents');+ expect($xErrors[0])->toContain('does not accept PDF documents');});test('request media takes precedence over the stored fallback', function () {@@ -219,7 +385,7 @@ test('request media takes precedence over the stored fallback', function () {});expect($errors)->toHaveCount(1);- expect($errors[0])->toContain('must be the only attachment');+ expect($errors[0])->toContain('must be posted on its own');});test('does nothing for invalid content type values', function () {diff --git a/tests/Unit/Support/VideoDurationProbeTest.php b/tests/Unit/Support/VideoDurationProbeTest.phpnew file mode 100644index 000000000..c5cc918d7--- /dev/null+++ b/tests/Unit/Support/VideoDurationProbeTest.php@@ -0,0 +1,160 @@+<?php++declare(strict_types=1);++use App\Support\VideoDurationProbe;++function probeAtom(string $type, string $payload, bool $largesize = false): string+{+ if ($largesize) {+ return pack('N', 1).$type.pack('J', 16 + strlen($payload)).$payload;+ }++ return pack('N', 8 + strlen($payload)).$type.$payload;+}++function probeMvhd(int $timescale, int $duration, int $version = 0): string+{+ $payload = $version === 1+ ? "\x01\0\0\0".pack('J', 0).pack('J', 0).pack('N', $timescale).pack('J', $duration)+ : "\0\0\0\0".pack('N', 0).pack('N', 0).pack('N', $timescale).pack('N', $duration);++ return probeAtom('mvhd', $payload.str_repeat("\0", 80));+}++function probeMp4(string ...$atoms): string+{+ return implode('', $atoms);+}++function probeReader(string $bytes): Closure+{+ return fn (int $offset, int $length): string => substr($bytes, $offset, $length);+}++test('reads the duration from the real fixture whose moov follows mdat', function () {+ expect(VideoDurationProbe::fromFile(base_path('tests/fixtures/sample.mp4')))->toBe(1.0);+});++test('reads real ffmpeg output: a QuickTime .mov and a version 1 mvhd', function () {+ // Both values were cross-checked against `ffprobe -show_entries format=duration`.+ expect(VideoDurationProbe::fromFile(base_path('tests/fixtures/sample.mov')))->toBe(2.5)+ ->and(VideoDurationProbe::fromFile(base_path('tests/fixtures/sample-mvhd-v1.mp4')))->toBe(2_400_000.0);+});++test('treats the all-ones "unknown" duration as missing in both mvhd versions', function () {+ $v0 = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('moov', probeMvhd(1000, 0xFFFFFFFF)));+ $v1 = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('moov', probeMvhd(1000, -1, version: 1)));++ expect(VideoDurationProbe::fromReader(probeReader($v0), strlen($v0)))->toBeNull()+ ->and(VideoDurationProbe::fromReader(probeReader($v1), strlen($v1)))->toBeNull();+});++test('reads a moov-first file', function () {+ $bytes = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('moov', probeMvhd(600, 45_000)), probeAtom('mdat', str_repeat('x', 100)));++ expect(VideoDurationProbe::fromReader(probeReader($bytes), strlen($bytes)))->toBe(75.0);+});++test('reads a version 1 mvhd with 64-bit duration', function () {+ $bytes = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('moov', probeMvhd(1000, 7_215_000, version: 1)));++ expect(VideoDurationProbe::fromReader(probeReader($bytes), strlen($bytes)))->toBe(7215.0);+});++test('skips a largesize mdat and a trailing size-zero atom', function () {+ $bytes = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('mdat', str_repeat('x', 64), largesize: true), pack('N', 0).'moov'.probeMvhd(30, 90));++ expect(VideoDurationProbe::fromReader(probeReader($bytes), strlen($bytes)))->toBe(3.0);+});++test('returns null when there is no mvhd, the duration is zero, or the bytes are not a video', function () {+ $noMvhd = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('moov', probeAtom('udta', 'x')));+ $fragmented = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('moov', probeMvhd(1000, 0)));++ expect(VideoDurationProbe::fromReader(probeReader($noMvhd), strlen($noMvhd)))->toBeNull()+ ->and(VideoDurationProbe::fromReader(probeReader($fragmented), strlen($fragmented)))->toBeNull()+ ->and(VideoDurationProbe::fromReader(probeReader('not a video at all'), 18))->toBeNull()+ ->and(VideoDurationProbe::fromReader(probeReader(''), 0))->toBeNull();+});++test('stops on a truncated or malformed atom header instead of looping', function () {+ $truncated = probeAtom('ftyp', 'isom').pack('N', 5000).'moov';+ $zeroSized = probeAtom('ftyp', 'isom').pack('N', 4).'moov'.probeMvhd(1, 1);++ expect(VideoDurationProbe::fromReader(probeReader($truncated), strlen($truncated)))->toBeNull()+ ->and(VideoDurationProbe::fromReader(probeReader($zeroSized), strlen($zeroSized)))->toBeNull();+});++test('reads only atom headers, never the mdat payload', function () {+ $bytes = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('mdat', str_repeat('x', 1_000_000)), probeAtom('moov', probeMvhd(1, 12)));+ $bytesRead = 0;++ $duration = VideoDurationProbe::fromReader(function (int $offset, int $length) use ($bytes, &$bytesRead): string {+ $bytesRead += $length;++ return substr($bytes, $offset, $length);+ }, strlen($bytes));++ expect($duration)->toBe(12.0)+ ->and($bytesRead)->toBeLessThan(200);+});++test('stops reading once mvhd is found and takes the first one, not the last', function () {+ // Two mvhd atoms: the first is the real one; the trailing `trak`s and the second mvhd must never be read.+ $moov = probeAtom('moov', probeMvhd(1, 12).probeAtom('trak', str_repeat('t', 64)).probeAtom('trak', str_repeat('t', 64)).probeMvhd(1, 99));+ $bytes = probeMp4(probeAtom('ftyp', 'isom'), $moov);+ $offsets = [];++ $duration = VideoDurationProbe::fromReader(function (int $offset, int $length) use ($bytes, &$offsets): string {+ $offsets[] = $offset;++ return substr($bytes, $offset, $length);+ }, strlen($bytes));++ // ftyp header, moov header, mvhd header, mvhd payload — and nothing past the first mvhd.+ expect($duration)->toBe(12.0)+ ->and($offsets)->toHaveCount(4)+ ->and(max($offsets))->toBeLessThan(strpos($bytes, 'trak'));+});++test('gives up after a bounded number of atoms so a padded upload cannot fan out into thousands of reads', function () {+ // 10k empty `free` atoms in front of moov: every header would be one ranged GET on object storage.+ $padding = str_repeat(probeAtom('free', ''), 10_000);+ $bytes = probeMp4(probeAtom('ftyp', 'isom'), $padding, probeAtom('moov', probeMvhd(1, 12)));+ $reads = 0;++ $duration = VideoDurationProbe::fromReader(function (int $offset, int $length) use ($bytes, &$reads): string {+ $reads++;++ return substr($bytes, $offset, $length);+ }, strlen($bytes));++ expect($duration)->toBeNull()+ ->and($reads)->toBeLessThanOrEqual(64);+});++test('returns null for an unreadable path', function () {+ expect(VideoDurationProbe::fromFile('/nonexistent/clip.mp4'))->toBeNull();+});++test('merges a positive duration into meta and leaves the rest untouched', function () {+ expect(VideoDurationProbe::mergeInto(['width' => 1920], 1.239))+ ->toBe(['width' => 1920, 'duration' => 1.24])+ ->and(VideoDurationProbe::mergeInto(['width' => 1920], null))->toBe(['width' => 1920])+ ->and(VideoDurationProbe::mergeInto(['width' => 1920], 0.0))->toBe(['width' => 1920])+ ->and(VideoDurationProbe::mergeInto(['width' => 1920], -3.0))->toBe(['width' => 1920])+ ->and(VideoDurationProbe::mergeInto(['width' => 1920], INF))->toBe(['width' => 1920])+ ->and(VideoDurationProbe::mergeInto(['width' => 1920], NAN))->toBe(['width' => 1920]);+});++test('returns null for a zero timescale or an mvhd payload shorter than its version needs', function () {+ $zeroTimescale = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('moov', probeMvhd(0, 1000)));+ // Version 1 needs 32 bytes; this payload declares v1 but carries only the v0 length.+ $shortV1 = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('moov', probeAtom('mvhd', "\x01".str_repeat("\0", 19))));+ $shortV0 = probeMp4(probeAtom('ftyp', 'isom'), probeAtom('moov', probeAtom('mvhd', str_repeat("\0", 8))));++ expect(VideoDurationProbe::fromReader(probeReader($zeroTimescale), strlen($zeroTimescale)))->toBeNull()+ ->and(VideoDurationProbe::fromReader(probeReader($shortV1), strlen($shortV1)))->toBeNull()+ ->and(VideoDurationProbe::fromReader(probeReader($shortV0), strlen($shortV0)))->toBeNull();+});diff --git a/tests/fixtures/media-type-corpus.json b/tests/fixtures/media-type-corpus.jsonnew file mode 100644index 000000000..bb005fd5b--- /dev/null+++ b/tests/fixtures/media-type-corpus.json@@ -0,0 +1,52 @@+[+ { "type": "image", "mime_type": "image/jpeg", "original_filename": "photo.jpg" },+ { "type": "video", "mime_type": "video/mp4", "original_filename": "clip.mp4" },+ { "type": "document", "mime_type": "application/pdf", "original_filename": "deck.pdf" },+ { "type": "image", "mime_type": "video/mp4" },+ { "type": "audio", "mime_type": "audio/mpeg", "original_filename": "song.mp3" },+ { "mime_type": "image/png" },+ { "mime_type": "image/heic" },+ { "mime_type": "video/quicktime" },+ { "mime_type": "video/x-msvideo" },+ { "mime_type": "application/pdf" },+ { "mime_type": "application/zip", "original_filename": "clip.mp4" },+ { "mime_type": "application/octet-stream", "original_filename": "clip.mp4" },+ { "mime_type": "Video/MP4" },+ { "mime_type": "video/mp4; codecs=\"avc1.42E01E\"" },+ { "mime_type": " image/gif " },+ { "mime_type": "IMAGE/GIF" },+ { "mime_type": "image" },+ { "mime_type": "video" },+ { "mime_type": "not-a-mime" },+ { "mime_type": "", "original_filename": "photo.PNG" },+ { "mime_type": null, "path": "medias/clip.mkv" },+ { "original_filename": "deck.pdf" },+ { "original_filename": "Photo #3.jpg" },+ { "original_filename": "what?.mp4" },+ { "original_filename": "IMG #1.MOV" },+ { "original_filename": "clip.mov" },+ { "original_filename": "Clip.Mov", "mime_type": "video/mp4" },+ { "original_filename": "archive.zip" },+ { "original_filename": "README.md" },+ { "original_filename": "clip" },+ { "original_filename": "/v1.2/clip" },+ { "original_filename": "clip.", "path": "medias/x.mp4" },+ { "path": "medias/0b1c.webp" },+ { "path": "medias/0b1c.MP4" },+ { "path": "medias/legacy.3gp" },+ { "path": "medias/legacy.mpeg" },+ { "path": "medias/legacy.mpg" },+ { "path": "medias/legacy.flv" },+ { "path": "medias/legacy.ogv" },+ { "path": "medias/legacy.tiff" },+ { "path": "medias/legacy.tif" },+ { "path": "medias/legacy.jfif" },+ { "path": "medias/legacy.avif" },+ { "path": "medias/legacy.psd" },+ { "original_filename": "", "path": "medias/clip.mp4" },+ { "url": "https://cdn.example.com/asset", "size": 999 },+ { "path": "https://cdn.example.com/medias/clip.mov?X-Amz-Signature=abc#frag" },+ { "path": "https://cdn.example.com/medias/photo.jpg?download=1" },+ { "original_filename": "clip.mp4", "path": "medias/photo.jpg" },+ {}+]diff --git a/tests/fixtures/media-type-harness.js b/tests/fixtures/media-type-harness.jsnew file mode 100644index 000000000..8c55139a4--- /dev/null+++ b/tests/fixtures/media-type-harness.js@@ -0,0 +1,23 @@+/**+ * Runs `resources/js/lib/mediaType.ts` over a corpus of media items and prints+ * `{ type, isMov, isGif }` per entry as JSON, so `MediaTypeParityTest.php` can+ * diff the TypeScript against `App\Enums\Media\Type`, which it mirrors.+ *+ * Node 22 strips type annotations on import, so the source is loaded as-is —+ * no bundler, and nothing in `mediaType.ts` may depend on the DOM.+ */+import fs from 'node:fs';+import path from 'node:path';+import { pathToFileURL } from 'node:url';++const [mediaTypeFile, corpusFile] = process.argv.slice(2);++const { classify, isMov, isGif } = await import(pathToFileURL(path.resolve(mediaTypeFile)).href);++const results = JSON.parse(fs.readFileSync(corpusFile, 'utf8')).map((item) => ({+ type: classify(item),+ isMov: isMov(item),+ isGif: isGif(item),+}));++console.log(JSON.stringify(results));diff --git a/tests/fixtures/sample-mvhd-v1.mp4 b/tests/fixtures/sample-mvhd-v1.mp4new file mode 100644index 000000000..1f029e8fcBinary files /dev/null and b/tests/fixtures/sample-mvhd-v1.mp4 differdiff --git a/tests/fixtures/sample.mov b/tests/fixtures/sample.movnew file mode 100644index 000000000..b50803a17Binary files /dev/null and b/tests/fixtures/sample.mov differ