import { NextApiRequest , NextApiResponse } from 'next' ; import Mux from '@mux/mux-node' ; import { buffer } from 'micro' ; import { sendSlackAssetReady , sendSlackAutoDeleteMessage } from '../../../lib/slack-notifier' ; import { getScores as moderationGoogle } from '../../../lib/moderation-google' ; import { getScores as moderationHive } from '../../../lib/moderation-hive' ; import { autoDelete } from '../../../lib/moderation-action' ; const webhookSignatureSecret = process . env . MUX_WEBHOOK_SIGNATURE_SECRET ; const verifyWebhookSignature = ( rawBody , req ) => { if ( webhookSignatureSecret ) { Mux . Webhooks . verifyHeader ( rawBody , req . headers [ 'mux-signature' ] as string , webhookSignatureSecret ) ; } else { console . log ( 'Skipping webhook sig verification because no secret is configured' ) ; } return true ; } ; export const config = { api : { bodyParser : false , } , } ; export default async function muxWebhookHandler ( req , res ) { const { method } = req ; switch ( method ) { case 'POST' : { const rawBody = ( await buffer ( req ) ) . toString ( ) ; try { verifyWebhookSignature ( rawBody , req ) ; } catch ( e ) { console . error ( 'Error verifyWebhookSignature - is the correct signature secret set?' , e ) ; res . status ( 400 ) . json ( { message : e . message } ) ; return ; } const jsonBody = JSON . parse ( rawBody ) ; const { data , type } = jsonBody ; if ( type !== 'video.asset.ready' ) { res . json ( { message : 'thanks Mux' } ) ; return ; } try { const assetId = data . id ; const playbackId = data . playback_ids && data . playback_ids [ 0 ] && data . playback_ids [ 0 ] . id ; const duration = data . duration ; const googleScores = await moderationGoogle ( { playbackId , duration } ) ; const hiveScores = await moderationHive ( { playbackId , duration } ) ; const didAutoDelete = hiveScores ? ( await autoDelete ( { assetId , playbackId , hiveScores } ) ) : false ; if ( didAutoDelete ) { await sendSlackAutoDeleteMessage ( { assetId , duration , hiveScores } ) ; res . json ( { message : 'thanks Mux, I autodeleted this asset because it was bad' } ) ; } else { await sendSlackAssetReady ( { assetId , playbackId , duration , googleScores , hiveScores , } ) ; res . json ( { message : 'thanks Mux, I notified myself about this' } ) ; } } catch ( e ) { res . statusCode = 500 ; console . error ( 'Request error' , e ) ; res . json ( { error : 'Error handling webhook' } ) ; } break ; } default : res . setHeader ( 'Allow' , [ 'POST' ] ) ; res . status ( 405 ) . end ( `Method ${ method } Not Allowed` ) ; } }