uploadController.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. const gm = require('gm')
  9. let uploadsController = {}
  10. const storage = multer.diskStorage({
  11. destination: function (req, file, cb) {
  12. cb(null, './' + 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. }).array('files[]')
  22. uploadsController.upload = function(req, res, next){
  23. if(config.private === true)
  24. if(req.headers.auth !== config.clientToken)
  25. return res.status(401).json({ success: false, description: 'not-authorized'})
  26. let album = req.params.albumid
  27. if(album !== undefined)
  28. if(req.headers.adminauth !== config.adminToken)
  29. return res.status(401).json({ success: false, description: 'not-authorized'})
  30. upload(req, res, function (err) {
  31. if (err) {
  32. console.error(err)
  33. return res.json({
  34. success: false,
  35. description: err
  36. })
  37. }
  38. if(req.files.length === 0) return res.json({ success: false, description: 'no-files' })
  39. let files = []
  40. let existingFiles = []
  41. let iteration = 1
  42. req.files.forEach(function(file) {
  43. // Check if the file exists by checking hash and size
  44. let hash = crypto.createHash('md5')
  45. let stream = fs.createReadStream('./' + config.uploads.folder + '/' + file.filename)
  46. stream.on('data', function (data) {
  47. hash.update(data, 'utf8')
  48. })
  49. stream.on('end', function () {
  50. let fileHash = hash.digest('hex') // 34f7a3113803f8ed3b8fd7ce5656ebec
  51. db.table('files').where({
  52. hash: fileHash,
  53. size: file.size
  54. }).then((dbfile) => {
  55. if(dbfile.length !== 0){
  56. uploadsController.deleteFile(file.filename).then(() => {}).catch((e) => console.error(e))
  57. existingFiles.push(dbfile[0])
  58. }else{
  59. files.push({
  60. name: file.filename,
  61. original: file.originalname,
  62. type: file.mimetype,
  63. size: file.size,
  64. hash: fileHash,
  65. ip: req.ip,
  66. albumid: album,
  67. timestamp: Math.floor(Date.now() / 1000)
  68. })
  69. }
  70. if(iteration === req.files.length)
  71. return uploadsController.processFilesForDisplay(req, res, files, existingFiles)
  72. iteration++
  73. })
  74. })
  75. })
  76. })
  77. }
  78. uploadsController.processFilesForDisplay = function(req, res, files, existingFiles){
  79. let basedomain = req.get('host')
  80. for(let domain of config.domains)
  81. if(domain.host === req.get('host'))
  82. if(domain.hasOwnProperty('resolve'))
  83. basedomain = domain.resolve
  84. if(files.length === 0){
  85. return res.json({
  86. success: true,
  87. files: existingFiles.map(file => {
  88. return {
  89. name: file.name,
  90. size: file.size,
  91. url: basedomain + '/' + file.name
  92. }
  93. })
  94. })
  95. }
  96. db.table('files').insert(files).then(() => {
  97. for(let efile of existingFiles) files.push(efile)
  98. res.json({
  99. success: true,
  100. files: files.map(file => {
  101. return {
  102. name: file.name,
  103. size: file.size,
  104. url: basedomain + '/' + file.name
  105. }
  106. })
  107. })
  108. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  109. }
  110. uploadsController.delete = function(req, res){
  111. if(req.headers.auth !== config.adminToken)
  112. return res.status(401).json({ success: false, description: 'not-authorized'})
  113. let id = req.body.id
  114. if(id === undefined || id === '')
  115. return res.json({ success: false, description: 'No file specified' })
  116. db.table('files').where('id', id).then((file) => {
  117. uploadsController.deleteFile(file[0].name).then(() => {
  118. db.table('files').where('id', id).del().then(() =>{
  119. return res.json({ success: true })
  120. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  121. }).catch((e) => {
  122. console.log(e.toString())
  123. db.table('files').where('id', id).del().then(() =>{
  124. return res.json({ success: true })
  125. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  126. })
  127. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  128. }
  129. uploadsController.deleteFile = function(file){
  130. return new Promise(function(resolve, reject){
  131. fs.stat('./' + config.uploads.folder + '/' + file, function (err, stats) {
  132. if (err) { return reject(err) }
  133. fs.unlink('./' + config.uploads.folder + '/' + file, function(err){
  134. if (err) { return reject(err) }
  135. return resolve()
  136. })
  137. })
  138. })
  139. }
  140. uploadsController.list = function(req, res){
  141. if(req.headers.auth !== config.adminToken)
  142. return res.status(401).json({ success: false, description: 'not-authorized'})
  143. let offset = req.params.page
  144. if(offset === undefined) offset = 0
  145. db.table('files')
  146. .where(function(){
  147. if(req.params.id === undefined)
  148. this.where('id', '<>', '')
  149. else
  150. this.where('albumid', req.params.id)
  151. })
  152. .orderBy('id', 'DESC')
  153. .limit(25)
  154. .offset(25 * offset)
  155. .then((files) => {
  156. db.table('albums').then((albums) => {
  157. let basedomain = req.get('host')
  158. for(let domain of config.domains)
  159. if(domain.host === req.get('host'))
  160. if(domain.hasOwnProperty('resolve'))
  161. basedomain = domain.resolve
  162. for(let file of files){
  163. file.file = basedomain + '/' + file.name
  164. file.date = new Date(file.timestamp * 1000)
  165. 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()
  166. file.album = ''
  167. if(file.albumid !== undefined)
  168. for(let album of albums)
  169. if(file.albumid === album.id)
  170. file.album = album.name
  171. if(config.uploads.generateThumbnails === true){
  172. let extensions = ['.jpg', '.jpeg', '.bmp', '.gif', '.png']
  173. for(let ext of extensions){
  174. if(path.extname(file.name) === ext){
  175. file.thumb = basedomain + '/thumbs/' + file.name.slice(0, -4) + '.png'
  176. let thumbname = path.join(__dirname, '..', 'uploads', 'thumbs') + '/' + file.name.slice(0, -4) + '.png'
  177. fs.access(thumbname, function(err) {
  178. if (err && err.code === 'ENOENT') {
  179. // File doesnt exist
  180. let size = {
  181. width: 200,
  182. height: 200
  183. }
  184. gm('./' + config.uploads.folder + '/' + file.name)
  185. .resize(size.width, size.height + '>')
  186. .gravity('Center')
  187. .extent(size.width, size.height)
  188. .background('transparent')
  189. .write(thumbname, function (error) {
  190. if (error) console.log('Error - ', error)
  191. })
  192. }
  193. })
  194. }
  195. }
  196. }
  197. }
  198. return res.json({
  199. success: true,
  200. files
  201. })
  202. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  203. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  204. }
  205. module.exports = uploadsController