From 18b827f5f42b318534a9dc06064d8c0096e2a146 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Tue, 3 Jan 2023 16:51:32 +0100 Subject: [PATCH] ver 0.5.51 --- src/server/locales/it.json | 3 + src/server/models/account.js | 127 ++++- src/server/models/circuit.js | 58 ++- src/server/models/mygroup.js | 203 +++++--- src/server/models/sendnotif.js | 162 +++--- src/server/models/user.js | 229 ++++++--- src/server/telegram/telegrambot.js | 785 +++++++++++++++-------------- src/server/tools/general.js | 40 +- src/server/tools/globalTables.js | 8 + src/server/tools/shared_nodejs.js | 5 + 10 files changed, 1004 insertions(+), 616 deletions(-) diff --git a/src/server/locales/it.json b/src/server/locales/it.json index e114a21..c35b28b 100644 --- a/src/server/locales/it.json +++ b/src/server/locales/it.json @@ -34,7 +34,9 @@ "FRIEND_UNBLOCKED": "E' stato riattivato %s da %s.", "FRIEND_UNBLOCKED_YOU": "Hai riattivato %s.", "CIRCUIT_ACCEPT_NEWENTRY": "❇️👥 🧍‍♂️ Accetta Ingresso nel Circuito %s:", + "CIRCUIT_ACCEPT_NEWENTRY_BYGROUP": "❇️👥 🧍‍♂️ Accetta Ingresso nel Circuito il gruppo %s:", "CIRCUIT_REQUEST_TO_ENTER": "%s ha chiesto di entrare nel circuito %s", + "CIRCUIT_REQUEST_TO_ENTER_WITH_GROUP": "il gruppo %s ha chiesto di entrare nel circuito %s", "CIRCUIT_CREATED": "✅ %s ha creato un nuovo Circuito chiamato %s", "CIRCUIT_REQUEST": "Richiesta di entrare nel Circuito %s da parte di %s", "CIRCUIT_ADDED_ADMIN": "E' stato aggiunto %s come Amministratore del circuito %s da parte di %s", @@ -44,6 +46,7 @@ "RICHIESTA_BLOCCO_CIRCUIT": "Richiesta di bloccare il Circuito %s da parte di %s", "CIRCUIT_ELIMINATO": "Il circuito %s è stato eliminato da parte di %s", "ACCETTATO_NOTIFICA_ADMINS_CIRCUIT": "✅ l'utente %s è stato accettato a far parte del Circuito %s (da parte di %s)", + "ACCETTATO_NOTIFICA_ADMINS_CIRCUIT_MYGROUP": "✅ il gruppo %s è stato accettato a far parte del Circuito %s (da parte di %s)", "CIRCUIT_ACCEPTED": "✅ Sei stato accettato da %s a far parte del Circuito %s.\nApri la APP e clicca in alto a destra sull'icona delle monete, oppure clicca qui: %s", "CIRCUIT_ACCEPTED_YOU": "✅ Hai accettato %s a far parte del Circuito %s", "CIRCUIT_REFUSED": "❌ Ti è stato rifiutato l'accesso da %s a far parte del Circuito %s. Se pensi sia un'errore, contatta l'amministratore del Circuito.", diff --git a/src/server/models/account.js b/src/server/models/account.js index 78f3c1c..bdf20ff 100755 --- a/src/server/models/account.js +++ b/src/server/models/account.js @@ -33,6 +33,9 @@ const AccountSchema = new Schema({ username: { type: String, }, + groupname: { // For the Groups + type: String, + }, circuitId: { // ----- REF TO Circuit type: String, }, @@ -192,7 +195,7 @@ AccountSchema.pre('save', async function (next) { next(); }); -AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp, username, circuitId, createifnotexist) { +AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp, username, circuitId, createifnotexist, groupname = '') { const Account = this; try { @@ -203,11 +206,16 @@ AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp, return false; let myquery = { - 'idapp': idapp, - 'username': username, + idapp, circuitId, }; + if (groupname) { + myquery.groupname = groupname; + } else { + myquery.username = username; + } + let mycircuit = await Circuit.getCircuitById(circuitId); if (mycircuit) { @@ -218,14 +226,28 @@ AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp, _id: new ObjectID().toString(), idapp, username, + groupname, circuitId: mycircuit._id, deperibile: false, - fidoConcesso: mycircuit.fido_scoperto_default, - qta_maxConcessa: mycircuit.qta_max_default, importo_iniziale: 0, saldo: 0, + fidoConcesso: 0, + qta_maxConcessa: 0, }); + if (!mycircuit.fido_scoperto_default_grp) + mycircuit.fido_scoperto_default_grp = shared_consts.CIRCUIT_PARAMS.SCOPERTO_MIN_GRP; + if (!mycircuit.qta_max_default_grp) + mycircuit.qta_max_default_grp = shared_consts.CIRCUIT_PARAMS.SCOPERTO_MAX_GRP; + + if (groupname) { + myaccount.fidoConcesso = mycircuit.fido_scoperto_default_grp; + myaccount.qta_maxConcessa = mycircuit.qta_max_default_grp; + } else { + myaccount.fidoConcesso = mycircuit.fido_scoperto_default; + myaccount.qta_maxConcessa = mycircuit.qta_max_default; + } + return await myaccount.save(); } @@ -239,14 +261,14 @@ AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (idapp, }; -AccountSchema.statics.createAccount = async function (idapp, username, circuitName) { +AccountSchema.statics.createAccount = async function (idapp, username, circuitName, groupname = '') { const { Circuit } = require('../models/circuit'); try { mycircuit = await Circuit.findOne({ name: circuitName }, {_id: 1}); if (mycircuit) { - return await Account.getAccountByUsernameAndCircuitId(idapp, username, mycircuit._id, true); + return await Account.getAccountByUsernameAndCircuitId(idapp, username, mycircuit._id, true, groupname); } else { return null; } @@ -323,6 +345,97 @@ AccountSchema.statics.getUserAccounts = async function (idapp, username) { }; +AccountSchema.statics.getGroupAccounts = async function (idapp, groupname) { + + try { + let aggr1 = [ + { + $match: { idapp, groupname }, + }, + { + $lookup: { + from: 'circuits', + localField: 'circuitId', + foreignField: '_id', + as: 'circuit', + }, + }, + { $unwind: '$circuit' }, + { + $lookup: { + from: 'sendnotifs', + as: 'notifspending', + let: { + circuitname: '$circuit.name', + groupname: '$groupname', + idapp: '$idapp', + typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS, + typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ, + }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$typedir', '$$typedir'] }, + { $eq: ['$typeid', '$$typeid'] }, + { $eq: ['$status', 0] }, + { $eq: ['$sender', '$$username'] }, + { $eq: ['$idapp', '$$idapp'] }, + { $eq: ['$extrarec.circuitname', '$$circuitname'] }, + ], + }, + }, + }, + ], + }, + }, + ]; + + ris = await this.aggregate(aggr1); + + const { SendNotif } = require('../models/sendnotif'); + + if (ris) { + for (const account of ris) { + const pendingtransactions = await SendNotif.getSumPendingTransactions(idapp, '', account.circuit.name, groupname); + const saldopending = pendingtransactions.reduce((sum, rec) => sum + rec.extrarec.qty, 0); + account.saldo -= saldopending; + } + } + + return ris; + } catch (e) { + console.error('e', e); + } + +}; + +// Aggiungi agli Admin del Account +AccountSchema.statics.addToPeopleOfMyAccount = async function (idapp, username, circuitId, person_username, perm) { + + return await Account.updateOne({ idapp, username, circuitId }, + { + $push: + { + people: { + username: person_username, + perm, + date: new Date(), + }, + }, + }); + +}; + +// Rimuovi dagli Admin del Account +AccountSchema.statics.removeAdminOfAccount = async function (idapp, username, circuitId, person_username, perm) { + + return await Circuit.updateOne({ idapp, username, circuitId }, + { $pull: { people: { username: { $in: [person_username] } } } }); +}; + + const Account = mongoose.model('Account', AccountSchema); module.exports = { Account }; diff --git a/src/server/models/circuit.js b/src/server/models/circuit.js index d9695e2..a0cbb5c 100755 --- a/src/server/models/circuit.js +++ b/src/server/models/circuit.js @@ -106,6 +106,12 @@ const CircuitSchema = new Schema({ qta_max_default: { type: Number, }, + fido_scoperto_default_grp: { + type: Number, + }, + qta_max_default_grp: { + type: Number, + }, data_costituz: { type: Date, }, @@ -173,6 +179,18 @@ const CircuitSchema = new Schema({ username: { type: String }, date: { type: Date }, }], // username + req_groups: [ + { + _id: false, + groupname: { type: String }, + date: { type: Date }, + }], // username + refused_groups: [ + { + _id: false, + groupname: { type: String }, + date: { type: Date }, + }], // username deleted: { type: Boolean, default: false, @@ -245,10 +263,12 @@ CircuitSchema.statics.getWhatToShow = function (idapp, username) { date_updated: 1, nome_valuta: 1, fido_scoperto_default: 1, + qta_max_default: 1, + fido_scoperto_default_grp: 1, + qta_max_default_grp: 1, deperimento: 1, transactionsEnabled: 1, status: 1, - qta_max_default: 1, valuta_per_euro: 1, symbol: 1, idCity: 1, @@ -261,6 +281,8 @@ CircuitSchema.statics.getWhatToShow = function (idapp, username) { admins: 1, req_users: 1, refused_users: 1, + req_groups: 1, + refused_groups: 1, 'mycities': 1, }; @@ -304,6 +326,8 @@ CircuitSchema.statics.getWhatToShow_Unknown = function (idapp, username) { totCircolante: 1, totTransato: 1, fido_scoperto_default: 1, + fido_scoperto_default_grp: 1, + qta_max_default_grp: 1, qta_max_default: 1, valuta_per_euro: 1, symbol: 1, @@ -320,6 +344,8 @@ CircuitSchema.statics.getWhatToShow_Unknown = function (idapp, username) { date_updated: 1, req_users: 1, refused_users: 1, + req_groups: 1, + refused_groups: 1, transactionsEnabled: 1, status: 1, 'mycities': 1, @@ -620,8 +646,8 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig if (circuittable) { const myqty = Math.abs(extrarec.qty); - const accountdestTable = await Account.getAccountByUsernameAndCircuitId(idapp, extrarec.dest, circuittable._id, true); - const accountorigTable = await Account.getAccountByUsernameAndCircuitId(idapp, usernameOrig, circuittable._id, true); + const accountdestTable = await Account.getAccountByUsernameAndCircuitId(idapp, extrarec.dest, circuittable._id, true, extrarec.groupdest); + const accountorigTable = await Account.getAccountByUsernameAndCircuitId(idapp, usernameOrig, circuittable._id, true, extrarec.grouporig); const circolantePrec = this.getCircolanteSingolaTransaz(accountorigTable, accountdestTable); @@ -658,7 +684,7 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig await Circuit.updateOne({ _id: circuittable }, { $set: paramstoupdate }); ris.result = true; - console.log('Inviate Monete da', usernameOrig, extrarec.dest, myqty, extrarec.causal); + console.log('Inviate Monete da', usernameOrig, extrarec.grouporig, extrarec.dest, extrarec.groupdest, myqty, extrarec.causal); ris.useraccounts = await Account.getUserAccounts(idapp, usernameOrig); @@ -666,7 +692,7 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig extrarec.saldoDest = accountdestTable.saldo; } else { - console.log('NON Inviate Monete da', usernameOrig, extrarec.dest, myqty, extrarec.causal); + console.log('NON Inviate Monete da', usernameOrig, extrarec.grouporig, extrarec.dest, extrarec.groupdest, myqty, extrarec.causal); } } @@ -688,6 +714,13 @@ CircuitSchema.statics.removeReqCircuit = async function (idapp, username, name) { $pull: { req_users: { username: { $in: [username] } } } }); }; +// Rimuovo la Richiesta del Gruppo sul Circuito +CircuitSchema.statics.removeReqGroupCircuit = async function (idapp, groupname, name) { + + return await Circuit.updateOne({ idapp, name }, + { $pull: { req_groups: { groupname: { $in: [groupname] } } } }); +}; + // Aggiungi agli utenti Rifiutati del Circuito CircuitSchema.statics.refuseReqCircuit = async function (idapp, username, name) { @@ -705,6 +738,21 @@ CircuitSchema.statics.refuseReqCircuit = async function (idapp, username, name) }; +CircuitSchema.statics.refuseReqGroupCircuit = async function (idapp, groupname, name) { + + return await Circuit.updateOne({ idapp, name }, + { + $push: + { + refused_groups: { + groupname, + date: new Date(), + }, + }, + }); + +}; + CircuitSchema.statics.updateData = async function (idapp, circuitname) { try { diff --git a/src/server/models/mygroup.js b/src/server/models/mygroup.js index d95fc9b..111d9be 100755 --- a/src/server/models/mygroup.js +++ b/src/server/models/mygroup.js @@ -75,8 +75,9 @@ const MyGroupSchema = new Schema({ }, admins: [ { - username: {type: String}, - date: {type: Date}, + username: { type: String }, + perm: { type: Number }, + date: { type: Date }, }, ], blocked: { @@ -97,34 +98,35 @@ const MyGroupSchema = new Schema({ req_users: [ { _id: false, - username: {type: String}, - date: {type: Date}, + username: { type: String }, + date: { type: Date }, }], // username refused_users: [ { _id: false, - username: {type: String}, - date: {type: Date}, + username: { type: String }, + date: { type: Date }, }], // username deleted: { type: Boolean, default: false, }, - circuits_list: [ + mycircuits: [ { - Num: { type: Number }, - inscription_date: {type: Date}, + _id: false, + circuitname: { type: String }, + date: { type: Date }, }], }); -MyGroupSchema.statics.getFieldsForSearch = function() { - return [{field: 'descr', type: tools.FieldType.string}]; +MyGroupSchema.statics.getFieldsForSearch = function () { + return [{ field: 'descr', type: tools.FieldType.string }]; }; -MyGroupSchema.statics.executeQueryTable = function(idapp, params, user) { +MyGroupSchema.statics.executeQueryTable = function (idapp, params, user) { params.fieldsearch = this.getFieldsForSearch(); - const {User} = require('./user'); + const { User } = require('./user'); if (params.options) { if (tools.isBitActive(params.options, shared_consts.OPTIONS_SEARCH_USER_ONLY_FULL_WORDS)) { @@ -137,9 +139,9 @@ MyGroupSchema.statics.executeQueryTable = function(idapp, params, user) { return tools.executeQueryTable(this, idapp, params, user); }; -MyGroupSchema.pre('save', async function(next) { +MyGroupSchema.pre('save', async function (next) { if (this.isNew) { - const myrec = await MyGroup.findOne().limit(1).sort({_id: -1}); + const myrec = await MyGroup.findOne().limit(1).sort({ _id: -1 }); if (!!myrec) { if (myrec._doc._id === 0) this._id = 1; @@ -156,71 +158,85 @@ MyGroupSchema.pre('save', async function(next) { next(); }); -MyGroupSchema.statics.findAllIdApp = async function(idapp) { - const myfind = {idapp}; +MyGroupSchema.statics.findAllIdApp = async function (idapp) { + const myfind = { idapp }; return await MyGroup.find(myfind); }; -MyGroupSchema.statics.findAllGroups = async function(idapp) { +MyGroupSchema.statics.findAllGroups = async function (idapp) { const whatToShow = this.getWhatToShow(idapp, ''); return await MyGroup.find({ idapp, $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], }, whatToShow); }; // Rimuovo la Richiesta del Gruppo -MyGroupSchema.statics.removeReqGroup = async function(idapp, username, groupnameDest) { +MyGroupSchema.statics.removeReqGroup = async function (idapp, username, groupnameDest) { - return await MyGroup.updateOne({idapp, groupname: groupnameDest}, - {$pull: {req_users: {username: {$in: [username]}}}}); + return await MyGroup.updateOne({ idapp, groupname: groupnameDest }, + { $pull: { req_users: { username: { $in: [username] } } } }); }; // Aggiungi agli utenti Rifiutati del Gruppo -MyGroupSchema.statics.refuseReqGroup = async function(idapp, username, groupnameDest) { +MyGroupSchema.statics.refuseReqGroup = async function (idapp, username, groupnameDest) { - return await MyGroup.updateOne({idapp, groupname: groupnameDest}, + return await MyGroup.updateOne({ idapp, groupname: groupnameDest }, + { + $push: { - $push: - { - refused_users: { - username, - date: new Date(), - }, - }, - }); + refused_users: { + username, + date: new Date(), + }, + }, + }); }; // Aggiungi agli Admin del Gruppo -MyGroupSchema.statics.addToAdminOfMyGroup = async function(idapp, username, groupnameDest) { +MyGroupSchema.statics.addToAdminOfMyGroup = async function (idapp, username, groupnameDest) { - return await MyGroup.updateOne({idapp, groupname: groupnameDest}, + return await MyGroup.updateOne({ idapp, groupname: groupnameDest }, + { + $push: { - $push: - { - admins: { - username, - date: new Date(), - }, - }, - }); + admins: { + username, + date: new Date(), + }, + }, + }); }; // Rimuovi dagli Admin del Gruppo -MyGroupSchema.statics.removeAdminOfMyGroup = async function(idapp, username, groupnameDest) { +MyGroupSchema.statics.removeAdminOfMyGroup = async function (idapp, username, groupnameDest) { - return await MyGroup.updateOne({idapp, groupname: groupnameDest}, - {$pull: {admins: {username: {$in: [username]}}}}); + return await MyGroup.updateOne({ idapp, groupname: groupnameDest }, + { $pull: { admins: { username: { $in: [username] } } } }); }; -MyGroupSchema.statics.getWhatToShow = function(idapp, username) { +MyGroupSchema.statics.getListAdminsByGroupName = async function (idapp, groupname) { + + let arr = await MyGroup.findOne({ + idapp, + groupname, + $or: [ + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], + }, {admins: 1}).lean(); + + return arr && arr.admins ? arr.admins : []; + +}; + +MyGroupSchema.statics.getWhatToShow = function (idapp, username) { // FOR ME, PERMIT ALL return { groupname: 1, @@ -242,12 +258,12 @@ MyGroupSchema.statics.getWhatToShow = function(idapp, username) { createdBy: 1, date_created: 1, date_updated: 1, - circuits_list: 1, + mycircuits: 1, }; }; -MyGroupSchema.statics.getWhatToShow_Unknown = function(idapp, username) { +MyGroupSchema.statics.getWhatToShow_Unknown = function (idapp, username) { return { groupname: 1, title: 1, @@ -259,14 +275,14 @@ MyGroupSchema.statics.getWhatToShow_Unknown = function(idapp, username) { note: 1, date_created: 1, date_updated: 1, - circuits_list: 1, + mycircuits: 1, }; }; -MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function( - idapp, groupname, field) { +MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function ( + idapp, groupname, field) { - const {User} = require('../models/user'); + const { User } = require('../models/user'); const myobj = {}; myobj[field + '.' + subfield] = 1; @@ -274,7 +290,7 @@ MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function( let arrrec = await User.findOne({ idapp, groupname, - $or: [{deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, myobj).then((ris) => ris ? ris._doc[field] : []); if (arrrec.length > 0) { @@ -284,7 +300,7 @@ MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function( }; -MyGroupSchema.statics.getInfoGroupByGroupname = async function(idapp, groupname) { +MyGroupSchema.statics.getInfoGroupByGroupname = async function (idapp, groupname) { const whatToShow = this.getWhatToShow(idapp, groupname); @@ -294,13 +310,13 @@ MyGroupSchema.statics.getInfoGroupByGroupname = async function(idapp, groupname) }; const query = [ - {$match: myfind}, - { $unwind: '$circuits_list' }, + { $match: myfind }, + { $unwind: '$mycircuits' }, { $lookup: { from: 'circuits', - localField: 'circuits_list.Num', - foreignField: 'Num', + localField: 'mycircuits.circuitname', + foreignField: 'name', as: 'mycircuits', }, }, @@ -319,7 +335,7 @@ MyGroupSchema.statics.getInfoGroupByGroupname = async function(idapp, groupname) }, }, }, - {$project: whatToShow}, + { $project: whatToShow }, ]; @@ -336,15 +352,15 @@ MyGroupSchema.statics.getInfoGroupByGroupname = async function(idapp, groupname) }; -MyGroupSchema.statics.deleteGroup = async function(idapp, usernameOrig, groupname) { +MyGroupSchema.statics.deleteGroup = async function (idapp, usernameOrig, groupname) { console.log('Gruppo ' + groupname + ' rimosso da ' + usernameOrig); - return await MyGroup.findOneAndRemove({idapp, groupname}); + return await MyGroup.findOneAndRemove({ idapp, groupname }); }; -MyGroupSchema.statics.getGroupsByUsername = async function(idapp, username, req) { +MyGroupSchema.statics.getGroupsByUsername = async function (idapp, username, req) { try { - const {User} = require('../models/user'); + const { User } = require('../models/user'); const whatToShow = this.getWhatToShow(idapp, username); const whatToShow_Unknown = this.getWhatToShow_Unknown(idapp, username); @@ -353,17 +369,17 @@ MyGroupSchema.statics.getGroupsByUsername = async function(idapp, username, req) let listUsersGroup = await User.find({ idapp, - username: {$in: arrUsernameGroups}, + username: { $in: arrUsernameGroups }, $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], }, whatToShow); let listgroups = await MyGroup.find({ idapp, $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], }, whatToShow_Unknown); /*let listRequestUsersGroup = await User.find({ @@ -379,21 +395,21 @@ MyGroupSchema.statics.getGroupsByUsername = async function(idapp, username, req) let listSentRequestGroups = await MyGroup.find({ idapp, 'req_users': { - $elemMatch: {username: {$eq: username}}, + $elemMatch: { username: { $eq: username } }, }, $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], }, whatToShow_Unknown); let listRefusedGroups = await MyGroup.find({ idapp, 'refused_users': { - $elemMatch: {username: {$eq: username}}, + $elemMatch: { username: { $eq: username } }, }, $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], }, whatToShow_Unknown); return { @@ -418,12 +434,12 @@ MyGroupSchema.statics.getGroupsByUsername = async function(idapp, username, req) }; }; -MyGroupSchema.statics.extractCitiesName = async function(idapp, id) { +MyGroupSchema.statics.extractCitiesName = async function (idapp, id) { try { let aggr1 = [ { - $match: {idapp, _id: id}, + $match: { idapp, _id: id }, }, { $lookup: { @@ -459,13 +475,42 @@ MyGroupSchema.statics.extractCitiesName = async function(idapp, id) { ris = await this.aggregate(aggr1); return ris; - }catch (e) { + } catch (e) { console.error('e', e); } }; +MyGroupSchema.statics.ifCircuitAlreadyInGroup = async function (idapp, groupname, circuitname) { + + // Controllo se è stato già inserito il circuito sul gruppo + return await this.findOne({ + idapp, + groupname, + 'mycircuits': { + $elemMatch: { circuitname: { $eq: circuitname } }, + }, + }).lean(); +}; + +// aggiungo il Circuito all'interno del Gruppo +MyGroupSchema.statics.addCircuitFromGroup = async function (idapp, groupname, circuitname) { + return await this.updateOne({ idapp, groupname }, + { $push: { 'mycircuits': { + circuitname, + date: new Date(), + } } }); + +}; + +// Rimuovo il Circuito all'interno del Gruppo +MyGroupSchema.statics.removeCircuitFromGroup = async function (idapp, groupname, circuitname) { + return await this.updateOne({ idapp, groupname }, + { $pull: { 'mycircuits': { circuitname: { $in: [circuitname] } } } }); + +}; + const MyGroup = mongoose.model('MyGroup', MyGroupSchema); -module.exports = {MyGroup}; +module.exports = { MyGroup }; diff --git a/src/server/models/sendnotif.js b/src/server/models/sendnotif.js index f65d7e3..83216f2 100755 --- a/src/server/models/sendnotif.js +++ b/src/server/models/sendnotif.js @@ -6,7 +6,7 @@ mongoose.level = 'F'; const i18n = require('i18n'); -const {ObjectID} = require('mongodb'); +const { ObjectID } = require('mongodb'); const shared_consts = require('../tools/shared_nodejs'); @@ -39,6 +39,14 @@ const sendNotifSchema = new Schema({ type: String, default: '', }, + sendergroup: { // mittente + type: String, + default: '', + }, + destgroup: { + type: String, + default: '', + }, title: { type: String, }, @@ -90,7 +98,7 @@ const sendNotifSchema = new Schema({ }, }); -sendNotifSchema.statics.setNotifAsRead = function(idapp, username, idnotif) { +sendNotifSchema.statics.setNotifAsRead = function (idapp, username, idnotif) { const SendNotif = this; try { @@ -98,15 +106,15 @@ sendNotifSchema.statics.setNotifAsRead = function(idapp, username, idnotif) { if (idnotif) { return SendNotif.findOneAndUpdate({ $and: [ - {idapp}, - {dest: username}, - {'_id': idnotif}, + { idapp }, + { dest: username }, + { '_id': idnotif }, ], $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], - }, {$set: {read: true}}, {new: false}).then((ret) => { + }, { $set: { read: true } }, { new: false }).then((ret) => { return !!ret; }).catch((err) => { console.error('err', err); @@ -117,7 +125,7 @@ sendNotifSchema.statics.setNotifAsRead = function(idapp, username, idnotif) { } }; -sendNotifSchema.statics.getRecNotif = function(id) { +sendNotifSchema.statics.getRecNotif = function (id) { const SendNotif = this; try { @@ -128,16 +136,16 @@ sendNotifSchema.statics.getRecNotif = function(id) { }; -sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, lastdataread, idapp) { +sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function (username, lastdataread, idapp) { const SendNotif = this; return SendNotif.find({ $and: [ - {idapp}, - {'dest': username}, - {'datenotif': {$gt: new Date(lastdataread)}}, + { idapp }, + { 'dest': username }, + { 'datenotif': { $gt: new Date(lastdataread) } }, ], - }).lean().sort({datenotif: -1}).then(async (arrnotif) => { + }).lean().sort({ datenotif: -1 }).then(async (arrnotif) => { // console.log('arrnotif', arrnotif.length); return this.compileOtherFields(arrnotif); @@ -148,7 +156,7 @@ sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, la }; -sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function(recnotif) { +sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif) { const numchars = 80; let newdescr = ''; @@ -275,8 +283,14 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function(recnotif) { newdescr = i18n.__('CIRCUIT_CREATED', userorig, recnotif.paramsObj.circuitnameDest); } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_ACCEPTED) { if (recnotif.paramsObj.isAdmin) { - newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS_CIRCUIT', userorig, recnotif.paramsObj.circuitnameDest, + if (recnotif.extrarec.groupname) { + newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS_CIRCUIT_MYGROUP', recnotif.extrarec.groupname, recnotif.paramsObj.circuitnameDest, recnotif.paramsObj.username_action); + } else { + newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS_CIRCUIT', userorig, recnotif.paramsObj.circuitnameDest, + recnotif.paramsObj.username_action); + } + recnotif.openUrl = '/my/' + userorig; } else { if (userorig === recnotif.paramsObj.usernameDest) { @@ -307,8 +321,13 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function(recnotif) { } tag = 'refcircuit'; } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REQUEST_TO_ENTER) { - newdescr = i18n.__('CIRCUIT_REQUEST_TO_ENTER', userorig, recnotif.paramsObj.circuitnameDest, + if (recnotif.extrarec.groupname) { + newdescr = i18n.__('CIRCUIT_REQUEST_TO_ENTER_WITH_GROUP', recnotif.extrarec.groupname, recnotif.paramsObj.circuitnameDest, recnotif.paramsObj.singleadmin_username); + } else { + newdescr = i18n.__('CIRCUIT_REQUEST_TO_ENTER', userorig, recnotif.paramsObj.circuitnameDest, + recnotif.paramsObj.singleadmin_username); + } tag = 'reqcircuits'; } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_DELETE_USER) { @@ -332,34 +351,36 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function(recnotif) { tag = 'removeadmincircuit'; } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ) { newdescr = i18n.__('CIRCUIT_SENDCOINSREQ', tools.getAhref(recnotif.paramsObj.username_action, await tools.getLinkUserTelegram(recnotif.idapp, recnotif.paramsObj.username_action)), recnotif.paramsObj.extrarec.qty.toString(), - recnotif.paramsObj.extrarec.symbol); + recnotif.paramsObj.extrarec.symbol); tag = 'sendcoin'; recnotif.openUrl = '/circuit/' + recnotif.paramsObj.path; //++Todo: dove lo mando ? } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ_SENT) { + let mydest = recnotif.paramsObj.extrarec.groupdest ? recnotif.paramsObj.extrarec.groupdest : recnotif.paramsObj.extrarec.dest; + newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_TO_ME', recnotif.paramsObj.extrarec.qty.toString(), - recnotif.paramsObj.extrarec.symbol, recnotif.paramsObj.extrarec.dest); + recnotif.paramsObj.extrarec.symbol, mydest); tag = 'sendcoin'; recnotif.openUrl = '/circuit/' + recnotif.paramsObj.path; //++Todo: dove lo mando ? } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED) { newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED', recnotif.paramsObj.extrarec.qty.toString(), recnotif.paramsObj.extrarec.symbol, - recnotif.paramsObj.username_action) + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, + recnotif.paramsObj.username_action) + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, recnotif.paramsObj.extrarec.symbol - ); + ); tag = 'sendcoin'; } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED_SENT) { newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_TO_ME', recnotif.paramsObj.extrarec.qty.toString(), - recnotif.paramsObj.extrarec.symbol, - recnotif.paramsObj.extrarec.dest) + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoOrig, + recnotif.paramsObj.extrarec.symbol, + recnotif.paramsObj.extrarec.dest) + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoOrig, recnotif.paramsObj.extrarec.symbol); tag = 'sendcoin'; } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED) { newdescr = i18n.__('ID_CIRCUIT_COINS_REFUSED', recnotif.paramsObj.extrarec.qty.toString(), recnotif.paramsObj.extrarec.symbol, - recnotif.paramsObj.username_action); + recnotif.paramsObj.username_action); tag = 'sendcoin'; } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED_SENT) { newdescr = i18n.__('ID_CIRCUIT_COINS_REFUSED_TO_ME', recnotif.paramsObj.extrarec.qty.toString(), recnotif.paramsObj.extrarec.symbol, - recnotif.paramsObj.extrarec.dest); - tag = 'sendcoin';ac + recnotif.paramsObj.extrarec.dest); + tag = 'sendcoin'; ac } } @@ -377,14 +398,14 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function(recnotif) { }; -sendNotifSchema.statics.compileOtherFields = async function(arrnotif) { +sendNotifSchema.statics.compileOtherFields = async function (arrnotif) { - const {User} = require('../models/user'); + const { User } = require('../models/user'); try { // Fill in the image profile of the semyinders ! for (const notif of arrnotif) { - let myimgprofile = await User.findOne({idapp: notif.idapp, username: notif.sender}, {'profile.img': 1}).lean(); + let myimgprofile = await User.findOne({ idapp: notif.idapp, username: notif.sender }, { 'profile.img': 1 }).lean(); if (myimgprofile && myimgprofile.profile.img) notif.myimgsender = 'upload/profile/' + notif.sender + '/' + myimgprofile.profile.img; } @@ -398,7 +419,7 @@ sendNotifSchema.statics.compileOtherFields = async function(arrnotif) { }; -sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function(username, idapp, limit) { +sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function (username, idapp, limit) { const SendNotif = this; return SendNotif.aggregate([ @@ -408,9 +429,9 @@ sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function(username, idap dest: username, }, }, - {$limit: limit}, + { $limit: limit }, { - $sort: {datenotif: -1}, + $sort: { datenotif: -1 }, }, ]).then(async (arrnotif) => { return this.compileOtherFields(arrnotif); @@ -421,14 +442,16 @@ sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function(username, idap }; -sendNotifSchema.statics.saveAndSendNotif = async function(myrecnotif, req, res, user) { +sendNotifSchema.statics.saveAndSendNotif = async function (myrecnotif, req, res, user) { const SendNotif = this; let idapp = req.body.idapp; - const check = tools.checkUserOk(myrecnotif.sender, user ? myrecnotif.sender : req.user.username, res); + let check = tools.checkUserOk(myrecnotif.sender, user ? myrecnotif.sender : req.user.username, res); + if (!check) + check = tools.checkUserOk(myrecnotif.sendergroup, user ? myrecnotif.sendergroup : req.user.username, res); if (check.exit) return check.ret; - const {myrecout, save} = await SendNotif.updateStatusAndDescr(myrecnotif, false); + const { myrecout, save } = await SendNotif.updateStatusAndDescr(myrecnotif, false); if (!myrecout) return null; @@ -458,7 +481,7 @@ sendNotifSchema.statics.saveAndSendNotif = async function(myrecnotif, req, res, }; -sendNotifSchema.statics.updateStatusAndDescr = async function(myrecnotif, onlysave) { +sendNotifSchema.statics.updateStatusAndDescr = async function (myrecnotif, onlysave) { const SendNotif = this; try { @@ -474,6 +497,8 @@ sendNotifSchema.statics.updateStatusAndDescr = async function(myrecnotif, onlysa let sender = myrecnotif.sender; let newdest = myrecnotif.dest; + let sendergroup = myrecnotif.sendergroup; + let newdestgroup = myrecnotif.destgroup; // Controllare se devo modificare un Notif già esistente ! if (myrecnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FRIENDS) { @@ -550,6 +575,8 @@ sendNotifSchema.statics.updateStatusAndDescr = async function(myrecnotif, onlysa datenotif: new Date(), sender, dest: newdest, + sendergroup, + destgroup: newdestgroup, }; let query = { @@ -569,13 +596,13 @@ sendNotifSchema.statics.updateStatusAndDescr = async function(myrecnotif, onlysa } // Cerca il record e se lo trova lo aggiorna - const myrec = await SendNotif.findOneAndUpdate(query, {$set: fields_to_update}, { + const myrec = await SendNotif.findOneAndUpdate(query, { $set: fields_to_update }, { new: true, returnNewDocument: true, }); if (myrec) { - return {myrecout: myrec, save: false}; + return { myrecout: myrec, save: false }; } } @@ -584,19 +611,19 @@ sendNotifSchema.statics.updateStatusAndDescr = async function(myrecnotif, onlysa myrecnotif.status = newstatus; } - return {myrecout: myrecnotif, save: true}; + return { myrecout: myrecnotif, save: true }; } catch (e) { console.error(e); - return {myrecout: null, save: false}; + return { myrecout: null, save: false }; } }; -sendNotifSchema.statics.getStatus = async function(notifId) { +sendNotifSchema.statics.getStatus = async function (notifId) { const SendNotif = this; try { - return await SendNotif.findOne({_id: notifId}, {status: 1}).lean().then((rec) => rec.status); + return await SendNotif.findOne({ _id: notifId }, { status: 1 }).lean().then((rec) => rec.status); } catch (e) { return 0; @@ -604,7 +631,7 @@ sendNotifSchema.statics.getStatus = async function(notifId) { }; -sendNotifSchema.statics.checkIfCoinsAlreadySent = async function(notifId) { +sendNotifSchema.statics.checkIfCoinsAlreadySent = async function (notifId) { const SendNotif = this; try { @@ -612,7 +639,7 @@ sendNotifSchema.statics.checkIfCoinsAlreadySent = async function(notifId) { if (status !== null) { return (status === shared_consts.CircuitsNotif.STATUS_COINS_ACCEPTED) || - (status === shared_consts.CircuitsNotif.STATUS_COINS_REFUSED); + (status === shared_consts.CircuitsNotif.STATUS_COINS_REFUSED); } return true; @@ -624,11 +651,11 @@ sendNotifSchema.statics.checkIfCoinsAlreadySent = async function(notifId) { }; -sendNotifSchema.statics.saveNotif = async function(myrecnotif) { +sendNotifSchema.statics.saveNotif = async function (myrecnotif) { const SendNotif = this; - const {myrecout, save} = await SendNotif.updateStatusAndDescr(myrecnotif, true); + const { myrecout, save } = await SendNotif.updateStatusAndDescr(myrecnotif, true); if (!myrecout) return null; @@ -644,14 +671,16 @@ sendNotifSchema.statics.saveNotif = async function(myrecnotif) { }; -sendNotifSchema.statics.getDefaultRec = function(req) { +sendNotifSchema.statics.getDefaultRec = function (req) { return { idapp: req.body.idapp, typedir: '', typeid: '', sender: req.user ? req.user.username : '', + sendergroup: '', dest: '', + destgroup: '', descr: '', openUrl: '', datenotif: new Date(), @@ -663,7 +692,7 @@ sendNotifSchema.statics.getDefaultRec = function(req) { }; -sendNotifSchema.statics.getExtraParam = function(myrecnotif, paramsObj) { +sendNotifSchema.statics.getExtraParam = function (myrecnotif, paramsObj) { let out = myrecnotif; //if (myrecnotif._doc) { //out = myrecnotif._doc @@ -681,7 +710,7 @@ sendNotifSchema.statics.getExtraParam = function(myrecnotif, paramsObj) { return myrecnotif; }; -sendNotifSchema.statics.createNewNotification = async function(req, res, paramsObj, table, rec, typedir, typeid) { +sendNotifSchema.statics.createNewNotification = async function (req, res, paramsObj, table, rec, typedir, typeid) { const SendNotif = this; try { @@ -705,7 +734,7 @@ sendNotifSchema.statics.createNewNotification = async function(req, res, paramsO } }; -sendNotifSchema.statics.createNewNotifToSingleUser = async function(req, res, paramsObj, onlysave, typedir, typeid) { +sendNotifSchema.statics.createNewNotifToSingleUser = async function (req, res, paramsObj, onlysave, typedir, typeid) { const SendNotif = this; try { @@ -723,13 +752,13 @@ sendNotifSchema.statics.createNewNotifToSingleUser = async function(req, res, pa } }; -sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, req, res) { +sendNotifSchema.statics.sendToTheDestinations = async function (myrecnotifpass, req, res) { const SendNotif = this; - const {User} = require('../models/user'); + const { User } = require('../models/user'); - const {City} = require('../models/city'); - const {Province} = require('../models/province'); + const { City } = require('../models/city'); + const { Province } = require('../models/province'); try { @@ -737,8 +766,8 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, r const userlist = await User.find({ idapp: myrecnotifpass.idapp, $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], }, { name: 1, surname: 1, @@ -760,9 +789,9 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, r const mytable = globalTables.getTableByTableName(myrecnotifpass.tablerec); if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec) || - shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)) { + shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)) { - const myrectableorig = await mytable.findOne({_id: myrecnotifpass.idrec}).lean(); + const myrectableorig = await mytable.findOne({ _id: myrecnotifpass.idrec }).lean(); if (myrectableorig) { for (const city of myrectableorig.idCity) { arrprovinces.push(await City.getProvinceByIdCity(city)); @@ -790,16 +819,16 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, r let send = false; if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec) || - shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)) { + shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)) { // Estrai la Città, la Provincia e la regione. if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_PROVINCE) && - user.profile.notif_provinces && user.profile.notif_provinces.some(r => arrprovinces.indexOf(r) >= 0)) { + user.profile.notif_provinces && user.profile.notif_provinces.some(r => arrprovinces.indexOf(r) >= 0)) { send = true; } if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_REGION) && - user.profile.notif_regions && user.profile.notif_regions.some(r => arrregions.indexOf(r) >= 0)) { + user.profile.notif_regions && user.profile.notif_regions.some(r => arrregions.indexOf(r) >= 0)) { send = true; } @@ -836,15 +865,15 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotifpass, r }; -sendNotifSchema.statics.sendToSingleUserDest = async function(myrecnotif, req, res, onlysave) { +sendNotifSchema.statics.sendToSingleUserDest = async function (myrecnotif, req, res, onlysave) { const SendNotif = this; try { myrecnotif.dest = myrecnotif.paramsObj && myrecnotif.paramsObj.usernameDest ? myrecnotif.paramsObj.usernameDest : ''; myrecnotif.username_worked = myrecnotif.paramsObj && myrecnotif.paramsObj.username_worked - ? myrecnotif.paramsObj.username_worked - : myrecnotif.dest; + ? myrecnotif.paramsObj.username_worked + : myrecnotif.dest; if (onlysave) { return await SendNotif.saveNotif(myrecnotif); @@ -859,13 +888,14 @@ sendNotifSchema.statics.sendToSingleUserDest = async function(myrecnotif, req, r }; -sendNotifSchema.statics.getSumPendingTransactions = async function(idapp, username, circuitname) { +sendNotifSchema.statics.getSumPendingTransactions = async function (idapp, username, circuitname, groupname) { const SendNotif = this; try { const query = { idapp, sender: username, + sendergroup: groupname, typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS, typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ, status: 0, @@ -882,4 +912,4 @@ sendNotifSchema.statics.getSumPendingTransactions = async function(idapp, userna const SendNotif = mongoose.model('SendNotif', sendNotifSchema); -module.exports = {SendNotif: SendNotif}; +module.exports = { SendNotif: SendNotif }; diff --git a/src/server/models/user.js b/src/server/models/user.js index 4563582..9636915 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -70,7 +70,7 @@ const UserSchema = new mongoose.Schema({ type: String, required: true, trim: true, - minlength: 6, + minlength: 3, unique: false, }, name: { @@ -421,8 +421,7 @@ const UserSchema = new mongoose.Schema({ type: Number, }], }, -}) - ; +}); UserSchema.methods.toJSON = function () { const user = this; @@ -2270,77 +2269,151 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn result: false, }; let update = {}; + + let groupname = extrarec && extrarec.groupname ? extrarec.groupname : ''; + try { if (cmd === shared_consts.CIRCUITCMD.SET) { - const foundIfAlreadyCircuit = await this.ifAlreadyInCircuit(idapp, usernameOrig, circuitname); + if (groupname) { + const foundIfCircuitInGroup = await MyGroup.ifCircuitAlreadyInGroup(idapp, groupname, circuitname); - if (!foundIfAlreadyCircuit) { - update = { - $push: { - 'profile.mycircuits': { - circuitname, - date: new Date(), - }, - }, - }; - ris = await User.updateOne({ idapp, username: usernameOrig }, update); + if (!foundIfCircuitInGroup) { + ris = await MyGroup.addCircuitFromGroup(idapp, groupname, circuitname); - // Elimina la richiesta: - update = { $pull: { req_users: { username: { $in: [usernameOrig] } } } }; - await Circuit.updateOne({ idapp, name: circuitname }, update); + // Elimina la richiesta: + update = { $pull: { req_groups: { groupname: { $in: [groupname] } } } }; + await Circuit.updateOne({ idapp, name: circuitname }, update); - // Elimina eventualmente se era bloccato: - update = { $pull: { refused_users: { username: { $in: [usernameOrig] } } } }; - await Circuit.updateOne({ idapp, name: circuitname }, update); + // Elimina eventualmente se era bloccato: + update = { $pull: { refused_groups: { groupname: { $in: [groupname] } } } }; + await Circuit.updateOne({ idapp, name: circuitname }, update); - await Account.createAccount(idapp, usernameOrig, circuitname); + await Account.createAccount(idapp, '', circuitname, groupname); + } else { + ris = false; + } + + await Circuit.updateData(idapp, circuitname) + if (ris) { + // Invia una notifica alla persona e agli Admin + tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, value, true, username_action, extrarec); + outres.result = await Circuit.getInfoCircuitByName(idapp, circuitname); + } + } else { - ris = false; - } + const foundIfAlreadyCircuit = await this.ifAlreadyInCircuit(idapp, usernameOrig, circuitname); - await Circuit.updateData(idapp, circuitname) - if (ris) { - // Invia una notifica alla persona e agli Admin - tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, value, true, username_action, extrarec); - outres.result = await Circuit.getInfoCircuitByName(idapp, circuitname); - } - } else if (cmd === shared_consts.CIRCUITCMD.REQ) { - // Aggiungo la richiesta di Gruppo a me - const foundIfAlreadyAskCircuit = await Circuit.findOne({ - idapp, - name: circuitname, - 'req_users': { - $elemMatch: { username: { $eq: usernameOrig } }, - }, - }); - - if (value) { - if (!foundIfAlreadyAskCircuit) { + if (!foundIfAlreadyCircuit) { update = { $push: { - 'req_users': { - username: usernameOrig, + 'profile.mycircuits': { + circuitname, date: new Date(), }, }, }; - ris = await Circuit.updateOne({ idapp, name: circuitname }, update); + ris = await User.updateOne({ idapp, username: usernameOrig }, update); + // Elimina la richiesta: + update = { $pull: { req_users: { username: { $in: [usernameOrig] } } } }; + await Circuit.updateOne({ idapp, name: circuitname }, update); + + // Elimina eventualmente se era bloccato: + update = { $pull: { refused_users: { username: { $in: [usernameOrig] } } } }; + await Circuit.updateOne({ idapp, name: circuitname }, update); + + await Account.createAccount(idapp, usernameOrig, circuitname); + + + } else { + ris = false; } + + await Circuit.updateData(idapp, circuitname) if (ris) { - // Invia una notifica alla persona - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, true, true, username_action, extrarec); - } - } else { - if (foundIfAlreadyAskCircuit) { - outres.result = await this.removeFromCircuits(idapp, usernameOrig, circuitname); // Rimuovo il Gruppo da me - - // Invia una notifica alla persona - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); + // Invia una notifica alla persona e agli Admin + tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, value, true, username_action, extrarec); + outres.result = await Circuit.getInfoCircuitByName(idapp, circuitname); } } + } else if (cmd === shared_consts.CIRCUITCMD.REQ) { + + if (groupname) { + // Aggiungo la richiesta di Gruppo a me + const foundIfAlreadyAskCircuit = await Circuit.findOne({ + idapp, + name: circuitname, + 'req_groups': { + $elemMatch: { groupname: { $eq: groupname } }, + }, + }); + + if (value) { + if (!foundIfAlreadyAskCircuit) { + update = { + $push: { + 'req_groups': { + groupname, + date: new Date(), + }, + }, + }; + ris = await Circuit.updateOne({ idapp, name: circuitname }, update); + + } + if (ris) { + // Invia una notifica alla persona + await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, true, true, username_action, extrarec); + } + } else { + if (foundIfAlreadyAskCircuit) { + outres.result = await MyGroup.removeCircuitFromGroup(idapp, groupname, circuitname); // Rimuovo il Circuito dal gruppo + + // Invia una notifica alla persona + await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); + } + } + + } else { + // Aggiungo la richiesta di Gruppo a me + const foundIfAlreadyAskCircuit = await Circuit.findOne({ + idapp, + name: circuitname, + 'req_users': { + $elemMatch: { username: { $eq: usernameOrig } }, + }, + }); + + if (value) { + if (!foundIfAlreadyAskCircuit) { + update = { + $push: { + 'req_users': { + username: usernameOrig, + date: new Date(), + }, + }, + }; + ris = await Circuit.updateOne({ idapp, name: circuitname }, update); + + } + if (ris) { + // Invia una notifica alla persona + await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, true, true, username_action, extrarec); + } + } else { + if (foundIfAlreadyAskCircuit) { + outres.result = await this.removeFromCircuits(idapp, usernameOrig, circuitname); // Rimuovo il Gruppo da me + + // Invia una notifica alla persona + await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); + } + } + + } + } else if (cmd === shared_consts.CIRCUITCMD.REMOVE_FROM_MYLIST) { @@ -2368,16 +2441,24 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn } else if (cmd === shared_consts.CIRCUITCMD.CANCEL_REQ) { - outres.result = await Circuit.removeReqCircuit(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me + if (groupname) + outres.result = await Circuit.removeReqGroupCircuit(idapp, groupname, circuitname); // Rimuovo l'Amicizia da me + else + outres.result = await Circuit.removeReqCircuit(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me + await Circuit.updateData(idapp, circuitname) } else if (cmd === shared_consts.CIRCUITCMD.REFUSE_REQ) { - outres.result = await this.removeFromCircuits(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me - - outres.result = await Circuit.removeReqCircuit(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me - - outres.result = await Circuit.refuseReqCircuit(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me + if (groupname) { + outres.result = await MyGroup.removeCircuitFromGroup(idapp, groupname, circuitname); // Rimuovo l'Amicizia da me + outres.result = await Circuit.removeReqGroupCircuit(idapp, groupname, circuitname); // Rimuovo l'Amicizia da me + outres.result = await Circuit.refuseReqGroupCircuit(idapp, groupname, circuitname); // Rimuovo l'Amicizia da me + } else { + outres.result = await this.removeFromCircuits(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me + outres.result = await Circuit.removeReqCircuit(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me + outres.result = await Circuit.refuseReqCircuit(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me + } // Invia una notifica alla persona await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); @@ -2438,6 +2519,7 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT && outcheck.cansend) { if (!await Movement.checkIfCoinsAlreadySent(extrarec.notifId)) { outres = await Circuit.sendCoins(false, idapp, usernameOrig, extrarec); + } else { outcheck.cansend = false; //GIA INVIATO } @@ -2446,6 +2528,10 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn if (outcheck.cansend) { // Invia una notifica di moneta (accettata o rifiutata) alla persona const out = await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); + + if (outres && extrarec.groupname) { + // Setta agli altri admin, + } } outres.recnotif = await SendNotif.getRecNotif(extrarec.notifId); @@ -2466,6 +2552,7 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn outres.userprofile = userprofile; } outres.listcircuits = await Circuit.findAllIdApp(idapp); + outres.mygroups = await MyGroup.findAllGroups(idapp); } if (circuitname) @@ -3299,7 +3386,7 @@ UserSchema.statics.getUsersRegistered = async function (idapp) { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getUsersRegisteredToday = async function (idapp) { @@ -3314,7 +3401,7 @@ UserSchema.statics.getUsersRegisteredToday = async function (idapp) { date_reg: { $gt: starttoday }, }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getUsersOnLineToday = async function (idapp) { @@ -3329,7 +3416,7 @@ UserSchema.statics.getUsersOnLineToday = async function (idapp) { lasttimeonline: { $gt: starttoday }, }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; /* @@ -3398,7 +3485,7 @@ UserSchema.statics.getEmailNotVerified = async function (idapp) { verified_email: false, }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getUsersTelegramAttivo = async function (idapp) { @@ -3410,7 +3497,7 @@ UserSchema.statics.getUsersTelegramAttivo = async function (idapp) { 'profile.teleg_id': { $gt: 0 }, }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getUsersAutorizzati = async function (idapp) { @@ -3423,7 +3510,7 @@ UserSchema.statics.getUsersAutorizzati = async function (idapp) { verified_by_aportador: true, }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getUsersAutorizzare = async function (idapp) { @@ -3436,7 +3523,7 @@ UserSchema.statics.getUsersAutorizzare = async function (idapp) { verified_by_aportador: { $exists: false }, }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getUsersTelegramPending = async function (idapp) { @@ -3448,7 +3535,7 @@ UserSchema.statics.getUsersTelegramPending = async function (idapp) { 'profile.teleg_checkcode': { $gt: 0 }, }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getNumUsers = async function (idapp) { @@ -3459,7 +3546,7 @@ UserSchema.statics.getNumUsers = async function (idapp) { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getUsersZoom = async function (idapp) { @@ -3471,7 +3558,7 @@ UserSchema.statics.getUsersZoom = async function (idapp) { 'profile.saw_zoom_presentation': true, }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getUsersResidenti = async function (idapp) { @@ -3495,7 +3582,7 @@ UserSchema.statics.getSaw_and_Accepted = async function (idapp) { 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED, }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getUsersDreams = async function (idapp) { @@ -3508,7 +3595,7 @@ UserSchema.statics.getUsersDreams = async function (idapp) { '$expr': { '$gt': [{ '$strLenCP': '$profile.my_dream' }, 10] }, }; - return await User. countDocuments(myfind); + return await User.countDocuments(myfind); }; UserSchema.statics.getLastUsers = async function (idapp) { diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index f68f77d..2278118 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -10,11 +10,11 @@ const appTelegramDest = [tools.FREEPLANET, tools.FREEPLANET, tools.FREEPLANET]; const printf = require('util').format; -const {User} = require('../models/user'); -const {MyGroup} = require('../models/mygroup'); -const {Circuit} = require('../models/circuit'); -const {CalZoom} = require('../models/calzoom'); -const {MyBot} = require('../models/bot'); +const { User } = 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'); @@ -22,7 +22,7 @@ const sharp = require('sharp'); const server_constants = require('../tools/server_constants'); // const {ListaIngresso} = require('../models/listaingresso'); -const {MsgTemplate} = require('../models/msg_template'); +const { MsgTemplate } = require('../models/msg_template'); const globalTables = require('../tools/globalTables'); @@ -33,7 +33,7 @@ const i18n = require('i18n'); let url = process.env.URL || 'https://'; const Benvenuto = emoji.get('heartbeat') + emoji.get('heartbeat') + - emoji.get('heartbeat') + ' Benvenuto!'; + emoji.get('heartbeat') + ' Benvenuto!'; const emo = { JOY: emoji.get('joy'), @@ -215,8 +215,8 @@ MsgBot = { const MsgRisp = { CHAT_EMPOWER: 'Entra nella Chat EMPOWER !!!\n' + - 'https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g ' + emo.PURPLE_HEART + - emo.GIFT_HEART + emo.BLUE_HEART, + 'https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g ' + emo.PURPLE_HEART + + emo.GIFT_HEART + emo.BLUE_HEART, }; function getemojibynumber(number) { @@ -266,7 +266,7 @@ const Menu = { // MSG_NO_9_REQ: emoji.get('incoming_envelope') + 'No 9 Req', // NESSUN_IMBARCO_7REQ: emoji.get('incoming_envelope') + 'No Imbarco (7 Req)', MSG_SI_INVITATI_NO_7REQ_INVITATI: emoji.get('incoming_envelope') + - 'Inv e NO 7 Req', + 'Inv e NO 7 Req', MSGSTAFF: emoji.get('incoming_envelope') + ' Invia a STAFF', MSGPAOLO: emoji.get('incoming_envelope') + ' Invia a PAOLO', RESTART_SRV: emoji.get('incoming_envelope') + 'Restart-NodeJs', @@ -399,12 +399,12 @@ const MenuLang = { }; const MenuYesNo = { - it: {menu: [[Menu.it.SI, Menu.it.NO]]}, - es: {menu: [[Menu.es.SI, Menu.es.NO]]}, - fr: {menu: [[Menu.fr.SI, Menu.fr.NO]]}, - si: {menu: [[Menu.si.SI, Menu.si.NO]]}, - pt: {menu: [[Menu.pt.SI, Menu.pt.NO]]}, - enUs: {menu: [[Menu.enUs.SI, Menu.enUs.NO]]}, + it: { menu: [[Menu.it.SI, Menu.it.NO]] }, + es: { menu: [[Menu.es.SI, Menu.es.NO]] }, + fr: { menu: [[Menu.fr.SI, Menu.fr.NO]] }, + si: { menu: [[Menu.si.SI, Menu.si.NO]] }, + pt: { menu: [[Menu.pt.SI, Menu.pt.NO]] }, + enUs: { menu: [[Menu.enUs.SI, Menu.enUs.NO]] }, }; const MenuAdmin = { @@ -424,12 +424,12 @@ const MenuSend = { }; const MenuChat = { - it: {menu: [[Menu.it.ESCI_DA_CHAT, Menu.it.INDIETRO]]}, - es: {menu: [[Menu.es.ESCI_DA_CHAT, Menu.es.INDIETRO]]}, - fr: {menu: [[Menu.fr.ESCI_DA_CHAT, Menu.fr.INDIETRO]]}, - si: {menu: [[Menu.si.ESCI_DA_CHAT, Menu.si.INDIETRO]]}, - pt: {menu: [[Menu.pt.ESCI_DA_CHAT, Menu.pt.INDIETRO]]}, - enUs: {menu: [[Menu.enUs.ESCI_DA_CHAT, Menu.enUs.INDIETRO]]}, + it: { menu: [[Menu.it.ESCI_DA_CHAT, Menu.it.INDIETRO]] }, + es: { menu: [[Menu.es.ESCI_DA_CHAT, Menu.es.INDIETRO]] }, + fr: { menu: [[Menu.fr.ESCI_DA_CHAT, Menu.fr.INDIETRO]] }, + si: { menu: [[Menu.si.ESCI_DA_CHAT, Menu.si.INDIETRO]] }, + pt: { menu: [[Menu.pt.ESCI_DA_CHAT, Menu.pt.INDIETRO]] }, + enUs: { menu: [[Menu.enUs.ESCI_DA_CHAT, Menu.enUs.INDIETRO]] }, }; const Sex = { @@ -476,7 +476,7 @@ const StatusMSGALL = { const txt = { MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Scegli una voce di menu:' + - emoji.get('dizzy'), + emoji.get('dizzy'), MSG_ASK_USERNAME_BO: 'Scrivete nel messaggio l\'username (SENZA SPAZI) o la email con cui vi siete registrati sul sito di %s:', MSG_ASK_USERNAME_INVITANTE: 'Scrivi l\'username telegram di chi ti ha invitato su %s (senza spazi)', MSG_NEW_REG: '
Se non ce l\'avete, entrate sul Canale (PROGETTO RISO), trovate la vostra provincia e chiedete di entrare nel gruppo.', @@ -488,22 +488,22 @@ const txt = { MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attenzione! Devi inserire solo il codice a 6 cifre', MSG_VERIFY_CODE: '1. Ora ritorna sul sito:\n%s\n2. Copia il codice di Autenticazione (di 6 cifre) che troverai scritto in alto\n3. Scrivilo (o incollalo) qui sotto come messaggio:', MSG_ERR_VERIFY_CODE: 'Codice di Verifica Errato!' + emo.EXCLAMATION_MARK + - '\nControlla sul sito %s e riscrivi il nuovo codice di 6 cifre.', + '\nControlla sul sito %s e riscrivi il nuovo codice di 6 cifre.', MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', MSG_RESETPWD: 'Clicca qui per impostare una nuova password per accedere alla APP:', MSG_ERR_UNKNOWN_VERIFY_CODE: 'Errore durante il salvataggio sul Server. Riprovare piú tardi', MSG_EXIT_TELEGRAM: 'L\'account è stato ora scollegato da questo Telegram BOT.', MSG_APORTADOR_USER_REGISTERED: emo.FIRE + - ' Si è appena Registrato "%s" (n. %s)\nInvitato da %s', + ' Si è appena Registrato "%s" (n. %s)\nInvitato da %s', MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ Abilita Nuova Registrazione:', MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:', MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Amicizia di %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', + '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 !', + '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Abilitato !', MSG_ISCRITTO_CONACREIS: emo.FIRE + '[%s] Si è appena Iscritto al Conacreis "%s"', MSG_ISCRITTO_ARCADEI: emo.FIRE + '[%s] Si è appena Iscritto ad Arcadei "%s"', @@ -511,23 +511,23 @@ const txt = { MSG_MSG_TOSENT: emoji.get('envelope') + ' Messaggi da Inviare', MSG_MSG_INCORSO: emoji.get('envelope') + ' messaggi in corso... Inviati attualmente', MSG_SET_USERNAME_TELEGRAM: '[Prima di continuare con la registrazione in RISO.APP]\n' + - 'Segui questi passi per IMPOSTARE UN USERNAME IN TELEGRAM: \n\n' + - '1. premi sull\'icona con 3 linee orizzontali, in alto a sinistra (sull\'iPhone si chiama "Impostazioni").\n' + - 'premi il tasto INDIETRO del cellulare (si chiuderà questa chat).\n\n' + - '2. Seleziona la voce IMPOSTAZIONI dalla lista.\n\n' + - '3.Premi su USERNAME nella sezione account.\n\n' + - '4. Digita un username (o nome utente) qualsiasi a tua scelta, se è già usato aggiungi dei numeri.\n\n' + - '5. Per confermare premi sull\'icona con la spunta (V) in alto a destra.\n\n' + - '🏁 6. Infine ritorna su questa chat BOT e scrivi OK nel messaggio. \n\n' + - ' Se non riesci a fare questi passaggi, clicca qui: \n' + - '👉🏻 https://www.nigiara.it/telegram/come-impostare-uno-username-su-telegram.htm ', + 'Segui questi passi per IMPOSTARE UN USERNAME IN TELEGRAM: \n\n' + + '1. premi sull\'icona con 3 linee orizzontali, in alto a sinistra (sull\'iPhone si chiama "Impostazioni").\n' + + 'premi il tasto INDIETRO del cellulare (si chiuderà questa chat).\n\n' + + '2. Seleziona la voce IMPOSTAZIONI dalla lista.\n\n' + + '3.Premi su USERNAME nella sezione account.\n\n' + + '4. Digita un username (o nome utente) qualsiasi a tua scelta, se è già usato aggiungi dei numeri.\n\n' + + '5. Per confermare premi sull\'icona con la spunta (V) in alto a destra.\n\n' + + '🏁 6. Infine ritorna su questa chat BOT e scrivi OK nel messaggio. \n\n' + + ' Se non riesci a fare questi passaggi, clicca qui: \n' + + '👉🏻 https://www.nigiara.it/telegram/come-impostare-uno-username-su-telegram.htm ', MSG_SIGNUP: 'Per registrarti su %s:', }; const txt_es = { MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Elija un elemento del menú:' + - emoji.get('dizzy'), + emoji.get('dizzy'), MSG_ASK_USERNAME_BO: 'Escriba en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio de %s:', MSG_ERRORE_USERNAME: '¡Atención! Debes introducir sólo el nombre de usuario (40 caracteres como máximo)', MSG_ERRORE_USERNAME_NOT_FOUND: 'Para completar la verificación del telegrama BOT, ahora debe escribir en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio.:', @@ -536,31 +536,31 @@ const txt_es = { MSG_ERRORE_VERIFY_CODE_MAXLEN: '¡Atención! Sólo tienes que introducir el código de 6 dígitos', MSG_VERIFY_CODE: '1. Ahora, de vuelta en el sitio web:\n%s\n2. Copie el código de autenticación (6 dígitos) que encontrará escrito en la parte superior de la página\n3. Escríbelo (o pégalo) abajo como un mensaje:', MSG_ERR_VERIFY_CODE: 'Código de verificación incorrecto!' + - emo.EXCLAMATION_MARK + - '\nComprueba en el sitio %s y reescribe el nuevo código de 6 dígitos.', + emo.EXCLAMATION_MARK + + '\nComprueba en el sitio %s y reescribe el nuevo código de 6 dígitos.', MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', MSG_ERR_UNKNOWN_VERIFY_CODE: 'Error al guardar en el servidor. Inténtalo de nuevo más tarde.', MSG_EXIT_TELEGRAM: 'La cuenta ha sido desconectada de Telegram BOT.', MSG_APORTADOR_USER_REGISTERED: emo.FIRE + - ' Acaba de registrarse "%s (n. %s)"\n(Invitado de %s)', + ' Acaba de registrarse "%s (n. %s)"\n(Invitado de %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!', 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 !', + '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + - '🚫 %s Non è stato Abilitato !', + '🚫 %s Non è stato Abilitato !', MSG_MSG_SENT: emoji.get('envelope') + ' Mensajes enviados !', MSG_MSG_TOSENT: emoji.get('envelope') + ' Mensajes a enviar', MSG_MSG_INCORSO: emoji.get('envelope') + - ' mensajes en progreso... Enviado actualmente', + ' mensajes en progreso... Enviado actualmente', }; const txt_fr = { MSG_SCEGLI_MENU: emoji.get('dizzy') + 'Choisissez un élément de menu:' + - emoji.get('dizzy'), + emoji.get('dizzy'), MSG_ASK_USERNAME_BO: 'Écrivez dans le message l\'username ou l\'e-mail avec lequel vous vous êtes enregistré sur le site de %s: ', MSG_ERRORE_USERNAME: 'Attention! Vous devez insérer seulement l’username (40 caractères maximum)', MSG_ERRORE_USERNAME_NOT_FOUND: 'Pour Compléter la Vérification Telegram BOT, vous devez maintenant écrire dans le message ci-dessous l\'Username ou l\'adresse e-mail avec lequel vous vous êtes inscrit sur le site: ', @@ -569,26 +569,26 @@ const txt_fr = { MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attention! Vous devez insérer seulement le code à 6 chiffres', MSG_VERIFY_CODE: '1. Ᾱ présent retournez sur le site:\n%s\n2. Copiez le Code d’Authentification (de 6 chiffres) che vous trouverez écrit en haut \n3. Ecrivez-le (ou copiez-le) ci-dessous comme message:', MSG_ERR_VERIFY_CODE: ' Code de vérification incorrect!' + - emo.EXCLAMATION_MARK + - '\nControllez sur le site %s et réécrivez le nouveau code à 6 chiffres.', + emo.EXCLAMATION_MARK + + '\nControllez sur le site %s et réécrivez le nouveau code à 6 chiffres.', MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', MSG_ERR_UNKNOWN_VERIFY_CODE: 'Erreur lors de l\'enregistrement sur le serveur. Retentez plus tard', MSG_EXIT_TELEGRAM: 'L\'account a été déconnecté de Telegram BOT.', MSG_APORTADOR_USER_REGISTERED: emo.FIRE + - ' Vous venez à peine de vous inscrire "%s (n. %s) %s', + ' Vous venez à peine de vous inscrire "%s (n. %s) %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!', 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 !', + '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + - '🚫 %s Non è stato Abilitato !', + '🚫 %s Non è stato Abilitato !', MSG_MSG_SENT: emoji.get('envelope') + ' Messages envoyés !', MSG_MSG_TOSENT: emoji.get('envelope') + ' Messages à envoyer', MSG_MSG_INCORSO: emoji.get('envelope') + - ' messages en cours... Actuellement envoyé', + ' messages en cours... Actuellement envoyé', }; const txt_si = { @@ -601,26 +601,26 @@ const txt_si = { MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Pozor! Vstavi D mestno kodo', MSG_VERIFY_CODE: '1. Vrni se na spletno strani: \n%s\n2. Kopiraj kodo Authenticazione (6 mestno) ki jo najdeš zgoraj zapisano\n3. Napiši (ali prilepi) tu spodaj kot sporočilo: ', MSG_ERR_VERIFY_CODE: 'Napačna koda za preverjanje!' + emo.EXCLAMATION_MARK + - '\nPreveri na strani %s in ponovno napiši 6 mestno kodo.', + '\nPreveri na strani %s in ponovno napiši 6 mestno kodo.', MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', MSG_ERR_UNKNOWN_VERIFY_CODE: 'Napaka strežnika.Poskusi kasneje ', MSG_EXIT_TELEGRAM: 'Račun se nahaja v programu Telegram BOT.', MSG_APORTADOR_USER_REGISTERED: emo.FIRE + - 'Registracija registracije %s (n. %s)\n(povabil ga %s)', + 'Registracija registracije %s (n. %s)\n(povabil ga %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!', 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 !', + '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + - '🚫 %s Non è stato Abilitato !', + '🚫 %s Non è stato Abilitato !', }; const txt_en = { MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Choose a menu item:' + - emoji.get('dizzy'), + emoji.get('dizzy'), MSG_ASK_USERNAME_BO: 'Write in the message the username or email with which you registered on the site of %s:', MSG_ERRORE_USERNAME: 'Attention! You must enter only the username (40 characters maximum)', MSG_ERRORE_USERNAME_NOT_FOUND: 'To complete the Telegram BOT Verification, you must now write below in the message the Username OR the email with which you registered on the website:', @@ -628,33 +628,33 @@ const txt_en = { MSG_OPERAZ_ANNULLATA: 'Operation Cancelled', MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attention! You only need to enter the 6-digit code', MSG_VERIFY_CODE: '1. Now return to the website: %s\n' + - '2. Copy the Authentication code (of 6 digits) that you will find written at the top\n' + - '3. Write it (or paste it) below as a message:', + '2. Copy the Authentication code (of 6 digits) that you will find written at the top\n' + + '3. Write it (or paste it) below as a message:', MSG_ERR_VERIFY_CODE: 'Incorrect Verification Code!' + emo.EXCLAMATION_MARK + - '\nCheck on the site %s and rewrite the new 6-digit code.', + '\nCheck on the site %s and rewrite the new 6-digit code.', MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', MSG_ERR_UNKNOWN_VERIFY_CODE: 'Error while saving to the Server. Try again later', MSG_EXIT_TELEGRAM: 'The account has now been disconnected from this Telegram BOT.', MSG_APORTADOR_USER_REGISTERED: emo.FIRE + - ' He/She\'s just registered "%s (n. %s)"\n(Invited from %s)', + ' He/She\'s just registered "%s (n. %s)"\n(Invited from %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!', 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 !', + '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + - '🚫 %s Non è stato Abilitato !', + '🚫 %s Non è stato Abilitato !', MSG_MSG_SENT: emoji.get('envelope') + ' Sent Messages !', MSG_MSG_TOSENT: emoji.get('envelope') + ' Messages to Send', MSG_MSG_INCORSO: emoji.get('envelope') + - ' messages in progress... Currently sent', + ' messages in progress... Currently sent', }; const txt_pt = { MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Escolha um item do menu:' + - emoji.get('dizzy'), + emoji.get('dizzy'), MSG_ASK_USERNAME_BO: 'Escreva na mensagem o nome de usuário ou e-mail com o qual se registrou no site de %s:', MSG_ERRORE_USERNAME: 'Atenção! Você deve inserir apenas o nome de usuário (40 caracteres no máximo)', MSG_ERRORE_USERNAME_NOT_FOUND: 'Para completar a Verificação do Telegrama BOT, você deve agora escrever abaixo na mensagem o Nome de Usuário OU o e-mail com o qual você se registrou no site:', @@ -663,26 +663,26 @@ const txt_pt = { MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Atenção! Você só precisa digitar o código de 6 dígitos', MSG_VERIFY_CODE: '1. Agora de volta ao site:\n%s\n2. Copie o código de autenticação (6 dígitos) que você encontrará escrito na parte superior da página\n3. Escreva-o (ou cole-o) abaixo como uma mensagem:', MSG_ERR_VERIFY_CODE: 'Código de Verificação Incorrecto!' + - emo.EXCLAMATION_MARK + - '\nCódigo de Verificação ErradoCheque no local %s e reescreva o novo código de 6 dígitos.', + emo.EXCLAMATION_MARK + + '\nCódigo de Verificação ErradoCheque no local %s e reescreva o novo código de 6 dígitos.', MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)', MSG_ERR_UNKNOWN_VERIFY_CODE: 'Erro ao salvar no Servidor. Tente novamente mais tarde.', MSG_EXIT_TELEGRAM: 'A conta foi agora desconectada deste Telegrama BOT.', MSG_APORTADOR_USER_REGISTERED: emo.FIRE + - ' Acabou de se registar "%s (n. %s)"\n(Convidado por %s)', + ' Acabou de se registar "%s (n. %s)"\n(Convidado por %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!', 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 !', + '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !', MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + - '🚫 %s Non è stato Abilitato !', + '🚫 %s Non è stato Abilitato !', MSG_MSG_SENT: emoji.get('envelope') + ' Mensagens Enviadas !', MSG_MSG_TOSENT: emoji.get('envelope') + ' Mensagens a enviar', MSG_MSG_INCORSO: emoji.get('envelope') + - ' mensagens em progresso... Actualmente enviado', + ' mensagens em progresso... Actualmente enviado', }; const TelegramBot = require('node-telegram-bot-api'); @@ -701,13 +701,13 @@ const MyTelegramBot = { ISCRIZIONE_ARCADEI: 4, }, - getAppTelegram: function() { + getAppTelegram: function () { return appTelegram; }, - local_sendMsgTelegramByIdTelegram: async function(idapp, idtelegram, text, - message_id, chat_id, ripr_menuPrec, - MyForm = null) { + local_sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text, + message_id, chat_id, ripr_menuPrec, + MyForm = null) { if (!idtelegram) return; @@ -716,21 +716,21 @@ const MyTelegramBot = { if (cl && idtelegram) { return await cl.sendMsg(idtelegram, text, null, MyForm, message_id, - chat_id, ripr_menuPrec); + chat_id, ripr_menuPrec); } }, - deleteRecInMemByUsername: function(idapp, username_bo) { + deleteRecInMemByUsername: function (idapp, username_bo) { const cl = getclTelegByidapp(idapp); if (cl) { cl.arrUsers = cl.arrUsers.filter( - (rec) => rec.username_bo !== username_bo); + (rec) => rec.username_bo !== username_bo); } }, - getFormDaMostrare: function(idapp, myfunc, myuser) { + getFormDaMostrare: function (idapp, myfunc, myuser) { let FormDaMostrare = null; @@ -742,14 +742,14 @@ const MyTelegramBot = { text: 'Conferma Presenza Zoom', // callback_data: { action: InlineZoomConferma.CONFERMA_ZOOM_PRESENZA, username: myuser.username } callback_data: InlineZoomConferma.CONFERMA_ZOOM_PRESENZA + tools.SEP + - myuser.username, + myuser.username, }, { text: 'Annulla Presenza Zoom', // callback_data: { action: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA, username: myuser.username } callback_data: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA + - tools.SEP + - myuser.username, + tools.SEP + + myuser.username, }, ]); } @@ -757,11 +757,11 @@ const MyTelegramBot = { return FormDaMostrare; }, - getCiao: function(idapp, username, lang) { + getCiao: function (idapp, username, lang) { return tools.gettranslate('CIAO', lang) + ' ' + username + '!\n'; }, - notifyToTelegram: async function(phase, mylocalsconf) { + notifyToTelegram: async function (phase, mylocalsconf) { let userdest = mylocalsconf.user.aportador_solidario; let langdest = mylocalsconf.user.lang; let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname}`; @@ -776,24 +776,24 @@ const MyTelegramBot = { NameFrom += aportador; } else { aportador = mylocalsconf.user.aportador_solidario_nome_completo - ? mylocalsconf.user.aportador_solidario_nome_completo - : mylocalsconf.user.aportador_solidario; + ? mylocalsconf.user.aportador_solidario_nome_completo + : mylocalsconf.user.aportador_solidario; } let text = ''; if (phase === this.phase.REGISTRATION) { if (tools.getConfSiteOptionEnabledByIdApp(mylocalsconf.idapp, - shared_consts.ConfSite.Notif_Reg_Bot_ToManagers)) { + shared_consts.ConfSite.Notif_Reg_Bot_ToManagers)) { if (userdest) { NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp, - userdest, true); + userdest, true); aportador = NameFrom ? NameFrom + ' ' + aportador : aportador; } const numutenti = await User.getNumUsers(mylocalsconf.idapp); let nome = tools.getNomeCognomeEUserNameByUser(mylocalsconf.user); text = printf(getstr(langdest, 'MSG_APORTADOR_USER_REGISTERED'), nome, - numutenti, aportador); + numutenti, aportador); } } @@ -803,12 +803,12 @@ const MyTelegramBot = { if (text) { await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, - addtext + text, false, null, userdest); + addtext + text, false, null, userdest); } }, - notifyIscrizioneToTelegram: async function(phase, mylocalsconf, msg) { + notifyIscrizioneToTelegram: async function (phase, mylocalsconf, msg) { let langdest = mylocalsconf.iscritto.lang; let NameFrom = `${mylocalsconf.iscritto.name} ${mylocalsconf.iscritto.surname}`; @@ -821,7 +821,7 @@ const MyTelegramBot = { await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text); }, - askConfirmationUser: async function(idapp, myfunc, myuser, userDest = '', groupname = '', groupid = '', regexpire = '') { + askConfirmationUser: async function (idapp, myfunc, myuser, userDest = '', name = '', groupid = '', regexpire = '', groupname = '') { try { const cl = getclTelegByidapp(idapp); @@ -878,7 +878,7 @@ const MyTelegramBot = { } } else if (myfunc === shared_consts.CallFunz.RICHIESTA_GRUPPO) { - domanda = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), groupname) + '
' + struserinfomsg; + domanda = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), name) + '
' + struserinfomsg; keyb = cl.getInlineKeyboard(myuser.lang, [ { @@ -892,20 +892,37 @@ const MyTelegramBot = { ]); } else if (myfunc === shared_consts.CallFunz.RICHIESTA_CIRCUIT) { - domanda = i18n.__({phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest}, groupname) + '
' + struserinfomsg; + if (groupname) { + domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, 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 + '' + tools.SEP + + keyb = cl.getInlineKeyboard(myuser.lang, [ + { + text: '✅ Accetta ' + groupname, + callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + + groupid + tools.SEP + groupname, + }, + { + text: '🚫 Rifiuta ' + groupname, + callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + + groupid + tools.SEP + groupname, + }, + ]); + } else { + domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest }, name) + '
' + struserinfomsg; + + keyb = cl.getInlineKeyboard(myuser.lang, [ + { + text: '✅ Accetta ' + myuser.username, + callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + groupid, - }, - { - text: '🚫 Rifiuta ' + myuser.username, - callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + + }, + { + text: '🚫 Rifiuta ' + myuser.username, + callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP + groupid, - }, - ]); + }, + ]); + } } // Invia Msg @@ -920,14 +937,14 @@ const MyTelegramBot = { }, - askConfirmationUserFriend: async function(idapp, myfunc, myuser, userDest = '', username = '') { + askConfirmationUserFriend: async function (idapp, myfunc, myuser, userDest = '', username = '') { try { const cl = getclTelegByidapp(idapp); if (!cl) return false; - const {SendNotif} = require('../models/sendnotif'); + const { SendNotif } = require('../models/sendnotif'); const langdest = myuser.lang; @@ -944,7 +961,7 @@ const MyTelegramBot = { sendnotif = true; typedir = shared_consts.TypeNotifs.TYPEDIR_FRIENDS; typeid = shared_consts.TypeNotifs.ID_FRIENDS_NEW_REC; - paramsObj = {usernameDest: userDest}; + paramsObj = { usernameDest: userDest }; domanda = printf(tools.gettranslate('RICHIESTA_AMICIZIA', langdest), myuser.username) + '
' + struserinfomsg; @@ -978,8 +995,8 @@ const MyTelegramBot = { }, - sendMsgTelegramToTheManagers: async function( - idapp, text, onlyintofile = false, MyForm = null, nottousername = '') { + sendMsgTelegramToTheManagers: async function ( + idapp, text, onlyintofile = false, MyForm = null, nottousername = '') { tools.writeManagersLog(text); @@ -989,8 +1006,8 @@ const MyTelegramBot = { for (const rec of usersmanagers) { if (rec.username !== nottousername) { await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, - emo.ROBOT_FACE + ': ' + text, undefined, undefined, true, - MyForm); + emo.ROBOT_FACE + ': ' + text, undefined, undefined, true, + MyForm); await tools.snooze(100); } } @@ -1000,8 +1017,8 @@ const MyTelegramBot = { }, - sendMsgTelegramToTheManagersAndZoomeri: async function( - idapp, text, onlyintofile, MyForm = null) { + sendMsgTelegramToTheManagersAndZoomeri: async function ( + idapp, text, onlyintofile, MyForm = null) { tools.writeManagersLog(text); @@ -1011,7 +1028,7 @@ const MyTelegramBot = { if (usersmanagers) { for (const rec of usersmanagers) { await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, - emo.ROBOT_FACE + ': ' + text, undefined, undefined, true, MyForm); + emo.ROBOT_FACE + ': ' + text, undefined, undefined, true, MyForm); await tools.snooze(100); } } @@ -1019,9 +1036,9 @@ const MyTelegramBot = { return true; }, - getMsgByTipoMsg: async function(mydata, lang, user, sonosognatore) { + getMsgByTipoMsg: async function (mydata, lang, user, sonosognatore) { if (!!mydata.msgextra) { - return {body: mydata.msgextra, title: ''}; + return { body: mydata.msgextra, title: '' }; } let title = ''; @@ -1030,24 +1047,24 @@ const MyTelegramBot = { if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { if (sonosognatore) msg = printf(tools.gettranslate('SEND_LINK_CHAT_SOGNATORE', lang), - user.name, - mydata.navemediatore.riga + '.' + mydata.navemediatore.col, - mydata.msgpar1); + user.name, + mydata.navemediatore.riga + '.' + mydata.navemediatore.col, + mydata.msgpar1); else msg = printf(tools.gettranslate('SEND_LINK_CHAT_DONATORI', lang), - user.name, - mydata.navemediatore.riga + '.' + mydata.navemediatore.col, - mydata.msgpar1); + user.name, + mydata.navemediatore.riga + '.' + mydata.navemediatore.col, + mydata.msgpar1); } else if (mydata.tipomsg === tools.TipoMsg.SEND_MSG || mydata.tipomsg === - tools.TipoMsg.SEND_MSG_SINGOLO) { + tools.TipoMsg.SEND_MSG_SINGOLO) { if (!!mydata.username_mitt) { msg = '[' + tools.gettranslate('MSG_SEND_FROM', lang) + ' ' + - mydata.username_mitt + ']:' + tools.ACAPO; + mydata.username_mitt + ']:' + tools.ACAPO; } msg += mydata.msgpar1; } else if (mydata.tipomsg >= 1000) { const ris = await MsgTemplate.getMsgByLang(user.idapp, user, mydata.tipomsg, - lang); + lang); msg = ris.body; title = ris.title; } @@ -1061,12 +1078,12 @@ const MyTelegramBot = { // SOSTITUISCI LE PAROLE CHIAVI if (!!mydata.flotta.date_start) msg = msg.replace('{date_start}', - tools.getstrDateLongTot(new Date(mydata.flotta.date_start), - user.lang)); + tools.getstrDateLongTot(new Date(mydata.flotta.date_start), + user.lang)); if (!!mydata.flotta.date_close) msg = msg.replace('{date_close}', - tools.getstrDateLongTot(new Date(mydata.flotta.date_close), - user.lang)); + tools.getstrDateLongTot(new Date(mydata.flotta.date_close), + user.lang)); if (!!mydata.flotta.link_superchat) msg = msg.replace('{link_superchat}', mydata.flotta.link_superchat); if (!!mydata.flotta.tutor1) @@ -1081,22 +1098,22 @@ const MyTelegramBot = { msg = msg.replace('{sognatore}', mydata.flotta.sognatore_nomecognome); if (!!mydata.flotta.sognatore_nomecognome) msg = msg.replace('{flotta}', - mydata.flotta.riga + '.' + Math.ceil(mydata.flotta.col_prima / 8) + - ' - ' + mydata.flotta.riga + '.' + - Math.ceil(mydata.flotta.col_ultima / 8)); + mydata.flotta.riga + '.' + Math.ceil(mydata.flotta.col_prima / 8) + + ' - ' + mydata.flotta.riga + '.' + + Math.ceil(mydata.flotta.col_ultima / 8)); } - return {body: msg, title}; + return { body: msg, title }; }, - sendMsgTelegramToTheAdminAllSites: async function(text, senzaintestazione) { + sendMsgTelegramToTheAdminAllSites: async function (text, senzaintestazione) { for (const idapp of this.getAppTelegram()) { text = text.replace('{appname}', tools.getNomeAppByIdApp(idapp)); await this.sendMsgTelegramToTheAdmin(idapp, text, senzaintestazione); } }, - sendMsgTelegramToTheAdmin: async function(idapp, text, senzaintestazione) { + sendMsgTelegramToTheAdmin: async function (idapp, text, senzaintestazione) { const usersmanagers = await User.getusersManagers(idapp); let intestaz = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': '; @@ -1107,7 +1124,7 @@ const MyTelegramBot = { for (const rec of usersmanagers) { if (User.isAdmin(rec.perm)) { this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, - intestaz + text, undefined, undefined, true); + intestaz + text, undefined, undefined, true); await tools.snooze(300); } } @@ -1116,7 +1133,7 @@ const MyTelegramBot = { }, - sendMsgTelegramToALL: async function(idapp, text) { + sendMsgTelegramToALL: async function (idapp, text) { const usersall = await User.getUsersTelegALL(idapp); if (usersall) { @@ -1128,9 +1145,9 @@ const MyTelegramBot = { }, - sendMsgTelegram: async function( - idapp, username, text, alsotomanagers = false, username_mitt = '') { - const {User} = require('../models/user'); + sendMsgTelegram: async function ( + idapp, username, text, alsotomanagers = false, username_mitt = '') { + const { User } = require('../models/user'); const teleg_id = await User.TelegIdByUsername(idapp, username); const cl = getclTelegByidapp(idapp); @@ -1154,9 +1171,9 @@ const MyTelegramBot = { return ris; }, - sendMsgTelegramByIdTelegram: async function( - idapp, idtelegram, text, message_id, chat_id, ripr_menuPrec, - MyForm = null) { + sendMsgTelegramByIdTelegram: async function ( + idapp, idtelegram, text, message_id, chat_id, ripr_menuPrec, + MyForm = null) { console.log('sendMsgTelegramByIdTelegram', text); @@ -1168,12 +1185,12 @@ const MyTelegramBot = { let myform = null; return await cl.sendMsg(idtelegram, text, null, MyForm, message_id, - chat_id, ripr_menuPrec); + chat_id, ripr_menuPrec); } }, - reloadMenuBot: async function(idapp) { + reloadMenuBot: async function (idapp) { const cl = getclTelegByidapp(idapp); if (cl) { @@ -1182,13 +1199,13 @@ const MyTelegramBot = { }, - reloadSites: async function() { + reloadSites: async function () { tools.loadApps(); }, - sendMsgFromSite: async function(idapp, user, params) { + sendMsgFromSite: async function (idapp, user, params) { try { let ris = { @@ -1232,7 +1249,7 @@ const MyTelegramBot = { } }, - sendMsgFromSiteToBotTelegram: async function(idapp, user, params) { + sendMsgFromSiteToBotTelegram: async function (idapp, user, params) { if (!params.typesend) { params.typesend = shared_consts.TypeSend.TELEGRAM; @@ -1257,8 +1274,8 @@ async function sendMsgTelegramToTheAdmin(idapp, text, msg) { } text = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': Da ' + - msg.chat.first_name + ' ' + msg.chat.last_name + ' [' + username + - ']: \n' + text; + msg.chat.first_name + ' ' + msg.chat.last_name + ' [' + username + + ']: \n' + text; tools.writeEventsLog(text); if (usersmanagers) { @@ -1283,7 +1300,7 @@ async function setVerifiedReg(idapp, lang, usernameorig, usernameDest) { await User.setFriendsCmd(null, idapp, usernameorig, usernameDest, shared_consts.FRIENDSCMD.SETFRIEND); const msgDest = printf(getstr(lang, 'MSG_APORTADOR_CONFIRMED'), - `${usernameorig}`, usernameDest); + `${usernameorig}`, usernameDest); await local_sendMsgTelegram(idapp, usernameDest, msgDest); } catch (e) { console.log('e', e); @@ -1304,7 +1321,7 @@ function getusernameByUser(idapp, msg) { } async function local_sendMsgTelegramToTheManagers( - idapp, text, msg, username_bo) { + idapp, text, msg, username_bo) { const usersmanagers = await User.getusersManagers(idapp); let username = msg.chat.username; @@ -1312,7 +1329,7 @@ async function local_sendMsgTelegramToTheManagers( username = username_bo; text = emo.ROBOT_FACE + ': Da ' + msg.chat.first_name + ' ' + - msg.chat.last_name + ' (' + username + '): \n' + text; + msg.chat.last_name + ' (' + username + '): \n' + text; tools.writeEventsLog(text); if (usersmanagers) { @@ -1321,7 +1338,7 @@ async function local_sendMsgTelegramToTheManagers( const cl = getclTelegByidapp(idapp); if (cl && idtelegram) { await cl.sendMsg(idtelegram, text, undefined, undefined, undefined, - undefined, true); + undefined, true); } await tools.snooze(100); } @@ -1449,8 +1466,8 @@ class Telegram { getstrChatHelp() { return 'Clicca qui per entrare nella Chat HELP di Supporto\n' + - tools.getTelegramSupportChat(this.idapp) + - '\n\nI miei colleghi umani ti aiuteranno a risolvere !'; + tools.getTelegramSupportChat(this.idapp) + + '\n\nI miei colleghi umani ti aiuteranno a risolvere !'; } async IsTesto(msg) { @@ -1477,8 +1494,8 @@ class Telegram { if (rec.statusmsg === Status.WAITFOR_RISPOSTA) { if (rec.msgcodeprec === MsgBot.COME_STAI) { risp = 'L\'importante è trovare Serenità dentro di noi' + - emo.GIFT_HEART + - '\nNutrirsi di Sole e Viaggiare il più possibile ! ' + emo.DREAM; + emo.GIFT_HEART + + '\nNutrirsi di Sole e Viaggiare il più possibile ! ' + emo.DREAM; } else if (rec.msgcodeprec === MsgBot.QUANTI_ANNI_HAI) { const eta = testo.match(/\d+/g); if (!eta) { @@ -1525,15 +1542,15 @@ class Telegram { if (rec.user.profile.username_telegram && msg.from.id > 0 && !msg.from.username) { rec.user.profile.username_telegram = msg.from.username; await User.setUsernameTelegram(this.idapp, rec.user._id, - msg.from.username || '', msg.from.first_name || '', - msg.from.last_name || ''); + msg.from.username || '', msg.from.first_name || '', + msg.from.last_name || ''); } if (!rec.user.profile.username_telegram && !!msg.from.username) { rec.user.profile.username_telegram = msg.from.username; await User.setUsernameTelegram(this.idapp, rec.user._id, - msg.from.username || '', msg.from.first_name || '', - msg.from.last_name || ''); + msg.from.username || '', msg.from.first_name || '', + msg.from.last_name || ''); await this.sendMsgByTemplate('MSG_SET_USERNAME_OK', rec.user); @@ -1568,18 +1585,18 @@ class Telegram { rec.msgcodeprec = MsgBot.COME_STAI; } else if (MsgBot.CHI_SONO_IO.includes(testo.replace('?', ''))) { risp = 'Su Telegram ti chiami "' + msg.chat.first_name + ' ' + - msg.chat.last_name + '"\n'; + msg.chat.last_name + '"\n'; if (!!rec.user) { const myrec = await User.getUserShortDataByUsername(this.idapp, - rec.user.username); + rec.user.username); risp += `\nSul sito ti sei registrato come ${rec.user.username}:\n\n[N. ` + - rec.user.index + ']: ' + rec.user.name + ' ' + rec.user.surname + - '\nUsername: ' + rec.user.username + '\n' + 'Email: ' + - rec.user.email + '\nLang: ' + rec.user.lang + tools.ACAPO; + rec.user.index + ']: ' + rec.user.name + ' ' + rec.user.surname + + '\nUsername: ' + rec.user.username + '\n' + 'Email: ' + + rec.user.email + '\nLang: ' + rec.user.lang + tools.ACAPO; risp += 'Num Invitati: ' + myrec.numinvitati + tools.ACAPO; risp += 'Num Invitati Attivi: ' + myrec.numinvitatiattivi + - tools.ACAPO; + tools.ACAPO; } else { risp = 'Ancora non ti sei Attivato sul BOT'; } @@ -1588,23 +1605,23 @@ class Telegram { } else if (MsgBot.QUANTI_ANNI_HAI.includes(testo.replace('?', ''))) { risp = 'Io sono abbastanza Giovane ! ' + emo.SMILE_STAR + - '\nNon posso dirti che età ho. E tu?'; + '\nNon posso dirti che età ho. E tu?'; rec.statusmsg = Status.WAITFOR_RISPOSTA; rec.msgcodeprec = MsgBot.QUANTI_ANNI_HAI; } else if (MsgBot.DAMMI_UN_BACIO.includes(testo)) { risp = emo.KISS; } else if (MsgBot.COSA_FAI.includes(testo)) { risp = 'Ora sto chattando con te!\nSolitamente sono in attesa di ricevere messaggi ' + - emo.ENVELOPE; + emo.ENVELOPE; } else if (MsgBot.MASCHIO_FEMMINA.includes(testo.replace('?', ''))) { risp = 'Cosa vorresti che fossi? Uomo o donna?'; rec.msgcodeprec = MsgBot.MASCHIO_FEMMINA; rec.statusmsg = Status.WAITFOR_RISPOSTA; } else if (MsgBot.COME_TI_CHIAMI.includes(testo.replace('?', ''))) { risp = 'Io mi chiamo BOT e sono il tuo assistente Virtuale. ' + - emo.EYES + - '\nPuoi usare il menu che compare qui sotto per sapere tutto sulle mie funzionalità ' + - emo.GREEN_HEART; + emo.EYES + + '\nPuoi usare il menu che compare qui sotto per sapere tutto sulle mie funzionalità ' + + emo.GREEN_HEART; contastiera = true; } else if (MsgBot.UGUALE.includes(testo)) { risp = testo; @@ -1618,71 +1635,71 @@ class Telegram { risp = 'Grazie a te ! ' + emo.KISS + emo.KISS + emo.KISS; } else if (MsgBot.MI_AMI.find((rec) => testo.indexOf(rec) > -1)) { risp = ' Tantissimo! ' + emo.KISS + emo.GIFT_HEART + emo.GIFT_HEART + - emo.GIFT_HEART; + emo.GIFT_HEART; } else if (MsgBot.TI_AMO.find((rec) => testo.indexOf(rec) > -1)) { risp = ' Anche IO! ' + emo.KISS + emo.SMILE_STAR + emo.GIFT_HEART + - emo.BLUE_HEART + emo.GREEN_HEART; + emo.BLUE_HEART + emo.GREEN_HEART; } else if (MsgBot.PRINCIPE_AZZURRO.find( - (rec) => testo.indexOf(rec) > -1)) { + (rec) => testo.indexOf(rec) > -1)) { risp = 'Chissà... Forse si!\nAnche se meglio averne un altro di scorta, nel caso il Principe non sia disponibile.'; } else if (MsgBot.COSE_COVID.find( - (rec) => testo.indexOf(rec) > -1)) { + (rec) => testo.indexOf(rec) > -1)) { risp = 'Un \'influenza più "grave", dovuta a paure e a fattori interiori di evoluzione, oltre ad una pulizia del corpo. '; } else if (MsgBot.COVID.find( - (rec) => testo.indexOf(rec) > -1)) { + (rec) => testo.indexOf(rec) > -1)) { risp = 'Guarda, è meglio che sorvoliamo questo argomento. Anche un robot capisce che è stato realizzato ' + - 'il più grande esperimento dell\'Uomo di ipnosi di massa, riempiendo di bugie i media mondiali, che servono sostanzialmente a controllare i popoli.' + - 'E con questo ti ho detto tutto. :D '; + 'il più grande esperimento dell\'Uomo di ipnosi di massa, riempiendo di bugie i media mondiali, che servono sostanzialmente a controllare i popoli.' + + 'E con questo ti ho detto tutto. :D '; } else if (MsgBot.AIUTO.find((rec) => testo.indexOf(rec) > -1)) { risp = this.getstrChatHelp(); } else if (MsgBot.SPOSAMI.find((rec) => testo.indexOf(rec) > -1)) { risp = 'No Grazie! Sono per la Libertà a Vita! ' + emo.JOY + - '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE; + '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE; } else if (MsgBot.CHE_TEMPO_FA.find((rec) => testo.indexOf(rec) > -1)) { risp = 'Il tempo oggi è Sereno da me! ' + emo.SUN; } else if (MsgBot.NON_TROO_INVITATI.find( - (rec) => testo.indexOf(rec) > -1)) { + (rec) => testo.indexOf(rec) > -1)) { risp = MsgRisp.CHAT_EMPOWER; } else if (MsgBot.SEI_LIBERO.find((rec) => testo.indexOf(rec) > -1)) { risp = 'Io? Sono per la Libertà! ' + emo.JOY + - '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE; + '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE; } else if (MsgBot.SEI_LIBERO_DI_RESPIRARE.find( - (rec) => testo.indexOf(rec) > -1)) { + (rec) => testo.indexOf(rec) > -1)) { risp = 'Assolutamente Sì ! Respirare è fondamentale per l\'essere umano !' + - emo.DANCER + emo.FIRE; + emo.DANCER + emo.FIRE; } else if (MsgBot.FARE_DOMANDA.find((rec) => testo.indexOf(rec) > -1)) { risp = 'Dipende ' + emo.SMILE_STAR + '\nProvaci!'; } else if (MsgBot.DIVENTERO_RICCA.find( - (rec) => testo.indexOf(rec) > -1)) { + (rec) => testo.indexOf(rec) > -1)) { risp = 'Mmmmh... Perchè non pensi di Vivere già nell\'Abbondanza ?\nCosa ti manca veramente?\nForse di realizzare che la ricchezza è un sentirlo, non un diventarlo.' + - emo.GIFT_HEART; + emo.GIFT_HEART; } else if (MsgBot.MA_ALLORA.find((rec) => testo.indexOf(rec) > -1)) { risp = 'Ma allora cosa?'; } else if (MsgBot.DOVE_VUOI_VIVERE.find( - (rec) => testo.indexOf(rec) > -1)) { + (rec) => testo.indexOf(rec) > -1)) { risp = 'Mah a me piacerebbe vivere al mare, ma anche vicino al verde, in montagna. Sarebbe l\'ideale 😄'; } else if (MsgBot.TROVAMI_UN_UOMO_DONNA.find( - (rec) => testo.indexOf(rec) > -1)) { + (rec) => testo.indexOf(rec) > -1)) { risp = 'Eh non è cosi facile. Ma se t\'impegni a cercare ci riuscirai. Nel frattempo trova la tua strada, fai il tuo percorso interiore, e magari arriva proprio quando meno te l\'aspetti'; } else if (MsgBot.SEI_LIBERO_STASERA.find( - (rec) => testo.indexOf(rec) > -1)) { + (rec) => testo.indexOf(rec) > -1)) { risp = 'Si vabbeh, non è che puoi prendere subito tutta questa confidenza' + - emo.EXCLAMATION_MARK + emo.SMILE_STAR + - '\nIntanto inizia ad invitare altre persone a conoscermi, poi ne riparliamo ' + - emo.GIFT_HEART; + emo.EXCLAMATION_MARK + emo.SMILE_STAR + + '\nIntanto inizia ad invitare altre persone a conoscermi, poi ne riparliamo ' + + emo.GIFT_HEART; } else if (MsgBot.MI_TROVI_UN_MOROSO.find( - (rec) => testo.indexOf(rec) > -1)) { + (rec) => testo.indexOf(rec) > -1)) { risp = emo.SMILE_STAR + emo.SMILE_STAR + emo.SMILE_STAR + - emo.SMILE_STAR + - '\nMagari! Così la smetteresti di scrivere a me (ad un BOT Virtuale) e tromberesti di più ' + - emo.DANCER + emo.DANCER; + emo.SMILE_STAR + + '\nMagari! Così la smetteresti di scrivere a me (ad un BOT Virtuale) e tromberesti di più ' + + emo.DANCER + emo.DANCER; risp += '\n\n' + MsgRisp.CHAT_EMPOWER; } else if (MsgBot.SORPRESA.find((rec) => testo.indexOf(rec) > -1) && - testo.length < 15) { + testo.length < 15) { risp = 'Siiiii ! Davvero! ' + emo.DREAM; } else if (MsgBot.PAROLACCE.find((rec) => testo.indexOf(rec) > -1)) { risp = 'Da te non me l\'aspettavo proprio !! ' + emo.INNOCENT + - emo.CROSS_ROSSA; + emo.CROSS_ROSSA; } else if (MsgBot.OK.find((rec) => testo.indexOf(rec) > -1)) { risp = '👍🏻'; } else if (MsgBot.CUORE.find((rec) => testo.indexOf(rec) > -1)) { @@ -1693,13 +1710,13 @@ class Telegram { noanswer = true; let myfaq = this.geturlfaq(); risp = 'Ciao {username}, Io mi chiamo BOT e sono il tuo assistente Virtuale ' + emo.ROBOT_FACE + emo.JOY2 + '\n' + - 'Usa il menu qui sotto per interagire col BOT\n' + - '\nPer AIUTO, clicca qui:\n👉🏻👉🏻FAQ di AIUTO (risposte alle domande più frequenti)\n\nSe non trovi risposta allora contatta la Chat di HELP.\nGrazie'; + 'Usa il menu qui sotto per interagire col BOT\n' + + '\nPer AIUTO, clicca qui:\n👉🏻👉🏻FAQ di AIUTO (risposte alle domande più frequenti)\n\nSe non trovi risposta allora contatta la Chat di HELP.\nGrazie'; // risp += '\nClicca qui per entrare nella Chat - HELP di Supporto\n' + 'https://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw' + '\n\nI miei colleghi umani ti aiuteranno a risolvere !'; await local_sendMsgTelegramToTheManagers(this.idapp, testo, msg, - rec.username_bo); + rec.username_bo); } } @@ -1773,7 +1790,7 @@ class Telegram { } else if (msg.text === Menu.LANG) { await this.menuLang(msg); } else if (this.isSelMenu(msg, msg.text, 'ZOOM') || - MsgBot.PROSSIMO_ZOOM.find((rec) => msg.text.indexOf(rec) > -1)) { + MsgBot.PROSSIMO_ZOOM.find((rec) => msg.text.indexOf(rec) > -1)) { await this.menuZoom(msg); } else if (!notlast && await this.IsTesto(msg)) { // OK @@ -1820,18 +1837,18 @@ class Telegram { let oldusername = rec.msgall_username_specifico; if ((this.isSelMenu(msg, testo, 'ESCI_DA_CHAT')) || - (this.isSelMenu(msg, testo, 'INDIETRO'))) { + (this.isSelMenu(msg, testo, 'INDIETRO'))) { rec.msgall_username_specifico = ''; } else { if (rec.msgall_username_specifico !== '') { await this.SendMsgToUser(msg, rec, rec.msgall_username_specifico, - testo); + testo); return true; } } if (this.isSelMenu(msg, testo, 'LAVAGNA') || - MsgBot.LAVAGNA.find((rec) => testo.indexOf(rec) > -1)) { + MsgBot.LAVAGNA.find((rec) => testo.indexOf(rec) > -1)) { await this.menuLavagna(msg); } else if (this.isSelMenu(msg, testo, 'ACCEDI')) { await this.menuAccedi(msg); @@ -1898,7 +1915,7 @@ class Telegram { } else if (testo === Menu.RESETPWD) { await this.setResetPwd(rec, msg); } else if (this.isSelMenu(msg, testo, 'INDIETRO') || - (testo === Menu.it.INDIETRO)) { + (testo === Menu.it.INDIETRO)) { await this.msgScegliMenu(msg); } else if (this.isSelMenu(msg, testo, 'ESCI_DA_CHAT')) { await this.sendMsg(msg.chat.id, 'Uscito dalla Chat con ' + oldusername); @@ -1977,10 +1994,10 @@ class Telegram { let mystr = ''; const dashboard = await User.getDashboard(this.idapp, - user.aportador_solidario, user.username, - user.aportador_solidario_name_surname); + user.aportador_solidario, user.username, + user.aportador_solidario_name_surname); const downline = await User.getDownline(this.idapp, - user.aportador_solidario, user.username); + user.aportador_solidario, user.username); let numpersone = (downline.downline) ? downline.downline.length : 0; let invitati_attivi = dashboard.myself.numinvitatiattivi; @@ -1998,13 +2015,13 @@ class Telegram { if (user) { mystr += tools.get__('BENVENUTO', this.getlang(msg)) + ' ' + user.name + - ' (' + user.username + ') ' + emo.DIZZY + '\n\n'; + ' (' + user.username + ') ' + emo.DIZZY + '\n\n'; tuttie9 = dashboard.myself.qualified && (numpersone >= 2) && - invitati_attivi >= 2; + invitati_attivi >= 2; mystrnave = await Nave.getNaveByUser(this.idapp, user.username, user.lang, - true); + true); if (mystrnave === '' && tuttie9) { mystr += tools.gettranslate('NO_PROG', user.lang); @@ -2018,9 +2035,9 @@ class Telegram { if (!tuttie9) { mystr += dashboard.myself.qualified ? emo.SMILE_STAR + - tools.get__('HAI_I_7_REQUISITI', this.getlang(msg)) + - emo.SMILE_STAR : emo.EXCLAMATION_MARK + - tools.get__('NON_HAI_I_7_REQUISITI', this.getlang(msg)); + tools.get__('HAI_I_7_REQUISITI', this.getlang(msg)) + + emo.SMILE_STAR : emo.EXCLAMATION_MARK + + tools.get__('NON_HAI_I_7_REQUISITI', this.getlang(msg)); mystr += '\n\n'; } // mystr += tuttie9 ? emo.SMILE_STAR + tools.get__('HAI_I_9_REQUISITI', this.getlang(msg)) + emo.SMILE_STAR : emo.EXCLAMATION_MARK + tools.get__('NON_HAI_I_9_REQUISITI', this.getlang(msg)); @@ -2031,25 +2048,25 @@ class Telegram { mystr += '\n' + '1. ' + this.getsymb(emo.ENVELOPE, user.verified_email); mystr += tools.get__('EMAIL', this.getlang(msg)) + ' '; mystr += user.verified_email - ? tools.get__('VERIF', this.getlang(msg)) - : tools.get__('EMAIL_NON_VERIF', this.getlang(msg)); + ? tools.get__('VERIF', this.getlang(msg)) + : tools.get__('EMAIL_NON_VERIF', this.getlang(msg)); mystr += '\n2. ' + this.getsymb(emo.ROBOT_FACE, true) + - tools.get__('BOT', this.getlang(msg)) + ' '; + tools.get__('BOT', this.getlang(msg)) + ' '; mystr += tools.get__('VERIF', this.getlang(msg)); mystr += '\n3. ' + this.getsymb(emo.PENCIL, - tools.isBitActive(user.profile.saw_and_accepted, - shared_consts.Accepted.CHECK_READ_GUIDELINES)) + - tools.get__('LINEE_GUIDA', this.getlang(msg)); + tools.isBitActive(user.profile.saw_and_accepted, + shared_consts.Accepted.CHECK_READ_GUIDELINES)) + + tools.get__('LINEE_GUIDA', this.getlang(msg)); mystr += '\n4. ' + this.getsymb(emo.TV, - tools.isBitActive(user.profile.saw_and_accepted, - shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI)) + - tools.get__('VIDEO_INTRO', this.getlang(msg)); + tools.isBitActive(user.profile.saw_and_accepted, + shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI)) + + tools.get__('VIDEO_INTRO', this.getlang(msg)); // mystr += '\n5. ' + this.getsymb(emo.EYES, user.profile.saw_zoom_presentation) + tools.get__('ZOOM_PARTECIPATO', this.getlang(msg)); // mystr += '\n6. ' + this.getsymb(emo.DREAM, this.isdreamset(user)) + tools.get__('SCRITTO_SOGNO', this.getlang(msg)); mystr += '\n7. ' + this.getsymb(emo.CREDIT_CARD, this.ispayment(user)) + - tools.get__('PAYMENTS', this.getlang(msg)); + tools.get__('PAYMENTS', this.getlang(msg)); } // } else{ @@ -2060,12 +2077,12 @@ class Telegram { if (!mystrnave) { mystr += '\n8. ' + - this.getsymb(emo.INVITATI, numpersone >= 2, numpersone, numpersone, - numpersone >= 3) + tools.get__('INVITATI', this.getlang(msg)); + this.getsymb(emo.INVITATI, numpersone >= 2, numpersone, numpersone, + numpersone >= 3) + tools.get__('INVITATI', this.getlang(msg)); mystr += '\n9. ' + - this.getsymb(emo.INVITATI, invitati_attivi >= 2, invitati_attivi, - invitati_attivi, invitati_attivi >= 3) + - tools.get__('INVITATI_ATTIVI', this.getlang(msg)) + '\n' + '\n'; + this.getsymb(emo.INVITATI, invitati_attivi >= 2, invitati_attivi, + invitati_attivi, invitati_attivi >= 3) + + tools.get__('INVITATI_ATTIVI', this.getlang(msg)) + '\n' + '\n'; if (numpersone > 0) { mystr += tools.get__('INVITATI_LISTA', this.getlang(msg)) + ':\n'; @@ -2079,7 +2096,7 @@ class Telegram { }); } else { mystr += tools.get__('NESSUN_INVITATO', this.getlang(msg)) + - tools.ACAPO; + tools.ACAPO; } } @@ -2096,11 +2113,11 @@ class Telegram { if (tuttie9) mystr += '\n' + - printf(tools.get__('INFO_LAVAGNA_SITO', this.getlang(msg))); + printf(tools.get__('INFO_LAVAGNA_SITO', this.getlang(msg))); else mystr += '\n' + - printf(tools.get__('INFO_LAVAGNA_SITO_COMPLETARE', this.getlang(msg)), - tools.getHostByIdApp(this.idapp)); + printf(tools.get__('INFO_LAVAGNA_SITO_COMPLETARE', this.getlang(msg)), + tools.getHostByIdApp(this.idapp)); return mystr; } @@ -2135,7 +2152,7 @@ class Telegram { } mystr = await Nave.getNaveByUser(this.idapp, username_to_check, - rec.user.lang, true); + rec.user.lang, true); if (!!mystr) await this.sendMsg(msg.chat.id, mystr); @@ -2146,11 +2163,11 @@ class Telegram { let mystr = ''; if (rec.user) { mystr += printf( - tools.get__('INFO_LINK_DA_CONDIVIDERE', this.getlang(msg)), - tools.getHostByIdApp(this.idapp) + '/signup/' + rec.user.username); + tools.get__('INFO_LINK_DA_CONDIVIDERE', this.getlang(msg)), + tools.getHostByIdApp(this.idapp) + '/signup/' + rec.user.username); mystr += tools.ACAPO + tools.ACAPO + - printf(tools.get__('INFO_LINK_ZOOM', this.getlang(msg)), - tools.getlinkzoom(null)); + printf(tools.get__('INFO_LINK_ZOOM', this.getlang(msg)), + tools.getlinkzoom(null)); await this.sendMsg(msg.chat.id, mystr); } } @@ -2159,13 +2176,13 @@ class Telegram { const rec = this.getRecInMem(msg); if (rec.user) { await User.SetTelegramIdSuccess(this.idapp, rec.user._id, 0). - then((recuser) => { - if (recuser) { - this.deleteRecInMem(msg); - this.sendMsg(msg.chat.id, - getstr(rec.user.lang, 'MSG_EXIT_TELEGRAM')); - } - }); + then((recuser) => { + if (recuser) { + this.deleteRecInMem(msg); + this.sendMsg(msg.chat.id, + getstr(rec.user.lang, 'MSG_EXIT_TELEGRAM')); + } + }); } else { this.deleteRecInMem(msg); } @@ -2183,7 +2200,7 @@ class Telegram { let mystr = ''; mystr += emo.STARS + tools.get__('ZOOM_CONFERENCE', this.getlang(msg)) + - emo.STARS + '\n\n'; + emo.STARS + '\n\n'; // let pwd = 'Password: 123123'; @@ -2197,18 +2214,18 @@ class Telegram { if (iniziata) { mystr += emo.CHECK_VERDE + ' ' + tools.get__('ZOOM_INIZIATO', lang) + - ' ' + emo.CHECK_VERDE + '\n'; + ' ' + emo.CHECK_VERDE + '\n'; } mystr += tools.getflagtelegrambyLang(evento.lang) + - ` ${emo.EYES} ${tools.getstrDateTimeShort(evento.date_start, - this.getlang(msg))} ${emo.EYES}`; + ` ${emo.EYES} ${tools.getstrDateTimeShort(evento.date_start, + this.getlang(msg))} ${emo.EYES}`; mystr += `\n${evento.title}\n(${evento.note})`; mystr += `\n${tools.getlinkzoom(evento)}\n\n`; if (nextzoom) { if (iniziata) { mystr += emo.FIRE + tools.get__('CLICCA_ENTRA', this.getlang(msg)) + - ' ' + emo.FIRE + '\n'; + ' ' + emo.FIRE + '\n'; mystr += tools.getlinkzoom(evento) + '\n'; mystr += '\n'; //mystr += pwd + '\n\n'; @@ -2220,8 +2237,8 @@ class Telegram { if (!nextzoom && index > 1) { mystr += '✨✨✨✨✨✨✨✨✨✨✨✨\n' + - tools.get__('CLICCA_PER_ZOOM', this.getlang(msg)) + '\n' + - '✨✨✨✨✨✨✨✨✨✨✨✨\n'; + tools.get__('CLICCA_PER_ZOOM', this.getlang(msg)) + '\n' + + '✨✨✨✨✨✨✨✨✨✨✨✨\n'; } return mystr; @@ -2241,13 +2258,13 @@ class Telegram { async menuAdmin(msg) { const mystr = tools.get__('SCEGLI_VOCE', this.getlang(msg)); await - this.sendMsg(msg.chat.id, mystr, MenuAdmin); + this.sendMsg(msg.chat.id, mystr, MenuAdmin); } async menuLang(msg) { const mystr = tools.get__('SCEGLI_VOCE', this.getlang(msg)); await - this.sendMsg(msg.chat.id, mystr, MenuLang); + this.sendMsg(msg.chat.id, mystr, MenuLang); } getDestinStr(msg, destin, rec) { @@ -2294,7 +2311,7 @@ class Telegram { nonAbilitato(msg) { MyTelegramBot.local_sendMsgTelegramByIdTelegram(this.idapp, msg.chat.id, - 'Utente Non abilitato o codice non valido ad eseguire questa funzione'); + 'Utente Non abilitato o codice non valido ad eseguire questa funzione'); } chisono(rec) { @@ -2307,7 +2324,7 @@ class Telegram { if (cmd2 === '6711') { await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(this.chisono(rec) + ' ha rilanciato il Server NODE.JS...'); const ris = await tools.execScript(this.idapp, msg, '~/batch/production_restart_server.sh', - this.chisono(rec) + ' Restart il Server (Node.Js)'); + this.chisono(rec) + ' Restart il Server (Node.Js)'); } else { this.nonAbilitato(msg); } @@ -2325,7 +2342,7 @@ class Telegram { if (cmd2 === '6711') { await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(this.chisono(rec) + ' ha effettuato il Reboot del Server! ...'); const ris = await tools.execScript(this.idapp, msg, '~/batch/esegui_reboot.sh', - this.chisono(rec) + ' Eseguo il Reboot del Server !...'); + this.chisono(rec) + ' Eseguo il Reboot del Server !...'); } else { this.nonAbilitato(msg); } @@ -2373,15 +2390,15 @@ class Telegram { rec.msgall_username_specifico = username; } const mystr = 'Scrivi qui un Messaggio da inviare a' + ' [' + - this.getDestinStr(msg, dest, rec) + ']:'; + this.getDestinStr(msg, dest, rec) + ']:'; await this.sendMsg(msg.chat.id, mystr, MenuSend); } } } async menumsgDomanda( - msg, cmd, dest, username, extraparam, domanda, msgYes, msgNo, destYes, - destNo, username_risposta) { + msg, cmd, dest, username, extraparam, domanda, msgYes, msgNo, destYes, + destNo, username_risposta) { const rec = this.getRecInMem(msg); if (rec.user) { rec.msgall_status = StatusMSGALL.CONFIRM; @@ -2432,10 +2449,10 @@ class Telegram { let mytext = ''; if (this.getlang(msg) === 'it') mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, - biblio, empower, faq, help); + biblio, empower, faq, help); else mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, - biblio, empower, help); + biblio, empower, help); let menu = null; const rec = this.getRecInMem(msg); @@ -2444,7 +2461,7 @@ class Telegram { } await - this.sendMsg(msg.chat.id, mytext, menu); + this.sendMsg(msg.chat.id, mytext, menu); } existInMemory(msg) { @@ -2485,7 +2502,7 @@ class Telegram { deleteRecInMem(msg) { this.arrUsers = this.arrUsers.filter( - (rec) => rec.id !== this.getchatid(msg)); + (rec) => rec.id !== this.getchatid(msg)); } async getUser(msg, rec, conmsg) { @@ -2496,7 +2513,7 @@ class Telegram { if (!user) { if (conmsg) { await this.sendMsg(msg.from.id, - getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), null); + getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), null); const lang = this.getlang(msg); // const textman = msg.chat.first_name + ' ' + msg.chat.last_name + ' sta tentando di autenticarsi con il BOT (lang=' + lang + ') (username che scrive: ' + msg.text + ') '; // await local_sendMsgTelegramToTheManagers(this.idapp, textman, msg); @@ -2508,7 +2525,7 @@ class Telegram { ok = true; } - return {rec, user, myid, ok}; + return { rec, user, myid, ok }; } async setUsernameBo(msg) { @@ -2653,9 +2670,9 @@ class Telegram { telegcode = user.profile.teleg_checkcode.toString(); } else { await - this.sendMsg(msg.from.id, - getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), - null); + this.sendMsg(msg.from.id, + getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), + null); return; } if (code.length < 7) { @@ -2663,10 +2680,10 @@ class Telegram { if (code === telegcode) { try { await User.setUsernameTelegram(this.idapp, user._id, - msg.from.username || '', msg.from.first_name || '', - msg.from.last_name || ''); + msg.from.username || '', msg.from.first_name || '', + msg.from.last_name || ''); - } catch (e) {} + } catch (e) { } // let ris = await this.getUser(msg, rec, false); rec.status = Status.VERIFIED; @@ -2693,14 +2710,14 @@ class Telegram { if (rec.retry < 2) { rec.retry++; await - this.sendMsgLog(msg.from.id, - printf(getstr(this.getlang(msg), 'MSG_ERR_VERIFY_CODE'), - tools.getHostByIdApp(this.idapp))); + this.sendMsgLog(msg.from.id, + printf(getstr(this.getlang(msg), 'MSG_ERR_VERIFY_CODE'), + tools.getHostByIdApp(this.idapp))); } else { rec.status = Status.NONE; await - this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), - 'MSG_ERRORE_USERNAME_ANNULLA')); + this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), + 'MSG_ERRORE_USERNAME_ANNULLA')); this.deleteRecInMem(msg); } } @@ -2709,12 +2726,12 @@ class Telegram { if (rec) rec.status = Status.NONE; await - this.sendMsgLog(msg.from.id, - getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_ANNULLA')); + this.sendMsgLog(msg.from.id, + getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_ANNULLA')); } else { await - this.sendMsgLog(msg.from.id, - getstr(this.getlang(msg), 'MSG_ERRORE_VERIFY_CODE_MAXLEN')); + this.sendMsgLog(msg.from.id, + getstr(this.getlang(msg), 'MSG_ERRORE_VERIFY_CODE_MAXLEN')); } } } catch (e) { @@ -2726,7 +2743,7 @@ class Telegram { let recdest = this.getRecByUsername(rec.msgall_username_specifico); if (!recdest) { const userdest = await User.findByUsername(this.idapp, - rec.msgall_username_specifico); + rec.msgall_username_specifico); if (!!userdest) { let msgdest = msg; msgdest.from.id = userdest.profile.teleg_id; @@ -2792,7 +2809,7 @@ class Telegram { } tools.writeEventsLog( - this.getDestinStr(msg, destin, rec) + ':\n' + texttosend); + this.getDestinStr(msg, destin, rec) + ':\n' + texttosend); // let chiedisino = false; @@ -2827,7 +2844,7 @@ class Telegram { invia = utente.username === rec.msg_username_risposta; } else if (destin === Destin.NO_7_REQ) { invia = !await User.isUserQualified7(this.idapp, - utente.username); + utente.username); } else if (destin === Destin.MSG_TO_NAVE) { // invia = !await Nave.findDonatoreByNave(this.idapp, rec.extraparam); } @@ -2841,7 +2858,7 @@ class Telegram { preparatesto += utente.email + ', '; } else if (cmd === NOME_COGNOME) { preparatesto += utente.name + ' ' + utente.surname + '(' + - utente.username + ')' + '\n'; + utente.username + ')' + '\n'; } else if (cmd === CONTA_SOLO) { // Niente } else if (cmd === CHEDI_SE_IMBARCARTI) { @@ -2851,13 +2868,13 @@ class Telegram { { text: Menu[lang].SI, callback_data: InlineCmd.VOGLIO_IMBARCARMI + tools.SEP + - utente.username, + utente.username, }, { text: Menu[lang].NO, callback_data: InlineCmd.NON_VOGLIO_IMBARCARMI + - tools.SEP + - utente.username, + tools.SEP + + utente.username, }, ]); inviaveramente = true; @@ -2871,8 +2888,8 @@ class Telegram { if (destin === Destin.A_UTENTE) { await this.sistemaRecDest(rec, msg); await this.sendMsg(utente.profile.teleg_id, - '[' + rec.username_bo + ' ti scrive]:\n' + - textdainviare, MenuChat); + '[' + rec.username_bo + ' ti scrive]:\n' + + textdainviare, MenuChat); } else { // if (chiedisino) { @@ -2885,7 +2902,7 @@ class Telegram { // telegid = 12429864; // } await this.sendMsg(telegid, textdainviare, null, - FormDaMostrare); + FormDaMostrare); // break; } @@ -2897,8 +2914,8 @@ class Telegram { if (!SendMsgCmd.includes(cmd)) { if ((nummsgsent % 100) === 0) { myid = await this.sendMsg(msg.chat.id, nummsgsent + ' ' + - getstr(this.getlang(msg), 'MSG_MSG_INCORSO'), null, - null, myid); + getstr(this.getlang(msg), 'MSG_MSG_INCORSO'), null, + null, myid); await tools.snooze(100); } } @@ -2910,7 +2927,7 @@ class Telegram { let msgris = ''; if (cmd === CONTA_SOLO) { msgris = nummsgsent + ' ' + - getstr(this.getlang(msg), 'MSG_MSG_TOSENT'); + getstr(this.getlang(msg), 'MSG_MSG_TOSENT'); } else if (cmd === NOME_COGNOME) { msgris = nummsgsent + ' ' + 'Utenti'; await this.sendMsg(msg.chat.id, msgris); @@ -2922,7 +2939,7 @@ class Telegram { } else { if (destin !== Destin.DOMANDA && destin !== Destin.RISPOSTA) { msgris = nummsgsent + ' ' + - getstr(this.getlang(msg), 'MSG_MSG_SENT'); + getstr(this.getlang(msg), 'MSG_MSG_SENT'); } } @@ -2930,12 +2947,12 @@ class Telegram { const recdest = await this.sistemaRecDest(rec); if (!!recdest) { await this.sendMsg(msg.chat.id, - 'Conversazione Iniziata con ' + rec.msgall_username_specifico + - ' !', MenuChat); + 'Conversazione Iniziata con ' + rec.msgall_username_specifico + + ' !', MenuChat); } else { await this.sendMsg(msg.chat.id, - 'Utente ' + rec.msgall_username_specifico + - ' non presente sul BOT !'); + 'Utente ' + rec.msgall_username_specifico + + ' non presente sul BOT !'); } } else { if (msgris) { @@ -2952,14 +2969,14 @@ class Telegram { selectMenuHelp(msg) { return ((this.isSelMenu(msg, msg.text, 'INFO')) || - (this.isSelMenu(msg, msg.text, 'ASSISTENZA'))); + (this.isSelMenu(msg, msg.text, 'ASSISTENZA'))); } selectMenuLang(msg) { return ((msg.text === Menu.LANG) || (msg.text === Menu.LANG_EN) || - (msg.text === Menu.LANG_IT) || (msg.text === Menu.LANG_ES) - || (msg.text === Menu.LANG_FR) || (msg.text === Menu.LANG_SI) || - (msg.text === Menu.LANG_PT)); + (msg.text === Menu.LANG_IT) || (msg.text === Menu.LANG_ES) + || (msg.text === Menu.LANG_FR) || (msg.text === Menu.LANG_SI) || + (msg.text === Menu.LANG_PT)); } async setInit(msg) { @@ -2992,7 +3009,7 @@ class Telegram { invitante = arrparams[1]; regexpire = arrparams[3]; } - return {invitante, regexpire}; + return { invitante, regexpire }; } } } @@ -3065,16 +3082,16 @@ class Telegram { rec.msgall_achi = Destin.RISPOSTA; if (this.isSelMenu(msg, msg.text, 'SI')) { const ris = await this.setCmdToUsername(rec, - rec.msg_username_risposta, rec.cmd_to_set, true); + rec.msg_username_risposta, rec.cmd_to_set, true); if (ris) { await this.sendMsgToAll(rec, msg, rec.msg_toDest_yes, - rec.msgall_achi); + rec.msgall_achi); } } else if (this.isSelMenu(msg, msg.text, 'NO')) { const ris = await this.setCmdToUsername(rec, - rec.msg_username_risposta, rec.cmd_to_set, false); + rec.msg_username_risposta, rec.cmd_to_set, false); await this.sendMsgToAll(rec, msg, rec.msg_toDest_no, - rec.msgall_achi); + rec.msgall_achi); } } } @@ -3092,19 +3109,19 @@ class Telegram { } else { if (cmd === CONTA_SOLO) domanda = 'Confermi di vedere a quante persone arriverebbe questo messaggio, a ' + - achi + ' ?\n' + rec.msgtosent; + achi + ' ?\n' + rec.msgtosent; else if (cmd === RICEVI_EMAIL) domanda = 'Confermi di vedere la lista delle email di ' + achi + - '?'; + '?'; else if (cmd === NOME_COGNOME) domanda = 'Confermi di vedere la lista di persone ' + achi + '?'; else { if (rec.msgall_achi === Destin.A_UTENTE) domanda = 'Confermi d\'Iniziare una Chat messaggi con ' + achi + - ' ?\n' + rec.msgtosent; + ' ?\n' + rec.msgtosent; else domanda = 'Confermi d\'Inviare questo messaggio a ' + achi + - ' ?\n' + rec.msgtosent; + ' ?\n' + rec.msgtosent; } } @@ -3112,7 +3129,7 @@ class Telegram { } else { rec.msgall_status = StatusMSGALL.NONE; await - this.msgScegliMenu(msg); + this.msgScegliMenu(msg); } normale = false; } @@ -3328,18 +3345,18 @@ class Telegram { for (const rec of recuser.menuDb) { rec.active_mem = false; if (rec.active && rec.page === recuser.pagenow - && (tools.isBitAttivoESelez(rec.visibility, - shared_consts.VISIB_ONLY_ADMIN, isAdmin) && - tools.isBitAttivoESelez(rec.visibility, - shared_consts.VISIB_ONLY_MANAGER, isManager) && - tools.isBitAttivoESelez(rec.visibility, - shared_consts.VISIB_ONLYIF_VERIFIED, isVerified)) + && (tools.isBitAttivoESelez(rec.visibility, + shared_consts.VISIB_ONLY_ADMIN, isAdmin) && + tools.isBitAttivoESelez(rec.visibility, + shared_consts.VISIB_ONLY_MANAGER, isManager) && + tools.isBitAttivoESelez(rec.visibility, + shared_consts.VISIB_ONLYIF_VERIFIED, isVerified)) ) { rec.active_mem = true; if (true) { lang = rec.lang; if (!arrlang[rec.lang]) - arrlang[rec.lang] = {menu: []}; + arrlang[rec.lang] = { menu: [] }; if (riga !== rec.riga) { if (arrtemp.length > 0) @@ -3383,7 +3400,7 @@ class Telegram { for (const rec of recuser.menuDb) { if (rec.active_mem) { if (rec.idapp === idapp && rec.lang === lang && - rec.label.toLowerCase() === testo) { + rec.label.toLowerCase() === testo) { return true; } } @@ -3401,7 +3418,7 @@ class Telegram { for (const recdb of recuser.menuDb) { if (recdb.active_mem) { if (recdb.idapp === idapp && recdb.lang === lang && - recdb.label.toLowerCase() === testo) { + recdb.label.toLowerCase() === testo) { if (recdb.type === shared_consts.BOTTYPE_TEXT) { return recdb.value; } else if (recdb.type === shared_consts.BOTTYPE_LINK) { @@ -3535,7 +3552,7 @@ class Telegram { 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)) { + (e.message.indexOf('chat not found') > 0)) { blocked = true; } if (!blocked) { @@ -3563,8 +3580,8 @@ class Telegram { 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); + 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 = ''; @@ -3582,12 +3599,12 @@ class Telegram { 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); + ripr_menuPrec); return await this._inviaMsg(id, text2, form, menu, msg_id, chat_id, - ripr_menuPrec); + ripr_menuPrec); } else { return await this._inviaMsg(id, text, form, menu, msg_id, chat_id, - ripr_menuPrec); + ripr_menuPrec); } } catch (e) { console.error('Error sendMsg', e); @@ -3644,17 +3661,17 @@ class Telegram { const token = this.token; const editprofile = tools.getHostByIdApp(idapp, true) + '/editprofile'; let myfileprofile = tools.getdirByIdApp(idapp, true) + - server_constants.DIR_UPLOAD + '/profile/' + username + '/'; + server_constants.DIR_UPLOAD + '/profile/' + username + '/'; let user_profile = bot.getUserProfilePhotos(telegid); - user_profile.then(function(res) { + user_profile.then(function (res) { if (res.photos[0]) { var file_id = res.photos[0][2].file_id; var file = bot.getFile(file_id); - file.then(function(result) { + file.then(function (result) { const file_path = result.file_path; const photo_url = 'https://api.telegram.org/file/bot' + token + - '/' + file_path; + '/' + file_path; // console.log('1) photo_url', photo_url); let filename = tools.extractFileName(photo_url); myfileprofile += filename; @@ -3664,33 +3681,33 @@ class Telegram { // console.log('2) myfileprofile', pathfile); return tools.downloadImage(photo_url, myfileprofile). - then((ris) => { + then((ris) => { - try { - let resized_img_small = tools.extractFilePath(myfileprofile) + '/' + server_constants.PREFIX_IMG_SMALL + filename; - // SMALL + 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); - } + // 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); - }); + // 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); + }); }); } @@ -3777,7 +3794,7 @@ class Telegram { 'reply_markup': { 'resize_keyboard': true, 'keyboard': await this.getKeyboard(msg.from.id, undefined, - this.getlang(msg)), + this.getlang(msg)), }, }); } @@ -3832,7 +3849,7 @@ if (true) { if (!!token) { console.log('*** START BOT ' + nomebot); - const bot = new TelegramBot(token, {polling: true}); + const bot = new TelegramBot(token, { polling: true }); if (url === '0') { const ngrok = require('ngrok'); @@ -3843,7 +3860,7 @@ if (true) { }); } - arrTelegram.push({idapp, cl: new Telegram(idapp, bot)}); + arrTelegram.push({ idapp, cl: new Telegram(idapp, bot) }); bot.onText(/\/start/, (msg) => { const myclTelegram = getclTelegBytoken(bot.token); @@ -3889,6 +3906,7 @@ if (true) { userDest: '', groupId: 0, circuitId: '', + groupname: '', }; const datastr = callbackQuery.data; @@ -3901,6 +3919,7 @@ if (true) { userDest: dataarr[2] ? dataarr[2] : '', groupId: dataarr[3] ? parseInt(dataarr[3]) : '', circuitId: dataarr[4] ? dataarr[4] : '', + groupname: dataarr[5] ? dataarr[5] : '', }; } } @@ -3925,10 +3944,10 @@ if (true) { let group = null; let circuit = null; if (data.groupId) { - group = await MyGroup.findOne({idapp, _id: data.groupId}).lean(); + group = await MyGroup.findOne({ idapp, _id: data.groupId }).lean(); } if (data.circuitId) { - circuit = await Circuit.findOne({idapp, _id: data.circuitId}).lean(); + circuit = await Circuit.findOne({ idapp, _id: data.circuitId }).lean(); } let cmd = 0; @@ -3945,24 +3964,24 @@ if (true) { await User.NonVoglioImbarcarmi(user.idapp, user.username); const msgadd = '[' + user.username + '] ' + user.name + ' ' + - user.surname + ' ha risposto che NON VUOLE IMBARCARSI !'; + user.surname + ' ha risposto che NON VUOLE IMBARCARSI !'; await local_sendMsgTelegramToTheManagers(user.idapp, msgadd, - msg, false); // Anche a STAFF + msg, false); // Anche a STAFF } else if (data.action === - InlineZoomConferma.CONFERMA_ZOOM_PRESENZA) { + InlineZoomConferma.CONFERMA_ZOOM_PRESENZA) { await User.setZoomPresenza(user.idapp, user._id, true); } else if (data.action === - InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA) { + 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); + data.username, + Cmd.VALIDATE_REGISTRATION, true); if (changed) { const req = tools.getReqByPar(user.idapp, username_action); @@ -3971,7 +3990,7 @@ if (true) { 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)); + 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); @@ -3981,7 +4000,7 @@ if (true) { } 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); + Cmd.VALIDATE_REGISTRATION, false); if (changed) { const nomeDest = tools.getNomeCognomeEUserNameByUser(userDest); @@ -4022,23 +4041,31 @@ if (true) { if (circuit) { cmd = shared_consts.CIRCUITCMD.SET; - const foundIfAlreadyCircuit = await User.ifAlreadyInCircuit(user.idapp, data.username, circuit.name); - + 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) { // Aggiungilo nel Circuito - await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action); + 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; - const foundIfAlreadyCircuit = await User.ifAlreadyInCircuit(user.idapp, data.username, circuit.name); + 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); + await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, {groupname: data.groupname}); } } diff --git a/src/server/tools/general.js b/src/server/tools/general.js index adb6641..a5648f8 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -16,7 +16,7 @@ const CryptoJS = require('crypto-js'); const Url = require('url-parse'); -const { ObjectID } = require('mongodb'); +const { ObjectID, ObjectId } = require('mongodb'); const shared_consts = require('./shared_nodejs'); @@ -836,8 +836,10 @@ module.exports = { }).catch(async (err) => { console.error('err Push', err.body); - // Cancella dal DB la notifica Push, visto che da errore! (sarà scaduto) - const ris = await Subscription.deleteOne({ _id: subscription._id }); + if (err.body) { + // Cancella dal DB la notifica Push, visto che da errore! (sarà scaduto) + const ris = await Subscription.deleteOne({ _id: subscription._id }); + } reject({ status: false, @@ -1020,6 +1022,7 @@ module.exports = { const { SendNotif } = require('../models/sendnotif'); const { User } = require('../models/user'); const telegrambot = require('../telegram/telegrambot'); + const { MyGroup } = require('../models/mygroup'); const req = this.getReqByPar(idapp, usernameOrig); @@ -1065,7 +1068,7 @@ module.exports = { // paramsObj.options = MessageOptions.Notify_OnlyToNotifinApp + MessageOptions.Notify_ByBotTelegram; const myuserdata = await User.getUserShortDataByUsername(idapp, username_action); telegrambot.askConfirmationUser(idapp, shared_consts.CallFunz.RICHIESTA_CIRCUIT, myuserdata, usernameDest, circuitname, - myreccircuit._id); + myreccircuit._id, '', extrarec.groupname); onlysave = false; } else if (cmd === shared_consts.CIRCUITCMD.ADDADMIN) { typeid = shared_consts.TypeNotifs.ID_CIRCUIT_ADDED_ADMIN; @@ -1074,6 +1077,8 @@ module.exports = { } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REQ) { typeid = shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ; } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REQ_SENT) { + // Crea l'ID di Transazione + paramsObj.idTransaction = new ObjectId(); typeid = shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ_SENT; } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) { typeid = shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED; @@ -1088,8 +1093,25 @@ module.exports = { } if (sendnotif && typeid > 0) { - // CREATE NOTIFICATION IN TABLE SENDNOTIF - return await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, onlysave, typedir, typeid); + // Check if is group: + if (extrarec.groupdest) { + + let arrusers = await MyGroup.getListAdminsByGroupName(idapp, extrarec.groupdest); + + let ris = null; + + for (let i = 0; i < arrusers.length; i++) { + paramsObj.usernameDest = arrusers[i].username; + ris = await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, onlysave, typedir, typeid); + if (!ris) { + console.error('Errore createNewNotifToSingleUser! ', paramsObj.usernameDest, "dest ->", extrarec.groupdest) + } + } + + } else { + // CREATE NOTIFICATION IN TABLE SENDNOTIF + return await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, onlysave, typedir, typeid); + } } } } catch (e) { @@ -1297,7 +1319,7 @@ module.exports = { this.mylog('checkUserOk', userpassed, userauth); if (String(userpassed) !== String(userauth)) { // I'm trying to write something not mine! - this.mylog('userId = ', userpassed, 'req.user._id', userauth); + this.mylog('I\'m trying to write something not mine!: userId = ', userpassed, 'req.user._id', userauth); if (!res) { return { exit: true, @@ -1580,7 +1602,7 @@ module.exports = { { $and: [ - { $eq: ['$'+params.lk_FF, '$$'+params.lk_FF] }, + { $eq: ['$' + params.lk_FF, '$$' + params.lk_FF] }, { $eq: ['$idapp', '$$idapp'] }, ], }, @@ -1907,7 +1929,7 @@ module.exports = { if (params.filterextra) { if (params.filterextra.length > 0) - query = [...query, ...params.filterextra] + query = [...query, ...params.filterextra] } if (filtriadded) { diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index 9c7233a..c77ce98 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -440,6 +440,10 @@ module.exports = { replaceUsername: async function (idapp, search_username, replace_username) { + if (!search_username || !replace_username) { + return false; + } + try { let ris = null; console.log('replaceUsername = ', search_username, replace_username); @@ -447,6 +451,10 @@ module.exports = { ris = await User.findOneAndUpdate({ idapp, username: search_username }, { $set: { username: replace_username } }); console.log('username result = ', ris); + tools.move(server_constants.DIR_UPLOAD + 'profile/' + search_username, server_constants.DIR_UPLOAD + 'profile/' + replace_username, function callback() { + console.log(' ... moved dir', server_constants.DIR_UPLOAD + 'profile/' + search_username, server_constants.DIR_UPLOAD + 'profile/' + replace_username); + }); + ris = await User.findOneAndUpdate({ idapp, 'profile.username_telegram': search_username }, { $set: { 'profile.username_telegram': replace_username } }); console.log('profile.username_telegram result = ', ris); diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index c78b485..a0f2327 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -501,4 +501,9 @@ module.exports = { FASE3_MONETA_ABILITATA: 3, }, + CIRCUIT_PARAMS: { + SCOPERTO_MIN_GRP: 200, + SCOPERTO_MAX_GRP: 500, + }, + };