uploadController.js 9.7 KB

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