uploadController.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. const path = require('path')
  2. const config = require('../config.js')
  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. let uploadsController = {}
  9. const storage = multer.diskStorage({
  10. destination: function (req, file, cb) {
  11. cb(null, './' + config.uploads.folder + '/')
  12. },
  13. filename: function (req, file, cb) {
  14. cb(null, randomstring.generate(config.uploads.fileLength) + path.extname(file.originalname))
  15. }
  16. })
  17. const upload = multer({
  18. storage: storage,
  19. limits: { fileSize: config.uploads.maxSize }
  20. }).array('files[]')
  21. uploadsController.upload = function(req, res, next){
  22. if(config.private === true)
  23. if(req.headers.auth !== config.clientToken)
  24. return res.status(401).json({ success: false, description: 'not-authorized'})
  25. let album = req.params.albumid
  26. if(album !== undefined)
  27. if(req.headers.adminauth !== config.adminToken)
  28. return res.status(401).json({ success: false, description: 'not-authorized'})
  29. upload(req, res, function (err) {
  30. if (err) {
  31. console.error(err)
  32. return res.json({
  33. success: false,
  34. description: err
  35. })
  36. }
  37. if(req.files.length === 0) return res.json({ success: false, description: 'no-files' })
  38. let files = []
  39. let existingFiles = []
  40. let iteration = 1
  41. req.files.forEach(function(file) {
  42. // Check if the file exists by checking hash and size
  43. let hash = crypto.createHash('md5')
  44. let stream = fs.createReadStream('./' + config.uploads.folder + '/' + file.filename)
  45. stream.on('data', function (data) {
  46. hash.update(data, 'utf8')
  47. })
  48. stream.on('end', function () {
  49. let fileHash = hash.digest('hex') // 34f7a3113803f8ed3b8fd7ce5656ebec
  50. db.table('files').where({
  51. hash: fileHash,
  52. size: file.size
  53. }).then((dbfile) => {
  54. if(dbfile.length !== 0){
  55. uploadsController.deleteFile(file.filename).then(() => {}).catch((e) => console.error(e))
  56. existingFiles.push(dbfile[0])
  57. }else{
  58. files.push({
  59. name: file.filename,
  60. original: file.originalname,
  61. type: file.mimetype,
  62. size: file.size,
  63. hash: fileHash,
  64. ip: req.ip,
  65. albumid: album,
  66. timestamp: Math.floor(Date.now() / 1000)
  67. })
  68. }
  69. if(iteration === req.files.length)
  70. return something(req, res, files, existingFiles)
  71. iteration++
  72. })
  73. })
  74. })
  75. })
  76. }
  77. function something(req, res, files, existingFiles){
  78. let basedomain = req.get('host')
  79. for(let domain of config.domains)
  80. if(domain.host === req.get('host'))
  81. if(domain.hasOwnProperty('resolve'))
  82. basedomain = domain.resolve
  83. if(files.length === 0){
  84. return res.json({
  85. success: true,
  86. files: existingFiles.map(file => {
  87. return {
  88. name: file.name,
  89. size: file.size,
  90. url: 'http://' + basedomain + '/' + file.name
  91. }
  92. })
  93. })
  94. }
  95. db.table('files').insert(files).then(() => {
  96. for(let efile of existingFiles) files.push(efile)
  97. res.json({
  98. success: true,
  99. files: files.map(file => {
  100. return {
  101. name: file.name,
  102. size: file.size,
  103. url: 'http://' + basedomain + '/' + file.name
  104. }
  105. })
  106. })
  107. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  108. }
  109. uploadsController.delete = function(req, res){
  110. if(req.headers.auth !== config.adminToken)
  111. return res.status(401).json({ success: false, description: 'not-authorized'})
  112. let id = req.body.id
  113. if(id === undefined || id === '')
  114. return res.json({ success: false, description: 'No file specified' })
  115. db.table('files').where('id', id).then((file) => {
  116. fs.stat('./' + config.uploads.folder + '/' + file[0].name, function (err, stats) {
  117. if (err) { return res.json({ success: false, description: err.toString() }) }
  118. fs.unlink('./' + config.uploads.folder + '/' + file[0].name, function(err){
  119. if (err) { return res.json({ success: false, description: err.toString() }) }
  120. db.table('files').where('id', id).del().then(() =>{
  121. return res.json({ success: true })
  122. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  123. })
  124. })
  125. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  126. }
  127. uploadsController.deleteFile = function(file){
  128. return new Promise(function(resolve, reject){
  129. fs.stat('./' + config.uploads.folder + '/' + file, function (err, stats) {
  130. if (err) { return reject(err) }
  131. fs.unlink('./' + config.uploads.folder + '/' + file, function(err){
  132. if (err) { return reject(err) }
  133. return resolve()
  134. })
  135. })
  136. })
  137. }
  138. uploadsController.list = function(req, res){
  139. if(req.headers.auth !== config.adminToken)
  140. return res.status(401).json({ success: false, description: 'not-authorized'})
  141. db.table('files')
  142. .where(function(){
  143. if(req.params.id === undefined)
  144. this.where('id', '<>', '')
  145. else
  146. this.where('albumid', req.params.id)
  147. })
  148. .orderBy('id', 'DESC')
  149. .then((files) => {
  150. db.table('albums').then((albums) => {
  151. let basedomain = req.get('host')
  152. for(let domain of config.domains)
  153. if(domain.host === req.get('host'))
  154. if(domain.hasOwnProperty('resolve'))
  155. basedomain = domain.resolve
  156. for(let file of files){
  157. file.file = 'http://' + basedomain + '/' + file.name
  158. file.date = new Date(file.timestamp * 1000)
  159. 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()
  160. file.album = ''
  161. if(file.albumid !== undefined)
  162. for(let album of albums)
  163. if(file.albumid === album.id)
  164. file.album = album.name
  165. }
  166. return res.json({
  167. success: true,
  168. files
  169. })
  170. })
  171. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  172. }
  173. module.exports = uploadsController