Add a Publisher abstraction and queued job to publish from the UI
Introduce Publisher/PublisherManager (WordPress + Reddit implementations) so publishing logic is shared between the CLI, the queue, and future network integrations. Add a "Publish" button on the Posts page that dispatches PublishPostJob instead of blocking the request — Reddit's publisher shells out to the existing Playwright sidecar and can take tens of seconds, so it can't run synchronously in a web request. Adds a `target` field (e.g. subreddit) and `publishing` status to Post, plus a `publish_error` field so failures surface in the UI. Refactors posts:publish to delegate to WordPressPublisher without changing its CLI output contract (existing tests pass unchanged). Also fixes two bugs found along the way: UpdatePostRequest was silently dropping `published_url` from PATCH requests (never in its validation rules, despite AI_API.md documenting it), and three Livewire index-page tests were broken by the earlier auth change (never re-run after adding the `auth` middleware) since they hit routes via HTTP without a logged-in user. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,9 +3,8 @@
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Post;
|
||||
use App\Support\Publishing\WordPressPublisher;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class PublishPost extends Command
|
||||
{
|
||||
@@ -13,7 +12,7 @@ class PublishPost extends Command
|
||||
|
||||
protected $description = 'Publish an existing blog post to its site\'s WordPress REST API';
|
||||
|
||||
public function handle(): int
|
||||
public function handle(WordPressPublisher $publisher): int
|
||||
{
|
||||
$post = Post::with('site')->find($this->argument('post'));
|
||||
|
||||
@@ -25,48 +24,20 @@ class PublishPost extends Command
|
||||
return $this->failWith("Post {$post->id} has type '{$post->type}', expected 'blog' to publish to a CMS.");
|
||||
}
|
||||
|
||||
if (! $post->title) {
|
||||
return $this->failWith("Post {$post->id} has no title, required to publish to WordPress.");
|
||||
$result = $publisher->publish($post);
|
||||
|
||||
if ($result->success) {
|
||||
$post->update(['status' => 'published', 'published_url' => $result->url, 'publish_error' => null]);
|
||||
$this->line(json_encode(['success' => true, 'url' => $result->url]));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$site = $post->site;
|
||||
|
||||
if ($site->cms_type !== 'wordpress') {
|
||||
return $this->failWith("Site '{$site->name}' is not configured as WordPress (cms_type={$site->cms_type}).");
|
||||
if ($result->attempted) {
|
||||
$post->update(['status' => 'failed', 'publish_error' => $result->error]);
|
||||
}
|
||||
|
||||
if (! $site->wp_username || ! $site->wp_app_password) {
|
||||
return $this->failWith("Site '{$site->name}' is missing WordPress credentials.");
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withBasicAuth($site->wp_username, $site->wp_app_password)
|
||||
->post(rtrim($site->url, '/') . '/wp-json/wp/v2/posts', [
|
||||
'title' => $post->title,
|
||||
'content' => $post->body,
|
||||
'status' => 'publish',
|
||||
]);
|
||||
} catch (ConnectionException $e) {
|
||||
return $this->publishFailed($post, "could not connect to site: {$e->getMessage()}");
|
||||
}
|
||||
|
||||
if ($response->failed()) {
|
||||
$message = $response->json('message') ?? 'unexpected response from WordPress';
|
||||
|
||||
return $this->publishFailed($post, $message);
|
||||
}
|
||||
|
||||
$link = $response->json('link');
|
||||
|
||||
if (! $link) {
|
||||
return $this->publishFailed($post, 'unexpected response from WordPress: missing post link');
|
||||
}
|
||||
|
||||
$post->update(['status' => 'published', 'published_url' => $link]);
|
||||
|
||||
$this->line(json_encode(['success' => true, 'url' => $link]));
|
||||
|
||||
return self::SUCCESS;
|
||||
return $this->failWith($result->error);
|
||||
}
|
||||
|
||||
private function failWith(string $message): int
|
||||
@@ -75,11 +46,4 @@ class PublishPost extends Command
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
private function publishFailed(Post $post, string $message): int
|
||||
{
|
||||
$post->update(['status' => 'failed']);
|
||||
|
||||
return $this->failWith($message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ class StorePostRequest extends FormRequest
|
||||
'type' => ['required', 'string', 'in:' . implode(',', Post::TYPES)],
|
||||
'title' => ['nullable', 'string', 'max:255'],
|
||||
'body' => ['required', 'string'],
|
||||
'target' => ['nullable', 'string', 'max:255'],
|
||||
'status' => ['sometimes', 'string', 'in:' . implode(',', Post::STATUSES)],
|
||||
'scheduled_at' => ['nullable', 'date'],
|
||||
];
|
||||
|
||||
@@ -20,8 +20,10 @@ class UpdatePostRequest extends FormRequest
|
||||
'type' => ['sometimes', 'required', 'string', 'in:' . implode(',', Post::TYPES)],
|
||||
'title' => ['nullable', 'string', 'max:255'],
|
||||
'body' => ['sometimes', 'required', 'string'],
|
||||
'target' => ['nullable', 'string', 'max:255'],
|
||||
'status' => ['sometimes', 'string', 'in:' . implode(',', Post::STATUSES)],
|
||||
'scheduled_at' => ['nullable', 'date'],
|
||||
'published_url' => ['nullable', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,9 +16,11 @@ class PostResource extends JsonResource
|
||||
'type' => $this->type,
|
||||
'title' => $this->title,
|
||||
'body' => $this->body,
|
||||
'target' => $this->target,
|
||||
'status' => $this->status,
|
||||
'scheduled_at' => $this->scheduled_at,
|
||||
'published_url' => $this->published_url,
|
||||
'publish_error' => $this->publish_error,
|
||||
'created_at' => $this->created_at,
|
||||
'updated_at' => $this->updated_at,
|
||||
];
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?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', 'socialAccount'])->find($this->postId);
|
||||
|
||||
if (! $post) {
|
||||
return;
|
||||
}
|
||||
|
||||
$publisher = $publishers->resolve($post);
|
||||
|
||||
if (! $publisher) {
|
||||
$post->update(['status' => 'draft', 'publish_error' => "No publisher available for post type '{$post->type}'."]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$result = $publisher->publish($post);
|
||||
|
||||
if ($result->success) {
|
||||
$post->update(['status' => 'published', 'published_url' => $result->url, 'publish_error' => null]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$post->update([
|
||||
'status' => $result->attempted ? 'failed' : 'draft',
|
||||
'publish_error' => $result->error,
|
||||
]);
|
||||
|
||||
Log::error('post publish failed', ['post_id' => $post->id, 'error' => $result->error]);
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ class Login extends Component
|
||||
return;
|
||||
}
|
||||
|
||||
request()->session()->regenerate();
|
||||
session()->regenerate();
|
||||
|
||||
$this->redirect(route('sites.index'), navigate: true);
|
||||
}
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
namespace App\Livewire\Posts;
|
||||
|
||||
use App\Jobs\PublishPostJob;
|
||||
use App\Models\Post;
|
||||
use App\Models\Site;
|
||||
use App\Models\SocialAccount;
|
||||
use App\Support\Publishing\PublisherManager;
|
||||
use Livewire\Attributes\Layout;
|
||||
use Livewire\Component;
|
||||
|
||||
@@ -25,21 +27,45 @@ class Index extends Component
|
||||
|
||||
public string $body = '';
|
||||
|
||||
public string $target = '';
|
||||
|
||||
public string $status = 'draft';
|
||||
|
||||
public string $scheduledAt = '';
|
||||
|
||||
public ?string $publishNotice = null;
|
||||
|
||||
public function render()
|
||||
{
|
||||
$posts = Post::with(['site', 'socialAccount'])->orderByDesc('created_at')->get();
|
||||
|
||||
return view('livewire.posts.index', [
|
||||
'posts' => Post::with(['site', 'socialAccount'])->orderByDesc('created_at')->get(),
|
||||
'posts' => $posts,
|
||||
'sites' => Site::orderBy('name')->get(),
|
||||
'accounts' => SocialAccount::orderBy('username')->get(),
|
||||
'types' => Post::TYPES,
|
||||
'statuses' => Post::STATUSES,
|
||||
'hasPublishing' => $posts->contains('status', 'publishing'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function publish(int $id): void
|
||||
{
|
||||
$this->publishNotice = null;
|
||||
|
||||
$post = Post::with('site')->findOrFail($id);
|
||||
|
||||
if (! app(PublisherManager::class)->resolve($post)) {
|
||||
$this->publishNotice = "No publisher available yet for post type '{$post->type}'.";
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$post->update(['status' => 'publishing', 'publish_error' => null]);
|
||||
|
||||
PublishPostJob::dispatch($post->id);
|
||||
}
|
||||
|
||||
public function create(): void
|
||||
{
|
||||
$this->resetForm();
|
||||
@@ -55,6 +81,7 @@ class Index extends Component
|
||||
$this->type = $post->type;
|
||||
$this->title = (string) $post->title;
|
||||
$this->body = $post->body;
|
||||
$this->target = (string) $post->target;
|
||||
$this->status = $post->status;
|
||||
$this->scheduledAt = $post->scheduled_at?->format('Y-m-d\TH:i') ?? '';
|
||||
$this->showForm = true;
|
||||
@@ -68,6 +95,7 @@ class Index extends Component
|
||||
'type' => ['required', 'string', 'in:' . implode(',', Post::TYPES)],
|
||||
'title' => ['nullable', 'string', 'max:255'],
|
||||
'body' => ['required', 'string'],
|
||||
'target' => ['nullable', 'string', 'max:255'],
|
||||
'status' => ['required', 'string', 'in:' . implode(',', Post::STATUSES)],
|
||||
'scheduledAt' => ['nullable', 'date'],
|
||||
]);
|
||||
@@ -78,6 +106,7 @@ class Index extends Component
|
||||
'type' => $validated['type'],
|
||||
'title' => $validated['title'] ?: null,
|
||||
'body' => $validated['body'],
|
||||
'target' => $validated['target'] ?: null,
|
||||
'status' => $validated['status'],
|
||||
'scheduled_at' => $validated['scheduledAt'] ?: null,
|
||||
]);
|
||||
@@ -99,6 +128,7 @@ class Index extends Component
|
||||
$this->type = '';
|
||||
$this->title = '';
|
||||
$this->body = '';
|
||||
$this->target = '';
|
||||
$this->status = 'draft';
|
||||
$this->scheduledAt = '';
|
||||
$this->resetValidation();
|
||||
|
||||
+3
-1
@@ -15,7 +15,7 @@ class Post extends Model
|
||||
'tiktok', 'linkedin', 'youtube', 'blog', 'other',
|
||||
];
|
||||
|
||||
public const STATUSES = ['draft', 'scheduled', 'published', 'failed'];
|
||||
public const STATUSES = ['draft', 'scheduled', 'publishing', 'published', 'failed'];
|
||||
|
||||
protected $fillable = [
|
||||
'site_id',
|
||||
@@ -23,9 +23,11 @@ class Post extends Model
|
||||
'type',
|
||||
'title',
|
||||
'body',
|
||||
'target',
|
||||
'status',
|
||||
'scheduled_at',
|
||||
'published_url',
|
||||
'publish_error',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Support\Publishing\PublisherManager;
|
||||
use App\Support\Publishing\RedditPublisher;
|
||||
use App\Support\Publishing\WordPressPublisher;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
@@ -11,7 +14,10 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
//
|
||||
$this->app->singleton(PublisherManager::class, fn ($app) => new PublisherManager([
|
||||
$app->make(WordPressPublisher::class),
|
||||
$app->make(RedditPublisher::class),
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Publishing;
|
||||
|
||||
final class PublishResult
|
||||
{
|
||||
private function __construct(
|
||||
public readonly bool $success,
|
||||
public readonly bool $attempted,
|
||||
public readonly ?string $url = null,
|
||||
public readonly ?string $error = null,
|
||||
) {}
|
||||
|
||||
public static function success(string $url): self
|
||||
{
|
||||
return new self(success: true, attempted: true, url: $url);
|
||||
}
|
||||
|
||||
/**
|
||||
* The publish attempt itself failed (network, API error, etc).
|
||||
*/
|
||||
public static function failed(string $error): self
|
||||
{
|
||||
return new self(success: false, attempted: true, error: $error);
|
||||
}
|
||||
|
||||
/**
|
||||
* A precondition wasn't met — no attempt was made (bad data, missing
|
||||
* credentials, wrong type). Callers should not treat this the same as
|
||||
* a failed attempt.
|
||||
*/
|
||||
public static function rejected(string $error): self
|
||||
{
|
||||
return new self(success: false, attempted: false, error: $error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Publishing;
|
||||
|
||||
use App\Models\Post;
|
||||
|
||||
interface Publisher
|
||||
{
|
||||
/**
|
||||
* Whether this publisher handles the given post's type. Does not imply
|
||||
* the post is actually publishable (see publish()'s rejected results).
|
||||
*/
|
||||
public function supports(Post $post): bool;
|
||||
|
||||
public function publish(Post $post): PublishResult;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Publishing;
|
||||
|
||||
use App\Models\Post;
|
||||
|
||||
class PublisherManager
|
||||
{
|
||||
/**
|
||||
* @param array<Publisher> $publishers
|
||||
*/
|
||||
public function __construct(private readonly array $publishers) {}
|
||||
|
||||
public function resolve(Post $post): ?Publisher
|
||||
{
|
||||
foreach ($this->publishers as $publisher) {
|
||||
if ($publisher->supports($post)) {
|
||||
return $publisher;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Publishing;
|
||||
|
||||
use App\Models\Post;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Process;
|
||||
|
||||
class RedditPublisher implements Publisher
|
||||
{
|
||||
public function supports(Post $post): bool
|
||||
{
|
||||
return $post->type === 'reddit';
|
||||
}
|
||||
|
||||
public function publish(Post $post): PublishResult
|
||||
{
|
||||
if (! $post->title) {
|
||||
return PublishResult::rejected("Post {$post->id} has no title, required for a Reddit post.");
|
||||
}
|
||||
|
||||
if (! $post->target) {
|
||||
return PublishResult::rejected("Post {$post->id} has no target subreddit set.");
|
||||
}
|
||||
|
||||
$account = $post->socialAccount;
|
||||
|
||||
if (! $account || $account->network !== 'reddit') {
|
||||
return PublishResult::rejected("Post {$post->id} has no linked Reddit social account.");
|
||||
}
|
||||
|
||||
$result = Process::timeout(120)->run([
|
||||
base_path('sidecars/reddit-post/run.sh'),
|
||||
"--username={$account->username}",
|
||||
"--password={$account->password}",
|
||||
"--subreddit={$post->target}",
|
||||
"--title={$post->title}",
|
||||
"--body={$post->body}",
|
||||
]);
|
||||
|
||||
$data = json_decode(trim($result->output()), true);
|
||||
|
||||
if (! is_array($data) || ! array_key_exists('success', $data)) {
|
||||
Log::error('reddit sidecar returned unparseable output', [
|
||||
'post_id' => $post->id,
|
||||
'output' => $result->output(),
|
||||
'stderr' => $result->errorOutput(),
|
||||
]);
|
||||
|
||||
return PublishResult::failed('Reddit sidecar returned unparseable output — check logs.');
|
||||
}
|
||||
|
||||
if (! $data['success']) {
|
||||
return PublishResult::failed($data['error'] ?? 'unknown Reddit sidecar failure');
|
||||
}
|
||||
|
||||
return PublishResult::success($data['url']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Publishing;
|
||||
|
||||
use App\Models\Post;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class WordPressPublisher implements Publisher
|
||||
{
|
||||
public function supports(Post $post): bool
|
||||
{
|
||||
return $post->type === 'blog';
|
||||
}
|
||||
|
||||
public function publish(Post $post): PublishResult
|
||||
{
|
||||
if (! $post->title) {
|
||||
return PublishResult::rejected("Post {$post->id} has no title, required to publish to WordPress.");
|
||||
}
|
||||
|
||||
$site = $post->site;
|
||||
|
||||
if ($site->cms_type !== 'wordpress') {
|
||||
return PublishResult::rejected("Site '{$site->name}' is not configured as WordPress (cms_type={$site->cms_type}).");
|
||||
}
|
||||
|
||||
if (! $site->wp_username || ! $site->wp_app_password) {
|
||||
return PublishResult::rejected("Site '{$site->name}' is missing WordPress credentials.");
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withBasicAuth($site->wp_username, $site->wp_app_password)
|
||||
->post(rtrim($site->url, '/').'/wp-json/wp/v2/posts', [
|
||||
'title' => $post->title,
|
||||
'content' => $post->body,
|
||||
'status' => 'publish',
|
||||
]);
|
||||
} catch (ConnectionException $e) {
|
||||
return PublishResult::failed("could not connect to site: {$e->getMessage()}");
|
||||
}
|
||||
|
||||
if ($response->failed()) {
|
||||
return PublishResult::failed($response->json('message') ?? 'unexpected response from WordPress');
|
||||
}
|
||||
|
||||
$link = $response->json('link');
|
||||
|
||||
if (! $link) {
|
||||
return PublishResult::failed('unexpected response from WordPress: missing post link');
|
||||
}
|
||||
|
||||
return PublishResult::success($link);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user