WIP message-delivery-method-web-push
Main daploy / deploy (push) Successful in 1m22s

This commit is contained in:
2024-11-27 15:57:11 +02:00
parent 056247a414
commit 1c8019d41a
48 changed files with 464 additions and 128 deletions
@@ -0,0 +1,7 @@
import PouchDB from "pouchdb-core";
import PouchDBAdapterHttp from "pouchdb-adapter-http";
import PouchDBFindPlugin from 'pouchdb-find'
export default PouchDB
.plugin(PouchDBAdapterHttp)
.plugin(PouchDBFindPlugin);
@@ -0,0 +1,38 @@
import PouchDB from "./PouchDB";
import type {
MessageDocument,
QRCodeDocument,
ServerSettingsDocument,
} from "@hereconnect/types";
export interface ServiceDoc {
_id: string;
lastSeq: string | number;
}
if (!process.env.API_URL) {
throw new Error("Environment variable API_URL is not set");
}
export const messagesDbUrl = `${process.env.API_URL}/messages`;
export const serverSettingsDb = new PouchDB<ServerSettingsDocument>(
`${process.env.API_URL}/server_settings`,
{
skip_setup: true,
},
);
export const qrDb = new PouchDB<QRCodeDocument>(`${process.env.API_URL}/qr`, {
skip_setup: true,
});
export const { messagesDb, serviceDb } = (() => {
const messagesDB = new PouchDB(messagesDbUrl, {
skip_setup: true,
});
return {
messagesDb: messagesDB as PouchDB.Database<MessageDocument>,
serviceDb: messagesDB as PouchDB.Database<ServiceDoc>,
} as const;
})();
@@ -0,0 +1,38 @@
import webpush from "web-push";
import PouchDB from "./PouchDB.js";
if (!process.env.VAPID_SUBJECT) {
throw new Error("VAPID_SUBJECT env is empty!");
}
const vapidKeys = webpush.generateVAPIDKeys();
await new PouchDB(`${process.env.API_URL}/server_settings`, {
_id: "server_settings:message_delivery_method_web_push_vapid",
type: "server_settings",
name: "message_delivery_method_web_push_vapid",
value: {
subject: process.env.VAPID_SUBJECT,
keys: vapidKeys,
},
});
await new PouchDB(`${process.env.API_URL}/public_settings`, {
skip_setup: true,
}).put({
_id: "public_settings:message_delivery_method_web_push_vapid_public_key",
type: "public_settings",
name: "message_delivery_method_web_push_vapid_public_key",
value: vapidKeys.publicKey,
});
if (process.env.GCM_API_KEY) {
await new PouchDB(`${process.env.API_URL}/public_settings`, {
skip_setup: true,
}).put({
_id: "server_settings:message_delivery_method_web_push_gcm_api_key",
type: "server_settings",
name: "message_delivery_method_web_push_gcm_api_key",
value: process.env.GCM_API_KEY,
});
}
@@ -0,0 +1,81 @@
import webpush from "web-push";
import { CouchDBChangesStream } from "couchdb-changes-stream";
import { qrDb, messagesDbUrl } from "./dbs";
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) {
const { seq, doc } = change;
if (!doc) {
console.error("Change missing document:", change);
continue;
}
serviceSeqTracker.checkNextSeq(seq);
try {
if (doc.from === "guest") {
const qrDoc = await qrDb.get(`qr:${doc.qr_code_uri}`);
if (qrDoc.messageDeliveryMethod !== "webPush") {
console.log(`Skip !webPush`);
continue;
}
console.log("FROM GUEST");
console.log(qrDoc.user_uuid);
console.log(qrDoc.browser_uuid);
} else if (doc.from === "owner") {
console.log("FROM OWNER");
} else {
continue;
}
console.log(
`Processed change: ${JSON.stringify({ _id: change.id, ref: doc._rev, seq: change.seq })}`,
);
} catch (error) {
console.error(
`Failed processing: ${JSON.stringify(error)} change: ${JSON.stringify({ id: doc._id, rev: doc._rev, seq: seq })}`,
);
} finally {
await serviceSeqTracker.saveSeq(seq);
}
}
};
start().catch((error) => {
console.error("error", error);
process.exit(1);
});
@@ -0,0 +1,38 @@
import { serviceDb, type ServiceDoc } from "./dbs";
const SERVICE_DOC_ID = "_local/service:message-delivery-method-web-push";
export class ServiceSeqTracker {
private serviceDoc: ServiceDoc;
async getSince() {
this.serviceDoc = await serviceDb.get(SERVICE_DOC_ID).catch((error) => {
if (error.name === "not_found") {
return {
_id: SERVICE_DOC_ID,
lastSeq: "0",
};
}
throw error; // Re-throw other errors
});
this.serviceDoc.lastSeq = 0;
return this.serviceDoc.lastSeq;
}
checkNextSeq(seq: number | string) {
const next = parseInt(seq as string, 10);
const current = parseInt(this.serviceDoc.lastSeq as string, 10);
if (next < current) {
throw new Error(
`Sequence number is too old: ${seq} (${next} < ${current})`,
);
}
}
saveSeq(seq: number | string) {
this.serviceDoc.lastSeq = seq;
return serviceDb.put(this.serviceDoc);
}
}
@@ -0,0 +1,77 @@
import webpush from "web-push";
import { serverSettingsDb } from "./dbs";
import { ServerSettingsDocument } from "@hereconnect/types";
function isType<N extends ServerSettingsDocument["name"]>(
doc: ServerSettingsDocument,
name: N,
): doc is ServerSettingsDocument & { name: N } {
return doc.name === name;
}
export const setupVapidDetails = async () => {
const changes = serverSettingsDb.changes({
since: "now",
live: true,
include_docs: true,
doc_ids: [
"server_settings:message_delivery_method_web_push_vapid",
"public_settings:message_delivery_method_web_push_gcm_api_key",
],
});
const {
rows: [vapidDetailsRow, gcmApiRow],
} = await serverSettingsDb.allDocs({
keys: [
"server_settings:message_delivery_method_web_push_vapid",
"public_settings:message_delivery_method_web_push_gcm_api_key",
],
include_docs: true,
});
if (
!("doc" in vapidDetailsRow) ||
!isType(vapidDetailsRow.doc, "message_delivery_method_web_push_vapid")
) {
throw new Error(
`VAPID details ${"error" in vapidDetailsRow ? vapidDetailsRow.error : "not exists"}`,
);
}
if (
"doc" in gcmApiRow &&
isType(gcmApiRow.doc, "message_delivery_method_web_push_gcm_api_key")
) {
webpush.setGCMAPIKey(gcmApiRow.doc.value);
}
webpush.setVapidDetails(
vapidDetailsRow.doc.value.subject,
vapidDetailsRow.doc.value.keys.publicKey,
vapidDetailsRow.doc.value.keys.privateKey,
);
changes.on("change", (change) => {
if (!("doc" in change)) {
return;
}
if (isType(change.doc, "message_delivery_method_web_push_vapid")) {
console.log("update vapid details");
webpush.setVapidDetails(
change.doc.value.subject,
change.doc.value.keys.publicKey,
change.doc.value.keys.privateKey,
);
return;
}
if (
"doc" in change &&
isType(change.doc, "message_delivery_method_web_push_gcm_api_key")
) {
console.log("update gcm api key");
webpush.setGCMAPIKey(change.doc.value);
}
});
};
@@ -0,0 +1,65 @@
import webpush from "web-push";
import PouchDB from "./PouchDB.js";
if (!process.env.API_URL) {
throw new Error(`env API_URL is not set`);
}
const settings = await new PouchDB(`${process.env.API_URL}/server_settings`, {
skip_setup: true,
}).get("server_settings:message_delivery_method_web_push:vapid");
webpush.setVapidDetails(
settings.vapid.subject,
settings.vapid.keys.publicKey,
settings.vapid.keys.privateKey,
);
const notification = {
type: "cancelNotification",
notification: {
title: "test",
options: {
icon: "/images/qr-code-logo-200x200.jpg",
body: "Test push message from DevTools.",
tag: "2105ef6f-3ca6-4f99-b258-0ca23f014309",
// requireInteraction: true,
// silent: false,
// vibrate: [200, 100, 200, 100, 200, 100, 200],
data: {
url: "/chat/6ilhxu/13trvu",
payload: { tag: "2105ef6f-3ca6-4f99-b258-0ca23f014309" },
},
},
},
};
const { rows } = await new PouchDB(
`${process.env.API_URL}/web_push_subscriptions`,
{ skip_setup: true },
).allDocs(
process.env.WEB_PUSH_SUBSCRIPTION_ID
? {
key: process.env.WEB_PUSH_SUBSCRIPTION_ID,
include_docs: true,
}
: {
startkey: "web_push_subscription:",
endkey: "web_push_subscription:\uFFFF",
include_docs: true,
},
);
await Promise.allSettled(
rows.map(async ({ doc }) => {
await webpush.sendNotification(
doc.subscription,
JSON.stringify(notification),
);
console.log("sent ", doc._id);
}),
);
// issues:
// 1. NO SOUND
// 2. SAFARI NO OPEN PAGE
@@ -0,0 +1,97 @@
import webpush from "web-push";
import PouchDB from "./PouchDB.js";
if (!process.env.API_URL) {
throw new Error(`env API_URL is not set`);
}
const {
rows: [
{
doc: { value: vapidDetails },
},
{ doc: gcmApiSettingsDoc },
],
} = await new PouchDB(`${process.env.API_URL}/server_settings`, {
skip_setup: true,
}).allDocs({
keys: [
"server_settings:message_delivery_method_web_push_vapid",
"public_settings:message_delivery_method_web_push_gcm_api_key",
],
include_docs: true,
});
webpush.setVapidDetails(
vapidDetails.subject,
vapidDetails.keys.publicKey,
vapidDetails.keys.privateKey,
);
if (gcmApiSettingsDoc) {
console.log(gcmApiSettingsDoc.value);
webpush.setGCMAPIKey(gcmApiSettingsDoc.value);
}
// optionally provide an identifier that the push service uses to coalesce notifications
const topic = "chat-6ilhxu-13trvu";
const notification = {
type: "notification",
notification: {
title: "test",
options: {
icon: "/images/qr-code-logo-200x200.jpg",
body: "Test push message from server.",
tag: "01936062-d10f-7f2f-8ae3-dd7f9fbc5c7f",
requireInteraction: true,
// silent: false,
// vibrate: [200, 100, 200, 100, 200, 100, 200],
// actions: [
// {
// action: "open_url",
// title: "Открыть",
// },
// ],
data: {
url: "/chat/6ilhxu/13trvu",
payload: { tag: "01936062-d10f-7f2f-8ae3-dd7f9fbc5c7f" },
},
},
},
};
const { rows } = await new PouchDB(
`${process.env.API_URL}/web_push_subscriptions`,
{ skip_setup: true },
).allDocs(
process.env.WEB_PUSH_SUBSCRIPTION_ID
? {
key: process.env.WEB_PUSH_SUBSCRIPTION_ID,
include_docs: true,
}
: {
startkey: "web_push_subscription:",
endkey: "web_push_subscription:\uFFFF",
include_docs: true,
},
);
const result = await Promise.allSettled(
rows.map(async ({ doc }) => {
await webpush.sendNotification(
doc.subscription,
JSON.stringify(notification),
{
urgency: "high",
topic,
},
);
console.log("sent ", doc._id);
}),
);
console.log(result);
// issues:
// 1. NO SOUND
// 2. SAFARI NO OPEN PAGE