uploadController.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. const config = require('../config.js')
  2. const path = require('path')
  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 utils = require('./utilsController.js')
  9. let uploadsController = {}
  10. const storage = multer.diskStorage({
  11. destination: function(req, file, cb) {
  12. cb(null, path.join(__dirname, '..', 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) userid = user[0].id
  33. // Check if user is trying to upload to an album
  34. let album
  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(path.join(__dirname, '..', 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')
  61. db.table('files')
  62. .where(function() {
  63. if (userid === undefined)
  64. this.whereNull('userid')
  65. else
  66. this.where('userid', userid)
  67. })
  68. .where({
  69. hash: fileHash,
  70. size: file.size
  71. }).then((dbfile) => {
  72. if (dbfile.length !== 0) {
  73. uploadsController.deleteFile(file.filename).then(() => {}).catch((e) => console.error(e))
  74. existingFiles.push(dbfile[0])
  75. } else {
  76. files.push({
  77. name: file.filename,
  78. original: file.originalname,
  79. type: file.mimetype,
  80. size: file.size,
  81. hash: fileHash,
  82. ip: req.ip,
  83. albumid: album,
  84. userid: userid,
  85. timestamp: Math.floor(Date.now() / 1000)
  86. })
  87. }
  88. if (iteration === req.files.length)
  89. return uploadsController.processFilesForDisplay(req, res, files, existingFiles)
  90. iteration++
  91. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  92. })
  93. })
  94. })
  95. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  96. }
  97. uploadsController.processFilesForDisplay = function(req, res, files, existingFiles) {
  98. let basedomain = req.get('host')
  99. for (let domain of config.domains)
  100. if (domain.host === req.get('host'))
  101. if (domain.hasOwnProperty('resolve'))
  102. basedomain = domain.resolve
  103. if (files.length === 0) {
  104. return res.json({
  105. success: true,
  106. files: existingFiles.map(file => {
  107. return {
  108. name: file.name,
  109. size: file.size,
  110. url: basedomain + '/' + file.name
  111. }
  112. })
  113. })
  114. }
  115. db.table('files').insert(files).then(() => {
  116. for (let efile of existingFiles) files.push(efile)
  117. res.json({
  118. success: true,
  119. files: files.map(file => {
  120. return {
  121. name: file.name,
  122. size: file.size,
  123. url: basedomain + '/' + file.name
  124. }
  125. })
  126. })
  127. for (let file of files) {
  128. let ext = path.extname(file.name).toLowerCase()
  129. if (utils.extensions.includes(ext)) {
  130. file.thumb = basedomain + '/thumbs/' + file.name.slice(0, -ext.length) + '.png'
  131. utils.generateThumbs(file)
  132. }
  133. }
  134. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  135. }
  136. uploadsController.delete = function(req, res) {
  137. let token = req.headers.token
  138. if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
  139. let id = req.body.id
  140. if (id === undefined || id === '')
  141. return res.json({ success: false, description: 'No file specified' })
  142. db.table('users').where('token', token).then((user) => {
  143. if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token' })
  144. db.table('files')
  145. .where('id', id)
  146. .where(function() {
  147. if (user[0].username !== 'root')
  148. this.where('userid', user[0].id)
  149. })
  150. .then((file) => {
  151. uploadsController.deleteFile(file[0].name).then(() => {
  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. }).catch((e) => {
  156. console.log(e.toString())
  157. db.table('files').where('id', id).del().then(() => {
  158. return res.json({ success: true })
  159. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  160. })
  161. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  162. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  163. }
  164. uploadsController.deleteFile = function(file) {
  165. return new Promise(function(resolve, reject) {
  166. fs.stat(path.join(__dirname, '..', config.uploads.folder, file), function(err, stats) {
  167. if (err) { return reject(err) }
  168. fs.unlink(path.join(__dirname, '..', config.uploads.folder, file), function(err) {
  169. if (err) { return reject(err) }
  170. return resolve()
  171. })
  172. })
  173. })
  174. }
  175. uploadsController.list = function(req, res) {
  176. let token = req.headers.token
  177. if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
  178. db.table('users').where('token', token).then((user) => {
  179. if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
  180. let offset = req.params.page
  181. if (offset === undefined) offset = 0
  182. db.table('files')
  183. .where(function() {
  184. if (req.params.id === undefined)
  185. this.where('id', '<>', '')
  186. else
  187. this.where('albumid', req.params.id)
  188. })
  189. .where(function() {
  190. if (user[0].username !== 'root')
  191. this.where('userid', user[0].id)
  192. })
  193. .orderBy('id', 'DESC')
  194. .limit(25)
  195. .offset(25 * offset)
  196. .select('id', 'albumid', 'timestamp', 'name', 'userid')
  197. .then((files) => {
  198. db.table('albums').then((albums) => {
  199. let basedomain = req.get('host')
  200. for (let domain of config.domains)
  201. if (domain.host === req.get('host'))
  202. if (domain.hasOwnProperty('resolve'))
  203. basedomain = domain.resolve
  204. let userids = []
  205. for (let file of files) {
  206. file.file = basedomain + '/' + file.name
  207. file.date = new Date(file.timestamp * 1000)
  208. file.date = utils.getPrettyDate(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()
  209. file.album = ''
  210. if (file.albumid !== undefined)
  211. for (let album of albums)
  212. if (file.albumid === album.id)
  213. file.album = album.name
  214. // Only push usernames if we are root
  215. if (user[0].username === 'root')
  216. if (file.userid !== undefined && file.userid !== null && file.userid !== '')
  217. userids.push(file.userid)
  218. let ext = path.extname(file.name).toLowerCase()
  219. if (utils.extensions.includes(ext)) {
  220. file.thumb = basedomain + '/thumbs/' + file.name.slice(0, -ext.length) + '.png'
  221. utils.generateThumbs(file)
  222. }
  223. }
  224. // If we are a normal user, send response
  225. if (user[0].username !== 'root') return res.json({ success: true, files })
  226. // If we are root but there are no uploads attached to a user, send response
  227. if (userids.length === 0) return res.json({ success: true, files })
  228. db.table('users').whereIn('id', userids).then((users) => {
  229. for (let user of users)
  230. for (let file of files)
  231. if (file.userid === user.id)
  232. file.username = user.username
  233. return res.json({ success: true, files })
  234. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  235. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  236. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  237. })
  238. }
  239. module.exports = uploadsController