uploadController.js 8.7 KB

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