trypost/app/Http/Requests/Api/Post/StorePostRequest.php

104 lines
2.9 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\Post;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Models\SocialAccount;
use App\Rules\ContentFitsPlatformLimits;
feat: complete create + publish post flow via MCP and REST API Lets ChatGPT (MCP) and external clients (REST API) drive the full lifecycle of a post — create with platform selection, attach media from URLs, schedule or publish immediately, and fetch engagement metrics — without touching the web UI. MCP tools added: UpdatePostTool, PublishPostTool, AttachMediaFromUrlTool, ListContentTypesTool, GetPostMetricsTool, PreviewPostTool. CreatePostTool now accepts platforms[] + scheduled_at + label_ids; ListPostsTool gains status/search/limit filters. REST endpoints added: POST /api/posts/{post}/media, GET /api/posts/{post}/metrics, GET /api/posts/{post}/preview, GET /api/content-types. Also fixes a silent CreatePost::execute bug — the action validated platforms[] but ignored it, so REST callers never saw their selection persisted. Adds cross validation rules (ContentTypeMatchesPlatform / ContentTypeMatchesPostPlatform) so a LinkedIn account can't be saddled with x_post, and rejects inactive social accounts during validation instead of failing silently downstream. Shared services (PostMetricsFetcher, PostPreviewer, MediaAttacher) back both MCP tools and REST controllers so behaviour stays aligned. New Resources (PlatformContentTypesResource, PostMetricsResource, PostPreviewResource, PostMediaAttachResource) keep controllers free of inline model mapping. Suite: 1.332 passing, 0 failing — covers web (PostControllerTest), REST (PostApiTest, PlatformApiTest, PostMediaApiTest), MCP (66 tool tests), and the publish job (PublishToSocialPlatformTest). Removes /docs from git tracking and TIKTOK_REVIEW_VIDEO_SCRIPT.md.
2026-05-04 11:12:28 +00:00
use App\Rules\ContentTypeMatchesPlatform;
use App\Support\PostMediaRules;
use App\Support\PostPlatformMetaRules;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Collection;
use Illuminate\Validation\Rule;
class StorePostRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
fix: address PR review findings — publish, REST store, SSRF, race Code-review surfaced two correctness bugs and a security gap that needed to land before merging. - UpdatePost::execute disabled every platform when called without a `platforms` key. PublishPostTool relied on that path, so every publish-via-MCP queued a job whose handler then found nothing enabled to publish to. Wrap the platform toggle in `Arr::has($data, 'platforms')` (matches the existing label_ids guard a few lines up). Add a regression assertion to `PostPublishToolTest::publish post immediate dispatches PublishPost job` that the previously-enabled platform stays enabled. - StorePostRequest declared rules for only `platforms`, `scheduled_at`, and `status`. `validated()` then stripped `content`, `media`, and `label_ids`, so REST `POST /api/posts` silently created empty drafts. Added rules for content / media / label_ids (with workspace-scoped `Rule::exists` for labels) and dropped the unused `status` field — REST callers transition state via `PUT /posts/{id}`. Removed the dead `platforms.*.content` rule. Added a feature test that asserts content + media + labels roundtrip on create, plus a regression that an `is_active=false` social_account is rejected at validation. - CreatePost::execute now syncs label_ids itself so REST and MCP share the behavior. Removed the duplicate sync from CreatePostTool. - MCP UpdatePostTool didn't scope `platforms.*.id` to the post being updated, drifting from the REST UpdatePostRequest which adds `Rule::exists('post_platforms','id')->where('post_id', ...)`. Now it loads the post first (failing fast with `Post not found.` if the workspace check rejects), then uses the same Rule::exists. - MediaAttacher fetched any URL the caller passed, including loopback / link-local / private targets — classic SSRF pivot. Now `isPublicHttpUrl` rejects non-http(s) schemes, restricted IP ranges, and DNS hostnames whose A/AAAA records resolve into those ranges (covers DNS rebinding). Bypassed under `app()->runningUnitTests()` so `Http::fake()` keeps working. Streaming the response body lets us abort early once we exceed MAX_BYTES instead of buffering the full payload first; redirects are disabled so a 200→302 trick can't bypass the host check. - The `media[]` JSON column had a lost-update race in `attachFromUrls`: read `$post->media`, mutate in PHP, write back. Two concurrent calls clobbered each other. Now wrapped in a transaction with `lockForUpdate()`. - ESLint: `resources/js/actions/**` and `resources/js/routes/**` are auto-generated by Wayfinder on every build. Their import order matches PHP scan order, not alphabetical, so import/order fought eslint-fix forever. Added them to ignores.
2026-05-04 15:16:39 +00:00
$workspaceId = $this->user()->currentWorkspace->id;
return [
'content' => [
'nullable',
'string',
'max:10000',
Rule::when(
$this->filled('scheduled_at'),
[new ContentFitsPlatformLimits($this->resolveSelectedPlatforms($workspaceId))]
),
],
...PostMediaRules::rules(hosted: false),
'platforms' => ['required', 'array', 'min:1'],
feat: complete create + publish post flow via MCP and REST API Lets ChatGPT (MCP) and external clients (REST API) drive the full lifecycle of a post — create with platform selection, attach media from URLs, schedule or publish immediately, and fetch engagement metrics — without touching the web UI. MCP tools added: UpdatePostTool, PublishPostTool, AttachMediaFromUrlTool, ListContentTypesTool, GetPostMetricsTool, PreviewPostTool. CreatePostTool now accepts platforms[] + scheduled_at + label_ids; ListPostsTool gains status/search/limit filters. REST endpoints added: POST /api/posts/{post}/media, GET /api/posts/{post}/metrics, GET /api/posts/{post}/preview, GET /api/content-types. Also fixes a silent CreatePost::execute bug — the action validated platforms[] but ignored it, so REST callers never saw their selection persisted. Adds cross validation rules (ContentTypeMatchesPlatform / ContentTypeMatchesPostPlatform) so a LinkedIn account can't be saddled with x_post, and rejects inactive social accounts during validation instead of failing silently downstream. Shared services (PostMetricsFetcher, PostPreviewer, MediaAttacher) back both MCP tools and REST controllers so behaviour stays aligned. New Resources (PlatformContentTypesResource, PostMetricsResource, PostPreviewResource, PostMediaAttachResource) keep controllers free of inline model mapping. Suite: 1.332 passing, 0 failing — covers web (PostControllerTest), REST (PostApiTest, PlatformApiTest, PostMediaApiTest), MCP (66 tool tests), and the publish job (PublishToSocialPlatformTest). Removes /docs from git tracking and TIKTOK_REVIEW_VIDEO_SCRIPT.md.
2026-05-04 11:12:28 +00:00
'platforms.*.social_account_id' => [
'required',
'uuid',
Rule::exists('social_accounts', 'id')
fix: address PR review findings — publish, REST store, SSRF, race Code-review surfaced two correctness bugs and a security gap that needed to land before merging. - UpdatePost::execute disabled every platform when called without a `platforms` key. PublishPostTool relied on that path, so every publish-via-MCP queued a job whose handler then found nothing enabled to publish to. Wrap the platform toggle in `Arr::has($data, 'platforms')` (matches the existing label_ids guard a few lines up). Add a regression assertion to `PostPublishToolTest::publish post immediate dispatches PublishPost job` that the previously-enabled platform stays enabled. - StorePostRequest declared rules for only `platforms`, `scheduled_at`, and `status`. `validated()` then stripped `content`, `media`, and `label_ids`, so REST `POST /api/posts` silently created empty drafts. Added rules for content / media / label_ids (with workspace-scoped `Rule::exists` for labels) and dropped the unused `status` field — REST callers transition state via `PUT /posts/{id}`. Removed the dead `platforms.*.content` rule. Added a feature test that asserts content + media + labels roundtrip on create, plus a regression that an `is_active=false` social_account is rejected at validation. - CreatePost::execute now syncs label_ids itself so REST and MCP share the behavior. Removed the duplicate sync from CreatePostTool. - MCP UpdatePostTool didn't scope `platforms.*.id` to the post being updated, drifting from the REST UpdatePostRequest which adds `Rule::exists('post_platforms','id')->where('post_id', ...)`. Now it loads the post first (failing fast with `Post not found.` if the workspace check rejects), then uses the same Rule::exists. - MediaAttacher fetched any URL the caller passed, including loopback / link-local / private targets — classic SSRF pivot. Now `isPublicHttpUrl` rejects non-http(s) schemes, restricted IP ranges, and DNS hostnames whose A/AAAA records resolve into those ranges (covers DNS rebinding). Bypassed under `app()->runningUnitTests()` so `Http::fake()` keeps working. Streaming the response body lets us abort early once we exceed MAX_BYTES instead of buffering the full payload first; redirects are disabled so a 200→302 trick can't bypass the host check. - The `media[]` JSON column had a lost-update race in `attachFromUrls`: read `$post->media`, mutate in PHP, write back. Two concurrent calls clobbered each other. Now wrapped in a transaction with `lockForUpdate()`. - ESLint: `resources/js/actions/**` and `resources/js/routes/**` are auto-generated by Wayfinder on every build. Their import order matches PHP scan order, not alphabetical, so import/order fought eslint-fix forever. Added them to ignores.
2026-05-04 15:16:39 +00:00
->where('workspace_id', $workspaceId)
feat: complete create + publish post flow via MCP and REST API Lets ChatGPT (MCP) and external clients (REST API) drive the full lifecycle of a post — create with platform selection, attach media from URLs, schedule or publish immediately, and fetch engagement metrics — without touching the web UI. MCP tools added: UpdatePostTool, PublishPostTool, AttachMediaFromUrlTool, ListContentTypesTool, GetPostMetricsTool, PreviewPostTool. CreatePostTool now accepts platforms[] + scheduled_at + label_ids; ListPostsTool gains status/search/limit filters. REST endpoints added: POST /api/posts/{post}/media, GET /api/posts/{post}/metrics, GET /api/posts/{post}/preview, GET /api/content-types. Also fixes a silent CreatePost::execute bug — the action validated platforms[] but ignored it, so REST callers never saw their selection persisted. Adds cross validation rules (ContentTypeMatchesPlatform / ContentTypeMatchesPostPlatform) so a LinkedIn account can't be saddled with x_post, and rejects inactive social accounts during validation instead of failing silently downstream. Shared services (PostMetricsFetcher, PostPreviewer, MediaAttacher) back both MCP tools and REST controllers so behaviour stays aligned. New Resources (PlatformContentTypesResource, PostMetricsResource, PostPreviewResource, PostMediaAttachResource) keep controllers free of inline model mapping. Suite: 1.332 passing, 0 failing — covers web (PostControllerTest), REST (PostApiTest, PlatformApiTest, PostMediaApiTest), MCP (66 tool tests), and the publish job (PublishToSocialPlatformTest). Removes /docs from git tracking and TIKTOK_REVIEW_VIDEO_SCRIPT.md.
2026-05-04 11:12:28 +00:00
->where('is_active', true),
],
'platforms.*.content_type' => [
'required',
'string',
Rule::in(array_column(ContentType::cases(), 'value')),
new ContentTypeMatchesPlatform,
],
...PostPlatformMetaRules::rules(),
'scheduled_at' => ['nullable', 'date', 'after:now'],
fix: address PR review findings — publish, REST store, SSRF, race Code-review surfaced two correctness bugs and a security gap that needed to land before merging. - UpdatePost::execute disabled every platform when called without a `platforms` key. PublishPostTool relied on that path, so every publish-via-MCP queued a job whose handler then found nothing enabled to publish to. Wrap the platform toggle in `Arr::has($data, 'platforms')` (matches the existing label_ids guard a few lines up). Add a regression assertion to `PostPublishToolTest::publish post immediate dispatches PublishPost job` that the previously-enabled platform stays enabled. - StorePostRequest declared rules for only `platforms`, `scheduled_at`, and `status`. `validated()` then stripped `content`, `media`, and `label_ids`, so REST `POST /api/posts` silently created empty drafts. Added rules for content / media / label_ids (with workspace-scoped `Rule::exists` for labels) and dropped the unused `status` field — REST callers transition state via `PUT /posts/{id}`. Removed the dead `platforms.*.content` rule. Added a feature test that asserts content + media + labels roundtrip on create, plus a regression that an `is_active=false` social_account is rejected at validation. - CreatePost::execute now syncs label_ids itself so REST and MCP share the behavior. Removed the duplicate sync from CreatePostTool. - MCP UpdatePostTool didn't scope `platforms.*.id` to the post being updated, drifting from the REST UpdatePostRequest which adds `Rule::exists('post_platforms','id')->where('post_id', ...)`. Now it loads the post first (failing fast with `Post not found.` if the workspace check rejects), then uses the same Rule::exists. - MediaAttacher fetched any URL the caller passed, including loopback / link-local / private targets — classic SSRF pivot. Now `isPublicHttpUrl` rejects non-http(s) schemes, restricted IP ranges, and DNS hostnames whose A/AAAA records resolve into those ranges (covers DNS rebinding). Bypassed under `app()->runningUnitTests()` so `Http::fake()` keeps working. Streaming the response body lets us abort early once we exceed MAX_BYTES instead of buffering the full payload first; redirects are disabled so a 200→302 trick can't bypass the host check. - The `media[]` JSON column had a lost-update race in `attachFromUrls`: read `$post->media`, mutate in PHP, write back. Two concurrent calls clobbered each other. Now wrapped in a transaction with `lockForUpdate()`. - ESLint: `resources/js/actions/**` and `resources/js/routes/**` are auto-generated by Wayfinder on every build. Their import order matches PHP scan order, not alphabetical, so import/order fought eslint-fix forever. Added them to ignores.
2026-05-04 15:16:39 +00:00
'label_ids' => ['sometimes', 'array'],
'label_ids.*' => [
'uuid',
Rule::exists('workspace_labels', 'id')->where('workspace_id', $workspaceId),
],
];
}
Add optional Pinterest pin title and destination link (#232) * Add optional Pinterest pin title, description, and link. Expose title/description/link across web, API, and MCP; seed description from caption into meta on save, and publish description only from meta. Co-authored-by: Cursor <cursoragent@cursor.com> * Expand Pinterest title/description/link test coverage. Cover web draft persistence and validation bounds, API/MCP update merge and seed, and publisher payload fields on video and carousel pins. Co-authored-by: Cursor <cursoragent@cursor.com> * Simplify Pinterest: description is post content again. Keep optional title and link in meta/settings only. Remove the separate description textarea, seed logic, and meta.description path so Pinterest follows the shared caption pattern. Co-authored-by: Cursor <cursoragent@cursor.com> * Refactor Pinterest meta handling and validation. - Update CreatePost and UpdatePost actions to filter out null values from meta fields. - Introduce a new method in PinterestPublisher to resolve board IDs, ensuring required fields are validated. - Enhance PinterestSettings component to manage title and link inputs, including validation for HTTP URLs. - Update PostPlatformMetaRules to enforce URL validation for Pinterest links. - Add tests for clearing Pinterest title and link, and for rejecting invalid links during scheduling. This refactor improves the handling of Pinterest metadata and enhances user experience by ensuring proper validation and error handling. * Add validation messages and attributes for Pinterest meta fields - Introduced custom validation messages and friendly attribute names for Pinterest link and title fields in PostPlatformMetaRules. - Updated StorePostRequest, UpdatePostRequest, and related tools to utilize these new messages and attributes. - Enhanced tests to assert correct error messages for invalid Pinterest links and title length constraints. This update improves user feedback during post creation and editing, ensuring clarity in validation errors. * Remove click.prevent directive from Pinterest link in PinterestPreview component. This change simplifies the link behavior, allowing default click actions to occur, which may enhance user interaction with the Pinterest link. * Update validation error messages for Pinterest meta fields in tests - Refined the assertions in PostApiPlatformMetaTest to include localized validation messages for Pinterest title and link fields. - Ensured that error messages reflect the updated validation rules, enhancing clarity for users during post creation and editing. --------- Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 21:15:50 +00:00
/**
* @return array<string, string>
*/
public function messages(): array
{
return PostPlatformMetaRules::messages();
}
/**
* @return array<string, string>
*/
public function attributes(): array
{
return PostPlatformMetaRules::attributes();
}
/**
* @return Collection<int, Platform>
*/
public function selectedPlatforms(): Collection
{
return $this->resolveSelectedPlatforms($this->user()->currentWorkspace->id)->values();
}
/**
* @return Collection<int|string, Platform>
*/
private function resolveSelectedPlatforms(string $workspaceId): Collection
{
$accountIds = collect($this->input('platforms', []))->pluck('social_account_id')->filter()->all();
if (empty($accountIds)) {
return collect();
}
return SocialAccount::query()
->where('workspace_id', $workspaceId)
->whereIn('id', $accountIds)
->pluck('platform', 'id');
}
}