v3.0.0/src/api/routes/albums/link/linkPOST.js

69 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-09-16 05:56:13 +02:00
const Route = require('../../../structures/Route');
const Util = require('../../../utils/Util');
class linkPOST extends Route {
constructor() {
super('/album/link/new', 'post', { canApiKey: true });
2018-09-16 05:56:13 +02:00
}
2019-02-19 15:52:24 +01:00
async run(req, res, db, user) {
2018-09-16 05:56:13 +02:00
if (!req.body) return res.status(400).json({ message: 'No body provided' });
2018-09-16 22:52:46 +02:00
const { albumId } = req.body;
2018-09-16 05:56:13 +02:00
if (!albumId) return res.status(400).json({ message: 'No album provided' });
2018-09-17 09:55:42 +02:00
/*
Make sure the album exists
*/
const exists = await db
.table('albums')
.where({ id: albumId, userId: user.id })
.first();
2018-09-16 05:56:13 +02:00
if (!exists) return res.status(400).json({ message: 'Album doesn\t exist' });
let { identifier } = req.body;
if (identifier) {
if (!user.isAdmin) return res.status(401).json({ message: 'Only administrators can create custom links' });
if (!(/^[a-zA-Z0-9-_]+$/.test(identifier))) return res.status(400).json({ message: 'Only alphanumeric, dashes, and underscore characters are allowed' });
/*
Make sure that the id doesn't already exists in the database
*/
const idExists = await db
.table('links')
.where({ identifier })
.first();
if (idExists) return res.status(400).json({ message: 'Album with this identifier already exists' });
} else {
/*
Try to allocate a new identifier in the database
*/
identifier = await Util.getUniqueAlbumIdentifier();
if (!identifier) return res.status(500).json({ message: 'There was a problem allocating a link for your album' });
}
2018-09-16 05:56:13 +02:00
try {
const insertObj = {
2018-09-16 05:56:13 +02:00
identifier,
2018-09-18 08:34:00 +02:00
userId: user.id,
2018-09-16 05:56:13 +02:00
albumId,
2018-09-16 22:52:46 +02:00
enabled: true,
enableDownload: true,
2019-02-22 16:45:45 +01:00
expiresAt: null,
2020-12-24 09:40:50 +01:00
views: 0
};
await db.table('links').insert(insertObj).wasMutated();
2018-09-16 05:56:13 +02:00
return res.json({
message: 'The link was created successfully',
2020-12-24 09:40:50 +01:00
data: insertObj
2018-09-16 05:56:13 +02:00
});
} catch (error) {
2019-03-12 06:38:13 +01:00
return super.error(res, error);
2018-09-16 05:56:13 +02:00
}
}
}
module.exports = linkPOST;