uploadController.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. for (let file of files){
  130. uploadsController.generateThumbs(file, basedomain)
  131. }
  132. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  133. }
  134. uploadsController.delete = function(req, res){
  135. let token = req.headers.token
  136. if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
  137. let id = req.body.id
  138. if(id === undefined || id === '')
  139. return res.json({ success: false, description: 'No file specified' })
  140. db.table('users').where('token', token).then((user) => {
  141. if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
  142. db.table('files')
  143. .where('id', id)
  144. .where(function(){
  145. if(user[0].username !== 'root')
  146. this.where('userid', user[0].id)
  147. })
  148. .then((file) => {
  149. uploadsController.deleteFile(file[0].name).then(() => {
  150. db.table('files').where('id', id).del().then(() =>{
  151. return res.json({ success: true })
  152. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  153. }).catch((e) => {
  154. console.log(e.toString())
  155. db.table('files').where('id', id).del().then(() =>{
  156. return res.json({ success: true })
  157. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  158. })
  159. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  160. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  161. }
  162. uploadsController.deleteFile = function(file){
  163. return new Promise(function(resolve, reject){
  164. fs.stat('./' + config.uploads.folder + '/' + file, function (err, stats) {
  165. if (err) { return reject(err) }
  166. fs.unlink('./' + config.uploads.folder + '/' + file, function(err){
  167. if (err) { return reject(err) }
  168. return resolve()
  169. })
  170. })
  171. })
  172. }
  173. uploadsController.list = function(req, res){
  174. let token = req.headers.token
  175. if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
  176. db.table('users').where('token', token).then((user) => {
  177. if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
  178. let offset = req.params.page
  179. if(offset === undefined) offset = 0
  180. db.table('files')
  181. .where(function(){
  182. if(req.params.id === undefined)
  183. this.where('id', '<>', '')
  184. else
  185. this.where('albumid', req.params.id)
  186. })
  187. .where(function(){
  188. if(user[0].username !== 'root')
  189. this.where('userid', user[0].id)
  190. })
  191. .orderBy('id', 'DESC')
  192. .limit(25)
  193. .offset(25 * offset)
  194. .select('id', 'albumid', 'timestamp', 'name', 'userid')
  195. .then((files) => {
  196. db.table('albums').then((albums) => {
  197. let basedomain = req.get('host')
  198. for(let domain of config.domains)
  199. if(domain.host === req.get('host'))
  200. if(domain.hasOwnProperty('resolve'))
  201. basedomain = domain.resolve
  202. let userids = []
  203. for(let file of files){
  204. file.file = basedomain + '/' + file.name
  205. file.date = new Date(file.timestamp * 1000)
  206. 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()
  207. file.album = ''
  208. if(file.albumid !== undefined)
  209. for(let album of albums)
  210. if(file.albumid === album.id)
  211. file.album = album.name
  212. // Only push usernames if we are root
  213. if(user[0].username === 'root')
  214. if(file.userid !== undefined && file.userid !== null && file.userid !== '')
  215. userids.push(file.userid)
  216. uploadsController.generateThumbs(file, basedomain)
  217. }
  218. // If we are a normal user, send response
  219. if(user[0].username !== 'root') return res.json({ success: true, files })
  220. // If we are root but there are no uploads attached to a user, send response
  221. if(userids.length === 0) return res.json({ success: true, files })
  222. db.table('users').whereIn('id', userids).then((users) => {
  223. for(let user of users)
  224. for(let file of files)
  225. if(file.userid === user.id)
  226. file.username = user.username
  227. return res.json({ success: true, files })
  228. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  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. uploadsController.generateThumbs = function(file, basedomain){
  234. if(config.uploads.generateThumbnails !== true) return
  235. let extensions = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.webm', '.mp4']
  236. for(let ext of extensions){
  237. if(path.extname(file.name).toLowerCase() === ext){
  238. let thumbname = path.join(__dirname, '..', config.uploads.folder, 'thumbs', file.name.slice(0, -ext.length) + '.png')
  239. fs.access(thumbname, function(err) {
  240. if (err && err.code === 'ENOENT') {
  241. // File doesnt exist
  242. if (ext === '.webm' || ext === '.mp4') {
  243. ffmpeg(path.join(__dirname, '..', config.uploads.folder, file.name))
  244. .thumbnail({
  245. timestamps: [0],
  246. filename: '%b.png',
  247. folder: path.join(__dirname, '..', config.uploads.folder, 'thumbs'),
  248. size: '200x?'
  249. })
  250. .on('error', function(error) {
  251. console.log('Error - ', error.message)
  252. })
  253. }
  254. else {
  255. let size = {
  256. width: 200,
  257. height: 200
  258. }
  259. gm(path.join(__dirname, '..', config.uploads.folder, file.name))
  260. .resize(size.width, size.height + '>')
  261. .gravity('Center')
  262. .extent(size.width, size.height)
  263. .background('transparent')
  264. .write(thumbname, function (error) {
  265. if (error) console.log('Error - ', error)
  266. })
  267. }
  268. }
  269. })
  270. }
  271. }
  272. }
  273. module.exports = uploadsController