UNPKG

origin_storage_manager

Version:

multi cloud's storage event manager

96 lines (74 loc) 2.36 kB
import CryptoJS from 'crypto-js'; const readFile = (file, chunkCallback) => { const blobSlice = Blob.prototype.slice; const fileSize = file.size; const chunkSize = 10 * 1024 * 1024; // 10MB const chunks = Math.ceil(fileSize / chunkSize); const reader = new FileReader(); let currentChunk = 0; reader.onload = function () { chunkCallback({ index: currentChunk, bufferArray: reader.result, length: chunks }); currentChunk++; if (currentChunk >= chunks) { return; } else { let start = currentChunk * chunkSize; let end = start + chunkSize >= fileSize ? fileSize : start + chunkSize; reader.readAsArrayBuffer(blobSlice.call(file, start, end)); } }; reader.onerror = function (err) { return; }; reader.readAsArrayBuffer(blobSlice.call(file, 0, chunkSize)); }; const getSha256 = (blob, uploader) => { const sha256 = CryptoJS.algo.SHA256.create(); const hashResults = []; let expectedIndex = 0; let handledChunks = 0; readFile(blob, (result) => { const wordArray = CryptoJS.lib.WordArray.create(result.bufferArray); if (expectedIndex === result.index) { sha256.update(wordArray); handledChunks++; expectedIndex++; } else { hashResults.push({ index: result.index, wordArray: wordArray }); } if (handledChunks + hashResults.length === result.length) { if (hashResults.length > 0) updateUntreatedWordArray(hashResults, sha256); const hashedStr = sha256.finalize().toString(); uploader.postMessage(hashedStr); } }); }; const updateUntreatedWordArray = (hashResults, sha256) => { sortIndexInArray(hashResults, 'index'); hashResults.forEach((obj) => { sha256.update(obj.wordArray); }); }; const sortIndexInArray = (arr, compareProp) => { let tempObj = null; for (let i = 0; i < arr.length; i++) { for (let j = i; j < arr.length - 1; j++) { let obj = arr[j]; let compareIndex = j + 1; let compareObj = arr[compareIndex]; if (obj[compareProp] > compareObj[compareProp]) { tempObj = compareObj; arr[compareIndex] = obj; arr[compareIndex - 1] = tempObj; } } } }; export default getSha256;