Added check for duplicate ID's (closes #75)

pull/77/head
tycrek 3 years ago
parent b801ae43a5
commit 29f7f25f38
No known key found for this signature in database
GPG Key ID: 25D74F3943625263

@ -64,62 +64,80 @@ router.post('/', (req, res, next) => {
// Fix spaces in originalname // Fix spaces in originalname
req.file.originalname = req.file.originalname.replace(/\s/g, spaceReplace === '!' ? '' : spaceReplace); req.file.originalname = req.file.originalname.replace(/\s/g, spaceReplace === '!' ? '' : spaceReplace);
// Save the file information // Generate a unique resource ID
const resourceId = generateId(generator, resourceIdSize, req.headers['x-ass-gfycat'] || gfyIdSize, req.file.originalname); let resourceId;
log.debug('Saving data', data.name);
data.put(resourceId.split('.')[0], req.file).then(() => { // Function to call to generate a fresh ID. Used for multiple attempts in case an ID is already taken
// Log the upload const gen = () => generateId(generator, resourceIdSize, req.headers['x-ass-gfycat'] || gfyIdSize, req.file.originalname);
const logInfo = `${req.file.originalname} (${req.file.mimetype}, ${formatBytes(req.file.size)})`;
log.success('File uploaded', logInfo, `uploaded by ${users[req.token] ? users[req.token].username : '<token-only>'}`); // Called by a promise, this will recursively resolve itself until a unique ID is found
// TODO: Add max attempts in case all available ID's are taken
// Build the URLs function genCheckId(resolve, reject) {
const resourceUrl = `${getTrueHttp()}${trueDomain}/${resourceId}`; let uniqueId = gen();
const thumbnailUrl = `${getTrueHttp()}${trueDomain}/${resourceId}/thumbnail`; data.has(uniqueId)
const deleteUrl = `${getTrueHttp()}${trueDomain}/${resourceId}/delete/${req.file.deleteId}`; .then((exists) => (log.debug('ID check', exists ? 'Taken' : 'Available'), exists ? genCheckId(resolve, reject) : resolve(uniqueId)))
.catch(reject);
// Send the response }
res.type('json').send({ resource: resourceUrl, thumbnail: thumbnailUrl, delete: deleteUrl })
.on('finish', () => { new Promise((resolve, reject) => genCheckId(resolve, reject))
log.debug('Upload response sent'); .then((uniqueId) => {
resourceId = uniqueId;
// After we have sent the user the response, also send a Webhook to Discord (if headers are present) log.debug('Saving data', data.name);
if (req.headers['x-ass-webhook-client'] && req.headers['x-ass-webhook-token']) { })
.then(() => data.put(resourceId.split('.')[0], req.file))
// Build the webhook .then(() => {
const hook = new Webhook(req.headers['x-ass-webhook-url']); // Log the upload
hook.setUsername(req.headers['x-ass-webhook-username'] || 'ass'); const logInfo = `${req.file.originalname} (${req.file.mimetype}, ${formatBytes(req.file.size)})`;
hook.setAvatar(req.headers['x-ass-webhook-avatar'] || ASS_LOGO); log.success('File uploaded', logInfo, `uploaded by ${users[req.token] ? users[req.token].username : '<token-only>'}`);
// Build the embed // Build the URLs
const embed = new MessageBuilder() const resourceUrl = `${getTrueHttp()}${trueDomain}/${resourceId}`;
.setTitle(logInfo) const thumbnailUrl = `${getTrueHttp()}${trueDomain}/${resourceId}/thumbnail`;
.setURL(resourceUrl) const deleteUrl = `${getTrueHttp()}${trueDomain}/${resourceId}/delete/${req.file.deleteId}`;
.setDescription(`**Size:** \`${formatBytes(req.file.size)}\`\n**[Delete](${deleteUrl})**`)
.setThumbnail(thumbnailUrl) // Send the response
.setColor(req.file.vibrant) res.type('json').send({ resource: resourceUrl, thumbnail: thumbnailUrl, delete: deleteUrl })
.setTimestamp(); .on('finish', () => {
log.debug('Upload response sent');
// Send the embed to the webhook, then delete the client after to free resources
log.debug('Sending embed to webhook'); // After we have sent the user the response, also send a Webhook to Discord (if headers are present)
hook.send(embed) if (req.headers['x-ass-webhook-client'] && req.headers['x-ass-webhook-token']) {
.then(() => log.debug('Webhook sent'))
.catch((err) => log.error('Webhook error').err(err)); // Build the webhook
} const hook = new Webhook(req.headers['x-ass-webhook-url']);
hook.setUsername(req.headers['x-ass-webhook-username'] || 'ass');
// Also update the users upload count hook.setAvatar(req.headers['x-ass-webhook-avatar'] || ASS_LOGO);
if (!users[req.token]) {
const generateUsername = () => generateId('random', 20, null); // skipcq: JS-0074 // Build the embed
let username = generateUsername(); const embed = new MessageBuilder()
while (Object.values(users).findIndex((user) => user.username === username) !== -1) // skipcq: JS-0073 .setTitle(logInfo)
username = generateUsername(); .setURL(resourceUrl)
users[req.token] = { username, count: 0 }; .setDescription(`**Size:** \`${formatBytes(req.file.size)}\`\n**[Delete](${deleteUrl})**`)
} .setThumbnail(thumbnailUrl)
users[req.token].count += 1; .setColor(req.file.vibrant)
fs.writeJsonSync(path('auth.json'), { users }, { spaces: 4 }); .setTimestamp();
log.debug('Upload request flow completed', ''); // Send the embed to the webhook, then delete the client after to free resources
}); log.debug('Sending embed to webhook');
}).catch(next); hook.send(embed)
.then(() => log.debug('Webhook sent'))
.catch((err) => log.error('Webhook error').err(err));
}
// Also update the users upload count
if (!users[req.token]) {
const generateUsername = () => generateId('random', 20, null); // skipcq: JS-0074
let username = generateUsername();
while (Object.values(users).findIndex((user) => user.username === username) !== -1) // skipcq: JS-0073
username = generateUsername();
users[req.token] = { username, count: 0 };
}
users[req.token].count += 1;
fs.writeJsonSync(path('auth.json'), { users }, { spaces: 4 });
log.debug('Upload request flow completed', '');
});
}).catch(next);
}); });
module.exports = router; module.exports = router;

Loading…
Cancel
Save