From 7e28d17d2c78b013ffc92f69f524d1c1b24bd267 Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Tue, 23 Jun 2026 14:30:29 -0300 Subject: [PATCH] refactor(bluesky): tidy video upload, correct formats, bound polling Builds on the video-upload feature with house-style cleanup and fixes: - Extract downloadToTempFile / unwrapJobStatus / videoUploadFormat helpers and guard tempnam/fopen on the image path too (no magic numbers; named consts). - Send the real content-type and extension for Bluesky's four accepted formats (mp4, mpeg, webm, mov), falling back to mp4 for anything else. - Mint the upload and status service-auth tokens once and reuse them. - Bound the whole upload/poll/retry flow to a wall-clock budget under the queue job timeout so a stuck transcode degrades to a text post instead of being killed mid-flight. - Config-drive the poll interval, max video size, and video-service hosts. - Expand BlueskyPublisherTest to cover every branch: 409 with and without a blob, upload/status token failures, did:plc fallback and did:web resolution, the format mapping, retries, and timeout. --- app/Services/Social/BlueskyLexicon.php | 2 - app/Services/Social/BlueskyPublisher.php | 255 ++++--- config/trypost.php | 4 + .../Services/Social/BlueskyPublisherTest.php | 628 +++++++++++++++++- 4 files changed, 762 insertions(+), 127 deletions(-) diff --git a/app/Services/Social/BlueskyLexicon.php b/app/Services/Social/BlueskyLexicon.php index 0bc90175..0fbc70be 100644 --- a/app/Services/Social/BlueskyLexicon.php +++ b/app/Services/Social/BlueskyLexicon.php @@ -27,8 +27,6 @@ final class BlueskyLexicon public const VIDEO_GET_JOB_STATUS = 'app.bsky.video.getJobStatus'; - public const VIDEO_GET_UPLOAD_LIMITS = 'app.bsky.video.getUploadLimits'; - public const FEED_POST = 'app.bsky.feed.post'; public const GET_POSTS = 'app.bsky.feed.getPosts'; diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.php index 71e08e6f..95c63fd3 100644 --- a/app/Services/Social/BlueskyPublisher.php +++ b/app/Services/Social/BlueskyPublisher.php @@ -10,6 +10,7 @@ use App\Models\SocialAccount; use App\Services\Media\MediaOptimizer; use App\Services\Social\Concerns\HasSocialHttpClient; +use Carbon\CarbonInterface; use Exception; use Illuminate\Http\Client\Response; use Illuminate\Support\Facades\Http; @@ -20,9 +21,22 @@ class BlueskyPublisher { use HasSocialHttpClient; - /** Times to retry a transiently-failing video transcode before giving up. */ + /** Seconds allowed for a remote media download (large videos need time). */ + private const DOWNLOAD_TIMEOUT = 600; + + /** Re-upload a transiently-failing transcode this many times before giving up. */ private const VIDEO_UPLOAD_ATTEMPTS = 3; + /** Poll getJobStatus up to this many times (× the configured interval) before timing out. */ + private const VIDEO_POLL_MAX_ATTEMPTS = 150; + + /** Wall-clock budget (seconds) for the whole upload+poll+retry flow, kept under the 600s job timeout so a stuck transcode degrades to text instead of being killed mid-flight. */ + private const VIDEO_PROCESSING_BUDGET = 420; + + private const JOB_STATE_COMPLETED = 'JOB_STATE_COMPLETED'; + + private const JOB_STATE_FAILED = 'JOB_STATE_FAILED'; + public function publish(PostPlatform $postPlatform): array { $this->validateContentLength($postPlatform); @@ -69,7 +83,7 @@ public function publish(PostPlatform $postPlatform): array $video = $medias->first(fn ($media) => $media->isVideo()); if ($video) { - $videoBlob = $this->uploadVideo($account, $service, $video->url); + $videoBlob = $this->uploadVideo($account, $service, $video->url, $video->mime_type); if ($videoBlob) { $embed = [ @@ -129,27 +143,16 @@ public function publish(PostPlatform $postPlatform): array private function uploadBlob(SocialAccount $account, string $service, string $url, string $mimeType): ?array { - $tempFile = tempnam(sys_get_temp_dir(), 'bsky_blob_'); + $tempFile = $this->downloadToTempFile($url, 'bsky_blob_'); + + if ($tempFile === null) { + return null; + } try { - $downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($url); - - if ($downloadResponse->failed()) { - throw new Exception('Failed to download media: HTTP '.$downloadResponse->status()); - } - - $fileSize = filesize($tempFile); - - if ($fileSize === false || $fileSize === 0) { - Log::error('Bluesky failed to download media', ['url' => $url]); - - return null; - } - - // Optimize images for Bluesky's 1MB limit + // Optimize images for Bluesky's 1MB limit (GIFs are passed through untouched). if (str_starts_with($mimeType, 'image/') && ! str_starts_with($mimeType, 'image/gif')) { - $optimizer = app(MediaOptimizer::class); - $optimizedPath = $optimizer->optimizeImage($tempFile, Platform::Bluesky); + $optimizedPath = app(MediaOptimizer::class)->optimizeImage($tempFile, Platform::Bluesky); @unlink($tempFile); $tempFile = $optimizedPath; $mimeType = 'image/jpeg'; @@ -157,6 +160,12 @@ private function uploadBlob(SocialAccount $account, string $service, string $url $stream = fopen($tempFile, 'r'); + if ($stream === false) { + Log::error('Bluesky could not open media file for upload', ['file' => $tempFile]); + + return null; + } + $response = $this->socialHttp()->withToken($account->access_token) ->withHeaders(['Content-Type' => $mimeType]) ->withBody($stream, $mimeType) @@ -176,7 +185,7 @@ private function uploadBlob(SocialAccount $account, string $service, string $url } return data_get($response->json(), 'blob'); - } catch (Exception $e) { + } catch (Throwable $e) { Log::error('Bluesky blob upload exception', [ 'error' => $e->getMessage(), 'url' => $url, @@ -189,51 +198,73 @@ private function uploadBlob(SocialAccount $account, string $service, string $url } /** - * Upload a video to Bluesky and return the processed blob for embedding. - * - * Unlike images, video does not go to the PDS via uploadBlob. It is sent to - * the separate video service (video.bsky.app), which transcodes it and - * stores the resulting blob on the account's PDS. The flow is: - * 1. resolve the account's real PDS host (for the service-auth audience), - * 2. mint a service-auth token scoped to uploadBlob, - * 3. POST the bytes to app.bsky.video.uploadVideo, - * 4. poll app.bsky.video.getJobStatus until the blob is ready. - * - * Returns null on any failure so the post still publishes as text rather - * than crashing the whole job (mirrors uploadBlob()). + * Download a remote media file to a temp file. Returns the temp path, or + * null (after cleaning up) if the temp file can't be created, the download + * fails, or the downloaded file is empty. */ - private function uploadVideo(SocialAccount $account, string $service, string $url): ?array + private function downloadToTempFile(string $url, string $prefix): ?string { - $videoService = (string) config('trypost.platforms.bluesky.video_service'); - $did = (string) $account->platform_user_id; - - $tempFile = tempnam(sys_get_temp_dir(), 'bsky_video_'); + $tempFile = tempnam(sys_get_temp_dir(), $prefix); if ($tempFile === false) { - Log::error('Bluesky could not create temp file for video upload', ['url' => $url]); + Log::error('Bluesky could not create temp file for download', ['url' => $url]); return null; } try { - $downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($url); + $response = Http::withOptions(['sink' => $tempFile])->timeout(self::DOWNLOAD_TIMEOUT)->get($url); - if ($downloadResponse->failed()) { - throw new Exception('Failed to download video: HTTP '.$downloadResponse->status()); + if ($response->failed()) { + throw new Exception('HTTP '.$response->status()); } + $size = filesize($tempFile); + + if ($size === false || $size === 0) { + throw new Exception('downloaded file is empty'); + } + + return $tempFile; + } catch (Throwable $e) { + Log::error('Bluesky media download failed', ['url' => $url, 'error' => $e->getMessage()]); + @unlink($tempFile); + + return null; + } + } + + /** + * Upload a video to Bluesky and return the processed blob for embedding. + * + * Unlike images, video does not go to the PDS via uploadBlob. It is sent to + * the separate video service (video.bsky.app), which transcodes it and + * stores the resulting blob on the account's PDS. The flow is: + * 1. resolve the account's real PDS host (for the upload-token audience), + * 2. mint two service-auth tokens — one for the video service to write + * the blob back to the PDS (uploadBlob), one to poll job status, + * 3. POST the bytes to app.bsky.video.uploadVideo, + * 4. poll app.bsky.video.getJobStatus until the blob is ready, + * retrying the whole upload a few times on a transient transcode failure. + * + * Returns null on any failure so the post still publishes as text rather + * than crashing the whole job (mirrors uploadBlob()). + */ + private function uploadVideo(SocialAccount $account, string $service, string $url, ?string $mimeType): ?array + { + $tempFile = $this->downloadToTempFile($url, 'bsky_video_'); + + if ($tempFile === null) { + return null; + } + + try { $fileSize = filesize($tempFile); - if ($fileSize === false || $fileSize === 0) { - Log::error('Bluesky failed to download video', ['url' => $url]); - - return null; - } - // Bluesky caps videos at 100MB; skip oversized files rather than // burning an upload that the service will reject. - if ($fileSize > 100 * 1024 * 1024) { - Log::error('Bluesky video exceeds 100MB limit', ['url' => $url, 'size' => $fileSize]); + if ($fileSize > (int) config('trypost.platforms.bluesky.video_max_bytes')) { + Log::error('Bluesky video exceeds size limit', ['url' => $url, 'size' => $fileSize]); return null; } @@ -242,25 +273,34 @@ private function uploadVideo(SocialAccount $account, string $service, string $ur $pdsHost = parse_url($pds, PHP_URL_HOST); if (! is_string($pdsHost) || $pdsHost === '') { - Log::error('Bluesky could not resolve PDS host for video upload', ['did' => $did]); + Log::error('Bluesky could not resolve PDS host for video upload', ['did' => $account->platform_user_id]); return null; } - // The upload token is consumed by the video service to write the - // blob back to the user's PDS, so its audience is the PDS itself. - // Minted once (valid 30 min) and reused across retries below. + // Two service-auth tokens, minted once (valid 30 min) and reused + // across retries: + // - upload: lets the video service write the blob back to the + // user's PDS, so its audience is the PDS itself; + // - status: lets us poll the video service for the transcode job. $uploadToken = $this->getServiceAuth($account, $pds, "did:web:{$pdsHost}", BlueskyLexicon::UPLOAD_BLOB); + $statusToken = $this->getServiceAuth($account, $pds, (string) config('trypost.platforms.bluesky.video_service_did'), BlueskyLexicon::VIDEO_GET_JOB_STATUS); - if ($uploadToken === null) { + if ($uploadToken === null || $statusToken === null) { return null; } + // Bound the whole upload+poll+retry flow to a wall-clock budget that + // stays under the queue job timeout: a stuck transcode must give up + // and let the post publish as text, not run the worker to its + // timeout (which would drop the post entirely on a $tries=1 job). + $deadline = now()->addSeconds(self::VIDEO_PROCESSING_BUDGET); + // The transcoder occasionally fails a job transiently - // (JOB_STATE_FAILED "Failed to process video") even for valid input, - // so retry the upload+poll a couple of times before giving up. - for ($attempt = 1; $attempt <= self::VIDEO_UPLOAD_ATTEMPTS; $attempt++) { - $blob = $this->attemptVideoUpload($account, $pds, $videoService, $did, $uploadToken, $tempFile); + // (JOB_STATE_FAILED "Failed to process video") even for valid input. + // Re-uploading starts a fresh job, so retry until the budget runs out. + for ($attempt = 1; $attempt <= self::VIDEO_UPLOAD_ATTEMPTS && now()->lessThan($deadline); $attempt++) { + $blob = $this->attemptVideoUpload($account, $uploadToken, $statusToken, $tempFile, $mimeType, $deadline); if ($blob !== null) { return $blob; @@ -275,7 +315,7 @@ private function uploadVideo(SocialAccount $account, string $service, string $ur } return null; - } catch (Exception $e) { + } catch (Throwable $e) { Log::error('Bluesky video upload exception', [ 'error' => $e->getMessage(), 'url' => $url, @@ -283,9 +323,7 @@ private function uploadVideo(SocialAccount $account, string $service, string $ur return null; } finally { - if (is_string($tempFile)) { - @unlink($tempFile); - } + @unlink($tempFile); } } @@ -293,7 +331,7 @@ private function uploadVideo(SocialAccount $account, string $service, string $ur * A single upload-and-poll attempt against the video service. Returns the * processed blob, or null if this attempt failed (so the caller can retry). */ - private function attemptVideoUpload(SocialAccount $account, string $pds, string $videoService, string $did, string $uploadToken, string $tempFile): ?array + private function attemptVideoUpload(SocialAccount $account, string $uploadToken, string $statusToken, string $tempFile, ?string $mimeType, CarbonInterface $deadline): ?array { $stream = fopen($tempFile, 'r'); @@ -303,26 +341,23 @@ private function attemptVideoUpload(SocialAccount $account, string $pds, string return null; } - $name = bin2hex(random_bytes(8)).'.mp4'; + [$contentType, $extension] = $this->videoUploadFormat($mimeType); + $videoService = (string) config('trypost.platforms.bluesky.video_service'); + $name = bin2hex(random_bytes(8)).'.'.$extension; $uploadUrl = "{$videoService}/xrpc/".BlueskyLexicon::VIDEO_UPLOAD - .'?did='.rawurlencode($did).'&name='.rawurlencode($name); + .'?did='.rawurlencode($account->platform_user_id).'&name='.rawurlencode($name); $response = $this->socialHttp()->withToken($uploadToken) - ->withHeaders(['Content-Type' => 'video/mp4']) - ->withBody($stream, 'video/mp4') + ->withHeaders(['Content-Type' => $contentType]) + ->withBody($stream, $contentType) ->post($uploadUrl); if (is_resource($stream)) { fclose($stream); } - // uploadVideo returns the jobStatus object directly (top-level), - // while getJobStatus wraps it under a `jobStatus` key — accept both. - $body = $response->json(); - $jobStatus = data_get($body, 'jobStatus') ?: $body; - - // A re-upload of identical bytes returns 409 with the already - // finished job, whose blob we can embed directly. + // A re-upload of identical bytes returns 409 with the already-finished + // job, whose blob we can embed directly. if ($response->failed() && $response->status() !== 409) { Log::error('Bluesky video upload failed', [ 'status' => $response->status(), @@ -332,8 +367,10 @@ private function attemptVideoUpload(SocialAccount $account, string $pds, string return null; } - if (data_get($jobStatus, 'blob')) { - return data_get($jobStatus, 'blob'); + $jobStatus = $this->unwrapJobStatus($response->json()); + + if ($blob = data_get($jobStatus, 'blob')) { + return $blob; } $jobId = data_get($jobStatus, 'jobId'); @@ -346,28 +383,24 @@ private function attemptVideoUpload(SocialAccount $account, string $pds, string return null; } - return $this->pollVideoJob($account, $pds, $videoService, $jobId); + return $this->pollVideoJob($statusToken, $jobId, $deadline); } /** * Poll the video service until the transcode job finishes, then return its - * blob. Returns null if the job fails or never completes in time. + * blob. Returns null if the job fails or never completes within the shared + * deadline. The status token is minted by the caller and reused per poll. */ - private function pollVideoJob(SocialAccount $account, string $pds, string $videoService, string $jobId): ?array + private function pollVideoJob(string $statusToken, string $jobId, CarbonInterface $deadline): ?array { - $videoServiceDid = (string) config('trypost.platforms.bluesky.video_service_did'); - $jobToken = $this->getServiceAuth($account, $pds, $videoServiceDid, BlueskyLexicon::VIDEO_GET_JOB_STATUS); + $statusUrl = (string) config('trypost.platforms.bluesky.video_service').'/xrpc/'.BlueskyLexicon::VIDEO_GET_JOB_STATUS; + $intervalSeconds = (int) config('trypost.platforms.bluesky.video_poll_seconds'); - if ($jobToken === null) { - return null; - } - - $statusUrl = "{$videoService}/xrpc/".BlueskyLexicon::VIDEO_GET_JOB_STATUS; - - // Up to ~5 minutes; processing usually finishes within seconds. State is - // checked before sleeping so an already-complete job returns at once. - for ($attempt = 0; $attempt < 150; $attempt++) { - $response = $this->socialHttp()->withToken($jobToken) + // Processing usually finishes within seconds. State is checked before + // sleeping so an already-complete job returns at once. The attempt cap + // and the wall-clock deadline both bound the loop. + for ($attempt = 0; $attempt < self::VIDEO_POLL_MAX_ATTEMPTS && now()->lessThan($deadline); $attempt++) { + $response = $this->socialHttp()->withToken($statusToken) ->get($statusUrl, ['jobId' => $jobId]); // Bail on a hard error (e.g. expired/invalid token) instead of @@ -382,15 +415,14 @@ private function pollVideoJob(SocialAccount $account, string $pds, string $video return null; } - $body = $response->json(); - $jobStatus = data_get($body, 'jobStatus') ?: $body; + $jobStatus = $this->unwrapJobStatus($response->json()); $state = data_get($jobStatus, 'state'); - if ($state === 'JOB_STATE_COMPLETED' && data_get($jobStatus, 'blob')) { - return data_get($jobStatus, 'blob'); + if ($state === self::JOB_STATE_COMPLETED && ($blob = data_get($jobStatus, 'blob'))) { + return $blob; } - if ($state === 'JOB_STATE_FAILED') { + if ($state === self::JOB_STATE_FAILED) { Log::error('Bluesky video processing failed', [ 'jobId' => $jobId, 'message' => data_get($jobStatus, 'message'), @@ -399,7 +431,7 @@ private function pollVideoJob(SocialAccount $account, string $pds, string $video return null; } - sleep(2); + sleep($intervalSeconds); } Log::error('Bluesky video processing timed out', ['jobId' => $jobId]); @@ -407,6 +439,33 @@ private function pollVideoJob(SocialAccount $account, string $pds, string $video return null; } + /** + * uploadVideo returns the job status at the top level, while getJobStatus + * wraps it under a `jobStatus` key. Fall back to the top level only when the + * key is absent (null), not when it's present-but-empty. + */ + private function unwrapJobStatus(mixed $body): mixed + { + return data_get($body, 'jobStatus') ?? $body; + } + + /** + * 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. + * + * @return array{0: string, 1: string} + */ + private function videoUploadFormat(?string $mimeType): array + { + return match ($mimeType) { + 'video/mpeg' => ['video/mpeg', 'mpeg'], + 'video/webm' => ['video/webm', 'webm'], + 'video/quicktime' => ['video/quicktime', 'mov'], + default => ['video/mp4', 'mp4'], + }; + } + /** * Mint a short-lived service-auth token (com.atproto.server.getServiceAuth) * scoped to a single audience + method, used to authorize the video service. diff --git a/config/trypost.php b/config/trypost.php index 7f80bfe7..761be98f 100644 --- a/config/trypost.php +++ b/config/trypost.php @@ -151,6 +151,10 @@ // here, then the resulting blob is embedded in the post record. 'video_service' => env('BLUESKY_VIDEO_SERVICE', 'https://video.bsky.app'), 'video_service_did' => env('BLUESKY_VIDEO_SERVICE_DID', 'did:web:video.bsky.app'), + // Seconds between transcode job-status polls. + 'video_poll_seconds' => env('BLUESKY_VIDEO_POLL_SECONDS', 2), + // Bluesky rejects videos larger than 100 MB; skip oversized files early. + 'video_max_bytes' => env('BLUESKY_VIDEO_MAX_BYTES', 100 * 1024 * 1024), // 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/tests/Feature/Services/Social/BlueskyPublisherTest.php b/tests/Feature/Services/Social/BlueskyPublisherTest.php index 53c31945..6bd662c6 100644 --- a/tests/Feature/Services/Social/BlueskyPublisherTest.php +++ b/tests/Feature/Services/Social/BlueskyPublisherTest.php @@ -595,12 +595,31 @@ }); }); +/** + * Attach a single video to the post under test (mp4 by default). + */ +function attachBlueskyVideo(Post $post, string $mimeType = 'video/mp4'): void +{ + $post->update([ + 'media' => [[ + 'id' => 'test-video-id', + 'path' => 'media/2026-01/test-video.mp4', + 'url' => 'https://example.com/media/2026-01/test-video.mp4', + 'mime_type' => $mimeType, + 'original_filename' => 'test.mp4', + ]], + ]); +} + /** * Fake the Bluesky video pipeline. Order matters: getServiceAuth must be * matched before uploadBlob because its query carries lxm=...uploadBlob. */ function fakeBlueskyVideoPipeline(string $jobState = 'JOB_STATE_COMPLETED', bool $blobOnComplete = true): void { + // Poll without sleeping so multi-poll paths stay instant under test. + config(['trypost.platforms.bluesky.video_poll_seconds' => 0]); + Http::fake(function ($request) use ($jobState, $blobOnComplete) { $url = $request->url(); @@ -647,15 +666,7 @@ function fakeBlueskyVideoPipeline(string $jobState = 'JOB_STATE_COMPLETED', bool } test('bluesky publisher uploads a video and embeds it', function () { - $this->post->update([ - 'media' => [[ - 'id' => 'test-video-id', - 'path' => 'media/2026-01/test-video.mp4', - 'url' => 'https://example.com/media/2026-01/test-video.mp4', - 'mime_type' => 'video/mp4', - 'original_filename' => 'test.mp4', - ]], - ]); + attachBlueskyVideo($this->post); fakeBlueskyVideoPipeline(); @@ -678,15 +689,7 @@ function fakeBlueskyVideoPipeline(string $jobState = 'JOB_STATE_COMPLETED', bool }); test('bluesky publisher scopes the upload service-auth to the resolved PDS host', function () { - $this->post->update([ - 'media' => [[ - 'id' => 'test-video-id', - 'path' => 'media/2026-01/test-video.mp4', - 'url' => 'https://example.com/media/2026-01/test-video.mp4', - 'mime_type' => 'video/mp4', - 'original_filename' => 'test.mp4', - ]], - ]); + attachBlueskyVideo($this->post); fakeBlueskyVideoPipeline(); @@ -724,15 +727,8 @@ function fakeBlueskyVideoPipeline(string $jobState = 'JOB_STATE_COMPLETED', bool }); test('bluesky publisher retries a transient video transcode failure', function () { - $this->post->update([ - 'media' => [[ - 'id' => 'test-video-id', - 'path' => 'media/2026-01/test-video.mp4', - 'url' => 'https://example.com/media/2026-01/test-video.mp4', - 'mime_type' => 'video/mp4', - 'original_filename' => 'test.mp4', - ]], - ]); + attachBlueskyVideo($this->post); + config(['trypost.platforms.bluesky.video_poll_seconds' => 0]); $jobCalls = 0; Http::fake(function ($request) use (&$jobCalls) { @@ -784,3 +780,581 @@ function fakeBlueskyVideoPipeline(string $jobState = 'JOB_STATE_COMPLETED', bool && data_get($embed, 'video.ref.$link') === 'bafretry456'; }); }); + +test('bluesky publisher skips an oversized video and publishes text-only', function () { + attachBlueskyVideo($this->post); + config(['trypost.platforms.bluesky.video_max_bytes' => 1024]); + + Http::fake(function ($request) { + if (str_contains($request->url(), 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3big', 'cid' => 'bafbig'], 200); + } + + // Video download is 2 KB — over the 1 KB cap set above. + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // Oversized video is dropped before any upload; the post still goes out as text. + Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed'])); + Http::assertNotSent(fn ($request) => str_contains($request->url(), 'app.bsky.video.uploadVideo')); +}); + +test('bluesky publisher publishes text-only when the video download fails', function () { + attachBlueskyVideo($this->post); + + Http::fake(function ($request) { + if (str_contains($request->url(), 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3dl', 'cid' => 'bafdl'], 200); + } + + // The CDN download 404s — no video, no service-auth, just text. + return Http::response('Not Found', 404); + }); + + $this->publisher->publish($this->postPlatform); + + Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed'])); + Http::assertNotSent(fn ($request) => str_contains($request->url(), 'getServiceAuth')); +}); + +test('bluesky publisher publishes text-only when service-auth minting fails', function () { + attachBlueskyVideo($this->post); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'plc.directory')) { + return Http::response(['service' => [['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://pds.example.host']]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['error' => 'AuthRequired'], 400); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3auth', 'cid' => 'bafauth'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // Without a service-auth token the upload can't proceed; degrade to text. + Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed'])); + Http::assertNotSent(fn ($request) => str_contains($request->url(), 'app.bsky.video.uploadVideo')); +}); + +test('bluesky publisher embeds the existing blob when upload returns 409 already-exists', function () { + attachBlueskyVideo($this->post); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'plc.directory')) { + return Http::response(['service' => [['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://pds.example.host']]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['token' => 'service-auth-token'], 200); + } + if (str_contains($url, 'app.bsky.video.uploadVideo')) { + // Re-upload of identical bytes: 409 carrying the already-finished job. + return Http::response([ + 'jobId' => 'job-dup', 'state' => 'JOB_STATE_COMPLETED', + 'blob' => ['$type' => 'blob', 'ref' => ['$link' => 'bafdup789'], 'mimeType' => 'video/mp4', 'size' => 2048], + ], 409); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3dup', 'cid' => 'bafdup'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + Http::assertSent(function ($request) { + if (! str_contains($request->url(), 'createRecord')) { + return false; + } + $embed = $request['record']['embed'] ?? null; + + return $embed + && $embed['$type'] === 'app.bsky.embed.video' + && data_get($embed, 'video.ref.$link') === 'bafdup789'; + }); + + // The blob came straight from the 409 body; no job polling needed. Match the + // endpoint path, not the bare NSID — the status-token getServiceAuth request + // also carries `lxm=app.bsky.video.getJobStatus` in its query string. + Http::assertNotSent(fn ($request) => str_contains($request->url(), 'xrpc/app.bsky.video.getJobStatus')); +}); + +test('bluesky publisher publishes text-only when upload returns no job id', function () { + attachBlueskyVideo($this->post); + config(['trypost.platforms.bluesky.video_poll_seconds' => 0]); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'plc.directory')) { + return Http::response(['service' => [['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://pds.example.host']]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['token' => 'service-auth-token'], 200); + } + if (str_contains($url, 'app.bsky.video.uploadVideo')) { + return Http::response([], 200); // neither blob nor jobId + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3nojob', 'cid' => 'bafnojob'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed'])); +}); + +test('bluesky publisher publishes text-only when getJobStatus errors', function () { + attachBlueskyVideo($this->post); + config(['trypost.platforms.bluesky.video_poll_seconds' => 0]); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'plc.directory')) { + return Http::response(['service' => [['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://pds.example.host']]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['token' => 'service-auth-token'], 200); + } + if (str_contains($url, 'app.bsky.video.uploadVideo')) { + return Http::response(['jobId' => 'job-err', 'state' => 'JOB_STATE_CREATED'], 200); + } + if (str_contains($url, 'app.bsky.video.getJobStatus')) { + return Http::response(['error' => 'InternalServerError'], 500); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3joberr', 'cid' => 'bafjoberr'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // A failing getJobStatus bails immediately rather than sleeping to timeout. + Http::assertSent(fn ($request) => str_contains($request->url(), 'xrpc/app.bsky.video.getJobStatus')); + Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed'])); +}); + +test('bluesky publisher retries the upload up to three times before giving up', function () { + attachBlueskyVideo($this->post); + config(['trypost.platforms.bluesky.video_poll_seconds' => 0]); + + $uploads = 0; + Http::fake(function ($request) use (&$uploads) { + $url = $request->url(); + + if (str_contains($url, 'plc.directory')) { + return Http::response(['service' => [['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://pds.example.host']]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['token' => 'service-auth-token'], 200); + } + if (str_contains($url, 'app.bsky.video.uploadVideo')) { + $uploads++; + + return Http::response(['jobId' => "job-{$uploads}", 'state' => 'JOB_STATE_CREATED'], 200); + } + if (str_contains($url, 'app.bsky.video.getJobStatus')) { + return Http::response(['jobStatus' => ['jobId' => 'job', 'state' => 'JOB_STATE_FAILED', 'message' => 'permanent']], 200); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3exhaust', 'cid' => 'bafex'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // Every attempt fails permanently → exactly VIDEO_UPLOAD_ATTEMPTS uploads, then text-only. + expect($uploads)->toBe(3); + Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed'])); +}); + +test('bluesky publisher times out and publishes text-only when the job never completes', function () { + attachBlueskyVideo($this->post); + config(['trypost.platforms.bluesky.video_poll_seconds' => 0]); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'plc.directory')) { + return Http::response(['service' => [['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://pds.example.host']]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['token' => 'service-auth-token'], 200); + } + if (str_contains($url, 'app.bsky.video.uploadVideo')) { + return Http::response(['jobId' => 'job-stuck', 'state' => 'JOB_STATE_CREATED'], 200); + } + if (str_contains($url, 'app.bsky.video.getJobStatus')) { + // Never reaches a terminal state — exercises the poll timeout. + return Http::response(['jobStatus' => ['jobId' => 'job-stuck', 'state' => 'JOB_STATE_RUNNING']], 200); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3stuck', 'cid' => 'bafstuck'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed'])); +}); + +test('bluesky publisher falls back to the entryway when the DID document is unavailable', function () { + attachBlueskyVideo($this->post); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'plc.directory')) { + return Http::response(['error' => 'NotFound'], 500); // DID doc unavailable + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['token' => 'service-auth-token'], 200); + } + if (str_contains($url, 'app.bsky.video.uploadVideo')) { + return Http::response(['jobId' => 'job-fb', 'state' => 'JOB_STATE_COMPLETED', 'blob' => ['$type' => 'blob', 'ref' => ['$link' => 'baffb'], 'mimeType' => 'video/mp4', 'size' => 2048]], 200); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3fb', 'cid' => 'baffb'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // With no DID doc, the upload-token audience falls back to the entryway host (bsky.social). + Http::assertSent(function ($request) { + return str_contains($request->url(), 'getServiceAuth') + && str_contains($request->url(), 'aud=did%3Aweb%3Absky.social') + && str_contains($request->url(), 'lxm=com.atproto.repo.uploadBlob'); + }); +}); + +test('bluesky publisher resolves the PDS from a did:web document', function () { + $this->socialAccount->update(['platform_user_id' => 'did:web:example.com']); + attachBlueskyVideo($this->post); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'example.com/.well-known/did.json')) { + return Http::response(['service' => [['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://pds.example.host']]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['token' => 'service-auth-token'], 200); + } + if (str_contains($url, 'app.bsky.video.uploadVideo')) { + return Http::response(['jobId' => 'job-web', 'state' => 'JOB_STATE_COMPLETED', 'blob' => ['$type' => 'blob', 'ref' => ['$link' => 'bafweb'], 'mimeType' => 'video/mp4', 'size' => 2048]], 200); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:web:example.com/app.bsky.feed.post/3web', 'cid' => 'bafweb'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + Http::assertSent(fn ($request) => str_contains($request->url(), 'example.com/.well-known/did.json')); + Http::assertSent(function ($request) { + return str_contains($request->url(), 'getServiceAuth') + && str_contains($request->url(), 'aud=did%3Aweb%3Apds.example.host') + && str_contains($request->url(), 'lxm=com.atproto.repo.uploadBlob'); + }); +}); + +test('bluesky publisher builds the did:web document url from colon path segments', function () { + $this->socialAccount->update(['platform_user_id' => 'did:web:example.com:user:alice']); + attachBlueskyVideo($this->post); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'example.com/user/alice/did.json')) { + return Http::response(['service' => [['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://pds.example.host']]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['token' => 'service-auth-token'], 200); + } + if (str_contains($url, 'app.bsky.video.uploadVideo')) { + return Http::response(['jobId' => 'job-seg', 'state' => 'JOB_STATE_COMPLETED', 'blob' => ['$type' => 'blob', 'ref' => ['$link' => 'bafseg'], 'mimeType' => 'video/mp4', 'size' => 2048]], 200); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://x/app.bsky.feed.post/3seg', 'cid' => 'bafseg'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // did:web:example.com:user:alice → https://example.com/user/alice/did.json + Http::assertSent(fn ($request) => str_contains($request->url(), 'example.com/user/alice/did.json')); +}); + +test('bluesky publisher scopes the status service-auth to the video service', function () { + attachBlueskyVideo($this->post); + + fakeBlueskyVideoPipeline(); + + $this->publisher->publish($this->postPlatform); + + // The getJobStatus token is minted for the video service DID, not the PDS. + Http::assertSent(function ($request) { + return str_contains($request->url(), 'getServiceAuth') + && str_contains($request->url(), 'aud=did%3Aweb%3Avideo.bsky.app') + && str_contains($request->url(), 'lxm=app.bsky.video.getJobStatus'); + }); +}); + +test('bluesky publisher picks the PDS entry even when other services come first', function () { + attachBlueskyVideo($this->post); + config(['trypost.platforms.bluesky.video_poll_seconds' => 0]); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'plc.directory')) { + // A labeler service is listed before the PDS; resolution must skip it. + return Http::response(['service' => [ + ['id' => '#atproto_labeler', 'type' => 'AtprotoLabeler', 'serviceEndpoint' => 'https://labeler.example'], + ['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://real-pds.example.host'], + ]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['token' => 'service-auth-token'], 200); + } + if (str_contains($url, 'app.bsky.video.uploadVideo')) { + return Http::response(['jobId' => 'job-pds', 'state' => 'JOB_STATE_COMPLETED', 'blob' => ['$type' => 'blob', 'ref' => ['$link' => 'bafpds'], 'mimeType' => 'video/mp4', 'size' => 2048]], 200); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3pds', 'cid' => 'bafpds'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // The upload-token audience is the PDS host, not the labeler listed first. + Http::assertSent(function ($request) { + return str_contains($request->url(), 'getServiceAuth') + && str_contains($request->url(), 'aud=did%3Aweb%3Areal-pds.example.host') + && str_contains($request->url(), 'lxm=com.atproto.repo.uploadBlob'); + }); +}); + +test('bluesky publisher uploads a webm video with the correct content type', function () { + attachBlueskyVideo($this->post, 'video/webm'); + + fakeBlueskyVideoPipeline(); + + $this->publisher->publish($this->postPlatform); + + // Bluesky accepts webm natively; send it as webm, not mislabeled mp4. + Http::assertSent(function ($request) { + return str_contains($request->url(), 'xrpc/app.bsky.video.uploadVideo') + && str_contains($request->url(), '.webm') + && $request->hasHeader('Content-Type', 'video/webm'); + }); +}); + +test('bluesky publisher uploads a mov video with the quicktime content type', function () { + attachBlueskyVideo($this->post, 'video/quicktime'); + + fakeBlueskyVideoPipeline(); + + $this->publisher->publish($this->postPlatform); + + Http::assertSent(function ($request) { + return str_contains($request->url(), 'xrpc/app.bsky.video.uploadVideo') + && str_contains($request->url(), '.mov') + && $request->hasHeader('Content-Type', 'video/quicktime'); + }); +}); + +test('bluesky publisher sends an unsupported video format as mp4', function () { + attachBlueskyVideo($this->post, 'video/x-matroska'); // .mkv is not one of Bluesky's four formats + + fakeBlueskyVideoPipeline(); + + $this->publisher->publish($this->postPlatform); + + // Unknown formats fall back to mp4 and let the transcoder decide. + Http::assertSent(function ($request) { + return str_contains($request->url(), 'xrpc/app.bsky.video.uploadVideo') + && str_contains($request->url(), '.mp4') + && $request->hasHeader('Content-Type', 'video/mp4'); + }); +}); + +test('bluesky publisher polls when a 409 carries an in-flight job without a blob', function () { + attachBlueskyVideo($this->post); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'plc.directory')) { + return Http::response(['service' => [['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://pds.example.host']]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + return Http::response(['token' => 'service-auth-token'], 200); + } + if (str_contains($url, 'app.bsky.video.uploadVideo')) { + // 409 already-exists, but the job is still processing (no blob yet) — must poll. + return Http::response(['jobId' => 'job-409', 'state' => 'JOB_STATE_CREATED'], 409); + } + if (str_contains($url, 'app.bsky.video.getJobStatus')) { + return Http::response(['jobStatus' => ['jobId' => 'job-409', 'state' => 'JOB_STATE_COMPLETED', 'blob' => ['$type' => 'blob', 'ref' => ['$link' => 'baf409poll'], 'mimeType' => 'video/mp4', 'size' => 2048]]], 200); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3p409', 'cid' => 'bafp409'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // The 409 had no blob, so the job is polled and the completed blob is embedded. + Http::assertSent(fn ($request) => str_contains($request->url(), 'xrpc/app.bsky.video.getJobStatus')); + Http::assertSent(function ($request) { + if (! str_contains($request->url(), 'createRecord')) { + return false; + } + $embed = $request['record']['embed'] ?? null; + + return $embed && $embed['$type'] === 'app.bsky.embed.video' + && data_get($embed, 'video.ref.$link') === 'baf409poll'; + }); +}); + +test('bluesky publisher embeds images and skips the video when a post carries both', function () { + $this->post->update([ + 'media' => [ + ['id' => 'img', 'path' => 'media/2026-01/test.jpg', 'url' => 'https://example.com/test.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'test.jpg'], + ['id' => 'vid', 'path' => 'media/2026-01/test.mp4', 'url' => 'https://example.com/test.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'test.mp4'], + ], + ]); + + $this->mock(MediaOptimizer::class) + ->shouldReceive('optimizeImage') + ->andReturnUsing(fn () => tap(tempnam(sys_get_temp_dir(), 'bsky_test_'), fn ($f) => file_put_contents($f, str_repeat('x', 1024)))); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'uploadBlob')) { + return Http::response(['blob' => ['$type' => 'blob', 'ref' => ['$link' => 'bafimg'], 'mimeType' => 'image/jpeg', 'size' => 1024]], 200); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3both', 'cid' => 'bafboth'], 200); + } + + return Http::response(str_repeat('x', 1024), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // Images win; the embed is images and the video service is never touched. + Http::assertSent(function ($request) { + if (! str_contains($request->url(), 'createRecord')) { + return false; + } + + return ($request['record']['embed']['$type'] ?? null) === 'app.bsky.embed.images'; + }); + Http::assertNotSent(fn ($request) => str_contains($request->url(), 'xrpc/app.bsky.video.uploadVideo')); +}); + +test('bluesky publisher publishes text-only when only the status token fails', function () { + attachBlueskyVideo($this->post); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'plc.directory')) { + return Http::response(['service' => [['id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => 'https://pds.example.host']]], 200); + } + if (str_contains($url, 'getServiceAuth')) { + // Upload token mints fine; only the getJobStatus token fails. + return str_contains($url, 'lxm=app.bsky.video.getJobStatus') + ? Http::response(['error' => 'AuthRequired'], 400) + : Http::response(['token' => 'upload-token'], 200); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3stok', 'cid' => 'bafstok'], 200); + } + + return Http::response(str_repeat('v', 2048), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // Without the status token the upload can't be polled, so we never upload — degrade to text. + Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed'])); + Http::assertNotSent(fn ($request) => str_contains($request->url(), 'xrpc/app.bsky.video.uploadVideo')); +}); + +test('bluesky publisher uploads an mpeg video with the correct content type', function () { + attachBlueskyVideo($this->post, 'video/mpeg'); + + fakeBlueskyVideoPipeline(); + + $this->publisher->publish($this->postPlatform); + + Http::assertSent(function ($request) { + return str_contains($request->url(), 'xrpc/app.bsky.video.uploadVideo') + && str_contains($request->url(), '.mpeg') + && $request->hasHeader('Content-Type', 'video/mpeg'); + }); +}); + +test('bluesky publisher uploads a gif without optimizing it', function () { + $this->post->update([ + 'media' => [['id' => 'gif', 'path' => 'media/2026-01/test.gif', 'url' => 'https://example.com/test.gif', 'mime_type' => 'image/gif', 'original_filename' => 'test.gif']], + ]); + + // GIFs are passed through untouched — the optimizer must not run. + $this->mock(MediaOptimizer::class)->shouldReceive('optimizeImage')->never(); + + Http::fake(function ($request) { + $url = $request->url(); + + if (str_contains($url, 'uploadBlob')) { + return Http::response(['blob' => ['$type' => 'blob', 'ref' => ['$link' => 'bafgif'], 'mimeType' => 'image/gif', 'size' => 1024]], 200); + } + if (str_contains($url, 'createRecord')) { + return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3gif', 'cid' => 'bafgif'], 200); + } + + return Http::response(str_repeat('g', 1024), 200); + }); + + $this->publisher->publish($this->postPlatform); + + // The GIF is uploaded as-is with its original content type. + Http::assertSent(fn ($request) => str_contains($request->url(), 'uploadBlob') + && $request->hasHeader('Content-Type', 'image/gif')); +});