filesafe/controllers/utilsController.js

76 lines
2.2 KiB
JavaScript
Raw Normal View History

2017-10-04 00:13:38 +00:00
const path = require('path');
const config = require('../config.js');
const fs = require('fs');
2018-12-11 20:34:16 +00:00
const sharp = require('sharp');
2017-10-04 00:13:38 +00:00
const ffmpeg = require('fluent-ffmpeg');
const db = require('knex')(config.database);
2017-10-04 00:13:38 +00:00
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' : '')
2017-10-04 00:13:38 +00:00
+ date.getSeconds();
2018-04-26 06:50:35 +00:00
};
2017-10-04 00:13:38 +00:00
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) {
2017-10-04 00:13:38 +00:00
if (config.uploads.generateThumbnails !== true) return;
const ext = path.extname(file.name).toLowerCase();
2017-10-04 00:13:38 +00:00
let thumbname = path.join(__dirname, '..', config.uploads.folder, 'thumbs', file.name.slice(0, -ext.length) + '.png');
fs.access(thumbname, err => {
2017-03-18 04:36:50 +00:00
if (err && err.code === 'ENOENT') {
2017-09-24 03:54:13 +00:00
if (utilsController.videoExtensions.includes(ext)) {
2017-03-18 04:36:50 +00:00
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?'
})
2017-10-04 00:13:38 +00:00
.on('error', error => console.log('Error - ', error.message));
2017-03-18 04:36:50 +00:00
} else {
2018-11-30 21:58:42 +00:00
let resizeOptions = {
2017-03-18 04:36:50 +00:00
width: 200,
2018-11-30 21:58:42 +00:00
height: 200,
fit: 'contain',
background: {
r: 0,
g: 0,
b: 0,
alpha: 0
}
2017-10-04 00:13:38 +00:00
};
2018-11-30 21:58:42 +00:00
sharp(path.join(__dirname, '..', config.uploads.folder, file.name))
.resize(resizeOptions)
.toFile(thumbname)
.catch((error) => {
if (error) {
console.log('Error - ', error);
}
2017-10-04 00:13:38 +00:00
});
2017-03-18 04:36:50 +00:00
}
}
2017-10-04 00:13:38 +00:00
});
};
2017-10-04 00:13:38 +00:00
module.exports = utilsController;