Notification: Set a new Friendship and Accepted Friendship

This commit is contained in:
Paolo Arena
2022-07-26 15:46:39 +02:00
parent b06f1e4ab8
commit 3515914f17
15 changed files with 411 additions and 150 deletions

View File

@@ -7,5 +7,10 @@
"Hello": "Hello", "Hello": "Hello",
"Hello %s": "Ciao %s", "Hello %s": "Ciao %s",
"Good: %s": "Good: %s", "Good: %s": "Good: %s",
"Service: %s": "Service: %s" "Service: %s": "Service: %s",
"<strong>%s</strong> new Good: %s": "<strong>%s</strong> new Good: %s",
"<strong>%s</strong> new Service: %s": "<strong>%s</strong> new Service: %s",
"OPEN PAGE": "OPEN PAGE",
"<strong>%s</strong> asked you for Friendship": "<strong>%s</strong> asked you for Friendship",
"<strong>%s</strong> accepted your Friendship": "<strong>%s</strong> accepted your Friendship"
} }

View File

@@ -2,5 +2,10 @@
"Hello": "Ciao", "Hello": "Ciao",
"Hello %s": "Ciao %s", "Hello %s": "Ciao %s",
"Good: %s": "Bene: %s", "Good: %s": "Bene: %s",
"Service: %s": "Servizio: %s" "Service: %s": "Servizio: %s",
"<strong>%s</strong> new Good: %s": "<strong>%s</strong> nuovo Bene: %s",
"<strong>%s</strong> new Service: %s": "<strong>%s</strong> nuovo Servizio: %s",
"OPEN PAGE": "APRI PAGINA",
"<strong>%s</strong> asked you for Friendship": "<strong>%s</strong> ti ha chiesto l'Amicizia",
"<strong>%s</strong> accepted your Friendship": "<strong>%s</strong> ha accettato l'Amicizia"
} }

View File

@@ -35,6 +35,9 @@ const sendNotifSchema = new Schema({
dest: { dest: {
type: String, type: String,
}, },
title: {
type: String,
},
descr: { descr: {
type: String, type: String,
}, },
@@ -100,9 +103,11 @@ sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, la
{'dest': username}, {'dest': username},
{'datenotif': {$gt: new Date(lastdataread)}}, {'datenotif': {$gt: new Date(lastdataread)}},
], ],
}).lean().sort({datenotif: -1}).then((arrnotif) => { }).lean().sort({datenotif: -1}).then(async (arrnotif) => {
// console.log('arrnotif', arrnotif.length); // console.log('arrnotif', arrnotif.length);
return arrnotif;
return this.compileOtherFields(arrnotif);
}).catch((err) => { }).catch((err) => {
console.error('err', err); console.error('err', err);
}); });
@@ -111,19 +116,66 @@ sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, la
sendNotifSchema.statics.getDescrAndLinkByRecNotif = function(recnotif) { sendNotifSchema.statics.getDescrAndLinkByRecNotif = function(recnotif) {
if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA) { const numchars = 80;
if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD) { let newdescr = '';
recnotif.descr = i18n.__('Good: %s'); let mydescr = '';
recnotif.openUrl = '/goods'; let myidrec = '';
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE) { let userorig = recnotif.sender;
recnotif.descr = i18n.__('Service: %s');
recnotif.openUrl = '/services'; try {
if (recnotif.myrectableorig) {
myidrec = recnotif.myrectableorig._id;
mydescr = recnotif.myrectableorig.descr ? tools.firstchars(recnotif.myrectableorig.descr, numchars) : '';
} }
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FRIENDS) {
recnotif.openUrl = '/friends'; if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA) {
if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD) {
newdescr = i18n.__('<strong>%s</strong> new Good: %s', userorig, mydescr);
recnotif.openUrl = '/mygood/' + myidrec;
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE) {
newdescr = i18n.__('<strong>%s</strong> new Service: %s', userorig, mydescr);
recnotif.openUrl = '/myservice/' + myidrec;
}
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FRIENDS) {
recnotif.openUrl = '/my/' + userorig;
if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_NEW_REC) {
newdescr = i18n.__('<strong>%s</strong> asked you for Friendship', userorig, mydescr);
} else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED) {
newdescr = i18n.__('<strong>%s</strong> accepted your Friendship', userorig, mydescr);
}
}
if (!recnotif.descr) {
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();
if (myimgprofile && myimgprofile.profile.img)
notif.myimgsender = 'upload/profile/' + notif.sender + '/' + myimgprofile.profile.img;
}
return arrnotif;
} catch (e) {
console.error(e);
return arrnotif;
} }
return recnotif;
}; };
sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function(username, idapp, limit) { sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function(username, idapp, limit) {
@@ -140,12 +192,8 @@ sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function(username, idap
{ {
$sort: {datenotif: -1}, $sort: {datenotif: -1},
}, },
]).then((arrnotif) => { ]).then(async (arrnotif) => {
// Remove duplicate return this.compileOtherFields(arrnotif);
// Exclude my chat
const myarr = arrnotif.filter((ris) => ris._id !== username);
// console.table(myarr);
return myarr;
}).catch((err) => { }).catch((err) => {
console.error(err); console.error(err);
@@ -160,7 +208,10 @@ sendNotifSchema.statics.saveAndSendNotif = function(myrecnotif, req, res, user)
if (check.exit) return check.ret; if (check.exit) return check.ret;
myrecnotif._id = new ObjectID(); myrecnotif._id = new ObjectID();
myrecnotif = this.getDescrAndLinkByRecNotif(myrecnotif); if (!myrecnotif.openUrl) {
// If not exist, then I set openUrl and description
myrecnotif = this.getDescrAndLinkByRecNotif(myrecnotif);
}
return myrecnotif.save().then((writeresult) => { return myrecnotif.save().then((writeresult) => {
let idobj = writeresult._id; let idobj = writeresult._id;
@@ -168,9 +219,32 @@ sendNotifSchema.statics.saveAndSendNotif = function(myrecnotif, req, res, user)
myrecnotif._id = idobj; myrecnotif._id = idobj;
return SendNotif.findById(idobj).lean().then(async (recnotif) => { return SendNotif.findById(idobj).lean().then(async (recnotif) => {
return await globalTables.sendNotif(myrecnotif.typedir, myrecnotif.typeid, res, idapp, user ? user : req.user, recnotif).then((ris) => { return await globalTables.sendNotif(myrecnotif.typedir, myrecnotif.typeid, res, idapp, user ? user : req.user, recnotif).
return recnotif; then((ris) => {
}); return recnotif;
});
});
}).catch((e) => {
console.log(e.message);
return null;
});
};
sendNotifSchema.statics.saveNotif = function(myrecnotif) {
myrecnotif._id = new ObjectID();
if (!myrecnotif.openUrl) {
// If not exist, then I set openUrl and description
myrecnotif = this.getDescrAndLinkByRecNotif(myrecnotif);
}
return myrecnotif.save().then((writeresult) => {
let idobj = writeresult._id;
myrecnotif._id = idobj;
return SendNotif.findById(idobj).lean().then(async (recnotif) => {
return recnotif;
}); });
}).catch((e) => { }).catch((e) => {
console.log(e.message); console.log(e.message);
@@ -191,6 +265,8 @@ sendNotifSchema.statics.getDefaultRec = function(req) {
datenotif: new Date(), datenotif: new Date(),
status: 0, status: 0,
read: false, read: false,
tablerec: '',
idrec: 0,
}; };
}; };
@@ -202,7 +278,7 @@ sendNotifSchema.statics.createNewNotification = async function(req, res, table,
let myrecnotif = new SendNotif(this.getDefaultRec(req)); let myrecnotif = new SendNotif(this.getDefaultRec(req));
myrecnotif.tablerec = table; myrecnotif.tablerec = table;
if (rec) { if (rec && table) {
myrecnotif.idrec = rec._id; myrecnotif.idrec = rec._id;
} }
@@ -218,6 +294,24 @@ sendNotifSchema.statics.createNewNotification = async function(req, res, table,
} }
}; };
sendNotifSchema.statics.createNewNotifToSingleUser = async function(req, res, usernameDest, onlysave, typedir, typeid) {
const SendNotif = this;
try {
let myrecnotif = new SendNotif(this.getDefaultRec(req));
myrecnotif.typedir = typedir;
myrecnotif.typeid = typeid;
await SendNotif.sendToSingleUserDest(myrecnotif, req, res, usernameDest, onlysave);
return true;
} catch (e) {
console.error('createNewNotification', e);
return false;
}
};
sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotif, req, res) { sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotif, req, res) {
const SendNotif = this; const SendNotif = this;
@@ -226,88 +320,119 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotif, req,
const {City} = require('../models/city'); const {City} = require('../models/city');
const {Province} = require('../models/province'); const {Province} = require('../models/province');
// Send only to the destination to reach: try {
const userlist = await User.find({
idapp: myrecnotif.idapp,
$or: [
{deleted: {$exists: false}},
{deleted: {$exists: true, $eq: false}}],
}, {
name: 1,
surname: 1,
lang: 1,
username: 1,
'profile.notifs': 1,
'profile.notif_idCities': 1,
'profile.notif_provinces': 1,
'profile.notif_regions': 1,
'profile.notif_sectors': 1,
'profile.notif_sector_goods': 1,
}).lean();
let arrprovinces = []; // Send only to the destination to reach:
let arrregions = []; const userlist = await User.find({
let idSector = 0; idapp: myrecnotif.idapp,
$or: [
{deleted: {$exists: false}},
{deleted: {$exists: true, $eq: false}}],
}, {
name: 1,
surname: 1,
lang: 1,
username: 1,
'profile.notifs': 1,
'profile.notif_idCities': 1,
'profile.notif_provinces': 1,
'profile.notif_regions': 1,
'profile.notif_sectors': 1,
'profile.notif_sector_goods': 1,
}).lean();
const mytable = globalTables.getTableByTableName(myrecnotif.tablerec); let arrprovinces = [];
let arrregions = [];
let idSector = 0;
if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotif.tablerec) || shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotif.tablerec)) { const mytable = globalTables.getTableByTableName(myrecnotif.tablerec);
if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotif.tablerec) ||
shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotif.tablerec)) {
const myrectableorig = await mytable.findOne({_id: myrecnotif.idrec}).lean();
if (myrectableorig) {
for (const city of myrectableorig.idCity) {
arrprovinces.push(await City.getProvinceByIdCity(city));
arrregions.push(await City.getRegionByIdCity(city));
}
if (myrecnotif.tablerec === shared_consts.TABLES_MYGOODS) {
idSector = myrectableorig.idSectorGood;
} else {
idSector = myrectableorig.idSector;
}
const myrec = await mytable.findOne({_id: myrecnotif.idrec}).lean();
if (myrec) {
for (const city of myrec.idCity) {
arrprovinces.push(await City.getProvinceByIdCity(city));
arrregions.push(await City.getRegionByIdCity(city));
} }
myrecnotif.myrectableorig = myrectableorig;
if (myrecnotif.tablerec === shared_consts.TABLES_MYGOODS) {
idSector = myrec.idSectorGood;
} else {
idSector = myrec.idSector;
}
} }
myrecnotif = this.getDescrAndLinkByRecNotif(myrecnotif);
for (const user of userlist) {
if (user.profile.notifs) {
const usernotifprofile = user.profile.notifs.find((notif) => notif.dir === myrecnotif.typedir);
let send = false;
if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotif.tablerec) ||
shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotif.tablerec)) {
// Estrai la Città, la Provincia e la regione.
if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_PROVINCE) &&
user.profile.notif_provinces && user.profile.notif_provinces.some(r => arrprovinces.indexOf(r) >= 0)) {
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 (idSector && usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_SECTOR)) {
// Controlla se è del settore selezionato
if (myrecnotif.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));
}
}
}
if (send) {
myrecnotif.dest = user.username;
await SendNotif.saveAndSendNotif(myrecnotif, req, res, user);
}
}
}
} catch (e) {
console.error('sendToTheDestinations', e);
return false;
} }
for (const user of userlist) { };
if (user.profile.notifs) { sendNotifSchema.statics.sendToSingleUserDest = async function(myrecnotif, req, res, usernameDest, onlysave) {
const usernotifprofile = user.profile.notifs.find((notif) => notif.dir === myrecnotif.typedir); const SendNotif = this;
let send = false; try {
if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotif.tablerec) || myrecnotif = this.getDescrAndLinkByRecNotif(myrecnotif);
shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotif.tablerec)) {
// Estrai la Città, la Provincia e la regione.
if (usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_PROVINCE) && myrecnotif.dest = usernameDest;
user.profile.notif_provinces && user.profile.notif_provinces.some(r => arrprovinces.indexOf(r) >= 0)) { if (onlysave) {
send = true; await SendNotif.saveNotif(myrecnotif);
} } else {
await SendNotif.saveAndSendNotif(myrecnotif, req, res, user);
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 (idSector && usernotifprofile && tools.isBitActive(usernotifprofile.value, shared_consts.UsersNotif.NEW_ADV_SECTOR)) {
// Controlla se è del settore selezionato
if (myrecnotif.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));
}
}
}
if (send) {
myrecnotif.dest = user.username;
await SendNotif.saveAndSendNotif(myrecnotif, req, res, user);
}
} }
} catch (e) {
console.error('sendToSingleUserDest', e);
return false;
} }
}; };

View File

@@ -1559,6 +1559,8 @@ UserSchema.statics.removeReqFriend = async function(
UserSchema.statics.setFriendsCmd = async function(idapp, usernameOrig, usernameDest, cmd, value) { UserSchema.statics.setFriendsCmd = async function(idapp, usernameOrig, usernameDest, cmd, value) {
const {SendNotif} = require('../models/sendnotif');
let ris = null; let ris = null;
let update = {}; let update = {};
try { try {
@@ -1593,6 +1595,11 @@ UserSchema.statics.setFriendsCmd = async function(idapp, usernameOrig, usernameD
}; };
ris = await User.updateOne({idapp, username: usernameOrig}, update); ris = await User.updateOne({idapp, username: usernameOrig}, update);
// CREATE NOTIFICATION IN TABLE SENDNOTIF
const req = tools.getReqByPar(idapp, usernameOrig);
SendNotif.createNewNotifToSingleUser(req, null, usernameDest, true, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED);
update = {$pull: {'profile.req_friends': {username: {$in: [usernameDest]}}}}; update = {$pull: {'profile.req_friends': {username: {$in: [usernameDest]}}}};
ris = await User.updateOne({idapp, username: usernameOrig}, update); ris = await User.updateOne({idapp, username: usernameOrig}, update);
} }

View File

@@ -339,9 +339,24 @@ router.post('/settable', authenticate, async (req, res) => {
}); });
} }
let setnotif = false;
let typedir = 0;
let typeid = 0;
if (shared_consts.TABLES_ADV_NOTIFICATION.includes(params.table)) { if (shared_consts.TABLES_ADV_NOTIFICATION.includes(params.table)) {
// E' un annuncio, pertanto mando una notifica a "tutti" typedir = shared_consts.TypeNotifs.TYPEDIR_BACHECA;
SendNotif.createNewNotification(req, res, params.table, myrec, shared_consts.TypeNotifs.TYPEDIR_BACHECA, shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD); typeid = (params.table === shared_consts.TABLES_MYGOODS) ? shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD : shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE
setnotif = true;
}
if (shared_consts.TABLES_EVENTS_NOTIFICATION.includes(params.table)) {
typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS;
typeid = shared_consts.TypeNotifs.ID_EVENTS_NEW_REC;
setnotif = true;
}
if (setnotif) {
SendNotif.createNewNotification(req, res, params.table, myrec, typedir, typeid);
} }
return res.send(myrec); return res.send(myrec);

View File

@@ -44,9 +44,7 @@ router.post('/', authenticate, (req, res) => {
}).then(async (recmyevent) => { }).then(async (recmyevent) => {
// tools.mylog('myevent:', myevent); // tools.mylog('myevent:', myevent);
// tools.mylog('already exist'); // tools.mylog('already exist');
recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS SendNotif.createNewNotification(req, res, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_NEW_REC);
recmyevent.typeid = shared_consts.TypeNotifs.ID_EVENTS_NEW_REC
await SendNotif.saveAndSendNotif(recmyevent, req, res);
return res; return res;
}).then((res) => { }).then((res) => {
res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id}); res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id});
@@ -61,9 +59,8 @@ router.post('/', authenticate, (req, res) => {
myevent.findById(idobj).then((recmyevent) => { myevent.findById(idobj).then((recmyevent) => {
recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS
recmyevent.typeid = shared_consts.TypeNotifs.ID_EVENTS_NEW_REC recmyevent.typeid = shared_consts.TypeNotifs.ID_EVENTS_NEW_REC
return SendNotif.saveAndSendNotif(recmyevent, req, res).then((ris) => { SendNotif.createNewNotification(req, res, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_NEW_REC);
return res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id}); return res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id});
});
}); });
}); });
} }
@@ -82,9 +79,7 @@ router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
} }
if (notify === '1') { if (notify === '1') {
recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS SendNotif.createNewNotification(req, res, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_REMOVE_REC);
recmyevent.typeid = shared_consts.TypeNotifs.ID_EVENTS_REMOVE_REC
SendNotif.saveAndSendNotif(recmyevent, req, res);
} }
tools.mylog('DELETED ', recmyevent.descr, recmyevent._id); tools.mylog('DELETED ', recmyevent.descr, recmyevent._id);

View File

@@ -23,13 +23,19 @@ const {ObjectID} = require('mongodb');
//GET orders //GET orders
router.post('/page', authenticate, function(req, res, next) { router.post('/page', authenticate, function(req, res, next) {
//++TODO: PERMESSI ??? const {SendNotif} = require('../models/sendnotif');
try { try {
let table = req.body.table; let table = req.body.table;
let id = req.body.id; let id = req.body.id;
let idapp = req.body.idapp; let idapp = req.body.idapp;
const username = req.user.username ? req.user.username : '';
// Check if ìs a Notif to read
const idnotif = req.body.idnotif ? req.body.idnotif : '';
SendNotif.setNotifAsRead(idapp, username, idnotif);
let mytable = null; let mytable = null;
if (shared_consts.TABLES_ENABLE_GETREC_BYID.includes(table)) { if (shared_consts.TABLES_ENABLE_GETREC_BYID.includes(table)) {
mytable = globalTables.getTableByTableName(table); mytable = globalTables.getTableByTableName(table);

View File

@@ -101,11 +101,10 @@ router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
return res.status(404).send({code: server_constants.RIS_CODE_NOT_MY_USERNAME}); return res.status(404).send({code: server_constants.RIS_CODE_NOT_MY_USERNAME});
} }
// Extract all the todos of the userId only
return SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdataread, idapp).then((arrnotif) => { return SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdataread, idapp).then((arrnotif) => {
// const wait = new Promise((resolve, reject) => { // const wait = new Promise((resolve, reject) => {
// setTimeout(() => { // setTimeout(() => {
res.send({arrnotif}); return res.send({arrnotif});
// }, 2000); // }, 2000);
// }); // });

View File

@@ -378,15 +378,16 @@ router.patch('/:id', authenticate, (req, res) => {
}); });
router.post('/profile', authenticate, (req, res) => { router.post('/profile', authenticate, (req, res) => {
const usernameOrig = req.user.username;
const username = req.body['username']; const username = req.body['username'];
const idapp = req.body.idapp; const idapp = req.body.idapp;
const locale = req.body.locale; const locale = req.body.locale;
const idnotif = req.body['idnotif'] ? req.body['idnotif'] : '';
//++Todo: controlla che tipo di dati ha il permesso di leggere //++Todo: controlla che tipo di dati ha il permesso di leggere
// Check if ìs a Notif to read // Check if ìs a Notif to read
SendNotif.setNotifAsRead(idapp, username, idnotif); const idnotif = req.body['idnotif'] ? req.body['idnotif'] : '';
SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif);
try { try {
return User.getUserProfileByUsername(idapp, username, req.user.username, return User.getUserProfileByUsername(idapp, username, req.user.username,
@@ -457,8 +458,10 @@ router.post('/notifs', authenticate, async (req, res) => {
if (tools.isArray(notifs) && notifs.length >= 0) { if (tools.isArray(notifs) && notifs.length >= 0) {
myuser.profile.notifs = notifs; myuser.profile.notifs = notifs;
myuser.save(); myuser.save();
return res.send({code: server_constants.RIS_CODE_OK, msg: ''});
} }
} }
return res.send({code: server_constants.RIS_CODE_OK, msg: ''});
} catch (e) { } catch (e) {
tools.mylogserr('Error profile: ', e); tools.mylogserr('Error profile: ', e);
res.status(400).send(); res.status(400).send();
@@ -577,7 +580,7 @@ router.post('/setperm', authenticate, (req, res) => {
const body = _.pick(req.body, ['idapp', 'username', 'perm']); const body = _.pick(req.body, ['idapp', 'username', 'perm']);
tools.mylog('SETPERM = ' + req.token); tools.mylog('SETPERM = ' + req.token);
User.setPermissionsById(res.user._id, body).then(() => { User.setPermissionsById(req.user._id, body).then(() => {
res.status(200).send(); res.status(200).send();
}, () => { }, () => {
res.status(400).send(); res.status(400).send();

View File

@@ -446,6 +446,35 @@ module.exports = {
// this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf); // this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf);
}, },
sendEmail_ByNotif: async function (lang, emailto, user, idapp, recnotif) {
tools.mylog('sendEmail_ByNotif');
let mylocalsconf = {
idapp,
dataemail: await this.getdataemail(idapp),
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
usernameorig: user.name + ' ' + user.surname,
};
mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);
mylocalsconf.emailto = emailto;
mylocalsconf.dataemail.emailtitle = recnotif.title;
mylocalsconf.dataemail.emailbody = tools.getTextNotifByRecNotif(recnotif);
if (!!mylocalsconf.dataemail.emailtitle && !!mylocalsconf.dataemail.emailbody) {
const replyto = tools.getreplyToEmailByIdApp(idapp);
//return this.sendEmail_base('standard', emailto, mylocalsconf, replyto);
return await this.sendEmail_Normale(emailto, mylocalsconf.dataemail.emailtitle, mylocalsconf.dataemail.emailbody, replyto);
}
// Send Email also to the Admin
// this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf);
},
Add_to_MailingList_AndSendEmailNotify: async function (lang, user, idapp, sendnews) { Add_to_MailingList_AndSendEmailNotify: async function (lang, user, idapp, sendnews) {
// console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp)); // console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));

View File

@@ -575,7 +575,7 @@ async function faitest() {
const langdest = 'it'; const langdest = 'it';
telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser); telegrambot.askConfirmationUser(req, res, myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser);
} }

View File

@@ -894,7 +894,6 @@ const MyTelegramBot = {
const cl = getclTelegByidapp(idapp); const cl = getclTelegByidapp(idapp);
const langdest = myuser.lang; const langdest = myuser.lang;
const telegid = myuser.profile.teleg_id;
let keyb = null; let keyb = null;
let domanda = ''; let domanda = '';
@@ -1639,10 +1638,10 @@ class Telegram {
} else if (testo.length >= 10) { } else if (testo.length >= 10) {
noanswer = true; noanswer = true;
let myfaq = this.geturlfaq(); 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\n' + 'Usa il menu qui sotto per interagire col BOT\n' +
'\n\nPer AIUTO, clicca qui:\n👉🏻👉🏻<a href="' + myfaq + '\nPer <strong>AIUTO</strong>, clicca qui:\n👉🏻👉🏻<a href="' + myfaq +
'">FAQ di AIUTO</a> (risposte alle domande più frequenti)\n\nSe non trovi risposta allora contatta la Chat HELP.\nGrazie'; '">FAQ di AIUTO</a> (risposte alle domande più frequenti)\n\nSe non trovi risposta allora contatta la <a href="' + tools.getTelegramSupportChat(this.idapp) + '">Chat di HELP</a>.\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 !'; // 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, await local_sendMsgTelegramToTheManagers(this.idapp, testo, msg,
rec.username_bo); rec.username_bo);

View File

@@ -30,6 +30,8 @@ const download = require('image-downloader');
// SETTINGS WebPush Configuration // SETTINGS WebPush Configuration
const webpush = require('web-push'); const webpush = require('web-push');
const i18n = require('i18n');
const FILELOG = 'filelog.txt'; const FILELOG = 'filelog.txt';
const FILEEVENTS = 'logevents.txt'; const FILEEVENTS = 'logevents.txt';
const FILEMANAGERS = 'logmanagers.txt'; const FILEMANAGERS = 'logmanagers.txt';
@@ -578,6 +580,7 @@ module.exports = {
'typeid', 'typeid',
'dest', 'dest',
'descr', 'descr',
'title',
'openUrl', 'openUrl',
'datenotif', 'datenotif',
'read', 'read',
@@ -852,9 +855,21 @@ module.exports = {
}, },
getReqByPar(idapp, usernameOrig) {
return {
body: {
idapp: idapp,
},
user: {
username: usernameOrig,
}
};
},
sendNotificationByUsername: async function(idapp, username, cmd, telegram, usernameOrig) { sendNotificationByUsername: async function(idapp, username, cmd, telegram, usernameOrig) {
var {User} = require('../models/user'); var {User} = require('../models/user');
const {SendNotif} = require('../models/sendnotif');
const telegrambot = require('../telegram/telegrambot'); const telegrambot = require('../telegram/telegrambot');
@@ -865,7 +880,7 @@ module.exports = {
let userId = user._id; let userId = user._id;
let lang = user.lang; let lang = user.lang;
let sendnotif = true; let sendmynotif = true;
let title = this.getNomeAppByIdApp(idapp); let title = this.getNomeAppByIdApp(idapp);
let descr = ''; let descr = '';
@@ -880,19 +895,26 @@ module.exports = {
const userrecDest = await User.getUserShortDataByUsername(idapp, usernameOrig); const userrecDest = await User.getUserShortDataByUsername(idapp, usernameOrig);
const req = this.getReqByPar(idapp, usernameOrig);
// CREATE NOTIFICATION IN TABLE SENDNOTIF
SendNotif.createNewNotifToSingleUser(req, null, username, true, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, shared_consts.TypeNotifs.ID_FRIENDS_NEW_REC);
if (userrecDest) { if (userrecDest) {
sendnotif = false; // non lo rimandare 2 volte ! sendmynotif = false; // non lo rimandare 2 volte !
// SEND TELEGRAM NOTIFICATION
telegrambot.askConfirmationUserFriend(idapp, shared_consts.CallFunz.RICHIESTA_AMICIZIA, userrecDest, username, usernameOrig); telegrambot.askConfirmationUserFriend(idapp, shared_consts.CallFunz.RICHIESTA_AMICIZIA, userrecDest, username, usernameOrig);
} }
} }
} }
if (userId) { if (userId) {
this.sendNotificationToUser(userId, title, descr, openUrl, '', tag, // SEND PUSH NOTIFICATION
actions); this.sendNotificationToUser(userId, title, descr, openUrl, '', tag, actions);
} }
if (telegram && sendnotif) { if (telegram && sendmynotif) {
const idtelegram = await User.TelegIdByUsername(idapp, username); const idtelegram = await User.TelegIdByUsername(idapp, username);
@@ -1105,11 +1127,18 @@ module.exports = {
if (String(userpassed) !== String(userauth)) { if (String(userpassed) !== String(userauth)) {
// I'm trying to write something not mine! // I'm trying to write something not mine!
this.mylog('userId = ', userpassed, 'req.user._id', userauth); this.mylog('userId = ', userpassed, 'req.user._id', userauth);
return { if (!res) {
exit: true, return {
ret: res.status(404). exit: true,
send({code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER}), ret: false,
}; }
} else {
return {
exit: true,
ret: res.status(404).
send({code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER}),
};
}
} else { } else {
return {exit: false, ret: false}; return {exit: false, ret: false};
} }
@@ -2754,7 +2783,7 @@ module.exports = {
async loadApps() { async loadApps() {
try { try {
this.MYAPPS = await Site.findAll(0); this.MYAPPS = await Site.findAll(0);
console.log('this.MYAPPS', this.MYAPPS); // console.log('this.MYAPPS', this.MYAPPS);
}catch (e) { }catch (e) {
console.error('loadApps', e); console.error('loadApps', e);
} }
@@ -2933,6 +2962,27 @@ module.exports = {
}); });
}, },
capitalize(value) {
if (!value) {
return ''
}
const myval = value.toString()
return myval.charAt(0).toUpperCase() + myval.slice(1)
},
firstchars(value, numchars = 200) {
if (!value) {
return ''
}
try {
let mycar = value.substring(0, numchars)
if (value.length > numchars) mycar += '...'
return mycar
} catch (e) {
return value
}
},
removeAtChar(mystr) { removeAtChar(mystr) {
if (mystr && mystr[0] === '@'){ if (mystr && mystr[0] === '@'){
return mystr = mystr.substring(1); return mystr = mystr.substring(1);
@@ -2961,4 +3011,16 @@ module.exports = {
}, },
getContentNotifByParams(params, content, typesend) {
if (typesend === shared_consts.TypeSend.TELEGRAM) {
let myhost = this.getHostByIdApp(params.idapp);
if (params.openUrl)
content = content + '\n' + '<a href="' + myhost + params.openUrl + '">' + i18n.__('OPEN PAGE') + '</a>';
}
return content;
}
}; };

View File

@@ -223,27 +223,36 @@ module.exports = {
try { try {
if (!recnotif.options) { if (!recnotif.options) {
recnotif.options = shared_consts.MessageOptions.Notify_ByPushNotification; recnotif.options = shared_consts.MessageOptions.Notify_ByPushNotification + shared_consts.MessageOptions.Notify_ByBotTelegram;
} }
if (tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByPushNotification)) { let invia = false;
if (this.checkifSendPushNotification) {
const params = { let params = {
sendreally: true, idapp,
typesend: shared_consts.TypeSend.PUSH_NOTIFICATION + shared_consts.TypeSend.TELEGRAM, sendreally: true,
title: tools.getNomeAppByIdApp(idapp), typesend: 0,
content: recnotif.descr ? recnotif.descr : tools.getContentByTypeMsg(recnotif.typemsg), title: tools.getNomeAppByIdApp(idapp),
openUrl: tools.updateQueryStringParameter(recnotif.openUrl, 'idnotif', recnotif._id), content: recnotif.descr ? recnotif.descr : tools.getContentByTypeMsg(recnotif.typemsg),
typemsg: recnotif.typemsg ? recnotif.typemsg : shared_consts.TypeMsg.SEND_TO_USER, openUrl: tools.updateQueryStringParameter(recnotif.openUrl, 'idnotif', recnotif._id),
typenotif, typemsg: recnotif.typemsg ? recnotif.typemsg : shared_consts.TypeMsg.SEND_TO_USER,
idnotif, typenotif,
usernameDest: recnotif.usernameDest ? recnotif.usernameDest : recnotif.dest, idnotif,
}; usernameDest: recnotif.usernameDest ? recnotif.usernameDest : recnotif.dest,
};
ris = await this.SendMsgToParam(idapp, params); if (tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByPushNotification) && this.checkifSendPushNotification) {
params.typesend = params.typesend + shared_consts.TypeSend.PUSH_NOTIFICATION;
invia = true;
}
if (tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByBotTelegram)) {
params.typesend = params.typesend + shared_consts.TypeSend.TELEGRAM;
invia = true;
}
}
if (invia) {
ris = await this.SendMsgToParam(idapp, params);
} }
// Send Msg by EMAIL // Send Msg by EMAIL
@@ -253,9 +262,7 @@ module.exports = {
if (!emaildest) if (!emaildest)
emaildest = await User.getEmailByUsername(recnotif.dest.idapp, recnotif.dest.username); emaildest = await User.getEmailByUsername(recnotif.dest.idapp, recnotif.dest.username);
console.log('emaildest', emaildest); await sendemail.sendEmail_ByNotif(res, user.lang, emaildest, user, idapp, recnotif);
await sendemail.sendEmail_Msg(res, user.lang, emaildest, user, idapp, recnotif);
} }
return true; return true;
@@ -347,8 +354,9 @@ module.exports = {
if (params.sendreally) { if (params.sendreally) {
if (tools.isBitActive(params.typesend, shared_consts.TypeSend.PUSH_NOTIFICATION)) { if (tools.isBitActive(params.typesend, shared_consts.TypeSend.PUSH_NOTIFICATION)) {
risult = tools.sendNotificationToUser(user._id, mytitle, mycontent, params.openUrl, params.openUrl2, params.tag, const myparam = {...params};
params.actions). risult = tools.sendNotificationToUser(user._id, mytitle, mycontent, myparam.openUrl, myparam.openUrl2, myparam.tag,
myparam.actions).
then(ris => { then(ris => {
}). }).
@@ -361,8 +369,8 @@ module.exports = {
const telegid = user.profile.teleg_id; const telegid = user.profile.teleg_id;
if (telegid > 0) { if (telegid > 0) {
risult = await telegrambot.local_sendMsgTelegramByIdTelegram(idapp, telegid, mycontent); risult = await telegrambot.local_sendMsgTelegramByIdTelegram(idapp, telegid, tools.getContentNotifByParams(params, mycontent, shared_consts.TypeSend.TELEGRAM));
await tools.snooze(100); await tools.snooze(50);
} }
} }
} }

View File

@@ -98,6 +98,7 @@ module.exports = {
TABLES_MYBACHECAS: 'mybachecas', TABLES_MYBACHECAS: 'mybachecas',
TABLES_MYHOSPS: 'myhosps', TABLES_MYHOSPS: 'myhosps',
TABLES_MYGOODS: 'mygoods', TABLES_MYGOODS: 'mygoods',
TABLES_MYEVENTS: 'myevents',
TABLES_ENABLE_GETREC_BYID: ['mybachecas', 'myhosps', 'myskills', 'mygoods'], TABLES_ENABLE_GETREC_BYID: ['mybachecas', 'myhosps', 'myskills', 'mygoods'],
@@ -203,6 +204,7 @@ module.exports = {
MessageOptions: { MessageOptions: {
Notify_ByEmail: 2, Notify_ByEmail: 2,
Notify_ByPushNotification: 4, Notify_ByPushNotification: 4,
Notify_ByBotTelegram: 8,
}, },
TypeMsg: { TypeMsg: {
@@ -296,6 +298,7 @@ module.exports = {
TYPEDIR_FRIENDS: 3, TYPEDIR_FRIENDS: 3,
ID_FRIENDS_NEW_REC: 1, ID_FRIENDS_NEW_REC: 1,
ID_FRIENDS_ACCEPTED: 2,
TYPEDIR_CIRCUITS: 4, TYPEDIR_CIRCUITS: 4,