2018-06-21 00:05:33 +00:00
|
|
|
const crypto = require('crypto');
|
|
|
|
const storage = require('../storage');
|
|
|
|
const config = require('../config');
|
|
|
|
const mozlog = require('../log');
|
|
|
|
const Limiter = require('../limiter');
|
2018-06-25 18:26:48 +00:00
|
|
|
const Parser = require('../streamparser');
|
2018-06-21 00:05:33 +00:00
|
|
|
const wsStream = require('websocket-stream/stream');
|
|
|
|
|
|
|
|
const log = mozlog('send.upload');
|
|
|
|
|
|
|
|
module.exports = async function(ws, req) {
|
|
|
|
let fileStream;
|
|
|
|
|
2018-06-21 20:57:53 +00:00
|
|
|
ws.on('close', e => {
|
2018-06-22 20:17:23 +00:00
|
|
|
if (e !== 1000 && fileStream !== undefined) {
|
|
|
|
fileStream.destroy();
|
2018-06-21 20:57:53 +00:00
|
|
|
}
|
|
|
|
});
|
2018-06-21 00:05:33 +00:00
|
|
|
|
2018-06-25 17:57:52 +00:00
|
|
|
ws.once('message', async function(message) {
|
2018-06-21 20:57:53 +00:00
|
|
|
try {
|
2018-06-25 17:57:52 +00:00
|
|
|
const newId = crypto.randomBytes(5).toString('hex');
|
|
|
|
const owner = crypto.randomBytes(10).toString('hex');
|
2018-06-21 00:05:33 +00:00
|
|
|
|
2018-06-25 17:57:52 +00:00
|
|
|
const fileInfo = JSON.parse(message);
|
|
|
|
const metadata = fileInfo.fileMetadata;
|
|
|
|
const auth = fileInfo.authorization;
|
2018-06-21 00:05:33 +00:00
|
|
|
|
2018-06-25 17:57:52 +00:00
|
|
|
if (!metadata || !auth) {
|
2018-06-21 00:05:33 +00:00
|
|
|
ws.send(
|
|
|
|
JSON.stringify({
|
2018-06-25 17:57:52 +00:00
|
|
|
error: 400
|
2018-06-21 00:05:33 +00:00
|
|
|
})
|
|
|
|
);
|
2018-06-25 17:57:52 +00:00
|
|
|
return ws.close();
|
2018-06-21 00:05:33 +00:00
|
|
|
}
|
2018-06-25 17:57:52 +00:00
|
|
|
|
|
|
|
const meta = {
|
|
|
|
owner,
|
|
|
|
metadata,
|
|
|
|
auth: auth.split(' ')[1],
|
|
|
|
nonce: crypto.randomBytes(16).toString('base64')
|
|
|
|
};
|
|
|
|
|
|
|
|
const protocol = config.env === 'production' ? 'https' : req.protocol;
|
|
|
|
const url = `${protocol}://${req.get('host')}/download/${newId}/`;
|
|
|
|
|
|
|
|
const limiter = new Limiter(config.max_file_size);
|
2018-06-25 18:26:48 +00:00
|
|
|
const parser = new Parser();
|
|
|
|
fileStream = wsStream(ws, { binary: true })
|
|
|
|
.pipe(limiter)
|
|
|
|
.pipe(parser);
|
2018-06-25 17:57:52 +00:00
|
|
|
storage.set(newId, fileStream, meta);
|
|
|
|
|
2018-06-25 18:52:29 +00:00
|
|
|
await parser.promise;
|
|
|
|
|
2018-06-25 17:57:52 +00:00
|
|
|
ws.send(
|
|
|
|
JSON.stringify({
|
|
|
|
url,
|
|
|
|
owner: meta.owner,
|
|
|
|
id: newId,
|
|
|
|
authentication: `send-v1 ${meta.nonce}`
|
|
|
|
})
|
|
|
|
);
|
2018-06-21 20:57:53 +00:00
|
|
|
} catch (e) {
|
|
|
|
log.error('upload', e);
|
|
|
|
ws.send(
|
|
|
|
JSON.stringify({
|
2018-06-25 18:26:48 +00:00
|
|
|
error: e === 'limit' ? 413 : 500
|
2018-06-21 20:57:53 +00:00
|
|
|
})
|
|
|
|
);
|
2018-06-22 20:17:23 +00:00
|
|
|
ws.close();
|
2018-06-21 20:57:53 +00:00
|
|
|
}
|
|
|
|
});
|
2018-06-21 00:05:33 +00:00
|
|
|
};
|