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

248 lines
7.9 KiB
TypeScript
Raw Normal View History

2024-11-27 15:57:11 +02:00
import webpush from "web-push";
import { CouchDBChangesStream } from "@hereconnect/couchdb-changes-stream";
2024-12-02 08:50:25 +02:00
import {
qrDb,
messagesDbUrl,
webPushSubscriptionsDb,
userChatSettingsDb,
} from "./dbs";
2024-11-27 15:57:11 +02:00
import { setupVapidDetails } from "./setupVapidDetails";
import type { MessageDocument } from "@hereconnect/types";
import { ServiceSeqTracker } from "./serviceSeqTracker";
import { startHealthServer } from "./health-server";
2024-11-27 15:57:11 +02:00
const abortController = new AbortController();
startHealthServer(abortController);
2024-11-27 15:57:11 +02:00
function limitStringLengthWithEllipsis(str: string, maxLength: number): string {
return str.length > maxLength ? str.substring(0, maxLength) + "…" : str;
}
2024-11-27 15:57:11 +02:00
const start = async () => {
await setupVapidDetails();
const serviceSeqTracker = await ServiceSeqTracker.Init(
"_local/service:message-delivery-method-web-push",
);
2024-11-27 15:57:11 +02:00
const changesStream = new CouchDBChangesStream<MessageDocument>(
messagesDbUrl,
{
abortController,
since: serviceSeqTracker.lastSeq,
2024-11-27 15:57:11 +02:00
feed: "continuous",
include_docs: true,
heartbeat: 1000,
filter: "_selector",
selector: {
type: "message",
},
},
);
// Gracefully handle SIGINT
process.on("SIGINT", async () => {
changesStream?.stop();
2024-11-27 15:57:11 +02:00
process.stdout.write("\n");
process.exit(2);
});
console.info("Service started from sequence", serviceSeqTracker.lastSeq);
2024-11-27 15:57:11 +02:00
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") {
2024-12-02 10:01:23 +02:00
console.log("FROM GUEST");
2024-11-29 00:05:43 +02:00
// 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-12-02 10:01:23 +02:00
const [{ rows: pushSubscriptionRows }, { rows: userChatSettingsRows }] =
await Promise.all([
webPushSubscriptionsDb.allDocs({
startkey: `web_push_subscription:${qrDoc.user_uuid}:`,
endkey: `web_push_subscription:${qrDoc.user_uuid}:\uffff`,
include_docs: true,
}),
userChatSettingsDb.allDocs({
startkey: `user_chat_settings:${msgDoc.qr_code_uri}:${msgDoc.chat}:owner:`,
endkey: `user_chat_settings:${msgDoc.qr_code_uri}:${msgDoc.chat}:owner:\uffff`,
include_docs: true,
}),
]);
if (
userChatSettingsRows.some(
(row) => row.doc!.is_push_notification_enabled === false,
)
) {
console.log("push notifications is disabled");
continue;
}
2024-11-29 00:05:43 +02:00
2024-12-02 10:01:23 +02:00
if (pushSubscriptionRows.length === 0) {
2024-11-29 00:05:43 +02:00
console.log("NO SUBSCRIPTIONS");
} else {
2024-12-02 10:01:23 +02:00
console.log(`sending to ${pushSubscriptionRows.length} devices`);
2024-11-29 00:05:43 +02:00
}
2024-12-02 10:01:23 +02:00
for (const row of pushSubscriptionRows) {
try {
const subscription = row.doc!.subscription;
const topic = `chat-${msgDoc.qr_code_uri}-${msgDoc.chat}`;
const timestamp = new Date(msgDoc.created_at).getTime();
const tag = `${topic}-${(timestamp - new Date(qrDoc.created_at).getTime()).toString(36)}`;
const title = limitStringLengthWithEllipsis(
`${qrDoc.name}: новое сообщение`,
53,
);
const body = limitStringLengthWithEllipsis(msgDoc.body, 470);
const options: NotificationOptions & { timestamp: number } = {
icon: "/images/qr-code-logo-200x200.jpg",
body,
tag,
requireInteraction: true,
timestamp,
data: {
2024-12-02 11:02:58 +02:00
url: `/manage/${msgDoc.qr_code_uri}/chat/${msgDoc.chat}#message-${msgDoc.created_at}`,
payload: { tag },
2024-11-29 00:05:43 +02:00
},
} as const;
await webpush.sendNotification(
subscription,
JSON.stringify({
type: "notification",
notification: {
title,
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");
2024-12-02 08:50:25 +02:00
const qrDoc = await qrDb.get(`qr_code:${msgDoc.qr_code_uri}`);
const { rows: userChatSettingsRows } = await userChatSettingsDb.allDocs(
{
startkey: `user_chat_settings:${msgDoc.qr_code_uri}:${msgDoc.chat}:guest:`,
endkey: `user_chat_settings:${msgDoc.qr_code_uri}:${msgDoc.chat}:guest:\uffff`,
include_docs: true,
},
);
for (const { doc: userChatSettingDoc } of userChatSettingsRows) {
if (!userChatSettingDoc) {
2024-12-02 10:01:23 +02:00
console.log("push notification has not been configured");
2024-12-02 08:50:25 +02:00
continue;
}
if (!userChatSettingDoc.is_push_notification_enabled) {
2024-12-02 10:01:23 +02:00
console.log("push notification is disabled");
2024-12-02 08:50:25 +02:00
continue;
}
const { rows: subscriptionRows } =
await webPushSubscriptionsDb.allDocs({
startkey: `web_push_subscription:${userChatSettingDoc.user_uuid}:`,
endkey: `web_push_subscription:${userChatSettingDoc.user_uuid}:\uffff`,
include_docs: true,
});
if (subscriptionRows.length === 0) {
2024-12-02 10:01:23 +02:00
console.log("no subscriptions");
2024-12-02 08:50:25 +02:00
} else {
console.log(`sending to ${subscriptionRows.length} devices`);
}
2024-12-02 10:01:23 +02:00
for (const row of subscriptionRows) {
try {
const subscription = row.doc!.subscription;
const topic = `chat-${msgDoc.qr_code_uri}-${msgDoc.chat}`;
const timestamp = new Date(msgDoc.created_at).getTime();
const tag = `${topic}-${(timestamp - new Date(qrDoc.created_at).getTime()).toString(36)}`;
const title = limitStringLengthWithEllipsis(
`Новое сообщение`,
53,
);
const body = limitStringLengthWithEllipsis(msgDoc.body, 470);
const options: NotificationOptions & { timestamp: number } = {
icon: "/images/qr-code-logo-200x200.jpg",
body,
tag,
requireInteraction: true,
timestamp,
data: {
2024-12-02 11:02:58 +02:00
url: `/chat/${msgDoc.qr_code_uri}/${msgDoc.chat}#message-${msgDoc.created_at}`,
2024-12-02 10:01:23 +02:00
payload: { tag },
},
} as const;
await webpush.sendNotification(
subscription,
JSON.stringify({
type: "notification",
notification: {
title,
options,
},
}),
{
urgency: "high",
topic,
},
);
} catch (error) {
console.error(
`Error sending notification to ${row.id} - ${JSON.stringify(error)}`,
);
}
}
2024-12-02 08:50:25 +02:00
}
2024-11-27 15:57:11 +02:00
} 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);
});