aboutsummaryrefslogtreecommitdiff
path: root/controllers/utilsController.js
blob: 86c84b687560b09df1743f37fe5aeae8c6654985 (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
69
70
71
72
73
74
75
const path = require('path');
const config = require('../config.js');
const fs = require('fs');
const sharp = require('sharp');
const ffmpeg = require('fluent-ffmpeg');
const db = require('knex')(config.database);

const utilsController = {};
utilsController.imageExtensions = ['.jpg', '.jpeg', '.bmp', '.gif', '.png'];
utilsController.videoExtensions = ['.webm', '.mp4', '.wmv', '.avi', '.mov'];

utilsController.getPrettyDate = function(date) {
	return date.getFullYear() + '-'
		+ (date.getMonth() + 1) + '-'
		+ date.getDate() + ' '
		+ (date.getHours() < 10 ? '0' : '')
		+ date.getHours() + ':'
		+ (date.getMinutes() < 10 ? '0' : '')
		+ date.getMinutes() + ':'
		+ (date.getSeconds() < 10 ? '0' : '')
		+ date.getSeconds();
};

utilsController.authorize = async (req, res) => {
	const token = req.headers.token;
	if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' });

	const user = await db.table('users').where('token', token).first();
	if (!user) return res.status(401).json({ success: false, description: 'Invalid token' });
	return user;
};

utilsController.generateThumbs = function(file, basedomain) {
	if (config.uploads.generateThumbnails !== true) return;
	const ext = path.extname(file.name).toLowerCase();

	let thumbname = path.join(__dirname, '..', config.uploads.folder, 'thumbs', file.name.slice(0, -ext.length) + '.png');
	fs.access(thumbname, err => {
		if (err && err.code === 'ENOENT') {
			if (utilsController.videoExtensions.includes(ext)) {
				ffmpeg(path.join(__dirname, '..', config.uploads.folder, file.name))
					.thumbnail({
						timestamps: [0],
						filename: '%b.png',
						folder: path.join(__dirname, '..', config.uploads.folder, 'thumbs'),
						size: '200x?'
					})
					.on('error', error => console.log('Error - ', error.message));
			} else {
				let resizeOptions = {
					width: 200,
					height: 200,
					fit: 'contain',
					background: {
						r: 0,
						g: 0,
						b: 0,
						alpha: 0
					}
				};

				sharp(path.join(__dirname, '..', config.uploads.folder, file.name))
					.resize(resizeOptions)
					.toFile(thumbname)
					.catch((error) => {
						if (error) {
							console.log('Error - ', error);
						}
					});
			}
		}
	});
};

module.exports = utilsController;