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:///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;