|
| 1 | +import { NextRequest, NextResponse } from 'next/server'; |
| 2 | +import Mux from '@mux/mux-node'; |
| 3 | +import { start, resumeHook } from 'workflow/api'; |
| 4 | +import { |
| 5 | + moderateAndSummarize, |
| 6 | + moderationHookToken, |
| 7 | + summarizeHookToken, |
| 8 | + askQuestionsHookToken, |
| 9 | + captionHookToken, |
| 10 | +} from '../../../../workflows/process-mux-ai'; |
| 11 | +import type { RobotsJobHookPayload, CaptionHookPayload } from '../../../../types'; |
| 12 | + |
| 13 | +const webhookSignatureSecret = process.env.MUX_WEBHOOK_SIGNATURE_SECRET; |
| 14 | +const mux = new Mux(); |
| 15 | + |
| 16 | +type RobotsJobStatus = 'completed' | 'errored' | 'cancelled'; |
| 17 | + |
| 18 | +// Robots job webhook data — we only read the fields we need. Everything else is |
| 19 | +// ignored; the workflow calls `.retrieve()` for authoritative outputs rather than |
| 20 | +// trusting the webhook body shape. |
| 21 | +interface RobotsJobWebhookData { |
| 22 | + id: string; |
| 23 | + resources?: { assets: Array<{ id: string }> }; |
| 24 | + errors?: Array<{ type: string; message: string; retryable?: boolean }>; |
| 25 | +} |
| 26 | + |
| 27 | +function buildRobotsHookPayload(data: RobotsJobWebhookData, terminalStatus: RobotsJobStatus): RobotsJobHookPayload { |
| 28 | + if (terminalStatus === 'errored') { |
| 29 | + return { |
| 30 | + status: 'errored', |
| 31 | + errorMessage: data.errors?.[0]?.message ?? 'Unknown error', |
| 32 | + }; |
| 33 | + } |
| 34 | + if (terminalStatus === 'cancelled') { |
| 35 | + return { status: 'cancelled' }; |
| 36 | + } |
| 37 | + return { status: 'completed' }; |
| 38 | +} |
| 39 | + |
| 40 | +export async function POST(request: NextRequest) { |
| 41 | + // Get raw body as text (NOT json) for signature verification and parsing |
| 42 | + const rawBody = await request.text(); |
| 43 | + |
| 44 | + // Verify webhook signature (required in production, optional in development) |
| 45 | + if (webhookSignatureSecret) { |
| 46 | + // Convert headers to plain object for Mux SDK |
| 47 | + const headers: Record<string, string> = {}; |
| 48 | + request.headers.forEach((value, key) => { |
| 49 | + headers[key] = value; |
| 50 | + }); |
| 51 | + |
| 52 | + try { |
| 53 | + mux.webhooks.verifySignature(rawBody, headers, webhookSignatureSecret); |
| 54 | + } catch (e) { |
| 55 | + console.error('Error verifyWebhookSignature - is the correct signature secret set?', e); |
| 56 | + return NextResponse.json( |
| 57 | + { message: (e as Error).message }, |
| 58 | + { status: 400 } |
| 59 | + ); |
| 60 | + } |
| 61 | + } else if (process.env.NODE_ENV === 'production') { |
| 62 | + console.error('MUX_WEBHOOK_SIGNATURE_SECRET is not set — rejecting webhook in production'); |
| 63 | + return NextResponse.json( |
| 64 | + { message: 'Webhook signature verification is required in production' }, |
| 65 | + { status: 500 } |
| 66 | + ); |
| 67 | + } else { |
| 68 | + console.log('Skipping webhook sig verification because no secret is configured'); // eslint-disable-line no-console |
| 69 | + } |
| 70 | + |
| 71 | + try { |
| 72 | + // Parse JSON inside try/catch to handle malformed payloads |
| 73 | + const jsonBody = JSON.parse(rawBody); |
| 74 | + const { data, type } = jsonBody; |
| 75 | + |
| 76 | + // Handle video.asset.ready - start unified AI workflow |
| 77 | + if (type === 'video.asset.ready') { |
| 78 | + const assetId = data.id; |
| 79 | + |
| 80 | + const workflowRun = await start(moderateAndSummarize, [assetId]); |
| 81 | + |
| 82 | + return NextResponse.json({ |
| 83 | + message: 'AI workflow started', |
| 84 | + asset_id: assetId, |
| 85 | + workflow_id: workflowRun.runId |
| 86 | + }); |
| 87 | + } |
| 88 | + |
| 89 | + // Handle Robots job terminal events — resume the workflow's matching hook. |
| 90 | + // Event type form: `robots.job.<workflow>.<status>`, e.g. `robots.job.moderate.completed`. |
| 91 | + // We only care about terminal statuses; pending/processing fall through. |
| 92 | + const robotsMatch = /^robots\.job\.(moderate|summarize|ask_questions)\.(completed|errored|cancelled)$/.exec(type); |
| 93 | + if (robotsMatch) { |
| 94 | + const [, workflow, status] = robotsMatch as unknown as [string, 'moderate' | 'summarize' | 'ask_questions', RobotsJobStatus]; |
| 95 | + const jobData = data as RobotsJobWebhookData; |
| 96 | + const assetId = jobData.resources?.assets?.[0]?.id; |
| 97 | + |
| 98 | + if (!assetId) { |
| 99 | + console.log(`Robots ${workflow} webhook missing resources.assets[0].id (job ${jobData.id})`); // eslint-disable-line no-console |
| 100 | + return NextResponse.json({ message: 'Robots event missing asset id' }); |
| 101 | + } |
| 102 | + |
| 103 | + const token = |
| 104 | + workflow === 'moderate' ? moderationHookToken(assetId) |
| 105 | + : workflow === 'summarize' ? summarizeHookToken(assetId) |
| 106 | + : askQuestionsHookToken(assetId); |
| 107 | + |
| 108 | + const payload = buildRobotsHookPayload(jobData, status); |
| 109 | + |
| 110 | + try { |
| 111 | + await resumeHook<RobotsJobHookPayload>(token, payload); |
| 112 | + } catch (e) { |
| 113 | + // Hook may not exist (stale workflow run, redelivered webhook after the workflow moved on, etc.) |
| 114 | + console.log(`Could not resume robots ${workflow} hook for asset ${assetId}: ${(e as Error).message}`); // eslint-disable-line no-console |
| 115 | + } |
| 116 | + |
| 117 | + return NextResponse.json({ |
| 118 | + message: `Robots ${workflow} hook resumed (${status})`, |
| 119 | + asset_id: assetId, |
| 120 | + job_id: jobData.id, |
| 121 | + }); |
| 122 | + } |
| 123 | + |
| 124 | + // Handle video.asset.track.ready — resume caption hook |
| 125 | + if (type === 'video.asset.track.ready') { |
| 126 | + const track = data; |
| 127 | + |
| 128 | + if (track.type === 'text' && track.text_type === 'subtitles' && track.text_source === 'generated_vod') { |
| 129 | + const assetId = track.asset_id; |
| 130 | + const token = captionHookToken(assetId); |
| 131 | + |
| 132 | + try { |
| 133 | + await resumeHook<CaptionHookPayload>(token, { includeTranscript: true }); |
| 134 | + } catch (e) { |
| 135 | + // Hook may not exist yet if captions arrived before workflow reached this point |
| 136 | + console.log(`Could not resume caption hook for asset ${assetId}: ${(e as Error).message}`); // eslint-disable-line no-console |
| 137 | + } |
| 138 | + |
| 139 | + return NextResponse.json({ |
| 140 | + message: 'Caption hook resumed', |
| 141 | + asset_id: assetId, |
| 142 | + track_id: track.id, |
| 143 | + }); |
| 144 | + } |
| 145 | + |
| 146 | + return NextResponse.json({ message: 'Track type not relevant for AI processing' }); |
| 147 | + } |
| 148 | + |
| 149 | + // Handle video.asset.track.errored — resume caption hook without transcript |
| 150 | + if (type === 'video.asset.track.errored') { |
| 151 | + const track = data; |
| 152 | + |
| 153 | + if (track.type === 'text' && track.text_type === 'subtitles' && track.text_source === 'generated_vod') { |
| 154 | + const assetId = track.asset_id; |
| 155 | + const errorMessages: string[] = track.error?.messages || []; |
| 156 | + const token = captionHookToken(assetId); |
| 157 | + |
| 158 | + const isExpectedError = errorMessages.includes('Asset does not have an audio track') || |
| 159 | + errorMessages.includes('Failed to generate caption track'); |
| 160 | + |
| 161 | + if (isExpectedError) { |
| 162 | + console.log(`Track errored for asset ${assetId} (${errorMessages.join(', ')}), resuming hook without transcript`); // eslint-disable-line no-console |
| 163 | + } else { |
| 164 | + console.log(`Track errored for asset ${assetId} with unhandled error: ${errorMessages.join(', ')}`); // eslint-disable-line no-console |
| 165 | + } |
| 166 | + |
| 167 | + try { |
| 168 | + await resumeHook<CaptionHookPayload>(token, { includeTranscript: false }); |
| 169 | + } catch (e) { |
| 170 | + console.log(`Could not resume caption hook for asset ${assetId}: ${(e as Error).message}`); // eslint-disable-line no-console |
| 171 | + } |
| 172 | + |
| 173 | + return NextResponse.json({ |
| 174 | + message: 'Caption hook resumed (track errored)', |
| 175 | + asset_id: assetId, |
| 176 | + track_id: track.id, |
| 177 | + }); |
| 178 | + } |
| 179 | + |
| 180 | + return NextResponse.json({ message: 'Track type not relevant for AI processing' }); |
| 181 | + } |
| 182 | + |
| 183 | + // Return 200 for unhandled event types to prevent Mux from retrying |
| 184 | + return NextResponse.json({ message: 'Event type not handled' }); |
| 185 | + } catch (e) { |
| 186 | + console.error('Request error', e); // eslint-disable-line no-console |
| 187 | + return NextResponse.json({ error: 'Error handling webhook' }, { status: 500 }); |
| 188 | + } |
| 189 | +} |
0 commit comments