$/, '');
miastr = miastr.trimRight().replace(/[\n\r]+$/, '');
miastr = miastr.replace(/
<\/div>$/, '');
miastr = miastr.replace(/
$/, '');
miastr = miastr.replace(/
$/, '');
miastr = miastr.replace(/
$/, '');
return miastr;
},
rimuoviAtPrimoCarattere(stringa) {
if (stringa.charAt(0) === '@') {
return stringa.slice(1);
} else {
return stringa;
}
},
// Funzione per ottenere le coordinate di una singola città
async getCityCoordinates(city) {
try {
const response = await axios.get(
`https://nominatim.openstreetmap.org/search?format=json&q=${city.descr},${city.prov},Italia`
);
if (response.data.length > 0) {
city.lat = parseFloat(response.data[0].lat);
city.long = parseFloat(response.data[0].lon);
// console.log(`${city.descr}: Lat ${city.lat}, Long ${city.long}`);
return city;
} else {
console.error(`Coordinate non trovate per ${city.descr}, ${city.prov}`);
}
return null;
} catch (error) {
console.error(`Errore durante il recupero delle coordinate per ${city.descr}, ${city.prov}:`, error.message);
}
},
/**
* Funzione per scaricare dati GeoJSON dei comuni d'Italia e salvarli localmente.
* @param {string} url - L'URL dal quale scaricare i dati GeoJSON.
* @param {string} outputPath - Il percorso del file in cui salvare i dati GeoJSON.
*/
async downloadGeoJSON(url, outputPath) {
try {
// Effettua una richiesta GET all'URL specificato per scaricare i dati.
const response = await axios.get(url);
const data = response.data;
// Salva i dati GeoJSON in un file locale.
await fs.writeFile(outputPath, JSON.stringify(data, null, 2));
console.log(`Dati GeoJSON salvati in ${outputPath}`);
} catch (error) {
console.error('Errore durante il download o il salvataggio dei dati GeoJSON:', error);
}
},
arrotondaA2Decimali(valore) {
try {
return parseFloat(valore).toFixed(2);
} catch (error) {
return valore;
}
},
cleanHtmlForTelegram(htmlContent) {
try {
// Assicurati che l'HTML abbia un elemento body
const dom = new JSDOM(`${htmlContent}`);
const document = dom.window.document;
// Definisci i tag permessi su Telegram
const allowedTags = ['b', 'strong', 'i', 'em', 'u', 's', 'strike', 'del', 'a', 'code'];
// Seleziona tutti gli elementi all'interno del body
const allElements = document.body.querySelectorAll('*');
allElements.forEach((element) => {
const tagName = element.tagName?.toLowerCase();
if (!allowedTags.includes(tagName)) {
// Crea un nodo di testo e sostituisci l'elemento con quel nodo di testo
const textNode = document.createTextNode(element.textContent || '');
element.replaceWith(textNode);
} else {
// Se il tag è permesso, rimuovi tutti gli attributi ad eccezione di 'href' per i link
if (tagName === 'a') {
const href = element.getAttribute('href');
while (element.attributes.length > 0) {
element.removeAttribute(element.attributes[0].name);
}
if (href) {
element.setAttribute('href', href);
}
} else {
while (element.attributes.length > 0) {
element.removeAttribute(element.attributes[0].name);
}
}
}
});
// Ritorna l'HTML pulito
return document.body.innerHTML;
} catch (error) {
console.error("Errore durante la pulizia dell'HTML:", error);
throw error; // Oppure, gestisci l'errore come preferisci
}
},
getHostWithNoHttporHttps(url) {
try {
const parsedUrl = new URL(url);
return parsedUrl.host;
} catch (error) {
console.error("Errore durante la pulizia dell'HTML:", error);
throw error; // Oppure, gestisci l'errore come preferisci
}
},
// Crea un file con all'interno il nome del dominio per ogni app:
createFileWithDomainName() {
const arrapps = getApps();
const filename = server_constants.FILECONFIG_SERVER;
for (const app of arrapps) {
fs.writeFile(filename, this.getHostWithNoHttporHttps(app.host), function (err) {
if (err) {
console.log(err);
}
});
if (app.host_test) {
fs.writeFile(filename, this.getHostWithNoHttporHttps(app.host_test), function (err) {
if (err) {
console.log(err);
}
});
}
}
},
async listCollectionsBySize() {
let output = ''; // Variabile per memorizzare l'output
try {
const conn = mongoose.connection;
// Ottieni le collezioni e calcola la dimensione
const collections = await conn.db.listCollections().toArray();
// Calcola la dimensione per ciascuna collezione
const collectionSizes = await Promise.all(
collections.map(async (collection) => {
const stats = await conn.db.collection(collection.name).stats();
return { name: collection.name, size: stats.size };
})
);
// Ordina le collezioni per dimensione
collectionSizes.sort((a, b) => b.size - a.size); // Ordine decrescente
output += 'Collezioni ordinate per dimensione:\n'; // Inizio dell'output
collectionSizes.forEach((collection) => {
const sizeInMB = (collection.size / (1024 * 1024)).toFixed(2); // Converti in MB
output += `Collezione: ${collection.name}, Dimensione: ${sizeInMB} MB\n`; // Aggiungi all'output
});
return output; // Restituisci l'output alla fine
} catch (error) {
console.error('Errore:', error);
return `Errore: ${error.message}`; // Restituisci l'errore come stringa
}
},
getStringaConto(mov) {
let mystr = '';
let userfrom = '';
let userto = '';
let profilefrom = null;
let profileto = null;
let tipocontofrom = shared_consts.AccountType.USER;
let tipocontoto = shared_consts.AccountType.USER;
if (mov.contocomfrom && mov.contocomfrom.name) {
userfrom += mov.contocomfrom.name;
tipocontofrom = shared_consts.AccountType.COMMUNITY_ACCOUNT;
}
if (mov.groupfrom) {
userfrom += mov.groupfrom.groupname;
tipocontofrom = shared_consts.AccountType.CONTO_DI_GRUPPO;
}
if (mov.userfrom) {
userfrom += mov.userfrom.username;
profilefrom = mov.userfrom.profile;
}
if (mov.contocomto && mov.contocomto.name) {
userto += mov.contocomto.name;
tipocontoto = shared_consts.AccountType.COMMUNITY_ACCOUNT;
}
if (mov.groupto) {
userto += mov.groupto.groupname;
tipocontoto = shared_consts.AccountType.CONTO_DI_GRUPPO;
}
if (mov.userto) {
userto += mov.userto.username;
profileto = mov.userto.profile;
}
// mystr = t('movement.from') + userfrom + ' ' + t('movement.to') + userto
return {
userfrom: { profile: profilefrom, username: userfrom },
userto: { profile: profileto, username: userto },
tipocontofrom,
tipocontoto,
};
},
getDirUpload() {
return 'upload/';
},
getDirByTable(idapp, table) {
let mydir = this.getdirByIdApp(idapp) + '/';
if (table === 'catalog') {
mydir = 'upload/cataloghi/';
}
return mydir;
},
getURLImg(idapp, table, username, img, checkifExist) {
let dirmain = '';
try {
// let dir = this.getdirByIdApp(idapp) + dirmain + '/' + this.getDirUpload();
let dir = this.getdirByIdApp(idapp);
'/' + this.getDirUpload() + shared_consts.getDirectoryImgByTable(table, username) + dirmain;
img = dir + img;
/*if (checkifExist) {
if (!this.isFileExistsAsync(img)) {
return '';
}
}*/
if (!this.sulServer()) {
// Finta Immagine
img = 'https://riso.app/upload/profile/SoniaVioletFlame/myskills/1000133092.jpg';
}
return img;
} catch (e) {
console.error('Err GetURLImg', e);
return '';
}
},
getLangByUsername(idapp, username) {
//++Todo LANG: Estrarre il Lang dall'username (user, group)
return 'it';
},
getFieldsForAnnunci() {
let annunciFields = {
idMyGroup: {
type: String,
},
expiryDateAdv: {
type: Date,
},
enableExpiringAdv: {
type: Boolean,
},
// **ADDFIELD_ANNUNCI
};
return annunciFields;
},
// Funzione per pulire il nome del file
cleanFileName(filePath) {
// Ottieni solo il nome del file dall'intero percorso
// const fileName = filePath.split('/').pop();
// Rimuovi apostrofi e sostituisci gli spazi con underscore
const cleanedName = fileName.replace(/'/g, '').replace(/\s+/g, '_');
// Restituisci il percorso chiaro; puoi decidere di mantenere il resto del percorso
return cleanedName;
},
fixUrl(myurl, idapp) {
if (!myurl.startsWith('http')) {
return this.getHostByIdApp(idapp) + myurl;
}
if (myurl.startsWith('http://127.0.0.1')) {
//myurl = myurl.replace('http://127.0.0.1:8084/', 'https://riso.app/')
// Se è in locale allora metti una foto finta...
myurl =
'https://images.unsplash.com/photo-1464047736614-af63643285bf?q=80&w=2874&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D';
//myurl = myurl.replace('http://127.0.0.1', 'http://localhost')
}
return myurl;
},
// Funzione per convertire XML in JSON
convertXMLToJSON(xml) {
const parser = new xml2js.Parser();
parser.parseString(xml, (err, result) => {
if (err) {
console.error('Error parsing XML:', err);
} else {
console.log(JSON.stringify(result, null, 2)); // Stampa il risultato in formato JSON
}
});
},
async getFreeDiskSpace(path = '/') {
try {
const { stdout } = await execPromise(`df -k ${path} | tail -1 | awk '{print $4}'`);
const freeSpaceKB = parseInt(stdout.trim());
const freeSpaceGB = (freeSpaceKB / 1024 / 1024).toFixed(2);
return `${freeSpaceGB} GB`;
} catch (error) {
console.error('Errore nel recupero dello spazio libero su disco:', error);
return null;
}
},
async findAllQueryIdApp(model, myfind, sort) {
try {
if (sort) {
return await model.find(myfind).sort(sort).lean();
} else {
return await model.find(myfind).lean();
}
} catch (err) {
console.error('Errore in findAllQueryIdApp:', err, model);
return null;
}
},
// Funzione per implementare il ritardo tra i tentativi
sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
},
/**
* Converte una data in formato italiano GG/MM/YYYY in un oggetto Date e restituisce il timestamp.
* @param {string} dateString - La data in formato GG/MM/YYYY.
* @returns {Object} - Un oggetto contenente la data (Date) e il timestamp (number).
* Restituisce null se la data non è valida.
*/
convertiDataItaliana(dateString) {
// Verifica che la data sia una stringa valida
if (!dateString || typeof dateString !== 'string') {
console.error('Input non valido: la data deve essere una stringa.');
return null;
}
// Rimuovi eventuali spazi bianchi e dividi la data in GG, MM, YYYY
const [giorno, mese, anno] = dateString.trim().split('/').map(Number);
// Controlla che i valori siano stati estratti correttamente
if (isNaN(giorno) || isNaN(mese) || isNaN(anno)) {
console.error('Formato data non valido:', dateString);
return null;
}
// Crea un oggetto Date (mese parte da 0 in JavaScript)
const dateObj = new Date(anno, mese - 1, giorno);
// Verifica che la data sia valida
if (isNaN(dateObj.getTime())) {
console.error('Data non valida:', dateString);
return null;
}
// Restituisci l'oggetto con la data e il timestamp
return {
date: dateObj,
timestamp: dateObj.getTime(),
};
},
getDateFromISOString(mydate) {
const mydate2 = new Date(mydate);
return mydate2;
},
async downloadImgIfMissing(productInfo) {
const ProductInfo = require('../models/productInfo');
const Product = require('../models/product');
try {
if (this.sulServer()) {
dirmain = '';
} else {
dirmain = server_constants.DIR_PUBLIC_LOCALE;
}
/*if (true) {
const prova = await this.isFileExistsAsync('prova');
console.log('PROVA:', prova);
}*/
const vecchiomodo = false;
if (productInfo.image_link && vecchiomodo) {
const relativeimg = productInfo.image_link.split('/').pop();
const img =
this.getdirByIdApp(productInfo.idapp) +
dirmain +
server_constants.DIR_UPLOAD +
'/products/' +
productInfo.image_link.split('/').pop();
const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
let scaricaimg = !productInfo.imagefile || !(await this.isFileExistsAsync(savePath));
if (!productInfo.imagefile && (await this.isFileExistsAsync(savePath))) {
// esiste il file, ma sul DB non è corretto
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
if (stats.size > 0) {
// Controlla se la dimensione del file è maggiore di zero
// Esiste il file ed è non vuoto, ma sul DB non è corretto
productInfo.imagefile = relativeimg;
return { prodInfo: productInfo, aggiornatoimg: true };
} else {
scaricaimg = true;
}
}
if (productInfo.imagefile && (await this.isFileExistsAsync(savePath))) {
// esiste il file, ma sul DB non è corretto
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
if (stats.size <= 0) {
// Controlla se la dimensione del file è maggiore di zero
scaricaimg = true;
}
}
if (scaricaimg && vecchiomodo) {
// Download image from the URL productInfo.image_link
productInfo.imagefile = relativeimg;
const downloader = new ImageDownloader();
const aggiornatoimg = await downloader
.downloadImage(productInfo.image_link, savePath, {
maxRetries: 1,
initialDelay: 300,
timeout: 15000,
})
.then((result) => {
if (result) {
// console.log('Download completato con successo!');
} else {
console.log('Download non riuscito.');
}
return result;
});
return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris };
}
}
let fileesistente = false;
if (productInfo.imagefile && productInfo.imagefile !== 'noimg.jpg') {
// controlla se esiste il file
const img =
this.getdirByIdApp(productInfo.idapp) +
dirmain +
server_constants.DIR_UPLOAD +
'/products/' +
productInfo.imagefile.split('/').pop();
const filecompleto = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
// Se non esiste lo scarico !
fileesistente = await this.isFileExistsAsync(filecompleto);
}
if (!vecchiomodo && (!productInfo.image_link || !fileesistente)) {
let scarica_da_sito = !productInfo.imagefile || productInfo.imagefile === 'noimg.jpg';
if (!scarica_da_sito && productInfo.imagefile) {
scarica_da_sito = !fileesistente; // Se non esiste lo scarico !
}
if (scarica_da_sito && !productInfo.image_not_found) {
// date and time
productInfo.imagefile = 'img_' + new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
const img =
this.getdirByIdApp(productInfo.idapp) +
dirmain +
server_constants.DIR_UPLOAD +
'/products/' +
productInfo.imagefile.split('/').pop();
let savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
let link = 'https://www.gruppomacro.com/copertine.php?id_gm=' + productInfo.sku;
const downloader = new ImageDownloader();
let aggiornatoimg;
try {
aggiornatoimg = await downloader.downloadImage(link, savePath, {
maxRetries: 3,
initialDelay: 300,
timeout: 15000,
nomefileoriginale: true,
});
} catch (e) {
aggiornatoimg = { ris: false };
}
if (
aggiornatoimg?.code === 404 ||
(aggiornatoimg?.filepath && aggiornatoimg.filepath.includes('noimg.jpg'))
) {
// non trovato quindi la prossima volta non richiederlo
await ProductInfo.setImgNotFound(productInfo._id);
}
if (aggiornatoimg?.filepath.includes('noimg.jpg')) {
// nascondi il prodotto se non trovo l'immagine !
await Product.updateOne({ idProductInfo: productInfo._id }, { $set: { deleted: true } });
aggiornatoimg = { ris: false, deleted: true };
}
if (aggiornatoimg?.filepath) {
const filenamebase = path.basename(aggiornatoimg.filepath);
// const img = '/upload/products/' + filenamebase;
productInfo.imagefile = filenamebase;
}
return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris };
} else {
return { prodInfo: null, aggiornatoimg: false };
}
}
} catch (e) {
console.error('downloadImgIfMissing', e.message);
}
return { prodInfo: null, aggiornatoimg: false };
},
removeAccents(mystr) {
if (!mystr) return mystr;
const accentsMap = new Map([
['á', 'a'],
['à', 'a'],
['ã', 'a'],
['ä', 'a'],
['â', 'a'],
['é', 'e'],
['è', 'e'],
['ë', 'e'],
['ê', 'e'],
['í', 'i'],
['ì', 'i'],
['ï', 'i'],
['î', 'i'],
['ó', 'o'],
['ò', 'o'],
['ö', 'o'],
['ô', 'o'],
['õ', 'o'],
['ú', 'u'],
['ù', 'u'],
['ü', 'u'],
['û', 'u'],
['ç', 'c'],
['ñ', 'n'],
]);
return Array.from(mystr)
.map((char) => accentsMap.get(char) || char)
.join('');
},
getDateYYYYMMDD_Today() {
// Ottieni la data attuale nel formato YYYY-MM-DD
const today = new Date();
const formattedDate = today.toISOString().split('T')[0]; // Format YYYY-MM-DD
return formattedDate;
},
convertFullFileNameToURL(idapp, fullfilename) {
const mydir = this.getdirByIdApp(idapp);
const myhost = this.getHostByIdApp(idapp);
// ++ remove mydir from fullfilename and add myhost to generate a URL
const url = fullfilename.replace(mydir, '').replace(/\\/g, '/'); // Replace backslashes with slashes
const myurl = myhost + '/' + url;
console.log('myurl', myurl);
return myurl;
},
removePathDirByFileName(idapp, fullfilename) {
const mydir = this.getdirByIdApp(idapp);
let filename = fullfilename.replace(mydir, '').replace(/\\/g, '/'); // Sostituisce backslash con slash
// Rimuove la barra iniziale se presente
if (filename.startsWith('/')) {
filename = filename.substring(1);
}
return filename;
},
isDateValid(mydate) {
try {
return (
mydate instanceof Date && isFinite(mydate.getTime()) && mydate.toISOString().split('T')[0] !== '1970-01-01'
);
} catch {
return false;
}
},
async getSizeFile(filename) {
try {
if (await this.isFileExistsAsync(filename)) {
const stats = fs.statSync ? fs.statSync(filename) : null;
const fileSizeInBytes = stats.size;
const fileSizeInMB = fileSizeInBytes / (1024 * 1024);
return fileSizeInMB.toFixed(2); // Returns size in MB with 2 decimal places
} else {
return 0;
}
} catch (e) {
console.error('Error getting file size:', e);
return '0.00';
}
},
aggiungiSuffissoAlNomeFile(filePath, suffisso) {
const dir = path.dirname(filePath);
const estensione = path.extname(filePath);
const nomeFile = path.basename(filePath, estensione);
const nuovoNomeFile = nomeFile + suffisso + estensione;
return path.join(dir, nuovoNomeFile);
},
async attendiNSecondi(numsec) {
await new Promise((resolve) => setTimeout(resolve, numsec * 1000));
},
async copyDirectory(sourceDir, destinationDir) {
try {
await fs.copy(sourceDir, destinationDir);
console.log('Directory copiata con successo!');
} catch (err) {
console.error('Errore durante la copia della directory:', err);
}
},
fixFilePath(myfilepath) {
return myfilepath.replace(/\\/g, '/');
},
getDateNow() {
const mydate = new Date();
return mydate;
},
};