diff --git a/src/server/models/mygood.js b/src/server/models/mygood.js index 82387de..eb9e288 100755 --- a/src/server/models/mygood.js +++ b/src/server/models/mygood.js @@ -175,7 +175,7 @@ MyGoodSchema.statics.executeQueryTable = function(idapp, params) { return tools.executeQueryTable(this, idapp, params); }; -MyGoodSchema.statics.getMyGoodById = function(idapp, idGood) { +MyGoodSchema.statics.getMyRecById = function(idapp, idGood) { const MyGood = this; const query = [ @@ -480,7 +480,7 @@ MyGoodSchema.statics.getMyGoodById = function(idapp, idGood) { MyGoodSchema.statics.getCompleteRecord = function(idapp, id) { const MyGood = this; - return MyGood.getMyGoodById(idapp, id); + return MyGood.getMyRecById(idapp, id); }; diff --git a/src/server/models/myskill.js b/src/server/models/myskill.js index b62d106..00ca85f 100755 --- a/src/server/models/myskill.js +++ b/src/server/models/myskill.js @@ -177,7 +177,7 @@ MySkillSchema.statics.executeQueryTable = function(idapp, params) { return tools.executeQueryTable(this, idapp, params); }; -MySkillSchema.statics.getMySkillByIdkill = function(idapp, idSkill) { +MySkillSchema.statics.getMyRecById = function(idapp, idSkill) { const MySkill = this; const query = [ @@ -479,7 +479,7 @@ MySkillSchema.statics.getMySkillByIdkill = function(idapp, idSkill) { MySkillSchema.statics.getCompleteRecord = function(idapp, id) { const MySkill = this; - return MySkill.getMySkillByIdkill(idapp, id); + return MySkill.getMyRecById(idapp, id); }; diff --git a/src/server/models/user.js b/src/server/models/user.js index 4dba0a0..7de9b40 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -1100,13 +1100,6 @@ UserSchema.statics.getLastUser = function(idapp) { }).sort({index: -1}); }; -UserSchema.statics.findByIndOrder = function(idapp, ind_order) { - const User = this; - - return User.getRecByIndOrder(idapp, ind_order); - -}; - UserSchema.statics.findByIndex = function(idapp, index) { const User = this; @@ -1606,21 +1599,26 @@ UserSchema.statics.setFriendsCmd = async function(idapp, usernameOrig, usernameD return ris; }; -UserSchema.statics.setGroupsCmd = async function( - idapp, usernameOrig, groupnameDest, cmd, value) { +UserSchema.statics.ifAlreadyInGroup = async function(idapp, usernameOrig, groupnameDest) { + + // Controllo se è stato già inserito + return User.findOne({ + idapp, + username: usernameOrig, + 'profile.mygroups': { + $elemMatch: {groupname: {$eq: groupnameDest}}, + }, + }).lean(); + +}; + +UserSchema.statics.setGroupsCmd = async function(idapp, usernameOrig, groupnameDest, cmd, value) { let ris = null; let update = {}; try { if (cmd === shared_consts.GROUPSCMD.SETGROUP) { - // Controllo se è stato già inserito - const foundIfAlreadyGroup = await User.findOne({ - idapp, - username: usernameOrig, - 'profile.mygroups': { - $elemMatch: {groupname: {$eq: groupnameDest}}, - }, - }); + const foundIfAlreadyGroup = await this.ifAlreadyInGroup(idapp, usernameOrig, groupnameDest); if (!foundIfAlreadyGroup) { update = { @@ -1640,12 +1638,13 @@ UserSchema.statics.setGroupsCmd = async function( } else { ris = false; } - if (ris) { + // Invia una notifica alla persona e agli Admin + tools.sendNotificationByGroupname(idapp, usernameOrig, groupnameDest, cmd, true); ris = await MyGroup.getInfoGroupByGroupname(idapp, groupnameDest); } } else if (cmd === shared_consts.GROUPSCMD.REQGROUP) { - // Aggiungo la richiesta di Amicizia a me + // Aggiungo la richiesta di Gruppo a me const foundIfAlreadyAskGroup = await MyGroup.findOne({ idapp, groupname: groupnameDest, @@ -1669,7 +1668,7 @@ UserSchema.statics.setGroupsCmd = async function( } if (ris) { // Invia una notifica alla persona - tools.sendNotificationByGroupname(idapp, groupnameDest, cmd, true); + tools.sendNotificationByGroupname(idapp, usernameOrig, groupnameDest, cmd, true); } } else { if (foundIfAlreadyAskGroup) { @@ -1704,7 +1703,7 @@ UserSchema.statics.setGroupsCmd = async function( }, }); //++Todo: Send Notification to Admin and Group's manager - tools.sendNotificationByGroupname(idapp, groupnameDest, cmd, true); + tools.sendNotificationByGroupname(idapp, usernameOrig, groupnameDest, cmd, true); } } catch (e) { @@ -1792,7 +1791,7 @@ UserSchema.statics.getInfoFriendByUsername = async function(idapp, username) { idapp, username, $or: [{deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}], - }, whatToShow).then((rec) => !!rec ? rec._doc : null); + }, whatToShow).lean().then((rec) => !!rec ? rec : null); }; @@ -1805,7 +1804,7 @@ UserSchema.statics.getInfoAskFriendByUsername = async function( idapp, username, $or: [{deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}], - }, whatToShow).then((rec) => !!rec ? rec._doc : null); + }, whatToShow).lean().then((rec) => !!rec ? rec : null); }; @@ -1910,8 +1909,8 @@ UserSchema.statics.UserByIdTelegram = async function(idapp, teleg_id) { return User.findOne({ idapp, 'profile.teleg_id': teleg_id, $or: [{deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}], - }).then((rec) => { - return (!!rec) ? rec._doc : null; + }).lean().then((rec) => { + return (!!rec) ? rec : null; }).catch((e) => { console.error('UserExistByIdTelegram', e); }); @@ -1924,7 +1923,7 @@ UserSchema.statics.UsersByIdTelegram = async function(idapp, teleg_id) { idapp, 'profile.teleg_id': teleg_id, $or: [{deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}], }).lean().then((rec) => { - return (!!rec) ? rec._doc : null; + return (!!rec) ? rec : null; }).catch((e) => { console.error('UserExistByIdTelegram', e); }); @@ -1957,6 +1956,20 @@ UserSchema.statics.TelegIdByUsername = async function(idapp, username) { console.error('TelegIdByUsername', e); }); }; + +UserSchema.statics.TelegIdById = async function(idapp, id) { + const User = this; + + return User.findOne({ + idapp, + _id: id, + $or: [{deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}], + }, {'profile.teleg_id': 1}).lean().then((rec) => { + return (!!rec) ? rec.profile.teleg_id : null; + }).catch((e) => { + console.error('TelegIdByUsername', e); + }); +}; UserSchema.statics.notAsk_VerifByUsername = async function(idapp, username) { return User.findOne({ @@ -2039,13 +2052,6 @@ UserSchema.statics.setUsernameTelegram = async function( }; -UserSchema.statics.getLangByIndOrder = async function(idapp, ind_order) { - const User = this; - - const rec = await User.getSmallRecByIndOrder(idapp, ind_order); - return (!!rec) ? rec.lang : ''; - -}; UserSchema.statics.SetLang = async function(idapp, id, lang) { const User = this; @@ -2122,6 +2128,19 @@ UserSchema.statics.getIdByUsername = async function(idapp, username) { }); }; +UserSchema.statics.getRecLangAndIdByUsername = async function(idapp, username) { + const User = this; + + return User.findOne({ + idapp, username, + $or: [{deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}], + }, {lang: 1, _id: 1}).then((rec) => { + return (!!rec) ? rec : null; + }).catch((e) => { + console.error('getRecLangAndIdByUsername', e); + }); +}; + UserSchema.statics.getNameSurnameById = async function(idapp, userId) { const User = this; @@ -2136,101 +2155,6 @@ UserSchema.statics.getNameSurnameById = async function(idapp, userId) { }); }; -UserSchema.statics.getSmallRecByIndOrder = async function(idapp, ind_order) { - - try { - const rec = {}; - /* - const rec = await ListaIngresso.getarray(idapp, - { - idapp, - ind_order, - $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], - }, - { - idapp: 1, - index: 1, - ind_order: 1, - old_order: 1, - username: 1, - name: 1, - lang: 1, - surname: 1, - 'profile.teleg_id': 1, - }); - - if (!!rec) - return rec[0]; - - */ - - return null; - - } catch (e) { - console.error('getSmallRecByIndOrder', e); - } - -}; - -UserSchema.statics.NuovoSistema = function(idapp) { - const User = this; - - try { - return User.findOne({idapp, old_order: {$exists: true}}).then((ris) => { - return !!ris; - }); - } catch (e) { - console.error('NuovoSistema', e.message); - } - -}; - -UserSchema.statics.getRecByIndOrder = async function(idapp, ind_order) { - const User = this; - - try { - /* - let filters = { - idapp: 1, - index: 1, - ind_order: 1, - old_order: 1, - username: 1, - email: 1, - name: 1, - lang: 1, - surname: 1, - 'profile.teleg_id': 1, - 'profile.email_paypal': 1, - 'profile.payeer_id': 1, - 'profile.advcash_id': 1, - 'profile.revolut': 1, - 'profile.link_payment': 1, - 'profile.note_payment': 1, - 'profile.paymenttypes': 1, - }; - - const rec = await ListaIngresso.getarray(idapp, - { - idapp, - ind_order, - }, - filters); - - if (!!rec) - return rec[0]; - - - */ - return null; - - } catch (e) { - console.error('getRecByIndOrder', e); - } - -}; UserSchema.statics.getusersManagers = async function(idapp) { const User = this; @@ -2943,13 +2867,6 @@ if (tools.INITDB_FIRSTIME) { // UserSchema.index({ surname: 1 }); } -UserSchema.statics.getUsernameByIndOrder = async function(idapp, ind_order) { - - const myrec = await User.getSmallRecByIndOrder(idapp, ind_order); - return (!!myrec) ? myrec.username : ''; - -}; - UserSchema.statics.getUsernameByIndex = async function(idapp, index) { const myrec = await User.findOne({ @@ -3221,7 +3138,7 @@ UserSchema.statics.addExtraInfo = async function(idapp, recUser) { {deleted: {$exists: true, $eq: false}}], }, {username: 1}).lean(); - recUser.profile.asked_friends = listSentMyRequestFriends + recUser._doc.profile.asked_friends = listSentMyRequestFriends ? listSentMyRequestFriends : []; @@ -3233,9 +3150,9 @@ UserSchema.statics.addExtraInfo = async function(idapp, recUser) { $or: [ {deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}], - }, MyGroup.getWhatToShow_Unknown()); + }, MyGroup.getWhatToShow_Unknown()).lean(); - recUser.profile.asked_groups = listSentMyRequestGroups + recUser._doc.profile.asked_groups = listSentMyRequestGroups ? listSentMyRequestGroups : []; @@ -3247,12 +3164,14 @@ UserSchema.statics.addExtraInfo = async function(idapp, recUser) { $or: [ {deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}], - }); + }).lean(); - recUser.profile.manage_mygroups = listManageGroups + recUser._doc.profile.manage_mygroups = listManageGroups ? listManageGroups : []; + return recUser._doc; + } catch (e) { console.error('Err', e); } diff --git a/src/server/router/dashboard_router.js b/src/server/router/dashboard_router.js index 22ddad5..f997b31 100755 --- a/src/server/router/dashboard_router.js +++ b/src/server/router/dashboard_router.js @@ -82,58 +82,6 @@ router.post('/downline', authenticate, async (req, res) => { }); - -router.post('/msgnave', authenticate, async (req, res) => { - const idapp = req.body.idapp; - let mydata = req.body; - - try { - - let ris = null; - if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_SINGOLO) { - let mymsg = ''; - if (!!mydata.username_mitt) { - mymsg = '[' + tools.getres__('MSG_SEND_FROM', res) + ' ' + mydata.username_mitt + ' a ' + mydata.username + ']:' + tools.ACAPO; - } - mymsg += mydata.msgpar1; - // ris = await telegrambot.sendMsgTelegram(idapp, mydata.username, mymsg, true, mydata.username_mitt); // Anche a STAFF - ris = await telegrambot.sendMsgTelegram(idapp, mydata.username, mymsg, true); // Anche a STAFF - } else - ris = await telegrambot.sendMsgTelegramToNave(idapp, mydata, res); - - if (ris) - res.send({ code: server_constants.RIS_CODE_OK, ris }); - else - res.send({ code: server_constants.RIS_CODE_ERR, ris: null }); - - - } catch (e) { - res.status(400).send(e); - } - -}); - -router.post('/msgflotta', authenticate, async (req, res) => { - const idapp = req.body.idapp; - let mydata = req.body; - - try { - - let ris = null; - ris = await telegrambot.sendMsgTelegramToNave(idapp, mydata, res); - - if (ris) - res.send({ code: server_constants.RIS_CODE_OK, ris }); - else - res.send({ code: server_constants.RIS_CODE_ERR, ris: null }); - - - } catch (e) { - res.status(400).send(e); - } - -}); - router.post('/getmsg_templates', authenticate, async (req, res) => { const idapp = req.body.idapp; diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 9e932ab..0caa83e 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -334,6 +334,10 @@ router.post('/settable', authenticate, async (req, res) => { } } + if (shared_consts.TABLES_UPDATE_LASTMODIFIED.includes(params.table)) { + mytablerec.date_updated = new Date(); + } + return mytablerec.save(). then(async (rec) => { @@ -1160,7 +1164,7 @@ function load(req, res, version) { myuser = arrdata[26]; if (myuser) { myuser.password = ''; - myuser._doc.calcstat = arrdata[13]; + myuser.calcstat = arrdata[13]; } } catch (e) {} } diff --git a/src/server/router/mygoods_router.js b/src/server/router/mygoods_router.js index 00e5554..631113e 100755 --- a/src/server/router/mygoods_router.js +++ b/src/server/router/mygoods_router.js @@ -23,7 +23,7 @@ router.post('/page', authenticate, function(req, res, next) { let idGood = req.body.idGood; let idapp = req.body.idapp; - return MyGood.getMyGoodByIdkill(idapp, idGood). + return MyGood.getMyRecById(idapp, idGood). then((ris) => { if (ris) { diff --git a/src/server/router/myskills_router.js b/src/server/router/myskills_router.js index 8315607..b92cb62 100755 --- a/src/server/router/myskills_router.js +++ b/src/server/router/myskills_router.js @@ -23,7 +23,7 @@ router.post('/page', authenticate, function(req, res, next) { let idSkill = req.body.idSkill; let idapp = req.body.idapp; - return MySkill.getMySkillByIdkill(idapp, idSkill). + return MySkill.getMyRecById(idapp, idSkill). then((ris) => { if (ris) { diff --git a/src/server/router/push_router.js b/src/server/router/push_router.js index f270a90..bc37cfc 100755 --- a/src/server/router/push_router.js +++ b/src/server/router/push_router.js @@ -1,18 +1,20 @@ const express = require('express'); const router = express.Router(); -const mongoose = require('mongoose').set('debug', false) +const mongoose = require('mongoose').set('debug', false); const Subscription = mongoose.model('subscribers'); // const q = require('q'); const webpush = require('web-push'); const tools = require('../tools/general'); -const { authenticate } = require('../middleware/authenticate'); +const {authenticate} = require('../middleware/authenticate'); const shared_consts = require('../tools/shared_nodejs'); const server_constants = require('../tools/server_constants'); -const { User } = require('../models/user'); +const {User} = require('../models/user'); + +const globalTables = require('../tools/globalTables'); router.post('/', (req, res) => { const payload = { @@ -23,14 +25,14 @@ router.post('/', (req, res) => { icon: req.body.icon, image: req.body.image, badge: req.body.badge, - tag: req.body.tag + tag: req.body.tag, }; Subscription.find({}, (err, subscriptions) => { if (err) { console.error(`Error occurred while getting subscriptions`); res.status(500).json({ - error: 'Technical error occurred' + error: 'Technical error occurred', }); } else { @@ -40,8 +42,8 @@ router.post('/', (req, res) => { endpoint: subscription.endpoint, keys: { p256dh: subscription.keys.p256dh, - auth: subscription.keys.auth - } + auth: subscription.keys.auth, + }, }; const pushPayload = JSON.stringify(payload); @@ -52,23 +54,23 @@ router.post('/', (req, res) => { publicKey: process.env.PUBLIC_VAPI_KEY, }, TTL: payload.ttl, - headers: {} + headers: {}, }; webpush.sendNotification( - pushSubscription, - pushPayload, - pushOptions + pushSubscription, + pushPayload, + pushOptions, ).then((value) => { resolve({ status: true, endpoint: subscription.endpoint, - data: value + data: value, }); }).catch((err) => { reject({ status: false, endpoint: subscription.endpoint, - data: err + data: err, }); }); }); @@ -77,84 +79,31 @@ router.post('/', (req, res) => { console.info(pushResults); }); res.json({ - data: 'Push triggered' + data: 'Push triggered', }); } }); }); -async function SendMsgToAll(idapp, params) { - const arrusers = await User.find({ idapp }, - { - username: 1, - name: 1, - surname: 1, - } - ); - let msgsent = 0; - - for (const user of arrusers) { - await SendMsgTo(idapp, user.username, params); - msgsent++; - } - - return msgsent; -} - -async function SendMsgToParam(idapp, params) { - const arrusers = await User.find({ idapp }, - { - username: 1, - name: 1, - surname: 1, - 'profile.socio': 1, - 'profile.socioresidente': 1, - } - ); - - let msgsent = 0; - - for (const user of arrusers) { - let invia = false; - if (params.typemsg === shared_consts.TypeMsg.SEND_TO_SOCI) { - invia = user.profile.socio; - }else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_SOCIO_RESIDENTE) { - invia = user.profile.socioresidente; - }else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_CONSIGLIO) { - invia = user.profile.consiglio; - }else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_NON_SOCI) { - invia = !user.profile.socio; - }else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_PAOLO) { - invia = user.username === 'paoloar77'; - } else { - invia = true; - } - if (invia) { - await SendMsgTo(idapp, user.username, params); - msgsent++; - } - } - - return msgsent; -} async function SendMsgTo(idapp, username, params) { - return User.find({ idapp, username }).then((arrusers) => { + return User.find({idapp, username}).then((arrusers) => { if (arrusers !== null) { for (const user of arrusers) { - tools.sendNotificationToUser(user._id, params.title, params.content, params.openUrl, params.openUrl2, params.tag, params.actions) - .then(ris => { - if (ris) { + tools.sendNotificationToUser(user._id, params.title, params.content, + params.openUrl, params.openUrl2, params.tag, params.actions). + then(ris => { + if (ris) { - } else { - // already sent the error on calling sendNotificationToUser - } - }) - .catch(e => { - console.error(e.message); - }) + } else { + // already sent the error on calling sendNotificationToUser + } + }). + catch(e => { + console.error(e.message); + }); } } }); @@ -169,28 +118,33 @@ router.post('/send', authenticate, async (req, res) => { let nummsg = 0; - if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTutor(req.user.perm))) { + if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && + !User.isTutor(req.user.perm))) { // If without permissions, exit - return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + return res.status(404). + send({code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: ''}); } try { - if (params.typemsg === shared_consts.TypeMsg.SEND_TO_ALL) { - nummsg = await SendMsgToAll(idapp, params); - } else { - nummsg = await SendMsgToParam(idapp, params); - } + params.typesend = shared_consts.TypeSend.PUSH_NOTIFICATION; + params.sendreally = true; + const ris = await globalTables.SendMsgToParam(idapp, params); - return res.send({ code: server_constants.RIS_CODE_OK, msg: nummsg + ' Msg Inviati !', nummsg }); - }catch (e) { - return res.send({ code: server_constants.RIS_CODE_ERR, msg: nummsg + ' Msg Inviati !' }); + return res.send({ + code: server_constants.RIS_CODE_OK, + msg: ris.nummsgsent + ' Msg Inviati su ' + ris.numrec + ' !', + nummsg: ris.nummsgsent, + }); + } catch (e) { + return res.send( + {code: server_constants.RIS_CODE_ERR, msg: nummsg + ' Msg Inviati !'}); } }); router.get('/', (req, res) => { res.json({ - data: 'Invalid Request Bad' + data: 'Invalid Request Bad', }); }); module.exports = router; diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index c0a6db0..ce06cde 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -250,13 +250,10 @@ router.post('/', async (req, res) => { await User.setaportador_solidario(user.idapp, user.username, user.aportador_solidario); - const myuser = await User.findOne({_id: trovarec._id}); + const myuser = await User.findOne({_id: trovarec._id}).lean(); if (myuser) { - await telegrambot.askConfirmationUserRegistration(myuser.idapp, - shared_consts.CallFunz.REGISTRATION, myuser, - myuser.profile.username_telegram, myuser.profile.firstname_telegram, - myuser.profile.lastname_telegram); + await telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser); const token = await myuser.generateAuthToken(req); res.header('x-auth', token).send(myuser); @@ -1088,4 +1085,24 @@ router.post('/dbop', authenticate, async (req, res) => { }); +router.post('/mgt', authenticate, async (req, res) => { + + const mydata = req.body.mydata; + idapp = req.body.idapp; + locale = req.body.locale; + + try { + const {nummsgsent, numrec } = await telegrambot.sendMsgFromSiteToBotTelegram(idapp, req.user, mydata); + + return res.send({numrec, nummsgsent }); + + } catch (e) { + res.status(400).send(); + res.send({code: server_constants.RIS_CODE_ERR, msg: e}); + + console.log(e.message); + } + +}); + module.exports = router; diff --git a/src/server/server.js b/src/server/server.js index 0a3844b..8072b11 100755 --- a/src/server/server.js +++ b/src/server/server.js @@ -35,7 +35,6 @@ const i18n = require('i18n'); // OBTAIN // https://www.psclistens.com/insight/blog/enabling-a-nodejs-ssl-webserver-using-let-s-encrypt-pem-certificates/ - if ((process.env.NODE_ENV === 'production') || (process.env.NODE_ENV === 'test')) { var privateKey = fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8'); @@ -45,8 +44,8 @@ if ((process.env.NODE_ENV === 'production') || cert: certificate, ca: [ fs.readFileSync(process.env.PATH_SSL_ROOT_PEM, 'utf8'), - fs.readFileSync(process.env.PATH_SSL_CHAIN_PEM, 'utf8') - ] + fs.readFileSync(process.env.PATH_SSL_CHAIN_PEM, 'utf8'), + ], }; var https = require('https'); } else { @@ -466,17 +465,17 @@ async function estraiImmagini(table) { try { // console.log('checkdir', folderprof); if (!fs.existsSync(folderprof)) { - console.log('*** Creadir', folderprof) + console.log('*** Creadir', folderprof); fs.mkdirSync(folderprof); } folderprof = dir + 'profile/' + myuser.username + '/' + table; // console.log('checkdir', folderprof); if (!fs.existsSync(folderprof)) { - console.log('creadir', folderprof) + console.log('creadir', folderprof); fs.mkdirSync(folderprof); } - }catch (e) { + } catch (e) { } } @@ -492,7 +491,7 @@ async function estraiImmagini(table) { // console.log('file', file); // console.log('filefrom', filefrom); - if (!tools.isFileExists(file)){ + if (!tools.isFileExists(file)) { // non esiste console.log('non esiste', file); console.log(' filefrom', filefrom); @@ -512,7 +511,7 @@ async function estraiImmagini(table) { } } console.log('FINE - estraiImmagini', table); - }catch (e) { + } catch (e) { console.error('e', e); } } @@ -524,8 +523,6 @@ async function estraiTutteLeImmagini() { await estraiImmagini('mybachecas'); } - - async function faitest() { // console.log('Fai Test:') @@ -533,8 +530,8 @@ async function faitest() { // const $vers = tools.getVersionint('1.92.45'); - if (false){ - const prova = tools.getConfSiteOptionEnabledByIdApp('13', shared_consts.ConfSite.Notif_Reg_Push_Admin) + if (false) { + const prova = tools.getConfSiteOptionEnabledByIdApp('13', shared_consts.ConfSite.Notif_Reg_Push_Admin); console.log('prova', prova); } @@ -557,8 +554,7 @@ async function faitest() { const langdest = 'it'; - telegrambot.askConfirmationUserRegistration(myuser.idapp, - shared_consts.CallFunz.REGISTRATION, myuser); + telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser); } diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 3f15377..b89192e 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -11,6 +11,7 @@ const appTelegramDest = [tools.FREEPLANET, tools.FREEPLANET]; const printf = require('util').format; const {User} = require('../models/user'); +const {MyGroup} = require('../models/mygroup'); const {CalZoom} = require('../models/calzoom'); const {MyBot} = require('../models/bot'); const shared_consts = require('../tools/shared_nodejs'); @@ -20,6 +21,8 @@ const server_constants = require('../tools/server_constants'); // const {ListaIngresso} = require('../models/listaingresso'); const {MsgTemplate} = require('../models/msg_template'); +const globalTables = require('../tools/globalTables'); + const emoji = require('node-emoji'); const i18n = require('i18n'); @@ -129,6 +132,8 @@ MsgBot = { 'grazie', 'grazie mille', 'graziee', + 'grazie ❤', + 'grazie️❤', 'grazie 😘', 'grazie😘'], PRINCIPE_AZZURRO: ['principe azzurro'], @@ -432,6 +437,7 @@ const Status = { const Cmd = { VALIDATE_REGISTRATION: 1, + RICHIESTA_GRUPPO: 2, }; const Destin = { @@ -494,10 +500,12 @@ const txt = { 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: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione: %s', + MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', + MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente (da %s)!', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato correttamente 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 + @@ -550,9 +558,11 @@ const txt_es = { 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: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione: %s', + MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', + MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente!', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato 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 + @@ -604,9 +614,11 @@ const txt_fr = { 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: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione: %s', + MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', + MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente!', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato 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 + @@ -656,9 +668,11 @@ const txt_si = { 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: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione: %s', + MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', + MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente!', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato 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 + @@ -707,9 +721,11 @@ const txt_en = { 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: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione: %s', + MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', + MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente!', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato 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 + @@ -761,10 +777,12 @@ const txt_pt = { 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: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione: %s', + MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', + MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_APORTADOR_CONFIRMED: '✅ %s è stato Abilitato correttamente!' + 'Vai sulla App oppure clicca qui per entrare 👉🏻 %s', MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Abilitato 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 + @@ -779,7 +797,7 @@ const TelegramBot = require('node-telegram-bot-api'); const ADMIN_IDTELEGRAM_TEST = 5022837609; //Perseo -module.exports = { +const MyTelegramBot = { ADMIN_IDTELEGRAM_SERVER: '12429864', //Paolo ADMIN_USER_SERVER: 'paoloar77', @@ -790,6 +808,22 @@ module.exports = { ISCRIZIONE_CONACREIS: 2, }, + local_sendMsgTelegramByIdTelegram: async function(idapp, idtelegram, text, + message_id, chat_id, ripr_menuPrec, + MyForm = null) { + + if (!idtelegram) + return; + + const cl = getclTelegByidapp(idapp); + if (cl && idtelegram) { + + return cl.sendMsg(idtelegram, text, null, MyForm, message_id, + chat_id, ripr_menuPrec); + } + + }, + deleteRecInMemByUsername: function(idapp, username_bo) { const cl = getclTelegByidapp(idapp); @@ -870,40 +904,11 @@ module.exports = { let rismsg = null; if (text) { - /*if (!!mylocalsconf.user.aportador_solidario) { - addtext = '[Inviato a ' + NameFrom + ']:' + '\n'; - rismsg = await this.sendMsgTelegram(mylocalsconf.idapp, userdest, text); - }*/ await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text, false, null, userdest); } - /* - // Invia richiesta allo Sponsor - const domanda = printf(getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM'), - `${mylocalsconf.user.name + ' ' + mylocalsconf.user.surname + '(' + mylocalsconf.user.username + ')' + 'email: ' + mylocalsconf.user.email }`); - const msgyes = printf(getstr(langdest, 'MSG_APORTADOR_CONFIRMED'), - `${mylocalsconf.user.name + ' ' + mylocalsconf.user.surname}`); - const msgNo = printf(getstr(langdest, 'MSG_APORTADOR_NOT_CONFIRMED'), - `${mylocalsconf.user.name + ' ' + mylocalsconf.user.surname}`); - - const msgDestyes = printf( - getstr(langdest, 'MSG_APORTADOR_DEST_CONFIRMED'), - `${mylocalsconf.user.name + ' ' + mylocalsconf.user.surname}`); - const msgDestNo = printf( - getstr(langdest, 'MSG_APORTADOR_DEST_NOT_CONFIRMED'), - `${mylocalsconf.user.name + ' ' + mylocalsconf.user.surname}`); - - const cl = getclTelegByidapp(mylocalsconf.idapp); - if (cl) { - await cl.createIfNotExist(rismsg); - await cl.menumsgDomanda(rismsg, Cmd.VALIDATE_REGISTRATION, - Destin.DOMANDA, userdest, '', domanda, msgyes, msgNo, msgDestyes, - msgDestNo, mylocalsconf.user.username); - } - - */ }, notifyIscrizioneToTelegram: async function(phase, mylocalsconf) { @@ -917,21 +922,21 @@ module.exports = { await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text); }, - askConfirmationUserRegistration: async function( - idapp, myfunc, myuser, usernametelegram = '', name_telegram = '', - surname_telegram = '') { + askConfirmationUser: async function(idapp, myfunc, myuser, userDest = '', {groupname, groupid}) { const cl = getclTelegByidapp(idapp); try { - const userDest = myuser.aportador_solidario; const langdest = myuser.lang; let keyb = null; let domanda = ''; + const struserinfomsg = tools.getUserInfoMsg(idapp, myuser); + if (myfunc === shared_consts.CallFunz.REGISTRATION) { + userDest = myuser.aportador_solidario; const notask_verif = await User.notAsk_VerifByUsername(idapp, userDest); if (notask_verif) { @@ -939,46 +944,43 @@ module.exports = { setVerifiedReg(myuser.idapp, myuser.lang, myuser.username, userDest); } else { - const name = myuser.username + - (myuser.name ? `(${myuser.name} + ' ' + ${myuser.surname})` : ''); - const linkuserprof = tools.getHostByIdApp(idapp) + '/my/' + - myuser.username; - domanda = printf(getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM'), - `
Username: ${name}
Profilo su APP: ${linkuserprof}
Email: ` + - myuser.email); - - if (usernametelegram) { - domanda += '
Profilo su Telegram [' + name_telegram + ' ' + - surname_telegram + ']:
' + 'https://t.me/' + - usernametelegram; - } + domanda = getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM') + '
' + struserinfomsg; keyb = cl.getInlineKeyboard(myuser.lang, [ { text: '✅ Abilita ' + myuser.username, - callback_data: InlineConferma.RISPOSTA_SI + - shared_consts.CallFunz.REGISTRATION + tools.SEP + - myuser.username + tools.SEP + userDest, + callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest, }, { text: '🚫 Rifiuta ' + myuser.username, - callback_data: InlineConferma.RISPOSTA_NO + - shared_consts.CallFunz.REGISTRATION + tools.SEP + - myuser.username + tools.SEP + userDest, + callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest, }, ]); } + } else if (myfunc === shared_consts.CallFunz.RICHIESTA_GRUPPO) { + + domanda = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), groupname) + '
' + 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 , + }, + ]); } // Invia Msg if (domanda) { const teleg_id = await User.TelegIdByUsername(idapp, userDest); - await local_sendMsgTelegramByIdTelegram(idapp, teleg_id, domanda, - undefined, undefined, true, keyb); + await this.local_sendMsgTelegramByIdTelegram(idapp, teleg_id, domanda, undefined, undefined, true, keyb); } } catch (e) { - console.error('Error askConfirmationUserRegistration', e); + console.error('Error askConfirmationUser', e); } }, @@ -1059,7 +1061,7 @@ module.exports = { const cl = getclTelegByidapp(user.idapp); if (cl) { - msg = cl.convertSpecialTags(rec.user, msg); + msg = tools.convertSpecialTags(rec.user, msg); } if (!!mydata.flotta) { @@ -1094,209 +1096,6 @@ module.exports = { return {body: msg, title}; }, - sendMsgTelegramToNave: async function(idapp, mydata, res) { - let nummsgtosend = 0; - let nummsgsent = 0; - let strout = ''; - let flotta = mydata.flotta; - - const sendemail = require('../sendemail'); - - try { - let arrnavi = null; - let strflotta = ''; - if (flotta) { - strflotta = Flotta.getStrFlotta(flotta); - arrnavi = await Nave.getusersByFlotta(idapp, flotta.riga, - flotta.col_prima, flotta.col_ultima); - - if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_A_SOGNATORE) { - arrnavi = await User.find({idapp, username: flotta.sognatore}); - } - } else { - arrnavi = await Nave.getusersByNave(idapp, mydata.navemediatore); - } - - // console.log('usersmanagers', usersmanagers); - - let mymsg = ''; - let mymsgprimo = ''; - - tipomsgorig = mydata.tipomsg; - - if (arrnavi) { - if (!flotta) - tools.writeManagersLog('sendMsgTelegramToNave', - mydata.navemediatore.riga + '.' + mydata.navemediatore.col); - let index = 1; - - if (mydata.inviareale) { - let mystrmsg = tools.getStrMsgByTipoMsg(tipomsgorig); - if (!!mystrmsg) { - tools.writeFlottaLog(idapp, mystrmsg, flotta.riga, - flotta.col_prima); - } - } - - for (const nave of arrnavi) { - - mydata.tipomsg = tipomsgorig; - - let user = null; - - if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_A_SOGNATORE) { - user = nave; - } else { - user = await User.findByIndOrder(idapp, nave.ind_order); - - if (mydata.tipomsg === - tools.TipoMsg.SEND_MSG_SOLLECITO_DONATORI_NO_DONO) { - // Solo a quelli che non hanno fatto il dono - if (nave.made_gift) - user = null; - } - - if ((nave.num_tess % 2) === 0) { - // MEDIATORE ! - // Se l'ultimo Donatore è un Mediatore, allora NON GLI MANDO IL MESSAGGIO ! - if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_EFFETTUA_IL_DONO) { - user = null; - } - if (mydata.tipomsg === - tools.TipoMsg.SEND_MSG_SOLLECITO_DONATORI_NO_DONO) { - user = null; - } - } else { - // DONATORE - - if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_A_MEDIATORI) { - user = null; // Se sto mandando msg a Mediatore, allora questo no! - } - } - } - - //mydata.tipomsg = tools.TipoMsg.SEND_MSG_A_MEDIATORI; - - if (!!user) { - const lang = user.lang; - const idteleg = user.profile.teleg_id; - mydata.nave = nave; - const rismsg = await this.getMsgByTipoMsg(mydata, lang, user, - false); - - mymsg = rismsg.body; - mytitle = rismsg.title; - - if (mymsgprimo === '') { - if (lang === 'it') - mymsgprimo = mymsg; - } - - if (!!idteleg) { - strout += '\n (' + index + ') ' + user.username + ' (' + - user.name + ' ' + user.surname + ':'; - if (mydata.inviareale) { - await this.sendMsgTelegramByIdTelegram(idapp, idteleg, mymsg, - undefined, undefined, true); - await tools.snooze(100); - strout += ' -> (MSG OK)'; - - if (mydata.inviaemail && !!user.email) { - // user.email = 'paolo.arena77@gmail.com'; - await sendemail.sendEmail_ByText(user.lang, user.email, user, - idapp, { - emailbody: mymsg, - emailtitle: mytitle, - }); - strout += ' -> (EMAIL OK)'; - } - - nummsgsent++; - } else { - strout += ' (Ok)'; - nummsgtosend++; - } - } - } - index++; - } - } - - if (!mydata.inviareale) { - await this.sendMsgTelegram(idapp, res.req.user.username, - 'TEST INVIO MESSAGGIO:\n' + mymsgprimo + - '\n\n(Messaggi da Inviare: ' + nummsgtosend + ')'); - } - - if ((nummsgsent > 1) && (mydata.inviareale)) { - try { - let msg = ''; - if (!!flotta) { - if (!!mydata.tipomsg) { - msg = 'Flotta ' + strflotta + '): ' + - tools.getStrMsgByTipoMsg(mydata.tipomsg) + '\n' + mymsg; - } else { - msg = 'Inviato messaggio a tutta la FLOTTA DA ' + flotta.riga + - '.' + flotta.col_prima + ' A ' + flotta.riga + '.' + - flotta.col_ultima + ' \n' + mymsg; - } - } else { - msg = 'Inviato messaggio a tutti i Donatori della Nave ' + - mydata.navemediatore.riga + '.' + mydata.navemediatore.col + - '\n' + mymsg; - } - await this.sendMsgTelegramToTheManagers(idapp, msg); - } catch (e) { - - } - } - - /* - if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { - - - const usersognatore = await Nave.getSognatoreByRigaColMediatore(idapp, mydata.navemediatore); - - console.log('Sognatore: ', usersognatore.username); - - if (!!usersognatore) { - const lang = usersognatore.lang; - const idteleg = usersognatore.profile.teleg_id; - const mymsg = this.getMsgByTipoMsg(mydata, lang, usersognatore, true); - - // Invia Msg al Sognatore ! - if (mydata.inviareale) { - await this.sendMsgTelegramByIdTelegram(idapp, idteleg, mymsg, undefined, undefined, true); - await tools.snooze(300); - nummsgsent++; - strout += '\n' + usersognatore.name + ' ' + usersognatore.surname + ':'; - strout += ' -> MSG INVIATO'; - } else { - strout += ' (Pronto da Inviare)'; - } - } - - } - */ - - if (nummsgsent > 0) { - if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { - const fields_to_update = { - sent_msg_howto_make_gift: true, - }; - await Nave.findOneAndUpdate({_id: mydata.navemediatore.id}, - {$set: fields_to_update}, {new: false}); - } - } - - return {nummsgsent, strout}; - } catch (e) { - console.error(e.message); - strout = 'Error: ' + e.message + '\n' + strout; - return {nummsgsent, strout}; - } - }, - sendMsgTelegramToTheAdmin: async function(idapp, text, senzaintestazione) { const usersmanagers = await User.getusersManagers(idapp); @@ -1389,6 +1188,56 @@ module.exports = { }, + sendMsgFromSite: async function(idapp, user, params) { + + try { + let ris = { + numrec: 0, + nummsgsent: 0, + }; + + let invia = false; + + 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; + } + + if (tipomsgtempl > 0) { + const rismsg = await MsgTemplate.getMsgByLang(idapp, 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 sendMsgTelegramToTheAdmin(idapp, text, msg) { @@ -1491,24 +1340,6 @@ async function local_sendMsgTelegram(idapp, username, text) { } -async function local_sendMsgTelegramByIdTelegram(idapp, idtelegram, text, - message_id, chat_id, ripr_menuPrec, - MyForm = null) { - - console.log('sendMsgTelegramByIdTelegram', text); - - if (!idtelegram) - return; - - const cl = getclTelegByidapp(idapp); - if (cl && idtelegram) { - - return await cl.sendMsg(idtelegram, text, null, MyForm, message_id, - chat_id, ripr_menuPrec); - } - -} - function getstr(lang, key, param1) { let mystr = ''; @@ -1610,38 +1441,6 @@ class Telegram { '\n\nI miei colleghi umani ti aiuteranno a risolvere !'; } - convertSpecialTags(user, msg) { - try { - if (!!user) { - msg = msg.replace('{username}', user.username); - msg = msg.replace('{name}', user.name ? user.name : user.username); - msg = msg.replace('{surname}', user.surname ? user.surname : ''); - msg = msg.replace('{aportador_solidario}', - user.aportador_solidario ? user.aportador_solidario : ''); - if (!!user.profile.link_payment) - msg = msg.replace('{link_paypalme}', user.profile.link_payment); - if (!!user.profile.revolut) - msg = msg.replace('{revolut}', user.profile.revolut); - if (!!user.profile.payeer_id) - msg = msg.replace('{payeer_id}', user.profile.payeer_id); - if (!!user.profile.advcash_id) - msg = msg.replace('{advcash_id}', user.profile.advcash_id); - if (!!user.profile.email_paypal) - msg = msg.replace('{email_paypal}', user.profile.email_paypal); - if (!!user.profile.note_payment) - msg = msg.replace('{note_payment}', user.profile.note_payment); - } - - // const cl = getclTelegByidapp(user.idapp); - msg = msg.replace('{link_chathelp}', tools.HELP_CHAT); - - } catch (e) { - console.log(e); - } - - return msg; - } - async IsTesto(msg) { let risp = ''; @@ -1728,10 +1527,7 @@ class Telegram { printf(getstr(rec.user.lang, 'MSG_SET_USERNAME_OK'))); if (!rec.user.verified_by_aportador) { - this.askConfirmationUserRegistration(this.idapp, - shared_consts.CallFunz.REGISTRATION, rec.user, - msg.from.username || '', msg.from.first_name || '', - msg.from.last_name || ''); + this.askConfirmationUser(this.idapp, shared_consts.CallFunz.REGISTRATION, rec.user); } } else { @@ -1887,7 +1683,7 @@ class Telegram { } } - risp = this.convertSpecialTags(rec.user, risp); + risp = tools.convertSpecialTags(rec.user, risp); let keyboard = null; @@ -2659,14 +2455,11 @@ class Telegram { } } - checkIfUsernameTelegramSet(msg, recuser) { + async checkIfUsernameTelegramSet(msg, recuser) { try { if (!msg.from.username) { // - this.sendMsg(msg.from.id, - printf(getstr(recuser.lang, 'MSG_SET_USERNAME'))); - - return true; + return this.sendMsg(msg.from.id, printf(getstr(recuser.lang, 'MSG_SET_USERNAME'))); } } catch (e) { console.error('e'); @@ -2678,8 +2471,7 @@ class Telegram { if (!!msg.text) { const code = msg.text.toString().trim(); const rec = this.getRecInMem(msg); - const user = await User.findByUsername(this.idapp, rec.username_bo, - true); + let user = await User.findByUsername(this.idapp, rec.username_bo, true); let telegcode = 0; if (user) { telegcode = user.profile.teleg_checkcode.toString(); @@ -2697,35 +2489,41 @@ class Telegram { 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; - await User.SetTelegramIdSuccess(this.idapp, user._id, - msg.from.id).then((recuser) => { + await User.SetTelegramIdSuccess(this.idapp, user._id, msg.from.id).then(async (recuser) => { + + const rismsg = await MsgTemplate.getMsgByLang(this.idapp, shared_consts.TypeMsgTemplate.MSG_BENVENUTO, recuser.lang); + const rismsg2 = await MsgTemplate.getMsgByLang(this.idapp, shared_consts.TypeMsgTemplate.MS_SHARE_LINK, recuser.lang); + + return {recuser, rismsg, rismsg2}; + + }).then(async ({recuser, rismsg, rismsg2}) => { + if (recuser) { - this.setPhotoProfile(rec, msg); + console.log(recuser.username, ' SI E\' VERIFICATO CON TELEGRAM !'); + this.setPhotoProfile(rec, msg, false); let username = recuser.name; - this.sendMsgLog(msg.from.id, - printf(getstr(recuser.lang, 'MSG_VERIFY_OK'), username, - tools.getHostByIdApp(this.idapp))); + // this.sendMsgLog(msg.from.id, printf(getstr(recuser.lang, 'MSG_VERIFY_OK'), username, tools.getHostByIdApp(this.idapp))); + await this.sendMsgLog(msg.from.id, rismsg.body); + await this.sendMsg(msg.from.id, rismsg2.body); if (msg.from.username) { - this.askConfirmationUserRegistration(this.idapp, - shared_consts.CallFunz.REGISTRATION, recuser, - msg.from.username || '', msg.from.first_name || '', - msg.from.last_name || ''); + MyTelegramBot.askConfirmationUser(this.idapp, shared_consts.CallFunz.REGISTRATION, recuser); } 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')); + this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERR_UNKNOWN_VERIFY_CODE')); } + }); } else { if (rec.retry < 2) { @@ -2784,6 +2582,8 @@ class Telegram { async setCmdToUsername(rec, username, cmd_to_set, valuebool) { if (cmd_to_set === Cmd.VALIDATE_REGISTRATION) { return User.setVerifiedByAportador(rec.user.idapp, username, valuebool); + } else if (cmd_to_set === Cmd.RICHIESTA_GRUPPO) { + } } @@ -2902,8 +2702,7 @@ class Telegram { } if (inviaveramente) { - textdainviare = this.convertSpecialTags(utente, - textdainviare); + textdainviare = tools.convertSpecialTags(utente, textdainviare); if (destin === Destin.A_UTENTE) { await this.sistemaRecDest(rec, msg); @@ -3117,9 +2916,7 @@ class Telegram { await this.addUser(msg); // 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_ASK_USERNAME_BO', - tools.getNomeAppByIdApp(this.idapp)), null); + await this.sendMsg(msg.chat.id, getstr(this.getlang(msg), 'MSG_ASK_USERNAME_BO', tools.getNomeAppByIdApp(this.idapp)), null); return false; } @@ -3542,7 +3339,7 @@ class Telegram { const username = rec ? rec.username_bo : ''; console.log('Msg inviato a ', username, '(', id, ')', text); - this.sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec); + return this.sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec); } getmenuKey(mymenu, lang) { @@ -3557,7 +3354,7 @@ class Telegram { return mymenuout; } - async setPhotoProfile(rec, msg) { + async setPhotoProfile(rec, msg, showmsg = true) { try { if (rec.user) { const idapp = this.idapp; @@ -3592,9 +3389,11 @@ class Telegram { return User.setPicProfile(idapp, username, filename). then((ris) => { // console.log('4) sendMsg picprofile Copied !'); - local_sendMsgTelegram(idapp, username, - printf(getstr(lang, 'MSG_SET_PICPROFILE'), - editprofile)); + if (showmsg) { + local_sendMsgTelegram(idapp, username, + printf(getstr(lang, 'MSG_SET_PICPROFILE'), + editprofile)); + } }); // console.log('scaricato'); }).catch((err) => { @@ -3784,120 +3583,138 @@ if (true) { bot.on('callback_query', async (callbackQuery) => { // console.log('callback_query', callbackQuery); - const myclTelegram = getclTelegBytoken(bot.token); + try { + const myclTelegram = getclTelegBytoken(bot.token); - let dataarr = []; - let data = { - action: '', - username: '', - userDest: '', - }; + let dataarr = []; + let data = { + action: '', + username: '', + userDest: '', + groupId: 0, + }; - 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] : '', - }; + 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] ? parseInt(dataarr[3]) : '', + }; + } } - } - const msg = callbackQuery.message; - const opts = { - chat_id: msg.chat.id, - message_id: msg.message_id, - }; + const msg = callbackQuery.message; + const opts = { + chat_id: msg.chat.id, + message_id: msg.message_id, + }; - const status = await myclTelegram.setInit(msg); + const status = await myclTelegram.setInit(msg); - const rec = myclTelegram.getRecInMem(msg); - const user = await User.getUserShortDataByUsername(idapp, - data.username); - const userDest = data.userDest - ? await User.getUserShortDataByUsername(idapp, data.userDest) - : null; + const rec = myclTelegram.getRecInMem(msg); + const user = await User.getUserShortDataByUsername(idapp, data.username); + const userDest = data.userDest ? await User.getUserShortDataByUsername(idapp, data.userDest) : null; - if (!!rec) { - if (!!user) { - if (data.action === InlineCmd.VOGLIO_IMBARCARMI) { - // Controlla se è qualificato! - const mydata = tools.AddDate(user.date_reg, 7); + let group = null; + if (data.groupId) { + group = await MyGroup.findOne({idapp, _id: data.groupId}).lean(); + } - // bot.editMessageText(tools.gettranslate('ADDED_TOLISTAINGRESSO', user.lang), opts); + let cmd = 0; - } else if (data.action === InlineCmd.NON_VOGLIO_IMBARCARMI) { - await User.NonVoglioImbarcarmi(user.idapp, user.username); + if (!!rec) { + if (!!user) { + if (data.action === InlineCmd.VOGLIO_IMBARCARMI) { + // Controlla se è qualificato! + const mydata = tools.AddDate(user.date_reg, 7); - const msgadd = '[' + user.username + '] ' + user.name + ' ' + - user.surname + ' ha risposto che NON VUOLE IMBARCARSI !'; + // bot.editMessageText(tools.gettranslate('ADDED_TOLISTAINGRESSO', user.lang), opts); - await local_sendMsgTelegramToTheManagers(user.idapp, msgadd, - msg, false); // Anche a STAFF - } else if (data.action === - InlineZoomConferma.CONFERMA_ZOOM_PRESENZA) { + } else if (data.action === InlineCmd.NON_VOGLIO_IMBARCARMI) { + await User.NonVoglioImbarcarmi(user.idapp, user.username); - await User.setZoomPresenza(user.idapp, user._id, true); + const msgadd = '[' + user.username + '] ' + user.name + ' ' + + user.surname + ' ha risposto che NON VUOLE IMBARCARSI !'; - } else if (data.action === - InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA) { + await local_sendMsgTelegramToTheManagers(user.idapp, msgadd, + msg, false); // Anche a STAFF + } else if (data.action === + InlineZoomConferma.CONFERMA_ZOOM_PRESENZA) { - await User.setZoomPresenza(user.idapp, user._id, false); + await User.setZoomPresenza(user.idapp, user._id, true); - } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.REGISTRATION) { - const changed = await myclTelegram.setCmdToUsername(rec, - data.username, - Cmd.VALIDATE_REGISTRATION, true); + } else if (data.action === + InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA) { - if (changed) { - await User.setFriendsCmd(user.idapp, data.username, - userDest.username, shared_consts.FRIENDSCMD.SETFRIEND); + await User.setZoomPresenza(user.idapp, user._id, false); - await User.setaportador_solidario(user.idapp, data.username, - userDest.username); - - const msgOrig = printf( - getstr(userDest.lang, 'MSG_APORTADOR_DEST_CONFIRMED'), - `${userDest.username}`, tools.getHostByIdApp(user.idapp)); - const msgDest = printf( - getstr(user.lang, 'MSG_APORTADOR_CONFIRMED'), - `${user.username}`); - - await local_sendMsgTelegram(user.idapp, data.username, - msgOrig); - await local_sendMsgTelegram(user.idapp, data.userDest, - msgDest); - } - - } else if (data.action === InlineConferma.RISPOSTA_NO + - shared_consts.CallFunz.REGISTRATION) { - if (userDest.username === user.aportador_solidario) { + } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.REGISTRATION) { const changed = await myclTelegram.setCmdToUsername(rec, data.username, - Cmd.VALIDATE_REGISTRATION, false); + Cmd.VALIDATE_REGISTRATION, true); if (changed) { - const nomeDest = tools.getNomeCognomeEUserNameByUser( - userDest); - const nomestr = tools.getNomeCognomeEUserNameByUser(user); + await User.setFriendsCmd(user.idapp, data.username, userDest.username, shared_consts.FRIENDSCMD.SETFRIEND); - const msgOrig = printf( - getstr(userDest.lang, - 'MSG_APORTADOR_DEST_NOT_CONFIRMED', - nomeDest)); - const msgDest = printf( - getstr(user.lang, 'MSG_APORTADOR_NOT_CONFIRMED'), - nomestr); + await User.setaportador_solidario(user.idapp, data.username, userDest.username); + + const msgOrig = printf(getstr(userDest.lang, 'MSG_APORTADOR_DEST_CONFIRMED'), `${userDest.username}`, + tools.getHostByIdApp(user.idapp)); + const msgDest = printf(getstr(user.lang, 'MSG_APORTADOR_CONFIRMED'), + `${user.username}`); + + await local_sendMsgTelegram(user.idapp, data.username, msgOrig); + await local_sendMsgTelegram(user.idapp, data.userDest, msgDest); + } + + } 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); + } + + } + } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_GRUPPO) { + + if (group) { + cmd = shared_consts.GROUPSCMD.REMOVE_FROM_MYGROUP; + 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); + } - await local_sendMsgTelegram(user.idapp, data.username, - msgOrig); - await local_sendMsgTelegram(user.idapp, data.userDest, - msgDest); } } } } + } catch (e) { + console.error('Error BOT callback_query', e); } /* @@ -3919,3 +3736,4 @@ if (true) { } } +module.exports = MyTelegramBot; diff --git a/src/server/tools/general.js b/src/server/tools/general.js index edbed1a..6181f25 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -123,6 +123,8 @@ const textlang = { 'MSG_SEND_FROM': 'Msg Inviato da', 'ZOOM_CONFERMATO': 'Sei stato confermato ad aver visto la Video Conferenza di Benvenuto!', 'RICHIESTA_AMICIZIA': 'Richiesta d\'Amicizia da parte di %s', + 'ACCETTATO_SUL_GRUPPO': 'Sei stato accettato da %s a far parte del Gruppo %s', + 'ACCETTATO_NOTIFICA_ADMINS': 'l\'utente %s è stato accettato a far parte del Gruppo %s', 'RICHIESTA_GRUPPO': 'Richiesta di entrare nel Gruppo %s da parte di %s', 'RICHIESTA_BLOCCO_GRUPPO': 'Richiesta di bloccare il Gruppo %s da parte di %s', }, @@ -190,6 +192,11 @@ const textlang = { 'NAVE': 'NAVE', 'MSG_SEND_FROM': 'Mensaje enviado por', 'ZOOM_CONFERMATO': '¡Se ha confirmado que ha visto la Video Conferencia de Bienvenida!', + 'RICHIESTA_AMICIZIA': 'Richiesta d\'Amicizia da parte di %s', + 'ACCETTATO_SUL_GRUPPO': 'Sei stato accettato da %s a far parte del Gruppo %s', + 'ACCETTATO_NOTIFICA_ADMINS': 'l\'utente %s è stato accettato a far parte del Gruppo %s', + 'RICHIESTA_GRUPPO': 'Richiesta di entrare nel Gruppo %s da parte di %s', + 'RICHIESTA_BLOCCO_GRUPPO': 'Richiesta di bloccare il Gruppo %s da parte di %s', }, enUs: { 'partecipanti': 'participants', @@ -249,6 +256,11 @@ const textlang = { 'NAVE': 'SHIP', 'MSG_SEND_FROM': 'Msg sent by', 'ZOOM_CONFERMATO': 'You have been confirmed to have seen the Welcome Video Conference!', + 'RICHIESTA_AMICIZIA': 'Richiesta d\'Amicizia da parte di %s', + 'ACCETTATO_SUL_GRUPPO': 'Sei stato accettato da %s a far parte del Gruppo %s', + 'ACCETTATO_NOTIFICA_ADMINS': 'l\'utente %s è stato accettato a far parte del Gruppo %s', + 'RICHIESTA_GRUPPO': 'Richiesta di entrare nel Gruppo %s da parte di %s', + 'RICHIESTA_BLOCCO_GRUPPO': 'Richiesta di bloccare il Gruppo %s da parte di %s', }, fr: { 'L\'Email è già stata Verificata': 'Le courrier électronique a déjà été vérifié', @@ -313,6 +325,11 @@ const textlang = { 'NAVE': 'NAVIRE', 'MSG_SEND_FROM': 'Message envoyé par', 'ZOOM_CONFERMATO': 'Vous avez été confirmé comme ayant vu la vidéoconférence de bienvenue !', + 'RICHIESTA_AMICIZIA': 'Richiesta d\'Amicizia da parte di %s', + 'ACCETTATO_SUL_GRUPPO': 'Sei stato accettato da %s a far parte del Gruppo %s', + 'ACCETTATO_NOTIFICA_ADMINS': 'l\'utente %s è stato accettato a far parte del Gruppo %s', + 'RICHIESTA_GRUPPO': 'Richiesta di entrare nel Gruppo %s da parte di %s', + 'RICHIESTA_BLOCCO_GRUPPO': 'Richiesta di bloccare il Gruppo %s da parte di %s', }, pt: { 'L\'Email è già stata Verificata': '', @@ -375,6 +392,11 @@ const textlang = { 'NAVE': 'NAVE', 'MSG_SEND_FROM': 'Mensagem enviada por', 'ZOOM_CONFERMATO': 'Foi-lhe confirmado que assistiu à Conferência de Vídeo de Boas-vindas!', + 'RICHIESTA_AMICIZIA': 'Richiesta d\'Amicizia da parte di %s', + 'ACCETTATO_SUL_GRUPPO': 'Sei stato accettato da %s a far parte del Gruppo %s', + 'ACCETTATO_NOTIFICA_ADMINS': 'l\'utente %s è stato accettato a far parte del Gruppo %s', + 'RICHIESTA_GRUPPO': 'Richiesta di entrare nel Gruppo %s da parte di %s', + 'RICHIESTA_BLOCCO_GRUPPO': 'Richiesta di bloccare il Gruppo %s da parte di %s', }, }; @@ -702,8 +724,7 @@ module.exports = { }); }, - sendNotificationToUser: function( - userId, title, content, openUrl, openUrl2, tag, actions) { + sendNotificationToUser: function(userId, title, content, openUrl, openUrl2, tag, actions) { let payload = { actions, @@ -850,11 +871,30 @@ module.exports = { }, - sendNotificationByGroupname: async function(idapp, groupname, cmd, telegram) { + sendNotifAndMsgTelegram: async function(idapp, userId, objmsg, telegram, msgextrateleg) { + + if (userId) { + this.sendNotificationToUser(userId, objmsg.title, objmsg.descr, objmsg.openUrl, '', objmsg.tag, objmsg.actions); + } + + if (telegram) { + var {User} = require('../models/user'); + const telegrambot = require('../telegram/telegrambot'); + + const idtelegram = await User.TelegIdById(idapp, userId); + + const msgteleg = objmsg.descr + (msgextrateleg ? '\n' + msgextrateleg : '') + await telegrambot.sendMsgTelegramByIdTelegram(idapp, idtelegram, msgteleg); + } + }, + + sendNotificationByGroupname: async function(idapp, usernameOrig, groupname, cmd, telegram) { var {User} = require('../models/user'); var {MyGroup} = require('../models/mygroup'); + const telegrambot = require('../telegram/telegrambot'); + const group = await MyGroup.findOne({idapp, groupname}, {_id: 1, admins: 1}); if (!group) @@ -864,50 +904,58 @@ module.exports = { const arrusernameAdmins = group.admins; - for (const arradmins of arrusernameAdmins) { + const myuser = await User.findOne({idapp, username: usernameOrig}).lean(); + + let struserinfomsg = this.getUserInfoMsg(idapp, myuser); + + let objmsg = { + title: this.getNomeAppByIdApp(idapp), + descr: '', + openUrl: '/', + tag: '', + actions: [], + }; + + for (const singleadmin of arrusernameAdmins) { try { - if (arradmins.username) { - const user = await User.findOne({idapp, username: arradmins.username}, + if (singleadmin.username) { + const user = await User.findOne({idapp, username: singleadmin.username}, {_id: 1, lang: 1}); if (user) { let userId = user._id; let lang = user.lang; - let title = this.getNomeAppByIdApp(idapp); - let descr = ''; - let openUrl = '/'; - let tag = ''; - let actions = []; + let sendnotif = true; + if (cmd) { - if (cmd === shared_consts.GROUPSCMD.REQGROUP) { - descr = printf(this.get__('RICHIESTA_GRUPPO', lang), groupname, - arradmins.username); - openUrl = '/grp/' + groupname; - tag = 'reqgroups'; + if (cmd === shared_consts.GROUPSCMD.SETGROUP) { + objmsg.descr = printf(this.get__('ACCETTATO_NOTIFICA_ADMINS', lang), singleadmin.username, groupname); + objmsg.openUrl = '/grp/' + groupname; + objmsg.tag = 'addgroups'; + + } else if (cmd === shared_consts.GROUPSCMD.REQGROUP) { + objmsg.descr = printf(this.get__('RICHIESTA_GRUPPO', lang), groupname, + singleadmin.username); + objmsg.openUrl = '/grp/' + groupname; + objmsg.tag = 'reqgroups'; + + sendnotif = false; // non lo rimandare 2 volte ! + telegrambot.askConfirmationUser(idapp, shared_consts.CallFunz.RICHIESTA_GRUPPO, myuser, singleadmin.username, {groupid: group._id, groupname }); + } else if (cmd === shared_consts.GROUPSCMD.BLOCK_USER) { - descr = printf(this.get__('RICHIESTA_BLOCCO_GRUPPO', lang), - groupname, arradmins.username); - openUrl = '/grp/' + groupname; - tag = 'blockgroups'; + objmsg.descr = printf(this.get__('RICHIESTA_BLOCCO_GRUPPO', lang), + groupname, singleadmin.username); + objmsg.openUrl = '/grp/' + groupname; + objmsg.tag = 'blockgroups'; } + } - if (userId) { - this.sendNotificationToUser(userId, title, descr, openUrl, '', - tag, - actions); + if (sendnotif && objmsg.descr) { + await this.sendNotifAndMsgTelegram(idapp, userId, objmsg, telegram, struserinfomsg); } - if (telegram) { - const telegrambot = require('../telegram/telegrambot'); - - const idtelegram = await User.TelegIdByUsername(idapp, - arradmins.username); - - await telegrambot.sendMsgTelegramByIdTelegram(idapp, idtelegram, - descr); - } } } } catch (e) { @@ -915,6 +963,16 @@ module.exports = { } } + if (cmd === shared_consts.GROUPSCMD.SETGROUP) { + const reclang = await User.getRecLangAndIdByUsername(idapp, usernameOrig); + objmsg.descr = printf(this.get__('ACCETTATO_SUL_GRUPPO', reclang.lang), usernameOrig, groupname); + objmsg.openUrl = '/grp/' + groupname; + objmsg.tag = 'addgroups'; + + // Send to User: + await this.sendNotifAndMsgTelegram(idapp, reclang._id, objmsg, telegram); + } + }, // ********************** @@ -1063,11 +1121,11 @@ module.exports = { return ''; }, - getLinkUserProfile: function (idapp, username) { + getLinkUserProfile: function(idapp, username) { return tools.getHostByIdApp(idapp) + '/my/' + username; }, - getLinkEditUserProfile: function (idapp) { + getLinkEditUserProfile: function(idapp) { return tools.getHostByIdApp(idapp) + '/editprofile'; }, @@ -2627,13 +2685,76 @@ module.exports = { try { return download.image({ url, - dest: filepath + dest: filepath, }); - }catch (e) { + } catch (e) { console.error('Err download image', e); return false; } }, + convertSpecialTags(user, msg) { + try { + if (!!user) { + msg = msg.replace('{username}', user.username); + msg = msg.replace('{name}', user.name ? user.name : user.username); + msg = msg.replace('{surname}', user.surname ? user.surname : ''); + msg = msg.replace('{aportador_solidario}', + user.aportador_solidario ? user.aportador_solidario : ''); + if (!!user.profile.link_payment) + msg = msg.replace('{link_paypalme}', user.profile.link_payment); + if (!!user.profile.revolut) + msg = msg.replace('{revolut}', user.profile.revolut); + if (!!user.profile.payeer_id) + msg = msg.replace('{payeer_id}', user.profile.payeer_id); + if (!!user.profile.advcash_id) + msg = msg.replace('{advcash_id}', user.profile.advcash_id); + if (!!user.profile.email_paypal) + msg = msg.replace('{email_paypal}', user.profile.email_paypal); + if (!!user.profile.note_payment) + msg = msg.replace('{note_payment}', user.profile.note_payment); + } + + // const cl = getclTelegByidapp(user.idapp); + msg = msg.replace('{link_chathelp}', this.HELP_CHAT); + + } catch (e) { + console.log(e); + } + + return msg; + }, + + getUserInfoMsg: function(idapp, myuser, usernametelegram = '', name_telegram = '', + surname_telegram = '') { + + let msg = ''; + try { + const name = myuser.username + + (myuser.name ? `(${myuser.name} + ' ' + ${myuser.surname})` : ''); + const linkuserprof = this.getHostByIdApp(idapp) + '/my/' + + myuser.username; + + msg = `
Username: ${name}
Profilo su APP: ${linkuserprof}
Email: ${myuser.email}`; + + let u_tg = myuser.profile && myuser.profile.hasOwnProperty('username_telegram') ? myuser.profile.username_telegram : usernametelegram; + let name_tg = myuser.profile && myuser.profile.hasOwnProperty('firstname_telegram') + ? myuser.profile.firstname_telegram + : name_telegram; + let surname_tg = myuser.profile && myuser.profile.hasOwnProperty('lastname_telegram') + ? myuser.profile.lastname_telegram + : surname_telegram; + + if (u_tg) { + msg += '
Profilo su Telegram [' + name_tg + ' ' + surname_tg + ']:
' + 'https://t.me/' + u_tg; + } + }catch (e) { + console.error('getUserInfoMsg', e); + } + + return msg; + }, + + }; diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index 7c4bb67..6111515 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -194,4 +194,111 @@ module.exports = { return mytable; }, + + SendMsgToParam: async function(idapp, params) { + + try { + const telegrambot = require('../telegram/telegrambot'); + + let query = {idapp}; + let addquery = {}; + + let invia = true; + + if (params.typemsg === shared_consts.TypeMsg.SEND_TO_ALL) { + addquery = {}; + } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_SOCI) { + addquery = {'profile.socio': true}; + } else if (params.typemsg === + shared_consts.TypeMsg.SEND_TO_SOCIO_RESIDENTE) { + addquery = {'profile.socioresidente': true}; + } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_CONSIGLIO) { + addquery = {'profile.consiglio': true}; + } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_NON_SOCI) { + addquery = {'profile.socio': false}; + } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_PAOLO) { + addquery = {username: 'paoloar77'}; + } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_USER) { + addquery = {username: params.usernameDest}; + } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_MYSELF) { + addquery = {username: params.usernameDest}; + } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_GROUP) { + if (params.groupnameDest) { + addquery = { + 'profile.mygroups': { + $elemMatch: {groupname: {$eq: params.groupnameDest}}, + }, + }; + } else { + invia = false; + } + } + + let numrec = 0; + let nummsgsent = 0; + + if (invia) { + + const allquery = {...query, ...addquery}; + + const arrusers = await User.find( + allquery, + { + username: 1, + 'profile.teleg_id': 1, + }, + ).lean(); + + for (const user of arrusers) { + + const mytitle = tools.convertSpecialTags(user, params.title); + const mycontent = tools.convertSpecialTags(user, params.content); + + if (params.sendreally) { + if (tools.isBitActive(params.typesend, + shared_consts.TypeSend.PUSH_NOTIFICATION)) { + tools.sendNotificationToUser(user._id, mytitle, mycontent, params.openUrl, params.openUrl2, params.tag, + params.actions). + then(ris => { + + }). + catch(e => { + console.error(e.message); + }); + + } else if (tools.isBitActive(params.typesend, shared_consts.TypeSend.TELEGRAM)) { + const telegid = user.profile.teleg_id; + + if (telegid > 0) { + telegrambot.local_sendMsgTelegramByIdTelegram(idapp, telegid, mycontent); + } + } + } + + numrec++; + if (params.sendreally) { + nummsgsent++; + } + } + } + + return { + numrec, + nummsgsent, + }; + } catch (e) { + console.error('SendMsgToParam', e); + } + + }, + + SendMsgToAll: async function(idapp, params) { + + params.typemsg = shared_consts.TypeMsg.SEND_TO_ALL; + params.sendreally = true; + params.typesend = shared_consts.TypeSend.PUSH_NOTIFICATION; + + return this.SendMsgToParam(idapp, params); + }, + }; diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index c6498eb..eacca97 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -90,7 +90,7 @@ module.exports = { TABLES_MYBACHECAS: 'mybachecas', TABLES_MYGOODS: 'mygoods', - TABLES_ENABLE_GETREC_BYID: ['mybachecas'], + TABLES_ENABLE_GETREC_BYID: ['mybachecas', 'myskills', 'mygoods'], TABLES_USER_INCLUDE_MY: ['mygroups'], TABLES_GETCOMPLETEREC: ['myskills', 'mybachecas', 'mygoods'], @@ -200,6 +200,9 @@ module.exports = { SEND_TO_CONSIGLIO: 5, SEND_TO_NON_SOCI: 10, SEND_TO_PAOLO: 20, + SEND_TO_USER: 25, + SEND_TO_GROUP: 30, + SEND_TO_MYSELF: 40, }, TypeMsg_Actions: { @@ -217,6 +220,7 @@ module.exports = { SET_VALBYTABLE: 410, ZOOM_GIA_PARTECIPATO: 510, REGISTRATION: 6, + RICHIESTA_GRUPPO: 10, }, OrderStatus: { @@ -245,6 +249,20 @@ module.exports = { Need_Aportador_On_DataReg_To_Verify_Reg: 4, }, + MsgTeleg: { + SHARE_MSGREG: 1 + }, + + TypeMsgTemplate: { + MSG_BENVENUTO: 2010, + MS_SHARE_LINK: 2000 + }, + + TypeSend: { + PUSH_NOTIFICATION: 1, + TELEGRAM: 2, + }, + fieldsUserToChange() { return [ '_id',