utilsController.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const path = require('path');
  2. const config = require('../config.js');
  3. const fs = require('fs');
  4. const gm = require('gm');
  5. const ffmpeg = require('fluent-ffmpeg');
  6. const db = require('knex')(config.database);
  7. const utilsController = {};
  8. utilsController.imageExtensions = ['.jpg', '.jpeg', '.bmp', '.gif', '.png'];
  9. utilsController.videoExtensions = ['.webm', '.mp4', '.wmv', '.avi', '.mov'];
  10. utilsController.getPrettyDate = function(date) {
  11. return date.getFullYear() + '-'
  12. + (date.getMonth() + 1) + '-'
  13. + date.getDate() + ' '
  14. + (date.getHours() < 10 ? '0' : '')
  15. + date.getHours() + ':'
  16. + (date.getMinutes() < 10 ? '0' : '')
  17. + date.getMinutes() + ':'
  18. + (date.getSeconds() < 10 ? '0' : '')
  19. + date.getSeconds();
  20. };
  21. utilsController.authorize = async (req, res) => {
  22. const token = req.headers.token;
  23. if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' });
  24. const user = await db.table('users').where('token', token).first();
  25. if (!user) return res.status(401).json({ success: false, description: 'Invalid token' });
  26. return user;
  27. };
  28. utilsController.generateThumbs = function(file, basedomain) {
  29. if (config.uploads.generateThumbnails !== true) return;
  30. const ext = path.extname(file.name).toLowerCase();
  31. let thumbname = path.join(__dirname, '..', config.uploads.folder, 'thumbs', file.name.slice(0, -ext.length) + '.png');
  32. fs.access(thumbname, err => {
  33. if (err && err.code === 'ENOENT') {
  34. if (utilsController.videoExtensions.includes(ext)) {
  35. ffmpeg(path.join(__dirname, '..', config.uploads.folder, file.name))
  36. .thumbnail({
  37. timestamps: [0],
  38. filename: '%b.png',
  39. folder: path.join(__dirname, '..', config.uploads.folder, 'thumbs'),
  40. size: '200x?'
  41. })
  42. .on('error', error => console.log('Error - ', error.message));
  43. } else {
  44. let size = {
  45. width: 200,
  46. height: 200
  47. };
  48. gm(path.join(__dirname, '..', config.uploads.folder, file.name))
  49. .resize(size.width, size.height + '>')
  50. .gravity('Center')
  51. .extent(size.width, size.height)
  52. .background('transparent')
  53. .write(thumbname, error => {
  54. if (error) console.log('Error - ', error);
  55. });
  56. }
  57. }
  58. });
  59. };
  60. module.exports = utilsController;