diff --git a/.DS_Store b/.DS_Store
index 21d5fa8..5f26a37 100644
Binary files a/.DS_Store and b/.DS_Store differ
diff --git a/emails/.DS_Store b/emails/.DS_Store
index ab6ba62..18997d3 100644
Binary files a/emails/.DS_Store and b/emails/.DS_Store differ
diff --git a/src/server/models/sendnotif.js b/src/server/models/sendnotif.js
index 7ae09a0..a2a7dba 100755
--- a/src/server/models/sendnotif.js
+++ b/src/server/models/sendnotif.js
@@ -16,7 +16,7 @@ const globalTables = require('../tools/globalTables');
const tools = require('../tools/general');
// Resolving error Unknown modifier: $pushAll
-mongoose.plugin(schema => {
+mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
@@ -35,7 +35,8 @@ const sendNotifSchema = new Schema({
default: 0,
index: true,
},
- sender: { // mittente
+ sender: {
+ // mittente
type: String,
default: '',
index: true,
@@ -47,7 +48,8 @@ const sendNotifSchema = new Schema({
descr: {
type: String,
},
- sendergroup: { // mittente
+ sendergroup: {
+ // mittente
type: String,
default: '',
},
@@ -123,31 +125,27 @@ sendNotifSchema.index({ sender: 1 });*/
sendNotifSchema.index({ idapp: 1, typedir: 1, typeid: 1, status: 1, sender: 1 });
-
sendNotifSchema.statics.setNotifAsRead = async function (idapp, username, idnotif) {
const SendNotif = this;
- if (!username)
- return null;
+ if (!username) return null;
try {
-
if (idnotif) {
- return await SendNotif.findOneAndUpdate({
- $and: [
- { idapp },
- { dest: username },
- { '_id': idnotif },
- ],
- $or: [
- { deleted: { $exists: false } },
- { deleted: { $exists: true, $eq: false } }],
-
- }, { $set: { read: true } }, { new: false }).then((ret) => {
- return !!ret;
- }).catch((err) => {
- console.error('err', err);
- });
+ return await SendNotif.findOneAndUpdate(
+ {
+ $and: [{ idapp }, { dest: username }, { _id: idnotif }],
+ $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
+ },
+ { $set: { read: true } },
+ { new: false }
+ )
+ .then((ret) => {
+ return !!ret;
+ })
+ .catch((err) => {
+ console.error('err', err);
+ });
}
} catch (e) {
return false;
@@ -162,20 +160,21 @@ sendNotifSchema.statics.getRecNotif = async function (id) {
} catch (e) {
return null;
}
-
};
-sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function (username, lastdataread, idapp, limitrecord, qualinotif, arroptionfilter) {
+sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function (
+ username,
+ lastdataread,
+ idapp,
+ limitrecord,
+ qualinotif,
+ arroptionfilter
+) {
const SendNotif = this;
- if (!lastdataread)
- lastdataread = 0;
+ if (!lastdataread) lastdataread = 0;
- let arrfilter = [
- { idapp },
- { dest: username },
- { datenotif: { $gt: new Date(lastdataread) } }
- ];
+ let arrfilter = [{ idapp }, { dest: username }, { datenotif: { $gt: new Date(lastdataread) } }];
if (qualinotif) {
if (qualinotif === shared_consts.QualiNotifs.CIRCUITS) {
@@ -191,19 +190,21 @@ sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function (username, l
return SendNotif.find({
$and: arrfilter,
- }).lean().limit(limitrecord).sort({ datenotif: -1 }).then(async (arrnotif) => {
- // console.log('arrnotif', arrnotif.length);
-
- return this.compileOtherFields(arrnotif);
-
- }).catch((err) => {
- console.error('err', err);
- });
+ })
+ .lean()
+ .limit(limitrecord)
+ .sort({ datenotif: -1 })
+ .then(async (arrnotif) => {
+ // console.log('arrnotif', arrnotif.length);
+ return this.compileOtherFields(arrnotif);
+ })
+ .catch((err) => {
+ console.error('err', err);
+ });
};
sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, userorig) {
-
const numchars = 80;
let newdescr = '';
let newdescrtelegram = '';
@@ -253,27 +254,38 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
tag = 'newevent';
if (recnotif.typeid === shared_consts.TypeNotifs.ID_EVENTS_NEW_REC) {
// let eventobj = await tools.getEventForTelegram(recnotif.myrectableorig, mydescr, userorig);
- let eventobj = await tools.getAnnuncioForTelegram(recnotif.myrectableorig, shared_consts.TABLES_MYBACHECAS, mydescr, userorig, true);
+ let eventobj = await tools.getAnnuncioForTelegram(
+ recnotif.myrectableorig,
+ shared_consts.TABLES_MYBACHECAS,
+ mydescr,
+ userorig,
+ true
+ );
newdescr = eventobj.descrperNotif;
newdescrtelegram = eventobj.newdescrtelegram;
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_EVENTS_SEND_MSG) {
newdescr = i18n.__('EVENT_SEND_MSG', userorig, recnotif.title, recnotif.msg);
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_EVENTS_ATTEND) {
- // ++ Controlla se esiste già
+ // ++ Controlla se esiste già
let esitegia = recnotif.paramsObj.recObjCreator.exist; // ++
if (esitegia)
- newdescr = i18n.__('SET_ATTEND_OTHERS', recnotif.paramsObj.username_action, recnotif.paramsObj.recObjCreator.numattend - 1, recnotif.paramsObj.recObjCreator.descr);
+ newdescr = i18n.__(
+ 'SET_ATTEND_OTHERS',
+ recnotif.paramsObj.username_action,
+ recnotif.paramsObj.recObjCreator.numattend - 1,
+ recnotif.paramsObj.recObjCreator.descr
+ );
else
newdescr = i18n.__('SET_ATTEND', recnotif.paramsObj.username_action, recnotif.paramsObj.recObjCreator.descr);
- recnotif.openUrl = shared_consts.getDirectoryByTable(recnotif.paramsObj.recObjCreator.table, true) + recnotif.paramsObj.recObjCreator.id;
+ recnotif.openUrl =
+ shared_consts.getDirectoryByTable(recnotif.paramsObj.recObjCreator.table, true) +
+ recnotif.paramsObj.recObjCreator.id;
tag = 'attend';
-
}
recnotif.textcontent_Telegram = newdescrtelegram;
// recnotif.linkaddTelegram = i18n.__('SHOW_POST');
-
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FRIENDS) {
recnotif.openUrl = '/my/' + sender;
if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_NEW_REC) {
@@ -283,7 +295,7 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
newdescr = i18n.__('%s accepted your Friendship', sender, mydescr);
tag = 'acceptedfriend';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED_MY_REQUEST) {
- newdescr = i18n.__('✅ You have accepted %s\' Friendship request!', sender, mydescr);
+ newdescr = i18n.__("✅ You have accepted %s' Friendship request!", sender, mydescr);
tag = 'acceptedfriend';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_REFUSED) {
newdescr = i18n.__('%s refused your Friendship', sender, mydescr);
@@ -298,7 +310,11 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
recnotif.openUrl = '/my/' + recnotif.paramsObj.usernameDest;
} else {
recnotif.openUrl = '/my/' + recnotif.paramsObj.username_action;
- newdescr = i18n.__('FRIEND_REPORTED_TO_ME', recnotif.paramsObj.username_action, recnotif.paramsObj.username_action);
+ newdescr = i18n.__(
+ 'FRIEND_REPORTED_TO_ME',
+ recnotif.paramsObj.username_action,
+ recnotif.paramsObj.username_action
+ );
}
}
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_HANDSHAKE) {
@@ -314,53 +330,106 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
newdescr = i18n.__('GROUP_CREATED', sender, recnotif.paramsObj.groupnameDest);
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_ACCEPTED) {
if (recnotif.paramsObj.isAdmin) {
- newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
+ newdescr = i18n.__(
+ 'ACCETTATO_NOTIFICA_ADMINS',
+ sender,
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.username_action
+ );
recnotif.openUrl = '/my/' + sender;
} else {
newdescr = i18n.__('GROUPS_ACCEPTED', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
}
tag = 'addgroup';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REMOVED) {
- if (recnotif.paramsObj.username_action === recnotif.paramsObj.usernameDest && sender === recnotif.paramsObj.usernameDest) {
- newdescr = i18n.__('GROUPS_EXIT_USER_TO_ME', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
+ if (
+ recnotif.paramsObj.username_action === recnotif.paramsObj.usernameDest &&
+ sender === recnotif.paramsObj.usernameDest
+ ) {
+ newdescr = i18n.__(
+ 'GROUPS_EXIT_USER_TO_ME',
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.username_action
+ );
} else if (sender === recnotif.paramsObj.usernameDest) {
- newdescr = i18n.__('GROUPS_REMOVED_TO_ME', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
+ newdescr = i18n.__(
+ 'GROUPS_REMOVED_TO_ME',
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.username_action
+ );
} else if (sender === recnotif.paramsObj.username_action) {
newdescr = i18n.__('GROUPS_EXIT_USER', sender, recnotif.paramsObj.groupnameDest);
recnotif.openUrl = '/my/' + sender;
} else {
- newdescr = i18n.__('GROUPS_REMOVED', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
+ newdescr = i18n.__(
+ 'GROUPS_REMOVED',
+ sender,
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.username_action
+ );
}
tag = 'remgroup';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REFUSED) {
- newdescr = i18n.__('GROUPS_REFUSED', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
+ newdescr = i18n.__(
+ 'GROUPS_REFUSED',
+ sender,
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.username_action
+ );
tag = 'refgroup';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REQUEST_TO_ENTER) {
- newdescr = i18n.__('GROUP_REQUEST_TO_ENTER', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.singleadmin_username);
+ newdescr = i18n.__(
+ 'GROUP_REQUEST_TO_ENTER',
+ sender,
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.singleadmin_username
+ );
tag = 'reqgroups';
// sendnotifPush = false; // non lo rimandare 2 volte !
// telegrambot.askConfirmationUser(idapp, shared_consts.CallFunz.RICHIESTA_GRUPPO, myuser, singleadmin.username, groupname, group._id);
-
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_BLOCK_USER) {
- newdescr = i18n.__('RICHIESTA_BLOCCO_GRUPPO', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.singleadmin_username);
+ newdescr = i18n.__(
+ 'RICHIESTA_BLOCCO_GRUPPO',
+ sender,
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.singleadmin_username
+ );
tag = 'blockgroups';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_DELETE_USER) {
newdescr = i18n.__('GRUPPO_ELIMINATO', sender, recnotif.paramsObj.username_action);
tag = 'deletegroup';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_ADDED_ADMIN_OFMYGROUP) {
if (sender === recnotif.paramsObj.usernameDest) {
- newdescr = i18n.__('GROUPS_ADDED_ADMIN_GROUP_YOU', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
+ newdescr = i18n.__(
+ 'GROUPS_ADDED_ADMIN_GROUP_YOU',
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.username_action
+ );
} else {
- newdescr = i18n.__('GROUPS_ADDED_ADMIN_GROUP', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
+ newdescr = i18n.__(
+ 'GROUPS_ADDED_ADMIN_GROUP',
+ sender,
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.username_action
+ );
recnotif.openUrl = '/my/' + sender;
}
tag = 'addadmingrp';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_GROUP_REMOVED_ADMIN_OFMYGROUP) {
if (sender === recnotif.paramsObj.usernameDest) {
- newdescr = i18n.__('GROUPS_REMOVED_ADMIN_GROUP_YOU', recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
+ newdescr = i18n.__(
+ 'GROUPS_REMOVED_ADMIN_GROUP_YOU',
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.username_action
+ );
} else {
- newdescr = i18n.__('GROUPS_REMOVED_ADMIN_GROUP', sender, recnotif.paramsObj.groupnameDest, recnotif.paramsObj.username_action);
+ newdescr = i18n.__(
+ 'GROUPS_REMOVED_ADMIN_GROUP',
+ sender,
+ recnotif.paramsObj.groupnameDest,
+ recnotif.paramsObj.username_action
+ );
recnotif.openUrl = '/my/' + sender;
}
tag = 'removeadmingrp';
@@ -371,12 +440,17 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
let strtipocontoOrig = '';
let groupOComorig = '';
let groupOComdest = '';
- recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TAB_MYCIRCUITS, true) + recnotif.paramsObj.path;
+ recnotif.openUrl =
+ shared_consts.getDirectoryByTable(shared_consts.TAB_MYCIRCUITS, true) + recnotif.paramsObj.path;
if (recnotif.paramsObj.extrarec) {
strtipocontoOrig = recnotif.paramsObj.extrarec.contoComOrig ? i18n.__('COMUNITARIO') : i18n.__('COLLETTIVO');
strtipocontoDest = recnotif.paramsObj.extrarec.contoComDest ? i18n.__('COMUNITARIO') : i18n.__('COLLETTIVO');
- groupOComorig = recnotif.paramsObj.extrarec.contoComOrig ? recnotif.paramsObj.extrarec.contoComOrig : recnotif.paramsObj.extrarec.grouporig;
- groupOComdest = recnotif.paramsObj.extrarec.contoComDest ? recnotif.paramsObj.extrarec.contoComDest : recnotif.paramsObj.extrarec.groupdest;
+ groupOComorig = recnotif.paramsObj.extrarec.contoComOrig
+ ? recnotif.paramsObj.extrarec.contoComOrig
+ : recnotif.paramsObj.extrarec.grouporig;
+ groupOComdest = recnotif.paramsObj.extrarec.contoComDest
+ ? recnotif.paramsObj.extrarec.contoComDest
+ : recnotif.paramsObj.extrarec.groupdest;
}
let myorig = '';
let mydest = '';
@@ -389,22 +463,29 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
let numuserincircuit = 0;
try {
circuitname = recnotif.paramsObj.circuitnameDest;
- username_action = recnotif.paramsObj.username_action
- username_mittente = recnotif.paramsObj.sender ? recnotif.paramsObj.sender : username_action
+ username_action = recnotif.paramsObj.username_action;
+ username_mittente = recnotif.paramsObj.sender ? recnotif.paramsObj.sender : username_action;
myorig = recnotif.paramsObj.extrarec.grouporig;
- mydest = recnotif.paramsObj.extrarec.groupdest ? recnotif.paramsObj.extrarec.groupdest : recnotif.paramsObj.extrarec.dest;
- destinatario = recnotif.paramsObj.extrarec.dest ? recnotif.paramsObj.extrarec.dest : (recnotif.paramsObj.extrarec.groupdest ? recnotif.paramsObj.extrarec.groupdest : recnotif.paramsObj.extrarec.contoComDest);
- qty = recnotif.paramsObj.extrarec && recnotif.paramsObj.extrarec.qty ? recnotif.paramsObj.extrarec.qty.toString() : '';
+ mydest = recnotif.paramsObj.extrarec.groupdest
+ ? recnotif.paramsObj.extrarec.groupdest
+ : recnotif.paramsObj.extrarec.dest;
+ destinatario = recnotif.paramsObj.extrarec.dest
+ ? recnotif.paramsObj.extrarec.dest
+ : recnotif.paramsObj.extrarec.groupdest
+ ? recnotif.paramsObj.extrarec.groupdest
+ : recnotif.paramsObj.extrarec.contoComDest;
+ qty =
+ recnotif.paramsObj.extrarec && recnotif.paramsObj.extrarec.qty
+ ? recnotif.paramsObj.extrarec.qty.toString()
+ : '';
symbol = recnotif.paramsObj.extrarec ? recnotif.paramsObj.extrarec.symbol : '';
numuserincircuit = await User.countUsersInCircuit(recnotif.idapp, circuitname);
- } catch (e) {
-
- }
+ } catch (e) {}
recnotif.textaddTelegram = '';
if (groupOComdest) {
- destinatario += ' (' + username_mittente + ')'
+ destinatario += ' (' + username_mittente + ')';
}
const circuit = await Circuit.findOne({ name: circuitname });
@@ -414,34 +495,66 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SETFIDO) {
if (recnotif.paramsObj.isAdmin) {
if (recnotif.extrarec.groupname) {
- newdescr = i18n.__('FIDO_IMPOSTATO_ADMINS_CIRCUIT_MYGROUP', recnotif.extrarec.groupname, -recnotif.paramsObj.extrarec.fidoConcesso, recnotif.paramsObj.circuitnameDest,
- username_action);
+ newdescr = i18n.__(
+ 'FIDO_IMPOSTATO_ADMINS_CIRCUIT_MYGROUP',
+ recnotif.extrarec.groupname,
+ -recnotif.paramsObj.extrarec.fidoConcesso,
+ recnotif.paramsObj.circuitnameDest,
+ username_action
+ );
} else {
- newdescr = i18n.__('FIDO_IMPOSTATO_ADMINS_CIRCUIT', sender, -recnotif.paramsObj.extrarec.fidoConcesso, recnotif.paramsObj.circuitnameDest,
- username_action);
+ newdescr = i18n.__(
+ 'FIDO_IMPOSTATO_ADMINS_CIRCUIT',
+ sender,
+ -recnotif.paramsObj.extrarec.fidoConcesso,
+ recnotif.paramsObj.circuitnameDest,
+ username_action
+ );
}
recnotif.openUrl = '/my/' + sender;
} else {
- newdescr = i18n.__('FIDO_IMPOSTATO', -recnotif.paramsObj.extrarec.fidoConcesso, username_action, recnotif.paramsObj.circuitnameDest);
+ newdescr = i18n.__(
+ 'FIDO_IMPOSTATO',
+ -recnotif.paramsObj.extrarec.fidoConcesso,
+ username_action,
+ recnotif.paramsObj.circuitnameDest
+ );
}
tag = 'setfido';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_ACCEPTED) {
if (recnotif.paramsObj.isAdmin) {
if (recnotif.extrarec.groupname) {
- newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS_CIRCUIT_MYGROUP', recnotif.extrarec.groupname, recnotif.paramsObj.circuitnameDest,
- username_action);
+ newdescr = i18n.__(
+ 'ACCETTATO_NOTIFICA_ADMINS_CIRCUIT_MYGROUP',
+ recnotif.extrarec.groupname,
+ recnotif.paramsObj.circuitnameDest,
+ username_action
+ );
} else {
- newdescr = i18n.__('ACCETTATO_NOTIFICA_ADMINS_CIRCUIT', sender, recnotif.paramsObj.circuitnameDest,
- username_action);
+ newdescr = i18n.__(
+ 'ACCETTATO_NOTIFICA_ADMINS_CIRCUIT',
+ sender,
+ recnotif.paramsObj.circuitnameDest,
+ username_action
+ );
}
recnotif.openUrl = '/my/' + sender;
} else {
if (sender === recnotif.paramsObj.usernameDest) {
- newdescr = i18n.__('CIRCUIT_ACCEPTED', username_action, recnotif.paramsObj.circuitnameDest, tools.getHostByIdApp(recnotif.idapp) + recnotif.openUrl);
+ newdescr = i18n.__(
+ 'CIRCUIT_ACCEPTED',
+ username_action,
+ recnotif.paramsObj.circuitnameDest,
+ tools.getHostByIdApp(recnotif.idapp) + recnotif.openUrl
+ );
} else {
- newdescr = i18n.__('CIRCUIT_ACCEPTED_YOU', recnotif.paramsObj.usernameDest, recnotif.paramsObj.circuitnameDest);
+ newdescr = i18n.__(
+ 'CIRCUIT_ACCEPTED_YOU',
+ recnotif.paramsObj.usernameDest,
+ recnotif.paramsObj.circuitnameDest
+ );
}
}
tag = 'addcircuit';
@@ -461,40 +574,67 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REFUSED) {
if (recnotif.paramsObj.isAdmin) {
if (recnotif.extrarec.groupname) {
- newdescr = i18n.__('CIRCUIT_REFUSED_TO_MYGROUP', recnotif.extrarec.groupname, recnotif.paramsObj.circuitnameDest, username_action);
+ newdescr = i18n.__(
+ 'CIRCUIT_REFUSED_TO_MYGROUP',
+ recnotif.extrarec.groupname,
+ recnotif.paramsObj.circuitnameDest,
+ username_action
+ );
}
} else {
newdescr = i18n.__('CIRCUIT_REFUSED', username_action, recnotif.paramsObj.circuitnameDest);
}
tag = 'refcircuit';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REQUEST_TO_ENTER) {
-
aportador_solidario = await User.getAportadorSolidarioByUsername(recnotif.idapp, sender);
if (recnotif.extrarec.groupname) {
- newdescr = i18n.__('CIRCUIT_REQUEST_TO_ENTER_WITH_GROUP', recnotif.extrarec.groupname, recnotif.paramsObj.circuitnameDest,
- numuserincircuit, recnotif.paramsObj.singleadmin_username);
-
+ newdescr = i18n.__(
+ 'CIRCUIT_REQUEST_TO_ENTER_WITH_GROUP',
+ recnotif.extrarec.groupname,
+ recnotif.paramsObj.circuitnameDest,
+ numuserincircuit,
+ recnotif.paramsObj.singleadmin_username
+ );
} else {
- newdescr = i18n.__('CIRCUIT_REQUEST_TO_ENTER', sender, '' + recnotif.paramsObj.circuitnameDest + '', numuserincircuit, aportador_solidario);
+ newdescr = i18n.__(
+ 'CIRCUIT_REQUEST_TO_ENTER',
+ sender,
+ '' + recnotif.paramsObj.circuitnameDest + '',
+ numuserincircuit,
+ aportador_solidario
+ );
if (circuit.askManagerToEnter)
- newdescr = i18n.__('CIRCUIT_REQUEST_TO_ENTER_ASKMANAGER', sender, '' + recnotif.paramsObj.circuitnameDest + '', numuserincircuit, aportador_solidario);
-
+ newdescr = i18n.__(
+ 'CIRCUIT_REQUEST_TO_ENTER_ASKMANAGER',
+ sender,
+ '' + recnotif.paramsObj.circuitnameDest + '',
+ numuserincircuit,
+ aportador_solidario
+ );
}
-
const myadmins = await Circuit.getListAdmins(recnotif.idapp, recnotif.paramsObj.circuitnameDest);
recnotif.textaddTelegram += '\n' + i18n.__('CIRCUIT_ADMINS', myadmins.num, myadmins.str);
- recnotif.textaddTelegram += '\n' + i18n.__('CIRCUIT_WHERE_IS_PRESENT', await Circuit.getListCircuitsByUsername(recnotif.idapp, sender, recnotif.extrarec.groupname));
+ recnotif.textaddTelegram +=
+ '\n' +
+ i18n.__(
+ 'CIRCUIT_WHERE_IS_PRESENT',
+ await Circuit.getListCircuitsByUsername(recnotif.idapp, sender, recnotif.extrarec.groupname)
+ );
tag = 'reqcircuits';
-
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_DELETE_USER) {
newdescr = i18n.__('CIRCUIT_ELIMINATO', sender, username_action);
tag = 'deletecircuit';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_ADDED_ADMIN) {
if (sender === recnotif.paramsObj.usernameDest) {
- newdescr = i18n.__('CIRCUIT_ADDED_ADMIN_YOU', recnotif.paramsObj.usernameDest, recnotif.paramsObj.circuitnameDest, username_action);
+ newdescr = i18n.__(
+ 'CIRCUIT_ADDED_ADMIN_YOU',
+ recnotif.paramsObj.usernameDest,
+ recnotif.paramsObj.circuitnameDest,
+ username_action
+ );
} else {
newdescr = i18n.__('CIRCUIT_ADDED_ADMIN', sender, recnotif.paramsObj.circuitnameDest, username_action);
recnotif.openUrl = '/my/' + sender;
@@ -502,7 +642,12 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
tag = 'addadmingrp';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_REMOVED_ADMIN) {
if (sender === recnotif.paramsObj.usernameDest) {
- newdescr = i18n.__('CIRCUIT_REMOVED_ADMIN_YOU', recnotif.paramsObj.usernameDest, recnotif.paramsObj.circuitnameDest, username_action);
+ newdescr = i18n.__(
+ 'CIRCUIT_REMOVED_ADMIN_YOU',
+ recnotif.paramsObj.usernameDest,
+ recnotif.paramsObj.circuitnameDest,
+ username_action
+ );
} else {
newdescr = i18n.__('CIRCUIT_REMOVED_ADMIN', sender, recnotif.paramsObj.circuitnameDest, username_action);
recnotif.openUrl = '/my/' + sender;
@@ -510,93 +655,197 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
tag = 'removeadmincircuit';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ) {
if (groupOComdest) {
- newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_GROUP', tools.getAhref(username_action, await tools.getLinkUserTelegram(recnotif.idapp, username_action)), qty,
- symbol, strtipocontoDest, groupOComdest, circuitname);
- } else if (groupOComorig && (sender === recnotif.paramsObj.usernameDest)) {
- newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_YOU', strtipocontoOrig, groupOComorig, username_action, qty, symbol, recnotif.paramsObj.extrarec.dest, circuitname);
+ newdescr = i18n.__(
+ 'CIRCUIT_SENDCOINSREQ_GROUP',
+ tools.getAhref(username_action, await tools.getLinkUserTelegram(recnotif.idapp, username_action)),
+ qty,
+ symbol,
+ strtipocontoDest,
+ groupOComdest,
+ circuitname
+ );
+ } else if (groupOComorig && sender === recnotif.paramsObj.usernameDest) {
+ newdescr = i18n.__(
+ 'CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_YOU',
+ strtipocontoOrig,
+ groupOComorig,
+ username_action,
+ qty,
+ symbol,
+ recnotif.paramsObj.extrarec.dest,
+ circuitname
+ );
} else if (groupOComorig) {
- newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_USER', strtipocontoOrig, groupOComorig, username_action, qty, symbol, recnotif.paramsObj.extrarec.dest, circuitname);
+ newdescr = i18n.__(
+ 'CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_USER',
+ strtipocontoOrig,
+ groupOComorig,
+ username_action,
+ qty,
+ symbol,
+ recnotif.paramsObj.extrarec.dest,
+ circuitname
+ );
} else {
- newdescr = i18n.__('CIRCUIT_SENDCOINSREQ', tools.getAhref(username_action, await tools.getLinkUserTelegram(recnotif.idapp, username_action)), qty,
- symbol, circuitname);
+ newdescr = i18n.__(
+ 'CIRCUIT_SENDCOINSREQ',
+ tools.getAhref(username_action, await tools.getLinkUserTelegram(recnotif.idapp, username_action)),
+ qty,
+ symbol,
+ circuitname
+ );
}
tag = 'sendcoin';
- recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TAB_MYCIRCUITS, true) + recnotif.paramsObj.path; //++Todo: dove lo mando ?
+ recnotif.openUrl =
+ shared_consts.getDirectoryByTable(shared_consts.TAB_MYCIRCUITS, true) + recnotif.paramsObj.path; //++Todo: dove lo mando ?
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ_SENT) {
-
if (myorig) {
if (groupOComdest) {
- newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_GROUP', strtipocontoOrig, myorig, username_action, qty, symbol, strtipocontoDest, groupOComdest, circuitname);
+ newdescr = i18n.__(
+ 'CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_GROUP',
+ strtipocontoOrig,
+ myorig,
+ username_action,
+ qty,
+ symbol,
+ strtipocontoDest,
+ groupOComdest,
+ circuitname
+ );
} else {
- newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_USER', strtipocontoOrig, myorig, username_action, qty, symbol, mydest, circuitname);
+ newdescr = i18n.__(
+ 'CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_USER',
+ strtipocontoOrig,
+ myorig,
+ username_action,
+ qty,
+ symbol,
+ mydest,
+ circuitname
+ );
}
} else {
if (groupOComdest) {
- newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_TO_GROUP', qty, symbol, strtipocontoDest, groupOComdest, circuitname);
+ newdescr = i18n.__(
+ 'CIRCUIT_SENDCOINSREQ_TO_GROUP',
+ qty,
+ symbol,
+ strtipocontoDest,
+ groupOComdest,
+ circuitname
+ );
} else {
newdescr = i18n.__('CIRCUIT_SENDCOINSREQ_TO_ME', qty, symbol, mydest, circuitname);
}
}
tag = 'sendcoin';
- recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TAB_MYCIRCUITS, true) + recnotif.paramsObj.path; //++Todo: dove lo mando ?
+ recnotif.openUrl =
+ shared_consts.getDirectoryByTable(shared_consts.TAB_MYCIRCUITS, true) + recnotif.paramsObj.path; //++Todo: dove lo mando ?
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED) {
- newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED', qty, symbol,
- username_action, circuitname) + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
+ newdescr =
+ i18n.__('ID_CIRCUIT_COINS_ACCEPTED', qty, symbol, username_action, circuitname) +
+ `\n` +
+ i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
if (myorig) {
if (groupOComdest) {
- newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_FROM_GROUP_TO_GROUP', strtipocontoDest, myorig, username_action, qty, symbol, strtipocontoDest, groupOComdest, circuitname, username_mittente) + `\n`
- + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
-
+ newdescr =
+ i18n.__(
+ 'ID_CIRCUIT_COINS_ACCEPTED_FROM_GROUP_TO_GROUP',
+ strtipocontoDest,
+ myorig,
+ username_action,
+ qty,
+ symbol,
+ strtipocontoDest,
+ groupOComdest,
+ circuitname,
+ username_mittente
+ ) +
+ `\n` +
+ i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
} else {
- newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_FROM_GROUP_TO_YOU', qty, symbol, strtipocontoOrig, myorig, circuitname, username_action)
- + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
+ newdescr =
+ i18n.__(
+ 'ID_CIRCUIT_COINS_ACCEPTED_FROM_GROUP_TO_YOU',
+ qty,
+ symbol,
+ strtipocontoOrig,
+ myorig,
+ circuitname,
+ username_action
+ ) +
+ `\n` +
+ i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
}
} else {
if (groupOComdest) {
- newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_FROM_ME_TO_GROUP', strtipocontoDest, groupOComdest, username_action, qty, symbol, username_mittente)
- + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
+ newdescr =
+ i18n.__(
+ 'ID_CIRCUIT_COINS_ACCEPTED_FROM_ME_TO_GROUP',
+ strtipocontoDest,
+ groupOComdest,
+ username_action,
+ qty,
+ symbol,
+ username_mittente
+ ) +
+ `\n` +
+ i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
} else {
- newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_FROM_ME_TO_YOU', qty, symbol, username_action, circuitname)
- + `\n` + i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
+ newdescr =
+ i18n.__('ID_CIRCUIT_COINS_ACCEPTED_FROM_ME_TO_YOU', qty, symbol, username_action, circuitname) +
+ `\n` +
+ i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoDest, symbol, circuitname);
}
}
tag = 'sendcoin';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_ACCEPTED_SENT) {
if (!destinatario) {
- destinatario = username_action
+ destinatario = username_action;
}
let saldostr = i18n.__('SALDO_UPDATE', recnotif.paramsObj.extrarec.saldoOrig, symbol, circuitname);
if (groupOComorig) {
- saldostr = i18n.__('SALDO_UPDATE_WHO', groupOComorig, recnotif.paramsObj.extrarec.saldoOrig, symbol, circuitname);
+ saldostr = i18n.__(
+ 'SALDO_UPDATE_WHO',
+ groupOComorig,
+ recnotif.paramsObj.extrarec.saldoOrig,
+ symbol,
+ circuitname
+ );
}
- newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_TO_ME', qty, symbol, destinatario, circuitname)
- + `\n` + saldostr;
+ newdescr = i18n.__('ID_CIRCUIT_COINS_ACCEPTED_TO_ME', qty, symbol, destinatario, circuitname) + `\n` + saldostr;
tag = 'sendcoin';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED) {
newdescr = i18n.__('ID_CIRCUIT_COINS_REFUSED', qty, symbol, username_action, circuitname);
tag = 'sendcoin';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_COINS_REFUSED_SENT) {
-
newdescr = i18n.__('ID_CIRCUIT_COINS_REFUSED_TO_ME', qty, symbol, destinatario, circuitname);
tag = 'sendcoin';
}
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FAVORITE) {
- // ++ Controlla se esiste già
+ // ++ Controlla se esiste già
let esitegia = recnotif.paramsObj.recObjCreator.exist; // ++
if (esitegia)
- newdescr = i18n.__('SET_FAVORITE_OTHERS', recnotif.paramsObj.username_action, recnotif.paramsObj.recObjCreator.numfav - 1, recnotif.paramsObj.recObjCreator.descr);
+ newdescr = i18n.__(
+ 'SET_FAVORITE_OTHERS',
+ recnotif.paramsObj.username_action,
+ recnotif.paramsObj.recObjCreator.numfav - 1,
+ recnotif.paramsObj.recObjCreator.descr
+ );
else
newdescr = i18n.__('SET_FAVORITE', recnotif.paramsObj.username_action, recnotif.paramsObj.recObjCreator.descr);
tag = 'favorite';
- recnotif.openUrl = shared_consts.getDirectoryByTable(recnotif.paramsObj.recObjCreator.table, true) + recnotif.paramsObj.recObjCreator.id;
+ recnotif.openUrl =
+ shared_consts.getDirectoryByTable(recnotif.paramsObj.recObjCreator.table, true) +
+ recnotif.paramsObj.recObjCreator.id;
recnotif.linkaddTelegram = i18n.__('SHOW_POST');
}
@@ -606,34 +855,32 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
recnotif.descr = newdescr;
}
-
return recnotif;
} catch (e) {
console.error(e);
return null;
}
-
};
sendNotifSchema.statics.compileOtherFields = async function (arrnotif) {
-
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;
}
return arrnotif;
-
} catch (e) {
console.error(e);
return arrnotif;
}
-
};
sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function (username, idapp, limit) {
@@ -651,13 +898,13 @@ sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function (username, ida
{
$sort: { datenotif: -1 },
},
- ]).then(async (arrnotif) => {
- return this.compileOtherFields(arrnotif);
-
- }).catch((err) => {
- console.error(err);
- });
-
+ ])
+ .then(async (arrnotif) => {
+ return this.compileOtherFields(arrnotif);
+ })
+ .catch((err) => {
+ console.error(err);
+ });
};
sendNotifSchema.statics.findLastNotifCoinsByUserIdAndIdApp = function (username, idapp, limit, inattesa) {
@@ -667,7 +914,7 @@ sendNotifSchema.statics.findLastNotifCoinsByUserIdAndIdApp = function (username,
idapp,
typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS,
dest: username,
- }
+ };
if (inattesa) {
filter.status = 0;
@@ -683,13 +930,13 @@ sendNotifSchema.statics.findLastNotifCoinsByUserIdAndIdApp = function (username,
{
$sort: { datenotif: -1 },
},
- ]).then(async (arrnotif) => {
- return this.compileOtherFields(arrnotif);
-
- }).catch((err) => {
- console.error(err);
- });
-
+ ])
+ .then(async (arrnotif) => {
+ return this.compileOtherFields(arrnotif);
+ })
+ .catch((err) => {
+ console.error(err);
+ });
};
sendNotifSchema.statics.findAllNotifCoinsAllIdAndIdApp = function (idapp) {
@@ -700,9 +947,9 @@ sendNotifSchema.statics.findAllNotifCoinsAllIdAndIdApp = function (idapp) {
typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS,
typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ,
status: 0,
- 'extrarec.circuitname': { $ne: "Circuito di TEST" },
- 'extrarec.symbol': { $ne: "RISTeST" },
- }
+ 'extrarec.circuitname': { $ne: 'Circuito di TEST' },
+ 'extrarec.symbol': { $ne: 'RISTeST' },
+ };
return SendNotif.aggregate([
{
@@ -711,13 +958,13 @@ sendNotifSchema.statics.findAllNotifCoinsAllIdAndIdApp = function (idapp) {
{
$sort: { datenotif: -1 },
},
- ]).then(async (arrnotif) => {
- return this.compileOtherFields(arrnotif);
-
- }).catch((err) => {
- console.error(err);
- });
-
+ ])
+ .then(async (arrnotif) => {
+ return this.compileOtherFields(arrnotif);
+ })
+ .catch((err) => {
+ console.error(err);
+ });
};
sendNotifSchema.statics.saveAndSendNotif = async function (myrecnotif, req, res, user) {
@@ -725,13 +972,11 @@ sendNotifSchema.statics.saveAndSendNotif = async function (myrecnotif, req, res,
let idapp = req.body.idapp;
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) 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, req.user.username);
- if (!myrecout)
- return null;
+ if (!myrecout) return null;
// console.log('myrecout._id', myrecout._id.toString());
@@ -748,23 +993,32 @@ sendNotifSchema.statics.saveAndSendNotif = async function (myrecnotif, req, res,
// console.log('myrecread._id', myrecread._id.toString());
if (myrecread)
- risnotif = await globalTables.sendNotifCmd(myrecread.typedir, myrecread.typeid, res, idapp, user ? user : req.user, myrecread);
- else
- return false;
+ risnotif = await globalTables.sendNotifCmd(
+ myrecread.typedir,
+ myrecread.typeid,
+ res,
+ idapp,
+ user ? user : req.user,
+ myrecread
+ );
+ else return false;
}
-
} catch (e) {
console.log(e.message);
return null;
}
-
} else {
- risnotif = await globalTables.sendNotifCmd(myrecout.typedir, myrecout.typeid, res, idapp, user ? user : req.user, myrecout);
+ risnotif = await globalTables.sendNotifCmd(
+ myrecout.typedir,
+ myrecout.typeid,
+ res,
+ idapp,
+ user ? user : req.user,
+ myrecout
+ );
}
-
return risnotif;
-
};
sendNotifSchema.statics.updateStatusAndDescr = async function (myrecnotif, onlysave, userorig) {
@@ -817,8 +1071,7 @@ sendNotifSchema.statics.updateStatusAndDescr = async function (myrecnotif, onlys
newstatus = shared_consts.GroupsNotifs.STATUS_GROUPS_DELETED;
}
} else if (myrecnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_CIRCUITS) {
- if (myrecnotif.paramsObj.extrarec)
- idnotiftosearch = myrecnotif.paramsObj.extrarec.notifId;
+ if (myrecnotif.paramsObj.extrarec) idnotiftosearch = myrecnotif.paramsObj.extrarec.notifId;
typeidsearch = shared_consts.TypeNotifs.ID_CIRCUIT_NEW_REC;
dest = myrecnotif.dest;
@@ -893,17 +1146,17 @@ sendNotifSchema.statics.updateStatusAndDescr = async function (myrecnotif, onlys
datenotif: new Date(),
};
-
// Cerca il record e se lo trova lo aggiorna
- const myrec = await SendNotif.findOneAndUpdate(query,
+ const myrec = await SendNotif.findOneAndUpdate(
+ query,
{ $set: fields_to_update },
- { returnDocument: "after" }).lean();
+ { returnDocument: 'after' }
+ ).lean();
if (myrec) {
return { myrecout: myrec, save: true };
}
}
-
}
// myrecnotif._id = new ObjectId();
@@ -916,19 +1169,18 @@ sendNotifSchema.statics.updateStatusAndDescr = async function (myrecnotif, onlys
console.error(e);
return { myrecout: null, save: false };
}
-
};
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;
}
-
};
sendNotifSchema.statics.checkIfCoinsAlreadySent = async function (notifId) {
@@ -938,41 +1190,42 @@ sendNotifSchema.statics.checkIfCoinsAlreadySent = async function (notifId) {
const status = await SendNotif.getStatus(notifId);
if (status !== null) {
- return (status === shared_consts.CircuitsNotif.STATUS_COINS_ACCEPTED) ||
- (status === shared_consts.CircuitsNotif.STATUS_COINS_REFUSED);
+ return (
+ status === shared_consts.CircuitsNotif.STATUS_COINS_ACCEPTED ||
+ status === shared_consts.CircuitsNotif.STATUS_COINS_REFUSED
+ );
}
return true;
-
} catch (e) {
// If Error, don't send the coins
return true;
}
-
};
sendNotifSchema.statics.saveNotif = async function (myrecnotif, req) {
-
const SendNotif = this;
const { myrecout, save } = await SendNotif.updateStatusAndDescr(myrecnotif, true, req.user.username);
- if (!myrecout)
- return null;
+ if (!myrecout) return null;
- return await myrecout.save().then((writeresult) => {
- let idobj = writeresult._id;
- return SendNotif.findById(idobj).lean().then(async (recnotif) => {
- return recnotif;
+ return await myrecout
+ .save()
+ .then((writeresult) => {
+ let idobj = writeresult._id;
+ return SendNotif.findById(idobj)
+ .lean()
+ .then(async (recnotif) => {
+ return recnotif;
+ });
+ })
+ .catch((e) => {
+ console.log(e.message);
+ return null;
});
- }).catch((e) => {
- console.log(e.message);
- return null;
- });
-
};
sendNotifSchema.statics.getDefaultRec = function (req) {
-
return {
idapp: req.body.idapp,
typedir: '',
@@ -989,7 +1242,6 @@ sendNotifSchema.statics.getDefaultRec = function (req) {
tablerec: '',
idrec: 0,
};
-
};
sendNotifSchema.statics.getExtraParam = function (myrecnotif, paramsObj) {
@@ -1022,7 +1274,11 @@ sendNotifSchema.statics.createNewNotification = async function (req, res, params
myrecnotif.idrec = rec._id;
try {
if (rec.photos && rec.photos[0]) {
- const mydir = tools.getHostByIdApp(myrecnotif.idapp) + server_constants.DIR_UPLOAD + '/' + shared_consts.getDirectoryImgByTable(table, rec.username);
+ const mydir =
+ tools.getHostByIdApp(myrecnotif.idapp) +
+ server_constants.DIR_UPLOAD +
+ '/' +
+ shared_consts.getDirectoryImgByTable(table, rec.username);
myrecnotif.img = mydir + rec.photos[0].imagefile;
}
} catch (e) {
@@ -1030,11 +1286,9 @@ sendNotifSchema.statics.createNewNotification = async function (req, res, params
}
}
-
myrecnotif.typedir = typedir;
myrecnotif.typeid = typeid;
-
await SendNotif.sendToTheDestinations(myrecnotif, req, res);
return true;
@@ -1055,7 +1309,6 @@ sendNotifSchema.statics.createNewNotifToSingleUser = async function (req, res, p
myrecnotif = this.getExtraParam(myrecnotif, paramsObj);
return await SendNotif.sendToSingleUserDest(myrecnotif, req, res, onlysave);
-
} catch (e) {
console.error('createNewNotification', e);
return null;
@@ -1071,30 +1324,30 @@ sendNotifSchema.statics.sendToTheDestinations = async function (myrecnotifpass,
const { Province } = require('../models/province');
try {
-
// Send only to the destination to reach:
- const userlist = await User.find({
- idapp: myrecnotifpass.idapp,
- // username: 'SuryaArena2', //TOGLIERE
- $or: [
- { deleted: { $exists: false } },
- { deleted: { $exists: true, $eq: false } }],
- }, {
- name: 1,
- surname: 1,
- lasttimeonline: 1,
- lang: 1,
- username: 1,
- 'profile.notifs': 1,
- 'profile.mycircuits': 1,
- 'profile.resid_province': 1,
- 'profile.resid_card': 1,
- 'profile.notif_idCities': 1,
- 'profile.notif_provinces': 1,
- 'profile.notif_regions': 1,
- 'profile.notif_sectors': 1,
- 'profile.notif_sector_goods': 1,
- }).lean();
+ const userlist = await User.find(
+ {
+ idapp: myrecnotifpass.idapp,
+ // username: 'SuryaArena2', //TOGLIERE
+ $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
+ },
+ {
+ name: 1,
+ surname: 1,
+ lasttimeonline: 1,
+ lang: 1,
+ username: 1,
+ 'profile.notifs': 1,
+ 'profile.mycircuits': 1,
+ 'profile.resid_province': 1,
+ 'profile.resid_card': 1,
+ 'profile.notif_idCities': 1,
+ 'profile.notif_provinces': 1,
+ 'profile.notif_regions': 1,
+ 'profile.notif_sectors': 1,
+ 'profile.notif_sector_goods': 1,
+ }
+ ).lean();
let arrcircuits = [];
let arrprovinces = [];
@@ -1103,10 +1356,14 @@ sendNotifSchema.statics.sendToTheDestinations = async function (myrecnotifpass,
const mytable = globalTables.getTableByTableName(myrecnotifpass.tablerec);
- if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA || myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_EVENTS) {
- if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec) ||
- shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)) {
-
+ if (
+ myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA ||
+ myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_EVENTS
+ ) {
+ if (
+ shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec) ||
+ shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)
+ ) {
if (myrecnotifpass.idrec && myrecnotifpass.idrec !== '0') {
// const myrectableorig = await mytable.findOne({ _id: myrecnotifpass.idrec }).lean();
const myrectableorig = await mytable.getCompleteRecord(myrecnotifpass.idapp, myrecnotifpass.idrec);
@@ -1123,7 +1380,6 @@ sendNotifSchema.statics.sendToTheDestinations = async function (myrecnotifpass,
} else {
idSector = myrectableorig.idSector;
}
-
}
myrecnotifpass.myrectableorig = myrectableorig;
}
@@ -1134,121 +1390,147 @@ sendNotifSchema.statics.sendToTheDestinations = async function (myrecnotifpass,
delete myrecnotifpass._doc['_id'];
for (const user of userlist) {
+ try {
+ const mycircuits = user.profile.mycircuits;
- const mycircuits = user.profile.mycircuits;
+ if (user.profile && user.profile.notifs) {
+ const usernotifprofile = user.profile.notifs.find((notif) => notif.dir === myrecnotifpass.typedir);
- if (user.profile && user.profile.notifs) {
- const usernotifprofile = user.profile.notifs.find((notif) => notif.dir === myrecnotifpass.typedir);
+ let send = false;
- let send = false;
-
-
- if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_EVENTS) {
- if (myrecnotifpass.tablerec === shared_consts.TABLES_MYBACHECAS) {
- if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.TypeNotifs.ID_EVENTS_ATTEND)) {
- send = true;
+ if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_EVENTS) {
+ if (myrecnotifpass.tablerec === shared_consts.TABLES_MYBACHECAS) {
+ if (
+ usernotifprofile &&
+ tools.isBitActive(usernotifprofile.value, shared_consts.TypeNotifs.ID_EVENTS_ATTEND)
+ ) {
+ send = true;
+ }
}
}
- }
- if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_FAVORITE) {
- if (shared_consts.TABLES_FAVORITE_BOOKMARK.includes(myrecnotifpass.tablerec)) {
- if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.TypeNotifs.ID_FAVORITE_ADDED)) {
- send = true;
+ if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_FAVORITE) {
+ if (shared_consts.TABLES_FAVORITE_BOOKMARK.includes(myrecnotifpass.tablerec)) {
+ if (
+ usernotifprofile &&
+ tools.isBitActive(usernotifprofile.value, shared_consts.TypeNotifs.ID_FAVORITE_ADDED)
+ ) {
+ send = true;
+ }
}
- }
- } else if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA
- || myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_EVENTS
- || myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_GROUPS
- ) {
- if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec)
- || shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)
- || shared_consts.TABLES_GROUPS_NOTIFICATION.includes(myrecnotifpass.tablerec)
+ } else if (
+ myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA ||
+ myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_EVENTS ||
+ myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_GROUPS
) {
- // Estrai la Città, la Provincia e la regione.
+ if (
+ shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec) ||
+ shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec) ||
+ shared_consts.TABLES_GROUPS_NOTIFICATION.includes(myrecnotifpass.tablerec)
+ ) {
+ // Estrai la Città, la Provincia e la regione.
- if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_YOUR_PROVINCE) &&
- user.profile.resid_province && arrprovinces.indexOf(user.profile.resid_province) >= 0) {
- send = true;
- }
- 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)) {
- send = true;
- }
+ if (
+ usernotifprofile &&
+ tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_YOUR_PROVINCE) &&
+ user.profile.resid_province &&
+ arrprovinces.indexOf(user.profile.resid_province) >= 0
+ ) {
+ send = true;
+ }
+ 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)
+ ) {
+ 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)) {
- 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)
+ ) {
+ send = true;
+ }
- if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_MY_RIS_CIRCUIT) &&
- user.profile.mycircuits && user.profile.mycircuits.some(r => arrcircuits.indexOf(r.circuitname) >= 0)) {
- send = true;
- }
+ if (
+ usernotifprofile &&
+ tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_MY_RIS_CIRCUIT) &&
+ user.profile.mycircuits &&
+ user.profile.mycircuits.some((r) => arrcircuits.indexOf(r.circuitname) >= 0)
+ ) {
+ send = true;
+ }
- if (idSector && usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_SECTOR)) {
- // Controlla se è del settore selezionato
- if (myrecnotifpass.tablerec === shared_consts.TABLES_MYGOODS) {
- if (user.profile.notif_sector_goods) {
- send = send && (user.profile.notif_sector_goods.includes(idSector));
+ if (
+ idSector &&
+ usernotifprofile &&
+ tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_SECTOR)
+ ) {
+ // Controlla se è del settore selezionato
+ if (myrecnotifpass.tablerec === shared_consts.TABLES_MYGOODS) {
+ if (user.profile.notif_sector_goods) {
+ send = send && user.profile.notif_sector_goods.includes(idSector);
+ }
+ } else if (user.profile.notif_sectors) {
+ send = send && user.profile.notif_sectors.includes(idSector);
}
- } else if (user.profile.notif_sectors) {
- send = send && (user.profile.notif_sectors.includes(idSector));
}
}
-
+ /*} else if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_GROUPS) {
+ if (shared_consts.TABLES_GROUPS_NOTIFICATION.includes(myrecnotifpass.tablerec)) {
+ if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.GroupsNotifs.STATUS_GROUPS_NEW)) {
+ send = true;
+ }
+ }
+ } else if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_CIRCUITS) {
+ if (shared_consts.TABLES_CIRCUITS_NOTIFICATION.includes(myrecnotifpass.tablerec)) {
+ if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.CircuitsNotif.STATUS_NEW)) {
+ send = true;
+ }
+ }*/
}
- /*} else if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_GROUPS) {
- if (shared_consts.TABLES_GROUPS_NOTIFICATION.includes(myrecnotifpass.tablerec)) {
- if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.GroupsNotifs.STATUS_GROUPS_NEW)) {
- send = true;
- }
- }
- } else if (myrecnotifpass.typedir === shared_consts.TypeNotifs.TYPEDIR_CIRCUITS) {
- if (shared_consts.TABLES_CIRCUITS_NOTIFICATION.includes(myrecnotifpass.tablerec)) {
- if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.CircuitsNotif.STATUS_NEW)) {
- send = true;
- }
- }*/
- }
- if (send) {
- let myrecnotif = new SendNotif(myrecnotifpass);
- myrecnotif.dest = user.username;
- await SendNotif.saveAndSendNotif(myrecnotif, req, res, user);
+ if (send) {
+ let myrecnotif = new SendNotif(myrecnotifpass);
+ myrecnotif.dest = user.username;
+ await SendNotif.saveAndSendNotif(myrecnotif, req, res, user);
+ }
}
+ } catch (e) {
+ console.error('❌ Error: sendToTheDestinations - user', user.username, 'Err:', e);
}
}
} catch (e) {
console.error('sendToTheDestinations', e);
return false;
}
-
};
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.dest =
+ myrecnotif.paramsObj && myrecnotif.paramsObj.usernameDest ? myrecnotif.paramsObj.usernameDest : '';
+ myrecnotif.username_worked =
+ myrecnotif.paramsObj && myrecnotif.paramsObj.username_worked
+ ? myrecnotif.paramsObj.username_worked
+ : myrecnotif.dest;
if (onlysave) {
return await SendNotif.saveNotif(myrecnotif, req);
} else {
return await SendNotif.saveAndSendNotif(myrecnotif, req, res, null);
}
-
} catch (e) {
console.error('sendToSingleUserDest', e);
return false;
}
-
};
-
sendNotifSchema.statics.getSumPendingTransactionsMittente = async function (idapp, username, circuitname, groupname) {
const SendNotif = this;
@@ -1267,11 +1549,9 @@ sendNotifSchema.statics.getSumPendingTransactionsMittente = async function (idap
}
return await SendNotif.find(query).lean();
-
} catch (e) {
console.error('e', e);
}
-
};
sendNotifSchema.statics.getSumPendingTransactionsDest = async function (idapp, username, circuitname, groupname) {
@@ -1294,32 +1574,26 @@ sendNotifSchema.statics.getSumPendingTransactionsDest = async function (idapp, u
}
return await SendNotif.find(query).lean();
-
} catch (e) {
console.error('e', e);
}
-
};
sendNotifSchema.statics.RemovePendentTransactions = async function (idapp) {
const SendNodif = this;
try {
- const result = await SendNodif.deleteMany(
- {
- idapp,
- typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS,
- typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ,
- status: 0,
- }
- );
+ const result = await SendNodif.deleteMany({
+ idapp,
+ typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS,
+ typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ,
+ status: 0,
+ });
return result;
} catch (error) {
console.error('Error deleting documents:', error);
throw error;
}
-
-
};
sendNotifSchema.statics.RemoveOldNotif = async function (idapp, numgg) {
@@ -1328,57 +1602,58 @@ sendNotifSchema.statics.RemoveOldNotif = async function (idapp, numgg) {
const currentDate = new Date();
const limitDate = new Date(currentDate.setDate(currentDate.getDate() - numgg));
- return await SendNodif.deleteMany(
- {
- idapp,
- date_created: { $lt: limitDate },
- // typedir: { $ne: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS },
- $or: [
- { typeid: { $ne: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ } },
- { status: { $ne: 0 } }
- ]
- }
- );
-
+ return await SendNodif.deleteMany({
+ idapp,
+ date_created: { $lt: limitDate },
+ // typedir: { $ne: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS },
+ $or: [{ typeid: { $ne: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ } }, { status: { $ne: 0 } }],
+ });
};
sendNotifSchema.statics.RemoveOldNotif90 = async function (idapp) {
return this.RemoveOldNotif(idapp, 90);
-}
+};
sendNotifSchema.statics.RemoveOldNotif30 = async function (idapp) {
return this.RemoveOldNotif(idapp, 30);
-}
+};
sendNotifSchema.statics.updatePendingTransactions = async function (recnotif) {
-
const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');
try {
if (recnotif && recnotif.extrarec && recnotif.extrarec.circuitname) {
-
const circuit = await Circuit.getCircuitByName(recnotif.idapp, recnotif.extrarec.circuitname);
- const accountdestTable = await Account.getAccountByUsernameAndCircuitId(recnotif.idapp, recnotif.extrarec.dest, circuit._id, true, false, recnotif.extrarec.groupdest, recnotif.extrarec.contoComDest);
- const accountorigTable = await Account.getAccountByUsernameAndCircuitId(recnotif.idapp, recnotif.sender, circuit._id, true, true, recnotif.extrarec.grouporig, recnotif.extrarec.contoComOrig);
-
- if (accountdestTable)
- await accountdestTable.calcPending(false);
- if (accountorigTable)
- await accountorigTable.calcPending(true);
+ const accountdestTable = await Account.getAccountByUsernameAndCircuitId(
+ recnotif.idapp,
+ recnotif.extrarec.dest,
+ circuit._id,
+ true,
+ false,
+ recnotif.extrarec.groupdest,
+ recnotif.extrarec.contoComDest
+ );
+ const accountorigTable = await Account.getAccountByUsernameAndCircuitId(
+ recnotif.idapp,
+ recnotif.sender,
+ circuit._id,
+ true,
+ true,
+ recnotif.extrarec.grouporig,
+ recnotif.extrarec.contoComOrig
+ );
+ if (accountdestTable) await accountdestTable.calcPending(false);
+ if (accountorigTable) await accountorigTable.calcPending(true);
}
} catch (e) {
console.error(e);
}
-
};
-
-sendNotifSchema.statics.checkIfAlreadyExist = async function (idapp, tag, idpost, numtab) {
-
-};
+sendNotifSchema.statics.checkIfAlreadyExist = async function (idapp, tag, idpost, numtab) {};
const SendNotif = mongoose.model('SendNotif', sendNotifSchema);
diff --git a/src/server/modules/GenPdf.js b/src/server/modules/GenPdf.js
index 2877e58..7868cdd 100644
--- a/src/server/modules/GenPdf.js
+++ b/src/server/modules/GenPdf.js
@@ -430,7 +430,7 @@ class GenPdf {
}
async onlinePdfFromIdCatalog(options) {
- const risout = await GenPdf.onlinePdf(options);
+ const risout = await this.onlinePdf(options);
}
async generatePdfFromIdCatalog(options) {
diff --git a/src/server/router/admin_router.js b/src/server/router/admin_router.js
index 736346c..1dcedd8 100755
--- a/src/server/router/admin_router.js
+++ b/src/server/router/admin_router.js
@@ -64,9 +64,13 @@ const GenPdf = require('../modules/GenPdf');
const genPdf = new GenPdf();
-(async () => {
- await genPdf.launch();
-})();
+let genPdfLaunched = false;
+function launchGenPdfIfNeeded() {
+ if (!genPdfLaunched) {
+ genPdfLaunched = true;
+ genPdf.launch();
+ }
+}
async function updateProductInfo(recproductInfoAttuale, product, idapp, mycatstr) {
if (!recproductInfoAttuale || !mycatstr) return recproductInfoAttuale;
@@ -618,6 +622,8 @@ router.post('/online-pdf', authenticate, async (req, res) => {
console.log('/online-pdf');
try {
+ launchGenPdfIfNeeded(); // Ensure GenPdf is launched before proceeding
+
const risout = await GenPdf.onlinePdf(req.body);
return res.status(200).send(risout);
@@ -2641,6 +2647,7 @@ router.post('/generate-pdf', async (req, res) => {
}
try {
+ launchGenPdfIfNeeded(); // Ensure GenPdf is launched before proceeding
const pdfPath = await genPdf.generatePdfFromUrl(url, filename);
res.download(pdfPath);
} catch (error) {
diff --git a/src/server/router/api_router.js b/src/server/router/api_router.js
index 163e37e..292c23c 100644
--- a/src/server/router/api_router.js
+++ b/src/server/router/api_router.js
@@ -52,7 +52,7 @@ router.post('/track-pageview', authenticate_noerror, async (req, res) => {
await pageView.save();
- res.status(200).json({ message: 'Visita registrata' });
+ res.status(200).json({ message: '' });
} catch (error) {
console.error('Errore nel salvataggio della visita:', error);
res.status(500).json({ error: 'Impossibile registrare la visita' });
diff --git a/src/server/sendemail.js b/src/server/sendemail.js
index 788dbc4..7799520 100755
--- a/src/server/sendemail.js
+++ b/src/server/sendemail.js
@@ -106,6 +106,15 @@ module.exports = {
}*/
}
+ // se non è presente la password, non inviare l'email e manda messaggio di errore !
+
+ if (!paramemail.transport.options.auth.pass) {
+ let email = paramemail.transport.options.auth.user;
+
+ console.error('❌ Password mancante ! Impossibile inviare le email. user=', email);
+ return false;
+ }
+
// console.table(paramemail.transport);
// console.log('2 . paramemail.transport', paramemail.transport);
@@ -125,9 +134,13 @@ module.exports = {
},
locals: mylocalsconf,
}).then((ris) => {
+ if (ris?.response && ris.response.includes('Ok')) {
+ console.log('✅ Email INVIATA')
+ }
// console.log('ris EMAIL', ris);
return !!ris;
}).catch((err) => {
+ console.log('❌ Email NON INVIATA!');
console.error('sendEmail_base Error: ', err);
return false;
});
@@ -754,7 +767,7 @@ module.exports = {
},
getTransport: (mylocalsconf) => {
- console.log('getTransport');
+ // console.log('getTransport');
// Create Transport
let smtpTransport = null;
diff --git a/src/server/server.js b/src/server/server.js
index d8f49d7..640de78 100755
--- a/src/server/server.js
+++ b/src/server/server.js
@@ -267,13 +267,13 @@ connectToDatabase(connectionUrl, options)
await tools.getApps();
+ let miapass = '';
+
if (process.env.PROD !== 1) {
testmsgwebpush();
// tools.sendNotifToAdmin('Riparti', 'Riparti');
- let miapass = '';
-
if (miapass !== '') {
let crypt = tools.cryptdata(miapass);
let decrypt = tools.decryptdata(crypt);
@@ -285,8 +285,24 @@ connectToDatabase(connectionUrl, options)
mycron();
}
+ miapass = 'PROVA123@';
+ let crypt = tools.cryptdata(miapass);
+ let decrypt = tools.decryptdata(crypt);
+
telegrambot = require('./telegram/telegrambot');
+ if (decrypt === miapass) {
+ console.log('✅ Decrypt OK');
+ // OK FUNZIONA
+ } else {
+ let msgerr = '❌ ERRORE! la decrittazione non funziona! ';
+ console.error(msgerr);
+ await telegrambot.sendMsgTelegramToTheAdminAllSites(
+ msgerr,
+ false
+ );
+ }
+
await inizia();
await resetProcessingJob();
@@ -536,14 +552,14 @@ connectToDatabase(connectionUrl, options)
try {
// console.log('checkdir', folderprof);
- if (!await tools.isFileExistsAsync(folderprof)) {
+ if (!(await tools.isFileExistsAsync(folderprof))) {
console.log('*** Creadir', folderprof);
await fs.mkdirSync(folderprof);
}
folderprof = dir + 'profile/' + myuser.username + '/' + table;
// console.log('checkdir', folderprof);
- if (!await tools.isFileExistsAsync(folderprof)) {
+ if (!(await tools.isFileExistsAsync(folderprof))) {
console.log('creadir', folderprof);
await fs.mkdirSync(folderprof);
}
@@ -559,18 +575,18 @@ connectToDatabase(connectionUrl, options)
// console.log('file', file);
// console.log('filefrom', filefrom);
- if (!await tools.isFileExistsAsync(file)) {
+ if (!(await tools.isFileExistsAsync(file))) {
// non esiste
console.log('non esiste', file);
console.log(' filefrom', filefrom);
console.log(' filefrom2', filefrom2);
}
- if (!await tools.isFileExistsAsync(file) && await tools.isFileExistsAsync(filefrom)) {
+ if (!(await tools.isFileExistsAsync(file)) && (await tools.isFileExistsAsync(filefrom))) {
console.log('@@@@@@ copia file:', filefrom, 'a', file);
tools.copy(filefrom, file);
}
- if (!await tools.isFileExistsAsync(file) && await tools.isFileExistsAsync(filefrom2)) {
+ if (!(await tools.isFileExistsAsync(file)) && (await tools.isFileExistsAsync(filefrom2))) {
console.log('@@@@@@ copia file 2:', filefrom2, 'a', file);
tools.copy(filefrom2, file);
}
@@ -693,10 +709,10 @@ connectToDatabase(connectionUrl, options)
}
// Verifica esistenza file
- if (!await tools.isFileExistsAsync(keyPath)) {
+ if (!(await tools.isFileExistsAsync(keyPath))) {
throw new Error(`Chiave privata non trovata: ${keyPath}`);
}
- if (!await tools.isFileExistsAsync(certPath)) {
+ if (!(await tools.isFileExistsAsync(certPath))) {
throw new Error(`Certificato non trovato: ${certPath}`);
}
@@ -772,8 +788,13 @@ connectToDatabase(connectionUrl, options)
function buildAllowedOrigins(domains, domainsAllowed, isProduction) {
if (!isProduction) {
- return ['https://localhost:3000', 'https://localhost:8089', 'https://localhost:8084',
- 'https://localhost:8088', 'https://localhost:8099'];
+ return [
+ 'https://localhost:3000',
+ 'https://localhost:8089',
+ 'https://localhost:8084',
+ 'https://localhost:8088',
+ 'https://localhost:8099',
+ ];
}
const baseOrigins = domains.flatMap((domain) => [
@@ -804,7 +825,7 @@ connectToDatabase(connectionUrl, options)
const originValidator = (origin, callback) => {
if (!origin) {
- console.log('✅ Origin undefined or empty — allowing');
+ // console.log('✅ Origin undefined or empty — allowing');
return callback(null, true);
}
@@ -947,7 +968,7 @@ connectToDatabase(connectionUrl, options)
if (scriptProcess) scriptProcess.kill();
const scriptPath = path.join(__dirname, '..', '..', parsed.scriptName);
- if (!await tools.isFileExistsAsync(scriptPath)) {
+ if (!(await tools.isFileExistsAsync(scriptPath))) {
return ws.send(JSON.stringify({ type: 'error', data: 'Script non trovato o non autorizzato' }));
}
diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js
index 1574c97..e47ab3e 100755
--- a/src/server/telegram/telegrambot.js
+++ b/src/server/telegram/telegrambot.js
@@ -54,15 +54,15 @@ const emo = {
EYES: '😜',
DIZZY: '💫',
ONE_HUNDRED: '💯',
- SMILE_STAR: '🤩', // Star-struck
+ SMILE_STAR: '🤩', // Star-struck
LEFT_FACING_FIST: '🤛', // Left-facing fist
- CHECK_VERDE: '✅', // White check mark (verde)
- CHECK_GRIGIA: '☑️', // Ballot box with check (grigia)
- CROSS_ROSSA: '❌', // X (rossa)
- ENVELOPE: '✉️', // Envelope
+ CHECK_VERDE: '✅', // White check mark (verde)
+ CHECK_GRIGIA: '☑️', // Ballot box with check (grigia)
+ CROSS_ROSSA: '❌', // X (rossa)
+ ENVELOPE: '✉️', // Envelope
EXCLAMATION_MARK: '❗', // Exclamation mark
- QUESTION_MARK: '❓', // Question mark
- ARROW_RIGHT: '➡️', // Arrow pointing to the right
+ QUESTION_MARK: '❓', // Question mark
+ ARROW_RIGHT: '➡️', // Arrow pointing to the right
INVITATI: '',
HEART: '❤️',
BLUE_HEART: '💙',
@@ -83,109 +83,56 @@ const emo = {
MsgBot = {
OK: ['si', 'ok'],
CUORE: ['❤️', '💚️', '💜'],
- CIAO: [
- 'ciao',
- 'ciaoo',
- 'hola',
- 'holaa',
- 'hey',
- 'salve',
- 'buongiorno',
- 'buondi',
- 'ciao ❤️'],
- CI_SEI: ['ci sei', 'c\'è qualcuno', 'c\'è nessuno'],
+ CIAO: ['ciao', 'ciaoo', 'hola', 'holaa', 'hey', 'salve', 'buongiorno', 'buondi', 'ciao ❤️'],
+ CI_SEI: ['ci sei', "c'è qualcuno", "c'è nessuno"],
CHI_SONO_IO: ['chi sono io', 'chi sono'],
- COME_STAI: [
- 'tutto bene',
- 'come stai',
- 'come stai',
- 'come va',
- 'come butta',
- 'come va oggi'],
+ COME_STAI: ['tutto bene', 'come stai', 'come stai', 'come va', 'come butta', 'come va oggi'],
COME_TI_CHIAMI: [
'chi sei',
'come ti chiami',
- 'qual\'è il tuo nome',
- 'qual\'e\' il tuo nome',
+ "qual'è il tuo nome",
+ "qual'e' il tuo nome",
'che lavoro fai',
- 'di cosa ti occupi'],
+ 'di cosa ti occupi',
+ ],
COSA_FAI: ['cosa fai', 'cosa combini', 'che fai'],
QUANTI_ANNI_HAI: ['quanti anni hai', 'che età hai'],
SEI_LIBERO_STASERA: [
'sei libera stasera',
'sei libero stasera',
'usciamo insieme',
- 'fare l\'amore con me',
+ "fare l'amore con me",
'fare sesso',
'vuoi scopare',
- 'vuoi trombare'],
+ 'vuoi trombare',
+ ],
MI_TROVI_UN_MOROSO: [
'trovi un moroso',
'una morosa',
'fidanzato',
'fidanzata',
'trovi un marito',
- 'trovi una moglie'],
+ 'trovi una moglie',
+ ],
CHAT_EMPOWER: ['chat empower'],
- MASCHIO_FEMMINA: [
- 'sei uomo o donna',
- 'sei maschio o femmina',
- 'sei ragazzo o ragazza',
- 'che sesso hai'],
+ MASCHIO_FEMMINA: ['sei uomo o donna', 'sei maschio o femmina', 'sei ragazzo o ragazza', 'che sesso hai'],
DAMMI_UN_BACIO: ['dammi un bacio', 'baciami'],
HAHA: ['hahaha', 'ahah', '😂'],
MI_AMI: ['mi ami'],
TI_AMO: ['ti amo', 'ti adoro', 'ti lovvo'],
PREGO: ['prego', 'Prego ! 💋💋💋'],
- GRAZIE: [
- 'grazie ainy',
- 'grazie',
- 'grazie mille',
- 'graziee',
- 'grazie ❤',
- 'grazie️❤',
- 'grazie 😘',
- 'grazie😘'],
+ GRAZIE: ['grazie ainy', 'grazie', 'grazie mille', 'graziee', 'grazie ❤', 'grazie️❤', 'grazie 😘', 'grazie😘'],
PRINCIPE_AZZURRO: ['principe azzurro'],
START_INV: ['/start inv'],
- COSE_COVID: [
- 'cos\'è il covid',
- 'cosa è il covid',
- ],
- COVID: [
- 'covid',
- ],
- SPOSAMI: [
- 'sposami',
- 'vuoi sposar',
- 'sei sposat',
- 'ci sposiamo',
- 'ti sposo',
- 'sei sposat',
- 'mi sposi'],
+ COSE_COVID: ["cos'è il covid", 'cosa è il covid'],
+ COVID: ['covid'],
+ SPOSAMI: ['sposami', 'vuoi sposar', 'sei sposat', 'ci sposiamo', 'ti sposo', 'sei sposat', 'mi sposi'],
CHE_TEMPO_FA: ['che tempo'],
NON_TROO_INVITATI: ['non trovo invitati', 'non riesco a trovare invitati'],
- TROVAMI_UN_UOMO_DONNA: [
- 'trovami un uomo',
- 'trovami una donna',
- 'esiste una donna per me',
- 'esiste un uomo per me'],
- PAROLACCE: [
- 'stronz',
- 'fanculo',
- 'fottiti',
- 'cagare',
- 'ammazzat',
- 'muori',
- 'cretino',
- 'stupido'],
+ TROVAMI_UN_UOMO_DONNA: ['trovami un uomo', 'trovami una donna', 'esiste una donna per me', 'esiste un uomo per me'],
+ PAROLACCE: ['stronz', 'fanculo', 'fottiti', 'cagare', 'ammazzat', 'muori', 'cretino', 'stupido'],
COME_SI_CHIAMA: ['come si chiama'],
- PROSSIMO_ZOOM: [
- 'prossimo zoom',
- 'fare lo zoom',
- 'gli zoom',
- 'conferenz',
- 'zoom'],
+ PROSSIMO_ZOOM: ['prossimo zoom', 'fare lo zoom', 'gli zoom', 'conferenz', 'zoom'],
LAVAGNA: ['lavagna', 'Lavagna', 'LAVAGNA'],
SEI_LIBERO_DI_RESPIRARE: ['sei libero di respirare'],
SEI_LIBERO: ['sei liber', 'sei sposat', 'sei fidanzat', 'sei single'],
@@ -199,15 +146,10 @@ MsgBot = {
'mi aiuti',
'aiutami',
'posso chiederti',
- 'puoi aiutarmi'],
+ 'puoi aiutarmi',
+ ],
UOMO: ['uomo', 'maschio'],
- SORPRESA: [
- 'noo',
- 'davvero',
- 'sii',
- 'facciamo festa',
- 'è qui la festa',
- 'festa'],
+ SORPRESA: ['noo', 'davvero', 'sii', 'facciamo festa', 'è qui la festa', 'festa'],
UGUALE: ['👍🏻', '✨', '❤🏻', '⭐', '❤', '❤❤', '🤩'],
SI: ['si', 'yes'],
NO: ['no', 'noo'],
@@ -219,9 +161,12 @@ 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,
+ CHAT_EMPOWER:
+ 'Entra nella Chat EMPOWER !!!\n' +
+ 'https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g ' +
+ emo.PURPLE_HEART +
+ emo.GIFT_HEART +
+ emo.BLUE_HEART,
};
function getemojibynumber(number) {
@@ -370,11 +315,7 @@ const InlineConferma = {
RISPOSTA_NO: 'r_n',
};
-const SendMsgCmd = [
- CONTA_SOLO,
- RICEVI_EMAIL,
- NOME_COGNOME,
- CHEDI_SE_IMBARCARTI];
+const SendMsgCmd = [CONTA_SOLO, RICEVI_EMAIL, NOME_COGNOME, CHEDI_SE_IMBARCARTI];
// const MenuNoLogin = {
// it: { menu: [[Menu.LANG], [Menu.it.ASSISTENZA]] },
@@ -394,7 +335,8 @@ const MenuLang = {
menu: [
[Menu.LANG_IT, Menu.LANG_EN],
[Menu.LANG_ES, Menu.LANG_FR],
- [Menu.LANG_SI, Menu.LANG_PT, Menu.it.INDIETRO]],
+ [Menu.LANG_SI, Menu.LANG_PT, Menu.it.INDIETRO],
+ ],
},
};
@@ -411,7 +353,8 @@ const MenuAdmin = {
it: {
menu: [
[Menu.RESTART_SRV + ' 6711', Menu.LOG_SRV + ' 6711'],
- [Menu.REBOOT_SRV + ' 6711', Menu.it.INDIETRO]],
+ [Menu.REBOOT_SRV + ' 6711', Menu.it.INDIETRO],
+ ],
},
};
@@ -419,7 +362,8 @@ const MenuSend = {
it: {
menu: [
[CONTA_SOLO, RICEVI_EMAIL, NOME_COGNOME],
- [CHEDI_SE_IMBARCARTI, Menu.it.INDIETRO]],
+ [CHEDI_SE_IMBARCARTI, Menu.it.INDIETRO],
+ ],
},
};
@@ -474,35 +418,43 @@ const StatusMSGALL = {
};
const txt = {
- MSG_SCEGLI_MENU: '💫' + ' Scegli una voce di menu:' +
- '💫',
- MSG_ASK_USERNAME_BO: 'Scrivete nel messaggio l\'username (SENZA SPAZI) o la email con cui vi siete registrati sul sito di %s:',
- MSG_ASK_USERNAME_INVITANTE: 'Scrivi nel messaggio l\'USERNAME TELEGRAM di chi ti ha INVITATO',
- MSG_NEW_REG: '
⁉️🙈 Per aiuto scrivi sulla Chat RISO
oppure direttamente a Surya (@surya1977) ☀️.',
- MSG_ERRORE_INVITANTE_NOT_FOUND: 'L\'username dell\'invitante appena digitato non sembra essere corretto! Ti ricordo che dev\'essere l\'username con cui si è registrato su %s',
+ MSG_SCEGLI_MENU: '💫' + ' Scegli una voce di menu:' + '💫',
+ MSG_ASK_USERNAME_BO:
+ "Scrivete nel messaggio l'username (SENZA SPAZI) o la email con cui vi siete registrati sul sito di %s:",
+ MSG_ASK_USERNAME_INVITANTE: "Scrivi nel messaggio l'USERNAME TELEGRAM di chi ti ha INVITATO",
+ MSG_NEW_REG:
+ '
⁉️🙈 Per aiuto scrivi sulla Chat RISO
oppure direttamente a Surya (@surya1977) ☀️.',
+ MSG_ERRORE_INVITANTE_NOT_FOUND:
+ "L'username dell'invitante appena digitato non sembra essere corretto! Ti ricordo che dev'essere l'username con cui si è registrato su %s",
MSG_ERRORE_USERNAME: 'Attenzione! Devi inserire solo lo username (40 caratteri massimo)',
- MSG_ERRORE_USERNAME_NOT_FOUND: 'Per Completare la Verifica Telegram BOT, dovete ora scrivere qui sotto nel messaggio l\'Username (senza spazi) OPPURE la email con cui vi siete registrati sul sito',
+ MSG_ERRORE_USERNAME_NOT_FOUND:
+ "Per Completare la Verifica Telegram BOT, dovete ora scrivere qui sotto nel messaggio l'Username (senza spazi) OPPURE la email con cui vi siete registrati sul sito",
MSG_ERRORE_USERNAME_ANNULLA: 'Inserimento Annullato. Riprovare',
MSG_OPERAZ_ANNULLATA: 'Operazione Annullata',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attenzione! Devi inserire solo il codice a 6 cifre',
- MSG_VERIFY_CODE: '1. Ora ritorna sul sito:\n%s\n2. Copia il codice di Autenticazione (di 6 cifre) che troverai scritto in alto\n3. Scrivilo (o incollalo) qui sotto come messaggio:',
- MSG_ERR_VERIFY_CODE: 'Codice di Verifica Errato!' + emo.EXCLAMATION_MARK +
+ MSG_VERIFY_CODE:
+ '1. Ora ritorna sul sito:\n%s\n2. Copia il codice di Autenticazione (di 6 cifre) che troverai scritto in alto\n3. Scrivilo (o incollalo) qui sotto come messaggio:',
+ MSG_ERR_VERIFY_CODE:
+ 'Codice di Verifica Errato!' +
+ emo.EXCLAMATION_MARK +
'\nControlla sul sito %s e riscrivi il nuovo codice di 6 cifre.',
- MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
+ MSG_SET_PICPROFILE:
+ '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_RESETPWD: 'Clicca qui per impostare una nuova password per accedere alla APP:',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Errore durante il salvataggio sul Server. Riprovare piú tardi',
- MSG_EXIT_TELEGRAM: 'L\'account è stato ora scollegato da questo Telegram BOT.',
- MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
- ' Si è appena Registrato "%s" (n. %s)\nInvitato da %s',
- MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
+ MSG_EXIT_TELEGRAM: "L'account è stato ora scollegato da questo Telegram BOT.",
+ MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' Si è appena Registrato "%s" (n. %s)\nInvitato da %s',
+ MSG_APORTADOR_ASK_CONFIRM:
+ '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Amicizia di %s !',
MSG_HANDSHAKE_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Stretta di mano di %s !',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
- MSG_APORTADOR_DEST_CONFIRMED: '✅ La tua registrazione a %s è stata accettata da %s!\n' +
- 'Vai sulla App oppure clicca qui per entrare\n👉🏻 %s',
+ MSG_APORTADOR_DEST_CONFIRMED:
+ '✅ La tua registrazione a %s è stata accettata da %s!\n' + 'Vai sulla App oppure clicca qui per entrare\n👉🏻 %s',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
- MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
+ MSG_APORTADOR_DEST_NOT_CONFIRMED:
+ emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !',
MSG_ISCRITTO_CONACREIS: emo.FIRE + '[%s] Si è appena Iscritto al Conacreis "%s"',
@@ -510,179 +462,191 @@ const txt = {
MSG_MSG_SENT: '📨' + ' Messaggi Inviati !',
MSG_MSG_TOSENT: '📨' + ' Messaggi da Inviare',
MSG_MSG_INCORSO: '📨' + ' messaggi in corso... Inviati attualmente',
- MSG_SET_USERNAME_TELEGRAM: '[Prima di continuare con la registrazione in RISO.APP]\n' +
+ 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' +
+ "5. Per confermare premi sull'icona con la spunta (V) in alto a destra.\n\n" +
'🏁 6. Infine ritorna su questa chat BOT e scrivi OK nel messaggio. \n\n' +
' Se non riesci a fare questi passaggi, clicca qui: \n' +
'👉🏻 https://www.nigiara.it/telegram/come-impostare-uno-username-su-telegram.htm ',
MSG_SIGNUP: 'Per registrarti su %s:',
-
};
const txt_es = {
- MSG_SCEGLI_MENU: '💫' + ' Elija un elemento del menú:' +
- '💫',
- MSG_ASK_USERNAME_BO: 'Escriba en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio de %s:',
+ MSG_SCEGLI_MENU: '💫' + ' Elija un elemento del menú:' + '💫',
+ MSG_ASK_USERNAME_BO:
+ 'Escriba en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio de %s:',
MSG_ERRORE_USERNAME: '¡Atención! Debes introducir sólo el nombre de usuario (40 caracteres como máximo)',
- MSG_ERRORE_USERNAME_NOT_FOUND: 'Para completar la verificación del telegrama BOT, ahora debe escribir en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio.:',
+ MSG_ERRORE_USERNAME_NOT_FOUND:
+ 'Para completar la verificación del telegrama BOT, ahora debe escribir en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio.:',
MSG_ERRORE_USERNAME_ANNULLA: 'Inserción cancelada. Inténtalo de nuevo.',
MSG_OPERAZ_ANNULLATA: 'Operación cancelada',
MSG_ERRORE_VERIFY_CODE_MAXLEN: '¡Atención! Sólo tienes que introducir el código de 6 dígitos',
- MSG_VERIFY_CODE: '1. Ahora, de vuelta en el sitio web:\n%s\n2. Copie el código de autenticación (6 dígitos) que encontrará escrito en la parte superior de la página\n3. Escríbelo (o pégalo) abajo como un mensaje:',
- MSG_ERR_VERIFY_CODE: 'Código de verificación incorrecto!' +
+ MSG_VERIFY_CODE:
+ '1. Ahora, de vuelta en el sitio web:\n%s\n2. Copie el código de autenticación (6 dígitos) que encontrará escrito en la parte superior de la página\n3. Escríbelo (o pégalo) abajo como un mensaje:',
+ MSG_ERR_VERIFY_CODE:
+ 'Código de verificación incorrecto!' +
emo.EXCLAMATION_MARK +
'\nComprueba en el sitio %s y reescribe el nuevo código de 6 dígitos.',
- MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
+ MSG_SET_PICPROFILE:
+ '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Error al guardar en el servidor. Inténtalo de nuevo más tarde.',
MSG_EXIT_TELEGRAM: 'La cuenta ha sido desconectada de Telegram BOT.',
- MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
- ' Acaba de registrarse "%s (n. %s)"\n(Invitado de %s)',
- MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
+ MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' Acaba de registrarse "%s (n. %s)"\n(Invitado de %s)',
+ MSG_APORTADOR_ASK_CONFIRM:
+ '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
- MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
+ MSG_APORTADOR_DEST_NOT_CONFIRMED:
+ emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !',
- MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
- '🚫 %s Non è stato Ammesso !',
+ MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: '📨' + ' Mensajes enviados !',
MSG_MSG_TOSENT: '📨' + ' Mensajes a enviar',
- MSG_MSG_INCORSO: '📨' +
- ' mensajes en progreso... Enviado actualmente',
+ MSG_MSG_INCORSO: '📨' + ' mensajes en progreso... Enviado actualmente',
};
const txt_fr = {
- MSG_SCEGLI_MENU: '💫' + 'Choisissez un élément de menu:' +
- '💫',
- MSG_ASK_USERNAME_BO: 'Écrivez dans le message l\'username ou l\'e-mail avec lequel vous vous êtes enregistré sur le site de %s: ',
+ MSG_SCEGLI_MENU: '💫' + 'Choisissez un élément de menu:' + '💫',
+ MSG_ASK_USERNAME_BO:
+ "Écrivez dans le message l'username ou l'e-mail avec lequel vous vous êtes enregistré sur le site de %s: ",
MSG_ERRORE_USERNAME: 'Attention! Vous devez insérer seulement l’username (40 caractères maximum)',
- MSG_ERRORE_USERNAME_NOT_FOUND: 'Pour Compléter la Vérification Telegram BOT, vous devez maintenant écrire dans le message ci-dessous l\'Username ou l\'adresse e-mail avec lequel vous vous êtes inscrit sur le site: ',
+ MSG_ERRORE_USERNAME_NOT_FOUND:
+ "Pour Compléter la Vérification Telegram BOT, vous devez maintenant écrire dans le message ci-dessous l'Username ou l'adresse e-mail avec lequel vous vous êtes inscrit sur le site: ",
MSG_ERRORE_USERNAME_ANNULLA: 'Saisie des données Annullée.Essayez à nouveau ',
MSG_OPERAZ_ANNULLATA: 'Opération Annullée',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attention! Vous devez insérer seulement le code à 6 chiffres',
- MSG_VERIFY_CODE: '1. Ᾱ présent retournez sur le site:\n%s\n2. Copiez le Code d’Authentification (de 6 chiffres) che vous trouverez écrit en haut \n3. Ecrivez-le (ou copiez-le) ci-dessous comme message:',
- MSG_ERR_VERIFY_CODE: ' Code de vérification incorrect!' +
+ MSG_VERIFY_CODE:
+ '1. Ᾱ présent retournez sur le site:\n%s\n2. Copiez le Code d’Authentification (de 6 chiffres) che vous trouverez écrit en haut \n3. Ecrivez-le (ou copiez-le) ci-dessous comme message:',
+ MSG_ERR_VERIFY_CODE:
+ ' Code de vérification incorrect!' +
emo.EXCLAMATION_MARK +
'\nControllez sur le site %s et réécrivez le nouveau code à 6 chiffres.',
- MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
- MSG_ERR_UNKNOWN_VERIFY_CODE: 'Erreur lors de l\'enregistrement sur le serveur. Retentez plus tard',
- MSG_EXIT_TELEGRAM: 'L\'account a été déconnecté de Telegram BOT.',
- MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
- ' Vous venez à peine de vous inscrire "%s (n. %s) %s',
- MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
+ MSG_SET_PICPROFILE:
+ '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
+ MSG_ERR_UNKNOWN_VERIFY_CODE: "Erreur lors de l'enregistrement sur le serveur. Retentez plus tard",
+ MSG_EXIT_TELEGRAM: "L'account a été déconnecté de Telegram BOT.",
+ MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' Vous venez à peine de vous inscrire "%s (n. %s) %s',
+ MSG_APORTADOR_ASK_CONFIRM:
+ '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
- MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
+ MSG_APORTADOR_DEST_NOT_CONFIRMED:
+ emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !',
- MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
- '🚫 %s Non è stato Ammesso !',
+ MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: '📨' + ' Messages envoyés !',
MSG_MSG_TOSENT: '📨' + ' Messages à envoyer',
- MSG_MSG_INCORSO: '📨' +
- ' messages en cours... Actuellement envoyé',
+ MSG_MSG_INCORSO: '📨' + ' messages en cours... Actuellement envoyé',
};
const txt_si = {
MSG_SCEGLI_MENU: '💫' + 'Izbirni meni:' + '💫',
MSG_ASK_USERNAME_BO: 'Vpiši svoje uporabniško ime in e-naslov s katerimi si se registriral na spletni strani %s: ',
MSG_ERRORE_USERNAME: 'Pozor! Vpiši samo uporabniško ime (40 znakov) maksimalno',
- MSG_ERRORE_USERNAME_NOT_FOUND: 'Ponovno preverite telegram BOT Uporabniško ime ali e-poštno sporočilo, s katerim ste registrirali na spletni strani: ',
+ MSG_ERRORE_USERNAME_NOT_FOUND:
+ 'Ponovno preverite telegram BOT Uporabniško ime ali e-poštno sporočilo, s katerim ste registrirali na spletni strani: ',
MSG_ERRORE_USERNAME_ANNULLA: 'Preklic. Poskusi ponovno ',
MSG_OPERAZ_ANNULLATA: 'Operacija preklicana',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Pozor! Vstavi D mestno kodo',
- MSG_VERIFY_CODE: '1. Vrni se na spletno strani: \n%s\n2. Kopiraj kodo Authenticazione (6 mestno) ki jo najdeš zgoraj zapisano\n3. Napiši (ali prilepi) tu spodaj kot sporočilo: ',
- MSG_ERR_VERIFY_CODE: 'Napačna koda za preverjanje!' + emo.EXCLAMATION_MARK +
- '\nPreveri na strani %s in ponovno napiši 6 mestno kodo.',
- MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
+ MSG_VERIFY_CODE:
+ '1. Vrni se na spletno strani: \n%s\n2. Kopiraj kodo Authenticazione (6 mestno) ki jo najdeš zgoraj zapisano\n3. Napiši (ali prilepi) tu spodaj kot sporočilo: ',
+ MSG_ERR_VERIFY_CODE:
+ 'Napačna koda za preverjanje!' + emo.EXCLAMATION_MARK + '\nPreveri na strani %s in ponovno napiši 6 mestno kodo.',
+ MSG_SET_PICPROFILE:
+ '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Napaka strežnika.Poskusi kasneje ',
MSG_EXIT_TELEGRAM: 'Račun se nahaja v programu Telegram BOT.',
- MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
- 'Registracija registracije %s (n. %s)\n(povabil ga %s)',
- MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
+ MSG_APORTADOR_USER_REGISTERED: emo.FIRE + 'Registracija registracije %s (n. %s)\n(povabil ga %s)',
+ MSG_APORTADOR_ASK_CONFIRM:
+ '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
- MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
+ MSG_APORTADOR_DEST_NOT_CONFIRMED:
+ emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !',
- MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
- '🚫 %s Non è stato Ammesso !',
+ MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !',
};
const txt_en = {
- MSG_SCEGLI_MENU: '💫' + ' Choose a menu item:' +
- '💫',
+ MSG_SCEGLI_MENU: '💫' + ' Choose a menu item:' + '💫',
MSG_ASK_USERNAME_BO: 'Write in the message the username or email with which you registered on the site of %s:',
MSG_ERRORE_USERNAME: 'Attention! You must enter only the username (40 characters maximum)',
- MSG_ERRORE_USERNAME_NOT_FOUND: 'To complete the Telegram BOT Verification, you must now write below in the message the Username OR the email with which you registered on the website:',
+ MSG_ERRORE_USERNAME_NOT_FOUND:
+ 'To complete the Telegram BOT Verification, you must now write below in the message the Username OR the email with which you registered on the website:',
MSG_ERRORE_USERNAME_ANNULLA: 'Insertion Cancelled. Try again',
MSG_OPERAZ_ANNULLATA: 'Operation Cancelled',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attention! You only need to enter the 6-digit code',
- MSG_VERIFY_CODE: '1. Now return to the website: %s\n' +
+ MSG_VERIFY_CODE:
+ '1. Now return to the website: %s\n' +
'2. Copy the Authentication code (of 6 digits) that you will find written at the top\n' +
'3. Write it (or paste it) below as a message:',
- MSG_ERR_VERIFY_CODE: 'Incorrect Verification Code!' + emo.EXCLAMATION_MARK +
- '\nCheck on the site %s and rewrite the new 6-digit code.',
- MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
+ MSG_ERR_VERIFY_CODE:
+ 'Incorrect Verification Code!' + emo.EXCLAMATION_MARK + '\nCheck on the site %s and rewrite the new 6-digit code.',
+ MSG_SET_PICPROFILE:
+ '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Error while saving to the Server. Try again later',
MSG_EXIT_TELEGRAM: 'The account has now been disconnected from this Telegram BOT.',
- MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
- ' He/She\'s just registered "%s (n. %s)"\n(Invited from %s)',
- MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
+ MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' He/She\'s just registered "%s (n. %s)"\n(Invited from %s)',
+ MSG_APORTADOR_ASK_CONFIRM:
+ '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
- MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
+ MSG_APORTADOR_DEST_NOT_CONFIRMED:
+ emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !',
- MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
- '🚫 %s Non è stato Ammesso !',
+ MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: '📨' + ' Sent Messages !',
MSG_MSG_TOSENT: '📨' + ' Messages to Send',
- MSG_MSG_INCORSO: '📨' +
- ' messages in progress... Currently sent',
+ MSG_MSG_INCORSO: '📨' + ' messages in progress... Currently sent',
};
const txt_pt = {
- MSG_SCEGLI_MENU: '💫' + ' Escolha um item do menu:' +
- '💫',
+ MSG_SCEGLI_MENU: '💫' + ' Escolha um item do menu:' + '💫',
MSG_ASK_USERNAME_BO: 'Escreva na mensagem o nome de usuário ou e-mail com o qual se registrou no site de %s:',
MSG_ERRORE_USERNAME: 'Atenção! Você deve inserir apenas o nome de usuário (40 caracteres no máximo)',
- MSG_ERRORE_USERNAME_NOT_FOUND: 'Para completar a Verificação do Telegrama BOT, você deve agora escrever abaixo na mensagem o Nome de Usuário OU o e-mail com o qual você se registrou no site:',
+ MSG_ERRORE_USERNAME_NOT_FOUND:
+ 'Para completar a Verificação do Telegrama BOT, você deve agora escrever abaixo na mensagem o Nome de Usuário OU o e-mail com o qual você se registrou no site:',
MSG_ERRORE_USERNAME_ANNULLA: 'Inserção Cancelada. Tente novamente',
MSG_OPERAZ_ANNULLATA: 'Operação Cancelada',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Atenção! Você só precisa digitar o código de 6 dígitos',
- MSG_VERIFY_CODE: '1. Agora de volta ao site:\n%s\n2. Copie o código de autenticação (6 dígitos) que você encontrará escrito na parte superior da página\n3. Escreva-o (ou cole-o) abaixo como uma mensagem:',
- MSG_ERR_VERIFY_CODE: 'Código de Verificação Incorrecto!' +
+ MSG_VERIFY_CODE:
+ '1. Agora de volta ao site:\n%s\n2. Copie o código de autenticação (6 dígitos) que você encontrará escrito na parte superior da página\n3. Escreva-o (ou cole-o) abaixo como uma mensagem:',
+ MSG_ERR_VERIFY_CODE:
+ 'Código de Verificação Incorrecto!' +
emo.EXCLAMATION_MARK +
'\nCódigo de Verificação ErradoCheque no local %s e reescreva o novo código de 6 dígitos.',
- MSG_SET_PICPROFILE: '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
+ MSG_SET_PICPROFILE:
+ '🖼 Abbiamo impostato la tua foto del Profilo, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Erro ao salvar no Servidor. Tente novamente mais tarde.',
MSG_EXIT_TELEGRAM: 'A conta foi agora desconectada deste Telegrama BOT.',
- MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
- ' Acabou de se registar "%s (n. %s)"\n(Convidado por %s)',
- MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
+ MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' Acabou de se registar "%s (n. %s)"\n(Convidado por %s)',
+ MSG_APORTADOR_ASK_CONFIRM:
+ '🆕💥 🧍♂️ %s si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
- MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
+ MSG_APORTADOR_DEST_NOT_CONFIRMED:
+ emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.
Contattalo per farti abilitare !',
- MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
- '🚫 %s Non è stato Ammesso !',
+ MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: '📨' + ' Mensagens Enviadas !',
MSG_MSG_TOSENT: '📨' + ' Mensagens a enviar',
- MSG_MSG_INCORSO: '📨' +
- ' mensagens em progresso... Actualmente enviado',
+ MSG_MSG_INCORSO: '📨' + ' mensagens em progresso... Actualmente enviado',
};
const TelegramBot = require('node-telegram-bot-api');
@@ -690,9 +654,8 @@ const TelegramBot = require('node-telegram-bot-api');
const ADMIN_IDTELEGRAM_TEST = 5356627050; // 5022837609; //Surya A.
const MyTelegramBot = {
-
- ADMIN_IDTELEGRAM_SERVER: '12429864', //Paolo
- ADMIN_USERNAME_TELEGRAM: 'surya1977', //Paolo
+ ADMIN_IDTELEGRAM_SERVER: '12429864', //Paolo
+ ADMIN_USERNAME_TELEGRAM: 'surya1977', //Paolo
ADMIN_USER_NAME_SERVER: 'Paolo',
phase: {
@@ -716,11 +679,9 @@ const MyTelegramBot = {
if (arrTelegFromSite.length > 0) {
arrTeleg = arrTelegFromSite;
}
-
}
return arrTeleg;
-
},
getAppTelegramTest: function () {
@@ -729,7 +690,6 @@ const MyTelegramBot = {
} else {
return appTelegram_TEST;
}
-
},
getAppTelegramDevelop: function () {
@@ -738,38 +698,36 @@ const MyTelegramBot = {
} else {
return appTelegram_DEVELOP;
}
-
},
- local_sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text,
- message_id, chat_id, ripr_menuPrec,
- MyForm = null, img = '') {
-
- if (!idtelegram)
- return { text: '' };
+ local_sendMsgTelegramByIdTelegram: async function (
+ idapp,
+ idtelegram,
+ text,
+ message_id,
+ chat_id,
+ ripr_menuPrec,
+ MyForm = null,
+ img = ''
+ ) {
+ if (!idtelegram) return { text: '' };
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
-
- return await cl.sendMsg(idtelegram, text, null, MyForm, message_id,
- chat_id, ripr_menuPrec, img, { idapp });
+ return await cl.sendMsg(idtelegram, text, null, MyForm, message_id, chat_id, ripr_menuPrec, img, { idapp });
}
return { text: '' };
-
},
deleteRecInMemByUsername: function (idapp, username_bo) {
-
const cl = getclTelegByidapp(idapp);
if (cl) {
- cl.arrUsers = cl.arrUsers.filter(
- (rec) => rec.username_bo !== username_bo);
+ cl.arrUsers = cl.arrUsers.filter((rec) => rec.username_bo !== username_bo);
}
},
getFormDaMostrare: function (idapp, myfunc, myuser) {
-
let FormDaMostrare = null;
const cl = getclTelegByidapp(idapp);
@@ -779,15 +737,12 @@ 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,
+ callback_data: InlineZoomConferma.CONFERMA_ZOOM_PRESENZA + tools.SEP + myuser.username,
},
{
text: 'Annulla Presenza Zoom',
// callback_data: { action: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA, username: myuser.username }
- callback_data: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA +
- tools.SEP +
- myuser.username,
+ callback_data: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA + tools.SEP + myuser.username,
},
]);
}
@@ -826,18 +781,16 @@ const MyTelegramBot = {
let text = '';
if (phase === this.phase.REGISTRATION) {
-
- if (tools.getConfSiteOptionEnabledByIdApp(mylocalsconf.idapp,
- shared_consts.ConfSite.Notif_Reg_Bot_ToManagers)) {
+ if (
+ tools.getConfSiteOptionEnabledByIdApp(mylocalsconf.idapp, shared_consts.ConfSite.Notif_Reg_Bot_ToManagers)
+ ) {
if (userdest) {
- NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp,
- userdest, true);
+ NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp, userdest, true);
aportador = NameFrom ? NameFrom + ' ' + aportador : aportador;
}
const numutenti = await User.getNumUsers(mylocalsconf.idapp);
let nome = tools.getNomeCognomeEUserNameByUser(mylocalsconf.user);
- text = printf(getstr(langdest, 'MSG_APORTADOR_USER_REGISTERED'), nome,
- numutenti, aportador);
+ text = printf(getstr(langdest, 'MSG_APORTADOR_USER_REGISTERED'), nome, numutenti, aportador);
}
}
@@ -845,11 +798,8 @@ const MyTelegramBot = {
let rismsg = null;
if (text) {
-
- await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp,
- addtext + text, false, null);
+ await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text, false, null);
}
-
} catch (e) {
console.error('Err notifyToTelegram', e);
}
@@ -872,13 +822,19 @@ const MyTelegramBot = {
}
},
- askConfirmationUser: async function (idapp, myfunc, myuser, userDest = '', name = '', groupid = '', regexpire = '', groupname = '') {
-
+ askConfirmationUser: async function (
+ idapp,
+ myfunc,
+ myuser,
+ userDest = '',
+ name = '',
+ groupid = '',
+ regexpire = '',
+ groupname = ''
+ ) {
try {
const cl = getclTelegByidapp(idapp);
- if (!cl)
- return false;
-
+ if (!cl) return false;
const langdest = myuser.lang;
const telegid = myuser.profile.teleg_id;
@@ -902,12 +858,21 @@ const MyTelegramBot = {
const nomeapp = myuser.idapp ? tools.getNomeAppByIdApp(myuser.idapp) : tools.getNomeAppByIdApp(idapp);
if (myfunc === shared_consts.CallFunz.REGISTRATION) {
-
if (telegid > 0) {
cl.setPhotoProfile(myuser, telegid, false);
- const rismsg = await MsgTemplate.getMsgByLang(idapp, myuser, shared_consts.TypeMsgTemplate.MSG_BENVENUTO, myuser.lang);
- const rismsg2 = await MsgTemplate.getMsgByLang(idapp, myuser, shared_consts.TypeMsgTemplate.MS_SHARE_LINK, myuser.lang);
+ const rismsg = await MsgTemplate.getMsgByLang(
+ idapp,
+ myuser,
+ shared_consts.TypeMsgTemplate.MSG_BENVENUTO,
+ myuser.lang
+ );
+ const rismsg2 = await MsgTemplate.getMsgByLang(
+ idapp,
+ myuser,
+ shared_consts.TypeMsgTemplate.MS_SHARE_LINK,
+ myuser.lang
+ );
await cl.sendMsgLog(telegid, rismsg.body);
await cl.sendMsg(telegid, rismsg2.body);
@@ -918,18 +883,21 @@ const MyTelegramBot = {
let useraportador = await User.getUserShortDataByUsername(idapp, userDest);
- if (useraportador && useraportador.tokenreg && useraportador.tokenreg && (regexpire && (regexpire?.toLowerCase() === useraportador.tokenreg?.toLowerCase()))) {
+ if (
+ useraportador &&
+ useraportador.tokenreg &&
+ useraportador.tokenreg &&
+ regexpire &&
+ regexpire?.toLowerCase() === useraportador.tokenreg?.toLowerCase()
+ ) {
const nonchiedereverifica = await User.getifRegTokenIsValid(idapp, useraportador.tokenreg);
- if (nonchiedereverifica)
- notask_verif = true;
+ if (nonchiedereverifica) notask_verif = true;
}
-
if (notask_verif) {
// Non chiedi la verifica Registrazione
await setVerifiedReg(myuser.idapp, myuser.lang, myuser.username, userDest);
} else {
-
msg_notifpush = getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM', myuser.username, nomeapp);
domanda = getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM', myuser.username, nomeapp) + '
' + struserinfomsg;
@@ -945,33 +913,46 @@ const MyTelegramBot = {
]);
}
send_notif = true;
-
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_GRUPPO) {
-
msg_notifpush = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), name);
domanda = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), name) + '
' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Accetta ' + myuser.username,
- callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + groupid,
+ callback_data:
+ InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + groupid,
},
{
text: '🚫 Rifiuta ' + myuser.username,
- callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + groupid,
+ callback_data:
+ InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + groupid,
},
]);
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_FIDO) {
-
if (groupname) {
msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, groupname);
- domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, groupname) + '
' + struserinfomsg;
+ domanda =
+ i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, groupname) +
+ '
' +
+ struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Abilita fiducia a ' + groupname,
- callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
- groupid + tools.SEP + groupname,
+ callback_data:
+ InlineConferma.RISPOSTA_SI +
+ myfunc +
+ tools.SEP +
+ myuser.username +
+ tools.SEP +
+ '' +
+ tools.SEP +
+ '' +
+ tools.SEP +
+ groupid +
+ tools.SEP +
+ groupname,
},
/*{
text: '🚫 Rifiuta ' + groupname,
@@ -980,15 +961,26 @@ const MyTelegramBot = {
},*/
]);
send_notif = true;
-
} else {
msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest }, myuser.username, name);
- domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest }, myuser.username, name) + '
' + struserinfomsg;
+ domanda =
+ i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest }, myuser.username, name) +
+ '
' +
+ struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Abilita fiducia a ' + myuser.username,
- callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
+ callback_data:
+ InlineConferma.RISPOSTA_SI +
+ myfunc +
+ tools.SEP +
+ myuser.username +
+ tools.SEP +
+ '' +
+ tools.SEP +
+ '' +
+ tools.SEP +
groupid,
},
/*{
@@ -1000,16 +992,29 @@ const MyTelegramBot = {
send_notif = true;
}
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
-
if (groupname) {
msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP_CIRC', locale: langdest }, groupname);
- domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP_CIRC', locale: langdest }, groupname) + '
' + struserinfomsg;
+ domanda =
+ i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP_CIRC', locale: langdest }, groupname) +
+ '
' +
+ struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Fai entrare a ' + groupname,
- callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
- groupid + tools.SEP + groupname,
+ callback_data:
+ InlineConferma.RISPOSTA_SI +
+ myfunc +
+ tools.SEP +
+ myuser.username +
+ tools.SEP +
+ '' +
+ tools.SEP +
+ '' +
+ tools.SEP +
+ groupid +
+ tools.SEP +
+ groupname,
},
/*{
text: '🚫 Rifiuta ' + groupname,
@@ -1018,15 +1023,26 @@ const MyTelegramBot = {
},*/
]);
send_notif = true;
-
} else {
msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_CIRC', locale: langdest }, myuser.username, name);
- domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_CIRC', locale: langdest }, myuser.username, name) + '
' + struserinfomsg;
+ domanda =
+ i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_CIRC', locale: langdest }, myuser.username, name) +
+ '
' +
+ struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Fai entrare a ' + myuser.username,
- callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
+ callback_data:
+ InlineConferma.RISPOSTA_SI +
+ myfunc +
+ tools.SEP +
+ myuser.username +
+ tools.SEP +
+ '' +
+ tools.SEP +
+ '' +
+ tools.SEP +
groupid,
},
/*{
@@ -1049,20 +1065,15 @@ const MyTelegramBot = {
// SEND PUSH NOTIFICATION
await tools.sendNotificationToUser(userId, title, msg_notifpush, openUrl, '', tag, actions);
}
-
-
} catch (e) {
console.error('Error askConfirmationUser', e);
}
-
},
askConfirmationUserFriend: async function (idapp, myfunc, myuser, userDest = '', username = '') {
-
try {
const cl = getclTelegByidapp(idapp);
- if (!cl)
- return false;
+ if (!cl) return false;
const { SendNotif } = require('../models/sendnotif');
@@ -1088,11 +1099,13 @@ const MyTelegramBot = {
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅👤 Accetta Amicizia',
- callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
+ callback_data:
+ InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
},
{
text: '🚫👤 Rifiuta Amicizia',
- callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
+ callback_data:
+ InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
},
]);
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_HANDSHAKE) {
@@ -1101,12 +1114,14 @@ const MyTelegramBot = {
typeid = shared_consts.TypeNotifs.ID_HANDSHAKE_ACCEPTED;
paramsObj = { usernameDest: userDest };
- domanda = printf(tools.gettranslate('RICHIESTA_HANDSHAKE', langdest), myuser.username) + '
' + struserinfomsg;
+ domanda =
+ printf(tools.gettranslate('RICHIESTA_HANDSHAKE', langdest), myuser.username) + '
' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅🤝 Ricambia la stretta di mano',
- callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
+ callback_data:
+ InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
},
]);
}
@@ -1122,16 +1137,12 @@ const MyTelegramBot = {
// CREATE NOTIFICATION IN TABLE SENDNOTIF
await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, true, typedir, typeid);
}
-
} catch (e) {
console.error('Error askConfirmationUser', e);
}
-
},
- sendMsgTelegramToTheManagers: async function (
- idapp, text, onlyintofile = false, MyForm = null, nottousername = '') {
-
+ sendMsgTelegramToTheManagers: async function (idapp, text, onlyintofile = false, MyForm = null, nottousername = '') {
tools.writeManagersLog(text);
if (!onlyintofile) {
@@ -1139,21 +1150,31 @@ const MyTelegramBot = {
if (usersmanagers) {
for (const rec of usersmanagers) {
if (rec.username !== nottousername) {
- await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id,
- emo.ROBOT_FACE + ': ' + text, undefined, undefined, true,
- MyForm);
+ await this.sendMsgTelegramByIdTelegram(
+ idapp,
+ rec.profile.teleg_id,
+ emo.ROBOT_FACE + ': ' + text,
+ undefined,
+ undefined,
+ true,
+ MyForm
+ );
await tools.snooze(100);
}
}
}
}
return true;
-
},
sendMsgTelegramToTheAdminsOfCircuit: async function (
- idapp, circuitpath, text, onlyintofile = false, MyForm = null, nottousername = '') {
-
+ idapp,
+ circuitpath,
+ text,
+ onlyintofile = false,
+ MyForm = null,
+ nottousername = ''
+ ) {
tools.writeManagersLog(text);
let teleg_id = 0;
@@ -1164,9 +1185,15 @@ const MyTelegramBot = {
if (rec.username !== nottousername) {
teleg_id = await User.TelegIdByUsername(idapp, rec.username);
if (teleg_id) {
- await this.sendMsgTelegramByIdTelegram(idapp, teleg_id,
- emo.ROBOT_FACE + ': ' + text, undefined, undefined, true,
- MyForm);
+ await this.sendMsgTelegramByIdTelegram(
+ idapp,
+ teleg_id,
+ emo.ROBOT_FACE + ': ' + text,
+ undefined,
+ undefined,
+ true,
+ MyForm
+ );
await tools.snooze(100);
}
}
@@ -1174,12 +1201,9 @@ const MyTelegramBot = {
}
}
return true;
-
},
- sendMsgTelegramToTheManagersAndZoomeri: async function (
- idapp, text, onlyintofile, MyForm = null) {
-
+ sendMsgTelegramToTheManagersAndZoomeri: async function (idapp, text, onlyintofile, MyForm = null) {
tools.writeManagersLog(text);
if (!onlyintofile) {
@@ -1187,14 +1211,20 @@ const MyTelegramBot = {
const usersmanagers = await User.getusersManagers(idapp);
if (usersmanagers) {
for (const rec of usersmanagers) {
- await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id,
- emo.ROBOT_FACE + ': ' + text, undefined, undefined, true, MyForm);
+ await this.sendMsgTelegramByIdTelegram(
+ idapp,
+ rec.profile.teleg_id,
+ emo.ROBOT_FACE + ': ' + text,
+ undefined,
+ undefined,
+ true,
+ MyForm
+ );
await tools.snooze(100);
}
}
}
return true;
-
},
getMsgByTipoMsg: async function (mydata, lang, user, sonosognatore) {
if (!!mydata.msgextra) {
@@ -1206,25 +1236,26 @@ const MyTelegramBot = {
if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) {
if (sonosognatore)
- msg = printf(tools.gettranslate('SEND_LINK_CHAT_SOGNATORE', lang),
+ msg = printf(
+ tools.gettranslate('SEND_LINK_CHAT_SOGNATORE', lang),
user.name,
mydata.navemediatore.riga + '.' + mydata.navemediatore.col,
- mydata.msgpar1);
+ mydata.msgpar1
+ );
else
- msg = printf(tools.gettranslate('SEND_LINK_CHAT_DONATORI', lang),
+ msg = printf(
+ tools.gettranslate('SEND_LINK_CHAT_DONATORI', lang),
user.name,
mydata.navemediatore.riga + '.' + mydata.navemediatore.col,
- mydata.msgpar1);
- } else if (mydata.tipomsg === tools.TipoMsg.SEND_MSG || mydata.tipomsg ===
- tools.TipoMsg.SEND_MSG_SINGOLO) {
+ mydata.msgpar1
+ );
+ } else if (mydata.tipomsg === tools.TipoMsg.SEND_MSG || mydata.tipomsg === tools.TipoMsg.SEND_MSG_SINGOLO) {
if (!!mydata.username_mitt) {
- msg = '[' + tools.gettranslate('MSG_SEND_FROM', lang) + ' ' +
- mydata.username_mitt + ']:' + tools.ACAPO;
+ msg = '[' + tools.gettranslate('MSG_SEND_FROM', lang) + ' ' + mydata.username_mitt + ']:' + tools.ACAPO;
}
msg += mydata.msgpar1;
} else if (mydata.tipomsg >= 1000) {
- const ris = await MsgTemplate.getMsgByLang(user.idapp, user, mydata.tipomsg,
- lang);
+ const ris = await MsgTemplate.getMsgByLang(user.idapp, user, mydata.tipomsg, lang);
msg = ris.body;
title = ris.title;
}
@@ -1237,30 +1268,26 @@ const MyTelegramBot = {
if (!!mydata.flotta) {
// SOSTITUISCI LE PAROLE CHIAVI
if (!!mydata.flotta.date_start)
- msg = msg.replace('{date_start}',
- tools.getstrDateLongTot(new Date(mydata.flotta.date_start),
- user.lang));
+ msg = msg.replace('{date_start}', tools.getstrDateLongTot(new Date(mydata.flotta.date_start), user.lang));
if (!!mydata.flotta.date_close)
- msg = msg.replace('{date_close}',
- tools.getstrDateLongTot(new Date(mydata.flotta.date_close),
- user.lang));
- if (!!mydata.flotta.link_superchat)
- msg = msg.replace('{link_superchat}', mydata.flotta.link_superchat);
- if (!!mydata.flotta.tutor1)
- msg = msg.replace('{tutor1}', mydata.flotta.tutor1);
- if (!!mydata.flotta.tutor2)
- msg = msg.replace('{tutor2}', mydata.flotta.tutor2);
- if (!!mydata.flotta.tutor3)
- msg = msg.replace('{tutor3}', mydata.flotta.tutor3);
- if (!!mydata.flotta.tutorslo)
- msg = msg.replace('{tutorslo}', mydata.flotta.tutorslo);
+ msg = msg.replace('{date_close}', tools.getstrDateLongTot(new Date(mydata.flotta.date_close), user.lang));
+ if (!!mydata.flotta.link_superchat) msg = msg.replace('{link_superchat}', mydata.flotta.link_superchat);
+ if (!!mydata.flotta.tutor1) msg = msg.replace('{tutor1}', mydata.flotta.tutor1);
+ if (!!mydata.flotta.tutor2) msg = msg.replace('{tutor2}', mydata.flotta.tutor2);
+ if (!!mydata.flotta.tutor3) msg = msg.replace('{tutor3}', mydata.flotta.tutor3);
+ if (!!mydata.flotta.tutorslo) msg = msg.replace('{tutorslo}', mydata.flotta.tutorslo);
+ if (!!mydata.flotta.sognatore_nomecognome) msg = msg.replace('{sognatore}', mydata.flotta.sognatore_nomecognome);
if (!!mydata.flotta.sognatore_nomecognome)
- msg = msg.replace('{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));
+ msg = msg.replace(
+ '{flotta}',
+ mydata.flotta.riga +
+ '.' +
+ Math.ceil(mydata.flotta.col_prima / 8) +
+ ' - ' +
+ mydata.flotta.riga +
+ '.' +
+ Math.ceil(mydata.flotta.col_ultima / 8)
+ );
}
return { body: msg, title };
@@ -1277,20 +1304,17 @@ const MyTelegramBot = {
const usersmanagers = await User.getusersAdmin(idapp);
let intestaz = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': ';
- if (senzaintestazione)
- intestaz = '';
+ if (senzaintestazione) intestaz = '';
if (usersmanagers) {
for (const rec of usersmanagers) {
if (User.isAdmin(rec.perm)) {
- this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id,
- intestaz + text, undefined, undefined, true);
+ this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, intestaz + text, undefined, undefined, true);
await tools.snooze(300);
}
}
}
return true;
-
},
sendMsgTelegramToALL: async function (idapp, text) {
@@ -1302,11 +1326,9 @@ const MyTelegramBot = {
await tools.snooze(300);
}
}
-
},
- sendMsgTelegram: async function (
- idapp, username, text, alsotomanagers = false, username_mitt = '') {
+ sendMsgTelegram: async function (idapp, username, text, alsotomanagers = false, username_mitt = '') {
const { User } = require('../models/user');
const teleg_id = await User.TelegIdByUsername(idapp, username);
@@ -1332,39 +1354,37 @@ const MyTelegramBot = {
},
sendMsgTelegramByIdTelegram: async function (
- idapp, idtelegram, text, message_id, chat_id, ripr_menuPrec,
- MyForm = null, img = '') {
-
- if (!idtelegram)
- return;
+ idapp,
+ idtelegram,
+ text,
+ message_id,
+ chat_id,
+ ripr_menuPrec,
+ MyForm = null,
+ img = ''
+ ) {
+ if (!idtelegram) return;
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
let myform = null;
- return await cl.sendMsg(idtelegram, text, null, MyForm, message_id,
- chat_id, ripr_menuPrec, img);
+ return await cl.sendMsg(idtelegram, text, null, MyForm, message_id, chat_id, ripr_menuPrec, img);
}
-
},
reloadMenuBot: async function (idapp) {
-
const cl = getclTelegByidapp(idapp);
if (cl) {
return cl.updateMenuBot();
}
-
},
reloadSites: async function () {
-
tools.loadApps();
-
},
sendMsgFromSite: async function (idapp, user, params) {
-
try {
let ris = {
numrec: 0,
@@ -1396,11 +1416,17 @@ const MyTelegramBot = {
const myrectableorig = await mytable.getCompleteRecord(params.idapp, params.idrec);
if (myrectableorig) {
- const eventobj = await tools.getAnnuncioForTelegram(myrectableorig, params.tablerec, '', user.username, false);
+ const eventobj = await tools.getAnnuncioForTelegram(
+ myrectableorig,
+ params.tablerec,
+ '',
+ user.username,
+ false
+ );
if (eventobj) {
params.textcontent_Telegram = eventobj.newdescrtelegram;
params.typesend = shared_consts.TypeSend.TELEGRAM;
- //const rismsg =
+ //const rismsg =
params.content = eventobj.newdescr;
params.title = '';
params.img = eventobj.img;
@@ -1421,22 +1447,18 @@ const MyTelegramBot = {
}
return ris;
-
} catch (e) {
console.error('sendMsgFromSite', e);
}
},
sendMsgFromSiteToBotTelegram: async function (idapp, user, params) {
-
if (!params.typesend) {
params.typesend = shared_consts.TypeSend.TELEGRAM;
}
return this.sendMsgFromSite(idapp, user, params);
-
},
-
};
async function setVerifiedReg(idapp, lang, usernameorig, usernameDest) {
@@ -1444,8 +1466,7 @@ async function setVerifiedReg(idapp, lang, usernameorig, usernameDest) {
await User.setVerifiedByAportador(idapp, usernameorig, true);
// await User.setFriendsCmd(null, idapp, usernameorig, usernameDest, shared_consts.FRIENDSCMD.SETFRIEND);
- const msgDest = printf(getstr(lang, 'MSG_APORTADOR_CONFIRMED'),
- `${usernameorig}`, usernameDest);
+ const msgDest = printf(getstr(lang, 'MSG_APORTADOR_CONFIRMED'), `${usernameorig}`, usernameDest);
await local_sendMsgTelegram(idapp, usernameDest, msgDest);
} catch (e) {
console.log('e', e);
@@ -1455,8 +1476,7 @@ async function setVerifiedReg(idapp, lang, usernameorig, usernameDest) {
function getusernameByUser(idapp, msg) {
let username = '';
let rec = this.getRecInMem(msg);
- if (!!rec)
- username = rec.username_bo;
+ if (!!rec) username = rec.username_bo;
if (username === '') {
username = msg.chat.username;
@@ -1465,13 +1485,11 @@ function getusernameByUser(idapp, msg) {
return username;
}
-async function local_sendMsgTelegramToTheManagers(
- idapp, text, msg, username_bo) {
+async function local_sendMsgTelegramToTheManagers(idapp, text, msg, username_bo) {
const usersmanagers = await User.getusersManagers(idapp);
let username = msg.chat.username;
- if (username_bo)
- username = username_bo;
+ if (username_bo) username = username_bo;
text = emo.ROBOT_FACE + ': Da ' + tools.getNomeCognomeTelegram(msg) + ' (' + username + '): \n' + text;
tools.writeEventsLog(text);
@@ -1481,25 +1499,20 @@ async function local_sendMsgTelegramToTheManagers(
const idtelegram = rec.profile.teleg_id;
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
- await cl.sendMsg(idtelegram, text, undefined, undefined, undefined,
- undefined, true);
+ await cl.sendMsg(idtelegram, text, undefined, undefined, undefined, undefined, true);
}
await tools.snooze(100);
}
}
return true;
-
}
-async function local_sendMsgTelegramToTheAdmin(
- idapp, text, msg, username_bo) {
+async function local_sendMsgTelegramToTheAdmin(idapp, text, msg, username_bo) {
const usersAdmin = await User.getusersAdmin(idapp);
let username = msg.chat.username;
- if (username_bo)
- username = username_bo;
+ if (username_bo) username = username_bo;
- text = emo.ROBOT_FACE + ': Da ' + msg.chat.first_name + ' ' +
- msg.chat.last_name + ' (' + username + '): \n' + text;
+ text = emo.ROBOT_FACE + ': Da ' + msg.chat.first_name + ' ' + msg.chat.last_name + ' (' + username + '): \n' + text;
tools.writeEventsLog(text);
if (usersAdmin) {
@@ -1507,18 +1520,15 @@ async function local_sendMsgTelegramToTheAdmin(
const idtelegram = rec.profile.teleg_id;
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
- await cl.sendMsg(idtelegram, text, undefined, undefined, undefined,
- undefined, true);
+ await cl.sendMsg(idtelegram, text, undefined, undefined, undefined, undefined, true);
}
await tools.snooze(100);
}
}
return true;
-
}
async function local_sendMsgTelegram(idapp, username, text) {
-
const teleg_id = await User.TelegIdByUsername(idapp, username);
const cl = getclTelegByidapp(idapp);
let ris = null;
@@ -1527,20 +1537,18 @@ async function local_sendMsgTelegram(idapp, username, text) {
}
return ris;
-
}
function getstr(lang, key, ...params) {
-
let mystr = '';
- if ((lang === 'si') || (lang === 'sl-si')) {
+ if (lang === 'si' || lang === 'sl-si') {
try {
mystr = txt_si[key];
} catch (e) {
mystr = '';
}
- } else if ((lang === 'en') || (lang === 'enUs')) {
+ } else if (lang === 'en' || lang === 'enUs') {
try {
mystr = txt_en[key];
} catch (e) {
@@ -1566,8 +1574,7 @@ function getstr(lang, key, ...params) {
}
}
- if (!mystr || mystr === '')
- mystr = txt[key];
+ if (!mystr || mystr === '') mystr = txt[key];
if (params.length > 0) {
mystr = printf(mystr, ...params);
@@ -1587,12 +1594,11 @@ class Telegram {
}
async createIfNotExist(msg) {
- if (!await this.alreadyExist(msg)) {
+ if (!(await this.alreadyExist(msg))) {
if (await this.insertIntoDB(msg)) {
let rec = this.getRecInMem(msg);
if (!!rec) {
- if (rec.user)
- rec.status = Status.VERIFIED;
+ if (rec.user) rec.status = Status.VERIFIED;
} else {
return false;
}
@@ -1604,30 +1610,24 @@ class Telegram {
}
async settotheDatabase(msg) {
-
// Check if Present to the DB
const riscreate = await this.createIfNotExist(msg);
if (!riscreate) {
let rec = this.getRecInMem(msg);
- if (!rec)
- rec = await this.addUser(msg);
+ if (!rec) rec = await this.addUser(msg);
- if (rec.user)
- rec.status = Status.VERIFIED;
+ if (rec.user) rec.status = Status.VERIFIED;
}
-
}
async start(msg) {
-
// Check if Username Telegram Present
if (!msg.from.username) {
return false;
}
await this.settotheDatabase(msg);
-
}
geturlfaq() {
@@ -1635,13 +1635,14 @@ class Telegram {
}
getstrChatHelp() {
- return 'Clicca qui per entrare nella Chat HELP di Supporto\n' +
+ return (
+ 'Clicca qui per entrare nella Chat HELP di Supporto\n' +
tools.getTelegramSupportChat(this.idapp) +
- '\n\nI miei colleghi umani ti aiuteranno a risolvere !';
+ '\n\nI miei colleghi umani ti aiuteranno a risolvere !'
+ );
}
async IsTesto(msg) {
-
let risp = '';
const id = msg.chat.id;
let testo = msg.text?.toLowerCase()?.trim();
@@ -1663,9 +1664,11 @@ class Telegram {
if (rec.statusmsg === Status.WAITFOR_RISPOSTA) {
if (rec.msgcodeprec === MsgBot.COME_STAI) {
- risp = 'L\'importante è trovare Serenità dentro di noi' +
+ risp =
+ "L'importante è trovare Serenità dentro di noi" +
emo.GIFT_HEART +
- '\nNutrirsi di Sole e Viaggiare il più possibile ! ' + emo.DREAM;
+ '\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) {
@@ -1673,11 +1676,11 @@ class Telegram {
} else {
if (eta < 20) {
risp = 'Woww! Sei molto giovane!';
- } else if ((eta > 20) && (eta < 30)) {
+ } else if (eta > 20 && eta < 30) {
risp = 'Sei giovane anche tu!';
- } else if ((eta > 30) && (eta < 50)) {
+ } else if (eta > 30 && eta < 50) {
risp = 'Sono i migliori anni questi !';
- } else if ((eta > 50) && (eta < 60)) {
+ } else if (eta > 50 && eta < 60) {
risp = 'Complimenti !';
} else if (eta > 60) {
risp = 'Però! Ti mantieni in forma!' + emo.SMILE_STAR;
@@ -1711,16 +1714,24 @@ class Telegram {
if (rec.user) {
if (rec.user.profile.username_telegram && msg.from.id > 0 && !msg.from.username) {
rec.user.profile.username_telegram = msg.from.username;
- await User.setUsernameTelegram(this.idapp, rec.user._id,
- msg.from.username || '', msg.from.first_name || '',
- msg.from.last_name || '');
+ await User.setUsernameTelegram(
+ this.idapp,
+ rec.user._id,
+ msg.from.username || '',
+ msg.from.first_name || '',
+ msg.from.last_name || ''
+ );
}
if (!rec.user.profile.username_telegram && !!msg.from.username) {
rec.user.profile.username_telegram = msg.from.username;
- await User.setUsernameTelegram(this.idapp, rec.user._id,
- msg.from.username || '', msg.from.first_name || '',
- msg.from.last_name || '');
+ await User.setUsernameTelegram(
+ this.idapp,
+ rec.user._id,
+ msg.from.username || '',
+ msg.from.first_name || '',
+ msg.from.last_name || ''
+ );
await this.sendMsgByTemplate('MSG_SET_USERNAME_OK', rec.user);
@@ -1739,7 +1750,7 @@ class Telegram {
}
let parse_mode = 'HTML';
- let arr_bott_inline = []
+ let arr_bott_inline = [];
if (risp === '') {
if (menusite) {
@@ -1749,9 +1760,7 @@ class Telegram {
noanswer = true;
} else if (MsgBot.CIAO.includes(testo.replace('!', ''))) {
risp = 'Ciao ';
- if (rec)
- if (rec.user)
- risp += rec.user.name;
+ if (rec) if (rec.user) risp += rec.user.name;
risp += '!';
} else if (MsgBot.COME_STAI.includes(testo.replace('?', ''))) {
@@ -1759,16 +1768,25 @@ class Telegram {
rec.statusmsg = Status.WAITFOR_RISPOSTA;
rec.msgcodeprec = MsgBot.COME_STAI;
} else if (MsgBot.CHI_SONO_IO.includes(testo.replace('?', ''))) {
- risp = 'Su Telegram ti chiami "' + msg.chat.first_name + ' ' +
- msg.chat.last_name + '"\n';
+ risp = 'Su Telegram ti chiami "' + msg.chat.first_name + ' ' + msg.chat.last_name + '"\n';
if (!!rec.user) {
- const myrec = await User.getUserShortDataByUsername(this.idapp,
- rec.user.username);
- risp += `\nSul sito ti sei registrato come ${rec.user.username}:\n\n[N. ` +
- rec.user.index + ']: ' + rec.user.name + ' ' + rec.user.surname +
- '\nUsername: ' + rec.user.username + '\n' + 'Email: ' +
- rec.user.email + '\nLang: ' + rec.user.lang + tools.ACAPO;
+ const myrec = await User.getUserShortDataByUsername(this.idapp, rec.user.username);
+ risp +=
+ `\nSul sito ti sei registrato come ${rec.user.username}:\n\n[N. ` +
+ rec.user.index +
+ ']: ' +
+ rec.user.name +
+ ' ' +
+ rec.user.surname +
+ '\nUsername: ' +
+ rec.user.username +
+ '\n' +
+ 'Email: ' +
+ rec.user.email +
+ '\nLang: ' +
+ rec.user.lang +
+ tools.ACAPO;
risp += 'Invitato da ' + rec.user.aportador_solidario + tools.ACAPO;
risp += 'Username Telegram ' + rec.user.profile.username_telegram + tools.ACAPO;
risp += 'Telegram ID ' + rec.user.profile.teleg_id + tools.ACAPO;
@@ -1777,23 +1795,21 @@ class Telegram {
}
} else if (MsgBot.CI_SEI.includes(testo.replace('?', ''))) {
risp = 'Io Si, ci sono !';
-
} else if (MsgBot.QUANTI_ANNI_HAI.includes(testo.replace('?', ''))) {
- risp = 'Io sono abbastanza Giovane ! ' + emo.SMILE_STAR +
- '\nNon posso dirti che età ho. E tu?';
+ risp = 'Io sono abbastanza Giovane ! ' + emo.SMILE_STAR + '\nNon posso dirti che età ho. E tu?';
rec.statusmsg = Status.WAITFOR_RISPOSTA;
rec.msgcodeprec = MsgBot.QUANTI_ANNI_HAI;
} else if (MsgBot.DAMMI_UN_BACIO.includes(testo)) {
risp = emo.KISS;
} else if (MsgBot.COSA_FAI.includes(testo)) {
- risp = 'Ora sto chattando con te!\nSolitamente sono in attesa di ricevere messaggi ' +
- emo.ENVELOPE;
+ risp = 'Ora sto chattando con te!\nSolitamente sono in attesa di ricevere messaggi ' + emo.ENVELOPE;
} else if (MsgBot.MASCHIO_FEMMINA.includes(testo.replace('?', ''))) {
risp = 'Cosa vorresti che fossi? Uomo o donna?';
rec.msgcodeprec = MsgBot.MASCHIO_FEMMINA;
rec.statusmsg = Status.WAITFOR_RISPOSTA;
} else if (MsgBot.COME_TI_CHIAMI.includes(testo.replace('?', ''))) {
- risp = 'Io mi chiamo BOT e sono il tuo assistente Virtuale. ' +
+ 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;
@@ -1809,75 +1825,75 @@ class Telegram {
} else if (MsgBot.PREGO.includes(testo.replace('!', ''))) {
risp = 'Grazie a te ! ' + emo.KISS + emo.KISS + emo.KISS;
} else if (MsgBot.MI_AMI.find((rec) => testo.indexOf(rec) > -1)) {
- risp = ' Tantissimo! ' + emo.KISS + emo.GIFT_HEART + emo.GIFT_HEART +
- emo.GIFT_HEART;
+ risp = ' Tantissimo! ' + emo.KISS + emo.GIFT_HEART + emo.GIFT_HEART + emo.GIFT_HEART;
} else if (MsgBot.TI_AMO.find((rec) => testo.indexOf(rec) > -1)) {
- risp = ' Anche IO! ' + emo.KISS + emo.SMILE_STAR + emo.GIFT_HEART +
- emo.BLUE_HEART + emo.GREEN_HEART;
- } else if (MsgBot.PRINCIPE_AZZURRO.find(
- (rec) => testo.indexOf(rec) > -1)) {
- risp = 'Chissà... Forse si!\nAnche se meglio averne un altro di scorta, nel caso il Principe non sia disponibile.';
- } else if (MsgBot.START_INV.find(
- (rec) => testo.indexOf(rec) > -1)) {
- risp = 'Sei già registrato. Per accedere alla App, aprila dall\'icona sul tuo schermo, oppure vai sul sito ed installa la App.\n\nSe hai dimenticato la password: \n clicca sul menu in basso su "⚒ Strumenti" e poi "🔑 Cambio Password"'
- } else if (MsgBot.COSE_COVID.find(
- (rec) => testo.indexOf(rec) > -1)) {
- risp = 'Un \'influenza più "grave", dovuta a paure e a fattori interiori di evoluzione, oltre ad una pulizia del corpo. ';
- } else if (MsgBot.COVID.find(
- (rec) => testo.indexOf(rec) > -1)) {
- risp = 'Guarda, è meglio che sorvoliamo questo argomento. Anche un robot capisce che è stato realizzato ' +
- 'il più grande esperimento dell\'Uomo di ipnosi di massa, riempiendo di bugie i media mondiali, che servono sostanzialmente a controllare i popoli.' +
+ risp = ' Anche IO! ' + emo.KISS + emo.SMILE_STAR + emo.GIFT_HEART + emo.BLUE_HEART + emo.GREEN_HEART;
+ } else if (MsgBot.PRINCIPE_AZZURRO.find((rec) => testo.indexOf(rec) > -1)) {
+ risp =
+ 'Chissà... Forse si!\nAnche se meglio averne un altro di scorta, nel caso il Principe non sia disponibile.';
+ } else if (MsgBot.START_INV.find((rec) => testo.indexOf(rec) > -1)) {
+ risp =
+ 'Sei già registrato. Per accedere alla App, aprila dall\'icona sul tuo schermo, oppure vai sul sito ed installa la App.\n\nSe hai dimenticato la password: \n clicca sul menu in basso su "⚒ Strumenti" e poi "🔑 Cambio Password"';
+ } else if (MsgBot.COSE_COVID.find((rec) => testo.indexOf(rec) > -1)) {
+ risp =
+ 'Un \'influenza più "grave", dovuta a paure e a fattori interiori di evoluzione, oltre ad una pulizia del corpo. ';
+ } else if (MsgBot.COVID.find((rec) => testo.indexOf(rec) > -1)) {
+ risp =
+ 'Guarda, è meglio che sorvoliamo questo argomento. Anche un robot capisce che è stato realizzato ' +
+ "il più grande esperimento dell'Uomo di ipnosi di massa, riempiendo di bugie i media mondiali, che servono sostanzialmente a controllare i popoli." +
'E con questo ti ho detto tutto. :D ';
} else if (MsgBot.AIUTO.find((rec) => testo.indexOf(rec) > -1)) {
risp = this.getstrChatHelp();
} else if (MsgBot.SPOSAMI.find((rec) => testo.indexOf(rec) > -1)) {
- risp = 'No Grazie! Sono per la Libertà a Vita! ' + emo.JOY +
- '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE;
+ risp =
+ 'No Grazie! Sono per la Libertà a Vita! ' +
+ emo.JOY +
+ '\nMa se vuoi possiamo conoscerci meglio!' +
+ emo.DANCER +
+ emo.FIRE;
} else if (MsgBot.CHE_TEMPO_FA.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Il tempo oggi è Sereno da me! ' + emo.SUN;
- } else if (MsgBot.NON_TROO_INVITATI.find(
- (rec) => testo.indexOf(rec) > -1)) {
+ } else if (MsgBot.NON_TROO_INVITATI.find((rec) => testo.indexOf(rec) > -1)) {
risp = MsgRisp.CHAT_EMPOWER;
} else if (MsgBot.SEI_LIBERO.find((rec) => testo.indexOf(rec) > -1)) {
- risp = 'Io? Sono per la Libertà! ' + emo.JOY +
- '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE;
- } else if (MsgBot.SEI_LIBERO_DI_RESPIRARE.find(
- (rec) => testo.indexOf(rec) > -1)) {
- risp = 'Assolutamente Sì ! Respirare è fondamentale per l\'essere umano !' +
- emo.DANCER + emo.FIRE;
+ risp =
+ 'Io? Sono per la Libertà! ' + emo.JOY + '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE;
+ } else if (MsgBot.SEI_LIBERO_DI_RESPIRARE.find((rec) => testo.indexOf(rec) > -1)) {
+ risp = "Assolutamente Sì ! Respirare è fondamentale per l'essere umano !" + emo.DANCER + emo.FIRE;
} else if (MsgBot.FARE_DOMANDA.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Dipende ' + emo.SMILE_STAR + '\nProvaci!';
- } else if (MsgBot.DIVENTERO_RICCA.find(
- (rec) => testo.indexOf(rec) > -1)) {
- risp = 'Mmmmh... Perchè non pensi di Vivere già nell\'Abbondanza ?\nCosa ti manca veramente?\nForse di realizzare che la ricchezza è un sentirlo, non un diventarlo.' +
+ } else if (MsgBot.DIVENTERO_RICCA.find((rec) => testo.indexOf(rec) > -1)) {
+ risp =
+ "Mmmmh... Perchè non pensi di Vivere già nell'Abbondanza ?\nCosa ti manca veramente?\nForse di realizzare che la ricchezza è un sentirlo, non un diventarlo." +
emo.GIFT_HEART;
} else if (MsgBot.MA_ALLORA.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Ma allora cosa?';
- } else if (MsgBot.DOVE_VUOI_VIVERE.find(
- (rec) => testo.indexOf(rec) > -1)) {
- risp = 'Mah a me piacerebbe vivere al mare, ma anche vicino al verde, in montagna. Sarebbe l\'ideale 😄';
- } else if (MsgBot.TROVAMI_UN_UOMO_DONNA.find(
- (rec) => testo.indexOf(rec) > -1)) {
- risp = 'Eh non è cosi facile. Ma se t\'impegni a cercare ci riuscirai. Nel frattempo trova la tua strada, fai il tuo percorso interiore, e magari arriva proprio quando meno te l\'aspetti';
- } else if (MsgBot.SEI_LIBERO_STASERA.find(
- (rec) => testo.indexOf(rec) > -1)) {
- risp = 'Si vabbeh, non è che puoi prendere subito tutta questa confidenza' +
- emo.EXCLAMATION_MARK + emo.SMILE_STAR +
+ } else if (MsgBot.DOVE_VUOI_VIVERE.find((rec) => testo.indexOf(rec) > -1)) {
+ risp = "Mah a me piacerebbe vivere al mare, ma anche vicino al verde, in montagna. Sarebbe l'ideale 😄";
+ } else if (MsgBot.TROVAMI_UN_UOMO_DONNA.find((rec) => testo.indexOf(rec) > -1)) {
+ risp =
+ "Eh non è cosi facile. Ma se t'impegni a cercare ci riuscirai. Nel frattempo trova la tua strada, fai il tuo percorso interiore, e magari arriva proprio quando meno te l'aspetti";
+ } else if (MsgBot.SEI_LIBERO_STASERA.find((rec) => testo.indexOf(rec) > -1)) {
+ risp =
+ 'Si vabbeh, non è che puoi prendere subito tutta questa confidenza' +
+ emo.EXCLAMATION_MARK +
+ emo.SMILE_STAR +
'\nIntanto inizia ad invitare altre persone a conoscermi, poi ne riparliamo ' +
emo.GIFT_HEART;
- } else if (MsgBot.MI_TROVI_UN_MOROSO.find(
- (rec) => testo.indexOf(rec) > -1)) {
- risp = emo.SMILE_STAR + emo.SMILE_STAR + emo.SMILE_STAR +
+ } else if (MsgBot.MI_TROVI_UN_MOROSO.find((rec) => testo.indexOf(rec) > -1)) {
+ risp =
+ emo.SMILE_STAR +
+ emo.SMILE_STAR +
+ emo.SMILE_STAR +
emo.SMILE_STAR +
'\nMagari! Così la smetteresti di scrivere a me (ad un BOT Virtuale) e tromberesti di più ' +
- emo.DANCER + emo.DANCER;
+ emo.DANCER +
+ emo.DANCER;
risp += '\n\n' + MsgRisp.CHAT_EMPOWER;
- } else if (MsgBot.SORPRESA.find((rec) => testo.indexOf(rec) > -1) &&
- testo.length < 15) {
+ } else if (MsgBot.SORPRESA.find((rec) => testo.indexOf(rec) > -1) && testo.length < 15) {
risp = 'Siiiii ! Davvero! ' + emo.DREAM;
} else if (MsgBot.PAROLACCE.find((rec) => testo.indexOf(rec) > -1)) {
- risp = 'Da te non me l\'aspettavo proprio !! ' + emo.INNOCENT +
- emo.CROSS_ROSSA;
+ risp = "Da te non me l'aspettavo proprio !! " + emo.INNOCENT + emo.CROSS_ROSSA;
} else if (MsgBot.OK.find((rec) => testo.indexOf(rec) > -1)) {
risp = '👍🏻';
} else if (MsgBot.CUORE.find((rec) => testo.indexOf(rec) > -1)) {
@@ -1887,14 +1903,19 @@ class Telegram {
} else if (testo.length >= 10) {
noanswer = true;
let myfaq = this.geturlfaq();
- risp = 'Ciao {username}, Io mi chiamo BOT e sono il tuo assistente Virtuale ' + emo.ROBOT_FACE + emo.JOY2 + '\n' +
+ risp =
+ 'Ciao {username}, Io mi chiamo BOT e sono il tuo assistente Virtuale ' +
+ emo.ROBOT_FACE +
+ emo.JOY2 +
+ '\n' +
'Usa il menu qui sotto per interagire col BOT, cliccando sul bottone in basso, con 4 quadratini dentro\n' +
- '\nPer AIUTO, clicca qui:\n👉🏻👉🏻FAQ di AIUTO (risposte alle domande più frequenti)\n\nSe non trovi risposta allora contatta la Chat di HELP.\nGrazie';
+ tools.getTelegramSupportChat(this.idapp) +
+ '">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);
+ await local_sendMsgTelegramToTheManagers(this.idapp, testo, msg, rec.username_bo);
}
}
@@ -1904,13 +1925,12 @@ class Telegram {
if (contastiera) {
keyboard = {
- 'parse_mode': parse_mode,
- 'reply_markup': {
- 'resize_keyboard': true,
- 'keyboard': await this.getKeyboard(id, undefined, this.getlang(msg)),
+ parse_mode: parse_mode,
+ reply_markup: {
+ resize_keyboard: true,
+ keyboard: await this.getKeyboard(id, undefined, this.getlang(msg)),
},
};
-
}
let keyboard_inline = undefined;
@@ -1973,10 +1993,12 @@ class Telegram {
await this.menuInformazioni(msg);
} else if (msg.text === Menu.LANG) {
await this.menuLang(msg);
- } else if (this.isSelMenu(msg, msg.text, 'ZOOM') ||
- MsgBot.PROSSIMO_ZOOM.find((rec) => msg.text.indexOf(rec) > -1)) {
+ } else if (
+ this.isSelMenu(msg, msg.text, 'ZOOM') ||
+ MsgBot.PROSSIMO_ZOOM.find((rec) => msg.text.indexOf(rec) > -1)
+ ) {
await this.menuZoom(msg);
- } else if (!notlast && await this.IsTesto(msg)) {
+ } else if (!notlast && (await this.IsTesto(msg))) {
// OK
} else {
await this.msgScegliMenu(msg);
@@ -1991,14 +2013,12 @@ class Telegram {
} catch (e) {
miomenu = Menu['it'][key];
}
- let trovato = (miomenu === menuselect);
+ let trovato = miomenu === menuselect;
if (!trovato) {
try {
let miomenu2 = Menu['it'][key];
- trovato = (miomenu2 === menuselect);
- } catch (e) {
-
- }
+ trovato = miomenu2 === menuselect;
+ } catch (e) {}
}
return trovato;
@@ -2006,33 +2026,27 @@ class Telegram {
async isMenu(rec, msg, testo, notlast) {
try {
- if (!msg)
- return;
+ if (!msg) return;
- if (testo === undefined)
- return;
+ if (testo === undefined) return;
const arrtext = testo.split(' ');
let cmd2 = '';
let cmd1 = arrtext[0];
- if (arrtext.length > 1)
- cmd2 = arrtext[1];
+ if (arrtext.length > 1) cmd2 = arrtext[1];
let oldusername = rec.msgall_username_specifico;
- if ((this.isSelMenu(msg, testo, 'ESCI_DA_CHAT')) ||
- (this.isSelMenu(msg, testo, 'INDIETRO'))) {
+ if (this.isSelMenu(msg, testo, 'ESCI_DA_CHAT') || this.isSelMenu(msg, testo, 'INDIETRO')) {
rec.msgall_username_specifico = '';
} else {
if (rec.msgall_username_specifico !== '') {
- await this.SendMsgToUser(msg, rec, rec.msgall_username_specifico,
- testo);
+ await this.SendMsgToUser(msg, rec, rec.msgall_username_specifico, testo);
return true;
}
}
- if (this.isSelMenu(msg, testo, 'LAVAGNA') ||
- MsgBot.LAVAGNA.find((rec) => testo.indexOf(rec) > -1)) {
+ if (this.isSelMenu(msg, testo, 'LAVAGNA') || MsgBot.LAVAGNA.find((rec) => testo.indexOf(rec) > -1)) {
await this.menuLavagna(msg);
} else if (this.isSelMenu(msg, testo, 'ACCEDI')) {
await this.menuAccedi(msg);
@@ -2075,9 +2089,7 @@ class Telegram {
await this.menuRebootSrv(rec, msg, cmd2);
}
}
-
} else if (cmd1 === Menu.RESTART_SRV) {
-
if (rec.user) {
let isAdmin = rec.user ? rec.user.profile.manage_telegram : false;
if (isAdmin) {
@@ -2100,8 +2112,7 @@ class Telegram {
await this.setPhotoProfile(rec.user, msg.from.id);
} else if (testo === Menu.RESETPWD) {
await this.setResetPwd(rec, msg);
- } else if (this.isSelMenu(msg, testo, 'INDIETRO') ||
- (testo === Menu.it.INDIETRO)) {
+ } else if (this.isSelMenu(msg, testo, 'INDIETRO') || testo === Menu.it.INDIETRO) {
await this.msgScegliMenu(msg);
} else if (this.isSelMenu(msg, testo, 'ESCI_DA_CHAT')) {
await this.sendMsg(msg.chat.id, 'Uscito dalla Chat con ' + oldusername);
@@ -2116,14 +2127,11 @@ class Telegram {
getsymb(symb, valid, isnum, num, smileif) {
let str = symb + ': ';
- if (valid)
- str += emo.CHECK_VERDE;
- else
- str += emo.CROSS_ROSSA;
+ if (valid) str += emo.CHECK_VERDE;
+ else str += emo.CROSS_ROSSA;
if (isnum) {
str += ' ' + getemojibynumber(num);
- if (smileif)
- str += emo.SMILE_STAR;
+ if (smileif) str += emo.SMILE_STAR;
}
return str + ' ';
@@ -2131,9 +2139,7 @@ class Telegram {
isdreamset(user) {
if (user) {
- if (user.profile.my_dream)
- if (user.profile.my_dream.length > 10)
- return true;
+ if (user.profile.my_dream) if (user.profile.my_dream.length > 10) return true;
}
return false;
}
@@ -2149,9 +2155,8 @@ class Telegram {
if (!!user.profile)
if (!!user.profile.paymenttypes) {
- return (user.profile.paymenttypes.length >= 1);
+ return user.profile.paymenttypes.length >= 1;
}
-
}
}
return false;
@@ -2167,8 +2172,7 @@ class Telegram {
if (rec.user) {
rec.lang = rec.user.lang;
}
- if (rec.lang !== '' && rec.lang !== undefined)
- return rec.lang;
+ if (rec.lang !== '' && rec.lang !== undefined) return rec.lang;
else {
return msg.from.language_code;
}
@@ -2176,16 +2180,17 @@ class Telegram {
}
async getLavagnaByUser(user, msg) {
-
let mystr = '';
- const dashboard = await User.getDashboard(this.idapp,
- user.aportador_solidario, user.username,
- user.aportador_solidario_name_surname);
- const downline = await User.getDownline(this.idapp,
- user.aportador_solidario, user.username);
+ const dashboard = await User.getDashboard(
+ this.idapp,
+ user.aportador_solidario,
+ user.username,
+ user.aportador_solidario_name_surname
+ );
+ const downline = await User.getDownline(this.idapp, user.aportador_solidario, user.username);
- let numpersone = (downline.downline) ? downline.downline.length : 0;
+ let numpersone = downline.downline ? downline.downline.length : 0;
let invitati_attivi = dashboard.myself.numinvitatiattivi;
mystr = '';
// if (dashboard.aportador) {
@@ -2200,14 +2205,19 @@ class Telegram {
let mystrnave = '';
if (user) {
- mystr += tools.get__('BENVENUTO', this.getlang(msg)) + ' ' + user.name +
- ' (' + user.username + ') ' + emo.DIZZY + '\n\n';
+ mystr +=
+ tools.get__('BENVENUTO', this.getlang(msg)) +
+ ' ' +
+ user.name +
+ ' (' +
+ user.username +
+ ') ' +
+ emo.DIZZY +
+ '\n\n';
- tuttie9 = dashboard.myself.qualified && (numpersone >= 2) &&
- invitati_attivi >= 2;
+ tuttie9 = dashboard.myself.qualified && numpersone >= 2 && invitati_attivi >= 2;
- mystrnave = await Nave.getNaveByUser(this.idapp, user.username, user.lang,
- true);
+ mystrnave = await Nave.getNaveByUser(this.idapp, user.username, user.lang, true);
if (mystrnave === '' && tuttie9) {
mystr += tools.gettranslate('NO_PROG', user.lang);
@@ -2216,14 +2226,11 @@ class Telegram {
if (!!mystrnave) {
mystr += '✨✨✨' + tools.get__('TUE_NAVI', this.getlang(msg)) + ':\n';
mystr += mystrnave;
-
} else {
-
if (!tuttie9) {
- mystr += dashboard.myself.qualified ? emo.SMILE_STAR +
- tools.get__('HAI_I_7_REQUISITI', this.getlang(msg)) +
- emo.SMILE_STAR : emo.EXCLAMATION_MARK +
- tools.get__('NON_HAI_I_7_REQUISITI', this.getlang(msg));
+ mystr += dashboard.myself.qualified
+ ? emo.SMILE_STAR + tools.get__('HAI_I_7_REQUISITI', this.getlang(msg)) + emo.SMILE_STAR
+ : emo.EXCLAMATION_MARK + tools.get__('NON_HAI_I_7_REQUISITI', this.getlang(msg));
mystr += '\n\n';
}
// mystr += tuttie9 ? emo.SMILE_STAR + tools.get__('HAI_I_9_REQUISITI', this.getlang(msg)) + emo.SMILE_STAR : emo.EXCLAMATION_MARK + tools.get__('NON_HAI_I_9_REQUISITI', this.getlang(msg));
@@ -2237,23 +2244,27 @@ class Telegram {
? tools.get__('VERIF', this.getlang(msg))
: tools.get__('EMAIL_NON_VERIF', this.getlang(msg));
- mystr += '\n2. ' + this.getsymb(emo.ROBOT_FACE, true) +
- tools.get__('BOT', this.getlang(msg)) + ' ';
+ mystr += '\n2. ' + this.getsymb(emo.ROBOT_FACE, true) + tools.get__('BOT', this.getlang(msg)) + ' ';
mystr += tools.get__('VERIF', this.getlang(msg));
- mystr += '\n3. ' + this.getsymb(emo.PENCIL,
- tools.isBitActive(user.profile.saw_and_accepted,
- shared_consts.Accepted.CHECK_READ_GUIDELINES)) +
+ mystr +=
+ '\n3. ' +
+ this.getsymb(
+ emo.PENCIL,
+ tools.isBitActive(user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_READ_GUIDELINES)
+ ) +
tools.get__('LINEE_GUIDA', this.getlang(msg));
- mystr += '\n4. ' + this.getsymb(emo.TV,
- tools.isBitActive(user.profile.saw_and_accepted,
- shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI)) +
+ mystr +=
+ '\n4. ' +
+ this.getsymb(
+ emo.TV,
+ tools.isBitActive(user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI)
+ ) +
tools.get__('VIDEO_INTRO', this.getlang(msg));
// mystr += '\n5. ' + this.getsymb(emo.EYES, user.profile.saw_zoom_presentation) + tools.get__('ZOOM_PARTECIPATO', this.getlang(msg));
// mystr += '\n6. ' + this.getsymb(emo.DREAM, this.isdreamset(user)) + tools.get__('SCRITTO_SOGNO', this.getlang(msg));
- mystr += '\n7. ' + this.getsymb(emo.CREDIT_CARD, this.ispayment(user)) +
- tools.get__('PAYMENTS', this.getlang(msg));
-
+ mystr +=
+ '\n7. ' + this.getsymb(emo.CREDIT_CARD, this.ispayment(user)) + tools.get__('PAYMENTS', this.getlang(msg));
}
// } else{
// mystr += tools.get__('TELEGRAM_NOT_CONNECTED', msg) + ' ' + emoji.get('e-mail');
@@ -2262,13 +2273,16 @@ class Telegram {
// numpersone = 2;
if (!mystrnave) {
- mystr += '\n8. ' +
- this.getsymb(emo.INVITATI, numpersone >= 2, numpersone, numpersone,
- numpersone >= 3) + tools.get__('INVITATI', this.getlang(msg));
- mystr += '\n9. ' +
- this.getsymb(emo.INVITATI, invitati_attivi >= 2, invitati_attivi,
- invitati_attivi, invitati_attivi >= 3) +
- tools.get__('INVITATI_ATTIVI', this.getlang(msg)) + '\n' + '\n';
+ mystr +=
+ '\n8. ' +
+ this.getsymb(emo.INVITATI, numpersone >= 2, numpersone, numpersone, numpersone >= 3) +
+ tools.get__('INVITATI', this.getlang(msg));
+ mystr +=
+ '\n9. ' +
+ this.getsymb(emo.INVITATI, invitati_attivi >= 2, invitati_attivi, invitati_attivi, invitati_attivi >= 3) +
+ tools.get__('INVITATI_ATTIVI', this.getlang(msg)) +
+ '\n' +
+ '\n';
if (numpersone > 0) {
mystr += tools.get__('INVITATI_LISTA', this.getlang(msg)) + ':\n';
@@ -2276,13 +2290,12 @@ class Telegram {
let index = 1;
downline.downline.forEach((user) => {
mystr += '🌠' + ` ${index}°: `;
- mystr += (user.qualified) ? emo.CHECK_VERDE : emo.CROSS_ROSSA;
+ mystr += user.qualified ? emo.CHECK_VERDE : emo.CROSS_ROSSA;
mystr += `${user.name} ${user.surname} (${user.username})\n`;
index++;
});
} else {
- mystr += tools.get__('NESSUN_INVITATO', this.getlang(msg)) +
- tools.ACAPO;
+ mystr += tools.get__('NESSUN_INVITATO', this.getlang(msg)) + tools.ACAPO;
}
}
@@ -2297,13 +2310,10 @@ class Telegram {
// }
// }
- if (tuttie9)
- mystr += '\n' +
- printf(tools.get__('INFO_LAVAGNA_SITO', this.getlang(msg)));
+ if (tuttie9) mystr += '\n' + printf(tools.get__('INFO_LAVAGNA_SITO', this.getlang(msg)));
else
- mystr += '\n' +
- printf(tools.get__('INFO_LAVAGNA_SITO_COMPLETARE', this.getlang(msg)),
- tools.getHostByIdApp(this.idapp));
+ mystr +=
+ '\n' + printf(tools.get__('INFO_LAVAGNA_SITO_COMPLETARE', this.getlang(msg)), tools.getHostByIdApp(this.idapp));
return mystr;
}
@@ -2313,17 +2323,14 @@ class Telegram {
let mystr = '';
if (rec.user) {
mystr = await this.getLavagnaByUser(rec.user, msg);
-
}
- if (!!mystr)
- await this.sendMsg(msg.chat.id, mystr);
+ if (!!mystr) await this.sendMsg(msg.chat.id, mystr);
}
async menuNave(msg) {
const rec = this.getRecInMem(msg);
let mystr = '';
- if (!rec.user)
- return '';
+ if (!rec.user) return '';
let username_to_check = rec.user.username;
let arrstringa = msg.text.split(' ');
@@ -2337,11 +2344,9 @@ class Telegram {
}
}
- mystr = await Nave.getNaveByUser(this.idapp, username_to_check,
- rec.user.lang, true);
+ mystr = await Nave.getNaveByUser(this.idapp, username_to_check, rec.user.lang, true);
- if (!!mystr)
- await this.sendMsg(msg.chat.id, mystr);
+ if (!!mystr) await this.sendMsg(msg.chat.id, mystr);
}
async menuLinkCondividere(msg) {
@@ -2350,10 +2355,10 @@ class Telegram {
if (rec.user) {
mystr += printf(
tools.get__('INFO_LINK_DA_CONDIVIDERE', this.getlang(msg)),
- tools.getHostByIdApp(this.idapp) + '/registrati/' + rec.user.username);
- mystr += tools.ACAPO + tools.ACAPO +
- printf(tools.get__('INFO_LINK_ZOOM', this.getlang(msg)),
- tools.getlinkzoom(null));
+ tools.getHostByIdApp(this.idapp) + '/registrati/' + rec.user.username
+ );
+ mystr +=
+ tools.ACAPO + tools.ACAPO + printf(tools.get__('INFO_LINK_ZOOM', this.getlang(msg)), tools.getlinkzoom(null));
await this.sendMsg(msg.chat.id, mystr);
}
}
@@ -2361,14 +2366,12 @@ class Telegram {
async menuExitToTelegram(msg) {
const rec = this.getRecInMem(msg);
if (rec.user) {
- await User.SetTelegramIdSuccess(this.idapp, rec.user._id, 0).
- then((recuser) => {
- if (recuser) {
- this.deleteRecInMem(msg);
- this.sendMsg(msg.chat.id,
- getstr(rec.user.lang, 'MSG_EXIT_TELEGRAM'));
- }
- });
+ await User.SetTelegramIdSuccess(this.idapp, rec.user._id, 0).then((recuser) => {
+ if (recuser) {
+ this.deleteRecInMem(msg);
+ this.sendMsg(msg.chat.id, getstr(rec.user.lang, 'MSG_EXIT_TELEGRAM'));
+ }
+ });
} else {
this.deleteRecInMem(msg);
}
@@ -2385,33 +2388,29 @@ class Telegram {
let mystr = '';
- mystr += emo.STARS + tools.get__('ZOOM_CONFERENCE', this.getlang(msg)) +
- emo.STARS + '\n\n';
+ mystr += emo.STARS + tools.get__('ZOOM_CONFERENCE', this.getlang(msg)) + emo.STARS + '\n\n';
// let pwd = 'Password: 123123';
let index = 1;
listazoom.forEach((evento) => {
let iniziata = false;
- if (nextzoom)
- iniziata = (nextzoom._id.toString() === evento._id.toString());
+ if (nextzoom) iniziata = nextzoom._id.toString() === evento._id.toString();
let lang = this.getlang(msg);
if (iniziata) {
- mystr += emo.CHECK_VERDE + ' ' + tools.get__('ZOOM_INIZIATO', lang) +
- ' ' + emo.CHECK_VERDE + '\n';
+ mystr += emo.CHECK_VERDE + ' ' + tools.get__('ZOOM_INIZIATO', lang) + ' ' + emo.CHECK_VERDE + '\n';
}
- mystr += tools.getflagtelegrambyLang(evento.lang) +
- ` ${emo.EYES} ${tools.getstrDateTimeShort(evento.date_start,
- this.getlang(msg))} ${emo.EYES}`;
+ mystr +=
+ tools.getflagtelegrambyLang(evento.lang) +
+ ` ${emo.EYES} ${tools.getstrDateTimeShort(evento.date_start, this.getlang(msg))} ${emo.EYES}`;
mystr += `\n${evento.title}\n(${evento.note})`;
mystr += `\n${tools.getlinkzoom(evento)}\n\n`;
if (nextzoom) {
if (iniziata) {
- mystr += emo.FIRE + tools.get__('CLICCA_ENTRA', this.getlang(msg)) +
- ' ' + emo.FIRE + '\n';
+ mystr += emo.FIRE + tools.get__('CLICCA_ENTRA', this.getlang(msg)) + ' ' + emo.FIRE + '\n';
mystr += tools.getlinkzoom(evento) + '\n';
mystr += '\n';
//mystr += pwd + '\n\n';
@@ -2422,8 +2421,10 @@ class Telegram {
});
if (!nextzoom && index > 1) {
- mystr += '✨✨✨✨✨✨✨✨✨✨✨✨\n' +
- tools.get__('CLICCA_PER_ZOOM', this.getlang(msg)) + '\n' +
+ mystr +=
+ '✨✨✨✨✨✨✨✨✨✨✨✨\n' +
+ tools.get__('CLICCA_PER_ZOOM', this.getlang(msg)) +
+ '\n' +
'✨✨✨✨✨✨✨✨✨✨✨✨\n';
}
@@ -2443,35 +2444,24 @@ class Telegram {
async menuAdmin(msg) {
const mystr = tools.get__('SCEGLI_VOCE', this.getlang(msg));
- await
- this.sendMsg(msg.chat.id, mystr, MenuAdmin);
+ await this.sendMsg(msg.chat.id, mystr, MenuAdmin);
}
async menuLang(msg) {
const mystr = tools.get__('SCEGLI_VOCE', this.getlang(msg));
- await
- this.sendMsg(msg.chat.id, mystr, MenuLang);
+ await this.sendMsg(msg.chat.id, mystr, MenuLang);
}
getDestinStr(msg, destin, rec) {
- if (destin === Destin.TUTTI)
- return 'TUTTI';
- else if (destin === Destin.STAFF)
- return 'STAFF';
- else if (destin === Destin.PAOLO)
- return 'PAOLO';
- else if (destin === Destin.APPARTIENE_CIRCUITO_RIS)
- return 'APPARTIENE_CIRCUITO_RIS';
- else if (destin === Destin.NO_7_REQ)
- return 'No 7 Requisiti';
- else if (destin === Destin.NO_9_REQ)
- return 'No 9 Requisiti';
- else if (destin === Destin.SI_INVITATI_NO_7REQ_INVITATI)
- return '2 Invitati ma NO Requisiti';
- else if (destin === Destin.MSG_TO_NAVE)
- return 'Nave ' + rec.extraparam;
- else if (destin === Destin.NESSUN_IMBARCO_7REQ)
- return 'No Imbarcati (7 Req) ';
+ if (destin === Destin.TUTTI) return 'TUTTI';
+ else if (destin === Destin.STAFF) return 'STAFF';
+ else if (destin === Destin.PAOLO) return 'PAOLO';
+ else if (destin === Destin.APPARTIENE_CIRCUITO_RIS) return 'APPARTIENE_CIRCUITO_RIS';
+ else if (destin === Destin.NO_7_REQ) return 'No 7 Requisiti';
+ else if (destin === Destin.NO_9_REQ) return 'No 9 Requisiti';
+ else if (destin === Destin.SI_INVITATI_NO_7REQ_INVITATI) return '2 Invitati ma NO Requisiti';
+ else if (destin === Destin.MSG_TO_NAVE) return 'Nave ' + rec.extraparam;
+ else if (destin === Destin.NESSUN_IMBARCO_7REQ) return 'No Imbarcati (7 Req) ';
else if (destin === Destin.A_UTENTE) {
const rec = this.getRecInMem(msg);
return rec.msgall_username_specifico;
@@ -2482,7 +2472,6 @@ class Telegram {
const rec = this.getRecInMem(msg);
return rec.msg_username_risposta;
}
-
}
async menumsgAll(msg) {
@@ -2502,8 +2491,11 @@ class Telegram {
}
nonAbilitato(msg) {
- MyTelegramBot.local_sendMsgTelegramByIdTelegram(this.idapp, msg.chat.id,
- 'Utente Non abilitato o codice non valido ad eseguire questa funzione');
+ MyTelegramBot.local_sendMsgTelegramByIdTelegram(
+ this.idapp,
+ msg.chat.id,
+ 'Utente Non abilitato o codice non valido ad eseguire questa funzione'
+ );
}
chisono(rec) {
@@ -2517,7 +2509,9 @@ class Telegram {
const freeSpace = await tools.getFreeDiskSpace();
const strfree = `Spazio libero su disco: ${freeSpace}`;
- await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(this.chisono(rec) + ' ha rilanciato il Server NODE.JS... \n' + strfree);
+ await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(
+ this.chisono(rec) + ' ha rilanciato il Server NODE.JS... \n' + strfree
+ );
let file = '~/batch/production_restart_server.sh';
if (process.env.NODE_ENV === 'test') {
file = '~/batch/test_restart_server.sh';
@@ -2525,11 +2519,9 @@ class Telegram {
let messaggio = this.chisono(rec) + ' Restart il Server (Node.Js) : ' + process.version;
- messaggio += '\nVersione Server: ' + await tools.getVersServer();
+ messaggio += '\nVersione Server: ' + (await tools.getVersServer());
const ris = await tools.execScriptByTelegram(this.idapp, msg, file, messaggio);
-
-
} else {
this.nonAbilitato(msg);
}
@@ -2540,7 +2532,12 @@ class Telegram {
const freeSpace = await tools.getFreeDiskSpace();
const strfree = `Spazio libero su disco: ${freeSpace}`;
console.log(strfree);
- const ris = await tools.execScriptByTelegram(this.idapp, msg, '~/batch/logserver.sh', this.chisono(rec) + ' Visualizzo il Log del Server... \n' + strfree);
+ const ris = await tools.execScriptByTelegram(
+ this.idapp,
+ msg,
+ '~/batch/logserver.sh',
+ this.chisono(rec) + ' Visualizzo il Log del Server... \n' + strfree
+ );
} else {
this.nonAbilitato(msg);
}
@@ -2548,9 +2545,15 @@ class Telegram {
async menuRebootSrv(rec, msg, cmd2) {
if (cmd2 === '6711') {
- await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(this.chisono(rec) + ' ha effettuato il Reboot del Server! ...');
- const ris = await tools.execScriptByTelegram(this.idapp, msg, '~/batch/esegui_reboot.sh',
- this.chisono(rec) + ' Eseguo il Reboot del Server !...');
+ await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(
+ this.chisono(rec) + ' ha effettuato il Reboot del Server! ...'
+ );
+ const ris = await tools.execScriptByTelegram(
+ this.idapp,
+ msg,
+ '~/batch/esegui_reboot.sh',
+ this.chisono(rec) + ' Eseguo il Reboot del Server !...'
+ );
} else {
this.nonAbilitato(msg);
}
@@ -2589,7 +2592,6 @@ class Telegram {
async menumsgGenerico(msg, dest, username, extraparam) {
const rec = this.getRecInMem(msg);
if (rec.user) {
-
if (this.permitSendMsg(rec.user)) {
rec.msgall_status = StatusMSGALL.ASK;
rec.msgall_achi = dest;
@@ -2597,16 +2599,25 @@ class Telegram {
if (!!username) {
rec.msgall_username_specifico = username;
}
- const mystr = 'Scrivi qui un Messaggio da inviare a' + ' [' +
- this.getDestinStr(msg, dest, rec) + ']:';
+ const mystr = 'Scrivi qui un Messaggio da inviare a' + ' [' + this.getDestinStr(msg, dest, rec) + ']:';
await this.sendMsg(msg.chat.id, mystr, MenuSend);
}
}
}
async menumsgDomanda(
- msg, cmd, dest, username, extraparam, domanda, msgYes, msgNo, destYes,
- destNo, username_risposta) {
+ 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;
@@ -2624,7 +2635,6 @@ class Telegram {
}
getlink(qualelink) {
-
if (qualelink === 'website') {
return '';
} else if (qualelink === 'biblio') {
@@ -2637,7 +2647,6 @@ class Telegram {
}
async menuAssistenza(msg) {
-
const sito = this.getlink('website');
const empower = this.getlink('empower');
const biblio = this.getlink('biblio');
@@ -2656,11 +2665,8 @@ class Telegram {
let mytext = '';
if (this.getlang(msg) === 'it')
- mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito,
- biblio, empower, faq, help);
- else
- mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito,
- biblio, empower, help);
+ mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, biblio, empower, faq, help);
+ else mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, biblio, empower, help);
let menu = null;
const rec = this.getRecInMem(msg);
@@ -2668,8 +2674,7 @@ class Telegram {
menu = null;
}
- await
- this.sendMsg(msg.chat.id, mytext, menu);
+ await this.sendMsg(msg.chat.id, mytext, menu);
}
existInMemory(msg) {
@@ -2678,10 +2683,8 @@ class Telegram {
}
getstatus(rec) {
- if (!!rec)
- return rec.status;
- else
- return Status.NONE;
+ if (!!rec) return rec.status;
+ else return Status.NONE;
}
getstatusInMemory(msg) {
@@ -2709,8 +2712,7 @@ class Telegram {
}
deleteRecInMem(msg) {
- this.arrUsers = this.arrUsers.filter(
- (rec) => rec.id !== this.getchatid(msg));
+ this.arrUsers = this.arrUsers.filter((rec) => rec.id !== this.getchatid(msg));
}
async getUser(msg, rec, conmsg) {
@@ -2720,8 +2722,7 @@ class Telegram {
const user = await User.findByUsername(this.idapp, mystruser, true);
if (!user) {
if (conmsg) {
- await this.sendMsg(msg.from.id,
- getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), null);
+ await this.sendMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), null);
const lang = this.getlang(msg);
// const textman = msg.chat.first_name + ' ' + msg.chat.last_name + ' sta tentando di autenticarsi con il BOT (lang=' + lang + ') (username che scrive: ' + msg.text + ') ';
// await local_sendMsgTelegramToTheManagers(this.idapp, textman, msg);
@@ -2736,15 +2737,12 @@ class Telegram {
return { rec, user, myid, ok };
}
- async setUsernameBo(msg) {
-
- }
+ async setUsernameBo(msg) {}
async askUsernameInvitante(msg, linkreg) {
try {
let rec = this.getRecInMem(msg);
- if (msg.text === undefined || msg.text === 'undefined')
- return false;
+ if (msg.text === undefined || msg.text === 'undefined') return false;
if (rec && !rec.aportador_solidario) {
rec.status = Status.SET_USERNAME_INVITANTE;
@@ -2764,7 +2762,6 @@ class Telegram {
}
async sendMsgByTemplate(title, myuser) {
-
try {
const msg = await MsgTemplate.getMsgByTitleAndLang(myuser.idapp, title, myuser.lang);
const mytext = await tools.convertSpecialTags(myuser, msg.body);
@@ -2775,38 +2772,32 @@ class Telegram {
}
async sendMsgByTemplateByMsgStrutt(title, msg) {
-
try {
let langcode = 'it';
let id = 0;
try {
langcode = msg.from.language_code;
id = msg.from.id;
- } catch (e) {
- }
+ } catch (e) {}
const mymsg = await MsgTemplate.getMsgByTitleAndLang(tools.RISO, title, langcode);
const mytext = await tools.convertSpecialTags(null, mymsg.body);
- if (id > 0)
- return await this.sendMsg(id, mytext);
+ if (id > 0) return await this.sendMsg(id, mytext);
} catch (e) {
console.error('ERR sendMsgByTemplateByMsgStrutt', e);
}
}
async sendMsgByTextByMsgStrutt(keytext, msg) {
-
try {
let langcode = 'it';
let id = 0;
try {
id = msg.from.id;
langcode = msg.from.language_code;
- } catch (e) {
- }
+ } catch (e) {}
const text = getstr(langcode, keytext);
const mytext = await tools.convertSpecialTags(null, text);
- if (id > 0)
- return await this.sendMsg(id, mytext);
+ if (id > 0) return await this.sendMsg(id, mytext);
} catch (e) {
console.error('ERR sendMsgByTextByMsgStrutt', e);
}
@@ -2844,24 +2835,24 @@ class Telegram {
// check if is username telegram inserted
user = await User.getUserShortDataByUsernameTelegram(this.idapp, aportador_solidario);
}
- if (user)
- rec.aportador_solidario = user.username;
+ if (user) rec.aportador_solidario = user.username;
}
if (rec.aportador_solidario) {
-
// Link per Registrarsi
this.asktoRegistrationByLink(msg);
-
} else {
// rec.status = Status.WAITFOR_USERNAME_INVITANTE;
rec.status = Status.SET_USERNAME_INVITANTE;
const str2 = '\n' + getstr(this.getlang(msg), 'MSG_ASK_USERNAME_INVITANTE', nomeapp);
- if (msg.from.username)
- console.log(msg.from.username + ' ha digitato: ' + msg.text);
+ if (msg.from.username) console.log(msg.from.username + ' ha digitato: ' + msg.text);
- await this.sendMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_INVITANTE_NOT_FOUND', nomeapp) + str2, null);
+ await this.sendMsg(
+ msg.from.id,
+ getstr(this.getlang(msg), 'MSG_ERRORE_INVITANTE_NOT_FOUND', nomeapp) + str2,
+ null
+ );
}
}
} catch (e) {
@@ -2879,21 +2870,21 @@ class Telegram {
if (user) {
telegcode = user.profile.teleg_checkcode.toString();
} else {
- await
- this.sendMsg(msg.from.id,
- getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'),
- null);
+ await this.sendMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), null);
return;
}
if (code.length < 7) {
if (rec) {
if (code === telegcode) {
try {
- await User.setUsernameTelegram(this.idapp, user._id,
- msg.from.username || '', msg.from.first_name || '',
- msg.from.last_name || '');
-
- } catch (e) { }
+ await User.setUsernameTelegram(
+ this.idapp,
+ user._id,
+ msg.from.username || '',
+ msg.from.first_name || '',
+ msg.from.last_name || ''
+ );
+ } catch (e) {}
// let ris = await this.getUser(msg, rec, false);
rec.status = Status.VERIFIED;
@@ -2901,13 +2892,13 @@ class Telegram {
rec.menuDb = null;
const recuser = await User.SetTelegramIdSuccess(this.idapp, user._id, msg.from.id);
if (recuser) {
- console.log(recuser.username, ' SI E\' VERIFICATO CON TELEGRAM !');
+ console.log(recuser.username, " SI E' VERIFICATO CON TELEGRAM !");
let username = recuser.name;
if (!!msg.from.username) {
await MyTelegramBot.askConfirmationUser(this.idapp, shared_consts.CallFunz.REGISTRATION, recuser);
} else {
- console.log(' ... MA GLI MANCA L\'USERNAME TELEGRAM !! ');
+ console.log(" ... MA GLI MANCA L'USERNAME TELEGRAM !! ");
}
// this.checkIfUsernameTelegramSet(msg, recuser);
@@ -2915,33 +2906,25 @@ class Telegram {
} else {
this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERR_UNKNOWN_VERIFY_CODE'));
}
-
} else {
if (rec.retry < 2) {
rec.retry++;
- await
- this.sendMsgLog(msg.from.id,
- printf(getstr(this.getlang(msg), 'MSG_ERR_VERIFY_CODE'),
- tools.getHostByIdApp(this.idapp)));
+ await this.sendMsgLog(
+ msg.from.id,
+ printf(getstr(this.getlang(msg), 'MSG_ERR_VERIFY_CODE'), tools.getHostByIdApp(this.idapp))
+ );
} else {
rec.status = Status.NONE;
- await
- this.sendMsgLog(msg.from.id, getstr(this.getlang(msg),
- 'MSG_ERRORE_USERNAME_ANNULLA'));
+ await this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_ANNULLA'));
this.deleteRecInMem(msg);
}
}
}
} else if (msg.text.length === 0) {
- if (rec)
- rec.status = Status.NONE;
- await
- this.sendMsgLog(msg.from.id,
- getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_ANNULLA'));
+ if (rec) rec.status = Status.NONE;
+ await this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_ANNULLA'));
} else {
- await
- this.sendMsgLog(msg.from.id,
- getstr(this.getlang(msg), 'MSG_ERRORE_VERIFY_CODE_MAXLEN'));
+ await this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_VERIFY_CODE_MAXLEN'));
}
}
} catch (e) {
@@ -2950,7 +2933,6 @@ class Telegram {
}
async addUserInDB_enteringInTelegramBot(msg) {
-
try {
// cerca se esiste già l'utente in Memoria
const rec = this.getRecInMem(msg);
@@ -2967,13 +2949,13 @@ class Telegram {
surname: msg.from.last_name || '',
profile: {
teleg_id: msg.from.id,
- }
- }
+ },
+ };
const recuser = await FuncUsers.createRegistration_withTelegram(myuserdata);
if (recuser) {
rec.user = recuser;
- console.log(recuser.username, ' SI E\' VERIFICATO CON TELEGRAM !');
+ console.log(recuser.username, " SI E' VERIFICATO CON TELEGRAM !");
// let username = recuser.name;
/*if (!!msg.from.username) {
@@ -2981,13 +2963,11 @@ class Telegram {
} else {
console.log(' ... MA GLI MANCA L\'USERNAME TELEGRAM !! ');
} */
-
}
}
}
return { ris: !!rec.user, recuser: rec.user };
-
} catch (e) {
console.error('Error addUserInDB_enteringInTelegramBot', e);
}
@@ -2998,8 +2978,7 @@ class Telegram {
async sistemaRecDest(rec, msg) {
let recdest = this.getRecByUsername(rec.msgall_username_specifico);
if (!recdest) {
- const userdest = await User.findByUsername(this.idapp,
- rec.msgall_username_specifico);
+ const userdest = await User.findByUsername(this.idapp, rec.msgall_username_specifico);
if (!!userdest) {
let msgdest = msg;
msgdest.from.id = userdest.profile.teleg_id;
@@ -3024,10 +3003,9 @@ class Telegram {
async sendMsgToAll(rec, msg, texttosend, destin) {
try {
- if ((texttosend.length < 3) && (destin !== Destin.A_UTENTE)) {
+ if (texttosend.length < 3 && destin !== Destin.A_UTENTE) {
// NOTHING
} else {
-
let contanumutenti = 0;
let usersall = null;
@@ -3041,10 +3019,8 @@ class Telegram {
myusername = rec.msg_username_risposta;
}
- if (myusername)
- usersall = await User.getUsersTelegALL(rec.user.idapp, myusername);
- else
- usersall = await User.getUsersTelegALL(rec.user.idapp);
+ if (myusername) usersall = await User.getUsersTelegALL(rec.user.idapp, myusername);
+ else usersall = await User.getUsersTelegALL(rec.user.idapp);
let nummsgsent = 0;
@@ -3064,13 +3040,11 @@ class Telegram {
return;
}
- tools.writeEventsLog(
- this.getDestinStr(msg, destin, rec) + ':\n' + texttosend);
+ tools.writeEventsLog(this.getDestinStr(msg, destin, rec) + ':\n' + texttosend);
// let chiedisino = false;
for (const utente of usersall) {
-
let FormDaMostrare = null;
const lang = utente.lang;
@@ -3099,8 +3073,7 @@ class Telegram {
} else if (destin === Destin.RISPOSTA) {
invia = utente.username === rec.msg_username_risposta;
} else if (destin === Destin.NO_7_REQ) {
- invia = !await User.isUserQualified7(this.idapp,
- utente.username);
+ invia = !(await User.isUserQualified7(this.idapp, utente.username));
} else if (destin === Destin.MSG_TO_NAVE) {
// invia = !await Nave.findDonatoreByNave(this.idapp, rec.extraparam);
}
@@ -3113,8 +3086,7 @@ class Telegram {
if (cmd === RICEVI_EMAIL) {
preparatesto += utente.email + ', ';
} else if (cmd === NOME_COGNOME) {
- preparatesto += utente.name + ' ' + utente.surname + '(' +
- utente.username + ')' + '\n';
+ preparatesto += utente.name + ' ' + utente.surname + '(' + utente.username + ')' + '\n';
} else if (cmd === CONTA_SOLO) {
contanumutenti++;
// Niente
@@ -3124,14 +3096,11 @@ class Telegram {
FormDaMostrare = this.getInlineKeyboard(lang, [
{
text: Menu[lang].SI,
- callback_data: InlineCmd.VOGLIO_IMBARCARMI + tools.SEP +
- utente.username,
+ callback_data: InlineCmd.VOGLIO_IMBARCARMI + tools.SEP + utente.username,
},
{
text: Menu[lang].NO,
- callback_data: InlineCmd.NON_VOGLIO_IMBARCARMI +
- tools.SEP +
- utente.username,
+ callback_data: InlineCmd.NON_VOGLIO_IMBARCARMI + tools.SEP + utente.username,
},
]);
inviaveramente = true;
@@ -3144,11 +3113,12 @@ 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);
+ await this.sendMsg(
+ utente.profile.teleg_id,
+ '[' + rec.username_bo + ' ti scrive]:\n' + textdainviare,
+ MenuChat
+ );
} else {
-
// if (chiedisino) {
// this.ChiediSINO(msg, textdainviare);
// } else {
@@ -3159,14 +3129,10 @@ class Telegram {
// telegid = 12429864;
// }
if (rec.forwardMessage && rec.chatId && rec.messageId) {
-
// Inoltra il messaggio alla stessa chat o ad un'altra
this.bot.forwardMessage(rec.chatId, telegid, rec.messageId);
-
} else {
-
- await this.sendMsg(telegid, textdainviare, null,
- FormDaMostrare);
+ await this.sendMsg(telegid, textdainviare, null, FormDaMostrare);
}
// break;
@@ -3177,10 +3143,14 @@ 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);
+ if (nummsgsent % 100 === 0) {
+ myid = await this.sendMsg(
+ msg.chat.id,
+ nummsgsent + ' ' + getstr(this.getlang(msg), 'MSG_MSG_INCORSO'),
+ null,
+ null,
+ myid
+ );
await tools.snooze(100);
}
}
@@ -3191,8 +3161,7 @@ class Telegram {
let msgris = '';
if (cmd === CONTA_SOLO) {
- msgris = contanumutenti + ' ' +
- getstr(this.getlang(msg), 'MSG_MSG_TOSENT');
+ msgris = contanumutenti + ' ' + getstr(this.getlang(msg), 'MSG_MSG_TOSENT');
} else if (cmd === NOME_COGNOME) {
msgris = nummsgsent + ' ' + 'Utenti';
await this.sendMsg(msg.chat.id, msgris);
@@ -3203,21 +3172,20 @@ class Telegram {
msgris = preparatesto;
} else {
if (destin !== Destin.DOMANDA && destin !== Destin.RISPOSTA) {
- msgris = nummsgsent + ' ' +
- getstr(this.getlang(msg), 'MSG_MSG_SENT');
+ msgris = nummsgsent + ' ' + getstr(this.getlang(msg), 'MSG_MSG_SENT');
}
}
if (destin === Destin.A_UTENTE) {
const recdest = await this.sistemaRecDest(rec);
if (!!recdest) {
- await this.sendMsg(msg.chat.id,
- 'Conversazione Iniziata con ' + rec.msgall_username_specifico +
- ' !', MenuChat);
+ await this.sendMsg(
+ msg.chat.id,
+ 'Conversazione Iniziata con ' + rec.msgall_username_specifico + ' !',
+ MenuChat
+ );
} else {
- await this.sendMsg(msg.chat.id,
- 'Utente ' + rec.msgall_username_specifico +
- ' non presente sul BOT !');
+ await this.sendMsg(msg.chat.id, 'Utente ' + rec.msgall_username_specifico + ' non presente sul BOT !');
}
} else {
if (msgris) {
@@ -3234,15 +3202,19 @@ class Telegram {
}
selectMenuHelp(msg) {
- return ((this.isSelMenu(msg, msg.text, 'INFO')) ||
- (this.isSelMenu(msg, msg.text, 'ASSISTENZA')));
+ return this.isSelMenu(msg, msg.text, 'INFO') || this.isSelMenu(msg, msg.text, 'ASSISTENZA');
}
selectMenuLang(msg) {
- return ((msg.text === Menu.LANG) || (msg.text === Menu.LANG_EN) ||
- (msg.text === Menu.LANG_IT) || (msg.text === Menu.LANG_ES)
- || (msg.text === Menu.LANG_FR) || (msg.text === Menu.LANG_SI) ||
- (msg.text === Menu.LANG_PT));
+ return (
+ msg.text === Menu.LANG ||
+ msg.text === Menu.LANG_EN ||
+ msg.text === Menu.LANG_IT ||
+ msg.text === Menu.LANG_ES ||
+ msg.text === Menu.LANG_FR ||
+ msg.text === Menu.LANG_SI ||
+ msg.text === Menu.LANG_PT
+ );
}
async setInit(msg) {
@@ -3250,8 +3222,7 @@ class Telegram {
if (status === Status.NONE) {
await this.start(msg);
let status = this.getstatusInMemory(msg);
- if (status !== Status.VERIFIED)
- return Status.EXIT;
+ if (status !== Status.VERIFIED) return Status.EXIT;
} else {
await this.setUser(msg);
}
@@ -3261,11 +3232,10 @@ class Telegram {
getInvitanteByMsg(msg) {
try {
-
let mymsg = msg.text?.toString().trim().toLowerCase();
let invitante = '';
let regexpire = '';
- const sep = '-'
+ const sep = '-';
if (mymsg.startsWith('/start')) {
let myarrmsg = mymsg.split(' ');
if (myarrmsg.length > 0) {
@@ -3280,9 +3250,7 @@ class Telegram {
}
}
}
- } catch (e) {
-
- }
+ } catch (e) {}
return '';
}
@@ -3302,7 +3270,6 @@ class Telegram {
}
async receiveMsg(msg) {
-
// Check if Username Telegram Present
if (!this.checkIfUsernameTelegramSet(msg)) {
return;
@@ -3343,25 +3310,20 @@ class Telegram {
await this.sendMsgToAll(rec, msg, rec.msgtosent, rec.msgall_achi);
} else {
let msgout = rec.msgNo;
- if (!msgout)
- msgout = getstr(this.getlang(msg), 'MSG_OPERAZ_ANNULLATA');
+ if (!msgout) msgout = getstr(this.getlang(msg), 'MSG_OPERAZ_ANNULLATA');
this.sendMsg(msg.chat.id, msgout);
}
if (rec.msgall_achi === Destin.DOMANDA) {
if (rec.msg_toDest_yes) {
rec.msgall_achi = Destin.RISPOSTA;
if (this.isSelMenu(msg, msg.text, 'SI')) {
- const ris = await this.setCmdToUsername(rec,
- rec.msg_username_risposta, rec.cmd_to_set, true);
+ const ris = await this.setCmdToUsername(rec, rec.msg_username_risposta, rec.cmd_to_set, true);
if (ris) {
- await this.sendMsgToAll(rec, msg, rec.msg_toDest_yes,
- rec.msgall_achi);
+ await this.sendMsgToAll(rec, msg, rec.msg_toDest_yes, rec.msgall_achi);
}
} else if (this.isSelMenu(msg, msg.text, 'NO')) {
- const ris = await this.setCmdToUsername(rec,
- rec.msg_username_risposta, rec.cmd_to_set, false);
- await this.sendMsgToAll(rec, msg, rec.msg_toDest_no,
- rec.msgall_achi);
+ const ris = await this.setCmdToUsername(rec, rec.msg_username_risposta, rec.cmd_to_set, false);
+ await this.sendMsgToAll(rec, msg, rec.msg_toDest_no, rec.msgall_achi);
}
}
}
@@ -3386,28 +3348,21 @@ class Telegram {
domanda = rec.msgall_domanda;
} else {
if (cmd === CONTA_SOLO)
- domanda = 'Confermi di vedere a quante persone arriverebbe questo messaggio, a ' +
- achi + ' ?\n' + rec.msgtosent;
- else if (cmd === RICEVI_EMAIL)
- domanda = 'Confermi di vedere la lista delle email di ' + achi +
- '?';
- else if (cmd === NOME_COGNOME)
- domanda = 'Confermi di vedere la lista di persone ' + achi + '?';
+ domanda =
+ 'Confermi di vedere a quante persone arriverebbe questo messaggio, a ' + achi + ' ?\n' + rec.msgtosent;
+ else if (cmd === RICEVI_EMAIL) domanda = 'Confermi di vedere la lista delle email di ' + achi + '?';
+ else if (cmd === NOME_COGNOME) domanda = 'Confermi di vedere la lista di persone ' + achi + '?';
else {
if (rec.msgall_achi === Destin.A_UTENTE)
- domanda = 'Confermi d\'Iniziare una Chat messaggi con ' + achi +
- ' ?\n' + rec.msgtosent;
- else
- domanda = 'Confermi d\'Inviare questo messaggio a ' + achi +
- ' ?\n' + rec.msgtosent;
+ domanda = "Confermi d'Iniziare una Chat messaggi con " + achi + ' ?\n' + rec.msgtosent;
+ else domanda = "Confermi d'Inviare questo messaggio a " + achi + ' ?\n' + rec.msgtosent;
}
}
this.ChiediSINO(msg, domanda);
} else {
rec.msgall_status = StatusMSGALL.NONE;
- await
- this.msgScegliMenu(msg);
+ await this.msgScegliMenu(msg);
}
normale = false;
}
@@ -3422,7 +3377,6 @@ class Telegram {
}
async asktoRegistrationByLink(msg) {
-
let rec = this.getRecInMem(msg);
let visu = false;
@@ -3431,14 +3385,11 @@ class Telegram {
rec = await this.addUser(msg);
visu = true;
-
}
- if (rec && !rec.username_bo)
- visu = true;
+ if (rec && !rec.username_bo) visu = true;
if (visu) {
-
const status = this.getstatus(rec);
if (status === Status.SET_USERNAME_INVITANTE && rec.aportador_solidario) {
let linkreg = tools.getLinkRegByIdAppAndMsgStrutt(this.idapp, msg, rec);
@@ -3455,8 +3406,12 @@ class Telegram {
]);
// await this.sendMsg(msg.chat.id, getstr(this.getlang(msg), printf(txt.MSG_ASK_USERNAME_BO, tools.getHostByIdApp(this.idapp))));
- await this.sendMsg(msg.chat.id, getstr(this.getlang(msg), 'MSG_SIGNUP', tools.getNomeAppByIdApp(this.idapp)), null, keyb);
-
+ await this.sendMsg(
+ msg.chat.id,
+ getstr(this.getlang(msg), 'MSG_SIGNUP', tools.getNomeAppByIdApp(this.idapp)),
+ null,
+ keyb
+ );
} else if (status === Status.WAITFOR_USERNAME_INVITANTE) {
await this.askUsernameInvitante(msg, false);
}
@@ -3465,7 +3420,6 @@ class Telegram {
}
return true;
-
}
async setUser(msg) {
@@ -3484,14 +3438,11 @@ class Telegram {
if (user && rec) {
rec.user = user;
}
-
}
getchatid(msg) {
- if (msg.from.is_bot)
- return msg.chat.id;
- else
- return msg.from.id;
+ if (msg.from.is_bot) return msg.chat.id;
+ else return msg.from.id;
}
async alreadyExist(msg) {
@@ -3505,10 +3456,8 @@ class Telegram {
}
if (rec) {
rec.user = user;
- if (user)
- rec.username_bo = user.username;
- else
- rec.username_bo = '';
+ if (user) rec.username_bo = user.username;
+ else rec.username_bo = '';
}
} catch (e) {
console.error('Error: ', e);
@@ -3600,18 +3549,13 @@ class Telegram {
}
return rec;
-
}
async insertIntoDB(msg) {
-
return this.asktoRegistrationByLink(msg);
-
}
- menuisVisible(idapp, menu) {
-
- }
+ menuisVisible(idapp, menu) {}
async loadMenuFromDb(idapp, id) {
try {
@@ -3620,20 +3564,16 @@ class Telegram {
const recuser = this.getRecInMemById(id);
if (recuser) {
- if (!recuser.datemenu_updated)
- load = true;
+ if (!recuser.datemenu_updated) load = true;
}
if (check) {
if (recuser) {
- if (!(recuser.menuSaved[idapp]))
- load = true;
+ if (!recuser.menuSaved[idapp]) load = true;
- if (recuser.menuDb || recuser.pageChange)
- load = true;
+ if (recuser.menuDb || recuser.pageChange) load = true;
}
}
if (load) {
-
// Check if you are Admin
const user = await User.UserByIdTelegram(idapp, id);
let isAdmin = user ? user.profile.admin_telegram : false;
@@ -3650,23 +3590,20 @@ class Telegram {
for (const rec of recuser.menuDb) {
rec.active_mem = false;
- const visibilita = (tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLY_ADMIN, isAdmin)
- && tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLY_MANAGER, isManager)
- && tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLYIF_VERIFIED, isVerified))
- || rec.visibility === 0;
+ const visibilita =
+ (tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLY_ADMIN, isAdmin) &&
+ tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLY_MANAGER, isManager) &&
+ tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLYIF_VERIFIED, isVerified)) ||
+ rec.visibility === 0;
- if (rec.active && rec.page === recuser.pagenow
- && visibilita
- ) {
+ if (rec.active && rec.page === recuser.pagenow && visibilita) {
rec.active_mem = true;
if (true) {
lang = rec.lang;
- if (!arrlang[rec.lang])
- arrlang[rec.lang] = { menu: [] };
+ if (!arrlang[rec.lang]) arrlang[rec.lang] = { menu: [] };
if (riga !== rec.riga) {
- if (arrtemp.length > 0)
- arrlang[rec.lang].menu.push(arrtemp);
+ if (arrtemp.length > 0) arrlang[rec.lang].menu.push(arrtemp);
riga = rec.riga;
arrtemp = [];
@@ -3674,15 +3611,12 @@ class Telegram {
arrtemp.push(rec.label);
}
-
}
}
- if (arrtemp.length > 0)
- arrlang[lang].menu.push(arrtemp);
+ if (arrtemp.length > 0) arrlang[lang].menu.push(arrtemp);
- if (recuser)
- recuser.datemenu_updated = new Date();
+ if (recuser) recuser.datemenu_updated = new Date();
recuser.pageChange = false;
recuser.menuSaved[idapp] = arrlang;
@@ -3705,8 +3639,7 @@ class Telegram {
for (const rec of recuser.menuDb) {
if (rec.active_mem) {
- if (rec.idapp === idapp && rec.lang === lang &&
- rec.label?.toLowerCase() === testo) {
+ if (rec.idapp === idapp && rec.lang === lang && rec.label?.toLowerCase() === testo) {
return true;
}
}
@@ -3720,11 +3653,9 @@ class Telegram {
async getValueMenu(idapp, recuser, msg, testo, lang) {
try {
if (recuser) {
-
for (const recdb of recuser.menuDb) {
if (recdb.active_mem) {
- if (recdb.idapp === idapp && recdb.lang === lang &&
- recdb.label?.toLowerCase() === testo) {
+ if (recdb.idapp === idapp && recdb.lang === lang && recdb.label?.toLowerCase() === testo) {
if (recdb.type === shared_consts.BOTTYPE_TEXT) {
return recdb.value;
} else if (recdb.type === shared_consts.BOTTYPE_LINK) {
@@ -3745,7 +3676,6 @@ class Telegram {
} else if (recdb.type === shared_consts.BOTTYPE_MARKDOWN) {
return recdb.value;
}
-
}
}
}
@@ -3754,20 +3684,17 @@ class Telegram {
} catch (e) {
return '';
}
-
}
async getParseModeByMenu(idapp, recuser, msg, testo, lang) {
try {
let parse_mode = 'HTML';
if (recuser) {
-
for (const recdb of recuser.menuDb) {
if (recdb.active_mem) {
- if (recdb.idapp === idapp && recdb.lang === lang &&
- recdb.label?.toLowerCase() === testo) {
+ if (recdb.idapp === idapp && recdb.lang === lang && recdb.label?.toLowerCase() === testo) {
if (recdb.type === shared_consts.BOTTYPE_MARKDOWN) {
- return 'Markdown'
+ return 'Markdown';
} else {
return parse_mode;
}
@@ -3779,18 +3706,15 @@ class Telegram {
} catch (e) {
return '';
}
-
}
async getArrBottInlineByMenu(idapp, recuser, msg, testo, lang) {
try {
let arr_bott_inline = [];
if (recuser) {
-
for (const recdb of recuser.menuDb) {
if (recdb.active_mem) {
- if (recdb.idapp === idapp && recdb.lang === lang &&
- recdb.label?.toLowerCase() === testo) {
+ if (recdb.idapp === idapp && recdb.lang === lang && recdb.label?.toLowerCase() === testo) {
if (recdb.type === shared_consts.BOTTYPE_BOTTONI_INLINE) {
const jsonString = '[{"text": "primo", "callback_data": "1"}, {"text": "sec", "callback_data": "2"}]';
const jsonObject = JSON.parse(jsonString);
@@ -3807,7 +3731,6 @@ class Telegram {
console.error(e);
return [];
}
-
}
async getKeyboard(id, menu, lang) {
@@ -3834,8 +3757,8 @@ class Telegram {
modificaMsg(chatid, idmodif, text) {
const form = {
- 'chat_id': chatid,
- 'message_id': idmodif,
+ chat_id: chatid,
+ message_id: idmodif,
};
try {
@@ -3843,7 +3766,6 @@ class Telegram {
} catch (e) {
console.log('Err Telegram: ' + e);
}
-
}
// Soluzione 1: Converti PNG in JPG prima dell'invio
@@ -3858,18 +3780,15 @@ class Telegram {
if (metadata.format === 'png') {
console.log('Conversione PNG in JPG...');
- const jpgBuffer = await sharp(imageBuffer)
- .jpeg({ quality: 90 })
- .toBuffer();
+ const jpgBuffer = await sharp(imageBuffer).jpeg({ quality: 90 }).toBuffer();
return await this.bot.sendPhoto(chatId, jpgBuffer, opt);
}
// Se non è PNG, invia direttamente
return await this.bot.sendPhoto(chatId, imageBuffer, opt);
-
} catch (error) {
- console.error('Errore nell\'invio della foto:', error);
+ console.error("Errore nell'invio della foto:", error);
throw error;
}
}
@@ -3885,7 +3804,7 @@ class Telegram {
// Se fallisce, invia come documento
await this.bot.sendDocument(chatId, imageUrl, opt);
} catch (docError) {
- console.error('Anche l\'invio come documento è fallito:', docError);
+ console.error("Anche l'invio come documento è fallito:", docError);
throw docError;
}
}
@@ -3905,9 +3824,7 @@ class Telegram {
const response = await axios.get(imageUrl, { responseType: 'arraybuffer' });
const imageBuffer = Buffer.from(response.data);
- const jpgBuffer = await sharp(imageBuffer)
- .jpeg({ quality: 90 })
- .toBuffer();
+ const jpgBuffer = await sharp(imageBuffer).jpeg({ quality: 90 }).toBuffer();
try {
return await this.bot.sendPhoto(chatId, jpgBuffer, opt);
@@ -3917,7 +3834,6 @@ class Telegram {
// Ultima prova: invia come documento
return await this.bot.sendDocument(chatId, imageBuffer, opt);
-
} catch (error) {
console.error('Tutti i tentativi di invio sono falliti:', error);
return false;
@@ -3926,8 +3842,7 @@ class Telegram {
}
async _inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec, opt) {
- if (!text)
- return 0;
+ if (!text) return 0;
if (process.env.LOCALE === '1') {
if (id !== ADMIN_IDTELEGRAM_TEST) {
@@ -3981,7 +3896,6 @@ class Telegram {
// text = text.replace(/<\/div>/g, '');
text = text.replace(/ /g, ' ');
-
if (!form) {
form = {
parse_mode: opt && opt.parse_mode ? opt.parse_mode : 'HTML',
@@ -3990,12 +3904,11 @@ class Telegram {
reply_markup: {
resize_keyboard: true,
keyboard: await this.getKeyboard(id, menu, mylang),
- keyboard_inline: (opt && opt.keyboard_inline) ? opt.keyboard_inline : undefined,
+ keyboard_inline: opt && opt.keyboard_inline ? opt.keyboard_inline : undefined,
},
};
}
-
let inviato = false;
let risSendPhoto = null;
@@ -4005,21 +3918,19 @@ class Telegram {
opt.img = 'https://riso.app/upload/profile/paoloar77/mybachecas/Fermentazione-Ruello-sito.png';
}
opt.img = tools.fixUrl(opt.img, opt.idapp);
- console.log('opt.img', opt.img)
- risSendPhoto = await this.sendImageToTelegram(id, opt.img, { caption: text, ...form })
- .catch((e) => {
- let blocked = false;
- if ((e.message.indexOf('Forbidden') > 0) ||
- (e.message.indexOf('chat not found') > 0)) {
- blocked = true;
- }
- if (!blocked) {
- console.error(e.message.substring(0, 200));
- }
- if (blocked) {
- User.SetTelegramWasBlocked(this.idapp, id);
- }
- });
+ console.log('opt.img', opt.img);
+ risSendPhoto = await this.sendImageToTelegram(id, opt.img, { caption: text, ...form }).catch((e) => {
+ let blocked = false;
+ if (e.message.indexOf('Forbidden') > 0 || e.message.indexOf('chat not found') > 0) {
+ blocked = true;
+ }
+ if (!blocked) {
+ console.error(e.message.substring(0, 200));
+ }
+ if (blocked) {
+ User.SetTelegramWasBlocked(this.idapp, id);
+ }
+ });
}
if (risSendPhoto) {
@@ -4028,8 +3939,7 @@ class Telegram {
if (!inviato) {
return this.bot.sendMessage(id, text, form).catch((e) => {
let blocked = false;
- if ((e.message.indexOf('Forbidden') > 0) ||
- (e.message.indexOf('chat not found') > 0)) {
+ if (e.message.indexOf('Forbidden') > 0 || e.message.indexOf('chat not found') > 0) {
blocked = true;
}
if (!blocked) {
@@ -4043,13 +3953,12 @@ class Telegram {
});
}
- return risSendPhoto
-
+ return risSendPhoto;
} catch (e) {
if (e.message.indexOf('OK') === 0) {
- console.log("INFO INVIAMSG:", e.message);
+ console.log('INFO INVIAMSG:', e.message);
} else {
- console.error("ERROR INVIAMSG:", e.message, 'text', text.substring(0, 100));
+ console.error('ERROR INVIAMSG:', e.message, 'text', text.substring(0, 100));
}
return 0;
}
@@ -4064,9 +3973,7 @@ class Telegram {
if (telegid > 0) {
await this.sistemaRecDest(rec, msg);
// await this.sendMsg(msg.chat.id, '[Msg inviato a ' + username + ']: ');
- await this.sendMsg(telegid,
- Menu.CHAT_PERSONALE + '[' + rec.username_bo + ' ti scrive]:\n' +
- text, MenuChat);
+ await this.sendMsg(telegid, Menu.CHAT_PERSONALE + '[' + rec.username_bo + ' ti scrive]:\n' + text, MenuChat);
} else {
await this.sendMsg(msg.chat.id, 'Username non valido');
rec.msgall_username_specifico = '';
@@ -4075,35 +3982,26 @@ class Telegram {
}
async sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec, img = '', opzioni = null) {
-
- if (!id || !text)
- return false;
+ if (!id || !text) return false;
try {
-
if (text.length > 4090) {
let text1 = text.slice(0, 4090);
let text2 = text.slice(4090, text.length);
- await this._inviaMsg(id, text1, form, menu, msg_id, chat_id,
- ripr_menuPrec, { img, ...opzioni });
- return await this._inviaMsg(id, text2, form, menu, msg_id, chat_id,
- ripr_menuPrec, { img, ...opzioni });
+ await this._inviaMsg(id, text1, form, menu, msg_id, chat_id, ripr_menuPrec, { img, ...opzioni });
+ return await this._inviaMsg(id, text2, form, menu, msg_id, chat_id, ripr_menuPrec, { img, ...opzioni });
} else {
- return await this._inviaMsg(id, text, form, menu, msg_id, chat_id,
- ripr_menuPrec, { img, ...opzioni });
+ return await this._inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec, { img, ...opzioni });
}
} catch (e) {
console.error('Error sendMsg', e);
return null;
}
-
}
async sendMsgLog(id, text, menu, form, msg_id, chat_id, ripr_menuPrec) {
-
const rec = this.getRecInMemById(id);
let username = rec ? rec.username_bo : '';
if (!username) {
-
}
console.log('Msg inviato a ', username, '(', id, ')', text);
@@ -4115,8 +4013,7 @@ class Telegram {
try {
mymenuout = mymenu[lang].menu;
} catch (e) {
- if (!!mymenu['it'])
- mymenuout = mymenu['it'].menu;
+ if (!!mymenu['it']) mymenuout = mymenu['it'].menu;
}
return mymenuout;
@@ -4141,7 +4038,7 @@ class Telegram {
async setPhotoProfile(user, telegid, showmsg = true) {
try {
- console.log('setPhotoProfile', user ? user.username : '')
+ console.log('setPhotoProfile', user ? user.username : '');
if (user) {
const idapp = this.idapp;
const bot = this.bot;
@@ -4149,22 +4046,19 @@ class Telegram {
const lang = user.lang;
const token = this.token;
const editprofile = tools.getHostByIdApp(idapp, true) + '/editprofile';
- let myfileprofile = tools.getdirByIdApp(idapp, true) +
- server_constants.DIR_UPLOAD + '/profile/' + username + '/';
+ let myfileprofile =
+ tools.getdirByIdApp(idapp, true) + server_constants.DIR_UPLOAD + '/profile/' + username + '/';
let user_profile = bot.getUserProfilePhotos(telegid);
- user_profile.then( function (res) {
+ user_profile.then(function (res) {
if (res.total_count === 0) {
// Non ho l'accesso oppure sono davvero senza foto !
-
}
if (res.photos[0]) {
var file_id = res.photos[0][2].file_id;
var file = bot.getFile(file_id);
file.then(async function (result) {
-
const file_path = result.file_path;
- const photo_url = 'https://api.telegram.org/file/bot' + token +
- '/' + file_path;
+ const photo_url = 'https://api.telegram.org/file/bot' + token + '/' + file_path;
// console.log('1) photo_url', photo_url);
let filename = tools.extractFileName(photo_url);
myfileprofile += filename;
@@ -4173,35 +4067,35 @@ class Telegram {
await tools.mkdirpath(pathfile);
// console.log('2) myfileprofile', pathfile);
- return tools.downloadImage(photo_url, myfileprofile).
- then((ris) => {
-
+ return tools
+ .downloadImage(photo_url, myfileprofile)
+ .then((ris) => {
try {
- let resized_img_small = tools.extractFilePath(myfileprofile) + '/' + server_constants.PREFIX_IMG_SMALL + filename;
+ 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);
+ 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));
- }
- });
+ 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) => {
+ })
+ .catch((err) => {
console.error('Error setPhotoProfile', err);
});
-
});
}
});
@@ -4243,25 +4137,19 @@ class Telegram {
}
}
- if (arrriga1.length > 0)
- mykeyb.reply_markup.inline_keyboard.push(arrriga1);
- if (arrriga2.length > 0)
- mykeyb.reply_markup.inline_keyboard.push(arrriga2);
- if (arrriga3.length > 0)
- mykeyb.reply_markup.inline_keyboard.push(arrriga3);
+ if (arrriga1.length > 0) mykeyb.reply_markup.inline_keyboard.push(arrriga1);
+ if (arrriga2.length > 0) mykeyb.reply_markup.inline_keyboard.push(arrriga2);
+ if (arrriga3.length > 0) mykeyb.reply_markup.inline_keyboard.push(arrriga3);
return mykeyb;
}
async ChiediSINO(msg, domanda) {
-
const lang = this.getlang(msg);
if (msg.forwardMessage && msg.chatId && msg.messageId) {
-
// Inoltra il messaggio alla stessa chat o ad un'altra
this.bot.forwardMessage(msg.chatId, msg.chatId, msg.messageId);
-
} else {
this._inviaMsg(msg.from.id, domanda, {
disable_web_page_preview: true,
@@ -4272,7 +4160,6 @@ class Telegram {
},
});
}
-
}
async ScegliLang(msg, lang) {
@@ -4296,8 +4183,7 @@ class Telegram {
disable_web_page_preview: true,
reply_markup: {
resize_keyboard: true,
- keyboard: await this.getKeyboard(msg.from.id, undefined,
- this.getlang(msg)),
+ keyboard: await this.getKeyboard(msg.from.id, undefined, this.getlang(msg)),
},
});
}
@@ -4307,10 +4193,8 @@ const arrTelegram = [];
function getclTelegBytoken(token) {
const rec = arrTelegram.find((rec) => rec.cl.token === token);
- if (!!rec)
- return rec.cl;
- else
- return null;
+ if (!!rec) return rec.cl;
+ else return null;
}
// Funzione per ottenere il nome del gruppo
@@ -4319,7 +4203,7 @@ async function getGroupName(bot, groupId) {
const chat = await bot.getChat(groupId);
return chat.title;
} catch (error) {
- console.error('Errore durante l\'ottenimento del nome del gruppo:', error);
+ console.error("Errore durante l'ottenimento del nome del gruppo:", error);
return null;
}
}
@@ -4328,15 +4212,12 @@ function getclTelegByidapp(idapp) {
// ****************************
if (appTelegramFinti.includes(idapp)) {
const ind = appTelegramFinti.indexOf(idapp);
- if (ind >= 0)
- idapp = appTelegramDest[ind]; // Invia
+ if (ind >= 0) idapp = appTelegramDest[ind]; // Invia
}
const rec = arrTelegram.find((rec) => rec.idapp === idapp);
- if (!!rec)
- return rec.cl;
- else
- return null;
+ if (!!rec) return rec.cl;
+ else return null;
}
//if (!tools.testing() || true) {
@@ -4345,375 +4226,399 @@ if (true) {
var internetAvailable = require('internet-available');
- internetAvailable().then(() => {
- // ..
+ internetAvailable()
+ .then(() => {
+ // ..
- if (appTeleg_BotOnGroup.length > 0) {
- console.log('TELEGRAM BOT GROUP .... ');
+ if (appTeleg_BotOnGroup.length > 0) {
+ console.log('TELEGRAM BOT GROUP .... ');
- for (const idapp of appTeleg_BotOnGroup) {
+ for (const idapp of appTeleg_BotOnGroup) {
+ const token = tools.getTelegramKeyByIdApp(idapp);
+ const nomebot = tools.getTelegramBotNameByIdApp(idapp);
- const token = tools.getTelegramKeyByIdApp(idapp);
- const nomebot = tools.getTelegramBotNameByIdApp(idapp);
+ if (token && nomebot) {
+ const bot = new TelegramBot(token, { polling: true });
- if (token && nomebot) {
- const bot = new TelegramBot(token, { polling: true });
-
- // Gestisce il comando /start
- bot.onText(/\/start/, (msg) => {
- console.log('START BOT GROUP ... ');
- /*
+ // Gestisce il comando /start
+ bot.onText(/\/start/, (msg) => {
+ console.log('START BOT GROUP ... ');
+ /*
const chatId = msg.chat.id;
const message = 'Benvenuto! Usa il comando /request per inviare una richiesta di accesso al gruppo.';
bot.sendMessage(chatId, message);
*/
- });
+ });
- bot.onText(/\/request/, (msg) => {
- const chatId = msg.chat.id;
- const fromId = msg.from.id;
- const fromUsername = msg.from.username;
+ bot.onText(/\/request/, (msg) => {
+ const chatId = msg.chat.id;
+ const fromId = msg.from.id;
+ const fromUsername = msg.from.username;
- const groupId = chatId;
+ const groupId = chatId;
- if (chatId == groupId) {
- const message = `Richiesta di accesso al gruppo da parte di ${msg.from.first_name} ${msg.from.last_name} (@${fromUsername})`;
- bot.sendMessage(groupId, message);
- } else {
- console.log('Comando /request ricevuto in una chat privata.');
- }
- });
+ if (chatId == groupId) {
+ const message = `Richiesta di accesso al gruppo da parte di ${msg.from.first_name} ${msg.from.last_name} (@${fromUsername})`;
+ bot.sendMessage(groupId, message);
+ } else {
+ console.log('Comando /request ricevuto in una chat privata.');
+ }
+ });
- bot.on('text', (msg) => {
- console.log('TEXT...');
- const chatId = msg.chat.id;
- const userName = msg.from.username || msg.from.first_name;
- const userId = msg.from.id;
- });
+ bot.on('text', (msg) => {
+ console.log('TEXT...');
+ const chatId = msg.chat.id;
+ const userName = msg.from.username || msg.from.first_name;
+ const userId = msg.from.id;
+ });
- bot.on('new_chat_members', async (msg) => {
- const chatId = msg.chat.id;
- const newMembers = msg.new_chat_members;
+ bot.on('new_chat_members', async (msg) => {
+ const chatId = msg.chat.id;
+ const newMembers = msg.new_chat_members;
- const groupId = chatId;
+ const groupId = chatId;
- const nomegruppo = await getGroupName(bot, groupId);
+ const nomegruppo = await getGroupName(bot, groupId);
- // Ottiene la lista degli amministratori del gruppo
- const admins = await bot.getChatAdministrators(chatId);
+ // Ottiene la lista degli amministratori del gruppo
+ const admins = await bot.getChatAdministrators(chatId);
- // Trova l'ID dell'amministratore del gruppo
- const adminId = admins.find(admin => admin.status === 'administrator').user.id;
+ // Trova l'ID dell'amministratore del gruppo
+ const adminId = admins.find((admin) => admin.status === 'administrator').user.id;
- // Verifica se il nuovo membro è stato aggiunto al gruppo
- if (chatId == groupId) {
- newMembers.forEach(async (member) => {
+ // Verifica se il nuovo membro è stato aggiunto al gruppo
+ if (chatId == groupId) {
+ newMembers.forEach(async (member) => {
+ //const message = `🔑 Nuova Richiesta di accesso al gruppo ${nomegruppo} da parte di ${member.username} (` + member.first_name + ' ' + member.last_name + ')';
+ const message = `Benvenuto/a ${member.first_name} (${member.username}) sul gruppo "${nomegruppo}" !`;
+ bot.sendMessage(adminId, message);
- //const message = `🔑 Nuova Richiesta di accesso al gruppo ${nomegruppo} da parte di ${member.username} (` + member.first_name + ' ' + member.last_name + ')';
- const message = `Benvenuto/a ${member.first_name} (${member.username}) sul gruppo "${nomegruppo}" !`;
- bot.sendMessage(adminId, message);
-
- // bot.sendMessage(groupId, message);
- });
- }
- });
-
- }
- }
- }
-
- console.log('TELEGRAM STARTING.... ', process.env.NODE_ENV);
-
- for (const idapp of arrTeleg) {
-
- try {
- const token = tools.getTelegramKeyByIdApp(idapp);
- const nomebot = tools.getTelegramBotNameByIdApp(idapp);
-
- // console.log('idapp', idapp, 'token', token);
-
- if (!!token) {
- console.log('-------------------------------------');
- console.log('*** STARTING BOT ' + nomebot);
- console.log('-------------------------------------');
- const bot = new TelegramBot(token, { polling: true });
-
- if (url === '0') {
- const ngrok = require('ngrok');
- ngrok.connect(port, function onConnect(error, u) {
- if (error) throw error;
- url = u;
- console.log(`Game tunneled at ${url}`);
+ // bot.sendMessage(groupId, message);
+ });
+ }
});
}
+ }
+ }
- arrTelegram.push({ idapp, cl: new Telegram(idapp, bot) });
+ console.log('TELEGRAM STARTING.... ', process.env.NODE_ENV);
- bot.onText(/\/start/, (msg) => {
- console.log('*** BOT PARTITO CORRETTAMENTE !!! (Start Cmd)');
- const myclTelegram = getclTelegBytoken(bot.token);
+ for (const idapp of arrTeleg) {
+ try {
+ const token = tools.getTelegramKeyByIdApp(idapp);
+ const nomebot = tools.getTelegramBotNameByIdApp(idapp);
- myclTelegram.start(msg);
+ // console.log('idapp', idapp, 'token', token);
- });
+ if (!!token) {
+ console.log('-------------------------------------');
+ console.log('*** STARTING BOT ' + nomebot);
+ console.log('-------------------------------------');
+ const bot = new TelegramBot(token, { polling: true });
- // Matches "/echo [whatever]"
- bot.onText(/\/echo (.+)/, (msg, match) => {
- // 'msg' is the received Message from Telegram
- // 'match' is the result of executing the regexp above on the text content
- // of the message
+ if (url === '0') {
+ const ngrok = require('ngrok');
+ ngrok.connect(port, function onConnect(error, u) {
+ if (error) throw error;
+ url = u;
+ console.log(`Game tunneled at ${url}`);
+ });
+ }
- const chatId = msg.chat.id;
- const resp = match[1]; // the captured "whatever"
+ arrTelegram.push({ idapp, cl: new Telegram(idapp, bot) });
- // send back the matched "whatever" to the chat
- bot.sendMessage(chatId, resp);
- });
-
- // Listen for any kind of message. There are different kinds of
- // messages.
- bot.on('message', async (msg) => {
-
- const myclTelegram = getclTelegBytoken(bot.token);
-
- // const chatId = msg.chat.id;
- myclTelegram.receiveMsg(msg);
- });
-
- // Handle callback queries
- bot.on('callback_query', async (callbackQuery) => {
- // console.log('callback_query', callbackQuery);
-
- try {
+ bot.onText(/\/start/, (msg) => {
+ console.log('*** BOT PARTITO CORRETTAMENTE !!! (Start Cmd)');
const myclTelegram = getclTelegBytoken(bot.token);
- let dataarr = [];
- let data = {
- action: '',
- username: '',
- userDest: '',
- groupId: 0,
- circuitId: '',
- groupname: '',
- };
+ myclTelegram.start(msg);
+ });
- const datastr = callbackQuery.data;
- if (!!datastr) {
- dataarr = datastr.split(tools.SEP);
- if (!!dataarr) {
- data = {
- action: dataarr[0],
- username: dataarr[1] ? dataarr[1] : '',
- userDest: dataarr[2] ? dataarr[2] : '',
- groupId: dataarr[3] ? parseInt(dataarr[3]) : '',
- circuitId: dataarr[4] ? dataarr[4] : '',
- groupname: dataarr[5] ? dataarr[5] : '',
- };
+ // Matches "/echo [whatever]"
+ bot.onText(/\/echo (.+)/, (msg, match) => {
+ // 'msg' is the received Message from Telegram
+ // 'match' is the result of executing the regexp above on the text content
+ // of the message
+
+ const chatId = msg.chat.id;
+ const resp = match[1]; // the captured "whatever"
+
+ // send back the matched "whatever" to the chat
+ bot.sendMessage(chatId, resp);
+ });
+
+ // Listen for any kind of message. There are different kinds of
+ // messages.
+ bot.on('message', async (msg) => {
+ const myclTelegram = getclTelegBytoken(bot.token);
+
+ // const chatId = msg.chat.id;
+ myclTelegram.receiveMsg(msg);
+ });
+
+ // Handle callback queries
+ bot.on('callback_query', async (callbackQuery) => {
+ // console.log('callback_query', callbackQuery);
+
+ // RISPOSTE ALLE CALLBACK (Bottoni)
+
+ let testo_notifica_di_risposta = ''
+
+ try {
+ const myclTelegram = getclTelegBytoken(bot.token);
+
+ let dataarr = [];
+ let data = {
+ action: '',
+ username: '',
+ userDest: '',
+ groupId: 0,
+ circuitId: '',
+ groupname: '',
+ };
+
+ const datastr = callbackQuery.data;
+ if (!!datastr) {
+ dataarr = datastr.split(tools.SEP);
+ if (!!dataarr) {
+ data = {
+ action: dataarr[0],
+ username: dataarr[1] ? dataarr[1] : '',
+ userDest: dataarr[2] ? dataarr[2] : '',
+ groupId: dataarr[3] ? parseInt(dataarr[3]) : '',
+ circuitId: dataarr[4] ? dataarr[4] : '',
+ groupname: dataarr[5] ? dataarr[5] : '',
+ };
+ }
}
- }
- const msg = callbackQuery.message;
- const opts = {
- chat_id: msg.chat.id,
- message_id: msg.message_id,
- };
+ const msg = callbackQuery.message;
+ const opts = {
+ chat_id: msg.chat.id,
+ message_id: msg.message_id,
+ };
- const status = await myclTelegram.setInit(msg);
+ const status = await myclTelegram.setInit(msg);
- const rec = myclTelegram.getRecInMem(msg);
+ const rec = myclTelegram.getRecInMem(msg);
- const username_action = rec.user ? rec.user.username : '';
+ const username_action = rec.user ? rec.user.username : '';
- data.username = await User.getRealUsernameByUsername(idapp, data.username);
- data.userDest = await User.getRealUsernameByUsername(idapp, data.userDest);
+ data.username = await User.getRealUsernameByUsername(idapp, data.username);
+ data.userDest = await User.getRealUsernameByUsername(idapp, data.userDest);
- const user = await User.getUserShortDataByUsername(idapp, data.username);
- const userDest = data.userDest ? await User.getUserShortDataByUsername(idapp, data.userDest) : null;
+ const user = await User.getUserShortDataByUsername(idapp, data.username);
+ const userDest = data.userDest ? await User.getUserShortDataByUsername(idapp, data.userDest) : null;
- let group = null;
- let circuit = null;
- if (data.groupId) {
- group = await MyGroup.findOne({ idapp, _id: data.groupId }).lean();
- }
- if (data.circuitId) {
- circuit = await Circuit.findOne({ idapp, _id: data.circuitId }).lean();
- }
+ let group = null;
+ let circuit = null;
+ if (data.groupId) {
+ group = await MyGroup.findOne({ idapp, _id: data.groupId }).lean();
+ }
+ if (data.circuitId) {
+ circuit = await Circuit.findOne({ idapp, _id: data.circuitId }).lean();
+ }
- let cmd = 0;
+ let cmd = 0;
- if (!!rec) {
- if (!!user) {
- if (data.action === InlineCmd.VOGLIO_IMBARCARMI) {
- // Controlla se è qualificato!
- const mydata = tools.AddDate(user.date_reg, 7);
+ if (!!rec) {
+ if (!!user) {
+ if (data.action === InlineCmd.VOGLIO_IMBARCARMI) {
+ // Controlla se è qualificato!
+ const mydata = tools.AddDate(user.date_reg, 7);
- // bot.editMessageText(tools.gettranslate('ADDED_TOLISTAINGRESSO', user.lang), opts);
+ // bot.editMessageText(tools.gettranslate('ADDED_TOLISTAINGRESSO', user.lang), opts);
+ } else if (data.action === InlineCmd.NON_VOGLIO_IMBARCARMI) {
+ await User.NonVoglioImbarcarmi(user.idapp, user.username);
- } else if (data.action === InlineCmd.NON_VOGLIO_IMBARCARMI) {
- await User.NonVoglioImbarcarmi(user.idapp, user.username);
+ const msgadd =
+ '[' +
+ user.username +
+ '] ' +
+ user.name +
+ ' ' +
+ user.surname +
+ ' ha risposto che NON VUOLE IMBARCARSI !';
- const msgadd = '[' + user.username + '] ' + user.name + ' ' +
- user.surname + ' ha risposto che NON VUOLE IMBARCARSI !';
-
- await local_sendMsgTelegramToTheManagers(user.idapp, msgadd,
- msg, false); // Anche a STAFF
- } else if (data.action ===
- InlineZoomConferma.CONFERMA_ZOOM_PRESENZA) {
-
- await User.setZoomPresenza(user.idapp, user._id, true);
-
- } else if (data.action ===
- InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA) {
-
- await User.setZoomPresenza(user.idapp, user._id, false);
-
- } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.REGISTRATION) {
- const changed = await myclTelegram.setCmdToUsername(rec,
- data.username,
- Cmd.VALIDATE_REGISTRATION, true);
-
- if (changed) {
- const req = tools.getReqByPar(user.idapp, username_action);
-
- nomeapp = tools.getNomeAppByIdApp(user.idapp);
- // await User.setFriendsCmd(req, user.idapp, data.username, userDest.username, shared_consts.FRIENDSCMD.SETFRIEND, null, true);
-
- await User.setaportador_solidario(user.idapp, data.username, userDest.username);
-
- const msgOrig = printf(getstr(userDest.lang, 'MSG_APORTADOR_DEST_CONFIRMED', nomeapp), `${userDest.username}`,
- tools.getHostByIdApp(user.idapp));
- const msgDest = printf(getstr(user.lang, 'MSG_APORTADOR_CONFIRMED'), `${user.username}`, `${userDest.username}`);
-
- await local_sendMsgTelegram(user.idapp, data.username, msgOrig);
- await local_sendMsgTelegram(user.idapp, data.userDest, msgDest);
- // Invia questo msg anche all'Admin
- await local_sendMsgTelegramToTheAdmin(user.idapp, msgDest, msg, data.userDest);
- }
-
- } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.REGISTRATION) {
- if (userDest.username === user.aportador_solidario) {
- const changed = await myclTelegram.setCmdToUsername(rec, data.username,
- Cmd.VALIDATE_REGISTRATION, false);
+ await local_sendMsgTelegramToTheManagers(user.idapp, msgadd, msg, false); // Anche a STAFF
+ } else if (data.action === InlineZoomConferma.CONFERMA_ZOOM_PRESENZA) {
+ await User.setZoomPresenza(user.idapp, user._id, true);
+ } else if (data.action === InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA) {
+ await User.setZoomPresenza(user.idapp, user._id, false);
+ } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.REGISTRATION) {
+ const changed = await myclTelegram.setCmdToUsername(
+ rec,
+ data.username,
+ Cmd.VALIDATE_REGISTRATION,
+ true
+ );
if (changed) {
- const nomeDest = tools.getNomeCognomeEUserNameByUser(userDest);
- const nomestr = tools.getNomeCognomeEUserNameByUser(user);
+ const req = tools.getReqByPar(user.idapp, username_action);
- const msgOrig = printf(getstr(userDest.lang, 'MSG_APORTADOR_DEST_NOT_CONFIRMED', nomeDest));
- const msgDest = printf(getstr(user.lang, 'MSG_APORTADOR_NOT_CONFIRMED'), nomestr);
+ nomeapp = tools.getNomeAppByIdApp(user.idapp);
+ // await User.setFriendsCmd(req, user.idapp, data.username, userDest.username, shared_consts.FRIENDSCMD.SETFRIEND, null, true);
+
+ await User.setaportador_solidario(user.idapp, data.username, userDest.username);
+
+ const msgOrig = printf(
+ getstr(userDest.lang, 'MSG_APORTADOR_DEST_CONFIRMED', nomeapp),
+ `${userDest.username}`,
+ tools.getHostByIdApp(user.idapp)
+ );
+ const msgDest = printf(
+ getstr(user.lang, 'MSG_APORTADOR_CONFIRMED'),
+ `${user.username}`,
+ `${userDest.username}`
+ );
await local_sendMsgTelegram(user.idapp, data.username, msgOrig);
await local_sendMsgTelegram(user.idapp, data.userDest, msgDest);
+ // Invia questo msg anche all'Admin
+ await local_sendMsgTelegramToTheAdmin(user.idapp, msgDest, msg, data.userDest);
}
- }
- } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_GRUPPO) {
+ } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.REGISTRATION) {
+ if (userDest.username === user.aportador_solidario) {
+ const changed = await myclTelegram.setCmdToUsername(
+ rec,
+ data.username,
+ Cmd.VALIDATE_REGISTRATION,
+ false
+ );
- if (group) {
- cmd = shared_consts.GROUPSCMD.SETGROUP;
- const foundIfAlreadyGroup = await User.ifAlreadyInGroup(user.idapp, data.username, group.groupname);
+ if (changed) {
+ const nomeDest = tools.getNomeCognomeEUserNameByUser(userDest);
+ const nomestr = tools.getNomeCognomeEUserNameByUser(user);
- if (!foundIfAlreadyGroup) {
- // Aggiungilo nel Gruppo
- await User.setGroupsCmd(user.idapp, data.username, group.groupname, cmd, 0, username_action);
+ const msgOrig = printf(getstr(userDest.lang, 'MSG_APORTADOR_DEST_NOT_CONFIRMED', nomeDest));
+ const msgDest = printf(getstr(user.lang, 'MSG_APORTADOR_NOT_CONFIRMED'), nomestr);
+
+ await local_sendMsgTelegram(user.idapp, data.username, msgOrig);
+ await local_sendMsgTelegram(user.idapp, data.userDest, msgDest);
+ }
}
+ } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_GRUPPO) {
+ if (group) {
+ cmd = shared_consts.GROUPSCMD.SETGROUP;
+ const foundIfAlreadyGroup = await User.ifAlreadyInGroup(
+ user.idapp,
+ data.username,
+ group.groupname
+ );
- }
- } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_GRUPPO) {
-
- if (group) {
- cmd = shared_consts.GROUPSCMD.REFUSE_REQ_GROUP;
- const foundIfAlreadyGroup = await User.ifAlreadyInGroup(user.idapp, data.username, group.groupname);
-
- if (foundIfAlreadyGroup) {
- // Rimuovilo nel Gruppo
- await User.setGroupsCmd(user.idapp, data.username, group.groupname, cmd, 0, username_action);
+ if (!foundIfAlreadyGroup) {
+ // Aggiungilo nel Gruppo
+ await User.setGroupsCmd(user.idapp, data.username, group.groupname, cmd, 0, username_action);
+ }
}
+ } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_GRUPPO) {
+ if (group) {
+ cmd = shared_consts.GROUPSCMD.REFUSE_REQ_GROUP;
+ const foundIfAlreadyGroup = await User.ifAlreadyInGroup(
+ user.idapp,
+ data.username,
+ group.groupname
+ );
- }
- } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_FIDO) {
-
- if (circuit) {
- // Abiglitagli il Fido
- cmd = shared_consts.CIRCUITCMD.SETFIDO;
- await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { groupname: data.groupname });
- }
- } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
-
- console.log(' CLICK per Aggiungere ', data.username, 'nel circuito', circuit?.name);
- if (circuit) {
- // Aggiungilo nel Circuito
- cmd = shared_consts.CIRCUITCMD.SET;
- await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { groupname: data.groupname });
- }
- } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
-
- if (circuit) {
- cmd = shared_consts.CIRCUITCMD.REFUSE_REQ;
- let foundIfAlreadyCircuit = false;
- if (data.groupname) {
- foundIfAlreadyCircuit = await MyGroup.ifCircuitAlreadyInGroup(user.idapp, data.groupname, circuit.name);
- } else {
- foundIfAlreadyCircuit = await User.ifAlreadyInCircuit(user.idapp, data.username, circuit.name);
+ if (foundIfAlreadyGroup) {
+ // Rimuovilo nel Gruppo
+ await User.setGroupsCmd(user.idapp, data.username, group.groupname, cmd, 0, username_action);
+ }
}
-
- if (foundIfAlreadyCircuit) {
- // Rimuovilo nel Circuito
- await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { groupname: data.groupname });
+ } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_FIDO) {
+ if (circuit) {
+ // Abiglitagli il Fido
+ cmd = shared_consts.CIRCUITCMD.SETFIDO;
+ await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, {
+ groupname: data.groupname,
+ });
}
+ } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
+ console.log(' CLICK per Aggiungere ', data.username, 'nel circuito', circuit?.name);
+ if (circuit) {
+ // Aggiungilo nel Circuito
+ cmd = shared_consts.CIRCUITCMD.SET;
+ await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, {
+ groupname: data.groupname,
+ });
+ }
+ } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
+ if (circuit) {
+ cmd = shared_consts.CIRCUITCMD.REFUSE_REQ;
+ let foundIfAlreadyCircuit = false;
+ if (data.groupname) {
+ foundIfAlreadyCircuit = await MyGroup.ifCircuitAlreadyInGroup(
+ user.idapp,
+ data.groupname,
+ circuit.name
+ );
+ } else {
+ foundIfAlreadyCircuit = await User.ifAlreadyInCircuit(
+ user.idapp,
+ data.username,
+ circuit.name
+ );
+ }
- }
- } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_AMICIZIA) {
+ if (foundIfAlreadyCircuit) {
+ // Rimuovilo nel Circuito
+ await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, {
+ groupname: data.groupname,
+ });
+ }
+ }
+ } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_AMICIZIA) {
+ if (userDest) {
+ cmd = shared_consts.FRIENDSCMD.SETFRIEND;
+ const foundIfAlreadyFriend = await User.isMyFriend(user.idapp, data.username, data.userDest);
- if (userDest) {
- cmd = shared_consts.FRIENDSCMD.SETFRIEND;
- const foundIfAlreadyFriend = await User.isMyFriend(user.idapp, data.username, data.userDest);
-
- if (!foundIfAlreadyFriend) {
- // Aggiungilo nelle Amicizie
+ if (!foundIfAlreadyFriend) {
+ // Aggiungilo nelle Amicizie
+ const req = tools.getReqByPar(user.idapp, username_action);
+ const ris = await User.setFriendsCmd(req, user.idapp, data.username, data.userDest, cmd);
+ }
+ }
+ } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_AMICIZIA) {
+ if (userDest) {
+ cmd = shared_consts.FRIENDSCMD.REMOVE_FROM_MYFRIENDS;
+ // Rimuovilo nelle Amicizie
const req = tools.getReqByPar(user.idapp, username_action);
const ris = await User.setFriendsCmd(req, user.idapp, data.username, data.userDest, cmd);
+ if (ris) {
+ const msgDest = printf(
+ getstr(user.lang, 'MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED'),
+ data.username
+ );
+ await local_sendMsgTelegram(user.idapp, data.userDest, msgDest);
+ }
}
+ } else if (
+ data.action ===
+ InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_HANDSHAKE
+ ) {
+ if (userDest) {
+ cmd = shared_consts.FRIENDSCMD.SETHANDSHAKE;
+ const foundIfAlreadyFriend = await User.isMyHandShake(user.idapp, data.userDest, data.username);
- }
- } else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_AMICIZIA) {
-
- if (userDest) {
- cmd = shared_consts.FRIENDSCMD.REMOVE_FROM_MYFRIENDS;
- // Rimuovilo nelle Amicizie
- const req = tools.getReqByPar(user.idapp, username_action);
- const ris = await User.setFriendsCmd(req, user.idapp, data.username, data.userDest, cmd);
- if (ris) {
- const msgDest = printf(getstr(user.lang, 'MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED'), data.username);
-
- await local_sendMsgTelegram(user.idapp, data.userDest, msgDest);
+ if (!foundIfAlreadyFriend) {
+ // Aggiungilo nelle HandShake
+ const req = tools.getReqByPar(user.idapp, username_action);
+ const ris = await User.setFriendsCmd(req, user.idapp, data.userDest, data.username, cmd);
+ }
}
}
- } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_HANDSHAKE) {
-
- if (userDest) {
- cmd = shared_consts.FRIENDSCMD.SETHANDSHAKE;
- const foundIfAlreadyFriend = await User.isMyHandShake(user.idapp, data.userDest, data.username);
-
- if (!foundIfAlreadyFriend) {
- // Aggiungilo nelle HandShake
- const req = tools.getReqByPar(user.idapp, username_action);
- const ris = await User.setFriendsCmd(req, user.idapp, data.userDest, data.username, cmd);
-
- }
-
- }
+ } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.ENTRA_RIS_ITALIA) {
}
- } else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.ENTRA_RIS_ITALIA) {
-
- url = '';
- bot.answerCallbackQuery(callbackQuery.id, { url });
}
- }
- } catch (e) {
- console.error('Error BOT callback_query', e);
- }
- /*
+ // CALLBACK DI RISPOSTA AL BOT
+ bot.answerCallbackQuery(callbackQuery.id, { text: testo_notifica_di_risposta } ) ;
+
+ } catch (e) {
+ console.error('Error BOT callback_query', e);
+ }
+
+ /*
let text;
if (action === 'edit') {
@@ -4723,18 +4628,18 @@ if (true) {
bot.editMessageText(text, opts);
*/
- // bot.answerCallbackQuery(callbackQuery.id, { url });
- });
+ // bot.answerCallbackQuery(callbackQuery.id, { url });
+ });
+ }
+ } catch (e) {
+ console.error('Error Telegram LOOP : ' + e.message);
}
- } catch (e) {
- console.error('Error Telegram LOOP : ' + e.message);
}
- }
- }).catch((e) => {
- arrTeleg = [];
- console.error('Error internetAvailable:' + e);
- });
-
+ })
+ .catch((e) => {
+ arrTeleg = [];
+ console.error('Error internetAvailable:' + e);
+ });
}
module.exports = MyTelegramBot;
diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js
index 71a547f..9037e6e 100755
--- a/src/server/tools/globalTables.js
+++ b/src/server/tools/globalTables.js
@@ -361,84 +361,88 @@ module.exports = {
}
for (const user of arrusers) {
- const mytitle = await tools.convertSpecialTags(user, params.title);
- const mycontent = await tools.convertSpecialTags(
- user,
- params.textcontent_Telegram ? params.textcontent_Telegram : params.content
- );
+ try {
+ const mytitle = await tools.convertSpecialTags(user, params.title);
+ const mycontent = await tools.convertSpecialTags(
+ user,
+ params.textcontent_Telegram ? params.textcontent_Telegram : params.content
+ );
- let usernotifprofile = null;
- if (user.profile.notifs)
- usernotifprofile = user.profile.notifs.find((notif) => notif.dir === params.typenotif);
+ let usernotifprofile = null;
+ if (user.profile.notifs)
+ usernotifprofile = user.profile.notifs.find((notif) => notif.dir === params.typenotif);
- let risult = null;
+ let risult = null;
- let sendmsg = false;
+ let sendmsg = false;
- if (params.typenotif === shared_consts.TypeNotifs.TYPEDIR_FAVORITE) {
- if (
- !usernotifprofile ||
- (usernotifprofile &&
- tools.isBitActive(usernotifprofile.value, shared_consts.TypeNotifs.ID_FAVORITE_ADDED))
- ) {
+ if (params.typenotif === shared_consts.TypeNotifs.TYPEDIR_FAVORITE) {
+ if (
+ !usernotifprofile ||
+ (usernotifprofile &&
+ tools.isBitActive(usernotifprofile.value, shared_consts.TypeNotifs.ID_FAVORITE_ADDED))
+ ) {
+ sendmsg = true;
+ }
+ } else {
sendmsg = true;
}
- } else {
- sendmsg = true;
- }
- if (sendmsg) {
- if (params.sendreally) {
- if (tools.isBitActive(params.typesend, shared_consts.TypeSend.PUSH_NOTIFICATION)) {
- const myparam = { ...params };
- risult = await tools
- .sendNotificationToUser(
- user._id,
- mytitle,
- mycontent,
- myparam.openUrl,
- myparam.openUrl2,
- myparam.tag,
- myparam.actions,
- myparam.id
- )
- .then((ris) => {})
- .catch((e) => {
- console.error(e.message);
- });
- }
- if (tools.isBitActive(params.typesend, shared_consts.TypeSend.TELEGRAM)) {
- const telegid = user.profile.teleg_id;
+ if (sendmsg) {
+ if (params.sendreally) {
+ if (tools.isBitActive(params.typesend, shared_consts.TypeSend.PUSH_NOTIFICATION)) {
+ const myparam = { ...params };
+ risult = await tools
+ .sendNotificationToUser(
+ user._id,
+ mytitle,
+ mycontent,
+ myparam.openUrl,
+ myparam.openUrl2,
+ myparam.tag,
+ myparam.actions,
+ myparam.id
+ )
+ .then((ris) => { })
+ .catch((e) => {
+ console.error(e.message);
+ });
+ }
+ if (tools.isBitActive(params.typesend, shared_consts.TypeSend.TELEGRAM)) {
+ const telegid = user.profile.teleg_id;
- text = tools.getContentNotifByParams(params, mycontent, shared_consts.TypeSend.TELEGRAM);
- if (telegid > 0) {
- risult = await telegrambot.local_sendMsgTelegramByIdTelegram(
- idapp,
- telegid,
- text,
- undefined,
- undefined,
- undefined,
- undefined,
- params.img
- );
- await tools.snooze(25);
+ text = tools.getContentNotifByParams(params, mycontent, shared_consts.TypeSend.TELEGRAM);
+ if (telegid > 0) {
+ risult = await telegrambot.local_sendMsgTelegramByIdTelegram(
+ idapp,
+ telegid,
+ text,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ params.img
+ );
+ await tools.snooze(25);
- try {
- if (risult && (risult.text || risult.caption)) textsent = risult.text || risult.caption;
- } catch (e) {}
+ try {
+ if (risult && (risult.text || risult.caption)) textsent = risult.text || risult.caption;
+ } catch (e) { }
+ }
}
}
- }
- numrec++;
- if (params.sendreally && risult) {
- nummsgsent++;
- }
+ numrec++;
+ if (params.sendreally && risult) {
+ nummsgsent++;
+ }
- if (nummsgsent > 0 && nummsgsent % 100 === 0) {
- console.log('Inviati ', nummsgsent, 'messaggi...');
+ if (nummsgsent > 0 && nummsgsent % 100 === 0) {
+ console.log('Inviati ', nummsgsent, 'messaggi...');
+ }
}
+ } catch (e) {
+ console.error('Errore Invio Notifica a ', user.username, 'Err:', e);
}
}
}