104 lines
2.4 KiB
JavaScript
104 lines
2.4 KiB
JavaScript
const fs = require('fs-extra');
|
|
const path = require('path');
|
|
const os = require('os');
|
|
|
|
const PRIMARY_UNROUTED_DIR = '/cadroute/__NON_SMISTATI';
|
|
const HOME_UNROUTED_DIR = path.join(os.homedir(), '.cadroute', '__NON_SMISTATI');
|
|
|
|
let resolvedUnroutedDirPromise = null;
|
|
|
|
async function resolveUnroutedDir() {
|
|
if (!resolvedUnroutedDirPromise) {
|
|
resolvedUnroutedDirPromise = (async () => {
|
|
try {
|
|
await fs.ensureDir(PRIMARY_UNROUTED_DIR);
|
|
return PRIMARY_UNROUTED_DIR;
|
|
} catch {
|
|
await fs.ensureDir(HOME_UNROUTED_DIR);
|
|
return HOME_UNROUTED_DIR;
|
|
}
|
|
})();
|
|
}
|
|
|
|
return resolvedUnroutedDirPromise;
|
|
}
|
|
|
|
async function getUniquePath(destinationDir, fileName) {
|
|
const parsed = path.parse(fileName);
|
|
let candidate = path.join(destinationDir, fileName);
|
|
let counter = 1;
|
|
|
|
while (await fs.pathExists(candidate)) {
|
|
candidate = path.join(destinationDir, `${parsed.name}__${counter}${parsed.ext}`);
|
|
counter += 1;
|
|
}
|
|
|
|
return candidate;
|
|
}
|
|
|
|
async function getUnroutedTarget(fileName) {
|
|
const destinationDir = await resolveUnroutedDir();
|
|
const destinationPath = await getUniquePath(destinationDir, fileName);
|
|
|
|
return {
|
|
destinationDir,
|
|
destinationPath,
|
|
};
|
|
}
|
|
|
|
async function listFilesRecursively(rootDir) {
|
|
const files = [];
|
|
|
|
async function walk(currentDir) {
|
|
let entries;
|
|
try {
|
|
entries = await fs.readdir(currentDir, { withFileTypes: true });
|
|
} catch {
|
|
return;
|
|
}
|
|
|
|
for (const entry of entries) {
|
|
const fullPath = path.join(currentDir, entry.name);
|
|
|
|
if (entry.isDirectory()) {
|
|
await walk(fullPath);
|
|
continue;
|
|
}
|
|
|
|
if (!entry.isFile()) {
|
|
continue;
|
|
}
|
|
|
|
const stats = await fs.stat(fullPath).catch(() => null);
|
|
if (!stats) {
|
|
continue;
|
|
}
|
|
|
|
files.push({
|
|
name: entry.name,
|
|
relativePath: path.relative(rootDir, fullPath),
|
|
size: stats.size,
|
|
updatedAt: stats.mtime.toISOString(),
|
|
});
|
|
}
|
|
}
|
|
|
|
await walk(rootDir);
|
|
files.sort((a, b) => a.relativePath.localeCompare(b.relativePath, 'it'));
|
|
return files;
|
|
}
|
|
|
|
async function listUnroutedFiles() {
|
|
const directory = await resolveUnroutedDir();
|
|
const files = await listFilesRecursively(directory);
|
|
return { directory, files };
|
|
}
|
|
|
|
module.exports = {
|
|
getUnroutedTarget,
|
|
resolveUnroutedDir,
|
|
listUnroutedFiles,
|
|
PRIMARY_UNROUTED_DIR,
|
|
HOME_UNROUTED_DIR,
|
|
};
|