send/app/serviceWorker.js

82 lines
2 KiB
JavaScript
Raw Normal View History

2018-07-05 19:40:49 +00:00
import Keychain from './keychain';
2018-07-06 22:49:50 +00:00
self.addEventListener('install', event => {
2018-07-05 19:40:49 +00:00
self.skipWaiting();
});
async function decryptStream(request) {
2018-07-09 22:39:06 +00:00
self.controller = new AbortController();
console.log("SW INTERCEPTED DOWNLOAD")
console.log(request)
2018-07-06 22:49:50 +00:00
const response = await fetch(request.url, {
method: 'GET',
2018-07-09 22:39:06 +00:00
headers: { Authorization: self.auth },
signal: controller.signal
2018-07-06 22:49:50 +00:00
});
2018-07-05 19:40:49 +00:00
if (response.status !== 200) {
2018-07-09 22:39:06 +00:00
console.log(response.status);
2018-07-06 22:49:50 +00:00
return response;
2018-07-05 19:40:49 +00:00
}
2018-07-09 22:39:06 +00:00
self.authHeader = response.headers.get('WWW-Authenticate');
2018-07-06 22:49:50 +00:00
const body = response.body; //stream
2018-07-09 22:39:06 +00:00
const progStream = new TransformStream({
transform: (chunk, controller) => {
self.progress += chunk.length;
controller.enqueue(chunk);
}
});
const decrypted = self.keychain.decryptStream(body.pipeThrough(progStream));
2018-07-06 22:49:50 +00:00
const headers = {
headers: {
'Content-Disposition': 'attachment; filename=' + self.filename
}
};
2018-07-05 19:40:49 +00:00
2018-07-06 22:49:50 +00:00
const newRes = new Response(decrypted, headers);
return newRes;
2018-07-05 19:40:49 +00:00
}
2018-07-06 22:49:50 +00:00
self.onfetch = event => {
2018-07-05 19:40:49 +00:00
const req = event.request.clone();
if (req.url.includes('/api/download')) {
event.respondWith(decryptStream(req));
}
};
2018-07-06 22:49:50 +00:00
self.onmessage = event => {
2018-07-09 22:39:06 +00:00
if (event.data.key) {
if (!self.keychain) {
self.keychain = new Keychain(event.data.key, event.data.nonce);
}
self.filename = event.data.filename;
self.auth = event.data.auth;
self.progress = 0;
self.cancelled = false;
event.ports[0].postMessage("file info received");
} else if (event.data === "progress") {
if (self.cancelled) {
event.ports[0].postMessage({error: "cancelled"});
} else {
event.ports[0].postMessage(self.progress);
}
} else if (event.data === "authHeader") {
event.ports[0].postMessage(self.authHeader);
} else if (event.data === "cancel") {
self.cancelled = true;
if (self.controller) {
self.controller.abort();
}
event.ports[0].postMessage("download cancelled");
}
2018-07-06 22:49:50 +00:00
};