-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathHelper.ts
More file actions
69 lines (55 loc) · 2.63 KB
/
Helper.ts
File metadata and controls
69 lines (55 loc) · 2.63 KB
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
import { IModify, IRead } from '@rocket.chat/apps-engine/definition/accessors';
import { IMessageFile } from '@rocket.chat/apps-engine/definition/messages';
import { DefaultMessage } from '../config/Settings';
import { AUDIO_EXTENSION, Base64, DialogflowRequestType, MIME_TYPE } from '../enum/Dialogflow';
import { Logs } from '../enum/Logs';
import { createMessage } from './Message';
export const base64urlEncode = (str: any) => {
const utf8str = unescape(encodeURIComponent(str));
return base64EncodeData(utf8str, utf8str.length, Base64.BASE64_DICTIONARY, Base64.BASE64_PAD);
};
export const base64EncodeData = (data: string, len: number, b64x: string, b64pad: string) => {
let dst = '';
let i: number;
// tslint:disable:no-bitwise
for (i = 0; i <= len - 3; i += 3) {
dst += b64x.charAt(data.charCodeAt(i) >>> 2);
dst += b64x.charAt(((data.charCodeAt(i) & 3) << 4) | (data.charCodeAt(i + 1) >>> 4));
dst += b64x.charAt(((data.charCodeAt(i + 1) & 15) << 2) | (data.charCodeAt(i + 2) >>> 6));
dst += b64x.charAt(data.charCodeAt(i + 2) & 63);
}
if (len % 3 === 2) {
dst += b64x.charAt(data.charCodeAt(i) >>> 2);
dst += b64x.charAt(((data.charCodeAt(i) & 3) << 4) | (data.charCodeAt(i + 1) >>> 4));
dst += b64x.charAt(((data.charCodeAt(i + 1) & 15) << 2));
dst += b64pad;
} else if (len % 3 === 1) {
dst += b64x.charAt(data.charCodeAt(i) >>> 2);
dst += b64x.charAt(((data.charCodeAt(i) & 3) << 4));
dst += b64pad;
dst += b64pad;
}
// tslint:enable:no-bitwise
return dst;
};
export const defineAudioFile = async (read: IRead, modify: IModify, roomId: string, file: IMessageFile): Promise<{ content: string, contentType: DialogflowRequestType}> => {
const { name } = await read.getUploadReader().getById(file._id);
if (!isSupportedAudioFormat(name)) {
await createMessage(roomId, read, modify, { text: DefaultMessage.DEFAULT_UnsupportedAudioFormatMessage });
}
const content = (await read.getUploadReader().getBufferById(file._id)).toString(Base64.BASE64);
const contentType = file && file.type === MIME_TYPE.AUDIO_OGG ? DialogflowRequestType.AUDIO_OGG : DialogflowRequestType.AUDIO;
return { content, contentType };
};
export const isSupportedAudioFormat = (fileName: string): boolean => {
const extension = fileName.split('.')[1];
if (!extension) {
throw new Error(Logs.INVALID_AUDIO_FILE_NAME);
}
if (extension === AUDIO_EXTENSION.OGA ||
extension === AUDIO_EXTENSION.WAV ||
extension === AUDIO_EXTENSION.OPUS) {
return true;
}
return false;
};