mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-12-02 05:04:13 +01:00
Merge branch 'master' into v3
This commit is contained in:
commit
4658ea1f05
8 files changed
+1832
-110
No files matched your search
@@ -4,6 +4,7 @@ const Logger = require('../Logger')
|
||||
const fs = require('../libs/fsExtra')
|
||||
const { toNumber } = require('../utils/index')
|
||||
const fileUtils = require('../utils/fileUtils')
|
||||
const uploadPath = require('../utils/uploadPath')
|
||||
const Database = require('../Database')
|
||||
|
||||
/**
|
||||
@@ -96,67 +97,44 @@ class FileSystemController {
|
||||
})
|
||||
}
|
||||
|
||||
// Check that library folder exists
|
||||
const libraryFolder = await Database.libraryFolderModel.findOne({
|
||||
where: {
|
||||
path: folderPath
|
||||
}
|
||||
})
|
||||
|
||||
if (!libraryFolder) {
|
||||
Logger.error(`[FileSystemController] Library folder not found: ${folderPath}`)
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
|
||||
if (!req.user.checkCanAccessLibrary(libraryFolder.libraryId)) {
|
||||
Logger.error(`[FileSystemController] User "${req.user.username}" attempting to check path exists for library "${libraryFolder.libraryId}" without access`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
let filepath = Path.join(libraryFolder.path, directory)
|
||||
filepath = fileUtils.filePathToPOSIX(filepath)
|
||||
|
||||
// Ensure filepath is inside library folder (prevents directory traversal)
|
||||
if (!fileUtils.isSameOrSubPath(libraryFolder.path, filepath)) {
|
||||
Logger.error(`[FileSystemController] Filepath is not inside library folder: ${filepath}`)
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
|
||||
if (await fs.pathExists(filepath)) {
|
||||
return res.json({
|
||||
exists: true
|
||||
})
|
||||
}
|
||||
|
||||
// Check if a library item exists in a subdirectory
|
||||
// See: https://github.com/advplyr/audiobookshelf/issues/4146
|
||||
const cleanedDirectory = directory.split('/').filter(Boolean).join('/')
|
||||
if (cleanedDirectory.includes('/')) {
|
||||
// Can only be 2 levels deep
|
||||
const possiblePaths = []
|
||||
const subdir = Path.dirname(directory)
|
||||
possiblePaths.push(fileUtils.filePathToPOSIX(Path.join(folderPath, subdir)))
|
||||
if (subdir.includes('/')) {
|
||||
possiblePaths.push(fileUtils.filePathToPOSIX(Path.join(folderPath, Path.dirname(subdir))))
|
||||
}
|
||||
|
||||
const libraryItem = await Database.libraryItemModel.findOne({
|
||||
// Check that library folder exists. The lookup is inside the try: Express 4 does not answer a rejected async route.
|
||||
try {
|
||||
const libraryFolder = await Database.libraryFolderModel.findOne({
|
||||
where: {
|
||||
path: possiblePaths
|
||||
path: folderPath
|
||||
}
|
||||
})
|
||||
|
||||
if (libraryItem) {
|
||||
if (!libraryFolder) {
|
||||
Logger.error(`[FileSystemController] Library folder not found: ${folderPath}`)
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
|
||||
if (!req.user.checkCanAccessLibrary(libraryFolder.libraryId)) {
|
||||
Logger.error(`[FileSystemController] User "${req.user.username}" attempting to check path exists for library "${libraryFolder.libraryId}" without access`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
// Same rules as POST /api/upload: the directory itself, then a library item in a parent folder.
|
||||
// See: https://github.com/advplyr/audiobookshelf/issues/4146
|
||||
const existing = await uploadPath.checkUploadDirectory(libraryFolder.path, directory)
|
||||
if ('libraryItemTitle' in existing) {
|
||||
return res.json({
|
||||
exists: true,
|
||||
libraryItemTitle: libraryItem.title
|
||||
libraryItemTitle: existing.libraryItemTitle
|
||||
})
|
||||
}
|
||||
return res.json({
|
||||
exists: existing.exists
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof uploadPath.UploadError) {
|
||||
Logger.error(`[FileSystemController] Filepath is not inside library folder: ${directory}`)
|
||||
return res.sendStatus(error.statusCode)
|
||||
}
|
||||
Logger.error('[FileSystemController] Failed to check if path exists', directory, error)
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
|
||||
return res.json({
|
||||
exists: false
|
||||
})
|
||||
}
|
||||
}
|
||||
module.exports = new FileSystemController()
|
||||
@@ -1,7 +1,6 @@
|
||||
const Sequelize = require('sequelize')
|
||||
const Path = require('path')
|
||||
const { Request, Response } = require('express')
|
||||
const fs = require('../libs/fsExtra')
|
||||
const Logger = require('../Logger')
|
||||
const SocketAuthority = require('../SocketAuthority')
|
||||
const Database = require('../Database')
|
||||
@@ -12,6 +11,7 @@ const cron = require('../libs/nodeCron')
|
||||
const { isObject, getTitleIgnorePrefix } = require('../utils/index')
|
||||
const ServerSettings = require('../objects/settings/ServerSettings')
|
||||
const { sanitizeFilename } = require('../utils/fileUtils')
|
||||
const uploadPath = require('../utils/uploadPath')
|
||||
const { sanitize } = require('../utils/htmlSanitizer')
|
||||
|
||||
const TaskManager = require('../managers/TaskManager')
|
||||
@@ -29,7 +29,8 @@ class MiscController {
|
||||
|
||||
/**
|
||||
* POST: /api/upload
|
||||
* Update library item
|
||||
* Upload files for a new library item, or add files to an existing folder with update permission.
|
||||
* Refuses to overwrite existing files unless `overwrite` is true and the user has update and delete permissions.
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
@@ -39,17 +40,22 @@ class MiscController {
|
||||
Logger.warn(`User "${req.user.username}" attempted to upload without permission`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
if (!req.files || !Object.values(req.files).length) {
|
||||
// Flatten first. A field can be present and still hold no files.
|
||||
const files = Object.values(req.files || {}).flat()
|
||||
if (!files.length) {
|
||||
Logger.error('Invalid request, no files')
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
|
||||
const files = Object.values(req.files).flat()
|
||||
let { title, author, series, folder: folderId, library: libraryId } = req.body
|
||||
// Validate request body
|
||||
if (!libraryId || !folderId || typeof libraryId !== 'string' || typeof folderId !== 'string' || !title || typeof title !== 'string') {
|
||||
return res.status(400).send('Invalid request body')
|
||||
}
|
||||
const overwrite = req.body.overwrite === true || req.body.overwrite === 'true' || req.body.overwrite === '1'
|
||||
if (overwrite && (!req.user.canUpdate || !req.user.canDelete)) {
|
||||
Logger.warn(`[MiscController] User "${req.user.username}" attempted to upload with overwrite without permission`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
if (!series || typeof series !== 'string') {
|
||||
series = null
|
||||
}
|
||||
@@ -57,55 +63,92 @@ class MiscController {
|
||||
author = null
|
||||
}
|
||||
|
||||
const library = await Database.libraryModel.findByIdWithFolders(libraryId)
|
||||
if (!library) {
|
||||
return res.status(404).send('Library not found')
|
||||
}
|
||||
const filenames = files.map((file) => sanitizeFilename(file.name))
|
||||
|
||||
if (!req.user.checkCanAccessLibrary(library.id)) {
|
||||
Logger.error(`[MiscController] User "${req.user.username}" attempting to upload to library "${library.id}" without access`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
const folder = library.libraryFolders.find((fold) => fold.id === folderId)
|
||||
if (!folder) {
|
||||
return res.status(404).send('Folder not found')
|
||||
}
|
||||
|
||||
// Podcasts should only be one folder deep
|
||||
const outputDirectoryParts = library.isPodcast ? [title] : [author, series, title]
|
||||
// `.filter(Boolean)` to strip out all the potentially missing details (eg: `author`)
|
||||
// before sanitizing all the directory parts to remove illegal chars and finally prepending
|
||||
// the base folder path
|
||||
const cleanedOutputDirectoryParts = outputDirectoryParts.filter(Boolean).map((part) => sanitizeFilename(part))
|
||||
const outputDirectory = Path.join(...[folder.path, ...cleanedOutputDirectoryParts])
|
||||
|
||||
try {
|
||||
await fs.ensureDir(outputDirectory)
|
||||
} catch (error) {
|
||||
Logger.error('[MiscController] Failed to create upload directory', outputDirectory, error)
|
||||
const respond = (error) => {
|
||||
if (error instanceof uploadPath.UploadError) {
|
||||
Logger.warn(`[MiscController] User "${req.user.username}" upload failed (${error.statusCode}): ${error.message}`)
|
||||
if (error.body) return res.status(error.statusCode).json(error.body)
|
||||
// Send only a known plain-text literal rather than arbitrary exception text.
|
||||
const message = uploadPath.PLAIN_TEXT_UPLOAD_ERRORS.find((known) => known === error.message)
|
||||
res.type('text/plain')
|
||||
return message ? res.status(error.statusCode).send(message) : res.sendStatus(error.statusCode)
|
||||
}
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
|
||||
Logger.info(`Uploading ${files.length} files to`, outputDirectory)
|
||||
// A 409 means a file or parent library item conflict. createUploadDirectory removes only
|
||||
// directories this request created when a later mkdir fails.
|
||||
// The library lookup is inside the try: Express 4 does not answer a rejected async route.
|
||||
let outputDirectory
|
||||
let firstCreated = null
|
||||
let createdOutputDirectory = true
|
||||
let existingFiles = new Set()
|
||||
try {
|
||||
const library = await Database.libraryModel.findByIdWithFolders(libraryId)
|
||||
if (!library) {
|
||||
return res.status(404).send('Library not found')
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const path = Path.join(outputDirectory, sanitizeFilename(file.name))
|
||||
if (!req.user.checkCanAccessLibrary(library.id)) {
|
||||
Logger.error(`[MiscController] User "${req.user.username}" attempting to upload to library "${library.id}" without access`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
await file
|
||||
.mv(path)
|
||||
.then(() => {
|
||||
return true
|
||||
})
|
||||
.catch((error) => {
|
||||
Logger.error('Failed to move file', path, error)
|
||||
return false
|
||||
})
|
||||
const folder = library.libraryFolders.find((fold) => fold.id === folderId)
|
||||
if (!folder) {
|
||||
return res.status(404).send('Folder not found')
|
||||
}
|
||||
|
||||
// Podcasts should only be one folder deep. A title that sanitizes to an empty name
|
||||
// must not fall through to the author folder or the library folder.
|
||||
const sanitizedTitle = sanitizeFilename(title)
|
||||
if (!sanitizedTitle) {
|
||||
return res.status(400).send('Invalid upload path')
|
||||
}
|
||||
const parentParts = library.isPodcast ? [] : [author, series].map((part) => sanitizeFilename(part)).filter(Boolean)
|
||||
const directoryParts = [...parentParts, sanitizedTitle]
|
||||
outputDirectory = Path.join(folder.path, ...directoryParts)
|
||||
|
||||
const destination = await uploadPath.assertUploadDestination(folder.path, outputDirectory, filenames, req.user, overwrite)
|
||||
createdOutputDirectory = !destination?.directoryExists
|
||||
existingFiles = destination?.existingFiles || new Set()
|
||||
if (createdOutputDirectory) {
|
||||
firstCreated = await uploadPath.createUploadDirectory(outputDirectory)
|
||||
}
|
||||
} catch (error) {
|
||||
if (!(error instanceof uploadPath.UploadError)) {
|
||||
Logger.error('[MiscController] Failed to upload', outputDirectory, error)
|
||||
}
|
||||
return respond(error)
|
||||
}
|
||||
|
||||
res.sendStatus(200)
|
||||
}
|
||||
const createdFiles = []
|
||||
try {
|
||||
Logger.info(`Uploading ${files.length} files to`, outputDirectory)
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const targetPath = Path.join(outputDirectory, filenames[i])
|
||||
if (!overwrite) {
|
||||
await uploadPath.reserveUploadFile(targetPath)
|
||||
createdFiles.push(targetPath)
|
||||
} else if (!existingFiles.has(filenames[i])) {
|
||||
createdFiles.push(targetPath)
|
||||
}
|
||||
await files[i].mv(targetPath)
|
||||
}
|
||||
|
||||
res.sendStatus(200)
|
||||
} catch (error) {
|
||||
if (!(error instanceof uploadPath.UploadError)) {
|
||||
Logger.error('[MiscController] Failed to upload', outputDirectory, error)
|
||||
}
|
||||
await uploadPath.rollbackFailedUpload(outputDirectory, firstCreated, createdOutputDirectory, createdFiles)
|
||||
if (error instanceof uploadPath.UploadError) return respond(error)
|
||||
const notWritable = uploadPath.notWritableUploadError(error)
|
||||
if (notWritable) return respond(notWritable)
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* GET: /api/tasks
|
||||
* Get tasks for task manager
|
||||
|
||||
@@ -399,7 +399,7 @@ class PlaylistController {
|
||||
// Find all library items
|
||||
const libraryItemIds = new Set(req.body.items.map((i) => i.libraryItemId).filter((i) => i))
|
||||
|
||||
const libraryItems = await Database.libraryItemModel.findAllExpandedWhere({ id: Array.from(libraryItemIds) })
|
||||
const libraryItems = await Database.libraryItemModel.findAllExpandedWhere({ id: Array.from(libraryItemIds), libraryId: req.playlist.libraryId })
|
||||
if (libraryItems.length !== libraryItemIds.size) {
|
||||
return res.status(400).send('Invalid request body items')
|
||||
}
|
||||
|
||||
+23
-12
@@ -19,25 +19,36 @@ const filePathToPOSIX = (path) => {
|
||||
}
|
||||
module.exports.filePathToPOSIX = filePathToPOSIX
|
||||
|
||||
/**
|
||||
* Check whether childPath is inside parentPath (or the same directory when allowSame is true).
|
||||
*/
|
||||
function checkSubPath(parentPath, childPath, allowSame) {
|
||||
const pathImpl = global.isWin === undefined ? Path : global.isWin ? Path.win32 : Path.posix
|
||||
parentPath = pathImpl.toNamespacedPath(parentPath)
|
||||
childPath = pathImpl.toNamespacedPath(childPath)
|
||||
if (parentPath === childPath) return allowSame
|
||||
const relativePath = pathImpl.relative(parentPath, childPath)
|
||||
if (relativePath === '') return allowSame // Same path (e.g. parentPath = '/a/b/', childPath = '/a/b')
|
||||
return relativePath !== '..' && !relativePath.startsWith('..' + pathImpl.sep) && !pathImpl.isAbsolute(relativePath)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check path is a child of or equal to another path
|
||||
*
|
||||
* @param {string} parentPath
|
||||
* @param {string} childPath
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isSameOrSubPath(parentPath, childPath) {
|
||||
parentPath = filePathToPOSIX(parentPath)
|
||||
childPath = filePathToPOSIX(childPath)
|
||||
if (parentPath === childPath) return true
|
||||
const relativePath = Path.relative(parentPath, childPath)
|
||||
return (
|
||||
relativePath === '' || // Same path (e.g. parentPath = '/a/b/', childPath = '/a/b')
|
||||
(!relativePath.startsWith('..') && !Path.isAbsolute(relativePath)) // Sub path
|
||||
)
|
||||
return checkSubPath(parentPath, childPath, true)
|
||||
}
|
||||
module.exports.isSameOrSubPath = isSameOrSubPath
|
||||
|
||||
/**
|
||||
* True when childPath is inside parentPath and is not the same directory.
|
||||
* Trailing separators still count as the same directory.
|
||||
*/
|
||||
function isStrictSubPath(parentPath, childPath) {
|
||||
return checkSubPath(parentPath, childPath, false)
|
||||
}
|
||||
module.exports.isStrictSubPath = isStrictSubPath
|
||||
|
||||
function getFileStat(path) {
|
||||
try {
|
||||
return fs.stat(path)
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
const Path = require('path')
|
||||
const { Op, where, fn, col } = require('sequelize')
|
||||
const fs = require('../libs/fsExtra')
|
||||
const Database = require('../Database')
|
||||
const Logger = require('../Logger')
|
||||
const { filePathToPOSIX, isSameOrSubPath, isStrictSubPath } = require('./fileUtils')
|
||||
|
||||
/**
|
||||
* Stable codes for new upload failures. `error` stays an English sentence so older clients
|
||||
* can keep displaying the body. Existing plain-text 400/404 responses are unchanged.
|
||||
*/
|
||||
const UPLOAD_ERROR_CODE = {
|
||||
pathExists: 'UPLOAD_PATH_EXISTS',
|
||||
libraryItemExists: 'UPLOAD_LIBRARY_ITEM_EXISTS',
|
||||
duplicateFileName: 'UPLOAD_DUPLICATE_FILENAME',
|
||||
folderNotWritable: 'UPLOAD_FOLDER_NOT_WRITABLE'
|
||||
}
|
||||
const UPLOAD_PATH_EXISTS_MESSAGE = 'File already exists'
|
||||
const UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX = 'Library item exists: '
|
||||
const UPLOAD_DUPLICATE_FILENAME_MESSAGE = 'Duplicate file name in upload'
|
||||
const UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE = 'Cannot write to this library folder'
|
||||
const UPLOAD_INVALID_PATH_MESSAGE = 'Invalid upload path'
|
||||
const UPLOAD_INVALID_FILENAME_MESSAGE = 'Invalid file name'
|
||||
const UPLOAD_FORBIDDEN_MESSAGE = 'Forbidden'
|
||||
const PLAIN_TEXT_UPLOAD_ERRORS = [UPLOAD_INVALID_PATH_MESSAGE, UPLOAD_INVALID_FILENAME_MESSAGE]
|
||||
|
||||
module.exports.UPLOAD_ERROR_CODE = UPLOAD_ERROR_CODE
|
||||
module.exports.UPLOAD_PATH_EXISTS_MESSAGE = UPLOAD_PATH_EXISTS_MESSAGE
|
||||
module.exports.UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX = UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX
|
||||
module.exports.UPLOAD_DUPLICATE_FILENAME_MESSAGE = UPLOAD_DUPLICATE_FILENAME_MESSAGE
|
||||
module.exports.UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE = UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE
|
||||
module.exports.PLAIN_TEXT_UPLOAD_ERRORS = PLAIN_TEXT_UPLOAD_ERRORS
|
||||
|
||||
/**
|
||||
* Paths of library items this upload would be nested inside (issue #4146).
|
||||
* At most two levels above the upload directory, matching the previous pathexists check.
|
||||
*
|
||||
* @param {string} folderPath
|
||||
* @param {string} outputDirectory
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function parentLibraryItemPaths(folderPath, outputDirectory) {
|
||||
const relative = filePathToPOSIX(Path.relative(folderPath, outputDirectory))
|
||||
if (!relative || relative === '.' || relative === '..' || relative.startsWith('../') || !relative.includes('/')) return []
|
||||
|
||||
const parent = Path.posix.dirname(relative)
|
||||
const paths = [filePathToPOSIX(Path.join(folderPath, parent))]
|
||||
if (parent.includes('/')) {
|
||||
paths.push(filePathToPOSIX(Path.join(folderPath, Path.posix.dirname(parent))))
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows and macOS treat paths that differ only by case as the same directory.
|
||||
* A case-sensitive match would miss `Author A/Book B` and write `author a/book b/extra` inside it.
|
||||
*
|
||||
* @param {string[]} paths
|
||||
* @returns {import('sequelize').WhereOptions}
|
||||
*/
|
||||
function libraryItemPathWhere(paths) {
|
||||
if (global.isWin || process.platform === 'darwin') {
|
||||
// Apply SQL lower() on both sides so both match SQLite's active lower() implementation
|
||||
// (Unicode via libnusqlite3 when loaded, or ASCII fallback without breaking exact Unicode matches).
|
||||
return where(fn('lower', col('path')), {
|
||||
[Op.in]: paths.map((libraryItemPath) => fn('lower', libraryItemPath))
|
||||
})
|
||||
}
|
||||
return { path: paths }
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} folderPath
|
||||
* @param {string} outputDirectory
|
||||
* @returns {Promise<import('../models/LibraryItem') | null>}
|
||||
*/
|
||||
async function libraryItemContainingUpload(folderPath, outputDirectory) {
|
||||
const paths = parentLibraryItemPaths(folderPath, outputDirectory)
|
||||
if (!paths.length) return null
|
||||
return Database.libraryItemModel.findOne({
|
||||
where: libraryItemPathWhere(paths)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} outputDirectory
|
||||
* @returns {Promise<import('../models/LibraryItem').LibraryItemExpanded | null>}
|
||||
*/
|
||||
async function libraryItemAtPath(outputDirectory) {
|
||||
return Database.libraryItemModel.findOneExpanded(libraryItemPathWhere([filePathToPOSIX(outputDirectory)]))
|
||||
}
|
||||
|
||||
class UploadError extends Error {
|
||||
/**
|
||||
* A code makes the response JSON `{ code, error, ...details }`. Without one, the response stays the plain message.
|
||||
*
|
||||
* @param {number} statusCode
|
||||
* @param {string} message plain-text response, also used as Error.message and as the JSON `error`
|
||||
* @param {string | null} [code]
|
||||
* @param {object} [details] extra JSON fields, such as libraryItemTitle
|
||||
*/
|
||||
constructor(statusCode, message, code = null, details = {}) {
|
||||
super(message)
|
||||
this.name = 'UploadError'
|
||||
this.statusCode = statusCode
|
||||
this.body = code ? { code, error: message, ...details } : null
|
||||
}
|
||||
}
|
||||
module.exports.UploadError = UploadError
|
||||
|
||||
/**
|
||||
* Shared lookup for the upload handler and POST /api/filesystem/pathexists.
|
||||
* Throws when the path escapes the library folder.
|
||||
*
|
||||
* @param {string} folderPath
|
||||
* @param {string} outputDirectory
|
||||
* @returns {Promise<{ exists: boolean, libraryItemTitle?: string }>}
|
||||
*/
|
||||
async function lookupUploadDirectory(folderPath, outputDirectory) {
|
||||
if (!isSameOrSubPath(folderPath, outputDirectory)) {
|
||||
throw new UploadError(400, UPLOAD_INVALID_PATH_MESSAGE)
|
||||
}
|
||||
if (await fs.pathExists(outputDirectory)) {
|
||||
return { exists: true }
|
||||
}
|
||||
|
||||
const libraryItem = await libraryItemContainingUpload(folderPath, outputDirectory)
|
||||
if (libraryItem) {
|
||||
return { exists: true, libraryItemTitle: libraryItem.title || '' }
|
||||
}
|
||||
return { exists: false }
|
||||
}
|
||||
|
||||
/**
|
||||
* Throw when this upload must not be written.
|
||||
* Allows adding non-conflicting files to an existing directory when the user has update permission
|
||||
* (and access to any matching library item), and overwriting existing regular files only when
|
||||
* `overwrite` is true. Nested uploads inside an existing library item are always refused.
|
||||
*
|
||||
* @param {string} folderPath
|
||||
* @param {string} outputDirectory absolute directory the files would be written into
|
||||
* @param {string[]} filenames sanitized file names
|
||||
* @param {import('../models/User') | null} [user]
|
||||
* @param {boolean} [overwrite]
|
||||
* @returns {Promise<{ directoryExists: boolean, existingFiles: Set<string> }>}
|
||||
*/
|
||||
async function assertUploadDestination(folderPath, outputDirectory, filenames, user = null, overwrite = false) {
|
||||
// The library folder itself is not a valid item directory, even when every name sanitized away.
|
||||
if (!isStrictSubPath(folderPath, outputDirectory)) {
|
||||
throw new UploadError(400, UPLOAD_INVALID_PATH_MESSAGE)
|
||||
}
|
||||
|
||||
const seen = new Set()
|
||||
for (const name of filenames) {
|
||||
if (!name) throw new UploadError(400, UPLOAD_INVALID_FILENAME_MESSAGE)
|
||||
const key = name.toLowerCase()
|
||||
if (seen.has(key)) throw new UploadError(409, UPLOAD_DUPLICATE_FILENAME_MESSAGE, UPLOAD_ERROR_CODE.duplicateFileName)
|
||||
seen.add(key)
|
||||
}
|
||||
|
||||
const parentLibraryItem = await libraryItemContainingUpload(folderPath, outputDirectory)
|
||||
if (parentLibraryItem) {
|
||||
const libraryItemTitle = parentLibraryItem.title || ''
|
||||
const message = `${UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX}${libraryItemTitle}`
|
||||
throw new UploadError(409, message, UPLOAD_ERROR_CODE.libraryItemExists, { libraryItemTitle })
|
||||
}
|
||||
|
||||
let dirStat = null
|
||||
try {
|
||||
dirStat = await fs.lstat(outputDirectory)
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOTDIR') {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
if (error.code !== 'ENOENT') {
|
||||
const notWritable = notWritableUploadError(error)
|
||||
if (notWritable) throw notWritable
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
if (!dirStat) {
|
||||
return { directoryExists: false, existingFiles: new Set() }
|
||||
}
|
||||
|
||||
if (!dirStat.isDirectory()) {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
|
||||
if (!user?.canUpdate) {
|
||||
throw new UploadError(403, UPLOAD_FORBIDDEN_MESSAGE)
|
||||
}
|
||||
|
||||
const existingLibraryItem = await libraryItemAtPath(outputDirectory)
|
||||
if (existingLibraryItem && !user.checkCanAccessLibraryItem(existingLibraryItem)) {
|
||||
throw new UploadError(403, UPLOAD_FORBIDDEN_MESSAGE)
|
||||
}
|
||||
|
||||
const existingFiles = new Set()
|
||||
for (const name of filenames) {
|
||||
const targetPath = Path.join(outputDirectory, name)
|
||||
let targetStat = null
|
||||
try {
|
||||
targetStat = await fs.lstat(targetPath)
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') continue
|
||||
const notWritable = notWritableUploadError(error)
|
||||
if (notWritable) throw notWritable
|
||||
throw error
|
||||
}
|
||||
|
||||
if (targetStat.isDirectory() || targetStat.isSymbolicLink() || !overwrite) {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
existingFiles.add(name)
|
||||
}
|
||||
|
||||
return { directoryExists: true, existingFiles }
|
||||
}
|
||||
module.exports.assertUploadDestination = assertUploadDestination
|
||||
|
||||
/**
|
||||
* POST /api/filesystem/pathexists. `directory` is the client path relative to the library folder.
|
||||
*
|
||||
* @param {string} folderPath
|
||||
* @param {string} directory
|
||||
* @returns {Promise<{ exists: boolean, libraryItemTitle?: string }>}
|
||||
*/
|
||||
async function checkUploadDirectory(folderPath, directory) {
|
||||
return lookupUploadDirectory(folderPath, Path.join(folderPath, directory))
|
||||
}
|
||||
module.exports.checkUploadDirectory = checkUploadDirectory
|
||||
|
||||
const NOT_WRITABLE_CODES = ['EACCES', 'EPERM', 'EROFS']
|
||||
|
||||
/**
|
||||
* Permission errors from mkdir or move. Null for every other failure.
|
||||
*
|
||||
* @param {NodeJS.ErrnoException} error
|
||||
* @returns {UploadError | null}
|
||||
*/
|
||||
function notWritableUploadError(error) {
|
||||
if (!error || !NOT_WRITABLE_CODES.includes(error.code)) return null
|
||||
return new UploadError(403, UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE, UPLOAD_ERROR_CODE.folderNotWritable)
|
||||
}
|
||||
module.exports.notWritableUploadError = notWritableUploadError
|
||||
|
||||
/**
|
||||
* Create the upload directory. Returns the first parent this call created, or null when
|
||||
* every parent already existed. The leaf mkdir is not recursive: an existing directory
|
||||
* would count as success, and a later failure would delete it.
|
||||
*
|
||||
* @param {string} outputDirectory
|
||||
* @returns {Promise<string | null>}
|
||||
*/
|
||||
async function createUploadDirectory(outputDirectory) {
|
||||
let firstCreated = null
|
||||
try {
|
||||
firstCreated = (await fs.mkdir(Path.dirname(outputDirectory), { recursive: true })) || null
|
||||
await fs.mkdir(outputDirectory)
|
||||
} catch (error) {
|
||||
if (firstCreated) await removeEmptyCreatedDirectories(Path.dirname(outputDirectory), firstCreated)
|
||||
// An existing directory is EEXIST. A parent segment that is a file is ENOTDIR on Linux and macOS, and EEXIST on Windows.
|
||||
if (error.code === 'EEXIST' || error.code === 'ENOTDIR') {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
const notWritable = notWritableUploadError(error)
|
||||
if (notWritable) throw notWritable
|
||||
throw error
|
||||
}
|
||||
return firstCreated
|
||||
}
|
||||
module.exports.createUploadDirectory = createUploadDirectory
|
||||
|
||||
/**
|
||||
* Remove empty directories this request created, from deepest up through firstCreated.
|
||||
* Directories that already existed are left alone, including empty ones.
|
||||
*
|
||||
* @param {string} deepest
|
||||
* @param {string} firstCreated
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function removeEmptyCreatedDirectories(deepest, firstCreated) {
|
||||
if (!firstCreated) return
|
||||
let current = deepest
|
||||
while (isSameOrSubPath(firstCreated, current)) {
|
||||
let names
|
||||
try {
|
||||
names = await fs.readdir(current)
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return
|
||||
Logger.error('[uploadPath] Failed to read upload directory during rollback', current, error)
|
||||
return
|
||||
}
|
||||
if (names.length) return
|
||||
try {
|
||||
await fs.rmdir(current)
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
Logger.error('[uploadPath] Failed to remove upload directory', current, error)
|
||||
}
|
||||
return
|
||||
}
|
||||
current = Path.dirname(current)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically reserve a destination file path so a concurrent upload cannot overwrite it.
|
||||
*
|
||||
* @param {string} targetPath
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function reserveUploadFile(targetPath) {
|
||||
let fd
|
||||
try {
|
||||
fd = await fs.open(targetPath, 'wx')
|
||||
} catch (error) {
|
||||
if (error.code === 'EEXIST' || error.code === 'EISDIR') {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
const notWritable = notWritableUploadError(error)
|
||||
if (notWritable) throw notWritable
|
||||
throw error
|
||||
}
|
||||
await fs.close(fd)
|
||||
}
|
||||
module.exports.reserveUploadFile = reserveUploadFile
|
||||
|
||||
/**
|
||||
* Roll back a failed upload without touching pre-existing directories or files.
|
||||
* When this request created outputDirectory, remove it and any empty parents this request created.
|
||||
* When outputDirectory already existed, remove only files created by this request.
|
||||
* Unmoved temp files are deleted by the multipart parser when the response closes.
|
||||
*
|
||||
* @param {string} outputDirectory
|
||||
* @param {string | null} firstCreated
|
||||
* @param {boolean} [createdOutputDirectory]
|
||||
* @param {string[]} [createdFiles]
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function rollbackFailedUpload(outputDirectory, firstCreated, createdOutputDirectory = true, createdFiles = []) {
|
||||
if (createdOutputDirectory) {
|
||||
try {
|
||||
await fs.remove(outputDirectory)
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
Logger.error('[uploadPath] Failed to remove partial upload', outputDirectory, error)
|
||||
}
|
||||
}
|
||||
|
||||
await removeEmptyCreatedDirectories(Path.dirname(outputDirectory), firstCreated)
|
||||
return
|
||||
}
|
||||
|
||||
for (const filePath of createdFiles) {
|
||||
try {
|
||||
await fs.unlink(filePath)
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
Logger.error('[uploadPath] Failed to remove partial upload file', filePath, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
module.exports.rollbackFailedUpload = rollbackFailedUpload
|
||||
Reference in new issue
Block a user