2017-08-10 17:02:13 +00:00
|
|
|
import EventEmitter from 'events';
|
|
|
|
import { hexToArray } from './utils';
|
2017-06-02 19:38:05 +00:00
|
|
|
|
2017-08-10 17:02:13 +00:00
|
|
|
export default class FileReceiver extends EventEmitter {
|
2017-08-14 18:14:47 +00:00
|
|
|
constructor(url, k) {
|
2017-06-02 19:38:05 +00:00
|
|
|
super();
|
2017-08-14 18:14:47 +00:00
|
|
|
this.key = window.crypto.subtle.importKey(
|
|
|
|
'jwk',
|
|
|
|
{
|
|
|
|
k,
|
|
|
|
kty: 'oct',
|
|
|
|
alg: 'A128GCM',
|
|
|
|
ext: true
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: 'AES-GCM'
|
|
|
|
},
|
|
|
|
false,
|
|
|
|
['decrypt']
|
|
|
|
);
|
|
|
|
this.url = url;
|
2017-06-02 19:38:05 +00:00
|
|
|
}
|
|
|
|
|
2017-08-14 18:14:47 +00:00
|
|
|
downloadFile() {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const xhr = new XMLHttpRequest();
|
2017-08-03 17:04:09 +00:00
|
|
|
|
2017-08-14 18:14:47 +00:00
|
|
|
xhr.onprogress = event => {
|
|
|
|
if (event.lengthComputable && event.target.status !== 404) {
|
|
|
|
this.emit('progress', [event.loaded, event.total]);
|
|
|
|
}
|
|
|
|
};
|
2017-08-03 17:04:09 +00:00
|
|
|
|
2017-08-14 18:14:47 +00:00
|
|
|
xhr.onload = function(event) {
|
|
|
|
if (xhr.status === 404) {
|
|
|
|
reject(new Error('notfound'));
|
|
|
|
return;
|
|
|
|
}
|
2017-08-03 17:04:09 +00:00
|
|
|
|
2017-08-14 18:14:47 +00:00
|
|
|
const blob = new Blob([this.response]);
|
|
|
|
const meta = JSON.parse(xhr.getResponseHeader('X-File-Metadata'));
|
|
|
|
const fileReader = new FileReader();
|
|
|
|
fileReader.onload = function() {
|
|
|
|
resolve({
|
|
|
|
data: this.result,
|
|
|
|
name: meta.filename,
|
2017-08-17 17:19:18 +00:00
|
|
|
type: meta.mimeType,
|
2017-08-14 18:14:47 +00:00
|
|
|
iv: meta.id
|
|
|
|
});
|
|
|
|
};
|
2017-08-03 17:04:09 +00:00
|
|
|
|
2017-08-14 18:14:47 +00:00
|
|
|
fileReader.readAsArrayBuffer(blob);
|
|
|
|
};
|
2017-08-03 17:04:09 +00:00
|
|
|
|
2017-08-14 18:14:47 +00:00
|
|
|
xhr.open('get', this.url);
|
|
|
|
xhr.responseType = 'blob';
|
|
|
|
xhr.send();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async download() {
|
|
|
|
const key = await this.key;
|
|
|
|
const file = await this.downloadFile();
|
|
|
|
this.emit('decrypting');
|
|
|
|
const plaintext = await window.crypto.subtle.decrypt(
|
|
|
|
{
|
|
|
|
name: 'AES-GCM',
|
|
|
|
iv: hexToArray(file.iv),
|
|
|
|
tagLength: 128
|
|
|
|
},
|
|
|
|
key,
|
|
|
|
file.data
|
|
|
|
);
|
|
|
|
return {
|
|
|
|
plaintext,
|
|
|
|
name: decodeURIComponent(file.name),
|
|
|
|
type: file.type
|
|
|
|
};
|
2017-06-02 19:38:05 +00:00
|
|
|
}
|
|
|
|
}
|