uploadController.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. for (let i = 0; i < maxTries; i++) {
  19. const name = randomstring.generate(config.uploads.fileLength) + path.extname(file.originalname);
  20. try {
  21. fs.accessSync(path.join(uploadDir, name));
  22. console.log(`A file named "${name}" already exists (${i + 1}/${maxTries}).`);
  23. } catch (err) {
  24. // Note: fs.accessSync() will throw an Error if a file with the same name does not exist
  25. return cb(null, name);
  26. }
  27. }
  28. return cb('Could not allocate a unique file name. Try again?');
  29. }
  30. });
  31. const upload = multer({
  32. storage: storage,
  33. limits: { fileSize: config.uploads.maxSize },
  34. fileFilter: function(req, file, cb) {
  35. if (config.blockedExtensions !== undefined) {
  36. if (config.blockedExtensions.some(extension => path.extname(file.originalname).toLowerCase() === extension)) {
  37. return cb('This file extension is not allowed');
  38. }
  39. return cb(null, true);
  40. }
  41. return cb(null, true);
  42. }
  43. }).array('files[]');
  44. uploadsController.upload = async (req, res, next) => {
  45. if (config.private === true) {
  46. await utils.authorize(req, res);
  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, album) => {
  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: album,
  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);
  114. }
  115. iteration++;
  116. });
  117. });
  118. });
  119. };
  120. uploadsController.processFilesForDisplay = async (req, res, files, existingFiles) => {
  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. res.json({
  137. success: true,
  138. files: files.map(file => {
  139. return {
  140. name: file.name,
  141. size: file.size,
  142. url: `${basedomain}/${file.name}`
  143. };
  144. })
  145. });
  146. for (let file of files) {
  147. let ext = path.extname(file.name).toLowerCase();
  148. if (utils.imageExtensions.includes(ext) || utils.videoExtensions.includes(ext)) {
  149. file.thumb = `${basedomain}/thumbs/${file.name.slice(0, -ext.length)}.png`;
  150. utils.generateThumbs(file);
  151. }
  152. if (file.albumid) {
  153. db.table('albums').where('id', file.albumid).update('editedAt', file.timestamp).then(() => {})
  154. .catch(error => { console.log(error); res.json({ success: false, description: 'Error updating album' }); });
  155. }
  156. }
  157. };
  158. uploadsController.delete = async (req, res) => {
  159. const user = await utils.authorize(req, res);
  160. const id = req.body.id;
  161. if (id === undefined || id === '') {
  162. return res.json({ success: false, description: 'No file specified' });
  163. }
  164. const file = await db.table('files')
  165. .where('id', id)
  166. .where(function() {
  167. if (user.username !== 'root') {
  168. this.where('userid', user.id);
  169. }
  170. })
  171. .first();
  172. try {
  173. await uploadsController.deleteFile(file.name);
  174. await db.table('files').where('id', id).del();
  175. if (file.albumid) {
  176. await db.table('albums').where('id', file.albumid).update('editedAt', Math.floor(Date.now() / 1000));
  177. }
  178. } catch (err) {
  179. console.log(err);
  180. }
  181. return res.json({ success: true });
  182. };
  183. uploadsController.deleteFile = function(file) {
  184. const ext = path.extname(file).toLowerCase();
  185. return new Promise((resolve, reject) => {
  186. fs.stat(path.join(__dirname, '..', config.uploads.folder, file), (err, stats) => {
  187. if (err) { return reject(err); }
  188. fs.unlink(path.join(__dirname, '..', config.uploads.folder, file), err => {
  189. if (err) { return reject(err); }
  190. if (!utils.imageExtensions.includes(ext) && !utils.videoExtensions.includes(ext)) {
  191. return resolve();
  192. }
  193. file = file.substr(0, file.lastIndexOf('.')) + '.png';
  194. fs.stat(path.join(__dirname, '..', config.uploads.folder, 'thumbs/', file), (err, stats) => {
  195. if (err) {
  196. console.log(err);
  197. return resolve();
  198. }
  199. fs.unlink(path.join(__dirname, '..', config.uploads.folder, 'thumbs/', file), err => {
  200. if (err) { return reject(err); }
  201. return resolve();
  202. });
  203. });
  204. });
  205. });
  206. });
  207. };
  208. uploadsController.list = async (req, res) => {
  209. const user = await utils.authorize(req, res);
  210. let offset = req.params.page;
  211. if (offset === undefined) offset = 0;
  212. const files = await db.table('files')
  213. .where(function() {
  214. if (req.params.id === undefined) this.where('id', '<>', '');
  215. else this.where('albumid', req.params.id);
  216. })
  217. .where(function() {
  218. if (user.username !== 'root') this.where('userid', user.id);
  219. })
  220. .orderBy('id', 'DESC')
  221. .limit(25)
  222. .offset(25 * offset)
  223. .select('id', 'albumid', 'timestamp', 'name', 'userid');
  224. const albums = await db.table('albums');
  225. let basedomain = config.domain;
  226. let userids = [];
  227. for (let file of files) {
  228. file.file = `${basedomain}/${file.name}`;
  229. file.date = new Date(file.timestamp * 1000);
  230. file.date = utils.getPrettyDate(file.date);
  231. file.album = '';
  232. if (file.albumid !== undefined) {
  233. for (let album of albums) {
  234. if (file.albumid === album.id) {
  235. file.album = album.name;
  236. }
  237. }
  238. }
  239. // Only push usernames if we are root
  240. if (user.username === 'root') {
  241. if (file.userid !== undefined && file.userid !== null && file.userid !== '') {
  242. userids.push(file.userid);
  243. }
  244. }
  245. let ext = path.extname(file.name).toLowerCase();
  246. if (utils.imageExtensions.includes(ext) || utils.videoExtensions.includes(ext)) {
  247. file.thumb = `${basedomain}/thumbs/${file.name.slice(0, -ext.length)}.png`;
  248. }
  249. }
  250. // If we are a normal user, send response
  251. if (user.username !== 'root') return res.json({ success: true, files });
  252. // If we are root but there are no uploads attached to a user, send response
  253. if (userids.length === 0) return res.json({ success: true, files });
  254. const users = await db.table('users').whereIn('id', userids);
  255. for (let dbUser of users) {
  256. for (let file of files) {
  257. if (file.userid === dbUser.id) {
  258. file.username = dbUser.username;
  259. }
  260. }
  261. }
  262. return res.json({ success: true, files });
  263. };
  264. module.exports = uploadsController;