2018-04-13 16:20:57 +00:00
|
|
|
const config = require('./../config')
|
2018-01-23 20:06:30 +00:00
|
|
|
const crypto = require('crypto')
|
2018-09-01 20:37:26 +00:00
|
|
|
const db = require('knex')(config.database)
|
2018-01-23 20:06:30 +00:00
|
|
|
const fs = require('fs')
|
2018-09-01 20:37:26 +00:00
|
|
|
const multer = require('multer')
|
|
|
|
const path = require('path')
|
|
|
|
const pce = require('path-complete-extname')
|
|
|
|
const randomstring = require('randomstring')
|
2018-05-11 14:34:13 +00:00
|
|
|
const snekfetch = require('snekfetch')
|
2018-04-13 16:20:57 +00:00
|
|
|
const utils = require('./utilsController')
|
2017-01-13 07:34:21 +00:00
|
|
|
|
2018-01-23 20:06:30 +00:00
|
|
|
const uploadsController = {}
|
2017-01-13 07:34:21 +00:00
|
|
|
|
2018-03-18 13:13:08 +00:00
|
|
|
const maxTries = config.uploads.maxTries || 1
|
2018-04-28 17:26:39 +00:00
|
|
|
const uploadsDir = path.join(__dirname, '..', config.uploads.folder)
|
2018-05-09 08:41:30 +00:00
|
|
|
const chunkedUploads = Boolean(config.uploads.chunkSize)
|
2018-04-28 17:26:39 +00:00
|
|
|
const chunksDir = path.join(uploadsDir, 'chunks')
|
2018-05-11 14:34:13 +00:00
|
|
|
const maxSize = config.uploads.maxSize
|
|
|
|
const maxSizeBytes = parseInt(maxSize) * 1000000
|
|
|
|
const urlMaxSizeBytes = parseInt(config.uploads.urlMaxSize) * 1000000
|
2018-03-13 14:51:39 +00:00
|
|
|
|
2017-01-13 07:34:21 +00:00
|
|
|
const storage = multer.diskStorage({
|
2018-04-05 10:52:57 +00:00
|
|
|
destination (req, file, cb) {
|
2018-03-28 11:36:28 +00:00
|
|
|
// If chunked uploads is disabled or the uploaded file is not a chunk
|
|
|
|
if (!chunkedUploads || (req.body.uuid === undefined && req.body.chunkindex === undefined)) {
|
2018-04-28 17:26:39 +00:00
|
|
|
return cb(null, uploadsDir)
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const uuidDir = path.join(chunksDir, req.body.uuid)
|
2018-03-29 23:22:08 +00:00
|
|
|
fs.access(uuidDir, error => {
|
|
|
|
if (!error) { return cb(null, uuidDir) }
|
|
|
|
fs.mkdir(uuidDir, error => {
|
|
|
|
if (!error) { return cb(null, uuidDir) }
|
2018-05-09 08:41:30 +00:00
|
|
|
console.error(error)
|
2018-03-18 16:59:03 +00:00
|
|
|
// eslint-disable-next-line standard/no-callback-literal
|
2018-03-28 11:36:28 +00:00
|
|
|
return cb('Could not process the chunked upload. Try again?')
|
2018-03-18 16:59:03 +00:00
|
|
|
})
|
2018-03-28 11:36:28 +00:00
|
|
|
})
|
|
|
|
},
|
2018-04-05 10:52:57 +00:00
|
|
|
filename (req, file, cb) {
|
2018-03-28 11:36:28 +00:00
|
|
|
// If chunked uploads is disabled or the uploaded file is not a chunk
|
|
|
|
if (!chunkedUploads || (req.body.uuid === undefined && req.body.chunkindex === undefined)) {
|
2018-09-01 20:37:26 +00:00
|
|
|
const extension = pce(file.originalname).toLowerCase()
|
2018-03-28 11:36:28 +00:00
|
|
|
const length = uploadsController.getFileNameLength(req)
|
2018-04-28 17:26:39 +00:00
|
|
|
return uploadsController.getUniqueRandomName(length, extension)
|
|
|
|
.then(name => cb(null, name))
|
|
|
|
.catch(error => cb(error))
|
2018-03-13 14:51:39 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-04-08 18:30:25 +00:00
|
|
|
// index.extension (e.i. 0, 1, ..., n - will prepend zeros depending on the amount of chunks)
|
2018-03-28 14:10:20 +00:00
|
|
|
const digits = req.body.totalchunkcount !== undefined ? String(req.body.totalchunkcount - 1).length : 1
|
|
|
|
const zeros = new Array(digits + 1).join('0')
|
|
|
|
const name = (zeros + req.body.chunkindex).slice(-digits)
|
2018-04-08 18:30:25 +00:00
|
|
|
return cb(null, name)
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
|
|
|
})
|
2017-01-13 07:34:21 +00:00
|
|
|
|
|
|
|
const upload = multer({
|
2018-03-28 11:36:28 +00:00
|
|
|
storage,
|
|
|
|
limits: {
|
2018-05-11 14:34:13 +00:00
|
|
|
fileSize: maxSizeBytes
|
2018-03-28 11:36:28 +00:00
|
|
|
},
|
2018-04-05 10:52:57 +00:00
|
|
|
fileFilter (req, file, cb) {
|
2018-09-01 20:37:26 +00:00
|
|
|
const extname = pce(file.originalname).toLowerCase()
|
2018-05-11 14:34:13 +00:00
|
|
|
if (uploadsController.isExtensionFiltered(extname)) {
|
|
|
|
// eslint-disable-next-line standard/no-callback-literal
|
2018-07-12 06:52:31 +00:00
|
|
|
return cb(`${extname.substr(1).toUpperCase()} files are not permitted due to security reasons.`)
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-05-09 08:41:30 +00:00
|
|
|
// Re-map Dropzone keys so people can manually use the API without prepending 'dz'
|
|
|
|
for (const key in req.body) {
|
|
|
|
if (!/^dz/.test(key)) { continue }
|
|
|
|
req.body[key.replace(/^dz/, '')] = req.body[key]
|
|
|
|
delete req.body[key]
|
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-05-09 08:41:30 +00:00
|
|
|
if (req.body.chunkindex) {
|
|
|
|
if (chunkedUploads && parseInt(req.body.totalfilesize) > maxSizeBytes) {
|
|
|
|
// This will not be true if "totalfilesize" key does not exist, since "NaN > number" is false.
|
2018-03-28 11:36:28 +00:00
|
|
|
// eslint-disable-next-line standard/no-callback-literal
|
2018-04-25 13:16:34 +00:00
|
|
|
return cb('Chunk error occurred. Total file size is larger than the maximum file size.')
|
2018-05-09 08:41:30 +00:00
|
|
|
} else if (!chunkedUploads) {
|
|
|
|
// eslint-disable-next-line standard/no-callback-literal
|
|
|
|
return cb('Chunked uploads is disabled at the moment.')
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-23 20:06:30 +00:00
|
|
|
return cb(null, true)
|
|
|
|
}
|
|
|
|
}).array('files[]')
|
2017-01-13 07:34:21 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
uploadsController.isExtensionFiltered = extname => {
|
|
|
|
// If there are extensions that have to be filtered
|
|
|
|
if (config.extensionsFilter && config.extensionsFilter.length) {
|
|
|
|
const match = config.extensionsFilter.some(extension => extname === extension.toLowerCase())
|
|
|
|
if ((config.filterBlacklist && match) || (!config.filterBlacklist && !match)) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2018-03-28 11:36:28 +00:00
|
|
|
uploadsController.getFileNameLength = req => {
|
|
|
|
// If the user has a preferred file length, make sure it is within the allowed range
|
|
|
|
if (req.headers.filelength) {
|
|
|
|
return Math.min(Math.max(req.headers.filelength, config.uploads.fileLength.min), config.uploads.fileLength.max)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Let's default it to 32 characters when config key is falsy
|
|
|
|
return config.uploads.fileLength.default || 32
|
|
|
|
}
|
|
|
|
|
2018-04-28 17:26:39 +00:00
|
|
|
uploadsController.getUniqueRandomName = (length, extension) => {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const access = i => {
|
|
|
|
const name = randomstring.generate(length) + extension
|
|
|
|
fs.access(path.join(uploadsDir, name), error => {
|
|
|
|
if (error) { return resolve(name) }
|
|
|
|
console.log(`A file named ${name} already exists (${++i}/${maxTries}).`)
|
|
|
|
if (i < maxTries) { return access(i) }
|
|
|
|
// eslint-disable-next-line prefer-promise-reject-errors
|
|
|
|
return reject('Sorry, we could not allocate a unique random name. Try again?')
|
|
|
|
})
|
|
|
|
}
|
|
|
|
access(0)
|
|
|
|
})
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
|
|
|
|
2017-10-04 00:13:38 +00:00
|
|
|
uploadsController.upload = async (req, res, next) => {
|
2018-03-24 19:47:41 +00:00
|
|
|
let user
|
2018-01-23 20:06:30 +00:00
|
|
|
if (config.private === true) {
|
2018-03-24 19:47:41 +00:00
|
|
|
user = await utils.authorize(req, res)
|
2018-03-28 17:40:50 +00:00
|
|
|
if (!user) { return }
|
2018-03-24 19:47:41 +00:00
|
|
|
} else if (req.headers.token) {
|
|
|
|
user = await db.table('users').where('token', req.headers.token).first()
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
|
|
|
|
2018-03-14 06:57:09 +00:00
|
|
|
if (user && (user.enabled === false || user.enabled === 0)) {
|
2018-04-28 17:26:39 +00:00
|
|
|
return res.json({ success: false, description: 'This account has been disabled.' })
|
2018-03-14 06:57:09 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
|
|
|
if (user && user.fileLength && !req.headers.filelength) {
|
|
|
|
req.headers.filelength = user.fileLength
|
2018-03-24 13:52:47 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-04-05 12:54:24 +00:00
|
|
|
let albumid = parseInt(req.headers.albumid || req.params.albumid)
|
|
|
|
if (isNaN(albumid)) { albumid = null }
|
2018-05-11 14:34:13 +00:00
|
|
|
|
|
|
|
if (req.body.urls) {
|
|
|
|
return uploadsController.actuallyUploadByUrl(req, res, user, albumid)
|
|
|
|
} else {
|
|
|
|
return uploadsController.actuallyUpload(req, res, user, albumid)
|
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
2017-01-19 06:34:48 +00:00
|
|
|
|
2018-03-28 11:36:28 +00:00
|
|
|
uploadsController.actuallyUpload = async (req, res, user, albumid) => {
|
2018-03-29 23:22:08 +00:00
|
|
|
const erred = error => {
|
2018-04-25 13:16:34 +00:00
|
|
|
const isError = error instanceof Error
|
2018-05-09 08:41:30 +00:00
|
|
|
if (isError) { console.error(error) }
|
2018-03-28 11:36:28 +00:00
|
|
|
res.json({
|
|
|
|
success: false,
|
2018-05-11 14:34:13 +00:00
|
|
|
description: isError ? error.toString() : error
|
2018-03-28 11:36:28 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-03-29 23:22:08 +00:00
|
|
|
upload(req, res, async error => {
|
2018-07-12 06:34:22 +00:00
|
|
|
if (error) { return erred(error) }
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
if (!req.files || !req.files.length) { return erred('No files.') }
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-04-08 18:30:25 +00:00
|
|
|
// If chunked uploads is enabled and the uploaded file is a chunk, then just say that it was a success
|
2018-03-28 17:40:50 +00:00
|
|
|
if (chunkedUploads && req.body.uuid) { return res.json({ success: true }) }
|
2018-03-28 11:36:28 +00:00
|
|
|
|
|
|
|
const infoMap = req.files.map(file => {
|
2018-04-08 18:30:25 +00:00
|
|
|
file.albumid = albumid
|
2018-03-28 11:36:28 +00:00
|
|
|
return {
|
|
|
|
path: path.join(__dirname, '..', config.uploads.folder, file.filename),
|
|
|
|
data: file
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2018-09-01 20:37:26 +00:00
|
|
|
if (config.uploads.scan) {
|
|
|
|
const scan = await uploadsController.scanFiles(req, infoMap)
|
|
|
|
if (!scan) { return erred('Virus detected.') }
|
|
|
|
}
|
|
|
|
|
2018-05-10 17:25:52 +00:00
|
|
|
const result = await uploadsController.formatInfoMap(req, res, user, infoMap)
|
2018-03-28 11:36:28 +00:00
|
|
|
.catch(erred)
|
2018-05-12 19:16:04 +00:00
|
|
|
if (!result) { return }
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-05-12 19:16:04 +00:00
|
|
|
uploadsController.processFilesForDisplay(req, res, result.files, result.existingFiles)
|
2018-03-28 11:36:28 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
uploadsController.actuallyUploadByUrl = async (req, res, user, albumid) => {
|
|
|
|
const erred = error => {
|
|
|
|
const isError = error instanceof Error
|
|
|
|
if (isError) { console.error(error) }
|
|
|
|
res.json({
|
|
|
|
success: false,
|
|
|
|
description: isError ? error.toString() : error
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!config.uploads.urlMaxSize) { return erred('Upload by URLs is disabled at the moment.') }
|
|
|
|
|
2018-06-05 17:16:41 +00:00
|
|
|
let urls = req.body.urls
|
2018-05-11 14:34:13 +00:00
|
|
|
if (!urls || !(urls instanceof Array)) { return erred('Missing "urls" property (Array).') }
|
|
|
|
|
2018-06-05 17:16:41 +00:00
|
|
|
// DuckDuckGo's proxy
|
|
|
|
if (config.uploads.urlDuckDuckGoProxy) {
|
|
|
|
urls = urls.map(url => `https://proxy.duckduckgo.com/iur/?f=1&image_host=${encodeURIComponent(url)}&u=${url}`)
|
|
|
|
}
|
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
let iteration = 0
|
|
|
|
const infoMap = []
|
|
|
|
for (const url of urls) {
|
|
|
|
const original = path.basename(url).split(/[?#]/)[0]
|
2018-09-01 20:37:26 +00:00
|
|
|
const extension = pce(original).toLowerCase()
|
2018-05-11 14:34:13 +00:00
|
|
|
if (uploadsController.isExtensionFiltered(extension)) {
|
2018-07-12 06:38:43 +00:00
|
|
|
return erred(`${extension.substr(1).toUpperCase()} files are not permitted due to security reasons.`)
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const head = await snekfetch.head(url)
|
2018-06-05 17:40:33 +00:00
|
|
|
.catch(error => error)
|
|
|
|
if (head.status !== 200) { return erred(head.toString()) }
|
2018-05-12 19:16:04 +00:00
|
|
|
if (!head) { return }
|
2018-05-11 14:34:13 +00:00
|
|
|
|
|
|
|
const size = parseInt(head.headers['content-length'])
|
|
|
|
if (isNaN(size)) {
|
|
|
|
return erred('URLs with missing Content-Length HTTP header are not supported.')
|
|
|
|
}
|
|
|
|
if (size > urlMaxSizeBytes) {
|
|
|
|
return erred('File too large.')
|
|
|
|
}
|
|
|
|
|
|
|
|
const download = await snekfetch.get(url)
|
2018-06-05 17:40:33 +00:00
|
|
|
.catch(error => error)
|
|
|
|
if (download.status !== 200) { return erred(download.toString()) }
|
2018-05-12 19:16:04 +00:00
|
|
|
if (!download) { return }
|
2018-05-11 14:34:13 +00:00
|
|
|
|
|
|
|
const length = uploadsController.getFileNameLength(req)
|
|
|
|
const name = await uploadsController.getUniqueRandomName(length, extension)
|
|
|
|
.catch(erred)
|
|
|
|
if (!name) { return }
|
|
|
|
|
|
|
|
const destination = path.join(uploadsDir, name)
|
|
|
|
fs.writeFile(destination, download.body, async error => {
|
|
|
|
if (error) { return erred(error) }
|
|
|
|
|
|
|
|
const data = {
|
|
|
|
filename: name,
|
|
|
|
originalname: original,
|
|
|
|
mimetype: download.headers['content-type'].split(';')[0] || '',
|
|
|
|
size,
|
|
|
|
albumid
|
|
|
|
}
|
|
|
|
|
|
|
|
infoMap.push({
|
|
|
|
path: destination,
|
|
|
|
data
|
|
|
|
})
|
|
|
|
|
|
|
|
iteration++
|
|
|
|
if (iteration === urls.length) {
|
2018-09-01 20:37:26 +00:00
|
|
|
if (config.uploads.scan) {
|
|
|
|
const scan = await uploadsController.scanFiles(req, infoMap)
|
|
|
|
if (!scan) { return erred('Virus detected.') }
|
|
|
|
}
|
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
const result = await uploadsController.formatInfoMap(req, res, user, infoMap)
|
|
|
|
.catch(erred)
|
2018-05-12 19:16:04 +00:00
|
|
|
if (!result) { return }
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2018-05-12 19:16:04 +00:00
|
|
|
uploadsController.processFilesForDisplay(req, res, result.files, result.existingFiles)
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-28 11:36:28 +00:00
|
|
|
uploadsController.finishChunks = async (req, res, next) => {
|
2018-04-08 18:30:25 +00:00
|
|
|
if (!chunkedUploads) {
|
2018-05-11 14:34:13 +00:00
|
|
|
return res.json({ success: false, description: 'Chunked upload is disabled at the moment.' })
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-03-28 11:36:28 +00:00
|
|
|
let user
|
|
|
|
if (config.private === true) {
|
|
|
|
user = await utils.authorize(req, res)
|
2018-03-28 17:40:50 +00:00
|
|
|
if (!user) { return }
|
2018-03-28 11:36:28 +00:00
|
|
|
} else if (req.headers.token) {
|
|
|
|
user = await db.table('users').where('token', req.headers.token).first()
|
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-03-28 11:36:28 +00:00
|
|
|
if (user && (user.enabled === false || user.enabled === 0)) {
|
2018-04-28 17:26:39 +00:00
|
|
|
return res.json({ success: false, description: 'This account has been disabled.' })
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (user && user.fileLength && !req.headers.filelength) {
|
|
|
|
req.headers.filelength = user.fileLength
|
|
|
|
}
|
|
|
|
|
2018-04-05 12:54:24 +00:00
|
|
|
let albumid = parseInt(req.headers.albumid || req.params.albumid)
|
|
|
|
if (isNaN(albumid)) { albumid = null }
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2018-03-28 11:36:28 +00:00
|
|
|
return uploadsController.actuallyFinishChunks(req, res, user, albumid)
|
|
|
|
}
|
|
|
|
|
|
|
|
uploadsController.actuallyFinishChunks = async (req, res, user, albumid) => {
|
2018-03-29 23:22:08 +00:00
|
|
|
const erred = error => {
|
2018-04-25 13:16:34 +00:00
|
|
|
const isError = error instanceof Error
|
2018-05-09 08:41:30 +00:00
|
|
|
if (isError) { console.error(error) }
|
2018-03-28 11:36:28 +00:00
|
|
|
res.json({
|
|
|
|
success: false,
|
2018-05-11 14:34:13 +00:00
|
|
|
description: isError ? error.toString() : error
|
2018-03-28 11:36:28 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const files = req.body.files
|
2018-05-11 14:34:13 +00:00
|
|
|
if (!files || !(files instanceof Array)) { return erred('Missing "files" property (Array).') }
|
2018-05-12 19:16:04 +00:00
|
|
|
if (!files.length) { return erred('"files" property can not be empty.') }
|
2018-03-28 11:36:28 +00:00
|
|
|
|
|
|
|
let iteration = 0
|
|
|
|
const infoMap = []
|
2018-04-05 12:54:24 +00:00
|
|
|
for (const file of files) {
|
2018-05-12 19:16:04 +00:00
|
|
|
if (!file.uuid || typeof file.uuid !== 'string') { return erred('Missing or empty "uuid" property (string).') }
|
|
|
|
if (typeof file.count !== 'number') { return erred('Missing "count" property (number).') }
|
|
|
|
if (file.count < 1) { return erred('"count" property can not be less than 1.') }
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-05-12 19:16:04 +00:00
|
|
|
const uuidDir = path.join(chunksDir, file.uuid)
|
2018-04-08 18:30:25 +00:00
|
|
|
fs.readdir(uuidDir, async (error, chunkNames) => {
|
2018-03-29 23:22:08 +00:00
|
|
|
if (error) { return erred(error) }
|
2018-05-12 19:16:04 +00:00
|
|
|
if (file.count < chunkNames.length) { return erred('Chunks count mismatch.') }
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-09-01 20:37:26 +00:00
|
|
|
const extension = typeof file.original === 'string' ? pce(file.original).toLowerCase() : ''
|
2018-05-11 14:34:13 +00:00
|
|
|
if (uploadsController.isExtensionFiltered(extension)) {
|
2018-07-12 06:52:31 +00:00
|
|
|
return erred(`${extension.substr(1).toUpperCase()} files are not permitted due to security reasons.`)
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
const length = uploadsController.getFileNameLength(req)
|
2018-04-28 17:26:39 +00:00
|
|
|
const name = await uploadsController.getUniqueRandomName(length, extension)
|
|
|
|
.catch(erred)
|
|
|
|
if (!name) { return }
|
|
|
|
|
|
|
|
const destination = path.join(uploadsDir, name)
|
|
|
|
|
|
|
|
// Sort chunk names
|
|
|
|
chunkNames.sort()
|
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
// Get total chunks size
|
|
|
|
const chunksTotalSize = await uploadsController.getTotalSize(uuidDir, chunkNames)
|
|
|
|
.catch(erred)
|
2018-05-12 19:16:04 +00:00
|
|
|
if (typeof chunksTotalSize !== 'number') { return }
|
2018-05-11 14:34:13 +00:00
|
|
|
if (chunksTotalSize > maxSizeBytes) {
|
|
|
|
// Delete all chunks and remove chunks dir
|
|
|
|
const chunksCleaned = await uploadsController.cleanUpChunks(uuidDir, chunkNames)
|
|
|
|
.catch(erred)
|
|
|
|
if (!chunksCleaned) { return }
|
|
|
|
return erred(`Total chunks size is bigger than ${maxSize}.`)
|
|
|
|
}
|
|
|
|
|
2018-04-28 17:26:39 +00:00
|
|
|
// Append all chunks
|
2018-05-11 14:34:13 +00:00
|
|
|
const destFileStream = fs.createWriteStream(destination, { flags: 'a' })
|
2018-04-28 17:26:39 +00:00
|
|
|
const chunksAppended = await uploadsController.appendToStream(destFileStream, uuidDir, chunkNames)
|
|
|
|
.catch(erred)
|
|
|
|
if (!chunksAppended) { return }
|
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
// Delete all chunks and remove chunks dir
|
|
|
|
const chunksCleaned = await uploadsController.cleanUpChunks(uuidDir, chunkNames)
|
|
|
|
.catch(erred)
|
|
|
|
if (!chunksCleaned) { return }
|
2018-04-05 12:54:24 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
const data = {
|
|
|
|
filename: name,
|
|
|
|
originalname: file.original || '',
|
|
|
|
mimetype: file.type || '',
|
|
|
|
size: file.size || 0
|
|
|
|
}
|
2018-04-05 12:54:24 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
data.albumid = parseInt(file.albumid)
|
|
|
|
if (isNaN(data.albumid)) { data.albumid = albumid }
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
infoMap.push({
|
|
|
|
path: destination,
|
|
|
|
data
|
|
|
|
})
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
iteration++
|
|
|
|
if (iteration === files.length) {
|
2018-09-01 20:37:26 +00:00
|
|
|
if (config.uploads.scan) {
|
|
|
|
const scan = await uploadsController.scanFiles(req, infoMap)
|
|
|
|
if (!scan) { return erred('Virus detected.') }
|
|
|
|
}
|
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
const result = await uploadsController.formatInfoMap(req, res, user, infoMap)
|
|
|
|
.catch(erred)
|
2018-05-12 19:16:04 +00:00
|
|
|
if (!result) { return }
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2018-05-12 19:16:04 +00:00
|
|
|
uploadsController.processFilesForDisplay(req, res, result.files, result.existingFiles)
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
})
|
2018-04-05 10:31:07 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
uploadsController.getTotalSize = (uuidDir, chunkNames) => {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
let size = 0
|
|
|
|
const stat = i => {
|
|
|
|
if (i === chunkNames.length) { return resolve(size) }
|
|
|
|
fs.stat(path.join(uuidDir, chunkNames[i]), (error, stats) => {
|
|
|
|
if (error) { return reject(error) }
|
|
|
|
size += stats.size
|
|
|
|
stat(i + 1)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
stat(0)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-04-20 21:39:06 +00:00
|
|
|
uploadsController.appendToStream = (destFileStream, uuidDr, chunkNames) => {
|
2018-03-28 11:36:28 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const append = i => {
|
2018-05-11 14:34:13 +00:00
|
|
|
if (i === chunkNames.length) {
|
2018-03-28 11:36:28 +00:00
|
|
|
destFileStream.end()
|
2018-05-11 14:34:13 +00:00
|
|
|
return resolve(true)
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
2018-05-11 14:34:13 +00:00
|
|
|
fs.createReadStream(path.join(uuidDr, chunkNames[i]))
|
|
|
|
.on('end', () => {
|
|
|
|
append(i + 1)
|
|
|
|
})
|
|
|
|
.on('error', error => {
|
|
|
|
console.error(error)
|
|
|
|
destFileStream.end()
|
|
|
|
return reject(error)
|
|
|
|
})
|
|
|
|
.pipe(destFileStream, { end: false })
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
|
|
|
append(0)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
uploadsController.cleanUpChunks = (uuidDir, chunkNames) => {
|
|
|
|
return new Promise(async (resolve, reject) => {
|
|
|
|
await Promise.all(chunkNames.map(chunkName => {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const chunkPath = path.join(uuidDir, chunkName)
|
|
|
|
fs.unlink(chunkPath, error => {
|
|
|
|
if (error && error.code !== 'ENOENT') {
|
|
|
|
console.error(error)
|
|
|
|
return reject(error)
|
|
|
|
}
|
|
|
|
resolve()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
})).catch(reject)
|
|
|
|
fs.rmdir(uuidDir, error => {
|
|
|
|
if (error) { return reject(error) }
|
|
|
|
resolve(true)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-05-10 17:25:52 +00:00
|
|
|
uploadsController.formatInfoMap = (req, res, user, infoMap) => {
|
2018-09-01 20:37:26 +00:00
|
|
|
return new Promise(async resolve => {
|
2018-03-28 11:36:28 +00:00
|
|
|
let iteration = 0
|
2018-01-23 20:06:30 +00:00
|
|
|
const files = []
|
|
|
|
const existingFiles = []
|
2018-04-08 18:30:25 +00:00
|
|
|
const albumsAuthorized = {}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-04-05 10:52:57 +00:00
|
|
|
for (const info of infoMap) {
|
2018-01-23 20:06:30 +00:00
|
|
|
// Check if the file exists by checking hash and size
|
2018-03-28 11:36:28 +00:00
|
|
|
const hash = crypto.createHash('md5')
|
|
|
|
const stream = fs.createReadStream(info.path)
|
2018-01-23 20:06:30 +00:00
|
|
|
|
|
|
|
stream.on('data', data => {
|
|
|
|
hash.update(data, 'utf8')
|
|
|
|
})
|
|
|
|
|
|
|
|
stream.on('end', async () => {
|
|
|
|
const fileHash = hash.digest('hex')
|
|
|
|
const dbFile = await db.table('files')
|
|
|
|
.where(function () {
|
2018-03-28 17:40:50 +00:00
|
|
|
if (user === undefined) {
|
|
|
|
this.whereNull('userid')
|
|
|
|
} else {
|
|
|
|
this.where('userid', user.id)
|
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
})
|
|
|
|
.where({
|
|
|
|
hash: fileHash,
|
2018-03-28 11:36:28 +00:00
|
|
|
size: info.data.size
|
2018-01-23 20:06:30 +00:00
|
|
|
})
|
|
|
|
.first()
|
|
|
|
|
|
|
|
if (!dbFile) {
|
2018-04-05 12:54:24 +00:00
|
|
|
if (info.data.albumid && albumsAuthorized[info.data.albumid] === undefined) {
|
|
|
|
const authorized = await db.table('albums')
|
|
|
|
.where({
|
|
|
|
id: info.data.albumid,
|
|
|
|
userid: user.id
|
|
|
|
})
|
|
|
|
.first()
|
|
|
|
albumsAuthorized[info.data.albumid] = Boolean(authorized)
|
|
|
|
}
|
|
|
|
|
2018-01-23 20:06:30 +00:00
|
|
|
files.push({
|
2018-03-28 11:36:28 +00:00
|
|
|
name: info.data.filename,
|
|
|
|
original: info.data.originalname,
|
|
|
|
type: info.data.mimetype,
|
|
|
|
size: info.data.size,
|
2018-01-23 20:06:30 +00:00
|
|
|
hash: fileHash,
|
|
|
|
ip: req.ip,
|
2018-04-05 12:54:24 +00:00
|
|
|
albumid: albumsAuthorized[info.data.albumid] ? info.data.albumid : null,
|
2018-03-24 19:47:41 +00:00
|
|
|
userid: user !== undefined ? user.id : null,
|
2018-01-23 20:06:30 +00:00
|
|
|
timestamp: Math.floor(Date.now() / 1000)
|
|
|
|
})
|
|
|
|
} else {
|
2018-04-29 12:47:24 +00:00
|
|
|
utils.deleteFile(info.data.filename).catch(console.error)
|
2018-01-23 20:06:30 +00:00
|
|
|
existingFiles.push(dbFile)
|
|
|
|
}
|
|
|
|
|
|
|
|
iteration++
|
2018-04-28 17:26:39 +00:00
|
|
|
if (iteration === infoMap.length) {
|
2018-05-11 14:34:13 +00:00
|
|
|
resolve({ files, existingFiles })
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
})
|
2018-04-05 10:31:07 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
})
|
|
|
|
}
|
2017-10-04 00:13:38 +00:00
|
|
|
|
2018-09-01 20:37:26 +00:00
|
|
|
uploadsController.scanFiles = async (req, infoMap) => {
|
|
|
|
const dirty = await new Promise(async resolve => {
|
|
|
|
let iteration = 0
|
2018-09-04 15:48:24 +00:00
|
|
|
const scanner = req.app.get('clam-scanner')
|
2018-09-01 20:37:26 +00:00
|
|
|
const dirty = []
|
|
|
|
|
|
|
|
for (const info of infoMap) {
|
|
|
|
const log = message => {
|
|
|
|
console.log(`ClamAV: ${info.data.filename}: ${message}.`)
|
|
|
|
}
|
|
|
|
|
2018-09-04 15:48:24 +00:00
|
|
|
scanner.scanFile(info.path).then(reply => {
|
|
|
|
if (!reply.includes('OK') || reply.includes('FOUND')) {
|
|
|
|
log(reply.replace(/^stream: /, ''))
|
2018-09-01 20:37:26 +00:00
|
|
|
dirty.push(info)
|
|
|
|
}
|
|
|
|
|
|
|
|
iteration++
|
|
|
|
if (iteration === infoMap.length) {
|
|
|
|
resolve(dirty)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
if (!dirty.length) { return true }
|
|
|
|
|
|
|
|
// If there is at least one dirty file, delete all files
|
|
|
|
infoMap.forEach(info => utils.deleteFile(info.data.filename).catch(console.error))
|
|
|
|
}
|
|
|
|
|
2018-04-05 12:54:24 +00:00
|
|
|
uploadsController.processFilesForDisplay = async (req, res, files, existingFiles) => {
|
2018-05-12 14:01:14 +00:00
|
|
|
const responseFiles = []
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-04-12 14:37:42 +00:00
|
|
|
if (files.length) {
|
|
|
|
// Insert new files to DB
|
|
|
|
await db.table('files').insert(files)
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-04-12 14:37:42 +00:00
|
|
|
for (const file of files) {
|
2018-05-12 14:01:14 +00:00
|
|
|
responseFiles.push(file)
|
2018-04-05 12:54:24 +00:00
|
|
|
}
|
2018-05-12 14:01:14 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-05-12 14:01:14 +00:00
|
|
|
if (existingFiles.length) {
|
|
|
|
for (const file of existingFiles) {
|
|
|
|
responseFiles.push(file)
|
2018-04-12 14:37:42 +00:00
|
|
|
}
|
2018-05-12 14:01:14 +00:00
|
|
|
}
|
2018-04-04 17:38:15 +00:00
|
|
|
|
2018-05-12 14:01:14 +00:00
|
|
|
// We send response first before generating thumbnails and updating album timestamps
|
|
|
|
res.json({
|
|
|
|
success: true,
|
|
|
|
files: responseFiles.map(file => {
|
2018-04-12 14:37:42 +00:00
|
|
|
return {
|
|
|
|
name: file.name,
|
|
|
|
size: file.size,
|
2018-05-12 14:01:14 +00:00
|
|
|
url: `${config.domain}/${file.name}`
|
2018-04-04 17:38:15 +00:00
|
|
|
}
|
|
|
|
})
|
2018-05-12 14:01:14 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
const albumids = []
|
|
|
|
for (const file of files) {
|
|
|
|
if (file.albumid && !albumids.includes(file.albumid)) {
|
|
|
|
albumids.push(file.albumid)
|
|
|
|
}
|
2018-09-01 20:37:26 +00:00
|
|
|
if (utils.mayGenerateThumb(pce(file.name).toLowerCase())) {
|
2018-05-12 14:01:14 +00:00
|
|
|
utils.generateThumbs(file.name)
|
|
|
|
}
|
2018-04-12 14:37:42 +00:00
|
|
|
}
|
|
|
|
|
2018-05-12 14:01:14 +00:00
|
|
|
if (albumids.length) {
|
|
|
|
await db.table('albums')
|
|
|
|
.whereIn('id', albumids)
|
|
|
|
.update('editedAt', Math.floor(Date.now() / 1000))
|
|
|
|
.catch(console.error)
|
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
2017-03-17 00:53:29 +00:00
|
|
|
|
2017-10-04 00:13:38 +00:00
|
|
|
uploadsController.delete = async (req, res) => {
|
2018-05-09 09:53:27 +00:00
|
|
|
req.body.field = 'id'
|
|
|
|
req.body.values = [req.body.id]
|
|
|
|
delete req.body.id
|
|
|
|
return uploadsController.bulkDelete(req, res)
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
|
|
|
|
2018-03-29 23:22:08 +00:00
|
|
|
uploadsController.bulkDelete = async (req, res) => {
|
|
|
|
const user = await utils.authorize(req, res)
|
|
|
|
if (!user) { return }
|
2018-05-05 19:44:58 +00:00
|
|
|
|
|
|
|
const field = req.body.field || 'id'
|
|
|
|
const values = req.body.values
|
|
|
|
if (values === undefined || !values.length) {
|
2018-03-29 23:22:08 +00:00
|
|
|
return res.json({ success: false, description: 'No files specified.' })
|
|
|
|
}
|
|
|
|
|
2018-05-05 19:44:58 +00:00
|
|
|
const failed = await utils.bulkDeleteFiles(field, values, user)
|
|
|
|
if (failed.length < values.length) {
|
|
|
|
return res.json({ success: true, failed })
|
2018-03-30 02:39:53 +00:00
|
|
|
}
|
2018-03-29 23:22:08 +00:00
|
|
|
|
2018-05-05 19:44:58 +00:00
|
|
|
return res.json({ success: false, description: 'Could not delete any files.' })
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
2017-10-04 00:13:38 +00:00
|
|
|
|
|
|
|
uploadsController.list = async (req, res) => {
|
2018-01-23 20:06:30 +00:00
|
|
|
const user = await utils.authorize(req, res)
|
2018-03-28 17:40:50 +00:00
|
|
|
if (!user) { return }
|
2018-01-23 20:06:30 +00:00
|
|
|
|
|
|
|
let offset = req.params.page
|
2018-03-28 17:40:50 +00:00
|
|
|
if (offset === undefined) { offset = 0 }
|
2018-01-23 20:06:30 +00:00
|
|
|
|
|
|
|
const files = await db.table('files')
|
|
|
|
.where(function () {
|
2018-03-28 17:40:50 +00:00
|
|
|
if (req.params.id === undefined) {
|
|
|
|
this.where('id', '<>', '')
|
|
|
|
} else {
|
|
|
|
this.where('albumid', req.params.id)
|
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
})
|
|
|
|
.where(function () {
|
2018-03-28 17:40:50 +00:00
|
|
|
if (user.username !== 'root') { this.where('userid', user.id) }
|
2018-01-23 20:06:30 +00:00
|
|
|
})
|
|
|
|
.orderBy('id', 'DESC')
|
|
|
|
.limit(25)
|
|
|
|
.offset(25 * offset)
|
2018-03-24 16:45:51 +00:00
|
|
|
.select('id', 'albumid', 'timestamp', 'name', 'userid', 'size')
|
2018-01-23 20:06:30 +00:00
|
|
|
|
|
|
|
const albums = await db.table('albums')
|
2018-04-28 17:26:39 +00:00
|
|
|
.where(function () {
|
|
|
|
this.where('enabled', 1)
|
|
|
|
if (user.username !== 'root') {
|
|
|
|
this.where('userid', user.id)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2018-04-05 10:52:57 +00:00
|
|
|
const basedomain = config.domain
|
|
|
|
const userids = []
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-04-05 10:52:57 +00:00
|
|
|
for (const file of files) {
|
2018-01-23 20:06:30 +00:00
|
|
|
file.file = `${basedomain}/${file.name}`
|
2018-05-12 14:01:14 +00:00
|
|
|
file.date = utils.getPrettyDate(new Date(file.timestamp * 1000))
|
2018-03-24 16:45:51 +00:00
|
|
|
file.size = utils.getPrettyBytes(parseInt(file.size))
|
2018-01-23 20:06:30 +00:00
|
|
|
|
|
|
|
file.album = ''
|
|
|
|
if (file.albumid !== undefined) {
|
2018-04-05 10:52:57 +00:00
|
|
|
for (const album of albums) {
|
2018-01-23 20:06:30 +00:00
|
|
|
if (file.albumid === album.id) {
|
|
|
|
file.album = album.name
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Only push usernames if we are root
|
|
|
|
if (user.username === 'root') {
|
|
|
|
if (file.userid !== undefined && file.userid !== null && file.userid !== '') {
|
|
|
|
userids.push(file.userid)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-01 20:37:26 +00:00
|
|
|
file.extname = pce(file.name).toLowerCase()
|
2018-05-12 14:01:14 +00:00
|
|
|
if (utils.mayGenerateThumb(file.extname)) {
|
|
|
|
file.thumb = `${basedomain}/thumbs/${file.name.slice(0, -file.extname.length)}.png`
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we are a normal user, send response
|
2018-03-28 17:40:50 +00:00
|
|
|
if (user.username !== 'root') { return res.json({ success: true, files }) }
|
2018-01-23 20:06:30 +00:00
|
|
|
|
|
|
|
// If we are root but there are no uploads attached to a user, send response
|
2018-03-28 17:40:50 +00:00
|
|
|
if (userids.length === 0) { return res.json({ success: true, files }) }
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-04-28 17:26:39 +00:00
|
|
|
const users = await db.table('users')
|
|
|
|
.whereIn('id', userids)
|
2018-04-05 10:52:57 +00:00
|
|
|
for (const dbUser of users) {
|
|
|
|
for (const file of files) {
|
2018-01-23 20:06:30 +00:00
|
|
|
if (file.userid === dbUser.id) {
|
|
|
|
file.username = dbUser.username
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return res.json({ success: true, files })
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = uploadsController
|