64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
const unzipper = require('unzipper');
|
|
const fs = require('fs-extra');
|
|
const path = require('path');
|
|
const { pipeline } = require('stream/promises');
|
|
const { getDestinationDecision, isCadFile } = require('./router');
|
|
const { buildDestinationIndex } = require('./destinationIndex');
|
|
const { getUnroutedTarget } = require('./unrouted');
|
|
|
|
async function processZip(zipPath, config) {
|
|
const stream = fs.createReadStream(zipPath).pipe(unzipper.Parse({ forceStream: true }));
|
|
const destinationIndex = await buildDestinationIndex(config?.destination);
|
|
const result = {
|
|
scanned: 0,
|
|
copied: 0,
|
|
skipped: 0,
|
|
unrouted: 0,
|
|
details: [],
|
|
};
|
|
|
|
for await (const entry of stream) {
|
|
if (entry.type !== 'File') {
|
|
entry.autodrain();
|
|
continue;
|
|
}
|
|
|
|
const file = entry.path;
|
|
const baseName = path.basename(file);
|
|
result.scanned += 1;
|
|
|
|
if (!isCadFile(baseName)) {
|
|
result.skipped += 1;
|
|
entry.autodrain();
|
|
continue;
|
|
}
|
|
|
|
const decision = getDestinationDecision(baseName, config, destinationIndex);
|
|
const destDir = decision.destination;
|
|
|
|
if (!destDir) {
|
|
const unroutedTarget = await getUnroutedTarget(baseName);
|
|
await pipeline(entry, fs.createWriteStream(unroutedTarget.destinationPath));
|
|
|
|
result.copied += 1;
|
|
result.unrouted += 1;
|
|
result.details.push({
|
|
file: baseName,
|
|
destination: unroutedTarget.destinationDir,
|
|
reason: decision.reason || 'Nessuna regola trovata',
|
|
});
|
|
continue;
|
|
}
|
|
|
|
const dest = path.join(destDir, baseName);
|
|
await pipeline(entry, fs.createWriteStream(dest));
|
|
|
|
result.copied += 1;
|
|
result.details.push({ file: baseName, destination: destDir });
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
module.exports = { processZip };
|