tweb-i2p/src/helpers/blob.ts

59 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-04-08 17:52:31 +04:00
/*
* https://github.com/morethanwords/tweb
* Copyright (C) 2019-2021 Eduard Kuzmenko
* https://github.com/morethanwords/tweb/blob/master/LICENSE
*
* Originally from:
* https://github.com/zhukov/webogram
* Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>
* https://github.com/zhukov/webogram/blob/master/LICENSE
*/
export const readBlobAsText = (blob: Blob) => {
return new Promise<string>(resolve => {
const reader = new FileReader();
reader.addEventListener('loadend', (e) => {
// @ts-ignore
resolve(e.srcElement.result);
});
reader.readAsText(blob);
});
2020-10-29 19:11:09 +02:00
};
export function blobConstruct(blobParts: any, mimeType: string = ''): Blob {
let blob;
const safeMimeType = blobSafeMimeType(mimeType);
try {
blob = new Blob(blobParts, {type: safeMimeType});
} catch(e) {
// @ts-ignore
let bb = new BlobBuilder;
blobParts.forEach((blobPart: any) => {
bb.append(blobPart);
});
blob = bb.getBlob(safeMimeType);
}
return blob;
}
export function blobSafeMimeType(mimeType: string) {
if([
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/bmp',
'video/mp4',
'video/webm',
'video/quicktime',
'audio/ogg',
'audio/mpeg',
'audio/mp4',
'application/json'
].indexOf(mimeType) === -1) {
return 'application/octet-stream';
}
return mimeType;
2021-04-08 17:52:31 +04:00
}