uploadController.js 9.2 KB

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