2020-05-28 19:52:58 +00:00
|
|
|
const blake3 = require('blake3')
|
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')
|
Updates (very important to read)
Client-side CSS & JS files will now be processed with Gulp.
Gulp tasks are configured in gulpfile.js file.
CSS files will be optimized with postcss-preset-env, which will
auto-add vendor prefixes and convert any parts necessary for browsers
compatibility.
Afterwards they will be minified with cssnano.
JS files will be optimized with bublé,
likewise for browsers compatibility.
Afterwards they will be minified with terser.
Unprocessed CSS & JS files will now be located at src directory, while
the processed results will be located at dist directory.
Due to bublé, the JS files should now be compatible up to IE 11
at the minimum.
Previously the safe would not work in IE 11 due to extensive usage of
template literals.
Due to that as well, JS files in src directory will now extensively use
arrow functions for my personal comfort (as they will be converted too).
The server will use the processed files at dist directory by default.
If you want to rebuild the files by your own, you can run "yarn build".
Gulp is a development dependency, so make sure you have installed all
development dependencies (e.i. NOT using "yarn install --production").
---
yarn lint -> gulp lint
yarn build -> gulp default
yarn watch -> gulp watch
yarn develop -> env NODE_ENV=development yarn watch
---
Fixed not being able to demote staff into normal users.
/api/token/verify will no longer respond with 401 HTTP error code,
unless an error occurred (which will be 500 HTTP error code).
Fixed /nojs route not displaying file's original name when a duplicate
is found on the server.
Removed is-breeze CSS class name, in favor of Bulma's is-info.
Removed custom styling from auth page, in favor of global styling.
Removed all usage of style HTML attribute in favor of CSS classes.
Renamed js/s/ to js/misc/.
Use loading spinners on dashboard's sidebar menus.
Disable all other sidebar menus when something is loading.
Changed title HTML attribute of disabled control buttons in
uploads & users list.
Hid checkboxes and WIP controls from users list.
Better error messages handling.
Especially homepage will now support CF's HTTP error codes.
Updated various icons.
Also, added fontello config file at public/libs/fontello/config.json.
This should let you edit them more easily with fontello.
Use Gatsby icon for my blog's link in homepage's footer.
A bunch of other improvements here & there.
2019-09-15 06:20:11 +00:00
|
|
|
const randomstring = require('randomstring')
|
2020-04-18 19:52:11 +00:00
|
|
|
const searchQuery = require('search-query-parser')
|
2019-09-08 01:56:29 +00:00
|
|
|
const paths = require('./pathsController')
|
2018-10-13 11:06:58 +00:00
|
|
|
const perms = require('./permissionController')
|
2018-04-13 16:20:57 +00:00
|
|
|
const utils = require('./utilsController')
|
2021-01-08 02:44:04 +00:00
|
|
|
const apiErrorsHandler = require('./handlers/apiErrorsHandler.js')
|
|
|
|
const ClientError = require('./utils/ClientError')
|
2021-01-08 00:25:27 +00:00
|
|
|
const multerStorage = require('./utils/multerStorage')
|
2021-01-08 02:44:04 +00:00
|
|
|
const ServerError = require('./utils/ServerError')
|
Updates (very important to read)
Client-side CSS & JS files will now be processed with Gulp.
Gulp tasks are configured in gulpfile.js file.
CSS files will be optimized with postcss-preset-env, which will
auto-add vendor prefixes and convert any parts necessary for browsers
compatibility.
Afterwards they will be minified with cssnano.
JS files will be optimized with bublé,
likewise for browsers compatibility.
Afterwards they will be minified with terser.
Unprocessed CSS & JS files will now be located at src directory, while
the processed results will be located at dist directory.
Due to bublé, the JS files should now be compatible up to IE 11
at the minimum.
Previously the safe would not work in IE 11 due to extensive usage of
template literals.
Due to that as well, JS files in src directory will now extensively use
arrow functions for my personal comfort (as they will be converted too).
The server will use the processed files at dist directory by default.
If you want to rebuild the files by your own, you can run "yarn build".
Gulp is a development dependency, so make sure you have installed all
development dependencies (e.i. NOT using "yarn install --production").
---
yarn lint -> gulp lint
yarn build -> gulp default
yarn watch -> gulp watch
yarn develop -> env NODE_ENV=development yarn watch
---
Fixed not being able to demote staff into normal users.
/api/token/verify will no longer respond with 401 HTTP error code,
unless an error occurred (which will be 500 HTTP error code).
Fixed /nojs route not displaying file's original name when a duplicate
is found on the server.
Removed is-breeze CSS class name, in favor of Bulma's is-info.
Removed custom styling from auth page, in favor of global styling.
Removed all usage of style HTML attribute in favor of CSS classes.
Renamed js/s/ to js/misc/.
Use loading spinners on dashboard's sidebar menus.
Disable all other sidebar menus when something is loading.
Changed title HTML attribute of disabled control buttons in
uploads & users list.
Hid checkboxes and WIP controls from users list.
Better error messages handling.
Especially homepage will now support CF's HTTP error codes.
Updated various icons.
Also, added fontello config file at public/libs/fontello/config.json.
This should let you edit them more easily with fontello.
Use Gatsby icon for my blog's link in homepage's footer.
A bunch of other improvements here & there.
2019-09-15 06:20:11 +00:00
|
|
|
const config = require('./../config')
|
|
|
|
const logger = require('./../logger')
|
2017-01-13 07:34:21 +00:00
|
|
|
|
2020-09-26 22:18:42 +00:00
|
|
|
const self = {
|
2022-04-22 21:44:01 +00:00
|
|
|
onHold: new Set(),
|
|
|
|
scanHelpers: {}
|
2020-09-26 22:18:42 +00:00
|
|
|
}
|
2017-01-13 07:34:21 +00:00
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Preferences */
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const fileIdentifierLengthFallback = 32
|
|
|
|
const fileIdentifierLengthChangeable = !config.uploads.fileIdentifierLength.force &&
|
|
|
|
typeof config.uploads.fileIdentifierLength.min === 'number' &&
|
|
|
|
typeof config.uploads.fileIdentifierLength.max === 'number'
|
|
|
|
|
|
|
|
const maxSize = parseInt(config.uploads.maxSize)
|
|
|
|
const maxSizeBytes = maxSize * 1e6
|
2022-05-08 08:19:29 +00:00
|
|
|
const urlMaxSize = parseInt(config.uploads.urlMaxSize)
|
|
|
|
const urlMaxSizeBytes = urlMaxSize * 1e6
|
2018-03-13 14:51:39 +00:00
|
|
|
|
2019-09-23 08:09:15 +00:00
|
|
|
const maxFilesPerUpload = 20
|
|
|
|
|
2020-05-28 19:52:58 +00:00
|
|
|
const chunkedUploads = config.uploads.chunkSize &&
|
|
|
|
typeof config.uploads.chunkSize === 'object' &&
|
|
|
|
config.uploads.chunkSize.default
|
2020-06-15 16:48:43 +00:00
|
|
|
const chunkedUploadsTimeout = config.uploads.chunkSize.timeout || 1800000
|
2019-09-08 01:56:29 +00:00
|
|
|
const chunksData = {}
|
2020-11-20 23:31:36 +00:00
|
|
|
// Hard-coded min chunk size of 1 MB (e.g. 50 MB = max 50 chunks)
|
2019-09-08 01:56:29 +00:00
|
|
|
const maxChunksCount = maxSize
|
2020-11-20 23:31:36 +00:00
|
|
|
// Use fs.copyFile() instead of fs.rename() if chunks dir is NOT inside uploads dir
|
|
|
|
const chunksCopyFile = !paths.chunks.startsWith(paths.uploads)
|
2019-09-08 01:56:29 +00:00
|
|
|
|
|
|
|
const extensionsFilter = Array.isArray(config.extensionsFilter) &&
|
|
|
|
config.extensionsFilter.length
|
|
|
|
const urlExtensionsFilter = Array.isArray(config.uploads.urlExtensionsFilter) &&
|
|
|
|
config.uploads.urlExtensionsFilter.length
|
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Chunks helper class & function **/
|
|
|
|
|
2020-06-15 16:48:43 +00:00
|
|
|
class ChunksData {
|
|
|
|
constructor (uuid, root) {
|
|
|
|
this.uuid = uuid
|
|
|
|
this.root = root
|
|
|
|
this.filename = 'tmp'
|
|
|
|
this.chunks = 0
|
|
|
|
this.stream = null
|
|
|
|
this.hasher = null
|
|
|
|
}
|
|
|
|
|
|
|
|
onTimeout () {
|
2022-05-08 05:01:18 +00:00
|
|
|
self.cleanUpChunks(this.uuid)
|
2020-06-15 16:48:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
setTimeout (delay) {
|
|
|
|
this.clearTimeout()
|
|
|
|
this._timeout = setTimeout(this.onTimeout.bind(this), delay)
|
|
|
|
}
|
|
|
|
|
|
|
|
clearTimeout () {
|
2020-10-30 18:12:09 +00:00
|
|
|
if (this._timeout) {
|
2020-06-15 16:48:43 +00:00
|
|
|
clearTimeout(this._timeout)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-06-15 16:48:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const initChunks = async uuid => {
|
|
|
|
if (chunksData[uuid] === undefined) {
|
|
|
|
const root = path.join(paths.chunks, uuid)
|
|
|
|
try {
|
|
|
|
await paths.access(root)
|
|
|
|
} catch (err) {
|
|
|
|
// Re-throw error
|
2020-10-30 18:12:09 +00:00
|
|
|
if (err && err.code !== 'ENOENT') throw err
|
2019-09-08 01:56:29 +00:00
|
|
|
await paths.mkdir(root)
|
2018-03-13 14:51:39 +00:00
|
|
|
}
|
2020-06-15 16:48:43 +00:00
|
|
|
chunksData[uuid] = new ChunksData(uuid, root)
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
2020-06-15 16:48:43 +00:00
|
|
|
chunksData[uuid].setTimeout(chunkedUploadsTimeout)
|
2020-06-15 16:14:33 +00:00
|
|
|
return chunksData[uuid]
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
2017-01-13 07:34:21 +00:00
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Multer */
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const executeMulter = multer({
|
2022-04-16 16:06:25 +00:00
|
|
|
// Guide: https://github.com/expressjs/multer/tree/v1.4.4#limits
|
2018-03-28 11:36:28 +00:00
|
|
|
limits: {
|
2019-09-17 04:13:41 +00:00
|
|
|
fileSize: maxSizeBytes,
|
|
|
|
// Maximum number of non-file fields.
|
|
|
|
// Dropzone.js will add 6 extra fields for chunked uploads.
|
|
|
|
// We don't use them for anything else.
|
|
|
|
fields: 6,
|
|
|
|
// Maximum number of file fields.
|
2020-10-30 18:12:09 +00:00
|
|
|
// Chunked uploads still need to provide ONLY 1 file field.
|
2019-09-17 04:13:41 +00:00
|
|
|
// Otherwise, only one of the files will end up being properly stored,
|
|
|
|
// and that will also be as a chunk.
|
2019-09-23 08:09:15 +00:00
|
|
|
files: maxFilesPerUpload
|
2018-03-28 11:36:28 +00:00
|
|
|
},
|
2018-04-05 10:52:57 +00:00
|
|
|
fileFilter (req, file, cb) {
|
2022-07-03 03:18:04 +00:00
|
|
|
// BUG: Since multer@1.4.5-lts.1, UTF-8 filenames are not handled properly, so we force it
|
|
|
|
file.originalname = file.originalname &&
|
|
|
|
Buffer.from(file.originalname, 'latin1').toString('utf8')
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
file.extname = utils.extname(file.originalname)
|
2020-10-30 18:12:09 +00:00
|
|
|
if (self.isExtensionFiltered(file.extname)) {
|
2021-01-08 02:44:04 +00:00
|
|
|
return cb(new ClientError(`${file.extname ? `${file.extname.substr(1).toUpperCase()} files` : 'Files with no extension'} are not permitted.`))
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2022-07-03 03:18:04 +00:00
|
|
|
// Re-map Dropzone chunked uploads keys so people can manually use the API without prepending 'dz'
|
2018-05-09 08:41:30 +00:00
|
|
|
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
|
|
|
|
2020-10-30 18:12:09 +00:00
|
|
|
if (req.body.chunkindex !== undefined && !chunkedUploads) {
|
2021-01-08 02:44:04 +00:00
|
|
|
return cb(new ClientError('Chunked uploads are disabled at the moment.'))
|
2020-10-30 18:12:09 +00:00
|
|
|
} else {
|
2019-09-08 01:56:29 +00:00
|
|
|
return cb(null, true)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
},
|
2020-05-28 19:52:58 +00:00
|
|
|
storage: multerStorage({
|
2019-09-08 01:56:29 +00:00
|
|
|
destination (req, file, cb) {
|
2020-05-28 19:52:58 +00:00
|
|
|
// Is file a chunk!?
|
2020-06-15 16:14:33 +00:00
|
|
|
file._isChunk = chunkedUploads && req.body.uuid !== undefined && req.body.chunkindex !== undefined
|
2020-05-28 19:52:58 +00:00
|
|
|
|
2020-10-30 18:12:09 +00:00
|
|
|
if (file._isChunk) {
|
2022-05-08 05:01:18 +00:00
|
|
|
// Calling this will also reset its timeout
|
2020-05-28 19:52:58 +00:00
|
|
|
initChunks(req.body.uuid)
|
2020-06-15 16:14:33 +00:00
|
|
|
.then(chunksData => {
|
|
|
|
file._chunksData = chunksData
|
|
|
|
cb(null, chunksData.root)
|
|
|
|
})
|
2020-05-28 19:52:58 +00:00
|
|
|
.catch(error => {
|
|
|
|
logger.error(error)
|
2021-01-08 02:44:04 +00:00
|
|
|
return cb(new ServerError('Could not process the chunked upload. Try again?'))
|
2020-05-28 19:52:58 +00:00
|
|
|
})
|
2020-10-30 18:12:09 +00:00
|
|
|
} else {
|
2019-09-08 01:56:29 +00:00
|
|
|
return cb(null, paths.uploads)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
filename (req, file, cb) {
|
2020-06-15 16:14:33 +00:00
|
|
|
if (file._isChunk) {
|
|
|
|
return cb(null, chunksData[req.body.uuid].filename)
|
2020-05-28 19:52:58 +00:00
|
|
|
} else {
|
2019-09-08 01:56:29 +00:00
|
|
|
const length = self.parseFileIdentifierLength(req.headers.filelength)
|
|
|
|
return self.getUniqueRandomName(length, file.extname)
|
|
|
|
.then(name => cb(null, name))
|
|
|
|
.catch(error => cb(error))
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
2022-04-15 09:41:05 +00:00
|
|
|
},
|
|
|
|
|
2022-04-22 21:44:01 +00:00
|
|
|
scan: utils.scan,
|
|
|
|
scanHelpers: self.scanHelpers
|
2019-09-08 01:56:29 +00:00
|
|
|
})
|
2019-09-19 01:27:19 +00:00
|
|
|
}).array('files[]')
|
2017-01-13 07:34:21 +00:00
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Helper functions */
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
self.isExtensionFiltered = extname => {
|
2018-12-20 11:53:37 +00:00
|
|
|
// If empty extension needs to be filtered
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!extname && config.filterNoExtension) return true
|
2019-09-08 01:56:29 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
// If there are extensions that have to be filtered
|
2019-09-08 01:56:29 +00:00
|
|
|
if (extname && extensionsFilter) {
|
2021-01-31 22:23:53 +00:00
|
|
|
const match = config.extensionsFilter.includes(extname.toLowerCase())
|
2018-12-20 11:53:37 +00:00
|
|
|
const whitelist = config.extensionsFilterMode === 'whitelist'
|
2020-10-30 18:12:09 +00:00
|
|
|
if ((!whitelist && match) || (whitelist && !match)) return true
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
self.parseFileIdentifierLength = fileLength => {
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!config.uploads.fileIdentifierLength) return fileIdentifierLengthFallback
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const parsed = parseInt(fileLength)
|
|
|
|
if (isNaN(parsed) ||
|
|
|
|
!fileIdentifierLengthChangeable ||
|
|
|
|
parsed < config.uploads.fileIdentifierLength.min ||
|
2020-10-30 18:12:09 +00:00
|
|
|
parsed > config.uploads.fileIdentifierLength.max) {
|
2019-09-08 01:56:29 +00:00
|
|
|
return config.uploads.fileIdentifierLength.default || fileIdentifierLengthFallback
|
2020-10-30 18:12:09 +00:00
|
|
|
} else {
|
2019-09-08 01:56:29 +00:00
|
|
|
return parsed
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
self.getUniqueRandomName = async (length, extension) => {
|
|
|
|
for (let i = 0; i < utils.idMaxTries; i++) {
|
|
|
|
const identifier = randomstring.generate(length)
|
|
|
|
const name = identifier + extension
|
|
|
|
if (config.uploads.cacheFileIdentifiers) {
|
|
|
|
if (utils.idSet.has(identifier)) {
|
|
|
|
logger.log(`Identifier ${identifier} is already in use (${i + 1}/${utils.idMaxTries}).`)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
utils.idSet.add(identifier)
|
2022-04-15 08:30:32 +00:00
|
|
|
logger.debug(`Added ${identifier} to identifiers cache`)
|
2020-09-26 22:18:42 +00:00
|
|
|
} else if (config.uploads.queryDbForFileCollisions) {
|
2020-10-30 18:12:09 +00:00
|
|
|
if (self.onHold.has(identifier)) continue
|
2020-09-26 22:18:42 +00:00
|
|
|
|
|
|
|
// Put token on-hold (wait for it to be inserted to DB)
|
|
|
|
self.onHold.add(identifier)
|
|
|
|
|
2022-06-03 21:21:56 +00:00
|
|
|
const file = await utils.db.table('files')
|
2020-09-27 01:04:41 +00:00
|
|
|
.whereRaw('?? like ?', ['name', `${identifier}.%`])
|
2020-09-26 22:18:42 +00:00
|
|
|
.select('id')
|
|
|
|
.first()
|
|
|
|
if (file) {
|
|
|
|
self.onHold.delete(identifier)
|
|
|
|
logger.log(`Identifier ${identifier} is already in use (${i + 1}/${utils.idMaxTries}).`)
|
|
|
|
continue
|
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
} else {
|
|
|
|
try {
|
|
|
|
await paths.access(path.join(paths.uploads, name))
|
|
|
|
logger.log(`${name} is already in use (${i + 1}/${utils.idMaxTries}).`)
|
|
|
|
continue
|
|
|
|
} catch (error) {
|
2021-01-08 02:44:04 +00:00
|
|
|
// Re-throw non-ENOENT error
|
2020-10-30 18:12:09 +00:00
|
|
|
if (error & error.code !== 'ENOENT') throw error
|
2018-12-03 09:18:52 +00:00
|
|
|
}
|
2018-04-28 17:26:39 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
return name
|
|
|
|
}
|
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ServerError('Failed to allocate a unique name for the upload. Try again?')
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
|
|
|
|
2022-05-06 19:17:31 +00:00
|
|
|
self.assertRetentionPeriod = (user, age) => {
|
|
|
|
if (!utils.retentions.enabled) return null
|
|
|
|
|
|
|
|
const group = user ? perms.group(user) : '_'
|
|
|
|
if (!group || !utils.retentions.periods[group]) {
|
|
|
|
throw new ClientError('You are not eligible for any file retention periods.', { statusCode: 403 })
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
|
|
|
|
2022-05-08 05:00:27 +00:00
|
|
|
let parsed = parseFloat(age)
|
|
|
|
if (Number.isNaN(parsed) || age < 0) {
|
2022-05-06 19:17:31 +00:00
|
|
|
parsed = utils.retentions.default[group]
|
2022-05-08 05:00:27 +00:00
|
|
|
} else if (!utils.retentions.periods[group].includes(parsed)) {
|
|
|
|
throw new ClientError('You are not eligible for the specified file retention period.', { statusCode: 403 })
|
2022-05-06 19:17:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!parsed && !utils.retentions.periods[group].includes(0)) {
|
|
|
|
throw new ClientError('Permanent uploads are not permitted.', { statusCode: 403 })
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2022-05-06 19:17:31 +00:00
|
|
|
|
|
|
|
return parsed
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
|
|
|
|
2019-11-29 13:42:53 +00:00
|
|
|
self.parseStripTags = stripTags => {
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!config.uploads.stripTags) return false
|
2019-11-29 13:42:53 +00:00
|
|
|
|
2020-10-30 18:12:09 +00:00
|
|
|
if (config.uploads.stripTags.force || stripTags === undefined) {
|
2019-11-29 13:42:53 +00:00
|
|
|
return config.uploads.stripTags.default
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-11-29 13:42:53 +00:00
|
|
|
|
|
|
|
return Boolean(parseInt(stripTags))
|
|
|
|
}
|
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Uploads */
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
self.upload = async (req, res, next) => {
|
2021-01-08 02:44:04 +00:00
|
|
|
try {
|
|
|
|
let user
|
|
|
|
if (config.private === true) {
|
2021-01-08 03:50:25 +00:00
|
|
|
user = await utils.authorize(req)
|
2021-01-08 02:44:04 +00:00
|
|
|
} else if (req.headers.token) {
|
2021-01-08 03:50:25 +00:00
|
|
|
user = await utils.assertUser(req.headers.token)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2021-05-22 13:59:00 +00:00
|
|
|
if (config.privateUploadGroup) {
|
|
|
|
if (!user || !perms.is(user, config.privateUploadGroup)) {
|
2021-06-08 01:01:11 +00:00
|
|
|
throw new ClientError(config.privateUploadCustomResponse || 'Your usergroup is not permitted to upload new files.', { statusCode: 403 })
|
2021-05-22 13:59:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
let albumid = parseInt(req.headers.albumid || req.params.albumid)
|
|
|
|
if (isNaN(albumid)) albumid = null
|
2019-09-08 01:56:29 +00:00
|
|
|
|
2022-05-06 19:17:31 +00:00
|
|
|
const age = self.assertRetentionPeriod(user, req.headers.age)
|
2017-01-19 06:34:48 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const func = req.body.urls ? self.actuallyUploadUrls : self.actuallyUploadFiles
|
|
|
|
await func(req, res, user, albumid, age)
|
|
|
|
} catch (error) {
|
2021-01-08 02:44:04 +00:00
|
|
|
return apiErrorsHandler(error, req, res, next)
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
self.actuallyUploadFiles = async (req, res, user, albumid, age) => {
|
|
|
|
const error = await new Promise(resolve => {
|
2022-04-22 21:44:01 +00:00
|
|
|
req._user = user
|
2019-09-08 01:56:29 +00:00
|
|
|
return executeMulter(req, res, err => resolve(err))
|
2022-04-22 21:44:01 +00:00
|
|
|
}).finally(() => delete req._user)
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
if (error) {
|
|
|
|
const suppress = [
|
|
|
|
'LIMIT_FILE_SIZE',
|
|
|
|
'LIMIT_UNEXPECTED_FILE'
|
|
|
|
]
|
2020-10-30 18:12:09 +00:00
|
|
|
if (suppress.includes(error.code)) {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError(error.toString())
|
2020-10-30 18:12:09 +00:00
|
|
|
} else {
|
2019-09-08 01:56:29 +00:00
|
|
|
throw error
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!req.files || !req.files.length) {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError('No files.')
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
// If chunked uploads is enabled and the uploaded file is a chunk, then just say that it was a success
|
|
|
|
const uuid = req.body.uuid
|
|
|
|
if (chunkedUploads && chunksData[uuid] !== undefined) {
|
|
|
|
req.files.forEach(file => {
|
2020-06-15 16:14:33 +00:00
|
|
|
chunksData[uuid].chunks++
|
2018-03-28 11:36:28 +00:00
|
|
|
})
|
2019-09-08 01:56:29 +00:00
|
|
|
return res.json({ success: true })
|
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const infoMap = req.files.map(file => {
|
|
|
|
file.albumid = albumid
|
|
|
|
file.age = age
|
|
|
|
return {
|
|
|
|
path: path.join(paths.uploads, file.filename),
|
|
|
|
data: file
|
2018-09-01 20:37:26 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
})
|
2018-09-01 20:37:26 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
if (config.filterEmptyFile && infoMap.some(file => file.data.size === 0)) {
|
|
|
|
// Unlink all files when at least one file is an empty file
|
2019-09-23 08:09:15 +00:00
|
|
|
// Should continue even when encountering errors
|
|
|
|
await Promise.all(infoMap.map(info =>
|
|
|
|
utils.unlinkFile(info.data.filename).catch(logger.error)
|
|
|
|
))
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError('Empty files are not allowed.')
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2022-04-22 21:44:01 +00:00
|
|
|
if (utils.scan.instance) {
|
2022-04-15 09:41:05 +00:00
|
|
|
let scanResult
|
2022-04-22 21:44:01 +00:00
|
|
|
if (utils.scan.passthrough) {
|
2022-04-15 09:41:05 +00:00
|
|
|
scanResult = await self.assertPassthroughScans(req, user, infoMap)
|
|
|
|
} else {
|
|
|
|
scanResult = await self.scanFiles(req, user, infoMap)
|
|
|
|
}
|
|
|
|
if (scanResult) {
|
|
|
|
throw new ClientError(scanResult)
|
|
|
|
}
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
|
|
|
|
2019-11-29 13:42:53 +00:00
|
|
|
await self.stripTags(req, infoMap)
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const result = await self.storeFilesToDb(req, res, user, infoMap)
|
2021-01-08 02:44:04 +00:00
|
|
|
return self.sendUploadResponse(req, res, user, result)
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** URL uploads */
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
self.actuallyUploadUrls = async (req, res, user, albumid, age) => {
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!config.uploads.urlMaxSize) {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError('Upload by URLs is disabled at the moment.', { statusCode: 403 })
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2018-12-08 17:55:04 +00:00
|
|
|
const urls = req.body.urls
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!urls || !(urls instanceof Array)) {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError('Missing "urls" property (array).')
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2020-10-30 18:12:09 +00:00
|
|
|
if (urls.length > maxFilesPerUpload) {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError(`Maximum ${maxFilesPerUpload} URLs at a time.`)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-23 08:09:15 +00:00
|
|
|
|
2022-05-08 08:19:29 +00:00
|
|
|
const assertSize = (size, isContentLength = false) => {
|
|
|
|
if (config.filterEmptyFile && size === 0) {
|
|
|
|
throw new ClientError('Empty files are not allowed.')
|
|
|
|
} else if (size > urlMaxSizeBytes) {
|
|
|
|
if (isContentLength) {
|
|
|
|
throw new ClientError(`File too large. Content-Length header reports file is bigger than ${urlMaxSize} MB.`)
|
|
|
|
} else {
|
|
|
|
throw new ClientError(`File too large. File is bigger than ${urlMaxSize} MB.`)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const downloaded = []
|
2018-05-11 14:34:13 +00:00
|
|
|
const infoMap = []
|
2019-09-08 01:56:29 +00:00
|
|
|
try {
|
2019-09-23 08:09:15 +00:00
|
|
|
await Promise.all(urls.map(async url => {
|
2022-05-08 08:35:28 +00:00
|
|
|
let outStream
|
|
|
|
let hasher
|
|
|
|
try {
|
|
|
|
const original = path.basename(url).split(/[?#]/)[0]
|
|
|
|
const extname = utils.extname(original)
|
|
|
|
|
|
|
|
// Extensions filter
|
|
|
|
let filtered = false
|
|
|
|
if (urlExtensionsFilter && ['blacklist', 'whitelist'].includes(config.uploads.urlExtensionsFilterMode)) {
|
|
|
|
const match = config.uploads.urlExtensionsFilter.includes(extname.toLowerCase())
|
|
|
|
const whitelist = config.uploads.urlExtensionsFilterMode === 'whitelist'
|
|
|
|
filtered = ((!whitelist && match) || (whitelist && !match))
|
|
|
|
} else {
|
|
|
|
filtered = self.isExtensionFiltered(extname)
|
|
|
|
}
|
2018-12-20 11:53:37 +00:00
|
|
|
|
2022-05-08 08:35:28 +00:00
|
|
|
if (filtered) {
|
|
|
|
throw new ClientError(`${extname ? `${extname.substr(1).toUpperCase()} files` : 'Files with no extension'} are not permitted.`)
|
|
|
|
}
|
2018-12-20 11:53:37 +00:00
|
|
|
|
2022-05-08 08:35:28 +00:00
|
|
|
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
|
|
|
|
2022-05-08 08:35:28 +00:00
|
|
|
// Try to determine size early via Content-Length header,
|
|
|
|
// but continue anyway if it isn't a valid number
|
|
|
|
try {
|
|
|
|
const head = await fetch(url, { method: 'HEAD', size: urlMaxSizeBytes })
|
|
|
|
if (head.status === 200) {
|
|
|
|
const contentLength = parseInt(head.headers.get('content-length'))
|
|
|
|
if (!Number.isNaN(contentLength)) {
|
|
|
|
assertSize(contentLength, true)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch (ex) {
|
|
|
|
// Re-throw only if ClientError, otherwise ignore
|
|
|
|
if (ex instanceof ClientError) {
|
|
|
|
throw ex
|
|
|
|
}
|
|
|
|
}
|
2018-09-23 16:28:15 +00:00
|
|
|
|
2022-05-08 08:35:28 +00:00
|
|
|
const length = self.parseFileIdentifierLength(req.headers.filelength)
|
|
|
|
const name = await self.getUniqueRandomName(length, extname)
|
|
|
|
|
|
|
|
const destination = path.join(paths.uploads, name)
|
|
|
|
outStream = fs.createWriteStream(destination)
|
|
|
|
hasher = blake3.createHash()
|
|
|
|
|
|
|
|
// Push to array early, so regardless of its progress it will be deleted on errors
|
|
|
|
downloaded.push(destination)
|
|
|
|
|
|
|
|
// Limit max response body size with maximum allowed size
|
|
|
|
const fetchFile = await fetch(url, { method: 'GET', size: urlMaxSizeBytes })
|
|
|
|
.then(res => new Promise((resolve, reject) => {
|
|
|
|
if (res.status === 200) {
|
|
|
|
outStream.on('error', reject)
|
|
|
|
res.body.on('error', reject)
|
|
|
|
res.body.on('data', d => hasher.update(d))
|
|
|
|
|
|
|
|
res.body.pipe(outStream)
|
|
|
|
outStream.on('finish', () => resolve(res))
|
|
|
|
} else {
|
|
|
|
resolve(res)
|
|
|
|
}
|
|
|
|
}))
|
2020-06-01 05:23:15 +00:00
|
|
|
|
2022-05-08 08:35:28 +00:00
|
|
|
if (fetchFile.status !== 200) {
|
|
|
|
throw new ServerError(`${fetchFile.status} ${fetchFile.statusText}`)
|
|
|
|
}
|
2018-09-23 16:28:15 +00:00
|
|
|
|
2022-05-08 08:35:28 +00:00
|
|
|
const contentType = fetchFile.headers.get('content-type')
|
|
|
|
// Re-test size via actual bytes written to physical file
|
|
|
|
assertSize(outStream.bytesWritten)
|
|
|
|
|
|
|
|
infoMap.push({
|
|
|
|
path: destination,
|
|
|
|
data: {
|
|
|
|
filename: name,
|
|
|
|
originalname: original,
|
|
|
|
extname,
|
|
|
|
mimetype: contentType ? contentType.split(';')[0] : '',
|
|
|
|
size: outStream.bytesWritten,
|
|
|
|
hash: hasher.digest('hex'),
|
|
|
|
albumid,
|
|
|
|
age
|
2022-05-08 08:19:29 +00:00
|
|
|
}
|
2022-05-08 08:35:28 +00:00
|
|
|
})
|
|
|
|
} catch (err) {
|
|
|
|
// Dispose of unfinished write & hasher streams
|
|
|
|
if (outStream && !outStream.destroyed) {
|
|
|
|
outStream.destroy()
|
2022-05-08 08:19:29 +00:00
|
|
|
}
|
2022-05-08 08:35:28 +00:00
|
|
|
try {
|
|
|
|
if (hasher) {
|
|
|
|
hasher.dispose()
|
2020-06-01 05:23:15 +00:00
|
|
|
}
|
2022-05-08 08:35:28 +00:00
|
|
|
} catch (_) {}
|
2020-06-01 05:23:15 +00:00
|
|
|
|
2022-05-08 08:35:28 +00:00
|
|
|
// Re-throw errors
|
|
|
|
throw err
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-23 08:09:15 +00:00
|
|
|
}))
|
2018-09-01 20:37:26 +00:00
|
|
|
|
2019-09-23 08:09:15 +00:00
|
|
|
// If no errors encountered, clear cache of downloaded files
|
2019-09-08 01:56:29 +00:00
|
|
|
downloaded.length = 0
|
2018-09-23 16:28:15 +00:00
|
|
|
|
2022-04-22 21:44:01 +00:00
|
|
|
if (utils.scan.instance) {
|
2019-11-05 20:35:04 +00:00
|
|
|
const scanResult = await self.scanFiles(req, user, infoMap)
|
2021-01-08 02:44:04 +00:00
|
|
|
if (scanResult) throw new ClientError(scanResult)
|
2018-12-18 17:41:42 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
|
|
|
|
const result = await self.storeFilesToDb(req, res, user, infoMap)
|
2020-06-19 18:28:23 +00:00
|
|
|
await self.sendUploadResponse(req, res, user, result)
|
2019-09-08 01:56:29 +00:00
|
|
|
} catch (error) {
|
|
|
|
// Unlink all downloaded files when at least one file threw an error from the for-loop
|
2019-09-23 08:09:15 +00:00
|
|
|
// Should continue even when encountering errors
|
2020-10-30 18:12:09 +00:00
|
|
|
if (downloaded.length) {
|
2019-09-23 08:09:15 +00:00
|
|
|
await Promise.all(downloaded.map(file =>
|
|
|
|
utils.unlinkFile(file).catch(logger.error)
|
|
|
|
))
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
|
2019-11-29 10:42:29 +00:00
|
|
|
const errorString = error.toString()
|
|
|
|
const suppress = [
|
|
|
|
/ over limit:/
|
|
|
|
]
|
2021-01-08 02:44:04 +00:00
|
|
|
if (suppress.some(t => t.test(errorString))) {
|
|
|
|
throw new ClientError(errorString)
|
2020-10-30 18:12:09 +00:00
|
|
|
} else {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw error
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Chunk uploads */
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
self.finishChunks = async (req, res, next) => {
|
2021-01-08 02:44:04 +00:00
|
|
|
try {
|
|
|
|
if (!chunkedUploads) {
|
|
|
|
throw new ClientError('Chunked upload is disabled.', { statusCode: 403 })
|
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
let user
|
|
|
|
if (config.private === true) {
|
2021-01-08 03:50:25 +00:00
|
|
|
user = await utils.authorize(req)
|
2021-01-08 02:44:04 +00:00
|
|
|
if (!user) return
|
|
|
|
} else if (req.headers.token) {
|
2021-01-08 03:50:25 +00:00
|
|
|
user = await utils.assertUser(req.headers.token)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
await self.actuallyFinishChunks(req, res, user)
|
|
|
|
} catch (error) {
|
2021-01-08 02:44:04 +00:00
|
|
|
return apiErrorsHandler(error, req, res, next)
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
self.actuallyFinishChunks = async (req, res, user) => {
|
2018-03-28 11:36:28 +00:00
|
|
|
const files = req.body.files
|
2022-05-08 05:01:18 +00:00
|
|
|
if (!Array.isArray(files) || !files.length) {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError('Bad request.')
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
|
|
|
|
const infoMap = []
|
2019-09-08 01:56:29 +00:00
|
|
|
try {
|
2019-09-23 08:09:15 +00:00
|
|
|
await Promise.all(files.map(async file => {
|
2022-05-08 05:01:18 +00:00
|
|
|
if (!file.uuid || typeof chunksData[file.uuid] === 'undefined') {
|
|
|
|
throw new ClientError('Invalid file UUID, or chunks data had already timed out. Try again?')
|
|
|
|
}
|
|
|
|
|
|
|
|
// Suspend timeout
|
|
|
|
// If the chunk errors out there, it will be immediately cleaned up anyway
|
|
|
|
chunksData[file.uuid].clearTimeout()
|
|
|
|
|
|
|
|
// Conclude write and hasher streams
|
2020-06-15 16:14:33 +00:00
|
|
|
chunksData[file.uuid].stream.end()
|
2022-05-08 05:01:18 +00:00
|
|
|
const hash = chunksData[file.uuid].hasher.digest('hex')
|
2020-06-15 16:14:33 +00:00
|
|
|
|
2022-05-08 05:01:18 +00:00
|
|
|
if (chunksData[file.uuid].chunks < 2 || chunksData[file.uuid].chunks > maxChunksCount) {
|
|
|
|
throw new ClientError('Invalid chunks count.')
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
|
|
|
|
file.extname = typeof file.original === 'string' ? utils.extname(file.original) : ''
|
2020-10-30 18:12:09 +00:00
|
|
|
if (self.isExtensionFiltered(file.extname)) {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError(`${file.extname ? `${file.extname.substr(1).toUpperCase()} files` : 'Files with no extension'} are not permitted.`)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
|
2022-05-06 19:17:31 +00:00
|
|
|
file.age = self.assertRetentionPeriod(user, file.age)
|
2018-04-28 17:26:39 +00:00
|
|
|
|
2020-06-15 16:14:33 +00:00
|
|
|
file.size = chunksData[file.uuid].stream.bytesWritten
|
2020-10-30 18:12:09 +00:00
|
|
|
if (config.filterEmptyFile && file.size === 0) {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError('Empty files are not allowed.')
|
2020-10-30 18:12:09 +00:00
|
|
|
} else if (file.size > maxSizeBytes) {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError(`File too large. Chunks are bigger than ${maxSize} MB.`)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-04-28 17:26:39 +00:00
|
|
|
|
2020-06-15 16:14:33 +00:00
|
|
|
// Double-check file size
|
|
|
|
const tmpfile = path.join(chunksData[file.uuid].root, chunksData[file.uuid].filename)
|
|
|
|
const lstat = await paths.lstat(tmpfile)
|
2020-10-30 18:12:09 +00:00
|
|
|
if (lstat.size !== file.size) {
|
2021-01-08 02:44:04 +00:00
|
|
|
throw new ClientError(`File size mismatched (${lstat.size} vs. ${file.size}).`)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-06-15 16:14:33 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
// Generate name
|
|
|
|
const length = self.parseFileIdentifierLength(file.filelength)
|
|
|
|
const name = await self.getUniqueRandomName(length, file.extname)
|
2018-12-20 11:53:37 +00:00
|
|
|
|
2020-06-15 16:14:33 +00:00
|
|
|
// Move tmp file to final destination
|
2020-11-20 23:31:36 +00:00
|
|
|
// For fs.copyFile(), tmpfile will eventually be unlinked by self.cleanUpChunks()
|
2019-09-08 01:56:29 +00:00
|
|
|
const destination = path.join(paths.uploads, name)
|
2020-11-20 23:31:36 +00:00
|
|
|
if (chunksCopyFile) {
|
|
|
|
await paths.copyFile(tmpfile, destination)
|
|
|
|
} else {
|
|
|
|
await paths.rename(tmpfile, destination)
|
|
|
|
}
|
2018-12-20 11:53:37 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
// Continue even when encountering errors
|
|
|
|
await self.cleanUpChunks(file.uuid).catch(logger.error)
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
let albumid = parseInt(file.albumid)
|
2020-10-30 18:12:09 +00:00
|
|
|
if (isNaN(albumid)) albumid = null
|
2018-04-05 12:54:24 +00:00
|
|
|
|
2018-05-11 14:34:13 +00:00
|
|
|
const data = {
|
|
|
|
filename: name,
|
|
|
|
originalname: file.original || '',
|
2019-09-08 01:56:29 +00:00
|
|
|
extname: file.extname,
|
2018-05-11 14:34:13 +00:00
|
|
|
mimetype: file.type || '',
|
2019-09-08 01:56:29 +00:00
|
|
|
size: file.size,
|
2020-05-28 19:52:58 +00:00
|
|
|
hash,
|
2019-09-08 01:56:29 +00:00
|
|
|
albumid,
|
|
|
|
age: file.age
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
2018-04-05 12:54:24 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
infoMap.push({ path: destination, data })
|
2019-09-23 08:09:15 +00:00
|
|
|
}))
|
2018-09-01 20:37:26 +00:00
|
|
|
|
2022-04-22 21:44:01 +00:00
|
|
|
if (utils.scan.instance) {
|
2019-11-05 20:35:04 +00:00
|
|
|
const scanResult = await self.scanFiles(req, user, infoMap)
|
2021-01-08 02:44:04 +00:00
|
|
|
if (scanResult) throw new ClientError(scanResult)
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
2018-05-11 14:34:13 +00:00
|
|
|
|
2019-11-29 13:42:53 +00:00
|
|
|
await self.stripTags(req, infoMap)
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const result = await self.storeFilesToDb(req, res, user, infoMap)
|
2020-06-19 18:28:23 +00:00
|
|
|
await self.sendUploadResponse(req, res, user, result)
|
2019-09-08 01:56:29 +00:00
|
|
|
} catch (error) {
|
2019-09-23 08:09:15 +00:00
|
|
|
// Should continue even when encountering errors
|
2020-10-30 18:12:09 +00:00
|
|
|
files.forEach(file => {
|
2022-05-08 05:01:18 +00:00
|
|
|
if (file.uuid && chunksData[file.uuid]) {
|
|
|
|
self.cleanUpChunks(file.uuid).catch(logger.error)
|
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
})
|
2019-09-23 08:09:15 +00:00
|
|
|
|
2019-09-19 01:27:19 +00:00
|
|
|
// Re-throw error
|
2019-09-08 01:56:29 +00:00
|
|
|
throw error
|
2018-04-05 10:31:07 +00:00
|
|
|
}
|
2018-03-28 11:36:28 +00:00
|
|
|
}
|
|
|
|
|
2022-05-08 05:01:18 +00:00
|
|
|
self.cleanUpChunks = async uuid => {
|
2022-05-08 08:35:28 +00:00
|
|
|
// Dispose of unfinished write & hasher streams
|
2022-05-08 05:01:18 +00:00
|
|
|
if (chunksData[uuid].stream && !chunksData[uuid].stream.destroyed) {
|
|
|
|
chunksData[uuid].stream.destroy()
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
if (chunksData[uuid].hasher) {
|
|
|
|
chunksData[uuid].hasher.dispose()
|
|
|
|
}
|
|
|
|
} catch (_) {}
|
|
|
|
|
2020-06-15 16:14:33 +00:00
|
|
|
// Remove tmp file
|
|
|
|
await paths.unlink(path.join(chunksData[uuid].root, chunksData[uuid].filename))
|
|
|
|
.catch(error => {
|
2021-01-08 02:44:04 +00:00
|
|
|
// Re-throw non-ENOENT error
|
2020-10-30 18:12:09 +00:00
|
|
|
if (error.code !== 'ENOENT') logger.error(error)
|
2020-06-15 16:14:33 +00:00
|
|
|
})
|
2020-10-30 18:12:09 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
// Remove UUID dir
|
|
|
|
await paths.rmdir(chunksData[uuid].root)
|
2020-10-30 18:12:09 +00:00
|
|
|
|
2020-06-15 16:14:33 +00:00
|
|
|
// Delete cached chunks data
|
2019-09-08 01:56:29 +00:00
|
|
|
delete chunksData[uuid]
|
2018-05-11 14:34:13 +00:00
|
|
|
}
|
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Virus scanning (ClamAV) */
|
|
|
|
|
2022-04-22 21:44:01 +00:00
|
|
|
self.scanHelpers.assertUserBypass = (user, filenames) => {
|
|
|
|
if (!user || !utils.scan.groupBypass) return false
|
|
|
|
if (!Array.isArray(filenames)) filenames = [filenames]
|
|
|
|
logger.debug(`[ClamAV]: ${filenames.join(', ')}: Skipped, uploaded by ${user.username} (${utils.scan.groupBypass})`)
|
|
|
|
return perms.is(user, utils.scan.groupBypass)
|
|
|
|
}
|
|
|
|
|
|
|
|
self.scanHelpers.assertFileBypass = data => {
|
|
|
|
if (typeof data !== 'object' || !data.filename) return false
|
|
|
|
|
|
|
|
const extname = data.extname || utils.extname(data.filename)
|
|
|
|
if (utils.scan.whitelistExtensions && utils.scan.whitelistExtensions.includes(extname)) {
|
|
|
|
logger.debug(`[ClamAV]: ${data.filename}: Skipped, extension whitelisted`)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-04-22 21:48:59 +00:00
|
|
|
if (utils.scan.maxSize && Number.isFinite(data.size) && data.size > utils.scan.maxSize) {
|
2022-04-22 21:44:01 +00:00
|
|
|
logger.debug(`[ClamAV]: ${data.filename}: Skipped, size ${data.size} > ${utils.scan.maxSize}`)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-04-15 09:41:05 +00:00
|
|
|
self.assertPassthroughScans = async (req, user, infoMap) => {
|
|
|
|
const foundThreats = []
|
|
|
|
const unableToScan = []
|
|
|
|
|
|
|
|
for (const info of infoMap) {
|
2022-04-22 21:44:01 +00:00
|
|
|
if (info.data.scan) {
|
|
|
|
if (info.data.scan.isInfected) {
|
|
|
|
logger.log(`[ClamAV]: ${info.data.filename}: ${info.data.scan.viruses.join(', ')}`)
|
|
|
|
foundThreats.push(...info.data.scan.viruses)
|
|
|
|
} else if (info.data.scan.isInfected === null) {
|
2022-04-16 06:33:11 +00:00
|
|
|
logger.log(`[ClamAV]: ${info.data.filename}: Unable to scan`)
|
2022-04-15 09:41:05 +00:00
|
|
|
unableToScan.push(info.data.filename)
|
2022-04-22 22:01:56 +00:00
|
|
|
} else {
|
|
|
|
logger.debug(`[ClamAV]: ${info.data.filename}: File is clean`)
|
2022-04-15 09:41:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let result = ''
|
|
|
|
if (foundThreats.length) {
|
|
|
|
const more = foundThreats.length > 1
|
|
|
|
result = `Threat${more ? 's' : ''} detected: ${foundThreats[0]}${more ? ', and more' : ''}.`
|
|
|
|
} else if (unableToScan.length) {
|
|
|
|
const more = unableToScan.length > 1
|
|
|
|
result = `Unable to scan: ${unableToScan[0]}${more ? ', and more' : ''}.`
|
|
|
|
}
|
|
|
|
|
|
|
|
if (result) {
|
|
|
|
// Unlink all files when at least one threat is found
|
|
|
|
// Should continue even when encountering errors
|
|
|
|
await Promise.all(infoMap.map(info =>
|
|
|
|
utils.unlinkFile(info.data.filename).catch(logger.error)
|
|
|
|
))
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2019-11-05 20:35:04 +00:00
|
|
|
self.scanFiles = async (req, user, infoMap) => {
|
2022-04-22 21:44:01 +00:00
|
|
|
const filenames = infoMap.map(info => info.data.filename)
|
|
|
|
if (self.scanHelpers.assertUserBypass(user, filenames)) {
|
2019-11-05 20:35:04 +00:00
|
|
|
return false
|
2020-04-04 14:20:01 +00:00
|
|
|
}
|
2019-09-23 08:09:15 +00:00
|
|
|
|
2019-11-05 20:35:04 +00:00
|
|
|
const foundThreats = []
|
2022-04-15 08:36:50 +00:00
|
|
|
const unableToScan = []
|
2022-04-15 09:41:05 +00:00
|
|
|
const result = await Promise.all(infoMap.map(async info => {
|
2022-04-22 21:44:01 +00:00
|
|
|
if (self.scanHelpers.assertFileBypass({
|
|
|
|
filename: info.data.filename,
|
|
|
|
extname: info.data.extname,
|
|
|
|
size: info.data.size
|
|
|
|
})) return
|
2020-04-04 14:20:01 +00:00
|
|
|
|
2022-04-15 09:41:05 +00:00
|
|
|
logger.debug(`[ClamAV]: ${info.data.filename}: Scanning\u2026`)
|
2022-04-22 21:44:01 +00:00
|
|
|
const response = await utils.scan.instance.isInfected(info.path)
|
2022-04-15 08:36:50 +00:00
|
|
|
if (response.isInfected) {
|
2020-10-31 23:35:56 +00:00
|
|
|
logger.log(`[ClamAV]: ${info.data.filename}: ${response.viruses.join(', ')}`)
|
|
|
|
foundThreats.push(...response.viruses)
|
2022-04-15 08:36:50 +00:00
|
|
|
} else if (response.isInfected === null) {
|
|
|
|
logger.log(`[ClamAV]: ${info.data.filename}: Unable to scan`)
|
|
|
|
unableToScan.push(info.data.filename)
|
2022-04-22 22:01:56 +00:00
|
|
|
} else {
|
|
|
|
logger.debug(`[ClamAV]: ${info.data.filename}: File is clean`)
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
2019-11-05 20:35:04 +00:00
|
|
|
})).then(() => {
|
2020-10-30 18:12:09 +00:00
|
|
|
if (foundThreats.length) {
|
2020-10-31 23:35:56 +00:00
|
|
|
const more = foundThreats.length > 1
|
|
|
|
return `Threat${more ? 's' : ''} detected: ${foundThreats[0]}${more ? ', and more' : ''}.`
|
2022-04-15 08:36:50 +00:00
|
|
|
} else if (unableToScan.length) {
|
|
|
|
const more = unableToScan.length > 1
|
|
|
|
return `Unable to scan: ${unableToScan[0]}${more ? ', and more' : ''}.`
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-11-05 20:35:04 +00:00
|
|
|
}).catch(error => {
|
2022-04-22 21:44:01 +00:00
|
|
|
logger.error(`[ClamAV]: ${filenames.join(', ')}: ${error.toString()}`)
|
2019-11-05 20:35:04 +00:00
|
|
|
return 'An unexpected error occurred with ClamAV, please contact the site owner.'
|
|
|
|
})
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2022-04-15 09:41:05 +00:00
|
|
|
if (result) {
|
2019-11-05 20:35:04 +00:00
|
|
|
// Unlink all files when at least one threat is found OR any errors occurred
|
|
|
|
// Should continue even when encountering errors
|
|
|
|
await Promise.all(infoMap.map(info =>
|
|
|
|
utils.unlinkFile(info.data.filename).catch(logger.error)
|
|
|
|
))
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2022-04-15 09:41:05 +00:00
|
|
|
return result
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Strip tags (EXIF, etc.) */
|
|
|
|
|
2019-11-29 13:42:53 +00:00
|
|
|
self.stripTags = async (req, infoMap) => {
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!self.parseStripTags(req.headers.striptags)) return
|
2019-11-29 13:42:53 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
await Promise.all(infoMap.map(info =>
|
|
|
|
utils.stripTags(info.data.filename, info.data.extname)
|
|
|
|
))
|
|
|
|
} catch (error) {
|
|
|
|
// Unlink all files when at least one threat is found OR any errors occurred
|
|
|
|
// Should continue even when encountering errors
|
|
|
|
await Promise.all(infoMap.map(info =>
|
|
|
|
utils.unlinkFile(info.data.filename).catch(logger.error)
|
|
|
|
))
|
|
|
|
|
|
|
|
// Re-throw error
|
|
|
|
throw error
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Database functions */
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
self.storeFilesToDb = async (req, res, user, infoMap) => {
|
|
|
|
const files = []
|
|
|
|
const exists = []
|
|
|
|
const albumids = []
|
2019-11-29 13:42:53 +00:00
|
|
|
|
2019-09-23 08:09:15 +00:00
|
|
|
await Promise.all(infoMap.map(async info => {
|
2019-09-08 01:56:29 +00:00
|
|
|
// Check if the file exists by checking its hash and size
|
2022-06-03 21:21:56 +00:00
|
|
|
const dbFile = await utils.db.table('files')
|
2019-09-08 01:56:29 +00:00
|
|
|
.where(function () {
|
2020-10-30 18:12:09 +00:00
|
|
|
if (user === undefined) {
|
2019-09-08 01:56:29 +00:00
|
|
|
this.whereNull('userid')
|
2020-10-30 18:12:09 +00:00
|
|
|
} else {
|
2019-09-08 01:56:29 +00:00
|
|
|
this.where('userid', user.id)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
})
|
|
|
|
.where({
|
2020-05-28 19:52:58 +00:00
|
|
|
hash: info.data.hash,
|
2022-06-29 07:35:00 +00:00
|
|
|
size: String(info.data.size)
|
2018-01-23 20:06:30 +00:00
|
|
|
})
|
2019-09-08 01:56:29 +00:00
|
|
|
// Select expirydate to display expiration date of existing files as well
|
|
|
|
.select('name', 'expirydate')
|
|
|
|
.first()
|
|
|
|
|
|
|
|
if (dbFile) {
|
|
|
|
// Continue even when encountering errors
|
|
|
|
await utils.unlinkFile(info.data.filename).catch(logger.error)
|
2022-04-15 08:30:32 +00:00
|
|
|
logger.debug(`Unlinked ${info.data.filename} since a duplicate named ${dbFile.name} exists`)
|
Updates (very important to read)
Client-side CSS & JS files will now be processed with Gulp.
Gulp tasks are configured in gulpfile.js file.
CSS files will be optimized with postcss-preset-env, which will
auto-add vendor prefixes and convert any parts necessary for browsers
compatibility.
Afterwards they will be minified with cssnano.
JS files will be optimized with bublé,
likewise for browsers compatibility.
Afterwards they will be minified with terser.
Unprocessed CSS & JS files will now be located at src directory, while
the processed results will be located at dist directory.
Due to bublé, the JS files should now be compatible up to IE 11
at the minimum.
Previously the safe would not work in IE 11 due to extensive usage of
template literals.
Due to that as well, JS files in src directory will now extensively use
arrow functions for my personal comfort (as they will be converted too).
The server will use the processed files at dist directory by default.
If you want to rebuild the files by your own, you can run "yarn build".
Gulp is a development dependency, so make sure you have installed all
development dependencies (e.i. NOT using "yarn install --production").
---
yarn lint -> gulp lint
yarn build -> gulp default
yarn watch -> gulp watch
yarn develop -> env NODE_ENV=development yarn watch
---
Fixed not being able to demote staff into normal users.
/api/token/verify will no longer respond with 401 HTTP error code,
unless an error occurred (which will be 500 HTTP error code).
Fixed /nojs route not displaying file's original name when a duplicate
is found on the server.
Removed is-breeze CSS class name, in favor of Bulma's is-info.
Removed custom styling from auth page, in favor of global styling.
Removed all usage of style HTML attribute in favor of CSS classes.
Renamed js/s/ to js/misc/.
Use loading spinners on dashboard's sidebar menus.
Disable all other sidebar menus when something is loading.
Changed title HTML attribute of disabled control buttons in
uploads & users list.
Hid checkboxes and WIP controls from users list.
Better error messages handling.
Especially homepage will now support CF's HTTP error codes.
Updated various icons.
Also, added fontello config file at public/libs/fontello/config.json.
This should let you edit them more easily with fontello.
Use Gatsby icon for my blog's link in homepage's footer.
A bunch of other improvements here & there.
2019-09-15 06:20:11 +00:00
|
|
|
|
|
|
|
// If on /nojs route, append original file name reported by client
|
2020-10-30 18:12:09 +00:00
|
|
|
if (req.path === '/nojs') {
|
Updates (very important to read)
Client-side CSS & JS files will now be processed with Gulp.
Gulp tasks are configured in gulpfile.js file.
CSS files will be optimized with postcss-preset-env, which will
auto-add vendor prefixes and convert any parts necessary for browsers
compatibility.
Afterwards they will be minified with cssnano.
JS files will be optimized with bublé,
likewise for browsers compatibility.
Afterwards they will be minified with terser.
Unprocessed CSS & JS files will now be located at src directory, while
the processed results will be located at dist directory.
Due to bublé, the JS files should now be compatible up to IE 11
at the minimum.
Previously the safe would not work in IE 11 due to extensive usage of
template literals.
Due to that as well, JS files in src directory will now extensively use
arrow functions for my personal comfort (as they will be converted too).
The server will use the processed files at dist directory by default.
If you want to rebuild the files by your own, you can run "yarn build".
Gulp is a development dependency, so make sure you have installed all
development dependencies (e.i. NOT using "yarn install --production").
---
yarn lint -> gulp lint
yarn build -> gulp default
yarn watch -> gulp watch
yarn develop -> env NODE_ENV=development yarn watch
---
Fixed not being able to demote staff into normal users.
/api/token/verify will no longer respond with 401 HTTP error code,
unless an error occurred (which will be 500 HTTP error code).
Fixed /nojs route not displaying file's original name when a duplicate
is found on the server.
Removed is-breeze CSS class name, in favor of Bulma's is-info.
Removed custom styling from auth page, in favor of global styling.
Removed all usage of style HTML attribute in favor of CSS classes.
Renamed js/s/ to js/misc/.
Use loading spinners on dashboard's sidebar menus.
Disable all other sidebar menus when something is loading.
Changed title HTML attribute of disabled control buttons in
uploads & users list.
Hid checkboxes and WIP controls from users list.
Better error messages handling.
Especially homepage will now support CF's HTTP error codes.
Updated various icons.
Also, added fontello config file at public/libs/fontello/config.json.
This should let you edit them more easily with fontello.
Use Gatsby icon for my blog's link in homepage's footer.
A bunch of other improvements here & there.
2019-09-15 06:20:11 +00:00
|
|
|
dbFile.original = info.data.originalname
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
Updates (very important to read)
Client-side CSS & JS files will now be processed with Gulp.
Gulp tasks are configured in gulpfile.js file.
CSS files will be optimized with postcss-preset-env, which will
auto-add vendor prefixes and convert any parts necessary for browsers
compatibility.
Afterwards they will be minified with cssnano.
JS files will be optimized with bublé,
likewise for browsers compatibility.
Afterwards they will be minified with terser.
Unprocessed CSS & JS files will now be located at src directory, while
the processed results will be located at dist directory.
Due to bublé, the JS files should now be compatible up to IE 11
at the minimum.
Previously the safe would not work in IE 11 due to extensive usage of
template literals.
Due to that as well, JS files in src directory will now extensively use
arrow functions for my personal comfort (as they will be converted too).
The server will use the processed files at dist directory by default.
If you want to rebuild the files by your own, you can run "yarn build".
Gulp is a development dependency, so make sure you have installed all
development dependencies (e.i. NOT using "yarn install --production").
---
yarn lint -> gulp lint
yarn build -> gulp default
yarn watch -> gulp watch
yarn develop -> env NODE_ENV=development yarn watch
---
Fixed not being able to demote staff into normal users.
/api/token/verify will no longer respond with 401 HTTP error code,
unless an error occurred (which will be 500 HTTP error code).
Fixed /nojs route not displaying file's original name when a duplicate
is found on the server.
Removed is-breeze CSS class name, in favor of Bulma's is-info.
Removed custom styling from auth page, in favor of global styling.
Removed all usage of style HTML attribute in favor of CSS classes.
Renamed js/s/ to js/misc/.
Use loading spinners on dashboard's sidebar menus.
Disable all other sidebar menus when something is loading.
Changed title HTML attribute of disabled control buttons in
uploads & users list.
Hid checkboxes and WIP controls from users list.
Better error messages handling.
Especially homepage will now support CF's HTTP error codes.
Updated various icons.
Also, added fontello config file at public/libs/fontello/config.json.
This should let you edit them more easily with fontello.
Use Gatsby icon for my blog's link in homepage's footer.
A bunch of other improvements here & there.
2019-09-15 06:20:11 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
exists.push(dbFile)
|
2019-09-23 08:09:15 +00:00
|
|
|
return
|
2018-04-05 10:31:07 +00:00
|
|
|
}
|
2017-10-04 00:13:38 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const timestamp = Math.floor(Date.now() / 1000)
|
|
|
|
const data = {
|
|
|
|
name: info.data.filename,
|
|
|
|
original: info.data.originalname,
|
|
|
|
type: info.data.mimetype,
|
2022-06-29 07:35:00 +00:00
|
|
|
size: String(info.data.size),
|
2020-05-28 19:52:58 +00:00
|
|
|
hash: info.data.hash,
|
2019-09-08 01:56:29 +00:00
|
|
|
// Only disable if explicitly set to false in config
|
|
|
|
ip: config.uploads.storeIP !== false ? req.ip : null,
|
|
|
|
timestamp
|
|
|
|
}
|
|
|
|
|
|
|
|
if (user) {
|
|
|
|
data.userid = user.id
|
|
|
|
data.albumid = info.data.albumid
|
2020-10-30 18:12:09 +00:00
|
|
|
if (data.albumid !== null && !albumids.includes(data.albumid)) {
|
2019-09-08 01:56:29 +00:00
|
|
|
albumids.push(data.albumid)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
|
|
|
|
2020-10-30 18:12:09 +00:00
|
|
|
if (info.data.age) {
|
2019-09-08 01:56:29 +00:00
|
|
|
data.expirydate = data.timestamp + (info.data.age * 3600) // Hours to seconds
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-09-01 20:37:26 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
files.push(data)
|
|
|
|
|
|
|
|
// Generate thumbs, but do not wait
|
2020-10-30 18:12:09 +00:00
|
|
|
if (utils.mayGenerateThumb(info.data.extname)) {
|
2020-06-15 14:10:40 +00:00
|
|
|
utils.generateThumbs(info.data.filename, info.data.extname, true).catch(logger.error)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2019-09-23 08:09:15 +00:00
|
|
|
}))
|
2018-03-28 11:36:28 +00:00
|
|
|
|
2018-04-12 14:37:42 +00:00
|
|
|
if (files.length) {
|
2019-09-08 01:56:29 +00:00
|
|
|
let authorizedIds = []
|
|
|
|
if (albumids.length) {
|
2022-06-03 21:21:56 +00:00
|
|
|
authorizedIds = await utils.db.table('albums')
|
2019-09-08 01:56:29 +00:00
|
|
|
.where({ userid: user.id })
|
|
|
|
.whereIn('id', albumids)
|
|
|
|
.select('id')
|
|
|
|
.then(rows => rows.map(row => row.id))
|
|
|
|
|
|
|
|
// Remove albumid if user do not own the album
|
2020-10-30 18:12:09 +00:00
|
|
|
for (const file of files) {
|
|
|
|
if (file.albumid !== null && !authorizedIds.includes(file.albumid)) {
|
2019-09-08 01:56:29 +00:00
|
|
|
file.albumid = null
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
|
|
|
}
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
|
|
|
|
2018-04-12 14:37:42 +00:00
|
|
|
// Insert new files to DB
|
2022-06-03 21:21:56 +00:00
|
|
|
await utils.db.table('files').insert(files)
|
2019-09-08 01:56:29 +00:00
|
|
|
utils.invalidateStatsCache('uploads')
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2020-10-30 18:12:09 +00:00
|
|
|
if (config.uploads.queryDbForFileCollisions) {
|
2020-09-26 22:18:42 +00:00
|
|
|
for (const file of files) {
|
|
|
|
const extname = utils.extname(file.name)
|
|
|
|
const identifier = file.name.slice(0, -(extname.length))
|
|
|
|
self.onHold.delete(identifier)
|
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-09-26 22:18:42 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
// Update albums' timestamp
|
2019-09-17 04:13:41 +00:00
|
|
|
if (authorizedIds.length) {
|
2022-06-03 21:21:56 +00:00
|
|
|
await utils.db.table('albums')
|
2019-09-08 01:56:29 +00:00
|
|
|
.whereIn('id', authorizedIds)
|
|
|
|
.update('editedAt', Math.floor(Date.now() / 1000))
|
2019-09-17 04:13:41 +00:00
|
|
|
utils.invalidateAlbumsCache(authorizedIds)
|
|
|
|
}
|
2018-05-12 14:01:14 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2020-10-11 10:32:22 +00:00
|
|
|
return [...files, ...exists]
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
2018-04-04 17:38:15 +00:00
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Final response */
|
|
|
|
|
2020-06-19 18:28:23 +00:00
|
|
|
self.sendUploadResponse = async (req, res, user, result) => {
|
2019-09-08 01:56:29 +00:00
|
|
|
// Send response
|
2021-01-08 02:44:04 +00:00
|
|
|
return res.json({
|
2018-05-12 14:01:14 +00:00
|
|
|
success: true,
|
2019-09-08 01:56:29 +00:00
|
|
|
files: result.map(file => {
|
|
|
|
const map = {
|
2018-04-12 14:37:42 +00:00
|
|
|
name: file.name,
|
2022-06-22 06:27:38 +00:00
|
|
|
url: `${utils.conf.domain ? `${utils.conf.domain}/` : ''}${file.name}`
|
2018-04-04 17:38:15 +00:00
|
|
|
}
|
2018-05-12 14:01:14 +00:00
|
|
|
|
Updates (very important to read)
Client-side CSS & JS files will now be processed with Gulp.
Gulp tasks are configured in gulpfile.js file.
CSS files will be optimized with postcss-preset-env, which will
auto-add vendor prefixes and convert any parts necessary for browsers
compatibility.
Afterwards they will be minified with cssnano.
JS files will be optimized with bublé,
likewise for browsers compatibility.
Afterwards they will be minified with terser.
Unprocessed CSS & JS files will now be located at src directory, while
the processed results will be located at dist directory.
Due to bublé, the JS files should now be compatible up to IE 11
at the minimum.
Previously the safe would not work in IE 11 due to extensive usage of
template literals.
Due to that as well, JS files in src directory will now extensively use
arrow functions for my personal comfort (as they will be converted too).
The server will use the processed files at dist directory by default.
If you want to rebuild the files by your own, you can run "yarn build".
Gulp is a development dependency, so make sure you have installed all
development dependencies (e.i. NOT using "yarn install --production").
---
yarn lint -> gulp lint
yarn build -> gulp default
yarn watch -> gulp watch
yarn develop -> env NODE_ENV=development yarn watch
---
Fixed not being able to demote staff into normal users.
/api/token/verify will no longer respond with 401 HTTP error code,
unless an error occurred (which will be 500 HTTP error code).
Fixed /nojs route not displaying file's original name when a duplicate
is found on the server.
Removed is-breeze CSS class name, in favor of Bulma's is-info.
Removed custom styling from auth page, in favor of global styling.
Removed all usage of style HTML attribute in favor of CSS classes.
Renamed js/s/ to js/misc/.
Use loading spinners on dashboard's sidebar menus.
Disable all other sidebar menus when something is loading.
Changed title HTML attribute of disabled control buttons in
uploads & users list.
Hid checkboxes and WIP controls from users list.
Better error messages handling.
Especially homepage will now support CF's HTTP error codes.
Updated various icons.
Also, added fontello config file at public/libs/fontello/config.json.
This should let you edit them more easily with fontello.
Use Gatsby icon for my blog's link in homepage's footer.
A bunch of other improvements here & there.
2019-09-15 06:20:11 +00:00
|
|
|
// If a temporary upload, add expiry date
|
2020-10-30 18:12:09 +00:00
|
|
|
if (file.expirydate) {
|
2019-09-08 01:56:29 +00:00
|
|
|
map.expirydate = file.expirydate
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-12-18 17:01:28 +00:00
|
|
|
|
Updates (very important to read)
Client-side CSS & JS files will now be processed with Gulp.
Gulp tasks are configured in gulpfile.js file.
CSS files will be optimized with postcss-preset-env, which will
auto-add vendor prefixes and convert any parts necessary for browsers
compatibility.
Afterwards they will be minified with cssnano.
JS files will be optimized with bublé,
likewise for browsers compatibility.
Afterwards they will be minified with terser.
Unprocessed CSS & JS files will now be located at src directory, while
the processed results will be located at dist directory.
Due to bublé, the JS files should now be compatible up to IE 11
at the minimum.
Previously the safe would not work in IE 11 due to extensive usage of
template literals.
Due to that as well, JS files in src directory will now extensively use
arrow functions for my personal comfort (as they will be converted too).
The server will use the processed files at dist directory by default.
If you want to rebuild the files by your own, you can run "yarn build".
Gulp is a development dependency, so make sure you have installed all
development dependencies (e.i. NOT using "yarn install --production").
---
yarn lint -> gulp lint
yarn build -> gulp default
yarn watch -> gulp watch
yarn develop -> env NODE_ENV=development yarn watch
---
Fixed not being able to demote staff into normal users.
/api/token/verify will no longer respond with 401 HTTP error code,
unless an error occurred (which will be 500 HTTP error code).
Fixed /nojs route not displaying file's original name when a duplicate
is found on the server.
Removed is-breeze CSS class name, in favor of Bulma's is-info.
Removed custom styling from auth page, in favor of global styling.
Removed all usage of style HTML attribute in favor of CSS classes.
Renamed js/s/ to js/misc/.
Use loading spinners on dashboard's sidebar menus.
Disable all other sidebar menus when something is loading.
Changed title HTML attribute of disabled control buttons in
uploads & users list.
Hid checkboxes and WIP controls from users list.
Better error messages handling.
Especially homepage will now support CF's HTTP error codes.
Updated various icons.
Also, added fontello config file at public/libs/fontello/config.json.
This should let you edit them more easily with fontello.
Use Gatsby icon for my blog's link in homepage's footer.
A bunch of other improvements here & there.
2019-09-15 06:20:11 +00:00
|
|
|
// If on /nojs route, add original name
|
2020-10-30 18:12:09 +00:00
|
|
|
if (req.path === '/nojs') {
|
2019-09-08 01:56:29 +00:00
|
|
|
map.original = file.original
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-04-12 14:37:42 +00:00
|
|
|
|
2020-06-19 18:28:23 +00:00
|
|
|
// If uploaded by user, add delete URL (intended for ShareX and its derivatives)
|
|
|
|
// Homepage uploader will not use this (use dashboard instead)
|
2022-06-28 05:03:49 +00:00
|
|
|
if (user) {
|
2022-06-29 06:58:09 +00:00
|
|
|
map.deleteUrl = `${utils.conf.homeDomain}/file/${file.name}?delete`
|
2022-06-28 05:03:49 +00:00
|
|
|
}
|
2020-06-19 18:28:23 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
return map
|
|
|
|
})
|
|
|
|
})
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
2017-03-17 00:53:29 +00:00
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** Delete uploads */
|
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
self.delete = async (req, res, next) => {
|
2020-06-19 18:28:23 +00:00
|
|
|
// Map /api/delete requests to /api/bulkdelete
|
|
|
|
let body
|
|
|
|
if (req.method === 'POST') {
|
|
|
|
// Original lolisafe API (this fork uses /api/bulkdelete immediately)
|
|
|
|
const id = parseInt(req.body.id)
|
|
|
|
body = {
|
|
|
|
field: 'id',
|
|
|
|
values: isNaN(id) ? undefined : [id]
|
|
|
|
}
|
2022-06-28 05:03:49 +00:00
|
|
|
}
|
2020-06-19 18:28:23 +00:00
|
|
|
|
2019-01-01 19:39:08 +00:00
|
|
|
req.body = body
|
2021-01-08 02:44:04 +00:00
|
|
|
return self.bulkDelete(req, res, next)
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
self.bulkDelete = async (req, res, next) => {
|
|
|
|
try {
|
2021-01-08 03:50:25 +00:00
|
|
|
const user = await utils.authorize(req)
|
2018-05-05 19:44:58 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
const field = req.body.field || 'id'
|
|
|
|
const values = req.body.values
|
2018-09-04 15:49:37 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
if (!Array.isArray(values) || !values.length) {
|
|
|
|
throw new ClientError('No array of files specified.')
|
|
|
|
}
|
2018-03-29 23:22:08 +00:00
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
const failed = await utils.bulkDeleteFromDb(field, values, user)
|
2021-01-08 02:44:04 +00:00
|
|
|
await res.json({ success: true, failed })
|
2019-09-08 01:56:29 +00:00
|
|
|
} catch (error) {
|
2021-01-08 02:44:04 +00:00
|
|
|
return apiErrorsHandler(error, req, res, next)
|
2019-09-08 01:56:29 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
2017-10-04 00:13:38 +00:00
|
|
|
|
2022-04-16 13:44:11 +00:00
|
|
|
/** List uploads */
|
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
self.list = async (req, res, next) => {
|
|
|
|
try {
|
2021-01-08 03:50:25 +00:00
|
|
|
const user = await utils.authorize(req)
|
2019-06-17 19:34:15 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
const all = req.headers.all === '1'
|
|
|
|
const filters = req.headers.filters
|
|
|
|
const minoffset = Number(req.headers.minoffset) || 0
|
|
|
|
const ismoderator = perms.is(user, 'moderator')
|
|
|
|
if (all && !ismoderator) return res.status(403).end()
|
|
|
|
|
2022-06-22 06:27:38 +00:00
|
|
|
const basedomain = utils.conf.domain
|
2021-01-08 02:44:04 +00:00
|
|
|
|
|
|
|
// Thresholds for regular users
|
|
|
|
const MAX_WILDCARDS_IN_KEY = 2
|
|
|
|
const MAX_TEXT_QUERIES = 3 // non-keyed keywords
|
|
|
|
const MAX_SORT_KEYS = 1
|
|
|
|
const MAX_IS_KEYS = 1
|
|
|
|
|
|
|
|
const filterObj = {
|
|
|
|
uploaders: [],
|
|
|
|
excludeUploaders: [],
|
|
|
|
queries: {
|
|
|
|
exclude: {}
|
|
|
|
},
|
|
|
|
typeIs: [
|
|
|
|
'image',
|
|
|
|
'video',
|
|
|
|
'audio'
|
|
|
|
],
|
|
|
|
flags: {}
|
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
const sortObj = {
|
|
|
|
// Cast columns to specific type if they are stored differently
|
|
|
|
casts: {
|
|
|
|
size: 'integer'
|
|
|
|
},
|
|
|
|
// Columns mapping
|
|
|
|
maps: {
|
|
|
|
date: 'timestamp',
|
|
|
|
expiry: 'expirydate',
|
|
|
|
originalname: 'original'
|
|
|
|
},
|
|
|
|
// Columns with which to use SQLite's NULLS LAST option
|
|
|
|
nullsLast: [
|
|
|
|
'userid',
|
|
|
|
'expirydate',
|
|
|
|
'ip'
|
|
|
|
],
|
|
|
|
parsed: []
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse glob wildcards into SQL wildcards
|
|
|
|
function sqlLikeParser (pattern) {
|
|
|
|
// Escape SQL operators
|
|
|
|
const escaped = pattern
|
|
|
|
.replace(/(?<!\\)%/g, '\\%')
|
|
|
|
.replace(/(?<!\\)_/g, '\\_')
|
|
|
|
|
|
|
|
// Look for any glob operators
|
|
|
|
const match = pattern.match(/(?<!\\)(\*|\?)/g)
|
|
|
|
if (match && match.length) {
|
|
|
|
return {
|
|
|
|
count: match.length,
|
|
|
|
// Replace glob operators with their SQL equivalents
|
|
|
|
escaped: escaped
|
|
|
|
.replace(/(?<!\\)\*/g, '%')
|
|
|
|
.replace(/(?<!\\)\?/g, '_')
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return {
|
|
|
|
count: 0,
|
|
|
|
// Assume partial match
|
|
|
|
escaped: `%${escaped}%`
|
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
if (filters) {
|
|
|
|
const keywords = []
|
2020-05-16 15:42:08 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
if (req.params.id === undefined) keywords.push('albumid')
|
2020-05-02 20:30:50 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Only allow filtering by 'ip' and 'user' keys when listing all uploads
|
|
|
|
if (all) keywords.push('ip', 'user')
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
const ranges = [
|
|
|
|
'date',
|
|
|
|
'expiry'
|
|
|
|
]
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
keywords.push('is', 'sort', 'orderby')
|
|
|
|
filterObj.queries = searchQuery.parse(filters, {
|
|
|
|
keywords,
|
|
|
|
ranges,
|
|
|
|
tokenize: true,
|
|
|
|
alwaysArray: true,
|
|
|
|
offsets: false
|
|
|
|
})
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Accept orderby as alternative for sort
|
|
|
|
if (filterObj.queries.orderby) {
|
|
|
|
if (!filterObj.queries.sort) filterObj.queries.sort = []
|
|
|
|
filterObj.queries.sort.push(...filterObj.queries.orderby)
|
|
|
|
delete filterObj.queries.orderby
|
|
|
|
}
|
2020-05-16 15:07:15 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// For some reason, single value won't be in Array even with 'alwaysArray' option
|
|
|
|
if (typeof filterObj.queries.exclude.text === 'string') {
|
|
|
|
filterObj.queries.exclude.text = [filterObj.queries.exclude.text]
|
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Text (non-keyed keywords) queries
|
|
|
|
let textQueries = 0
|
|
|
|
if (filterObj.queries.text) textQueries += filterObj.queries.text.length
|
|
|
|
if (filterObj.queries.exclude.text) textQueries += filterObj.queries.exclude.text.length
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Regular user threshold check
|
|
|
|
if (!ismoderator && textQueries > MAX_TEXT_QUERIES) {
|
|
|
|
throw new ClientError(`Users are only allowed to use ${MAX_TEXT_QUERIES} non-keyed keyword${MAX_TEXT_QUERIES === 1 ? '' : 's'} at a time.`)
|
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
if (filterObj.queries.text) {
|
|
|
|
for (let i = 0; i < filterObj.queries.text.length; i++) {
|
|
|
|
const result = sqlLikeParser(filterObj.queries.text[i])
|
|
|
|
if (!ismoderator && result.count > MAX_WILDCARDS_IN_KEY) {
|
|
|
|
throw new ClientError(`Users are only allowed to use ${MAX_WILDCARDS_IN_KEY} wildcard${MAX_WILDCARDS_IN_KEY === 1 ? '' : 's'} per key.`)
|
|
|
|
}
|
|
|
|
filterObj.queries.text[i] = result.escaped
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
}
|
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
if (filterObj.queries.exclude.text) {
|
|
|
|
for (let i = 0; i < filterObj.queries.exclude.text.length; i++) {
|
|
|
|
const result = sqlLikeParser(filterObj.queries.exclude.text[i])
|
|
|
|
if (!ismoderator && result.count > MAX_WILDCARDS_IN_KEY) {
|
|
|
|
throw new ClientError(`Users are only allowed to use ${MAX_WILDCARDS_IN_KEY} wildcard${MAX_WILDCARDS_IN_KEY === 1 ? '' : 's'} per key.`)
|
|
|
|
}
|
|
|
|
filterObj.queries.exclude.text[i] = result.escaped
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
}
|
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
for (const key of keywords) {
|
|
|
|
let queryIndex = -1
|
|
|
|
let excludeIndex = -1
|
2020-04-19 18:19:20 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Make sure keyword arrays only contain unique values
|
|
|
|
if (filterObj.queries[key]) {
|
|
|
|
filterObj.queries[key] = filterObj.queries[key].filter((v, i, a) => a.indexOf(v) === i)
|
|
|
|
queryIndex = filterObj.queries[key].indexOf('-')
|
|
|
|
}
|
|
|
|
if (filterObj.queries.exclude[key]) {
|
|
|
|
filterObj.queries.exclude[key] = filterObj.queries.exclude[key].filter((v, i, a) => a.indexOf(v) === i)
|
|
|
|
excludeIndex = filterObj.queries.exclude[key].indexOf('-')
|
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Flag to match NULL values
|
|
|
|
const inQuery = queryIndex !== -1
|
|
|
|
const inExclude = excludeIndex !== -1
|
|
|
|
if (inQuery || inExclude) {
|
|
|
|
// Prioritize exclude keys when both types found
|
|
|
|
filterObj.flags[`${key}Null`] = inExclude ? false : inQuery
|
|
|
|
if (inQuery) {
|
|
|
|
if (filterObj.queries[key].length === 1) {
|
|
|
|
// Delete key to avoid unexpected behavior
|
|
|
|
delete filterObj.queries[key]
|
|
|
|
} else {
|
|
|
|
filterObj.queries[key].splice(queryIndex, 1)
|
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2021-01-08 02:44:04 +00:00
|
|
|
if (inExclude) {
|
|
|
|
if (filterObj.queries.exclude[key].length === 1) {
|
|
|
|
// Delete key to avoid unexpected behavior
|
|
|
|
delete filterObj.queries.exclude[key]
|
|
|
|
} else {
|
|
|
|
filterObj.queries.exclude[key].splice(excludeIndex, 1)
|
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
}
|
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
const parseDate = (date, minoffset, resetMs) => {
|
|
|
|
// [YYYY][/MM][/DD] [HH][:MM][:SS]
|
|
|
|
// e.g. 2020/01/01 00:00:00, 2018/01/01 06, 2019/11, 12:34:00
|
|
|
|
const match = date.match(/^(\d{4})?(\/\d{2})?(\/\d{2})?\s?(\d{2})?(:\d{2})?(:\d{2})?$/)
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
if (match) {
|
|
|
|
let offset = 0
|
|
|
|
if (minoffset !== undefined) {
|
|
|
|
offset = 60000 * (utils.timezoneOffset - minoffset)
|
|
|
|
}
|
2020-05-24 01:28:54 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
const dateObj = new Date(Date.now() + offset)
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
if (match[1] !== undefined) {
|
|
|
|
dateObj.setFullYear(Number(match[1]), // full year
|
|
|
|
match[2] !== undefined ? (Number(match[2].slice(1)) - 1) : 0, // month, zero-based
|
|
|
|
match[3] !== undefined ? Number(match[3].slice(1)) : 1) // date
|
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
if (match[4] !== undefined) {
|
|
|
|
dateObj.setHours(Number(match[4]), // hours
|
|
|
|
match[5] !== undefined ? Number(match[5].slice(1)) : 0, // minutes
|
|
|
|
match[6] !== undefined ? Number(match[6].slice(1)) : 0) // seconds
|
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
if (resetMs) {
|
|
|
|
dateObj.setMilliseconds(0)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Calculate timezone differences
|
|
|
|
return new Date(dateObj.getTime() - offset)
|
|
|
|
} else {
|
|
|
|
return null
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2021-01-08 02:44:04 +00:00
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Parse dates to timestamps
|
|
|
|
for (const range of ranges) {
|
|
|
|
if (filterObj.queries[range]) {
|
|
|
|
if (filterObj.queries[range].from) {
|
|
|
|
const parsed = parseDate(filterObj.queries[range].from, minoffset, true)
|
|
|
|
filterObj.queries[range].from = parsed ? Math.floor(parsed / 1000) : null
|
|
|
|
}
|
|
|
|
if (filterObj.queries[range].to) {
|
|
|
|
const parsed = parseDate(filterObj.queries[range].to, minoffset, true)
|
|
|
|
filterObj.queries[range].to = parsed ? Math.ceil(parsed / 1000) : null
|
|
|
|
}
|
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
}
|
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Query users table for user IDs
|
|
|
|
if (filterObj.queries.user || filterObj.queries.exclude.user) {
|
|
|
|
const usernames = []
|
|
|
|
if (filterObj.queries.user) {
|
|
|
|
usernames.push(...filterObj.queries.user)
|
2020-04-04 16:36:43 +00:00
|
|
|
}
|
2021-01-08 02:44:04 +00:00
|
|
|
if (filterObj.queries.exclude.user) {
|
|
|
|
usernames.push(...filterObj.queries.exclude.user)
|
2020-04-18 19:52:11 +00:00
|
|
|
}
|
2018-10-09 19:52:41 +00:00
|
|
|
|
2022-06-03 21:21:56 +00:00
|
|
|
const uploaders = await utils.db.table('users')
|
2021-01-08 02:44:04 +00:00
|
|
|
.whereIn('username', usernames)
|
|
|
|
.select('id', 'username')
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// If no matches, or mismatched results
|
|
|
|
if (!uploaders || (uploaders.length !== usernames.length)) {
|
|
|
|
const notFound = usernames.filter(username => {
|
|
|
|
return !uploaders.find(uploader => uploader.username === username)
|
2020-04-18 19:52:11 +00:00
|
|
|
})
|
2021-01-08 02:44:04 +00:00
|
|
|
if (notFound) {
|
|
|
|
throw new ClientError(`User${notFound.length === 1 ? '' : 's'} not found: ${notFound.join(', ')}.`)
|
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
for (const uploader of uploaders) {
|
|
|
|
if (filterObj.queries.user && filterObj.queries.user.includes(uploader.username)) {
|
|
|
|
filterObj.uploaders.push(uploader)
|
|
|
|
} else {
|
|
|
|
filterObj.excludeUploaders.push(uploader)
|
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-05-02 20:30:50 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Delete keys to avoid unexpected behavior
|
|
|
|
delete filterObj.queries.user
|
|
|
|
delete filterObj.queries.exclude.user
|
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Parse sort keys
|
|
|
|
if (filterObj.queries.sort) {
|
|
|
|
const allowed = [
|
|
|
|
'expirydate',
|
|
|
|
'id',
|
|
|
|
'name',
|
|
|
|
'original',
|
|
|
|
'size',
|
|
|
|
'timestamp'
|
|
|
|
]
|
|
|
|
|
|
|
|
// Only allow sorting by 'albumid' when not listing album's uploads
|
|
|
|
if (req.params.id === undefined) allowed.push('albumid')
|
|
|
|
|
|
|
|
// Only allow sorting by 'ip' and 'userid' columns when listing all uploads
|
|
|
|
if (all) allowed.push('ip', 'userid')
|
|
|
|
|
|
|
|
for (const obQuery of filterObj.queries.sort) {
|
|
|
|
const tmp = obQuery.toLowerCase().split(':')
|
|
|
|
const column = sortObj.maps[tmp[0]] || tmp[0]
|
|
|
|
|
|
|
|
if (!allowed.includes(column)) {
|
|
|
|
// Alert users if using disallowed/missing columns
|
|
|
|
throw new ClientError(`Column "${column}" cannot be used for sorting.\n\nTry the following instead:\n${allowed.join(', ')}`)
|
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
sortObj.parsed.push({
|
|
|
|
column,
|
|
|
|
order: (tmp[1] && /^d/.test(tmp[1])) ? 'desc' : 'asc',
|
|
|
|
clause: sortObj.nullsLast.includes(column) ? 'nulls last' : '',
|
|
|
|
cast: sortObj.casts[column] || null
|
2020-10-30 18:12:09 +00:00
|
|
|
})
|
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Regular user threshold check
|
|
|
|
if (!ismoderator && sortObj.parsed.length > MAX_SORT_KEYS) {
|
|
|
|
throw new ClientError(`Users are only allowed to use ${MAX_SORT_KEYS} sort key${MAX_SORT_KEYS === 1 ? '' : 's'} at a time.`)
|
|
|
|
}
|
2020-04-18 19:52:11 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Delete key to avoid unexpected behavior
|
|
|
|
delete filterObj.queries.sort
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Parse is keys
|
|
|
|
let isKeys = 0
|
|
|
|
let isLast
|
|
|
|
if (filterObj.queries.is || filterObj.queries.exclude.is) {
|
|
|
|
for (const type of filterObj.typeIs) {
|
|
|
|
const inQuery = filterObj.queries.is && filterObj.queries.is.includes(type)
|
|
|
|
const inExclude = filterObj.queries.exclude.is && filterObj.queries.exclude.is.includes(type)
|
|
|
|
|
|
|
|
// Prioritize exclude keys when both types found
|
|
|
|
if (inQuery || inExclude) {
|
|
|
|
filterObj.flags[`is${type}`] = inExclude ? false : inQuery
|
|
|
|
if (isLast !== undefined && isLast !== filterObj.flags[`is${type}`]) {
|
|
|
|
throw new ClientError('Cannot mix inclusion and exclusion type-is keys.')
|
|
|
|
}
|
|
|
|
isKeys++
|
|
|
|
isLast = filterObj.flags[`is${type}`]
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-05-02 21:32:45 +00:00
|
|
|
}
|
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Delete keys to avoid unexpected behavior
|
|
|
|
delete filterObj.queries.is
|
|
|
|
delete filterObj.queries.exclude.is
|
|
|
|
}
|
2020-05-02 21:32:45 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Regular user threshold check
|
|
|
|
if (!ismoderator && isKeys > MAX_IS_KEYS) {
|
|
|
|
throw new ClientError(`Users are only allowed to use ${MAX_IS_KEYS} type-is key${MAX_IS_KEYS === 1 ? '' : 's'} at a time.`)
|
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-04-12 09:30:33 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
function filter () {
|
|
|
|
// If listing all uploads
|
|
|
|
if (all) {
|
|
|
|
this.where(function () {
|
|
|
|
// Filter uploads matching any of the supplied 'user' keys and/or NULL flag
|
|
|
|
// Prioritze exclude keys when both types found
|
|
|
|
this.orWhere(function () {
|
|
|
|
if (filterObj.excludeUploaders.length) {
|
|
|
|
this.whereNotIn('userid', filterObj.excludeUploaders.map(v => v.id))
|
|
|
|
} else if (filterObj.uploaders.length) {
|
|
|
|
this.orWhereIn('userid', filterObj.uploaders.map(v => v.id))
|
|
|
|
}
|
|
|
|
// Such overbearing logic for NULL values, smh...
|
|
|
|
if ((filterObj.excludeUploaders.length && filterObj.flags.userNull !== false) ||
|
2020-05-02 20:30:50 +00:00
|
|
|
(filterObj.uploaders.length && filterObj.flags.userNull) ||
|
2020-10-30 18:12:09 +00:00
|
|
|
(!filterObj.excludeUploaders.length && !filterObj.uploaders.length && filterObj.flags.userNull)) {
|
2021-01-08 02:44:04 +00:00
|
|
|
this.orWhereNull('userid')
|
|
|
|
} else if (filterObj.flags.userNull === false) {
|
|
|
|
this.whereNotNull('userid')
|
|
|
|
}
|
|
|
|
})
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Filter uploads matching any of the supplied 'ip' keys and/or NULL flag
|
|
|
|
// Same prioritization logic as above
|
|
|
|
this.orWhere(function () {
|
|
|
|
if (filterObj.queries.exclude.ip) {
|
|
|
|
this.whereNotIn('ip', filterObj.queries.exclude.ip)
|
|
|
|
} else if (filterObj.queries.ip) {
|
|
|
|
this.orWhereIn('ip', filterObj.queries.ip)
|
|
|
|
}
|
|
|
|
// ...
|
|
|
|
if ((filterObj.queries.exclude.ip && filterObj.flags.ipNull !== false) ||
|
2020-05-02 20:30:50 +00:00
|
|
|
(filterObj.queries.ip && filterObj.flags.ipNull) ||
|
2020-10-30 18:12:09 +00:00
|
|
|
(!filterObj.queries.exclude.ip && !filterObj.queries.ip && filterObj.flags.ipNull)) {
|
2021-01-08 02:44:04 +00:00
|
|
|
this.orWhereNull('ip')
|
|
|
|
} else if (filterObj.flags.ipNull === false) {
|
|
|
|
this.whereNotNull('ip')
|
|
|
|
}
|
|
|
|
})
|
2020-05-02 19:39:24 +00:00
|
|
|
})
|
2021-01-08 02:44:04 +00:00
|
|
|
} else {
|
|
|
|
// If not listing all uploads, list user's uploads
|
|
|
|
this.where('userid', user.id)
|
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Then, refine using any of the supplied 'albumid' keys and/or NULL flag
|
|
|
|
// Same prioritization logic as 'userid' and 'ip' above
|
|
|
|
if (req.params.id === undefined) {
|
|
|
|
this.andWhere(function () {
|
|
|
|
if (filterObj.queries.exclude.albumid) {
|
|
|
|
this.whereNotIn('albumid', filterObj.queries.exclude.albumid)
|
|
|
|
} else if (filterObj.queries.albumid) {
|
|
|
|
this.orWhereIn('albumid', filterObj.queries.albumid)
|
|
|
|
}
|
|
|
|
// ...
|
|
|
|
if ((filterObj.queries.exclude.albumid && filterObj.flags.albumidNull !== false) ||
|
2020-10-30 18:12:09 +00:00
|
|
|
(filterObj.queries.albumid && filterObj.flags.albumidNull) ||
|
|
|
|
(!filterObj.queries.exclude.albumid && !filterObj.queries.albumid && filterObj.flags.albumidNull)) {
|
2021-01-08 02:44:04 +00:00
|
|
|
this.orWhereNull('albumid')
|
|
|
|
} else if (filterObj.flags.albumidNull === false) {
|
|
|
|
this.whereNotNull('albumid')
|
|
|
|
}
|
|
|
|
})
|
|
|
|
} else if (!all) {
|
|
|
|
// If not listing all uploads, list uploads from user's album
|
|
|
|
this.andWhere('albumid', req.params.id)
|
|
|
|
}
|
2020-05-02 20:30:50 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Then, refine using the supplied 'date' ranges
|
|
|
|
this.andWhere(function () {
|
|
|
|
if (!filterObj.queries.date || (!filterObj.queries.date.from && !filterObj.queries.date.to)) return
|
|
|
|
if (typeof filterObj.queries.date.from === 'number') {
|
|
|
|
if (typeof filterObj.queries.date.to === 'number') {
|
|
|
|
this.andWhereBetween('timestamp', [filterObj.queries.date.from, filterObj.queries.date.to])
|
|
|
|
} else {
|
|
|
|
this.andWhere('timestamp', '>=', filterObj.queries.date.from)
|
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
} else {
|
2021-01-08 02:44:04 +00:00
|
|
|
this.andWhere('timestamp', '<=', filterObj.queries.date.to)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2021-01-08 02:44:04 +00:00
|
|
|
})
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Then, refine using the supplied 'expiry' ranges
|
|
|
|
this.andWhere(function () {
|
|
|
|
if (!filterObj.queries.expiry || (!filterObj.queries.expiry.from && !filterObj.queries.expiry.to)) return
|
|
|
|
if (typeof filterObj.queries.expiry.from === 'number') {
|
|
|
|
if (typeof filterObj.queries.expiry.to === 'number') {
|
|
|
|
this.andWhereBetween('expirydate', [filterObj.queries.expiry.from, filterObj.queries.expiry.to])
|
|
|
|
} else {
|
|
|
|
this.andWhere('expirydate', '>=', filterObj.queries.expiry.from)
|
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
} else {
|
2021-01-08 02:44:04 +00:00
|
|
|
this.andWhere('expirydate', '<=', filterObj.queries.expiry.to)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2021-01-08 02:44:04 +00:00
|
|
|
})
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Then, refine using type-is flags
|
|
|
|
this.andWhere(function () {
|
|
|
|
for (const type of filterObj.typeIs) {
|
|
|
|
let func
|
|
|
|
let operator
|
|
|
|
if (filterObj.flags[`is${type}`] === true) {
|
|
|
|
func = 'orWhere'
|
|
|
|
operator = 'like'
|
|
|
|
} else if (filterObj.flags[`is${type}`] === false) {
|
|
|
|
func = 'andWhere'
|
|
|
|
operator = 'not like'
|
|
|
|
}
|
2020-05-02 21:32:45 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
if (func) {
|
|
|
|
for (const pattern of utils[`${type}Exts`].map(ext => `%${ext}`)) {
|
|
|
|
this[func]('name', operator, pattern)
|
|
|
|
}
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
|
|
|
}
|
2021-01-08 02:44:04 +00:00
|
|
|
})
|
2020-05-02 21:32:45 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Then, refine using the supplied keywords against their file names
|
|
|
|
this.andWhere(function () {
|
|
|
|
if (!filterObj.queries.text) return
|
|
|
|
for (const pattern of filterObj.queries.text) {
|
|
|
|
this.orWhereRaw('?? like ? escape ?', ['name', pattern, '\\'])
|
|
|
|
this.orWhereRaw('?? like ? escape ?', ['original', pattern, '\\'])
|
|
|
|
}
|
|
|
|
})
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
// Finally, refine using the supplied exclusions against their file names
|
|
|
|
this.andWhere(function () {
|
|
|
|
if (!filterObj.queries.exclude.text) return
|
|
|
|
for (const pattern of filterObj.queries.exclude.text) {
|
|
|
|
this.andWhereRaw('?? not like ? escape ?', ['name', pattern, '\\'])
|
|
|
|
this.andWhereRaw('?? not like ? escape ?', ['original', pattern, '\\'])
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2019-01-01 19:39:08 +00:00
|
|
|
|
2020-04-12 09:30:33 +00:00
|
|
|
// Query uploads count for pagination
|
2022-06-03 21:21:56 +00:00
|
|
|
const count = await utils.db.table('files')
|
2020-04-12 09:30:33 +00:00
|
|
|
.where(filter)
|
|
|
|
.count('id as count')
|
|
|
|
.then(rows => rows[0].count)
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!count) return res.json({ success: true, files: [], count })
|
2019-01-01 19:39:08 +00:00
|
|
|
|
2020-05-02 15:42:23 +00:00
|
|
|
let offset = Number(req.params.page)
|
|
|
|
if (isNaN(offset)) offset = 0
|
|
|
|
else if (offset < 0) offset = Math.max(0, Math.ceil(count / 25) + offset)
|
2019-01-01 19:39:08 +00:00
|
|
|
|
2020-06-07 05:29:17 +00:00
|
|
|
const columns = ['id', 'name', 'original', 'userid', 'size', 'timestamp']
|
2022-05-06 19:17:31 +00:00
|
|
|
if (utils.retentions.enabled) columns.push('expirydate')
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!all ||
|
|
|
|
filterObj.queries.albumid ||
|
|
|
|
filterObj.queries.exclude.albumid ||
|
|
|
|
filterObj.flags.albumidNull !== undefined) columns.push('albumid')
|
2019-09-08 01:56:29 +00:00
|
|
|
|
2020-04-12 09:30:33 +00:00
|
|
|
// Only select IPs if we are listing all uploads
|
2020-10-30 18:12:09 +00:00
|
|
|
if (all) columns.push('ip')
|
2019-06-04 00:57:37 +00:00
|
|
|
|
2020-05-02 19:39:24 +00:00
|
|
|
// Build raw query for order by (sorting) operation
|
|
|
|
let orderByRaw
|
2020-10-30 18:12:09 +00:00
|
|
|
if (sortObj.parsed.length) {
|
2020-05-02 19:39:24 +00:00
|
|
|
orderByRaw = sortObj.parsed.map(sort => {
|
|
|
|
// Use Knex.raw() to sanitize user inputs
|
2020-10-30 18:12:09 +00:00
|
|
|
if (sort.cast) {
|
2022-06-03 21:21:56 +00:00
|
|
|
return utils.db.raw(`cast (?? as ${sort.cast}) ${sort.order} ${sort.clause}`.trim(), sort.column)
|
2020-10-30 18:12:09 +00:00
|
|
|
} else {
|
2022-06-03 21:21:56 +00:00
|
|
|
return utils.db.raw(`?? ${sort.order} ${sort.clause}`.trim(), sort.column)
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
}).join(', ')
|
2020-10-30 18:12:09 +00:00
|
|
|
} else {
|
2020-05-02 19:39:24 +00:00
|
|
|
orderByRaw = '`id` desc'
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-05-02 19:39:24 +00:00
|
|
|
|
2022-06-03 21:21:56 +00:00
|
|
|
const files = await utils.db.table('files')
|
2020-04-12 09:30:33 +00:00
|
|
|
.where(filter)
|
2020-05-02 19:39:24 +00:00
|
|
|
.orderByRaw(orderByRaw)
|
2020-04-12 09:30:33 +00:00
|
|
|
.limit(25)
|
|
|
|
.offset(25 * offset)
|
|
|
|
.select(columns)
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!files.length) return res.json({ success: true, files, count, basedomain })
|
2019-06-18 18:48:30 +00:00
|
|
|
|
2020-04-12 09:30:33 +00:00
|
|
|
for (const file of files) {
|
|
|
|
file.extname = utils.extname(file.name)
|
2020-10-30 18:12:09 +00:00
|
|
|
if (utils.mayGenerateThumb(file.extname)) {
|
2020-04-12 09:30:33 +00:00
|
|
|
file.thumb = `thumbs/${file.name.slice(0, -file.extname.length)}.png`
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-04-12 09:30:33 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2020-05-02 20:30:50 +00:00
|
|
|
// If we queried albumid, query album names
|
2020-04-12 09:30:33 +00:00
|
|
|
let albums = {}
|
2020-05-02 20:30:50 +00:00
|
|
|
if (columns.includes('albumid')) {
|
2020-04-12 09:30:33 +00:00
|
|
|
const albumids = files
|
|
|
|
.map(file => file.albumid)
|
|
|
|
.filter((v, i, a) => {
|
|
|
|
return v !== null && v !== undefined && v !== '' && a.indexOf(v) === i
|
|
|
|
})
|
2022-06-03 21:21:56 +00:00
|
|
|
albums = await utils.db.table('albums')
|
2020-04-12 09:30:33 +00:00
|
|
|
.whereIn('id', albumids)
|
|
|
|
.where('enabled', 1)
|
|
|
|
.select('id', 'name')
|
|
|
|
.then(rows => {
|
2020-04-18 19:52:11 +00:00
|
|
|
// Build Object indexed by their IDs
|
2020-04-12 09:30:33 +00:00
|
|
|
const obj = {}
|
2020-10-30 18:12:09 +00:00
|
|
|
for (const row of rows) {
|
2020-04-12 09:30:33 +00:00
|
|
|
obj[row.id] = row.name
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2020-04-12 09:30:33 +00:00
|
|
|
return obj
|
|
|
|
})
|
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2020-04-12 09:30:33 +00:00
|
|
|
// If we are not listing all uploads, send response
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!all) return res.json({ success: true, files, count, albums, basedomain })
|
2020-04-12 09:30:33 +00:00
|
|
|
|
|
|
|
// Otherwise proceed to querying usernames
|
2020-04-18 19:52:11 +00:00
|
|
|
let usersTable = filterObj.uploaders
|
|
|
|
if (!usersTable.length) {
|
2020-04-12 09:30:33 +00:00
|
|
|
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
|
|
|
|
2020-04-12 09:30:33 +00:00
|
|
|
// If there are no uploads attached to a registered user, send response
|
2020-10-30 18:12:09 +00:00
|
|
|
if (!userids.length) return res.json({ success: true, files, count, albums, basedomain })
|
2019-06-17 19:48:42 +00:00
|
|
|
|
2020-04-12 09:30:33 +00:00
|
|
|
// Query usernames of user IDs from currently selected files
|
2022-06-03 21:21:56 +00:00
|
|
|
usersTable = await utils.db.table('users')
|
2020-04-12 09:30:33 +00:00
|
|
|
.whereIn('id', userids)
|
|
|
|
.select('id', 'username')
|
|
|
|
}
|
2019-06-17 19:48:42 +00:00
|
|
|
|
2020-04-12 09:30:33 +00:00
|
|
|
const users = {}
|
2020-10-30 18:12:09 +00:00
|
|
|
for (const user of usersTable) {
|
2020-04-12 09:30:33 +00:00
|
|
|
users[user.id] = user.username
|
2020-10-30 18:12:09 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
|
2021-01-08 02:44:04 +00:00
|
|
|
await res.json({ success: true, files, count, users, albums, basedomain })
|
2020-04-12 09:30:33 +00:00
|
|
|
} catch (error) {
|
2021-01-08 02:44:04 +00:00
|
|
|
return apiErrorsHandler(error, req, res, next)
|
2020-04-12 09:30:33 +00:00
|
|
|
}
|
2018-01-23 20:06:30 +00:00
|
|
|
}
|
|
|
|
|
2022-06-28 04:57:56 +00:00
|
|
|
/** Get file info */
|
|
|
|
|
|
|
|
self.get = async (req, res, next) => {
|
|
|
|
try {
|
|
|
|
const user = await utils.authorize(req)
|
|
|
|
const ismoderator = perms.is(user, 'moderator')
|
|
|
|
|
|
|
|
const identifier = req.params.identifier
|
|
|
|
if (identifier === undefined) {
|
|
|
|
throw new ClientError('No identifier provided.')
|
|
|
|
}
|
|
|
|
|
|
|
|
const file = await utils.db.table('files')
|
|
|
|
.where('name', identifier)
|
|
|
|
.where(function () {
|
|
|
|
if (!ismoderator) {
|
|
|
|
this.where('userid', user.id)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.first()
|
|
|
|
|
|
|
|
if (!file) {
|
|
|
|
throw new ClientError('File not found.', { statusCode: 404 })
|
|
|
|
}
|
|
|
|
|
|
|
|
await res.json({ success: true, file })
|
|
|
|
} catch (error) {
|
|
|
|
return apiErrorsHandler(error, req, res, next)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-08 01:56:29 +00:00
|
|
|
module.exports = self
|