uploadController.js 9.4 KB

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