-
Notifications
You must be signed in to change notification settings - Fork 25
/
EmbedVideo.ts
104 lines (91 loc) · 2.44 KB
/
EmbedVideo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { URL } from "url";
import { getVideoService, videoIdProcessors } from "./config";
import { IEmbedVideoOptions, IVideoId, IVideoService } from "./interfaces";
export function embedVideoHTML(
type: string,
id: string,
options: IEmbedVideoOptions
): string {
try {
const videoId: IVideoId = readVideoId(type, id);
const videoService = getVideoService(videoId.service, options);
const url = createUrl(videoId.id, videoService, options);
let iframe = createIframe(url, id, videoService, options);
return iframe;
} catch (e) {
return `<p style="color: red">Error: ${(e as Error).message}</p>`;
}
}
export function readVideoId(type: string, id: string): IVideoId {
let videoId: IVideoId | {};
for (let processor of videoIdProcessors) {
try {
videoId = processor(id);
} catch (e) {
videoId = {};
}
if (
Object.keys(videoId).length !== 0 &&
(videoId as IVideoId).id !== null
) {
return videoId as IVideoId;
}
}
if (type === "video") {
throw new TypeError("Id could not be processed");
}
return {
id: id,
service: type.toLowerCase(),
};
}
function createUrl(
videoId: string,
videoService: IVideoService,
options: IEmbedVideoOptions
): string {
const videoUrl = videoService.embedUrl(videoId);
let url = new URL(videoUrl);
if (videoService.urlProcessing) {
url = videoService.urlProcessing(videoId, url, options);
}
return url.toString();
}
function createIframe(
url: string,
id: string,
videoService: IVideoService,
options: IEmbedVideoOptions
) {
const {
title = "",
width,
height,
containerClass,
loadingStrategy,
} = options;
let iframeNode = `
<div class="${containerClass}">
<iframe
title="${title}"
width="${width}"
height="${height}"
src="${url}"
class="embedVideo-iframe"
${options.noIframeBorder ? 'style="border:0"' : ""}
${options.iframeId ? `id="${id}"` : ""}
${
options.sandbox
? `sandbox=${options.sandbox}`
: ""
}
loading="${loadingStrategy}"
allowfullscreen
sandbox="allow-same-origin allow-scripts allow-popups"
></iframe>
</div>`;
if (videoService.additionalHTML) {
iframeNode += videoService.additionalHTML;
}
return iframeNode;
}