Skip to content

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

7.9 KB
Raw Blame
<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Actions\Post\FinalizePostPublication;
use App\Enums\GoogleBusiness\LocalPostState;
use App\Enums\Post\PublishStatus as Status;
use App\Events\PostStatusUpdated;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\GoogleBusinessPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Social\ConnectionVerifier;
use App\Services\Social\GoogleBusinessPublisher;
use App\Support\Social\GoogleBusinessDerivativeCleaner;
use Carbon\CarbonInterface;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Http\Client\ConnectionException;
use Throwable;

/**
 * Settles a Google Business Profile target that the publish job had to leave
 * open. Google answers a create with 200 long before the post clears review,
 * so the state it reports later is what decides published vs. rejected.
 */
class ReconcileGoogleBusinessPost implements ShouldBeUnique, ShouldQueue
{
    use Queueable;

    public int $tries = 3;

    /** Must exceed HasSocialHttpClient's 120s HTTP timeout so a slow GET cannot kill the worker. */
    public int $timeout = 180;

    public int $uniqueFor = 600;

    /**
     * How long a target may sit in review before we stop believing it will
     * settle. Generous on purpose: a short ceiling fails posts that were only
     * slow, and Google normally clears review in minutes.
     */
    public const REVIEW_CEILING_HOURS = 24;

    public function __construct(public Post $post)
    {
        $this->onQueue($post->platform->queue());
    }

    public function uniqueId(): string
    {
        return $this->post->id;
    }

    public function handle(): void
    {
        $this->post->refresh();

        if ($this->post->publish_status !== Status::PendingReview || blank($this->post->platform_post_id)) {
            return;
        }

        $account = $this->post->socialAccount;

        if (! $account instanceof SocialAccount) {
            $this->giveUp(__('posts.errors.account_disconnected'), [
                'category' => 'account_disconnected',
            ]);

            return;
        }

        try {
            $remote = $this->fetchRemote($account);
        } catch (TokenExpiredException) {
            $remote = $this->retryAfterExpiredToken($account);

            if ($remote === null) {
                return;
            }
        } catch (PlatformUnavailableException|ConnectionException $e) {
            $this->deferOrGiveUp($e->getMessage());

            return;
        } catch (GoogleBusinessPublishException $e) {
            $this->handlePublishException($e);

            return;
        }

        $state = LocalPostState::fromApi(data_get($remote, 'state'));
        $platformUrl = (string) (data_get($remote, 'searchUrl') ?: $this->post->platform_url);

        if ($state->isLive()) {
            $this->post->markPublicationPublished((string) $this->post->platform_post_id, $platformUrl);
        } elseif ($state->isRejected()) {
            $this->post->markPublicationRejected(
                (string) $this->post->platform_post_id,
                $platformUrl,
                __('posts.errors.rejected_in_review'),
                ['provider_state' => $state->value],
            );
        } elseif ($this->reviewExpired()) {
            $this->post->markPublicationRejected(
                (string) $this->post->platform_post_id,
                $platformUrl,
                __('posts.errors.review_unconfirmed'),
                ['category' => 'review_unconfirmed', 'provider_state' => $state->value],
            );
        } else {
            $this->post->writePublication([
                'platform_url' => $platformUrl,
                'last_reconciled_at' => now(),
            ]);

            return;
        }

        $this->post->writePublication(['last_reconciled_at' => now()]);
        $this->settle();
    }

    public function failed(?Throwable $exception): void
    {
        $this->post->refresh();

        if ($this->post->publish_status !== Status::PendingReview) {
            return;
        }

        $this->deferOrGiveUp(
            $exception instanceof GoogleBusinessPublishException
                ? $exception->userMessage
                : ($exception?->getMessage() ?: __('posts.errors.review_unconfirmed')),
        );
    }

    /**
     * @return array<string, mixed>
     */
    private function fetchRemote(SocialAccount $account): array
    {
        if ($account->needsProactiveTokenRefresh()) {
            app(ConnectionVerifier::class)->refreshToken($account);
        }

        return app(GoogleBusinessPublisher::class)->fetchLocalPost(
            $account,
            (string) $this->post->platform_post_id,
        );
    }

    /**
     * Publish retries a 401 through verify(); reconcile used to park the
     * target for 24h even when a refresh would have unstuck it.
     *
     * @return array<string, mixed>|null
     */
    private function retryAfterExpiredToken(SocialAccount $account): ?array
    {
        try {
            app(ConnectionVerifier::class)->verify($account);
            $account->refresh();
        } catch (TokenExpiredException $e) {
            $account->markAsTokenExpired($e->getMessage());
            $this->deferOrGiveUp($e->getMessage());

            return null;
        } catch (PlatformUnavailableException|ConnectionException $e) {
            $this->deferOrGiveUp($e->getMessage());

            return null;
        } catch (GoogleBusinessPublishException $e) {
            $this->handlePublishException($e);

            return null;
        }

        try {
            return $this->fetchRemote($account);
        } catch (TokenExpiredException $e) {
            $this->deferOrGiveUp($e->getMessage());

            return null;
        } catch (PlatformUnavailableException|ConnectionException $e) {
            $this->deferOrGiveUp($e->getMessage());

            return null;
        } catch (GoogleBusinessPublishException $e) {
            $this->handlePublishException($e);

            return null;
        }
    }

    private function handlePublishException(GoogleBusinessPublishException $e): void
    {
        if (in_array($e->category, [ErrorCategory::ServerError, ErrorCategory::RateLimit], true)) {
            $this->deferOrGiveUp($e->userMessage);

            return;
        }

        $this->giveUp($e->userMessage, [
            'category' => $e->category->value,
            'platform_error_code' => $e->platformErrorCode,
        ]);
    }

    private function deferOrGiveUp(string $errorMessage): void
    {
        if ($this->reviewExpired()) {
            $this->giveUp(__('posts.errors.review_unconfirmed'), [
                'category' => 'review_unconfirmed',
                'detail' => $errorMessage,
            ]);

            return;
        }

        $this->post->writePublication(['last_reconciled_at' => now()]);
    }

    /**
     * @param  array<string, mixed>  $errorContext
     */
    private function giveUp(string $errorMessage, array $errorContext = []): void
    {
        $this->post->markPublicationRejected(
            (string) $this->post->platform_post_id,
            $this->post->platform_url,
            $errorMessage,
            $errorContext,
        );
        $this->post->writePublication(['last_reconciled_at' => now()]);
        $this->settle();
    }

    private function reviewExpired(): bool
    {
        $submittedAt = $this->post->submitted_at;

        return $submittedAt instanceof CarbonInterface
            && $submittedAt->copy()->addHours(self::REVIEW_CEILING_HOURS)->isPast();
    }

    private function settle(): void
    {
        app(GoogleBusinessDerivativeCleaner::class)->cleanup($this->post);
        app(FinalizePostPublication::class)->handle($this->post);
        PostStatusUpdated::dispatch($this->post->fresh());
    }
}