uploadController.js 8.9 KB

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