- MultiDominio: api.riso.app, api.gruppomacro.app

This commit is contained in:
Surya Paolo
2024-07-23 12:25:10 +02:00
parent 017ac82d8b
commit 21862f87a1
17 changed files with 484 additions and 97 deletions

View File

@@ -50,6 +50,7 @@ const catalogo = new Schema(
productTypes: [{ type: Number }],
excludeproductTypes: [{ type: Number }],
Editore: [{ type: String }],
pdf: { type: Boolean },
// formato: [{ type: String, default: '' }],
// categoria: [{ type: String, default: '' }],
}

View File

@@ -7,6 +7,8 @@ const shared_consts = require('../tools/shared_nodejs');
const tools = require('../tools/general');
const fs = require('fs');
const { City } = require('../models/city');
const Product = require('../models/product');
const Inventariogm = require('../models/inventariogm');
@@ -18,6 +20,10 @@ const Publisher = require('../models/publisher');
const SubCatProd = require('../models/subcatprod');
const Gasordine = require('../models/gasordine');
const { ImageDownloader } = require('../tools/general.js');
const path = require('path');
var { authenticate } = require('../middleware/authenticate');
router.post('/updateval', authenticate, async (req, res) => {
@@ -45,6 +51,35 @@ function fixURL(url) {
return url.replace(/https:\//g, 'https://');
}
async function downloadImgIfMissing(productInfo) {
if (!productInfo.image_link)
return { prodInfo: null, aggiornatoimg: false };
const img = 'upload/products/' + productInfo.image_link.split('/').pop();
const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
if (!productInfo.img || !fs.existsSync(savePath)) {
// Download image from the URL productInfo.image_link
productInfo.img = img;
const downloader = new ImageDownloader();
const aggiornatoimg = await downloader.downloadImage(productInfo.image_link, savePath).then(result => {
if (result) {
// console.log('Download completato con successo!');
} else {
console.log('Download non riuscito.');
}
return result;
});
return { prodInfo: productInfo, aggiornatoimg };
}
return { prodInfo: null, aggiornatoimg: false };
}
async function completaSettaggioProduct_AndProductInfo(arrcampi_productInfo, arrcampi_product, rec, product, productInfo) {
@@ -329,6 +364,8 @@ router.post('/import', authenticate, async (req, res) => {
let indprod = 0;
let newprod = 0;
let numprod = dataObjects.length;
for (const product of dataObjects) {
let isnuovo = false
let setta = false
@@ -367,6 +404,8 @@ router.post('/import', authenticate, async (req, res) => {
let versione = 0;
console.log(indprod + '/' + numprod);
productInfo.productTypes = [];
// console.log('indprod', indprod, 'arrversGM', arrversGM, 'versione', product.Versione);
@@ -553,6 +592,12 @@ router.post('/import', authenticate, async (req, res) => {
product.idProductInfo = risrecInfo._id;
recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean();
let { prodInfo, aggiornatoimg } = await downloadImgIfMissing(recnewInfo);
if (aggiornatoimg) {
await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: prodInfo });
}
if (risrecInfo._id) {
// Record existed, so it was updated
let arrfieldchange = tools.differentObjects(productInfo, recnewInfo);

View File

@@ -721,11 +721,14 @@ router.post('/login', checkBlocked, (req, res) => {
failedLoginAttempts[body.username]++;
}
let numvolteerrati = failedLoginAttempts[body.username];
const msg = 'Tentativo (' + failedLoginAttempts[body.username] + ') di Login ERRATO [' + body.username + ' , ' + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + ']';
tools.mylogshow(msg);
await telegrambot.sendMsgTelegramToTheAdmin(myuser.idapp, msg, true);
tools.writeErrorLog(msg);
if (numvolteerrati > 2) {
const msg = 'Tentativo (' + numvolteerrati + ') di Login ERRATO [' + body.username + ' , ' + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + ']';
tools.mylogshow(msg);
await telegrambot.sendMsgTelegramToTheAdmin(myuser.idapp, msg, true);
tools.writeErrorLog(msg);
}
// telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg);
if (failedLoginAttempts[body.username] >= MAX_FAILED_ATTEMPTS) {
@@ -1623,7 +1626,7 @@ async function eseguiDbOp(idapp, mydata, locale, req, res) {
await Circuit.createCircuitIfNotExist(req, idapp, recprov.prov);
}
} else if (mydata.dbop === 'correggiProductTypes') {
} else if (mydata.dbop === 'correggiProductTypes') {
await ProductInfo.correggiProductTypes();
@@ -1634,7 +1637,7 @@ async function eseguiDbOp(idapp, mydata, locale, req, res) {
{},
{ $pull: { "profile.mycircuits": { "circuitname": null } } }
);
} else if (mydata.dbop === 'ImpostaMinMaxPersonali') {
await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, '');

View File

@@ -12,18 +12,23 @@ const cors = require('cors');
// console.log(" 2) fs");
const fs = require('fs');
var https = require('https');
var http = require('http');
const NUOVO_METODO_TEST = true;
const METODO_MULTI_CORS = false;
const server_constants = require('./tools/server_constants');
//const throttle = require('express-throttle-bandwidth');
// app.use(throttle(1024 * 128)) // throttling bandwidth
const port = process.env.PORT;
// var cookieParser = require('cookie-parser')
// var csrf = require('csurf')
const express = require('express');
const vhost = require('vhost');
const bodyParser = require('body-parser');
const path = require('path');
@@ -246,79 +251,14 @@ myLoad().then(ris => {
if ((process.env.NODE_ENV === 'production') ||
(process.env.NODE_ENV === 'test')) {
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
const privateKey = fs.readFileSync(keyStream, "utf8");
const certificate = fs.readFileSync(certificateStream, "utf8");
if (NUOVO_METODO_TEST) {
credentials = {
key: privateKey,
cert: certificate,
};
} else {
// NON USATO !
credentials = {
key: privateKey,
cert: certificate,
ca: [
fs.readFileSync(process.env.PATH_SSL_ROOT_PEM, 'utf8'),
fs.readFileSync(process.env.PATH_SSL_CHAIN_PEM, 'utf8'),
],
};
}
var https = require('https');
} else {
if (process.env.HTTPS_LOCALHOST === "true") {
var privateKey = fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8');
var certificate = fs.readFileSync(process.env.PATH_SERVER_CRT, 'utf8');
credentials = {
key: privateKey,
cert: certificate,
ciphers: 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
honorCipherOrder: true,
secureProtocol: 'TLSv1_2_method',
};
var https = require('https');
} else {
var http = require('http');
}
}
if ((process.env.NODE_ENV === 'production') ||
(process.env.NODE_ENV === 'test') || process.env.HTTPS_LOCALHOST === "true") {
if (false) {
/*pem.createCertificate({ days: 1, selfSigned: true }, (err, keys) => {
if (err) {
throw err
}
const httpsServer = https.createServer({ key: keys.clientKey, cert: keys.certificate }, (req, res) => {
res.end('o hai!')
}).listen(port)
}) */
} else {
const httpsServer = https.createServer(credentials, app);
console.log('httpsServer: port ', port);
httpsServer.listen(port);
}
} else {
console.log('httpServer: port ', port);
const httpServer = http.createServer(app);
httpServer.listen(port);
}
startServer(app, process.env.PORT);
mystart();
});
// app.use(throttle(1024 * 128)); // throttling bandwidth
// app.use((req, res, next) => {
@@ -769,5 +709,104 @@ async function faitest() {
}
}
/*const domains = [
{ hostname: 'piuchebuono.app', port: 3000 },
{ hostname: 'gruppomacro.app', port: 3010 },
];*/
function getCredentials(hostname) {
if (NUOVO_METODO_TEST) {
if (METODO_MULTI_CORS) {
const fileprivkey = `/etc/letsencrypt/live/${hostname}/privkey.pem`;
const filecert = `/etc/letsencrypt/live/${hostname}/cert.pem`;
console.log('fileprivkey: ', fileprivkey, ' filecert: ', filecert);
/* return {
SNICallback: function (hostname, callback) {
console.log('hostname: ', hostname);
if (domains.includes(hostname)) {
const fileprivkey = `/etc/letsencrypt/live/${hostname}/privkey.pem`;
const filecert = `/etc/letsencrypt/live/${hostname}/fullchain.pem`;
// console.log('fileprivkey: ', fileprivkey, ' filecert: ', filecert);
const domainCert = {
key: fs.readFileSync(fileprivkey, "utf8"),
cert: fs.readFileSync(filecert, "utf8"),
};
callback(null, domainCert);
} else {
callback(null, { key: privateKey, cert: certificate });
}
}
};*/
return {
key: fs.readFileSync(fileprivkey, "utf8"),
cert: fs.readFileSync(filecert, "utf8")
};
} else {
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
const privateKey = fs.readFileSync(keyStream, "utf8");
const certificate = fs.readFileSync(certificateStream, "utf8");
return { key: privateKey, cert: certificate };
}
} else if (process.env.HTTPS_LOCALHOST === "true") {
try {
return {
key: fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8'),
cert: fs.readFileSync(process.env.PATH_SERVER_CRT, 'utf8'),
ciphers: 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
honorCipherOrder: true,
secureProtocol: 'TLSv1_2_method'
};
} catch (error) {
console.error('Errore durante la lettura dei file di certificazione, error:', error.message);
throw error;
}
}
// Caso di default non specificato, potrebbe essere necessario aggiungere una gestione degli errori qui
}
function startServer(app, port) {
try {
const isProduction = ['production', 'test'].includes(process.env.NODE_ENV);
let domains = [];
try {
domains = JSON.parse(process.env.DOMAINS);
} catch (error) {
console.error("Errore durante la conversione della stringa DOMAINS:", error);
}
console.log('domains', domains);
if (isProduction) {
for (let i = 0; i < domains.length; i++) {
const credentials = getCredentials(domains[i].hostname);
// console.log('credentials: ', credentials);
const httpsServer = https.createServer(credentials, app);
console.log('⭐️⭐️⭐️⭐️⭐️ HTTPS server: ' + domains[i].hostname + ' Port:', domains[i].port);
httpsServer.listen(domains[i].port);
}
} else {
const httpServer = http.createServer(app);
console.log('⭐️⭐️⭐️ HTTP server IN LOCALE : port', port);
httpServer.listen(port);
}
} catch (e) {
console.log('error ' + e);
}
}
module.exports = { app };

View File

@@ -399,6 +399,70 @@ const textlang = {
},
};
/**
* Scarica un'immagine da una URL e la salva in una directory locale
* @param {string} url - L'URL dell'immagine da scaricare
* @param {string} filepath - Il percorso dove salvare l'immagine scaricata
*/
class ImageDownloader {
/**
* Scarica un'immagine da una URL e la salva in una directory locale.
* Tenta di scaricare fino a 3 volte in caso di errore, con un ritardo tra i tentativi.
*
* @param {string} url - L'URL dell'immagine da scaricare
* @param {string} filepath - Il percorso dove salvare l'immagine scaricata
* @param {number} maxRetries - Numero massimo di tentativi in caso di fallimento (default: 3)
* @param {number} delay - Ritardo in millisecondi tra i tentativi (default: 1000)
* @returns {Promise<boolean>}
*/
async downloadImage(url, filepath, maxRetries = 1, delay = 1000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const writer = fs.createWriteStream(filepath);
console.log('url da scaricare:', url);
const response = await axios({
url,
method: 'GET',
responseType: 'stream',
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
}
});
response.data.pipe(writer);
await new Promise((resolve, reject) => {
writer.on('finish', () => {
console.info('✅ Immagine scaricata ' + url + ' in ' + filepath);
resolve(true);
});
writer.on('error', reject);
});
return true;
} catch (error) {
console.error(`❌ Tentativo ${attempt} fallito per l'URL ${url}. Errore:`, error.message);
if (attempt === maxRetries) {
console.error('❌ Tutti i tentativi sono falliti. Scaricamento interrotto.');
return false;
} else {
console.info(`🔁 Ritentando... (${attempt + 1} di ${maxRetries})`);
await sleep(delay);
}
}
}
}
}
// Funzione per implementare il ritardo tra i tentativi
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
module.exports = {
MYAPPS: [],
INITDB_FIRSTIME: true,
@@ -1125,10 +1189,10 @@ module.exports = {
typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED;
} else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT_SENT) {
typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED_SENT;
// } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) {
// typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED;
//} else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE_SENT) {
// typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED_SENT;
// } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) {
// typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED;
//} else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE_SENT) {
// typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED_SENT;
}
}
@@ -5195,5 +5259,7 @@ module.exports = {
}
}
},
ImageDownloader,
};