utilsController.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const path = require('path');
  2. const config = require('../config.js');
  3. const fs = require('fs');
  4. const sharp = require('sharp');
  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 resizeOptions = {
  45. width: 200,
  46. height: 200,
  47. fit: 'contain',
  48. background: {
  49. r: 0,
  50. g: 0,
  51. b: 0,
  52. alpha: 0
  53. }
  54. };
  55. sharp(path.join(__dirname, '..', config.uploads.folder, file.name))
  56. .resize(resizeOptions)
  57. .toFile(thumbname)
  58. .catch((error) => {
  59. if (error) {
  60. console.log('Error - ', error);
  61. }
  62. });
  63. }
  64. }
  65. });
  66. };
  67. module.exports = utilsController;