2021-10-05 15:39:44 +02:00
const os = require ( 'os' ) ;
2019-12-27 12:41:39 +01:00
const fs = require ( 'fs' ) ;
2024-11-28 16:05:00 +01:00
const xml2js = require ( 'xml2js' ) ;
2021-02-18 12:19:35 +01:00
const path = require ( 'path' ) ;
2024-08-29 23:30:58 +02:00
const WebSocket = require ( 'ws' ) ;
2021-02-18 12:19:35 +01:00
2019-10-05 20:01:56 +02:00
require ( '../config/config' ) ;
2019-02-14 19:01:41 +01:00
require ( '../models/subscribers' ) ;
2022-01-14 23:54:33 +01:00
const printf = require ( 'util' ) . format ;
2024-05-10 01:59:54 +02:00
const { JSDOM } = require ( 'jsdom' ) ;
2024-03-19 00:21:54 +01:00
const axios = require ( 'axios' ) ;
2019-12-04 02:03:44 +01:00
const CryptoJS = require ( 'crypto-js' ) ;
2020-01-20 01:48:25 +01:00
const Url = require ( 'url-parse' ) ;
2019-02-14 19:01:41 +01:00
2023-01-03 16:51:32 +01:00
const { ObjectID , ObjectId } = require ( 'mongodb' ) ;
2019-10-21 20:38:10 +02:00
2020-02-07 22:08:46 +01:00
const shared _consts = require ( './shared_nodejs' ) ;
2020-02-02 04:06:32 +01:00
2022-09-14 11:32:04 +02:00
const mongoose = require ( 'mongoose' ) . set ( 'debug' , false ) ;
2024-02-27 22:08:06 +01:00
2019-11-21 00:18:40 +01:00
const server _constants = require ( './server_constants' ) ;
2019-02-27 02:59:02 +01:00
2019-02-12 12:06:25 +01:00
// SETTINGS WebPush Configuration
const webpush = require ( 'web-push' ) ;
2022-07-26 15:46:39 +02:00
const i18n = require ( 'i18n' ) ;
2023-03-21 18:11:56 +01:00
2020-02-19 16:09:16 +01:00
const FILELOG = 'filelog.txt' ;
const FILEEVENTS = 'logevents.txt' ;
2020-03-10 21:44:14 +01:00
const FILEMANAGERS = 'logmanagers.txt' ;
2023-02-06 22:58:10 +01:00
const FILETRANSACTION = 'logtrans.txt' ;
2022-02-27 16:56:02 +01:00
const FILEERRLOGIN = 'errlogin.txt' ;
2020-06-08 13:31:05 +02:00
const FILESOSTITUZIONI = 'log_sostituzioni.txt' ;
2020-07-13 23:35:05 +02:00
const FILEIP _TO _BAN = 'log_iptoban.txt' ;
2020-03-10 21:44:14 +01:00
const FILENAVE = 'logNave.txt' ;
2021-09-22 01:13:41 +02:00
const subject = process . env . VAPI _KEY _SUBJECT ;
2019-02-12 12:06:25 +01:00
const publicVapidKey = process . env . PUBLIC _VAPI _KEY ;
const privateVapidKey = process . env . PRIVATE _VAPI _KEY ;
2019-02-14 19:01:41 +01:00
2020-03-21 10:28:26 +01:00
const FIELDS _REGEX = [ 'username' , 'name' , 'surname' ] ;
2020-03-10 21:44:14 +01:00
2024-05-04 14:49:02 +02:00
const sanitizeHtml = require ( 'sanitize-html' ) ;
2024-08-29 23:30:58 +02:00
const { exec } = require ( 'child_process' ) ;
const { spawn } = require ( 'child_process' ) ;
const readline = require ( 'readline' ) ;
2020-01-03 01:52:49 +01:00
// Code goes here
const keySize = 256 ;
const ivSize = 128 ;
const iterations = 100 ;
2021-10-05 15:39:44 +02:00
if ( ! ! process . env . GCM _API _KEY && process . env . GCM _API _KEY !== '' ) {
2019-02-14 19:01:41 +01:00
webpush . setGCMAPIKey ( process . env . GCM _API _KEY ) ;
2021-04-30 01:31:12 +02:00
webpush . setVapidDetails ( subject , publicVapidKey , privateVapidKey ) ;
}
2019-04-06 21:02:39 +02:00
// console.log('setVapidDetails... config...');
2019-02-14 19:01:41 +01:00
2020-01-20 01:48:25 +01:00
// To Translate!
2021-04-30 01:31:12 +02:00
const textlang = {
2020-01-20 01:48:25 +01:00
it : {
2021-10-05 15:39:44 +02:00
'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 a Pranzo' : 'partecipanti a Pranzo' ,
'partecipanti a Cena' : 'partecipanti a Cena' ,
'partecipanti a Cena Condivisa' : 'partecipanti a Cena Condivisa' ,
2021-12-23 14:13:40 +01:00
'TESTO_ASSISTENZA' : '<strong><a href="%s">👉 Per entrare nel Sito</a></strong>\n\n' +
2022-12-15 18:09:43 +01:00
'👉 <strong><a href="https://freeplanet.app/requestresetpwd">Hai dimenticato la password?</a></strong>\n\n' ,
2022-02-21 13:12:27 +01:00
'BENVENUTO' : 'Benvenut@' ,
2021-10-05 15:39:44 +02:00
'TUE_NAVI' : 'Ecco le tue Navi programmate' ,
2021-12-23 14:13:40 +01:00
'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 !' ,
2020-03-10 21:44:14 +01:00
'INFO_LA_MIA_LAVAGNA' : '✨ Lista dei Passi: ✨ \n' ,
2021-12-23 14:13:40 +01:00
'INFO_LAVAGNA_SITO_COMPLETARE' : 'Per completare tutti i requisiti vai sul sito:\n%s\n👉🏻 <a href="%s">Entra nella tua Lavagna</a>.\n' ,
'INFO_LAVAGNA_SITO' : 'Per vedere in dettaglio lo <strong>STATO</strong>, sul sito \n 👉🏻 <a href="%s">Entra nella tua Lavagna</a>.\n' ,
'INFO_LINK_DA_CONDIVIDERE' : 'Link da condividere ai tuoi invitati per farli registrare al sito:\n\n%s' ,
2020-04-24 10:29:25 +02:00
'INFO_LINK_ZOOM' : 'Link da condividere per partecipare allo Zoom (Conferenza OnLine):\n%s' ,
2020-05-04 19:34:41 +02:00
'ZOOM_CONFERENCE' : 'Ecco il programma delle Conferenze (Zoom) aperti a TUTTI:' ,
2021-10-05 15:39:44 +02:00
'NON_VERIF' : 'Non Verificata' ,
'VERIF' : 'Verificata' ,
'EMAIL' : 'Email' ,
2021-12-23 14:13:40 +01:00
'BOT' : 'BOT' ,
'EMAIL_NON_VERIF' : 'Email Non Verificata\nleggi la tua casella email e trova **"Confermare la Registrazione"**\ne clicca sul bottone **"Verifica Registrazione"**' ,
2021-10-05 15:39:44 +02:00
'TELEGRAM_NOT_CONNECTED' : 'Telegram non associato al tuo account!' ,
2020-01-20 01:48:25 +01:00
'NESSUN_INVITATO' : 'Non hai invitato nessuno' ,
'ZOOM_PARTECIPATO' : 'Partecipazione ad almeno 1 Conferenza (Zoom)' ,
2020-02-07 22:08:46 +01:00
'LINEE_GUIDA' : 'Accettato le Linee Guida' ,
2021-12-23 14:13:40 +01:00
'VIDEO_INTRO' : 'Visto il Video' ,
2020-01-20 01:48:25 +01:00
'SCRITTO_SOGNO' : 'Hai scritto il tuo Sogno' ,
2020-07-02 22:00:58 +02:00
'PAYMENTS' : 'Modalità di Pagamento' ,
2020-01-20 01:48:25 +01:00
'INVITATI' : 'persone registrate che hai invitato' ,
2020-02-19 16:09:16 +01:00
'INVITATI_ATTIVI' : 'Invitati con i 7 Requisiti' ,
2020-02-02 04:06:32 +01:00
'NONREG' : 'Invitati non Registrati' ,
2020-07-02 22:00:58 +02:00
'CLICCA_PER_ZOOM' : 'AL GIORNO E ORA INDICATA, PER ENTRARE NELLA VIDEO-CONFERENZA, CLICCA SUL LINK INDICATO' ,
2020-02-19 16:09:16 +01:00
'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)' ,
2020-03-10 21:44:14 +01:00
'CIAO' : 'Ciao' ,
2020-05-11 22:43:14 +02:00
'ADDED_TOLISTAINGRESSO' : '<strong>Complimenti! 🎊</strong>\nSei stato aggiunto alla <strong>Lista D\'Imbarco</strong> !\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} !' ,
2020-03-10 21:44:14 +01:00
'NO_PROG' : 'Attualmente non sei ancora dentro alla Lista d\'Imbarco!' ,
2020-05-10 21:07:51 +02:00
'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:' ,
2020-03-31 20:34:24 +02:00
'SOGNATORE' : 'SOGNATORE' ,
2020-05-13 01:32:27 +02:00
'INTERMEDIO' : 'Intermedio' ,
2020-03-31 20:34:24 +02:00
'MEDIATORE' : 'MEDIATORE' ,
'DONATORI' : 'DONATORI' ,
'RITESSITURA' : 'RITESSITURA' ,
'NAVE COMPLETATA' : 'NAVE COMPLETATA' ,
'Doni Effettuati' : 'Doni Effettuati' ,
2022-07-11 23:20:28 +02:00
'Facilitatore che affianchèra il Mediatore' : 'Facilitatore che affianchèra il Mediatore' ,
2020-07-02 22:00:58 +02:00
'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.' ,
2020-03-31 20:34:24 +02:00
'Giorno di Apertura GIFT CHAT' : 'Giorno di Apertura GIFT CHAT' ,
2020-07-02 22:00:58 +02:00
'Giorno in cui Inviare il DONO' : 'Hai 3 giorni di tempo per inviare il tuo dono.\nGiorno di Chiusura' ,
2020-05-10 21:07:51 +02:00
'SPOSTATO' : 'Sei stato Spostato in una Nuova Nave !' ,
2020-03-31 20:34:24 +02:00
'Note' : 'Note' ,
'TEMPORANEA' : 'TEMPORANEA' ,
'NAVE' : 'NAVE' ,
2020-04-07 14:34:29 +02:00
'MSG_SEND_FROM' : 'Msg Inviato da' ,
2020-09-04 00:06:49 +02:00
'ZOOM_CONFERMATO' : 'Sei stato confermato ad aver visto la Video Conferenza di Benvenuto!' ,
2022-03-11 12:38:01 +01:00
'RICHIESTA_AMICIZIA' : '🌈 Richiesta d\'Amicizia da parte di %s' ,
2023-01-09 02:37:35 +01:00
'RICHIESTA_HANDSHAKE' : '🌈 %s ha comunicato che ti conosce personalmente e ha fiducia in te.' ,
2022-03-30 22:51:03 +02:00
'ACCETTATO_SUL_GRUPPO' : '✅ Sei stato accettato da %s a far parte del Gruppo %s' ,
2022-06-17 12:30:44 +02:00
'CREATO_NUOVO_GRUPPO' : '✅ Hai appena creato un nuovo Gruppo chiamato %s' ,
2022-03-30 22:51:03 +02:00
'ACCETTATO_NOTIFICA_ADMINS' : '✅ l\'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)' ,
2022-08-04 17:30:57 +02:00
'GROUP_REQUEST' : 'Richiesta di entrare nel Gruppo %s da parte di %s' ,
2023-04-12 15:37:54 +02:00
"CLICCA_QUI" : "CLICCA QUI" ,
2024-09-30 14:50:19 +02:00
"TELEFONO" : "Tel" ,
2020-03-31 20:34:24 +02:00
} ,
2022-01-14 23:54:33 +01:00
si : { } ,
2020-01-20 01:48:25 +01:00
es : {
2021-10-05 15:39:44 +02:00
'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 a Pranzo' : 'partecipanti a Pranzo' ,
'partecipanti a Cena' : 'partecipanti a Cena' ,
2021-12-23 14:13:40 +01:00
'TESTO_ASSISTENZA' : 'Para entrar en el sitio:\n%s\n\n' +
2022-12-15 18:09:43 +01:00
'¿Olvidó su contraseña para acceder al sitio?\nhttps://freeplanet.app/requestresetpwd\n\n' ,
2021-10-05 15:39:44 +02:00
'BENVENUTO' : 'Bienvenido' ,
'TUE_NAVI' : 'Aquí están sus naves programadas' ,
2020-03-31 20:34:24 +02:00
'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!' ,
2021-12-23 14:13:40 +01:00
'HAI_I_9_REQUISITI' : '¡FELICITACIONES!\n¡Has completado los 9 pasos de la Guía! Gracias por ayudar a expandirse!' ,
2020-03-31 20:34:24 +02:00
'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' ,
2020-05-11 22:43:14 +02:00
'INFO_LAVAGNA_SITO_COMPLETARE' : 'Para completar todos los requisitos vaya al sitio:\n%s\nPara ver el estado de su nave y sus invitados,👉🏻 <a href="%s">Pizarra</a>.\n' ,
2021-12-23 14:13:40 +01:00
'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' ,
2020-04-24 10:29:25 +02:00
'INFO_LINK_ZOOM' : 'Enlaces para compartir para participar en el Zoom (Conferencia en línea):\n%s' ,
2020-03-31 20:34:24 +02:00
'ZOOM_CONFERENCE' : 'Aquí puedes encontrar las fechas de programación en el Zoom:' ,
2021-10-05 15:39:44 +02:00
'NON_VERIF' : 'No verificado' ,
'VERIF' : 'Verificado' ,
'EMAIL' : 'Email' ,
2021-12-23 14:13:40 +01:00
'BOT' : 'BOT' ,
'EMAIL_NON_VERIF' : 'Correo electrónico no verificado\nlea su buzón y encuentre **"Confirmar Registro "** <marca>y haga clic en el botón **"Verificar Registro "**.' ,
2021-10-05 15:39:44 +02:00
'TELEGRAM_NOT_CONNECTED' : 'Telegram no asociado a su cuenta!' ,
2020-03-31 20:34:24 +02:00
'NESSUN_INVITATO' : 'No invitaste a nadie' ,
'ZOOM_PARTECIPATO' : 'Participación en al menos 1 Conferencia (Zoom)' ,
'LINEE_GUIDA' : 'Directrices aceptadas' ,
2021-12-23 14:13:40 +01:00
'VIDEO_INTRO' : 'Ver el video' ,
2020-03-31 20:34:24 +02:00
'SCRITTO_SOGNO' : 'Escribiste tu sueño' ,
2020-07-02 22:00:58 +02:00
'PAYMENTS' : 'Métodos de pago' ,
2020-03-31 20:34:24 +02:00
'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)' ,
2020-03-10 21:44:14 +01:00
'CIAO' : 'Hola' ,
'ADDED_TOLISTAINGRESSO' : 'Has sido añadido a la lista de personas que entrarán en Lista de embarque!' ,
2020-03-31 20:34:24 +02:00
'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' ,
2020-05-10 21:07:51 +02:00
'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:' ,
2020-03-31 20:34:24 +02:00
'SOGNATORE' : 'SOÑADOR' ,
2020-05-13 01:32:27 +02:00
'INTERMEDIO' : 'Intermedio' ,
2020-03-31 20:34:24 +02:00
'MEDIATORE' : 'MEDIATOR' ,
'DONATORI' : 'DONANTES' ,
'RITESSITURA' : 'RETEJIDO' ,
'NAVE COMPLETATA' : 'NAVE COMPLETADA' ,
'Doni Effettuati' : 'Regalos Realizados' ,
2022-07-11 23:20:28 +02:00
'Facilitatore che affianchèra il Mediatore' : 'Facilitatore de apoyo al Donante' ,
2020-07-02 22:00:58 +02:00
'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' ,
2020-05-10 21:07:51 +02:00
'SPOSTATO' : 'Has sido trasladado a una nueva nave !' ,
2020-03-31 20:34:24 +02:00
'Note' : 'Notas' ,
'TEMPORANEA' : 'TEMPORAL' ,
'NAVE' : 'NAVE' ,
2020-04-07 14:34:29 +02:00
'MSG_SEND_FROM' : 'Mensaje enviado por' ,
2020-09-04 00:06:49 +02:00
'ZOOM_CONFERMATO' : '¡Se ha confirmado que ha visto la Video Conferencia de Bienvenida!' ,
2022-03-06 00:48:33 +01:00
'RICHIESTA_AMICIZIA' : 'Richiesta d\'Amicizia da parte di %s' ,
'ACCETTATO_SUL_GRUPPO' : 'Sei stato accettato da %s a far parte del Gruppo %s' ,
2022-03-30 22:51:03 +02:00
'ACCETTATO_NOTIFICA_ADMINS' : 'l\'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)' ,
2022-03-06 00:48:33 +01:00
'RICHIESTA_BLOCCO_GRUPPO' : 'Richiesta di bloccare il Gruppo %s da parte di %s' ,
2020-01-20 01:48:25 +01:00
} ,
2020-03-31 20:34:24 +02:00
enUs : {
2021-10-05 15:39:44 +02:00
'partecipanti' : 'participants' ,
'partecipanti a Pranzo' : 'partecipanti a Pranzo' ,
'partecipanti a Cena' : 'partecipanti a Cena' ,
2021-12-23 14:13:40 +01:00
'TESTO_ASSISTENZA' : 'To enter the Site:\n%s\n\nForgot your password to access the site?\n' +
2022-12-15 18:09:43 +01:00
'https://freeplanet.app/requestresetpwd\nChat AYNI BOT (this one):\nhttps://t.me/notevoleaynibot\n\n' ,
2021-10-05 15:39:44 +02:00
'BENVENUTO' : 'Welcome' ,
'TUE_NAVI' : 'Here are your programmed ships' ,
2020-03-31 20:34:24 +02:00
'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' ,
2020-05-11 22:43:14 +02:00
'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👉🏻 <a href="%s">Dashboard</a>\n' ,
2021-12-23 14:13:40 +01:00
'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' ,
2020-04-24 10:29:25 +02:00
'INFO_LINK_ZOOM' : 'Links to share to participate in Zoom (Online Conference):\n%s' ,
2020-03-31 20:34:24 +02:00
'ZOOM_CONFERENCE' : 'Here you can find the Zoom Conference Planning:' ,
2021-10-05 15:39:44 +02:00
'NON_VERIF' : 'Not Verified' ,
'VERIF' : 'Verified' ,
'EMAIL' : 'Email' ,
2021-12-23 14:13:40 +01:00
'BOT' : 'BOT' ,
'EMAIL_NON_VERIF' : 'Email Not Verified\nread your mailbox and find **"Confirm Registration "**<br>and click on the button **"Verify Registration "**.' ,
2021-10-05 15:39:44 +02:00
'TELEGRAM_NOT_CONNECTED' : 'Telegram not associated with your account!' ,
2020-03-31 20:34:24 +02:00
'NESSUN_INVITATO' : 'You didn\'t invite anyone' ,
'ZOOM_PARTECIPATO' : 'Participation in at least 1 Conference (Zoom)' ,
'LINEE_GUIDA' : 'Guidelines Accepted' ,
2021-12-23 14:13:40 +01:00
'VIDEO_INTRO' : 'Seen the Video' ,
2020-03-31 20:34:24 +02:00
'SCRITTO_SOGNO' : 'You wrote your Dream' ,
2020-07-02 22:00:58 +02:00
'PAYMENTS' : 'Methods of Payment' ,
2020-03-31 20:34:24 +02:00
'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' ,
2020-05-10 21:07:51 +02:00
'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:' ,
2020-03-31 20:34:24 +02:00
'SOGNATORE' : 'DREAMER' ,
2020-05-13 01:32:27 +02:00
'INTERMEDIO' : 'Intermediate' ,
2020-03-31 20:34:24 +02:00
'MEDIATORE' : 'MEDIATOR' ,
'DONATORI' : 'DONOR' ,
'RITESSITURA' : 'RE-ENTER' ,
'NAVE COMPLETATA' : 'SHIP COMPLETED' ,
'Doni Effettuati' : 'Gifts Made' ,
2022-07-11 23:20:28 +02:00
'Facilitatore che affianchèra il Mediatore' : 'Facilitatore supporting the Mediator' ,
2020-07-02 22:00:58 +02:00
'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.' ,
2020-05-10 21:07:51 +02:00
'SPOSTATO' : 'You\'ve been moved to a New Ship !' ,
2020-03-31 20:34:24 +02:00
'Note' : 'Note' ,
'TEMPORANEA' : 'TEMPORARY' ,
'NAVE' : 'SHIP' ,
2020-04-07 14:34:29 +02:00
'MSG_SEND_FROM' : 'Msg sent by' ,
2020-09-04 00:06:49 +02:00
'ZOOM_CONFERMATO' : 'You have been confirmed to have seen the Welcome Video Conference!' ,
2022-03-06 00:48:33 +01:00
'RICHIESTA_AMICIZIA' : 'Richiesta d\'Amicizia da parte di %s' ,
'ACCETTATO_SUL_GRUPPO' : 'Sei stato accettato da %s a far parte del Gruppo %s' ,
2022-03-30 22:51:03 +02:00
'ACCETTATO_NOTIFICA_ADMINS' : 'l\'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)' ,
2022-03-06 00:48:33 +01:00
'RICHIESTA_BLOCCO_GRUPPO' : 'Richiesta di bloccare il Gruppo %s da parte di %s' ,
2020-03-31 20:34:24 +02:00
} ,
fr : {
2021-10-05 15:39:44 +02:00
'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 a Pranzo' : 'partecipanti a Pranzo' ,
'partecipanti a Cena' : 'partecipanti a Cena' ,
2021-12-23 14:13:40 +01:00
'TESTO_ASSISTENZA' : 'Pour entrer sur le site:\n%s\n\n' +
2022-12-15 18:09:43 +01:00
'Vous avez oublié votre mot de passe pour accéder au site ?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n' ,
2021-10-05 15:39:44 +02:00
'BENVENUTO' : 'Bienvenue' ,
'TUE_NAVI' : 'Voici vos navires programmés' ,
2020-03-31 20:34:24 +02:00
'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!' ,
2021-12-23 14:13:40 +01:00
'HAI_I_9_REQUISITI' : 'FÉLICITATIONS!\n!Vous avez franchi les 9 étapes de la conduite ! Merci d\'avoir aidé à se développer!' ,
2020-03-31 20:34:24 +02:00
'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' ,
2020-05-11 22:43:14 +02:00
'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 👉🏻 <a href="%s">Tableau</a>.\n' ,
2021-12-23 14:13:40 +01:00
'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' ,
2020-04-24 10:29:25 +02:00
'INFO_LINK_ZOOM' : 'Liens à partager pour participer à Zoom (Conférence en ligne):\n%s' ,
2020-03-31 20:34:24 +02:00
'ZOOM_CONFERENCE' : 'Vous trouverez ici les dates de programmation sur Zoom:' ,
2021-10-05 15:39:44 +02:00
'NON_VERIF' : 'Non vérifié' ,
'VERIF' : 'Vérifié' ,
'EMAIL' : 'Courriel' ,
2021-12-23 14:13:40 +01:00
'BOT' : 'BOT' ,
'EMAIL_NON_VERIF' : 'Courriel non vérifié\nlisez votre boîte aux lettres et trouvez **"Confirmer l\'inscription "**<br>et cliquez sur le bouton **"Vérifier l\'inscription "**.' ,
2021-10-05 15:39:44 +02:00
'TELEGRAM_NOT_CONNECTED' : 'Télégramme non associé à votre compte!' ,
2020-03-31 20:34:24 +02:00
'NESSUN_INVITATO' : 'Vous n\'avez invité personne' ,
'ZOOM_PARTECIPATO' : 'Participation à au moins 1 conférence (Zoom)' ,
'LINEE_GUIDA' : 'Lignes directrices acceptées' ,
2021-12-23 14:13:40 +01:00
'VIDEO_INTRO' : 'Voir la vidéo' ,
2020-03-31 20:34:24 +02:00
'SCRITTO_SOGNO' : 'Vous avez écrit votre rêve' ,
2020-07-02 22:00:58 +02:00
'PAYMENTS' : 'Modes de paiement' ,
2020-03-31 20:34:24 +02:00
'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' ,
2020-05-10 21:07:51 +02:00
'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:' ,
2020-03-31 20:34:24 +02:00
'SOGNATORE' : 'Rêveur' ,
2020-05-13 01:32:27 +02:00
'INTERMEDIO' : 'Intermediaire' ,
2020-03-31 20:34:24 +02:00
'MEDIATORE' : 'Médiateur' ,
'DONATORI' : 'DONATEUR' ,
'RITESSITURA' : 'RETESSITURA' ,
'NAVE COMPLETATA' : 'NAVIRE COMPLÉTÉ' ,
'Doni Effettuati' : 'Don effectués' ,
2022-07-11 23:20:28 +02:00
'Facilitatore che affianchèra il Mediatore' : 'Le tuteur qui soutient le Mediateur' ,
2020-07-02 22:00:58 +02:00
'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' ,
2020-05-10 21:07:51 +02:00
'SPOSTATO' : 'Vous avez été transféré sur un nouveau navire !' ,
2020-03-31 20:34:24 +02:00
'Note' : 'Notes' ,
'TEMPORANEA' : 'TEMPORAIRE' ,
'NAVE' : 'NAVIRE' ,
2020-04-07 14:34:29 +02:00
'MSG_SEND_FROM' : 'Message envoyé par' ,
2020-09-04 00:06:49 +02:00
'ZOOM_CONFERMATO' : 'Vous avez été confirmé comme ayant vu la vidéoconférence de bienvenue !' ,
2022-03-06 00:48:33 +01:00
'RICHIESTA_AMICIZIA' : 'Richiesta d\'Amicizia da parte di %s' ,
'ACCETTATO_SUL_GRUPPO' : 'Sei stato accettato da %s a far parte del Gruppo %s' ,
2022-03-30 22:51:03 +02:00
'ACCETTATO_NOTIFICA_ADMINS' : 'l\'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)' ,
2022-03-06 00:48:33 +01:00
'RICHIESTA_BLOCCO_GRUPPO' : 'Richiesta di bloccare il Gruppo %s da parte di %s' ,
2020-03-31 20:34:24 +02:00
} ,
pt : {
2021-10-05 15:39:44 +02:00
'L\'Email è già stata Verificata' : '' ,
'Nuova Registrazione' : 'Novo Registo' ,
'Effettuata una Nuova Registrazione' : 'Foi efectuado um novo registo' ,
'partecipanti' : 'participantes' ,
'partecipanti a Pranzo' : 'partecipanti a Pranzo' ,
'partecipanti a Cena' : 'partecipanti a Cena' ,
2021-12-23 14:13:40 +01:00
'TESTO_ASSISTENZA' : 'Para entrar no site:\n%s\n\n' +
2022-12-15 18:09:43 +01:00
'Esqueceu sua senha para acessar o site?\nhttps://freeplanet.app/requestresetpwd\n\n' ,
2021-10-05 15:39:44 +02:00
'BENVENUTO' : 'Bem-vindo' ,
'TUE_NAVI' : 'Aqui estão os seus navios programados' ,
2020-05-04 19:34:41 +02:00
'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' ,
2020-05-11 22:43:14 +02:00
'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 👉🏻 <a href="%s">Entre no seu Tablero</a>.\n' ,
2021-12-23 14:13:40 +01:00
'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' ,
2020-05-04 19:34:41 +02:00
'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:' ,
2021-10-05 15:39:44 +02:00
'NON_VERIF' : 'Não verificado' ,
'VERIF' : 'Verificado' ,
'EMAIL' : 'Email' ,
2021-12-23 14:13:40 +01:00
'BOT' : 'BOT' ,
'EMAIL_NON_VERIF' : 'Email Não verificado\nleia a sua caixa de correio e encontre **"Confirmar o registo"**<br>e clique no botão **"Verificação do registo"**' ,
2021-10-05 15:39:44 +02:00
'TELEGRAM_NOT_CONNECTED' : 'Telegrama não associado à sua conta!' ,
2020-05-04 19:34:41 +02:00
'NESSUN_INVITATO' : 'Você não convidou ninguém' ,
'ZOOM_PARTECIPATO' : 'Participação em pelo menos 1 Conferência (Zoom)' ,
'LINEE_GUIDA' : 'Directrizes Aceites' ,
2021-12-23 14:13:40 +01:00
'VIDEO_INTRO' : 'Ver o vídeo' ,
2020-05-04 19:34:41 +02:00
'SCRITTO_SOGNO' : 'Você escreveu o seu sonho' ,
2020-07-02 22:00:58 +02:00
'PAYMENTS' : 'Formas de pagamento' ,
2020-05-04 19:34:41 +02:00
'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' ,
2020-05-10 21:07:51 +02:00
'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:' ,
2020-03-31 20:34:24 +02:00
'SOGNATORE' : 'SONHEIROS' ,
2020-05-13 01:32:27 +02:00
'INTERMEDIO' : 'Intermediar' ,
2020-03-31 20:34:24 +02:00
'MEDIATORE' : 'MEDIATOR' ,
'DONATORI' : 'DONATORES' ,
'RITESSITURA' : 'ENTRE EM' ,
'NAVE COMPLETATA' : 'NAVIO COMPLETADO' ,
'Doni Effettuati' : 'Regalo Feitos' ,
2022-07-11 23:20:28 +02:00
'Facilitatore che affianchèra il Mediatore' : 'Facilitatore que apoia o Mediator' ,
2020-07-02 22:00:58 +02:00
'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.' ,
2020-05-10 21:07:51 +02:00
'SPOSTATO' : 'Você foi transferido para um novo navio !' ,
2020-03-31 20:34:24 +02:00
'Note' : 'Notas' ,
'TEMPORANEA' : 'TEMPORÁRIO' ,
'NAVE' : 'NAVE' ,
2020-04-07 14:34:29 +02:00
'MSG_SEND_FROM' : 'Mensagem enviada por' ,
2020-09-04 00:06:49 +02:00
'ZOOM_CONFERMATO' : 'Foi-lhe confirmado que assistiu à Conferência de Vídeo de Boas-vindas!' ,
2022-03-06 00:48:33 +01:00
'RICHIESTA_AMICIZIA' : 'Richiesta d\'Amicizia da parte di %s' ,
'ACCETTATO_SUL_GRUPPO' : 'Sei stato accettato da %s a far parte del Gruppo %s' ,
2022-03-30 22:51:03 +02:00
'ACCETTATO_NOTIFICA_ADMINS' : 'l\'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)' ,
2022-08-04 17:30:57 +02:00
2022-03-06 00:48:33 +01:00
'RICHIESTA_BLOCCO_GRUPPO' : 'Richiesta di bloccare il Gruppo %s da parte di %s' ,
2020-03-31 20:34:24 +02:00
} ,
2020-01-20 01:48:25 +01:00
} ;
2024-07-23 12:25:10 +02:00
/ * *
* Scarica un ' immagine da una URL e la salva in una directory locale
* @ param { string } url - L 'URL dell' immagine da scaricare
* @ param { string } filepath - Il percorso dove salvare l ' immagine scaricata
* /
class ImageDownloader {
/ * *
* Scarica un ' immagine da una URL e la salva in una directory locale .
* Tenta di scaricare fino a 3 volte in caso di errore , con un ritardo tra i tentativi .
*
* @ param { string } url - L 'URL dell' immagine da scaricare
* @ param { string } filepath - Il percorso dove salvare l ' immagine scaricata
* @ param { number } maxRetries - Numero massimo di tentativi in caso di fallimento ( default : 3 )
* @ param { number } delay - Ritardo in millisecondi tra i tentativi ( default : 1000 )
* @ returns { Promise < boolean > }
* /
2024-10-26 17:11:52 +02:00
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
} = options ;
// Funzione per il backoff esponenziale
const getDelay = ( attempt ) => {
return Math . min ( initialDelay * Math . pow ( 2 , attempt - 1 ) , maxDelay ) ;
} ;
2024-07-23 12:25:10 +02:00
for ( let attempt = 1 ; attempt <= maxRetries ; attempt ++ ) {
try {
2024-10-26 17:11:52 +02:00
// Verifica se il filepath esiste già
if ( fs . existsSync ( filepath ) ) {
fs . unlinkSync ( filepath ) ;
}
2024-07-23 12:25:10 +02:00
2024-10-26 17:11:52 +02:00
const writer = fs . createWriteStream ( filepath ) ;
if ( attempt > 1 )
console . log ( ` 📥 Tentativo ${ attempt } / ${ maxRetries } - Scaricamento: ${ url } ` ) ;
2024-07-23 12:25:10 +02:00
const response = await axios ( {
url ,
method : 'GET' ,
responseType : 'stream' ,
2024-10-26 17:11:52 +02:00
timeout : timeout ,
maxRedirects : 5 ,
2024-07-23 12:25:10 +02:00
headers : {
2024-10-26 17:11:52 +02:00
'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 } ` ) ;
2024-07-23 12:25:10 +02:00
}
2024-10-26 17:11:52 +02:00
}
// 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 ;
2024-07-23 12:25:10 +02:00
} ) ;
2024-08-29 23:30:58 +02:00
2024-07-23 12:25:10 +02:00
response . data . pipe ( writer ) ;
await new Promise ( ( resolve , reject ) => {
2024-10-26 17:11:52 +02:00
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 ) ;
2024-07-23 12:25:10 +02:00
} ) ;
} ) ;
2024-10-26 17:11:52 +02:00
console . info ( ` ✅ Immagine scaricata con successo in ${ filepath } ` ) ;
2024-07-23 12:25:10 +02:00
return true ;
2024-10-26 17:11:52 +02:00
2024-07-23 12:25:10 +02:00
} catch ( error ) {
2024-10-26 17:11:52 +02:00
console . error ( ` ❌ Errore nel tentativo ${ attempt } / ${ maxRetries } : ` , error . message ) ;
// Pulizia del file in caso di errore
if ( fs . existsSync ( filepath ) ) {
fs . unlinkSync ( filepath ) ;
}
2024-07-23 12:25:10 +02:00
if ( attempt === maxRetries ) {
2024-10-26 17:11:52 +02:00
console . error ( ` Download fallito dopo ${ maxRetries } tentativi: ${ error . message } ` ) ;
2024-07-23 12:25:10 +02:00
return false ;
}
2024-10-26 17:11:52 +02:00
const delay = getDelay ( attempt ) ;
console . info ( ` 🔄 Attendo ${ delay } ms prima del prossimo tentativo... ` ) ;
await new Promise ( resolve => setTimeout ( resolve , delay ) ) ;
2024-07-23 12:25:10 +02:00
}
}
}
}
// Funzione per implementare il ritardo tra i tentativi
function sleep ( ms ) {
return new Promise ( resolve => setTimeout ( resolve , ms ) ) ;
}
2018-12-24 20:31:02 +01:00
module . exports = {
2021-04-30 01:31:12 +02:00
MYAPPS : [ ] ,
2019-10-28 16:01:28 +01:00
INITDB _FIRSTIME : true ,
2020-02-19 16:09:16 +01:00
ACAPO : '\n' ,
2019-10-28 16:01:28 +01:00
2020-05-19 00:18:13 +02:00
ENABLE _CRONTAB : 'CRONTAB' ,
2020-06-08 13:31:05 +02:00
UPDATE _GRADUATORIA : 'UPDATE_GRAD' ,
2020-05-19 00:18:13 +02:00
2020-01-03 01:52:49 +01:00
LANGADMIN : 'it' ,
2021-12-23 14:13:40 +01:00
FREEPLANET : '1' ,
2020-02-19 16:09:16 +01:00
AYNI : '7' ,
2021-02-24 04:48:31 +01:00
CNM : '10' ,
2022-03-02 20:18:29 +01:00
RISO : '13' ,
2023-10-21 15:27:53 +02:00
FIOREDELLAVITA : '15' ,
2023-12-16 00:51:03 +01:00
PIUCHEBUONO : '17' ,
2020-02-19 16:09:16 +01:00
2024-02-27 22:08:06 +01:00
IDAPP _BOTONGROUP : '1000' ,
2021-12-23 14:13:40 +01:00
HELP _CHAT : '' ,
2020-07-02 22:00:58 +02:00
TYPECONF _ZOOM : 'zoom' ,
TYPECONF _JITSI : 'jitsi' ,
2020-01-13 23:52:51 +01:00
APORTADOR _NONE : '------' ,
2022-01-16 23:21:03 +01:00
SEP : '|' ,
2023-03-21 18:11:56 +01:00
USER _ADMIN _CIRCUITS : 'paoloar77' ,
2019-04-07 21:24:27 +02:00
TYPE _PROJECT : 1 ,
TYPE _TODO : 2 ,
2020-03-10 21:44:14 +01:00
TipoMsg : {
SEND _LINK _CHAT _DONATORI : 1 ,
2020-03-25 09:25:31 +01:00
SEND _MSG : 2 ,
SEND _MSG _SINGOLO : 3 ,
2020-04-24 10:29:25 +02:00
SEND _TO _ALL : 10 ,
2020-06-08 13:31:05 +02:00
SEND _MSG _EFFETTUA _IL _DONO : 1000 ,
SEND _MSG _SOLLECITO _DONATORI _NO _DONO : 1005 ,
SEND _MSG _A _MEDIATORI : 1010 ,
SEND _MSG _A _SOGNATORE : 1020 ,
SEND _MSG _A _UTENTE _SOSTITUITO : 1030 ,
SEND _MSG _DONO _RICEVUTO _CORRETTAMENTE : 1040 ,
2020-07-02 22:00:58 +02:00
SEND _MSG _DONO _NON _RICEVUTO : 1050 ,
2020-03-10 21:44:14 +01:00
} ,
2022-01-03 21:53:50 +01:00
Perm : {
PERM _NONE : 0 ,
PERM _FRIEND : 1 ,
PERM _ALL : 10 ,
} ,
2020-03-10 21:44:14 +01:00
Placca : {
DONATORI : 1 ,
TUTTI : 2 ,
2020-05-11 22:43:14 +02:00
STR _SOGNATORE : '<strong>Sognatore</strong>' ,
STR _MEDIATORE : '<strong>Mediatore</strong>' ,
STR _MEDIATORI : '<strong>Mediatori</strong>' ,
STR _DONATORI : '<strong>Donatori</strong>' ,
2020-03-10 21:44:14 +01:00
SOGNATORE : 'E1 🌈 ' ,
MEDIATORE : 'A1 💦 ' ,
SONOFUOCO : 0 ,
SONOACQUA : 3 ,
2020-03-21 10:28:26 +01:00
SONOTERRA : 2 ,
SONOARIA : 1 ,
2020-03-10 21:44:14 +01:00
} ,
2019-11-05 23:53:39 +01:00
FieldType : {
boolean : 1 ,
date : 2 ,
string : 4 ,
binary : 8 ,
html : 16 ,
select : 32 ,
number : 64 ,
typeinrec : 128 ,
2019-11-12 21:34:03 +01:00
multiselect : 256 ,
2019-12-04 02:03:44 +01:00
password : 512 ,
2019-12-27 12:41:39 +01:00
listimages : 1024 ,
2020-04-07 14:34:29 +02:00
exact : 2048 ,
2021-02-18 12:19:35 +01:00
image : 3000 ,
2024-03-02 22:53:29 +01:00
image _and _filename : 3100 ,
2021-02-18 12:19:35 +01:00
nationality : 4096 ,
intcode : 5000 ,
multioption : 6000 ,
onlydate : 7000 ,
2021-10-05 15:39:44 +02:00
hours : 8000 ,
2021-12-23 14:13:40 +01:00
crypted : 9000 ,
2019-11-05 23:53:39 +01:00
} ,
2019-04-07 21:24:27 +02:00
MAX _PHASES : 5 ,
2019-04-06 21:02:39 +02:00
FIRST _PROJ : '__PROJECTS' ,
EXECUTE _CALCPROJ : true ,
2019-10-13 20:44:05 +02:00
2020-01-20 01:48:25 +01:00
gettranslate ( text , lang ) {
try {
2021-10-05 15:39:44 +02:00
return textlang [ lang ] [ text ] ;
2020-01-21 01:37:15 +01:00
} catch ( e ) {
2021-10-05 15:39:44 +02:00
return textlang [ 'it' ] [ text ] ;
2020-01-20 01:48:25 +01:00
}
} ,
2020-03-31 20:34:24 +02:00
getlangbyres ( res ) {
// ++Todo: res estrarre la lingua
let lang = '' ;
try {
2021-10-05 15:39:44 +02:00
lang = res . lang ;
2020-03-31 20:34:24 +02:00
} catch ( e ) {
}
if ( ! lang ) {
lang = 'it' ;
}
2021-10-05 15:39:44 +02:00
return lang ;
2020-03-31 20:34:24 +02:00
} ,
get _ _ ( text , lang ) {
2020-01-20 01:48:25 +01:00
try {
2021-10-05 15:39:44 +02:00
return textlang [ lang ] [ text ] ;
2020-01-21 01:37:15 +01:00
} catch ( e ) {
2021-10-05 15:39:44 +02:00
return textlang [ 'it' ] [ text ] ;
2020-01-20 01:48:25 +01:00
}
} ,
getres _ _ ( text , res ) {
2020-04-07 14:34:29 +02:00
let lang = this . getlangbyres ( res ) ;
2020-01-20 01:48:25 +01:00
try {
2021-10-05 15:39:44 +02:00
return textlang [ lang ] [ text ] ;
2020-01-21 01:37:15 +01:00
} catch ( e ) {
2021-10-05 15:39:44 +02:00
return textlang [ 'it' ] [ text ] ;
2020-01-20 01:48:25 +01:00
}
} ,
2022-12-15 18:09:43 +01:00
getHostname : function ( ) {
2021-10-05 15:39:44 +02:00
return os . hostname ( ) ;
2019-02-07 00:52:48 +01:00
} ,
2022-12-15 18:09:43 +01:00
testing : function ( ) {
2021-10-05 15:39:44 +02:00
return ( process . env . TESTING _ON === '1' ) ;
2019-02-07 00:52:48 +01:00
} ,
2022-12-15 18:09:43 +01:00
mylog : function ( ... args ) {
2019-02-07 00:52:48 +01:00
if ( ! this . testing ( ) )
2021-10-05 15:39:44 +02:00
console . log ( args ) ;
2019-02-07 00:52:48 +01:00
} ,
2022-12-15 18:09:43 +01:00
mylogoff : function ( ... args ) {
2019-02-11 02:59:05 +01:00
// doing nothing
} ,
2022-12-15 18:09:43 +01:00
mylogshow : function ( ... args ) {
2021-10-05 15:39:44 +02:00
console . log ( args ) ;
} ,
2022-12-15 18:09:43 +01:00
mylogserr : function ( ... args ) {
2021-10-05 15:39:44 +02:00
console . error ( args ) ;
} ,
2022-12-15 18:09:43 +01:00
allfieldSendMsg : function ( ) {
2021-10-05 15:39:44 +02:00
return [
'userId' ,
'source' ,
'dest' ,
'message' ,
'datemsg' ,
'read' ,
'deleted' ,
'origin' ,
'idapp' ,
'status' ,
'options' ] ;
} ,
2022-12-15 18:09:43 +01:00
allfieldSendNotif : function ( ) {
2022-07-10 01:25:19 +02:00
return [
'type' ,
'userId' ,
'sender' ,
2022-07-23 17:48:33 +02:00
'typedir' ,
'typeid' ,
2022-07-10 01:25:19 +02:00
'dest' ,
'descr' ,
2022-07-26 15:46:39 +02:00
'title' ,
2022-07-23 17:48:33 +02:00
'openUrl' ,
2022-07-10 01:25:19 +02:00
'datenotif' ,
2022-09-18 20:17:24 +02:00
'date_updated' ,
2022-07-10 01:25:19 +02:00
'read' ,
'deleted' ,
'idapp' ,
2022-07-23 17:48:33 +02:00
'tablerec' ,
2022-08-04 17:30:57 +02:00
'extrafield' ,
2022-08-07 02:01:35 +02:00
'tag' ,
'options' ,
2022-07-23 17:48:33 +02:00
'idrec' ,
2022-07-10 01:25:19 +02:00
'status' ] ;
} ,
2022-12-15 18:09:43 +01:00
allfieldTodo : function ( ) {
2021-10-05 15:39:44 +02:00
return [
'userId' ,
'pos' ,
'category' ,
'descr' ,
'note' ,
'priority' ,
'statustodo' ,
'assignedToUsers' ,
'created_at' ,
'groupId' ,
'modify_at' ,
'completed_at' ,
'expiring_at' ,
'enableExpiring' ,
'progress' ,
'modified' ,
'phase' ,
'assigned_to_userId' ,
'assignedToUsers' ,
'hoursplanned' ,
'hoursworked' ,
'start_date' ,
'themecolor' ,
'themebgcolor' ] ;
} ,
2022-12-15 18:09:43 +01:00
allfieldMyEvent : function ( ) {
2021-10-05 15:39:44 +02:00
return [ 'userId' ] ;
} ,
2022-12-15 18:09:43 +01:00
allfieldTodoWithId : function ( ) {
2021-10-05 15:39:44 +02:00
return [ '_id' , ... this . allfieldTodo ( ) ] ;
2019-02-12 12:06:25 +01:00
} ,
2019-03-28 12:58:58 +01:00
// #TODO Projects++ Add fields ...
2022-12-15 18:09:43 +01:00
allfieldProject : function ( ) {
2021-10-05 15:39:44 +02:00
return [
'idapp' ,
'userId' ,
'respUsername' ,
'viceRespUsername' ,
'pos' ,
'typeproj' ,
'id_main_project' ,
'id_parent' ,
'descr' ,
'longdescr' ,
'groupId' ,
'hoursplanned' ,
'hoursleft' ,
'themecolor' ,
'themebgcolor' ,
'hoursworked' ,
'priority' ,
'statusproj' ,
'created_at' ,
'modify_at' ,
'completed_at' ,
'expiring_at' ,
'enableExpiring' ,
'progressCalc' ,
'modified' ,
'live_url' ,
'test_url' ,
'begin_development' ,
'begin_test' ,
'totalphases' ,
'actualphase' ,
'hoursweeky_plannedtowork' ,
'endwork_estimate'
,
'privacyread' ,
'privacywrite' ,
'tipovisu' ,
'view' ] ;
} ,
2022-12-15 18:09:43 +01:00
allfieldBooking : function ( ) {
2021-10-05 15:39:44 +02:00
return [
'idapp' ,
'userId' ,
2023-04-17 00:11:36 +02:00
'username' ,
2021-10-05 15:39:44 +02:00
'id_bookedevent' ,
2023-04-17 00:11:36 +02:00
'tableType' ,
2021-10-05 15:39:44 +02:00
'numpeople' ,
'numpeopleLunch' ,
'numpeopleDinner' ,
'numpeopleDinnerShared' ,
'msgbooking' ,
'modified' ,
'infoevent' ,
'datebooked' ,
'booked' ] ;
} ,
2022-12-15 18:09:43 +01:00
allfieldBookingChange : function ( ) {
2021-10-05 15:39:44 +02:00
return [
'numpeople' ,
'numpeopleLunch' ,
'numpeopleDinner' ,
'numpeopleDinnerShared' ,
'msgbooking' ,
'modified' ,
'infoevent' ,
'datebooked' ,
'booked' ] ;
} ,
2022-12-15 18:09:43 +01:00
allfieldProjectWithId : function ( ) {
2021-10-05 15:39:44 +02:00
return [ '_id' , ... this . allfieldProject ( ) ] ;
2019-03-28 12:58:58 +01:00
} ,
jsonCopy ( src ) {
2021-10-05 15:39:44 +02:00
return JSON . parse ( JSON . stringify ( src ) ) ;
2019-03-28 12:58:58 +01:00
} ,
2019-10-21 20:38:10 +02:00
CloneRecordToNew ( src ) {
const myrec = Object . assign ( { } , src ) ;
delete myrec . _doc [ '_id' ] ;
myrec . _id = new ObjectID ( ) ;
2021-10-05 15:39:44 +02:00
return myrec . _doc ;
2019-10-21 20:38:10 +02:00
} ,
2022-12-15 18:09:43 +01:00
sendBackNotif : function ( subscription , payload ) {
2024-02-28 23:56:23 +01:00
const Subscription = require ( '../models/subscribers' ) ;
2019-02-12 12:06:25 +01:00
2022-02-09 19:48:39 +01:00
// console.log('sendBackNotif:', subscription, payload);
2021-10-05 15:39:44 +02:00
const pushOptions = {
vapidDetails : {
subject : process . env . VAPI _KEY _SUBJECT ,
privateKey : process . env . PRIVATE _VAPI _KEY ,
publicKey : process . env . PUBLIC _VAPI _KEY ,
} ,
TTL : payload . ttl ,
2022-01-14 23:54:33 +01:00
headers : { } ,
2021-10-05 15:39:44 +02:00
} ;
2019-02-12 12:06:25 +01:00
// Pass object into sendNotification
2022-07-23 17:48:33 +02:00
return webpush . sendNotification ( subscription . _doc , JSON . stringify ( payload ) ,
2022-12-15 18:09:43 +01:00
pushOptions ) .
catch ( ( err ) => {
if ( err . statusCode === 410 ) {
// Gone: is not valid anymore (Expired probably!), so I have to delete from my db
return Subscription . findOneAndRemove ( { _id : subscription . _id } ) ;
} else {
console . log ( 'Subscription is no longer valid: ' , err ) ;
}
} ) . then ( ( ris ) => {
2022-09-19 14:37:57 +02:00
2022-12-15 18:09:43 +01:00
} ) .
// console.log('sendNotification', ris);
catch ( err => {
console . error ( err ) ;
} ) ;
2019-02-14 19:01:41 +01:00
} ,
2022-12-15 18:09:43 +01:00
sendNotificationToUser : async function ( userId , title , content , openUrl , openUrl2 , tag , actions , id ) {
2024-02-28 23:56:23 +01:00
const Subscription = require ( '../models/subscribers' ) ;
2022-08-07 02:01:35 +02:00
content = this . convertHTMLtoText ( content ) ;
2019-02-14 19:01:41 +01:00
2022-09-18 20:17:24 +02:00
content = this . ConvertHTMLToPlainText ( content ) ;
2019-02-14 19:01:41 +01:00
let payload = {
2020-04-24 10:29:25 +02:00
actions ,
2019-02-14 19:01:41 +01:00
title : title ,
2020-04-24 10:29:25 +02:00
content ,
2019-02-14 19:01:41 +01:00
url : openUrl ,
2020-04-24 10:29:25 +02:00
url2 : openUrl2 ,
2019-02-14 19:01:41 +01:00
tag ,
2022-08-07 02:01:35 +02:00
id ,
2019-02-14 19:01:41 +01:00
// ttl: req.body.ttl,
// icon: req.body.icon,
// image: req.body.image,
// badge: req.body.badge,
// tag: req.body.tag
} ;
2022-09-11 11:45:33 +02:00
try {
2019-02-14 19:01:41 +01:00
2022-12-15 18:09:43 +01:00
return await Subscription . find ( { userId } , ( err , subscriptions ) => {
2022-09-11 11:45:33 +02:00
if ( err ) {
console . error ( ` Error occurred while getting subscriptions ` ) ;
// res.status(500).json({
// error: 'Technical error occurred'
// });
2022-02-22 18:27:59 +01:00
2022-09-11 11:45:33 +02:00
//++ Rimuovi questo record !?
2022-02-22 18:27:59 +01:00
2022-09-11 11:45:33 +02:00
return false ;
} else {
let conta = 0 ;
let parallelSubscriptionCalls = subscriptions . map ( ( subscription ) => {
const trovati = subscriptions . length ;
return new Promise ( ( resolve , reject ) => {
const pushSubscription = {
2019-02-14 19:01:41 +01:00
endpoint : subscription . endpoint ,
2022-09-11 11:45:33 +02:00
keys : {
p256dh : subscription . keys . p256dh ,
auth : subscription . keys . auth ,
} ,
} ;
conta ++ ;
const parse = require ( 'url-parse' ) ;
const parsedUrl = parse ( subscription . endpoint ) ;
const audience = parsedUrl . protocol + '//' + parsedUrl . hostname ;
const vapidHeaders = webpush . getVapidHeaders (
2022-12-15 18:09:43 +01:00
audience ,
process . env . VAPI _KEY _SUBJECT ,
process . env . PUBLIC _VAPI _KEY ,
process . env . PRIVATE _VAPI _KEY ,
'aes128gcm' ,
2022-09-11 11:45:33 +02:00
) ;
const pushOptions = {
vapidDetails : {
subject : process . env . VAPI _KEY _SUBJECT ,
privateKey : process . env . PRIVATE _VAPI _KEY ,
publicKey : process . env . PUBLIC _VAPI _KEY ,
} ,
TTL : payload . ttl ,
headers : vapidHeaders ,
} ;
2023-12-28 00:50:35 +01:00
// console.log('************ INVIO WEBPUSH.SENDNOTIFICATION N° ', conta, '/', trovati, 'A', subscription.browser);
2022-09-11 11:45:33 +02:00
const pushPayload = JSON . stringify ( payload ) ;
webpush . sendNotification (
2022-12-15 18:09:43 +01:00
pushSubscription ,
pushPayload ,
pushOptions ,
2022-09-11 11:45:33 +02:00
) . then ( ( value ) => {
// console.log('Invio Push', value);
resolve ( {
status : true ,
endpoint : subscription . endpoint ,
data : value ,
} ) ;
} ) . catch ( async ( err ) => {
console . error ( 'err Push' , err . body ) ;
2023-01-03 16:51:32 +01:00
if ( err . body ) {
// Cancella dal DB la notifica Push, visto che da errore! (sarà scaduto)
const ris = await Subscription . deleteOne ( { _id : subscription . _id } ) ;
}
2022-09-11 11:45:33 +02:00
reject ( {
status : false ,
endpoint : subscription . endpoint ,
data : err ,
} ) ;
2019-02-14 19:01:41 +01:00
} ) ;
2022-09-11 11:45:33 +02:00
} ) . catch ( error => {
console . log ( 'ERROR: sendNotificationToUser' , error . data . body ? error . data . body : error ) ;
2019-02-14 19:01:41 +01:00
} ) ;
} ) ;
2022-09-11 11:45:33 +02:00
// q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
// console.info(pushResults);
// });
// res.json({
// data: 'Push triggered'
// });
return true ;
}
} ) ;
2022-09-14 11:32:04 +02:00
} catch ( e ) {
2022-09-11 11:45:33 +02:00
console . error ( 'sendNotificationToUser' , e . message ) ;
}
2019-02-12 12:06:25 +01:00
2019-02-27 02:59:02 +01:00
} ,
2022-01-14 23:54:33 +01:00
2023-01-21 19:02:19 +01:00
getReqByPar ( idapp , usernameOrig , groupOrig ) {
2022-07-26 15:46:39 +02:00
return {
body : {
idapp : idapp ,
} ,
user : {
username : usernameOrig ,
2023-01-21 19:02:19 +01:00
groupOrig ,
2022-08-04 17:30:57 +02:00
} ,
2022-07-26 15:46:39 +02:00
} ;
} ,
2023-04-12 15:37:54 +02:00
sendNotificationByUsername : async function ( idapp , username , cmd , telegram , usernameOrig , recObjCreator ) {
2022-01-14 23:54:33 +01:00
2022-12-15 18:09:43 +01:00
var { User } = require ( '../models/user' ) ;
const { SendNotif } = require ( '../models/sendnotif' ) ;
2022-01-14 23:54:33 +01:00
2022-03-11 12:38:01 +01:00
const telegrambot = require ( '../telegram/telegrambot' ) ;
2022-12-15 18:09:43 +01:00
const user = await User . findOne ( { idapp , username } , { _id : 1 , username : 1 , lang : 1 } ) . lean ( ) ;
2022-01-14 23:54:33 +01:00
if ( ! user )
return ;
let userId = user . _id ;
let lang = user . lang ;
2022-07-26 15:46:39 +02:00
let sendmynotif = true ;
2022-03-11 12:38:01 +01:00
2022-01-14 23:54:33 +01:00
let title = this . getNomeAppByIdApp ( idapp ) ;
let descr = '' ;
let openUrl = '/' ;
let tag = '' ;
let actions = [ ] ;
2023-11-19 23:40:38 +01:00
let domanda = '' ;
2023-12-11 19:06:22 +01:00
let keyb = null ;
2022-01-14 23:54:33 +01:00
if ( cmd ) {
if ( cmd === shared _consts . FRIENDSCMD . REQFRIEND ) {
2022-02-14 15:38:34 +01:00
descr = printf ( this . get _ _ ( 'RICHIESTA_AMICIZIA' , lang ) , usernameOrig ) ;
openUrl = '/my/' + usernameOrig ;
2022-01-14 23:54:33 +01:00
tag = 'reqfriends' ;
2022-03-11 12:38:01 +01:00
const userrecDest = await User . getUserShortDataByUsername ( idapp , usernameOrig ) ;
if ( userrecDest ) {
2022-07-26 15:46:39 +02:00
sendmynotif = false ; // non lo rimandare 2 volte !
// SEND TELEGRAM NOTIFICATION
2022-03-11 12:38:01 +01:00
telegrambot . askConfirmationUserFriend ( idapp , shared _consts . CallFunz . RICHIESTA _AMICIZIA , userrecDest , username , usernameOrig ) ;
}
2022-07-26 15:46:39 +02:00
2023-01-09 02:37:35 +01:00
} else if ( cmd === shared _consts . FRIENDSCMD . SETHANDSHAKE ) {
2023-06-07 10:14:57 +02:00
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 ) ;
}
2022-01-14 23:54:33 +01:00
}
}
if ( userId ) {
2022-07-26 15:46:39 +02:00
// SEND PUSH NOTIFICATION
2022-09-11 11:45:33 +02:00
await this . sendNotificationToUser ( userId , title , descr , openUrl , '' , tag , actions ) ;
2022-01-14 23:54:33 +01:00
}
2022-07-26 15:46:39 +02:00
if ( telegram && sendmynotif ) {
2022-01-14 23:54:33 +01:00
const idtelegram = await User . TelegIdByUsername ( idapp , username ) ;
2023-11-19 23:40:38 +01:00
await telegrambot . sendMsgTelegramByIdTelegram ( idapp , idtelegram , descr + domanda , undefined , undefined , true , keyb ) ;
2022-01-14 23:54:33 +01:00
}
} ,
2023-02-06 22:58:10 +01:00
sendMsgTelegramToAdmin : async function ( idapp , msg ) {
const telegrambot = require ( '../telegram/telegrambot' ) ;
const idtelegram = telegrambot . ADMIN _IDTELEGRAM _SERVER ;
await telegrambot . sendMsgTelegramByIdTelegram ( idapp , idtelegram , msg ) ;
} ,
2022-12-15 18:09:43 +01:00
sendNotifAndMsgTelegram : async function ( idapp , userId , objmsg , telegram , msgextrateleg ) {
2022-03-06 00:48:33 +01:00
if ( userId ) {
2022-09-11 11:45:33 +02:00
await this . sendNotificationToUser ( userId , objmsg . title , objmsg . descr , objmsg . openUrl , '' , objmsg . tag , objmsg . actions ) ;
2022-03-06 00:48:33 +01:00
}
if ( telegram ) {
2022-12-15 18:09:43 +01:00
var { User } = require ( '../models/user' ) ;
2022-03-06 00:48:33 +01:00
const telegrambot = require ( '../telegram/telegrambot' ) ;
const idtelegram = await User . TelegIdById ( idapp , userId ) ;
2022-06-16 20:34:42 +02:00
const msgteleg = objmsg . descr + ( msgextrateleg ? '\n' + msgextrateleg : '' ) ;
2022-03-06 00:48:33 +01:00
await telegrambot . sendMsgTelegramByIdTelegram ( idapp , idtelegram , msgteleg ) ;
}
} ,
2022-12-15 18:09:43 +01:00
sendNotifGroupByUsername : async function (
cmd , idapp , usernameOrig , usernameDest , username _action , groupname , myrecgroup , isAdmin , username _worked ) {
2022-02-03 00:33:15 +01:00
2022-12-15 18:09:43 +01:00
const { SendNotif } = require ( '../models/sendnotif' ) ;
const { User } = require ( '../models/user' ) ;
2022-03-06 00:48:33 +01:00
const telegrambot = require ( '../telegram/telegrambot' ) ;
2022-08-04 17:30:57 +02:00
const req = this . getReqByPar ( idapp , usernameOrig ) ;
2022-12-15 18:09:43 +01:00
const user = await User . findOne ( { idapp , username : usernameDest } ,
{ _id : 1 , lang : 1 } ) ;
2022-08-04 17:30:57 +02:00
if ( user ) {
let lang = user . lang ;
let paramsObj = {
usernameDest ,
groupnameDest : groupname ,
username _action : username _action ,
singleadmin _username : usernameDest ,
options : 0 ,
lang ,
isAdmin ,
username _worked ,
} ;
2022-03-06 00:48:33 +01:00
2022-08-04 17:30:57 +02:00
let sendnotif = true ;
let typedir = shared _consts . TypeNotifs . TYPEDIR _GROUPS ;
let typeid = 0 ;
let onlysave = false ;
2022-09-03 13:06:58 +02:00
let numuseringroup = await User . countUsersInGroup ( idapp , groupname ) ;
2022-03-06 00:48:33 +01:00
2022-08-04 17:30:57 +02:00
if ( cmd ) {
if ( cmd === shared _consts . GROUPSCMD . SETGROUP ) {
if ( myrecgroup && myrecgroup . createdBy === usernameDest && numuseringroup <= 1 ) {
typeid = shared _consts . TypeNotifs . ID _GROUP _NEW _REC ;
} else {
typeid = shared _consts . TypeNotifs . ID _GROUP _ACCEPTED ;
}
} else if ( cmd === shared _consts . GROUPSCMD . REFUSE _REQ _GROUP ) {
typeid = shared _consts . TypeNotifs . ID _GROUP _REFUSED ;
} else if ( cmd === shared _consts . GROUPSCMD . REMOVE _FROM _MYGROUP ) {
typeid = shared _consts . TypeNotifs . ID _GROUP _REMOVED ;
} else if ( cmd === shared _consts . GROUPSCMD . REQGROUP ) {
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 ) ;
2022-08-07 02:01:35 +02:00
telegrambot . askConfirmationUser ( idapp , shared _consts . CallFunz . RICHIESTA _GRUPPO , myuserdata , usernameDest , groupname ,
2022-12-15 18:09:43 +01:00
myrecgroup . _id ) ;
2022-08-04 17:30:57 +02:00
onlysave = false ;
} else if ( cmd === shared _consts . GROUPSCMD . BLOCK _USER ) {
typeid = shared _consts . TypeNotifs . ID _GROUP _BLOCK _USER ;
} else if ( cmd === shared _consts . GROUPSCMD . DELETE _GROUP ) {
typeid = shared _consts . TypeNotifs . ID _GROUP _DELETE _USER ;
2022-08-09 17:32:06 +02:00
} else if ( cmd === shared _consts . GROUPSCMD . ADDADMIN _OFMYGROUP ) {
typeid = shared _consts . TypeNotifs . ID _GROUP _ADDED _ADMIN _OFMYGROUP ;
} else if ( cmd === shared _consts . GROUPSCMD . REMOVEADMIN _OFMYGROUP ) {
typeid = shared _consts . TypeNotifs . ID _GROUP _REMOVED _ADMIN _OFMYGROUP ;
2022-08-04 17:30:57 +02:00
}
2022-03-06 00:48:33 +01:00
2022-08-04 17:30:57 +02:00
}
2022-06-17 12:30:44 +02:00
2022-08-04 17:30:57 +02:00
if ( sendnotif && typeid > 0 ) {
// CREATE NOTIFICATION IN TABLE SENDNOTIF
await SendNotif . createNewNotifToSingleUser ( req , null , paramsObj , onlysave , typedir , typeid ) ;
}
}
2022-06-17 12:30:44 +02:00
2022-08-04 17:30:57 +02:00
} ,
2022-06-17 12:30:44 +02:00
2022-12-15 18:09:43 +01:00
sendNotifCircuitByUsername : async function (
2023-01-21 19:02:19 +01:00
cmd , idapp , usernameOrig , groupOrig , usernameDest , groupDest , username _action ,
2022-12-15 18:09:43 +01:00
circuitname , path , myreccircuit , isAdmin , username _worked , extrarec ) {
2022-09-02 02:25:38 +02:00
2022-12-15 18:09:43 +01:00
const { SendNotif } = require ( '../models/sendnotif' ) ;
const { User } = require ( '../models/user' ) ;
2022-09-02 02:25:38 +02:00
const telegrambot = require ( '../telegram/telegrambot' ) ;
2023-01-03 16:51:32 +01:00
const { MyGroup } = require ( '../models/mygroup' ) ;
2023-02-01 16:36:10 +01:00
const { Circuit } = require ( '../models/circuit' ) ;
2022-09-02 02:25:38 +02:00
2023-01-21 19:02:19 +01:00
const req = this . getReqByPar ( idapp , usernameOrig , groupOrig ) ;
let arrris = [ ] ;
2022-09-02 02:25:38 +02:00
2022-12-15 18:09:43 +01:00
const user = await User . findOne ( { idapp , username : usernameDest } ,
{ _id : 1 , lang : 1 } ) ;
2022-09-02 02:25:38 +02:00
2023-01-12 01:03:10 +01:00
let lang = 'it' ;
if ( user ) {
lang = user . lang ;
}
2023-01-21 19:02:19 +01:00
let ris = null ;
2023-01-12 01:03:10 +01:00
2022-09-03 13:06:58 +02:00
try {
2023-01-12 01:03:10 +01:00
let paramsObj = {
usernameDest ,
circuitnameDest : circuitname ,
path ,
username _action : username _action ,
singleadmin _username : usernameDest ,
extrarec ,
options : 0 ,
lang ,
isAdmin ,
username _worked ,
} ;
2022-09-02 02:25:38 +02:00
2023-01-12 01:03:10 +01:00
let sendnotif = true ;
let typedir = shared _consts . TypeNotifs . TYPEDIR _CIRCUITS ;
let typeid = 0 ;
let onlysave = false ;
let numuserincircuit = await User . countUsersInCircuit ( idapp , circuitname ) ;
2023-08-27 23:55:31 +02:00
const mycircuit = await Circuit . findOne ( { name : circuitname } ) . lean ( ) ;
2023-12-11 20:48:52 +01:00
if ( mycircuit && extrarec ) {
2023-06-20 01:07:57 +02:00
extrarec . fido _scoperto _default = mycircuit . fido _scoperto _default ;
extrarec . fido _scoperto _default _grp = mycircuit . fido _scoperto _default _grp ;
}
2022-09-02 02:25:38 +02:00
2023-01-12 01:03:10 +01:00
if ( cmd ) {
if ( cmd === shared _consts . CIRCUITCMD . SET ) {
if ( myreccircuit && myreccircuit . createdBy === usernameDest && numuserincircuit <= 1 ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _NEW _REC ;
} else {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _ACCEPTED ;
}
} else if ( cmd === shared _consts . CIRCUITCMD . REFUSE _REQ ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _REFUSED ;
} else if ( cmd === shared _consts . CIRCUITCMD . REMOVE _FROM _MYLIST ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _REMOVED ;
} else if ( cmd === shared _consts . CIRCUITCMD . REQ ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _REQUEST _TO _ENTER ;
// paramsObj.options = MessageOptions.Notify_OnlyToNotifinApp + MessageOptions.Notify_ByBotTelegram;
const myuserdata = await User . getUserShortDataByUsername ( idapp , username _action ) ;
2023-06-01 11:39:53 +02:00
telegrambot . askConfirmationUser ( idapp , shared _consts . CallFunz . RICHIESTA _FIDO , myuserdata , usernameDest , circuitname ,
2023-01-12 01:03:10 +01:00
myreccircuit . _id , '' , extrarec . groupname ) ;
onlysave = false ;
} else if ( cmd === shared _consts . CIRCUITCMD . ADDADMIN ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _ADDED _ADMIN ;
2023-06-01 11:39:53 +02:00
} else if ( cmd === shared _consts . CIRCUITCMD . SETFIDO ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _SETFIDO ;
2023-01-12 01:03:10 +01:00
} else if ( cmd === shared _consts . CIRCUITCMD . REMOVEADMIN ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _REMOVED _ADMIN ;
} else if ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _REQ ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _SENDCOINSREQ ;
} else if ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _REQ _SENT ) {
// Crea l'ID di Transazione
paramsObj . idTransaction = new ObjectId ( ) ;
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _SENDCOINSREQ _SENT ;
} else if ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _ACCEPT ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _COINS _ACCEPTED ;
} else if ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _ACCEPT _SENT ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _COINS _ACCEPTED _SENT ;
2024-07-23 12:25:10 +02:00
// } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) {
// typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED;
//} else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE_SENT) {
// typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED_SENT;
2022-09-03 13:06:58 +02:00
}
2022-09-02 02:25:38 +02:00
2023-01-12 01:03:10 +01:00
}
2023-01-03 16:51:32 +01:00
2023-01-12 01:03:10 +01:00
if ( sendnotif && typeid > 0 ) {
2023-02-01 16:36:10 +01:00
const groupDestoContoCom = groupDest ? groupDest : ( extrarec && extrarec . contoComDest ? extrarec . contoComDest : '' ) ;
2023-01-12 01:03:10 +01:00
// Check if is group:
2023-02-01 16:36:10 +01:00
if ( groupDestoContoCom && (
2023-01-21 19:02:19 +01:00
( cmd !== shared _consts . CIRCUITCMD . SENDCOINS _ACCEPT _SENT ) &&
( cmd !== shared _consts . CIRCUITCMD . SENDCOINS _REFUSE _SENT )
) ) {
2023-02-01 16:36:10 +01:00
let arrusers = await MyGroup . getListAdminsByGroupName ( idapp , groupDestoContoCom ) ;
if ( arrusers . length <= 0 )
arrusers = await Circuit . getListAdminsByCircuitPath ( idapp , groupDestoContoCom ) ;
2023-01-21 19:02:19 +01:00
let notiftoUpdate = '' ;
let findrecnotif = await SendNotif . findOne ( { _id : paramsObj . extrarec . notifId } ) . lean ( ) ;
notiftoUpdate = findrecnotif ? findrecnotif . extrarec . notifIdToUpdate : '' ;
if ( findrecnotif ) {
let arrrec = [ ] ;
if ( notiftoUpdate )
arrrec = await SendNotif . find ( { 'extrarec.notifIdToUpdate' : notiftoUpdate } ) ;
for ( let rec of arrrec ) {
paramsObj . usernameDest = rec . dest ;
2023-02-02 13:53:02 +01:00
paramsObj . sender = rec . sender ;
2023-01-21 19:02:19 +01:00
if ( ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _ACCEPT ) || ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _REFUSE ) ) {
try {
paramsObj . extrarec . notifId = rec . _id ;
} catch ( e ) {
}
}
ris = await SendNotif . createNewNotifToSingleUser ( req , null , paramsObj , onlysave , typedir , typeid ) ;
if ( ! ris ) {
2023-02-01 16:36:10 +01:00
console . error ( 'Errore createNewNotifToSingleUser! ' , paramsObj . usernameDest , "dest ->" , groupDestoContoCom )
2023-01-21 19:02:19 +01:00
} else {
arrris . push ( ris . _id ) ;
}
2023-01-03 16:51:32 +01:00
2023-01-21 19:02:19 +01:00
}
} else {
2023-01-03 16:51:32 +01:00
2023-01-21 19:02:19 +01:00
for ( let i = 0 ; i < arrusers . length ; i ++ ) {
paramsObj . usernameDest = arrusers [ i ] . username ;
2023-01-03 16:51:32 +01:00
2023-01-21 19:02:19 +01:00
ris = await SendNotif . createNewNotifToSingleUser ( req , null , paramsObj , onlysave , typedir , typeid ) ;
if ( ! ris ) {
2023-02-01 16:36:10 +01:00
console . error ( 'Errore createNewNotifToSingleUser! ' , paramsObj . usernameDest , "dest ->" , groupDestoContoCom )
2023-01-21 19:02:19 +01:00
} else {
arrris . push ( ris . _id ) ;
}
2023-01-12 01:03:10 +01:00
}
2023-01-21 19:02:19 +01:00
2023-01-03 16:51:32 +01:00
}
2023-01-12 01:03:10 +01:00
} else {
// CREATE NOTIFICATION IN TABLE SENDNOTIF
2023-01-21 19:02:19 +01:00
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 ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _COINS _ACCEPTED _SENT ;
} else if ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _REFUSE ) {
typeid = shared _consts . TypeNotifs . ID _CIRCUIT _COINS _REFUSED _SENT ;
}
let notiftoUpdate = '' ;
let findrecnotif = await SendNotif . findOne ( { _id : paramsObj . extrarec . notifId } ) . lean ( ) ;
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 ) {
2023-02-01 16:36:10 +01:00
console . error ( 'Errore createNewNotifToSingleUser! ' , paramsObj . usernameDest , "dest ->" , groupDestoContoCom )
2023-01-21 19:02:19 +01:00
}
}
}
}
}
2022-09-03 13:06:58 +02:00
}
2022-09-02 02:25:38 +02:00
}
2023-01-21 19:02:19 +01:00
return { recnotif : ris , arrris } ;
2022-09-03 13:06:58 +02:00
} catch ( e ) {
console . log ( e . message ) ;
2022-09-02 02:25:38 +02:00
}
} ,
2022-12-15 18:09:43 +01:00
sendNotificationByGroupname : async function ( idapp , usernameOrig , groupname , cmd , value , telegram , username _action ) {
2022-02-05 23:28:15 +01:00
2022-12-15 18:09:43 +01:00
const { MyGroup } = require ( '../models/mygroup' ) ;
const { User } = require ( '../models/user' ) ;
2022-02-05 23:28:15 +01:00
2022-12-15 18:09:43 +01:00
const group = await MyGroup . findOne ( { idapp , groupname } , { _id : 1 , admins : 1 , createdBy : 1 } ) . lean ( ) ;
2022-08-04 17:30:57 +02:00
if ( ! group )
return ;
2022-02-05 23:28:15 +01:00
2022-08-04 17:30:57 +02:00
let giainviato = false ;
2022-02-05 23:28:15 +01:00
2022-08-04 17:30:57 +02:00
try {
// SEND TO THE ADMINS THE NOTIFICATIONS
for ( const singleadmin of group . admins ) {
try {
if ( singleadmin . username ) {
if ( usernameOrig === singleadmin . username )
giainviato = true ;
2022-03-06 00:48:33 +01:00
2022-08-08 16:35:32 +02:00
await this . sendNotifGroupByUsername ( cmd , idapp , usernameOrig , singleadmin . username , username _action , groupname , group , true ) ;
2022-02-05 23:28:15 +01:00
}
2022-08-04 17:30:57 +02:00
} catch ( e ) {
console . error ( 'sendNotificationByGroupname' , e ) ;
2022-02-03 00:33:15 +01:00
}
}
2022-08-04 17:30:57 +02:00
if ( ! giainviato && ( cmd !== shared _consts . GROUPSCMD . REQGROUP ) ) {
// SEND TO THE USER THE NOTIFICATION
2022-09-02 02:25:38 +02:00
await this . sendNotifGroupByUsername ( cmd , idapp , usernameOrig , usernameOrig , username _action , groupname , null , false ) ;
2022-06-17 12:30:44 +02:00
}
2022-08-04 17:30:57 +02:00
} catch ( e ) {
console . error ( 'e' , e ) ;
2022-03-06 00:48:33 +01:00
}
2022-02-03 00:33:15 +01:00
} ,
2022-12-15 18:09:43 +01:00
sendNotificationByCircuit : async function ( idapp , usernameOrig , circuitname , cmd , value , telegram , username _action , extrarec ) {
2022-09-02 02:25:38 +02:00
2022-12-15 18:09:43 +01:00
const { Circuit } = require ( '../models/circuit' ) ;
2023-01-21 19:02:19 +01:00
const { SendNotif } = require ( '../models/sendnotif' ) ;
2022-09-02 02:25:38 +02:00
2022-12-15 18:09:43 +01:00
const circuit = await Circuit . findOne ( { idapp , name : circuitname } , { _id : 1 , admins : 1 , createdBy : 1 , path : 1 } ) . lean ( ) ;
2022-09-02 02:25:38 +02:00
if ( ! circuit )
return ;
let giainviato = false ;
try {
// SEND TO THE ADMINS THE NOTIFICATIONS
2022-09-11 11:45:33 +02:00
let ris = false ;
let inviato = false ;
2023-10-21 15:27:53 +02:00
let arrris = [ ] ;
2022-09-11 11:45:33 +02:00
2022-09-14 11:32:04 +02:00
if ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _REQ || cmd === shared _consts . CIRCUITCMD . SENDCOINS _ACCEPT || cmd ===
2022-12-15 18:09:43 +01:00
shared _consts . CIRCUITCMD . SENDCOINS _REFUSE ) {
2022-09-14 11:32:04 +02:00
2023-01-21 19:02:19 +01:00
groupOrig = extrarec . grouporig
2022-09-14 11:32:04 +02:00
let recnotif = null ;
2023-01-21 19:02:19 +01:00
2022-09-14 11:32:04 +02:00
if ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _REQ ) {
2023-01-21 19:02:19 +01:00
// 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 ,
2022-12-15 18:09:43 +01:00
username _action , circuitname , circuit . path , null ,
false , '' , extrarec ) ;
2023-01-21 19:02:19 +01:00
if ( res ) {
recnotif = res . recnotif ;
arrris = res . arrris ;
}
2022-09-14 11:32:04 +02:00
} else if ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _ACCEPT ) {
2023-01-21 19:02:19 +01:00
// 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 ,
2022-12-15 18:09:43 +01:00
username _action , circuitname , circuit . path , null ,
false , '' , extrarec ) ;
2022-09-14 11:32:04 +02:00
} else if ( cmd === shared _consts . CIRCUITCMD . SENDCOINS _REFUSE ) {
2023-01-21 19:02:19 +01:00
await this . sendNotifCircuitByUsername ( shared _consts . CIRCUITCMD . SENDCOINS _REFUSE _SENT , idapp , extrarec . dest , extrarec . groupdest , usernameOrig , groupOrig ,
2022-12-15 18:09:43 +01:00
username _action , circuitname , circuit . path , null ,
false , '' , extrarec ) ;
2022-09-14 11:32:04 +02:00
}
if ( recnotif )
extrarec . notifIdToUpdate = recnotif . _id ;
2023-01-21 19:02:19 +01:00
if ( arrris )
extrarec . arrnotifIdToUpdate = arrris ;
2023-01-12 01:03:10 +01:00
2023-01-21 19:02:19 +01:00
let usernametoOrigUse = usernameOrig
if ( extrarec . groupname ) {
usernametoOrigUse = ''
}
ris = await this . sendNotifCircuitByUsername ( cmd , idapp , usernametoOrigUse , groupOrig , extrarec . dest , extrarec . groupdest , username _action , circuitname , circuit . path ,
2023-01-12 01:03:10 +01:00
null , false , '' , extrarec ) ;
2022-09-03 13:06:58 +02:00
2023-01-21 19:02:19 +01:00
if ( arrris && ris && ris . recnotif ) {
for ( const rec of arrris ) {
let obj = {
'extrarec.notifIdToUpdate' : ris . recnotif . _id
} ;
await SendNotif . findOneAndUpdate ( { _id : rec . _id } , { $set : obj } , { new : false } ) ;
}
}
2022-09-14 11:32:04 +02:00
extrarec . notifIdToUpdate = '' ;
2023-01-21 19:02:19 +01:00
if ( ris . recnotif )
2022-09-11 11:45:33 +02:00
inviato = true ;
// ++Todo: Inviare anche agli Admin ?!
2022-09-03 13:06:58 +02:00
} else {
2023-01-21 19:02:19 +01:00
const groupOrig = '' //++Todo: extrarec.groupOrig
2022-09-03 13:06:58 +02:00
for ( const singleadmin of circuit . admins ) {
try {
if ( singleadmin . username ) {
if ( usernameOrig === singleadmin . username )
giainviato = true ;
2023-01-21 19:02:19 +01:00
await this . sendNotifCircuitByUsername ( cmd , idapp , usernameOrig , groupOrig , singleadmin . username , '' , username _action , circuitname ,
2022-12-15 18:09:43 +01:00
circuit . path , circuit , true , '' , extrarec ) ;
2022-09-11 11:45:33 +02:00
inviato = true ;
2022-09-03 13:06:58 +02:00
}
} catch ( e ) {
console . error ( 'sendNotificationByCircuit' , e ) ;
2022-09-02 02:25:38 +02:00
}
}
2022-09-03 13:06:58 +02:00
if ( ! giainviato && cmd !== shared _consts . CIRCUITCMD . REQ ) {
// SEND TO THE USER DEST THE NOTIFICATION
2023-01-21 19:02:19 +01:00
ris = await this . sendNotifCircuitByUsername ( cmd , idapp , usernameOrig , groupOrig , usernameOrig , '' , username _action , circuitname , circuit . path ,
2023-12-11 20:48:52 +01:00
null , false , '' , extrarec ) ;
if ( ris && ris . recnotif )
2022-09-11 11:45:33 +02:00
inviato = true ;
2022-09-03 13:06:58 +02:00
}
2022-09-02 02:25:38 +02:00
}
2023-10-21 15:27:53 +02:00
if ( inviato ) {
if ( arrris && arrris . length > 0 ) {
for ( const notif of arrris ) {
await SendNotif . updatePendingTransactions ( notif ) ;
}
} else {
if ( ris ) {
await SendNotif . updatePendingTransactions ( ris . recnotif ) ;
}
}
}
2023-01-21 19:02:19 +01:00
return { ris : ris . recnotif , inviato } ;
2022-09-03 13:06:58 +02:00
2022-09-02 02:25:38 +02:00
} catch ( e ) {
console . error ( 'sendNotificationByCircuit: ' , e ) ;
2022-12-15 18:09:43 +01:00
return { ris : null , inviato : false } ;
2022-09-02 02:25:38 +02:00
}
} ,
2019-02-27 02:59:02 +01:00
// **********************
// SORT WITH PREV_ID
// **********************
2021-02-03 01:33:30 +01:00
/ * m a p S o r t : f u n c t i o n ( l i n k e d L i s t ) {
2019-04-20 13:59:07 +02:00
let sortedList = [ ] ;
let remainingList = [ ] ;
2019-02-27 02:59:02 +01:00
var map = new Map ( ) ;
var currentId = null ;
// console.log('linkedList', linkedList);
// index the linked list by previous_item_id
for ( var i = 0 ; i < linkedList . length ; i ++ ) {
var item = linkedList [ i ] ;
if ( item . id _prev === server _constants . LIST _START ) {
// first item
2021-02-03 01:33:30 +01:00
currentId = item . _id . toString ( ) ;
2019-02-27 02:59:02 +01:00
// console.log('currentId', currentId);
sortedList . push ( item ) ;
} else {
2021-02-03 01:33:30 +01:00
map . set ( item . id _prev . toString ( ) , i ) ;
2019-02-27 02:59:02 +01:00
}
}
2019-04-20 13:59:07 +02:00
let conta = 0 ;
while ( conta < linkedList . length ) {
2019-02-27 02:59:02 +01:00
// get the item with a previous item ID referencing the current item
var nextItem = linkedList [ map . get ( currentId ) ] ;
2019-04-13 03:04:49 +02:00
if ( nextItem === undefined ) {
2019-04-20 13:59:07 +02:00
} else {
sortedList . push ( nextItem ) ;
2021-02-03 01:33:30 +01:00
currentId = nextItem . _id . toString ( ) ;
2019-04-13 03:04:49 +02:00
}
2019-04-20 13:59:07 +02:00
conta ++ ;
2019-02-27 02:59:02 +01:00
}
2019-04-20 13:59:07 +02:00
if ( linkedList . length > sortedList . length ) {
// If are not in the list, I'll put at the bottom of the list
2019-04-22 01:43:58 +02:00
// console.log('ATTENZIONE !!! ', sortedList.length, linkedList.length);
2019-04-20 13:59:07 +02:00
for ( const itemlinked of linkedList ) {
const elemtrov = sortedList . find ( ( item ) => item . _id === itemlinked . _id ) ;
if ( elemtrov === undefined ) {
sortedList . push ( itemlinked ) ;
}
}
2019-04-13 03:04:49 +02:00
}
2019-02-27 02:59:02 +01:00
// console.log('DOPO sortedList', sortedList);
return sortedList ;
2019-10-05 20:01:56 +02:00
} ,
2021-02-03 01:33:30 +01:00
* /
2024-04-25 23:26:16 +02:00
async sendNotifToCircuitsAdmin ( idapp , circuit , alsotelegram , title , msg , tag = '' ) {
const { User } = require ( '../models/user' ) ;
const telegrambot = require ( '../telegram/telegrambot' ) ;
if ( ! circuit || ! circuit . admins ) {
console . error ( 'sendNotifToCircuitsAdmin: missing circuit or circuit.admins' , circuit ) ;
return ;
}
for ( const singleadmin of circuit . admins ) {
try {
if ( singleadmin && singleadmin . username ) {
const user = await User . getUserShortDataByUsername ( idapp , singleadmin . username ) ;
if ( user ) {
if ( alsotelegram ) {
if ( ! user . profile || ! user . profile . teleg _id ) {
console . error ( 'sendNotifToCircuitsAdmin: missing user.profile.teleg_id' , user ) ;
} else {
telegrambot . local _sendMsgTelegramByIdTelegram ( idapp , user . profile . teleg _id , title + ' ' + msg ) ;
}
}
if ( ! user . _id ) {
console . error ( 'sendNotifToCircuitsAdmin: missing user._id' , user ) ;
} else {
await this . sendNotificationToUser ( user . _id , title , msg , '/' , '' , tag , [ ] ) ;
}
}
}
} catch ( e ) {
console . error ( 'sendNotifToCircuitsAdmin' , e ) ;
}
}
} ,
2023-08-27 23:55:31 +02:00
sendNotifToAdmin ( idapp , alsotelegram , title , msg , tag = '' ) {
try {
const { User } = require ( '../models/user' ) ;
2021-02-03 01:33:30 +01:00
2023-08-27 23:55:31 +02:00
const queryadmins = { username : 'paoloar77' , idapp } ;
2021-03-17 02:24:11 +01:00
2023-08-27 23:55:31 +02:00
if ( idapp === 0 )
idapp = '13' ;
2021-10-05 15:39:44 +02:00
2023-08-27 23:55:31 +02:00
User . find ( queryadmins ) . then ( async ( arrusers ) => {
if ( arrusers !== null ) {
for ( const user of arrusers ) {
if ( alsotelegram ) {
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
}
} ) ;
}
2021-03-17 02:24:11 +01:00
}
2023-08-27 23:55:31 +02:00
} ) ;
} catch ( e ) {
console . error ( e ) ;
}
2021-03-17 02:24:11 +01:00
} ,
2019-10-05 20:01:56 +02:00
2019-11-05 23:53:39 +01:00
checkUserOk ( userpassed , userauth , res ) {
2023-06-18 22:29:06 +02:00
// this.mylog('checkUserOk', userpassed, userauth);
2019-10-05 20:01:56 +02:00
if ( String ( userpassed ) !== String ( userauth ) ) {
// I'm trying to write something not mine!
2023-01-03 16:51:32 +01:00
this . mylog ( 'I\'m trying to write something not mine!: userId = ' , userpassed , 'req.user._id' , userauth ) ;
2022-07-26 15:46:39 +02:00
if ( ! res ) {
return {
exit : true ,
ret : false ,
2022-08-04 17:30:57 +02:00
} ;
2022-07-26 15:46:39 +02:00
} else {
return {
exit : true ,
2023-04-17 00:11:36 +02:00
ret : false ,
// ret: res.status(404).
// send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }),
2022-07-26 15:46:39 +02:00
} ;
}
2019-10-05 20:01:56 +02:00
} else {
2022-12-15 18:09:43 +01:00
return { exit : false , ret : false } ;
2019-10-05 20:01:56 +02:00
}
} ,
2022-09-18 20:17:24 +02:00
ConvertHTMLToPlainText ( strHTML ) {
2022-10-29 12:37:50 +02:00
if ( strHTML )
return strHTML . replace ( /<[^>]+>/g , '' ) ;
return '' ;
2022-09-18 20:17:24 +02:00
} ,
2023-03-21 18:11:56 +01:00
convertSpaces _ToUScore ( mystr ) {
if ( mystr )
return mystr . replace ( /\s+/g , '_' ) ;
return '' ;
} ,
2019-10-05 20:01:56 +02:00
convertHTMLtoText ( myhtml ) {
let msg = myhtml ;
2022-10-29 12:37:50 +02:00
if ( msg ) {
msg = msg . replace ( '"' , '"' ) ;
msg = msg . replace ( /<strong>/g , '' ) ;
msg = msg . replace ( /<\/strong>/g , '' ) ;
msg = msg . replace ( /<em>/g , '' ) ;
msg = msg . replace ( /<\/em>/g , '' ) ;
msg = msg . replace ( '>' , '>' ) ;
msg = msg . replace ( '<' , '<' ) ;
msg = msg . replace ( '&' , '&' ) ;
msg = msg . replace ( '<br>' , '\n' ) ;
}
2019-10-05 20:01:56 +02:00
2021-10-05 15:39:44 +02:00
return msg ;
2019-10-05 20:01:56 +02:00
} ,
2023-10-01 01:24:47 +02:00
htmlToTelegramText ( html ) {
try {
const withMarkdown = html
. replace ( /<strong>(.*?)<\/strong>/g , '*$1*' )
. replace ( /<b>(.*?)<\/b>/g , '*$1*' )
. replace ( /<em>(.*?)<\/em>/g , '_$1_' )
. replace ( /<u>(.*?)<\/u>/g , '__$1__' ) ;
// Remove other HTML tags
const plainText = withMarkdown . replace ( /<[^>]*>/g , '' ) ;
// Replace HTML entities with their equivalent Markdown or plain text representations
const replacements = [
{ pattern : /&/g , replacement : '&' } ,
{ pattern : /</g , replacement : '<' } ,
{ pattern : />/g , replacement : '>' } ,
{ pattern : /"/g , replacement : '"' } ,
{ pattern : /'/g , replacement : "'" } ,
] ;
let telegramText = plainText ;
replacements . forEach ( ( replacement ) => {
telegramText = telegramText . replace ( replacement . pattern , replacement . replacement ) ;
} ) ;
return telegramText ;
} catch ( e ) {
console . error ( e ) ;
} ;
} ,
2023-10-03 00:44:24 +02:00
htmlToTelegramText ( html ) {
try {
const withMarkdown = html
. replace ( /<strong>(.*?)<\/strong>/g , '*$1*' )
. replace ( /<b>(.*?)<\/b>/g , '*$1*' )
. replace ( /<em>(.*?)<\/em>/g , '_$1_' )
. replace ( /<u>(.*?)<\/u>/g , '__$1__' ) ;
// Remove other HTML tags
const plainText = withMarkdown . replace ( /<[^>]*>/g , '' ) ;
// Replace HTML entities with their equivalent Markdown or plain text representations
const replacements = [
{ pattern : /&/g , replacement : '&' } ,
{ pattern : /</g , replacement : '<' } ,
{ pattern : />/g , replacement : '>' } ,
{ pattern : /"/g , replacement : '"' } ,
{ pattern : /'/g , replacement : "'" } ,
] ;
let telegramText = plainText ;
replacements . forEach ( ( replacement ) => {
telegramText = telegramText . replace ( replacement . pattern , replacement . replacement ) ;
} ) ;
return telegramText ;
} catch ( e ) {
console . error ( e ) ;
} ;
} ,
2019-11-06 22:29:29 +01:00
convertTexttoHtml ( myhtml ) {
// let msg = myhtml;
// msg = msg.replace('\n', '<br>');
// return msg
return myhtml ;
} ,
2019-10-05 20:01:56 +02:00
removeSpecialCharForEmail ( myhtml ) {
let msg = myhtml ;
2024-09-30 14:50:19 +02:00
try {
if ( msg )
msg = msg . replace ( /"/g , '\'' ) ;
} catch ( e ) {
return msg ;
}
2019-10-05 20:01:56 +02:00
2021-10-05 15:39:44 +02:00
return msg ;
2019-10-05 20:01:56 +02:00
} ,
2022-12-15 18:09:43 +01:00
getNomeAppByIdApp : function ( idapp ) {
2019-10-05 20:01:56 +02:00
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( item => item . idapp === idapp ) ;
2019-10-05 20:01:56 +02:00
if ( myapp )
2022-01-07 01:18:01 +01:00
return ( ( process . env . NODE _ENV === 'test' ) ? 'Test: ' : '' ) + myapp . name ;
2019-10-05 20:01:56 +02:00
else
return '' ;
} ,
2022-12-15 18:09:43 +01:00
getTimeExpReg : async function ( idapp , username ) {
var { User } = require ( '../models/user' ) ;
2022-11-02 22:32:54 +01:00
return await User . createNewReqRegistrationGetLink ( idapp , username ) ;
} ,
2022-12-15 18:09:43 +01:00
getLinkRegByIdAppAndMsgStrutt : function ( idapp , msg , rec ) {
2022-05-04 00:26:12 +02:00
let myapp = this . getHostByIdApp ( idapp ) ;
if ( myapp ) {
2023-02-20 02:19:53 +01:00
myapp += '/registrati/' + rec . aportador _solidario + '/' + msg . from . username + '/' + msg . from . id + '/' + rec . regexpire ;
2022-05-04 00:26:12 +02:00
}
return myapp ;
} ,
2022-12-15 18:09:43 +01:00
getHostByIdApp : function ( idapp ) {
2019-10-16 15:28:49 +02:00
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( item => item . idapp === idapp ) ;
2019-10-16 15:28:49 +02:00
if ( myapp ) {
2022-01-14 23:54:33 +01:00
let siteport = ( myapp . portapp && myapp . portapp !== '0' ) ? ( ':' +
2022-12-15 18:09:43 +01:00
myapp . portapp ) : '' ;
2022-01-07 01:18:01 +01:00
if ( process . env . NODE _ENV === 'test' )
return myapp . host _test + siteport ;
else
return myapp . host + siteport ;
2019-10-16 15:28:49 +02:00
} else
return '' ;
} ,
2022-12-15 18:09:43 +01:00
getLinkUserProfile : function ( idapp , username ) {
2022-08-04 17:30:57 +02:00
return this . getHostByIdApp ( idapp ) + '/my/' + username ;
2022-03-02 20:18:29 +01:00
} ,
2022-12-15 18:09:43 +01:00
getLinkUserTelegram : async function ( idapp , username , myuser ) {
var { User } = require ( '../models/user' ) ;
2022-09-18 20:17:24 +02:00
let u _tg = '' ;
if ( myuser )
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 '' ;
} ,
2022-12-15 18:09:43 +01:00
getLinkEditUserProfile : function ( idapp ) {
2022-08-04 17:30:57 +02:00
return this . getHostByIdApp ( idapp ) + '/editprofile' ;
2022-03-02 20:18:29 +01:00
} ,
2022-12-15 18:09:43 +01:00
getConfSiteOptionEnabledByIdApp : function ( idapp , option ) {
2022-02-27 16:56:02 +01:00
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( item => item . idapp === idapp ) ;
2022-02-27 16:56:02 +01:00
if ( myapp ) {
if ( myapp . hasOwnProperty ( 'confsite' ) ) {
if ( myapp . confsite . hasOwnProperty ( 'options' ) ) {
return this . isBitActive ( myapp . confsite . options , option ) ;
}
}
}
return false ;
} ,
2024-04-09 21:56:50 +02:00
getEnableTokenExpiredByIdApp : function ( idapp ) {
const myapp = this . MYAPPS . find ( item => item . idapp === idapp ) ;
2024-04-19 15:44:34 +02:00
if ( myapp && myapp . confpages && myapp . confpages . hasOwnProperty ( 'enableTokenExpired' ) ) {
2024-04-09 21:56:50 +02:00
return myapp . confpages . enableTokenExpired ;
}
return false ;
} ,
2022-12-15 18:09:43 +01:00
getConfParamSiteByIdApp : function ( idapp , field ) {
2022-02-27 16:56:02 +01:00
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( item => item . idapp === idapp ) ;
2022-02-27 16:56:02 +01:00
if ( myapp ) {
if ( myapp . hasOwnProperty ( 'confsite' ) ) {
if ( myapp . confsite . hasOwnProperty ( field ) ) {
return myapp . confsite [ field ] ;
}
}
}
return false ;
} ,
2022-12-15 18:09:43 +01:00
isAbilitaNave : function ( idapp ) {
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( item => item . idapp === idapp ) ;
2020-03-10 21:44:14 +01:00
return myapp . abilitanave ;
} ,
2022-12-15 18:09:43 +01:00
removeLastSlashFromPath : function ( myString ) {
2022-11-17 08:09:48 +01:00
let regex = /\/$/ ;
2023-12-28 23:53:11 +01:00
let result = myString ;
try {
if ( myString )
result = myString . replace ( regex , "" ) ;
} catch ( e ) {
return myString ;
}
2022-11-17 08:09:48 +01:00
return result ;
} ,
2022-12-15 18:09:43 +01:00
getdirByIdApp : function ( idapp , dirmain = false ) {
2019-12-27 12:41:39 +01:00
2022-03-01 23:50:58 +01:00
let mypath = '' ;
2019-12-27 12:41:39 +01:00
const myapp =
2022-12-15 18:09:43 +01:00
this . MYAPPS . find ( item => item . idapp === idapp ) ;
2019-12-27 12:41:39 +01:00
if ( myapp ) {
2022-01-07 01:18:01 +01:00
if ( process . env . NODE _ENV === 'test' )
2024-09-06 19:57:09 +02:00
mypath = ( myapp && myapp . dir _test ) ? myapp . dir _test : '' ;
2022-01-07 01:18:01 +01:00
else
2024-09-06 19:57:09 +02:00
mypath = ( myapp && myapp . dir ) ? myapp . dir : '' ;
2022-03-01 23:50:58 +01:00
if ( dirmain ) {
2022-03-02 20:18:29 +01:00
if ( ! this . sulServer ( ) ) {
2022-09-19 19:40:30 +02:00
mypath += 'public' ;
2022-03-01 23:50:58 +01:00
}
}
}
2022-11-17 08:09:48 +01:00
return this . removeLastSlashFromPath ( mypath ) ;
2019-12-27 12:41:39 +01:00
} ,
2022-12-15 18:09:43 +01:00
getAdminEmailByIdApp : function ( idapp ) {
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
2019-10-05 20:01:56 +02:00
if ( myapp )
return myapp . adminemail ;
else
return '' ;
} ,
2022-12-15 18:09:43 +01:00
getreplyToEmailByIdApp : function ( idapp ) {
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
2019-10-16 15:28:49 +02:00
if ( myapp )
return myapp . replyTo ;
else
return '' ;
} ,
2022-12-15 18:09:43 +01:00
getpathregByIdApp : function ( idapp , lang ) {
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
2021-09-22 01:13:41 +02:00
if ( myapp ) {
const addstr = myapp . pathreg _add ? myapp . pathreg _add : '' ;
return 'registration' + addstr + '/' + lang ;
} else {
return 'registration' + '/' + lang ;
}
2020-02-07 22:08:46 +01:00
} ,
2024-09-12 14:49:00 +02:00
getparamSiteTableByIdApp : function ( idapp , param ) {
const myapp = this . MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
return myapp && param ? myapp [ param ] : '' ;
} ,
2022-12-15 18:09:43 +01:00
getAskToVerifyReg : function ( idapp ) {
2022-05-04 00:26:12 +02:00
return this . getConfSiteOptionEnabledByIdApp ( idapp , shared _consts . ConfSite . Need _Aportador _On _DataReg _To _Verify _Reg ) ;
2022-01-07 01:18:01 +01:00
} ,
2024-08-29 23:30:58 +02:00
getidMyGroupBySite : function ( idapp ) {
2024-09-12 14:49:00 +02:00
return this . getparamSiteTableByIdApp ( idapp , 'idMyGroup' ) ;
2024-08-29 23:30:58 +02:00
} ,
2019-10-16 15:28:49 +02:00
isManagAndAdminDifferent ( idapp ) {
2019-10-20 01:21:54 +02:00
const manag = this . getManagerEmailByIdApp ( idapp ) ;
return ( manag !== this . getAdminEmailByIdApp ( idapp ) ) && ( manag !== '' ) ;
2019-10-16 15:28:49 +02:00
} ,
2022-12-15 18:09:43 +01:00
getManagerEmailByIdApp : function ( idapp ) {
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
2019-10-16 15:28:49 +02:00
if ( myapp )
2021-04-30 01:31:12 +02:00
return ! ! myapp . manageremail ? myapp . manageremail : '' ;
2019-10-16 15:28:49 +02:00
else
return '' ;
} ,
2022-12-15 18:09:43 +01:00
getEmailByIdApp : function ( idapp ) {
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
2021-10-05 15:39:44 +02:00
return ( myapp ) ? myapp . email _from : '' ;
2020-01-03 01:52:49 +01:00
} ,
2022-12-15 18:09:43 +01:00
getPwdByIdApp : function ( idapp ) {
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
2021-10-05 15:39:44 +02:00
return ( myapp ) ? this . decryptdata ( myapp . email _pwd ) : '' ;
2020-01-03 01:52:49 +01:00
} ,
2023-12-09 19:38:23 +01:00
2022-12-15 18:09:43 +01:00
getTelegramBotNameByIdApp : function ( idapp ) {
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
2023-12-17 16:20:44 +01:00
if ( process . env . NODE _ENV === 'test' || process . env . NODE _ENV === 'development' )
2022-01-07 01:18:01 +01:00
return ( myapp ) ? myapp . telegram _bot _name _test : '' ;
else
return ( myapp ) ? myapp . telegram _bot _name : '' ;
2020-01-03 01:52:49 +01:00
} ,
2022-12-15 18:09:43 +01:00
getTelegramSupportChat : function ( idapp ) {
2022-02-25 17:24:31 +01:00
try {
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
2022-02-25 17:24:31 +01:00
return ( myapp && myapp . telegram _support _chat )
2022-12-15 18:09:43 +01:00
? myapp . telegram _support _chat
: '' ;
2022-03-01 23:50:58 +01:00
} catch ( e ) {
2022-02-25 17:24:31 +01:00
return '' ;
}
} ,
2022-12-15 18:09:43 +01:00
getTelegramKeyByIdApp : function ( idapp ) {
2022-07-23 17:48:33 +02:00
const myapp = this . MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
2023-12-17 16:20:44 +01:00
if ( process . env . NODE _ENV === 'test' || process . env . NODE _ENV === 'development' )
2022-01-07 01:18:01 +01:00
return ( myapp ) ? myapp . telegram _key _test : '' ;
else
return ( myapp ) ? myapp . telegram _key : '' ;
2020-01-03 01:52:49 +01:00
} ,
2023-12-17 16:20:44 +01:00
getArrTelegramFromSite : function ( ) {
const myapp = this . MYAPPS ;
let arrteleg = [ ]
for ( const site of myapp ) {
if ( site . active ) {
if ( process . env . NODE _ENV === 'test' ) {
2024-02-06 20:12:54 +01:00
if ( site . telegram _bot _name _test )
arrteleg . push ( site . idapp )
2023-12-17 16:20:44 +01:00
} else {
2024-02-06 20:12:54 +01:00
if ( site . telegram _bot _name )
arrteleg . push ( site . idapp )
2023-12-17 16:20:44 +01:00
}
}
}
return arrteleg ;
} ,
2022-12-15 18:09:43 +01:00
getLookupPipeLine ( params , proj ) {
let myquery = [
{
$lookup : {
from : params . lk _tab ,
let : { username : '$' + params . lk _LF , idapp : params . idapp } ,
pipeline : [
{
$match :
{
$expr :
{
$and :
[
2023-01-03 16:51:32 +01:00
{ $eq : [ '$' + params . lk _FF , '$$' + params . lk _FF ] } ,
2022-12-15 18:09:43 +01:00
{ $eq : [ '$idapp' , '$$idapp' ] } ,
] ,
} ,
} ,
} ,
] ,
as : params . lk _as ,
} ,
} ,
{ $project : proj } ,
] ;
return myquery ;
} ,
2023-04-07 02:45:21 +02:00
getNumTabByTable ( table ) {
const myrec = shared _consts . MYTABS . find ( ( rec ) => rec . table === table )
return myrec ? myrec . id : - 1
} ,
2023-04-12 15:37:54 +02:00
getTableByNumTab ( numtab ) {
const myrec = shared _consts . MYTABS . find ( ( rec ) => rec . id === numtab )
return myrec ? myrec . table : ''
} ,
2023-02-16 20:13:38 +01:00
getGroupnameLookupPipeLine ( params , proj ) {
let myquery = [
{
$lookup : {
from : params . lk _tab ,
let : { groupname : '$' + params . lk _LF , idapp : params . idapp } ,
pipeline : [
{
$match :
{
$expr :
{
$and :
[
{ $eq : [ '$' + params . lk _FF , '$$' + params . lk _FF ] } ,
{ $eq : [ '$idapp' , '$$idapp' ] } ,
] ,
} ,
} ,
} ,
] ,
as : params . lk _as ,
} ,
} ,
{ $project : proj } ,
] ;
return myquery ;
} ,
2023-09-27 18:38:57 +02:00
getLookupStandardPipeline : function ( params , num ) {
const query = [ ] ;
if ( ! params )
return ;
query . push (
{
$lookup : {
from : params . lk _tab ,
let : { searchId : { $toObjectId : "$" + params . lk _LF } } ,
pipeline : [
{
$match : {
$expr : {
$and : [
{ $eq : [ "$" + params . lk _FF , "$$searchId" ] } ,
] ,
} ,
} ,
} ,
{
$project : params . lk _proj
} ,
] ,
as : params . lk _as + num ,
} ,
} ,
{
$replaceRoot : {
newRoot : {
$mergeObjects : [
{
$arrayElemAt : [
'$' + params . lk _as + num , 0 ] ,
} , '$$ROOT' ] ,
} ,
} ,
}
)
return query ;
} ,
2024-05-09 23:36:46 +02:00
sanitizzaHtml ( html ) {
try {
return sanitizeHtml ( html ) ;
} catch ( e ) {
return html
}
} ,
sanitizzaLookup : function ( str ) {
return str ;
} ,
2024-03-26 18:11:19 +01:00
sanitizzaProjection : function ( mioproj ) {
// mioproj = {valore: '$password'};
const COL _TO _REMOVE = [ '$password' , '$tokens' , '$tokens.token' , 'ipaddr' ] ;
for ( let chiave in mioproj ) {
// Elimina questa richiesta della password !
if ( COL _TO _REMOVE . includes ( mioproj [ chiave ] ) ) {
delete mioproj [ chiave ] ;
}
}
return mioproj ;
} ,
2023-04-07 02:45:21 +02:00
getLookup : function ( params , num , pass _proj , proj _add ) {
2022-01-14 23:54:33 +01:00
const query = [ ] ;
2021-12-21 01:27:45 +01:00
if ( ! params )
return ;
let mylkLF = params . lk _LF ;
if ( params . af _objId _tab ) {
2022-01-14 23:54:33 +01:00
const myobj = { } ;
2022-12-15 18:09:43 +01:00
myobj [ 'myId' + num ] = { '$toObjectId' : '$' + params . lk _LF } ;
2023-04-12 15:37:54 +02:00
if ( params . lk _tab === 'users' ) {
myobj . namecomplete = {
$concat : [
{ $toLower : "$name" } ,
{ $toLower : "$surname" } ,
{ $toLower : "$username" } ,
] ,
} ;
}
2021-12-21 01:27:45 +01:00
query . push (
2022-12-15 18:09:43 +01:00
{ '$addFields' : myobj } ,
2021-12-21 01:27:45 +01:00
) ;
mylkLF = 'myId' + num ;
} else {
}
if ( params . lk _tab ) {
2022-01-14 23:54:33 +01:00
let proj = params . lk _proj ;
2024-03-26 18:11:19 +01:00
proj = this . sanitizzaProjection ( proj ) ;
2021-12-21 01:27:45 +01:00
if ( ! ! pass _proj ) {
2022-01-14 23:54:33 +01:00
proj = pass _proj ;
2021-12-21 01:27:45 +01:00
}
2023-04-07 02:45:21 +02:00
proj = Object . assign ( { } , proj , proj _add ) ;
2021-12-21 01:27:45 +01:00
query . push (
2022-12-15 18:09:43 +01:00
{
$lookup : {
from : params . lk _tab ,
localField : mylkLF , // field in my collection
foreignField : params . lk _FF , // field in the 'from' collection
as : params . lk _as ,
2021-12-21 01:27:45 +01:00
} ,
2023-04-17 00:11:36 +02:00
} ) ;
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' ] ,
} ,
2021-12-21 01:27:45 +01:00
} ,
2023-04-17 00:11:36 +02:00
} ) ;
}
query . push (
2022-12-15 18:09:43 +01:00
{ $project : proj } ,
2021-12-21 01:27:45 +01:00
) ;
}
return query ;
} ,
2022-12-15 18:09:43 +01:00
getFilterParam : function ( filter , fieldsearch ) {
2022-02-12 02:20:07 +01:00
let myregexp = { } ;
myregexp = new RegExp ( filter . trim ( ) . replace ( ' ' , '|' ) , 'ig' ) ;
let query = [ ] ;
const myfilters = [ ] ;
2022-02-24 19:13:20 +01:00
for ( const rec of fieldsearch ) {
2022-02-12 02:20:07 +01:00
let data = { } ;
if ( rec . type === this . FieldType . exact ) {
data [ rec . field ] = filter . trim ( ) ;
} else if ( rec . type === this . FieldType . string ) {
data [ rec . field ] = myregexp ;
2024-02-28 17:04:28 +01:00
if ( rec . field === 'profile.username_telegram' ) {
myregexp = new RegExp ( this . rimuoviAtPrimoCarattere ( filter ) . trim ( ) . replace ( ' ' , '|' ) , 'ig' ) ;
data [ rec . field ] = myregexp
}
2022-02-12 02:20:07 +01:00
} else if ( ( rec . type === this . FieldType . number ) ||
2022-12-15 18:09:43 +01:00
( rec . type === this . FieldType . hours ) ) {
2022-02-12 02:20:07 +01:00
data [ rec . field ] = parseFloat ( filter . trim ( ) ) ;
}
if ( data )
myfilters . push ( data ) ;
}
if ( myfilters . length > 0 ) {
query = [
2022-12-15 18:09:43 +01:00
{ $match : { $or : myfilters } } ,
2022-02-12 02:20:07 +01:00
] ;
}
return query ;
} ,
2022-12-15 18:09:43 +01:00
addQueryIdMatch : function ( params ) {
2022-09-02 02:25:38 +02:00
myquery = { } ;
2022-09-14 11:32:04 +02:00
if ( shared _consts . TABLES _ID _NUMBER . includes ( params . table ) || shared _consts . TABLES _ID _STRING . includes ( params . table ) ) {
2022-09-02 02:25:38 +02:00
myquery = {
$match : {
$expr : {
$eq : [ '$_id' , params . myid ] ,
} ,
} ,
} ;
2022-09-03 13:06:58 +02:00
} else if ( shared _consts . TABLES _NUM _AS _ID _NUMBER . includes ( params . table ) ) {
myquery = {
$match : {
$expr : {
$eq : [ '$Num' , params . myid ] ,
} ,
} ,
} ;
2022-09-02 02:25:38 +02:00
} else {
myquery = {
$match : {
$expr : {
$eq : [ '$_id' , mongoose . Types . ObjectId ( params . myid ) ] ,
} ,
} ,
2022-09-03 13:06:58 +02:00
} ;
2022-09-02 02:25:38 +02:00
}
return myquery ;
} ,
2024-02-19 18:51:10 +01:00
contieneIdStatusSkill ( filtersearch ) {
for ( let i = 0 ; i < filtersearch . length ; i ++ ) {
const obj = filtersearch [ i ] ;
if ( obj . $or ) {
for ( let j = 0 ; j < obj . $or . length ; j ++ ) {
const condition = obj . $or [ j ] ;
if ( condition . idStatusSkill ) {
return true ;
}
}
}
}
return false ;
} ,
2023-04-07 02:45:21 +02:00
addNumFavoriteAndBookmarkToQuery ( idapp , numtab ) {
2023-06-01 11:39:53 +02:00
2023-10-01 01:24:47 +02:00
let query = [ ] ;
2023-09-27 18:38:57 +02:00
2023-06-01 11:39:53 +02:00
try {
2023-10-01 01:24:47 +02:00
/ *
2023-06-01 11:39:53 +02:00
query =
2023-09-27 18:38:57 +02:00
[
{
$lookup : {
from : "reactions" ,
let : {
tab : numtab ,
id : '$_id' ,
2023-06-01 11:39:53 +02:00
} ,
2023-09-27 18:38:57 +02:00
pipeline : [
{
$match : {
$expr : {
$and : [
{ $eq : [ '$idrec' , '$$id' ] } ,
{ $eq : [ '$tab' , numtab ] } ,
{ $eq : [ '$idapp' , idapp ] } ,
] ,
} ,
2023-06-01 11:39:53 +02:00
} ,
2023-04-07 02:45:21 +02:00
} ,
2023-09-27 18:38:57 +02:00
{
$group : {
_id : "$idrec" ,
numseen : {
$sum : {
$cond : {
if : { $ifNull : [ "$seen" , false ] } , // Check if the field exists and is not null
then : 1 , // Increment count by 1 if the field exists
else : 0 , // Otherwise, keep the count unchanged
}
}
} ,
numfav : {
$sum : {
$cond : {
if : { $ifNull : [ "$fav" , false ] } , // Check if the field exists and is not null
then : 1 , // Increment count by 1 if the field exists
else : 0 , // Otherwise, keep the count unchanged
}
}
} ,
numbook : {
$sum : {
$cond : {
if : { $ifNull : [ "$book" , false ] } , // Check if the field exists and is not null
then : 1 , // Increment count by 1 if the field exists
else : 0 , // Otherwise, keep the count unchanged
}
}
}
2023-06-01 11:39:53 +02:00
} ,
2023-04-07 02:45:21 +02:00
} ,
2023-09-27 18:38:57 +02:00
] ,
as : 'myreact' ,
} ,
} ,
{
2023-10-01 01:24:47 +02:00
$unwind : {
path : "$myreact" ,
preserveNullAndEmptyArrays : true ,
2023-09-27 18:38:57 +02:00
} ,
2023-10-01 01:24:47 +02:00
} ,
2023-09-27 18:38:57 +02:00
] ;
2023-04-17 00:11:36 +02:00
2023-10-01 01:24:47 +02:00
if ( true ) {
// RIMUOVI
// query = {};
}
2023-10-03 00:44:24 +02:00
if ( true ) {
// RIMUOVI
// query = {};
}
2023-09-27 18:38:57 +02:00
if ( Object . keys ( query ) . length > 0 ) {
const numtabbacheca = this . getNumTabByTable ( shared _consts . TABLES _MYBACHECAS ) ;
if ( numtab === numtabbacheca ) {
const queryadd = this . getQueryMyBacheca ( idapp ) ;
query = [ ... query , ... queryadd ] ;
}
2023-06-01 11:39:53 +02:00
}
2024-09-30 14:50:19 +02:00
const numtabbacheca = this . getNumTabByTable ( shared _consts . TABLES _MYBACHECAS ) ;
if ( numtab === numtabbacheca ) {
const queryadd = this . getQueryMyBacheca ( idapp ) ;
query = [ ... query , ... queryadd ] ;
}
2023-10-01 01:24:47 +02:00
* /
2023-04-07 02:45:21 +02:00
2023-06-01 11:39:53 +02:00
proj = {
2023-10-01 01:24:47 +02:00
numseen : 1 ,
numfav : 1 ,
numbook : 1 ,
numattend : 1 ,
2023-06-01 11:39:53 +02:00
} ;
} catch ( e ) {
console . error ( e ) ;
}
2023-04-07 02:45:21 +02:00
return { query , proj } ;
2023-06-01 11:39:53 +02:00
2023-04-07 02:45:21 +02:00
} ,
2023-06-01 11:39:53 +02:00
getQueryMyBacheca : function ( idapp ) {
2023-04-17 00:11:36 +02:00
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 ,
2024-09-30 14:50:19 +02:00
numpeopleDinnerShared : 1 ,
2023-04-17 00:11:36 +02:00
infoevent : 1 ,
msgbooking : 1 ,
booked : 1 ,
datebooked : 1 ,
userId : 1 ,
2024-09-30 14:50:19 +02:00
idapp : 1 ,
2023-04-17 00:11:36 +02:00
}
} ,
] ,
as : 'mybookings' ,
} ,
} ,
/ * *
{
$lookup : {
from : "users" ,
localField : "myId1" ,
foreignField : "_id" ,
as : "user" ,
} ,
} ,
{
$lookup : {
from : "users" ,
let : {
myid : { $toObjectId : "$mybookings.userId" } ,
} ,
pipeline : [
{
$match : {
$expr : {
$and : [
{
$eq : [
"$_id" ,
"$$myid" ,
] ,
} ,
{
$eq : [
"$idapp" ,
"13" ,
] ,
} ,
] ,
} ,
} ,
} ,
{
$project : { _id : 1 , username : 1 } ,
}
] ,
as : "myuser" ,
} ,
} * * /
] ;
return arrquery ;
} ,
2022-12-15 18:09:43 +01:00
getQueryTable : async function ( idapp , params , user ) {
2019-02-07 00:52:48 +01:00
2024-03-21 22:58:46 +01:00
try {
2023-04-17 00:11:36 +02:00
2024-03-21 22:58:46 +01:00
const { Search } = require ( '../models/search' ) ;
2023-04-13 13:46:48 +02:00
2024-03-21 22:58:46 +01:00
if ( typeof params . startRow !== 'number' ) {
throw new Error ( 'startRow must be number' ) ;
} else if ( typeof params . endRow !== 'number' ) {
throw new Error ( 'endRow must be number' ) ;
}
2019-10-20 01:21:54 +02:00
2024-03-21 22:58:46 +01:00
let newvers = ! ! params . newvers ;
2021-12-21 01:27:45 +01:00
2024-03-21 22:58:46 +01:00
let query = [ ] ;
2021-12-21 01:27:45 +01:00
2024-03-21 22:58:46 +01:00
if ( params . filter && params . fieldsearch ) {
2024-05-09 23:36:46 +02:00
params . filter = this . sanitizzaHtml ( params . filter ) ;
params . fieldsearch = this . sanitizzaHtml ( params . fieldsearch ) ;
2024-03-21 22:58:46 +01:00
const querytemp = this . getFilterParam ( params . filter , params . fieldsearch ) ;
if ( querytemp ) {
query = [ ... query , ... querytemp ] ;
}
2022-02-12 02:20:07 +01:00
}
2020-02-02 04:06:32 +01:00
2024-03-21 22:58:46 +01:00
let filtriadded = [ ] ;
2020-02-02 04:06:32 +01:00
2024-03-21 22:58:46 +01:00
// if (params.table === 'extralist') {
// if (params.filterand.includes(shared_consts.FILTER_EXTRALIST_DELETED))
// filtriadded.push({ deleted: true });
// else
// filtriadded.push({ deleted: { $exists: false } });
// }
2020-02-02 04:06:32 +01:00
2024-03-21 22:58:46 +01:00
if ( params . filterand ) {
2024-05-09 23:36:46 +02:00
params . filterand = this . sanitizzaHtml ( params . filterand ) ;
2020-02-02 04:06:32 +01:00
2024-03-21 22:58:46 +01:00
if ( params . filterand . includes (
shared _consts . FILTER _EXTRALIST _NOT _REGISTERED ) )
filtriadded . push ( { registered : false } ) ;
2021-02-11 02:20:35 +01:00
2024-03-21 22:58:46 +01:00
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 ] } ,
} ) ;
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 ) )
filtriadded . push ( { 'profile.ask_zoom_partecipato' : false } ) ;
if ( params . filterand . includes ( shared _consts . FILTER _USER _NO _INVITANTE ) )
filtriadded . push ( {
aportador _solidario : { $exists : false } ,
} ) ;
if ( params . filterand . includes ( shared _consts . FILTER _USER _NO _TELEGRAM _ID ) )
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 ) )
filtriadded . push ( { 'profile.teleg_checkcode' : { $gt : 1 } } ) ;
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 ( {
verified _by _aportador : { $exists : false } ,
} ) ;
if ( params . filterand . includes ( shared _consts . FILTER _USER _WITHOUT _USERNAME _TELEGRAM ) )
filtriadded . push ( {
2022-12-15 18:09:43 +01:00
$or : [
2024-03-21 22:58:46 +01:00
{ 'profile.username_telegram' : { $exists : false } } ,
{ 'profile.username_telegram' : { $exists : true , $eq : '' } } ] ,
} ) ;
if ( params . filterand . includes ( shared _consts . FILTER _USER _NO _DREAM ) )
filtriadded . push ( {
'profile.my_dream' : {
$exists : false ,
} ,
} ) ;
if ( params . filterand . includes ( shared _consts . FILTER _USER _TELEGRAM _BLOCKED ) )
filtriadded . push ( { 'profile.teleg_id_old' : { $gt : 1 } } ) ;
if ( params . filterand . includes ( shared _consts . FILTER _USER _PROVINCE ) )
filtriadded . push ( { 'profile.resid_province' : { $exists : true } } ) ;
if ( params . filterand . includes ( shared _consts . FILTER _ATTIVI ) )
filtriadded . push ( {
2022-12-15 18:09:43 +01:00
$or : [
{ deleted : { $exists : false } } ,
{ deleted : { $exists : true , $eq : false } } ] ,
2024-03-21 22:58:46 +01:00
} ) ;
2021-02-11 02:20:35 +01:00
2024-03-21 22:58:46 +01:00
// 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 } } ] ,
} ,
) ;
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 } } ] ,
} ,
) ;
2020-02-02 04:06:32 +01:00
2024-03-21 22:58:46 +01:00
if ( params . filterand . includes ( shared _consts . FILTER _NASCOSTI ) )
filtriadded . push ( {
deleted : { $exists : true , $eq : true } ,
} ) ;
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 } } ] ,
} ) ;
2021-06-04 10:07:57 +02:00
2024-03-21 22:58:46 +01:00
// Iscritti Conacreis
if ( params . filterand . includes ( shared _consts . FILTER _REPORTED ) )
filtriadded . push (
{ reported : { $exists : true , $eq : true } } ,
) ;
2021-06-04 10:07:57 +02:00
2024-03-21 22:58:46 +01:00
if ( params . filterand . includes (
shared _consts . FILTER _TO _MAKE _MEMBERSHIP _CARD ) )
filtriadded . push ( {
$or : [
{ codiceConacreis : { $exists : false } } ,
{ codiceConacreis : { $exists : true , $eq : '' } } ] ,
} ) ;
2021-06-04 10:07:57 +02:00
2024-03-21 22:58:46 +01:00
if ( params . filterand . includes ( shared _consts . FILTER _MEMBERSHIP _CARD _OK ) )
filtriadded . push ( {
codiceConacreis : { $exists : true } ,
'$expr' : { '$gt' : [ { '$strLenCP' : '$codiceConacreis' } , 0 ] } ,
} ) ;
2020-02-02 04:06:32 +01:00
2022-01-03 21:53:50 +01:00
}
2021-12-11 00:25:54 +01:00
2024-03-21 22:58:46 +01:00
if ( params . filtercustom ) {
2024-05-09 23:36:46 +02:00
params . filtercustom = this . sanitizzaHtml ( params . filtercustom ) ;
2024-03-21 22:58:46 +01:00
let condition = { } ;
for ( const myfilter of params . filtercustom ) {
if ( myfilter [ 'userId' ] ) {
myfilter [ 'userId' ] = ObjectID ( myfilter [ 'userId' ] ) ;
}
if ( myfilter [ '_idOBJ' ] ) {
filtriadded . push ( { _id : ObjectID ( myfilter [ '_idOBJ' ] ) } ) ;
} else if ( myfilter [ 'dateTimeStart' ] ) {
const gte = myfilter [ 'dateTimeStart' ] . $gte ;
const lte = myfilter [ 'dateTimeStart' ] . $lte ;
condition = {
dateTimeStart : {
$gte : new Date ( gte ) ,
$lte : new Date ( lte ) ,
} ,
} ;
2022-05-08 13:19:49 +02:00
filtriadded . push ( condition ) ;
2024-03-21 22:58:46 +01:00
} else if ( myfilter . hasOwnProperty ( 'pub_to_share' ) ) {
// non aggiungere niente
} else {
filtriadded . push ( myfilter ) ;
2022-05-08 13:19:49 +02:00
}
}
}
2024-03-21 22:58:46 +01:00
if ( params . filter _gte ) {
2024-05-09 23:36:46 +02:00
params . filter _gte = this . sanitizzaHtml ( params . filter _gte ) ;
2024-03-21 22:58:46 +01:00
for ( let ind = 0 ; ind < params . filter _gte . length ; ind ++ ) {
for ( const [ key , value ] of Object . entries ( params . filter _gte [ ind ] ) ) {
if ( value > 0 ) {
let condition = { } ;
condition [ key ] = { $gte : value } ;
filtriadded . push ( condition ) ;
}
}
}
}
2021-12-11 00:25:54 +01:00
2024-03-21 22:58:46 +01:00
if ( params . filtersearch ) {
2024-05-09 23:36:46 +02:00
params . filtersearch = this . sanitizzaHtml ( params . filtersearch ) ;
2024-03-21 22:58:46 +01:00
filtriadded . push ( ... params . filtersearch ) ;
2022-01-12 00:38:47 +01:00
}
2024-03-21 22:58:46 +01:00
if ( params . options ) {
if ( this . isBitActive ( params . options ,
shared _consts . OPTIONS _SEARCH _ONLY _FULL _WORDS ) ) {
}
}
2023-04-07 02:45:21 +02:00
2022-11-06 13:39:01 +01:00
2024-03-21 22:58:46 +01:00
if ( params . filterextra ) {
2024-05-09 23:36:46 +02:00
params . filterextra = this . sanitizzaHtml ( params . filterextra ) ;
2024-03-21 22:58:46 +01:00
if ( params . filterextra . length > 0 )
query = [ ... query , ... params . filterextra ]
}
2020-02-02 04:06:32 +01:00
2024-03-21 22:58:46 +01:00
if ( filtriadded ) {
2024-05-09 23:36:46 +02:00
filtriadded = this . sanitizzaHtml ( filtriadded ) ;
2024-03-21 22:58:46 +01:00
if ( filtriadded . length > 0 )
query . push ( { $match : { $and : filtriadded } } ) ;
}
2019-10-28 16:01:28 +01:00
2024-08-29 23:30:58 +02:00
let numrowend = params . endRow - params . startRow ;
if ( numrowend < 0 )
numrowend = 1 ;
let projectEnd = { $slice : [ '$results' , params . startRow , numrowend ] } ;
let querymatch = { } ;
2024-03-21 22:58:46 +01:00
if ( idapp > 0 ) {
2024-08-29 23:30:58 +02:00
querymatch . idapp = idapp ;
}
if ( params . searchByBoundariesMap ) {
projectEnd = "$results" ;
querymatch . coordinate _gps = {
$geoWithin : {
$box : [
[ params . searchByBoundariesMap . sw . lng , params . searchByBoundariesMap . sw . lat ] ,
[ params . searchByBoundariesMap . ne . lng , params . searchByBoundariesMap . ne . lat ]
]
}
} ;
} ;
if ( Object . keys ( querymatch ) . length > 0 ) {
query . push (
{ $match : querymatch } ) ;
2024-03-21 22:58:46 +01:00
}
2019-02-15 01:38:01 +01:00
2024-03-21 22:58:46 +01:00
// console.log('QUERYMATCH', query[0].$match.or);
// console.log('filter', params.filter);
2020-01-30 01:19:25 +01:00
2022-09-02 02:25:38 +02:00
2024-03-21 22:58:46 +01:00
if ( params . querytype === shared _consts . QUERYTYPE _MYGROUP || params . querytype === shared _consts . QUERYTYPE _CIRCUIT ) {
2022-09-02 02:25:38 +02:00
2024-03-21 22:58:46 +01:00
const myq = this . addQueryIdMatch ( params ) ;
if ( myq )
query . push ( myq ) ;
2022-12-15 18:09:43 +01:00
2024-03-21 22:58:46 +01:00
query . push ( { $project : { req _users : 1 } } ) ;
const qa1 = this . getLookup (
{
lk _tab : 'users' ,
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 ,
} ) ;
if ( qa1 ) query = [ ... query , ... qa1 ] ;
query . push ( { $unwind : '$user' } ) ;
2022-12-15 18:09:43 +01:00
2024-03-21 22:58:46 +01:00
query . push ( {
$match : {
$and : [
{ 'user.idapp' : params . idapp } ,
] ,
} ,
} ) ;
2022-02-08 23:14:08 +01:00
2024-03-21 22:58:46 +01:00
query . push ( {
$replaceRoot : {
newRoot : '$user' ,
} ,
2022-12-15 18:09:43 +01:00
} ,
2024-03-21 22:58:46 +01:00
) ;
2022-08-08 16:35:32 +02:00
2024-03-21 22:58:46 +01:00
} else if ( params . querytype === shared _consts . QUERYTYPE _REFUSED _USER _GRP || params . querytype ===
shared _consts . QUERYTYPE _REFUSED _USER _CIRCUIT ) {
2022-09-02 02:25:38 +02:00
2024-03-21 22:58:46 +01:00
/ *
const myq = this . addQueryIdMatch ( params ) ;
if ( myq )
query . push ( myq ) ;
* /
2022-09-02 02:25:38 +02:00
2024-03-21 22:58:46 +01:00
const myq = this . addQueryIdMatch ( params ) ;
if ( myq )
query . push ( myq ) ;
2022-12-15 18:09:43 +01:00
2024-03-21 22:58:46 +01:00
query . push ( { $project : { refused _users : 1 } } ) ;
query . push ( { $unwind : '$refused_users' } ) ;
const qa1 = this . getLookupPipeLine (
{
lk _tab : 'users' ,
lk _LF : 'refused_users.username' ,
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 ,
} ) ;
if ( qa1 ) query = [ ... query , ... qa1 ] ;
query . push ( { $unwind : '$user' } ) ;
/ *
query . push ( {
$match : {
$and : [
{ 'user.idapp' : params . idapp } ,
] ,
} ,
} ) ;
* /
2022-02-08 23:14:08 +01:00
2024-03-21 22:58:46 +01:00
query . push ( {
$replaceRoot : {
newRoot : '$user' ,
} ,
2022-12-15 18:09:43 +01:00
} ,
2024-03-21 22:58:46 +01:00
) ;
} else if ( params . querytype === shared _consts . QUERYTYPE _GROUP _CIRCUIT ) {
2023-02-16 20:13:38 +01:00
2024-03-21 22:58:46 +01:00
const myq = this . addQueryIdMatch ( params ) ;
if ( myq )
query . push ( myq ) ;
2023-02-16 20:13:38 +01:00
2024-03-21 22:58:46 +01:00
query . push ( { $project : { req _groups : 1 } } ) ;
const qa1 = this . getLookup (
{
lk _tab : 'mygroups' ,
lk _LF : 'req_groups.groupname' ,
lk _FF : 'groupname' ,
lk _as : 'group' ,
} , 0 , {
'group.idapp' : 1 ,
'group.groupname' : 1 ,
'group.photos' : 1 ,
} ) ;
if ( qa1 ) query = [ ... query , ... qa1 ] ;
query . push ( { $unwind : '$group' } ) ;
2023-02-16 20:13:38 +01:00
2024-08-29 23:30:58 +02:00
if ( true ) {
query . push ( {
$match : {
$and : [
{ 'group.idapp' : params . idapp } ,
] ,
coordinate _gps : {
$geoWithin : {
$box : [
[ searchByBoudariesMap . sw . lng , searchByBoudariesMap . sw . lat ] ,
[ searchByBoudariesMap . ne . lng , searchByBoudariesMap . ne . lat ]
]
}
}
} ,
} ) ;
} else {
query . push ( {
$match : {
$and : [
{ 'group.idapp' : params . idapp } ,
] ,
} ,
} ) ;
}
2023-02-16 20:13:38 +01:00
2024-03-21 22:58:46 +01:00
query . push ( {
$replaceRoot : {
newRoot : '$group' ,
} ,
2023-02-16 20:13:38 +01:00
} ,
2024-03-21 22:58:46 +01:00
) ;
2023-02-16 20:13:38 +01:00
2024-03-21 22:58:46 +01:00
} else if ( params . querytype === shared _consts . QUERYTYPE _REFUSED _GROUP _CIRCUIT ) {
2023-02-16 20:13:38 +01:00
2024-03-21 22:58:46 +01:00
const myq = this . addQueryIdMatch ( params ) ;
if ( myq )
query . push ( myq ) ;
2023-02-16 20:13:38 +01:00
2024-03-21 22:58:46 +01:00
query . push ( { $project : { refused _groups : 1 } } ) ;
query . push ( { $unwind : '$refused_groups' } ) ;
const qa1 = this . getGroupnameLookupPipeLine (
{
lk _tab : 'mygroups' ,
lk _LF : 'refused_groups.groupname' ,
lk _FF : 'groupname' ,
lk _as : 'group' ,
idapp ,
} , {
'group.idapp' : 1 ,
'group.groupname' : 1 ,
'group.descr' : 1 ,
'group.photos' : 1 ,
} ) ;
if ( qa1 ) query = [ ... query , ... qa1 ] ;
query . push ( { $unwind : '$group' } ) ;
/ *
query . push ( {
$match : {
$and : [
{ 'user.idapp' : params . idapp } ,
] ,
} ,
} ) ;
* /
2023-02-16 20:13:38 +01:00
2024-03-21 22:58:46 +01:00
query . push ( {
$replaceRoot : {
newRoot : '$group' ,
} ,
2023-02-16 20:13:38 +01:00
} ,
2024-03-21 22:58:46 +01:00
) ;
2023-03-17 19:07:31 +01:00
2024-03-21 22:58:46 +01:00
} else if ( params . querytype === shared _consts . QUERYTYPE _LIST _MOVEMENTS ) {
2023-03-17 19:07:31 +01:00
2024-03-21 22:58:46 +01:00
const { Movement } = require ( '../models/movement' ) ;
2023-03-17 19:07:31 +01:00
2024-03-21 22:58:46 +01:00
const myquery = await Movement . getQueryMovsByCircuitId ( params . idapp , params . username , '' , '' , params . myid ) ;
2023-03-17 19:07:31 +01:00
2024-03-21 22:58:46 +01:00
query . push ( ... myquery ) ;
} else if ( params . querytype === shared _consts . QUERYTYPE _LIST _MOVEMENTS _GROUPNAME ) {
2023-03-17 19:07:31 +01:00
2024-03-21 22:58:46 +01:00
const { Movement } = require ( '../models/movement' ) ;
2023-03-17 19:07:31 +01:00
2024-03-21 22:58:46 +01:00
const myquery = await Movement . getQueryMovsByCircuitId ( params . idapp , '' , params . groupname , '' , params . myid ) ;
2023-03-17 19:07:31 +01:00
2024-03-21 22:58:46 +01:00
query . push ( ... myquery ) ;
2022-09-11 11:45:33 +02:00
2024-03-21 22:58:46 +01:00
} else if ( params . querytype === shared _consts . QUERYTYPE _LIST _MOVEMENTS _CONTOCOM ) {
2022-09-11 11:45:33 +02:00
2024-03-21 22:58:46 +01:00
const { Movement } = require ( '../models/movement' ) ;
2022-09-16 19:39:32 +02:00
2024-03-21 22:58:46 +01:00
const myquery = await Movement . getQueryMovsByCircuitId ( params . idapp , '' , '' , params . contocom , params . myid ) ;
2022-09-16 19:39:32 +02:00
2024-03-21 22:58:46 +01:00
query . push ( ... myquery ) ;
2022-09-16 19:39:32 +02:00
2024-03-21 22:58:46 +01:00
} else if ( params . querytype === shared _consts . QUERYTYPE _LIST _ALLMOVEMENTS ) {
2022-09-12 18:37:08 +02:00
2024-03-21 22:58:46 +01:00
const { Movement } = require ( '../models/movement' ) ;
2022-02-08 23:14:08 +01:00
2024-03-21 22:58:46 +01:00
const myquery = await Movement . getQueryAllUsersMovsByCircuitId ( params . idapp , params . myid ) ;
2022-11-30 21:26:05 +01:00
2024-03-21 22:58:46 +01:00
query . push ( ... myquery ) ;
2021-12-21 01:27:45 +01:00
2022-02-08 23:14:08 +01:00
}
2024-03-21 22:58:46 +01:00
if ( params . filterextra2 ) {
if ( params . filterextra2 . length > 0 )
query = [ ... query , ... params . filterextra2 ] ;
2022-02-08 23:14:08 +01:00
}
2024-03-21 22:58:46 +01:00
if ( newvers ) {
// NUOVA VERSIONE
let proj = params . lookup2 ? params . lookup2 . lk _proj : null ;
2023-04-07 02:45:21 +02:00
2024-03-26 18:11:19 +01:00
proj = this . sanitizzaProjection ( proj ) ;
2024-03-21 22:58:46 +01:00
if ( params . proj0 ) {
query . push ( { $project : params . proj0 } ) ;
}
2023-04-07 02:45:21 +02:00
2024-03-21 22:58:46 +01:00
if ( params . unwind0 ) {
query . push ( { $unwind : params . unwind0 } ) ;
}
2023-04-07 02:45:21 +02:00
2024-03-21 22:58:46 +01:00
let objadd = { query : [ ] , proj : { } } ;
2021-12-21 01:27:45 +01:00
2024-03-21 22:58:46 +01:00
let numtab = this . getNumTabByTable ( params . table ) ;
2022-02-08 23:14:08 +01:00
2021-12-21 01:27:45 +01:00
2024-03-21 22:58:46 +01:00
const q1 = this . getLookup ( params . lookup1 , 1 , proj , objadd . proj ) ;
if ( q1 ) query = [ ... query , ... q1 ] ;
2023-09-27 18:38:57 +02:00
2024-03-21 22:58:46 +01:00
if ( params . unwind1 ) {
query . push ( { $unwind : params . unwind1 } ) ;
}
2021-12-21 01:27:45 +01:00
2024-03-21 22:58:46 +01:00
if ( params . lookupPipeline1 ) {
const q1p = this . getLookupStandardPipeline ( params . lookupPipeline1 , 1 ) ;
if ( q1p ) query = [ ... query , ... q1p ] ;
}
2021-12-31 01:44:28 +01:00
2024-05-04 14:49:02 +02:00
params . lookup2 = this . sanitizzaLookup ( params . lookup2 ) ;
params . lookup3 = this . sanitizzaLookup ( params . lookup3 ) ;
params . lookup4 = this . sanitizzaLookup ( params . lookup4 ) ;
params . lookup5 = this . sanitizzaLookup ( params . lookup5 ) ;
2024-03-21 22:58:46 +01:00
const q2 = this . getLookup ( params . lookup2 , 2 , proj , objadd . proj ) ;
if ( q2 ) query = [ ... query , ... q2 ] ;
2022-01-20 00:39:06 +01:00
2024-03-21 22:58:46 +01:00
if ( params . lookupPipeline2 ) {
const q2p = this . getLookupStandardPipeline ( params . lookupPipeline2 , 2 ) ;
if ( q2p ) query = [ ... query , ... q2p ] ;
2022-01-07 01:18:01 +01:00
}
2022-06-16 20:34:42 +02:00
2024-03-21 22:58:46 +01:00
const q3 = this . getLookup ( params . lookup3 , 3 , proj , objadd . proj ) ;
if ( q3 ) query = [ ... query , ... q3 ] ;
2023-04-07 02:45:21 +02:00
2024-03-21 22:58:46 +01:00
const q4 = this . getLookup ( params . lookup4 , 4 , proj , objadd . proj ) ;
if ( q4 ) query = [ ... query , ... q4 ] ;
2022-06-16 20:34:42 +02:00
2024-03-21 22:58:46 +01:00
const q5 = this . getLookup ( params . lookup5 , 5 , proj , objadd . proj ) ;
if ( q5 ) query = [ ... query , ... q5 ] ;
if ( params . filtersearch2 ) {
if ( params . filtersearch2 . length > 0 ) {
query . push ( { $match : { $and : params . filtersearch2 } } ) ;
2022-08-11 13:38:42 +02:00
}
2024-03-21 22:58:46 +01:00
}
2022-08-11 13:38:42 +02:00
2022-06-16 20:34:42 +02:00
2024-03-21 22:58:46 +01:00
let filteradmin = false ;
if ( params . filtercustom ) {
let condition = { } ;
for ( const myfilter of params . filtercustom ) {
2022-06-16 20:34:42 +02:00
2024-03-21 22:58:46 +01:00
if ( ! ! myfilter . admins ) {
filteradmin = true ;
2022-06-16 20:34:42 +02:00
}
2024-03-21 22:58:46 +01:00
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 ) ;
}
// prendere i gruppi dell'utente
// Cerca tra i gruppi di ogni record, se combaciano almeno 1
condition = {
'profile.mygroups' :
{
$elemMatch : {
groupname : { $in : arraygroups } ,
} ,
2022-12-15 18:09:43 +01:00
} ,
2024-03-21 22:58:46 +01:00
} ;
2022-06-16 20:34:42 +02:00
2024-03-21 22:58:46 +01:00
query . push ( { $match : { $and : [ condition ] } } ) ;
} else if ( myfilter [ 'pub_to_share' ] === shared _consts . PUBTOSHARE . ONLY _TABLE _FOLLOW && params . table === 'circuits' ) {
2022-06-16 20:34:42 +02:00
2024-03-21 22:58:46 +01:00
let arraycircuits = [ ] ;
2022-09-19 14:37:57 +02:00
2024-03-21 22:58:46 +01:00
if ( user && user . profile . mycircuits ) {
arraycircuits = user . profile . mycircuits . map ( rec => rec . circuitname ) ;
}
// prendere i gruppi dell'utente
2022-09-19 14:37:57 +02:00
2024-03-21 22:58:46 +01:00
// Cerca tra i gruppi di ogni record, se combaciano almeno 1
condition = {
'profile.mycircuits' :
{
$elemMatch : {
circuitname : { $in : arraycircuits } ,
} ,
2022-09-19 14:37:57 +02:00
2022-12-15 18:09:43 +01:00
} ,
2024-03-21 22:58:46 +01:00
} ;
2022-09-19 14:37:57 +02:00
2024-03-21 22:58:46 +01:00
query . push ( { $match : { $and : [ condition ] } } ) ;
} else if ( shared _consts . TABLES _ENABLE _GETREC _BYID . includes ( params . table ) ) {
// Rimuovi dalla query quelli non visibili
2022-09-19 14:37:57 +02:00
2024-03-21 22:58:46 +01:00
let arraygroups = [ ] ;
2022-06-17 12:30:44 +02:00
2024-03-21 22:58:46 +01:00
if ( user && user . profile . mygroups ) {
arraygroups = user . profile . mygroups . map ( rec => rec . groupname ) ;
}
// prendere i gruppi dell'utente
2022-06-17 12:30:44 +02:00
2024-03-21 22:58:46 +01:00
// Cerca tra i gruppi di ogni record, se combaciano almeno 1
condition = {
'profile.mygroups' :
{
$elemMatch : {
groupname : { $in : arraygroups } ,
} ,
2022-06-17 12:30:44 +02:00
2022-12-15 18:09:43 +01:00
} ,
2024-03-21 22:58:46 +01:00
} ;
2022-06-17 12:30:44 +02:00
2024-03-21 22:58:46 +01:00
query . push (
2022-06-17 12:30:44 +02:00
{
2024-03-21 22:58:46 +01:00
$match :
{
$or : [
{
$and : [ condition , { pub _to _share : 1 } ] ,
} ,
{ $or : [ { pub _to _share : { $exists : false } } , { pub _to _share : { $exists : true , $eq : shared _consts . PUBTOSHARE . ALL } } ] } ,
] ,
} ,
2022-06-17 12:30:44 +02:00
} ,
2024-03-21 22:58:46 +01:00
) ;
2022-06-17 12:30:44 +02:00
2024-03-21 22:58:46 +01:00
}
2022-06-16 20:34:42 +02:00
2024-03-21 22:58:46 +01:00
}
2022-06-16 20:34:42 +02:00
}
2024-09-30 14:50:19 +02:00
if ( params . table === shared _consts . TABLES _MYBACHECAS ) {
const myq = this . getQueryMyBacheca ( idapp ) ;
query . push ( myq [ 0 ] ) ;
}
2024-03-21 22:58:46 +01:00
if ( params . filtersearch3or ) {
if ( params . filtersearch3or . length > 0 ) {
query . push ( { $match : { $or : params . filtersearch3or } } ) ;
}
2022-01-24 23:49:02 +01:00
}
2021-12-21 01:27:45 +01:00
2024-03-21 22:58:46 +01:00
if ( params . filtersearch3and ) {
if ( params . filtersearch3and . length > 0 ) {
// Se c'è statusskill allora glielo metto in OR
2024-02-19 18:51:10 +01:00
2024-03-21 22:58:46 +01:00
if ( params . table === 'myskills' && params . filtersearch && ! this . contieneIdStatusSkill ( params . filtersearch ) ) {
2024-02-19 18:51:10 +01:00
2024-03-21 22:58:46 +01:00
query . push ( {
$match : {
$or : [
{ $and : params . filtersearch3and } ,
{ idStatusSkill : { $in : [ 2 ] } }
]
}
} ) ;
} else {
query . push ( { $match : { $and : params . filtersearch3and } } ) ;
}
2024-02-19 18:51:10 +01:00
2024-03-21 22:58:46 +01:00
}
2022-02-25 12:01:34 +01:00
}
2024-03-21 22:58:46 +01:00
if ( params . filter && params . fieldsearch _last ) {
const querytemp = this . getFilterParam ( params . filter ,
params . fieldsearch _last ) ;
if ( querytemp ) {
query = [ ... query , ... querytemp ] ;
}
2023-04-13 13:46:48 +02:00
2024-03-21 22:58:46 +01:00
// Save the search:
if ( user . _id ) {
const mysearch = new Search ( { idapp , userId : user . _id , text : params . filter } ) ;
await mysearch . save ( ) ;
}
2023-04-13 13:46:48 +02:00
}
2022-02-12 02:20:07 +01:00
2024-03-21 22:58:46 +01:00
if ( params . table === 'mygroups' || params . table === 'circuits' ) {
// BINARY CHECK (?): const filter = [{ visibility: { $bitsAnyClear: [1] } }];
// if (!User.isAdmin(req.user.perm)) {
// not Visibility_Group.HIDDEN
if ( ! filteradmin ) {
if ( user ) {
const filter = [
2022-09-19 14:37:57 +02:00
{
2024-03-21 22:58:46 +01:00
$or : [
{
visibility : {
$nin : [ shared _consts . Visibility _Group . HIDDEN ] ,
} ,
} ,
{
createdBy : {
$eq : user . username ,
} ,
} ,
] ,
2022-09-19 14:37:57 +02:00
} ,
2024-03-21 22:58:46 +01:00
] ;
query . push ( { $match : { $and : filter } } ) ;
} else {
const filter = [
2022-09-19 14:37:57 +02:00
{
2024-03-21 22:58:46 +01:00
visibility : {
$nin : [ shared _consts . Visibility _Group . HIDDEN ] ,
2022-09-19 14:37:57 +02:00
} ,
} ,
2024-03-21 22:58:46 +01:00
] ;
query . push ( { $match : { $and : filter } } ) ;
}
}
// }
2022-08-11 13:38:42 +02:00
}
2024-03-21 22:58:46 +01:00
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];
}
2023-09-27 18:38:57 +02:00
2024-03-21 22:58:46 +01:00
} else {
// VECCHIA VERSIONE
const q1 = this . getLookup ( params , 1 ) ;
if ( q1 ) query = [ ... query , ... q1 ] ;
}
2021-02-11 02:20:35 +01:00
2024-08-29 23:30:58 +02:00
if ( params . sortBy && ! params . searchByBoundariesMap ) {
2024-03-21 22:58:46 +01:00
// maybe we want to sort by blog title or something
const mysort = { $sort : params . sortBy } ;
// console.log('sortBy', params.sortBy);
// console.table(mysort);
query . push ( mysort ) ;
}
2023-04-12 15:37:54 +02:00
2024-03-21 22:58:46 +01:00
query . push (
{
$group : {
_id : null ,
// get a count of every result that matches until now
count : { $sum : 1 } ,
// keep our results for the next operation
results : { $push : '$$ROOT' } ,
} ,
2021-10-05 15:39:44 +02:00
} ,
2024-03-21 22:58:46 +01:00
// and finally trim the results to within the range given by start/endRow
) ;
2024-08-29 23:30:58 +02:00
if ( projectEnd ) {
query . push (
{
$project : {
count : 1 ,
rows : projectEnd ,
} ,
} ,
) ;
}
2019-10-28 16:01:28 +01:00
2024-03-21 22:58:46 +01:00
if ( this . testing ( ) ) {
2024-04-04 18:43:17 +02:00
// console.log('query', query);
2024-03-21 22:58:46 +01:00
}
2024-08-29 23:30:58 +02:00
//console.log('query', query);
2019-10-28 16:01:28 +01:00
2024-03-21 22:58:46 +01:00
return query ;
} catch ( e ) {
console . error ( 'Err query:' , e ) ;
}
2019-10-20 01:21:54 +02:00
} ,
2023-09-27 18:38:57 +02:00
startTimeLog ( name ) {
if ( this . testing ( ) ) {
2023-12-09 11:55:58 +01:00
// console.log('inizio', name);
2023-09-27 18:38:57 +02:00
console . time ( name ) ;
}
} ,
endTimeLog ( name ) {
if ( this . testing ( ) ) {
2023-12-09 11:55:58 +01:00
// console.log(' ... fine', name);
2023-09-27 18:38:57 +02:00
console . timeEnd ( name ) ;
}
} ,
2022-06-16 20:34:42 +02:00
async executeQueryTable ( mythistable , idapp , params , user ) {
2022-09-11 11:45:33 +02:00
let query = await this . getQueryTable ( idapp , params , user ) ;
2019-10-20 01:21:54 +02:00
2021-12-11 00:25:54 +01:00
try {
2021-12-21 01:27:45 +01:00
// console.log('query', query);
2023-09-27 18:38:57 +02:00
this . startTimeLog ( 'Query 1' ) ;
2021-12-11 00:25:54 +01:00
const [ ris ] = await mythistable . aggregate ( query ) ;
2021-02-24 04:48:31 +01:00
2021-12-11 00:25:54 +01:00
if ( ris ) {
2022-08-07 02:01:35 +02:00
if ( params . table === 'users' ) {
for ( const myrec of ris . rows ) {
2024-03-26 18:11:19 +01:00
if ( myrec . ipaddr )
myrec . ipaddr = '' ;
if ( myrec . tokens )
myrec . tokens = [ ] ;
if ( myrec . password )
myrec . password = '' ;
2022-08-07 02:01:35 +02:00
}
} else if ( params . table === 'mygroups' ) {
for ( const myrec of ris . rows ) {
if ( myrec . pwd _cryp )
2024-03-26 18:11:19 +01:00
myrec . pwd _cryp = '' ;
2022-08-07 02:01:35 +02:00
}
}
2023-09-27 18:38:57 +02:00
this . endTimeLog ( 'Query 1' ) ;
2021-12-11 00:25:54 +01:00
// console.table(ris.rows);
// console.log('ROW ', ris.count);
2022-12-15 18:09:43 +01:00
return ( { count : ris . count , rows : ris . rows } ) ;
2021-12-11 00:25:54 +01:00
} else {
2022-12-15 18:09:43 +01:00
return ( { count : 0 , rows : [ ] } ) ;
2021-12-11 00:25:54 +01:00
}
} catch ( e ) {
console . log ( 'error' , e ) ;
2021-02-24 04:48:31 +01:00
}
2019-10-20 01:21:54 +02:00
2019-10-27 00:37:10 +02:00
} ,
2020-01-13 23:52:51 +01:00
async DuplicateAllRecords ( mythistable , idapporig , idappdest ) {
console . log ( mythistable . name ) ;
const numrec = await mythistable . findAllIdApp ( idappdest ) . then ( ( arrrec ) => {
if ( arrrec && arrrec . length > 1 ) {
return arrrec . length ; // Has Already set
} else {
return 0 ;
}
} ) ;
// Before check if exist more than 1 record in the destination,
// if Yes don't copy
if ( numrec <= 0 ) {
2022-09-11 11:45:33 +02:00
return await mythistable . findAllIdApp ( idapporig ) . then ( async ( arrrec ) => {
2020-01-13 23:52:51 +01:00
let num = 0 ;
for ( let ind = 0 ; ind < arrrec . length ; ind ++ ) {
2022-05-14 00:31:53 +02:00
let newrec = new mythistable ( arrrec [ ind ] ) ;
2020-01-13 23:52:51 +01:00
newrec . _id = new ObjectID ( ) ;
newrec . idapp = idappdest ;
2022-02-12 22:12:49 +01:00
try {
await newrec . save ( ( err , rec ) => {
if ( rec ) {
num ++ ;
}
2020-01-13 23:52:51 +01:00
2022-02-12 22:12:49 +01:00
} ) ;
2022-02-24 19:13:20 +01:00
} catch ( e ) {
2022-02-12 22:12:49 +01:00
console . error ( 'e' , e ) ;
}
2020-01-13 23:52:51 +01:00
}
return num ;
} ) ;
}
} ,
2019-10-27 00:37:10 +02:00
isBitActive ( bit , whattofind ) {
2021-10-05 15:39:44 +02:00
return ( ( bit & whattofind ) === whattofind ) ;
2019-10-27 00:37:10 +02:00
} ,
2022-03-02 20:18:29 +01:00
isBitAttivoESelez ( bit , whattofind , loSono ) {
const abil = this . isBitActive ( bit , whattofind ) ;
return ( ( abil && loSono ) || ! abil ) ;
} ,
2019-10-27 00:37:10 +02:00
SetBit ( myval , bit ) {
2023-04-13 13:46:48 +02:00
let myvalout = myval
myvalout |= bit
return myvalout
2019-11-05 23:53:39 +01:00
} ,
2019-10-27 00:37:10 +02:00
2020-02-19 16:09:16 +01:00
async snooze ( ms ) {
2019-11-21 00:18:40 +01:00
return new Promise ( resolve => setTimeout ( resolve , ms ) ) ;
} ,
IncDateNow ( secs ) {
let mydate = new Date ( new Date ( ) . getTime ( ) + secs ) ;
// console.log('mydate', mydate);
2021-10-05 15:39:44 +02:00
return mydate ;
2019-12-04 02:03:44 +01:00
} ,
2020-07-13 23:35:05 +02:00
isdiffSecDateLess ( mydatediffstr , secs ) {
let mydate = new Date ( ) ;
// console.log('mydate', mydate);
let mydata2 = new Date ( mydatediffstr ) ;
let ris = ( ( mydate . getTime ( ) - mydata2 . getTime ( ) ) / 1000 ) ;
return ( ris < secs ) ;
} ,
2020-03-21 10:28:26 +01:00
AddDate ( mydate , days ) {
let date = new Date ( mydate ) ;
date . setTime ( date . getTime ( ) + days * 86400000 ) ;
return date ;
} ,
2020-05-10 21:07:51 +02:00
isMonToSat ( ) {
const dayOfWeek = new Date ( new Date ( ) ) . getDay ( ) ;
2021-10-05 15:39:44 +02:00
return dayOfWeek >= 1 && dayOfWeek <= 6 ;
2020-05-10 21:07:51 +02:00
} ,
2020-09-04 00:06:49 +02:00
isMonToFri ( ) {
const dayOfWeek = new Date ( new Date ( ) ) . getDay ( ) ;
2021-10-05 15:39:44 +02:00
return dayOfWeek >= 1 && dayOfWeek <= 5 ;
2020-09-04 00:06:49 +02:00
} ,
2020-05-10 21:07:51 +02:00
// var startTime = '15:10:10';
// var endTime = '22:30:00';
isBetweenTwoTime ( startTime , endTime ) {
currentDate = new Date ( ) ;
startDate = new Date ( currentDate . getTime ( ) ) ;
2021-10-05 15:39:44 +02:00
startDate . setHours ( startTime . split ( ':' ) [ 0 ] ) ;
startDate . setMinutes ( startTime . split ( ':' ) [ 1 ] ) ;
startDate . setSeconds ( startTime . split ( ':' ) [ 2 ] ) ;
2020-05-10 21:07:51 +02:00
endDate = new Date ( currentDate . getTime ( ) ) ;
2021-10-05 15:39:44 +02:00
endDate . setHours ( endTime . split ( ':' ) [ 0 ] ) ;
endDate . setMinutes ( endTime . split ( ':' ) [ 1 ] ) ;
endDate . setSeconds ( endTime . split ( ':' ) [ 2 ] ) ;
2020-05-10 21:07:51 +02:00
valid = startDate < currentDate && endDate > currentDate ;
return valid ;
} ,
getlimiti ( mypos ) {
if ( mypos . col < 0 ) {
mypos . col = 0 ;
}
if ( mypos . riga < 0 ) {
mypos . riga = 0 ;
mypos . col = 0 ;
}
return mypos ;
} ,
2020-03-21 10:28:26 +01:00
getRigaColByPosUp ( mypos ) {
2020-03-25 18:26:51 +01:00
if ( mypos . numup > 0 ) {
mypos . riga = mypos . riga - 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 ) ) ) ;
}
2020-05-04 19:34:41 +02:00
if ( mypos . riga < 1 ) {
mypos . riga = 1 ;
}
if ( mypos . col < 1 ) {
mypos . col = 1 ;
}
2020-03-21 10:28:26 +01:00
} ,
2020-05-10 21:07:51 +02:00
getRigaColGenerica ( idapp , riga , col , numup ) {
mypos = {
idapp ,
riga ,
col ,
2021-10-05 15:39:44 +02:00
numup ,
2020-05-10 21:07:51 +02:00
} ;
2020-06-08 13:31:05 +02:00
if ( idapp === this . AYNI ) {
2020-05-10 21:07:51 +02:00
this . getRigaColByPosUp ( mypos ) ;
ris = this . getlimiti ( mypos ) ;
}
return ris ;
} ,
getRigaColSognatoreByDonatore ( idapp , riga , col ) {
return this . getRigaColGenerica ( idapp , riga , col , 6 ) ;
} ,
getRigaColMediatoreByFuoco ( idapp , riga , col ) {
return this . getRigaColGenerica ( idapp , riga , col , 3 ) ;
} ,
getRigaColSognatoreByMediatore ( idapp , riga , col ) {
return this . getRigaColGenerica ( idapp , riga , col , 3 ) ;
} ,
2020-01-21 01:37:15 +01:00
appendLeadingZeroes ( n ) {
if ( n <= 9 ) {
2021-10-05 15:39:44 +02:00
return '0' + n ;
2020-01-21 01:37:15 +01:00
}
2021-10-05 15:39:44 +02:00
return n ;
2020-01-21 01:37:15 +01:00
} ,
2020-07-02 22:00:58 +02:00
getWeekDayByLangByNumCar ( date , lang , num ) {
2020-05-04 19:34:41 +02:00
if ( ! lang )
lang = 'it' ;
const dayOfWeek = new Date ( date ) . getDay ( ) ;
const myday = {
2021-10-05 15:39:44 +02:00
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' ] ,
2020-07-02 22:00:58 +02:00
} ;
if ( num > 0 ) {
2021-10-05 15:39:44 +02:00
return isNaN ( dayOfWeek ) ? '' : myday [ lang ] [ dayOfWeek ] . substring ( 0 , num ) ;
2020-07-02 22:00:58 +02:00
} else {
2021-10-05 15:39:44 +02:00
return isNaN ( dayOfWeek ) ? '' : myday [ lang ] [ dayOfWeek ] ;
2020-05-04 19:34:41 +02:00
}
2020-07-02 22:00:58 +02:00
} ,
2021-02-24 04:48:31 +01:00
isSunday ( mydate ) {
2021-10-05 15:39:44 +02:00
const dayOfWeek = new Date ( mydate ) . getDay ( ) ;
return dayOfWeek === 0 ;
2021-02-24 04:48:31 +01:00
} ,
isMonday ( mydate ) {
2021-10-05 15:39:44 +02:00
const dayOfWeek = new Date ( mydate ) . getDay ( ) ;
return dayOfWeek === 1 ;
2021-02-24 04:48:31 +01:00
} ,
2021-03-17 02:24:11 +01:00
isSundayDate ( mydate ) {
2021-10-05 15:39:44 +02:00
const dayOfWeek = mydate . getDay ( ) ;
return dayOfWeek === 0 ;
2021-03-17 02:24:11 +01:00
} ,
isMondayDate ( mydate ) {
2021-10-05 15:39:44 +02:00
const dayOfWeek = mydate . getDay ( ) ;
return dayOfWeek === 1 ;
2021-03-17 02:24:11 +01:00
} ,
2020-07-02 22:00:58 +02:00
getWeekDayByLang ( date , lang ) {
2021-10-05 15:39:44 +02:00
return this . getWeekDayByLangByNumCar ( date , lang , 3 ) ;
2020-07-02 22:00:58 +02:00
} ,
2020-05-04 19:34:41 +02:00
2020-07-02 22:00:58 +02:00
getWeekDayByLangTot ( date , lang ) {
2021-10-05 15:39:44 +02:00
return this . getWeekDayByLangByNumCar ( date , lang , 0 ) ;
2020-05-04 19:34:41 +02:00
} ,
2020-01-21 01:37:15 +01:00
getWeekDay ( date ) {
//Create an array containing each day, starting with Sunday.
const weekdays = [
2021-10-05 15:39:44 +02:00
'Domenica' ,
'Lunedì' ,
'Martedì' ,
'Mercoledì' ,
'Giovedí' ,
'Venerdì' ,
'Sabato' ,
2020-01-21 01:37:15 +01:00
] ;
//Use the getDay() method to get the day.
const day = date . getDay ( ) ;
//Return the element that corresponds to that index.
return weekdays [ day ] ;
} ,
2020-05-04 19:34:41 +02:00
getstrDateTimeShort ( mydate , lang ) {
2020-03-10 21:44:14 +01:00
if ( mydate ) {
// console.log('getstrDate', mytimestamp)
2021-10-05 15:39:44 +02:00
return this . getWeekDayByLang ( mydate , lang ) + ' ' +
2022-12-15 18:09:43 +01:00
this . appendLeadingZeroes ( mydate . getDate ( ) ) + '/' +
this . appendLeadingZeroes ( mydate . getMonth ( ) + 1 ) + ' ORE ' +
this . appendLeadingZeroes ( mydate . getHours ( ) ) + ':' +
this . appendLeadingZeroes ( mydate . getMinutes ( ) ) ;
2020-03-10 21:44:14 +01:00
} else {
return '' ;
}
} ,
2023-10-01 01:24:47 +02:00
getstrTime ( mytimestamp ) {
// Create a Date object with your desired date
const date = new Date ( mytimestamp ) ; // You can replace this with your specific date
// Get the hour and minute components from the date
const hours = date . getHours ( ) ;
const minutes = date . getMinutes ( ) ;
// Format the hour and minute components as HH:MM
const formattedTime = ` ${ String ( hours ) . padStart ( 2 , '0' ) } : ${ String ( minutes ) . padStart ( 2 , '0' ) } ` ;
return formattedTime
} ,
2020-05-04 19:34:41 +02:00
getstrDateShort ( mydate , lang ) {
2020-03-10 21:44:14 +01:00
if ( mydate ) {
// console.log('getstrDate', mytimestamp)
2021-10-05 15:39:44 +02:00
return this . getWeekDayByLang ( mydate , lang ) . substring ( 0 , 3 ) + ' ' +
2022-12-15 18:09:43 +01:00
this . appendLeadingZeroes ( mydate . getDate ( ) ) + '/' +
this . appendLeadingZeroes ( mydate . getMonth ( ) + 1 ) ;
2020-03-10 21:44:14 +01:00
} else {
return '' ;
}
} ,
2021-06-04 10:07:57 +02:00
getstrDate _DD _MM _YYYY ( mydate ) {
if ( mydate ) {
// console.log('getstrDate', mytimestamp)
2021-10-05 15:39:44 +02:00
return this . appendLeadingZeroes ( mydate . getDate ( ) ) + '/' +
2022-12-15 18:09:43 +01:00
this . appendLeadingZeroes ( mydate . getMonth ( ) + 1 ) + '/' +
this . appendLeadingZeroes ( mydate . getFullYear ( ) ) ;
2021-06-04 10:07:57 +02:00
} else {
return '' ;
}
} ,
2021-02-24 04:48:31 +01:00
getstrDateYYYY _MM _DD ( mydate ) {
if ( mydate ) {
// console.log('getstrDate', mytimestamp)
2021-10-05 15:39:44 +02:00
return mydate . getFullYear ( ) + '-' +
2022-12-15 18:09:43 +01:00
this . appendLeadingZeroes ( mydate . getMonth ( ) + 1 ) + '-' +
this . appendLeadingZeroes ( mydate . getDate ( ) ) ;
2021-02-24 04:48:31 +01:00
} else {
return '' ;
}
} ,
2021-03-17 02:24:11 +01:00
getstrUTCDateYYYY _MM _DD ( mydate ) {
if ( mydate ) {
// console.log('getstrDate', mytimestamp)
2021-10-05 15:39:44 +02:00
return mydate . getUTCFullYear ( ) + '-' +
2022-12-15 18:09:43 +01:00
this . appendLeadingZeroes ( mydate . getUTCMonth ( ) + 1 ) + '-' +
this . appendLeadingZeroes ( mydate . getUTCDate ( ) ) ;
2021-03-17 02:24:11 +01:00
} else {
return '' ;
}
} ,
2020-05-04 19:34:41 +02:00
getstrDateLong ( mydate , lang ) {
2020-03-10 21:44:14 +01:00
if ( mydate ) {
// console.log('getstrDate', mytimestamp)
2021-10-05 15:39:44 +02:00
return this . getWeekDayByLang ( mydate , lang ) + ' ' +
2022-12-15 18:09:43 +01:00
this . appendLeadingZeroes ( mydate . getDate ( ) ) + '/' +
this . appendLeadingZeroes ( mydate . getMonth ( ) + 1 ) + '/' +
mydate . getFullYear ( ) ;
2020-03-10 21:44:14 +01:00
} else {
return '' ;
}
2020-01-21 01:37:15 +01:00
} ,
2020-07-02 22:00:58 +02:00
getstrDateLongTot ( mydate , lang ) {
if ( mydate ) {
// console.log('getstrDate', mytimestamp)
2021-10-05 15:39:44 +02:00
return this . getWeekDayByLangTot ( mydate , lang ) + ' ' +
2022-12-15 18:09:43 +01:00
this . appendLeadingZeroes ( mydate . getDate ( ) ) + '/' +
this . appendLeadingZeroes ( mydate . getMonth ( ) + 1 ) + '/' +
mydate . getFullYear ( ) ;
2020-07-02 22:00:58 +02:00
} else {
return '' ;
}
} ,
2020-06-08 13:31:05 +02:00
getstrDateLongFile ( mydate , lang ) {
if ( mydate ) {
// console.log('getstrDate', mytimestamp)
2021-10-05 15:39:44 +02:00
return mydate . getFullYear ( ) + '-' +
2022-12-15 18:09:43 +01:00
this . appendLeadingZeroes ( mydate . getMonth ( ) + 1 ) + '-' +
this . appendLeadingZeroes ( mydate . getDate ( ) ) + ' (' +
this . getWeekDayByLang ( mydate , lang ) + ')' ;
2020-06-08 13:31:05 +02:00
} else {
return '' ;
}
} ,
2020-07-02 22:00:58 +02:00
getlinkzoom ( rec ) {
if ( rec === null ) {
rec = {
typeconf : this . TYPECONF _ZOOM ,
id _conf _zoom : '' ,
2021-10-05 15:39:44 +02:00
} ;
2020-07-02 22:00:58 +02:00
}
let typeconf = rec . typeconf ;
if ( typeconf === '' )
typeconf = this . TYPECONF _ZOOM ;
let mylink = 'https://zoom.us/j/' ;
if ( typeconf === this . TYPECONF _JITSI )
mylink = 'https://meet.jit.si/' ;
if ( rec . id _conf _zoom === '' ) {
rec . id _conf _zoom = '6668882000' ;
}
2021-10-05 15:39:44 +02:00
return mylink + rec . id _conf _zoom ;
2020-07-02 22:00:58 +02:00
2020-01-21 01:37:15 +01:00
} ,
2024-11-02 19:25:37 +01:00
getmd5 ( mystr ) {
return CryptoJS . MD5 ( mystr ? mystr . toLowerCase ( ) : '' ) . toString ( ) ;
2019-12-04 02:03:44 +01:00
} ,
getHash ( mystr ) {
2022-12-15 18:09:43 +01:00
return CryptoJS . SHA512 ( mystr , { outputLength : 256 } ) . toString ( ) ;
2019-12-04 02:03:44 +01:00
} ,
2020-01-03 01:52:49 +01:00
encrypt ( msg , pass ) {
var salt = CryptoJS . lib . WordArray . random ( 128 / 8 ) ;
var key = CryptoJS . PBKDF2 ( pass , salt , {
keySize : keySize / 32 ,
2021-10-05 15:39:44 +02:00
iterations : iterations ,
2020-01-03 01:52:49 +01:00
} ) ;
var iv = CryptoJS . lib . WordArray . random ( 128 / 8 ) ;
var encrypted = CryptoJS . AES . encrypt ( msg , key , {
iv : iv ,
padding : CryptoJS . pad . Pkcs7 ,
2021-10-05 15:39:44 +02:00
mode : CryptoJS . mode . CBC ,
2020-01-03 01:52:49 +01:00
} ) ;
// salt, iv will be hex 32 in length
// append them to the ciphertext for use in decryption
var transitmessage = salt . toString ( ) + iv . toString ( ) + encrypted . toString ( ) ;
return transitmessage ;
} ,
decrypt ( transitmessage , pass ) {
var salt = CryptoJS . enc . Hex . parse ( transitmessage . substr ( 0 , 32 ) ) ;
2021-10-05 15:39:44 +02:00
var iv = CryptoJS . enc . Hex . parse ( transitmessage . substr ( 32 , 32 ) ) ;
2020-01-03 01:52:49 +01:00
var encrypted = transitmessage . substring ( 64 ) ;
var key = CryptoJS . PBKDF2 ( pass , salt , {
keySize : keySize / 32 ,
2021-10-05 15:39:44 +02:00
iterations : iterations ,
2020-01-03 01:52:49 +01:00
} ) ;
var decrypted = CryptoJS . AES . decrypt ( encrypted , key , {
iv : iv ,
padding : CryptoJS . pad . Pkcs7 ,
2021-10-05 15:39:44 +02:00
mode : CryptoJS . mode . CBC ,
2020-01-03 01:52:49 +01:00
} ) ;
return decrypted ;
} ,
2019-12-04 02:03:44 +01:00
cryptdata ( mydata ) {
2022-01-07 01:18:01 +01:00
if ( mydata === '' )
return '' ;
2019-12-04 02:03:44 +01:00
// Encrypt
2020-01-03 01:52:49 +01:00
//return CryptoJS.AES.encrypt(JSON.stringify(mydata), process.env.SECRK);
return this . encrypt ( mydata , process . env . SECRK ) ;
2019-12-04 02:03:44 +01:00
} ,
decryptdata ( mydatacrypted ) {
2023-12-09 19:38:23 +01:00
if ( mydatacrypted === '' || mydatacrypted === undefined )
2022-01-07 01:18:01 +01:00
return '' ;
2019-12-04 02:03:44 +01:00
// Decrypt
2020-01-03 01:52:49 +01:00
// const bytes = CryptoJS.AES.decrypt(mydatacrypted.toString(), process.env.SECRK);
// return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
2021-10-05 15:39:44 +02:00
return this . decrypt ( mydatacrypted , process . env . SECRK ) .
2022-12-15 18:09:43 +01:00
toString ( CryptoJS . enc . Utf8 ) ;
2019-12-04 02:03:44 +01:00
} ,
BoolToInt ( mybool ) {
2021-10-05 15:39:44 +02:00
return ( mybool ) ? - 1 : 0 ;
2019-12-04 02:03:44 +01:00
} ,
StrToBool ( mystr ) {
2021-10-05 15:39:44 +02:00
return ( mystr === '-1' ) ? true : false ;
2019-12-27 12:41:39 +01:00
} ,
2020-02-19 16:09:16 +01:00
writelogfile ( mystr , filename ) {
// fs.appendFile(FILELOG, mystr, function (err) {
// if (err) throw err;
// console.log('Saved!');
// });
2022-02-27 16:56:02 +01:00
try {
mystr = this . getstrDateTimeShort ( new Date ( ) , 'it' ) + ': ' + mystr ;
2020-02-19 16:09:16 +01:00
2022-12-15 18:09:43 +01:00
const stream = fs . createWriteStream ( filename , { flags : 'a' } ) ;
2022-02-27 16:56:02 +01:00
stream . write ( '\n' + mystr ) ;
stream . end ( ) ;
2022-03-01 23:50:58 +01:00
} catch ( e ) {
2022-02-27 16:56:02 +01:00
}
2020-06-08 13:31:05 +02:00
2020-02-19 16:09:16 +01:00
} ,
2024-09-06 19:57:09 +02:00
async readlogfile ( idapp , filename ) {
2020-06-08 13:31:05 +02:00
2020-07-02 22:00:58 +02:00
try {
2024-09-06 19:57:09 +02:00
return await fs . readFileSync ( idapp + '/' + filename , 'utf8' ) ;
2020-07-02 22:00:58 +02:00
} catch ( e ) {
2020-06-08 13:31:05 +02:00
return '' ;
}
} ,
2024-09-06 19:57:09 +02:00
async readfilecontent ( filename ) {
try {
const cont = await fs . readFileSync ( filename , 'utf8' ) ;
return cont ;
} catch ( e ) {
return '' ;
}
} ,
async getVersServer ( ) {
return await this . readfilecontent ( _ _dirname + '/../version.txt' ) ;
} ,
2020-02-19 16:09:16 +01:00
writelog ( mystr ) {
this . writelogfile ( mystr , FILELOG ) ;
} ,
writeEventsLog ( mystr ) {
this . writelogfile ( mystr , FILEEVENTS ) ;
} ,
2020-03-10 21:44:14 +01:00
writeManagersLog ( mystr ) {
this . writelogfile ( mystr , FILEMANAGERS ) ;
} ,
2023-02-06 22:58:10 +01:00
writeTransactionLog ( mystr ) {
this . writelogfile ( mystr , FILETRANSACTION ) ;
} ,
2022-02-27 16:56:02 +01:00
writeErrorLog ( mystr ) {
this . writelogfile ( mystr , FILEERRLOGIN ) ;
} ,
2020-03-10 21:44:14 +01:00
2020-06-08 13:31:05 +02:00
writeSostituzioniLog ( mystr ) {
this . writelogfile ( mystr , FILESOSTITUZIONI ) ;
} ,
2020-07-13 23:35:05 +02:00
writeIPToBan ( mystr ) {
this . writelogfile ( mystr , FILEIP _TO _BAN ) ;
} ,
2020-06-08 13:31:05 +02:00
writeFlottaLog ( idapp , mystr , riga , col ) {
this . mkdirpath ( idapp + '/' ) ;
this . writelogfile ( mystr , idapp + '/' + riga + '_' + col + '.txt' ) ;
} ,
2020-03-10 21:44:14 +01:00
writeNaveLog ( mystr ) {
this . writelogfile ( mystr , FILENAVE ) ;
2020-02-19 16:09:16 +01:00
} ,
2024-09-13 19:42:48 +02:00
async move ( oldPath , newPath , callback ) {
try {
const ris = await fs . promises . rename ( oldPath , newPath ) ;
console . log ( '... File Rinominato:' , oldPath , 'in:' , newPath , 'ris' , ris ) ;
callback ( ) ; // Chiamare il callback senza errori
} catch ( err ) {
if ( err . code === 'EXDEV' ) {
await copy ( ) ; // Se EXDEV, utilizza la funzione copy
2022-03-01 23:50:58 +01:00
} else {
2024-09-13 19:42:48 +02:00
console . error ( 'Errore durante lo spostamento:' , err ) ;
callback ( err ) ; // Passa l'errore al callback
2019-12-27 12:41:39 +01:00
}
2024-09-13 19:42:48 +02:00
}
2022-03-01 23:50:58 +01:00
2024-09-13 19:42:48 +02:00
async function copy ( ) {
2019-12-27 12:41:39 +01:00
const readStream = fs . createReadStream ( oldPath ) ;
const writeStream = fs . createWriteStream ( newPath ) ;
2024-09-13 19:42:48 +02:00
readStream . on ( 'error' , ( err ) => {
console . error ( 'Errore nella lettura del file:' , err ) ;
callback ( err ) ; // Passa l'errore al callback
} ) ;
writeStream . on ( 'error' , ( err ) => {
console . error ( 'Errore nella scrittura del file:' , err ) ;
callback ( err ) ; // Passa l'errore al callback
2019-12-27 12:41:39 +01:00
} ) ;
readStream . pipe ( writeStream ) ;
2024-09-13 19:42:48 +02:00
writeStream . on ( 'finish' , async ( ) => {
console . log ( 'File copiato, ora rimuovo il file di origine:' , oldPath ) ;
try {
await fs . promises . unlink ( oldPath ) ; // Rimuovi il file originale
callback ( ) ; // Chiama il callback al termine
} catch ( err ) {
console . error ( 'Errore nella rimozione del file originale:' , err ) ;
callback ( err ) ; // Passa l'errore al callback
}
} ) ;
2019-12-27 12:41:39 +01:00
}
} ,
2019-11-21 00:18:40 +01:00
2022-02-16 09:40:16 +01:00
copy ( oldPath , newPath , callback ) {
fs . copyFile ( oldPath , newPath , ( err ) => {
if ( err ) throw err ;
// console.log('source.txt was copied to destination.txt');
} ) ;
} ,
2022-12-15 18:09:43 +01:00
extractFileName : function ( filename ) {
2022-01-14 23:54:33 +01:00
return path . basename ( filename ) ;
2021-12-21 18:12:28 +01:00
} ,
2022-12-15 18:09:43 +01:00
extractFilePath : function ( filename ) {
2022-01-14 23:54:33 +01:00
return path . dirname ( filename ) ;
2021-12-21 18:12:28 +01:00
} ,
2024-12-05 14:12:51 +01:00
async deleteFile ( filePath ) {
try {
await fs . promises . unlink ( filePath ) ;
console . log ( ` File eliminato con successo: ${ filePath } ` ) ;
} catch ( err ) {
console . error ( ` Errore durante l'eliminazione del file: ${ filePath } ` , err ) ;
throw err ;
}
} ,
2021-12-21 18:12:28 +01:00
delete ( mypath , alsothumb , callback ) {
2019-12-28 02:16:29 +01:00
2022-12-15 18:09:43 +01:00
fs . unlink ( mypath , function ( err ) {
2021-12-21 18:12:28 +01:00
if ( alsothumb ) {
try {
2022-01-14 23:54:33 +01:00
let img _small = path . dirname ( mypath ) + '/' +
2022-12-15 18:09:43 +01:00
server _constants . PREFIX _IMG _SMALL + path . basename ( mypath ) ;
fs . unlink ( img _small , function ( err ) {
2022-03-01 23:50:58 +01:00
if ( err )
console . log ( 'Errore durante la Cancellazione del file' , mypath ) ;
else
console . log ( 'deleted file' , mypath ) ;
} ) ;
2021-12-21 18:12:28 +01:00
} catch ( e ) {
console . error ( err ) ;
}
}
2019-12-28 02:16:29 +01:00
if ( err ) {
console . error ( err ) ;
callback ( err ) ;
2021-10-05 15:39:44 +02:00
return ;
2019-12-28 02:16:29 +01:00
}
callback ( ) ;
} ) ;
2019-12-28 14:30:30 +01:00
} ,
mkdirpath ( dirPath ) {
2020-01-03 01:52:49 +01:00
if ( ! fs . existsSync ( dirPath ) ) {
2019-12-28 14:30:30 +01:00
try {
2022-12-15 18:09:43 +01:00
fs . mkdirSync ( dirPath , { recursive : true } ) ;
2020-12-21 02:16:42 +01:00
} catch ( e ) {
2021-02-18 12:19:35 +01:00
if ( dirPath !== path . dirname ( dirPath ) ) {
const myname = path . dirname ( dirPath ) ;
this . mkdirpath ( myname ) ;
// this.mkdirpath(dirPath);
}
2019-12-28 14:30:30 +01:00
}
}
} ,
2019-12-28 02:16:29 +01:00
2024-03-28 20:25:48 +01:00
getNomeCognomeTelegram ( msg ) {
if ( msg && msg . chat ) {
let nomecognome = msg . chat . first _name ? msg . chat . first _name : '' ;
nomecognome += msg . chat . last _name ? ' ' + msg . chat . last _name : '' ;
return nomecognome ;
}
return '' ;
} ,
2020-01-13 23:52:51 +01:00
extractNameAndSurnameByComplete ( name _complete ) {
const suffissoCognome = [ 'Del' , 'La' , 'De' , 'Lo' ] ;
2021-10-05 15:39:44 +02:00
let campi = name _complete . split ( ' ' ) ;
2020-01-13 23:52:51 +01:00
let namesurname = {
name : '' ,
surname : '' ,
} ;
if ( campi . length === 2 ) {
namesurname . name = campi [ 0 ] ;
namesurname . surname = campi [ 1 ] ;
2020-01-21 01:37:15 +01:00
} else if ( campi . length === 3 ) {
2020-01-13 23:52:51 +01:00
if ( suffissoCognome . includes ( campi [ 1 ] ) ) {
namesurname . name = campi [ 0 ] ;
2021-10-05 15:39:44 +02:00
namesurname . surname = campi [ 1 ] + ' ' + campi [ 2 ] ;
2020-01-13 23:52:51 +01:00
} else {
2021-10-05 15:39:44 +02:00
namesurname . name = campi [ 0 ] + ' ' + campi [ 1 ] ;
2020-01-13 23:52:51 +01:00
namesurname . surname = campi [ 2 ] ;
}
2020-01-21 01:37:15 +01:00
} else if ( campi . length === 4 ) {
2021-10-05 15:39:44 +02:00
namesurname . name = campi [ 0 ] + ' ' + campi [ 1 ] ;
namesurname . surname = campi [ 2 ] + ' ' + campi [ 3 ] ;
2020-01-21 01:37:15 +01:00
} else if ( campi . length > 4 ) {
2021-10-05 15:39:44 +02:00
namesurname . name = campi [ 0 ] + ' ' + campi [ 1 ] ;
namesurname . surname = ' ' + campi [ 2 ] ;
2020-01-20 01:48:25 +01:00
for ( let ind = 3 ; ind < campi . length ; ind ++ ) {
2021-10-05 15:39:44 +02:00
namesurname . surname += ' ' + campi [ ind ] ;
2020-01-13 23:52:51 +01:00
}
}
2021-10-05 15:39:44 +02:00
return namesurname ;
2020-01-13 23:52:51 +01:00
} ,
2022-01-23 23:25:34 +01:00
isFileExists ( filename ) {
2024-12-05 14:12:51 +01:00
try {
return fs . existsSync ( filename ) ;
} catch ( e ) {
return false
}
2022-01-23 23:25:34 +01:00
} ,
2020-02-02 04:06:32 +01:00
getiPAddressUser ( req ) {
2020-01-27 15:07:53 +01:00
try {
const striniziale = '::ffff:' ;
2020-02-02 04:06:32 +01:00
if ( req . ip . indexOf ( striniziale ) >= 0 ) {
2021-10-05 15:39:44 +02:00
return req . ip . substring ( striniziale . length ) ;
2020-01-27 15:07:53 +01:00
} else {
return req . ip ; // Express
}
} catch ( e ) {
2021-10-05 15:39:44 +02:00
return '' ;
2020-01-27 15:07:53 +01:00
}
2020-01-30 01:19:25 +01:00
} ,
removespaces ( mystr ) {
2021-10-05 15:39:44 +02:00
return mystr . replace ( /\s+/g , '' ) ;
2020-01-30 01:19:25 +01:00
} ,
2024-04-04 18:43:17 +02:00
async ModificheConsentite ( req , table , fieldsvalue , idrec , user ) {
const { Circuit } = require ( '../models/circuit' ) ;
2021-01-18 00:48:17 +01:00
if ( table === 'sharewithus' ) {
return true ;
}
2024-03-21 22:58:46 +01:00
2021-02-18 12:19:35 +01:00
if ( table === 'hours' ) {
return true ;
}
2020-02-05 00:39:25 +01:00
if ( table === 'users' ) {
2024-03-21 21:22:57 +01:00
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 ) ) ) {
return true ;
}
}
2020-02-05 00:39:25 +01:00
if ( 'aportador_solidario' in fieldsvalue ) {
return true ;
}
2020-03-10 21:44:14 +01:00
if ( 'ALL' in fieldsvalue ) {
//++Todo: Cancellalo solo se sono io il creatore dell'utente ... o se posso!
2021-10-05 15:39:44 +02:00
return true ;
2020-03-10 21:44:14 +01:00
}
2024-04-04 18:43:17 +02:00
} else if ( table === 'circuits' ) {
if ( idrec ) {
// Permetti di fare modifiche se è un admin del circuito
return await Circuit . isCircuitAdmin ( idrec , req . user ? req . user . username : '' ) ;
}
} else if ( table === 'accounts' ) {
if ( idrec ) {
if ( 'fidoConcesso' in fieldsvalue ) {
// Permetti di fare modifiche se è un admin del circuito
return await Circuit . isCircuitAdmin ( idrec , req . user ? req . user . username : '' ) ;
}
}
2020-02-05 00:39:25 +01:00
}
2021-12-23 14:13:40 +01:00
if ( shared _consts . TABLES _PERM _CHANGE _FOR _USERS . includes ( table ) ) {
return true ;
}
2022-01-28 00:57:39 +01:00
if ( shared _consts . TABLES _PERM _NEWREC . includes ( table ) ) {
return true ;
}
2021-12-23 14:13:40 +01:00
2020-02-05 00:39:25 +01:00
return false ;
} ,
NotifyIfDelRecord ( table ) {
2021-10-05 15:39:44 +02:00
if ( ( table === 'users' ) || ( table === 'extralist' ) ||
2022-12-15 18:09:43 +01:00
( table === 'groups' ) || ( table === 'graduatorias' ) ) {
2020-02-05 00:39:25 +01:00
return true ;
}
return false ;
} ,
2020-03-10 21:44:14 +01:00
getFirstWord ( mystr ) {
2021-10-05 15:39:44 +02:00
const myarr = mystr . split ( ' ' ) ;
2020-03-10 21:44:14 +01:00
if ( myarr . length > 0 )
return myarr [ 0 ] ;
else
2021-10-05 15:39:44 +02:00
return mystr ;
2020-03-10 21:44:14 +01:00
} ,
getFirst2Car ( mystr ) {
if ( ! ! mystr )
return mystr . substring ( 0 , 2 ) + '.' ;
else
2021-10-05 15:39:44 +02:00
return '' ;
2020-03-10 21:44:14 +01:00
} ,
2020-05-19 00:18:13 +02:00
getmaxcol ( riga ) {
return Math . pow ( 2 , riga - 1 ) ;
} ,
2020-06-08 13:31:05 +02:00
getPrimoFuocoByIndCol ( col ) {
// let ris = Math.ceil(col - (col % 8)) + 1;
let ris = ( ( Math . ceil ( col / 8 ) - 1 ) * 8 ) + 1 ;
if ( ris <= 0 )
ris = 1 ;
2021-10-05 15:39:44 +02:00
return ris ;
2020-06-08 13:31:05 +02:00
} ,
getPrimaColFlotta ( col ) {
// let ris = Math.ceil(col - (col % 8)) + 1;
let ris = ( ( Math . ceil ( col / 64 ) - 1 ) * 64 ) + 1 ;
if ( ris <= 0 )
ris = 1 ;
2021-10-05 15:39:44 +02:00
return ris ;
2020-06-08 13:31:05 +02:00
} ,
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' ;
else if ( tipomsg === this . TipoMsg . SEND _MSG _DONO _RICEVUTO _CORRETTAMENTE )
mystr = 'Inviato Messaggio Dono Ricevuto Correttamente' ;
return mystr ;
2020-07-02 22:00:58 +02:00
} ,
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 '🇫🇷' ;
2020-07-13 23:35:05 +02:00
} ,
2020-06-08 13:31:05 +02:00
2020-07-13 23:35:05 +02:00
blockwords ( mystr ) {
2022-02-24 19:13:20 +01:00
const arrwords = [
'http' ,
'Http' ,
'Asasfasfas' ,
'://' ,
'mrbit' ,
'admin' ,
'superuser' ] ;
2022-02-12 22:12:49 +01:00
try {
for ( const myword of arrwords ) {
if ( mystr ) {
if ( mystr . includes ( myword ) ) {
return true ;
}
}
2020-09-04 00:06:49 +02:00
}
2022-02-12 22:12:49 +01:00
} catch ( e ) {
2020-07-13 23:35:05 +02:00
}
2020-01-27 15:07:53 +01:00
2020-07-13 23:35:05 +02:00
return false ;
} ,
isAlphaNumeric ( str ) {
let code , i , len ;
for ( i = 0 , len = str . length ; i < len ; i ++ ) {
code = str . charCodeAt ( i ) ;
if ( ! ( code > 47 && code < 58 ) && // numeric (0-9)
2022-12-15 18:09:43 +01:00
! ( code > 64 && code < 91 ) && // upper alpha (A-Z)
! ( code > 96 && code < 123 ) ) { // lower alpha (a-z)
2020-07-13 23:35:05 +02:00
return false ;
}
}
return true ;
2020-12-21 02:16:42 +01:00
} ,
2022-02-14 19:35:11 +01:00
isAlphaNumericAndSpecialCharacter ( str ) {
let code , i , len ;
for ( i = 0 , len = str . length ; i < len ; i ++ ) {
code = str . charCodeAt ( i ) ;
if ( ! ( code > 47 && code < 58 ) && // numeric (0-9)
2022-12-15 18:09:43 +01:00
! ( code > 63 && code < 91 ) && // upper alpha (A-Z) // e @
( code !== 46 ) && // . (punto)
( code !== 95 ) && // _
( code !== 45 ) && // -
! ( code > 96 && code < 123 ) ) { // lower alpha (a-z)
2022-02-14 19:35:11 +01:00
return false ;
}
}
return true ;
} ,
2020-12-21 02:16:42 +01:00
categorizeQueryString ( queryObj ) {
2021-10-05 15:39:44 +02:00
let query = { } ;
let order = { } ;
2020-12-21 02:16:42 +01:00
//extract query, order, filter value
for ( const i in queryObj ) {
if ( queryObj [ i ] ) {
// extract order
if ( i === 'order' ) {
2021-10-05 15:39:44 +02:00
order [ 'sort' ] = queryObj [ i ] ;
continue ;
2020-12-21 02:16:42 +01:00
}
// extract range
if ( i === 'range' ) {
2021-10-05 15:39:44 +02:00
let range _arr = [ ] ;
let query _arr = [ ] ;
2020-12-21 02:16:42 +01:00
// multi ranges
if ( queryObj [ i ] . constructor === Array ) {
for ( const r of queryObj [ i ] ) {
2021-10-05 15:39:44 +02:00
range _arr = r . split ( '-' ) ;
2020-12-21 02:16:42 +01:00
query _arr . push ( {
2022-12-15 18:09:43 +01:00
price : { $gt : range _arr [ 0 ] , $lt : range _arr [ 1 ] } ,
2021-10-05 15:39:44 +02:00
} ) ;
2020-12-21 02:16:42 +01:00
}
}
// one range
if ( queryObj [ i ] . constructor === String ) {
2021-10-05 15:39:44 +02:00
range _arr = queryObj [ i ] . split ( '-' ) ;
2020-12-21 02:16:42 +01:00
query _arr . push ( {
2022-12-15 18:09:43 +01:00
price : { $gt : range _arr [ 0 ] , $lt : range _arr [ 1 ] } ,
2021-10-05 15:39:44 +02:00
} ) ;
2020-12-21 02:16:42 +01:00
}
2022-12-15 18:09:43 +01:00
Object . assign ( query , { $or : query _arr } ) ;
2021-10-05 15:39:44 +02:00
delete query [ i ] ;
continue ;
2020-12-21 02:16:42 +01:00
}
2021-10-05 15:39:44 +02:00
query [ i ] = queryObj [ i ] ;
2020-12-21 02:16:42 +01:00
}
}
2022-12-15 18:09:43 +01:00
return { query , order } ;
2020-12-21 02:16:42 +01:00
} ,
2021-02-24 04:48:31 +01:00
dateToEpoch ( thedate ) {
const time = new Date ( thedate ) . getTime ( ) ;
return time - ( time % 86400000 ) ;
} ,
dateToEpochStr ( thedate ) {
const time = new Date ( thedate ) . getTime ( ) ;
return new Date ( time - ( time % 86400000 ) ) ;
2021-04-30 01:31:12 +02:00
} ,
async loadApps ( ) {
2023-12-09 11:55:58 +01:00
const Site = require ( '../models/site' ) ;
2022-07-23 17:48:33 +02:00
try {
this . MYAPPS = await Site . findAll ( 0 ) ;
2022-07-26 15:46:39 +02:00
// console.log('this.MYAPPS', this.MYAPPS);
2022-08-04 17:30:57 +02:00
} catch ( e ) {
2022-07-23 17:48:33 +02:00
console . error ( 'loadApps' , e ) ;
}
2021-04-30 01:31:12 +02:00
} ,
2023-12-11 20:48:52 +01:00
2022-07-23 17:48:33 +02:00
async getApps ( ) {
2021-04-30 01:31:12 +02:00
if ( this . MYAPPS . length <= 0 )
2022-07-23 17:48:33 +02:00
await this . loadApps ( ) ;
2021-04-30 01:31:12 +02:00
return this . MYAPPS ;
2021-05-10 01:50:40 +02:00
} ,
getPaymentTypesById ( idmetodo ) {
2021-10-05 15:39:44 +02:00
return shared _consts . PaymentTypes [ idmetodo ] ;
2021-05-10 01:50:40 +02:00
} ,
2021-02-24 04:48:31 +01:00
2021-10-05 00:20:12 +02:00
getVersionint ( versionstr ) {
2021-10-28 00:38:10 +02:00
let versionarr = versionstr . split ( '.' ) ;
let version = 0 ;
versionarr = versionarr . reverse ( ) ;
for ( let i = 0 ; i < versionarr . length ; i ++ ) {
2022-01-14 23:54:33 +01:00
version += versionarr [ i ] * Math . pow ( 10 , i * 2 ) ;
2021-10-28 00:38:10 +02:00
}
2021-10-05 00:20:12 +02:00
return parseInt ( version ) ;
2021-10-05 15:39:44 +02:00
} ,
2021-10-05 00:20:12 +02:00
2024-12-02 19:37:53 +01:00
convstrToInt ( mystr ) {
try {
const parsed = parseInt ( mystr , 10 ) ; // Specifica la base come 10
return isNaN ( parsed ) ? 0 : parsed ; // Restituisce 0 se il valore è NaN
} catch ( e ) {
return 0 ; // Se c'è un errore, restituisce 0
}
} ,
isValidNumber ( value ) {
// Controlla se il valore è un numero valido
return ! isNaN ( value ) && value !== null && value !== '' ;
} ,
2024-12-05 14:12:51 +01:00
2021-10-28 00:38:10 +02:00
invertescapeslash ( mystr ) {
2022-09-19 19:40:30 +02:00
return mystr . replace ( /Ç/g , '/' ) ;
2021-10-28 00:38:10 +02:00
} ,
2022-01-14 23:54:33 +01:00
isNumber ( n ) {
return typeof ( n ) != 'boolean' && ! isNaN ( n ) && n ;
2021-12-29 18:26:08 +01:00
} ,
2021-12-03 22:48:05 +01:00
getNumObj ( obj ) {
let count = 0 ;
for ( let properties in obj ) {
count = count + 1 ;
}
return count ;
} ,
2022-02-08 23:14:08 +01:00
getNomeCognomeEUserNameByUser ( user ) {
2022-02-24 19:13:20 +01:00
let nome = ` ${ user . name } ${ user . surname } ( ${ user . username } ) ` ;
2022-02-08 23:14:08 +01:00
if ( ! user . name ) {
nome = user . username ;
}
return nome ;
} ,
2022-02-09 19:48:39 +01:00
sulServer ( ) {
2022-02-24 19:13:20 +01:00
return process . env . LOCALE !== '1' ;
2022-02-12 02:20:07 +01:00
} ,
2022-03-04 15:30:11 +01:00
refreshAllTablesInMem ( idapp , table , updatebot , username ) {
2022-02-27 16:56:02 +01:00
const telegrambot = require ( '../telegram/telegrambot' ) ;
2022-05-14 00:31:53 +02:00
if ( table === shared _consts . TAB _BOTS || updatebot ) {
2022-02-27 16:56:02 +01:00
telegrambot . reloadMenuBot ( idapp ) ;
2022-03-04 15:30:11 +01:00
}
if ( table === shared _consts . TAB _USERS ) {
telegrambot . deleteRecInMemByUsername ( idapp , username ) ;
2022-02-27 16:56:02 +01:00
} else if ( table === shared _consts . TAB _SITES ) {
telegrambot . reloadSites ( ) ;
}
2022-03-01 23:50:58 +01:00
} ,
downloadImage ( url , filepath ) {
2024-02-28 23:56:23 +01:00
const download = require ( 'image-downloader' ) ;
2022-03-02 20:18:29 +01:00
try {
return download . image ( {
url ,
2022-03-06 00:48:33 +01:00
dest : filepath ,
2022-03-02 20:18:29 +01:00
} ) ;
2022-03-06 00:48:33 +01:00
} catch ( e ) {
2022-03-03 20:32:04 +01:00
console . error ( 'Err download image' , e ) ;
2022-03-02 20:18:29 +01:00
return false ;
}
2022-03-01 23:50:58 +01:00
} ,
2022-02-27 16:56:02 +01:00
2022-11-02 22:32:54 +01:00
async checkStr ( msg , mystr , user , cmd ) {
if ( msg . includes ( mystr ) ) {
if ( cmd === 1 ) {
msg = msg . replace ( mystr , await this . getTimeExpReg ( user . idapp , user . username ) ) ;
}
}
return msg ;
} ,
2024-02-08 01:34:30 +01:00
getUnsubsribeUrl ( mylocalsconf ) {
if ( mylocalsconf ) {
const baseurl = this . getHostByIdApp ( mylocalsconf . idapp ) ;
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 ;
}
return '' ;
} ,
2022-11-02 22:32:54 +01:00
async convertSpecialTags ( user , msg ) {
2022-03-06 00:48:33 +01:00
try {
2022-09-02 02:25:38 +02:00
if ( ! msg )
return msg ;
2023-12-17 16:20:44 +01:00
2022-03-06 00:48:33 +01:00
if ( ! ! user ) {
2023-12-17 16:20:44 +01:00
if ( msg . includes ( '{host}' ) ) {
msg = msg . replace ( '{host}' , this . getHostByIdApp ( user . idapp ) ) ;
}
2022-11-02 22:32:54 +01:00
if ( msg . includes ( '{appname}' ) )
msg = msg . replace ( '{appname}' , this . getNomeAppByIdApp ( user . idapp ) ) ;
2022-03-06 00:48:33 +01:00
msg = msg . replace ( '{username}' , user . username ) ;
2024-04-04 18:43:17 +02:00
// msg = await this.checkStr(msg, '{time_exp_reg}', user, 1);
2022-03-06 00:48:33 +01:00
msg = msg . replace ( '{name}' , user . name ? user . name : user . username ) ;
msg = msg . replace ( '{surname}' , user . surname ? user . surname : '' ) ;
2024-02-08 01:34:30 +01:00
2024-02-17 14:13:39 +01:00
msg = msg . replace ( '{urlunsubscribe_user}' , this . getUnsubsribeUrl _User ( user ) ) ;
2024-02-08 01:34:30 +01:00
2022-03-09 14:53:09 +01:00
msg = msg . replace ( '{aportador_solidario}' , user . aportador _solidario ? user . aportador _solidario : '' ) ;
2022-03-06 00:48:33 +01:00
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 ) ;
}
return msg ;
} ,
2022-12-15 18:09:43 +01:00
getUserInfoMsg : function ( idapp , myuser , usernametelegram = '' , name _telegram = '' ,
surname _telegram = '' ) {
2022-03-06 00:48:33 +01:00
let msg = '' ;
try {
const name = myuser . username +
2022-12-15 18:09:43 +01:00
( myuser . name ? ` ( ${ myuser . name } ${ myuser . surname } ) ` : '' ) ;
2022-03-06 00:48:33 +01:00
const linkuserprof = this . getHostByIdApp ( idapp ) + '/my/' +
2022-12-15 18:09:43 +01:00
myuser . username ;
2022-03-06 00:48:33 +01:00
2023-06-05 16:36:00 +02:00
msg = ` <br>👉🏻 <a href=" ${ linkuserprof } "> ${ name } </a><br>email: ${ myuser . email } ` ;
2022-03-06 00:48:33 +01:00
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' )
2022-12-15 18:09:43 +01:00
? myuser . profile . firstname _telegram
: name _telegram ;
2022-03-06 00:48:33 +01:00
let surname _tg = myuser . profile && myuser . profile . hasOwnProperty ( 'lastname_telegram' )
2022-12-15 18:09:43 +01:00
? myuser . profile . lastname _telegram
: surname _telegram ;
2022-03-06 00:48:33 +01:00
2023-01-12 01:03:10 +01:00
let namesurnametg = '' ;
if ( name _tg || surname _tg )
namesurnametg = ` [ ${ name _tg } ${ surname _tg } ] ` ; ;
2022-03-06 00:48:33 +01:00
if ( u _tg ) {
2023-06-05 16:36:00 +02:00
msg += ` <br><br>Apri chat 👉🏻 https://t.me/ ${ u _tg } ` ;
2022-03-06 00:48:33 +01:00
}
2022-06-16 20:34:42 +02:00
} catch ( e ) {
2022-03-06 00:48:33 +01:00
console . error ( 'getUserInfoMsg' , e ) ;
}
return msg ;
} ,
2023-01-08 19:20:02 +01:00
getUserShortInfoMsg : function ( idapp , myuser , usernametelegram = '' , name _telegram = '' ,
surname _telegram = '' ) {
let msg = '' ;
try {
const name = myuser . username +
( myuser . name ? ` ( ${ myuser . name } ${ myuser . surname } ) ` : '' ) ;
2023-06-20 01:07:57 +02:00
const linkuserprof = this . getLinkUserProfile ( idapp , myuser . username ) ;
2023-01-12 01:03:10 +01:00
let u _tg = myuser . profile && myuser . profile . hasOwnProperty ( 'username_telegram' ) ? myuser . profile . username _telegram : usernametelegram ;
2023-01-08 19:20:02 +01:00
msg = ` <br>Vedi Profilo sulla APP di <a href=" ${ linkuserprof } "> ${ name } </a> ` ;
msg += ` <br>Telegram: @ ${ u _tg } ` ;
} catch ( e ) {
console . error ( 'getUserInfoMsg' , e ) ;
}
return msg ;
} ,
2022-12-15 18:09:43 +01:00
getlinkRelativeRequestNewPassword : function ( idapp , email , tokenforgot ) {
2022-12-11 18:04:02 +01:00
const strlinkreg = process . env . LINK _UPDATE _PASSWORD +
2022-12-15 18:09:43 +01:00
` ?idapp= ${ idapp } &email= ${ email } &tokenforgot= ${ tokenforgot } ` ;
2022-03-08 01:01:20 +01:00
return strlinkreg ;
} ,
2022-03-06 00:48:33 +01:00
2022-12-15 18:09:43 +01:00
getlinkRequestNewPassword : function ( idapp , email , tokenforgot ) {
2022-12-11 18:04:02 +01:00
const strlinkreg = this . getHostByIdApp ( idapp ) + this . getlinkRelativeRequestNewPassword ( idapp , email , tokenforgot ) ;
return strlinkreg ;
} ,
2024-08-29 23:30:58 +02:00
execScriptOnServer : async function ( idapp , script , dir , listafiles , extfiles ) {
return new Promise ( async ( resolve , reject ) => {
exec ( script , async ( error , stdout , stderr ) => { // Aggiunto async qui
if ( error ) {
console . error ( ` error: ${ error } ` ) ;
return reject ( ` Execution failed: ${ error } ` ) ;
}
if ( stderr ) {
console . error ( ` stderr: ${ stderr } ` ) ;
}
// Se vuoi mantenere questa parte, puoi decommentarla
// if (stdout) {
// console.log(`OUT: ${stdout}`);
// }
let arrout = [ ] ;
let arrscripts = stdout
. split ( '\n' )
. filter ( ( script ) => script . trim ( ) !== '' )
. map ( ( script ) => script . replace ( /\//g , '' ) ) ;
for ( let i = 0 ; i < arrscripts . length ; i ++ ) {
let label = arrscripts [ i ] ;
2024-09-06 19:57:09 +02:00
let sock = false ;
2024-08-29 23:30:58 +02:00
let description = '' ;
if ( listafiles ) {
if ( arrscripts [ i ] . endsWith ( '.sh' ) ) {
let labelFilePath = path . join ( _ _dirname , '..' , '..' , '..' , dir , ` ${ arrscripts [ i ] } ` ) ;
// Verifica se il file esiste
try {
// console.log(__dirname);
// console.log(labelFilePath);
// Leggi il contenuto del file .label
const labelContent = await fs . readFileSync ( labelFilePath , 'utf-8' ) ;
const lines = labelContent . split ( '\n' ) ;
for ( let i = 0 ; i < lines . length ; i ++ ) {
let linea = lines [ i ] ;
// se la linea inizia con #DATA
if ( linea . indexOf ( '#DATA' ) !== - 1 ) {
// estrai la linea separata da |
let arrparams = linea . split ( '|' ) ;
if ( arrparams && arrparams . length > 0 ) {
let paramstr = arrparams [ 1 ] . trim ( ) ;
let value = arrparams [ 2 ] . trim ( ) ;
if ( paramstr === 'TITLE' ) {
label = value ;
} else if ( paramstr === 'DESCRIZ' ) {
description = value ;
2024-09-06 19:57:09 +02:00
} else if ( paramstr === 'SOCK' ) {
2024-11-02 19:25:37 +01:00
sock = ( value ? ( value . toLowerCase ( ) === 'true' ) : false ) ;
2024-08-29 23:30:58 +02:00
}
}
}
}
} catch ( error ) {
// Se desideri, puoi tenere un avviso o un log qui
}
}
} else {
label = '' ;
}
if ( ( label ) && ( ! extfiles || ( extfiles && arrscripts [ i ] . endsWith ( '.' + extfiles ) ) ) ) {
2024-09-06 19:57:09 +02:00
arrout . push ( { label , value : arrscripts [ i ] , description , sock } ) ;
2024-08-29 23:30:58 +02:00
}
}
resolve ( { error , stdout , stderr , arrout } ) ;
} ) ;
} ) ;
} ,
2024-09-06 19:57:09 +02:00
execScriptNoOutput : async function ( script ) {
return new Promise ( async ( resolve , reject ) => {
console . log ( 'execScriptNoOutput:' , script ) ;
exec ( script , async ( error , stdout , stderr ) => { // Aggiunto async qui
if ( error ) {
console . error ( ` error: ${ error } ` ) ;
}
if ( stderr ) {
console . error ( ` stderr: ${ stderr } ` ) ;
}
resolve ( ! error && ! stderr ) ;
} ) ;
} ) ;
} ,
2024-08-29 23:30:58 +02:00
execScriptWithInputOnServer : async function ( idapp , script ) {
return new Promise ( ( resolve , reject ) => {
const rl = readline . createInterface ( {
input : process . stdin ,
output : process . stdout ,
} ) ;
// Esegui il processo
const child = spawn ( 'bash' , [ script ] ) ;
let outputData = '' ;
let errorData = '' ;
// Gestisci l'output standard
child . stdout . on ( 'data' , ( data ) => {
outputData += data . toString ( ) ; // Accumulate output data
console . log ( ` Output: ${ data } ` ) ;
// Chiedi l'input dell'utente
rl . question ( 'Your input: ' , ( answer ) => {
child . stdin . write ( ` ${ answer } \n ` ) ; // Invia la risposta allo script
} ) ;
} ) ;
// Gestisci l'output di errore
child . stderr . on ( 'data' , ( data ) => {
errorData += data . toString ( ) ; // Accumulate error data
console . error ( ` Error: ${ data } ` ) ;
} ) ;
// Gestisci la chiusura del processo
child . on ( 'close' , ( code ) => {
console . log ( ` Process exited with code ${ code } ` ) ;
rl . close ( ) ; // Chiusura dell'interfaccia readline
// Risolvi la promessa con i dati raccolti
if ( code !== 0 ) {
reject ( new Error ( ` Process exited with code ${ code } : ${ errorData } ` ) ) ; // Rifiuta in caso di errore
} else {
resolve ( { stdout : outputData , stderr : errorData } ) ;
}
} ) ;
// Gestisci errori nel processo
child . on ( 'error' , ( error ) => {
reject ( new Error ( ` Failed to start process: ${ error . message } ` ) ) ;
} ) ;
} ) ;
} ,
execScriptByTelegram : function ( idapp , msg , script , testo ) {
2022-12-15 18:09:43 +01:00
const { exec } = require ( 'child_process' ) ;
2022-03-12 21:38:19 +01:00
const telegrambot = require ( '../telegram/telegrambot' ) ;
const idchat = msg . chat . id ;
console . log ( testo + ' (' + script + ')' ) ;
telegrambot . local _sendMsgTelegramByIdTelegram ( idapp , idchat , testo ) ;
exec ( script , ( error , stdout , stderr ) => {
if ( error ) {
telegrambot . local _sendMsgTelegramByIdTelegram ( idapp , idchat , 'ERROR: ' + error . message ) ;
console . log ( ` error: ${ error . message } ` ) ;
return ;
}
if ( stderr ) {
telegrambot . local _sendMsgTelegramByIdTelegram ( idapp , idchat , 'ERROR: ' + stderr ) ;
console . log ( ` stderr: ${ stderr } ` ) ;
return ;
}
// console.log(` ... stdout: ${stdout}`);
telegrambot . local _sendMsgTelegramByIdTelegram ( idapp , idchat , stdout ) ;
} ) ;
2022-06-16 20:34:42 +02:00
} ,
2022-03-12 21:38:19 +01:00
2022-07-26 15:46:39 +02:00
capitalize ( value ) {
if ( ! value ) {
2022-08-04 17:30:57 +02:00
return '' ;
2022-07-26 15:46:39 +02:00
}
2022-08-04 17:30:57 +02:00
const myval = value . toString ( ) ;
return myval . charAt ( 0 ) . toUpperCase ( ) + myval . slice ( 1 ) ;
2022-07-26 15:46:39 +02:00
} ,
2024-03-06 20:46:00 +01:00
truncateString ( str , maxLength ) {
if ( str . length > maxLength ) {
return str . slice ( 0 , maxLength ) + '...' ;
} else {
return str ;
}
} ,
2024-12-05 14:12:51 +01:00
removeFileExtension ( filename ) {
// Trova l'ultima occorrenza del punto nel nome del file
const lastDotIndex = filename . lastIndexOf ( '.' ) ;
// Se non c'è un punto o il punto è all'inizio del nome file,
// restituisci il nome file originale
if ( lastDotIndex === - 1 || lastDotIndex === 0 ) {
return filename ;
}
// Altrimenti, restituisci la parte del nome file prima dell'ultimo punto
return filename . substring ( 0 , lastDotIndex ) ;
} ,
2024-03-06 20:46:00 +01:00
removeSpanAndDivTags ( text ) {
// Rimozione dei tag <span> e </span> dalla stringa di testo
const spanRegex = /<span[^>]*>|<\/span>/gi ;
const cleanedText = text . replace ( spanRegex , '' ) ;
// Rimozione dei tag <div> e </div> dalla stringa di testo
const divRegex = /<div[^>]*>|<\/div>/gi ;
const finalText = cleanedText . replace ( divRegex , '' ) ;
return finalText ;
} ,
2022-07-26 15:46:39 +02:00
2024-02-27 22:08:06 +01:00
firstchars ( value , numchars = 200 , continua , link ) {
2022-07-26 15:46:39 +02:00
if ( ! value ) {
2022-08-04 17:30:57 +02:00
return '' ;
2022-07-26 15:46:39 +02:00
}
try {
2024-03-06 20:46:00 +01:00
value = this . convertHTMLTagsForTelegram ( value ) ;
value = this . removeSpanAndDivTags ( value ) ;
truncatedValue = this . truncateString ( value , numchars ) ;
2024-05-10 01:59:54 +02:00
if ( str . length < maxLength ) {
continua = false ;
}
2024-03-06 20:46:00 +01:00
// Aggiungi il testo aggiuntivo per indicare il troncamento
if ( continua ) {
if ( link ) {
truncatedValue += ` <em> (... <a href=" ${ link } ">continua sulla App</a>)</em> ` ;
2024-02-27 22:08:06 +01:00
} else {
2024-03-06 20:46:00 +01:00
truncatedValue += ` <em> (... continua sulla App)</em> ` ;
2024-02-27 22:08:06 +01:00
}
2024-03-06 20:46:00 +01:00
} else {
truncatedValue += ' ...' ;
2024-02-27 22:08:06 +01:00
}
2024-03-06 20:46:00 +01:00
2024-02-28 00:20:02 +01:00
return truncatedValue ;
2022-07-26 15:46:39 +02:00
} catch ( e ) {
2022-08-04 17:30:57 +02:00
return value ;
2022-07-26 15:46:39 +02:00
}
} ,
2024-03-06 20:46:00 +01:00
removeFontTags ( text ) {
// Rimozione dei tag <font> e </font> dalla stringa di testo
const regex = /<font[^>]*>|<\/font>/gi ;
const cleanedText = text . replace ( regex , '' ) ;
return cleanedText ;
} ,
2022-07-10 01:25:19 +02:00
removeAtChar ( mystr ) {
2022-08-04 17:30:57 +02:00
if ( mystr && mystr [ 0 ] === '@' ) {
2022-07-10 01:25:19 +02:00
return mystr = mystr . substring ( 1 ) ;
}
return mystr ;
} ,
2022-07-21 00:21:03 +02:00
updateQueryStringParameter ( uri , key , value ) {
2023-04-17 00:11:36 +02:00
if ( uri === '' || ! uri )
2022-07-23 17:48:33 +02:00
return '' ;
2022-08-04 17:30:57 +02:00
var re = new RegExp ( '([?&])' + key + '=.*?(&|$)' , 'i' ) ;
var separator = uri . indexOf ( '?' ) !== - 1 ? '&' : '?' ;
2022-07-21 00:21:03 +02:00
if ( uri . match ( re ) ) {
2022-08-04 17:30:57 +02:00
return uri . replace ( re , '$1' + key + '=' + value + '$2' ) ;
2022-07-21 00:21:03 +02:00
} else {
2022-08-04 17:30:57 +02:00
return uri + separator + key + '=' + value ;
2022-07-21 00:21:03 +02:00
}
} ,
isArray ( val ) {
2022-08-04 17:30:57 +02:00
return Array . isArray ( val ) ;
2022-07-21 00:21:03 +02:00
} ,
2022-08-04 17:30:57 +02:00
getContentByTypeMsg ( typemsg ) {
2022-07-21 00:21:03 +02:00
} ,
2022-07-26 15:46:39 +02:00
getContentNotifByParams ( params , content , typesend ) {
if ( typesend === shared _consts . TypeSend . TELEGRAM ) {
let myhost = this . getHostByIdApp ( params . idapp ) ;
2023-04-12 15:37:54 +02:00
if ( params . textaddTelegram ) {
2023-08-27 23:55:31 +02:00
content = content + '\n' + params . textaddTelegram ;
}
if ( params . linkaddTelegram ) {
2023-04-12 15:37:54 +02:00
if ( params . openUrl )
2023-08-27 23:55:31 +02:00
content = content + '\n' + '<a href="' + myhost + params . openUrl + '">' + params . linkaddTelegram + '</a>' ;
2023-04-12 15:37:54 +02:00
}
2023-08-27 23:55:31 +02:00
2022-09-18 20:17:24 +02:00
/ * i f ( p a r a m s . o p e n U r l )
2022-07-26 15:46:39 +02:00
content = content + '\n' + '<a href="' + myhost + params . openUrl + '">' + i18n . _ _ ( 'OPEN PAGE' ) + '</a>' ;
2024-08-29 23:30:58 +02:00
2022-09-18 20:17:24 +02:00
* /
2022-07-26 15:46:39 +02:00
}
return content ;
2022-08-04 17:30:57 +02:00
} ,
2022-07-26 15:46:39 +02:00
2022-09-18 20:17:24 +02:00
getAhref ( username , link ) {
return ` <a href=' ${ link } '> ${ username } </a> ` ;
2022-09-19 14:37:57 +02:00
} ,
2023-10-21 15:27:53 +02:00
2023-10-01 01:24:47 +02:00
replaceStringAtEnd ( inputString , searchString , replacement ) {
// Create a regular expression that matches the searchString at the end of the inputString
const regex = new RegExp ( searchString + '$' ) ;
// Use the replace method with the regular expression to replace the string
const result = inputString . replace ( regex , replacement ) ;
return result ;
} ,
2022-09-18 20:17:24 +02:00
2023-10-01 01:24:47 +02:00
getstrDateTimeEvent ( myevent ) {
let mystr = '' ;
// 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 ) )
} else {
mystr = i18n . _ _ ( 'DATE_2DAYS' , this . getstrDateLong ( myevent . dateTimeStart ) , this . getstrTime ( myevent . dateTimeStart ) ,
this . getstrDateLong ( myevent . dateTimeEnd ) , this . getstrTime ( myevent . dateTimeEnd ) )
}
return '🗓 ' + mystr ;
} ,
getDoveStrByEvent ( myrec ) {
let dove = '🏠 ' ;
if ( myrec . mycities && myrec . mycities . length > 0 ) {
dove += myrec . mycities [ 0 ] . comune + ' (' + myrec . mycities [ 0 ] . prov + ')'
}
return dove ;
} ,
async getDescrEstesaStrByEvent ( myrec ) {
let mystr = '' ;
2024-02-06 20:12:54 +01:00
mystr = await this . firstchars ( this . replaceStringAtEnd ( myrec . note , '</div>' , '' ) , 800 ) ;
2023-10-01 01:24:47 +02:00
if ( mystr )
mystr = 'ℹ ️ ' + mystr
return mystr ;
} ,
async getEventForTelegram ( myrec , mydescr , userorig ) {
try {
let datastr = this . getstrDateTimeEvent ( myrec ) ;
let dovestr = this . getDoveStrByEvent ( myrec ) ;
let descrestesa = await this . getDescrEstesaStrByEvent ( myrec ) ;
let organizedby = myrec . organisedBy ;
let contributo = myrec . contribstr ;
let newdescr = i18n . _ _ ( 'NEW_EVENT' , userorig , datastr , mydescr , dovestr ) ;
let newdescrtelegram = i18n . _ _ ( 'NEW_EVENT_TELEGRAM' , datastr , mydescr , dovestr , descrestesa , userorig ) ;
if ( organizedby ) {
newdescrtelegram += i18n . _ _ ( 'ORGANIZED_BY' , organizedby ) ;
}
if ( contributo ) {
newdescrtelegram += i18n . _ _ ( 'CONTRIB' , contributo ) ;
}
2024-02-06 20:12:54 +01:00
newdescrtelegram += i18n . _ _ ( 'EVENT_ADDED_FROM' , userorig ) ;
return { newdescr , newdescrtelegram }
} catch ( e ) {
console . error ( 'Error' , e ) ;
}
} ,
2024-11-03 19:15:35 +01:00
addRowTelegram ( icon , title , content , acapo , acapofine , islink ) {
2024-02-27 22:08:06 +01:00
let mystr = '' ;
let descrcontent = content ;
if ( islink ) {
title = ` <a href=" ${ content } "> ${ title } </a> ` ;
descrcontent = '' ;
}
2024-11-03 19:15:35 +01:00
mystr += ` ${ icon } <strong> ${ title } </strong> ` ;
if ( acapo ) {
mystr += ` \n ` ;
} else {
mystr += ` : ` ;
}
2024-02-27 22:08:06 +01:00
if ( descrcontent ) {
mystr += ` ${ descrcontent } \n ` ;
2024-11-03 19:15:35 +01:00
if ( acapofine ) {
2024-02-27 22:08:06 +01:00
mystr += ` \n ` ;
}
}
return mystr ;
} ,
async getInCambioDiByRec ( myrec ) {
2024-02-28 23:56:23 +01:00
const { Contribtype } = require ( '../models/contribtype' ) ;
2024-02-27 22:08:06 +01:00
try {
2024-04-19 18:12:10 +02:00
const idapp = myrec . idapp ;
if ( ! idapp )
return '' ;
const contribtype = await Contribtype . findAllIdApp ( idapp ) ;
2024-02-27 22:08:06 +01:00
let mystr = '' ;
for ( const contribId of myrec . idContribType ) {
const reccontr = contribtype . find ( ( rec ) => rec . _id . toString ( ) === contribId ) ;
if ( reccontr ) {
if ( mystr ) {
mystr += ', ' ;
}
mystr += reccontr . label ;
}
}
return mystr ;
} catch ( e ) {
}
} ,
async getStatusSkillByRec ( myrec , onlyifNoDiPersona ) {
2024-02-28 23:56:23 +01:00
const { StatusSkill } = require ( '../models/statusSkill' ) ;
2024-02-27 22:08:06 +01:00
try {
2024-04-19 18:12:10 +02:00
const idapp = myrec . idapp ;
if ( ! idapp )
return '' ;
const statusskill = await StatusSkill . findAllIdApp ( idapp ) ;
2024-02-27 22:08:06 +01:00
let mystr = '' ;
if ( onlyifNoDiPersona ) {
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 ) ;
if ( reccontr ) {
if ( mystr ) {
mystr += ' e ' ;
}
mystr += reccontr . descr ;
}
}
return mystr ;
} catch ( e ) {
}
} ,
getIconByAdType ( adType ) {
if ( adType === shared _consts . AdType . OFFRO )
return '🟢' ;
else if ( adType === shared _consts . AdType . CERCO )
return '🔴' ;
return '' ;
} ,
async getCategoriaSkillByRec ( myrec ) {
2024-02-28 23:56:23 +01:00
const { Skill } = require ( '../models/skill' ) ;
const { Sector } = require ( '../models/sector' ) ;
2024-02-27 22:08:06 +01:00
try {
2024-04-19 18:12:10 +02:00
// console.log('myrec', myrec);
const idapp = myrec . idapp ;
if ( ! idapp )
return '' ;
const skillrec = await Skill . findAllIdApp ( idapp ) ;
const sectorrec = await Sector . findAllIdApp ( idapp ) ;
2024-02-27 22:08:06 +01:00
let mystr = '' ;
2024-02-28 15:02:02 +01:00
const recsec = sectorrec . find ( ( rec ) => rec . _id === myrec . idSector ) ;
if ( recsec ) {
mystr += recsec . descr ;
}
2024-02-27 22:08:06 +01:00
const rec = skillrec . find ( ( rec ) => rec . _id === myrec . idSkill ) ;
if ( rec ) {
2024-02-28 15:02:02 +01:00
mystr += ' 👉🏻 ' + rec . descr ;
2024-02-27 22:08:06 +01:00
}
return mystr ;
} catch ( e ) {
}
} ,
async getCategoriaGoodByRec ( myrec ) {
2024-02-28 23:56:23 +01:00
const { SectorGood } = require ( '../models/sectorgood' ) ;
// const { Good } = require('../models/good');
2024-02-27 22:08:06 +01:00
// const goodrec = await Good.findAllIdApp(idapp);
try {
2024-04-19 18:12:10 +02:00
const idapp = myrec . idapp ;
if ( ! idapp )
return '' ;
const secgoodrec = await SectorGood . findAllIdApp ( idapp ) ;
2024-02-27 22:08:06 +01:00
let mystr = '' ;
const rec = secgoodrec . find ( ( rec ) => rec . _id === myrec . idSectorGood ) ;
// const rec = goodrec.find((rec) => rec._id === myrec.idSectorGood);
if ( rec ) {
mystr += rec . descr ;
}
return mystr ;
} catch ( e ) {
}
} ,
getComuniEProvinceByRec ( myrec ) {
try {
let mystr = '' ;
if ( myrec . hasOwnProperty ( 'mycities' ) ) {
let ind = 0 ;
for ( const city of myrec . mycities ) {
if ( ind > 0 )
mystr += ', '
mystr += city . comune + ' (' + city . prov + ')' ;
ind ++ ;
}
}
return mystr ;
} catch ( e ) {
}
} ,
2024-09-18 13:11:47 +02:00
convertAndTruncateHTMLForTelegram ( text , maxLength = 200 , link = '' ) {
const tagMap = {
"<ul>" : "" , "<ol>" : "" , "<li>" : "\n• " , "</ul>" : "" , "</ol>" : "" , "</li>" : "" ,
"<br>" : "\n" , "<div>" : "" , "</div>" : "\n"
} ;
// Rimuoviamo specificamente <b>\n</b>
text = text . replace ( /<b>\n<\/b>/g , '' ) ;
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 ( ) ;
if ( text . length <= maxLength ) {
return text ;
}
// Tronchiamo il testo
let truncated = text . slice ( 0 , maxLength ) ;
let openTags = [ ] ;
// Troviamo tutti i tag aperti
const regex = /<(\w+)[^>]*>/g ;
let match ;
while ( ( match = regex . exec ( truncated ) ) !== null ) {
if ( ! truncated . includes ( ` </ ${ match [ 1 ] } > ` , match . index ) ) {
openTags . push ( match [ 1 ] ) ;
}
}
// Rimuoviamo l'ultima parola parziale
truncated = truncated . replace ( /\S+$/ , '' ) ;
let strcontinua = '' ;
if ( link ) {
strcontinua = ` <em> (... <a href=" ${ link } ">continua sulla App</a>)</em> ` ;
} else {
strcontinua = ` <em> (... continua sulla App)</em> ` ;
}
// Aggiungiamo '...' e chiudiamo i tag aperti
truncated += strcontinua ;
while ( openTags . length > 0 ) {
truncated += ` </ ${ openTags . pop ( ) } > ` ;
}
return truncated ;
} ,
convertHTMLTagsForTelegram ( text ) {
2024-02-28 11:37:29 +01:00
const tagMap = {
"<ul>" : "" ,
2024-09-18 13:11:47 +02:00
"<ol>" : "" ,
"<li>" : "\n• " ,
2024-02-28 11:37:29 +01:00
"</ul>" : "" ,
"</ol>" : "" ,
2024-09-18 13:11:47 +02:00
"</li>" : "" ,
"<br>" : "\n" ,
"<div>" : "" ,
"</div>" : "\n"
2024-02-28 11:37:29 +01:00
} ;
2024-09-18 13:11:47 +02:00
// 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 => {
const replacement = tagMap [ tag ] ;
text = text . replaceAll ( tag , replacement ) ;
2024-02-28 11:37:29 +01:00
} ) ;
2024-09-18 13:11:47 +02:00
// Rimuoviamo gli spazi bianchi all'inizio e alla fine di ogni riga
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' ) ;
// Rimuoviamo le righe vuote alla fine del testo
text = text . replace ( /\n+$/ , '' ) ;
text = text . replace ( /<b>\n<\/b>/g , '' ) ;
return text . trim ( ) ;
2024-02-28 11:37:29 +01:00
} ,
2024-02-27 22:08:06 +01:00
async getAnnuncioForTelegram ( myrec , tablerec , mydescr , userorig , nuovo ) {
2024-02-06 20:12:54 +01:00
try {
let newdescr = '' ;
2024-02-27 22:08:06 +01:00
let out = '' ;
let tiposcambio = ''
let iconascambio = '🟢' ;
2024-09-30 14:50:19 +02:00
let lang = 'it' ;
2024-02-27 22:08:06 +01:00
let datastr = '' ;
let dovestr = '' ;
let organizedby = '' ;
let contributo = '' ;
2024-09-29 16:58:14 +02:00
let img = '' ;
2024-02-27 22:08:06 +01:00
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' ;
} else if ( tablerec === shared _consts . TABLES _MYHOSPS ) {
2024-09-30 00:05:47 +02:00
iconascambio = this . getIconByAdType ( myrec . adType ) ;
if ( myrec . adType === shared _consts . AdType . CERCO )
tiposcambio = 'Cerco' ;
else
tiposcambio = 'Offro' ;
2024-02-27 22:08:06 +01:00
if ( myrec . typeHosp === shared _consts . TYPEHOSP _OSPITALITA )
2024-09-30 00:05:47 +02:00
tiposcambio += ' Ospitalità' ;
2024-02-27 22:08:06 +01:00
else if ( myrec . typeHosp === shared _consts . TYPEHOSP _SCAMBIOCASA )
2024-09-30 00:05:47 +02:00
tiposcambio += ' Scambio Casa' ;
2024-02-27 22:08:06 +01:00
} else if ( tablerec === shared _consts . TABLES _MYBACHECAS ) {
datastr = this . getstrDateTimeEvent ( myrec ) ;
organizedby = myrec . organisedBy ;
contributo = myrec . contribstr ;
2024-02-06 20:12:54 +01:00
}
2024-03-06 20:46:00 +01:00
if ( tablerec === shared _consts . TABLES _MYGOODS ) {
newdescr = i18n . _ _ ( 'Good' , userorig , mydescr ) ;
} else if ( tablerec === shared _consts . TABLES _MYSKILLS ) {
newdescr = i18n . _ _ ( 'Service' , userorig , mydescr ) ;
} else if ( tablerec === shared _consts . TABLES _MYHOSPS ) {
newdescr = i18n . _ _ ( 'Hosp' , userorig , mydescr ) ;
2024-02-27 22:08:06 +01:00
}
2024-04-09 21:56:50 +02:00
let contatto = userorig ;
2024-09-30 14:50:19 +02:00
let contatto _telegram = '' ;
2024-04-09 21:56:50 +02:00
try {
let username _telegram = myrec . profile . username _telegram ;
2024-09-30 14:50:19 +02:00
if ( username _telegram ) {
contatto _telegram = ` @ ${ username _telegram } ` ;
contatto = contatto _telegram ;
}
2024-04-09 21:56:50 +02:00
} catch ( e ) {
}
let organizedBy = '' ;
2024-02-27 22:08:06 +01:00
let cat = '' ;
let status = '' ;
let online = false ;
let solo _online = false ;
2024-11-02 19:25:37 +01:00
let writtenby = myrec . profile . username _telegram ;
2024-11-02 18:06:12 +01:00
let sitoweb = '' ;
let contact _phone = '' ;
let contact _email = '' ;
2024-02-27 22:08:06 +01:00
if ( tablerec === shared _consts . TABLES _MYGOODS ) {
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
status = await this . getStatusSkillByRec ( myrec , true ) ;
if ( status ) {
status = ' ' + status ;
}
} else if ( tablerec === shared _consts . TABLES _MYHOSPS ) {
cat = '' ;
2024-04-09 21:56:50 +02:00
} else if ( tablerec === shared _consts . TABLES _MYBACHECAS ) {
2024-11-02 18:06:12 +01:00
if ( myrec . website ) {
sitoweb = myrec . website
}
2024-11-03 19:15:35 +01:00
2024-11-02 18:06:12 +01:00
contact _phone = myrec . contact _phone || '' ;
contact _email = myrec . contact _email || '' ;
2024-04-09 21:56:50 +02:00
if ( myrec . organisedBy ) {
organizedBy = myrec . organisedBy ;
contatto = '' ;
2024-11-02 19:25:37 +01:00
} else {
if ( myrec . mygrp && myrec . mygrp . title ) {
organizedBy = myrec . mygrp . title ;
contatto = '' ;
}
2024-04-09 21:56:50 +02:00
}
2024-11-02 18:06:12 +01:00
if ( ( myrec . contact _telegram && myrec . contact _telegram . toLowerCase ( ) !== contatto _telegram . toLowerCase ( ) ) || ! contatto ) {
2024-09-30 14:50:19 +02:00
contatto += '\n' + myrec . contact _telegram ;
2024-04-09 21:56:50 +02:00
}
2024-11-03 19:15:35 +01:00
/ * i f ( m y r e c . c o n t a c t _ p h o n e ) {
contatto += ' 📞 ' + myrec . contact _phone ;
} * /
2024-04-09 21:56:50 +02:00
2024-02-27 22:08:06 +01:00
}
// let out = i18n.__('NEW_ANNUNCIO_TELEGRAM', mydescr, dovestr, descrestesa, userorig);
2023-10-21 15:27:53 +02:00
2024-02-27 22:08:06 +01:00
if ( tiposcambio )
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( iconascambio , tiposcambio + status , '' , true , false ) ;
2024-02-27 22:08:06 +01:00
const url = this . getHostByIdApp ( myrec . idapp ) + shared _consts . getDirectoryByTable ( tablerec , true ) + myrec . _id ;
out += ` <strong> ${ myrec . descr } </strong> \n \n ` ;
if ( datastr )
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( '✨' , 'Data Evento' , datastr , true , true ) ;
2024-02-27 22:08:06 +01:00
if ( cat )
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( '⭐️' , 'Categoria' , cat , true , true ) ;
2024-02-27 22:08:06 +01:00
2024-09-18 13:11:47 +02:00
let descrcontent = this . convertAndTruncateHTMLForTelegram ( myrec . note , 500 , url )
2024-02-28 11:37:29 +01:00
2024-09-18 13:11:47 +02:00
// let descrcontent = this.firstchars(this.removeLastSpaceAndACapo(note), 200, true, url);
2024-03-06 20:46:00 +01:00
2024-05-10 01:59:54 +02:00
descrcontent = this . cleanHtmlForTelegram ( descrcontent ) ;
2024-03-06 20:46:00 +01:00
// descrcontent = '<span size="3"><b>Prova Pao</b> Ciaooo</span>';
2024-02-27 22:08:06 +01:00
if ( descrcontent )
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( '📝' , 'Descrizione ' + newdescr , descrcontent , true , true ) ;
2024-02-27 22:08:06 +01:00
const localita = this . getComuniEProvinceByRec ( myrec ) ;
if ( ! solo _online )
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( '🏠' , 'Località' , localita , false , true ) ;
2024-02-27 22:08:06 +01:00
const incambiodi = await this . getInCambioDiByRec ( myrec ) ;
if ( incambiodi )
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( '⚖️' , 'In cambio di' , incambiodi , false , true ) ;
2024-02-27 22:08:06 +01:00
2024-11-02 19:25:37 +01:00
if ( organizedBy ) {
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( '🏠' , 'Organizzato da' , organizedBy , false , true ) ;
2024-11-02 19:25:37 +01:00
} else {
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( '👤' , 'Contatto' , contatto , false , true ) ;
2024-11-02 19:25:37 +01:00
}
2024-11-02 18:06:12 +01:00
2024-02-27 22:08:06 +01:00
if ( contributo )
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( '💰' , 'Contributo Richiesto' , contributo , false , true ) ;
2024-11-02 18:06:12 +01:00
2024-11-02 19:25:37 +01:00
if ( contact _phone || contact _email || sitoweb ) {
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( 'ℹ ️ ' , 'Per Info:' ,
2024-11-02 19:25:37 +01:00
( contact _phone ? ( '📞 ' + contact _phone + ' ' ) : '' )
+ ( contact _email ? ( ' 📨 ' + contact _email + ' ' ) : '' )
+ ( sitoweb ? ( ' 🌐 ' + sitoweb + ' ' ) : '' )
2024-11-03 19:15:35 +01:00
, true , true ) ;
2024-11-02 18:06:12 +01:00
}
2024-02-27 22:08:06 +01:00
2024-11-02 19:25:37 +01:00
if ( writtenby && organizedBy ) {
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( '✍️' , 'Redatto da' , '@' + writtenby , false , true ) ;
}
let cosastr = 'Annuncio' ;
if ( tablerec === shared _consts . TABLES _MYBACHECAS ) {
cosastr = 'Evento' ;
2024-02-27 22:08:06 +01:00
}
2024-11-03 19:15:35 +01:00
out += this . addRowTelegram ( '' , ` 👉🏻 Vedi ${ cosastr } completo su RISO ` , url , true , true , true ) ;
2024-02-27 22:08:06 +01:00
2024-09-29 16:58:14 +02:00
if ( myrec . photos && myrec . photos . length > 0 ) {
// prende la prima foto ! ;
if ( myrec . photos [ 0 ] . imagefile )
img = this . getURLImg ( myrec . idapp , tablerec , myrec . username , myrec . photos [ 0 ] . imagefile , false ) ;
}
2024-03-06 20:46:00 +01:00
console . log ( 'out' , out ) ;
2024-02-27 22:08:06 +01:00
// out += i18n.__('ADDED_FROM', );
2024-09-29 16:58:14 +02:00
return { newdescr , newdescrtelegram : out , img } ;
2023-10-01 01:24:47 +02:00
} catch ( e ) {
console . error ( 'Error' , e ) ;
}
} ,
2024-02-06 20:12:54 +01:00
2023-12-02 15:23:35 +01:00
generateVapiKey ( ) {
const webpush = require ( 'web-push' ) ;
const vapidKeys = webpush . generateVAPIDKeys ( ) ;
const msg1 = 'VAPID Public Key:' + vapidKeys . publicKey ;
const msg2 = 'VAPID Private Key:' + vapidKeys . privateKey ;
console . log ( msg1 ) ;
console . log ( msg2 ) ;
return { msg : msg1 + ' ' + msg2 } ;
} ,
2023-12-18 12:11:12 +01:00
differentObjects ( obj1 , obj2 ) {
try {
const fieldsUpdated = [ ] ;
const obj1Fields = obj1 ? Object . keys ( obj1 ) : [ ] ;
const obj2Fields = obj2 ? Object . keys ( obj2 ) : [ ] ;
const commonFields = obj1Fields . filter ( field => obj2Fields . includes ( field ) ) ;
commonFields . forEach ( ( field ) => {
2024-05-04 14:49:02 +02:00
if ( obj1 && obj2 && ( ( obj1 [ field ] && obj1 [ field ] . toString ( ) ) !== ( obj2 [ field ] && obj2 [ field ] . toString ( ) ) ) ) {
if ( obj1 [ field ] !== undefined && obj2 [ field ] !== undefined )
fieldsUpdated . push ( field ) ;
2023-12-18 12:11:12 +01:00
}
} ) ;
return fieldsUpdated
} catch ( e ) {
console . error ( 'Err:' , e ) ;
}
} ,
2023-12-27 02:58:15 +01:00
isObjectEmpty ( obj ) {
return Object . keys ( obj ) . length === 0 ;
} ,
2023-12-02 15:23:35 +01:00
2023-12-28 00:50:35 +01:00
getUnitsMeasure ( unit , short ) {
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
} ,
2024-02-06 20:12:54 +01:00
getWeightAndUnitByText ( text ) {
const result = [ ] ;
2024-02-08 01:34:30 +01:00
2024-02-06 20:12:54 +01:00
text = text . replace ( "," , "." ) ;
2024-06-19 00:21:39 +02:00
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
2024-02-06 20:12:54 +01:00
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'
const unit = this . getIdUnitsByText ( unita ) ;
return { weight : peso , unit } ;
}
return { weight : 0 , unit : 0 } ;
} ,
2024-01-17 20:30:07 +01:00
async isManagerByReq ( req ) {
2024-02-06 20:12:54 +01:00
try {
2024-01-17 21:49:59 +01:00
var { User } = require ( '../models/user' ) ;
2024-02-06 20:12:54 +01:00
2024-01-17 20:30:07 +01:00
const idapp = req . body . idapp ;
let userId = '' ;
if ( req . body )
userId = req . body . userId ;
const myuser = await User . getUserById ( idapp , userId ) ;
let ismanager = false ;
if ( myuser && myuser . perm ) {
ismanager = User . isManager ( myuser . perm ) ;
}
return ismanager ;
} catch ( e ) {
return false ;
}
} ,
2024-02-06 20:12:54 +01:00
addslashes ( str ) {
return ( str + '' ) . replace ( /[\\"']/g , '\\$&' ) . replace ( /\u0000/g , '\\0' )
} ,
removeescape ( inputString ) {
2024-03-02 22:53:29 +01:00
// return inputString.replace(/\\/g, '').replace(/"/g, '');
if ( inputString )
return inputString . replace ( /\\/g , '' ) . replace ( /"/g , '' ) ;
2024-03-06 20:46:00 +01:00
else
2024-03-02 22:53:29 +01:00
return '' ;
} ,
escapeQuotes ( stringa ) {
if ( stringa )
return stringa . replace ( /"/g , '\\"' ) ;
else
return '' ;
} ,
replaceQuotesWithSingleQuotes ( jsonString ) {
if ( jsonString )
return jsonString . replace ( /"/g , "'" ) ;
else
return '' ;
} ,
ripulisciCampo ( stringa ) {
let mystr = this . replaceQuotesWithSingleQuotes ( stringa ) ;
return mystr ;
2024-02-06 20:12:54 +01:00
} ,
convertToNumeroVirgola ( valstr ) {
if ( valstr === '' || valstr === undefined )
valstr = '0' ;
2024-02-08 01:34:30 +01:00
2024-02-06 20:12:54 +01:00
valstr = valstr + '' ;
valstr = valstr . replace ( ',' , '.' ) ;
return parseFloat ( valstr ) ;
} ,
2024-02-08 01:34:30 +01:00
2024-02-06 20:12:54 +01:00
convertPriceEurToValue ( inputString ) {
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 ( ',' , '.' ) ;
} ,
2024-02-27 22:08:06 +01:00
removeLastSpaceAndACapo ( miastr ) {
miastr = miastr . trimRight ( ) . replace ( /[\n\r]+$/ , '' ) ;
// Rimuove eventuali '<br>' in fondo alla stringa
// Rimuove eventuali '<div><br></div>' in fondo alla stringa
miastr = miastr . replace ( /<\/div>$/ , '' ) ;
miastr = miastr . replace ( /<\/div>$/ , '' ) ;
miastr = miastr . replace ( /<br>$/ , '' ) ;
miastr = miastr . replace ( /<div><br><\/div>$/ , '' ) ;
miastr = miastr . replace ( /<br>$/ , '' ) ;
miastr = miastr . trimRight ( ) . replace ( /[\n\r]+$/ , '' ) ;
miastr = miastr . replace ( /<div><br><\/div>$/ , '' ) ;
miastr = miastr . replace ( /<div>$/ , '' ) ;
miastr = miastr . replace ( /<br>$/ , '' ) ;
miastr = miastr . replace ( /<br>$/ , '' ) ;
return miastr ;
2024-02-28 17:04:28 +01:00
} ,
rimuoviAtPrimoCarattere ( stringa ) {
if ( stringa . charAt ( 0 ) === '@' ) {
return stringa . slice ( 1 ) ;
} else {
return stringa ;
}
} ,
2023-04-12 15:37:54 +02:00
2024-03-19 00:21:54 +01:00
// Funzione per ottenere le coordinate di una singola città
async getCityCoordinates ( city ) {
try {
const response = await axios . get ( ` https://nominatim.openstreetmap.org/search?format=json&q= ${ city . descr } , ${ city . prov } ,Italia ` ) ;
if ( response . data . length > 0 ) {
city . lat = parseFloat ( response . data [ 0 ] . lat ) ;
city . long = parseFloat ( response . data [ 0 ] . lon ) ;
// console.log(`${city.descr}: Lat ${city.lat}, Long ${city.long}`);
return city ;
} else {
2024-03-21 21:22:57 +01:00
console . error ( ` Coordinate non trovate per ${ city . descr } , ${ city . prov } ` ) ;
2024-03-19 00:21:54 +01:00
}
return null ;
} catch ( error ) {
console . error ( ` Errore durante il recupero delle coordinate per ${ city . descr } , ${ city . prov } : ` , error . message ) ;
}
} ,
2024-03-23 00:21:32 +01:00
/ * *
* Funzione per scaricare dati GeoJSON dei comuni d ' Italia e salvarli localmente .
* @ param { string } url - L ' URL dal quale scaricare i dati GeoJSON .
* @ param { string } outputPath - Il percorso del file in cui salvare i dati GeoJSON .
2024-03-26 18:11:19 +01:00
* /
2024-03-23 00:21:32 +01:00
async downloadGeoJSON ( url , outputPath ) {
try {
// Effettua una richiesta GET all'URL specificato per scaricare i dati.
const response = await axios . get ( url ) ;
const data = response . data ;
// Salva i dati GeoJSON in un file locale.
await fs . writeFile ( outputPath , JSON . stringify ( data , null , 2 ) ) ;
console . log ( ` Dati GeoJSON salvati in ${ outputPath } ` ) ;
} catch ( error ) {
console . error ( 'Errore durante il download o il salvataggio dei dati GeoJSON:' , error ) ;
}
} ,
2024-03-19 00:21:54 +01:00
2024-05-04 14:49:02 +02:00
arrotondaA2Decimali ( valore ) {
try {
return parseFloat ( valore ) . toFixed ( 2 ) ;
} catch ( error ) {
return valore ;
}
} ,
2024-05-10 01:59:54 +02:00
cleanHtmlForTelegram ( htmlContent ) {
try {
// Assicurati che l'HTML abbia un elemento body
const dom = new JSDOM ( ` <body> ${ htmlContent } </body> ` ) ;
const document = dom . window . document ;
// Definisci i tag permessi su Telegram
const allowedTags = [ 'b' , 'strong' , 'i' , 'em' , 'u' , 's' , 'strike' , 'del' , 'a' , 'code' ] ;
// Seleziona tutti gli elementi all'interno del body
const allElements = document . body . querySelectorAll ( '*' ) ;
allElements . forEach ( element => {
const tagName = element . tagName . toLowerCase ( ) ;
if ( ! allowedTags . includes ( tagName ) ) {
// Crea un nodo di testo e sostituisci l'elemento con quel nodo di testo
const textNode = document . createTextNode ( element . textContent || '' ) ;
element . replaceWith ( textNode ) ;
} else {
// Se il tag è permesso, rimuovi tutti gli attributi ad eccezione di 'href' per i link
if ( tagName === 'a' ) {
const href = element . getAttribute ( 'href' ) ;
while ( element . attributes . length > 0 ) {
element . removeAttribute ( element . attributes [ 0 ] . name ) ;
}
if ( href ) {
element . setAttribute ( 'href' , href ) ;
}
} else {
while ( element . attributes . length > 0 ) {
element . removeAttribute ( element . attributes [ 0 ] . name ) ;
}
}
}
} ) ;
// Ritorna l'HTML pulito
return document . body . innerHTML ;
} catch ( error ) {
console . error ( 'Errore durante la pulizia dell\'HTML:' , error ) ;
throw error ; // Oppure, gestisci l'errore come preferisci
}
2024-07-03 13:22:32 +02:00
} ,
getHostWithNoHttporHttps ( url ) {
try {
const parsedUrl = new URL ( url ) ;
return parsedUrl . host ;
} catch ( error ) {
console . error ( 'Errore durante la pulizia dell\'HTML:' , error ) ;
throw error ; // Oppure, gestisci l'errore come preferisci
}
} ,
// Crea un file con all'interno il nome del dominio per ogni app:
createFileWithDomainName ( ) {
const arrapps = getApps ( ) ;
2024-05-10 01:59:54 +02:00
2024-07-03 13:22:32 +02:00
const filename = server _constants . FILECONFIG _SERVER ;
for ( const app of arrapps ) {
fs . writeFile ( filename , this . getHostWithNoHttporHttps ( app . host ) , function ( err ) {
if ( err ) {
console . log ( err ) ;
}
} ) ;
if ( app . host _test ) {
fs . writeFile ( filename , this . getHostWithNoHttporHttps ( app . host _test ) , function ( err ) {
if ( err ) {
console . log ( err ) ;
}
} ) ;
}
}
} ,
2024-09-17 17:38:47 +02:00
async listCollectionsBySize ( ) {
let output = "" ; // Variabile per memorizzare l'output
try {
const conn = mongoose . connection ;
// Ottieni le collezioni e calcola la dimensione
const collections = await conn . db . listCollections ( ) . toArray ( ) ;
// Calcola la dimensione per ciascuna collezione
const collectionSizes = await Promise . all ( collections . map ( async ( collection ) => {
const stats = await conn . db . collection ( collection . name ) . stats ( ) ;
return { name : collection . name , size : stats . size } ;
} ) ) ;
// Ordina le collezioni per dimensione
collectionSizes . sort ( ( a , b ) => b . size - a . size ) ; // Ordine decrescente
output += "Collezioni ordinate per dimensione:\n" ; // Inizio dell'output
collectionSizes . forEach ( collection => {
const sizeInMB = ( collection . size / ( 1024 * 1024 ) ) . toFixed ( 2 ) ; // Converti in MB
output += ` Collezione: ${ collection . name } , Dimensione: ${ sizeInMB } MB \n ` ; // Aggiungi all'output
} ) ;
return output ; // Restituisci l'output alla fine
} catch ( error ) {
console . error ( "Errore:" , error ) ;
return ` Errore: ${ error . message } ` ; // Restituisci l'errore come stringa
}
} ,
2024-09-26 02:14:33 +02:00
getStringaConto ( mov ) {
let mystr = ''
2024-10-02 03:46:33 +02:00
let userfrom = ''
let userto = ''
let profilefrom = null
let profileto = null
2024-09-26 02:14:33 +02:00
let tipocontofrom = shared _consts . AccountType . USER
let tipocontoto = shared _consts . AccountType . USER
if ( mov . contocomfrom && mov . contocomfrom . name ) {
2024-10-02 03:46:33 +02:00
userfrom += mov . contocomfrom . name
2024-09-26 02:14:33 +02:00
tipocontofrom = shared _consts . AccountType . COMMUNITY _ACCOUNT
}
if ( mov . groupfrom ) {
2024-10-02 03:46:33 +02:00
userfrom += mov . groupfrom . groupname
2024-09-26 02:14:33 +02:00
tipocontofrom = shared _consts . AccountType . COLLECTIVE _ACCOUNT
}
if ( mov . userfrom ) {
2024-10-02 03:46:33 +02:00
userfrom += mov . userfrom . username
profilefrom = mov . userfrom . profile
2024-09-26 02:14:33 +02:00
}
if ( mov . contocomto && mov . contocomto . name ) {
2024-10-02 03:46:33 +02:00
userto += mov . contocomto . name
2024-09-26 02:14:33 +02:00
tipocontoto = shared _consts . AccountType . COMMUNITY _ACCOUNT
}
if ( mov . groupto ) {
2024-10-02 03:46:33 +02:00
userto += mov . groupto . groupname
2024-09-26 02:14:33 +02:00
tipocontoto = shared _consts . AccountType . COLLECTIVE _ACCOUNT
}
if ( mov . userto ) {
2024-10-02 03:46:33 +02:00
userto += mov . userto . username
profileto = mov . userto . profile
2024-09-26 02:14:33 +02:00
}
2024-10-02 03:46:33 +02:00
// mystr = t('movement.from') + userfrom + ' ' + t('movement.to') + userto
2024-09-26 02:14:33 +02:00
2024-10-03 03:55:05 +02:00
return { userfrom : { profile : profilefrom , username : userfrom } , userto : { profile : profileto , username : userto } , tipocontofrom , tipocontoto }
2024-09-26 02:14:33 +02:00
} ,
2024-07-23 12:25:10 +02:00
ImageDownloader ,
2024-09-29 16:58:14 +02:00
getDirUpload ( ) {
return 'upload/'
} ,
getURLImg ( idapp , table , username , img , checkifExist ) {
let dirmain = '' ;
try {
2024-11-02 18:06:12 +01:00
// let dir = this.getdirByIdApp(idapp) + dirmain + '/' + this.getDirUpload();
let dir = this . getHostByIdApp ( idapp ) + '/' + this . getDirUpload ( ) + shared _consts . getDirectoryImgByTable ( table , username ) + dirmain ;
2024-09-29 16:58:14 +02:00
2024-11-02 18:06:12 +01:00
img = dir + img ;
2024-09-29 16:58:14 +02:00
2024-11-02 18:06:12 +01:00
/ * i f ( c h e c k i f E x i s t ) {
2024-09-29 16:58:14 +02:00
if ( ! fs . existsSync ( img ) ) {
return '' ;
}
2024-11-02 18:06:12 +01:00
} * /
2024-09-29 16:58:14 +02:00
2024-09-30 14:50:19 +02:00
if ( ! this . sulServer ( ) ) {
// Finta Immagine
img = 'https://riso.app/upload/profile/SoniaVioletFlame/myskills/1000133092.jpg' ;
}
2024-09-29 16:58:14 +02:00
return img ;
} catch ( e ) {
console . error ( 'Err GetURLImg' , e ) ;
return '' ;
}
} ,
2024-09-29 23:26:37 +02:00
getLangByUsername ( idapp , username ) {
//++Todo LANG: Estrarre il Lang dall'username (user, group)
return 'it' ;
} ,
2024-10-02 03:46:33 +02:00
getFieldsForAnnunci ( ) {
let annunciFields = {
idMyGroup : {
type : String ,
} ,
expiryDateAdv : {
type : Date ,
} ,
enableExpiringAdv : {
type : Boolean ,
} ,
// **ADDFIELD_ANNUNCI
} ;
2024-10-03 03:55:05 +02:00
2024-10-02 03:46:33 +02:00
return annunciFields ;
2024-10-03 03:55:05 +02:00
} ,
// Funzione per pulire il nome del file
cleanFileName ( filePath ) {
// Ottieni solo il nome del file dall'intero percorso
// const fileName = filePath.split('/').pop();
// Rimuovi apostrofi e sostituisci gli spazi con underscore
const cleanedName = fileName . replace ( /'/g , '' ) . replace ( /\s+/g , '_' ) ;
// Restituisci il percorso chiaro; puoi decidere di mantenere il resto del percorso
return cleanedName ;
} ,
2024-05-10 01:59:54 +02:00
2024-11-02 18:06:12 +01:00
fixUrl ( myurl , idapp ) {
if ( ! myurl . startsWith ( 'http' ) ) {
return this . getHostByIdApp ( idapp ) + myurl ;
}
if ( myurl . startsWith ( 'http://127.0.0.1' ) ) {
//myurl = myurl.replace('http://127.0.0.1:8084/', 'https://riso.app/')
2024-11-02 19:25:37 +01:00
2024-11-02 18:06:12 +01:00
// Se è in locale allora metti una foto finta...
myurl = 'https://images.unsplash.com/photo-1464047736614-af63643285bf?q=80&w=2874&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'
//myurl = myurl.replace('http://127.0.0.1', 'http://localhost')
}
return myurl ;
2024-11-28 16:05:00 +01:00
} ,
// Funzione per convertire XML in JSON
convertXMLToJSON ( xml ) {
const parser = new xml2js . Parser ( ) ;
parser . parseString ( xml , ( err , result ) => {
if ( err ) {
console . error ( 'Error parsing XML:' , err ) ;
} else {
console . log ( JSON . stringify ( result , null , 2 ) ) ; // Stampa il risultato in formato JSON
}
} ) ;
2024-11-02 18:06:12 +01:00
}
2024-11-28 16:05:00 +01:00
2019-12-28 14:30:30 +01:00
} ;