utilsController.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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.getUser = async (req) => {
  22. const token = req.headers.token;
  23. if(token === undefined) return null;
  24. return await db.table('users').where('token', token).first();
  25. };
  26. utilsController.authorize = async (req, res) => {
  27. const token = req.headers.token;
  28. if (token === undefined) return {user: null, response: res.status(401).json({ success: false, description: 'No token provided' })};
  29. const user = await db.table('users').where('token', token).first();
  30. if (!user) return {user: null, response: res.status(401).json({ success: false, description: 'Invalid token' })};
  31. return {user: user, response: null};
  32. };
  33. utilsController.generateThumbs = function(file, basedomain) {
  34. if (config.uploads.generateThumbnails !== true) return;
  35. const ext = path.extname(file.name).toLowerCase();
  36. let thumbname = path.join(__dirname, '..', config.uploads.folder, 'thumbs', file.name.slice(0, -ext.length) + '.png');
  37. fs.access(thumbname, err => {
  38. if (err && err.code === 'ENOENT') {
  39. if (utilsController.videoExtensions.includes(ext)) {
  40. ffmpeg(path.join(__dirname, '..', config.uploads.folder, file.name))
  41. .thumbnail({
  42. timestamps: [0],
  43. filename: '%b.png',
  44. folder: path.join(__dirname, '..', config.uploads.folder, 'thumbs'),
  45. size: '200x?'
  46. })
  47. .on('error', error => console.log('Error - ', error.message));
  48. } else {
  49. let resizeOptions = {
  50. width: 200,
  51. height: 200,
  52. fit: 'contain',
  53. background: {
  54. r: 0,
  55. g: 0,
  56. b: 0,
  57. alpha: 0
  58. }
  59. };
  60. sharp(path.join(__dirname, '..', config.uploads.folder, file.name))
  61. .resize(resizeOptions)
  62. .toFile(thumbname)
  63. .catch((error) => {
  64. if (error) {
  65. console.log('Error - ', error);
  66. }
  67. });
  68. }
  69. }
  70. });
  71. };
  72. module.exports = utilsController;