trypost/app/Http/Controllers/Api/PostController.php

202 lines
6.3 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api;
feat: Asset Library list, preview, and attach via API and MCP (#282) * feat: list, preview, and attach Asset Library media via API and MCP Let API and MCP clients reuse workspace assets instead of re-uploading, sharing the same scoped query, signed preview, and idempotent attach path. Co-authored-by: Cursor <cursoragent@cursor.com> * Align Asset Library API and MCP with main media patterns. Drop the signed-preview stack, return Storage URLs and PostResource like existing attach flows, and query medias by morph owner instead of getMedia(). Co-authored-by: Cursor <cursoragent@cursor.com> * Paginate workspace assets with the app default page size. Keep list pagination in the action via config('app.pagination.default') instead of a hardcoded API page size. Co-authored-by: Cursor <cursoragent@cursor.com> * Move asset API and MCP input rules into FormRequests. Keep controllers and tools free of inline field validation; MCP tools reuse the request rule definitions. Co-authored-by: Cursor <cursoragent@cursor.com> * Document asset MCP tools with explicit parameters and constraints. Spell out workspace scope, return fields, sibling tools, and rejection cases so agents can call list/get/attach without guessing. Co-authored-by: Cursor <cursoragent@cursor.com> * Harden asset attach against races and keep library metadata on the post. Co-authored-by: Cursor <cursoragent@cursor.com> * Relock the library asset on attach so a deleted file cannot land on the post. Co-authored-by: Cursor <cursoragent@cursor.com> * Document that omitting alt on attach keeps the library alt text. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 20:08:20 +00:00
use App\Actions\Post\AttachExistingAsset;
use App\Actions\Post\CreatePost;
use App\Actions\Post\DeletePost;
use App\Actions\Post\HostInlineMedia;
use App\Actions\Post\UpdatePost;
use App\Enums\Media\Type as MediaType;
use App\Enums\Post\Action as PostAction;
use App\Enums\Post\CreatedVia;
feat: Asset Library list, preview, and attach via API and MCP (#282) * feat: list, preview, and attach Asset Library media via API and MCP Let API and MCP clients reuse workspace assets instead of re-uploading, sharing the same scoped query, signed preview, and idempotent attach path. Co-authored-by: Cursor <cursoragent@cursor.com> * Align Asset Library API and MCP with main media patterns. Drop the signed-preview stack, return Storage URLs and PostResource like existing attach flows, and query medias by morph owner instead of getMedia(). Co-authored-by: Cursor <cursoragent@cursor.com> * Paginate workspace assets with the app default page size. Keep list pagination in the action via config('app.pagination.default') instead of a hardcoded API page size. Co-authored-by: Cursor <cursoragent@cursor.com> * Move asset API and MCP input rules into FormRequests. Keep controllers and tools free of inline field validation; MCP tools reuse the request rule definitions. Co-authored-by: Cursor <cursoragent@cursor.com> * Document asset MCP tools with explicit parameters and constraints. Spell out workspace scope, return fields, sibling tools, and rejection cases so agents can call list/get/attach without guessing. Co-authored-by: Cursor <cursoragent@cursor.com> * Harden asset attach against races and keep library metadata on the post. Co-authored-by: Cursor <cursoragent@cursor.com> * Relock the library asset on attach so a deleted file cannot land on the post. Co-authored-by: Cursor <cursoragent@cursor.com> * Document that omitting alt on attach keeps the library alt text. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 20:08:20 +00:00
use App\Http\Requests\Api\Post\AttachExistingAssetRequest;
use App\Http\Requests\Api\Post\AttachMediaFromUrlRequest;
use App\Http\Requests\Api\Post\StoreMediaRequest;
use App\Http\Requests\Api\Post\StorePostRequest;
use App\Http\Requests\Api\Post\UpdatePostRequest;
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\Http\Resources\Api\PostMediaAttachResource;
use App\Http\Resources\Api\PostMetricsResource;
use App\Http\Resources\Api\PostPreviewResource;
use App\Http\Resources\Api\PostResource;
use App\Models\Post;
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\Services\Post\MediaAttacher;
use App\Support\PostStatusRules;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
class PostController extends Controller
{
public function index(Request $request): AnonymousResourceCollection
{
$posts = $request->user()->currentWorkspace->posts()
->with(['postPlatforms.socialAccount', 'user', 'labels'])
->latest('scheduled_at')
->paginate(15);
return PostResource::collection($posts);
}
public function show(Request $request, Post $post): PostResource
{
$this->authorize('view', $post);
$post->load(['postPlatforms.socialAccount', 'user', 'labels']);
return new PostResource($post);
}
public function store(StorePostRequest $request): JsonResponse
{
$workspace = $request->user()->currentWorkspace;
$data = $request->validated();
if (array_key_exists('media', $data)) {
$data['media'] = HostInlineMedia::execute(
$workspace,
Post::allowedMediaTypesFor($request->selectedPlatforms()),
$data['media'],
);
}
$data['created_via'] = CreatedVia::Api;
$post = CreatePost::execute($workspace, $workspace->owner, $data);
$post->load(['postPlatforms.socialAccount']);
return (new PostResource($post))
->response()
->setStatusCode(Response::HTTP_CREATED);
}
public function update(UpdatePostRequest $request, Post $post): PostResource|JsonResponse
{
$this->authorize('update', $post);
$data = $request->validated();
if (array_key_exists('media', $data)) {
$data['media'] = HostInlineMedia::execute(
$request->user()->currentWorkspace,
$post->allowedMediaTypes(),
$data['media'],
);
}
$result = UpdatePost::execute($request->user()->currentWorkspace, $post, $data);
if (data_get($result, 'action') === PostAction::Finalized) {
return response()->json(
['message' => PostStatusRules::editBlockedMessage()],
Response::HTTP_UNPROCESSABLE_ENTITY
);
}
$updated = data_get($result, 'post');
$updated->load(['postPlatforms.socialAccount']);
return new PostResource($updated);
}
public function destroy(Request $request, Post $post): JsonResponse
{
$this->authorize('delete', $post);
DeletePost::execute($post);
return response()->json(null, Response::HTTP_NO_CONTENT);
}
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
public function storeMedia(StoreMediaRequest $request, Post $post): PostResource
{
$this->authorize('update', $post);
$file = $request->file('media');
$type = MediaType::fromMime((string) $file->getMimeType());
if ($type === null || ! in_array($type, $post->allowedMediaTypes(), true)) {
throw ValidationException::withMessages([
'media' => 'This file type is not supported by the platforms enabled on the post.',
]);
}
if ($file->getSize() > $type->maxSizeInBytes()) {
throw ValidationException::withMessages([
'media' => 'File size exceeds the maximum allowed for this media type.',
]);
}
$media = $post->workspace->addMedia($file, 'assets');
$post->appendMedia([[
'id' => $media->id,
'path' => $media->path,
'url' => $media->url,
'type' => $media->type,
'mime_type' => $media->mime_type,
'original_filename' => $media->original_filename,
]]);
$post->refresh()->load(['postPlatforms.socialAccount', 'labels']);
return new PostResource($post);
}
feat: Asset Library list, preview, and attach via API and MCP (#282) * feat: list, preview, and attach Asset Library media via API and MCP Let API and MCP clients reuse workspace assets instead of re-uploading, sharing the same scoped query, signed preview, and idempotent attach path. Co-authored-by: Cursor <cursoragent@cursor.com> * Align Asset Library API and MCP with main media patterns. Drop the signed-preview stack, return Storage URLs and PostResource like existing attach flows, and query medias by morph owner instead of getMedia(). Co-authored-by: Cursor <cursoragent@cursor.com> * Paginate workspace assets with the app default page size. Keep list pagination in the action via config('app.pagination.default') instead of a hardcoded API page size. Co-authored-by: Cursor <cursoragent@cursor.com> * Move asset API and MCP input rules into FormRequests. Keep controllers and tools free of inline field validation; MCP tools reuse the request rule definitions. Co-authored-by: Cursor <cursoragent@cursor.com> * Document asset MCP tools with explicit parameters and constraints. Spell out workspace scope, return fields, sibling tools, and rejection cases so agents can call list/get/attach without guessing. Co-authored-by: Cursor <cursoragent@cursor.com> * Harden asset attach against races and keep library metadata on the post. Co-authored-by: Cursor <cursoragent@cursor.com> * Relock the library asset on attach so a deleted file cannot land on the post. Co-authored-by: Cursor <cursoragent@cursor.com> * Document that omitting alt on attach keeps the library alt text. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 20:08:20 +00:00
public function attachExistingAsset(AttachExistingAssetRequest $request, Post $post): PostResource|JsonResponse
{
$this->authorize('update', $post);
if (PostStatusRules::blocksEditing($post)) {
return response()->json(
['message' => PostStatusRules::editBlockedMessage()],
Response::HTTP_UNPROCESSABLE_ENTITY,
);
}
AttachExistingAsset::execute(
$post,
$request->asset(),
$request->validated('alt'),
);
$post->refresh()->load(['postPlatforms.socialAccount', 'labels']);
return new PostResource($post);
}
public function attachMediaFromUrl(AttachMediaFromUrlRequest $request, Post $post): PostMediaAttachResource
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
{
$this->authorize('update', $post);
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
$result = app(MediaAttacher::class)->attachFromUrls($post, $request->validated('urls'));
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
$post->refresh()->load(['postPlatforms.socialAccount', 'labels']);
return new PostMediaAttachResource($post, $result);
}
public function metrics(Request $request, Post $post): PostMetricsResource
{
$this->authorize('view', $post);
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
$post->load(['postPlatforms.socialAccount']);
return new PostMetricsResource($post);
}
public function preview(Request $request, Post $post): PostPreviewResource
{
$this->authorize('view', $post);
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
$post->load(['postPlatforms.socialAccount']);
return new PostPreviewResource($post);
}
}