uploadController.js 8.8 KB

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