Merge pull request #2749 from thelounge/xpaw/fix-upload

Move correct file after upload, put file extension in slug
This commit is contained in:
Pavel Djundik 2018-09-05 10:09:19 +03:00 committed by GitHub
commit d6a150c5d6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -42,39 +42,37 @@ class Uploader {
}); });
uploader.on("complete", (data) => { uploader.on("complete", (data) => {
handleSaving(data).then((randomName) => { let randomName;
const randomFileName = randomName; let destPath;
const slug = data.file.base;
const url = `uploads/${randomFileName}/${slug}`;
socket.emit("upload:success", url);
});
});
uploader.on("error", (data) => { // Generate a random file name for storage on disk
log.error(`Error uploading ${data.error.name}`);
log.error(data.error);
});
// maxFileSize is in bytes, but config option is passed in as KB
uploader.maxFileSize = Uploader.getMaxFileSize();
uploader.listen(socket);
// Returns Promise
function handleSaving(data) {
const tempPath = path.join(Helper.getFileUploadPath(), ".tmp", data.file.name);
let randomName, destPath;
// If file conflicts
do { do {
randomName = crypto.randomBytes(8).toString("hex"); randomName = crypto.randomBytes(8).toString("hex");
destPath = path.join(Helper.getFileUploadPath(), randomName.substring(0, 2), randomName); destPath = path.join(Helper.getFileUploadPath(), randomName.substring(0, 2), randomName);
} while (fs.stat(destPath, (err) => (err ? true : false))); } while (fs.stat(destPath, (err) => (err ? true : false)));
return fsextra.move(tempPath, destPath) fsextra.move(data.file.pathName, destPath).then(() => {
.then(() => randomName).catch(() => { const slug = path.basename(data.file.pathName);
log.warn(`Unable to move file ${tempPath} to ${destPath}`); const url = `uploads/${randomName}/${slug}`;
socket.emit("upload:success", url);
}).catch(() => {
log.warn(`Unable to move uploaded file "${data.file.pathName}"`);
// Emit failed upload to the client if file move fails
socket.emit("siofu_error", {
id: data.file.id,
message: "Unable to move uploaded file",
}); });
} });
});
uploader.on("error", (data) => {
log.error(`File upload failed: ${data.error}`);
});
// maxFileSize is in bytes, but config option is passed in as KB
uploader.maxFileSize = Uploader.getMaxFileSize();
uploader.listen(socket);
} }
static isValidType(mimeType) { static isValidType(mimeType) {