diff --git a/src/apps.js b/src/apps.js index 1b587ab59..55777d38f 100644 --- a/src/apps.js +++ b/src/apps.js @@ -2519,33 +2519,28 @@ function downloadFile(app, filePath, callback) { }); } -function uploadFile(app, sourceFilePath, destFilePath, callback) { +async function uploadFile(app, sourceFilePath, destFilePath) { assert.strictEqual(typeof app, 'object'); assert.strictEqual(typeof sourceFilePath, 'string'); assert.strictEqual(typeof destFilePath, 'string'); - assert.strictEqual(typeof callback, 'function'); - - const done = once(function (error) { - safe.fs.unlinkSync(sourceFilePath); // remove file in /tmp - if (error) return callback(new BoxError(BoxError.FS_ERROR, error.message)); // blame it on filesystem for now - callback(null); - }); // the built-in bash printf understands "%q" but not /usr/bin/printf. // ' gets replaced with '\'' . the first closes the quote and last one starts a new one const escapedDestFilePath = safe.child_process.execSync(`printf %q '${destFilePath.replace(/'/g, '\'\\\'\'')}'`, { shell: '/bin/bash', encoding: 'utf8' }); debug(`uploadFile: ${sourceFilePath} -> ${escapedDestFilePath}`); - exec(app, { cmd: [ 'bash', '-c', `cat - > ${escapedDestFilePath}` ], tty: false }, function (error, stream) { - if (error) return done(error); + const destStream = await exec(app, { cmd: [ 'bash', '-c', `cat - > ${escapedDestFilePath}` ], tty: false }); - var readFile = fs.createReadStream(sourceFilePath); - readFile.on('error', done); + return new Promise((resolve, reject) => { + const done = once(error => reject(new BoxError(BoxError.FS_ERROR, error.message))); - stream.on('error', done); - stream.on('finish', done); + const sourceStream = fs.createReadStream(sourceFilePath); + sourceStream.on('error', done); + destStream.on('error', done); - readFile.pipe(stream); + destStream.on('finish', resolve); + + sourceStream.pipe(destStream); }); } diff --git a/src/routes/apps.js b/src/routes/apps.js index f4d7b2b9e..caf40df53 100644 --- a/src/routes/apps.js +++ b/src/routes/apps.js @@ -783,7 +783,7 @@ async function listBackups(req, res, next) { next(new HttpSuccess(200, { backups: result })); } -function uploadFile(req, res, next) { +async function uploadFile(req, res, next) { assert.strictEqual(typeof req.app, 'object'); if (typeof req.query.file !== 'string' || !req.query.file) return next(new HttpError(400, 'file query argument must be provided')); @@ -791,11 +791,11 @@ function uploadFile(req, res, next) { req.clearTimeout(); - apps.uploadFile(req.app, req.files.file.path, req.query.file, function (error) { - if (error) return next(BoxError.toHttpError(error)); + const [error] = await safe(apps.uploadFile(req.app, req.files.file.path, req.query.file)); + safe.fs.unlinkSync(req.files.file.path); // remove file in /tmp - next(new HttpSuccess(202, {})); - }); + if (error) return next(BoxError.toHttpError(error)); + next(new HttpSuccess(202, {})); } function downloadFile(req, res, next) {