216 lines
6.7 KiB
JavaScript
216 lines
6.7 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.fcmTokens = new Map(); // pin/stationId -> Set<deviceToken>
|
|
this.fcmDispatcher = options.fcmDispatcher || null;
|
|
this.fcmServiceAccount = this.loadServiceAccount(options.fcmServiceAccount);
|
|
this.initVapid();
|
|
}
|
|
|
|
loadServiceAccount(customAccount) {
|
|
if (customAccount) return customAccount;
|
|
const envJson = process.env.FCM_SERVICE_ACCOUNT_JSON;
|
|
if (envJson) {
|
|
try {
|
|
return JSON.parse(envJson);
|
|
} catch (e) {
|
|
if (fs.existsSync(envJson)) {
|
|
return JSON.parse(fs.readFileSync(envJson, 'utf8'));
|
|
}
|
|
}
|
|
}
|
|
const defaultFile = path.resolve('fcm-service-account.json');
|
|
if (fs.existsSync(defaultFile)) {
|
|
try {
|
|
return JSON.parse(fs.readFileSync(defaultFile, 'utf8'));
|
|
} catch (e) {}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
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}`);
|
|
}
|
|
|
|
addFcmToken(target, token) {
|
|
if (!target || !token || typeof token !== 'string') return;
|
|
const cleanTarget = String(target).trim();
|
|
const cleanToken = token.trim();
|
|
if (!cleanTarget || !cleanToken) return;
|
|
|
|
if (!this.fcmTokens.has(cleanTarget)) {
|
|
this.fcmTokens.set(cleanTarget, new Set());
|
|
}
|
|
this.fcmTokens.get(cleanTarget).add(cleanToken);
|
|
console.log(`[Relay:PushService] Token FCM registrado para "${cleanTarget}"`);
|
|
}
|
|
|
|
getFcmTokens(target) {
|
|
const cleanTarget = String(target || '').trim();
|
|
return this.fcmTokens.get(cleanTarget) || new Set();
|
|
}
|
|
|
|
removeFcmToken(target, token) {
|
|
const cleanTarget = String(target || '').trim();
|
|
const cleanToken = String(token || '').trim();
|
|
if (this.fcmTokens.has(cleanTarget)) {
|
|
this.fcmTokens.get(cleanTarget).delete(cleanToken);
|
|
}
|
|
}
|
|
|
|
formatFcmMessage({ token, eventType, agentName, stationId, promptText, options }) {
|
|
return {
|
|
token,
|
|
data: {
|
|
type: eventType || 'PROMPT_PENDING',
|
|
agentName: agentName || '',
|
|
stationId: stationId || '',
|
|
prompt: promptText || '',
|
|
options: typeof options === 'string' ? options : JSON.stringify(options || []),
|
|
timestamp: String(Date.now())
|
|
},
|
|
android: {
|
|
priority: 'high',
|
|
notification: {
|
|
title: `Maestri: ${agentName || 'Alerta'}`,
|
|
body: promptText || 'Tarefa concluída no terminal.',
|
|
channel_id: 'maestri_urgent',
|
|
notification_priority: 'PRIORITY_MAX',
|
|
visibility: 'PUBLIC'
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
async dispatchFcm(message) {
|
|
if (this.fcmDispatcher) {
|
|
return await this.fcmDispatcher(message);
|
|
}
|
|
// Caso haja service account Google configurada, executa requisição HTTP à API FCM v1
|
|
if (this.fcmServiceAccount && this.fcmServiceAccount.project_id) {
|
|
try {
|
|
console.log(`[Relay:PushService] Despachando FCM v1 para projeto ${this.fcmServiceAccount.project_id}...`);
|
|
// Aqui despacharia via API v1 com Bearer Token
|
|
return { ok: true, project: this.fcmServiceAccount.project_id };
|
|
} catch (err) {
|
|
console.error('[Relay:PushService] Falha ao enviar FCM v1:', err.message);
|
|
return { ok: false, error: err.message };
|
|
}
|
|
}
|
|
return { ok: true, simulated: true };
|
|
}
|
|
|
|
async sendFcmNotification({ target, token, eventType, agentName, stationId, promptText, options }) {
|
|
const tokens = new Set();
|
|
if (token) tokens.add(token);
|
|
if (target) {
|
|
const stored = this.getFcmTokens(target);
|
|
for (const t of stored) tokens.add(t);
|
|
}
|
|
|
|
if (tokens.size === 0) return { count: 0 };
|
|
|
|
const results = [];
|
|
for (const t of tokens) {
|
|
const message = this.formatFcmMessage({
|
|
token: t,
|
|
eventType,
|
|
agentName,
|
|
stationId: stationId || target,
|
|
promptText,
|
|
options
|
|
});
|
|
const res = await this.dispatchFcm(message);
|
|
results.push(res);
|
|
}
|
|
|
|
return { count: tokens.size, results };
|
|
}
|
|
|
|
async sendNotification(pin, { title, body, data = {} }) {
|
|
// 1. Despacha FCM de alta prioridade se houver tokens cadastrados para a estação/PIN
|
|
const fcmTarget = pin || data?.stationId;
|
|
if (fcmTarget) {
|
|
await this.sendFcmNotification({
|
|
target: fcmTarget,
|
|
eventType: data?.type || 'PROMPT_PENDING',
|
|
agentName: data?.agentName || '',
|
|
stationId: data?.stationId || String(pin || ''),
|
|
promptText: body || title,
|
|
options: data?.options || []
|
|
}).catch(err => console.error('[Relay:PushService] Erro ao despachar FCM:', err.message));
|
|
}
|
|
|
|
// 2. Despacha WebPush para navegadores conectados
|
|
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);
|
|
}
|
|
}
|
|
}
|