uploadController.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 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. utils.generateThumbs(file)
  129. }
  130. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  131. }
  132. uploadsController.delete = function(req, res) {
  133. let token = req.headers.token
  134. if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
  135. let id = req.body.id
  136. if (id === undefined || id === '')
  137. return res.json({ success: false, description: 'No file specified' })
  138. db.table('users').where('token', token).then((user) => {
  139. if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token' })
  140. db.table('files')
  141. .where('id', id)
  142. .where(function() {
  143. if (user[0].username !== 'root')
  144. this.where('userid', user[0].id)
  145. })
  146. .then((file) => {
  147. uploadsController.deleteFile(file[0].name).then(() => {
  148. db.table('files').where('id', id).del().then(() => {
  149. return res.json({ success: true })
  150. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  151. }).catch((e) => {
  152. console.log(e.toString())
  153. db.table('files').where('id', id).del().then(() => {
  154. return res.json({ success: true })
  155. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  156. })
  157. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  158. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  159. }
  160. uploadsController.deleteFile = function(file) {
  161. return new Promise(function(resolve, reject) {
  162. fs.stat(path.join(__dirname, '..', config.uploads.folder, file), function(err, stats) {
  163. if (err) { return reject(err) }
  164. fs.unlink(path.join(__dirname, '..', config.uploads.folder, file), function(err) {
  165. if (err) { return reject(err) }
  166. return resolve()
  167. })
  168. })
  169. })
  170. }
  171. uploadsController.list = function(req, res) {
  172. let token = req.headers.token
  173. if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
  174. db.table('users').where('token', token).then((user) => {
  175. if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
  176. let offset = req.params.page
  177. if (offset === undefined) offset = 0
  178. db.table('files')
  179. .where(function() {
  180. if (req.params.id === undefined)
  181. this.where('id', '<>', '')
  182. else
  183. this.where('albumid', req.params.id)
  184. })
  185. .where(function() {
  186. if (user[0].username !== 'root')
  187. this.where('userid', user[0].id)
  188. })
  189. .orderBy('id', 'DESC')
  190. .limit(25)
  191. .offset(25 * offset)
  192. .select('id', 'albumid', 'timestamp', 'name', 'userid')
  193. .then((files) => {
  194. db.table('albums').then((albums) => {
  195. let basedomain = req.get('host')
  196. for (let domain of config.domains)
  197. if (domain.host === req.get('host'))
  198. if (domain.hasOwnProperty('resolve'))
  199. basedomain = domain.resolve
  200. let userids = []
  201. for (let file of files) {
  202. file.file = basedomain + '/' + file.name
  203. file.date = new Date(file.timestamp * 1000)
  204. 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()
  205. file.album = ''
  206. if (file.albumid !== undefined)
  207. for (let album of albums)
  208. if (file.albumid === album.id)
  209. file.album = album.name
  210. // Only push usernames if we are root
  211. if (user[0].username === 'root')
  212. if (file.userid !== undefined && file.userid !== null && file.userid !== '')
  213. userids.push(file.userid)
  214. utils.generateThumbs(file)
  215. }
  216. // If we are a normal user, send response
  217. if (user[0].username !== 'root') return res.json({ success: true, files })
  218. // If we are root but there are no uploads attached to a user, send response
  219. if (userids.length === 0) return res.json({ success: true, files })
  220. db.table('users').whereIn('id', userids).then((users) => {
  221. for (let user of users)
  222. for (let file of files)
  223. if (file.userid === user.id)
  224. file.username = user.username
  225. return res.json({ success: true, files })
  226. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  227. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  228. }).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
  229. })
  230. }
  231. module.exports = uploadsController