Notification system enhanced

- Base for notifcation center
- Show text in map if no data is available
This commit is contained in:
2020-11-21 14:11:26 +01:00
parent 8b54431449
commit 533749c7c8
26 changed files with 323 additions and 76 deletions

View File

@@ -1,7 +1,12 @@
import * as amqp from 'amqplib';
import { Schema, SchemaType } from 'mongoose';
import { logger, RABBITMQ_URI } from '../app';
import { Beat } from '../models/beat/beat.model.';
import { ISeverity, NotificationType } from '../models/notifications/notification.interface';
import { addNotification, Notification } from '../models/notifications/notification.model';
import { IPhone } from '../models/phone/phone.interface';
import { Phone } from '../models/phone/phone.model';
import { User } from '../models/user/user.model';
interface IBeat {
token: string,
@@ -14,7 +19,7 @@ export class RabbitMQ {
connection: amqp.Connection | null = null;
channel: amqp.Channel | null = null;
timeouts: Map<string, Timeout> = new Map<string, Timeout>();
timeouts: Map<string, NodeJS.Timeout> = new Map<string, NodeJS.Timeout>();
async init() {
this.connection = await amqp.connect(RABBITMQ_URI);
@@ -46,16 +51,15 @@ export class RabbitMQ {
// Broadcast if device became active
if (this.timeouts.has(phone.id)) {
clearTimeout(this.timeouts.get(phone.id));
clearTimeout(this.timeouts.get(phone.id)!!);
} else {
logger.debug('Set phone active');
phone.active = true;
await phone.save();
this.publish(phone.user.toString(), phone.toJSON(), 'phone_alive');
this.publish(phone.user.toString(), phone.toJSON(), 'phone_alive', ISeverity.SUCCESS);
}
const timeoutTimer = setTimeout(async () => {
this.publish(phone.user.toString(), phone.toJSON(), 'phone_dead');
this.publish(phone.user.toString(), phone.toJSON(), 'phone_dead', ISeverity.WARN);
this.timeouts.delete(phone.id);
phone.active = false;
await phone.save();
@@ -66,10 +70,22 @@ export class RabbitMQ {
}, { noAck: true });
}
async publish(userId: string, data: any, type: 'beat' | 'phone_alive' | 'phone_dead' | 'phone_register' | 'panic' = 'beat') {
if (this.connection == undefined) await this.init()
async publish(userId: string, data: any, type: NotificationType, severity = ISeverity.INFO) {
if (this.connection == undefined) await this.init();
data = { type, ...data };
const user = await User.findById(userId);
if (user === null) return;
/* Manage notifications */
if (type != 'beat') {
if (type == 'phone_alive' || type == 'phone_dead') {
addNotification(type, severity, ((data as IPhone)._id), user);
}
}
data = { type, severity, ...data };
console.log('Send:', data);
this.channel?.publish('amq.topic', userId, Buffer.from(JSON.stringify(data)));
}
}