Files

99 lines
2.8 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Jobs;
use App\Models\Post;
use App\Support\Publishing\PublisherManager;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class PublishPostJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $timeout = 150;
public function __construct(public readonly int $postId) {}
public function handle(PublisherManager $publishers): void
{
$post = Post::with(['site', 'socialAccounts'])->find($this->postId);
if (! $post) {
return;
}
// A duplicate/stale job for a post already resolved by an earlier
// run of this same job (e.g. a double-dispatch while no worker was
// running) — skip it rather than risk publishing twice.
if ($post->status !== 'publishing') {
return;
}
$results = [];
$errors = [];
$urls = [];
// Get all social accounts that match the post's type
$socialAccounts = $post->socialAccounts->filter(
fn ($account) => $account->network === $post->type
);
if ($socialAccounts->isEmpty()) {
$post->update([
'status' => 'draft',
'publish_error' => "No social accounts linked to this post for type '{$post->type}'.",
]);
return;
}
$publisher = $publishers->resolve($post);
if (! $publisher) {
$post->update(['status' => 'draft', 'publish_error' => "No publisher available for post type '{$post->type}'."]);
return;
}
// Publish to each social account
foreach ($socialAccounts as $socialAccount) {
$result = $publisher->publish($post, $socialAccount);
$results[] = $result;
if ($result->success) {
$urls[] = $result->url;
} else {
$errors[] = $result->error;
}
}
// If at least one succeeded, mark as published with the first URL
if (! empty($urls)) {
$post->update([
'status' => 'published',
'published_url' => $urls[0],
'publish_error' => ! empty($errors) ? implode('; ', $errors) : null,
]);
return;
}
// All failed
$post->update([
'status' => 'failed',
'published_url' => null,
'publish_error' => implode('; ', $errors),
]);
Log::error('post publish failed for all accounts', [
'post_id' => $post->id,
'errors' => $errors,
]);
}
}