maestri-remote/src/relay/push-service.js

83 lines
2.3 KiB
JavaScript

import webpush from 'web-push';
import fs from 'node:fs';
import path from 'node:path';
export class PushService {
constructor(options = {}) {
this.keysFile = options.keysFile || path.resolve('vapid-keys.json');
this.subscriptions = new Map(); // pin -> Set<subscription>
this.initVapid();
}
initVapid() {
let vapidKeys;
if (fs.existsSync(this.keysFile)) {
try {
vapidKeys = JSON.parse(fs.readFileSync(this.keysFile, 'utf8'));
} catch (err) {
console.warn('[Relay:PushService] Erro ao ler chaves VAPID existentes, gerando novas.');
}
}
if (!vapidKeys || !vapidKeys.publicKey || !vapidKeys.privateKey) {
vapidKeys = webpush.generateVAPIDKeys();
try {
fs.writeFileSync(this.keysFile, JSON.stringify(vapidKeys, null, 2));
} catch (err) {
// Ignora se read-only
}
}
this.vapidKeys = vapidKeys;
webpush.setVapidDetails(
'mailto:admin@winicomw.ddnsfree.com',
this.vapidKeys.publicKey,
this.vapidKeys.privateKey
);
console.log('[Relay:PushService] VAPID configurado com sucesso');
}
getPublicKey() {
return this.vapidKeys.publicKey;
}
addSubscription(pin, subscription) {
if (!pin || !subscription || !subscription.endpoint) return;
if (!this.subscriptions.has(pin)) {
this.subscriptions.set(pin, new Set());
}
this.subscriptions.get(pin).add(JSON.stringify(subscription));
console.log(`[Relay:PushService] Nova subscrição de push registrada para o PIN ${pin}`);
}
async sendNotification(pin, { title, body, data = {} }) {
const subs = this.subscriptions.get(pin);
if (!subs || subs.size === 0) return;
const payload = JSON.stringify({
title: title || 'Maestri Remote',
body: body || 'Novo prompt aguardando sua resposta',
data,
timestamp: Date.now()
});
const deadSubs = [];
for (const subStr of subs) {
try {
const sub = JSON.parse(subStr);
await webpush.sendNotification(sub, payload);
} catch (err) {
if (err.statusCode === 410 || err.statusCode === 404) {
deadSubs.push(subStr);
} else {
console.error('[Relay:PushService] Erro ao enviar push notification:', err.message);
}
}
}
for (const dead of deadSubs) {
subs.delete(dead);
}
}
}