mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-12-02 05:04:13 +01:00
Allow adding files to existing upload folders and opt-in file overwrite
This commit is contained in:
1 parent
de5f80e0ff
commit
508516e1df
3 files changed
+612
-33
No files matched your search
+122
-20
@@ -21,6 +21,7 @@ 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
|
||||
@@ -81,6 +82,14 @@ async function libraryItemContainingUpload(folderPath, outputDirectory) {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @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.
|
||||
@@ -124,26 +133,22 @@ async function lookupUploadDirectory(folderPath, outputDirectory) {
|
||||
|
||||
/**
|
||||
* Throw when this upload must not be written.
|
||||
* An existing destination directory is refused outright, so individual files are not checked on disk.
|
||||
* 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
|
||||
* @returns {Promise<void>}
|
||||
* @param {import('../models/User') | null} [user]
|
||||
* @param {boolean} [overwrite]
|
||||
* @returns {Promise<{ directoryExists: boolean, existingFiles: Set<string> }>}
|
||||
*/
|
||||
async function assertUploadDestination(folderPath, outputDirectory, filenames) {
|
||||
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 existing = await lookupUploadDirectory(folderPath, outputDirectory)
|
||||
if ('libraryItemTitle' in existing) {
|
||||
const message = `${UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX}${existing.libraryItemTitle}`
|
||||
throw new UploadError(409, message, UPLOAD_ERROR_CODE.libraryItemExists, { libraryItemTitle: existing.libraryItemTitle })
|
||||
}
|
||||
if (existing.exists) {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
|
||||
const seen = new Set()
|
||||
for (const name of filenames) {
|
||||
@@ -152,6 +157,65 @@ async function assertUploadDestination(folderPath, outputDirectory, filenames) {
|
||||
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
|
||||
|
||||
@@ -242,23 +306,61 @@ async function removeEmptyCreatedDirectories(deepest, firstCreated) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the item directory this request created, then empty parents this request created.
|
||||
* firstCreated is the return value of createUploadDirectory.
|
||||
* 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) {
|
||||
try {
|
||||
await fs.remove(outputDirectory)
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
Logger.error('[uploadPath] Failed to remove partial upload', outputDirectory, error)
|
||||
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
|
||||
}
|
||||
|
||||
await removeEmptyCreatedDirectories(Path.dirname(outputDirectory), firstCreated)
|
||||
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