Devices can now subscribe to specific topics.
- Device can now become (in)active - Error alert makes sound - Alerts now execute function on click
This commit is contained in:
@@ -14,6 +14,8 @@ export class RabbitMQ {
|
||||
connection: amqp.Connection | null = null;
|
||||
channel: amqp.Channel | null = null;
|
||||
|
||||
timeouts: Map<string, Timeout> = new Map<string, Timeout>();
|
||||
|
||||
async init() {
|
||||
this.connection = await amqp.connect(RABBITMQ_URI);
|
||||
this.channel = await this.connection.createChannel();
|
||||
@@ -26,7 +28,7 @@ export class RabbitMQ {
|
||||
// Get phone
|
||||
const phone = await Phone.findOne({ androidId: msg.token });
|
||||
if (phone == undefined) {
|
||||
logger.info(`Received beat from unknown device with id ${msg.token}`);
|
||||
logger.warning(`Received beat from unknown device with id ${msg.token}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -41,13 +43,33 @@ export class RabbitMQ {
|
||||
battery: msg.battery,
|
||||
createdAt: msg.timestamp
|
||||
});
|
||||
|
||||
// Broadcast if device became active
|
||||
if (this.timeouts.has(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');
|
||||
}
|
||||
|
||||
const timeoutTimer = setTimeout(async () => {
|
||||
this.publish(phone.user.toString(), phone.toJSON(), 'phone_dead');
|
||||
this.timeouts.delete(phone.id);
|
||||
phone.active = false;
|
||||
await phone.save();
|
||||
}, 30_000);
|
||||
this.timeouts.set(phone.id, timeoutTimer);
|
||||
|
||||
this.channel!.publish('amq.topic', '.', Buffer.from(JSON.stringify(newBeat.toJSON())));
|
||||
this.publish(phone.user.toString(), newBeat.toJSON(), 'beat');
|
||||
}, { noAck: true });
|
||||
}
|
||||
|
||||
async publish(queueName = 'tracker', data: any) {
|
||||
async publish(userId: string, data: any, type: 'beat' | 'phone_alive' | 'phone_dead' | 'phone_register' | 'panic' = 'beat') {
|
||||
if (this.connection == undefined) await this.init()
|
||||
this.channel?.sendToQueue(queueName, Buffer.from(data));
|
||||
|
||||
data = { type, ...data };
|
||||
this.channel?.publish('amq.topic', userId, Buffer.from(JSON.stringify(data)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user