-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
76 lines (73 loc) · 2.28 KB
/
index.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
export const moduleName = 'toWebVTT';
/**
* @param blob
* @param readAs
* @returns Promise<ArrayBuffer>
*/
const blobToBufferOrString = (blob: Blob, readAs: 'string' | 'buffer'): Promise<Uint8Array | String> =>
new Promise((resolve, reject) => {
const reader = new FileReader();
/**
* @param event
*/
const loadedCb = (event: Event) => {
const buf = (event.target as any).result;
reader.removeEventListener('loadend', loadedCb);
resolve(readAs !== 'string' ? new Uint8Array(buf) : buf);
};
const errorCb = () => {
reader.removeEventListener('error', errorCb);
reject(new Error(`${moduleName}: Error while reading the Blob object`));
};
reader.addEventListener('loadend', loadedCb);
reader.addEventListener('error', errorCb);
if (readAs !== 'string') {
reader.readAsArrayBuffer(blob);
} else {
reader.readAsText(blob);
}
});
/**
* @param text
* @returns ObjectURL
*/
const blobToURL = (text: string): string => URL
.createObjectURL(new Blob([text], { type: 'text/vtt' }));
/**
* @param utf8str
* @returns string
*/
const toVTT = (utf8str: string) => utf8str
.replace(/\{\\([ibu])\}/g, '</$1>')
.replace(/\{\\([ibu])1\}/g, '<$1>')
.replace(/\{([ibu])\}/g, '<$1>')
.replace(/\{\/([ibu])\}/g, '</$1>')
.replace(/(\d\d:\d\d:\d\d),(\d\d\d)/g, '$1.$2')
.concat('\r\n\r\n');
/**
* @param resource
* @returns Promise<string>
*/
const toWebVTT = async (resource: Blob): Promise<string> => {
if (!(FileReader)) {
throw (new Error(`${moduleName}: No FileReader constructor found`));
}
if (!TextDecoder) {
throw (new Error(`${moduleName}: No TextDecoder constructor found`));
}
if (!(resource instanceof Blob)) {
throw new Error(`${moduleName}: Expecting resource to be a Blob but something else found.`);
}
let text;
const vttString = 'WEBVTT FILE\r\n\r\n'; // leading text
try {
const buffer = await blobToBufferOrString(resource, 'string');
text = vttString.concat(toVTT(buffer as string));
} catch (e) {
const buffer = await blobToBufferOrString(resource, 'buffer');
const decode = new TextDecoder('utf-8').decode(buffer as Uint8Array);
text = vttString.concat(toVTT(decode));
}
return Promise.resolve(blobToURL(text));
};
export default toWebVTT;