Skip to content

Commit a33c497

Browse files
RuBiCKclaudeandrasbacsai
authored
feat(api): video upload and per-target format in the public API (#196)
* feat(api): video upload and per-target format in the public API Add the presigned video upload to /api/v1, reusing the StoresPresignedVideo handshake the web composer already uses: - POST /api/v1/media/video/upload-url returns a signed URL (absolute) and a server-generated key under the API key's workspace tmp prefix. - POST /api/v1/media/video registers the uploaded object (key prefix check, size ceiling, MP4 sniff) and returns the same shape as POST /api/v1/media. Both sit in the write-scoped group next to POST /media and authorize create on Post like the image upload. POST and PATCH /api/v1/posts now accept an optional targets[].format (feed/reels/story), validated against PostFormat and the formats the target's platform offers (PostFormat::forPlatform), and persisted on the target. createDraft now honours formats carried by DraftData. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(api): validate post target formats in a single account lookup --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com>
1 parent 4ede2be commit a33c497

8 files changed

Lines changed: 403 additions & 13 deletions

File tree

‎app/Http/Controllers/Api/V1/MediaController.php‎

Lines changed: 62 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace App\Http\Controllers\Api\V1;
66

7+
use App\Http\Controllers\Concerns\StoresPresignedVideo;
78
use App\Http\Controllers\Controller;
89
use App\Models\Post;
910
use App\Models\PostMedia;
@@ -15,6 +16,8 @@
1516

1617
class MediaController extends Controller
1718
{
19+
use StoresPresignedVideo;
20+
1821
public function store(Request $request, MediaStorageService $media): JsonResponse
1922
{
2023
$this->authorize('create', Post::class);
@@ -36,13 +39,54 @@ public function store(Request $request, MediaStorageService $media): JsonRespons
3639
abort(422, $e->getMessage());
3740
}
3841

39-
return response()->json([
40-
'id' => $stored->id,
41-
'mime' => $stored->mime,
42-
'width' => $stored->width,
43-
'height' => $stored->height,
44-
'alt_text' => $stored->alt_text,
45-
], 201);
42+
return $this->createdMedia($stored);
43+
}
44+
45+
/**
46+
* Request a video upload URL.
47+
*
48+
* Step 1 of the video upload: returns a short-lived (15 min) signed URL and a
49+
* server-generated `key`. `PUT` the raw MP4 bytes to `url` with the returned
50+
* `headers`, then register the upload with `POST /media/video`.
51+
*/
52+
public function videoUploadUrl(Request $request): JsonResponse
53+
{
54+
$this->authorize('create', Post::class);
55+
56+
$request->validate([
57+
'content_type' => ['required', 'string', 'in:video/mp4'],
58+
]);
59+
60+
$target = $this->videoUploadTarget((string) Context::get('workspace_id'));
61+
62+
// On a local disk the signed URL is relative to the instance; API clients
63+
// are not on the page's origin, so hand them an absolute one.
64+
return response()->json([...$target, 'url' => url($target['url'])]);
65+
}
66+
67+
/**
68+
* Register an uploaded video.
69+
*
70+
* Step 2 of the video upload: confirms the object `PUT` to the signed URL,
71+
* checks it is an MP4 under the size ceiling, and adds it to the media
72+
* library. Returns the same shape as `POST /media`.
73+
*/
74+
public function storeVideo(Request $request): JsonResponse
75+
{
76+
$this->authorize('create', Post::class);
77+
78+
$validated = $request->validate([
79+
'key' => ['required', 'string'],
80+
'duration_seconds' => ['required', 'integer', 'min:1'],
81+
'width' => ['required', 'integer', 'min:1'],
82+
'height' => ['required', 'integer', 'min:1'],
83+
'alt_text' => ['nullable', 'string', 'max:1000'],
84+
]);
85+
86+
$workspaceId = (string) Context::get('workspace_id');
87+
$stored = $this->persistUploadedVideo($validated, $workspaceId, ['workspace_id' => $workspaceId, 'via' => 'api']);
88+
89+
return $this->createdMedia($stored);
4690
}
4791

4892
public function destroy(string $mediaId): JsonResponse
@@ -54,4 +98,15 @@ public function destroy(string $mediaId): JsonResponse
5498

5599
return response()->json(['deleted' => true, 'id' => $mediaId]);
56100
}
101+
102+
private function createdMedia(PostMedia $media): JsonResponse
103+
{
104+
return response()->json([
105+
'id' => $media->id,
106+
'mime' => $media->mime,
107+
'width' => $media->width,
108+
'height' => $media->height,
109+
'alt_text' => $media->alt_text,
110+
], 201);
111+
}
57112
}

‎app/Http/Controllers/Api/V1/PostsController.php‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@
55
namespace App\Http\Controllers\Api\V1;
66

77
use App\Dto\Post\DraftData;
8+
use App\Enums\PostFormat;
89
use App\Enums\PostStatus;
910
use App\Http\Controllers\Api\V1\Concerns\ResolvesWorkspacePost;
1011
use App\Http\Controllers\Controller;
1112
use App\Jobs\DeletePostTarget;
13+
use App\Models\ConnectedAccount;
1214
use App\Models\Post;
1315
use App\Models\PostTarget;
1416
use App\Models\User;
@@ -21,6 +23,7 @@
2123
use Illuminate\Http\Request;
2224
use Illuminate\Support\Facades\Context;
2325
use Illuminate\Validation\Rule;
26+
use Illuminate\Validation\ValidationException;
2427

2528
class PostsController extends Controller
2629
{
@@ -71,9 +74,14 @@ public function store(Request $request, DraftService $drafts): JsonResponse
7174
'destination' => ['required', 'array'],
7275
'destination.kind' => ['required', Rule::in(['all', 'set', 'account'])],
7376
'destination.id' => ['nullable', 'string', 'required_if:destination.kind,set,account'],
77+
'targets' => ['array'],
78+
'targets.*.connected_account_id' => ['required', 'string'],
79+
'targets.*.format' => ['nullable', Rule::enum(PostFormat::class)],
7480
'auto_repost' => ['sometimes', 'nullable', 'boolean'],
7581
]);
7682

83+
$this->ensureFormatsSupported($validated['targets'] ?? []);
84+
7785
/** @var User $user */
7886
$user = $request->user();
7987

@@ -88,6 +96,7 @@ public function store(Request $request, DraftService $drafts): JsonResponse
8896
$segments,
8997
$validated['mentions'] ?? [],
9098
$validated['auto_repost'] ?? null,
99+
DraftData::fromArray($validated),
91100
);
92101

93102
return response()->json(['post' => PostView::make($post->fresh(['targets.account', 'media']))], 201);
@@ -116,6 +125,7 @@ public function update(Request $request, string $id, DraftService $drafts): Json
116125
'targets' => ['array'],
117126
'targets.*.connected_account_id' => ['required', 'string'],
118127
'targets.*.auto_split' => ['boolean'],
128+
'targets.*.format' => ['nullable', Rule::enum(PostFormat::class)],
119129
'targets.*.content_override' => ['nullable', 'array'],
120130
'targets.*.content_override.text' => ['nullable', 'string'],
121131
'targets.*.content_override.media_ids' => ['array'],
@@ -126,6 +136,8 @@ public function update(Request $request, string $id, DraftService $drafts): Json
126136
'expected_updated_at' => ['nullable', 'string'],
127137
]);
128138

139+
$this->ensureFormatsSupported($validated['targets'] ?? []);
140+
129141
try {
130142
$updated = $drafts->updateDraft($model, DraftData::fromArray($validated));
131143
} catch (PostStaleWriteException $e) {
@@ -158,4 +170,45 @@ public function destroy(string $id): JsonResponse
158170

159171
return response()->json(['deleted' => true, 'remote' => true, 'message' => 'Remote deletion queued for published targets.']);
160172
}
173+
174+
/**
175+
* Reject a per-target `format` the target's platform does not offer (e.g.
176+
* Reels on X) — the same set the web composer exposes via PostFormat::forPlatform.
177+
*
178+
* @param array<int, array{connected_account_id: string, format?: string|null}> $targets
179+
*
180+
* @throws ValidationException
181+
*/
182+
private function ensureFormatsSupported(array $targets): void
183+
{
184+
$accounts = ConnectedAccount::query()
185+
->whereKey(array_column($targets, 'connected_account_id'))
186+
->get()
187+
->keyBy('id');
188+
$errors = [];
189+
190+
foreach ($targets as $index => $target) {
191+
$format = PostFormat::tryFrom((string) ($target['format'] ?? ''));
192+
193+
if (! $format instanceof PostFormat) {
194+
continue;
195+
}
196+
197+
$account = $accounts->get($target['connected_account_id']);
198+
199+
if (! $account instanceof ConnectedAccount) {
200+
$errors["targets.{$index}.connected_account_id"] = 'No connected account with that id exists in this workspace.';
201+
202+
continue;
203+
}
204+
205+
if (! in_array($format, PostFormat::forPlatform($account->platform), true)) {
206+
$errors["targets.{$index}.format"] = "The {$format->value} format is not available on {$account->platform->value}.";
207+
}
208+
}
209+
210+
if ($errors !== []) {
211+
throw ValidationException::withMessages($errors);
212+
}
213+
}
161214
}

‎app/Http/Controllers/Concerns/StoresPresignedVideo.php‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,17 @@ trait StoresPresignedVideo
2828
* The storage key is generated server-side — never trusted from the client.
2929
*/
3030
private function signVideoUpload(string $workspaceId): JsonResponse
31+
{
32+
return response()->json($this->videoUploadTarget($workspaceId));
33+
}
34+
35+
/**
36+
* The sign step without the response shape, so each surface (the web
37+
* composer, the public API) can render the upload target its own way.
38+
*
39+
* @return array{key: string, url: string, headers: array<string, string>}
40+
*/
41+
private function videoUploadTarget(string $workspaceId): array
3142
{
3243
$key = 'tmp/media/'.$workspaceId.'/'.Str::uuid().'.mp4';
3344

@@ -36,11 +47,11 @@ private function signVideoUpload(string $workspaceId): JsonResponse
3647
now()->addMinutes(15),
3748
);
3849

39-
return response()->json([
50+
return [
4051
'key' => $key,
4152
'url' => $uploadUrl,
4253
'headers' => $headers,
43-
]);
54+
];
4455
}
4556

4657
/**
@@ -51,6 +62,20 @@ private function signVideoUpload(string $workspaceId): JsonResponse
5162
* @param array<string, mixed> $logContext Identifies the owner in rejection logs.
5263
*/
5364
private function storeUploadedVideo(array $validated, string $workspaceId, array $logContext = []): JsonResponse
65+
{
66+
$media = $this->persistUploadedVideo($validated, $workspaceId, $logContext);
67+
68+
return response()->json(['media' => $media->toView()], 201);
69+
}
70+
71+
/**
72+
* The confirm step without the response shape, so each surface (the web
73+
* composer, the public API) can render the stored media its own way.
74+
*
75+
* @param array<string, mixed> $validated
76+
* @param array<string, mixed> $logContext Identifies the owner in rejection logs.
77+
*/
78+
private function persistUploadedVideo(array $validated, string $workspaceId, array $logContext = []): PostMedia
5479
{
5580
$key = (string) $validated['key'];
5681
$disk = FileStorage::diskName();
@@ -82,7 +107,7 @@ private function storeUploadedVideo(array $validated, string $workspaceId, array
82107
$final = 'media/'.$workspaceId.'/'.Str::uuid().'.mp4';
83108
Storage::disk($disk)->move($key, $final);
84109

85-
$media = PostMedia::create([
110+
return PostMedia::create([
86111
'workspace_id' => $workspaceId,
87112
'post_id' => null,
88113
'disk' => $disk,
@@ -96,8 +121,6 @@ private function storeUploadedVideo(array $validated, string $workspaceId, array
96121
'alt_text' => $validated['alt_text'] ?? null,
97122
'position' => 0,
98123
]);
99-
100-
return response()->json(['media' => $media->toView()], 201);
101124
}
102125

103126
/**

‎app/Services/Posts/DraftService.php‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,13 @@ public function createDraft(string $workspaceId, User $author, array $destinatio
5757
// Pass the DraftData so the created targets carry the thread's
5858
// segment_breaks from the first save (placements settle on the next
5959
// PUT once their media is attached).
60-
$this->syncTargets($post, $accountIds, $segments, [], [], $post->mentions ?? [], [], $data);
60+
$formatByAccount = [];
61+
foreach ($accountIds as $accountId) {
62+
if ($data instanceof DraftData && $data->hasFormatFor($accountId)) {
63+
$formatByAccount[$accountId] = $data->formatFor($accountId);
64+
}
65+
}
66+
$this->syncTargets($post, $accountIds, $segments, [], [], $post->mentions ?? [], $formatByAccount, $data);
6167

6268
return $post->load('targets');
6369
});

‎routes/api.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@
3939
Route::delete('posts/{id}/shares/{shareId}', [SharesController::class, 'destroy']);
4040

4141
Route::post('media', [MediaController::class, 'store']);
42+
Route::post('media/video/upload-url', [MediaController::class, 'videoUploadUrl']);
43+
Route::post('media/video', [MediaController::class, 'storeVideo']);
4244
Route::delete('media/{mediaId}', [MediaController::class, 'destroy']);
4345

4446
Route::post('account-sets', [AccountSetsController::class, 'store']);

0 commit comments

Comments
 (0)