You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bit4sat/web/src/worker.js

88 lines
1.9 KiB
JavaScript

//This worker will be used for cryptographic, long running and API calls
//to keep the UI free
import Api from './api.js'
const name = 'main'
function hexString(buffer) {
const byteArray = new Uint8Array(buffer);
const hexCodes = [...byteArray].map(value => {
const hexCode = value.toString(16);
const paddedHexCode = hexCode.padStart(2, '0');
return paddedHexCode;
});
return hexCodes.join('');
}
async function getSHA256(file){
// Read as array buffer
let fileReader = new FileReaderSync();
let buffer = fileReader.readAsArrayBuffer(file);
// Return hex encoded sha256
return crypto.subtle.digest('SHA-256', buffer)
.then(v => { return hexString(v) })
}
async function newUpload(files){
let filesMetadata = await Promise.all(files.map(async (f) => {
return {
lastModified: f.lastModified,
type: f.type,
name: f.name,
size: f.size,
sha256: await getSHA256(f)
}
}))
// Get sha256
//for (let file of files) {
// let sha256 = getSHA256(file)
// file.sha256 = sha256
// console.log(files)
//}
let upload = new Api.Upload(filesMetadata, files)
await upload.create()
.then(data => {
// Get the upload id
let { result: { id: id } } = data
// Notify the UI
postMessage({msg: 'upload-id', id: id})
// Send the files
upload.send()
})
}
self.onmessage = e => {
switch (e.data.msg) {
case 'init':
console.log(`initialized ${name} worker`);
break;
case 'file-sha256':
getSHA256(e.data.payload)
break;
case 'new-upload':
newUpload(e.data.payload)
break;
default:
console.log(`${name} worker: need {msg: "message type", ... }`)
}
}