/
VideoResolver.ts
55 lines (50 loc) · 1.89 KB
/
VideoResolver.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
/**
* VideoResolver provides abstraction of loading feature for video element.
* Despite the other resolvers, VideoResolver doesn't extends ExternalResourceResolver since
* that element contains frame operation also and it affects frame control in each function of grimoire using.
* @param {string} path [description]
* @return {Promise<HTMLVideoElement>} [description]
*/
export class VideoResolver {
public static defaultCORSConfig = "anonymous";
/**
* Cors config resolvers.
* If all of resolvers returns null, defaultCORSConfig will be used.
*/
public static corsResolvers: ((path: string) => string)[] = [];
public resolve(path: string): Promise<HTMLVideoElement> {
return new Promise<HTMLVideoElement>((resolve, reject) => {
const video = document.createElement("video");
video.crossOrigin = this._getCORSConfig(path);
video.preload = "auto";
video.addEventListener("canplay", () => {
resolve(video);
});
video.addEventListener("canplaythrough", () => {
resolve(video);
});
video.onerror = (e) => {
reject(`Error has been occured during loading "${path}"\n${e}`);
};
video.src = path;
video.load();
if (video.readyState > 3) {
resolve(video);
}
});
}
private _getCORSConfig(path: string): string {
let corsConfig = null;
for (let i = 0; i < VideoResolver.corsResolvers.length; i++) {
corsConfig = VideoResolver.corsResolvers[i](path);
if (corsConfig !== null) {
break;
}
}
if (corsConfig === null) {
corsConfig = VideoResolver.defaultCORSConfig;
}
return corsConfig;
}
}
export default new VideoResolver();