Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
<?php
declare(strict_types=1);
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ContentLimitException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\MastodonPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\MastodonPublisher;
use App\Support\Social\ThreadProgress;
use Illuminate\Support\Facades\Http;
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->socialAccount = SocialAccount::factory()->mastodon()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => '123456789',
'username' => 'testuser',
]);
$this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Hello from Mastodon!',
'content_type' => ContentType::MastodonPost,
]);
$this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new MastodonPublisher;
});
test('mastodon publisher can publish text-only post', function () {
Http::fake([
'https://mastodon.social/api/v1/statuses' => Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
'content' => '<p>Hello from Mastodon!</p>',
'created_at' => now()->toIso8601String(),
], 200),
]);
$result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
expect($result['id'])->toBe('109876543210');
expect($result['url'])->toBe('https://mastodon.social/@testuser/109876543210');
Http::assertSent(function ($request) {
return str_contains($request->url(), '/api/v1/statuses')
&& $request['status'] === 'Hello from Mastodon!'
&& $request['visibility'] === 'public';
});
});
test('mastodon publisher works with custom instance', function () {
$this->socialAccount->update([
'meta' => [
'instance' => 'https://techhub.social',
'client_id' => 'test-client-id',
'client_secret' => 'test-client-secret',
],
]);
Http::fake([
'https://techhub.social/api/v1/statuses' => Http::response([
'id' => '987654321',
'url' => 'https://techhub.social/@testuser/987654321',
], 200),
]);
$result = $this->publisher->publish($this->post);
expect($result['url'])->toContain('techhub.social');
Http::assertSent(function ($request) {
return str_contains($request->url(), 'techhub.social');
});
});
test('mastodon publisher uploads media', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-id',
'path' => 'media/2026-01/test-image.jpg',
'url' => 'https://example.com/media/2026-01/test-image.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'test.jpg',
],
],
]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'masto_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake([
'https://example.com/*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png')),
'https://mastodon.social/api/v1/media' => Http::response([
'id' => 'media-123',
'type' => 'image',
'url' => 'https://mastodon.social/media/image.jpg',
], 200),
'https://mastodon.social/api/v1/statuses' => Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200),
]);
$this->publisher->publish($this->post);
Http::assertSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses')
&& data_get($request->data(), 'media_ids') === ['media-123']);
});
test('mastodon publisher sends capped alt text as media description', function () {
// Minimal 1x1 JPEG bytes so mime_content_type() detects image/jpeg
$minimalJpeg = "\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00"
."\xFF\xDB\x00\x43\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\x09\x09\x08\x0A\x0C"
."\x14\x0D\x0C\x0B\x0B\x0C\x19\x12\x13\x0F\x14\x1D\x1A\x1F\x1E\x1D\x1A\x1C\x1C\x20"
."\xFF\xC0\x00\x0B\x08\x00\x01\x00\x01\x01\x01\x11\x00\xFF\xC4\x00\x1F\x00\x00\x01"
."\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05"
."\xFF\xDA\x00\x08\x01\x01\x00\x00\x3F\x00\xFB\xD3\xFF\xD9";
$optimizedFile = tempnam(sys_get_temp_dir(), 'masto_alt_opt_');
file_put_contents($optimizedFile, str_repeat('x', 1024));
$longAlt = str_repeat('a', 2000);
$this->post->update([
'media' => [
[
'id' => 'test-media-id',
'path' => 'media/2026-01/test-image.jpg',
'url' => 'https://example.com/media/2026-01/test-image.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'test.jpg',
'meta' => ['alt_text' => $longAlt],
],
],
]);
$this->mock(MediaOptimizer::class)
->shouldReceive('optimizeImage')
->once()
->with(Mockery::any(), Platform::Mastodon)
->andReturn($optimizedFile);
Http::fake(function ($request) use ($minimalJpeg) {
$url = $request->url();
if (str_contains($url, '/api/v1/media')) {
return Http::response([
'id' => 'media-alt-123',
'type' => 'image',
'url' => 'https://mastodon.social/media/image.jpg',
], 200);
}
if (str_contains($url, '/api/v1/statuses')) {
return Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200);
}
// Media download: return valid JPEG so mime_content_type() detects image/jpeg
return Http::response($minimalJpeg, 200, ['Content-Type' => 'image/jpeg']);
});
$this->publisher->publish($this->post);
$expectedDescription = mb_substr($longAlt, 0, Platform::Mastodon->altTextMaxLength());
Http::assertSent(function ($request) use ($expectedDescription) {
if (! str_contains($request->url(), '/api/v1/media')) {
return false;
}
$description = collect($request->data())->firstWhere('name', 'description');
return $description !== null
&& $description['contents'] === $expectedDescription
&& mb_strlen($description['contents']) === 1500;
});
@unlink($optimizedFile);
});
test('mastodon publisher sends no description part when image has no alt text', function () {
// Minimal 1x1 JPEG bytes so mime_content_type() detects image/jpeg
$minimalJpeg = "\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00"
."\xFF\xDB\x00\x43\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\x09\x09\x08\x0A\x0C"
."\x14\x0D\x0C\x0B\x0B\x0C\x19\x12\x13\x0F\x14\x1D\x1A\x1F\x1E\x1D\x1A\x1C\x1C\x20"
."\xFF\xC0\x00\x0B\x08\x00\x01\x00\x01\x01\x01\x11\x00\xFF\xC4\x00\x1F\x00\x00\x01"
."\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05"
."\xFF\xDA\x00\x08\x01\x01\x00\x00\x3F\x00\xFB\xD3\xFF\xD9";
$optimizedFile = tempnam(sys_get_temp_dir(), 'masto_no_alt_opt_');
file_put_contents($optimizedFile, str_repeat('x', 1024));
$this->post->update([
'media' => [
[
'id' => 'test-media-id',
'path' => 'media/2026-01/test-image.jpg',
'url' => 'https://example.com/media/2026-01/test-image.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'test.jpg',
],
],
]);
$this->mock(MediaOptimizer::class)
->shouldReceive('optimizeImage')
->once()
->with(Mockery::any(), Platform::Mastodon)
->andReturn($optimizedFile);
Http::fake(function ($request) use ($minimalJpeg) {
$url = $request->url();
if (str_contains($url, '/api/v1/media')) {
return Http::response([
'id' => 'media-no-alt-123',
'type' => 'image',
'url' => 'https://mastodon.social/media/image.jpg',
], 200);
}
if (str_contains($url, '/api/v1/statuses')) {
return Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200);
}
// Media download: return valid JPEG so mime_content_type() detects image/jpeg
return Http::response($minimalJpeg, 200, ['Content-Type' => 'image/jpeg']);
});
$this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/api/v1/media')) {
return false;
}
return collect($request->data())->firstWhere('name', 'description') === null;
});
@unlink($optimizedFile);
});
test('mastodon publisher sends the alt text of a video as its media description', function () {
$this->post->update([
'media' => [
[
'id' => 'test-media-video',
'path' => 'media/2026-01/clip.mp4',
'url' => 'https://example.com/media/2026-01/clip.mp4',
'mime_type' => 'video/mp4',
'original_filename' => 'clip.mp4',
'meta' => ['alt_text' => 'a cyclist crossing a bridge'],
],
],
]);
Http::fake(function ($request) {
$url = $request->url();
if (str_contains($url, '/api/v1/media')) {
return Http::response([
'id' => 'media-video-123',
'type' => 'video',
'url' => 'https://mastodon.social/media/clip.mp4',
], 200);
}
if (str_contains($url, '/api/v1/statuses')) {
return Http::response([
'id' => '109876543211',
'url' => 'https://mastodon.social/@testuser/109876543211',
], 200);
}
return Http::response('fake-video-content', 200);
});
$this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/api/v1/media')) {
return false;
}
return data_get(collect($request->data())->firstWhere('name', 'description'), 'contents') === 'a cyclist crossing a bridge';
});
});
test('mastodon publisher includes media ids in post', function () {
Http::fake([
'https://mastodon.social/api/v1/statuses' => Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200),
]);
$this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/api/v1/statuses')
&& $request['visibility'] === 'public';
});
});
test('mastodon publisher throws exception on api error', function () {
Http::fake([
'https://mastodon.social/api/v1/statuses' => Http::response([
'error' => 'Validation failed: Text can\'t be blank',
], 422),
]);
expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
test('mastodon publisher throws token expired exception on auth error', function () {
Http::fake([
'https://mastodon.social/api/v1/statuses' => Http::response([
'error' => 'The access token is invalid',
], 401),
]);
expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
test('mastodon publisher throws permission exception on forbidden', function () {
Http::fake([
'https://mastodon.social/api/v1/statuses' => Http::response([
'error' => 'This action is not allowed',
], 403),
]);
expect(fn () => $this->publisher->publish($this->post))
->toThrow(MastodonPublishException::class);
});
test('mastodon publisher limits media to 4', function () {
$mediaItems = [];
for ($i = 0; $i < 6; $i++) {
$mediaItems[] = [
'id' => "test-media-{$i}",
'path' => "media/2026-01/test-image-{$i}.jpg",
'url' => "https://example.com/media/2026-01/test-image-{$i}.jpg",
'mime_type' => 'image/jpeg',
'original_filename' => "test-{$i}.jpg",
];
}
$this->post->update([
'media' => $mediaItems]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'masto_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake([
'https://example.com/*' => fn () => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png')),
'https://mastodon.social/api/v1/media' => Http::response([
'id' => 'media-123',
'type' => 'image',
], 200),
'https://mastodon.social/api/v1/statuses' => Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200),
]);
$this->publisher->publish($this->post);
Http::assertSentCount(9);
Http::assertSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses')
&& count(data_get($request->data(), 'media_ids', [])) === 4);
});
test('mastodon publisher handles empty content', function () {
$this->post->update(['content' => '']);
Http::fake([
'https://mastodon.social/api/v1/statuses' => Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200),
]);
$result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('109876543210');
Http::assertSent(function ($request) {
return $request['status'] === '';
});
});
test('mastodon publisher uses bearer token authentication', function () {
Http::fake([
'https://mastodon.social/api/v1/statuses' => Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200),
]);
$this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return $request->hasHeader('Authorization')
&& str_starts_with($request->header('Authorization')[0], 'Bearer ');
});
});
test('mastodon publisher optimizes images before upload', function () {
// Create a temp file with a valid JPEG so mime_content_type() detects image/jpeg
$optimizedFile = tempnam(sys_get_temp_dir(), 'masto_opt_');
file_put_contents($optimizedFile, str_repeat('x', 1024));
// Minimal 1x1 JPEG bytes so mime_content_type() returns image/jpeg for the downloaded file
$minimalJpeg = "\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00"
."\xFF\xDB\x00\x43\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\x09\x09\x08\x0A\x0C"
."\x14\x0D\x0C\x0B\x0B\x0C\x19\x12\x13\x0F\x14\x1D\x1A\x1F\x1E\x1D\x1A\x1C\x1C\x20"
."\xFF\xC0\x00\x0B\x08\x00\x01\x00\x01\x01\x01\x11\x00\xFF\xC4\x00\x1F\x00\x00\x01"
."\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05"
."\xFF\xDA\x00\x08\x01\x01\x00\x00\x3F\x00\xFB\xD3\xFF\xD9";
$this->post->update([
'media' => [
[
'id' => 'test-media-id',
'path' => 'media/2026-01/test-image.jpg',
'url' => 'https://example.com/media/2026-01/test-image.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'test.jpg',
],
],
]);
$this->mock(MediaOptimizer::class)
->shouldReceive('optimizeImage')
->once()
->with(Mockery::any(), Platform::Mastodon)
->andReturn($optimizedFile);
Http::fake(function ($request) use ($minimalJpeg) {
$url = $request->url();
if (str_contains($url, '/api/v1/media')) {
return Http::response([
'id' => 'media-optimized-123',
'type' => 'image',
'url' => 'https://mastodon.social/media/image.jpg',
], 200);
}
if (str_contains($url, '/api/v1/statuses')) {
return Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200);
}
// Media download: return valid JPEG so mime_content_type() detects image/jpeg
return Http::response($minimalJpeg, 200, ['Content-Type' => 'image/jpeg']);
});
$this->publisher->publish($this->post);
@unlink($optimizedFile);
});
test('mastodon publisher retries a media upload server error before creating the status', function () {
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'masto_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
$this->post->update(['media' => [[
'id' => 'test-media-fail',
'path' => 'media/2026-01/failing-upload.jpg',
'url' => 'https://example.com/media/2026-01/failing-upload.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'failing-upload.jpg',
]]]);
Http::fake([
'https://example.com/*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png')),
'https://mastodon.social/api/v1/media' => Http::response(['error' => 'Internal server error'], 500),
'https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1'], 200),
]);
expect(fn () => $this->publisher->publish($this->post))
->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBe(500));
Http::assertNotSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses'));
});
test('mastodon publisher fails with Mastodon\'s message when it refuses the media', function () {
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'masto_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
$this->post->update(['media' => [[
'id' => 'test-media-refused',
'path' => 'media/2026-01/refused.jpg',
'url' => 'https://example.com/media/2026-01/refused.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'refused.jpg',
]]]);
Http::fake([
'https://example.com/*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png')),
'https://mastodon.social/api/v1/media' => Http::response(['error' => 'Validation failed: File content type is invalid'], 422),
'https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1'], 200),
]);
expect(fn () => $this->publisher->publish($this->post))
->toThrow(MastodonPublishException::class, 'Validation failed: File content type is invalid');
Http::assertNotSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses'));
});
test('mastodon publisher fails instead of posting without the media it could not download', function () {
$this->post->update(['media' => [[
'id' => 'test-media-missing',
'path' => 'media/2026-01/missing.jpg',
'url' => 'https://example.com/media/2026-01/missing.jpg',
'mime_type' => 'image/jpeg',
'original_filename' => 'missing.jpg',
]]]);
Http::fake([
'https://example.com/*' => Http::response('', 404),
'https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1'], 200),
]);
expect(fn () => $this->publisher->publish($this->post))
->toThrow(MastodonPublishException::class, __('posts.errors.media_unavailable', ['platform' => 'Mastodon']));
Http::assertNotSent(fn ($request): bool => str_contains($request->url(), '/api/v1/'));
});
test('mastodon publisher defaults to mastodon.social if no instance in meta', function () {
$this->socialAccount->update(['meta' => []]);
Http::fake([
'https://mastodon.social/api/v1/statuses' => Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200),
]);
$this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'mastodon.social');
});
});
test('mastodon publisher keeps links intact', function () {
config()->set('trypost.platforms.x.defuse_links', true);
$this->post->update(['content' => 'New post: https://acme.com/blog']);
Http::fake(['https://mastodon.social/api/v1/statuses' => Http::response([
'id' => '109876543210',
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200)]);
$this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/api/v1/statuses')
&& $request['status'] === 'New post: https://acme.com/blog');
});
test('mastodon content warning reaches the status payload', function () {
$this->post->update(['meta' => ['spoiler_text' => 'Spoilers for episode 3']]);
Http::fake(['https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1', 'url' => 'https://mastodon.social/@t/1'])]);
$this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => $request->data() === [
'status' => 'Hello from Mastodon!',
'visibility' => 'public',
'spoiler_text' => 'Spoilers for episode 3',
]);
});
test('mastodon trims unicode space padding from the content warning like the composer does', function () {
$this->post->update(['meta' => ['spoiler_text' => "\u{3000}\u{200B}Spoilers\u{00A0}"]]);
Http::fake(['https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1', 'url' => 'https://mastodon.social/@t/1'])]);
$this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => data_get($request->data(), 'spoiler_text') === 'Spoilers');
});
test('mastodon refuses a post whose content and content warning exceed the limit before any request', function () {
$limit = Platform::Mastodon->maxContentLength();
$this->post->update(['content' => str_repeat('b', $limit - 9)]);
$this->post->update(['meta' => ['spoiler_text' => str_repeat('a', 10)]]);
Http::fake();
expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(fn (ContentLimitException $exception) => expect($exception->category)->toBe(ErrorCategory::ContentPolicy)
->and($exception->userMessage)->toBe(__('posts.errors.content_too_long', ['platform' => 'Mastodon', 'max' => $limit, 'provided' => $limit + 1])));
Http::assertNothingSent();
});
test('mastodon publisher sends plain text for a post and a reply that still hold editor html', function () {
$this->post->update([
'content' => '<p>Teste TryPost <strong>negrito</strong> e <em>itálico</em></p><p>Segunda linha #teste https://example.com</p>',
'meta' => ['thread_replies' => ['<p>Reply <strong>two</strong></p>', ['text' => '<p>Reply <em>three</em></p>', 'media' => []]]],
]);
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::sequence()
->push(['id' => '1', 'url' => "{$instance}/@t/1"])
->push(['id' => '2', 'url' => "{$instance}/@t/2"])
->push(['id' => '3', 'url' => "{$instance}/@t/3"])]);
$this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => $request['status'] === "Teste TryPost negrito e itálico\nSegunda linha #teste https://example.com");
Http::assertSent(fn ($request): bool => $request['status'] === 'Reply two' && $request['in_reply_to_id'] === '1');
Http::assertSent(fn ($request): bool => $request['status'] === 'Reply three' && $request['in_reply_to_id'] === '2');
});
test('a mastodon thread chains each reply to the previous one with the root content warning', function () {
$this->post->update(['meta' => ['thread_replies' => ['Two', 'Three'], 'spoiler_text' => 'CW']]);
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::sequence()
->push(['id' => '1', 'url' => "{$instance}/@t/1"])
->push(['id' => '2', 'url' => "{$instance}/@t/2"])
->push(['id' => '3', 'url' => "{$instance}/@t/3"])]);
$result = $this->publisher->publish($this->post->fresh());
expect($result)->toBe(['id' => '1', 'url' => "{$instance}/@t/1", 'thread_reply_ids' => ['2', '3']]);
Http::assertSent(fn ($request): bool => $request->data() === [
'status' => 'Two',
'visibility' => 'public',
'in_reply_to_id' => '1',
'spoiler_text' => 'CW',
]);
Http::assertSent(fn ($request): bool => $request->data() === [
'status' => 'Three',
'visibility' => 'public',
'in_reply_to_id' => '2',
'spoiler_text' => 'CW',
] && $request->header('Idempotency-Key') === ["{$this->post->id}:2:".ThreadProgress::hash('Three')]);
});
test('a mastodon thread attaches each reply media to that reply only', function () {
$image = ['id' => 'reply-image', 'path' => 'media/2026-01/photo.jpg', 'url' => 'https://example.com/media/2026-01/photo.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'photo.jpg'];
$this->post->update(['meta' => ['thread_replies' => [['text' => 'Two', 'media' => [$image]], 'Three']]]);
$instance = data_get($this->socialAccount->meta, 'instance');
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'masto_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake([
'https://example.com/*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png')),
"{$instance}/api/v1/media" => Http::response(['id' => 'media-1']),
"{$instance}/api/v1/statuses" => Http::sequence()
->push(['id' => '1', 'url' => "{$instance}/@t/1"])
->push(['id' => '2', 'url' => "{$instance}/@t/2"])
->push(['id' => '3', 'url' => "{$instance}/@t/3"]),
]);
$result = $this->publisher->publish($this->post->fresh());
expect($result['thread_reply_ids'])->toBe(['2', '3']);
Http::assertSent(fn ($request): bool => str_contains($request->url(), '/statuses') && data_get($request->data(), 'status') === $this->post->content && ! array_key_exists('media_ids', $request->data()));
Http::assertSent(fn ($request): bool => $request->data() === ['status' => 'Two', 'visibility' => 'public', 'in_reply_to_id' => '1', 'media_ids' => ['media-1']]
&& $request->header('Idempotency-Key') === ["{$this->post->id}:1:".ThreadProgress::hash('Two', ['reply-image'])]);
Http::assertSent(fn ($request): bool => $request->data() === ['status' => 'Three', 'visibility' => 'public', 'in_reply_to_id' => '2']);
});
test('a mastodon thread with a reply over the limit fails before posting anything', function () {
$this->post->update(['meta' => ['thread_replies' => [str_repeat('a', 495)], 'spoiler_text' => 'Ten chars!']]);
Http::fake();
expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(ContentLimitException::class, __('posts.form.thread.reply_too_long', ['limit' => 490, 'over' => 5]));
Http::assertNothingSent();
});
test('a mastodon poll sends its choices, length in seconds and switches instead of media', function () {
$this->post->update([
'content' => 'Tabs or spaces?',
'content_type' => ContentType::MastodonPoll,
'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 90, 'multiple' => true]],
]);
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::response(['id' => '1', 'url' => "{$instance}/@t/1"])]);
$this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => $request->data() === [
'status' => 'Tabs or spaces?',
'visibility' => 'public',
'poll' => ['options' => ['Tabs', 'Spaces'], 'expires_in' => 5400, 'multiple' => true, 'hide_totals' => false],
]);
});
test('a mastodon poll that cannot go fails before calling mastodon', function (array $changes, string $message) {
$this->post->update([
'content' => 'Tabs or spaces?',
'content_type' => ContentType::MastodonPoll,
'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],
...$changes,
]);
Http::fake();
expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(MastodonPublishException::class, __($message, ['min' => 2]));
Http::assertNothingSent();
})->with([
'media' => [['media' => [['id' => 'm', 'type' => 'image', 'path' => 'm.jpg', 'url' => 'https://example.com/m.jpg', 'mime_type' => 'image/jpeg']]], 'posts.errors.media_not_accepted'],
'one choice' => [['meta' => ['poll' => ['options' => ['Tabs'], 'duration_minutes' => 60]]], 'posts.form.poll.options_required'],
'no length' => [['meta' => ['poll' => ['options' => ['Tabs', 'Spaces']]]], 'posts.form.poll.duration_required'],
'no question' => [['content' => ''], 'posts.form.poll.question_required'],
]);
test('a mastodon thread reply can be a poll, chained under the post before it', function () {
$poll = ['options' => ['Yes', 'No'], 'duration_minutes' => 60, 'hide_totals' => true];
$this->post->update(['meta' => ['thread_replies' => [['text' => 'Which one?', 'poll' => $poll]]]]);
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::sequence()
->push(['id' => '1', 'url' => "{$instance}/@t/1"])
->push(['id' => '2', 'url' => "{$instance}/@t/2"])]);
$result = $this->publisher->publish($this->post->fresh());
expect($result['thread_reply_ids'])->toBe(['2']);
Http::assertSent(fn ($request): bool => $request->data() === [
'status' => 'Which one?',
'visibility' => 'public',
'in_reply_to_id' => '1',
'poll' => ['options' => ['Yes', 'No'], 'expires_in' => 3600, 'multiple' => false, 'hide_totals' => true],
] && $request->header('Idempotency-Key') === ["{$this->post->id}:1:".ThreadProgress::hash('Which one?', [], $poll)]);
});
test('a mastodon poll changed before a retry gets a new idempotency key', function () {
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::response(['id' => '1', 'url' => "{$instance}/@t/1"])]);
$this->post->update(['content' => 'Tabs or spaces?', 'content_type' => ContentType::MastodonPoll, 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]]]);
$this->publisher->publish($this->post->fresh());
$this->post->update(['meta' => ['poll' => ['options' => ['Tabs', 'Both'], 'duration_minutes' => 60]]]);
$this->publisher->publish($this->post->fresh());
$keys = collect(Http::recorded())->map(fn (array $pair): string => $pair[0]->header('Idempotency-Key')[0]);
expect($keys->unique())->toHaveCount(2)
->and($keys->first())->not->toBe("{$this->post->id}:".ThreadProgress::hash('Tabs or spaces?'));
});
test('a plain mastodon post keeps the idempotency key it had before polls', function () {
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::response(['id' => '1', 'url' => "{$instance}/@t/1"])]);
$this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => $request->header('Idempotency-Key') === ["{$this->post->id}:".ThreadProgress::hash('Hello from Mastodon!')]);
});
test('a mastodon reply poll that cannot go fails before posting anything', function (array $reply, string $message) {
$this->post->update(['meta' => ['thread_replies' => [$reply]]]);
Http::fake();
expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(Exception::class, __($message, ['min' => 2]));
Http::assertNothingSent();
})->with([
'one choice' => [['text' => 'Which one?', 'poll' => ['options' => ['Yes'], 'duration_minutes' => 60]], 'posts.form.poll.options_required'],
'repeated choices' => [['text' => 'Which one?', 'poll' => ['options' => ['Yes', ' yes'], 'duration_minutes' => 60]], 'posts.form.poll.options_distinct'],
'no length' => [['text' => 'Which one?', 'poll' => ['options' => ['Yes', 'No']]], 'posts.form.poll.duration_required'],
'no question' => [['text' => '', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], 'posts.form.poll.question_required'],
]);
test('a mastodon reply poll with media is refused at publish and never sent', function () {
$this->post->update(['meta' => ['thread_replies' => [[
'text' => 'Which one?',
'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60],
'media' => [['id' => 'm', 'type' => 'image', 'path' => 'm.jpg', 'url' => 'https://example.com/m.jpg', 'mime_type' => 'image/jpeg']],
]]]]);
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::response(['id' => '1', 'url' => "{$instance}/@t/1"])]);
expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(ContentLimitException::class, __('posts.errors.media_not_accepted'));
Http::assertNothingSent();
});
test('a mastodon reply poll changed before a retry is sent again under a new idempotency key, its post resumed and a plain reply keeping its text hash', function () {
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::sequence()
->push(['id' => '1', 'url' => "{$instance}/@t/1"])
->push(['id' => '2', 'url' => "{$instance}/@t/2"])
->push(['id' => '3', 'url' => "{$instance}/@t/3"])
->push(['id' => '4', 'url' => "{$instance}/@t/4"])
->push(['id' => '5', 'url' => "{$instance}/@t/5"])]);
$first = ['options' => ['Yes', 'No'], 'duration_minutes' => 60];
$changed = ['options' => ['Yes', 'Maybe'], 'duration_minutes' => 60];
$this->post->update(['meta' => ['thread_replies' => [['text' => 'Which one?', 'poll' => $first], 'Thanks!']]]);
$this->publisher->publish($this->post->fresh());
$this->post->update(['meta' => ['thread_replies' => [['text' => 'Which one?', 'poll' => $changed], 'Thanks!']]]);
$this->publisher->publish($this->post->fresh());
$keys = collect(Http::recorded())->map(fn (array $pair): string => $pair[0]->header('Idempotency-Key')[0])->values();
expect($keys->all())->toBe([
"{$this->post->id}:".ThreadProgress::hash('Hello from Mastodon!'),
"{$this->post->id}:1:".ThreadProgress::hash('Which one?', [], $first),
"{$this->post->id}:2:".ThreadProgress::hash('Thanks!'),
"{$this->post->id}:1:".ThreadProgress::hash('Which one?', [], $changed),
"{$this->post->id}:4:".ThreadProgress::hash('Thanks!'),
])
->and($keys->get(1))->not->toBe($keys->get(3));
});
test('a mastodon poll with a content warning sends both', function () {
$this->post->update([
'content' => 'Tabs or spaces?',
'content_type' => ContentType::MastodonPoll,
'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60], 'spoiler_text' => 'Holy war'],
]);
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::response(['id' => '1', 'url' => "{$instance}/@t/1"])]);
$this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => data_get($request->data(), 'spoiler_text') === 'Holy war'
&& data_get($request->data(), 'poll') === ['options' => ['Tabs', 'Spaces'], 'expires_in' => 3600, 'multiple' => false, 'hide_totals' => false]);
});
test('a mastodon poll followed by plain replies chains them without a poll', function () {
$this->post->update([
'content' => 'Tabs or spaces?',
'content_type' => ContentType::MastodonPoll,
'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60], 'thread_replies' => ['Two', 'Three']],
]);
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::sequence()
->push(['id' => '1', 'url' => "{$instance}/@t/1"])
->push(['id' => '2', 'url' => "{$instance}/@t/2"])
->push(['id' => '3', 'url' => "{$instance}/@t/3"])]);
$result = $this->publisher->publish($this->post->fresh());
expect($result['thread_reply_ids'])->toBe(['2', '3']);
Http::assertSent(fn ($request): bool => data_get($request->data(), 'status') === 'Tabs or spaces?' && filled(data_get($request->data(), 'poll')));
Http::assertSent(fn ($request): bool => $request->data() === ['status' => 'Two', 'visibility' => 'public', 'in_reply_to_id' => '1']);
Http::assertSent(fn ($request): bool => $request->data() === ['status' => 'Three', 'visibility' => 'public', 'in_reply_to_id' => '2']);
});