aboutsummaryrefslogtreecommitdiff
path: root/src/api/routes/albums/link/linkPOST.js
blob: afa2505b2ca27ee598766b3b0a607a819c975ecc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const Route = require('../../../structures/Route');
const Util = require('../../../utils/Util');

class linkPOST extends Route {
	constructor() {
		super('/album/link/new', 'post', { canApiKey: true });
	}

	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' });

		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).wasMutated();

			return res.json({
				message: 'The link was created successfully',
				data: insertObj
			});
		} catch (error) {
			return super.error(res, error);
		}
	}
}

module.exports = linkPOST;