2018-04-22 23:50:07 +00:00
|
|
|
'use strict';
|
|
|
|
|
2018-05-23 15:03:12 +00:00
|
|
|
const config = require('config');
|
2018-04-22 23:50:07 +00:00
|
|
|
const fs = require('fs-extra');
|
|
|
|
const path = require('path');
|
2018-07-06 22:37:10 +00:00
|
|
|
const truncate = require('../utils/truncate-bytes');
|
2021-12-17 01:04:25 +00:00
|
|
|
const logger = require('../logger')(__filename);
|
2018-04-26 01:26:39 +00:00
|
|
|
|
2018-06-30 23:49:59 +00:00
|
|
|
function limitPathElement(element, limit) {
|
|
|
|
return element.split('/').map((component) => {
|
2018-07-06 22:37:10 +00:00
|
|
|
if (config.library.truncate && Buffer.from(component).length > limit) {
|
|
|
|
return truncate(component, limit - config.library.truncate.truncator.length) + config.library.truncate.truncator;
|
2018-05-23 15:03:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return component;
|
|
|
|
}).join(path.sep);
|
2018-06-30 23:49:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function getPathElements(requestedFilepath) {
|
|
|
|
const originalPathElements = path.parse(requestedFilepath);
|
|
|
|
|
|
|
|
return {
|
|
|
|
root: originalPathElements.root,
|
|
|
|
dir: limitPathElement(originalPathElements.dir, config.library.truncate.limit),
|
|
|
|
name: limitPathElement(originalPathElements.name, config.library.truncate.limit - originalPathElements.ext.length),
|
|
|
|
ext: originalPathElements.ext,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-11-05 03:52:17 +00:00
|
|
|
async function writeBufferToFile(target, buffer, item) {
|
|
|
|
await fs.writeFile(target, buffer);
|
|
|
|
|
|
|
|
if (item && item.mux) {
|
2021-12-17 01:04:25 +00:00
|
|
|
logger.debug(`Temporarily saved '${target}', queued for muxing`);
|
2019-11-05 03:52:17 +00:00
|
|
|
} else {
|
2021-12-17 01:04:25 +00:00
|
|
|
logger.verbose(`Saved '${target}'`);
|
2019-11-05 03:52:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return target;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function save(requestedFilepath, bufferOrBuffers, item) {
|
|
|
|
const pathElements = getPathElements(requestedFilepath);
|
|
|
|
const buffers = [].concat(bufferOrBuffers); // allow for single stream argument
|
|
|
|
|
|
|
|
await fs.ensureDir(pathElements.dir);
|
|
|
|
|
|
|
|
return Promise.all(buffers.map((buffer, index) => {
|
|
|
|
const target = path.join(pathElements.root, pathElements.dir, `${pathElements.name}${buffers.length > 1 ? `-${index}` : ''}${pathElements.ext}`);
|
|
|
|
|
|
|
|
return writeBufferToFile(target, buffer, item);
|
|
|
|
}));
|
|
|
|
}
|
2018-04-22 23:50:07 +00:00
|
|
|
|
|
|
|
module.exports = save;
|