Notifications

Settings Notifications
User Panel
This commit is contained in:
Paolo Arena
2022-07-23 17:48:33 +02:00
parent e9ce597027
commit b06f1e4ab8
19 changed files with 472 additions and 121 deletions

View File

@@ -3,5 +3,9 @@
"Email Verificata!": "Email Verificada! Cierre esta ventana y regrese a la otra.", "Email Verificata!": "Email Verificada! Cierre esta ventana y regrese a la otra.",
"Nuova Registrazione": "Nuevo Registro", "Nuova Registrazione": "Nuevo Registro",
"Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro", "Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro",
"partecipanti": "participantes" "partecipanti": "participantes",
"Hello": "Hello",
"Hello %s": "Ciao %s",
"Good: %s": "Good: %s",
"Service: %s": "Service: %s"
} }

View File

@@ -1,2 +1,6 @@
{ {
"Hello": "Ciao",
"Hello %s": "Ciao %s",
"Good: %s": "Bene: %s",
"Service: %s": "Servizio: %s"
} }

View File

@@ -68,6 +68,24 @@ CitySchema.pre('save', async function(next) {
next(); next();
}); });
CitySchema.statics.getProvinceByIdCity = async function(idcity) {
const myrec = await City.findOne({_id: idcity}).lean();
if (myrec) {
return myrec.prov;
}
return '';
}
CitySchema.statics.getRegionByIdCity = async function(idcity) {
const myrec = await City.findOne({_id: idcity}).lean();
if (myrec) {
return myrec.reg;
}
return '';
}
CitySchema.statics.findByCity = function(mycity) { CitySchema.statics.findByCity = function(mycity) {
let myregexp = new RegExp(mycity.trim().replace(' ', '|'), 'ig'); let myregexp = new RegExp(mycity.trim().replace(' ', '|'), 'ig');

View File

@@ -37,6 +37,16 @@ const ProvinceSchema = new Schema({
}, },
}, { _id : false }); }, { _id : false });
ProvinceSchema.statics.getRegionByStrProvince = async function(strprovince) {
const myrec = await Province.findOne({prov: strprovince}).lean();
if (myrec) {
return myrec.reg;
}
return '';
}
ProvinceSchema.statics.getFieldsForSearch = function() { ProvinceSchema.statics.getFieldsForSearch = function() {
return [ return [

View File

@@ -4,8 +4,16 @@ const Schema = mongoose.Schema;
mongoose.Promise = global.Promise; mongoose.Promise = global.Promise;
mongoose.level = 'F'; mongoose.level = 'F';
const i18n = require('i18n');
const {ObjectID} = require('mongodb'); const {ObjectID} = require('mongodb');
const shared_consts = require('../tools/shared_nodejs');
const globalTables = require('../tools/globalTables');
const tools = require('../tools/general');
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => { mongoose.plugin(schema => {
schema.options.usePushEach = true; schema.options.usePushEach = true;
@@ -15,7 +23,10 @@ const sendNotifSchema = new Schema({
idapp: { idapp: {
type: String, type: String,
}, },
type: { typedir: {
type: Number,
},
typeid: {
type: Number, type: Number,
}, },
sender: { // mittente sender: { // mittente
@@ -27,7 +38,7 @@ const sendNotifSchema = new Schema({
descr: { descr: {
type: String, type: String,
}, },
link: { openUrl: {
type: String, type: String,
}, },
datenotif: { datenotif: {
@@ -40,6 +51,12 @@ const sendNotifSchema = new Schema({
type: Boolean, type: Boolean,
default: false, default: false,
}, },
tablerec: {
type: String,
},
idrec: {
type: String,
},
deleted: { deleted: {
type: Boolean, type: Boolean,
default: false, default: false,
@@ -52,7 +69,6 @@ sendNotifSchema.statics.setNotifAsRead = function(idapp, username, idnotif) {
try { try {
if (idnotif) { if (idnotif) {
return SendNotif.findOneAndUpdate({ return SendNotif.findOneAndUpdate({
$and: [ $and: [
@@ -70,7 +86,7 @@ sendNotifSchema.statics.setNotifAsRead = function(idapp, username, idnotif) {
console.error('err', err); console.error('err', err);
}); });
} }
}catch (e) { } catch (e) {
return false; return false;
} }
}; };
@@ -85,7 +101,7 @@ sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, la
{'datenotif': {$gt: new Date(lastdataread)}}, {'datenotif': {$gt: new Date(lastdataread)}},
], ],
}).lean().sort({datenotif: -1}).then((arrnotif) => { }).lean().sort({datenotif: -1}).then((arrnotif) => {
console.log('arrnotif', arrnotif.length); // console.log('arrnotif', arrnotif.length);
return arrnotif; return arrnotif;
}).catch((err) => { }).catch((err) => {
console.error('err', err); console.error('err', err);
@@ -93,7 +109,24 @@ sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, la
}; };
sendNotifSchema.statics.findLastGroupByUserIdAndIdApp = function(username, idapp) { 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';
}
} else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FRIENDS) {
recnotif.openUrl = '/friends';
}
return recnotif;
};
sendNotifSchema.statics.findLastNotifsByUserIdAndIdApp = function(username, idapp, limit) {
const SendNotif = this; const SendNotif = this;
return SendNotif.aggregate([ return SendNotif.aggregate([
@@ -103,16 +136,7 @@ sendNotifSchema.statics.findLastGroupByUserIdAndIdApp = function(username, idapp
dest: username, dest: username,
}, },
}, },
{ {$limit: limit},
$group:
{
_id: '$dest',
descr: {$last: '$message'},
datenotif: {$last: '$datenotif'},
read: {$last: '$read'},
},
},
{ {
$sort: {datenotif: -1}, $sort: {datenotif: -1},
}, },
@@ -129,6 +153,165 @@ sendNotifSchema.statics.findLastGroupByUserIdAndIdApp = function(username, idapp
}; };
sendNotifSchema.statics.saveAndSendNotif = function(myrecnotif, req, res, user) {
let idapp = req.body.idapp;
const check = tools.checkUserOk(myrecnotif.sender, user ? myrecnotif.sender : req.user.username, res);
if (check.exit) return check.ret;
myrecnotif._id = new ObjectID();
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 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.getDefaultRec = function(req) {
return {
idapp: req.body.idapp,
typedir: '',
typeid: '',
sender: req.user ? req.user.username : '',
dest: '',
descr: '',
openUrl: '',
datenotif: new Date(),
status: 0,
read: false,
};
};
sendNotifSchema.statics.createNewNotification = async function(req, res, table, rec, typedir, typeid) {
const SendNotif = this;
try {
let myrecnotif = new SendNotif(this.getDefaultRec(req));
myrecnotif.tablerec = table;
if (rec) {
myrecnotif.idrec = rec._id;
}
myrecnotif.typedir = typedir;
myrecnotif.typeid = typeid;
await SendNotif.sendToTheDestinations(myrecnotif, req, res);
return true;
} catch (e) {
console.error('createNewNotification', e);
return false;
}
};
sendNotifSchema.statics.sendToTheDestinations = async function(myrecnotif, req, res) {
const SendNotif = this;
const {User} = require('../models/user');
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();
let arrprovinces = [];
let arrregions = [];
let idSector = 0;
const mytable = globalTables.getTableByTableName(myrecnotif.tablerec);
if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotif.tablerec) || shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotif.tablerec)) {
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;
}
}
}
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);
}
}
}
};
const SendNotif = mongoose.model('SendNotif', sendNotifSchema); const SendNotif = mongoose.model('SendNotif', sendNotifSchema);
module.exports = {SendNotif: SendNotif}; module.exports = {SendNotif: SendNotif};

View File

@@ -131,7 +131,7 @@ module.exports.findAll = async function () {
const myfind = { active: true }; const myfind = { active: true };
return Site.find(myfind).lean(); return await Site.find(myfind).lean();
}; };

View File

@@ -365,6 +365,26 @@ const UserSchema = new mongoose.Schema({
value: {type: Number}, value: {type: Number},
}, },
], ],
notif_idCities: [
{
type: Number,
}],
notif_provinces: [
{
type: String,
}],
notif_regions: [
{
type: String,
}],
notif_sectors: [
{
type: Number,
}],
notif_sector_goods: [
{
type: Number,
}]
}, },
}) })
; ;

View File

@@ -6,7 +6,6 @@ const mongoose = require('mongoose').set('debug', false)
const shared_consts = require('../tools/shared_nodejs'); const shared_consts = require('../tools/shared_nodejs');
const globalTables = require('../tools/globalTables');
module.exports = { module.exports = {
@@ -146,6 +145,8 @@ module.exports = {
const scrivi_citta = false; const scrivi_citta = false;
const scrivi_contribtype = false; const scrivi_contribtype = false;
const globalTables = require('../tools/globalTables');
let ris = null; let ris = null;
try { try {

View File

@@ -253,6 +253,7 @@ router.post('/settable', authenticate, async (req, res) => {
} }
} }
if (params.table === shared_consts.TAB_MYGROUPS) { if (params.table === shared_consts.TAB_MYGROUPS) {
if (shared_consts.MYGROUPS_KEY_TO_CRYPTED in mydata) { if (shared_consts.MYGROUPS_KEY_TO_CRYPTED in mydata) {
if (mydata[shared_consts.MYGROUPS_KEY_TO_CRYPTED]) { if (mydata[shared_consts.MYGROUPS_KEY_TO_CRYPTED]) {
@@ -338,6 +339,11 @@ router.post('/settable', authenticate, async (req, res) => {
}); });
} }
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);
}
return res.send(myrec); return res.send(myrec);
}).catch((e) => { }).catch((e) => {
console.error('settable', e.message); console.error('settable', e.message);
@@ -1301,7 +1307,7 @@ router.get(process.env.LINK_CHECK_UPDATES, authenticate, async (req, res) => {
// msgs = SendMsg.findAllByUserIdAndIdApp(userId, req.user.username, req.user.idapp); // msgs = SendMsg.findAllByUserIdAndIdApp(userId, req.user.username, req.user.idapp);
let last_msgs = SendMsg.findLastGroupByUserIdAndIdApp(userId, req.user.username, idapp); let last_msgs = SendMsg.findLastGroupByUserIdAndIdApp(userId, req.user.username, idapp);
let last_notifs = SendNotif.findLastGroupByUserIdAndIdApp(userId, req.user.username, idapp); let last_notifs = SendNotif.findLastNotifsByUserIdAndIdApp(req.user.username, idapp, 20);
let usersList = null; let usersList = null;

View File

@@ -14,6 +14,10 @@ const sendemail = require('../sendemail');
const globalTables = require('../tools/globalTables'); const globalTables = require('../tools/globalTables');
const {SendNotif} = require('../models/sendnotif');
const shared_consts = require('../tools/shared_nodejs');
const _ = require('lodash'); const _ = require('lodash');
router.post('/', authenticate, (req, res) => { router.post('/', authenticate, (req, res) => {
@@ -37,10 +41,12 @@ router.post('/', authenticate, (req, res) => {
return myevent.findOneAndUpdate({id}, {$set: fieldtochange}, { return myevent.findOneAndUpdate({id}, {$set: fieldtochange}, {
new: false, new: false,
upsert: true, upsert: true,
}).then((recmyevent) => { }).then(async (recmyevent) => {
// tools.mylog('myevent:', myevent); // tools.mylog('myevent:', myevent);
// tools.mylog('already exist'); // tools.mylog('already exist');
globalTables.sendNotif(res, myrec.idapp, req.user, recmyevent); recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS
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});
@@ -53,8 +59,11 @@ router.post('/', authenticate, (req, res) => {
let idobj = writeresult._id; let idobj = writeresult._id;
myevent.findById(idobj).then((recmyevent) => { myevent.findById(idobj).then((recmyevent) => {
globalTables.sendNotif(res, myrec.idapp, req.user, recmyevent); recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS
res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id}); 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});
});
}); });
}); });
} }
@@ -72,8 +81,11 @@ router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
return res.status(404).send(); return res.status(404).send();
} }
if (notify === '1') if (notify === '1') {
globalTables.sendNotif(res, idapp, req.user, recmyevent); recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS
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

@@ -10,6 +10,8 @@ const { User } = require('../models/user');
const { Operator } = require('../models/operator'); const { Operator } = require('../models/operator');
const { SendMsg } = require('../models/sendmsg'); const { SendMsg } = require('../models/sendmsg');
const {SendNotif} = require('../models/sendnotif');
const { ObjectID } = require('mongodb'); const { ObjectID } = require('mongodb');
const sendemail = require('../sendemail'); const sendemail = require('../sendemail');
@@ -46,9 +48,15 @@ router.post('/', authenticate, (req, res) => {
// Add this field because I don't want to add into the database // Add this field because I don't want to add into the database
recmsg.source.infoevent = body.source.infoevent; recmsg.source.infoevent = body.source.infoevent;
return await globalTables.sendNotif(res, body.idapp, req.user, recmsg).then((ris) => { recmsg.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS;
recmsg.typeid = shared_consts.TypeNotifs.ID_EVENTS_REMOVE_REC;
return SendNotif.saveAndSendNotif(recmyevent, req, res).then((out) => {
if (out)
return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmsg._id }); return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmsg._id });
else
return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
}) })
}); });
}).catch((e) => { }).catch((e) => {
console.log(e.message); console.log(e.message);

View File

@@ -6,49 +6,24 @@ const server_constants = require('../tools/server_constants');
const {authenticate} = require('../middleware/authenticate'); const {authenticate} = require('../middleware/authenticate');
const {User} = require('../models/user');
const {Operator} = require('../models/operator');
const {SendNotif} = require('../models/sendnotif'); const {SendNotif} = require('../models/sendnotif');
const {ObjectID} = require('mongodb');
const sendemail = require('../sendemail');
const shared_consts = require('../tools/shared_nodejs');
const _ = require('lodash'); const _ = require('lodash');
router.post('/', authenticate, (req, res) => { router.post('/', authenticate, async (req, res) => {
tools.mylog('INIZIO - SendNotif'); tools.mylog('INIZIO - SendNotif');
// tools.mylog('req.body', req.body); // tools.mylog('req.body', req.body);
const body = _.pick(req.body, tools.allfieldSendNotif()); const body = _.pick(req.body, tools.allfieldSendNotif());
tools.mylog('crea SendNotif'); tools.mylog('crea SendNotif');
const myrecnotif = new SendNotif(body); let myrecnotif = new SendNotif(body);
const check = tools.checkUserOk(myrecnotif.sender, req.user.username, res); const recout = await SendNotif.saveAndSendNotif(myrecnotif, req, res);
if (check.exit) return check.ret; if (recout) {
return res.send({code: server_constants.RIS_CODE_OK, notif: '', record: recout});
// console.log('fieldtochange', fieldtochange); } else {
myrecnotif._id = new ObjectID();
return myrecnotif.save().then((writeresult) => {
let idobj = writeresult._id;
myrecnotif._id = idobj;
return SendNotif.findById(idobj).then(async (recnotif) => {
// Add this field because I don't want to add into the database
return await globalTables.sendNotif(res, body.idapp, req.user, recnotif).then((ris) => {
return res.send({code: server_constants.RIS_CODE_OK, notif: '', id: recnotif._id});
});
});
}).catch((e) => {
console.log(e.message);
// res.status(400).send(e);
return res.send({code: server_constants.RIS_CODE_ERR, notif: ''}); return res.send({code: server_constants.RIS_CODE_ERR, notif: ''});
}); }
}); });
@@ -74,6 +49,46 @@ router.get('/setall/:username/:idapp', authenticate, async (req, res) => {
}); });
router.get('/del/:username/:id/:idapp', authenticate, async (req, res) => {
const idapp = req.params.idapp;
const username = req.params.username;
const myid = req.params.id;
const username_call = req.user.username;
try {
if (username === username_call) {
await SendNotif.findOneAndRemove({idapp, _id: myid});
return res.send(true);
}
} catch (e) {
return res.status(400).send(e);
}
return res.send(false);
});
router.get('/delall/:username/:idapp', authenticate, async (req, res) => {
const idapp = req.params.idapp;
const username = req.params.username;
const username_call = req.user.username;
try {
if (username === username_call) {
const ris = await SendNotif.deleteMany({idapp, dest: username});
if (ris)
return res.send(true);
}
} catch (e) {
return res.status(400).send(e);
}
return res.send(false);
});
router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => { router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
tools.mylog('GET NotifS : ', req.params); tools.mylog('GET NotifS : ', req.params);
const username = req.params.username; const username = req.params.username;

View File

@@ -56,6 +56,7 @@ router.post('/', authenticate, (req, res) => {
} else { } else {
myitem.endpoint = subscriptionModel.endpoint; myitem.endpoint = subscriptionModel.endpoint;
myitem.keys = subscriptionModel.keys; myitem.keys = subscriptionModel.keys;
myitem.createDate = new Date();
} }
return myitem.save((err, subscription) => { return myitem.save((err, subscription) => {

View File

@@ -422,10 +422,12 @@ router.post('/panel', authenticate, async (req, res) => {
try { try {
const myuser = await User.findOne({idapp, username}, const myuser = await User.findOne({idapp, username},
{username: 1, email: 1, verified_by_aportador: 1, aportador_solidario: 1, {
username: 1, email: 1, verified_by_aportador: 1, aportador_solidario: 1,
lasttimeonline: 1, lasttimeonline: 1,
deleted: 1, deleted: 1,
profile: 1}).lean(); profile: 1,
}).lean();
if (!!myuser) { if (!!myuser) {
res.send(myuser); res.send(myuser);
} else { } else {
@@ -450,7 +452,6 @@ router.post('/notifs', authenticate, async (req, res) => {
send({code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: ''}); send({code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: ''});
} }
try { try {
if (!!myuser) { if (!!myuser) {
if (tools.isArray(notifs) && notifs.length >= 0) { if (tools.isArray(notifs) && notifs.length >= 0) {
@@ -465,7 +466,6 @@ router.post('/notifs', authenticate, async (req, res) => {
}); });
router.post('/login', (req, res) => { router.post('/login', (req, res) => {
var body = _.pick(req.body, var body = _.pick(req.body,
['username', 'password', 'idapp', 'keyappid', 'lang']); ['username', 'password', 'idapp', 'keyappid', 'lang']);

View File

@@ -28,7 +28,6 @@ require('./db/mongoose');
const {Settings} = require('./models/settings'); const {Settings} = require('./models/settings');
const globalTables = require('./tools/globalTables');
const i18n = require('i18n'); const i18n = require('i18n');
@@ -133,8 +132,13 @@ myLoad().then(ris => {
i18n.configure({ i18n.configure({
locales: ['it', 'enUs', 'es', 'fr', 'pt', 'si'], locales: ['it', 'enUs', 'es', 'fr', 'pt', 'si'],
defaultLocale: 'it',
// cookie: 'cook', // cookie: 'cook',
directory: __dirname + '/locales', directory: __dirname + '/locales',
api: {
'__': 'translate',
'__n': 'translateN'
},
}); });
app.use(cors({ app.use(cors({
@@ -245,6 +249,8 @@ async function mystart() {
// await estraiTutteLeImmagini(); // await estraiTutteLeImmagini();
await tools.getApps();
if (process.env.PROD !== 1) { if (process.env.PROD !== 1) {
testmsgwebpush(); testmsgwebpush();
@@ -266,6 +272,7 @@ async function mystart() {
} }
} }
telegrambot = require('./telegram/telegrambot'); telegrambot = require('./telegram/telegrambot');
await inizia(); await inizia();
@@ -437,6 +444,9 @@ async function estraiImmagini(table) {
let arrlist; let arrlist;
const globalTables = require('./tools/globalTables');
const mytable = globalTables.getTableByTableName(table); const mytable = globalTables.getTableByTableName(table);
if (!mytable) if (!mytable)
return; return;

View File

@@ -3701,6 +3701,8 @@ if (true) {
arrTeleg = appTelegram_TEST; arrTeleg = appTelegram_TEST;
console.log('TELEGRAM STARTING.... NODE_ENV:' + process.env.NODE_ENV); console.log('TELEGRAM STARTING.... NODE_ENV:' + process.env.NODE_ENV);
for (const idapp of arrTeleg) { for (const idapp of arrTeleg) {
try { try {

View File

@@ -574,13 +574,17 @@ module.exports = {
'type', 'type',
'userId', 'userId',
'sender', 'sender',
'typedir',
'typeid',
'dest', 'dest',
'descr', 'descr',
'link', 'openUrl',
'datenotif', 'datenotif',
'read', 'read',
'deleted', 'deleted',
'idapp', 'idapp',
'tablerec',
'idrec',
'status']; 'status'];
}, },
@@ -723,7 +727,7 @@ module.exports = {
}; };
// Pass object into sendNotification // Pass object into sendNotification
return webpush.sendNotification(subscription, JSON.stringify(payload), return webpush.sendNotification(subscription._doc, JSON.stringify(payload),
pushOptions). pushOptions).
catch(err => { catch(err => {
if (err.statusCode === 410) { if (err.statusCode === 410) {
@@ -734,7 +738,7 @@ module.exports = {
} }
}). }).
then(ris => { then(ris => {
// console.log('ris', ris) console.log('sendNotification', ris)
}). }).
catch(err => { catch(err => {
console.error(err); console.error(err);
@@ -1141,8 +1145,7 @@ module.exports = {
getNomeAppByIdApp: function(idapp) { getNomeAppByIdApp: function(idapp) {
const myapp = const myapp = this.MYAPPS.find(item => item.idapp === idapp);
this.getApps().find(item => item.idapp === idapp);
if (myapp) if (myapp)
return ((process.env.NODE_ENV === 'test') ? 'Test: ' : '') + myapp.name; return ((process.env.NODE_ENV === 'test') ? 'Test: ' : '') + myapp.name;
else else
@@ -1161,7 +1164,7 @@ module.exports = {
getHostByIdApp: function(idapp) { getHostByIdApp: function(idapp) {
const myapp = this.getApps().find(item => item.idapp === idapp); const myapp = this.MYAPPS.find(item => item.idapp === idapp);
if (myapp) { if (myapp) {
let siteport = (myapp.portapp && myapp.portapp !== '0') ? (':' + let siteport = (myapp.portapp && myapp.portapp !== '0') ? (':' +
myapp.portapp) : ''; myapp.portapp) : '';
@@ -1185,7 +1188,7 @@ module.exports = {
getConfSiteOptionEnabledByIdApp: function(idapp, option) { getConfSiteOptionEnabledByIdApp: function(idapp, option) {
const myapp = this.getApps().find(item => item.idapp === idapp); const myapp = this.MYAPPS.find(item => item.idapp === idapp);
if (myapp) { if (myapp) {
if (myapp.hasOwnProperty('confsite')) { if (myapp.hasOwnProperty('confsite')) {
@@ -1200,7 +1203,7 @@ module.exports = {
getConfParamSiteByIdApp: function(idapp, field) { getConfParamSiteByIdApp: function(idapp, field) {
const myapp = this.getApps().find(item => item.idapp === idapp); const myapp = this.MYAPPS.find(item => item.idapp === idapp);
if (myapp) { if (myapp) {
if (myapp.hasOwnProperty('confsite')) { if (myapp.hasOwnProperty('confsite')) {
@@ -1214,7 +1217,7 @@ module.exports = {
}, },
isAbilitaNave: function(idapp) { isAbilitaNave: function(idapp) {
const myapp = this.getApps().find(item => item.idapp === idapp); const myapp = this.MYAPPS.find(item => item.idapp === idapp);
return myapp.abilitanave; return myapp.abilitanave;
}, },
@@ -1222,7 +1225,7 @@ module.exports = {
let mypath = ''; let mypath = '';
const myapp = const myapp =
this.getApps().find(item => item.idapp === idapp); this.MYAPPS.find(item => item.idapp === idapp);
if (myapp) { if (myapp) {
if (process.env.NODE_ENV === 'test') if (process.env.NODE_ENV === 'test')
mypath = (myapp) ? myapp.dir_test : ''; mypath = (myapp) ? myapp.dir_test : '';
@@ -1240,7 +1243,7 @@ module.exports = {
}, },
getAdminEmailByIdApp: function(idapp) { getAdminEmailByIdApp: function(idapp) {
const myapp = this.getApps().find((item) => item.idapp === idapp); const myapp = this.MYAPPS.find((item) => item.idapp === idapp);
if (myapp) if (myapp)
return myapp.adminemail; return myapp.adminemail;
else else
@@ -1248,7 +1251,7 @@ module.exports = {
}, },
getreplyToEmailByIdApp: function(idapp) { getreplyToEmailByIdApp: function(idapp) {
const myapp = this.getApps().find((item) => item.idapp === idapp); const myapp = this.MYAPPS.find((item) => item.idapp === idapp);
if (myapp) if (myapp)
return myapp.replyTo; return myapp.replyTo;
else else
@@ -1256,7 +1259,7 @@ module.exports = {
}, },
getpathregByIdApp: function(idapp, lang) { getpathregByIdApp: function(idapp, lang) {
const myapp = this.getApps().find((item) => item.idapp === idapp); const myapp = this.MYAPPS.find((item) => item.idapp === idapp);
if (myapp) { if (myapp) {
const addstr = myapp.pathreg_add ? myapp.pathreg_add : ''; const addstr = myapp.pathreg_add ? myapp.pathreg_add : '';
@@ -1276,7 +1279,7 @@ module.exports = {
}, },
getManagerEmailByIdApp: function(idapp) { getManagerEmailByIdApp: function(idapp) {
const myapp = this.getApps().find((item) => item.idapp === idapp); const myapp = this.MYAPPS.find((item) => item.idapp === idapp);
if (myapp) if (myapp)
return !!myapp.manageremail ? myapp.manageremail : ''; return !!myapp.manageremail ? myapp.manageremail : '';
else else
@@ -1284,17 +1287,17 @@ module.exports = {
}, },
getEmailByIdApp: function(idapp) { getEmailByIdApp: function(idapp) {
const myapp = this.getApps().find((item) => item.idapp === idapp); const myapp = this.MYAPPS.find((item) => item.idapp === idapp);
return (myapp) ? myapp.email_from : ''; return (myapp) ? myapp.email_from : '';
}, },
getPwdByIdApp: function(idapp) { getPwdByIdApp: function(idapp) {
const myapp = this.getApps().find((item) => item.idapp === idapp); const myapp = this.MYAPPS.find((item) => item.idapp === idapp);
return (myapp) ? this.decryptdata(myapp.email_pwd) : ''; return (myapp) ? this.decryptdata(myapp.email_pwd) : '';
}, },
getTelegramBotNameByIdApp: function(idapp) { getTelegramBotNameByIdApp: function(idapp) {
const myapp = this.getApps().find((item) => item.idapp === idapp); const myapp = this.MYAPPS.find((item) => item.idapp === idapp);
if (process.env.NODE_ENV === 'test') if (process.env.NODE_ENV === 'test')
return (myapp) ? myapp.telegram_bot_name_test : ''; return (myapp) ? myapp.telegram_bot_name_test : '';
else else
@@ -1303,7 +1306,7 @@ module.exports = {
getTelegramSupportChat: function(idapp) { getTelegramSupportChat: function(idapp) {
try { try {
const myapp = this.getApps().find((item) => item.idapp === idapp); const myapp = this.MYAPPS.find((item) => item.idapp === idapp);
return (myapp && myapp.telegram_support_chat) return (myapp && myapp.telegram_support_chat)
? myapp.telegram_support_chat ? myapp.telegram_support_chat
: ''; : '';
@@ -1313,8 +1316,7 @@ module.exports = {
}, },
getTelegramKeyByIdApp: function(idapp) { getTelegramKeyByIdApp: function(idapp) {
const myarr = this.getApps(); const myapp = this.MYAPPS.find((item) => item.idapp === idapp);
const myapp = myarr.find((item) => item.idapp === idapp);
if (process.env.NODE_ENV === 'test') if (process.env.NODE_ENV === 'test')
return (myapp) ? myapp.telegram_key_test : ''; return (myapp) ? myapp.telegram_key_test : '';
else else
@@ -2750,12 +2752,16 @@ module.exports = {
}, },
async loadApps() { async loadApps() {
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) {
console.error('loadApps', e);
}
}, },
getApps() { async getApps() {
if (this.MYAPPS.length <= 0) if (this.MYAPPS.length <= 0)
this.loadApps(); await this.loadApps();
return this.MYAPPS; return this.MYAPPS;
}, },
@@ -2936,6 +2942,8 @@ module.exports = {
}, },
updateQueryStringParameter(uri, key, value) { updateQueryStringParameter(uri, key, value) {
if (uri === '')
return '';
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"); var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?"; var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) { if (uri.match(re)) {

View File

@@ -74,7 +74,6 @@ const tools = require('./general');
const shared_consts = require('./shared_nodejs'); const shared_consts = require('./shared_nodejs');
const sendemail = require('../sendemail');
module.exports = { module.exports = {
@@ -217,30 +216,38 @@ module.exports = {
return process.env.ENABLE_PUSHNOTIFICATION === '1'; return process.env.ENABLE_PUSHNOTIFICATION === '1';
}, },
async sendNotif(res, idapp, user, recnotif, cmd) { async sendNotif(typenotif, idnotif, res, idapp, user, recnotif, cmd) {
// Controlla nelle impostazioni che tipo di Notifica visualizzare // Controlla nelle impostazioni che tipo di Notifica visualizzare
const sendemail = require('../sendemail');
try {
if (!recnotif.options) {
recnotif.options = shared_consts.MessageOptions.Notify_ByPushNotification;
}
if (tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByPushNotification)) { if (tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByPushNotification)) {
if (this.checkifSendPushNotification) { if (this.checkifSendPushNotification) {
console.log('SEND PUSH NOTIFICATION ');
const params = { const params = {
sendreally: true, sendreally: true,
typesend: shared_consts.TypeSend.PUSH_NOTIFICATION, typesend: shared_consts.TypeSend.PUSH_NOTIFICATION + shared_consts.TypeSend.TELEGRAM,
title: this.getNomeAppByIdApp(idapp), title: tools.getNomeAppByIdApp(idapp),
content: recnotif.descr ? recnotif.descr : tools.getContentByTypeMsg(recnotif.typemsg), content: recnotif.descr ? recnotif.descr : tools.getContentByTypeMsg(recnotif.typemsg),
openUrl: tools.updateQueryStringParameter(recnotif.link, 'idnotif', recnotif._id), openUrl: tools.updateQueryStringParameter(recnotif.openUrl, 'idnotif', recnotif._id),
typemsg: recnotif.typemsg ? recnotif.typemsg : shared_consts.TypeMsg.SEND_TO_USER, 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); ris = await this.SendMsgToParam(idapp, params);
recnotif.link = mylink;
} }
} }
// Send Msg by EMAIL // Send Msg by EMAIL
if (emaildest && tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByEmail)) { if (tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByEmail)) {
// Read from the operator table first // Read from the operator table first
let emaildest = await Operator.getEmailByUsername(recnotif.dest.idapp, recnotif.dest.username); let emaildest = await Operator.getEmailByUsername(recnotif.dest.idapp, recnotif.dest.username);
if (!emaildest) if (!emaildest)
@@ -252,11 +259,17 @@ module.exports = {
} }
return true; return true;
} catch (e) {
console.error('sendNotif', e, typenotif, recnotif);
return false;
}
}, },
SendMsgToParam: async function(idapp, params) { SendMsgToParam: async function(idapp, params) {
try { try {
console.log('SendMsgToParam');
const telegrambot = require('../telegram/telegrambot'); const telegrambot = require('../telegram/telegrambot');
if (params.typesend === 0) if (params.typesend === 0)
@@ -343,7 +356,8 @@ module.exports = {
console.error(e.message); console.error(e.message);
}); });
} else if (tools.isBitActive(params.typesend, shared_consts.TypeSend.TELEGRAM)) { }
if (tools.isBitActive(params.typesend, shared_consts.TypeSend.TELEGRAM)) {
const telegid = user.profile.teleg_id; const telegid = user.profile.teleg_id;
if (telegid > 0) { if (telegid > 0) {

View File

@@ -108,6 +108,9 @@ module.exports = {
TABLES_VISU_STAT_IN_HOME: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'mygroups'], TABLES_VISU_STAT_IN_HOME: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'mygroups'],
TABLES_ADV_NOTIFICATION: ['myskills', 'myhosps', 'mygoods'],
TABLES_EVENTS_NOTIFICATION: ['mybachecas'],
TABLES_ID_NUMBER: [ TABLES_ID_NUMBER: [
'permissions', 'permissions',
'levels', 'levels',
@@ -273,8 +276,38 @@ module.exports = {
PUSH_NOTIFICATION: 1, PUSH_NOTIFICATION: 1,
TELEGRAM: 2, TELEGRAM: 2,
}, },
UsersNotif: {
NEW_ADV_CITY: 1,
NEW_ADV_PROVINCE: 2,
NEW_ADV_REGION: 4,
NEW_ADV_MY_GROUPS: 8,
NEW_ADV_MY_RIS_CIRCUIT: 16,
NEW_ADV_SECTOR: 32,
},
TypeNotifs: {
TYPEDIR_BACHECA: 1,
ID_BACHECA_NEW_GOOD: 1,
ID_BACHECA_NEW_SERVICE: 2,
TYPEDIR_EVENTS: 2,
ID_EVENTS_NEW_REC: 1,
ID_EVENTS_REMOVE_REC: 2,
TYPEDIR_FRIENDS: 3,
ID_FRIENDS_NEW_REC: 1,
TYPEDIR_CIRCUITS: 4,
TYPEDIR_BOOKING: 5,
TYPEDIR_MSGS: 6,
ID_MSGS_NEW_REC: 1,
},
// Tipi di Notifiche: // Tipi di Notifiche:
/*
Notif: { Notif: {
UPDATE_APP: 1, UPDATE_APP: 1,
NEW_GOOD_MY_PROVINCE: 12, NEW_GOOD_MY_PROVINCE: 12,
@@ -292,6 +325,8 @@ module.exports = {
RIS_SENT_REFUSED: 52, RIS_SENT_REFUSED: 52,
}, },
*/
fieldsUserToChange() { fieldsUserToChange() {
return [ return [