From a3c7b92c0ca8a4f72bc22f786134742ff7b3cd74 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Mon, 19 May 2025 17:33:58 +0200 Subject: [PATCH] - Estrazione dei dati da Amazon - Ciclo di Estrapolazione di tutti i prodotti ed aggiornamento dei campi scraped e scraped_updated - Creazione file CSV con i campi modificati. --- src/server/models/product.js | 8 +- src/server/models/productInfo.js | 7 - src/server/modules/CronMod.js | 17 +- src/server/modules/ImageDownloader.js | 179 ++ src/server/modules/Macro.js | 1 + src/server/modules/Scraping.js | 554 +++- src/server/modules/dist/Cloudflare.dev.js | 885 ++++++ src/server/modules/dist/CronMod.dev.js | 1745 +++++++++++ src/server/modules/dist/ErrorHandler.dev.js | 45 + src/server/modules/dist/Mailinabox.dev.js | 348 +++ src/server/populate/populate.js | 4 +- src/server/router/admin_router.js | 8 +- src/server/router/index_router.js | 4 +- src/server/server.js | 33 +- src/server/tools/general.js | 3019 +++++++++---------- yarn.lock | 5 + 16 files changed, 5131 insertions(+), 1731 deletions(-) create mode 100644 src/server/modules/ImageDownloader.js create mode 100644 src/server/modules/dist/Cloudflare.dev.js create mode 100644 src/server/modules/dist/CronMod.dev.js create mode 100755 src/server/modules/dist/ErrorHandler.dev.js create mode 100644 src/server/modules/dist/Mailinabox.dev.js diff --git a/src/server/models/product.js b/src/server/models/product.js index f088173..1247e9a 100755 --- a/src/server/models/product.js +++ b/src/server/models/product.js @@ -241,6 +241,12 @@ const productSchema = new Schema({ scraped: { type: Boolean, }, + scraped_error: { + type: Boolean, + }, + scraped_updated: { + type: Boolean, + }, scraped_date: { type: Date, }, @@ -476,7 +482,7 @@ module.exports.findAllIdApp = async function (idapp, code, id, all, isbn) { if (idapp) { myfind = { idapp, - $or: [{ delete: { $exists: false } }, { delete: false }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }; } diff --git a/src/server/models/productInfo.js b/src/server/models/productInfo.js index 07dccb5..532b303 100755 --- a/src/server/models/productInfo.js +++ b/src/server/models/productInfo.js @@ -183,13 +183,6 @@ const productInfoSchema = new Schema({ sottotitolo: String, link_macro: String, - scraped: { - type: Boolean, - }, - scraped_date: { - type: Date, - }, - }); var productInfo = module.exports = mongoose.model('ProductInfo', productInfoSchema); diff --git a/src/server/modules/CronMod.js b/src/server/modules/CronMod.js index ab4b587..1e5e8cc 100644 --- a/src/server/modules/CronMod.js +++ b/src/server/modules/CronMod.js @@ -47,14 +47,27 @@ class CronMod { const globalTables = require("../tools/globalTables"); const { Reaction } = require("../models/reaction"); + const AmazonBookScraper = require('../modules/Scraping'); + + let mystr = ""; try { if (mydata.dbop === "") { // } else if (mydata.dbop === 'rigeneraTutto') { // await ListaIngresso.Esegui_CronTab(idapp, mydata); - } else if (mydata.dbop === "ScraperDataAmazon") { - await ScraperDataAmazon(idapp, mydata.options) + } else if (mydata.dbop === "ScraperMultipleDataAmazon") { + mystr = await AmazonBookScraper.ScraperMultipleDataAmazon(idapp, mydata.options); + ris = { mystr }; + } else if (mydata.dbop === "ScraperGeneraCSV") { + mystr = await AmazonBookScraper.ScraperGeneraCSV(idapp, mydata.options, res); + ris = { mystr }; + } else if (mydata.dbop === "removeDuplicateVariations") { + mystr = await AmazonBookScraper.removeDuplicateVariations(idapp, mydata.options); + ris = { mystr }; + } else if (mydata.dbop === "ScraperAzzeraFlagProducts") { + mystr = await AmazonBookScraper.ScraperAzzeraFlagProducts(idapp, mydata.options); + ris = { mystr }; } else if (mydata.dbop === "ReplaceAllCircuits") { // ++ Replace All Circuitname with 'Circuito RIS %s' await Circuit.replaceAllCircuitNames(idapp); diff --git a/src/server/modules/ImageDownloader.js b/src/server/modules/ImageDownloader.js new file mode 100644 index 0000000..bb476d2 --- /dev/null +++ b/src/server/modules/ImageDownloader.js @@ -0,0 +1,179 @@ +const fs = require('fs'); // 👈 Usa il modulo promises +const axios = require('axios'); +const path = require('path'); + +/** + * 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} + */ + async downloadImage(url, filepath, options = {}) { + const { + maxRetries = 3, // Aumentato il numero di tentativi predefiniti + initialDelay = 1000, // Ritardo iniziale + maxDelay = 10000, // Ritardo massimo + timeout = 30000, // Timeout della richiesta + validateContentType = true, // Verifica del tipo di contenuto + nomefileoriginale = true, + } = options; + + // Funzione per il backoff esponenziale + const getDelay = (attempt) => { + return Math.min(initialDelay * Math.pow(2, attempt - 1), maxDelay); + }; + + for (let attempt = 1; attempt <= maxRetries; attempt++) { + try { + // Verifica se il filepath esiste già + if (await this.isFileExistsAsync(filepath)) { + fs.unlinkSync(filepath); + } + + if (attempt > 1) console.log(`📥 Tentativo ${attempt}/${maxRetries} - Scaricamento: ${url}`); + + const response = await axios({ + url, + method: 'GET', + responseType: 'stream', + timeout: timeout, + maxRedirects: 5, + headers: { + 'User-Agent': + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + Accept: 'image/jpeg,image/png,image/webp,image/gif,image/*', // Specifico per immagini + 'Cache-Control': 'no-cache', // Evita problemi di caching + Connection: 'keep-alive', + }, + validateStatus: (status) => status === 200, // Per immagini ci aspettiamo 200 + maxContentLength: 10 * 1024 * 1024, // Limite di 10MB per immagine + }); + + // Verifica del content-type se richiesto + if (validateContentType) { + const contentType = response.headers['content-type']; + if (!contentType || !contentType.startsWith('image/')) { + throw new Error(`Content-Type non valido: ${contentType}`); + } + } + + // Verifica della dimensione del file + const contentLength = parseInt(response.headers['content-length']); + if (contentLength && contentLength > 100 * 1024 * 1024) { + // 100MB limit + throw new Error('File troppo grande'); + } + + let downloadedBytes = 0; + response.data.on('data', (chunk) => { + downloadedBytes += chunk.length; + }); + + let writer = null; + + if (nomefileoriginale) { + // Estrai il nome del file dall'URL o da Content-Disposition + //let fileName = this.extractFileNameFromUrl(url) || this.extractFileNameFromHeaders(response.headers); + let fileName = path.basename(response.data.responseUrl); + + // Se il nome del file non è specificato, genera un nome predefinito + if (!fileName) { + fileName = `image_${Date.now()}.jpg`; + } + + // Genera il percorso completo del file + const fullPath = path.join(path.dirname(filepath), fileName); + + filepath = fullPath; + } + + // Scrivi il file sul disco + writer = fs.createWriteStream(filepath); + + response.data.pipe(writer); + + await new Promise((resolve, reject) => { + writer.on('finish', resolve); + writer.on('error', (error) => { + fs.unlink(filepath, () => {}); // Pulizia in caso di errore + reject(error); + }); + response.data.on('error', (error) => { + fs.unlink(filepath, () => {}); + reject(error); + }); + }); + + console.info(`✅ Immagine scaricata con successo in ${filepath}`); + + return { ris: true, filepath }; + } catch (error) { + console.error(`❌ Errore nel tentativo ${attempt}/${maxRetries}:`, error.message); + + // Pulizia del file in caso di errore + if (await this.isFileExistsAsync(filepath)) { + fs.unlinkSync(filepath); + } + + // se in error.message c'è '404' allora esci e ritorna code: 404 + if (error.message.includes('404')) { + return { ris: false, code: 404 }; + } + + if (attempt === maxRetries) { + console.error(`Download fallito dopo ${maxRetries} tentativi: ${error.message}`); + return { ris: false }; + } + + const delay = getDelay(attempt); + console.info(`🔄 Attendo ${delay}ms prima del prossimo tentativo...`); + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + } + + // Funzione per estrarre il nome del file dall'URL + extractFileNameFromUrl(url) { + const match = url.match(/\/([^/?#]+)(?:[?#]|$)/); + return match ? decodeURIComponent(match[1]) : null; + } + + // Funzione per estrarre il nome del file da Content-Disposition + extractFileNameFromHeaders(headers) { + const contentDisposition = headers['content-disposition']; + if (contentDisposition) { + const match = contentDisposition.match(/filename="([^"]+)"/); + if (match) { + return decodeURIComponent(match[1]); + } + } + return null; + } + + async isFileExistsAsync (filename) { + try { + let fileExists = await fs.promises + .stat(filename) + .then(() => true) + .catch(() => false); + // console.log(filename, 'esiste', fileExists) + return fileExists; + } catch (e) { + // console.log(filename, 'esiste', 'FALSE') + return false; + } + } + +} + +module.exports = ImageDownloader; diff --git a/src/server/modules/Macro.js b/src/server/modules/Macro.js index 97f6138..79fffd9 100644 --- a/src/server/modules/Macro.js +++ b/src/server/modules/Macro.js @@ -613,6 +613,7 @@ class Macro { await this.gestisciAutori(productInfo, product); await this.gestisciEditore(productInfo, product); await this.gestisciCollana(productInfo, product); + const risrecInfo = await ProductInfo.findOneAndUpdate( diff --git a/src/server/modules/Scraping.js b/src/server/modules/Scraping.js index 140ddcc..4a906c5 100644 --- a/src/server/modules/Scraping.js +++ b/src/server/modules/Scraping.js @@ -5,6 +5,9 @@ const Product = require('../models/product'); const ProductInfo = require('../models/productInfo'); const tools = require('../tools/general'); +const shared_consts = require('../tools/shared_nodejs'); + +const fs = require('fs').promises; // 👈 Usa il modulo promises class AmazonBookScraper { constructor() { @@ -23,7 +26,7 @@ class AmazonBookScraper { // altri header se necessario }, }); - return data; + return { html: data, url }; } catch (err) { console.error(`Errore fetching ISBN ${isbn10}:`, err.message); return null; @@ -57,7 +60,7 @@ class AmazonBookScraper { } } - async extractData(myproduct, html) { + async extractData(myproduct, html, url) { const $ = cheerio.load(html); const productInfo = await ProductInfo.findOne({ _id: myproduct.idProductInfo }).lean(); @@ -107,99 +110,258 @@ class AmazonBookScraper { return { titolo: title, ...(titoloOriginale ? { titoloOriginale } : {}), - ...(sottotitolo ? { sottotitolo } : {sottotitolo: ''}), - numpagine, - misure, - edizione, - data_pubblicazione, - editore: publisher, + ...(sottotitolo ? { sottotitolo } : { sottotitolo: '' }), + ...(numpagine ? { numpagine } : {}), + ...(misure ? { misure } : {}), + ...(edizione ? { edizione } : {}), + ...(data_pubblicazione ? { data_pubblicazione } : {}), + ...(publisher ? { editore: publisher } : {}), + url: `URL`, }; } async scrapeISBN(myproduct, isbn, options) { - const isbn10 = this.isbn13to10(isbn); - const html = await this.fetchPageISBN10(isbn10); - if (!html) return null; + try { + const isbn10 = this.isbn13to10(isbn); + const res = await this.fetchPageISBN10(isbn10); + if (!res) { + await Product.findOneAndUpdate( + { _id: myproduct._id }, + { $set: { scraped: true, scraped_error: true } }, + { upsert: true, new: true, includeResultMetadata: true } + ).lean(); - const data = await this.extractData(myproduct, html); + return null; + } + const html = res.html; + if (!html) return null; - if (!options?.update) return data; + let updated = null; + let risupdate = null; - const arrvariazioni = myproduct.arrvariazioni || []; - let index = -1; + const data = await this.extractData(myproduct, html, res.url); - if (arrvariazioni.length === 1) { - index = 0; - } else { - index = arrvariazioni.findIndex((v) => v.versione === shared_consts.PRODUCTTYPE.NUOVO); - if (index < 0) index = 0; + if (!options?.update) return data; + + let recModificato = {}; + + const arrvariazioni = myproduct.arrvariazioni || []; + let index = -1; + + if (arrvariazioni.length === 1) { + index = 0; + } else { + index = arrvariazioni.findIndex((v) => v.versione === shared_consts.PRODUCTTYPE.NUOVO); + if (index < 0) index = 0; + } + + const productInfo = {}; + let aggiornaDataPubb = false; + + let aggiornaPages = false; + let aggiornaMisure = false; + let aggiornaEdizione = false; + + let aggiornaProductInfo = false; + let aggiornaSottotitolo = false; + + if (index !== -1) { + const variante = arrvariazioni[index]; + + // Determina se aggiornare pagine + aggiornaPages = (!options.aggiornasoloSeVuoti || !variante.pagine || variante.pagine === 0) && data.numpagine; + if (aggiornaPages) { + variante.pagine = Number(data.numpagine); + recModificato['pagine'] = variante.pagine; + } + + // Determina se aggiornare misure + aggiornaMisure = (!options.aggiornasoloSeVuoti || !variante.misure) && data.misure; + if (aggiornaMisure) { + variante.misure = data.misure; + recModificato['misure'] = variante.misure; + } + + // Determina se aggiornare edizione + aggiornaEdizione = (!options.aggiornasoloSeVuoti || !variante.edizione) && data.edizione; + if (aggiornaEdizione) { + variante.edizione = data.edizione; + recModificato['edizione'] = variante.edizione; + } + } + + // Determina se aggiornare data pubblicazione + const currentDatePub = myproduct.idProductInfo.date_pub; + aggiornaDataPubb = + (!options.aggiornasoloSeVuoti || !tools.isDateValid(currentDatePub)) && + tools.isDateValid(data.data_pubblicazione); + if (aggiornaDataPubb && data.data_pubblicazione) { + productInfo.date_pub = new Date(data.data_pubblicazione); + } + + aggiornaSottotitolo = (!options.aggiornasoloSeVuoti || !myproduct.idProductInfo.sottotitolo) && data.sottotitolo; + if (aggiornaSottotitolo && data.sottotitolo) { + productInfo.sottotitolo = data.sottotitolo; + } + + aggiornaSottotitolo = false; // !! PER ORA LO DISATTIVO PERCHE' non esiste sempre il sottotitolo in un libro. + + // Aggiorna arrvariazioni se pagine o misure sono cambiati + const aggiornadati = aggiornaPages || aggiornaMisure || aggiornaEdizione; + + aggiornaProductInfo = aggiornaDataPubb || aggiornaSottotitolo; + + if (aggiornadati) { + updated = await Product.findOneAndUpdate( + { _id: myproduct._id }, + { $set: { arrvariazioni, scraped: true, scraped_updated: true, scraped_date: new Date() } }, + { upsert: true, new: true, includeResultMetadata: true } + ); + } else if (aggiornaProductInfo) { + if (!tools.isObjectEmpty(productInfo)) { + // Aggiorna il flag che ho modificato i dati + updated = await Product.findOneAndUpdate( + { _id: myproduct._id }, + { $set: { scraped: true, scraped_updated: true, scraped_date: new Date() } }, + { upsert: true, new: true, includeResultMetadata: true } + ); + } + } + if (!updated) { + const upd = await Product.findOneAndUpdate( + { _id: myproduct._id }, + { $set: { scraped: true, scraped_date: new Date() } }, + { upsert: true, new: true, returnDocument: 'after' } + ); + console.log('upd', upd); + } + + if (aggiornaProductInfo) { + // Aggiorna productInfo se contiene dati + if (!tools.isObjectEmpty(productInfo)) { + risupdate = await ProductInfo.findOneAndUpdate( + { _id: myproduct.idProductInfo }, + { $set: productInfo }, + { new: true, upsert: true, includeResultMetadata: true } + ).lean(); + } + // console.log('risupdate', risupdate); + } + + const concatenatedProduct = { + ...recModificato, + ...productInfo, + }; + + if (updated) { + console.log(' DATI AGGIORNATI:', JSON.stringify(concatenatedProduct)); + } + + return { data, updated: this.isRecordAggiornato(updated) || this.isRecordAggiornato(risupdate) }; + } catch (error) { + console.error('Errore in scrapeISBN:', error?.message); + return { data: null, updated: false, error: 'Errore in scrapeISBN:' + error?.message }; } - - const productInfo = {}; - let aggiornaDataPubb = false; - - let aggiornaPages = false; - let aggiornaMisure = false; - let aggiornaEdizione = false; - - if (index !== -1) { - const variante = arrvariazioni[index]; - - // Determina se aggiornare pagine - aggiornaPages = !options.aggiornasoloSeVuoti || !variante.pagine || variante.pagine === 0; - if (aggiornaPages) variante.pagine = Number(data.numpagine); - - // Determina se aggiornare misure - aggiornaMisure = !options.aggiornasoloSeVuoti || !variante.misure; - if (aggiornaMisure) variante.misure = data.misure; - - // Determina se aggiornare edizione - aggiornaEdizione = !options.aggiornasoloSeVuoti || !variante.edizione; - if (aggiornaEdizione) variante.edizione = data.edizione; - } - - // Determina se aggiornare data pubblicazione - const currentDatePub = productInfo.date_pub; - aggiornaDataPubb = !options.aggiornasoloSeVuoti || !tools.isDateValid(currentDatePub); - if (aggiornaDataPubb && data.data_pubblicazione) { - productInfo.date_pub = new Date(data.data_pubblicazione); - } - - // Aggiorna arrvariazioni se pagine o misure sono cambiati - const aggiornadati = aggiornaPages || aggiornaMisure || aggiornaEdizione; - - if (aggiornadati) { - await Product.findOneAndUpdate( - { _id: myproduct._id }, - { $set: { arrvariazioni, scraped: true, scraped_date: new Date() } }, - { upsert: true, new: true, includeResultMetadata: true } - ); - } - - // Aggiorna productInfo se contiene dati - if (!tools.isObjectEmpty(productInfo)) { - const risupdate = await ProductInfo.findOneAndUpdate( - { _id: myproduct.idProductInfo }, - { $set: productInfo, scraped: true, scraped_date: new Date() }, - { new: true, upsert: true, returnOriginal: false } - ).lean(); - console.log('risupdate', risupdate) ; - } - - return data; } - async scrapeMultiple(isbnList, options) { - const results = []; - for (const isbn of isbnList) { - console.log(`Scraping ISBN: ${isbn}`); - const myproduct = null; - /// myproduct... - const data = await this.scrapeISBN(myproduct, isbn, options); - results.push({ isbn, ...data }); - // Per evitare blocchi, metti una pausa (es. 2 secondi) - await new Promise((r) => setTimeout(r, 2000)); + isRecordAggiornato(updatedDoc) { + try { + if (updatedDoc) { + const wasUpserted = updatedDoc.lastErrorObject.upserted !== undefined; + return updatedDoc.lastErrorObject.n === 1 && !wasUpserted; + } else { + return false; + } + } catch (e) { + console.log('error isRecordAggiornato', e); + return false; } + } + + numeroValido(num) { + return !isNaN(num) && num !== null && num !== '' && num > 0; + } + + datiMancanti(product) { + let datimancanti = false; + + if (product.arrvariazioni?.length > 0) { + const arrvar = product.arrvariazioni[0]; + if (!this.numeroValido(arrvar.pagine)) { + datimancanti = true; + } + if (!arrvar.misure) { + datimancanti = true; + } + if (!arrvar.edizione) { + datimancanti = true; + } + } + + if (product.idProductInfo) { + if (!tools.isDateValid(product.idProductInfo.date_pub)) datimancanti = true; + } + + return datimancanti; + } + + getRemainingTimeToTheEnd(dataorainizio, index, numrecord) { + // calcola il tempo stimato rimanente (ore e minuti), tenendo conto che sono arrivato a index, e devo raggiongere "numrecord", e sono partito alla data "dataorainizio" + const differenza = ((new Date().getTime() - dataorainizio.getTime()) / (index + 1)) * (numrecord - index); + + // Se la differenza è negativa, restituisce 0 + if (differenza <= 0) { + return 'COMPLETATO !'; + } + + // Calcola ore, minuti, secondi rimanenti + const ore = Math.floor(differenza / (1000 * 60 * 60)); + const minuti = Math.floor((differenza % (1000 * 60 * 60)) / (1000 * 60)); + + // Restituisci il tempo rimanente in formato ore:minuti:secondi + return `Stimato: ${ore} ore e ${minuti} min`; + } + + includiNelControlloIlRecProduct(product) { + return product.idProductInfo && [1, 4, 34, 45, 46].includes(product.idProductInfo.idStatoProdotto); + } + + async scrapeMultiple(products, options) { + const results = []; + let quanti = 0; + let mylog = ''; + console.log(`scrapeMultiple INIZIATO...`); + let dataorainizio = new Date(); + + for (let i = 0; i < 100 && i < products.length; i++) { + const product = products[i]; + let isbn = product.isbn; + + if (this.includiNelControlloIlRecProduct(product)) { + if (this.datiMancanti(product)) { + // console.log(`${quanti} / ${products.length} - Scraping: ${product.idProductInfo.name}`); + const data = await this.scrapeISBN(product, isbn, options); + + if (data?.updated) { + results.push({ isbn, ...data }); + quanti++; + } + + if (i % 1 === 0) { + const percentuale = ((quanti / products.length) * 100).toFixed(2); + console.log( + `Scraping: ${product.isbn} - ${product.idProductInfo.name} - ${quanti} su ${i + 1} / ${ + products.length + } - [${percentuale}%] - ${this.getRemainingTimeToTheEnd(dataorainizio, i, products.length)}` + ); + } + + // Per evitare blocchi, metti una pausa (es. 2 secondi) + await new Promise((r) => setTimeout(r, 3000)); + } + } + } + mylog += `RECORD AGGIORNATI: ${results.length - 1} su ${quanti}`; return results; } @@ -220,30 +382,238 @@ class AmazonBookScraper { return html; } - async ScraperDataAmazon(idapp, options) { + static async ScraperAzzeraFlagProducts(idapp, options) { + // aggiorna tutti i record di Product (con idapp) scraped: false + + await Product.updateMany({ idapp, scraped: true }, { $set: { scraped: false } }); + await Product.updateMany({ idapp, scraped_updated: true }, { $set: { scraped_updated: false } }); + } + + static async removeDuplicateVariations(idapp, options) { + let mylog = 'removeDuplicateVariations...\n'; + + // Fase 1: Troviamo i documenti che hanno almeno due elementi in arrvariazioni, + // uno con `versione` e uno senza. + const result = await Product.aggregate([ + { $match: { idapp } }, // Seleziona il prodotto in base a idapp + { + $unwind: '$arrvariazioni', // Esplodi l'array `arrvariazioni` in documenti separati + }, + { + $group: { + _id: '$_id', // Gruppo per _id del prodotto + arrvariazioni: { $push: '$arrvariazioni' }, // Ricostruisci l'array arrvariazioni + // Trova se c'è almeno un elemento con `versione` e uno senza + hasVersione: { + $sum: { $cond: [{ $ifNull: ['$arrvariazioni.versione', false] }, 1, 0] }, + }, + }, + }, + { + $match: { + hasVersione: { $gt: 0 }, // Se c'è almeno un record con `versione` + }, + }, + ]); + + // Ora possiamo rimuovere i duplicati + for (let doc of result) { + // Filtra gli oggetti dentro `arrvariazioni` per mantenere quelli con versione + const arrvariazioniWithVersione = doc.arrvariazioni.filter((item) => item.versione); + + // Rimuovi gli elementi che non hanno versione ma hanno gli stessi altri campi + const cleanedArr = arrvariazioniWithVersione.filter( + (item, index, self) => + index === + self.findIndex( + (t) => + t.active === item.active && + t.status === item.status && + t.price === item.price && + t.sale_price === item.sale_price && + t.quantita === item.quantita && + t.pagine === item.pagine && + t.misure === item.misure && + t.edizione === item.edizione && + t.ristampa === item.ristampa && + t.formato === item.formato && + t.tipologia === item.tipologia && + t.idTipologia === item.idTipologia && + t.idTipoFormato === item.idTipoFormato && + t.preOrderDate === item.preOrderDate && + t.addtocart_link === item.addtocart_link && + t.eta === item.eta + ) + ); + + if (doc.arrvariazioni.length - cleanedArr.length > 0) { + const logtemp = `Elaborato ${doc._id} con ${arrvariazioniWithVersione.length} elementi\n`; + logtemp += `Rimossi ${doc.arrvariazioni.length - cleanedArr.length} duplicati\n`; + console.log(logtemp); + mylog += logtemp; + + // Aggiorna il documento eliminando i duplicati + await Product.updateOne({ _id: doc._id }, { $set: { arrvariazioni: cleanedArr } }); + } + } + + return { mylog }; + } + + static async queryArrVariazioni(idapp) { + const result = await Product.aggregate([ + { $match: { idapp, 'arrvariazioni.0': { $exists: true }, 'arrvariazioni.1': { $exists: true } } }, + { $project: { arrvariazioni: 1, _id: 0 } }, + ]); + console.log('result', result); + } + + static async ScraperGeneraCSV(idapp, options, res) { + // Dichiara le intestazioni del CSV + const headers = ['isbn', 'titolo', 'pagine', 'misure', 'edizione', 'date_pub' /*'sottotitolo'*/]; + + try { + // Trova i prodotti e popula 'idProductInfo' + const products = await Product.find({ idapp, scraped_updated: true }) + .populate({ path: 'idProductInfo', select: 'date_pub name sottotitolo' }) + .lean(); + + + // Funzione per "appiattire" i dati + const flattenData = (data) => { + return data.map((item) => { + const flattened = { ...item }; + + // Se arrvariazioni esiste, prendi solo il primo elemento o elabora come richiesto + if (item.arrvariazioni && item.arrvariazioni.length > 0) { + const variation = item.arrvariazioni[0]; // Usa il primo elemento o modifica se necessario + flattened.pagine = variation.pagine || ''; // Usa '' se pagine non esiste + flattened.misure = variation.misure || ''; + flattened.edizione = variation.edizione || ''; + flattened.ristampa = variation.ristampa || ''; + } + + // Assicurati che 'idProductInfo' esista prima di usarlo + flattened.date_pub = item.idProductInfo ? item.idProductInfo.date_pub : ''; + flattened.titolo = item.idProductInfo ? item.idProductInfo.name : ''; + // flattened.sottotitolo = item.idProductInfo ? item.idProductInfo.sottotitolo : ''; + + return flattened; + }); + }; + + // Appiattisci i dati + const records = flattenData(products); + + // Prepara le righe del CSV + const rows = records.map((item) => { + // Se 'date_pub' è valido, convertilo in formato data, altrimenti metti una stringa vuota + const formattedDate = item.date_pub + ? item.date_pub.toLocaleDateString('it-IT', { year: 'numeric', month: '2-digit', day: '2-digit' }) + : ''; + return [ + item.isbn || '', // Assicurati che ISBN sia sempre una stringa, anche vuota + item.titolo || '', + //item.sottotitolo || '', + item.pagine || '', // Gestisci il caso in cui 'pagine' non esiste + item.misure || '', + item.edizione || '', + formattedDate, // La data formattata + ]; + }); + + // Aggiungi l'intestazione al CSV + rows.unshift(headers); + + // Unisci tutte le righe con il delimitatore "|" + const csvData = rows.map((row) => row.join('|')).join('\n'); + + // Scrivi il file CSV in modo asincrono + // Ritorna la stringa CSV come oggetto per eventuali elaborazioni future + return { data: csvData }; + } catch (e) { + console.error('Error in ScraperGeneraCSV:', e); + return { error: e.message }; + } + } + + static async ScraperDataAmazon(idapp, options) { const scraper = new AmazonBookScraper(); const isbn = options.isbn; try { const myproduct = await Product.getProductByIsbn(isbn); - const data = await scraper.scrapeISBN(myproduct, isbn, options); + const ris = await scraper.scrapeISBN(myproduct, isbn, options); - // let html = this.generateHtmlTableFromObject(data); - - console.log(data); - return res.status(200).send({ code: server_constants.RIS_CODE_OK, data, html }); + console.log(ris?.data); + return res.status(200).send({ code: server_constants.RIS_CODE_OK, data: ris?.data, html }); } catch (e) { console.error(e); return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: '' }); } } - async ScraperMultipleDataAmazon(idapp, options) { + static async ScraperMultipleDataAmazon(idapp, options) { const scraper = new AmazonBookScraper(); - const isbnList = ['8850224248']; // metti i tuoi ISBN qui try { - const books = await scraper.scrapeMultiple(isbnList); + // Prendi solo quelli che non sono ancora stati scraped ! + const products = await Product.aggregate([ + // Filtro di base sui campi idapp, isbn, scraped, e scraped_error + { + $match: { + idapp, + isbn: { $exists: true, $ne: '' }, + scraped: { $ne: true }, // Escludi direttamente i record con scraped = true + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + $or: [{ scraped_error: { $exists: false } }, { scraped_error: { $exists: true, $eq: false } }], + }, + }, + // Popoliamo il campo idProductInfo + { + $lookup: { + from: 'productinfos', // Nome della collezione per 'idProductInfo' + localField: 'idProductInfo', // Campo del documento corrente (Product) + foreignField: '_id', // Campo di riferimento in ProductInfo + as: 'idProductInfo', // Campo in cui verranno inseriti i dati popolati + }, + }, + // De-strutturiamo l'array idProductInfo, se è un array + { + $unwind: { + path: '$idProductInfo', + preserveNullAndEmptyArrays: true, // Mantieni i documenti anche se idProductInfo è null o vuoto + }, + }, + { + $match: { + 'idProductInfo.idStatoProdotto': { $in: [1, 4, 34, 45, 46] }, // Condizione su idStatoProdotto + }, + }, + // Proiettiamo solo i campi necessari + { + $project: { + scraped: 1, + scraped_updated: 1, + isbn: 1, + title: 1, + sottotitolo: 1, + arrvariazioni: 1, + 'idProductInfo._id': 1, + 'idProductInfo.date_pub': 1, + 'idProductInfo.name': 1, + 'idProductInfo.sottotitolo': 1, + 'idProductInfo.idStatoProdotto': 1, + 'idProductInfo.link_macro': 1, + 'idProductInfo.imagefile': 1, + }, + }, + // A questo punto, puoi aggiungere altre operazioni di aggregazione se necessario (e.g., ordinamento) + ]); + + // console.log(products); + + const books = await scraper.scrapeMultiple(products, options); console.log(books); } catch (e) { console.error(e); diff --git a/src/server/modules/dist/Cloudflare.dev.js b/src/server/modules/dist/Cloudflare.dev.js new file mode 100644 index 0000000..2209995 --- /dev/null +++ b/src/server/modules/dist/Cloudflare.dev.js @@ -0,0 +1,885 @@ +"use strict"; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var axios = require('axios'); + +var apiUrl = 'https://api.cloudflare.com/client/v4'; // Endpoint + +var MailinaboxClass = require('./Mailinabox.js'); + +var CloudFlare = +/*#__PURE__*/ +function () { + function CloudFlare(config) { + _classCallCheck(this, CloudFlare); + + this.config = config ? config : {}; + + if (!this.config.arrTokens) { + this.config.arrTokens = process.env.CLOUDFLARE_TOKENS; + } + } + + _createClass(CloudFlare, [{ + key: "init", + value: function init() { + if (this.config.arrTokens) { + // this.zones = this.fetchCloudflareZones(this.config.apiToken); + this.zones = []; + this.dnsRecords = null; + } + } + }, { + key: "fetchCloudflareZones", + value: function fetchCloudflareZones(apiToken) { + var response, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, zone, domain; + + return regeneratorRuntime.async(function fetchCloudflareZones$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return regeneratorRuntime.awrap(axios.get(apiUrl + '/zones', { + headers: { + 'Authorization': "Bearer ".concat(apiToken), + // Autenticazione con token + 'Content-Type': 'application/json' // Tipo di contenuto + + } + })); + + case 3: + response = _context.sent; + // Estrai i dati dalla risposta + this.zones = response.data.result; + + if (!(this.zones && this.zones.length > 0)) { + _context.next = 33; + break; + } + + _iteratorNormalCompletion = true; + _didIteratorError = false; + _iteratorError = undefined; + _context.prev = 9; + _iterator = this.zones[Symbol.iterator](); + + case 11: + if (_iteratorNormalCompletion = (_step = _iterator.next()).done) { + _context.next = 19; + break; + } + + zone = _step.value; + domain = zone.name; + _context.next = 16; + return regeneratorRuntime.awrap(this.findAndUpdateOnSite(domain, zone, apiToken)); + + case 16: + _iteratorNormalCompletion = true; + _context.next = 11; + break; + + case 19: + _context.next = 25; + break; + + case 21: + _context.prev = 21; + _context.t0 = _context["catch"](9); + _didIteratorError = true; + _iteratorError = _context.t0; + + case 25: + _context.prev = 25; + _context.prev = 26; + + if (!_iteratorNormalCompletion && _iterator["return"] != null) { + _iterator["return"](); + } + + case 28: + _context.prev = 28; + + if (!_didIteratorError) { + _context.next = 31; + break; + } + + throw _iteratorError; + + case 31: + return _context.finish(28); + + case 32: + return _context.finish(25); + + case 33: + return _context.abrupt("return", this.zones); + + case 36: + _context.prev = 36; + _context.t1 = _context["catch"](0); + console.error('Errore durante il recupero delle zone di Cloudflare:', _context.t1.message); + + case 39: + case "end": + return _context.stop(); + } + } + }, null, this, [[0, 36], [9, 21, 25, 33], [26,, 28, 32]]); + } + }, { + key: "findAndUpdateOnSite", + value: function findAndUpdateOnSite(domain, zone, apiToken) { + var Site, normalizedDomain, recsite, modif, miab, dkim; + return regeneratorRuntime.async(function findAndUpdateOnSite$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.prev = 0; + Site = require('../models/site'); + domain = domain.replace(/^https?:\/\//, ''); + normalizedDomain = domain.startsWith("http://") || domain.startsWith("https://") ? domain : "https://" + domain; // Trova il sito usando il dominio normalizzato + + _context2.next = 6; + return regeneratorRuntime.awrap(Site.findOne({ + host: normalizedDomain + })); + + case 6: + recsite = _context2.sent; + + if (!recsite) { + _context2.next = 21; + break; + } + + // Aggiorna i parametri token e zoneId + modif = recsite.cf_token !== apiToken || recsite.cf_zoneId !== zone.id; + + if (!(modif && apiToken)) { + _context2.next = 12; + break; + } + + _context2.next = 12; + return regeneratorRuntime.awrap(Site.findOneAndUpdate({ + _id: recsite._id + }, { + $set: { + cf_token: apiToken, + cf_zoneId: zone.id + } + }, { + "new": true + }).then(function (updatedSite) { + console.log('Site aggiornato:', updatedSite); + })["catch"](function (error) { + console.error('Errore durante l\'aggiornamento del Site:', error); + })); + + case 12: + if (!(recsite.enable_servermail && !recsite.dkim)) { + _context2.next = 21; + break; + } + + miab = new MailinaboxClass(null); + miab.init(); + _context2.next = 17; + return regeneratorRuntime.awrap(miab.getDKIMRecord(recsite.host.replace(/^https?:\/\//, ''))); + + case 17: + dkim = _context2.sent; + + if (!dkim) { + _context2.next = 21; + break; + } + + _context2.next = 21; + return regeneratorRuntime.awrap(Site.findOneAndUpdate({ + _id: recsite._id + }, { + $set: { + dkim: dkim + } + })); + + case 21: + _context2.next = 26; + break; + + case 23: + _context2.prev = 23; + _context2.t0 = _context2["catch"](0); + console.error('Errore durante il recupero dei record DNS di Cloudflare:', _context2.t0.message); + + case 26: + case "end": + return _context2.stop(); + } + } + }, null, null, [[0, 23]]); + } // Funzione per estrarre i record DNS + + }, { + key: "fetchDNSRecords", + value: function fetchDNSRecords(apiToken, zoneId) { + var apiUrlDNS, response; + return regeneratorRuntime.async(function fetchDNSRecords$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + apiUrlDNS = apiUrl + "/zones/".concat(zoneId, "/dns_records"); + _context3.prev = 1; + _context3.next = 4; + return regeneratorRuntime.awrap(axios.get(apiUrlDNS, { + headers: { + 'Authorization': "Bearer ".concat(apiToken), + // Autenticazione con token + 'Content-Type': 'application/json' // Tipo di contenuto + + } + })); + + case 4: + response = _context3.sent; + this.dnsRecords = response.data.result; + return _context3.abrupt("return", this.dnsRecords); + + case 9: + _context3.prev = 9; + _context3.t0 = _context3["catch"](1); + console.error('Errore durante il recupero dei record DNS di Cloudflare:', _context3.t0.message); + + case 12: + case "end": + return _context3.stop(); + } + } + }, null, this, [[1, 9]]); + } // Funzione per aggiornare un record DNS + + }, { + key: "updateDNSRecord", + value: function updateDNSRecord(apiToken, zoneId, dnsRecordId, newDnsRecordData) { + var apiUrlDNS, response, updatedRecord; + return regeneratorRuntime.async(function updateDNSRecord$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + apiUrlDNS = apiUrl + "/zones/".concat(zoneId, "/dns_records/").concat(dnsRecordId); + _context4.prev = 1; + _context4.next = 4; + return regeneratorRuntime.awrap(axios.put(apiUrlDNS, newDnsRecordData, { + headers: { + 'Authorization': "Bearer ".concat(apiToken), + // Autenticazione con token + 'Content-Type': 'application/json' // Tipo di contenuto + + } + })); + + case 4: + response = _context4.sent; + updatedRecord = response.data.result; // Stampa il record DNS aggiornato + + console.log('Record DNS aggiornato:', updatedRecord); + return _context4.abrupt("return", updatedRecord); + + case 10: + _context4.prev = 10; + _context4.t0 = _context4["catch"](1); + console.error('Errore durante l\'aggiornamento del record DNS:', _context4.t0.message); + + case 13: + case "end": + return _context4.stop(); + } + } + }, null, null, [[1, 10]]); + } // Funzione per creare un record DNS di CloudFlare + + }, { + key: "createDNSRecord", + value: function createDNSRecord(apiToken, zoneId, dnsRecordData) { + var apiUrlDNS, response, createdRecord; + return regeneratorRuntime.async(function createDNSRecord$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + apiUrlDNS = apiUrl + "/zones/".concat(zoneId, "/dns_records"); + _context5.prev = 1; + _context5.next = 4; + return regeneratorRuntime.awrap(axios.post(apiUrlDNS, dnsRecordData, { + headers: { + 'Authorization': "Bearer ".concat(apiToken), + // Autenticazione con token + 'Content-Type': 'application/json' // Tipo di contenuto + + } + })); + + case 4: + response = _context5.sent; + createdRecord = response.data.result; + console.log('Record DNS creato:', createdRecord); + return _context5.abrupt("return", createdRecord); + + case 10: + _context5.prev = 10; + _context5.t0 = _context5["catch"](1); + console.error('Errore durante la creazione del record DNS:', _context5.t0.message); + + case 13: + case "end": + return _context5.stop(); + } + } + }, null, null, [[1, 10]]); + } // Funzione per cancellare un record DNS di CloudFlare + + }, { + key: "deleteDNSRecord", + value: function deleteDNSRecord(apiToken, zoneId, dnsRecordId) { + var apiUrlDNS, response, deletedRecord; + return regeneratorRuntime.async(function deleteDNSRecord$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + apiUrlDNS = apiUrl + "/zones/".concat(zoneId, "/dns_records/").concat(dnsRecordId); + _context6.prev = 1; + _context6.next = 4; + return regeneratorRuntime.awrap(axios["delete"](apiUrlDNS, { + headers: { + 'Authorization': "Bearer ".concat(apiToken), + // Autenticazione con token + 'Content-Type': 'application/json' // Tipo di contenuto + + } + })); + + case 4: + response = _context6.sent; + deletedRecord = response.data.result; + console.log('Record DNS cancellato:', deletedRecord); + return _context6.abrupt("return", deletedRecord); + + case 10: + _context6.prev = 10; + _context6.t0 = _context6["catch"](1); + console.error('Errore durante la cancellazione del record DNS:', _context6.t0.message); + + case 13: + case "end": + return _context6.stop(); + } + } + }, null, null, [[1, 10]]); + } + }, { + key: "setCorrectIpsOnDNS", + value: function setCorrectIpsOnDNS(domainrec) { + var arrparams, i; + return regeneratorRuntime.async(function setCorrectIpsOnDNS$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + arrparams = [{ + urladd: '', + paramsite: 'host_ip', + type: 'A' + }, { + urladd: 'test.', + paramsite: 'host_test_ip', + type: 'A' + }, { + urladd: 'api.', + paramsite: 'host_api_ip', + type: 'A' + }, { + urladd: 'testapi.', + paramsite: 'host_testapi_ip', + type: 'A' + }, { + urladd: 'www.', + paramsite: 'host', + type: 'CNAME' + }]; + i = 0; + + case 2: + if (!(i < arrparams.length)) { + _context7.next = 8; + break; + } + + _context7.next = 5; + return regeneratorRuntime.awrap(this.setSingleIpsOnDNS(domainrec.name, arrparams[i])); + + case 5: + i++; + _context7.next = 2; + break; + + case 8: + _context7.next = 10; + return regeneratorRuntime.awrap(this.setServerMail(domainrec)); + + case 10: + _context7.next = 12; + return regeneratorRuntime.awrap(new Promise(function (resolve) { + return setTimeout(resolve, 3000); + })); + + case 12: + case "end": + return _context7.stop(); + } + } + }, null, this); + } + }, { + key: "setServerMail", + value: function setServerMail(domainrec) { + var _this = this; + + var Site, domain, normalizedDomain; + return regeneratorRuntime.async(function setServerMail$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.prev = 0; + // get the parameters (Token and zoneId on Database) + Site = require('../models/site'); + domain = domainrec.name.replace(/^https?:\/\//, ''); + normalizedDomain = domain.startsWith("http://") || domain.startsWith("https://") ? domain : "https://" + domain; // Trova il sito usando il dominio normalizzato + + _context9.next = 6; + return regeneratorRuntime.awrap(Site.findOne({ + host: normalizedDomain + }).lean().then(function _callee(site) { + var myarrrecdns, recTypeMX, newRecord, recTypeTXTspf1, contentTXTspf1, _newRecord, nameDkimtoFind, recTypeTXTDKIM, contentTXTDKIM, _newRecord2, nameDmarctoFind, recTypeTXTdmarc, contentTXTdmarc, _newRecord3, myType, strfind, contentExpected, rectofind, _newRecord4, _newRecord5; + + return regeneratorRuntime.async(function _callee$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + if (!site) { + _context8.next = 91; + break; + } + + if (!(site.cf_token && site.cf_zoneId)) { + _context8.next = 91; + break; + } + + _context8.next = 4; + return regeneratorRuntime.awrap(_this.fetchDNSRecords(site.cf_token, site.cf_zoneId)); + + case 4: + myarrrecdns = _context8.sent; + _context8.next = 7; + return regeneratorRuntime.awrap(myarrrecdns.find(function (rec) { + return rec.type === 'MX' && rec.name === domain; + })); + + case 7: + recTypeMX = _context8.sent; + + if (!recTypeMX) { + _context8.next = 14; + break; + } + + if (!(recTypeMX.content !== site.servermail)) { + _context8.next = 12; + break; + } + + recTypeMX.content = site.servermail; + return _context8.abrupt("return", _this.updateDNSRecord(site.cf_token, site.cf_zoneId, recTypeMX.id, recTypeMX)); + + case 12: + _context8.next = 17; + break; + + case 14: + // create a new record + newRecord = { + type: 'MX', + name: domain, + content: site.servermail, + ttl: 1, + proxied: false, + priority: 10 + }; + _context8.next = 17; + return regeneratorRuntime.awrap(_this.createDNSRecord(site.cf_token, site.cf_zoneId, newRecord)); + + case 17: + _context8.next = 19; + return regeneratorRuntime.awrap(myarrrecdns.find(function (rec) { + return rec.type === 'TXT' && rec.name === domain && rec.content.indexOf('v=spf1') > -1; + })); + + case 19: + recTypeTXTspf1 = _context8.sent; + + if (!site.servermailip) { + _context8.next = 31; + break; + } + + contentTXTspf1 = "v=spf1 a mx:".concat(site.servermail, " ip4:").concat(site.servermailip, " ~all"); + + if (!recTypeTXTspf1) { + _context8.next = 28; + break; + } + + if (!(recTypeTXTspf1.content !== contentTXTspf1)) { + _context8.next = 26; + break; + } + + recTypeTXTspf1.content = contentTXTspf1; + return _context8.abrupt("return", _this.updateDNSRecord(site.cf_token, site.cf_zoneId, recTypeTXTspf1.id, recTypeTXTspf1)); + + case 26: + _context8.next = 31; + break; + + case 28: + // create a new record + _newRecord = { + type: 'TXT', + name: domain, + content: contentTXTspf1, + ttl: 3600 + }; + _context8.next = 31; + return regeneratorRuntime.awrap(_this.createDNSRecord(site.cf_token, site.cf_zoneId, _newRecord)); + + case 31: + // mail._domainkey.nomedominio v=DKIM1; h=sha256; k=rsa; s=email; p= + nameDkimtoFind = "mail._domainkey.".concat(domain); + _context8.next = 34; + return regeneratorRuntime.awrap(myarrrecdns.find(function (rec) { + return rec.type === 'TXT' && rec.name === nameDkimtoFind; + })); + + case 34: + recTypeTXTDKIM = _context8.sent; + + if (!site.dkim) { + _context8.next = 46; + break; + } + + contentTXTDKIM = "v=DKIM1; h=sha256; k=rsa; s=email; p=".concat(site.dkim); + + if (!recTypeTXTDKIM) { + _context8.next = 43; + break; + } + + if (!(recTypeTXTDKIM.content !== contentTXTDKIM)) { + _context8.next = 41; + break; + } + + recTypeTXTDKIM.content = contentTXTDKIM; + return _context8.abrupt("return", _this.updateDNSRecord(site.cf_token, site.cf_zoneId, recTypeTXTDKIM.id, recTypeTXTDKIM)); + + case 41: + _context8.next = 46; + break; + + case 43: + // create a new record + _newRecord2 = { + type: 'TXT', + name: nameDkimtoFind, + content: contentTXTDKIM, + ttl: 1 + }; + _context8.next = 46; + return regeneratorRuntime.awrap(_this.createDNSRecord(site.cf_token, site.cf_zoneId, _newRecord2)); + + case 46: + // DMARC: + nameDmarctoFind = "_dmarc.".concat(domain); + _context8.next = 49; + return regeneratorRuntime.awrap(myarrrecdns.find(function (rec) { + return rec.type === 'TXT' && rec.name === nameDmarctoFind && rec.content.indexOf('v=DMARC1') > -1; + })); + + case 49: + recTypeTXTdmarc = _context8.sent; + + if (!site.servermailip) { + _context8.next = 61; + break; + } + + contentTXTdmarc = "v=DMARC1; p=quarantine; ruf=mailto:dmarc@".concat(domain, ";"); + + if (!recTypeTXTdmarc) { + _context8.next = 58; + break; + } + + if (!(recTypeTXTdmarc.content !== contentTXTdmarc)) { + _context8.next = 56; + break; + } + + recTypeTXTdmarc.content = contentTXTdmarc; + return _context8.abrupt("return", _this.updateDNSRecord(site.cf_token, site.cf_zoneId, recTypeTXTspf1.id, recTypeTXTspf1)); + + case 56: + _context8.next = 61; + break; + + case 58: + // create a new record + _newRecord3 = { + type: 'TXT', + name: nameDmarctoFind, + content: contentTXTdmarc, + ttl: 1 + }; + _context8.next = 61; + return regeneratorRuntime.awrap(_this.createDNSRecord(site.cf_token, site.cf_zoneId, _newRecord3)); + + case 61: + // AutoConfig: + myType = 'CNAME'; + strfind = "autoconfig.".concat(domain); + contentExpected = site.servermail; + _context8.next = 66; + return regeneratorRuntime.awrap(myarrrecdns.find(function (rec) { + return rec.type === 'CNAME' && rec.name === strfind; + })); + + case 66: + rectofind = _context8.sent; + + if (!rectofind) { + _context8.next = 73; + break; + } + + if (!(rectofind.content !== contentExpected)) { + _context8.next = 71; + break; + } + + rectofind.content = contentExpected; + return _context8.abrupt("return", _this.updateDNSRecord(site.cf_token, site.cf_zoneId, rectofind.id, rectofind)); + + case 71: + _context8.next = 76; + break; + + case 73: + // create a new record + _newRecord4 = { + type: myType, + name: strfind, + content: contentExpected, + ttl: 1 + }; + _context8.next = 76; + return regeneratorRuntime.awrap(_this.createDNSRecord(site.cf_token, site.cf_zoneId, _newRecord4)); + + case 76: + // AutoDiscover: + myType = 'CNAME'; + strfind = "autodiscover.".concat(domain); + contentExpected = site.servermail; + _context8.next = 81; + return regeneratorRuntime.awrap(myarrrecdns.find(function (rec) { + return rec.type === 'CNAME' && rec.name === strfind; + })); + + case 81: + rectofind = _context8.sent; + + if (!rectofind) { + _context8.next = 88; + break; + } + + if (!(rectofind.content !== contentExpected)) { + _context8.next = 86; + break; + } + + rectofind.content = contentExpected; + return _context8.abrupt("return", _this.updateDNSRecord(site.cf_token, site.cf_zoneId, rectofind.id, rectofind)); + + case 86: + _context8.next = 91; + break; + + case 88: + // create a new record + _newRecord5 = { + type: myType, + name: strfind, + content: contentExpected, + ttl: 1 + }; + _context8.next = 91; + return regeneratorRuntime.awrap(_this.createDNSRecord(site.cf_token, site.cf_zoneId, _newRecord5)); + + case 91: + case "end": + return _context8.stop(); + } + } + }); + })); + + case 6: + _context9.next = 11; + break; + + case 8: + _context9.prev = 8; + _context9.t0 = _context9["catch"](0); + console.error('e', _context9.t0); + + case 11: + case "end": + return _context9.stop(); + } + } + }, null, null, [[0, 8]]); + } + }, { + key: "setSingleIpsOnDNS", + value: function setSingleIpsOnDNS(domain, paramobj) { + var _this2 = this; + + var Site, normalizedDomain; + return regeneratorRuntime.async(function setSingleIpsOnDNS$(_context11) { + while (1) { + switch (_context11.prev = _context11.next) { + case 0: + _context11.prev = 0; + // get the parameters (Token and zoneId on Database) + Site = require('../models/site'); + domain = domain.replace(/^https?:\/\//, ''); + normalizedDomain = domain.startsWith("http://") || domain.startsWith("https://") ? domain : "https://" + domain; // Trova il sito usando il dominio normalizzato + + _context11.next = 6; + return regeneratorRuntime.awrap(Site.findOne({ + host: normalizedDomain + }).lean().then(function _callee2(site) { + var myarrrecdns, nametofind, recType, paramexpected, newRecord; + return regeneratorRuntime.async(function _callee2$(_context10) { + while (1) { + switch (_context10.prev = _context10.next) { + case 0: + if (!site) { + _context10.next = 20; + break; + } + + if (!(site.cf_token && site.cf_zoneId)) { + _context10.next = 20; + break; + } + + _context10.next = 4; + return regeneratorRuntime.awrap(_this2.fetchDNSRecords(site.cf_token, site.cf_zoneId)); + + case 4: + myarrrecdns = _context10.sent; + nametofind = paramobj.urladd + domain; // find + + _context10.next = 8; + return regeneratorRuntime.awrap(myarrrecdns.find(function (rec) { + return rec.type === paramobj.type && rec.name === nametofind; + })); + + case 8: + recType = _context10.sent; + paramexpected = ''; + + try { + paramexpected = site[paramobj.paramsite].replace(/^https?:\/\//, ''); + ; + } catch (e) {} + + if (!(recType && paramexpected)) { + _context10.next = 17; + break; + } + + if (!(recType.content !== paramexpected)) { + _context10.next = 15; + break; + } + + recType.content = paramexpected; + return _context10.abrupt("return", _this2.updateDNSRecord(site.cf_token, site.cf_zoneId, recType.id, recType)); + + case 15: + _context10.next = 20; + break; + + case 17: + // create a new record + newRecord = { + type: paramobj.type, + name: nametofind, + content: paramexpected, + ttl: 1, + proxied: true + }; + _context10.next = 20; + return regeneratorRuntime.awrap(_this2.createDNSRecord(site.cf_token, site.cf_zoneId, newRecord)); + + case 20: + case "end": + return _context10.stop(); + } + } + }); + })); + + case 6: + _context11.next = 11; + break; + + case 8: + _context11.prev = 8; + _context11.t0 = _context11["catch"](0); + console.error('e', _context11.t0); + + case 11: + case "end": + return _context11.stop(); + } + } + }, null, null, [[0, 8]]); + } + }]); + + return CloudFlare; +}(); + +module.exports = CloudFlare; \ No newline at end of file diff --git a/src/server/modules/dist/CronMod.dev.js b/src/server/modules/dist/CronMod.dev.js new file mode 100644 index 0000000..a947659 --- /dev/null +++ b/src/server/modules/dist/CronMod.dev.js @@ -0,0 +1,1745 @@ +"use strict"; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var _require = require('../models/user'), + User = _require.User; + +var Hours = require('../models/hours'); + +var _require2 = require('mongodb'), + ObjectId = _require2.ObjectId; + +var tools = require('../tools/general'); + +var shared_consts = require('../tools/shared_nodejs'); + +var server_constants = require('../tools/server_constants'); + +var _require3 = require('../models/settings'), + Settings = _require3.Settings; + +var _require4 = require('../models/bot'), + MyBot = _require4.MyBot; + +var _require5 = require('../models/myelem'), + MyElem = _require5.MyElem; + +var telegrambot = require('../telegram/telegrambot'); + +var Cart = require('../models/cart'); + +var CartClass = require('../modules/Cart'); + +var Product = require('../models/product'); + +var ProductInfo = require('../models/productInfo'); + +var CatProd = require('../models/catprod'); + +var SubCatProd = require('../models/subcatprod'); + +var Order = require('../models/order'); + +var OrdersCart = require('../models/orderscart'); + +var Variant = require('../models/variant'); + +var TypedError = require('../modules/ErrorHandler'); + +var _require6 = require('../models/mygroup'), + MyGroup = _require6.MyGroup; + +var _require7 = require('../models/circuit'), + Circuit = _require7.Circuit; + +var _require8 = require('../models/province'), + Province = _require8.Province; + +var _require9 = require('../models/city'), + City = _require9.City; + +var _require10 = require('../models/account'), + Account = _require10.Account; + +var Macro = require('../modules/Macro'); + +var CronMod = +/*#__PURE__*/ +function () { + function CronMod() { + _classCallCheck(this, CronMod); + } + + _createClass(CronMod, [{ + key: "eseguiDbOp", + value: function eseguiDbOp(idapp, mydata, req, res) { + var ris, populate, globalTables, _require11, Reaction, mystr, macro, _require12, updateAllBook, _require13, _updateAllBook, num, last, ind, myuser, _require14, mssqlmigrateTables, idapporig, idappdest, _globalTables, mytablesstr, numrectot, _i, _mytablesstr, table, mytable, _require15, MyHosp, _require16, Sector, _require17, SectorGood, _require18, Skill, _require19, Good, _require20, _Sector, _require21, _SectorGood, _require22, _Skill, _require23, _Good, _require24, SubSkill, _require25, Contribtype, _require26, AdType, _require27, AdTypeGood, _require28, StatusSkill, _require29, CatGrp, _require30, _City, _require31, _Province, deleteProducts, _deleteProductInfo, deleteCatProd, deleteSubCatProd, deleteOrder, deleteOrdersCart, deleteCart, arrrec, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, rec, _arrrec, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, _rec, arrrec2, _iteratorNormalCompletion3, _didIteratorError3, _iteratorError3, _iterator3, _step3, _rec2, _require32, _City2, _require33, _Province2, _require34, MySkill, _require35, MyBacheca, _require36, _MyHosp, _require37, MyGood, _require38, _MySkill, _require39, _MyBacheca, _require40, _MyHosp2, _require41, _MyGood, _require42, _Province3, arrProv, _iteratorNormalCompletion4, _didIteratorError4, _iteratorError4, _iterator4, _step4, recprov; + + return regeneratorRuntime.async(function eseguiDbOp$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return regeneratorRuntime.awrap(User.DbOp(idapp, mydata)); + + case 2: + ris = _context.sent; + mydata.idapp = idapp; + populate = require("../populate/populate"); + globalTables = require("../tools/globalTables"); + _require11 = require("../models/reaction"), Reaction = _require11.Reaction; + mystr = ""; + _context.prev = 8; + + if (!(mydata.dbop === "")) { + _context.next = 12; + break; + } + + _context.next = 682; + break; + + case 12: + if (!(mydata.dbop === "ScraperDataAmazon")) { + _context.next = 17; + break; + } + + _context.next = 15; + return regeneratorRuntime.awrap(ScraperDataAmazon(idapp, mydata.options)); + + case 15: + _context.next = 682; + break; + + case 17: + if (!(mydata.dbop === "ReplaceAllCircuits")) { + _context.next = 22; + break; + } + + _context.next = 20; + return regeneratorRuntime.awrap(Circuit.replaceAllCircuitNames(idapp)); + + case 20: + _context.next = 682; + break; + + case 22: + if (!(mydata.dbop === "eliminaCatProds")) { + _context.next = 29; + break; + } + + _context.next = 25; + return regeneratorRuntime.awrap(CatProd.deleteMany({ + idapp: idapp + })); + + case 25: + _context.next = 27; + return regeneratorRuntime.awrap(SubCatProd.deleteMany({ + idapp: idapp + })); + + case 27: + _context.next = 682; + break; + + case 29: + if (!(mydata.dbop === "removeProductInfoWithoutDateUpdatedFromGM")) { + _context.next = 36; + break; + } + + _context.next = 32; + return regeneratorRuntime.awrap(ProductInfo.removeProductInfoWithoutDateUpdatedFromGM(idapp)); + + case 32: + mystr = _context.sent; + ris = { + mystr: mystr + }; + _context.next = 682; + break; + + case 36: + if (!(mydata.dbop === "StatMacro")) { + _context.next = 44; + break; + } + + macro = new Macro(idapp, {}); + _context.next = 40; + return regeneratorRuntime.awrap(macro.getStat()); + + case 40: + mystr = _context.sent; + ris = { + mystr: mystr + }; + _context.next = 682; + break; + + case 44: + if (!(mydata.dbop === "updateAllBook")) { + _context.next = 52; + break; + } + + // chiama updateAllBook + _require12 = require("../controllers/articleController"), updateAllBook = _require12.updateAllBook; + _context.next = 48; + return regeneratorRuntime.awrap(updateAllBook(idapp, mydata.options)); + + case 48: + mystr = _context.sent; + ris = { + mystr: mystr + }; + _context.next = 682; + break; + + case 52: + if (!(mydata.dbop === "updateAllBooksAndRemoveCanc")) { + _context.next = 61; + break; + } + + // chiama updateAllBooksAndRemoveCanc + _require13 = require("../controllers/articleController"), _updateAllBook = _require13.updateAllBook; + console.log('updateAllBooksAndRemoveCanc...'); + _context.next = 57; + return regeneratorRuntime.awrap(_updateAllBook(idapp, { + usaDBGMLocale: false, + caricatutti: true, + rimuovieventualiCancellati: true + })); + + case 57: + mystr = _context.sent; + ris = { + mystr: mystr + }; + _context.next = 682; + break; + + case 61: + if (!(mydata.dbop === "creaUtentiTest")) { + _context.next = 95; + break; + } + + num = 0; + _context.next = 65; + return regeneratorRuntime.awrap(User.find({ + idapp: idapp + }).sort({ + _id: -1 + }).limit(1)); + + case 65: + lastrec = _context.sent; + last = 1; + + if (lastrec) { + last = lastrec[0].index; + } + + if (!last) { + last = 1; + } + + ind = 0; + + case 70: + if (!(ind < 100)) { + _context.next = 92; + break; + } + + myuser = new User(); + myuser._id = new ObjectId(); + myuser.index = last + ind + 1; + myuser.idapp = idapp; + myuser.password = "$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG"; + myuser.lang = "it"; + myuser.email = "miaemail@email.it"; + myuser.name = "U" + myuser.index; + myuser.surname = "Ar" + myuser.index; + myuser.verified_email = true; + myuser.verified_by_aportador = true; + if (myuser.index < 2) myuser.perm = "3"; + myuser.username = "Userna_" + myuser.name; + myuser.profile.special_req = true; + myuser.profile.nationality = "IT"; + _context.next = 88; + return regeneratorRuntime.awrap(myuser.save()); + + case 88: + num++; + + case 89: + ind++; + _context.next = 70; + break; + + case 92: + ris = { + num: num + }; + /*} else if (mydata.dbop === 'visuPlacca') { + mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' + + 'NAVI CHE SALPANO DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) + '\n' + + 'AUGURI ALLA NUOVA SOGNATRICE !!!\n' + + '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨'; + const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT'); + for (let ind = 0; ind < 8; ind++) { + mystr += await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col) + ind, false); + mystr += tools.ACAPO; + if (visu_nave_Bot && ind === 3) { + await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); + mystr = ''; + } + } + if (visu_nave_Bot) + await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); + ris = { mystr }; + */ + + _context.next = 682; + break; + + case 95: + if (!(mydata.dbop === "CorreggiTabHours")) { + _context.next = 101; + break; + } + + _context.next = 98; + return regeneratorRuntime.awrap(Hours.correggiHours(idapp)); + + case 98: + ris = _context.sent; + _context.next = 682; + break; + + case 101: + if (!(mydata.dbop === "setVerifiedByAportadorToALL")) { + _context.next = 107; + break; + } + + _context.next = 104; + return regeneratorRuntime.awrap(User.setVerifiedByAportadorToALL()); + + case 104: + ris = _context.sent; + _context.next = 682; + break; + + case 107: + if (!(mydata.dbop === "RewriteContribType")) { + _context.next = 111; + break; + } + + ris = populate.rewriteTable("contribtypes"); + _context.next = 682; + break; + + case 111: + if (!(mydata.dbop === "ReplaceUsername")) { + _context.next = 115; + break; + } + + if (User.isAdmin(req.user.perm)) { + ris = globalTables.replaceUsername(req.body.idapp, mydata.search_username, mydata.replace_username); + } + + _context.next = 682; + break; + + case 115: + if (!(mydata.dbop === "ExitFromAllCircuitWithZero")) { + _context.next = 119; + break; + } + + if (User.isAdmin(req.user.perm)) { + ris = globalTables.ExitFromAllCircuitWithZero(req.body.idapp, mydata.search_username); + } + + _context.next = 682; + break; + + case 119: + if (!(mydata.dbop === "replaceAportadorSolidario")) { + _context.next = 123; + break; + } + + if (User.isAdmin(req.user.perm)) { + ris = globalTables.replaceAportadorSolidario(req.body.idapp, mydata.search_username, mydata.replace_username); + } + + _context.next = 682; + break; + + case 123: + if (!(mydata.dbop === "SearchString")) { + _context.next = 131; + break; + } + + if (!User.isAdmin(req.user.perm)) { + _context.next = 128; + break; + } + + _context.next = 127; + return regeneratorRuntime.awrap(globalTables.SearchString(req.body.idapp, mydata.search)); + + case 127: + mystr = _context.sent; + + case 128: + ris = { + mystr: mystr + }; + _context.next = 682; + break; + + case 131: + if (!(mydata.dbop === "UpdateCatDeleteEmpty")) { + _context.next = 138; + break; + } + + _context.next = 134; + return regeneratorRuntime.awrap(CatProd.updateCatDeleteEmpty(req.body.idapp)); + + case 134: + mystr = _context.sent; + ris = { + mystr: mystr + }; + _context.next = 682; + break; + + case 138: + if (!(mydata.dbop === "UpdateStatFatturato")) { + _context.next = 145; + break; + } + + _context.next = 141; + return regeneratorRuntime.awrap(ProductInfo.updateProductInfoByStats(req.body.idapp)); + + case 141: + mystr = _context.sent; + ris = { + mystr: mystr + }; + _context.next = 682; + break; + + case 145: + if (!(mydata.dbop === "MigrateMSSQLToMongoDb")) { + _context.next = 153; + break; + } + + _require14 = require("../controllers/articleController"), mssqlmigrateTables = _require14.mssqlmigrateTables; + _context.next = 149; + return regeneratorRuntime.awrap(mssqlmigrateTables(req)); + + case 149: + mystr = _context.sent; + ris = { + mystr: mystr + }; + _context.next = 682; + break; + + case 153: + if (!(mydata.dbop === "copyFrom1To14")) { + _context.next = 180; + break; + } + + idapporig = 1; + idappdest = 14; + + if (!(!idapporig || !idappdest)) { + _context.next = 158; + break; + } + + return _context.abrupt("return"); + + case 158: + _globalTables = require("../tools/globalTables"); //++ Todo: TO FIXIT ! + + mytablesstr = ["settings", "users", "templemail", "destnewsletter", "contribtypes", "bots", "cfgservers"]; + _context.prev = 160; + numrectot = 0; + _i = 0, _mytablesstr = mytablesstr; + + case 163: + if (!(_i < _mytablesstr.length)) { + _context.next = 172; + break; + } + + table = _mytablesstr[_i]; + mytable = _globalTables.getTableByTableName(table); + tools.mylogshow("copyfromapptoapp: ", table, mytable); + _context.next = 169; + return regeneratorRuntime.awrap(mytable.DuplicateAllRecords(idapporig, idappdest).then(function (numrec) { + // tools.mylogshow(' REC TO MODIFY: ', rec); + if (numrec) numrectot += numrec; + })); + + case 169: + _i++; + _context.next = 163; + break; + + case 172: + ris = true; + _context.next = 178; + break; + + case 175: + _context.prev = 175; + _context.t0 = _context["catch"](160); + console.log("e", _context.t0); + + case 178: + _context.next = 682; + break; + + case 180: + if (!(mydata.dbop === "removeRecordsFav")) { + _context.next = 185; + break; + } + + _context.next = 183; + return regeneratorRuntime.awrap(User.removerecordsFavorite()); + + case 183: + _context.next = 682; + break; + + case 185: + if (!(mydata.dbop === "updateReactionsCounts")) { + _context.next = 190; + break; + } + + _context.next = 188; + return regeneratorRuntime.awrap(Reaction.updateReactionsCounts()); + + case 188: + _context.next = 682; + break; + + case 190: + if (!(mydata.dbop === "GeneraCSVOrdineProdotti")) { + _context.next = 195; + break; + } + + _context.next = 193; + return regeneratorRuntime.awrap(Order.GeneraCSVOrdineProdotti()); + + case 193: + _context.next = 682; + break; + + case 195: + if (!(mydata.dbop === "RemoveDeletedOrdersInOrderscart")) { + _context.next = 200; + break; + } + + _context.next = 198; + return regeneratorRuntime.awrap(Order.RemoveDeletedOrdersInOrderscart()); + + case 198: + _context.next = 682; + break; + + case 200: + if (!(mydata.dbop === "CheckTransazioniCircuiti")) { + _context.next = 205; + break; + } + + _context.next = 203; + return regeneratorRuntime.awrap(Circuit.CheckTransazioniCircuiti(false)); + + case 203: + _context.next = 682; + break; + + case 205: + if (!(mydata.dbop === "CorreggiTransazioniCircuiti")) { + _context.next = 210; + break; + } + + _context.next = 208; + return regeneratorRuntime.awrap(Circuit.CheckTransazioniCircuiti(true)); + + case 208: + _context.next = 682; + break; + + case 210: + if (!(mydata.dbop === "RemovePendentTransactions")) { + _context.next = 216; + break; + } + + _context.next = 213; + return regeneratorRuntime.awrap(SendNotif.RemovePendentTransactions(idapp)); + + case 213: + ris = _context.sent; + _context.next = 682; + break; + + case 216: + if (!(mydata.dbop === "RemoveOldNotif90")) { + _context.next = 221; + break; + } + + _context.next = 219; + return regeneratorRuntime.awrap(SendNotif.RemoveOldNotif90(idapp)); + + case 219: + _context.next = 682; + break; + + case 221: + if (!(mydata.dbop === "RemoveOldNotif30")) { + _context.next = 226; + break; + } + + _context.next = 224; + return regeneratorRuntime.awrap(SendNotif.RemoveOldNotif30(idapp)); + + case 224: + _context.next = 682; + break; + + case 226: + if (!(mydata.dbop === "UpdateCoordProv")) { + _context.next = 231; + break; + } + + _context.next = 229; + return regeneratorRuntime.awrap(Province.setCoordinatesOnDB()); + + case 229: + _context.next = 682; + break; + + case 231: + if (!(mydata.dbop === "insertGeojsonToMongoDB")) { + _context.next = 236; + break; + } + + _context.next = 234; + return regeneratorRuntime.awrap(City.insertGeojsonToMongoDB("comuni_italia.geojson")); + + case 234: + _context.next = 682; + break; + + case 236: + if (!(mydata.dbop === "listCollectionsBySize")) { + _context.next = 243; + break; + } + + _context.next = 239; + return regeneratorRuntime.awrap(tools.listCollectionsBySize()); + + case 239: + mystr = _context.sent; + ris = { + mystr: mystr + }; + _context.next = 682; + break; + + case 243: + if (!(mydata.dbop === "EnableNewsOn_ToAll")) { + _context.next = 249; + break; + } + + _context.next = 246; + return regeneratorRuntime.awrap(User.setNewsletterToAll(idapp)); + + case 246: + mystr = _context.sent; + _context.next = 682; + break; + + case 249: + if (!(mydata.dbop === "MyElemSetIdPageInsteadThePah")) { + _context.next = 256; + break; + } + + _context.next = 252; + return regeneratorRuntime.awrap(MyElem.SetIdPageInsteadThePah(idapp)); + + case 252: + mystr = _context.sent; + ris = { + mystr: mystr + }; + _context.next = 682; + break; + + case 256: + if (!(mydata.dbop === "AbilitaNewsletterALL")) { + _context.next = 261; + break; + } + + _context.next = 259; + return regeneratorRuntime.awrap(User.updateMany({ + $or: [{ + deleted: { + $exists: false + } + }, { + deleted: { + $exists: true, + $eq: false + } + }] + }, { + $set: { + news_on: true + } + }, { + "new": false + })); + + case 259: + _context.next = 682; + break; + + case 261: + if (!(mydata.dbop === "SvuotaTuttiGliAccessiOnlineConToken")) { + _context.next = 266; + break; + } + + _context.next = 264; + return regeneratorRuntime.awrap(User.SvuotaTuttiGliAccessiOnlineConToken(idapp)); + + case 264: + _context.next = 682; + break; + + case 266: + if (!(mydata.dbop === "SettaAdTypeOffro_In_Hosps")) { + _context.next = 272; + break; + } + + _require15 = require("../models/myhosp"), MyHosp = _require15.MyHosp; + _context.next = 270; + return regeneratorRuntime.awrap(MyHosp.SettaAdTypeOffro_In_Hosps(idapp)); + + case 270: + _context.next = 682; + break; + + case 272: + if (!(mydata.dbop === "removeRegulations")) { + _context.next = 277; + break; + } + + _context.next = 275; + return regeneratorRuntime.awrap(Circuit.updateMany({}, { + $set: { + regulation: "" + } + })); + + case 275: + _context.next = 682; + break; + + case 277: + if (!(mydata.dbop === "newRecordsFav")) { + _context.next = 290; + break; + } + + _context.next = 280; + return regeneratorRuntime.awrap(User.moverecordsFavorite(1)); + + case 280: + _context.next = 282; + return regeneratorRuntime.awrap(User.moverecordsFavorite(2)); + + case 282: + _context.next = 284; + return regeneratorRuntime.awrap(User.moverecordsFavorite(3)); + + case 284: + _context.next = 286; + return regeneratorRuntime.awrap(User.moverecordsFavorite(4)); + + case 286: + _context.next = 288; + return regeneratorRuntime.awrap(User.moverecordsFavorite(5)); + + case 288: + _context.next = 682; + break; + + case 290: + if (!(mydata.dbop === "emptyTabCatServiziBeni")) { + _context.next = 306; + break; + } + + _require16 = require("../models/sector"), Sector = _require16.Sector; + _require17 = require("../models/sectorgood"), SectorGood = _require17.SectorGood; + _require18 = require("../models/skill"), Skill = _require18.Skill; + _require19 = require("../models/good"), Good = _require19.Good; + _context.next = 297; + return regeneratorRuntime.awrap(Sector.deleteMany({})); + + case 297: + _context.next = 299; + return regeneratorRuntime.awrap(SectorGood.deleteMany({})); + + case 299: + _context.next = 301; + return regeneratorRuntime.awrap(Skill.deleteMany({})); + + case 301: + _context.next = 303; + return regeneratorRuntime.awrap(Good.deleteMany({})); + + case 303: + ris = _context.sent; + _context.next = 682; + break; + + case 306: + if (!(mydata.dbop === "emptyDbSkill")) { + _context.next = 342; + break; + } + + // Svuota e Ricrea + _require20 = require("../models/sector"), _Sector = _require20.Sector; + _require21 = require("../models/sectorgood"), _SectorGood = _require21.SectorGood; + _require22 = require("../models/skill"), _Skill = _require22.Skill; + _require23 = require("../models/good"), _Good = _require23.Good; + _require24 = require("../models/subskill"), SubSkill = _require24.SubSkill; + _require25 = require("../models/contribtype"), Contribtype = _require25.Contribtype; + _require26 = require("../models/adtype"), AdType = _require26.AdType; + _require27 = require("../models/adtypegood"), AdTypeGood = _require27.AdTypeGood; + _require28 = require("../models/statusSkill"), StatusSkill = _require28.StatusSkill; + _require29 = require("../models/catgrp"), CatGrp = _require29.CatGrp; + _context.next = 319; + return regeneratorRuntime.awrap(_Sector.deleteMany({})); + + case 319: + _context.next = 321; + return regeneratorRuntime.awrap(_SectorGood.deleteMany({})); + + case 321: + _context.next = 323; + return regeneratorRuntime.awrap(_Skill.deleteMany({})); + + case 323: + _context.next = 325; + return regeneratorRuntime.awrap(_Good.deleteMany({})); + + case 325: + _context.next = 327; + return regeneratorRuntime.awrap(SubSkill.deleteMany({})); + + case 327: + _context.next = 329; + return regeneratorRuntime.awrap(Contribtype.deleteMany({})); + + case 329: + _context.next = 331; + return regeneratorRuntime.awrap(AdType.deleteMany({})); + + case 331: + _context.next = 333; + return regeneratorRuntime.awrap(AdTypeGood.deleteMany({})); + + case 333: + _context.next = 335; + return regeneratorRuntime.awrap(StatusSkill.deleteMany({})); + + case 335: + _context.next = 337; + return regeneratorRuntime.awrap(CatGrp.deleteMany({})); + + case 337: + _context.next = 339; + return regeneratorRuntime.awrap(populate.popolaTabelleNuove()); + + case 339: + ris = _context.sent; + _context.next = 682; + break; + + case 342: + if (!(mydata.dbop === "ricreaTabCitiesProvinces")) { + _context.next = 354; + break; + } + + // Svuota e Ricrea + _require30 = require("../models/city"), _City = _require30.City; + _require31 = require("../models/province"), _Province = _require31.Province; + _context.next = 347; + return regeneratorRuntime.awrap(_City.deleteMany({})); + + case 347: + _context.next = 349; + return regeneratorRuntime.awrap(_Province.deleteMany({})); + + case 349: + _context.next = 351; + return regeneratorRuntime.awrap(populate.popolaTabelleNuove()); + + case 351: + ris = _context.sent; + _context.next = 682; + break; + + case 354: + if (!(mydata.dbop === "PopulateTables")) { + _context.next = 358; + break; + } + + ris = populate.popolaTabelleNuove(); + _context.next = 682; + break; + + case 358: + if (!(mydata.dbop === "dropProducts")) { + _context.next = 371; + break; + } + + if (!idapp) { + _context.next = 368; + break; + } + + _context.next = 362; + return regeneratorRuntime.awrap(Product.deleteMany({ + idapp: idapp + })); + + case 362: + deleteProducts = _context.sent; + console.log("Cancellati ".concat(deleteProducts.deletedCount, " record dalla collezione Product.")); // Cancellazione dei record nella collezione ProductInfo + + _context.next = 366; + return regeneratorRuntime.awrap(ProductInfo.deleteMany({ + idapp: idapp + })); + + case 366: + _deleteProductInfo = _context.sent; + console.log("Cancellati ".concat(_deleteProductInfo.deletedCount, " record dalla collezione ProductInfo.")); + + case 368: + ris = deleteProductInfo ? true : false; + _context.next = 682; + break; + + case 371: + if (!(mydata.dbop === "dropCatProd")) { + _context.next = 377; + break; + } + + _context.next = 374; + return regeneratorRuntime.awrap(CatProd.deleteMany({ + idapp: idapp + })); + + case 374: + deleteCatProd = _context.sent; + _context.next = 682; + break; + + case 377: + if (!(mydata.dbop === "dropSubCatProd")) { + _context.next = 383; + break; + } + + _context.next = 380; + return regeneratorRuntime.awrap(SubCatProd.deleteMany({ + idapp: idapp + })); + + case 380: + deleteSubCatProd = _context.sent; + _context.next = 682; + break; + + case 383: + if (!(mydata.dbop === "dropAllOrders")) { + _context.next = 402; + break; + } + + _context.prev = 384; + _context.next = 387; + return regeneratorRuntime.awrap(Order.deleteMany({ + idapp: idapp + })); + + case 387: + deleteOrder = _context.sent; + _context.next = 390; + return regeneratorRuntime.awrap(OrdersCart.deleteMany({ + idapp: idapp + })); + + case 390: + deleteOrdersCart = _context.sent; + _context.next = 393; + return regeneratorRuntime.awrap(Cart.deleteMany({ + idapp: idapp + })); + + case 393: + deleteCart = _context.sent; + ris = deleteCart; + _context.next = 400; + break; + + case 397: + _context.prev = 397; + _context.t1 = _context["catch"](384); + console.error("Err:", _context.t1); + + case 400: + _context.next = 682; + break; + + case 402: + if (!(mydata.dbop === "SistemaGasOrdine")) { + _context.next = 439; + break; + } + + _context.next = 405; + return regeneratorRuntime.awrap(Product.find({}).lean()); + + case 405: + arrrec = _context.sent; + _iteratorNormalCompletion = true; + _didIteratorError = false; + _iteratorError = undefined; + _context.prev = 409; + _iterator = arrrec[Symbol.iterator](); + + case 411: + if (_iteratorNormalCompletion = (_step = _iterator.next()).done) { + _context.next = 423; + break; + } + + rec = _step.value; + + if (!(tools.isArray(rec.idGasordines) && rec.idGasordines.length > 0)) { + _context.next = 418; + break; + } + + _context.next = 416; + return regeneratorRuntime.awrap(Product.findByIdAndUpdate(rec._id, { + $set: { + idGasordine: rec.idGasordines[0] + } + })); + + case 416: + _context.next = 420; + break; + + case 418: + _context.next = 420; + return regeneratorRuntime.awrap(Product.findByIdAndUpdate(rec._id, { + $set: { + idGasordine: null + } + })); + + case 420: + _iteratorNormalCompletion = true; + _context.next = 411; + break; + + case 423: + _context.next = 429; + break; + + case 425: + _context.prev = 425; + _context.t2 = _context["catch"](409); + _didIteratorError = true; + _iteratorError = _context.t2; + + case 429: + _context.prev = 429; + _context.prev = 430; + + if (!_iteratorNormalCompletion && _iterator["return"] != null) { + _iterator["return"](); + } + + case 432: + _context.prev = 432; + + if (!_didIteratorError) { + _context.next = 435; + break; + } + + throw _iteratorError; + + case 435: + return _context.finish(432); + + case 436: + return _context.finish(429); + + case 437: + _context.next = 682; + break; + + case 439: + if (!(mydata.dbop === "CopyPriceToCalc")) { + _context.next = 506; + break; + } + + _context.prev = 440; + _context.next = 443; + return regeneratorRuntime.awrap(OrdersCart.find({}).lean()); + + case 443: + _arrrec = _context.sent; + _iteratorNormalCompletion2 = true; + _didIteratorError2 = false; + _iteratorError2 = undefined; + _context.prev = 447; + _iterator2 = _arrrec[Symbol.iterator](); + + case 449: + if (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done) { + _context.next = 456; + break; + } + + _rec = _step2.value; + _context.next = 453; + return regeneratorRuntime.awrap(OrdersCart.findByIdAndUpdate(_rec._id, { + $set: { + totalPriceCalc: _rec.totalPrice + } + })); + + case 453: + _iteratorNormalCompletion2 = true; + _context.next = 449; + break; + + case 456: + _context.next = 462; + break; + + case 458: + _context.prev = 458; + _context.t3 = _context["catch"](447); + _didIteratorError2 = true; + _iteratorError2 = _context.t3; + + case 462: + _context.prev = 462; + _context.prev = 463; + + if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { + _iterator2["return"](); + } + + case 465: + _context.prev = 465; + + if (!_didIteratorError2) { + _context.next = 468; + break; + } + + throw _iteratorError2; + + case 468: + return _context.finish(465); + + case 469: + return _context.finish(462); + + case 470: + _context.next = 472; + return regeneratorRuntime.awrap(Order.find({}).lean()); + + case 472: + arrrec2 = _context.sent; + _iteratorNormalCompletion3 = true; + _didIteratorError3 = false; + _iteratorError3 = undefined; + _context.prev = 476; + _iterator3 = arrrec2[Symbol.iterator](); + + case 478: + if (_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done) { + _context.next = 485; + break; + } + + _rec2 = _step3.value; + _context.next = 482; + return regeneratorRuntime.awrap(Order.findByIdAndUpdate(_rec2._id, { + $set: { + TotalPriceProductCalc: _rec2.TotalPriceProduct + } + })); + + case 482: + _iteratorNormalCompletion3 = true; + _context.next = 478; + break; + + case 485: + _context.next = 491; + break; + + case 487: + _context.prev = 487; + _context.t4 = _context["catch"](476); + _didIteratorError3 = true; + _iteratorError3 = _context.t4; + + case 491: + _context.prev = 491; + _context.prev = 492; + + if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) { + _iterator3["return"](); + } + + case 494: + _context.prev = 494; + + if (!_didIteratorError3) { + _context.next = 497; + break; + } + + throw _iteratorError3; + + case 497: + return _context.finish(494); + + case 498: + return _context.finish(491); + + case 499: + _context.next = 504; + break; + + case 501: + _context.prev = 501; + _context.t5 = _context["catch"](440); + console.error("Err:", _context.t5); + + case 504: + _context.next = 682; + break; + + case 506: + if (!(mydata.dbop === "dropAllCarts")) { + _context.next = 512; + break; + } + + _context.next = 509; + return regeneratorRuntime.awrap(Cart.deleteMany({ + idapp: idapp + })); + + case 509: + ris = _context.sent; + _context.next = 682; + break; + + case 512: + if (!(mydata.dbop === "RewriteCitiesTable")) { + _context.next = 516; + break; + } + + ris = populate.rewriteTable("cities"); + _context.next = 682; + break; + + case 516: + if (!(mydata.dbop === "RewriteLevelsTable")) { + _context.next = 520; + break; + } + + ris = populate.rewriteTable("levels"); + _context.next = 682; + break; + + case 520: + if (!(mydata.dbop === "RewriteProvincesTable")) { + _context.next = 524; + break; + } + + ris = populate.rewriteTable("provinces"); + _context.next = 682; + break; + + case 524: + if (!(mydata.dbop === "emptyCityProvinces")) { + _context.next = 533; + break; + } + + _require32 = require("../models/city"), _City2 = _require32.City; + _require33 = require("../models/province"), _Province2 = _require33.Province; + _context.next = 529; + return regeneratorRuntime.awrap(_City2.deleteMany({})); + + case 529: + _context.next = 531; + return regeneratorRuntime.awrap(_Province2.deleteMany({})); + + case 531: + _context.next = 682; + break; + + case 533: + if (!(mydata.dbop === "ConvTablesFromIntToString")) { + _context.next = 552; + break; + } + + _require34 = require("../models/myskill"), MySkill = _require34.MySkill; + _require35 = require("../models/mybacheca"), MyBacheca = _require35.MyBacheca; + _require36 = require("../models/myhosp"), _MyHosp = _require36.MyHosp; + _require37 = require("../models/mygood"), MyGood = _require37.MyGood; // const { MyGroup } = require('../models/mygroup'); + + console.log("INIZIO - Conversioni"); // 'myskills', + // 'mybachecas', + // 'myhosps', + // 'mygoods', + // 'mygroups' + + _context.next = 541; + return regeneratorRuntime.awrap(ConvertiDaIntAStr(MySkill)); + + case 541: + _context.next = 543; + return regeneratorRuntime.awrap(ConvertiDaIntAStr(MyBacheca)); + + case 543: + _context.next = 545; + return regeneratorRuntime.awrap(ConvertiDaIntAStr(_MyHosp)); + + case 545: + _context.next = 547; + return regeneratorRuntime.awrap(ConvertiDaIntAStr(MyGood)); + + case 547: + _context.next = 549; + return regeneratorRuntime.awrap(ConvertiDaIntAStr(MyGroup)); + + case 549: + console.log("FINE - Conversioni"); + _context.next = 682; + break; + + case 552: + if (!(mydata.dbop === "Removeinteger")) { + _context.next = 571; + break; + } + + _require38 = require("../models/myskill"), _MySkill = _require38.MySkill; + _require39 = require("../models/mybacheca"), _MyBacheca = _require39.MyBacheca; + _require40 = require("../models/myhosp"), _MyHosp2 = _require40.MyHosp; + _require41 = require("../models/mygood"), _MyGood = _require41.MyGood; // const { MyGroup } = require('../models/mygroup'); + + console.log("INIZIO - Rimozione"); + _context.next = 560; + return regeneratorRuntime.awrap(RimuoviInteri(_MySkill)); + + case 560: + _context.next = 562; + return regeneratorRuntime.awrap(RimuoviInteri(_MyBacheca)); + + case 562: + _context.next = 564; + return regeneratorRuntime.awrap(RimuoviInteri(_MyHosp2)); + + case 564: + _context.next = 566; + return regeneratorRuntime.awrap(RimuoviInteri(_MyGood)); + + case 566: + _context.next = 568; + return regeneratorRuntime.awrap(RimuoviInteri(MyGroup)); + + case 568: + console.log("FINE - Rimozione"); + _context.next = 682; + break; + + case 571: + if (!(mydata.dbop === "createAllCircuits")) { + _context.next = 604; + break; + } + + _require42 = require("../models/province"), _Province3 = _require42.Province; + _context.next = 575; + return regeneratorRuntime.awrap(_Province3.find({})); + + case 575: + arrProv = _context.sent; + _iteratorNormalCompletion4 = true; + _didIteratorError4 = false; + _iteratorError4 = undefined; + _context.prev = 579; + _iterator4 = arrProv[Symbol.iterator](); + + case 581: + if (_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done) { + _context.next = 588; + break; + } + + recprov = _step4.value; + _context.next = 585; + return regeneratorRuntime.awrap(Circuit.createCircuitIfNotExist(req, idapp, recprov.prov)); + + case 585: + _iteratorNormalCompletion4 = true; + _context.next = 581; + break; + + case 588: + _context.next = 594; + break; + + case 590: + _context.prev = 590; + _context.t6 = _context["catch"](579); + _didIteratorError4 = true; + _iteratorError4 = _context.t6; + + case 594: + _context.prev = 594; + _context.prev = 595; + + if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) { + _iterator4["return"](); + } + + case 597: + _context.prev = 597; + + if (!_didIteratorError4) { + _context.next = 600; + break; + } + + throw _iteratorError4; + + case 600: + return _context.finish(597); + + case 601: + return _context.finish(594); + + case 602: + _context.next = 682; + break; + + case 604: + if (!(mydata.dbop === "correggiProductTypes")) { + _context.next = 609; + break; + } + + _context.next = 607; + return regeneratorRuntime.awrap(ProductInfo.correggiProductTypes()); + + case 607: + _context.next = 682; + break; + + case 609: + if (!(mydata.dbop === "replaceProductImgToImageFile")) { + _context.next = 614; + break; + } + + _context.next = 612; + return regeneratorRuntime.awrap(ProductInfo.replaceProductImgToImageFile(true)); + + case 612: + _context.next = 682; + break; + + case 614: + if (!(mydata.dbop === "removeUploadProducts_Path")) { + _context.next = 619; + break; + } + + _context.next = 617; + return regeneratorRuntime.awrap(ProductInfo.replaceProductImgToImageFile(false)); + + case 617: + _context.next = 682; + break; + + case 619: + if (!(mydata.dbop === "correggiCircuitiANull")) { + _context.next = 624; + break; + } + + _context.next = 622; + return regeneratorRuntime.awrap(User.updateMany({}, { + $pull: { + "profile.mycircuits": { + circuitname: null + } + } + })); + + case 622: + _context.next = 682; + break; + + case 624: + if (!(mydata.dbop === "ImpostaMinMaxPersonali")) { + _context.next = 629; + break; + } + + _context.next = 627; + return regeneratorRuntime.awrap(Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, "")); + + case 627: + _context.next = 682; + break; + + case 629: + if (!(mydata.dbop === "ImpostaMinMaxPersonaliCircuito")) { + _context.next = 634; + break; + } + + _context.next = 632; + return regeneratorRuntime.awrap(Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId)); + + case 632: + _context.next = 682; + break; + + case 634: + if (!(mydata.dbop === "ImpostaMinMaxComunitari")) { + _context.next = 639; + break; + } + + _context.next = 637; + return regeneratorRuntime.awrap(Account.SetMinMaxComunitari(idapp, mydata.valmin, mydata.valmax)); + + case 637: + _context.next = 682; + break; + + case 639: + if (!(mydata.dbop === "ImpostaMinMaxCollettivi")) { + _context.next = 644; + break; + } + + _context.next = 642; + return regeneratorRuntime.awrap(Account.SetMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax)); + + case 642: + _context.next = 682; + break; + + case 644: + if (!(mydata.dbop === "ImpostaDefMinMaxPersonali")) { + _context.next = 649; + break; + } + + _context.next = 647; + return regeneratorRuntime.awrap(Circuit.SetDefMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId)); + + case 647: + _context.next = 682; + break; + + case 649: + if (!(mydata.dbop === "ImpostaDefMinMaxCollettivi")) { + _context.next = 654; + break; + } + + _context.next = 652; + return regeneratorRuntime.awrap(Circuit.SetDefMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax, mydata.circuitId)); + + case 652: + _context.next = 682; + break; + + case 654: + if (!(mydata.dbop === "AbilitaTuttiCircuiti")) { + _context.next = 659; + break; + } + + _context.next = 657; + return regeneratorRuntime.awrap(Circuit.AbilitaTuttiCircuiti(idapp)); + + case 657: + _context.next = 682; + break; + + case 659: + if (!(mydata.dbop === "AzzeraRegolamentiTuttiCircuiti")) { + _context.next = 664; + break; + } + + _context.next = 662; + return regeneratorRuntime.awrap(Circuit.AzzeraRegolamentiTuttiCircuiti(idapp)); + + case 662: + _context.next = 682; + break; + + case 664: + if (!(mydata.dbop === "setstrProvByIdCityCircuits")) { + _context.next = 669; + break; + } + + _context.next = 667; + return regeneratorRuntime.awrap(Circuit.setstrProvByIdCityCircuits(idapp)); + + case 667: + _context.next = 682; + break; + + case 669: + if (!(mydata.dbop === "updateSaldoAndTransato_AllAccounts")) { + _context.next = 674; + break; + } + + _context.next = 672; + return regeneratorRuntime.awrap(Account.updateSaldoAndTransato_AllAccounts(idapp)); + + case 672: + _context.next = 682; + break; + + case 674: + if (!(mydata.dbop === "generateBotMenuRecords")) { + _context.next = 679; + break; + } + + _context.next = 677; + return regeneratorRuntime.awrap(MyBot.generateBotMenuRecords(idapp)); + + case 677: + _context.next = 682; + break; + + case 679: + if (!(mydata.dbop === "GenerateVapiKey")) { + _context.next = 682; + break; + } + + _context.next = 682; + return regeneratorRuntime.awrap(tools.generateVapiKey()); + + case 682: + return _context.abrupt("return", ris); + + case 685: + _context.prev = 685; + _context.t7 = _context["catch"](8); + console.log(_context.t7.message); + + case 688: + case "end": + return _context.stop(); + } + } + }, null, null, [[8, 685], [160, 175], [384, 397], [409, 425, 429, 437], [430,, 432, 436], [440, 501], [447, 458, 462, 470], [463,, 465, 469], [476, 487, 491, 499], [492,, 494, 498], [579, 590, 594, 602], [595,, 597, 601]]); + } + }]); + + return CronMod; +}(); + +module.exports = CronMod; \ No newline at end of file diff --git a/src/server/modules/dist/ErrorHandler.dev.js b/src/server/modules/dist/ErrorHandler.dev.js new file mode 100755 index 0000000..de27d2a --- /dev/null +++ b/src/server/modules/dist/ErrorHandler.dev.js @@ -0,0 +1,45 @@ +"use strict"; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } + +function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } + +function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var TypedError = +/*#__PURE__*/ +function (_Error) { + _inherits(TypedError, _Error); + + function TypedError(args, status, type, error) { + var _this; + + _classCallCheck(this, TypedError); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(TypedError).call(this, args)); + _this.status = status; + _this.type = type; + _this.error = error; + return _this; + } + + return TypedError; +}(_wrapNativeSuper(Error)); + +module.exports = TypedError; \ No newline at end of file diff --git a/src/server/modules/dist/Mailinabox.dev.js b/src/server/modules/dist/Mailinabox.dev.js new file mode 100644 index 0000000..0231d7a --- /dev/null +++ b/src/server/modules/dist/Mailinabox.dev.js @@ -0,0 +1,348 @@ +"use strict"; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var axios = require('axios'); + +var apiUrl = 'https://api.cloudflare.com/client/v4'; // Endpoint + +var Mailinabox = +/*#__PURE__*/ +function () { + function Mailinabox(config) { + _classCallCheck(this, Mailinabox); + + this.config = config ? config : {}; + + if (!this.config.miabHost) { + this.config.miabHost = process.env.MIAB_HOST; + this.config.adminEmail = process.env.MIAB_ADMIN_EMAIL; + this.config.adminPassword = process.env.MIAB_ADMIN_PASSWORD; + } + } + + _createClass(Mailinabox, [{ + key: "init", + value: function init() { + if (this.config.arrTokens) { + this.zones = []; + } + } + }, { + key: "checkIfParamOk", + value: function checkIfParamOk() { + if (!this.config.miabHost || !this.config.adminEmail || !this.config.adminPassword) { + console.error('Configurazione mancante per il recupero del record DKIM.'); + return false; + } + + return true; + } // Funzione per ottenere il record DKIM + + }, { + key: "getDKIMRecord", + value: function getDKIMRecord(domain) { + var url, auth, response, records, dkimRecord, pattern, match; + return regeneratorRuntime.async(function getDKIMRecord$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (this.checkIfParamOk()) { + _context.next = 2; + break; + } + + return _context.abrupt("return", ''); + + case 2: + url = "https://".concat(this.config.miabHost, "/admin/dns/zonefile/").concat(domain); + auth = Buffer.from("".concat(this.config.adminEmail, ":").concat(this.config.adminPassword)).toString('base64'); + _context.prev = 4; + _context.next = 7; + return regeneratorRuntime.awrap(axios.get(url, { + headers: { + 'Authorization': "Basic ".concat(auth) + } + })); + + case 7: + response = _context.sent; + // console.log(`Record DNS esterni per ${config.domain}:`); + // Analizza la risposta per estrarre i record DNS + records = response.data.split('\n').filter(function (line) { + return line.trim() !== '' && !line.startsWith(';'); + }).map(function (line) { + return line.trim(); + }); // Trova e stampa il record DKIM + + dkimRecord = records.find(function (record) { + return record.includes('mail._domainkey'); + }); + + if (!dkimRecord) { + _context.next = 18; + break; + } + + pattern = /p=([A-Za-z0-9+/=]+)(?:"\s*"([A-Za-z0-9+/=]+))?/; // Esegui la ricerca + + match = dkimRecord.match(pattern); + + if (!match) { + _context.next = 17; + break; + } + + return _context.abrupt("return", match[1] + (match[2] || '')); + + case 17: + console.log('Record DKIM non trovato.'); + + case 18: + return _context.abrupt("return", ''); + + case 21: + _context.prev = 21; + _context.t0 = _context["catch"](4); + console.error('Errore nel recupero del record DKIM:', _context.t0.message); + + if (_context.t0.response) { + console.error('Dettagli errore:', _context.t0.response.data); + } + + case 25: + return _context.abrupt("return", ''); + + case 26: + case "end": + return _context.stop(); + } + } + }, null, this, [[4, 21]]); + } + }, { + key: "MIAB_getEmails", + value: function MIAB_getEmails(myrec) { + var url, auth, response, records; + return regeneratorRuntime.async(function MIAB_getEmails$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!(!this.checkIfParamOk() || !myrec.domain)) { + _context2.next = 2; + break; + } + + return _context2.abrupt("return"); + + case 2: + url = "https://".concat(this.config.miabHost, "/admin/mail/users?format=text"); + auth = Buffer.from("".concat(this.config.adminEmail, ":").concat(this.config.adminPassword)).toString('base64'); + _context2.prev = 4; + _context2.next = 7; + return regeneratorRuntime.awrap(axios.get(url, { + headers: { + 'Authorization': "Basic ".concat(auth) + } + })); + + case 7: + response = _context2.sent; + records = response.data.split('\n').filter(function (line) { + return line.trim() !== '' && line.indexOf(myrec.domain) > -1; + }).map(function (line) { + return line.trim(); + }); + return _context2.abrupt("return", records); + + case 12: + _context2.prev = 12; + _context2.t0 = _context2["catch"](4); + console.error('Errore nel recupero delle Email ', _context2.t0.message); + + if (_context2.t0.response) { + console.error('Dettagli errore:', _context2.t0.response.data); + } + + case 16: + return _context2.abrupt("return", ''); + + case 17: + case "end": + return _context2.stop(); + } + } + }, null, this, [[4, 12]]); + } + }, { + key: "removeEmail", + value: function removeEmail(myrec) { + var url, auth, myrecout, response, ris; + return regeneratorRuntime.async(function removeEmail$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + if (!(!this.checkIfParamOk() || !myrec.email)) { + _context3.next = 2; + break; + } + + return _context3.abrupt("return"); + + case 2: + url = "https://".concat(this.config.miabHost, "/admin/mail/users/remove"); + auth = Buffer.from("".concat(this.config.adminEmail, ":").concat(this.config.adminPassword)).toString('base64'); + _context3.prev = 4; + myrecout = "email=".concat(myrec.email); + _context3.next = 8; + return regeneratorRuntime.awrap(axios.post(url, myrecout, { + headers: { + 'Authorization': "Basic ".concat(auth) + } + })); + + case 8: + response = _context3.sent; + ris = response.data; + return _context3.abrupt("return", ris); + + case 13: + _context3.prev = 13; + _context3.t0 = _context3["catch"](4); + console.error('Errore nella cancellazione della Email ' + record.email, _context3.t0.message); + + if (_context3.t0.response) { + console.error('Dettagli errore:', _context3.t0.response.data); + } + + case 17: + return _context3.abrupt("return", ''); + + case 18: + case "end": + return _context3.stop(); + } + } + }, null, this, [[4, 13]]); + } + }, { + key: "addEmail", + value: function addEmail(myrec) { + var url, auth, privileges, myrecout, response, ris; + return regeneratorRuntime.async(function addEmail$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + if (!(!this.checkIfParamOk() || !myrec.email)) { + _context4.next = 2; + break; + } + + return _context4.abrupt("return"); + + case 2: + url = "https://".concat(this.config.miabHost, "/admin/mail/users/add"); + auth = Buffer.from("".concat(this.config.adminEmail, ":").concat(this.config.adminPassword)).toString('base64'); + _context4.prev = 4; + privileges = myrec.privileges ? 'admin' : ''; + myrecout = "email=".concat(myrec.email, "&password=").concat(myrec.pwd, "&privileges=\"").concat(privileges, "\""); + _context4.next = 9; + return regeneratorRuntime.awrap(axios.post(url, myrecout, { + headers: { + 'Authorization': "Basic ".concat(auth) + } + })); + + case 9: + response = _context4.sent; + ris = response.data; + return _context4.abrupt("return", ris); + + case 14: + _context4.prev = 14; + _context4.t0 = _context4["catch"](4); + console.error('Errore nella creazione della Email ' + record.email, _context4.t0.message); + + if (_context4.t0.response) { + console.error('Dettagli errore:', _context4.t0.response.data); + } + + case 18: + return _context4.abrupt("return", ''); + + case 19: + case "end": + return _context4.stop(); + } + } + }, null, this, [[4, 14]]); + } + }, { + key: "setMailUserPassword", + value: function setMailUserPassword(myrec) { + var url, auth, data, response, ris; + return regeneratorRuntime.async(function setMailUserPassword$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + if (!(!this.checkIfParamOk() || !myrec.email)) { + _context5.next = 2; + break; + } + + return _context5.abrupt("return"); + + case 2: + url = "https://".concat(this.config.miabHost, "/admin/mail/users/password"); + auth = Buffer.from("".concat(this.config.adminEmail, ":").concat(this.config.adminPassword)).toString('base64'); + _context5.prev = 4; + data = "email=".concat(myrec.email, "&password=").concat(myrec.pwd); + _context5.next = 8; + return regeneratorRuntime.awrap(axios.post(url, data, { + headers: { + 'Authorization': "Basic ".concat(auth), + 'Content-Type': 'application/x-www-form-urlencoded' + } + })); + + case 8: + response = _context5.sent; + ris = ''; + + if (response.status === 200) { + ris = "Password cambiata con successo per ".concat(myrec.email); + } else { + ris = "Errore nel cambio password per ".concat(myrec.email); + } + + return _context5.abrupt("return", ris); + + case 14: + _context5.prev = 14; + _context5.t0 = _context5["catch"](4); + console.error('Errore nella creazione della Email ' + record.email, _context5.t0.message); + + if (_context5.t0.response) { + console.error('Dettagli errore:', _context5.t0.response.data); + } + + case 18: + return _context5.abrupt("return", ''); + + case 19: + case "end": + return _context5.stop(); + } + } + }, null, this, [[4, 14]]); + } + }]); + + return Mailinabox; +}(); + +module.exports = Mailinabox; \ No newline at end of file diff --git a/src/server/populate/populate.js b/src/server/populate/populate.js index ffb8000..89c9e06 100644 --- a/src/server/populate/populate.js +++ b/src/server/populate/populate.js @@ -13,7 +13,7 @@ module.exports = { try { const pathfile = Path.join(__dirname, tablename + '.js'); - if (tools.isFileExists(pathfile)) { + if (await tools.isFileExistsAsync(pathfile)) { const mydbfile = require(pathfile); if (mydbfile && mydbfile.list) { @@ -39,7 +39,7 @@ module.exports = { let primavolta = false; const pathfile = Path.join(__dirname, tablename + '.js'); - if (tools.isFileExists(pathfile)) { + if (await tools.isFileExistsAsync(pathfile)) { const mydbfile = require(pathfile); if (mydbfile && mydbfile.list) { diff --git a/src/server/router/admin_router.js b/src/server/router/admin_router.js index 244096a..6da839f 100755 --- a/src/server/router/admin_router.js +++ b/src/server/router/admin_router.js @@ -139,7 +139,7 @@ function updateProductInfoCatProds(productInfo, reccatprod) { async function compressPdf(inputFile, outputFile, compressione) { try { const tempFolder = path.join(cwd, 'temp'); - const hasTempFolder = tools.isFileExists(tempFolder); + const hasTempFolder = await tools.isFileExistsAsync(tempFolder); if (!hasTempFolder) { console.log('creo directory', tempFolder); @@ -176,7 +176,7 @@ async function compressPdf(inputFile, outputFile, compressione) { async function convertPDF_GS(inputFile, outputFile, width, height) { // Verifica che il file di input esista - if (!tools.isFileExists(inputFile)) { + if (!await tools.isFileExistsAsync(inputFile)) { throw new Error(`Il file di input non esiste: ${inputFile}`); } @@ -210,7 +210,7 @@ async function convertPDF_GS(inputFile, outputFile, width, height) { console.log('Conversione completata con successo!'); // Verifica che il file di output sia stato generato - if (tools.isFileExists(outputFile)) { + if (await tools.isFileExistsAsync(outputFile)) { console.log('File di output generato:', outputFile); } else { console.error('Il File di output NON è stato generato! :', outputFile); @@ -256,7 +256,7 @@ async function extractPdfInfo(inputFile) { } async function convertPDF_PdfLib(idapp, inputFile, outputFile, options) { - if (!tools.isFileExists(inputFile)) { + if (!await tools.isFileExistsAsync(inputFile)) { throw new Error(`Il file di input non esiste: ${inputFile}`); } diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 6b5f531..1931291 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -2425,11 +2425,11 @@ function uploadFile(req, res, version) { //fit: sharp.fit.cover, fit: sharp.fit.contain, // position: sharp.strategy.entropy, - }).withMetadata().toFile(resized_img, function (err) { + }).withMetadata().toFile(resized_img, async function (err) { // console.log('3) Ridimensionata Immagine ' + newname, 'in', resized_img); - if (tools.isFileExists(resized_img)) { + if (await tools.isFileExistsAsync(resized_img)) { // console.log('4) Cancella l \'immagine grande originale:', newname); // DELETE THE ORIGINAL BIG tools.delete(newname, false, () => { }); diff --git a/src/server/server.js b/src/server/server.js index 92378bd..86fca86 100755 --- a/src/server/server.js +++ b/src/server/server.js @@ -534,14 +534,14 @@ connectToDatabase(connectionUrl, options) try { // console.log('checkdir', folderprof); - if (!tools.isFileExists(folderprof)) { + if (!await tools.isFileExistsAsync(folderprof)) { console.log('*** Creadir', folderprof); await fs.mkdirSync(folderprof); } folderprof = dir + 'profile/' + myuser.username + '/' + table; // console.log('checkdir', folderprof); - if (!tools.isFileExists(folderprof)) { + if (!await tools.isFileExistsAsync(folderprof)) { console.log('creadir', folderprof); await fs.mkdirSync(folderprof); } @@ -557,18 +557,18 @@ connectToDatabase(connectionUrl, options) // console.log('file', file); // console.log('filefrom', filefrom); - if (!tools.isFileExists(file)) { + if (!await tools.isFileExistsAsync(file)) { // non esiste console.log('non esiste', file); console.log(' filefrom', filefrom); console.log(' filefrom2', filefrom2); } - if (!tools.isFileExists(file) && tools.isFileExists(filefrom)) { + if (!await tools.isFileExistsAsync(file) && await tools.isFileExistsAsync(filefrom)) { console.log('@@@@@@ copia file:', filefrom, 'a', file); tools.copy(filefrom, file); } - if (!tools.isFileExists(file) && tools.isFileExists(filefrom2)) { + if (!await tools.isFileExistsAsync(file) && await tools.isFileExistsAsync(filefrom2)) { console.log('@@@@@@ copia file 2:', filefrom2, 'a', file); tools.copy(filefrom2, file); } @@ -675,7 +675,7 @@ connectToDatabase(connectionUrl, options) } // Funzione migliorata per ottenere chiave e certificato - function getCredentials(hostname) { + async function getCredentials(hostname) { try { let keyPath, certPath; @@ -691,10 +691,10 @@ connectToDatabase(connectionUrl, options) } // Verifica esistenza file - if (!tools.isFileExists(keyPath)) { + if (!await tools.isFileExistsAsync(keyPath)) { throw new Error(`Chiave privata non trovata: ${keyPath}`); } - if (!tools.isFileExists(certPath)) { + if (!await tools.isFileExistsAsync(certPath)) { throw new Error(`Certificato non trovato: ${certPath}`); } @@ -875,11 +875,11 @@ connectToDatabase(connectionUrl, options) }); } - function createHttpOrHttpsServer(app, port, isProduction, domains) { + async function createHttpOrHttpsServer(app, port, isProduction, domains) { if (isProduction) { - domains.forEach((domain) => { - const credentials = getCredentials(domain.hostname); - createHttpsServer({ + const promises = domains.map(async (domain) => { + const credentials = await getCredentials(domain.hostname); + return createHttpsServer({ hostname: domain.hostname, port: domain.port, website: domain.website, @@ -888,6 +888,7 @@ connectToDatabase(connectionUrl, options) timeoutMinutes: 6, }); }); + await Promise.all(promises); return null; } @@ -936,7 +937,7 @@ connectToDatabase(connectionUrl, options) const pty = require('node-pty'); let scriptProcess = null; - ws.on('message', (message) => { + ws.on('message', async (message) => { try { const parsed = JSON.parse(message); @@ -944,7 +945,7 @@ connectToDatabase(connectionUrl, options) if (scriptProcess) scriptProcess.kill(); const scriptPath = path.join(__dirname, '..', '..', parsed.scriptName); - if (!tools.isFileExists(scriptPath)) { + if (!await tools.isFileExistsAsync(scriptPath)) { return ws.send(JSON.stringify({ type: 'error', data: 'Script non trovato o non autorizzato' })); } @@ -999,7 +1000,7 @@ connectToDatabase(connectionUrl, options) return wss; } - function startServer(app, port) { + async function startServer(app, port) { try { const isProduction = ['production', 'test'].includes(process.env.NODE_ENV); const ISDEBUG = false; @@ -1014,7 +1015,7 @@ connectToDatabase(connectionUrl, options) setupMiddleware(app, corsOptions, ISDEBUG); - const server = createHttpOrHttpsServer(app, port, isProduction, domains); + const server = await createHttpOrHttpsServer(app, port, isProduction, domains); const wss = setupWebSocketServer(server); diff --git a/src/server/tools/general.js b/src/server/tools/general.js index e58a231..d85bde8 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -7,6 +7,8 @@ const WebSocket = require('ws'); require('../config/config'); require('../models/subscribers'); +const ImageDownloader = require('../modules/ImageDownloader'); + const printf = require('util').format; const { JSDOM } = require('jsdom'); @@ -53,7 +55,6 @@ const execPromise = util.promisify(exec); const { spawn } = require('child_process'); const readline = require('readline'); - // Code goes here const keySize = 256; // const ivSize = 128; @@ -69,515 +70,393 @@ if (!!process.env.GCM_API_KEY && process.env.GCM_API_KEY !== '') { // To Translate! const textlang = { it: { - 'L\'Email è già stata Verificata': 'L\'Email è già stata Verificata', + "L'Email è già stata Verificata": "L'Email è già stata Verificata", 'Nuova Registrazione': 'Nuova Registrazione', 'Effettuata una Nuova Registrazione': 'Effettuata una Nuova Registrazione', - 'partecipanti': 'partecipanti all\'Evento', + partecipanti: "partecipanti all'Evento", 'partecipanti a Pranzo': 'partecipanti a Pranzo', 'partecipanti a Cena': 'partecipanti a Cena', 'partecipanti a Cena Condivisa': 'partecipanti a Cena Condivisa', - 'TESTO_ASSISTENZA': '👉 Per entrare nel Sito\n\n' + + TESTO_ASSISTENZA: + '👉 Per entrare nel Sito\n\n' + '👉 Hai dimenticato la password?\n\n', - 'BENVENUTO': 'Benvenut@', - 'TUE_NAVI': 'Ecco le tue Navi programmate', - 'HAI_I_7_REQUISITI': 'PRIMI PASSI OK!\nHai i Primi Requisiti per Entrare nella Lista !', - 'NON_HAI_I_7_REQUISITI': 'Attenzione!\nAncora non hai i 7 Requisiti per Entrare nella Lista !', - 'INFO_LA_MIA_LAVAGNA': '✨ Lista dei Passi: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'Per completare tutti i requisiti vai sul sito:\n%s\n👉🏻 Entra nella tua Lavagna.\n', - 'INFO_LAVAGNA_SITO': 'Per vedere in dettaglio lo STATO, sul sito \n 👉🏻 Entra nella tua Lavagna.\n', - 'INFO_LINK_DA_CONDIVIDERE': 'Link da condividere ai tuoi invitati per farli registrare al sito:\n\n%s', - 'INFO_LINK_ZOOM': 'Link da condividere per partecipare allo Zoom (Conferenza OnLine):\n%s', - 'ZOOM_CONFERENCE': 'Ecco il programma delle Conferenze (Zoom) aperti a TUTTI:', - 'NON_VERIF': 'Non Verificata', - 'VERIF': 'Verificata', - 'EMAIL': 'Email', - 'BOT': 'BOT', - 'EMAIL_NON_VERIF': 'Email Non Verificata\nleggi la tua casella email e trova **"Confermare la Registrazione"**\ne clicca sul bottone **"Verifica Registrazione"**', - 'TELEGRAM_NOT_CONNECTED': 'Telegram non associato al tuo account!', - 'NESSUN_INVITATO': 'Non hai invitato nessuno', - 'ZOOM_PARTECIPATO': 'Partecipazione ad almeno 1 Conferenza (Zoom)', - 'LINEE_GUIDA': 'Accettato le Linee Guida', - 'VIDEO_INTRO': 'Visto il Video', - 'SCRITTO_SOGNO': 'Hai scritto il tuo Sogno', - 'PAYMENTS': 'Modalità di Pagamento', - 'INVITATI': 'persone registrate che hai invitato', - 'INVITATI_ATTIVI': 'Invitati con i 7 Requisiti', - 'NONREG': 'Invitati non Registrati', - 'CLICCA_PER_ZOOM': 'AL GIORNO E ORA INDICATA, PER ENTRARE NELLA VIDEO-CONFERENZA, CLICCA SUL LINK INDICATO', - 'CLICCA_ENTRA': 'CLICCA QUI PER ENTRARE !', - 'ZOOM_INIZIATO': 'QUESTA CONFERENZA E\' INIZIATA!', - 'SCEGLI_VOCE': 'scegli una voce:', - 'INVITATI_LISTA': 'I Tuoi Invitati (in verde con almeno i primi 7 Requisiti)', - 'CIAO': 'Ciao', - 'ADDED_TOLISTAINGRESSO': 'Complimenti! 🎊\nSei stato aggiunto alla Lista D\'Imbarco !\nNei prossimi giorni riceverai un messaggio qui quando la tua Nave sarà pronta a partire.\nRicorda che per salire di graduatoria, puoi condividere il Movimento con i tuoi amici ❤️.', - 'REGALATO_INVITANTE': 'da fare.... 😍🎊 Hai ricevuto in Regalo un Invitato {invitato} da parte di {mittente} !', - 'NO_PROG': 'Attualmente non sei ancora dentro alla Lista d\'Imbarco!', - 'SEND_LINK_CHAT_DONATORI': 'Ciao %s!\nLa tua NAVE sta finalmente Salpando!\nEntra nella Gift Chat della nave {%s} cliccando qui: %s', - 'SEND_LINK_CHAT_SOGNATORE': 'Ciao %s!\nOggi Diventi Sognatore !!! 🎊🎊🎊 Entra nella Gift Chat della nave {%s} cliccando qui: %s', - 'ENTRA_GIFT_CHAT': 'Entra nella Gift Chat', - 'DATA_PART_NAVE': 'data di Partenza della Nave:', - 'SOGNATORE': 'SOGNATORE', - 'INTERMEDIO': 'Intermedio', - 'MEDIATORE': 'MEDIATORE', - 'DONATORI': 'DONATORI', - 'RITESSITURA': 'RITESSITURA', + BENVENUTO: 'Benvenut@', + TUE_NAVI: 'Ecco le tue Navi programmate', + HAI_I_7_REQUISITI: 'PRIMI PASSI OK!\nHai i Primi Requisiti per Entrare nella Lista !', + NON_HAI_I_7_REQUISITI: 'Attenzione!\nAncora non hai i 7 Requisiti per Entrare nella Lista !', + INFO_LA_MIA_LAVAGNA: '✨ Lista dei Passi: ✨ \n', + INFO_LAVAGNA_SITO_COMPLETARE: + 'Per completare tutti i requisiti vai sul sito:\n%s\n👉🏻 Entra nella tua Lavagna.\n', + INFO_LAVAGNA_SITO: + 'Per vedere in dettaglio lo STATO, sul sito \n 👉🏻 Entra nella tua Lavagna.\n', + INFO_LINK_DA_CONDIVIDERE: 'Link da condividere ai tuoi invitati per farli registrare al sito:\n\n%s', + INFO_LINK_ZOOM: 'Link da condividere per partecipare allo Zoom (Conferenza OnLine):\n%s', + ZOOM_CONFERENCE: 'Ecco il programma delle Conferenze (Zoom) aperti a TUTTI:', + NON_VERIF: 'Non Verificata', + VERIF: 'Verificata', + EMAIL: 'Email', + BOT: 'BOT', + EMAIL_NON_VERIF: + 'Email Non Verificata\nleggi la tua casella email e trova **"Confermare la Registrazione"**\ne clicca sul bottone **"Verifica Registrazione"**', + TELEGRAM_NOT_CONNECTED: 'Telegram non associato al tuo account!', + NESSUN_INVITATO: 'Non hai invitato nessuno', + ZOOM_PARTECIPATO: 'Partecipazione ad almeno 1 Conferenza (Zoom)', + LINEE_GUIDA: 'Accettato le Linee Guida', + VIDEO_INTRO: 'Visto il Video', + SCRITTO_SOGNO: 'Hai scritto il tuo Sogno', + PAYMENTS: 'Modalità di Pagamento', + INVITATI: 'persone registrate che hai invitato', + INVITATI_ATTIVI: 'Invitati con i 7 Requisiti', + NONREG: 'Invitati non Registrati', + CLICCA_PER_ZOOM: 'AL GIORNO E ORA INDICATA, PER ENTRARE NELLA VIDEO-CONFERENZA, CLICCA SUL LINK INDICATO', + CLICCA_ENTRA: 'CLICCA QUI PER ENTRARE !', + ZOOM_INIZIATO: "QUESTA CONFERENZA E' INIZIATA!", + SCEGLI_VOCE: 'scegli una voce:', + INVITATI_LISTA: 'I Tuoi Invitati (in verde con almeno i primi 7 Requisiti)', + CIAO: 'Ciao', + ADDED_TOLISTAINGRESSO: + "Complimenti! 🎊\nSei stato aggiunto alla Lista D'Imbarco !\nNei prossimi giorni riceverai un messaggio qui quando la tua Nave sarà pronta a partire.\nRicorda che per salire di graduatoria, puoi condividere il Movimento con i tuoi amici ❤️.", + REGALATO_INVITANTE: 'da fare.... 😍🎊 Hai ricevuto in Regalo un Invitato {invitato} da parte di {mittente} !', + NO_PROG: "Attualmente non sei ancora dentro alla Lista d'Imbarco!", + SEND_LINK_CHAT_DONATORI: + 'Ciao %s!\nLa tua NAVE sta finalmente Salpando!\nEntra nella Gift Chat della nave {%s} cliccando qui: %s', + SEND_LINK_CHAT_SOGNATORE: + 'Ciao %s!\nOggi Diventi Sognatore !!! 🎊🎊🎊 Entra nella Gift Chat della nave {%s} cliccando qui: %s', + ENTRA_GIFT_CHAT: 'Entra nella Gift Chat', + DATA_PART_NAVE: 'data di Partenza della Nave:', + SOGNATORE: 'SOGNATORE', + INTERMEDIO: 'Intermedio', + MEDIATORE: 'MEDIATORE', + DONATORI: 'DONATORI', + RITESSITURA: 'RITESSITURA', 'NAVE COMPLETATA': 'NAVE COMPLETATA', 'Doni Effettuati': 'Doni Effettuati', 'Facilitatore che affianchèra il Mediatore': 'Facilitatore che affianchèra il Mediatore', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura GIFT CHAT\n%s Chiusura GIFT CHAT\nNota Bene: Hai tempo 3 giorni dall\'apertura per entrare in Chat ed effettuare il tuo Dono, dopodichè effettueremo la sostituzione.', + APERTURA_CHIUSURA_GIFT_CHAT: + "%s: Apertura GIFT CHAT\n%s Chiusura GIFT CHAT\nNota Bene: Hai tempo 3 giorni dall'apertura per entrare in Chat ed effettuare il tuo Dono, dopodichè effettueremo la sostituzione.", 'Giorno di Apertura GIFT CHAT': 'Giorno di Apertura GIFT CHAT', 'Giorno in cui Inviare il DONO': 'Hai 3 giorni di tempo per inviare il tuo dono.\nGiorno di Chiusura', - 'SPOSTATO': 'Sei stato Spostato in una Nuova Nave !', - 'Note': 'Note', - 'TEMPORANEA': 'TEMPORANEA', - 'NAVE': 'NAVE', - 'MSG_SEND_FROM': 'Msg Inviato da', - 'ZOOM_CONFERMATO': 'Sei stato confermato ad aver visto la Video Conferenza di Benvenuto!', - 'RICHIESTA_AMICIZIA': '🌈 Richiesta d\'Amicizia da parte di %s', - 'RICHIESTA_HANDSHAKE': '🌈 %s ha comunicato che ti conosce personalmente e ha fiducia in te.', - 'ACCETTATO_SUL_GRUPPO': '✅ Sei stato accettato da %s a far parte del Gruppo %s', - 'CREATO_NUOVO_GRUPPO': '✅ Hai appena creato un nuovo Gruppo chiamato %s', - 'ACCETTATO_NOTIFICA_ADMINS': '✅ l\'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)', - 'GROUP_REQUEST': 'Richiesta di entrare nel Gruppo %s da parte di %s', - "CLICCA_QUI": "CLICCA QUI", - "TELEFONO": "Tel", + SPOSTATO: 'Sei stato Spostato in una Nuova Nave !', + Note: 'Note', + TEMPORANEA: 'TEMPORANEA', + NAVE: 'NAVE', + MSG_SEND_FROM: 'Msg Inviato da', + ZOOM_CONFERMATO: 'Sei stato confermato ad aver visto la Video Conferenza di Benvenuto!', + RICHIESTA_AMICIZIA: "🌈 Richiesta d'Amicizia da parte di %s", + RICHIESTA_HANDSHAKE: '🌈 %s ha comunicato che ti conosce personalmente e ha fiducia in te.', + ACCETTATO_SUL_GRUPPO: '✅ Sei stato accettato da %s a far parte del Gruppo %s', + CREATO_NUOVO_GRUPPO: '✅ Hai appena creato un nuovo Gruppo chiamato %s', + ACCETTATO_NOTIFICA_ADMINS: "✅ l'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)", + GROUP_REQUEST: 'Richiesta di entrare nel Gruppo %s da parte di %s', + CLICCA_QUI: 'CLICCA QUI', + TELEFONO: 'Tel', }, si: {}, es: { - 'L\'Email è già stata Verificata': 'El correo electrónico ya ha sido verificado', + "L'Email è già stata Verificata": 'El correo electrónico ya ha sido verificado', 'Nuova Registrazione': 'Nuevo Registro', 'Effettuata una Nuova Registrazione': 'Se ha realizado un nuevo registro', - 'partecipanti': 'participantes', + partecipanti: 'participantes', 'partecipanti a Pranzo': 'partecipanti a Pranzo', 'partecipanti a Cena': 'partecipanti a Cena', - 'TESTO_ASSISTENZA': 'Para entrar en el sitio:\n%s\n\n' + + TESTO_ASSISTENZA: + 'Para entrar en el sitio:\n%s\n\n' + '¿Olvidó su contraseña para acceder al sitio?\nhttps://freeplanet.app/requestresetpwd\n\n', - 'BENVENUTO': 'Bienvenido', - 'TUE_NAVI': 'Aquí están sus naves programadas', - 'HAI_I_7_REQUISITI': '¡LOS PRIMEROS PASOS ESTÁN BIEN!\nTiene los primeros 7 requisitos para entrar en la lista de embarque!', - 'NON_HAI_I_7_REQUISITI': '¡Atención!\nTodavía no tienes los 7 requisitos para entrar en la lista de embarque!', - 'HAI_I_9_REQUISITI': '¡FELICITACIONES!\n¡Has completado los 9 pasos de la Guía! Gracias por ayudar a expandirse!', - 'NON_HAI_I_9_REQUISITI': 'Recuerda que puedes ayudar a que el Movimiento crezca y se expanda compartiendo nuestro viaje con todos.!', - 'INFO_LA_MIA_LAVAGNA': '✨ Lista de pasos: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'Para completar todos los requisitos vaya al sitio:\n%s\nPara ver el estado de su nave y sus invitados,👉🏻 Pizarra.\n', - 'INFO_LAVAGNA_SITO': 'Para ver en detalle el estado de su nave, en el sitio web, haga clic en las 3 líneas de la parte superior izquierda y vaya a "Pizarra"..\n', - 'INFO_LINK_DA_CONDIVIDERE': 'Enlaces para compartir con sus invitados para que se registren en el sitio web:\n\n%s', - 'INFO_LINK_ZOOM': 'Enlaces para compartir para participar en el Zoom (Conferencia en línea):\n%s', - 'ZOOM_CONFERENCE': 'Aquí puedes encontrar las fechas de programación en el Zoom:', - 'NON_VERIF': 'No verificado', - 'VERIF': 'Verificado', - 'EMAIL': 'Email', - 'BOT': 'BOT', - 'EMAIL_NON_VERIF': 'Correo electrónico no verificado\nlea su buzón y encuentre **"Confirmar Registro "** y haga clic en el botón **"Verificar Registro "**.', - 'TELEGRAM_NOT_CONNECTED': 'Telegram no asociado a su cuenta!', - 'NESSUN_INVITATO': 'No invitaste a nadie', - 'ZOOM_PARTECIPATO': 'Participación en al menos 1 Conferencia (Zoom)', - 'LINEE_GUIDA': 'Directrices aceptadas', - 'VIDEO_INTRO': 'Ver el video', - 'SCRITTO_SOGNO': 'Escribiste tu sueño', - 'PAYMENTS': 'Métodos de pago', - 'INVITATI': 'las personas registradas que usted invitó', - 'INVITATI_ATTIVI': 'Invitado con los 7 requisitos', - 'NONREG': 'Invitados no registrados', - 'CLICCA_PER_ZOOM': 'AL DÍA Y HORA INDICADOS, PARA ENTRAR EN LA VIDEOCONFERENCIA, PULSE AQUÍ', - 'CLICCA_ENTRA': 'HAGA CLIC AQUÍ PARA ENTRAR !', - 'ZOOM_INIZIATO': 'ESTA CONFERENCIA HA COMENZADO!', - 'SCEGLI_VOCE': 'elegir una voz:', - 'INVITATI_LISTA': 'Sus invitados (en verde con al menos los 7 primeros requisitos)', - 'CIAO': 'Hola', - 'ADDED_TOLISTAINGRESSO': 'Has sido añadido a la lista de personas que entrarán en Lista de embarque!', - 'NO_PROG': 'Actualmente no está en la lista de embarque.!', - 'SEND_LINK_CHAT_DONATORI': 'Hola %s!\n¡Tu barco por fin está navegando!\nEntra en el Gift Chat haciendo clic aquí: %s', - 'SEND_LINK_CHAT_SOGNATORE': '¡Hola!\n¡Hoy te conviertes en un soñador! 🎊🎊🎊 Entre en el Chat de Regalos de la nave {%s} haciendo clic aquí: %s', - 'ENTRA_GIFT_CHAT': 'Entre en el Chat de Regalos', - 'DATA_PART_NAVE': 'fecha de salida de la nave:', - 'SOGNATORE': 'SOÑADOR', - 'INTERMEDIO': 'Intermedio', - 'MEDIATORE': 'MEDIATOR', - 'DONATORI': 'DONANTES', - 'RITESSITURA': 'RETEJIDO', + BENVENUTO: 'Bienvenido', + TUE_NAVI: 'Aquí están sus naves programadas', + HAI_I_7_REQUISITI: + '¡LOS PRIMEROS PASOS ESTÁN BIEN!\nTiene los primeros 7 requisitos para entrar en la lista de embarque!', + NON_HAI_I_7_REQUISITI: '¡Atención!\nTodavía no tienes los 7 requisitos para entrar en la lista de embarque!', + HAI_I_9_REQUISITI: '¡FELICITACIONES!\n¡Has completado los 9 pasos de la Guía! Gracias por ayudar a expandirse!', + NON_HAI_I_9_REQUISITI: + 'Recuerda que puedes ayudar a que el Movimiento crezca y se expanda compartiendo nuestro viaje con todos.!', + INFO_LA_MIA_LAVAGNA: '✨ Lista de pasos: ✨ \n', + INFO_LAVAGNA_SITO_COMPLETARE: + 'Para completar todos los requisitos vaya al sitio:\n%s\nPara ver el estado de su nave y sus invitados,👉🏻 Pizarra.\n', + INFO_LAVAGNA_SITO: + 'Para ver en detalle el estado de su nave, en el sitio web, haga clic en las 3 líneas de la parte superior izquierda y vaya a "Pizarra"..\n', + INFO_LINK_DA_CONDIVIDERE: 'Enlaces para compartir con sus invitados para que se registren en el sitio web:\n\n%s', + INFO_LINK_ZOOM: 'Enlaces para compartir para participar en el Zoom (Conferencia en línea):\n%s', + ZOOM_CONFERENCE: 'Aquí puedes encontrar las fechas de programación en el Zoom:', + NON_VERIF: 'No verificado', + VERIF: 'Verificado', + EMAIL: 'Email', + BOT: 'BOT', + EMAIL_NON_VERIF: + 'Correo electrónico no verificado\nlea su buzón y encuentre **"Confirmar Registro "** y haga clic en el botón **"Verificar Registro "**.', + TELEGRAM_NOT_CONNECTED: 'Telegram no asociado a su cuenta!', + NESSUN_INVITATO: 'No invitaste a nadie', + ZOOM_PARTECIPATO: 'Participación en al menos 1 Conferencia (Zoom)', + LINEE_GUIDA: 'Directrices aceptadas', + VIDEO_INTRO: 'Ver el video', + SCRITTO_SOGNO: 'Escribiste tu sueño', + PAYMENTS: 'Métodos de pago', + INVITATI: 'las personas registradas que usted invitó', + INVITATI_ATTIVI: 'Invitado con los 7 requisitos', + NONREG: 'Invitados no registrados', + CLICCA_PER_ZOOM: 'AL DÍA Y HORA INDICADOS, PARA ENTRAR EN LA VIDEOCONFERENCIA, PULSE AQUÍ', + CLICCA_ENTRA: 'HAGA CLIC AQUÍ PARA ENTRAR !', + ZOOM_INIZIATO: 'ESTA CONFERENCIA HA COMENZADO!', + SCEGLI_VOCE: 'elegir una voz:', + INVITATI_LISTA: 'Sus invitados (en verde con al menos los 7 primeros requisitos)', + CIAO: 'Hola', + ADDED_TOLISTAINGRESSO: 'Has sido añadido a la lista de personas que entrarán en Lista de embarque!', + NO_PROG: 'Actualmente no está en la lista de embarque.!', + SEND_LINK_CHAT_DONATORI: + 'Hola %s!\n¡Tu barco por fin está navegando!\nEntra en el Gift Chat haciendo clic aquí: %s', + SEND_LINK_CHAT_SOGNATORE: + '¡Hola!\n¡Hoy te conviertes en un soñador! 🎊🎊🎊 Entre en el Chat de Regalos de la nave {%s} haciendo clic aquí: %s', + ENTRA_GIFT_CHAT: 'Entre en el Chat de Regalos', + DATA_PART_NAVE: 'fecha de salida de la nave:', + SOGNATORE: 'SOÑADOR', + INTERMEDIO: 'Intermedio', + MEDIATORE: 'MEDIATOR', + DONATORI: 'DONANTES', + RITESSITURA: 'RETEJIDO', 'NAVE COMPLETATA': 'NAVE COMPLETADA', 'Doni Effettuati': 'Regalos Realizados', 'Facilitatore che affianchèra il Mediatore': 'Facilitatore de apoyo al Donante', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura del CHAT DE REGALOS\n%s Cierre del CHAT DE REGALOS\nNota: Tienes 3 días desde la apertura para entrar en el Chat y hacer tu Regalo, después de lo cual haremos el reemplazo', - 'SPOSTATO': 'Has sido trasladado a una nueva nave !', - 'Note': 'Notas', - 'TEMPORANEA': 'TEMPORAL', - 'NAVE': 'NAVE', - 'MSG_SEND_FROM': 'Mensaje enviado por', - 'ZOOM_CONFERMATO': '¡Se ha confirmado que ha visto la Video Conferencia de Bienvenida!', - 'RICHIESTA_AMICIZIA': 'Richiesta d\'Amicizia da parte di %s', - 'ACCETTATO_SUL_GRUPPO': 'Sei stato accettato da %s a far parte del Gruppo %s', - 'ACCETTATO_NOTIFICA_ADMINS': 'l\'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)', - 'RICHIESTA_BLOCCO_GRUPPO': 'Richiesta di bloccare il Gruppo %s da parte di %s', + APERTURA_CHIUSURA_GIFT_CHAT: + '%s: Apertura del CHAT DE REGALOS\n%s Cierre del CHAT DE REGALOS\nNota: Tienes 3 días desde la apertura para entrar en el Chat y hacer tu Regalo, después de lo cual haremos el reemplazo', + SPOSTATO: 'Has sido trasladado a una nueva nave !', + Note: 'Notas', + TEMPORANEA: 'TEMPORAL', + NAVE: 'NAVE', + MSG_SEND_FROM: 'Mensaje enviado por', + ZOOM_CONFERMATO: '¡Se ha confirmado que ha visto la Video Conferencia de Bienvenida!', + RICHIESTA_AMICIZIA: "Richiesta d'Amicizia da parte di %s", + ACCETTATO_SUL_GRUPPO: 'Sei stato accettato da %s a far parte del Gruppo %s', + ACCETTATO_NOTIFICA_ADMINS: "l'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)", + RICHIESTA_BLOCCO_GRUPPO: 'Richiesta di bloccare il Gruppo %s da parte di %s', }, enUs: { - 'partecipanti': 'participants', + partecipanti: 'participants', 'partecipanti a Pranzo': 'partecipanti a Pranzo', 'partecipanti a Cena': 'partecipanti a Cena', - 'TESTO_ASSISTENZA': 'To enter the Site:\n%s\n\nForgot your password to access the site?\n' + + TESTO_ASSISTENZA: + 'To enter the Site:\n%s\n\nForgot your password to access the site?\n' + 'https://freeplanet.app/requestresetpwd\nChat AYNI BOT (this one):\nhttps://t.me/notevoleaynibot\n\n', - 'BENVENUTO': 'Welcome', - 'TUE_NAVI': 'Here are your programmed ships', - 'HAI_I_7_REQUISITI': 'FIRST STEPS OK!\nYou have the First 7 Requirements to Enter the Boarding List!', - 'NON_HAI_I_7_REQUISITI': 'Attention!\nYou still do not have the 7 requirements to enter the boarding list!', - 'INFO_LA_MIA_LAVAGNA': '✨ Step List: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'To complete all the requirements go to the site:%s\nTo see the status of your Ship and your guests\n👉🏻 Dashboard\n', - 'INFO_LAVAGNA_SITO': 'To see in detail the status of your ship, on the website, click on the 3 lines at the top left and go to "Blackboard".\n', - 'INFO_LINK_DA_CONDIVIDERE': 'Links to share with your guests to have them register on website:\n\n%s', - 'INFO_LINK_ZOOM': 'Links to share to participate in Zoom (Online Conference):\n%s', - 'ZOOM_CONFERENCE': 'Here you can find the Zoom Conference Planning:', - 'NON_VERIF': 'Not Verified', - 'VERIF': 'Verified', - 'EMAIL': 'Email', - 'BOT': 'BOT', - 'EMAIL_NON_VERIF': 'Email Not Verified\nread your mailbox and find **"Confirm Registration "**
and click on the button **"Verify Registration "**.', - 'TELEGRAM_NOT_CONNECTED': 'Telegram not associated with your account!', - 'NESSUN_INVITATO': 'You didn\'t invite anyone', - 'ZOOM_PARTECIPATO': 'Participation in at least 1 Conference (Zoom)', - 'LINEE_GUIDA': 'Guidelines Accepted', - 'VIDEO_INTRO': 'Seen the Video', - 'SCRITTO_SOGNO': 'You wrote your Dream', - 'PAYMENTS': 'Methods of Payment', - 'INVITATI': 'registered people you invited', - 'INVITATI_ATTIVI': 'Guests with the 7 Requirements', - 'NONREG': 'Non-registered Guests', - 'CLICCA_PER_ZOOM': 'TO THE DAY AND TIME INDICATED, TO ENTER THE VIDEO-CONFERENCE, CLICK HERE', - 'CLICCA_ENTRA': 'CLICK HERE TO ENTER !', - 'ZOOM_INIZIATO': 'THIS CONFERENCE HAS BEGUN!', - 'SCEGLI_VOCE': 'choose a menu item:', - 'INVITATI_LISTA': 'Your Guests (in green with at least the first 7 requirements)', - 'CIAO': 'Hi', - 'ADDED_TOLISTAINGRESSO': 'You have been added to the List of people who will enter the Boarding List!', - 'NO_PROG': 'You are not currently on the boarding list.!', - 'SEND_LINK_CHAT_DONATORI': 'Hi %s!\nYour ship is finally sailing!\nEnter the Gift Chat by clicking here: %s', - 'SEND_LINK_CHAT_SOGNATORE': 'Hello %s!\nToday you become a Dreamer! 🎊🎊🎊 Enter the ship\'s Gift Chat {%s} by clicking here: %s', - 'ENTRA_GIFT_CHAT': 'Enter the ship\'s Gift Chat', - 'DATA_PART_NAVE': 'date of departure of the ship:', - 'SOGNATORE': 'DREAMER', - 'INTERMEDIO': 'Intermediate', - 'MEDIATORE': 'MEDIATOR', - 'DONATORI': 'DONOR', - 'RITESSITURA': 'RE-ENTER', + BENVENUTO: 'Welcome', + TUE_NAVI: 'Here are your programmed ships', + HAI_I_7_REQUISITI: 'FIRST STEPS OK!\nYou have the First 7 Requirements to Enter the Boarding List!', + NON_HAI_I_7_REQUISITI: 'Attention!\nYou still do not have the 7 requirements to enter the boarding list!', + INFO_LA_MIA_LAVAGNA: '✨ Step List: ✨ \n', + INFO_LAVAGNA_SITO_COMPLETARE: + 'To complete all the requirements go to the site:%s\nTo see the status of your Ship and your guests\n👉🏻 Dashboard\n', + INFO_LAVAGNA_SITO: + 'To see in detail the status of your ship, on the website, click on the 3 lines at the top left and go to "Blackboard".\n', + INFO_LINK_DA_CONDIVIDERE: 'Links to share with your guests to have them register on website:\n\n%s', + INFO_LINK_ZOOM: 'Links to share to participate in Zoom (Online Conference):\n%s', + ZOOM_CONFERENCE: 'Here you can find the Zoom Conference Planning:', + NON_VERIF: 'Not Verified', + VERIF: 'Verified', + EMAIL: 'Email', + BOT: 'BOT', + EMAIL_NON_VERIF: + 'Email Not Verified\nread your mailbox and find **"Confirm Registration "**
and click on the button **"Verify Registration "**.', + TELEGRAM_NOT_CONNECTED: 'Telegram not associated with your account!', + NESSUN_INVITATO: "You didn't invite anyone", + ZOOM_PARTECIPATO: 'Participation in at least 1 Conference (Zoom)', + LINEE_GUIDA: 'Guidelines Accepted', + VIDEO_INTRO: 'Seen the Video', + SCRITTO_SOGNO: 'You wrote your Dream', + PAYMENTS: 'Methods of Payment', + INVITATI: 'registered people you invited', + INVITATI_ATTIVI: 'Guests with the 7 Requirements', + NONREG: 'Non-registered Guests', + CLICCA_PER_ZOOM: 'TO THE DAY AND TIME INDICATED, TO ENTER THE VIDEO-CONFERENCE, CLICK HERE', + CLICCA_ENTRA: 'CLICK HERE TO ENTER !', + ZOOM_INIZIATO: 'THIS CONFERENCE HAS BEGUN!', + SCEGLI_VOCE: 'choose a menu item:', + INVITATI_LISTA: 'Your Guests (in green with at least the first 7 requirements)', + CIAO: 'Hi', + ADDED_TOLISTAINGRESSO: 'You have been added to the List of people who will enter the Boarding List!', + NO_PROG: 'You are not currently on the boarding list.!', + SEND_LINK_CHAT_DONATORI: 'Hi %s!\nYour ship is finally sailing!\nEnter the Gift Chat by clicking here: %s', + SEND_LINK_CHAT_SOGNATORE: + "Hello %s!\nToday you become a Dreamer! 🎊🎊🎊 Enter the ship's Gift Chat {%s} by clicking here: %s", + ENTRA_GIFT_CHAT: "Enter the ship's Gift Chat", + DATA_PART_NAVE: 'date of departure of the ship:', + SOGNATORE: 'DREAMER', + INTERMEDIO: 'Intermediate', + MEDIATORE: 'MEDIATOR', + DONATORI: 'DONOR', + RITESSITURA: 'RE-ENTER', 'NAVE COMPLETATA': 'SHIP COMPLETED', 'Doni Effettuati': 'Gifts Made', 'Facilitatore che affianchèra il Mediatore': 'Facilitatore supporting the Mediator', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Opening GIFT CHAT\n%s Closing GIFT CHAT\nNote: You have 3 days from the opening to enter the Chat and make your Gift, after which we will make the replacement.', - 'SPOSTATO': 'You\'ve been moved to a New Ship !', - 'Note': 'Note', - 'TEMPORANEA': 'TEMPORARY', - 'NAVE': 'SHIP', - 'MSG_SEND_FROM': 'Msg sent by', - 'ZOOM_CONFERMATO': 'You have been confirmed to have seen the Welcome Video Conference!', - 'RICHIESTA_AMICIZIA': 'Richiesta d\'Amicizia da parte di %s', - 'ACCETTATO_SUL_GRUPPO': 'Sei stato accettato da %s a far parte del Gruppo %s', - 'ACCETTATO_NOTIFICA_ADMINS': 'l\'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)', - 'RICHIESTA_BLOCCO_GRUPPO': 'Richiesta di bloccare il Gruppo %s da parte di %s', + APERTURA_CHIUSURA_GIFT_CHAT: + '%s: Opening GIFT CHAT\n%s Closing GIFT CHAT\nNote: You have 3 days from the opening to enter the Chat and make your Gift, after which we will make the replacement.', + SPOSTATO: "You've been moved to a New Ship !", + Note: 'Note', + TEMPORANEA: 'TEMPORARY', + NAVE: 'SHIP', + MSG_SEND_FROM: 'Msg sent by', + ZOOM_CONFERMATO: 'You have been confirmed to have seen the Welcome Video Conference!', + RICHIESTA_AMICIZIA: "Richiesta d'Amicizia da parte di %s", + ACCETTATO_SUL_GRUPPO: 'Sei stato accettato da %s a far parte del Gruppo %s', + ACCETTATO_NOTIFICA_ADMINS: "l'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)", + RICHIESTA_BLOCCO_GRUPPO: 'Richiesta di bloccare il Gruppo %s da parte di %s', }, fr: { - 'L\'Email è già stata Verificata': 'Le courrier électronique a déjà été vérifié', + "L'Email è già stata Verificata": 'Le courrier électronique a déjà été vérifié', 'Nuova Registrazione': 'Nouvelle inscription', 'Effettuata una Nuova Registrazione': 'Un nouvel enregistrement a été effectué', - 'partecipanti': 'participants', + partecipanti: 'participants', 'partecipanti a Pranzo': 'partecipanti a Pranzo', 'partecipanti a Cena': 'partecipanti a Cena', - 'TESTO_ASSISTENZA': 'Pour entrer sur le site:\n%s\n\n' + + TESTO_ASSISTENZA: + 'Pour entrer sur le site:\n%s\n\n' + 'Vous avez oublié votre mot de passe pour accéder au site ?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n', - 'BENVENUTO': 'Bienvenue', - 'TUE_NAVI': 'Voici vos navires programmés', - 'HAI_I_7_REQUISITI': 'PREMIÈRES ÉTAPES OK!\nvous avez les 7 premiers Requis pour Entrer dans la liste d\'embarquement!', - 'NON_HAI_I_7_REQUISITI': '\'Attention!\nVous ne remplissez pas encore les 7 conditions pour figurer sur la liste d\'embarquement!', - 'HAI_I_9_REQUISITI': 'FÉLICITATIONS!\n!Vous avez franchi les 9 étapes de la conduite ! Merci d\'avoir aidé à se développer!', - 'NON_HAI_I_9_REQUISITI': 'N\'oubliez pas que vous pouvez aider le Mouvement à grandir et à se développer en partageant notre voyage avec tout le monde.!', - 'INFO_LA_MIA_LAVAGNA': '✨ Liste des étapes: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'Pour remplir toutes les conditions, rendez-vous sur le site:\n%s\nPour voir le statut de votre navire et de vos invités\n 👉🏻 Tableau.\n', - 'INFO_LAVAGNA_SITO': 'Pour voir en détail le statut de votre navire, sur le site, cliquez sur les 3 lignes en haut à gauche et allez sur "Tableau".\n', - 'INFO_LINK_DA_CONDIVIDERE': 'Liens à partager avec vos invités pour qu\'ils s\'inscrivent sur le site web:\n\n%s', - 'INFO_LINK_ZOOM': 'Liens à partager pour participer à Zoom (Conférence en ligne):\n%s', - 'ZOOM_CONFERENCE': 'Vous trouverez ici les dates de programmation sur Zoom:', - 'NON_VERIF': 'Non vérifié', - 'VERIF': 'Vérifié', - 'EMAIL': 'Courriel', - 'BOT': 'BOT', - 'EMAIL_NON_VERIF': 'Courriel non vérifié\nlisez votre boîte aux lettres et trouvez **"Confirmer l\'inscription "**
et cliquez sur le bouton **"Vérifier l\'inscription "**.', - 'TELEGRAM_NOT_CONNECTED': 'Télégramme non associé à votre compte!', - 'NESSUN_INVITATO': 'Vous n\'avez invité personne', - 'ZOOM_PARTECIPATO': 'Participation à au moins 1 conférence (Zoom)', - 'LINEE_GUIDA': 'Lignes directrices acceptées', - 'VIDEO_INTRO': 'Voir la vidéo', - 'SCRITTO_SOGNO': 'Vous avez écrit votre rêve', - 'PAYMENTS': 'Modes de paiement', - 'INVITATI': 'personnes inscrites que vous avez invitées', - 'INVITATI_ATTIVI': 'Invité avec les 7 exigences', - 'NONREG': 'Invités non enregistrés', - 'CLICCA_PER_ZOOM': 'AU JOUR ET À L\'HEURE INDIQUÉS, POUR ENTRER DANS LA VIDÉOCONFÉRENCE, CLIQUEZ ICI', - 'CLICCA_ENTRA': 'CLIQUEZ ICI POUR ENTRER !', - 'ZOOM_INIZIATO': 'CETTE CONFÉRENCE A COMMENCÉ!', - 'SCEGLI_VOCE': 'choisir une voix:', - 'INVITATI_LISTA': 'Vos invités (en vert avec au moins les 7 premières exigences)', - 'CIAO': 'Salut', - 'ADDED_TOLISTAINGRESSO': 'Vous avez été ajouté à la liste d\'embarquement !', - 'NO_PROG': 'Vous n\'êtes pas encore sur la liste d\'embarquement.!', - 'SEND_LINK_CHAT_DONATORI': 'Salut %s!\nVotre SHIP prend enfin la mer.!\nEntrez dans le Chat Cadeau en cliquant ici: %s', - 'SEND_LINK_CHAT_SOGNATORE': 'Bonjour %s !\nAujourd\'hui, vous devenez un Rêveur ! 🎊🎊🎊 Entrez dans le chat des cadeaux du navire {%s} en cliquant ici : %s', - 'ENTRA_GIFT_CHAT': 'Entrez dans le chat des cadeaux', - 'DATA_PART_NAVE': 'la date de départ du navire:', - 'SOGNATORE': 'Rêveur', - 'INTERMEDIO': 'Intermediaire', - 'MEDIATORE': 'Médiateur', - 'DONATORI': 'DONATEUR', - 'RITESSITURA': 'RETESSITURA', + BENVENUTO: 'Bienvenue', + TUE_NAVI: 'Voici vos navires programmés', + HAI_I_7_REQUISITI: + "PREMIÈRES ÉTAPES OK!\nvous avez les 7 premiers Requis pour Entrer dans la liste d'embarquement!", + NON_HAI_I_7_REQUISITI: + "'Attention!\nVous ne remplissez pas encore les 7 conditions pour figurer sur la liste d'embarquement!", + HAI_I_9_REQUISITI: + "FÉLICITATIONS!\n!Vous avez franchi les 9 étapes de la conduite ! Merci d'avoir aidé à se développer!", + NON_HAI_I_9_REQUISITI: + "N'oubliez pas que vous pouvez aider le Mouvement à grandir et à se développer en partageant notre voyage avec tout le monde.!", + INFO_LA_MIA_LAVAGNA: '✨ Liste des étapes: ✨ \n', + INFO_LAVAGNA_SITO_COMPLETARE: + 'Pour remplir toutes les conditions, rendez-vous sur le site:\n%s\nPour voir le statut de votre navire et de vos invités\n 👉🏻 Tableau.\n', + INFO_LAVAGNA_SITO: + 'Pour voir en détail le statut de votre navire, sur le site, cliquez sur les 3 lignes en haut à gauche et allez sur "Tableau".\n', + INFO_LINK_DA_CONDIVIDERE: "Liens à partager avec vos invités pour qu'ils s'inscrivent sur le site web:\n\n%s", + INFO_LINK_ZOOM: 'Liens à partager pour participer à Zoom (Conférence en ligne):\n%s', + ZOOM_CONFERENCE: 'Vous trouverez ici les dates de programmation sur Zoom:', + NON_VERIF: 'Non vérifié', + VERIF: 'Vérifié', + EMAIL: 'Courriel', + BOT: 'BOT', + EMAIL_NON_VERIF: + 'Courriel non vérifié\nlisez votre boîte aux lettres et trouvez **"Confirmer l\'inscription "**
et cliquez sur le bouton **"Vérifier l\'inscription "**.', + TELEGRAM_NOT_CONNECTED: 'Télégramme non associé à votre compte!', + NESSUN_INVITATO: "Vous n'avez invité personne", + ZOOM_PARTECIPATO: 'Participation à au moins 1 conférence (Zoom)', + LINEE_GUIDA: 'Lignes directrices acceptées', + VIDEO_INTRO: 'Voir la vidéo', + SCRITTO_SOGNO: 'Vous avez écrit votre rêve', + PAYMENTS: 'Modes de paiement', + INVITATI: 'personnes inscrites que vous avez invitées', + INVITATI_ATTIVI: 'Invité avec les 7 exigences', + NONREG: 'Invités non enregistrés', + CLICCA_PER_ZOOM: "AU JOUR ET À L'HEURE INDIQUÉS, POUR ENTRER DANS LA VIDÉOCONFÉRENCE, CLIQUEZ ICI", + CLICCA_ENTRA: 'CLIQUEZ ICI POUR ENTRER !', + ZOOM_INIZIATO: 'CETTE CONFÉRENCE A COMMENCÉ!', + SCEGLI_VOCE: 'choisir une voix:', + INVITATI_LISTA: 'Vos invités (en vert avec au moins les 7 premières exigences)', + CIAO: 'Salut', + ADDED_TOLISTAINGRESSO: "Vous avez été ajouté à la liste d'embarquement !", + NO_PROG: "Vous n'êtes pas encore sur la liste d'embarquement.!", + SEND_LINK_CHAT_DONATORI: + 'Salut %s!\nVotre SHIP prend enfin la mer.!\nEntrez dans le Chat Cadeau en cliquant ici: %s', + SEND_LINK_CHAT_SOGNATORE: + "Bonjour %s !\nAujourd'hui, vous devenez un Rêveur ! 🎊🎊🎊 Entrez dans le chat des cadeaux du navire {%s} en cliquant ici : %s", + ENTRA_GIFT_CHAT: 'Entrez dans le chat des cadeaux', + DATA_PART_NAVE: 'la date de départ du navire:', + SOGNATORE: 'Rêveur', + INTERMEDIO: 'Intermediaire', + MEDIATORE: 'Médiateur', + DONATORI: 'DONATEUR', + RITESSITURA: 'RETESSITURA', 'NAVE COMPLETATA': 'NAVIRE COMPLÉTÉ', 'Doni Effettuati': 'Don effectués', 'Facilitatore che affianchèra il Mediatore': 'Le tuteur qui soutient le Mediateur', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s : Chat d\'ouverture\n%s Clôture du GIFT CHAT\nNote: Vous avez 3 jours à partir de l\'ouverture pour entrer dans le Chat et faire votre Cadeau, après quoi nous ferons le remplacement', - 'SPOSTATO': 'Vous avez été transféré sur un nouveau navire !', - 'Note': 'Notes', - 'TEMPORANEA': 'TEMPORAIRE', - 'NAVE': 'NAVIRE', - 'MSG_SEND_FROM': 'Message envoyé par', - 'ZOOM_CONFERMATO': 'Vous avez été confirmé comme ayant vu la vidéoconférence de bienvenue !', - 'RICHIESTA_AMICIZIA': 'Richiesta d\'Amicizia da parte di %s', - 'ACCETTATO_SUL_GRUPPO': 'Sei stato accettato da %s a far parte del Gruppo %s', - 'ACCETTATO_NOTIFICA_ADMINS': 'l\'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)', - 'RICHIESTA_BLOCCO_GRUPPO': 'Richiesta di bloccare il Gruppo %s da parte di %s', + APERTURA_CHIUSURA_GIFT_CHAT: + "%s : Chat d'ouverture\n%s Clôture du GIFT CHAT\nNote: Vous avez 3 jours à partir de l'ouverture pour entrer dans le Chat et faire votre Cadeau, après quoi nous ferons le remplacement", + SPOSTATO: 'Vous avez été transféré sur un nouveau navire !', + Note: 'Notes', + TEMPORANEA: 'TEMPORAIRE', + NAVE: 'NAVIRE', + MSG_SEND_FROM: 'Message envoyé par', + ZOOM_CONFERMATO: 'Vous avez été confirmé comme ayant vu la vidéoconférence de bienvenue !', + RICHIESTA_AMICIZIA: "Richiesta d'Amicizia da parte di %s", + ACCETTATO_SUL_GRUPPO: 'Sei stato accettato da %s a far parte del Gruppo %s', + ACCETTATO_NOTIFICA_ADMINS: "l'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)", + RICHIESTA_BLOCCO_GRUPPO: 'Richiesta di bloccare il Gruppo %s da parte di %s', }, pt: { - 'L\'Email è già stata Verificata': '', + "L'Email è già stata Verificata": '', 'Nuova Registrazione': 'Novo Registo', 'Effettuata una Nuova Registrazione': 'Foi efectuado um novo registo', - 'partecipanti': 'participantes', + partecipanti: 'participantes', 'partecipanti a Pranzo': 'partecipanti a Pranzo', 'partecipanti a Cena': 'partecipanti a Cena', - 'TESTO_ASSISTENZA': 'Para entrar no site:\n%s\n\n' + + TESTO_ASSISTENZA: + 'Para entrar no site:\n%s\n\n' + 'Esqueceu sua senha para acessar o site?\nhttps://freeplanet.app/requestresetpwd\n\n', - 'BENVENUTO': 'Bem-vindo', - 'TUE_NAVI': 'Aqui estão os seus navios programados', - 'HAI_I_7_REQUISITI': 'PRIMEIROS PASSOS OK!\nVocê tem os 7 primeiros requisitos para entrar na lista de embarque!', - 'NON_HAI_I_7_REQUISITI': 'Atenção!\nVocê ainda não tem os 7 requisitos para entrar na lista de embarque!', - 'INFO_LA_MIA_LAVAGNA': '✨ Lista de etapas: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'Para completar todos os requisitos ir para o sitio:\n%s\nPara ver o estado do seu navio e dos seus convidados:\n 👉🏻 Entre no seu Tablero.\n', - 'INFO_LAVAGNA_SITO': 'Para ver em detalhe o estado do seu navio, no site, clique nas 3 linhas no canto superior esquerdo e vá para "DashBoard"..\n', - 'INFO_LINK_DA_CONDIVIDERE': 'Links para partilhar com os seus convidados para que se registem no website:\n\n%s', - 'INFO_LINK_ZOOM': 'Links para partilhar para participar na Zoom (Conferência Online):\n%s', - 'ZOOM_CONFERENCE': 'Aqui está o programa das Conferências (Zoom) aberto a TODOS:', - 'NON_VERIF': 'Não verificado', - 'VERIF': 'Verificado', - 'EMAIL': 'Email', - 'BOT': 'BOT', - 'EMAIL_NON_VERIF': 'Email Não verificado\nleia a sua caixa de correio e encontre **"Confirmar o registo"**
e clique no botão **"Verificação do registo"**', - 'TELEGRAM_NOT_CONNECTED': 'Telegrama não associado à sua conta!', - 'NESSUN_INVITATO': 'Você não convidou ninguém', - 'ZOOM_PARTECIPATO': 'Participação em pelo menos 1 Conferência (Zoom)', - 'LINEE_GUIDA': 'Directrizes Aceites', - 'VIDEO_INTRO': 'Ver o vídeo', - 'SCRITTO_SOGNO': 'Você escreveu o seu sonho', - 'PAYMENTS': 'Formas de pagamento', - 'INVITATI': 'pessoas registadas que convidou', - 'INVITATI_ATTIVI': 'Convidado com os 7 Requisitos', - 'NONREG': 'Convidados não registados', - 'CLICCA_PER_ZOOM': 'PARA O DIA E HORA INDICADOS, PARA ENTRAR NA VÍDEO-CONFERÊNCIA, CLIQUE AQUI', - 'CLICCA_ENTRA': 'CLIQUE AQUI PARA ENTRAR !', - 'ZOOM_INIZIATO': 'ESTA CONFERÊNCIA JÁ COMEÇOU!', - 'SCEGLI_VOCE': 'escolha uma voz:', - 'INVITATI_LISTA': 'Os seus convidados (em verde com, pelo menos, os 7 primeiros requisitos)', - 'CIAO': 'Olá', - 'ADDED_TOLISTAINGRESSO': 'Foi acrescentado à Lista de Embarque !', - 'NO_PROG': 'Actualmente, ainda não consta da lista de embarque.!', - 'SEND_LINK_CHAT_DONATORI': 'Olà %s!\nO seu SHIP está finalmente a zarpar.!\nEntre no Gift Chat, clicando aqui: %s', - 'SEND_LINK_CHAT_SOGNATORE': 'Olá %s!\nHoje você se torna um sonhador! 🎊🎊🎊 Entre no Gift Chat do navio {%s} clicando aqui: %s', - 'ENTRA_GIFT_CHAT': 'Entre no Gift Chat do navio', - 'DATA_PART_NAVE': 'data de partida do navio:', - 'SOGNATORE': 'SONHEIROS', - 'INTERMEDIO': 'Intermediar', - 'MEDIATORE': 'MEDIATOR', - 'DONATORI': 'DONATORES', - 'RITESSITURA': 'ENTRE EM', + BENVENUTO: 'Bem-vindo', + TUE_NAVI: 'Aqui estão os seus navios programados', + HAI_I_7_REQUISITI: 'PRIMEIROS PASSOS OK!\nVocê tem os 7 primeiros requisitos para entrar na lista de embarque!', + NON_HAI_I_7_REQUISITI: 'Atenção!\nVocê ainda não tem os 7 requisitos para entrar na lista de embarque!', + INFO_LA_MIA_LAVAGNA: '✨ Lista de etapas: ✨ \n', + INFO_LAVAGNA_SITO_COMPLETARE: + 'Para completar todos os requisitos ir para o sitio:\n%s\nPara ver o estado do seu navio e dos seus convidados:\n 👉🏻 Entre no seu Tablero.\n', + INFO_LAVAGNA_SITO: + 'Para ver em detalhe o estado do seu navio, no site, clique nas 3 linhas no canto superior esquerdo e vá para "DashBoard"..\n', + INFO_LINK_DA_CONDIVIDERE: 'Links para partilhar com os seus convidados para que se registem no website:\n\n%s', + INFO_LINK_ZOOM: 'Links para partilhar para participar na Zoom (Conferência Online):\n%s', + ZOOM_CONFERENCE: 'Aqui está o programa das Conferências (Zoom) aberto a TODOS:', + NON_VERIF: 'Não verificado', + VERIF: 'Verificado', + EMAIL: 'Email', + BOT: 'BOT', + EMAIL_NON_VERIF: + 'Email Não verificado\nleia a sua caixa de correio e encontre **"Confirmar o registo"**
e clique no botão **"Verificação do registo"**', + TELEGRAM_NOT_CONNECTED: 'Telegrama não associado à sua conta!', + NESSUN_INVITATO: 'Você não convidou ninguém', + ZOOM_PARTECIPATO: 'Participação em pelo menos 1 Conferência (Zoom)', + LINEE_GUIDA: 'Directrizes Aceites', + VIDEO_INTRO: 'Ver o vídeo', + SCRITTO_SOGNO: 'Você escreveu o seu sonho', + PAYMENTS: 'Formas de pagamento', + INVITATI: 'pessoas registadas que convidou', + INVITATI_ATTIVI: 'Convidado com os 7 Requisitos', + NONREG: 'Convidados não registados', + CLICCA_PER_ZOOM: 'PARA O DIA E HORA INDICADOS, PARA ENTRAR NA VÍDEO-CONFERÊNCIA, CLIQUE AQUI', + CLICCA_ENTRA: 'CLIQUE AQUI PARA ENTRAR !', + ZOOM_INIZIATO: 'ESTA CONFERÊNCIA JÁ COMEÇOU!', + SCEGLI_VOCE: 'escolha uma voz:', + INVITATI_LISTA: 'Os seus convidados (em verde com, pelo menos, os 7 primeiros requisitos)', + CIAO: 'Olá', + ADDED_TOLISTAINGRESSO: 'Foi acrescentado à Lista de Embarque !', + NO_PROG: 'Actualmente, ainda não consta da lista de embarque.!', + SEND_LINK_CHAT_DONATORI: 'Olà %s!\nO seu SHIP está finalmente a zarpar.!\nEntre no Gift Chat, clicando aqui: %s', + SEND_LINK_CHAT_SOGNATORE: + 'Olá %s!\nHoje você se torna um sonhador! 🎊🎊🎊 Entre no Gift Chat do navio {%s} clicando aqui: %s', + ENTRA_GIFT_CHAT: 'Entre no Gift Chat do navio', + DATA_PART_NAVE: 'data de partida do navio:', + SOGNATORE: 'SONHEIROS', + INTERMEDIO: 'Intermediar', + MEDIATORE: 'MEDIATOR', + DONATORI: 'DONATORES', + RITESSITURA: 'ENTRE EM', 'NAVE COMPLETATA': 'NAVIO COMPLETADO', 'Doni Effettuati': 'Regalo Feitos', 'Facilitatore che affianchèra il Mediatore': 'Facilitatore que apoia o Mediator', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Abertura do GIFT CHAT\n%s Fechamento GIFT CHAT\nNota: Você tem 3 dias desde a abertura para entrar no Chat e fazer o seu Presente, depois do qual faremos o substituição.', - 'SPOSTATO': 'Você foi transferido para um novo navio !', - 'Note': 'Notas', - 'TEMPORANEA': 'TEMPORÁRIO', - 'NAVE': 'NAVE', - 'MSG_SEND_FROM': 'Mensagem enviada por', - 'ZOOM_CONFERMATO': 'Foi-lhe confirmado que assistiu à Conferência de Vídeo de Boas-vindas!', - 'RICHIESTA_AMICIZIA': 'Richiesta d\'Amicizia da parte di %s', - 'ACCETTATO_SUL_GRUPPO': 'Sei stato accettato da %s a far parte del Gruppo %s', - 'ACCETTATO_NOTIFICA_ADMINS': 'l\'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)', + APERTURA_CHIUSURA_GIFT_CHAT: + '%s: Abertura do GIFT CHAT\n%s Fechamento GIFT CHAT\nNota: Você tem 3 dias desde a abertura para entrar no Chat e fazer o seu Presente, depois do qual faremos o substituição.', + SPOSTATO: 'Você foi transferido para um novo navio !', + Note: 'Notas', + TEMPORANEA: 'TEMPORÁRIO', + NAVE: 'NAVE', + MSG_SEND_FROM: 'Mensagem enviada por', + ZOOM_CONFERMATO: 'Foi-lhe confirmado que assistiu à Conferência de Vídeo de Boas-vindas!', + RICHIESTA_AMICIZIA: "Richiesta d'Amicizia da parte di %s", + ACCETTATO_SUL_GRUPPO: 'Sei stato accettato da %s a far parte del Gruppo %s', + ACCETTATO_NOTIFICA_ADMINS: "l'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)", - 'RICHIESTA_BLOCCO_GRUPPO': 'Richiesta di bloccare il Gruppo %s da parte di %s', + RICHIESTA_BLOCCO_GRUPPO: 'Richiesta di bloccare il Gruppo %s da parte di %s', }, }; -/** - * 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} - */ - async downloadImage(url, filepath, options = {}) { - const { - maxRetries = 3, // Aumentato il numero di tentativi predefiniti - initialDelay = 1000, // Ritardo iniziale - maxDelay = 10000, // Ritardo massimo - timeout = 30000, // Timeout della richiesta - validateContentType = true, // Verifica del tipo di contenuto - nomefileoriginale = true, - } = options; - - // Funzione per il backoff esponenziale - const getDelay = (attempt) => { - return Math.min(initialDelay * Math.pow(2, attempt - 1), maxDelay); - }; - - for (let attempt = 1; attempt <= maxRetries; attempt++) { - try { - // Verifica se il filepath esiste già - if (await this.isFileExists(filepath)) { - fs.unlinkSync(filepath); - } - - if (attempt > 1) - console.log(`📥 Tentativo ${attempt}/${maxRetries} - Scaricamento: ${url}`); - - const response = await axios({ - url, - method: 'GET', - responseType: 'stream', - timeout: timeout, - maxRedirects: 5, - headers: { - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', - 'Accept': 'image/jpeg,image/png,image/webp,image/gif,image/*', // Specifico per immagini - 'Cache-Control': 'no-cache', // Evita problemi di caching - 'Connection': 'keep-alive' - }, - validateStatus: (status) => status === 200, // Per immagini ci aspettiamo 200 - maxContentLength: 10 * 1024 * 1024 // Limite di 10MB per immagine - }); - - // Verifica del content-type se richiesto - if (validateContentType) { - const contentType = response.headers['content-type']; - if (!contentType || !contentType.startsWith('image/')) { - throw new Error(`Content-Type non valido: ${contentType}`); - } - } - - // Verifica della dimensione del file - const contentLength = parseInt(response.headers['content-length']); - if (contentLength && contentLength > 100 * 1024 * 1024) { // 100MB limit - throw new Error('File troppo grande'); - } - - let downloadedBytes = 0; - response.data.on('data', chunk => { - downloadedBytes += chunk.length; - }); - - let writer = null; - - if (nomefileoriginale) { - // Estrai il nome del file dall'URL o da Content-Disposition - //let fileName = this.extractFileNameFromUrl(url) || this.extractFileNameFromHeaders(response.headers); - let fileName = path.basename(response.data.responseUrl); - - // Se il nome del file non è specificato, genera un nome predefinito - if (!fileName) { - fileName = `image_${Date.now()}.jpg`; - } - - // Genera il percorso completo del file - const fullPath = path.join(path.dirname(filepath), fileName); - - filepath = fullPath; - - } - - // Scrivi il file sul disco - writer = fs.createWriteStream(filepath); - - response.data.pipe(writer); - - await new Promise((resolve, reject) => { - writer.on('finish', resolve); - writer.on('error', error => { - fs.unlink(filepath, () => { }); // Pulizia in caso di errore - reject(error); - }); - response.data.on('error', error => { - fs.unlink(filepath, () => { }); - reject(error); - }); - }); - - - console.info(`✅ Immagine scaricata con successo in ${filepath}`); - - - return { ris: true, filepath }; - - } catch (error) { - console.error(`❌ Errore nel tentativo ${attempt}/${maxRetries}:`, error.message); - - // Pulizia del file in caso di errore - if (await this.isFileExists(filepath)) { - fs.unlinkSync(filepath); - } - - // se in error.message c'è '404' allora esci e ritorna code: 404 - if (error.message.includes('404')) { - return { ris: false, code: 404 }; - } - - if (attempt === maxRetries) { - console.error(`Download fallito dopo ${maxRetries} tentativi: ${error.message}`); - return { ris: false }; - } - - const delay = getDelay(attempt); - console.info(`🔄 Attendo ${delay}ms prima del prossimo tentativo...`); - await new Promise(resolve => setTimeout(resolve, delay)); - } - } - } - - // Funzione per estrarre il nome del file dall'URL - extractFileNameFromUrl(url) { - const match = url.match(/\/([^/?#]+)(?:[?#]|$)/); - return match ? decodeURIComponent(match[1]) : null; - } - - // Funzione per estrarre il nome del file da Content-Disposition - extractFileNameFromHeaders(headers) { - const contentDisposition = headers['content-disposition']; - if (contentDisposition) { - const match = contentDisposition.match(/filename="([^"]+)"/); - if (match) { - return decodeURIComponent(match[1]); - } - } - return null; - } -} - - module.exports = { MYAPPS: [], INITDB_FIRSTIME: true, ACAPO: '\n', + ENABLE_CRONTAB: 'CRONTAB', UPDATE_GRADUATORIA: 'UPDATE_GRAD', @@ -668,7 +547,22 @@ module.exports = { FIRST_PROJ: '__PROJECTS', EXECUTE_CALCPROJ: true, - gettranslate(text, lang) { + isFileExistsAsync: async function (filename) { + try { + let fileExists = await fs.promises + .stat(filename) + .then(() => true) + .catch(() => false); + // console.log(filename, 'esiste', fileExists) + return fileExists; + } catch (e) { + // console.log(filename, 'esiste', 'FALSE') + return false; + } + }, + + + gettranslate: function (text, lang) { try { return textlang[lang][text]; } catch (e) { @@ -676,21 +570,19 @@ module.exports = { } }, - getlangbyres(res) { + getlangbyres: function (res) { // ++Todo: res estrarre la lingua let lang = ''; try { lang = res.lang; - } catch (e) { - - } + } catch (e) {} if (!lang) { lang = 'it'; } return lang; }, - get__(text, lang) { + get__: function (text, lang) { try { return textlang[lang][text]; } catch (e) { @@ -698,7 +590,7 @@ module.exports = { } }, - getres__(text, res) { + getres__: function(text, res) { let lang = this.getlangbyres(res); try { return textlang[lang][text]; @@ -711,12 +603,11 @@ module.exports = { return os.hostname(); }, testing: function () { - return (process.env.TESTING_ON === '1'); + return process.env.TESTING_ON === '1'; }, mylog: function (...args) { - if (!this.testing()) - console.log(args); + if (!this.testing()) console.log(args); }, mylogoff: function (...args) { @@ -743,7 +634,8 @@ module.exports = { 'origin', 'idapp', 'status', - 'options']; + 'options', + ]; }, allfieldSendNotif: function () { @@ -767,7 +659,8 @@ module.exports = { 'tag', 'options', 'idrec', - 'status']; + 'status', + ]; }, allfieldTodo: function () { @@ -795,7 +688,8 @@ module.exports = { 'hoursworked', 'start_date', 'themecolor', - 'themebgcolor']; + 'themebgcolor', + ]; }, allfieldMyEvent: function () { @@ -841,12 +735,12 @@ module.exports = { 'totalphases', 'actualphase', 'hoursweeky_plannedtowork', - 'endwork_estimate' - , + 'endwork_estimate', 'privacyread', 'privacywrite', 'tipovisu', - 'view']; + 'view', + ]; }, allfieldBooking: function () { @@ -864,7 +758,8 @@ module.exports = { 'modified', 'infoevent', 'datebooked', - 'booked']; + 'booked', + ]; }, allfieldBookingChange: function () { @@ -877,7 +772,8 @@ module.exports = { 'modified', 'infoevent', 'datebooked', - 'booked']; + 'booked', + ]; }, allfieldProjectWithId: function () { @@ -917,22 +813,23 @@ module.exports = { }; // Pass object into sendNotification - return webpush.sendNotification(subscription._doc, JSON.stringify(payload), - pushOptions). - catch((err) => { - if (err.statusCode === 410) { - // Gone: is not valid anymore (Expired probably!), so I have to delete from my db - return Subscription.findOneAndDelete({ _id: subscription._id }); - } else { - console.log('Subscription is no longer valid: ', err); - } - }).then((ris) => { - - }). - // console.log('sendNotification', ris); - catch(err => { - console.error(err); - }); + return ( + webpush + .sendNotification(subscription._doc, JSON.stringify(payload), pushOptions) + .catch((err) => { + if (err.statusCode === 410) { + // Gone: is not valid anymore (Expired probably!), so I have to delete from my db + return Subscription.findOneAndDelete({ _id: subscription._id }); + } else { + console.log('Subscription is no longer valid: ', err); + } + }) + .then((ris) => {}) + // console.log('sendNotification', ris); + .catch((err) => { + console.error(err); + }) + ); }, sendNotificationToUser: async function (userId, title, content, openUrl, openUrl2, tag, actions, id) { @@ -958,7 +855,6 @@ module.exports = { }; try { - let subscriptions = []; try { subscriptions = await Subscription.find({ userId }); @@ -997,7 +893,7 @@ module.exports = { process.env.VAPI_KEY_SUBJECT, process.env.PUBLIC_VAPI_KEY, process.env.PRIVATE_VAPI_KEY, - 'aes128gcm', + 'aes128gcm' ); const pushOptions = { @@ -1014,32 +910,31 @@ module.exports = { const pushPayload = JSON.stringify(payload); - webpush.sendNotification( - pushSubscription, - pushPayload, - pushOptions, - ).then((value) => { - // console.log('Invio Push', value); - resolve({ - status: true, - endpoint: subscription.endpoint, - data: value, - }); - }).catch(async (err) => { - console.error('err Push', err.body); + webpush + .sendNotification(pushSubscription, pushPayload, pushOptions) + .then((value) => { + // console.log('Invio Push', value); + resolve({ + status: true, + endpoint: subscription.endpoint, + data: value, + }); + }) + .catch(async (err) => { + console.error('err Push', err.body); - if (err.body) { - // Cancella dal DB la notifica Push, visto che da errore! (sarà scaduto) - const ris = await Subscription.deleteOne({ _id: subscription._id }); - } + if (err.body) { + // Cancella dal DB la notifica Push, visto che da errore! (sarà scaduto) + const ris = await Subscription.deleteOne({ _id: subscription._id }); + } - reject({ - status: false, - endpoint: subscription.endpoint, - data: err, + reject({ + status: false, + endpoint: subscription.endpoint, + data: err, + }); }); - }); - }).catch(error => { + }).catch((error) => { console.log('ERROR: sendNotificationToUser', error.data.body ? error.data.body : error); }); }); @@ -1051,11 +946,9 @@ module.exports = { // res.json({ // data: 'Push triggered' // }); - } catch (e) { console.error('sendNotificationToUser', e.message); } - }, getReqByPar(idapp, usernameOrig, groupOrig) { @@ -1071,15 +964,13 @@ module.exports = { }, sendNotificationByUsername: async function (idapp, username, cmd, telegram, usernameOrig, recObjCreator) { - var { User } = require('../models/user'); const { SendNotif } = require('../models/sendnotif'); const telegrambot = require('../telegram/telegrambot'); const user = await User.findOne({ idapp, username }, { _id: 1, username: 1, lang: 1 }).lean(); - if (!user) - return; + if (!user) return; let userId = user._id; let lang = user.lang; @@ -1102,17 +993,28 @@ module.exports = { const userrecDest = await User.getUserShortDataByUsername(idapp, usernameOrig); if (userrecDest) { - sendmynotif = false; // non lo rimandare 2 volte ! + sendmynotif = false; // non lo rimandare 2 volte ! // SEND TELEGRAM NOTIFICATION - telegrambot.askConfirmationUserFriend(idapp, shared_consts.CallFunz.RICHIESTA_AMICIZIA, userrecDest, username, usernameOrig); + telegrambot.askConfirmationUserFriend( + idapp, + shared_consts.CallFunz.RICHIESTA_AMICIZIA, + userrecDest, + username, + usernameOrig + ); } - } else if (cmd === shared_consts.FRIENDSCMD.SETHANDSHAKE) { const userrecDest = await User.getUserShortDataByUsername(idapp, usernameOrig); const foundIfAlready = await User.isMyHandShake(idapp, username, usernameOrig); if (!foundIfAlready) { - telegrambot.askConfirmationUserFriend(idapp, shared_consts.CallFunz.RICHIESTA_HANDSHAKE, userrecDest, username, usernameOrig); + telegrambot.askConfirmationUserFriend( + idapp, + shared_consts.CallFunz.RICHIESTA_HANDSHAKE, + userrecDest, + username, + usernameOrig + ); } } } @@ -1123,16 +1025,21 @@ module.exports = { } if (telegram && sendmynotif) { - const idtelegram = await User.TelegIdByUsername(idapp, username); - await telegrambot.sendMsgTelegramByIdTelegram(idapp, idtelegram, descr + domanda, undefined, undefined, true, keyb); + await telegrambot.sendMsgTelegramByIdTelegram( + idapp, + idtelegram, + descr + domanda, + undefined, + undefined, + true, + keyb + ); } - }, sendMsgTelegramToAdmin: async function (idapp, msg) { - const telegrambot = require('../telegram/telegrambot'); const idtelegram = telegrambot.ADMIN_IDTELEGRAM_SERVER; @@ -1141,9 +1048,16 @@ module.exports = { }, sendNotifAndMsgTelegram: async function (idapp, userId, objmsg, telegram, msgextrateleg) { - if (userId) { - await this.sendNotificationToUser(userId, objmsg.title, objmsg.descr, objmsg.openUrl, '', objmsg.tag, objmsg.actions); + await this.sendNotificationToUser( + userId, + objmsg.title, + objmsg.descr, + objmsg.openUrl, + '', + objmsg.tag, + objmsg.actions + ); } if (telegram) { @@ -1158,18 +1072,24 @@ module.exports = { }, sendNotifGroupByUsername: async function ( - cmd, idapp, usernameOrig, usernameDest, username_action, groupname, myrecgroup, isAdmin, username_worked) { - + cmd, + idapp, + usernameOrig, + usernameDest, + username_action, + groupname, + myrecgroup, + isAdmin, + username_worked + ) { const { SendNotif } = require('../models/sendnotif'); const { User } = require('../models/user'); const telegrambot = require('../telegram/telegrambot'); const req = this.getReqByPar(idapp, usernameOrig); - const user = await User.findOne({ idapp, username: usernameDest }, - { _id: 1, lang: 1 }); + const user = await User.findOne({ idapp, username: usernameDest }, { _id: 1, lang: 1 }); if (user) { - let lang = user.lang; let paramsObj = { usernameDest, @@ -1203,8 +1123,14 @@ module.exports = { typeid = shared_consts.TypeNotifs.ID_GROUP_REQUEST_TO_ENTER; // paramsObj.options = MessageOptions.Notify_OnlyToNotifinApp + MessageOptions.Notify_ByBotTelegram; const myuserdata = await User.getUserShortDataByUsername(idapp, username_action); - telegrambot.askConfirmationUser(idapp, shared_consts.CallFunz.RICHIESTA_GRUPPO, myuserdata, usernameDest, groupname, - myrecgroup._id); + telegrambot.askConfirmationUser( + idapp, + shared_consts.CallFunz.RICHIESTA_GRUPPO, + myuserdata, + usernameDest, + groupname, + myrecgroup._id + ); onlysave = false; } else if (cmd === shared_consts.GROUPSCMD.BLOCK_USER) { typeid = shared_consts.TypeNotifs.ID_GROUP_BLOCK_USER; @@ -1215,7 +1141,6 @@ module.exports = { } else if (cmd === shared_consts.GROUPSCMD.REMOVEADMIN_OFMYGROUP) { typeid = shared_consts.TypeNotifs.ID_GROUP_REMOVED_ADMIN_OFMYGROUP; } - } if (sendnotif && typeid > 0) { @@ -1223,13 +1148,23 @@ module.exports = { await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, onlysave, typedir, typeid); } } - }, sendNotifCircuitByUsername: async function ( - cmd, idapp, usernameOrig, groupOrig, usernameDest, groupDest, username_action, - circuitname, path, myreccircuit, isAdmin, username_worked, extrarec) { - + cmd, + idapp, + usernameOrig, + groupOrig, + usernameDest, + groupDest, + username_action, + circuitname, + path, + myreccircuit, + isAdmin, + username_worked, + extrarec + ) { const { SendNotif } = require('../models/sendnotif'); const { User } = require('../models/user'); const telegrambot = require('../telegram/telegrambot'); @@ -1240,11 +1175,12 @@ module.exports = { let arrris = []; - const userOrig = await User.findOne({ idapp, username: usernameOrig }, - { _id: 1, lang: 1, aportador_solidario: 1, name: 1, surname: 1, username: 1 }); + const userOrig = await User.findOne( + { idapp, username: usernameOrig }, + { _id: 1, lang: 1, aportador_solidario: 1, name: 1, surname: 1, username: 1 } + ); - const user = await User.findOne({ idapp, username: usernameDest }, - { _id: 1, lang: 1 }); + const user = await User.findOne({ idapp, username: usernameDest }, { _id: 1, lang: 1 }); let lang = 'it'; if (user) { @@ -1297,8 +1233,16 @@ module.exports = { cmdrichiesta = shared_consts.CallFunz.RICHIESTA_CIRCUIT; } - telegrambot.askConfirmationUser(idapp, cmdrichiesta, myuserdata, usernameDest, circuitname, - myreccircuit._id, '', extrarec.groupname); + telegrambot.askConfirmationUser( + idapp, + cmdrichiesta, + myuserdata, + usernameDest, + circuitname, + myreccircuit._id, + '', + extrarec.groupname + ); if (mycircuit.sendEmailAfterAskingToEnter) { const { Circuit } = require('../models/circuit'); @@ -1308,7 +1252,13 @@ module.exports = { let linkcirc = myapp + path; let messaggio = ''; let mytitle = i18n.__('CIRCUIT_REQUEST_TO_ENTER_ASKMANAGER_TITLE', usernameOrig); - messaggio = i18n.__('CIRCUIT_REQUEST_TO_ENTER_ASKMANAGER_SHORT', usernameOrig, '' + circuitname + '', numuserincircuit, userOrig.aportador_solidario); + messaggio = i18n.__( + 'CIRCUIT_REQUEST_TO_ENTER_ASKMANAGER_SHORT', + usernameOrig, + '' + circuitname + '', + numuserincircuit, + userOrig.aportador_solidario + ); messaggio += '\n\n'; messaggio += 'Clicca qui per entrare sul Circuito\n'; @@ -1319,7 +1269,7 @@ module.exports = { sendemail.sendEmail_ByText(lang, email, myuserdata, idapp, { emailbody: messaggio, emailtitle: mytitle, - }) + }); } onlysave = false; } else if (cmd === shared_consts.CIRCUITCMD.ADDADMIN) { @@ -1343,20 +1293,22 @@ module.exports = { //} else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE_SENT) { // typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED_SENT; } - } if (sendnotif && typeid > 0) { - const groupDestoContoCom = groupDest ? groupDest : (extrarec && extrarec.contoComDest ? extrarec.contoComDest : ''); + const groupDestoContoCom = groupDest + ? groupDest + : extrarec && extrarec.contoComDest + ? extrarec.contoComDest + : ''; // Check if is group: - if (groupDestoContoCom && ( - (cmd !== shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT_SENT) && - (cmd !== shared_consts.CIRCUITCMD.SENDCOINS_REFUSE_SENT) - )) { - + if ( + groupDestoContoCom && + cmd !== shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT_SENT && + cmd !== shared_consts.CIRCUITCMD.SENDCOINS_REFUSE_SENT + ) { let arrusers = await MyGroup.getListAdminsByGroupName(idapp, groupDestoContoCom); - if (arrusers.length <= 0) - arrusers = await Circuit.getListAdminsByCircuitPath(idapp, groupDestoContoCom); + if (arrusers.length <= 0) arrusers = await Circuit.getListAdminsByCircuitPath(idapp, groupDestoContoCom); let notiftoUpdate = ''; let findrecnotif = await SendNotif.findOne({ _id: paramsObj.extrarec.notifId }).lean(); @@ -1364,50 +1316,54 @@ module.exports = { if (findrecnotif) { let arrrec = []; - if (notiftoUpdate) - arrrec = await SendNotif.find({ 'extrarec.notifIdToUpdate': notiftoUpdate }); + if (notiftoUpdate) arrrec = await SendNotif.find({ 'extrarec.notifIdToUpdate': notiftoUpdate }); for (let rec of arrrec) { paramsObj.usernameDest = rec.dest; paramsObj.sender = rec.sender; - if ((cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) || (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE)) { + if ( + cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT || + cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE + ) { try { paramsObj.extrarec.notifId = rec._id; - } catch (e) { - } + } catch (e) {} } ris = await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, onlysave, typedir, typeid); if (!ris) { - console.error('Errore createNewNotifToSingleUser! ', paramsObj.usernameDest, "dest ->", groupDestoContoCom) + console.error( + 'Errore createNewNotifToSingleUser! ', + paramsObj.usernameDest, + 'dest ->', + groupDestoContoCom + ); } else { arrris.push(ris._id); } - } - } else { - for (let i = 0; i < arrusers.length; i++) { paramsObj.usernameDest = arrusers[i].username; ris = await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, onlysave, typedir, typeid); if (!ris) { - console.error('Errore createNewNotifToSingleUser! ', paramsObj.usernameDest, "dest ->", groupDestoContoCom) + console.error( + 'Errore createNewNotifToSingleUser! ', + paramsObj.usernameDest, + 'dest ->', + groupDestoContoCom + ); } else { arrris.push(ris._id); } } - } - } else { // CREATE NOTIFICATION IN TABLE SENDNOTIF ris = await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, onlysave, typedir, typeid); - if ((cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) || - (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE)) { - + if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT || cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) { if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) { typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED_SENT; } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) { @@ -1419,23 +1375,24 @@ module.exports = { notiftoUpdate = findrecnotif ? findrecnotif.extrarec.notifIdToUpdate : ''; arrnotiftoUpdate = findrecnotif ? findrecnotif.extrarec.arrnotifIdToUpdate : ''; if (findrecnotif && notiftoUpdate && arrnotiftoUpdate) { - for (let myid of arrnotiftoUpdate) { let rec = await SendNotif.findOne({ _id: myid }).lean(); if (rec && rec.status === 0) { paramsObj.usernameDest = rec.dest; paramsObj.extrarec.idStatusToSent = rec._id; - ris = await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, onlysave, typedir, typeid); if (!ris) { - console.error('Errore createNewNotifToSingleUser! ', paramsObj.usernameDest, "dest ->", groupDestoContoCom) + console.error( + 'Errore createNewNotifToSingleUser! ', + paramsObj.usernameDest, + 'dest ->', + groupDestoContoCom + ); } } - } } - } } } @@ -1444,17 +1401,14 @@ module.exports = { } catch (e) { console.log(e.message); } - }, sendNotificationByGroupname: async function (idapp, usernameOrig, groupname, cmd, value, telegram, username_action) { - const { MyGroup } = require('../models/mygroup'); const { User } = require('../models/user'); const group = await MyGroup.findOne({ idapp, groupname }, { _id: 1, admins: 1, createdBy: 1 }).lean(); - if (!group) - return; + if (!group) return; let giainviato = false; @@ -1463,41 +1417,66 @@ module.exports = { for (const singleadmin of group.admins) { try { if (singleadmin.username) { - if (usernameOrig === singleadmin.username) - giainviato = true; + if (usernameOrig === singleadmin.username) giainviato = true; - await this.sendNotifGroupByUsername(cmd, idapp, usernameOrig, singleadmin.username, username_action, groupname, group, true); + await this.sendNotifGroupByUsername( + cmd, + idapp, + usernameOrig, + singleadmin.username, + username_action, + groupname, + group, + true + ); } } catch (e) { console.error('sendNotificationByGroupname', e); } } - if (!giainviato && (cmd !== shared_consts.GROUPSCMD.REQGROUP)) { + if (!giainviato && cmd !== shared_consts.GROUPSCMD.REQGROUP) { // SEND TO THE USER THE NOTIFICATION - await this.sendNotifGroupByUsername(cmd, idapp, usernameOrig, usernameOrig, username_action, groupname, null, false); + await this.sendNotifGroupByUsername( + cmd, + idapp, + usernameOrig, + usernameOrig, + username_action, + groupname, + null, + false + ); } - } catch (e) { console.error('e', e); } - }, getAdminsByCircuit(circuit) { // return circuit.admins - return [...circuit.admins, { username: shared_consts.USER_ADMIN_CIRCUITS }] + return [...circuit.admins, { username: shared_consts.USER_ADMIN_CIRCUITS }]; }, - sendNotificationByCircuit: async function (idapp, usernameOrig, circuitname, cmd, value, telegram, username_action, extrarec) { - + sendNotificationByCircuit: async function ( + idapp, + usernameOrig, + circuitname, + cmd, + value, + telegram, + username_action, + extrarec + ) { const { Circuit } = require('../models/circuit'); const { SendNotif } = require('../models/sendnotif'); - const circuit = await Circuit.findOne({ idapp, name: circuitname }, { _id: 1, admins: 1, createdBy: 1, path: 1 }).lean(); - if (!circuit) - return; + const circuit = await Circuit.findOne( + { idapp, name: circuitname }, + { _id: 1, admins: 1, createdBy: 1, path: 1 } + ).lean(); + if (!circuit) return; let giainviato = false; @@ -1508,18 +1487,32 @@ module.exports = { let inviato = false; let arrris = []; - if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REQ || cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT || cmd === - shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) { - - groupOrig = extrarec.grouporig + if ( + cmd === shared_consts.CIRCUITCMD.SENDCOINS_REQ || + cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT || + cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE + ) { + groupOrig = extrarec.grouporig; let recnotif = null; if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REQ) { // msg al Mittente (o mittenti del 'groupOrig') "Stai inviando X RIS" - let res = await this.sendNotifCircuitByUsername(shared_consts.CIRCUITCMD.SENDCOINS_REQ_SENT, idapp, extrarec.dest, extrarec.groupdest, usernameOrig, groupOrig, - username_action, circuitname, circuit.path, null, - false, '', extrarec); + let res = await this.sendNotifCircuitByUsername( + shared_consts.CIRCUITCMD.SENDCOINS_REQ_SENT, + idapp, + extrarec.dest, + extrarec.groupdest, + usernameOrig, + groupOrig, + username_action, + circuitname, + circuit.path, + null, + false, + '', + extrarec + ); if (res) { recnotif = res.recnotif; @@ -1527,31 +1520,66 @@ module.exports = { } } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) { // msg ai MITTENTI: "X RIS sono stati accettati da Destinatario" - await this.sendNotifCircuitByUsername(shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT_SENT, idapp, extrarec.dest, extrarec.groupdest, usernameOrig, groupOrig, - username_action, circuitname, circuit.path, null, - false, '', extrarec); + await this.sendNotifCircuitByUsername( + shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT_SENT, + idapp, + extrarec.dest, + extrarec.groupdest, + usernameOrig, + groupOrig, + username_action, + circuitname, + circuit.path, + null, + false, + '', + extrarec + ); } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) { - await this.sendNotifCircuitByUsername(shared_consts.CIRCUITCMD.SENDCOINS_REFUSE_SENT, idapp, extrarec.dest, extrarec.groupdest, usernameOrig, groupOrig, - username_action, circuitname, circuit.path, null, - false, '', extrarec); + await this.sendNotifCircuitByUsername( + shared_consts.CIRCUITCMD.SENDCOINS_REFUSE_SENT, + idapp, + extrarec.dest, + extrarec.groupdest, + usernameOrig, + groupOrig, + username_action, + circuitname, + circuit.path, + null, + false, + '', + extrarec + ); } - if (recnotif) - extrarec.notifIdToUpdate = recnotif._id; - if (arrris) - extrarec.arrnotifIdToUpdate = arrris; + if (recnotif) extrarec.notifIdToUpdate = recnotif._id; + if (arrris) extrarec.arrnotifIdToUpdate = arrris; - let usernametoOrigUse = usernameOrig + let usernametoOrigUse = usernameOrig; if (extrarec.groupname) { - usernametoOrigUse = '' + usernametoOrigUse = ''; } - ris = await this.sendNotifCircuitByUsername(cmd, idapp, usernametoOrigUse, groupOrig, extrarec.dest, extrarec.groupdest, username_action, circuitname, circuit.path, - null, false, '', extrarec); + ris = await this.sendNotifCircuitByUsername( + cmd, + idapp, + usernametoOrigUse, + groupOrig, + extrarec.dest, + extrarec.groupdest, + username_action, + circuitname, + circuit.path, + null, + false, + '', + extrarec + ); if (arrris && ris && ris.recnotif) { for (const rec of arrris) { let obj = { - 'extrarec.notifIdToUpdate': ris.recnotif._id + 'extrarec.notifIdToUpdate': ris.recnotif._id, }; await SendNotif.findOneAndUpdate({ _id: rec._id }, { $set: obj }, { new: false }); @@ -1560,21 +1588,31 @@ module.exports = { extrarec.notifIdToUpdate = ''; - if (ris.recnotif) - inviato = true; + if (ris.recnotif) inviato = true; // ++Todo: Inviare anche agli Admin ?! } else { - - const groupOrig = '' //++Todo: extrarec.groupOrig + const groupOrig = ''; //++Todo: extrarec.groupOrig for (const singleadmin of this.getAdminsByCircuit(circuit)) { try { if (singleadmin.username) { - if (usernameOrig === singleadmin.username) - giainviato = true; + if (usernameOrig === singleadmin.username) giainviato = true; - await this.sendNotifCircuitByUsername(cmd, idapp, usernameOrig, groupOrig, singleadmin.username, '', username_action, circuitname, - circuit.path, circuit, true, '', extrarec); + await this.sendNotifCircuitByUsername( + cmd, + idapp, + usernameOrig, + groupOrig, + singleadmin.username, + '', + username_action, + circuitname, + circuit.path, + circuit, + true, + '', + extrarec + ); inviato = true; } } catch (e) { @@ -1584,15 +1622,26 @@ module.exports = { if (!giainviato && cmd !== shared_consts.CIRCUITCMD.REQ) { // SEND TO THE USER DEST THE NOTIFICATION - ris = await this.sendNotifCircuitByUsername(cmd, idapp, usernameOrig, groupOrig, usernameOrig, '', username_action, circuitname, circuit.path, - null, false, '', extrarec); + ris = await this.sendNotifCircuitByUsername( + cmd, + idapp, + usernameOrig, + groupOrig, + usernameOrig, + '', + username_action, + circuitname, + circuit.path, + null, + false, + '', + extrarec + ); - if (ris && ris.recnotif) - inviato = true; + if (ris && ris.recnotif) inviato = true; } } - if (inviato) { if (arrris && arrris.length > 0) { for (const notif of arrris) { @@ -1606,12 +1655,10 @@ module.exports = { } return { ris: ris.recnotif, inviato }; - } catch (e) { console.error('sendNotificationByCircuit: ', e); return { ris: null, inviato: false }; } - }, // ********************** @@ -1669,7 +1716,6 @@ module.exports = { */ async sendNotifToCircuitsAdmin(idapp, circuit, alsotelegram, title, msg, tag = '') { - const { User } = require('../models/user'); const telegrambot = require('../telegram/telegrambot'); @@ -1712,8 +1758,7 @@ module.exports = { const queryadmins = { username: 'paoloar77', idapp }; - if (idapp === 0) - idapp = '13'; + if (idapp === 0) idapp = '13'; User.find(queryadmins).then(async (arrusers) => { if (arrusers !== null) { @@ -1722,29 +1767,25 @@ module.exports = { this.sendMsgTelegramToAdmin(idapp, title + ' ' + msg); } - await this.sendNotificationToUser(user._id, title, msg, '/', '', tag, []). - then(ris => { - if (ris) { - - } else { - // already sent the error on calling sendNotificationToUser - } - }); + await this.sendNotificationToUser(user._id, title, msg, '/', '', tag, []).then((ris) => { + if (ris) { + } else { + // already sent the error on calling sendNotificationToUser + } + }); } } }); - } catch (e) { console.error(e); } - }, checkUserOk(userpassed, userauth, res) { // this.mylog('checkUserOk', userpassed, userauth); if (String(userpassed) !== String(userauth)) { // I'm trying to write something not mine! - this.mylog('I\'m trying to write something not mine!: userId = ', userpassed, 'req.user._id', userauth); + this.mylog("I'm trying to write something not mine!: userId = ", userpassed, 'req.user._id', userauth); if (!res) { return { exit: true, @@ -1761,18 +1802,15 @@ module.exports = { } else { return { exit: false, ret: false }; } - }, ConvertHTMLToPlainText(strHTML) { - if (strHTML) - return strHTML.replace(/<[^>]+>/g, ''); + if (strHTML) return strHTML.replace(/<[^>]+>/g, ''); return ''; }, convertSpaces_ToUScore(mystr) { - if (mystr) - return mystr.replace(/\s+/g, '_'); + if (mystr) return mystr.replace(/\s+/g, '_'); return ''; }, @@ -1794,7 +1832,6 @@ module.exports = { }, htmlToTelegramText(html) { - try { const withMarkdown = html .replace(/(.*?)<\/strong>/g, '*$1*') @@ -1820,15 +1857,12 @@ module.exports = { }); return telegramText; - } catch (e) { console.error(e); - }; - + } }, htmlToTelegramText(html) { - try { const withMarkdown = html .replace(/(.*?)<\/strong>/g, '*$1*') @@ -1854,11 +1888,9 @@ module.exports = { }); return telegramText; - } catch (e) { console.error(e); - }; - + } }, convertTexttoHtml(myhtml) { @@ -1873,8 +1905,7 @@ module.exports = { removeSpecialCharForEmail(myhtml) { let msg = myhtml; try { - if (msg) - msg = msg.replace(/"/g, '\''); + if (msg) msg = msg.replace(/"/g, "'"); } catch (e) { return msg; } @@ -1883,12 +1914,9 @@ module.exports = { }, getNomeAppByIdApp: function (idapp) { - - const myapp = this.MYAPPS.find(item => item.idapp === idapp); - if (myapp) - return ((process.env.NODE_ENV === 'test') ? 'Test: ' : '') + myapp.name; - else - return ''; + const myapp = this.MYAPPS.find((item) => item.idapp === idapp); + if (myapp) return (process.env.NODE_ENV === 'test' ? 'Test: ' : '') + myapp.name; + else return ''; }, getTimeExpReg: async function (idapp, username) { @@ -1898,29 +1926,23 @@ module.exports = { }, getLinkRegByIdAppAndMsgStrutt: function (idapp, msg, rec) { - let myapp = this.getHostByIdApp(idapp); if (myapp) { - myapp += '/registrati/' + rec.aportador_solidario + '/' + msg.from.username + '/' + msg.from.id + '/' + rec.regexpire; + myapp += + '/registrati/' + rec.aportador_solidario + '/' + msg.from.username + '/' + msg.from.id + '/' + rec.regexpire; } return myapp; }, getHostByIdApp: function (idapp) { - - const myapp = this.MYAPPS.find(item => item.idapp === idapp); + const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (myapp) { - let siteport = (myapp.portapp && myapp.portapp !== '0') ? (':' + - myapp.portapp) : ''; + let siteport = myapp.portapp && myapp.portapp !== '0' ? ':' + myapp.portapp : ''; - if (process.env.NODE_ENV === 'test') - return myapp.host_test + siteport; - else - return myapp.host + siteport; - - } else - return ''; + if (process.env.NODE_ENV === 'test') return myapp.host_test + siteport; + else return myapp.host + siteport; + } else return ''; }, getLinkUserProfile: function (idapp, username) { @@ -1932,16 +1954,17 @@ module.exports = { let u_tg = ''; if (myuser) - u_tg = myuser.profile && myuser.profile.hasOwnProperty('username_telegram') ? myuser.profile.username_telegram : usernametelegram; + u_tg = + myuser.profile && myuser.profile.hasOwnProperty('username_telegram') + ? myuser.profile.username_telegram + : usernametelegram; if (!u_tg) { u_tg = await User.getUsernameTelegram(idapp, username); } - if (u_tg) - return `https://t.me/${u_tg}`; - else - return ''; + if (u_tg) return `https://t.me/${u_tg}`; + else return ''; }, getLinkEditUserProfile: function (idapp) { @@ -1949,10 +1972,8 @@ module.exports = { }, getConfSiteOptionEnabledByIdApp: function (idapp, option) { - - const myapp = this.MYAPPS.find(item => item.idapp === idapp); + const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (myapp) { - if (myapp.hasOwnProperty('confsite')) { if (myapp.confsite.hasOwnProperty('options')) { return this.isBitActive(myapp.confsite.options, option); @@ -1964,8 +1985,7 @@ module.exports = { }, getEnableTokenExpiredByIdApp: function (idapp) { - - const myapp = this.MYAPPS.find(item => item.idapp === idapp); + const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (myapp && myapp.confpages && myapp.confpages.hasOwnProperty('enableTokenExpired')) { return myapp.confpages.enableTokenExpired; } @@ -1974,10 +1994,8 @@ module.exports = { }, getConfParamSiteByIdApp: function (idapp, field) { - - const myapp = this.MYAPPS.find(item => item.idapp === idapp); + const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (myapp) { - if (myapp.hasOwnProperty('confsite')) { if (myapp.confsite.hasOwnProperty(field)) { return myapp.confsite[field]; @@ -1989,7 +2007,7 @@ module.exports = { }, isAbilitaNave: function (idapp) { - const myapp = this.MYAPPS.find(item => item.idapp === idapp); + const myapp = this.MYAPPS.find((item) => item.idapp === idapp); return myapp.abilitanave; }, @@ -1998,8 +2016,7 @@ module.exports = { let result = myString; try { - if (myString) - result = myString.replace(regex, ""); + if (myString) result = myString.replace(regex, ''); } catch (e) { return myString; } @@ -2008,15 +2025,11 @@ module.exports = { }, getdirByIdApp: function (idapp, dirmain = false) { - let mypath = ''; - const myapp = - this.MYAPPS.find(item => item.idapp === idapp); + const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (myapp) { - if (process.env.NODE_ENV === 'test') - mypath = (myapp && myapp.dir_test) ? myapp.dir_test : ''; - else - mypath = (myapp && myapp.dir) ? myapp.dir : ''; + if (process.env.NODE_ENV === 'test') mypath = myapp && myapp.dir_test ? myapp.dir_test : ''; + else mypath = myapp && myapp.dir ? myapp.dir : ''; if (dirmain) { if (!this.sulServer()) { @@ -2030,18 +2043,14 @@ module.exports = { getAdminEmailByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); - if (myapp) - return myapp.adminemail; - else - return ''; + if (myapp) return myapp.adminemail; + else return ''; }, getreplyToEmailByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); - if (myapp) - return myapp.replyTo; - else - return ''; + if (myapp) return myapp.replyTo; + else return ''; }, getpathregByIdApp: function (idapp, lang) { @@ -2060,7 +2069,6 @@ module.exports = { return myapp && param ? myapp[param] : ''; }, - getAskToVerifyReg: function (idapp) { return this.getConfSiteOptionEnabledByIdApp(idapp, shared_consts.ConfSite.Need_Aportador_On_DataReg_To_Verify_Reg); }, @@ -2071,42 +2079,36 @@ module.exports = { isManagAndAdminDifferent(idapp) { const manag = this.getManagerEmailByIdApp(idapp); - return (manag !== this.getAdminEmailByIdApp(idapp)) && (manag !== ''); + return manag !== this.getAdminEmailByIdApp(idapp) && manag !== ''; }, getManagerEmailByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); - if (myapp) - return !!myapp.manageremail ? myapp.manageremail : ''; - else - return ''; + if (myapp) return !!myapp.manageremail ? myapp.manageremail : ''; + else return ''; }, getEmailByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); - return (myapp) ? myapp.email_from : ''; + return myapp ? myapp.email_from : ''; }, getPwdByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); - return (myapp) ? this.decryptdata(myapp.email_pwd) : ''; + return myapp ? this.decryptdata(myapp.email_pwd) : ''; }, - getTelegramBotNameByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') - return (myapp) ? myapp.telegram_bot_name_test : ''; - else - return (myapp) ? myapp.telegram_bot_name : ''; + return myapp ? myapp.telegram_bot_name_test : ''; + else return myapp ? myapp.telegram_bot_name : ''; }, getTelegramSupportChat: function (idapp) { try { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); - return (myapp && myapp.telegram_support_chat) - ? myapp.telegram_support_chat - : ''; + return myapp && myapp.telegram_support_chat ? myapp.telegram_support_chat : ''; } catch (e) { return ''; } @@ -2115,22 +2117,19 @@ module.exports = { getTelegramKeyByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') - return (myapp) ? myapp.telegram_key_test : ''; - else - return (myapp) ? myapp.telegram_key : ''; + return myapp ? myapp.telegram_key_test : ''; + else return myapp ? myapp.telegram_key : ''; }, getArrTelegramFromSite: function () { const myapp = this.MYAPPS; - let arrteleg = [] + let arrteleg = []; for (const site of myapp) { if (site.active) { if (process.env.NODE_ENV === 'test') { - if (site.telegram_bot_name_test) - arrteleg.push(site.idapp) + if (site.telegram_bot_name_test) arrteleg.push(site.idapp); } else { - if (site.telegram_bot_name) - arrteleg.push(site.idapp) + if (site.telegram_bot_name) arrteleg.push(site.idapp); } } } @@ -2139,7 +2138,6 @@ module.exports = { }, getLookupPipeLine(params, proj) { - let myquery = [ { $lookup: { @@ -2147,15 +2145,9 @@ module.exports = { let: { username: '$' + params.lk_LF, idapp: params.idapp }, pipeline: [ { - $match: - { - $expr: - { - $and: - [ - { $eq: ['$' + params.lk_FF, '$$' + params.lk_FF] }, - { $eq: ['$idapp', '$$idapp'] }, - ], + $match: { + $expr: { + $and: [{ $eq: ['$' + params.lk_FF, '$$' + params.lk_FF] }, { $eq: ['$idapp', '$$idapp'] }], }, }, }, @@ -2170,17 +2162,16 @@ module.exports = { }, getNumTabByTable(table) { - const myrec = shared_consts.MYTABS.find((rec) => rec.table === table) - return myrec ? myrec.id : -1 + const myrec = shared_consts.MYTABS.find((rec) => rec.table === table); + return myrec ? myrec.id : -1; }, getTableByNumTab(numtab) { - const myrec = shared_consts.MYTABS.find((rec) => rec.id === numtab) - return myrec ? myrec.table : '' + const myrec = shared_consts.MYTABS.find((rec) => rec.id === numtab); + return myrec ? myrec.table : ''; }, getGroupnameLookupPipeLine(params, proj) { - let myquery = [ { $lookup: { @@ -2188,15 +2179,9 @@ module.exports = { let: { groupname: '$' + params.lk_LF, idapp: params.idapp }, pipeline: [ { - $match: - { - $expr: - { - $and: - [ - { $eq: ['$' + params.lk_FF, '$$' + params.lk_FF] }, - { $eq: ['$idapp', '$$idapp'] }, - ], + $match: { + $expr: { + $and: [{ $eq: ['$' + params.lk_FF, '$$' + params.lk_FF] }, { $eq: ['$idapp', '$$idapp'] }], }, }, }, @@ -2213,26 +2198,23 @@ module.exports = { getLookupStandardPipeline: function (params, num) { const query = []; - if (!params) - return; + if (!params) return; query.push( { $lookup: { from: params.lk_tab, - let: { searchId: { $toObjectId: "$" + params.lk_LF } }, + let: { searchId: { $toObjectId: '$' + params.lk_LF } }, pipeline: [ { $match: { $expr: { - $and: [ - { $eq: ["$" + params.lk_FF, "$$searchId"] }, - ], + $and: [{ $eq: ['$' + params.lk_FF, '$$searchId'] }], }, }, }, { - $project: params.lk_proj + $project: params.lk_proj, }, ], as: params.lk_as + num, @@ -2243,13 +2225,14 @@ module.exports = { newRoot: { $mergeObjects: [ { - $arrayElemAt: [ - '$' + params.lk_as + num, 0], - }, '$$ROOT'], + $arrayElemAt: ['$' + params.lk_as + num, 0], + }, + '$$ROOT', + ], }, }, } - ) + ); return query; }, @@ -2257,7 +2240,7 @@ module.exports = { try { return sanitizeHtml(html); } catch (e) { - return html + return html; } }, @@ -2266,7 +2249,6 @@ module.exports = { }, sanitizzaProjection: function (mioproj) { - // mioproj = {valore: '$password'}; const COL_TO_REMOVE = ['$password', '$tokens', '$tokens.token', 'ipaddr']; @@ -2284,30 +2266,22 @@ module.exports = { getLookup: function (params, num, pass_proj, proj_add) { const query = []; - if (!params) - return; + if (!params) return; let mylkLF = params.lk_LF; if (params.af_objId_tab) { const myobj = {}; - myobj['myId' + num] = { '$toObjectId': '$' + params.lk_LF }; + myobj['myId' + num] = { $toObjectId: '$' + params.lk_LF }; if (params.lk_tab === 'users') { myobj.namecomplete = { - $concat: [ - { $toLower: "$name" }, - { $toLower: "$surname" }, - { $toLower: "$username" }, - ], + $concat: [{ $toLower: '$name' }, { $toLower: '$surname' }, { $toLower: '$username' }], }; } - query.push( - { '$addFields': myobj }, - ); + query.push({ $addFields: myobj }); mylkLF = 'myId' + num; } else { - } if (params.lk_tab) { @@ -2318,43 +2292,39 @@ module.exports = { } proj = Object.assign({}, proj, proj_add); - query.push( - { - $lookup: { - from: params.lk_tab, - localField: mylkLF, // field in my collection - foreignField: params.lk_FF, // field in the 'from' collection - as: params.lk_as, - }, - }); + query.push({ + $lookup: { + from: params.lk_tab, + localField: mylkLF, // field in my collection + foreignField: params.lk_FF, // field in the 'from' collection + as: params.lk_as, + }, + }); if (params.unwind) { - query.push({ $unwind: { path: '$' + params.lk_as, preserveNullAndEmptyArrays: true, - } - }) + }, + }); } if (!params.noarray) { - query.push( - { - $replaceRoot: { - newRoot: { - $mergeObjects: [ - { - $arrayElemAt: [ - '$' + params.lk_as, 0], - }, '$$ROOT'], - }, + query.push({ + $replaceRoot: { + newRoot: { + $mergeObjects: [ + { + $arrayElemAt: ['$' + params.lk_as, 0], + }, + '$$ROOT', + ], }, - }); + }, + }); } - query.push( - { $project: proj }, - ); + query.push({ $project: proj }); } return query; @@ -2375,30 +2345,28 @@ module.exports = { data[rec.field] = myregexp; if (rec.field === 'profile.username_telegram') { myregexp = new RegExp(this.rimuoviAtPrimoCarattere(filter).trim().replace(' ', '|'), 'ig'); - data[rec.field] = myregexp + data[rec.field] = myregexp; } - } else if ((rec.type === this.FieldType.number) || - (rec.type === this.FieldType.hours)) { + } else if (rec.type === this.FieldType.number || rec.type === this.FieldType.hours) { data[rec.field] = parseFloat(filter.trim()); } - if (data) - myfilters.push(data); + if (data) myfilters.push(data); } if (myfilters.length > 0) { - query = [ - { $match: { $or: myfilters } }, - ]; + query = [{ $match: { $or: myfilters } }]; } return query; }, addQueryIdMatch: function (params) { - myquery = {}; - if (shared_consts.TABLES_ID_NUMBER.includes(params.table) || shared_consts.TABLES_ID_STRING.includes(params.table)) { + if ( + shared_consts.TABLES_ID_NUMBER.includes(params.table) || + shared_consts.TABLES_ID_STRING.includes(params.table) + ) { myquery = { $match: { $expr: { @@ -2422,7 +2390,6 @@ module.exports = { }, }, }; - } return myquery; @@ -2444,7 +2411,6 @@ module.exports = { }, addNumFavoriteAndBookmarkToQuery(idapp, numtab) { - let query = []; try { @@ -2553,48 +2519,44 @@ module.exports = { } return { query, proj }; - }, getQueryMyBacheca: function (idapp) { - - const arrquery = [{ - $lookup: { - from: "bookings", - let: { - id: '$_id', - }, - pipeline: [ - { - $match: { - $expr: { - $and: [ - { $eq: ['$id_bookedevent', '$$id'] }, - { $eq: ['$idapp', idapp] }, - ], + const arrquery = [ + { + $lookup: { + from: 'bookings', + let: { + id: '$_id', + }, + pipeline: [ + { + $match: { + $expr: { + $and: [{ $eq: ['$id_bookedevent', '$$id'] }, { $eq: ['$idapp', idapp] }], + }, }, }, - }, - { - $project: { - id_bookedevent: 1, - username: 1, - numpeople: 1, - numpeopleLunch: 1, - numpeopleDinner: 1, - numpeopleDinnerShared: 1, - infoevent: 1, - msgbooking: 1, - booked: 1, - datebooked: 1, - userId: 1, - idapp: 1, - } - }, - ], - as: 'mybookings', + { + $project: { + id_bookedevent: 1, + username: 1, + numpeople: 1, + numpeopleLunch: 1, + numpeopleDinner: 1, + numpeopleDinnerShared: 1, + infoevent: 1, + msgbooking: 1, + booked: 1, + datebooked: 1, + userId: 1, + idapp: 1, + }, + }, + ], + as: 'mybookings', + }, }, - }, /** { $lookup: { @@ -2639,17 +2601,13 @@ module.exports = { as: "myuser", }, }**/ - ]; return arrquery; - }, getQueryTable: async function (idapp, params, user) { - try { - const { Search } = require('../models/search'); if (typeof params.startRow !== 'number') { @@ -2683,21 +2641,18 @@ module.exports = { if (params.filterand) { params.filterand = this.sanitizzaHtml(params.filterand); - if (params.filterand.includes( - shared_consts.FILTER_EXTRALIST_NOT_REGISTERED)) + if (params.filterand.includes(shared_consts.FILTER_EXTRALIST_NOT_REGISTERED)) filtriadded.push({ registered: false }); - if (params.filterand.includes( - shared_consts.FILTER_EXTRALIST_NOT_CONTACTED)) { + if (params.filterand.includes(shared_consts.FILTER_EXTRALIST_NOT_CONTACTED)) { filtriadded.push({ contacted: { $exists: false } }); } if (params.filterand.includes(shared_consts.FILTER_EXTRALIST_WITH_NOTE)) filtriadded.push({ - 'note': { $exists: true }, - '$expr': { '$gt': [{ '$strLenCP': '$note' }, 1] }, + note: { $exists: true }, + $expr: { $gt: [{ $strLenCP: '$note' }, 1] }, }); - if (params.filterand.includes(shared_consts.FILTER_QUALIFIED)) - filtriadded.push({ 'profile.qualified': true }); + if (params.filterand.includes(shared_consts.FILTER_QUALIFIED)) filtriadded.push({ 'profile.qualified': true }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_ZOOM)) filtriadded.push({ 'profile.saw_zoom_presentation': false }); if (params.filterand.includes(shared_consts.FILTER_ASK_ZOOM_VISTO)) @@ -2710,11 +2665,9 @@ module.exports = { filtriadded.push({ 'profile.teleg_id': { $lt: 1 } }); if (params.filterand.includes(shared_consts.FILTER_USER_SI_TELEGRAM_ID)) filtriadded.push({ 'profile.teleg_id': { $gt: 1 } }); - if (params.filterand.includes( - shared_consts.FILTER_USER_CODICE_AUTH_TELEGRAM)) + if (params.filterand.includes(shared_consts.FILTER_USER_CODICE_AUTH_TELEGRAM)) filtriadded.push({ 'profile.teleg_checkcode': { $gt: 1 } }); - if (params.filterand.includes( - shared_consts.FILTER_USER_NO_EMAIL_VERIFICATA)) + if (params.filterand.includes(shared_consts.FILTER_USER_NO_EMAIL_VERIFICATA)) filtriadded.push({ verified_email: false }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_VERIFIED_APORTADOR)) filtriadded.push({ @@ -2724,8 +2677,8 @@ module.exports = { filtriadded.push({ $or: [ { 'profile.username_telegram': { $exists: false } }, - { 'profile.username_telegram': { $exists: true, $eq: '' } }], - + { 'profile.username_telegram': { $exists: true, $eq: '' } }, + ], }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_DREAM)) filtriadded.push({ @@ -2741,33 +2694,23 @@ module.exports = { filtriadded.push({ 'profile.resid_province': { $exists: false } }); if (params.filterand.includes(shared_consts.FILTER_ATTIVI)) filtriadded.push({ - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); // Hours if (params.filterand.includes(shared_consts.FILTER_HOURS_ALL)) - filtriadded.push( - { - idapp, - todoId: params.codeId, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }, - ); + filtriadded.push({ + idapp, + todoId: params.codeId, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }); else if (params.filterand.includes(shared_consts.FILTER_HOURS_MYLIST)) - filtriadded.push( - { - idapp, - userId: params.userId, - todoId: params.codeId, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }, - ); + filtriadded.push({ + idapp, + userId: params.userId, + todoId: params.codeId, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }); if (params.filterand.includes(shared_consts.FILTER_NASCOSTI)) filtriadded.push({ @@ -2776,31 +2719,23 @@ module.exports = { if (params.filterand.includes(shared_consts.FILTER_NAVI_NON_PRESENTI)) filtriadded.push({ navinonpresenti: { $exists: true, $eq: true }, - $or: [ - { subaccount: { $exists: false } }, - { subaccount: { $exists: true, $eq: false } }], + $or: [{ subaccount: { $exists: false } }, { subaccount: { $exists: true, $eq: false } }], }); // Iscritti Conacreis if (params.filterand.includes(shared_consts.FILTER_REPORTED)) - filtriadded.push( - { reported: { $exists: true, $eq: true } }, - ); + filtriadded.push({ reported: { $exists: true, $eq: true } }); - if (params.filterand.includes( - shared_consts.FILTER_TO_MAKE_MEMBERSHIP_CARD)) + if (params.filterand.includes(shared_consts.FILTER_TO_MAKE_MEMBERSHIP_CARD)) filtriadded.push({ - $or: [ - { codiceConacreis: { $exists: false } }, - { codiceConacreis: { $exists: true, $eq: '' } }], + $or: [{ codiceConacreis: { $exists: false } }, { codiceConacreis: { $exists: true, $eq: '' } }], }); if (params.filterand.includes(shared_consts.FILTER_MEMBERSHIP_CARD_OK)) filtriadded.push({ codiceConacreis: { $exists: true }, - '$expr': { '$gt': [{ '$strLenCP': '$codiceConacreis' }, 0] }, + $expr: { $gt: [{ $strLenCP: '$codiceConacreis' }, 0] }, }); - } if (params.filtercustom) { @@ -2849,27 +2784,22 @@ module.exports = { } if (params.options) { - if (this.isBitActive(params.options, - shared_consts.OPTIONS_SEARCH_ONLY_FULL_WORDS)) { + if (this.isBitActive(params.options, shared_consts.OPTIONS_SEARCH_ONLY_FULL_WORDS)) { } } - if (params.filterextra) { params.filterextra = this.sanitizzaHtml(params.filterextra); - if (params.filterextra.length > 0) - query = [...query, ...params.filterextra] + if (params.filterextra.length > 0) query = [...query, ...params.filterextra]; } if (filtriadded) { filtriadded = this.sanitizzaHtml(filtriadded); - if (filtriadded.length > 0) - query.push({ $match: { $and: filtriadded } }); + if (filtriadded.length > 0) query.push({ $match: { $and: filtriadded } }); } let numrowend = params.endRow - params.startRow; - if (numrowend < 0) - numrowend = 1; + if (numrowend < 0) numrowend = 1; let projectEnd = { $slice: ['$results', params.startRow, numrowend] }; @@ -2880,33 +2810,31 @@ module.exports = { } if (params.searchByBoundariesMap) { - projectEnd = "$results"; + projectEnd = '$results'; querymatch.coordinate_gps = { $geoWithin: { $box: [ [params.searchByBoundariesMap.sw.lng, params.searchByBoundariesMap.sw.lat], - [params.searchByBoundariesMap.ne.lng, params.searchByBoundariesMap.ne.lat] - ] - } + [params.searchByBoundariesMap.ne.lng, params.searchByBoundariesMap.ne.lat], + ], + }, }; - }; + } if (Object.keys(querymatch).length > 0) { - query.push( - { $match: querymatch }); - + query.push({ $match: querymatch }); } // console.log('QUERYMATCH', query[0].$match.or); // console.log('filter', params.filter); - - if (params.querytype === shared_consts.QUERYTYPE_MYGROUP || params.querytype === shared_consts.QUERYTYPE_CIRCUIT) { - + if ( + params.querytype === shared_consts.QUERYTYPE_MYGROUP || + params.querytype === shared_consts.QUERYTYPE_CIRCUIT + ) { const myq = this.addQueryIdMatch(params); - if (myq) - query.push(myq); + if (myq) query.push(myq); query.push({ $project: { req_users: 1 } }); const qa1 = this.getLookup( @@ -2915,38 +2843,37 @@ module.exports = { lk_LF: 'req_users.username', lk_FF: 'username', lk_as: 'user', - }, 0, { - 'user.idapp': 1, - 'user.username': 1, - 'user.name': 1, - 'user.surname': 1, - 'user.profile.img': 1, - 'user.profile.qualifica': 1, - 'user.profile.note': 1, - 'profile.da_contattare': 1, - }); + }, + 0, + { + 'user.idapp': 1, + 'user.username': 1, + 'user.name': 1, + 'user.surname': 1, + 'user.profile.img': 1, + 'user.profile.qualifica': 1, + 'user.profile.note': 1, + 'profile.da_contattare': 1, + } + ); if (qa1) query = [...query, ...qa1]; query.push({ $unwind: '$user' }); query.push({ $match: { - $and: [ - { 'user.idapp': params.idapp }, - ], + $and: [{ 'user.idapp': params.idapp }], }, }); - query.push({ $replaceRoot: { newRoot: '$user', }, - }, - ); - - } else if (params.querytype === shared_consts.QUERYTYPE_REFUSED_USER_GRP || params.querytype === - shared_consts.QUERYTYPE_REFUSED_USER_CIRCUIT) { - + }); + } else if ( + params.querytype === shared_consts.QUERYTYPE_REFUSED_USER_GRP || + params.querytype === shared_consts.QUERYTYPE_REFUSED_USER_CIRCUIT + ) { /* const myq = this.addQueryIdMatch(params); if (myq) @@ -2954,8 +2881,7 @@ module.exports = { */ const myq = this.addQueryIdMatch(params); - if (myq) - query.push(myq); + if (myq) query.push(myq); query.push({ $project: { refused_users: 1 } }); query.push({ $unwind: '$refused_users' }); @@ -2966,16 +2892,18 @@ module.exports = { lk_FF: 'username', lk_as: 'user', idapp, - }, { - 'user.idapp': 1, - 'user.username': 1, - 'user.name': 1, - 'user.surname': 1, - 'user.profile.img': 1, - 'user.profile.qualifica': 1, - 'user.profile.note': 1, - 'profile.da_contattare': 1, - }); + }, + { + 'user.idapp': 1, + 'user.username': 1, + 'user.name': 1, + 'user.surname': 1, + 'user.profile.img': 1, + 'user.profile.qualifica': 1, + 'user.profile.note': 1, + 'profile.da_contattare': 1, + } + ); if (qa1) query = [...query, ...qa1]; query.push({ $unwind: '$user' }); /* @@ -2992,13 +2920,10 @@ module.exports = { $replaceRoot: { newRoot: '$user', }, - }, - ); + }); } else if (params.querytype === shared_consts.QUERYTYPE_GROUP_CIRCUIT) { - const myq = this.addQueryIdMatch(params); - if (myq) - query.push(myq); + if (myq) query.push(myq); query.push({ $project: { req_groups: 1 } }); const qa1 = this.getLookup( @@ -3007,56 +2932,47 @@ module.exports = { lk_LF: 'req_groups.groupname', lk_FF: 'groupname', lk_as: 'group', - }, 0, { - 'group.idapp': 1, - 'group.groupname': 1, - 'group.photos': 1, - }); + }, + 0, + { + 'group.idapp': 1, + 'group.groupname': 1, + 'group.photos': 1, + } + ); if (qa1) query = [...query, ...qa1]; query.push({ $unwind: '$group' }); if (true) { - query.push({ $match: { - $and: [ - { 'group.idapp': params.idapp }, - ], + $and: [{ 'group.idapp': params.idapp }], coordinate_gps: { $geoWithin: { $box: [ [searchByBoudariesMap.sw.lng, searchByBoudariesMap.sw.lat], - [searchByBoudariesMap.ne.lng, searchByBoudariesMap.ne.lat] - ] - } - } + [searchByBoudariesMap.ne.lng, searchByBoudariesMap.ne.lat], + ], + }, + }, }, }); } else { - query.push({ $match: { - $and: [ - { 'group.idapp': params.idapp }, - ], + $and: [{ 'group.idapp': params.idapp }], }, }); } - query.push({ $replaceRoot: { newRoot: '$group', }, - }, - ); - + }); } else if (params.querytype === shared_consts.QUERYTYPE_REFUSED_GROUP_CIRCUIT) { - - const myq = this.addQueryIdMatch(params); - if (myq) - query.push(myq); + if (myq) query.push(myq); query.push({ $project: { refused_groups: 1 } }); query.push({ $unwind: '$refused_groups' }); @@ -3067,12 +2983,14 @@ module.exports = { lk_FF: 'groupname', lk_as: 'group', idapp, - }, { - 'group.idapp': 1, - 'group.groupname': 1, - 'group.descr': 1, - 'group.photos': 1, - }); + }, + { + 'group.idapp': 1, + 'group.groupname': 1, + 'group.descr': 1, + 'group.photos': 1, + } + ); if (qa1) query = [...query, ...qa1]; query.push({ $unwind: '$group' }); /* @@ -3089,45 +3007,35 @@ module.exports = { $replaceRoot: { newRoot: '$group', }, - }, - ); - + }); } else if (params.querytype === shared_consts.QUERYTYPE_LIST_MOVEMENTS) { - const { Movement } = require('../models/movement'); const myquery = await Movement.getQueryMovsByCircuitId(params.idapp, params.username, '', '', params.myid); query.push(...myquery); } else if (params.querytype === shared_consts.QUERYTYPE_LIST_MOVEMENTS_GROUPNAME) { - const { Movement } = require('../models/movement'); const myquery = await Movement.getQueryMovsByCircuitId(params.idapp, '', params.groupname, '', params.myid); query.push(...myquery); - } else if (params.querytype === shared_consts.QUERYTYPE_LIST_MOVEMENTS_CONTOCOM) { - const { Movement } = require('../models/movement'); const myquery = await Movement.getQueryMovsByCircuitId(params.idapp, '', '', params.contocom, params.myid); query.push(...myquery); - } else if (params.querytype === shared_consts.QUERYTYPE_LIST_ALLMOVEMENTS) { - const { Movement } = require('../models/movement'); const myquery = await Movement.getQueryAllUsersMovsByCircuitId(params.idapp, params.myid); query.push(...myquery); - } if (params.filterextra2) { - if (params.filterextra2.length > 0) - query = [...query, ...params.filterextra2]; + if (params.filterextra2.length > 0) query = [...query, ...params.filterextra2]; } if (newvers) { @@ -3148,7 +3056,6 @@ module.exports = { let numtab = this.getNumTabByTable(params.table); - const q1 = this.getLookup(params.lookup1, 1, proj, objadd.proj); if (q1) query = [...query, ...q1]; @@ -3166,7 +3073,6 @@ module.exports = { params.lookup4 = this.sanitizzaLookup(params.lookup4); params.lookup5 = this.sanitizzaLookup(params.lookup5); - const q2 = this.getLookup(params.lookup2, 2, proj, objadd.proj); if (q2) query = [...query, ...q2]; @@ -3190,54 +3096,52 @@ module.exports = { } } - let filteradmin = false; if (params.filtercustom) { let condition = {}; for (const myfilter of params.filtercustom) { - if (!!myfilter.admins) { filteradmin = true; } - if (myfilter['pub_to_share'] === shared_consts.PUBTOSHARE.ONLY_TABLE_FOLLOW && params.table === 'mygroups') { - + if ( + myfilter['pub_to_share'] === shared_consts.PUBTOSHARE.ONLY_TABLE_FOLLOW && + params.table === 'mygroups' + ) { let arraygroups = []; if (user && user.profile.mygroups) { - arraygroups = user.profile.mygroups.map(rec => rec.groupname); + arraygroups = user.profile.mygroups.map((rec) => rec.groupname); } // prendere i gruppi dell'utente // Cerca tra i gruppi di ogni record, se combaciano almeno 1 condition = { - 'profile.mygroups': - { + 'profile.mygroups': { $elemMatch: { groupname: { $in: arraygroups }, }, - }, }; query.push({ $match: { $and: [condition] } }); - } else if (myfilter['pub_to_share'] === shared_consts.PUBTOSHARE.ONLY_TABLE_FOLLOW && params.table === 'circuits') { - + } else if ( + myfilter['pub_to_share'] === shared_consts.PUBTOSHARE.ONLY_TABLE_FOLLOW && + params.table === 'circuits' + ) { let arraycircuits = []; if (user && user.profile.mycircuits) { - arraycircuits = user.profile.mycircuits.map(rec => rec.circuitname); + arraycircuits = user.profile.mycircuits.map((rec) => rec.circuitname); } // prendere i gruppi dell'utente // Cerca tra i gruppi di ogni record, se combaciano almeno 1 condition = { - 'profile.mycircuits': - { + 'profile.mycircuits': { $elemMatch: { circuitname: { $in: arraycircuits }, }, - }, }; @@ -3248,37 +3152,35 @@ module.exports = { let arraygroups = []; if (user && user.profile.mygroups) { - arraygroups = user.profile.mygroups.map(rec => rec.groupname); + arraygroups = user.profile.mygroups.map((rec) => rec.groupname); } // prendere i gruppi dell'utente // Cerca tra i gruppi di ogni record, se combaciano almeno 1 condition = { - 'profile.mygroups': - { + 'profile.mygroups': { $elemMatch: { groupname: { $in: arraygroups }, }, - }, }; - query.push( - { - $match: - { - $or: [ - { - $and: [condition, { pub_to_share: 1 }], - }, - { $or: [{ pub_to_share: { $exists: false } }, { pub_to_share: { $exists: true, $eq: shared_consts.PUBTOSHARE.ALL } }] }, - ], - }, + query.push({ + $match: { + $or: [ + { + $and: [condition, { pub_to_share: 1 }], + }, + { + $or: [ + { pub_to_share: { $exists: false } }, + { pub_to_share: { $exists: true, $eq: shared_consts.PUBTOSHARE.ALL } }, + ], + }, + ], }, - ); - + }); } - } } @@ -3297,27 +3199,24 @@ module.exports = { if (params.filtersearch3and.length > 0) { // Se c'è statusskill allora glielo metto in OR - if (params.table === 'myskills' && params.filtersearch && !this.contieneIdStatusSkill(params.filtersearch)) { - + if ( + params.table === 'myskills' && + params.filtersearch && + !this.contieneIdStatusSkill(params.filtersearch) + ) { query.push({ $match: { - $or: [ - { $and: params.filtersearch3and }, - { idStatusSkill: { $in: [2] } } - ] - } + $or: [{ $and: params.filtersearch3and }, { idStatusSkill: { $in: [2] } }], + }, }); } else { query.push({ $match: { $and: params.filtersearch3and } }); } - - } } if (params.filter && params.fieldsearch_last) { - const querytemp = this.getFilterParam(params.filter, - params.fieldsearch_last); + const querytemp = this.getFilterParam(params.filter, params.fieldsearch_last); if (querytemp) { query = [...query, ...querytemp]; } @@ -3361,19 +3260,16 @@ module.exports = { }, ]; query.push({ $match: { $and: filter } }); - } } // } } - if (params.options && this.isBitActive(params.options, - shared_consts.OPTIONS_ADD_COUNT_FAVORITE)) { + if (params.options && this.isBitActive(params.options, shared_consts.OPTIONS_ADD_COUNT_FAVORITE)) { // objadd = this.addNumFavoriteAndBookmarkToQuery(idapp, numtab); // if (Object.keys(objadd.query).length > 0) // query = [...query, ...objadd.query]; } - } else { // VECCHIA VERSIONE const q1 = this.getLookup(params, 1); @@ -3397,18 +3293,16 @@ module.exports = { // keep our results for the next operation results: { $push: '$$ROOT' }, }, - }, + } // and finally trim the results to within the range given by start/endRow ); if (projectEnd) { - query.push( - { - $project: { - count: 1, - rows: projectEnd, - }, + query.push({ + $project: { + count: 1, + rows: projectEnd, }, - ); + }); } if (this.testing()) { @@ -3420,7 +3314,6 @@ module.exports = { } catch (e) { console.error('Err query:', e); } - }, startTimeLog(name) { @@ -3428,9 +3321,7 @@ module.exports = { // console.log('inizio', name); try { console.time(name); - } catch (e) { - - } + } catch (e) {} } }, @@ -3453,17 +3344,13 @@ module.exports = { if (ris) { if (params.table === 'users') { for (const myrec of ris.rows) { - if (myrec.ipaddr) - myrec.ipaddr = ''; - if (myrec.tokens) - myrec.tokens = []; - if (myrec.password) - myrec.password = ''; + if (myrec.ipaddr) myrec.ipaddr = ''; + if (myrec.tokens) myrec.tokens = []; + if (myrec.password) myrec.password = ''; } } else if (params.table === 'mygroups') { for (const myrec of ris.rows) { - if (myrec.pwd_cryp) - myrec.pwd_cryp = ''; + if (myrec.pwd_cryp) myrec.pwd_cryp = ''; } } @@ -3471,14 +3358,13 @@ module.exports = { // console.table(ris.rows); // console.log('ROW ', ris.count); - return ({ count: ris.count, rows: ris.rows }); + return { count: ris.count, rows: ris.rows }; } else { - return ({ count: 0, rows: [] }); + return { count: 0, rows: [] }; } } catch (e) { console.log('error', e); } - }, async DuplicateAllRecords(mythistable, idapporig, idappdest) { console.log(mythistable.name); @@ -3507,11 +3393,9 @@ module.exports = { if (rec) { num++; } - } catch (e) { console.error('e', e); } - } return num; }); @@ -3519,23 +3403,23 @@ module.exports = { }, isBitActive(bit, whattofind) { - return ((bit & whattofind) === whattofind); + return (bit & whattofind) === whattofind; }, isBitAttivoESelez(bit, whattofind, loSono) { const abil = this.isBitActive(bit, whattofind); - return ((abil && loSono) || !abil); + return (abil && loSono) || !abil; }, SetBit(myval, bit) { - let myvalout = myval - myvalout |= bit - return myvalout + let myvalout = myval; + myvalout |= bit; + return myvalout; }, async snooze(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); }, IncDateNow(secs) { @@ -3548,8 +3432,8 @@ module.exports = { let mydate = new Date(); // console.log('mydate', mydate); let mydata2 = new Date(mydatediffstr); - let ris = ((mydate.getTime() - mydata2.getTime()) / 1000); - return (ris < secs); + let ris = (mydate.getTime() - mydata2.getTime()) / 1000; + return ris < secs; }, AddDate(mydate, days) { @@ -3571,7 +3455,6 @@ module.exports = { // var startTime = '15:10:10'; // var endTime = '22:30:00'; isBetweenTwoTime(startTime, endTime) { - currentDate = new Date(); startDate = new Date(currentDate.getTime()); @@ -3590,7 +3473,6 @@ module.exports = { }, getlimiti(mypos) { - if (mypos.col < 0) { mypos.col = 0; } @@ -3606,11 +3488,11 @@ module.exports = { getRigaColByPosUp(mypos) { if (mypos.numup > 0) { mypos.riga = mypos.riga - mypos.numup; - mypos.col = Math.ceil(mypos.col / (Math.pow(2, mypos.numup))); + mypos.col = Math.ceil(mypos.col / Math.pow(2, mypos.numup)); } if (mypos.numup < 0) { mypos.riga = mypos.riga - mypos.numup; - mypos.col = Math.ceil(mypos.col * (Math.pow(2, -mypos.numup))); + mypos.col = Math.ceil(mypos.col * Math.pow(2, -mypos.numup)); } if (mypos.riga < 1) { mypos.riga = 1; @@ -3656,68 +3538,18 @@ module.exports = { }, getWeekDayByLangByNumCar(date, lang, num) { - if (!lang) - lang = 'it'; + if (!lang) lang = 'it'; const dayOfWeek = new Date(date).getDay(); const myday = { - it: [ - 'Domenica', - 'Lunedì', - 'Martedì', - 'Mercoledì', - 'Giovedì', - 'Venerdì', - 'Sabato'], - enUs: [ - 'Sunday', - 'Monday', - 'Tuesday', - 'Wednesday', - 'Thursday', - 'Friday', - 'Saturday'], - fr: [ - 'Dimanche', - 'Lundi', - 'Mardi', - 'Mercredi', - 'Jeudi', - 'Vendredi', - 'Samedi'], - es: [ - 'Domingo', - 'Lunes', - 'Martes', - 'Miércoles', - 'Jueves', - 'iernes', - 'Sábado'], - pt: [ - 'Domingo', - 'Segunda', - 'Terça', - 'Quarta', - 'Quinta', - 'Sexta', - 'Sábado'], - de: [ - 'Sonntag', - 'Montag', - 'Dienstag', - 'Mittwoch', - 'Donnerstag', - 'Freitag', - 'Samstag'], - si: [ - 'Nedelja', - 'Ponedeljek', - 'Torek', - 'Sreda', - 'četrtek', - 'Petek', - 'Sobota'], + it: ['Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato'], + enUs: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + fr: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], + es: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'iernes', 'Sábado'], + pt: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'], + de: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], + si: ['Nedelja', 'Ponedeljek', 'Torek', 'Sreda', 'četrtek', 'Petek', 'Sobota'], }; if (num > 0) { @@ -3757,15 +3589,7 @@ module.exports = { getWeekDay(date) { //Create an array containing each day, starting with Sunday. - const weekdays = [ - 'Domenica', - 'Lunedì', - 'Martedì', - 'Mercoledì', - 'Giovedí', - 'Venerdì', - 'Sabato', - ]; + const weekdays = ['Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedí', 'Venerdì', 'Sabato']; //Use the getDay() method to get the day. const day = date.getDay(); //Return the element that corresponds to that index. @@ -3775,11 +3599,17 @@ module.exports = { getstrDateTimeShort(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) - return this.getWeekDayByLang(mydate, lang) + ' ' + - this.appendLeadingZeroes(mydate.getDate()) + '/' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + ' ORE ' + - this.appendLeadingZeroes(mydate.getHours()) + ':' + - this.appendLeadingZeroes(mydate.getMinutes()); + return ( + this.getWeekDayByLang(mydate, lang) + + ' ' + + this.appendLeadingZeroes(mydate.getDate()) + + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + + ' ORE ' + + this.appendLeadingZeroes(mydate.getHours()) + + ':' + + this.appendLeadingZeroes(mydate.getMinutes()) + ); } else { return ''; } @@ -3795,15 +3625,19 @@ module.exports = { // Format the hour and minute components as HH:MM const formattedTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`; - return formattedTime + return formattedTime; }, getstrDateShort(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) - return this.getWeekDayByLang(mydate, lang).substring(0, 3) + ' ' + - this.appendLeadingZeroes(mydate.getDate()) + '/' + - this.appendLeadingZeroes(mydate.getMonth() + 1); + return ( + this.getWeekDayByLang(mydate, lang).substring(0, 3) + + ' ' + + this.appendLeadingZeroes(mydate.getDate()) + + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + ); } else { return ''; } @@ -3812,9 +3646,13 @@ module.exports = { getstrDate_DD_MM_YYYY(mydate) { if (mydate) { // console.log('getstrDate', mytimestamp) - return this.appendLeadingZeroes(mydate.getDate()) + '/' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + - this.appendLeadingZeroes(mydate.getFullYear()); + return ( + this.appendLeadingZeroes(mydate.getDate()) + + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + + '/' + + this.appendLeadingZeroes(mydate.getFullYear()) + ); } else { return ''; } @@ -3823,9 +3661,13 @@ module.exports = { getstrDateYYYY_MM_DD(mydate) { if (mydate) { // console.log('getstrDate', mytimestamp) - return mydate.getFullYear() + '-' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + - this.appendLeadingZeroes(mydate.getDate()); + return ( + mydate.getFullYear() + + '-' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + + '-' + + this.appendLeadingZeroes(mydate.getDate()) + ); } else { return ''; } @@ -3834,9 +3676,13 @@ module.exports = { getstrUTCDateYYYY_MM_DD(mydate) { if (mydate) { // console.log('getstrDate', mytimestamp) - return mydate.getUTCFullYear() + '-' + - this.appendLeadingZeroes(mydate.getUTCMonth() + 1) + '-' + - this.appendLeadingZeroes(mydate.getUTCDate()); + return ( + mydate.getUTCFullYear() + + '-' + + this.appendLeadingZeroes(mydate.getUTCMonth() + 1) + + '-' + + this.appendLeadingZeroes(mydate.getUTCDate()) + ); } else { return ''; } @@ -3845,10 +3691,15 @@ module.exports = { getstrDateLong(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) - return this.getWeekDayByLang(mydate, lang) + ' ' + - this.appendLeadingZeroes(mydate.getDate()) + '/' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + - mydate.getFullYear(); + return ( + this.getWeekDayByLang(mydate, lang) + + ' ' + + this.appendLeadingZeroes(mydate.getDate()) + + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + + '/' + + mydate.getFullYear() + ); } else { return ''; } @@ -3857,10 +3708,15 @@ module.exports = { getstrDateLongTot(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) - return this.getWeekDayByLangTot(mydate, lang) + ' ' + - this.appendLeadingZeroes(mydate.getDate()) + '/' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + - mydate.getFullYear(); + return ( + this.getWeekDayByLangTot(mydate, lang) + + ' ' + + this.appendLeadingZeroes(mydate.getDate()) + + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + + '/' + + mydate.getFullYear() + ); } else { return ''; } @@ -3869,10 +3725,16 @@ module.exports = { getstrDateLongFile(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) - return mydate.getFullYear() + '-' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + - this.appendLeadingZeroes(mydate.getDate()) + ' (' + - this.getWeekDayByLang(mydate, lang) + ')'; + return ( + mydate.getFullYear() + + '-' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + + '-' + + this.appendLeadingZeroes(mydate.getDate()) + + ' (' + + this.getWeekDayByLang(mydate, lang) + + ')' + ); } else { return ''; } @@ -3886,19 +3748,16 @@ module.exports = { }; } let typeconf = rec.typeconf; - if (typeconf === '') - typeconf = this.TYPECONF_ZOOM; + if (typeconf === '') typeconf = this.TYPECONF_ZOOM; let mylink = 'https://zoom.us/j/'; - if (typeconf === this.TYPECONF_JITSI) - mylink = 'https://meet.jit.si/'; + if (typeconf === this.TYPECONF_JITSI) mylink = 'https://meet.jit.si/'; if (rec.id_conf_zoom === '') { rec.id_conf_zoom = '6668882000'; } return mylink + rec.id_conf_zoom; - }, getmd5(mystr) { @@ -3984,8 +3843,7 @@ module.exports = { } }, cryptdata(mydata) { - if (mydata === '') - return ''; + if (mydata === '') return ''; // Encrypt //return CryptoJS.AES.encrypt(JSON.stringify(mydata), process.env.SECRK); return this.encrypt(mydata, process.env.SECRK); @@ -4006,11 +3864,11 @@ module.exports = { }, BoolToInt(mybool) { - return (mybool) ? -1 : 0; + return mybool ? -1 : 0; }, StrToBool(mystr) { - return (mystr === '-1') ? true : false; + return mystr === '-1' ? true : false; }, writelogfile(mystr, filename) { @@ -4024,14 +3882,10 @@ module.exports = { const stream = fs.createWriteStream(filename, { flags: 'a' }); stream.write('\n' + mystr); stream.end(); - } catch (e) { - - } - + } catch (e) {} }, async readlogfile(idapp, filename) { - try { return await fs.readFileSync(idapp + '/' + filename, 'utf8'); } catch (e) { @@ -4040,7 +3894,6 @@ module.exports = { }, async readfilecontent(filename) { - try { const cont = await fs.readFileSync(filename, 'utf8'); return cont; @@ -4053,7 +3906,6 @@ module.exports = { return await this.readfilecontent(__dirname + '/../version.txt'); }, - writelog(mystr) { this.writelogfile(mystr, FILELOG); }, @@ -4132,7 +3984,6 @@ module.exports = { }, copy(oldPath, newPath, callback) { - fs.copyFile(oldPath, newPath, (err) => { if (err) throw err; // console.log('source.txt was copied to destination.txt'); @@ -4158,19 +4009,14 @@ module.exports = { }, delete(mypath, alsothumb, callback) { - fs.unlink(mypath, function (err) { if (alsothumb) { try { - let img_small = path.dirname(mypath) + '/' + - server_constants.PREFIX_IMG_SMALL + path.basename(mypath); + let img_small = path.dirname(mypath) + '/' + server_constants.PREFIX_IMG_SMALL + path.basename(mypath); fs.unlink(img_small, function (err) { - if (err) - console.log('Errore durante la Cancellazione del file', mypath); - else - console.log('deleted file', mypath); + if (err) console.log('Errore durante la Cancellazione del file', mypath); + else console.log('deleted file', mypath); }); - } catch (e) { console.error(err); } @@ -4186,7 +4032,7 @@ module.exports = { async mkdirpath(dirPath) { try { - if (!await this.isFileExists(dirPath)) { + if (!(await this.isFileExistsAsync(dirPath))) { fs.mkdirSync(dirPath, { recursive: true }); } } catch (e) { @@ -4242,26 +4088,14 @@ module.exports = { return namesurname; }, - async isFileExists(filename) { - try { - let fileExists = await fs.promises.stat(filename).then(() => true).catch(() => false); - // console.log(filename, 'esiste', fileExists) - return fileExists; - } catch (e) { - // console.log(filename, 'esiste', 'FALSE') - return false - } - }, - getiPAddressUser(req) { try { const striniziale = '::ffff:'; if (req.ip.indexOf(striniziale) >= 0) { return req.ip.substring(striniziale.length); } else { - return req.ip; // Express + return req.ip; // Express } - } catch (e) { return ''; } @@ -4281,11 +4115,11 @@ module.exports = { return true; } if (table === 'users') { - if (idrec && (req.user._id.toString() === idrec)) { - if (Object.keys(fieldsvalue).some(key => key.startsWith('profile.'))) { + if (idrec && req.user._id.toString() === idrec) { + if (Object.keys(fieldsvalue).some((key) => key.startsWith('profile.'))) { return true; } - if (Object.keys(fieldsvalue).some(key => server_constants.User_Fields.includes(key))) { + if (Object.keys(fieldsvalue).some((key) => server_constants.User_Fields.includes(key))) { return true; } } @@ -4321,8 +4155,7 @@ module.exports = { }, NotifyIfDelRecord(table) { - if ((table === 'users') || (table === 'extralist') || - (table === 'groups') || (table === 'graduatorias')) { + if (table === 'users' || table === 'extralist' || table === 'groups' || table === 'graduatorias') { return true; } @@ -4331,17 +4164,13 @@ module.exports = { getFirstWord(mystr) { const myarr = mystr.split(' '); - if (myarr.length > 0) - return myarr[0]; - else - return mystr; + if (myarr.length > 0) return myarr[0]; + else return mystr; }, getFirst2Car(mystr) { - if (!!mystr) - return mystr.substring(0, 2) + '.'; - else - return ''; + if (!!mystr) return mystr.substring(0, 2) + '.'; + else return ''; }, getmaxcol(riga) { @@ -4350,34 +4179,28 @@ module.exports = { getPrimoFuocoByIndCol(col) { // let ris = Math.ceil(col - (col % 8)) + 1; - let ris = ((Math.ceil(col / 8) - 1) * 8) + 1; - if (ris <= 0) - ris = 1; + let ris = (Math.ceil(col / 8) - 1) * 8 + 1; + if (ris <= 0) ris = 1; return ris; }, getPrimaColFlotta(col) { // let ris = Math.ceil(col - (col % 8)) + 1; - let ris = ((Math.ceil(col / 64) - 1) * 64) + 1; - if (ris <= 0) - ris = 1; + let ris = (Math.ceil(col / 64) - 1) * 64 + 1; + if (ris <= 0) ris = 1; return ris; }, getStrMsgByTipoMsg(tipomsg) { - let mystr = ''; if (tipomsg === this.TipoMsg.SEND_MSG_EFFETTUA_IL_DONO) mystr = 'Inviato Messaggio per Effettuare il Dono a Tutta la Flotta'; else if (tipomsg === this.TipoMsg.SEND_MSG_SOLLECITO_DONATORI_NO_DONO) - mystr = 'Inviato Messaggio per RICORDARE di Effettuare il Dono a chi ancora non l\'ha fatto'; - else if (tipomsg === this.TipoMsg.SEND_MSG_A_MEDIATORI) - mystr = 'Inviato Messaggio ai Mediatori'; - else if (tipomsg === this.TipoMsg.SEND_MSG_A_SOGNATORE) - mystr = 'Inviato Messaggio al Sognatore'; - else if (tipomsg === this.TipoMsg.SEND_MSG_A_UTENTE_SOSTITUITO) - mystr = 'Inviato Messaggio all\'utente Sostituito'; + mystr = "Inviato Messaggio per RICORDARE di Effettuare il Dono a chi ancora non l'ha fatto"; + else if (tipomsg === this.TipoMsg.SEND_MSG_A_MEDIATORI) mystr = 'Inviato Messaggio ai Mediatori'; + else if (tipomsg === this.TipoMsg.SEND_MSG_A_SOGNATORE) mystr = 'Inviato Messaggio al Sognatore'; + else if (tipomsg === this.TipoMsg.SEND_MSG_A_UTENTE_SOSTITUITO) mystr = "Inviato Messaggio all'utente Sostituito"; else if (tipomsg === this.TipoMsg.SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE) mystr = 'Inviato Messaggio Dono Ricevuto Correttamente'; @@ -4385,29 +4208,16 @@ module.exports = { }, getflagtelegrambyLang(lang) { - if (lang === 'it') - return '🇮🇹'; - else if (lang === 'si') - return '🇸🇮'; - else if (lang === 'es') - return '🇪🇸'; - else if (lang === 'enUs') - return '🇬🇧'; - else if (lang === 'uk') - return '🇬🇧'; - else if (lang === 'fr') - return '🇫🇷'; + if (lang === 'it') return '🇮🇹'; + else if (lang === 'si') return '🇸🇮'; + else if (lang === 'es') return '🇪🇸'; + else if (lang === 'enUs') return '🇬🇧'; + else if (lang === 'uk') return '🇬🇧'; + else if (lang === 'fr') return '🇫🇷'; }, blockwords(mystr) { - const arrwords = [ - 'http', - 'Http', - 'Asasfasfas', - '://', - 'mrbit', - 'admin', - 'superuser']; + const arrwords = ['http', 'Http', 'Asasfasfas', '://', 'mrbit', 'admin', 'superuser']; try { for (const myword of arrwords) { if (mystr) { @@ -4416,9 +4226,7 @@ module.exports = { } } } - } catch (e) { - - } + } catch (e) {} return false; }, @@ -4428,9 +4236,12 @@ module.exports = { for (i = 0, len = str.length; i < len; i++) { code = str.charCodeAt(i); - if (!(code > 47 && code < 58) && // numeric (0-9) + if ( + !(code > 47 && code < 58) && // numeric (0-9) !(code > 64 && code < 91) && // upper alpha (A-Z) - !(code > 96 && code < 123)) { // lower alpha (a-z) + !(code > 96 && code < 123) + ) { + // lower alpha (a-z) return false; } } @@ -4442,12 +4253,15 @@ module.exports = { for (i = 0, len = str.length; i < len; i++) { code = str.charCodeAt(i); - if (!(code > 47 && code < 58) && // numeric (0-9) + if ( + !(code > 47 && code < 58) && // numeric (0-9) !(code > 63 && code < 91) && // upper alpha (A-Z) // e @ - (code !== 46) && // . (punto) - (code !== 95) && // _ - (code !== 45) && // - - !(code > 96 && code < 123)) { // lower alpha (a-z) + code !== 46 && // . (punto) + code !== 95 && // _ + code !== 45 && // - + !(code > 96 && code < 123) + ) { + // lower alpha (a-z) return false; } } @@ -4517,8 +4331,7 @@ module.exports = { }, async getApps() { - if (this.MYAPPS.length <= 0) - await this.loadApps(); + if (this.MYAPPS.length <= 0) await this.loadApps(); return this.MYAPPS; }, @@ -4559,7 +4372,7 @@ module.exports = { }, isNumber(n) { - return typeof (n) != 'boolean' && !isNaN(n) && n; + return typeof n != 'boolean' && !isNaN(n) && n; }, getNumObj(obj) { let count = 0; @@ -4594,7 +4407,6 @@ module.exports = { } else if (table === shared_consts.TAB_SITES) { telegrambot.reloadSites(); } - }, downloadImage(url, filepath) { @@ -4609,7 +4421,6 @@ module.exports = { console.error('Err download image', e); return false; } - }, async checkStr(msg, mystr, user, cmd) { @@ -4622,18 +4433,22 @@ module.exports = { }, getUnsubsribeUrl(mylocalsconf) { - if (mylocalsconf) { const baseurl = this.getHostByIdApp(mylocalsconf.idapp); - const urlunsibscribe = baseurl + '/unsubscribe?em=' + mylocalsconf.hashemail + '&mc=' + mylocalsconf.dataemail.mailchimpactive + - '&email=' + mylocalsconf.emailto; + const urlunsibscribe = + baseurl + + '/unsubscribe?em=' + + mylocalsconf.hashemail + + '&mc=' + + mylocalsconf.dataemail.mailchimpactive + + '&email=' + + mylocalsconf.emailto; return urlunsibscribe; } return ''; }, getUnsubsribeUrl_User(user) { - if (user && user.email) { const hash = this.getHash(user.email + user.username); return this.getHostByIdApp(user.idapp) + '/unsubscribe_user?em=' + hash + '&email=' + user.email; @@ -4643,16 +4458,13 @@ module.exports = { async convertSpecialTags(user, msg) { try { - if (!msg) - return msg; - + if (!msg) return msg; if (!!user) { if (msg.includes('{host}')) { msg = msg.replace('{host}', this.getHostByIdApp(user.idapp)); } - if (msg.includes('{appname}')) - msg = msg.replace('{appname}', this.getNomeAppByIdApp(user.idapp)); + if (msg.includes('{appname}')) msg = msg.replace('{appname}', this.getNomeAppByIdApp(user.idapp)); msg = msg.replace('{username}', user.username); // msg = await this.checkStr(msg, '{time_exp_reg}', user, 1); msg = msg.replace('{name}', user.name ? user.name : user.username); @@ -4661,23 +4473,16 @@ module.exports = { msg = msg.replace('{urlunsubscribe_user}', this.getUnsubsribeUrl_User(user)); msg = msg.replace('{aportador_solidario}', user.aportador_solidario ? user.aportador_solidario : ''); - if (!!user.profile.link_payment) - msg = msg.replace('{link_paypalme}', user.profile.link_payment); - if (!!user.profile.revolut) - msg = msg.replace('{revolut}', user.profile.revolut); - if (!!user.profile.payeer_id) - msg = msg.replace('{payeer_id}', user.profile.payeer_id); - if (!!user.profile.advcash_id) - msg = msg.replace('{advcash_id}', user.profile.advcash_id); - if (!!user.profile.email_paypal) - msg = msg.replace('{email_paypal}', user.profile.email_paypal); - if (!!user.profile.note_payment) - msg = msg.replace('{note_payment}', user.profile.note_payment); + if (!!user.profile.link_payment) msg = msg.replace('{link_paypalme}', user.profile.link_payment); + if (!!user.profile.revolut) msg = msg.replace('{revolut}', user.profile.revolut); + if (!!user.profile.payeer_id) msg = msg.replace('{payeer_id}', user.profile.payeer_id); + if (!!user.profile.advcash_id) msg = msg.replace('{advcash_id}', user.profile.advcash_id); + if (!!user.profile.email_paypal) msg = msg.replace('{email_paypal}', user.profile.email_paypal); + if (!!user.profile.note_payment) msg = msg.replace('{note_payment}', user.profile.note_payment); } // const cl = getclTelegByidapp(user.idapp); msg = msg.replace('{link_chathelp}', this.HELP_CHAT); - } catch (e) { console.log(e); } @@ -4685,29 +4490,29 @@ module.exports = { return msg; }, - getUserInfoMsg: function (idapp, myuser, usernametelegram = '', name_telegram = '', - surname_telegram = '') { - + getUserInfoMsg: function (idapp, myuser, usernametelegram = '', name_telegram = '', surname_telegram = '') { let msg = ''; try { - const name = myuser.username + - (myuser.name ? ` (${myuser.name} ${myuser.surname})` : ''); - const linkuserprof = this.getHostByIdApp(idapp) + '/my/' + - myuser.username; + const name = myuser.username + (myuser.name ? ` (${myuser.name} ${myuser.surname})` : ''); + const linkuserprof = this.getHostByIdApp(idapp) + '/my/' + myuser.username; msg = `
👉🏻 ${name}
email: ${myuser.email}`; - let u_tg = myuser.profile && myuser.profile.hasOwnProperty('username_telegram') ? myuser.profile.username_telegram : usernametelegram; - let name_tg = myuser.profile && myuser.profile.hasOwnProperty('firstname_telegram') - ? myuser.profile.firstname_telegram - : name_telegram; - let surname_tg = myuser.profile && myuser.profile.hasOwnProperty('lastname_telegram') - ? myuser.profile.lastname_telegram - : surname_telegram; + let u_tg = + myuser.profile && myuser.profile.hasOwnProperty('username_telegram') + ? myuser.profile.username_telegram + : usernametelegram; + let name_tg = + myuser.profile && myuser.profile.hasOwnProperty('firstname_telegram') + ? myuser.profile.firstname_telegram + : name_telegram; + let surname_tg = + myuser.profile && myuser.profile.hasOwnProperty('lastname_telegram') + ? myuser.profile.lastname_telegram + : surname_telegram; let namesurnametg = ''; - if (name_tg || surname_tg) - namesurnametg = ` [${name_tg} ${surname_tg}]`;; + if (name_tg || surname_tg) namesurnametg = ` [${name_tg} ${surname_tg}]`; if (u_tg) { msg += `

Apri chat 👉🏻 https://t.me/${u_tg}`; @@ -4719,20 +4524,19 @@ module.exports = { return msg; }, - getUserShortInfoMsg: function (idapp, myuser, usernametelegram = '', name_telegram = '', - surname_telegram = '') { - + getUserShortInfoMsg: function (idapp, myuser, usernametelegram = '', name_telegram = '', surname_telegram = '') { let msg = ''; try { - const name = myuser.username + - (myuser.name ? ` (${myuser.name} ${myuser.surname})` : ''); + const name = myuser.username + (myuser.name ? ` (${myuser.name} ${myuser.surname})` : ''); const linkuserprof = this.getLinkUserProfile(idapp, myuser.username); - let u_tg = myuser.profile && myuser.profile.hasOwnProperty('username_telegram') ? myuser.profile.username_telegram : usernametelegram; + let u_tg = + myuser.profile && myuser.profile.hasOwnProperty('username_telegram') + ? myuser.profile.username_telegram + : usernametelegram; msg = `
Vedi Profilo sulla APP di ${name}`; msg += `
Telegram: @${u_tg}`; - } catch (e) { console.error('getUserInfoMsg', e); } @@ -4741,8 +4545,7 @@ module.exports = { }, getlinkRelativeRequestNewPassword: function (idapp, email, tokenforgot) { - const strlinkreg = process.env.LINK_UPDATE_PASSWORD + - `?idapp=${idapp}&email=${email}&tokenforgot=${tokenforgot}`; + const strlinkreg = process.env.LINK_UPDATE_PASSWORD + `?idapp=${idapp}&email=${email}&tokenforgot=${tokenforgot}`; return strlinkreg; }, @@ -4753,7 +4556,8 @@ module.exports = { execScriptOnServer: async function (idapp, script, dir, listafiles, extfiles) { return new Promise(async (resolve, reject) => { - exec(script, async (error, stdout, stderr) => { // Aggiunto async qui + exec(script, async (error, stdout, stderr) => { + // Aggiunto async qui if (error) { console.error(`error: ${error}`); return reject(`Execution failed: ${error}`); @@ -4772,7 +4576,6 @@ module.exports = { .filter((script) => script.trim() !== '') .map((script) => script.replace(/\//g, '')); - for (let i = 0; i < arrscripts.length; i++) { let label = arrscripts[i]; let sock = false; @@ -4807,10 +4610,9 @@ module.exports = { } else if (paramstr === 'DESCRIZ') { description = value; } else if (paramstr === 'SOCK') { - sock = (value ? (value.toLowerCase() === 'true') : false); + sock = value ? value.toLowerCase() === 'true' : false; } } - } } } catch (error) { @@ -4821,7 +4623,7 @@ module.exports = { label = ''; } - if ((label) && (!extfiles || (extfiles && arrscripts[i].endsWith('.' + extfiles)))) { + if (label && (!extfiles || (extfiles && arrscripts[i].endsWith('.' + extfiles)))) { arrout.push({ label, value: arrscripts[i], description, sock }); } } @@ -4833,7 +4635,8 @@ module.exports = { execScriptNoOutput: async function (script) { return new Promise(async (resolve, reject) => { console.log('execScriptNoOutput:', script); - exec(script, async (error, stdout, stderr) => { // Aggiunto async qui + exec(script, async (error, stdout, stderr) => { + // Aggiunto async qui if (error) { console.error(`error: ${error}`); } @@ -5000,18 +4803,16 @@ module.exports = { return cleanedText; }, - removeAtChar(mystr) { if (mystr && mystr[0] === '@') { - return mystr = mystr.substring(1); + return (mystr = mystr.substring(1)); } return mystr; }, updateQueryStringParameter(uri, key, value) { - if (uri === '' || !uri) - return ''; + if (uri === '' || !uri) return ''; var re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i'); var separator = uri.indexOf('?') !== -1 ? '&' : '?'; if (uri.match(re)) { @@ -5025,13 +4826,10 @@ module.exports = { return Array.isArray(val); }, - getContentByTypeMsg(typemsg) { - - }, + getContentByTypeMsg(typemsg) {}, getContentNotifByParams(params, content, typesend) { if (typesend === shared_consts.TypeSend.TELEGRAM) { - let myhost = this.getHostByIdApp(params.idapp); if (params.textaddTelegram) { @@ -5043,7 +4841,6 @@ module.exports = { content = content + '\n' + '' + params.linkaddTelegram + ''; } - /*if (params.openUrl) content = content + '\n' + '' + i18n.__('OPEN PAGE') + ''; @@ -5072,11 +4869,20 @@ module.exports = { // is same day? if (this.getstrDateShort(myevent.dateTimeStart) === this.getstrDateShort(myevent.dateTimeEnd)) { - mystr = i18n.__('DATEDAYONLY', this.getstrDateLong(myevent.dateTimeStart), this.getstrTime(myevent.dateTimeStart), - this.getstrTime(myevent.dateTimeEnd)) + mystr = i18n.__( + 'DATEDAYONLY', + this.getstrDateLong(myevent.dateTimeStart), + this.getstrTime(myevent.dateTimeStart), + this.getstrTime(myevent.dateTimeEnd) + ); } else { - mystr = i18n.__('DATE_2DAYS', this.getstrDateLong(myevent.dateTimeStart), this.getstrTime(myevent.dateTimeStart), - this.getstrDateLong(myevent.dateTimeEnd), this.getstrTime(myevent.dateTimeEnd)) + mystr = i18n.__( + 'DATE_2DAYS', + this.getstrDateLong(myevent.dateTimeStart), + this.getstrTime(myevent.dateTimeStart), + this.getstrDateLong(myevent.dateTimeEnd), + this.getstrTime(myevent.dateTimeEnd) + ); } return '🗓 ' + mystr; @@ -5085,9 +4891,11 @@ module.exports = { getDoveStrByAnnuncio(myrec) { let dove = '🏠 '; if (myrec.mycities && myrec.mycities.length > 0) { - dove += myrec.mycities.map(city => { - return `${city.comune} (${city.prov})`; - }).join(', '); + dove += myrec.mycities + .map((city) => { + return `${city.comune} (${city.prov})`; + }) + .join(', '); } return dove; }, @@ -5096,12 +4904,10 @@ module.exports = { let mystr = ''; mystr = await this.firstchars(this.replaceStringAtEnd(myrec.note, '', ''), 800); - if (mystr) - mystr = 'ℹ️ ' + mystr + if (mystr) mystr = 'ℹ️ ' + mystr; return mystr; }, - async getEventForTelegram(myrec, mydescr, userorig) { try { let datastr = this.getstrDateTimeEvent(myrec); @@ -5120,11 +4926,10 @@ module.exports = { } newdescrtelegram += i18n.__('EVENT_ADDED_FROM', userorig); - return { newdescr, newdescrtelegram } + return { newdescr, newdescrtelegram }; } catch (e) { console.error('Error', e); } - }, addRowTelegram(icon, title, content, acapo, acapofine, islink) { @@ -5137,8 +4942,7 @@ module.exports = { } if (title) { - if (icon) - mystr += `${icon} `; + if (icon) mystr += `${icon} `; mystr += `${title}`; @@ -5164,8 +4968,7 @@ module.exports = { try { const idapp = myrec.idapp; - if (!idapp) - return ''; + if (!idapp) return ''; const contribtype = await Contribtype.findAllIdApp(idapp); let mystr = ''; @@ -5179,9 +4982,7 @@ module.exports = { } } return mystr; - } catch (e) { - - } + } catch (e) {} }, async getStatusSkillByRec(myrec, onlyifNoDiPersona) { @@ -5189,14 +4990,13 @@ module.exports = { try { const idapp = myrec.idapp; - if (!idapp) - return ''; + if (!idapp) return ''; const statusskill = await StatusSkill.findAllIdApp(idapp); let mystr = ''; if (onlyifNoDiPersona) { - if ((myrec.idStatusSkill.length === 1) && (myrec.idStatusSkill[0] === shared_consts.STATUSSKILL_DI_PERSONA)) - return '' + if (myrec.idStatusSkill.length === 1 && myrec.idStatusSkill[0] === shared_consts.STATUSSKILL_DI_PERSONA) + return ''; } for (const status of myrec.idStatusSkill) { const reccontr = statusskill.find((rec) => rec._id === status); @@ -5208,16 +5008,12 @@ module.exports = { } } return mystr; - } catch (e) { - - } + } catch (e) {} }, getIconByAdType(adType) { - if (adType === shared_consts.AdType.OFFRO) - return '🟢'; - else if (adType === shared_consts.AdType.CERCO) - return '🔴'; + if (adType === shared_consts.AdType.OFFRO) return '🟢'; + else if (adType === shared_consts.AdType.CERCO) return '🔴'; return ''; }, @@ -5226,12 +5022,10 @@ module.exports = { const { Skill } = require('../models/skill'); const { Sector } = require('../models/sector'); - try { // console.log('myrec', myrec); const idapp = myrec.idapp; - if (!idapp) - return ''; + if (!idapp) return ''; const skillrec = await Skill.findAllIdApp(idapp); const sectorrec = await Sector.findAllIdApp(idapp); @@ -5246,9 +5040,7 @@ module.exports = { mystr += ' 👉🏻 ' + rec.descr; } return mystr; - } catch (e) { - - } + } catch (e) {} }, async getCategoriaGoodByRec(myrec) { const { SectorGood } = require('../models/sectorgood'); @@ -5258,8 +5050,7 @@ module.exports = { try { const idapp = myrec.idapp; - if (!idapp) - return ''; + if (!idapp) return ''; const secgoodrec = await SectorGood.findAllIdApp(idapp); let mystr = ''; @@ -5269,9 +5060,7 @@ module.exports = { mystr += rec.descr; } return mystr; - } catch (e) { - - } + } catch (e) {} }, getComuniEProvinceByRec(myrec) { @@ -5280,34 +5069,44 @@ module.exports = { if (myrec.hasOwnProperty('mycities')) { let ind = 0; for (const city of myrec.mycities) { - if (ind > 0) - mystr += ', ' + if (ind > 0) mystr += ', '; mystr += city.comune + ' (' + city.prov + ')'; ind++; } } return mystr; - } catch (e) { - - } + } catch (e) {} }, convertAndTruncateHTMLForTelegram(text, maxLength = 200, link = '') { const tagMap = { - "
    ": "", "
      ": "", "
    1. ": "\n• ", "
": "", "": "", "": "", - "
": "\n", "
": "", "
": "\n" + '
    ': '', + '
      ': '', + '
    1. ': '\n• ', + '
': '', + '': '', + '': '', + '
': '\n', + '
': '', + '
': '\n', }; // Rimuoviamo specificamente \n text = text.replace(/\n<\/b>/g, ''); - Object.keys(tagMap).forEach(tag => { + Object.keys(tagMap).forEach((tag) => { const replacement = tagMap[tag]; text = text.replaceAll(tag, replacement); }); - text = text.split('\n').map(line => line.trim()).join('\n'); - text = text.replace(/\n{3,}/g, '\n\n').replace(/\n+$/, '').trim(); + text = text + .split('\n') + .map((line) => line.trim()) + .join('\n'); + text = text + .replace(/\n{3,}/g, '\n\n') + .replace(/\n+$/, '') + .trim(); if (text.length <= maxLength) { return text; @@ -5347,27 +5146,30 @@ module.exports = { convertHTMLTagsForTelegram(text) { const tagMap = { - "
    ": "", - "
      ": "", - "
    1. ": "\n• ", - "
": "", - "": "", - "": "", - "
": "\n", - "
": "", - "
": "\n" + '
    ': '', + '
      ': '', + '
    1. ': '\n• ', + '
': '', + '': '', + '': '', + '
': '\n', + '
': '', + '
': '\n', }; // Rimuoviamo i tag vuoti o contenenti solo spazi bianchi o newline text = text.replace(/<(b|i|strong|em)>(\s|\n)*<\/\1>/g, ''); - Object.keys(tagMap).forEach(tag => { + Object.keys(tagMap).forEach((tag) => { const replacement = tagMap[tag]; text = text.replaceAll(tag, replacement); }); // Rimuoviamo gli spazi bianchi all'inizio e alla fine di ogni riga - text = text.split('\n').map(line => line.trim()).join('\n'); + text = text + .split('\n') + .map((line) => line.trim()) + .join('\n'); // Rimuoviamo le righe vuote consecutive, lasciandone solo una text = text.replace(/\n{3,}/g, '\n\n'); @@ -5382,12 +5184,11 @@ module.exports = { async getAnnuncioForTelegram(myrec, tablerec, mydescr, userorig, nuovo) { try { - let newdescr = ''; let out = ''; - let tiposcambio = '' + let tiposcambio = ''; let iconascambio = '🟢'; let lang = 'it'; @@ -5401,23 +5202,17 @@ module.exports = { let descrperNotif = ''; - if ((tablerec === shared_consts.TABLES_MYGOODS) || (tablerec === shared_consts.TABLES_MYSKILLS)) { + if (tablerec === shared_consts.TABLES_MYGOODS || tablerec === shared_consts.TABLES_MYSKILLS) { iconascambio = this.getIconByAdType(myrec.adType); - if (myrec.adType === shared_consts.AdType.OFFRO) - tiposcambio = 'Offro'; - else if (myrec.adType === shared_consts.AdType.CERCO) - tiposcambio = 'Cerco'; + if (myrec.adType === shared_consts.AdType.OFFRO) tiposcambio = 'Offro'; + else if (myrec.adType === shared_consts.AdType.CERCO) tiposcambio = 'Cerco'; } else if (tablerec === shared_consts.TABLES_MYHOSPS) { iconascambio = this.getIconByAdType(myrec.adType); - if (myrec.adType === shared_consts.AdType.CERCO) - tiposcambio = 'Cerco'; - else - tiposcambio = 'Offro'; + if (myrec.adType === shared_consts.AdType.CERCO) tiposcambio = 'Cerco'; + else tiposcambio = 'Offro'; - if (myrec.typeHosp === shared_consts.TYPEHOSP_OSPITALITA) - tiposcambio += ' Ospitalità'; - else if (myrec.typeHosp === shared_consts.TYPEHOSP_SCAMBIOCASA) - tiposcambio += ' Scambio Casa'; + if (myrec.typeHosp === shared_consts.TYPEHOSP_OSPITALITA) tiposcambio += ' Ospitalità'; + else if (myrec.typeHosp === shared_consts.TYPEHOSP_SCAMBIOCASA) tiposcambio += ' Scambio Casa'; } else if (tablerec === shared_consts.TABLES_MYBACHECAS) { datastr = this.getstrDateTimeEvent(myrec); organizedby = myrec.organisedBy; @@ -5439,7 +5234,6 @@ module.exports = { descrperNotif = i18n.__('NEW_EVENT', userorig, datastr, mydescr, dovestr); } - let contatto = userorig; let contatto_telegram = ''; try { @@ -5451,8 +5245,7 @@ module.exports = { } else { contatto = myrec.email; } - } catch (e) { - } + } catch (e) {} let organizedBy = ''; let cat = ''; @@ -5464,11 +5257,11 @@ module.exports = { let contact_phone = ''; let contact_email = ''; if (tablerec === shared_consts.TABLES_MYGOODS) { - cat = await this.getCategoriaGoodByRec(myrec) + cat = await this.getCategoriaGoodByRec(myrec); } else if (tablerec === shared_consts.TABLES_MYSKILLS) { - cat = await this.getCategoriaSkillByRec(myrec) - online = myrec.idStatusSkill.findIndex((id) => id === shared_consts.STATUSSKILL_ONLINE) >= 0 - solo_online = online && myrec.idStatusSkill.length === 1 + cat = await this.getCategoriaSkillByRec(myrec); + online = myrec.idStatusSkill.findIndex((id) => id === shared_consts.STATUSSKILL_ONLINE) >= 0; + solo_online = online && myrec.idStatusSkill.length === 1; status = await this.getStatusSkillByRec(myrec, true); if (status) { status = ' ' + status; @@ -5476,9 +5269,8 @@ module.exports = { } else if (tablerec === shared_consts.TABLES_MYHOSPS) { cat = ''; } else if (tablerec === shared_consts.TABLES_MYBACHECAS) { - if (myrec.website) { - sitoweb = myrec.website + sitoweb = myrec.website; } contact_phone = myrec.contact_phone || ''; @@ -5493,30 +5285,29 @@ module.exports = { contatto = ''; } } - if ((myrec.contact_telegram && myrec.contact_telegram?.toLowerCase() !== contatto_telegram?.toLowerCase()) || !contatto) { + if ( + (myrec.contact_telegram && myrec.contact_telegram?.toLowerCase() !== contatto_telegram?.toLowerCase()) || + !contatto + ) { contatto += '\n' + myrec.contact_telegram; } /*if (myrec.contact_phone) { contatto += ' 📞 ' + myrec.contact_phone; }*/ - } // let out = i18n.__('NEW_ANNUNCIO_TELEGRAM', mydescr, dovestr, descrestesa, userorig); - if (tiposcambio) - out += this.addRowTelegram(iconascambio, tiposcambio + status, '', true, false); + if (tiposcambio) out += this.addRowTelegram(iconascambio, tiposcambio + status, '', true, false); const url = this.getHostByIdApp(myrec.idapp) + shared_consts.getDirectoryByTable(tablerec, true) + myrec._id; out += `${myrec.descr}\n\n`; - if (datastr) - out += this.addRowTelegram('', '', datastr, true, true); + if (datastr) out += this.addRowTelegram('', '', datastr, true, true); - if (cat) - out += this.addRowTelegram('⭐️', 'Categoria', cat, true, true); + if (cat) out += this.addRowTelegram('⭐️', 'Categoria', cat, true, true); - let descrcontent = this.convertAndTruncateHTMLForTelegram(myrec.note, 500, url) + let descrcontent = this.convertAndTruncateHTMLForTelegram(myrec.note, 500, url); // let descrcontent = this.firstchars(this.removeLastSpaceAndACapo(note), 200, true, url); @@ -5524,17 +5315,14 @@ module.exports = { // descrcontent = 'Prova Pao Ciaooo'; - if (descrcontent) - out += this.addRowTelegram('', '', '📝 ' + descrcontent, true, true); + if (descrcontent) out += this.addRowTelegram('', '', '📝 ' + descrcontent, true, true); const localita = this.getComuniEProvinceByRec(myrec); - if (!solo_online) - out += this.addRowTelegram('🏠', 'Località', localita, false, true); + if (!solo_online) out += this.addRowTelegram('🏠', 'Località', localita, false, true); const incambiodi = await this.getInCambioDiByRec(myrec); - if (incambiodi) - out += this.addRowTelegram('⚖️', 'In cambio di', incambiodi, false, true); + if (incambiodi) out += this.addRowTelegram('⚖️', 'In cambio di', incambiodi, false, true); if (organizedBy) { out += this.addRowTelegram('🏠', 'Organizzato da', organizedBy, false, true); @@ -5542,15 +5330,18 @@ module.exports = { out += this.addRowTelegram('👤', 'Contatto', contatto, false, true); } - if (contributo) - out += this.addRowTelegram('💰', 'Contributo Richiesto', contributo, false, true); + if (contributo) out += this.addRowTelegram('💰', 'Contributo Richiesto', contributo, false, true); if (contact_phone || contact_email || sitoweb) { - out += this.addRowTelegram('ℹ️', 'Per Info:', - (contact_phone ? ('📞 ' + contact_phone + ' ') : '') - + (contact_email ? (' 📨 ' + contact_email + ' ') : '') - + (sitoweb ? (' 🌐 ' + sitoweb + ' ') : '') - , true, true); + out += this.addRowTelegram( + 'ℹ️', + 'Per Info:', + (contact_phone ? '📞 ' + contact_phone + ' ' : '') + + (contact_email ? ' 📨 ' + contact_email + ' ' : '') + + (sitoweb ? ' 🌐 ' + sitoweb + ' ' : ''), + true, + true + ); } if (writtenby && organizedBy) { @@ -5578,7 +5369,6 @@ module.exports = { } catch (e) { console.error('Error', e); } - }, generateVapiKey() { @@ -5589,7 +5379,6 @@ module.exports = { const msg1 = 'VAPID Public Key:' + vapidKeys.publicKey; const msg2 = 'VAPID Private Key:' + vapidKeys.privateKey; - console.log(msg1); console.log(msg2); return { msg: msg1 + ' ' + msg2 }; @@ -5601,16 +5390,14 @@ module.exports = { const obj1Fields = obj1 ? Object.keys(obj1) : []; const obj2Fields = obj2 ? Object.keys(obj2) : []; - const commonFields = obj1Fields.filter(field => obj2Fields.includes(field)); - + const commonFields = obj1Fields.filter((field) => obj2Fields.includes(field)); commonFields.forEach((field) => { - if (obj1 && obj2 && ((obj1[field] && obj1[field].toString()) !== (obj2[field] && obj2[field].toString()))) { - if (obj1[field] !== undefined && obj2[field] !== undefined) - fieldsUpdated.push(field); + if (obj1 && obj2 && (obj1[field] && obj1[field].toString()) !== (obj2[field] && obj2[field].toString())) { + if (obj1[field] !== undefined && obj2[field] !== undefined) fieldsUpdated.push(field); } }); - return fieldsUpdated + return fieldsUpdated; } catch (e) { console.error('Err:', e); } @@ -5621,34 +5408,32 @@ module.exports = { }, getUnitsMeasure(unit, short) { - const unitrec = shared_consts.Units_Of_Measure_ListBox.find((rec) => rec.value === unit) - return unitrec ? (short ? unitrec.short : unitrec.label) : '' + const unitrec = shared_consts.Units_Of_Measure_ListBox.find((rec) => rec.value === unit); + return unitrec ? (short ? unitrec.short : unitrec.label) : ''; }, getIdUnitsByText(unitstr) { - const unitrec = shared_consts.Units_Of_Measure_ListBox.find((rec) => rec.short === unitstr) - return unitrec ? unitrec.value : 0 + const unitrec = shared_consts.Units_Of_Measure_ListBox.find((rec) => rec.short === unitstr); + return unitrec ? unitrec.value : 0; }, getWeightAndUnitByText(text) { const result = []; - text = text.replace(",", "."); + text = text.replace(',', '.'); const regex = /^(\d+\.?\d*)\s*(ml|gr|g|l|kg|uova)\s*$/; // Aggiunto un punto dopo \d+ per accettare anche i numeri con la virgola const match = regex.exec(text); if (match) { let peso = parseFloat(match[1]); // Cambiato da parseInt a parseFloat per gestire i numeri con la virgola let unita = match[2]; - if (unita === 'gr') - unita = 'g' + if (unita === 'gr') unita = 'g'; const unit = this.getIdUnitsByText(unita); return { weight: peso, unit }; } return { weight: 0, unit: 0 }; - }, async isManagerByReq(req) { @@ -5657,8 +5442,7 @@ module.exports = { const idapp = req.body.idapp; let userId = ''; - if (req.body) - userId = req.body.userId; + if (req.body) userId = req.body.userId; const myuser = await User.getUserById(idapp, userId); let ismanager = false; @@ -5667,36 +5451,29 @@ module.exports = { } return ismanager; - } catch (e) { return false; } }, addslashes(str) { - return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0') + return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0'); }, removeescape(inputString) { // return inputString.replace(/\\/g, '').replace(/"/g, ''); - if (inputString) - return inputString.replace(/\\/g, '').replace(/"/g, ''); - else - return ''; + if (inputString) return inputString.replace(/\\/g, '').replace(/"/g, ''); + else return ''; }, escapeQuotes(stringa) { - if (stringa) - return stringa.replace(/"/g, '\\"'); - else - return ''; + if (stringa) return stringa.replace(/"/g, '\\"'); + else return ''; }, replaceQuotesWithSingleQuotes(jsonString) { - if (jsonString) - return jsonString.replace(/"/g, "'"); - else - return ''; + if (jsonString) return jsonString.replace(/"/g, "'"); + else return ''; }, ripulisciCampo(stringa) { @@ -5705,9 +5482,7 @@ module.exports = { }, convertToNumeroVirgola(valstr) { - - if (valstr === '' || valstr === undefined) - valstr = '0'; + if (valstr === '' || valstr === undefined) valstr = '0'; valstr = valstr + ''; valstr = valstr.replace(',', '.'); @@ -5716,9 +5491,8 @@ module.exports = { }, convertPriceEurToValue(inputString) { - inputString = this.removeescape(this.addslashes(inputString)) - if (inputString === '') - return '0'; + inputString = this.removeescape(this.addslashes(inputString)); + if (inputString === '') return '0'; // Rimuovi il simbolo della valuta (€) e sostituisci la virgola con un punto return inputString.replace(/[^\d.,]/g, '').replace(',', '.'); }, @@ -5752,7 +5526,9 @@ module.exports = { // 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`); + 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); @@ -5805,7 +5581,7 @@ module.exports = { // Seleziona tutti gli elementi all'interno del body const allElements = document.body.querySelectorAll('*'); - allElements.forEach(element => { + allElements.forEach((element) => { const tagName = element.tagName?.toLowerCase(); if (!allowedTags.includes(tagName)) { @@ -5833,7 +5609,7 @@ module.exports = { // Ritorna l'HTML pulito return document.body.innerHTML; } catch (error) { - console.error('Errore durante la pulizia dell\'HTML:', error); + console.error("Errore durante la pulizia dell'HTML:", error); throw error; // Oppure, gestisci l'errore come preferisci } }, @@ -5843,7 +5619,7 @@ module.exports = { const parsedUrl = new URL(url); return parsedUrl.host; } catch (error) { - console.error('Errore durante la pulizia dell\'HTML:', error); + console.error("Errore durante la pulizia dell'HTML:", error); throw error; // Oppure, gestisci l'errore come preferisci } }, @@ -5871,7 +5647,7 @@ module.exports = { }, async listCollectionsBySize() { - let output = ""; // Variabile per memorizzare l'output + let output = ''; // Variabile per memorizzare l'output try { const conn = mongoose.connection; @@ -5880,88 +5656,96 @@ module.exports = { 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 }; - })); + 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 => { + 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); + console.error('Errore:', error); return `Errore: ${error.message}`; // Restituisci l'errore come stringa } }, getStringaConto(mov) { + let mystr = ''; + let userfrom = ''; + let userto = ''; - let mystr = '' - let userfrom = '' - let userto = '' + let profilefrom = null; + let profileto = null; - let profilefrom = null - let profileto = null - - let tipocontofrom = shared_consts.AccountType.USER - let tipocontoto = shared_consts.AccountType.USER + 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 + userfrom += mov.contocomfrom.name; + tipocontofrom = shared_consts.AccountType.COMMUNITY_ACCOUNT; } if (mov.groupfrom) { - userfrom += mov.groupfrom.groupname - tipocontofrom = shared_consts.AccountType.CONTO_DI_GRUPPO + userfrom += mov.groupfrom.groupname; + tipocontofrom = shared_consts.AccountType.CONTO_DI_GRUPPO; } if (mov.userfrom) { - userfrom += mov.userfrom.username - profilefrom = mov.userfrom.profile + userfrom += mov.userfrom.username; + profilefrom = mov.userfrom.profile; } if (mov.contocomto && mov.contocomto.name) { - userto += mov.contocomto.name - tipocontoto = shared_consts.AccountType.COMMUNITY_ACCOUNT + userto += mov.contocomto.name; + tipocontoto = shared_consts.AccountType.COMMUNITY_ACCOUNT; } if (mov.groupto) { - userto += mov.groupto.groupname - tipocontoto = shared_consts.AccountType.CONTO_DI_GRUPPO + userto += mov.groupto.groupname; + tipocontoto = shared_consts.AccountType.CONTO_DI_GRUPPO; } if (mov.userto) { - userto += mov.userto.username - profileto = mov.userto.profile + 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 } + return { + userfrom: { profile: profilefrom, username: userfrom }, + userto: { profile: profileto, username: userto }, + tipocontofrom, + tipocontoto, + }; }, - ImageDownloader, - getDirUpload() { - return 'upload/' + return 'upload/'; }, getURLImg(idapp, table, username, img, checkifExist) { let dirmain = ''; try { - // let dir = this.getdirByIdApp(idapp) + dirmain + '/' + this.getDirUpload(); - let dir = this.getHostByIdApp(idapp) + '/' + this.getDirUpload() + shared_consts.getDirectoryImgByTable(table, username) + dirmain; + let dir = + this.getHostByIdApp(idapp) + + '/' + + this.getDirUpload() + + shared_consts.getDirectoryImgByTable(table, username) + + dirmain; img = dir + img; /*if (checkifExist) { - if (!this.isFileExists(img)) { + if (!this.isFileExistsAsync(img)) { return ''; } }*/ @@ -5979,7 +5763,6 @@ module.exports = { }, getLangByUsername(idapp, username) { - //++Todo LANG: Estrarre il Lang dall'username (user, group) return 'it'; }, @@ -6021,7 +5804,8 @@ module.exports = { //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 = + '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') } @@ -6060,28 +5844,27 @@ module.exports = { } else { return await model.find(myfind).lean(); } - } catch (err) { - console.error("Errore in findAllQueryIdApp:", err, model); + 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)); + 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. - */ + * 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."); + console.error('Input non valido: la data deve essere una stringa.'); return null; } @@ -6090,7 +5873,7 @@ module.exports = { // Controlla che i valori siano stati estratti correttamente if (isNaN(giorno) || isNaN(mese) || isNaN(anno)) { - console.error("Formato data non valido:", dateString); + console.error('Formato data non valido:', dateString); return null; } @@ -6099,24 +5882,23 @@ module.exports = { // Verifica che la data sia valida if (isNaN(dateObj.getTime())) { - console.error("Data non valida:", dateString); + console.error('Data non valida:', dateString); return null; } // Restituisci l'oggetto con la data e il timestamp return { date: dateObj, - timestamp: dateObj.getTime() + timestamp: dateObj.getTime(), }; }, getDateFromISOString(mydate) { - const mydate2 = new Date(mydate) - return mydate2 + const mydate2 = new Date(mydate); + return mydate2; }, async downloadImgIfMissing(productInfo) { - const ProductInfo = require('../models/productInfo'); try { @@ -6126,22 +5908,32 @@ module.exports = { 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 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.isFileExists(savePath); + let scaricaimg = !productInfo.imagefile || !(await this.isFileExistsAsync(savePath)); - if (!productInfo.imagefile && await this.isFileExists(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 + 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 }; @@ -6149,30 +5941,30 @@ module.exports = { scaricaimg = true; } } - - if (productInfo.imagefile && await this.isFileExists(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 + 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, - { + const aggiornatoimg = await downloader + .downloadImage(productInfo.image_link, savePath, { maxRetries: 1, initialDelay: 300, timeout: 15000, - }).then(result => { + }) + .then((result) => { if (result) { // console.log('Download completato con successo!'); } else { @@ -6180,7 +5972,6 @@ module.exports = { } return result; - }); return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris }; } @@ -6189,44 +5980,48 @@ module.exports = { let fileesistente = false; if (productInfo.imagefile) { // controlla se esiste il file - const img = this.getdirByIdApp(productInfo.idapp) + dirmain + - server_constants.DIR_UPLOAD + '/products/' + productInfo.imagefile.split('/').pop(); + 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.isFileExists(filecompleto); + // Se non esiste lo scarico ! + fileesistente = await this.isFileExistsAsync(filecompleto); } if (!vecchiomodo && (!productInfo.image_link || !fileesistente)) { - let scarica_da_sito = !productInfo.imagefile; if (!scarica_da_sito && productInfo.imagefile) { - scarica_da_sito = !fileesistente; // Se non esiste lo scarico ! + 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(); + 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 + 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: 1, - initialDelay: 300, - timeout: 15000, - nomefileoriginale: true, - }); + aggiornatoimg = await downloader.downloadImage(link, savePath, { + maxRetries: 1, + initialDelay: 300, + timeout: 15000, + nomefileoriginale: true, + }); } catch (e) { aggiornatoimg = { ris: false }; } @@ -6235,7 +6030,6 @@ module.exports = { await ProductInfo.setImgNotFound(productInfo._id); } - if (aggiornatoimg?.filepath) { const filenamebase = path.basename(aggiornatoimg.filepath); // const img = '/upload/products/' + filenamebase; @@ -6247,38 +6041,55 @@ module.exports = { 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'], + ['á', '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(''); + 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 + return formattedDate; }, - convertFullFileNameToURL(idapp, fullfilename) { const mydir = this.getdirByIdApp(idapp); const myhost = this.getHostByIdApp(idapp); @@ -6288,7 +6099,7 @@ module.exports = { const myurl = myhost + '/' + url; console.log('myurl', myurl); - return myurl; + return myurl; }, removePathDirByFileName(idapp, fullfilename) { @@ -6307,7 +6118,5 @@ module.exports = { } catch { return false; } - }, - - + } }; diff --git a/yarn.lock b/yarn.lock index 627fe02..7c00bda 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2552,6 +2552,11 @@ csurf@^1.11.0: csrf "3.1.0" http-errors "~1.7.3" +csv-writer@^1.6.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/csv-writer/-/csv-writer-1.6.0.tgz#d0cea44b6b4d7d3baa2ecc6f3f7209233514bcf9" + integrity sha512-NOx7YDFWEsM/fTRAJjRpPp8t+MKRVvniAg9wQlUKx20MFrPs73WLJhFf5iteqrxNYnsy924K3Iroh3yNHeYd2g== + dashdash@^1.12.0: version "1.14.1" resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0"