From 3515914f1767e23360f88504604bd7791062a3ad Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Tue, 26 Jul 2022 15:46:39 +0200 Subject: [PATCH] Notification: Set a new Friendship and Accepted Friendship --- src/server/locales/en.json | 7 +- src/server/locales/it.json | 7 +- src/server/models/sendnotif.js | 309 ++++++++++++++++++-------- src/server/models/user.js | 7 + src/server/router/index_router.js | 19 +- src/server/router/myevent_router.js | 13 +- src/server/router/mygen_router.js | 8 +- src/server/router/sendnotif_router.js | 3 +- src/server/router/users_router.js | 9 +- src/server/sendemail.js | 29 +++ src/server/server.js | 2 +- src/server/telegram/telegrambot.js | 7 +- src/server/tools/general.js | 84 ++++++- src/server/tools/globalTables.js | 54 +++-- src/server/tools/shared_nodejs.js | 3 + 15 files changed, 411 insertions(+), 150 deletions(-) diff --git a/src/server/locales/en.json b/src/server/locales/en.json index b4a43a4..26074ea 100755 --- a/src/server/locales/en.json +++ b/src/server/locales/en.json @@ -7,5 +7,10 @@ "Hello": "Hello", "Hello %s": "Ciao %s", "Good: %s": "Good: %s", - "Service: %s": "Service: %s" + "Service: %s": "Service: %s", + "%s new Good: %s": "%s new Good: %s", + "%s new Service: %s": "%s new Service: %s", + "OPEN PAGE": "OPEN PAGE", + "%s asked you for Friendship": "%s asked you for Friendship", + "%s accepted your Friendship": "%s accepted your Friendship" } diff --git a/src/server/locales/it.json b/src/server/locales/it.json index 5393b9d..dad6388 100755 --- a/src/server/locales/it.json +++ b/src/server/locales/it.json @@ -2,5 +2,10 @@ "Hello": "Ciao", "Hello %s": "Ciao %s", "Good: %s": "Bene: %s", - "Service: %s": "Servizio: %s" + "Service: %s": "Servizio: %s", + "%s new Good: %s": "%s nuovo Bene: %s", + "%s new Service: %s": "%s nuovo Servizio: %s", + "OPEN PAGE": "APRI PAGINA", + "%s asked you for Friendship": "%s ti ha chiesto l'Amicizia", + "%s accepted your Friendship": "%s ha accettato l'Amicizia" } diff --git a/src/server/models/sendnotif.js b/src/server/models/sendnotif.js index c1cef52..9817a1a 100755 --- a/src/server/models/sendnotif.js +++ b/src/server/models/sendnotif.js @@ -35,6 +35,9 @@ const sendNotifSchema = new Schema({ dest: { type: String, }, + title: { + type: String, + }, descr: { type: String, }, @@ -100,9 +103,11 @@ sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, la {'dest': username}, {'datenotif': {$gt: new Date(lastdataread)}}, ], - }).lean().sort({datenotif: -1}).then((arrnotif) => { + }).lean().sort({datenotif: -1}).then(async (arrnotif) => { // console.log('arrnotif', arrnotif.length); - return arrnotif; + + return this.compileOtherFields(arrnotif); + }).catch((err) => { console.error('err', err); }); @@ -111,19 +116,66 @@ sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, la sendNotifSchema.statics.getDescrAndLinkByRecNotif = function(recnotif) { - if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_BACHECA) { - if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD) { - recnotif.descr = i18n.__('Good: %s'); - recnotif.openUrl = '/goods'; - } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE) { - recnotif.descr = i18n.__('Service: %s'); - recnotif.openUrl = '/services'; + const numchars = 80; + let newdescr = ''; + let mydescr = ''; + let myidrec = ''; + let userorig = recnotif.sender; + + 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.__('%s new Good: %s', userorig, mydescr); + recnotif.openUrl = '/mygood/' + myidrec; + } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE) { + newdescr = i18n.__('%s 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.__('%s asked you for Friendship', userorig, mydescr); + } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED) { + newdescr = i18n.__('%s 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) { @@ -140,12 +192,8 @@ sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function(username, idap { $sort: {datenotif: -1}, }, - ]).then((arrnotif) => { - // Remove duplicate - // Exclude my chat - const myarr = arrnotif.filter((ris) => ris._id !== username); - // console.table(myarr); - return myarr; + ]).then(async (arrnotif) => { + return this.compileOtherFields(arrnotif); }).catch((err) => { console.error(err); @@ -160,7 +208,10 @@ sendNotifSchema.statics.saveAndSendNotif = function(myrecnotif, req, res, user) if (check.exit) return check.ret; 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) => { let idobj = writeresult._id; @@ -168,9 +219,32 @@ sendNotifSchema.statics.saveAndSendNotif = function(myrecnotif, req, res, user) myrecnotif._id = idobj; 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 recnotif; - }); + return await globalTables.sendNotif(myrecnotif.typedir, myrecnotif.typeid, res, idapp, user ? user : req.user, 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) => { console.log(e.message); @@ -191,6 +265,8 @@ sendNotifSchema.statics.getDefaultRec = function(req) { datenotif: new Date(), status: 0, read: false, + tablerec: '', + idrec: 0, }; }; @@ -202,7 +278,7 @@ sendNotifSchema.statics.createNewNotification = async function(req, res, table, let myrecnotif = new SendNotif(this.getDefaultRec(req)); myrecnotif.tablerec = table; - if (rec) { + if (rec && table) { 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) { const SendNotif = this; @@ -226,88 +320,119 @@ sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotif, req, const {City} = require('../models/city'); const {Province} = require('../models/province'); - // Send only to the destination to reach: - 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(); + try { - let arrprovinces = []; - let arrregions = []; - let idSector = 0; + // Send only to the destination to reach: + 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(); - 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)); } - - if (myrecnotif.tablerec === shared_consts.TABLES_MYGOODS) { - idSector = myrec.idSectorGood; - } else { - idSector = myrec.idSector; - } - + myrecnotif.myrectableorig = myrectableorig; } + + 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) { - const usernotifprofile = user.profile.notifs.find((notif) => notif.dir === myrecnotif.typedir); +sendNotifSchema.statics.sendToSingleUserDest = async function(myrecnotif, req, res, usernameDest, onlysave) { + const SendNotif = this; - let send = false; + try { - 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. + myrecnotif = this.getDescrAndLinkByRecNotif(myrecnotif); - 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); - } + myrecnotif.dest = usernameDest; + if (onlysave) { + await SendNotif.saveNotif(myrecnotif); + } else { + await SendNotif.saveAndSendNotif(myrecnotif, req, res, user); } + + } catch (e) { + console.error('sendToSingleUserDest', e); + return false; } }; diff --git a/src/server/models/user.js b/src/server/models/user.js index d5ea7d9..68369eb 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -1559,6 +1559,8 @@ UserSchema.statics.removeReqFriend = async function( UserSchema.statics.setFriendsCmd = async function(idapp, usernameOrig, usernameDest, cmd, value) { + const {SendNotif} = require('../models/sendnotif'); + let ris = null; let update = {}; try { @@ -1593,6 +1595,11 @@ UserSchema.statics.setFriendsCmd = async function(idapp, usernameOrig, usernameD }; 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]}}}}; ris = await User.updateOne({idapp, username: usernameOrig}, update); } diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index facea35..511f556 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -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)) { - // E' un annuncio, pertanto mando una notifica a "tutti" - SendNotif.createNewNotification(req, res, params.table, myrec, shared_consts.TypeNotifs.TYPEDIR_BACHECA, shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD); + typedir = shared_consts.TypeNotifs.TYPEDIR_BACHECA; + 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); diff --git a/src/server/router/myevent_router.js b/src/server/router/myevent_router.js index 45bb1d6..1970ba3 100755 --- a/src/server/router/myevent_router.js +++ b/src/server/router/myevent_router.js @@ -44,9 +44,7 @@ router.post('/', authenticate, (req, res) => { }).then(async (recmyevent) => { // tools.mylog('myevent:', myevent); // tools.mylog('already exist'); - recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS - recmyevent.typeid = shared_consts.TypeNotifs.ID_EVENTS_NEW_REC - await SendNotif.saveAndSendNotif(recmyevent, req, res); + SendNotif.createNewNotification(req, res, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_NEW_REC); return res; }).then((res) => { 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) => { recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS recmyevent.typeid = shared_consts.TypeNotifs.ID_EVENTS_NEW_REC - return SendNotif.saveAndSendNotif(recmyevent, req, res).then((ris) => { - return res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id}); - }); + 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}); }); }); } @@ -82,9 +79,7 @@ router.delete('/:id/:notify/:idapp', authenticate, (req, res) => { } if (notify === '1') { - recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS - recmyevent.typeid = shared_consts.TypeNotifs.ID_EVENTS_REMOVE_REC - SendNotif.saveAndSendNotif(recmyevent, req, res); + SendNotif.createNewNotification(req, res, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_REMOVE_REC); } tools.mylog('DELETED ', recmyevent.descr, recmyevent._id); diff --git a/src/server/router/mygen_router.js b/src/server/router/mygen_router.js index f7f4596..9b17824 100755 --- a/src/server/router/mygen_router.js +++ b/src/server/router/mygen_router.js @@ -23,13 +23,19 @@ const {ObjectID} = require('mongodb'); //GET orders router.post('/page', authenticate, function(req, res, next) { - //++TODO: PERMESSI ??? + const {SendNotif} = require('../models/sendnotif'); try { let table = req.body.table; let id = req.body.id; 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; if (shared_consts.TABLES_ENABLE_GETREC_BYID.includes(table)) { mytable = globalTables.getTableByTableName(table); diff --git a/src/server/router/sendnotif_router.js b/src/server/router/sendnotif_router.js index d759315..feb8a82 100755 --- a/src/server/router/sendnotif_router.js +++ b/src/server/router/sendnotif_router.js @@ -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}); } - // Extract all the todos of the userId only return SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdataread, idapp).then((arrnotif) => { // const wait = new Promise((resolve, reject) => { // setTimeout(() => { - res.send({arrnotif}); + return res.send({arrnotif}); // }, 2000); // }); diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index ff8c048..9f5231e 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -378,15 +378,16 @@ router.patch('/:id', authenticate, (req, res) => { }); router.post('/profile', authenticate, (req, res) => { + const usernameOrig = req.user.username; const username = req.body['username']; const idapp = req.body.idapp; const locale = req.body.locale; - const idnotif = req.body['idnotif'] ? req.body['idnotif'] : ''; //++Todo: controlla che tipo di dati ha il permesso di leggere // 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 { 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) { myuser.profile.notifs = notifs; myuser.save(); + return res.send({code: server_constants.RIS_CODE_OK, msg: ''}); } } + return res.send({code: server_constants.RIS_CODE_OK, msg: ''}); } catch (e) { tools.mylogserr('Error profile: ', e); res.status(400).send(); @@ -577,7 +580,7 @@ router.post('/setperm', authenticate, (req, res) => { const body = _.pick(req.body, ['idapp', 'username', 'perm']); 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(400).send(); diff --git a/src/server/sendemail.js b/src/server/sendemail.js index 906631c..793e37c 100755 --- a/src/server/sendemail.js +++ b/src/server/sendemail.js @@ -446,6 +446,35 @@ module.exports = { // 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) { // console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp)); diff --git a/src/server/server.js b/src/server/server.js index 3ffc02f..8b497b1 100755 --- a/src/server/server.js +++ b/src/server/server.js @@ -575,7 +575,7 @@ async function faitest() { const langdest = 'it'; - telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser); + telegrambot.askConfirmationUser(req, res, myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser); } diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index e27257b..80444e6 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -894,7 +894,6 @@ const MyTelegramBot = { const cl = getclTelegByidapp(idapp); const langdest = myuser.lang; - const telegid = myuser.profile.teleg_id; let keyb = null; let domanda = ''; @@ -1639,10 +1638,10 @@ 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\n' + - '\n\nPer AIUTO, clicca qui:\n👉🏻👉🏻FAQ di AIUTO (risposte alle domande più frequenti)\n\nSe non trovi risposta allora contatta la Chat HELP.\nGrazie'; + '\nPer AIUTO, clicca qui:\n👉🏻👉🏻FAQ di AIUTO (risposte alle domande più frequenti)\n\nSe non trovi risposta allora contatta la Chat di HELP.\nGrazie'; // risp += '\nClicca qui per entrare nella Chat - HELP di Supporto\n' + 'https://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw' + '\n\nI miei colleghi umani ti aiuteranno a risolvere !'; await local_sendMsgTelegramToTheManagers(this.idapp, testo, msg, rec.username_bo); diff --git a/src/server/tools/general.js b/src/server/tools/general.js index fa1ef41..2d01311 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -30,6 +30,8 @@ const download = require('image-downloader'); // SETTINGS WebPush Configuration const webpush = require('web-push'); +const i18n = require('i18n'); + const FILELOG = 'filelog.txt'; const FILEEVENTS = 'logevents.txt'; const FILEMANAGERS = 'logmanagers.txt'; @@ -578,6 +580,7 @@ module.exports = { 'typeid', 'dest', 'descr', + 'title', 'openUrl', 'datenotif', '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) { var {User} = require('../models/user'); + const {SendNotif} = require('../models/sendnotif'); const telegrambot = require('../telegram/telegrambot'); @@ -865,7 +880,7 @@ module.exports = { let userId = user._id; let lang = user.lang; - let sendnotif = true; + let sendmynotif = true; let title = this.getNomeAppByIdApp(idapp); let descr = ''; @@ -880,19 +895,26 @@ module.exports = { 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) { - 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); } + } } if (userId) { - this.sendNotificationToUser(userId, title, descr, openUrl, '', tag, - actions); + // SEND PUSH NOTIFICATION + this.sendNotificationToUser(userId, title, descr, openUrl, '', tag, actions); } - if (telegram && sendnotif) { + if (telegram && sendmynotif) { const idtelegram = await User.TelegIdByUsername(idapp, username); @@ -1105,11 +1127,18 @@ module.exports = { if (String(userpassed) !== String(userauth)) { // I'm trying to write something not mine! this.mylog('userId = ', userpassed, 'req.user._id', userauth); - return { - exit: true, - ret: res.status(404). - send({code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER}), - }; + if (!res) { + return { + exit: true, + ret: false, + } + } else { + return { + exit: true, + ret: res.status(404). + send({code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER}), + }; + } } else { return {exit: false, ret: false}; } @@ -2754,7 +2783,7 @@ module.exports = { async loadApps() { try { this.MYAPPS = await Site.findAll(0); - console.log('this.MYAPPS', this.MYAPPS); + // console.log('this.MYAPPS', this.MYAPPS); }catch (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) { if (mystr && mystr[0] === '@'){ 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' + '' + i18n.__('OPEN PAGE') + ''; + } + + return content; + } + }; diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index a00c9ca..eec0dba 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -223,27 +223,36 @@ module.exports = { try { 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)) { - if (this.checkifSendPushNotification) { + let invia = false; - const params = { - sendreally: true, - typesend: shared_consts.TypeSend.PUSH_NOTIFICATION + shared_consts.TypeSend.TELEGRAM, - title: tools.getNomeAppByIdApp(idapp), - content: recnotif.descr ? recnotif.descr : tools.getContentByTypeMsg(recnotif.typemsg), - openUrl: tools.updateQueryStringParameter(recnotif.openUrl, 'idnotif', recnotif._id), - typemsg: recnotif.typemsg ? recnotif.typemsg : shared_consts.TypeMsg.SEND_TO_USER, - typenotif, - idnotif, - usernameDest: recnotif.usernameDest ? recnotif.usernameDest : recnotif.dest, - }; + let params = { + idapp, + sendreally: true, + typesend: 0, + title: tools.getNomeAppByIdApp(idapp), + content: recnotif.descr ? recnotif.descr : tools.getContentByTypeMsg(recnotif.typemsg), + openUrl: tools.updateQueryStringParameter(recnotif.openUrl, 'idnotif', recnotif._id), + typemsg: recnotif.typemsg ? recnotif.typemsg : shared_consts.TypeMsg.SEND_TO_USER, + typenotif, + 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 @@ -253,9 +262,7 @@ module.exports = { if (!emaildest) emaildest = await User.getEmailByUsername(recnotif.dest.idapp, recnotif.dest.username); - console.log('emaildest', emaildest); - - await sendemail.sendEmail_Msg(res, user.lang, emaildest, user, idapp, recnotif); + await sendemail.sendEmail_ByNotif(res, user.lang, emaildest, user, idapp, recnotif); } return true; @@ -347,8 +354,9 @@ module.exports = { if (params.sendreally) { if (tools.isBitActive(params.typesend, shared_consts.TypeSend.PUSH_NOTIFICATION)) { - risult = tools.sendNotificationToUser(user._id, mytitle, mycontent, params.openUrl, params.openUrl2, params.tag, - params.actions). + const myparam = {...params}; + risult = tools.sendNotificationToUser(user._id, mytitle, mycontent, myparam.openUrl, myparam.openUrl2, myparam.tag, + myparam.actions). then(ris => { }). @@ -361,8 +369,8 @@ module.exports = { const telegid = user.profile.teleg_id; if (telegid > 0) { - risult = await telegrambot.local_sendMsgTelegramByIdTelegram(idapp, telegid, mycontent); - await tools.snooze(100); + risult = await telegrambot.local_sendMsgTelegramByIdTelegram(idapp, telegid, tools.getContentNotifByParams(params, mycontent, shared_consts.TypeSend.TELEGRAM)); + await tools.snooze(50); } } } diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index f83d8f0..e2369fc 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -98,6 +98,7 @@ module.exports = { TABLES_MYBACHECAS: 'mybachecas', TABLES_MYHOSPS: 'myhosps', TABLES_MYGOODS: 'mygoods', + TABLES_MYEVENTS: 'myevents', TABLES_ENABLE_GETREC_BYID: ['mybachecas', 'myhosps', 'myskills', 'mygoods'], @@ -203,6 +204,7 @@ module.exports = { MessageOptions: { Notify_ByEmail: 2, Notify_ByPushNotification: 4, + Notify_ByBotTelegram: 8, }, TypeMsg: { @@ -296,6 +298,7 @@ module.exports = { TYPEDIR_FRIENDS: 3, ID_FRIENDS_NEW_REC: 1, + ID_FRIENDS_ACCEPTED: 2, TYPEDIR_CIRCUITS: 4,