feat: Add hash checking for chunked uploads

This commit is contained in:
Pitu 2020-12-27 04:48:03 +09:00
parent e97fee4844
commit aa7d245317
3 changed files with 34 additions and 12 deletions

View File

@ -58,6 +58,28 @@ class uploadPOST extends Route {
await jetpack.removeAsync(chunkOutput);
}
/*
If a file with the same hash and user is found, delete this
uploaded copy and return a link to the original
*/
info.hash = await Util.getFileHash(info.name);
let existingFile = await Util.checkIfFileExists(db, user, info.hash);
if (existingFile) {
existingFile = Util.constructFilePublicLink(existingFile);
res.json({
message: 'Successfully uploaded the file.',
name: existingFile.name,
hash: existingFile.hash,
size: existingFile.size,
url: `${process.env.DOMAIN}/${existingFile.name}`,
deleteUrl: `${process.env.DOMAIN}/api/file/${existingFile.id}`,
repeated: true
});
return Util.deleteFile(info.name);
}
// Otherwise generate thumbs and do the rest
Util.generateThumbnails(info.name);
const insertedId = await Util.saveFileToDatabase(req, res, user, db, info, {
originalname: info.data.original, mimetype: info.data.type

View File

@ -79,7 +79,7 @@ class uploadPOST extends Route {
For this we need to wait until we have a filename so that we can delete the uploaded file.
*/
const exists = await this.checkIfFileExists(db, user, hash);
const exists = await Util.checkIfFileExists(db, user, hash);
if (exists) return this.fileExists(res, exists, filename);
if (remappedKeys && remappedKeys.uuid) {
@ -140,17 +140,6 @@ class uploadPOST extends Route {
return Util.deleteFile(filename);
}
async checkIfFileExists(db, user, hash) {
const exists = await db.table('files')
.where(function() { // eslint-disable-line func-names
if (user) this.where('userId', user.id);
else this.whereNull('userId');
})
.where({ hash })
.first();
return exists;
}
_remapKeys(body) {
const keys = Object.keys(body);
if (keys.length) {

View File

@ -108,6 +108,17 @@ class Util {
return hash;
}
static async checkIfFileExists(db, user, hash) {
const exists = await db.table('files')
.where(function() { // eslint-disable-line func-names
if (user) this.where('userId', user.id);
else this.whereNull('userId');
})
.where({ hash })
.first();
return exists;
}
static getFilenameFromPath(fullPath) {
return fullPath.replace(/^.*[\\\/]/, ''); // eslint-disable-line no-useless-escape
}