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

123 lines
2.8 KiB
JavaScript

//This worker will be used for cryptographic, long running and API calls
//to keep the UI free
import Api from './api.js'
import { WS } from './Websocket.js';
self.websocket = new WS()
const name = 'main'
// TODO
//if (window.isSecureContext) {
//// Page is a secure context so service workers are now available
//navigator.serviceWorker.register("/offline-worker.js").then(function () {
//...
//});
//}
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)
// Ask permission to send a new upload
await upload.create()
.then(data => {
// Get the upload id
let { result: { upload_id: id, invoice: invoice } } = data;
// Register to updates on our uploadId from websocket
//self.websocket.listenTo('upload-accepted')
//postMessage({
//msg: 'upload-invoice',
//id: id,
//invoice: resp.result.invoice
//})
// Notify the UI
postMessage({msg: 'upload-invoice', id: id, invoice: invoice})
// Send the files
//upload.send()
//.then(resp =>{
//postMessage({
//msg: 'upload-invoice',
//id: id,
//invoice: resp.result.invoice
//})
//})
//.catch(err =>{
//console.error(err)
//})
})
}
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", ... }`)
}
}