Files
hereconnect/services/message-delivery-method-web-push/src/server.ts
T

129 lines
3.6 KiB
TypeScript
Raw Normal View History

2024-11-27 15:57:11 +02:00
import webpush from "web-push";
import { CouchDBChangesStream } from "couchdb-changes-stream";
2024-11-29 00:05:43 +02:00
import { qrDb, messagesDbUrl, webPushSubscriptionsDb } from "./dbs";
2024-11-27 15:57:11 +02:00
import { setupVapidDetails } from "./setupVapidDetails";
import type { MessageDocument } from "@hereconnect/types";
import { ServiceSeqTracker } from "./serviceSeqTracker";
const serviceSeqTracker = new ServiceSeqTracker();
const start = async () => {
await setupVapidDetails();
const since = await serviceSeqTracker.getSince();
const changesStream = new CouchDBChangesStream<MessageDocument>(
messagesDbUrl,
{
since,
feed: "continuous",
include_docs: true,
heartbeat: 1000,
filter: "_selector",
selector: {
type: "message",
},
},
);
// Gracefully handle SIGINT
process.on("SIGINT", async () => {
changesStream.stop();
process.stdout.write("\n");
process.exit(2);
});
console.info("Service started from sequence", since);
for await (const change of changesStream) {
2024-11-29 00:05:43 +02:00
const { seq, doc: msgDoc } = change;
2024-11-27 15:57:11 +02:00
2024-11-29 00:05:43 +02:00
if (!msgDoc) {
2024-11-27 15:57:11 +02:00
console.error("Change missing document:", change);
continue;
}
serviceSeqTracker.checkNextSeq(seq);
try {
2024-11-29 00:05:43 +02:00
if (msgDoc.from === "guest") {
// send message to owner
const qrDoc = await qrDb.get(`qr_code:${msgDoc.qr_code_uri}`);
2024-11-27 15:57:11 +02:00
if (qrDoc.messageDeliveryMethod !== "webPush") {
console.log(`Skip !webPush`);
continue;
}
2024-11-29 00:05:43 +02:00
const { rows } = await webPushSubscriptionsDb.allDocs({
startkey: `web_push_subscription:${qrDoc.user_uuid}:`,
endkey: `web_push_subscription:${qrDoc.user_uuid}:\uffff`,
include_docs: true,
});
if (rows.length === 0) {
console.log("NO SUBSCRIPTIONS");
} else {
console.log(`sending to ${rows.length} devices`);
2024-11-29 00:05:43 +02:00
}
for (const row of rows) {
try {
const subscription = row.doc.subscription;
const topic = `chat-${msgDoc.qr_code_uri}-${msgDoc.chat}`;
const tag = `${topic}-${(new Date(msgDoc.created_at).getTime() - new Date(qrDoc.created_at).getTime()).toString(36)}`;
const options: NotificationOptions = {
icon: "/images/qr-code-logo-200x200.jpg",
body: msgDoc.body,
tag,
requireInteraction: true,
data: {
url: `/manage/${msgDoc.qr_code_uri}/chat/${msgDoc.chat}`,
payload: { tag },
2024-11-29 00:05:43 +02:00
},
} as const;
await webpush.sendNotification(
subscription,
JSON.stringify({
type: "notification",
notification: {
title: qrDoc.name,
options,
},
}),
{
urgency: "high",
topic,
},
);
} catch (error) {
console.error(
`Error sending notification to ${row.id} - ${JSON.stringify(error)}`,
);
}
2024-11-29 00:05:43 +02:00
}
} else if (msgDoc.from === "owner") {
2024-11-27 15:57:11 +02:00
console.log("FROM OWNER");
} else {
continue;
}
console.log(
2024-11-29 00:05:43 +02:00
`Processed change: ${JSON.stringify({ _id: change.id, ref: msgDoc._rev, seq: change.seq })}`,
2024-11-27 15:57:11 +02:00
);
} catch (error) {
console.error(
2024-11-29 00:05:43 +02:00
`Failed processing: ${JSON.stringify(error)} change: ${JSON.stringify({ id: msgDoc._id, rev: msgDoc._rev, seq: seq })}`,
2024-11-27 15:57:11 +02:00
);
} finally {
await serviceSeqTracker.saveSeq(seq);
}
}
};
start().catch((error) => {
console.error("error", error);
process.exit(1);
});