diff options
Diffstat (limited to 'src/api/routes/albums/link/linkPOST.js')
| -rw-r--r-- | src/api/routes/albums/link/linkPOST.js | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/src/api/routes/albums/link/linkPOST.js b/src/api/routes/albums/link/linkPOST.js new file mode 100644 index 0000000..28e9dfe --- /dev/null +++ b/src/api/routes/albums/link/linkPOST.js @@ -0,0 +1,78 @@ +const Route = require('../../../structures/Route'); +const Util = require('../../../utils/Util'); + +class linkPOST extends Route { + constructor() { + super('/album/link/new', 'post'); + } + + async run(req, res, db, user) { + if (!req.body) return res.status(400).json({ message: 'No body provided' }); + const { albumId } = req.body; + if (!albumId) return res.status(400).json({ message: 'No album provided' }); + + /* + Make sure the album exists + */ + const exists = await db + .table('albums') + .where({ id: albumId, userId: user.id }) + .first(); + if (!exists) return res.status(400).json({ message: 'Album doesn\t exist' }); + + /* + Count the amount of links created for that album already and error out if max was reached + */ + const count = await db + .table('links') + .where('albumId', albumId) + .count({ count: 'id' }) + .first(); + if (count >= parseInt(process.env.MAX_LINKS_PER_ALBUM, 10)) return res.status(400).json({ message: 'Maximum links per album reached' }); + + 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' }); + } + + try { + const insertObj = { + identifier, + userId: user.id, + albumId, + enabled: true, + enableDownload: true, + expiresAt: null, + views: 0 + }; + await db.table('links').insert(insertObj); + + return res.json({ + message: 'The link was created successfully', + data: insertObj + }); + } catch (error) { + return super.error(res, error); + } + } +} + +module.exports = linkPOST; |