uploadController.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. const config = require('../config.js');
  2. const path = require('path');
  3. const multer = require('multer');
  4. const randomstring = require('randomstring');
  5. const db = require('knex')(config.database);
  6. const crypto = require('crypto');
  7. const fs = require('fs');
  8. const utils = require('./utilsController.js');
  9. const uploadsController = {};
  10. const storage = multer.diskStorage({
  11. destination: function(req, file, cb) {
  12. cb(null, path.join(__dirname, '..', config.uploads.folder));
  13. },
  14. filename: function(req, file, cb) {
  15. cb(null, randomstring.generate(config.uploads.fileLength) + path.extname(file.originalname));
  16. }
  17. });
  18. const upload = multer({
  19. storage: storage,
  20. limits: { fileSize: config.uploads.maxSize },
  21. fileFilter: function(req, file, cb) {
  22. if (config.blockedExtensions !== undefined) {
  23. if (config.blockedExtensions.some(extension => path.extname(file.originalname).toLowerCase() === extension)) {
  24. return cb('This file extension is not allowed');
  25. }
  26. return cb(null, true);
  27. }
  28. return cb(null, true);
  29. }
  30. }).array('files[]');
  31. uploadsController.upload = async (req, res, next) => {
  32. if (config.private === true) {
  33. await utils.authorize(req, res);
  34. }
  35. const token = req.headers.token || '';
  36. const user = await db.table('users').where('token', token).first();
  37. const albumid = req.headers.albumid || req.params.albumid;
  38. if (albumid && user) {
  39. const album = await db.table('albums').where({ id: albumid, userid: user.id }).first();
  40. if (!album) {
  41. return res.json({
  42. success: false,
  43. description: 'Album doesn\'t exist or it doesn\'t belong to the user'
  44. });
  45. }
  46. return uploadsController.actuallyUpload(req, res, user.id, albumid);
  47. }
  48. return uploadsController.actuallyUpload(req, res, user.id, albumid);
  49. };
  50. uploadsController.actuallyUpload = async (req, res, userid, album) => {
  51. upload(req, res, async err => {
  52. if (err) {
  53. console.error(err);
  54. return res.json({ success: false, description: err });
  55. }
  56. if (req.files.length === 0) return res.json({ success: false, description: 'no-files' });
  57. const files = [];
  58. const existingFiles = [];
  59. let iteration = 1;
  60. req.files.forEach(async file => {
  61. // Check if the file exists by checking hash and size
  62. let hash = crypto.createHash('md5');
  63. let stream = fs.createReadStream(path.join(__dirname, '..', config.uploads.folder, file.filename));
  64. stream.on('data', data => {
  65. hash.update(data, 'utf8');
  66. });
  67. stream.on('end', async () => {
  68. const fileHash = hash.digest('hex');
  69. const dbFile = await db.table('files')
  70. .where(function() {
  71. if (userid === undefined) this.whereNull('userid');
  72. else this.where('userid', userid);
  73. })
  74. .where({
  75. hash: fileHash,
  76. size: file.size
  77. })
  78. .first();
  79. if (!dbFile) {
  80. files.push({
  81. name: file.filename,
  82. original: file.originalname,
  83. type: file.mimetype,
  84. size: file.size,
  85. hash: fileHash,
  86. ip: req.ip,
  87. albumid: album,
  88. userid: userid,
  89. timestamp: Math.floor(Date.now() / 1000)
  90. });
  91. } else {
  92. uploadsController.deleteFile(file.filename).then(() => {}).catch(err => console.error(err));
  93. existingFiles.push(dbFile);
  94. }
  95. if (iteration === req.files.length) {
  96. return uploadsController.processFilesForDisplay(req, res, files, existingFiles);
  97. }
  98. iteration++;
  99. });
  100. });
  101. });
  102. };
  103. uploadsController.processFilesForDisplay = async (req, res, files, existingFiles) => {
  104. let basedomain = config.domain;
  105. if (files.length === 0) {
  106. return res.json({
  107. success: true,
  108. files: existingFiles.map(file => {
  109. return {
  110. name: file.name,
  111. size: file.size,
  112. url: `${basedomain}/${file.name}`
  113. };
  114. })
  115. });
  116. }
  117. await db.table('files').insert(files);
  118. for (let efile of existingFiles) files.push(efile);
  119. res.json({
  120. success: true,
  121. files: files.map(file => {
  122. return {
  123. name: file.name,
  124. size: file.size,
  125. url: `${basedomain}/${file.name}`
  126. };
  127. })
  128. });
  129. for (let file of files) {
  130. let ext = path.extname(file.name).toLowerCase();
  131. if (utils.imageExtensions.includes(ext) || utils.videoExtensions.includes(ext)) {
  132. file.thumb = `${basedomain}/thumbs/${file.name.slice(0, -ext.length)}.png`;
  133. utils.generateThumbs(file);
  134. }
  135. if (file.albumid) {
  136. db.table('albums').where('id', file.albumid).update('editedAt', file.timestamp).then(() => {})
  137. .catch(error => { console.log(error); res.json({ success: false, description: 'Error updating album' }); });
  138. }
  139. }
  140. };
  141. uploadsController.delete = async (req, res) => {
  142. const user = await utils.authorize(req, res);
  143. const id = req.body.id;
  144. if (id === undefined || id === '') {
  145. return res.json({ success: false, description: 'No file specified' });
  146. }
  147. const file = await db.table('files')
  148. .where('id', id)
  149. .where(function() {
  150. if (user.username !== 'root') {
  151. this.where('userid', user.id);
  152. }
  153. })
  154. .first();
  155. try {
  156. await uploadsController.deleteFile(file.name);
  157. await db.table('files').where('id', id).del();
  158. if (file.albumid) {
  159. await db.table('albums').where('id', file.albumid).update('editedAt', Math.floor(Date.now() / 1000));
  160. }
  161. } catch (err) {
  162. console.log(err);
  163. }
  164. return res.json({ success: true });
  165. };
  166. uploadsController.deleteFile = function(file) {
  167. const ext = path.extname(file).toLowerCase();
  168. return new Promise((resolve, reject) => {
  169. fs.stat(path.join(__dirname, '..', config.uploads.folder, file), (err, stats) => {
  170. if (err) { return reject(err); }
  171. fs.unlink(path.join(__dirname, '..', config.uploads.folder, file), err => {
  172. if (err) { return reject(err); }
  173. if (!utils.imageExtensions.includes(ext) && !utils.videoExtensions.includes(ext)) {
  174. return resolve();
  175. }
  176. file = file.substr(0, file.lastIndexOf('.')) + '.png';
  177. fs.stat(path.join(__dirname, '..', config.uploads.folder, 'thumbs/', file), (err, stats) => {
  178. if (err) {
  179. console.log(err);
  180. return resolve();
  181. }
  182. fs.unlink(path.join(__dirname, '..', config.uploads.folder, 'thumbs/', file), err => {
  183. if (err) { return reject(err); }
  184. return resolve();
  185. });
  186. });
  187. });
  188. });
  189. });
  190. };
  191. uploadsController.list = async (req, res) => {
  192. const user = await utils.authorize(req, res);
  193. let offset = req.params.page;
  194. if (offset === undefined) offset = 0;
  195. const files = await db.table('files')
  196. .where(function() {
  197. if (req.params.id === undefined) this.where('id', '<>', '');
  198. else this.where('albumid', req.params.id);
  199. })
  200. .where(function() {
  201. if (user.username !== 'root') this.where('userid', user.id);
  202. })
  203. .orderBy('id', 'DESC')
  204. .limit(25)
  205. .offset(25 * offset)
  206. .select('id', 'albumid', 'timestamp', 'name', 'userid');
  207. const albums = await db.table('albums');
  208. let basedomain = config.domain;
  209. let userids = [];
  210. for (let file of files) {
  211. file.file = `${basedomain}/${file.name}`;
  212. file.date = new Date(file.timestamp * 1000);
  213. file.date = utils.getPrettyDate(file.date);
  214. file.album = '';
  215. if (file.albumid !== undefined) {
  216. for (let album of albums) {
  217. if (file.albumid === album.id) {
  218. file.album = album.name;
  219. }
  220. }
  221. }
  222. // Only push usernames if we are root
  223. if (user.username === 'root') {
  224. if (file.userid !== undefined && file.userid !== null && file.userid !== '') {
  225. userids.push(file.userid);
  226. }
  227. }
  228. let ext = path.extname(file.name).toLowerCase();
  229. if (utils.imageExtensions.includes(ext) || utils.videoExtensions.includes(ext)) {
  230. file.thumb = `${basedomain}/thumbs/${file.name.slice(0, -ext.length)}.png`;
  231. }
  232. }
  233. // If we are a normal user, send response
  234. if (user.username !== 'root') return res.json({ success: true, files });
  235. // If we are root but there are no uploads attached to a user, send response
  236. if (userids.length === 0) return res.json({ success: true, files });
  237. const users = await db.table('users').whereIn('id', userids);
  238. for (let dbUser of users) {
  239. for (let file of files) {
  240. if (file.userid === dbUser.id) {
  241. file.username = dbUser.username;
  242. }
  243. }
  244. }
  245. return res.json({ success: true, files });
  246. };
  247. module.exports = uploadsController;