uploadController.js 9.3 KB

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