uploadController.js 8.3 KB

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