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
fix: Pinterest video processing timeout — longer poll + retry (#246)
Paulo Castellano27287aa13054
diff --git a/app/Console/Commands/RecoverStuckPosts.php b/app/Console/Commands/RecoverStuckPosts.phpindex 2b4a574b4..a4cee4b49 100644--- a/app/Console/Commands/RecoverStuckPosts.php+++ b/app/Console/Commands/RecoverStuckPosts.php@@ -23,25 +23,33 @@ class RecoverStuckPosts extends Command->where('status', PostStatus::Publishing)->where('updated_at', '<=', now()->subHour())->each(function (Post $post) use (&$count) {- // Mark stuck platforms as failed$post->postPlatforms()->where('enabled', true)- ->whereIn('status', [PlatformStatus::Publishing, PlatformStatus::Pending])+ ->whereIn('status', [PlatformStatus::Publishing, PlatformStatus::Pending, PlatformStatus::Retrying])->where('updated_at', '<=', now()->subHour())->update(['status' => PlatformStatus::Failed,- 'error_message' => 'Publishing timed out. Please try again.',- 'error_context' => json_encode([+ 'error_message' => __('posts.errors.publishing_timed_out'),+ 'error_context' => ['category' => 'timeout','failed_at' => now()->toIso8601String(),- ]),+ ],]);- // Recalculate post status+ // Delayed platform-unavailable retries keep the platform Retrying with a+ // fresh updated_at — do not finalize the post while that work is still live.+ $stillActive = $post->postPlatforms()+ ->where('enabled', true)+ ->whereIn('status', [PlatformStatus::Publishing, PlatformStatus::Pending, PlatformStatus::Retrying])+ ->exists();++ if ($stillActive) {+ return;+ }+$enabledPlatforms = $post->postPlatforms()->where('enabled', true)->get();$total = $enabledPlatforms->count();$publishedCount = $enabledPlatforms->where('status', PlatformStatus::Published)->count();- $failedCount = $enabledPlatforms->where('status', PlatformStatus::Failed)->count();if ($publishedCount === $total) {$post->markAsPublished();diff --git a/app/Enums/Pinterest/MediaUploadStatus.php b/app/Enums/Pinterest/MediaUploadStatus.phpnew file mode 100644index 000000000..1714e7cf3--- /dev/null+++ b/app/Enums/Pinterest/MediaUploadStatus.php@@ -0,0 +1,18 @@+<?php++declare(strict_types=1);++namespace App\Enums\Pinterest;++/**+ * Pinterest media upload lifecycle statuses from GET /v5/media/{media_id}.+ *+ * @see https://developers.pinterest.com/docs/api/v5/media-get/+ */+enum MediaUploadStatus: string+{+ case Registered = 'registered';+ case Processing = 'processing';+ case Succeeded = 'succeeded';+ case Failed = 'failed';+}diff --git a/app/Jobs/PublishToSocialPlatform.php b/app/Jobs/PublishToSocialPlatform.phpindex 88a46d6e4..a39c6b3b6 100644--- a/app/Jobs/PublishToSocialPlatform.php+++ b/app/Jobs/PublishToSocialPlatform.php@@ -31,29 +31,42 @@ use App\Services\Social\ThreadsPublisher;use App\Services\Social\TikTokPublisher;use App\Services\Social\XPublisher;use App\Services\Social\YouTubePublisher;+use Illuminate\Contracts\Queue\ShouldBeUnique;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;use Illuminate\Support\Facades\Log;-class PublishToSocialPlatform implements ShouldQueue+class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue{use Queueable;public int $tries = 1;- public int $timeout = 600; // 10 minutes — large video uploads need time+ /** Download/upload + Pinterest poll headroom; keep Horizon/Redis timeouts above this. */+ public int $timeout = 900;- public function __construct(public PostPlatform $postPlatform)- {+ public int $uniqueFor = 960;++ /** Max platform-unavailable reschedules (~1 hour at 10 min each). */+ public const MAX_PLATFORM_UNAVAILABLE_RETRIES = 6;++ public function __construct(+ public PostPlatform $postPlatform,+ public int $uniqueAttempt = 0,+ ) {$this->onQueue($postPlatform->platform->queue());}+ public function uniqueId(): string+ {+ return "{$this->postPlatform->id}:{$this->uniqueAttempt}";+ }+public function handle(): void{- // Idempotency: skip if already published (prevents duplicate posts on retry)$this->postPlatform->refresh();- if ($this->postPlatform->status === PostPlatformStatus::Published) {+ if ($this->isTerminal()) {return;}@@ -193,30 +206,57 @@ class PublishToSocialPlatform implements ShouldQueueprivate function rescheduleForRetry(PlatformUnavailableException $e): void{- $retryCount = (int) ($this->postPlatform->error_context['retry_count'] ?? 0) + 1;+ $retryCount = (int) data_get($this->postPlatform->error_context, 'retry_count', 0) + 1;+ $context = [+ 'category' => 'platform_unavailable',+ 'http_status' => $e->httpStatus,+ 'retry_count' => $retryCount,+ 'detail' => $e->getMessage(),+ ];++ if ($retryCount > self::MAX_PLATFORM_UNAVAILABLE_RETRIES) {+ Log::warning('Publish retries exhausted: platform unavailable', [+ 'post_platform_id' => $this->postPlatform->id,+ 'platform' => $this->postPlatform->platform->value,+ ...$context,+ ]);++ $this->postPlatform->markAsFailed(+ __('posts.errors.platform_unavailable_exhausted'),+ [...$context, 'failed_at' => now()->toIso8601String()],+ );++ return;+ }+$nextAttemptAt = now()->addMinutes(10);Log::warning('Publish rescheduled: platform unavailable', ['post_platform_id' => $this->postPlatform->id,'platform' => $this->postPlatform->platform->value,- 'retry_count' => $retryCount,'next_attempt_at' => $nextAttemptAt->toIso8601String(),- 'error' => $e->getMessage(),+ ...$context,]);$this->postPlatform->update(['status' => PostPlatformStatus::Retrying,- 'error_message' => $e->getMessage(),+ 'error_message' => __('posts.errors.platform_unavailable'),'error_context' => [- 'category' => 'platform_unavailable',- 'http_status' => $e->httpStatus,- 'retry_count' => $retryCount,+ ...$context,'last_attempt_at' => now()->toIso8601String(),'next_attempt_at' => $nextAttemptAt->toIso8601String(),],]);- self::dispatch($this->postPlatform)->delay($nextAttemptAt);+ self::dispatch($this->postPlatform, $retryCount)->delay($nextAttemptAt);+ }++ private function isTerminal(): bool+ {+ return in_array($this->postPlatform->status, [+ PostPlatformStatus::Published,+ PostPlatformStatus::Failed,+ ], true);}private function broadcastStatus(): void@@ -319,17 +359,19 @@ class PublishToSocialPlatform implements ShouldQueue$this->postPlatform->refresh();- if ($this->postPlatform->status !== PostPlatformStatus::Published) {- $this->postPlatform->markAsFailed(- $exception ? $this->safeFailureMessage($exception) : 'Unknown error',- [- 'category' => 'job_failed',- 'failed_at' => now()->toIso8601String(),- ]- );- $this->updatePostStatus();- $this->broadcastStatus();+ if ($this->isTerminal()) {+ return;}++ $this->postPlatform->markAsFailed(+ $exception ? $this->safeFailureMessage($exception) : 'Unknown error',+ [+ 'category' => 'job_failed',+ 'failed_at' => now()->toIso8601String(),+ ]+ );+ $this->updatePostStatus();+ $this->broadcastStatus();}private function notifyFailure(Post $post): voiddiff --git a/app/Services/Social/PinterestPublisher.php b/app/Services/Social/PinterestPublisher.phpindex ecdbaabc6..bbee0944f 100644--- a/app/Services/Social/PinterestPublisher.php+++ b/app/Services/Social/PinterestPublisher.php@@ -5,17 +5,21 @@ declare(strict_types=1);namespace App\Services\Social;use App\Enums\Media\Type as MediaType;+use App\Enums\Pinterest\MediaUploadStatus;use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;+use App\Exceptions\PlatformUnavailableException;use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\PinterestPublishException;use App\Models\PostPlatform;use App\Models\SocialAccount;use App\Services\Media\MediaOptimizer;use App\Services\Social\Concerns\HasSocialHttpClient;+use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\Response;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;+use Illuminate\Support\Sleep;class PinterestPublisher{@@ -320,45 +324,69 @@ class PinterestPublisherreturn $this->createPin($account, $payload, 'Pinterest carousel creation failed');}- private function waitForMediaProcessing(SocialAccount $account, string $mediaId, int $maxAttempts = 30): void+ /** @throws PlatformUnavailableException|PinterestPublishException */+ private function waitForMediaProcessing(SocialAccount $account, string $mediaId): void{+ $maxAttempts = 60;+ $pollSeconds = 5;+ $lastStatus = null;+for ($i = 0; $i < $maxAttempts; $i++) {- $response = $this->socialHttp()->withToken($account->access_token)- ->get($this->baseUrl."/media/{$mediaId}");+ if ($i > 0) {+ Sleep::for($pollSeconds)->seconds();+ }++ try {+ $response = $this->socialHttp()->withToken($account->access_token)+ ->get($this->baseUrl."/media/{$mediaId}");+ } catch (ConnectionException $e) {+ throw new PlatformUnavailableException(+ "Pinterest media status check connection failed (media_id={$mediaId}): {$e->getMessage()}",+ );+ }if ($response->failed()) {+ if ($response->status() === 401) {+ $this->handleApiError($response);+ }+Log::warning('Pinterest media status check failed', ['media_id' => $mediaId,- 'attempt' => $i,+ 'attempt' => $i + 1,+ 'status_code' => $response->status(),'body' => $this->redactResponseBody($response->body()),]);- sleep(3);continue;}$data = $response->json();- $status = data_get($data, 'status', 'unknown');+ $lastStatus = MediaUploadStatus::tryFrom((string) data_get($data, 'status', ''));- if ($status === 'succeeded') {+ if ($lastStatus === MediaUploadStatus::Succeeded) {return;}- if ($status === 'failed') {+ if ($lastStatus === MediaUploadStatus::Failed) {$failureCode = data_get($data, 'failure_code', 'unknown');throw new PinterestPublishException(userMessage: "Pinterest media processing failed: {$failureCode}",category: ErrorCategory::ServerError,platformErrorCode: (string) $failureCode,+ rawResponse: $response->body(),);}-- sleep(3);}- throw new PinterestPublishException(- userMessage: "Pinterest media processing timeout after {$maxAttempts} attempts",- category: ErrorCategory::ServerError,+ Log::warning('Pinterest media processing timeout', [+ 'media_id' => $mediaId,+ 'attempts' => $maxAttempts,+ 'last_status' => $lastStatus?->value,+ 'poll_seconds' => $pollSeconds,+ ]);++ throw new PlatformUnavailableException(+ "Pinterest media processing timeout after {$maxAttempts} attempts (media_id={$mediaId}, last_status=".($lastStatus?->value ?? 'unknown').')',);}diff --git a/config/horizon.php b/config/horizon.phpindex b6fcbfcca..c2e8b3184 100644--- a/config/horizon.php+++ b/config/horizon.php@@ -233,7 +233,7 @@ return ['autoScalingStrategy' => 'time','minProcesses' => 1,'maxProcesses' => 3,- 'timeout' => 630,+ 'timeout' => 930,'maxTime' => 0,'maxJobs' => 0,'memory' => 256,diff --git a/config/queue.php b/config/queue.phpindex e4aef0983..84eac290a 100644--- a/config/queue.php+++ b/config/queue.php@@ -70,7 +70,7 @@ return ['driver' => 'redis','connection' => env('REDIS_QUEUE_CONNECTION', 'default'),'queue' => env('REDIS_QUEUE', 'default'),- 'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 660),+ 'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 960),'block_for' => null,'after_commit' => false,],diff --git a/lang/ar/posts.php b/lang/ar/posts.phpindex 5bc649b3d..d9ff67233 100644--- a/lang/ar/posts.php+++ b/lang/ar/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'الحساب الاجتماعي مفصول','account_inactive' => 'الحساب الاجتماعي مُعطَّل','account_token_expired' => 'انتهت جلسة الحساب الاجتماعي — يرجى إعادة الربط',+ 'platform_unavailable' => 'المنصة غير متاحة مؤقتًا. سنعيد المحاولة قريبًا.',+ 'platform_unavailable_exhausted' => 'ظلت المنصة غير متاحة بعد عدة محاولات. يرجى المحاولة لاحقًا.',+ 'publishing_timed_out' => 'انتهت مهلة النشر. يرجى المحاولة مرة أخرى.',],'delete' => [diff --git a/lang/de/posts.php b/lang/de/posts.phpindex 4445d1392..ce4999ee5 100644--- a/lang/de/posts.php+++ b/lang/de/posts.php@@ -577,6 +577,9 @@ return ['account_disconnected' => 'Social-Media-Konto ist getrennt','account_inactive' => 'Social-Media-Konto ist deaktiviert','account_token_expired' => 'Sitzung des Social-Media-Kontos abgelaufen – bitte erneut verbinden',+ 'platform_unavailable' => 'Die Plattform ist vorübergehend nicht verfügbar. Wir versuchen es in Kürze erneut.',+ 'platform_unavailable_exhausted' => 'Die Plattform blieb nach mehreren Versuchen nicht verfügbar. Bitte später erneut versuchen.',+ 'publishing_timed_out' => 'Die Veröffentlichung ist abgelaufen. Bitte erneut versuchen.',],'delete' => [diff --git a/lang/el/posts.php b/lang/el/posts.phpindex 1f2edd343..625687e93 100644--- a/lang/el/posts.php+++ b/lang/el/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'Ο λογαριασμός κοινωνικού δικτύου έχει αποσυνδεθεί','account_inactive' => 'Ο λογαριασμός κοινωνικού δικτύου έχει απενεργοποιηθεί','account_token_expired' => 'Η συνεδρία του λογαριασμού κοινωνικού δικτύου έληξε — επανασυνδεθείτε',+ 'platform_unavailable' => 'Η πλατφόρμα είναι προσωρινά μη διαθέσιμη. Θα δοκιμάσουμε ξανά σύντομα.',+ 'platform_unavailable_exhausted' => 'Η πλατφόρμα παρέμεινε μη διαθέσιμη μετά από αρκετές προσπάθειες. Δοκιμάστε ξανά αργότερα.',+ 'publishing_timed_out' => 'Η δημοσίευση έληξε. Δοκιμάστε ξανά.',],'delete' => [diff --git a/lang/en/posts.php b/lang/en/posts.phpindex 918c0c299..35864b4af 100644--- a/lang/en/posts.php+++ b/lang/en/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'Social account is disconnected','account_inactive' => 'Social account is deactivated','account_token_expired' => 'Social account session expired — please reconnect',+ 'platform_unavailable' => 'The platform is temporarily unavailable. We\'ll retry shortly.',+ 'platform_unavailable_exhausted' => 'The platform stayed unavailable after several retries. Please try again later.',+ 'publishing_timed_out' => 'Publishing timed out. Please try again.',],'delete' => [diff --git a/lang/es/posts.php b/lang/es/posts.phpindex a2d8110bd..7353c8df5 100644--- a/lang/es/posts.php+++ b/lang/es/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'Cuenta social desconectada','account_inactive' => 'Cuenta social desactivada','account_token_expired' => 'Sesión de la cuenta social expirada — reconecta la cuenta',+ 'platform_unavailable' => 'La plataforma no está disponible temporalmente. Reintentaremos en breve.',+ 'platform_unavailable_exhausted' => 'La plataforma siguió sin estar disponible tras varios reintentos. Inténtalo de nuevo más tarde.',+ 'publishing_timed_out' => 'La publicación agotó el tiempo de espera. Inténtalo de nuevo.',],'delete' => [diff --git a/lang/fr/posts.php b/lang/fr/posts.phpindex 6e7ffc3ba..4b6162c40 100644--- a/lang/fr/posts.php+++ b/lang/fr/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'Le compte social est déconnecté','account_inactive' => 'Le compte social est désactivé','account_token_expired' => 'La session du compte social a expiré — veuillez reconnecter',+ 'platform_unavailable' => 'La plateforme est temporairement indisponible. Nouvelle tentative sous peu.',+ 'platform_unavailable_exhausted' => 'La plateforme est restée indisponible après plusieurs tentatives. Réessayez plus tard.',+ 'publishing_timed_out' => 'La publication a expiré. Veuillez réessayer.',],'delete' => [diff --git a/lang/it/posts.php b/lang/it/posts.phpindex 4d08795fc..3a1e355d5 100644--- a/lang/it/posts.php+++ b/lang/it/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'L\'account social è scollegato','account_inactive' => 'L\'account social è disattivato','account_token_expired' => 'Sessione dell\'account social scaduta — ricollegalo',+ 'platform_unavailable' => 'La piattaforma è temporaneamente non disponibile. Riproveremo a breve.',+ 'platform_unavailable_exhausted' => 'La piattaforma è rimasta non disponibile dopo diversi tentativi. Riprova più tardi.',+ 'publishing_timed_out' => 'Pubblicazione scaduta. Riprova.',],'delete' => [diff --git a/lang/ja/posts.php b/lang/ja/posts.phpindex 1af1a4431..ffdd60ce0 100644--- a/lang/ja/posts.php+++ b/lang/ja/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'ソーシャルアカウントの接続が解除されています','account_inactive' => 'ソーシャルアカウントが無効化されています','account_token_expired' => 'ソーシャルアカウントのセッションの有効期限が切れました — 再接続してください',+ 'platform_unavailable' => 'プラットフォームが一時的に利用できません。まもなく再試行します。',+ 'platform_unavailable_exhausted' => '何度か再試行しましたがプラットフォームが利用できませんでした。後でもう一度お試しください。',+ 'publishing_timed_out' => '公開がタイムアウトしました。もう一度お試しください。',],'delete' => [diff --git a/lang/ko/posts.php b/lang/ko/posts.phpindex bd8c1ab98..77f5c4437 100644--- a/lang/ko/posts.php+++ b/lang/ko/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => '소셜 계정 연결이 해제되었습니다','account_inactive' => '소셜 계정이 비활성화되었습니다','account_token_expired' => '소셜 계정 세션이 만료되었습니다 — 재연결하세요',+ 'platform_unavailable' => '플랫폼을 일시적으로 사용할 수 없습니다. 곧 다시 시도합니다.',+ 'platform_unavailable_exhausted' => '여러 번 재시도했지만 플랫폼을 사용할 수 없었습니다. 나중에 다시 시도하세요.',+ 'publishing_timed_out' => '게시에 시간이 초과되었습니다. 다시 시도하세요.',],'delete' => [diff --git a/lang/nl/posts.php b/lang/nl/posts.phpindex 9a83be401..ff94a555d 100644--- a/lang/nl/posts.php+++ b/lang/nl/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'Social account is losgekoppeld','account_inactive' => 'Social account is gedeactiveerd','account_token_expired' => 'Sessie van social account verlopen — koppel opnieuw',+ 'platform_unavailable' => 'Het platform is tijdelijk niet beschikbaar. We proberen het zo opnieuw.',+ 'platform_unavailable_exhausted' => 'Het platform bleef na meerdere pogingen niet beschikbaar. Probeer het later opnieuw.',+ 'publishing_timed_out' => 'Publiceren is timed-out. Probeer het opnieuw.',],'delete' => [diff --git a/lang/pl/posts.php b/lang/pl/posts.phpindex c040718f7..b8bde35a0 100644--- a/lang/pl/posts.php+++ b/lang/pl/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'Konto społecznościowe jest rozłączone','account_inactive' => 'Konto społecznościowe jest dezaktywowane','account_token_expired' => 'Sesja konta społecznościowego wygasła — połącz ponownie',+ 'platform_unavailable' => 'Platforma jest tymczasowo niedostępna. Spróbujemy ponownie wkrótce.',+ 'platform_unavailable_exhausted' => 'Platforma pozostała niedostępna po kilku próbach. Spróbuj ponownie później.',+ 'publishing_timed_out' => 'Publikowanie przekroczyło limit czasu. Spróbuj ponownie.',],'delete' => [diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.phpindex 10ccc0fe8..37b20993f 100644--- a/lang/pt-BR/posts.php+++ b/lang/pt-BR/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'Conta social está desconectada','account_inactive' => 'Conta social está desativada','account_token_expired' => 'Sessão da conta social expirou — reconecte a conta',+ 'platform_unavailable' => 'A plataforma está temporariamente indisponível. Vamos tentar de novo em breve.',+ 'platform_unavailable_exhausted' => 'A plataforma continuou indisponível após várias tentativas. Tente de novo mais tarde.',+ 'publishing_timed_out' => 'A publicação excedeu o tempo limite. Tente novamente.',],'delete' => [diff --git a/lang/ru/posts.php b/lang/ru/posts.phpindex 3c83c63e6..e1bc618ed 100644--- a/lang/ru/posts.php+++ b/lang/ru/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'Социальный аккаунт отключён','account_inactive' => 'Социальный аккаунт деактивирован','account_token_expired' => 'Сессия социального аккаунта истекла — переподключите',+ 'platform_unavailable' => 'Платформа временно недоступна. Мы повторим попытку вскоре.',+ 'platform_unavailable_exhausted' => 'Платформа оставалась недоступной после нескольких попыток. Попробуйте позже.',+ 'publishing_timed_out' => 'Публикация превысила время ожидания. Попробуйте снова.',],'delete' => [diff --git a/lang/tr/posts.php b/lang/tr/posts.phpindex 22e9f3e95..d3074fc5a 100644--- a/lang/tr/posts.php+++ b/lang/tr/posts.php@@ -577,6 +577,9 @@ return ['account_disconnected' => 'Sosyal hesabın bağlantısı kesildi','account_inactive' => 'Sosyal hesap devre dışı bırakıldı','account_token_expired' => 'Sosyal hesap oturumunun süresi doldu — lütfen yeniden bağlanın',+ 'platform_unavailable' => 'Platform geçici olarak kullanılamıyor. Kısa süre içinde yeniden deneyeceğiz.',+ 'platform_unavailable_exhausted' => 'Platform birkaç denemeden sonra kullanılamaz kaldı. Lütfen daha sonra tekrar deneyin.',+ 'publishing_timed_out' => 'Yayınlama zaman aşımına uğradı. Lütfen tekrar deneyin.',],'delete' => [diff --git a/lang/uk/posts.php b/lang/uk/posts.phpindex 50a859103..37beb05c8 100644--- a/lang/uk/posts.php+++ b/lang/uk/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => 'Соціальний акаунт відключено','account_inactive' => 'Соціальний акаунт деактивовано','account_token_expired' => 'Сесія соціального акаунта закінчилася — перепідключіть',+ 'platform_unavailable' => 'Платформа тимчасово недоступна. Ми спробуємо знову незабаром.',+ 'platform_unavailable_exhausted' => 'Платформа залишалася недоступною після кількох спроб. Спробуйте пізніше.',+ 'publishing_timed_out' => 'Публікація перевищила час очікування. Спробуйте ще раз.',],'delete' => [diff --git a/lang/zh/posts.php b/lang/zh/posts.phpindex 4f281001c..27cde3989 100644--- a/lang/zh/posts.php+++ b/lang/zh/posts.php@@ -575,6 +575,9 @@ return ['account_disconnected' => '社交账号已断开连接','account_inactive' => '社交账号已停用','account_token_expired' => '社交账号会话已过期——请重新连接',+ 'platform_unavailable' => '平台暂时不可用。我们稍后会重试。',+ 'platform_unavailable_exhausted' => '多次重试后平台仍不可用。请稍后再试。',+ 'publishing_timed_out' => '发布超时。请重试。',],'delete' => [diff --git a/tests/Feature/Commands/RecoverStuckPostsTest.php b/tests/Feature/Commands/RecoverStuckPostsTest.phpindex bc69db7b1..a41fe08e0 100644--- a/tests/Feature/Commands/RecoverStuckPostsTest.php+++ b/tests/Feature/Commands/RecoverStuckPostsTest.php@@ -5,11 +5,15 @@ declare(strict_types=1);use App\Enums\Post\Status as PostStatus;use App\Enums\PostPlatform\Status as PlatformStatus;use App\Enums\SocialAccount\Platform;+use App\Jobs\PublishToSocialPlatform;use App\Models\Post;use App\Models\PostPlatform;use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;+use App\Services\Social\LinkedInPublisher;+use Illuminate\Support\Facades\Event;+use Illuminate\Support\Facades\Mail;beforeEach(function () {$this->user = User::factory()->create();@@ -42,7 +46,10 @@ test('it recovers posts stuck in publishing for over 1 hour', function () {$post->refresh();expect($platform->status)->toBe(PlatformStatus::Failed);- expect($platform->error_message)->toBe('Publishing timed out. Please try again.');+ expect($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'));+ expect($platform->error_context)->toMatchArray([+ 'category' => 'timeout',+ ]);expect($post->status)->toBe(PostStatus::Failed);});@@ -104,3 +111,170 @@ test('it marks post as partially published when some platforms succeeded', functexpect($stuckPlatform->status)->toBe(PlatformStatus::Failed);expect($post->status)->toBe(PostStatus::PartiallyPublished);});++test('it recovers platforms stuck in retrying for over 1 hour', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Publishing,+ 'updated_at' => now()->subHours(2),+ ]);++ $platform = PostPlatform::factory()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'status' => PlatformStatus::Retrying,+ 'enabled' => true,+ 'error_message' => __('posts.errors.platform_unavailable'),+ 'updated_at' => now()->subHours(2),+ ]);++ $this->artisan('social:recover-stuck-posts')->assertSuccessful();++ $platform->refresh();+ $post->refresh();++ expect($platform->status)->toBe(PlatformStatus::Failed)+ ->and($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'))+ ->and($post->status)->toBe(PostStatus::Failed);+});++test('it does not finalize a post while a platform is still actively retrying', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Publishing,+ 'updated_at' => now()->subHours(2),+ ]);++ $platform = PostPlatform::factory()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'status' => PlatformStatus::Retrying,+ 'enabled' => true,+ 'error_message' => __('posts.errors.platform_unavailable'),+ 'updated_at' => now()->subMinutes(5),+ ]);++ $this->artisan('social:recover-stuck-posts')+ ->expectsOutput('Recovered 0 stuck posts.')+ ->assertSuccessful();++ $platform->refresh();+ $post->refresh();++ expect($platform->status)->toBe(PlatformStatus::Retrying)+ ->and($post->status)->toBe(PostStatus::Publishing);+});++test('it does not finalize a post while a platform is still actively pending or publishing', function (PlatformStatus $status) {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Publishing,+ 'updated_at' => now()->subHours(2),+ ]);++ $platform = PostPlatform::factory()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'status' => $status,+ 'enabled' => true,+ 'updated_at' => now()->subMinutes(5),+ ]);++ $this->artisan('social:recover-stuck-posts')+ ->expectsOutput('Recovered 0 stuck posts.')+ ->assertSuccessful();++ $platform->refresh();+ $post->refresh();++ expect($platform->status)->toBe($status)+ ->and($post->status)->toBe(PostStatus::Publishing);+})->with([+ PlatformStatus::Pending,+ PlatformStatus::Publishing,+]);++test('it fails stale platforms but keeps the post publishing when another platform is still retrying', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Publishing,+ 'updated_at' => now()->subHours(2),+ ]);++ $stalePlatform = PostPlatform::factory()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'status' => PlatformStatus::Publishing,+ 'enabled' => true,+ 'updated_at' => now()->subHours(2),+ ]);++ $activeRetry = PostPlatform::factory()->create([+ 'post_id' => $post->id,+ 'social_account_id' => SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::Pinterest,+ ])->id,+ 'status' => PlatformStatus::Retrying,+ 'enabled' => true,+ 'error_message' => __('posts.errors.platform_unavailable'),+ 'updated_at' => now()->subMinutes(5),+ ]);++ $this->artisan('social:recover-stuck-posts')+ ->expectsOutput('Recovered 0 stuck posts.')+ ->assertSuccessful();++ $stalePlatform->refresh();+ $activeRetry->refresh();+ $post->refresh();++ expect($stalePlatform->status)->toBe(PlatformStatus::Failed)+ ->and($stalePlatform->error_message)->toBe(__('posts.errors.publishing_timed_out'))+ ->and($activeRetry->status)->toBe(PlatformStatus::Retrying)+ ->and($post->status)->toBe(PostStatus::Publishing);+});++test('delayed publish job no-ops after recover fails a stuck retrying platform', function () {+ Event::fake();+ Mail::fake();++ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Publishing,+ 'updated_at' => now()->subHours(2),+ ]);++ $platform = PostPlatform::factory()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'status' => PlatformStatus::Retrying,+ 'enabled' => true,+ 'error_message' => __('posts.errors.platform_unavailable'),+ 'updated_at' => now()->subHours(2),+ ]);++ $this->artisan('social:recover-stuck-posts')->assertSuccessful();++ $platform->refresh();+ expect($platform->status)->toBe(PlatformStatus::Failed)+ ->and($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'));++ $publisher = Mockery::mock(LinkedInPublisher::class);+ $publisher->shouldNotReceive('publish');+ $this->app->instance(LinkedInPublisher::class, $publisher);++ (new PublishToSocialPlatform($platform))->handle();++ $platform->refresh();+ $post->refresh();++ expect($platform->status)->toBe(PlatformStatus::Failed)+ ->and($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'))+ ->and($post->status)->toBe(PostStatus::Failed);+});diff --git a/tests/Feature/Jobs/PublishToSocialPlatformTest.php b/tests/Feature/Jobs/PublishToSocialPlatformTest.phpindex 8657bbd80..97d516212 100644--- a/tests/Feature/Jobs/PublishToSocialPlatformTest.php+++ b/tests/Feature/Jobs/PublishToSocialPlatformTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\Notification\Type;use App\Enums\Post\Status as PostStatus;use App\Enums\PostPlatform\ContentType;use App\Enums\PostPlatform\Status as PlatformStatus;@@ -23,12 +24,15 @@ use App\Models\Workspace;use App\Services\Social\ConnectionVerifier;use App\Services\Social\LinkedInPagePublisher;use App\Services\Social\LinkedInPublisher;+use App\Services\Social\PinterestPublisher;use Carbon\Carbon;+use Illuminate\Contracts\Queue\ShouldBeUnique;use Illuminate\Support\Facades\Bus;use Illuminate\Support\Facades\Event;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Mail;use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Sleep;beforeEach(function () {Mail::fake();@@ -273,10 +277,57 @@ test('publish reschedules platform unavailable retry via Bus dispatch (not markeexpect($this->postPlatform->error_context['category'] ?? null)->toBe('platform_unavailable');expect($this->postPlatform->error_context['http_status'] ?? null)->toBe(503);expect($this->postPlatform->error_context['retry_count'] ?? null)->toBe(1);+ expect($this->postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable'));+ expect($this->postPlatform->error_context['detail'] ?? null)->toContain('LinkedIn API returned 503');expect($this->socialAccount->status)->toBe(AccountStatus::Connected);Bus::assertDispatched(PublishToSocialPlatform::class, function ($job) {- return $job->postPlatform->id === $this->postPlatform->id;+ return $job->postPlatform->id === $this->postPlatform->id+ && $job->uniqueAttempt === 1+ && $job->uniqueId() === "{$this->postPlatform->id}:1";+ });+});++test('publish reschedules when pinterest video processing times out', function () {+ Bus::fake([PublishToSocialPlatform::class]);+ Event::fake();+ Mail::fake();++ $pinterestAccount = SocialAccount::factory()->pinterest()->create([+ 'workspace_id' => $this->workspace->id,+ 'meta' => ['default_board_id' => 'board_123'],+ ]);++ $postPlatform = PostPlatform::factory()->pinterest()->create([+ 'post_id' => $this->post->id,+ 'social_account_id' => $pinterestAccount->id,+ 'platform' => Platform::Pinterest,+ 'content_type' => ContentType::PinterestVideoPin,+ 'enabled' => true,+ 'status' => PlatformStatus::Pending,+ 'meta' => ['board_id' => 'board_123'],+ ]);++ $publisher = Mockery::mock(PinterestPublisher::class);+ $publisher->shouldReceive('publish')->andThrow(+ new PlatformUnavailableException(+ 'Pinterest media processing timeout after 60 attempts (media_id=media_abc, last_status=processing)'+ )+ );+ $this->app->instance(PinterestPublisher::class, $publisher);++ (new PublishToSocialPlatform($postPlatform))->handle();++ $postPlatform->refresh();++ expect($postPlatform->status)->toBe(PlatformStatus::Retrying)+ ->and($postPlatform->error_context['category'] ?? null)->toBe('platform_unavailable')+ ->and($postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable'))+ ->and($postPlatform->error_context['detail'] ?? null)->toContain('Pinterest media processing timeout');++ Bus::assertDispatched(PublishToSocialPlatform::class, function ($job) use ($postPlatform) {+ return $job->postPlatform->id === $postPlatform->id+ && $job->uniqueAttempt === 1;});});@@ -450,9 +501,216 @@ test('publish retry count increments across successive platform_unavailable atte$this->postPlatform->refresh();+ expect($this->postPlatform->status)->toBe(PlatformStatus::Retrying);expect($this->postPlatform->error_context['retry_count'] ?? null)->toBe(6);});+test('publish hard-fails when platform unavailable retries are exhausted', function () {+ Bus::fake([PublishToSocialPlatform::class]);+ Event::fake();+ Mail::fake();++ $publisher = Mockery::mock(LinkedInPublisher::class);+ $publisher->shouldReceive('publish')->andThrow(+ new PlatformUnavailableException('LinkedIn 503', 503)+ );+ $this->app->instance(LinkedInPublisher::class, $publisher);++ $this->postPlatform->update([+ 'error_context' => ['retry_count' => PublishToSocialPlatform::MAX_PLATFORM_UNAVAILABLE_RETRIES],+ ]);++ (new PublishToSocialPlatform($this->postPlatform))->handle();++ $this->postPlatform->refresh();++ expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)+ ->and($this->postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable_exhausted'))+ ->and($this->postPlatform->error_context['category'] ?? null)->toBe('platform_unavailable')+ ->and($this->postPlatform->error_context['retry_count'] ?? null)->toBe(PublishToSocialPlatform::MAX_PLATFORM_UNAVAILABLE_RETRIES + 1)+ ->and($this->postPlatform->error_context['detail'] ?? null)->toContain('LinkedIn 503');++ Bus::assertNotDispatched(PublishToSocialPlatform::class);+});++test('publish skips platforms that are already failed', function () {+ Event::fake();+ Mail::fake();++ $this->postPlatform->update([+ 'status' => PlatformStatus::Failed,+ 'error_message' => __('posts.errors.publishing_timed_out'),+ ]);++ $publisher = Mockery::mock(LinkedInPublisher::class);+ $publisher->shouldNotReceive('publish');+ $this->app->instance(LinkedInPublisher::class, $publisher);++ (new PublishToSocialPlatform($this->postPlatform))->handle();++ $this->postPlatform->refresh();++ expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)+ ->and($this->postPlatform->error_message)->toBe(__('posts.errors.publishing_timed_out'));+});++test('publish job timeout leaves headroom above the pinterest media poll budget', function () {+ $job = new PublishToSocialPlatform($this->postPlatform);+ $horizonTimeout = (int) config('horizon.defaults.social-publishing.timeout');+ $retryAfter = (int) config('queue.connections.redis.retry_after');++ expect($job->timeout)->toBe(900)+ ->and($horizonTimeout)->toBe(930)+ ->and($retryAfter)->toBe(960)+ ->and($job->uniqueFor)->toBe(960)+ ->and($job->timeout)->toBeLessThan($horizonTimeout)+ ->and($horizonTimeout)->toBeLessThan($retryAfter)+ ->and($job->uniqueFor)->toBeGreaterThanOrEqual($job->timeout);+});++test('publish job unique id includes the platform and attempt', function () {+ $job = new PublishToSocialPlatform($this->postPlatform, 3);++ expect($job)->toBeInstanceOf(ShouldBeUnique::class)+ ->and($job->uniqueId())->toBe("{$this->postPlatform->id}:3")+ ->and($job->uniqueFor)->toBe(960);+});++test('publish job unique lock drops a duplicate dispatch for the same platform attempt', function () {+ Bus::fake([PublishToSocialPlatform::class]);++ PublishToSocialPlatform::dispatch($this->postPlatform, 0);+ PublishToSocialPlatform::dispatch($this->postPlatform, 0);++ Bus::assertDispatchedTimes(PublishToSocialPlatform::class, 1);+});++test('publish job unique lock allows concurrent dispatches for different attempts', function () {+ Bus::fake([PublishToSocialPlatform::class]);++ PublishToSocialPlatform::dispatch($this->postPlatform, 0);+ PublishToSocialPlatform::dispatch($this->postPlatform, 1);++ Bus::assertDispatchedTimes(PublishToSocialPlatform::class, 2);+ Bus::assertDispatched(PublishToSocialPlatform::class, fn ($job) => $job->uniqueAttempt === 0);+ Bus::assertDispatched(PublishToSocialPlatform::class, fn ($job) => $job->uniqueAttempt === 1);+});++test('failed hook skips platforms that are already failed', function () {+ Event::fake();+ Mail::fake();++ $this->postPlatform->update([+ 'status' => PlatformStatus::Failed,+ 'error_message' => __('posts.errors.publishing_timed_out'),+ 'error_context' => ['category' => 'timeout'],+ ]);++ (new PublishToSocialPlatform($this->postPlatform))->failed(new TypeError('Simulated worker kill'));++ $this->postPlatform->refresh();++ expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)+ ->and($this->postPlatform->error_message)->toBe(__('posts.errors.publishing_timed_out'))+ ->and($this->postPlatform->error_context['category'] ?? null)->toBe('timeout');+});++test('failed hook skips platforms that are already published', function () {+ Event::fake();+ Mail::fake();++ $this->postPlatform->update([+ 'status' => PlatformStatus::Published,+ 'platform_post_id' => 'already-published',+ 'error_message' => null,+ ]);++ (new PublishToSocialPlatform($this->postPlatform))->failed(new TypeError('Simulated worker kill'));++ $this->postPlatform->refresh();++ expect($this->postPlatform->status)->toBe(PlatformStatus::Published)+ ->and($this->postPlatform->platform_post_id)->toBe('already-published')+ ->and($this->postPlatform->error_message)->toBeNull();+});++test('pinterest media status 401 marks the account token expired and notifies to reconnect', function () {+ Event::fake();+ Queue::fake();+ Mail::fake();+ Sleep::fake();++ $pinterestAccount = SocialAccount::factory()->pinterest()->create([+ 'workspace_id' => $this->workspace->id,+ 'status' => AccountStatus::Connected,+ 'token_expires_at' => now()->addDays(30),+ 'meta' => ['default_board_id' => 'board_123'],+ ]);++ $postPlatform = PostPlatform::factory()->pinterest()->create([+ 'post_id' => $this->post->id,+ 'social_account_id' => $pinterestAccount->id,+ 'platform' => Platform::Pinterest,+ 'content_type' => ContentType::PinterestVideoPin,+ 'enabled' => true,+ 'status' => PlatformStatus::Pending,+ 'meta' => ['board_id' => 'board_123'],+ ]);++ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-video',+ 'path' => 'media/2026-01/video.mp4',+ 'url' => 'https://example.com/media/2026-01/video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'video.mp4',+ ]],+ ]);++ $s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';++ Http::fake(function ($request) use ($s3UploadUrl) {+ $url = $request->url();++ if (str_contains($url, '/v5/media') && $request->method() === 'POST') {+ return Http::response([+ 'media_id' => 'media_video_401_job',+ 'upload_url' => $s3UploadUrl,+ 'upload_parameters' => [],+ ], 201);+ }++ if ($url === $s3UploadUrl) {+ return Http::response('', 204);+ }++ if (str_contains($url, '/v5/media/media_video_401_job')) {+ return Http::response(['message' => 'Access token has expired or been revoked'], 401);+ }++ return Http::response('fake-video-content', 200);+ });++ $verifier = Mockery::mock(ConnectionVerifier::class);+ $verifier->shouldReceive('verify')->once()->andThrow(new Exception('Refresh failed'));+ $this->app->instance(ConnectionVerifier::class, $verifier);++ (new PublishToSocialPlatform($postPlatform))->handle();++ $postPlatform->refresh();+ $pinterestAccount->refresh();++ expect($postPlatform->status)->toBe(PlatformStatus::Failed)+ ->and($postPlatform->error_context['category'] ?? null)->toBe('token_expired')+ ->and($pinterestAccount->status)->toBe(AccountStatus::TokenExpired);++ Queue::assertPushed(SendNotification::class, function ($job) use ($pinterestAccount) {+ return $job->type === Type::AccountDisconnected+ && data_get($job->data, 'social_account_id') === $pinterestAccount->id+ && str_contains($job->title, 'needs to be reconnected');+ });+});+test('publish to social platform updates post status when all platforms finished', function () {Event::fake();diff --git a/tests/Feature/Services/Social/PinterestPublisherTest.php b/tests/Feature/Services/Social/PinterestPublisherTest.phpindex 3ca4877a0..75aba56d8 100644--- a/tests/Feature/Services/Social/PinterestPublisherTest.php+++ b/tests/Feature/Services/Social/PinterestPublisherTest.php@@ -4,6 +4,8 @@ declare(strict_types=1);use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;+use App\Exceptions\PlatformUnavailableException;+use App\Exceptions\Social\PinterestPublishException;use App\Exceptions\TokenExpiredException;use App\Models\Post;use App\Models\PostPlatform;@@ -12,7 +14,9 @@ use App\Models\User;use App\Models\Workspace;use App\Services\Media\MediaOptimizer;use App\Services\Social\PinterestPublisher;+use Illuminate\Http\Client\ConnectionException;use Illuminate\Support\Facades\Http;+use Illuminate\Support\Sleep;beforeEach(function () {$this->user = User::factory()->create();@@ -951,3 +955,354 @@ test('pinterest publisher throws exception for unsupported content type', functiexpect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(Exception::class, 'Unsupported content type');});++test('pinterest publisher waits through pending video processing before creating the pin', function () {+ Sleep::fake();++ $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);++ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-video',+ 'path' => 'media/2026-01/video.mp4',+ 'url' => 'https://example.com/media/2026-01/video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'video.mp4',+ ]],+ ]);++ $s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';+ $statusChecks = 0;++ Http::fake(function ($request) use ($s3UploadUrl, &$statusChecks) {+ $url = $request->url();++ if (str_contains($url, '/v5/media') && $request->method() === 'POST') {+ return Http::response([+ 'media_id' => 'media_video_pending',+ 'upload_url' => $s3UploadUrl,+ 'upload_parameters' => [],+ ], 201);+ }++ if ($url === $s3UploadUrl) {+ return Http::response('', 204);+ }++ if (str_contains($url, '/v5/media/media_video_pending')) {+ $statusChecks++;++ return Http::response([+ 'status' => $statusChecks < 3 ? 'processing' : 'succeeded',+ ], 200);+ }++ if (str_contains($url, '/v5/pins')) {+ return Http::response(['id' => 'video_pin_after_wait'], 200);+ }++ return Http::response('fake-video-content', 200);+ });++ $result = $this->publisher->publish($this->postPlatform);++ expect($result['id'])->toBe('video_pin_after_wait')+ ->and($statusChecks)->toBe(3);++ Sleep::assertSleptTimes(2);+});++test('pinterest publisher treats video processing timeout as platform unavailable for retry', function () {+ Sleep::fake();++ $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);++ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-video',+ 'path' => 'media/2026-01/video.mp4',+ 'url' => 'https://example.com/media/2026-01/video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'video.mp4',+ ]],+ ]);++ $s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';++ Http::fake(function ($request) use ($s3UploadUrl) {+ $url = $request->url();++ if (str_contains($url, '/v5/media') && $request->method() === 'POST') {+ return Http::response([+ 'media_id' => 'media_video_timeout',+ 'upload_url' => $s3UploadUrl,+ 'upload_parameters' => [],+ ], 201);+ }++ if ($url === $s3UploadUrl) {+ return Http::response('', 204);+ }++ if (str_contains($url, '/v5/media/media_video_timeout')) {+ return Http::response(['status' => 'processing'], 200);+ }++ return Http::response('fake-video-content', 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(PlatformUnavailableException::class, 'Pinterest media processing timeout after 60 attempts');++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));+ Sleep::assertSleptTimes(59);+});++test('pinterest publisher fails hard when video processing reports failed', function () {+ Sleep::fake();++ $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);++ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-video',+ 'path' => 'media/2026-01/video.mp4',+ 'url' => 'https://example.com/media/2026-01/video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'video.mp4',+ ]],+ ]);++ $s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';++ Http::fake(function ($request) use ($s3UploadUrl) {+ $url = $request->url();++ if (str_contains($url, '/v5/media') && $request->method() === 'POST') {+ return Http::response([+ 'media_id' => 'media_video_failed',+ 'upload_url' => $s3UploadUrl,+ 'upload_parameters' => [],+ ], 201);+ }++ if ($url === $s3UploadUrl) {+ return Http::response('', 204);+ }++ if (str_contains($url, '/v5/media/media_video_failed')) {+ return Http::response([+ 'status' => 'failed',+ 'failure_code' => 'VIDEO_TOO_LONG',+ ], 200);+ }++ return Http::response('fake-video-content', 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(PinterestPublishException::class, 'Pinterest media processing failed: VIDEO_TOO_LONG');++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));+ Sleep::assertNeverSlept();+});++test('pinterest publisher treats media status 401 as token expired', function () {+ Sleep::fake();++ $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);++ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-video',+ 'path' => 'media/2026-01/video.mp4',+ 'url' => 'https://example.com/media/2026-01/video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'video.mp4',+ ]],+ ]);++ $s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';++ Http::fake(function ($request) use ($s3UploadUrl) {+ $url = $request->url();++ if (str_contains($url, '/v5/media') && $request->method() === 'POST') {+ return Http::response([+ 'media_id' => 'media_video_401',+ 'upload_url' => $s3UploadUrl,+ 'upload_parameters' => [],+ ], 201);+ }++ if ($url === $s3UploadUrl) {+ return Http::response('', 204);+ }++ if (str_contains($url, '/v5/media/media_video_401')) {+ return Http::response(['message' => 'Access token has expired or been revoked'], 401);+ }++ return Http::response('fake-video-content', 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(TokenExpiredException::class, 'Access token has expired or been revoked');++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));+ Sleep::assertNeverSlept();+});++test('pinterest publisher keeps polling through transient media status http errors', function () {+ Sleep::fake();++ $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);++ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-video',+ 'path' => 'media/2026-01/video.mp4',+ 'url' => 'https://example.com/media/2026-01/video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'video.mp4',+ ]],+ ]);++ $s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';+ $statusChecks = 0;++ Http::fake(function ($request) use ($s3UploadUrl, &$statusChecks) {+ $url = $request->url();++ if (str_contains($url, '/v5/media') && $request->method() === 'POST') {+ return Http::response([+ 'media_id' => 'media_video_5xx',+ 'upload_url' => $s3UploadUrl,+ 'upload_parameters' => [],+ ], 201);+ }++ if ($url === $s3UploadUrl) {+ return Http::response('', 204);+ }++ if (str_contains($url, '/v5/media/media_video_5xx')) {+ $statusChecks++;++ if ($statusChecks < 3) {+ return Http::response(['message' => 'temporary error'], 503);+ }++ return Http::response(['status' => 'succeeded'], 200);+ }++ if (str_contains($url, '/v5/pins')) {+ return Http::response(['id' => 'video_pin_after_5xx'], 200);+ }++ return Http::response('fake-video-content', 200);+ });++ $result = $this->publisher->publish($this->postPlatform);++ expect($result['id'])->toBe('video_pin_after_5xx')+ ->and($statusChecks)->toBe(3);++ Sleep::assertSleptTimes(2);+});++test('pinterest publisher treats unknown media status as still processing until timeout', function (string $status) {+ Sleep::fake();++ $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);++ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-video',+ 'path' => 'media/2026-01/video.mp4',+ 'url' => 'https://example.com/media/2026-01/video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'video.mp4',+ ]],+ ]);++ $s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';++ Http::fake(function ($request) use ($s3UploadUrl, $status) {+ $url = $request->url();++ if (str_contains($url, '/v5/media') && $request->method() === 'POST') {+ return Http::response([+ 'media_id' => 'media_video_unknown',+ 'upload_url' => $s3UploadUrl,+ 'upload_parameters' => [],+ ], 201);+ }++ if ($url === $s3UploadUrl) {+ return Http::response('', 204);+ }++ if (str_contains($url, '/v5/media/media_video_unknown')) {+ return Http::response(['status' => $status], 200);+ }++ return Http::response('fake-video-content', 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(PlatformUnavailableException::class, 'Pinterest media processing timeout after 60 attempts');++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));+ Sleep::assertSleptTimes(59);+})->with([+ 'registered',+ 'not_a_real_status',+ '',+]);++test('pinterest publisher treats media status connection errors as platform unavailable', function () {+ Sleep::fake();++ $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);++ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-video',+ 'path' => 'media/2026-01/video.mp4',+ 'url' => 'https://example.com/media/2026-01/video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'video.mp4',+ ]],+ ]);++ $s3UploadUrl = 'https://pinterest-media-upload.s3.amazonaws.com/upload';++ Http::fake(function ($request) use ($s3UploadUrl) {+ $url = $request->url();++ if (str_contains($url, '/v5/media') && $request->method() === 'POST') {+ return Http::response([+ 'media_id' => 'media_video_conn',+ 'upload_url' => $s3UploadUrl,+ 'upload_parameters' => [],+ ], 201);+ }++ if ($url === $s3UploadUrl) {+ return Http::response('', 204);+ }++ if (str_contains($url, '/v5/media/media_video_conn')) {+ throw new ConnectionException('cURL error 28: Connection timed out');+ }++ return Http::response('fake-video-content', 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(PlatformUnavailableException::class, 'Pinterest media status check connection failed');++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));+ Sleep::assertNeverSlept();+});diff --git a/tests/Unit/Pinterest/MediaUploadStatusTest.php b/tests/Unit/Pinterest/MediaUploadStatusTest.phpnew file mode 100644index 000000000..c9e082b42--- /dev/null+++ b/tests/Unit/Pinterest/MediaUploadStatusTest.php@@ -0,0 +1,24 @@+<?php++declare(strict_types=1);++use App\Enums\Pinterest\MediaUploadStatus;++test('media upload status mirrors the pinterest api enum values', function () {+ expect(MediaUploadStatus::cases())->toHaveCount(4)+ ->and(MediaUploadStatus::Registered->value)->toBe('registered')+ ->and(MediaUploadStatus::Processing->value)->toBe('processing')+ ->and(MediaUploadStatus::Succeeded->value)->toBe('succeeded')+ ->and(MediaUploadStatus::Failed->value)->toBe('failed');+});++test('media upload status tryFrom accepts known values and rejects unknown', function (string $value, ?MediaUploadStatus $expected) {+ expect(MediaUploadStatus::tryFrom($value))->toBe($expected);+})->with([+ ['registered', MediaUploadStatus::Registered],+ ['processing', MediaUploadStatus::Processing],+ ['succeeded', MediaUploadStatus::Succeeded],+ ['failed', MediaUploadStatus::Failed],+ ['unknown', null],+ ['', null],+]);diff --git a/tests/Unit/PostsErrorsTranslationTest.php b/tests/Unit/PostsErrorsTranslationTest.phpnew file mode 100644index 000000000..d41224475--- /dev/null+++ b/tests/Unit/PostsErrorsTranslationTest.php@@ -0,0 +1,27 @@+<?php++declare(strict_types=1);++test('platform unavailable and publish timeout error keys exist in every locale', function () {+ $locales = collect(glob(lang_path('*')) ?: [])+ ->filter(fn (string $path) => is_dir($path) && is_file("{$path}/posts.php"))+ ->map(fn (string $path) => basename($path))+ ->values()+ ->all();++ expect($locales)->not->toBeEmpty();++ foreach ($locales as $locale) {+ $translations = require lang_path("{$locale}/posts.php");++ expect(data_get($translations, 'errors.platform_unavailable'))+ ->toBeString()+ ->not->toBeEmpty("Missing errors.platform_unavailable in {$locale}")+ ->and(data_get($translations, 'errors.platform_unavailable_exhausted'))+ ->toBeString()+ ->not->toBeEmpty("Missing errors.platform_unavailable_exhausted in {$locale}")+ ->and(data_get($translations, 'errors.publishing_timed_out'))+ ->toBeString()+ ->not->toBeEmpty("Missing errors.publishing_timed_out in {$locale}");+ }+});