uploadController.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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, album) => {
  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: album,
  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);
  113. }
  114. iteration++;
  115. });
  116. });
  117. });
  118. };
  119. uploadsController.processFilesForDisplay = async (req, res, files, existingFiles) => {
  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. res.json({
  136. success: true,
  137. files: files.map(file => {
  138. return {
  139. name: file.name,
  140. size: file.size,
  141. url: `${basedomain}/${file.name}`
  142. };
  143. })
  144. });
  145. for (let file of files) {
  146. let ext = path.extname(file.name).toLowerCase();
  147. if (utils.imageExtensions.includes(ext) || utils.videoExtensions.includes(ext)) {
  148. file.thumb = `${basedomain}/thumbs/${file.name.slice(0, -ext.length)}.png`;
  149. utils.generateThumbs(file);
  150. }
  151. if (file.albumid) {
  152. db.table('albums').where('id', file.albumid).update('editedAt', file.timestamp).then(() => {})
  153. .catch(error => { console.log(error); res.json({ success: false, description: 'Error updating album' }); });
  154. }
  155. }
  156. };
  157. uploadsController.delete = async (req, res) => {
  158. const user = await utils.authorize(req, res);
  159. const id = req.body.id;
  160. if (id === undefined || id === '') {
  161. return res.json({ success: false, description: 'No file specified' });
  162. }
  163. const file = await db.table('files')
  164. .where('id', id)
  165. .where(function() {
  166. if (user.username !== 'root') {
  167. this.where('userid', user.id);
  168. }
  169. })
  170. .first();
  171. try {
  172. await uploadsController.deleteFile(file.name);
  173. await db.table('files').where('id', id).del();
  174. if (file.albumid) {
  175. await db.table('albums').where('id', file.albumid).update('editedAt', Math.floor(Date.now() / 1000));
  176. }
  177. } catch (err) {
  178. console.log(err);
  179. }
  180. return res.json({ success: true });
  181. };
  182. uploadsController.deleteFile = function(file) {
  183. const ext = path.extname(file).toLowerCase();
  184. return new Promise((resolve, reject) => {
  185. fs.stat(path.join(__dirname, '..', config.uploads.folder, file), (err, stats) => {
  186. if (err) { return reject(err); }
  187. fs.unlink(path.join(__dirname, '..', config.uploads.folder, file), err => {
  188. if (err) { return reject(err); }
  189. if (!utils.imageExtensions.includes(ext) && !utils.videoExtensions.includes(ext)) {
  190. return resolve();
  191. }
  192. file = file.substr(0, file.lastIndexOf('.')) + '.png';
  193. fs.stat(path.join(__dirname, '..', config.uploads.folder, 'thumbs/', file), (err, stats) => {
  194. if (err) {
  195. console.log(err);
  196. return resolve();
  197. }
  198. fs.unlink(path.join(__dirname, '..', config.uploads.folder, 'thumbs/', file), err => {
  199. if (err) { return reject(err); }
  200. return resolve();
  201. });
  202. });
  203. });
  204. });
  205. });
  206. };
  207. uploadsController.list = async (req, res) => {
  208. const user = await utils.authorize(req, res);
  209. let offset = req.params.page;
  210. if (offset === undefined) offset = 0;
  211. const files = await db.table('files')
  212. .where(function() {
  213. if (req.params.id === undefined) this.where('id', '<>', '');
  214. else this.where('albumid', req.params.id);
  215. })
  216. .where(function() {
  217. if (user.username !== 'root') this.where('userid', user.id);
  218. })
  219. .orderBy('id', 'DESC')
  220. .limit(25)
  221. .offset(25 * offset)
  222. .select('id', 'albumid', 'timestamp', 'name', 'userid');
  223. const albums = await db.table('albums');
  224. let basedomain = config.domain;
  225. let userids = [];
  226. for (let file of files) {
  227. file.file = `${basedomain}/${file.name}`;
  228. file.date = new Date(file.timestamp * 1000);
  229. file.date = utils.getPrettyDate(file.date);
  230. file.album = '';
  231. if (file.albumid !== undefined) {
  232. for (let album of albums) {
  233. if (file.albumid === album.id) {
  234. file.album = album.name;
  235. }
  236. }
  237. }
  238. // Only push usernames if we are root
  239. if (user.username === 'root') {
  240. if (file.userid !== undefined && file.userid !== null && file.userid !== '') {
  241. userids.push(file.userid);
  242. }
  243. }
  244. let ext = path.extname(file.name).toLowerCase();
  245. if (utils.imageExtensions.includes(ext) || utils.videoExtensions.includes(ext)) {
  246. file.thumb = `${basedomain}/thumbs/${file.name.slice(0, -ext.length)}.png`;
  247. }
  248. }
  249. // If we are a normal user, send response
  250. if (user.username !== 'root') return res.json({ success: true, files });
  251. // If we are root but there are no uploads attached to a user, send response
  252. if (userids.length === 0) return res.json({ success: true, files });
  253. const users = await db.table('users').whereIn('id', userids);
  254. for (let dbUser of users) {
  255. for (let file of files) {
  256. if (file.userid === dbUser.id) {
  257. file.username = dbUser.username;
  258. }
  259. }
  260. }
  261. return res.json({ success: true, files });
  262. };
  263. module.exports = uploadsController;