uploadController.js 10 KB

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