fix(x): recover a missing media MIME from the downloaded bytes

A post created via the API with bare external-URL media (no mime_type, no
path to infer one from) reached XPublisher::getMediaCategory() with a null
$mimeType — whose parameter is typed string — throwing a TypeError. The
TypeError's message embeds the server file path, which then surfaced verbatim
in the user's failure email.

X downloads the media bytes anyway, so recover the MIME from the downloaded
file when the item carries none, and fail with a clean XPublishException
(MediaFormat) rather than a TypeError when it still can't be determined. Also
drive the image/video decision off the resolved MIME so sniffed images are
still optimized.

Audited every publisher: X was the only one whose strict mime path was
reachable with null (no isImage() gate + no path to backfill from). Bluesky's
uploadBlob is also strictly typed but is guarded by an isImage() check plus the
DTO's extension-based MIME backfill; the pull-from-URL publishers classify via
nullable helpers and fail cleanly; Pinterest/Mastodon already sniff; YouTube
and Facebook video fall back to video/mp4.
This commit is contained in:
Paulo Castellano 2026-06-28 19:29:14 -03:00
parent 81d43c30f4
commit 4417aa99ac
2 changed files with 62 additions and 1 deletions

View file

@ -6,6 +6,7 @@
use App\Enums\Media\Type as MediaType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\XPublishException;
use App\Models\PostPlatform;
use App\Services\Media\MediaOptimizer;
@ -117,8 +118,22 @@ private function uploadMedia($mediaItem): ?array
throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status());
}
// Recover the MIME from the downloaded bytes when the item carries
// none (e.g. media attached by URL), and fail cleanly rather than
// with a TypeError when it still can't be determined.
if (blank($mimeType)) {
$mimeType = mime_content_type($tempFile) ?: null;
}
if (blank($mimeType)) {
throw new XPublishException(
userMessage: 'Unsupported media type for X.',
category: ErrorCategory::MediaFormat,
);
}
// Optimize images (skip GIFs — they need special handling)
if ($mediaItem->isImage() && ! MediaType::isGif($mimeType)) {
if (MediaType::classify($mimeType) === MediaType::Image && ! MediaType::isGif($mimeType)) {
$optimizer = app(MediaOptimizer::class);
$optimizedPath = $optimizer->optimizeImage($tempFile, Platform::X);
@unlink($tempFile);

View file

@ -10,6 +10,7 @@
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\XPublisher;
use Illuminate\Support\Facades\Http;
@ -252,6 +253,51 @@
Http::assertSent(fn ($request) => str_contains($request->url(), '/2/media/gif_media_555'));
});
test('x publisher recovers a missing mime type from the downloaded bytes', function () {
// Media attached by URL can arrive without a mime_type; X must still publish
// it instead of crashing with a TypeError in getMediaCategory().
$this->post->update([
'media' => [
['url' => 'https://cdn.example.com/listing'],
],
]);
// The resize itself is covered by MediaOptimizerTest; here we only need the
// MIME to be recovered so the upload doesn't crash on a null mime.
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {
$optimized = tempnam(sys_get_temp_dir(), 'x_opt_');
copy($tempFile, $optimized);
return $optimized;
});
app()->instance(MediaOptimizer::class, $mockOptimizer);
Http::fake(function ($request) {
$url = $request->url();
if (str_contains($url, '/media/upload')) {
return Http::response(['data' => ['id' => 'media_id_111']], 200);
}
if (str_contains($url, '/2/tweets')) {
return Http::response(['data' => ['id' => '1212121212', 'text' => 'Hello from X!']], 200);
}
// The media download — real image bytes so the MIME can be sniffed.
return Http::response(
file_get_contents(__DIR__.'/../../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
);
});
$result = $this->publisher->publish($this->postPlatform);
expect($result['id'])->toBe('1212121212');
Http::assertSent(fn ($request) => str_contains($request->url(), '/media/upload'));
});
test('x publisher uploads video via chunked upload', function () {
$this->post->update([
'media' => [