trypost/tests/Feature/Api/PostMediaApiTest.php

950 lines
35 KiB
PHP
Raw Normal View History

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
<?php
declare(strict_types=1);
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\Enums\Post\Status as PostStatus;
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\Enums\SocialAccount\Platform;
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\Enums\UserWorkspace\Role;
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\Models\Media;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
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\Models\User;
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\Models\Workspace;
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\Support\PostMediaRules;
use App\Support\PostStatusRules;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\UploadedFile;
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 Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
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 Illuminate\Validation\ValidationException;
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
// A public IP literal as the host lets SafeHttpFetcher's SSRF guard pass without
// a real DNS lookup; Http::fake() intercepts the request before any network I/O.
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
beforeEach(function () {
$result = createApiTestToken();
$this->user = $result['user'];
$this->workspace = $result['workspace'];
$this->plainToken = $result['plain_token'];
$this->socialAccount = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::LinkedIn,
]);
$this->post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
PostPlatform::factory()->linkedin()->create([
'post_id' => $this->post->id,
'social_account_id' => $this->socialAccount->id,
'enabled' => true,
]);
Storage::fake();
});
it('attaches media from url', function () {
Http::fake([
refactor: move URL validation to the request layer with active_url The MediaAttacher used to roll its own SSRF guard with DNS resolution and a static fakeUrlSafety() flag for tests. Validating URLs is a request-layer concern, not a service-layer one. Laravel ships 'active_url' which does the same DNS resolvability check via dns_get_record — applying it at the FormRequest / MCP validate() level catches dead URLs upfront with a proper 422 instead of letting the download silently fail. - Replace the inline 'urls.*' => ['url:http,https'] rule with ['url:http,https', 'active_url'] in both Api/PostController::attachMedia and Mcp/Tools/Post/AttachMediaFromUrlTool. - Drop isUrlSafe(), fakeUrlSafety(), resetUrlSafety(), $skipUrlSafety from MediaAttacher. The remaining defenses (Http::sink streaming + progress abort at MAX_BYTES, allow_redirects: false, MIME allowlist) cover the operational concerns. - Restore tests/TestCase to the original setUp — no SSRF bypass needed anymore because active_url is satisfied by the test hosts. - Swap synthetic test hosts (cdn.example.com / evil.example.com) for example.com / example.org. Both are RFC-reserved AND have stable A records, so active_url accepts them while Http::fake() still intercepts the actual request. For SSRF defense beyond 'active_url' (which doesn't block private IPs), trypost relies on production network egress controls. Open-source self-hosters who run without a firewall accept the corresponding risk; that's a deployment concern, not a request validation concern.
2026-05-04 17:35:28 +00:00
'example.com/photo.png' => Http::response(
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
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media-from-url', $this->post), [
'urls' => [['url' => 'https://example.com/photo.png']],
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
])
->assertOk()
->assertJsonPath('attached_count', 1)
->assertJsonPath('failed_urls', []);
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);
expect($this->post->fresh()->media)->toHaveCount(1);
});
it('attaches media from url with alt text', function () {
Http::fake([
'example.com/photo.png' => Http::response(
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media-from-url', $this->post), [
'urls' => [['url' => 'https://example.com/photo.png', 'alt' => 'A red bicycle by a wall']],
])
->assertOk()
->assertJsonPath('attached_count', 1);
expect(data_get($this->post->fresh()->media, '0.meta.alt_text'))->toBe('A red bicycle by a wall');
});
it('does not store alt text on a non-image url', function () {
Http::fake([
'example.com/deck.pdf' => Http::response(
"%PDF-1.4\n1 0 obj<</Type/Catalog>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF\n",
200,
['Content-Type' => 'application/pdf'],
),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media-from-url', $this->post), [
'urls' => [['url' => 'https://example.com/deck.pdf', 'alt' => 'alt is meaningless for a pdf']],
])
->assertOk()
->assertJsonPath('attached_count', 1);
expect(data_get($this->post->fresh()->media, '0.type'))->toBe('document')
->and(data_get($this->post->fresh()->media, '0.meta'))->toBeNull();
});
it('rejects alt text over the max length on a url', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media-from-url', $this->post), [
'urls' => [['url' => 'https://example.com/photo.png', 'alt' => str_repeat('a', 2001)]],
])
->assertUnprocessable()
->assertJsonValidationErrors(['urls.0.alt']);
});
it('rejects the old bare-string urls shape', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media-from-url', $this->post), [
'urls' => ['https://example.com/photo.png'],
])
->assertUnprocessable()
->assertJsonValidationErrors(['urls.0.url']);
});
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
it('reports failures for unreachable urls', function () {
Http::fake([
refactor: move URL validation to the request layer with active_url The MediaAttacher used to roll its own SSRF guard with DNS resolution and a static fakeUrlSafety() flag for tests. Validating URLs is a request-layer concern, not a service-layer one. Laravel ships 'active_url' which does the same DNS resolvability check via dns_get_record — applying it at the FormRequest / MCP validate() level catches dead URLs upfront with a proper 422 instead of letting the download silently fail. - Replace the inline 'urls.*' => ['url:http,https'] rule with ['url:http,https', 'active_url'] in both Api/PostController::attachMedia and Mcp/Tools/Post/AttachMediaFromUrlTool. - Drop isUrlSafe(), fakeUrlSafety(), resetUrlSafety(), $skipUrlSafety from MediaAttacher. The remaining defenses (Http::sink streaming + progress abort at MAX_BYTES, allow_redirects: false, MIME allowlist) cover the operational concerns. - Restore tests/TestCase to the original setUp — no SSRF bypass needed anymore because active_url is satisfied by the test hosts. - Swap synthetic test hosts (cdn.example.com / evil.example.com) for example.com / example.org. Both are RFC-reserved AND have stable A records, so active_url accepts them while Http::fake() still intercepts the actual request. For SSRF defense beyond 'active_url' (which doesn't block private IPs), trypost relies on production network egress controls. Open-source self-hosters who run without a firewall accept the corresponding risk; that's a deployment concern, not a request validation concern.
2026-05-04 17:35:28 +00:00
'example.com/missing.png' => Http::response(null, 404),
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->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media-from-url', $this->post), [
'urls' => [['url' => 'https://example.com/missing.png']],
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
])
->assertOk()
->assertJsonPath('attached_count', 0)
refactor: move URL validation to the request layer with active_url The MediaAttacher used to roll its own SSRF guard with DNS resolution and a static fakeUrlSafety() flag for tests. Validating URLs is a request-layer concern, not a service-layer one. Laravel ships 'active_url' which does the same DNS resolvability check via dns_get_record — applying it at the FormRequest / MCP validate() level catches dead URLs upfront with a proper 422 instead of letting the download silently fail. - Replace the inline 'urls.*' => ['url:http,https'] rule with ['url:http,https', 'active_url'] in both Api/PostController::attachMedia and Mcp/Tools/Post/AttachMediaFromUrlTool. - Drop isUrlSafe(), fakeUrlSafety(), resetUrlSafety(), $skipUrlSafety from MediaAttacher. The remaining defenses (Http::sink streaming + progress abort at MAX_BYTES, allow_redirects: false, MIME allowlist) cover the operational concerns. - Restore tests/TestCase to the original setUp — no SSRF bypass needed anymore because active_url is satisfied by the test hosts. - Swap synthetic test hosts (cdn.example.com / evil.example.com) for example.com / example.org. Both are RFC-reserved AND have stable A records, so active_url accepts them while Http::fake() still intercepts the actual request. For SSRF defense beyond 'active_url' (which doesn't block private IPs), trypost relies on production network egress controls. Open-source self-hosters who run without a firewall accept the corresponding risk; that's a deployment concern, not a request validation concern.
2026-05-04 17:35:28 +00:00
->assertJsonPath('failed_urls.0', 'https://example.com/missing.png');
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
});
it('cannot attach media to a post from another workspace', function () {
$other = Workspace::factory()->create();
$post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media-from-url', $post), [
'urls' => [['url' => 'https://example.com/photo.png']],
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
])
->assertNotFound();
});
it('previews per platform with sanitized content and length', function () {
$this->post->update(['content' => str_repeat('a', 500)]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.posts.preview', $this->post))
->assertOk()
->assertJsonStructure([
'post_id',
'original_content',
'original_length',
'platforms' => [
'*' => [
'post_platform_id',
'platform',
'content_type',
'sanitized_content',
'sanitized_length',
'max_content_length',
'truncated',
],
],
])
->assertJsonPath('original_length', 500);
});
it('returns metrics shape including unsupported reason for unpublished platforms', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.posts.metrics', $this->post))
->assertOk()
->assertJsonStructure([
'post_id',
'platforms' => [
'*' => [
'post_platform_id',
'platform',
'status',
'platform_post_id',
'platform_url',
'metrics',
],
],
])
->assertJsonPath('platforms.0.metrics.unsupported', true)
->assertJsonPath('platforms.0.metrics.reason', 'not_published');
});
it('cannot get metrics from another workspace post', function () {
$other = Workspace::factory()->create();
$post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.posts.metrics', $post))
->assertNotFound();
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.posts.preview', $post))
->assertNotFound();
});
it('rejects attach media payload without urls', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media-from-url', $this->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
->assertUnprocessable()
->assertJsonValidationErrors(['urls']);
});
it('uploads a media file and attaches it to the post', function () {
$file = UploadedFile::fake()->createWithContent(
'photo.png',
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken, 'Accept' => 'application/json'])
->post(route('api.posts.store-media', $this->post), ['media' => $file])
->assertOk();
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);
expect($this->post->fresh()->media)->toHaveCount(1);
});
it('rejects upload of an unsupported mime type', function () {
$file = UploadedFile::fake()->createWithContent('doc.txt', 'plain text content');
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken, 'Accept' => 'application/json'])
->post(route('api.posts.store-media', $this->post), ['media' => $file])
->assertUnprocessable()
->assertJsonValidationErrors(['media']);
});
it('rejects upload when the file type is not supported by enabled platforms', function () {
$tiktokAccount = SocialAccount::factory()->tiktok()->create([
'workspace_id' => $this->workspace->id,
]);
$tiktokOnlyPost = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
PostPlatform::factory()->tiktok()->create([
'post_id' => $tiktokOnlyPost->id,
'social_account_id' => $tiktokAccount->id,
'enabled' => true,
]);
$file = UploadedFile::fake()->createWithContent(
'photo.png',
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken, 'Accept' => 'application/json'])
->post(route('api.posts.store-media', $tiktokOnlyPost), ['media' => $file])
->assertUnprocessable()
->assertJsonValidationErrors(['media']);
});
it('cannot upload media to a post from another workspace', function () {
$other = Workspace::factory()->create();
$post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);
$file = UploadedFile::fake()->createWithContent(
'photo.png',
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken, 'Accept' => 'application/json'])
->post(route('api.posts.store-media', $post), ['media' => $file])
->assertNotFound();
});
it('rejects upload without a media file', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store-media', $this->post), [])
->assertUnprocessable()
->assertJsonValidationErrors(['media']);
});
it('downloads and hosts an external media url when creating a post', function () {
$this->socialAccount->update(['is_active' => true]);
Http::fake([
'93.184.216.34/listing.jpg' => Http::response(
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => 'External media post',
'media' => [['url' => 'https://93.184.216.34/listing.jpg']],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
])
->assertCreated();
$media = Post::where('content', 'External media post')->firstOrFail()->media;
expect($media)->toHaveCount(1)
->and(data_get($media, '0.path'))->not->toBeNull()
->and(data_get($media, '0.url'))->not->toContain('93.184.216.34');
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);
});
it('persists alt text submitted on a bare external media url', function () {
$this->socialAccount->update(['is_active' => true]);
Http::fake([
'93.184.216.34/car.jpg' => Http::response(
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => 'External alt post',
'media' => [[
'url' => 'https://93.184.216.34/car.jpg',
'meta' => ['alt_text' => 'A red car parked on a hill'],
]],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
])
->assertCreated();
$media = Post::where('content', 'External alt post')->firstOrFail()->media;
expect(data_get($media, '0.meta.alt_text'))->toBe('A red car parked on a hill')
->and(data_get($media, '0.path'))->not->toBeNull();
});
it('rejects creating a post when an external media url cannot be fetched', function () {
$this->socialAccount->update(['is_active' => true]);
Http::fake(['93.184.216.34/missing.jpg' => Http::response(null, 404)]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => 'Broken media post',
'media' => [['url' => 'https://93.184.216.34/missing.jpg']],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
])
->assertUnprocessable()
->assertJsonValidationErrors(['media']);
expect(Post::where('content', 'Broken media post')->exists())->toBeFalse();
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(0);
});
it('rolls back already-hosted media when another url in the batch fails', function () {
$this->socialAccount->update(['is_active' => true]);
Http::fake([
'93.184.216.34/good.jpg' => Http::response(
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
'93.184.216.34/missing.jpg' => Http::response(null, 404),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => 'Partial media post',
'media' => [
['url' => 'https://93.184.216.34/good.jpg'],
['url' => 'https://93.184.216.34/missing.jpg'],
],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
])
->assertUnprocessable()
->assertJsonValidationErrors(['media']);
expect(Post::where('content', 'Partial media post')->exists())->toBeFalse();
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(0);
});
it('rejects and rolls back when a media url connection fails (timeout/dns)', function () {
$this->socialAccount->update(['is_active' => true]);
Http::fake([
'93.184.216.34/good.jpg' => Http::response(
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
'93.184.216.34/timeout.jpg' => fn () => throw new ConnectionException('Connection timed out'),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => 'Timeout media post',
'media' => [
['url' => 'https://93.184.216.34/good.jpg'],
['url' => 'https://93.184.216.34/timeout.jpg'],
],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
])
->assertUnprocessable()
->assertJsonValidationErrors(['media']);
expect(Post::where('content', 'Timeout media post')->exists())->toBeFalse();
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(0);
});
it('rejects creating a post when an external media url is not a supported type', function () {
$this->socialAccount->update(['is_active' => true]);
// Downloads fine (200) but the bytes are not a supported media type.
Http::fake(['93.184.216.34/notes.txt' => Http::response('just some text', 200)]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => 'Bad type post',
'media' => [['url' => 'https://93.184.216.34/notes.txt']],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
])
->assertUnprocessable()
->assertJsonValidationErrors(['media']);
expect(Post::where('content', 'Bad type post')->exists())->toBeFalse();
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(0);
});
it('keeps an already-hosted item and a freshly-hosted url in order', function () {
$this->socialAccount->update(['is_active' => true]);
Http::fake([
'93.184.216.34/external.jpg' => Http::response(
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => 'Mixed media post',
'media' => [
['id' => 'hosted-1', 'path' => 'assets/already.jpg', 'url' => 'https://cdn.trypost.test/assets/already.jpg', 'type' => 'image'],
['url' => 'https://93.184.216.34/external.jpg'],
],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
])
->assertCreated();
$media = Post::where('content', 'Mixed media post')->firstOrFail()->media;
expect($media)->toHaveCount(2)
->and(data_get($media, '0.path'))->toBe('assets/already.jpg')
->and(data_get($media, '1.url'))->not->toContain('93.184.216.34')
->and(data_get($media, '1.path'))->not->toBeNull();
// Only the external URL is hosted; the passed-through item creates no new row.
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);
});
it('passes already-hosted media through on create without downloading', function () {
$this->socialAccount->update(['is_active' => true]);
Http::preventStrayRequests();
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => 'Hosted media post',
'media' => [[
'id' => 'media-1',
'path' => 'assets/foo.jpg',
'url' => 'https://cdn.trypost.test/assets/foo.jpg',
'type' => 'image',
]],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
])
->assertCreated();
expect(data_get(Post::where('content', 'Hosted media post')->firstOrFail()->media, '0.path'))->toBe('assets/foo.jpg');
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(0);
});
it('downloads and hosts an external media url when updating a post', function () {
Http::fake([
'93.184.216.34/listing.jpg' => Http::response(
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $this->post), [
'status' => 'draft',
'media' => [['url' => 'https://93.184.216.34/listing.jpg']],
])
->assertOk();
$media = $this->post->fresh()->media;
expect($media)->toHaveCount(1)
->and(data_get($media, '0.path'))->not->toBeNull()
->and(data_get($media, '0.url'))->not->toContain('93.184.216.34');
});
it('rejects updating a post when an external media url cannot be fetched', function () {
Http::fake(['93.184.216.34/missing.jpg' => Http::response(null, 404)]);
$original = $this->post->fresh()->media;
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $this->post), [
'status' => 'draft',
'media' => [['url' => 'https://93.184.216.34/missing.jpg']],
])
->assertUnprocessable()
->assertJsonValidationErrors(['media']);
expect($this->post->fresh()->media)->toBe($original);
});
it('accepts and persists media alt text on create', function () {
$this->socialAccount->update(['is_active' => true]);
Http::preventStrayRequests();
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => 'Alt text post',
'media' => [[
'id' => 'media-1',
'path' => 'assets/foo.jpg',
'url' => 'https://cdn.trypost.test/assets/foo.jpg',
'type' => 'image',
'meta' => ['alt_text' => 'A description of the photo'],
]],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
])
->assertCreated();
$media = Post::where('content', 'Alt text post')->firstOrFail()->media;
expect(data_get($media, '0.meta.alt_text'))->toBe('A description of the photo');
});
it('accepts and persists media alt text on update', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $this->post), [
'status' => 'draft',
'media' => [[
'id' => 'media-1',
'path' => 'assets/foo.jpg',
'url' => 'https://cdn.trypost.test/assets/foo.jpg',
'type' => 'image',
'meta' => ['alt_text' => 'Updated alt text'],
]],
])
->assertOk();
expect(data_get($this->post->fresh()->media, '0.meta.alt_text'))->toBe('Updated alt text');
});
it('preserves every media meta key on update, not just alt_text', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $this->post), [
'status' => 'draft',
'media' => [[
'id' => 'media-1',
'path' => 'assets/foo.jpg',
'url' => 'https://cdn.trypost.test/assets/foo.jpg',
'type' => 'image',
'meta' => [
'width' => 1920,
'height' => 1080,
'duration' => 30,
'alt_text' => 'A description of the photo',
],
]],
])
->assertOk();
expect(data_get($this->post->fresh()->media, '0.meta'))->toMatchArray([
'width' => 1920,
'height' => 1080,
'duration' => 30,
'alt_text' => 'A description of the photo',
]);
});
it('rejects media alt text over 2000 characters', function () {
$this->socialAccount->update(['is_active' => true]);
Http::preventStrayRequests();
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => 'Alt text too long post',
'media' => [[
'id' => 'media-1',
'path' => 'assets/foo.jpg',
'url' => 'https://cdn.trypost.test/assets/foo.jpg',
'type' => 'image',
'meta' => ['alt_text' => str_repeat('a', 2001)],
]],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
])
->assertUnprocessable()
->assertJsonValidationErrors(['media.0.meta']);
expect(Post::where('content', 'Alt text too long post')->exists())->toBeFalse();
});
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
it('attaches an existing workspace asset to a post', function () {
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
'original_filename' => 'library.jpg',
'size' => 12345,
'meta' => [
'width' => 1920,
'height' => 1080,
'duration' => 12.5,
'color_space' => 'srgb',
],
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
'alt' => 'Library hero',
])
->assertOk()
->assertJsonPath('id', $this->post->id);
expect($this->post->fresh()->media)->toHaveCount(1)
->and(data_get($this->post->fresh()->media, '0.id'))->toBe($asset->id)
->and(data_get($this->post->fresh()->media, '0.size'))->toBe(12345)
Make the test suite pass on MySQL (#307) * Give the foreign key a backing index before dropping the unique social_accounts.workspace_id carries a foreign key, and the composite unique index is the only one covering it, as its leftmost prefix. MySQL refuses to drop the sole index backing a foreign key (SQLSTATE[HY000] 1553), so both rehearsal suites failed in beforeEach and never ran a single assertion on MySQL. Add a plain index on workspace_id first; PostgreSQL has no such requirement and simply carries it. This unmasks one assertion underneath that had never executed: the automation graph comparison at DuplicateIdentityMigrationTest.php:419 depended on JSON object key order, which MySQL normalises on storage. (cherry picked from commit 98a494bd2205e873321a18232f63b358ae259fdf) * Compare JSON payloads without depending on key order MySQL normalises JSON object keys (length, then lexicographic) on storage, so an identity comparison against a literal asserts how the driver chose to lay the object out rather than what it contains. PostgreSQL preserves insertion order, which is why these passed there. toEqual compares associative arrays recursively without regard to key order. Applied to every assertion in this class, including the few that pass today only because their keys already happen to match MySQL's ordering. (cherry picked from commit 3124023c548d6c2b8b52126afc6fc5f38d461ea6) * Match logged SQL without depending on identifier quoting Four DB::listen predicates matched 'select * from "post_platforms"'. PostgreSQL quotes identifiers with double quotes and MySQL with backticks, so on MySQL the predicates never matched, the simulated mid-run pause never fired, and the race these tests exist to cover went unexercised while the tests still reported failures elsewhere. Compare against the unquoted form via a small helper. (cherry picked from commit 67a81df5de155e80227df748b34cd8b3cfd744f9) * Cast raw boolean reads in tests so they pass on MySQL Three assertions read oauth_refresh_tokens.revoked through the query builder rather than Eloquent, so no cast applies and the driver's native representation leaks into the test: a real boolean on PostgreSQL, 1 on MySQL. Cast explicitly at the call site. (cherry picked from commit 2911c5c48cf65d24a34a41e667335c40005839a7) * Use a scheduling date inside MySQL's TIMESTAMP range MySQL TIMESTAMP columns end at 2038-01-19, so the 2099 sentinel these tests used is rejected outright with SQLSTATE[22007]. 2037-12-31 still reads as a far-future schedule and works on both engines. (cherry picked from commit bde33eb239cdbd3a5567d4c21e1d85302913cdd7) * Remove the duplicate-identity migration scenario test The suite rebuilt a pre-migration schema by dropping the unique index in beforeEach and re-running the migration by hand, exercising a database state the application never runs in. * Fix the MySQL rollback path and run CI on both engines The migration's down() dropped a unique whose leftmost prefix is an FK column, which MySQL refuses when nothing else backs the constraint (SQLSTATE 1553). It now creates a standalone index first, so migrate:rollback works on MySQL and stays a no-op change for PostgreSQL. up() is untouched: every database already migrated keeps its schema. The rehearsal test calls that down() instead of hand-rolling the drop, so it exercises the real rollback rather than an imitation of it. Matches logged SQL through the connection's query grammar rather than stripping quote characters, and adds a MySQL leg to the backend CI job. * Use a readiness check both database images can run mysql:8.4 installs mysql-community-server-minimal, which ships neither mysqladmin nor the mysql client, so a mysqladmin health command never succeeds and the service never reports healthy. Both images run their init phase without networking, so an open port is the point either engine starts accepting connections - one check covers both, and the per-engine matrix key goes away. * Use each engine's own readiness tool pg_isready and mysqladmin ping are what the respective images ship for this, and the mysql image's entrypoint invokes mysqladmin itself, so it is present. Keeps 20 retries, which MySQL needs to finish initialising. * State the two-engine ceiling as a rule, not a test detail The 2038 TIMESTAMP limit binds anything written to the column, not just the sentinel dates in fixtures, and the same reasoning generalises: what the app supports is the intersection of both engines. * Let the release image connect to MySQL The published image installed only pdo_pgsql, so DB_CONNECTION=mysql failed with "could not find driver" before any query ran - the app supports MySQL but the image people actually deploy could not reach it. mysql-client mirrors the postgresql-client already present, for artisan db and dumps. * Keep "backend" a single required status check Matrixing the job split its check in two, so the "backend" context the branch protection requires was never reported and every PR sat waiting on it. The matrix is now "tests" and a small "backend" job gates on it, which keeps the required check stable however many engines the matrix grows to - and leaves the open PRs mergeable without a rebase. --------- Co-authored-by: Paulo Castellano <paulo@castellanos.llc>
2026-08-29 14:05:33 +00:00
->and(data_get($this->post->fresh()->media, '0.meta'))->toEqual([
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
'width' => 1920,
'height' => 1080,
'duration' => 12.5,
'color_space' => 'srgb',
'alt_text' => 'Library hero',
]);
});
it('preserves library alt text when attach omits alt', function () {
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
'meta' => [
'width' => 800,
'height' => 600,
'alt_text' => 'From library',
],
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
])
->assertOk();
Make the test suite pass on MySQL (#307) * Give the foreign key a backing index before dropping the unique social_accounts.workspace_id carries a foreign key, and the composite unique index is the only one covering it, as its leftmost prefix. MySQL refuses to drop the sole index backing a foreign key (SQLSTATE[HY000] 1553), so both rehearsal suites failed in beforeEach and never ran a single assertion on MySQL. Add a plain index on workspace_id first; PostgreSQL has no such requirement and simply carries it. This unmasks one assertion underneath that had never executed: the automation graph comparison at DuplicateIdentityMigrationTest.php:419 depended on JSON object key order, which MySQL normalises on storage. (cherry picked from commit 98a494bd2205e873321a18232f63b358ae259fdf) * Compare JSON payloads without depending on key order MySQL normalises JSON object keys (length, then lexicographic) on storage, so an identity comparison against a literal asserts how the driver chose to lay the object out rather than what it contains. PostgreSQL preserves insertion order, which is why these passed there. toEqual compares associative arrays recursively without regard to key order. Applied to every assertion in this class, including the few that pass today only because their keys already happen to match MySQL's ordering. (cherry picked from commit 3124023c548d6c2b8b52126afc6fc5f38d461ea6) * Match logged SQL without depending on identifier quoting Four DB::listen predicates matched 'select * from "post_platforms"'. PostgreSQL quotes identifiers with double quotes and MySQL with backticks, so on MySQL the predicates never matched, the simulated mid-run pause never fired, and the race these tests exist to cover went unexercised while the tests still reported failures elsewhere. Compare against the unquoted form via a small helper. (cherry picked from commit 67a81df5de155e80227df748b34cd8b3cfd744f9) * Cast raw boolean reads in tests so they pass on MySQL Three assertions read oauth_refresh_tokens.revoked through the query builder rather than Eloquent, so no cast applies and the driver's native representation leaks into the test: a real boolean on PostgreSQL, 1 on MySQL. Cast explicitly at the call site. (cherry picked from commit 2911c5c48cf65d24a34a41e667335c40005839a7) * Use a scheduling date inside MySQL's TIMESTAMP range MySQL TIMESTAMP columns end at 2038-01-19, so the 2099 sentinel these tests used is rejected outright with SQLSTATE[22007]. 2037-12-31 still reads as a far-future schedule and works on both engines. (cherry picked from commit bde33eb239cdbd3a5567d4c21e1d85302913cdd7) * Remove the duplicate-identity migration scenario test The suite rebuilt a pre-migration schema by dropping the unique index in beforeEach and re-running the migration by hand, exercising a database state the application never runs in. * Fix the MySQL rollback path and run CI on both engines The migration's down() dropped a unique whose leftmost prefix is an FK column, which MySQL refuses when nothing else backs the constraint (SQLSTATE 1553). It now creates a standalone index first, so migrate:rollback works on MySQL and stays a no-op change for PostgreSQL. up() is untouched: every database already migrated keeps its schema. The rehearsal test calls that down() instead of hand-rolling the drop, so it exercises the real rollback rather than an imitation of it. Matches logged SQL through the connection's query grammar rather than stripping quote characters, and adds a MySQL leg to the backend CI job. * Use a readiness check both database images can run mysql:8.4 installs mysql-community-server-minimal, which ships neither mysqladmin nor the mysql client, so a mysqladmin health command never succeeds and the service never reports healthy. Both images run their init phase without networking, so an open port is the point either engine starts accepting connections - one check covers both, and the per-engine matrix key goes away. * Use each engine's own readiness tool pg_isready and mysqladmin ping are what the respective images ship for this, and the mysql image's entrypoint invokes mysqladmin itself, so it is present. Keeps 20 retries, which MySQL needs to finish initialising. * State the two-engine ceiling as a rule, not a test detail The 2038 TIMESTAMP limit binds anything written to the column, not just the sentinel dates in fixtures, and the same reasoning generalises: what the app supports is the intersection of both engines. * Let the release image connect to MySQL The published image installed only pdo_pgsql, so DB_CONNECTION=mysql failed with "could not find driver" before any query ran - the app supports MySQL but the image people actually deploy could not reach it. mysql-client mirrors the postgresql-client already present, for artisan db and dumps. * Keep "backend" a single required status check Matrixing the job split its check in two, so the "backend" context the branch protection requires was never reported and every PR sat waiting on it. The matrix is now "tests" and a small "backend" job gates on it, which keeps the required check stable however many engines the matrix grows to - and leaves the open PRs mergeable without a rebase. --------- Co-authored-by: Paulo Castellano <paulo@castellanos.llc>
2026-08-29 14:05:33 +00:00
expect(data_get($this->post->fresh()->media, '0.meta'))->toEqual([
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
'width' => 800,
'height' => 600,
'alt_text' => 'From library',
]);
});
it('attaches an existing document asset without inventing meta', function () {
$asset = Media::factory()->assets()->document()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
'original_filename' => 'brief.pdf',
'meta' => [],
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
'alt' => 'ignored for pdf',
])
->assertOk();
expect($this->post->fresh()->media)->toHaveCount(1)
->and(data_get($this->post->fresh()->media, '0.id'))->toBe($asset->id)
->and(data_get($this->post->fresh()->media, '0.type'))->toBe('document')
->and(data_get($this->post->fresh()->media, '0.meta'))->toBeNull();
});
it('does not duplicate an already attached asset', function () {
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
'alt' => 'First alt',
])
->assertOk()
->assertJsonPath('id', $this->post->id);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
'alt' => 'Replacement alt',
])
->assertOk()
->assertJsonPath('id', $this->post->id);
expect($this->post->fresh()->media)->toHaveCount(1)
->and(data_get($this->post->fresh()->media, '0.meta.alt_text'))->toBe('First alt');
});
it('does not store alt text for existing non-image assets', function () {
$asset = Media::factory()->assets()->video()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
'alt' => 'ignored for video',
])
->assertOk();
expect(data_get($this->post->fresh()->media, '0.meta.alt_text'))->toBeNull()
->and(data_get($this->post->fresh()->media, '0.meta.duration'))->not->toBeNull();
});
it('rejects existing-asset alt text over the stored maximum', function () {
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
'alt' => str_repeat('a', PostMediaRules::ALT_TEXT_MAX_LENGTH + 1),
])
->assertUnprocessable()
->assertJsonValidationErrors(['alt']);
expect($this->post->fresh()->media)->toHaveCount(0);
});
it('attaches an existing asset to a scheduled post', function () {
$this->post->update([
'status' => PostStatus::Scheduled,
'scheduled_at' => now()->addDay(),
]);
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
])
->assertOk();
expect($this->post->fresh()->media)->toHaveCount(1);
});
it('does not reveal a post from another workspace when attaching an asset', function () {
$other = Workspace::factory()->create();
$foreignPost = Post::factory()->create([
'workspace_id' => $other->id,
'user_id' => $this->user->id,
]);
$tiktok = SocialAccount::factory()->tiktok()->create([
'workspace_id' => $other->id,
]);
PostPlatform::factory()->tiktok()->create([
'post_id' => $foreignPost->id,
'social_account_id' => $tiktok->id,
'enabled' => true,
]);
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $foreignPost), [
'asset_id' => $asset->id,
])
->assertNotFound();
});
it('does not duplicate an asset when two post instances attach it', function () {
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
$first = $this->post->fresh();
$second = $this->post->fresh();
AttachExistingAsset::execute($first, $asset);
AttachExistingAsset::execute($second, $asset);
expect($this->post->fresh()->media)->toHaveCount(1);
});
it('forbids viewers from attaching an existing asset', function () {
$viewer = User::factory()->create(['account_id' => $this->user->account_id]);
$this->workspace->members()->attach($viewer->id, ['role' => Role::Viewer->value]);
$viewer->update(['current_workspace_id' => $this->workspace->id]);
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.passportToken($viewer, $this->workspace)])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
])
->assertForbidden();
expect($this->post->fresh()->media)->toHaveCount(0);
});
it('rejects an asset from another workspace', function () {
$other = Workspace::factory()->create();
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $other->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
])
->assertUnprocessable()
->assertJsonValidationErrors(['asset_id']);
expect($this->post->fresh()->media)->toHaveCount(0);
});
it('rejects attaching an existing asset when the post cannot be edited', function (PostStatus $status) {
$this->post->update(['status' => $status]);
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
])
->assertUnprocessable()
->assertJsonPath('message', PostStatusRules::editBlockedMessage());
expect($this->post->fresh()->media)->toHaveCount(0);
})->with([
PostStatus::Published,
PostStatus::PartiallyPublished,
PostStatus::Failed,
PostStatus::Publishing,
]);
it('rejects attaching via the action when the post cannot be edited', function () {
$this->post->update(['status' => PostStatus::Published]);
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
expect(fn () => AttachExistingAsset::execute($this->post, $asset))
->toThrow(ValidationException::class);
expect($this->post->fresh()->media)->toHaveCount(0);
});
it('rejects attaching via the action when the library asset was deleted', function () {
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
$stale = $asset->fresh();
$asset->delete();
expect(fn () => AttachExistingAsset::execute($this->post, $stale))
->toThrow(ValidationException::class);
expect($this->post->fresh()->media)->toHaveCount(0);
});
it('rejects an asset type the enabled platforms cannot publish', function () {
$this->socialAccount->update(['platform' => Platform::TikTok]);
$this->post->postPlatforms()->delete();
PostPlatform::factory()->tiktok()->create([
'post_id' => $this->post->id,
'social_account_id' => $this->socialAccount->id,
'enabled' => true,
]);
$asset = Media::factory()->assets()->create([
'mediable_type' => (new Workspace)->getMorphClass(),
'mediable_id' => $this->workspace->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-existing-asset', $this->post), [
'asset_id' => $asset->id,
])
->assertUnprocessable()
->assertJsonValidationErrors(['asset_id']);
expect($this->post->fresh()->media)->toHaveCount(0);
});