Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import CircularProgress from '@mui/material/CircularProgress'
import Divider from '@mui/material/Divider'
import Stack from '@mui/material/Stack'
import TextField from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
import { useTranslation } from 'next-i18next'
import { ReactElement } from 'react'
import { KeyboardEvent, ReactElement, useState } from 'react'
import { useDropzone } from 'react-dropzone'

import { useJourney } from '@core/journeys/ui/JourneyProvider'

import { useTemplateVideoUpload } from '../../../../TemplateVideoUploadProvider'
import {
extractYouTubeVideoId,
getCustomizableCardVideoBlock,
getVideoBlockDisplayTitle
} from '../../utils'
Expand Down Expand Up @@ -102,7 +105,13 @@ export function VideosSection({
}: VideosSectionProps): ReactElement {
const { t } = useTranslation('apps-journeys-admin')
const { journey } = useJourney()
const { startUpload, getUploadStatus } = useTemplateVideoUpload()
const { startUpload, startYouTubeLink, getUploadStatus } =
useTemplateVideoUpload()

const [youtubeUrl, setYoutubeUrl] = useState('')
const [youtubeUrlError, setYoutubeUrlError] = useState<string | undefined>(
undefined
)

const videoBlock = getCustomizableCardVideoBlock(journey, cardBlockId)
const videoBlockDisplayTitle =
Expand Down Expand Up @@ -130,6 +139,25 @@ export function VideosSection({
disabled: loading
})

async function handleYouTubeSubmit(): Promise<void> {
const extractedId = extractYouTubeVideoId(youtubeUrl.trim())
if (extractedId == null) {
setYoutubeUrlError(t('Please enter a valid YouTube URL'))
return
}
if (videoBlock == null) return

setYoutubeUrlError(undefined)
setYoutubeUrl('')
await startYouTubeLink(videoBlock.id, extractedId)
}
Comment on lines +150 to +153
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Preserve the URL until linking succeeds.

Line 151 clears youtubeUrl before the async link attempt completes. If the mutation fails, users lose the pasted URL and need to re-enter it.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/journeys-admin/src/components/TemplateCustomization/MultiStepForm/Screens/MediaScreen/Sections/VideosSection/VideosSection.tsx`
around lines 150 - 153, The code clears youtubeUrl (via setYoutubeUrl(''))
before awaiting the async startYouTubeLink call, which discards the user's
pasted URL if the mutation fails; change the flow in the handler that currently
calls setYoutubeUrlError(undefined); setYoutubeUrl(''); await
startYouTubeLink(videoBlock.id, extractedId) to instead clear the url only after
startYouTubeLink resolves successfully—e.g., call setYoutubeUrlError(undefined)
then await startYouTubeLink(videoBlock.id, extractedId) inside a try block and
only call setYoutubeUrl('') in the success path, and catch errors to set an
appropriate error via setYoutubeUrlError without clearing the input so the
user’s URL is preserved.


function handleYouTubeKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
if (event.key === 'Enter') {
void handleYouTubeSubmit()
}
}

return (
<Stack data-testid="VideosSection" gap={2} width="100%">
<Stack gap={2}>
Expand Down Expand Up @@ -167,6 +195,44 @@ export function VideosSection({
defaultMessage={t('Max size is 1 GB')}
errorMessage={errorMessage}
/>
<Divider>
<Typography variant="caption" color="text.secondary">
{t('or')}
</Typography>
</Divider>
<Stack gap={1}>
<Stack direction="row" gap={1} alignItems="flex-start">
<TextField
size="small"
label={t('YouTube URL')}
value={youtubeUrl}
onChange={(e) => setYoutubeUrl(e.target.value)}
onKeyDown={handleYouTubeKeyDown}
disabled={loading}
error={youtubeUrlError != null}
helperText={youtubeUrlError}
inputProps={{ 'aria-label': t('YouTube URL') }}
sx={{ flex: 1 }}
/>
<Button
size="small"
color="secondary"
variant="outlined"
disabled={loading || youtubeUrl.trim() === ''}
onClick={() => void handleYouTubeSubmit()}
aria-label={t('Set YouTube video')}
sx={{
height: 40,
borderRadius: 2,
flexShrink: 0
}}
>
<Typography variant="subtitle2" sx={{ color: 'text.secondary' }}>
{t('Set')}
</Typography>
</Button>
</Stack>
</Stack>
</Stack>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ export {
showVideosSection,
getCustomizableCardVideoBlock,
getVideoBlockDisplayTitle,
getVideoPoster
getVideoPoster,
extractYouTubeVideoId
} from './videoSectionUtils'
export {
getCustomizableMediaSteps,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ export {
getCustomizableCardVideoBlock,
showVideosSection,
getVideoBlockDisplayTitle,
getVideoPoster
getVideoPoster,
extractYouTubeVideoId
} from './videoSectionUtils'
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ import {
import { VideoBlockSource } from '../../../../../../../../__generated__/globalTypes'
import { getJourneyMedia } from '../../../../../utils/getJourneyMedia'

const YOUTUBE_ID_REGEX = /(\/|%3D|vi=|v=)([0-9A-Za-z-_]{11})([%#?&/]|$)/

/**
* Extracts an 11-character YouTube video ID from a URL.
*
* Supports standard watch URLs, youtu.be short links, shorts, and embed URLs.
* Returns null when no valid ID can be found.
*/
export function extractYouTubeVideoId(url: string): string | null {
return url.match(YOUTUBE_ID_REGEX)?.[2] ?? null
Comment on lines +8 to +17
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Restrict extraction to YouTube hosts to avoid false positives.

Line 8 currently matches IDs from non-YouTube URLs (e.g., any domain containing /XXXXXXXXXXX or v=XXXXXXXXXXX). That means invalid links can pass validation and be submitted as YouTube videos.

🔧 Proposed fix
-const YOUTUBE_ID_REGEX = /(\/|%3D|vi=|v=)([0-9A-Za-z-_]{11})([%#?&/]|$)/
+const YOUTUBE_ID_REGEX = /^[0-9A-Za-z_-]{11}$/
+const YOUTUBE_HOST_REGEX = /(^|\.)youtube\.com$|(^|\.)youtu\.be$/

 export function extractYouTubeVideoId(url: string): string | null {
-  return url.match(YOUTUBE_ID_REGEX)?.[2] ?? null
+  try {
+    const parsed = new URL(url.trim())
+    const host = parsed.hostname.toLowerCase()
+    if (!YOUTUBE_HOST_REGEX.test(host)) return null
+
+    const candidate =
+      host.endsWith('youtu.be')
+        ? parsed.pathname.split('/').filter(Boolean)[0]
+        : parsed.searchParams.get('v') ??
+          parsed.pathname.split('/').filter(Boolean).at(-1)
+
+    return candidate != null && YOUTUBE_ID_REGEX.test(candidate)
+      ? candidate
+      : null
+  } catch {
+    return null
+  }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/journeys-admin/src/components/TemplateCustomization/MultiStepForm/Screens/MediaScreen/utils/videoSectionUtils/videoSectionUtils.ts`
around lines 8 - 17, The extractYouTubeVideoId function currently uses
YOUTUBE_ID_REGEX against any string and can return false positives from
non-YouTube hosts; update extractYouTubeVideoId to first parse the input with
the URL constructor (catching invalid URLs) and verify the hostname belongs to
an allowed YouTube host (e.g., endsWith "youtube.com", equals "youtu.be", or
includes "youtube-nocookie.com" and handle "shorts."), and only then apply
YOUTUBE_ID_REGEX (or extract from pathname/search) to get the 11-character ID;
ensure non-YouTube hosts or parse failures return null and keep YOUTUBE_ID_REGEX
as the extraction pattern reference.

}

/**
* Returns the first customizable video block that belongs to the given card.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type { TemplateVideoUploadContextType } from './types'
import { MAX_VIDEO_SIZE, createInitialTask } from './types'
import { useMuxVideoProcessing } from './useMuxVideoProcessing'
import { useUploadTaskMap } from './useUploadTaskMap'
import { useYouTubeVideoLinking } from './useYouTubeVideoLinking'

const TemplateVideoUploadContext = createContext<
TemplateVideoUploadContextType | undefined
Expand Down Expand Up @@ -56,6 +57,13 @@ export function TemplateVideoUploadProvider({
activeBlocksRef
})

const { linkYouTubeVideo } = useYouTubeVideoLinking({
setUploadTasks,
updateTask,
removeTask,
activeBlocksRef
})

const [createMuxVideoUploadByFile] = useMutation(
CREATE_MUX_VIDEO_UPLOAD_BY_FILE_MUTATION
)
Expand Down Expand Up @@ -167,10 +175,11 @@ export function TemplateVideoUploadProvider({
const value = useMemo<TemplateVideoUploadContextType>(
() => ({
startUpload,
startYouTubeLink: linkYouTubeVideo,
getUploadStatus,
hasActiveUploads
}),
[startUpload, getUploadStatus, hasActiveUploads]
[startUpload, linkYouTubeVideo, getUploadStatus, hasActiveUploads]
)

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface VideoUploadState {

export interface TemplateVideoUploadContextType {
startUpload: (videoBlockId: string, file: File) => void
startYouTubeLink: (videoBlockId: string, youtubeVideoId: string) => Promise<void>
getUploadStatus: (videoBlockId: string) => VideoUploadState | null
hasActiveUploads: boolean
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { useMutation } from '@apollo/client'
import { useTranslation } from 'next-i18next'
import { useSnackbar } from 'notistack'
import { Dispatch, RefObject, SetStateAction, useCallback } from 'react'

import { useJourney } from '@core/journeys/ui/JourneyProvider'
import { GET_JOURNEY } from '@core/journeys/ui/useJourneyQuery'

import {
IdType,
VideoBlockSource
} from '../../../../../__generated__/globalTypes'
import { VIDEO_BLOCK_UPDATE } from '../../../Editor/Slider/Settings/CanvasDetails/Properties/blocks/Video/Options/VideoOptions'

import type { UploadTaskInternal } from './types'

interface UseYouTubeVideoLinkingParams {
setUploadTasks: Dispatch<SetStateAction<Map<string, UploadTaskInternal>>>
updateTask: (
videoBlockId: string,
updates: Partial<UploadTaskInternal>
) => void
removeTask: (videoBlockId: string) => void
activeBlocksRef: RefObject<Set<string>>
}

/**
* Manages persisting a YouTube video URL to a video block via VIDEO_BLOCK_UPDATE.
*
* Unlike Mux uploads there is no file transfer or polling — just a single
* mutation call. The block is marked as 'updating' for the duration so that
* `hasActiveUploads` stays true, preventing navigation away from the media screen.
*/
export function useYouTubeVideoLinking({
setUploadTasks,
updateTask,
removeTask,
activeBlocksRef
}: UseYouTubeVideoLinkingParams): {
linkYouTubeVideo: (videoBlockId: string, youtubeVideoId: string) => Promise<void>
} {
const { t } = useTranslation('apps-journeys-admin')
const { enqueueSnackbar } = useSnackbar()
const { journey } = useJourney()

const [videoBlockUpdate] = useMutation(VIDEO_BLOCK_UPDATE)

const linkYouTubeVideo = useCallback(
async (videoBlockId: string, youtubeVideoId: string) => {
if (activeBlocksRef.current.has(videoBlockId)) return
if (journey?.id == null) return

activeBlocksRef.current.add(videoBlockId)
setUploadTasks((prev) => {
const next = new Map(prev)
next.set(videoBlockId, {
videoBlockId,
status: 'updating',
progress: 0,
retryCount: 0
})
return next
})

try {
await videoBlockUpdate({
variables: {
id: videoBlockId,
input: {
videoId: youtubeVideoId,
source: VideoBlockSource.youTube
}
},
refetchQueries: [
{
query: GET_JOURNEY,
variables: {
id: journey.id,
idType: IdType.databaseId,
options: { skipRoutingFilter: true }
}
}
]
})
enqueueSnackbar(t('YouTube video set successfully'), {
variant: 'success',
autoHideDuration: 2000
})
removeTask(videoBlockId)
} catch {
enqueueSnackbar(t('Failed to set YouTube video. Please try again'), {
variant: 'error',
autoHideDuration: 2000
})
updateTask(videoBlockId, {
status: 'error',
error: 'Failed to set YouTube video. Please try again'
})
} finally {
activeBlocksRef.current.delete(videoBlockId)
}
},
[
activeBlocksRef,
journey?.id,
videoBlockUpdate,
enqueueSnackbar,
t,
setUploadTasks,
updateTask,
removeTask
]
)

return { linkYouTubeVideo }
}
Loading