uploadController.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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')
  64. .where(function(){
  65. if(userid === undefined)
  66. this.whereNull('userid')
  67. else
  68. this.where('userid', userid)
  69. })
  70. .where({
  71. hash: fileHash,
  72. size: file.size
  73. }).then((dbfile) => {
  74. if(dbfile.length !== 0){
  75. uploadsController.deleteFile(file.filename).then(() => {}).catch((e) => console.error(e))
  76. existingFiles.push(dbfile[0])
  77. }else{
  78. files.push({
  79. name: file.filename,
  80. original: file.originalname,
  81. type: file.mimetype,
  82. size: file.size,
  83. hash: fileHash,
  84. ip: req.ip,
  85. albumid: album,
  86. userid: userid,
  87. timestamp: Math.floor(Date.now() / 1000)
  88. })
  89. }
  90. if(iteration === req.files.length)
  91. return uploadsController.processFilesForDisplay(req, res, files, existingFiles)
  92. iteration++
  93. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  94. })
  95. })
  96. })
  97. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  98. }
  99. uploadsController.processFilesForDisplay = function(req, res, files, existingFiles){
  100. let basedomain = req.get('host')
  101. for(let domain of config.domains)
  102. if(domain.host === req.get('host'))
  103. if(domain.hasOwnProperty('resolve'))
  104. basedomain = domain.resolve
  105. if(files.length === 0){
  106. return res.json({
  107. success: true,
  108. files: existingFiles.map(file => {
  109. return {
  110. name: file.name,
  111. size: file.size,
  112. url: basedomain + '/' + file.name
  113. }
  114. })
  115. })
  116. }
  117. db.table('files').insert(files).then(() => {
  118. for(let efile of existingFiles) files.push(efile)
  119. res.json({
  120. success: true,
  121. files: files.map(file => {
  122. return {
  123. name: file.name,
  124. size: file.size,
  125. url: basedomain + '/' + file.name
  126. }
  127. })
  128. })
  129. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  130. }
  131. uploadsController.delete = function(req, res){
  132. let token = req.headers.token
  133. if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
  134. let id = req.body.id
  135. if(id === undefined || id === '')
  136. return res.json({ success: false, description: 'No file specified' })
  137. db.table('users').where('token', token).then((user) => {
  138. if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
  139. db.table('files')
  140. .where('id', id)
  141. .where(function(){
  142. if(user[0].username !== 'root')
  143. this.where('userid', user[0].id)
  144. })
  145. .then((file) => {
  146. uploadsController.deleteFile(file[0].name).then(() => {
  147. db.table('files').where('id', id).del().then(() =>{
  148. return res.json({ success: true })
  149. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  150. }).catch((e) => {
  151. console.log(e.toString())
  152. db.table('files').where('id', id).del().then(() =>{
  153. return res.json({ success: true })
  154. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  155. })
  156. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  157. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  158. }
  159. uploadsController.deleteFile = function(file){
  160. return new Promise(function(resolve, reject){
  161. fs.stat('./' + config.uploads.folder + '/' + file, function (err, stats) {
  162. if (err) { return reject(err) }
  163. fs.unlink('./' + config.uploads.folder + '/' + file, function(err){
  164. if (err) { return reject(err) }
  165. return resolve()
  166. })
  167. })
  168. })
  169. }
  170. uploadsController.list = function(req, res){
  171. let token = req.headers.token
  172. if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
  173. db.table('users').where('token', token).then((user) => {
  174. if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
  175. let offset = req.params.page
  176. if(offset === undefined) offset = 0
  177. db.table('files')
  178. .where(function(){
  179. if(req.params.id === undefined)
  180. this.where('id', '<>', '')
  181. else
  182. this.where('albumid', req.params.id)
  183. })
  184. .where(function(){
  185. if(user[0].username !== 'root')
  186. this.where('userid', user[0].id)
  187. })
  188. .orderBy('id', 'DESC')
  189. .limit(25)
  190. .offset(25 * offset)
  191. .then((files) => {
  192. db.table('albums').then((albums) => {
  193. let basedomain = req.get('host')
  194. for(let domain of config.domains)
  195. if(domain.host === req.get('host'))
  196. if(domain.hasOwnProperty('resolve'))
  197. basedomain = domain.resolve
  198. for(let file of files){
  199. file.file = basedomain + '/' + file.name
  200. file.date = new Date(file.timestamp * 1000)
  201. 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()
  202. file.album = ''
  203. if(file.albumid !== undefined)
  204. for(let album of albums)
  205. if(file.albumid === album.id)
  206. file.album = album.name
  207. if(config.uploads.generateThumbnails === true){
  208. let extensions = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.webm', '.mp4']
  209. for(let ext of extensions){
  210. if(path.extname(file.name) === ext){
  211. file.thumb = basedomain + '/thumbs/' + file.name.slice(0, -ext.length) + '.png'
  212. let thumbname = path.join(__dirname, '..', config.uploads.folder, 'thumbs') + '/' + file.name.slice(0, -ext.length) + '.png'
  213. fs.access(thumbname, function(err) {
  214. if (err && err.code === 'ENOENT') {
  215. // File doesnt exist
  216. if (ext === '.webm' || ext === '.mp4') {
  217. ffmpeg('./' + config.uploads.folder + '/' + file.name)
  218. .thumbnail({
  219. timestamps: [0],
  220. filename: '%b.png',
  221. folder: './' + config.uploads.folder + '/thumbs',
  222. size: '200x?'
  223. })
  224. .on('error', function(error) {
  225. console.log('Error - ', error.message)
  226. })
  227. }
  228. else {
  229. let size = {
  230. width: 200,
  231. height: 200
  232. }
  233. gm('./' + config.uploads.folder + '/' + file.name)
  234. .resize(size.width, size.height + '>')
  235. .gravity('Center')
  236. .extent(size.width, size.height)
  237. .background('transparent')
  238. .write(thumbname, function (error) {
  239. if (error) console.log('Error - ', error)
  240. })
  241. }
  242. }
  243. })
  244. }
  245. }
  246. }
  247. }
  248. return res.json({
  249. success: true,
  250. files
  251. })
  252. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  253. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  254. })
  255. }
  256. module.exports = uploadsController