/**
 * Copyright (c) 2020, 2021 Oracle and/or its affiliates.  All rights reserved.
 * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
 */ import { UploadableBlob } from "./uploadable-blob" ; import { createHash } from "crypto" ; export class BrowserBlob implements UploadableBlob { size : number ; type : string ; private readonly chunkSize : number ; private readonly blob : Blob ; constructor ( blob , chunkSize ) { this . size = blob . size ; this . blob = blob ; this . chunkSize = chunkSize ; this . type = blob . type ; } public async getData ( ) { return new Promise ( resolve => { resolve ( this . blob ) ; } ) ; } public async text ( ) { return this . blob . text ( ) ; } public async arrayBuffer ( ) { return this . blob . arrayBuffer ( ) ; } public stream ( ) { return ( this . blob . stream ( ) as unknown ) as ReadableStream < any > ; } public async getMD5Hash ( ) { return new Promise ( resolve => { const blobSize = this . size - 1 ; const chunkSize = this . chunkSize ; const md5 = createHash ( "md5" ) ; const fileReader = new FileReader ( ) ; var updateMD5 = function ( ) { md5 . update ( fileReader . result as string ) ; } ; for ( var startPos = 0 ; startPos < blobSize ; startPos += chunkSize ) { ( ( blb , start ) => { const browserBlob = < BrowserBlob > blb . slice ( start , chunkSize + start ) ; fileReader . onload = updateMD5 ; fileReader . readAsBinaryString ( browserBlob . blob ) ; } ) ( this , startPos ) ; } resolve ( md5 . digest ( "base64" ) ) ; } ) ; } public slice ( start ? , end ? , contentType ? ) { return new BrowserBlob ( this . blob . slice ( start , end , contentType ) , this . chunkSize ) ; } }