2022-07-06 02:53:01 +02:00
|
|
|
const fs = require('../libs/fsExtra')
|
2022-07-05 02:19:38 +02:00
|
|
|
const rra = require('../libs/recursiveReaddirAsync')
|
2021-11-19 01:53:00 +01:00
|
|
|
const axios = require('axios')
|
2022-04-27 02:11:32 +02:00
|
|
|
const Path = require('path')
|
2021-09-30 03:43:36 +02:00
|
|
|
const Logger = require('../Logger')
|
2022-07-24 20:32:05 +02:00
|
|
|
const { AudioMimeType } = require('./constants')
|
2021-08-18 00:01:11 +02:00
|
|
|
|
|
|
|
async function getFileStat(path) {
|
|
|
|
try {
|
|
|
|
var stat = await fs.stat(path)
|
|
|
|
return {
|
|
|
|
size: stat.size,
|
|
|
|
atime: stat.atime,
|
|
|
|
mtime: stat.mtime,
|
|
|
|
ctime: stat.ctime,
|
|
|
|
birthtime: stat.birthtime
|
|
|
|
}
|
|
|
|
} catch (err) {
|
2022-08-16 00:35:13 +02:00
|
|
|
Logger.error('[fileUtils] Failed to stat', err)
|
2021-08-18 00:01:11 +02:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
module.exports.getFileStat = getFileStat
|
|
|
|
|
2022-02-28 01:07:36 +01:00
|
|
|
async function getFileTimestampsWithIno(path) {
|
|
|
|
try {
|
|
|
|
var stat = await fs.stat(path, { bigint: true })
|
|
|
|
return {
|
|
|
|
size: Number(stat.size),
|
|
|
|
mtimeMs: Number(stat.mtimeMs),
|
|
|
|
ctimeMs: Number(stat.ctimeMs),
|
|
|
|
birthtimeMs: Number(stat.birthtimeMs),
|
|
|
|
ino: String(stat.ino)
|
|
|
|
}
|
|
|
|
} catch (err) {
|
2022-08-16 00:35:13 +02:00
|
|
|
Logger.error('[fileUtils] Failed to getFileTimestampsWithIno', err)
|
2022-02-28 01:07:36 +01:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
module.exports.getFileTimestampsWithIno = getFileTimestampsWithIno
|
|
|
|
|
2021-09-04 21:17:26 +02:00
|
|
|
async function getFileSize(path) {
|
|
|
|
var stat = await getFileStat(path)
|
|
|
|
if (!stat) return 0
|
|
|
|
return stat.size || 0
|
|
|
|
}
|
|
|
|
module.exports.getFileSize = getFileSize
|
|
|
|
|
2022-02-28 01:07:36 +01:00
|
|
|
|
|
|
|
function getIno(path) {
|
|
|
|
return fs.stat(path, { bigint: true }).then((data => String(data.ino))).catch((err) => {
|
|
|
|
Logger.error('[Utils] Failed to get ino for path', path, err)
|
|
|
|
return null
|
|
|
|
})
|
|
|
|
}
|
|
|
|
module.exports.getIno = getIno
|
|
|
|
|
2021-09-30 03:43:36 +02:00
|
|
|
async function readTextFile(path) {
|
|
|
|
try {
|
|
|
|
var data = await fs.readFile(path)
|
|
|
|
return String(data)
|
|
|
|
} catch (error) {
|
|
|
|
Logger.error(`[FileUtils] ReadTextFile error ${error}`)
|
|
|
|
return ''
|
|
|
|
}
|
|
|
|
}
|
|
|
|
module.exports.readTextFile = readTextFile
|
|
|
|
|
2021-08-18 00:01:11 +02:00
|
|
|
function bytesPretty(bytes, decimals = 0) {
|
|
|
|
if (bytes === 0) {
|
|
|
|
return '0 Bytes'
|
|
|
|
}
|
|
|
|
const k = 1024
|
2021-09-29 17:16:38 +02:00
|
|
|
var dm = decimals < 0 ? 0 : decimals
|
2021-08-18 00:01:11 +02:00
|
|
|
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
|
|
|
|
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
2021-09-29 17:16:38 +02:00
|
|
|
if (i > 2 && dm === 0) dm = 1
|
2021-08-18 00:01:11 +02:00
|
|
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
|
|
|
|
}
|
|
|
|
module.exports.bytesPretty = bytesPretty
|
|
|
|
|
2021-11-22 03:00:40 +01:00
|
|
|
async function recurseFiles(path, relPathToReplace = null) {
|
2021-11-06 23:26:44 +01:00
|
|
|
path = path.replace(/\\/g, '/')
|
|
|
|
if (!path.endsWith('/')) path = path + '/'
|
|
|
|
|
2021-11-22 03:00:40 +01:00
|
|
|
if (relPathToReplace) {
|
|
|
|
relPathToReplace = relPathToReplace.replace(/\\/g, '/')
|
|
|
|
if (!relPathToReplace.endsWith('/')) relPathToReplace += '/'
|
|
|
|
} else {
|
|
|
|
relPathToReplace = path
|
|
|
|
}
|
|
|
|
|
2021-11-06 23:26:44 +01:00
|
|
|
const options = {
|
|
|
|
mode: rra.LIST,
|
|
|
|
recursive: true,
|
|
|
|
stats: false,
|
|
|
|
ignoreFolders: true,
|
|
|
|
extensions: true,
|
|
|
|
deep: true,
|
|
|
|
realPath: true,
|
|
|
|
normalizePath: true
|
|
|
|
}
|
|
|
|
var list = await rra.list(path, options)
|
|
|
|
if (list.error) {
|
|
|
|
Logger.error('[fileUtils] Recurse files error', list.error)
|
|
|
|
return []
|
|
|
|
}
|
|
|
|
|
2022-04-27 02:11:32 +02:00
|
|
|
const directoriesToIgnore = []
|
|
|
|
|
2021-11-06 23:26:44 +01:00
|
|
|
list = list.filter((item) => {
|
|
|
|
if (item.error) {
|
2022-04-27 02:11:32 +02:00
|
|
|
Logger.error(`[fileUtils] Recurse files file "${item.fullname}" has error`, item.error)
|
2021-11-06 23:26:44 +01:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2021-11-22 03:00:40 +01:00
|
|
|
var relpath = item.fullname.replace(relPathToReplace, '')
|
2022-04-27 02:11:32 +02:00
|
|
|
var reldirname = Path.dirname(relpath)
|
2022-04-28 02:42:34 +02:00
|
|
|
if (reldirname === '.') reldirname = ''
|
2022-04-27 02:11:32 +02:00
|
|
|
var dirname = Path.dirname(item.fullname)
|
|
|
|
|
|
|
|
// Directory has a file named ".ignore" flag directory and ignore
|
|
|
|
if (item.name === '.ignore' && reldirname && reldirname !== '.' && !directoriesToIgnore.includes(dirname)) {
|
|
|
|
Logger.debug(`[fileUtils] .ignore found - ignoring directory "${reldirname}"`)
|
|
|
|
directoriesToIgnore.push(dirname)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ignore any file if a directory or the filename starts with "."
|
2021-11-06 23:26:44 +01:00
|
|
|
var pathStartsWithPeriod = relpath.split('/').find(p => p.startsWith('.'))
|
|
|
|
if (pathStartsWithPeriod) {
|
|
|
|
Logger.debug(`[fileUtils] Ignoring path has . "${relpath}"`)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-04-27 02:11:32 +02:00
|
|
|
return true
|
|
|
|
}).filter(item => {
|
|
|
|
// Filter out items in ignore directories
|
2022-09-11 23:22:07 +02:00
|
|
|
if (directoriesToIgnore.some(dir => item.fullname.startsWith(dir))) {
|
2022-04-27 02:11:32 +02:00
|
|
|
Logger.debug(`[fileUtils] Ignoring path in dir with .ignore "${item.fullname}"`)
|
|
|
|
return false
|
|
|
|
}
|
2021-11-06 23:26:44 +01:00
|
|
|
return true
|
2022-04-28 02:42:34 +02:00
|
|
|
}).map((item) => {
|
|
|
|
var isInRoot = (item.path + '/' === relPathToReplace)
|
|
|
|
return {
|
|
|
|
name: item.name,
|
|
|
|
path: item.fullname.replace(relPathToReplace, ''),
|
|
|
|
dirpath: item.path,
|
|
|
|
reldirpath: isInRoot ? '' : item.path.replace(relPathToReplace, ''),
|
|
|
|
fullpath: item.fullname,
|
|
|
|
extension: item.extension,
|
|
|
|
deep: item.deep
|
|
|
|
}
|
|
|
|
})
|
2021-11-06 23:26:44 +01:00
|
|
|
|
|
|
|
// Sort from least deep to most
|
|
|
|
list.sort((a, b) => a.deep - b.deep)
|
|
|
|
|
|
|
|
return list
|
|
|
|
}
|
2021-11-18 02:19:24 +01:00
|
|
|
module.exports.recurseFiles = recurseFiles
|
|
|
|
|
|
|
|
module.exports.downloadFile = async (url, filepath) => {
|
|
|
|
Logger.debug(`[fileUtils] Downloading file to ${filepath}`)
|
|
|
|
|
|
|
|
const writer = fs.createWriteStream(filepath)
|
|
|
|
const response = await axios({
|
|
|
|
url,
|
|
|
|
method: 'GET',
|
2022-10-09 00:15:37 +02:00
|
|
|
responseType: 'stream',
|
|
|
|
timeout: 30000
|
2021-11-18 02:19:24 +01:00
|
|
|
})
|
|
|
|
response.data.pipe(writer)
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
writer.on('finish', resolve)
|
|
|
|
writer.on('error', reject)
|
|
|
|
})
|
2022-03-22 01:24:38 +01:00
|
|
|
}
|
|
|
|
|
2022-05-14 00:13:58 +02:00
|
|
|
module.exports.sanitizeFilename = (filename, colonReplacement = ' - ') => {
|
2022-03-22 01:24:38 +01:00
|
|
|
if (typeof filename !== 'string') {
|
|
|
|
return false
|
|
|
|
}
|
2022-05-14 00:13:58 +02:00
|
|
|
|
2022-12-14 00:46:18 +01:00
|
|
|
// Most file systems use number of bytes for max filename
|
|
|
|
// to support most filesystems we will use max of 255 bytes in utf-16
|
|
|
|
// Ref: https://doc.owncloud.com/server/next/admin_manual/troubleshooting/path_filename_length.html
|
|
|
|
// Issue: https://github.com/advplyr/audiobookshelf/issues/1261
|
|
|
|
const MAX_FILENAME_BYTES = 255
|
|
|
|
|
|
|
|
const replacement = ''
|
|
|
|
const illegalRe = /[\/\?<>\\:\*\|"]/g
|
|
|
|
const controlRe = /[\x00-\x1f\x80-\x9f]/g
|
|
|
|
const reservedRe = /^\.+$/
|
|
|
|
const windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i
|
|
|
|
const windowsTrailingRe = /[\. ]+$/
|
|
|
|
const lineBreaks = /[\n\r]/g
|
2022-03-22 01:24:38 +01:00
|
|
|
|
2022-12-19 22:02:31 +01:00
|
|
|
let sanitized = filename
|
2022-05-14 00:13:58 +02:00
|
|
|
.replace(':', colonReplacement) // Replace first occurrence of a colon
|
2022-03-22 01:24:38 +01:00
|
|
|
.replace(illegalRe, replacement)
|
|
|
|
.replace(controlRe, replacement)
|
|
|
|
.replace(reservedRe, replacement)
|
2022-06-02 03:14:10 +02:00
|
|
|
.replace(lineBreaks, replacement)
|
2022-03-22 01:24:38 +01:00
|
|
|
.replace(windowsReservedRe, replacement)
|
2022-06-02 03:14:10 +02:00
|
|
|
.replace(windowsTrailingRe, replacement)
|
|
|
|
|
2022-12-14 00:46:18 +01:00
|
|
|
// Check if basename is too many bytes
|
|
|
|
const ext = Path.extname(sanitized) // separate out file extension
|
|
|
|
const basename = Path.basename(sanitized, ext)
|
|
|
|
const extByteLength = Buffer.byteLength(ext, 'utf16le')
|
|
|
|
const basenameByteLength = Buffer.byteLength(basename, 'utf16le')
|
|
|
|
if (basenameByteLength + extByteLength > MAX_FILENAME_BYTES) {
|
|
|
|
const MaxBytesForBasename = MAX_FILENAME_BYTES - extByteLength
|
|
|
|
let totalBytes = 0
|
|
|
|
let trimmedBasename = ''
|
|
|
|
|
|
|
|
// Add chars until max bytes is reached
|
|
|
|
for (const char of basename) {
|
|
|
|
totalBytes += Buffer.byteLength(char, 'utf16le')
|
|
|
|
if (totalBytes > MaxBytesForBasename) break
|
|
|
|
else trimmedBasename += char
|
|
|
|
}
|
|
|
|
|
|
|
|
trimmedBasename = trimmedBasename.trim()
|
|
|
|
sanitized = trimmedBasename + ext
|
2022-06-02 03:14:10 +02:00
|
|
|
}
|
|
|
|
|
2022-03-22 01:24:38 +01:00
|
|
|
return sanitized
|
2022-06-26 22:46:16 +02:00
|
|
|
}
|
2022-07-24 20:32:05 +02:00
|
|
|
|
|
|
|
// Returns null if extname is not in our defined list of audio extnames
|
|
|
|
module.exports.getAudioMimeTypeFromExtname = (extname) => {
|
|
|
|
if (!extname || !extname.length) return null
|
|
|
|
const formatUpper = extname.slice(1).toUpperCase()
|
|
|
|
if (AudioMimeType[formatUpper]) return AudioMimeType[formatUpper]
|
|
|
|
return null
|
2022-08-16 00:35:13 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports.removeFile = (path) => {
|
|
|
|
if (!path) return false
|
|
|
|
return fs.remove(path).then(() => true).catch((error) => {
|
|
|
|
Logger.error(`[fileUtils] Failed remove file "${path}"`, error)
|
|
|
|
return false
|
|
|
|
})
|
2022-07-24 20:32:05 +02:00
|
|
|
}
|