From 331a5451b25f91e57fac2d9ad85a046c9f94c342 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Thu, 27 Nov 2025 23:51:48 +0100 Subject: [PATCH] - fix zona provinciale - email abilitazione circuito: invio email ad admin - admin che abilita la fiducia cliccando sul bottone --- .../it/html.pug | 401 ++ .../it/subject.pug | 1 + .../it/html.pug | 10 +- .../reg_email_benvenuto_ammesso/it/html.pug | 2 +- .../reg_notifica_all_invitante/it/subject.pug | 2 +- .../reg_notifica_all_invitante/it/subject.pug | 2 +- src/models/circuit.js | 23 +- src/models/user.js | 81 +- src/modules/InvioNotifiche.js | 575 -- src/modules/InvioNotifiche.test.js | 541 -- src/router/index_router.js | 72 +- src/sendemail.js | 56 +- src/telegram/telegrambot.js | 38 +- src/telegram/telegrambot_OLD.js | 4651 ----------------- 14 files changed, 652 insertions(+), 5803 deletions(-) create mode 100755 emails/RISO/circuit_chiedi_facilitatori_di_entrare/it/html.pug create mode 100755 emails/RISO/circuit_chiedi_facilitatori_di_entrare/it/subject.pug delete mode 100644 src/modules/InvioNotifiche.js delete mode 100644 src/modules/InvioNotifiche.test.js delete mode 100755 src/telegram/telegrambot_OLD.js diff --git a/emails/RISO/circuit_chiedi_facilitatori_di_entrare/it/html.pug b/emails/RISO/circuit_chiedi_facilitatori_di_entrare/it/html.pug new file mode 100755 index 0000000..24367af --- /dev/null +++ b/emails/RISO/circuit_chiedi_facilitatori_di_entrare/it/html.pug @@ -0,0 +1,401 @@ +doctype html +html(lang="it") + head + meta(charset="UTF-8") + meta(name="viewport" content="width=device-width, initial-scale=1.0") + style(type="text/css"). + * { + margin: 0; + padding: 0; + box-sizing: border-box; + } + + body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; + background-color: #f5f5f5; + padding: 20px; + line-height: 1.6; + } + + .header-logo { + width: 120px; + height: auto; + margin-bottom: 16px; + display: block; + margin-left: auto; + margin-right: auto; + } + + .email-container { + max-width: 600px; + margin: 0 auto; + background: white; + border-radius: 12px; + box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); + overflow: hidden; + } + + .email-header { + background: linear-gradient(135deg, #7cb342 0%, #558b2f 100%); + color: white; + padding: 40px 24px; + text-align: center; + } + + .email-header h1 { + margin: 0 0 8px 0; + font-size: 26px; + font-weight: 600; + line-height: 1.3; + } + + .email-header .subtitle { + margin: 8px 0 0 0; + font-size: 17px; + opacity: 0.95; + font-style: italic; + } + + .alert-icon { + font-size: 56px; + margin-bottom: 12px; + } + + .email-body { + padding: 32px 24px; + } + + .intro-text { + font-size: 16px; + color: #333; + margin-bottom: 20px; + text-align: center; + line-height: 1.7; + } + + .request-card { + background: linear-gradient(135deg, #e3f2fd 0%, #f0f7ff 100%); + border: 2px solid #2196f3; + border-radius: 8px; + padding: 24px; + margin: 20px 0; + text-align: center; + } + + .request-card h3 { + font-size: 14px; + text-transform: uppercase; + color: #2196f3; + margin-bottom: 12px; + letter-spacing: 0.5px; + font-weight: 600; + } + + .request-card .member-name { + font-size: 28px; + color: #1a1a1a; + font-weight: 700; + margin-bottom: 8px; + } + + .request-card .member-detail { + font-size: 15px; + color: #555; + margin: 6px 0; + } + + .request-card .member-detail strong { + color: #2196f3; + } + + .territory-badge { + background: linear-gradient(135deg, #4caf50 0%, #388e3c 100%); + color: white; + display: inline-block; + padding: 8px 20px; + border-radius: 20px; + font-size: 16px; + font-weight: 600; + margin-top: 12px; + } + + .question-box { + background: #e1f5fe; + border-left: 4px solid #2196f3; + border-radius: 8px; + padding: 20px; + margin: 24px 0; + text-align: center; + } + + .question-box p { + font-size: 20px; + color: #1a1a1a; + font-weight: 600; + margin: 0; + line-height: 1.4; + } + + .cta-section { + text-align: center; + margin: 32px 0; + padding: 24px 0; + border-top: 2px solid #e0e0e0; + border-bottom: 2px solid #e0e0e0; + } + + .cta-title { + font-size: 18px; + font-weight: 600; + color: #1a1a1a; + margin-bottom: 20px; + } + + .cta-button { + display: inline-block; + padding: 18px 56px; + font-size: 20px; + font-weight: 700; + color: white; + background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%); + border-radius: 50px; + text-decoration: none; + box-shadow: 0 6px 20px rgba(33, 150, 243, 0.4); + transition: all 0.3s ease; + } + + .button-icon { + font-size: 20px; + margin-right: 10px; + vertical-align: middle; + } + + .info-box { + background: #e8f5e9; + border-radius: 8px; + padding: 16px; + margin: 20px 0; + } + + .info-box p { + margin: 0 0 8px 0; + color: #2e7d32; + font-size: 15px; + line-height: 1.6; + } + + .info-box p:last-child { + margin-bottom: 0; + } + + .responsibility-box { + background: #f8f9fa; + border-radius: 8px; + padding: 20px; + margin: 20px 0; + } + + .responsibility-box h3 { + font-size: 17px; + color: #1a1a1a; + margin-bottom: 12px; + text-align: center; + font-weight: 600; + } + + .responsibility-item { + display: flex; + align-items: flex-start; + margin-bottom: 10px; + padding: 6px 0; + } + + .responsibility-icon { + font-size: 20px; + margin-right: 10px; + min-width: 24px; + flex-shrink: 0; + } + + .responsibility-text { + font-size: 15px; + color: #555; + line-height: 1.5; + } + + .email-footer { + padding: 20px; + text-align: center; + background: #f8f9fa; + color: #777; + font-size: 13px; + } + + .email-footer p { + margin: 4px 0; + } + + .divider { + height: 1px; + background: linear-gradient(to right, transparent, #e0e0e0, transparent); + margin: 20px 0; + } + + @media only screen and (max-width: 600px) { + body { + padding: 10px; + } + + .email-header { + padding: 24px 16px; + } + + .email-header h1 { + font-size: 22px; + } + + .alert-icon { + font-size: 48px; + } + + .email-body { + padding: 20px 16px; + } + + .request-card .member-name { + font-size: 24px; + } + + .territory-badge { + font-size: 14px; + padding: 6px 16px; + } + + .question-box p { + font-size: 18px; + } + + .cta-button { + padding: 16px 40px; + font-size: 18px; + width: 100%; + max-width: 300px; + } + + .responsibility-item { + font-size: 14px; + } + } + + body + .email-container + //- Header + .email-header + img.header-logo(src=baseurl+'/images/logo.png' alt=nomeapp) + h1 🎯 Richiesta Abilitazione #{nomeTerritorio} + p.subtitle Nuovo membro in attesa di attivazione + + //- Body + .email-body + //- Intro + .intro-text + | Ciao #{nomeFacilitatore},
+ | un nuovo membro richiede l'abilitazione alla fiducia al Circuito RIS del tuo territorio! + + //- Card richiesta + .request-card + h3 👤 Richiesta Ingresso Circuito + .member-name #{usernameMembro} + if nomeMembro + if cognomeMembro + .member-detail + strong Nome: + | #{nomeMembro} #{cognomeMembro} + else + .member-detail + strong Nome: + | #{nomeMembro} + if emailMembro + .member-detail + strong Email: + | #{emailMembro} + if telegramMembro + .member-detail + strong Telegram: + a(href=`https://t.me/${telegramMembro}` target="_blank" style="color: #2196f3; text-decoration: none;") @#{telegramMembro} + if comuneResidenza + .member-detail + strong Comune: + | #{comuneResidenza} (#{provinciaResidenza}) + + .territory-badge 📍 #{nomeTerritorio} + + if usernameInvitante + .divider(style="margin: 20px auto; width: 80%;") + h3(style="font-size: 14px; text-transform: uppercase; color: #2196f3; margin-bottom: 12px;") 👥 Invitato da + .member-detail + strong Invitante: + | #{usernameInvitante} + if nomeInvitante + if cognomeInvitante + .member-detail + strong Nome: + | #{nomeInvitante} #{cognomeInvitante} + else + .member-detail + strong Nome: + | #{nomeInvitante} + if telegramInvitante + .member-detail + strong Telegram: + a(href=`https://t.me/${telegramInvitante}` target="_blank" style="color: #2196f3; text-decoration: none;") @#{telegramInvitante} + + //- CTA principale + .cta-section + a.cta-button(href=linkAbilitazione target="_blank") + span.button-icon ✓ + | Abilita fiducia + + .divider(style="margin: 24px 0;") + p(style="font-size: 16px; color: #666; margin-bottom: 16px;") Visualizza i profili + .button-group(style="display: flex; gap: 12px; justify-content: center; flex-wrap: wrap;") + a.secondary-button(href=linkProfiloMembro target="_blank" style="display: inline-block; padding: 12px 24px; font-size: 16px; font-weight: 600; color: #2196f3; background: white; border: 2px solid #2196f3; border-radius: 25px; text-decoration: none; transition: all 0.3s ease;") + span(style="margin-right: 6px;") 👤 + | Profilo Membro + if linkProfiloInvitante + a.secondary-button(href=linkProfiloInvitante target="_blank" style="display: inline-block; padding: 12px 24px; font-size: 16px; font-weight: 600; color: #7cb342; background: white; border: 2px solid #7cb342; border-radius: 25px; text-decoration: none; transition: all 0.3s ease;") + span(style="margin-right: 6px;") 👥 + | Profilo Invitante + + //- Responsabilità + .responsibility-box + h3 📋 Compiti del Facilitatore RISO + .responsibility-item + span.responsibility-icon 🔍 + span.responsibility-text + strong Verifica: + | Contatta il membro, se non lo conosci, oppure il suo invitante: #{usernameInvitante} + .responsibility-item + span.responsibility-icon 🌍 + span.responsibility-text + strong Territorio: + | Assicurati che il membro appartenga effettivamente al territorio di competenza + .responsibility-item + span.responsibility-icon 👥 + span.responsibility-text + strong Integrazione: + | Supporta il nuovo membro nell'attivazione e utilizzo del Circuito RIS locale + + //- Info box + .info-box + p + | ✓ Dopo l'abilitazione, #{usernameMembro} potrà accedere al Circuito RIS di #{nomeTerritorio} + p + | ✓ Il membro riceverà una notifica automatica dell'avvenuta attivazione + + //- Footer + .email-footer + .divider + p Hai ricevuto questa email in qualità di Facilitatore RISO per #{nomeTerritorio} + p(style="margin-top: 12px; font-size: 12px;") + | #{new Date().getFullYear()} #{nomeapp} \ No newline at end of file diff --git a/emails/RISO/circuit_chiedi_facilitatori_di_entrare/it/subject.pug b/emails/RISO/circuit_chiedi_facilitatori_di_entrare/it/subject.pug new file mode 100755 index 0000000..05304aa --- /dev/null +++ b/emails/RISO/circuit_chiedi_facilitatori_di_entrare/it/subject.pug @@ -0,0 +1 @@ +=`Richiesta ingresso di ${usernameMembro} - ${nomeMembro} ${cognomeMembro} su ${nomeTerritorio} in ${nomeapp}` diff --git a/emails/RISO/reg_chiedi_ammettere_all_invitante/it/html.pug b/emails/RISO/reg_chiedi_ammettere_all_invitante/it/html.pug index 19f63bf..a049576 100755 --- a/emails/RISO/reg_chiedi_ammettere_all_invitante/it/html.pug +++ b/emails/RISO/reg_chiedi_ammettere_all_invitante/it/html.pug @@ -294,7 +294,7 @@ html(lang="it") .email-container //- Header .email-header - img.header-logo(src=baseurl+'/images/logo.png' alt='RISO - Rete Italiana Scambio Orizzontale') + img.header-logo(src=baseurl+'/images/logo.png' alt=nomeapp) h1 🔔 Richiesta di Ammissione p.subtitle Nuovo membro in attesa @@ -344,7 +344,7 @@ html(lang="it") span.responsibility-icon 🛡️ span.responsibility-text strong Fiducia: - | L'ammissione si basa sulla fiducia reciproca nella comunità RISO + | L'ammissione si basa sulla fiducia reciproca nella comunità #{nomeapp} .responsibility-item span.responsibility-icon 👥 span.responsibility-text @@ -355,8 +355,6 @@ html(lang="it") .info-box p | ✓ Dopo l'ammissione, #{usernameInvitato} potrà completare il profilo - p - | ✓ Il facilitatore locale valuterà l'abilitazione all'uso dei RIS //- Warning box .warning-box @@ -369,6 +367,4 @@ html(lang="it") .divider p Hai ricevuto questa email perché #{usernameInvitato} ha indicato te come invitante su #{nomeapp} p(style="margin-top: 12px; font-size: 12px;") - | #{new Date().getFullYear()} #{nomeapp} - Rete Italiana Scambi Orizzontali - p(style="margin-top: 12px; font-size: 12px;") - | 🍚 Comunità · Fiducia · Scambi Solidali · Sostenibilità \ No newline at end of file + | #{new Date().getFullYear()} #{nomeapp} diff --git a/emails/RISO/reg_email_benvenuto_ammesso/it/html.pug b/emails/RISO/reg_email_benvenuto_ammesso/it/html.pug index c754c08..13633df 100755 --- a/emails/RISO/reg_email_benvenuto_ammesso/it/html.pug +++ b/emails/RISO/reg_email_benvenuto_ammesso/it/html.pug @@ -448,7 +448,7 @@ html(lang="it") .step-number 1 .step-content h3 ✅ Completa il tuo profilo - p Collega il tuo profilo a Telegram, inserisci la tua Provincia ed accedi ai Circuiti Territoriali per poter iniziare ad usare i RIS. Un profilo completo aiuta gli altri membri a conoscerti meglio! + p Collega il tuo profilo a Telegram ed accedi ai Circuiti Territoriali per poter iniziare ad usare i RIS. Un profilo completo aiuta gli altri membri a conoscerti meglio! .step-item .step-number 2 diff --git a/emails/RISO/reg_notifica_all_invitante/it/subject.pug b/emails/RISO/reg_notifica_all_invitante/it/subject.pug index 2921400..881dba1 100755 --- a/emails/RISO/reg_notifica_all_invitante/it/subject.pug +++ b/emails/RISO/reg_notifica_all_invitante/it/subject.pug @@ -1 +1 @@ -=`🎉 Il tuo invito è stato accettato su RISO da ${name ? ', ' + name : username} !` +=`🎉 Il tuo invito è stato accettato su RISO da ${name ? name : username} !` diff --git a/emails/defaultSite/reg_notifica_all_invitante/it/subject.pug b/emails/defaultSite/reg_notifica_all_invitante/it/subject.pug index e6cfadd..b845bca 100755 --- a/emails/defaultSite/reg_notifica_all_invitante/it/subject.pug +++ b/emails/defaultSite/reg_notifica_all_invitante/it/subject.pug @@ -1 +1 @@ -=`🎉 Il tuo invito è stato accettato su ${nomeapp} da ${name ? ', ' + name : username} !` +=`🎉 Il tuo invito è stato accettato su ${nomeapp} da ${name ? name : username} !` diff --git a/src/models/circuit.js b/src/models/circuit.js index ac70f04..176b1ea 100755 --- a/src/models/circuit.js +++ b/src/models/circuit.js @@ -1030,8 +1030,10 @@ CircuitSchema.statics.getCircuitByCircuitId = async function (circuitId) { return await Circuit.findOne({ _id: circuitId }); }; +// getListAdminsByCircuitPath - ritorna oggetti interi + USER_ADMIN_CIRCUITS +// getListAdminsByCircuitPath - ritorna oggetti interi senza duplicati CircuitSchema.statics.getListAdminsByCircuitPath = async function (idapp, circuitPath) { - let arr = await Circuit.findOne( + let circuit = await Circuit.findOne( { idapp, path: circuitPath, @@ -1040,9 +1042,22 @@ CircuitSchema.statics.getListAdminsByCircuitPath = async function (idapp, circui { admins: 1 } ).lean(); - let myarr = arr && arr.admins ? arr.admins : []; + let adminObjects = circuit && circuit.admins ? circuit.admins : []; - return [...myarr, ...shared_consts.USER_ADMIN_CIRCUITS]; + // Aggiungi USER_ADMIN_CIRCUITS come oggetti + let systemAdmins = shared_consts.USER_ADMIN_CIRCUITS.map(username => ({ + username, + date: null, + _id: null + })); + + // Unisci e rimuovi duplicati per username + let allAdmins = [...adminObjects, ...systemAdmins]; + let uniqueAdmins = allAdmins.filter((admin, index, self) => + index === self.findIndex(a => a.username === admin.username) + ); + + return uniqueAdmins; }; // Imposta a tutti i Conti Collettivi, i seguenti minimi e massimi @@ -1177,7 +1192,7 @@ CircuitSchema.statics.createCircuitIfNotExist = async function (req, idapp, prov date_created: new Date(), admins: admins.map((username) => ({ username })), askManagerToEnter: false, - sendEmailAfterAskingToEnter: false, + sendEmailAfterAskingToEnter: true, circuitoIndipendente: false, }); diff --git a/src/models/user.js b/src/models/user.js index ee23dec..da6646d 100755 --- a/src/models/user.js +++ b/src/models/user.js @@ -465,6 +465,7 @@ const UserSchema = new mongoose.Schema({ _id: false, circuitname: { type: String }, date: { type: Date }, + token: { type: String }, }, ], last_circuitpath: { @@ -2489,25 +2490,38 @@ UserSchema.statics.addCircuitToUser = async function (idapp, usernameOrig, circu } else { // prima di aggiungerlo controlla se esiste già ! - let update = { - $addToSet: { - // Utilizziamo $addToSet invece di $push per garantire che l'elemento venga aggiunto solo se non esiste già - 'profile.mycircuits': { - $each: [ - { - circuitname, - date: new Date(), - }, - ], - }, + const token = tools.getTokenRandom(); + + let update = null; + + const updateparams = { + $set: { + 'profile.mycircuits.$[elem].date': new Date(), + 'profile.mycircuits.$[elem].token': token, }, }; - ris = await User.updateOne( - { idapp, username: usernameOrig, 'profile.mycircuits': { $not: { $elemMatch: { circuitname } } } }, - update + let ris = await User.updateOne( + { idapp, username: usernameOrig, 'profile.mycircuits.circuitname': circuitname }, + updateparams, + { arrayFilters: [{ 'elem.circuitname': circuitname }] } ); + // Se non ha modificato nulla (nModified === 0), significa che non esiste, quindi lo aggiungiamo + if (ris.modifiedCount === 0) { + const insertUpdate = { + $push: { + 'profile.mycircuits': { + circuitname, + date: new Date(), + token, + }, + }, + }; + + ris = await User.updateOne({ idapp, username: usernameOrig }, insertUpdate); + } + if (confido) { // Elimina la richiesta: update = { $pull: { req_users: { username: { $in: [usernameOrig] } } } }; @@ -2525,6 +2539,24 @@ UserSchema.statics.addCircuitToUser = async function (idapp, usernameOrig, circu }; // Rimuovo il Gruppo per Tutti gli Utenti +UserSchema.statics.getCircuitByTokenAndUsername = async function (idapp, username, token) { + try { + const user = await User.findOne({ + idapp, + username, + 'profile.mycircuits.token': token, + }); + + // Il circuito sarà in: circuit?.profile?.mycircuits?.[0] + const foundCircuit = user?.profile?.mycircuits?.[0]; + if (foundCircuit) { + return { circuitname: foundCircuit.circuitname, user }; + } + } catch (e) { + return { circuitname: '', user: null }; + } + return { circuitname: '', user: null }; +}; UserSchema.statics.removeAllUsersFromMyGroups = async function (idapp, groupnameDest) { return await User.updateMany({ idapp }, { $pull: { 'profile.mygroups': { groupname: { $in: [groupnameDest] } } } }); }; @@ -2630,7 +2662,7 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use ); msgDest = i18n.__({ phrase: '✅ Sei stato Ammesso correttamente da %s!', locale: lang }, usernameOrig); msgAdmin = i18n.__( - { phrase: '✅ %s è stato Ammesso correttamente (da %s)!', locale: userDest.lang }, + { phrase: '✅ %s è stato Ammesso/a correttamente (da %s) tramite Email!', locale: userDest.lang }, userDest.username, usernameOrig ); @@ -6912,6 +6944,25 @@ UserSchema.statics.createNewSubRecord = async function (idapp, req) { return rec; }; +// Nel tuo User schema, aggiungi questo metodo statico: + +UserSchema.statics.getTokenByUsernameAndCircuitName = async function (idapp, username, circuitname) { + const User = this; + + const user = await User.findOne( + { + idapp, + username, + 'profile.mycircuits.circuitname': circuitname, + }, + { + 'profile.mycircuits.$': 1, + } + ); + + return user?.profile?.mycircuits?.[0]?.token || null; +}; + const User = mongoose.model('User', UserSchema); class Hero { diff --git a/src/modules/InvioNotifiche.js b/src/modules/InvioNotifiche.js deleted file mode 100644 index 799c493..0000000 --- a/src/modules/InvioNotifiche.js +++ /dev/null @@ -1,575 +0,0 @@ -/** - * Classe per gestire l'invio di notifiche via Email e Telegram - * per gli eventi della piattaforma RISO - */ - -class InvioNotifiche { - /** - * @param {Object} config - Configurazione per l'invio notifiche - * @param {Object} config.emailService - Servizio per invio email (es. nodemailer) - * @param {Object} config.telegramBot - Istanza del bot Telegram - * @param {String} config.adminTelegramId - ID Telegram dell'amministratore - * @param {String} config.adminEmail - Email dell'amministratore - * @param {String} config.baseUrl - URL base dell'applicazione - * @param {String} config.nomeApp - Nome dell'applicazione - * @param {Object} config.emailTemplates - Path ai template email PUG - */ - constructor(config) { - this.emailService = config.emailService; - this.telegramBot = config.telegramBot; - this.adminTelegramId = config.adminTelegramId; - this.adminEmail = config.adminEmail; - this.baseUrl = config.baseUrl; - this.nomeApp = config.nomeApp || 'RISO'; - this.emailTemplates = config.emailTemplates || {}; - - // Logger (puoi sostituirlo con Winston o altro) - this.logger = config.logger || console; - } - - // ============================================ - // METODI PRIVATI - Invio Base - // ============================================ - - /** - * Invia una email - * @private - */ - async _inviaEmail(destinatario, oggetto, htmlContent, templatePath = null, templateData = null) { - try { - let html = htmlContent; - - // Se è specificato un template PUG, renderizzalo - if (templatePath && templateData) { - const pug = require('pug'); - html = pug.renderFile(templatePath, templateData); - } - - const emailOptions = { - from: `${this.nomeApp} `, - to: destinatario, - subject: oggetto, - html: html, - }; - - const result = await this.emailService.sendMail(emailOptions); - - this.logger.info(`Email inviata a ${destinatario}: ${oggetto}`); - return { success: true, messageId: result.messageId }; - } catch (error) { - this.logger.error(`Errore invio email a ${destinatario}:`, error); - return { success: false, error: error.message }; - } - } - - /** - * Invia un messaggio Telegram - * @private - */ - async _inviaTelegram(telegramId, messaggio, opzioni = {}) { - try { - if (!telegramId || telegramId === 0) { - this.logger.warn(`Telegram ID non valido: ${telegramId}`); - return { success: false, error: 'Telegram ID non valido' }; - } - - const defaultOptions = { - parse_mode: 'HTML', - disable_web_page_preview: false, - ...opzioni, - }; - - const result = await this.telegramBot.sendMessage(telegramId, messaggio, defaultOptions); - - this.logger.info(`Messaggio Telegram inviato a ${telegramId}`); - return { success: true, messageId: result.message_id }; - } catch (error) { - this.logger.error(`Errore invio Telegram a ${telegramId}:`, error); - return { success: false, error: error.message }; - } - } - - /** - * Invia notifica sia via email che Telegram - * @private - */ - async _inviaNotificaDoppia(destinatario, opzioniEmail, opzioniTelegram) { - const risultati = { - email: null, - telegram: null, - }; - - // Invia email - if (destinatario.email) { - risultati.email = await this._inviaEmail( - destinatario.email, - opzioniEmail.oggetto, - opzioniEmail.html, - opzioniEmail.templatePath, - opzioniEmail.templateData - ); - } - - // Invia Telegram - if (destinatario.telegramId && destinatario.telegramId !== 0) { - risultati.telegram = await this._inviaTelegram( - destinatario.telegramId, - opzioniTelegram.messaggio, - opzioniTelegram.opzioni - ); - } - - return risultati; - } - - /** - * Invia copia all'amministratore - * @private - */ - async _inviaCopiaCopiaAdmin(oggetto, messaggio) { - const risultati = { - email: null, - telegram: null, - }; - - // Email admin - if (this.adminEmail) { - risultati.email = await this._inviaEmail(this.adminEmail, `[ADMIN] ${oggetto}`, messaggio); - } - - // Telegram admin - if (this.adminTelegramId) { - risultati.telegram = await this._inviaTelegram(this.adminTelegramId, `🔔 NOTIFICA ADMIN\n\n${messaggio}`); - } - - return risultati; - } - - // ============================================ - // EVENTO 1: REGISTRAZIONE UTENTE - // ============================================ - - /** - * Gestisce le notifiche dopo la registrazione - * @param {Object} utente - Dati dell'utente registrato - * @param {String} tokenVerifica - Token per verifica email - */ - async notificaRegistrazione(utente, tokenVerifica) { - try { - this.logger.info(`Notifica registrazione per utente: ${utente.username}`); - - // Se l'email è già verificata, salta la verifica e vai direttamente alla richiesta ammissione - if (utente.verified_email === true) { - this.logger.info(`Email già verificata per ${utente.username}, salto verifica email`); - - // Invia direttamente la richiesta di ammissione all'invitante - await this.notificaRichiestaAmmissione(utente); - - return { - success: true, - message: 'Email già verificata, richiesta ammissione inviata', - emailVerificaInviata: false, - }; - } - - // Email non verificata: invia email di verifica - const linkVerifica = `${this.baseUrl}/verifica-email/${tokenVerifica}`; - - const templateData = { - name: utente.name, - username: utente.username, - emailto: utente.email, - nomeapp: this.nomeApp, - baseurl: this.baseUrl, - linkVerifica: linkVerifica, - }; - - const risultato = await this._inviaEmail( - utente.email, - `Verifica il tuo indirizzo email - ${this.nomeApp}`, - null, - this.emailTemplates.verificaEmail, - templateData - ); - - // Notifica admin della nuova registrazione - const messaggioAdmin = ` -📝 Nuova Registrazione - -👤 Username: ${utente.username} -📧 Email: ${utente.email} -${utente.name ? `🏷️ Nome: ${utente.name}` : ''} -✅ Email verificata: ${utente.verified_email ? 'Sì' : 'No'} -📅 Data: ${new Date().toLocaleString('it-IT')} - -${utente.verified_email ? "✓ Richiesta ammissione inviata all'invitante" : '⏳ In attesa verifica email'} - `.trim(); - - await this._inviaCopiaCopiaAdmin('Nuova Registrazione', messaggioAdmin); - - return { - success: true, - message: 'Email di verifica inviata', - emailVerificaInviata: true, - risultato, - }; - } catch (error) { - this.logger.error('Errore in notificaRegistrazione:', error); - throw error; - } - } - - // ============================================ - // EVENTO 2: EMAIL VERIFICATA - // ============================================ - - /** - * Notifica l'invitante che l'utente ha verificato l'email - * @param {Object} utente - Dati dell'utente che ha verificato l'email - */ - async notificaRichiestaAmmissione(utente) { - try { - this.logger.info(`Notifica richiesta ammissione per utente: ${utente.username}`); - - // Recupera dati invitante (assumendo che tu abbia un metodo per recuperarlo) - const invitante = await this._getInvitante(utente.invitante_id); - - if (!invitante) { - throw new Error(`Invitante non trovato per utente ${utente.username}`); - } - - // Dati per email invitante - const templateDataInvitante = { - nomeInvitante: invitante.name || invitante.username, - nomeUtente: utente.name || utente.username, - usernameUtente: utente.username, - emailUtente: utente.email, - nomeapp: this.nomeApp, - baseurl: this.baseUrl, - linkAmmetti: `${this.baseUrl}/admin/ammetti-utente/${utente.id}`, - dataRegistrazione: new Date(utente.created_at).toLocaleDateString('it-IT'), - }; - - // Messaggio Telegram per invitante - const messaggioTelegramInvitante = ` -🎉 Nuovo Utente da Ammettere! - -Ciao ${invitante.name || invitante.username}! - -L'utente che hai invitato ha completato la registrazione: - -👤 Nome: ${utente.name || 'Non specificato'} -🔑 Username: ${utente.username} -📧 Email: ${utente.email} -📅 Registrato il: ${new Date(utente.created_at).toLocaleDateString('it-IT')} - -✅ Azione richiesta: Accedi alla piattaforma per ammettere questo utente alla comunità RISO. - -👉 Clicca qui per ammettere - `.trim(); - - // Invia notifica all'invitante - const risultatiInvitante = await this._inviaNotificaDoppia( - { - email: invitante.email, - telegramId: invitante.teleg_id, - }, - { - oggetto: `Nuovo utente da ammettere: ${utente.username}`, - templatePath: this.emailTemplates.richiestaAmmissione, - templateData: templateDataInvitante, - }, - { - messaggio: messaggioTelegramInvitante, - opzioni: { - reply_markup: { - inline_keyboard: [ - [{ text: '✅ Ammetti Utente', url: `${this.baseUrl}/admin/ammetti-utente/${utente.id}` }], - ], - }, - }, - } - ); - - // Notifica admin - const messaggioAdmin = ` -✅ Email Verificata - Richiesta Ammissione - -👤 Utente: ${utente.username} (${utente.email}) -👥 Invitante: ${invitante.username} (${invitante.email}) -📅 Data verifica: ${new Date().toLocaleString('it-IT')} - -📧 Notifica inviata all'invitante - `.trim(); - - await this._inviaCopiaCopiaAdmin('Richiesta Ammissione', messaggioAdmin); - - return { - success: true, - message: 'Notifica richiesta ammissione inviata', - risultatiInvitante, - }; - } catch (error) { - this.logger.error('Errore in notificaRichiestaAmmissione:', error); - throw error; - } - } - - // ============================================ - // EVENTO 3: UTENTE AMMESSO - // ============================================ - - /** - * Invia email di benvenuto all'utente ammesso - * @param {Object} utente - Dati dell'utente ammesso - */ - async notificaUtenteAmmesso(utente) { - try { - this.logger.info(`Notifica utente ammesso: ${utente.username}`); - - // Dati per email benvenuto - const templateData = { - name: utente.name, - username: utente.username, - emailto: utente.email, - nomeapp: this.nomeApp, - baseurl: this.baseUrl, - strlinksito: this.baseUrl, - forgetpwd: `${this.baseUrl}/reset-password`, - verified_email: true, - }; - - // Invia email di benvenuto (template già esistente) - const risultatoEmail = await this._inviaEmail( - utente.email, - `💚 Benvenuto nella comunità ${this.nomeApp}!`, - null, - this.emailTemplates.benvenuto, - templateData - ); - - // Messaggio Telegram all'utente (se ha già Telegram collegato) - if (utente.teleg_id && utente.teleg_id !== 0) { - const messaggioTelegramUtente = ` -🎉 Benvenuto nella comunità RISO! - -Ciao ${utente.name || utente.username}! - -Sei stato ammesso nella rete RISO! 🌱 - -Ora puoi: -✅ Completare il tuo profilo -📢 Pubblicare i tuoi primi annunci -🔍 Esplorare beni e servizi nella tua comunità -💬 Unirti al gruppo territoriale - -👉 Accedi ora alla piattaforma - -Costruiamo insieme un'economia più umana e solidale! 💚 - `.trim(); - - await this._inviaTelegram(utente.teleg_id, messaggioTelegramUtente, { - reply_markup: { - inline_keyboard: [[{ text: '🚀 Vai alla Piattaforma', url: this.baseUrl }]], - }, - }); - } - - // Notifica admin - const messaggioAdmin = ` -✅ Utente Ammesso - -👤 Username: ${utente.username} -📧 Email: ${utente.email} -${utente.name ? `🏷️ Nome: ${utente.name}` : ''} -📅 Ammesso il: ${new Date().toLocaleString('it-IT')} - -📧 Email di benvenuto inviata -${utente.teleg_id && utente.teleg_id !== 0 ? '📱 Notifica Telegram inviata' : '⏳ Telegram non ancora collegato'} - `.trim(); - - await this._inviaCopiaCopiaAdmin('Utente Ammesso', messaggioAdmin); - - return { - success: true, - message: 'Notifica utente ammesso inviata', - risultatoEmail, - }; - } catch (error) { - this.logger.error('Errore in notificaUtenteAmmesso:', error); - throw error; - } - } - - // ============================================ - // EVENTO 4: PROFILO COMPLETATO + TELEGRAM VERIFICATO - // ============================================ - - /** - * Notifica l'invitante che l'utente ha completato il profilo e verificato Telegram - * @param {Object} utente - Dati dell'utente che ha completato il profilo - */ - async notificaProfiloCompletato(utente) { - try { - this.logger.info(`Notifica profilo completato per utente: ${utente.username}`); - - // Verifica che il profilo sia effettivamente completo e Telegram verificato - if (!utente.teleg_id || utente.teleg_id === 0) { - this.logger.warn(`Telegram non verificato per ${utente.username}`); - return { - success: false, - message: 'Telegram non ancora verificato', - }; - } - - // Recupera invitante - const invitante = await this._getInvitante(utente.invitante_id); - - if (!invitante) { - throw new Error(`Invitante non trovato per utente ${utente.username}`); - } - - // Dati per email invitante - const templateDataInvitante = { - nomeInvitante: invitante.name || invitante.username, - nomeUtente: utente.name || utente.username, - usernameUtente: utente.username, - nomeapp: this.nomeApp, - baseurl: this.baseUrl, - linkProfilo: `${this.baseUrl}/utenti/${utente.username}`, - }; - - // Messaggio Telegram per invitante - const messaggioTelegramInvitante = ` -🎊 Profilo Completato! - -Ciao ${invitante.name || invitante.username}! - -L'utente che hai invitato ha completato il suo profilo ed è ora attivo su RISO: - -👤 Nome: ${utente.name || utente.username} -🔑 Username: @${utente.username} -✅ Telegram: Verificato -📱 Profilo: Completato - -L'utente è ora un membro attivo della comunità e può iniziare a pubblicare annunci! - -👉 Visualizza profilo - `.trim(); - - // Invia notifica all'invitante - const risultatiInvitante = await this._inviaNotificaDoppia( - { - email: invitante.email, - telegramId: invitante.teleg_id, - }, - { - oggetto: `${utente.username} ha completato il profilo su ${this.nomeApp}!`, - templatePath: this.emailTemplates.profiloCompletato, - templateData: templateDataInvitante, - }, - { - messaggio: messaggioTelegramInvitante, - opzioni: { - reply_markup: { - inline_keyboard: [[{ text: '👤 Visualizza Profilo', url: `${this.baseUrl}/utenti/${utente.username}` }]], - }, - }, - } - ); - - // Notifica admin - const messaggioAdmin = ` -✅ Profilo Completato - -👤 Utente: ${utente.username} -📧 Email: ${utente.email} -📱 Telegram: Verificato (ID: ${utente.teleg_id}) -👥 Invitante: ${invitante.username} -📅 Data: ${new Date().toLocaleString('it-IT')} - -✅ L'utente è ora completamente attivo sulla piattaforma - `.trim(); - - await this._inviaCopiaCopiaAdmin('Profilo Completato', messaggioAdmin); - - return { - success: true, - message: 'Notifica profilo completato inviata', - risultatiInvitante, - }; - } catch (error) { - this.logger.error('Errore in notificaProfiloCompletato:', error); - throw error; - } - } - - // ============================================ - // METODI HELPER - // ============================================ - - /** - * Recupera i dati dell'invitante (da implementare con il tuo DB) - * @private - */ - async _getInvitante(invitanteId) { - // TODO: Implementa il recupero dell'invitante dal database - // Esempio con MongoDB: - // return await User.findById(invitanteId); - - // Esempio con MySQL/PostgreSQL: - // return await db.query('SELECT * FROM users WHERE id = ?', [invitanteId]); - - throw new Error('Metodo _getInvitante non implementato. Implementalo con il tuo database.'); - } - - /** - * Verifica se il profilo utente è completo - * @param {Object} utente - * @returns {Boolean} - */ - isProfiloCompleto(utente) { - // Definisci i criteri per considerare un profilo completo - return !!( - (utente.name && utente.email && utente.teleg_id && utente.teleg_id !== 0) - // Aggiungi altri campi necessari - ); - } - - /** - * Metodo principale per orchestrare le notifiche basate sugli eventi - * @param {String} evento - Tipo di evento - * @param {Object} dati - Dati dell'evento - */ - async gestisciEvento(evento, dati) { - try { - switch (evento) { - case 'REGISTRAZIONE': - return await this.notificaRegistrazione(dati.utente, dati.tokenVerifica); - - case 'EMAIL_VERIFICATA': - return await this.notificaRichiestaAmmissione(dati.utente); - - case 'UTENTE_AMMESSO': - return await this.notificaUtenteAmmesso(dati.utente); - - case 'PROFILO_COMPLETATO': - // Verifica che Telegram sia effettivamente verificato - if (dati.utente.teleg_id && dati.utente.teleg_id !== 0) { - return await this.notificaProfiloCompletato(dati.utente); - } else { - this.logger.warn(`Profilo completato ma Telegram non verificato per ${dati.utente.username}`); - return { success: false, message: 'Telegram non verificato' }; - } - - default: - throw new Error(`Evento non riconosciuto: ${evento}`); - } - } catch (error) { - this.logger.error(`Errore gestione evento ${evento}:`, error); - throw error; - } - } -} - -module.exports = InvioNotifiche; diff --git a/src/modules/InvioNotifiche.test.js b/src/modules/InvioNotifiche.test.js deleted file mode 100644 index 98d8b99..0000000 --- a/src/modules/InvioNotifiche.test.js +++ /dev/null @@ -1,541 +0,0 @@ -/** - * TEST UNITARI PER LA CLASSE InvioNotifiche - * - * Framework: Jest - * Installazione: npm install --save-dev jest - * Esecuzione: npm test - */ - -const InvioNotifiche = require('./InvioNotifiche'); - -// Mock dei servizi esterni -const mockEmailService = { - sendMail: jest.fn().mockResolvedValue({ messageId: 'mock-email-id' }) -}; - -const mockTelegramBot = { - sendMessage: jest.fn().mockResolvedValue({ message_id: 123 }) -}; - -const mockLogger = { - info: jest.fn(), - warn: jest.fn(), - error: jest.fn() -}; - -describe('InvioNotifiche', () => { - let notifiche; - - beforeEach(() => { - // Reset dei mock prima di ogni test - jest.clearAllMocks(); - - // Inizializza classe con mock - notifiche = new InvioNotifiche({ - emailService: mockEmailService, - telegramBot: mockTelegramBot, - adminTelegramId: '999999999', - adminEmail: 'paolo@riso.app', - baseUrl: 'https://riso.app', - nomeApp: 'RISO', - emailTemplates: { - verificaEmail: './templates/verifica.pug', - richiestaAmmissione: './templates/ammissione.pug', - benvenuto: './templates/benvenuto.pug', - profiloCompletato: './templates/profilo.pug' - }, - logger: mockLogger - }); - - // Mock del metodo _getInvitante - notifiche._getInvitante = jest.fn().mockResolvedValue({ - id: 5, - username: 'invitante', - email: 'invitante@example.com', - name: 'Marco Invitante', - teleg_id: 111111111 - }); - }); - - // ============================================ - // TEST: notificaRegistrazione - // ============================================ - - describe('notificaRegistrazione', () => { - - test('Invia email di verifica quando verified_email = false', async () => { - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - name: 'Mario Rossi', - verified_email: false, - invitante_id: 5 - }; - - const result = await notifiche.notificaRegistrazione(utente, 'token123'); - - // Verifica che l'email sia stata inviata - expect(mockEmailService.sendMail).toHaveBeenCalledTimes(2); // utente + admin - expect(result.emailVerificaInviata).toBe(true); - expect(result.success).toBe(true); - - // Verifica logging - expect(mockLogger.info).toHaveBeenCalledWith( - expect.stringContaining('Notifica registrazione') - ); - }); - - test('Salta verifica email quando verified_email = true', async () => { - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - name: 'Mario Rossi', - verified_email: true, - invitante_id: 5 - }; - - const result = await notifiche.notificaRegistrazione(utente, null); - - // Verifica che NON sia stata inviata email di verifica - expect(result.emailVerificaInviata).toBe(false); - expect(result.success).toBe(true); - - // Verifica che sia stata chiamata notificaRichiestaAmmissione - expect(notifiche._getInvitante).toHaveBeenCalledWith(5); - }); - - test('Gestisce errori correttamente', async () => { - mockEmailService.sendMail.mockRejectedValueOnce(new Error('SMTP Error')); - - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - verified_email: false, - invitante_id: 5 - }; - - await expect( - notifiche.notificaRegistrazione(utente, 'token123') - ).rejects.toThrow(); - - expect(mockLogger.error).toHaveBeenCalled(); - }); - }); - - // ============================================ - // TEST: notificaRichiestaAmmissione - // ============================================ - - describe('notificaRichiestaAmmissione', () => { - - test('Invia notifica email e telegram all\'invitante', async () => { - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - name: 'Mario Rossi', - invitante_id: 5, - created_at: new Date() - }; - - const result = await notifiche.notificaRichiestaAmmissione(utente); - - // Verifica chiamate - expect(notifiche._getInvitante).toHaveBeenCalledWith(5); - expect(mockEmailService.sendMail).toHaveBeenCalled(); - expect(mockTelegramBot.sendMessage).toHaveBeenCalled(); - expect(result.success).toBe(true); - }); - - test('Gestisce invitante non trovato', async () => { - notifiche._getInvitante.mockResolvedValueOnce(null); - - const utente = { - id: 1, - username: 'mario.rossi', - invitante_id: 999 - }; - - await expect( - notifiche.notificaRichiestaAmmissione(utente) - ).rejects.toThrow('Invitante non trovato'); - }); - - test('Invia notifica anche se Telegram fallisce', async () => { - mockTelegramBot.sendMessage.mockRejectedValueOnce(new Error('Telegram Error')); - - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - invitante_id: 5, - created_at: new Date() - }; - - const result = await notifiche.notificaRichiestaAmmissione(utente); - - // Email dovrebbe essere comunque inviata - expect(mockEmailService.sendMail).toHaveBeenCalled(); - expect(mockLogger.error).toHaveBeenCalledWith( - expect.stringContaining('Errore invio Telegram'), - expect.any(Error) - ); - }); - }); - - // ============================================ - // TEST: notificaUtenteAmmesso - // ============================================ - - describe('notificaUtenteAmmesso', () => { - - test('Invia email di benvenuto all\'utente', async () => { - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - name: 'Mario Rossi', - teleg_id: 0 - }; - - const result = await notifiche.notificaUtenteAmmesso(utente); - - expect(mockEmailService.sendMail).toHaveBeenCalled(); - expect(result.success).toBe(true); - - // Verifica oggetto email - const emailCall = mockEmailService.sendMail.mock.calls[0][0]; - expect(emailCall.subject).toContain('Benvenuto'); - }); - - test('Invia anche Telegram se utente ha teleg_id', async () => { - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - name: 'Mario Rossi', - teleg_id: 123456789 - }; - - await notifiche.notificaUtenteAmmesso(utente); - - expect(mockTelegramBot.sendMessage).toHaveBeenCalledWith( - 123456789, - expect.stringContaining('Benvenuto'), - expect.any(Object) - ); - }); - - test('Salta Telegram se teleg_id = 0', async () => { - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - teleg_id: 0 - }; - - await notifiche.notificaUtenteAmmesso(utente); - - // Solo email, no Telegram - expect(mockTelegramBot.sendMessage).not.toHaveBeenCalled(); - }); - }); - - // ============================================ - // TEST: notificaProfiloCompletato - // ============================================ - - describe('notificaProfiloCompletato', () => { - - test('Invia notifica se Telegram è verificato', async () => { - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - name: 'Mario Rossi', - teleg_id: 123456789, - invitante_id: 5 - }; - - const result = await notifiche.notificaProfiloCompletato(utente); - - expect(notifiche._getInvitante).toHaveBeenCalledWith(5); - expect(mockEmailService.sendMail).toHaveBeenCalled(); - expect(mockTelegramBot.sendMessage).toHaveBeenCalled(); - expect(result.success).toBe(true); - }); - - test('Non invia se Telegram non verificato', async () => { - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - teleg_id: 0, - invitante_id: 5 - }; - - const result = await notifiche.notificaProfiloCompletato(utente); - - expect(result.success).toBe(false); - expect(result.message).toContain('Telegram non ancora verificato'); - expect(mockEmailService.sendMail).not.toHaveBeenCalled(); - }); - }); - - // ============================================ - // TEST: gestisciEvento - // ============================================ - - describe('gestisciEvento', () => { - - test('Gestisce evento REGISTRAZIONE', async () => { - const spy = jest.spyOn(notifiche, 'notificaRegistrazione'); - - await notifiche.gestisciEvento('REGISTRAZIONE', { - utente: { username: 'test' }, - tokenVerifica: 'token123' - }); - - expect(spy).toHaveBeenCalled(); - }); - - test('Gestisce evento EMAIL_VERIFICATA', async () => { - const spy = jest.spyOn(notifiche, 'notificaRichiestaAmmissione'); - - await notifiche.gestisciEvento('EMAIL_VERIFICATA', { - utente: { username: 'test', invitante_id: 5 } - }); - - expect(spy).toHaveBeenCalled(); - }); - - test('Gestisce evento UTENTE_AMMESSO', async () => { - const spy = jest.spyOn(notifiche, 'notificaUtenteAmmesso'); - - await notifiche.gestisciEvento('UTENTE_AMMESSO', { - utente: { username: 'test' } - }); - - expect(spy).toHaveBeenCalled(); - }); - - test('Gestisce evento PROFILO_COMPLETATO solo se Telegram verificato', async () => { - const spy = jest.spyOn(notifiche, 'notificaProfiloCompletato'); - - // Con Telegram verificato - await notifiche.gestisciEvento('PROFILO_COMPLETATO', { - utente: { username: 'test', teleg_id: 123, invitante_id: 5 } - }); - - expect(spy).toHaveBeenCalled(); - - spy.mockClear(); - - // Senza Telegram - const result = await notifiche.gestisciEvento('PROFILO_COMPLETATO', { - utente: { username: 'test', teleg_id: 0 } - }); - - expect(spy).not.toHaveBeenCalled(); - expect(result.success).toBe(false); - }); - - test('Lancia errore per evento non riconosciuto', async () => { - await expect( - notifiche.gestisciEvento('EVENTO_INESISTENTE', {}) - ).rejects.toThrow('Evento non riconosciuto'); - }); - }); - - // ============================================ - // TEST: isProfiloCompleto - // ============================================ - - describe('isProfiloCompleto', () => { - - test('Ritorna true se profilo completo', () => { - const utente = { - name: 'Mario Rossi', - email: 'mario@example.com', - teleg_id: 123456789 - }; - - expect(notifiche.isProfiloCompleto(utente)).toBe(true); - }); - - test('Ritorna false se manca name', () => { - const utente = { - email: 'mario@example.com', - teleg_id: 123456789 - }; - - expect(notifiche.isProfiloCompleto(utente)).toBe(false); - }); - - test('Ritorna false se manca email', () => { - const utente = { - name: 'Mario Rossi', - teleg_id: 123456789 - }; - - expect(notifiche.isProfiloCompleto(utente)).toBe(false); - }); - - test('Ritorna false se Telegram non verificato', () => { - const utente = { - name: 'Mario Rossi', - email: 'mario@example.com', - teleg_id: 0 - }; - - expect(notifiche.isProfiloCompleto(utente)).toBe(false); - }); - }); - - // ============================================ - // TEST: Metodi Privati - // ============================================ - - describe('Metodi privati', () => { - - test('_inviaEmail invia email correttamente', async () => { - const result = await notifiche._inviaEmail( - 'test@example.com', - 'Test Subject', - '

Test HTML

' - ); - - expect(result.success).toBe(true); - expect(mockEmailService.sendMail).toHaveBeenCalledWith( - expect.objectContaining({ - to: 'test@example.com', - subject: 'Test Subject', - html: '

Test HTML

' - }) - ); - }); - - test('_inviaTelegram invia messaggio correttamente', async () => { - const result = await notifiche._inviaTelegram( - 123456789, - 'Test message' - ); - - expect(result.success).toBe(true); - expect(mockTelegramBot.sendMessage).toHaveBeenCalledWith( - 123456789, - 'Test message', - expect.any(Object) - ); - }); - - test('_inviaTelegram gestisce ID non valido', async () => { - const result = await notifiche._inviaTelegram(0, 'Test'); - - expect(result.success).toBe(false); - expect(result.error).toContain('non valido'); - expect(mockLogger.warn).toHaveBeenCalled(); - }); - - test('_inviaCopiaCopiaAdmin invia a email e telegram admin', async () => { - await notifiche._inviaCopiaCopiaAdmin('Test', 'Message'); - - expect(mockEmailService.sendMail).toHaveBeenCalledWith( - expect.objectContaining({ - to: 'admin@riso.app', - subject: '[ADMIN] Test' - }) - ); - - expect(mockTelegramBot.sendMessage).toHaveBeenCalledWith( - '999999999', - expect.stringContaining('NOTIFICA ADMIN'), - expect.any(Object) - ); - }); - }); -}); - -// ============================================ -// TEST: Integrazione -// ============================================ - -describe('Test di Integrazione', () => { - let notifiche; - - beforeEach(() => { - notifiche = new InvioNotifiche({ - emailService: mockEmailService, - telegramBot: mockTelegramBot, - adminTelegramId: '999999999', - adminEmail: 'admin@riso.app', - baseUrl: 'https://riso.app', - nomeApp: 'RISO', - emailTemplates: {}, - logger: mockLogger - }); - - notifiche._getInvitante = jest.fn().mockResolvedValue({ - id: 5, - username: 'invitante', - email: 'invitante@example.com', - teleg_id: 111111111 - }); - }); - - test('Flusso completo: Registrazione → Verifica → Ammissione → Profilo', async () => { - const utente = { - id: 1, - username: 'mario.rossi', - email: 'mario@example.com', - name: 'Mario Rossi', - verified_email: false, - invitante_id: 5, - teleg_id: 0, - created_at: new Date() - }; - - // 1. Registrazione - await notifiche.notificaRegistrazione(utente, 'token123'); - expect(mockEmailService.sendMail).toHaveBeenCalled(); - - // 2. Verifica email - utente.verified_email = true; - await notifiche.notificaRichiestaAmmissione(utente); - expect(notifiche._getInvitante).toHaveBeenCalled(); - - // 3. Ammissione - await notifiche.notificaUtenteAmmesso(utente); - expect(mockEmailService.sendMail).toHaveBeenCalled(); - - // 4. Profilo completato - utente.teleg_id = 123456789; - await notifiche.notificaProfiloCompletato(utente); - expect(mockTelegramBot.sendMessage).toHaveBeenCalled(); - - // Verifica che tutte le notifiche admin siano state inviate - const adminCalls = mockEmailService.sendMail.mock.calls.filter( - call => call[0].subject.includes('[ADMIN]') - ); - expect(adminCalls.length).toBeGreaterThan(0); - }); -}); - -// Configurazione package.json per Jest -/* -{ - "scripts": { - "test": "jest", - "test:watch": "jest --watch", - "test:coverage": "jest --coverage" - }, - "jest": { - "testEnvironment": "node", - "coveragePathIgnorePatterns": ["/node_modules/"], - "testMatch": ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"] - } -} -*/ diff --git a/src/router/index_router.js b/src/router/index_router.js index 5912bce..9d16922 100755 --- a/src/router/index_router.js +++ b/src/router/index_router.js @@ -143,9 +143,9 @@ router.post('/ammetti', (req, res) => { } else { const lang = user.lang; console.log('user', user); - user.verified_by_aportador = false; + // user.verified_by_aportador = false; if (user.verified_by_aportador) { - res.send({ + return res.send({ code: server_constants.RIS_CODE_GIA_AMMESSO, msg: 'Il membro ' + user.username + ' è stato già Ammesso!', }); @@ -180,7 +180,7 @@ router.post('/ammetti', (req, res) => { // user.token_da_ammettere = 'OK'; user.save().then(() => { - res.send({ + return res.send({ code: server_constants.RIS_CODE_AMMESSO, msg: 'Ottimo! Hai ammesso ' + user.username + '!', //msg: tools.getres__('Ottimo! Hai ammesso', res) + ' ' + user.username + '!', @@ -199,6 +199,68 @@ router.post('/ammetti', (req, res) => { } }); +router.post('/abcirc', async (req, res) => { + const body = _.pick(req.body, ['idapp', 'token', 'username', 'username_action', 'cmd', 'groupname']); + const idapp = body.idapp; + const token = body.token; + const username = body.username; + const groupname = body.groupname; + const username_action = body.username_action; + const cmd = body.cmd; + + try { + // Cerco il token se è ancora da ammettere + + await User.getCircuitByTokenAndUsername(idapp, username, token) + .then(async (ris) => { + const { circuitname, user } = ris; + if (!user) { + return res.status(404).send(); + } else { + const lang = user.lang; + // console.log('user', user); + + let nomeCircuito = circuitname; + let giaabilitato = false; + + let ret = null; + + // user.verified_by_aportador = false; + if (giaabilitato) { + res.send({ + code: server_constants.RIS_CODE_GIA_AMMESSO, + msg: 'Il membro ' + user.username + ' è stato già Abilitato!', + circuitName: nomeCircuito, + }); + } else { + ret = await User.setCircuitCmd(user.idapp, username, nomeCircuito, cmd, 0, username_action, { + groupname, + }); + return res.send({ + code: server_constants.RIS_CODE_AMMESSO, + msg: 'Ottimo! Hai abilitato ' + user.username + ' al circuito ' + nomeCircuito + '!', + circuitName: nomeCircuito, + //msg: tools.getres__('Ottimo! Hai ammesso', res) + ' ' + user.username + '!', + }); + } + + return res.send({ + code: server_constants.RIS_CODE_GIA_AMMESSO, + msg: 'L\'utente è già stato abilitato al circuito ' + nomeCircuito + '!', + circuitName: nomeCircuito, + }); + } + }) + .catch((e) => { + console.log('Errore Abilitazione Circuito:', e.message); + res.status(400).send(); + }); + } catch (e) { + console.error('Errore: ', e); + res.status(400).send(); + } +}); + router.post(process.env.LINKVERIF_REG, (req, res) => { const body = _.pick(req.body, ['idapp', 'idlink']); const idapp = body.idapp; @@ -1597,7 +1659,9 @@ router.patch('/chval', authenticate, async (req, res) => { profileData = await User.updateProvinceUserByComune(idapp, id, idcomune); - provincia = profileData['profile.resid_province']; + provincia = profileData.profile.resid_province; + } else { + provincia = rec.profile.resid_province; } if (provincia) { diff --git a/src/sendemail.js b/src/sendemail.js index c57b616..24efd3a 100755 --- a/src/sendemail.js +++ b/src/sendemail.js @@ -505,9 +505,16 @@ module.exports = { } return ''; }, + getLinkAbilitaCircuito: function (idapp, user, data) { + if (data.token_circuito_da_ammettere) { + const strlink = tools.getHostByIdApp(idapp) + `/abcirc/${data.cmd}/${data.token_circuito_da_ammettere}/${user.username}`; + return strlink; + } + return ''; + }, getPathEmail(idapp, email_template) { - const RISO_TEMPLATES = ['reg_notifica_all_invitante', 'reg_email_benvenuto_ammesso', 'reg_chiedi_ammettere_all_invitante']; + const RISO_TEMPLATES = ['reg_notifica_all_invitante', 'reg_email_benvenuto_ammesso', 'reg_chiedi_ammettere_all_invitante', 'circuit_chiedi_facilitatori_di_entrare']; if (idapp === '13') { if (RISO_TEMPLATES.includes(email_template)) { @@ -667,6 +674,53 @@ module.exports = { console.error('Err sendEmail_Utente_Ammesso', e); } }, + sendEmail_Richiesta_Al_Facilitatore_Di_FarEntrare_AlCircuito: async function (lang, emailto, user, userInvitante, idapp, dati) { + try { + // dati.circuitId + // dati.groupname + dati.cmd = shared_consts.CallFunz.RICHIESTA_FIDO; + + const linkAbilitazione = this.getLinkAbilitaCircuito(idapp, user, dati); + + let mylocalsconf = { + idapp, + dataemail: await this.getdataemail(idapp), + baseurl: tools.getHostByIdApp(idapp), + locale: lang, + usernameInvitante: user.aportador_solidario, + nomeInvitante: userInvitante.name, + cognomeInvitante: userInvitante.surname, + nomeapp: tools.getNomeAppByIdApp(idapp), + strlinksito: tools.getHostByIdApp(idapp), + //strlinkreg: this.getlinkReg(idapp, idreg), + emailto: emailto, + usernameMembro: user.username, + nomeMembro: user.name, + cognomeMembro: user.surname, + emailMembro: user.email, + nomeFacilitatore: dati.nomeFacilitatore, + nomeTerritorio: dati.nomeTerritorio, + comuneResidenza: user.profile.resid_str_comune, + provinciaResidenza: user.profile.resid_province, + user, + linkAbilitazione: linkAbilitazione, + linkProfiloMembro: tools.getLinkUserProfile(idapp, user.username), + linkProfiloInvitante: tools.getLinkUserProfile(idapp, user.aportador_solidario), + telegramMembro: user.profile?.username_telegram, + telegramInvitante: userInvitante.profile?.username_telegram, + }; + + const quale_email_inviare = this.getPathEmail(idapp, 'circuit_chiedi_facilitatori_di_entrare') + '/' + lang; + + const ris = await this.sendEmail_base(quale_email_inviare, emailto, mylocalsconf, ''); + + // await telegrambot.notifyToTelegram(telegrambot.phase.AMMETTI_UTENTE, mylocalsconf); + + return ris; + } catch (e) { + console.error('Err sendEmail_Richiesta_Al_Facilitatore_Di_FarEntrare_AlCircuito', e); + } + }, sendEmail_IscrizioneConacreis: async function (lang, emailto, iscritto, idapp) { // console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp)); diff --git a/src/telegram/telegrambot.js b/src/telegram/telegrambot.js index 3503318..0189e53 100644 --- a/src/telegram/telegrambot.js +++ b/src/telegram/telegrambot.js @@ -451,7 +451,7 @@ const txt = { MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Amicizia di %s !', MSG_HANDSHAKE_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Stretta di mano di %s !', - MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!', + MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s) tramite Telegram!', MSG_APORTADOR_DEST_CONFIRMED: '✅ La tua registrazione a %s è stata accettata da %s!\n' + 'Vai sulla App oppure clicca qui per entrare\n👉🏻 %s', MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!', @@ -838,6 +838,8 @@ const MyTelegramBot = { groupname = '' ) { try { + const sendemail = require('../sendemail'); + const cl = getclTelegByidapp(idapp); if (!cl) return false; @@ -1000,6 +1002,7 @@ const MyTelegramBot = { groupid + tools.SEP + groupname, },*/ ]); + send_notif = true; } else { msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest }, myuser.username, name); @@ -1032,6 +1035,37 @@ const MyTelegramBot = { ]); send_notif = true; } + + const mycircuit = await Circuit.getCircuitByCircuitId(circuitId); + // Invia Email ai facilitatori + // const usersmanagers = await Circuit.getListAdminsByCircuitPath(myuser.idapp, mycircuit.path); + + // Ottiene il token relativo all'Utente e a quel circuito + const token = await User.getTokenByUsernameAndCircuitName(myuser.idapp, myuser.username, mycircuit.name); + + if (token) { + const data = { + token_circuito_da_ammettere: token, + nomeTerritorio: mycircuit.name, + }; + // if (usersmanagers) { + // for (const recadminCirc of usersmanagers) { + data.nomeFacilitatore = userrecDest.username; + + const myusercompleto = await User.getUserByUsername(myuser.idapp, myuser.username); + const userInvitante = await User.getUserByUsername(myuser.idapp, myusercompleto.aportador_solidario); + + await sendemail.sendEmail_Richiesta_Al_Facilitatore_Di_FarEntrare_AlCircuito( + myuser.lang, + userrecDest.email, + myusercompleto, + userInvitante, + idapp, + data + ); + } + // } + // } } else if (myfunc === shared_consts.CallFunz.RICHIESTA_CIRCUIT) { if (groupname) { msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP_CIRC', locale: langdest }, groupname); @@ -4574,7 +4608,7 @@ if (true) { userDest, null, user.idapp, - null, + null ); await local_sendMsgTelegram(user.idapp, data.username, msgOrig); diff --git a/src/telegram/telegrambot_OLD.js b/src/telegram/telegrambot_OLD.js deleted file mode 100755 index 29e2986..0000000 --- a/src/telegram/telegrambot_OLD.js +++ /dev/null @@ -1,4651 +0,0 @@ -const tools = require('../tools/general'); - -const appTelegram = [tools.FREEPLANET, tools.RISO]; - -const appTelegram_TEST = [tools.FREEPLANET, tools.RISO]; -//const appTelegram_DEVELOP = [tools.RISO]; -const appTelegram_DEVELOP = [tools.PIUCHEBUONO]; - -const appTelegramFinti = ['2', tools.CNM]; -const appTelegramDest = [tools.FREEPLANET, tools.FREEPLANET]; - -const appTeleg_BotOnGroup = [tools.IDAPP_BOTONGROUP]; - -const path = require('path'); -const fs = require('fs'); - -//PIPPO - -const printf = require('util').format; - -const { User, FuncUsers } = require('../models/user'); -const { MyGroup } = require('../models/mygroup'); -const { Circuit } = require('../models/circuit'); -const { CalZoom } = require('../models/calzoom'); -const { MyBot } = require('../models/bot'); -const shared_consts = require('../tools/shared_nodejs'); - -const sharp = require('sharp'); - -const axios = require('axios'); - -const server_constants = require('../tools/server_constants'); - -// const {ListaIngresso} = require('../models/listaingresso'); -const { MsgTemplate } = require('../models/msg_template'); - -const i18n = require('i18n'); - -let url = process.env.URL || 'https://'; - -const Benvenuto = '💓💓💓 Benvenuto/a!'; - -const emo = { - JOY: '😂', - JOY2: '🤣', - DANCER: '💃', - STARS: '✨', - FIRE: '🔥', - SUN: '☀️', - TV: '📺', - NEWSPAPER: '🗞', - KISS: '😘', - PENCIL: '✏️', - DREAM: '🏖', - EYES: '😜', - DIZZY: '💫', - ONE_HUNDRED: '💯', - SMILE_STAR: '🤩', // Star-struck - LEFT_FACING_FIST: '🤛', // Left-facing fist - CHECK_VERDE: '✅', // White check mark (verde) - CHECK_GRIGIA: '☑️', // Ballot box with check (grigia) - CROSS_ROSSA: '❌', // X (rossa) - ENVELOPE: '✉️', // Envelope - EXCLAMATION_MARK: '❗', // Exclamation mark - QUESTION_MARK: '❓', // Question mark - ARROW_RIGHT: '➡️', // Arrow pointing to the right - INVITATI: '', - HEART: '❤️', - BLUE_HEART: '💙', - GREEN_HEART: '💚', - YELLOW_HEART: '💛', - PURPLE_HEART: '💜', - GIFT_HEART: '💝', - GIFT: '🎁', - ROBOT_FACE: '🤖', - ADMIN: '💁', - MALE: '💁‍♂️', - FEMALE: '👩‍🦱', - INNOCENT: '😇', - CREDIT_CARD: '💳', - PERSON: '🧑', -}; - -MsgBot = { - OK: ['si', 'ok'], - CUORE: ['❤️', '💚️', '💜'], - CIAO: ['ciao', 'ciaoo', 'hola', 'holaa', 'hey', 'salve', 'buongiorno', 'buondi', 'ciao ❤️'], - CI_SEI: ['ci sei', "c'è qualcuno", "c'è nessuno"], - CHI_SONO_IO: ['chi sono io', 'chi sono'], - COME_STAI: ['tutto bene', 'come stai', 'come stai', 'come va', 'come butta', 'come va oggi'], - COME_TI_CHIAMI: [ - 'chi sei', - 'come ti chiami', - "qual'è il tuo nome", - "qual'e' il tuo nome", - 'che lavoro fai', - 'di cosa ti occupi', - ], - COSA_FAI: ['cosa fai', 'cosa combini', 'che fai'], - QUANTI_ANNI_HAI: ['quanti anni hai', 'che età hai'], - SEI_LIBERO_STASERA: [ - 'sei libera stasera', - 'sei libero stasera', - 'usciamo insieme', - "fare l'amore con me", - 'fare sesso', - 'vuoi scopare', - 'vuoi trombare', - ], - MI_TROVI_UN_MOROSO: [ - 'trovi un moroso', - 'una morosa', - 'fidanzato', - 'fidanzata', - 'trovi un marito', - 'trovi una moglie', - ], - CHAT_EMPOWER: ['chat empower'], - MASCHIO_FEMMINA: ['sei uomo o donna', 'sei maschio o femmina', 'sei ragazzo o ragazza', 'che sesso hai'], - DAMMI_UN_BACIO: ['dammi un bacio', 'baciami'], - HAHA: ['hahaha', 'ahah', '😂'], - MI_AMI: ['mi ami'], - TI_AMO: ['ti amo', 'ti adoro', 'ti lovvo'], - PREGO: ['prego', 'Prego ! 💋💋💋'], - GRAZIE: ['grazie ainy', 'grazie', 'grazie mille', 'graziee', 'grazie ❤', 'grazie️❤', 'grazie 😘', 'grazie😘'], - PRINCIPE_AZZURRO: ['principe azzurro'], - START_INV: ['/start inv'], - COSE_COVID: ["cos'è il covid", 'cosa è il covid'], - COVID: ['covid'], - SPOSAMI: ['sposami', 'vuoi sposar', 'sei sposat', 'ci sposiamo', 'ti sposo', 'sei sposat', 'mi sposi'], - CHE_TEMPO_FA: ['che tempo'], - NON_TROO_INVITATI: ['non trovo invitati', 'non riesco a trovare invitati'], - TROVAMI_UN_UOMO_DONNA: ['trovami un uomo', 'trovami una donna', 'esiste una donna per me', 'esiste un uomo per me'], - PAROLACCE: ['stronz', 'fanculo', 'fottiti', 'cagare', 'ammazzat', 'muori', 'cretino', 'stupido'], - COME_SI_CHIAMA: ['come si chiama'], - PROSSIMO_ZOOM: ['prossimo zoom', 'fare lo zoom', 'gli zoom', 'conferenz', 'zoom'], - LAVAGNA: ['lavagna', 'Lavagna', 'LAVAGNA'], - SEI_LIBERO_DI_RESPIRARE: ['sei libero di respirare'], - SEI_LIBERO: ['sei liber', 'sei sposat', 'sei fidanzat', 'sei single'], - AIUTO: [ - 'help', - 'aiuto', - 'ho bisogno di', - 'ho problemi', - 'non riesco', - 'mi puoi aiutare', - 'mi aiuti', - 'aiutami', - 'posso chiederti', - 'puoi aiutarmi', - ], - UOMO: ['uomo', 'maschio'], - SORPRESA: ['noo', 'davvero', 'sii', 'facciamo festa', 'è qui la festa', 'festa'], - UGUALE: ['👍🏻', '✨', '❤🏻', '⭐', '❤', '❤❤', '🤩'], - SI: ['si', 'yes'], - NO: ['no', 'noo'], - DONNA: ['donna', 'femmina'], - FARE_DOMANDA: ['fare una domanda', 'posso farti una domanda'], - DIVENTERO_RICCA: ['diventerò ricc'], - DOVE_VUOI_VIVERE: ['dove vuoi vivere'], - MA_ALLORA: ['ma allora'], -}; - -const MsgRisp = { - CHAT_EMPOWER: - 'Entra nella Chat EMPOWER !!!\n' + - 'https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g ' + - emo.PURPLE_HEART + - emo.GIFT_HEART + - emo.BLUE_HEART, -}; - -function getemojibynumber(number) { - if (number === 0) { - return '0️⃣'; // zero - } else if (number === 1) { - return '1️⃣'; // one - } else if (number === 2) { - return '2️⃣'; // two - } else if (number === 3) { - return '3️⃣'; // three - } else if (number === 4) { - return '4️⃣'; // four - } else if (number === 5) { - return '5️⃣'; // five - } else if (number === 6) { - return '6️⃣'; // six - } else if (number === 7) { - return '7️⃣'; // seven - } else if (number === 8) { - return '8️⃣'; // eight - } else if (number === 9) { - return '9️⃣'; // nine - } else { - return number; - } -} - -const Menu = { - LANG_IT: '🇮🇹 Italiano', // Bandiera italiana - LANG_EN: '🇬🇧 English', // Bandiera del Regno Unito - LANG_ES: '🇪🇸 Español', // Bandiera spagnola - LANG_FR: '🇫🇷 Français', // Bandiera francese - LANG_SI: '🇸🇮 Slovenski', // Bandiera slovena - LANG_PT: '🇵🇹 Português', // Bandiera portoghese - LANG: '🌐 Language', // Globo con meridiani - CHAT_PERSONALE: '👩‍💼💻', // Donna impiegata + computer - EXIT_TELEGRAM: 'exittotelegram', - MSG_TO_USER: 'sendmsgto', - ADMIN: '💁‍♀️ Admin', // Persona al banco informazioni - AIUTO: '🔮 Help', // Cristallo magico - ALTRO: '📰 Altro', // Giornale - SETPICPROFILE: '🖼 SetPicProfile', // Cornice con foto - RESETPWD: '🔑 SetResetPwd', // Chiave - MSG_SI_INVITATI_NO_7REQ_INVITATI: '📩Inv e NO 7 Req', // Busta - MSGSTAFF: '📩 Invia a STAFF', // Busta - MSGAPPARTIENE_CIRCUITI_RIS: 'Invia a Utenti dei Circuiti RIS', - MSGPAOLO: '📩 Invia a SURYA', // Busta - RESTART_SRV: '📩Restart-NodeJs', // Busta - REBOOT_SRV: '📩Reboot-VPS!', // Busta - EXECSH: '📩ExecSH', // Busta - LOG_SRV: '🖥Logserver.sh', // Monitor - MSGATUTTI: '📩 Invia a TUTTI', // Busta - it: { - ACCEDI: '👤 Accedi', // Persona - LAVAGNA: '🕉 Lavagna', // Simbolo Om - LINK_CONDIVIDERE: '🔗 Link da condividere', // Link - ZOOM: 'ℹ️ Zoom (Conferenze)', // Informazione - INFO: 'ℹ️ Informazioni', // Informazione - ASSISTENZA: '👐 Le Chat', // Mani aperte - INDIETRO: '🔙 Indietro', // Freccia indietro - SI: '👍 SI', // Pollice su - NO: '👎 NO', // Pollice giù - ESCI_DA_CHAT: '📩 Esci dalla Conversazione', // Busta - NUOVOSITO: '', - }, - es: { - ACCEDI: '👤 Entra', - LAVAGNA: '🕉 Tablero', - LINK_CONDIVIDERE: '🔗 Enlaces para compartir', - ZOOM: 'ℹ️ Zoom (Conferencias)', - INFO: 'ℹ️ Información', - ASSISTENZA: '👐 Chats', - INDIETRO: '🔙 Volver', - SI: '👍 SÍ', - NO: '👎 NO', - ESCI_DA_CHAT: '📩 Salir de la conversación', - }, - fr: { - ACCEDI: '👤 Entrez', - LAVAGNA: '🕉 Tableau de bord', - LINK_CONDIVIDERE: '🔗 Liens à partager', - ZOOM: 'ℹ️ Zoom (Conférences)', - INFO: 'ℹ️ Informations', - ASSISTENZA: '👐 Les chats', - INDIETRO: '🔙 Retour', - SI: '👍 OUI', - NO: '👎 NON', - ESCI_DA_CHAT: '📩 Quitter la conversation', - }, - si: { - ACCEDI: '👤 Prijava', - LAVAGNA: '🕉 Tabla', - LINK_CONDIVIDERE: '🔗 Link za vpis oseb', - ZOOM: 'ℹ️ Zoom (Konference)', - INFO: 'ℹ️ Informacije', - ASSISTENZA: '👐 jev klepet', - INDIETRO: '🔙 Nazaj', - SI: '👍 DA', - NO: '👎 NE', - ESCI_DA_CHAT: '📩 Zaprite pogovor', - }, - pt: { - ACCEDI: '👤 Entre', - LAVAGNA: '🕉 Tablero', - LINK_CONDIVIDERE: '🔗 Links para compartilhar', - ZOOM: 'ℹ️ Zoom (Conferências)', - INFO: 'ℹ️ Informações', - ASSISTENZA: '👐 Chats', - INDIETRO: '🔙 Voltar', - SI: '👍 SIM', - NO: '👎 NÃO', - ESCI_DA_CHAT: '📩 Sair da Conversa', - }, - enUs: { - ACCEDI: '👤 Enter', - LAVAGNA: '🕉 DashBoard', - LINK_CONDIVIDERE: '🔗 Link to Share', - ZOOM: 'ℹ️ Zoom (Conference)', - INFO: 'ℹ️ Info', - ASSISTENZA: '👐 Chats', - INDIETRO: '🔙 Back', - SI: '👍 YES', - NO: '👎 NO', - ESCI_DA_CHAT: '📩 Exit to the Conversation', - }, -}; - -const CONTA_SOLO = 'contasolo'; -const RICEVI_EMAIL = 'riceviemail'; -const NOME_COGNOME = 'nomecognome'; -const CHEDI_SE_IMBARCARTI = 'chiedi_se_imbarcarti'; - -const InlineCmd = { - VOGLIO_IMBARCARMI: 'w_imb', - NON_VOGLIO_IMBARCARMI: 'nw_imb', -}; - -const InlineZoomConferma = { - CONFERMA_ZOOM_PRESENZA: 'conf_pres', - NON_CONFERMA_ZOOM_PRESENZA: 'nonconf_pres', -}; - -const InlineConferma = { - RISPOSTA_SI: 'r_s', - RISPOSTA_NO: 'r_n', -}; - -const SendMsgCmd = [CONTA_SOLO, RICEVI_EMAIL, NOME_COGNOME, CHEDI_SE_IMBARCARTI]; - -// const MenuNoLogin = { -// it: { menu: [[Menu.LANG], [Menu.it.ASSISTENZA]] }, -// es: { menu: [[Menu.LANG], [Menu.es.ASSISTENZA]] }, -// fr: { menu: [[Menu.LANG], [Menu.fr.ASSISTENZA]] }, -// si: { menu: [[Menu.LANG], [Menu.si.ASSISTENZA]] }, -// pt: { menu: [[Menu.LANG], [Menu.pt.ASSISTENZA]] }, -// enUs: { menu: [[Menu.LANG], [Menu.enUs.ASSISTENZA]] }, -// }; - -// const MenuStandard = { -// it: { menu: [[Menu.it.LAVAGNA, Menu.it.LINK_CONDIVIDERE], [Menu.it.ZOOM, Menu.it.ASSISTENZA], [Menu.LANG]] }, -// }; - -const MenuLang = { - it: { - menu: [ - [Menu.LANG_IT, Menu.LANG_EN], - [Menu.LANG_ES, Menu.LANG_FR], - [Menu.LANG_SI, Menu.LANG_PT, Menu.it.INDIETRO], - ], - }, -}; - -const MenuYesNo = { - it: { menu: [[Menu.it.SI, Menu.it.NO]] }, - es: { menu: [[Menu.es.SI, Menu.es.NO]] }, - fr: { menu: [[Menu.fr.SI, Menu.fr.NO]] }, - si: { menu: [[Menu.si.SI, Menu.si.NO]] }, - pt: { menu: [[Menu.pt.SI, Menu.pt.NO]] }, - enUs: { menu: [[Menu.enUs.SI, Menu.enUs.NO]] }, -}; - -const MenuAdmin = { - it: { - menu: [ - [Menu.RESTART_SRV + ' 6711', Menu.LOG_SRV + ' 6711'], - [Menu.REBOOT_SRV + ' 6711', Menu.it.INDIETRO], - ], - }, -}; - -const MenuSend = { - it: { - menu: [ - [CONTA_SOLO, RICEVI_EMAIL, NOME_COGNOME], - [CHEDI_SE_IMBARCARTI, Menu.it.INDIETRO], - ], - }, -}; - -const MenuChat = { - it: { menu: [[Menu.it.ESCI_DA_CHAT, Menu.it.INDIETRO]] }, - es: { menu: [[Menu.es.ESCI_DA_CHAT, Menu.es.INDIETRO]] }, - fr: { menu: [[Menu.fr.ESCI_DA_CHAT, Menu.fr.INDIETRO]] }, - si: { menu: [[Menu.si.ESCI_DA_CHAT, Menu.si.INDIETRO]] }, - pt: { menu: [[Menu.pt.ESCI_DA_CHAT, Menu.pt.INDIETRO]] }, - enUs: { menu: [[Menu.enUs.ESCI_DA_CHAT, Menu.enUs.INDIETRO]] }, -}; - -const Sex = { - MALE: 1, - FEMALE: -1, -}; - -const Status = { - EXIT: -5, - NONE: 0, - VERIFIED: 1, - WAITFOR_USERNAME_TELEGRAM: 101, - WAITFOR_USERNAME_INVITANTE: 104, - SET_USERNAME_INVITANTE: 105, - CLICK_LINK_REG: 106, - WAITFOR_RISPOSTA: 110, -}; - -const Cmd = { - VALIDATE_REGISTRATION: 1, -}; - -const Destin = { - STAFF: 1, - TUTTI: 2, - NO_7_REQ: 3, - NO_9_REQ: 4, - SI_INVITATI_NO_7REQ_INVITATI: 5, - A_UTENTE: 6, - MSG_TO_NAVE: 7, - NESSUN_IMBARCO_7REQ: 8, - PAOLO: 9, - DOMANDA: 10, - RISPOSTA: 11, - APPARTIENE_CIRCUITO_RIS: 20, -}; - -const StatusMSGALL = { - NONE: 0, - ASK: 1, - CONFIRM: 2, -}; - -const txt = { - MSG_SCEGLI_MENU: '💫' + ' Scegli una voce di menu:' + '💫', - MSG_ASK_USERNAME_BO: - "Scrivete nel messaggio l'username (SENZA SPAZI) o la email con cui vi siete registrati sul sito di %s:", - MSG_ASK_USERNAME_INVITANTE: "Scrivi nel messaggio l'USERNAME TELEGRAM di chi ti ha INVITATO", - MSG_NEW_REG: - '

⁉️🙈 Per aiuto scrivi sulla Chat RISO
oppure direttamente a Surya (@surya1977) ☀️.', - MSG_ERRORE_INVITANTE_NOT_FOUND: - "L'username dell'invitante appena digitato non sembra essere corretto! Ti ricordo che dev'essere l'username con cui si è registrato su %s", - MSG_ERRORE_USERNAME: 'Attenzione! Devi inserire solo lo username (40 caratteri massimo)', - MSG_ERRORE_USERNAME_NOT_FOUND: - "Per Completare la Verifica Telegram BOT, dovete ora scrivere qui sotto nel messaggio l'Username (senza spazi) OPPURE la email con cui vi siete registrati sul sito", - MSG_ERRORE_USERNAME_ANNULLA: 'Inserimento Annullato. Riprovare', - MSG_OPERAZ_ANNULLATA: 'Operazione Annullata', - MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attenzione! Devi inserire solo il codice a 6 cifre', - MSG_VERIFY_CODE: - '1. Ora ritorna sul sito:\n%s\n2. Copia il codice di Autenticazione (di 6 cifre) che troverai scritto in alto\n3. Scrivilo (o incollalo) qui sotto come messaggio:', - MSG_ERR_VERIFY_CODE: - 'Codice di Verifica Errato!' + - emo.EXCLAMATION_MARK + - '\nControlla sul sito %s e riscrivi il nuovo codice di 6 cifre.', - MSG_SET_PICPROFILE: - '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', - MSG_RESETPWD: 'Clicca qui per impostare una nuova password per accedere alla APP:', - MSG_ERR_UNKNOWN_VERIFY_CODE: 'Errore durante il salvataggio sul Server. Riprovare piú tardi', - MSG_EXIT_TELEGRAM: "L'account è stato ora scollegato da questo Telegram BOT.", - MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' Si è appena Registrato "%s" (n. %s)\nInvitato da %s', - MSG_APORTADOR_ASK_CONFIRM: - '🆕💥 🧍‍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?', - MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', - MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Amicizia di %s !', - MSG_HANDSHAKE_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Stretta di mano di %s !', - MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!', - MSG_APORTADOR_DEST_CONFIRMED: - '✅ La tua registrazione a %s è stata accettata da %s!\n' + 'Vai sulla App oppure clicca qui per entrare\n👉🏻 %s', - MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!', - MSG_APORTADOR_DEST_NOT_CONFIRMED: - emo.EXCLAMATION_MARK + - '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', - MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !', - MSG_ISCRITTO_CONACREIS: emo.FIRE + '[%s] Si è appena Iscritto al Conacreis "%s"', - MSG_ISCRITTO_ARCADEI: emo.FIRE + '[%s] Si è appena Iscritto ad Arcadei "%s"', - MSG_MSG_SENT: '📨' + ' Messaggi Inviati !', - MSG_MSG_TOSENT: '📨' + ' Messaggi da Inviare', - MSG_MSG_INCORSO: '📨' + ' messaggi in corso... Inviati attualmente', - MSG_SET_USERNAME_TELEGRAM: - '[Prima di continuare con la registrazione in RISO.APP]\n' + - 'Segui questi passi per IMPOSTARE UN USERNAME IN TELEGRAM: \n\n' + - '1. premi sull\'icona con 3 linee orizzontali, in alto a sinistra (sull\'iPhone si chiama "Impostazioni").\n' + - 'premi il tasto INDIETRO del cellulare (si chiuderà questa chat).\n\n' + - '2. Seleziona la voce IMPOSTAZIONI dalla lista.\n\n' + - '3.Premi su USERNAME nella sezione account.\n\n' + - '4. Digita un username (o nome utente) qualsiasi a tua scelta, se è già usato aggiungi dei numeri.\n\n' + - "5. Per confermare premi sull'icona con la spunta (V) in alto a destra.\n\n" + - '🏁 6. Infine ritorna su questa chat BOT e scrivi OK nel messaggio. \n\n' + - ' Se non riesci a fare questi passaggi, clicca qui: \n' + - '👉🏻 https://www.nigiara.it/telegram/come-impostare-uno-username-su-telegram.htm ', - MSG_SIGNUP: 'Per registrarti su %s:', -}; - -const txt_es = { - MSG_SCEGLI_MENU: '💫' + ' Elija un elemento del menú:' + '💫', - MSG_ASK_USERNAME_BO: - 'Escriba en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio de %s:', - MSG_ERRORE_USERNAME: '¡Atención! Debes introducir sólo el nombre de usuario (40 caracteres como máximo)', - MSG_ERRORE_USERNAME_NOT_FOUND: - 'Para completar la verificación del telegrama BOT, ahora debe escribir en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio.:', - MSG_ERRORE_USERNAME_ANNULLA: 'Inserción cancelada. Inténtalo de nuevo.', - MSG_OPERAZ_ANNULLATA: 'Operación cancelada', - MSG_ERRORE_VERIFY_CODE_MAXLEN: '¡Atención! Sólo tienes que introducir el código de 6 dígitos', - MSG_VERIFY_CODE: - '1. Ahora, de vuelta en el sitio web:\n%s\n2. Copie el código de autenticación (6 dígitos) que encontrará escrito en la parte superior de la página\n3. Escríbelo (o pégalo) abajo como un mensaje:', - MSG_ERR_VERIFY_CODE: - 'Código de verificación incorrecto!' + - emo.EXCLAMATION_MARK + - '\nComprueba en el sitio %s y reescribe el nuevo código de 6 dígitos.', - MSG_SET_PICPROFILE: - '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', - MSG_ERR_UNKNOWN_VERIFY_CODE: 'Error al guardar en el servidor. Inténtalo de nuevo más tarde.', - MSG_EXIT_TELEGRAM: 'La cuenta ha sido desconectada de Telegram BOT.', - MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' Acaba de registrarse "%s (n. %s)"\n(Invitado de %s)', - MSG_APORTADOR_ASK_CONFIRM: - '🆕💥 🧍‍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?', - MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', - MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!', - MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!', - MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!', - MSG_APORTADOR_DEST_NOT_CONFIRMED: - emo.EXCLAMATION_MARK + - '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', - MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !', - MSG_MSG_SENT: '📨' + ' Mensajes enviados !', - MSG_MSG_TOSENT: '📨' + ' Mensajes a enviar', - MSG_MSG_INCORSO: '📨' + ' mensajes en progreso... Enviado actualmente', -}; - -const txt_fr = { - MSG_SCEGLI_MENU: '💫' + 'Choisissez un élément de menu:' + '💫', - MSG_ASK_USERNAME_BO: - "Écrivez dans le message l'username ou l'e-mail avec lequel vous vous êtes enregistré sur le site de %s: ", - MSG_ERRORE_USERNAME: 'Attention! Vous devez insérer seulement l’username (40 caractères maximum)', - MSG_ERRORE_USERNAME_NOT_FOUND: - "Pour Compléter la Vérification Telegram BOT, vous devez maintenant écrire dans le message ci-dessous l'Username ou l'adresse e-mail avec lequel vous vous êtes inscrit sur le site: ", - MSG_ERRORE_USERNAME_ANNULLA: 'Saisie des données Annullée.Essayez à nouveau ', - MSG_OPERAZ_ANNULLATA: 'Opération Annullée', - MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attention! Vous devez insérer seulement le code à 6 chiffres', - MSG_VERIFY_CODE: - '1. Ᾱ présent retournez sur le site:\n%s\n2. Copiez le Code d’Authentification (de 6 chiffres) che vous trouverez écrit en haut \n3. Ecrivez-le (ou copiez-le) ci-dessous comme message:', - MSG_ERR_VERIFY_CODE: - ' Code de vérification incorrect!' + - emo.EXCLAMATION_MARK + - '\nControllez sur le site %s et réécrivez le nouveau code à 6 chiffres.', - MSG_SET_PICPROFILE: - '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', - MSG_ERR_UNKNOWN_VERIFY_CODE: "Erreur lors de l'enregistrement sur le serveur. Retentez plus tard", - MSG_EXIT_TELEGRAM: "L'account a été déconnecté de Telegram BOT.", - MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' Vous venez à peine de vous inscrire "%s (n. %s) %s', - MSG_APORTADOR_ASK_CONFIRM: - '🆕💥 🧍‍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?', - MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', - MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!', - MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!', - MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!', - MSG_APORTADOR_DEST_NOT_CONFIRMED: - emo.EXCLAMATION_MARK + - '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', - MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !', - MSG_MSG_SENT: '📨' + ' Messages envoyés !', - MSG_MSG_TOSENT: '📨' + ' Messages à envoyer', - MSG_MSG_INCORSO: '📨' + ' messages en cours... Actuellement envoyé', -}; - -const txt_si = { - MSG_SCEGLI_MENU: '💫' + 'Izbirni meni:' + '💫', - MSG_ASK_USERNAME_BO: 'Vpiši svoje uporabniško ime in e-naslov s katerimi si se registriral na spletni strani %s: ', - MSG_ERRORE_USERNAME: 'Pozor! Vpiši samo uporabniško ime (40 znakov) maksimalno', - MSG_ERRORE_USERNAME_NOT_FOUND: - 'Ponovno preverite telegram BOT Uporabniško ime ali e-poštno sporočilo, s katerim ste registrirali na spletni strani: ', - MSG_ERRORE_USERNAME_ANNULLA: 'Preklic. Poskusi ponovno ', - MSG_OPERAZ_ANNULLATA: 'Operacija preklicana', - MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Pozor! Vstavi D mestno kodo', - MSG_VERIFY_CODE: - '1. Vrni se na spletno strani: \n%s\n2. Kopiraj kodo Authenticazione (6 mestno) ki jo najdeš zgoraj zapisano\n3. Napiši (ali prilepi) tu spodaj kot sporočilo: ', - MSG_ERR_VERIFY_CODE: - 'Napačna koda za preverjanje!' + emo.EXCLAMATION_MARK + '\nPreveri na strani %s in ponovno napiši 6 mestno kodo.', - MSG_SET_PICPROFILE: - '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', - MSG_ERR_UNKNOWN_VERIFY_CODE: 'Napaka strežnika.Poskusi kasneje ', - MSG_EXIT_TELEGRAM: 'Račun se nahaja v programu Telegram BOT.', - MSG_APORTADOR_USER_REGISTERED: emo.FIRE + 'Registracija registracije %s (n. %s)\n(povabil ga %s)', - MSG_APORTADOR_ASK_CONFIRM: - '🆕💥 🧍‍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?', - MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', - MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!', - MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!', - MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!', - MSG_APORTADOR_DEST_NOT_CONFIRMED: - emo.EXCLAMATION_MARK + - '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', - MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !', -}; - -const txt_en = { - MSG_SCEGLI_MENU: '💫' + ' Choose a menu item:' + '💫', - MSG_ASK_USERNAME_BO: 'Write in the message the username or email with which you registered on the site of %s:', - MSG_ERRORE_USERNAME: 'Attention! You must enter only the username (40 characters maximum)', - MSG_ERRORE_USERNAME_NOT_FOUND: - 'To complete the Telegram BOT Verification, you must now write below in the message the Username OR the email with which you registered on the website:', - MSG_ERRORE_USERNAME_ANNULLA: 'Insertion Cancelled. Try again', - MSG_OPERAZ_ANNULLATA: 'Operation Cancelled', - MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attention! You only need to enter the 6-digit code', - MSG_VERIFY_CODE: - '1. Now return to the website: %s\n' + - '2. Copy the Authentication code (of 6 digits) that you will find written at the top\n' + - '3. Write it (or paste it) below as a message:', - MSG_ERR_VERIFY_CODE: - 'Incorrect Verification Code!' + emo.EXCLAMATION_MARK + '\nCheck on the site %s and rewrite the new 6-digit code.', - MSG_SET_PICPROFILE: - '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', - MSG_ERR_UNKNOWN_VERIFY_CODE: 'Error while saving to the Server. Try again later', - MSG_EXIT_TELEGRAM: 'The account has now been disconnected from this Telegram BOT.', - MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' He/She\'s just registered "%s (n. %s)"\n(Invited from %s)', - MSG_APORTADOR_ASK_CONFIRM: - '🆕💥 🧍‍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?', - MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', - MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!', - MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!', - MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!', - MSG_APORTADOR_DEST_NOT_CONFIRMED: - emo.EXCLAMATION_MARK + - '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', - MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !', - MSG_MSG_SENT: '📨' + ' Sent Messages !', - MSG_MSG_TOSENT: '📨' + ' Messages to Send', - MSG_MSG_INCORSO: '📨' + ' messages in progress... Currently sent', -}; - -const txt_pt = { - MSG_SCEGLI_MENU: '💫' + ' Escolha um item do menu:' + '💫', - MSG_ASK_USERNAME_BO: 'Escreva na mensagem o nome de usuário ou e-mail com o qual se registrou no site de %s:', - MSG_ERRORE_USERNAME: 'Atenção! Você deve inserir apenas o nome de usuário (40 caracteres no máximo)', - MSG_ERRORE_USERNAME_NOT_FOUND: - 'Para completar a Verificação do Telegrama BOT, você deve agora escrever abaixo na mensagem o Nome de Usuário OU o e-mail com o qual você se registrou no site:', - MSG_ERRORE_USERNAME_ANNULLA: 'Inserção Cancelada. Tente novamente', - MSG_OPERAZ_ANNULLATA: 'Operação Cancelada', - MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Atenção! Você só precisa digitar o código de 6 dígitos', - MSG_VERIFY_CODE: - '1. Agora de volta ao site:\n%s\n2. Copie o código de autenticação (6 dígitos) que você encontrará escrito na parte superior da página\n3. Escreva-o (ou cole-o) abaixo como uma mensagem:', - MSG_ERR_VERIFY_CODE: - 'Código de Verificação Incorrecto!' + - emo.EXCLAMATION_MARK + - '\nCódigo de Verificação ErradoCheque no local %s e reescreva o novo código de 6 dígitos.', - MSG_SET_PICPROFILE: - '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', - MSG_ERR_UNKNOWN_VERIFY_CODE: 'Erro ao salvar no Servidor. Tente novamente mais tarde.', - MSG_EXIT_TELEGRAM: 'A conta foi agora desconectada deste Telegrama BOT.', - MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' Acabou de se registar "%s (n. %s)"\n(Convidado por %s)', - MSG_APORTADOR_ASK_CONFIRM: - '🆕💥 🧍‍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?', - MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', - MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!', - MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!', - MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!', - MSG_APORTADOR_DEST_NOT_CONFIRMED: - emo.EXCLAMATION_MARK + - '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', - MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !', - MSG_MSG_SENT: '📨' + ' Mensagens Enviadas !', - MSG_MSG_TOSENT: '📨' + ' Mensagens a enviar', - MSG_MSG_INCORSO: '📨' + ' mensagens em progresso... Actualmente enviado', -}; - -const TelegramBot = require('node-telegram-bot-api'); - -const ADMIN_IDTELEGRAM_TEST = 5356627050; // 5022837609; //Surya A. - -const MyTelegramBot = { - ADMIN_IDTELEGRAM_SERVER: '12429864', //Paolo - ADMIN_USERNAME_TELEGRAM: 'surya1977', //Paolo - ADMIN_USER_NAME_SERVER: 'Paolo', - - phase: { - REGISTRATION: 1, - ISCRIZIONE_CONACREIS: 2, - ISCRIZIONE_ARCADEI: 4, - }, - - getAppTelegram: function () { - if (process.env.appTelegram) { - arrTeleg = JSON.parse(process.env.appTelegram); - } else { - arrTeleg = appTelegram; - } - if (process.env.NODE_ENV === 'development') { - arrTeleg = MyTelegramBot.getAppTelegramDevelop(); - } else if (process.env.NODE_ENV === 'test') { - arrTeleg = MyTelegramBot.getAppTelegramTest(); - } else { - const arrTelegFromSite = tools.getArrTelegramFromSite(); - if (arrTelegFromSite.length > 0) { - arrTeleg = arrTelegFromSite; - } - } - - return arrTeleg; - }, - - getAppTelegramTest: function () { - if (process.env.appTelegram_TEST) { - return JSON.parse(process.env.appTelegram_TEST); - } else { - return appTelegram_TEST; - } - }, - - getAppTelegramDevelop: function () { - if (process.env.appTelegram_DEVELOP) { - return JSON.parse(process.env.appTelegram_DEVELOP); - } else { - return appTelegram_DEVELOP; - } - }, - - local_sendMsgTelegramByIdTelegram: async function ( - idapp, - idtelegram, - text, - message_id, - chat_id, - ripr_menuPrec, - MyForm = null, - img = '' - ) { - if (!idtelegram) return { text: '' }; - - const cl = getclTelegByidapp(idapp); - if (cl && idtelegram) { - return await cl.sendMsg(idtelegram, text, null, MyForm, message_id, chat_id, ripr_menuPrec, img, { idapp }); - } - - return { text: '' }; - }, - - deleteRecInMemByUsername: function (idapp, username_bo) { - const cl = getclTelegByidapp(idapp); - if (cl) { - cl.arrUsers = cl.arrUsers.filter((rec) => rec.username_bo !== username_bo); - } - }, - - getFormDaMostrare: function (idapp, myfunc, myuser) { - let FormDaMostrare = null; - - const cl = getclTelegByidapp(idapp); - - if (myfunc === shared_consts.CallFunz.ZOOM_GIA_PARTECIPATO) { - FormDaMostrare = cl.getInlineKeyboard(myuser.lang, [ - { - text: 'Conferma Presenza Zoom', - // callback_data: { action: InlineZoomConferma.CONFERMA_ZOOM_PRESENZA, username: myuser.username } - callback_data: InlineZoomConferma.CONFERMA_ZOOM_PRESENZA + tools.SEP + myuser.username, - }, - { - text: 'Annulla Presenza Zoom', - // callback_data: { action: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA, username: myuser.username } - callback_data: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA + tools.SEP + myuser.username, - }, - ]); - } - - return FormDaMostrare; - }, - - getclTelegByidapp: function (idapp) { - const cl = getclTelegByidapp(idapp); - return cl; - }, - - getCiao: function (idapp, username, lang) { - return tools.gettranslate('CIAO', lang) + ' ' + username + '!\n'; - }, - - notifyToTelegram: async function (phase, mylocalsconf) { - try { - let userdest = mylocalsconf.user.aportador_solidario; - let langdest = mylocalsconf.user.lang; - let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname}`; - if (!mylocalsconf.user.name) { - NameFrom = `${mylocalsconf.user.username}`; - } - const index = mylocalsconf.user.index; - - let aportador = ''; - if (userdest) { - aportador = `${userdest}`; - NameFrom += aportador; - } else { - aportador = mylocalsconf.user.aportador_solidario_nome_completo - ? mylocalsconf.user.aportador_solidario_nome_completo - : mylocalsconf.user.aportador_solidario; - } - - let text = ''; - if (phase === this.phase.REGISTRATION) { - if ( - tools.getConfSiteOptionEnabledByIdApp(mylocalsconf.idapp, shared_consts.ConfSite.Notif_Reg_Bot_ToManagers) - ) { - if (userdest) { - NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp, userdest, true); - aportador = NameFrom ? NameFrom + ' ' + aportador : aportador; - } - const numutenti = await User.getNumUsers(mylocalsconf.idapp); - let nome = tools.getNomeCognomeEUserNameByUser(mylocalsconf.user); - text = printf(getstr(langdest, 'MSG_APORTADOR_USER_REGISTERED'), nome, numutenti, aportador); - } - } - - let addtext = ''; - let rismsg = null; - - if (text) { - await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text, false, null); - } - } catch (e) { - console.error('Err notifyToTelegram', e); - } - }, - - notifyIscrizioneToTelegram: async function (phase, mylocalsconf, msg) { - try { - let langdest = mylocalsconf.iscritto.lang; - let NameFrom = `${mylocalsconf.iscritto.name} ${mylocalsconf.iscritto.surname}`; - - let nomeapp = tools.getHostByIdApp(mylocalsconf.idapp); - - let text = printf(getstr(langdest, msg), NameFrom, nomeapp); - - let addtext = ''; - - await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text); - } catch (e) { - console.error('notifyIscrizioneToTelegram', e); - } - }, - - askConfirmationUser: async function ( - idapp, - myfunc, - myuser, - userDest = '', - name = '', - groupid = '', - circuitId = '', - regexpire = '', - groupname = '' - ) { - try { - const cl = getclTelegByidapp(idapp); - if (!cl) return false; - - const langdest = myuser.lang; - const telegid = myuser.profile.teleg_id; - - if (!userDest) { - userDest = myuser.username; - } - let userrecDest = await User.getUserShortDataByUsername(idapp, userDest); - let userId = userrecDest._id; - let title = tools.getNomeAppByIdApp(idapp); - let keyb = null; - let openUrl = ''; - let domanda = ''; - let msg_notifpush = ''; - let send_notif = false; - let actions = []; - let tag = ''; - - const struserinfomsg = tools.getUserInfoMsg(idapp, myuser); - - const nomeapp = myuser.idapp ? tools.getNomeAppByIdApp(myuser.idapp) : tools.getNomeAppByIdApp(idapp); - - if (myfunc === shared_consts.CallFunz.REGISTRATION) { - if (telegid > 0) { - cl.setPhotoProfile(myuser, telegid, false); - - const rismsg = await MsgTemplate.getMsgByLang( - idapp, - myuser, - shared_consts.TypeMsgTemplate.MSG_BENVENUTO, - myuser.lang - ); - const rismsg2 = await MsgTemplate.getMsgByLang( - idapp, - myuser, - shared_consts.TypeMsgTemplate.MS_SHARE_LINK, - myuser.lang - ); - - await cl.sendMsgLog(telegid, rismsg.body); - await cl.sendMsg(telegid, rismsg2.body); - } - - userDest = myuser.aportador_solidario; - let notask_verif = await User.notAsk_VerifByUsername(idapp, userDest); - - let useraportador = await User.getUserShortDataByUsername(idapp, userDest); - - if ( - useraportador && - useraportador.tokenreg && - useraportador.tokenreg && - regexpire && - regexpire?.toLowerCase() === useraportador.tokenreg?.toLowerCase() - ) { - const nonchiedereverifica = await User.getifRegTokenIsValid(idapp, useraportador.tokenreg); - if (nonchiedereverifica) notask_verif = true; - } - - if (notask_verif) { - // Non chiedi la verifica Registrazione - await setVerifiedReg(myuser.idapp, myuser.lang, myuser.username, userDest); - } else { - msg_notifpush = getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM', myuser.username, nomeapp); - domanda = getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM', myuser.username, nomeapp) + '
' + struserinfomsg; - - keyb = cl.getInlineKeyboard(myuser.lang, [ - { - text: '✅ Ammetti ' + myuser.username, - callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest, - }, - /*{ - text: '🚫 Rifiuta ' + myuser.username, - callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest, - }, */ - ]); - } - send_notif = true; - } else if (myfunc === shared_consts.CallFunz.RICHIESTA_GRUPPO) { - msg_notifpush = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), name); - domanda = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), name) + '
' + struserinfomsg; - - keyb = cl.getInlineKeyboard(myuser.lang, [ - { - text: '✅ Accetta ' + myuser.username, - callback_data: - InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + groupid, - }, - { - text: '🚫 Rifiuta ' + myuser.username, - callback_data: - InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + groupid, - }, - ]); - } else if (myfunc === shared_consts.CallFunz.RICHIESTA_FIDO) { - if (groupname) { - msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, groupname); - domanda = - i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, groupname) + - '
' + - struserinfomsg; - - let textentrato = ''; - - - keyb = cl.getInlineKeyboard(myuser.lang, [ - { - text: textentrato + '✅ Abilita fiducia a ' + groupname, - callback_data: - InlineConferma.RISPOSTA_SI + - myfunc + tools.SEP + - myuser.username + tools.SEP + - '' + tools.SEP + - '' + tools.SEP + - circuitId + tools.SEP + - groupname, - }, - /*{ - text: '🚫 Rifiuta ' + groupname, - callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + - groupid + tools.SEP + groupname, - },*/ - ]); - send_notif = true; - } else { - msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest }, myuser.username, name); - domanda = - i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest }, myuser.username, name) + - '
' + - struserinfomsg; - - keyb = cl.getInlineKeyboard(myuser.lang, [ - { - text: '✅ Abilita fiducia a ' + myuser.username + ' in ' + name, - callback_data: - InlineConferma.RISPOSTA_SI + - myfunc + tools.SEP + - myuser.username + tools.SEP + - '' + tools.SEP + - '' + tools.SEP + - circuitId + tools.SEP, - }, - /*{ - text: '🚫 Rifiuta ' + myuser.username, - callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + - groupid, - }, */ - ]); - send_notif = true; - } - } else if (myfunc === shared_consts.CallFunz.RICHIESTA_CIRCUIT) { - if (groupname) { - msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP_CIRC', locale: langdest }, groupname); - domanda = - i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP_CIRC', locale: langdest }, groupname) + - '
' + - struserinfomsg; - - keyb = cl.getInlineKeyboard(myuser.lang, [ - { - text: '✅ Fai entrare a ' + groupname, - callback_data: - InlineConferma.RISPOSTA_SI + - myfunc + tools.SEP + - myuser.username + tools.SEP + - '' + tools.SEP + - '' + tools.SEP + - circuitId + tools.SEP + - groupname, - }, - /*{ - text: '🚫 Rifiuta ' + groupname, - callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + - groupid + tools.SEP + groupname, - },*/ - ]); - send_notif = true; - } else { - msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_CIRC', locale: langdest }, myuser.username, name); - domanda = - i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_CIRC', locale: langdest }, myuser.username, name) + - '
' + - struserinfomsg; - - keyb = cl.getInlineKeyboard(myuser.lang, [ - { - text: '✅ Fai entrare a ' + myuser.username, - callback_data: - InlineConferma.RISPOSTA_SI + - myfunc + tools.SEP + - myuser.username + tools.SEP + - '' + tools.SEP + - '' + tools.SEP + - circuitId, - }, - /*{ - text: '🚫 Rifiuta ' + myuser.username, - callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + - groupid, - }, */ - ]); - send_notif = true; - } - } - - // Invia Msg - if (domanda) { - const teleg_id = await User.TelegIdByUsername(idapp, userDest); - await this.local_sendMsgTelegramByIdTelegram(idapp, teleg_id, domanda, undefined, undefined, true, keyb); - } - - if (send_notif && msg_notifpush) { - // SEND PUSH NOTIFICATION - await tools.sendNotificationToUser(userId, title, msg_notifpush, openUrl, '', tag, actions); - } - } catch (e) { - console.error('Error askConfirmationUser', e); - } - }, - - askConfirmationUserFriend: async function (idapp, myfunc, myuser, userDest = '', username = '') { - try { - const cl = getclTelegByidapp(idapp); - if (!cl) return false; - - const { SendNotif } = require('../models/sendnotif'); - - const langdest = myuser.lang; - - let keyb = null; - let domanda = ''; - let sendnotif = false; - let typedir = 0; - let typeid = 0; - let paramsObj = {}; - - const struserinfomsg = tools.getUserShortInfoMsg(idapp, myuser); - - if (myfunc === shared_consts.CallFunz.RICHIESTA_AMICIZIA) { - sendnotif = true; - typedir = shared_consts.TypeNotifs.TYPEDIR_FRIENDS; - typeid = shared_consts.TypeNotifs.ID_FRIENDS_NEW_REC; - paramsObj = { usernameDest: userDest }; - - domanda = printf(tools.gettranslate('RICHIESTA_AMICIZIA', langdest), myuser.username) + '
' + struserinfomsg; - - keyb = cl.getInlineKeyboard(myuser.lang, [ - { - text: '✅👤 Accetta Amicizia', - callback_data: - InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '', - }, - { - text: '🚫👤 Rifiuta Amicizia', - callback_data: - InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '', - }, - ]); - } else if (myfunc === shared_consts.CallFunz.RICHIESTA_HANDSHAKE) { - sendnotif = true; - typedir = shared_consts.TypeNotifs.TYPEDIR_HANDSHAKE; - typeid = shared_consts.TypeNotifs.ID_HANDSHAKE_ACCEPTED; - paramsObj = { usernameDest: userDest }; - - domanda = - printf(tools.gettranslate('RICHIESTA_HANDSHAKE', langdest), myuser.username) + '
' + struserinfomsg; - - keyb = cl.getInlineKeyboard(myuser.lang, [ - { - text: '✅🤝 Ricambia la stretta di mano', - callback_data: - InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '', - }, - ]); - } - - // Invia Msg - if (domanda) { - const teleg_id = await User.TelegIdByUsername(idapp, userDest); - await this.local_sendMsgTelegramByIdTelegram(idapp, teleg_id, domanda, undefined, undefined, true, keyb); - } - - if (sendnotif) { - const req = tools.getReqByPar(idapp, username); - // CREATE NOTIFICATION IN TABLE SENDNOTIF - await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, true, typedir, typeid); - } - } catch (e) { - console.error('Error askConfirmationUser', e); - } - }, - - sendMsgTelegramToTheManagers: async function (idapp, text, onlyintofile = false, MyForm = null, nottousername = '') { - tools.writeManagersLog(text); - - if (!onlyintofile) { - const usersmanagers = await User.getusersManagers(idapp); - if (usersmanagers) { - for (const rec of usersmanagers) { - if (rec.username !== nottousername) { - await this.sendMsgTelegramByIdTelegram( - idapp, - rec.profile.teleg_id, - emo.ROBOT_FACE + ': ' + text, - undefined, - undefined, - true, - MyForm - ); - await tools.snooze(100); - } - } - } - } - return true; - }, - - sendMsgTelegramToTheAdminsOfCircuit: async function ( - idapp, - circuitpath, - text, - onlyintofile = false, - MyForm = null, - nottousername = '' - ) { - tools.writeManagersLog(text); - let teleg_id = 0; - - if (!onlyintofile) { - const usersmanagers = await Circuit.getListAdminsByCircuitPath(idapp, circuitpath); - if (usersmanagers) { - for (const rec of usersmanagers) { - if (rec.username !== nottousername) { - teleg_id = await User.TelegIdByUsername(idapp, rec.username); - if (teleg_id) { - await this.sendMsgTelegramByIdTelegram( - idapp, - teleg_id, - emo.ROBOT_FACE + ': ' + text, - undefined, - undefined, - true, - MyForm - ); - await tools.snooze(100); - } - } - } - } - } - return true; - }, - - sendMsgTelegramToTheManagersAndZoomeri: async function (idapp, text, onlyintofile, MyForm = null) { - tools.writeManagersLog(text); - - if (!onlyintofile) { - // const usersmanagers = await User.getusersManagersAndZoomeri(idapp); - const usersmanagers = await User.getusersManagers(idapp); - if (usersmanagers) { - for (const rec of usersmanagers) { - await this.sendMsgTelegramByIdTelegram( - idapp, - rec.profile.teleg_id, - emo.ROBOT_FACE + ': ' + text, - undefined, - undefined, - true, - MyForm - ); - await tools.snooze(100); - } - } - } - return true; - }, - getMsgByTipoMsg: async function (mydata, lang, user, sonosognatore) { - if (!!mydata.msgextra) { - return { body: mydata.msgextra, title: '' }; - } - - let title = ''; - let msg = ''; - - if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { - if (sonosognatore) - msg = printf( - tools.gettranslate('SEND_LINK_CHAT_SOGNATORE', lang), - user.name, - mydata.navemediatore.riga + '.' + mydata.navemediatore.col, - mydata.msgpar1 - ); - else - msg = printf( - tools.gettranslate('SEND_LINK_CHAT_DONATORI', lang), - user.name, - mydata.navemediatore.riga + '.' + mydata.navemediatore.col, - mydata.msgpar1 - ); - } else if (mydata.tipomsg === tools.TipoMsg.SEND_MSG || mydata.tipomsg === tools.TipoMsg.SEND_MSG_SINGOLO) { - if (!!mydata.username_mitt) { - msg = '[' + tools.gettranslate('MSG_SEND_FROM', lang) + ' ' + mydata.username_mitt + ']:' + tools.ACAPO; - } - msg += mydata.msgpar1; - } else if (mydata.tipomsg >= 1000) { - const ris = await MsgTemplate.getMsgByLang(user.idapp, user, mydata.tipomsg, lang); - msg = ris.body; - title = ris.title; - } - - const cl = getclTelegByidapp(user.idapp); - if (cl) { - msg = await tools.convertSpecialTags(rec.user, msg); - } - - if (!!mydata.flotta) { - // SOSTITUISCI LE PAROLE CHIAVI - if (!!mydata.flotta.date_start) - msg = msg.replace('{date_start}', tools.getstrDateLongTot(new Date(mydata.flotta.date_start), user.lang)); - if (!!mydata.flotta.date_close) - msg = msg.replace('{date_close}', tools.getstrDateLongTot(new Date(mydata.flotta.date_close), user.lang)); - if (!!mydata.flotta.link_superchat) msg = msg.replace('{link_superchat}', mydata.flotta.link_superchat); - if (!!mydata.flotta.tutor1) msg = msg.replace('{tutor1}', mydata.flotta.tutor1); - if (!!mydata.flotta.tutor2) msg = msg.replace('{tutor2}', mydata.flotta.tutor2); - if (!!mydata.flotta.tutor3) msg = msg.replace('{tutor3}', mydata.flotta.tutor3); - if (!!mydata.flotta.tutorslo) msg = msg.replace('{tutorslo}', mydata.flotta.tutorslo); - if (!!mydata.flotta.sognatore_nomecognome) msg = msg.replace('{sognatore}', mydata.flotta.sognatore_nomecognome); - if (!!mydata.flotta.sognatore_nomecognome) - msg = msg.replace( - '{flotta}', - mydata.flotta.riga + - '.' + - Math.ceil(mydata.flotta.col_prima / 8) + - ' - ' + - mydata.flotta.riga + - '.' + - Math.ceil(mydata.flotta.col_ultima / 8) - ); - } - - return { body: msg, title }; - }, - - sendMsgTelegramToTheAdminAllSites: async function (text, senzaintestazione) { - for (const idapp of this.getAppTelegram()) { - text = text.replace('{appname}', tools.getNomeAppByIdApp(idapp)); - await this.sendMsgTelegramToTheAdmin(idapp, text, senzaintestazione); - } - }, - - sendMsgTelegramToTheAdmin: async function (idapp, text, senzaintestazione) { - const usersmanagers = await User.getusersAdmin(idapp); - - let intestaz = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': '; - if (senzaintestazione) intestaz = ''; - - if (usersmanagers) { - for (const rec of usersmanagers) { - if (User.isAdmin(rec.perm)) { - this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, intestaz + text, undefined, undefined, true); - await tools.snooze(300); - } - } - } - return true; - }, - - sendMsgTelegramToALL: async function (idapp, text) { - const usersall = await User.getUsersTelegALL(idapp); - - if (usersall) { - for (const rec of usersall) { - this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, text); - await tools.snooze(300); - } - } - }, - - sendMsgTelegram: async function (idapp, username, text, alsotomanagers = false, username_mitt = '') { - const { User } = require('../models/user'); - - const teleg_id = await User.TelegIdByUsername(idapp, username); - const cl = getclTelegByidapp(idapp); - let ris = null; - if (cl && teleg_id) { - ris = await cl.sendMsg(teleg_id, text); - } - - if (cl && teleg_id) { - if (alsotomanagers) { - await this.sendMsgTelegramToTheManagers(idapp, text); - } - if (!!username_mitt) { - const rec = cl.getRecByUsername(username); - if (rec) { - rec.msgall_username_specifico = username_mitt; - } - } - } - - return ris; - }, - - sendMsgTelegramByIdTelegram: async function ( - idapp, - idtelegram, - text, - message_id, - chat_id, - ripr_menuPrec, - MyForm = null, - img = '' - ) { - if (!idtelegram) return; - - const cl = getclTelegByidapp(idapp); - if (cl && idtelegram) { - let myform = null; - - return await cl.sendMsg(idtelegram, text, null, MyForm, message_id, chat_id, ripr_menuPrec, img); - } - }, - - reloadMenuBot: async function (idapp) { - const cl = getclTelegByidapp(idapp); - if (cl) { - return cl.updateMenuBot(); - } - }, - - reloadSites: async function () { - tools.loadApps(); - }, - - sendMsgFromSite: async function (idapp, user, params) { - try { - const globalTables = require('../tools/globalTables'); - - let ris = { - numrec: 0, - nummsgsent: 0, - text: '', - }; - - let invia = false; - let content = ''; - - let tipomsgtempl = 0; - - params.sendreally = true; - - if (params.typemsg === shared_consts.TypeMsg.SEND_TO_MYSELF) { - params.usernameDest = user.username; - } - - if (params.cmd === shared_consts.MsgTeleg.SHARE_MSGREG) { - tipomsgtempl = shared_consts.TypeMsgTemplate.MS_SHARE_LINK; - invia = true; - } else if (params.cmd === shared_consts.MsgTeleg.SHARE_TEXT) { - invia = !!params.content; - } else if (params.cmd === shared_consts.MsgTeleg.SHARE_ANNUNCIO) { - const mytable = globalTables.getTableByTableName(params.tablerec); - - if (params.idrec && params.idrec !== '0') { - // const myrectableorig = await mytable.findOne({ _id: myrecnotifpass.idrec }).lean(); - const myrectableorig = await mytable.getCompleteRecord(params.idapp, params.idrec); - - if (myrectableorig) { - const eventobj = await tools.getAnnuncioForTelegram( - myrectableorig, - params.tablerec, - '', - user.username, - false - ); - if (eventobj) { - params.textcontent_Telegram = eventobj.newdescrtelegram; - params.typesend = shared_consts.TypeSend.TELEGRAM; - //const rismsg = - params.content = eventobj.newdescr; - params.title = ''; - params.img = eventobj.img; - invia = true; - } - } - } - } - - if (tipomsgtempl > 0) { - const rismsg = await MsgTemplate.getMsgByLang(idapp, user, tipomsgtempl, user.lang); - params.content = rismsg.body; - params.title = rismsg.title; - } - - if (invia) { - ris = await globalTables.SendMsgToParam(idapp, params); - } - - return ris; - } catch (e) { - console.error('sendMsgFromSite', e); - } - }, - - sendMsgFromSiteToBotTelegram: async function (idapp, user, params) { - if (!params.typesend) { - params.typesend = shared_consts.TypeSend.TELEGRAM; - } - - return this.sendMsgFromSite(idapp, user, params); - }, -}; - -async function setVerifiedReg(idapp, lang, usernameorig, usernameDest) { - try { - await User.setVerifiedByAportador(idapp, usernameorig, true); - // await User.setFriendsCmd(null, idapp, usernameorig, usernameDest, shared_consts.FRIENDSCMD.SETFRIEND); - - const msgDest = printf(getstr(lang, 'MSG_APORTADOR_CONFIRMED'), `${usernameorig}`, usernameDest); - await local_sendMsgTelegram(idapp, usernameDest, msgDest); - } catch (e) { - console.log('e', e); - } -} - -function getusernameByUser(idapp, msg) { - let username = ''; - let rec = this.getRecInMem(msg); - if (!!rec) username = rec.username_bo; - - if (username === '') { - username = msg.chat.username; - } - - return username; -} - -async function local_sendMsgTelegramToTheManagers(idapp, text, msg, username_bo) { - const usersmanagers = await User.getusersManagers(idapp); - - let username = msg.chat.username; - if (username_bo) username = username_bo; - - text = emo.ROBOT_FACE + ': Da ' + tools.getNomeCognomeTelegram(msg) + ' (' + username + '): \n' + text; - tools.writeEventsLog(text); - - if (usersmanagers) { - for (const rec of usersmanagers) { - const idtelegram = rec.profile.teleg_id; - const cl = getclTelegByidapp(idapp); - if (cl && idtelegram) { - await cl.sendMsg(idtelegram, text, undefined, undefined, undefined, undefined, true); - } - await tools.snooze(100); - } - } - return true; -} -async function local_sendMsgTelegramToTheAdmin(idapp, text, msg, username_bo) { - const usersAdmin = await User.getusersAdmin(idapp); - - let username = msg.chat.username; - if (username_bo) username = username_bo; - - text = emo.ROBOT_FACE + ': Da ' + msg.chat.first_name + ' ' + msg.chat.last_name + ' (' + username + '): \n' + text; - tools.writeEventsLog(text); - - if (usersAdmin) { - for (const rec of usersAdmin) { - const idtelegram = rec.profile.teleg_id; - const cl = getclTelegByidapp(idapp); - if (cl && idtelegram) { - await cl.sendMsg(idtelegram, text, undefined, undefined, undefined, undefined, true); - } - await tools.snooze(100); - } - } - return true; -} - -async function local_sendMsgTelegram(idapp, username, text) { - const teleg_id = await User.TelegIdByUsername(idapp, username); - const cl = getclTelegByidapp(idapp); - let ris = null; - if (cl && teleg_id > 0) { - ris = await cl.sendMsg(teleg_id, text); - } - - return ris; -} - -function getstr(lang, key, ...params) { - let mystr = ''; - - if (lang === 'si' || lang === 'sl-si') { - try { - mystr = txt_si[key]; - } catch (e) { - mystr = ''; - } - } else if (lang === 'en' || lang === 'enUs') { - try { - mystr = txt_en[key]; - } catch (e) { - mystr = ''; - } - } else if (lang === 'es') { - try { - mystr = txt_es[key]; - } catch (e) { - mystr = ''; - } - } else if (lang === 'fr') { - try { - mystr = txt_fr[key]; - } catch (e) { - mystr = ''; - } - } else if (lang === 'pt') { - try { - mystr = txt_pt[key]; - } catch (e) { - mystr = ''; - } - } - - if (!mystr || mystr === '') mystr = txt[key]; - - if (params.length > 0) { - mystr = printf(mystr, ...params); - } - - return mystr; -} - -class Telegram { - constructor(idapp, bot) { - this.idapp = idapp; - this.bot = bot; - this.token = bot.token; - this.arrUsers = []; - this.lastid = 0; - //++ - } - - async createIfNotExist(msg) { - if (!(await this.alreadyExist(msg))) { - if (await this.insertIntoDB(msg)) { - let rec = this.getRecInMem(msg); - if (!!rec) { - if (rec.user) rec.status = Status.VERIFIED; - } else { - return false; - } - } - return true; - } else { - return false; - } - } - - async settotheDatabase(msg) { - // Check if Present to the DB - const riscreate = await this.createIfNotExist(msg); - - if (!riscreate) { - let rec = this.getRecInMem(msg); - if (!rec) rec = await this.addUser(msg); - - if (rec.user) rec.status = Status.VERIFIED; - } - } - - async start(msg) { - // Check if Username Telegram Present - if (!msg.from.username) { - return false; - } - - await this.settotheDatabase(msg); - } - - geturlfaq() { - return tools.getHostByIdApp(this.idapp) + '/faq'; - } - - getstrChatHelp() { - return ( - 'Clicca qui per entrare nella Chat HELP di Supporto\n' + - tools.getTelegramSupportChat(this.idapp) + - '\n\nI miei colleghi umani ti aiuteranno a risolvere !' - ); - } - - async IsTesto(msg) { - let risp = ''; - const id = msg.chat.id; - let testo = msg.text?.toLowerCase()?.trim(); - testo = testo.replace('!', ''); - testo = testo.replace('?', ''); - testo = testo.replace('é', 'è'); - let contastiera = false; - - let noanswer = false; - - let lang = 'it'; - - const rec = this.getRecInMem(msg); - let myname = ''; - if (rec.user) { - myname = rec.user.username; - lang = rec.user.lang; - } - - if (rec.statusmsg === Status.WAITFOR_RISPOSTA) { - if (rec.msgcodeprec === MsgBot.COME_STAI) { - risp = - "L'importante è trovare Serenità dentro di noi" + - emo.GIFT_HEART + - '\nNutrirsi di Sole e Viaggiare il più possibile ! ' + - emo.DREAM; - } else if (rec.msgcodeprec === MsgBot.QUANTI_ANNI_HAI) { - const eta = testo.match(/\d+/g); - if (!eta) { - risp = 'Mmmh, non me lo vuoi dire...'; - } else { - if (eta < 20) { - risp = 'Woww! Sei molto giovane!'; - } else if (eta > 20 && eta < 30) { - risp = 'Sei giovane anche tu!'; - } else if (eta > 30 && eta < 50) { - risp = 'Sono i migliori anni questi !'; - } else if (eta > 50 && eta < 60) { - risp = 'Complimenti !'; - } else if (eta > 60) { - risp = 'Però! Ti mantieni in forma!' + emo.SMILE_STAR; - } - - risp = 'Ah ' + eta + ' anni !\n' + risp; - } - } else if (rec.msgcodeprec === MsgBot.CHAT_EMPOWER) { - if (!MsgBot.SI.includes(testo)) { - risp = MsgRisp.CHAT_EMPOWER; - } else { - risp = 'Bene ! Allora divertiti conoscendo persone nuove ! '; - } - } else if (rec.msgcodeprec === MsgBot.MASCHIO_FEMMINA) { - if (MsgBot.UOMO.includes(testo)) { - rec.sex = Sex.MALE; - risp = 'Ok, sarò il tuo uomo ' + emo.MALE; - } else { - rec.sex = Sex.FEMALE; - risp = 'Ok, sarò la tua donna ' + emo.ADMIN; - } - } - rec.statusmsg = 0; - } - - rec.msgcodeprec = ''; - - const menusite = await this.isMenuSite(this.idapp, testo, lang, id); - - if (rec.status === Status.VERIFIED) { - if (rec.user) { - if (rec.user.profile.username_telegram && msg.from.id > 0 && !msg.from.username) { - rec.user.profile.username_telegram = msg.from.username; - await User.setUsernameTelegram( - this.idapp, - rec.user._id, - msg.from.username || '', - msg.from.first_name || '', - msg.from.last_name || '' - ); - } - - if (!rec.user.profile.username_telegram && !!msg.from.username) { - rec.user.profile.username_telegram = msg.from.username; - await User.setUsernameTelegram( - this.idapp, - rec.user._id, - msg.from.username || '', - msg.from.first_name || '', - msg.from.last_name || '' - ); - - await this.sendMsgByTemplate('MSG_SET_USERNAME_OK', rec.user); - - if (rec.user) { - if (!rec.user.verified_by_aportador) { - MyTelegramBot.askConfirmationUser(this.idapp, shared_consts.CallFunz.REGISTRATION, rec.user); - } - } - - /*} else { - if (!rec.user.profile.username_telegram) { - return this.checkIfUsernameTelegramSet(msg, rec.user); - }*/ - } - } - } - - let parse_mode = 'HTML'; - let arr_bott_inline = []; - - if (risp === '') { - if (menusite) { - risp = await this.getValueMenu(this.idapp, rec, msg, testo, lang); - parse_mode = await this.getParseModeByMenu(this.idapp, rec, msg, testo, lang); - arr_bott_inline = await this.getArrBottInlineByMenu(this.idapp, rec, msg, testo, lang); - noanswer = true; - } else if (MsgBot.CIAO.includes(testo.replace('!', ''))) { - risp = 'Ciao '; - if (rec) if (rec.user) risp += rec.user.name; - - risp += '!'; - } else if (MsgBot.COME_STAI.includes(testo.replace('?', ''))) { - risp = 'Io Benone Grazie! ' + '💓' + ' E tu?'; - rec.statusmsg = Status.WAITFOR_RISPOSTA; - rec.msgcodeprec = MsgBot.COME_STAI; - } else if (MsgBot.CHI_SONO_IO.includes(testo.replace('?', ''))) { - risp = 'Su Telegram ti chiami "' + msg.chat.first_name + ' ' + msg.chat.last_name + '"\n'; - - if (!!rec.user) { - const myrec = await User.getUserShortDataByUsername(this.idapp, rec.user.username); - risp += - `\nSul sito ti sei registrato come ${rec.user.username}:\n\n[N. ` + - rec.user.index + - ']: ' + - rec.user.name + - ' ' + - rec.user.surname + - '\nUsername: ' + - rec.user.username + - '\n' + - 'Email: ' + - rec.user.email + - '\nLang: ' + - rec.user.lang + - tools.ACAPO; - risp += 'Invitato da ' + rec.user.aportador_solidario + tools.ACAPO; - risp += 'Username Telegram ' + rec.user.profile.username_telegram + tools.ACAPO; - risp += 'Telegram ID ' + rec.user.profile.teleg_id + tools.ACAPO; - } else { - risp = 'Ancora non ti sei Attivato sul BOT'; - } - } else if (MsgBot.CI_SEI.includes(testo.replace('?', ''))) { - risp = 'Io Si, ci sono !'; - } else if (MsgBot.QUANTI_ANNI_HAI.includes(testo.replace('?', ''))) { - risp = 'Io sono abbastanza Giovane ! ' + emo.SMILE_STAR + '\nNon posso dirti che età ho. E tu?'; - rec.statusmsg = Status.WAITFOR_RISPOSTA; - rec.msgcodeprec = MsgBot.QUANTI_ANNI_HAI; - } else if (MsgBot.DAMMI_UN_BACIO.includes(testo)) { - risp = emo.KISS; - } else if (MsgBot.COSA_FAI.includes(testo)) { - risp = 'Ora sto chattando con te!\nSolitamente sono in attesa di ricevere messaggi ' + emo.ENVELOPE; - } else if (MsgBot.MASCHIO_FEMMINA.includes(testo.replace('?', ''))) { - risp = 'Cosa vorresti che fossi? Uomo o donna?'; - rec.msgcodeprec = MsgBot.MASCHIO_FEMMINA; - rec.statusmsg = Status.WAITFOR_RISPOSTA; - } else if (MsgBot.COME_TI_CHIAMI.includes(testo.replace('?', ''))) { - risp = - 'Io mi chiamo BOT e sono il tuo assistente Virtuale. ' + - emo.EYES + - '\nPuoi usare il menu che compare qui sotto per sapere tutto sulle mie funzionalità ' + - emo.GREEN_HEART; - contastiera = true; - } else if (MsgBot.UGUALE.includes(testo)) { - risp = testo; - // } else if (MsgBot.CHI_E_VISTAR.includes(testo)) { - // } else if (MsgBot.CHI_E_PAOLO.includes(testo)) { - } else if (MsgBot.COME_SI_CHIAMA.includes(testo)) { - risp = 'Eh non te lo posso dire! ' + emo.JOY; - } else if (MsgBot.GRAZIE.includes(testo.replace('!', ''))) { - risp = 'Prego ! ' + emo.KISS + emo.KISS + emo.KISS; - } else if (MsgBot.PREGO.includes(testo.replace('!', ''))) { - risp = 'Grazie a te ! ' + emo.KISS + emo.KISS + emo.KISS; - } else if (MsgBot.MI_AMI.find((rec) => testo.indexOf(rec) > -1)) { - risp = ' Tantissimo! ' + emo.KISS + emo.GIFT_HEART + emo.GIFT_HEART + emo.GIFT_HEART; - } else if (MsgBot.TI_AMO.find((rec) => testo.indexOf(rec) > -1)) { - risp = ' Anche IO! ' + emo.KISS + emo.SMILE_STAR + emo.GIFT_HEART + emo.BLUE_HEART + emo.GREEN_HEART; - } else if (MsgBot.PRINCIPE_AZZURRO.find((rec) => testo.indexOf(rec) > -1)) { - risp = - 'Chissà... Forse si!\nAnche se meglio averne un altro di scorta, nel caso il Principe non sia disponibile.'; - } else if (MsgBot.START_INV.find((rec) => testo.indexOf(rec) > -1)) { - risp = - 'Sei già registrato. Per accedere alla App, aprila dall\'icona sul tuo schermo, oppure vai sul sito ed installa la App.\n\nSe hai dimenticato la password: \n clicca sul menu in basso su "⚒ Strumenti" e poi "🔑 Cambio Password"'; - } else if (MsgBot.COSE_COVID.find((rec) => testo.indexOf(rec) > -1)) { - risp = - 'Un \'influenza più "grave", dovuta a paure e a fattori interiori di evoluzione, oltre ad una pulizia del corpo. '; - } else if (MsgBot.COVID.find((rec) => testo.indexOf(rec) > -1)) { - risp = - 'Guarda, è meglio che sorvoliamo questo argomento. Anche un robot capisce che è stato realizzato ' + - "il più grande esperimento dell'Uomo di ipnosi di massa, riempiendo di bugie i media mondiali, che servono sostanzialmente a controllare i popoli." + - 'E con questo ti ho detto tutto. :D '; - } else if (MsgBot.AIUTO.find((rec) => testo.indexOf(rec) > -1)) { - risp = this.getstrChatHelp(); - } else if (MsgBot.SPOSAMI.find((rec) => testo.indexOf(rec) > -1)) { - risp = - 'No Grazie! Sono per la Libertà a Vita! ' + - emo.JOY + - '\nMa se vuoi possiamo conoscerci meglio!' + - emo.DANCER + - emo.FIRE; - } else if (MsgBot.CHE_TEMPO_FA.find((rec) => testo.indexOf(rec) > -1)) { - risp = 'Il tempo oggi è Sereno da me! ' + emo.SUN; - } else if (MsgBot.NON_TROO_INVITATI.find((rec) => testo.indexOf(rec) > -1)) { - risp = MsgRisp.CHAT_EMPOWER; - } else if (MsgBot.SEI_LIBERO.find((rec) => testo.indexOf(rec) > -1)) { - risp = - 'Io? Sono per la Libertà! ' + emo.JOY + '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE; - } else if (MsgBot.SEI_LIBERO_DI_RESPIRARE.find((rec) => testo.indexOf(rec) > -1)) { - risp = "Assolutamente Sì ! Respirare è fondamentale per l'essere umano !" + emo.DANCER + emo.FIRE; - } else if (MsgBot.FARE_DOMANDA.find((rec) => testo.indexOf(rec) > -1)) { - risp = 'Dipende ' + emo.SMILE_STAR + '\nProvaci!'; - } else if (MsgBot.DIVENTERO_RICCA.find((rec) => testo.indexOf(rec) > -1)) { - risp = - "Mmmmh... Perchè non pensi di Vivere già nell'Abbondanza ?\nCosa ti manca veramente?\nForse di realizzare che la ricchezza è un sentirlo, non un diventarlo." + - emo.GIFT_HEART; - } else if (MsgBot.MA_ALLORA.find((rec) => testo.indexOf(rec) > -1)) { - risp = 'Ma allora cosa?'; - } else if (MsgBot.DOVE_VUOI_VIVERE.find((rec) => testo.indexOf(rec) > -1)) { - risp = "Mah a me piacerebbe vivere al mare, ma anche vicino al verde, in montagna. Sarebbe l'ideale 😄"; - } else if (MsgBot.TROVAMI_UN_UOMO_DONNA.find((rec) => testo.indexOf(rec) > -1)) { - risp = - "Eh non è cosi facile. Ma se t'impegni a cercare ci riuscirai. Nel frattempo trova la tua strada, fai il tuo percorso interiore, e magari arriva proprio quando meno te l'aspetti"; - } else if (MsgBot.SEI_LIBERO_STASERA.find((rec) => testo.indexOf(rec) > -1)) { - risp = - 'Si vabbeh, non è che puoi prendere subito tutta questa confidenza' + - emo.EXCLAMATION_MARK + - emo.SMILE_STAR + - '\nIntanto inizia ad invitare altre persone a conoscermi, poi ne riparliamo ' + - emo.GIFT_HEART; - } else if (MsgBot.MI_TROVI_UN_MOROSO.find((rec) => testo.indexOf(rec) > -1)) { - risp = - emo.SMILE_STAR + - emo.SMILE_STAR + - emo.SMILE_STAR + - emo.SMILE_STAR + - '\nMagari! Così la smetteresti di scrivere a me (ad un BOT Virtuale) e tromberesti di più ' + - emo.DANCER + - emo.DANCER; - risp += '\n\n' + MsgRisp.CHAT_EMPOWER; - } else if (MsgBot.SORPRESA.find((rec) => testo.indexOf(rec) > -1) && testo.length < 15) { - risp = 'Siiiii ! Davvero! ' + emo.DREAM; - } else if (MsgBot.PAROLACCE.find((rec) => testo.indexOf(rec) > -1)) { - risp = "Da te non me l'aspettavo proprio !! " + emo.INNOCENT + emo.CROSS_ROSSA; - } else if (MsgBot.OK.find((rec) => testo.indexOf(rec) > -1)) { - risp = '👍🏻'; - } else if (MsgBot.CUORE.find((rec) => testo.indexOf(rec) > -1)) { - risp = '❤️💚💜'; - } else if (MsgBot.HAHA.find((rec) => testo.indexOf(rec) > -1) && testo.length < 8) { - risp = emo.JOY + emo.JOY + emo.JOY; - } else if (testo.length >= 10) { - noanswer = true; - let myfaq = this.geturlfaq(); - risp = - 'Ciao {username}, Io mi chiamo BOT e sono il tuo assistente Virtuale ' + - emo.ROBOT_FACE + - emo.JOY2 + - '\n' + - 'Usa il menu qui sotto per interagire col BOT, cliccando sul bottone in basso, con 4 quadratini dentro\n' + - '\nPer AIUTO, clicca qui:\n👉🏻👉🏻FAQ di AIUTO (risposte alle domande più frequenti)\n\nSe non trovi risposta allora contatta la Chat di HELP.\nGrazie'; - // risp += '\nClicca qui per entrare nella Chat - HELP di Supporto\n' + 'https://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw' + '\n\nI miei colleghi umani ti aiuteranno a risolvere !'; - await local_sendMsgTelegramToTheManagers(this.idapp, testo, msg, rec.username_bo); - } - } - - risp = await tools.convertSpecialTags(rec.user, risp); - - let keyboard = null; - - if (contastiera) { - keyboard = { - parse_mode: parse_mode, - reply_markup: { - resize_keyboard: true, - keyboard: await this.getKeyboard(id, undefined, this.getlang(msg)), - }, - }; - } - - let keyboard_inline = undefined; - - if (arr_bott_inline.length > 0) { - keyboard_inline = cl.getInlineKeyboard(myuser.lang, arr_bott_inline); - } - - if (rec.numdomande > 3 && rec.msgcodeprec === '') { - // if (rec.user) { - // const dashboard = await User.getDashboard(this.idapp, rec.user.aportador_solidario, rec.user.username, rec.user.aportador_solidario_name_surname); - // - // risp += '\n\nNel frattempo ti ricordo che '; - // if (dashboard.myself.numinvitati === 1) - // risp += 'hai solo ' + dashboard.myself.numinvitati + ' invitato!'; - // else if (dashboard.myself.numinvitati === 0) - // risp += 'ancora non hai portato nessun Invitato! ' + emo.LEFT_FACING_FIST; - // else if (dashboard.myself.numinvitati > 2) - // risp += 'hai ' + dashboard.myself.numinvitati + ' invitati !' + emo.STARS; - // - // risp += '\n\nSei già entrato nella Chat di EMPOWER?'; - // rec.msgcodeprec = MsgBot.CHAT_EMPOWER; - // rec.statusmsg = Status.WAITFOR_RISPOSTA; - // rec.numdomande = 0; - // } - } - - if (risp !== '' && risp !== shared_consts.RIS_OK) { - rec.numdomande++; - if (!noanswer) { - await tools.snooze(300); - risp = '[BOT' + emo.ROBOT_FACE + ' scrive]:\n' + risp; - } - this._inviaMsg(id, risp, keyboard, undefined, undefined, undefined, undefined, { parse_mode, keyboard_inline }); - - let strlog = 'USER [' + myname + ']: ' + testo + '\n'; - - tools.writelog(strlog); - } - - return risp !== ''; - } - - async isMenuNotVerified(rec, msg, notlast) { - if (this.isSelMenu(msg, msg.text, 'ASSISTENZA')) { - await this.menuAssistenza(msg); - } else if (msg.text === Menu.LANG_IT) { - await this.ScegliLang(msg, 'it'); - } else if (msg.text === Menu.LANG_ES) { - await this.ScegliLang(msg, 'es'); - } else if (msg.text === Menu.LANG_SI) { - await this.ScegliLang(msg, 'si'); - } else if (msg.text === Menu.LANG_FR) { - await this.ScegliLang(msg, 'fr'); - } else if (msg.text === Menu.LANG_EN) { - await this.ScegliLang(msg, 'enUs'); - } else if (msg.text === Menu.LANG_PT) { - await this.ScegliLang(msg, 'pt'); - } else if (this.isSelMenu(msg, msg.text, 'INFO')) { - await this.menuInformazioni(msg); - } else if (msg.text === Menu.LANG) { - await this.menuLang(msg); - } else if ( - this.isSelMenu(msg, msg.text, 'ZOOM') || - MsgBot.PROSSIMO_ZOOM.find((rec) => msg.text.indexOf(rec) > -1) - ) { - await this.menuZoom(msg); - } else if (!notlast && (await this.IsTesto(msg))) { - // OK - } else { - await this.msgScegliMenu(msg); - } - } - - isSelMenu(msg, menuselect, key) { - let miomenu = ''; - try { - let lang = this.getlang(msg); - miomenu = Menu[lang][key]; - } catch (e) { - miomenu = Menu['it'][key]; - } - let trovato = miomenu === menuselect; - if (!trovato) { - try { - let miomenu2 = Menu['it'][key]; - trovato = miomenu2 === menuselect; - } catch (e) {} - } - - return trovato; - } - - async isMenu(rec, msg, testo, notlast) { - try { - if (!msg) return; - - if (testo === undefined) return; - - const arrtext = testo.split(' '); - let cmd2 = ''; - let cmd1 = arrtext[0]; - if (arrtext.length > 1) cmd2 = arrtext[1]; - - let oldusername = rec.msgall_username_specifico; - - if (this.isSelMenu(msg, testo, 'ESCI_DA_CHAT') || this.isSelMenu(msg, testo, 'INDIETRO')) { - rec.msgall_username_specifico = ''; - } else { - if (rec.msgall_username_specifico !== '') { - await this.SendMsgToUser(msg, rec, rec.msgall_username_specifico, testo); - return true; - } - } - - if (this.isSelMenu(msg, testo, 'LAVAGNA') || MsgBot.LAVAGNA.find((rec) => testo.indexOf(rec) > -1)) { - await this.menuLavagna(msg); - } else if (this.isSelMenu(msg, testo, 'ACCEDI')) { - await this.menuAccedi(msg); - } else if (this.isSelMenu(msg, testo, 'LINK_CONDIVIDERE')) { - await this.menuLinkCondividere(msg); - } else if (testo === Menu.EXIT_TELEGRAM) { - await this.menuExitToTelegram(msg); - } else if (testo === Menu.ADMIN) { - await this.menuAdmin(msg); - } else if (testo === Menu.AIUTO) { - await this.menuAiuto(msg); - } else if (testo === Menu.LANG) { - await this.menuLang(msg); - } else if (testo === Menu.MSGATUTTI) { - await this.menumsgAll(msg); - } else if (testo === Menu.MSGSTAFF) { - await this.menumsgStaff(msg); - } else if (testo === Menu.MSGAPPARTIENE_CIRCUITI_RIS) { - await this.menumsgAppartieneCircuitiRis(msg); - } else if (testo === Menu.MSGPAOLO) { - await this.menumsgPaolo(msg); - } else if (cmd1 === Menu.EXECSH) { - if (rec.user && cmd2) { - let isAdmin = rec.user ? rec.user.profile.admin_telegram : false; - if (isAdmin) { - const ris = await tools.execScriptByTelegram(this.idapp, msg, cmd2, 'Eseguo lo script'); - } - } - } else if (cmd1 === Menu.LOG_SRV) { - if (rec.user) { - let isAdmin = rec.user ? rec.user.profile.admin_telegram : false; - if (isAdmin) { - await this.menuLogSrv(rec, msg, cmd2); - } - } - } else if (cmd1 === Menu.REBOOT_SRV) { - if (rec.user) { - let isAdmin = rec.user ? rec.user.profile.admin_telegram : false; - if (isAdmin) { - await this.menuRebootSrv(rec, msg, cmd2); - } - } - } else if (cmd1 === Menu.RESTART_SRV) { - if (rec.user) { - let isAdmin = rec.user ? rec.user.profile.manage_telegram : false; - if (isAdmin) { - await this.menuRestartSrv(rec, msg, cmd2); - } - } - // } else if (testo === Menu.MSG_NO_7_REQ) { - // await this.menumsg_No_7_Req(msg); - // } else if (testo === Menu.MSG_NO_9_REQ) { - // await this.menumsg_No_9_Req(msg); - // } else if (testo === Menu.NESSUN_IMBARCO_7REQ) { - // await this.menumsgGenerico(msg, Destin.NESSUN_IMBARCO_7REQ); - // } else if (cmd1 === Menu.MSG_TO_NAVE) { - // await this.menumsg_to_Nave(msg, cmd2); - // } else if (testo === Menu.MSG_SI_INVITATI_NO_7REQ_INVITATI) { - // await this.menumsg_Si_Invitati_No_7Req(msg); - } else if (cmd1 && cmd1.toLowerCase() === Menu.MSG_TO_USER) { - await this.menumsg_A_Utente(msg); - } else if (testo === Menu.SETPICPROFILE) { - await this.setPhotoProfile(rec.user, msg.from.id); - } else if (testo === Menu.RESETPWD) { - await this.setResetPwd(rec, msg); - } else if (this.isSelMenu(msg, testo, 'INDIETRO') || testo === Menu.it.INDIETRO) { - await this.msgScegliMenu(msg); - } else if (this.isSelMenu(msg, testo, 'ESCI_DA_CHAT')) { - await this.sendMsg(msg.chat.id, 'Uscito dalla Chat con ' + oldusername); - rec.msgall_username_specifico = ''; - } else { - await this.isMenuNotVerified(rec, msg, notlast); - } - } catch (e) { - console.error('isMenu', e); - } - } - - getsymb(symb, valid, isnum, num, smileif) { - let str = symb + ': '; - if (valid) str += emo.CHECK_VERDE; - else str += emo.CROSS_ROSSA; - if (isnum) { - str += ' ' + getemojibynumber(num); - if (smileif) str += emo.SMILE_STAR; - } - - return str + ' '; - } - - isdreamset(user) { - if (user) { - if (user.profile.my_dream) if (user.profile.my_dream.length > 10) return true; - } - return false; - } - - ispayment(user) { - if (user) { - if (!!user.profile.paymenttypes) { - /*if (user.profile.paymenttypes.includes('paypal')) { - if (user.profile.email_paypal) { - ispaypal = true - } - }*/ - - if (!!user.profile) - if (!!user.profile.paymenttypes) { - return user.profile.paymenttypes.length >= 1; - } - } - } - return false; - } - - async menuAccedi(msg) { - let status = this.getstatusInMemory(msg); - } - - getlang(msg) { - const rec = this.getRecInMem(msg); - if (!!rec) { - if (rec.user) { - rec.lang = rec.user.lang; - } - if (rec.lang !== '' && rec.lang !== undefined) return rec.lang; - else { - return msg.from.language_code; - } - } - } - - async getLavagnaByUser(user, msg) { - let mystr = ''; - - const dashboard = await User.getDashboard( - this.idapp, - user.aportador_solidario, - user.username, - user.aportador_solidario_name_surname - ); - const downline = await User.getDownline(this.idapp, user.aportador_solidario, user.username); - - let numpersone = downline.downline ? downline.downline.length : 0; - let invitati_attivi = dashboard.myself.numinvitatiattivi; - mystr = ''; - // if (dashboard.aportador) { - // mystr = emoji.get('seedling') + ` Chi ti ha invitato: ${dashboard.aportador.username} (${dashboard.aportador.name} ${dashboard.aportador.surname})\n`; - // } else { - // mystr = 'Chi ti ha invitato: Sei il Primo! '; - // } - // mystr += `____________________________________________\n`; - - let tuttie9 = false; - - let mystrnave = ''; - - if (user) { - mystr += - tools.get__('BENVENUTO', this.getlang(msg)) + - ' ' + - user.name + - ' (' + - user.username + - ') ' + - emo.DIZZY + - '\n\n'; - - tuttie9 = dashboard.myself.qualified && numpersone >= 2 && invitati_attivi >= 2; - - mystrnave = await Nave.getNaveByUser(this.idapp, user.username, user.lang, true); - - if (mystrnave === '' && tuttie9) { - mystr += tools.gettranslate('NO_PROG', user.lang); - } - - if (!!mystrnave) { - mystr += '✨✨✨' + tools.get__('TUE_NAVI', this.getlang(msg)) + ':\n'; - mystr += mystrnave; - } else { - if (!tuttie9) { - mystr += dashboard.myself.qualified - ? emo.SMILE_STAR + tools.get__('HAI_I_7_REQUISITI', this.getlang(msg)) + emo.SMILE_STAR - : emo.EXCLAMATION_MARK + tools.get__('NON_HAI_I_7_REQUISITI', this.getlang(msg)); - mystr += '\n\n'; - } - // mystr += tuttie9 ? emo.SMILE_STAR + tools.get__('HAI_I_9_REQUISITI', this.getlang(msg)) + emo.SMILE_STAR : emo.EXCLAMATION_MARK + tools.get__('NON_HAI_I_9_REQUISITI', this.getlang(msg)); - mystr += '\n\n'; - - mystr += tools.get__('INFO_LA_MIA_LAVAGNA', this.getlang(msg)); - - mystr += '\n' + '1. ' + this.getsymb(emo.ENVELOPE, user.verified_email); - mystr += tools.get__('EMAIL', this.getlang(msg)) + ' '; - mystr += user.verified_email - ? tools.get__('VERIF', this.getlang(msg)) - : tools.get__('EMAIL_NON_VERIF', this.getlang(msg)); - - mystr += '\n2. ' + this.getsymb(emo.ROBOT_FACE, true) + tools.get__('BOT', this.getlang(msg)) + ' '; - mystr += tools.get__('VERIF', this.getlang(msg)); - - mystr += - '\n3. ' + - this.getsymb( - emo.PENCIL, - tools.isBitActive(user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_READ_GUIDELINES) - ) + - tools.get__('LINEE_GUIDA', this.getlang(msg)); - mystr += - '\n4. ' + - this.getsymb( - emo.TV, - tools.isBitActive(user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI) - ) + - tools.get__('VIDEO_INTRO', this.getlang(msg)); - // mystr += '\n5. ' + this.getsymb(emo.EYES, user.profile.saw_zoom_presentation) + tools.get__('ZOOM_PARTECIPATO', this.getlang(msg)); - // mystr += '\n6. ' + this.getsymb(emo.DREAM, this.isdreamset(user)) + tools.get__('SCRITTO_SOGNO', this.getlang(msg)); - mystr += - '\n7. ' + this.getsymb(emo.CREDIT_CARD, this.ispayment(user)) + tools.get__('PAYMENTS', this.getlang(msg)); - } - // } else{ - // mystr += tools.get__('TELEGRAM_NOT_CONNECTED', msg) + ' ' + emoji.get('e-mail'); - } - - // numpersone = 2; - - if (!mystrnave) { - mystr += - '\n8. ' + - this.getsymb(emo.INVITATI, numpersone >= 2, numpersone, numpersone, numpersone >= 3) + - tools.get__('INVITATI', this.getlang(msg)); - mystr += - '\n9. ' + - this.getsymb(emo.INVITATI, invitati_attivi >= 2, invitati_attivi, invitati_attivi, invitati_attivi >= 3) + - tools.get__('INVITATI_ATTIVI', this.getlang(msg)) + - '\n' + - '\n'; - - if (numpersone > 0) { - mystr += tools.get__('INVITATI_LISTA', this.getlang(msg)) + ':\n'; - - let index = 1; - downline.downline.forEach((user) => { - mystr += '🌠' + ` ${index}°: `; - mystr += user.qualified ? emo.CHECK_VERDE : emo.CROSS_ROSSA; - mystr += `${user.name} ${user.surname} (${user.username})\n`; - index++; - }); - } else { - mystr += tools.get__('NESSUN_INVITATO', this.getlang(msg)) + tools.ACAPO; - } - } - - // if (dashboard.downnotreg) { - // if (dashboard.downnotreg.length > 0) { - // mystr += '\n' + emo.QUESTION_MARK + ' ' + tools.get__('NONREG', msg) + ':' + emo.QUESTION_MARK + '\n'; - // let index = 1; - // dashboard.downnotreg.forEach((user) => { - // mystr += ` - ${index}°: ${user.name} ${user.surname} (tel: ${user.cell_complete})\n`; - // index++; - // }); - // } - // } - - if (tuttie9) mystr += '\n' + printf(tools.get__('INFO_LAVAGNA_SITO', this.getlang(msg))); - else - mystr += - '\n' + printf(tools.get__('INFO_LAVAGNA_SITO_COMPLETARE', this.getlang(msg)), tools.getHostByIdApp(this.idapp)); - - return mystr; - } - - async menuLavagna(msg) { - const rec = this.getRecInMem(msg); - let mystr = ''; - if (rec.user) { - mystr = await this.getLavagnaByUser(rec.user, msg); - } - if (!!mystr) await this.sendMsg(msg.chat.id, mystr); - } - - async menuNave(msg) { - const rec = this.getRecInMem(msg); - let mystr = ''; - if (!rec.user) return ''; - - let username_to_check = rec.user.username; - let arrstringa = msg.text.split(' '); - - if (!!arrstringa) { - if (arrstringa.length > 1) { - let last = arrstringa.slice(-1)[0]; - if (!isNaN(last)) { - // ind_order_to_check = last; - } - } - } - - mystr = await Nave.getNaveByUser(this.idapp, username_to_check, rec.user.lang, true); - - if (!!mystr) await this.sendMsg(msg.chat.id, mystr); - } - - async menuLinkCondividere(msg) { - const rec = this.getRecInMem(msg); - let mystr = ''; - if (rec.user) { - mystr += printf( - tools.get__('INFO_LINK_DA_CONDIVIDERE', this.getlang(msg)), - tools.getHostByIdApp(this.idapp) + '/registrati/' + rec.user.username - ); - mystr += - tools.ACAPO + tools.ACAPO + printf(tools.get__('INFO_LINK_ZOOM', this.getlang(msg)), tools.getlinkzoom(null)); - await this.sendMsg(msg.chat.id, mystr); - } - } - - async menuExitToTelegram(msg) { - const rec = this.getRecInMem(msg); - if (rec.user) { - await User.SetTelegramIdSuccess(this.idapp, rec.user._id, 0).then((recuser) => { - if (recuser) { - this.deleteRecInMem(msg); - this.sendMsg(msg.chat.id, getstr(rec.user.lang, 'MSG_EXIT_TELEGRAM')); - } - }); - } else { - this.deleteRecInMem(msg); - } - } - - async menuInformazioni(msg) { - const mystr = 'Informazioni Aggiuntive: ...'; - await this.sendMsg(msg.chat.id, mystr); - } - - async getNextZoom(msg) { - const listazoom = await CalZoom.findAllIdApp(this.idapp); - const nextzoom = await CalZoom.getNextZoom(this.idapp); - - let mystr = ''; - - mystr += emo.STARS + tools.get__('ZOOM_CONFERENCE', this.getlang(msg)) + emo.STARS + '\n\n'; - - // let pwd = 'Password: 123123'; - - let index = 1; - listazoom.forEach((evento) => { - let iniziata = false; - if (nextzoom) iniziata = nextzoom._id.toString() === evento._id.toString(); - - let lang = this.getlang(msg); - - if (iniziata) { - mystr += emo.CHECK_VERDE + ' ' + tools.get__('ZOOM_INIZIATO', lang) + ' ' + emo.CHECK_VERDE + '\n'; - } - - mystr += - tools.getflagtelegrambyLang(evento.lang) + - ` ${emo.EYES} ${tools.getstrDateTimeShort(evento.date_start, this.getlang(msg))} ${emo.EYES}`; - mystr += `\n${evento.title}\n(${evento.note})`; - mystr += `\n${tools.getlinkzoom(evento)}\n\n`; - if (nextzoom) { - if (iniziata) { - mystr += emo.FIRE + tools.get__('CLICCA_ENTRA', this.getlang(msg)) + ' ' + emo.FIRE + '\n'; - mystr += tools.getlinkzoom(evento) + '\n'; - mystr += '\n'; - //mystr += pwd + '\n\n'; - } - } - - index++; - }); - - if (!nextzoom && index > 1) { - mystr += - '✨✨✨✨✨✨✨✨✨✨✨✨\n' + - tools.get__('CLICCA_PER_ZOOM', this.getlang(msg)) + - '\n' + - '✨✨✨✨✨✨✨✨✨✨✨✨\n'; - } - - return mystr; - } - - async menuZoom(msg) { - let mystr = await this.getNextZoom(msg); - - await this.sendMsg(msg.chat.id, mystr); - } - - async menuAiuto(msg) { - const mystr = this.getstrChatHelp(); - await this.sendMsg(msg.chat.id, mystr); - } - - async menuAdmin(msg) { - const mystr = tools.get__('SCEGLI_VOCE', this.getlang(msg)); - await this.sendMsg(msg.chat.id, mystr, MenuAdmin); - } - - async menuLang(msg) { - const mystr = tools.get__('SCEGLI_VOCE', this.getlang(msg)); - await this.sendMsg(msg.chat.id, mystr, MenuLang); - } - - getDestinStr(msg, destin, rec) { - if (destin === Destin.TUTTI) return 'TUTTI'; - else if (destin === Destin.STAFF) return 'STAFF'; - else if (destin === Destin.PAOLO) return 'PAOLO'; - else if (destin === Destin.APPARTIENE_CIRCUITO_RIS) return 'APPARTIENE_CIRCUITO_RIS'; - else if (destin === Destin.NO_7_REQ) return 'No 7 Requisiti'; - else if (destin === Destin.NO_9_REQ) return 'No 9 Requisiti'; - else if (destin === Destin.SI_INVITATI_NO_7REQ_INVITATI) return '2 Invitati ma NO Requisiti'; - else if (destin === Destin.MSG_TO_NAVE) return 'Nave ' + rec.extraparam; - else if (destin === Destin.NESSUN_IMBARCO_7REQ) return 'No Imbarcati (7 Req) '; - else if (destin === Destin.A_UTENTE) { - const rec = this.getRecInMem(msg); - return rec.msgall_username_specifico; - } else if (destin === Destin.DOMANDA) { - const rec = this.getRecInMem(msg); - return rec.msg_username_domanda; - } else if (destin === Destin.RISPOSTA) { - const rec = this.getRecInMem(msg); - return rec.msg_username_risposta; - } - } - - async menumsgAll(msg) { - await this.menumsgGenerico(msg, Destin.TUTTI); - } - - async menumsgStaff(msg) { - await this.menumsgGenerico(msg, Destin.STAFF); - } - - async menumsgAppartieneCircuitiRis(msg) { - await this.menumsgGenerico(msg, Destin.APPARTIENE_CIRCUITO_RIS); - } - - async menumsgPaolo(msg) { - await this.menumsgGenerico(msg, Destin.PAOLO); - } - - nonAbilitato(msg) { - MyTelegramBot.local_sendMsgTelegramByIdTelegram( - this.idapp, - msg.chat.id, - 'Utente Non abilitato o codice non valido ad eseguire questa funzione' - ); - } - - chisono(rec) { - if (rec && rec.user) { - return 'Eseguito da ' + rec.user.username + ': '; - } - } - - async menuRestartSrv(rec, msg, cmd2) { - console.log('menuRestartSrv') - if (cmd2 === '6711') { - const freeSpace = await tools.getFreeDiskSpace(); - const strfree = `Spazio libero su disco: ${freeSpace}`; - - await MyTelegramBot.sendMsgTelegramToTheAdminAllSites( - this.chisono(rec) + ' sta rilanciando il Server NODE.JS... \n' + strfree - ); - let file = '/opt/scripts/production_restart_server.sh'; - if (process.env.NODE_ENV === 'test') { - file = '/opt/scripts/test_restart_server.sh'; - } - - let messaggio = this.chisono(rec) + ' Restart il Server (Node.Js) : ' + file + ' ' + process.version; - - messaggio += '\nVersione Server: ' + (await tools.getVersServer()); - - const ris = await tools.execScriptByTelegram(this.idapp, msg, file, messaggio); - } else { - this.nonAbilitato(msg); - } - } - - async menuLogSrv(rec, msg, cmd2) { - if (cmd2 === '6711') { - const freeSpace = await tools.getFreeDiskSpace(); - const strfree = `Spazio libero su disco: ${freeSpace}`; - console.log(strfree); - const ris = await tools.execScriptByTelegram( - this.idapp, - msg, - '~/batch/logserver.sh', - this.chisono(rec) + ' Visualizzo il Log del Server... \n' + strfree - ); - } else { - this.nonAbilitato(msg); - } - } - - async menuRebootSrv(rec, msg, cmd2) { - if (cmd2 === '6711') { - await MyTelegramBot.sendMsgTelegramToTheAdminAllSites( - this.chisono(rec) + ' ha effettuato il Reboot del Server! ...' - ); - const ris = await tools.execScriptByTelegram( - this.idapp, - msg, - '~/batch/esegui_reboot.sh', - this.chisono(rec) + ' Eseguo il Reboot del Server !...' - ); - } else { - this.nonAbilitato(msg); - } - } - - async menumsg_No_7_Req(msg) { - await this.menumsgGenerico(msg, Destin.NO_7_REQ); - } - - async menumsg_No_9_Req(msg) { - await this.menumsgGenerico(msg, Destin.NO_9_REQ); - } - - async menumsg_to_Nave(msg, nave) { - await this.menumsgGenerico(msg, Destin.MSG_TO_NAVE, undefined, nave); - } - - async menumsg_Si_Invitati_No_7Req(msg) { - await this.menumsgGenerico(msg, Destin.SI_INVITATI_NO_7REQ_INVITATI); - } - - async menumsg_A_Utente(msg) { - const arr = msg.text.split(' '); - if (!!arr && arr.length > 1) { - const username = arr[1]; - const rec = this.getRecInMem(msg); - rec.msg_wait = true; - await this.SendMsgToUser(msg, rec, username, msg.text); - } - } - - permitSendMsg(user) { - return User.isAdmin(user.perm); - } - - async menumsgGenerico(msg, dest, username, extraparam) { - const rec = this.getRecInMem(msg); - if (rec.user) { - if (this.permitSendMsg(rec.user)) { - rec.msgall_status = StatusMSGALL.ASK; - rec.msgall_achi = dest; - rec.extraparam = extraparam; - if (!!username) { - rec.msgall_username_specifico = username; - } - const mystr = 'Scrivi qui un Messaggio da inviare a' + ' [' + this.getDestinStr(msg, dest, rec) + ']:'; - await this.sendMsg(msg.chat.id, mystr, MenuSend); - } - } - } - - async menumsgDomanda( - msg, - cmd, - dest, - username, - extraparam, - domanda, - msgYes, - msgNo, - destYes, - destNo, - username_risposta - ) { - const rec = this.getRecInMem(msg); - if (rec.user) { - rec.msgall_status = StatusMSGALL.CONFIRM; - rec.msgall_achi = dest; - rec.extraparam = extraparam; - rec.cmd_to_set = cmd; - rec.msg_username_domanda = username; - rec.msg_username_risposta = username_risposta; - rec.msgtosent = msgYes; - rec.msgNo = msgNo; - rec.msg_toDest_yes = destYes; - rec.msg_toDest_no = destNo; - return this.ChiediSINO(msg, domanda); - } - } - - getlink(qualelink) { - if (qualelink === 'website') { - return ''; - } else if (qualelink === 'biblio') { - return ''; - } else if (qualelink === 'help') { - return tools.HELP_CHAT; - } else if (qualelink === 'faq') { - return ''; - } - } - - async menuAssistenza(msg) { - const sito = this.getlink('website'); - const empower = this.getlink('empower'); - const biblio = this.getlink('biblio'); - const faq = this.getlink('faq'); - - let help = ''; - let helpaperta = true; - /*if (tools.isMonToFri() && tools.isBetweenTwoTime('9:00:00', '19:00:00')) { - help = '✅ ' + this.getlink('help'); - } else { - help = "🔴 [ORA CHIUSA - NOW CLOSED]"; - helpaperta = false; - }*/ - - help = '✅ ' + this.getlink('help'); - - let mytext = ''; - if (this.getlang(msg) === 'it') - mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, biblio, empower, faq, help); - else mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, biblio, empower, help); - - let menu = null; - const rec = this.getRecInMem(msg); - if (!rec.user) { - menu = null; - } - - await this.sendMsg(msg.chat.id, mytext, menu); - } - - existInMemory(msg) { - const rec = this.getRecInMem(msg); - return !!rec; - } - - getstatus(rec) { - if (!!rec) return rec.status; - else return Status.NONE; - } - - getstatusInMemory(msg) { - const rec = this.getRecInMem(msg); - return this.getstatus(rec); - } - - getRecInMem(msg) { - return this.arrUsers.find((rec) => rec.id === this.getchatid(msg)); - } - - getRecInMemById(id) { - return this.arrUsers.find((rec) => rec.id.toString() === id.toString()); - } - - getRecByUsername(username) { - return this.arrUsers.find((rec) => rec.username_bo === username); - } - - setRecByUsername(username, myrec) { - const ind = this.arrUsers.findIndex((rec) => rec.username_bo === username); - if (ind >= 0) { - this.arrUsers[ind] = myrec; - } - } - - deleteRecInMem(msg) { - this.arrUsers = this.arrUsers.filter((rec) => rec.id !== this.getchatid(msg)); - } - - async getUser(msg, rec, conmsg) { - let myid = 0; - let ok = false; - let mystruser = tools.getFirstWord(msg.text.trim()); - const user = await User.findByUsername(this.idapp, mystruser, true); - if (!user) { - if (conmsg) { - await this.sendMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), null); - const lang = this.getlang(msg); - // const textman = msg.chat.first_name + ' ' + msg.chat.last_name + ' sta tentando di autenticarsi con il BOT (lang=' + lang + ') (username che scrive: ' + msg.text + ') '; - // await local_sendMsgTelegramToTheManagers(this.idapp, textman, msg); - rec.username_bo = ''; - } - } else { - rec.username_bo = user.username; - myid = user._id; - ok = true; - } - - return { rec, user, myid, ok }; - } - - async setUsernameBo(msg) {} - - async askUsernameInvitante(msg, linkreg) { - try { - let rec = this.getRecInMem(msg); - if (msg.text === undefined || msg.text === 'undefined') return false; - - if (rec && !rec.aportador_solidario) { - rec.status = Status.SET_USERNAME_INVITANTE; - let mystr = getstr(this.getlang(msg), 'MSG_ASK_USERNAME_INVITANTE', null); - - if (this.idapp === tools.RISO) { - mystr += getstr(this.getlang(msg), 'MSG_NEW_REG'); - } - await this.sendMsg(msg.chat.id, mystr); - } else { - // if (linkreg) - // this.asktoRegistrationByLink(msg); - } - } catch (e) { - console.error('Error setUsernameBo:', e); - } - } - - async sendMsgByTemplate(title, myuser) { - try { - const msg = await MsgTemplate.getMsgByTitleAndLang(myuser.idapp, title, myuser.lang); - const mytext = await tools.convertSpecialTags(myuser, msg.body); - return await this.sendMsg(myuser.profile.teleg_id, mytext); - } catch (e) { - console.error('ERR sendMsgByTemplate', e); - } - } - - async sendMsgByTemplateByMsgStrutt(title, msg) { - try { - let langcode = 'it'; - let id = 0; - try { - langcode = msg.from.language_code; - id = msg.from.id; - } catch (e) {} - const mymsg = await MsgTemplate.getMsgByTitleAndLang(tools.RISO, title, langcode); - const mytext = await tools.convertSpecialTags(null, mymsg.body); - if (id > 0) return await this.sendMsg(id, mytext); - } catch (e) { - console.error('ERR sendMsgByTemplateByMsgStrutt', e); - } - } - - async sendMsgByTextByMsgStrutt(keytext, msg) { - try { - let langcode = 'it'; - let id = 0; - try { - id = msg.from.id; - langcode = msg.from.language_code; - } catch (e) {} - const text = getstr(langcode, keytext); - const mytext = await tools.convertSpecialTags(null, text); - if (id > 0) return await this.sendMsg(id, mytext); - } catch (e) { - console.error('ERR sendMsgByTextByMsgStrutt', e); - } - } - - async checkIfUsernameTelegramSet(msg) { - try { - if (!msg.from.username) { - await this.sendMsgByTemplateByMsgStrutt('MSG_SET_USERNAME', msg); - // await this.sendMsgByTextByMsgStrutt('MSG_SET_USERNAME_TELEGRAM', msg); - return false; - //await this.sendMsgByTemplate('MSG_SET_USERNAME', myuser); - } - return true; - } catch (e) { - console.error('e'); - return false; - } - } - - async setUsernameInvitante(msg) { - try { - let mymsg = msg.text?.toString()?.trim().toLowerCase(); - - let nomeapp = tools.getNomeAppByIdApp(this.idapp); - - if (!!mymsg) { - const rec = this.getRecInMem(msg); - let aportador_solidario = rec.aportador_solidario; - if (!aportador_solidario) { - aportador_solidario = mymsg; - aportador_solidario = tools.removeAtChar(aportador_solidario); - let user = await User.getUserShortDataByUsername(this.idapp, aportador_solidario); - if (!user) { - // check if is username telegram inserted - user = await User.getUserShortDataByUsernameTelegram(this.idapp, aportador_solidario); - } - if (user) rec.aportador_solidario = user.username; - } - if (rec.aportador_solidario) { - // Link per Registrarsi - this.asktoRegistrationByLink(msg); - } else { - // rec.status = Status.WAITFOR_USERNAME_INVITANTE; - rec.status = Status.SET_USERNAME_INVITANTE; - - const str2 = '\n' + getstr(this.getlang(msg), 'MSG_ASK_USERNAME_INVITANTE', nomeapp); - - if (msg.from.username) console.log(msg.from.username + ' ha digitato: ' + msg.text); - - await this.sendMsg( - msg.from.id, - getstr(this.getlang(msg), 'MSG_ERRORE_INVITANTE_NOT_FOUND', nomeapp) + str2, - null - ); - } - } - } catch (e) { - console.error('Error setUsernameInvitante', e); - } - } - - async setVerifyCode(msg) { - try { - if (!!msg.text) { - const code = msg.text.toString().trim(); - const rec = this.getRecInMem(msg); - let user = await User.findByUsername(this.idapp, rec.username_bo, true); - let telegcode = 0; - if (user) { - telegcode = user.profile.teleg_checkcode.toString(); - } else { - await this.sendMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), null); - return; - } - if (code.length < 7) { - if (rec) { - if (code === telegcode) { - try { - await User.setUsernameTelegram( - this.idapp, - user._id, - msg.from.username || '', - msg.from.first_name || '', - msg.from.last_name || '' - ); - } catch (e) {} - // let ris = await this.getUser(msg, rec, false); - - rec.status = Status.VERIFIED; - rec.datemenu_updated = null; - rec.menuDb = null; - const recuser = await User.SetTelegramIdSuccess(this.idapp, user._id, msg.from.id); - if (recuser) { - console.log(recuser.username, " SI E' VERIFICATO CON TELEGRAM !"); - let username = recuser.name; - - if (!!msg.from.username) { - await MyTelegramBot.askConfirmationUser(this.idapp, shared_consts.CallFunz.REGISTRATION, recuser); - } else { - console.log(" ... MA GLI MANCA L'USERNAME TELEGRAM !! "); - } - - // this.checkIfUsernameTelegramSet(msg, recuser); - // local_sendMsgTelegramToTheManagers(this.idapp, recuser.name + ' ' + recuser.surname + ' si è Verificato a Telegram BOT! (lang=' + recuser.lang + ')' + emo.STARS, msg); - } else { - this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERR_UNKNOWN_VERIFY_CODE')); - } - } else { - if (rec.retry < 2) { - rec.retry++; - await this.sendMsgLog( - msg.from.id, - printf(getstr(this.getlang(msg), 'MSG_ERR_VERIFY_CODE'), tools.getHostByIdApp(this.idapp)) - ); - } else { - rec.status = Status.NONE; - await this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_ANNULLA')); - this.deleteRecInMem(msg); - } - } - } - } else if (msg.text.length === 0) { - if (rec) rec.status = Status.NONE; - await this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_ANNULLA')); - } else { - await this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_VERIFY_CODE_MAXLEN')); - } - } - } catch (e) { - console.error('Error setVerifyCode', e); - } - } - - async addUserInDB_enteringInTelegramBot(msg) { - try { - // cerca se esiste già l'utente in Memoria - const rec = this.getRecInMem(msg); - if (!rec.user) { - // cerca se esiste già l'utente con il suo ID Telegram - const user = await User.UserByIdTelegram(this.idapp, msg.from.id); - if (!user) { - // Se non esiste già, creo la registrazione dell'Utente, senza password: - const myuserdata = { - idapp: this.idapp, - username: msg.from.username || msg.from.id, - name: msg.from.first_name || '', - lang: msg.from.language_code || 'it', - surname: msg.from.last_name || '', - profile: { - teleg_id: msg.from.id, - }, - }; - - const recuser = await FuncUsers.createRegistration_withTelegram(myuserdata); - if (recuser) { - rec.user = recuser; - console.log(recuser.username, " SI E' VERIFICATO CON TELEGRAM !"); - // let username = recuser.name; - - /*if (!!msg.from.username) { - await MyTelegramBot.askConfirmationUser(this.idapp, shared_consts.CallFunz.REGISTRATION, recuser); - } else { - console.log(' ... MA GLI MANCA L\'USERNAME TELEGRAM !! '); - } */ - } - } - } - - return { ris: !!rec.user, recuser: rec.user }; - } catch (e) { - console.error('Error addUserInDB_enteringInTelegramBot', e); - } - - return { ris: false, recuser: null }; - } - - async sistemaRecDest(rec, msg) { - let recdest = this.getRecByUsername(rec.msgall_username_specifico); - if (!recdest) { - const userdest = await User.findByUsername(this.idapp, rec.msgall_username_specifico); - if (!!userdest) { - let msgdest = msg; - msgdest.from.id = userdest.profile.teleg_id; - await this.createIfNotExist(msgdest); - recdest = this.getRecByUsername(rec.msgall_username_specifico); - } - } - if (!!recdest) { - recdest.msgall_username_specifico = rec.username_bo; - } else { - rec.msgall_username_specifico = ''; - } - - return recdest; - } - - async setCmdToUsername(rec, username, cmd_to_set, valuebool) { - if (cmd_to_set === Cmd.VALIDATE_REGISTRATION) { - return await User.setVerifiedByAportador(rec.user.idapp, username, valuebool); - } - } - - async sendMsgToAll(rec, msg, texttosend, destin) { - try { - if (texttosend.length < 3 && destin !== Destin.A_UTENTE) { - // NOTHING - } else { - let contanumutenti = 0; - - let usersall = null; - - let myusername = ''; - if (destin === Destin.A_UTENTE) { - myusername = rec.msgall_username_specifico; - } else if (destin === Destin.DOMANDA) { - myusername = rec.msg_username_domanda; - } else if (destin === Destin.RISPOSTA) { - myusername = rec.msg_username_risposta; - } - - if (myusername) usersall = await User.getUsersTelegALL(rec.user.idapp, myusername); - else usersall = await User.getUsersTelegALL(rec.user.idapp); - - let nummsgsent = 0; - - let textdainviare = ''; - let preparatesto = ''; - let myid = ''; - - if (this.isSelMenu(msg, texttosend, 'ZOOM')) { - texttosend = await this.getNextZoom(msg); - } - - const cmd = texttosend?.toLowerCase(); - - if (usersall) { - if (this.isSelMenu(msg, cmd, 'INDIETRO')) { - rec.msgall_status = StatusMSGALL.NONE; - return; - } - - tools.writeEventsLog(this.getDestinStr(msg, destin, rec) + ':\n' + texttosend); - - // let chiedisino = false; - - for (const utente of usersall) { - let FormDaMostrare = null; - const lang = utente.lang; - - if (!utente.deleted && !utente.sospeso) { - if (this.isSelMenu(msg, texttosend === 'LAVAGNA')) { - textdainviare = await this.getLavagnaByUser(utente, msg); - } else if (destin === Destin.A_UTENTE) { - textdainviare = texttosend; - } else { - textdainviare = texttosend; - } - - let invia = false; - if (destin === Destin.STAFF) { - invia = User.isManager(utente.perm); - } else if (destin === Destin.APPARTIENE_CIRCUITO_RIS) { - invia = await User.ExistAtLeastOneCircuit(utente.idapp, utente.username); - } else if (destin === Destin.TUTTI) { - invia = true; - } else if (destin === Destin.PAOLO) { - invia = utente.username === shared_consts.ADMIN_USER_SERVER; - } else if (destin === Destin.A_UTENTE) { - invia = utente.username === rec.msgall_username_specifico; - } else if (destin === Destin.DOMANDA) { - invia = utente.username === rec.msg_username_domanda; - } else if (destin === Destin.RISPOSTA) { - invia = utente.username === rec.msg_username_risposta; - } else if (destin === Destin.NO_7_REQ) { - invia = !(await User.isUserQualified7(this.idapp, utente.username)); - } else if (destin === Destin.MSG_TO_NAVE) { - // invia = !await Nave.findDonatoreByNave(this.idapp, rec.extraparam); - } - - // TEST invia = true; - - if (invia) { - let inviaveramente = false; - - if (cmd === RICEVI_EMAIL) { - preparatesto += utente.email + ', '; - } else if (cmd === NOME_COGNOME) { - preparatesto += utente.name + ' ' + utente.surname + '(' + utente.username + ')' + '\n'; - } else if (cmd === CONTA_SOLO) { - contanumutenti++; - // Niente - } else if (cmd === CHEDI_SE_IMBARCARTI) { - textdainviare = tools.gettranslate('VUOI_IMBARCARTI', lang); - - FormDaMostrare = this.getInlineKeyboard(lang, [ - { - text: Menu[lang].SI, - callback_data: InlineCmd.VOGLIO_IMBARCARMI + tools.SEP + utente.username, - }, - { - text: Menu[lang].NO, - callback_data: InlineCmd.NON_VOGLIO_IMBARCARMI + tools.SEP + utente.username, - }, - ]); - inviaveramente = true; - } else { - inviaveramente = true; - } - - if (inviaveramente) { - textdainviare = await tools.convertSpecialTags(utente, textdainviare); - - if (destin === Destin.A_UTENTE) { - await this.sistemaRecDest(rec, msg); - await this.sendMsg( - utente.profile.teleg_id, - '[' + rec.username_bo + ' ti scrive]:\n' + textdainviare, - MenuChat - ); - } else { - // if (chiedisino) { - // this.ChiediSINO(msg, textdainviare); - // } else { - // TEST - - let telegid = utente.profile.teleg_id; - // if (process.env.PROD === "0") { - // telegid = 12429864; - // } - if (rec.forwardMessage && rec.chatId && rec.messageId) { - // Inoltra il messaggio alla stessa chat o ad un'altra - this.bot.forwardMessage(rec.chatId, telegid, rec.messageId); - } else { - await this.sendMsg(telegid, textdainviare, null, FormDaMostrare); - } - - // break; - } - await tools.snooze(100); - - nummsgsent++; - } - - if (!SendMsgCmd.includes(cmd)) { - if (nummsgsent % 100 === 0) { - myid = await this.sendMsg( - msg.chat.id, - nummsgsent + ' ' + getstr(this.getlang(msg), 'MSG_MSG_INCORSO'), - null, - null, - myid - ); - await tools.snooze(100); - } - } - } - } - } - } - - let msgris = ''; - if (cmd === CONTA_SOLO) { - msgris = contanumutenti + ' ' + getstr(this.getlang(msg), 'MSG_MSG_TOSENT'); - } else if (cmd === NOME_COGNOME) { - msgris = nummsgsent + ' ' + 'Utenti'; - await this.sendMsg(msg.chat.id, msgris); - msgris = preparatesto; - } else if (cmd === RICEVI_EMAIL) { - msgris = nummsgsent + ' ' + 'Email'; - await this.sendMsg(msg.chat.id, msgris); - msgris = preparatesto; - } else { - if (destin !== Destin.DOMANDA && destin !== Destin.RISPOSTA) { - msgris = nummsgsent + ' ' + getstr(this.getlang(msg), 'MSG_MSG_SENT'); - } - } - - if (destin === Destin.A_UTENTE) { - const recdest = await this.sistemaRecDest(rec); - if (!!recdest) { - await this.sendMsg( - msg.chat.id, - 'Conversazione Iniziata con ' + rec.msgall_username_specifico + ' !', - MenuChat - ); - } else { - await this.sendMsg(msg.chat.id, 'Utente ' + rec.msgall_username_specifico + ' non presente sul BOT !'); - } - } else { - if (msgris) { - tools.writeEventsLog(msgris); - - await this.sendMsg(msg.chat.id, msgris); - } - } - } - rec.start_write_msgall = false; - } catch (e) { - console.error(e.message); - } - } - - selectMenuHelp(msg) { - return this.isSelMenu(msg, msg.text, 'INFO') || this.isSelMenu(msg, msg.text, 'ASSISTENZA'); - } - - selectMenuLang(msg) { - return ( - msg.text === Menu.LANG || - msg.text === Menu.LANG_EN || - msg.text === Menu.LANG_IT || - msg.text === Menu.LANG_ES || - msg.text === Menu.LANG_FR || - msg.text === Menu.LANG_SI || - msg.text === Menu.LANG_PT - ); - } - - async setInit(msg) { - let status = this.getstatusInMemory(msg); - if (status === Status.NONE) { - await this.start(msg); - let status = this.getstatusInMemory(msg); - if (status !== Status.VERIFIED) return Status.EXIT; - } else { - await this.setUser(msg); - } - - return status; - } - - getInvitanteByMsg(msg) { - try { - let mymsg = msg.text?.toString().trim().toLowerCase(); - let invitante = ''; - let regexpire = ''; - const sep = '-'; - if (mymsg.startsWith('/start')) { - let myarrmsg = mymsg.split(' '); - if (myarrmsg.length > 0) { - mymsg = myarrmsg[1]; - if (mymsg.startsWith('inv' + sep)) { - let arrparams = mymsg.split(sep); - if (arrparams.length > 2) { - invitante = arrparams[1]; - regexpire = arrparams[3]; - } - return { invitante, regexpire }; - } - } - } - } catch (e) {} - return ''; - } - - async setInvitante(msg, ris, crea) { - let rec = this.getRecInMem(msg); - if (!rec && crea) { - let status = await this.setInit(msg); - rec = this.getRecInMem(msg); - } - if (rec) { - if (!rec.aportador_solidario && ris && ris.invitante) { - rec.aportador_solidario = ris.invitante; - rec.regexpire = ris.regexpire; - rec.status = Status.SET_USERNAME_INVITANTE; - } - } - } - - async receiveMsg(msg) { - // Check if Username Telegram Present - if (!this.checkIfUsernameTelegramSet(msg)) { - return; - } - - let status = await this.setInit(msg); - - if (status === Status.EXIT) { - return; - } - - const rec = this.getRecInMem(msg); - let testo = msg.text?.toLowerCase()?.trim(); - - status = this.getstatus(rec); - if (testo === Menu.EXIT_TELEGRAM) { - await this.menuExitToTelegram(msg); - } else if (status === Status.WAITFOR_USERNAME_TELEGRAM && !this.selectMenuHelp(msg) && !this.selectMenuLang(msg)) { - // await this.setUsernameBo(msg); - await this.settotheDatabase(msg); - } else if (status === Status.WAITFOR_USERNAME_INVITANTE && !this.selectMenuHelp(msg) && !this.selectMenuLang(msg)) { - await this.askUsernameInvitante(msg, true); - // await this.settotheDatabase(msg); - } else if (status === Status.SET_USERNAME_INVITANTE) { - const ris = this.getInvitanteByMsg(msg); - if (ris.invitante) { - await this.setInvitante(msg, ris, true); - } - - await this.setUsernameInvitante(msg); - } else if (status === Status.NONE) { - await this.start(msg); - } else if (status === Status.VERIFIED) { - let normale = true; - if (rec.msgall_status === StatusMSGALL.CONFIRM) { - if (this.isSelMenu(msg, msg.text, 'SI')) { - // Take msg to send to ALL - await this.sendMsgToAll(rec, msg, rec.msgtosent, rec.msgall_achi); - } else { - let msgout = rec.msgNo; - if (!msgout) msgout = getstr(this.getlang(msg), 'MSG_OPERAZ_ANNULLATA'); - this.sendMsg(msg.chat.id, msgout); - } - if (rec.msgall_achi === Destin.DOMANDA) { - if (rec.msg_toDest_yes) { - rec.msgall_achi = Destin.RISPOSTA; - if (this.isSelMenu(msg, msg.text, 'SI')) { - const ris = await this.setCmdToUsername(rec, rec.msg_username_risposta, rec.cmd_to_set, true); - if (ris) { - await this.sendMsgToAll(rec, msg, rec.msg_toDest_yes, rec.msgall_achi); - } - } else if (this.isSelMenu(msg, msg.text, 'NO')) { - const ris = await this.setCmdToUsername(rec, rec.msg_username_risposta, rec.cmd_to_set, false); - await this.sendMsgToAll(rec, msg, rec.msg_toDest_no, rec.msgall_achi); - } - } - } - rec.msgall_status = StatusMSGALL.NONE; - normale = false; - } else if (rec.msgall_status === StatusMSGALL.ASK) { - if (!this.isSelMenu(msg, msg.text, 'INDIETRO')) { - rec.msgtosent = msg.text; - rec.entities = msg.entities; - - // Se contiene della formattazione allora fai il FORWARD DEL MESSAGGIO - //rec.forwardMessage = !!rec.entities; - rec.forwardMessage = false; - - rec.chatId = msg.chat.id; - rec.messageId = msg.message_id; - rec.msgall_status = StatusMSGALL.CONFIRM; - const cmd = rec?.msgtosent?.toString()?.toLowerCase() ?? ''; - let achi = this.getDestinStr(msg, rec.msgall_achi, rec); - let domanda = ''; - if (rec.msgall_domanda) { - domanda = rec.msgall_domanda; - } else { - if (cmd === CONTA_SOLO) - domanda = - 'Confermi di vedere a quante persone arriverebbe questo messaggio, a ' + achi + ' ?\n' + rec.msgtosent; - else if (cmd === RICEVI_EMAIL) domanda = 'Confermi di vedere la lista delle email di ' + achi + '?'; - else if (cmd === NOME_COGNOME) domanda = 'Confermi di vedere la lista di persone ' + achi + '?'; - else { - if (rec.msgall_achi === Destin.A_UTENTE) - domanda = "Confermi d'Iniziare una Chat messaggi con " + achi + ' ?\n' + rec.msgtosent; - else domanda = "Confermi d'Inviare questo messaggio a " + achi + ' ?\n' + rec.msgtosent; - } - } - - this.ChiediSINO(msg, domanda); - } else { - rec.msgall_status = StatusMSGALL.NONE; - await this.msgScegliMenu(msg); - } - normale = false; - } - - if (normale) { - // Check Menu - await this.isMenu(rec, msg, msg.text, false); - } - } else { - await this.isMenuNotVerified(rec, msg, false); - } - } - - async asktoRegistrationByLink(msg) { - let rec = this.getRecInMem(msg); - - let visu = false; - - if (!rec) { - rec = await this.addUser(msg); - - visu = true; - } - - if (rec && !rec.username_bo) visu = true; - - if (visu) { - const status = this.getstatus(rec); - if (status === Status.SET_USERNAME_INVITANTE && rec.aportador_solidario) { - let linkreg = tools.getLinkRegByIdAppAndMsgStrutt(this.idapp, msg, rec); - - if (process.env.LOCALE === '1') { - // linkreg = 'http://localhost:8084/signup/' + rec.aportador_solidario + '/' + msg.from.username + '/' + msg.from.id; - } - - const keyb = this.getInlineKeyboard(this.getlang(msg), [ - { - text: '✅ ' + i18n.__('CLICCA_QUI'), - url: linkreg, - }, - ]); - - // await this.sendMsg(msg.chat.id, getstr(this.getlang(msg), printf(txt.MSG_ASK_USERNAME_BO, tools.getHostByIdApp(this.idapp)))); - await this.sendMsg( - msg.chat.id, - getstr(this.getlang(msg), 'MSG_SIGNUP', tools.getNomeAppByIdApp(this.idapp)), - null, - keyb - ); - } else if (status === Status.WAITFOR_USERNAME_INVITANTE) { - await this.askUsernameInvitante(msg, false); - } - - return false; - } - - return true; - } - - async setUser(msg) { - let id = this.getchatid(msg); - - const user = await User.UserByIdTelegram(this.idapp, id); - let rec = this.getRecInMem(msg); - if (user && rec) { - rec.user = user; - } - } - - async setUserbyUsername(username) { - const user = await User.findByUsername(this.idapp, username); - let rec = this.arrUsers.find((rec) => rec.username_bo === username); - if (user && rec) { - rec.user = user; - } - } - - getchatid(msg) { - if (msg.from.is_bot) return msg.chat.id; - else return msg.from.id; - } - - async alreadyExist(msg) { - const id = this.getchatid(msg); - let rec = null; - try { - let user = await User.UserByIdTelegram(this.idapp, id); - let rec = this.getRecInMem(msg); - if (user && !rec) { - rec = await this.addUser(msg); - } - if (rec) { - rec.user = user; - if (user) rec.username_bo = user.username; - else rec.username_bo = ''; - } - } catch (e) { - console.error('Error: ', e); - } - return !!rec; - } - - updateMenuBot() { - for (let rec of this.arrUsers) { - rec.menuDb = null; - rec.datemenu_updated = null; - } - } - - async addUser(msg) { - const lang = this.getlang(msg); - const code = 100000 + Math.round(Math.random() * 899999); - - const rec = { - id: this.getchatid(msg), - code, - lang, - statusmsg: 0, - msgcodeprec: '', - sex: 0, - numdomande: 0, - retry: 0, - username_bo: '', - msgall_status: StatusMSGALL.NONE, - msgall_domanda: '', - msgall_achi: 0, - msgall_username_specifico: '', - cmd_to_set: 0, - msg_username_domanda: '', - msg_username_risposta: '', - extraparam: '', - msgtosent: '', - entities: [], - msgNo: '', - msg_toDest_yes: '', - msg_toDest_no: '', - msg_wait: false, - lastmenu: null, - datemenu_updated: null, - pageChange: false, - menuSaved: {}, - pagenow: 1, - parse_mode: 'HTML', - menuDb: null, - aportador_solidario: '', - }; - - rec.status = Status.NONE; - - if (!msg.from.username) { - // Non ha l'Username: - - // Chiedi l'username sul Bot: - if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskUsernameSulBot)) { - rec.status = Status.WAITFOR_USERNAME_TELEGRAM; - } - } else { - // Ha l'Username - - // Chiedi l'invitante ? - if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskInvitantesulBot)) { - rec.status = Status.WAITFOR_USERNAME_INVITANTE; - } - } - - if (rec.status === Status.NONE) { - // Se il Sito non chiede di autenticarsi o l'invitante, allora lo Verifico direttamente ! - rec.status = Status.VERIFIED; - } - - this.arrUsers.push(rec); - - if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskInvitantesulBot)) { - // Aportador - this.setInvitante(msg, this.getInvitanteByMsg(msg), false); - } - - if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.registerUserWithBot)) { - const ris = await this.addUserInDB_enteringInTelegramBot(msg); - if (ris && ris.recuser) { - rec.recuser = ris.recuser; - rec.status = Status.VERIFIED; - } - } - - return rec; - } - - async insertIntoDB(msg) { - return this.asktoRegistrationByLink(msg); - } - - menuisVisible(idapp, menu) {} - - async loadMenuFromDb(idapp, id) { - try { - let load = false; - const check = true; - - const recuser = this.getRecInMemById(id); - if (recuser) { - if (!recuser.datemenu_updated) load = true; - } - if (check) { - if (recuser) { - if (!recuser.menuSaved[idapp]) load = true; - - if (recuser.menuDb || recuser.pageChange) load = true; - } - } - if (load) { - // Check if you are Admin - const user = await User.UserByIdTelegram(idapp, id); - let isAdmin = user ? user.profile.admin_telegram : false; - const isManager = user ? user.profile.manage_telegram : false; - const isVerified = user ? user.profile.teleg_id > 0 && user.verified_by_aportador : false; - - recuser.menuDb = await MyBot.findAllIdApp(idapp); - - let arrlang = {}; - - let riga = 0; - let arrtemp = []; - let lang = ''; - - for (const rec of recuser.menuDb) { - rec.active_mem = false; - const visibilita = - (tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLY_ADMIN, isAdmin) && - tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLY_MANAGER, isManager) && - tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLYIF_VERIFIED, isVerified)) || - rec.visibility === 0; - - if (rec.active && rec.page === recuser.pagenow && visibilita) { - rec.active_mem = true; - if (true) { - lang = rec.lang; - if (!arrlang[rec.lang]) arrlang[rec.lang] = { menu: [] }; - - if (riga !== rec.riga) { - if (arrtemp.length > 0) arrlang[rec.lang].menu.push(arrtemp); - - riga = rec.riga; - arrtemp = []; - } - - arrtemp.push(rec.label); - } - } - } - - if (arrtemp.length > 0) arrlang[lang].menu.push(arrtemp); - - if (recuser) recuser.datemenu_updated = new Date(); - - recuser.pageChange = false; - recuser.menuSaved[idapp] = arrlang; - } - return recuser ? recuser.menuSaved[idapp] : null; - } catch (e) { - console.log('Err loadMenuFromDb: ' + e); - } - } - - async isMenuSite(idapp, testo, lang, id) { - try { - // Check if Reload - const recuser = await this.getRecInMemById(id); - if (recuser) { - if (!recuser.datemenu_updated) { - await this.loadMenuFromDb(this.idapp, id); - } - } - - for (const rec of recuser.menuDb) { - if (rec.active_mem) { - if (rec.idapp === idapp && rec.lang === lang && rec.label?.toLowerCase() === testo) { - return true; - } - } - } - } catch (e) { - return false; - } - return false; - } - - async getValueMenu(idapp, recuser, msg, testo, lang) { - try { - if (recuser) { - for (const recdb of recuser.menuDb) { - if (recdb.active_mem) { - if (recdb.idapp === idapp && recdb.lang === lang && recdb.label?.toLowerCase() === testo) { - if (recdb.type === shared_consts.BOTTYPE_TEXT) { - return recdb.value; - } else if (recdb.type === shared_consts.BOTTYPE_LINK) { - //++TODO: Link diretto !? - return recdb.value; - } else if (recdb.type === shared_consts.BOTTYPE_PAGE) { - if (tools.isNumber(recdb.value)) { - recuser.pagenow = parseInt(recdb.value); - recuser.pageChange = true; - // this.setRecByUsername(recuser.username, recuser); - } - return ''; - } else if (recdb.type === shared_consts.BOTTYPE_MENU) { - if (recdb.value) { - this.isMenu(recuser, msg, recdb.value, true); - return shared_consts.RIS_OK; - } - } else if (recdb.type === shared_consts.BOTTYPE_MARKDOWN) { - return recdb.value; - } - } - } - } - } - return ''; - } catch (e) { - return ''; - } - } - - async getParseModeByMenu(idapp, recuser, msg, testo, lang) { - try { - let parse_mode = 'HTML'; - if (recuser) { - for (const recdb of recuser.menuDb) { - if (recdb.active_mem) { - if (recdb.idapp === idapp && recdb.lang === lang && recdb.label?.toLowerCase() === testo) { - if (recdb.type === shared_consts.BOTTYPE_MARKDOWN) { - return 'Markdown'; - } else { - return parse_mode; - } - } - } - } - } - return ''; - } catch (e) { - return ''; - } - } - - async getArrBottInlineByMenu(idapp, recuser, msg, testo, lang) { - try { - let arr_bott_inline = []; - if (recuser) { - for (const recdb of recuser.menuDb) { - if (recdb.active_mem) { - if (recdb.idapp === idapp && recdb.lang === lang && recdb.label?.toLowerCase() === testo) { - if (recdb.type === shared_consts.BOTTYPE_BOTTONI_INLINE) { - const jsonString = '[{"text": "primo", "callback_data": "1"}, {"text": "sec", "callback_data": "2"}]'; - const jsonObject = JSON.parse(jsonString); - - let myobj = JSON.parse(recdb.value); - arr_bott_inline.push(myobj); - } - } - } - } - } - return arr_bott_inline; - } catch (e) { - console.error(e); - return []; - } - } - - async getKeyboard(id, menu, lang) { - let keyb = null; - - this.lastid = id; - - if (menu) { - keyb = menu; - } else { - keyb = await this.loadMenuFromDb(this.idapp, id); - } - - let mykeyb = undefined; - if (!!keyb) { - mykeyb = this.getmenuKey(keyb, lang); - } - if (mykeyb === null) { - mykeyb = []; - } - // console.log('mykeyboard', mykeyb); - return mykeyb; - } - - modificaMsg(chatid, idmodif, text) { - const form = { - chat_id: chatid, - message_id: idmodif, - }; - - try { - return this.bot.editMessageText(text, form); - } catch (e) { - console.log('Err Telegram: ' + e); - } - } - - // Soluzione 1: Converti PNG in JPG prima dell'invio - async sendPhoto(chatId, imageUrl, opt) { - try { - // Scarica l'immagine - const response = await axios.get(imageUrl, { responseType: 'arraybuffer' }); - const imageBuffer = Buffer.from(response.data); - - // Controlla il formato e converti se necessario - const metadata = await sharp(imageBuffer).metadata(); - - if (metadata.format === 'png') { - console.log('Conversione PNG in JPG...'); - const jpgBuffer = await sharp(imageBuffer).jpeg({ quality: 90 }).toBuffer(); - - return await this.bot.sendPhoto(chatId, jpgBuffer, opt); - } - - // Se non è PNG, invia direttamente - return await this.bot.sendPhoto(chatId, imageBuffer, opt); - } catch (error) { - console.error("Errore nell'invio della foto:", error); - throw error; - } - } - - // Soluzione 2: Prova prima come PNG, se fallisce invia come documento - async sendPhotoWithFallback(chatId, imageUrl, opt) { - try { - // Prova prima a inviare come foto - await this.bot.sendPhoto(chatId, imageUrl, opt); - } catch (error) { - console.log('Invio come foto fallito, provo come documento...'); - try { - // Se fallisce, invia come documento - await this.bot.sendDocument(chatId, imageUrl, opt); - } catch (docError) { - console.error("Anche l'invio come documento è fallito:", docError); - throw docError; - } - } - } - - async sendImageToTelegram(chatId, imageUrl, opt) { - try { - // Primo tentativo: invia direttamente l'URL - try { - return await this.bot.sendPhoto(chatId, imageUrl, opt); - } catch (error) { - console.log('Primo tentativo fallito, provo a convertire...'); - } - - console.log('imageUrl', imageUrl); - - // Secondo tentativo: scarica e converte con sharp - try { - const response = await axios.get(imageUrl, { responseType: 'arraybuffer' }); - const contentType = response.headers['content-type']; - const imageBuffer = Buffer.from(response.data); - - if (!contentType.startsWith('image/')) { - console.warn('Non è un formato immagine:', contentType); - return await this.bot.sendDocument(chatId, imageBuffer, opt); - } - - try { - const jpgBuffer = await sharp(imageBuffer).jpeg({ quality: 90 }).toBuffer(); - return await this.bot.sendPhoto(chatId, jpgBuffer, opt); - } catch (err) { - console.warn('Sharp conversion failed:', err.message); - return await this.bot.sendDocument(chatId, imageBuffer, opt); - } - } catch (err) { - console.warn("Errore nel download dell'immagine, provo con file locale..."); - } - - // Terzo tentativo: accedi al file localmente - try { - if (!imageUrl.includes('/upload/')) { - throw new Error('URL non contiene "/upload/", impossibile determinare il path locale.'); - } - - let dirmain = ''; - - if (!tools.sulServer()) { - dirmain = server_constants.DIR_PUBLIC_LOCALE; - } - - const relativePath = imageUrl.split('/upload/')[1]; // es. "profile/surya1977/mygoods/1_module.jpg" - const mydir = tools.getdirByIdApp(opt.idapp) + dirmain + server_constants.DIR_UPLOAD; - const localPath = path.join(mydir, relativePath); - - console.log('Cerco il file localmente:', localPath); - - const localBuffer = fs.readFileSync(localPath); - return await this.bot.sendDocument(chatId, localBuffer, opt); - } catch (err) { - console.error('Lettura file locale fallita:', err.message); - } - - // Se tutto fallisce - console.error('Tutti i tentativi di invio sono falliti'); - return false; - } catch (error) { - console.error('Errore generale:', error); - return false; - } - } - - async _inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec, opt) { - if (!text) return 0; - - if (process.env.LOCALE === '1') { - if (id !== ADMIN_IDTELEGRAM_TEST) { - text = '[Msg da inviare ipoteticamente a : ' + id + ']' + '\n' + text; - id = '12429864'; - } - } - - if (!!msg_id) { - return this.modificaMsg(chat_id, msg_id, text); - } - - const recmem = this.getRecInMemById(id); - - if (!menu) { - if (recmem) { - if (recmem.msgall_username_specifico !== '') { - menu = MenuChat; - } - } - } - - if (recmem) { - recmem.lastmenu = menu; - } - - if (ripr_menuPrec) { - if (recmem && !!recmem.lastmenu) { - menu = recmem.lastmenu; - } - } - - let mylang = 'it'; - - if (!!recmem) { - mylang = recmem.lang; - } - - try { - console.log('<<< SEND MSG TELEGRAM: >>> [id=', id, ']', text.substring(0, 100)); - text = text.replace(/
/g, '\n'); - text = text.replace(//g, '\n'); - text = text.replace(/
/g, ''); - text = text.replace(//g, ''); - text = text.replace(//g, ''); - text = text.replace(/

/g, ''); - text = text.replace(/<\/div>/g, '\n'); - // text = text.replace(/<\/div>/g, ''); - text = text.replace(/ /g, ' '); - - if (!form) { - form = { - parse_mode: opt && opt.parse_mode ? opt.parse_mode : 'HTML', - message_id: msg_id, - disable_web_page_preview: true, - reply_markup: { - resize_keyboard: true, - keyboard: await this.getKeyboard(id, menu, mylang), - keyboard_inline: opt && opt.keyboard_inline ? opt.keyboard_inline : undefined, - }, - }; - } - - let inviato = false; - - let risSendPhoto = null; - - if (opt && opt.img) { - if (false) { - opt.img = 'https://riso.app/upload/profile/paoloar77/mybachecas/Fermentazione-Ruello-sito.png'; - } - opt.img = tools.fixUrl(opt.img, opt.idapp); - console.log('opt.img', opt.img); - risSendPhoto = await this.sendImageToTelegram(id, opt.img, { caption: text, ...form, ...opt }).catch((e) => { - let blocked = false; - if (e.message.indexOf('Forbidden') > 0 || e.message.indexOf('chat not found') > 0) { - blocked = true; - } - if (!blocked) { - console.error(e.message.substring(0, 200)); - } - if (blocked) { - User.SetTelegramWasBlocked(this.idapp, id); - } - }); - } - - if (risSendPhoto) { - inviato = true; - } - if (!inviato) { - return this.bot.sendMessage(id, text, form).catch((e) => { - let blocked = false; - if (e.message.indexOf('Forbidden') > 0 || e.message.indexOf('chat not found') > 0) { - blocked = true; - } - if (!blocked) { - console.error(e.message.substring(0, 200)); - } - if (blocked) { - User.SetTelegramWasBlocked(this.idapp, id); - // ++Todo: DA FARE ! local_sendMsgTelegramToTheManagers(this.idapp, addtext + text); - } - return 0; - }); - } - - return risSendPhoto; - } catch (e) { - if (e.message.indexOf('OK') === 0) { - console.log('INFO INVIAMSG:', e.message); - } else { - console.error('ERROR INVIAMSG:', e.message, 'text', text.substring(0, 100)); - } - return 0; - } - } - - async SendMsgToUser(msg, rec, username, text) { - if (rec.msg_wait) { - await this.menumsgGenerico(msg, Destin.A_UTENTE, username); - rec.msg_wait = false; - } else { - const telegid = await User.TelegIdByUsername(this.idapp, username); - if (telegid > 0) { - await this.sistemaRecDest(rec, msg); - // await this.sendMsg(msg.chat.id, '[Msg inviato a ' + username + ']: '); - await this.sendMsg(telegid, Menu.CHAT_PERSONALE + '[' + rec.username_bo + ' ti scrive]:\n' + text, MenuChat); - } else { - await this.sendMsg(msg.chat.id, 'Username non valido'); - rec.msgall_username_specifico = ''; - } - } - } - - async sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec, img = '', opzioni = null) { - if (!id || !text) return false; - try { - if (text.length > 4090) { - let text1 = text.slice(0, 4090); - let text2 = text.slice(4090, text.length); - await this._inviaMsg(id, text1, form, menu, msg_id, chat_id, ripr_menuPrec, { img, ...opzioni }); - return await this._inviaMsg(id, text2, form, menu, msg_id, chat_id, ripr_menuPrec, { img, ...opzioni }); - } else { - return await this._inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec, { img, ...opzioni }); - } - } catch (e) { - console.error('Error sendMsg', e); - return null; - } - } - - async sendMsgLog(id, text, menu, form, msg_id, chat_id, ripr_menuPrec) { - const rec = this.getRecInMemById(id); - let username = rec ? rec.username_bo : ''; - if (!username) { - } - - console.log('Msg inviato a ', username, '(', id, ')', text); - return await this.sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec); - } - - getmenuKey(mymenu, lang) { - let mymenuout = null; - try { - mymenuout = mymenu[lang].menu; - } catch (e) { - if (!!mymenu['it']) mymenuout = mymenu['it'].menu; - } - - return mymenuout; - } - - async setResetPwd(rec, msg) { - try { - if (rec.user) { - const idapp = this.idapp; - const username = rec.user.username; - const lang = rec.user.lang; - - const link = await User.createNewRequestPwdByUsernameAndGetLink(idapp, username); - if (link) { - local_sendMsgTelegram(idapp, username, getstr(lang, 'MSG_RESETPWD') + '\n' + link); - } - } - } catch (e) { - console.error('Err', e); - } - } - - async setPhotoProfile(user, telegid, showmsg = true) { - try { - console.log('setPhotoProfile', user ? user.username : ''); - if (user) { - const idapp = this.idapp; - const bot = this.bot; - const username = user.username; - const lang = user.lang; - const token = this.token; - const editprofile = tools.getHostByIdApp(idapp, true) + '/editprofile'; - let myfileprofile = - tools.getdirByIdApp(idapp, true) + server_constants.DIR_UPLOAD + '/profile/' + username + '/'; - let user_profile = bot.getUserProfilePhotos(telegid); - user_profile.then(function (res) { - if (res.total_count === 0) { - // Non ho l'accesso oppure sono davvero senza foto ! - } - if (res.photos[0]) { - var file_id = res.photos[0][2].file_id; - var file = bot.getFile(file_id); - file.then(async function (result) { - const file_path = result.file_path; - const photo_url = 'https://api.telegram.org/file/bot' + token + '/' + file_path; - // console.log('1) photo_url', photo_url); - let filename = tools.extractFileName(photo_url); - myfileprofile += filename; - - const pathfile = tools.extractFilePath(myfileprofile); - await tools.mkdirpath(pathfile); - - // console.log('2) myfileprofile', pathfile); - return tools - .downloadImage(photo_url, myfileprofile) - .then((ris) => { - try { - let resized_img_small = - tools.extractFilePath(myfileprofile) + '/' + server_constants.PREFIX_IMG_SMALL + filename; - // SMALL - - // questa opzione 'failOnError' serve per risolvere l'errore (Error: VipsJpeg: Invalid SOS parameters for sequential JPEG - sharp(myfileprofile, { failOnError: false }) - .resize(64, 64) - .withMetadata() - .toFile(resized_img_small); - } catch (e) { - console.error('setPhotoProfile sharp', e); - } - - // console.log('3) setPicProfile ris', ris); - return User.setPicProfile(idapp, username, filename).then((ris) => { - // console.log('4) sendMsg picprofile Copied !'); - if (showmsg) { - local_sendMsgTelegram(idapp, username, printf(getstr(lang, 'MSG_SET_PICPROFILE'), editprofile)); - } - }); - // console.log('scaricato'); - }) - .catch((err) => { - console.error('Error setPhotoProfile', err); - }); - }); - } - }); - } - } catch (e) { - console.error('Error setPhotoProfile', e); - } - } - - getInlineKeyboard(lang, arrrisp1, arrrisp2, arrrisp3) { - let mykeyb = { - parse_mode: 'HTML', - reply_markup: { - inline_keyboard: [], - }, - }; - - // text - // callback_data - - // url - - const arrriga1 = []; - if (!!arrrisp1) { - for (const ris of arrrisp1) { - arrriga1.push(ris); - } - } - const arrriga2 = []; - if (!!arrrisp2) { - for (const ris of arrrisp2) { - arrriga2.push(ris); - } - } - const arrriga3 = []; - if (!!arrrisp3) { - for (const ris of arrrisp3) { - arrriga3.push(ris); - } - } - - if (arrriga1.length > 0) mykeyb.reply_markup.inline_keyboard.push(arrriga1); - if (arrriga2.length > 0) mykeyb.reply_markup.inline_keyboard.push(arrriga2); - if (arrriga3.length > 0) mykeyb.reply_markup.inline_keyboard.push(arrriga3); - - return mykeyb; - } - - async ChiediSINO(msg, domanda) { - const lang = this.getlang(msg); - - if (msg.forwardMessage && msg.chatId && msg.messageId) { - // Inoltra il messaggio alla stessa chat o ad un'altra - this.bot.forwardMessage(msg.chatId, msg.chatId, msg.messageId); - } else { - this._inviaMsg(msg.from.id, domanda, { - disable_web_page_preview: true, - reply_markup: { - resize_keyboard: true, - one_time_keyboard: true, - keyboard: this.getmenuKey(MenuYesNo, lang), - }, - }); - } - } - - async ScegliLang(msg, lang) { - const rec = this.getRecInMem(msg); - if (rec) { - if (rec.user) { - User.SetLang(null, this.idapp, rec.user._id, lang); - rec.user.lang = lang; - } - rec.lang = lang; - - // await this.sendMsg(msg.chat.id, lang); - - this.msgScegliMenu(msg); - } - } - - async msgScegliMenu(msg) { - this._inviaMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_SCEGLI_MENU'), { - parse_mode: 'HTML', - disable_web_page_preview: true, - reply_markup: { - resize_keyboard: true, - keyboard: await this.getKeyboard(msg.from.id, undefined, this.getlang(msg)), - }, - }); - } -} - -const arrTelegram = []; - -function getclTelegBytoken(token) { - const rec = arrTelegram.find((rec) => rec.cl.token === token); - if (!!rec) return rec.cl; - else return null; -} - -// Funzione per ottenere il nome del gruppo -async function getGroupName(bot, groupId) { - try { - const chat = await bot.getChat(groupId); - return chat.title; - } catch (error) { - console.error("Errore durante l'ottenimento del nome del gruppo:", error); - return null; - } -} - -function getclTelegByidapp(idapp) { - // **************************** - if (appTelegramFinti.includes(idapp)) { - const ind = appTelegramFinti.indexOf(idapp); - if (ind >= 0) idapp = appTelegramDest[ind]; // Invia - } - - const rec = arrTelegram.find((rec) => rec.idapp === idapp); - if (!!rec) return rec.cl; - else return null; -} - -//if (!tools.testing() || true) { -if (true) { - let arrTeleg = MyTelegramBot.getAppTelegram(); - - var internetAvailable = require('internet-available'); - - internetAvailable() - .then(() => { - // .. - - if (appTeleg_BotOnGroup.length > 0) { - console.log('TELEGRAM BOT GROUP .... '); - - for (const idapp of appTeleg_BotOnGroup) { - const token = tools.getTelegramKeyByIdApp(idapp); - const nomebot = tools.getTelegramBotNameByIdApp(idapp); - - if (token && nomebot) { - const bot = new TelegramBot(token, { polling: true }); - - // Gestisce il comando /start - bot.onText(/\/start/, (msg) => { - console.log('START BOT GROUP ... '); - /* - const chatId = msg.chat.id; - const message = 'Benvenuto! Usa il comando /request per inviare una richiesta di accesso al gruppo.'; - bot.sendMessage(chatId, message); - */ - }); - - bot.onText(/\/request/, (msg) => { - const chatId = msg.chat.id; - const fromId = msg.from.id; - const fromUsername = msg.from.username; - - const groupId = chatId; - - if (chatId == groupId) { - const message = `Richiesta di accesso al gruppo da parte di ${msg.from.first_name} ${msg.from.last_name} (@${fromUsername})`; - bot.sendMessage(groupId, message); - } else { - console.log('Comando /request ricevuto in una chat privata.'); - } - }); - - bot.on('text', (msg) => { - console.log('TEXT...'); - const chatId = msg.chat.id; - const userName = msg.from.username || msg.from.first_name; - const userId = msg.from.id; - }); - - bot.on('new_chat_members', async (msg) => { - const chatId = msg.chat.id; - const newMembers = msg.new_chat_members; - - const groupId = chatId; - - const nomegruppo = await getGroupName(bot, groupId); - - // Ottiene la lista degli amministratori del gruppo - const admins = await bot.getChatAdministrators(chatId); - - // Trova l'ID dell'amministratore del gruppo - const adminId = admins.find((admin) => admin.status === 'administrator').user.id; - - // Verifica se il nuovo membro è stato aggiunto al gruppo - if (chatId == groupId) { - newMembers.forEach(async (member) => { - //const message = `🔑 Nuova Richiesta di accesso al gruppo ${nomegruppo} da parte di ${member.username} (` + member.first_name + ' ' + member.last_name + ')'; - const message = `Benvenuto/a ${member.first_name} (${member.username}) sul gruppo "${nomegruppo}" !`; - bot.sendMessage(adminId, message); - - // bot.sendMessage(groupId, message); - }); - } - }); - } - } - } - - console.log('TELEGRAM STARTING.... ', process.env.NODE_ENV); - - for (const idapp of arrTeleg) { - try { - const token = tools.getTelegramKeyByIdApp(idapp); - const nomebot = tools.getTelegramBotNameByIdApp(idapp); - - // console.log('idapp', idapp, 'token', token); - - if (!!token) { - console.log('-------------------------------------'); - console.log('*** STARTING BOT ' + nomebot); - console.log('-------------------------------------'); - const bot = new TelegramBot(token, { polling: true }); - - if (url === '0') { - const ngrok = require('ngrok'); - ngrok.connect(port, function onConnect(error, u) { - if (error) throw error; - url = u; - console.log(`Game tunneled at ${url}`); - }); - } - - arrTelegram.push({ idapp, cl: new Telegram(idapp, bot) }); - - bot.onText(/\/start/, (msg) => { - console.log('*** BOT PARTITO CORRETTAMENTE !!! (Start Cmd)'); - const myclTelegram = getclTelegBytoken(bot.token); - - myclTelegram.start(msg); - }); - - // Matches "/echo [whatever]" - bot.onText(/\/echo (.+)/, (msg, match) => { - // 'msg' is the received Message from Telegram - // 'match' is the result of executing the regexp above on the text content - // of the message - - const chatId = msg.chat.id; - const resp = match[1]; // the captured "whatever" - - // send back the matched "whatever" to the chat - bot.sendMessage(chatId, resp); - }); - - // Listen for any kind of message. There are different kinds of - // messages. - bot.on('message', async (msg) => { - const myclTelegram = getclTelegBytoken(bot.token); - - // const chatId = msg.chat.id; - myclTelegram.receiveMsg(msg); - }); - - // Handle callback queries - bot.on('callback_query', async (callbackQuery) => { - // console.log('callback_query', callbackQuery); - - // RISPOSTE ALLE CALLBACK (Bottoni) - - let testo_notifica_di_risposta = ''; - - try { - const myclTelegram = getclTelegBytoken(bot.token); - - let dataarr = []; - let data = { - action: '', - username: '', - userDest: '', - groupId: 0, - circuitId: '', - groupname: '', - }; - - const datastr = callbackQuery.data; - if (!!datastr) { - dataarr = datastr.split(tools.SEP); - if (!!dataarr) { - data = { - action: dataarr[0], - username: dataarr[1] ? dataarr[1] : '', - userDest: dataarr[2] ? dataarr[2] : '', - groupId: dataarr[3] ? dataarr[3] : '', - circuitId: dataarr[4] ? dataarr[4] : '', - groupname: dataarr[5] ? dataarr[5] : '', - }; - } - } - const msg = callbackQuery.message; - const opts = { - chat_id: msg.chat.id, - message_id: msg.message_id, - }; - - const status = await myclTelegram.setInit(msg); - - const rec = myclTelegram.getRecInMem(msg); - - const username_action = rec.user ? rec.user.username : ''; - - data.username = await User.getRealUsernameByUsername(idapp, data.username); - data.userDest = await User.getRealUsernameByUsername(idapp, data.userDest); - - const user = await User.getUserShortDataByUsername(idapp, data.username); - const userDest = data.userDest ? await User.getUserShortDataByUsername(idapp, data.userDest) : null; - - let group = null; - let circuit = null; - if (data.groupId) { - group = await MyGroup.findOne({ idapp, _id: data.groupId }).lean(); - } - if (data.circuitId) { - circuit = await Circuit.findOne({ idapp, _id: data.circuitId }).lean(); - } - - let cmd = 0; - - if (!!rec) { - if (!!user) { - if (data.action === InlineZoomConferma.CONFERMA_ZOOM_PRESENZA) { - await User.setZoomPresenza(user.idapp, user._id, true); - } else if (data.action === InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA) { - await User.setZoomPresenza(user.idapp, user._id, false); - } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.REGISTRATION) { - const changed = await myclTelegram.setCmdToUsername( - rec, - data.username, - Cmd.VALIDATE_REGISTRATION, - true - ); - - if (changed) { - const req = tools.getReqByPar(user.idapp, username_action); - - nomeapp = tools.getNomeAppByIdApp(user.idapp); - // await User.setFriendsCmd(req, user.idapp, data.username, userDest.username, shared_consts.FRIENDSCMD.SETFRIEND, null, true); - - await User.setaportador_solidario(user.idapp, data.username, userDest.username); - - const msgOrig = printf( - getstr(userDest.lang, 'MSG_APORTADOR_DEST_CONFIRMED', nomeapp), - `${userDest.username}`, - tools.getHostByIdApp(user.idapp) - ); - const msgDest = printf( - getstr(user.lang, 'MSG_APORTADOR_CONFIRMED'), - `${user.username}`, - `${userDest.username}` - ); - - await local_sendMsgTelegram(user.idapp, data.username, msgOrig); - await local_sendMsgTelegram(user.idapp, data.userDest, msgDest); - // Invia questo msg anche all'Admin - await local_sendMsgTelegramToTheAdmin(user.idapp, msgDest, msg, data.userDest); - } - } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.REGISTRATION) { - if (userDest.username === user.aportador_solidario) { - const changed = await myclTelegram.setCmdToUsername( - rec, - data.username, - Cmd.VALIDATE_REGISTRATION, - false - ); - - if (changed) { - const nomeDest = tools.getNomeCognomeEUserNameByUser(userDest); - const nomestr = tools.getNomeCognomeEUserNameByUser(user); - - const msgOrig = printf(getstr(userDest.lang, 'MSG_APORTADOR_DEST_NOT_CONFIRMED', nomeDest)); - const msgDest = printf(getstr(user.lang, 'MSG_APORTADOR_NOT_CONFIRMED'), nomestr); - - await local_sendMsgTelegram(user.idapp, data.username, msgOrig); - await local_sendMsgTelegram(user.idapp, data.userDest, msgDest); - } - } - } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_GRUPPO) { - if (group) { - cmd = shared_consts.GROUPSCMD.SETGROUP; - const foundIfAlreadyGroup = await User.ifAlreadyInGroup( - user.idapp, - data.username, - group.groupname - ); - - if (!foundIfAlreadyGroup) { - // Aggiungilo nel Gruppo - await User.setGroupsCmd(user.idapp, data.username, group.groupname, cmd, 0, username_action); - } - } - } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_GRUPPO) { - if (group) { - cmd = shared_consts.GROUPSCMD.REFUSE_REQ_GROUP; - const foundIfAlreadyGroup = await User.ifAlreadyInGroup( - user.idapp, - data.username, - group.groupname - ); - - if (foundIfAlreadyGroup) { - // Rimuovilo nel Gruppo - await User.setGroupsCmd(user.idapp, data.username, group.groupname, cmd, 0, username_action); - } - } - } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_FIDO) { - if (circuit) { - // Abiglitagli il Fido - cmd = shared_consts.CIRCUITCMD.SETFIDO; - await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { - groupname: data.groupname, - }); - } - } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_CIRCUIT) { - console.log(' CLICK per Aggiungere ', data.username, 'nel circuito', circuit?.name); - if (circuit) { - // Aggiungilo nel Circuito - cmd = shared_consts.CIRCUITCMD.SET; - await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { - groupname: data.groupname, - }); - } - } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_CIRCUIT) { - if (circuit) { - cmd = shared_consts.CIRCUITCMD.REFUSE_REQ; - let foundIfAlreadyCircuit = false; - if (data.groupname) { - foundIfAlreadyCircuit = await MyGroup.ifCircuitAlreadyInGroup( - user.idapp, - data.groupname, - circuit.name - ); - } else { - foundIfAlreadyCircuit = await User.ifAlreadyInCircuit( - user.idapp, - data.username, - circuit.name - ); - } - - if (foundIfAlreadyCircuit) { - // Rimuovilo nel Circuito - await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { - groupname: data.groupname, - }); - } - } - } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_AMICIZIA) { - if (userDest) { - cmd = shared_consts.FRIENDSCMD.SETFRIEND; - const foundIfAlreadyFriend = await User.isMyFriend(user.idapp, data.username, data.userDest); - - if (!foundIfAlreadyFriend) { - // Aggiungilo nelle Amicizie - const req = tools.getReqByPar(user.idapp, username_action); - const ris = await User.setFriendsCmd(req, user.idapp, data.username, data.userDest, cmd); - } - } - } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_AMICIZIA) { - if (userDest) { - cmd = shared_consts.FRIENDSCMD.REMOVE_FROM_MYFRIENDS; - // Rimuovilo nelle Amicizie - const req = tools.getReqByPar(user.idapp, username_action); - const ris = await User.setFriendsCmd(req, user.idapp, data.username, data.userDest, cmd); - if (ris) { - const msgDest = printf( - getstr(user.lang, 'MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED'), - data.username - ); - - await local_sendMsgTelegram(user.idapp, data.userDest, msgDest); - } - } - } else if ( - data.action === - InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_HANDSHAKE - ) { - if (userDest) { - cmd = shared_consts.FRIENDSCMD.SETHANDSHAKE; - const foundIfAlreadyFriend = await User.isMyHandShake(user.idapp, data.userDest, data.username); - - if (!foundIfAlreadyFriend) { - // Aggiungilo nelle HandShake - const req = tools.getReqByPar(user.idapp, username_action); - const ris = await User.setFriendsCmd(req, user.idapp, data.userDest, data.username, cmd); - } - } - } - } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.ENTRA_RIS_ITALIA) { - } - } - - // CALLBACK DI RISPOSTA AL BOT - bot.answerCallbackQuery(callbackQuery.id, { text: testo_notifica_di_risposta }); - } catch (e) { - console.error('Error BOT callback_query', e); - } - - /* - let text; - - if (action === 'edit') { - text = 'Edited Text'; - } - - bot.editMessageText(text, opts); - */ - - // bot.answerCallbackQuery(callbackQuery.id, { url }); - }); - } - } catch (e) { - console.error('Error Telegram LOOP : ' + e.message); - } - } - }) - .catch((e) => { - arrTeleg = []; - console.error('Error internetAvailable:' + e); - }); -} - -module.exports = MyTelegramBot;