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-09-23 16:28:15 +00:00
|
|
|
const fetch = require('node-fetch')
|
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')
|
2018-10-13 11:06:58 +00:00
|
|
|
const perms = require('./permissionController')
|
2018-09-01 20:37:26 +00:00
|
|
|
const randomstring = require('randomstring')
|
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
|
2019-08-20 02:16:34 +00:00
|
|
|
const maxSizeBytes = parseInt(maxSize) * 1e6
|
|
|
|
const urlMaxSizeBytes = parseInt(config.uploads.urlMaxSize) * 1e6
|
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
|
2018-12-18 17:01:28 +00:00
|
|
|
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 => {
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!error) return cb(null, uuidDir)
|
2018-03-29 23:22:08 +00:00
|
|
|
fs.mkdir(uuidDir, error => {
|
2018-12-18 17:01:28 +00:00
|
|
|
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-17 19:32:27 +00:00
|
|
|
const extension = utils.extname(file.originalname)
|
2018-03-28 11:36:28 +00:00
|
|
|
const length = uploadsController.getFileNameLength(req)
|
2018-12-03 09:18:52 +00:00
|
|
|
return uploadsController.getUniqueRandomName(length, extension, req.app.get('uploads-set'))
|
2018-04-28 17:26:39 +00:00
|
|
|
.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-12-18 18:14:24 +00:00
|
|
|
const digits = req.body.totalchunkcount !== undefined ? `${req.body.totalchunkcount - 1}`.length : 1
|
2018-03-28 14:10:20 +00:00
|
|
|
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-17 19:32:27 +00:00
|
|
|
const extname = utils.extname(file.originalname)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (uploadsController.isExtensionFiltered(extname))
|
2018-05-11 14:34:13 +00:00
|
|
|
// eslint-disable-next-line standard/no-callback-literal
|
2018-11-28 17:52:12 +00:00
|
|
|
return cb(`${extname ? `${extname.substr(1).toUpperCase()} files` : 'Files with no extension'} are not permitted.`)
|
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) {
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!/^dz/.test(key)) continue
|
2018-05-09 08:41:30 +00:00
|
|
|
req.body[key.replace(/^dz/, '')] = req.body[key]
|
|
|
|
delete req.body[key]
|
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-12-20 11:53:37 +00:00
|
|
|
if (req.body.chunkindex) {
|
|
|
|
if (!chunkedUploads)
|
2018-05-09 08:41:30 +00:00
|
|
|
// eslint-disable-next-line standard/no-callback-literal
|
2018-11-28 17:52:12 +00:00
|
|
|
return cb('Chunked uploads are disabled at the moment.')
|
2018-12-20 11:53:37 +00:00
|
|
|
|
|
|
|
const totalfilesize = parseInt(req.body.totalfilesize)
|
|
|
|
if (!isNaN(totalfilesize)) {
|
|
|
|
if (config.filterEmptyFile && totalfilesize === 0)
|
|
|
|
// eslint-disable-next-line standard/no-callback-literal
|
|
|
|
return cb('Empty files are not allowed.')
|
|
|
|
if (totalfilesize > maxSizeBytes)
|
|
|
|
// eslint-disable-next-line standard/no-callback-literal
|
|
|
|
return cb('Chunk error occurred. Total file size is larger than the maximum file size.')
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
2018-12-20 11:53:37 +00:00
|
|
|
}
|
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 => {
|
2018-12-20 11:53:37 +00:00
|
|
|
// If empty extension needs to be filtered
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!extname && config.filterNoExtension) return true
|
2018-05-11 14:34:13 +00:00
|
|
|
// If there are extensions that have to be filtered
|
2018-12-20 11:53:37 +00:00
|
|
|
if (extname && Array.isArray(config.extensionsFilter) && config.extensionsFilter.length) {
|
2018-05-11 14:34:13 +00:00
|
|
|
const match = config.extensionsFilter.some(extension => extname === extension.toLowerCase())
|
2018-12-20 11:53:37 +00:00
|
|
|
const whitelist = config.extensionsFilterMode === 'whitelist'
|
|
|
|
if ((!whitelist && match) || (whitelist && !match)) return true
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
|
|
|
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
|
2018-12-18 17:01:28 +00:00
|
|
|
if (req.headers.filelength)
|
2018-03-28 11:36:28 +00:00
|
|
|
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-12-03 09:18:52 +00:00
|
|
|
uploadsController.getUniqueRandomName = (length, extension, set) => {
|
2018-04-28 17:26:39 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const access = i => {
|
2018-11-28 17:52:12 +00:00
|
|
|
const identifier = randomstring.generate(length)
|
2018-12-04 11:58:53 +00:00
|
|
|
if (config.uploads.cacheFileIdentifiers) {
|
2018-12-08 00:38:12 +00:00
|
|
|
// Check whether the identifier is already used in cache
|
2018-12-03 09:18:52 +00:00
|
|
|
if (set.has(identifier)) {
|
2018-12-08 00:38:12 +00:00
|
|
|
console.log(`Identifier ${identifier} is already in use (${++i}/${maxTries}).`)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (i < maxTries) return access(i)
|
2018-12-03 09:18:52 +00:00
|
|
|
// eslint-disable-next-line prefer-promise-reject-errors
|
|
|
|
return reject('Sorry, we could not allocate a unique random name. Try again?')
|
2018-11-28 17:52:12 +00:00
|
|
|
}
|
2018-12-03 09:18:52 +00:00
|
|
|
set.add(identifier)
|
|
|
|
// console.log(`Added ${identifier} to identifiers cache`)
|
2018-11-28 17:52:12 +00:00
|
|
|
return resolve(identifier + extension)
|
2018-12-03 09:18:52 +00:00
|
|
|
} else {
|
2018-12-08 00:38:42 +00:00
|
|
|
// Less stricter collision check, as in the same identifier
|
2018-12-08 00:38:12 +00:00
|
|
|
// can be used by multiple different extensions
|
|
|
|
const name = identifier + extension
|
|
|
|
fs.access(path.join(uploadsDir, name), error => {
|
2018-12-18 17:01:28 +00:00
|
|
|
if (error) return resolve(name)
|
2018-12-08 00:38:12 +00:00
|
|
|
console.log(`A file named ${name} already exists (${++i}/${maxTries}).`)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (i < maxTries) return access(i)
|
2018-12-08 00:38:12 +00:00
|
|
|
// eslint-disable-next-line prefer-promise-reject-errors
|
|
|
|
return reject('Sorry, we could not allocate a unique random name. Try again?')
|
2018-12-03 09:18:52 +00:00
|
|
|
})
|
|
|
|
}
|
2018-04-28 17:26:39 +00:00
|
|
|
}
|
|
|
|
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-12-18 17:01:28 +00:00
|
|
|
if (!user) return
|
2018-12-18 17:41:42 +00:00
|
|
|
} else if (req.headers.token) {
|
2018-03-24 19:47:41 +00:00
|
|
|
user = await db.table('users').where('token', req.headers.token).first()
|
2018-12-18 17:41:42 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-12-18 17:01: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
|
|
|
|
2018-12-18 17:01:28 +00:00
|
|
|
if (user && user.fileLength && !req.headers.filelength)
|
2018-03-28 11:36:28 +00:00
|
|
|
req.headers.filelength = user.fileLength
|
|
|
|
|
2018-04-05 12:54:24 +00:00
|
|
|
let albumid = parseInt(req.headers.albumid || req.params.albumid)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (isNaN(albumid)) albumid = null
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2018-12-18 17:01:28 +00:00
|
|
|
if (req.body.urls)
|
2018-05-11 14:34:13 +00:00
|
|
|
return uploadsController.actuallyUploadByUrl(req, res, user, albumid)
|
2018-12-18 17:01:28 +00:00
|
|
|
else
|
2018-05-11 14:34:13 +00:00
|
|
|
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-12-18 17:01:28 +00:00
|
|
|
if (isError) console.error(error)
|
2018-11-28 17:52:12 +00:00
|
|
|
res.status(400).json({
|
2018-03-28 11:36:28 +00:00
|
|
|
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-10-08 16:14:10 +00:00
|
|
|
if (error) {
|
2019-08-20 02:16:34 +00:00
|
|
|
// Suppress error logging for errors with these codes
|
|
|
|
const suppress = [
|
2018-10-08 16:14:10 +00:00
|
|
|
'LIMIT_FILE_SIZE',
|
|
|
|
'LIMIT_UNEXPECTED_FILE'
|
|
|
|
]
|
2019-08-20 02:16:34 +00:00
|
|
|
if (error.code && suppress.includes(error.code)) return erred(error.toString())
|
2018-10-08 16:14:10 +00:00
|
|
|
return erred(error)
|
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-12-18 17:01:28 +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-12-18 17:01:28 +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-12-20 11:53:37 +00:00
|
|
|
if (config.filterEmptyFile && infoMap.some(file => file.data.size === 0)) {
|
|
|
|
infoMap.forEach(file => {
|
|
|
|
utils.deleteFile(file.data.filename, req.app.get('uploads-set')).catch(console.error)
|
|
|
|
})
|
|
|
|
return erred('Empty files are not allowed.')
|
|
|
|
}
|
|
|
|
|
2018-09-14 21:40:58 +00:00
|
|
|
if (config.uploads.scan && config.uploads.scan.enabled) {
|
2018-12-08 03:56:23 +00:00
|
|
|
const scan = await uploadsController.scanFiles(req, infoMap)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (scan) return erred(scan)
|
2018-09-01 20:37:26 +00:00
|
|
|
}
|
|
|
|
|
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-12-18 17:01:28 +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
|
2018-12-18 17:01:28 +00:00
|
|
|
if (isError) console.error(error)
|
2018-11-28 17:52:12 +00:00
|
|
|
res.status(400).json({
|
2018-05-11 14:34:13 +00:00
|
|
|
success: false,
|
|
|
|
description: isError ? error.toString() : error
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!config.uploads.urlMaxSize) return erred('Upload by URLs is disabled at the moment.')
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2018-12-08 17:55:04 +00:00
|
|
|
const urls = req.body.urls
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!urls || !(urls instanceof Array)) return erred('Missing "urls" property (Array).')
|
2018-05-11 14:34:13 +00:00
|
|
|
|
|
|
|
let iteration = 0
|
|
|
|
const infoMap = []
|
2018-12-20 11:53:37 +00:00
|
|
|
for (let url of urls) {
|
2018-05-11 14:34:13 +00:00
|
|
|
const original = path.basename(url).split(/[?#]/)[0]
|
2018-12-20 11:53:37 +00:00
|
|
|
const extname = utils.extname(original)
|
|
|
|
|
|
|
|
// Extensions filter
|
|
|
|
let filtered = false
|
|
|
|
if (['blacklist', 'whitelist'].includes(config.uploads.urlExtensionsFilterMode))
|
|
|
|
if (Array.isArray(config.uploads.urlExtensionsFilter) && config.uploads.urlExtensionsFilter.length) {
|
|
|
|
const match = config.uploads.urlExtensionsFilter.some(extension => extname === extension.toLowerCase())
|
|
|
|
const whitelist = config.uploads.urlExtensionsFilterMode === 'whitelist'
|
|
|
|
filtered = ((!whitelist && match) || (whitelist && !match))
|
|
|
|
} else {
|
|
|
|
return erred('config.uploads.urlExtensionsFilter is not an array or is an empty array, please contact site owner.')
|
|
|
|
}
|
|
|
|
else filtered = uploadsController.isExtensionFiltered(extname)
|
|
|
|
|
|
|
|
if (filtered)
|
|
|
|
return erred(`${extname ? `${extname.substr(1).toUpperCase()} files` : 'Files with no extension'} are not permitted due to security reasons.`)
|
|
|
|
|
|
|
|
if (config.uploads.urlProxy)
|
|
|
|
url = config.uploads.urlProxy
|
|
|
|
.replace(/{url}/g, encodeURIComponent(url))
|
|
|
|
.replace(/{url-noprot}/g, encodeURIComponent(url.replace(/^https?:\/\//, '')))
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2018-09-23 16:28:15 +00:00
|
|
|
try {
|
2019-04-11 15:27:45 +00:00
|
|
|
// Limit max response body size with maximum allowed size
|
|
|
|
const fetchFile = await fetch(url, { size: urlMaxSizeBytes })
|
2018-12-18 17:01:28 +00:00
|
|
|
if (fetchFile.status !== 200)
|
2019-04-11 15:27:45 +00:00
|
|
|
return erred(`${fetchFile.status} ${fetchFile.statusText}`)
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2019-04-11 15:27:45 +00:00
|
|
|
const headers = fetchFile.headers
|
2018-09-23 16:28:15 +00:00
|
|
|
const file = await fetchFile.buffer()
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2018-09-23 16:28:15 +00:00
|
|
|
const length = uploadsController.getFileNameLength(req)
|
2018-12-20 11:53:37 +00:00
|
|
|
const name = await uploadsController.getUniqueRandomName(length, extname, req.app.get('uploads-set'))
|
2018-09-23 16:28:15 +00:00
|
|
|
|
|
|
|
const destination = path.join(uploadsDir, name)
|
|
|
|
fs.writeFile(destination, file, async error => {
|
2018-12-18 17:01:28 +00:00
|
|
|
if (error) return erred(error)
|
2018-09-23 16:28:15 +00:00
|
|
|
|
|
|
|
const data = {
|
|
|
|
filename: name,
|
|
|
|
originalname: original,
|
|
|
|
mimetype: headers.get('content-type').split(';')[0] || '',
|
2019-04-11 15:27:45 +00:00
|
|
|
size: file.byteLength,
|
2018-09-23 16:28:15 +00:00
|
|
|
albumid
|
2018-09-01 20:37:26 +00:00
|
|
|
}
|
|
|
|
|
2018-09-23 16:28:15 +00:00
|
|
|
infoMap.push({
|
|
|
|
path: destination,
|
|
|
|
data
|
|
|
|
})
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2018-09-23 16:28:15 +00:00
|
|
|
iteration++
|
|
|
|
if (iteration === urls.length) {
|
|
|
|
if (config.uploads.scan && config.uploads.scan.enabled) {
|
2018-12-08 03:56:23 +00:00
|
|
|
const scan = await uploadsController.scanFiles(req, infoMap)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (scan) return erred(scan)
|
2018-09-23 16:28:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const result = await uploadsController.formatInfoMap(req, res, user, infoMap)
|
|
|
|
.catch(erred)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!result) return
|
2018-09-23 16:28:15 +00:00
|
|
|
|
|
|
|
uploadsController.processFilesForDisplay(req, res, result.files, result.existingFiles)
|
|
|
|
}
|
|
|
|
})
|
2018-12-18 17:41:42 +00:00
|
|
|
} catch (error) {
|
|
|
|
erred(error)
|
|
|
|
}
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-28 11:36:28 +00:00
|
|
|
uploadsController.finishChunks = async (req, res, next) => {
|
2018-12-18 17:01:28 +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-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-12-18 17:01:28 +00:00
|
|
|
if (!user) return
|
2018-12-18 17:41:42 +00:00
|
|
|
} else if (req.headers.token) {
|
2018-03-28 11:36:28 +00:00
|
|
|
user = await db.table('users').where('token', req.headers.token).first()
|
2018-12-18 17:41:42 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-12-18 17:01: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
|
|
|
|
2018-12-18 17:01:28 +00:00
|
|
|
if (user && user.fileLength && !req.headers.filelength)
|
2018-03-28 11:36:28 +00:00
|
|
|
req.headers.filelength = user.fileLength
|
|
|
|
|
2018-04-05 12:54:24 +00:00
|
|
|
let albumid = parseInt(req.headers.albumid || req.params.albumid)
|
2018-12-18 17:01:28 +00:00
|
|
|
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-12-18 17:01:28 +00:00
|
|
|
if (isError) console.error(error)
|
2018-11-28 17:52:12 +00:00
|
|
|
res.status(400).json({
|
2018-03-28 11:36:28 +00:00
|
|
|
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-12-18 17:01:28 +00:00
|
|
|
if (!files || !(files instanceof Array) || !files.length) return erred('Invalid "files" property (Array).')
|
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-12-18 17:01:28 +00:00
|
|
|
if (!file.uuid || typeof file.uuid !== 'string') return erred('Invalid "uuid" property (string).')
|
|
|
|
if (typeof file.count !== 'number' || file.count < 1) return erred('Invalid "count" property (number).')
|
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-11-28 17:52:12 +00:00
|
|
|
if (error) {
|
2018-12-18 17:01:28 +00:00
|
|
|
if (error.code === 'ENOENT') return erred('UUID is not being used.')
|
2018-11-28 17:52:12 +00:00
|
|
|
return erred(error)
|
|
|
|
}
|
2018-12-18 17:01:28 +00:00
|
|
|
if (file.count < chunkNames.length) return erred('Chunks count mismatch.')
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-12-20 11:53:37 +00:00
|
|
|
const extname = typeof file.original === 'string' ? utils.extname(file.original) : ''
|
|
|
|
if (uploadsController.isExtensionFiltered(extname))
|
|
|
|
return erred(`${extname ? `${extname.substr(1).toUpperCase()} files` : 'Files with no extension'} are not permitted due to security reasons.`)
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
const length = uploadsController.getFileNameLength(req)
|
2018-12-20 11:53:37 +00:00
|
|
|
const name = await uploadsController.getUniqueRandomName(length, extname, req.app.get('uploads-set'))
|
2018-04-28 17:26:39 +00:00
|
|
|
.catch(erred)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!name) return
|
2018-04-28 17:26:39 +00:00
|
|
|
|
|
|
|
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-12-18 17:01:28 +00:00
|
|
|
if (typeof chunksTotalSize !== 'number') return
|
2018-12-20 11:53:37 +00:00
|
|
|
|
|
|
|
const isEmpty = config.filterEmptyFile && (chunksTotalSize === 0)
|
|
|
|
const isBigger = chunksTotalSize > maxSizeBytes
|
|
|
|
if (isEmpty || isBigger) {
|
2018-05-11 14:34:13 +00:00
|
|
|
// Delete all chunks and remove chunks dir
|
|
|
|
const chunksCleaned = await uploadsController.cleanUpChunks(uuidDir, chunkNames)
|
|
|
|
.catch(erred)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!chunksCleaned) return
|
2018-12-20 11:53:37 +00:00
|
|
|
|
|
|
|
if (isEmpty)
|
|
|
|
return erred('Empty files are not allowed.')
|
|
|
|
else
|
|
|
|
return erred(`Total chunks size is bigger than ${maxSize}.`)
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
|
|
|
|
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)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!chunksAppended) return
|
2018-04-28 17:26:39 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
// Delete all chunks and remove chunks dir
|
|
|
|
const chunksCleaned = await uploadsController.cleanUpChunks(uuidDir, chunkNames)
|
|
|
|
.catch(erred)
|
2018-12-18 17:01:28 +00:00
|
|
|
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)
|
2018-12-18 17:01:28 +00:00
|
|
|
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-14 21:40:58 +00:00
|
|
|
if (config.uploads.scan && config.uploads.scan.enabled) {
|
2018-12-08 03:56:23 +00:00
|
|
|
const scan = await uploadsController.scanFiles(req, infoMap)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (scan) return erred(scan)
|
2018-09-01 20:37:26 +00:00
|
|
|
}
|
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
const result = await uploadsController.formatInfoMap(req, res, user, infoMap)
|
|
|
|
.catch(erred)
|
2018-12-18 17:01:28 +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 => {
|
2018-12-18 17:01:28 +00:00
|
|
|
if (i === chunkNames.length) return resolve(size)
|
2018-05-11 14:34:13 +00:00
|
|
|
fs.stat(path.join(uuidDir, chunkNames[i]), (error, stats) => {
|
2018-12-18 17:01:28 +00:00
|
|
|
if (error) return reject(error)
|
2018-05-11 14:34:13 +00:00
|
|
|
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)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-08-03 23:37:55 +00:00
|
|
|
uploadsController.cleanUpChunks = async (uuidDir, chunkNames) => {
|
|
|
|
await Promise.all(chunkNames.map(chunkName =>
|
|
|
|
new Promise((resolve, reject) => {
|
|
|
|
const chunkPath = path.join(uuidDir, chunkName)
|
|
|
|
fs.unlink(chunkPath, error => {
|
|
|
|
if (error && error.code !== 'ENOENT')
|
|
|
|
return reject(error)
|
|
|
|
resolve()
|
2018-05-11 14:34:13 +00:00
|
|
|
})
|
2019-08-03 23:37:55 +00:00
|
|
|
})
|
|
|
|
))
|
|
|
|
return new Promise((resolve, reject) => {
|
2018-05-11 14:34:13 +00:00
|
|
|
fs.rmdir(uuidDir, error => {
|
2019-08-03 23:42:35 +00:00
|
|
|
if (error) return reject(error)
|
2018-05-11 14:34:13 +00:00
|
|
|
resolve(true)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-05-10 17:25:52 +00:00
|
|
|
uploadsController.formatInfoMap = (req, res, user, infoMap) => {
|
2019-08-03 23:42:35 +00:00
|
|
|
return new Promise(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-12-18 17:01:28 +00:00
|
|
|
if (user === undefined)
|
2018-03-28 17:40:50 +00:00
|
|
|
this.whereNull('userid')
|
2018-12-18 17:01:28 +00:00
|
|
|
else
|
2018-03-28 17:40:50 +00:00
|
|
|
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,
|
2019-06-04 00:57:37 +00:00
|
|
|
ip: config.uploads.storeIP !== false ? req.ip : null, // only disable if explicitly set to false
|
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)
|
|
|
|
})
|
2019-04-12 00:45:33 +00:00
|
|
|
utils.invalidateStatsCache('uploads')
|
2018-01-23 20:06:30 +00:00
|
|
|
} else {
|
2018-12-20 11:53:37 +00:00
|
|
|
utils.deleteFile(info.data.filename, req.app.get('uploads-set')).catch(console.error)
|
2018-01-23 20:06:30 +00:00
|
|
|
existingFiles.push(dbFile)
|
|
|
|
}
|
|
|
|
|
|
|
|
iteration++
|
2018-12-18 17:01:28 +00:00
|
|
|
if (iteration === infoMap.length)
|
2018-05-11 14:34:13 +00:00
|
|
|
resolve({ files, existingFiles })
|
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-12-08 03:56:23 +00:00
|
|
|
uploadsController.scanFiles = (req, infoMap) => {
|
2019-08-03 23:37:55 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
2018-12-08 03:56:23 +00:00
|
|
|
const scanner = req.app.get('clam-scanner')
|
2019-04-18 09:06:14 +00:00
|
|
|
const timeout = config.uploads.scan.timeout || 5000
|
|
|
|
const chunkSize = config.uploads.scan.chunkSize || 64 * 1024
|
2018-09-01 20:37:26 +00:00
|
|
|
let iteration = 0
|
2018-12-18 17:01:28 +00:00
|
|
|
for (const info of infoMap)
|
2019-04-18 09:06:14 +00:00
|
|
|
scanner.scanFile(info.path, timeout, chunkSize).then(reply => {
|
|
|
|
iteration++
|
|
|
|
const lastIteration = iteration === infoMap.length
|
2018-09-04 15:48:24 +00:00
|
|
|
if (!reply.includes('OK') || reply.includes('FOUND')) {
|
2018-12-20 12:25:41 +00:00
|
|
|
// eslint-disable-next-line no-control-regex
|
2018-09-20 10:45:16 +00:00
|
|
|
const virus = reply.replace(/^stream: /, '').replace(/ FOUND\u0000$/, '')
|
|
|
|
console.log(`ClamAV: ${info.data.filename}: ${virus} FOUND.`)
|
2019-04-18 09:06:14 +00:00
|
|
|
return resolve({ virus, lastIteration })
|
2018-09-01 20:37:26 +00:00
|
|
|
}
|
2019-04-18 09:06:14 +00:00
|
|
|
if (lastIteration) resolve(null)
|
2018-09-20 10:45:16 +00:00
|
|
|
}).catch(reject)
|
2019-04-18 09:06:14 +00:00
|
|
|
}).then(result => {
|
|
|
|
if (!result) return false
|
2018-12-08 03:56:23 +00:00
|
|
|
// If there is at least one dirty file, then delete all files
|
|
|
|
const set = req.app.get('uploads-set')
|
|
|
|
infoMap.forEach(info => {
|
|
|
|
utils.deleteFile(info.data.filename).catch(console.error)
|
|
|
|
if (set) {
|
|
|
|
const identifier = info.data.filename.split('.')[0]
|
|
|
|
set.delete(identifier)
|
|
|
|
// console.log(`Removed ${identifier} from identifiers cache (formatInfoMap)`)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
// Unfortunately, we will only be returning name of the first virus
|
|
|
|
// even if the current session was made up by multiple virus types
|
2019-04-18 09:06:14 +00:00
|
|
|
return `Threat found: ${result.virus}${result.lastIteration ? '' : ', and maybe more'}.`
|
2018-09-20 10:45:16 +00:00
|
|
|
}).catch(error => {
|
|
|
|
console.error(`ClamAV: ${error.toString()}.`)
|
2019-08-20 02:16:34 +00:00
|
|
|
return `ClamAV: ${error.code !== undefined ? `${error.code}, p` : 'P'}lease contact the site owner.`
|
2018-09-01 20:37:26 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
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-12-18 17:01:28 +00:00
|
|
|
for (const file of files)
|
2018-05-12 14:01:14 +00:00
|
|
|
responseFiles.push(file)
|
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-12-18 17:01:28 +00:00
|
|
|
if (existingFiles.length)
|
|
|
|
for (const file of existingFiles)
|
2018-05-12 14:01:14 +00:00
|
|
|
responseFiles.push(file)
|
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
|
2019-01-09 10:11:45 +00:00
|
|
|
const nojs = req.path === '/nojs'
|
2018-05-12 14:01:14 +00:00
|
|
|
res.json({
|
|
|
|
success: true,
|
|
|
|
files: responseFiles.map(file => {
|
2019-01-09 10:11:45 +00:00
|
|
|
const result = {
|
2018-04-12 14:37:42 +00:00
|
|
|
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
|
|
|
}
|
2019-01-09 10:11:45 +00:00
|
|
|
// Add original name if it's /nojs route
|
|
|
|
if (nojs) result.original = file.original
|
|
|
|
return result
|
2018-04-04 17:38:15 +00:00
|
|
|
})
|
2018-05-12 14:01:14 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
const albumids = []
|
|
|
|
for (const file of files) {
|
2018-12-18 17:01:28 +00:00
|
|
|
if (file.albumid && !albumids.includes(file.albumid))
|
2018-05-12 14:01:14 +00:00
|
|
|
albumids.push(file.albumid)
|
2018-12-18 17:01:28 +00:00
|
|
|
|
|
|
|
if (utils.mayGenerateThumb(utils.extname(file.name)))
|
2018-05-12 14:01:14 +00:00
|
|
|
utils.generateThumbs(file.name)
|
2018-04-12 14:37:42 +00:00
|
|
|
}
|
|
|
|
|
2018-12-18 17:01:28 +00:00
|
|
|
if (albumids.length)
|
2019-01-09 10:11:45 +00:00
|
|
|
db.table('albums')
|
2018-05-12 14:01:14 +00:00
|
|
|
.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-12-18 18:14:24 +00:00
|
|
|
const id = parseInt(req.body.id)
|
2019-01-01 19:39:08 +00:00
|
|
|
const body = {
|
|
|
|
field: 'id',
|
|
|
|
values: isNaN(id) ? undefined : [id]
|
|
|
|
}
|
|
|
|
req.body = body
|
2018-05-09 09:53:27 +00:00
|
|
|
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)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!user) return
|
2018-05-05 19:44:58 +00:00
|
|
|
|
|
|
|
const field = req.body.field || 'id'
|
|
|
|
const values = req.body.values
|
2018-09-04 15:49:37 +00:00
|
|
|
|
2018-12-18 17:01:28 +00:00
|
|
|
if (!values || !Array.isArray(values) || !values.length)
|
2018-09-04 15:49:37 +00:00
|
|
|
return res.json({ success: false, description: 'No array of files specified.' })
|
2018-03-29 23:22:08 +00:00
|
|
|
|
2018-12-03 09:18:52 +00:00
|
|
|
const failed = await utils.bulkDeleteFiles(field, values, user, req.app.get('uploads-set'))
|
2019-04-12 00:45:33 +00:00
|
|
|
utils.invalidateStatsCache('uploads')
|
2018-12-18 17:01:28 +00:00
|
|
|
if (failed.length < values.length)
|
2018-05-05 19:44:58 +00:00
|
|
|
return res.json({ success: true, failed })
|
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-12-18 17:01:28 +00:00
|
|
|
if (!user) return
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2018-10-09 19:52:41 +00:00
|
|
|
// Headers is string-only, this seem to be the safest and lightest
|
|
|
|
const all = req.headers.all === '1'
|
2019-06-17 19:34:15 +00:00
|
|
|
const filters = req.headers.filters
|
2018-10-13 11:06:58 +00:00
|
|
|
const ismoderator = perms.is(user, 'moderator')
|
2019-06-17 19:34:15 +00:00
|
|
|
if ((all || filters) && !ismoderator) return res.status(403).end()
|
2019-01-03 04:49:56 +00:00
|
|
|
|
2019-06-04 00:57:37 +00:00
|
|
|
const basedomain = config.domain
|
|
|
|
|
2019-06-17 19:34:15 +00:00
|
|
|
// For filtering uploads
|
|
|
|
const _filters = {
|
|
|
|
uploaders: [],
|
|
|
|
names: [],
|
|
|
|
ips: [],
|
|
|
|
flags: {
|
|
|
|
nouser: false,
|
|
|
|
noip: false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Perhaps this can be simplified even further?
|
|
|
|
if (filters) {
|
|
|
|
const usernames = []
|
|
|
|
filters
|
|
|
|
.split(' ')
|
|
|
|
.map((v, i, a) => {
|
|
|
|
if (/[^\\]\\$/.test(v) && a[i + 1]) {
|
|
|
|
const tmp = `${v.slice(0, -1)} ${a[i + 1]}`
|
|
|
|
a[i + 1] = ''
|
|
|
|
return tmp
|
|
|
|
}
|
|
|
|
return v.replace(/\\\\/, '\\')
|
|
|
|
})
|
|
|
|
.map((v, i) => {
|
|
|
|
const x = v.indexOf(':')
|
|
|
|
if (x >= 0 && v.substring(x + 1))
|
|
|
|
return [v.substring(0, x), v.substring(x + 1)]
|
|
|
|
else if (v.startsWith('-'))
|
|
|
|
return [v]
|
|
|
|
})
|
|
|
|
.forEach(v => {
|
|
|
|
if (!v) return
|
|
|
|
if (v[0] === 'user') usernames.push(v[1])
|
|
|
|
else if (v[0] === 'name') _filters.names.push(v[1])
|
|
|
|
else if (v[0] === 'ip') _filters.ips.push(v[1])
|
|
|
|
else if (v[0] === '-user') _filters.flags.nouser = true
|
|
|
|
else if (v[0] === '-ip') _filters.flags.noip = true
|
|
|
|
})
|
|
|
|
_filters.uploaders = await db.table('users')
|
|
|
|
.whereIn('username', usernames)
|
2019-06-17 19:48:42 +00:00
|
|
|
.select('id', 'username')
|
2019-06-04 00:57:37 +00:00
|
|
|
}
|
2018-10-09 19:52:41 +00:00
|
|
|
|
2019-01-01 19:39:08 +00:00
|
|
|
function filter () {
|
2019-06-17 19:34:15 +00:00
|
|
|
if (req.params.id !== undefined) {
|
2019-01-01 19:39:08 +00:00
|
|
|
this.where('albumid', req.params.id)
|
2019-06-17 19:34:15 +00:00
|
|
|
} else if (!all) {
|
2019-01-01 19:39:08 +00:00
|
|
|
this.where('userid', user.id)
|
2019-06-17 19:34:15 +00:00
|
|
|
} else {
|
|
|
|
// Fisrt, look for uploads matching ANY of the supplied 'user' OR 'ip' filters
|
2019-06-17 19:48:42 +00:00
|
|
|
// Then, refine the matches using the supplied 'name' filters
|
2019-06-17 19:34:15 +00:00
|
|
|
const raw = []
|
|
|
|
const source = []
|
|
|
|
if (_filters.uploaders.length)
|
2019-06-17 19:48:42 +00:00
|
|
|
source.push(`\`userid\` in (${_filters.uploaders.map(v => `'${v.id}'`).join(', ')})`)
|
2019-06-17 19:34:15 +00:00
|
|
|
if (_filters.ips.length)
|
|
|
|
source.push(`\`ip\` in (${_filters.ips.map(v => `'${v}'`).join(', ')})`)
|
|
|
|
if (_filters.flags.nouser)
|
|
|
|
source.push('(`userid` is null or \'\')')
|
|
|
|
if (_filters.flags.noip)
|
|
|
|
source.push('(`ip` is null or \'\')')
|
|
|
|
if (source.length)
|
|
|
|
raw.push(`(${source.join(' or ')})`)
|
|
|
|
if (_filters.names.length)
|
|
|
|
raw.push(`(${_filters.names.map(v => {
|
|
|
|
if (v.includes('*'))
|
|
|
|
return `\`name\` like '${v.replace(/\*/g, '%')}'`
|
|
|
|
else
|
|
|
|
return `\`name\` = '${v}'`
|
|
|
|
}).join(' or ')})`)
|
|
|
|
this.whereRaw(raw.join(' and '))
|
|
|
|
}
|
2019-01-01 19:39:08 +00:00
|
|
|
}
|
|
|
|
|
2019-06-04 00:57:37 +00:00
|
|
|
// Query uploads count for pagination
|
2019-01-01 19:39:08 +00:00
|
|
|
const count = await db.table('files')
|
|
|
|
.where(filter)
|
|
|
|
.count('id as count')
|
|
|
|
.then(rows => rows[0].count)
|
|
|
|
if (!count) return res.json({ success: true, files: [], count })
|
|
|
|
|
|
|
|
let offset = req.params.page
|
|
|
|
if (offset === undefined) offset = 0
|
|
|
|
|
2019-06-04 00:57:37 +00:00
|
|
|
const columns = ['id', 'timestamp', 'name', 'userid', 'size']
|
|
|
|
// Only select IPs if we are listing all uploads
|
|
|
|
columns.push(all ? 'ip' : 'albumid')
|
|
|
|
|
2018-01-23 20:06:30 +00:00
|
|
|
const files = await db.table('files')
|
2019-01-01 19:39:08 +00:00
|
|
|
.where(filter)
|
2018-01-23 20:06:30 +00:00
|
|
|
.orderBy('id', 'DESC')
|
|
|
|
.limit(25)
|
|
|
|
.offset(25 * offset)
|
2019-06-04 00:57:37 +00:00
|
|
|
.select(columns)
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2019-06-18 18:48:30 +00:00
|
|
|
if (!files.length) return res.json({ success: true, files, count, basedomain })
|
|
|
|
|
2018-04-05 10:52:57 +00:00
|
|
|
for (const file of files) {
|
2018-09-17 19:32:27 +00:00
|
|
|
file.extname = utils.extname(file.name)
|
2018-12-18 17:01:28 +00:00
|
|
|
if (utils.mayGenerateThumb(file.extname))
|
2019-07-26 16:54:45 +00:00
|
|
|
file.thumb = `thumbs/${file.name.slice(0, -file.extname.length)}.png`
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
|
|
|
|
2019-06-04 00:57:37 +00:00
|
|
|
// If we are not listing all uploads, query album names
|
|
|
|
let albums = {}
|
|
|
|
if (!all) {
|
|
|
|
const albumids = files
|
|
|
|
.map(file => file.albumid)
|
|
|
|
.filter((v, i, a) => {
|
|
|
|
return v !== null && v !== undefined && v !== '' && a.indexOf(v) === i
|
|
|
|
})
|
|
|
|
albums = await db.table('albums')
|
|
|
|
.whereIn('id', albumids)
|
|
|
|
.where('enabled', 1)
|
|
|
|
.where('userid', user.id)
|
|
|
|
.select('id', 'name')
|
|
|
|
.then(rows => {
|
|
|
|
// Build Object indexed by their IDs
|
|
|
|
const obj = {}
|
|
|
|
for (const row of rows) obj[row.id] = row.name
|
|
|
|
return obj
|
|
|
|
})
|
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2019-06-17 19:48:42 +00:00
|
|
|
// If we are not listing all uploads, send response
|
|
|
|
if (!all) return res.json({ success: true, files, count, albums, basedomain })
|
2019-06-04 00:57:37 +00:00
|
|
|
|
|
|
|
// Otherwise proceed to querying usernames
|
2019-06-17 19:48:42 +00:00
|
|
|
let _users = _filters.uploaders
|
|
|
|
if (!_users.length) {
|
|
|
|
const userids = files
|
|
|
|
.map(file => file.userid)
|
|
|
|
.filter((v, i, a) => {
|
|
|
|
return v !== null && v !== undefined && v !== '' && a.indexOf(v) === i
|
|
|
|
})
|
2019-06-04 00:57:37 +00:00
|
|
|
|
2019-06-17 19:48:42 +00:00
|
|
|
// If there are no uploads attached to a registered user, send response
|
|
|
|
if (userids.length === 0) return res.json({ success: true, files, count, basedomain })
|
|
|
|
|
|
|
|
// Query usernames of user IDs from currently selected files
|
|
|
|
_users = await db.table('users')
|
|
|
|
.whereIn('id', userids)
|
|
|
|
.select('id', 'username')
|
|
|
|
}
|
|
|
|
|
|
|
|
const users = {}
|
|
|
|
for (const user of _users)
|
|
|
|
users[user.id] = user.username
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2019-06-04 00:57:37 +00:00
|
|
|
return res.json({ success: true, files, count, users, basedomain })
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = uploadsController
|