Merge pull request #514 from mozilla/refactor-download

use async and removed jquery from download.js
This commit is contained in:
Danny Coates 2017-08-14 12:12:11 -07:00 committed by GitHub
commit f1fb877c7f
3 changed files with 141 additions and 144 deletions

View File

@ -5,26 +5,29 @@ import Storage from './storage';
import * as links from './links'; import * as links from './links';
import * as metrics from './metrics'; import * as metrics from './metrics';
import * as progress from './progress'; import * as progress from './progress';
import $ from 'jquery/dist/jquery.slim';
const storage = new Storage(); const storage = new Storage();
function onUnload(size) { function onUnload(size) {
metrics.cancelledDownload({ size }); metrics.cancelledDownload({ size });
} }
function download() { async function download() {
const $downloadBtn = $('#download-btn'); const downloadBtn = document.getElementById('download-btn');
const $title = $('.title'); const downloadPanel = document.getElementById('download-page-one');
const $file = $('#dl-file'); const progressPanel = document.getElementById('download-progress');
const size = Number($file.attr('data-size')); const file = document.getElementById('dl-file');
const ttl = Number($file.attr('data-ttl')); const size = Number(file.getAttribute('data-size'));
const ttl = Number(file.getAttribute('data-ttl'));
const unloadHandler = onUnload.bind(null, size); const unloadHandler = onUnload.bind(null, size);
const startTime = Date.now(); const startTime = Date.now();
const fileReceiver = new FileReceiver(); const fileReceiver = new FileReceiver(
'/assets' + location.pathname.slice(0, -1),
location.hash.slice(1)
);
$downloadBtn.attr('disabled', 'disabled'); downloadBtn.disabled = true;
$('#download-page-one').attr('hidden', true); downloadPanel.hidden = true;
$('#download-progress').removeAttr('hidden'); progressPanel.hidden = false;
metrics.startedDownload({ size, ttl }); metrics.startedDownload({ size, ttl });
links.setOpenInNewTab(true); links.setOpenInNewTab(true);
window.addEventListener('unload', unloadHandler); window.addEventListener('unload', unloadHandler);
@ -41,76 +44,72 @@ function download() {
document.l10n.formatValue('decryptingFile').then(progress.setText); document.l10n.formatValue('decryptingFile').then(progress.setText);
}); });
fileReceiver try {
.download() const file = await fileReceiver.download();
.catch(err => { const endTime = Date.now();
metrics.stoppedDownload({ size, err }); const time = endTime - startTime;
const downloadTime = endTime - downloadEnd;
const speed = size / (downloadTime / 1000);
if (err.message === 'notfound') { links.setOpenInNewTab(false);
location.reload(); storage.totalDownloads += 1;
} else { metrics.completedDownload({ size, time, speed });
document.l10n.formatValue('errorPageHeader').then(translated => { progress.setText(' ');
$title.text(translated); document.l10n
}); .formatValues('downloadNotification', 'downloadFinish')
$downloadBtn.attr('hidden', true); .then(translated => {
$('#expired-img').removeAttr('hidden'); notify(translated[0]);
} document.getElementById('dl-title').textContent = translated[1];
throw err; document.querySelector('#download-progress .description').textContent =
}) ' ';
.then(([decrypted, file]) => { });
const fname = file.name; const dataView = new DataView(file.plaintext);
const endTime = Date.now(); const blob = new Blob([dataView], { type: file.type });
const time = endTime - startTime; const downloadUrl = URL.createObjectURL(blob);
const downloadTime = endTime - downloadEnd;
const speed = size / (downloadTime / 1000);
storage.totalDownloads += 1;
metrics.completedDownload({ size, time, speed });
progress.setText(' ');
document.l10n
.formatValues('downloadNotification', 'downloadFinish')
.then(translated => {
notify(translated[0]);
$title.text(translated[1]);
});
const dataView = new DataView(decrypted); const a = document.createElement('a');
const blob = new Blob([dataView], { type: file.type }); a.href = downloadUrl;
const downloadUrl = URL.createObjectURL(blob); if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob, file.name);
return;
}
a.download = file.name;
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(downloadUrl);
} catch (err) {
metrics.stoppedDownload({ size, err });
const a = document.createElement('a'); if (err.message === 'notfound') {
a.href = downloadUrl; location.reload();
if (window.navigator.msSaveBlob) { } else {
// if we are in microsoft edge or IE progressPanel.hidden = true;
window.navigator.msSaveBlob(blob, fname); downloadPanel.hidden = true;
return; document.getElementById('upload-error').hidden = false;
} }
a.download = fname; Raven.captureException(err);
document.body.appendChild(a); }
a.click();
URL.revokeObjectURL(downloadUrl);
})
.catch(err => {
Raven.captureException(err);
return Promise.reject(err);
})
.then(() => links.setOpenInNewTab(false));
} }
$(() => { document.addEventListener('DOMContentLoaded', function() {
const $file = $('#dl-file'); const file = document.getElementById('dl-file');
const filename = $file.attr('data-filename'); const filename = file.getAttribute('data-filename');
const b = Number($file.attr('data-size')); const b = Number(file.getAttribute('data-size'));
const size = bytes(b); const size = bytes(b);
document.l10n document.l10n.formatValue('downloadFileSize', { size }).then(str => {
.formatValue('downloadFileSize', { size }) document.getElementById('dl-filesize').textContent = str;
.then(str => $('#dl-filesize').text(str)); });
document.l10n document.l10n
.formatValue('downloadingPageProgress', { filename, size }) .formatValue('downloadingPageProgress', { filename, size })
.then(str => $('#dl-title').text(str)); .then(str => {
document.getElementById('dl-title').textContent = str;
});
gcmCompliant() gcmCompliant()
.then(() => { .then(() => {
$('#download-btn').on('click', download); document
.getElementById('download-btn')
.addEventListener('click', download);
}) })
.catch(err => { .catch(err => {
metrics.unsupported({ err }).then(() => { metrics.unsupported({ err }).then(() => {

View File

@ -2,87 +2,80 @@ import EventEmitter from 'events';
import { hexToArray } from './utils'; import { hexToArray } from './utils';
export default class FileReceiver extends EventEmitter { export default class FileReceiver extends EventEmitter {
constructor() { constructor(url, k) {
super(); super();
this.key = window.crypto.subtle.importKey(
'jwk',
{
k,
kty: 'oct',
alg: 'A128GCM',
ext: true
},
{
name: 'AES-GCM'
},
false,
['decrypt']
);
this.url = url;
} }
download() { downloadFile() {
return window.crypto.subtle return new Promise((resolve, reject) => {
.importKey( const xhr = new XMLHttpRequest();
'jwk',
{
kty: 'oct',
k: location.hash.slice(1),
alg: 'A128GCM',
ext: true
},
{
name: 'AES-GCM'
},
true,
['encrypt', 'decrypt']
)
.then(key => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onprogress = event => { xhr.onprogress = event => {
if (event.lengthComputable && event.target.status !== 404) { if (event.lengthComputable && event.target.status !== 404) {
this.emit('progress', [event.loaded, event.total]); this.emit('progress', [event.loaded, event.total]);
} }
}; };
xhr.onload = function(event) { xhr.onload = function(event) {
if (xhr.status === 404) { if (xhr.status === 404) {
reject(new Error('notfound')); reject(new Error('notfound'));
return; return;
} }
const blob = new Blob([this.response]); const blob = new Blob([this.response]);
const type = xhr.getResponseHeader('Content-Type'); const type = xhr.getResponseHeader('Content-Type');
const meta = JSON.parse(xhr.getResponseHeader('X-File-Metadata')); const meta = JSON.parse(xhr.getResponseHeader('X-File-Metadata'));
const fileReader = new FileReader(); const fileReader = new FileReader();
fileReader.onload = function() { fileReader.onload = function() {
resolve([ resolve({
{ data: this.result,
data: this.result, name: meta.filename,
filename: meta.filename, type,
type, iv: meta.id
iv: meta.id });
}, };
key
]);
};
fileReader.readAsArrayBuffer(blob); fileReader.readAsArrayBuffer(blob);
}; };
xhr.open('get', '/assets' + location.pathname.slice(0, -1), true); xhr.open('get', this.url);
xhr.responseType = 'blob'; xhr.responseType = 'blob';
xhr.send(); xhr.send();
}); });
}) }
.then(([fdata, key]) => {
this.emit('decrypting'); async download() {
return Promise.all([ const key = await this.key;
window.crypto.subtle const file = await this.downloadFile();
.decrypt( this.emit('decrypting');
{ const plaintext = await window.crypto.subtle.decrypt(
name: 'AES-GCM', {
iv: hexToArray(fdata.iv), name: 'AES-GCM',
tagLength: 128 iv: hexToArray(file.iv),
}, tagLength: 128
key, },
fdata.data key,
) file.data
.then(decrypted => { );
return Promise.resolve(decrypted); return {
}), plaintext,
{ name: decodeURIComponent(file.name),
name: decodeURIComponent(fdata.filename), type: file.type
type: fdata.type };
}
]);
});
} }
} }

View File

@ -35,5 +35,10 @@
</div> </div>
</div> </div>
<div id="upload-error" hidden="true">
<div class="title" data-l10n-id="errorPageHeader"></div>
<img id="upload-error-img" data-l10n-id="errorAltText" src="/resources/illustration_error.svg"/>
</div>
<a class="send-new" data-state="completed" data-l10n-id="sendYourFilesLink" href="/"></a> <a class="send-new" data-state="completed" data-l10n-id="sendYourFilesLink" href="/"></a>
</div> </div>