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:
@@ -36,8 +36,11 @@ SocialAccount (login for a social network)
|
|||||||
|
|
||||||
Post (one piece of content, belongs to a Site, optionally a SocialAccount)
|
Post (one piece of content, belongs to a Site, optionally a SocialAccount)
|
||||||
└─ type: same vocabulary as SocialAccount.network, plus "blog"
|
└─ type: same vocabulary as SocialAccount.network, plus "blog"
|
||||||
└─ status: draft -> scheduled -> published | failed
|
└─ target: nullable, network-specific destination (e.g. a subreddit for type=reddit)
|
||||||
|
└─ status: draft -> scheduled -> publishing -> published | failed
|
||||||
└─ published_url: set once it's actually live somewhere
|
└─ published_url: set once it's actually live somewhere
|
||||||
|
└─ publish_error: set to the failure reason when status=failed (or when a
|
||||||
|
publish attempt is rejected back to draft — see below)
|
||||||
```
|
```
|
||||||
|
|
||||||
The typical agent loop is:
|
The typical agent loop is:
|
||||||
@@ -45,7 +48,14 @@ The typical agent loop is:
|
|||||||
1. Read Sites/Social Accounts to know what you're working with (`GET /api/sites`, `GET /api/accounts`).
|
1. Read Sites/Social Accounts to know what you're working with (`GET /api/sites`, `GET /api/accounts`).
|
||||||
2. Create a Post as a draft (`POST /api/posts`), or find one that's already `due` (`GET /api/posts?due=1`).
|
2. Create a Post as a draft (`POST /api/posts`), or find one that's already `due` (`GET /api/posts?due=1`).
|
||||||
3. Publish it externally, by whatever mechanism fits its `type`/site (see "How to actually publish" below).
|
3. Publish it externally, by whatever mechanism fits its `type`/site (see "How to actually publish" below).
|
||||||
4. Report the outcome back with `PATCH /api/posts/{id}` — set `status` to `published` or `failed`, and `published_url` if you have one, **unless** you used the `posts:publish` command, which already does this step for you.
|
4. Report the outcome back with `PATCH /api/posts/{id}` — set `status` to `published` or `failed`, and `published_url` if you have one, **unless** you used the `posts:publish` command or the app's own Publish button/job, which already does this step for you.
|
||||||
|
|
||||||
|
`publishing` is a transient status set automatically while a background publish
|
||||||
|
job (triggered by the app's own "Publish" button in the UI) is running — you
|
||||||
|
won't normally set it yourself. If the underlying publisher rejects the post
|
||||||
|
before attempting anything (missing title, no target, credentials not set),
|
||||||
|
the job puts it back to `draft` rather than `failed`, since nothing was
|
||||||
|
actually attempted; check `publish_error` for why.
|
||||||
|
|
||||||
## Sites
|
## Sites
|
||||||
|
|
||||||
@@ -117,7 +127,7 @@ Full CRUD — this is the resource the agent actively drives.
|
|||||||
|
|
||||||
`GET /api/posts`
|
`GET /api/posts`
|
||||||
Query params (all optional, combine freely):
|
Query params (all optional, combine freely):
|
||||||
- `?status=` — exact match: `draft` | `scheduled` | `published` | `failed`
|
- `?status=` — exact match: `draft` | `scheduled` | `publishing` | `published` | `failed`
|
||||||
- `?site_id=` — exact match
|
- `?site_id=` — exact match
|
||||||
- `?social_account_id=` — exact match
|
- `?social_account_id=` — exact match
|
||||||
- `?due=1` — the important one for automation: returns posts where
|
- `?due=1` — the important one for automation: returns posts where
|
||||||
@@ -134,6 +144,7 @@ Body:
|
|||||||
"type": "blog",
|
"type": "blog",
|
||||||
"title": "Optional title",
|
"title": "Optional title",
|
||||||
"body": "Required content",
|
"body": "Required content",
|
||||||
|
"target": null,
|
||||||
"status": "draft",
|
"status": "draft",
|
||||||
"scheduled_at": null
|
"scheduled_at": null
|
||||||
}
|
}
|
||||||
@@ -141,8 +152,9 @@ Body:
|
|||||||
Validation: `site_id` required, must exist. `social_account_id` nullable,
|
Validation: `site_id` required, must exist. `social_account_id` nullable,
|
||||||
must exist if given. `type` required, one of `twitter`, `instagram`,
|
must exist if given. `type` required, one of `twitter`, `instagram`,
|
||||||
`facebook`, `reddit`, `tiktok`, `linkedin`, `youtube`, `blog`, `other`.
|
`facebook`, `reddit`, `tiktok`, `linkedin`, `youtube`, `blog`, `other`.
|
||||||
`body` required. `title` nullable. `status` defaults to `draft` if omitted.
|
`body` required. `title` nullable. `target` nullable — a network-specific
|
||||||
`scheduled_at` nullable datetime.
|
destination, e.g. the subreddit name for `type=reddit`. `status` defaults to
|
||||||
|
`draft` if omitted. `scheduled_at` nullable datetime.
|
||||||
|
|
||||||
Note: `type` and the linked Social Account's `network` are **not**
|
Note: `type` and the linked Social Account's `network` are **not**
|
||||||
cross-validated — you can link a `type=blog` post to a Twitter account, or
|
cross-validated — you can link a `type=blog` post to a Twitter account, or
|
||||||
@@ -151,7 +163,7 @@ it's what later determines *how* the post gets published (see below).
|
|||||||
|
|
||||||
`PATCH /api/posts/{id}` — partial update. This is how you **report a
|
`PATCH /api/posts/{id}` — partial update. This is how you **report a
|
||||||
publish result** back for anything you didn't publish via the
|
publish result** back for anything you didn't publish via the
|
||||||
`posts:publish` command:
|
`posts:publish` command or the app's own Publish button:
|
||||||
```json
|
```json
|
||||||
{ "status": "published", "published_url": "https://example.com/2026/07/my-post" }
|
{ "status": "published", "published_url": "https://example.com/2026/07/my-post" }
|
||||||
```
|
```
|
||||||
@@ -164,9 +176,28 @@ or on failure:
|
|||||||
|
|
||||||
## How to actually publish a post
|
## How to actually publish a post
|
||||||
|
|
||||||
This app is a data store and scheduler — **it does not publish content by
|
Publishing happens through a shared `Publisher` abstraction
|
||||||
itself except via one specific command below.** Publishing mechanism
|
(`app/Support/Publishing/`) — one implementation per network family
|
||||||
depends on the post's target:
|
(`WordPressPublisher`, `RedditPublisher`, more to come), resolved by `Post.type`
|
||||||
|
via `PublisherManager`. There are three ways to trigger it, depending on
|
||||||
|
who/what is driving:
|
||||||
|
|
||||||
|
- **From the UI**: the Posts page has a "Publish" button (for any post whose
|
||||||
|
type currently has a publisher). Clicking it sets `status=publishing` and
|
||||||
|
dispatches `PublishPostJob` on the queue — a worker must be running
|
||||||
|
(`php artisan queue:work`) for anything to actually happen. The UI polls
|
||||||
|
and updates itself once the job finishes.
|
||||||
|
- **From the CLI**, for WordPress specifically: `php artisan posts:publish
|
||||||
|
{post_id}` (unchanged, see below) — synchronous, no queue needed.
|
||||||
|
- **Manually**, for anything without a wired-in publisher yet: do it
|
||||||
|
yourself and `PATCH` the result back (see below).
|
||||||
|
|
||||||
|
Note the asymmetry: WordPress is synchronous (a single HTTP call, fast
|
||||||
|
enough to run inline), Reddit is not (it's real browser automation via
|
||||||
|
Playwright, tens of seconds) — which is exactly why the UI path is
|
||||||
|
queue-backed rather than a direct synchronous call.
|
||||||
|
|
||||||
|
Publishing mechanism depends on the post's target:
|
||||||
|
|
||||||
### WordPress sites (`type=blog`, site has `cms_type=wordpress`)
|
### WordPress sites (`type=blog`, site has `cms_type=wordpress`)
|
||||||
|
|
||||||
@@ -244,6 +275,7 @@ setting `status` and, if applicable, `published_url`.**
|
|||||||
| Task | How |
|
| Task | How |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Find work to publish | `GET /api/posts?due=1` |
|
| Find work to publish | `GET /api/posts?due=1` |
|
||||||
|
| Publish from the UI | click "Publish" on the Posts page (queues `PublishPostJob`; needs a queue worker running) |
|
||||||
| Publish to a WordPress site | `php artisan posts:publish {post_id}` (handles status/published_url itself) |
|
| Publish to a WordPress site | `php artisan posts:publish {post_id}` (handles status/published_url itself) |
|
||||||
| Publish to Reddit | `sidecars/reddit-post/run.sh ...`, then `PATCH /api/posts/{id}` yourself |
|
| Publish to Reddit | `sidecars/reddit-post/run.sh ...`, then `PATCH /api/posts/{id}` yourself |
|
||||||
| Publish anywhere else | do it yourself, then `PATCH /api/posts/{id}` yourself |
|
| Publish anywhere else | do it yourself, then `PATCH /api/posts/{id}` yourself |
|
||||||
|
|||||||
@@ -15,17 +15,23 @@ Built with Laravel 13, Livewire, and Tailwind CSS.
|
|||||||
- **Social Accounts** — logins for social networks (Twitter, Instagram,
|
- **Social Accounts** — logins for social networks (Twitter, Instagram,
|
||||||
Facebook, Reddit, TikTok, LinkedIn, YouTube, etc.).
|
Facebook, Reddit, TikTok, LinkedIn, YouTube, etc.).
|
||||||
- **Posts** — the actual content, each tied to a Site and optionally a
|
- **Posts** — the actual content, each tied to a Site and optionally a
|
||||||
Social Account, moving through `draft -> scheduled -> published/failed`.
|
Social Account, moving through
|
||||||
|
`draft -> scheduled -> publishing -> published/failed`.
|
||||||
- A **JSON API** (`/api/sites`, `/api/accounts`, `/api/posts`) plus thin
|
- A **JSON API** (`/api/sites`, `/api/accounts`, `/api/posts`) plus thin
|
||||||
Python CLI wrappers in `python_scripts/`, so an agent can poll for due
|
Python CLI wrappers in `python_scripts/`, so an agent can poll for due
|
||||||
posts (`?due=1`) and drive the publish lifecycle without hand-rolling
|
posts (`?due=1`) and drive the publish lifecycle without hand-rolling
|
||||||
HTTP requests.
|
HTTP requests.
|
||||||
- Built-in publishing paths:
|
- A **Publish button** in the UI (Posts page) for any post whose network has
|
||||||
- **WordPress**: `php artisan posts:publish {post_id}` posts directly to
|
a publisher wired up — queues a background job so slow, flaky publishers
|
||||||
a site's WordPress REST API and updates the post's status.
|
(e.g. Reddit's browser automation) don't block the page.
|
||||||
- **Reddit**: a standalone Playwright sidecar at
|
- Built-in publishers (`app/Support/Publishing/`), one per network, resolved
|
||||||
`sidecars/reddit-post/` logs in and creates a post.
|
by `Post.type`:
|
||||||
- Anything else: publish however fits, then report back via the API.
|
- **WordPress**: posts directly to a site's WordPress REST API. Also
|
||||||
|
available synchronously from the CLI: `php artisan posts:publish {post_id}`.
|
||||||
|
- **Reddit**: drives a standalone Playwright sidecar at
|
||||||
|
`sidecars/reddit-post/` that logs in and creates a post.
|
||||||
|
- Anything else: no publisher yet — publish however fits, then report
|
||||||
|
back via the API.
|
||||||
|
|
||||||
See `AI_API.md` for the full API reference and publishing contract, and
|
See `AI_API.md` for the full API reference and publishing contract, and
|
||||||
`python_scripts/README.md` for the CLI wrapper usage.
|
`python_scripts/README.md` for the CLI wrapper usage.
|
||||||
@@ -80,6 +86,14 @@ This starts the PHP dev server, queue listener, log viewer (Pail), and
|
|||||||
Vite dev server together. The app is served at `http://localhost:8000` by
|
Vite dev server together. The app is served at `http://localhost:8000` by
|
||||||
default.
|
default.
|
||||||
|
|
||||||
|
Outside of `composer run dev` (e.g. a plain production deploy), the Publish
|
||||||
|
button needs its own queue worker running, or queued publishes will just sit
|
||||||
|
in the `jobs` table:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan queue:work
|
||||||
|
```
|
||||||
|
|
||||||
### Reddit sidecar (optional)
|
### Reddit sidecar (optional)
|
||||||
|
|
||||||
If you plan to publish to Reddit, set up the Playwright sidecar separately:
|
If you plan to publish to Reddit, set up the Playwright sidecar separately:
|
||||||
|
|||||||
@@ -3,9 +3,8 @@
|
|||||||
namespace App\Console\Commands;
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
use App\Models\Post;
|
use App\Models\Post;
|
||||||
|
use App\Support\Publishing\WordPressPublisher;
|
||||||
use Illuminate\Console\Command;
|
use Illuminate\Console\Command;
|
||||||
use Illuminate\Http\Client\ConnectionException;
|
|
||||||
use Illuminate\Support\Facades\Http;
|
|
||||||
|
|
||||||
class PublishPost extends Command
|
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';
|
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'));
|
$post = Post::with('site')->find($this->argument('post'));
|
||||||
|
|
||||||
@@ -25,61 +24,26 @@ class PublishPost extends Command
|
|||||||
return $this->failWith("Post {$post->id} has type '{$post->type}', expected 'blog' to publish to a CMS.");
|
return $this->failWith("Post {$post->id} has type '{$post->type}', expected 'blog' to publish to a CMS.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! $post->title) {
|
$result = $publisher->publish($post);
|
||||||
return $this->failWith("Post {$post->id} has no title, required to publish to WordPress.");
|
|
||||||
}
|
|
||||||
|
|
||||||
$site = $post->site;
|
if ($result->success) {
|
||||||
|
$post->update(['status' => 'published', 'published_url' => $result->url, 'publish_error' => null]);
|
||||||
if ($site->cms_type !== 'wordpress') {
|
$this->line(json_encode(['success' => true, 'url' => $result->url]));
|
||||||
return $this->failWith("Site '{$site->name}' is not configured as WordPress (cms_type={$site->cms_type}).");
|
|
||||||
}
|
|
||||||
|
|
||||||
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 self::SUCCESS;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($result->attempted) {
|
||||||
|
$post->update(['status' => 'failed', 'publish_error' => $result->error]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->failWith($result->error);
|
||||||
|
}
|
||||||
|
|
||||||
private function failWith(string $message): int
|
private function failWith(string $message): int
|
||||||
{
|
{
|
||||||
$this->line(json_encode(['success' => false, 'error' => $message]));
|
$this->line(json_encode(['success' => false, 'error' => $message]));
|
||||||
|
|
||||||
return self::FAILURE;
|
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)],
|
'type' => ['required', 'string', 'in:' . implode(',', Post::TYPES)],
|
||||||
'title' => ['nullable', 'string', 'max:255'],
|
'title' => ['nullable', 'string', 'max:255'],
|
||||||
'body' => ['required', 'string'],
|
'body' => ['required', 'string'],
|
||||||
|
'target' => ['nullable', 'string', 'max:255'],
|
||||||
'status' => ['sometimes', 'string', 'in:' . implode(',', Post::STATUSES)],
|
'status' => ['sometimes', 'string', 'in:' . implode(',', Post::STATUSES)],
|
||||||
'scheduled_at' => ['nullable', 'date'],
|
'scheduled_at' => ['nullable', 'date'],
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -20,8 +20,10 @@ class UpdatePostRequest extends FormRequest
|
|||||||
'type' => ['sometimes', 'required', 'string', 'in:' . implode(',', Post::TYPES)],
|
'type' => ['sometimes', 'required', 'string', 'in:' . implode(',', Post::TYPES)],
|
||||||
'title' => ['nullable', 'string', 'max:255'],
|
'title' => ['nullable', 'string', 'max:255'],
|
||||||
'body' => ['sometimes', 'required', 'string'],
|
'body' => ['sometimes', 'required', 'string'],
|
||||||
|
'target' => ['nullable', 'string', 'max:255'],
|
||||||
'status' => ['sometimes', 'string', 'in:' . implode(',', Post::STATUSES)],
|
'status' => ['sometimes', 'string', 'in:' . implode(',', Post::STATUSES)],
|
||||||
'scheduled_at' => ['nullable', 'date'],
|
'scheduled_at' => ['nullable', 'date'],
|
||||||
|
'published_url' => ['nullable', 'string', 'max:255'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,9 +16,11 @@ class PostResource extends JsonResource
|
|||||||
'type' => $this->type,
|
'type' => $this->type,
|
||||||
'title' => $this->title,
|
'title' => $this->title,
|
||||||
'body' => $this->body,
|
'body' => $this->body,
|
||||||
|
'target' => $this->target,
|
||||||
'status' => $this->status,
|
'status' => $this->status,
|
||||||
'scheduled_at' => $this->scheduled_at,
|
'scheduled_at' => $this->scheduled_at,
|
||||||
'published_url' => $this->published_url,
|
'published_url' => $this->published_url,
|
||||||
|
'publish_error' => $this->publish_error,
|
||||||
'created_at' => $this->created_at,
|
'created_at' => $this->created_at,
|
||||||
'updated_at' => $this->updated_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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
request()->session()->regenerate();
|
session()->regenerate();
|
||||||
|
|
||||||
$this->redirect(route('sites.index'), navigate: true);
|
$this->redirect(route('sites.index'), navigate: true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
namespace App\Livewire\Posts;
|
namespace App\Livewire\Posts;
|
||||||
|
|
||||||
|
use App\Jobs\PublishPostJob;
|
||||||
use App\Models\Post;
|
use App\Models\Post;
|
||||||
use App\Models\Site;
|
use App\Models\Site;
|
||||||
use App\Models\SocialAccount;
|
use App\Models\SocialAccount;
|
||||||
|
use App\Support\Publishing\PublisherManager;
|
||||||
use Livewire\Attributes\Layout;
|
use Livewire\Attributes\Layout;
|
||||||
use Livewire\Component;
|
use Livewire\Component;
|
||||||
|
|
||||||
@@ -25,21 +27,45 @@ class Index extends Component
|
|||||||
|
|
||||||
public string $body = '';
|
public string $body = '';
|
||||||
|
|
||||||
|
public string $target = '';
|
||||||
|
|
||||||
public string $status = 'draft';
|
public string $status = 'draft';
|
||||||
|
|
||||||
public string $scheduledAt = '';
|
public string $scheduledAt = '';
|
||||||
|
|
||||||
|
public ?string $publishNotice = null;
|
||||||
|
|
||||||
public function render()
|
public function render()
|
||||||
{
|
{
|
||||||
|
$posts = Post::with(['site', 'socialAccount'])->orderByDesc('created_at')->get();
|
||||||
|
|
||||||
return view('livewire.posts.index', [
|
return view('livewire.posts.index', [
|
||||||
'posts' => Post::with(['site', 'socialAccount'])->orderByDesc('created_at')->get(),
|
'posts' => $posts,
|
||||||
'sites' => Site::orderBy('name')->get(),
|
'sites' => Site::orderBy('name')->get(),
|
||||||
'accounts' => SocialAccount::orderBy('username')->get(),
|
'accounts' => SocialAccount::orderBy('username')->get(),
|
||||||
'types' => Post::TYPES,
|
'types' => Post::TYPES,
|
||||||
'statuses' => Post::STATUSES,
|
'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
|
public function create(): void
|
||||||
{
|
{
|
||||||
$this->resetForm();
|
$this->resetForm();
|
||||||
@@ -55,6 +81,7 @@ class Index extends Component
|
|||||||
$this->type = $post->type;
|
$this->type = $post->type;
|
||||||
$this->title = (string) $post->title;
|
$this->title = (string) $post->title;
|
||||||
$this->body = $post->body;
|
$this->body = $post->body;
|
||||||
|
$this->target = (string) $post->target;
|
||||||
$this->status = $post->status;
|
$this->status = $post->status;
|
||||||
$this->scheduledAt = $post->scheduled_at?->format('Y-m-d\TH:i') ?? '';
|
$this->scheduledAt = $post->scheduled_at?->format('Y-m-d\TH:i') ?? '';
|
||||||
$this->showForm = true;
|
$this->showForm = true;
|
||||||
@@ -68,6 +95,7 @@ class Index extends Component
|
|||||||
'type' => ['required', 'string', 'in:' . implode(',', Post::TYPES)],
|
'type' => ['required', 'string', 'in:' . implode(',', Post::TYPES)],
|
||||||
'title' => ['nullable', 'string', 'max:255'],
|
'title' => ['nullable', 'string', 'max:255'],
|
||||||
'body' => ['required', 'string'],
|
'body' => ['required', 'string'],
|
||||||
|
'target' => ['nullable', 'string', 'max:255'],
|
||||||
'status' => ['required', 'string', 'in:' . implode(',', Post::STATUSES)],
|
'status' => ['required', 'string', 'in:' . implode(',', Post::STATUSES)],
|
||||||
'scheduledAt' => ['nullable', 'date'],
|
'scheduledAt' => ['nullable', 'date'],
|
||||||
]);
|
]);
|
||||||
@@ -78,6 +106,7 @@ class Index extends Component
|
|||||||
'type' => $validated['type'],
|
'type' => $validated['type'],
|
||||||
'title' => $validated['title'] ?: null,
|
'title' => $validated['title'] ?: null,
|
||||||
'body' => $validated['body'],
|
'body' => $validated['body'],
|
||||||
|
'target' => $validated['target'] ?: null,
|
||||||
'status' => $validated['status'],
|
'status' => $validated['status'],
|
||||||
'scheduled_at' => $validated['scheduledAt'] ?: null,
|
'scheduled_at' => $validated['scheduledAt'] ?: null,
|
||||||
]);
|
]);
|
||||||
@@ -99,6 +128,7 @@ class Index extends Component
|
|||||||
$this->type = '';
|
$this->type = '';
|
||||||
$this->title = '';
|
$this->title = '';
|
||||||
$this->body = '';
|
$this->body = '';
|
||||||
|
$this->target = '';
|
||||||
$this->status = 'draft';
|
$this->status = 'draft';
|
||||||
$this->scheduledAt = '';
|
$this->scheduledAt = '';
|
||||||
$this->resetValidation();
|
$this->resetValidation();
|
||||||
|
|||||||
+3
-1
@@ -15,7 +15,7 @@ class Post extends Model
|
|||||||
'tiktok', 'linkedin', 'youtube', 'blog', 'other',
|
'tiktok', 'linkedin', 'youtube', 'blog', 'other',
|
||||||
];
|
];
|
||||||
|
|
||||||
public const STATUSES = ['draft', 'scheduled', 'published', 'failed'];
|
public const STATUSES = ['draft', 'scheduled', 'publishing', 'published', 'failed'];
|
||||||
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'site_id',
|
'site_id',
|
||||||
@@ -23,9 +23,11 @@ class Post extends Model
|
|||||||
'type',
|
'type',
|
||||||
'title',
|
'title',
|
||||||
'body',
|
'body',
|
||||||
|
'target',
|
||||||
'status',
|
'status',
|
||||||
'scheduled_at',
|
'scheduled_at',
|
||||||
'published_url',
|
'published_url',
|
||||||
|
'publish_error',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $casts = [
|
protected $casts = [
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
namespace App\Providers;
|
namespace App\Providers;
|
||||||
|
|
||||||
|
use App\Support\Publishing\PublisherManager;
|
||||||
|
use App\Support\Publishing\RedditPublisher;
|
||||||
|
use App\Support\Publishing\WordPressPublisher;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
|
||||||
class AppServiceProvider extends ServiceProvider
|
class AppServiceProvider extends ServiceProvider
|
||||||
@@ -11,7 +14,10 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
*/
|
*/
|
||||||
public function register(): void
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('posts', function (Blueprint $table) {
|
||||||
|
$table->string('target')->nullable()->after('body');
|
||||||
|
$table->text('publish_error')->nullable()->after('published_url');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::statement("ALTER TABLE posts MODIFY status ENUM('draft', 'scheduled', 'publishing', 'published', 'failed') NOT NULL DEFAULT 'draft'");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
DB::statement("UPDATE posts SET status = 'failed' WHERE status = 'publishing'");
|
||||||
|
DB::statement("ALTER TABLE posts MODIFY status ENUM('draft', 'scheduled', 'published', 'failed') NOT NULL DEFAULT 'draft'");
|
||||||
|
|
||||||
|
Schema::table('posts', function (Blueprint $table) {
|
||||||
|
$table->dropColumn(['target', 'publish_error']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -5,10 +5,10 @@ Usage:
|
|||||||
python3 posts.py list [--status STATUS] [--site-id ID] [--social-account-id ID] [--due]
|
python3 posts.py list [--status STATUS] [--site-id ID] [--social-account-id ID] [--due]
|
||||||
python3 posts.py get POST_ID
|
python3 posts.py get POST_ID
|
||||||
python3 posts.py create --site-id ID --type TYPE --body BODY
|
python3 posts.py create --site-id ID --type TYPE --body BODY
|
||||||
[--social-account-id ID] [--title TITLE]
|
[--social-account-id ID] [--title TITLE] [--target TARGET]
|
||||||
[--status STATUS] [--scheduled-at DATETIME]
|
[--status STATUS] [--scheduled-at DATETIME]
|
||||||
python3 posts.py update POST_ID [--site-id ID] [--social-account-id ID]
|
python3 posts.py update POST_ID [--site-id ID] [--social-account-id ID]
|
||||||
[--type TYPE] [--title TITLE] [--body BODY]
|
[--type TYPE] [--title TITLE] [--body BODY] [--target TARGET]
|
||||||
[--status STATUS] [--scheduled-at DATETIME]
|
[--status STATUS] [--scheduled-at DATETIME]
|
||||||
[--published-url URL]
|
[--published-url URL]
|
||||||
python3 posts.py delete POST_ID
|
python3 posts.py delete POST_ID
|
||||||
@@ -22,7 +22,7 @@ import argparse
|
|||||||
import _client
|
import _client
|
||||||
|
|
||||||
TYPES = ["twitter", "instagram", "facebook", "reddit", "tiktok", "linkedin", "youtube", "blog", "other"]
|
TYPES = ["twitter", "instagram", "facebook", "reddit", "tiktok", "linkedin", "youtube", "blog", "other"]
|
||||||
STATUSES = ["draft", "scheduled", "published", "failed"]
|
STATUSES = ["draft", "scheduled", "publishing", "published", "failed"]
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
@@ -46,6 +46,7 @@ def main() -> None:
|
|||||||
create_parser.add_argument("--body", required=True)
|
create_parser.add_argument("--body", required=True)
|
||||||
create_parser.add_argument("--social-account-id", type=int)
|
create_parser.add_argument("--social-account-id", type=int)
|
||||||
create_parser.add_argument("--title")
|
create_parser.add_argument("--title")
|
||||||
|
create_parser.add_argument("--target", help="Network-specific destination, e.g. a subreddit for Reddit posts")
|
||||||
create_parser.add_argument("--status", choices=STATUSES)
|
create_parser.add_argument("--status", choices=STATUSES)
|
||||||
create_parser.add_argument("--scheduled-at", help="ISO 8601 datetime, e.g. 2026-07-20T09:00:00")
|
create_parser.add_argument("--scheduled-at", help="ISO 8601 datetime, e.g. 2026-07-20T09:00:00")
|
||||||
|
|
||||||
@@ -56,6 +57,7 @@ def main() -> None:
|
|||||||
update_parser.add_argument("--type", choices=TYPES)
|
update_parser.add_argument("--type", choices=TYPES)
|
||||||
update_parser.add_argument("--title")
|
update_parser.add_argument("--title")
|
||||||
update_parser.add_argument("--body")
|
update_parser.add_argument("--body")
|
||||||
|
update_parser.add_argument("--target", help="Network-specific destination, e.g. a subreddit for Reddit posts")
|
||||||
update_parser.add_argument("--status", choices=STATUSES)
|
update_parser.add_argument("--status", choices=STATUSES)
|
||||||
update_parser.add_argument("--scheduled-at", help="ISO 8601 datetime")
|
update_parser.add_argument("--scheduled-at", help="ISO 8601 datetime")
|
||||||
update_parser.add_argument("--published-url")
|
update_parser.add_argument("--published-url")
|
||||||
@@ -85,6 +87,7 @@ def main() -> None:
|
|||||||
"type": args.type,
|
"type": args.type,
|
||||||
"title": args.title,
|
"title": args.title,
|
||||||
"body": args.body,
|
"body": args.body,
|
||||||
|
"target": args.target,
|
||||||
"status": args.status,
|
"status": args.status,
|
||||||
"scheduled_at": args.scheduled_at,
|
"scheduled_at": args.scheduled_at,
|
||||||
}
|
}
|
||||||
@@ -98,6 +101,7 @@ def main() -> None:
|
|||||||
"type": args.type,
|
"type": args.type,
|
||||||
"title": args.title,
|
"title": args.title,
|
||||||
"body": args.body,
|
"body": args.body,
|
||||||
|
"target": args.target,
|
||||||
"status": args.status,
|
"status": args.status,
|
||||||
"scheduled_at": args.scheduled_at,
|
"scheduled_at": args.scheduled_at,
|
||||||
"published_url": args.published_url,
|
"published_url": args.published_url,
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
<div>
|
<div @if ($hasPublishing) wire:poll.3s @endif>
|
||||||
<div class="flex justify-between items-center mb-4">
|
<div class="flex justify-between items-center mb-4">
|
||||||
<h1 class="text-xl font-semibold">Posts</h1>
|
<h1 class="text-xl font-semibold">Posts</h1>
|
||||||
<button wire:click="create" class="bg-blue-600 text-white px-4 py-2 rounded">Add Post</button>
|
<button wire:click="create" class="bg-blue-600 text-white px-4 py-2 rounded">Add Post</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@if ($publishNotice)
|
||||||
|
<div class="mb-4 p-3 bg-amber-50 border border-amber-200 text-amber-800 rounded text-sm">{{ $publishNotice }}</div>
|
||||||
|
@endif
|
||||||
|
|
||||||
<table class="w-full bg-white border border-gray-200 rounded">
|
<table class="w-full bg-white border border-gray-200 rounded">
|
||||||
<thead>
|
<thead>
|
||||||
<tr class="text-left border-b border-gray-200">
|
<tr class="text-left border-b border-gray-200">
|
||||||
@@ -22,10 +26,22 @@
|
|||||||
<td class="p-3">{{ $post->site->name }}</td>
|
<td class="p-3">{{ $post->site->name }}</td>
|
||||||
<td class="p-3">{{ ucfirst($post->type) }}</td>
|
<td class="p-3">{{ ucfirst($post->type) }}</td>
|
||||||
<td class="p-3">{{ $post->title ?: \Illuminate\Support\Str::limit($post->body, 40) }}</td>
|
<td class="p-3">{{ $post->title ?: \Illuminate\Support\Str::limit($post->body, 40) }}</td>
|
||||||
<td class="p-3">{{ ucfirst($post->status) }}</td>
|
<td class="p-3">
|
||||||
|
@if ($post->status === 'published' && $post->published_url)
|
||||||
|
<a href="{{ $post->published_url }}" target="_blank" class="text-green-700 hover:underline">Published</a>
|
||||||
|
@else
|
||||||
|
{{ ucfirst($post->status) }}
|
||||||
|
@endif
|
||||||
|
@if ($post->status === 'failed' && $post->publish_error)
|
||||||
|
<div class="text-xs text-red-600 mt-0.5">{{ $post->publish_error }}</div>
|
||||||
|
@endif
|
||||||
|
</td>
|
||||||
<td class="p-3">{{ $post->scheduled_at?->format('Y-m-d H:i') ?? '—' }}</td>
|
<td class="p-3">{{ $post->scheduled_at?->format('Y-m-d H:i') ?? '—' }}</td>
|
||||||
<td class="p-3">{{ $post->socialAccount?->username ?? '—' }}</td>
|
<td class="p-3">{{ $post->socialAccount?->username ?? '—' }}</td>
|
||||||
<td class="p-3 text-right space-x-2">
|
<td class="p-3 text-right space-x-2">
|
||||||
|
@if (in_array($post->type, ['blog', 'reddit']) && in_array($post->status, ['draft', 'scheduled', 'failed']))
|
||||||
|
<button wire:click="publish({{ $post->id }})" class="text-green-700">Publish</button>
|
||||||
|
@endif
|
||||||
<button wire:click="edit({{ $post->id }})" class="text-blue-600">Edit</button>
|
<button wire:click="edit({{ $post->id }})" class="text-blue-600">Edit</button>
|
||||||
<button wire:click="delete({{ $post->id }})" wire:confirm="Delete this post?" class="text-red-600">Delete</button>
|
<button wire:click="delete({{ $post->id }})" wire:confirm="Delete this post?" class="text-red-600">Delete</button>
|
||||||
</td>
|
</td>
|
||||||
@@ -84,6 +100,12 @@
|
|||||||
@error('body') <span class="text-red-600 text-sm">{{ $message }}</span> @enderror
|
@error('body') <span class="text-red-600 text-sm">{{ $message }}</span> @enderror
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium">Target (optional — e.g. subreddit for Reddit posts)</label>
|
||||||
|
<input type="text" wire:model="target" class="w-full border rounded p-2">
|
||||||
|
@error('target') <span class="text-red-600 text-sm">{{ $message }}</span> @enderror
|
||||||
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label class="block text-sm font-medium">Status</label>
|
<label class="block text-sm font-medium">Status</label>
|
||||||
<select wire:model="status" class="w-full border rounded p-2">
|
<select wire:model="status" class="w-full border rounded p-2">
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Livewire\Auth\Login;
|
||||||
|
use App\Models\User;
|
||||||
|
use Livewire\Livewire;
|
||||||
|
|
||||||
|
test('guests are redirected to login when visiting a protected page', function () {
|
||||||
|
$this->get(route('sites.index'))
|
||||||
|
->assertRedirect(route('login'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the api stays open to guests', function () {
|
||||||
|
$this->getJson('/api/sites')->assertOk();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('users can log in with correct credentials', function () {
|
||||||
|
$user = User::factory()->create(['password' => bcrypt('correct-password')]);
|
||||||
|
|
||||||
|
Livewire::test(Login::class)
|
||||||
|
->set('email', $user->email)
|
||||||
|
->set('password', 'correct-password')
|
||||||
|
->call('login')
|
||||||
|
->assertRedirect(route('sites.index'));
|
||||||
|
|
||||||
|
$this->assertAuthenticatedAs($user);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('users cannot log in with incorrect credentials', function () {
|
||||||
|
$user = User::factory()->create(['password' => bcrypt('correct-password')]);
|
||||||
|
|
||||||
|
Livewire::test(Login::class)
|
||||||
|
->set('email', $user->email)
|
||||||
|
->set('password', 'wrong-password')
|
||||||
|
->call('login')
|
||||||
|
->assertHasErrors('email');
|
||||||
|
|
||||||
|
$this->assertGuest();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('authenticated users are redirected away from the login page', function () {
|
||||||
|
$this->actingAs(User::factory()->create())
|
||||||
|
->get(route('login'))
|
||||||
|
->assertRedirect();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('users can log out', function () {
|
||||||
|
$this->actingAs(User::factory()->create())
|
||||||
|
->post(route('logout'))
|
||||||
|
->assertRedirect('/login');
|
||||||
|
|
||||||
|
$this->assertGuest();
|
||||||
|
});
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Jobs\PublishPostJob;
|
||||||
|
use App\Models\Post;
|
||||||
|
use App\Models\Site;
|
||||||
|
use App\Models\SocialAccount;
|
||||||
|
use App\Support\Publishing\PublisherManager;
|
||||||
|
use Illuminate\Support\Facades\Http;
|
||||||
|
use Illuminate\Support\Facades\Process;
|
||||||
|
|
||||||
|
test('it publishes and updates the post on success', function () {
|
||||||
|
Http::fake([
|
||||||
|
'*/wp-json/wp/v2/posts' => Http::response(['link' => 'https://wp.example.com/post'], 201),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$site = Site::factory()->wordpress()->create();
|
||||||
|
$post = Post::factory()->create(['site_id' => $site->id, 'type' => 'blog', 'title' => 'Hi', 'status' => 'publishing']);
|
||||||
|
|
||||||
|
(new PublishPostJob($post->id))->handle(app(PublisherManager::class));
|
||||||
|
|
||||||
|
expect($post->fresh())
|
||||||
|
->status->toBe('published')
|
||||||
|
->published_url->toBe('https://wp.example.com/post')
|
||||||
|
->publish_error->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it marks the post failed when the publish attempt fails', function () {
|
||||||
|
Http::fake([
|
||||||
|
'*/wp-json/wp/v2/posts' => Http::response(['message' => 'nope'], 401),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$site = Site::factory()->wordpress()->create();
|
||||||
|
$post = Post::factory()->create(['site_id' => $site->id, 'type' => 'blog', 'title' => 'Hi', 'status' => 'publishing']);
|
||||||
|
|
||||||
|
(new PublishPostJob($post->id))->handle(app(PublisherManager::class));
|
||||||
|
|
||||||
|
expect($post->fresh())
|
||||||
|
->status->toBe('failed')
|
||||||
|
->publish_error->toBe('nope');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it reverts a rejected post to draft instead of failed', function () {
|
||||||
|
$site = Site::factory()->wordpress()->create();
|
||||||
|
$post = Post::factory()->create(['site_id' => $site->id, 'type' => 'blog', 'title' => null, 'status' => 'publishing']);
|
||||||
|
|
||||||
|
(new PublishPostJob($post->id))->handle(app(PublisherManager::class));
|
||||||
|
|
||||||
|
expect($post->fresh())
|
||||||
|
->status->toBe('draft')
|
||||||
|
->publish_error->toContain('no title');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it reverts to draft when no publisher supports the post type', function () {
|
||||||
|
$post = Post::factory()->create(['type' => 'twitter', 'status' => 'publishing']);
|
||||||
|
|
||||||
|
(new PublishPostJob($post->id))->handle(app(PublisherManager::class));
|
||||||
|
|
||||||
|
expect($post->fresh())
|
||||||
|
->status->toBe('draft')
|
||||||
|
->publish_error->toContain('No publisher available');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it publishes a reddit post via the sidecar', function () {
|
||||||
|
Process::fake([
|
||||||
|
'*' => Process::result(output: json_encode(['success' => true, 'url' => 'https://reddit.com/r/test/comments/abc'])),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$account = SocialAccount::factory()->create(['network' => 'reddit']);
|
||||||
|
$post = Post::factory()->create([
|
||||||
|
'type' => 'reddit',
|
||||||
|
'title' => 'Hi',
|
||||||
|
'target' => 'test',
|
||||||
|
'social_account_id' => $account->id,
|
||||||
|
'status' => 'publishing',
|
||||||
|
]);
|
||||||
|
|
||||||
|
(new PublishPostJob($post->id))->handle(app(PublisherManager::class));
|
||||||
|
|
||||||
|
expect($post->fresh())
|
||||||
|
->status->toBe('published')
|
||||||
|
->published_url->toBe('https://reddit.com/r/test/comments/abc');
|
||||||
|
});
|
||||||
@@ -1,16 +1,20 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use App\Jobs\PublishPostJob;
|
||||||
use App\Livewire\Posts\Index;
|
use App\Livewire\Posts\Index;
|
||||||
use App\Models\Post;
|
use App\Models\Post;
|
||||||
use App\Models\Site;
|
use App\Models\Site;
|
||||||
use App\Models\SocialAccount;
|
use App\Models\SocialAccount;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Support\Facades\Queue;
|
||||||
use Livewire\Livewire;
|
use Livewire\Livewire;
|
||||||
|
|
||||||
test('posts index page lists existing posts', function () {
|
test('posts index page lists existing posts', function () {
|
||||||
$site = Site::factory()->create(['name' => 'My Blog']);
|
$site = Site::factory()->create(['name' => 'My Blog']);
|
||||||
Post::factory()->create(['site_id' => $site->id, 'title' => 'Hello World Post']);
|
Post::factory()->create(['site_id' => $site->id, 'title' => 'Hello World Post']);
|
||||||
|
|
||||||
$this->get(route('posts.index'))
|
$this->actingAs(User::factory()->create())
|
||||||
|
->get(route('posts.index'))
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertSee('Hello World Post')
|
->assertSee('Hello World Post')
|
||||||
->assertSee('My Blog');
|
->assertSee('My Blog');
|
||||||
@@ -79,3 +83,28 @@ test('a post can be deleted', function () {
|
|||||||
|
|
||||||
expect(Post::find($post->id))->toBeNull();
|
expect(Post::find($post->id))->toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('publishing a post queues the job and marks it publishing', function () {
|
||||||
|
Queue::fake();
|
||||||
|
|
||||||
|
$site = Site::factory()->wordpress()->create();
|
||||||
|
$post = Post::factory()->create(['site_id' => $site->id, 'type' => 'blog', 'title' => 'Hi', 'status' => 'draft']);
|
||||||
|
|
||||||
|
Livewire::test(Index::class)->call('publish', $post->id);
|
||||||
|
|
||||||
|
expect($post->fresh()->status)->toBe('publishing');
|
||||||
|
Queue::assertPushed(PublishPostJob::class, fn ($job) => $job->postId === $post->id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('publishing a post with no available publisher shows a notice and does not queue anything', function () {
|
||||||
|
Queue::fake();
|
||||||
|
|
||||||
|
$post = Post::factory()->create(['type' => 'twitter', 'status' => 'draft']);
|
||||||
|
|
||||||
|
Livewire::test(Index::class)
|
||||||
|
->call('publish', $post->id)
|
||||||
|
->assertSee("No publisher available yet for post type 'twitter'");
|
||||||
|
|
||||||
|
expect($post->fresh()->status)->toBe('draft');
|
||||||
|
Queue::assertNotPushed(PublishPostJob::class);
|
||||||
|
});
|
||||||
|
|||||||
@@ -2,12 +2,14 @@
|
|||||||
|
|
||||||
use App\Livewire\Sites\Index;
|
use App\Livewire\Sites\Index;
|
||||||
use App\Models\Site;
|
use App\Models\Site;
|
||||||
|
use App\Models\User;
|
||||||
use Livewire\Livewire;
|
use Livewire\Livewire;
|
||||||
|
|
||||||
test('sites index page lists existing sites', function () {
|
test('sites index page lists existing sites', function () {
|
||||||
$site = Site::factory()->create(['name' => 'Example Site']);
|
$site = Site::factory()->create(['name' => 'Example Site']);
|
||||||
|
|
||||||
$this->get(route('sites.index'))
|
$this->actingAs(User::factory()->create())
|
||||||
|
->get(route('sites.index'))
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertSee('Example Site');
|
->assertSee('Example Site');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,12 +2,14 @@
|
|||||||
|
|
||||||
use App\Livewire\SocialAccounts\Index;
|
use App\Livewire\SocialAccounts\Index;
|
||||||
use App\Models\SocialAccount;
|
use App\Models\SocialAccount;
|
||||||
|
use App\Models\User;
|
||||||
use Livewire\Livewire;
|
use Livewire\Livewire;
|
||||||
|
|
||||||
test('social accounts index page lists existing accounts', function () {
|
test('social accounts index page lists existing accounts', function () {
|
||||||
SocialAccount::factory()->create(['username' => 'example_user']);
|
SocialAccount::factory()->create(['username' => 'example_user']);
|
||||||
|
|
||||||
$this->get(route('social-accounts.index'))
|
$this->actingAs(User::factory()->create())
|
||||||
|
->get(route('social-accounts.index'))
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertSee('example_user');
|
->assertSee('example_user');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\Post;
|
||||||
|
use App\Support\Publishing\PublisherManager;
|
||||||
|
use App\Support\Publishing\RedditPublisher;
|
||||||
|
use App\Support\Publishing\WordPressPublisher;
|
||||||
|
|
||||||
|
test('it resolves the first publisher that supports the post', function () {
|
||||||
|
$manager = new PublisherManager([
|
||||||
|
new WordPressPublisher,
|
||||||
|
new RedditPublisher,
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect($manager->resolve(Post::factory()->make(['type' => 'blog'])))->toBeInstanceOf(WordPressPublisher::class);
|
||||||
|
expect($manager->resolve(Post::factory()->make(['type' => 'reddit'])))->toBeInstanceOf(RedditPublisher::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it returns null when no publisher supports the post', function () {
|
||||||
|
$manager = new PublisherManager([
|
||||||
|
new WordPressPublisher,
|
||||||
|
new RedditPublisher,
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect($manager->resolve(Post::factory()->make(['type' => 'twitter'])))->toBeNull();
|
||||||
|
});
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\Post;
|
||||||
|
use App\Models\SocialAccount;
|
||||||
|
use App\Support\Publishing\RedditPublisher;
|
||||||
|
use Illuminate\Support\Facades\Process;
|
||||||
|
|
||||||
|
test('it supports reddit posts only', function () {
|
||||||
|
$publisher = new RedditPublisher;
|
||||||
|
|
||||||
|
expect($publisher->supports(Post::factory()->make(['type' => 'reddit'])))->toBeTrue();
|
||||||
|
expect($publisher->supports(Post::factory()->make(['type' => 'blog'])))->toBeFalse();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it rejects a post with no title', function () {
|
||||||
|
$post = Post::factory()->for(SocialAccount::factory()->state(['network' => 'reddit']), 'socialAccount')
|
||||||
|
->create(['type' => 'reddit', 'title' => null, 'target' => 'test']);
|
||||||
|
|
||||||
|
$result = (new RedditPublisher)->publish($post);
|
||||||
|
|
||||||
|
expect($result->success)->toBeFalse();
|
||||||
|
expect($result->attempted)->toBeFalse();
|
||||||
|
expect($result->error)->toContain('no title');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it rejects a post with no target subreddit', function () {
|
||||||
|
$post = Post::factory()->for(SocialAccount::factory()->state(['network' => 'reddit']), 'socialAccount')
|
||||||
|
->create(['type' => 'reddit', 'title' => 'Hi', 'target' => null]);
|
||||||
|
|
||||||
|
$result = (new RedditPublisher)->publish($post);
|
||||||
|
|
||||||
|
expect($result->success)->toBeFalse();
|
||||||
|
expect($result->attempted)->toBeFalse();
|
||||||
|
expect($result->error)->toContain('no target subreddit');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it rejects a post with no linked reddit account', function () {
|
||||||
|
$post = Post::factory()->create(['type' => 'reddit', 'title' => 'Hi', 'target' => 'test', 'social_account_id' => null]);
|
||||||
|
|
||||||
|
$result = (new RedditPublisher)->publish($post);
|
||||||
|
|
||||||
|
expect($result->success)->toBeFalse();
|
||||||
|
expect($result->attempted)->toBeFalse();
|
||||||
|
expect($result->error)->toContain('no linked Reddit social account');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it publishes successfully via the sidecar', function () {
|
||||||
|
Process::fake([
|
||||||
|
'*' => Process::result(output: json_encode(['success' => true, 'url' => 'https://reddit.com/r/test/comments/abc123'])),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$account = SocialAccount::factory()->create(['network' => 'reddit', 'username' => 'redditor']);
|
||||||
|
$post = Post::factory()->create([
|
||||||
|
'type' => 'reddit',
|
||||||
|
'title' => 'Hi',
|
||||||
|
'target' => 'test',
|
||||||
|
'social_account_id' => $account->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = (new RedditPublisher)->publish($post);
|
||||||
|
|
||||||
|
expect($result->success)->toBeTrue();
|
||||||
|
expect($result->url)->toBe('https://reddit.com/r/test/comments/abc123');
|
||||||
|
|
||||||
|
Process::assertRan(function ($process) use ($account) {
|
||||||
|
return str_contains($process->command[0], 'sidecars/reddit-post/run.sh')
|
||||||
|
&& in_array("--username={$account->username}", $process->command)
|
||||||
|
&& in_array('--subreddit=test', $process->command);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it treats a sidecar-reported failure as an attempted, failed publish', function () {
|
||||||
|
Process::fake([
|
||||||
|
'*' => Process::result(output: json_encode(['success' => false, 'error' => 'invalid credentials'])),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$account = SocialAccount::factory()->create(['network' => 'reddit']);
|
||||||
|
$post = Post::factory()->create([
|
||||||
|
'type' => 'reddit',
|
||||||
|
'title' => 'Hi',
|
||||||
|
'target' => 'test',
|
||||||
|
'social_account_id' => $account->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = (new RedditPublisher)->publish($post);
|
||||||
|
|
||||||
|
expect($result->success)->toBeFalse();
|
||||||
|
expect($result->attempted)->toBeTrue();
|
||||||
|
expect($result->error)->toBe('invalid credentials');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('it fails gracefully when the sidecar output is unparseable', function () {
|
||||||
|
Process::fake([
|
||||||
|
'*' => Process::result(output: 'not json'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$account = SocialAccount::factory()->create(['network' => 'reddit']);
|
||||||
|
$post = Post::factory()->create([
|
||||||
|
'type' => 'reddit',
|
||||||
|
'title' => 'Hi',
|
||||||
|
'target' => 'test',
|
||||||
|
'social_account_id' => $account->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = (new RedditPublisher)->publish($post);
|
||||||
|
|
||||||
|
expect($result->success)->toBeFalse();
|
||||||
|
expect($result->attempted)->toBeTrue();
|
||||||
|
expect($result->error)->toContain('unparseable');
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user