uploadController.js 8.1 KB

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