uses fetch.body

This commit is contained in:
Emily 2018-06-29 09:36:08 -07:00
parent 5f79a9fb6d
commit 38ef52d3ba
3 changed files with 192 additions and 24 deletions

View file

@ -1,7 +1,7 @@
import Nanobus from 'nanobus';
import Keychain from './keychain';
import { bytes } from './utils';
import { metadata, downloadFile } from './api';
import { metadata, downloadFile, downloadStream} from './api';
export default class FileReceiver extends Nanobus {
constructor(fileInfo) {
@ -51,24 +51,64 @@ export default class FileReceiver extends Nanobus {
this.state = 'ready';
}
async streamToArrayBuffer(stream, streamSize) {
const reader = stream.getReader();
const result = new Uint8Array(streamSize);
let offset = 0;
/*
async streamToArrayBuffer(stream, streamSize) {
try {
var finish;
const promise = new Promise((resolve) => {
finish = resolve;
});
const result = new Uint8Array(streamSize);
let offset = 0;
let state = await reader.read();
while (!state.done) {
result.set(state.value, offset);
offset += state.value.length;
state = await reader.read();
const writer = new WritableStream(
{
write(chunk) {
result.set(state.value, offset);
offset += state.value.length;
},
close() {
//resolve a promise or something
finish.resolve();
}
}
);
stream.pipeTo(writer);
await promise;
return result.slice(0, offset).buffer;
} catch (e) {
console.log(e)
}
}
*/
return result.slice(0, offset).buffer;
async streamToArrayBuffer(stream, streamSize) {
try {
const result = new Uint8Array(streamSize);
let offset = 0;
console.log("reading...")
const reader = stream.getReader();
let state = await reader.read();
console.log("read done")
while (!state.done) {
result.set(state.value, offset);
offset += state.value.length;
state = await reader.read();
}
return result.slice(0, offset).buffer;
} catch (e) {
console.log(e)
}
}
async download(noSave = false) {
this.state = 'downloading';
this.downloadRequest = await downloadFile(
this.downloadRequest = await downloadStream(
this.fileInfo.id,
this.keychain,
p => {
@ -78,18 +118,22 @@ export default class FileReceiver extends Nanobus {
);
try {
const ciphertext = await this.downloadRequest.result;
this.downloadRequest = null;
this.msg = 'decryptingFile';
this.state = 'decrypting';
this.emit('decrypting');
const dec = await this.keychain.decryptStream(ciphertext);
const plaintext = await this.streamToArrayBuffer(
const dec = this.keychain.decryptStream(ciphertext);
let plaintext = await this.streamToArrayBuffer(
dec.stream,
this.fileInfo.size
);
if (plaintext === undefined) { plaintext = (new Uint8Array(1)).buffer; }
if (!noSave) {
await saveFile({
plaintext,
@ -97,8 +141,10 @@ export default class FileReceiver extends Nanobus {
type: this.fileInfo.type
});
}
this.msg = 'downloadFinish';
this.state = 'complete';
} catch (e) {
this.downloadRequest = null;
throw e;