ThumbnailGenerationHandler (#40): generates thumbnail candidates via StabilityAI, one per style (default: two contrasting styles) — all stored as assets on the same step, so the existing approval UI's "show every asset on this step side by side" behavior is the A/B comparison the task calls for, no extra UI needed. MetadataGenerationHandler (#41): SEO title/description/tags/hashtags from the project's script via OpenAI in JSON mode, same pattern as StoryboardHandler. YoutubePublishHandler (#42): real OAuth2 + YouTube Data API v3 resumable upload (token refresh -> init session -> PUT video bytes), supporting scheduling via publishAt (forces privacyStatus=private per YouTube's own constraint). Reuses the AiProvider table for credentials (provider='youtube', api_key=refresh_token, config=client_id/secret) rather than a new table — added 'youtube' to AiProvider::PROVIDERS. Does not cover analytics retrieval: that's an ongoing query against a published video, not a one-shot publish action, so it doesn't fit the per-video step model at all. All 8 WorkflowStep::TYPES now have real handlers, so the "unhandled type" test fixtures (which used real-but-not-yet-implemented types) would go stale every time a new module lands — switched them to fabricated type strings so they stay meaningful regardless of what gets built next. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\VideoWorkflow\StepHandlers;
|
||||
|
||||
use App\Models\AiProvider;
|
||||
use App\Models\WorkflowStep;
|
||||
use App\Support\AiProviders\AiGenerationException;
|
||||
use App\Support\AiProviders\AiProviderManager;
|
||||
use App\Support\AssetStorage\AssetStorage;
|
||||
use App\Support\VideoWorkflow\WorkflowEngine;
|
||||
|
||||
/**
|
||||
* Generates SEO-optimized title/description/tags/hashtags from the
|
||||
* project's script via an OpenAI-backed AiProvider in JSON mode.
|
||||
*/
|
||||
class MetadataGenerationHandler implements StepHandler
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AiProviderManager $aiProviders,
|
||||
private readonly AssetStorage $assets,
|
||||
) {}
|
||||
|
||||
public function type(): string
|
||||
{
|
||||
return 'metadata_generation';
|
||||
}
|
||||
|
||||
public function handle(WorkflowStep $step, WorkflowEngine $engine): void
|
||||
{
|
||||
$provider = AiProvider::query()->where('provider', 'openai')->where('is_active', true)->first();
|
||||
|
||||
if (! $provider) {
|
||||
$engine->failStep($step, 'No active OpenAI provider configured.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$script = $this->resolveScript($step);
|
||||
|
||||
if (! $script) {
|
||||
$engine->failStep($step, 'No script available to generate metadata from — complete a script_generation step first.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $this->aiProviders->generate($provider, $this->buildPrompt($script), ['json_mode' => true]);
|
||||
} catch (AiGenerationException $e) {
|
||||
$engine->failStep($step, $e->getMessage());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$decoded = json_decode($result->content, true);
|
||||
|
||||
if (! is_array($decoded) || empty($decoded['title']) || empty($decoded['description'])) {
|
||||
$engine->failStep($step, 'AI provider returned unusable metadata: missing title/description.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$decoded += ['tags' => [], 'hashtags' => []];
|
||||
|
||||
$asset = $this->assets->store(
|
||||
$step->videoProject,
|
||||
'other',
|
||||
json_encode($decoded, JSON_PRETTY_PRINT),
|
||||
'json',
|
||||
step: $step,
|
||||
mimeType: 'application/json',
|
||||
metadata: ['kind' => 'metadata'],
|
||||
);
|
||||
|
||||
$engine->completeStep($step, [
|
||||
'asset_id' => $asset->id,
|
||||
'title' => $decoded['title'],
|
||||
]);
|
||||
}
|
||||
|
||||
private function resolveScript(WorkflowStep $step): ?string
|
||||
{
|
||||
$input = $step->input ?? [];
|
||||
|
||||
if (! empty($input['script'])) {
|
||||
return $input['script'];
|
||||
}
|
||||
|
||||
$scriptAsset = $step->videoProject->assets()
|
||||
->where('type', 'script')
|
||||
->orderByDesc('version')
|
||||
->first();
|
||||
|
||||
return $scriptAsset ? $this->assets->contents($scriptAsset) : null;
|
||||
}
|
||||
|
||||
private function buildPrompt(string $script): string
|
||||
{
|
||||
return "Based on the following YouTube video script, generate SEO-optimized metadata.\n\n"
|
||||
."Script:\n{$script}\n\n"
|
||||
.'Respond with JSON only, in exactly this shape: '
|
||||
.'{"title": "...", "description": "...", "tags": ["...", "..."], "hashtags": ["#...", "#..."]}. '
|
||||
.'Title must be under 100 characters. Description should be 2-4 paragraphs with a natural, '
|
||||
.'keyword-rich summary. Provide 10-15 tags and 3-5 hashtags.';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\VideoWorkflow\StepHandlers;
|
||||
|
||||
use App\Models\AiProvider;
|
||||
use App\Models\VideoProject;
|
||||
use App\Models\WorkflowStep;
|
||||
use App\Support\AiProviders\AiGenerationException;
|
||||
use App\Support\AiProviders\AiProviderManager;
|
||||
use App\Support\AssetStorage\AssetStorage;
|
||||
use App\Support\VideoWorkflow\WorkflowEngine;
|
||||
|
||||
/**
|
||||
* Generates thumbnail candidates via a StabilityAI-backed AiProvider. One
|
||||
* variant per style in step.input.styles (default: two contrasting styles),
|
||||
* all stored as assets on the same step — the approval UI already shows
|
||||
* every asset on an awaiting_approval step side by side, so this is the
|
||||
* A/B comparison the task calls for, with no extra UI needed.
|
||||
*/
|
||||
class ThumbnailGenerationHandler implements StepHandler
|
||||
{
|
||||
private const DEFAULT_STYLES = ['vibrant and colorful', 'minimalist and clean'];
|
||||
|
||||
public function __construct(
|
||||
private readonly AiProviderManager $aiProviders,
|
||||
private readonly AssetStorage $assets,
|
||||
) {}
|
||||
|
||||
public function type(): string
|
||||
{
|
||||
return 'thumbnail_generation';
|
||||
}
|
||||
|
||||
public function handle(WorkflowStep $step, WorkflowEngine $engine): void
|
||||
{
|
||||
$provider = AiProvider::query()->where('provider', 'stability_ai')->where('is_active', true)->first();
|
||||
|
||||
if (! $provider) {
|
||||
$engine->failStep($step, 'No active StabilityAI provider configured.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$input = $step->input ?? [];
|
||||
$basePrompt = $input['prompt'] ?? $this->defaultPrompt($step->videoProject);
|
||||
$styles = $input['styles'] ?? self::DEFAULT_STYLES;
|
||||
|
||||
$assetIds = [];
|
||||
|
||||
foreach (array_values($styles) as $i => $style) {
|
||||
$prompt = "{$basePrompt}. Eye-catching YouTube thumbnail, bold, high contrast, {$style}.";
|
||||
|
||||
try {
|
||||
$result = $this->aiProviders->generate($provider, $prompt);
|
||||
} catch (AiGenerationException $e) {
|
||||
$engine->failStep($step, 'variant '.($i + 1).": {$e->getMessage()}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$extension = str($result->contentType)->after('image/')->toString() ?: 'png';
|
||||
|
||||
$asset = $this->assets->store(
|
||||
$step->videoProject,
|
||||
'image',
|
||||
$result->content,
|
||||
$extension,
|
||||
step: $step,
|
||||
mimeType: $result->contentType,
|
||||
metadata: ['kind' => 'thumbnail', 'variant' => $i + 1, 'style' => $style],
|
||||
);
|
||||
|
||||
$assetIds[] = $asset->id;
|
||||
}
|
||||
|
||||
$engine->completeStep($step, [
|
||||
'asset_ids' => $assetIds,
|
||||
'variant_count' => count($assetIds),
|
||||
]);
|
||||
}
|
||||
|
||||
private function defaultPrompt(VideoProject $project): string
|
||||
{
|
||||
return trim(($project->title ?? '').'. '.($project->description ?? ''));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\VideoWorkflow\StepHandlers;
|
||||
|
||||
use App\Models\AiProvider;
|
||||
use App\Models\WorkflowStep;
|
||||
use App\Support\AssetStorage\AssetStorage;
|
||||
use App\Support\VideoWorkflow\WorkflowEngine;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Uploads the project's finished video to YouTube via the Data API v3's
|
||||
* resumable upload protocol, using OAuth2 credentials stored as an
|
||||
* AiProvider (provider='youtube'; api_key is a refresh_token, config holds
|
||||
* client_id/client_secret — see AiProvider::PROVIDERS).
|
||||
*
|
||||
* Supports scheduling (step.input.publish_at sets status.publishAt, which
|
||||
* requires privacyStatus=private per YouTube's API). Does NOT cover
|
||||
* analytics retrieval — that's an ongoing query against a published
|
||||
* video, not a one-shot publish action, so it doesn't fit this
|
||||
* once-per-video step model. Would need a separate service/command.
|
||||
*/
|
||||
class YoutubePublishHandler implements StepHandler
|
||||
{
|
||||
public function __construct(private readonly AssetStorage $assets) {}
|
||||
|
||||
public function type(): string
|
||||
{
|
||||
return 'youtube_publish';
|
||||
}
|
||||
|
||||
public function handle(WorkflowStep $step, WorkflowEngine $engine): void
|
||||
{
|
||||
$credential = AiProvider::query()->where('provider', 'youtube')->where('is_active', true)->first();
|
||||
|
||||
if (! $credential) {
|
||||
$engine->failStep($step, 'No active YouTube credential configured.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$videoAsset = $step->videoProject->assets()->where('type', 'video')->orderByDesc('version')->first();
|
||||
|
||||
if (! $videoAsset) {
|
||||
$engine->failStep($step, 'No finished video available — complete a video_editing step first.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$accessToken = $this->refreshAccessToken($credential);
|
||||
} catch (RuntimeException|ConnectionException $e) {
|
||||
$engine->failStep($step, "could not refresh YouTube access token: {$e->getMessage()}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$metadata = $this->resolveMetadata($step);
|
||||
$input = $step->input ?? [];
|
||||
$publishAt = $input['publish_at'] ?? null;
|
||||
|
||||
$snippet = [
|
||||
'title' => $metadata['title'] ?? $step->videoProject->title,
|
||||
'description' => $metadata['description'] ?? ($step->videoProject->description ?? ''),
|
||||
'tags' => $metadata['tags'] ?? [],
|
||||
];
|
||||
$status = array_filter([
|
||||
'privacyStatus' => $publishAt ? 'private' : ($input['privacy_status'] ?? 'private'),
|
||||
'publishAt' => $publishAt,
|
||||
]);
|
||||
|
||||
$videoBytes = $this->assets->contents($videoAsset);
|
||||
|
||||
try {
|
||||
$initResponse = Http::withToken($accessToken)
|
||||
->withHeaders([
|
||||
'X-Upload-Content-Type' => 'video/mp4',
|
||||
'X-Upload-Content-Length' => (string) strlen($videoBytes),
|
||||
])
|
||||
->post('https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status', [
|
||||
'snippet' => $snippet,
|
||||
'status' => $status,
|
||||
]);
|
||||
} catch (ConnectionException $e) {
|
||||
$engine->failStep($step, "could not connect to YouTube: {$e->getMessage()}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($initResponse->failed()) {
|
||||
$engine->failStep($step, $initResponse->json('error.message') ?? 'unexpected response from YouTube while starting the upload');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$uploadUrl = $initResponse->header('Location');
|
||||
|
||||
if (! $uploadUrl) {
|
||||
$engine->failStep($step, 'unexpected response from YouTube: missing upload session location');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$uploadResponse = Http::withToken($accessToken)
|
||||
->withBody($videoBytes, 'video/mp4')
|
||||
->put($uploadUrl);
|
||||
} catch (ConnectionException $e) {
|
||||
$engine->failStep($step, "could not upload video to YouTube: {$e->getMessage()}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($uploadResponse->failed()) {
|
||||
$engine->failStep($step, $uploadResponse->json('error.message') ?? 'unexpected response from YouTube while uploading the video');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$videoId = $uploadResponse->json('id');
|
||||
|
||||
if (! $videoId) {
|
||||
$engine->failStep($step, 'unexpected response from YouTube: missing video id');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$engine->completeStep($step, [
|
||||
'youtube_video_id' => $videoId,
|
||||
'youtube_url' => "https://www.youtube.com/watch?v={$videoId}",
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws RuntimeException|ConnectionException
|
||||
*/
|
||||
private function refreshAccessToken(AiProvider $credential): string
|
||||
{
|
||||
$config = $credential->config ?? [];
|
||||
|
||||
$response = Http::asForm()->post('https://oauth2.googleapis.com/token', [
|
||||
'client_id' => $config['client_id'] ?? null,
|
||||
'client_secret' => $config['client_secret'] ?? null,
|
||||
'refresh_token' => $credential->api_key,
|
||||
'grant_type' => 'refresh_token',
|
||||
]);
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new RuntimeException($response->json('error_description') ?? 'token refresh failed');
|
||||
}
|
||||
|
||||
$token = $response->json('access_token');
|
||||
|
||||
if (! $token) {
|
||||
throw new RuntimeException('no access_token in refresh response');
|
||||
}
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function resolveMetadata(WorkflowStep $step): array
|
||||
{
|
||||
$input = $step->input ?? [];
|
||||
|
||||
if (! empty($input['title']) || ! empty($input['description'])) {
|
||||
return $input;
|
||||
}
|
||||
|
||||
$metaAsset = $step->videoProject->assets()
|
||||
->where('type', 'other')
|
||||
->whereJsonContains('metadata->kind', 'metadata')
|
||||
->orderByDesc('version')
|
||||
->first();
|
||||
|
||||
if (! $metaAsset) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return json_decode($this->assets->contents($metaAsset), true) ?? [];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user