Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

17.7 KB
Raw Blame
<?php

declare(strict_types=1);

use App\Dto\MediaItem;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Models\Media;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

test('an Instagram media warning links to the network limits', function () {
    [$post] = seedInstagramFeedImagePost(size: 9 * 1024 * 1024);

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, '@media-rules-warning');

    expect($page->script('document.querySelector("[data-testid=media-rules-warning] a")?.href'))
        ->toBe('https://docs.trypost.it/knowledge-base/media#instagram');
    $page->assertNoJavaScriptErrors();
});

/**
 * @param  array<string, string>  $platformMeta
 * @param  array<string, int>  $imageMeta
 * @return array{Post}
 */
function seedInstagramFeedImagePost(array $platformMeta = [], array $imageMeta = ['width' => 1080, 'height' => 1600], int $size = 1024, int $imageCount = 5, Platform $platform = Platform::Instagram): array
{
    $user = User::factory()->create();
    $workspace = Workspace::factory()->create(['user_id' => $user->id]);
    $workspace->members()->attach($user->id, membershipPivot('member'));
    $user->update(['current_workspace_id' => $workspace->id]);

    $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => $platform]);
    $post = Post::factory()->forAccount($account, $platform === Platform::Facebook ? ContentType::FacebookPost : ContentType::InstagramFeed)->create([
        'user_id' => $user->id,
        'meta' => $platformMeta,
        'content' => 'A five-image carousel',
        'media' => array_map(fn (int $index): array => [
            'id' => "image-{$index}",
            'type' => 'image',
            'mime_type' => 'image/jpeg',
            'path' => "uploads/image-{$index}.jpg",
            'url' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
            'size' => $size,
            'meta' => $imageMeta,
        ], range(1, $imageCount)),
    ]);
    test()->actingAs($user);

    return [$post];
}

test('Instagram feed has no global aspect control and asks to adjust unsupported images', function () {
    [$post] = seedInstagramFeedImagePost();

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, '@post-composer-dialog');

    $page->assertMissing('@instagram-aspect-original')
        ->assertMissing('@instagram-aspect-1-1')
        ->assertVisible('@instagram-image-aspect-issue-0')
        ->assertDisabled('@composer-submit')
        ->assertVisible('@instagram-edit-image-0');

    waitFor($page, '@instagram-feed-media');
    $heightToWidth = $page->script('(() => { const frame = document.querySelector("[data-testid=instagram-feed-media]"); const rect = frame.getBoundingClientRect(); return rect.height / rect.width; })()');
    expect(abs($heightToWidth - 1600 / 1080))->toBeLessThan(0.01);

    $page->assertNoJavaScriptErrors();
});

test('Facebook has no aspect ratio selector and accepts an image of any ratio', function (int $width, int $height) {
    [$post] = seedInstagramFeedImagePost(imageMeta: ['width' => $width, 'height' => $height], imageCount: 1, platform: Platform::Facebook);

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, "@composer-account-{$post->social_account_id}");

    expect($page->script('document.querySelectorAll("[data-testid^=facebook-aspect-]").length'))->toBe(0);

    $page->assertMissing('@media-rules-warning')
        ->assertEnabled('@composer-submit')
        ->assertNoJavaScriptErrors();
})->with([
    'very tall' => [800, 3200],
]);

test('saving an Instagram post stores no global aspect ratio', function () {
    [$post] = seedInstagramFeedImagePost([], ['width' => 1080, 'height' => 1350], imageCount: 1);
    $asset = Media::factory()->ownedByPost($post)->create([
        'meta' => ['width' => 1080, 'height' => 1350],
    ]);
    $post->update(['media' => [MediaItem::fromMedia($asset)->toArray()]]);
    Storage::put($asset->path, (string) file_get_contents(base_path('tests/fixtures/1x1.png')));

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, '@composer-save-draft');

    $page->assertMissing('@instagram-aspect-original')
        ->assertMissing('@instagram-image-aspect-issue-0')
        ->click('@composer-save-draft')
        ->assertNoJavaScriptErrors();

    waitForGone($page, '@post-composer-dialog');

    expect($page->script('Boolean(document.querySelector("[data-testid=post-composer-dialog]"))'))->toBeFalse();
    expect(data_get($post->fresh()->meta, 'aspect_ratio'))->toBeNull();

    Storage::delete([$asset->path, ...$post->ownedMedia()->pluck('path')->all()]);
});

test('Instagram original preview falls back to square when image dimensions are unavailable', function () {
    [$post] = seedInstagramFeedImagePost(imageMeta: []);

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, '@instagram-feed-media');

    $heightToWidth = $page->script('(() => { const frame = document.querySelector("[data-testid=instagram-feed-media]"); const rect = frame.getBoundingClientRect(); return rect.height / rect.width; })()');

    expect(abs($heightToWidth - 1.0))->toBeLessThan(0.01);
});

test('supported Instagram original image keeps its own aspect and can publish', function (int $height) {
    [$post] = seedInstagramFeedImagePost(imageMeta: ['width' => 1080, 'height' => $height]);

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, '@post-composer-dialog');

    $page->assertMissing('@instagram-image-aspect-issue-0')
        ->assertEnabled('@composer-submit')
        ->assertNoJavaScriptErrors();
})->with([
    '3:4, accepted by the Graph API although its docs still say 4:5' => [1440],
]);

test('Instagram image adjustment offers supported crop presets and clears the original warning', function () {
    [$post] = seedInstagramFeedImagePost(imageCount: 1);

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, '@instagram-edit-image-0');

    $page->click('@instagram-edit-image-0')
        ->assertVisible('@crop-aspect-4-5')
        ->assertVisible('@crop-aspect-1-1')
        ->assertVisible('@crop-aspect-1-91-1')
        ->assertVisible('@crop-aspect-3-4')
        ->click('@crop-aspect-1-1')
        ->click('@media-editor-apply');

    waitForGone($page, '@instagram-image-aspect-issue-0');
    waitForGone($page, '@media-editor-apply');

    $page->assertMissing('@instagram-image-aspect-issue-0')
        ->assertEnabled('@composer-submit')
        ->assertNoJavaScriptErrors();
});

test('Instagram image editor saves alt text on the selected slide', function () {
    [$post] = seedInstagramFeedImagePost(imageCount: 1);
    $asset = Media::factory()->ownedByPost($post)->create([
        'meta' => ['width' => 1080, 'height' => 1600],
    ]);
    $post->update(['media' => [MediaItem::fromMedia($asset)->toArray()]]);
    Storage::put($asset->path, (string) file_get_contents(base_path('tests/fixtures/1x1.png')));

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, '@instagram-edit-image-0');

    $page->click('@instagram-edit-image-0')
        ->click('@media-editor-alt-tab')
        ->fill('@media-editor-alt-text', 'A bright room with a wooden table')
        ->click('@media-editor-apply')
        ->click('@composer-save-draft')
        ->assertNoJavaScriptErrors();

    waitForGone($page, '@post-composer-dialog');

    expect($page->script('Boolean(document.querySelector("[data-testid=post-composer-dialog]"))'))->toBeFalse();
    expect(data_get($post->fresh()->media, '0.meta.alt_text'))
        ->toBe('A bright room with a wooden table');

    Storage::delete([$asset->path, ...$post->ownedMedia()->pluck('path')->all()]);
});

test('appearance filter saves a new image without cropping its original dimensions', function () {
    [$post] = seedInstagramFeedImagePost(imageMeta: ['width' => 200, 'height' => 200], imageCount: 1);
    $base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $media = $post->media;
    $media[0]['url'] = "data:image/png;base64,{$base64}";
    $post->update(['media' => $media]);

    $page = visit(route('app.posts.edit', $post));

    waitFor($page, "@composer-{$post->social_account_id}-edit-0");
    $page->click("@composer-{$post->social_account_id}-edit-0")
        ->click('@media-editor-appearance-section')
        ->click('@media-filter-mono');

    $page->script(<<<'JS'
        const slider = document.querySelector('[data-testid="media-adjust-brightness"]');
        slider.value = '50';
        slider.dispatchEvent(new Event('input', { bubbles: true }));
    JS);

    $page->assertSee('50%')
        ->assertEnabled('@media-editor-apply')
        ->click('@media-editor-apply');

    waitForCondition($page, "!document.querySelector('[data-testid=\"media-editor-apply\"]') && !document.querySelector('[data-testid=\"composer-save-draft\"]')?.disabled");

    $newAsset = Media::where('workspace_id', $post->workspace_id)->where('collection', Media::COLLECTION_UPLOADS)->sole();
    $image = imagecreatefromstring(Storage::get($newAsset->path));
    expect($image)->toBeInstanceOf(GdImage::class)
        ->and(imagesx($image))->toBe(200)
        ->and(imagesy($image))->toBe(200);

    $pixel = imagecolorsforindex($image, imagecolorat($image, 50, 50));
    expect(abs($pixel['red'] - $pixel['green']))->toBeLessThan(5)
        ->and(abs($pixel['green'] - $pixel['blue']))->toBeLessThan(5)
        ->and($pixel['red'])->toBeGreaterThan(70);
});

test('a media ratio warning names the destination with the same message the server returns', function () {
    [$post] = seedInstagramFeedImagePost(imageCount: 1);
    $post->update(['media' => [[
        'id' => 'reel-1',
        'type' => 'video',
        'mime_type' => 'video/mp4',
        'path' => 'uploads/reel.mp4',
        'url' => 'https://cdn.test/reel.mp4',
        'size' => 1024,
        'meta' => ['width' => 2200, 'height' => 200, 'duration' => 10],
    ]]]);
    $post->update(['content_type' => ContentType::InstagramReel]);

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, '@media-rules-warning');

    $message = trans('posts.form.warnings.aspect_ratio_too_wide', [
        'destination' => ContentType::InstagramReel->destinationLabel(),
        'current' => '11.00',
        'max' => '10.00',
    ]);

    expect(trim((string) $page->script('document.querySelector("[data-testid=media-rules-warning] span")?.firstChild?.textContent')))
        ->toBe($message);
    $page->assertNoJavaScriptErrors();
});

test('an Instagram feed post without media shows the inline warning once, under the post type', function () {
    [$post] = seedInstagramFeedImagePost();
    $post->update(['media' => []]);

    $page = visit(route('app.posts.edit', $post));
    $warning = "composer-media-warning-{$post->social_account_id}";
    waitFor($page, "@{$warning}");

    $page->assertSeeIn("@{$warning}", 'Please include an image or video.')
        ->assertMissing('@media-rules-warning')
        ->assertDisabled('@composer-submit')
        ->assertNoJavaScriptErrors();
});

/**
 * @param  array<string, mixed>  $overrides
 * @return array<string, mixed>
 */
function channelMediaIssueItem(string $id, array $overrides = []): array
{
    return [
        'id' => $id,
        'type' => 'image',
        'mime_type' => 'image/jpeg',
        'path' => "uploads/{$id}.jpg",
        'url' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
        'size' => 1024,
        'meta' => ['width' => 1080, 'height' => 1080],
        ...$overrides,
    ];
}

/**
 * @param  array<string, mixed>  $attributes
 */
function seedChannelMediaIssuePost(Platform $platform, ContentType $type, array $attributes): Post
{
    $user = User::factory()->create();
    $workspace = Workspace::factory()->create(['user_id' => $user->id]);
    $workspace->members()->attach($user->id, membershipPivot('member'));
    $user->update(['current_workspace_id' => $workspace->id]);

    $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => $platform]);
    $post = Post::factory()->forAccount($account, $type)->create(['user_id' => $user->id, ...$attributes]);
    test()->actingAs($user);

    return $post;
}

test('a thread reply says why its media is refused', function (Platform $platform, ContentType $type) {
    $post = seedChannelMediaIssuePost($platform, $type, [
        'content' => 'The thread starts here',
        'media' => [],
        'meta' => ['thread_replies' => [[
            'text' => 'Five photos in one reply',
            'media' => array_map(fn (int $index): array => channelMediaIssueItem("reply-photo-{$index}"), range(1, 5)),
        ]]],
    ]);

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, '@media-rules-warning');

    $page->assertSeeIn('@media-rules-warning', __('posts.form.warnings.max_files_exceeded', ['max' => '4', 'current' => '5']))
        ->assertDisabled('@composer-submit')
        ->assertNoJavaScriptErrors();
})->with([
    'X' => [Platform::X, ContentType::XPost],
    'Bluesky' => [Platform::Bluesky, ContentType::BlueskyPost],
    'Mastodon' => [Platform::Mastodon, ContentType::MastodonPost],
]);

test('a warning about the post\'s media as a whole shows once, above the editor', function () {
    $post = seedChannelMediaIssuePost(Platform::LinkedIn, ContentType::LinkedInPost, [
        'content' => 'A photo next to a video',
        'media' => [
            channelMediaIssueItem('photo-1'),
            channelMediaIssueItem('video-1', ['type' => 'video', 'mime_type' => 'video/mp4', 'path' => 'uploads/video-1.mp4', 'meta' => ['duration' => 10]]),
        ],
    ]);

    $page = visit(route('app.posts.edit', $post));
    $warning = "composer-media-warning-{$post->social_account_id}";
    waitFor($page, "@{$warning}");

    $page->assertSeeIn("@{$warning}", __('posts.form.warnings.no_mixed_media'))
        ->assertMissing('@media-rules-warning')
        ->assertNoJavaScriptErrors();
});

test('every network says why its media is refused inside its card', function (Platform $platform, ContentType $type, array $item, string $warning, string $docsAnchor) {
    $post = seedChannelMediaIssuePost($platform, $type, ['content' => 'A file this network refuses', 'media' => [$item]]);

    $page = visit(route('app.posts.edit', $post));
    waitFor($page, '@media-rules-warning');

    expect((string) $page->script('document.querySelector("[data-testid=media-rules-warning] span")?.firstChild?.textContent'))
        ->toContain(Str::before(__("posts.form.warnings.{$warning}"), ':'))
        ->and($page->script('document.querySelector("[data-testid=media-rules-warning] a")?.href'))
        ->toBe("https://docs.trypost.it/knowledge-base/media#{$docsAnchor}");
    $page->assertDisabled('@composer-submit')
        ->assertNoJavaScriptErrors();
})->with(function (): array {
    $tooLargeImage = channelMediaIssueItem('photo-1', ['size' => 60 * 1024 * 1024]);
    $tooLargeVideo = channelMediaIssueItem('video-1', ['type' => 'video', 'mime_type' => 'video/mp4', 'path' => 'uploads/video-1.mp4', 'size' => 2 * 1024 * 1024 * 1024, 'meta' => ['duration' => 10]]);
    $gif = channelMediaIssueItem('gif-1', ['mime_type' => 'image/gif', 'path' => 'uploads/gif-1.gif']);

    return [
        'Facebook' => [Platform::Facebook, ContentType::FacebookPost, $tooLargeImage, 'image_too_large', 'facebook'],
        'Instagram' => [Platform::Instagram, ContentType::InstagramFeed, $tooLargeImage, 'image_too_large', 'instagram'],
        'Instagram via Facebook' => [Platform::InstagramFacebook, ContentType::InstagramFeed, $tooLargeImage, 'image_too_large', 'instagram'],
        'Threads' => [Platform::Threads, ContentType::ThreadsPost, $gif, 'gif_not_allowed', 'threads'],
        'X' => [Platform::X, ContentType::XPost, $tooLargeImage, 'image_too_large', 'x-twitter'],
        'LinkedIn' => [Platform::LinkedIn, ContentType::LinkedInPost, $tooLargeImage, 'image_too_large', 'linkedin'],
        'LinkedIn Page' => [Platform::LinkedInPage, ContentType::LinkedInPagePost, $tooLargeImage, 'image_too_large', 'linkedin'],
        'TikTok' => [Platform::TikTok, ContentType::TikTokVideo, $tooLargeVideo, 'video_too_large', 'tiktok'],
        'YouTube' => [Platform::YouTube, ContentType::YouTubeShort, $tooLargeVideo, 'video_too_large', 'youtube'],
        'Pinterest' => [Platform::Pinterest, ContentType::PinterestPin, $tooLargeImage, 'image_too_large', 'pinterest'],
        'Bluesky' => [Platform::Bluesky, ContentType::BlueskyPost, $tooLargeVideo, 'video_too_large', 'bluesky'],
        'Mastodon' => [Platform::Mastodon, ContentType::MastodonPost, $tooLargeImage, 'image_too_large', 'mastodon'],
        'Telegram' => [Platform::Telegram, ContentType::TelegramPost, $tooLargeImage, 'image_too_large', 'telegram'],
        'Discord' => [Platform::Discord, ContentType::DiscordMessage, $tooLargeImage, 'image_too_large', 'discord'],
        'Google Business' => [Platform::GoogleBusiness, ContentType::GoogleBusinessPost, $gif, 'gif_not_allowed', 'google-business-profile'],
    ];
});

test('a post type that takes no media says so once, above the editor', function () {
    $post = seedChannelMediaIssuePost(Platform::X, ContentType::XPoll, [
        'content' => 'Which one?',
        'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]],
        'media' => [channelMediaIssueItem('photo-1')],
    ]);

    $page = visit(route('app.posts.edit', $post));
    $warning = "composer-text-only-warning-{$post->social_account_id}";
    waitFor($page, "@{$warning}");

    $page->assertSeeIn("@{$warning}", __('posts.form.warnings.text_only'))
        ->assertMissing('@media-rules-warning')
        ->assertNoJavaScriptErrors();
});