Notifiche - Tutti - non letti

This commit is contained in:
Paolo Arena
2022-07-21 00:21:03 +02:00
parent cbd65ccdbe
commit e9ce597027
10 changed files with 235 additions and 177 deletions

View File

@@ -1,14 +1,14 @@
const mongoose = require('mongoose').set('debug', false)
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
mongoose.level = 'F';
const { ObjectID } = require('mongodb');
const {ObjectID} = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
schema.options.usePushEach = true;
});
const sendNotifSchema = new Schema({
@@ -27,6 +27,9 @@ const sendNotifSchema = new Schema({
descr: {
type: String,
},
link: {
type: String,
},
datenotif: {
type: Date,
},
@@ -35,36 +38,62 @@ const sendNotifSchema = new Schema({
},
read: {
type: Boolean,
default: false
default: false,
},
deleted: {
type: Boolean,
default: false
default: false,
},
});
sendNotifSchema.statics.setNotifAsRead = function(idapp, username, idnotif) {
const SendNotif = this;
try {
sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function (username, lastdataread, idapp) {
if (idnotif) {
return SendNotif.findOneAndUpdate({
$and: [
{idapp},
{dest: username},
{'_id': idnotif},
],
$or: [
{deleted: {$exists: false}},
{deleted: {$exists: true, $eq: false}}],
}, {$set: {read: true}}, {new: false}).then((ret) => {
return !!ret;
}).catch((err) => {
console.error('err', err);
});
}
}catch (e) {
return false;
}
};
sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function(username, lastdataread, idapp) {
const SendNotif = this;
return SendNotif.find({
$and: [
{ idapp },
{ 'dest': username },
{ 'datenotif': {$gt: new Date(lastdataread)} },
]
}).then((arrnotif) => {
{idapp},
{'dest': username},
{'datenotif': {$gt: new Date(lastdataread)}},
],
}).lean().sort({datenotif: -1}).then((arrnotif) => {
console.log('arrnotif', arrnotif.length);
return arrnotif
return arrnotif;
}).catch((err) => {
console.error('err', err);
});
};
sendNotifSchema.statics.findLastGroupByUserIdAndIdApp = function (username, idapp) {
sendNotifSchema.statics.findLastGroupByUserIdAndIdApp = function(username, idapp) {
const SendNotif = this;
return SendNotif.aggregate([
@@ -72,36 +101,34 @@ sendNotifSchema.statics.findLastGroupByUserIdAndIdApp = function (username, idap
$match: {
idapp,
dest: username,
}
},
},
{
$group:
{
_id: "$dest",
descr: { $last: "$message" },
datenotif: { $last: "$datenotif" },
read: { $last: "$read" }
}
{
_id: '$dest',
descr: {$last: '$message'},
datenotif: {$last: '$datenotif'},
read: {$last: '$read'},
},
},
{
$sort: { datenotif: -1 }
$sort: {datenotif: -1},
},
])
.then((arrnotif) => {
// Remove duplicate
// Exclude my chat
const myarr = arrnotif.filter((ris) => ris._id !== username);
// console.table(myarr);
return myarr
]).then((arrnotif) => {
// Remove duplicate
// Exclude my chat
const myarr = arrnotif.filter((ris) => ris._id !== username);
// console.table(myarr);
return myarr;
}).catch((err) => {
console.error(err);
});
}).catch((err) => {
console.error(err);
});
};
const SendNotif = mongoose.model('SendNotif', sendNotifSchema);
module.exports = { SendNotif: SendNotif };
module.exports = {SendNotif: SendNotif};

View File

@@ -358,10 +358,13 @@ const UserSchema = new mongoose.Schema({
date: {type: Date},
}], // username
notifs: {
type: Number,
default: 1,
},
notifs: [
{
_id: false,
dir: {type: Number},
value: {type: Number},
},
],
},
})
;
@@ -1350,7 +1353,7 @@ UserSchema.statics.getUserProfileByUsername = async function(
verified_email: 1,
verified_by_aportador: 1,
'profile.nationality': 1,
"profile.mygroups": 1,
'profile.mygroups': 1,
'profile.qualifica': 1,
'profile.biografia': 1,
'profile.teleg_id': 1,
@@ -1384,7 +1387,7 @@ UserSchema.statics.getUserProfileByUsername = async function(
verified_by_aportador: 1,
notask_verif: 1,
'profile.nationality': 1,
"profile.mygroups": 1,
'profile.mygroups': 1,
'profile.qualifica': 1,
'profile.biografia': 1,
'profile.teleg_id': 1,
@@ -1774,7 +1777,6 @@ UserSchema.statics.setGroupsCmd = async function(idapp, usernameOrig, groupnameD
ris = await MyGroup.deleteGroup(idapp, usernameOrig, groupnameDest); // Rimuovo l'Amicizia da me
console.log('ris', ris);
} else if (cmd === shared_consts.GROUPSCMD.CANCEL_REQ_GROUP) {
ris = await MyGroup.removeReqGroup(idapp, usernameOrig, groupnameDest); // Rimuovo l'Amicizia da me
@@ -1814,7 +1816,7 @@ function getWhatToShow(idapp, username) {
verified_by_aportador: 1,
notask_verif: 1,
'profile.nationality': 1,
"profile.mygroups": 1,
'profile.mygroups': 1,
'profile.qualifica': 1,
'profile.biografia': 1,
'profile.username_telegram': 1,
@@ -2706,8 +2708,8 @@ UserSchema.statics.getUsersAutorizzare = async function(idapp) {
const myfind = {
idapp,
$or: [{deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}],
'profile.teleg_id': { $gt: 0 },
verified_by_aportador: { $exists: false },
'profile.teleg_id': {$gt: 0},
verified_by_aportador: {$exists: false},
};
return User.count(myfind);

View File

@@ -14,7 +14,7 @@ const sendemail = require('../sendemail');
const _ = require('lodash');
const sendNotif = async (res, idapp, user, recbooking) => {
const sendNotifBooking = async (res, idapp, user, recbooking) => {
//++Todo: tools.sendNotificationToUser
// Send Email
@@ -50,7 +50,7 @@ router.post('/', authenticate, (req, res) => {
}).then((recbooking) => {
// tools.mylog('booking:', booking);
// tools.mylog('already exist');
sendNotif(res, myrec.idapp, req.user, myrec);
sendNotifBooking(res, myrec.idapp, req.user, myrec);
return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id });
});
} else {
@@ -62,7 +62,7 @@ router.post('/', authenticate, (req, res) => {
Booking.findById(idobj)
.then((recbooking) => {
sendNotif(res, myrec.idapp, req.user, writeresult);
sendNotifBooking(res, myrec.idapp, req.user, writeresult);
return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: writeresult._id });
});
});
@@ -86,7 +86,7 @@ router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
if (notify === '1') {
recbooking.booked = false;
sendNotif(res, idapp, req.user, recbooking);
sendNotifBooking(res, idapp, req.user, recbooking);
}
tools.mylog('DELETED ', recbooking._id);

View File

@@ -4,14 +4,16 @@ const router = express.Router();
const tools = require('../tools/general');
const server_constants = require('../tools/server_constants');
const { authenticate } = require('../middleware/authenticate');
const {authenticate} = require('../middleware/authenticate');
const { MyEvent } = require('../models/myevent');
const {MyEvent} = require('../models/myevent');
const { ObjectID } = require('mongodb');
const {ObjectID} = require('mongodb');
const sendemail = require('../sendemail');
const globalTables = require('../tools/globalTables');
const _ = require('lodash');
router.post('/', authenticate, (req, res) => {
@@ -29,36 +31,34 @@ router.post('/', authenticate, (req, res) => {
if (check.exit) return check.ret;
// Modify:
return MyEvent.findOne({ id })
.then((trovato) => {
// console.log('trovato', trovato);
if (trovato) {
return myevent.findOneAndUpdate({ id }, { $set: fieldtochange }, {
new: false,
upsert: true
}).then((recmyevent) => {
// tools.mylog('myevent:', myevent);
// tools.mylog('already exist');
sendNotif(res, myrec.idapp, req.user, recmyevent);
return res
}).then((res) => {
res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id });
});
} else {
// save to database a new record
tools.mylog('save to database a new record');
myevent._id = new ObjectID();
return myevent.save().then((writeresult) => {
let idobj = writeresult._id;
return MyEvent.findOne({id}).then((trovato) => {
// console.log('trovato', trovato);
if (trovato) {
return myevent.findOneAndUpdate({id}, {$set: fieldtochange}, {
new: false,
upsert: true,
}).then((recmyevent) => {
// tools.mylog('myevent:', myevent);
// tools.mylog('already exist');
globalTables.sendNotif(res, myrec.idapp, req.user, recmyevent);
return res;
}).then((res) => {
res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id});
});
} else {
// save to database a new record
tools.mylog('save to database a new record');
myevent._id = new ObjectID();
return myevent.save().then((writeresult) => {
let idobj = writeresult._id;
myevent.findById(idobj)
.then((recmyevent) => {
sendNotif(res, myrec.idapp, req.user, recmyevent);
res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id });
});
myevent.findById(idobj).then((recmyevent) => {
globalTables.sendNotif(res, myrec.idapp, req.user, recmyevent);
res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id});
});
}
})
});
}
});
});
router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
@@ -73,18 +73,17 @@ router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
}
if (notify === '1')
sendNotif(res, idapp, req.user, recmyevent);
globalTables.sendNotif(res, idapp, req.user, recmyevent);
tools.mylog('DELETED ', recmyevent.descr, recmyevent._id);
res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id });
res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id});
}).catch((e) => {
res.status(400).send();
});
});
router.get('/:userId/:idapp/:sall', authenticate, (req, res) => {
const userId = req.params.userId;
const idapp = req.params.idapp;
@@ -99,12 +98,12 @@ router.get('/:userId/:idapp/:sall', authenticate, (req, res) => {
if (userId !== String(req.user._id)) {
// I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
return res.status(404).send({code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER});
}
// Extract all the todos of the userId only
return MyEvent.findAllByUserIdAndIdApp(userId, idapp, sall).then((recevent) => {
res.send({ recevent });
res.send({recevent});
}).catch((e) => {
console.log(e.message);
res.status(400).send(e);
@@ -112,5 +111,4 @@ router.get('/:userId/:idapp/:sall', authenticate, (req, res) => {
});
module.exports = router;

View File

@@ -131,16 +131,12 @@ router.post('/send', authenticate, async (req, res) => {
}
try {
if (params.typesend === 0)
params.typesend = shared_consts.TypeSend.PUSH_NOTIFICATION;
if (params.typemsg === shared_consts.TypeMsg.SEND_TO_MYSELF) {
params.usernameDest = req.user.username;
}
const ris = await globalTables.SendMsgToParam(idapp, params);
return res.send({
code: server_constants.RIS_CODE_OK,
msg: ris.nummsgsent + ` Msg ${msgcosa} su ` + ris.numrec + ' !',

View File

@@ -16,36 +16,10 @@ const sendemail = require('../sendemail');
const shared_consts = require('../tools/shared_nodejs');
const globalTables = require('../tools/globalTables');
const _ = require('lodash');
function checkifSendPushNotification() {
return process.env.ENABLE_PUSHNOTIFICATION === "1";
//return false;
}
async function sendNotif(res, idapp, user, recmsg) {
if (tools.isBitActive(recmsg.options, shared_consts.MessageOptions.Notify_ByPushNotification)) {
if (this.checkifSendPushNotification) {
console.log('SEND PUSH NOTIFICATION ')
//++Todo: tools.sendNotificationToUser
}
}
// Read from the operator table first
let emaildest = await Operator.getEmailByUsername(recmsg.dest.idapp, recmsg.dest.username);
if (!emaildest)
emaildest = await User.getEmailByUsername(recmsg.dest.idapp, recmsg.dest.username);
console.log('emaildest', emaildest);
// Send Msg by EMAIL
if (emaildest && tools.isBitActive(recmsg.options, shared_consts.MessageOptions.Notify_ByEmail))
await sendemail.sendEmail_Msg(res, user.lang, emaildest, user, idapp, recmsg);
return true
}
router.post('/', authenticate, (req, res) => {
tools.mylog('INIZIO - SendMsg');
@@ -72,7 +46,7 @@ router.post('/', authenticate, (req, res) => {
// Add this field because I don't want to add into the database
recmsg.source.infoevent = body.source.infoevent;
return await sendNotif(res, body.idapp, req.user, recmsg).then((ris) => {
return await globalTables.sendNotif(res, body.idapp, req.user, recmsg).then((ris) => {
return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmsg._id });
})
});

View File

@@ -4,13 +4,13 @@ const router = express.Router();
const tools = require('../tools/general');
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 {User} = require('../models/user');
const {Operator} = require('../models/operator');
const {SendNotif} = require('../models/sendnotif');
const { ObjectID } = require('mongodb');
const {ObjectID} = require('mongodb');
const sendemail = require('../sendemail');
@@ -18,33 +18,6 @@ const shared_consts = require('../tools/shared_nodejs');
const _ = require('lodash');
async function sendNotif(res, idapp, user, recnotif) {
// Controlla nelle impostazioni che tipo di Notifica visualizzare
if (tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByPushNotification)) {
if (this.checkifSendPushNotification) {
console.log('SEND PUSH NOTIFICATION ')
//++Todo: tools.sendNotificationToUser
}
}
// Read from the operator table first
let emaildest = await Operator.getEmailByUsername(recnotif.dest.idapp, recnotif.dest.username);
if (!emaildest)
emaildest = await User.getEmailByUsername(recnotif.dest.idapp, recnotif.dest.username);
console.log('emaildest', emaildest);
// Send Msg by EMAIL
if (emaildest && tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByEmail))
await sendemail.sendEmail_Msg(res, user.lang, emaildest, user, idapp, recnotif);
return true
}
router.post('/', authenticate, (req, res) => {
tools.mylog('INIZIO - SendNotif');
// tools.mylog('req.body', req.body);
@@ -59,25 +32,45 @@ router.post('/', authenticate, (req, res) => {
// console.log('fieldtochange', fieldtochange);
myrecnotif._id = new ObjectID();
return myrecnotif.save()
.then((writeresult) => {
let idobj = writeresult._id;
return myrecnotif.save().then((writeresult) => {
let idobj = writeresult._id;
myrecnotif._id = idobj;
myrecnotif._id = idobj;
return SendNotif.findById(idobj)
.then(async (recnotif) => {
// Add this field because I don't want to add into the database
return SendNotif.findById(idobj).then(async (recnotif) => {
// Add this field because I don't want to add into the database
return await 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 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: ''});
});
});
router.get('/setall/: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 arrNotifs = await SendNotif.find({idapp, dest: username, read: false}).lean();
if (arrNotifs) {
for (const rec of arrNotifs) {
await SendNotif.setNotifAsRead(idapp, username_call, rec._id);
}
}
res.send(true);
}
} catch (e) {
res.status(400).send(e);
}
});
@@ -90,15 +83,14 @@ router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
if (req.user.idapp !== idapp) {
// I'm trying to get something not mine!
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) => {
// const wait = new Promise((resolve, reject) => {
// setTimeout(() => {
res.send({ arrnotif });
res.send({arrnotif});
// }, 2000);
// });
@@ -109,5 +101,4 @@ router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
});
module.exports = router;

View File

@@ -15,6 +15,8 @@ const sendemail = require('../sendemail');
const {Settings} = require('../models/settings');
const {SendNotif} = require('../models/sendnotif');
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
@@ -377,11 +379,15 @@ router.patch('/:id', authenticate, (req, res) => {
router.post('/profile', authenticate, (req, res) => {
const username = req.body['username'];
idapp = req.body.idapp;
locale = req.body.locale;
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);
try {
return User.getUserProfileByUsername(idapp, username, req.user.username,
false, req.user.perm).
@@ -447,7 +453,7 @@ router.post('/notifs', authenticate, async (req, res) => {
try {
if (!!myuser) {
if (notifs) {
if (tools.isArray(notifs) && notifs.length >= 0) {
myuser.profile.notifs = notifs;
myuser.save();
}

View File

@@ -576,6 +576,7 @@ module.exports = {
'sender',
'dest',
'descr',
'link',
'datenotif',
'read',
'deleted',
@@ -2934,4 +2935,22 @@ module.exports = {
return mystr;
},
updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
return uri + separator + key + "=" + value;
}
},
isArray(val) {
return Array.isArray(val)
},
getContentByTypeMsg (typemsg) {
},
};

View File

@@ -74,6 +74,8 @@ const tools = require('./general');
const shared_consts = require('./shared_nodejs');
const sendemail = require('../sendemail');
module.exports = {
getTableByTableName(tablename) {
@@ -211,11 +213,55 @@ module.exports = {
return mytable;
},
checkifSendPushNotification() {
return process.env.ENABLE_PUSHNOTIFICATION === '1';
},
async sendNotif(res, idapp, user, recnotif, cmd) {
// Controlla nelle impostazioni che tipo di Notifica visualizzare
if (tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByPushNotification)) {
if (this.checkifSendPushNotification) {
console.log('SEND PUSH NOTIFICATION ');
const params = {
sendreally: true,
typesend: shared_consts.TypeSend.PUSH_NOTIFICATION,
title: this.getNomeAppByIdApp(idapp),
content: recnotif.descr ? recnotif.descr : tools.getContentByTypeMsg(recnotif.typemsg),
openUrl: tools.updateQueryStringParameter(recnotif.link, 'idnotif', recnotif._id),
typemsg: recnotif.typemsg ? recnotif.typemsg : shared_consts.TypeMsg.SEND_TO_USER,
}
ris = await this.SendMsgToParam(idapp, params);
recnotif.link = mylink;
}
}
// Send Msg by EMAIL
if (emaildest && tools.isBitActive(recnotif.options, shared_consts.MessageOptions.Notify_ByEmail)) {
// Read from the operator table first
let emaildest = await Operator.getEmailByUsername(recnotif.dest.idapp, recnotif.dest.username);
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);
}
return true;
},
SendMsgToParam: async function(idapp, params) {
try {
const telegrambot = require('../telegram/telegrambot');
if (params.typesend === 0)
params.typesend = shared_consts.TypeSend.PUSH_NOTIFICATION;
let query = {idapp};
let addquery = {};
@@ -249,8 +295,8 @@ module.exports = {
addquery = {
'profile.teleg_id': {$gt: 1},
'profile.username_telegram': {$exists: true},
$expr: { $gt: [ { $strLenCP: "$profile.username_telegram" }, 3 ] },
'verified_by_aportador': {$exists: false}
$expr: {$gt: [{$strLenCP: '$profile.username_telegram'}, 3]},
'verified_by_aportador': {$exists: false},
};
} else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_GROUP) {
if (params.groupnameDest) {
@@ -287,8 +333,7 @@ module.exports = {
let risult = null;
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,
params.actions).
then(ris => {