uploadController.js 8.4 KB

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