diff --git a/src/util/test/video.spec.ts b/src/util/test/video.spec.ts new file mode 100644 index 00000000..0063f219 --- /dev/null +++ b/src/util/test/video.spec.ts @@ -0,0 +1,33 @@ +import { VideoService } from '../video'; + +describe('VideoService', () => { + describe('getEmbedHtml', () => { + it.each([ + ['https://www.youtube.com/watch?v=dQw4w9WgXcQ', null, ''], + [ + 'https://vimeo.com/123456789', + null, + `
`, + ], + ['https://youtube.com/some/other/path', null, ``], + [ + 'https://player.vimeo.com/video/123456789', + 'My Video', + `
`, + ], + [ + 'https://player.vimeo.com/video/123456789', + null, + `
`, + ], + [ + 'https://player.vimeo.com/video/123456789', + '', + `
`, + ], + ['https://example.com/video.mp4', null, ``], + ] as const)('Returns appropriate HTML embed snippet for Video URL', (url: string, title: string | null, expectedSnippet: string) => { + expect(VideoService.getEmbedHtml(url, title)).toBe(expectedSnippet); + }); + }); +}); diff --git a/src/util/video.ts b/src/util/video.ts index 405dacec..7f1fc86c 100644 --- a/src/util/video.ts +++ b/src/util/video.ts @@ -1,5 +1,7 @@ export class VideoService { static getEmbedHtml(url: string, title: string | null) { + url = this.replacePageURLwithEmbedURL(url); + if (url.match(/youtube\.com/g)) { return ``; } else if (url.match(/player\.vimeo\.com/g)) { @@ -9,4 +11,20 @@ export class VideoService { return ``; } } + + /** + * If the user supplied a URL to view a page video in a page on youtube or vimeo, + * we replace it with the URL to the related embedabble iframe. + */ + private static replacePageURLwithEmbedURL(url: string) { + let YoutubeMatch: RegExpMatchArray | null = null; + let VimeoMatch: RegExpMatchArray | null = null; + + if ((YoutubeMatch = url.match(/youtube.com\/watch\?v=([a-zA-Z0-9]+)/))) { + url = `https://youtube\.com/embed/${YoutubeMatch[1]}`; + } else if ((VimeoMatch = url.match(/vimeo.com\/([0-9]+)/))) { + url = `https://player\.vimeo\.com/video/${VimeoMatch[1]}`; + } + return url; + } }