@aarconada/urserver
Version:
Basic Server definitions to develope REST API with a node + express Server
316 lines (276 loc) • 11.2 kB
JavaScript
/**
* Created by ubuntu on 24/04/18.
*/
;
const _ = require('lodash');
const server = require('./server')();
const path = require('path');
const fs = require('fs');
const checkResourcesConfig = function() {
if(!server.configuration.resourcesFolder || server.configuration.resourcesFolder === null) throw server.defaultResponses.resources_folder_undefined;
};
const getResourcesPath = function() {
if(!server.configuration.appFolder || server.configuration.appFolder === null) throw server.defaultResponses.app_folder_undefined;
var rootPath = server.configuration.appFolder;
if (!_.isEmpty(rootPath) && fs.statSync(rootPath).isDirectory()) {
if (!rootPath.endsWith('/')) rootPath += '/';
rootPath += server.configuration.resourcesFolder;
if (!fs.existsSync(rootPath)) fs.mkdirSync(rootPath);
if (!rootPath.endsWith('/')) rootPath += '/';
}
return rootPath;
};
module.exports.getLogsPath = function() {
if(!server.configuration.appFolder || server.configuration.appFolder === null) throw server.defaultResponses.app_folder_undefined;
var rootPath = server.configuration.appFolder;
if (!_.isEmpty(rootPath) && fs.statSync(rootPath).isDirectory()) {
if (!rootPath.endsWith('/')) rootPath += '/';
rootPath += server.configuration.logger.path;
if (!fs.existsSync(rootPath)) fs.mkdirSync(rootPath);
if (!rootPath.endsWith('/')) rootPath += '/';
}
return rootPath;
};
const getSubFolderPath = function(rootPath, subFolder) {
var result = rootPath;
const elements = subFolder.split('/');
elements.forEach(currentSubFolder => {
result += currentSubFolder;
if (!fs.existsSync(result)) fs.mkdirSync(result);
result += '/';
});
return result;
};
module.exports.getSubFolderPath = getSubFolderPath;
const getExtension = function(filename) {
var ext = path.extname(filename||'').split('.');
return ext[ext.length - 1];
};
module.exports.saveResource = function(subFolder, newFile, newFileName) {
var resultPath = null;
checkResourcesConfig();
if (newFile) {
var rootPath = getSubFolderPath(getResourcesPath(), subFolder);
//*** SAVING THE FILE...
const attachmentFileName = newFileName; // + '.' + getExtension(newFile.name);
const newImageFullPath = rootPath + attachmentFileName
resultPath = subFolder + '/' + attachmentFileName;
fs.writeFileSync(newImageFullPath, newFile.data);
}
return resultPath;
};
module.exports.deleteResource = function(fileName) {
checkResourcesConfig();
if (fileName) {
var rootPath = getResourcesPath();
//*** FIRST, I HAVE TO DELETE THE OLD IMAGE (TAKING OUT RABBISH)
if (!_.isEmpty(fileName)) {
const fileFullPath = rootPath + fileName;
if (fs.existsSync(fileFullPath)) fs.unlinkSync(fileFullPath);
}
}
};
module.exports.replaceResource = function(subFolder, newFile, newFileName, oldFileName) {
var resultPath = null;
checkResourcesConfig();
if (newFile) {
var rootPath = getResourcesPath();
//*** FIRST, I HAVE TO DELETE THE OLD IMAGE (TAKING OUT RABBISH)
if (!_.isEmpty(oldFileName)) {
const oldImageFullPath = rootPath + oldFileName;
if (fs.existsSync(oldImageFullPath)) fs.unlinkSync(oldImageFullPath);
}
//*** AND NOW, I CAN SAVE THE NEW ONE...
//*** BUILDING THE PATH TO THE IMAGES FOLDER
rootPath = getSubFolderPath(rootPath, subFolder);
if (!fs.existsSync(rootPath)) fs.mkdirSync(rootPath);
if (!rootPath.endsWith('/')) rootPath += '/';
//*** SAVING THE IMAGE...
const attachmentFileName = newFileName; // + '.' + getExtension(newFile.name);
const newImageFullPath = rootPath + attachmentFileName
resultPath = subFolder + '/' + attachmentFileName;
fs.writeFileSync(newImageFullPath, newFile.data);
}
return resultPath;
};
module.exports.resizeImage = function(subFolder, originalImageName, imageName) {
var resultPath = null;
checkResourcesConfig();
if (originalImageName) {
//*** I HAVE TO BUIL THE PATH TO THE RESOURCES FOLDER
var rootPath = getResourcesPath();
//*** AND NOW, I CAN SAVE THE NEW ONE...
//*** BUILDING THE PATH TO THE IMAGES FOLDER
rootPath += subFolder;
if (!fs.existsSync(rootPath)) fs.mkdirSync(rootPath);
if (!rootPath.endsWith('/')) rootPath += '/';
//*** SAVING THE IMAGE...
const resizedProfileFileName = imageName + '.png';
const resizedImageFullPath = rootPath + resizedProfileFileName
resultPath = subFolder + '/' + resizedProfileFileName;
const roundedCorners = new Buffer(
'<svg><rect x="0" y="0" width="50" height="50" rx="50" ry="50"/></svg>'
);
const originalProfileImage = server.configuration.appFolder + server.configuration.resourcesFolder + '/' + originalImageName;
const sharp = require('sharp');
sharp(originalProfileImage)
.resize(50, 50)
.overlayWith(roundedCorners, {cutout: true})
.png()
.toFile(resizedImageFullPath)
.then(data => {
server.debug('Resized image succes', data);
})
.catch(err => {
server.debug('Error on Resizing image', err);
throw err;
});
}
return resultPath;
};
module.exports.overlayImages = function(subFolder, imageName, backgroundImage, frontImage, frontWidth, frontHeigth, frontTop, frontLeft) {
var resultPath = null;
checkResourcesConfig();
var rootPath = getResourcesPath();
const backgroundFullPath = rootPath + backgroundImage;
const frontFullPath = rootPath + frontImage;
const overlayFileName = imageName + '.png';
const overlayFullPath = rootPath + subFolder + '/' + overlayFileName;
const sharp = require('sharp');
resultPath = subFolder + '/' + overlayFileName;
const roundedCorners = new Buffer(
'<svg><rect x="0" y="0" width="' + frontWidth + '" height="' + frontHeigth + '" rx="50" ry="50"/></svg>'
);
sharp(frontFullPath)
.resize(frontWidth, frontHeigth)
.overlayWith(roundedCorners, {cutout: true})
.toBuffer()
.then(frontResizedBuffer => {
sharp(backgroundFullPath)
.overlayWith(frontResizedBuffer, {top: frontTop, left: frontLeft})
.png()
.toFile(overlayFullPath)
.then(data => {
server.debug('Overlay image succes', data);
})
.catch(err => {
server.debug('Error on Overlay image', err);
throw server.defaultResponses.error_on_image_overlay;
});
})
.catch(err => {
server.debug('Error on Overlay image', err);
throw server.defaultResponses.error_on_image_overlay;
});
return resultPath;
};
module.exports.readFile = function(subFolder, fileName) {
var resultTemplate = null;
checkResourcesConfig();
if (fileName) {
//*** I HAVE TO BUILD THE PATH TO THE RESOURCES FOLDER
var rootPath = getSubFolderPath(getResourcesPath(), subFolder);
//*** reading the file...
const templateFullPath = rootPath + fileName;
resultTemplate = fs.readFileSync(templateFullPath, 'utf8');
}
return resultTemplate;
};
module.exports.readAbsoluteFile = function(fileFullName) {
var fileContent = null;
if (!_.isUndefined(fileFullName) && !_.isEmpty(fileFullName)) {
fileContent = fs.readFileSync(fileFullName, 'utf8');
}
return fileContent;
};
module.exports.saveAbsoluteFile = function(fileFullName, fileContent) {
var resultPath = null;
if (!_.isUndefined(fileFullName) && !_.isEmpty(fileFullName) && !_.isUndefined(fileContent)) {
//*** SAVING THE FILE...
fs.writeFileSync(fileFullName, fileContent);
}
return resultPath;
};
module.exports.getFilesAttachments = function(subFolder, fileName) {
var result = [];
checkResourcesConfig();
const fileContent = exports.readFile(subFolder, fileName);
if (fileContent) {
var rootPath = getResourcesPath();
//*** BUILDING THE PATH TO THE TEMPLATES FOLDER
rootPath += subFolder;
if (!fs.existsSync(rootPath)) fs.mkdirSync(rootPath);
if (!rootPath.endsWith('/')) {
rootPath += '/';
}
const templatesImages = fs.readdirSync(rootPath);
templatesImages.forEach(currentImage => {
if (fs.lstatSync(rootPath + currentImage).isFile() && fileContent.indexOf(currentImage) != -1) {
result.push({
filename: currentImage,
content: fs.createReadStream(rootPath + currentImage),
cid: currentImage
});
}
});
}
return result;
};
module.exports.serverResourcesPath = getResourcesPath;
module.exports.readDirectory = function(path) {
var result = null;
if (!_.isEmpty(path) && fs.statSync(path).isDirectory()) {
result = fs.readdirSync(path);
}
return result;
};
module.exports.isDirectory = function(path) {
return fs.statSync(path).isDirectory();
};
module.exports.createDirectoryIfNotExists = function(path) {
if (!_.isEmpty(path) && !fs.existsSync(path)) {
fs.mkdirSync(path);
}
};
module.exports.copyFileSync = function(source, target) {
var targetFile = target;
//if target is a directory a new file with the same name will be created
if ( fs.existsSync( target ) ) {
if ( fs.lstatSync( target ).isDirectory() ) {
targetFile = path.join( target, path.basename( source ) );
}
}
fs.writeFileSync(targetFile, fs.readFileSync(source));
};
module.exports.copyFolderRecursiveSync = function(source, target) {
var files = [];
//check if folder needs to be created or integrated
var targetFolder = path.join( target, path.basename( source ) );
if ( !fs.existsSync( targetFolder ) ) {
server.debug(targetFolder);
fs.mkdirSync( targetFolder );
}
//copy
if ( fs.lstatSync( source ).isDirectory() ) {
files = fs.readdirSync( source );
files.forEach( function ( file ) {
var curSource = path.join( source, file );
if ( fs.lstatSync( curSource ).isDirectory() ) {
module.exports.copyFolderRecursiveSync( curSource, targetFolder );
} else {
module.exports.copyFileSync( curSource, targetFolder );
}
} );
}
};
module.exports.appendToFile = function(fullFileName, data) {
fs.appendFileSync(fullFileName, data);
};
module.exports.deleteFile = function(path, fileName) {
if (path && fileName) {
const fileFullPath = path + fileName;
if( fs.existsSync(fileFullPath)) {
fs.unlinkSync(fileFullPath);
}
}
};